[scala-2.10] 53/166: Imported Upstream version 2.8.1.dfsg

Emmanuel Bourg ebourg-guest at moszumanska.debian.org
Tue Nov 15 12:43:28 UTC 2016


This is an automated email from the git hooks/post-receive script.

ebourg-guest pushed a commit to branch master
in repository scala-2.10.

commit 0595a1a2ca9e52669e666e7ec8f96a991341f96f
Author: Mehdi Dogguy <mehdi at debian.org>
Date:   Sat Mar 5 19:10:43 2011 +0100

    Imported Upstream version 2.8.1.dfsg
---
 .classpath                                         |    4 +-
 META-INF/MANIFEST.MF                               |   33 +-
 OMakefile                                          |  187 -
 OMakeroot                                          |    3 -
 README                                             |  126 +-
 build.examples.xml                                 |    1 -
 build.number                                       |    4 +-
 build.xml                                          | 1279 +++--
 docs/LICENSE                                       |    2 +-
 docs/README                                        |    7 +-
 docs/TODO                                          |    1 -
 .../FileBrowser/AndroidManifest.xml                |   11 -
 docs/android-examples/FileBrowser/build.xml        |  222 -
 .../FileBrowser/res/drawable/audio.png             |  Bin 964 -> 0 bytes
 .../FileBrowser/res/drawable/folder.png            |  Bin 1015 -> 0 bytes
 .../FileBrowser/res/drawable/goroot.png            |  Bin 1044 -> 0 bytes
 .../FileBrowser/res/drawable/icon.png              |  Bin 667 -> 0 bytes
 .../FileBrowser/res/drawable/image.png             |  Bin 1031 -> 0 bytes
 .../FileBrowser/res/drawable/packed.png            |  Bin 1036 -> 0 bytes
 .../FileBrowser/res/drawable/text.png              |  Bin 971 -> 0 bytes
 .../FileBrowser/res/drawable/uponelevel.png        |  Bin 1050 -> 0 bytes
 .../FileBrowser/res/drawable/webtext.png           |  Bin 1080 -> 0 bytes
 .../FileBrowser/res/layout/file_row.xml            |    6 -
 .../FileBrowser/res/layout/main.xml                |   12 -
 .../FileBrowser/res/values/fileendings.xml         |   28 -
 .../FileBrowser/res/values/strings.xml             |   10 -
 .../android/filebrowser/AndroidFileBrowser.scala   |  196 -
 .../filebrowser/iconifiedlist/IconifiedText.scala  |   54 -
 .../iconifiedlist/IconifiedTextListAdapter.scala   |   69 -
 .../iconifiedlist/IconifiedTextView.scala          |   59 -
 .../LunarLander/AndroidManifest.xml                |   11 -
 docs/android-examples/LunarLander/build.xml        |  222 -
 .../LunarLander/res/drawable-land/earthrise.png    |  Bin 39333 -> 0 bytes
 .../LunarLander/res/drawable-port/earthrise.png    |  Bin 37054 -> 0 bytes
 .../LunarLander/res/drawable/app_lunar_lander.png  |  Bin 10336 -> 0 bytes
 .../LunarLander/res/drawable/lander_crashed.png    |  Bin 12259 -> 0 bytes
 .../LunarLander/res/drawable/lander_firing.png     |  Bin 12540 -> 0 bytes
 .../LunarLander/res/drawable/lander_plain.png      |  Bin 11565 -> 0 bytes
 .../LunarLander/res/layout/lunar_layout.xml        |   43 -
 .../LunarLander/res/layout/main.xml                |   13 -
 .../LunarLander/res/values/strings.xml             |   41 -
 .../google/android/lunarlander/LunarLander.scala   |   88 -
 .../com/google/android/lunarlander/LunarView.scala |  647 ---
 docs/android-examples/NotePad/AndroidManifest.xml  |   91 -
 docs/android-examples/NotePad/build.xml            |  222 -
 .../NotePad/res/drawable/app_notes.png             |  Bin 1388 -> 0 bytes
 .../NotePad/res/layout/note_editor.xml             |   25 -
 .../NotePad/res/layout/title_editor.xml            |   42 -
 .../NotePad/res/values-zz-rZZ/strings.xml          |   39 -
 .../android-examples/NotePad/res/values/colors.xml |   21 -
 .../NotePad/res/values/strings.xml                 |   39 -
 docs/android-examples/NotePad/sample_note.png      |  Bin 3973 -> 0 bytes
 docs/android-examples/NotePad/sample_notepad.png   |  Bin 6743 -> 0 bytes
 .../com/google/android/notepad/NoteEditor.scala    |  328 --
 .../google/android/notepad/NotePadProvider.scala   |  201 -
 .../src/com/google/android/notepad/NotesList.scala |  203 -
 .../com/google/android/notepad/TitleEditor.scala   |  115 -
 .../NotePad/src/com/google/provider/NotePad.scala  |   69 -
 .../PhoneDialer/AndroidManifest.xml                |   14 -
 docs/android-examples/PhoneDialer/build.xml        |  222 -
 .../PhoneDialer/res/layout/main.xml                |   17 -
 .../PhoneDialer/res/values/strings.xml             |    4 -
 .../google/android/phonedialer/PhoneDialer.scala   |   40 -
 docs/android-examples/Snake/AndroidManifest.xml    |   28 -
 docs/android-examples/Snake/build.xml              |  222 -
 .../Snake/res/drawable/greenstar.png               |  Bin 7020 -> 0 bytes
 .../Snake/res/drawable/redstar.png                 |  Bin 6680 -> 0 bytes
 .../Snake/res/drawable/yellowstar.png              |  Bin 6653 -> 0 bytes
 .../Snake/res/layout/snake_layout.xml              |   44 -
 docs/android-examples/Snake/res/values/attrs.xml   |   23 -
 docs/android-examples/Snake/res/values/strings.xml |   25 -
 .../Snake/src/com/google/android/snake/Snake.scala |   80 -
 .../src/com/google/android/snake/SnakeView.scala   |  464 --
 .../src/com/google/android/snake/TileView.scala    |  137 -
 docs/development/jvm.txt                           |    4 +-
 docs/development/scala.dbc/SQLTypes.dot            |    2 +-
 docs/development/scala.tools.nsc/nscNodes.dot      |    2 +-
 docs/examples/actors/boundedbuffer.scala           |    2 +-
 docs/examples/actors/message.scala                 |    5 +-
 docs/examples/fors.scala                           |    2 +-
 docs/examples/jolib/Ref.scala                      |    1 -
 docs/examples/jolib/parallelOr.scala               |    1 -
 docs/examples/monads/callccInterpreter.scala       |    4 +-
 docs/examples/monads/directInterpreter.scala       |    4 +-
 docs/examples/monads/errorInterpreter.scala        |    4 +-
 docs/examples/monads/simpleInterpreter.scala       |    4 +-
 docs/examples/monads/stateInterpreter.scala        |    6 +-
 docs/examples/parsing/ArithmeticParser.scala       |    4 +-
 docs/examples/parsing/lambda/TestParser.scala      |    2 +-
 docs/examples/patterns.scala                       |    2 +-
 docs/examples/pilib/elasticBuffer.scala            |    2 +-
 docs/examples/pilib/mobilePhoneProtocol.scala      |    2 +-
 docs/examples/pilib/piNat.scala                    |   27 +-
 docs/examples/pilib/scheduler.scala                |   42 +-
 docs/examples/pilib/semaphore.scala                |   34 +-
 docs/examples/pilib/twoPlaceBuffer.scala           |   32 +-
 docs/examples/plugintemplate/lib/scalatest.jar     |  Bin 654468 -> 1827900 bytes
 docs/examples/plugintemplate/plugin.properties     |    2 +-
 .../src/plugintemplate/PluginProperties.scala      |    2 +-
 .../src/plugintemplate/TemplateComponent.scala     |    2 +-
 .../TemplateInfoTransformComponent.scala           |    2 +-
 .../src/plugintemplate/TemplatePlugin.scala        |    2 +-
 .../TemplateTransformComponent.scala               |    2 +-
 .../plugintemplate/TemplateTraverseComponent.scala |    2 +-
 .../src/plugintemplate/standalone/Main.scala       |    7 +-
 .../plugintemplate/standalone/PluginRunner.scala   |   22 +-
 docs/examples/tcpoly/collection/HOSeq.scala        |    8 +-
 docs/examples/tcpoly/monads/Monads.scala           |    2 +-
 docs/examples/xml/phonebook/phonebook3.scala       |    4 +-
 docs/licenses/apache_android.txt                   |   16 +
 docs/licenses/apache_ant.txt                       |   16 +
 docs/licenses/bsd_jline.txt                        |   34 +
 docs/licenses/mit_jquery.txt                       |   13 +
 docs/licenses/mit_sizzle.txt                       |   13 +
 docs/licenses/mit_tools.tooltip.txt                |   13 +
 lib/ScalaCheck.jar                                 |  Bin 737362 -> 0 bytes
 lib/ScalaCheckHelper.jar                           |  Bin 6886 -> 0 bytes
 lib/ant/ant-contrib.jar                            |  Bin 224277 -> 0 bytes
 lib/ant/ant-dotnet-1.0.jar                         |  Bin 57795 -> 0 bytes
 lib/ant/maven-ant-tasks-2.0.9.jar                  |  Bin 1018394 -> 0 bytes
 lib/ant/vizant.jar                                 |  Bin 15910 -> 0 bytes
 lib/cldcapi10.jar                                  |  Bin 119381 -> 0 bytes
 lib/fjbg.jar                                       |  Bin 104948 -> 101616 bytes
 lib/forkjoin.jar                                   |  Bin 0 -> 47215 bytes
 lib/jline.jar                                      |  Bin 61187 -> 87543 bytes
 lib/midpapi10.jar                                  |  Bin 364901 -> 0 bytes
 lib/msil.jar                                       |  Bin 235287 -> 273092 bytes
 lib/scala-compiler.jar                             |  Bin 5962763 -> 8706407 bytes
 lib/scala-library-src.jar                          |  Bin 640207 -> 1103550 bytes
 lib/scala-library.jar                              |  Bin 3708736 -> 5789202 bytes
 src/actors/scala/actors/AbstractActor.scala        |   20 +-
 src/actors/scala/actors/Actor.scala                |  895 ++-
 src/actors/scala/actors/ActorCanReply.scala        |   66 +
 src/actors/scala/actors/ActorGC.scala              |   29 -
 src/actors/scala/actors/ActorProxy.scala           |    8 +-
 src/actors/scala/actors/ActorTask.scala            |   54 +
 src/actors/scala/actors/CanReply.scala             |   66 +
 src/actors/scala/actors/Channel.scala              |  159 +-
 src/actors/scala/actors/Combinators.scala          |   46 +
 src/actors/scala/actors/DaemonActor.scala          |   22 +
 src/actors/scala/actors/Debug.scala                |   40 +-
 src/actors/scala/actors/FJTask.java                |  531 --
 src/actors/scala/actors/FJTaskRunner.java          |  996 ----
 src/actors/scala/actors/FJTaskRunnerGroup.java     |  714 ---
 src/actors/scala/actors/FJTaskScheduler2.scala     |  201 -
 src/actors/scala/actors/Future.scala               |  216 +-
 src/actors/scala/actors/IFJTaskRunnerGroup.java    |   18 -
 src/actors/scala/actors/IScheduler.scala           |   82 +
 src/actors/scala/actors/InputChannel.scala         |   20 +-
 src/actors/scala/actors/MessageQueue.scala         |  314 +-
 src/actors/scala/actors/OutputChannel.scala        |   22 +-
 src/actors/scala/actors/ReactChannel.scala         |  125 +
 src/actors/scala/actors/Reaction.scala             |   92 +-
 src/actors/scala/actors/Reactor.scala              |  298 +
 src/actors/scala/actors/ReactorCanReply.scala      |   90 +
 src/actors/scala/actors/ReactorTask.scala          |   77 +
 src/actors/scala/actors/ReplyReactor.scala         |  170 +
 src/actors/scala/actors/ReplyReactorTask.scala     |   36 +
 src/actors/scala/actors/Scheduler.scala            |  320 +-
 src/actors/scala/actors/SchedulerAdapter.scala     |   46 +-
 src/actors/scala/actors/TickedScheduler.scala      |  173 -
 src/actors/scala/actors/UncaughtException.scala    |   33 +
 src/actors/scala/actors/package.scala              |   32 +
 .../scala/actors/remote/FreshNameCreator.scala     |    8 +-
 .../scala/actors/remote/JavaSerializer.scala       |   21 +-
 src/actors/scala/actors/remote/NetKernel.scala     |   22 +-
 src/actors/scala/actors/remote/Proxy.scala         |   77 +-
 src/actors/scala/actors/remote/RemoteActor.scala   |   55 +-
 src/actors/scala/actors/remote/Serializer.scala    |   14 +-
 src/actors/scala/actors/remote/Service.scala       |    8 +-
 src/actors/scala/actors/remote/TcpService.scala    |   49 +-
 src/actors/scala/actors/scheduler/ActorGC.scala    |  101 +
 .../scala/actors/scheduler/DaemonScheduler.scala   |   33 +
 .../actors/scheduler/DelegatingScheduler.scala     |   74 +
 .../actors/scheduler/DrainableForkJoinPool.scala   |   12 +
 .../scala/actors/scheduler/ExecutorScheduler.scala |   93 +
 .../scala/actors/scheduler/ForkJoinScheduler.scala |  178 +
 .../scala/actors/scheduler/QuitControl.scala       |   19 +
 .../scheduler/ResizableThreadPoolScheduler.scala   |  199 +
 .../actors/scheduler/SingleThreadedScheduler.scala |   68 +
 .../actors/scheduler/TerminationMonitor.scala      |   24 +-
 .../actors/scheduler/TerminationService.scala      |   68 +
 .../scala/actors/scheduler/ThreadPoolConfig.scala  |   53 +
 .../actors/threadpool/AbstractExecutorService.java |   10 +-
 .../scala/actors/threadpool/BlockingQueue.java     |   24 +-
 src/actors/scala/actors/threadpool/Executors.java  |    6 +-
 .../actors/threadpool/LinkedBlockingQueue.java     |  716 ++-
 .../actors/threadpool/ThreadPoolExecutor.java      |    2 +-
 .../actors/threadpool/helpers/FIFOWaitQueue.java   |    2 +-
 .../scala/actors/threadpool/helpers/Utils.java     |   12 +-
 .../scala/actors/threadpool/locks/CondVar.java     |    1 +
 .../scala/actors/threadpool/locks/FIFOCondVar.java |    1 +
 .../threadpool/locks/ReentrantReadWriteLock.java   |    8 +-
 src/android-library/scala/ScalaObject.scala        |   14 +-
 src/attic/README                                   |    2 +
 src/attic/scala/tools/nsc/models/Models.scala      |  419 ++
 .../scala/tools/nsc/models/SemanticTokens.scala    |  713 +++
 src/attic/scala/tools/nsc/models/Signatures.scala  |   85 +
 .../scala/tools/nsc/symtab/SymbolWalker.scala      |  253 +
 src/build/four.xml                                 |  470 --
 src/build/genprod.scala                            |  771 ++-
 src/build/maven/continuations-plugin-pom.xml       |   51 +
 src/build/maven/maven-deploy.xml                   |   61 +-
 src/build/maven/scala-compiler-pom.xml             |   10 +-
 src/build/maven/scala-dbc-pom.xml                  |    4 +-
 src/build/maven/scala-dotnet-library-pom.xml       |   46 +
 src/build/maven/scala-library-pom.xml              |    4 +-
 src/build/maven/scala-partest-pom.xml              |   51 +
 src/build/maven/scala-swing-pom.xml                |    4 +-
 src/build/maven/scalap-pom.xml                     |   51 +
 src/build/msil.properties.SAMPLE                   |    4 -
 src/build/msil.xml                                 |  300 -
 src/build/old_sabbus.xml                           | 2012 -------
 src/build/pack.xml                                 |  105 +-
 src/cldc-library/scala/Array.scala                 |  430 --
 src/cldc-library/scala/Console.scala               |   96 -
 src/cldc-library/scala/List.scala                  | 1244 ----
 src/cldc-library/scala/Math.scala                  |   56 -
 src/cldc-library/scala/Predef.scala                |  285 -
 src/cldc-library/scala/Random.scala                |   41 -
 src/cldc-library/scala/StringBuilder.scala         |  862 ---
 src/cldc-library/scala/Symbol.scala                |   48 -
 .../collection/mutable/CloneableCollection.scala   |   19 -
 src/cldc-library/scala/compat/Platform.scala       |   56 -
 src/cldc-library/scala/runtime/BooleanRef.java     |   19 -
 src/cldc-library/scala/runtime/BoxedAnyArray.scala |  234 -
 .../scala/runtime/BoxedObjectArray.scala           |   73 -
 src/cldc-library/scala/runtime/BoxedUnit.java      |   33 -
 src/cldc-library/scala/runtime/BoxesRunTime.java   |  361 --
 src/cldc-library/scala/runtime/BoxesUtility.java   |  147 -
 src/cldc-library/scala/runtime/ByteRef.java        |   19 -
 src/cldc-library/scala/runtime/CharRef.java        |   19 -
 src/cldc-library/scala/runtime/Comparator.java     |   53 -
 src/cldc-library/scala/runtime/IntRef.java         |   19 -
 src/cldc-library/scala/runtime/LongRef.java        |   19 -
 src/cldc-library/scala/runtime/ObjectRef.java      |   19 -
 src/cldc-library/scala/runtime/RichChar.scala      |   71 -
 src/cldc-library/scala/runtime/RichException.scala |   29 -
 src/cldc-library/scala/runtime/RichLong.scala      |   30 -
 src/cldc-library/scala/runtime/RichString.scala    |  219 -
 src/cldc-library/scala/runtime/ScalaRunTime.scala  |  142 -
 src/cldc-library/scala/runtime/ShortRef.java       |   19 -
 src/cldc-library/scala/runtime/SquareRoot.scala    |  151 -
 src/cldc-library/scala/runtime/StringAdd.scala     |   22 -
 src/compiler/scala/tools/ant/FastScalac.scala      |   41 +-
 src/compiler/scala/tools/ant/Pack200Task.scala     |  184 +
 src/compiler/scala/tools/ant/Same.scala            |    5 +-
 src/compiler/scala/tools/ant/ScalaBazaar.scala     |   31 +-
 src/compiler/scala/tools/ant/ScalaTool.scala       |  119 +-
 src/compiler/scala/tools/ant/Scalac.scala          |  349 +-
 src/compiler/scala/tools/ant/ScalacShared.scala    |   25 +
 src/compiler/scala/tools/ant/Scaladoc.scala        |  171 +-
 src/compiler/scala/tools/ant/antlib.xml            |    2 +
 src/compiler/scala/tools/ant/sabbus/Break.scala    |    7 +-
 .../tools/ant/sabbus/CompilationFailure.scala      |    3 +-
 src/compiler/scala/tools/ant/sabbus/Compiler.scala |   31 +-
 .../scala/tools/ant/sabbus/Compilers.scala         |   10 +-
 .../scala/tools/ant/sabbus/ForeignCompiler.scala   |    9 +-
 src/compiler/scala/tools/ant/sabbus/Make.scala     |    9 +-
 .../scala/tools/ant/sabbus/ScalacFork.scala        |  137 +-
 src/compiler/scala/tools/ant/sabbus/Settings.scala |   12 +-
 src/compiler/scala/tools/ant/sabbus/TaskArgs.scala |   63 +-
 src/compiler/scala/tools/ant/sabbus/Use.scala      |   13 +-
 src/compiler/scala/tools/ant/sabbus/antlib.xml     |    2 +-
 .../scala/tools/ant/templates/tool-unix.tmpl       |   29 +-
 .../scala/tools/ant/templates/tool-windows.tmpl    |    4 +-
 src/compiler/scala/tools/cmd/CommandLine.scala     |   91 +
 src/compiler/scala/tools/cmd/Demo.scala            |   84 +
 src/compiler/scala/tools/cmd/FromString.scala      |   72 +
 src/compiler/scala/tools/cmd/Instance.scala        |   24 +
 src/compiler/scala/tools/cmd/Interpolation.scala   |   57 +
 src/compiler/scala/tools/cmd/Meta.scala            |   67 +
 src/compiler/scala/tools/cmd/Opt.scala             |   91 +
 src/compiler/scala/tools/cmd/Parser.scala          |   52 +
 src/compiler/scala/tools/cmd/Property.scala        |   71 +
 src/compiler/scala/tools/cmd/Reference.scala       |   99 +
 src/compiler/scala/tools/cmd/Spec.scala            |   52 +
 src/compiler/scala/tools/cmd/package.scala         |   28 +
 src/compiler/scala/tools/cmd/program/Scmp.scala    |   59 +
 src/compiler/scala/tools/cmd/program/Simple.scala  |   81 +
 src/compiler/scala/tools/cmd/program/Tokens.scala  |  100 +
 .../scala/tools/nsc/CompilationUnits.scala         |   48 +-
 src/compiler/scala/tools/nsc/CompileClient.scala   |  133 +-
 src/compiler/scala/tools/nsc/CompileServer.scala   |  171 +-
 src/compiler/scala/tools/nsc/CompileSocket.scala   |  247 +-
 src/compiler/scala/tools/nsc/CompilerCommand.scala |  199 +-
 src/compiler/scala/tools/nsc/CompilerRun.scala     |    3 +-
 src/compiler/scala/tools/nsc/ConsoleWriter.scala   |    5 +-
 src/compiler/scala/tools/nsc/EvalLoop.scala        |   22 +-
 src/compiler/scala/tools/nsc/FatalError.scala      |   16 +-
 .../scala/tools/nsc/GenericRunnerCommand.scala     |   97 +-
 .../scala/tools/nsc/GenericRunnerSettings.scala    |   53 +-
 src/compiler/scala/tools/nsc/Global.scala          |  840 ++-
 src/compiler/scala/tools/nsc/IdeSupport.scala      |   42 -
 src/compiler/scala/tools/nsc/Interpreter.scala     | 1563 +++--
 .../scala/tools/nsc/InterpreterCommand.scala       |    8 +-
 src/compiler/scala/tools/nsc/InterpreterLoop.scala |  691 ++-
 .../scala/tools/nsc/InterpreterResults.scala       |    3 +-
 .../scala/tools/nsc/InterpreterSettings.scala      |   64 +-
 src/compiler/scala/tools/nsc/Main.scala            |   73 +-
 .../scala/tools/nsc/MainGenericRunner.scala        |  206 +-
 src/compiler/scala/tools/nsc/MainInterpreter.scala |    3 +-
 src/compiler/scala/tools/nsc/MainTokenMetric.scala |   23 +-
 .../scala/tools/nsc/NewLinePrintWriter.scala       |    3 +-
 src/compiler/scala/tools/nsc/NoPhase.scala         |    3 +-
 src/compiler/scala/tools/nsc/ObjectRunner.scala    |   61 +-
 .../scala/tools/nsc/OfflineCompilerCommand.scala   |   26 +-
 src/compiler/scala/tools/nsc/Phase.scala           |    7 +-
 src/compiler/scala/tools/nsc/PhaseAssembly.scala   |  316 +
 src/compiler/scala/tools/nsc/Properties.scala      |   78 +-
 src/compiler/scala/tools/nsc/ScalaDoc.scala        |  115 +-
 src/compiler/scala/tools/nsc/ScriptRunner.scala    |  474 +-
 src/compiler/scala/tools/nsc/Settings.scala        |  568 +-
 src/compiler/scala/tools/nsc/SubComponent.scala    |   21 +-
 src/compiler/scala/tools/nsc/ast/DocComments.scala |  431 ++
 .../scala/tools/nsc/ast/NodePrinters.scala         |  106 +-
 .../scala/tools/nsc/ast/TreeBrowsers.scala         |   97 +-
 src/compiler/scala/tools/nsc/ast/TreeDSL.scala     |  267 +
 src/compiler/scala/tools/nsc/ast/TreeGen.scala     |  310 +-
 src/compiler/scala/tools/nsc/ast/TreeInfo.scala    |  148 +-
 .../scala/tools/nsc/ast/TreePrinters.scala         |  441 +-
 src/compiler/scala/tools/nsc/ast/Trees.scala       | 1490 ++---
 .../scala/tools/nsc/ast/parser/BracePair.scala     |   17 +
 .../scala/tools/nsc/ast/parser/BracePatch.scala    |   13 +
 .../scala/tools/nsc/ast/parser/Change.scala        |   10 +
 .../scala/tools/nsc/ast/parser/MarkupParsers.scala |  822 +--
 .../scala/tools/nsc/ast/parser/NewScanners.scala   |  905 ---
 .../scala/tools/nsc/ast/parser/Parsers.scala       | 2703 +++++----
 .../scala/tools/nsc/ast/parser/Patch.scala         |    8 +
 .../scala/tools/nsc/ast/parser/Scanners.scala      | 1716 +++---
 .../tools/nsc/ast/parser/SymbolicXMLBuilder.scala  |  465 +-
 .../tools/nsc/ast/parser/SyntaxAnalyzer.scala      |   12 +-
 .../scala/tools/nsc/ast/parser/Tokens.scala        |   75 +-
 .../scala/tools/nsc/ast/parser/TreeBuilder.scala   |  426 +-
 .../scala/tools/nsc/backend/JavaPlatform.scala     |   41 +
 .../scala/tools/nsc/backend/MSILPlatform.scala     |   36 +
 .../scala/tools/nsc/backend/Platform.scala         |   31 +
 .../scala/tools/nsc/backend/ScalaPrimitives.scala  |  196 +-
 .../tools/nsc/backend/WorklistAlgorithm.scala      |    6 +-
 .../tools/nsc/backend/icode/BasicBlocks.scala      |  175 +-
 .../tools/nsc/backend/icode/CheckerError.scala     |   11 -
 .../tools/nsc/backend/icode/CheckerException.scala |   12 +
 .../scala/tools/nsc/backend/icode/Checkers.scala   |   35 +-
 .../nsc/backend/icode/ExceptionHandlers.scala      |    7 +-
 .../scala/tools/nsc/backend/icode/GenICode.scala   | 1355 ++---
 .../scala/tools/nsc/backend/icode/ICodes.scala     |   32 +-
 .../tools/nsc/backend/icode/Linearizers.scala      |  158 +-
 .../scala/tools/nsc/backend/icode/Members.scala    |  104 +-
 .../scala/tools/nsc/backend/icode/Opcodes.scala    |   57 +-
 .../scala/tools/nsc/backend/icode/Primitives.scala |    7 +-
 .../scala/tools/nsc/backend/icode/Printers.scala   |   16 +-
 .../scala/tools/nsc/backend/icode/Repository.scala |    8 +-
 .../scala/tools/nsc/backend/icode/TypeKinds.scala  |  217 +-
 .../scala/tools/nsc/backend/icode/TypeStacks.scala |   40 +-
 .../backend/icode/analysis/CompleteLattice.scala   |   14 +-
 .../backend/icode/analysis/CopyPropagation.scala   |  158 +-
 .../backend/icode/analysis/DataFlowAnalysis.scala  |   28 +-
 .../nsc/backend/icode/analysis/Liveness.scala      |   10 +-
 .../nsc/backend/icode/analysis/LubError.scala      |   12 -
 .../nsc/backend/icode/analysis/LubException.scala  |   12 +
 .../nsc/backend/icode/analysis/ProgramPoint.scala  |    7 +-
 .../icode/analysis/ReachingDefinitions.scala       |   44 +-
 .../backend/icode/analysis/TypeFlowAnalysis.scala  |   78 +-
 .../scala/tools/nsc/backend/jvm/GenJVM.scala       |  945 +--
 .../scala/tools/nsc/backend/msil/GenMSIL.scala     | 1439 ++---
 .../tools/nsc/backend/opt/ClosureElimination.scala |   75 +-
 .../nsc/backend/opt/DeadCodeElimination.scala      |   37 +-
 .../scala/tools/nsc/backend/opt/Inliners.scala     |  253 +-
 .../scala/tools/nsc/dependencies/Changes.scala     |  211 +
 .../nsc/dependencies/DependencyAnalysis.scala      |  231 +
 .../scala/tools/nsc/dependencies/Files.scala       |  177 +
 .../scala/tools/nsc/doc/DefaultDocDriver.scala     |  305 -
 src/compiler/scala/tools/nsc/doc/DocDriver.scala   |   20 -
 src/compiler/scala/tools/nsc/doc/DocFactory.scala  |   66 +
 src/compiler/scala/tools/nsc/doc/DocUtil.scala     |  123 -
 .../scala/tools/nsc/doc/ModelAdditions.scala       |  410 --
 .../scala/tools/nsc/doc/ModelExtractor.scala       |  449 --
 src/compiler/scala/tools/nsc/doc/ModelFrames.scala |  395 --
 src/compiler/scala/tools/nsc/doc/ModelToXML.scala  |  376 --
 src/compiler/scala/tools/nsc/doc/Settings.scala    |   42 +-
 .../scala/tools/nsc/doc/SourcelessComments.scala   |  249 +
 src/compiler/scala/tools/nsc/doc/Universe.scala    |   11 +
 .../scala/tools/nsc/doc/html/HtmlFactory.scala     |   79 +
 .../scala/tools/nsc/doc/html/HtmlPage.scala        |  239 +
 .../scala/tools/nsc/doc/html/page/Index.scala      |  127 +
 .../scala/tools/nsc/doc/html/page/Source.scala     |  129 +
 .../scala/tools/nsc/doc/html/page/Template.scala   |  540 ++
 .../tools/nsc/doc/html/resource/lib/class.png      |  Bin 0 -> 516 bytes
 .../tools/nsc/doc/html/resource/lib/class_big.png  |  Bin 0 -> 3183 bytes
 .../nsc/doc/html/resource/lib/filter_box_left.png  |  Bin 0 -> 481 bytes
 .../nsc/doc/html/resource/lib/filter_box_left.psd  |  Bin 0 -> 30823 bytes
 .../nsc/doc/html/resource/lib/filter_box_right.png |  Bin 0 -> 533 bytes
 .../nsc/doc/html/resource/lib/filter_box_right.psd |  Bin 0 -> 31295 bytes
 .../tools/nsc/doc/html/resource/lib/index.css      |  204 +
 .../scala/tools/nsc/doc/html/resource/lib/index.js |  290 +
 .../tools/nsc/doc/html/resource/lib/jquery-ui.js   |  401 ++
 .../tools/nsc/doc/html/resource/lib/jquery.js      |  154 +
 .../nsc/doc/html/resource/lib/jquery.layout.js     |   18 +
 .../tools/nsc/doc/html/resource/lib/object.png     |  Bin 0 -> 518 bytes
 .../tools/nsc/doc/html/resource/lib/object_big.png |  Bin 0 -> 3318 bytes
 .../tools/nsc/doc/html/resource/lib/package.png    |  Bin 0 -> 488 bytes
 .../nsc/doc/html/resource/lib/package_big.png      |  Bin 0 -> 3183 bytes
 .../tools/nsc/doc/html/resource/lib/remove.png     |  Bin 0 -> 3186 bytes
 .../tools/nsc/doc/html/resource/lib/remove.psd     |  Bin 0 -> 28904 bytes
 .../tools/nsc/doc/html/resource/lib/scheduler.js   |   71 +
 .../tools/nsc/doc/html/resource/lib/template.css   |  496 ++
 .../tools/nsc/doc/html/resource/lib/template.js    |  270 +
 .../nsc/doc/html/resource/lib/tools.tooltip.js     |   14 +
 .../tools/nsc/doc/html/resource/lib/trait.png      |  Bin 0 -> 494 bytes
 .../tools/nsc/doc/html/resource/lib/trait_big.png  |  Bin 0 -> 3088 bytes
 .../tools/nsc/doc/html/resource/lib/type_tags.ai   | 6020 ++++++++++++++++++++
 .../tools/nsc/doc/html/resource/lib/versions.txt   |    1 +
 .../scala/tools/nsc/doc/model/Entity.scala         |  190 +
 .../scala/tools/nsc/doc/model/ModelFactory.scala   |  572 ++
 .../scala/tools/nsc/doc/model/TreeEntity.scala     |   16 +
 .../scala/tools/nsc/doc/model/TreeFactory.scala    |   89 +
 .../scala/tools/nsc/doc/model/TypeEntity.scala     |   25 +
 .../scala/tools/nsc/doc/model/comment/Body.scala   |   73 +
 .../tools/nsc/doc/model/comment/Comment.scala      |   77 +
 .../nsc/doc/model/comment/CommentFactory.scala     |  865 +++
 src/compiler/scala/tools/nsc/doc/script.js         |  112 -
 src/compiler/scala/tools/nsc/doc/style.css         |  148 -
 .../scala/tools/nsc/interactive/BuildManager.scala |   87 +
 .../tools/nsc/interactive/CompilerControl.scala    |  157 +
 .../scala/tools/nsc/interactive/ContextTrees.scala |  146 +
 .../scala/tools/nsc/interactive/Global.scala       |  627 ++
 .../scala/tools/nsc/interactive/REPL.scala         |  128 +
 .../tools/nsc/interactive/RangePositions.scala     |  270 +
 .../nsc/interactive/RefinedBuildManager.scala      |  351 ++
 .../scala/tools/nsc/interactive/Response.scala     |   97 +
 .../nsc/interactive/RichCompilationUnits.scala     |   44 +
 .../tools/nsc/interactive/SimpleBuildManager.scala |   99 +
 .../nsc/interpreter/AbstractFileClassLoader.scala  |   36 +-
 .../scala/tools/nsc/interpreter/ByteCode.scala     |   64 +
 .../scala/tools/nsc/interpreter/Completion.scala   |  366 ++
 .../tools/nsc/interpreter/CompletionAware.scala    |  130 +
 .../tools/nsc/interpreter/CompletionOutput.scala   |   88 +
 .../scala/tools/nsc/interpreter/Delimited.scala    |   36 +
 .../tools/nsc/interpreter/FileCompletion.scala     |   54 +
 .../scala/tools/nsc/interpreter/History.scala      |   36 +
 .../tools/nsc/interpreter/InteractiveReader.scala  |   49 +-
 .../scala/tools/nsc/interpreter/JLineReader.scala  |   32 +-
 .../scala/tools/nsc/interpreter/Parsed.scala       |   68 +
 .../tools/nsc/interpreter/ProductCompletion.scala  |   44 +
 .../nsc/interpreter/ReflectionCompletion.scala     |  112 +
 .../scala/tools/nsc/interpreter/SimpleReader.scala |   13 +-
 .../tools/nsc/interpreter/XMLCompletion.scala      |   44 +
 .../scala/tools/nsc/interpreter/package.scala      |   30 +
 src/compiler/scala/tools/nsc/io/AbstractFile.scala |  124 +-
 src/compiler/scala/tools/nsc/io/Directory.scala    |   87 +
 src/compiler/scala/tools/nsc/io/File.scala         |  157 +
 .../tools/nsc/io/FileOperationException.scala      |   13 +
 .../scala/tools/nsc/io/NullPrintStream.scala       |   19 +
 src/compiler/scala/tools/nsc/io/Path.scala         |  258 +
 src/compiler/scala/tools/nsc/io/PlainFile.scala    |   82 +-
 src/compiler/scala/tools/nsc/io/Process.scala      |  201 +
 src/compiler/scala/tools/nsc/io/Socket.scala       |   46 +
 src/compiler/scala/tools/nsc/io/SourceReader.scala |   45 +-
 src/compiler/scala/tools/nsc/io/Streamable.scala   |  109 +
 .../scala/tools/nsc/io/VirtualDirectory.scala      |   63 +-
 src/compiler/scala/tools/nsc/io/VirtualFile.scala  |   45 +-
 src/compiler/scala/tools/nsc/io/ZipArchive.scala   |  483 +-
 .../scala/tools/nsc/javac/JavaParsers.scala        |  147 +-
 .../scala/tools/nsc/javac/JavaScanners.scala       |   61 +-
 .../scala/tools/nsc/javac/JavaTokens.scala         |   37 +-
 .../scala/tools/nsc/matching/CodeFactory.scala     |  191 -
 .../scala/tools/nsc/matching/MatchSupport.scala    |  141 +
 .../scala/tools/nsc/matching/MatchUtil.scala       |   95 -
 src/compiler/scala/tools/nsc/matching/Matrix.scala |  210 +
 .../scala/tools/nsc/matching/MatrixAdditions.scala |  236 +
 .../tools/nsc/matching/ParallelMatching.scala      | 1728 +++---
 .../scala/tools/nsc/matching/PatternBindings.scala |  153 +
 .../scala/tools/nsc/matching/PatternNodes.scala    |  246 -
 .../scala/tools/nsc/matching/Patterns.scala        |  531 ++
 .../scala/tools/nsc/matching/TransMatcher.scala    |  143 +-
 src/compiler/scala/tools/nsc/models/Models.scala   |  423 --
 .../scala/tools/nsc/models/SemanticTokens.scala    |  718 ---
 .../scala/tools/nsc/models/Signatures.scala        |   88 -
 src/compiler/scala/tools/nsc/plugins/Plugin.scala  |  116 +-
 .../scala/tools/nsc/plugins/PluginComponent.scala  |   22 +-
 .../tools/nsc/plugins/PluginDescription.scala      |    6 +-
 .../tools/nsc/plugins/PluginLoadException.scala    |    6 +-
 src/compiler/scala/tools/nsc/plugins/Plugins.scala |  215 +-
 .../tools/nsc/reporters/AbstractReporter.scala     |   37 +-
 .../tools/nsc/reporters/ConsoleReporter.scala      |   66 +-
 .../scala/tools/nsc/reporters/Reporter.scala       |   36 +-
 .../scala/tools/nsc/reporters/ReporterTimer.scala  |    6 +-
 .../scala/tools/nsc/reporters/StoreReporter.scala  |    6 +-
 .../tools/nsc/settings/AbsScalaSettings.scala      |   40 +
 .../scala/tools/nsc/settings/AbsSettings.scala     |  137 +
 .../tools/nsc/settings/AdvancedScalaSettings.scala |   76 +
 .../tools/nsc/settings/ImmutableSettings.scala     |   11 +
 .../scala/tools/nsc/settings/MutableSettings.scala |  599 ++
 .../scala/tools/nsc/settings/ScalaSettings.scala   |  163 +
 .../tools/nsc/settings/StandardScalaSettings.scala |   54 +
 .../tools/nsc/symtab/AnnotationCheckers.scala      |   70 +-
 .../scala/tools/nsc/symtab/AnnotationInfos.scala   |  208 +-
 .../scala/tools/nsc/symtab/BaseTypeSeqs.scala      |  135 +-
 .../scala/tools/nsc/symtab/Constants.scala         |  244 -
 .../scala/tools/nsc/symtab/Definitions.scala       | 1009 ++--
 src/compiler/scala/tools/nsc/symtab/Flags.scala    |  163 +-
 .../scala/tools/nsc/symtab/IdeSupport.scala        |  665 ---
 .../scala/tools/nsc/symtab/InfoTransformers.scala  |    6 +-
 src/compiler/scala/tools/nsc/symtab/Names.scala    |   71 +-
 .../scala/tools/nsc/symtab/Positions.scala         |   39 +
 src/compiler/scala/tools/nsc/symtab/Scopes.scala   |  217 +-
 src/compiler/scala/tools/nsc/symtab/StdNames.scala |  198 +-
 .../scala/tools/nsc/symtab/SymbolLoaders.scala     |  371 +-
 .../scala/tools/nsc/symtab/SymbolTable.scala       |   45 +-
 .../scala/tools/nsc/symtab/SymbolWalker.scala      |  254 -
 src/compiler/scala/tools/nsc/symtab/Symbols.scala  | 1120 ++--
 src/compiler/scala/tools/nsc/symtab/Types.scala    | 3705 +++++++-----
 .../nsc/symtab/classfile/AbstractFileReader.scala  |   16 +-
 .../nsc/symtab/classfile/ClassfileConstants.scala  |   12 +-
 .../nsc/symtab/classfile/ClassfileParser.scala     |  768 ++-
 .../tools/nsc/symtab/classfile/ICodeReader.scala   |  208 +-
 .../tools/nsc/symtab/classfile/MetaParser.scala    |   24 +-
 .../tools/nsc/symtab/classfile/PickleBuffer.scala  |  148 -
 .../tools/nsc/symtab/classfile/PickleFormat.scala  |  244 -
 .../scala/tools/nsc/symtab/classfile/Pickler.scala | 1252 ++--
 .../tools/nsc/symtab/classfile/UnPickler.scala     |  800 +--
 .../scala/tools/nsc/symtab/clr/CLRTypes.scala      |  145 +-
 .../scala/tools/nsc/symtab/clr/TypeParser.scala    |  106 +-
 .../scala/tools/nsc/transform/AddInterfaces.scala  |   55 +-
 .../scala/tools/nsc/transform/CleanUp.scala        | 1046 ++--
 .../scala/tools/nsc/transform/Constructors.scala   |  215 +-
 .../scala/tools/nsc/transform/Erasure.scala        |  800 +--
 .../scala/tools/nsc/transform/ExplicitOuter.scala  |  350 +-
 .../scala/tools/nsc/transform/Flatten.scala        |   18 +-
 .../scala/tools/nsc/transform/InfoTransform.scala  |    9 +-
 .../scala/tools/nsc/transform/LambdaLift.scala     |  129 +-
 .../scala/tools/nsc/transform/LazyVals.scala       |  104 +-
 .../scala/tools/nsc/transform/LiftCode.scala       |   16 +-
 src/compiler/scala/tools/nsc/transform/Mixin.scala |  416 +-
 .../tools/nsc/transform/OverridingPairs.scala      |  180 +-
 .../scala/tools/nsc/transform/Reifiers.scala       |   24 +-
 .../tools/nsc/transform/SampleTransform.scala      |    9 +-
 .../tools/nsc/transform/SpecializeTypes.scala      | 1478 +++++
 .../scala/tools/nsc/transform/TailCalls.scala      |  213 +-
 .../scala/tools/nsc/transform/Transform.scala      |    6 +-
 .../tools/nsc/transform/TypingTransformers.scala   |   21 +-
 .../scala/tools/nsc/transform/UnCurry.scala        |  459 +-
 .../scala/tools/nsc/typechecker/Analyzer.scala     |   59 +-
 .../tools/nsc/typechecker/ConstantFolder.scala     |  209 +-
 .../scala/tools/nsc/typechecker/Contexts.scala     |  386 +-
 .../scala/tools/nsc/typechecker/DeVirtualize.scala |   65 +-
 .../scala/tools/nsc/typechecker/Duplicators.scala  |  293 +
 .../scala/tools/nsc/typechecker/EtaExpansion.scala |   86 +-
 .../scala/tools/nsc/typechecker/IdeSupport.scala   |  375 --
 .../scala/tools/nsc/typechecker/Implicits.scala    |  980 ++++
 .../scala/tools/nsc/typechecker/Infer.scala        | 1117 ++--
 .../scala/tools/nsc/typechecker/Namers.scala       | 1045 ++--
 .../tools/nsc/typechecker/NamesDefaults.scala      |  504 ++
 .../scala/tools/nsc/typechecker/RefChecks.scala    | 1026 +++-
 .../tools/nsc/typechecker/SuperAccessors.scala     |  364 +-
 .../tools/nsc/typechecker/SyntheticMethods.scala   |  469 +-
 .../scala/tools/nsc/typechecker/TreeCheckers.scala |  148 +-
 .../tools/nsc/typechecker/TypeDiagnostics.scala    |  268 +
 .../scala/tools/nsc/typechecker/Typers.scala       | 3695 ++++++------
 .../scala/tools/nsc/typechecker/Unapplies.scala    |  205 +-
 .../scala/tools/nsc/typechecker/Variances.scala    |   28 +-
 .../scala/tools/nsc/util/ArgumentsExpander.scala   |   42 -
 src/compiler/scala/tools/nsc/util/BitSet.scala     |  156 +
 .../scala/tools/nsc/util/CharArrayReader.scala     |  198 +-
 src/compiler/scala/tools/nsc/util/Chars.scala      |   85 +
 src/compiler/scala/tools/nsc/util/ClassPath.scala  |  657 ++-
 .../scala/tools/nsc/util/CommandLineParser.scala   |  145 +
 src/compiler/scala/tools/nsc/util/DocStrings.scala |  138 +
 .../scala/tools/nsc/util/FreshNameCreator.scala    |   66 +-
 src/compiler/scala/tools/nsc/util/HashSet.scala    |   72 +-
 .../scala/tools/nsc/util/InterruptReq.scala        |   35 +
 .../scala/tools/nsc/util/JavaCharArrayReader.scala |  123 +
 .../scala/tools/nsc/util/MsilClassPath.scala       |  169 +
 .../scala/tools/nsc/util/NameTransformer.scala     |  148 -
 .../scala/tools/nsc/util/NewCharArrayReader.scala  |   74 -
 src/compiler/scala/tools/nsc/util/Position.scala   |  314 +-
 src/compiler/scala/tools/nsc/util/RegexCache.scala |    6 +-
 .../scala/tools/nsc/util/ScalaClassLoader.scala    |  131 +
 src/compiler/scala/tools/nsc/util/Set.scala        |   12 +-
 .../scala/tools/nsc/util/ShowPickled.scala         |  236 +-
 src/compiler/scala/tools/nsc/util/SourceFile.scala |  294 +-
 src/compiler/scala/tools/nsc/util/Statistics.scala |  290 +-
 src/compiler/scala/tools/nsc/util/TreeSet.scala    |   18 +-
 .../scala/tools/nsc/util/WorkScheduler.scala       |   79 +
 src/compiler/scala/tools/nsc/util/package.scala    |   29 +
 src/compiler/scala/tools/nsc/util/trace.scala      |   13 +
 src/compiler/scala/tools/util/AbstractTimer.scala  |    5 +-
 .../scala/tools/util/ClassPathSettings.scala       |   32 +
 src/compiler/scala/tools/util/PathResolver.scala   |  253 +
 .../scala/tools/util/SocketConnection.scala        |    3 +-
 src/compiler/scala/tools/util/SocketServer.scala   |   92 +-
 src/compiler/scala/tools/util/StringOps.scala      |   26 +-
 src/compiler/scala/tools/util/UTF8Codec.scala      |   82 -
 src/compiler/scala/tools/util/Which.scala          |   39 +
 .../scala/util/continuations/ControlContext.scala  |  161 +
 .../library/scala/util/continuations/package.scala |   65 +
 .../tools/selectivecps/CPSAnnotationChecker.scala  |  462 ++
 .../plugin/scala/tools/selectivecps/CPSUtils.scala |  131 +
 .../tools/selectivecps/SelectiveANFTransform.scala |  414 ++
 .../tools/selectivecps/SelectiveCPSPlugin.scala    |   60 +
 .../tools/selectivecps/SelectiveCPSTransform.scala |  384 ++
 src/continuations/plugin/scalac-plugin.xml         |    5 +
 src/dbc/scala/dbc/DataType.scala                   |    3 +-
 src/dbc/scala/dbc/Database.scala                   |    5 +-
 src/dbc/scala/dbc/Syntax.scala                     |    3 +-
 src/dbc/scala/dbc/Utilities.scala                  |    3 +-
 src/dbc/scala/dbc/Value.scala                      |    3 +-
 src/dbc/scala/dbc/Vendor.scala                     |    3 +-
 .../scala/dbc/datatype/ApproximateNumeric.scala    |    6 +-
 src/dbc/scala/dbc/datatype/Boolean.scala           |    6 +-
 src/dbc/scala/dbc/datatype/Character.scala         |    6 +-
 .../scala/dbc/datatype/CharacterLargeObject.scala  |    6 +-
 src/dbc/scala/dbc/datatype/CharacterString.scala   |    6 +-
 src/dbc/scala/dbc/datatype/CharacterVarying.scala  |    6 +-
 src/dbc/scala/dbc/datatype/ExactNumeric.scala      |    6 +-
 src/dbc/scala/dbc/datatype/Factory.scala           |    8 +-
 src/dbc/scala/dbc/datatype/Numeric.scala           |    6 +-
 src/dbc/scala/dbc/datatype/String.scala            |    6 +-
 src/dbc/scala/dbc/datatype/Unknown.scala           |    6 +-
 .../scala/dbc/exception/IncompatibleSchema.scala   |    6 +-
 .../scala/dbc/exception/UnsupportedFeature.scala   |    6 +-
 src/dbc/scala/dbc/result/Field.scala               |    6 +-
 src/dbc/scala/dbc/result/FieldMetadata.scala       |    6 +-
 src/dbc/scala/dbc/result/Relation.scala            |   32 +-
 src/dbc/scala/dbc/result/Status.scala              |    6 +-
 src/dbc/scala/dbc/result/Tuple.scala               |    6 +-
 src/dbc/scala/dbc/statement/AccessMode.scala       |    6 +-
 src/dbc/scala/dbc/statement/DerivedColumn.scala    |    6 +-
 src/dbc/scala/dbc/statement/Expression.scala       |    6 +-
 src/dbc/scala/dbc/statement/Insert.scala           |    6 +-
 src/dbc/scala/dbc/statement/InsertionData.scala    |    6 +-
 src/dbc/scala/dbc/statement/IsolationLevel.scala   |    6 +-
 src/dbc/scala/dbc/statement/JoinType.scala         |    6 +-
 src/dbc/scala/dbc/statement/Jointure.scala         |    6 +-
 src/dbc/scala/dbc/statement/Relation.scala         |    6 +-
 src/dbc/scala/dbc/statement/Select.scala           |    6 +-
 src/dbc/scala/dbc/statement/SetClause.scala        |    6 +-
 src/dbc/scala/dbc/statement/SetQuantifier.scala    |    6 +-
 src/dbc/scala/dbc/statement/Statement.scala        |    6 +-
 src/dbc/scala/dbc/statement/Status.scala           |    6 +-
 src/dbc/scala/dbc/statement/Table.scala            |    6 +-
 src/dbc/scala/dbc/statement/Transaction.scala      |    6 +-
 src/dbc/scala/dbc/statement/Update.scala           |    6 +-
 .../scala/dbc/statement/expression/Aggregate.scala |    7 +-
 .../dbc/statement/expression/BinaryOperator.scala  |    7 +-
 .../scala/dbc/statement/expression/Constant.scala  |    7 +-
 .../scala/dbc/statement/expression/Default.scala   |    7 +-
 src/dbc/scala/dbc/statement/expression/Field.scala |    7 +-
 .../dbc/statement/expression/FunctionCall.scala    |    7 +-
 .../scala/dbc/statement/expression/Select.scala    |    7 +-
 .../dbc/statement/expression/SetFunction.scala     |    7 +-
 .../scala/dbc/statement/expression/TypeCast.scala  |    7 +-
 .../dbc/statement/expression/UnaryOperator.scala   |    7 +-
 src/dbc/scala/dbc/syntax/DataTypeUtil.scala        |    6 +-
 src/dbc/scala/dbc/syntax/Database.scala            |    6 +-
 src/dbc/scala/dbc/syntax/Statement.scala           |    6 +-
 src/dbc/scala/dbc/syntax/StatementExpression.scala |    6 +-
 src/dbc/scala/dbc/value/ApproximateNumeric.scala   |    6 +-
 src/dbc/scala/dbc/value/Boolean.scala              |    6 +-
 src/dbc/scala/dbc/value/Character.scala            |    6 +-
 src/dbc/scala/dbc/value/CharacterLargeObject.scala |    6 +-
 src/dbc/scala/dbc/value/CharacterVarying.scala     |    6 +-
 src/dbc/scala/dbc/value/Conversion.scala           |    6 +-
 src/dbc/scala/dbc/value/ExactNumeric.scala         |    6 +-
 src/dbc/scala/dbc/value/Factory.scala              |    6 +-
 src/dbc/scala/dbc/value/Unknown.scala              |    6 +-
 src/dbc/scala/dbc/vendor/PostgreSQL.scala          |    6 +-
 src/dotnet-library/README                          |   78 -
 src/dotnet-library/scala/Application.scala         |   61 -
 src/dotnet-library/scala/BigDecimal.scala          |    1 -
 src/dotnet-library/scala/BigInt.scala              |    1 -
 src/dotnet-library/scala/Console.scala             |  308 -
 src/dotnet-library/scala/List.scala                | 1362 -----
 src/dotnet-library/scala/Math.scala                |  147 -
 src/dotnet-library/scala/Predef.scala              |  328 --
 src/dotnet-library/scala/Random.scala              |   77 -
 src/dotnet-library/scala/StringBuilder.scala       |  913 ---
 src/dotnet-library/scala/Symbol.scala              |   49 -
 .../scala/collection/immutable/PagedSeq.scala      |    1 -
 .../scala/collection/jcl/ArrayList.scala           |    1 -
 .../scala/collection/jcl/Buffer.scala              |    1 -
 .../scala/collection/jcl/BufferIterator.scala      |    1 -
 .../scala/collection/jcl/BufferWrapper.scala       |    1 -
 .../scala/collection/jcl/Collection.scala          |    1 -
 .../scala/collection/jcl/CollectionWrapper.scala   |    1 -
 .../scala/collection/jcl/Conversions.scala         |    1 -
 .../scala/collection/jcl/HashMap.scala             |    1 -
 .../scala/collection/jcl/HashSet.scala             |    1 -
 .../scala/collection/jcl/Hashtable.scala           |    1 -
 .../scala/collection/jcl/IdentityHashMap.scala     |    1 -
 .../scala/collection/jcl/IterableWrapper.scala     |    1 -
 .../scala/collection/jcl/LinkedHashMap.scala       |    1 -
 .../scala/collection/jcl/LinkedHashSet.scala       |    1 -
 .../scala/collection/jcl/LinkedList.scala          |    1 -
 src/dotnet-library/scala/collection/jcl/Map.scala  |    1 -
 .../scala/collection/jcl/MapWrapper.scala          |    1 -
 .../scala/collection/jcl/MutableIterable.scala     |    1 -
 .../scala/collection/jcl/MutableIterator.scala     |    1 -
 .../scala/collection/jcl/MutableSeq.scala          |    1 -
 .../scala/collection/jcl/Ranged.scala              |    1 -
 .../scala/collection/jcl/SeqIterator.scala         |    1 -
 src/dotnet-library/scala/collection/jcl/Set.scala  |    1 -
 .../scala/collection/jcl/SetWrapper.scala          |    1 -
 .../scala/collection/jcl/Sorted.scala              |    1 -
 .../scala/collection/jcl/SortedMap.scala           |    1 -
 .../scala/collection/jcl/SortedMapWrapper.scala    |    1 -
 .../scala/collection/jcl/SortedSet.scala           |    1 -
 .../scala/collection/jcl/SortedSetWrapper.scala    |    1 -
 .../scala/collection/jcl/Tests.scala               |    1 -
 .../scala/collection/jcl/TreeMap.scala             |    1 -
 .../scala/collection/jcl/TreeSet.scala             |    1 -
 .../scala/collection/jcl/WeakHashMap.scala         |    1 -
 .../scala/collection/mutable/JavaMapAdaptor.scala  |    1 -
 .../scala/collection/mutable/JavaSetAdaptor.scala  |    1 -
 .../scala/collection/mutable/OpenHashMap.scala     |    4 -
 src/dotnet-library/scala/compat/Platform.scala     |   63 -
 src/dotnet-library/scala/concurrent/jolib.scala    |    1 -
 src/dotnet-library/scala/concurrent/ops.scala      |    1 -
 src/dotnet-library/scala/concurrent/pilib.scala    |    1 -
 src/dotnet-library/scala/io/BufferedSource.scala   |    1 -
 src/dotnet-library/scala/io/BytePickle.scala       |    1 -
 src/dotnet-library/scala/io/Position.scala         |    1 -
 src/dotnet-library/scala/io/Source.scala           |    1 -
 src/dotnet-library/scala/io/UTF8Codec.scala        |    1 -
 src/dotnet-library/scala/mobile/Code.scala         |    1 -
 src/dotnet-library/scala/mobile/Location.scala     |    1 -
 .../scala/ref/PhantomReference.scala               |    1 -
 src/dotnet-library/scala/ref/ReferenceQueue.scala  |    1 -
 .../scala/ref/ReferenceWrapper.scala               |    1 -
 src/dotnet-library/scala/ref/SoftReference.scala   |    1 -
 src/dotnet-library/scala/ref/WeakReference.scala   |    1 -
 src/dotnet-library/scala/reflect/Manifest.scala    |  143 -
 .../scala/reflect/ScalaBeanInfo.scala              |    1 -
 src/dotnet-library/scala/runtime/BooleanRef.cs     |   22 -
 src/dotnet-library/scala/runtime/BoxedUnit.cs      |   36 -
 src/dotnet-library/scala/runtime/ByteRef.cs        |   22 -
 src/dotnet-library/scala/runtime/CharRef.cs        |   22 -
 src/dotnet-library/scala/runtime/Comparator.cs     |   51 -
 src/dotnet-library/scala/runtime/DoubleRef.cs      |   22 -
 .../scala/runtime/ExceptionHandling.cs             |   27 -
 src/dotnet-library/scala/runtime/FloatRef.cs       |   22 -
 src/dotnet-library/scala/runtime/IntRef.cs         |   22 -
 src/dotnet-library/scala/runtime/LongRef.cs        |   22 -
 .../scala/runtime/NonLocalReturnException.scala    |   17 -
 src/dotnet-library/scala/runtime/ObjectRef.cs      |   22 -
 src/dotnet-library/scala/runtime/RichChar.scala    |   70 -
 src/dotnet-library/scala/runtime/RichClass.scala   |   25 -
 src/dotnet-library/scala/runtime/RichDouble.scala  |   52 -
 .../scala/runtime/RichException.scala              |   21 -
 src/dotnet-library/scala/runtime/RichFloat.scala   |   54 -
 src/dotnet-library/scala/runtime/RichInt.scala     |   39 -
 src/dotnet-library/scala/runtime/RichLong.scala    |   30 -
 src/dotnet-library/scala/runtime/RichString.scala  |  219 -
 .../scala/runtime/RichStringBuilder.scala          |    1 -
 src/dotnet-library/scala/runtime/Runnable.cs       |   17 -
 src/dotnet-library/scala/runtime/ShortRef.cs       |   22 -
 src/dotnet-library/scala/runtime/StringAdd.scala   |   28 -
 .../scala/runtime/SymtabAttribute.cs               |   22 -
 src/dotnet-library/scala/testing/Benchmark.scala   |    1 -
 src/dotnet-library/scala/testing/SUnit.scala       |    1 -
 src/dotnet-library/scala/testing/Show.scala        |    1 -
 src/dotnet-library/scala/text/Document.scala       |  122 -
 .../scala/util/DynamicVariable.scala               |   83 -
 src/dotnet-library/scala/util/Marshal.scala        |    1 -
 src/dotnet-library/scala/util/Properties.scala     |    1 -
 src/dotnet-library/scala/util/Random.scala         |   74 -
 .../scala/util/automata/BaseBerrySethi.scala       |    1 -
 .../scala/util/automata/DetWordAutom.scala         |    1 -
 .../scala/util/automata/Inclusion.scala            |    1 -
 .../scala/util/automata/NondetWordAutom.scala      |    1 -
 .../scala/util/automata/SubsetConstruction.scala   |    1 -
 .../scala/util/automata/WordBerrySethi.scala       |    1 -
 .../scala/util/grammar/HedgeRHS.scala              |    1 -
 .../scala/util/grammar/TreeRHS.scala               |    1 -
 .../scala/util/logging/ConsoleLogger.scala         |    1 -
 src/dotnet-library/scala/util/logging/Logged.scala |    1 -
 .../scala/util/matching/BitField.scala             |    1 -
 .../scala/util/matching/FixedBitField.scala        |    1 -
 .../scala/util/matching/MatchableBigInt.scala      |    1 -
 src/dotnet-library/scala/util/matching/Regex.scala |    1 -
 .../util/parsing/CharInputStreamIterator.scala     |    1 -
 .../scala/util/parsing/Parsers.scala               |    1 -
 .../scala/util/parsing/SimpleTokenizer.scala       |    1 -
 .../scala/util/parsing/ast/AbstractSyntax.scala    |    1 -
 .../scala/util/parsing/ast/Binders.scala           |    1 -
 .../parsing/combinator/ImplicitConversions.scala   |    1 -
 .../util/parsing/combinator/JavaTokenParsers.scala |    1 -
 .../scala/util/parsing/combinator/Parsers.scala    |    1 -
 .../util/parsing/combinator/RegexParsers.scala     |    1 -
 .../util/parsing/combinator/lexical/Lexical.scala  |    1 -
 .../util/parsing/combinator/lexical/Scanners.scala |    1 -
 .../parsing/combinator/lexical/StdLexical.scala    |    1 -
 .../syntactical/StandardTokenParsers.scala         |    1 -
 .../combinator/syntactical/StdTokenParsers.scala   |    1 -
 .../combinator/syntactical/TokenParsers.scala      |    1 -
 .../parsing/combinator/testing/RegexTest.scala     |    1 -
 .../util/parsing/combinator/testing/Tester.scala   |    1 -
 .../scala/util/parsing/combinatorold/$tilde.scala  |    1 -
 .../combinatorold/ImplicitConversions.scala        |    1 -
 .../scala/util/parsing/combinatorold/Parsers.scala |    1 -
 .../parsing/combinatorold/lexical/Lexical.scala    |    1 -
 .../parsing/combinatorold/lexical/Scanners.scala   |    1 -
 .../parsing/combinatorold/lexical/StdLexical.scala |    1 -
 .../combinatorold/syntactical/BindingParsers.scala |    1 -
 .../syntactical/StdTokenParsers.scala              |    1 -
 .../combinatorold/syntactical/TokenParsers.scala   |    1 -
 .../parsing/combinatorold/testing/Tester.scala     |    1 -
 .../util/parsing/input/CharArrayPosition.scala     |    1 -
 .../scala/util/parsing/input/CharArrayReader.scala |    1 -
 .../util/parsing/input/CharSequenceReader.scala    |    1 -
 .../scala/util/parsing/input/NoPosition.scala      |    1 -
 .../scala/util/parsing/input/OffsetPosition.scala  |    1 -
 .../scala/util/parsing/input/PagedSeqReader.scala  |    1 -
 .../scala/util/parsing/input/Position.scala        |    1 -
 .../scala/util/parsing/input/Positional.scala      |    1 -
 .../scala/util/parsing/input/Reader.scala          |    1 -
 .../scala/util/parsing/input/StreamReader.scala    |    1 -
 .../scala/util/parsing/json/JSON.scala             |    1 -
 .../scala/util/parsing/json/Lexer.scala            |    1 -
 .../scala/util/parsing/json/Parser.scala           |    1 -
 .../scala/util/parsing/syntax/StdTokens.scala      |    1 -
 .../scala/util/parsing/syntax/Tokens.scala         |    1 -
 src/dotnet-library/scala/util/regexp/Base.scala    |    1 -
 .../scala/util/regexp/PointedHedgeExp.scala        |    1 -
 .../scala/util/regexp/SyntaxError.scala            |    1 -
 src/dotnet-library/scala/util/regexp/WordExp.scala |    1 -
 src/dotnet-library/scala/xml/Atom.scala            |    1 -
 src/dotnet-library/scala/xml/Comment.scala         |    1 -
 src/dotnet-library/scala/xml/Document.scala        |    1 -
 src/dotnet-library/scala/xml/Elem.scala            |    1 -
 src/dotnet-library/scala/xml/EntityRef.scala       |    1 -
 src/dotnet-library/scala/xml/Group.scala           |    1 -
 src/dotnet-library/scala/xml/HasKeyValue.scala     |    1 -
 .../scala/xml/MalformedAttributeException.scala    |    1 -
 src/dotnet-library/scala/xml/MetaData.scala        |    1 -
 .../scala/xml/NamespaceBinding.scala               |    1 -
 src/dotnet-library/scala/xml/Node.scala            |    1 -
 src/dotnet-library/scala/xml/NodeBuffer.scala      |    1 -
 src/dotnet-library/scala/xml/NodeSeq.scala         |    1 -
 src/dotnet-library/scala/xml/NodeTraverser.scala   |    1 -
 src/dotnet-library/scala/xml/Null.scala            |    1 -
 src/dotnet-library/scala/xml/PCData.scala          |    1 -
 src/dotnet-library/scala/xml/Parsing.scala         |    1 -
 .../scala/xml/PrefixedAttribute.scala              |    1 -
 src/dotnet-library/scala/xml/PrettyPrinter.scala   |    1 -
 src/dotnet-library/scala/xml/ProcInstr.scala       |    1 -
 src/dotnet-library/scala/xml/QNode.scala           |    1 -
 src/dotnet-library/scala/xml/SpecialNode.scala     |    1 -
 src/dotnet-library/scala/xml/Text.scala            |    1 -
 src/dotnet-library/scala/xml/TextBuffer.scala      |    1 -
 src/dotnet-library/scala/xml/TopScope.scala        |    1 -
 src/dotnet-library/scala/xml/TypeSymbol.scala      |    1 -
 src/dotnet-library/scala/xml/Unparsed.scala        |    1 -
 .../scala/xml/UnprefixedAttribute.scala            |    1 -
 src/dotnet-library/scala/xml/Utility.scala         |    1 -
 src/dotnet-library/scala/xml/XML.scala             |    1 -
 src/dotnet-library/scala/xml/Xhtml.scala           |    1 -
 .../scala/xml/dtd/ContentModel.scala               |    1 -
 .../scala/xml/dtd/ContentModelParser.scala         |    1 -
 src/dotnet-library/scala/xml/dtd/DTD.scala         |    1 -
 src/dotnet-library/scala/xml/dtd/Decl.scala        |    1 -
 src/dotnet-library/scala/xml/dtd/DocType.scala     |    1 -
 .../scala/xml/dtd/DtdTypeSymbol.scala              |    1 -
 .../scala/xml/dtd/ElementValidator.scala           |    1 -
 src/dotnet-library/scala/xml/dtd/ExternalID.scala  |    1 -
 src/dotnet-library/scala/xml/dtd/Scanner.scala     |    1 -
 src/dotnet-library/scala/xml/dtd/Tokens.scala      |    1 -
 .../scala/xml/dtd/ValidationException.scala        |    1 -
 src/dotnet-library/scala/xml/factory/Binder.scala  |    1 -
 .../scala/xml/factory/LoggedNodeFactory.scala      |    1 -
 .../scala/xml/factory/NodeFactory.scala            |    1 -
 .../xml/include/CircularIncludeException.scala     |    1 -
 .../xml/include/UnavailableResourceException.scala |    1 -
 .../scala/xml/include/XIncludeException.scala      |    1 -
 .../scala/xml/include/sax/EncodingHeuristics.scala |    1 -
 .../scala/xml/include/sax/Main.scala               |    1 -
 .../scala/xml/include/sax/XIncludeFilter.scala     |    1 -
 .../scala/xml/include/sax/XIncluder.scala          |    1 -
 .../scala/xml/parsing/ConstructingHandler.scala    |    1 -
 .../scala/xml/parsing/ConstructingParser.scala     |    1 -
 .../scala/xml/parsing/DefaultMarkupHandler.scala   |    1 -
 .../scala/xml/parsing/ExternalSources.scala        |    1 -
 .../scala/xml/parsing/FactoryAdapter.scala         |    1 -
 .../scala/xml/parsing/FatalError.scala             |    1 -
 .../scala/xml/parsing/MarkupHandler.scala          |    1 -
 .../scala/xml/parsing/MarkupParser.scala           |    1 -
 .../xml/parsing/NoBindingFactoryAdapter.scala      |    1 -
 .../scala/xml/parsing/TokenTests.scala             |    1 -
 .../xml/parsing/ValidatingMarkupHandler.scala      |    1 -
 .../scala/xml/parsing/XhtmlEntities.scala          |    1 -
 .../scala/xml/parsing/XhtmlParser.scala            |    1 -
 src/dotnet-library/scala/xml/path/Expression.scala |    1 -
 .../scala/xml/persistent/CachedFileStorage.scala   |    1 -
 .../scala/xml/persistent/Index.scala               |    1 -
 .../scala/xml/persistent/IndexedStorage.scala      |    1 -
 .../scala/xml/persistent/SetStorage.scala          |    1 -
 src/dotnet-library/scala/xml/pull/XMLEvent.scala   |    1 -
 .../scala/xml/pull/XMLEventReader.scala            |    1 -
 .../scala/xml/transform/BasicTransformer.scala     |    1 -
 .../scala/xml/transform/RewriteRule.scala          |    1 -
 .../scala/xml/transform/RuleTransformer.scala      |    1 -
 src/fjbg/ch/epfl/lamp/fjbg/FJBGContext.java        |  169 +
 src/fjbg/ch/epfl/lamp/fjbg/JAccessFlags.java       |   31 +
 src/fjbg/ch/epfl/lamp/fjbg/JArrayType.java         |   58 +
 src/fjbg/ch/epfl/lamp/fjbg/JAttribute.java         |   74 +
 src/fjbg/ch/epfl/lamp/fjbg/JAttributeFactory.java  |   90 +
 .../ch/epfl/lamp/fjbg/JBootstrapInvokeDynamic.java |   35 +
 src/fjbg/ch/epfl/lamp/fjbg/JClass.java             |  319 ++
 src/fjbg/ch/epfl/lamp/fjbg/JCode.java              | 1130 ++++
 src/fjbg/ch/epfl/lamp/fjbg/JCodeAttribute.java     |   88 +
 src/fjbg/ch/epfl/lamp/fjbg/JCodeIterator.java      |  373 ++
 src/fjbg/ch/epfl/lamp/fjbg/JConstantPool.java      |  638 +++
 src/fjbg/ch/epfl/lamp/fjbg/JExtendedCode.java      |  613 ++
 src/fjbg/ch/epfl/lamp/fjbg/JField.java             |   29 +
 src/fjbg/ch/epfl/lamp/fjbg/JFieldOrMethod.java     |  121 +
 .../ch/epfl/lamp/fjbg/JInnerClassesAttribute.java  |   89 +
 src/fjbg/ch/epfl/lamp/fjbg/JLabel.java             |   26 +
 .../epfl/lamp/fjbg/JLineNumberTableAttribute.java  |   98 +
 src/fjbg/ch/epfl/lamp/fjbg/JLocalVariable.java     |   34 +
 src/fjbg/ch/epfl/lamp/fjbg/JMember.java            |   98 +
 src/fjbg/ch/epfl/lamp/fjbg/JMethod.java            |  132 +
 src/fjbg/ch/epfl/lamp/fjbg/JMethodType.java        |   71 +
 src/fjbg/ch/epfl/lamp/fjbg/JObjectType.java        |   52 +
 src/fjbg/ch/epfl/lamp/fjbg/JOpcode.java            | 1263 ++++
 src/fjbg/ch/epfl/lamp/fjbg/JOtherAttribute.java    |   53 +
 src/fjbg/ch/epfl/lamp/fjbg/JReferenceType.java     |   15 +
 .../ch/epfl/lamp/fjbg/JSourceFileAttribute.java    |   52 +
 src/fjbg/ch/epfl/lamp/fjbg/JType.java              |  288 +
 src/fjbg/ch/epfl/lamp/util/ByteArray.java          |  139 +
 .../scala/concurrent/forkjoin/ForkJoinPool.java    | 1870 ++++++
 .../scala/concurrent/forkjoin/ForkJoinTask.java    | 1063 ++++
 .../concurrent/forkjoin/ForkJoinWorkerThread.java  |  773 +++
 .../concurrent/forkjoin/LinkedTransferQueue.java   |  840 +++
 .../scala/concurrent/forkjoin/RecursiveAction.java |  151 +
 .../scala/concurrent/forkjoin/RecursiveTask.java   |   71 +
 .../concurrent/forkjoin/ThreadLocalRandom.java     |  186 +
 .../scala/concurrent/forkjoin/TransferQueue.java   |  118 +
 .../scala/concurrent/forkjoin/package-info.java    |   29 +
 src/intellij/actors.iml.SAMPLE                     |   21 +
 src/intellij/compiler.iml.SAMPLE                   |   27 +
 src/intellij/dbc.iml.SAMPLE                        |   22 +
 src/intellij/library.iml.SAMPLE                    |   23 +
 src/intellij/manual.iml.SAMPLE                     |   27 +
 src/intellij/partest.iml.SAMPLE                    |   28 +
 src/intellij/scala-lang.ipr.SAMPLE                 | 1446 +++++
 src/intellij/scalap.iml.SAMPLE                     |   19 +
 src/intellij/swing.iml.SAMPLE                      |   22 +
 src/jline/LICENSE.txt                              |   33 +
 src/jline/pom.xml                                  |  224 +
 src/jline/src/assembly/assembly.xml                |   55 +
 src/jline/src/main/java/jline/ANSIBuffer.java      |  405 ++
 .../src/main/java/jline/ArgumentCompletor.java     |  439 ++
 .../jline/CandidateCycleCompletionHandler.java     |   28 +
 .../java/jline/CandidateListCompletionHandler.java |  189 +
 .../src/main/java/jline/ClassNameCompletor.java    |  146 +
 .../src/main/java/jline/CompletionHandler.java     |   20 +
 src/jline/src/main/java/jline/Completor.java       |   32 +
 .../src/main/java/jline/ConsoleOperations.java     |  276 +
 src/jline/src/main/java/jline/ConsoleReader.java   | 1625 ++++++
 .../main/java/jline/ConsoleReaderInputStream.java  |  108 +
 src/jline/src/main/java/jline/ConsoleRunner.java   |   86 +
 src/jline/src/main/java/jline/CursorBuffer.java    |  104 +
 .../src/main/java/jline/FileNameCompletor.java     |  133 +
 src/jline/src/main/java/jline/History.java         |  255 +
 src/jline/src/main/java/jline/MultiCompletor.java  |   83 +
 src/jline/src/main/java/jline/NullCompletor.java   |   27 +
 src/jline/src/main/java/jline/SimpleCompletor.java |  194 +
 src/jline/src/main/java/jline/Terminal.java        |  180 +
 src/jline/src/main/java/jline/UnixTerminal.java    |  431 ++
 .../src/main/java/jline/UnsupportedTerminal.java   |   98 +
 src/jline/src/main/java/jline/WindowsTerminal.java |  513 ++
 src/jline/src/main/java/jline/package.html         |    9 +
 src/jline/src/main/native/Makefile                 |    8 +
 src/jline/src/main/native/jline_WindowsTerminal.c  |   57 +
 src/jline/src/main/native/jline_WindowsTerminal.h  |   68 +
 .../CandidateListCompletionHandler.properties      |    5 +
 src/jline/src/main/resources/jline/jline32.dll     |  Bin 0 -> 16069 bytes
 src/jline/src/main/resources/jline/jline64.dll     |  Bin 0 -> 48128 bytes
 .../main/resources/jline/keybindings.properties    |   62 +
 .../resources/jline/windowsbindings.properties     |   65 +
 src/jline/src/site/apt/building.apt                |   39 +
 src/jline/src/site/apt/downloads.apt               |   39 +
 src/jline/src/site/docbook/index.xml               |  492 ++
 src/jline/src/site/fml/faq.fml                     |   26 +
 src/jline/src/site/resources/css/site.css          |  311 +
 src/jline/src/site/resources/images/collapsed.png  |  Bin 0 -> 222 bytes
 src/jline/src/site/resources/images/dotted.png     |  Bin 0 -> 190 bytes
 src/jline/src/site/resources/images/expanded.png   |  Bin 0 -> 198 bytes
 src/jline/src/site/resources/images/external.png   |  Bin 0 -> 223 bytes
 .../src/site/resources/images/ico_file_pdf.png     |  Bin 0 -> 280 bytes
 src/jline/src/site/resources/images/logo.jpg       |  Bin 0 -> 4121 bytes
 src/jline/src/site/resources/images/newwindow.png  |  Bin 0 -> 224 bytes
 src/jline/src/site/site.xml                        |   40 +
 .../src/test/java/jline/ConsoleReaderTest.java     |  162 +
 src/jline/src/test/java/jline/JLineTestCase.java   |  140 +
 src/jline/src/test/java/jline/TestCompletion.java  |   71 +
 src/jline/src/test/java/jline/TestEditLine.java    |  160 +
 src/jline/src/test/java/jline/TestHistory.java     |   76 +
 src/jline/src/test/java/jline/example/Example.java |   97 +
 .../test/java/jline/example/PasswordReader.java    |   32 +
 .../src/test/resources/jline/example/english.gz    |  Bin 0 -> 130975 bytes
 src/jvm14-actors/scala/actors/Actor.scala          |  970 ----
 .../scala/actors/FJTaskScheduler2.scala            |  179 -
 src/jvm14-library/scala/BigDecimal.scala           |  269 -
 src/jvm14-library/scala/runtime/RichString.scala   |  266 -
 .../scala/util/parsing/json/JSON.scala             |   95 -
 .../scala/util/parsing/json/Parser.scala           |   50 -
 src/library/scala/Annotation.scala                 |    4 +-
 src/library/scala/Application.scala                |   42 +-
 src/library/scala/Array.scala                      |  755 +--
 src/library/scala/Attribute.scala                  |   22 -
 src/library/scala/BigDecimal.scala                 |  267 -
 src/library/scala/BigInt.scala                     |  366 --
 src/library/scala/BufferedIterator.scala           |  194 -
 src/library/scala/ByNameFunction.scala             |   26 -
 src/library/scala/Cell.scala                       |    3 +-
 src/library/scala/ClassfileAnnotation.scala        |    6 +-
 src/library/scala/ClassfileAttribute.scala         |   26 -
 src/library/scala/Collection.scala                 |   47 -
 src/library/scala/CollectionProxy.scala            |   55 -
 src/library/scala/Console.scala                    |  129 +-
 src/library/scala/CountedIterator.scala            |   13 +-
 src/library/scala/Either.scala                     |  118 +-
 src/library/scala/Enumeration.scala                |  424 +-
 src/library/scala/Equals.scala                     |   27 +
 src/library/scala/Equiv.scala                      |   41 -
 src/library/scala/Function.scala                   |   18 +-
 src/library/scala/Function0.scala                  |   15 +-
 src/library/scala/Function1.scala                  |   22 +-
 src/library/scala/Function10.scala                 |   27 +-
 src/library/scala/Function11.scala                 |   27 +-
 src/library/scala/Function12.scala                 |   27 +-
 src/library/scala/Function13.scala                 |   27 +-
 src/library/scala/Function14.scala                 |   27 +-
 src/library/scala/Function15.scala                 |   27 +-
 src/library/scala/Function16.scala                 |   27 +-
 src/library/scala/Function17.scala                 |   27 +-
 src/library/scala/Function18.scala                 |   27 +-
 src/library/scala/Function19.scala                 |   27 +-
 src/library/scala/Function2.scala                  |   35 +-
 src/library/scala/Function20.scala                 |   27 +-
 src/library/scala/Function21.scala                 |   27 +-
 src/library/scala/Function22.scala                 |   27 +-
 src/library/scala/Function3.scala                  |   27 +-
 src/library/scala/Function4.scala                  |   27 +-
 src/library/scala/Function5.scala                  |   27 +-
 src/library/scala/Function6.scala                  |   27 +-
 src/library/scala/Function7.scala                  |   27 +-
 src/library/scala/Function8.scala                  |   27 +-
 src/library/scala/Function9.scala                  |   27 +-
 src/library/scala/Immutable.scala                  |   18 +
 src/library/scala/Iterable.scala                   |  516 --
 src/library/scala/IterableProxy.scala              |   79 -
 src/library/scala/Iterator.scala                   |  765 ---
 src/library/scala/List.scala                       | 1407 -----
 src/library/scala/LowPriorityImplicits.scala       |   60 +
 src/library/scala/MatchError.scala                 |    6 +-
 src/library/scala/Math.scala                       |  209 +-
 src/library/scala/MathCommon.scala                 |  143 +
 src/library/scala/Mutable.scala                    |   18 +
 src/library/scala/NotDefinedError.scala            |   12 +-
 src/library/scala/NotNull.scala                    |    9 +-
 src/library/scala/Option.scala                     |  216 +-
 src/library/scala/Ordered.scala                    |   53 -
 src/library/scala/Ordering.scala                   |   74 -
 src/library/scala/PartialFunction.scala            |   82 +-
 src/library/scala/PartialOrdering.scala            |   62 -
 src/library/scala/PartiallyOrdered.scala           |   50 -
 src/library/scala/Predef.scala                     |  388 +-
 src/library/scala/Product.scala                    |   20 +-
 src/library/scala/Product1.scala                   |   19 +-
 src/library/scala/Product10.scala                  |   35 +-
 src/library/scala/Product11.scala                  |   37 +-
 src/library/scala/Product12.scala                  |   39 +-
 src/library/scala/Product13.scala                  |   41 +-
 src/library/scala/Product14.scala                  |   43 +-
 src/library/scala/Product15.scala                  |   45 +-
 src/library/scala/Product16.scala                  |   47 +-
 src/library/scala/Product17.scala                  |   49 +-
 src/library/scala/Product18.scala                  |   51 +-
 src/library/scala/Product19.scala                  |   53 +-
 src/library/scala/Product2.scala                   |   21 +-
 src/library/scala/Product20.scala                  |   55 +-
 src/library/scala/Product21.scala                  |   57 +-
 src/library/scala/Product22.scala                  |   59 +-
 src/library/scala/Product3.scala                   |   21 +-
 src/library/scala/Product4.scala                   |   23 +-
 src/library/scala/Product5.scala                   |   25 +-
 src/library/scala/Product6.scala                   |   27 +-
 src/library/scala/Product7.scala                   |   29 +-
 src/library/scala/Product8.scala                   |   31 +-
 src/library/scala/Product9.scala                   |   33 +-
 src/library/scala/Proxy.scala                      |   14 +-
 src/library/scala/Random.scala                     |   75 -
 src/library/scala/RandomAccessSeq.scala            |  245 -
 src/library/scala/RandomAccessSeqProxy.scala       |   37 -
 src/library/scala/Range.scala                      |  109 -
 src/library/scala/Responder.scala                  |    8 +-
 src/library/scala/ScalaObject.scala                |   15 +-
 src/library/scala/Seq.scala                        |  511 --
 src/library/scala/SeqProxy.scala                   |   85 -
 src/library/scala/SerialVersionUID.scala           |    9 +-
 src/library/scala/StaticAnnotation.scala           |    4 +-
 src/library/scala/StaticAttribute.scala            |   25 -
 src/library/scala/Stream.scala                     |  518 --
 src/library/scala/StringBuilder.scala              |  952 ----
 src/library/scala/Symbol.scala                     |   76 +-
 src/library/scala/Tuple1.scala                     |   21 +-
 src/library/scala/Tuple10.scala                    |   21 +-
 src/library/scala/Tuple11.scala                    |   21 +-
 src/library/scala/Tuple12.scala                    |   22 +-
 src/library/scala/Tuple13.scala                    |   22 +-
 src/library/scala/Tuple14.scala                    |   22 +-
 src/library/scala/Tuple15.scala                    |   22 +-
 src/library/scala/Tuple16.scala                    |   22 +-
 src/library/scala/Tuple17.scala                    |   22 +-
 src/library/scala/Tuple18.scala                    |   22 +-
 src/library/scala/Tuple19.scala                    |   22 +-
 src/library/scala/Tuple2.scala                     |  119 +-
 src/library/scala/Tuple20.scala                    |   22 +-
 src/library/scala/Tuple21.scala                    |   22 +-
 src/library/scala/Tuple22.scala                    |   22 +-
 src/library/scala/Tuple3.scala                     |  138 +-
 src/library/scala/Tuple4.scala                     |   21 +-
 src/library/scala/Tuple5.scala                     |   21 +-
 src/library/scala/Tuple6.scala                     |   21 +-
 src/library/scala/Tuple7.scala                     |   21 +-
 src/library/scala/Tuple8.scala                     |   21 +-
 src/library/scala/Tuple9.scala                     |   21 +-
 src/library/scala/TypeConstraint.scala             |    4 +-
 src/library/scala/UninitializedError.scala         |    6 +-
 src/library/scala/UninitializedFieldError.scala    |   11 +-
 src/library/scala/annotation/elidable.scala        |   68 +
 .../scala/annotation/implicitNotFound.scala        |   18 +
 src/library/scala/annotation/migration.scala       |   28 +
 src/library/scala/annotation/switch.scala          |   38 +
 src/library/scala/annotation/tailrec.scala         |   18 +
 .../scala/annotation/target/beanGetter.scala       |   51 +
 .../scala/annotation/target/beanSetter.scala       |   51 +
 src/library/scala/annotation/target/field.scala    |   51 +
 src/library/scala/annotation/target/getter.scala   |   51 +
 src/library/scala/annotation/target/param.scala    |   51 +
 src/library/scala/annotation/target/setter.scala   |   51 +
 .../annotation/unchecked/uncheckedStable.scala     |    4 +-
 .../annotation/unchecked/uncheckedVariance.scala   |    4 +-
 src/library/scala/cloneable.scala                  |    3 +-
 src/library/scala/collection/BitSet.scala          |  163 +-
 src/library/scala/collection/BitSetLike.scala      |  194 +
 .../scala/collection/BufferedIterator.scala        |   27 +
 src/library/scala/collection/DefaultMap.scala      |   51 +
 src/library/scala/collection/IndexedSeq.scala      |   34 +
 src/library/scala/collection/IndexedSeqLike.scala  |   97 +
 .../scala/collection/IndexedSeqOptimized.scala     |  287 +
 src/library/scala/collection/Iterable.scala        |   59 +
 src/library/scala/collection/IterableLike.scala    |  394 ++
 src/library/scala/collection/IterableProxy.scala   |   24 +
 .../scala/collection/IterableProxyLike.scala       |   40 +
 src/library/scala/collection/IterableView.scala    |   31 +
 .../scala/collection/IterableViewLike.scala        |  126 +
 src/library/scala/collection/Iterator.scala        | 1066 ++++
 src/library/scala/collection/JavaConversions.scala |  927 +++
 src/library/scala/collection/JavaConverters.scala  |  456 ++
 src/library/scala/collection/LinearSeq.scala       |   33 +
 src/library/scala/collection/LinearSeqLike.scala   |   61 +
 .../scala/collection/LinearSeqOptimized.scala      |  294 +
 src/library/scala/collection/Map.scala             |  212 +-
 src/library/scala/collection/MapLike.scala         |  361 ++
 src/library/scala/collection/MapProxy.scala        |   31 +-
 src/library/scala/collection/MapProxyLike.scala    |   50 +
 src/library/scala/collection/Ranged.scala          |   61 -
 .../scala/collection/RollbackIterator.scala        |   87 -
 src/library/scala/collection/Seq.scala             |   46 +
 src/library/scala/collection/SeqLike.scala         |  897 +++
 src/library/scala/collection/SeqProxy.scala        |   20 +
 src/library/scala/collection/SeqProxyLike.scala    |   73 +
 src/library/scala/collection/SeqView.scala         |   32 +
 src/library/scala/collection/SeqViewLike.scala     |  228 +
 src/library/scala/collection/Set.scala             |  143 +-
 src/library/scala/collection/SetLike.scala         |  210 +
 src/library/scala/collection/SetProxy.scala        |   15 +-
 src/library/scala/collection/SetProxyLike.scala    |   38 +
 src/library/scala/collection/Sorted.scala          |   70 -
 src/library/scala/collection/SortedMap.scala       |   57 +-
 src/library/scala/collection/SortedMapLike.scala   |   75 +
 src/library/scala/collection/SortedSet.scala       |   48 +-
 src/library/scala/collection/SortedSetLike.scala   |   43 +
 src/library/scala/collection/Traversable.scala     |   97 +
 src/library/scala/collection/TraversableLike.scala |  839 +++
 src/library/scala/collection/TraversableOnce.scala |  538 ++
 .../scala/collection/TraversableProxy.scala        |   23 +
 .../scala/collection/TraversableProxyLike.scala    |   98 +
 src/library/scala/collection/TraversableView.scala |   39 +
 .../scala/collection/TraversableViewLike.scala     |  225 +
 src/library/scala/collection/generic/Addable.scala |   55 +
 .../scala/collection/generic/BitSetFactory.scala   |   38 +
 .../scala/collection/generic/CanBuildFrom.scala    |   46 +
 .../scala/collection/generic/FilterMonadic.scala   |   11 +
 .../collection/generic/GenericCompanion.scala      |   50 +
 .../collection/generic/GenericSetTemplate.scala    |   20 +
 .../generic/GenericTraversableTemplate.scala       |  124 +
 .../scala/collection/generic/Growable.scala        |   54 +
 .../scala/collection/generic/HasNewBuilder.scala   |   16 +
 .../collection/generic/ImmutableMapFactory.scala   |   18 +
 .../collection/generic/ImmutableSetFactory.scala   |   18 +
 .../generic/ImmutableSortedMapFactory.scala        |   26 +
 .../generic/ImmutableSortedSetFactory.scala        |   26 +
 .../collection/generic/IterableForwarder.scala     |   45 +
 .../scala/collection/generic/MapFactory.scala      |   62 +
 .../collection/generic/MutableMapFactory.scala     |   29 +
 .../collection/generic/MutableSetFactory.scala     |   18 +
 .../scala/collection/generic/SeqFactory.scala      |   26 +
 .../scala/collection/generic/SeqForwarder.scala    |   59 +
 .../scala/collection/generic/SetFactory.scala      |   44 +
 .../scala/collection/generic/Shrinkable.scala      |   54 +
 src/library/scala/collection/generic/Sorted.scala  |  101 +
 .../collection/generic/SortedMapFactory.scala      |   35 +
 .../collection/generic/SortedSetFactory.scala      |   35 +
 .../scala/collection/generic/Subtractable.scala    |   59 +
 .../collection/generic/TraversableFactory.scala    |  242 +
 .../collection/generic/TraversableForwarder.scala  |   88 +
 src/library/scala/collection/generic/package.scala |    6 +
 .../scala/collection/immutable/BitSet.scala        |  126 +-
 .../scala/collection/immutable/DefaultMap.scala    |   65 +
 .../scala/collection/immutable/EmptyMap.scala      |   39 -
 .../scala/collection/immutable/EmptySet.scala      |   36 -
 .../scala/collection/immutable/HashMap.scala       |  467 +-
 .../scala/collection/immutable/HashSet.scala       |  420 +-
 .../collection/immutable/ImmutableIterator.scala   |  111 -
 .../scala/collection/immutable/IndexedSeq.scala    |   40 +
 .../scala/collection/immutable/IntMap.scala        |  166 +-
 .../scala/collection/immutable/Iterable.scala      |   37 +
 .../scala/collection/immutable/LinearSeq.scala     |   36 +
 src/library/scala/collection/immutable/List.scala  |  791 +++
 .../scala/collection/immutable/ListMap.scala       |   96 +-
 .../scala/collection/immutable/ListSet.scala       |   91 +-
 .../scala/collection/immutable/LongMap.scala       |  145 +-
 src/library/scala/collection/immutable/Map.scala   |  365 +-
 src/library/scala/collection/immutable/Map1.scala  |   43 -
 src/library/scala/collection/immutable/Map2.scala  |   48 -
 src/library/scala/collection/immutable/Map3.scala  |   51 -
 src/library/scala/collection/immutable/Map4.scala  |   52 -
 .../scala/collection/immutable/MapLike.scala       |  127 +
 .../scala/collection/immutable/MapProxy.scala      |   40 +
 .../scala/collection/immutable/NumericRange.scala  |  230 +
 .../scala/collection/immutable/PagedSeq.scala      |   70 +-
 src/library/scala/collection/immutable/Queue.scala |  152 +-
 src/library/scala/collection/immutable/Range.scala |  347 ++
 .../scala/collection/immutable/RedBlack.scala      |  137 +-
 src/library/scala/collection/immutable/Seq.scala   |   39 +
 src/library/scala/collection/immutable/Set.scala   |  305 +-
 src/library/scala/collection/immutable/Set1.scala  |   42 -
 src/library/scala/collection/immutable/Set2.scala  |   43 -
 src/library/scala/collection/immutable/Set3.scala  |   44 -
 src/library/scala/collection/immutable/Set4.scala  |   45 -
 .../scala/collection/immutable/SetProxy.scala      |   32 +
 .../scala/collection/immutable/SortedMap.scala     |  115 +-
 .../scala/collection/immutable/SortedSet.scala     |   37 +-
 src/library/scala/collection/immutable/Stack.scala |  205 +-
 .../scala/collection/immutable/Stream.scala        |  679 +++
 .../scala/collection/immutable/StringLike.scala    |  274 +
 .../scala/collection/immutable/StringOps.scala     |   51 +
 .../scala/collection/immutable/Traversable.scala   |   36 +
 src/library/scala/collection/immutable/Tree.scala  |  439 --
 .../scala/collection/immutable/TreeHashMap.scala   |   85 +-
 .../scala/collection/immutable/TreeMap.scala       |  149 +-
 .../collection/immutable/TreeMap.scala.disabled    |  101 -
 .../scala/collection/immutable/TreeSet.scala       |  112 +-
 .../collection/immutable/UnbalancedTreeMap.scala   |  143 -
 .../scala/collection/immutable/Vector.scala        | 1178 ++++
 .../scala/collection/immutable/WrappedString.scala |   50 +
 .../collection/interfaces/IterableMethods.scala    |   36 +
 .../scala/collection/interfaces/MapMethods.scala   |   44 +
 .../scala/collection/interfaces/SeqMethods.scala   |   57 +
 .../scala/collection/interfaces/SetMethods.scala   |   60 +
 .../collection/interfaces/TraversableMethods.scala |  109 +
 .../interfaces/TraversableOnceMethods.scala        |   69 +
 src/library/scala/collection/jcl/ArrayList.scala   |   21 -
 src/library/scala/collection/jcl/Buffer.scala      |  229 -
 .../scala/collection/jcl/BufferIterator.scala      |   31 -
 .../scala/collection/jcl/BufferWrapper.scala       |   52 -
 src/library/scala/collection/jcl/Collection.scala  |   67 -
 .../scala/collection/jcl/CollectionWrapper.scala   |   43 -
 src/library/scala/collection/jcl/Conversions.scala |   17 -
 src/library/scala/collection/jcl/HashMap.scala     |   21 -
 src/library/scala/collection/jcl/HashSet.scala     |   21 -
 src/library/scala/collection/jcl/Hashtable.scala   |   22 -
 .../scala/collection/jcl/IdentityHashMap.scala     |   24 -
 .../scala/collection/jcl/IterableWrapper.scala     |   32 -
 .../scala/collection/jcl/LinkedHashMap.scala       |   22 -
 .../scala/collection/jcl/LinkedHashSet.scala       |   22 -
 src/library/scala/collection/jcl/LinkedList.scala  |   32 -
 src/library/scala/collection/jcl/Map.scala         |  129 -
 src/library/scala/collection/jcl/MapWrapper.scala  |   76 -
 .../scala/collection/jcl/MutableIterable.scala     |  110 -
 .../scala/collection/jcl/MutableIterator.scala     |   70 -
 src/library/scala/collection/jcl/MutableSeq.scala  |  123 -
 src/library/scala/collection/jcl/Ranged.scala      |   54 -
 src/library/scala/collection/jcl/SeqIterator.scala |   58 -
 src/library/scala/collection/jcl/Set.scala         |   72 -
 src/library/scala/collection/jcl/SetWrapper.scala  |   22 -
 src/library/scala/collection/jcl/Sorted.scala      |   46 -
 src/library/scala/collection/jcl/SortedMap.scala   |  103 -
 .../scala/collection/jcl/SortedMapWrapper.scala    |   39 -
 src/library/scala/collection/jcl/SortedSet.scala   |   99 -
 .../scala/collection/jcl/SortedSetWrapper.scala    |   39 -
 src/library/scala/collection/jcl/Tests.scala       |   79 -
 src/library/scala/collection/jcl/TreeMap.scala     |   24 -
 src/library/scala/collection/jcl/TreeSet.scala     |   26 -
 src/library/scala/collection/jcl/WeakHashMap.scala |   31 -
 .../scala/collection/mutable/AddingBuilder.scala   |   36 +
 .../scala/collection/mutable/ArrayBuffer.scala     |  239 +-
 .../scala/collection/mutable/ArrayBuilder.scala    |  682 +++
 .../scala/collection/mutable/ArrayLike.scala       |   67 +
 .../scala/collection/mutable/ArrayOps.scala        |  219 +
 .../scala/collection/mutable/ArraySeq.scala        |   96 +
 .../scala/collection/mutable/ArrayStack.scala      |  240 +-
 src/library/scala/collection/mutable/BitSet.scala  |  158 +-
 src/library/scala/collection/mutable/Buffer.scala  |  294 +-
 .../scala/collection/mutable/BufferLike.scala      |  343 ++
 .../scala/collection/mutable/BufferProxy.scala     |  106 +-
 src/library/scala/collection/mutable/Builder.scala |  106 +
 .../scala/collection/mutable/Cloneable.scala       |   23 +
 .../collection/mutable/CloneableCollection.scala   |   13 +-
 .../scala/collection/mutable/ConcurrentMap.scala   |   68 +
 .../scala/collection/mutable/DefaultEntry.scala    |   11 +-
 .../scala/collection/mutable/DefaultMapModel.scala |   30 +-
 .../collection/mutable/DoubleLinkedList.scala      |  111 +-
 .../collection/mutable/DoubleLinkedListLike.scala  |   58 +
 .../scala/collection/mutable/FlatHashTable.scala   |   89 +-
 .../scala/collection/mutable/GrowingBuilder.scala  |   38 +
 .../scala/collection/mutable/HashEntry.scala       |   17 +
 src/library/scala/collection/mutable/HashMap.scala |  122 +-
 src/library/scala/collection/mutable/HashSet.scala |   76 +-
 .../scala/collection/mutable/HashTable.scala       |  158 +-
 src/library/scala/collection/mutable/History.scala |   58 +-
 .../collection/mutable/ImmutableMapAdaptor.scala   |   43 +-
 .../collection/mutable/ImmutableSetAdaptor.scala   |   24 +-
 .../scala/collection/mutable/IndexedSeq.scala      |   36 +
 .../scala/collection/mutable/IndexedSeqLike.scala  |   73 +
 .../collection/mutable/IndexedSeqOptimized.scala   |   20 +
 .../scala/collection/mutable/IndexedSeqView.scala  |  115 +
 .../scala/collection/mutable/Iterable.scala        |   32 +
 .../scala/collection/mutable/JavaMapAdaptor.scala  |   69 -
 .../scala/collection/mutable/JavaSetAdaptor.scala  |   47 -
 .../scala/collection/mutable/LazyBuilder.scala     |   30 +
 .../scala/collection/mutable/LinearSeq.scala       |   38 +
 .../scala/collection/mutable/LinkedEntry.scala     |   23 +
 .../scala/collection/mutable/LinkedHashMap.scala   |  157 +-
 .../scala/collection/mutable/LinkedHashSet.scala   |  100 +-
 .../scala/collection/mutable/LinkedList.scala      |   81 +-
 .../scala/collection/mutable/LinkedListLike.scala  |  115 +
 .../scala/collection/mutable/ListBuffer.scala      |  430 +-
 src/library/scala/collection/mutable/ListMap.scala |   67 +
 .../scala/collection/mutable/Location.scala        |   29 -
 src/library/scala/collection/mutable/Map.scala     |  293 +-
 .../scala/collection/mutable/MapBuilder.scala      |   36 +
 src/library/scala/collection/mutable/MapLike.scala |  246 +
 .../scala/collection/mutable/MapProxy.scala        |   65 +-
 src/library/scala/collection/mutable/Message.scala |   82 -
 .../scala/collection/mutable/MultiMap.scala        |   85 +-
 .../scala/collection/mutable/MutableList.scala     |  130 +-
 .../collection/mutable/ObservableBuffer.scala      |   56 +-
 .../scala/collection/mutable/ObservableMap.scala   |   70 +-
 .../scala/collection/mutable/ObservableSet.scala   |   43 +-
 .../scala/collection/mutable/OpenHashMap.scala     |  154 +-
 .../scala/collection/mutable/PriorityQueue.scala   |  277 +-
 .../collection/mutable/PriorityQueueProxy.scala    |   34 +-
 .../scala/collection/mutable/Publisher.scala       |   68 +-
 src/library/scala/collection/mutable/Queue.scala   |  184 +-
 .../scala/collection/mutable/QueueProxy.scala      |   33 +-
 .../scala/collection/mutable/ResizableArray.scala  |   94 +-
 .../collection/mutable/RevertableHistory.scala     |   33 -
 .../collection/mutable/RevertibleHistory.scala     |   37 +
 .../scala/collection/mutable/Scriptable.scala      |   26 -
 src/library/scala/collection/mutable/Seq.scala     |   50 +
 src/library/scala/collection/mutable/Set.scala     |  224 +-
 .../scala/collection/mutable/SetBuilder.scala      |   23 +
 src/library/scala/collection/mutable/SetLike.scala |  236 +
 .../scala/collection/mutable/SetProxy.scala        |   50 +-
 .../collection/mutable/SingleLinkedList.scala      |   62 -
 src/library/scala/collection/mutable/Stack.scala   |  132 +-
 .../scala/collection/mutable/StackProxy.scala      |   41 +-
 .../scala/collection/mutable/StringBuilder.scala   |  433 ++
 .../scala/collection/mutable/Subscriber.scala      |   16 +-
 .../collection/mutable/SynchronizedBuffer.scala    |   94 +-
 .../scala/collection/mutable/SynchronizedMap.scala |  180 +-
 .../mutable/SynchronizedPriorityQueue.scala        |   60 +-
 .../collection/mutable/SynchronizedQueue.scala     |   39 +-
 .../scala/collection/mutable/SynchronizedSet.scala |   58 +-
 .../collection/mutable/SynchronizedStack.scala     |   62 +-
 .../scala/collection/mutable/Traversable.scala     |   37 +
 .../scala/collection/mutable/Undoable.scala        |   20 +-
 .../scala/collection/mutable/WeakHashMap.scala     |   51 +
 .../scala/collection/mutable/WrappedArray.scala    |  174 +
 .../collection/mutable/WrappedArrayBuilder.scala   |   70 +
 src/library/scala/collection/package.scala         |   79 +
 .../readme-if-you-want-to-add-something.txt        |   50 +
 src/library/scala/collection/script/Location.scala |   27 +
 src/library/scala/collection/script/Message.scala  |   85 +
 .../scala/collection/script/Scriptable.scala       |   26 +
 src/library/scala/compat/Platform.scala            |   49 +-
 src/library/scala/concurrent/Channel.scala         |   23 +-
 src/library/scala/concurrent/DelayedLazyVal.scala  |   48 +
 .../scala/concurrent/FutureTaskRunner.scala        |   17 +
 src/library/scala/concurrent/JavaConversions.scala |   50 +
 src/library/scala/concurrent/Lock.scala            |    5 +-
 src/library/scala/concurrent/MailBox.scala         |    3 +-
 src/library/scala/concurrent/ManagedBlocker.scala  |   34 +
 src/library/scala/concurrent/SyncChannel.scala     |    5 +-
 src/library/scala/concurrent/SyncVar.scala         |   36 +-
 src/library/scala/concurrent/TIMEOUT.scala         |    5 +-
 src/library/scala/concurrent/TaskRunner.scala      |   27 +
 src/library/scala/concurrent/TaskRunners.scala     |   37 +
 .../scala/concurrent/ThreadPoolRunner.scala        |   51 +
 src/library/scala/concurrent/ThreadRunner.scala    |   59 +
 src/library/scala/concurrent/jolib.scala           |   80 -
 src/library/scala/concurrent/ops.scala             |   50 +-
 src/library/scala/concurrent/pilib.scala           |    6 +-
 src/library/scala/deprecated.scala                 |   14 +-
 src/library/scala/inline.scala                     |    3 +-
 src/library/scala/io/BufferedSource.scala          |   85 +-
 src/library/scala/io/BytePickle.scala              |   28 +-
 src/library/scala/io/Codec.scala                   |  120 +
 src/library/scala/io/Position.scala                |   23 +-
 src/library/scala/io/Source.scala                  |  496 +-
 src/library/scala/io/UTF8Codec.scala               |  129 +-
 src/library/scala/math/BigDecimal.scala            |  405 ++
 src/library/scala/math/BigInt.scala                |  376 ++
 src/library/scala/math/Equiv.scala                 |   45 +
 src/library/scala/math/Fractional.scala            |   24 +
 src/library/scala/math/Integral.scala              |   26 +
 src/library/scala/math/Numeric.scala               |  202 +
 src/library/scala/math/Ordered.scala               |   56 +
 src/library/scala/math/Ordering.scala              |  376 ++
 src/library/scala/math/PartialOrdering.scala       |   85 +
 src/library/scala/math/PartiallyOrdered.scala      |   49 +
 src/library/scala/math/ScalaNumber.java            |   21 +
 .../scala/math/ScalaNumericConversions.scala       |   60 +
 src/library/scala/math/package.scala               |   30 +
 src/library/scala/mobile/Code.scala                |   29 +-
 src/library/scala/mobile/Location.scala            |    3 +-
 src/library/scala/native.scala                     |   23 +-
 src/library/scala/noinline.scala                   |    4 +-
 src/library/scala/package.scala                    |  157 +
 src/library/scala/ref/PhantomReference.scala       |   12 +-
 src/library/scala/ref/Reference.scala              |    6 +-
 src/library/scala/ref/ReferenceQueue.scala         |   18 +-
 src/library/scala/ref/ReferenceWrapper.scala       |   15 +-
 src/library/scala/ref/SoftReference.scala          |   14 +-
 src/library/scala/ref/WeakReference.scala          |   12 +-
 src/library/scala/reflect/BeanDescription.scala    |    3 +-
 src/library/scala/reflect/BeanDisplayName.scala    |    3 +-
 src/library/scala/reflect/BeanInfo.scala           |    7 +-
 src/library/scala/reflect/BeanInfoSkip.scala       |    5 +-
 src/library/scala/reflect/BeanProperty.scala       |   19 +-
 .../scala/reflect/BooleanBeanProperty.scala        |   23 +
 src/library/scala/reflect/ClassManifest.scala      |  232 +
 src/library/scala/reflect/Code.scala               |    7 +-
 src/library/scala/reflect/Manifest.scala           |  295 +-
 src/library/scala/reflect/NameTransformer.scala    |  154 +
 src/library/scala/reflect/NoManifest.scala         |   18 +
 src/library/scala/reflect/OptManifest.scala        |   22 +
 src/library/scala/reflect/Print.scala              |   13 +-
 src/library/scala/reflect/ScalaBeanInfo.scala      |    3 +-
 src/library/scala/reflect/ScalaLongSignature.java  |   13 +
 src/library/scala/reflect/ScalaSignature.java      |   13 +
 src/library/scala/reflect/Symbol.scala             |    5 +-
 src/library/scala/reflect/Tree.scala               |    5 +-
 src/library/scala/reflect/Type.scala               |    9 +-
 .../scala/reflect/generic/AnnotationInfos.scala    |   42 +
 src/library/scala/reflect/generic/ByteCodecs.scala |  224 +
 src/library/scala/reflect/generic/Constants.scala  |  235 +
 src/library/scala/reflect/generic/Flags.scala      |  199 +
 src/library/scala/reflect/generic/Names.scala      |   21 +
 .../scala/reflect/generic/PickleBuffer.scala       |  187 +
 .../scala/reflect/generic/PickleFormat.scala       |  223 +
 src/library/scala/reflect/generic/Scopes.scala     |   15 +
 .../reflect/generic/StandardDefinitions.scala      |   66 +
 src/library/scala/reflect/generic/StdNames.scala   |   26 +
 src/library/scala/reflect/generic/Symbols.scala    |  195 +
 src/library/scala/reflect/generic/Trees.scala      |  739 +++
 src/library/scala/reflect/generic/Types.scala      |  156 +
 src/library/scala/reflect/generic/UnPickler.scala  |  774 +++
 src/library/scala/reflect/generic/Universe.scala   |   16 +
 src/library/scala/remote.scala                     |    8 +-
 src/library/scala/runtime/AbstractFunction0.scala  |   19 +
 src/library/scala/runtime/AbstractFunction1.scala  |   18 +
 src/library/scala/runtime/AbstractFunction10.scala |   18 +
 src/library/scala/runtime/AbstractFunction11.scala |   18 +
 src/library/scala/runtime/AbstractFunction12.scala |   18 +
 src/library/scala/runtime/AbstractFunction13.scala |   18 +
 src/library/scala/runtime/AbstractFunction14.scala |   18 +
 src/library/scala/runtime/AbstractFunction15.scala |   18 +
 src/library/scala/runtime/AbstractFunction16.scala |   18 +
 src/library/scala/runtime/AbstractFunction17.scala |   18 +
 src/library/scala/runtime/AbstractFunction18.scala |   18 +
 src/library/scala/runtime/AbstractFunction19.scala |   18 +
 src/library/scala/runtime/AbstractFunction2.scala  |   18 +
 src/library/scala/runtime/AbstractFunction20.scala |   18 +
 src/library/scala/runtime/AbstractFunction21.scala |   18 +
 src/library/scala/runtime/AbstractFunction22.scala |   18 +
 src/library/scala/runtime/AbstractFunction3.scala  |   18 +
 src/library/scala/runtime/AbstractFunction4.scala  |   18 +
 src/library/scala/runtime/AbstractFunction5.scala  |   18 +
 src/library/scala/runtime/AbstractFunction6.scala  |   18 +
 src/library/scala/runtime/AbstractFunction7.scala  |   18 +
 src/library/scala/runtime/AbstractFunction8.scala  |   18 +
 src/library/scala/runtime/AbstractFunction9.scala  |   18 +
 src/library/scala/runtime/AnyValCompanion.scala    |   86 +
 src/library/scala/runtime/ArrayRuntime.java        |   16 +
 src/library/scala/runtime/BooleanRef.java          |    3 +-
 src/library/scala/runtime/Boxed.scala              |   17 +
 src/library/scala/runtime/BoxedAnyArray.scala      |  320 --
 src/library/scala/runtime/BoxedArray.scala         |  187 -
 src/library/scala/runtime/BoxedBooleanArray.scala  |   65 -
 src/library/scala/runtime/BoxedByteArray.scala     |   65 -
 src/library/scala/runtime/BoxedCharArray.scala     |   66 -
 src/library/scala/runtime/BoxedDoubleArray.scala   |   65 -
 src/library/scala/runtime/BoxedFloatArray.scala    |   65 -
 src/library/scala/runtime/BoxedIntArray.scala      |   67 -
 src/library/scala/runtime/BoxedLongArray.scala     |   65 -
 src/library/scala/runtime/BoxedObjectArray.scala   |   72 -
 src/library/scala/runtime/BoxedShortArray.scala    |   65 -
 src/library/scala/runtime/BoxedUnit.java           |    5 +-
 src/library/scala/runtime/BoxesRunTime.java        |  719 +--
 src/library/scala/runtime/ByteRef.java             |    5 +-
 src/library/scala/runtime/CharRef.java             |    5 +-
 src/library/scala/runtime/DoubleRef.java           |    5 +-
 .../scala/runtime/DynamicDispatch.java-notyet      |   42 +
 src/library/scala/runtime/ExceptionHandling.java   |   26 -
 src/library/scala/runtime/FloatRef.java            |    5 +-
 src/library/scala/runtime/IntRef.java              |    5 +-
 src/library/scala/runtime/LongRef.java             |    5 +-
 src/library/scala/runtime/MethodCache.scala        |   83 +
 .../scala/runtime/NonLocalReturnControl.scala      |   15 +
 .../scala/runtime/NonLocalReturnException.scala    |   23 -
 src/library/scala/runtime/Nothing$.scala           |    3 +-
 src/library/scala/runtime/Null$.scala              |    3 +-
 src/library/scala/runtime/ObjectRef.java           |    3 +-
 src/library/scala/runtime/RichBoolean.scala        |    3 +-
 src/library/scala/runtime/RichByte.scala           |    3 +-
 src/library/scala/runtime/RichChar.scala           |   68 +-
 src/library/scala/runtime/RichDouble.scala         |   41 +-
 src/library/scala/runtime/RichException.scala      |   15 +-
 src/library/scala/runtime/RichFloat.scala          |   21 +-
 src/library/scala/runtime/RichInt.scala            |   19 +-
 src/library/scala/runtime/RichLong.scala           |   17 +-
 src/library/scala/runtime/RichShort.scala          |    3 +-
 src/library/scala/runtime/RichString.scala         |  262 -
 src/library/scala/runtime/RichStringBuilder.scala  |   57 -
 src/library/scala/runtime/RichUnit.scala           |   22 +
 src/library/scala/runtime/ScalaRunTime.scala       |  317 +-
 src/library/scala/runtime/ShortRef.java            |    4 +-
 src/library/scala/runtime/StreamCons.scala         |   17 -
 src/library/scala/runtime/StringAdd.scala          |    6 +-
 src/library/scala/runtime/TraitSetter.java         |    6 +
 src/library/scala/runtime/VolatileBooleanRef.java  |   20 +
 src/library/scala/runtime/VolatileByteRef.java     |   20 +
 src/library/scala/runtime/VolatileCharRef.java     |   20 +
 src/library/scala/runtime/VolatileDoubleRef.java   |   19 +
 src/library/scala/runtime/VolatileFloatRef.java    |   20 +
 src/library/scala/runtime/VolatileIntRef.java      |   19 +
 src/library/scala/runtime/VolatileLongRef.java     |   20 +
 src/library/scala/runtime/VolatileObjectRef.java   |   20 +
 src/library/scala/runtime/VolatileShortRef.java    |   20 +
 src/library/scala/serializable.scala               |    5 +-
 src/library/scala/specialized.scala                |   33 +
 src/library/scala/testing/Benchmark.scala          |   26 +-
 src/library/scala/testing/SUnit.scala              |   41 +-
 src/library/scala/testing/Show.scala               |   35 +-
 src/library/scala/text/Document.scala              |    3 +-
 src/library/scala/throws.scala                     |   22 +-
 src/library/scala/transient.scala                  |    6 +-
 src/library/scala/unchecked.scala                  |    5 +-
 src/library/scala/unsealed.scala                   |   17 -
 src/library/scala/util/DynamicVariable.scala       |   10 +-
 src/library/scala/util/Marshal.scala               |   22 +-
 src/library/scala/util/Properties.scala            |  143 +-
 src/library/scala/util/Random.scala                |   82 +-
 src/library/scala/util/Sorting.scala               |  132 +-
 .../scala/util/automata/BaseBerrySethi.scala       |  189 +-
 src/library/scala/util/automata/DetWordAutom.scala |   39 +-
 src/library/scala/util/automata/Inclusion.scala    |    3 +-
 .../scala/util/automata/NondetWordAutom.scala      |   93 +-
 .../scala/util/automata/SubsetConstruction.scala   |  170 +-
 .../scala/util/automata/WordBerrySethi.scala       |  251 +-
 src/library/scala/util/control/Breaks.scala        |   64 +
 .../scala/util/control/ControlThrowable.scala      |   38 +
 src/library/scala/util/control/Exception.scala     |  214 +
 src/library/scala/util/control/NoStackTrace.scala  |   20 +
 src/library/scala/util/control/TailCalls.scala     |   56 +
 src/library/scala/util/grammar/HedgeRHS.scala      |    5 +-
 src/library/scala/util/grammar/TreeRHS.scala       |    5 +-
 src/library/scala/util/logging/ConsoleLogger.scala |    5 +-
 src/library/scala/util/logging/Logged.scala        |    3 +-
 src/library/scala/util/matching/Regex.scala        |   83 +-
 .../util/parsing/CharInputStreamIterator.scala     |   52 -
 src/library/scala/util/parsing/Parsers.scala       |   90 -
 .../scala/util/parsing/SimpleTokenizer.scala       |   68 -
 .../scala/util/parsing/ast/AbstractSyntax.scala    |    2 +-
 src/library/scala/util/parsing/ast/Binders.scala   |   42 +-
 .../parsing/combinator/ImplicitConversions.scala   |    3 +-
 .../util/parsing/combinator/JavaTokenParsers.scala |    3 +-
 .../util/parsing/combinator/PackratParsers.scala   |  327 ++
 .../scala/util/parsing/combinator/Parsers.scala    |  145 +-
 .../util/parsing/combinator/RegexParsers.scala     |   22 +-
 .../util/parsing/combinator/lexical/Lexical.scala  |   11 +-
 .../util/parsing/combinator/lexical/Scanners.scala |   18 +-
 .../parsing/combinator/lexical/StdLexical.scala    |   40 +-
 .../syntactical/StandardTokenParsers.scala         |   18 +-
 .../combinator/syntactical/StdTokenParsers.scala   |   18 +-
 .../combinator/syntactical/TokenParsers.scala      |   18 +-
 .../parsing/combinator/testing/RegexTest.scala     |    1 -
 .../util/parsing/combinator/testing/Tester.scala   |    4 +-
 .../util/parsing/combinator/token/StdTokens.scala  |   37 +
 .../util/parsing/combinator/token/Tokens.scala     |   40 +
 .../scala/util/parsing/combinatorold/$tilde.scala  |   16 -
 .../combinatorold/ImplicitConversions.scala        |   36 -
 .../scala/util/parsing/combinatorold/Parsers.scala |  960 ----
 .../parsing/combinatorold/lexical/Lexical.scala    |   41 -
 .../parsing/combinatorold/lexical/Scanners.scala   |   77 -
 .../parsing/combinatorold/lexical/StdLexical.scala |   97 -
 .../combinatorold/syntactical/BindingParsers.scala |  143 -
 .../syntactical/StdTokenParsers.scala              |   44 -
 .../combinatorold/syntactical/TokenParsers.scala   |   64 -
 .../parsing/combinatorold/testing/Tester.scala     |   45 -
 .../util/parsing/input/CharArrayPosition.scala     |   45 -
 .../scala/util/parsing/input/CharArrayReader.scala |    6 +-
 .../util/parsing/input/CharSequenceReader.scala    |    3 +-
 .../scala/util/parsing/input/NoPosition.scala      |    3 +-
 .../scala/util/parsing/input/OffsetPosition.scala  |    2 +-
 .../scala/util/parsing/input/PagedSeqReader.scala  |    3 +-
 .../scala/util/parsing/input/Position.scala        |    4 +-
 .../scala/util/parsing/input/Positional.scala      |    2 +-
 src/library/scala/util/parsing/input/Reader.scala  |    3 +-
 .../scala/util/parsing/input/StreamReader.scala    |    3 +-
 src/library/scala/util/parsing/json/JSON.scala     |   57 +-
 src/library/scala/util/parsing/json/Lexer.scala    |    5 +-
 src/library/scala/util/parsing/json/Parser.scala   |   32 +-
 .../scala/util/parsing/syntax/StdTokens.scala      |   35 -
 src/library/scala/util/parsing/syntax/Tokens.scala |   38 -
 .../scala/util/parsing/syntax/package.scala        |   19 +
 src/library/scala/util/regexp/Base.scala           |   61 +-
 .../scala/util/regexp/PointedHedgeExp.scala        |    3 +-
 src/library/scala/util/regexp/SyntaxError.scala    |    3 +-
 src/library/scala/util/regexp/WordExp.scala        |    3 +-
 src/library/scala/volatile.scala                   |    6 +-
 src/library/scala/xml/Atom.scala                   |   39 +-
 src/library/scala/xml/Attribute.scala              |   91 +
 src/library/scala/xml/Comment.scala                |   33 +-
 src/library/scala/xml/Document.scala               |   10 +-
 src/library/scala/xml/Elem.scala                   |   83 +-
 src/library/scala/xml/EntityRef.scala              |   26 +-
 src/library/scala/xml/Equality.scala               |  115 +
 src/library/scala/xml/Group.scala                  |   72 +-
 src/library/scala/xml/HasKeyValue.scala            |    4 +-
 .../scala/xml/MalformedAttributeException.scala    |    3 +-
 src/library/scala/xml/MetaData.scala               |  157 +-
 src/library/scala/xml/NamespaceBinding.scala       |   68 +-
 src/library/scala/xml/Node.scala                   |   75 +-
 src/library/scala/xml/NodeBuffer.scala             |   30 +-
 src/library/scala/xml/NodeSeq.scala                |  257 +-
 src/library/scala/xml/NodeTraverser.scala          |   37 -
 src/library/scala/xml/Null.scala                   |   74 +-
 src/library/scala/xml/PCData.scala                 |   15 +-
 src/library/scala/xml/Parsing.scala                |  105 -
 src/library/scala/xml/PrefixedAttribute.scala      |   67 +-
 src/library/scala/xml/PrettyPrinter.scala          |  153 +-
 src/library/scala/xml/ProcInstr.scala              |   48 +-
 src/library/scala/xml/QNode.scala                  |    7 +-
 src/library/scala/xml/SpecialNode.scala            |   11 +-
 src/library/scala/xml/Text.scala                   |   38 +-
 src/library/scala/xml/TextBuffer.scala             |   38 +-
 src/library/scala/xml/TopScope.scala               |   28 +-
 src/library/scala/xml/TypeSymbol.scala             |    3 +-
 src/library/scala/xml/Unparsed.scala               |   25 +-
 src/library/scala/xml/UnprefixedAttribute.scala    |   61 +-
 src/library/scala/xml/Utility.scala                |  388 +-
 src/library/scala/xml/XML.scala                    |  150 +-
 src/library/scala/xml/Xhtml.scala                  |  133 +-
 src/library/scala/xml/dtd/ContentModel.scala       |  197 +-
 src/library/scala/xml/dtd/ContentModelParser.scala |   30 +-
 src/library/scala/xml/dtd/DTD.scala                |   42 +-
 src/library/scala/xml/dtd/Decl.scala               |   68 +-
 src/library/scala/xml/dtd/DocType.scala            |   33 +-
 src/library/scala/xml/dtd/DtdTypeSymbol.scala      |   15 -
 src/library/scala/xml/dtd/ElementValidator.scala   |  170 +-
 src/library/scala/xml/dtd/ExternalID.scala         |   80 +-
 src/library/scala/xml/dtd/Scanner.scala            |   15 +-
 src/library/scala/xml/dtd/Tokens.scala             |    6 +-
 .../scala/xml/dtd/ValidationException.scala        |   16 +-
 src/library/scala/xml/factory/Binder.scala         |    9 +-
 .../scala/xml/factory/LoggedNodeFactory.scala      |    8 +-
 src/library/scala/xml/factory/NodeFactory.scala    |   90 +-
 src/library/scala/xml/factory/XMLLoader.scala      |   60 +
 .../xml/include/CircularIncludeException.scala     |    6 +-
 .../xml/include/UnavailableResourceException.scala |    6 +-
 .../scala/xml/include/XIncludeException.scala      |    8 +-
 .../scala/xml/include/sax/EncodingHeuristics.scala |  208 +-
 src/library/scala/xml/include/sax/Main.scala       |  148 +-
 .../scala/xml/include/sax/XIncludeFilter.scala     |  119 +-
 src/library/scala/xml/include/sax/XIncluder.scala  |   31 +-
 src/library/scala/xml/package.scala                |   11 +
 .../scala/xml/parsing/ConstructingHandler.scala    |   22 +-
 .../scala/xml/parsing/ConstructingParser.scala     |   65 +-
 .../scala/xml/parsing/DefaultMarkupHandler.scala   |    8 +-
 .../scala/xml/parsing/ExternalSources.scala        |   66 +-
 src/library/scala/xml/parsing/FactoryAdapter.scala |  306 +-
 src/library/scala/xml/parsing/FatalError.scala     |   11 +-
 src/library/scala/xml/parsing/MarkupHandler.scala  |  101 +-
 src/library/scala/xml/parsing/MarkupParser.scala   |  633 +-
 .../scala/xml/parsing/MarkupParserCommon.scala     |  263 +
 .../xml/parsing/NoBindingFactoryAdapter.scala      |   66 +-
 src/library/scala/xml/parsing/TokenTests.scala     |  138 +-
 .../xml/parsing/ValidatingMarkupHandler.scala      |    9 +-
 src/library/scala/xml/parsing/XhtmlEntities.scala  |   21 +-
 src/library/scala/xml/parsing/XhtmlParser.scala    |   67 +-
 src/library/scala/xml/path/Expression.scala        |   66 -
 .../scala/xml/persistent/CachedFileStorage.scala   |   10 +-
 src/library/scala/xml/persistent/Index.scala       |    6 +-
 .../scala/xml/persistent/IndexedStorage.scala      |   48 -
 src/library/scala/xml/persistent/SetStorage.scala  |   10 +-
 src/library/scala/xml/pull/XMLEvent.scala          |   49 +-
 src/library/scala/xml/pull/XMLEventReader.scala    |  230 +-
 src/library/scala/xml/pull/package.scala           |   41 +
 .../scala/xml/transform/BasicTransformer.scala     |  135 +-
 src/library/scala/xml/transform/RewriteRule.scala  |    6 +-
 .../scala/xml/transform/RuleTransformer.scala      |   18 +-
 src/manual/scala/man1/Command.scala                |    5 +-
 src/manual/scala/man1/fsc.scala                    |    6 +-
 src/manual/scala/man1/sbaz.scala                   |    6 +-
 src/manual/scala/man1/scala.scala                  |    6 +-
 src/manual/scala/man1/scalac.scala                 |   10 +-
 src/manual/scala/man1/scaladoc.scala               |  132 +-
 src/manual/scala/man1/scalap.scala                 |  108 +
 src/manual/scala/tools/docutil/EmitHtml.scala      |    3 +-
 src/manual/scala/tools/docutil/EmitManPage.scala   |    5 +-
 src/manual/scala/tools/docutil/ManMaker.scala      |    2 +-
 src/manual/scala/tools/docutil/ManPage.scala       |    3 +-
 .../tools/docutil/resources/images/external.gif    |  Bin 289 -> 290 bytes
 .../tools/docutil/resources/images/scala_logo.png  |  Bin 4751 -> 4752 bytes
 .../scala/tools/docutil/resources/index.html       |   24 +-
 src/mono/bin/scala-net                             |   60 -
 src/mono/bin/scala-net.bat                         |   81 -
 src/mono/bin/scalac-net                            |   86 -
 src/mono/bin/scalac-net.bat                        |  116 -
 src/msil/ch/epfl/lamp/compiler/msil/Assembly.java  |  253 +
 .../ch/epfl/lamp/compiler/msil/AssemblyName.java   |   96 +
 src/msil/ch/epfl/lamp/compiler/msil/Attribute.java |  557 ++
 .../ch/epfl/lamp/compiler/msil/BindingFlags.java   |  169 +
 .../lamp/compiler/msil/CallingConventions.java     |   75 +
 .../epfl/lamp/compiler/msil/ConstructorInfo.java   |   54 +
 .../compiler/msil/CustomAttributeProvider.java     |   82 +
 .../epfl/lamp/compiler/msil/EventAttributes.java   |   32 +
 src/msil/ch/epfl/lamp/compiler/msil/EventInfo.java |   58 +
 .../epfl/lamp/compiler/msil/FieldAttributes.java   |  119 +
 src/msil/ch/epfl/lamp/compiler/msil/FieldInfo.java |  112 +
 .../compiler/msil/ICustomAttributeProvider.java    |   57 +
 .../ch/epfl/lamp/compiler/msil/MemberInfo.java     |   47 +
 .../ch/epfl/lamp/compiler/msil/MemberTypes.java    |   81 +
 .../epfl/lamp/compiler/msil/MethodAttributes.java  |  158 +
 .../ch/epfl/lamp/compiler/msil/MethodBase.java     |  144 +
 .../lamp/compiler/msil/MethodImplAttributes.java   |  116 +
 .../ch/epfl/lamp/compiler/msil/MethodInfo.java     |   56 +
 src/msil/ch/epfl/lamp/compiler/msil/Module.java    |  155 +
 .../ch/epfl/lamp/compiler/msil/PEAssembly.java     |   69 +
 src/msil/ch/epfl/lamp/compiler/msil/PEFile.java    |  877 +++
 src/msil/ch/epfl/lamp/compiler/msil/PEModule.java  |  335 ++
 src/msil/ch/epfl/lamp/compiler/msil/PEType.java    |  398 ++
 .../lamp/compiler/msil/ParameterAttributes.java    |   72 +
 .../ch/epfl/lamp/compiler/msil/ParameterInfo.java  |   76 +
 .../lamp/compiler/msil/PropertyAttributes.java     |   45 +
 .../ch/epfl/lamp/compiler/msil/PropertyInfo.java   |  104 +
 src/msil/ch/epfl/lamp/compiler/msil/Type.java      | 1041 ++++
 .../ch/epfl/lamp/compiler/msil/TypeAttributes.java |  190 +
 src/msil/ch/epfl/lamp/compiler/msil/Version.java   |   71 +
 .../lamp/compiler/msil/emit/AssemblyBuilder.scala  |  124 +
 .../compiler/msil/emit/ConstructorBuilder.scala    |   64 +
 .../lamp/compiler/msil/emit/FieldBuilder.scala     |   57 +
 .../msil/emit/ICustomAttributeSetter.scala         |   18 +
 .../epfl/lamp/compiler/msil/emit/ILGenerator.scala |  537 ++
 .../lamp/compiler/msil/emit/ILPrinterVisitor.scala |  734 +++
 .../ch/epfl/lamp/compiler/msil/emit/Label.scala    |  148 +
 .../lamp/compiler/msil/emit/LocalBuilder.scala     |   44 +
 .../lamp/compiler/msil/emit/MethodBuilder.scala    |   70 +
 .../lamp/compiler/msil/emit/ModuleBuilder.scala    |  133 +
 .../msil/emit/MultipleFilesILPrinterVisitor.scala  |  138 +
 .../ch/epfl/lamp/compiler/msil/emit/OpCode.scala   | 1934 +++++++
 .../ch/epfl/lamp/compiler/msil/emit/OpCodes.scala  | 1195 ++++
 .../lamp/compiler/msil/emit/ParameterBuilder.scala |   44 +
 .../msil/emit/SingleFileILPrinterVisitor.scala     |   93 +
 .../epfl/lamp/compiler/msil/emit/TypeBuilder.scala |  233 +
 .../epfl/lamp/compiler/msil/emit/Visitable.scala   |   24 +
 .../ch/epfl/lamp/compiler/msil/emit/Visitor.scala  |   58 +
 .../compiler/msil/tests/CustomAttributesTest.java  |   31 +
 .../lamp/compiler/msil/tests/JavaTypeTest.java     |   18 +
 .../epfl/lamp/compiler/msil/tests/MembersTest.java |  100 +
 .../epfl/lamp/compiler/msil/tests/TableDump.java   |  311 +
 .../ch/epfl/lamp/compiler/msil/tests/Test.java     |   92 +
 .../ch/epfl/lamp/compiler/msil/util/PESection.java |   57 +
 .../ch/epfl/lamp/compiler/msil/util/PEStream.java  |  199 +
 .../ch/epfl/lamp/compiler/msil/util/Signature.java |  118 +
 .../ch/epfl/lamp/compiler/msil/util/Table.java     | 1599 ++++++
 src/partest-alternative/README                     |   50 +
 .../scala/tools/partest/Actions.scala              |  231 +
 .../scala/tools/partest/Alarms.scala               |   86 +
 .../scala/tools/partest/BuildContributors.scala    |  102 +
 .../scala/tools/partest/Categories.scala           |   70 +
 .../scala/tools/partest/Compilable.scala           |  106 +
 .../scala/tools/partest/Config.scala               |  129 +
 .../scala/tools/partest/Dispatcher.scala           |  162 +
 .../scala/tools/partest/Entities.scala             |   74 +
 .../scala/tools/partest/Housekeeping.scala         |  187 +
 .../scala/tools/partest/Partest.scala              |   81 +
 .../scala/tools/partest/PartestSpec.scala          |  104 +
 .../scala/tools/partest/Properties.scala           |   17 +
 .../scala/tools/partest/Results.scala              |  121 +
 .../scala/tools/partest/Runner.scala               |   36 +
 .../scala/tools/partest/Statistics.scala           |   46 +
 .../scala/tools/partest/Universe.scala             |   96 +
 .../scala/tools/partest/ant/JavaTask.scala         |   57 +
 .../scala/tools/partest/antlib.xml                 |    3 +
 .../tools/partest/category/AllCategories.scala     |   20 +
 .../scala/tools/partest/category/Analysis.scala    |   64 +
 .../scala/tools/partest/category/Compiler.scala    |  140 +
 .../scala/tools/partest/category/Runner.scala      |  108 +
 .../scala/tools/partest/io/ANSIWriter.scala        |   58 +
 .../scala/tools/partest/io/Diff.java               |  873 +++
 .../scala/tools/partest/io/DiffPrint.java          |  606 ++
 .../scala/tools/partest/io/JUnitReport.scala       |   38 +
 .../scala/tools/partest/io/Logging.scala           |  137 +
 .../scala/tools/partest/nest/StreamAppender.scala  |   94 +
 .../scala/tools/partest/package.scala              |   45 +
 .../scala/tools/partest/util/package.scala         |   61 +
 src/partest/README                                 |   13 +-
 .../scala/tools/partest/PartestDefaults.scala      |   30 +
 src/partest/scala/tools/partest/PartestTask.scala  |  407 +-
 .../scala/tools/partest/nest/AntRunner.scala       |   25 +-
 .../scala/tools/partest/nest/CompileManager.scala  |  301 +-
 .../tools/partest/nest/ConsoleFileManager.scala    |  315 +-
 .../scala/tools/partest/nest/ConsoleRunner.scala   |  374 +-
 src/partest/scala/tools/partest/nest/Diff.java     |   29 +-
 .../scala/tools/partest/nest/DiffPrint.java        |    3 +-
 .../scala/tools/partest/nest/DirectRunner.scala    |   71 +-
 .../scala/tools/partest/nest/FileManager.scala     |  115 +-
 .../scala/tools/partest/nest/NestRunner.scala      |    7 +-
 src/partest/scala/tools/partest/nest/NestUI.scala  |   39 +-
 .../scala/tools/partest/nest/PathSettings.scala    |   41 +
 .../tools/partest/nest/ReflectiveRunner.scala      |   93 +-
 .../scala/tools/partest/nest/RunnerUtils.scala     |   46 +-
 .../scala/tools/partest/nest/StreamAppender.scala  |   88 +-
 .../scala/tools/partest/nest/TestFile.scala        |  129 +-
 src/partest/scala/tools/partest/nest/Worker.scala  | 1073 ++--
 src/partest/scala/tools/partest/package.scala      |   40 +
 .../scala/tools/partest/utils/PrintMgr.scala       |    7 +-
 .../scala/tools/partest/utils/Properties.scala     |   54 +-
 src/scalap/decoder.properties                      |    2 +
 src/scalap/scala/tools/scalap/Arguments.scala      |  204 +
 .../scala/tools/scalap/ByteArrayReader.scala       |  112 +
 src/scalap/scala/tools/scalap/Classfile.scala      |  129 +
 src/scalap/scala/tools/scalap/Classfiles.scala     |   71 +
 src/scalap/scala/tools/scalap/CodeWriter.scala     |  134 +
 src/scalap/scala/tools/scalap/Decode.scala         |  101 +
 src/scalap/scala/tools/scalap/JavaWriter.scala     |  241 +
 src/scalap/scala/tools/scalap/Main.scala           |  280 +
 src/scalap/scala/tools/scalap/MetaParser.scala     |  183 +
 src/scalap/scala/tools/scalap/Names.scala          |   96 +
 src/scalap/scala/tools/scalap/Properties.scala     |   16 +
 .../scala/tools/scalap/scalax/rules/Arrows.scala   |   37 +
 .../scala/tools/scalap/scalax/rules/Functors.scala |   81 +
 .../scala/tools/scalap/scalax/rules/Input.scala    |   68 +
 .../tools/scalap/scalax/rules/Memoisable.scala     |   61 +
 .../scala/tools/scalap/scalax/rules/Monad.scala    |   46 +
 .../scala/tools/scalap/scalax/rules/Result.scala   |   72 +
 .../scala/tools/scalap/scalax/rules/Rule.scala     |  177 +
 .../scala/tools/scalap/scalax/rules/Rules.scala    |  146 +
 .../scala/tools/scalap/scalax/rules/SeqRule.scala  |  101 +
 .../scalax/rules/scalasig/ClassFileParser.scala    |  246 +
 .../tools/scalap/scalax/rules/scalasig/Flags.scala |   69 +
 .../scalap/scalax/rules/scalasig/ScalaSig.scala    |  351 ++
 .../scalax/rules/scalasig/ScalaSigPrinter.scala    |  440 ++
 .../rules/scalasig/SourceFileAttributeParser.scala |   28 +
 .../scalap/scalax/rules/scalasig/Symbol.scala      |   73 +
 .../tools/scalap/scalax/rules/scalasig/Type.scala  |   26 +
 .../tools/scalap/scalax/util/StringUtil.scala      |   19 +
 src/swing/doc/README                               |    2 +-
 src/swing/doc/build.xml                            |    2 +-
 src/swing/scala/swing/AbstractButton.scala         |   22 +-
 src/swing/scala/swing/Action.scala                 |   50 +-
 src/swing/scala/swing/Adjustable.scala             |   53 +
 src/swing/scala/swing/Alignment.scala              |   10 +
 src/swing/scala/swing/Applet.scala                 |   29 +-
 src/swing/scala/swing/BorderPanel.scala            |   18 +-
 src/swing/scala/swing/BoxPanel.scala               |   10 +
 src/swing/scala/swing/BufferWrapper.scala          |   27 +-
 src/swing/scala/swing/Button.scala                 |   16 +-
 src/swing/scala/swing/ButtonGroup.scala            |   24 +-
 src/swing/scala/swing/CheckBox.scala               |   12 +-
 src/swing/scala/swing/ComboBox.scala               |   27 +-
 src/swing/scala/swing/Component.scala              |  249 +-
 src/swing/scala/swing/Container.scala              |   41 +-
 src/swing/scala/swing/Dialog.scala                 |   81 -
 src/swing/scala/swing/EditorPane.scala             |   31 +
 src/swing/scala/swing/FileChooser.scala            |   48 +-
 src/swing/scala/swing/FlowPanel.scala              |   24 +-
 src/swing/scala/swing/Font.scala                   |   70 +
 src/swing/scala/swing/FormattedTextField.scala     |   16 +-
 src/swing/scala/swing/Frame.scala                  |   52 -
 src/swing/scala/swing/GUIApplication.scala         |   33 +-
 src/swing/scala/swing/GridBagPanel.scala           |   18 +-
 src/swing/scala/swing/GridPanel.scala              |   13 +-
 src/swing/scala/swing/Key.scala                    |  195 -
 src/swing/scala/swing/Label.scala                  |   13 +-
 src/swing/scala/swing/LayoutContainer.scala        |   58 +-
 src/swing/scala/swing/ListView.scala               |   82 +-
 src/swing/scala/swing/MainFrame.scala              |   14 +-
 src/swing/scala/swing/Menu.scala                   |   18 +-
 src/swing/scala/swing/Orientable.scala             |   18 +-
 src/swing/scala/swing/Orientation.scala            |   13 +-
 src/swing/scala/swing/Oriented.scala               |   32 +-
 src/swing/scala/swing/Panel.scala                  |   12 +-
 src/swing/scala/swing/PasswordField.scala          |   14 +-
 src/swing/scala/swing/ProgressBar.scala            |   17 +-
 src/swing/scala/swing/Publisher.scala              |  104 +-
 src/swing/scala/swing/RadioButton.scala            |   14 +-
 src/swing/scala/swing/Reactions.scala              |   18 +-
 src/swing/scala/swing/Reactor.scala                |   14 +-
 src/swing/scala/swing/RichWindow.scala             |  205 +
 src/swing/scala/swing/RootPanel.scala              |   22 +-
 src/swing/scala/swing/ScrollBar.scala              |   39 +
 src/swing/scala/swing/ScrollPane.scala             |   65 +-
 src/swing/scala/swing/Scrollable.scala             |   40 +-
 src/swing/scala/swing/Separator.scala              |   14 +-
 src/swing/scala/swing/SequentialContainer.scala    |   19 +-
 src/swing/scala/swing/SimpleGUIApplication.scala   |   38 +-
 src/swing/scala/swing/SimpleSwingApplication.scala |   17 +
 src/swing/scala/swing/Slider.scala                 |   31 +-
 src/swing/scala/swing/SplitPane.scala              |   23 +-
 src/swing/scala/swing/Swing.scala                  |   43 +-
 src/swing/scala/swing/SwingActor.scala             |   35 +
 src/swing/scala/swing/SwingApplication.scala       |    9 +
 src/swing/scala/swing/SwingWorker.scala            |   21 +
 src/swing/scala/swing/TabbedPane.scala             |   29 +-
 src/swing/scala/swing/Table.scala                  |   93 +-
 src/swing/scala/swing/TextArea.scala               |   19 +-
 src/swing/scala/swing/TextComponent.scala          |   25 +-
 src/swing/scala/swing/TextField.scala              |   45 +-
 src/swing/scala/swing/ToggleButton.scala           |   14 +-
 src/swing/scala/swing/UIElement.scala              |   98 +-
 src/swing/scala/swing/Views.scala                  |    7 -
 src/swing/scala/swing/Window.scala                 |   73 +
 src/swing/scala/swing/event/ActionEvent.scala      |   19 +-
 src/swing/scala/swing/event/AdjustingEvent.scala   |   26 +-
 .../scala/swing/event/BackgroundChanged.scala      |   13 +-
 src/swing/scala/swing/event/ButtonClicked.scala    |   13 +-
 src/swing/scala/swing/event/CaretUpdate.scala      |   13 +-
 src/swing/scala/swing/event/ComponentEvent.scala   |   27 +-
 src/swing/scala/swing/event/ContainerEvent.scala   |   13 +-
 src/swing/scala/swing/event/EditDone.scala         |   13 +-
 src/swing/scala/swing/event/Event.scala            |   13 +-
 src/swing/scala/swing/event/FocusEvent.scala       |   15 +-
 src/swing/scala/swing/event/FontChanged.scala      |   13 +-
 .../scala/swing/event/ForegroundChanged.scala      |   13 +-
 src/swing/scala/swing/event/InputEvent.scala       |   20 +-
 src/swing/scala/swing/event/Key.scala              |  232 +
 src/swing/scala/swing/event/KeyEvent.scala         |   43 +
 src/swing/scala/swing/event/ListEvent.scala        |   15 +-
 src/swing/scala/swing/event/MouseEvent.scala       |  105 +-
 src/swing/scala/swing/event/SelectionEvent.scala   |   31 +-
 src/swing/scala/swing/event/TableEvent.scala       |   19 +-
 src/swing/scala/swing/event/UIEvent.scala          |   18 +-
 src/swing/scala/swing/event/ValueChanged.scala     |   19 +-
 src/swing/scala/swing/event/WindowActivated.scala  |   15 +-
 src/swing/scala/swing/event/WindowClosed.scala     |    5 +-
 src/swing/scala/swing/event/WindowClosing.scala    |   15 +-
 .../scala/swing/event/WindowDeactivated.scala      |   15 +-
 .../scala/swing/event/WindowDeiconified.scala      |   15 +-
 src/swing/scala/swing/event/WindowEvent.scala      |   15 +-
 src/swing/scala/swing/event/WindowIconified.scala  |   15 +-
 src/swing/scala/swing/event/WindowOpened.scala     |   15 +-
 src/swing/scala/swing/model/Matrix.scala           |   17 +-
 src/swing/scala/swing/package.scala                |   20 +
 src/swing/scala/swing/test/ButtonApp.scala         |   10 +-
 src/swing/scala/swing/test/CelsiusConverter.scala  |    5 +-
 src/swing/scala/swing/test/CelsiusConverter2.scala |   44 +-
 src/swing/scala/swing/test/ComboBoxes.scala        |    9 +-
 src/swing/scala/swing/test/CountButton.scala       |    5 +-
 src/swing/scala/swing/test/Dialogs.scala           |  105 +-
 src/swing/scala/swing/test/GridBagDemo.scala       |    7 +-
 src/swing/scala/swing/test/HelloWorld.scala        |   20 +-
 src/swing/scala/swing/test/LabelTest.scala         |   20 +
 src/swing/scala/swing/test/LinePainting.scala      |   53 +
 src/swing/scala/swing/test/ListViewDemo.scala      |   18 +
 src/swing/scala/swing/test/SimpleApplet.scala      |    6 +-
 src/swing/scala/swing/test/SwingApp.scala          |    5 +-
 src/swing/scala/swing/test/TableSelection.scala    |  169 +-
 src/swing/scala/swing/test/UIDemo.scala            |  133 +-
 src/swing/scala/swing/test/images/banana.jpg       |  Bin 5999 -> 6000 bytes
 src/swing/scala/swing/test/images/margarita1.jpg   |  Bin 14769 -> 14770 bytes
 src/swing/scala/swing/test/images/margarita2.jpg   |  Bin 17309 -> 17310 bytes
 src/swing/scala/swing/test/images/rose.jpg         |  Bin 13807 -> 13808 bytes
 src/swing/swing.version.properties                 |    2 +-
 test/{ => attic}/files/cli/test1/Main.check.j9vm5  |    0
 test/{ => attic}/files/cli/test1/Main.check.java   |    0
 test/{ => attic}/files/cli/test1/Main.check.java5  |    0
 .../files/cli/test1/Main.check.java5_api           |    0
 .../files/cli/test1/Main.check.java5_j9            |    0
 test/{ => attic}/files/cli/test1/Main.check.javac  |    0
 test/{ => attic}/files/cli/test1/Main.check.javac5 |    0
 test/{ => attic}/files/cli/test1/Main.check.javac6 |    0
 test/{ => attic}/files/cli/test1/Main.check.jikes  |    0
 test/{ => attic}/files/cli/test1/Main.check.jikes5 |    0
 test/{ => attic}/files/cli/test1/Main.check.scala  |    0
 .../files/cli/test1/Main.check.scala_api           |    0
 .../files/cli/test1/Main.check.scala_j9            |    0
 test/attic/files/cli/test1/Main.check.scalac       |   63 +
 .../files/cli/test1/Main.check.scalaint            |    0
 test/{ => attic}/files/cli/test1/Main.java         |    0
 test/{ => attic}/files/cli/test1/Main.scala        |    0
 test/{ => attic}/files/cli/test2/Main.check.j9vm5  |    0
 test/{ => attic}/files/cli/test2/Main.check.java   |    0
 test/{ => attic}/files/cli/test2/Main.check.java5  |    0
 .../files/cli/test2/Main.check.java5_api           |    0
 .../files/cli/test2/Main.check.java5_j9            |    0
 test/{ => attic}/files/cli/test2/Main.check.javac  |    0
 test/{ => attic}/files/cli/test2/Main.check.javac5 |    0
 test/{ => attic}/files/cli/test2/Main.check.javac6 |    0
 test/{ => attic}/files/cli/test2/Main.check.jikes  |    0
 test/{ => attic}/files/cli/test2/Main.check.jikes5 |    0
 test/{ => attic}/files/cli/test2/Main.check.scala  |    0
 .../files/cli/test2/Main.check.scala_api           |    0
 .../files/cli/test2/Main.check.scala_j9            |    0
 test/attic/files/cli/test2/Main.check.scalac       |   63 +
 .../files/cli/test2/Main.check.scalaint            |    0
 test/{ => attic}/files/cli/test2/Main.java         |    0
 test/{ => attic}/files/cli/test2/Main.scala        |    0
 test/{ => attic}/files/cli/test3/Main.check.j9vm5  |    0
 test/{ => attic}/files/cli/test3/Main.check.java   |    0
 test/{ => attic}/files/cli/test3/Main.check.java5  |    0
 .../files/cli/test3/Main.check.java5_api           |    0
 .../files/cli/test3/Main.check.java5_j9            |    0
 test/{ => attic}/files/cli/test3/Main.check.javac  |    0
 test/{ => attic}/files/cli/test3/Main.check.javac5 |    0
 test/{ => attic}/files/cli/test3/Main.check.javac6 |    0
 test/{ => attic}/files/cli/test3/Main.check.jikes  |    0
 test/{ => attic}/files/cli/test3/Main.check.jikes5 |    0
 test/{ => attic}/files/cli/test3/Main.check.scala  |    0
 .../files/cli/test3/Main.check.scala_api           |    0
 .../files/cli/test3/Main.check.scala_j9            |    0
 test/attic/files/cli/test3/Main.check.scalac       |   63 +
 .../files/cli/test3/Main.check.scalaint            |    0
 test/attic/files/cli/test3/Main.java               |   10 +
 test/attic/files/cli/test3/Main.scala              |   10 +
 test/clitest                                       |  497 --
 .../bug680.check => debug/buildmanager/.gitignore} |    0
 .../jvm5/bug680.check => debug/jvm/.gitignore}     |    0
 .../jvm5/bug680.check => debug/neg/.gitignore}     |    0
 .../jvm5/bug680.check => debug/pos/.gitignore}     |    0
 .../jvm5/bug680.check => debug/res/.gitignore}     |    0
 .../jvm5/bug680.check => debug/run/.gitignore}     |    0
 .../bug680.check => debug/scalacheck/.gitignore}   |    0
 .../jvm5/bug680.check => debug/scalap/.gitignore}  |    0
 .../bug680.check => debug/shootout/.gitignore}     |    0
 test/diff/diff.README                              |   16 -
 test/diff/diff.exe                                 |  Bin 150528 -> 0 bytes
 test/diff/libiconv2.dll                            |  Bin 898048 -> 0 bytes
 test/diff/libintl3.dll                             |  Bin 92672 -> 0 bytes
 test/disabled-windows/script/loadAndExecute.check  |    1 +
 .../script/loadAndExecute/lAndE1.scala             |    3 +
 .../script/loadAndExecute/lAndE2.scala             |    1 +
 .../script/loadAndExecute/loadAndExecute.scala     |    3 +
 test/{files => disabled-windows}/script/utf8.bat   |    0
 test/{files => disabled-windows}/script/utf8.check |    0
 test/disabled-windows/script/utf8.scala            |   26 +
 test/disabled/buildmanager/t2651_1/A.scala         |    1 +
 test/disabled/buildmanager/t2651_1/B.scala         |    2 +
 test/disabled/buildmanager/t2651_1/C.scala         |    3 +
 test/disabled/buildmanager/t2651_1/D.scala         |    3 +
 .../buildmanager/t2651_1/t2651_1.changes/A2.scala  |    2 +
 test/disabled/buildmanager/t2651_1/t2651_1.check   |   19 +
 test/disabled/buildmanager/t2651_1/t2651_1.test    |    3 +
 test/disabled/lib/annotations.jar                  |  Bin 0 -> 2242 bytes
 test/disabled/lib/enums.jar                        |  Bin 0 -> 1372 bytes
 test/disabled/lib/genericNest.jar                  |  Bin 0 -> 1136 bytes
 test/disabled/lib/methvsfield.jar                  |  Bin 0 -> 609 bytes
 test/disabled/lib/nest.jar                         |  Bin 0 -> 2920 bytes
 test/disabled/lib/scalacheck.jar                   |  Bin 0 -> 743774 bytes
 test/disabled/pos/bug2919.scala                    |   12 +
 test/disabled/pos/spec-traits.scala                |   83 +
 test/{files => disabled}/run/docgenerator.check    |    0
 test/disabled/run/docgenerator.scala               |  295 +
 test/disabled/run/script-positions.scala           |   86 +
 test/disabled/run/t2946/Parsers.scala              |    4 +
 test/disabled/run/t2946/ResponseCommon.scala       |   14 +
 test/disabled/run/t2946/Test.scala                 |    7 +
 test/disabled/scalacheck/redblack.scala            |  157 +
 test/files/ant/fsc-build.xml                       |    1 -
 test/files/ant/imported.xml                        |    1 -
 test/files/ant/scalac-build.xml                    |    1 -
 test/files/ant/scaladoc-build.xml                  |    1 -
 test/files/bench/equality/eq.scala                 |   34 +
 test/files/bench/equality/eqeq.eqlog               |   42 +
 test/files/bench/equality/eqeq.scala               |   46 +
 test/files/buildmanager/annotated/A.scala          |    1 +
 test/files/buildmanager/annotated/annotated.check  |    6 +
 test/files/buildmanager/annotated/annotated.test   |    2 +
 test/files/buildmanager/freshnames/A.scala         |   16 +
 test/files/buildmanager/freshnames/B.scala         |    4 +
 .../files/buildmanager/freshnames/freshnames.check |    6 +
 test/files/buildmanager/freshnames/freshnames.test |    2 +
 test/files/buildmanager/infer/A.scala              |   16 +
 test/files/buildmanager/infer/infer.check          |    6 +
 test/files/buildmanager/infer/infer.test           |    2 +
 test/files/buildmanager/overloaded_1/A.scala       |   11 +
 .../buildmanager/overloaded_1/overloaded_1.check   |    6 +
 .../buildmanager/overloaded_1/overloaded_1.test    |    2 +
 test/files/buildmanager/simpletest/A.scala         |    3 +
 test/files/buildmanager/simpletest/B.scala         |    3 +
 .../simpletest/simpletest.changes/A1.scala         |    1 +
 .../files/buildmanager/simpletest/simpletest.check |   11 +
 test/files/buildmanager/simpletest/simpletest.test |    3 +
 test/files/buildmanager/t2280/A.scala              |    1 +
 test/files/buildmanager/t2280/B.java               |    2 +
 test/files/buildmanager/t2280/t2280.check          |    6 +
 test/files/buildmanager/t2280/t2280.test           |    2 +
 test/files/buildmanager/t2556_1/A.scala            |    3 +
 test/files/buildmanager/t2556_1/B.scala            |    3 +
 .../buildmanager/t2556_1/t2556_1.changes/A2.scala  |    4 +
 test/files/buildmanager/t2556_1/t2556_1.check      |   12 +
 test/files/buildmanager/t2556_1/t2556_1.test       |    3 +
 test/files/buildmanager/t2556_2/A.scala            |    4 +
 test/files/buildmanager/t2556_2/B.scala            |    2 +
 test/files/buildmanager/t2556_2/C.scala            |    4 +
 .../buildmanager/t2556_2/t2556_2.changes/A2.scala  |    4 +
 test/files/buildmanager/t2556_2/t2556_2.check      |   13 +
 test/files/buildmanager/t2556_2/t2556_2.test       |    3 +
 test/files/buildmanager/t2556_3/A.scala            |    5 +
 test/files/buildmanager/t2556_3/B.scala            |    5 +
 test/files/buildmanager/t2556_3/C.scala            |    2 +
 .../buildmanager/t2556_3/t2556_3.changes/A2.scala  |    5 +
 test/files/buildmanager/t2556_3/t2556_3.check      |   18 +
 test/files/buildmanager/t2556_3/t2556_3.test       |    3 +
 test/files/buildmanager/t2557/A.scala              |    4 +
 test/files/buildmanager/t2557/B.scala              |    4 +
 test/files/buildmanager/t2557/C.scala              |    3 +
 test/files/buildmanager/t2557/D.scala              |    1 +
 test/files/buildmanager/t2557/E.scala              |    1 +
 test/files/buildmanager/t2557/F.scala              |    4 +
 .../buildmanager/t2557/t2557.changes/D2.scala      |    2 +
 test/files/buildmanager/t2557/t2557.check          |   10 +
 test/files/buildmanager/t2557/t2557.test           |    3 +
 test/files/buildmanager/t2559/A.scala              |    5 +
 test/files/buildmanager/t2559/D.scala              |    8 +
 .../buildmanager/t2559/t2559.changes/A2.scala      |    5 +
 test/files/buildmanager/t2559/t2559.check          |   14 +
 test/files/buildmanager/t2559/t2559.test           |    3 +
 test/files/buildmanager/t2562/A.scala              |    7 +
 test/files/buildmanager/t2562/B.scala              |    8 +
 .../buildmanager/t2562/t2562.changes/A2.scala      |    8 +
 test/files/buildmanager/t2562/t2562.check          |   12 +
 test/files/buildmanager/t2562/t2562.test           |    3 +
 test/files/buildmanager/t2649/A.scala              |    3 +
 test/files/buildmanager/t2649/B.scala              |    4 +
 .../buildmanager/t2649/t2649.changes/A2.scala      |    4 +
 test/files/buildmanager/t2649/t2649.check          |    9 +
 test/files/buildmanager/t2649/t2649.test           |    3 +
 test/files/buildmanager/t2650_1/A.scala            |    4 +
 test/files/buildmanager/t2650_1/B.scala            |    3 +
 .../buildmanager/t2650_1/t2650_1.changes/A2.scala  |    3 +
 test/files/buildmanager/t2650_1/t2650_1.check      |   11 +
 test/files/buildmanager/t2650_1/t2650_1.test       |    3 +
 test/files/buildmanager/t2650_2/A.scala            |    3 +
 test/files/buildmanager/t2650_2/B.scala            |    4 +
 .../buildmanager/t2650_2/t2650_2.changes/A2.scala  |    4 +
 test/files/buildmanager/t2650_2/t2650_2.check      |   13 +
 test/files/buildmanager/t2650_2/t2650_2.test       |    3 +
 test/files/buildmanager/t2650_3/A.scala            |    4 +
 test/files/buildmanager/t2650_3/B.scala            |    3 +
 .../buildmanager/t2650_3/t2650_3.changes/A2.scala  |    4 +
 test/files/buildmanager/t2650_3/t2650_3.check      |   13 +
 test/files/buildmanager/t2650_3/t2650_3.test       |    3 +
 test/files/buildmanager/t2650_4/A.scala            |    5 +
 test/files/buildmanager/t2650_4/B.scala            |    3 +
 .../buildmanager/t2650_4/t2650_4.changes/A2.scala  |    5 +
 test/files/buildmanager/t2650_4/t2650_4.check      |   13 +
 test/files/buildmanager/t2650_4/t2650_4.test       |    3 +
 test/files/buildmanager/t2651_2/A.scala            |    1 +
 .../buildmanager/t2651_2/t2651_2.changes/A2.scala  |    1 +
 test/files/buildmanager/t2651_2/t2651_2.check      |    6 +
 test/files/buildmanager/t2651_2/t2651_2.test       |    3 +
 test/files/buildmanager/t2651_3/A.scala            |    3 +
 .../buildmanager/t2651_3/t2651_3.changes/A2.scala  |    3 +
 test/files/buildmanager/t2651_3/t2651_3.check      |    6 +
 test/files/buildmanager/t2651_3/t2651_3.test       |    3 +
 test/files/buildmanager/t2651_4/A.scala            |    5 +
 test/files/buildmanager/t2651_4/B.scala            |    3 +
 .../buildmanager/t2651_4/t2651_4.changes/A2.scala  |    5 +
 test/files/buildmanager/t2651_4/t2651_4.check      |   13 +
 test/files/buildmanager/t2651_4/t2651_4.test       |    3 +
 test/files/buildmanager/t2652/A.scala              |    3 +
 test/files/buildmanager/t2652/B.scala              |    4 +
 .../buildmanager/t2652/t2652.changes/A2.scala      |    4 +
 test/files/buildmanager/t2652/t2652.check          |    9 +
 test/files/buildmanager/t2652/t2652.test           |    3 +
 test/files/buildmanager/t2653/A.scala              |    2 +
 test/files/buildmanager/t2653/B.scala              |    3 +
 .../buildmanager/t2653/t2653.changes/A2.scala      |    2 +
 test/files/buildmanager/t2653/t2653.check          |   13 +
 test/files/buildmanager/t2653/t2653.test           |    3 +
 test/files/buildmanager/t2654/A.scala              |    2 +
 test/files/buildmanager/t2654/B.scala              |    1 +
 .../buildmanager/t2654/t2654.changes/A2.scala      |    4 +
 test/files/buildmanager/t2654/t2654.check          |    6 +
 test/files/buildmanager/t2654/t2654.test           |    3 +
 test/files/buildmanager/t2655/A.scala              |    4 +
 test/files/buildmanager/t2655/B.scala              |    3 +
 .../buildmanager/t2655/t2655.changes/A2.scala      |    4 +
 test/files/buildmanager/t2655/t2655.check          |   13 +
 test/files/buildmanager/t2655/t2655.test           |    3 +
 test/files/buildmanager/t2657/A.scala              |    3 +
 test/files/buildmanager/t2657/B.scala              |    4 +
 .../buildmanager/t2657/t2657.changes/A2.scala      |    3 +
 test/files/buildmanager/t2657/t2657.check          |   13 +
 test/files/buildmanager/t2657/t2657.test           |    3 +
 test/files/buildmanager/t2789/A.scala              |    5 +
 test/files/buildmanager/t2789/B.scala              |    3 +
 .../buildmanager/t2789/t2789.changes/A2.scala      |    5 +
 test/files/buildmanager/t2789/t2789.check          |   11 +
 test/files/buildmanager/t2789/t2789.test           |    3 +
 test/files/buildmanager/t2790/A.scala              |    5 +
 test/files/buildmanager/t2790/B.scala              |    4 +
 .../buildmanager/t2790/t2790.changes/A2.scala      |    4 +
 test/files/buildmanager/t2790/t2790.check          |   14 +
 test/files/buildmanager/t2790/t2790.test           |    3 +
 test/files/buildmanager/t3045/A.java               |    7 +
 test/files/buildmanager/t3045/t3045.check          |    3 +
 test/files/buildmanager/t3045/t3045.test           |    1 +
 test/files/buildmanager/t3054/bar/Bar.java         |    7 +
 test/files/buildmanager/t3054/foo/Foo.scala        |    5 +
 test/files/buildmanager/t3054/t3054.check          |    3 +
 test/files/buildmanager/t3054/t3054.test           |    1 +
 test/files/buildmanager/t3133/A.java               |    7 +
 test/files/buildmanager/t3133/t3133.check          |    3 +
 test/files/buildmanager/t3133/t3133.test           |    1 +
 test/files/cldc/randoms.check                      |    1 -
 test/files/cldc/randoms.scala                      |   29 -
 test/files/cli/test1/Main.check.scalac             |   63 -
 test/files/cli/test2/Main.check.scalac             |   63 -
 test/files/cli/test3/Main.check.scalac             |   63 -
 test/files/cli/test3/Main.java                     |   10 -
 test/files/cli/test3/Main.scala                    |   10 -
 test/files/continuations-neg/function0.check       |    6 +
 test/files/continuations-neg/function0.scala       |   16 +
 test/files/continuations-neg/function2.check       |    6 +
 test/files/continuations-neg/function2.scala       |   16 +
 test/files/continuations-neg/function3.check       |    6 +
 test/files/continuations-neg/function3.scala       |   15 +
 test/files/continuations-neg/infer0.check          |    4 +
 test/files/continuations-neg/infer0.scala          |   14 +
 test/files/continuations-neg/infer2.check          |    4 +
 test/files/continuations-neg/infer2.scala          |   19 +
 test/files/continuations-neg/lazy.check            |    6 +
 test/files/continuations-neg/lazy.scala            |   16 +
 test/files/continuations-neg/t1929.check           |    6 +
 test/files/continuations-neg/t1929.scala           |   17 +
 test/files/continuations-neg/t2285.check           |    6 +
 test/files/continuations-neg/t2285.scala           |   11 +
 test/files/continuations-neg/t2949.check           |    6 +
 test/files/continuations-neg/t2949.scala           |   15 +
 test/files/continuations-neg/trycatch2.check       |    7 +
 test/files/continuations-neg/trycatch2.scala       |   33 +
 test/files/continuations-run/basics.check          |    2 +
 test/files/continuations-run/basics.scala          |   23 +
 test/files/continuations-run/function1.check       |    1 +
 test/files/continuations-run/function1.scala       |   16 +
 test/files/continuations-run/function4.check       |    1 +
 test/files/continuations-run/function4.scala       |   15 +
 test/files/continuations-run/function5.check       |    1 +
 test/files/continuations-run/function5.scala       |   15 +
 test/files/continuations-run/function6.check       |    1 +
 test/files/continuations-run/function6.scala       |   16 +
 test/files/continuations-run/ifelse0.check         |    2 +
 test/files/continuations-run/ifelse0.scala         |   18 +
 test/files/continuations-run/ifelse1.check         |    4 +
 test/files/continuations-run/ifelse1.scala         |   25 +
 test/files/continuations-run/ifelse2.check         |    4 +
 test/files/continuations-run/ifelse2.scala         |   16 +
 test/files/continuations-run/ifelse3.check         |    2 +
 test/files/continuations-run/ifelse3.scala         |   21 +
 test/files/continuations-run/infer1.scala          |   33 +
 test/files/continuations-run/match0.check          |    2 +
 test/files/continuations-run/match0.scala          |   18 +
 test/files/continuations-run/match1.check          |    2 +
 test/files/continuations-run/match1.scala          |   18 +
 test/files/continuations-run/match2.check          |    2 +
 test/files/continuations-run/match2.scala          |   26 +
 test/files/continuations-run/t1807.check           |    1 +
 test/files/continuations-run/t1807.scala           |   14 +
 test/files/continuations-run/t1808.scala           |   10 +
 test/files/continuations-run/t1820.scala           |   14 +
 test/files/continuations-run/t1821.check           |    4 +
 test/files/continuations-run/t1821.scala           |   20 +
 test/files/continuations-run/t2864.check           |    1 +
 test/files/continuations-run/t2864.scala           |   30 +
 test/files/continuations-run/t2934.check           |    1 +
 test/files/continuations-run/t2934.scala           |   10 +
 test/files/continuations-run/t3199.check           |    1 +
 test/files/continuations-run/t3199.scala           |   20 +
 test/files/continuations-run/t3199b.check          |    1 +
 test/files/continuations-run/t3199b.scala          |   11 +
 test/files/continuations-run/t3223.check           |    1 +
 test/files/continuations-run/t3223.scala           |   19 +
 test/files/continuations-run/t3225.check           |   12 +
 test/files/continuations-run/t3225.scala           |   56 +
 test/files/continuations-run/trycatch0.check       |    2 +
 test/files/continuations-run/trycatch0.scala       |   25 +
 test/files/continuations-run/trycatch1.check       |    4 +
 test/files/continuations-run/trycatch1.scala       |   48 +
 test/files/continuations-run/while0.check          |    1 +
 test/files/continuations-run/while0.scala          |   22 +
 test/files/continuations-run/while1.check          |   11 +
 test/files/continuations-run/while1.scala          |   22 +
 test/files/continuations-run/while2.check          |   19 +
 test/files/continuations-run/while2.scala          |   23 +
 test/files/jvm/JavaInteraction.scala               |    1 -
 test/files/jvm/actor-bangbang.scala                |   47 -
 test/files/jvm/actor-bangbang2.scala               |   45 -
 test/files/jvm/actor-exceptions.check              |    1 +
 test/files/jvm/actor-exceptions.scala              |   65 +
 test/files/jvm/actor-executor.check                |   20 +
 test/files/jvm/actor-executor.scala                |   75 +
 test/files/jvm/actor-executor2.check               |   21 +
 test/files/jvm/actor-executor2.scala               |   88 +
 test/files/jvm/actor-executor3.check               |   20 +
 test/files/jvm/actor-executor3.scala               |   62 +
 test/files/jvm/actor-getstate.check                |    2 +
 test/files/jvm/actor-getstate.scala                |   85 +
 test/files/jvm/actor-link-getstate.check           |    2 +
 test/files/jvm/actor-link-getstate.scala           |   62 +
 test/files/jvm/actor-looping.scala                 |    5 +
 test/files/jvm/actor-normal-exit.scala             |   10 +
 test/files/jvm/actor-receivewithin.scala           |   24 +-
 test/files/jvm/actor-reply.scala                   |   31 -
 test/files/jvm/actor-syncsend.scala                |   44 -
 test/files/jvm/actor-syncsend2.scala               |   44 -
 test/files/jvm/actor-termination.scala             |    5 +
 test/files/jvm/actor-uncaught-exception.check      |    2 +
 test/files/jvm/actor-uncaught-exception.scala      |   63 +
 test/files/jvm/actor-uncaught-exception2.check     |    2 +
 test/files/jvm/actor-uncaught-exception2.scala     |   63 +
 test/files/jvm/annotations.check                   |   52 +
 test/files/jvm/annotations.scala                   |  214 +
 test/files/jvm/bigints.check                       |   14 -
 test/files/jvm/bigints.scala                       |   88 +-
 test/files/{jvm5 => jvm}/bug676.check              |    0
 test/files/{jvm5 => jvm}/bug676.scala              |    0
 test/files/{jvm5 => jvm}/bug680.check              |    0
 test/files/{jvm5 => jvm}/bug680.scala              |    0
 test/files/{jvm5 => jvm}/console.check             |    0
 test/files/{jvm5 => jvm}/console.scala             |    0
 test/files/jvm/daemon-actor-termination.check      |    2 +
 test/files/jvm/daemon-actor-termination.scala      |   38 +
 test/files/jvm/deprecation.cmds                    |    3 +
 test/files/jvm/deprecation/Defs.java               |   12 +
 test/files/jvm/deprecation/Test_1.scala            |   17 +
 test/files/jvm/deprecation/Use_2.java              |   10 +
 test/files/jvm/future-alarm.check                  |   20 +
 test/files/jvm/future-alarm.scala                  |   21 +
 test/files/jvm/future-awaitall-zero.check          |    1 +
 test/files/jvm/future-awaitall-zero.scala          |   22 +
 test/files/jvm/future-termination.check            |    1 +
 test/files/jvm/future-termination.scala            |   19 +
 test/files/{jvm5 => jvm}/genericNest.scala         |    0
 test/files/jvm/getGenericSuperclass.check          |    2 +
 test/files/jvm/getGenericSuperclass.scala          |    6 +
 test/files/jvm/inner.scala                         |  127 +
 test/files/jvm/interpreter.check                   |  235 +
 test/files/jvm/interpreter.scala                   |  191 +
 test/files/jvm/libnatives.jnilib                   |  Bin 8456 -> 8456 bytes
 test/files/jvm/manifests.check                     |   48 +-
 test/files/jvm/mkLibNatives.bat                    |    1 -
 test/files/jvm/mkLibNatives.sh                     |    1 -
 test/files/jvm/nest.scala                          |    1 -
 test/files/jvm/nest/nest.java                      |   38 +
 test/files/jvm/nest/nest.scala                     |   21 +
 test/files/{jvm5 => jvm}/outerEnum.check           |    0
 test/files/{jvm5 => jvm}/outerEnum.scala           |    0
 test/files/jvm/protectedacc.scala                  |    1 -
 test/files/jvm/reactor-exceptionOnSend.check       |    2 +
 test/files/jvm/reactor-exceptionOnSend.scala       |   55 +
 test/files/jvm/reactor-producer-consumer.check     |   10 +
 test/files/jvm/reactor-producer-consumer.scala     |   95 +
 test/files/jvm/reactor.check                       |   22 +
 test/files/jvm/reactor.scala                       |   70 +
 ...actor-bangbang.check => replyablereactor.check} |    0
 test/files/jvm/replyablereactor.scala              |   56 +
 ...tor-bangbang2.check => replyablereactor2.check} |    0
 test/files/jvm/replyablereactor2.scala             |   55 +
 ...ctor-syncsend.check => replyablereactor3.check} |    0
 test/files/jvm/replyablereactor3.scala             |   54 +
 ...tor-syncsend2.check => replyablereactor4.check} |    0
 test/files/jvm/replyablereactor4.scala             |   54 +
 test/files/jvm/replyreactor-react-sender.check     |    1 +
 test/files/jvm/replyreactor-react-sender.scala     |   51 +
 .../jvm/{actor-reply.check => replyreactor.check}  |    0
 test/files/jvm/replyreactor.scala                  |   41 +
 test/files/jvm/scheduler-adapter.check             |    6 +
 test/files/jvm/scheduler-adapter.scala             |   51 +
 test/files/jvm/serialization.check                 |  277 +-
 test/files/jvm/serialization.scala                 |  557 +-
 test/files/jvm/stringbuilder.scala                 |   98 +
 test/files/{jvm5 => jvm}/sync-var.check            |    0
 test/files/jvm/sync-var.scala                      |   53 +
 test/files/{jvm5 => jvm}/t0014.check               |    0
 test/files/{jvm5 => jvm}/t0014.scala               |    0
 test/files/jvm/t1143-2/t1143-2.scala               |    2 +-
 test/files/jvm/t1143.scala                         |    2 +-
 test/files/jvm/t1342.check                         |    2 +
 test/files/jvm/t1342/JI.java                       |    3 +
 test/files/jvm/t1342/SI.scala                      |   10 +
 test/files/jvm/t1449.check                         |    1 +
 test/files/jvm/t1449.scala                         |   25 +
 test/files/{jvm5 => jvm}/t1461.scala               |    0
 test/files/{jvm5 => jvm}/t1464.check               |    0
 test/files/{jvm5 => jvm}/t1464/MyTrait.scala       |    0
 test/files/{jvm5 => jvm}/t1464/Test.java           |    0
 test/files/jvm/t1600.scala                         |   76 +
 test/files/jvm/t1652.check                         |    2 +
 test/files/{jvm5/bug680.check => jvm/t1948.check}  |    0
 test/files/jvm/t1948.scala                         |   24 +
 test/files/{jvm5/bug680.check => jvm/t2104.check}  |    0
 test/files/jvm/t2104.scala                         |   51 +
 test/files/jvm/t2214.check                         |    3 +
 test/files/jvm/t2214.scala                         |   39 +
 test/files/jvm/t2359.check                         |    5 +
 test/files/jvm/t2359.scala                         |   46 +
 test/files/jvm/t2470.check                         |    1 +
 test/files/jvm/t2470.cmds                          |    3 +
 test/files/jvm/t2470/Action.java                   |    6 +
 test/files/jvm/t2470/Read_Classfile_2.scala        |    3 +
 test/files/jvm/t2470/Task.java                     |    3 +
 test/files/jvm/t2470/Test_1.scala                  |   11 +
 test/files/jvm/t2511.check                         |    1 +
 test/files/jvm/t2511.scala                         |   30 +
 test/files/jvm/t2530.check                         |   21 +
 test/files/jvm/t2530.scala                         |   96 +
 test/files/{jvm5/bug680.check => jvm/t2570.check}  |    0
 test/files/jvm/t2570/Test.scala                    |    3 +
 test/files/jvm/t2570/Test1.java                    |    2 +
 test/files/jvm/t2570/Test3.java                    |    2 +
 test/files/{jvm5/bug680.check => jvm/t2585.check}  |    0
 test/files/jvm/t2585/Test.java                     |   16 +
 test/files/jvm/t2585/genericouter.scala            |   25 +
 test/files/jvm/t2827.check                         |    3 +
 test/files/jvm/t2827.scala                         |   14 +
 test/files/jvm/t3003.check                         |    1 +
 test/files/jvm/t3003.cmds                          |    2 +
 test/files/jvm/t3003/Annot.java                    |    4 +
 test/files/jvm/t3003/Test_1.scala                  |    8 +
 test/files/jvm/t3102.check                         |    2 +
 test/files/jvm/t3102.scala                         |   36 +
 test/files/jvm/t3356.check                         |    1 +
 test/files/jvm/t3356.scala                         |   54 +
 .../jvm/{actor-bangbang.check => t3365.check}      |    0
 test/files/jvm/t3365.scala                         |   65 +
 test/files/jvm/t3407.check                         |   10 +
 test/files/jvm/t3407.scala                         |   19 +
 test/files/jvm/t3412-channel.check                 |   10 +
 test/files/jvm/t3412-channel.scala                 |   38 +
 test/files/jvm/t3412.check                         |   10 +
 test/files/jvm/t3412.scala                         |   32 +
 test/files/jvm/t3415/Hello.java                    |    3 +
 test/files/jvm/t3415/HelloWorld.scala              |    4 +
 test/files/jvm/t3470.check                         |    3 +
 test/files/jvm/t3470.scala                         |   30 +
 test/files/{jvm5 => jvm}/throws-annot.check        |    0
 test/files/{jvm5 => jvm}/throws-annot.scala        |    0
 test/files/jvm/ticket2163/ticket2163.java          |    9 +
 test/files/jvm/ticket2163/ticket2163.scala         |    5 +
 test/files/jvm/typerep.check                       |    2 +
 test/files/jvm/typerep.scala                       |   30 +-
 test/files/jvm/unittest_io.scala                   |    4 +-
 test/files/jvm/unittest_xml.scala                  |   21 +-
 test/files/jvm/xml01.scala                         |   44 +-
 test/files/jvm/xml02.scala                         |   18 +-
 test/files/jvm/xmlpull.scala                       |   20 +-
 test/files/jvm/xmlstuff.scala                      |    8 +-
 test/files/jvm5/annotations.check                  |   35 -
 test/files/jvm5/annotations.scala                  |  159 -
 test/files/jvm5/interpreter.check                  |  212 -
 test/files/jvm5/interpreter.scala                  |  172 -
 test/files/jvm5/mkAnnotationsJar.sh                |   29 -
 test/files/jvm5/stringbuilder.scala                |   99 -
 test/files/jvm5/sync-var.scala                     |   53 -
 test/files/jvm5/typerep.check                      |   49 -
 test/files/jvm5/typerep.scala                      |  383 --
 test/files/lib/ScalaCheck.jar                      |  Bin 737362 -> 0 bytes
 test/files/lib/scalacheck.jar                      |  Bin 0 -> 743774 bytes
 test/files/neg/abstract-vars.check                 |   21 +
 test/files/neg/abstract-vars.scala                 |   29 +
 test/files/neg/abstract.check                      |    4 +-
 test/files/neg/accesses.check                      |    8 +-
 test/files/neg/annot-nonconst.check                |   16 +-
 test/files/neg/annot-nonconst.scala                |    4 +-
 test/files/neg/array-not-seq.check                 |    7 +
 test/files/neg/array-not-seq.flags                 |    1 +
 test/files/neg/array-not-seq.scala                 |   26 +
 test/files/neg/badtok-1.check                      |    4 +-
 test/files/neg/badtok-1.scala                      |    2 +-
 test/files/neg/badtok-2.check                      |    7 +-
 test/files/neg/badtok-2.scala                      |    2 +-
 test/files/neg/badtok-3.check                      |    4 +
 test/files/neg/badtok-3.scala                      |    2 +
 test/files/neg/bug1038.check                       |    5 +
 test/files/neg/bug1038.scala                       |    8 +
 test/files/neg/bug1106.scala                       |    2 +-
 test/files/neg/bug1112.check                       |    4 +-
 test/files/neg/bug112706A.check                    |    6 +
 test/files/neg/bug112706A.scala                    |    8 +
 test/files/neg/bug1181.check                       |    2 +-
 test/files/neg/bug1275.check                       |    8 +-
 test/files/neg/bug1275.scala                       |   29 +-
 test/files/neg/bug1279a.check                      |    6 -
 test/files/neg/bug1279a.scala                      |   38 -
 test/files/neg/bug1286.check                       |    2 +
 test/files/neg/bug1286/a.scala                     |    3 +
 test/files/neg/bug1286/b.scala                     |    3 +
 test/files/neg/bug1333.check                       |    4 +
 test/files/neg/bug1333.scala                       |    1 +
 test/files/neg/bug1523.check                       |    4 +
 test/files/neg/bug1523.scala                       |    5 +
 test/files/neg/bug1623.check                       |    4 +
 test/files/neg/bug1623.scala                       |   12 +
 test/files/neg/bug1838.check                       |    7 +
 test/files/neg/bug1838.scala                       |    7 +
 test/files/neg/bug1878.check                       |   15 +
 test/files/neg/bug1878.scala                       |   15 +
 test/files/neg/bug1909b.check                      |    4 +
 test/files/neg/bug1909b.scala                      |    7 +
 test/files/neg/bug1960.check                       |    4 +
 test/files/neg/bug1960.scala                       |    5 +
 test/files/neg/bug2102.check                       |    6 +
 test/files/neg/bug2102.scala                       |    3 +
 test/files/neg/bug2144.check                       |    4 +
 test/files/neg/bug2144.scala                       |    3 +
 test/files/neg/bug2148.check                       |    4 +
 test/files/neg/bug2148.scala                       |   10 +
 test/files/neg/bug2206.check                       |    5 +
 test/files/neg/bug2206.scala                       |   15 +
 test/files/neg/bug2213.check                       |   15 +
 test/files/neg/bug2213.scala                       |   11 +
 test/files/neg/bug2275a.check                      |   13 +
 test/files/neg/bug2275a.scala                      |    7 +
 test/files/neg/bug2275b.check                      |   13 +
 test/files/neg/bug2275b.scala                      |    3 +
 test/files/neg/bug276.check                        |    5 +
 test/files/neg/bug276.scala                        |    7 +
 test/files/neg/bug278.check                        |   10 +
 test/files/neg/bug278.scala                        |    6 +
 test/files/neg/bug284.check                        |    8 +
 test/files/neg/bug284.scala                        |    6 +
 test/files/neg/bug3209.check                       |    4 +
 test/files/neg/bug3209.scala                       |    2 +
 test/files/neg/bug3631.check                       |    4 +
 test/files/neg/bug3631.scala                       |    3 +
 test/files/neg/bug414.check                        |    5 -
 test/files/neg/bug414.scala                        |    2 +-
 test/files/neg/bug421.check                        |    3 +-
 test/files/neg/bug473.check                        |    4 +
 test/files/neg/bug473.scala                        |    3 +
 test/files/neg/bug520.check                        |    2 +-
 test/files/neg/bug521.check                        |    6 +-
 test/files/neg/bug545.scala                        |    2 +-
 test/files/neg/bug550.check                        |    6 +-
 test/files/neg/bug555.check                        |    4 -
 test/files/neg/bug555.scala                        |    5 -
 test/files/neg/bug563.scala                        |    4 +-
 test/files/neg/bug576.check                        |    2 +-
 test/files/neg/bug585.check                        |    2 +-
 test/files/neg/bug588.check                        |   12 +-
 test/files/neg/bug588.scala                        |    2 +-
 test/files/neg/bug608.check                        |    8 +-
 test/files/neg/bug608.scala                        |   24 +-
 test/files/neg/bug630.check                        |    4 +-
 test/files/neg/bug649.check                        |    2 +-
 test/files/neg/bug663.check                        |    6 +-
 test/files/neg/bug668.check                        |    2 +-
 test/files/neg/bug691.check                        |    2 +-
 test/files/neg/bug692.check                        |   23 +-
 test/files/neg/bug693.scala                        |    2 +-
 test/files/neg/bug696.check                        |    2 +-
 test/files/neg/bug700.check                        |    2 +-
 test/files/neg/bug700.scala                        |    2 +-
 test/files/neg/bug708.check                        |    4 +-
 test/files/neg/bug765.scala                        |    2 +-
 test/files/neg/bug766.scala                        |    2 +-
 test/files/neg/bug783.check                        |    2 +-
 test/files/neg/bug856.check                        |    4 +-
 test/files/neg/bug875.check                        |    4 +-
 test/files/neg/bug875.scala                        |    6 +-
 test/files/neg/bug876.check                        |    4 +-
 test/files/neg/bug877.check                        |    6 +-
 test/files/neg/bug882.check                        |    2 +-
 test/files/neg/bug900.check                        |    4 +-
 test/files/neg/bug910.check                        |    4 +-
 test/files/neg/bug910.scala                        |    2 +-
 test/files/neg/bug935.check                        |    7 +
 test/files/neg/bug935.scala                        |   12 +
 test/files/neg/bug944.check                        |    4 +
 test/files/neg/bug944.scala                        |    6 +
 test/files/neg/bug960.check                        |    4 +-
 test/files/neg/bug961.check                        |    9 +-
 test/files/neg/bug961.scala                        |    6 +-
 test/files/neg/bug987.scala                        |    2 +-
 test/files/neg/bug997.check                        |    4 +-
 test/files/neg/checksensible.check                 |   38 +-
 test/files/neg/checksensible.scala                 |    4 +-
 test/files/neg/checksensibleUnit.check             |    7 +
 test/files/neg/checksensibleUnit.scala             |    5 +
 test/files/neg/constrs.check                       |    2 +-
 test/files/neg/constrs.scala                       |    2 +-
 test/files/neg/cyclics.check                       |   10 +
 test/files/neg/cyclics.scala                       |    6 +
 test/files/neg/depmet_1.check                      |   10 +
 test/files/neg/depmet_1.flags                      |    1 +
 test/files/neg/depmet_1.scala                      |    5 +
 test/files/neg/divergent-implicit.check            |    7 +-
 test/files/neg/gadts1.check                        |    2 +-
 test/files/neg/gadts1.scala                        |    8 +-
 test/files/neg/higherkind_novalue.scala            |    2 +-
 test/files/neg/illegal-stmt-start.check            |    4 +
 test/files/neg/illegal-stmt-start.scala            |    5 +
 test/files/neg/implicits.check                     |   22 +-
 test/files/neg/implicits.scala                     |   40 +-
 test/files/neg/java-access-neg.check               |   16 +
 test/files/neg/java-access-neg/J.java              |   15 +
 test/files/neg/java-access-neg/S2.scala            |   61 +
 test/files/neg/lazy-override.check                 |    4 +-
 test/files/neg/migration28.check                   |    8 +
 test/files/neg/migration28.flags                   |    1 +
 test/files/neg/migration28.scala                   |   12 +
 test/files/neg/multi-array.check                   |    6 +-
 test/files/neg/multi-array.flags                   |    1 +
 test/files/neg/names-defaults-neg-ref.check        |   16 +
 test/files/neg/names-defaults-neg-ref.scala        |   26 +
 test/files/neg/names-defaults-neg.check            |  149 +
 test/files/neg/names-defaults-neg.scala            |  173 +
 test/files/neg/overload-msg.check                  |   13 +
 test/files/neg/overload-msg.scala                  |    4 +
 test/files/neg/overload.check                      |    8 +-
 test/files/neg/overload.scala                      |    2 +-
 test/files/neg/override.check                      |    5 +
 test/files/neg/override.scala                      |   15 +
 test/files/neg/parstar.check                       |    7 +
 test/{pending => files}/neg/parstar.scala          |    0
 test/files/neg/pat_unreachable.check               |    7 +
 test/files/neg/pat_unreachable.scala               |   20 +
 test/files/neg/patmat-type-check.check             |   21 +
 test/files/neg/patmat-type-check.scala             |   28 +
 test/files/neg/patmatexhaust.check                 |   11 +-
 test/files/neg/patmatexhaust.scala                 |   28 +-
 test/files/neg/patternalts.scala                   |    5 +-
 test/files/neg/sabin2.check                        |    2 +-
 test/files/neg/spec-overrides.check                |    7 +
 test/files/neg/spec-overrides.scala                |   26 +
 test/files/neg/structural.check                    |   44 +-
 test/files/neg/structural.scala                    |   57 +-
 test/files/neg/switch.check                        |   10 +
 test/files/neg/switch.scala                        |   66 +
 test/files/neg/t0003.check                         |    2 +-
 test/files/neg/t0015.check                         |    7 +-
 test/files/neg/t0015.scala                         |    2 +-
 test/files/neg/t0117.check                         |    2 +-
 test/files/neg/t0152.check                         |    2 +-
 test/files/neg/t0204.check                         |    2 +-
 test/files/neg/t0218.check                         |    2 +-
 test/files/neg/t0218.scala                         |    2 +-
 test/files/neg/t0226.check                         |    4 +-
 test/files/neg/t0259.check                         |    6 +-
 test/files/neg/t0345.check                         |    6 +-
 test/files/neg/t0351.check                         |    2 +-
 test/files/neg/t0528neg.scala                      |    2 +-
 test/files/neg/t0590.check                         |    5 +-
 test/files/neg/t0673.check                         |    4 +
 test/{pending => files}/neg/t0673/JavaClass.java   |    0
 test/{pending => files}/neg/t0673/Test.scala       |    0
 test/{pending => files}/neg/t0699.check            |    0
 test/files/neg/t0699/A.scala                       |    4 +
 test/files/neg/t0699/B.scala                       |    5 +
 test/files/neg/t0842.check                         |    2 +-
 test/files/neg/t1163.check                         |    4 +-
 test/files/neg/t1215.check                         |    2 +-
 test/files/neg/t1355.check                         |    4 +
 test/files/neg/t1355.scala                         |    1 +
 test/files/neg/t1422.check                         |    4 +
 test/files/neg/t1422.scala                         |    1 +
 test/files/neg/t1477.check                         |    5 +
 test/files/neg/t1477.scala                         |   25 +
 test/files/neg/t1659.check                         |    5 -
 test/files/neg/t1701.check                         |    4 +
 test/files/neg/t1701.scala                         |    1 +
 test/files/neg/t1705.check                         |    7 +
 test/files/neg/t1705.scala                         |   35 +
 test/files/neg/t2031.check                         |    6 +
 test/files/neg/t2031.scala                         |    9 +
 test/files/neg/t2130.check                         |    4 +
 test/files/neg/t2130.scala                         |    6 +
 test/files/neg/t2139.check                         |    6 +
 test/files/neg/t2139.scala                         |   15 +
 test/files/neg/t2179.check                         |    9 +
 test/files/neg/t2179.scala                         |    3 +
 test/files/neg/t2208.check                         |    4 +
 test/files/neg/t2208.scala                         |    8 +
 test/files/neg/t2316.check                         |    7 +
 test/files/neg/t2316.scala                         |   43 +
 test/files/neg/t2336.check                         |    4 +
 test/files/neg/t2336.scala                         |    7 +
 test/files/neg/t2386.check                         |    4 +
 test/files/neg/t2386.scala                         |    3 +
 test/files/neg/t2416.check                         |   10 +
 test/files/neg/t2416.scala                         |   14 +
 test/files/neg/t2421b.check                        |    4 +
 test/files/neg/t2421b.scala                        |   17 +
 test/files/neg/t2462a.check                        |    4 +
 test/files/neg/t2462a.scala                        |    3 +
 test/files/neg/t2462b.check                        |   14 +
 test/files/neg/t2462b.scala                        |   12 +
 test/files/neg/t2494.check                         |    4 +
 test/files/neg/t2494.scala                         |    1 +
 test/files/neg/t2641.check                         |   35 +
 test/files/neg/t2641.scala                         |   31 +
 test/files/neg/t2773.check                         |    7 +
 test/files/neg/t2773.scala                         |    8 +
 test/files/neg/t2775.check                         |    4 +
 test/files/neg/t2775.scala                         |    1 +
 test/files/neg/t2779.check                         |    4 +
 test/files/neg/t2779.scala                         |   25 +
 test/files/neg/t2801.check                         |    6 +
 test/files/neg/t2801.scala                         |    3 +
 test/files/neg/t2870.check                         |    7 +
 test/files/neg/t2870.scala                         |    9 +
 test/files/neg/t2918.check                         |    7 +
 test/files/neg/t2918.scala                         |    3 +
 test/files/neg/t3006.check                         |    6 +
 test/files/neg/t3006.scala                         |   10 +
 test/files/neg/t3015.check                         |   11 +
 test/files/neg/t3015.scala                         |    8 +
 test/files/neg/t3115.check                         |   10 +
 test/files/neg/t3115.flags                         |    1 +
 test/files/neg/t3115.scala                         |    9 +
 test/files/neg/t3118.check                         |    7 +
 test/files/neg/t3118.scala                         |    8 +
 test/files/neg/t3222.check                         |   13 +
 test/files/neg/t3222.scala                         |    9 +
 test/files/neg/t3224.check                         |    6 +
 test/files/neg/t3224.scala                         |   30 +
 test/files/neg/t3399.check                         |    4 +
 test/files/neg/t3399.scala                         |   24 +
 test/files/neg/t3403.check                         |    4 +
 test/files/neg/t3403.scala                         |    2 +
 test/files/neg/t3453.check                         |   21 +
 test/files/neg/t3453.scala                         |   66 +
 test/files/neg/t3507.check                         |    4 +
 test/files/neg/t3507.scala                         |   15 +
 test/files/neg/t3604.check                         |    7 +
 test/files/neg/t3604.scala                         |    6 +
 test/files/neg/t3653.check                         |    7 +
 test/files/neg/t3653.scala                         |    4 +
 test/files/neg/t3663.check                         |    4 +
 test/files/neg/t3663/PackageProtected.java         |    5 +
 test/files/neg/t3663/main.scala                    |   14 +
 test/files/neg/t3691.check                         |   16 +
 test/files/neg/t3691.scala                         |   11 +
 test/files/neg/t3692.check                         |   14 +
 test/files/neg/t3692.scala                         |   17 +
 test/files/neg/t3757.check                         |    4 +
 test/files/neg/t3757/A.java                        |    5 +
 test/files/neg/t3757/B.scala                       |    5 +
 test/files/neg/t3769.check                         |   10 +
 test/files/neg/t3769.scala                         |    3 +
 test/files/neg/t3773.check                         |    4 +
 test/files/neg/t3773.flags                         |    1 +
 test/files/neg/t3773.scala                         |    5 +
 test/files/neg/t3774.check                         |    7 +
 test/files/neg/t3774.scala                         |    5 +
 test/files/neg/t3776.check                         |    4 +
 test/files/neg/t3776.scala                         |   10 +
 test/files/neg/t3873.check                         |    6 +
 test/files/neg/t3873.flags                         |    1 +
 test/files/neg/t3873.scala                         |   12 +
 test/files/neg/t742.check                          |    5 +
 test/files/neg/t742.scala                          |    8 +
 test/files/neg/t771.check                          |    4 +
 test/files/neg/t771.scala                          |    5 +
 test/files/neg/tailrec.check                       |   16 +
 test/files/neg/tailrec.scala                       |   65 +
 test/files/neg/tcpoly_bounds.scala                 |    2 +-
 test/files/neg/tcpoly_infer_ticket1162.check       |    4 +
 test/files/neg/tcpoly_infer_ticket1162.scala       |    8 +
 test/files/neg/tcpoly_override.scala               |    2 +-
 test/files/neg/tcpoly_ticket2101.check             |    4 +
 test/files/neg/tcpoly_ticket2101.scala             |   28 +
 test/files/neg/tcpoly_variance.check               |    4 +-
 test/files/neg/tcpoly_variance.scala               |    2 +-
 test/files/neg/tcpoly_variance_enforce.check       |   22 +-
 test/files/neg/tcpoly_variance_enforce.scala       |    2 +-
 test/files/neg/ticket513.check                     |    4 +
 test/files/neg/ticket513.scala                     |    6 +
 test/files/neg/typeerror.check                     |    2 +-
 test/files/neg/unit2anyref.check                   |    8 +
 test/files/neg/unit2anyref.scala                   |    3 +
 test/files/neg/unreachablechar.check               |    2 +-
 test/files/neg/variances.check                     |   10 +-
 test/files/neg/variances.scala                     |   20 +
 test/files/neg/viewtest.check                      |    8 +-
 test/files/neg/viewtest.scala                      |   22 +-
 test/files/neg/wellkinded_app2.scala               |    2 +-
 test/files/neg/wellkinded_bounds.check             |    2 +-
 test/files/neg/wellkinded_bounds.scala             |    2 +-
 test/files/neg/wellkinded_wrongarity.scala         |    2 +-
 test/files/neg/wellkinded_wrongarity2.scala        |    2 +-
 test/files/neg/xmlcorner.check                     |    2 +-
 test/files/pos/NoCyclicReference.scala             |    7 +
 test/files/pos/annotations.scala                   |   87 +-
 test/files/pos/arrays2.scala                       |   12 +
 test/files/pos/attributes.scala                    |    9 +-
 test/files/pos/bounds.scala                        |    2 +-
 test/files/pos/bug0029.scala                       |    2 +-
 test/files/pos/bug0091.scala                       |    2 +-
 test/files/pos/bug0646.scala                       |    2 +-
 test/files/pos/bug1001.scala                       |    2 +-
 test/files/pos/bug1049.scala                       |    4 +-
 test/files/pos/bug1050.scala                       |    2 +-
 test/{pending => files}/pos/bug1070.scala          |    0
 test/files/pos/bug1075.scala                       |    2 +-
 test/files/pos/bug1085.scala                       |    2 +-
 test/files/pos/bug1090.scala                       |    6 +-
 test/files/pos/bug1136.check                       |    2 -
 test/files/pos/bug116.scala                        |    2 -
 test/files/pos/bug1185.scala                       |   15 +
 test/files/pos/bug1210a.scala                      |    2 +-
 test/files/pos/bug1272.scala                       |    9 +
 test/files/pos/bug1279a.scala                      |   40 +
 test/files/pos/bug1381.scala                       |   31 +
 test/files/pos/bug1385.scala                       |    3 +
 test/files/pos/bug1560.scala                       |   11 +
 test/files/pos/bug1565.scala                       |   18 +
 test/files/pos/bug160.scala                        |    2 -
 test/files/pos/bug1626.scala                       |    4 +
 test/files/pos/bug1737/A.java                      |    3 +
 test/files/pos/bug1737/B.java                      |    1 +
 test/files/pos/bug1737/c.scala                     |    4 +
 test/files/pos/bug175.scala                        |    2 -
 test/files/pos/bug177.scala                        |    2 -
 test/files/pos/bug183.scala                        |    2 -
 test/files/pos/bug1843.scala                       |   25 +
 test/files/pos/bug1858.scala                       |   13 +
 test/files/pos/bug1909.scala                       |    8 +
 test/files/pos/bug1909b.scala                      |    6 +
 test/files/pos/bug2018.scala                       |   15 +
 test/files/pos/bug2023.scala                       |   16 +
 test/files/pos/bug2081.scala                       |   11 +
 test/files/pos/bug2127.scala                       |    5 +
 test/files/pos/bug2168.scala                       |    6 +
 test/files/pos/bug2187-2.scala                     |    7 +
 test/files/pos/bug2187.scala                       |    7 +
 test/files/pos/bug2260.scala                       |   10 +
 test/files/pos/bug2261.scala                       |    6 +
 test/files/pos/bug2310.scala                       |   38 +
 test/files/pos/bug2409/J.java                      |    4 +
 test/files/pos/bug2409/bug2409.scala               |    1 +
 test/files/pos/bug247.scala                        |    5 +-
 test/files/pos/bug2486.scala                       |    3 +
 test/files/pos/bug252.scala                        |   17 +
 test/files/pos/bug2691.scala                       |   10 +
 test/files/pos/bug284.scala                        |    5 +
 test/files/pos/bug287.scala                        |    2 +-
 test/files/pos/bug289.scala                        |    2 -
 test/files/pos/bug2939.scala                       |   13 +
 test/files/pos/bug2945.scala                       |   12 +
 test/files/pos/bug3020.scala                       |    9 +
 test/files/pos/bug3097.flags                       |    1 +
 test/files/pos/bug3097.scala                       |   31 +
 test/files/pos/bug3136.scala                       |   19 +
 test/files/pos/bug3175.scala                       |    7 +
 test/files/pos/bug318.scala                        |    2 -
 test/files/pos/bug3252.flags                       |    1 +
 test/files/pos/bug3252.scala                       |   15 +
 test/files/pos/bug3278.scala                       |   15 +
 test/files/pos/bug3411.scala                       |    8 +
 test/files/pos/bug3420.flags                       |    1 +
 test/files/pos/bug3420.scala                       |    5 +
 test/files/pos/bug3430.flags                       |    1 +
 test/files/pos/bug3430.scala                       |   13 +
 test/files/pos/bug3480.scala                       |    4 +
 test/files/pos/bug3495.flags                       |    1 +
 test/files/pos/bug3495.scala                       |    2 +
 test/files/pos/bug3521/DoubleValue.java            |    7 +
 test/files/pos/bug3521/a.scala                     |    4 +
 test/files/pos/bug3568.scala                       |   46 +
 test/files/pos/bug3570.scala                       |    7 +
 test/files/pos/bug3578.scala                       |   30 +
 test/files/pos/bug359.scala                        |    2 -
 test/files/pos/bug360.scala                        |    2 -
 test/files/pos/bug361.scala                        |    2 -
 test/files/pos/bug372.scala                        |    2 -
 test/files/pos/bug430-feb09.scala                  |   34 +
 test/files/pos/bug432.scala                        |    2 +-
 test/files/pos/bug460.scala                        |    9 +
 test/files/pos/bug516.scala                        |    5 +-
 test/files/pos/bug703.scala                        |    2 +-
 test/files/pos/bug715.cmds                         |    2 +
 test/files/pos/bug715/meredith_1.scala             |   98 +
 test/files/pos/bug715/runner_2.scala               |    3 +
 test/files/pos/bug756.scala                        |    6 +
 test/files/pos/bug927.scala                        |    4 +-
 test/files/pos/builders.scala                      |   66 +
 test/files/pos/caseClassInMethod.scala             |    5 +
 test/files/{pos5 => pos}/chang/Outer.java          |    0
 test/files/{pos5 => pos}/chang/Test.scala          |    0
 test/files/pos/cls.scala                           |    2 +-
 test/files/pos/clsrefine.scala                     |    2 +-
 test/files/pos/collectGenericCC.scala              |   14 +
 test/files/pos/collections.scala                   |    6 +-
 test/files/pos/compile.scala                       |    1 -
 test/files/pos/compile1.scala                      |    1 -
 test/files/pos/context.scala                       |   38 +
 test/files/pos/context.scala.disabled              |   34 -
 test/files/pos/cyclics.scala                       |   26 +
 test/files/pos/depexists.scala                     |    5 +
 test/files/pos/depmet_1.flags                      |    1 +
 test/files/pos/depmet_1.scala                      |    6 +
 test/files/pos/depmet_implicit_chaining_zw.flags   |    1 +
 test/files/pos/depmet_implicit_chaining_zw.scala   |   28 +
 test/files/pos/depmet_implicit_norm_ret.flags      |    1 +
 test/files/pos/depmet_implicit_norm_ret.scala      |   29 +
 .../files/pos/depmet_implicit_oopsla_session.flags |    1 +
 .../files/pos/depmet_implicit_oopsla_session.scala |   63 +
 .../pos/depmet_implicit_oopsla_session_2.flags     |    1 +
 .../pos/depmet_implicit_oopsla_session_2.scala     |   87 +
 .../depmet_implicit_oopsla_session_simpler.flags   |    1 +
 .../depmet_implicit_oopsla_session_simpler.scala   |   44 +
 .../files/pos/depmet_implicit_oopsla_zipwith.flags |    1 +
 .../files/pos/depmet_implicit_oopsla_zipwith.scala |   44 +
 test/files/pos/depmet_implicit_tpbetareduce.flags  |    1 +
 test/files/pos/depmet_implicit_tpbetareduce.scala  |   12 +
 test/files/pos/eta.scala                           |    2 -
 test/files/pos/exbound.scala                       |    7 +
 test/files/pos/ilya/J.java                         |   14 +
 test/files/pos/ilya/S.scala                        |    5 +
 test/files/{pos5 => pos}/ilya2/A.scala             |    0
 test/files/{pos5 => pos}/ilya2/B.java              |    0
 test/files/{pos5 => pos}/ilya2/Nullable.java       |    0
 test/files/pos/implicits.scala                     |   89 +
 test/files/pos/imports.scala                       |    2 +-
 test/files/pos/java-access-pos/J.java              |   15 +
 test/files/pos/java-access-pos/S1.scala            |   67 +
 test/files/pos/jesper.scala                        |   30 -
 test/files/pos/lambdalift.scala                    |    2 +-
 test/files/pos/lambdalift1.scala                   |    2 +-
 test/files/pos/lexical.scala                       |    9 +
 test/files/pos/looping-jsig.scala                  |    2 +-
 test/files/pos/manifest1.scala                     |    7 +-
 test/files/pos/michel3.scala                       |    2 +-
 test/files/pos/nested2.scala                       |    2 +-
 test/files/pos/nothing_manifest_disambig.scala     |   10 +
 test/files/pos/null.scala                          |    2 +-
 test/files/pos/nullary.scala                       |    2 +-
 test/files/pos/nullary_poly.scala                  |    2 +-
 test/files/pos/packageobjs.scala                   |    8 +
 test/files/pos/patterns2.scala                     |    2 +-
 test/files/pos/philippe1.scala                     |    2 +-
 test/files/pos/philippe2.scala                     |    2 -
 test/files/pos/relax_implicit_divergence.scala     |    7 +
 test/files/pos/scala-singleton.scala               |   55 +
 test/files/pos/scan.scala                          |   23 +
 test/files/pos/scoping3.scala                      |    2 -
 test/files/pos/selftails.scala                     |   23 +
 test/files/pos/signatures/Test.java                |   11 +
 test/files/pos/signatures/sig.scala                |   12 +
 test/files/pos/spec-Function1.scala                |   48 +
 test/files/pos/spec-List.scala                     |  869 +++
 test/files/pos/spec-annotations.scala              |   35 +
 test/files/pos/spec-arrays.scala                   |  214 +
 test/files/pos/spec-asseenfrom.scala               |   29 +
 test/files/pos/spec-constr.scala                   |    7 +
 test/files/pos/spec-cyclic.scala                   |   33 +
 test/files/pos/spec-doubledef.scala                |   28 +
 test/files/pos/spec-example1.scala                 |   17 +
 test/files/pos/spec-fields.scala                   |   10 +
 test/files/pos/spec-foo.scala                      |    4 +
 test/files/pos/spec-funs.scala                     |   63 +
 test/files/pos/spec-lists.scala                    |    6 +
 test/files/pos/spec-localdefs.scala                |    7 +
 test/files/pos/spec-maps.scala                     |   10 +
 test/files/pos/spec-multiplectors.scala            |    3 +
 test/files/pos/spec-params.scala                   |   32 +
 test/files/pos/spec-partially.scala                |    5 +
 test/files/pos/spec-partialmap.scala               |   17 +
 test/files/pos/spec-polymeth.scala                 |    8 +
 test/files/pos/spec-private.scala                  |   10 +
 test/files/pos/spec-sealed.scala                   |   32 +
 test/files/pos/spec-short.scala                    |   26 +
 test/files/pos/spec-simple.scala                   |   51 +
 test/files/pos/spec-sparsearray.scala              |   24 +
 test/files/pos/spec-super.scala                    |   20 +
 test/files/pos/spec-t3497.scala                    |   16 +
 test/files/pos/spec-tailcall.scala                 |   17 +
 test/files/pos/spec-thistype.scala                 |    3 +
 test/files/pos/spec-vector.scala                   |    4 +
 test/files/pos/strings.scala                       |    4 +
 test/files/pos/sudoku.scala                        |    2 +-
 test/files/pos/super.cmds                          |    2 +
 test/files/pos/super/Super_1.java                  |    6 +
 test/files/pos/super/Super_2.scala                 |    6 +
 test/files/pos/switchUnbox.flags                   |    1 +
 test/files/pos/switchUnbox.scala                   |   11 +
 test/files/pos/t0165.scala                         |    2 +-
 test/files/pos/t0586.scala                         |    2 +-
 test/files/pos/t0591.scala                         |    2 +-
 test/files/pos/t0612/C.scala                       |    6 +
 test/{pending => files}/pos/t0612/Ob.scala         |    0
 test/files/pos/t0674.scala                         |   11 +-
 test/files/{pos5 => pos}/t0695/JavaClass.java      |    0
 test/files/{pos5 => pos}/t0695/Test.scala          |    0
 test/files/pos/t0710.scala                         |    2 +-
 test/files/pos/t0816.scala                         |   12 +
 test/files/pos/t0851.scala                         |   14 -
 test/files/pos/t0872.scala                         |    8 -
 test/files/pos/t0971.java                          |    4 -
 test/files/pos/t0999.scala                         |    5 -
 test/{pending => files}/pos/t1000.scala            |    0
 test/files/pos/t1029.cmds                          |    2 +
 test/files/pos/t1029/Test_1.scala                  |    7 +
 test/files/pos/t1029/Test_2.scala                  |    3 +
 test/files/pos/t1035.scala                         |   32 +
 test/files/pos/t1049.scala                         |    9 -
 test/{pending => files}/pos/t1053.scala            |    0
 test/files/pos/t1087.scala                         |    3 -
 test/files/{pos5 => pos}/t1101/J.java              |    0
 test/files/{pos5 => pos}/t1101/S.scala             |    0
 test/files/{pos5 => pos}/t1102/J.java              |    0
 test/files/{pos5 => pos}/t1102/S.scala             |    0
 test/files/pos/t1107/O.scala                       |   13 +
 test/files/pos/t1107/T.scala                       |    7 +
 test/files/pos/t1147.scala                         |    2 +-
 test/files/{pos5 => pos}/t1150/J.java              |    0
 test/files/{pos5 => pos}/t1150/S.scala             |    0
 test/files/{pos5 => pos}/t1152/J.java              |    0
 test/files/{pos5 => pos}/t1152/S.scala             |    0
 test/files/pos/t1164.scala                         |   29 +
 test/files/{pos5 => pos}/t1176/J.java              |    0
 test/files/{pos5 => pos}/t1176/S.scala             |    0
 test/files/pos/t1186/t1186.java                    |    8 +
 test/files/{pos5 => pos}/t1196/J.java              |    0
 test/files/{pos5 => pos}/t1196/S.scala             |    0
 test/files/{pos5 => pos}/t1197/J.java              |    0
 test/files/{pos5 => pos}/t1197/S.scala             |    0
 test/files/{pos5 => pos}/t1203/J.java              |    0
 test/files/{pos5 => pos}/t1203/S.scala             |    0
 test/files/pos/t1226.scala                         |    8 +
 test/files/pos/t1230/J.java                        |    1 +
 test/files/pos/t1230/S.scala                       |    1 +
 test/files/pos/t1231/J.java                        |    1 +
 test/files/pos/t1231/S.scala                       |    1 +
 test/files/pos/t1232/J.java                        |    2 +
 test/files/pos/t1232/J2.java                       |    2 +
 test/files/pos/t1232/S.scala                       |    2 +
 test/files/{pos5 => pos}/t1235/Test.java           |    0
 test/files/pos/t1236.scala                         |   14 +
 test/files/pos/t1254/t1254.java                    |   28 +
 test/files/pos/t1260.scala                         |   18 +
 test/files/{pos5 => pos}/t1263/Test.java           |    0
 test/files/{pos5 => pos}/t1263/test.scala          |    0
 test/files/pos/t1380.flags                         |    1 -
 .../{pending => files}/pos/t1409/AbstractImpl.java |    0
 .../pos/t1409/ConcreteImpl.scala                   |    0
 .../pos/t1409/OuterInterface.java                  |    0
 test/files/pos/t1422.scala                         |    2 +
 test/{pending => files}/pos/t1438.scala            |    0
 test/{pending => files}/pos/t1439.scala            |    0
 test/files/pos/t1459/AbstractBase.java             |    5 +
 test/files/pos/t1459/App.scala                     |   18 +
 test/files/pos/t1459/Caller.java                   |    7 +
 test/files/pos/t1545.scala                         |   16 +
 test/files/pos/t1560.scala                         |   13 +
 test/files/pos/t1569.flags                         |    1 +
 test/files/pos/t1569.scala                         |    5 +
 test/files/pos/t1614/bar.scala                     |    4 +
 test/files/pos/t1614/foo.scala                     |   12 +
 test/files/pos/t1642/JavaCallingScalaHashMap.java  |    8 +
 test/files/pos/t1642/test.scala                    |    6 +
 test/files/{neg => pos}/t1659.scala                |    0
 test/files/pos/t1675.scala                         |   11 +
 test/files/pos/t1693.scala                         |    9 +
 test/files/{pos5 => pos}/t1711/Seq.scala           |    0
 test/files/{pos5 => pos}/t1711/Test.java           |    0
 test/files/pos/t1722-A.scala                       |   10 +
 test/files/pos/t1722/Test.scala                    |    5 +
 test/files/pos/t1722/Top.scala                     |   13 +
 test/files/pos/t1745/J.java                        |   10 +
 test/files/pos/t1745/S.scala                       |    7 +
 test/files/pos/t1751.cmds                          |    3 +
 test/files/pos/t1751/A1_2.scala                    |    2 +
 test/files/pos/t1751/A2_1.scala                    |    2 +
 test/files/pos/t1751/SuiteClasses.java             |    3 +
 test/files/pos/t1756.scala                         |   54 +
 test/files/pos/t1761.scala                         |   10 +
 test/files/pos/t1782.cmds                          |    2 +
 test/files/pos/t1782/Ann.java                      |    3 +
 test/files/pos/t1782/Days.java                     |    3 +
 test/files/pos/t1782/ImplementedBy.java            |    3 +
 test/files/pos/t1782/Test_1.scala                  |   16 +
 test/files/pos/t1789.scala                         |    5 +
 test/files/pos/t1798.scala                         |   10 +
 test/files/pos/t1836/J.java                        |    1 +
 test/files/pos/t1836/S.scala                       |    1 +
 test/files/pos/t1840/J.java                        |    4 +
 test/files/pos/t1840/S.scala                       |    2 +
 test/files/pos/t1896/D0.scala                      |   11 +
 test/files/pos/t1896/D1.scala                      |    2 +
 test/files/pos/t1937/NumberGenerator.java          |    7 +
 test/files/pos/t1942.cmds                          |    2 +
 test/files/pos/t1942/A_1.scala                     |   11 +
 test/files/pos/t1942/Test_2.scala                  |    3 +
 test/files/pos/t1987.scala                         |    8 +
 test/files/pos/t1996.scala                         |   19 +
 test/files/pos/t2023.scala                         |   16 +
 test/files/pos/t2060.scala                         |   44 +
 test/files/pos/t2082.scala                         |   39 +
 test/files/pos/t2133.scala                         |   18 +
 test/files/pos/t2183.scala                         |    5 +
 test/files/pos/t2208.scala                         |    8 +
 test/files/pos/t2234.scala                         |    4 +
 test/files/pos/t2261.scala                         |    9 +
 test/files/pos/t2293.scala                         |    5 +
 test/files/pos/t2305.scala                         |   26 +
 test/files/pos/t2331.scala                         |   11 +
 test/files/pos/t2377/Q.java                        |   12 +
 test/files/pos/t2377/a.scala                       |    8 +
 test/files/pos/t2413/TestJava.java                 |    7 +
 test/files/pos/t2413/TestScalac.scala              |   23 +
 test/files/pos/t2421.scala                         |   14 +
 test/files/pos/t2421_delitedsl.scala               |   37 +
 test/files/pos/t2421b.scala                        |   19 +
 test/files/pos/t2421c.scala                        |   17 +
 test/files/pos/t2425.scala                         |   15 +
 test/files/pos/t2429.scala                         |   25 +
 test/files/pos/t2433/A.java                        |    4 +
 test/files/pos/t2433/B.java                        |    4 +
 test/files/pos/t2433/Test.scala                    |    3 +
 test/files/pos/t2444.scala                         |   15 +
 test/files/pos/t2454.scala                         |   25 +
 test/files/pos/t2464.cmds                          |    3 +
 test/files/pos/t2464/JavaOne.java                  |    5 +
 test/files/pos/t2464/ScalaOne_1.scala              |    6 +
 test/files/pos/t2464/t2464_2.scala                 |    3 +
 test/files/pos/t2484.scala                         |   17 +
 test/files/pos/t2500.scala                         |    6 +
 test/files/pos/t2504.scala                         |    5 +
 test/files/pos/t2545.scala                         |   10 +
 test/files/pos/t2569/Child.scala                   |    9 +
 test/files/pos/t2569/Parent.java                   |   13 +
 test/files/pos/t2591.scala                         |   15 +
 test/files/pos/t2610.scala                         |   17 +
 test/files/pos/t2619.scala                         |   80 +
 test/files/pos/t2624.scala                         |    4 +
 test/files/pos/t2635.scala                         |   16 +
 test/files/pos/t2660.scala                         |   25 +
 test/files/pos/t2664.scala                         |    9 +
 test/files/pos/t2665.scala                         |    3 +
 test/files/pos/t2667.scala                         |    6 +
 test/files/pos/t2669.scala                         |   28 +
 test/files/pos/t2673.scala                         |    4 +
 test/files/pos/t2683.scala                         |    7 +
 test/files/pos/t2691.scala                         |    9 +
 test/files/pos/t2698.scala                         |   10 +
 test/files/pos/t2708.scala                         |    1 +
 test/files/pos/t2726.cmds                          |    2 +
 test/files/pos/t2726/SQLBuilder_1.scala            |    7 +
 test/files/pos/t2726/test_2.scala                  |    3 +
 test/files/pos/t2741/2741-1.scala                  |   13 +
 test/files/pos/t2741/2741-2.scala                  |    5 +
 test/files/pos/t2794.scala                         |    9 +
 test/files/pos/t2795.scala                         |   17 +
 test/files/pos/t2797.scala                         |    9 +
 test/files/pos/t2799.flags                         |    1 +
 test/files/pos/t2799.scala                         |    1 +
 test/files/pos/t2809.scala                         |   20 +
 test/files/pos/t2810.scala                         |    8 +
 test/files/pos/t2868.cmds                          |    3 +
 test/files/pos/t2868/Jann.java                     |    5 +
 test/files/pos/t2868/Nest.java                     |    3 +
 test/files/pos/t2868/pick_1.scala                  |    7 +
 test/files/pos/t2868/test_2.scala                  |    6 +
 test/files/pos/t2913.scala                         |   53 +
 test/files/pos/t294.cmds                           |    3 +
 test/files/pos/t294/Ann.java                       |    3 +
 test/files/pos/t294/Ann2.java                      |    3 +
 test/files/pos/t294/Test_1.scala                   |    7 +
 test/files/pos/t294/Test_2.scala                   |    1 +
 test/files/pos/t2940/Cycle.java                    |    3 +
 test/files/pos/t2940/Error.scala                   |   12 +
 test/files/pos/t2956/BeanDefinitionVisitor.java    |    6 +
 test/files/pos/t2956/t2956.scala                   |    7 +
 test/files/pos/t2994a.scala                        |   27 +
 test/files/pos/t2994b.scala                        |    7 +
 test/files/pos/t3037.scala                         |   13 +
 test/files/pos/t3071.scala                         |    7 +
 test/files/pos/t3076/C2.scala                      |    4 +
 test/files/pos/t3076/T.scala                       |    2 +
 test/files/pos/t3079.scala                         |   17 +
 test/files/pos/t3108.scala                         |    5 +
 test/files/pos/t3152.scala                         |   20 +
 test/files/pos/t3174.scala                         |   14 +
 test/files/pos/t3174b.scala                        |   12 +
 test/files/pos/t3177.scala                         |   39 +
 test/files/pos/t3249/Test.java                     |    5 +
 test/files/pos/t3249/a.scala                       |   11 +
 test/files/pos/t3274.scala                         |    9 +
 test/files/pos/t3349/AbstractTupleSet.java         |    9 +
 test/files/pos/t3349/Table.java                    |    9 +
 test/files/pos/t3349/Test.scala                    |    5 +
 test/files/pos/t3349/TupleSet.java                 |    4 +
 test/files/pos/t3363.scala                         |   18 +
 test/files/pos/t3373.scala                         |   11 +
 test/files/pos/t3374.scala                         |    6 +
 test/files/pos/t3384.scala                         |   14 +
 test/files/pos/t3404/Base.java                     |    3 +
 test/files/pos/t3404/Derived.scala                 |    3 +
 test/files/pos/t3417.scala                         |   11 +
 test/files/pos/t3419/B_1.scala                     |    3 +
 test/files/pos/t3419/C_2.scala                     |    3 +
 test/files/pos/t3429/A.scala                       |   12 +
 test/files/pos/t3429/Test.java                     |    3 +
 test/files/pos/t3477.scala                         |    7 +
 test/files/pos/t3486/JTest.java                    |    3 +
 test/files/pos/t3486/test.scala                    |    6 +
 test/files/pos/t3494.scala                         |    7 +
 test/files/pos/t3560.scala                         |    2 +
 test/files/pos/t3568.scala                         |   46 +
 test/files/pos/t3582.scala                         |   12 +
 test/files/pos/t3582b.scala                        |    5 +
 test/files/pos/t3612.scala                         |    6 +
 test/files/pos/t3622/test/AsyncTask.java           |    5 +
 test/files/pos/t3622/test/MyAsyncTask.java         |    9 +
 test/files/pos/t3622/test/Test.scala               |    5 +
 test/files/pos/t3676.scala                         |    5 +
 test/files/pos/t3688.scala                         |    9 +
 test/files/pos/t3731.scala                         |   13 +
 test/files/pos/t3777.scala                         |    7 +
 test/files/pos/t3859.scala                         |    4 +
 test/files/pos/t3864/scalaz_2.scala                |    1 +
 test/files/pos/t3864/tuples_1.scala                |   78 +
 test/{pending => files}/pos/t425.scala             |    0
 test/files/pos/tcpoly_boundedmonad.scala           |    2 +-
 test/files/pos/tcpoly_bounds1.scala                |    2 +-
 test/files/pos/tcpoly_checkkinds_mix.scala         |    2 +-
 test/files/pos/tcpoly_gm.scala                     |    2 +-
 test/files/pos/tcpoly_infer_easy.scala             |    5 +
 .../pos/tcpoly_infer_explicit_tuple_wrapper.scala  |   16 +
 .../pos/tcpoly_infer_implicit_tuple_wrapper.scala  |   18 +
 test/files/pos/tcpoly_infer_ticket1864.scala       |   51 +
 test/files/pos/tcpoly_infer_ticket474.scala        |   27 +
 test/files/pos/tcpoly_infer_ticket716.scala        |   26 +
 test/files/pos/tcpoly_late_method_params.scala     |    2 +-
 test/files/pos/tcpoly_method.scala                 |    2 +-
 test/files/pos/tcpoly_overloaded.scala             |    2 +-
 test/files/pos/tcpoly_param_scoping.scala          |    2 +-
 test/files/pos/tcpoly_return_overriding.scala      |    2 +-
 test/files/pos/tcpoly_seq.scala                    |   12 +-
 test/files/pos/tcpoly_seq_typealias.scala          |   12 +-
 test/files/pos/tcpoly_subst.scala                  |    2 +-
 test/files/pos/tcpoly_ticket2096.scala             |   30 +
 test/files/pos/tcpoly_typeapp.scala                |    2 +-
 test/files/pos/tcpoly_typesub.scala                |    2 +-
 test/files/pos/tcpoly_variance.scala               |    2 +-
 test/files/pos/tcpoly_wildcards.scala              |    2 +-
 test/files/pos/test2.scala                         |    2 +-
 test/files/pos/test5refine.scala                   |    2 +-
 test/files/pos/thistypes.scala                     |    2 +-
 test/files/pos/ticket0137.scala                    |    2 +-
 test/files/pos/ticket2197.scala                    |    7 +
 test/files/pos/ticket2201.scala                    |    8 +
 test/files/pos/ticket2251.scala                    |   25 +
 test/files/pos/tryexpr.scala                       |   10 +
 test/files/pos/typealias_dubious.scala             |    2 +-
 test/files/pos/typesafecons.scala                  |    2 +-
 test/files/pos/unapplyComplex.scala                |    4 +-
 test/files/pos/unapplyGeneric.scala                |    4 +-
 test/files/pos5/ilya/J.java                        |   14 -
 test/files/pos5/ilya/S.scala                       |    5 -
 test/files/pos5/misc-pos.log                       |    4 -
 test/files/pos5/t1186.java                         |    8 -
 test/files/pos5/t1230/J.java                       |    1 -
 test/files/pos5/t1230/S.scala                      |    1 -
 test/files/pos5/t1231/J.java                       |    1 -
 test/files/pos5/t1231/S.scala                      |    1 -
 test/files/pos5/t1232/J.java                       |    2 -
 test/files/pos5/t1232/J2.java                      |    2 -
 test/files/pos5/t1232/S.scala                      |    2 -
 test/files/positions/Anon.scala                    |    9 +
 .../{jvm5/bug680.check => positions/Empty.scala}   |    0
 test/files/positions/Enclosing1.scala              |    5 +
 test/files/positions/Enclosing2.scala              |    5 +
 test/files/positions/Enclosing3.scala              |    1 +
 test/files/positions/Enclosing4.scala              |    1 +
 test/files/positions/ExcludedPrefix1.scala         |   41 +
 test/files/positions/MultipleDefs1.scala           |    3 +
 test/files/positions/New1.scala                    |    3 +
 test/files/positions/Overlap1.scala                |    5 +
 test/files/positions/Overlap2.scala                |    3 +
 test/files/positions/Overlap3.scala                |    3 +
 test/files/positions/Overlap4.scala                |    3 +
 test/files/positions/Overlap5.scala                |    3 +
 test/files/positions/Overlap6.scala                |    3 +
 test/files/positions/Overlap7.scala                |    3 +
 test/files/positions/Scaladoc1.scala               |    8 +
 test/files/positions/Scaladoc2.scala               |   16 +
 test/files/positions/Scaladoc3.scala               |    8 +
 test/files/positions/Scaladoc4.scala               |    8 +
 test/files/positions/Scaladoc5.scala               |    8 +
 test/files/positions/Scaladoc6.scala               |   10 +
 test/files/positions/Scaladoc7.scala               |    6 +
 test/files/positions/Scaladoc8.scala               |    6 +
 test/files/positions/SyntheticNonSynthetic1.scala  |    3 +
 test/files/positions/SyntheticNonSynthetic2.scala  |    3 +
 test/files/positions/Unpositioned1.scala           |    3 +
 test/files/positions/Unsupported1.scala            |    3 +
 test/files/positions/Unsupported2.scala            |    5 +
 test/files/res/bug597.check                        |    2 +-
 test/files/res/bug687.check                        |    8 +-
 test/files/res/bug687/QueryB.scala                 |    2 +-
 test/files/res/bug722.check                        |    2 +-
 test/files/res/bug722/IfElse.scala                 |    2 +-
 test/files/res/bug735.check                        |    2 +-
 test/files/res/bug735/ScalaTyper.scala             |    2 +-
 test/files/res/bug743.check                        |    2 +-
 test/files/res/bug785.check                        |    2 +-
 test/files/res/bug831.check                        |    2 +-
 test/files/res/bug831/NewScalaTestXXX.scala        |    2 +-
 test/files/run/Course-2002-01.scala                |    1 -
 test/files/run/Course-2002-02.scala                |    1 -
 test/files/run/Course-2002-03.scala                |    1 -
 test/files/run/Course-2002-04.scala                |    1 -
 test/files/run/Course-2002-05.scala                |    1 -
 test/files/run/Course-2002-06.scala                |    1 -
 test/files/run/Course-2002-07.scala                |    1 -
 test/files/run/Course-2002-08.scala                |    1 -
 test/files/run/Course-2002-09.scala                |    9 +-
 test/files/run/Course-2002-10.scala                |    1 -
 test/files/run/Course-2002-13.scala                |    5 +-
 test/files/run/MutableListTest.scala               |  126 +
 test/files/run/NestedClasses.scala                 |    1 -
 test/files/run/OrderingTest.scala                  |   36 +
 test/files/run/QueueTest.scala                     |  297 +
 test/files/run/ReplacementMatching.scala           |   47 +
 test/files/run/ReverseSeqView.scala                |   25 +
 test/files/run/SymbolsTest.scala                   |  283 +
 test/files/run/adding-growing-set.scala            |   11 +
 test/files/run/arrayclone.scala                    |  106 +
 test/files/run/arraycopy.scala                     |   31 +
 test/files/run/arrays.check                        |    2 +-
 test/files/run/arrays.scala                        |   16 +-
 test/files/run/arybufgrow.scala                    |    4 +-
 test/files/run/bigDecimalCache.scala               |    9 +
 test/files/run/bitsets-msil.check                  |   32 +-
 test/files/run/bitsets.check                       |   32 +-
 test/files/run/bitsets.scala                       |   37 +-
 test/files/run/boolexprs.scala                     |    1 -
 test/files/run/breakout.check                      |    1 +
 test/files/run/breakout.scala                      |    9 +
 test/files/run/bridges.scala                       |    1 -
 test/files/run/bug1005.check                       |    2 +
 test/files/run/bug1005.scala                       |   19 +
 test/files/run/bug1044.scala                       |    4 +
 test/files/run/bug1074.check                       |    2 +-
 test/{pending => files}/run/bug1079.check          |    0
 test/files/run/bug1079.scala                       |    3 +
 test/files/run/bug1110.scala                       |   11 +
 test/files/run/bug1141.check                       |    2 +
 test/files/run/bug1141.scala                       |    7 +
 test/files/run/bug1192.scala                       |    2 +-
 test/files/run/bug1300.check                       |    1 +
 test/files/run/bug1300.scala                       |   13 +
 test/files/run/bug1309.scala                       |    7 +
 test/files/run/bug1360.check                       |    2 +
 test/files/run/bug1360.scala                       |    7 +
 test/files/run/bug1373.scala                       |    6 +
 test/files/run/bug1434.scala                       |   15 +
 test/files/run/bug1466.scala                       |   11 +
 test/files/run/bug1766.scala                       |   16 +
 test/files/run/bug2005.scala                       |   10 +
 test/files/run/bug2029.check                       |    3 +
 test/files/run/bug2029.scala                       |   16 +
 test/files/run/bug2075.scala                       |    7 +
 test/files/run/bug2124.check                       |    1 +
 test/files/run/bug2124.scala                       |   25 +
 test/files/run/bug2125.check                       |    1 +
 test/files/run/bug2125.scala                       |   25 +
 test/files/run/bug2175.scala                       |   20 +
 test/files/run/bug2241.scala                       |    7 +
 test/files/run/bug2250.scala                       |   12 +
 test/files/run/bug2276.check                       |    8 +
 test/files/run/bug2276.scala                       |   24 +
 test/files/run/bug2354.scala                       |   17 +
 test/files/run/bug2378.scala                       |    9 +
 test/files/run/bug2512.scala                       |   14 +
 test/files/run/bug2514.scala                       |   15 +
 test/files/run/bug2552.check                       |   48 +
 test/files/run/bug2552.scala                       |   34 +
 test/files/run/bug2636.scala                       |   35 +
 test/files/run/bug2721.check                       |    2 +
 test/files/run/bug2721.scala                       |   12 +
 test/files/run/bug2876.scala                       |    7 +
 test/files/run/bug2958.scala                       |   16 +
 test/files/run/bug298.check                        |    2 +
 test/files/run/bug298.scala                        |   17 +
 test/files/run/bug3004.scala                       |   14 +
 test/files/run/bug3126.scala                       |    9 +
 test/files/run/bug3175.check                       |   11 +
 test/files/run/bug3175.scala                       |   55 +
 test/files/run/bug3269.check                       |    2 +
 test/files/run/bug3269.scala                       |    9 +
 test/files/run/bug3327.check                       |    1 +
 test/files/run/bug3327.scala                       |    8 +
 test/files/run/bug3395.check                       |    2 +
 test/files/run/bug3395.scala                       |   13 +
 test/files/run/bug3397.scala                       |    7 +
 test/files/run/bug3516.check                       |    3 +
 test/files/run/bug3516.scala                       |   13 +
 test/files/run/bug3529.scala                       |   14 +
 test/files/run/bug3540.scala                       |    7 +
 test/files/run/bug3563.scala                       |   21 +
 test/files/run/bug3616.check                       |    1 +
 test/files/run/bug3616.scala                       |   12 +
 test/files/run/bug363.check                        |    1 +
 test/files/run/bug363.scala                        |    9 +
 test/files/run/bug408.scala                        |   12 +
 test/files/run/bug429.check                        |    2 +-
 test/files/run/bug594.scala                        |    4 +-
 test/files/run/bug627.check                        |    2 +-
 test/files/run/bug627.scala                        |    2 +-
 test/files/run/bug751.scala                        |    6 +
 test/files/run/bugs.scala                          |    1 -
 test/files/run/bugs2087-and-2400.scala             |   20 +
 test/files/run/bytecodecs.scala                    |   39 +
 test/files/run/caseClassEquality.scala             |   36 +
 test/files/run/caseclasses.scala                   |    6 -
 test/files/run/castsingleton.check                 |    2 +
 test/files/run/castsingleton.scala                 |   11 +
 test/files/run/classof.check                       |    4 +-
 test/files/run/collection-stacks.check             |   14 -
 test/files/run/collection-stacks.scala             |   38 -
 test/files/run/collections.check                   |    4 -
 test/files/run/collections.scala                   |    1 -
 test/files/run/colltest.scala                      |    4 +-
 test/files/run/colltest1.check                     |  109 +
 test/files/run/colltest1.scala                     |  237 +
 test/{pending => files}/run/complicatedmatch.check |    0
 test/{pending => files}/run/complicatedmatch.scala |    0
 test/files/run/concurrent-stream.check             |    3 +
 test/files/run/concurrent-stream.scala             |   36 +
 test/files/run/constrained-types.check             |   16 +-
 test/files/run/constrained-types.scala             |    5 +-
 test/files/run/constructors.scala                  |    2 -
 test/files/run/deeps.check                         |   83 -
 test/files/run/deeps.scala                         |  112 -
 test/files/run/distinct.check                      |    1 +
 test/files/run/distinct.scala                      |   15 +
 test/files/run/docgenerator.scala                  |  288 -
 test/files/run/elidable.check                      |    1 +
 test/files/run/elidable.flags                      |    1 +
 test/files/run/elidable.scala                      |   16 +
 test/files/run/enums.check                         |    1 +
 test/files/run/enums.scala                         |   27 +-
 test/files/run/equality.scala                      |   40 +
 test/files/run/exceptions-2.scala                  |   21 +-
 test/files/run/exceptions-nest.check               |   13 +
 test/files/run/exceptions-nest.scala               |  157 +
 test/files/run/exceptions.scala                    |    1 -
 test/files/run/existentials.scala                  |    2 +-
 test/files/run/exoticnames.scala                   |    2 +-
 test/files/run/fors.scala                          |    1 -
 test/files/run/forvaleq.scala                      |    3 +-
 test/files/run/groupby.scala                       |   18 +
 test/files/run/hashCodeBoxesRunTime.scala          |   28 +
 test/files/run/hashhash.scala                      |   15 +
 test/files/run/implicits.scala                     |   23 +
 test/files/run/imports.scala                       |    1 -
 test/files/run/infiniteloop.check                  |    2 +-
 test/files/run/inliner-infer.check                 |    2 +
 test/files/run/inliner-infer.scala                 |   29 +
 test/files/run/iq.scala                            |    6 +-
 test/files/run/issue192.scala                      |    6 +-
 test/files/run/iterables.scala                     |    2 +-
 test/files/run/iterator-iterate-lazy.scala         |    5 +
 test/files/run/iterator3444.scala                  |   23 +
 test/files/run/iterators.check                     |    2 +-
 test/files/run/iterators.scala                     |   11 +-
 test/files/run/json.check                          |   21 +-
 test/files/run/json.scala                          |   99 +-
 test/files/run/lazy-concurrent.check               |    1 +
 test/files/run/lazy-concurrent.scala               |   17 +
 test/files/run/lazy-leaks.scala                    |   18 +
 test/files/run/lazy-locals.check                   |    5 +
 test/files/run/lazy-locals.scala                   |   24 +
 test/files/run/lisp.scala                          |    3 +-
 test/files/run/lists.scala                         |  110 +-
 test/files/run/literals.scala                      |    1 -
 test/files/run/manifests.scala                     |  147 +
 test/files/run/mapValues.scala                     |    8 +
 test/files/run/map_java_conversions.scala          |   60 +
 test/files/run/matcharraytail.check                |    2 +-
 test/files/run/matcharraytail.scala                |    2 +-
 test/files/run/matchemptyarray.scala               |    2 +-
 test/files/run/matchnull.check                     |    3 +
 test/files/run/matchnull.scala                     |   12 +
 test/files/run/misc.scala                          |    2 -
 test/files/run/mixins.scala                        |    2 -
 test/files/run/multi-array.check                   |    1 +
 test/files/run/multi-array.scala                   |    4 +-
 test/files/run/names-defaults.check                |  118 +
 test/files/run/names-defaults.scala                |  470 ++
 test/files/run/nodebuffer-array.check              |    3 +
 test/files/run/nodebuffer-array.scala              |   15 +
 test/files/run/numbereq.scala                      |   41 +
 test/files/run/overloads.scala                     |    1 -
 test/files/run/packrat1.check                      |    7 +
 test/files/run/packrat1.scala                      |   47 +
 test/files/run/packrat2.check                      |    7 +
 test/files/run/packrat2.scala                      |   57 +
 test/files/run/packrat3.check                      |    7 +
 test/files/run/packrat3.scala                      |   51 +
 test/files/run/patmat-seqs.check                   |   13 +
 test/files/run/patmat-seqs.scala                   |   42 +
 test/files/run/patmatnew.scala                     |   32 +-
 test/files/run/priorityQueue.scala                 |  346 ++
 test/files/run/programmatic-main.check             |   25 +
 test/files/run/programmatic-main.scala             |   12 +
 test/files/run/proxy.check                         |    4 +
 test/files/run/proxy.scala                         |    9 +
 test/files/run/randomAccessSeq-apply.scala         |    2 +-
 test/files/run/range.scala                         |   61 +-
 test/files/run/regularpatmat.check                 |  126 -
 test/files/run/regularpatmat.scala.disabled        |  729 ---
 test/files/run/richs.scala                         |    2 +-
 test/files/run/runtime.scala                       |    1 -
 test/files/run/sequenceComparisons.scala           |  121 +
 test/files/run/slice-strings.scala                 |   19 +
 test/files/run/slices.check                        |    2 -
 test/files/run/slices.scala                        |   30 +-
 test/files/run/spec-absfun.scala                   |   43 +
 test/files/run/spec-ame.check                      |    2 +
 test/files/run/spec-ame.scala                      |   17 +
 test/files/run/spec-constr.check                   |    2 +
 test/files/run/spec-constr.scala                   |   14 +
 test/files/run/spec-early.check                    |    4 +
 test/files/run/spec-early.scala                    |   15 +
 test/files/run/spec-init.check                     |    9 +
 test/files/run/spec-init.scala                     |   41 +
 test/files/run/spec-matrix.check                   |    1 +
 test/files/run/spec-matrix.scala                   |   70 +
 .../bug680.check => run/spec-overrides.check}      |    0
 test/files/run/spec-overrides.scala                |   20 +
 test/files/run/spec-patmatch.check                 |   19 +
 test/files/run/spec-patmatch.scala                 |   52 +
 test/files/run/streamWithFilter.check              |    5 +
 test/files/run/streamWithFilter.scala              |   11 +
 test/files/run/stream_flatmap_odds.check           |    1 +
 test/files/run/stream_flatmap_odds.scala           |    4 +
 test/files/run/stream_length.check                 |    1 +
 test/files/run/stream_length.scala                 |   15 +
 test/files/run/streams.scala                       |    4 +-
 test/files/run/stringbuilder.scala                 |   40 +
 test/files/run/t0017.check                         |    2 +-
 test/files/run/t0017.scala                         |    2 +-
 test/files/run/t0421.check                         |    6 +-
 test/files/run/t0421.scala                         |    4 +-
 test/files/run/t0432.scala                         |   15 +
 test/files/run/t0485.check                         |   32 -
 test/files/run/t0485.scala                         |   54 -
 test/files/run/t0528.scala                         |    4 +-
 test/files/run/t0607.scala                         |    6 +-
 test/files/run/t0677.scala                         |    5 +-
 test/files/run/t0883.scala                         |    3 +-
 test/files/run/t1167.check                         |    3 +
 test/files/run/t1167.scala                         |   25 +
 test/files/run/t1323.scala                         |   36 +-
 test/files/run/t1368.scala                         |    9 +
 test/files/run/t1500.check                         |    2 +-
 test/files/run/t1500.scala                         |    6 +-
 test/files/run/t1501.check                         |    2 +-
 test/files/run/t1501.scala                         |    7 +-
 test/files/run/t1505.scala                         |   14 +-
 test/files/run/t1524.check                         |    1 +
 test/files/run/t1524.scala                         |    7 +
 test/files/run/t153.check                          |    1 +
 test/files/run/t153.scala                          |    5 +
 test/files/run/t1535.check                         |    2 +-
 test/files/run/t1535.scala                         |    2 +-
 test/files/run/t1618.scala                         |   11 +
 test/files/run/t1718.check                         |    1 +
 test/files/run/t1718.scala                         |   10 +
 test/files/run/t1747.scala                         |    6 +
 test/files/run/t1773.scala                         |   12 +
 test/files/{jvm5/bug680.check => run/t1829.check}  |    0
 test/files/run/t1829.scala                         |   12 +
 test/files/run/t1939.scala                         |   34 +
 test/files/run/t2027.check                         |    1 +
 test/files/run/t2027.scala                         |    6 +
 test/files/run/t2030.check                         |    2 +
 test/files/run/t2030.scala                         |    8 +
 test/files/run/t2074_2.check                       |    3 +
 test/files/run/t2074_2.scala                       |   22 +
 test/files/run/t2111.check                         |    6 +
 test/files/run/t2111.scala                         |   20 +
 test/files/run/t2127.scala                         |   32 +
 test/files/run/t2147.check                         |    2 +
 test/files/run/t2147.scala                         |    8 +
 test/files/run/t2176.check                         |    1 +
 test/files/run/t2176.scala                         |    4 +
 test/files/run/t2177.check                         |    1 +
 test/files/run/t2177.scala                         |    3 +
 test/files/run/t2212.check                         |    3 +
 test/files/run/t2212.scala                         |   10 +
 test/files/run/t2236.scala                         |   17 +
 test/files/run/t2255.check                         |    1 +
 test/files/run/t2255.scala                         |    3 +
 test/files/run/t2316.scala                         |   32 +
 test/files/run/t2417.check                         |   12 +
 test/files/run/t2417.scala                         |   77 +
 test/files/run/t2446.check                         |    1 +
 test/files/run/t2446.scala                         |    9 +
 test/files/run/t2503.scala                         |   19 +
 test/files/run/t2524.scala                         |   10 +
 test/files/run/t2526.scala                         |   53 +
 test/files/run/t2544.check                         |   10 +
 test/files/run/t2544.scala                         |   19 +
 .../{jvm5/bug680.check => run/t2594_tcpoly.check}  |    0
 test/files/run/t2594_tcpoly.scala                  |   18 +
 test/files/run/t2754.scala                         |   39 +
 test/files/run/t2849.scala                         |   46 +
 .../jvm5/t1464.check => files/run/t2857.check}     |    0
 test/files/run/t2857.scala                         |    9 +
 test/files/run/t2867.scala                         |   15 +
 test/files/run/t2886.check                         |    1 +
 test/files/run/t2886.scala                         |    7 +
 test/files/run/t3026.check                         |    2 +
 test/files/run/t3026.scala                         |    8 +
 test/files/run/t3112.check                         |    4 +
 test/files/run/t3112.scala                         |   11 +
 test/files/run/t3158.check                         |    1 +
 test/files/run/t3158.scala                         |    9 +
 test/files/{jvm5/t1464.check => run/t3186.check}   |    0
 test/files/run/t3186.scala                         |    7 +
 test/files/run/t3241.check                         |    1 +
 test/files/run/t3241.scala                         |   23 +
 test/files/run/t3242.check                         |   18 +
 test/files/run/t3242.scala                         |   49 +
 test/files/run/t3242b.scala                        |   17 +
 test/files/run/t3361.scala                         |  100 +
 test/files/run/t3493.scala                         |   15 +
 test/files/run/t3496.scala                         |   15 +
 test/files/run/t3502.scala                         |   24 +
 test/files/run/t3508.scala                         |   11 +
 test/files/run/t3580.scala                         |   17 +
 test/files/run/t3603.scala                         |   18 +
 test/files/run/t3645.scala                         |    6 +
 test/files/run/t3667.check                         |    3 +
 test/files/run/t3667.scala                         |   53 +
 test/files/run/t3726.check                         |    2 +
 test/files/run/t3726.scala                         |    8 +
 test/files/run/t3763.scala                         |    3 +
 test/files/run/t493.scala                          |   22 +
 test/files/run/t498.check                          |    1 +
 test/files/run/t498.scala                          |    5 +
 test/files/run/tailcalls.scala                     |   13 +-
 test/files/run/takeAndDrop.scala                   |   14 +
 test/files/run/tcpoly_monads.scala                 |    2 +-
 test/files/run/tcpoly_overriding.scala             |    2 +-
 test/files/run/tcpoly_parseridioms.scala           |    2 +-
 test/files/run/treePrint.check                     |    5 +
 test/files/run/treePrint.scala                     |   40 +
 test/files/run/try-2.scala                         |    1 -
 test/files/run/typealias_overriding.scala          |    2 +-
 test/files/run/unapply.scala                       |    6 +-
 test/files/run/unapplyArray.scala                  |    2 +-
 test/files/run/unittest_collection.scala           |    2 +-
 test/files/run/unittest_iterator.scala             |   53 +
 test/files/run/vector1.check                       |    6 +
 test/files/run/vector1.scala                       |  199 +
 test/files/run/viewtest.check                      |   12 +
 test/files/run/viewtest.scala                      |   46 +
 test/files/run/weakconform.scala                   |    4 +
 test/files/run/withIndex.scala                     |    8 +-
 test/files/run/xml-loop-bug.scala                  |    6 +
 .../{jvm5/bug680.check => scalacheck/.gitignore}   |    0
 test/files/scalacheck/list.scala                   |   10 -
 test/files/scalap/abstractClass/A.scala            |    5 +
 test/files/scalap/abstractClass/result.test        |    4 +
 test/files/scalap/abstractMethod/A.scala           |    4 +
 test/files/scalap/abstractMethod/result.test       |    5 +
 test/files/scalap/caseClass/A.scala                |    3 +
 test/files/scalap/caseClass/result.test            |   14 +
 test/files/scalap/caseObject/A.scala               |    3 +
 test/files/scalap/caseObject/result.test           |    9 +
 test/files/scalap/cbnParam/A.scala                 |    1 +
 test/files/scalap/cbnParam/result.test             |    3 +
 test/files/scalap/classPrivate/A.scala             |    9 +
 test/files/scalap/classPrivate/result.test         |   10 +
 test/files/scalap/classWithExistential/A.scala     |    3 +
 test/files/scalap/classWithExistential/result.test |    4 +
 test/files/scalap/classWithSelfAnnotation/A.scala  |    4 +
 .../scalap/classWithSelfAnnotation/result.test     |    5 +
 test/files/scalap/covariantParam/A.scala           |    3 +
 test/files/scalap/covariantParam/result.test       |    4 +
 test/files/scalap/defaultParameter/A.scala         |    3 +
 test/files/scalap/defaultParameter/result.test     |    3 +
 test/files/scalap/implicitParam/A.scala            |    3 +
 test/files/scalap/implicitParam/result.test        |    4 +
 test/files/scalap/packageObject/A.scala            |    4 +
 test/files/scalap/packageObject/result.test        |    5 +
 test/files/scalap/paramClauses/A.scala             |    3 +
 test/files/scalap/paramClauses/result.test         |    4 +
 test/files/scalap/paramNames/A.scala               |    3 +
 test/files/scalap/paramNames/result.test           |    4 +
 test/files/scalap/sequenceParam/A.scala            |    1 +
 test/files/scalap/sequenceParam/result.test        |    3 +
 test/files/scalap/simpleClass/A.scala              |    3 +
 test/files/scalap/simpleClass/result.test          |    4 +
 test/files/scalap/traitObject/A.scala              |    7 +
 test/files/scalap/traitObject/result.test          |    8 +
 test/files/scalap/typeAnnotations/A.scala          |    9 +
 test/files/scalap/typeAnnotations/result.test      |    8 +
 test/files/scalap/valAndVar/A.scala                |    4 +
 test/files/scalap/valAndVar/result.test            |    5 +
 test/files/scalap/wildcardType/A.scala             |    1 +
 test/files/scalap/wildcardType/result.test         |    3 +
 test/files/script/fact.args                        |    2 +-
 test/files/script/second.bat                       |    6 +-
 test/files/script/utf8.scala                       |   27 -
 test/files/shootout/README                         |    2 +-
 test/files/shootout/ackermann.scala.runner         |    2 +-
 test/files/shootout/ary.scala.runner               |    2 +-
 .../shootout/binarytrees.scala-2.scala.runner      |    2 +-
 .../shootout/binarytrees.scala-3.scala.runner      |    2 +-
 test/files/shootout/binarytrees.scala.runner       |    2 +-
 test/files/shootout/chameneos.scala.runner         |    2 +-
 test/files/shootout/except.scala                   |    2 +-
 test/files/shootout/except.scala.runner            |    2 +-
 test/files/shootout/fannkuch.scala-2.scala.runner  |    2 +-
 test/files/shootout/fannkuch.scala.runner          |    2 +-
 test/files/shootout/fibo.scala.runner              |    2 +-
 test/files/shootout/harmonic.scala.runner          |    2 +-
 test/files/shootout/hash.scala.runner              |    2 +-
 test/files/shootout/hash2.scala                    |    2 +-
 test/files/shootout/hash2.scala.runner             |    2 +-
 test/files/shootout/hello.scala.runner             |    2 +-
 test/files/shootout/howtorun                       |   14 +-
 .../shootout/knucleotide.scala-2.scala.runner      |    4 +-
 test/files/shootout/knucleotide.scala-3.scala      |    4 +-
 .../shootout/knucleotide.scala-3.scala.runner      |    4 +-
 test/files/shootout/lists.scala                    |    6 +-
 test/files/shootout/lists.scala.runner             |    2 +-
 test/files/shootout/message.scala-2.javaopts       |    1 -
 test/files/shootout/message.scala-2.scala          |    3 +
 test/files/shootout/message.scala-2.scala.runner   |    2 +-
 test/files/shootout/nbody.scala-2.scala.runner     |    2 +-
 test/files/shootout/nestedloop.scala               |    2 +-
 test/files/shootout/nestedloop.scala.runner        |    2 +-
 test/files/shootout/nsieve.scala-2.scala.runner    |    2 +-
 test/files/shootout/nsieve.scala-3.scala.runner    |    2 +-
 .../files/shootout/nsievebits.scala-2.scala.runner |    2 +-
 .../files/shootout/nsievebits.scala-3.scala.runner |    2 +-
 test/files/shootout/nsievebits.scala.runner        |    2 +-
 test/files/shootout/objinst.scala                  |    2 +-
 test/files/shootout/objinst.scala.runner           |    2 +-
 .../shootout/partialsums.scala-2.scala.runner      |    2 +-
 test/files/shootout/partialsums.scala.runner       |    2 +-
 test/files/shootout/recursive.scala.runner         |    2 +-
 test/files/shootout/regexdna.scala                 |    6 +-
 test/files/shootout/regexdna.scala.runner          |    4 +-
 test/files/shootout/strcat.scala.runner            |    2 +-
 test/files/shootout/sumcol.scala-2.scala.runner    |    4 +-
 test/files/shootout/sumcol.scala.runner            |    4 +-
 test/files/shootout/takfp.scala.runner             |    2 +-
 test/long-running/jvm/memleak2_actor.scala         |   39 +
 test/partest                                       |   23 +-
 test/partest-tests/jvm/actor-receivewithin.check   |   16 +
 test/partest-tests/jvm/actor-receivewithin.scala   |   69 +
 test/partest-tests/run/crash.scala                 |    6 +
 test/partest-tests/run/streamWithFilter.check      |    5 +
 test/partest-tests/run/streamWithFilter.scala      |   11 +
 test/partest-tests/run/timeout.scala               |    5 +
 test/partest.bat                                   |    4 +-
 test/partestall                                    |    8 -
 test/partestall.bat                                |    7 -
 test/pending/buildmanager/t2443/BitSet.scala       |    2 +
 .../buildmanager/t2443/t2443.changes/BitSet2.scala |    1 +
 test/pending/buildmanager/t2443/t2443.check        |    6 +
 test/pending/buildmanager/t2443/t2443.test         |    3 +
 test/pending/continuations-run/example0.scala      |    9 +
 test/pending/continuations-run/example1.scala      |    9 +
 test/pending/continuations-run/example16.scala     |    9 +
 test/pending/continuations-run/example2.scala      |    9 +
 test/pending/continuations-run/example3.scala      |    9 +
 test/pending/continuations-run/example4.scala      |    9 +
 test/pending/continuations-run/example5.scala      |    9 +
 test/pending/continuations-run/example6.scala      |    9 +
 test/pending/continuations-run/example7.scala      |    9 +
 test/pending/continuations-run/example8.scala      |    9 +
 test/pending/continuations-run/example9.scala      |    9 +
 test/pending/continuations-run/foreach.check       |    4 +
 test/pending/continuations-run/foreach.scala       |   33 +
 test/pending/jvm/actor-executor4.check             |   21 +
 test/pending/jvm/actor-executor4.scala             |   64 +
 test/pending/jvm/actor-receive-sender.check        |    2 +
 test/pending/jvm/actor-receive-sender.scala        |   51 +
 .../jvm/actorgc_leak.check}                        |    0
 test/pending/jvm/actorgc_leak.scala                |   63 +
 test/pending/{jvm5 => jvm}/annotations.scala       |    0
 test/pending/jvm/inner.scala                       |  126 -
 test/pending/jvm/reactWithinZero.check             |    2 +
 test/pending/jvm/reactWithinZero.scala             |   18 +
 test/pending/jvm/receiveWithinZero.check           |    2 +
 test/pending/jvm/receiveWithinZero.scala           |   18 +
 test/pending/jvm/serialization.check               |  118 +-
 test/pending/jvm/serialization.scala               |  264 +-
 test/{files/jvm5 => pending/jvm}/t1464.check       |    0
 test/pending/jvm/t1801.check                       |    6 +
 test/pending/jvm/t1801.scala                       |   31 +
 test/pending/jvm/t2515.check                       |   10 +
 test/pending/jvm/t2515.scala                       |   43 +
 test/pending/jvm/t2705/GenericInterface.java       |    1 +
 test/pending/jvm/t2705/Methods.java                |    4 +
 test/pending/jvm/t2705/t2705.scala                 |    5 +
 test/{files => pending}/jvm/terminateLinked.check  |    0
 test/{files => pending}/jvm/terminateLinked.scala  |    0
 test/pending/jvm/timeout.scala                     |    5 +
 test/pending/neg/badtok-3.check                    |    1 -
 test/pending/neg/badtok-3.scala                    |    2 -
 test/pending/neg/bug112506A.scala                  |    2 +-
 test/pending/neg/bug112706A.scala                  |    8 -
 test/{files => pending}/neg/bug1210.check          |    0
 test/pending/neg/bug1210.scala                     |    2 +-
 test/pending/neg/bug1987.scala                     |   14 +
 test/pending/neg/bug3189.check                     |    7 +
 test/pending/neg/bug3189.scala                     |    3 +
 test/pending/neg/bug421.scala                      |    9 -
 test/pending/neg/bug452.check                      |    6 -
 test/pending/neg/bug452.scala                      |    8 -
 test/pending/neg/bug558.check                      |    4 -
 test/pending/neg/bug558.scala                      |   19 -
 test/pending/neg/plugin-after-terminal.check       |    2 +
 test/pending/neg/plugin-after-terminal.flags       |    2 +
 .../neg/plugin-after-terminal/lib/plugins.jar      |  Bin 0 -> 4139 bytes
 .../neg/plugin-after-terminal/misc/build.sh        |   14 +
 .../plugin-after-terminal/misc/scalac-plugin.xml   |    5 +
 .../neg/plugin-after-terminal/src/ThePlugin.scala  |   31 +
 .../neg/plugin-after-terminal/testsource.scala     |    4 +
 test/pending/neg/plugin-before-parser.check        |    2 +
 test/pending/neg/plugin-before-parser.flags        |    2 +
 .../neg/plugin-before-parser/lib/plugins.jar       |  Bin 0 -> 4222 bytes
 .../pending/neg/plugin-before-parser/misc/build.sh |   14 +
 .../plugin-before-parser/misc/scalac-plugin.xml    |    5 +
 .../neg/plugin-before-parser/src/ThePlugin.scala   |   32 +
 .../neg/plugin-before-parser/testsource.scala      |    4 +
 test/pending/neg/plugin-cyclic-dependency.check    |    2 +
 test/pending/neg/plugin-cyclic-dependency.flags    |    2 +
 .../neg/plugin-cyclic-dependency/lib/plugins.jar   |  Bin 0 -> 5574 bytes
 .../neg/plugin-cyclic-dependency/misc/build.sh     |   14 +
 .../misc/scalac-plugin.xml                         |    5 +
 .../plugin-cyclic-dependency/src/ThePlugin.scala   |   41 +
 .../neg/plugin-cyclic-dependency/testsource.scala  |    4 +
 test/pending/neg/plugin-multiple-rafter.check      |    4 +
 test/pending/neg/plugin-multiple-rafter.flags      |    2 +
 .../neg/plugin-multiple-rafter/lib/plugins.jar     |  Bin 0 -> 4137 bytes
 .../neg/plugin-multiple-rafter/misc/build.sh       |   14 +
 .../plugin-multiple-rafter/misc/scalac-plugin.xml  |    5 +
 .../neg/plugin-multiple-rafter/src/ThePlugin.scala |   31 +
 .../neg/plugin-multiple-rafter/testsource.scala    |    4 +
 test/pending/neg/plugin-rafter-before-1.check      |    2 +
 test/pending/neg/plugin-rafter-before-1.flags      |    2 +
 .../neg/plugin-rafter-before-1/lib/plugins.jar     |  Bin 0 -> 4181 bytes
 .../neg/plugin-rafter-before-1/misc/build.sh       |   14 +
 .../plugin-rafter-before-1/misc/scalac-plugin.xml  |    5 +
 .../neg/plugin-rafter-before-1/src/ThePlugin.scala |   31 +
 .../neg/plugin-rafter-before-1/testsource.scala    |    4 +
 test/pending/neg/plugin-rightafter-terminal.check  |    2 +
 test/pending/neg/plugin-rightafter-terminal.flags  |    2 +
 .../neg/plugin-rightafter-terminal/lib/plugins.jar |  Bin 0 -> 4179 bytes
 .../neg/plugin-rightafter-terminal/misc/build.sh   |   14 +
 .../misc/scalac-plugin.xml                         |    5 +
 .../plugin-rightafter-terminal/src/ThePlugin.scala |   32 +
 .../plugin-rightafter-terminal/testsource.scala    |    4 +
 test/pending/neg/t0605.scala                       |    3 -
 test/pending/neg/t0673.check                       |    4 -
 test/pending/neg/t1049.scala                       |    5 -
 test/pending/neg/t1477.scala                       |   25 +
 test/pending/neg/t1800.scala                       |   28 +
 test/pending/neg/t1845.scala                       |   12 +
 test/pending/neg/t2078.scala                       |    9 +
 test/pending/neg/t2079.scala                       |   25 +
 test/pending/neg/t2080.scala                       |   17 +
 test/pending/neg/t2180.scala                       |   31 +
 test/pending/neg/tcpoly_typealias_eta.scala        |    2 +-
 .../tcpoly_variance_enforce_getter_setter.scala    |    2 +-
 test/pending/pos/bug0305.scala                     |    2 +-
 test/pending/pos/bug1087.scala                     |    2 -
 test/pending/pos/bug1357.scala                     |   21 +
 test/pending/pos/bug1957.scala                     |   38 +
 test/pending/pos/bug2018.scala                     |   15 +
 test/pending/pos/bug3420.flags                     |    1 +
 test/pending/pos/bug3420.scala                     |    5 +
 test/pending/pos/bug586.scala                      |    2 +-
 test/pending/pos/local-objects.scala               |    9 +
 test/pending/pos/misc/A.java                       |   13 +
 test/pending/pos/misc/B.scala                      |    7 +
 test/pending/pos/misc/J.java                       |    4 +
 test/pending/pos/misc/S.scala                      |    4 +
 test/pending/pos/switchUnbox.flags                 |    1 -
 test/pending/pos/switchUnbox.scala                 |   11 -
 test/pending/pos/t0612/C.scala                     |    5 -
 test/pending/pos/t0699/A.scala                     |    4 -
 test/pending/pos/t0699/B.scala                     |    5 -
 test/pending/pos/t0816.scala                       |   12 -
 test/pending/pos/t1003.scala                       |    2 +-
 test/pending/pos/t1035.scala                       |   32 -
 test/pending/pos/t1107/Object.scala                |   10 -
 test/pending/pos/t1107/Trait.scala                 |    9 -
 test/pending/pos/t1164.scala                       |   29 -
 test/pending/pos/t1260.scala                       |   17 -
 test/{files => pending}/pos/t1380/gnujaxp.jar      |  Bin
 test/{files => pending}/pos/t1380/hallo.scala      |    0
 test/pending/pos/t1786.scala                       |   20 +
 test/pending/pos/t2071.scala                       |   21 +
 test/pending/pos/t2099.scala                       |   27 +
 test/pending/pos/t2162.scala                       |   20 +
 test/pending/pos/t2173.scala                       |   17 +
 test/pending/pos/t2179.scala                       |    6 +
 test/pending/pos/t2194.scala                       |    8 +
 test/pending/pos/t2625.scala                       |    9 +
 test/pending/pos/t2635.scala                       |   16 +
 test/pending/pos/t2641.scala                       |   16 +
 test/pending/pos5/misc/A.java                      |   13 -
 test/pending/pos5/misc/B.scala                     |    7 -
 test/pending/pos5/misc/J.java                      |    4 -
 test/pending/pos5/misc/S.scala                     |    4 -
 test/pending/res/bug837/DataFlowAnalysis.scala     |    2 +-
 test/pending/run/arrays-2.scala                    |    1 -
 test/pending/run/bug1042.scala                     |    2 +-
 test/pending/run/bug1079.scala                     |    3 -
 test/pending/run/bug1697.scala                     |   19 +
 test/pending/run/bug2087.scala                     |    8 +
 test/pending/run/bug2364.check                     |    1 +
 test/pending/run/bug2364.scala                     |   60 +
 test/pending/run/bug2365/Test.scala                |   35 +
 test/pending/run/bug2365/bug2365.javaopts          |    1 +
 test/pending/run/bug2365/run                       |   13 +
 test/pending/run/bug3050.scala                     |   10 +
 test/pending/run/bug3150.scala                     |   10 +
 test/pending/run/hashCodeDistribution.flags        |    1 +
 test/pending/run/hashCodeDistribution.scala        |   17 +
 test/pending/run/instanceOfAndTypeMatching.scala   |  193 +
 test/pending/run/string-reverse.scala              |   22 +
 test/pending/run/t0446.scala                       |    2 +-
 test/pending/run/t1044.scala                       |    3 +-
 test/pending/run/t1939.scala                       |   41 +
 test/pending/run/t1980.scala                       |   27 +
 test/pending/run/t2034.scala                       |   15 +
 test/pending/run/t3609.scala                       |   11 +
 test/pending/run/treesetmap.check                  |    1 +
 test/pending/run/treesetmap.scala                  |    5 +
 test/pending/scalacheck/array.scala                |   37 +
 test/pending/scalacheck/eqeq.scala                 |   37 +
 test/pending/scalacheck/list.scala                 |   21 +
 test/pending/scalacheck/range.scala                |  205 +
 test/pending/scalacheck/scan.scala                 |   17 +
 test/pending/script/bug2365.javaopts               |    1 +
 test/pending/script/bug2365/Test.scala             |   35 +
 test/pending/script/bug2365/bug2365.scala          |    9 +
 test/pending/shootout/fasta.scala.runner           |    2 +-
 .../pending/shootout/harmonic.scala-3.scala.runner |    2 +-
 test/pending/shootout/heapsort.scala               |    2 +-
 test/pending/shootout/heapsort.scala.runner        |    2 +-
 test/pending/shootout/mandelbrot.scala-2.scala     |   16 +
 .../shootout/mandelbrot.scala-2.scala.runner       |    2 +-
 test/pending/shootout/message.scala.runner         |    2 +-
 test/pending/shootout/meteor.scala-2.scala.runner  |    2 +-
 test/pending/shootout/meteor.scala-3.scala.runner  |    2 +-
 test/pending/shootout/meteor.scala-4.scala         |   32 +-
 test/pending/shootout/meteor.scala-4.scala.runner  |    2 +-
 test/pending/shootout/meteor.scala.runner          |    2 +-
 test/pending/shootout/methcall.scala               |    2 +-
 test/pending/shootout/methcall.scala.runner        |    2 +-
 test/pending/shootout/nsieve.scala-4.scala.runner  |    2 +-
 test/pending/shootout/pidigits.scala.runner        |    2 +-
 test/pending/shootout/prodcons.scala.runner        |    2 +-
 test/pending/shootout/random.scala.runner          |    2 +-
 test/pending/shootout/revcomp.scala-2.scala.runner |    4 +-
 test/pending/shootout/revcomp.scala-3.scala.runner |    4 +-
 test/pending/shootout/sieve.scala.runner           |    2 +-
 test/postreview.py                                 | 2540 +++++++++
 test/review                                        |   44 +
 test/scala2-nightly-test.scm                       |  137 -
 test/scala2-nightly-test.sh                        |   69 -
 test/scalatest                                     |  973 ----
 test/scalatest.bat                                 |  321 --
 test/simplejson/__init__.py                        |  318 ++
 test/simplejson/decoder.py                         |  354 ++
 test/simplejson/encoder.py                         |  440 ++
 test/simplejson/scanner.py                         |   65 +
 test/simplejson/tool.py                            |   37 +
 .../annotations}/NestedAnnotations.java            |    0
 .../jvm5 => support/annotations}/OuterEnum.java    |    0
 .../jvm5 => support/annotations}/OuterTParams.java |    0
 .../annotations}/SourceAnnotation.java             |    0
 test/support/annotations/mkAnnotationsJar.sh       |   28 +
 tools/abspath                                      |    9 +
 tools/cpof                                         |   30 +
 tools/diffPickled                                  |   51 +
 tools/git-get-rev                                  |    5 +
 tools/packcp                                       |    5 +
 tools/pathResolver                                 |   11 +
 tools/quickcp                                      |    8 +
 tools/scalawhich                                   |    4 +
 tools/scmp                                         |    4 +
 tools/showPickled                                  |   32 +
 tools/starrcp                                      |    5 +
 tools/strapcp                                      |    8 +
 tools/tokens                                       |    4 +
 tools/truncate                                     |    7 +
 4033 files changed, 175984 insertions(+), 92263 deletions(-)

diff --git a/.classpath b/.classpath
index bb25526..dbbacc4 100644
--- a/.classpath
+++ b/.classpath
@@ -2,9 +2,9 @@
 <classpath>
 	<classpathentry kind="src" path="src/compiler"/>
 	<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
-	<classpathentry kind="lib" path="lib/msil.jar"/>
+	<classpathentry exported="true" kind="lib" path="lib/msil.jar"/>
 	<classpathentry kind="lib" path="lib/jline.jar"/>
 	<classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
-	<classpathentry kind="lib" path="lib/fjbg.jar"/>
+	<classpathentry exported="true" kind="lib" path="lib/fjbg.jar"/>
 	<classpathentry kind="output" path="bin"/>
 </classpath>
diff --git a/META-INF/MANIFEST.MF b/META-INF/MANIFEST.MF
index eaebcf4..19d9caa 100644
--- a/META-INF/MANIFEST.MF
+++ b/META-INF/MANIFEST.MF
@@ -2,7 +2,7 @@ Manifest-Version: 1.0
 Bundle-ManifestVersion: 2
 Bundle-Name: Scala Distribution
 Bundle-SymbolicName: scala.tools.nsc;singleton:=true
-Bundle-Version: 2.7.7.final
+Bundle-Version: 2.8.1.final
 Eclipse-LazyStart: true
 Bundle-ClassPath: 
  .,
@@ -12,13 +12,34 @@ Bundle-ClassPath:
  lib/msil.jar
 Export-Package: 
  scala.tools.nsc,
- scala.tools.nsc.util,
- scala.tools.nsc.io,
- scala.tools.nsc.typechecker,
- scala.tools.nsc.symtab,
  scala.tools.nsc.ast,
  scala.tools.nsc.ast.parser,
- scala.tools.nsc.reporters
+ scala.tools.nsc.backend,
+ scala.tools.nsc.backend.icode,
+ scala.tools.nsc.backend.icode.analysis,
+ scala.tools.nsc.backend.jvm,
+ scala.tools.nsc.backend.opt,
+ scala.tools.nsc.dependencies,
+ scala.tools.nsc.doc,
+ scala.tools.nsc.interactive,
+ scala.tools.nsc.interpreter,
+ scala.tools.nsc.io,
+ scala.tools.nsc.javac,
+ scala.tools.nsc.matching,
+ scala.tools.nsc.plugins,
+ scala.tools.nsc.reporters,
+ scala.tools.nsc.settings,
+ scala.tools.nsc.symtab,
+ scala.tools.nsc.symtab.classfile,
+ scala.tools.nsc.transform,
+ scala.tools.nsc.typechecker,
+ scala.tools.nsc.util,
+ scala.tools.util,
+ ch.epfl.lamp.compiler.msil,
+ ch.epfl.lamp.compiler.msil.emit,
+ ch.epfl.lamp.compiler.msil.util,
+ ch.epfl.lamp.fjbg,
+ ch.epfl.lamp.util
 Require-Bundle: 
  org.apache.ant,
  scala.library
diff --git a/OMakefile b/OMakefile
deleted file mode 100644
index ba6f087..0000000
--- a/OMakefile
+++ /dev/null
@@ -1,187 +0,0 @@
-######################################################################
-
-# If you aren't running on a LAMP system, you need to make sure you 
-# have JAVA_HOME and JAVACMD (and optionally JAVAC) set correctly.
-JAVA_HOME = $(getenv JAVA_HOME,  /home/linuxsoft/apps/java-1.6/)
-JAVACMD = $(getenv JAVACMD, $(JAVA_HOME)$(DIRSEP)bin$(DIRSEP)java)
-JAVAC = $(getenv JAVAC, $(JAVA_HOME)$(DIRSEP)bin$(DIRSEP)javac)
-JAVAP = $(JAVA_HOME)$(DIRSEP)bin$(DIRSEP)javap
-
-# Default options for the JVM
-JAVA_OPTS = -Xms1024M -Xmx1024M -XX:MaxPermSize=256M
-
-DIFF=diff
-DIFF_OPTS=-r
-
-######################################################################
-
-# The current copyright string
-COPYRIGHT_STRING = Copyright 2002-2009, LAMP/EPFL
-# Need to generate this correctly
-VERSION_NUMBER = 2.7.2
-
-# The directory where the STARR is kept
-LIB_DIR = .$(DIRSEP)lib
-# The directory where we store the built files
-BUILD_DIR = .$(DIRSEP)build
-# The directory where the locker files are kept
-LOCKER_DIR = $(BUILD_DIR)$(DIRSEP)locker
-LOCKER_CLASS_DIR = $(LOCKER_DIR)$(DIRSEP)classes
-# The directory where the quick files are kept
-QUICK_DIR = $(BUILD_DIR)$(DIRSEP)quick
-QUICK_CLASS_DIR = $(QUICK_DIR)$(DIRSEP)classes
-# The directory where the strap files are kept
-STRAP_DIR = $(BUILD_DIR)$(DIRSEP)strap
-STRAP_CLASS_DIR = $(STRAP_DIR)$(DIRSEP)classes
-
-# Scala compiler class
-SCALAC_CLASS = scala.tools.nsc.Main
-
-# The Partest class
-PARTEST_CLASS = scala.tools.partest.nest.NestRunner
-
-# Arguments used to configure which tests are run
-PARTEST_ARGS = --pos --neg --run --jvm --jvm5 --res --shootout
-
-######################################################################
-
-# CLASSPATHs for the various build modes
-COMMON_CLASSPATH = $(addprefix $(LIB_DIR)$(DIRSEP), jline.jar msil.jar fjbg.jar)
-
-STARR_CLASSPATH = $(array $(addprefix $(LIB_DIR)$(DIRSEP), scala-library.jar scala-compiler.jar) $(COMMON_CLASSPATH))
-# Debugging remove
-#println($(string $(STARR_CLASSPATH)))
-LOCKER_CLASSPATH = $(array $(addprefix $(LOCKER_CLASS_DIR)$(DIRSEP), compiler library) $(COMMON_CLASSPATH))
-QUICK_CLASSPATH = $(array $(addprefix $(QUICK_CLASS_DIR)$(DIRSEP), compiler library partest) $(COMMON_CLASSPATH))
-STRAP_CLASSPATH = $(array $(addprefix $(STRAP_CLASS_DIR)$(DIRSEP), compiler library partest) $(COMMON_CLASSPATH))
-
-######################################################################
-
-# Helper functions
-
-# Convert a sequence to a path by concatenating it together with
-# the appropriate separator for the current platform
-topath(seq) =
-  return $(concat $(PATHSEP), $(seq))
-
-# Create an empty file
-touch(file) =
-  close($(fopen $(file), w))
-
-# "idempotent-mkdir", create a directory if it doesn't already exist
-idem-mkdir(dir) =
-  if $(not $(file-exists $(dir)))
-    # println(Creating directory $(dir))
-    mkdir(-p $(dir))
-
-# compare two classes using javap 
-javap-diff(cpath1, cpath2, cls) =
-  tmp1 = $(tmpfile javap1, .txt)
-  tmp2 = $(tmpfile javap2, .txt)
-  $(JAVAP) -classpath $(cpath1) -private $(cls) > $(tmp1)
-  $(JAVAP) -classpath $(cpath2) -private $(cls) > $(tmp2)
-  ($(DIFF) $(tmp1) $(tmp2)) || echo $(cls) is different in $(cpath1) and $(cpath2)
-
-# Write a property file
-propfile(file) =
-  handle = $(fopen $(file), w)
-  # Need to correctly generated date/time
-  fprint($(handle), \# Generated at some time\n)
-  fprint($(handle), copyright.string=$(COPYRIGHT_STRING)\n)
-  fprint($(handle), version.number=$(VERSION_NUMBER)\n)
-  close($(handle))
-
-# Compile the Scala files in the sequence args with the specified
-# classpath, placing the generated class files in the directory outdir
-scalac(classpath, outdir, args) =
-  # println(scalac compiling $(string $(args)))
-  $(JAVACMD) -cp $(topath $(classpath)) $(JAVA_OPTS) $(SCALAC_CLASS) -d $(outdir) $(args)
-
-# Compile the Java files in the sequence args with the specified 
-# classpath, placing the generated class files in the directory outdir
-javac(classpath, outdir, args) =
-  # println(javac compiling $(string $(args)))
-  $(JAVAC) -cp $(topath $(classpath)) -d $(outdir) $(args)
-
-# Build an instance of the Scala compiler and libraries using 
-# the compiler in the specified classpath as the bootstrap 
-# compiler, and placing the result in the directory outdir
-buildscala(classpath, outdir) =
-  idem-mkdir($(outdir)$(DIRSEP)classes$(DIRSEP)compiler)
-  scalac($(classpath), $(outdir)$(DIRSEP)classes$(DIRSEP)compiler, \
-    $(find ./src/compiler/scala/tools/nsc -name *.scala) $(find ./src/compiler/scala/tools/util -name *.scala))
-  propfile($(outdir)$(DIRSEP)classes$(DIRSEP)compiler$(DIRSEP)compiler.properties)
-  # For compatibility with the old ant script we'll create a flag 
-  # touch($(outdir)$(DIRSEP)compiler.complete)
-  idem-mkdir($(outdir)$(DIRSEP)classes$(DIRSEP)library)
-  javac($(classpath), $(outdir)$(DIRSEP)classes$(DIRSEP)library, \
-    $(find ./src/library -name *.java) $(find ./src/actors -name *.java))
-  scalac($(classpath), $(outdir)$(DIRSEP)classes$(DIRSEP)library, \
-    $(find ./src/library -name *.scala) \
-    $(find ./src/dbc -name *.scala) \
-    $(find ./src/swing -name *.scala) \
-    $(find ./src/actors -name *.scala))
-  # Need to copy over script.js and style.css for scaladoc to find them
-  cp($(addprefix ./src/compiler/scala/tools/nsc/doc/,script.js style.css) \
-    $(outdir)$(DIRSEP)classes$(DIRSEP)compiler$(DIRSEP)scala$(DIRSEP)tools$(DIRSEP)nsc$(DIRSEP)doc)
-  propfile($(outdir)$(DIRSEP)classes$(DIRSEP)library$(DIRSEP)library.properties)
-  # For compatibility with the old ant script we'll create some flags
-  touch($(outdir)$(DIRSEP)library.complete)
-  # touch($(outdir)$(DIRSEP)all.complete)
-
-# Run partest with respect to the specified classpath
-partest(classpath) =
-  # println(testing)
-  $(JAVACMD) -cp $(topath $(classpath)) $(JAVA_OPTS) \
-    $(PARTEST_CLASS) --classpath $(QUICK_CLASS_DIR) --show-diff $(PARTEST_ARGS)
-
-######################################################################
-
-# Specify those targets that are "phony", as in, they do not
-# correspond to actual files that will be created.
-
-.PHONY : locker quick partest test clean all.clean locker.clean strap stability
-
-# Specify the default target
-.DEFAULT : test
-
-######################################################################
-
-# Just clean out the quick build
-clean :
-  $(rm -rf $(QUICK_DIR))
-
-# Just clean out the locker
-locker.clean :
-  $(rm -rf $(LOCKER_DIR))
-
-# Clean up everything
-all.clean :
-  $(rm -rf $(BUILD_DIR))
-
-######################################################################
-
-locker $(LOCKER_DIR) :
-  buildscala($(STARR_CLASSPATH), $(LOCKER_DIR))
-
-quick $(QUICK_DIR) : $(LOCKER_DIR)
-  buildscala($(LOCKER_CLASSPATH), $(QUICK_DIR))
-
-strap $(STRAP_DIR) : $(QUICK_DIR)
-  buildscala($(QUICK_CLASSPATH), $(STRAP_DIR))
-
-test.stability : $(STRAP_DIR)
-#  javap-diff($(QUICK_CLASS_DIR)/library, $(STRAP_CLASS_DIR)/library, "scala.swing.Key")
-  $(DIFF) $(DIFF_OPTS) $(QUICK_CLASS_DIR) $(STRAP_CLASS_DIR)
-
-partest : quick
-  idem-mkdir($(QUICK_CLASS_DIR)$(DIRSEP)partest)
-  javac($(LOCKER_CLASSPATH), $(QUICK_CLASS_DIR)$(DIRSEP)partest, \
-    $(find ./src/partest/scala -name *.java))
-  scalac($(LOCKER_CLASSPATH), $(QUICK_CLASS_DIR)$(DIRSEP)partest, \
-    $(filter-out %PartestTask.scala %AntRunner.scala, $(find ./src/partest/scala -name *.scala)))
-  # For compatibility with the old ant script we'll create a flag
-  # touch($(QUICK_DIR)$(DIRSEP)partest.complete)
-
-test : partest
-  partest($(QUICK_CLASSPATH))
diff --git a/OMakeroot b/OMakeroot
deleted file mode 100644
index cdb7699..0000000
--- a/OMakeroot
+++ /dev/null
@@ -1,3 +0,0 @@
-open build/Common
-
-.SUBDIRS: .
diff --git a/README b/README
index afd8969..1065033 100644
--- a/README
+++ b/README
@@ -4,7 +4,7 @@
 ================================================================================
 
 This document describes the Scala core (core library and compiler) repository
-and how to build it. For information about Scala as a languages, you can visit
+and how to build it. For information about Scala as a language, you can visit
 the web site http://www.scala-lang.org/
 
 Part I. The repository layout
@@ -12,9 +12,10 @@ Part I. The repository layout
 
 Follows the file layout of the Scala repository. Files marked with a † are not
 part of the Subversion repository but are either automatically generated by the
-build script or user-created if needed.
+build script or user-created if needed.  This is not a complete listing.
 
 scala/
+      bin/                      Developer utilities.
       build/ †                  Temporary staging area for build products.
       build.excludes †          An optional build configuration file.
       build.number              The version number of the current distribution.
@@ -23,125 +24,128 @@ scala/
       dist/ †                   The destination folder of Scala distributions.
       docs/                     Documentation of Scala. More in its own module.
            development/         Developer documentation.
-           examples/            Scala example files.
-           man/                 UNIX manual files.
+           examples/            Scala source code examples.
       lib/                      Pre-compiled libraries for the build.
           fjbg.jar              The Java byte-code generation library.
-          jaco.jar              The JaCo Java compiler.
-          scala-compiler.jar    The last stable version of the Scala compiler.
-          scala-library.jar     The last stable version of the Scala library.
+          scala-compiler.jar    The stable reference version (aka 'starr')
+                                of the Scala compiler
+          scala-library.jar     The stable reference version (aka 'starr')
+                                of the Scala library.
+          scala-library-src.jar A snapshot of the source code which was used
+                                to build starr.
           ant/                  Support libraries for the build tool.
               ant-contrib.jar   Provides additional features for Ant
               vizant.jar        Provides DOT graph generation for Ant
       README                    The file you are currently reading.
       sandbox/ †                A folder to test code etc.
       src/                      All the source files of Scala.
+          actors/               The sources of the Actor library.
           compiler/             The sources of the Scala compiler.
-          library/              The sources of the Scala library.
+          library/              The sources of the core Scala library.
+          swing/                The sources of the Swing library.
       test/                     The Scala test suite.
 
-Any change to this structure requires a modification of the 'build.xml' file.
-
-Part IV. Building Scala with SABBUS
+Part II. Building Scala with SABBUS
 --------------------------------------------------------------------------------
 
-SABBUS is the name of the Ant build script used to compile Scala. It is mostly automated and takes care of managing the dependencies.
+SABBUS is the name of the Ant build script used to compile Scala. It is mostly
+automated and takes care of managing the dependencies.
 
 LAYERS:
 
-In order to guarantee the bootstrapping of the Scala compiler, SABBUS builds Scala in layers. Each layer is a complete compiled Scala compiler and library. A superior layer is always compiled by the layer just below it. Here is a short description of the four layers that SABBUS uses, from bottom to top:
+In order to guarantee the bootstrapping of the Scala compiler, SABBUS builds
+Scala in layers. Each layer is a complete compiled Scala compiler and library.
+A superior layer is always compiled by the layer just below it. Here is a short
+description of the four layers that SABBUS uses, from bottom to top:
 
-'starr': the stable reference Scala release which is shared by all the developers. It is found in the repository as 'lib/scala.compiler.jar' and 'lib/scala-library.jar'. Any committable source code must be compiled directly by starr to guarantee the bootstrapping of the compiler.
+'starr': the stable reference Scala release which is shared by all the
+developers. It is found in the repository as 'lib/scala-compiler.jar' and
+'lib/scala-library.jar'. Any committable source code must be compiled directly
+by starr to guarantee the bootstrapping of the compiler.
 
-'locker': the local reference which is compiled by starr and is the work compiler in a typical development cycle. When it has been built once, it is “frozen” in this state. Updating it to fit the current source code must be explicitly required (see below).
+'locker': the local reference which is compiled by starr and is the work
+compiler in a typical development cycle. When it has been built once, it is
+“frozen” in this state. Updating it to fit the current source code must be
+explicitly required (see below).
 
-'quick': the layer which is incrementally built when testing changes in the compiler or library. This is considered a actual new version when locker is up-to-date in relation to the source code.
+'quick': the layer which is incrementally built when testing changes in the
+compiler or library. This is considered an actual new version when locker is
+up-to-date in relation to the source code.
 
 'strap': a test layer used to check stability of the build.
 
 DEPENDANT CHANGES:
 
-SABBUS compiles, for each layer, the Scala library first and the compiler next. That means that any changes in the library can immediately be used in the compiler without an intermediate build. On the other hand, if building the library requires changes in the compiler a new starr (or in some case only locker if bootstrapping is still possible) compiler must be built in-between.
+SABBUS compiles, for each layer, the Scala library first and the compiler next.
+That means that any changes in the library can immediately be used in the
+compiler without an intermediate build. On the other hand, if building the
+library requires changes in the compiler, a new locker must be built if
+bootstrapping is still possible, or a new starr if it is not.
 
 Part III. Requirements for SABBUS
 --------------------------------------------------------------------------------
 
-The Scala build system is based on Apache Ant. Most required pre-compiled libraries are part of the repository (in 'lib/'). The following however is assumed to be installed on the build machine:
-  - A Java runtime environment (JRE) or SDK 1.4 or above.
+The Scala build system is based on Apache Ant. Most required pre-compiled
+libraries are part of the repository (in 'lib/'). The following however is
+assumed to be installed on the build machine:
+  - A Java runtime environment (JRE) or SDK 1.6 or above.
   - Apache Ant version 1.7.0 or above.
 
-Part IV. Common use-cases
+Part IV. Common use cases
 --------------------------------------------------------------------------------
 
 'ant -p'
-  Prints-out information about all available targets in the build script.
+  Prints out information about the commonly used ant targets. The interested
+  developer can find the rest in the XML files.
 
 'ant' or 'ant build'
   A quick compilation (to quick) of your changes using the locker compiler.
     - This will rebuild all quick if locker changed.
     - This will also rebuild locker if starr changed.
 
-'ant test.quick' (planned)
-  Runs the test suite against quick. This is not a full test but merely a
-  commodity feature for development.
-
-'ln -s build/quick/exec/ bin' (once)
-'ant && bin/scalac -d sandbox sandbox/test.scala && bin/scala -cp sandbox Test'
+'ln -s build/quick/bin qbin' (once)
+'ant && qbin/scalac -d sandbox sandbox/test.scala && qbin/scala -cp sandbox Test'
   Incrementally builds quick, and then uses it to compile and run the file
   'sandbox/test.scala'. This is a typical debug cycle.
 
-'ant newlocker'
-  “unfreezes” locker by updating it to match the current source code.
+'ant replacelocker'
+  "unfreezes" locker by updating it to match the current source code.
     - This will delete quick so as not to mix classes compiled with different
       versions of locker.
 
 'ant test'
   Tests that your code is working and fit to be committed.
-    - Rebuilds locker from scratch (to make sure it bootstraps).
-    - Builds everything twice more and compares bit-to-bit the two builds (to
-      make sure it is stable).
-    - (planned) Runs the test suite.
+    - Runs the test suite and bootstrapping test on quick.
+    - You can run the suite only (skipping strap) with 'ant test.suite'.
 
 'ant docs'
   Generates the HTML documentation for the library from the sources using the
-  scaladoc tool in quick.
-
-'ant docs.compiler'
-  Generates the HTML documentation for the compiler from the sources using the
-  scaladoc tool in quick.
+  scaladoc tool in quick.  Note: on most machines this requires more heap than
+  is allocate by default.  You can adjust the parameters with ANT_OPTS.
+  Example command line:
+    ANT_OPTS="-Xms512M -Xmx2048M -Xss1M -XX:MaxPermSize=128M" ant docs
 
 'ant dist'
   Builds a distribution.
-    - Runs all the tests as above (and refuses to build a distribution if it
-      fails).
-    - Creates a local distribution in 'dists/latest'.
-
-'ant pack'
-  Builds a distribution, and packages it for distribution.
-    - Runs all the tests as above (and refuses to build a distribution if it
-      fails).
+    - Rebuilds locker from scratch (to make sure it bootstraps).
+    - Builds everything twice more and compares bit-to-bit the two builds (to
+      make sure it is stable).
+    - Runs the test suite (and refuses to build a distribution if it fails).
     - Creates a local distribution in 'dists/latest'.
-    - Creates all relevant Scala Bazaar archives, advertisement files and
-      ZIP/TAR archives.
-
-'ant dist.devel' or 'ant dist.patch' or 'ant dist.minor'
-  Builds a distribution (with packaging) to be publicly released and manages
-  version numbers.
-    - Patch and Minor versions are public releases. The version number is
-      automatically bumped up and is formatted as 'major.minor.patch'.
-    - Devel versions are betas for semi-public release. Numbers are formatted as
-      'major.minor.patch.svn'. Version '2.3.4.5875' is a beta for either patch
-      '2.3.5' or minor version '2.4.0'.
 
 'ant clean'
   Removes all temporary build files (locker is preserved).
 
-'ant clean.build'
-  Removes all build files (including locker).
+'ant locker.clean'
+  Removes all build files.
 
-'ant clean.all'
+'ant all.clean'
   Removes all build files (including locker) and all distributions.
 
+Many of these targets offer a variant which runs with -optimise enabled.
+Optimized targets include build-opt, test-opt, dist-opt, fastdist-opt,
+replacestarr-opt, replacelocker-opt, and distpack-opt.
+
 Part V. Contributing to Scala
 --------------------------------------------------------------------------------
 
@@ -149,7 +153,7 @@ If you wish to contribute, you can find all of the necessary information on
 the official Scala website: www.scala-lang.org.
 
 Specifically, you can subscribe to the Scala mailing lists, read all of the
-available documentation, and browse the live SVN repository. You can contact
+available documentation, and browse the live SVN repository.  You can contact
 the Scala team by sending us a message on one of the mailing lists, or by using
 the available contact form.
 
diff --git a/build.examples.xml b/build.examples.xml
index 7947241..a71e29c 100644
--- a/build.examples.xml
+++ b/build.examples.xml
@@ -1,5 +1,4 @@
 <?xml version="1.0" encoding="UTF-8"?>
-<!-- $Id: build.examples.xml 15045 2008-05-16 12:21:35Z dubochet $ -->
 
 <project name="scala-examples" default="build">
 
diff --git a/build.number b/build.number
index c98c498..96b8566 100644
--- a/build.number
+++ b/build.number
@@ -1,5 +1,5 @@
 #Tue Sep 11 19:21:09 CEST 2007
-version.minor=7
-version.patch=7
+version.minor=8
+version.patch=1
 version.suffix=final
 version.major=2
diff --git a/build.xml b/build.xml
index eb15d91..59cd959 100644
--- a/build.xml
+++ b/build.xml
@@ -3,7 +3,7 @@
 <project name="sabbus" default="build">
 
   <description>
-    SuperSabbus for Scala core, builds the scala library and compiler. It can also package it as a simple distribution, tests it for stable bootstrapping and against the Scala test suite. Use PackSabbus to package it for different install management tools such as Sbaz.
+SuperSabbus for Scala core, builds the scala library and compiler. It can also package it as a simple distribution, tests it for stable bootstrapping and against the Scala test suite.
   </description>
 
 <!-- ===========================================================================
@@ -12,15 +12,26 @@ END-USER TARGETS
   
   <target name="build" depends="pack.done"
     description="Builds the Scala compiler and library. Executables are in 'build/pack/bin'."/>
-  
+    
+  <target name="build-opt"
+    description="Builds the optimised Scala compiler and library. Executables are in 'build/pack/bin'.">
+    <antcall target="build">
+      <param name="scalac.args.optimise" value="-optimise"/>
+    </antcall>
+  </target>
+
   <target name="clean" depends="quick.clean"
     description="Removes binaries of compiler and library. Distributions are untouched."/>
-  
+
   <target name="test" depends="test.done"
     description="Runs test suite and bootstrapping test on Scala compiler and library."/>
-  
-  <target name="optimised.test" depends="optimised.test.done"
-    description="Runs test suite and bootstrapping test on the optimised Scala compiler and library."/>
+
+  <target name="test-opt"
+    description="Runs test suite and bootstrapping test, everything is optimised (compiler, library, tests).">
+    <antcall target="test">
+      <param name="scalac.args.optimise" value="-optimise"/>
+    </antcall>
+  </target>
 
   <target name="docs" depends="docs.done"
     description="Builds documentation for the Scala library. Scaladoc is in 'build/scaladoc/library'."/>
@@ -38,15 +49,29 @@ END-USER TARGETS
     <antcall target="all.done"/>
   </target>
   
+  <target name="dist-opt"
+    description="Makes a new optimised distribution and tests it. Will remove existing binaries and documentation.">
+    <antcall target="dist">
+      <param name="scalac.args.optimise" value="-optimise"/>
+    </antcall>
+  </target>
+
   <target name="fastdist" depends="dist.done"
-    description="Makes a new distribution without testing it or removing partially build elements"/>
-  
+    description="Makes a new distribution without testing it or removing partially build elements."/>
+
+  <target name="fastdist-opt"
+    description="Makes a new optimised distribution without testing it or removing partially build elements.">
+    <antcall target="fastdist">
+      <param name="scalac.args.optimise" value="-optimise"/>
+    </antcall>
+  </target>
+
   <target name="distclean" depends="dist.clean"
     description="Removes all distributions. Binaries and documentation are untouched."/>
   
-  <target name="newstarr"
-    description="Replaces the Starr compiler and library by one built from current sources and tests it.">
-    <fail message="This target is not available on Windows. Use 'ant newstarrwin' instead.">
+  <target name="replacestarr"
+    description="Replaces the Starr compiler and library by fresh ones built from current sources and tests them.">
+    <fail message="This target is not available on Windows. Use 'ant replacestarrwin' instead.">
       <condition>
         <os family="windows"/>
       </condition>
@@ -57,45 +82,63 @@ END-USER TARGETS
     <antcall target="locker.clean"/>
     <antcall target="test.done"/>
   </target>
+  
+  <target name="replacestarr-opt"
+    description="Replaces the Starr compiler and library by fresh, optimised ones built from current sources and tests them.">
+    <antcall target="replacestarr">
+      <param name="scalac.args.optimise" value="-optimise"/>
+    </antcall>
+  </target>
 
   <!-- Ant on Windows is not able to delete jar files that are referenced in any <path>.
        See ticket 1290 on trac. -->
-  <target name="newstarrwin"
-          description="Creates a new Starr on Windows. Manually execute 'ant locker.clean build' first!">
-    <fail message="This target is only available on Windows. Use 'ant newstarr' instead.">
+  <target name="replacestarrwin"
+    description="Creates a new Starr on Windows. Manually execute 'ant locker.clean build' first!">
+    <fail message="This target is only available on Windows. Use 'ant replacestarr' instead.">
       <condition>
         <not><os family="windows"/></not>
       </condition>
     </fail>
-    <echo message="CAUTION: Make sure to execute 'ant locker.clean build' prior to calling 'newstarrwin'."/>
+    <echo message="CAUTION: Make sure to execute 'ant locker.clean build' prior to calling 'replacestarrwin'."/>
     <antcall target="starr.done"/>
     <antcall target="locker.clean"/>
     <antcall target="test.done"/>
   </target>
   
-  <target name="freshlocker"
-    description="Replaces the Locker compiler and library by one built from current sources.">
-    <antcall target="locker.clean"/>
-    <antcall target="locker.done"/>
+  <target name="replacelocker"
+    description="Replaces the Locker compiler and library by fresh ones built from current sources.">
+    <antcall target="palo.clean"/>
+    <antcall target="unlocklocker"/>
   </target>
-  
-  <target name="newlocker"
-    description="Unlocks the Locker compiler and library and lets them be updated by Scalac.">
+
+  <target name="replacelocker-opt"
+    description="Replaces the Locker compiler and library by fresh, optimised ones built from current sources.">
+    <antcall target="replacelocker">
+      <param name="scalac.args.optimise" value="-optimise"/>
+    </antcall>
+  </target>
+
+  <target name="unlocklocker"
+    description="Unlocks Locker, allowing its compiler and library to be rebuilt">
     <antcall target="locker.unlock"/>
-    <antcall target="locker.done"/>
+    <antcall target="palo.done"/>
   </target>
 
-  <target name="optimised"
-          description="Build the compiler and standard library using optimisations, running 'quick'">
-    <antcall target="optimised.bin"/>
+  <target name="newlibs"
+    description="Requires libraries (MSIL, FJBG) to be rebuilt. Add this target before any other if class file format is incompatible.">
+    <property name="libs.outdated" value="yes"/>
   </target>
-  
+
+  <target name="newforkjoin"
+    description="Requires forkjoin library to be rebuilt. Add this target before any other if class file format is incompatible.">
+    <property name="forkjoin.outdated" value="yes"/>
+  </target>
+
 <!-- ===========================================================================
 PROPERTIES
 ============================================================================ -->
 
   <property environment="env"/>
-
   <!-- Prevents system classpath from being used -->
   <property name="build.sysclasspath" value="ignore"/>
 
@@ -104,7 +147,7 @@ PROPERTIES
   <property name="lib.dir" value="${basedir}/lib"/>
   <property name="lib-ant.dir" value="${lib.dir}/ant"/>
   <property name="src.dir" value="${basedir}/src"/>
-  <property name="test.dir" value="${basedir}/test"/>
+  <property name="partest.dir" value="${basedir}/test"/>
 
   <!-- Loads custom properties definitions -->
   <property file="${basedir}/build.properties"/>
@@ -116,39 +159,52 @@ PROPERTIES
   <!-- Sets location of pre-compiled libraries -->
   <property name="lib.starr.jar" value="${lib.dir}/scala-library.jar"/>
   <property name="comp.starr.jar" value="${lib.dir}/scala-compiler.jar"/>
-  <property name="fjbg.jar" value="${lib.dir}/fjbg.jar"/>
-  <property name="msil.jar" value="${lib.dir}/msil.jar"/>
   <property name="jline.jar" value="${lib.dir}/jline.jar"/>
   <property name="ant.jar" value="${ant.home}/lib/ant.jar"/>
+  <property name="scalacheck.jar" value="${lib.dir}/scalacheck.jar"/>
 
   <!-- Sets location of build folders -->
   <property name="build.dir" value="${basedir}/build"/>
   <property name="build-locker.dir" value="${build.dir}/locker"/>
+  <property name="build-palo.dir" value="${build.dir}/palo"/>
   <property name="build-quick.dir" value="${build.dir}/quick"/>
-  <property name="build-optimised.dir" value="${build.dir}/optimised"/>
   <property name="build-pack.dir" value="${build.dir}/pack"/>
   <property name="build-strap.dir" value="${build.dir}/strap"/>
   <property name="build-docs.dir" value="${build.dir}/scaladoc"/>
+  <property name="build-libs.dir" value="${build.dir}/libs"/>
 
   <property name="dists.dir" value="${basedir}/dists"/>
-  
-  <property name="copyright.string" value="Copyright 2002-2009, LAMP/EPFL"/>
-  
+
+  <property name="copyright.string" value="Copyright 2002-2010, LAMP/EPFL"/>
+  <property name="partest.version.number" value="0.9.2"/>
+
   <!-- These are NOT the flags used to run SuperSabbus, but the ones written
        into the script runners created with scala.tools.ant.ScalaTool -->
   <property name="java.flags" value="-Xmx256M -Xms32M"/>
 
+  <!-- if ANT_OPTS is already set by the environment, it will be unaltered,
+       but if it is unset it will take this default value. -->
+  <property name="env.ANT_OPTS" value="-Xms512M -Xmx1536M -Xss1M -XX:MaxPermSize=128M" />
+  <!--  to find max heap usage: -Xaprof ; currently at 980M for locker.comp -->
+  <echo message="Using ANT_OPTS: ${env.ANT_OPTS}" />
+
   <property
       name="scalacfork.jvmargs"
-      value="-Xms512M -Xmx512M -Xss1M -XX:MaxPermSize=128M"/>
-
-  <property name="javac.cmd" value="${env.JAVA_HOME}/bin/javac"/>
+      value="${env.ANT_OPTS}"/>
 
 <!-- ===========================================================================
 INITIALISATION
 ============================================================================ -->
 
   <target name="init">
+  <!-- scalac.args.optimise is selectively overridden in certain antcall tasks. -->
+    <property name="scalac.args.optimise" value=""/>
+  <!-- scalac.args.quickonly are added to quick.* targets but not others (particularly, locker.)
+       This is to facilitate testing new command line options which do not yet exist in starr. -->
+	<property name="scalac.args.quickonly" value=""/>
+	
+    <property name="scalac.args.all" value="${scalac.args} ${scalac.args.optimise}"/>
+	<property name="scalac.args.quick" value="${scalac.args.all} ${scalac.args.quickonly}"/>
   <!-- Setting-up Ant contrib tasks -->
     <taskdef resource="net/sf/antcontrib/antlib.xml" classpath="${lib.dir}/ant/ant-contrib.jar"/>
   <!-- This is the start time for the distribution -->
@@ -160,16 +216,34 @@ INITIALISATION
     <condition property="os.win">
       <os family="windows"/>
     </condition>
-  <!-- Finding out SVN revision -->
+    <!-- Finding out SVN revision, svn style -->
     <exec executable="svn" outputproperty="svn.out"
       failifexecutionfails="false">
       <arg line=" info ${basedir}"/>
     </exec>
     <propertyregex
-      property="svn.number" input="${svn.out}" select="\1"
+      property="svn.number.svn" input="${svn.out}" select="\1"
       regexp="Revision: ([0-9]+)"
       defaultValue="0"/>
+
+    <!-- Both clauses of the conditional set svn.number -->
+    <if>
+      <equals arg1="${svn.number.svn}" arg2="0" />
+      <then>
+        <!-- Finding SVN revision, git style -->
+        <exec osfamily="unix" executable="tools/git-get-rev" outputproperty="svn.number.git" failifexecutionfails="false" />
+        <propertyregex
+          property="svn.number" input="${svn.number.git}" select="\1"
+          regexp="\D*?(\d+)"
+          defaultValue="0"/>
+      </then>
+      <else>
+        <property name="svn.number" value="${svn.number.svn}" />
+      </else>
+    </if>
+
     <property name="init.avail" value="yes"/>
+
   <!-- Generating version number -->
     <property file="${basedir}/build.number"/>
     <property
@@ -182,9 +256,20 @@ INITIALISATION
     <path id="starr.classpath">
       <pathelement location="${lib.starr.jar}"/>
       <pathelement location="${comp.starr.jar}"/>
-      <pathelement location="${fjbg.jar}"/>
+      <pathelement location="${lib.dir}/fjbg.jar"/>
+      <pathelement location="${lib.dir}/msil.jar"/>
+      <pathelement location="${lib.dir}/forkjoin.jar"/>
       <pathelement location="${ant.jar}"/>
     </path>
+    <!-- What to have on the compilation path when compiling during certain phases -->
+    <path id="quick.compilation.path">
+      <pathelement location="${build-quick.dir}/classes/library"/>
+      <pathelement location="${lib.dir}/forkjoin.jar"/>
+    </path>
+    <path id="strap.compilation.path">
+      <pathelement location="${build-strap.dir}/classes/library"/>
+      <pathelement location="${lib.dir}/forkjoin.jar"/>
+    </path>  
     <taskdef resource="scala/tools/ant/sabbus/antlib.xml" classpathref="starr.classpath"/>
   </target>
 
@@ -215,27 +300,17 @@ LOCAL REFERENCE BUILD (LOCKER)
       target="1.5" source="1.5">
         <compilerarg line="${javac.args}"/>
     </javac>
+    <!-- NOTE: Potential problem with maximal command line length on Windows
+         (32768 characters for XP, since executed with Java's "exec"). See
+         src/build/msil.xml in msil branch for more details. -->
     <scalacfork
       destdir="${build-locker.dir}/classes/library"
       compilerpathref="starr.classpath"
       srcpath="${src.dir}/library"
-      params="${scalac.args}"
-      srcdir="${src.dir}/library"
-      jvmargs="${scalacfork.jvmargs}">
-      <include name="scala/Predef.scala"/>
-      <compilationpath>
-        <pathelement location="${build-locker.dir}/classes/library"/>
-      </compilationpath>
-    </scalacfork>
-    <scalacfork
-      destdir="${build-locker.dir}/classes/library"
-      compilerpathref="starr.classpath"
-      srcpath="${src.dir}/library"
-      params="${scalac.args}"
+      params="${scalac.args.all}"
       srcdir="${src.dir}/library"
       jvmargs="${scalacfork.jvmargs}">
       <include name="**/*.scala"/>
-      <exclude name="scala/Predef.scala"/>
       <compilationpath>
         <pathelement location="${build-locker.dir}/classes/library"/>
       </compilationpath>
@@ -268,18 +343,18 @@ LOCAL REFERENCE BUILD (LOCKER)
     <scalacfork
       destdir="${build-locker.dir}/classes/compiler"
       compilerpathref="starr.classpath"
-      srcpath="${src.dir}/compiler"
-      params="${scalac.args}"
+      params="${scalac.args.all}"
       srcdir="${src.dir}/compiler"
       jvmargs="${scalacfork.jvmargs}">
       <include name="**/*.scala"/>
       <compilationpath>
         <pathelement location="${build-locker.dir}/classes/library"/>
         <pathelement location="${build-locker.dir}/classes/compiler"/>
-        <pathelement location="${fjbg.jar}"/>
-        <pathelement location="${msil.jar}"/>
-        <pathelement location="${jline.jar}"/>
+        <pathelement location="${lib.dir}/fjbg.jar"/>
+        <pathelement location="${lib.dir}/msil.jar"/>
+        <pathelement location="${lib.dir}/forkjoin.jar"/>
         <pathelement location="${ant.jar}"/>
+        <pathelement location="${jline.jar}"/>
       </compilationpath>
     </scalacfork>
     <propertyfile file="${build-locker.dir}/classes/compiler/compiler.properties">
@@ -291,44 +366,95 @@ LOCAL REFERENCE BUILD (LOCKER)
         <include name="**/*.tmpl"/>
         <include name="**/*.xml"/>
         <include name="**/*.js"/>
+        <include name="**/*.html"/>
         <include name="**/*.css"/>
+        <include name="**/*.properties"/>
+        <include name="**/*.swf"/>
+        <include name="**/*.png"/>
+
       </fileset>
     </copy>
     <touch file="${build-locker.dir}/compiler.complete" verbose="no"/>
     <stopwatch name="locker.comp.timer" action="total"/>
   </target>
-  
+
   <target name="locker.done" depends="locker.comp">
     <touch file="${build-locker.dir}/all.complete" verbose="no"/>
     <path id="locker.classpath">
       <pathelement location="${build-locker.dir}/classes/library"/>
       <pathelement location="${build-locker.dir}/classes/compiler"/>
-      <pathelement location="${fjbg.jar}"/>
+      <pathelement location="${lib.dir}/fjbg.jar"/>
+      <pathelement location="${lib.dir}/msil.jar"/>
+      <pathelement location="${lib.dir}/forkjoin.jar"/>
       <pathelement location="${ant.jar}"/>
     </path>
   </target>
   
-  <target name="locker.clean" depends="quick.clean">
+  <target name="locker.clean" depends="palo.clean">
     <delete dir="${build-locker.dir}" includeemptydirs="yes" quiet="yes" failonerror="no"/>
   </target>
   
-  <target name="locker.unlock" depends="quick.clean">
+  <target name="locker.unlock">
+    <delete file="${build-locker.dir}/all.complete"/>
     <delete file="${build-locker.dir}/library.complete"/>
     <delete file="${build-locker.dir}/compiler.complete"/>
   </target>
 
 <!-- ===========================================================================
+PACKED LOCKER BUILD (PALO)
+============================================================================ -->
+
+  <target name="palo.start" depends="locker.done"/>
+
+  <target name="palo.pre-lib" depends="palo.start">
+    <uptodate
+      property="palo.lib.available"
+      targetfile="${build-palo.dir}/lib/scala-library.jar"
+      srcfile="${build-locker.dir}/library.complete"/>
+  </target>
+
+  <target name="palo.lib" depends="palo.pre-lib" unless="palo.lib.available">
+    <mkdir dir="${build-palo.dir}/lib"/>
+    <jar destfile="${build-palo.dir}/lib/scala-library.jar">
+      <fileset dir="${build-locker.dir}/classes/library"/>
+    </jar>
+  </target>
+
+  <target name="palo.pre-comp" depends="palo.lib">
+    <uptodate
+      property="palo.comp.available"
+      targetfile="${build-palo.dir}/lib/scala-compiler.jar"
+      srcfile="${build-locker.dir}/compiler.complete"/>
+  </target>
+
+  <target name="palo.comp" depends="palo.pre-comp" unless="palo.comp.available">
+    <mkdir dir="${build-palo.dir}/lib"/>
+    <jar destfile="${build-palo.dir}/lib/scala-compiler.jar" manifest="${basedir}/META-INF/MANIFEST.MF">
+      <fileset dir="${build-locker.dir}/classes/compiler"/>
+      <!-- filemode / dirmode: see trac ticket #1294 -->
+    </jar>
+  </target>
+
+  <target name="palo.done" depends="palo.comp">
+  </target>
+
+  <target name="palo.clean" depends="quick.clean">
+    <delete dir="${build-palo.dir}" includeemptydirs="yes" quiet="yes" failonerror="no"/>
+  </target>
+
+<!-- ===========================================================================
 QUICK BUILD (QUICK)
 ============================================================================ -->
   
   <target name="quick.start" depends="locker.done"/>
-  
+
   <target name="quick.pre-lib" depends="quick.start">
     <uptodate property="quick.lib.available" targetfile="${build-quick.dir}/library.complete">
       <srcfiles dir="${src.dir}">
         <include name="library/**"/>
         <include name="dbc/**"/>
         <include name="actors/**"/>
+        <include name="continuations/**"/>
         <include name="swing/**"/>
       </srcfiles>
     </uptodate>
@@ -357,62 +483,38 @@ QUICK BUILD (QUICK)
       destdir="${build-quick.dir}/classes/library"
       compilerpathref="locker.classpath"
       srcpath="${src.dir}/library"
-      params="${scalac.args}"
-      srcdir="${src.dir}/library"
-      jvmargs="${scalacfork.jvmargs}">
-      <include name="scala/Predef.scala"/>
-      <compilationpath>
-        <pathelement location="${build-quick.dir}/classes/library"/>
-      </compilationpath>
-    </scalacfork>
-    <scalacfork
-      destdir="${build-quick.dir}/classes/library"
-      compilerpathref="locker.classpath"
-      srcpath="${src.dir}/library"
-      params="${scalac.args}"
+      params="${scalac.args.quick}"
       srcdir="${src.dir}/library"
       jvmargs="${scalacfork.jvmargs}">
       <include name="**/*.scala"/>
-      <exclude name="scala/Predef.scala"/>
-      <compilationpath>
-        <pathelement location="${build-quick.dir}/classes/library"/>
-      </compilationpath>
+      <compilationpath refid="quick.compilation.path"/>
     </scalacfork>
     <scalacfork
       destdir="${build-quick.dir}/classes/library"
       compilerpathref="locker.classpath"
-      srcpath="${src.dir}/library"
-      params="${scalac.args}"
+      params="${scalac.args.quick}"
       srcdir="${src.dir}/actors"
       jvmargs="${scalacfork.jvmargs}">
       <include name="**/*.scala"/>
-      <compilationpath>
-        <pathelement location="${build-quick.dir}/classes/library"/>
-      </compilationpath>
+      <compilationpath refid="quick.compilation.path"/>
     </scalacfork>
     <scalacfork
       destdir="${build-quick.dir}/classes/library"
       compilerpathref="locker.classpath"
-      srcpath="${src.dir}/library"
-      params="${scalac.args}"
+      params="${scalac.args.quick}"
       srcdir="${src.dir}/dbc"
       jvmargs="${scalacfork.jvmargs}">
       <include name="**/*.scala"/>
-      <compilationpath>
-        <pathelement location="${build-quick.dir}/classes/library"/>
-      </compilationpath>
+      <compilationpath refid="quick.compilation.path"/>
     </scalacfork>
     <scalacfork
       destdir="${build-quick.dir}/classes/library"
       compilerpathref="locker.classpath"
-      srcpath="${src.dir}/library"
-      params="${scalac.args}"
+      params="${scalac.args.quick}"
       srcdir="${src.dir}/swing"
       jvmargs="${scalacfork.jvmargs}">
       <include name="**/*.scala"/>
-      <compilationpath>
-        <pathelement location="${build-quick.dir}/classes/library"/>
-      </compilationpath>
+      <compilationpath refid="quick.compilation.path"/>
     </scalacfork>
     <propertyfile file="${build-quick.dir}/classes/library/library.properties">
       <entry key="version.number" value="${version.number}"/>
@@ -430,7 +532,27 @@ QUICK BUILD (QUICK)
     <stopwatch name="quick.lib.timer" action="total"/>
   </target>
   
-  <target name="quick.pre-comp" depends="quick.lib">
+  <target name="quick.newlibs" depends="quick.lib" if="libs.outdated">
+    <antcall target="libs.done" inheritRefs="true"/>
+    <property name="fjbg.jar" value="${build-libs.dir}/fjbg.jar"/>
+    <property name="msil.jar" value="${build-libs.dir}/msil.jar"/>
+  </target>
+  
+  <target name="quick.libs" depends="quick.newlibs" unless="libs.outdated">
+    <property name="fjbg.jar" value="${lib.dir}/fjbg.jar"/>
+    <property name="msil.jar" value="${lib.dir}/msil.jar"/>
+  </target>
+
+  <target name="quick.newforkjoin" depends="quick.libs" if="forkjoin.outdated">
+    <antcall target="forkjoin.done" inheritRefs="true"/>
+    <property name="forkjoin.jar" value="${build-libs.dir}/forkjoin.jar"/>
+  </target>
+
+  <target name="quick.forkjoin" depends="quick.newforkjoin" unless="forkjoin.outdated">
+    <property name="forkjoin.jar" value="${lib.dir}/forkjoin.jar"/>
+  </target>
+
+  <target name="quick.pre-comp" depends="quick.forkjoin">
     <uptodate property="quick.comp.available" targetfile="${build-quick.dir}/compiler.complete">
       <srcfiles dir="${src.dir}/compiler"/>
     </uptodate>
@@ -442,8 +564,7 @@ QUICK BUILD (QUICK)
     <scalacfork
       destdir="${build-quick.dir}/classes/compiler"
       compilerpathref="locker.classpath"
-      srcpath="${src.dir}/compiler"
-      params="${scalac.args}"
+      params="${scalac.args.quick}"
       srcdir="${src.dir}/compiler"
       jvmargs="${scalacfork.jvmargs}">
       <include name="**/*.scala"/>
@@ -452,8 +573,9 @@ QUICK BUILD (QUICK)
         <pathelement location="${build-quick.dir}/classes/compiler"/>
         <pathelement location="${fjbg.jar}"/>
         <pathelement location="${msil.jar}"/>
-        <pathelement location="${jline.jar}"/>
+        <pathelement location="${forkjoin.jar}"/>
         <pathelement location="${ant.jar}"/>
+        <pathelement location="${jline.jar}"/>
       </compilationpath>
     </scalacfork>
     <propertyfile file="${build-quick.dir}/classes/compiler/compiler.properties">
@@ -466,13 +588,89 @@ QUICK BUILD (QUICK)
         <include name="**/*.xml"/>
         <include name="**/*.js"/>
         <include name="**/*.css"/>
+        <include name="**/*.html"/>
+        <include name="**/*.properties"/>
+        <include name="**/*.swf"/>
+        <include name="**/*.png"/>
       </fileset>
     </copy>
     <touch file="${build-quick.dir}/compiler.complete" verbose="no"/>
     <stopwatch name="quick.comp.timer" action="total"/>
   </target>
-  
-  <target name="quick.pre-partest" depends="quick.comp">
+
+  <target name="quick.pre-plugins" depends="quick.comp">
+    <uptodate property="quick.plugins.available" targetfile="${build-quick.dir}/plugins.complete">
+      <srcfiles dir="${src.dir}/continuations"/>
+    </uptodate>
+  </target>
+
+  <target name="quick.plugins" depends="quick.pre-plugins" unless="quick.plugins.available">
+    <stopwatch name="quick.plugins.timer"/>
+    <mkdir dir="${build-quick.dir}/classes/continuations-plugin"/>
+    <scalacfork
+      destdir="${build-quick.dir}/classes/continuations-plugin"
+      compilerpathref="locker.classpath"
+      params="${scalac.args.quick}"
+      srcdir="${src.dir}/continuations/plugin"
+      jvmargs="${scalacfork.jvmargs}">
+      <include name="**/*.scala"/>
+      <compilationpath>
+        <pathelement location="${build-quick.dir}/classes/library"/>
+        <pathelement location="${build-quick.dir}/classes/compiler"/>
+        <pathelement location="${build-quick.dir}/classes/continuations-plugin"/>
+      </compilationpath>
+    </scalacfork>
+    <copy
+       file="${src.dir}/continuations/plugin/scalac-plugin.xml"
+       todir="${build-quick.dir}/classes/continuations-plugin"/>
+    <!-- not very nice to create jar here but needed to load plugin -->
+    <mkdir dir="${build-quick.dir}/misc/scala-devel/plugins"/>
+    <jar destfile="${build-quick.dir}/misc/scala-devel/plugins/continuations.jar">
+      <fileset dir="${build-quick.dir}/classes/continuations-plugin"/>
+    </jar>
+    <!-- might split off library part into its own ant target -->
+    <scalacfork
+      destdir="${build-quick.dir}/classes/library"
+      compilerpathref="locker.classpath"
+      params="${scalac.args.quick} -Xpluginsdir ${build-quick.dir}/misc/scala-devel/plugins -Xplugin-require:continuations -P:continuations:enable"
+      srcdir="${src.dir}/continuations/library"
+      jvmargs="${scalacfork.jvmargs}">
+      <include name="**/*.scala"/>
+      <compilationpath refid="quick.compilation.path"/>
+    </scalacfork>
+    <touch file="${build-quick.dir}/plugins.complete" verbose="no"/>
+    <stopwatch name="quick.plugins.timer" action="total"/>
+  </target>
+
+  <target name="quick.pre-scalap" depends="quick.plugins">
+    <uptodate property="quick.scalap.available" targetfile="${build-quick.dir}/scalap.complete">
+      <srcfiles dir="${src.dir}/scalap"/>
+    </uptodate>
+  </target>
+
+  <target name="quick.scalap" depends="quick.pre-scalap" unless="quick.scalap.available">
+    <stopwatch name="quick.scalap.timer"/>
+    <mkdir dir="${build-quick.dir}/classes/scalap"/>
+    <scalacfork
+      destdir="${build-quick.dir}/classes/scalap"
+      compilerpathref="locker.classpath"
+      params="${scalac.args.quick}"
+      srcdir="${src.dir}/scalap"
+      jvmargs="${scalacfork.jvmargs}">
+      <include name="**/*.scala"/>
+      <compilationpath>
+        <pathelement location="${build-quick.dir}/classes/library"/>
+        <pathelement location="${build-quick.dir}/classes/compiler"/>
+        <pathelement location="${build-quick.dir}/classes/scalap"/>
+        <pathelement location="${build-quick.dir}/classes/partest"/>
+        <pathelement location="${ant.jar}"/>
+      </compilationpath>
+    </scalacfork>
+    <touch file="${build-quick.dir}/scalap.complete" verbose="no"/>
+    <stopwatch name="quick.scalap.timer" action="total"/>
+  </target>
+
+  <target name="quick.pre-partest" depends="quick.scalap">
     <uptodate property="quick.partest.available" targetfile="${build-quick.dir}/partest.complete">
       <srcfiles dir="${src.dir}/partest"/>
     </uptodate>
@@ -488,6 +686,7 @@ QUICK BUILD (QUICK)
       <classpath>
         <pathelement location="${build-quick.dir}/classes/library"/>
         <pathelement location="${build-quick.dir}/classes/compiler"/>
+        <pathelement location="${build-quick.dir}/classes/scalap"/>
         <pathelement location="${build-quick.dir}/classes/partest"/>
       </classpath>
       <include name="**/*.java"/>
@@ -496,18 +695,24 @@ QUICK BUILD (QUICK)
     <scalacfork
       destdir="${build-quick.dir}/classes/partest"
       compilerpathref="locker.classpath"
-      srcpath="${src.dir}/partest"
-      params="${scalac.args}"
+      params="${scalac.args.quick}"
       srcdir="${src.dir}/partest"
       jvmargs="${scalacfork.jvmargs}">
       <include name="**/*.scala"/>
       <compilationpath>
         <pathelement location="${build-quick.dir}/classes/library"/>
         <pathelement location="${build-quick.dir}/classes/compiler"/>
+        <pathelement location="${build-quick.dir}/classes/scalap"/>
         <pathelement location="${build-quick.dir}/classes/partest"/>
         <pathelement location="${ant.jar}"/>
+        <pathelement location="${lib.dir}/forkjoin.jar"/>
+        <pathelement location="${scalacheck.jar}"/>
       </compilationpath>
     </scalacfork>
+    <propertyfile file="${build-quick.dir}/classes/partest/partest.properties">
+      <entry key="version.number" value="${partest.version.number}"/>
+      <entry key="copyright.string" value="${copyright.string}"/>
+    </propertyfile>
     <copy todir="${build-quick.dir}/classes/partest">
       <fileset dir="${src.dir}/partest">
         <include name="**/*.xml"/>
@@ -516,7 +721,7 @@ QUICK BUILD (QUICK)
     <touch file="${build-quick.dir}/partest.complete" verbose="no"/>
     <stopwatch name="quick.partest.timer" action="total"/>
   </target>
-  
+
   <target name="quick.pre-bin" depends="quick.partest">
     <condition property="quick.bin.available">
       <isset property="quick.comp.available"/>
@@ -527,7 +732,10 @@ QUICK BUILD (QUICK)
     <path id="quick.bin.classpath">
       <pathelement location="${build-quick.dir}/classes/library"/>
       <pathelement location="${build-quick.dir}/classes/compiler"/>
+      <pathelement location="${build-quick.dir}/classes/scalap"/>
       <pathelement location="${fjbg.jar}"/>
+      <pathelement location="${msil.jar}"/>
+      <pathelement location="${forkjoin.jar}"/>
       <pathelement location="${jline.jar}"/>
     </path>
     <taskdef name="quick-bin" classname="scala.tools.ant.ScalaTool" classpathref="quick.bin.classpath"/>
@@ -552,10 +760,16 @@ QUICK BUILD (QUICK)
       class="scala.tools.nsc.CompileClient"
       javaFlags="${java.flags}"
       classpathref="quick.bin.classpath"/>
+    <quick-bin
+      file="${build-quick.dir}/bin/scalap"
+      class="scala.tools.scalap.Main"
+      javaFlags="${java.flags}"
+      classpathref="quick.bin.classpath"/>
     <chmod perm="ugo+rx" file="${build-quick.dir}/bin/scala"/>
     <chmod perm="ugo+rx" file="${build-quick.dir}/bin/scalac"/>
     <chmod perm="ugo+rx" file="${build-quick.dir}/bin/scaladoc"/>
     <chmod perm="ugo+rx" file="${build-quick.dir}/bin/fsc"/>
+    <chmod perm="ugo+rx" file="${build-quick.dir}/bin/scalap"/>
     <touch file="${build-quick.dir}/bin.complete" verbose="no"/>
   </target>
 
@@ -564,11 +778,13 @@ QUICK BUILD (QUICK)
       <pathelement location="${build-quick.dir}/classes/library"/>
       <pathelement location="${build-quick.dir}/classes/compiler"/>
       <pathelement location="${fjbg.jar}"/>
+      <pathelement location="${msil.jar}"/>
+      <pathelement location="${forkjoin.jar}"/>
       <pathelement location="${ant.jar}"/>
     </path>
   </target>
 
-  <target name="quick.clean" depends="pack.clean">
+  <target name="quick.clean" depends="libs.clean">
     <delete dir="${build-quick.dir}" includeemptydirs="yes" quiet="yes" failonerror="no"/>
   </target>
 
@@ -592,6 +808,7 @@ PACKED QUICK BUILD (PACK)
         <exclude name="scala/dbc/**"/>
         <exclude name="scala/swing/**"/>
       </fileset>
+      <zipfileset dirmode="755" filemode="644" src="${forkjoin.jar}"/>
     </jar>
     <jar destfile="${build-pack.dir}/lib/scala-dbc.jar">
       <fileset dir="${build-quick.dir}/classes/library">
@@ -627,11 +844,25 @@ PACKED QUICK BUILD (PACK)
       <!-- filemode / dirmode: see trac ticket #1294 -->
       <zipfileset dirmode="755" filemode="644" src="${fjbg.jar}"/>
       <zipfileset dirmode="755" filemode="644" src="${msil.jar}"/>
-      <zipfileset dirmode="755" filemode="644" src="${jline.jar}"/>
+    </jar>
+    <copy file="${jline.jar}" toDir="${build-pack.dir}/lib"/>
+  </target>
+  
+  <target name="pack.pre-plugins" depends="pack.comp">
+    <uptodate
+      property="pack.plugins.available"
+      targetfile="${build-pack.dir}/misc/scala-devel/plugins/continuations.jar"
+      srcfile="${build-quick.dir}/plugins.complete"/>
+  </target>
+
+  <target name="pack.plugins" depends="pack.pre-plugins" unless="pack.plugins.available">
+    <mkdir dir="${build-pack.dir}/misc/scala-devel/plugins"/>
+    <jar destfile="${build-pack.dir}/misc/scala-devel/plugins/continuations.jar">
+      <fileset dir="${build-quick.dir}/classes/continuations-plugin"/>
     </jar>
   </target>
   
-  <target name="pack.pre-partest" depends="pack.comp">
+  <target name="pack.pre-partest" depends="pack.plugins">
     <uptodate
       property="pack.partest.available"
       targetfile="${build-pack.dir}/lib/scala-partest.jar"
@@ -645,7 +876,22 @@ PACKED QUICK BUILD (PACK)
     </jar>
   </target>
   
-  <target name="pack.pre-bin" depends="pack.partest">
+  <target name="pack.pre-scalap" depends="pack.partest">
+    <uptodate
+      property="pack.scalap.available"
+      targetfile="${build-pack.dir}/lib/scalap.jar"
+      srcfile="${build-quick.dir}/scalap.complete"/>
+  </target>
+
+  <target name="pack.scalap" depends="pack.pre-scalap" unless="pack.scalap.available">
+    <mkdir dir="${build-pack.dir}/lib"/>
+    <jar destfile="${build-pack.dir}/lib/scalap.jar">
+      <fileset dir="${build-quick.dir}/classes/scalap"/>
+      <fileset file="${src.dir}/scalap/decoder.properties"/>  
+    </jar>
+  </target>
+  
+  <target name="pack.pre-bin" depends="pack.scalap">
     <uptodate
       property="pack.bin.available"
       srcfile="${build-pack.dir}/lib/scala-compiler.jar"
@@ -657,6 +903,7 @@ PACKED QUICK BUILD (PACK)
       <classpath>
         <pathelement location="${build-pack.dir}/lib/scala-library.jar"/>
         <pathelement location="${build-pack.dir}/lib/scala-compiler.jar"/>
+        <pathelement location="${build-pack.dir}/lib/jline.jar"/>
       </classpath>
     </taskdef>
     <mkdir dir="${build-pack.dir}/bin"/>
@@ -676,10 +923,15 @@ PACKED QUICK BUILD (PACK)
       file="${build-pack.dir}/bin/fsc"
       class="scala.tools.nsc.CompileClient"
       javaFlags="${java.flags}"/>
+    <pack-bin
+      file="${build-pack.dir}/bin/scalap"
+      class="scala.tools.scalap.Main"
+      javaFlags="${java.flags}"/>
     <chmod perm="ugo+rx" file="${build-pack.dir}/bin/scala"/>
     <chmod perm="ugo+rx" file="${build-pack.dir}/bin/scalac"/>
     <chmod perm="ugo+rx" file="${build-pack.dir}/bin/scaladoc"/>
     <chmod perm="ugo+rx" file="${build-pack.dir}/bin/fsc"/>
+    <chmod perm="ugo+rx" file="${build-pack.dir}/bin/scalap"/>
     <touch file="${build-pack.dir}/bin.complete" verbose="no"/>
   </target>
   
@@ -688,7 +940,9 @@ PACKED QUICK BUILD (PACK)
       <pathelement location="${build-pack.dir}/lib/scala-library.jar"/>
       <pathelement location="${build-pack.dir}/lib/scala-compiler.jar"/>
       <pathelement location="${build-pack.dir}/lib/scala-partest.jar"/>
+      <pathelement location="${build-pack.dir}/lib/scalap.jar"/>
       <pathelement location="${ant.jar}"/>
+      <pathelement location="${jline.jar}"/>
     </path>
     <taskdef resource="scala/tools/ant/antlib.xml" classpathref="pack.classpath"/>
     <taskdef resource="scala/tools/partest/antlib.xml" classpathref="pack.classpath"/>
@@ -734,48 +988,43 @@ BOOTSTRAPPING BUILD (STRAP)
       target="1.5" source="1.5">
       <compilerarg line="${javac.args}"/>
     </javac>
-    <scalac
-      srcdir="${src.dir}/library"
+    <scalacfork
       destdir="${build-strap.dir}/classes/library"
-      classpath="${build-strap.dir}/classes/library"
-      sourcepath="${src.dir}/library"
-      target="jvm-1.5"
-      addparams="${scalac.args}">
-      <include name="scala/Predef.scala"/>
-    </scalac>
-    <scalac
+      compilerpathref="pack.classpath"
+      srcpath="${src.dir}/library"
+      params="${scalac.args.all}"
       srcdir="${src.dir}/library"
-      destdir="${build-strap.dir}/classes/library"
-      classpath="${build-strap.dir}/classes/library"
-      target="jvm-1.5"
-      addparams="${scalac.args}">
+      jvmargs="${scalacfork.jvmargs}">
       <include name="**/*.scala"/>
-      <exclude name="scala/Predef.scala"/>
-    </scalac>
-    <scalac
-      srcdir="${src.dir}/actors"
+      <compilationpath refid="strap.compilation.path"/>
+    </scalacfork>
+    <scalacfork
       destdir="${build-strap.dir}/classes/library"
-      classpath="${build-strap.dir}/classes/library"
-      target="jvm-1.5"
-      addparams="${scalac.args}">
+      compilerpathref="pack.classpath"
+      params="${scalac.args.all}"
+      srcdir="${src.dir}/actors"
+      jvmargs="${scalacfork.jvmargs}">
       <include name="**/*.scala"/>
-    </scalac>
-    <scalac
-      srcdir="${src.dir}/dbc"
+      <compilationpath refid="strap.compilation.path"/>
+    </scalacfork>
+    <scalacfork
       destdir="${build-strap.dir}/classes/library"
-      classpath="${build-strap.dir}/classes/library"
-      target="jvm-1.5"
-      addparams="${scalac.args}">
+      compilerpathref="pack.classpath"
+      params="${scalac.args.all}"
+      srcdir="${src.dir}/dbc"
+      jvmargs="${scalacfork.jvmargs}">
       <include name="**/*.scala"/>
-    </scalac>
-    <scalac
-      srcdir="${src.dir}/swing"
+      <compilationpath refid="strap.compilation.path"/>
+    </scalacfork>
+    <scalacfork
       destdir="${build-strap.dir}/classes/library"
-      classpath="${build-strap.dir}/classes/library"
-      target="jvm-1.5"
-      addparams="${scalac.args}">
+      compilerpathref="pack.classpath"
+      params="${scalac.args.all}"
+      srcdir="${src.dir}/swing"
+      jvmargs="${scalacfork.jvmargs}">
       <include name="**/*.scala"/>
-    </scalac>
+      <compilationpath refid="strap.compilation.path"/>
+    </scalacfork>
     <propertyfile file="${build-strap.dir}/classes/library/library.properties">
       <entry key="version.number" value="${version.number}"/>
       <entry key="copyright.string" value="${copyright.string}"/>
@@ -801,21 +1050,23 @@ BOOTSTRAPPING BUILD (STRAP)
   <target name="strap.comp" depends="strap.pre-comp" unless="strap.comp.available">
     <stopwatch name="strap.comp.timer"/>
     <mkdir dir="${build-strap.dir}/classes/compiler"/>
-    <scalac
-      srcdir="${src.dir}/compiler"
+    <scalacfork
       destdir="${build-strap.dir}/classes/compiler"
-      target="jvm-1.5"
-      addparams="${scalac.args}">
+      compilerpathref="pack.classpath"
+      params="${scalac.args.all}"
+      srcdir="${src.dir}/compiler"
+      jvmargs="${scalacfork.jvmargs}">
       <include name="**/*.scala"/>
-      <classpath>
+      <compilationpath>
         <pathelement location="${build-strap.dir}/classes/library"/>
         <pathelement location="${build-strap.dir}/classes/compiler"/>
         <pathelement location="${fjbg.jar}"/>
         <pathelement location="${msil.jar}"/>
-        <pathelement location="${jline.jar}"/>
+        <pathelement location="${forkjoin.jar}"/>
         <pathelement location="${ant.jar}"/>
-      </classpath>
-    </scalac>
+        <pathelement location="${jline.jar}"/>
+      </compilationpath>
+    </scalacfork>
     <propertyfile file="${build-strap.dir}/classes/compiler/compiler.properties">
       <entry key="version.number" value="${version.number}"/>
       <entry key="copyright.string" value="${copyright.string}"/>
@@ -826,13 +1077,92 @@ BOOTSTRAPPING BUILD (STRAP)
         <include name="**/*.xml"/>
         <include name="**/*.js"/>
         <include name="**/*.css"/>
-      </fileset>
+        <include name="**/*.html"/>
+        <include name="**/*.properties"/>
+        <include name="**/*.swf"/>
+        <include name="**/*.png"/>
+       </fileset>
     </copy>
     <touch file="${build-strap.dir}/compiler.complete" verbose="no"/>
     <stopwatch name="strap.comp.timer" action="total"/>
   </target>
+
+  <target name="strap.pre-plugins" depends="strap.comp">
+    <uptodate property="strap.plugins.available" targetfile="${build-strap.dir}/plugins.complete">
+      <srcfiles dir="${src.dir}/continuations"/>
+    </uptodate>
+  </target>
+
+  <target name="strap.plugins" depends="strap.pre-plugins" unless="strap.plugins.available">
+    <stopwatch name="strap.plugins.timer"/>
+    <mkdir dir="${build-strap.dir}/classes/continuations-plugin"/>
+    <scalacfork
+      destdir="${build-strap.dir}/classes/continuations-plugin"
+      compilerpathref="pack.classpath"
+      params="${scalac.args.all}"
+      srcdir="${src.dir}/continuations/plugin"
+      jvmargs="${scalacfork.jvmargs}">
+      <include name="**/*.scala"/>
+      <compilationpath>
+        <pathelement location="${build-strap.dir}/classes/library"/>
+        <pathelement location="${build-strap.dir}/classes/compiler"/>
+        <pathelement location="${build-strap.dir}/classes/continuations-plugin"/>
+      </compilationpath>
+    </scalacfork>
+    <copy
+       file="${src.dir}/continuations/plugin/scalac-plugin.xml"
+       todir="${build-strap.dir}/classes/continuations-plugin"/>
+    <!-- not very nice to create jar here but needed to load plugin -->
+    <mkdir dir="${build-strap.dir}/misc/scala-devel/plugins"/>
+    <jar destfile="${build-strap.dir}/misc/scala-devel/plugins/continuations.jar">
+      <fileset dir="${build-strap.dir}/classes/continuations-plugin"/>
+    </jar>
+    <!-- might split off library part into its own ant target -->
+    <scalacfork
+      destdir="${build-strap.dir}/classes/library"
+      compilerpathref="pack.classpath"
+      params="${scalac.args.all} -Xpluginsdir ${build-strap.dir}/misc/scala-devel/plugins -Xplugin-require:continuations -P:continuations:enable"
+      srcdir="${src.dir}/continuations/library"
+      jvmargs="${scalacfork.jvmargs}">
+      <include name="**/*.scala"/>
+      <compilationpath>
+        <pathelement location="${build-strap.dir}/classes/library"/>
+        <pathelement location="${lib.dir}/forkjoin.jar"/>
+      </compilationpath>
+    </scalacfork>
+    <touch file="${build-strap.dir}/plugins.complete" verbose="no"/>
+    <stopwatch name="strap.plugins.timer" action="total"/>
+  </target>
+
+  <target name="strap.pre-scalap" depends="strap.plugins">
+    <uptodate property="strap.scalap.available" targetfile="${build-strap.dir}/scalap.complete">
+      <srcfiles dir="${src.dir}/scalap"/>
+    </uptodate>
+  </target>
+
+  <target name="strap.scalap" depends="strap.pre-scalap" unless="strap.scalap.available">
+    <stopwatch name="strap.scalap.timer"/>
+    <mkdir dir="${build-strap.dir}/classes/scalap"/>
+    <scalacfork
+      destdir="${build-strap.dir}/classes/scalap"
+      compilerpathref="pack.classpath"
+      params="${scalac.args.all}"
+      srcdir="${src.dir}/scalap"
+      jvmargs="${scalacfork.jvmargs}">
+      <include name="**/*.scala"/>
+      <compilationpath>
+        <pathelement location="${build-strap.dir}/classes/library"/>
+        <pathelement location="${build-strap.dir}/classes/compiler"/>
+        <pathelement location="${build-strap.dir}/classes/scalap"/>
+        <pathelement location="${build-strap.dir}/classes/partest"/>
+        <pathelement location="${ant.jar}"/>
+      </compilationpath>
+    </scalacfork>
+    <touch file="${build-strap.dir}/scalap.complete" verbose="no"/>
+    <stopwatch name="strap.scalap.timer" action="total"/>
+  </target>
   
-  <target name="strap.pre-partest" depends="strap.comp">
+  <target name="strap.pre-partest" depends="strap.scalap">
     <uptodate property="strap.partest.available" targetfile="${build-strap.dir}/partest.complete">
       <srcfiles dir="${src.dir}/partest"/>
     </uptodate>
@@ -848,24 +1178,29 @@ BOOTSTRAPPING BUILD (STRAP)
       <classpath>
         <pathelement location="${build-strap.dir}/classes/library"/>
         <pathelement location="${build-strap.dir}/classes/compiler"/>
+        <pathelement location="${build-strap.dir}/classes/scalap"/>
         <pathelement location="${build-strap.dir}/classes/partest"/>
       </classpath>
       <include name="**/*.java"/>
       <compilerarg line="${javac.args}"/>
     </javac>
-    <scalac
-      srcdir="${src.dir}/partest"
+    <scalacfork
       destdir="${build-strap.dir}/classes/partest"
-      target="jvm-1.5"
-      addparams="${scalac.args}">
+      compilerpathref="pack.classpath"
+      params="${scalac.args.all}"
+      srcdir="${src.dir}/partest"
+      jvmargs="${scalacfork.jvmargs}">
       <include name="**/*.scala"/>
-      <classpath>
+      <compilationpath>
         <pathelement location="${build-strap.dir}/classes/library"/>
         <pathelement location="${build-strap.dir}/classes/compiler"/>
+        <pathelement location="${build-strap.dir}/classes/scalap"/>
         <pathelement location="${build-strap.dir}/classes/partest"/>
         <pathelement location="${ant.jar}"/>
-      </classpath>
-    </scalac>
+        <pathelement location="${lib.dir}/forkjoin.jar"/>
+        <pathelement location="${scalacheck.jar}"/>
+      </compilationpath>
+    </scalacfork>
     <copy todir="${build-strap.dir}/classes/partest">
       <fileset dir="${src.dir}/partest">
         <include name="**/*.xml"/>
@@ -874,7 +1209,7 @@ BOOTSTRAPPING BUILD (STRAP)
     <touch file="${build-strap.dir}/partest.complete" verbose="no"/>
     <stopwatch name="strap.partest.timer" action="total"/>
   </target>
-  
+
   <target name="strap.done" depends="strap.partest"/>
 
   <target name="strap.clean">
@@ -882,259 +1217,136 @@ BOOTSTRAPPING BUILD (STRAP)
   </target>
 
 <!-- ===========================================================================
-OPTIMISED COMPILER
+LIBRARIES (MSIL, FJBG maybe later)
 ============================================================================ -->
-
-  <target name="optimised.start" depends="quick.done"/>
   
-  <target name="optimised.pre-lib" depends="optimised.start">
-    <uptodate property="optimised.lib.available" targetfile="${build-optimised.dir}/library.complete">
-      <srcfiles dir="${src.dir}">
-        <include name="library/**"/>
-        <include name="dbc/**"/>
-        <include name="actors/**"/>
-        <include name="swing/**"/>
+  <target name="libs.start"/>
+  
+  <target name="libs.pre-forkjoin" depends="libs.start">
+    <property name="java6.home" value="/home/linuxsoft/apps/java-1.6"/>
+    <fail message="Compiling forkjoin.jar requires java 1.6. Please set the property `java6.home` in build.properties or using `-Djava6.home=/path/to/java6`">
+      <condition><not>
+        <available file="${java6.home}/bin/javac"/>
+      </not></condition>
+    </fail>
+
+    <uptodate property="libs.forkjoin.available" targetfile="${build-libs.dir}/forkjoin.complete">
+      <srcfiles dir="${src.dir}/forkjoin">
+        <include name="**/*.java"/>
+        <include name="**/*.scala"/>
       </srcfiles>
     </uptodate>
   </target>
-
-  <target name="optimised.lib" depends="optimised.pre-lib" unless="optimised.lib.available">
-    <stopwatch name="optimised.lib.timer"/>
-    <mkdir dir="${build-optimised.dir}/classes/library"/>
+  
+  <target name="libs.forkjoin" depends="libs.pre-forkjoin" unless="libs.forkjoin.available">
+    <mkdir dir="${build-libs.dir}/classes/forkjoin"/>
     <javac
-      srcdir="${src.dir}/library"
-      destdir="${build-optimised.dir}/classes/library"
-      classpath="${build-optimised.dir}/classes/library"
+      executable="${java6.home}/bin/javac"
+      fork="yes"
+      compiler="javac1.6"
+      srcdir="${src.dir}/forkjoin"
+      destdir="${build-libs.dir}/classes/forkjoin"
+      classpath="${build-libs.dir}/classes/forkjoin"
       includes="**/*.java"
+      debug="true"
       target="1.5" source="1.5">
-      <compilerarg line="${javac.args}"/> 
+        <compilerarg line="${javac.args}"/>
     </javac>
+    <touch file="${build-libs.dir}/forkjoin.complete" verbose="no"/>
+  </target>
+  
+  <target name="libs.pre-forkjoinpack" depends="libs.forkjoin">
+  </target>
+  
+  <target name="libs.forkjoinpack" depends="libs.pre-forkjoinpack" unless="libs.forkjoinpack.available">
+    <jar destfile="${build-libs.dir}/forkjoin.jar">
+      <fileset dir="${build-libs.dir}/classes/forkjoin"/>
+    </jar>
+  </target>
+  
+  <target name="libs.pre-msil" depends="libs.start">
+    <uptodate property="libs.msil.available" targetfile="${build-libs.dir}/msil.complete">
+      <srcfiles dir="${src.dir}/msil">
+        <include name="**/*.java"/>
+        <include name="**/*.scala"/>
+      </srcfiles>
+    </uptodate>
+  </target>
+  
+  <target name="libs.msil" depends="libs.pre-msil" unless="libs.msil.available">
+    <mkdir dir="${build-libs.dir}/classes/msil"/>
     <javac
-      srcdir="${src.dir}/actors"
-      destdir="${build-optimised.dir}/classes/library"
-      classpath="${build-optimised.dir}/classes/library"
+      srcdir="${src.dir}/msil"
+      destdir="${build-libs.dir}/classes/msil"
+      classpath="${build-libs.dir}/classes/msil"
       includes="**/*.java"
-      target="1.5" source="1.5">
-      <compilerarg line="${javac.args}"/>
+      excludes="**/tests/**"
+      debug="true"
+      target="1.5" source="1.4">
+        <compilerarg line="${javac.args}"/>
     </javac>
     <scalacfork
-      destdir="${build-optimised.dir}/classes/library"
-      compilerpathref="quick.classpath"
-      srcpath="${src.dir}/library"
-      params="-optimise ${scalac.args}"
-      srcdir="${src.dir}/library"
-      jvmargs="${scalacfork.jvmargs}">
-      <include name="scala/Predef.scala"/>
-      <compilationpath>
-        <pathelement location="${build-optimised.dir}/classes/library"/>
-      </compilationpath>
-    </scalacfork>
-    <scalacfork
-      destdir="${build-optimised.dir}/classes/library"
-      compilerpathref="quick.classpath"
-      srcpath="${src.dir}/library"
-      params="-optimise ${scalac.args}"
-      srcdir="${src.dir}/library"
-      jvmargs="${scalacfork.jvmargs}">
-      <include name="**/*.scala"/>
-      <exclude name="scala/Predef.scala"/>
-      <compilationpath>
-        <pathelement location="${build-optimised.dir}/classes/library"/>
-      </compilationpath>
-    </scalacfork>
-    <scalacfork
-      destdir="${build-optimised.dir}/classes/library"
-      compilerpathref="quick.classpath"
-      srcpath="${src.dir}/library"
-      params="-optimise ${scalac.args}"
-      srcdir="${src.dir}/actors"
-      jvmargs="${scalacfork.jvmargs}">
-      <include name="**/*.scala"/>
-      <compilationpath>
-        <pathelement location="${build-optimised.dir}/classes/library"/>
-      </compilationpath>
-    </scalacfork>
-    <scalacfork
-      destdir="${build-optimised.dir}/classes/library"
-      compilerpathref="quick.classpath"
-      srcpath="${src.dir}/library"
-      params="-optimise ${scalac.args}"
-      srcdir="${src.dir}/dbc"
-      jvmargs="${scalacfork.jvmargs}">
-      <include name="**/*.scala"/>
-      <compilationpath>
-        <pathelement location="${build-optimised.dir}/classes/library"/>
-      </compilationpath>
-    </scalacfork>
-    <scalacfork
-      destdir="${build-optimised.dir}/classes/library"
-      compilerpathref="quick.classpath"
-      srcpath="${src.dir}/library"
-      params="-optimise ${scalac.args}"
-      srcdir="${src.dir}/swing"
+      destdir="${build-libs.dir}/classes/msil"
+      compilerpathref="locker.classpath"
+      params="${scalac.args.all}"
+      srcdir="${src.dir}/msil"
       jvmargs="${scalacfork.jvmargs}">
       <include name="**/*.scala"/>
       <compilationpath>
-        <pathelement location="${build-optimised.dir}/classes/library"/>
+        <pathelement location="${build-quick.dir}/classes/library"/>
+        <pathelement location="${build-libs.dir}/classes/msil"/>
       </compilationpath>
     </scalacfork>
-    <propertyfile file="${build-optimised.dir}/classes/library/library.properties">
-      <entry key="version.number" value="${version.number}"/>
-      <entry key="copyright.string" value="${copyright.string}"/>
-    </propertyfile>
-    <copy todir="${build-optimised.dir}/classes/library">
-      <fileset dir="${src.dir}/library">
-        <include name="**/*.tmpl"/>
-        <include name="**/*.xml"/>
-        <include name="**/*.js"/>
-        <include name="**/*.css"/>
-      </fileset>
-    </copy>
-    <touch file="${build-optimised.dir}/library.complete" verbose="no"/>
-    <stopwatch name="optimised.lib.timer" action="total"/>
+    <touch file="${build-libs.dir}/msil.complete" verbose="no"/>
   </target>
   
-  <target name="optimised.pre-comp" depends="optimised.lib">
-    <uptodate property="optimised.comp.available" targetfile="${build-opimised.dir}/compiler.complete">
-      <srcfiles dir="${src.dir}/compiler"/>
-    </uptodate>
+  <target name="libs.pre-msilpack" depends="libs.msil">
   </target>
-
-  <target name="optimised.comp" depends="optimised.pre-comp" unless="optimised.comp.available">
-    <stopwatch name="optimised.comp.timer"/>
-    <mkdir dir="${build-optimised.dir}/classes/compiler"/>
-    <scalacfork
-      destdir="${build-optimised.dir}/classes/compiler"
-      compilerpathref="quick.classpath"
-      srcpath="${src.dir}/compiler"
-      params="-optimise ${scalac.args}"
-      srcdir="${src.dir}/compiler"
-      jvmargs="${scalacfork.jvmargs}">
-      <include name="**/*.scala"/>
-      <compilationpath>
-        <pathelement location="${build-optimised.dir}/classes/library"/>
-        <pathelement location="${build-optimised.dir}/classes/compiler"/>
-        <pathelement location="${fjbg.jar}"/>
-        <pathelement location="${msil.jar}"/>
-        <pathelement location="${jline.jar}"/>
-        <pathelement location="${ant.jar}"/>
-      </compilationpath>
-    </scalacfork>
-    <propertyfile file="${build-optimised.dir}/classes/compiler/compiler.properties">
-      <entry key="version.number" value="${version.number}"/>
-      <entry key="copyright.string" value="${copyright.string}"/>
-    </propertyfile>
-    <copy todir="${build-optimised.dir}/classes/compiler">
-      <fileset dir="${src.dir}/compiler">
-        <include name="**/*.tmpl"/>
-        <include name="**/*.xml"/>
-        <include name="**/*.js"/>
-        <include name="**/*.css"/>
-      </fileset>
-    </copy>
-    <touch file="${build-optimised.dir}/compiler.complete" verbose="no"/>
-    <stopwatch name="optimised.comp.timer" action="total"/>
+  
+  <target name="libs.msilpack" depends="libs.pre-msilpack" unless="libs.msilpack.available">
+    <jar destfile="${build-libs.dir}/msil.jar">
+      <fileset dir="${build-libs.dir}/classes/msil"/>
+    </jar>
   </target>
-
-  <target name="optimised.pre-partest" depends="optimised.comp">
-    <uptodate property="optimised.partest.available" targetfile="${build-optimised.dir}/partest.complete">
-      <srcfiles dir="${src.dir}/partest"/>
+  
+  <target name="libs.pre-fjbg" depends="libs.start">
+    <uptodate property="libs.fjbg.available" targetfile="${build-libs.dir}/fjbg.complete">
+      <srcfiles dir="${src.dir}/fjbg">
+        <include name="**/*.java"/>
+        <include name="**/*.scala"/>
+      </srcfiles>
     </uptodate>
   </target>
-
-  <target name="optimised.partest" depends="optimised.pre-partest" unless="optimised.partest.available">
-    <stopwatch name="optimised.partest.timer"/>
-    <mkdir dir="${build-optimised.dir}/classes/partest"/>
+  
+  <target name="libs.fjbg" depends="libs.pre-fjbg" unless="libs.fjbg.available">
+    <mkdir dir="${build-libs.dir}/classes/fjbg"/>
     <javac
-      srcdir="${src.dir}/partest"
-      destdir="${build-optimised.dir}/classes/partest"
-      target="1.5" source="1.5">
-      <classpath>
-        <pathelement location="${build-optimised.dir}/classes/library"/>
-        <pathelement location="${build-optimised.dir}/classes/compiler"/>
-        <pathelement location="${build-optimised.dir}/classes/partest"/>
-      </classpath>
-      <include name="**/*.java"/>
-      <compilerarg line="${javac.args}"/>
+      srcdir="${src.dir}/fjbg"
+      destdir="${build-libs.dir}/classes/fjbg"
+      classpath="${build-libs.dir}/classes/fjbg"
+      includes="**/*.java"
+      debug="true"
+      target="1.5" source="1.4">
+        <compilerarg line="${javac.args}"/>
     </javac>
-    <scalacfork
-      destdir="${build-optimised.dir}/classes/partest"
-      compilerpathref="locker.classpath"
-      srcpath="${src.dir}/partest"
-      params="${scalac.args}"
-      srcdir="${src.dir}/partest"
-      jvmargs="${scalacfork.jvmargs}">
-      <include name="**/*.scala"/>
-      <compilationpath>
-        <pathelement location="${build-optimised.dir}/classes/library"/>
-        <pathelement location="${build-optimised.dir}/classes/compiler"/>
-        <pathelement location="${build-optimised.dir}/classes/partest"/>
-        <pathelement location="${ant.jar}"/>
-      </compilationpath>
-    </scalacfork>
-    <copy todir="${build-optimised.dir}/classes/partest">
-      <fileset dir="${src.dir}/partest">
-        <include name="**/*.xml"/>
-      </fileset>
-    </copy>
-    <touch file="${build-optimised.dir}/partest.complete" verbose="no"/>
-    <stopwatch name="optimised.partest.timer" action="total"/>
+    <touch file="${build-libs.dir}/fjbg.complete" verbose="no"/>
   </target>
-
-  <target name="optimised.pre-bin" depends="optimised.partest">
-    <condition property="optimised.bin.available">
-      <isset property="optimised.comp.available"/>
-    </condition>
+  
+  <target name="libs.pre-fjbgpack" depends="libs.fjbg">
   </target>
-
-  <target name="optimised.bin" depends="optimised.pre-bin" unless="optimised.bin.available">
-    <path id="optimised.bin.classpath">
-      <pathelement location="${build-optimised.dir}/classes/library"/>
-      <pathelement location="${build-optimised.dir}/classes/compiler"/>
-      <pathelement location="${fjbg.jar}"/>
-      <pathelement location="${jline.jar}"/>
-    </path>
-    <taskdef name="optimised-bin" classname="scala.tools.ant.ScalaTool" classpathref="optimised.bin.classpath"/>
-    <mkdir dir="${build-optimised.dir}/bin"/>
-    <optimised-bin
-      file="${build-optimised.dir}/bin/scala"
-      class="scala.tools.nsc.MainGenericRunner"
-      javaFlags="${java.flags}"
-      classpathref="optimised.bin.classpath"/>
-    <optimised-bin
-      file="${build-optimised.dir}/bin/scalac"
-      class="scala.tools.nsc.Main"
-      javaFlags="${java.flags}"
-      classpathref="optimised.bin.classpath"/>
-    <optimised-bin
-      file="${build-optimised.dir}/bin/scaladoc"
-      class="scala.tools.nsc.ScalaDoc"
-      javaFlags="${java.flags}"
-      classpathref="optimised.bin.classpath"/>
-    <optimised-bin
-      file="${build-optimised.dir}/bin/fsc"
-      class="scala.tools.nsc.CompileClient"
-      javaFlags="${java.flags}"
-      classpathref="optimised.bin.classpath"/>
-    <chmod perm="ugo+rx" file="${build-optimised.dir}/bin/scala"/>
-    <chmod perm="ugo+rx" file="${build-optimised.dir}/bin/scalac"/>
-    <chmod perm="ugo+rx" file="${build-optimised.dir}/bin/scaladoc"/>
-    <chmod perm="ugo+rx" file="${build-optimised.dir}/bin/fsc"/>
-    <touch file="${build-optimised.dir}/bin.complete" verbose="no"/>
-  </target>
-
-  <target name="optimised.done" depends="optimised.bin">
-    <path id="optimised.classpath">
-      <pathelement location="${build-optimised.dir}/classes/library"/>
-      <pathelement location="${build-optimised.dir}/classes/compiler"/>
-      <pathelement location="${build-optimised.dir}/classes/partest"/>
-      <pathelement location="${fjbg.jar}"/>
-      <pathelement location="${ant.jar}"/>
-    </path>
+  
+  <target name="libs.fjbgpack" depends="libs.pre-fjbgpack" unless="libs.fjbgpack.available">
+    <jar destfile="${build-libs.dir}/fjbg.jar">
+      <fileset dir="${build-libs.dir}/classes/fjbg"/>
+    </jar>
   </target>
 
-  <target name="optimised.clean">
-    <delete dir="${build-optimised.dir}" includeemptydirs="yes" quiet="yes" failonerror="no"/>
+  <target name="libs.done" depends="libs.msilpack, libs.fjbgpack"/>
+
+  <target name="forkjoin.done" depends="libs.forkjoinpack"/>
+
+  <target name="libs.clean" depends="pack.clean">
+    <delete dir="${build-libs.dir}" includeemptydirs="yes" quiet="yes" failonerror="no"/>
   </target>
 
 <!-- ===========================================================================
@@ -1159,13 +1371,16 @@ DOCUMENTATION
     <mkdir dir="${build-docs.dir}/library"/>
     <scaladoc
       destdir="${build-docs.dir}/library"
-      windowtitle="Scala Library"
-      doctitle="Scala ${version.number} API"
+      doctitle="Scala Standard Library"
+      docversion="${version.number}"
+      docsourceurl="https://lampsvn.epfl.ch/trac/scala/browser/scala/tags/R_2_8_1_final/src/€{FILE_PATH}.scala#L1"
+      sourcepath="${src.dir}"
       classpathref="pack.classpath">
       <src>
         <files includes="${src.dir}/actors"/>
         <files includes="${src.dir}/library/scala"/>
         <files includes="${src.dir}/swing"/>
+        <files includes="${src.dir}/continuations/library"/>
       </src>
       <include name="**/*.scala"/>
       <exclude name="reflect/Code.scala"/>
@@ -1180,6 +1395,7 @@ DOCUMENTATION
       <exclude name="runtime/ScalaRunTime.scala"/>
       <exclude name="runtime/StreamCons.scala"/>
       <exclude name="runtime/StringAdd.scala"/>
+      <exclude name="scala/swing/test/**"/>
     </scaladoc>
     <touch file="${build-docs.dir}/library.complete" verbose="no"/>
     <stopwatch name="docs.lib.timer" action="total"/>
@@ -1198,7 +1414,7 @@ DOCUMENTATION
       classpathref="pack.classpath"
       srcdir="${src.dir}/manual"
       includes="**/*.scala"
-      addparams="${scalac.args}"/>
+      addparams="${scalac.args.all}"/>
     <path id="manual.classpath">
       <pathelement location="${build-pack.dir}/lib/scala-library.jar"/>
       <pathelement location="${build.dir}/manmaker/classes"/>
@@ -1212,7 +1428,7 @@ DOCUMENTATION
     <taskdef name="genman"
              classname="scala.tools.docutil.ManMaker"
              classpathref="manual.classpath"/>
-    <genman command="fsc, sbaz, scala, scalac, scaladoc"
+    <genman command="fsc, sbaz, scala, scalac, scaladoc, scalap"
             htmlout="${build-docs.dir}/manual/html"
             manout="${build-docs.dir}/manual/genman"/>
     <!-- On Windows source and target files can't be the same ! -->
@@ -1242,8 +1458,10 @@ DOCUMENTATION
     <mkdir dir="${build-docs.dir}/compiler"/>
     <scaladoc
       destdir="${build-docs.dir}/compiler"
-      windowtitle="Scala Compiler"
-      doctitle="Scala Compiler ${version.number} API"
+      doctitle="Scala Compiler"
+      docversion="${version.number}"
+      docsourceurl="https://lampsvn.epfl.ch/trac/scala/browser/scala/tags/R_2_8_1_final/src/€{FILE_PATH}.scala#L1"
+      sourcepath="${src.dir}"
       classpathref="pack.classpath"
       srcdir="${src.dir}/compiler">
       <include name="**/*.scala"/>
@@ -1264,75 +1482,80 @@ BOOTRAPING TEST AND TEST SUITE
 ============================================================================ -->
 
   <target name="test.stability" depends="strap.done">
-    <same dir="${build-quick.dir}" todir="${build-strap.dir}" failondifferent="no">
+    <same dir="${build-quick.dir}" todir="${build-strap.dir}" failondifferent="yes">
       <exclude name="**/*.properties"/>
       <exclude name="bin/**"/>
       <exclude name="*.complete"/>
+      <exclude name="misc/scala-devel/plugins/*.jar"/>
     </same>
   </target>
+  
+  <!-- this target will run only those tests found in test/debug -->
+  <target name="test.debug">
+    <antcall target="test.suite">
+      <param name="partest.srcdir" value="debug" />
+    </antcall>
+  </target>
 
   <target name="test.run" depends="pack.done">
     <partest showlog="yes" erroronfailed="yes" javacmd="${java.home}/bin/java"
-             timeout="1200000" javaccmd="${javac.cmd}">
-      <classpath>
+             timeout="1200000"
+             scalacopts="${scalac.args.optimise}">
+      <compilationpath>
         <path refid="pack.classpath"/>
-        <fileset dir="${test.dir}/files/lib" includes="*.jar"/>
-      </classpath>
-      <runtests  dir="${test.dir}/files">
+        <fileset dir="${partest.dir}/files/lib" includes="*.jar" />
+      </compilationpath>
+      <runtests  dir="${partest.dir}/files">
         <include name="run/**/*.scala"/>
         <include name="jvm/**/*.scala"/>
       </runtests>
-      <jvm5tests dir="${test.dir}/files/jvm5" includes="*.scala"/>
     </partest>
   </target>
 
   <target name="test.suite" depends="pack.done">
+    <property name="partest.srcdir" value="files" />
     <partest showlog="yes" erroronfailed="yes" javacmd="${java.home}/bin/java"
-             timeout="1200000" javaccmd="${javac.cmd}">
-      <classpath>
+             timeout="2400000"
+             srcdir="${partest.srcdir}"
+             scalacopts="${scalac.args.optimise}">
+      <compilationpath>
         <path refid="pack.classpath"/>
-        <fileset dir="${test.dir}/files/lib" includes="*.jar"/>
-      </classpath>
-      <postests  dir="${test.dir}/files/pos" includes="*.scala"/>
-      <pos5tests dir="${test.dir}/files/pos5" includes="*.scala"/>
-      <negtests  dir="${test.dir}/files/neg" includes="*.scala"/>
-      <runtests  dir="${test.dir}/files">
+        <pathelement location="${pack.dir}/lib/scala-swing.jar"/>
+        <fileset dir="${partest.dir}/files/lib" includes="*.jar" />
+      </compilationpath>
+      <postests  dir="${partest.dir}/${partest.srcdir}/pos" includes="*.scala"/>
+      <negtests  dir="${partest.dir}/${partest.srcdir}/neg" includes="*.scala"/>
+      <runtests  dir="${partest.dir}/${partest.srcdir}">
         <include name="run/**/*.scala"/>
       </runtests>
-      <jvmtests dir="${test.dir}/files/jvm" includes="*.scala"/>
-      <jvm5tests dir="${test.dir}/files/jvm5" includes="*.scala"/>
-      <residenttests dir="${test.dir}/files/res" includes="*.res"/>
-      <!-- <scripttests dir="${test.dir}/files/script" includes="*.scala"/> -->
-      <shootouttests dir="${test.dir}/files/shootout" includes="*.scala"/>
+      <jvmtests dir="${partest.dir}/${partest.srcdir}/jvm" includes="*.scala"/>
+	  <scalachecktests dir="${partest.dir}/${partest.srcdir}/scalacheck" includes="**/*.scala"/>
+      <residenttests dir="${partest.dir}/${partest.srcdir}/res" includes="*.res"/>
+      <buildmanagertests dir="${partest.dir}/${partest.srcdir}/buildmanager" includes="*"/>
+      <shootouttests dir="${partest.dir}/${partest.srcdir}/shootout" includes="*.scala"/>
+      <scalaptests dir="${partest.dir}/${partest.srcdir}/scalap" includes="**/*.scala"/>
+      <!-- <scripttests dir="${partest.dir}/${partest.srcdir}/script" includes="*.scala"/> -->
     </partest>
   </target>
-  
-  <target name="test.done" depends="test.suite, test.stability"/>
 
-  <target name="optimised.test.suite" depends="optimised.done">
-    <taskdef resource="scala/tools/partest/antlib.xml" classpathref="optimised.classpath"/>
+  <target name="test.continuations.suite" depends="pack.done">
+    <property name="partest.srcdir" value="files" />
     <partest showlog="yes" erroronfailed="yes" javacmd="${java.home}/bin/java"
-             timeout="1200000" javaccmd="${javac.cmd}">
-      <classpath>
-        <path refid="optimised.classpath"/>
-        <fileset dir="${test.dir}/files/lib" includes="*.jar"/>
-      </classpath>
-      <postests  dir="${test.dir}/files/pos" includes="*.scala"/>
-      <pos5tests dir="${test.dir}/files/pos5" includes="*.scala"/>
-      <negtests  dir="${test.dir}/files/neg" includes="*.scala"/>
-      <runtests  dir="${test.dir}/files">
-        <include name="run/**/*.scala"/>
+             timeout="2400000"
+             srcdir="${partest.srcdir}"
+             scalacopts="${scalac.args.optimise} -Xpluginsdir ${build-quick.dir}/misc/scala-devel/plugins -Xplugin-require:continuations -P:continuations:enable">
+      <compilationpath>
+        <path refid="pack.classpath"/>
+        <fileset dir="${partest.dir}/files/lib" includes="*.jar" />
+      </compilationpath>
+      <negtests  dir="${partest.dir}/${partest.srcdir}/continuations-neg" includes="*.scala"/>
+      <runtests  dir="${partest.dir}/${partest.srcdir}">
+        <include name="continuations-run/**/*.scala"/>
       </runtests>
-      <jvmtests dir="${test.dir}/files/jvm" includes="*.scala"/>
-      <jvm5tests dir="${test.dir}/files/jvm5" includes="*.scala"/>
-      <residenttests dir="${test.dir}/files/res" includes="*.res"/>
-      <!-- <scripttests dir="${test.dir}/files/script" includes="*.scala"/> -->
-      <shootouttests dir="${test.dir}/files/shootout" includes="*.scala"/>
     </partest>
   </target>
 
-
-  <target name="optimised.test.done" depends="optimised.test.suite"/>
+  <target name="test.done" depends="test.suite, test.continuations.suite, test.stability"/>
 
 <!-- ===========================================================================
 DISTRIBUTION
@@ -1355,6 +1578,11 @@ DISTRIBUTION
     <chmod perm="ugo+rx" file="${dist.dir}/bin/scalac"/>
     <chmod perm="ugo+rx" file="${dist.dir}/bin/scaladoc"/>
     <chmod perm="ugo+rx" file="${dist.dir}/bin/fsc"/>
+    <chmod perm="ugo+rx" file="${dist.dir}/bin/scalap"/>
+    <mkdir dir="${dist.dir}/misc/scala-devel/plugins"/>
+    <copy toDir="${dist.dir}/misc/scala-devel/plugins">
+      <fileset dir="${build-pack.dir}/misc/scala-devel/plugins"/>
+    </copy>
   </target>
 
   <target name="dist.doc" depends="dist.base">
@@ -1389,6 +1617,7 @@ DISTRIBUTION
     <jar destfile="${dist.dir}/src/scala-library-src.jar">
       <fileset dir="${src.dir}/library"/>
       <fileset dir="${src.dir}/actors"/>
+      <fileset dir="${src.dir}/continuations/library"/>
     </jar>
     <jar destfile="${dist.dir}/src/scala-dbc-src.jar">
       <fileset dir="${src.dir}/dbc"/>
@@ -1399,6 +1628,13 @@ DISTRIBUTION
     <jar destfile="${dist.dir}/src/scala-compiler-src.jar">
       <fileset dir="${src.dir}/compiler"/>
     </jar>
+    <jar destfile="${dist.dir}/src/scalap-src.jar">
+      <fileset dir="${src.dir}/scalap"/>
+    </jar>
+    <!-- Needed for Maven distribution -->
+    <jar destfile="${dist.dir}/src/scala-partest-src.jar">
+      <fileset dir="${src.dir}/partest"/>
+    </jar>
   </target>
 
   <target name="dist.latest.unix" depends="dist.src" unless="os.win">
@@ -1431,7 +1667,7 @@ TEST AND DISTRIBUTION BUNDLE (ALL)
 STABLE REFERENCE (STARR)
 ============================================================================ -->
 <!-- Does not use any properties other than ${basedir}, so that it can
-     run without 'init' (when using 'newstarrwin') -->
+     run without 'init' (when using 'replacestarrwin') -->
 
   <target name="starr.start">
     <fail message="Library in build/pack not available">
@@ -1453,9 +1689,10 @@ STABLE REFERENCE (STARR)
     <delete file="${basedir}/lib/scala-library-src.jar"/>
   </target>
 
-  <target name="starr.lib" depends="starr.clean">
-    <copy file="${basedir}/build/pack/lib/scala-library.jar"
-          toFile="${basedir}/lib/scala-library.jar"/>
+  <target name="starr.lib" depends="starr.start">
+    <jar destfile="${basedir}/lib/scala-library.jar">
+      <fileset dir="${basedir}/build/quick/classes/library"/>
+    </jar>
   </target>
 
   <target name="starr.comp" depends="starr.lib">
@@ -1468,48 +1705,22 @@ STABLE REFERENCE (STARR)
     <jar destfile="${basedir}/lib/scala-library-src.jar">
       <fileset dir="${basedir}/src/library"/>
       <fileset dir="${basedir}/src/actors"/>
+      <fileset dir="${basedir}/src/swing"/>
+      <fileset dir="${basedir}/src/dbc"/>
     </jar>
   </target>
 
-  <target name="starr.done" depends="starr.src"/>
-
-<!-- ===========================================================================
-FORWARDED TARGETS FOR JVM 1.4 BUILD
-============================================================================ -->
-  
-  <target name="four" depends="pack.done">
-    <ant antfile="${src.dir}/build/four.xml" target="four-pack.done" inheritall="yes" inheritrefs="yes"/>
-  </target>
-
-  <target name="fourtest" depends="pack.done">
-    <ant antfile="${src.dir}/build/four.xml" target="four-test.done" inheritall="yes" inheritrefs="yes"/>
-  </target>
-
-  <target name="fourdist" depends="pack.done">
-    <ant antfile="${src.dir}/build/four.xml" target="four-all.done" inheritall="yes" inheritrefs="yes"/>
-  </target>
-
-  <target name="fourclean">
-    <ant antfile="${src.dir}/build/four.xml" target="four-all.clean" inheritall="yes" inheritrefs="yes"/>
-  </target>
-
-<!-- ===========================================================================
-FORWARDED TARGETS FOR MSIL BUILD
-============================================================================ -->
-
-  <target name="msil" depends="pack.done">
-    <ant antfile="${src.dir}/build/msil.xml" target="msil-pack.done" inheritall="yes" inheritrefs="yes"/>
-  </target>
-
-  <target name="msiltest"/>
-
-  <target name="msildist" depends="pack.done">
-    <ant antfile="${src.dir}/build/msil.xml" target="msil-all.done" inheritall="yes" inheritrefs="yes"/>
+  <target name="starr.libs" depends="starr.src" if="libs.outdated">
+    <copy toDir="${lib.dir}" overwrite="yes">
+      <fileset dir="${build-libs.dir}">
+        <include name="fjbg.jar"/>
+        <include name="msil.jar"/>
+        <include name="forkjoin.jar"/>
+      </fileset>
+    </copy>
   </target>
 
-  <target name="msilclean">
-    <ant antfile="${src.dir}/build/msil.xml" target="msil-all.clean" inheritall="yes" inheritrefs="yes"/>
-  </target>
+  <target name="starr.done" depends="starr.libs"/>
 
 <!-- ===========================================================================
 FORWARDED TARGETS FOR PACKAGING
@@ -1518,43 +1729,127 @@ FORWARDED TARGETS FOR PACKAGING
   <target name="distpack" depends="dist.done">
     <ant antfile="${src.dir}/build/pack.xml" target="pack-all.done" inheritall="yes" inheritrefs="yes"/>
   </target>
-  
-  <target name="fourdistpack" depends="pack.done">
-    <ant antfile="${src.dir}/build/four.xml" target="four-dist.done" inheritall="yes" inheritrefs="yes"/>
-    <ant antfile="${src.dir}/build/pack.xml" target="fourpack-all.done" inheritall="yes" inheritrefs="yes"/>
-  </target>
 
-  <target name="msildistpack" depends="pack.done">
-    <ant antfile="${src.dir}/build/msil.xml" target="msil-dist.done" inheritall="yes" inheritrefs="yes"/>
-    <ant antfile="${src.dir}/build/pack.xml" target="msilpack-all.done" inheritall="yes" inheritrefs="yes"/>
+  <target name="distpack-opt"
+    description="Builds an optimised distribution.">
+    <antcall target="distpack">
+      <param name="scalac.args.optimise" value="-optimise"/>
+    </antcall>
   </target>
-
+  
   <!-- Used by the scala-installer script -->
-  <target name="alldistpack" depends="distpack, fourdistpack, msildistpack"/>
-  <target name="allallclean" depends="all.clean, fourclean, msilclean"/>
+  <target name="allallclean" depends="all.clean"/>
 
 <!-- ===========================================================================
 FORWARDED TARGETS FOR NIGHTLY BUILDS
 ============================================================================ -->
 
-  <target name="nightly" depends="all.done">
+  <target name="nightly">
+    <antcall target="nightly-nopt">
+      <param name="scalac.args.optimise" value="-optimise"/>
+    </antcall>
+  </target>
+
+  <target name="nightly-nopt" depends="all.done">
+    <!-- cannot antcall all.done, the properties defined in there (dist.dir) are not returned. need depends. -->
     <ant antfile="${src.dir}/build/pack.xml" target="pack-all.done" inheritall="yes" inheritrefs="yes"/>
   </target>
 
-  <target name="fournightly" depends="pack.done">
-    <ant antfile="${src.dir}/build/four.xml" target="four-all.done" inheritall="yes" inheritrefs="yes"/>
-    <ant antfile="${src.dir}/build/pack.xml" target="fourpack-all.done" inheritall="yes" inheritrefs="yes"/>
+  <target name="nightly.checkinit">
+    <antcall target="nightly-nopt">
+      <param name="scalac.args.optimise" value="-Xcheckinit"/>
+    </antcall>
   </target>
 
-  <target name="fourfournightly">
-    <ant antfile="${src.dir}/build/four.xml" target="fourfour-test.done"/>
+  <target name="nightly.checkall">
+    <antcall target="nightly-nopt">
+      <param name="partest.scalacopts" value="-Ycheck:all"/>
+    </antcall>
   </target>
 
-  <target name="msilnightly" depends="pack.done">
-    <ant antfile="${src.dir}/build/msil.xml" target="msil-all.done" inheritall="yes" inheritrefs="yes"/>
-    <ant antfile="${src.dir}/build/pack.xml" target="msilpack-all.done" inheritall="yes" inheritrefs="yes"/>
+<!-- ===========================================================================
+POSITIONS
+============================================================================ -->
+
+  <target name="test.positions" depends="quick.comp">
+    <antcall target="test.positions.tests.sub" inheritRefs="true">
+      <param name="test.tests.srcs" value="${partest.dir}/files/positions"/>
+    </antcall>
+    <antcall target="test.positions.sub" inheritRefs="true">
+      <param name="test.srcs" value="${src.dir}/compiler"/>
+    </antcall>
+    <antcall target="test.positions.sub" inheritRefs="true">
+      <param name="test.srcs" value="${src.dir}/library"/>
+    </antcall>
+    <antcall target="test.positions.sub" inheritRefs="true">
+      <param name="test.srcs" value="${src.dir}/actors"/>
+    </antcall>
+    <antcall target="test.positions.sub" inheritRefs="true">
+      <param name="test.srcs" value="${src.dir}/dbc"/>
+    </antcall>
+    <antcall target="test.positions.sub" inheritRefs="true">
+      <param name="test.srcs" value="${src.dir}/swing"/>
+    </antcall>
+    <antcall target="test.positions.sub" inheritRefs="true">
+      <param name="test.srcs" value="${src.dir}/partest"/>
+    </antcall>
+    <antcall target="test.positions.sub" inheritRefs="true">
+      <param name="test.srcs" value="${src.dir}/scalap"/>
+    </antcall>
+    <antcall target="test.positions.tests.sub" inheritRefs="true">
+      <param name="test.tests.srcs" value="${partest.dir}/files/pos"/>
+    </antcall>
+    <antcall target="test.positions.tests.sub" inheritRefs="true">
+      <param name="test.tests.srcs" value="${partest.dir}/files/run"/>
+    </antcall>
+    <antcall target="test.positions.tests.sub" inheritRefs="true">
+      <param name="test.tests.srcs" value="${partest.dir}/files/neg"/>
+    </antcall>
+  </target>
+  
+  <target name="test.positions.sub">
+    <echo message="Validating positions for: ${test.srcs}"/>
+    <if>
+      <isfileselected file="${test.srcs}">
+        <type type="dir"/>
+      </isfileselected>
+      <then>
+        <property name="srcdir" value="${test.srcs}"/>
+        <property name="srcs" value="**/*.scala"/>
+      </then>
+      <else>
+        <dirname property="srcdir" file="${test.srcs}"/>
+        <basename property="srcs" file="${test.srcs}"/>
+      </else>
+    </if>
+    <scalacfork
+      destdir=""
+      compilerpathref="locker.classpath"
+      srcpath="${srcdir}"
+      params="-Xprint-pos -Yide-debug"
+      srcdir="${srcdir}"
+      jvmargs="${scalacfork.jvmargs}">
+      <include name="${srcs}"/>
+      <compilationpath>
+        <pathelement location="${build-quick.dir}/classes/library"/>
+      </compilationpath>
+    </scalacfork>
   </target>
 
+  <target name="test.positions.tests.sub">
+    <foreach target="test.positions.sub"
+      inheritAll="true"
+      inheritRefs="true"
+      param="test.srcs">
+      <path>
+        <fileset dir="${test.tests.srcs}" includes="*.scala"/>
+        <dirset dir="${test.tests.srcs}">
+          <include name="*"/>
+        </dirset>
+      </path>
+    </foreach>
+  </target>
+  
 <!-- ===========================================================================
 MISCELLANEOUS
 ============================================================================ -->
diff --git a/docs/LICENSE b/docs/LICENSE
index fd4d83e..b75bb42 100644
--- a/docs/LICENSE
+++ b/docs/LICENSE
@@ -1,6 +1,6 @@
 SCALA LICENSE
 
-Copyright (c) 2002-2009 EPFL, Lausanne, unless otherwise specified.
+Copyright (c) 2002-2010 EPFL, Lausanne, unless otherwise specified.
 All rights reserved.
 
 This software was developed by the Programming Methods Laboratory of the
diff --git a/docs/README b/docs/README
index f63f2e2..bcc7108 100644
--- a/docs/README
+++ b/docs/README
@@ -2,11 +2,11 @@
 Scala Software Distributions
 ----------------------------
 
-- scala-<major>.<minor>.<patch>.tar.bz2     Unis distribution
+- scala-<major>.<minor>.<patch>.tar.bz2     Unix distribution
 - scala-<major>.<minor>.<patch>.tar.gz      Unix distribution
 - scala-<major>.<minor>.<patch>.zip         Windows distribution
 
-The standard distributions require Java 1.4.x or above. If you don't
+The standard distributions require Java 1.5 or above. If you don't
 know which version of Java you have, run the command "java -version".
 
 
@@ -32,7 +32,8 @@ directly accessible.
 
 You may test the distribution by running the following commands:
 
-$ ./bin/scalac share/doc/scala/examples/sort.scala
+$ ./bin/sbaz install scala-devel-docs
+$ ./bin/scalac doc/scala-devel-docs/examples/sort.scala
 $ ./bin/scala examples.sort
 [6,2,8,5,1]
 [1,2,5,6,8]
diff --git a/docs/TODO b/docs/TODO
index a13efdf..094202f 100644
--- a/docs/TODO
+++ b/docs/TODO
@@ -1,7 +1,6 @@
 //###########################################################-*-outline-*-####
 // TODO list
 //############################################################################
-// $Id: TODO 5371 2005-12-16 18:48:00Z dubochet $
 
 * Histories
 
diff --git a/docs/android-examples/FileBrowser/AndroidManifest.xml b/docs/android-examples/FileBrowser/AndroidManifest.xml
deleted file mode 100644
index c61667d..0000000
--- a/docs/android-examples/FileBrowser/AndroidManifest.xml
+++ /dev/null
@@ -1,11 +0,0 @@
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
-    package="org.anddev.android.filebrowser">
-    <application>
-        <activity class=".AndroidFileBrowser" android:label="AndroidFileBrowser">
-            <intent-filter>
-                <action android:value="android.intent.action.MAIN" />
-                <category android:value="android.intent.category.LAUNCHER" />
-            </intent-filter>
-        </activity>
-    </application>
-</manifest> 
diff --git a/docs/android-examples/FileBrowser/build.xml b/docs/android-examples/FileBrowser/build.xml
deleted file mode 100644
index d501e5c..0000000
--- a/docs/android-examples/FileBrowser/build.xml
+++ /dev/null
@@ -1,222 +0,0 @@
-<?xml version="1.0" ?>
-<project name="AndroidFileBrowser" default="package">
-    <property name="sdk-folder" value="/home/linuxsoft/apps/android-m3-rc37a" />
-    <property name="android-tools" value="/home/linuxsoft/apps/android-m3-rc37a/tools" />
-
-    <!-- The intermediates directory -->
-    <!-- Eclipse uses "bin" for its own output, so we do the same. -->
-    <property name="outdir" value="bin" />
-
-    <!-- No user servicable parts below. -->
-
-    <!-- Input directories -->
-    <property name="resource-dir" value="res" />
-    <property name="asset-dir" value="assets" />
-    <property name="srcdir" value="src" />
-
-    <!-- Output directories -->
-    <property name="outdir-classes" value="${outdir}/classes" />
-
-    <!-- Create R.java in the source directory -->
-    <property name="outdir-r" value="src" />
-
-    <!-- Intermediate files -->
-    <property name="dex-file" value="classes.dex" />
-    <property name="intermediate-dex" value="${outdir}/${dex-file}" />
-
-    <!-- The final package file to generate -->
-    <property name="out-package" value="${outdir}/${ant.project.name}.apk" />
-
-    <!-- Tools -->
-    <property name="aapt" value="${android-tools}/aapt" />
-    <property name="aidl" value="${android-tools}/aidl" />
-    <property name="dx" value="${android-tools}/dx" />
-    <property name="zip" value="zip" />
-    <property name="android-jar" value="${sdk-folder}/android.jar" />
-
-    <!-- Scala -->
-    <property environment="env"/>
-    <property name="scala.dir" value="${env.SCALA_HOME}"/>
-    <property name="scala-compiler.jar" value="${scala.dir}/lib/scala-compiler.jar"/>
-    <property name="scala-library.jar" value="${scala.dir}/lib/scala-library.jar"/>
-    <property name="scala-android.jar" value="${scala.dir}/lib/scala-android.jar"/>
-    <fail message="Missing library scala-android.jar (use sbaz to install it)">
-      <condition><not><available file="${scala-android.jar}"/></not></condition>
-    </fail>
-    <property name="scala-depend.jar" value="${android-tools}/lib/scala-depend.jar"/>
-    <path id="scala.path">
-        <pathelement path="${scala-library.jar}"/>
-        <pathelement path="${scala-compiler.jar}"/>
-    </path>
-    <path id="scalac.path">
-        <pathelement path="${android-jar}"/>
-        <pathelement path="${scala-library.jar}"/>
-    </path>
-    <taskdef
-        resource="scala/tools/ant/antlib.xml"
-        classpathref="scala.path"
-    />
-    <macrodef name="smartjar">
-        <attribute name="srcdir"/>
-        <attribute name="basedir"/>
-        <attribute name="classname"/>
-        <attribute name="destfile"/>
-        <sequential>
-          <depend
-            srcdir="@{srcdir}"
-            destdir="@{basedir}" closure="true"
-            cache="@{basedir}"
-            classpath="${android-jar}"
-          />
-          <java
-             classname="ch.epfl.lamp.util.depend" output="@{basedir}/classes.dep"
-             classpath="${scala-library.jar}${path.separator}${scala-depend.jar}">
-            <arg line="@{basedir}${file.separator}dependencies.txt"/>
-            <arg line="@{classname}"/>
-          </java>
-          <jar
-            destfile="@{destfile}"
-            basedir="@{basedir}"
-            includesfile="@{basedir}/classes.dep"
-           />
-        </sequential>
-    </macrodef>
-
-    <!-- Rules -->
-
-    <!-- Create the output directories if they don't exist yet. -->
-    <target name="dirs">
-        <mkdir dir="${outdir}" />
-        <mkdir dir="${outdir-classes}" />
-    </target>
-
-    <!-- Generate the R.java file for this project's resources. -->
-    <target name="resource-src" depends="dirs">
-        <echo>Generating R.java...</echo>
-        <exec executable="${aapt}" failonerror="true">
-            <arg value="compile" />
-            <arg value="-m" />
-            <arg value="-J" />
-            <arg value="${outdir-r}" />
-            <arg value="-M" />
-            <arg value="AndroidManifest.xml" />
-            <arg value="-S" />
-            <arg value="${resource-dir}" />
-            <arg value="-I" />
-            <arg value="${android-jar}" />
-        </exec>
-    </target>
-
-    <!-- Generate java classes from .aidl files. -->
-    <target name="aidl" depends="dirs">
-        <apply executable="${aidl}" failonerror="true">
-            <fileset dir="${srcdir}">
-                <include name="**/*.aidl"/>
-            </fileset>
-        </apply>
-    </target>
-
-    <!-- Compile this project's .java files into .class files. -->
-    <target name="compile" depends="dirs, resource-src, aidl">
-        <javac encoding="ascii" target="1.5" debug="true" extdirs=""
-                srcdir="."
-                destdir="${outdir-classes}"
-                bootclasspath="${android-jar}" />
-        <scalac encoding="ascii" target="jvm-1.5"
-            srcdir="${srcdir}"
-            destdir="${outdir-classes}"
-            bootclasspathref="scalac.path" />
-        <unjar src="${scala-android.jar}" dest="${outdir-classes}"/>
-        <smartjar
-          srcdir="${srcdir}"
-          basedir="${outdir-classes}"
-          classname="org.anddev.android.filebrowser.AndroidFileBrowser"
-          destfile="${outdir}/${ant.project.name}.jar"
-        />
-        <delete includeemptydirs="true">
-          <fileset dir="${outdir-classes}" includes="**/*"/>
-        </delete>
-        <unjar src="${outdir}/${ant.project.name}.jar" dest="${outdir-classes}"/>
-    </target>
-
-    <!-- Convert this project's .class files into .dex files. -->
-    <target name="dex" depends="compile">
-        <exec executable="${dx}" failonerror="true">
-            <arg value="-JXmx384M" />
-            <arg value="--dex" />
-            <arg value="--output=${intermediate-dex}" />
-            <arg value="--locals=full" />
-            <arg value="--positions=lines" />
-            <arg path="${outdir-classes}" />
-        </exec>
-    </target>
-
-    <!-- Put the project's resources into the output package file. -->
-    <target name="package-res-and-assets">
-        <echo>Packaging resources and assets...</echo>
-        <exec executable="${aapt}" failonerror="true">
-            <arg value="package" />
-            <arg value="-f" />
-            <arg value="-c" />
-            <arg value="-M" />
-            <arg value="AndroidManifest.xml" />
-            <arg value="-S" />
-            <arg value="${resource-dir}" />
-            <arg value="-A" />
-            <arg value="${asset-dir}" />
-            <arg value="-I" />
-            <arg value="${android-jar}" />
-            <arg value="${out-package}" />
-        </exec>
-    </target>
-
-    <!-- Same as package-res-and-assets, but without "-A ${asset-dir}" -->
-    <target name="package-res-no-assets">
-        <echo>Packaging resources...</echo>
-        <exec executable="${aapt}" failonerror="true">
-            <arg value="package" />
-            <arg value="-f" />
-            <arg value="-c" />
-            <arg value="-M" />
-            <arg value="AndroidManifest.xml" />
-            <arg value="-S" />
-            <arg value="${resource-dir}" />
-            <!-- No assets directory -->
-            <arg value="-I" />
-            <arg value="${android-jar}" />
-            <arg value="${out-package}" />
-        </exec>
-    </target>
-
-    <!-- Invoke the proper target depending on whether or not
-         an assets directory is present. -->
-    <!-- TODO: find a nicer way to include the "-A ${asset-dir}" argument
-         only when the assets dir exists. -->
-    <target name="package-res">
-        <available file="${asset-dir}" type="dir"
-                property="res-target" value="and-assets" />
-        <property name="res-target" value="no-assets" />
-        <antcall target="package-res-${res-target}" />
-    </target>
-
-    <!-- Put the project's .class files into the output package file. -->
-    <target name="package-java" depends="compile, package-res">
-        <echo>Packaging java...</echo>
-        <jar destfile="${out-package}"
-                basedir="${outdir-classes}"
-                update="true" />
-    </target>
-
-    <!-- Put the project's .dex files into the output package file. -->
-    <target name="package-dex" depends="dex, package-res">
-        <echo>Packaging dex...</echo>
-        <exec executable="${zip}" failonerror="true">
-            <arg value="-qj" />
-            <arg value="${out-package}" />
-            <arg value="${intermediate-dex}" />
-        </exec>
-    </target>
-
-    <!-- Create the package file for this project from the sources. -->
-    <target name="package" depends="package-dex" />
-</project>
diff --git a/docs/android-examples/FileBrowser/res/drawable/audio.png b/docs/android-examples/FileBrowser/res/drawable/audio.png
deleted file mode 100644
index 40eda1a..0000000
Binary files a/docs/android-examples/FileBrowser/res/drawable/audio.png and /dev/null differ
diff --git a/docs/android-examples/FileBrowser/res/drawable/folder.png b/docs/android-examples/FileBrowser/res/drawable/folder.png
deleted file mode 100644
index 6fa1283..0000000
Binary files a/docs/android-examples/FileBrowser/res/drawable/folder.png and /dev/null differ
diff --git a/docs/android-examples/FileBrowser/res/drawable/goroot.png b/docs/android-examples/FileBrowser/res/drawable/goroot.png
deleted file mode 100644
index dafcc7b..0000000
Binary files a/docs/android-examples/FileBrowser/res/drawable/goroot.png and /dev/null differ
diff --git a/docs/android-examples/FileBrowser/res/drawable/icon.png b/docs/android-examples/FileBrowser/res/drawable/icon.png
deleted file mode 100644
index 1d6ce31..0000000
Binary files a/docs/android-examples/FileBrowser/res/drawable/icon.png and /dev/null differ
diff --git a/docs/android-examples/FileBrowser/res/drawable/image.png b/docs/android-examples/FileBrowser/res/drawable/image.png
deleted file mode 100644
index 46a509f..0000000
Binary files a/docs/android-examples/FileBrowser/res/drawable/image.png and /dev/null differ
diff --git a/docs/android-examples/FileBrowser/res/drawable/packed.png b/docs/android-examples/FileBrowser/res/drawable/packed.png
deleted file mode 100644
index 64587e2..0000000
Binary files a/docs/android-examples/FileBrowser/res/drawable/packed.png and /dev/null differ
diff --git a/docs/android-examples/FileBrowser/res/drawable/text.png b/docs/android-examples/FileBrowser/res/drawable/text.png
deleted file mode 100644
index 9e9f8b5..0000000
Binary files a/docs/android-examples/FileBrowser/res/drawable/text.png and /dev/null differ
diff --git a/docs/android-examples/FileBrowser/res/drawable/uponelevel.png b/docs/android-examples/FileBrowser/res/drawable/uponelevel.png
deleted file mode 100644
index 9d1d81e..0000000
Binary files a/docs/android-examples/FileBrowser/res/drawable/uponelevel.png and /dev/null differ
diff --git a/docs/android-examples/FileBrowser/res/drawable/webtext.png b/docs/android-examples/FileBrowser/res/drawable/webtext.png
deleted file mode 100644
index c61d754..0000000
Binary files a/docs/android-examples/FileBrowser/res/drawable/webtext.png and /dev/null differ
diff --git a/docs/android-examples/FileBrowser/res/layout/file_row.xml b/docs/android-examples/FileBrowser/res/layout/file_row.xml
deleted file mode 100644
index 8f5efd7..0000000
--- a/docs/android-examples/FileBrowser/res/layout/file_row.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<TextView
-	xmlns:android="http://schemas.android.com/apk/res/android"
-	android:layout_width="fill_parent"
-	android:layout_height="wrap_content"
-/>
\ No newline at end of file
diff --git a/docs/android-examples/FileBrowser/res/layout/main.xml b/docs/android-examples/FileBrowser/res/layout/main.xml
deleted file mode 100644
index 27e40f0..0000000
--- a/docs/android-examples/FileBrowser/res/layout/main.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
-    android:orientation="vertical"
-    android:layout_width="fill_parent"
-    android:layout_height="fill_parent"
-    >
-<TextView  
-    android:layout_width="fill_parent" 
-    android:layout_height="wrap_content" 
-    android:text="Hello World, AndroidFileBrowser"
-    />
-</LinearLayout>
\ No newline at end of file
diff --git a/docs/android-examples/FileBrowser/res/values/fileendings.xml b/docs/android-examples/FileBrowser/res/values/fileendings.xml
deleted file mode 100644
index 6efb5ac..0000000
--- a/docs/android-examples/FileBrowser/res/values/fileendings.xml
+++ /dev/null
@@ -1,28 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<resources>
-<array name="fileEndingImage">
-        <item>.png</item>
-        <item>.gif</item>
-        <item>.jpg</item>
-        <item>.jpeg</item>
-        <item>.bmp</item>
-    </array>
-<array name="fileEndingAudio">
-        <item>.mp3</item>
-        <item>.wav</item>
-        <item>.ogg</item>
-        <item>.midi</item>
-    </array>
-<array name="fileEndingPackage">
-        <item>.jar</item>
-        <item>.zip</item>
-        <item>.rar</item>
-        <item>.gz</item>
-    </array>
-<array name="fileEndingWebText">
-        <item>.htm</item>
-        <item>.html</item>
-        <item>.php</item>
-    </array>
-</resources>
-     
\ No newline at end of file
diff --git a/docs/android-examples/FileBrowser/res/values/strings.xml b/docs/android-examples/FileBrowser/res/values/strings.xml
deleted file mode 100644
index 8b4e531..0000000
--- a/docs/android-examples/FileBrowser/res/values/strings.xml
+++ /dev/null
@@ -1,10 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<resources>
-    <string name="app_name">Android File Browser - anddev.org</string>
-    <string name="dirname_app_name">Android File Browser - by anddev.org</string>
-    <string name="menu_new_folder">New Folder</string>
-    <string name="dirnameinput_cmd_return">Save</string>
-    <string name="dirnameinput_hint">Enter a directory-name:</string>
-    <string name="up_one_level">..</string>
-    <string name="current_dir">.</string>
-</resources>
diff --git a/docs/android-examples/FileBrowser/src/org/anddev/android/filebrowser/AndroidFileBrowser.scala b/docs/android-examples/FileBrowser/src/org/anddev/android/filebrowser/AndroidFileBrowser.scala
deleted file mode 100644
index 3e8d82a..0000000
--- a/docs/android-examples/FileBrowser/src/org/anddev/android/filebrowser/AndroidFileBrowser.scala
+++ /dev/null
@@ -1,196 +0,0 @@
-package org.anddev.android.filebrowser
-
-import java.io.File
-import java.net.URISyntaxException
-import java.util.Collections
-
-import scala.collection.jcl.ArrayList
-
-import _root_.android.app.{AlertDialog, ListActivity}
-import _root_.android.content.{DialogInterface, Intent}
-import _root_.android.content.DialogInterface.OnClickListener
-import _root_.android.graphics.drawable.Drawable
-import _root_.android.net.ContentURI
-import _root_.android.os.Bundle
-import _root_.android.view.View
-import _root_.android.widget.ListView
-
-import iconifiedlist.{IconifiedText, IconifiedTextListAdapter}
-
-/**
- *  Based on plusminus's tutorial on anddev.org
- *  (http://www.anddev.org/android_filebrowser__v20-t101.html)
- */
-class AndroidFileBrowser extends ListActivity {
-     
-  private object DISPLAYMODE extends Enumeration {
-    val ABSOLUTE, RELATIVE = Value
-  }
-  import DISPLAYMODE._
-
-  private val displayMode = ABSOLUTE
-  private val directoryEntries = new ArrayList[IconifiedText]()
-  private var currentDirectory = new File("/")
-
-  /** Called when the activity is first created. */
-  override def onCreate(icicle: Bundle) {
-    super.onCreate(icicle)
-    browseToRoot()
-  }
-
-  /**
-   * This function browses to the
-   * root-directory of the file-system.
-   */
-  private def browseToRoot() {
-    browseTo(new File("/"))
-  }
-
-  /**
-   * This function browses up one level
-   * according to the field: currentDirectory
-   */
-  private def upOneLevel() {
-    if (currentDirectory.getParent() != null)
-      browseTo(currentDirectory.getParentFile())
-  }
-
-  private def browseTo(aDirectory: File) {
-    // On relative we display the full path in the title.
-    if (displayMode == RELATIVE)
-      setTitle(aDirectory.getAbsolutePath() + " :: " +
-               getString(R.string.app_name))
-    if (aDirectory.isDirectory) {
-      currentDirectory = aDirectory
-      fill(aDirectory.listFiles())
-    } else {
-      val okButtonListener = new OnClickListener() {
-        // @Override
-        def onClick(arg0: DialogInterface, arg1: Int) {
-          // Lets start an intent to View the file, that was clicked...
-          openFile(aDirectory)
-        }
-      }
-      val cancelButtonListener = new OnClickListener() {
-        // @Override
-        def onClick(arg0: DialogInterface, arg1: Int) {
-          // Do nothing
-        }
-      }
-      AlertDialog.show(
-        this,
-        "Question", "Do you want to open that file?\n" + aDirectory.getName(),
-        "OK", okButtonListener,
-        "Cancel", cancelButtonListener,
-        false, null
-      )
-    }
-  }
-
-  private def openFile(aFile: File) {
-    try {
-      val myIntent = new Intent(
-        _root_.android.content.Intent.VIEW_ACTION,
-        new ContentURI("file://" + aFile.getAbsolutePath()));
-      startActivity(myIntent);
-    } catch {
-      case e: URISyntaxException =>
-        e.printStackTrace()
-    }
-  } 
-
-  private def fill(files: Array[File]) {
-    directoryEntries.clear()
-
-    // Add the "." == "current directory"
-    directoryEntries.add(
-      new IconifiedText(
-        getString(R.string.current_dir),
-        getResources().getDrawable(R.drawable.folder)))
-    // and the ".." == 'Up one level'
-    if (currentDirectory.getParent() != null)
-      directoryEntries.add(
-        new IconifiedText(
-          getString(R.string.up_one_level),
-          getResources().getDrawable(R.drawable.uponelevel)));
-
-    var currentIcon: Drawable = null
-    for (currentFile <- files) {
-      if (currentFile.isDirectory) {
-        currentIcon = getResources().getDrawable(R.drawable.folder);
-      } else {
-        val fileName = currentFile.getName();
-        /* Determine the Icon to be used,
-         * depending on the FileEndings defined in:
-         * res/values/fileendings.xml. */
-        if (checkEndsWithInStringArray(fileName, getResources().
-                                       getStringArray(R.array.fileEndingImage))) {
-          currentIcon = getResources().getDrawable(R.drawable.image);
-        } else if (checkEndsWithInStringArray(fileName, getResources().
-                                        getStringArray(R.array.fileEndingWebText))) {
-          currentIcon = getResources().getDrawable(R.drawable.webtext)
-        } else if (checkEndsWithInStringArray(fileName, getResources().
-                                        getStringArray(R.array.fileEndingPackage))) {
-          currentIcon = getResources().getDrawable(R.drawable.packed)
-        } else if (checkEndsWithInStringArray(fileName, getResources().
-                                        getStringArray(R.array.fileEndingAudio))){
-          currentIcon = getResources().getDrawable(R.drawable.audio)
-        } else {
-          currentIcon = getResources().getDrawable(R.drawable.text)
-        }                   
-      }
-      displayMode match {
-        case ABSOLUTE =>
-          /* On absolute Mode, we show the full path */
-          directoryEntries.add(new IconifiedText(currentFile.getPath(), currentIcon))
-        case RELATIVE =>
-          /* On relative Mode, we have to cut the
-           * current-path at the beginning */
-          val currentPathStringLenght = currentDirectory.getAbsolutePath().length()
-          directoryEntries.add(new IconifiedText(
-                                   currentFile.getAbsolutePath().
-                                   substring(currentPathStringLenght),
-                                   currentIcon))
-      }
-    }
-    Collections.sort(directoryEntries.underlying)
-          
-    val itla = new IconifiedTextListAdapter(this)
-    itla setListItems directoryEntries      
-    setListAdapter(itla)
-  }
-
-  protected override def onListItemClick(l: ListView, v: View, position: Int, id: Long) {
-    super.onListItemClick(l, v, position, id)
-    val selectionRowID = getSelectionRowID().toInt
-    val selectedFileString = directoryEntries(selectionRowID).getText
-    if (selectedFileString equals getString(R.string.current_dir)) {
-      // Refresh
-      browseTo(currentDirectory)
-    } else if (selectedFileString equals getString(R.string.up_one_level)) {
-      upOneLevel()
-    } else {
-      val clickedFile = new File(
-        displayMode match {
-          case RELATIVE =>
-            currentDirectory.getAbsolutePath() + directoryEntries(selectionRowID).getText
-          case ABSOLUTE =>
-            directoryEntries(selectionRowID).getText
-        }
-      )
-      if (clickedFile != null)
-        browseTo(clickedFile)
-    }
-  }
-
-  /** Checks whether checkItsEnd ends with
-   * one of the Strings from fileEndings */
-  private def checkEndsWithInStringArray(checkItsEnd: String,
-                         fileEndings: Array[String]): Boolean = {
-    for (aEnd <- fileEndings) {
-      if (checkItsEnd endsWith aEnd)
-        return true
-    }
-    false
-  }
-}
diff --git a/docs/android-examples/FileBrowser/src/org/anddev/android/filebrowser/iconifiedlist/IconifiedText.scala b/docs/android-examples/FileBrowser/src/org/anddev/android/filebrowser/iconifiedlist/IconifiedText.scala
deleted file mode 100644
index 0150876..0000000
--- a/docs/android-examples/FileBrowser/src/org/anddev/android/filebrowser/iconifiedlist/IconifiedText.scala
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Copyright 2007 Steven Osborn
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.anddev.android.filebrowser.iconifiedlist
-
-import _root_.android.graphics.drawable.Drawable
-
-/**
- *  Based on Steven Osborn's tutorial on anddev.org
- *  (http://www.anddev.org/iconified_textlist_-_the_making_of-t97.html)
- */
-class IconifiedText(text: String, bullet: Drawable) extends Comparable/*[IconifiedText]*/ {
-
-  private var mText = text
-  private var mIcon: Drawable = bullet
-  private var mSelectable = true
-
-  def isSelectable: Boolean = mSelectable
-
-  def setSelectable(selectable: Boolean) {
-    mSelectable = selectable
-  }
-
-  def getText: String = mText
-
-  def setText(text: String) {
-    mText = text
-  }
-
-  def setIcon(icon: Drawable) {
-    mIcon = icon
-  }
-
-  def getIcon: Drawable = mIcon
-
-  /** Make IconifiedText comparable by its name */
-  override def compareTo(other: Any): Int =
-    if (mText != null && other.isInstanceOf[IconifiedText])
-      mText compareTo other.asInstanceOf[IconifiedText].getText
-    else
-      throw new IllegalArgumentException()
-}
diff --git a/docs/android-examples/FileBrowser/src/org/anddev/android/filebrowser/iconifiedlist/IconifiedTextListAdapter.scala b/docs/android-examples/FileBrowser/src/org/anddev/android/filebrowser/iconifiedlist/IconifiedTextListAdapter.scala
deleted file mode 100644
index 1f81d53..0000000
--- a/docs/android-examples/FileBrowser/src/org/anddev/android/filebrowser/iconifiedlist/IconifiedTextListAdapter.scala
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * Copyright 2007 Steven Osborn
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.anddev.android.filebrowser.iconifiedlist
-
-import scala.collection.jcl.ArrayList
-
-import _root_.android.content.Context
-import _root_.android.widget.BaseAdapter
-import _root_.android.view.{View, ViewGroup}
-
-/**
- *  Based on Steven Osborn's tutorial on anddev.org
- *  (http://www.anddev.org/iconified_textlist_-_the_making_of-t97.html)
- */
-class IconifiedTextListAdapter(context: Context) extends BaseAdapter {
-
-  /** Remember our context so we can use it when constructing views. */
-  private var mContext: Context = context
-
-  private var mItems = new ArrayList[IconifiedText]()
-
-  def addItem(it: IconifiedText) { mItems add it }
-
-  def setListItems(lit: ArrayList[IconifiedText]) { mItems = lit }
-
-  /** @return The number of items in the */
-  def getCount: Int = mItems.size
-
-  def getItem(position: Int): AnyRef = mItems(position)
-
-  override def areAllItemsSelectable(): Boolean = false
-
-  override def isSelectable(position: Int): Boolean =
-    try {
-      mItems(position).isSelectable
-    } catch {
-      case aioobe: IndexOutOfBoundsException =>
-        super.isSelectable(position)
-    }
-
-  /** Use the array index as a unique id. */
-  def getItemId(position: Int): Long = position
-
-  /** @param convertView The old view to overwrite, if one is passed
-   * @returns a IconifiedTextView that holds wraps around an IconifiedText */
-  def getView(position: Int, convertView: View, parent: ViewGroup): View =
-    if (convertView == null) {
-      new IconifiedTextView(mContext, mItems(position))
-    } else { // Reuse/Overwrite the View passed
-             // We are assuming(!) that it is castable!
-      val btv = convertView.asInstanceOf[IconifiedTextView]
-      btv setText mItems(position).getText
-      btv setIcon mItems(position).getIcon
-      btv
-    }
-}
diff --git a/docs/android-examples/FileBrowser/src/org/anddev/android/filebrowser/iconifiedlist/IconifiedTextView.scala b/docs/android-examples/FileBrowser/src/org/anddev/android/filebrowser/iconifiedlist/IconifiedTextView.scala
deleted file mode 100644
index 8457d43..0000000
--- a/docs/android-examples/FileBrowser/src/org/anddev/android/filebrowser/iconifiedlist/IconifiedTextView.scala
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * Copyright 2007 Steven Osborn
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.anddev.android.filebrowser.iconifiedlist
-
-import _root_.android.content.Context
-import _root_.android.graphics.drawable.Drawable
-import _root_.android.view.ViewGroup.LayoutParams
-import _root_.android.widget.{ImageView, LinearLayout, TextView}
-
-/**
- *  Based on Steven Osborn's tutorial on anddev.org
- *  (http://www.anddev.org/iconified_textlist_-_the_making_of-t97.html)
- */
-class IconifiedTextView(context: Context, aIconifiedText: IconifiedText)
-extends LinearLayout(context) {
-
-  /* First Icon and the Text to the right (horizontal),
-   * not above and below (vertical) */
-  setOrientation(LinearLayout.HORIZONTAL)
-
-  private val mIcon = new ImageView(context)
-  mIcon setImageDrawable aIconifiedText.getIcon
-  // left, top, right, bottom
-  mIcon.setPadding(0, 2, 5, 0) // 5px to the right
-
-  /* At first, add the Icon to ourself
-   * (! we are extending LinearLayout) */
-  addView(mIcon, new LinearLayout.LayoutParams(
-                    LayoutParams.WRAP_CONTENT,
-                    LayoutParams.WRAP_CONTENT))
-          
-  private val mText = new TextView(context)
-  mText setText aIconifiedText.getText
-  /* Now the text (after the icon) */
-  addView(mText, new LinearLayout.LayoutParams(
-                    LayoutParams.WRAP_CONTENT,
-                    LayoutParams.WRAP_CONTENT))
-
-  def setText(words: String) {
-    mText setText words
-  }
-
-  def setIcon(bullet: Drawable) {
-    mIcon setImageDrawable bullet
-  }
-}
diff --git a/docs/android-examples/LunarLander/AndroidManifest.xml b/docs/android-examples/LunarLander/AndroidManifest.xml
deleted file mode 100644
index df91d90..0000000
--- a/docs/android-examples/LunarLander/AndroidManifest.xml
+++ /dev/null
@@ -1,11 +0,0 @@
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
-    package="com.google.android.lunarlander">
-    <application>
-        <activity class=".LunarLander" android:label="LunarLander">
-            <intent-filter>
-                <action android:value="android.intent.action.MAIN" />
-                <category android:value="android.intent.category.LAUNCHER" />
-            </intent-filter>
-        </activity>
-    </application>
-</manifest> 
diff --git a/docs/android-examples/LunarLander/build.xml b/docs/android-examples/LunarLander/build.xml
deleted file mode 100644
index be89540..0000000
--- a/docs/android-examples/LunarLander/build.xml
+++ /dev/null
@@ -1,222 +0,0 @@
-<?xml version="1.0" ?>
-<project name="LunarLander" default="package">
-    <property name="sdk-folder" value="/home/linuxsoft/apps/android-m3-rc37a" />
-    <property name="android-tools" value="/home/linuxsoft/apps/android-m3-rc37a/tools" />
-
-    <!-- The intermediates directory -->
-    <!-- Eclipse uses "bin" for its own output, so we do the same. -->
-    <property name="outdir" value="bin" />
-
-    <!-- No user servicable parts below. -->
-
-    <!-- Input directories -->
-    <property name="resource-dir" value="res" />
-    <property name="asset-dir" value="assets" />
-    <property name="srcdir" value="src" />
-
-    <!-- Output directories -->
-    <property name="outdir-classes" value="${outdir}/classes" />
-
-    <!-- Create R.java in the source directory -->
-    <property name="outdir-r" value="src" />
-
-    <!-- Intermediate files -->
-    <property name="dex-file" value="classes.dex" />
-    <property name="intermediate-dex" value="${outdir}/${dex-file}" />
-
-    <!-- The final package file to generate -->
-    <property name="out-package" value="${outdir}/${ant.project.name}.apk" />
-
-    <!-- Tools -->
-    <property name="aapt" value="${android-tools}/aapt" />
-    <property name="aidl" value="${android-tools}/aidl" />
-    <property name="dx" value="${android-tools}/dx" />
-    <property name="zip" value="zip" />
-    <property name="android-jar" value="${sdk-folder}/android.jar" />
-
-    <!-- Scala -->
-    <property environment="env"/>
-    <property name="scala.dir" value="${env.SCALA_HOME}"/>
-    <property name="scala-compiler.jar" value="${scala.dir}/lib/scala-compiler.jar"/>
-    <property name="scala-library.jar" value="${scala.dir}/lib/scala-library.jar"/>
-    <property name="scala-android.jar" value="${scala.dir}/lib/scala-android.jar"/>
-    <fail message="Missing library scala-android.jar (use sbaz to install it)">
-      <condition><not><available file="${scala-android.jar}"/></not></condition>
-    </fail>
-    <property name="scala-depend.jar" value="${android-tools}/lib/scala-depend.jar"/>
-    <path id="scala.path">
-        <pathelement path="${scala-library.jar}"/>
-        <pathelement path="${scala-compiler.jar}"/>
-    </path>
-    <path id="scalac.path">
-        <pathelement path="${android-jar}"/>
-        <pathelement path="${scala-library.jar}"/>
-    </path>
-    <taskdef
-        resource="scala/tools/ant/antlib.xml"
-        classpathref="scala.path"
-    />
-    <macrodef name="smartjar">
-        <attribute name="srcdir"/>
-        <attribute name="basedir"/>
-        <attribute name="classname"/>
-        <attribute name="destfile"/>
-        <sequential>
-          <depend
-            srcdir="@{srcdir}"
-            destdir="@{basedir}" closure="true"
-            cache="@{basedir}"
-            classpath="${android-jar}"
-          />
-          <java
-             classname="ch.epfl.lamp.util.depend" output="@{basedir}/classes.dep"
-             classpath="${scala-library.jar}${path.separator}${scala-depend.jar}">
-            <arg line="@{basedir}${file.separator}dependencies.txt"/>
-            <arg line="@{classname}"/>
-          </java>
-          <jar
-            destfile="@{destfile}"
-            basedir="@{basedir}"
-            includesfile="@{basedir}/classes.dep"
-           />
-        </sequential>
-    </macrodef>
-
-    <!-- Rules -->
-
-    <!-- Create the output directories if they don't exist yet. -->
-    <target name="dirs">
-        <mkdir dir="${outdir}" />
-        <mkdir dir="${outdir-classes}" />
-    </target>
-
-    <!-- Generate the R.java file for this project's resources. -->
-    <target name="resource-src" depends="dirs">
-        <echo>Generating R.java...</echo>
-        <exec executable="${aapt}" failonerror="true">
-            <arg value="compile" />
-            <arg value="-m" />
-            <arg value="-J" />
-            <arg value="${outdir-r}" />
-            <arg value="-M" />
-            <arg value="AndroidManifest.xml" />
-            <arg value="-S" />
-            <arg value="${resource-dir}" />
-            <arg value="-I" />
-            <arg value="${android-jar}" />
-        </exec>
-    </target>
-
-    <!-- Generate java classes from .aidl files. -->
-    <target name="aidl" depends="dirs">
-        <apply executable="${aidl}" failonerror="true">
-            <fileset dir="${srcdir}">
-                <include name="**/*.aidl"/>
-            </fileset>
-        </apply>
-    </target>
-
-    <!-- Compile this project's .java files into .class files. -->
-    <target name="compile" depends="dirs, resource-src, aidl">
-        <javac encoding="ascii" target="1.5" debug="true" extdirs=""
-                srcdir="."
-                destdir="${outdir-classes}"
-                bootclasspath="${android-jar}" />
-        <scalac encoding="ascii" target="jvm-1.5"
-            srcdir="${srcdir}"
-            destdir="${outdir-classes}"
-            bootclasspathref="scalac.path" />
-        <unjar src="${scala-android.jar}" dest="${outdir-classes}"/>
-        <smartjar
-          srcdir="${srcdir}"
-          basedir="${outdir-classes}"
-          classname="com.google.android.lunarlander.LunarLander"
-          destfile="${outdir}/${ant.project.name}.jar"
-        />
-        <delete includeemptydirs="true">
-          <fileset dir="${outdir-classes}" includes="**/*"/>
-        </delete>
-        <unjar src="${outdir}/${ant.project.name}.jar" dest="${outdir-classes}"/>
-    </target>
-
-    <!-- Convert this project's .class files into .dex files. -->
-    <target name="dex" depends="compile">
-        <exec executable="${dx}" failonerror="true">
-            <arg value="-JXmx384M" />
-            <arg value="--dex" />
-            <arg value="--output=${intermediate-dex}" />
-            <arg value="--locals=full" />
-            <arg value="--positions=lines" />
-            <arg path="${outdir-classes}" />
-        </exec>
-    </target>
-
-    <!-- Put the project's resources into the output package file. -->
-    <target name="package-res-and-assets">
-        <echo>Packaging resources and assets...</echo>
-        <exec executable="${aapt}" failonerror="true">
-            <arg value="package" />
-            <arg value="-f" />
-            <arg value="-c" />
-            <arg value="-M" />
-            <arg value="AndroidManifest.xml" />
-            <arg value="-S" />
-            <arg value="${resource-dir}" />
-            <arg value="-A" />
-            <arg value="${asset-dir}" />
-            <arg value="-I" />
-            <arg value="${android-jar}" />
-            <arg value="${out-package}" />
-        </exec>
-    </target>
-
-    <!-- Same as package-res-and-assets, but without "-A ${asset-dir}" -->
-    <target name="package-res-no-assets">
-        <echo>Packaging resources...</echo>
-        <exec executable="${aapt}" failonerror="true">
-            <arg value="package" />
-            <arg value="-f" />
-            <arg value="-c" />
-            <arg value="-M" />
-            <arg value="AndroidManifest.xml" />
-            <arg value="-S" />
-            <arg value="${resource-dir}" />
-            <!-- No assets directory -->
-            <arg value="-I" />
-            <arg value="${android-jar}" />
-            <arg value="${out-package}" />
-        </exec>
-    </target>
-
-    <!-- Invoke the proper target depending on whether or not
-         an assets directory is present. -->
-    <!-- TODO: find a nicer way to include the "-A ${asset-dir}" argument
-         only when the assets dir exists. -->
-    <target name="package-res">
-        <available file="${asset-dir}" type="dir"
-                property="res-target" value="and-assets" />
-        <property name="res-target" value="no-assets" />
-        <antcall target="package-res-${res-target}" />
-    </target>
-
-    <!-- Put the project's .class files into the output package file. -->
-    <target name="package-java" depends="compile, package-res">
-        <echo>Packaging java...</echo>
-        <jar destfile="${out-package}"
-                basedir="${outdir-classes}"
-                update="true" />
-    </target>
-
-    <!-- Put the project's .dex files into the output package file. -->
-    <target name="package-dex" depends="dex, package-res">
-        <echo>Packaging dex...</echo>
-        <exec executable="${zip}" failonerror="true">
-            <arg value="-qj" />
-            <arg value="${out-package}" />
-            <arg value="${intermediate-dex}" />
-        </exec>
-    </target>
-
-    <!-- Create the package file for this project from the sources. -->
-    <target name="package" depends="package-dex" />
-</project>
diff --git a/docs/android-examples/LunarLander/res/drawable-land/earthrise.png b/docs/android-examples/LunarLander/res/drawable-land/earthrise.png
deleted file mode 100644
index e2ecdc5..0000000
Binary files a/docs/android-examples/LunarLander/res/drawable-land/earthrise.png and /dev/null differ
diff --git a/docs/android-examples/LunarLander/res/drawable-port/earthrise.png b/docs/android-examples/LunarLander/res/drawable-port/earthrise.png
deleted file mode 100644
index a13836c..0000000
Binary files a/docs/android-examples/LunarLander/res/drawable-port/earthrise.png and /dev/null differ
diff --git a/docs/android-examples/LunarLander/res/drawable/app_lunar_lander.png b/docs/android-examples/LunarLander/res/drawable/app_lunar_lander.png
deleted file mode 100644
index 7557b8c..0000000
Binary files a/docs/android-examples/LunarLander/res/drawable/app_lunar_lander.png and /dev/null differ
diff --git a/docs/android-examples/LunarLander/res/drawable/lander_crashed.png b/docs/android-examples/LunarLander/res/drawable/lander_crashed.png
deleted file mode 100644
index a73c015..0000000
Binary files a/docs/android-examples/LunarLander/res/drawable/lander_crashed.png and /dev/null differ
diff --git a/docs/android-examples/LunarLander/res/drawable/lander_firing.png b/docs/android-examples/LunarLander/res/drawable/lander_firing.png
deleted file mode 100644
index 91378de..0000000
Binary files a/docs/android-examples/LunarLander/res/drawable/lander_firing.png and /dev/null differ
diff --git a/docs/android-examples/LunarLander/res/drawable/lander_plain.png b/docs/android-examples/LunarLander/res/drawable/lander_plain.png
deleted file mode 100644
index da448e4..0000000
Binary files a/docs/android-examples/LunarLander/res/drawable/lander_plain.png and /dev/null differ
diff --git a/docs/android-examples/LunarLander/res/layout/lunar_layout.xml b/docs/android-examples/LunarLander/res/layout/lunar_layout.xml
deleted file mode 100644
index 695001b..0000000
--- a/docs/android-examples/LunarLander/res/layout/lunar_layout.xml
+++ /dev/null
@@ -1,43 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- 
- * Copyright (C) 2007 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- -->
-
-<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
-    android:layout_width="fill_parent"
-    android:layout_height="fill_parent">
-    
-    <com.google.android.lunarlander.LunarView
-      id="@+id/lunar"
-      android:layout_width="fill_parent"
-      android:layout_height="fill_parent"
-      android:background="@drawable/earthrise" />
-    
-    <RelativeLayout
-        android:layout_width="fill_parent"
-        android:layout_height="fill_parent" >
-        <TextView
-          id="@+id/text"
-		  android:text="@string/lunar_layout_text_text"
-		  android:visibility="visible"
-          android:layout_width="wrap_content"
-          android:layout_height="wrap_content"
-          android:layout_centerInParent="true"
-          android:textAlign="center"
-          android:textColor="#88ffffff"
-          android:textSize="24sp"/>
-     </RelativeLayout>
-         
-</FrameLayout>
diff --git a/docs/android-examples/LunarLander/res/layout/main.xml b/docs/android-examples/LunarLander/res/layout/main.xml
deleted file mode 100644
index b14f1bb..0000000
--- a/docs/android-examples/LunarLander/res/layout/main.xml
+++ /dev/null
@@ -1,13 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
-    android:orientation="vertical"
-    android:layout_width="fill_parent"
-    android:layout_height="fill_parent"
-    >
-<TextView  
-    android:layout_width="fill_parent" 
-    android:layout_height="wrap_content" 
-    android:text="Hello World, LunarLander"
-    />
-</LinearLayout>
-
diff --git a/docs/android-examples/LunarLander/res/values/strings.xml b/docs/android-examples/LunarLander/res/values/strings.xml
deleted file mode 100644
index 64e5a0a..0000000
--- a/docs/android-examples/LunarLander/res/values/strings.xml
+++ /dev/null
@@ -1,41 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- 
- * Copyright (C) 2007 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- -->
-
-<resources>
-	<string name="app_name">Lunar Lander</string>
-	
-    <string name="menu_start">Start</string>
-    <string name="menu_stop">Stop</string>
-    <string name="menu_pause">Pause</string>
-    <string name="menu_resume">Resume</string>
-    <string name="menu_easy">Easy</string>
-    <string name="menu_medium">Medium</string>
-    <string name="menu_hard">Hard</string>
-    
-    <string name="mode_ready">Lunar Lander\nPress Up To Play</string>
-	<string name="mode_pause">Paused\nPress Up To Resume</string>
-	<string name="mode_lose">Game Over\nPress Up To Play</string>
-	<string name="mode_win_prefix">Success!\n</string> 
-	<string name="mode_win_suffix">in a row\nPress Up to Play</string> 
-	
-	<string name="message_stopped">Stopped</string>
-	<string name="message_off_pad">Off Landing Pad</string> 
-	<string name="message_too_fast">Too Fast</string> 
-	<string name="message_bad_angle">Bad Angle</string> 
-
-    <string name="lunar_layout_text_text"></string>
-</resources>
diff --git a/docs/android-examples/LunarLander/src/com/google/android/lunarlander/LunarLander.scala b/docs/android-examples/LunarLander/src/com/google/android/lunarlander/LunarLander.scala
deleted file mode 100644
index 2dadad3..0000000
--- a/docs/android-examples/LunarLander/src/com/google/android/lunarlander/LunarLander.scala
+++ /dev/null
@@ -1,88 +0,0 @@
-/* 
- * Copyright (C) 2007 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- 
-package com.google.android.lunarlander
-
-import _root_.android.app.Activity
-import _root_.android.os.Bundle
-import _root_.android.view.{Menu, Window}
-import _root_.android.widget.TextView
-
-/**
- * This is a simple LunarLander activity
- * that houses a single LunarView. It demonstrates...
- * <ul>
- * <li>animating by calling invalidate() from draw()
- * <li>loading and drawing resources
- * <li>handling onPause() in an animation
- * </ul>
- */
-class LunarLander extends Activity {
-  private var mLunarView: LunarView = _
-
-  override def onCreate(icicle: Bundle) {
-    super.onCreate(icicle)
-
-    // Turn off the title bar
-    requestWindowFeature(Window.FEATURE_NO_TITLE)
-
-    // Make our view
-    setContentView(R.layout.lunar_layout)
-    mLunarView = findViewById(R.id.lunar).asInstanceOf[LunarView]
-        
-    // Tell the view about the text view
-    mLunarView setTextView findViewById(R.id.text).asInstanceOf[TextView]
-
-    if (icicle == null) {
-      // We were just launched -- set up a new game
-      mLunarView.mode = LunarView.READY 
-    } else {
-      // We are being restored
-      val map = icicle getBundle "lunar-view"
-      if (map != null) mLunarView restoreState map
-      else mLunarView.mode = LunarView.READY
-    }
-  }
-
-  override def onPause() {
-    super.onPause()
-    // Pause the came when our activity pauses
-    mLunarView.doPause()
-  }
-
-  override def onFreeze(outState: Bundle) {
-   // Remember game state
-   outState.putBundle("lunar-view", mLunarView.saveState())
-  }
-
-  override def onCreateOptionsMenu(menu: Menu): Boolean = {
-    super.onCreateOptionsMenu(menu)
-
-    def run(b: => Unit) = new Runnable { def run() { mLunarView.doStart() } }
-        
-    menu.add(0, 0, R.string.menu_start, run { mLunarView.doStart() })
-    menu.add(0, 0, R.string.menu_stop, run {
-      mLunarView.setMode(LunarView.LOSE, LunarLander.this.getText(R.string.message_stopped))
-    })
-    menu.add(0, 0, R.string.menu_pause, run { mLunarView.doPause() })
-    menu.add(0, 0, R.string.menu_resume, run { mLunarView.doResume() })
-    menu.addSeparator(0, 0)
-    menu.add(0, 0, R.string.menu_easy, run { mLunarView.difficulty = LunarView.EASY })
-    menu.add(0, 0, R.string.menu_medium, run { mLunarView.difficulty = LunarView.MEDIUM })
-    menu.add(0, 0, R.string.menu_hard, run { mLunarView.difficulty = LunarView.HARD })
-    true
-  }
-}
diff --git a/docs/android-examples/LunarLander/src/com/google/android/lunarlander/LunarView.scala b/docs/android-examples/LunarLander/src/com/google/android/lunarlander/LunarView.scala
deleted file mode 100644
index 7521173..0000000
--- a/docs/android-examples/LunarLander/src/com/google/android/lunarlander/LunarView.scala
+++ /dev/null
@@ -1,647 +0,0 @@
-/* 
- * Copyright (C) 2007 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.google.android.lunarlander
-
-import _root_.android.content.{Context, Resources}
-import _root_.android.graphics.{Canvas, Paint, RectF}
-import _root_.android.graphics.drawable.Drawable
-import _root_.android.os.Bundle
-import _root_.android.util.AttributeSet
-import _root_.android.view.{KeyEvent, View}
-import _root_.android.widget.TextView
-
-import java.util.Map
-
-object LunarView {
-  final val READY = 0
-  final val RUNNING = 1
-  final val PAUSE = 2
-  final val LOSE = 3
-  final val WIN = 4
-   
-  final val EASY = 0
-  final val MEDIUM = 1
-  final val HARD = 2
-   
-  // Parameters for how the physics works.
-  final val FIRE_ACCEL_SEC = 80
-  final val DOWN_ACCEL_SEC = 35
-  final val FUEL_SEC = 10
-
-  final val SLEW_SEC = 120 // degrees/second rotate
-   
-  final val FUEL_INIT = 60d
-  final val FUEL_MAX = 100
-   
-  final val SPEED_INIT = 30
-  final val SPEED_MAX = 120
-  final val SPEED_HYPERSPACE = 180
-   
-  // Parameters for landing successfully (MEDIUM difficulty).
-  final val TARGET_SPEED = 28
-  final val TARGET_WIDTH = 1.6 // how much wider than lander
-  final val TARGET_ANGLE = 18
-   
-  /**
-   * Pixel height of the fuel/speed bar.
-   */
-  final val BAR_HEIGHT = 10
-   
-  /**
-   * Pixel width of the fuel/speed bar.
-   */
-  final val BAR = 100
-   
-  /**
-   * Height of the landing pad off the bottom.
-   */
-  final val PAD_HEIGHT = 8
-   
-  /**
-   * Extra pixels below the landing gear in the images
-   */
-  final val BOTTOM_PADDING = 17
-}
-
-/**
- * View that draws, takes keystrokes, etc. for a simple LunarLander game.
- * 
- * Has a mode which RUNNING, PAUSED, etc. Has a x, y, dx, dy, ... capturing the
- * current ship physics. All x/y etc. are measured with (0,0) at the lower left.
- * updatePhysics() advances the physics based on realtime. draw() renders the
- * ship, and does an invalidate() to prompt another draw() as soon as possible
- * by the system.
- */
-class LunarView(context: Context, attrs: AttributeSet, inflateParams: Map) 
-      extends View(context, attrs, inflateParams) {
-  import LunarView._  // companion object
-   
-  /**
-   * The state of the game. One of READY, RUNNING, PAUSE, LOSE, or WIN
-   */
-  private var mMode = READY
-
-  /**
-   * Current difficulty -- amount of fuel, allowed angle, etc.
-   * Default is MEDIUM.
-   */
-  private var mDifficulty = MEDIUM
-
-  /**
-   * Velocity dx.
-   */
-  private var mDX = 0.0
-    
-  /**
-   * Velocity dy.
-   */
-  private var mDY = 0.0
-
-  /**
-   * Lander heading in degrees, with 0 up, 90 right.
-   * Kept in the range 0..360.
-   */
-  private var mHeading = 0.0
-   
-  /**
-   * Currently rotating, -1 left, 0 none, 1 right.
-   */
-  private var mRotating = 0
-
-  /**
-   * X of the landing pad.
-   */
-  private var mGoalX = 0
-    
-  /**
-   * Allowed speed.
-   */
-  private var mGoalSpeed = 0
-    
-  /**
-   * Allowed angle.
-   */
-  private var mGoalAngle = 0
-    
-  /**
-   * Width of the landing pad.
-   */
-  private var mGoalWidth = 0
-    
-  /**
-   * Number of wins in a row.
-   */
-  private var mWinsInARow = 0
- 
-  /**
-   * Fuel remaining
-   */
-  private var mFuel = FUEL_INIT
-
-  /**
-   * Is the engine burning?
-   */
-  private var mEngineFiring = true
-    
-    
-  /**
-   * Used to figure out elapsed time between frames
-   */
-  private var mLastTime: Long = _
-
-  /**
-   * Paint to draw the lines on screen.
-   */
-  private val mLinePaint = new Paint
-  mLinePaint setAntiAlias true
-  mLinePaint.setARGB(255, 0, 255, 0)
-    
-  /**
-   * "Bad" speed-too-high variant of the line color.
-   */
-  private val mLinePaintBad = new Paint
-  mLinePaintBad setAntiAlias true
-  mLinePaintBad.setARGB(255, 120, 180, 0)
-
-  /**
-   * What to draw for the Lander in its normal state
-   */
-  private val mLanderImage =
-    context.getResources getDrawable R.drawable.lander_plain
-
-  /**
-   * What to draw for the Lander when the engine is firing
-   */
-  private val mFiringImage =
-    context.getResources getDrawable R.drawable.lander_firing
-
-  /**
-   * What to draw for the Lander when it has crashed
-   */
-  private val mCrashedImage =
-    context.getResources getDrawable R.drawable.lander_crashed
-
-  /**
-   * Pixel width of lander image.
-   */
-  var mLanderWidth = mLanderImage.getIntrinsicWidth
-      
-  /**
-   * Pixel height of lander image.
-   */
-  var mLanderHeight = mLanderImage.getIntrinsicHeight
-      
-  /**
-   * X of lander center.
-   */
-  private var mX: Double = mLanderWidth
-
-  /**
-   * Y of lander center.
-   */
-  private var mY: Double = mLanderHeight * 2
-
-  /**
-   * Pointer to the text view to display "Paused.." etc.
-   */
-  private var mStatusText: TextView = _
-    
-  /**
-   * Scratch rect object.
-   */
-  private val mScratchRect= new RectF(0, 0, 0, 0)
-
-
-  setBackground(R.drawable.earthrise)
-  // Make sure we get keys
-  setFocusable(true)
-
-  /**
-   * Save game state so that the user does not lose anything
-   * if the game process is killed while we are in the 
-   * background.
-   * 
-   * @return Map with this view's state
-   */
-  def saveState(): Bundle = {
-    val map = new Bundle
-
-    map.putInteger("mDifficulty", mDifficulty)
-    map.putDouble("mX", mX)
-    map.putDouble("mY", mY)
-    map.putDouble("mDX", mDX)
-    map.putDouble("mDY", mDY)
-    map.putDouble("mHeading", mHeading)
-    map.putInteger("mLanderWidth", mLanderWidth)
-    map.putInteger("mLanderHeight", mLanderHeight)
-    map.putInteger("mGoalX", mGoalX)
-    map.putInteger("mGoalSpeed", mGoalSpeed)
-    map.putInteger("mGoalAngle", mGoalAngle)
-    map.putInteger("mGoalWidth", mGoalWidth)
-    map.putInteger("mWinsInARow", mWinsInARow)
-    map.putDouble("mFuel", mFuel)
-
-    map
-  }
-
-  /**
-   * Restore game state if our process is being relaunched
-   * 
-   * @param icicle Map containing the game state
-   */
-  def restoreState(icicle: Bundle) {
-    mode = PAUSE
-    mRotating = 0
-    mEngineFiring = false
-        
-    mDifficulty = icicle.getInteger("mDifficulty").intValue
-    mX = icicle.getDouble("mX").doubleValue
-    mY = icicle.getDouble("mY").doubleValue
-    mDX = icicle.getDouble("mDX").doubleValue
-    mDY = icicle.getDouble("mDY").doubleValue
-    mHeading = icicle.getDouble("mHeading").doubleValue
- 
-    mLanderWidth = icicle.getInteger("mLanderWidth").intValue
-    mLanderHeight = icicle.getInteger("mLanderHeight").intValue
-    mGoalX = icicle.getInteger("mGoalX").intValue
-    mGoalSpeed = icicle.getInteger("mGoalSpeed").intValue
-    mGoalAngle = icicle.getInteger("mGoalAngle").intValue
-    mGoalWidth = icicle.getInteger("mGoalWidth").intValue
-    mWinsInARow = icicle.getInteger("mWinsInARow").intValue
-    mFuel = icicle.getDouble("mFuel").doubleValue
-  }
-
-  /**
-   * Installs a pointer to the text view used
-   * for messages.
-   */
-  def setTextView(textView: TextView) { mStatusText = textView }
-
-  /**
-   * Standard window-focus override.
-   * Notice focus lost so we can pause on focus lost.
-   * e.g. user switches to take a call.
-   */
-  override def windowFocusChanged(hasWindowFocus: Boolean) {
-    if (!hasWindowFocus) doPause()
-  }
-
-  /**
-   * Standard override of View.draw.
-   * Draws the ship and fuel/speed bars.
-   */
-  override def onDraw(canvas: Canvas) {
-    super.onDraw(canvas)
-
-    if (mMode == RUNNING) updatePhysics()
-
-    val screenWidth = getWidth
-    val screenHeight = getHeight
-
-    val yTop = screenHeight - (mY.toInt + mLanderHeight/2)
-    val xLeft = mX.toInt - mLanderWidth/2
-
-    // Draw fuel rect
-    val fuelWidth = (BAR * mFuel / FUEL_MAX).toInt
-    mScratchRect.set(4, 4, 4 + fuelWidth, 4 + BAR_HEIGHT)
-    canvas.drawRect(mScratchRect, mLinePaint)
-        
-    val speed = Math.sqrt(mDX*mDX + mDY*mDY)
-    val speedWidth = (BAR * speed / SPEED_MAX).toInt
-        
-    if (speed <= mGoalSpeed) {
-      mScratchRect.set(4 + BAR + 4, 4, 4 + BAR + 4 + speedWidth, 4 + BAR_HEIGHT)
-      canvas.drawRect(mScratchRect, mLinePaint)
-    } else {
-      // Draw the bad color in back, with the good color in front of it
-      mScratchRect.set(4 + BAR + 4, 4, 4 + BAR + 4 + speedWidth, 4 + BAR_HEIGHT)
-      canvas.drawRect(mScratchRect, mLinePaintBad)
-      val goalWidth = (BAR * mGoalSpeed / SPEED_MAX)
-      mScratchRect.set(4 + BAR + 4, 4, 4 + BAR + 4 + goalWidth, 4 + BAR_HEIGHT)
-      canvas.drawRect(mScratchRect, mLinePaint)
-    }
-
-    // Draw the landing pad
-    canvas.drawLine(mGoalX, 1 + screenHeight - PAD_HEIGHT,
-                    mGoalX + mGoalWidth, 1 + screenHeight - PAD_HEIGHT,  mLinePaint)
-
-
-    // Draw the ship with its current rotation
-    canvas.save()
-    canvas.rotate(mHeading.toFloat, mX.toFloat, screenHeight - mY.toFloat)
-
-    if (mMode == LOSE) {
-      mCrashedImage.setBounds(xLeft, yTop, xLeft+mLanderWidth, yTop+mLanderHeight)
-      mCrashedImage.draw(canvas)
-    } else if (mEngineFiring) {
-      mFiringImage.setBounds(xLeft, yTop, xLeft+mLanderWidth, yTop+mLanderHeight)
-      mFiringImage.draw(canvas)
-    } else {
-      mLanderImage.setBounds(xLeft, yTop, xLeft+mLanderWidth, yTop+mLanderHeight)          
-      mLanderImage.draw(canvas)
-    }
-
-    /*
-     * Our animation strategy is that each draw() does an invalidate(),
-     * so we get a series of draws. This is a known animation strategy
-     * within Android, and the system throttles the draws down to match
-     * the refresh rate.
-     */
-
-    if (mMode == RUNNING) {
-      // Invalidate a space around the current lander + the bars at the top.
-      // Note: invalidating a relatively small part of the screen to draw
-      // is a good optimization. In this case, the bars and the ship
-      // may be far apart, limiting the value of the optimization.
-      invalidate(xLeft-20, yTop-20, xLeft+mLanderWidth+20, yTop+mLanderHeight+20)
-      invalidate(0, 0, screenWidth, 4 + BAR_HEIGHT)
-    }
-        
-    canvas.restore()
-  }
-
-  /**
-   * Figures the lander state (x, y, fuel, ...) based on the passage of
-   * realtime. Does not invalidate(). Called at the start
-   * of draw(). Detects the end-of-game and sets the UI to the next state.
-   */
-  def updatePhysics() {
-    val now = System.currentTimeMillis
-
-    // Do nothing if mLastTime is in the future.
-    // This allows the game-start to delay the start of the physics
-    // by 100ms or whatever.
-    if (mLastTime > now) return
-        
-    val elapsed = (now - mLastTime) / 1000.0
-        
-    // mRotating -- update heading
-    if (mRotating != 0) {
-      mHeading += mRotating * (SLEW_SEC * elapsed)
-          
-      // Bring things back into the range 0..360
-      if (mHeading < 0) mHeading += 360
-      else if (mHeading >= 360) mHeading -= 360
-    }
-        
-    // Base accelerations -- 0 for x, gravity for y
-    var ddx = 0.0
-    var ddy = -DOWN_ACCEL_SEC * elapsed
-
-    if (mEngineFiring) {
-      // taking 0 as up, 90 as to the right
-      // cos(deg) is ddy component, sin(deg) is ddx component
-      var elapsedFiring = elapsed
-      var fuelUsed = elapsedFiring * FUEL_SEC
-
-      // tricky case where we run out of fuel partway through the elapsed
-      if (fuelUsed > mFuel) {
-        elapsedFiring = mFuel / fuelUsed * elapsed
-        fuelUsed = mFuel
-
-        // Oddball case where we adjust the "control" from here
-        mEngineFiring = false
-      }
-
-      mFuel -= fuelUsed
-            
-      // have this much acceleration from the engine
-      val accel = FIRE_ACCEL_SEC * elapsedFiring
-            
-      val radians = 2 * Math.Pi * mHeading / 360
-      ddx = Math.sin(radians) * accel
-      ddy += Math.cos(radians) * accel
-    }
-
-    val dxOld = mDX
-    val dyOld = mDY
-        
-    // figure speeds for the end of the period
-    mDX += ddx
-    mDY += ddy
-
-    // figure position based on average speed during the period
-    mX += elapsed * (mDX + dxOld)/2
-    mY += elapsed * (mDY + dyOld)/2
-
-    mLastTime = now
-
-    checkLanding()
-  }
-
-  def checkLanding() {
-    val yLowerBound = PAD_HEIGHT + mLanderHeight/2 - BOTTOM_PADDING
-    if (mY <= yLowerBound) {
-      mY = yLowerBound
-
-      val res = getContext.getResources
-      val speed = Math.sqrt(mDX*mDX + mDY*mDY)
-      val onGoal = (mGoalX <= mX - mLanderWidth/2  &&
-                    mX + mLanderWidth/2 <= mGoalX + mGoalWidth)
-        
-      // "Hyperspace" win -- upside down, going fast,
-      // puts you back at the top.
-      if (onGoal && Math.abs(mHeading - 180) < mGoalAngle &&
-        speed > SPEED_HYPERSPACE) {
-        mWinsInARow += 1
-        doStart()
-      } else {
-        val (result, message) = 
-          if (!onGoal) 
-            (LOSE, res.getText(R.string.message_off_pad))
-          else if (!(mHeading <= mGoalAngle || mHeading >= 360 - mGoalAngle))
-            (LOSE, res.getText(R.string.message_bad_angle))
-          else if (speed  > mGoalSpeed) 
-            (LOSE, res.getText(R.string.message_too_fast))
-          else {
-            mWinsInARow += 1
-            (WIN, "")
-          }
-        setMode(result, message)
-      }
-    }
-  }
-
-  /**
-   * Sets if the engine is currently firing.
-   */
-  def isFiring_=(firing: Boolean) { mEngineFiring = firing }
-  def isFiring = mEngineFiring
-
-  /**
-   * Sets the game mode, RUNNING, PAUSED, etc.
-   * @param mode RUNNING, PAUSED, ...
-   */
-  def mode_=(mode: Int) { setMode(mode, null) }
-  def mode = mMode
-  
-  /**
-   * Sets the game mode, RUNNING, PAUSED, etc.
-   * @param mode RUNNING, PAUSED, ...
-   * @param message string to add to screen or null
-   */
-  def setMode(mode: Int, message: CharSequence) {
-    mMode = mode
-    invalidate()
-	
-    if (mMode == RUNNING) {
-      mStatusText.setVisibility(View.INVISIBLE)
-    } else {
-      mRotating = 0
-      mEngineFiring = false
-      val res = getContext.getResources
-      var str = mMode match {
-        case READY => res.getText(R.string.mode_ready)
-        case PAUSE => res.getText(R.string.mode_pause)
-        case LOSE => mWinsInARow = 0; res.getText(R.string.mode_lose)
-        case WIN => res.getString(R.string.mode_win_prefix)
-          + mWinsInARow + " " + res.getString(R.string.mode_win_suffix)
-        case _ => ""
-      }
-      mStatusText setText (if (message != null) message + "\n" + str else str)
-      mStatusText setVisibility View.VISIBLE
-    }
-  }
-
-  /**
-   * Starts the game, setter parameters for the current
-   * difficulty.
-   */
-  def doStart() {
-    // First set the game for Medium difficulty
-    mFuel = FUEL_INIT
-    mEngineFiring = false
-    mGoalWidth = (mLanderWidth * TARGET_WIDTH).toInt
-    mGoalSpeed = TARGET_SPEED
-    mGoalAngle = TARGET_ANGLE
-    var speedInit = SPEED_INIT
-        
-    // Adjust difficulty params for EASY/HARD
-    if (mDifficulty == EASY) {
-      mFuel = mFuel * 3 / 2
-      mGoalWidth = mGoalWidth * 4 / 3
-      mGoalSpeed = mGoalSpeed * 3 / 2
-      mGoalAngle = mGoalAngle * 4 / 3
-      speedInit = speedInit * 3 / 4
-    } else if (mDifficulty == HARD) {
-      mFuel = mFuel * 7 / 8
-      mGoalWidth = mGoalWidth * 3 / 4
-      mGoalSpeed = mGoalSpeed * 7 / 8
-      speedInit = speedInit * 4 / 3
-    }
-        
-    mX = getWidth/2
-    mY = getHeight - mLanderHeight/2
-        
-    // start with a little random motion
-    mDY = Math.random * -speedInit
-    mDX = Math.random * 2*speedInit - speedInit
-        
-    mHeading = 0
-        
-    // Figure initial spot for landing, not too near center
-    do {
-      mGoalX = (Math.random * (getWidth - mGoalWidth)).toInt
-    } while (Math.abs(mGoalX - (mX - mLanderWidth/2)) <= getWidth/6)
-        
-    mLastTime = System.currentTimeMillis + 100
-    mode = RUNNING
-  }
-
-  /**
-   * Resumes from a pause.
-   */
-  def doResume() {
-    // Move the real time clock up to now
-    mLastTime = System.currentTimeMillis + 100
-    mode = RUNNING
-  }
-
-  /**
-   * Pauses from the running state.
-   */
-  def doPause() { if (mMode == RUNNING) mode = PAUSE }
-
-    
-  /**
-   * Standard override to get key events.
-   */
-  override def onKeyDown(keyCode: Int, msg: KeyEvent): Boolean = {
-    var handled = false
-
-    val okStart = keyCode == KeyEvent.KEYCODE_DPAD_UP ||
-                  keyCode == KeyEvent.KEYCODE_DPAD_DOWN ||
-                  keyCode == KeyEvent.KEYCODE_S
-
-    val center = keyCode == KeyEvent.KEYCODE_DPAD_UP
-
-    // ready-to-start -> start
-    if (okStart && (mMode == READY || mMode == LOSE || mMode == WIN)) {
-      doStart()
-      handled = true
-    }
-    // paused -> running
-    else if (mMode == PAUSE && okStart) {
-      doResume()
-      handled = true
-    } else if (mMode == RUNNING) {
-      // center/space -> fire
-      if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER  ||
-          keyCode == KeyEvent.KEYCODE_SPACE) {
-        isFiring = true
-        handled = true
-        // left/q -> left
-      } else if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT ||
-                 keyCode == KeyEvent.KEYCODE_Q) {
-        mRotating = -1
-        handled = true
-        // right/w -> right
-      } else if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT ||
-                 keyCode == KeyEvent.KEYCODE_W) {
-        mRotating = 1
-        handled = true
-        // up -> pause
-      } else if (keyCode == KeyEvent.KEYCODE_DPAD_UP) {
-        doPause()
-        handled = true
-      }
-    }
-    handled
-  }
-
-  /**
-   * Standard override for key-up. We actually care about these,
-   * so we can turn off the engine or stop rotating.
-   */
-  override def onKeyUp(keyCode: Int, msg: KeyEvent): Boolean = 
-    if (mMode == RUNNING) {
-      if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER ||
-          keyCode == KeyEvent.KEYCODE_SPACE) {
-        isFiring = false
-        true
-      } else if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT ||
-                 keyCode == KeyEvent.KEYCODE_Q || 
-                 keyCode == KeyEvent.KEYCODE_DPAD_RIGHT ||
-                 keyCode == KeyEvent.KEYCODE_W) {
-        mRotating = 0
-        true
-      } else false
-    } else false
-
-  def difficulty_=(d: Int) { mDifficulty = d }
-  def difficulty = mDifficulty
-}
diff --git a/docs/android-examples/NotePad/AndroidManifest.xml b/docs/android-examples/NotePad/AndroidManifest.xml
deleted file mode 100644
index 1b79871..0000000
--- a/docs/android-examples/NotePad/AndroidManifest.xml
+++ /dev/null
@@ -1,91 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- 
- * Copyright (C) 2007 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- -->
-
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
-    package="com.google.android.notepad">
-    <application android:icon="@drawable/app_notes"
-            android:label="@string/app_name">
-        <provider class="NotePadProvider"
-                android:authorities="com.google.provider.NotePad" />
-
-        <activity class="NotesList" android:label="@string/title_notes_list">
-            <intent-filter>
-                <action android:value="android.intent.action.MAIN" />
-                <category android:value="android.intent.category.LAUNCHER" />
-            </intent-filter>
-            <intent-filter>
-                <action android:value="android.intent.action.VIEW" />
-                <action android:value="android.intent.action.EDIT" />
-                <action android:value="android.intent.action.PICK" />
-                <category android:value="android.intent.category.DEFAULT" />
-                <type android:value="vnd.android.cursor.dir/vnd.google.note" />
-            </intent-filter>
-            <intent-filter>
-                <action android:value="android.intent.action.GET_CONTENT" />
-                <category android:value="android.intent.category.DEFAULT" />
-                <type android:value="vnd.android.cursor.item/vnd.google.note" />
-            </intent-filter>
-        </activity>
-        
-        <activity class="NoteEditor" android:label="@string/title_note">
-            <!-- This filter says that we can view or edit the data of
-                 a single note -->
-            <intent-filter android:label="@string/resolve_edit">
-                <action android:value="android.intent.action.VIEW" />
-                <action android:value="android.intent.action.EDIT" />
-                <action android:value="com.google.android.notepad.action.EDIT_NOTE" />
-                <category android:value="android.intent.category.DEFAULT" />
-                <type android:value="vnd.android.cursor.item/vnd.google.note" />
-            </intent-filter>
-
-            <!-- This filter says that we can create a new note inside
-                 of a directory of notes. -->
-            <intent-filter>
-                <action android:value="android.intent.action.INSERT" />
-                <category android:value="android.intent.category.DEFAULT" />
-                <type android:value="vnd.android.cursor.dir/vnd.google.note" />
-            </intent-filter>
-
-        </activity>
-        
-		<activity class="TitleEditor" android:label="@string/title_edit_title"
-				android:theme="@android:style/Theme.Dialog">
-            <!-- This activity implements an alternative action that can be
-                 performed on notes: editing their title.  It can be used as
-                 a default operation if the user invokes this action, and is
-                 available as an alternative action for any note data. -->
-            <intent-filter android:label="@string/resolve_title">
-                <!-- This is the action we perform.  It is a custom action we
-                     define for our application, not a generic VIEW or EDIT
-                     action since we are not a general note viewer/editor. -->
-                <action android:value="com.google.android.notepad.action.EDIT_TITLE" />
-                <!-- DEFAULT: execute if being directly invoked. -->
-                <category android:value="android.intent.category.DEFAULT" />
-                <!-- ALTERNATIVE: show as an alternative action when the user is
-                     working with this type of data. -->
-                <category android:value="android.intent.category.ALTERNATIVE" />
-                <!-- SELECTED_ALTERNATIVE: show as an alternative action the user
-                     can perform when selecting this type of data. -->
-                <category android:value="android.intent.category.SELECTED_ALTERNATIVE" />
-                <!-- This is the data type we operate on. -->
-                <type android:value="vnd.android.cursor.item/vnd.google.note" />
-            </intent-filter>
-        </activity>
-        
-    </application>
-</manifest>
-
diff --git a/docs/android-examples/NotePad/build.xml b/docs/android-examples/NotePad/build.xml
deleted file mode 100644
index 0c72dfa..0000000
--- a/docs/android-examples/NotePad/build.xml
+++ /dev/null
@@ -1,222 +0,0 @@
-<?xml version="1.0" ?>
-<project name="NotePad" default="package">
-    <property name="sdk-folder" value="/home/linuxsoft/apps/android-m3-rc22a" />
-    <property name="android-tools" value="/home/linuxsoft/apps/android-m3-rc22a/tools" />
-
-    <!-- The intermediates directory -->
-    <!-- Eclipse uses "bin" for its own output, so we do the same. -->
-    <property name="outdir" value="bin" />
-
-    <!-- No user servicable parts below. -->
-
-    <!-- Input directories -->
-    <property name="resource-dir" value="res" />
-    <property name="asset-dir" value="assets" />
-    <property name="srcdir" value="src" />
-
-    <!-- Output directories -->
-    <property name="outdir-classes" value="${outdir}/classes" />
-
-    <!-- Create R.java in the source directory -->
-    <property name="outdir-r" value="src" />
-
-    <!-- Intermediate files -->
-    <property name="dex-file" value="classes.dex" />
-    <property name="intermediate-dex" value="${outdir}/${dex-file}" />
-
-    <!-- The final package file to generate -->
-    <property name="out-package" value="${outdir}/${ant.project.name}.apk" />
-
-    <!-- Tools -->
-    <property name="aapt" value="${android-tools}/aapt" />
-    <property name="aidl" value="${android-tools}/aidl" />
-    <property name="dx" value="${android-tools}/dx" />
-    <property name="zip" value="zip" />
-    <property name="android-jar" value="${sdk-folder}/android.jar" />
-
-    <!-- Scala -->
-    <property environment="env"/>
-    <property name="scala.dir" value="${env.SCALA_HOME}"/>
-    <property name="scala-compiler.jar" value="${scala.dir}/lib/scala-compiler.jar"/>
-    <property name="scala-library.jar" value="${scala.dir}/lib/scala-library.jar"/>
-    <property name="scala-android.jar" value="${scala.dir}/lib/scala-android.jar"/>
-    <fail message="Missing library scala-android.jar (use sbaz to install it)">
-      <condition><not><available file="${scala-android.jar}"/></not></condition>
-    </fail>
-    <property name="scala-depend.jar" value="${android-tools}/lib/scala-depend.jar"/>
-    <path id="scala.path">
-        <pathelement path="${scala-library.jar}"/>
-        <pathelement path="${scala-compiler.jar}"/>
-    </path>
-    <path id="scalac.path">
-        <pathelement path="${android-jar}"/>
-        <pathelement path="${scala-library.jar}"/>
-    </path>
-    <taskdef
-        resource="scala/tools/ant/antlib.xml"
-        classpathref="scala.path"
-    />
-    <macrodef name="smartjar">
-        <attribute name="srcdir"/>
-        <attribute name="basedir"/>
-        <attribute name="classname"/>
-        <attribute name="destfile"/>
-        <sequential>
-          <depend
-            srcdir="@{srcdir}"
-            destdir="@{basedir}" closure="true"
-            cache="@{basedir}"
-            classpath="${android-jar}"
-          />
-          <java
-             classname="ch.epfl.lamp.util.depend" output="@{basedir}/classes.dep"
-             classpath="${scala-library.jar}${path.separator}${scala-depend.jar}">
-            <arg line="@{basedir}${file.separator}dependencies.txt"/>
-            <arg line="@{classname}"/>
-          </java>
-          <jar
-            destfile="@{destfile}"
-            basedir="@{basedir}"
-            includesfile="@{basedir}/classes.dep"
-           />
-        </sequential>
-    </macrodef>
-
-    <!-- Rules -->
-
-    <!-- Create the output directories if they don't exist yet. -->
-    <target name="dirs">
-        <mkdir dir="${outdir}" />
-        <mkdir dir="${outdir-classes}" />
-    </target>
-
-    <!-- Generate the R.java file for this project's resources. -->
-    <target name="resource-src" depends="dirs">
-        <echo>Generating R.java...</echo>
-        <exec executable="${aapt}" failonerror="true">
-            <arg value="compile" />
-            <arg value="-m" />
-            <arg value="-J" />
-            <arg value="${outdir-r}" />
-            <arg value="-M" />
-            <arg value="AndroidManifest.xml" />
-            <arg value="-S" />
-            <arg value="${resource-dir}" />
-            <arg value="-I" />
-            <arg value="${android-jar}" />
-        </exec>
-    </target>
-
-    <!-- Generate java classes from .aidl files. -->
-    <target name="aidl" depends="dirs">
-        <apply executable="${aidl}" failonerror="true">
-            <fileset dir="${srcdir}">
-                <include name="**/*.aidl"/>
-            </fileset>
-        </apply>
-    </target>
-
-    <!-- Compile this project's .java files into .class files. -->
-    <target name="compile" depends="dirs, resource-src, aidl">
-        <javac encoding="ascii" target="1.5" debug="true" extdirs=""
-                srcdir="."
-                destdir="${outdir-classes}"
-                bootclasspath="${android-jar}" />
-        <scalac encoding="ascii" target="jvm-1.5"
-            srcdir="${srcdir}"
-            destdir="${outdir-classes}"
-            bootclasspathref="scalac.path" />
-        <unjar src="${scala-android.jar}" dest="${outdir-classes}"/>
-        <smartjar
-          srcdir="${srcdir}"
-          basedir="${outdir-classes}"
-          classname="com.google.android.notepad.NotePad"
-          destfile="${outdir}/${ant.project.name}.jar"
-        />
-        <delete includeemptydirs="true">
-          <fileset dir="${outdir-classes}" includes="**/*"/>
-        </delete>
-        <unjar src="${outdir}/${ant.project.name}.jar" dest="${outdir-classes}"/>
-    </target>
-
-    <!-- Convert this project's .class files into .dex files. -->
-    <target name="dex" depends="compile">
-        <exec executable="${dx}" failonerror="true">
-            <arg value="-JXmx384M" />
-            <arg value="--dex" />
-            <arg value="--output=${intermediate-dex}" />
-            <arg value="--locals=full" />
-            <arg value="--positions=lines" />
-            <arg path="${outdir-classes}" />
-        </exec>
-    </target>
-
-    <!-- Put the project's resources into the output package file. -->
-    <target name="package-res-and-assets">
-        <echo>Packaging resources and assets...</echo>
-        <exec executable="${aapt}" failonerror="true">
-            <arg value="package" />
-            <arg value="-f" />
-            <arg value="-c" />
-            <arg value="-M" />
-            <arg value="AndroidManifest.xml" />
-            <arg value="-S" />
-            <arg value="${resource-dir}" />
-            <arg value="-A" />
-            <arg value="${asset-dir}" />
-            <arg value="-I" />
-            <arg value="${android-jar}" />
-            <arg value="${out-package}" />
-        </exec>
-    </target>
-
-    <!-- Same as package-res-and-assets, but without "-A ${asset-dir}" -->
-    <target name="package-res-no-assets">
-        <echo>Packaging resources...</echo>
-        <exec executable="${aapt}" failonerror="true">
-            <arg value="package" />
-            <arg value="-f" />
-            <arg value="-c" />
-            <arg value="-M" />
-            <arg value="AndroidManifest.xml" />
-            <arg value="-S" />
-            <arg value="${resource-dir}" />
-            <!-- No assets directory -->
-            <arg value="-I" />
-            <arg value="${android-jar}" />
-            <arg value="${out-package}" />
-        </exec>
-    </target>
-
-    <!-- Invoke the proper target depending on whether or not
-         an assets directory is present. -->
-    <!-- TODO: find a nicer way to include the "-A ${asset-dir}" argument
-         only when the assets dir exists. -->
-    <target name="package-res">
-        <available file="${asset-dir}" type="dir"
-                property="res-target" value="and-assets" />
-        <property name="res-target" value="no-assets" />
-        <antcall target="package-res-${res-target}" />
-    </target>
-
-    <!-- Put the project's .class files into the output package file. -->
-    <target name="package-java" depends="compile, package-res">
-        <echo>Packaging java...</echo>
-        <jar destfile="${out-package}"
-                basedir="${outdir-classes}"
-                update="true" />
-    </target>
-
-    <!-- Put the project's .dex files into the output package file. -->
-    <target name="package-dex" depends="dex, package-res">
-        <echo>Packaging dex...</echo>
-        <exec executable="${zip}" failonerror="true">
-            <arg value="-qj" />
-            <arg value="${out-package}" />
-            <arg value="${intermediate-dex}" />
-        </exec>
-    </target>
-
-    <!-- Create the package file for this project from the sources. -->
-    <target name="package" depends="package-dex" />
-</project>
diff --git a/docs/android-examples/NotePad/res/drawable/app_notes.png b/docs/android-examples/NotePad/res/drawable/app_notes.png
deleted file mode 100644
index b84d171..0000000
Binary files a/docs/android-examples/NotePad/res/drawable/app_notes.png and /dev/null differ
diff --git a/docs/android-examples/NotePad/res/layout/note_editor.xml b/docs/android-examples/NotePad/res/layout/note_editor.xml
deleted file mode 100644
index 46f3187..0000000
--- a/docs/android-examples/NotePad/res/layout/note_editor.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- 
- * Copyright (C) 2007 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- -->
-
-<view xmlns:android="http://schemas.android.com/apk/res/android" class="com.google.android.notepad.NoteEditor$MyEditText" id="@+id/note"
-    android:layout_width="fill_parent"
-    android:layout_height="fill_parent"
-    android:background="#ffffff"
-    android:padding="10dip"
-    android:scrollbars="vertical"
-    android:fadingEdge="vertical" />
- 
diff --git a/docs/android-examples/NotePad/res/layout/title_editor.xml b/docs/android-examples/NotePad/res/layout/title_editor.xml
deleted file mode 100644
index 8bef991..0000000
--- a/docs/android-examples/NotePad/res/layout/title_editor.xml
+++ /dev/null
@@ -1,42 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- 
- * Copyright (C) 2007 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- -->
-
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
-  	android:layout_width="wrap_content" 
-    android:layout_height="wrap_content"
-    android:orientation="vertical"
-    android:paddingLeft="6dip"
-    android:paddingRight="6dip"
-    android:paddingBottom="3dip">
-   					  
-    <EditText id="@+id/title" 
-        android:maxLines="1" 
-        android:layout_marginTop="2dip"
-        android:layout_width="wrap_content"
-      	android:ems="25"
-        android:layout_height="wrap_content" 
-        android:autoText="true"
-        android:capitalize="sentences"
-        android:scrollHorizontally="true" />
-   		
-    <Button id="@+id/ok"
-        android:layout_width="wrap_content" 
-        android:layout_height="wrap_content" 
-        android:layout_gravity="right"
-        android:text="@string/button_ok" />
-   		
-</LinearLayout>
diff --git a/docs/android-examples/NotePad/res/values-zz-rZZ/strings.xml b/docs/android-examples/NotePad/res/values-zz-rZZ/strings.xml
deleted file mode 100644
index 4b5bad3..0000000
--- a/docs/android-examples/NotePad/res/values-zz-rZZ/strings.xml
+++ /dev/null
@@ -1,39 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- 
- * Copyright (C) 2007 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- -->
-
-<resources>
-    <string name="menu_delete">Ðéļéţé</string>
-    <string name="menu_insert">Ådd ñöţé</string>
-    <string name="menu_revert">®évérţ</string>
-    <string name="menu_discard">Ðîšçård</string>
-
-    <string name="resolve_edit">Édîţ ñöţé</string>
-    <string name="resolve_title">Édîţ ţîţļé</string>  
-
-    <string name="title_create">Çréåţé ñöţé</string>
-    <string name="title_edit">Édîţ ñöţé</string>
-	<string name="title_notes_list">Ñöţé þåd</string>   
-	<string name="title_note">Ñöţé</string>  
-	<string name="title_edit_title">Ñöţé ţîţļé:</string>  
-	
-    <string name="app_name">Ñöţé Þåd</string>  
-	
-	<string name="button_ok">ÖĶ</string>  
-	
-	<string name="error_title">Érrör</string>
-	<string name="error_message">Érrör löading nöté</string>
-</resources>
diff --git a/docs/android-examples/NotePad/res/values/colors.xml b/docs/android-examples/NotePad/res/values/colors.xml
deleted file mode 100644
index 75db7ac..0000000
--- a/docs/android-examples/NotePad/res/values/colors.xml
+++ /dev/null
@@ -1,21 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- 
- * Copyright (C) 2007 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- -->
-
-<resources>
-	<drawable name="even_stripe">#e5edfa</drawable>
-	<drawable name="odd_stripe">#ffffffff</drawable>
-</resources>
diff --git a/docs/android-examples/NotePad/res/values/strings.xml b/docs/android-examples/NotePad/res/values/strings.xml
deleted file mode 100644
index 8ab7794..0000000
--- a/docs/android-examples/NotePad/res/values/strings.xml
+++ /dev/null
@@ -1,39 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- 
- * Copyright (C) 2007 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- -->
-
-<resources>
-    <string name="menu_delete">Delete</string>
-    <string name="menu_insert">Add note</string>
-    <string name="menu_revert">Revert</string>
-    <string name="menu_discard">Discard</string>
-
-    <string name="resolve_edit">Edit note</string>
-    <string name="resolve_title">Edit title</string>  
-
-    <string name="title_create">Create note</string>
-    <string name="title_edit">Edit note</string>
-	<string name="title_notes_list">Note pad</string>   
-	<string name="title_note">Note</string>  
-	<string name="title_edit_title">Note title:</string>  
-	
-	<string name="app_name">Note Pad</string>  
-	
-	<string name="button_ok">OK</string>  
-	
-	<string name="error_title">Error</string>
-	<string name="error_message">Error loading note</string>
-</resources>
diff --git a/docs/android-examples/NotePad/sample_note.png b/docs/android-examples/NotePad/sample_note.png
deleted file mode 100644
index cea1a08..0000000
Binary files a/docs/android-examples/NotePad/sample_note.png and /dev/null differ
diff --git a/docs/android-examples/NotePad/sample_notepad.png b/docs/android-examples/NotePad/sample_notepad.png
deleted file mode 100644
index c498847..0000000
Binary files a/docs/android-examples/NotePad/sample_notepad.png and /dev/null differ
diff --git a/docs/android-examples/NotePad/src/com/google/android/notepad/NoteEditor.scala b/docs/android-examples/NotePad/src/com/google/android/notepad/NoteEditor.scala
deleted file mode 100644
index 86b8317..0000000
--- a/docs/android-examples/NotePad/src/com/google/android/notepad/NoteEditor.scala
+++ /dev/null
@@ -1,328 +0,0 @@
-/* 
- * Copyright (C) 2007 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.google.android.notepad
-
-import com.google.provider.NotePad
-
-import _root_.android.app.Activity
-import _root_.android.app.Activity._
-import _root_.android.content.{ComponentName, Context, Intent}
-import _root_.android.database.Cursor
-import _root_.android.graphics.{Canvas, Paint, Rect}
-import _root_.android.net.ContentURI
-import _root_.android.os.Bundle
-import _root_.android.text.TextUtils
-import _root_.android.util.{AttributeSet, Log, Config}
-import _root_.android.view.{KeyEvent, Menu}
-import _root_.android.widget.EditText
-
-import java.util.Map
-
-/**
- * A generic activity for editing a note in a database.  This can be used
- * either to simply view a note (Intent.VIEW_ACTION), view and edit a note
- * (Intent.EDIT_ACTION), or create a new note (Intent.INSERT_ACTION).  
- */
-object NoteEditor {
-  private val TAG = "Notes"
-
-  private val NOTE_INDEX = 1
-  private val TITLE_INDEX = 2
-  private val MODIFIED_INDEX = 3
-
-  /**
-   * Standard projection for the interesting columns of a normal note.
-   */
-  private val PROJECTION = Array(
-    NotePad.Notes._ID, // 0
-    NotePad.Notes.NOTE, // 1
-    NotePad.Notes.TITLE, // 2
-    NotePad.Notes.MODIFIED_DATE // 3
-  )
-    
-  // This is our state data that is stored when freezing.
-  private val ORIGINAL_CONTENT = "origContent"
-
-  // Identifiers for our menu items.
-  private val REVERT_ID = Menu.FIRST
-  private val DISCARD_ID = Menu.FIRST + 1
-  private val DELETE_ID = Menu.FIRST + 2
-
-  // The different distinct states the activity can be run in.
-  private val STATE_UNDEF = -1
-  private val STATE_EDIT = 0
-  private val STATE_INSERT = 1
-
-  // we need this constructor for ViewInflate
-  class MyEditText(context: Context, attrs: AttributeSet, params: Map)
-      extends EditText(context, attrs, params) {
-    private val mRect = new Rect()
-    private val mPaint = new Paint()
-    mPaint setStyle Paint.Style.STROKE
-    mPaint setColor 0xFF0000FF
-        
-    override protected def onDraw(canvas: Canvas) {
-      val count = getLineCount()
-      val r = mRect
-      val paint = mPaint
-
-      for (i <- 0 until count) {
-        val baseline = getLineBounds(i, r)
-        canvas.drawLine(r.left, baseline + 1, r.right, baseline + 1, paint)
-      }
-      super.onDraw(canvas)
-    }
-  }
-}
-
-class NoteEditor extends Activity {
-  import NoteEditor._ // companion object
-
-  private var mState = STATE_UNDEF
-  private var mNoteOnly = false
-  private var mURI: ContentURI = _
-  private var mCursor: Cursor = null
-  private var mText: EditText = null
-  private var mOriginalContent: String = ""
-
-  override protected def onCreate(icicle: Bundle) {
-    super.onCreate(icicle)
-
-    val intent = getIntent()
-    //val type = intent.resolveType(this)
-
-    // Do some setup based on the action being performed.
-
-    val action = intent.getAction()
-    if (action equals Intent.EDIT_ACTION) {
-      // Requested to edit: set that state, and the data being edited.
-      mState = STATE_EDIT
-      mURI = intent.getData()
-
-    } else if (action equals Intent.INSERT_ACTION) {
-      // Requested to insert: set that state, and create a new entry
-      // in the container.
-      mState = STATE_INSERT
-      mURI = getContentResolver().insert(intent.getData(), null)
-
-      // If we were unable to create a new note, then just finish
-      // this activity.  A RESULT_CANCELED will be sent back to the
-      // original activity if they requested a result.
-      if (mURI == null) {
-        Log.e("Notes", "Failed to insert new note into " +
-              getIntent().getData())
-        finish()
-        return
-      }
-
-      // The new entry was created, so assume all will end well and
-      // set the result to be returned.
-      setResult(RESULT_OK, mURI.toString())
-
-    } else {
-      // Whoops, unknown action!  Bail.
-      Log.e(TAG, "Unknown action, exiting")
-      finish()
-      return
-    }
-
-    // Set the layout for this activity.  You can find it
-    // in res/layout/hello_activity.xml
-    setContentView(R.layout.note_editor)
-        
-    // The text view for our note, identified by its ID in the XML file.
-    mText = findViewById(R.id.note).asInstanceOf[EditText]
-
-    // Get the note!
-    mCursor = managedQuery(mURI, PROJECTION, null, null)
-
-    // If an instance of this activity had previously stopped, we can
-    // get the original text it started with.
-    if (icicle != null)
-      mOriginalContent = icicle getString ORIGINAL_CONTENT
-  }
-
-  override protected def onResume() {
-    super.onResume()
-
-    // If we didn't have any trouble retrieving the data, it is now
-    // time to get at the stuff.
-    if (mCursor != null) {
-      // Make sure we are at the one and only row in the cursor.
-      mCursor.first()
-
-      // Modify our overall title depending on the mode we are running in.
-      if (mState == STATE_EDIT)
-        setTitle(getText(R.string.title_edit))
-      else if (mState == STATE_INSERT)
-        setTitle(getText(R.string.title_create))
-
-      // This is a little nasty: we be resumed after previously being
-      // paused/stopped.  We want to re-retrieve the data to make sure
-      // we are still accurately showing what is in the cursor...  but
-      // we don't want to lose any UI state like the current cursor
-      // position.  This trick accomplishes that.  In the future we
-      // should have a better API for doing this...
-      val curState = mText.saveState()
-      val note = mCursor getString NOTE_INDEX
-      mText setText note
-      mText restoreState curState
-
-      // If we hadn't previously retrieved the original text, do so
-      // now.  This allows the user to revert their changes.
-      if (mOriginalContent == null)
-        mOriginalContent = note
-    } else {
-      setTitle(getText(R.string.error_title))
-      mText setText getText(R.string.error_message)
-    }
-  }
-
-  override protected def onFreeze(outState: Bundle) {
-    // Save away the original text, so we still have it if the activity
-    // needs to be killed while paused.
-    outState.putString(ORIGINAL_CONTENT, mOriginalContent)
-  }
-
-  override protected def onPause() {
-    super.onPause()
-
-    // The user is going somewhere else, so make sure their current
-    // changes are safely saved away in the provider.  We don't need
-    // to do this if only editing.
-    if (mCursor != null) {
-      val text = mText.getText().toString()
-      val length = text.length()
-
-      // If this activity is finished, and there is no text, then we
-      // do something a little special: simply delete the note entry.
-      // Note that we do this both for editing and inserting...  it
-      // would be reasonable to only do it when inserting.
-      if (isFinishing() && (length == 0) && !mNoteOnly) {
-        setResult(RESULT_CANCELED)
-        deleteNote()
-
-        // Get out updates into the provider.
-      } else {
-        // This stuff is only done when working with a full-fledged note.
-        if (!mNoteOnly) {
-          // Bump the modification time to now.
-          mCursor.updateLong(MODIFIED_INDEX, System.currentTimeMillis())
-
-          // If we are creating a new note, then we want to also create
-          // an initial title for it.
-          if (mState == STATE_INSERT) {
-            var title = text.substring(0, Math.min(30, length))
-            if (length > 30) {
-              val lastSpace = title lastIndexOf ' '
-              if (lastSpace > 0)
-                title = title.substring(0, lastSpace)
-            }
-            mCursor.updateString(TITLE_INDEX, title)
-          }
-        }
-
-        // Write our text back into the provider.
-        mCursor.updateString(NOTE_INDEX, text)
-
-        // Commit all of our changes to persistent storage.  Note the
-        // use of managedCommitUpdates() instead of
-        // mCursor.commitUpdates() -- this lets Activity take care of
-        // requerying the new data if needed.
-        managedCommitUpdates(mCursor)
-      }
-    }
-  }
-
-  override def onCreateOptionsMenu(menu: Menu): Boolean = {
-    super.onCreateOptionsMenu(menu)
-
-    // Build the menus that are shown when editing.
-    if (mState == STATE_EDIT) {
-      menu.add(0, REVERT_ID, R.string.menu_revert).setShortcut(
-               KeyEvent.KEYCODE_0, 0, KeyEvent.KEYCODE_R)
-      if (!mNoteOnly)
-        menu.add(0, DELETE_ID, R.string.menu_delete).setShortcut(
-                 KeyEvent.KEYCODE_1, 0, KeyEvent.KEYCODE_D)
-
-      // Build the menus that are shown when inserting.
-    } else
-      menu.add(0, DISCARD_ID, R.string.menu_discard).setShortcut(
-               KeyEvent.KEYCODE_0, 0, KeyEvent.KEYCODE_D)
-
-    // If we are working on a real honest-to-ghod note, then append to the
-    // menu items for any other activities that can do stuff with it
-    // as well.  This does a query on the system for any activities that
-    // implement the ALTERNATIVE_ACTION for our data, adding a menu item
-    // for each one that is found.
-    if (!mNoteOnly) {
-      val intent = new Intent(null, getIntent().getData())
-      intent addCategory Intent.ALTERNATIVE_CATEGORY
-      menu.addIntentOptions(
-        Menu.ALTERNATIVE, 0,
-        new ComponentName(this, classOf[NoteEditor]), null,
-        intent, 0, null)
-    }
-
-    true
-  }
-
-  override def onOptionsItemSelected(item: Menu.Item): Boolean = {
-    // Handle all of the possible menu actions.
-    item.getId() match {
-      case DELETE_ID =>
-        deleteNote()
-        finish()
-      case DISCARD_ID =>
-        cancelNote()
-      case REVERT_ID =>
-        cancelNote()
-      case _ =>
-    }
-    super.onOptionsItemSelected(item)
-  }
-
-  /**
-   * Take care of cancelling work on a note.  Deletes the note if we
-   * had created it, otherwise reverts to the original text.
-   */
-  private final def cancelNote() {
-    if (mCursor != null) {
-      if (mState == STATE_EDIT) {
-        mCursor.updateString(NOTE_INDEX, mOriginalContent)
-        mCursor.commitUpdates()
-        mCursor.deactivate()
-        mCursor = null
-      } else if (mState == STATE_INSERT)
-        deleteNote()
-    }
-    setResult(RESULT_CANCELED)
-    finish()
-  }
-
-  /**
-   * Take care of deleting a note.  Simply deletes the entry.
-   */
-  private final def deleteNote() {
-    if (mCursor != null) {
-      mText setText ""
-      mCursor.deleteRow()
-      mCursor.deactivate()
-      mCursor = null
-    }
-  }
-}
diff --git a/docs/android-examples/NotePad/src/com/google/android/notepad/NotePadProvider.scala b/docs/android-examples/NotePad/src/com/google/android/notepad/NotePadProvider.scala
deleted file mode 100644
index 8e94c9f..0000000
--- a/docs/android-examples/NotePad/src/com/google/android/notepad/NotePadProvider.scala
+++ /dev/null
@@ -1,201 +0,0 @@
-/* 
- * Copyright (C) 2007 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.google.android.notepad
-
-import com.google.provider.NotePad
-
-import _root_.android.content.{ContentProvider, ContentProviderDatabaseHelper,
-                               ContentURIParser, ContentValues, QueryBuilder,
-                               Resources}
-import _root_.android.database.{Cursor, SQLException}
-import _root_.android.database.sqlite.SQLiteDatabase
-import _root_.android.net.ContentURI
-import _root_.android.text.TextUtils
-import _root_.android.util.Log
-
-import java.util.HashMap // note: setProjectionMap expects a Java map
-
-/**
- * Provides access to a database of notes. Each note has a title, the note
- * itself, a creation date and a modified data.
- *
- */
-object NotePadProvider {
-  private val TAG = "NotePadProvider"
-  private val DATABASE_NAME = "note_pad.db"
-  private val DATABASE_VERSION = 2
-
-  private val NOTES_LIST_PROJECTION_MAP = new HashMap/*[String, String]*/()
-  NOTES_LIST_PROJECTION_MAP.put(NotePad.Notes._ID, "_id")
-  NOTES_LIST_PROJECTION_MAP.put(NotePad.Notes.TITLE, "title")
-  NOTES_LIST_PROJECTION_MAP.put(NotePad.Notes.NOTE, "note")
-  NOTES_LIST_PROJECTION_MAP.put(NotePad.Notes.CREATED_DATE, "created")
-  NOTES_LIST_PROJECTION_MAP.put(NotePad.Notes.MODIFIED_DATE, "modified")
-
-  private val NOTES = 1
-  private val NOTE_ID = 2
-
-  private val URL_MATCHER = new ContentURIParser(ContentURIParser.NO_MATCH)
-  URL_MATCHER.addURI("com.google.provider.NotePad", "notes", NOTES)
-  URL_MATCHER.addURI("com.google.provider.NotePad", "notes/#", NOTE_ID)
-
-  private class DatabaseHelper extends ContentProviderDatabaseHelper {
-    override def onCreate(db: SQLiteDatabase) {
-      db execSQL "CREATE TABLE notes (_id INTEGER PRIMARY KEY," +
-                 "title TEXT," + "note TEXT," + "created INTEGER," +
-                 "modified INTEGER" + ");"
-    }
-
-    override def onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
-      Log.w(TAG, "Upgrading database from version " + oldVersion + " to " +
-                 newVersion + ", which will destroy all old data")
-      db execSQL "DROP TABLE IF EXISTS notes"
-      onCreate(db)
-    }
-  }
-}
-
-class NotePadProvider extends ContentProvider {
-  import NotePadProvider._
-
-  private var mDB: SQLiteDatabase = _
-
-  override def onCreate(): Boolean = {
-    val dbHelper = new DatabaseHelper()
-    mDB = dbHelper.openDatabase(getContext(), DATABASE_NAME, null, DATABASE_VERSION)
-    mDB != null
-  }
-
-  override def query(url: ContentURI, projection: Array[String],
-                     selection: String, selectionArgs: Array[String],
-                     groupBy: String, having: String, sort: String): Cursor = {
-    val qb = new QueryBuilder()
-
-    (URL_MATCHER `match` url) match {
-      case NOTES =>
-        qb setTables "notes" 
-        qb setProjectionMap NOTES_LIST_PROJECTION_MAP
-
-       case NOTE_ID =>
-         qb setTables "notes"
-         qb appendWhere ("_id=" + url.getPathSegment(1))
-
-       case _ =>
-         throw new IllegalArgumentException("Unknown URL " + url)
-    }
-
-    // If no sort order is specified use the default
-    val orderBy =
-      if (TextUtils isEmpty sort)
-        NotePad.Notes.DEFAULT_SORT_ORDER
-      else
-        sort
-
-    val c = qb.query(mDB, projection, selection, selectionArgs, groupBy,
-                having, orderBy)
-    c.setNotificationUri(getContext().getContentResolver(), url);
-    c
-  }
-
-  override def getType(url: ContentURI): String = (URL_MATCHER `match` url) match {
-    case NOTES =>
-      "vnd.android.cursor.dir/vnd.google.note"
-    case NOTE_ID =>
-      "vnd.android.cursor.item/vnd.google.note"
-    case _ =>
-      throw new IllegalArgumentException("Unknown URL " + url)
-  }
-
-  override def insert(url: ContentURI, initialValues: ContentValues): ContentURI = {
-    val values =
-      if (initialValues != null)
-        new ContentValues(initialValues)
-      else
-        new ContentValues()
-
-    if ((URL_MATCHER `match` url) != NOTES)
-      throw new IllegalArgumentException("Unknown URL " + url)
-
-    val now = System.currentTimeMillis()
-    val r = Resources.getSystem()
-
-    // Make sure that the fields are all set
-    if (! values.containsKey(NotePad.Notes.CREATED_DATE))
-      values.put(NotePad.Notes.CREATED_DATE, now)
-
-    if (! values.containsKey(NotePad.Notes.MODIFIED_DATE))
-      values.put(NotePad.Notes.MODIFIED_DATE, now)
-
-    if (! values.containsKey(NotePad.Notes.TITLE))
-      values.put(NotePad.Notes.TITLE, r.getString(_root_.android.R.string.untitled))
-
-    if (! values.containsKey(NotePad.Notes.NOTE))
-      values.put(NotePad.Notes.NOTE, "")
-
-    val rowID = mDB.insert("notes", "note", values)
-    if (rowID > 0) {
-      val uri = NotePad.Notes.CONTENT_URI addId rowID
-      getContext().getContentResolver().notifyChange(uri, null)
-      uri
-    } else
-      throw new SQLException("Failed to insert row into " + url)
-  }
-
-  override def delete(url: ContentURI, where: String, whereArgs: Array[String]): Int = {
-    val count = (URL_MATCHER `match` url) match {
-      case NOTES =>
-        mDB.delete("note_pad", where, whereArgs)
-
-      case NOTE_ID =>
-        val segment = url.getPathSegment(1)
-        //rowId = Long.parseLong(segment);
-        mDB.delete("notes", "_id=" +
-                   segment +
-                   (if (!TextUtils.isEmpty(where)) " AND (" + where + ')' else ""),
-                   whereArgs)
-
-      case _ =>
-        throw new IllegalArgumentException("Unknown URL " + url)
-    }
-
-    getContext().getContentResolver().notifyChange(url, null)
-    count
-  }
-
-  override def update(url: ContentURI, values: ContentValues,
-                      where: String, whereArgs: Array[String]): Int = {
-    val count = (URL_MATCHER `match` url) match {
-      case NOTES =>
-        mDB.update("notes", values, where, whereArgs)
-
-      case NOTE_ID =>
-        val segment = url getPathSegment 1
-        mDB.update("notes", values, "_id=" +
-                   segment +
-                   (if (!TextUtils.isEmpty(where)) " AND (" + where + ')'
-                    else ""),
-                   whereArgs)
-
-      case _ =>
-        throw new IllegalArgumentException("Unknown URL " + url)
-    }
-
-    getContext().getContentResolver().notifyChange(url, null)
-    count
-  }
-
-}
diff --git a/docs/android-examples/NotePad/src/com/google/android/notepad/NotesList.scala b/docs/android-examples/NotePad/src/com/google/android/notepad/NotesList.scala
deleted file mode 100644
index f737721..0000000
--- a/docs/android-examples/NotePad/src/com/google/android/notepad/NotesList.scala
+++ /dev/null
@@ -1,203 +0,0 @@
-/* 
- * Copyright (C) 2007 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.google.android.notepad
-
-import com.google.provider.NotePad
-
-import _root_.android.app.Activity._
-import _root_.android.app.ListActivity
-import _root_.android.content.{ComponentName, Intent}
-import _root_.android.database.Cursor
-import _root_.android.graphics.drawable.Drawable
-import _root_.android.net.ContentURI
-import _root_.android.os.Bundle
-import _root_.android.view.{KeyEvent, Menu, View}
-import _root_.android.view.View.MeasureSpec
-import _root_.android.widget.{ListAdapter, ListView, SimpleCursorAdapter, TextView}
-
-
-/**
- * Displays a list of notes. Will display notes from the ContentUri
- * provided int the intent if there is one, otherwise uses the default list
- * from the 
- *
- */
-object NotesList {
-  // Menu item Ids
-  val DELETE_ID = Menu.FIRST
-  val INSERT_ID = Menu.FIRST + 1
-
-  /**
-   * The columns we are interested in from the database
-   */
-  private val PROJECTION = Array(
-    NotePad.Notes._ID,
-    NotePad.Notes.TITLE
-  )
-}
-
-class NotesList extends ListActivity {
-  import NotesList._ // companion object
-
-  /**
-   * Cursor which holds list of all notes
-   */
-  private var mCursor: Cursor = _
-
-  override protected def onCreate(icicle: Bundle) {
-    super.onCreate(icicle)
-
-    setDefaultKeyMode(SHORTCUT_DEFAULT_KEYS)
-
-    // If no data was given in the intent (because we were started
-    // as a MAIN activity), then use our default content provider.
-    val intent = getIntent()
-    if (intent.getData() == null)
-      intent setData NotePad.Notes.CONTENT_URI
-
-    setupListStripes()
-
-    mCursor = managedQuery(getIntent().getData(), PROJECTION, null, null)
-        
-    // Used to map notes entries from the database to views
-    val adapter = new SimpleCursorAdapter(this,
-                _root_.android.R.layout.simple_list_item_1, mCursor,
-                Array(NotePad.Notes.TITLE), Array(_root_.android.R.id.text1))
-    setListAdapter(adapter)
-  }
-
-  /**
-   * Add stripes to the list view.
-   */
-  private def setupListStripes() {
-    // Get Drawables for alternating stripes
-    val lineBackgrounds = new Array[Drawable](2)
-
-    lineBackgrounds(0) = getResources().getDrawable(R.drawable.even_stripe)
-    lineBackgrounds(1) = getResources().getDrawable(R.drawable.odd_stripe)
-
-    // Make and measure a sample TextView of the sort our adapter will
-    // return
-    val view = getViewInflate().
-      inflate(_root_.android.R.layout.simple_list_item_1, null, null)
-
-    val v = view.findViewById(_root_.android.R.id.text1).asInstanceOf[TextView]
-    v setText "X"
-    // Make it 100 pixels wide, and let it choose its own height.
-    v.measure(MeasureSpec.makeMeasureSpec(View.MeasureSpec.EXACTLY, 100),
-              MeasureSpec.makeMeasureSpec(View.MeasureSpec.UNSPECIFIED, 0))
-    val height = v.getMeasuredHeight()
-    getListView().setStripes(lineBackgrounds, height)
-  }
-
-  override def onCreateOptionsMenu(menu: Menu): Boolean = {
-    super.onCreateOptionsMenu(menu)
-
-    // This is our one standard application action -- inserting a
-    // new note into the list.
-    menu.add(0, INSERT_ID, R.string.menu_insert).setShortcut(
-            KeyEvent.KEYCODE_3, 0, KeyEvent.KEYCODE_A)
-
-    // Generate any additional actions that can be performed on the
-    // overall list.  In a normal install, there are no additional
-    // actions found here, but this allows other applications to extend
-    // our menu with their own actions.
-    val intent = new Intent(null, getIntent().getData())
-    intent addCategory Intent.ALTERNATIVE_CATEGORY
-    menu.addIntentOptions(
-        Menu.ALTERNATIVE, 0, new ComponentName(this, classOf[NotesList]),
-        null, intent, 0, null)
-
-    true
-  }
-
-  override def onPrepareOptionsMenu(menu: Menu): Boolean = {
-    super.onPrepareOptionsMenu(menu)
-    val haveItems = mCursor.count() > 0
-
-    // If there are any notes in the list (which implies that one of
-    // them is selected), then we need to generate the actions that
-    // can be performed on the current selection.  This will be a combination
-    // of our own specific actions along with any extensions that can be
-    // found.
-    if (haveItems) {
-      // This is the selected item.
-      val uri = getIntent().getData() addId getSelectionRowID()
-
-      // Build menu...  always starts with the EDIT action...
-      val specifics = Array(new Intent(Intent.EDIT_ACTION, uri))
-      val items = new Array[Menu.Item](1)
-
-      // ... is followed by whatever other actions are available...
-      val intent = new Intent(null, uri)
-      intent addCategory Intent.SELECTED_ALTERNATIVE_CATEGORY
-      menu.addIntentOptions(Menu.SELECTED_ALTERNATIVE, 0, null, specifics,
-                            intent, Menu.NO_SEPARATOR_AFTER, items)
-
-      // ... and ends with the delete command.
-      menu.add(Menu.SELECTED_ALTERNATIVE, DELETE_ID, R.string.menu_delete).
-        setShortcut(KeyEvent.KEYCODE_2, 0, KeyEvent.KEYCODE_D)
-      menu.addSeparator(Menu.SELECTED_ALTERNATIVE, 0)
-
-      // Give a shortcut to the edit action.
-      if (items(0) != null)
-        items(0).setShortcut(KeyEvent.KEYCODE_1, 0, KeyEvent.KEYCODE_E)
-    }
-    else
-      menu removeGroup Menu.SELECTED_ALTERNATIVE
-
-    // Make sure the delete action is disabled if there are no items.
-    menu.setItemShown(DELETE_ID, haveItems)
-    true
-  }
-
-  override def onOptionsItemSelected(item: Menu.Item): Boolean = item.getId() match {
-    case DELETE_ID =>
-      deleteItem()
-      true
-    case INSERT_ID =>
-      insertItem()
-      true
-    case _ =>
-      super.onOptionsItemSelected(item)
-  }
-
-  override protected def onListItemClick(l: ListView, v: View,
-                                         position: Int, id: Long) {
-    val url = getIntent().getData() addId getSelectionRowID()
-
-    val action = getIntent().getAction()
-    if ((Intent.PICK_ACTION equals action) ||
-        (Intent.GET_CONTENT_ACTION equals action))
-      // The caller is waiting for us to return a note selected by
-      // the user.  The have clicked on one, so return it now.
-      setResult(RESULT_OK, url.toString())
-    else
-      // Launch activity to view/edit the currently selected item
-      startActivity(new Intent(Intent.EDIT_ACTION, url))
-  }
-
-  private final def deleteItem() {
-    mCursor moveTo getSelection()
-    mCursor.deleteRow()
-  }
-
-  private final def insertItem() {
-    // Launch activity to insert a new item
-    startActivity(new Intent(Intent.INSERT_ACTION, getIntent().getData()))
-  }
-}
diff --git a/docs/android-examples/NotePad/src/com/google/android/notepad/TitleEditor.scala b/docs/android-examples/NotePad/src/com/google/android/notepad/TitleEditor.scala
deleted file mode 100644
index 488b264..0000000
--- a/docs/android-examples/NotePad/src/com/google/android/notepad/TitleEditor.scala
+++ /dev/null
@@ -1,115 +0,0 @@
-/* 
- * Copyright (C) 2007 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.google.android.notepad
-
-import com.google.provider.NotePad
-
-import _root_.android.app.Activity
-import _root_.android.database.Cursor
-import _root_.android.net.ContentURI
-import _root_.android.os.Bundle
-import _root_.android.view.View
-import _root_.android.widget.{Button, EditText}
-
-
-/**
- * An activity that will edit the title of a note. Displays a floating
- * window with a text field.
- */
-object TitleEditor {
-
-  /**
-   * This is a special intent action that means "edit the title of a note".
-   */
-  val EDIT_TITLE_ACTION =
-    "com.google.android.notepad.action.EDIT_TITLE"
-
-  /**
-   * Index of the title column
-   */
-  private val TITLE_INDEX = 1
-
-  /**
-   * An array of the columns we are interested in.
-   */
-  private val PROJECTION = Array(
-    NotePad.Notes._ID, // 0
-    NotePad.Notes.TITLE, // 1
-  )
-}
-
-class TitleEditor extends Activity with View.OnClickListener {
-  import TitleEditor._ // companion object
-
-  /**
-   * Cursor which will provide access to the note whose title we are editing.
-   */
-  var mCursor: Cursor = _
-
-  /**
-   * The EditText field from our UI. Keep track of this so we can extract the
-   * text when we are finished.
-   */
-  var mText: EditText = _
-
-  override def onCreate(icicle: Bundle) {
-    super.onCreate(icicle)
-
-    setContentView(R.layout.title_editor)
-
-    // Get the uri of the note whose title we want to edit
-    val uri = getIntent().getData()
-
-    // Get a cursor to access the note
-    mCursor = managedQuery(uri, PROJECTION, null, null)
-
-    // Set up click handlers for the text field and button
-    mText = this.findViewById(R.id.title).asInstanceOf[EditText]
-    mText setOnClickListener this
-
-    val b = /*(Button)*/ findViewById(R.id.ok)
-    b setOnClickListener this
-  }
-
-  override protected def onResume() {
-    super.onResume()
-
-    // Initialize the text with the title column from the cursor
-    if (mCursor != null) {
-      mCursor.first()
-      val title = mCursor getString TITLE_INDEX
-      mText setText title
-    }
-  }
-
-  override protected def onPause() {
-    super.onPause()
-
-    // Write the text back into the cursor 
-    if (mCursor != null) {
-      val title = mText.getText().toString()
-       mCursor.updateString(TITLE_INDEX, title)
-       mCursor.commitUpdates()
-    }
-  }
-
-  def onClick(v: View) {
-    // When the user clicks, just finish this activity.
-    // onPause will be called, and we save our data there.
-    finish()
-  }
-}
diff --git a/docs/android-examples/NotePad/src/com/google/provider/NotePad.scala b/docs/android-examples/NotePad/src/com/google/provider/NotePad.scala
deleted file mode 100644
index 882e534..0000000
--- a/docs/android-examples/NotePad/src/com/google/provider/NotePad.scala
+++ /dev/null
@@ -1,69 +0,0 @@
-/* 
- * Copyright (C) 2007 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.google.provider
-
-import _root_.android.net.ContentURI
-import _root_.android.provider.BaseColumns
-
-/**
- * Convenience definitions for NotePadProvider
- */
-object NotePad {
-  /**
-   * Notes table
-   */
-  object Notes {
-  
-    val _ID = BaseColumns._ID
-
-    val _COUNT = BaseColumns._COUNT
-    /**
-     * The content:// style URL for this table
-     */
-    val CONTENT_URI =
-      ContentURI.create("content://com.google.provider.NotePad/notes")
-
-    /**
-     * The default sort order for this table
-     */
-    val DEFAULT_SORT_ORDER = "modified DESC"
-
-    /**
-     * The title of the note
-     * <P>Type: TEXT</P>
-     */
-    val TITLE = "title"
-
-    /**
-     * The note itself
-     * <P>Type: TEXT</P>
-     */
-    val NOTE = "note"
-
-    /**
-     * The timestamp for when the note was created
-     * <P>Type: INTEGER (long)</P>
-     */
-    val CREATED_DATE = "created"
-
-    /**
-     * The timestamp for when the note was last modified
-     * <P>Type: INTEGER (long)</P>
-     */
-    val MODIFIED_DATE = "modified"
-  }
-}
diff --git a/docs/android-examples/PhoneDialer/AndroidManifest.xml b/docs/android-examples/PhoneDialer/AndroidManifest.xml
deleted file mode 100644
index 0a5e084..0000000
--- a/docs/android-examples/PhoneDialer/AndroidManifest.xml
+++ /dev/null
@@ -1,14 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
-    package="com.google.android.phonedialer">
-    <uses-permission id="android.permission.READ_CONTACTS"/>
-    <uses-permission id="android.permission.CALL_PHONE"/>
-    <application>
-        <activity class=".PhoneDialer" android:label="PhoneDialer">
-            <intent-filter>
-                <action android:value="android.intent.action.MAIN" />
-                <category android:value="android.intent.category.LAUNCHER" />
-            </intent-filter>
-        </activity>
-    </application>
-</manifest> 
diff --git a/docs/android-examples/PhoneDialer/build.xml b/docs/android-examples/PhoneDialer/build.xml
deleted file mode 100644
index 6fb8127..0000000
--- a/docs/android-examples/PhoneDialer/build.xml
+++ /dev/null
@@ -1,222 +0,0 @@
-<?xml version="1.0" ?>
-<project name="PhoneDialer" default="package">
-    <property name="sdk-folder" value="/home/linuxsoft/apps/android-m3-rc37a" />
-    <property name="android-tools" value="/home/linuxsoft/apps/android-m3-rc37a/tools" />
-
-    <!-- The intermediates directory -->
-    <!-- Eclipse uses "bin" for its own output, so we do the same. -->
-    <property name="outdir" value="bin" />
-
-    <!-- No user servicable parts below. -->
-
-    <!-- Input directories -->
-    <property name="resource-dir" value="res" />
-    <property name="asset-dir" value="assets" />
-    <property name="srcdir" value="src" />
-
-    <!-- Output directories -->
-    <property name="outdir-classes" value="${outdir}/classes" />
-
-    <!-- Create R.java in the source directory -->
-    <property name="outdir-r" value="src" />
-
-    <!-- Intermediate files -->
-    <property name="dex-file" value="classes.dex" />
-    <property name="intermediate-dex" value="${outdir}/${dex-file}" />
-
-    <!-- The final package file to generate -->
-    <property name="out-package" value="${outdir}/${ant.project.name}.apk" />
-
-    <!-- Tools -->
-    <property name="aapt" value="${android-tools}/aapt" />
-    <property name="aidl" value="${android-tools}/aidl" />
-    <property name="dx" value="${android-tools}/dx" />
-    <property name="zip" value="zip" />
-    <property name="android-jar" value="${sdk-folder}/android.jar" />
-
-    <!-- Scala -->
-    <property environment="env"/>
-    <property name="scala.dir" value="${env.SCALA_HOME}"/>
-    <property name="scala-compiler.jar" value="${scala.dir}/lib/scala-compiler.jar"/>
-    <property name="scala-library.jar" value="${scala.dir}/lib/scala-library.jar"/>
-    <property name="scala-android.jar" value="${scala.dir}/lib/scala-android.jar"/>
-    <fail message="Missing library scala-android.jar (use sbaz to install it)">
-      <condition><not><available file="${scala-android.jar}"/></not></condition>
-    </fail>
-    <property name="scala-depend.jar" value="${android-tools}/lib/scala-depend.jar"/>
-    <path id="scala.path">
-        <pathelement path="${scala-library.jar}"/>
-        <pathelement path="${scala-compiler.jar}"/>
-    </path>
-    <path id="scalac.path">
-        <pathelement path="${android-jar}"/>
-        <pathelement path="${scala-library.jar}"/>
-    </path>
-    <taskdef
-        resource="scala/tools/ant/antlib.xml"
-        classpathref="scala.path"
-    />
-    <macrodef name="smartjar">
-        <attribute name="srcdir"/>
-        <attribute name="basedir"/>
-        <attribute name="classname"/>
-        <attribute name="destfile"/>
-        <sequential>
-          <depend
-            srcdir="@{srcdir}"
-            destdir="@{basedir}" closure="true"
-            cache="@{basedir}"
-            classpath="${android-jar}"
-          />
-          <java
-             classname="ch.epfl.lamp.util.depend" output="@{basedir}/classes.dep"
-             classpath="${scala-library.jar}${path.separator}${scala-depend.jar}">
-            <arg line="@{basedir}${file.separator}dependencies.txt"/>
-            <arg line="@{classname}"/>
-          </java>
-          <jar
-            destfile="@{destfile}"
-            basedir="@{basedir}"
-            includesfile="@{basedir}/classes.dep"
-           />
-        </sequential>
-    </macrodef>
-
-    <!-- Rules -->
-
-    <!-- Create the output directories if they don't exist yet. -->
-    <target name="dirs">
-        <mkdir dir="${outdir}" />
-        <mkdir dir="${outdir-classes}" />
-    </target>
-
-    <!-- Generate the R.java file for this project's resources. -->
-    <target name="resource-src" depends="dirs">
-        <echo>Generating R.java...</echo>
-        <exec executable="${aapt}" failonerror="true">
-            <arg value="compile" />
-            <arg value="-m" />
-            <arg value="-J" />
-            <arg value="${outdir-r}" />
-            <arg value="-M" />
-            <arg value="AndroidManifest.xml" />
-            <arg value="-S" />
-            <arg value="${resource-dir}" />
-            <arg value="-I" />
-            <arg value="${android-jar}" />
-        </exec>
-    </target>
-
-    <!-- Generate java classes from .aidl files. -->
-    <target name="aidl" depends="dirs">
-        <apply executable="${aidl}" failonerror="true">
-            <fileset dir="${srcdir}">
-                <include name="**/*.aidl"/>
-            </fileset>
-        </apply>
-    </target>
-
-    <!-- Compile this project's .java files into .class files. -->
-    <target name="compile" depends="dirs, resource-src, aidl">
-        <javac encoding="ascii" target="1.5" debug="true" extdirs=""
-                srcdir="."
-                destdir="${outdir-classes}"
-                bootclasspath="${android-jar}" />
-        <scalac encoding="ascii" target="jvm-1.5"
-            srcdir="${srcdir}"
-            destdir="${outdir-classes}"
-            bootclasspathref="scalac.path" />
-        <unjar src="${scala-android.jar}" dest="${outdir-classes}"/>
-        <smartjar
-          srcdir="${srcdir}"
-          basedir="${outdir-classes}"
-          classname="com.google.android.phonedialer.PhoneDialer"
-          destfile="${outdir}/${ant.project.name}.jar"
-        />
-        <delete includeemptydirs="true">
-          <fileset dir="${outdir-classes}" includes="**/*"/>
-        </delete>
-        <unjar src="${outdir}/${ant.project.name}.jar" dest="${outdir-classes}"/>
-    </target>
-
-    <!-- Convert this project's .class files into .dex files. -->
-    <target name="dex" depends="compile">
-        <exec executable="${dx}" failonerror="true">
-            <arg value="-JXmx384M" />
-            <arg value="--dex" />
-            <arg value="--output=${intermediate-dex}" />
-            <arg value="--locals=full" />
-            <arg value="--positions=lines" />
-            <arg path="${outdir-classes}" />
-        </exec>
-    </target>
-
-    <!-- Put the project's resources into the output package file. -->
-    <target name="package-res-and-assets">
-        <echo>Packaging resources and assets...</echo>
-        <exec executable="${aapt}" failonerror="true">
-            <arg value="package" />
-            <arg value="-f" />
-            <arg value="-c" />
-            <arg value="-M" />
-            <arg value="AndroidManifest.xml" />
-            <arg value="-S" />
-            <arg value="${resource-dir}" />
-            <arg value="-A" />
-            <arg value="${asset-dir}" />
-            <arg value="-I" />
-            <arg value="${android-jar}" />
-            <arg value="${out-package}" />
-        </exec>
-    </target>
-
-    <!-- Same as package-res-and-assets, but without "-A ${asset-dir}" -->
-    <target name="package-res-no-assets">
-        <echo>Packaging resources...</echo>
-        <exec executable="${aapt}" failonerror="true">
-            <arg value="package" />
-            <arg value="-f" />
-            <arg value="-c" />
-            <arg value="-M" />
-            <arg value="AndroidManifest.xml" />
-            <arg value="-S" />
-            <arg value="${resource-dir}" />
-            <!-- No assets directory -->
-            <arg value="-I" />
-            <arg value="${android-jar}" />
-            <arg value="${out-package}" />
-        </exec>
-    </target>
-
-    <!-- Invoke the proper target depending on whether or not
-         an assets directory is present. -->
-    <!-- TODO: find a nicer way to include the "-A ${asset-dir}" argument
-         only when the assets dir exists. -->
-    <target name="package-res">
-        <available file="${asset-dir}" type="dir"
-                property="res-target" value="and-assets" />
-        <property name="res-target" value="no-assets" />
-        <antcall target="package-res-${res-target}" />
-    </target>
-
-    <!-- Put the project's .class files into the output package file. -->
-    <target name="package-java" depends="compile, package-res">
-        <echo>Packaging java...</echo>
-        <jar destfile="${out-package}"
-                basedir="${outdir-classes}"
-                update="true" />
-    </target>
-
-    <!-- Put the project's .dex files into the output package file. -->
-    <target name="package-dex" depends="dex, package-res">
-        <echo>Packaging dex...</echo>
-        <exec executable="${zip}" failonerror="true">
-            <arg value="-qj" />
-            <arg value="${out-package}" />
-            <arg value="${intermediate-dex}" />
-        </exec>
-    </target>
-
-    <!-- Create the package file for this project from the sources. -->
-    <target name="package" depends="package-dex" />
-</project>
diff --git a/docs/android-examples/PhoneDialer/res/layout/main.xml b/docs/android-examples/PhoneDialer/res/layout/main.xml
deleted file mode 100644
index f03a74f..0000000
--- a/docs/android-examples/PhoneDialer/res/layout/main.xml
+++ /dev/null
@@ -1,17 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
-    android:orientation="horizontal"
-    android:layout_width="fill_parent"
-    android:layout_height="wrap_content"
-    >
-<TextView  
-    android:layout_width="wrap_content" 
-    android:layout_height="wrap_content" 
-    android:text="Name: "
-    />
-<TextView id="@+id/row_entry"
-    android:layout_width="wrap_content" 
-    android:layout_height="wrap_content"
-    />
-</LinearLayout>
-
diff --git a/docs/android-examples/PhoneDialer/res/values/strings.xml b/docs/android-examples/PhoneDialer/res/values/strings.xml
deleted file mode 100644
index 9843ef6..0000000
--- a/docs/android-examples/PhoneDialer/res/values/strings.xml
+++ /dev/null
@@ -1,4 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<resources>
-    <string name="app_name">PhoneDialer</string>
-</resources>
diff --git a/docs/android-examples/PhoneDialer/src/com/google/android/phonedialer/PhoneDialer.scala b/docs/android-examples/PhoneDialer/src/com/google/android/phonedialer/PhoneDialer.scala
deleted file mode 100644
index 135c543..0000000
--- a/docs/android-examples/PhoneDialer/src/com/google/android/phonedialer/PhoneDialer.scala
+++ /dev/null
@@ -1,40 +0,0 @@
-package com.google.android.phonedialer
-
-import _root_.android.app.ListActivity
-import _root_.android.content.Intent
-import _root_.android.database.Cursor
-import _root_.android.os.Bundle
-import _root_.android.provider.Contacts.{People, PeopleColumns, Phones}
-import _root_.android.widget.{ListAdapter, ListView, SimpleCursorAdapter}
-import _root_.android.view.View
-
-/**
- *  Based on YouTube demo by Dan Morrill
- *  (http://www.youtube.com/watch?v=I6ObTqIiYfE)
- */
-class PhoneDialer extends ListActivity {
-  private var mAdapter1: ListAdapter = _
-
-  /** Called when the activity is first created. */
-  override def onCreate(icicle: Bundle) {
-    super.onCreate(icicle)
-    val c = getContentResolver.query(People.CONTENT_URI, null, null, null, null)
-    startManagingCursor(c)
-    
-    val columns = Array(PeopleColumns.NAME)
-    val names = Array(R.id.row_entry)
-    
-    mAdapter1 = new SimpleCursorAdapter(this, R.layout.main, c, columns, names)
-    setListAdapter(mAdapter1)
-  }
-  
-  override def onListItemClick(l: ListView, v: View, position: Int, id: Long) {
-    super.onListItemClick(l, v, position, id)
-    val i = new Intent(Intent.CALL_ACTION)
-    val c = mAdapter1.getItem(position).asInstanceOf[Cursor]
-    val phoneId = c.getLong(c.getColumnIndex(People.PREFERRED_PHONE_ID))
-    i.setData(Phones.CONTENT_URI.addId(phoneId))
-    
-    startActivity(i)
-  }
-}
diff --git a/docs/android-examples/Snake/AndroidManifest.xml b/docs/android-examples/Snake/AndroidManifest.xml
deleted file mode 100644
index dafacef..0000000
--- a/docs/android-examples/Snake/AndroidManifest.xml
+++ /dev/null
@@ -1,28 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- 
- * Copyright (C) 2007 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- -->
-
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
-    package="com.google.android.snake">
-    <application>
-        <activity class="Snake" android:label="Snake on a Phone">
-            <intent-filter>
-                <action android:value="android.intent.action.MAIN" />
-                <category android:value="android.intent.category.LAUNCHER" />
-            </intent-filter>
-        </activity>
-    </application>
-</manifest> 
diff --git a/docs/android-examples/Snake/build.xml b/docs/android-examples/Snake/build.xml
deleted file mode 100644
index 6d2b050..0000000
--- a/docs/android-examples/Snake/build.xml
+++ /dev/null
@@ -1,222 +0,0 @@
-<?xml version="1.0" ?>
-<project name="Snake" default="package">
-    <property name="sdk-folder" value="/home/linuxsoft/apps/android-m3-rc22a" />
-    <property name="android-tools" value="/home/linuxsoft/apps/android-m3-rc22a/tools" />
-
-    <!-- The intermediates directory -->
-    <!-- Eclipse uses "bin" for its own output, so we do the same. -->
-    <property name="outdir" value="bin" />
-
-    <!-- No user servicable parts below. -->
-
-    <!-- Input directories -->
-    <property name="resource-dir" value="res" />
-    <property name="asset-dir" value="assets" />
-    <property name="srcdir" value="src" />
-
-    <!-- Output directories -->
-    <property name="outdir-classes" value="${outdir}/classes" />
-
-    <!-- Create R.java in the source directory -->
-    <property name="outdir-r" value="src" />
-
-    <!-- Intermediate files -->
-    <property name="dex-file" value="classes.dex" />
-    <property name="intermediate-dex" value="${outdir}/${dex-file}" />
-
-    <!-- The final package file to generate -->
-    <property name="out-package" value="${outdir}/${ant.project.name}.apk" />
-
-    <!-- Tools -->
-    <property name="aapt" value="${android-tools}/aapt" />
-    <property name="aidl" value="${android-tools}/aidl" />
-    <property name="dx" value="${android-tools}/dx" />
-    <property name="zip" value="zip" />
-    <property name="android-jar" value="${sdk-folder}/android.jar" />
-
-    <!-- Scala -->
-    <property environment="env"/>
-    <property name="scala.dir" value="${env.SCALA_HOME}"/>
-    <property name="scala-compiler.jar" value="${scala.dir}/lib/scala-compiler.jar"/>
-    <property name="scala-library.jar" value="${scala.dir}/lib/scala-library.jar"/>
-    <property name="scala-android.jar" value="${scala.dir}/lib/scala-android.jar"/>
-    <fail message="Missing library scala-android.jar (use sbaz to install it)">
-      <condition><not><available file="${scala-android.jar}"/></not></condition>
-    </fail>
-    <property name="scala-depend.jar" value="${android-tools}/lib/scala-depend.jar"/>
-    <path id="scala.path">
-        <pathelement path="${scala-library.jar}"/>
-        <pathelement path="${scala-compiler.jar}"/>
-    </path>
-    <path id="scalac.path">
-        <pathelement path="${android-jar}"/>
-        <pathelement path="${scala-library.jar}"/>
-    </path>
-    <taskdef
-        resource="scala/tools/ant/antlib.xml"
-        classpathref="scala.path"
-    />
-    <macrodef name="smartjar">
-        <attribute name="srcdir"/>
-        <attribute name="basedir"/>
-        <attribute name="classname"/>
-        <attribute name="destfile"/>
-        <sequential>
-          <depend
-            srcdir="@{srcdir}"
-            destdir="@{basedir}" closure="true"
-            cache="@{basedir}"
-            classpath="${android-jar}"
-          />
-          <java
-             classname="ch.epfl.lamp.util.depend" output="@{basedir}/classes.dep"
-             classpath="${scala-library.jar}${path.separator}${scala-depend.jar}">
-            <arg line="@{basedir}${file.separator}dependencies.txt"/>
-            <arg line="@{classname}"/>
-          </java>
-          <jar
-            destfile="@{destfile}"
-            basedir="@{basedir}"
-            includesfile="@{basedir}/classes.dep"
-           />
-        </sequential>
-    </macrodef>
-
-    <!-- Rules -->
-
-    <!-- Create the output directories if they don't exist yet. -->
-    <target name="dirs">
-        <mkdir dir="${outdir}" />
-        <mkdir dir="${outdir-classes}" />
-    </target>
-
-    <!-- Generate the R.java file for this project's resources. -->
-    <target name="resource-src" depends="dirs">
-        <echo>Generating R.java...</echo>
-        <exec executable="${aapt}" failonerror="true">
-            <arg value="compile" />
-            <arg value="-m" />
-            <arg value="-J" />
-            <arg value="${outdir-r}" />
-            <arg value="-M" />
-            <arg value="AndroidManifest.xml" />
-            <arg value="-S" />
-            <arg value="${resource-dir}" />
-            <arg value="-I" />
-            <arg value="${android-jar}" />
-        </exec>
-    </target>
-
-    <!-- Generate java classes from .aidl files. -->
-    <target name="aidl" depends="dirs">
-        <apply executable="${aidl}" failonerror="true">
-            <fileset dir="${srcdir}">
-                <include name="**/*.aidl"/>
-            </fileset>
-        </apply>
-    </target>
-
-    <!-- Compile this project's .java files into .class files. -->
-    <target name="compile" depends="dirs, resource-src, aidl">
-        <javac encoding="ascii" target="1.5" debug="true" extdirs=""
-                srcdir="."
-                destdir="${outdir-classes}"
-                bootclasspath="${android-jar}" />
-        <scalac encoding="ascii" target="jvm-1.5"
-            srcdir="${srcdir}"
-            destdir="${outdir-classes}"
-            bootclasspathref="scalac.path" />
-        <unjar src="${scala-android.jar}" dest="${outdir-classes}"/>
-        <smartjar
-          srcdir="${srcdir}"
-          basedir="${outdir-classes}"
-          classname="com.google.android.snake.Snake"
-          destfile="${outdir}/${ant.project.name}.jar"
-        />
-        <delete includeemptydirs="true">
-          <fileset dir="${outdir-classes}" includes="**/*"/>
-        </delete>
-        <unjar src="${outdir}/${ant.project.name}.jar" dest="${outdir-classes}"/>
-    </target>
-
-    <!-- Convert this project's .class files into .dex files. -->
-    <target name="dex" depends="compile">
-        <exec executable="${dx}" failonerror="true">
-            <arg value="-JXmx384M" />
-            <arg value="--dex" />
-            <arg value="--output=${intermediate-dex}" />
-            <arg value="--locals=full" />
-            <arg value="--positions=lines" />
-            <arg path="${outdir-classes}" />
-        </exec>
-    </target>
-
-    <!-- Put the project's resources into the output package file. -->
-    <target name="package-res-and-assets">
-        <echo>Packaging resources and assets...</echo>
-        <exec executable="${aapt}" failonerror="true">
-            <arg value="package" />
-            <arg value="-f" />
-            <arg value="-c" />
-            <arg value="-M" />
-            <arg value="AndroidManifest.xml" />
-            <arg value="-S" />
-            <arg value="${resource-dir}" />
-            <arg value="-A" />
-            <arg value="${asset-dir}" />
-            <arg value="-I" />
-            <arg value="${android-jar}" />
-            <arg value="${out-package}" />
-        </exec>
-    </target>
-
-    <!-- Same as package-res-and-assets, but without "-A ${asset-dir}" -->
-    <target name="package-res-no-assets">
-        <echo>Packaging resources...</echo>
-        <exec executable="${aapt}" failonerror="true">
-            <arg value="package" />
-            <arg value="-f" />
-            <arg value="-c" />
-            <arg value="-M" />
-            <arg value="AndroidManifest.xml" />
-            <arg value="-S" />
-            <arg value="${resource-dir}" />
-            <!-- No assets directory -->
-            <arg value="-I" />
-            <arg value="${android-jar}" />
-            <arg value="${out-package}" />
-        </exec>
-    </target>
-
-    <!-- Invoke the proper target depending on whether or not
-         an assets directory is present. -->
-    <!-- TODO: find a nicer way to include the "-A ${asset-dir}" argument
-         only when the assets dir exists. -->
-    <target name="package-res">
-        <available file="${asset-dir}" type="dir"
-                property="res-target" value="and-assets" />
-        <property name="res-target" value="no-assets" />
-        <antcall target="package-res-${res-target}" />
-    </target>
-
-    <!-- Put the project's .class files into the output package file. -->
-    <target name="package-java" depends="compile, package-res">
-        <echo>Packaging java...</echo>
-        <jar destfile="${out-package}"
-                basedir="${outdir-classes}"
-                update="true" />
-    </target>
-
-    <!-- Put the project's .dex files into the output package file. -->
-    <target name="package-dex" depends="dex, package-res">
-        <echo>Packaging dex...</echo>
-        <exec executable="${zip}" failonerror="true">
-            <arg value="-qj" />
-            <arg value="${out-package}" />
-            <arg value="${intermediate-dex}" />
-        </exec>
-    </target>
-
-    <!-- Create the package file for this project from the sources. -->
-    <target name="package" depends="package-dex" />
-</project>
diff --git a/docs/android-examples/Snake/res/drawable/greenstar.png b/docs/android-examples/Snake/res/drawable/greenstar.png
deleted file mode 100644
index 26be5c8..0000000
Binary files a/docs/android-examples/Snake/res/drawable/greenstar.png and /dev/null differ
diff --git a/docs/android-examples/Snake/res/drawable/redstar.png b/docs/android-examples/Snake/res/drawable/redstar.png
deleted file mode 100644
index e9c0947..0000000
Binary files a/docs/android-examples/Snake/res/drawable/redstar.png and /dev/null differ
diff --git a/docs/android-examples/Snake/res/drawable/yellowstar.png b/docs/android-examples/Snake/res/drawable/yellowstar.png
deleted file mode 100644
index 134b234..0000000
Binary files a/docs/android-examples/Snake/res/drawable/yellowstar.png and /dev/null differ
diff --git a/docs/android-examples/Snake/res/layout/snake_layout.xml b/docs/android-examples/Snake/res/layout/snake_layout.xml
deleted file mode 100644
index 8e2ced1..0000000
--- a/docs/android-examples/Snake/res/layout/snake_layout.xml
+++ /dev/null
@@ -1,44 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- 
- * Copyright (C) 2007 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- -->
-
-<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
-	android:layout_width="fill_parent"
-	android:layout_height="fill_parent">
-	
-	<com.google.android.snake.SnakeView
-		id="@+id/snake"
-		android:layout_width="fill_parent"
-                android:layout_height="fill_parent"
-                tileSize="12"
-                />
-	
-	<RelativeLayout
-		android:layout_width="fill_parent"
-		android:layout_height="fill_parent" >
-		
-		<TextView
-			id="@+id/text"
-			android:text="@string/snake_layout_text_text"
-			android:visibility="visible"
-			android:layout_width="wrap_content"
-			android:layout_height="wrap_content"
-			android:layout_centerInParent="true"
-			android:textAlign="center"
-			android:textColor="#ff8888ff"
-			android:textSize="24sp"/>
-	</RelativeLayout>
-</FrameLayout>
diff --git a/docs/android-examples/Snake/res/values/attrs.xml b/docs/android-examples/Snake/res/values/attrs.xml
deleted file mode 100644
index 169e527..0000000
--- a/docs/android-examples/Snake/res/values/attrs.xml
+++ /dev/null
@@ -1,23 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- 
- * Copyright (C) 2007 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- -->
-
-<resources>
-  <declare-styleable name="TileView">
-    <attr name="tileSize" format="integer" />
-  </declare-styleable>
-</resources>
-
diff --git a/docs/android-examples/Snake/res/values/strings.xml b/docs/android-examples/Snake/res/values/strings.xml
deleted file mode 100644
index 7772062..0000000
--- a/docs/android-examples/Snake/res/values/strings.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- 
- * Copyright (C) 2007 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- -->
-
-<resources>
-  <string name="mode_ready">Snake\nPress Up To Play</string>
-  <string name="mode_pause">Paused\nPress Up To Resume</string>
-  <string name="mode_lose_prefix">Game Over\nScore: </string>
-  <string name="mode_lose_suffix">\nPress Up To Play</string>
-
-    <string name="snake_layout_text_text"></string>
-</resources>
diff --git a/docs/android-examples/Snake/src/com/google/android/snake/Snake.scala b/docs/android-examples/Snake/src/com/google/android/snake/Snake.scala
deleted file mode 100644
index 079ba4f..0000000
--- a/docs/android-examples/Snake/src/com/google/android/snake/Snake.scala
+++ /dev/null
@@ -1,80 +0,0 @@
-/* 
- * Copyright (C) 2007 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.google.android.snake
-
-import _root_.android.app.Activity
-import _root_.android.os.Bundle
-import _root_.android.view.Window
-import _root_.android.widget.TextView
-
-/**
- * Snake: a simple game that everyone can enjoy.
- * 
- * This is an implementation of the classic Game "Snake", in which you control a
- * serpent roaming around the garden looking for apples. Be careful, though,
- * because when you catch one, not only will you become longer, but you'll move
- * faster. Running into yourself or the walls will end the game.
- */
-object Snake {
-  private val ICICLE_KEY = "snake-view"
-}
-
-class Snake extends Activity {
-  import Snake._ // companion object
-
-  private var mSnakeView: SnakeView = _
-
-  /**
-   * Called when Activity is first created. Turns off the title bar, sets up
-   * the content views, and fires up the SnakeView.
-   */
-  override def onCreate(icicle: Bundle) {
-    super.onCreate(icicle)
-
-    // No Title bar
-    requestWindowFeature(Window.FEATURE_NO_TITLE)
-
-    setContentView(R.layout.snake_layout)
-
-    mSnakeView = findViewById(R.id.snake).asInstanceOf[SnakeView]
-    mSnakeView setTextView findViewById(R.id.text).asInstanceOf[TextView]
-
-    if (icicle == null) {
-      // We were just launched -- set up a new game
-      mSnakeView setMode SnakeView.READY
-    } else {
-      // We are being restored
-      val map = icicle getBundle ICICLE_KEY
-      if (map != null)
-        mSnakeView restoreState map
-      else
-        mSnakeView setMode SnakeView.PAUSE
-    }
-  }
-
-  override protected def onPause() {
-    super.onPause()
-    // Pause the game along with the activity
-    mSnakeView setMode SnakeView.PAUSE
-  }
-
-  override def onFreeze(outState: Bundle) {
-    //Store the game state
-    outState.putBundle(ICICLE_KEY, mSnakeView.saveState())
-  }
-
-}
diff --git a/docs/android-examples/Snake/src/com/google/android/snake/SnakeView.scala b/docs/android-examples/Snake/src/com/google/android/snake/SnakeView.scala
deleted file mode 100644
index 8e961b7..0000000
--- a/docs/android-examples/Snake/src/com/google/android/snake/SnakeView.scala
+++ /dev/null
@@ -1,464 +0,0 @@
-/* 
- * Copyright (C) 2007 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.google.android.snake
-
-import java.util.Map
-
-import scala.collection.jcl.ArrayList
-
-import _root_.android.content.{Context, Resources}
-import _root_.android.os.{Bundle, Handler, Message}
-import _root_.android.util.{AttributeSet, Log}
-import _root_.android.view.{KeyEvent, View}
-import _root_.android.widget.TextView
-
-/**
- * SnakeView: implementation of a simple game of Snake
- */
-object SnakeView {
-  private val TAG = "SnakeView"
-
-  final val PAUSE = 0
-  final val READY = 1
-  final val RUNNING = 2
-  final val LOSE = 3
-
-  private final val NORTH = 1
-  private final val SOUTH = 2
-  private final val EAST = 3
-  private final val WEST = 4
-
-  /**
-   * Labels for the drawables that will be loaded into the TileView class
-   */
-  private final val RED_STAR = 1
-  private final val YELLOW_STAR = 2
-  private final val GREEN_STAR = 3
-
-  /**
-   * Everyone needs a little randomness in their life
-   */
-  private final val RND = new Random()
-
-}
-
-/**
- * Constructs a SnakeView based on inflation from XML
- * 
- * @param context
- * @param attrs
- * @param inflateParams
- */
-class SnakeView(context: Context, attrs: AttributeSet, inflateParams: Map,
-    		defStyle: Int) extends TileView(context, attrs, inflateParams, defStyle) {
-  import SnakeView._  // companion object
-
-  def this(context: Context, attrs: AttributeSet, inflateParams: Map) =
-    this(context, attrs, inflateParams, 0)
-
-  /**
-   * Current mode of application: READY to run, RUNNING, or you have already
-   * lost. static final ints are used instead of an enum for performance
-   * reasons.
-   */
-  private var mMode = READY
-
-  /**
-   * Current direction the snake is headed.
-   */
-  private var mDirection = NORTH
-  private var mNextDirection = NORTH
-
-  /**
-   * mScore: used to track the number of apples captured mMoveDelay: number of
-   * milliseconds between snake movements. This will decrease as apples are
-   * captured.
-   */
-  private var mScore = 0L
-  private var mMoveDelay = 600L
-
-  /**
-   * mLastMove: tracks the absolute time when the snake last moved, and is used
-   * to determine if a move should be made based on mMoveDelay.
-   */
-  private var mLastMove: Long = _
-
-  /**
-   * mStatusText: text shows to the user in some run states
-   */
-  private var mStatusText: TextView = _
-
-  /**
-   * mSnakeTrail: a list of Coordinates that make up the snake's body
-   * mAppleList: the secret location of the juicy apples the snake craves.
-   */
-  private val mSnakeTrail = new ArrayList[Coordinate]()
-  private val mAppleList = new ArrayList[Coordinate]()
-
-  /**
-   * Create a simple handler that we can use to cause animation to happen.  We
-   * set ourselves as a target and we can use the sleep()
-   * function to cause an update/invalidate to occur at a later date.
-   */
-  private val mRedrawHandler = new RefreshHandler()
-
-  class RefreshHandler extends Handler {
-    override def handleMessage(msg: Message) {
-      SnakeView.this.update()
-      SnakeView.this.invalidate()
-    }
-    def sleep(delayMillis: Long) {
-      this.removeMessages(0)
-      sendMessageDelayed(obtainMessage(0), delayMillis)
-    }
-  }
-
-  {
-    setFocusable(true)
-
-    val r = this.getContext().getResources()
-
-    resetTiles(4)
-    loadTile(RED_STAR, r getDrawable R.drawable.redstar)
-    loadTile(YELLOW_STAR, r getDrawable R.drawable.yellowstar)
-    loadTile(GREEN_STAR, r getDrawable R.drawable.greenstar)	
-  }
-
-  private def initNewGame() {
-    mSnakeTrail.clear()
-    mAppleList.clear()
-
-    // For now we're just going to load up a short default eastbound snake
-    // that's just turned north
-    mSnakeTrail add new Coordinate(7, 7)
-    mSnakeTrail add new Coordinate(6, 7)
-    mSnakeTrail add new Coordinate(5, 7)
-    mSnakeTrail add new Coordinate(4, 7)
-    mSnakeTrail add new Coordinate(3, 7)
-    mSnakeTrail add new Coordinate(2, 7)
-    mNextDirection = NORTH
-
-    // Two apples to start with
-    addRandomApple()
-    addRandomApple()
-
-    mMoveDelay = 600
-    mScore = 0
-  }
-
-  /**
-   * Given a ArrayList of coordinates, we need to flatten them into an array of
-   * ints before we can stuff them into a map for flattening and storage.
-   * 
-   * @param cvec : a ArrayList of Coordinate objects
-   * @return : a simple array containing the x/y values of the coordinates
-   * as [x1,y1,x2,y2,x3,y3...]
-   */
-  private def coordArrayListToArray(cvec: ArrayList[Coordinate]): Array[Int] = {
-    val count = cvec.size
-    val rawArray = new Array[Int](count * 2)
-    for (index <- 0 until count) {
-      val c = cvec(index)
-      rawArray(2 * index) = c.x
-      rawArray(2 * index + 1) = c.y
-    }
-    rawArray
-  }
-
-  /**
-   * Save game state so that the user does not lose anything
-   * if the game process is killed while we are in the 
-   * background.
-   * 
-   * @return a Bundle with this view's state
-   */
-  def saveState(): Bundle = {
-    val map = new Bundle()
-
-    map.putIntArray("mAppleList", coordArrayListToArray(mAppleList))
-    map.putInteger("mDirection", mDirection)
-    map.putInteger("mNextDirection", mNextDirection)
-    map.putLong("mMoveDelay", mMoveDelay)
-    map.putLong("mScore", mScore)
-    map.putIntArray("mSnakeTrail", coordArrayListToArray(mSnakeTrail))
-
-    map
-  }
-
-  /**
-   * Given a flattened array of ordinate pairs, we reconstitute them into a
-   * ArrayList of Coordinate objects
-   * 
-   * @param rawArray : [x1,y1,x2,y2,...]
-   * @return a ArrayList of Coordinates
-   */
-  private def coordArrayToArrayList(dest: ArrayList[Coordinate], rawArray: Array[Int]) {
-    dest.clear()
-    var index = 0; while (index < rawArray.length) {
-      dest add Coordinate(rawArray(index), rawArray(index + 1))
-      index += 2
-    }
-  }
-
-  /**
-   * Restore game state if our process is being relaunched
-   * 
-   * @param icicle a Bundle containing the game state
-   */
-  def restoreState(icicle: Bundle) {
-    setMode(PAUSE)
-
-    coordArrayToArrayList(mAppleList, icicle getIntArray "mAppleList")
-    mDirection = (icicle getInteger "mDirection").intValue
-    mNextDirection = (icicle getInteger "mNextDirection").intValue
-    mMoveDelay = (icicle getLong "mMoveDelay").longValue
-    mScore = (icicle getLong "mScore").longValue
-    coordArrayToArrayList(mSnakeTrail, icicle getIntArray "mSnakeTrail")
-  }
-
-  /*
-   * handles key events in the game. Update the direction our snake is traveling
-   * based on the DPAD. Ignore events that would cause the snake to immediately
-   * turn back on itself.
-   * 
-   * (non-Javadoc)
-   * 
-   * @see android.view.View#onKeyDown(int, android.os.KeyEvent)
-   */
-  override def onKeyDown(keyCode: Int, msg: KeyEvent): Boolean = keyCode match {
-    case KeyEvent.KEYCODE_DPAD_UP =>
-      if (mMode == READY | mMode == LOSE) {
-        /*
-         * At the beginning of the game, or the end of a previous one,
-         * we should start a new game.
-         */
-        initNewGame()
-        setMode(RUNNING)
-        update()
-      }
-      else if (mMode == PAUSE) {
-        /*
-         * If the game is merely paused, we should just continue where
-         * we left off.
-         */
-        setMode(RUNNING)
-        update()
-      }
-
-      if (mDirection != SOUTH) mNextDirection = NORTH
-      true
-
-    case KeyEvent.KEYCODE_DPAD_DOWN =>
-      if (mDirection != NORTH) mNextDirection = SOUTH
-      true
-
-    case KeyEvent.KEYCODE_DPAD_LEFT =>
-      if (mDirection != EAST) mNextDirection = WEST
-      true
-
-    case KeyEvent.KEYCODE_DPAD_RIGHT =>
-      if (mDirection != WEST) mNextDirection = EAST
-      true
-
-    case _ =>
-      super.onKeyDown(keyCode, msg)
-  }
-
-  /**
-   * Sets the TextView that will be used to give information (such as "Game
-   * Over" to the user.
-   * 
-   * @param newView
-   */
-  def setTextView(newView: TextView) {
-    mStatusText = newView
-  }
-
-  /**
-   * Updates the current mode of the application (RUNNING or PAUSED or the like)
-   * as well as sets the visibility of textview for notification
-   * 
-   * @param newMode
-   */
-  def setMode(newMode: Int) {
-    val oldMode = mMode
-    mMode = newMode
-
-    if (newMode == RUNNING & oldMode != RUNNING) {
-      mStatusText setVisibility View.INVISIBLE
-      update()
-      return
-    }
-
-    val res = getContext().getResources()
-    val str =
-      if (newMode == PAUSE)
-        res getText R.string.mode_pause
-      else if (newMode == READY)
-        res getText R.string.mode_ready
-      else if (newMode == LOSE)
-        (res getString R.string.mode_lose_prefix) + mScore +
-        (res getString R.string.mode_lose_suffix)
-      else
-        ""
-
-    mStatusText setText str
-    mStatusText setVisibility View.VISIBLE
-  }
-
-  /**
-   * Selects a random location within the garden that is not currently covered
-   * by the snake. Currently _could_ go into an infinite loop if the snake
-   * currently fills the garden, but we'll leave discovery of this prize to a
-   * truly excellent snake-player.
-   * 
-   */
-  private def addRandomApple() {
-    var newCoord: Coordinate = null
-    var found = false
-    while (!found) {
-      // Choose a new location for our apple
-      val newX = 1 + RND.nextInt(mXTileCount - 2)
-      val newY = 1 + RND.nextInt(mYTileCount - 2)
-      newCoord = Coordinate(newX, newY)
-
-      // Make sure it's not already under the snake
-      var collision = false
-      for (index <- 0 until mSnakeTrail.size) {
-        if (mSnakeTrail(index) equals newCoord) collision = true
-      }
-      // if we're here and there's been no collision, then we have
-      // a good location for an apple. Otherwise, we'll circle back
-      // and try again
-      found = !collision
-    }
-    if (newCoord == null)
-      Log.e(TAG, "Somehow ended up with a null newCoord!")
-    mAppleList add newCoord
-  }
-
-  /**
-   * Handles the basic update loop, checking to see if we are in the running
-   * state, determining if a move should be made, updating the snake's location.
-   */
-  def update() {
-    if (mMode == RUNNING) {
-      val now = System.currentTimeMillis()
-
-      if (now - mLastMove > mMoveDelay) {
-        clearTiles()
-        updateWalls()
-        updateSnake()
-        updateApples()
-        mLastMove = now
-      }
-      mRedrawHandler sleep mMoveDelay
-    }
-  }
-
-  /**
-   * Draws some walls.
-   * 
-   */
-  private def updateWalls() {
-    for (x <- 0 until mXTileCount) {
-      setTile(GREEN_STAR, x, 0)
-      setTile(GREEN_STAR, x, mYTileCount - 1)
-    }
-    for (y <- 1 until (mYTileCount-1)) {
-      setTile(GREEN_STAR, 0, y)
-      setTile(GREEN_STAR, mXTileCount - 1, y)
-    }
-  }
-
-  /**
-   * Draws some apples.
-   * 
-   */
-  private def updateApples() {
-    for (c <- mAppleList) setTile(YELLOW_STAR, c.x, c.y)
-  }
-
-  /**
-   * Figure out which way the snake is going, see if he's run into anything (the
-   * walls, himself, or an apple). If he's not going to die, we then add to the
-   * front and subtract from the rear in order to simulate motion. If we want to
-   * grow him, we don't subtract from the rear.
-   */
-  private def updateSnake() {
-    var growSnake = false
-
-    // grab the snake by the head
-    val head = mSnakeTrail(0)
-
-    mDirection = mNextDirection
-
-    val newHead = mDirection match {
-      case EAST  => Coordinate(head.x + 1, head.y)
-      case WEST  => Coordinate(head.x - 1, head.y)
-      case NORTH => Coordinate(head.x, head.y - 1)
-      case SOUTH => Coordinate(head.x, head.y + 1)
-    }
-
-    // Collision detection
-    // For now we have a 1-square wall around the entire arena
-    if ((newHead.x < 1) || (newHead.y < 1) ||
-        (newHead.x > mXTileCount - 2) || (newHead.y > mYTileCount - 2)) {
-      setMode(LOSE)
-      return
-    }
-
-    // Look for collisions with itself
-    for (c <- mSnakeTrail if c equals newHead) {
-      setMode(LOSE)
-      return
-    }
-
-    // Look for apples
-    for (c <- mAppleList if c equals newHead) {
-      mAppleList remove c
-      addRandomApple()
-                
-      mScore += 1
-      mMoveDelay = 9 * mMoveDelay / 10
-
-      growSnake = true
-    }
-
-    // push a new head onto the ArrayList and pull off the tail
-    mSnakeTrail.add(0, newHead)
-    // except if we want the snake to grow
-    if (!growSnake)
-      mSnakeTrail remove (mSnakeTrail.size - 1)
-
-    var index = 0
-    for (c <- mSnakeTrail) {
-      setTile(if (index == 0) YELLOW_STAR else RED_STAR, c.x, c.y)
-      index += 1
-    }
-  }
-
-  /**
-   * Simple class containing two integer values and a comparison function.
-   * There's probably something I should use instead, but this was quick and
-   * easy to build.
-   */
-  private case class Coordinate(x: Int, y: Int) {
-    override def toString() = "Coordinate: [" + x + "," + y + "]"
-  }
-
-}
diff --git a/docs/android-examples/Snake/src/com/google/android/snake/TileView.scala b/docs/android-examples/Snake/src/com/google/android/snake/TileView.scala
deleted file mode 100644
index 784b7cb..0000000
--- a/docs/android-examples/Snake/src/com/google/android/snake/TileView.scala
+++ /dev/null
@@ -1,137 +0,0 @@
-/* 
- * Copyright (C) 2007 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.google.android.snake
-
-import _root_.android.content.{Context, Resources}
-import _root_.android.graphics.{Bitmap, Canvas, Paint}
-import _root_.android.graphics.drawable.Drawable
-import _root_.android.util.AttributeSet
-import _root_.android.view.View
-
-import java.util.Map
-
-/**
- * TileView: a View-variant designed for handling arrays of "icons" or other
- * drawables.
- */
-class TileView(context: Context, attrs: AttributeSet, inflateParams: Map,
-               defStyle: Int) extends View(context, attrs, inflateParams, defStyle) {
-
-  /**
-   * Parameters controlling the size of the tiles and their range within view.
-   * Width/Height are in pixels, and Drawables will be scaled to fit to these
-   * dimensions. X/Y Tile Counts are the number of tiles that will be drawn.
-   */
-  protected var mTileSize: Int = _
-
-  protected var mXTileCount: Int = _
-  protected var mYTileCount: Int = _
-
-  private var mXOffset: Int = _
-  private var mYOffset: Int = _
-
-  /**
-   * A hash that maps integer handles specified by the subclasser to the
-   * drawable that will be used for that reference
-   */
-  private var mTileArray: Array[Bitmap] = _
-
-  /**
-   * A two-dimensional array of integers in which the number represents the
-   * index of the tile that should be drawn at that locations
-   */
-  private var mTileGrid: Array[Array[Int]] = _
-
-  private val mPaint = new Paint()
-
-  mTileSize = {
-    val a = context.obtainStyledAttributes(attrs, R.styleable.TileView)
-    a.getInt(R.styleable.TileView_tileSize, 12)
-  }
-
-  def this(context: Context, attrs: AttributeSet, inflateParams: Map) =
-    this(context, attrs, inflateParams, 0)
-    
-  /**
-   * Rests the internal array of Bitmaps used for drawing tiles, and
-   * sets the maximum index of tiles to be inserted
-   * 
-   * @param tilecount
-   */
-  def resetTiles(tilecount: Int) {
-    mTileArray = new Array[Bitmap](tilecount)
-  }
-
-  override protected def onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
-    mXTileCount = java.lang.Math.floor(w / mTileSize).toInt
-    mYTileCount = java.lang.Math.floor(h / mTileSize).toInt
-
-    mXOffset = (w - (mTileSize * mXTileCount)) / 2
-    mYOffset = (h - (mTileSize * mYTileCount)) / 2
-
-    mTileGrid = new Array[Array[Int]](mXTileCount, mYTileCount)
-    clearTiles()
-  }
-
-  /**
-   * Function to set the specified Drawable as the tile for a particular
-   * integer key.
-   * 
-   * @param key
-   * @param tile
-   */
-  def loadTile(key: Int, tile: Drawable) {
-    val bitmap = Bitmap.createBitmap(mTileSize, mTileSize, true)
-    val canvas = new Canvas(bitmap)
-    tile.setBounds(0, 0, mTileSize, mTileSize)
-    tile draw canvas
-
-    mTileArray(key) = bitmap
-  }
-
-  /**
-   * Resets all tiles to 0 (empty)
-   * 
-   */
-  def clearTiles() {
-    for (x <- 0 until mXTileCount; y <- 0 until mYTileCount)
-      setTile(0, x, y)
-  }
-
-  /**
-   * Used to indicate that a particular tile (set with loadTile and referenced
-   * by an integer) should be drawn at the given x/y coordinates during the
-   * next invalidate/draw cycle.
-   * 
-   * @param tileindex
-   * @param x
-   * @param y
-   */
-  def setTile(tileindex: Int, x: Int, y: Int) {
-    mTileGrid(x)(y) = tileindex
-  }
-
-  override def onDraw(canvas: Canvas) {
-    super.onDraw(canvas)
-    for (x <- 0 until mXTileCount; y <- 0 until mYTileCount if mTileGrid(x)(y) > 0)
-      canvas.drawBitmap(mTileArray(mTileGrid(x)(y)), 
-                        mXOffset + x * mTileSize,
-                    	mYOffset + y * mTileSize,
-                    	mPaint)
-  }
-
-}
diff --git a/docs/development/jvm.txt b/docs/development/jvm.txt
index b007a81..2f8085a 100644
--- a/docs/development/jvm.txt
+++ b/docs/development/jvm.txt
@@ -53,7 +53,7 @@ Scala Environment Options
 
 
 In the following example, simply replace <jdk> by
-"java-1.4", "java-1.5", "java-1.6", "java-1.7" or
+"java-1.5", "java-1.6", "java-1.7" or
 "java-ibm-1.5" to experiment with different Java VMs:
 
 > env JAVACMD=/home/linuxsoft/apps/<jdk>/bin/java \
@@ -122,5 +122,3 @@ Garbage Collection
 [gc04] Garbage Collector Ergonomics
        http://java.sun.com/j2se/1.5.0/docs/guide/vm/gc-ergonomics.html
 
-
-$Id: jvm.txt 10778 2007-04-20 17:21:27Z michelou $
diff --git a/docs/development/scala.dbc/SQLTypes.dot b/docs/development/scala.dbc/SQLTypes.dot
index 755b2fc..77c27cf 100644
--- a/docs/development/scala.dbc/SQLTypes.dot
+++ b/docs/development/scala.dbc/SQLTypes.dot
@@ -45,4 +45,4 @@ digraph SQLTypes {
   TimeWithTimezoneType -> TimeType
   TimestampWithoutTimezoneType -> TimestampType
   TimestampWithTimezoneType -> TimestampType
-}
\ No newline at end of file
+}
diff --git a/docs/development/scala.tools.nsc/nscNodes.dot b/docs/development/scala.tools.nsc/nscNodes.dot
index eb0b792..ab96c45 100644
--- a/docs/development/scala.tools.nsc/nscNodes.dot
+++ b/docs/development/scala.tools.nsc/nscNodes.dot
@@ -101,4 +101,4 @@ digraph SQLTypes {
   
   AppliedTypeTree -> TypTree
   
-}
\ No newline at end of file
+}
diff --git a/docs/examples/actors/boundedbuffer.scala b/docs/examples/actors/boundedbuffer.scala
index d4ab971..c65bb77 100644
--- a/docs/examples/actors/boundedbuffer.scala
+++ b/docs/examples/actors/boundedbuffer.scala
@@ -3,7 +3,7 @@ package examples.actors
 import scala.actors.Actor._
 
 object boundedbuffer {
-  class BoundedBuffer[T](N: Int) {
+  class BoundedBuffer[T](N: Int)(implicit m: Manifest[T]) {
     private case class Put(x: T)
     private case object Get
     private case object Stop
diff --git a/docs/examples/actors/message.scala b/docs/examples/actors/message.scala
index 9158fef..d385543 100644
--- a/docs/examples/actors/message.scala
+++ b/docs/examples/actors/message.scala
@@ -1,7 +1,8 @@
 package examples.actors
 
-import scala.actors._
+import scala.actors.{Actor, Scheduler}
 import scala.actors.Actor._
+import scala.actors.scheduler.SingleThreadedScheduler
 
 object message {
   def main(args: Array[String]) {
@@ -33,5 +34,7 @@ object message {
 
     val firstActor = actorChain(nActors, null)
     var i = n; while (i > 0) { firstActor ! 0; i -= 1 }
+
+    Scheduler.shutdown()
   }
 }
diff --git a/docs/examples/fors.scala b/docs/examples/fors.scala
index b840de5..b937e53 100644
--- a/docs/examples/fors.scala
+++ b/docs/examples/fors.scala
@@ -13,7 +13,7 @@ object fors {
   }
 
   def printOlderThan20(xs: Seq[Person]): Iterator[String] =
-    printOlderThan20(xs.elements)
+    printOlderThan20(xs.iterator)
 
   def printOlderThan20(xs: Iterator[Person]): Iterator[String] =
     for (p <- xs if p.age > 20) yield p.name
diff --git a/docs/examples/jolib/Ref.scala b/docs/examples/jolib/Ref.scala
index 0a57db2..5f655f1 100644
--- a/docs/examples/jolib/Ref.scala
+++ b/docs/examples/jolib/Ref.scala
@@ -4,7 +4,6 @@
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
-** $Id: Ref.scala 5359 2005-12-16 15:33:49Z dubochet $
 \*                                                                      */
 
 package examples.jolib;
diff --git a/docs/examples/jolib/parallelOr.scala b/docs/examples/jolib/parallelOr.scala
index 53d019d..72d282b 100644
--- a/docs/examples/jolib/parallelOr.scala
+++ b/docs/examples/jolib/parallelOr.scala
@@ -4,7 +4,6 @@
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
-** $Id: parallelOr.scala 5359 2005-12-16 15:33:49Z dubochet $
 \*                                                                  */
 
 package examples.jolib;
diff --git a/docs/examples/monads/callccInterpreter.scala b/docs/examples/monads/callccInterpreter.scala
index 781535f..5b556bd 100644
--- a/docs/examples/monads/callccInterpreter.scala
+++ b/docs/examples/monads/callccInterpreter.scala
@@ -21,7 +21,7 @@ object callccInterpreter {
 
   trait Term;
   case class Var(x: Name) extends Term;
-  case class Con(n: int) extends Term;
+  case class Con(n: Int) extends Term;
   case class Add(l: Term, r: Term) extends Term;
   case class Lam(x: Name, body: Term) extends Term;
   case class App(fun: Term, arg: Term) extends Term;
@@ -31,7 +31,7 @@ object callccInterpreter {
   case object Wrong extends Value {
    override def toString() = "wrong"
   } 
-  case class Num(n: int) extends Value {
+  case class Num(n: Int) extends Value {
     override def toString() = n.toString();
   }
   case class Fun(f: Value => M[Value]) extends Value {
diff --git a/docs/examples/monads/directInterpreter.scala b/docs/examples/monads/directInterpreter.scala
index 224b19b..06fffba 100644
--- a/docs/examples/monads/directInterpreter.scala
+++ b/docs/examples/monads/directInterpreter.scala
@@ -4,14 +4,14 @@ object directInterpreter {
 
   trait Term;
   case class Var(x: Name) extends Term;
-  case class Con(n: int) extends Term;
+  case class Con(n: Int) extends Term;
   case class Add(l: Term, r: Term) extends Term;
   case class Lam(x: Name, body: Term) extends Term;
   case class App(fun: Term, arg: Term) extends Term;
 
   trait Value;
   case object Wrong extends Value;
-  case class Num(n: int) extends Value;
+  case class Num(n: Int) extends Value;
   case class Fun(f: Value => Value)extends Value;
 
   def showval(v: Value): String = v match {
diff --git a/docs/examples/monads/errorInterpreter.scala b/docs/examples/monads/errorInterpreter.scala
index 536b7a1..d3cc456 100644
--- a/docs/examples/monads/errorInterpreter.scala
+++ b/docs/examples/monads/errorInterpreter.scala
@@ -25,7 +25,7 @@ object errorInterpreter {
 
   trait Term
   case class Var(x: Name) extends Term
-  case class Con(n: int) extends Term
+  case class Con(n: Int) extends Term
   case class Add(l: Term, r: Term) extends Term
   case class Lam(x: Name, body: Term) extends Term
   case class App(fun: Term, arg: Term) extends Term
@@ -34,7 +34,7 @@ object errorInterpreter {
   case object Wrong extends Value {
     override def toString() = "wrong"
   }
-  case class Num(n: int) extends Value {
+  case class Num(n: Int) extends Value {
     override def toString() = n.toString()
   }
   case class Fun(f: Value => M[Value]) extends Value {
diff --git a/docs/examples/monads/simpleInterpreter.scala b/docs/examples/monads/simpleInterpreter.scala
index b168b25..cde3a92 100644
--- a/docs/examples/monads/simpleInterpreter.scala
+++ b/docs/examples/monads/simpleInterpreter.scala
@@ -14,7 +14,7 @@ object simpleInterpreter {
 
   trait Term;
   case class Var(x: Name) extends Term;
-  case class Con(n: int) extends Term;
+  case class Con(n: Int) extends Term;
   case class Add(l: Term, r: Term) extends Term;
   case class Lam(x: Name, body: Term) extends Term;
   case class App(fun: Term, arg: Term) extends Term;
@@ -23,7 +23,7 @@ object simpleInterpreter {
   case object Wrong extends Value {
    override def toString() = "wrong"
   } 
-  case class Num(n: int) extends Value {
+  case class Num(n: Int) extends Value {
     override def toString() = n.toString();
   }
   case class Fun(f: Value => M[Value]) extends Value {
diff --git a/docs/examples/monads/stateInterpreter.scala b/docs/examples/monads/stateInterpreter.scala
index ace37b9..97f3335 100644
--- a/docs/examples/monads/stateInterpreter.scala
+++ b/docs/examples/monads/stateInterpreter.scala
@@ -2,7 +2,7 @@ package examples.monads;
 
 object stateInterpreter {
 
-  type State = int;
+  type State = Int;
 
   val tickS = new M(s => Pair((), s + 1));
 
@@ -25,7 +25,7 @@ object stateInterpreter {
 
   trait Term;
   case class Var(x: Name) extends Term;
-  case class Con(n: int) extends Term;
+  case class Con(n: Int) extends Term;
   case class Add(l: Term, r: Term) extends Term;
   case class Lam(x: Name, body: Term) extends Term;
   case class App(fun: Term, arg: Term) extends Term;
@@ -34,7 +34,7 @@ object stateInterpreter {
   case object Wrong extends Value {
    override def toString() = "wrong"
   }
-  case class Num(n: int) extends Value {
+  case class Num(n: Int) extends Value {
     override def toString() = n.toString();
   }
   case class Fun(f: Value => M[Value]) extends Value {
diff --git a/docs/examples/parsing/ArithmeticParser.scala b/docs/examples/parsing/ArithmeticParser.scala
index 2d4ab0d..cbd8493 100644
--- a/docs/examples/parsing/ArithmeticParser.scala
+++ b/docs/examples/parsing/ArithmeticParser.scala
@@ -1,6 +1,6 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2006-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
@@ -54,4 +54,4 @@ object arithmeticParserDesugared extends StdTokenParsers {
         "usage: scala examples.parsing.arithmeticParser <expr-string>"
     )
   }
-}
\ No newline at end of file
+}
diff --git a/docs/examples/parsing/lambda/TestParser.scala b/docs/examples/parsing/lambda/TestParser.scala
index c87cede..d26589d 100644
--- a/docs/examples/parsing/lambda/TestParser.scala
+++ b/docs/examples/parsing/lambda/TestParser.scala
@@ -20,7 +20,7 @@ trait TestParser extends StdTokenParsers  with ImplicitConversions with TestSynt
   
 	def name : Parser[Name] = ident ^^ Name
   
-  // meaning of the argumens to the closure during subsequent iterations
+  // meaning of the arguments to the closure during subsequent iterations
   // (...(expr2 op1 expr1) ... op1 expr1)
   //      ^a^^^ ^o^ ^b^^^
   //      ^^^^^^^a^^^^^^^      ^o^ ^^b^^
diff --git a/docs/examples/patterns.scala b/docs/examples/patterns.scala
index 208b216..738deab 100644
--- a/docs/examples/patterns.scala
+++ b/docs/examples/patterns.scala
@@ -24,7 +24,7 @@ object patterns {
   }
 
   def printFinds[a](xs: List[Pair[a, String]], x: a) =
-    find(xs.elements, x) match {
+    find(xs.iterator, x) match {
       case Some(y) => System.out.println(y)
       case None => System.out.println("no match")
     }
diff --git a/docs/examples/pilib/elasticBuffer.scala b/docs/examples/pilib/elasticBuffer.scala
index 26a6103..5fec96a 100644
--- a/docs/examples/pilib/elasticBuffer.scala
+++ b/docs/examples/pilib/elasticBuffer.scala
@@ -64,7 +64,7 @@ object elasticBuffer {
   def Consumer(get: Chan[String]): Unit = {
     Thread.sleep(1 + random.nextInt(1000))
     val msg = get.read
-    System.out.println("Consummer took " + msg)
+    System.out.println("Consumer took " + msg)
     Consumer(get)
   }
 
diff --git a/docs/examples/pilib/mobilePhoneProtocol.scala b/docs/examples/pilib/mobilePhoneProtocol.scala
index fd83c5c..e8c0ac1 100644
--- a/docs/examples/pilib/mobilePhoneProtocol.scala
+++ b/docs/examples/pilib/mobilePhoneProtocol.scala
@@ -158,7 +158,7 @@ object mobilePhoneProtocol {
     def Consumer(get: Chan[String]): unit = {
       Thread.sleep(1 + random.nextInt(1000));
       val msg = get.read;
-      System.out.println("Consummer took " + msg);
+      System.out.println("Consumer took " + msg);
       Consumer(get)
     }
     
diff --git a/docs/examples/pilib/piNat.scala b/docs/examples/pilib/piNat.scala
index 292e996..a1a0e68 100644
--- a/docs/examples/pilib/piNat.scala
+++ b/docs/examples/pilib/piNat.scala
@@ -1,38 +1,37 @@
 package examples.pilib
 
 import scala.concurrent.pilib._
-//import pilib._;
 
 /** Church encoding of naturals in the Pi-calculus */
 object piNat extends Application {
  
   /** Locations of Pi-calculus natural */
-  class NatChan extends Chan[Triple[Chan[unit], Chan[NatChan], Chan[NatChan]]]
+  class NatChan extends Chan[Triple[Chan[Unit], Chan[NatChan], Chan[NatChan]]]
 
   /** Zero */
-  def Z(l: NatChan): unit = choice (
+  def Z(l: NatChan): Unit = choice (
     l * { case Triple(z, sd, d) => z.write(()) }
   )
 
   /** Successor of Double */
-  def SD(n: NatChan, l: NatChan): unit = choice (
+  def SD(n: NatChan, l: NatChan): Unit = choice (
     l * { case Triple(z, sd, d) => sd.write(n) }
   )
 
   /** Double */
-  def D(n: NatChan, l: NatChan): unit = choice (
+  def D(n: NatChan, l: NatChan): Unit = choice (
     l * { case Triple(z, sd, d) => d.write(n) }
   )
 
   /** Make "l" a location representing the natural "n" */
-  def make(n: int, l: NatChan): unit =
+  def make(n: Int, l: NatChan): Unit =
     if (n == 0) Z(l)
     else if (n % 2 == 0) { val l1 = new NatChan; spawn < D(l1, l) >; make(n/2, l1) }
     else { val l1 = new NatChan; spawn < SD(l1, l) >; make(n/2, l1) }
 
   /** Consume the natural "m" and put it successor at location "n" */
-  def Succ(m: NatChan, n: NatChan): unit = {
-    val z = new Chan[unit]
+  def Succ(m: NatChan, n: NatChan) {
+    val z = new Chan[Unit]
     val sd = new Chan[NatChan]
     val d = new Chan[NatChan]
     spawn < m.write(Triple(z, sd, d)) >;
@@ -44,8 +43,8 @@ object piNat extends Application {
   }
 
   /** Consume the natural "l" and put two copies at locations "m" and "n" */
-  def Copy(l: NatChan, m: NatChan, n: NatChan): unit = {
-    val z = new Chan[unit]
+  def Copy(l: NatChan, m: NatChan, n: NatChan) {
+    val z = new Chan[Unit]
     val sd = new Chan[NatChan]
     val d = new Chan[NatChan]
     spawn < l.write(Triple(z, sd, d)) >;
@@ -61,8 +60,8 @@ object piNat extends Application {
   }
 
   /** Consume the natural at location "n" and return its value */
-  def value(n: NatChan): int =  {
-    val z = new Chan[unit]
+  def value(n: NatChan): Int = {
+    val z = new Chan[Unit]
     val sd = new Chan[NatChan]
     val d = new Chan[NatChan]
     spawn < n.write(Triple(z, sd, d)) >;
@@ -84,7 +83,7 @@ object piNat extends Application {
   make(i, l) |
   Copy(l, l1, l2) |
   Succ(l2, l3) |
-  System.out.println("" + i + " = " + value(l1)) |
-  System.out.println("succ " + i + " = " + value(l3)) >
+  println("" + i + " = " + value(l1)) |
+  println("succ " + i + " = " + value(l3)) >
 
 }
diff --git a/docs/examples/pilib/scheduler.scala b/docs/examples/pilib/scheduler.scala
index dfaef73..fd8fd52 100644
--- a/docs/examples/pilib/scheduler.scala
+++ b/docs/examples/pilib/scheduler.scala
@@ -7,14 +7,14 @@ object scheduler {
   /**
    * Random number generator.
    */
-  val random = new java.util.Random()
+  val random = new util.Random()
 
   //***************** Scheduler ******************//
 
   /**
    * A cell of the scheduler whose attached agent is allowed to start.
    */
-  def A(a: Chan[unit], b: Chan[unit])(d: Chan[unit], c: Chan[unit]): unit = {
+  def A(a: Chan[Unit], b: Chan[Unit])(d: Chan[Unit], c: Chan[Unit]) {
     ///- ... complete here ...
     choice ( a * { x => C(a, b)(d, c) })
     ///+
@@ -23,7 +23,7 @@ object scheduler {
   /**
    * A cell of the scheduler in another intermediate state.
    */
-  def C(a: Chan[unit], b: Chan[unit])(d: Chan[unit], c: Chan[unit]): unit = {
+  def C(a: Chan[Unit], b: Chan[Unit])(d: Chan[Unit], c: Chan[Unit]) {
     ///- ... complete here ...
     choice (c * { x => B(a, b)(d, c) })
     ///+
@@ -32,7 +32,7 @@ object scheduler {
   /**
    * A cell of the scheduler whose attached agent is allowed to finish.
    */
-  def B(a: Chan[unit], b: Chan[unit])(d: Chan[unit], c: Chan[unit]): unit = {
+  def B(a: Chan[Unit], b: Chan[Unit])(d: Chan[Unit], c: Chan[Unit]) {
     ///- ... complete here ...
     //     choice (b * { x => D(a, b)(d, c) }) // incorrect naive solution
     choice (
@@ -45,7 +45,7 @@ object scheduler {
   /**
    * A cell of the scheduler whose attached agent is not yet allowed to start.
    */
-  def D(a: Chan[unit], b: Chan[unit])(d: Chan[unit], c: Chan[unit]): unit = {
+  def D(a: Chan[Unit], b: Chan[Unit])(d: Chan[Unit], c: Chan[Unit]) {
     ///- ... complete here ...
     choice (d(()) * A(a, b)(d, c))
     ///+
@@ -53,16 +53,16 @@ object scheduler {
 
   //***************** Agents ******************//
 
-  def agent(i: Int)(a: Chan[unit], b: Chan[unit]): unit = {
+  def agent(i: Int)(a: Chan[Unit], b: Chan[Unit]) {
     // 50% chance that we sleep forever
     if (i == 0 && random.nextInt(10) < 5) {
-      a.attach(x => System.out.println("Start and sleeps ----> " + i))
+      a.attach(x => println("Start and sleeps ----> " + i))
       Thread.sleep(random.nextInt(1000))
       a.write(())
     }
     else {
-      a.attach(x => System.out.println("Start ----> " + i))
-      b.attach(x => System.out.println("Stop -> " + i))
+      a.attach(x => println("Start ----> " + i))
+      b.attach(x => println("Stop -> " + i))
       Thread.sleep(random.nextInt(1000))
       a.write(())
       Thread.sleep(random.nextInt(1000))
@@ -77,7 +77,7 @@ object scheduler {
    * Creates a scheduler for five agents (programs).
    */
 
-  def main(args: Array[String]): unit = {
+  def main(args: Array[String]) {
     val agentNb = 5
     val agents = List.range(0, agentNb) map agent
     scheduleAgents(agents)
@@ -89,22 +89,22 @@ object scheduler {
    * A cell is modelled as a function that takes as parameters
    * input and output channels and which returns nothing.  
    */
-  type Cell = (Chan[unit], Chan[unit]) => unit
+  type Cell = (Chan[Unit], Chan[Unit]) => Unit
 
   /**
    * Creates a cell composed of two cells linked together.
    */
   def join(cell1: Cell, cell2: Cell): Cell =
-    (l: Chan[unit], r: Chan[unit]) => {
-      val link = new Chan[unit];
+    (l: Chan[Unit], r: Chan[Unit]) => {
+      val link = new Chan[Unit];
       spawn < cell1(l, link) | cell2(link, r) >
     };
 
   /**
    * Links the output of a cell to its input.
    */
-  def close(cell: Cell): unit = {
-    val a = new Chan[unit]
+  def close(cell: Cell) {
+    val a = new Chan[Unit]
     cell(a, a)
   }
 
@@ -117,25 +117,25 @@ object scheduler {
   /**
    * Creates a cell consisting of a chain of cells.
    */
-  def makeRing(cells: List[Cell]): unit =
+  def makeRing(cells: List[Cell]): Unit =
     close(chain(cells))
 
   /**
    * An agent is modelled as a function that takes as parameters channels to
    * signal that it has started or finished.
    */
-  type Agent = (Chan[unit], Chan[unit]) => unit
+  type Agent = (Chan[Unit], Chan[Unit]) => Unit
 
   /**
    * Takes a list of agents and schedules them.
    */
-  def scheduleAgents(agents: List[Agent]): unit = {
+  def scheduleAgents(agents: List[Agent]) {
     var firstAgent = true;
     val cells = agents map (ag => {
-      val a = new Chan[unit];
-      val b = new Chan[unit];
+      val a = new Chan[Unit];
+      val b = new Chan[Unit];
       spawn < ag(a, b) >;
-      (d: Chan[unit], c: Chan[unit]) => if (firstAgent) {
+      (d: Chan[Unit], c: Chan[Unit]) => if (firstAgent) {
         firstAgent = false;
         A(a, b)(d, c)
       }
diff --git a/docs/examples/pilib/semaphore.scala b/docs/examples/pilib/semaphore.scala
index e4e3dbe..951c90e 100644
--- a/docs/examples/pilib/semaphore.scala
+++ b/docs/examples/pilib/semaphore.scala
@@ -1,19 +1,19 @@
 package examples.pilib
 
+import scala.concurrent.pilib._
+
 /** Solution of exercise session 6 (first question). */
 object semaphore {
 
-  import scala.concurrent.pilib._
-
-  class Signal extends Chan[unit] {
+  class Signal extends Chan[Unit] {
     def send = write(())
     def receive = read
   }
 
   /** Interface. */
   trait Semaphore {
-    def get: unit
-    def release: unit
+    def get: Unit
+    def release: Unit
   }
 
   /** First implementation. */
@@ -22,10 +22,10 @@ object semaphore {
     private val g = new Signal
     private val r = new Signal
 
-    def get: unit = g.send
-    def release: unit = r.send
+    def get: Unit = g.send
+    def release: Unit = r.send
 
-    private def Sched: unit = choice (
+    private def Sched: Unit = choice (
       g * (x => { r.receive; Sched }),
       r * (x => Sched)
     )
@@ -38,8 +38,8 @@ object semaphore {
     private val a = new Signal
     private val na = new Signal
 
-    def get: unit = { a.receive; spawn< na.send > }
-    def release: unit = choice (
+    def get { a.receive; spawn< na.send > }
+    def release: Unit = choice (
       a * (x => spawn< a.send >),
       na * (x => spawn< a.send >)
     )
@@ -47,24 +47,24 @@ object semaphore {
   }
 
   /** Test program. */
-  def main(args: Array[String]): unit = {
-    val random = new java.util.Random()
+  def main(args: Array[String]) {
+    val random = new util.Random()
     val sem = new Sem2
-    def mutex(p: => unit): unit = { sem.get; p; sem.release }
+    def mutex(p: => Unit) { sem.get; p; sem.release }
 
     spawn< {
       Thread.sleep(1 + random.nextInt(100));
       mutex( {
-        System.out.println("a1");
+        println("a1");
         Thread.sleep(1 + random.nextInt(100));
-        System.out.println("a2")
+        println("a2")
       } )
     } | {
       Thread.sleep(1 + random.nextInt(100));
       mutex( {
-        System.out.println("b1");
+        println("b1");
         Thread.sleep(1 + random.nextInt(100));
-        System.out.println("b2")
+        println("b2")
       } ) 
     } >;
   }
diff --git a/docs/examples/pilib/twoPlaceBuffer.scala b/docs/examples/pilib/twoPlaceBuffer.scala
index d690619..255f70c 100644
--- a/docs/examples/pilib/twoPlaceBuffer.scala
+++ b/docs/examples/pilib/twoPlaceBuffer.scala
@@ -8,18 +8,18 @@ object twoPlaceBuffer extends Application {
   /**
    * Specification.
    */
-  def Spec[a](in: Chan[a], out: Chan[a]): Unit = {
+  def Spec[A](in: Chan[A], out: Chan[A]) {
 
-    def B0: unit = choice (
+    def B0: Unit = choice (
       in * (x => B1(x))
     )
 
-    def B1(x: a): unit = choice (
+    def B1(x: A): Unit = choice (
       out(x) * (B0),
       in * (y => B2(x, y)) 
     )
 
-    def B2(x: a, y: a): unit = choice (
+    def B2(x: A, y: A): Unit = choice (
       out(x) * (B1(y))
     )
 
@@ -29,38 +29,38 @@ object twoPlaceBuffer extends Application {
   /**
    * Implementation using two one-place buffers.
    */
-  def Impl[a](in: Chan[a], out: Chan[a]): unit =  {
+  def Impl[A](in: Chan[A], out: Chan[A]) {
     ///- ... complete here ...
     // one-place buffer
-    def OnePlaceBuffer[a](in: Chan[a], out: Chan[a]): Unit = {
-      def B0: unit = choice ( in * (x => B1(x)) )
-      def B1(x: a): unit = choice ( out(x) * (B0))
+    def OnePlaceBuffer[A](in: Chan[A], out: Chan[A]) {
+      def B0: Unit = choice ( in * (x => B1(x)) )
+      def B1(x: A): Unit = choice ( out(x) * (B0))
       B0
     }
-    val hidden = new Chan[a]
+    val hidden = new Chan[A]
     spawn < OnePlaceBuffer(in, hidden) | OnePlaceBuffer(hidden, out) >
     ///+
   }
 
-  val random = new java.util.Random()
+  val random = new util.Random()
 
-  def Producer(n: Int, in: Chan[String]): Unit = {
+  def Producer(n: Int, in: Chan[String]) {
     Thread.sleep(random.nextInt(1000))
     val msg = "" + n
     choice (in(msg) * {})
     Producer(n + 1, in)
   }
 
-  def Consumer(out: Chan[String]): unit = {
-    Thread.sleep(random.nextInt(1000));
-    choice (out * { msg => () });
+  def Consumer(out: Chan[String]) {
+    Thread.sleep(random.nextInt(1000))
+    choice (out * { msg => () })
     Consumer(out)
   }
 
   val in = new Chan[String]
-  in.attach(s => System.out.println("put " + s))
+  in.attach(s => println("put " + s))
   val out = new Chan[String]
-  out.attach(s => System.out.println("get " + s))
+  out.attach(s => println("get " + s))
   //spawn < Producer(0, in) | Consumer(out) | Spec(in, out) >
   spawn < Producer(0, in) | Consumer(out) | Impl(in, out) >
 
diff --git a/docs/examples/plugintemplate/lib/scalatest.jar b/docs/examples/plugintemplate/lib/scalatest.jar
index dd3e79c..bfcd450 100644
Binary files a/docs/examples/plugintemplate/lib/scalatest.jar and b/docs/examples/plugintemplate/lib/scalatest.jar differ
diff --git a/docs/examples/plugintemplate/plugin.properties b/docs/examples/plugintemplate/plugin.properties
index 44e4900..131f961 100644
--- a/docs/examples/plugintemplate/plugin.properties
+++ b/docs/examples/plugintemplate/plugin.properties
@@ -1,4 +1,4 @@
-scala.home=/Users/luc/scala/trunk/build/pack
+scala.home=../../../build/pack
 
 plugin.name=plugintemplate
 plugin.commandname=runplugintemplate
diff --git a/docs/examples/plugintemplate/src/plugintemplate/PluginProperties.scala b/docs/examples/plugintemplate/src/plugintemplate/PluginProperties.scala
index e9c2050..ed078a0 100644
--- a/docs/examples/plugintemplate/src/plugintemplate/PluginProperties.scala
+++ b/docs/examples/plugintemplate/src/plugintemplate/PluginProperties.scala
@@ -58,4 +58,4 @@ object PluginProperties {
       Some(p)
     }
   }
-}
\ No newline at end of file
+}
diff --git a/docs/examples/plugintemplate/src/plugintemplate/TemplateComponent.scala b/docs/examples/plugintemplate/src/plugintemplate/TemplateComponent.scala
index d740395..b63f320 100644
--- a/docs/examples/plugintemplate/src/plugintemplate/TemplateComponent.scala
+++ b/docs/examples/plugintemplate/src/plugintemplate/TemplateComponent.scala
@@ -14,7 +14,7 @@ import scala.tools.nsc.plugins.PluginComponent
 class TemplateComponent(val global: Global) extends PluginComponent {
   import global._
 
-  val runsAfter = "refchecks"
+  val runsAfter = List[String]("refchecks")
 
   /** The name of this plugin phase
    *  @todo Adapt to specific plugin.
diff --git a/docs/examples/plugintemplate/src/plugintemplate/TemplateInfoTransformComponent.scala b/docs/examples/plugintemplate/src/plugintemplate/TemplateInfoTransformComponent.scala
index 60f56ba..71069ae 100644
--- a/docs/examples/plugintemplate/src/plugintemplate/TemplateInfoTransformComponent.scala
+++ b/docs/examples/plugintemplate/src/plugintemplate/TemplateInfoTransformComponent.scala
@@ -22,7 +22,7 @@ class TemplateInfoTransformComponent(val global: Global) extends PluginComponent
   import global._
   import global.definitions._
 
-  val runsAfter = "refchecks"
+  val runsAfter = List[String]("refchecks")
   /** The phase name of the compiler plugin
    *  @todo Adapt to specific plugin.
    */
diff --git a/docs/examples/plugintemplate/src/plugintemplate/TemplatePlugin.scala b/docs/examples/plugintemplate/src/plugintemplate/TemplatePlugin.scala
index d92a457..6cda37d 100644
--- a/docs/examples/plugintemplate/src/plugintemplate/TemplatePlugin.scala
+++ b/docs/examples/plugintemplate/src/plugintemplate/TemplatePlugin.scala
@@ -12,7 +12,7 @@ class TemplatePlugin(val global: Global) extends Plugin {
   /** The name of this plugin. Extracted from the properties file. */
   val name = PluginProperties.pluginName
 
-  val runsAfter = "refchecks"
+  val runsAfter = List[String]("refchecks")
 
   /** A short description of the plugin, read from the properties file */
   val description = PluginProperties.pluginDescription
diff --git a/docs/examples/plugintemplate/src/plugintemplate/TemplateTransformComponent.scala b/docs/examples/plugintemplate/src/plugintemplate/TemplateTransformComponent.scala
index 06afeda..7c2630d 100644
--- a/docs/examples/plugintemplate/src/plugintemplate/TemplateTransformComponent.scala
+++ b/docs/examples/plugintemplate/src/plugintemplate/TemplateTransformComponent.scala
@@ -19,7 +19,7 @@ class TemplateTransformComponent(val global: Global) extends PluginComponent
   import global._
   import global.definitions._
 
-  val runsAfter = "refchecks"
+  val runsAfter = List[String]("refchecks")
   /** The phase name of the compiler plugin
    *  @todo Adapt to specific plugin.
    */
diff --git a/docs/examples/plugintemplate/src/plugintemplate/TemplateTraverseComponent.scala b/docs/examples/plugintemplate/src/plugintemplate/TemplateTraverseComponent.scala
index e87d4d1..400daf7 100644
--- a/docs/examples/plugintemplate/src/plugintemplate/TemplateTraverseComponent.scala
+++ b/docs/examples/plugintemplate/src/plugintemplate/TemplateTraverseComponent.scala
@@ -9,7 +9,7 @@ class TemplateTraverseComponent (val global: Global) extends PluginComponent {
   import global._
   import global.definitions._
 
-  val runsAfter = "refchecks"
+  val runsAfter = List[String]("refchecks")
   /** The phase name of the compiler plugin
    *  @todo Adapt to specific plugin.
    */
diff --git a/docs/examples/plugintemplate/src/plugintemplate/standalone/Main.scala b/docs/examples/plugintemplate/src/plugintemplate/standalone/Main.scala
index eadada5..19d2613 100644
--- a/docs/examples/plugintemplate/src/plugintemplate/standalone/Main.scala
+++ b/docs/examples/plugintemplate/src/plugintemplate/standalone/Main.scala
@@ -1,5 +1,6 @@
 package plugintemplate.standalone
 
+import plugintemplate.PluginProperties
 import scala.tools.nsc.CompilerCommand
 import scala.tools.nsc.Settings
 
@@ -14,9 +15,9 @@ object Main {
   def main(args: Array[String]) {
     val settings = new Settings
 
-    val command = new CompilerCommand(args.toList, settings, println, false) {
+    val command = new CompilerCommand(args.toList, settings) {
       /** The command name that will be printed in in the usage message.
-       *  This is autmatically set to the value of 'plugin.commandname' in the
+       *  This is automatically set to the value of 'plugin.commandname' in the
        *  file build.properties.
        */
       override val cmdName = PluginProperties.pluginCommand
@@ -25,7 +26,7 @@ object Main {
     if (!command.ok)
       return()
 
-    /** The version number of this plugin is read from the porperties file
+    /** The version number of this plugin is read from the properties file
      */
     if (settings.version.value) {
       println(command.cmdName +" version "+ PluginProperties.versionString)
diff --git a/docs/examples/plugintemplate/src/plugintemplate/standalone/PluginRunner.scala b/docs/examples/plugintemplate/src/plugintemplate/standalone/PluginRunner.scala
index 16b6ce2..786d72d 100644
--- a/docs/examples/plugintemplate/src/plugintemplate/standalone/PluginRunner.scala
+++ b/docs/examples/plugintemplate/src/plugintemplate/standalone/PluginRunner.scala
@@ -1,5 +1,6 @@
 package plugintemplate.standalone
 
+import plugintemplate.{TemplateAnnotationChecker, TemplatePlugin}
 import scala.tools.nsc.{Global, Settings, SubComponent}
 import scala.tools.nsc.reporters.{ConsoleReporter, Reporter}
 
@@ -11,7 +12,7 @@ extends Global(settings, reporter) {
   def this(settings: Settings) = this(settings, new ConsoleReporter(settings))
 
   val annotChecker = new TemplateAnnotationChecker {
-      val global: PluginRunner.this.type = PluginRunner.this
+    val global: PluginRunner.this.type = PluginRunner.this
   }
   addAnnotationChecker(annotChecker.checker)
 
@@ -19,10 +20,17 @@ extends Global(settings, reporter) {
    *
    *  @todo: Adapt to specific plugin implementation
    */
-  override def phaseDescriptors: List[SubComponent] = List(
-    analyzer.namerFactory,
-    analyzer.typerFactory,
-    superAccessors,
-    pickler,
-    refchecks) ::: TemplatePlugin.components(this)
+  override protected def computeInternalPhases() {
+    phasesSet += syntaxAnalyzer
+    phasesSet += analyzer.namerFactory
+    phasesSet += analyzer.typerFactory
+    phasesSet += superAccessors			       // add super accessors
+    phasesSet += pickler			       // serialize symbol tables
+    phasesSet += refchecks			       // perform reference and override checking, translate nested objects
+
+    for (phase <- TemplatePlugin.components(this)) {
+      phasesSet += phase
+    }
+  }
+
 }
diff --git a/docs/examples/tcpoly/collection/HOSeq.scala b/docs/examples/tcpoly/collection/HOSeq.scala
index 83332d0..a6757b9 100644
--- a/docs/examples/tcpoly/collection/HOSeq.scala
+++ b/docs/examples/tcpoly/collection/HOSeq.scala
@@ -16,7 +16,7 @@ trait HOSeq {
   //           is an invariant position -- should probably rule that out?
   trait Iterable[+m[+x], +t] {
     //def unit[a](orig: a): m[a]
-    def elements: Iterator[t]
+    def iterator: Iterator[t]
     
     // construct an empty accumulator that will produce the same structure as this iterable, with elements of type t
     def accumulator[t]: Accumulator[m, t]
@@ -44,7 +44,7 @@ trait HOSeq {
         // -- 2nd-order type params are not yet in scope in view bound
       val elems = elements
       while (elems.hasNext) {
-        val elemss: Iterator[s] = f(elems.next).elements
+        val elemss: Iterator[s] = f(elems.next).iterator
         while (elemss.hasNext) buf += elemss.next
       }
       buf.result
@@ -108,7 +108,7 @@ trait HOSeq {
           def head: t
           def tail: List[t]
           def isEmpty: Boolean
-          def elements: Iterator[t] = error("TODO")
+          def iterator: Iterator[t] = error("TODO")
 
           // construct an empty accumulator that will produce the same structure as this iterable, with elements of type t
           def accumulator[t]: Accumulator[List, t] = error("TODO")         
@@ -164,4 +164,4 @@ trait HOSeq {
   // @pre hasNext
   // @post hasAdvanced
   def advance: Unit
-}*/
\ No newline at end of file
+}*/
diff --git a/docs/examples/tcpoly/monads/Monads.scala b/docs/examples/tcpoly/monads/Monads.scala
index 249f34a..b6e3d5b 100644
--- a/docs/examples/tcpoly/monads/Monads.scala
+++ b/docs/examples/tcpoly/monads/Monads.scala
@@ -66,4 +66,4 @@ class SomeIsMonad[a] extends OptionIsMonad[Some, a] {
 class NoneIsMonad[a] extends OptionIsMonad[None, a] {
   def >>=[b](fun: a => Option[b]): Option[b] = None
 }
-*/
\ No newline at end of file
+*/
diff --git a/docs/examples/xml/phonebook/phonebook3.scala b/docs/examples/xml/phonebook/phonebook3.scala
index 8fcf24e..12f2dea 100644
--- a/docs/examples/xml/phonebook/phonebook3.scala
+++ b/docs/examples/xml/phonebook/phonebook3.scala
@@ -25,7 +25,7 @@ object phonebook3 {
           case x @ <entry><name>{ Text(Name) }</name>{ ch1 @ _* }</entry> => 
 
             var updated = false;
-            val ch2 = for(val c <- ch1) yield c match { // does it have the phone number?
+            val ch2 = for(c <- ch1) yield c match { // does it have the phone number?
 
               case y @ <phone>{ _* }</phone> if y \ "@where" == Where => 
                 updated = true
@@ -62,7 +62,7 @@ object phonebook3 {
     // decompose phonebook, apply updates
     phonebook match {
       case <phonebook>{ ch @ _* }</phonebook> =>
-        <phonebook>{ copyOrChange( ch.elements ) }</phonebook>
+        <phonebook>{ copyOrChange( ch.iterator ) }</phonebook>
     }
     
   }
diff --git a/docs/licenses/apache_android.txt b/docs/licenses/apache_android.txt
new file mode 100644
index 0000000..00f3396
--- /dev/null
+++ b/docs/licenses/apache_android.txt
@@ -0,0 +1,16 @@
+Scala includes various example files for Android:
+
+Copyright (c) 2005-2009, The Android Open Source Project
+Copyright (c) 2007, Steven Osborn
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+     http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
\ No newline at end of file
diff --git a/docs/licenses/apache_ant.txt b/docs/licenses/apache_ant.txt
new file mode 100644
index 0000000..ac637d7
--- /dev/null
+++ b/docs/licenses/apache_ant.txt
@@ -0,0 +1,16 @@
+Scala includes Ant as a library needed for build with sbt
+
+Copyright © 1999-2010, The Apache Software Foundation.
+     http://ant.apache.org/
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+     http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
diff --git a/docs/licenses/bsd_jline.txt b/docs/licenses/bsd_jline.txt
new file mode 100644
index 0000000..4ac4a37
--- /dev/null
+++ b/docs/licenses/bsd_jline.txt
@@ -0,0 +1,34 @@
+Scala includes the jLine library:
+
+Copyright (c) 2002-2006, Marc Prud'hommeaux <mwp1 at cornell.edu>
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or
+without modification, are permitted provided that the following
+conditions are met:
+
+Redistributions of source code must retain the above copyright
+notice, this list of conditions and the following disclaimer.
+
+Redistributions in binary form must reproduce the above copyright
+notice, this list of conditions and the following disclaimer
+in the documentation and/or other materials provided with
+the distribution.
+
+Neither the name of JLine nor the names of its contributors
+may be used to endorse or promote products derived from this
+software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
+BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
+EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
+OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
+AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
+IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/docs/licenses/mit_jquery.txt b/docs/licenses/mit_jquery.txt
new file mode 100644
index 0000000..ef2c570
--- /dev/null
+++ b/docs/licenses/mit_jquery.txt
@@ -0,0 +1,13 @@
+Scala includes the jQuery library:
+
+Copyright (c) 2010 John Resig
+
+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.
diff --git a/docs/licenses/mit_sizzle.txt b/docs/licenses/mit_sizzle.txt
new file mode 100644
index 0000000..d81d30a
--- /dev/null
+++ b/docs/licenses/mit_sizzle.txt
@@ -0,0 +1,13 @@
+Scala includes the Sizzle library:
+
+Copyright (c) 2010 The Dojo Foundation
+
+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.
diff --git a/docs/licenses/mit_tools.tooltip.txt b/docs/licenses/mit_tools.tooltip.txt
new file mode 100644
index 0000000..27a4dbc
--- /dev/null
+++ b/docs/licenses/mit_tools.tooltip.txt
@@ -0,0 +1,13 @@
+Scala includes the Tools Tooltip library:
+
+Copyright (c) 2009 Tero Piirainen
+
+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.
diff --git a/lib/ScalaCheck.jar b/lib/ScalaCheck.jar
deleted file mode 100644
index 4789417..0000000
Binary files a/lib/ScalaCheck.jar and /dev/null differ
diff --git a/lib/ScalaCheckHelper.jar b/lib/ScalaCheckHelper.jar
deleted file mode 100644
index ff2505f..0000000
Binary files a/lib/ScalaCheckHelper.jar and /dev/null differ
diff --git a/lib/ant/ant-contrib.jar b/lib/ant/ant-contrib.jar
deleted file mode 100644
index 0625376..0000000
Binary files a/lib/ant/ant-contrib.jar and /dev/null differ
diff --git a/lib/ant/ant-dotnet-1.0.jar b/lib/ant/ant-dotnet-1.0.jar
deleted file mode 100644
index 2d48db4..0000000
Binary files a/lib/ant/ant-dotnet-1.0.jar and /dev/null differ
diff --git a/lib/ant/maven-ant-tasks-2.0.9.jar b/lib/ant/maven-ant-tasks-2.0.9.jar
deleted file mode 100644
index 82a30e5..0000000
Binary files a/lib/ant/maven-ant-tasks-2.0.9.jar and /dev/null differ
diff --git a/lib/ant/vizant.jar b/lib/ant/vizant.jar
deleted file mode 100644
index 106fbf6..0000000
Binary files a/lib/ant/vizant.jar and /dev/null differ
diff --git a/lib/cldcapi10.jar b/lib/cldcapi10.jar
deleted file mode 100644
index 139d9a5..0000000
Binary files a/lib/cldcapi10.jar and /dev/null differ
diff --git a/lib/fjbg.jar b/lib/fjbg.jar
index 0b28038..c5b57e6 100644
Binary files a/lib/fjbg.jar and b/lib/fjbg.jar differ
diff --git a/lib/forkjoin.jar b/lib/forkjoin.jar
new file mode 100644
index 0000000..3830868
Binary files /dev/null and b/lib/forkjoin.jar differ
diff --git a/lib/jline.jar b/lib/jline.jar
index 87e12a8..6ed67fa 100644
Binary files a/lib/jline.jar and b/lib/jline.jar differ
diff --git a/lib/midpapi10.jar b/lib/midpapi10.jar
deleted file mode 100644
index d586a51..0000000
Binary files a/lib/midpapi10.jar and /dev/null differ
diff --git a/lib/msil.jar b/lib/msil.jar
index 2f4baa2..6fb6e00 100644
Binary files a/lib/msil.jar and b/lib/msil.jar differ
diff --git a/lib/scala-compiler.jar b/lib/scala-compiler.jar
index ad25f50..a64c09e 100644
Binary files a/lib/scala-compiler.jar and b/lib/scala-compiler.jar differ
diff --git a/lib/scala-library-src.jar b/lib/scala-library-src.jar
index d1a4ee7..bd02597 100644
Binary files a/lib/scala-library-src.jar and b/lib/scala-library-src.jar differ
diff --git a/lib/scala-library.jar b/lib/scala-library.jar
index 8e9087b..bd4367e 100644
Binary files a/lib/scala-library.jar and b/lib/scala-library.jar differ
diff --git a/src/actors/scala/actors/AbstractActor.scala b/src/actors/scala/actors/AbstractActor.scala
index 7eaa4a0..c25e785 100644
--- a/src/actors/scala/actors/AbstractActor.scala
+++ b/src/actors/scala/actors/AbstractActor.scala
@@ -1,24 +1,26 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2005-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2005-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id$
 
 package scala.actors
 
 /**
  * The <code>AbstractActor</code> trait.
  *
- * @version 0.9.18
  * @author Philipp Haller
+ *
+ * @define actor actor
  */
-trait AbstractActor extends OutputChannel[Any] {
+trait AbstractActor extends OutputChannel[Any] with CanReply[Any, Any] {
+
+  type Future[+R] = scala.actors.Future[R]
 
-  private[actors] var exiting = false
+  private[actors] def exiting: Boolean = false
 
   private[actors] def linkTo(to: AbstractActor): Unit
 
@@ -26,12 +28,4 @@ trait AbstractActor extends OutputChannel[Any] {
 
   private[actors] def exit(from: AbstractActor, reason: AnyRef): Unit
 
-  def !?(msg: Any): Any
-
-  def !?(msec: Long, msg: Any): Option[Any]
-
-  def !!(msg: Any): Future[Any]
-
-  def !![A](msg: Any, f: PartialFunction[Any, A]): Future[A]
-
 }
diff --git a/src/actors/scala/actors/Actor.scala b/src/actors/scala/actors/Actor.scala
index 2c49828..df05ce5 100644
--- a/src/actors/scala/actors/Actor.scala
+++ b/src/actors/scala/actors/Actor.scala
@@ -1,18 +1,15 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2005-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2005-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Actor.scala 18846 2009-10-01 07:30:14Z phaller $
 
 package scala.actors
 
-import scala.collection.mutable.{HashSet, Queue}
-import scala.compat.Platform
-
+import scala.util.control.ControlThrowable
 import java.util.{Timer, TimerTask}
 
 /**
@@ -21,16 +18,45 @@ import java.util.{Timer, TimerTask}
  * <code>receive</code>, <code>react</code>, <code>reply</code>,
  * etc.
  *
- * @version 0.9.18
  * @author Philipp Haller
  */
-object Actor {
-
-  private[actors] val tl = new ThreadLocal[Actor]
+object Actor extends Combinators {
+
+  /** An actor state. An actor can be in one of the following states:
+   *  <ul>
+   *    <li>New<br>
+   *      An actor that has not yet started is in this state.</li>
+   *    <li>Runnable<br>
+   *      An actor executing is in this state.</li>
+   *    <li>Suspended<br>
+   *      An actor that is suspended waiting in a react is in this state.</li>
+   *    <li>TimedSuspended<br>
+   *      An actor that is suspended waiting in a reactWithin is in this state.</li>
+   *    <li>Blocked<br>
+   *      An actor that is blocked waiting in a receive is in this state.</li>
+   *    <li>TimedBlocked<br>
+   *      An actor that is blocked waiting in a receiveWithin is in this state.</li>
+   *    <li>Terminated<br>
+   *      An actor that has terminated is in this state.</li>
+   *  </ul>
+   */
+  object State extends Enumeration {
+    val New,
+        Runnable,
+        Suspended,
+        TimedSuspended,
+        Blocked,
+        TimedBlocked,
+        Terminated = Value
+  }
+
+  private[actors] val tl = new ThreadLocal[ReplyReactor]
 
   // timer thread runs as daemon
   private[actors] val timer = new Timer(true)
 
+  private[actors] val suspendException = new SuspendActorControl
+
   /**
    * Returns the currently executing actor. Should be used instead
    * of <code>this</code> in all blocks of code executed by
@@ -38,13 +64,27 @@ object Actor {
    *
    * @return returns the currently executing actor.
    */
-  def self: Actor = {
-    var a = tl.get.asInstanceOf[Actor]
-    if (null eq a) {
-      a = new ActorProxy(currentThread)
-      tl.set(a)
-    }
-    a
+  def self: Actor = self(Scheduler)
+
+  private[actors] def self(sched: IScheduler): Actor =
+    rawSelf(sched).asInstanceOf[Actor]
+
+  private[actors] def rawSelf: ReplyReactor =
+    rawSelf(Scheduler)
+
+  private[actors] def rawSelf(sched: IScheduler): ReplyReactor = {
+    val s = tl.get
+    if (s eq null) {
+      val r = new ActorProxy(currentThread, sched)
+      tl.set(r)
+      r
+    } else
+      s
+  }
+
+  private def parentScheduler: IScheduler = {
+    val s = tl.get
+    if (s eq null) Scheduler else s.scheduler
   }
 
   /**
@@ -56,9 +96,9 @@ object Actor {
    * even if its <code>ActorProxy</code> has died for some reason.
    */
   def resetProxy {
-    val a = tl.get.asInstanceOf[Actor]
+    val a = tl.get
     if ((null ne a) && a.isInstanceOf[ActorProxy])
-      tl.set(new ActorProxy(currentThread))
+      tl.set(new ActorProxy(currentThread, parentScheduler))
   }
 
   /**
@@ -75,38 +115,37 @@ object Actor {
   }
 
   /**
-   * <p>This is a factory method for creating actors.</p>
+   * This is a factory method for creating actors.
    *
-   * <p>The following example demonstrates its usage:</p>
+   * The following example demonstrates its usage:
    *
-   * <pre>
+   * {{{
    * import scala.actors.Actor._
    * ...
    * val a = actor {
    *   ...
    * }
-   * </pre>
+   * }}}
    *
    * @param  body  the code block to be executed by the newly created actor
    * @return       the newly created actor. Note that it is automatically started.
    */
   def actor(body: => Unit): Actor = {
-    val actor = new Actor {
+    val a = new Actor {
       def act() = body
+      override final val scheduler: IScheduler = parentScheduler
     }
-    actor.start()
-    actor
+    a.start()
+    a
   }
 
   /**
-   * <p>
    * This is a factory method for creating actors whose
-   * body is defined using a <code>Responder</code>.
-   * </p>
+   * body is defined using a `Responder`.
    *
-   * <p>The following example demonstrates its usage:</p>
+   * The following example demonstrates its usage:
    *
-   * <pre>
+   * {{{
    * import scala.actors.Actor._
    * import Responder.exec
    * ...
@@ -116,9 +155,9 @@ object Actor {
    *     if exec(println("result: "+res))
    *   } yield {}
    * }
-   * </pre>
+   * }}}
    *
-   * @param  body  the <code>Responder</code> to be executed by the newly created actor
+   * @param  body  the `Responder` to be executed by the newly created actor
    * @return       the newly created actor. Note that it is automatically started.
    */
   def reactor(body: => Responder[Unit]): Actor = {
@@ -126,6 +165,7 @@ object Actor {
       def act() {
         Responder.run(body)
       }
+      override final val scheduler: IScheduler = parentScheduler
     }
     a.start()
     a
@@ -174,7 +214,7 @@ object Actor {
    * @return   this function never returns
    */
   def react(f: PartialFunction[Any, Unit]): Nothing =
-    self.react(f)
+    rawSelf.react(f)
 
   /**
    * Lightweight variant of <code>receiveWithin</code>.
@@ -191,57 +231,58 @@ object Actor {
     self.reactWithin(msec)(f)
 
   def eventloop(f: PartialFunction[Any, Unit]): Nothing =
-    self.react(new RecursiveProxyHandler(self, f))
+    rawSelf.react(new RecursiveProxyHandler(rawSelf, f))
 
-  private class RecursiveProxyHandler(a: Actor, f: PartialFunction[Any, Unit])
+  private class RecursiveProxyHandler(a: ReplyReactor, f: PartialFunction[Any, Unit])
           extends PartialFunction[Any, Unit] {
     def isDefinedAt(m: Any): Boolean =
       true // events are immediately removed from the mailbox
     def apply(m: Any) {
       if (f.isDefinedAt(m)) f(m)
-      self.react(this)
+      a.react(this)
     }
   }
 
   /**
    * Returns the actor which sent the last received message.
    */
-  def sender: OutputChannel[Any] = self.sender
+  def sender: OutputChannel[Any] =
+    rawSelf.sender
 
   /**
    * Send <code>msg</code> to the actor waiting in a call to
    * <code>!?</code>.
    */
-  def reply(msg: Any): Unit = self.reply(msg)
+  def reply(msg: Any): Unit =
+    rawSelf.reply(msg)
 
   /**
    * Send <code>()</code> to the actor waiting in a call to
    * <code>!?</code>.
    */
-  def reply(): Unit = self.reply(())
+  def reply(): Unit =
+    rawSelf.reply(())
 
   /**
    * Returns the number of messages in <code>self</code>'s mailbox
    *
    * @return the number of messages in <code>self</code>'s mailbox
    */
-  def mailboxSize: Int = self.mailboxSize
+  def mailboxSize: Int = rawSelf.mailboxSize
 
   /**
-   * <p>
    * Converts a synchronous event-based operation into
-   * an asynchronous <code>Responder</code>.
-   * </p>
+   * an asynchronous `Responder`.
    *
-   * <p>The following example demonstrates its usage:</p>
+   * The following example demonstrates its usage:
    * 
-   * <pre>
+   * {{{
    * val adder = reactor {
    *   for {
    *     _ <- respondOn(react) { case Add(a, b) => reply(a+b) }
    *   } yield {}
    * }
-   * </pre>
+   * }}}
    */
   def respondOn[A, B](fun: PartialFunction[A, Unit] => Nothing):
     PartialFunction[A, B] => Responder[B] =
@@ -254,42 +295,22 @@ object Actor {
   }
 
   implicit def mkBody[a](body: => a) = new Body[a] {
-    def andThen[b](other: => b): Unit = self.seq(body, other)
+    def andThen[b](other: => b): Unit = rawSelf.seq(body, other)
   }
 
   /**
-   * Causes <code>self</code> to repeatedly execute
-   * <code>body</code>.
-   *
-   * @param body the code block to be executed
-   */
-  def loop(body: => Unit): Unit = body andThen loop(body)
-
-  /**
-   * Causes <code>self</code> to repeatedly execute
-   * <code>body</code> while the condition
-   * <code>cond</code> is <code>true</code>.
-   *
-   * @param cond the condition to test
-   * @param body the code block to be executed
-   */
-  def loopWhile(cond: => Boolean)(body: => Unit): Unit =
-    if (cond) { body andThen loopWhile(cond)(body) }
-    else continue
-
-  /**
    * Links <code>self</code> to actor <code>to</code>.
    *
    * @param  to the actor to link to
-   * @return 
+   * @return    the parameter actor
    */
   def link(to: AbstractActor): AbstractActor = self.link(to)
 
   /**
-   * Links <code>self</code> to actor defined by <code>body</code>.
+   * Links <code>self</code> to the actor defined by <code>body</code>.
    *
-   * @param body ...
-   * @return     ...
+   * @param body the body of the actor to link to
+   * @return     the parameter actor
    */
   def link(body: => Unit): Actor = self.link(body)
 
@@ -298,7 +319,7 @@ object Actor {
    *
    * @param from the actor to unlink from
    */
-  def unlink(from: Actor): Unit = self.unlink(from)
+  def unlink(from: AbstractActor): Unit = self.unlink(from)
 
   /**
    * <p>
@@ -330,16 +351,51 @@ object Actor {
    *   <code>Exit(self, 'normal)</code> to <code>a</code>.
    * </p>
    */
-  def exit(): Nothing = self.exit()
+  def exit(): Nothing = rawSelf.exit()
 
-  def continue: Unit = throw new KillActorException
 }
 
 /**
  * <p>
- *   This class provides an implementation of event-based actors.
- *   The main ideas of our approach are explained in the two papers
+ *   This trait provides lightweight, concurrent actors. Actors are
+ *   created by extending the `Actor` trait (alternatively, one of the
+ *   factory methods in its companion object can be used).  The
+ *   behavior of an `Actor` subclass is defined by implementing its
+ *   `act` method:
+ *   
+ *   {{{
+ *   class MyActor extends Actor {
+ *     def act() {
+ *       // actor behavior goes here
+ *     }
+ *   }
+ *   }}}
+ *   
+ *   A new `Actor` instance is started by invoking its `start` method.
+ *   
+ *   '''Note:''' care must be taken when invoking thread-blocking methods
+ *   other than those provided by the `Actor` trait or its companion
+ *   object (such as `receive`). Blocking the underlying thread inside
+ *   an actor may lead to starvation of other actors. This also
+ *   applies to actors hogging their thread for a long time between
+ *   invoking `receive`/`react`.
+ *   
+ *   If actors use blocking operations (for example, methods for
+ *   blocking I/O), there are several options:
+ *   <ul>
+ *     <li>The run-time system can be configured to use a larger thread pool size
+ *     (for example, by setting the `actors.corePoolSize` JVM property).</li>
+ *     
+ *     <li>The `scheduler` method of the `Actor` trait can be overridden to return a 
+ *     `ResizableThreadPoolScheduler`, which resizes its thread pool to
+ *     avoid starvation caused by actors that invoke arbitrary blocking methods.</li>
+ *     
+ *     <li>The `actors.enableForkJoin` JVM property can be set to `false`, in which 
+ *     case a `ResizableThreadPoolScheduler` is used by default to execute actors.</li>
+ *   </ul>
  * </p>
+ * <p>
+ * The main ideas of the implementation are explained in the two papers
  * <ul>
  *   <li>
  *     <a href="http://lampwww.epfl.ch/~odersky/papers/jmlc06.pdf">
@@ -354,483 +410,314 @@ object Actor {
  *     Philipp Haller and Martin Odersky, <i>Proc. COORDINATION 2007</i>.
  *   </li>
  * </ul>
- *
- * @version 0.9.18
+ * </p>
+ * 
  * @author Philipp Haller
+ *
+ * @define actor actor
+ * @define channel actor's mailbox
  */
- at serializable
-trait Actor extends AbstractActor {
-
-  private var received: Option[Any] = None
-
-  private val waitingForNone = (m: Any) => false
-  private var waitingFor: Any => Boolean = waitingForNone
-  private var isSuspended = false
+ at serializable @SerialVersionUID(-781154067877019505L)
+trait Actor extends AbstractActor with ReplyReactor with ActorCanReply with InputChannel[Any] {
 
-  protected val mailbox = new MessageQueue
-  private var sessions: List[OutputChannel[Any]] = Nil
-
-  protected def scheduler: IScheduler =
-    Scheduler
-
-  /**
-   * Returns the number of messages in this actor's mailbox
-   *
-   * @return the number of messages in this actor's mailbox
+  /* The following two fields are only used when the actor
+   * suspends by blocking its underlying thread, for example,
+   * when waiting in a receive or synchronous send.
    */
-  def mailboxSize: Int = synchronized {
-    mailbox.size
-  }
+  @volatile
+  private var isSuspended = false
 
-  /**
-   * Sends <code>msg</code> to this actor (asynchronous) supplying
-   * explicit reply destination.
-   *
-   * @param  msg      the message to send
-   * @param  replyTo  the reply destination
+  /* This field is used to communicate the received message from
+   * the invocation of send to the place where the thread of
+   * the receiving actor resumes inside receive/receiveWithin.
    */
-  def send(msg: Any, replyTo: OutputChannel[Any]) = synchronized {
-    if (waitingFor(msg)) {
-      received = Some(msg)
-
-      if (isSuspended)
-        sessions = replyTo :: sessions
-      else
-        sessions = List(replyTo)
+  @volatile
+  private var received: Option[Any] = None
 
-      waitingFor = waitingForNone
+  protected[actors] override def scheduler: IScheduler = Scheduler
 
-      if (!onTimeout.isEmpty) {
-        onTimeout.get.cancel()
-        onTimeout = None
-      }
-
-      if (isSuspended)
+  private[actors] override def startSearch(msg: Any, replyTo: OutputChannel[Any], handler: PartialFunction[Any, Any]) =
+    if (isSuspended) {
+      () => synchronized {
+        mailbox.append(msg, replyTo)
         resumeActor()
-      else // assert continuation != null
-        scheduler.execute(new Reaction(this, continuation, msg))
-    } else {
-      mailbox.append(msg, replyTo)
-    }
-  }
-
-  /**
-   * Receives a message from this actor's mailbox.
-   *
-   * @param  f    a partial function with message patterns and actions
-   * @return      result of processing the received value
-   */
-  def receive[R](f: PartialFunction[Any, R]): R = {
-    assert(Actor.self == this, "receive from channel belonging to other actor")
-    this.synchronized {
-      if (shouldExit) exit() // links
-      val qel = mailbox.extractFirst((m: Any) => f.isDefinedAt(m))
+      }
+    } else super.startSearch(msg, replyTo, handler)
+
+  // we override this method to check `shouldExit` before suspending
+  private[actors] override def searchMailbox(startMbox: MQueue[Any],
+                                             handler: PartialFunction[Any, Any],
+                                             resumeOnSameThread: Boolean) {
+    var tmpMbox = startMbox
+    var done = false
+    while (!done) {
+      val qel = tmpMbox.extractFirst((msg: Any, replyTo: OutputChannel[Any]) => {
+        senders = List(replyTo)
+        handler.isDefinedAt(msg)
+      })
+      if (tmpMbox ne mailbox)
+        tmpMbox.foreach((m, s) => mailbox.append(m, s))
       if (null eq qel) {
-        waitingFor = f.isDefinedAt
-        isSuspended = true
-        suspendActor()
+        synchronized {
+          // in mean time new stuff might have arrived
+          if (!sendBuffer.isEmpty) {
+            tmpMbox = new MQueue[Any]("Temp")
+            drainSendBuffer(tmpMbox)
+            // keep going
+          } else {
+            // very important to check for `shouldExit` at this point
+            // since linked actors might have set it after we checked
+            // last time (e.g., at the beginning of `react`)
+            if (shouldExit) exit()
+            waitingFor = handler
+            // see Reactor.searchMailbox
+            throw Actor.suspendException
+          }
+        }
       } else {
-        received = Some(qel.msg)
-        sessions = qel.session :: sessions
+        resumeReceiver((qel.msg, qel.session), handler, resumeOnSameThread)
+        done = true
       }
-      waitingFor = waitingForNone
-      isSuspended = false
     }
-    val result = f(received.get)
-    sessions = sessions.tail
-    result
   }
 
-  /**
-   * Receives a message from this actor's mailbox within a certain
-   * time span.
-   *
-   * @param  msec the time span before timeout
-   * @param  f    a partial function with message patterns and actions
-   * @return      result of processing the received value
-   */
-  def receiveWithin[R](msec: Long)(f: PartialFunction[Any, R]): R = {
-    assert(Actor.self == this, "receive from channel belonging to other actor")
-    this.synchronized {
-      if (shouldExit) exit() // links
+  private[actors] override def makeReaction(fun: () => Unit, handler: PartialFunction[Any, Any], msg: Any): Runnable =
+    new ActorTask(this, fun, handler, msg)
+
+  def receive[R](f: PartialFunction[Any, R]): R = {
+    assert(Actor.self(scheduler) == this, "receive from channel belonging to other actor")
 
-      // first, remove spurious TIMEOUT message from mailbox if any
-      val spurious = mailbox.extractFirst((m: Any) => m == TIMEOUT)
+    synchronized {
+      if (shouldExit) exit() // links
+      drainSendBuffer(mailbox)
+    }
 
-      val qel = mailbox.extractFirst((m: Any) => f.isDefinedAt(m))
+    var done = false
+    while (!done) {
+      val qel = mailbox.extractFirst((m: Any, replyTo: OutputChannel[Any]) => {
+        senders = replyTo :: senders
+        val matches = f.isDefinedAt(m)
+        senders = senders.tail
+        matches
+      })
       if (null eq qel) {
-        if (msec == 0) {
-          if (f.isDefinedAt(TIMEOUT))
-            return f(TIMEOUT)
-          else
-            error("unhandled timeout")
-        }
-        else {
-          waitingFor = f.isDefinedAt
-          isSuspended = true
-          received = None
-          suspendActorFor(msec)
-          if (received.isEmpty) {
-            if (f.isDefinedAt(TIMEOUT)) {
-              waitingFor = waitingForNone
-              isSuspended = false
-              val result = f(TIMEOUT)
-              return result
-            }
-            else
-              error("unhandled timeout")
+        synchronized {
+          // in mean time new stuff might have arrived
+          if (!sendBuffer.isEmpty) {
+            drainSendBuffer(mailbox)
+            // keep going
+          } else {
+            waitingFor = f
+            isSuspended = true
+            scheduler.managedBlock(blocker)
+            drainSendBuffer(mailbox)
+            // keep going
           }
         }
       } else {
         received = Some(qel.msg)
-        sessions = qel.session :: sessions
+        senders = qel.session :: senders
+        done = true
       }
-      waitingFor = waitingForNone
-      isSuspended = false
     }
+
     val result = f(received.get)
-    sessions = sessions.tail
+    received = None
+    senders = senders.tail
     result
   }
 
-  /**
-   * Receives a message from this actor's mailbox.
-   * <p>
-   * This method never returns. Therefore, the rest of the computation
-   * has to be contained in the actions of the partial function.
-   *
-   * @param  f    a partial function with message patterns and actions
-   */
-  def react(f: PartialFunction[Any, Unit]): Nothing = {
-    assert(Actor.self == this, "react on channel belonging to other actor")
-    this.synchronized {
+  def receiveWithin[R](msec: Long)(f: PartialFunction[Any, R]): R = {
+    assert(Actor.self(scheduler) == this, "receive from channel belonging to other actor")
+
+    synchronized {
       if (shouldExit) exit() // links
-      val qel = mailbox.extractFirst((m: Any) => f.isDefinedAt(m))
-      if (null eq qel) {
-        waitingFor = f.isDefinedAt
-        continuation = f
-        isDetached = true
-      } else {
-        sessions = List(qel.session)
-        scheduleActor(f, qel.msg)
-      }
-      throw new SuspendActorException
+      drainSendBuffer(mailbox)
     }
-  }
 
-  /**
-   * Receives a message from this actor's mailbox within a certain
-   * time span.
-   * <p>
-   * This method never returns. Therefore, the rest of the computation
-   * has to be contained in the actions of the partial function.
-   *
-   * @param  msec the time span before timeout
-   * @param  f    a partial function with message patterns and actions
-   */
-  def reactWithin(msec: Long)(f: PartialFunction[Any, Unit]): Nothing = {
-    assert(Actor.self == this, "react on channel belonging to other actor")
-    this.synchronized {
-      if (shouldExit) exit() // links
+    // first, remove spurious TIMEOUT message from mailbox if any
+    mailbox.extractFirst((m: Any, replyTo: OutputChannel[Any]) => m == TIMEOUT)
 
-      // first, remove spurious TIMEOUT message from mailbox if any
-      val spurious = mailbox.extractFirst((m: Any) => m == TIMEOUT)
+    val receiveTimeout = () => {
+      if (f.isDefinedAt(TIMEOUT)) {
+        received = Some(TIMEOUT)
+        senders = this :: senders
+      } else
+        error("unhandled timeout")
+    }
 
-      val qel = mailbox.extractFirst((m: Any) => f.isDefinedAt(m))
+    var done = false
+    while (!done) {
+      val qel = mailbox.extractFirst((m: Any, replyTo: OutputChannel[Any]) => {
+        senders = replyTo :: senders
+        val matches = f.isDefinedAt(m)
+        senders = senders.tail
+        matches
+      })
       if (null eq qel) {
-        if (msec == 0) {
-          if (f.isDefinedAt(TIMEOUT)) {
-            sessions = List(Actor.self)
-            scheduleActor(f, TIMEOUT)
+        val todo = synchronized {
+          // in mean time new stuff might have arrived
+          if (!sendBuffer.isEmpty) {
+            drainSendBuffer(mailbox)
+            // keep going
+            () => {}
+          } else if (msec == 0L) {
+            done = true
+            receiveTimeout
+          } else {
+            waitingFor = f
+            received = None
+            isSuspended = true
+            val thisActor = this
+            onTimeout = Some(new TimerTask {
+              def run() { thisActor.send(TIMEOUT, thisActor) }
+            })
+            Actor.timer.schedule(onTimeout.get, msec)
+            scheduler.managedBlock(blocker)
+            drainSendBuffer(mailbox)
+            // keep going
+            () => {}
           }
-          else
-            error("unhandled timeout")
-        }
-        else {
-          waitingFor = f.isDefinedAt
-          val thisActor = this
-          onTimeout = Some(new TimerTask {
-            def run() { thisActor ! TIMEOUT }
-          })
-          Actor.timer.schedule(onTimeout.get, msec)
-          continuation = f
-          isDetached = true
         }
+        todo()
       } else {
-        sessions = List(qel.session)
-        scheduleActor(f, qel.msg)
+        synchronized {
+          if (!onTimeout.isEmpty) {
+            onTimeout.get.cancel()
+            onTimeout = None
+          }
+        }
+        received = Some(qel.msg)
+        senders = qel.session :: senders
+        done = true
       }
-      throw new SuspendActorException
-    }
-  }
-
-  /**
-   * The behavior of an actor is specified by implementing this
-   * abstract method. Note that the preferred way to create actors
-   * is through the <code>actor</code> method
-   * defined in object <code>Actor</code>.
-   */
-  def act(): Unit
-
-  /**
-   * Sends <code>msg</code> to this actor (asynchronous).
-   */
-  def !(msg: Any) {
-    send(msg, Actor.self)
-  }
-
-  /**
-   * Forwards <code>msg</code> to this actor (asynchronous).
-   */
-  def forward(msg: Any) {
-    send(msg, Actor.sender)
-  }
-
-  /**
-   * Sends <code>msg</code> to this actor and awaits reply
-   * (synchronous).
-   *
-   * @param  msg the message to be sent
-   * @return     the reply
-   */
-  def !?(msg: Any): Any = {
-    val replyCh = Actor.self.freshReplyChannel
-    send(msg, replyCh)
-    replyCh.receive {
-      case x => x
     }
-  }
 
-  /**
-   * Sends <code>msg</code> to this actor and awaits reply
-   * (synchronous) within <code>msec</code> milliseconds.
-   *
-   * @param  msec the time span before timeout
-   * @param  msg  the message to be sent
-   * @return      <code>None</code> in case of timeout, otherwise
-   *              <code>Some(x)</code> where <code>x</code> is the reply
-   */
-  def !?(msec: Long, msg: Any): Option[Any] = {
-    val replyCh = Actor.self.freshReplyChannel
-    send(msg, replyCh)
-    replyCh.receiveWithin(msec) {
-      case TIMEOUT => None
-      case x => Some(x)
-    }
+    val result = f(received.get)
+    received = None
+    senders = senders.tail
+    result
   }
 
-  /**
-   * Sends <code>msg</code> to this actor and immediately
-   * returns a future representing the reply value.
-   */
-  def !!(msg: Any): Future[Any] = {
-    val ftch = new Channel[Any](Actor.self)
-    send(msg, ftch)
-    new Future[Any](ftch) {
-      def apply() =
-        if (isSet) value.get
-        else ch.receive {
-          case any => value = Some(any); any
-        }
-      def respond(k: Any => Unit): Unit =
- 	if (isSet) k(value.get)
- 	else ch.react {
- 	  case any => value = Some(any); k(any)
- 	}
-      def isSet = value match {
-        case None => ch.receiveWithin(0) {
-          case TIMEOUT => false
-          case any => value = Some(any); true
-        }
-        case Some(_) => true
-      }
+  override def react(handler: PartialFunction[Any, Unit]): Nothing = {
+    synchronized {
+      if (shouldExit) exit()
     }
+    super.react(handler)
   }
 
-  /**
-   * Sends <code>msg</code> to this actor and immediately
-   * returns a future representing the reply value.
-   * The reply is post-processed using the partial function
-   * <code>f</code>. This also allows to recover a more
-   * precise type for the reply value.
-   */
-  def !![A](msg: Any, f: PartialFunction[Any, A]): Future[A] = {
-    val ftch = new Channel[Any](Actor.self)
-    send(msg, ftch)
-    new Future[A](ftch) {
-      def apply() =
-        if (isSet) value.get.asInstanceOf[A]
-        else ch.receive {
-          case any => value = Some(f(any)); value.get.asInstanceOf[A]
-        }
-      def respond(k: A => Unit): Unit =
- 	if (isSet) k(value.get.asInstanceOf[A])
- 	else ch.react {
- 	  case any => value = Some(f(any)); k(value.get.asInstanceOf[A])
- 	}
-      def isSet = value match {
-        case None => ch.receiveWithin(0) {
-          case TIMEOUT => false
-          case any => value = Some(f(any)); true
-        }
-        case Some(_) => true
-      }
+  override def reactWithin(msec: Long)(handler: PartialFunction[Any, Unit]): Nothing = {
+    synchronized {
+      if (shouldExit) exit()
     }
+    super.reactWithin(msec)(handler)
   }
 
-  /**
-   * Replies with <code>msg</code> to the sender.
-   */
-  def reply(msg: Any) {
-    sender ! msg
-  }
-
-  private var rc: Channel[Any] = null
-  private[actors] def replyChannel = rc
-  private[actors] def freshReplyChannel: Channel[Any] =
-    { rc = new Channel[Any](this); rc }
-
-  /**
-   * Receives the next message from this actor's mailbox.
-   */
   def ? : Any = receive {
     case x => x
   }
 
-  def sender: OutputChannel[Any] = sessions.head
-
-  def receiver: Actor = this
-
-  private var continuation: PartialFunction[Any, Unit] = null
-  private var onTimeout: Option[TimerTask] = None
-  // accessed in Reaction
-  private[actors] var isDetached = false
-  private var isWaiting = false
-
   // guarded by lock of this
-  protected def scheduleActor(f: PartialFunction[Any, Unit], msg: Any) =
-    if ((f eq null) && (continuation eq null)) {
+  // never throws SuspendActorControl
+  private[actors] override def scheduleActor(f: PartialFunction[Any, Any], msg: Any) =
+    if (f eq null) {
       // do nothing (timeout is handled instead)
     }
     else {
-      val task = new Reaction(this,
-                              if (f eq null) continuation else f,
-                              msg)
-      scheduler execute task
+      val task = new ActorTask(this, null, f, msg)
+      scheduler executeFromActor task
     }
 
-  private def tick(): Unit =
-    scheduler tick this
-
-  private[actors] var kill: () => Unit = () => {}
-
-  private def suspendActor() {
-    isWaiting = true
-    while (isWaiting) {
-      try {
-        wait()
-      } catch {
-        case _: InterruptedException =>
-      }
+  /* Used for notifying scheduler when blocking inside receive/receiveWithin. */
+  private object blocker extends scala.concurrent.ManagedBlocker {
+    def block() = {
+      Actor.this.suspendActor()
+      true
     }
-    // links: check if we should exit
-    if (shouldExit) exit()
+    def isReleasable =
+      !Actor.this.isSuspended
   }
 
-  private def suspendActorFor(msec: Long) {
-    val ts = Platform.currentTime
-    var waittime = msec
-    var fromExc = false
-    isWaiting = true
-    while (isWaiting) {
+  private def suspendActor() = synchronized {
+    while (isSuspended) {
       try {
-        fromExc = false
-        wait(waittime)
+        wait()
       } catch {
-        case _: InterruptedException => {
-          fromExc = true
-          val now = Platform.currentTime
-          val waited = now-ts
-          waittime = msec-waited
-          if (waittime < 0) { isWaiting = false }
-        }
+        case _: InterruptedException =>
       }
-      if (!fromExc) { isWaiting = false }
     }
     // links: check if we should exit
     if (shouldExit) exit()
   }
 
   private def resumeActor() {
-    isWaiting = false
+    isSuspended = false
     notify()
   }
 
-  /**
-   * Starts this actor.
-   */
-  def start(): Actor = synchronized {
+  private[actors] override def exiting = synchronized {
+    _state == Actor.State.Terminated
+  }
+
+  // guarded by this
+  private[actors] override def dostart() {
     // Reset various flags.
     //
     // Note that we do *not* reset `trapExit`. The reason is that
     // users should be able to set the field in the constructor
     // and before `act` is called.
-
     exitReason = 'normal
-    exiting = false
     shouldExit = false
 
-    scheduler execute {
-      ActorGC.newActor(Actor.this)
-      (new Reaction(Actor.this)).run()
-    }
+    super.dostart()
+  }
 
+  override def start(): Actor = synchronized {
+    super.start()
     this
   }
 
-  private def seq[a, b](first: => a, next: => b): Unit = {
-    val s = Actor.self
-    val killNext = s.kill
-    s.kill = () => {
-      s.kill = killNext
-
-      // to avoid stack overflow:
-      // instead of directly executing `next`,
-      // schedule as continuation
-      scheduleActor({ case _ => next }, 1)
-      throw new SuspendActorException
-    }
-    first
-    throw new KillActorException
+  override def getState: Actor.State.Value = synchronized {
+    if (isSuspended) {
+      if (onTimeout.isEmpty)
+        Actor.State.Blocked
+      else
+        Actor.State.TimedBlocked
+    } else
+      super.getState
   }
 
+  // guarded by this
   private[actors] var links: List[AbstractActor] = Nil
 
   /**
    * Links <code>self</code> to actor <code>to</code>.
    *
-   * @param to ...
-   * @return   ...
+   * @param to the actor to link to
+   * @return   the parameter actor
    */
   def link(to: AbstractActor): AbstractActor = {
-    assert(Actor.self == this, "link called on actor different from self")
-    synchronized {
-      links = to :: links
-    }
-    to.linkTo(this)
+    assert(Actor.self(scheduler) == this, "link called on actor different from self")
+    this linkTo to
+    to linkTo this
     to
   }
 
   /**
-   * Links <code>self</code> to actor defined by <code>body</code>.
+   * Links <code>self</code> to the actor defined by <code>body</code>.
+   *
+   * @param body the body of the actor to link to
+   * @return     the parameter actor
    */
   def link(body: => Unit): Actor = {
-    val actor = new Actor {
+    assert(Actor.self(scheduler) == this, "link called on actor different from self")
+    val a = new Actor {
       def act() = body
+      override final val scheduler: IScheduler = Actor.this.scheduler
     }
-    link(actor)
-    actor.start()
-    actor
+    link(a)
+    a.start()
+    a
   }
 
   private[actors] def linkTo(to: AbstractActor) = synchronized {
@@ -841,19 +728,20 @@ trait Actor extends AbstractActor {
    * Unlinks <code>self</code> from actor <code>from</code>.
    */
   def unlink(from: AbstractActor) {
-    assert(Actor.self == this, "unlink called on actor different from self")
-    synchronized {
-      links = links.remove(from.==)
-    }
-    from.unlinkFrom(this)
+    assert(Actor.self(scheduler) == this, "unlink called on actor different from self")
+    this unlinkFrom from
+    from unlinkFrom this
   }
 
   private[actors] def unlinkFrom(from: AbstractActor) = synchronized {
-    links = links.remove(from.==)
+    links = links.filterNot(from.==)
   }
 
+  @volatile
   var trapExit = false
-  private[actors] var exitReason: AnyRef = 'normal
+  // guarded by this
+  private var exitReason: AnyRef = 'normal
+  // guarded by this
   private[actors] var shouldExit = false
 
   /**
@@ -873,36 +761,51 @@ trait Actor extends AbstractActor {
    *   <code>reason != 'normal</code>.
    * </p>
    */
-  def exit(reason: AnyRef): Nothing = {
-    exitReason = reason
+  protected[actors] def exit(reason: AnyRef): Nothing = {
+    synchronized {
+      exitReason = reason
+    }
     exit()
   }
 
   /**
    * Terminates with exit reason <code>'normal</code>.
    */
-  def exit(): Nothing = {
-    // links
-    if (!links.isEmpty)
-      exitLinked()
-    throw new ExitActorException
+  protected[actors] override def exit(): Nothing = {
+    val todo = synchronized {
+      if (!links.isEmpty)
+        exitLinked()
+      else
+        () => {}
+    }
+    todo()
+    super.exit()
   }
 
   // Assume !links.isEmpty
-  private[actors] def exitLinked() {
-    exiting = true
+  // guarded by this
+  private[actors] def exitLinked(): () => Unit = {
+    _state = Actor.State.Terminated
+    // reset waitingFor, otherwise getState returns Suspended
+    waitingFor = Reactor.waitingForNone
     // remove this from links
-    val mylinks = links.remove(this.==)
-    // exit linked processes
-    mylinks.foreach((linked: AbstractActor) => {
-      unlink(linked)
-      if (!linked.exiting)
-        linked.exit(this, exitReason)
-    })
+    val mylinks = links.filterNot(this.==)
+    // unlink actors
+    mylinks.foreach(unlinkFrom(_))
+    // return closure that locks linked actors
+    () => {
+      mylinks.foreach((linked: AbstractActor) => {
+        linked.synchronized {
+          if (!linked.exiting)
+            linked.exit(this, exitReason)
+        }
+      })
+    }
   }
 
   // Assume !links.isEmpty
-  private[actors] def exitLinked(reason: AnyRef) {
+  // guarded by this
+  private[actors] def exitLinked(reason: AnyRef): () => Unit = {
     exitReason = reason
     exitLinked()
   }
@@ -913,16 +816,35 @@ trait Actor extends AbstractActor {
       this ! Exit(from, reason)
     }
     else if (reason != 'normal)
-      this.synchronized {
+      synchronized {
         shouldExit = true
         exitReason = reason
+        // resume this Actor in a way that
+        // causes it to exit
+        // (because shouldExit == true)
         if (isSuspended)
           resumeActor()
-        else if (isDetached)
-          scheduleActor(null, null)
+        else if (waitingFor ne Reactor.waitingForNone) {
+          waitingFor = Reactor.waitingForNone
+          // it doesn't matter what partial function we are passing here
+          scheduleActor(waitingFor, null)
+          /* Here we should not throw a SuspendActorControl,
+             since the current method is called from an actor that
+             is in the process of exiting.
+             
+             Therefore, the contract for scheduleActor is that
+             it never throws a SuspendActorControl.
+           */
+        }
       }
   }
 
+  /* Requires qualified private, because <code>RemoteActor</code> must
+   * register a termination handler.
+   */
+  private[actors] def onTerminate(f: => Unit) {
+    scheduler.onTerminate(this) { f }
+  }
 }
 
 
@@ -941,12 +863,18 @@ trait Actor extends AbstractActor {
  *      <b>case</b> TIMEOUT <b>=></b> ...
  *    }</pre>
  *
- *  @version 0.9.8
  *  @author Philipp Haller
  */
 case object TIMEOUT
 
 
+/** An `Exit` message (an instance of this class) is sent to an actor
+ *  with `trapExit` set to `true` whenever one of its linked actors
+ *  terminates.
+ *
+ *  @param from   the actor that terminated
+ *  @param reason the reason that caused the actor to terminate
+ */
 case class Exit(from: AbstractActor, reason: AnyRef)
 
 /** <p>
@@ -954,13 +882,6 @@ case class Exit(from: AbstractActor, reason: AnyRef)
  *    executions.
  *  </p>
  *
- * @version 0.9.8
  * @author Philipp Haller
  */
-private[actors] class SuspendActorException extends Throwable {
-  /*
-   * For efficiency reasons we do not fill in
-   * the execution stack trace.
-   */
-  override def fillInStackTrace(): Throwable = this
-}
+private[actors] class SuspendActorControl extends ControlThrowable
diff --git a/src/actors/scala/actors/ActorCanReply.scala b/src/actors/scala/actors/ActorCanReply.scala
new file mode 100644
index 0000000..9d52081
--- /dev/null
+++ b/src/actors/scala/actors/ActorCanReply.scala
@@ -0,0 +1,66 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2005-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+package scala.actors
+
+import scala.concurrent.SyncVar
+
+/**
+ * The `ActorCanReply` trait provides message send operations that
+ * may result in a response from the receiver.
+ *
+ * @author Philipp Haller
+ */
+private[actors] trait ActorCanReply extends ReactorCanReply {
+  this: AbstractActor with ReplyReactor =>
+
+  override def !?(msg: Any): Any = {
+    val replyCh = new Channel[Any](Actor.self(scheduler))
+    send(msg, replyCh)
+    replyCh.?
+  }
+
+  override def !?(msec: Long, msg: Any): Option[Any] = {
+    val replyCh = new Channel[Any](Actor.self(scheduler))
+    send(msg, replyCh)
+    replyCh.receiveWithin(msec) {
+      case TIMEOUT => None
+      case x => Some(x)
+    }
+  }
+
+  override def !![A](msg: Any, handler: PartialFunction[Any, A]): Future[A] = {
+    val c = new Channel[A](Actor.self(scheduler))
+    val fun = (res: SyncVar[A]) => {
+      val ftch = new Channel[A](Actor.self(scheduler))
+      send(msg, new OutputChannel[Any] {
+        def !(msg: Any) =
+          ftch ! handler(msg)
+        def send(msg: Any, replyTo: OutputChannel[Any]) =
+          ftch.send(handler(msg), replyTo)
+        def forward(msg: Any) =
+          ftch.forward(handler(msg))
+        def receiver =
+          ftch.receiver
+      })
+      ftch.react {
+        case any => res.set(any)
+      }
+    }
+    val a = new FutureActor[A](fun, c)
+    a.start()
+    a
+  }
+
+  override def !!(msg: Any): Future[Any] = {
+    val noTransform: PartialFunction[Any, Any] = { case x => x }
+    this !! (msg, noTransform)
+  }
+
+}
diff --git a/src/actors/scala/actors/ActorGC.scala b/src/actors/scala/actors/ActorGC.scala
deleted file mode 100644
index fabea8b..0000000
--- a/src/actors/scala/actors/ActorGC.scala
+++ /dev/null
@@ -1,29 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2005-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id:$
-
-package scala.actors
-
-import java.lang.ref.{Reference, WeakReference, ReferenceQueue}
-import java.util.WeakHashMap
-
-import scala.collection.mutable.{HashMap, HashSet}
-import scala.actors.scheduler.TerminationMonitor
-
-object ActorGC extends TerminationMonitor {
-
-  private[actors] def getPendingCount = synchronized {
-    activeActors
-  }
-
-  private[actors] def setPendingCount(cnt: Int) = synchronized {
-    activeActors = cnt
-  }
-
-}
diff --git a/src/actors/scala/actors/ActorProxy.scala b/src/actors/scala/actors/ActorProxy.scala
index 6b1efb1..be54ca9 100644
--- a/src/actors/scala/actors/ActorProxy.scala
+++ b/src/actors/scala/actors/ActorProxy.scala
@@ -1,27 +1,23 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2005-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2005-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: ActorProxy.scala 18846 2009-10-01 07:30:14Z phaller $
-
 
 package scala.actors
 
-
 import java.lang.Thread
 
 /**
  * The class <code>ActorProxy</code> provides a dynamic actor proxy for normal
  * Java threads.
  *
- * @version 0.9.8
  * @author Philipp Haller
  */
-private[actors] class ActorProxy(t: Thread) extends Actor {
+private[actors] class ActorProxy(t: Thread, override final val scheduler: IScheduler) extends Actor {
 
   def act() {}
 
diff --git a/src/actors/scala/actors/ActorTask.scala b/src/actors/scala/actors/ActorTask.scala
new file mode 100644
index 0000000..66c47f6
--- /dev/null
+++ b/src/actors/scala/actors/ActorTask.scala
@@ -0,0 +1,54 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2005-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |                                         **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.actors
+
+/** <p>
+ *    The class <code>ActorTask</code>.
+ *  </p>
+ *
+ *  @author Philipp Haller
+ */
+private[actors] class ActorTask(actor: Actor,
+                                fun: () => Unit,
+                                handler: PartialFunction[Any, Any],
+                                msg: Any)
+  extends ReplyReactorTask(actor, fun, handler, msg) {
+
+  protected override def beginExecution() {
+    super.beginExecution()
+    actor.synchronized { // shouldExit guarded by actor
+      if (actor.shouldExit)
+        actor.exit()
+    }
+  }
+
+  protected override def terminateExecution(e: Throwable) {
+    val senderInfo = try { Some(actor.sender) } catch {
+      case _: Exception => None
+    }
+    val uncaught = UncaughtException(actor,
+                                     if (msg != null) Some(msg) else None,
+                                     senderInfo,
+                                     currentThread,
+                                     e)
+
+    val todo = actor.synchronized {
+      if (!actor.links.isEmpty)
+        actor.exitLinked(uncaught)
+      else {
+        super.terminateExecution(e)
+        () => {}
+      }
+    }
+    todo()
+  }
+
+}
diff --git a/src/actors/scala/actors/CanReply.scala b/src/actors/scala/actors/CanReply.scala
new file mode 100644
index 0000000..eaaaef1
--- /dev/null
+++ b/src/actors/scala/actors/CanReply.scala
@@ -0,0 +1,66 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2005-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+package scala.actors
+
+/**
+ * The <code>CanReply</code> trait defines result-bearing message send operations.
+ *
+ * @author Philipp Haller
+ *
+ * @define actor `CanReply`
+ */
+trait CanReply[-T, +R] {
+
+  type Future[+P] <: () => P
+
+  /**
+   * Sends <code>msg</code> to this $actor and
+   * awaits reply (synchronous).
+   *
+   * @param  msg the message to be sent
+   * @return     the reply
+   */
+  def !?(msg: T): R
+
+  /**
+   * Sends <code>msg</code> to this $actor and
+   * awaits reply (synchronous) within <code>msec</code>
+   * milliseconds.
+   *
+   * @param  msec the time span before timeout
+   * @param  msg  the message to be sent
+   * @return      <code>None</code> in case of timeout, otherwise
+   *              <code>Some(x)</code> where <code>x</code> is the reply
+   */
+  def !?(msec: Long, msg: T): Option[R]
+
+  /**
+   * Sends <code>msg</code> to this $actor and
+   * immediately returns a future representing the reply value.
+   *
+   * @param  msg the message to be sent
+   * @return     the future
+   */
+  def !!(msg: T): Future[R]
+
+  /**
+   * Sends <code>msg</code> to this $actor and
+   * immediately returns a future representing the reply value.
+   * The reply is post-processed using the partial function
+   * <code>handler</code>. This also allows to recover a more
+   * precise type for the reply value.
+   *
+   * @param      msg the message to be sent
+   * @param  handler the function to be applied to the response
+   * @return         the future
+   */
+  def !![P](msg: T, handler: PartialFunction[R, P]): Future[P]
+
+}
diff --git a/src/actors/scala/actors/Channel.scala b/src/actors/scala/actors/Channel.scala
index d671afe..1be9653 100644
--- a/src/actors/scala/actors/Channel.scala
+++ b/src/actors/scala/actors/Channel.scala
@@ -1,31 +1,29 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2005-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2005-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Channel.scala 18846 2009-10-01 07:30:14Z phaller $
 
 package scala.actors
 
+import scala.concurrent.SyncVar
 
-/** <p>
- *    This class is used to pattern match on values that were sent
- *    to some channel <code>Chan<sub>n</sub></code> by the current
- *    actor <code>self</code>.
- *  </p>
- *  <p>
- *    The following example demonstrates its usage:
- *  </p><pre>
+/**
+ *  This class is used to pattern match on values that were sent
+ *  to some channel <code>Chan<sub>n</sub></code> by the current
+ *  actor <code>self</code>.
+ * 
+ *  The following example demonstrates its usage:
+ *  {{{
  *  receive {
  *    <b>case</b> Chan1 ! msg1 => ...
  *    <b>case</b> Chan2 ! msg2 => ...
  *  }
- *  </pre>
- *
- * @version 0.9.8
+ *  }}}
+ * 
  * @author Philipp Haller
  */
 case class ! [a](ch: Channel[a], msg: a)
@@ -35,151 +33,106 @@ case class ! [a](ch: Channel[a], msg: a)
  * actors. Only the actor creating an instance of a
  * <code>Channel</code> may receive from it.
  *
- * @version 0.9.17
  * @author Philipp Haller
+ *
+ * @define actor channel
+ * @define channel channel
  */
-class Channel[Msg] extends InputChannel[Msg] with OutputChannel[Msg] {
+class Channel[Msg](val receiver: Actor) extends InputChannel[Msg] with OutputChannel[Msg] with CanReply[Msg, Any] {
 
-  private[actors] var recv: Actor = {
-    // basically Actor.self, but can be null
-    Actor.tl.get.asInstanceOf[Actor]
-  }
-
-  def receiver: Actor = recv
+  type Future[+P] = scala.actors.Future[P]
 
-  def this(recv: Actor) = {
-    this()
-    this.recv = recv
-  }
+  def this() = this(Actor.self)
 
-  /**
-   * Sends a message to this <code>Channel</code>.
-   *
-   * @param  msg the message to be sent
-   */
   def !(msg: Msg) {
-    recv ! scala.actors.!(this, msg)
+    receiver ! scala.actors.!(this, msg)
   }
 
-  /**
-   * Sends a message to this <code>Channel</code>
-   * (asynchronous) supplying explicit reply destination.
-   *
-   * @param  msg     the message to send
-   * @param  replyTo the reply destination
-   */
   def send(msg: Msg, replyTo: OutputChannel[Any]) {
-    recv.send(scala.actors.!(this, msg), replyTo)
+    receiver.send(scala.actors.!(this, msg), replyTo)
   }
 
-  /**
-   * Forwards <code>msg</code> to <code>this</code> keeping the
-   * last sender as sender instead of <code>self</code>.
-   */
   def forward(msg: Msg) {
-    recv forward scala.actors.!(this, msg)
+    receiver forward scala.actors.!(this, msg)
   }
 
-  /**
-   * Receives a message from this <code>Channel</code>.
-   *
-   * @param  f    a partial function with message patterns and actions
-   * @return      result of processing the received value
-   */
   def receive[R](f: PartialFunction[Msg, R]): R = {
     val C = this.asInstanceOf[Channel[Any]]
-    recv.receive {
+    receiver.receive {
       case C ! msg if (f.isDefinedAt(msg.asInstanceOf[Msg])) => f(msg.asInstanceOf[Msg])
     }
   }
 
-  /**
-   * Receives the next message from this <code>Channel</code>.
-   */
   def ? : Msg = receive {
     case x => x
   }
 
-  /**
-   * Receives a message from this <code>Channel</code> within a certain
-   * time span.
-   *
-   * @param  msec the time span before timeout
-   * @param  f    a partial function with message patterns and actions
-   * @return      result of processing the received value
-   */
   def receiveWithin[R](msec: Long)(f: PartialFunction[Any, R]): R = {
     val C = this.asInstanceOf[Channel[Any]]
-    recv.receiveWithin(msec) {
+    receiver.receiveWithin(msec) {
       case C ! msg if (f.isDefinedAt(msg)) => f(msg)
       case TIMEOUT => f(TIMEOUT)
     }
   }
 
-  /**
-   * Receives a message from this <code>Channel</code>.
-   * <p>
-   * This method never returns. Therefore, the rest of the computation
-   * has to be contained in the actions of the partial function.
-   *
-   * @param  f    a partial function with message patterns and actions
-   */
   def react(f: PartialFunction[Msg, Unit]): Nothing = {
     val C = this.asInstanceOf[Channel[Any]]
-    recv.react {
+    receiver.react {
       case C ! msg if (f.isDefinedAt(msg.asInstanceOf[Msg])) => f(msg.asInstanceOf[Msg])
     }
   }
 
-  /**
-   * Receives a message from this <code>Channel</code> within a certain
-   * time span.
-   * <p>
-   * This method never returns. Therefore, the rest of the computation
-   * has to be contained in the actions of the partial function.
-   *
-   * @param  msec the time span before timeout
-   * @param  f    a partial function with message patterns and actions
-   */
   def reactWithin(msec: Long)(f: PartialFunction[Any, Unit]): Nothing = {
     val C = this.asInstanceOf[Channel[Any]]
-    recv.reactWithin(msec) {
+    receiver.reactWithin(msec) {
       case C ! msg if (f.isDefinedAt(msg)) => f(msg)
       case TIMEOUT => f(TIMEOUT)
     }
   }
 
-  /**
-   * Sends a message to this <code>Channel</code> and
-   * awaits reply.
-   *
-   * @param  msg the message to be sent
-   * @return     the reply
-   */
   def !?(msg: Msg): Any = {
-    val replyCh = Actor.self.freshReplyChannel
-    recv.send(scala.actors.!(this, msg), replyCh)
+    val replyCh = new Channel[Any](Actor.self(receiver.scheduler))
+    receiver.send(scala.actors.!(this, msg), replyCh)
     replyCh.receive {
       case x => x
     }
   }
 
-  /**
-   * Sends a message to this <code>Channel</code> and
-   * awaits reply within a certain time span.
-   *
-   * @param  msec the time span before timeout
-   * @param  msg  the message to be sent
-   * @return      <code>None</code> in case of timeout, otherwise
-   *              <code>Some(x)</code> where <code>x</code> is the reply
-   */
   def !?(msec: Long, msg: Msg): Option[Any] = {
-    val replyCh = Actor.self.freshReplyChannel
-    recv.send(scala.actors.!(this, msg), replyCh)
+    val replyCh = new Channel[Any](Actor.self(receiver.scheduler))
+    receiver.send(scala.actors.!(this, msg), replyCh)
     replyCh.receiveWithin(msec) {
       case TIMEOUT => None
       case x => Some(x)
     }
   }
 
+  def !![A](msg: Msg, handler: PartialFunction[Any, A]): Future[A] = {
+    val c = new Channel[A](Actor.self(receiver.scheduler))
+    val fun = (res: SyncVar[A]) => {
+      val ftch = new Channel[A](Actor.self(receiver.scheduler))
+      receiver.send(scala.actors.!(this, msg), new OutputChannel[Any] {
+        def !(msg: Any) =
+          ftch ! handler(msg)
+        def send(msg: Any, replyTo: OutputChannel[Any]) =
+          ftch.send(handler(msg), replyTo)
+        def forward(msg: Any) =
+          ftch.forward(handler(msg))
+        def receiver =
+          ftch.receiver
+      })
+      ftch.react {
+        case any => res.set(any)
+      }
+    }
+    val a = new FutureActor[A](fun, c)
+    a.start()
+    a
+  }
+
+  def !!(msg: Msg): Future[Any] = {
+    val noTransform: PartialFunction[Any, Any] = { case x => x }
+    this !! (msg, noTransform)
+  }
+
 }
diff --git a/src/actors/scala/actors/Combinators.scala b/src/actors/scala/actors/Combinators.scala
new file mode 100644
index 0000000..6082f92
--- /dev/null
+++ b/src/actors/scala/actors/Combinators.scala
@@ -0,0 +1,46 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2005-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+// $Id$
+
+package scala.actors
+
+private[actors] trait Combinators {
+
+  /**
+   * Enables the composition of suspendable closures using `andThen`,
+   * `loop`, `loopWhile`, etc.
+   */
+  implicit def mkBody[a](body: => a): Actor.Body[a]
+
+  /**
+   * Repeatedly executes `body`.
+   *
+   * @param body the block to be executed
+   */
+  def loop(body: => Unit): Unit = body andThen loop(body)
+
+  /**
+   * Repeatedly executes `body` while the condition `cond` is `true`.
+   *
+   * @param cond the condition to test
+   * @param body the block to be executed
+   */
+  def loopWhile(cond: => Boolean)(body: => Unit): Unit =
+    if (cond) { body andThen loopWhile(cond)(body) }
+    else continue
+
+  /**
+   * Continues with the execution of the closure registered as
+   * continuation following `andThen`. Continues with the execution
+   * of the next loop iteration when invoked inside the body of `loop`
+   * or `loopWhile`.
+   */
+  def continue: Unit = throw new KillActorControl
+
+}
diff --git a/src/actors/scala/actors/DaemonActor.scala b/src/actors/scala/actors/DaemonActor.scala
new file mode 100644
index 0000000..27b8cd8
--- /dev/null
+++ b/src/actors/scala/actors/DaemonActor.scala
@@ -0,0 +1,22 @@
+/*                     __                                               *\ 
+**     ________ ___   / /  ___     Scala API                            ** 
+**    / __/ __// _ | / /  / _ |    (c) 2005-2010, LAMP/EPFL             ** 
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               ** 
+** /____/\___/_/ |_/____/_/ | |                                         ** 
+**                          |/                                          ** 
+\*                                                                      */ 
+ 
+package scala.actors 
+
+import scheduler.DaemonScheduler
+ 
+/** 
+ * Base trait for actors with daemon semantics.
+ * Unlike a regular <code>Actor</code>, an active <code>DaemonActor</code> will 
+ * not prevent an application terminating, much like a daemon thread. 
+ *
+ * @author Erik Engbrecht 
+ */ 
+trait DaemonActor extends Actor { 
+  override def scheduler: IScheduler = DaemonScheduler
+}
diff --git a/src/actors/scala/actors/Debug.scala b/src/actors/scala/actors/Debug.scala
index 3aecd0e..fc66ca5 100644
--- a/src/actors/scala/actors/Debug.scala
+++ b/src/actors/scala/actors/Debug.scala
@@ -1,47 +1,47 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2005-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2005-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Debug.scala 18830 2009-09-29 22:53:36Z phaller $
 
 package scala.actors
 
 /**
+ * Provides methods for generating debugging output.
+ * 
  * @author Philipp Haller
  */
-object Debug {
+object Debug extends Logger("") {}
+
+private[actors] class Logger(tag: String) {
   private var lev = 2
 
   def level = lev
   def level_= (lev: Int) = { this.lev = lev }
 
+  private val tagString = if (tag == "") "" else " ["+tag+"]"
+
   def info(s: String) =
-    if (lev > 2) System.out.println("Info: " + s)
+    if (lev > 2) System.out.println("Info" + tagString + ": " + s)
 
   def warning(s: String) =
-    if (lev > 1) System.err.println("Warning: " + s)
+    if (lev > 1) System.err.println("Warning" + tagString + ": " + s)
 
   def error(s: String) =
-    if (lev > 0) System.err.println("Error: " + s)
-}
-
- at deprecated
-class Debug(tag: String) {
-  private var lev = 2
-
-  def level = lev
-  def level_= (lev: Int) = { this.lev = lev }
+    if (lev > 0) System.err.println("Error" + tagString + ": " + s)
 
-  def info(s: String) =
-    if (lev > 2) System.out.println(tag + " (info): " + s)
+  def doInfo(b: => Unit) =
+    if (lev > 2) b
 
-  def warning(s: String) =
-    if (lev > 1) System.err.println(tag + " (warn): " + s)
+  def doWarning(b: => Unit) =
+    if (lev > 1) b
 
-  def error(s: String) =
-    if (lev > 0) System.err.println(tag + " (erro): " + s)
+  def doError(b: => Unit) =
+    if (lev > 0) b
 }
+
+ at deprecated("this class is going to be removed in a future release")
+class Debug(tag: String) extends Logger(tag) {}
diff --git a/src/actors/scala/actors/FJTask.java b/src/actors/scala/actors/FJTask.java
deleted file mode 100644
index 7fce0c8..0000000
--- a/src/actors/scala/actors/FJTask.java
+++ /dev/null
@@ -1,531 +0,0 @@
-/*
-  File: Task.java
-
-  Originally written by Doug Lea and released into the public domain.
-  This may be used for any purposes whatsoever without acknowledgment.
-  Thanks for the assistance and support of Sun Microsystems Labs,
-  and everyone contributing, testing, and using this code.
-
-  History:
-  Date       Who                What
-  7Jan1999   dl                 first release
-  14jan1999  dl                 simplify start() semantics;
-                                improve documentation
-  18Jan1999  dl                 Eliminate useless time-based waits.
-  7Mar1999   dl                 Add reset method, 
-                                add array-based composite operations
-  27Apr1999  dl                 Rename
-*/
-
-package scala.actors;
-
-
-/**
- * Abstract base class for Fork/Join Tasks.
- *
- * <p>
- * FJTasks are lightweight, stripped-down analogs of Threads. 
- * Many FJTasks share the same pool of Java threads. This is
- * supported by the FJTaskRunnerGroup and FJTaskRunner classes, that 
- * mainly contain
- * methods called only internally by FJTasks.
- * FJTasks support versions of the most common methods found in class Thread,
- * including start(), yield() and join(). However, they
- * don't support priorities, ThreadGroups or other bookkeeping
- * or control methods of class Thread.
- * <p>
- * FJTasks should normally be defined by subclassing and adding a run() method.
- * Alternatively, static inner class <code>Wrap(Runnable r)</code> 
- * can be used to
- * wrap an existing Runnable object in a FJTask. 
- * <p>
- * <code>FJTaskRunnerGroup.execute(FJTask)</code> can be used to
- * initiate a FJTask from a non-FJTask thread. 
- * And <code>FJTaskRunnerGroup.invoke(FJTask)</code> can be used to initiate
- * a FJTask and then wait for it to complete before returning.
- * These are the only entry-points from normal threads to FJTasks.
- * Most FJTask methods themselves may only be called from within running FJTasks.
- * They throw ClassCastExceptions if they are not, 
- * reflecting the fact that these methods
- * can only be executed using FJTaskRunner threads, not generic
- * java.lang.Threads.
- * <p>
- * There are three different ways to run a FJTask,
- * with different scheduling semantics:
- * <ul>
- *   <li> FJTask.start() (as well as FJTaskRunnerGroup.execute(FJTask)) 
- *         behaves pretty much like Thread.start(). It enqueues a task to be
- *         run the next time any FJTaskRunner thread is otherwise idle.
- *         It maintains standard FIFO ordering with respect to
- *         the group of worker threads.
- *   <li> FJTask.fork() (as well as the two-task spawning method,
- *         coInvoke(task1, task2), and the array version 
- *         coInvoke(FJTask[] tasks)) starts a task 
- *         that will be executed in
- *         procedure-call-like LIFO order if executed by the 
- *         same worker thread as the one that created it, but is FIFO 
- *         with respect to other tasks if it is run by
- *         other worker threads. That is, earlier-forked
- *         tasks are preferred to later-forked tasks by other idle workers.
- *         Fork() is noticeably faster than start(), but can only be
- *         used when these scheduling semantics are acceptable.
- *   <li> FJTask.invoke(FJTask) just executes the run method
- *        of one task from within another. It is the analog of a
- *        direct call.
- * </ul>
- * <p>
- * The main economies of FJTasks stem from the fact that
- * FJTasks do not support blocking operations of any kind. 
- * FJTasks should just run to completion without
- * issuing waits or performing blocking IO. 
- * There are several styles for creating the run methods that
- * execute as tasks, including
- * event-style methods, and pure computational methods.
- * Generally, the best kinds of FJTasks are those that in turn
- * generate other FJTasks. 
- * <p>
- * There is nothing actually
- * preventing you from blocking within a FJTask, and very short waits/blocks are
- * completely well behaved. But FJTasks are not designed
- * to support arbitrary synchronization 
- * since there is no way to suspend and resume individual tasks
- * once they have begun executing. FJTasks should also be finite
- * in duration -- they should not contain infinite loops.
- * FJTasks that might need to perform a blocking
- * action, or hold locks for extended periods, or 
- * loop forever can instead create normal 
- * java Thread objects that will do so. FJTasks are just not
- * designed to support these things. 
- * FJTasks may however yield() control to allow their FJTaskRunner threads
- * to run other tasks,
- * and may wait for other dependent tasks via join(). These
- * are the only coordination mechanisms supported by FJTasks.
- * <p>
- * FJTasks, and the FJTaskRunners that execute them are not
- * intrinsically robust with respect to exceptions. 
- * A FJTask that aborts via an exception does not automatically
- * have its completion flag (isDone) set. 
- * As with ordinary Threads, an uncaught exception will normally cause
- * its FJTaskRunner thread to die, which in turn may sometimes
- * cause other computations being performed to hang or abort.
- * You can of course
- * do better by trapping exceptions inside the run methods of FJTasks.
- * <p>
- * The overhead differences between FJTasks and Threads are substantial,
- * especially when using fork() or coInvoke().
- * FJTasks can be two or three orders of magnitude faster than Threads,
- * at least when run on JVMs with high-performance garbage collection
- * (every FJTask quickly becomes garbage) and good native thread support.
- * <p>
- * Given these overhead savings, you might be tempted to use FJTasks for 
- * everything you would use a normal Thread to do. Don't. Java Threads
- * remain better for general purpose thread-based programming. Remember
- * that FJTasks cannot be used for designs involving arbitrary blocking 
- * synchronization or I/O. Extending FJTasks to support such capabilities
- * would amount to re-inventing the Thread class, and would make them
- * less optimal in the contexts that they were designed for.
- * <p>[<a href="http://gee.cs.oswego.edu/dl/classes/EDU/oswego/cs/dl/util/concurrent/intro.html"> Introduction to this package. </a>]
- * <p>
- * @see FJTaskRunner
- * @see FJTaskRunnerGroup
- **/
-
-public abstract class FJTask implements Runnable {
-
-  /**
-   * The only status information associated with FJTasks is whether
-   * the they are considered to have completed.
-   * It is set true automatically within
-   * FJTaskRunner methods upon completion
-   * of the run method, or manually via cancel.
-   **/
-
-  private volatile boolean done; // = false;
-
-  /**
-   * Return the FJTaskRunner thread running the current FJTask.
-   * Most FJTask methods are just relays to their current
-   * FJTaskRunners, that perform the indicated actions.
-   * @exception ClassCastException if caller thread is not a
-   * running FJTask.
-   **/
-
-  public static FJTaskRunner getFJTaskRunner() {
-    return (FJTaskRunner)(Thread.currentThread());
-  }
-
-  /**
-   * Return the FJTaskRunnerGroup of the thread running the current FJTask.
-   * @exception ClassCastException if caller thread is not a
-   * running FJTask.
-   **/
-  public static IFJTaskRunnerGroup getFJTaskRunnerGroup() {
-    return getFJTaskRunner().getGroup();
-  }
-
-
-  /**
-   * Return true if current task has terminated or been cancelled.
-   * The  method is a simple analog of the Thread.isAlive()
-   * method. However, it reports true only when the task has terminated
-   * or has been cancelled. It does not distinguish these two cases.
-   * And there is no way to determine whether a FJTask has been started
-   * or is currently executing.
-   **/
-
-  public final boolean isDone() { return done; }
-
-  /** 
-   * Indicate termination. Intended only to be called by FJTaskRunner.
-   * FJTasks themselves should use (non-final) method
-   * cancel() to suppress execution.
-   **/
-
-  protected final void setDone() { done = true; }
-
-  /**
-   * Set the termination status of this task. This simple-minded
-   * analog of Thread.interrupt
-   * causes the task not to execute if it has not already been started.
-   * Cancelling a running FJTask
-   * has no effect unless the run method itself uses isDone()
-   * to probe cancellation and take appropriate action.
-   * Individual run() methods may sense status and
-   * act accordingly, normally by returning early. 
-   **/
-
-  public void cancel() { setDone();  }
-
-
-  /**
-   * Clear the termination status of this task. 
-   * This method is intended to be used
-   * only as a means to allow task objects to be recycled. It should
-   * be called only when you are sure that the previous
-   * execution of this task has terminated and, if applicable, has
-   * been joined by all other waiting tasks. Usage in any other
-   * context is a very bad idea.
-   **/
-
-  public void reset() { done = false;  }
-
-
-  /**
-   * Execute this task. This method merely places the task in a 
-   * group-wide scheduling queue.
-   * It will be run 
-   * the next time any TaskRunner thread is otherwise idle.
-   * This scheduling  maintains FIFO ordering of started tasks 
-   * with respect to
-   * the group of worker threads.
-   * @exception ClassCastException if caller thread is not
-   * running in a FJTaskRunner thread.
-   **/
-
-  public void start() { getFJTaskRunnerGroup().executeTask(this);  }
-  
-
-  /**
-   * Arrange for execution of a strictly dependent task.
-   * The task that will be executed in
-   * procedure-call-like LIFO order if executed by the 
-   * same worker thread, but is FIFO with respect to other tasks
-   * forked by this thread when taken by other worker threads. 
-   * That is, earlier-forked
-   * tasks are preferred to later-forked tasks by other idle workers.
-   * <p>
-   * Fork() is noticeably
-   * faster than start(). However, it may only
-   * be used for strictly dependent tasks -- generally, those that
-   * could logically be issued as straight method calls without 
-   * changing the logic of the program.
-   * The method is optimized for use in parallel fork/join designs
-   * in which the thread that issues one or more forks
-   * cannot continue until at least some of the forked 
-   * threads terminate and are joined. 
-   * @exception ClassCastException if caller thread is not
-   * running in a FJTaskRunner thread.
-   **/
-
-  public void fork() { getFJTaskRunner().push(this);  }
-
-  /**
-   * Allow the current underlying FJTaskRunner thread to process other tasks.
-   * <p>
-   * Spinloops based on yield() are well behaved so long
-   * as the event or condition being waited for is produced via another
-   * FJTask. Additionally, you must never hold a lock
-   * while performing a yield or join. (This is because
-   * multiple FJTasks can be run by the same Thread during
-   * a yield. Since java locks are held per-thread, the lock would not
-   * maintain the conceptual exclusion you have in mind.)
-   * <p>
-   * Otherwise, spinloops using
-   * yield are the main construction of choice when a task must wait
-   * for a condition that it is sure will eventually occur because it
-   * is being produced by some other FJTask.  The most common
-   * such condition is built-in: join() repeatedly yields until a task
-   * has terminated after producing some needed results. You can also
-   * use yield to wait for callbacks from other FJTasks, to wait for
-   * status flags to be set, and so on. However, in all these cases,
-   * you should be confident that the condition being waited for will
-   * occur, essentially always because it is produced by 
-   * a FJTask generated by the current task, or one of its subtasks.
-   *
-   * @exception ClassCastException if caller thread is not
-   * running in a FJTaskRunner thread.
-   **/
-
-  public static void yield() { getFJTaskRunner().taskYield(); }
-
-  /**
-   * Yield until this task isDone.
-   * Equivalent to <code>while(!isDone()) yield(); </code>
-   * @exception ClassCastException if caller thread is not
-   * running in a FJTaskRunner thread.
-   **/
-
-  public void join() { getFJTaskRunner().taskJoin(this);   }
-
-  /**
-   * Immediately execute task t by calling its run method. Has no
-   * effect if t has already been run or has been cancelled.
-   * It is equivalent to  calling t.run except that it
-   * deals with completion status, so should always be used
-   * instead of directly calling run.
-   * The method can be useful
-   * when a computation has been packaged as a FJTask, but you just need to 
-   * directly execute its body from within some other task.
-   **/
-
-  public static void invoke(FJTask t) {
-    if (!t.isDone()) { 
-      t.run(); 
-      t.setDone();
-    }
-  }
-
-  /**
-   * Fork both tasks and then wait for their completion. It behaves as:
-   * <pre>
-   * task1.fork(); task2.fork(); task2.join(); task1.join();
-   * </pre>
-   * As a simple classic example, here is
-   * a class that computes the Fibonacci function:
-   * <pre>
-   * public class Fib extends FJTask {
-   * 
-   *  // Computes fibonacci(n) = fibonacci(n-1) + fibonacci(n-2);  for n> 1
-   *  //          fibonacci(0) = 0; 
-   *  //          fibonacci(1) = 1.       
-   *
-   *  // Value to compute fibonacci function for.
-   *  // It is replaced with the answer when computed.
-   *  private volatile int number;
-   *
-   *  public Fib(int n) { number = n; }
-   *
-   *  public int getAnswer() {
-   *    if (!isDone()) throw new Error("Not yet computed");
-   *    return number;
-   *  }
-   *
-   *  public void run() {
-   *    int n = number;
-   *    if (n > 1) {
-   *      Fib f1 = new Fib(n - 1);
-   *      Fib f2 = new Fib(n - 2);
-   *
-   *      coInvoke(f1, f2); // run these in parallel
-   *
-   *      // we know f1 and f2 are computed, so just directly access numbers
-   *      number = f1.number + f2.number;
-   *    }
-   *  }
-   *
-   *  public static void main(String[] args) { // sample driver
-   *    try {
-   *      int groupSize = 2;    // 2 worker threads
-   *      int num = 35;         // compute fib(35)
-   *      FJTaskRunnerGroup group = new FJTaskRunnerGroup(groupSize);
-   *      Fib f = new Fib(num);
-   *      group.invoke(f);
-   *      int result = f.getAnswer();
-   *      System.out.println(" Answer: " + result);
-   *    }
-   *    catch (InterruptedException ex) {
-   *      System.out.println("Interrupted");
-   *    }
-   *  }
-   * }
-   * </pre>
-   *
-   * @exception ClassCastException if caller thread is not 
-   * running in a FJTaskRunner thread.
-   **/
-
-  public static void coInvoke(FJTask task1, FJTask task2) {
-    getFJTaskRunner().coInvoke(task1, task2);
-  }
-
-
-  /**
-   * Fork all tasks in array, and await their completion.
-   * Behaviorally equivalent to:
-   * <pre>
-   * for (int i = 0; i < tasks.length; ++i) tasks[i].fork();
-   * for (int i = 0; i < tasks.length; ++i) tasks[i].join();
-   * </pre>
-   **/
-
-  public static void coInvoke(FJTask[] tasks) {
-    getFJTaskRunner().coInvoke(tasks);
-  }
-
-  /**
-   * A FJTask that holds a Runnable r, and calls r.run when executed.
-   * The class is a simple utilty to allow arbitrary Runnables
-   * to be used as FJTasks.
-   **/
-
-  public static class Wrap extends FJTask {
-    protected final Runnable runnable;
-    public Wrap(Runnable r) { runnable = r; }
-    public void run() { runnable.run(); }
-  }
-
-
-  /**
-   * A  <code>new Seq</code>, when executed,
-   * invokes each task provided in the constructor,  in order. 
-   * The class is a simple utility
-   * that makes it easier to create composite FJTasks. 
-   **/
-  public static class Seq extends FJTask {
-    protected final FJTask[] tasks;
-
-    /**
-     * Construct a Seq that, when executed, will process each of the
-     * tasks in the tasks array in order
-     **/
-    public Seq(FJTask[] tasks) {
-      this.tasks = tasks;
-    }
-
-    /** 
-     * Two-task constructor, for compatibility with previous release.
-     **/
-    public Seq(FJTask task1, FJTask task2) {
-      this.tasks = new FJTask[] { task1, task2 };
-    }
-
-    public void run() {
-      for (int i = 0; i < tasks.length; ++i) FJTask.invoke(tasks[i]);
-    }
-  }
-
-  /** 
-   * Construct and return a FJTask object that, when executed, will
-   * invoke the tasks in the tasks array in array order
-   **/
-
-  public static FJTask seq(FJTask[] tasks) { 
-    return new Seq(tasks); 
-  }
-
-  /**
-   * A <code>new Par</code>, when executed,
-   * runs the tasks provided in the constructor in parallel using 
-   * coInvoke(tasks).
-   * The class is a simple utility
-   * that makes it easier to create composite FJTasks. 
-   **/
-  public static class Par extends FJTask {
-    protected final FJTask[] tasks;
-
-    /**
-     * Construct a Seq that, when executed, will process each of the
-     * tasks in the tasks array in parallel
-     **/
-    public Par(FJTask[] tasks) {
-      this.tasks = tasks;
-    }
-
-    /** 
-     * Two-task constructor, for compatibility with previous release.
-     **/
-    public Par(FJTask task1, FJTask task2) {
-      this.tasks = new FJTask[] { task1, task2 };
-    }
-
-
-    public void run() {
-      FJTask.coInvoke(tasks);
-    }
-  }
-
-
-  /** 
-   * Construct and return a FJTask object that, when executed, will
-   * invoke the tasks in the tasks array in parallel using coInvoke
-   **/
-  public static FJTask par(FJTask[] tasks) {
-    return new Par(tasks); 
-  }
-
-  /**
-   * A  <code>new Seq2(task1, task2)</code>, when executed,
-   * invokes task1 and then task2, in order. 
-   * The class is a simple utility
-   * that makes it easier to create composite Tasks. 
-   **/
-  public static class Seq2 extends FJTask {
-    protected final FJTask fst;
-    protected final FJTask snd;
-    public Seq2(FJTask task1, FJTask task2) {
-      fst = task1;
-      snd = task2;
-    }
-    public void run() {
-      FJTask.invoke(fst);
-      FJTask.invoke(snd);
-    }
-  }
-
-  /** 
-   * Construct and return a FJTask object that, when executed, will
-   * invoke task1 and task2, in order
-   **/
-
-  public static FJTask seq(FJTask task1, FJTask task2) { 
-    return new Seq2(task1, task2); 
-  }
-
-  /**
-   * A <code>new Par(task1, task2)</code>, when executed,
-   * runs task1 and task2 in parallel using coInvoke(task1, task2).
-   * The class is a simple utility
-   * that makes it easier to create composite Tasks. 
-   **/
-  public static class Par2 extends FJTask {
-    protected final FJTask fst;
-    protected final FJTask snd;
-    public Par2(FJTask task1, FJTask task2) {
-      fst = task1;
-      snd = task2;
-    }
-    public void run() {
-      FJTask.coInvoke(fst, snd);
-    }
-  }
-
-
-  /** 
-   * Construct and return a FJTask object that, when executed, will
-   * invoke task1 and task2, in parallel
-   **/
-  public static FJTask par(FJTask task1, FJTask task2) {
-    return new Par2(task1, task2); 
-  }
-
-}
diff --git a/src/actors/scala/actors/FJTaskRunner.java b/src/actors/scala/actors/FJTaskRunner.java
deleted file mode 100644
index 20cf60d..0000000
--- a/src/actors/scala/actors/FJTaskRunner.java
+++ /dev/null
@@ -1,996 +0,0 @@
-/*
-  File: FJTaskRunner.java
-
-  Originally written by Doug Lea and released into the public domain.
-  This may be used for any purposes whatsoever without acknowledgment.
-  Thanks for the assistance and support of Sun Microsystems Labs,
-  and everyone contributing, testing, and using this code.
-
-  History:
-  Date       Who                What
-  7Jan1999   dl                 First public release
-  13Jan1999  dl                 correct a stat counter update; 
-                                ensure inactive status on run termination;
-                                misc minor cleaup
-  14Jan1999  dl                 Use random starting point in scan;
-                                variable renamings.
-  18Jan1999  dl                 Runloop allowed to die on task exception;
-                                remove useless timed join
-  22Jan1999  dl                 Rework scan to allow use of priorities.
-  6Feb1999   dl                 Documentation updates.
-  7Mar1999   dl                 Add array-based coInvoke
-  31Mar1999  dl                 Revise scan to remove need for NullTasks
-  27Apr1999  dl                 Renamed
-  23oct1999  dl                 Earlier detect of interrupt in scanWhileIdling
-  24nov1999  dl                 Now works on JVMs that do not properly
-                                implement read-after-write of 2 volatiles.
-*/
-
-package scala.actors;
-
-import java.util.Random;
-
-/**
- * Specialized Thread subclass for running FJTasks.
- * <p>
- * Each FJTaskRunner keeps FJTasks in a double-ended queue (DEQ).
- * Double-ended queues support stack-based operations
- * push and pop, as well as queue-based operations put and take.
- * Normally, threads run their own tasks. But they
- * may also steal tasks from each others DEQs.
- * <p>
- * The algorithms are minor variants of those used
- * in <A href="http://supertech.lcs.mit.edu/cilk/"> Cilk</A> and
- * <A href="http://www.cs.utexas.edu/users/hood/"> Hood</A>, and
- * to a lesser extent 
- * <A href="http://www.cs.uga.edu/~dkl/filaments/dist.html"> Filaments</A>,
- * but are adapted to work in Java.
- * <p>
- * The two most important capabilities are:
- * <ul>
- *  <li> Fork a FJTask: 
- *  <pre>
- *  Push task onto DEQ
- *  </pre>
- *  <li> Get a task to run (for example within taskYield)
- *  <pre>
- *  If DEQ is not empty, 
- *     Pop a task and run it.
- *  Else if any other DEQ is not empty, 
- *     Take ("steal") a task from it and run it.
- *  Else if the entry queue for our group is not empty,
- *     Take a task from it and run it.
- *  Else if current thread is otherwise idling
- *     If all threads are idling
- *        Wait for a task to be put on group entry queue
- *  Else
- *      Yield or Sleep for a while, and then retry
- *  </pre>
- * </ul>
- * The push, pop, and put are designed to only ever called by the
- * current thread, and take (steal) is only ever called by
- * other threads.
- * All other operations are composites and variants of these,
- * plus a few miscellaneous bookkeeping methods.
- * <p>
- * Implementations of the underlying representations and operations
- * are geared for use on JVMs operating on multiple CPUs (although
- * they should of course work fine on single CPUs as well).
- * <p>
- * A possible snapshot of a FJTaskRunner's DEQ is:
- * <pre>
- *     0     1     2     3     4     5     6    ...
- *  +-----+-----+-----+-----+-----+-----+-----+--
- *  |     |  t  |  t  |  t  |  t  |     |     | ...  deq array
- *  +-----+-----+-----+-----+-----+-----+-----+--
- *           ^                       ^
- *          base                    top 
- *   (incremented                     (incremented 
- *       on take,                         on push    
- *    decremented                     decremented
- *       on put)                          on pop)
- * </pre>
- * <p>
- * FJTasks are held in elements of the DEQ. 
- * They are maintained in a bounded array that
- * works similarly to a circular bounded buffer. To ensure
- * visibility of stolen FJTasks across threads, the array elements
- * must be <code>volatile</code>. 
- * Using volatile rather than synchronizing suffices here since
- * each task accessed by a thread is either one that it
- * created or one that has never seen before. Thus we cannot
- * encounter any staleness problems executing run methods,
- * although FJTask programmers must be still sure to either synch or use
- * volatile for shared data within their run methods.
- * <p>
- * However, since there is no way
- * to declare an array of volatiles in Java, the DEQ elements actually
- * hold VolatileTaskRef objects, each of which in turn holds a
- * volatile reference to a FJTask. 
- * Even with the double-indirection overhead of 
- * volatile refs, using an array for the DEQ works out
- * better than linking them since fewer shared
- * memory locations need to be
- * touched or modified by the threads while using the DEQ.
- * Further, the double indirection may alleviate cache-line
- * sharing effects (which cannot otherwise be directly dealt with in Java).
- * <p>
- * The indices for the <code>base</code> and <code>top</code> of the DEQ
- * are declared as volatile. The main contention point with
- * multiple FJTaskRunner threads occurs when one thread is trying
- * to pop its own stack while another is trying to steal from it.
- * This is handled via a specialization of Dekker's algorithm,
- * in which the popping thread pre-decrements <code>top</code>,
- * and then checks it against <code>base</code>. 
- * To be conservative in the face of JVMs that only partially
- * honor the specification for volatile, the pop proceeds
- * without synchronization only if there are apparently enough
- * items for both a simultaneous pop and take to succeed.
- * It otherwise enters a 
- * synchronized lock to check if the DEQ is actually empty,
- * if so failing. The stealing thread
- * does almost the opposite, but is set up to be less likely
- * to win in cases of contention: Steals always run under synchronized
- * locks in order to avoid conflicts with other ongoing steals.
- * They pre-increment <code>base</code>, and then check against
- * <code>top</code>. They back out (resetting the base index 
- * and failing to steal) if the
- * DEQ is empty or is about to become empty by an ongoing pop.
- * <p>
- * A push operation can normally run concurrently with a steal.
- * A push enters a synch lock only if the DEQ appears full so must
- * either be resized or have indices adjusted due to wrap-around
- * of the bounded DEQ. The put operation always requires synchronization.
- * <p>
- * When a FJTaskRunner thread has no tasks of its own to run, 
- * it tries to be a good citizen. 
- * Threads run at lower priority while scanning for work.
- * <p>
- * If the task is currently waiting
- * via yield, the thread alternates scans (starting at a randomly 
- * chosen victim) with Thread.yields. This is
- * well-behaved so long as the JVM handles Thread.yield in a
- * sensible fashion. (It need not. Thread.yield is so underspecified
- * that it is legal for a JVM to treat it as a no-op.) This also
- * keeps things well-behaved even if we are running on a uniprocessor
- * JVM using a simple cooperative threading model.
- * <p>
- * If a thread needing work is
- * is otherwise idle (which occurs only in the main runloop), and
- * there are no available tasks to steal or poll, it
- * instead enters into a sleep-based (actually timed wait(msec))
- * phase in which it progressively sleeps for longer durations
- * (up to a maximum of FJTaskRunnerGroup.MAX_SLEEP_TIME,
- * currently 100ms) between scans. 
- * If all threads in the group
- * are idling, they further progress to a hard wait phase, suspending
- * until a new task is entered into the FJTaskRunnerGroup entry queue.
- * A sleeping FJTaskRunner thread may be awakened by a new
- * task being put into the group entry queue or by another FJTaskRunner
- * becoming active, but not merely by some DEQ becoming non-empty.
- * Thus the MAX_SLEEP_TIME provides a bound for sleep durations
- * in cases where all but one worker thread start sleeping
- * even though there will eventually be work produced
- * by a thread that is taking a long time to place tasks in DEQ.
- * These sleep mechanics are handled in the FJTaskRunnerGroup class.
- * <p>
- * Composite operations such as taskJoin include heavy
- * manual inlining of the most time-critical operations
- * (mainly FJTask.invoke). 
- * This opens up a few opportunities for further hand-optimizations. 
- * Until Java compilers get a lot smarter, these tweaks
- * improve performance significantly enough for task-intensive 
- * programs to be worth the poorer maintainability and code duplication.
- * <p>
- * Because they are so fragile and performance-sensitive, nearly
- * all methods are declared as final. However, nearly all fields
- * and methods are also declared as protected, so it is possible,
- * with much care, to extend functionality in subclasses. (Normally
- * you would also need to subclass FJTaskRunnerGroup.)
- * <p>
- * None of the normal java.lang.Thread class methods should ever be called
- * on FJTaskRunners. For this reason, it might have been nicer to
- * declare FJTaskRunner as a Runnable to run within a Thread. However,
- * this would have complicated many minor logistics. And since
- * no FJTaskRunner methods should normally be called from outside the
- * FJTask and FJTaskRunnerGroup classes either, this decision doesn't impact
- * usage.
- * <p>
- * You might think that layering this kind of framework on top of
- * Java threads, which are already several levels removed from raw CPU
- * scheduling on most systems, would lead to very poor performance. 
- * But on the platforms
- * tested, the performance is quite good.
- * <p>[<a href="http://gee.cs.oswego.edu/dl/classes/EDU/oswego/cs/dl/util/concurrent/intro.html"> Introduction to this package. </a>]
- * @see FJTask
- * @see FJTaskRunnerGroup
- **/
-
-public class FJTaskRunner extends Thread {
-  
-  /** The group of which this FJTaskRunner is a member **/
-  protected final IFJTaskRunnerGroup group;
-
-  /**
-   *  Constructor called only during FJTaskRunnerGroup initialization
-   **/
-
-    /*protected*/ public FJTaskRunner(IFJTaskRunnerGroup g) { 
-    group = g;
-    victimRNG = new Random(System.identityHashCode(this));
-    runPriority = getPriority();
-    setDaemon(true);
-  }
-
-  /**
-   * Return the FJTaskRunnerGroup of which this thread is a member
-   **/
-  
-  protected final IFJTaskRunnerGroup getGroup() { return group; }
-
-
-  /* ------------ DEQ Representation ------------------- */
-
-
-  /**
-   * FJTasks are held in an array-based DEQ with INITIAL_CAPACITY
-   * elements. The DEQ is grown if necessary, but default value is
-   * normally much more than sufficient unless  there are
-   * user programming errors or questionable operations generating
-   * large numbers of Tasks without running them.
-   * Capacities must be a power of two. 
-   **/
-
-  protected static final int INITIAL_CAPACITY = 4096; 
-
-  /**
-   * The maximum supported DEQ capacity.
-   * When exceeded, FJTaskRunner operations throw Errors
-   **/
-
-  protected static final int MAX_CAPACITY = 1 << 30;
-
-  /**
-   * An object holding a single volatile reference to a FJTask.
-   **/
-  
-  protected final static class VolatileTaskRef {
-    /** The reference **/
-    protected volatile FJTask ref;
-
-    /** Set the reference **/
-    protected final void put(FJTask r) { ref = r; }
-    /** Return the reference **/
-    protected final FJTask get()     { return ref; }
-    /** Return the reference and clear it **/
-    protected final FJTask take()    { FJTask r = ref; ref = null; return r;  }
-
-    /**
-     * Initialization utility for constructing arrays. 
-     * Make an array of given capacity and fill it with
-     * VolatileTaskRefs.
-     **/
-    protected static VolatileTaskRef[] newArray(int cap) {
-      VolatileTaskRef[] a = new VolatileTaskRef[cap];
-      for (int k = 0; k < cap; k++) a[k] = new VolatileTaskRef();
-      return a;
-    }
-
-  }
-
-  /**
-   * The DEQ array.
-   **/
-    
-  protected VolatileTaskRef[] deq = VolatileTaskRef.newArray(INITIAL_CAPACITY);
-
-  /** Current size of the task DEQ **/
-  protected int deqSize() { return deq.length; }
-
-  /** 
-   * Current top of DEQ. Generally acts just like a stack pointer in an 
-   * array-based stack, except that it circularly wraps around the
-   * array, as in an array-based queue. The value is NOT
-   * always kept within <code>0 ... deq.length</code> though. 
-   * The current top element is always at <code>top & (deq.length-1)</code>.
-   * To avoid integer overflow, top is reset down 
-   * within bounds whenever it is noticed to be out out bounds;
-   * at worst when it is at <code>2 * deq.length</code>.
-   **/
-  protected volatile int top = 0;
-
-
-  /** 
-   * Current base of DEQ. Acts like a take-pointer in an
-   * array-based bounded queue. Same bounds and usage as top.
-   **/
-
-  protected volatile int base = 0;
-
-
-  /**
-   * An extra object to synchronize on in order to
-   * achieve a memory barrier.
-   **/
-
-  protected final Object barrier = new Object();
-
-  /* ------------ Other BookKeeping ------------------- */
-
-  /**
-   * Record whether current thread may be processing a task
-   * (i.e., has been started and is not in an idle wait).
-   * Accessed, under synch, ONLY by FJTaskRunnerGroup, but the field is
-   * stored here for simplicity.
-   **/
-
-    /*protected*/ public boolean active = false;
-
-  /** Random starting point generator for scan() **/
-  protected final Random victimRNG;
-
-
-  /** Priority to use while scanning for work **/
-    protected int scanPriority = Thread.MIN_PRIORITY + 1;
-
-  /** Priority to use while running tasks **/
-  protected int runPriority;
-
-  /**
-   * Set the priority to use while scanning.
-   * We do not bother synchronizing access, since
-   * by the time the value is needed, both this FJTaskRunner 
-   * and its FJTaskRunnerGroup will
-   * necessarily have performed enough synchronization
-   * to avoid staleness problems of any consequence.
-   **/
-  protected void setScanPriority(int pri) { scanPriority = pri; }
-
-
-  /**
-   * Set the priority to use while running tasks.
-   * Same usage and rationale as setScanPriority.
-   **/
-  protected void setRunPriority(int pri) {  runPriority = pri; }
-
-  /**
-   * Compile-time constant for statistics gathering.
-   * Even when set, reported values may not be accurate
-   * since all are read and written without synchronization.
-   **/
-
-
-
-  static final boolean COLLECT_STATS = true;
-  // static final boolean COLLECT_STATS = false;
-
-
-  // for stat collection
-
-  /** Total number of tasks run **/
-  protected int runs = 0;
-
-  /** Total number of queues scanned for work **/
-  protected int scans = 0;
-
-  /** Total number of tasks obtained via scan **/
-  protected int steals = 0;
-
-
-
-    /* -------- Suspending -------- */
-    protected boolean suspending = false;
-
-    synchronized void setSuspending(boolean susp) {
-        suspending = susp;
-    }
-
-  /* ------------ DEQ operations ------------------- */
-
-
-  /**
-   * Push a task onto DEQ.
-   * Called ONLY by current thread.
-   **/
-
-    /*protected*/ public final void push(final FJTask r) {
-    int t = top;
-
-    /*
-      This test catches both overflows and index wraps.  It doesn't
-      really matter if base value is in the midst of changing in take. 
-      As long as deq length is < 2^30, we are guaranteed to catch wrap in
-      time since base can only be incremented at most length times
-      between pushes (or puts). 
-    */
-
-    if (t < (base & (deq.length-1)) + deq.length) {
-
-      deq[t & (deq.length-1)].put(r);
-      top = t + 1;
-    }
-
-    else  // isolate slow case to increase chances push is inlined
-      slowPush(r); // check overflow and retry
-  }
-
-
-  /**
-   * Handle slow case for push
-   **/
-
-  protected synchronized void slowPush(final FJTask r) {
-    checkOverflow();
-    push(r); // just recurse -- this one is sure to succeed.
-  }
-
-
-  /**
-   * Enqueue task at base of DEQ.
-   * Called ONLY by current thread.
-   * This method is currently not called from class FJTask. It could be used
-   * as a faster way to do FJTask.start, but most users would
-   * find the semantics too confusing and unpredictable.
-   **/
-
-  protected final synchronized void put(final FJTask r) {
-    for (;;) {
-      int b = base - 1;
-      if (top < b + deq.length) {
-        
-        int newBase = b & (deq.length-1);
-        deq[newBase].put(r);
-        base = newBase;
-        
-        if (b != newBase) { // Adjust for index underflow
-          int newTop = top & (deq.length-1);
-          if (newTop < newBase) newTop += deq.length;
-          top = newTop;
-        }
-        return;
-      }
-      else {
-        checkOverflow();
-        // ... and retry
-      }
-    }
-  }
-
-  /**
-   * Return a popped task, or null if DEQ is empty.
-   * Called ONLY by current thread.
-   * <p>
-   * This is not usually called directly but is
-   * instead inlined in callers. This version differs from the
-   * cilk algorithm in that pop does not fully back down and
-   * retry in the case of potential conflict with take. It simply
-   * rechecks under synch lock. This gives a preference
-   * for threads to run their own tasks, which seems to
-   * reduce flailing a bit when there are few tasks to run.
-   **/
-
-  protected final FJTask pop() {
-    /* 
-       Decrement top, to force a contending take to back down.
-    */
-
-    int t = --top;      
-
-    /*
-      To avoid problems with JVMs that do not properly implement
-      read-after-write of a pair of volatiles, we conservatively
-      grab without lock only if the DEQ appears to have at least two
-      elements, thus guaranteeing that both a pop and take will succeed,
-      even if the pre-increment in take is not seen by current thread.
-      Otherwise we recheck under synch.
-    */
-
-    if (base + 1 < t) 
-      return deq[t & (deq.length-1)].take();
-    else
-      return confirmPop(t);
-
-  }
-
-
-  /**
-   * Check under synch lock if DEQ is really empty when doing pop. 
-   * Return task if not empty, else null.
-   **/
-
-  protected final synchronized FJTask confirmPop(int provisionalTop) {
-    if (base <= provisionalTop) 
-      return deq[provisionalTop & (deq.length-1)].take();
-    else {    // was empty
-      /*
-        Reset DEQ indices to zero whenever it is empty.
-        This both avoids unnecessary calls to checkOverflow
-        in push, and helps keep the DEQ from accumulating garbage
-      */
-
-      top = base = 0;
-      return null;
-    }
-  }
-
-
-  /** 
-   * Take a task from the base of the DEQ.
-   * Always called by other threads via scan()
-   **/
-
-  
-  protected final synchronized FJTask take() {
-
-    /*
-      Increment base in order to suppress a contending pop
-    */
-    
-    int b = base++;     
-    
-    if (b < top) 
-      return confirmTake(b);
-    else {
-      // back out
-      base = b; 
-      return null;
-    }
-  }
-
-
-  /**
-   * double-check a potential take
-   **/
-  
-  protected FJTask confirmTake(int oldBase) {
-
-    /*
-      Use a second (guaranteed uncontended) synch
-      to serve as a barrier in case JVM does not
-      properly process read-after-write of 2 volatiles
-    */
-
-    synchronized(barrier) {
-      if (oldBase < top) {
-        /*
-          We cannot call deq[oldBase].take here because of possible races when
-          nulling out versus concurrent push operations.  Resulting
-          accumulated garbage is swept out periodically in
-          checkOverflow, or more typically, just by keeping indices
-          zero-based when found to be empty in pop, which keeps active
-          region small and constantly overwritten. 
-        */
-        
-        return deq[oldBase & (deq.length-1)].get();
-      }
-      else {
-        base = oldBase;
-        return null;
-      }
-    }
-  }
-
-
-  /**
-   * Adjust top and base, and grow DEQ if necessary.
-   * Called only while DEQ synch lock being held.
-   * We don't expect this to be called very often. In most
-   * programs using FJTasks, it is never called.
-   **/
-
-  protected void checkOverflow() { 
-    int t = top;
-    int b = base;
-    
-    if (t - b < deq.length-1) { // check if just need an index reset
-      
-      int newBase = b & (deq.length-1);
-      int newTop  = top & (deq.length-1);
-      if (newTop < newBase) newTop += deq.length;
-      top = newTop;
-      base = newBase;
-      
-      /* 
-         Null out refs to stolen tasks. 
-         This is the only time we can safely do it.
-      */
-      
-      int i = newBase;
-      while (i != newTop && deq[i].ref != null) {
-        deq[i].ref = null;
-        i = (i - 1) & (deq.length-1);
-      }
-      
-    }
-    else { // grow by doubling array
-      
-      int newTop = t - b;
-      int oldcap = deq.length;
-      int newcap = oldcap * 2;
-      
-      if (newcap >= MAX_CAPACITY)
-        throw new Error("FJTask queue maximum capacity exceeded");
-      
-      VolatileTaskRef[] newdeq = new VolatileTaskRef[newcap];
-      
-      // copy in bottom half of new deq with refs from old deq
-      for (int j = 0; j < oldcap; ++j) newdeq[j] = deq[b++ & (oldcap-1)];
-      
-      // fill top half of new deq with new refs
-      for (int j = oldcap; j < newcap; ++j) newdeq[j] = new VolatileTaskRef();
-      
-      deq = newdeq;
-      base = 0;
-      top = newTop;
-    }
-  }
-
-
-  /* ------------ Scheduling  ------------------- */
-
-
-  /**
-   * Do all but the pop() part of yield or join, by
-   * traversing all DEQs in our group looking for a task to
-   * steal. If none, it checks the entry queue. 
-   * <p>
-   * Since there are no good, portable alternatives,
-   * we rely here on a mixture of Thread.yield and priorities
-   * to reduce wasted spinning, even though these are
-   * not well defined. We are hoping here that the JVM
-   * does something sensible.
-   * @param waitingFor if non-null, the current task being joined
-   **/
-
-  protected void scan(final FJTask waitingFor) {
-
-    FJTask task = null;
-
-    // to delay lowering priority until first failure to steal
-    boolean lowered = false;
-    
-    /*
-      Circularly traverse from a random start index. 
-      
-      This differs slightly from cilk version that uses a random index
-      for each attempted steal.
-      Exhaustive scanning might impede analytic tractablity of 
-      the scheduling policy, but makes it much easier to deal with
-      startup and shutdown.
-    */
-    
-    FJTaskRunner[] ts = group.getArray();
-    int idx = victimRNG.nextInt(ts.length);
-    
-    for (int i = 0; i < ts.length; ++i) {
-      
-      FJTaskRunner t = ts[idx];
-      if (++idx >= ts.length) idx = 0; // circularly traverse
-      
-      if (t != null && t != this) {
-        
-        if (waitingFor != null && waitingFor.isDone()) {
-          break;
-        }
-        else {
-          if (COLLECT_STATS) ++scans;
-          task = t.take();
-          if (task != null) {
-            if (COLLECT_STATS) ++steals;
-            break;
-          }
-          else if (isInterrupted()) {
-            break;
-          }
-          else if (!lowered) { // if this is first fail, lower priority
-            lowered = true;
-            setPriority(scanPriority);
-          }
-          else {           // otherwise we are at low priority; just yield
-            yield();
-          }
-        }
-      }
-      
-    } 
-
-    if (task == null) {
-      if (COLLECT_STATS) ++scans;
-      task = group.pollEntryQueue();
-      if (COLLECT_STATS) if (task != null) ++steals;
-    }
-    
-    if (lowered) setPriority(runPriority);
-    
-    if (task != null && !task.isDone()) {
-      if (COLLECT_STATS) ++runs;
-      task.run(); 
-      task.setDone(); 
-    }
-
-  }
-
-  /**
-   * Same as scan, but called when current thread is idling.
-   * It repeatedly scans other threads for tasks,
-   * sleeping while none are available. 
-   * <p>
-   * This differs from scan mainly in that
-   * since there is no reason to return to recheck any
-   * condition, we iterate until a task is found, backing
-   * off via sleeps if necessary.
-   **/
-
-  protected void scanWhileIdling() {
-    FJTask task = null;
-    
-    boolean lowered = false;
-    long iters = 0;
-    
-    FJTaskRunner[] ts = group.getArray();
-    int idx = victimRNG.nextInt(ts.length);
-    
-    do {
-      for (int i = 0; i < ts.length; ++i) {
-        
-        FJTaskRunner t = ts[idx];
-        if (++idx >= ts.length) idx = 0; // circularly traverse
-        
-        if (t != null && t != this) {
-          if (COLLECT_STATS) ++scans;
-          
-          task = t.take();
-          if (task != null) {
-            if (COLLECT_STATS) ++steals;
-            if (lowered) setPriority(runPriority);
-            group.setActive(this);
-            break;
-          }
-        }
-      } 
-      
-      if (task == null) {
-        if (isInterrupted()) 
-          return;
-        
-        if (COLLECT_STATS) ++scans;
-        task = group.pollEntryQueue();
-        
-        if (task != null) {
-          if (COLLECT_STATS) ++steals;
-          if (lowered) setPriority(runPriority);
-          group.setActive(this);
-        }
-        else {
-          ++iters;
-          //  Check here for yield vs sleep to avoid entering group synch lock
-          if (iters >= /*group.SCANS_PER_SLEEP*/ 15) {
-            group.checkActive(this, iters);
-            if (isInterrupted())
-              return;
-          }
-          else if (!lowered) {
-            lowered = true;
-            setPriority(scanPriority);
-          }
-          else {
-            yield();
-          }
-        }
-      }
-    } while (task == null);
-
-
-    if (!task.isDone()) {
-      if (COLLECT_STATS) ++runs;
-      task.run(); 
-      task.setDone(); 
-    }
-    
-  }
-
-  /* ------------  composite operations ------------------- */
-
-    
-  /**
-   * Main runloop
-   **/
-
-  public void run() {
-    try{ 
-      while (!interrupted()) {
-        FJTask task = pop();
-        if (task != null) {
-          if (!task.isDone()) {
-            // inline FJTask.invoke
-            if (COLLECT_STATS) ++runs;
-            task.run(); 
-            task.setDone(); 
-          }
-        }
-        else
-          scanWhileIdling();
-      }
-      // check for suspending
-      if (suspending) {
-          synchronized(this) {
-              // move all local tasks to group-wide entry queue
-              for (int i = 0; i < deq.length; ++i) {
-                  synchronized(group) {
-                      try {
-                          FJTask task = (FJTask)deq[i].take();
-                          if (task != null)
-                              group.getEntryQueue().put(task);
-                      } catch (InterruptedException ie) {
-                          System.err.println("Suspend: when transferring task to entryQueue: "+ie);
-                      }
-                  }
-              }
-          }
-      }
-    }
-    finally {
-      group.setInactive(this);
-    }
-  }
-
-  /**
-   * Execute a task in this thread. Generally called when current task
-   * cannot otherwise continue.
-   **/
-
-    
-  protected final void taskYield() {
-    FJTask task = pop();
-    if (task != null) {
-      if (!task.isDone()) {
-        if (COLLECT_STATS) ++runs;
-        task.run(); 
-        task.setDone(); 
-      }
-    }
-    else
-      scan(null);
-  }
-
-
-  /**
-   * Process tasks until w is done.
-   * Equivalent to <code>while(!w.isDone()) taskYield(); </code>
-   **/
-
-  protected final void taskJoin(final FJTask w) {
-
-    while (!w.isDone()) { 
-
-      FJTask task = pop();
-      if (task != null) {
-        if (!task.isDone()) {
-          if (COLLECT_STATS) ++runs;
-          task.run(); 
-          task.setDone(); 
-          if (task == w) return; // fast exit if we just ran w
-        }
-      }
-      else
-        scan(w);
-    }
-  }
-
-  /**
-   * A specialized expansion of
-   * <code> w.fork(); invoke(v); w.join(); </code>
-   **/
-
-
-  protected final void coInvoke(final FJTask w, final FJTask v) {
-
-    // inline  push
-
-    int t = top;
-    if (t < (base & (deq.length-1)) + deq.length) {
-
-      deq[t & (deq.length-1)].put(w);
-      top = t + 1;
-
-      // inline  invoke
-
-      if (!v.isDone()) { 
-        if (COLLECT_STATS) ++runs; 
-        v.run(); 
-        v.setDone(); 
-      }
-      
-      // inline  taskJoin
-      
-      while (!w.isDone()) {
-        FJTask task  = pop();
-        if (task != null) {
-          if (!task.isDone()) {
-            if (COLLECT_STATS) ++runs;
-            task.run(); 
-            task.setDone(); 
-            if (task == w) return; // fast exit if we just ran w
-          }
-        }
-        else
-          scan(w);
-      }
-    }
-
-    else      // handle non-inlinable cases
-      slowCoInvoke(w, v);
-  }
-
-
-  /**
-   * Backup to handle noninlinable cases of coInvoke
-   **/
-
-  protected void slowCoInvoke(final FJTask w, final FJTask v) {
-    push(w); // let push deal with overflow
-    FJTask.invoke(v);
-    taskJoin(w);
-  }
-
-
-  /**
-   * Array-based version of coInvoke
-   **/
-
-  protected final void coInvoke(FJTask[] tasks) {
-    int nforks = tasks.length - 1;
-
-    // inline bulk push of all but one task
-
-    int t = top;
-
-    if (nforks >= 0 && t + nforks < (base & (deq.length-1)) + deq.length) {
-      for (int i = 0; i < nforks; ++i) {
-        deq[t++ & (deq.length-1)].put(tasks[i]);
-        top = t;
-      }
-
-      // inline invoke of one task
-      FJTask v = tasks[nforks];
-      if (!v.isDone()) { 
-        if (COLLECT_STATS) ++runs; 
-        v.run(); 
-        v.setDone(); 
-      }
-      
-      // inline  taskJoins
-      
-      for (int i = 0; i < nforks; ++i) { 
-        FJTask w = tasks[i];
-        while (!w.isDone()) {
-
-          FJTask task = pop();
-          if (task != null) {
-            if (!task.isDone()) {
-              if (COLLECT_STATS) ++runs;
-              task.run(); 
-              task.setDone(); 
-            }
-          }
-          else
-            scan(w);
-        }
-      }
-    }
-
-    else  // handle non-inlinable cases
-      slowCoInvoke(tasks);
-  }
-
-  /**
-   * Backup to handle atypical or noninlinable cases of coInvoke
-   **/
-
-  protected void slowCoInvoke(FJTask[] tasks) {
-    for (int i = 0; i < tasks.length; ++i) push(tasks[i]);
-    for (int i = 0; i < tasks.length; ++i) taskJoin(tasks[i]);
-  }
-
-}
-
diff --git a/src/actors/scala/actors/FJTaskRunnerGroup.java b/src/actors/scala/actors/FJTaskRunnerGroup.java
deleted file mode 100644
index 161b626..0000000
--- a/src/actors/scala/actors/FJTaskRunnerGroup.java
+++ /dev/null
@@ -1,714 +0,0 @@
-/*
-  File: FJTaskRunnerGroup.java
-
-  Originally written by Doug Lea and released into the public domain.
-  This may be used for any purposes whatsoever without acknowledgment.
-  Thanks for the assistance and support of Sun Microsystems Labs,
-  and everyone contributing, testing, and using this code.
-
-  History:
-  Date       Who                What
-  7Jan1999   dl                 First public release
-  12Jan1999  dl                 made getActiveCount public; misc minor cleanup.
-  14Jan1999  dl                 Added executeTask
-  20Jan1999  dl                 Allow use of priorities; reformat stats
-  6Feb1999   dl                 Lazy thread starts
-  27Apr1999  dl                 Renamed
-*/
-
-package scala.actors;
-
-/**
- * A stripped down analog of a ThreadGroup used for
- * establishing and managing FJTaskRunner threads.
- * ThreadRunnerGroups serve as the control boundary separating
- * the general world of normal threads from the specialized world
- * of FJTasks. 
- * <p>
- * By intent, this class does not subclass java.lang.ThreadGroup, and
- * does not support most methods found in ThreadGroups, since they
- * would make no sense for FJTaskRunner threads. In fact, the class
- * does not deal with ThreadGroups at all. If you want to restrict
- * a FJTaskRunnerGroup to a particular ThreadGroup, you can create
- * it from within that ThreadGroup.
- * <p>
- * The main contextual parameter for a FJTaskRunnerGroup is
- * the group size, established in the constructor. 
- * Groups must be of a fixed size.
- * There is no way to dynamically increase or decrease the number
- * of threads in an existing group.
- * <p>
- * In general, the group size should be equal to the number
- * of CPUs on the system. (Unfortunately, there is no portable
- * means of automatically detecting the number of CPUs on a JVM, so there is
- * no good way to automate defaults.)  In principle, when
- * FJTasks are used for computation-intensive tasks, having only 
- * as many threads as CPUs should minimize bookkeeping overhead
- * and contention, and so maximize throughput. However, because
- * FJTaskRunners lie atop Java threads, and in turn operating system
- * thread support and scheduling policies, 
- * it is very possible that using more threads
- * than CPUs will improve overall throughput even though it adds
- * to overhead. This will always be so if FJTasks are I/O bound.
- * So it may pay to experiment a bit when tuning on particular platforms.
- * You can also use <code>setRunPriorities</code> to either
- * increase or decrease the priorities of active threads, which
- * may interact with group size choice.
- * <p>
- * In any case, overestimating group sizes never
- * seriously degrades performance (at least within reasonable bounds). 
- * You can also use a value
- * less than the number of CPUs in order to reserve processing
- * for unrelated threads. 
- * <p>
- * There are two general styles for using a FJTaskRunnerGroup.
- * You can create one group per entire program execution, for example 
- * as a static singleton, and use it for all parallel tasks:
- * <pre>
- * class Tasks {
- *   static FJTaskRunnerGroup group;
- *   public void initialize(int groupsize) {
- *      group = new FJTaskRunnerGroup(groupSize);
- *   }
- *   // ...
- * }
- * </pre>
- * Alternatively, you can make new groups on the fly and use them only for
- * particular task sets. This is more flexible,,
- * and leads to more controllable and deterministic execution patterns,
- * but it encounters greater overhead on startup. Also, to reclaim
- * system resources, you should
- * call <code>FJTaskRunnerGroup.interruptAll</code> when you are done
- * using one-shot groups. Otherwise, because FJTaskRunners set 
- * <code>Thread.isDaemon</code>
- * status, they will not normally be reclaimed until program termination.
- * <p>
- * The main supported methods are <code>execute</code>,
- * which starts a task processed by FJTaskRunner threads,
- * and <code>invoke</code>, which starts one and waits for completion.
- * For example, you might extend the above <code>FJTasks</code>
- * class to support a task-based computation, say, the
- * <code>Fib</code> class from the <code>FJTask</code> documentation:
- * <pre>
- * class Tasks { // continued
- *   // ...
- *   static int fib(int n) {
- *     try {
- *       Fib f = new Fib(n);
- *       group.invoke(f);
- *       return f.getAnswer();
- *     }
- *     catch (InterruptedException ex) {
- *       throw new Error("Interrupted during computation");
- *     }
- *   }
- * }
- * </pre>
- * <p>
- * Method <code>stats()</code> can be used to monitor performance.
- * Both FJTaskRunnerGroup and FJTaskRunner may be compiled with
- * the compile-time constant COLLECT_STATS set to false. In this
- * case, various simple counts reported in stats() are not collected.
- * On platforms tested,
- * this leads to such a tiny performance improvement that there is 
- * very little motivation to bother.
- *
- * <p>[<a href="http://gee.cs.oswego.edu/dl/classes/EDU/oswego/cs/dl/util/concurrent/intro.html"> Introduction to this package. </a>]
- * <p>
- * @see FJTask
- * @see FJTaskRunner
- **/
-
-public class FJTaskRunnerGroup implements IFJTaskRunnerGroup {
-
-  /** The threads in this group **/
-    /*protected*/ /*final*/ FJTaskRunner[] threads;
-
-  /** Group-wide queue for tasks entered via execute() **/
-    /*protected*/ final LinkedQueue entryQueue = new LinkedQueue();
-
-    public LinkedQueue getEntryQueue() {
-        return entryQueue;
-    }
-
-  /** Number of threads that are not waiting for work **/
-  protected int activeCount = 0;
-
-  /** Number of threads that have been started. Used to avoid
-      unecessary contention during startup of task sets.
-  **/
-  protected int nstarted = 0;
-
-  /**
-   * Compile-time constant. If true, various counts of
-   * runs, waits, etc., are maintained. These are NOT
-   * updated with synchronization, so statistics reports
-   * might not be accurate.
-   **/
-  
-  static final boolean COLLECT_STATS = true;
-  //  static final boolean COLLECT_STATS = false;
-
-  // for stats
-
-  /** The time at which this ThreadRunnerGroup was constructed **/
-  long initTime = 0;
-
-  /** Total number of executes or invokes **/
-  int entries = 0;
-
-  static final int DEFAULT_SCAN_PRIORITY = Thread.MIN_PRIORITY+1;
-
-    /* -------- Suspending -------- */
-
-    LinkedQueue snapshot() throws InterruptedException {
-        synchronized (this) {
-            for (int i = 0; i < threads.length; ++i) {
-                FJTaskRunner t = threads[i];
-                // set flag in all task runners to suspend
-                t.setSuspending(true);
-                // interrupt all task runners
-                // assume: current thread not in threads (scheduler)
-                t.interrupt();
-            }
-        }
-
-        // wait until all of them have terminated
-        for (int i = 0; i < threads.length; ++i) {
-            Thread t = threads[i];
-            t.join();
-        };
-
-        return entryQueue;
-    }
-
-  /** 
-   * Create a FJTaskRunnerGroup with the indicated number
-   * of FJTaskRunner threads. Normally, the best size to use is
-   * the number of CPUs on the system. 
-   * <p>
-   * The threads in a FJTaskRunnerGroup are created with their
-   * isDaemon status set, so do not normally need to be
-   * shut down manually upon program termination.
-   **/
-
-  public FJTaskRunnerGroup(int groupSize) { 
-      //System.out.println("Creating FJTaskRunnerGroup of size "+groupSize);
-    threads = new FJTaskRunner[groupSize];
-    initializeThreads();
-    initTime = System.currentTimeMillis();
-  }
-
-
-    public boolean existsTask() {
-        FJTask task = null;
-        /*
-          Circularly traverse from a random start index. 
-          
-          This differs slightly from cilk version that uses a random index
-          for each attempted steal.
-          Exhaustive scanning might impede analytic tractablity of 
-          the scheduling policy, but makes it much easier to deal with
-          startup and shutdown.
-        */
-        
-        FJTaskRunner[] ts = threads;
-        int idx = /*victimRNG.nextInt(ts.length)*/ 0;
-
-        for (int i = 0; i < ts.length; ++i) {
-            FJTaskRunner t = ts[idx];
-            if (++idx >= ts.length) idx = 0; // circularly traverse
-
-            if (t != null) {
-                task = t.take();
-                if (task != null) {
-                    break;
-                }
-            }
-        }
-
-        if (task == null) {
-            task = pollEntryQueue();
-        }
-
-        if (task != null && !task.isDone()) {
-            boolean quit = false;
-            while (!quit) {
-                quit = true;
-                try {
-                    // put task back into entry queue and return true
-                    entryQueue.put(task);
-                } catch (InterruptedException ie) {
-                    quit = false;
-                }
-            }
-            return true;
-        }
-        else return false;
-    }
-
-    public boolean checkPoolSize() {
-        // if there is a task in the entryQueue or any of the
-        // worker queues, increase thread pool size by one
-        if (!entryQueue.isEmpty() ||
-            existsTask()) {
-            int newsize = threads.length + 1;
-            FJTaskRunner[] newar = new FJTaskRunner[newsize];
-            System.arraycopy(threads, 0, newar, 0, newsize-1);
-            synchronized(this) {
-                threads = newar;
-                FJTaskRunner t = new FJTaskRunner(this);
-                threads[newsize-1] = t;
-                setActive(t);
-            }
-            return true;
-        }
-        else return false;
-    }
-
-
-  /**
-   * Arrange for execution of the given task
-   * by placing it in a work queue. If the argument
-   * is not of type FJTask, it is embedded in a FJTask via 
-   * <code>FJTask.Wrap</code>.
-   * @exception InterruptedException if current Thread is
-   * currently interrupted 
-   **/
-
-  public void execute(Runnable r) throws InterruptedException {
-    if (r instanceof FJTask) {
-      entryQueue.put((FJTask)r);
-    }
-    else {
-      entryQueue.put(new FJTask.Wrap(r));
-    }
-    signalNewTask();
-  }
-
-
-  /**
-   * Specialized form of execute called only from within FJTasks
-   **/
-  public void executeTask(FJTask t) {
-    try {
-      entryQueue.put(t);
-      signalNewTask();
-    }
-    catch (InterruptedException ex) {
-      Thread.currentThread().interrupt();
-    }
-  }
-
-
-  /**
-   * Start a task and wait it out. Returns when the task completes.
-   * @exception InterruptedException if current Thread is
-   * interrupted before completion of the task.
-   **/
-
-  public void invoke(Runnable r) throws InterruptedException {
-    InvokableFJTask w = new InvokableFJTask(r);
-    entryQueue.put(w);
-    signalNewTask();
-    w.awaitTermination();
-  }
-
-
-  /**
-   * Try to shut down all FJTaskRunner threads in this group
-   * by interrupting them all. This method is designed
-   * to be used during cleanup when it is somehow known
-   * that all threads are idle.
-   * FJTaskRunners only
-   * check for interruption when they are not otherwise
-   * processing a task (and its generated subtasks,
-   * if any), so if any threads are active, shutdown may
-   * take a while, and may lead to unpredictable
-   * task processing.
-   **/
-
-  public void interruptAll() {
-    // paranoically interrupt current thread last if in group.
-    Thread current = Thread.currentThread();
-    boolean stopCurrent = false;
-
-    for (int i = 0; i < threads.length; ++i) {
-      Thread t = threads[i];
-      if (t == current) 
-        stopCurrent = true;
-      else
-        t.interrupt();
-    }
-    if (stopCurrent)
-      current.interrupt();
-  }
-
-
-  /**
-   * Set the priority to use while a FJTaskRunner is
-   * polling for new tasks to perform. Default
-   * is currently Thread.MIN_PRIORITY+1. The value
-   * set may not go into effect immediately, but
-   * will be used at least the next time a thread scans for work.
-   **/
-  public synchronized void setScanPriorities(int pri) {
-    for (int i = 0; i < threads.length; ++i) {
-      FJTaskRunner t = threads[i];
-      t.setScanPriority(pri);
-      if (!t.active) t.setPriority(pri);
-    }
-  }
-
-
-  /**
-   * Set the priority to use while a FJTaskRunner is
-   * actively running tasks. Default
-   * is the priority that was in effect by the thread that
-   * constructed this FJTaskRunnerGroup. Setting this value
-   * while threads are running may momentarily result in
-   * them running at this priority even when idly waiting for work.
-   **/
-  public synchronized void setRunPriorities(int pri) {
-    for (int i = 0; i < threads.length; ++i) {
-      FJTaskRunner t = threads[i];
-      t.setRunPriority(pri);
-      if (t.active) t.setPriority(pri);
-    }
-  }
-
-    
-
-  /** Return the number of FJTaskRunner threads in this group **/
-
-  public int size() { return threads.length; }
-
-
-  /** 
-   * Return the number of threads that are not idly waiting for work.
-   * Beware that even active threads might not be doing any useful
-   * work, but just spinning waiting for other dependent tasks.
-   * Also, since this is just a snapshot value, some tasks
-   * may be in the process of becoming idle.
-   **/
-  public synchronized int getActiveCount() { return activeCount; }
-
-  /**
-   * Prints various snapshot statistics to System.out.
-   * <ul>
-   *   <li> For each FJTaskRunner thread (labeled as T<em>n</em>, for
-   *         <em>n</em> from zero to group size - 1):
-   *     <ul>
-   *       <li> A star "*" is printed if the thread is currently active;
-   *            that is, not sleeping while waiting for work. Because
-   *            threads gradually enter sleep modes, an active thread
-   *            may in fact be about to sleep (or wake up).
-   *       <li> <em>Q Cap</em> The current capacity of its task queue.
-   *       <li> <em>Run</em> The total number of tasks that have been run.
-   *       <li> <em>New</em> The number of these tasks that were
-   *               taken from either the entry queue or from other 
-   *               thread queues; that is, the number of tasks run
-   *               that were <em>not</em> forked by the thread itself.
-   *       <li> <em>Scan</em> The number of times other task
-   *               queues or the entry queue were polled for tasks.
-   *     </ul>
-   *   <li> <em>Execute</em> The total number of tasks entered
-   *        (but not necessarily yet run) via execute or invoke.
-   *   <li> <em>Time</em> Time in seconds since construction of this
-   *         FJTaskRunnerGroup.
-   *   <li> <em>Rate</em> The total number of tasks processed
-   *          per second across all threads. This
-   *          may be useful as a simple throughput indicator
-   *          if all processed tasks take approximately the
-   *          same time to run.
-   * </ul>
-   * <p>
-   * Cautions: Some statistics are updated and gathered 
-   * without synchronization,
-   * so may not be accurate. However, reported counts may be considered
-   * as lower bounds of actual values. 
-   * Some values may be zero if classes are compiled
-   * with COLLECT_STATS set to false. (FJTaskRunner and FJTaskRunnerGroup
-   * classes can be independently compiled with different values of
-   * COLLECT_STATS.) Also, the counts are maintained as ints so could
-   * overflow in exceptionally long-lived applications.
-   * <p>
-   * These statistics can be useful when tuning algorithms or diagnosing
-   * problems. For example:
-   * <ul>
-   *  <li> High numbers of scans may mean that there is insufficient
-   *      parallelism to keep threads busy. However, high scan rates
-   *      are expected if the number
-   *      of Executes is also high or there is a lot of global
-   *      synchronization in the application, and the system is not otherwise
-   *      busy. Threads may scan
-   *      for work hundreds of times upon startup, shutdown, and
-   *      global synch points of task sets.
-   *  <li> Large imbalances in tasks run across different threads might
-   *      just reflect contention with unrelated threads on a system
-   *      (possibly including JVM threads such as GC), but may also
-   *      indicate some systematic bias in how you generate tasks.
-   *  <li> Large task queue capacities may mean that too many tasks are being
-   *     generated before they can be run. 
-   *     Capacities are reported rather than current numbers of tasks
-   *     in queues because they are better indicators of the existence
-   *     of these kinds of possibly-transient problems.
-   *     Queue capacities are
-   *     resized on demand from their initial value of 4096 elements,
-   *     which is much more than sufficient for the kinds of 
-   *     applications that this framework is intended to best support.
-   * </ul>
-   **/
-
-  public void stats() {
-    long time = System.currentTimeMillis() - initTime;
-    double secs = ((double)time) / 1000.0;
-    long totalRuns = 0;
-    long totalScans = 0;
-    long totalSteals = 0;
-
-    System.out.print("Thread" +
-                     "\tQ Cap" +
-                       "\tScans" +
-                       "\tNew" +
-                       "\tRuns" +
-                       "\n");
-
-    for (int i = 0; i < threads.length; ++i) {
-      FJTaskRunner t = threads[i];
-      int truns = t.runs;
-      totalRuns += truns;
-
-      int tscans = t.scans;
-      totalScans += tscans;
-
-      int tsteals = t.steals;
-      totalSteals += tsteals;
-
-      String star = (getActive(t))? "*" : " ";
-
-
-      System.out.print("T" + i + star +
-                       "\t" + t.deqSize() +
-                       "\t" + tscans +
-                       "\t" + tsteals +
-                       "\t" + truns +
-                       "\n");
-    }
-
-    System.out.print("Total" +
-                     "\t    " +
-                     "\t" + totalScans +
-                     "\t" + totalSteals +
-                     "\t" + totalRuns +
-                     "\n");
-
-    System.out.print("Execute: " + entries); 
-    
-    System.out.print("\tTime: " + secs);
-
-    long rps = 0;
-    if (secs != 0) rps = Math.round((double)(totalRuns) / secs);
-
-    System.out.println("\tRate: " + rps);
-  }
-
-
-  /* ------------ Methods called only by FJTaskRunners ------------- */
-
-
-  /**
-   * Return the array of threads in this group. 
-   * Called only by FJTaskRunner.scan().
-   **/
-
-  public FJTaskRunner[] getArray() { return threads; }
-
-
-  /**
-   * Return a task from entry queue, or null if empty.
-   * Called only by FJTaskRunner.scan().
-   **/
-
-  public FJTask pollEntryQueue() {
-    try {
-      FJTask t = (FJTask)(entryQueue.poll(0));
-      return t;
-    }
-    catch(InterruptedException ex) { // ignore interrupts
-      Thread.currentThread().interrupt();
-      return null;
-    }
-  }
-
-
-  /**
-   * Return active status of t.
-   * Per-thread active status can only be accessed and
-   * modified via synchronized method here in the group class.
-   **/
-
-  protected synchronized boolean getActive(FJTaskRunner t) {
-    return t.active;
-  }
-
-
-  /**
-   * Set active status of thread t to true, and notify others
-   * that might be waiting for work. 
-   **/
-
-  public synchronized void setActive(FJTaskRunner t) {
-    if (!t.active) { 
-      t.active = true;
-      ++activeCount;
-      if (nstarted < threads.length) 
-        threads[nstarted++].start();
-      else
-        notifyAll();
-    }
-  }
-
-  /**
-   * Set active status of thread t to false.
-   **/
-
-  public synchronized void setInactive(FJTaskRunner t) {
-    if (t.active) { 
-      t.active = false;
-      --activeCount;
-    }
-  }
-
-  /**
-   * The number of times to scan other threads for tasks 
-   * before transitioning to a mode where scans are
-   * interleaved with sleeps (actually timed waits).
-   * Upon transition, sleeps are for duration of
-   * scans / SCANS_PER_SLEEP milliseconds.
-   * <p>
-   * This is not treated as a user-tunable parameter because
-   * good values do not appear to vary much across JVMs or
-   * applications. Its main role is to help avoid some
-   * useless spinning and contention during task startup.
-   **/
-  static final long SCANS_PER_SLEEP = 15;
-
-  /**
-   * The maximum time (in msecs) to sleep when a thread is idle,
-   * yet others are not, so may eventually generate work that
-   * the current thread can steal. This value reflects the maximum time
-   * that a thread may sleep when it possibly should not, because there
-   * are other active threads that might generate work. In practice,
-   * designs in which some threads become stalled because others
-   * are running yet not generating tasks are not likely to work
-   * well in this framework anyway, so the exact value does not matter
-   * too much. However, keeping it in the sub-second range does
-   * help smooth out startup and shutdown effects.
-   **/
-
-  static final long MAX_SLEEP_TIME = 100;
-
-  /**
-   * Set active status of thread t to false, and
-   * then wait until: (a) there is a task in the entry 
-   * queue, or (b) other threads are active, or (c) the current
-   * thread is interrupted. Upon return, it
-   * is not certain that there will be work available.
-   * The thread must itself check. 
-   * <p>
-   * The main underlying reason
-   * for these mechanics is that threads do not
-   * signal each other when they add elements to their queues.
-   * (This would add to task overhead, reduce locality.
-   * and increase contention.)
-   * So we must rely on a tamed form of polling. However, tasks
-   * inserted into the entry queue do result in signals, so
-   * tasks can wait on these if all of them are otherwise idle.
-   **/
-
-  public synchronized void checkActive(FJTaskRunner t, long scans) {
-
-    setInactive(t);
-
-    try {
-      // if nothing available, do a hard wait
-      if (activeCount == 0 && entryQueue.peek() == null) { 
-        wait();
-      }
-      else { 
-        // If there is possibly some work,
-        // sleep for a while before rechecking 
-
-        long msecs = scans / SCANS_PER_SLEEP;
-        if (msecs > MAX_SLEEP_TIME) msecs = MAX_SLEEP_TIME;
-        int nsecs = (msecs == 0) ? 1 : 0; // forces shortest possible sleep
-        wait(msecs, nsecs);
-      }
-    }
-    catch (InterruptedException ex) {
-      notify(); // avoid lost notifies on interrupts
-      Thread.currentThread().interrupt();
-    }
-  }
-
-  /* ------------ Utility methods  ------------- */
-
-  /**
-   * Start or wake up any threads waiting for work
-   **/
-
-  protected synchronized void signalNewTask() {
-    if (COLLECT_STATS) ++entries;
-    if (nstarted < threads.length) 
-       threads[nstarted++].start();
-    else
-      notify();
-  }
-
-  /**
-   * Create all FJTaskRunner threads in this group.
-   **/
-
-  protected void initializeThreads() {
-    for (int i = 0; i < threads.length; ++i) threads[i] = new FJTaskRunner(this);
-  }
-
-
-
-
-  /**
-   * Wrap wait/notify mechanics around a task so that
-   * invoke() can wait it out 
-   **/
-  protected static final class InvokableFJTask extends FJTask {
-    protected final Runnable wrapped;
-    protected boolean terminated = false;
-
-    protected InvokableFJTask(Runnable r) { wrapped = r; }
-
-    public void run() {
-      try {
-        if (wrapped instanceof FJTask)
-          FJTask.invoke((FJTask)(wrapped));
-        else
-          wrapped.run();
-      }
-      finally {
-        setTerminated();
-      }
-    }
-
-    protected synchronized void setTerminated() {
-      terminated = true;
-      notifyAll(); 
-    }
-
-    protected synchronized void awaitTermination() throws InterruptedException {
-      while (!terminated) wait();
-    }
-  }
-
-
-}
-
diff --git a/src/actors/scala/actors/FJTaskScheduler2.scala b/src/actors/scala/actors/FJTaskScheduler2.scala
deleted file mode 100644
index dbb4d8b..0000000
--- a/src/actors/scala/actors/FJTaskScheduler2.scala
+++ /dev/null
@@ -1,201 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2005-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: FJTaskScheduler2.scala 18846 2009-10-01 07:30:14Z phaller $
-
-package scala.actors
-
-import java.lang.{Runnable, Thread, InterruptedException, System, Runtime}
-import scala.actors.threadpool.{ThreadPoolExecutor, TimeUnit, LinkedBlockingQueue}
-
-/**
- * FJTaskScheduler2
- *
- * @version 0.9.19
- * @author Philipp Haller
- */
-class FJTaskScheduler2 extends Thread with IScheduler {
-  // as long as this thread runs, JVM should not exit
-  setDaemon(false)
-
-  @deprecated var printStats = false
-
-  @deprecated val rt = Runtime.getRuntime()
-  private val numCores = rt.availableProcessors()
-  @deprecated val minNumThreads = 4
-
-  @deprecated val coreProp = try {
-    System.getProperty("actors.corePoolSize")
-  } catch {
-    case ace: java.security.AccessControlException =>
-      null
-  }
-  @deprecated val maxProp =
-    try {
-      System.getProperty("actors.maxPoolSize")
-    } catch {
-      case ace: java.security.AccessControlException =>
-        null
-    }
-  @deprecated val timeFreqProp =
-    try {
-      System.getProperty("actors.timeFreq")
-    } catch {
-      case ace: java.security.AccessControlException =>
-        null
-    }
-
-  val initCoreSize =
-    if (null ne coreProp) Integer.parseInt(coreProp)
-    else {
-      if (2 * numCores > minNumThreads)
-        2 * numCores
-      else
-        minNumThreads
-    }
-
-  val maxSize =
-    if (null ne maxProp) Integer.parseInt(maxProp)
-    else 256
-
-  @deprecated val timeFreq =
-    if (null ne timeFreqProp) Integer.parseInt(timeFreqProp)
-    else 10
-
-  private var coreSize = initCoreSize
-
-  Debug.info(this+": corePoolSize = "+coreSize+", maxPoolSize = "+maxSize)
-
-  private val executor = {
-    val workQueue = new LinkedBlockingQueue[Runnable]
-
-    new ThreadPoolExecutor(coreSize,
-                           maxSize,
-                           60000L,
-                           TimeUnit.MILLISECONDS,
-                           workQueue,
-                           new ThreadPoolExecutor.CallerRunsPolicy)
-  }
-
-  @volatile private var terminating = false
-  private var suspending = false
-
-  private var submittedTasks = 0
-
-  @deprecated def printActorDump {}
-
-  private val TICK_FREQ = 50
-  private val CHECK_FREQ = timeFreq
-
-  @deprecated def onLockup(handler: () => Unit) =
-    lockupHandler = handler
-
-  @deprecated def onLockup(millis: Int)(handler: () => Unit) = {
-    //LOCKUP_CHECK_FREQ = millis / CHECK_FREQ
-    lockupHandler = handler
-  }
-
-  private var lockupHandler: () => Unit = null
-
-  private def numWorkersBlocked = {
-    executor.mainLock.lock()
-    val iter = executor.workers.iterator()
-    var numBlocked = 0
-    while (iter.hasNext()) {
-      val w = iter.next().asInstanceOf[ThreadPoolExecutor#Worker]
-      if (w.tryLock()) {
-        // worker is idle
-        w.unlock()
-      } else {
-        val s = w.thread.getState()
-        if (s == Thread.State.WAITING || s == Thread.State.TIMED_WAITING)
-          numBlocked += 1
-      }
-    }
-    executor.mainLock.unlock()
-    numBlocked
-  }
-
-  override def run() {
-    try {
-      while (!terminating) {
-        this.synchronized {
-          try {
-            wait(CHECK_FREQ)
-          } catch {
-            case _: InterruptedException =>
-              if (terminating) throw new QuitException
-          }
-
-          if (!suspending) {
-            // check if we need more worker threads
-            val activeBlocked = numWorkersBlocked
-            if (coreSize - activeBlocked < numCores && coreSize < maxSize) {
-              coreSize = numCores + activeBlocked
-              Debug.info(this+": increasing thread pool size to "+coreSize)
-              executor.setCorePoolSize(coreSize)
-            } else {
-              if (ActorGC.allTerminated) {
-                // if all worker threads idle terminate
-                if (executor.getActiveCount() == 0) {
-                  Debug.info(this+": initiating shutdown...")
-                  Debug.info(this+": corePoolSize = "+coreSize+", maxPoolSize = "+maxSize)
-
-                  terminating = true
-                  throw new QuitException
-                }
-              }
-            }
-          }
-        } // sync
-
-      } // while (!terminating)
-    } catch {
-      case _: QuitException =>
-        // allow thread to exit
-        //if (printStats) executor.stats()
-        executor.shutdown()
-    }
-  }
-
-  /**
-   *  @param  task the task to be executed
-   */
-  def execute(task: Runnable): Unit =
-    executor execute task
-
-  def execute(fun: => Unit): Unit =
-    executor.execute(new Runnable {
-      def run() { fun }
-    })
-
-  /**
-   *  @param  a the actor
-   */
-  def tick(a: Actor) = {}
-
-  /** Shuts down all idle worker threads.
-   */
-  def shutdown(): Unit = synchronized {
-    terminating = true
-  }
-
-  @deprecated def snapshot(): LinkedQueue = {
-    suspending = true
-    val tasks: java.util.List[_] = executor.shutdownNow()
-    val linkedQ = new LinkedQueue
-    val iter = tasks.iterator()
-    while (iter.hasNext()) {
-      linkedQ put iter.next()
-    }
-    linkedQ
-  }
-
-  private[actors] override def isActive =
-    !terminating
-}
diff --git a/src/actors/scala/actors/Future.scala b/src/actors/scala/actors/Future.scala
index 5ebdfcd..ce69a67 100644
--- a/src/actors/scala/actors/Future.scala
+++ b/src/actors/scala/actors/Future.scala
@@ -1,82 +1,186 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2005-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2005-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Future.scala 18846 2009-10-01 07:30:14Z phaller $
 
 package scala.actors
 
-/**
- * <p>
- *   A <code>Future[T]</code> is a function of arity 0 that
- *   returns a value of type <code>T</code>.
- *   Applying a future blocks the current actor (<code>self</code>)
- *   until the future's value is available.
- * </p>
- * <p>
- *   A future can be queried to find out whether its value
- *   is already available.
- * </p>
+import scala.actors.scheduler.DaemonScheduler
+import scala.concurrent.SyncVar
+
+/** A `Future[T]` is a function of arity 0 that returns
+ *  a value of type `T`.
+ *  Applying a future blocks the current actor (`Actor.self`)
+ *  until the future's value is available.
+ *
+ *  A future can be queried to find out whether its value
+ *  is already available without blocking.
  *
- * @author Philipp Haller
- * @version 0.9.16
+ *  @author Philipp Haller
  */
-abstract class Future[+T](val ch: InputChannel[Any]) extends Responder[T] with Function0[T] {
-  protected var value: Option[Any] = None
+abstract class Future[+T] extends Responder[T] with Function0[T] {
+
+  @volatile
+  private[actors] var fvalue: Option[Any] = None
+  private[actors] def fvalueTyped = fvalue.get.asInstanceOf[T]
+  
+  @deprecated("this member is going to be removed in a future release")
+  def ch: InputChannel[Any] = inputChannel
+
+  @deprecated("this member is going to be removed in a future release")
+  protected def value: Option[Any] = fvalue
+  @deprecated("this member is going to be removed in a future release")
+  protected def value_=(x: Option[Any]) { fvalue = x }
+
+  /** Tests whether the future's result is available.
+   *
+   *  @return `true`  if the future's result is available,
+   *          `false` otherwise.
+   */
   def isSet: Boolean
+
+  /** Returns an input channel that can be used to receive the future's result.
+   *
+   *  @return the future's input channel
+   */
+  def inputChannel: InputChannel[T]
+
 }
 
-/**
- * The <code>Futures</code> object contains methods that operate on Futures.
+private case object Eval
+
+private class FutureActor[T](fun: SyncVar[T] => Unit, channel: Channel[T]) extends Future[T] with DaemonActor {
+
+  var enableChannel = false // guarded by this
+
+  def isSet = !fvalue.isEmpty
+
+  def apply(): T = {
+    if (fvalue.isEmpty) {
+      this !? Eval
+    }
+    fvalueTyped
+  }
+
+  def respond(k: T => Unit) {
+    if (isSet) k(fvalueTyped)
+    else {
+      val ft = this !! Eval
+      ft.inputChannel.react {
+        case _ => k(fvalueTyped)
+      }
+    }
+  }
+
+  def inputChannel: InputChannel[T] = {
+    synchronized {
+      if (!enableChannel) {
+        if (isSet)
+          channel ! fvalueTyped
+        enableChannel = true
+      }
+    }
+    channel
+  }
+
+  def act() {
+    val res = new SyncVar[T]
+
+    {
+      fun(res)
+    } andThen {
+
+      synchronized {
+        val v = res.get
+        fvalue =  Some(v)
+        if (enableChannel)
+          channel ! v
+      }
+
+      loop {
+        react {
+          case Eval => reply()
+        }
+      }
+    }
+  }
+}
+
+/** The `Futures` object contains methods that operate on futures.
  *
- * @version 0.9.8
- * @author Philipp Haller
+ *  @author Philipp Haller
  */
 object Futures {
 
+  /** Arranges for the asynchronous execution of `body`,
+   *  returning a future representing the result.
+   *
+   *  @param  body the computation to be carried out asynchronously
+   *  @return      the future representing the result of the
+   *               computation
+   */
   def future[T](body: => T): Future[T] = {
-    case object Eval
-    val a = Actor.actor {
-      Actor.react {
-        case Eval => Actor.reply(body)
-      }
-    }
-    a !! (Eval, { case any => any.asInstanceOf[T] })
+    val c = new Channel[T](Actor.self(DaemonScheduler))
+    val a = new FutureActor[T](_.set(body), c)
+    a.start()
+    a
   }
 
-  def alarm(t: Long) = future {
-    Actor.reactWithin(t) {
-      case TIMEOUT => {}
+  /** Creates a future that resolves after a given time span.
+   *
+   *  @param  timespan the time span in ms after which the future resolves
+   *  @return          the future
+   */
+  def alarm(timespan: Long): Future[Unit] = {
+    val c = new Channel[Unit](Actor.self(DaemonScheduler))
+    val fun = (res: SyncVar[Unit]) => {
+      Actor.reactWithin(timespan) {
+        case TIMEOUT => res.set({})
+      }
     }
+    val a = new FutureActor[Unit](fun, c)
+    a.start()
+    a
   }
 
-  def awaitEither[a, b](ft1: Future[a], ft2: Future[b]): Any = {
-    val FutCh1 = ft1.ch; val FutCh2 = ft2.ch
+  /** Waits for the first result returned by one of two
+   *  given futures.
+   *
+   *  @param  ft1 the first future
+   *  @param  ft2 the second future
+   *  @return the result of the future that resolves first
+   */
+  def awaitEither[A, B >: A](ft1: Future[A], ft2: Future[B]): B = {
+    val FutCh1 = ft1.inputChannel
+    val FutCh2 = ft2.inputChannel
     Actor.receive {
-      case FutCh1 ! arg1 => arg1
-      case FutCh2 ! arg2 => arg2
+      case FutCh1 ! arg1 => arg1.asInstanceOf[B]
+      case FutCh2 ! arg2 => arg2.asInstanceOf[B]
     }
   }
 
-  /**
-   * <p>
-   *   Awaits all futures returning an option containing a list of replies,
-   *   or timeouts returning <code>None</code>.
-   * </p>
-   * <p>
-   *   Note that some of the futures might already have been awaited.
-   * </p>
+  /** Waits until either all futures are resolved or a given
+   *  time span has passed. Results are collected in a list of
+   *  options. The result of a future that resolved during the
+   *  time span is its value wrapped in `Some`. The result of a
+   *  future that did not resolve during the time span is `None`.
+   *  
+   *  Note that some of the futures might already have been awaited,
+   *  in which case their value is returned wrapped in `Some`.
+   *  Passing a timeout of 0 causes `awaitAll` to return immediately.
+   *  
+   *  @param  timeout the time span in ms after which waiting is
+   *                  aborted
+   *  @param  fts     the futures to be awaited
+   *  @return         the list of optional future values
+   *  @throws java.lang.IllegalArgumentException  if timeout is negative,
+   *                  or timeout + `System.currentTimeMillis()` is negative.
    */
   def awaitAll(timeout: Long, fts: Future[Any]*): List[Option[Any]] = {
-    val thisActor = Actor.self
-    Actor.timer.schedule(new java.util.TimerTask {
-      def run() { thisActor ! TIMEOUT }
-    }, timeout)
-
     var resultsMap: collection.mutable.Map[Int, Option[Any]] = new collection.mutable.HashMap[Int, Option[Any]]
 
     var cnt = 0
@@ -89,13 +193,19 @@ object Futures {
     })
 
     val partFuns = unsetFts.map((p: Pair[Int, Future[Any]]) => {
-      val FutCh = p._2.ch
+      val FutCh = p._2.inputChannel
       val singleCase: PartialFunction[Any, Pair[Int, Any]] = {
         case FutCh ! any => Pair(p._1, any)
       }
       singleCase
     })
 
+    val thisActor = Actor.self
+    val timerTask = new java.util.TimerTask {
+      def run() { thisActor ! TIMEOUT }
+    }
+    Actor.timer.schedule(timerTask, timeout)
+
     def awaitWith(partFuns: Seq[PartialFunction[Any, Pair[Int, Any]]]) {
       val reaction: PartialFunction[Any, Unit] = new PartialFunction[Any, Unit] {
         def isDefinedAt(msg: Any) = msg match {
@@ -120,13 +230,19 @@ object Futures {
       Actor.receive(reaction)
     }
 
-    awaitWith(partFuns)
+    if (partFuns.length > 0)
+      awaitWith(partFuns)
 
     var results: List[Option[Any]] = Nil
     val size = resultsMap.size
     for (i <- 0 until size) {
       results = resultsMap(size - i - 1) :: results
     }
+
+    // cancel scheduled timer task
+    timerTask.cancel()
+
     results
   }
+
 }
diff --git a/src/actors/scala/actors/IFJTaskRunnerGroup.java b/src/actors/scala/actors/IFJTaskRunnerGroup.java
deleted file mode 100644
index dbbb325..0000000
--- a/src/actors/scala/actors/IFJTaskRunnerGroup.java
+++ /dev/null
@@ -1,18 +0,0 @@
-
-package scala.actors;
-
-/**
- * IFJTaskRunnerGroup
- *
- * @version 0.9.8
- * @author Philipp Haller
- */
-interface IFJTaskRunnerGroup {
-    public void executeTask(FJTask t);
-    public FJTaskRunner[] getArray();
-    public FJTask pollEntryQueue();
-    public void setActive(FJTaskRunner t);
-    public void checkActive(FJTaskRunner t, long scans);
-    public void setInactive(FJTaskRunner t);
-    public LinkedQueue getEntryQueue();
-}
diff --git a/src/actors/scala/actors/IScheduler.scala b/src/actors/scala/actors/IScheduler.scala
new file mode 100644
index 0000000..c235b99
--- /dev/null
+++ b/src/actors/scala/actors/IScheduler.scala
@@ -0,0 +1,82 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2005-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+package scala.actors
+
+/**
+ * The <code>IScheduler</code> trait provides a common interface
+ * for all schedulers used to execute actor tasks.
+ *
+ * Subclasses of <code>Actor</code> that override its
+ * <code>scheduler</code> member must provide
+ * an <code>IScheduler</code> implementation.
+ *
+ * @author Philipp Haller
+ */
+trait IScheduler {
+
+  /** Submits a closure for execution.
+   *
+   *  @param  fun  the closure to be executed
+   */
+  def execute(fun: => Unit): Unit
+
+  /** Submits a <code>Runnable</code> for execution.
+   *
+   *  @param  task  the task to be executed
+   */
+  def execute(task: Runnable): Unit
+
+  def executeFromActor(task: Runnable): Unit =
+    execute(task)
+
+  /** Shuts down the scheduler.
+   */
+  def shutdown(): Unit
+
+  /** When the scheduler is active, it can execute tasks.
+   */ 
+  def isActive: Boolean
+
+  /** Registers a newly created actor with this scheduler.
+   *
+   *  @param  a  the actor to be registered
+   */
+  def newActor(a: TrackedReactor): Unit
+
+  /** Unregisters an actor from this scheduler, because it
+   *  has terminated.
+   * 
+   *  @param  a  the actor to be registered
+   */
+  def terminated(a: TrackedReactor): Unit
+
+  /** Registers a closure to be executed when the specified
+   *  actor terminates.
+   * 
+   *  @param  a  the actor
+   *  @param  f  the closure to be registered
+   */
+  def onTerminate(a: TrackedReactor)(f: => Unit): Unit
+
+  def managedBlock(blocker: scala.concurrent.ManagedBlocker): Unit
+
+  @deprecated("this member is going to be removed in a future release")
+  def tick(a: Actor) {}
+
+  @deprecated("this member is going to be removed in a future release")
+  def onLockup(handler: () => Unit) {}
+
+  @deprecated("this member is going to be removed in a future release")
+  def onLockup(millis: Int)(handler: () => Unit) {}
+
+  @deprecated("this member is going to be removed in a future release")
+  def printActorDump {}
+
+}
diff --git a/src/actors/scala/actors/InputChannel.scala b/src/actors/scala/actors/InputChannel.scala
index 02e1a16..3f5bd71 100644
--- a/src/actors/scala/actors/InputChannel.scala
+++ b/src/actors/scala/actors/InputChannel.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2005-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2005-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: InputChannel.scala 18846 2009-10-01 07:30:14Z phaller $
 
 package scala.actors
 
@@ -14,13 +13,14 @@ package scala.actors
  * The <code>InputChannel</code> trait provides a common interface
  * for all channels from which values can be received.
  *
- * @version 0.9.8
  * @author Philipp Haller
+ *
+ * @define channel `InputChannel`
  */
 trait InputChannel[+Msg] {
 
   /**
-   * Receives a message from this <code>InputChannel</code>.
+   * Receives a message from this $channel.
    *
    * @param  f    a partial function with message patterns and actions
    * @return      result of processing the received value
@@ -28,7 +28,7 @@ trait InputChannel[+Msg] {
   def receive[R](f: PartialFunction[Msg, R]): R
 
   /**
-   * Receives a message from this <code>InputChannel</code> within
+   * Receives a message from this $channel within
    * a certain time span.
    *
    * @param  msec the time span before timeout
@@ -38,8 +38,8 @@ trait InputChannel[+Msg] {
   def receiveWithin[R](msec: Long)(f: PartialFunction[Any, R]): R
 
   /**
-   * Receives a message from this <code>InputChannel</code>.
-   * <p>
+   * Receives a message from this $channel.
+   *
    * This method never returns. Therefore, the rest of the computation
    * has to be contained in the actions of the partial function.
    *
@@ -48,9 +48,9 @@ trait InputChannel[+Msg] {
   def react(f: PartialFunction[Msg, Unit]): Nothing
 
   /**
-   * Receives a message from this <code>InputChannel</code> within
+   * Receives a message from this $channel within
    * a certain time span.
-   * <p>
+   *
    * This method never returns. Therefore, the rest of the computation
    * has to be contained in the actions of the partial function.
    *
@@ -60,7 +60,7 @@ trait InputChannel[+Msg] {
   def reactWithin(msec: Long)(f: PartialFunction[Any, Unit]): Nothing
 
   /**
-   * Receives the next message from this <code>Channel</code>.
+   * Receives the next message from this $channel.
    */
   def ? : Msg
 }
diff --git a/src/actors/scala/actors/MessageQueue.scala b/src/actors/scala/actors/MessageQueue.scala
index 4ede984..2d72487 100644
--- a/src/actors/scala/actors/MessageQueue.scala
+++ b/src/actors/scala/actors/MessageQueue.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2005-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2005-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: MessageQueue.scala 18846 2009-10-01 07:30:14Z phaller $
 
 package scala.actors
 
@@ -14,15 +13,18 @@ package scala.actors
  * This class is used by our efficient message queue
  * implementation.
  *
- * @version 0.9.9
  * @author Philipp Haller
  */
- at serializable
- at deprecated
-class MessageQueueElement {
-  var msg: Any = _
-  var session: OutputChannel[Any] = null
-  var next: MessageQueueElement = null
+ at serializable @SerialVersionUID(7124278808020037465L)
+ at deprecated("this class is going to be removed in a future release")
+class MessageQueueElement(msg: Any, session: OutputChannel[Any], next: MessageQueueElement) extends MQueueElement[Any](msg, session, next) {
+  def this() = this(null, null, null)
+  def this(msg: Any, session: OutputChannel[Any]) = this(msg, session, null)
+}
+
+private[actors] class MQueueElement[Msg >: Null](val msg: Msg, val session: OutputChannel[Any], var next: MQueueElement[Msg]) {
+  def this() = this(null, null, null)
+  def this(msg: Msg, session: OutputChannel[Any]) = this(msg, session, null)
 }
 
 /**
@@ -31,45 +33,71 @@ class MessageQueueElement {
  * library. Classes in this package are supposed to be the only
  * clients of this class.
  *
- * @version 0.9.9
  * @author Philipp Haller
  */
- at serializable
- at deprecated
-class MessageQueue {
-  var first: MessageQueueElement = null
-  // last == null iff list empty
-  var last: MessageQueueElement = null
-
-  def isEmpty = null eq last
+ at serializable @SerialVersionUID(2168935872884095767L)
+ at deprecated("this class is going to be removed in a future release")
+class MessageQueue(label: String) extends MQueue[Any](label)
 
+private[actors] class MQueue[Msg >: Null](protected val label: String) {
+  protected var first: MQueueElement[Msg] = null
+  protected var last: MQueueElement[Msg] = null  // last eq null iff list is empty
   private var _size = 0
+  
   def size = _size
+  final def isEmpty = last eq null
 
-  protected def changeSize(diff: Int) = {
+  protected def changeSize(diff: Int) {
     _size += diff
   }
 
-  def append(msg: Any, session: OutputChannel[Any]) = {
+  def append(msg: Msg, session: OutputChannel[Any]) {
     changeSize(1) // size always increases by 1
+    val el = new MQueueElement(msg, session)
+
+    if (isEmpty) first = el
+    else last.next = el
+    
+    last = el
+  }
+
+  def append(el: MQueueElement[Msg]) {
+    changeSize(1) // size always increases by 1
+
+    if (isEmpty) first = el
+    else last.next = el
+    
+    last = el
+  }
 
-    if (null eq last) { // list empty
-      val el = new MessageQueueElement
-      el.msg = msg
-      el.session = session
-      first = el
-      last = el
+  def foreach(f: (Msg, OutputChannel[Any]) => Unit) {
+    var curr = first
+    while (curr != null) {
+      f(curr.msg, curr.session)
+      curr = curr.next
     }
-    else {
-      val el = new MessageQueueElement
-      el.msg = msg
-      el.session = session
-      last.next = el
-      last = el
+  }
+
+  def foreachAppend(target: MQueue[Msg]) {
+    var curr = first
+    while (curr != null) {
+      target.append(curr)
+      curr = curr.next
     }
   }
 
-  def foldLeft[B](z: B)(f: (B, Any) => B): B = {
+  def foreachDequeue(target: MQueue[Msg]) {
+    var curr = first
+    while (curr != null) {
+      target.append(curr)
+      curr = curr.next
+    }
+    first = null
+    last = null
+    _size = 0
+  }
+
+  def foldLeft[B](z: B)(f: (B, Msg) => B): B = {
     var acc = z
     var curr = first
     while (curr != null) {
@@ -79,128 +107,156 @@ class MessageQueue {
     acc
   }
 
-  /** Returns the n-th msg that satisfies the predicate
+  /** Returns the n-th message that satisfies the predicate <code>p</code>
    *  without removing it.
    */
-  def get(n: Int)(p: Any => Boolean): Option[Any] = {
-    var found: Option[Any] = None
+  def get(n: Int)(p: Msg => Boolean): Option[Msg] = {
     var pos = 0
+    
+    def test(msg: Msg): Boolean =
+      p(msg) && (pos == n || { pos += 1; false })
+      
+    var curr = first
+    while (curr != null)
+      if (test(curr.msg)) return Some(curr.msg) // early return
+      else curr = curr.next
 
-    def test(msg: Any): Boolean =
-      if (p(msg)) {
-        if (pos == n)
-          true
-        else {
-          pos += 1
-          false
-        }
-      } else
-        false
-
-    if (last == null) None
-    else if (test(first.msg))
-      Some(first.msg)
-    else {
-      var curr = first
-      while(curr.next != null && found.isEmpty) {
-        curr = curr.next
-        if (test(curr.msg))
-          found = Some(curr.msg)
-      }
-      found
-    }
+    None
   }
 
-  /** Removes the n-th msg that satisfies the predicate.
+  /** Removes the n-th message that satisfies the predicate <code>p</code>.
    */
-  def remove(n: Int)(p: Any => Boolean): Option[(Any, OutputChannel[Any])] = {
-    var found: Option[(Any, OutputChannel[Any])] = None
-    var pos = 0
-
-    def test(msg: Any): Boolean =
-      if (p(msg)) {
-        if (pos == n)
-          true
-        else {
-          pos += 1
-          false
-        }
-      } else
-        false
+  def remove(n: Int)(p: (Msg, OutputChannel[Any]) => Boolean): Option[(Msg, OutputChannel[Any])] =
+    removeInternal(n)(p) map (x => (x.msg, x.session))
+    
+  /** Extracts the first message that satisfies the predicate <code>p</code>
+   *  or <code>null</code> if <code>p</code> fails for all of them.
+   */
+  def extractFirst(p: (Msg, OutputChannel[Any]) => Boolean): MQueueElement[Msg] =
+    removeInternal(0)(p) orNull
 
-    if (last == null) None
-    else if (test(first.msg)) {
-      val tmp = first
-      // remove first element
+  def extractFirst(pf: PartialFunction[Msg, Any]): MQueueElement[Msg] = {
+    if (isEmpty)    // early return
+      return null
+    
+    // special handling if returning the head
+    if (pf.isDefinedAt(first.msg)) {
+      val res = first
       first = first.next
-      // might have to update last
-      if (tmp eq last) {
+      if (res eq last)
         last = null
-      }
-      Some((tmp.msg, tmp.session))
-    } else {
-      var curr = first
-      var prev = curr
-      while(curr.next != null && found.isEmpty) {
-        prev = curr
-        curr = curr.next
-        if (test(curr.msg)) {
-          // remove curr
+      
+      changeSize(-1)
+      res
+    }
+    else {
+      var curr = first.next   // init to element #2
+      var prev = first
+      
+      while (curr != null) {
+        if (pf.isDefinedAt(curr.msg)) {
           prev.next = curr.next
-          // might have to update last
-          if (curr eq last) {
+          if (curr eq last)
             last = prev
-          }
-          found = Some((curr.msg, curr.session))
+
+          changeSize(-1)
+          return curr // early return
+        }
+        else {
+          prev = curr
+          curr = curr.next
         }
       }
-      found
+      // not found
+      null
     }
   }
 
-  def extractFirst(p: Any => Boolean): MessageQueueElement = {
-    changeSize(-1) // assume size decreases by 1
+  private def removeInternal(n: Int)(p: (Msg, OutputChannel[Any]) => Boolean): Option[MQueueElement[Msg]] = {
+    var pos = 0
+
+    def foundMsg(x: MQueueElement[Msg]) = {        
+      changeSize(-1)
+      Some(x)
+    }
+    def test(msg: Msg, session: OutputChannel[Any]): Boolean =
+      p(msg, session) && (pos == n || { pos += 1 ; false })
 
-    val msg = if (null eq last) null
+    if (isEmpty)    // early return
+      return None
+    
+    // special handling if returning the head
+    if (test(first.msg, first.session)) {
+      val res = first
+      first = first.next
+      if (res eq last)
+        last = null
+      
+      foundMsg(res)
+    }
     else {
-      // test first element
-      if (p(first.msg)) {
-        val tmp = first
-        // remove first element
-        first = first.next
-
-        // might have to update last
-        if (tmp eq last) {
-          last = null
+      var curr = first.next   // init to element #2
+      var prev = first
+      
+      while (curr != null) {
+        if (test(curr.msg, curr.session)) {
+          prev.next = curr.next
+          if (curr eq last)
+            last = prev
+            
+          return foundMsg(curr) // early return
         }
-
-        tmp
-      }
-      else {
-        var curr = first
-        var prev = curr
-        while(curr.next != null) {
+        else {
           prev = curr
           curr = curr.next
-          if (p(curr.msg)) {
-            // remove curr
-            prev.next = curr.next
-
-            // might have to update last
-            if (curr eq last) {
-              last = prev
-            }
-
-            return curr
-          }
         }
-        null
       }
+      // not found
+      None
     }
+  }
+}
 
-    if (null eq msg)
-      changeSize(1) // correct wrong assumption
+/** Debugging trait.
+ */
+private[actors] trait MessageQueueTracer extends MQueue[Any]
+{
+  private val queueNumber = MessageQueueTracer.getQueueNumber
+
+  override def append(msg: Any, session: OutputChannel[Any]) {
+    super.append(msg, session)
+    printQueue("APPEND %s" format msg)
+  }
+  override def get(n: Int)(p: Any => Boolean): Option[Any] = {
+    val res = super.get(n)(p)
+    printQueue("GET %s" format res)
+    res
+  }
+  override def remove(n: Int)(p: (Any, OutputChannel[Any]) => Boolean): Option[(Any, OutputChannel[Any])] = {
+    val res = super.remove(n)(p)
+    printQueue("REMOVE %s" format res)
+    res
+  }
+  override def extractFirst(p: (Any, OutputChannel[Any]) => Boolean): MQueueElement[Any] = {
+    val res = super.extractFirst(p)
+    printQueue("EXTRACT_FIRST %s" format res)
+    res
+  }
+  
+  private def printQueue(msg: String) = {
+    def firstMsg = if (first eq null) "null" else first.msg
+    def lastMsg = if (last eq null) "null" else last.msg
+
+    println("[%s size=%d] [%s] first = %s, last = %s".format(this, size, msg, firstMsg, lastMsg))
+  }
+  override def toString() = "%s:%d".format(label, queueNumber)
+}
 
-    msg
+private[actors] object MessageQueueTracer {
+  // for tracing purposes
+  private var queueNumberAssigner = 0
+  private def getQueueNumber = synchronized {
+    queueNumberAssigner += 1
+    queueNumberAssigner
   }
 }
diff --git a/src/actors/scala/actors/OutputChannel.scala b/src/actors/scala/actors/OutputChannel.scala
index 3518d67..c86cfba 100644
--- a/src/actors/scala/actors/OutputChannel.scala
+++ b/src/actors/scala/actors/OutputChannel.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2005-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2005-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: OutputChannel.scala 18846 2009-10-01 07:30:14Z phaller $
 
 package scala.actors
 
@@ -14,20 +13,21 @@ package scala.actors
  * The <code>OutputChannel</code> trait provides a common interface
  * for all channels to which values can be sent.
  *
- * @version 0.9.17
  * @author Philipp Haller
+ *
+ * @define actor `OutputChannel`
  */
 trait OutputChannel[-Msg] {
 
   /**
-   * Sends <code>msg</code> to this
-   * <code>OutputChannel</code> (asynchronous).
+   * Sends <code>msg</code> to this $actor (asynchronous).
+   *
+   * @param  msg      the message to send
    */
   def !(msg: Msg): Unit
 
   /**
-   * Sends <code>msg</code> to this
-   * <code>OutputChannel</code> (asynchronous) supplying
+   * Sends <code>msg</code> to this $actor (asynchronous) supplying
    * explicit reply destination.
    *
    * @param  msg      the message to send
@@ -36,14 +36,14 @@ trait OutputChannel[-Msg] {
   def send(msg: Msg, replyTo: OutputChannel[Any]): Unit
 
   /**
-   * Forwards <code>msg</code> to this
-   * <code>OutputChannel</code> (asynchronous).
+   * Forwards <code>msg</code> to this $actor (asynchronous).
+   *
+   * @param  msg      the message to forward
    */
   def forward(msg: Msg): Unit
 
   /**
-   * Returns the <code>Actor</code> that is
-   * receiving from this <code>OutputChannel</code>.
+   * Returns the <code>Actor</code> that is receiving from this $actor.
    */
   def receiver: Actor
 }
diff --git a/src/actors/scala/actors/ReactChannel.scala b/src/actors/scala/actors/ReactChannel.scala
new file mode 100644
index 0000000..69312e4
--- /dev/null
+++ b/src/actors/scala/actors/ReactChannel.scala
@@ -0,0 +1,125 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2005-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+package scala.actors
+
+/**
+ * The <code>ReactChannel</code> trait.
+ *
+ * @author Philipp Haller
+ */
+private[actors] class ReactChannel[Msg](receiver: ReplyReactor) extends InputChannel[Msg] {
+
+  private case class SendToReactor(channel: ReactChannel[Msg], msg: Msg)
+
+  /**
+   * Sends a message to this <code>ReactChannel</code>.
+   *
+   * @param  msg the message to be sent
+   */
+  def !(msg: Msg) {
+    receiver ! SendToReactor(this, msg)
+  }
+
+  /**
+   * Sends a message to this <code>ReactChannel</code>
+   * (asynchronous) supplying explicit reply destination.
+   *
+   * @param  msg     the message to send
+   * @param  replyTo the reply destination
+   */
+  def send(msg: Msg, replyTo: OutputChannel[Any]) {
+    receiver.send(SendToReactor(this, msg), replyTo)
+  }
+
+  /**
+   * Forwards <code>msg</code> to <code>this</code> keeping the
+   * last sender as sender instead of <code>self</code>.
+   */
+  def forward(msg: Msg) {
+    receiver forward SendToReactor(this, msg)
+  }
+
+  /**
+   * Receives a message from this <code>ReactChannel</code>.
+   * <p>
+   * This method never returns. Therefore, the rest of the computation
+   * has to be contained in the actions of the partial function.
+   *
+   * @param  f    a partial function with message patterns and actions
+   */
+  def react(f: PartialFunction[Msg, Unit]): Nothing = {
+    val C = this
+    receiver.react {
+      case SendToReactor(C, msg) if (f.isDefinedAt(msg.asInstanceOf[Msg])) =>
+        f(msg.asInstanceOf[Msg])
+    }
+  }
+
+  /**
+   * Receives a message from this <code>ReactChannel</code> within
+   * a certain time span.
+   * <p>
+   * This method never returns. Therefore, the rest of the computation
+   * has to be contained in the actions of the partial function.
+   *
+   * @param  msec the time span before timeout
+   * @param  f    a partial function with message patterns and actions
+   */
+  def reactWithin(msec: Long)(f: PartialFunction[Any, Unit]): Nothing = {
+    val C = this
+    val recvActor = receiver.asInstanceOf[Actor]
+    recvActor.reactWithin(msec) {
+      case C ! msg if (f.isDefinedAt(msg.asInstanceOf[Msg])) =>
+        f(msg.asInstanceOf[Msg])
+      case TIMEOUT => f(TIMEOUT)
+    }
+  }
+
+  /**
+   * Receives a message from this <code>ReactChannel</code>.
+   *
+   * @param  f    a partial function with message patterns and actions
+   * @return      result of processing the received value
+   */
+  def receive[R](f: PartialFunction[Msg, R]): R = {
+    val C = this
+    val recvActor = receiver.asInstanceOf[Actor]
+    recvActor.receive {
+      case C ! msg if (f.isDefinedAt(msg.asInstanceOf[Msg])) =>
+        f(msg.asInstanceOf[Msg])
+    }
+  }
+
+  /**
+   * Receives a message from this <code>ReactChannel</code> within a certain
+   * time span.
+   *
+   * @param  msec the time span before timeout
+   * @param  f    a partial function with message patterns and actions
+   * @return      result of processing the received value
+   */
+  def receiveWithin[R](msec: Long)(f: PartialFunction[Any, R]): R = {
+    val C = this
+    val recvActor = receiver.asInstanceOf[Actor]
+    recvActor.receiveWithin(msec) {
+      case C ! msg if (f.isDefinedAt(msg.asInstanceOf[Msg])) =>
+        f(msg.asInstanceOf[Msg])
+      case TIMEOUT => f(TIMEOUT)
+    }
+  }
+
+  /**
+   * Receives the next message from this <code>ReactChannel</code>.
+   */
+  def ? : Msg = receive {
+    case x => x
+  }
+
+}
diff --git a/src/actors/scala/actors/Reaction.scala b/src/actors/scala/actors/Reaction.scala
index bc18fc2..83eedf4 100644
--- a/src/actors/scala/actors/Reaction.scala
+++ b/src/actors/scala/actors/Reaction.scala
@@ -1,42 +1,19 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2005-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2005-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Reaction.scala 18846 2009-10-01 07:30:14Z phaller $
 
 
 package scala.actors
 
+import scala.util.control.ControlThrowable
 import java.lang.{InterruptedException, Runnable}
 
-/** <p>
- *    This exception is thrown whenever an actor exits.
- *    Its purpose is to let <code>exit</code> have
- *    return type <code>Nothing</code>.
- *  </p>
- *
- *  @version 0.9.10
- *  @author Philipp Haller
- */
-private[actors] class ExitActorException extends Throwable {
-  /*
-   * For efficiency reasons we do not fill in
-   * the execution stack trace.
-   */
-  override def fillInStackTrace(): Throwable = this
-}
-
-private[actors] class KillActorException extends Throwable {
-  /*
-   * For efficiency reasons we do not fill in
-   * the execution stack trace.
-   */
-  override def fillInStackTrace(): Throwable = this
-}
+private[actors] class KillActorControl extends ControlThrowable
 
 /** <p>
  *    The abstract class <code>Reaction</code> associates
@@ -45,69 +22,12 @@ private[actors] class KillActorException extends Throwable {
  *    <code>java.lang.Runnable</code></a>.
  *  </p>
  *
- *  @version 0.9.10
  *  @author Philipp Haller
  */
- at deprecated
-class Reaction extends Runnable {
-
-  private[actors] var a: Actor = _
-  private var f: PartialFunction[Any, Unit] = _
-  private var msg: Any = _
-
-  def this(a: Actor, f: PartialFunction[Any, Unit], msg: Any) = {
-    this()
-    this.a = a
-    this.f = f
-    this.msg = msg
-  }
+ at deprecated("This class will be removed in a future release")
+class Reaction(a: Actor, f: PartialFunction[Any, Any], msg: Any)
+extends ActorTask(a, if (f == null) (() => a.act()) else null, f, msg) {
 
   def this(a: Actor) = this(a, null, null)
 
-  def run() {
-    val saved = Actor.tl.get.asInstanceOf[Actor]
-    Actor.tl.set(a)
-    a.isDetached = false
-    try {
-      if (a.shouldExit) // links
-        a.exit()
-      else {
-        try {
-          if (f == null)
-            a.act()
-          else
-            f(msg)
-        } catch {
-          case _: KillActorException =>
-        }
-        a.kill(); a.exit()
-      }
-    }
-    catch {
-      case eae: ExitActorException => {
-        //Debug.info(a+": exiting...")
-        ActorGC.terminated(a)
-      }
-      case _: SuspendActorException => {
-        // do nothing (continuation is already saved)
-      }
-      case t: Throwable => {
-        Debug.info(a+": caught "+t)
-        ActorGC.terminated(a)
-        // links
-        a.synchronized {
-          if (!a.links.isEmpty)
-            a.exitLinked(t)
-          else
-            t.printStackTrace()
-        }
-      }
-    } finally {
-      Actor.tl.set(saved)
-      this.a = null
-      this.f = null
-      this.msg = null
-    }
-  }
-
 }
diff --git a/src/actors/scala/actors/Reactor.scala b/src/actors/scala/actors/Reactor.scala
new file mode 100644
index 0000000..c7a900d
--- /dev/null
+++ b/src/actors/scala/actors/Reactor.scala
@@ -0,0 +1,298 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2005-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+package scala.actors
+
+import scala.actors.scheduler.{DelegatingScheduler, ExecutorScheduler,
+                               ForkJoinScheduler, ThreadPoolConfig}
+import java.util.concurrent.{ThreadPoolExecutor, TimeUnit, LinkedBlockingQueue}
+
+private[actors] object Reactor {
+
+  val scheduler = new DelegatingScheduler {
+    def makeNewScheduler: IScheduler = {
+      val sched = if (!ThreadPoolConfig.useForkJoin) {
+        // default is non-daemon
+        val workQueue = new LinkedBlockingQueue[Runnable]
+        ExecutorScheduler(
+          new ThreadPoolExecutor(ThreadPoolConfig.corePoolSize,
+                                 ThreadPoolConfig.maxPoolSize,
+                                 60000L,
+                                 TimeUnit.MILLISECONDS,
+                                 workQueue,
+                                 new ThreadPoolExecutor.CallerRunsPolicy))
+      } else {
+        // default is non-daemon, non-fair
+        val s = new ForkJoinScheduler(ThreadPoolConfig.corePoolSize, ThreadPoolConfig.maxPoolSize, false, false)
+        s.start()
+        s
+      }
+      Debug.info(this+": starting new "+sched+" ["+sched.getClass+"]")
+      sched
+    }
+  }
+
+  val waitingForNone = new PartialFunction[Any, Unit] {
+    def isDefinedAt(x: Any) = false
+    def apply(x: Any) {}
+  }
+
+}
+
+/**
+ * The Reactor trait provides lightweight actors.
+ *
+ * @author Philipp Haller
+ *
+ * @define actor reactor
+ */
+trait Reactor[Msg >: Null] extends OutputChannel[Msg] with Combinators {
+
+  /* The $actor's mailbox. */
+  private[actors] val mailbox = new MQueue[Msg]("Reactor")
+
+  // guarded by this
+  private[actors] val sendBuffer = new MQueue[Msg]("SendBuffer")
+
+  /* Whenever this $actor executes on some thread, `waitingFor` is
+   * guaranteed to be equal to `Reactor.waitingForNone`.
+   *
+   * In other words, whenever `waitingFor` is not equal to
+   * `Reactor.waitingForNone`, this $actor is guaranteed not to execute
+   * on some thread.
+   *
+   * If the $actor waits in a `react`, `waitingFor` holds the
+   * message handler that `react` was called with.
+   *
+   * guarded by this
+   */
+  private[actors] var waitingFor: PartialFunction[Msg, Any] =
+    Reactor.waitingForNone
+
+  // guarded by this
+  private[actors] var _state: Actor.State.Value = Actor.State.New
+
+  /**
+   * The $actor's behavior is specified by implementing this method.
+   */
+  def act(): Unit
+
+  /**
+   * This partial function is applied to exceptions that propagate out of
+   * this $actor's body.
+   */
+  protected[actors] def exceptionHandler: PartialFunction[Exception, Unit] =
+    Map()
+
+  protected[actors] def scheduler: IScheduler =
+    Reactor.scheduler
+
+  protected[actors] def mailboxSize: Int =
+    mailbox.size
+
+  def send(msg: Msg, replyTo: OutputChannel[Any]) {
+    val todo = synchronized {
+      if (waitingFor ne Reactor.waitingForNone) {
+        val savedWaitingFor = waitingFor
+        waitingFor = Reactor.waitingForNone
+        startSearch(msg, replyTo, savedWaitingFor)
+      } else {
+        sendBuffer.append(msg, replyTo)
+        () => { /* do nothing */ }
+      }
+    }
+    todo()
+  }
+
+  private[actors] def startSearch(msg: Msg, replyTo: OutputChannel[Any], handler: PartialFunction[Msg, Any]) =
+    () => scheduler execute makeReaction(() => {
+      val startMbox = new MQueue[Msg]("Start")
+      synchronized { startMbox.append(msg, replyTo) }
+      searchMailbox(startMbox, handler, true)
+    })
+
+  private[actors] final def makeReaction(fun: () => Unit): Runnable =
+    makeReaction(fun, null, null)
+
+  /* This method is supposed to be overridden. */
+  private[actors] def makeReaction(fun: () => Unit, handler: PartialFunction[Msg, Any], msg: Msg): Runnable =
+    new ReactorTask(this, fun, handler, msg)
+
+  private[actors] def resumeReceiver(item: (Msg, OutputChannel[Any]), handler: PartialFunction[Msg, Any], onSameThread: Boolean) {
+    if (onSameThread)
+      makeReaction(null, handler, item._1).run()
+    else
+      scheduleActor(handler, item._1)
+
+    /* Here, we throw a SuspendActorControl to avoid
+       terminating this actor when the current ReactorTask
+       is finished.
+
+       The SuspendActorControl skips the termination code
+       in ReactorTask.
+     */
+    throw Actor.suspendException
+  }
+
+  def !(msg: Msg) {
+    send(msg, null)
+  }
+
+  def forward(msg: Msg) {
+    send(msg, null)
+  }
+
+  def receiver: Actor = this.asInstanceOf[Actor]
+
+  // guarded by this
+  private[actors] def drainSendBuffer(mbox: MQueue[Msg]) {
+    sendBuffer.foreachDequeue(mbox)
+  }
+
+  private[actors] def searchMailbox(startMbox: MQueue[Msg],
+                                    handler: PartialFunction[Msg, Any],
+                                    resumeOnSameThread: Boolean) {
+    var tmpMbox = startMbox
+    var done = false
+    while (!done) {
+      val qel = tmpMbox.extractFirst(handler)
+      if (tmpMbox ne mailbox)
+        tmpMbox.foreachAppend(mailbox)
+      if (null eq qel) {
+        synchronized {
+          // in mean time new stuff might have arrived
+          if (!sendBuffer.isEmpty) {
+            tmpMbox = new MQueue[Msg]("Temp")
+            drainSendBuffer(tmpMbox)
+            // keep going
+          } else {
+            waitingFor = handler
+            /* Here, we throw a SuspendActorControl to avoid
+               terminating this actor when the current ReactorTask
+               is finished.
+
+               The SuspendActorControl skips the termination code
+               in ReactorTask.
+             */
+            throw Actor.suspendException
+          }
+        }
+      } else {
+        resumeReceiver((qel.msg, qel.session), handler, resumeOnSameThread)
+        done = true
+      }
+    }
+  }
+
+  /**
+   * Receives a message from this $actor's mailbox.
+   *
+   * This method never returns. Therefore, the rest of the computation
+   * has to be contained in the actions of the partial function.
+   *
+   * @param  handler  a partial function with message patterns and actions
+   */
+  protected def react(handler: PartialFunction[Msg, Unit]): Nothing = {
+    synchronized { drainSendBuffer(mailbox) }
+    searchMailbox(mailbox, handler, false)
+    throw Actor.suspendException
+  }
+
+  /* This method is guaranteed to be executed from inside
+   * an $actor's act method.
+   *
+   * assume handler != null
+   *
+   * never throws SuspendActorControl
+   */
+  private[actors] def scheduleActor(handler: PartialFunction[Msg, Any], msg: Msg) {
+    scheduler executeFromActor makeReaction(null, handler, msg)
+  }
+
+  // guarded by this
+  private[actors] def dostart() {
+    _state = Actor.State.Runnable
+    scheduler newActor this
+    scheduler execute makeReaction(() => act(), null, null)
+  }
+
+  /**
+   * Starts this $actor. This method is idempotent.
+   */
+  def start(): Reactor[Msg] = synchronized {
+    if (_state == Actor.State.New)
+      dostart()
+    this
+  }
+
+  /**
+   * Restarts this $actor.
+   *
+   * @throws java.lang.IllegalStateException  if the $actor is not in state `Actor.State.Terminated`
+   */
+  def restart(): Unit = synchronized {
+    if (_state == Actor.State.Terminated)
+      dostart()
+    else
+      throw new IllegalStateException("restart only in state "+Actor.State.Terminated)
+  }
+
+  /** Returns the execution state of this $actor.
+   *  
+   *  @return the execution state
+   */
+  def getState: Actor.State.Value = synchronized {
+    if (waitingFor ne Reactor.waitingForNone)
+      Actor.State.Suspended
+    else
+      _state
+  }
+
+  implicit def mkBody[A](body: => A) = new Actor.Body[A] {
+    def andThen[B](other: => B): Unit = Reactor.this.seq(body, other)
+  }
+
+  /* This closure is used to implement control-flow operations
+   * built on top of `seq`. Note that the only invocation of
+   * `kill` is supposed to be inside `ReactorTask.run`.
+   */
+  @volatile
+  private[actors] var kill: () => Unit =
+    () => { exit() }
+
+  private[actors] def seq[a, b](first: => a, next: => b): Unit = {
+    val killNext = this.kill
+    this.kill = () => {
+      this.kill = killNext
+
+      // to avoid stack overflow:
+      // instead of directly executing `next`,
+      // schedule as continuation
+      scheduleActor({ case _ => next }, null)
+      throw Actor.suspendException
+    }
+    first
+    throw new KillActorControl
+  }
+
+  protected[actors] def exit(): Nothing = {
+    terminated()
+    throw Actor.suspendException
+  }
+
+  private[actors] def terminated() {
+    synchronized {
+      _state = Actor.State.Terminated
+      // reset waitingFor, otherwise getState returns Suspended
+      waitingFor = Reactor.waitingForNone
+    }
+    scheduler.terminated(this)
+  }
+
+}
diff --git a/src/actors/scala/actors/ReactorCanReply.scala b/src/actors/scala/actors/ReactorCanReply.scala
new file mode 100644
index 0000000..4f7bafc
--- /dev/null
+++ b/src/actors/scala/actors/ReactorCanReply.scala
@@ -0,0 +1,90 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2005-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+package scala.actors
+
+/**
+ * The ReactorCanReply trait provides message send operations that
+ * may result in a response from the receiver.
+ *
+ * @author Philipp Haller
+ */
+private[actors] trait ReactorCanReply extends CanReply[Any, Any] {
+  _: ReplyReactor =>
+
+  override type Future[+P] = scala.actors.Future[P]
+
+  def !?(msg: Any): Any =
+    (this !! msg)()
+
+  def !?(msec: Long, msg: Any): Option[Any] = {
+    val myself = Actor.rawSelf(this.scheduler)
+    val res = new scala.concurrent.SyncVar[Any]
+    val out = new OutputChannel[Any] {
+      def !(msg: Any) =
+        res set msg
+      def send(msg: Any, replyTo: OutputChannel[Any]) =
+        res set msg
+      def forward(msg: Any) =
+        res set msg
+      def receiver =
+        myself.asInstanceOf[Actor]
+    }
+    this.send(msg, out)
+    res.get(msec)
+  }
+
+  def !!(msg: Any): Future[Any] =
+    this !! (msg, { case x => x })
+
+  def !![A](msg: Any, handler: PartialFunction[Any, A]): Future[A] = {
+    val myself = Actor.rawSelf(this.scheduler)
+    val ftch = new ReactChannel[A](myself)
+    val res = new scala.concurrent.SyncVar[A]
+
+    val out = new OutputChannel[Any] {
+      def !(msg: Any) = {
+        val msg1 = handler(msg)
+        ftch ! msg1
+        res set msg1
+      }
+      def send(msg: Any, replyTo: OutputChannel[Any]) = {
+        val msg1 = handler(msg)
+        ftch.send(msg1, replyTo)
+        res set msg1
+      }
+      def forward(msg: Any) = {
+        val msg1 = handler(msg)
+        ftch forward msg1
+        res set msg1
+      }
+      def receiver =
+        myself.asInstanceOf[Actor]
+    }
+
+    this.send(msg, out)
+
+    new Future[A] {
+      def apply() = {
+        if (!isSet)
+          fvalue = Some(res.get)
+        
+        fvalueTyped
+      }
+      def respond(k: A => Unit): Unit =
+        if (isSet) k(fvalueTyped)
+        else inputChannel.react {
+          case any => fvalue = Some(any); k(fvalueTyped)
+        }
+      def isSet =
+        !fvalue.isEmpty
+      def inputChannel = ftch
+    }
+  }
+}
diff --git a/src/actors/scala/actors/ReactorTask.scala b/src/actors/scala/actors/ReactorTask.scala
new file mode 100644
index 0000000..c4eab2a
--- /dev/null
+++ b/src/actors/scala/actors/ReactorTask.scala
@@ -0,0 +1,77 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2005-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |                                         **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+package scala.actors
+
+import java.lang.Runnable
+import java.util.concurrent.Callable
+
+import scala.concurrent.forkjoin.RecursiveAction
+
+/** <p>
+ *    The class <code>ReactorTask</code>.
+ *  </p>
+ *
+ *  @author Philipp Haller
+ */
+private[actors] class ReactorTask[Msg >: Null](var reactor: Reactor[Msg],
+                                               var fun: () => Any,
+                                               var handler: PartialFunction[Msg, Any],
+                                               var msg: Msg)
+  extends RecursiveAction with Callable[Unit] with Runnable {
+
+  def run() {
+    try {
+      beginExecution()
+      try {
+        if (fun eq null)
+          handler(msg)
+        else
+          fun()
+      } catch {
+        case _: KillActorControl =>
+          // do nothing
+
+        case e: Exception if reactor.exceptionHandler.isDefinedAt(e) =>
+          reactor.exceptionHandler(e)
+      }
+      reactor.kill()
+    }
+    catch {
+      case _: SuspendActorControl =>
+        // do nothing (continuation is already saved)
+
+      case e: Throwable =>
+        terminateExecution(e)
+        reactor.terminated()
+        if (!e.isInstanceOf[Exception])
+          throw e
+    } finally {
+      suspendExecution()
+      this.reactor = null
+      this.fun = null
+      this.handler = null
+      this.msg = null
+    }
+  }
+
+  def call() = run()
+
+  def compute() = run()
+
+  protected def beginExecution() {}
+
+  protected def suspendExecution() {}
+
+  protected def terminateExecution(e: Throwable) {
+    Console.err.println(reactor+": caught "+e)
+    e.printStackTrace()
+  }
+
+}
diff --git a/src/actors/scala/actors/ReplyReactor.scala b/src/actors/scala/actors/ReplyReactor.scala
new file mode 100644
index 0000000..af97e28
--- /dev/null
+++ b/src/actors/scala/actors/ReplyReactor.scala
@@ -0,0 +1,170 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2005-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+package scala.actors
+
+import java.util.{Timer, TimerTask}
+
+/** <p>
+ *    The <code>ReplyReactor</code> trait extends the <code>Reactor</code>
+ *    trait with methods to reply to the sender of a message.
+ *    Sending a message to a <code>ReplyReactor</code> implicitly
+ *    passes a reference to the sender together with the message.
+ *  </p>
+ *
+ *  @author Philipp Haller
+ *
+ *  @define actor `ReplyReactor`
+ */
+trait ReplyReactor extends Reactor[Any] with ReactorCanReply {
+
+  /* A list of the current senders. The head of the list is
+   * the sender of the message that was received last.
+   */
+  @volatile
+  private[actors] var senders: List[OutputChannel[Any]] = List()
+
+  /* This option holds a TimerTask when the actor waits in a
+   * reactWithin. The TimerTask is cancelled when the actor
+   * resumes.
+   *
+   * guarded by this
+   */
+  private[actors] var onTimeout: Option[TimerTask] = None
+
+  /**
+   * Returns the $actor which sent the last received message.
+   */
+  protected[actors] def sender: OutputChannel[Any] = senders.head
+
+  /**
+   * Replies with <code>msg</code> to the sender.
+   */
+  protected[actors] def reply(msg: Any) {
+    sender ! msg
+  }
+
+  override def !(msg: Any) {
+    send(msg, Actor.rawSelf(scheduler))
+  }
+
+  override def forward(msg: Any) {
+    send(msg, Actor.sender)
+  }
+
+  private[actors] override def resumeReceiver(item: (Any, OutputChannel[Any]), handler: PartialFunction[Any, Any], onSameThread: Boolean) {
+    synchronized {
+      if (!onTimeout.isEmpty) {
+        onTimeout.get.cancel()
+        onTimeout = None
+      }
+    }
+    senders = List(item._2)
+    super.resumeReceiver(item, handler, onSameThread)
+  }
+
+  private[actors] override def searchMailbox(startMbox: MQueue[Any],
+                                             handler: PartialFunction[Any, Any],
+                                             resumeOnSameThread: Boolean) {
+    var tmpMbox = startMbox
+    var done = false
+    while (!done) {
+      val qel = tmpMbox.extractFirst((msg: Any, replyTo: OutputChannel[Any]) => {
+        senders = List(replyTo)
+        handler.isDefinedAt(msg)
+      })
+      if (tmpMbox ne mailbox)
+        tmpMbox.foreach((m, s) => mailbox.append(m, s))
+      if (null eq qel) {
+        synchronized {
+          // in mean time new stuff might have arrived
+          if (!sendBuffer.isEmpty) {
+            tmpMbox = new MQueue[Any]("Temp")
+            drainSendBuffer(tmpMbox)
+            // keep going
+          } else {
+            waitingFor = handler
+            // see Reactor.searchMailbox
+            throw Actor.suspendException
+          }
+        }
+      } else {
+        resumeReceiver((qel.msg, qel.session), handler, resumeOnSameThread)
+        done = true
+      }
+    }
+  }
+
+  private[actors] override def makeReaction(fun: () => Unit, handler: PartialFunction[Any, Any], msg: Any): Runnable =
+    new ReplyReactorTask(this, fun, handler, msg)
+
+  protected[actors] override def react(handler: PartialFunction[Any, Unit]): Nothing = {
+    assert(Actor.rawSelf(scheduler) == this, "react on channel belonging to other actor")
+    super.react(handler)
+  }
+
+  /**
+   * Receives a message from this $actor's mailbox within a certain
+   * time span.
+   *
+   * This method never returns. Therefore, the rest of the computation
+   * has to be contained in the actions of the partial function.
+   *
+   * @param  msec     the time span before timeout
+   * @param  handler  a partial function with message patterns and actions
+   */
+  protected[actors] def reactWithin(msec: Long)(handler: PartialFunction[Any, Unit]): Nothing = {
+    assert(Actor.rawSelf(scheduler) == this, "react on channel belonging to other actor")
+
+    synchronized { drainSendBuffer(mailbox) }
+
+    // first, remove spurious TIMEOUT message from mailbox if any
+    mailbox.extractFirst((m: Any, replyTo: OutputChannel[Any]) => m == TIMEOUT)
+
+    while (true) {
+      val qel = mailbox.extractFirst((m: Any, replyTo: OutputChannel[Any]) => {
+        senders = List(replyTo)
+        handler isDefinedAt m
+      })
+      if (null eq qel) {
+        synchronized {
+          // in mean time new messages might have arrived
+          if (!sendBuffer.isEmpty) {
+            drainSendBuffer(mailbox)
+            // keep going
+          } else if (msec == 0L) {
+            // throws Actor.suspendException
+            resumeReceiver((TIMEOUT, this), handler, false)
+          } else {
+            waitingFor = handler
+            val thisActor = this
+            onTimeout = Some(new TimerTask {
+              def run() { thisActor.send(TIMEOUT, thisActor) }
+            })
+            Actor.timer.schedule(onTimeout.get, msec)
+            throw Actor.suspendException
+          }
+        }
+      } else
+        resumeReceiver((qel.msg, qel.session), handler, false)
+    }
+    throw Actor.suspendException
+  }
+
+  override def getState: Actor.State.Value = synchronized {
+    if (waitingFor ne Reactor.waitingForNone) {
+      if (onTimeout.isEmpty)
+        Actor.State.Suspended
+      else
+        Actor.State.TimedSuspended
+    } else
+      _state
+  }
+
+}
diff --git a/src/actors/scala/actors/ReplyReactorTask.scala b/src/actors/scala/actors/ReplyReactorTask.scala
new file mode 100644
index 0000000..5915027
--- /dev/null
+++ b/src/actors/scala/actors/ReplyReactorTask.scala
@@ -0,0 +1,36 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2005-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |                                         **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+// $Id$
+
+package scala.actors
+
+/** <p>
+ *    The class <code>ReplyReactorTask</code>.
+ *  </p>
+ *
+ *  @author Philipp Haller
+ */
+private[actors] class ReplyReactorTask(reactor: ReplyReactor,
+                                       fun: () => Unit,
+                                       handler: PartialFunction[Any, Any],
+                                       msg: Any)
+  extends ReactorTask(reactor, fun, handler, msg) {
+
+  var saved: ReplyReactor = _
+
+  protected override def beginExecution() {
+    saved = Actor.tl.get
+    Actor.tl set reactor
+  }
+
+  protected override def suspendExecution() {
+    Actor.tl set saved
+  }
+
+}
diff --git a/src/actors/scala/actors/Scheduler.scala b/src/actors/scala/actors/Scheduler.scala
index b0ba55e..ad5d83e 100644
--- a/src/actors/scala/actors/Scheduler.scala
+++ b/src/actors/scala/actors/Scheduler.scala
@@ -1,317 +1,61 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2005-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2005-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Scheduler.scala 18846 2009-10-01 07:30:14Z phaller $
 
 package scala.actors
 
-import java.lang.{Runnable, Thread, InterruptedException}
+import java.util.concurrent._
+import scheduler.{DelegatingScheduler, ForkJoinScheduler, ResizableThreadPoolScheduler, ThreadPoolConfig}
 
 /**
- * The <code>Scheduler</code> object is used by
- * <code>Actor</code> to execute tasks of an execution of an actor.
+ * The <code>Scheduler</code> object is used by <code>Actor</code> to
+ * execute tasks of an actor execution.
  *
- * @version 0.9.18
  * @author Philipp Haller
  */
-object Scheduler extends IScheduler {
+object Scheduler extends DelegatingScheduler {
 
-  def makeNewScheduler: IScheduler = {
-    val s = new FJTaskScheduler2
-    Debug.info(this+": starting new "+s+" ["+s.getClass+"]")
-    s.start()
-    s
-  }
-
-  private var sched: IScheduler =
-    makeNewScheduler
-
-  def impl = {
-    if (!sched.isActive)
-      sched = makeNewScheduler
-    sched
-  }
+  Debug.info("initializing "+this+"...")
 
-  def impl_= (scheduler: IScheduler) = {
-    sched = scheduler
-  }
-
-  private var tasks: LinkedQueue = null
-  private var pendingCount = 0
-
-  /* Assumes <code>sched</code> holds an instance
-   * of <code>FJTaskScheduler2</code>.
-   */
-  def snapshot(): Unit =
-    if (sched.isInstanceOf[FJTaskScheduler2]) {
-      val fjts = sched.asInstanceOf[FJTaskScheduler2]
-      tasks = fjts.snapshot()
-      pendingCount = ActorGC.getPendingCount
-      fjts.shutdown()
-    } else
-      error("snapshot operation not supported.")
-
-  /* Creates an instance of class <code>FJTaskScheduler2</code>
-   * and submits <code>tasks</code> for execution.
-   */
-  def restart(): Unit = synchronized {
-    sched = {
-      val s = new FJTaskScheduler2
-      ActorGC.setPendingCount(pendingCount)
+  def makeNewScheduler: IScheduler = {
+    val sched = if (!ThreadPoolConfig.useForkJoin) {
+      // default is non-daemon
+      val s = new ResizableThreadPoolScheduler(false)
+      s.start()
+      s
+    } else {
+      // default is non-daemon, fair
+      val s = new ForkJoinScheduler
       s.start()
       s
     }
-    //Actor.timer = new java.util.Timer
-    if (tasks ne null) {
-      while (!tasks.isEmpty()) {
-        sched.execute(tasks.take().asInstanceOf[Runnable])
-      }
-      tasks = null
-    }
-  }
-
-  def execute(task: Runnable) {
-/*
-    val t = currentThread
-    if (t.isInstanceOf[FJTaskRunner]) {
-      val tr = t.asInstanceOf[FJTaskRunner]
-      tr.push(new FJTask {
-        def run() { task.run() }
-      })
-    } else
-*/
-      impl execute task
-  }
-
-  def execute(fun: => Unit) {
-/*
-    val t = currentThread
-    if (t.isInstanceOf[FJTaskRunner]) {
-      val tr = t.asInstanceOf[FJTaskRunner]
-      tr.push(new FJTask {
-        def run() { fun }
-      })
-    } else
-*/
-      impl execute { fun }
-  }
-
-  /* This method is used to notify the scheduler
-   * of library activity by the argument Actor.
-   */
-  def tick(a: Actor) = sched tick a
-
-  def shutdown() = sched.shutdown()
-
-  def onLockup(handler: () => Unit) = sched.onLockup(handler)
-  def onLockup(millis: Int)(handler: () => Unit) = sched.onLockup(millis)(handler)
-  def printActorDump = sched.printActorDump
-}
-
-
-/**
- * The <code>IScheduler</code> trait provides a common interface
- * for all schedulers used to execute actor tasks.
- *
- * Subclasses of <code>Actor</code> that override its
- * <code>scheduler</code> member value must provide
- * an implementation of the <code>IScheduler</code>
- * trait.
- *
- * @version 0.9.18
- * @author Philipp Haller
- */
-trait IScheduler {
-
-  /** Submits a closure for execution.
-   *
-   *  @param  fun  the closure to be executed
-   */
-  def execute(fun: => Unit): Unit
-
-  /** Submits a <code>Runnable</code> for execution.
-   *
-   *  @param  task  the task to be executed
-   */
-  def execute(task: Runnable): Unit
-
-  /** Notifies the scheduler about activity of the
-   *  executing actor.
-   *
-   *  @param  a  the active actor
-   */
-  def tick(a: Actor): Unit
-
-  /** Shuts down the scheduler.
-   */
-  def shutdown(): Unit
-
-  @deprecated def onLockup(handler: () => Unit): Unit
-  @deprecated def onLockup(millis: Int)(handler: () => Unit): Unit
-  @deprecated def printActorDump: Unit
-
-  @deprecated
-  val QUIT_TASK = new Reaction(null) {
-    override def run(): Unit = {}
-    override def toString() = "QUIT_TASK"
+    Debug.info(this+": starting new "+sched+" ["+sched.getClass+"]")
+    sched
   }
 
-  private[actors] def isActive: Boolean = true
-}
-
-
- at deprecated
-trait WorkerThreadScheduler extends IScheduler {
-  /**
-   *  @param  worker the worker thread executing tasks
-   *  @return        the task to be executed
+  /* Only <code>ForkJoinScheduler</code> implements this method.
    */
-  def getTask(worker: WorkerThread): Runnable
-}
-
-
-/**
- * This scheduler executes the tasks of an actor on a single
- * thread (the current thread).
- *
- * @version 0.9.18
- * @author Philipp Haller
- */
-class SingleThreadedScheduler extends IScheduler {
-
-  def execute(task: Runnable) {
-    task.run()
+  @deprecated("snapshot will be removed")
+  def snapshot() {
+    if (sched.isInstanceOf[ForkJoinScheduler]) {
+      sched.asInstanceOf[ForkJoinScheduler].snapshot()
+    } else
+      error("scheduler does not implement snapshot")
   }
 
-  def execute(fun: => Unit): Unit =
-    execute(new Runnable {
-      def run() { fun }
-    })
-
-  def tick(a: Actor) {}
-
-  def shutdown() {}
-
-  def onLockup(handler: () => Unit) {}
-  def onLockup(millis: Int)(handler: () => Unit) {}
-  def printActorDump {}
-}
-
-
-/**
- * The <code>QuitException</code> class is used to manage control flow
- * of certain schedulers and worker threads.
- *
- * @version 0.9.8
- * @author Philipp Haller
- */
-private[actors] class QuitException extends Throwable {
-  /*
-   For efficiency reasons we do not fill in
-   the execution stack trace.
+  /* Only <code>ForkJoinScheduler</code> implements this method.
    */
-  override def fillInStackTrace(): Throwable = this
-}
-
-
-/**
- * <p>
- *   The class <code>WorkerThread</code> is used by schedulers to execute
- *   actor tasks on multiple threads.
- * </p>
- * <p>
- *   !!ACHTUNG: If you change this, make sure you understand the following
- *   proof of deadlock-freedom!!
- * </p>
- * <p>
- *   We proof that there is no deadlock between the scheduler and
- *   any worker thread possible. For this, note that the scheduler
- *   only acquires the lock of a worker thread by calling
- *   <code>execute</code>.  This method is only called when the worker thread
- *   is in the idle queue of the scheduler. On the other hand, a
- *   worker thread only acquires the lock of the scheduler when it
- *   calls <code>getTask</code>. At the only callsite of <code>getTask</code>,
- *   the worker thread holds its own lock.
- * </p>
- * <p>
- *   Thus, deadlock can only occur when a worker thread calls
- *   <code>getTask</code> while it is in the idle queue of the scheduler,
- *   because then the scheduler might call (at any time!) <code>execute</code>
- *   which tries to acquire the lock of the worker thread. In such
- *   a situation the worker thread would be waiting to acquire the
- *   lock of the scheduler and vice versa.
- * </p>
- * <p>
- *   Therefore, to prove deadlock-freedom, it suffices to ensure
- *   that a worker thread will never call <code>getTask</code> when
- *   it is in the idle queue of the scheduler.
- * </p>
- * <p>
- *   A worker thread enters the idle queue of the scheduler when
- *   <code>getTask</code> returns <code>null</code>. Then it will also stay
- *   in the while-loop W (<code>while (task eq null)</code>) until
- *   <code>task</code> becomes non-null. The only way this can happen is
- *   through a call of <code>execute</code> by the scheduler. Before every
- *   call of <code>execute</code> the worker thread is removed from the idle
- *   queue of the scheduler. Only then--after executing its task--
- *   the worker thread may call <code>getTask</code>. However, the scheduler
- *   is unable to call <code>execute</code> as the worker thread is not in
- *   the idle queue any more. In fact, the scheduler made sure
- *   that this is the case even _before_ calling <code>execute</code> and
- *   thus releasing the worker thread from the while-loop W. Thus,
- *   the property holds for every possible interleaving of thread
- *   execution. QED
- * </p>
- *
- * @version 0.9.18
- * @author Philipp Haller
- */
- at deprecated
-class WorkerThread(sched: WorkerThreadScheduler) extends Thread {
-  private var task: Runnable = null
-  private[actors] var running = true
-
-  def execute(r: Runnable) = synchronized {
-    task = r
-    notify()
+  @deprecated("restart will be removed")
+  def restart() {
+    if (sched.isInstanceOf[ForkJoinScheduler]) {
+      sched.asInstanceOf[ForkJoinScheduler].restart()
+    } else
+      error("scheduler does not implement restart")
   }
 
-  override def run(): Unit =
-    try {
-      while (running) {
-        if (task ne null) {
-          try {
-            task.run()
-          } catch {
-            case consumed: InterruptedException =>
-              if (!running) throw new QuitException
-          }
-        }
-        this.synchronized {
-          task = sched getTask this
-
-          while (task eq null) {
-            try {
-              wait()
-            } catch {
-              case consumed: InterruptedException =>
-                if (!running) throw new QuitException
-            }
-          }
-
-          if (task == sched.QUIT_TASK) {
-            running = false
-          }
-        }
-      }
-    } catch {
-      case consumed: QuitException =>
-        // allow thread to quit
-    }
-
 }
diff --git a/src/actors/scala/actors/SchedulerAdapter.scala b/src/actors/scala/actors/SchedulerAdapter.scala
index d2313cd..ce27532 100644
--- a/src/actors/scala/actors/SchedulerAdapter.scala
+++ b/src/actors/scala/actors/SchedulerAdapter.scala
@@ -1,11 +1,12 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2005-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2005-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
+
 package scala.actors
 
 /** The <code>SchedulerAdapter</code> trait is used to adapt
@@ -13,9 +14,8 @@ package scala.actors
  *
  *  Providing an implementation for the
  *  <code>execute(f: => Unit)</code> method is sufficient to
- *  obtain a concrete <code>IScheduler</code> class.
+ *  obtain a concrete <code>IScheduler</code> implementation.
  *
- *  @version 0.9.18
  *  @author Philipp Haller
  */
 trait SchedulerAdapter extends IScheduler {
@@ -27,23 +27,41 @@ trait SchedulerAdapter extends IScheduler {
   def execute(task: Runnable): Unit =
     execute { task.run() }
 
-  /** Notifies the scheduler about activity of the
-   *  executing actor.
-   *
-   *  @param  a  the active actor
-   */
-  def tick(a: Actor): Unit =
-    Scheduler tick a
-
   /** Shuts down the scheduler.
    */
   def shutdown(): Unit =
     Scheduler.shutdown()
 
-  def onLockup(handler: () => Unit) {}
+  /** When the scheduler is active, it can execute tasks.
+   */ 
+  def isActive: Boolean =
+    Scheduler.isActive
 
-  def onLockup(millis: Int)(handler: () => Unit) {}
+  /** Registers a newly created actor with this scheduler.
+   *
+   *  @param  a  the actor to be registered
+   */
+  def newActor(a: TrackedReactor) =
+    Scheduler.newActor(a)
+
+  /** Unregisters an actor from this scheduler, because it
+   *  has terminated.
+   * 
+   *  @param  a  the actor to be unregistered
+   */
+  def terminated(a: TrackedReactor) =
+    Scheduler.terminated(a)
 
-  def printActorDump {}
+  /** Registers a closure to be executed when the specified
+   *  actor terminates.
+   * 
+   *  @param  a  the actor
+   *  @param  f  the closure to be registered
+   */
+  def onTerminate(a: TrackedReactor)(f: => Unit) =
+    Scheduler.onTerminate(a)(f)
 
+  def managedBlock(blocker: scala.concurrent.ManagedBlocker) {
+    blocker.block()
+  }
 }
diff --git a/src/actors/scala/actors/TickedScheduler.scala b/src/actors/scala/actors/TickedScheduler.scala
deleted file mode 100644
index 0c18b2b..0000000
--- a/src/actors/scala/actors/TickedScheduler.scala
+++ /dev/null
@@ -1,173 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2005-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: TickedScheduler.scala 18846 2009-10-01 07:30:14Z phaller $
-
-package scala.actors
-
-import java.lang.{Thread, InterruptedException}
-
-import scala.collection.Set
-import scala.collection.mutable.{ArrayBuffer, Buffer, HashMap, Queue}
-import scala.compat.Platform
-
-/**
- * <p>This scheduler uses a thread pool to execute tasks that are generated
- * by the execution of actors.</p>
- *
- * Use class <code>FJTaskScheduler2</code> instead.
- *
- * @version 0.9.18
- * @author Philipp Haller
- */
- at deprecated
-class TickedScheduler extends Thread with WorkerThreadScheduler {
-  // as long as this thread runs, JVM should not exit
-  setDaemon(false)
-
-  private val tasks = new Queue[Runnable]
-
-  // Worker threads
-  private val workers: Buffer[WorkerThread] = new ArrayBuffer[WorkerThread]
-  private val idle = new Queue[WorkerThread]
-  private val ticks = new HashMap[WorkerThread, Long]
-
-  private var terminating = false
-
-  private var lastActivity = Platform.currentTime
-
-  def printActorDump {}
-
-  private var TICK_FREQ = 5
-  private var CHECK_FREQ = 50
-
-  for (i <- List.range(0, 2)) {
-    val worker = new WorkerThread(this)
-    workers += worker
-    worker.start()
-  }
-
-  def onLockup(handler: () => Unit) {
-    lockupHandler = handler
-  }
-
-  def onLockup(millis: Int)(handler: () => Unit) {
-    //LOCKUP_CHECK_FREQ = millis / CHECK_FREQ
-    lockupHandler = handler
-  }
-
-  private var lockupHandler: () => Unit = null
-
-  override def run() {
-    try {
-      while (!terminating) {
-        this.synchronized {
-          try {
-            wait(CHECK_FREQ)
-          } catch {
-            case _: InterruptedException =>
-              if (terminating) throw new QuitException
-          }
-
-          if (tasks.length > 0) {
-            // check if we need more threads
-            if (Platform.currentTime - lastActivity >= TICK_FREQ) {
-              val newWorker = new WorkerThread(this)
-              workers += newWorker
-
-              // dequeue item to be processed
-              val item = tasks.dequeue
-
-              newWorker.execute(item)
-              newWorker.start()
-            }
-          } // tasks.length > 0
-          else {
-            if (ActorGC.allTerminated) {
-              // if all worker threads idle terminate
-              if (workers.length == idle.length) {
-                Debug.info(this+": initiating shutdown...")
-
-                val idleThreads = idle.elements
-                while (idleThreads.hasNext) {
-                  val worker = idleThreads.next
-                  worker.running = false
-                  worker.interrupt()
-                }
-                // terminate timer thread
-                Actor.timer.cancel()
-                throw new QuitException
-              }
-            }
-          }
-        } // sync
-
-      } // while (!terminating)
-    } catch {
-      case _: QuitException =>
-        // allow thread to exit
-    }
-  }
-
-  /**
-   *  @param item the task to be executed.
-   */
-  def execute(item: Runnable): Unit = synchronized {
-    if (!terminating) {
-      if (idle.length > 0) {
-        val wt = idle.dequeue
-        wt.execute(item)
-      }
-      else
-        tasks += item
-    }
-  }
-
-  def execute(fun: => Unit): Unit =
-    execute(new Runnable {
-      def run() { fun }
-    })
-
-  /**
-   *  @param worker the worker thread executing tasks
-   *  @return       the executed task
-   */
-  def getTask(worker: WorkerThread) = synchronized {
-    if (terminating)
-      QUIT_TASK
-    if (tasks.length > 0) {
-      val item = tasks.dequeue
-      item
-    }
-    else {
-      idle += worker
-      null
-    }
-  }
-
-  /**
-   *  @param a the actor
-   */
-  def tick(a: Actor) {
-    lastActivity = Platform.currentTime
-  }
-
-  /** Shuts down all idle worker threads.
-   */
-  def shutdown(): Unit = synchronized {
-    terminating = true
-    val idleThreads = idle.elements
-    while (idleThreads.hasNext) {
-      val worker = idleThreads.next
-      worker.running = false
-      worker.interrupt()
-    }
-    // terminate timer thread
-    Actor.timer.cancel()
-  }
-}
diff --git a/src/actors/scala/actors/UncaughtException.scala b/src/actors/scala/actors/UncaughtException.scala
new file mode 100644
index 0000000..2b61b1a
--- /dev/null
+++ b/src/actors/scala/actors/UncaughtException.scala
@@ -0,0 +1,33 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2005-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |                                         **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+package scala.actors
+
+/**
+ * The exit reason when an actor fails to catch an exception.
+ *
+ * @param actor   the actor that threw the exception
+ * @param message the message the actor was processing, or None if no message (e.g. on initial startup)
+ * @param sender  the sender of the most recent message
+ * @param thread  the thread on which the actor was running
+ * @param cause   the uncaught exception
+ *
+ * @author Philipp Haller
+ * @author Erik Engbrecht
+ */
+case class UncaughtException(actor: Actor,
+                             message: Option[Any],
+                             sender: Option[OutputChannel[Any]],
+                             thread: Thread,
+                             cause: Throwable)
+extends Exception(cause) {
+
+  override def toString() =
+    "UncaughtException("+actor+","+message+","+sender+","+cause+")"
+
+}
diff --git a/src/actors/scala/actors/package.scala b/src/actors/scala/actors/package.scala
new file mode 100644
index 0000000..66ba05b
--- /dev/null
+++ b/src/actors/scala/actors/package.scala
@@ -0,0 +1,32 @@
+package scala
+
+package object actors {
+
+  // type of Reactors tracked by termination detector
+  private[actors] type TrackedReactor = Reactor[A] forSome { type A >: Null }
+
+  @deprecated("use scheduler.ForkJoinScheduler instead")
+  type FJTaskScheduler2 = scala.actors.scheduler.ForkJoinScheduler
+
+  @deprecated("use scheduler.ForkJoinScheduler instead")
+  type TickedScheduler = scala.actors.scheduler.ForkJoinScheduler
+
+  @deprecated("use scheduler.ForkJoinScheduler instead")
+  type WorkerThreadScheduler = scala.actors.scheduler.ForkJoinScheduler
+
+  @deprecated("this class is going to be removed in a future release")
+  type WorkerThread = java.lang.Thread
+
+  @deprecated("use scheduler.SingleThreadedScheduler instead")
+  type SingleThreadedScheduler = scala.actors.scheduler.SingleThreadedScheduler
+
+  // This used to do a blind cast and throw a CCE after the package
+  // object was loaded.  I have replaced with a variation that should work
+  // in whatever cases that was working but fail less exceptionally for
+  // those not intentionally using it.
+  @deprecated("this value is going to be removed in a future release")
+  val ActorGC = scala.actors.Scheduler.impl match {
+    case x: scala.actors.scheduler.ActorGC  => x
+    case _                                  => null
+  }
+}
diff --git a/src/actors/scala/actors/remote/FreshNameCreator.scala b/src/actors/scala/actors/remote/FreshNameCreator.scala
index 1119be8..f7cfcab 100644
--- a/src/actors/scala/actors/remote/FreshNameCreator.scala
+++ b/src/actors/scala/actors/remote/FreshNameCreator.scala
@@ -1,16 +1,16 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2005-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2005-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: FreshNameCreator.scala 18830 2009-09-29 22:53:36Z phaller $
 
-package scala.actors.remote
+package scala.actors
+package remote
 
-private[remote] object FreshNameCreator {
+object FreshNameCreator {
 
   protected var counter = 0
   protected val counters = new scala.collection.mutable.HashMap[String, Int]
diff --git a/src/actors/scala/actors/remote/JavaSerializer.scala b/src/actors/scala/actors/remote/JavaSerializer.scala
index 61bdc01..5d9f981 100644
--- a/src/actors/scala/actors/remote/JavaSerializer.scala
+++ b/src/actors/scala/actors/remote/JavaSerializer.scala
@@ -1,14 +1,14 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2005-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2005-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: JavaSerializer.scala 18830 2009-09-29 22:53:36Z phaller $
 
-package scala.actors.remote
+package scala.actors
+package remote
 
 import java.io.{ByteArrayInputStream, ByteArrayOutputStream,
                 ObjectInputStream, ObjectOutputStream, InputStream,
@@ -17,20 +17,29 @@ import java.io.{ByteArrayInputStream, ByteArrayOutputStream,
 /**
  *  @author Guy Oliver
  */
-private[remote] class CustomObjectInputStream(os: InputStream, cl: ClassLoader) extends ObjectInputStream(os) {
-  override def resolveClass(cd: ObjectStreamClass): Class[T] forSome { type T } =
+private[remote] class CustomObjectInputStream(in: InputStream, cl: ClassLoader)
+extends ObjectInputStream(in) {
+  override def resolveClass(cd: ObjectStreamClass): Class[_] =
     try {
       cl.loadClass(cd.getName())
     } catch {
       case cnf: ClassNotFoundException =>
         super.resolveClass(cd)
     }
+  override def resolveProxyClass(interfaces: Array[String]): Class[_] =
+    try {
+      val ifaces = interfaces map { iface => cl.loadClass(iface) }
+      java.lang.reflect.Proxy.getProxyClass(cl, ifaces: _*)
+    } catch {
+      case e: ClassNotFoundException =>
+        super.resolveProxyClass(interfaces)
+    }
 }
 
 /**
  *  @author Philipp Haller
  */
-private[remote] class JavaSerializer(serv: Service, cl: ClassLoader) extends Serializer(serv) {
+class JavaSerializer(serv: Service, cl: ClassLoader) extends Serializer(serv) {
   def serialize(o: AnyRef): Array[Byte] = {
     val bos = new ByteArrayOutputStream()
     val out = new ObjectOutputStream(bos)
diff --git a/src/actors/scala/actors/remote/NetKernel.scala b/src/actors/scala/actors/remote/NetKernel.scala
index a72237d..a5ec3e3 100644
--- a/src/actors/scala/actors/remote/NetKernel.scala
+++ b/src/actors/scala/actors/remote/NetKernel.scala
@@ -1,28 +1,26 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2005-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2005-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: NetKernel.scala 18846 2009-10-01 07:30:14Z phaller $
 
-package scala.actors.remote
+package scala.actors
+package remote
 
 import scala.collection.mutable.{HashMap, HashSet}
 
-private[remote] case class NamedSend(senderLoc: Locator, receiverLoc: Locator, data: Array[Byte], session: Symbol)
+case class NamedSend(senderLoc: Locator, receiverLoc: Locator, data: Array[Byte], session: Symbol)
 
-private[remote] case class RemoteApply0(senderLoc: Locator, receiverLoc: Locator, rfun: Function2[AbstractActor, Proxy, Unit])
+case class RemoteApply0(senderLoc: Locator, receiverLoc: Locator, rfun: Function2[AbstractActor, Proxy, Unit])
+case class LocalApply0(rfun: Function2[AbstractActor, Proxy, Unit], a: AbstractActor)
 
-private[remote] case class LocalApply0(rfun: Function2[AbstractActor, Proxy, Unit], a: AbstractActor)
+case class  SendTo(a: OutputChannel[Any], msg: Any, session: Symbol)
+case object Terminate
 
-private[remote] case class SendTo(a: OutputChannel[Any], msg: Any, session: Symbol)
-
-private[remote] case object Terminate
-
-private[remote] case class Locator(node: Node, name: Symbol)
+case class Locator(node: Node, name: Symbol)
 
 /**
  * @version 0.9.17
@@ -141,7 +139,7 @@ private[remote] class NetKernel(service: Service) {
 
   def terminate() {
     // tell all proxies to terminate
-    proxies.values foreach { p => p.send(Terminate, null) }
+    proxies.values foreach { _.send(Terminate, null) }
 
     // tell service to terminate
     service.terminate()
diff --git a/src/actors/scala/actors/remote/Proxy.scala b/src/actors/scala/actors/remote/Proxy.scala
index 0ff16b7..625ce8b 100644
--- a/src/actors/scala/actors/remote/Proxy.scala
+++ b/src/actors/scala/actors/remote/Proxy.scala
@@ -1,23 +1,22 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2005-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2005-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id$
 
-package scala.actors.remote
+package scala.actors
+package remote
 
 import scala.collection.mutable.HashMap
 
 /**
- * @version 0.9.17
  * @author Philipp Haller
  */
 @serializable
-class Proxy(node: Node, name: Symbol, @transient var kernel: NetKernel) extends AbstractActor {
+private[remote] class Proxy(node: Node, name: Symbol, @transient var kernel: NetKernel) extends AbstractActor {
   import java.io.{IOException, ObjectOutputStream, ObjectInputStream}
 
   @transient
@@ -42,7 +41,7 @@ class Proxy(node: Node, name: Symbol, @transient var kernel: NetKernel) extends
   }
 
   private def setupKernel() {
-    kernel = RemoteActor.someKernel
+    kernel = RemoteActor.someNetKernel
     kernel.registerProxy(node, name, this)
   }
 
@@ -84,7 +83,7 @@ class Proxy(node: Node, name: Symbol, @transient var kernel: NetKernel) extends
 }
 
 @serializable
-private[remote] class LinkToFun extends Function2[AbstractActor, Proxy, Unit] {
+class LinkToFun extends Function2[AbstractActor, Proxy, Unit] {
   def apply(target: AbstractActor, creator: Proxy) {
     target.linkTo(creator)
   }
@@ -93,7 +92,7 @@ private[remote] class LinkToFun extends Function2[AbstractActor, Proxy, Unit] {
 }
 
 @serializable
-private[remote] class UnlinkFromFun extends Function2[AbstractActor, Proxy, Unit] {
+class UnlinkFromFun extends Function2[AbstractActor, Proxy, Unit] {
   def apply(target: AbstractActor, creator: Proxy) {
     target.unlinkFrom(creator)
   }
@@ -102,7 +101,7 @@ private[remote] class UnlinkFromFun extends Function2[AbstractActor, Proxy, Unit
 }
 
 @serializable
-private[remote] class ExitFun(reason: AnyRef) extends Function2[AbstractActor, Proxy, Unit] {
+class ExitFun(reason: AnyRef) extends Function2[AbstractActor, Proxy, Unit] {
   def apply(target: AbstractActor, creator: Proxy) {
     target.exit(creator, reason)
   }
@@ -113,12 +112,11 @@ private[remote] class ExitFun(reason: AnyRef) extends Function2[AbstractActor, P
 private[remote] case class Apply0(rfun: Function2[AbstractActor, Proxy, Unit])
 
 /**
- * @version 0.9.17
  * @author Philipp Haller
  */
 private[remote] class DelegateActor(creator: Proxy, node: Node, name: Symbol, kernel: NetKernel) extends Actor {
   var channelMap = new HashMap[Symbol, OutputChannel[Any]]
-  var sessionMap = new HashMap[Channel[Any], Symbol]
+  var sessionMap = new HashMap[OutputChannel[Any], Symbol]
 
   def act() {
     Actor.loop {
@@ -132,26 +130,25 @@ private[remote] class DelegateActor(creator: Proxy, node: Node, name: Symbol, ke
         // Request from remote proxy.
         // `this` is local proxy.
         case cmd at SendTo(out, msg, session) =>
-          // is this an active session?
-          channelMap.get(session) match {
-            case None =>
-              // create a new reply channel...
-              val replyCh = new Channel[Any](this)
-          
-              // ...that maps to session
-              sessionMap += Pair(replyCh, session)
-          
-              // local send
-              out.send(msg, replyCh)
-
-            case Some(replyCh) =>
-              replyCh ! msg
-              // TODO:
-              // remove `replyCh` from mapping
-              // to avoid memory leak (always safe?)
-              // or: use WeakHashMap
-              // however, it's the value (channel)
-              // that should be weak!
+          if (session.name == "nosession") {
+            // local send
+            out.send(msg, this)
+          } else {
+            // is this an active session?
+            channelMap.get(session) match {
+              case None =>
+                // create a new reply channel...
+                val replyCh = new Channel[Any](this)
+                // ...that maps to session
+                sessionMap += Pair(replyCh, session)
+                // local send
+                out.send(msg, replyCh)
+
+              // finishes request-reply cycle
+              case Some(replyCh) =>
+                channelMap -= session
+                replyCh ! msg
+            }
           }
 
         case cmd at Terminate =>
@@ -163,6 +160,7 @@ private[remote] class DelegateActor(creator: Proxy, node: Node, name: Symbol, ke
           // lookup session ID
           sessionMap.get(ch) match {
             case Some(sid) =>
+              sessionMap -= ch
               val msg = resp.asInstanceOf[AnyRef]
               // send back response
               kernel.forward(sender, node, name, msg, sid)
@@ -173,13 +171,16 @@ private[remote] class DelegateActor(creator: Proxy, node: Node, name: Symbol, ke
 
         // remote proxy receives request
         case msg: AnyRef =>
-          // create fresh session ID...
-          val sid = FreshNameCreator.newName(node+"@"+name)
-
-          // ...that maps to reply channel
-          channelMap += Pair(sid, sender)
-
-          kernel.forward(sender, node, name, msg, sid)
+          // find out whether it's a synchronous send
+          if (sender.getClass.toString.contains("Channel")) {
+            // create fresh session ID...
+            val fresh = FreshNameCreator.newName(node+"@"+name)
+            // ...that maps to reply channel
+            channelMap += Pair(fresh, sender)
+            kernel.forward(sender, node, name, msg, fresh)
+          } else {
+            kernel.forward(sender, node, name, msg, 'nosession)
+          }
       }
     }
   }
diff --git a/src/actors/scala/actors/remote/RemoteActor.scala b/src/actors/scala/actors/remote/RemoteActor.scala
index 9baa6fa..c5397bc 100644
--- a/src/actors/scala/actors/remote/RemoteActor.scala
+++ b/src/actors/scala/actors/remote/RemoteActor.scala
@@ -1,44 +1,41 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2005-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2005-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: RemoteActor.scala 18846 2009-10-01 07:30:14Z phaller $
 
 
-package scala.actors.remote
+package scala.actors
+package remote
 
 
-/** <p>
- *    This object provides methods for creating, registering, and
- *    selecting remotely accessible actors.
- *  </p>
- *  <p>
- *    A remote actor is typically created like this:
- *  </p><pre>
+/**
+ *  This object provides methods for creating, registering, and
+ *  selecting remotely accessible actors.
+ *
+ *  A remote actor is typically created like this:
+ *  {{{
  *  actor {
  *    alive(9010)
  *    register('myName, self)
  *
  *    // behavior
  *  }
- *  </pre>
- *  <p>
- *    It can be accessed by an actor running on a (possibly)
- *    different node by selecting it in the following way:
- *  </p><pre>
+ *  }}}
+ *  It can be accessed by an actor running on a (possibly)
+ *  different node by selecting it in the following way:
+ *  {{{
  *  actor {
  *    // ...
- *    <b>val</b> c = select(Node("127.0.0.1", 9010), 'myName)
+ *    val c = select(Node("127.0.0.1", 9010), 'myName)
  *    c ! msg
  *    // ...
  *  }
- *  </pre>
+ *  }}}
  *
- * @version 0.9.18
  * @author Philipp Haller
  */
 object RemoteActor {
@@ -59,22 +56,22 @@ object RemoteActor {
    * <code>port</code>.
    */
   def alive(port: Int): Unit = synchronized {
-    createKernelOnPort(port)
+    createNetKernelOnPort(port)
   }
 
-  private[remote] def createKernelOnPort(port: Int): NetKernel = {
+  private def createNetKernelOnPort(port: Int): NetKernel = {
     val serv = TcpService(port, cl)
     val kern = serv.kernel
     val s = Actor.self
     kernels += Pair(s, kern)
 
-    ActorGC.onTerminate(s) {
+    s.onTerminate {
       Debug.info("alive actor "+s+" terminated")
       // remove mapping for `s`
       kernels -= s
       // terminate `kern` when it does
       // not appear as value any more
-      if (!kernels.values.contains(kern)) {
+      if (!kernels.valuesIterator.contains(kern)) {
         Debug.info("terminating "+kern)
         // terminate NetKernel
         kern.terminate()
@@ -84,6 +81,10 @@ object RemoteActor {
     kern
   }
 
+  @deprecated("this member is going to be removed in a future release")
+  def createKernelOnPort(port: Int): NetKernel =
+    createNetKernelOnPort(port)
+
   /**
    * Registers <code>a</code> under <code>name</code> on this
    * node.
@@ -104,7 +105,7 @@ object RemoteActor {
     case None =>
       // establish remotely accessible
       // return path (sender)
-      createKernelOnPort(TcpService.generatePort)
+      createNetKernelOnPort(TcpService.generatePort)
     case Some(k) =>
       k
   }
@@ -117,8 +118,12 @@ object RemoteActor {
     selfKernel.getOrCreateProxy(node, sym)
   }
 
-  private[remote] def someKernel: NetKernel =
-    kernels.values.next
+  private[remote] def someNetKernel: NetKernel =
+    kernels.valuesIterator.next
+
+  @deprecated("this member is going to be removed in a future release")
+  def someKernel: NetKernel =
+    someNetKernel
 }
 
 
diff --git a/src/actors/scala/actors/remote/Serializer.scala b/src/actors/scala/actors/remote/Serializer.scala
index ec9e9dd..e6f5bd5 100644
--- a/src/actors/scala/actors/remote/Serializer.scala
+++ b/src/actors/scala/actors/remote/Serializer.scala
@@ -1,32 +1,32 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2005-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2005-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Serializer.scala 18830 2009-09-29 22:53:36Z phaller $
 
 
-package scala.actors.remote
+package scala.actors
+package remote
 
 
 import java.lang.ClassNotFoundException
 
 import java.io.{DataInputStream, DataOutputStream, EOFException, IOException}
 
-private[remote] abstract class Serializer(val service: Service) {
+abstract class Serializer(val service: Service) {
   def serialize(o: AnyRef): Array[Byte]
   def deserialize(a: Array[Byte]): AnyRef
 
   @throws(classOf[IOException])
-  def readBytes(inputStream: DataInputStream): Array[Byte] = {
+  private def readBytes(inputStream: DataInputStream): Array[Byte] = {
     try {
       val length = inputStream.readInt()
       val bytes = new Array[Byte](length)
       inputStream.readFully(bytes, 0, length)
-      return bytes
+      bytes
     }
     catch {
       case npe: NullPointerException =>
@@ -41,7 +41,7 @@ private[remote] abstract class Serializer(val service: Service) {
   }
 
   @throws(classOf[IOException])
-  def writeBytes(outputStream: DataOutputStream, bytes: Array[Byte]) {
+  private def writeBytes(outputStream: DataOutputStream, bytes: Array[Byte]) {
     val length = bytes.length;
     // original length
     outputStream.writeInt(length)
diff --git a/src/actors/scala/actors/remote/Service.scala b/src/actors/scala/actors/remote/Service.scala
index af3c08d..298d87e 100644
--- a/src/actors/scala/actors/remote/Service.scala
+++ b/src/actors/scala/actors/remote/Service.scala
@@ -1,20 +1,20 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2005-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2005-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Service.scala 18846 2009-10-01 07:30:14Z phaller $
 
-package scala.actors.remote
+package scala.actors
+package remote
 
 /**
  * @version 0.9.10
  * @author Philipp Haller
  */
-private[remote] trait Service {
+trait Service {
   val kernel = new NetKernel(this)
   val serializer: Serializer
   def node: Node
diff --git a/src/actors/scala/actors/remote/TcpService.scala b/src/actors/scala/actors/remote/TcpService.scala
index 49185c3..a6f7adf 100644
--- a/src/actors/scala/actors/remote/TcpService.scala
+++ b/src/actors/scala/actors/remote/TcpService.scala
@@ -1,15 +1,15 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2005-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2005-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: TcpService.scala 18846 2009-10-01 07:30:14Z phaller $
 
 
-package scala.actors.remote
+package scala.actors
+package remote
 
 
 import java.io.{DataInputStream, DataOutputStream, IOException}
@@ -24,7 +24,7 @@ import scala.util.Random
  * @version 0.9.9
  * @author Philipp Haller
  */
-private[remote] object TcpService {
+object TcpService {
   private val random = new Random
   private val ports = new HashMap[Int, TcpService]
 
@@ -67,7 +67,7 @@ private[remote] object TcpService {
  * @version 0.9.10
  * @author Philipp Haller
  */
-private[remote] class TcpService(port: Int, cl: ClassLoader) extends Thread with Service {
+class TcpService(port: Int, cl: ClassLoader) extends Thread with Service {
   val serializer: JavaSerializer = new JavaSerializer(this, cl)
 
   private val internalNode = new Node(InetAddress.getLocalHost().getHostAddress(), port)
@@ -138,7 +138,7 @@ private[remote] class TcpService(port: Int, cl: ClassLoader) extends Thread with
     try {
       val socket = new ServerSocket(port)
       while (!shouldTerminate) {
-        Debug.info(this+": waiting for new connection...")
+        Debug.info(this+": waiting for new connection on port "+port+"...")
         val nextClient = socket.accept()
         if (!shouldTerminate) {
           val worker = new TcpServiceWorker(this, nextClient)
@@ -149,18 +149,11 @@ private[remote] class TcpService(port: Int, cl: ClassLoader) extends Thread with
           nextClient.close()
       }
     } catch {
-      case ioe: IOException =>
-        Debug.info(this+": caught "+ioe)
-      case sec: SecurityException =>
-        Debug.info(this+": caught "+sec)
       case e: Exception =>
         Debug.info(this+": caught "+e)
     } finally {
       Debug.info(this+": shutting down...")
-
-      var workers: List[TcpServiceWorker] = List()
-      connections.values foreach { w => workers = w :: workers }
-      workers foreach { w => w.halt }
+      connections foreach { case (_, worker) => worker.halt }
     }
   }
 
@@ -182,8 +175,8 @@ private[remote] class TcpService(port: Int, cl: ClassLoader) extends Thread with
   }
 
   def connect(n: Node): TcpServiceWorker = synchronized {
-    val sock = new Socket(n.address, n.port)
-    val worker = new TcpServiceWorker(this, sock)
+    val socket = new Socket(n.address, n.port)
+    val worker = new TcpServiceWorker(this, socket)
     worker.sendNode(n)
     worker.start()
     addConnection(n, worker)
@@ -192,13 +185,11 @@ private[remote] class TcpService(port: Int, cl: ClassLoader) extends Thread with
 
   def disconnectNode(n: Node) = synchronized {
     connections.get(n) match {
-      case None => {
+      case None =>
         // do nothing
-      }
-      case Some(worker) => {
+      case Some(worker) =>
         connections -= n
         worker.halt
-      }
     }
   }
 
@@ -219,27 +210,23 @@ private[remote] class TcpService(port: Int, cl: ClassLoader) extends Thread with
 }
 
 
-private[remote] class TcpServiceWorker(parent: TcpService, so: Socket) extends Thread {
-  val in = so.getInputStream()
-  val out = so.getOutputStream()
-
-  val datain = new DataInputStream(in)
-  val dataout = new DataOutputStream(out)
+private[actors] class TcpServiceWorker(parent: TcpService, so: Socket) extends Thread {
+  val datain = new DataInputStream(so.getInputStream)
+  val dataout = new DataOutputStream(so.getOutputStream)
 
   var connectedNode: Node = _
 
-  def sendNode(n: Node) = {
+  def sendNode(n: Node) {
     connectedNode = n
     parent.serializer.writeObject(dataout, parent.node)
   }
 
-  def readNode = {
+  def readNode {
     val node = parent.serializer.readObject(datain)
     node match {
-      case n: Node => {
+      case n: Node =>
         connectedNode = n
         parent.addConnection(n, this)
-      }
     }
   }
 
@@ -272,6 +259,6 @@ private[remote] class TcpServiceWorker(parent: TcpService, so: Socket) extends T
         Debug.info(this+": caught "+e)
         parent nodeDown connectedNode
     }
-    Debug.info(this+": terminated")
+    Debug.info(this+": service terminated at "+parent.node)
   }
 }
diff --git a/src/actors/scala/actors/scheduler/ActorGC.scala b/src/actors/scala/actors/scheduler/ActorGC.scala
new file mode 100644
index 0000000..059eedf
--- /dev/null
+++ b/src/actors/scala/actors/scheduler/ActorGC.scala
@@ -0,0 +1,101 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2005-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+package scala.actors
+package scheduler
+
+import java.lang.ref.{Reference, WeakReference, ReferenceQueue}
+
+import scala.collection.mutable.HashSet
+
+/**
+ * ActorGC keeps track of the number of live actors being managed by a
+ * a scheduler so that it can shutdown when all of the actors it manages have
+ * either been explicitly terminated or garbage collected.
+ *
+ * When an actor is started, it is registered with the ActorGC via the
+ * <code>newActor</code> method, and when an actor is knowingly terminated
+ * (e.g. act method finishes, exit explicitly called, an exception is thrown),
+ * the ActorGC is informed via the <code>terminated</code> method.
+ */
+trait ActorGC extends TerminationMonitor {
+  self: IScheduler =>
+
+  /** Actors are added to refQ in newActor. */
+  private val refQ = new ReferenceQueue[TrackedReactor]
+
+  /**
+   * This is a set of references to all the actors registered with
+   * this ActorGC. It is maintained so that the WeakReferences will not be GC'd
+   * before the actors to which they point.
+   */
+  private val refSet = new HashSet[Reference[t] forSome { type t <: TrackedReactor }]
+
+  /** newActor is invoked whenever a new actor is started. */
+  override def newActor(a: TrackedReactor) = synchronized {
+    // registers a reference to the actor with the ReferenceQueue
+    val wr = new WeakReference[TrackedReactor](a, refQ)
+    refSet += wr
+    activeActors += 1
+  }
+
+  /** Checks for actors that have become garbage. */
+  protected override def gc() = synchronized {
+    // check for unreachable actors
+    def drainRefQ() {
+      val wr = refQ.poll
+      if (wr != null) {
+        activeActors -= 1
+        refSet -= wr
+        // continue draining
+        drainRefQ()
+      }
+    }
+    drainRefQ()
+  }
+
+  /** Prints some status information on currently managed actors. */
+  protected def status() {
+    println(this+": size of refSet: "+refSet.size)
+  }
+
+  /** Checks whether all actors have terminated. */
+  override private[actors] def allActorsTerminated: Boolean = synchronized {
+    activeActors <= 0
+  }
+
+  override def onTerminate(a: TrackedReactor)(f: => Unit): Unit = synchronized {
+    terminationHandlers += (a -> (() => f))
+  }
+
+  override def terminated(a: TrackedReactor) = {
+    super.terminated(a)
+
+    synchronized {
+      // find the weak reference that points to the terminated actor, if any
+      refSet.find((ref: Reference[t] forSome { type t <: TrackedReactor }) => ref.get() == a) match {
+        case Some(r) =>
+          // invoking clear will not cause r to be enqueued
+          r.clear()
+          refSet -= r.asInstanceOf[Reference[t] forSome { type t <: TrackedReactor }]
+        case None =>
+          // do nothing
+      }
+    }
+  }
+
+  private[actors] def getPendingCount = synchronized {
+    activeActors
+  }
+
+  private[actors] def setPendingCount(cnt: Int) = synchronized {
+    activeActors = cnt
+  }
+
+}
diff --git a/src/actors/scala/actors/scheduler/DaemonScheduler.scala b/src/actors/scala/actors/scheduler/DaemonScheduler.scala
new file mode 100644
index 0000000..257e847
--- /dev/null
+++ b/src/actors/scala/actors/scheduler/DaemonScheduler.scala
@@ -0,0 +1,33 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2005-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+package scala.actors
+package scheduler
+
+/**
+ * Default scheduler for actors with daemon semantics, such as those backing futures.
+ *
+ * @author Erik Engbrecht
+ */
+object DaemonScheduler extends DelegatingScheduler {
+
+  protected def makeNewScheduler(): IScheduler = {
+    val sched = if (!ThreadPoolConfig.useForkJoin) {
+      val s = new ResizableThreadPoolScheduler(true)
+      s.start()
+      s
+    } else {
+      val s = new ForkJoinScheduler(true)
+      s.start()
+      s
+    }
+    Debug.info(this+": starting new "+sched+" ["+sched.getClass+"]")
+    sched
+  }
+
+}
diff --git a/src/actors/scala/actors/scheduler/DelegatingScheduler.scala b/src/actors/scala/actors/scheduler/DelegatingScheduler.scala
new file mode 100644
index 0000000..193b1e3
--- /dev/null
+++ b/src/actors/scala/actors/scheduler/DelegatingScheduler.scala
@@ -0,0 +1,74 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2005-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+package scala.actors
+package scheduler
+
+import scala.concurrent.ManagedBlocker
+
+/**
+ * @author Erik Engbrecht
+ */
+private[actors] trait DelegatingScheduler extends IScheduler {
+  protected def makeNewScheduler(): IScheduler
+
+  protected var sched: IScheduler = null
+
+  final def impl = synchronized {
+    if ((sched eq null) || (!sched.isActive))
+      sched = makeNewScheduler()
+    sched
+  }
+
+  final def impl_= (scheduler: IScheduler): Unit = synchronized {
+    //TODO: if there is already a scheduler, should it be shutdown?
+    sched = scheduler
+  }
+
+  /**
+   * Always active because it will just make a new scheduler if required
+   */
+  def isActive: Boolean = true
+
+  def execute(fun: => Unit) = impl.execute(fun)
+
+  def execute(task: Runnable) = impl.execute(task)
+
+  override def executeFromActor(task: Runnable) = impl.executeFromActor(task)
+
+  def shutdown(): Unit = synchronized {
+    if (sched ne null) {
+      sched.shutdown()
+      sched = null
+    }
+  }
+
+  def newActor(actor: TrackedReactor) = synchronized {
+    val createNew = if (sched eq null)
+      true
+    else sched.synchronized {
+      if (!sched.isActive)
+        true
+      else {
+        sched.newActor(actor)
+        false
+      }
+    }
+    if (createNew) {
+      sched = makeNewScheduler()
+      sched.newActor(actor)
+    }
+  }
+
+  def terminated(actor: TrackedReactor) = impl.terminated(actor)
+
+  def onTerminate(actor: TrackedReactor)(f: => Unit) = impl.onTerminate(actor)(f)
+
+  override def managedBlock(blocker: ManagedBlocker): Unit =
+    impl.managedBlock(blocker)
+}
diff --git a/src/actors/scala/actors/scheduler/DrainableForkJoinPool.scala b/src/actors/scala/actors/scheduler/DrainableForkJoinPool.scala
new file mode 100644
index 0000000..257fe92
--- /dev/null
+++ b/src/actors/scala/actors/scheduler/DrainableForkJoinPool.scala
@@ -0,0 +1,12 @@
+package scala.actors
+package scheduler
+
+import java.util.Collection
+import scala.concurrent.forkjoin.{ForkJoinPool, ForkJoinTask}
+
+private class DrainableForkJoinPool extends ForkJoinPool {
+
+  override def drainTasksTo(c: Collection[ForkJoinTask[_]]): Int =
+    super.drainTasksTo(c)
+
+}
diff --git a/src/actors/scala/actors/scheduler/ExecutorScheduler.scala b/src/actors/scala/actors/scheduler/ExecutorScheduler.scala
new file mode 100644
index 0000000..d9194c0
--- /dev/null
+++ b/src/actors/scala/actors/scheduler/ExecutorScheduler.scala
@@ -0,0 +1,93 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2005-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+package scala.actors
+package scheduler
+
+import java.util.concurrent.{Callable, ExecutorService}
+import scala.concurrent.ThreadPoolRunner
+
+/**
+ * The <code>ExecutorScheduler</code> object is used to create
+ * <code>ExecutorScheduler</code> instances.
+ *
+ * @author Philipp Haller
+ */
+object ExecutorScheduler {
+
+  private def start(sched: ExecutorScheduler): ExecutorScheduler = {
+    sched.start()
+    sched
+  }
+
+  /** Creates an <code>ExecutorScheduler</code> using the provided
+   *  <code>ExecutorService</code>.
+   *
+   *  @param  exec the executor to use
+   *  @return      the scheduler
+   */
+  def apply(exec: ExecutorService): ExecutorScheduler =
+    start(new ExecutorScheduler {
+      val executor: ExecutorService = exec
+    })
+
+  /** Creates an <code>ExecutorScheduler</code> using the provided
+   *  <code>ExecutorService</code>.
+   *
+   *  @param  exec the executor to use
+   *  @param  term whether the scheduler should automatically terminate
+   *  @return      the scheduler
+   */
+  def apply(exec: ExecutorService, term: Boolean): ExecutorScheduler =
+    start(new ExecutorScheduler {
+      val executor: ExecutorService = exec
+      override val terminate = term
+    })
+
+}
+
+/**
+ * The <code>ExecutorScheduler</code> class uses an
+ * <code>ExecutorService</code> to execute <code>Actor</code>s.
+ *
+ * @author Philipp Haller
+ */
+trait ExecutorScheduler extends Thread
+                        with IScheduler with TerminationService
+                        with ThreadPoolRunner {
+
+  def execute(task: Runnable) {
+    super[ThreadPoolRunner].execute(task.asInstanceOf[Task[Unit]])
+  }
+
+  private class RunCallable(fun: => Unit) extends Callable[Unit] with Runnable {
+    def call() { fun }
+    def run() { fun }
+  }
+
+  /** Submits a closure for execution.
+   *
+   *  @param  fun  the closure to be executed
+   */
+  override def execute(fun: => Unit) {
+    super[ThreadPoolRunner].execute((new RunCallable(fun)).asInstanceOf[Task[Unit]])
+  }
+
+  /** This method is called when the scheduler shuts down.
+   */
+  def onShutdown(): Unit =
+    executor.shutdown()
+
+  /** The scheduler is active if the underlying <code>ExecutorService</code>
+   *  has not been shut down.
+   */
+  def isActive =
+    (executor ne null) && !executor.isShutdown
+
+}
diff --git a/src/actors/scala/actors/scheduler/ForkJoinScheduler.scala b/src/actors/scala/actors/scheduler/ForkJoinScheduler.scala
new file mode 100644
index 0000000..4aaef16
--- /dev/null
+++ b/src/actors/scala/actors/scheduler/ForkJoinScheduler.scala
@@ -0,0 +1,178 @@
+package scala.actors
+package scheduler
+
+import java.util.{Collection, ArrayList}
+import scala.concurrent.forkjoin._
+
+/** The <code>ForkJoinScheduler</code> is backed by a lightweight
+ *  fork-join task execution framework.
+ *
+ * @author Philipp Haller
+ */
+class ForkJoinScheduler(val initCoreSize: Int, val maxSize: Int, daemon: Boolean, fair: Boolean)
+      extends Runnable with IScheduler with TerminationMonitor {
+
+  private var pool = makeNewPool() // guarded by this
+  private var terminating = false  // guarded by this
+  private var snapshoting = false  // guarded by this
+
+  // this has to be a java.util.Collection, since this is what
+  // the ForkJoinPool returns.
+  private var drainedTasks: Collection[ForkJoinTask[_]] = null
+
+  protected val CHECK_FREQ = 10
+
+  // this random number generator is only used in fair mode
+  private lazy val random = new java.util.Random // guarded by random
+
+  def this(d: Boolean, f: Boolean) {
+    this(ThreadPoolConfig.corePoolSize, ThreadPoolConfig.maxPoolSize, d, f)
+  }
+
+  def this(d: Boolean) {
+    this(d, true) // default is fair
+  }
+
+  def this() {
+    this(false) // default is non-daemon
+  }
+
+  private def makeNewPool(): DrainableForkJoinPool = {
+    val p = new DrainableForkJoinPool()
+    // enable locally FIFO scheduling mode
+    p.setAsyncMode(true)
+    p.setParallelism(initCoreSize)
+    p.setMaximumPoolSize(maxSize)
+    Debug.info(this+": parallelism "+p.getParallelism())
+    Debug.info(this+": max pool size "+p.getMaximumPoolSize())
+    p
+  }
+
+  /** Starts this scheduler.
+   */
+  def start() {
+    try {
+      val t = new Thread(this)
+      t.setDaemon(daemon)
+      t.setName("ForkJoinScheduler")
+      t.start()
+    } catch {
+      case e: Exception =>
+        Debug.info(this+": could not create scheduler thread: "+e)
+    }
+  }
+
+  override def run() {
+    try {
+      while (true) {
+        this.synchronized {
+          try {
+            wait(CHECK_FREQ)
+          } catch {
+            case _: InterruptedException =>
+          }
+
+          if (terminating)
+            throw new QuitControl
+
+          if (allActorsTerminated) {
+            Debug.info(this+": all actors terminated")
+            terminating = true
+            throw new QuitControl
+          }
+
+          if (!snapshoting) {
+            gc()
+          } else if (pool.isQuiescent()) {
+            val list = new ArrayList[ForkJoinTask[_]]
+            val num = pool.drainTasksTo(list)
+            Debug.info(this+": drained "+num+" tasks")
+            drainedTasks = list
+            terminating = true
+            throw new QuitControl
+          }
+        }
+      }
+    } catch {
+      case _: QuitControl =>
+        Debug.info(this+": initiating shutdown...")
+        while (!pool.isQuiescent()) {
+          try {
+            Thread.sleep(10)
+          } catch {
+            case ignore: InterruptedException =>
+          }
+        }
+        pool.shutdown()
+        // allow thread to exit
+    }
+  }
+
+  // TODO: when do we pass a task that is not a RecursiveAction?
+  def execute(task: Runnable) {
+    pool.execute(task)
+  }
+
+  override def executeFromActor(task: Runnable) {
+    // in fair mode: 2% chance of submitting to global task queue
+    if (fair && random.synchronized { random.nextInt(50) == 1 })
+      pool.execute(task)
+    else
+      task.asInstanceOf[RecursiveAction].fork()
+  }
+
+  /** Submits a closure for execution.
+   *
+   *  @param  fun  the closure to be executed
+   */
+  def execute(fun: => Unit): Unit =
+    execute(new Runnable {
+      def run() { fun }
+    })
+
+  /** Shuts down the scheduler.
+   */
+  def shutdown(): Unit = synchronized {
+    terminating = true
+  }
+
+  def isActive = synchronized {
+    !terminating && (pool ne null) && !pool.isShutdown()
+  }
+
+  override def managedBlock(blocker: scala.concurrent.ManagedBlocker) {
+    ForkJoinPool.managedBlock(new ForkJoinPool.ManagedBlocker {
+      def block = blocker.block()
+      def isReleasable() = blocker.isReleasable
+    }, true)
+  }
+
+  /** Suspends the scheduler. All threads that were in use by the
+   *  scheduler and its internal thread pool are terminated.
+   */
+  def snapshot() = synchronized {
+    snapshoting = true
+  }
+
+  /** Resumes the execution of the scheduler if it was previously
+   *  suspended using <code>ForkJoinScheduler.snapshot</code>.
+   */
+  def restart() {
+    synchronized {
+      if (!snapshoting)
+        error("snapshot has not been invoked")
+      else if (isActive)
+        error("scheduler is still active")
+      else
+        snapshoting = false
+
+      pool = makeNewPool()
+    }
+    val iter = drainedTasks.iterator()
+    while (iter.hasNext()) {
+      pool.execute(iter.next())
+    }
+    start()
+  }
+
+}
diff --git a/src/actors/scala/actors/scheduler/QuitControl.scala b/src/actors/scala/actors/scheduler/QuitControl.scala
new file mode 100644
index 0000000..b217094
--- /dev/null
+++ b/src/actors/scala/actors/scheduler/QuitControl.scala
@@ -0,0 +1,19 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2005-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+package scala.actors.scheduler
+
+import scala.util.control.ControlThrowable
+
+/**
+ * The <code>QuitControl</code> class is used to manage control flow
+ * of certain schedulers.
+ *
+ * @author Philipp Haller
+ */
+private[scheduler] class QuitControl extends ControlThrowable
diff --git a/src/actors/scala/actors/scheduler/ResizableThreadPoolScheduler.scala b/src/actors/scala/actors/scheduler/ResizableThreadPoolScheduler.scala
new file mode 100644
index 0000000..209eb09
--- /dev/null
+++ b/src/actors/scala/actors/scheduler/ResizableThreadPoolScheduler.scala
@@ -0,0 +1,199 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2005-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+package scala.actors.scheduler
+
+import scala.actors.threadpool.{ThreadPoolExecutor, TimeUnit, LinkedBlockingQueue,
+                                ThreadFactory}
+import scala.actors.{Debug, IScheduler}
+import scala.concurrent.ManagedBlocker
+
+/**
+ * This scheduler class uses a <code>ThreadPoolExecutor</code>
+ * to execute <code>Actor</code>s.
+ * 
+ * The scheduler attempts to shut down itself and the underlying
+ * <code>ThreadPoolExecutor</code> only if <code>terminate</code>
+ * is set to true. Otherwise, the scheduler must be shut down
+ * explicitly.
+ * 
+ * @author Philipp Haller
+ */
+class ResizableThreadPoolScheduler(protected val terminate: Boolean,
+                                   protected val daemon: Boolean)
+  extends Thread with IScheduler with TerminationMonitor {
+
+  setDaemon(daemon)
+
+  // guarded by this
+  private var terminating = false
+  // guarded by this
+  private var suspending = false
+
+  // this has to be a java.util.Collection, since this is what
+  // the ForkJoinPool returns.
+  @volatile
+  private var drainedTasks: java.util.List[_] = null
+
+  // guarded by this
+  private var coreSize = ThreadPoolConfig.corePoolSize
+  private val maxSize = ThreadPoolConfig.maxPoolSize
+  private val numCores = Runtime.getRuntime().availableProcessors()
+
+  protected val CHECK_FREQ = 10
+
+  private class DaemonThreadFactory extends ThreadFactory {
+    def newThread(r: Runnable): Thread = {
+      val t = new Thread(r)
+      t.setDaemon(daemon)
+      t
+    }
+  }
+  private val threadFac = new DaemonThreadFactory
+
+  private def makeNewPool(): ThreadPoolExecutor = {
+    val workQueue = new LinkedBlockingQueue
+    new ThreadPoolExecutor(coreSize,
+                           maxSize,
+                           60000L,
+                           TimeUnit.MILLISECONDS,
+                           workQueue,
+                           threadFac,
+                           new ThreadPoolExecutor.CallerRunsPolicy)
+  }
+
+  // guarded by this
+  private var executor = makeNewPool()
+
+  Debug.info(this+": corePoolSize = "+coreSize+", maxPoolSize = "+maxSize)
+
+  def this(d: Boolean) {
+    this(true, d)
+  }
+
+  def this() {
+    this(false)
+  }
+
+  private def numWorkersBlocked = {
+    executor.mainLock.lock()
+    val iter = executor.workers.iterator()
+    var numBlocked = 0
+    while (iter.hasNext()) {
+      val w = iter.next().asInstanceOf[ThreadPoolExecutor#Worker]
+      if (w.tryLock()) {
+        // worker is idle
+        w.unlock()
+      } else {
+        val s = w.thread.getState()
+        if (s == Thread.State.WAITING || s == Thread.State.TIMED_WAITING)
+          numBlocked += 1
+      }
+    }
+    executor.mainLock.unlock()
+    numBlocked
+  }
+
+  override def run() {
+    try {
+      while (true) {
+        this.synchronized {
+          try {
+            wait(CHECK_FREQ)
+          } catch {
+            case _: InterruptedException =>
+          }
+
+          if (terminating)
+            throw new QuitControl
+
+          if (!suspending) {
+            gc()
+
+            // check if we need more worker threads
+            val activeBlocked = numWorkersBlocked
+            if (coreSize - activeBlocked < numCores && coreSize < maxSize) {
+              coreSize = numCores + activeBlocked
+              executor.setCorePoolSize(coreSize)
+            } else if (terminate && allActorsTerminated) {
+              // if all worker threads idle terminate
+              if (executor.getActiveCount() == 0) {
+                Debug.info(this+": initiating shutdown...")
+                Debug.info(this+": corePoolSize = "+coreSize+", maxPoolSize = "+maxSize)
+                
+                terminating = true
+                throw new QuitControl
+              }
+            }
+          } else {
+            drainedTasks = executor.shutdownNow()
+            Debug.info(this+": drained "+drainedTasks.size()+" tasks")
+            terminating = true
+            throw new QuitControl
+          }
+        } // sync
+      }
+    } catch {
+      case _: QuitControl =>
+        executor.shutdown()
+        // allow thread to exit
+    }
+  }
+
+  def execute(task: Runnable): Unit =
+    executor execute task
+
+  def execute(fun: => Unit): Unit =
+    executor.execute(new Runnable {
+      def run() { fun }
+    })
+
+  /** Shuts down the scheduler.
+   */
+  def shutdown(): Unit = synchronized {
+    terminating = true
+  }
+
+  def isActive = synchronized {
+    !terminating && (executor ne null) && !executor.isShutdown()
+  }
+
+  def managedBlock(blocker: ManagedBlocker) {
+    blocker.block()
+  }
+
+  /** Suspends the scheduler. All threads that were in use by the
+   *  scheduler and its internal thread pool are terminated.
+   */
+  def snapshot() = synchronized {
+    suspending = true
+  }
+
+  /** Resumes the execution of the scheduler if it was previously
+   *  suspended using <code>snapshot</code>.
+   */
+  def restart() {
+    synchronized {
+      if (!suspending)
+        error("snapshot has not been invoked")
+      else if (isActive)
+        error("scheduler is still active")
+      else
+        suspending = false
+
+      executor = makeNewPool()
+    }
+    val iter = drainedTasks.iterator()
+    while (iter.hasNext()) {
+      executor.execute(iter.next().asInstanceOf[Runnable])
+    }
+    start()
+  }
+
+}
diff --git a/src/actors/scala/actors/scheduler/SingleThreadedScheduler.scala b/src/actors/scala/actors/scheduler/SingleThreadedScheduler.scala
new file mode 100644
index 0000000..6ee3754
--- /dev/null
+++ b/src/actors/scala/actors/scheduler/SingleThreadedScheduler.scala
@@ -0,0 +1,68 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2005-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+package scala.actors
+package scheduler
+
+import scala.collection.mutable.Queue
+
+/**
+ * This scheduler executes actor tasks on the current thread.
+ *
+ * @author Philipp Haller
+ */
+class SingleThreadedScheduler extends IScheduler {
+
+  private val tasks = new Queue[Runnable]
+
+  /** The maximum number of nested tasks that are run
+   *  without unwinding the call stack.
+   */
+  protected val maxNesting = 10
+
+  private var curNest = 0
+  private var isShutdown = false
+
+  def execute(task: Runnable) {
+    if (curNest < maxNesting) {
+      curNest += 1
+      task.run()
+    } else {
+      curNest = 0
+      tasks += task
+    }
+  }
+
+  def execute(fun: => Unit): Unit =
+    execute(new Runnable {
+      def run() { fun }
+    })
+
+  def shutdown() {
+    isShutdown = false
+    while (!tasks.isEmpty) {
+      val task = tasks.dequeue()
+      task.run()
+    }
+    isShutdown = true
+  }
+
+  def newActor(actor: TrackedReactor) {}
+  def terminated(actor: TrackedReactor) {}
+
+  // TODO: run termination handlers at end of shutdown.
+  def onTerminate(actor: TrackedReactor)(f: => Unit) {}
+
+  def isActive =
+    !isShutdown
+
+  def managedBlock(blocker: scala.concurrent.ManagedBlocker) {
+    blocker.block()
+  }
+}
diff --git a/src/actors/scala/actors/scheduler/TerminationMonitor.scala b/src/actors/scala/actors/scheduler/TerminationMonitor.scala
index b563b5e..02fe147 100644
--- a/src/actors/scala/actors/scheduler/TerminationMonitor.scala
+++ b/src/actors/scala/actors/scheduler/TerminationMonitor.scala
@@ -1,25 +1,26 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2005-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2005-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: TerminationMonitor.scala 18781 2009-09-24 18:28:17Z phaller $
 
-package scala.actors.scheduler
+package scala.actors
+package scheduler
 
 import scala.collection.mutable.HashMap
 
-private[actors] trait TerminationMonitor {
+private[scheduler] trait TerminationMonitor {
+  _: IScheduler =>
 
   protected var activeActors = 0
-  protected val terminationHandlers = new HashMap[Actor, () => Unit]
+  protected val terminationHandlers = new HashMap[TrackedReactor, () => Unit]
   private var started = false
 
   /** newActor is invoked whenever a new actor is started. */
-  def newActor(a: Actor) = synchronized {
+  def newActor(a: TrackedReactor) = synchronized {
     activeActors += 1
     if (!started)
       started = true
@@ -31,7 +32,7 @@ private[actors] trait TerminationMonitor {
    *  @param  a  the actor
    *  @param  f  the closure to be registered
    */
-  def onTerminate(a: Actor)(f: => Unit): Unit = synchronized {
+  def onTerminate(a: TrackedReactor)(f: => Unit): Unit = synchronized {
     terminationHandlers += (a -> (() => f))
   }
 
@@ -39,7 +40,7 @@ private[actors] trait TerminationMonitor {
    *
    *  @param  a  the actor that has terminated
    */
-  def terminated(a: Actor) = {
+  def terminated(a: TrackedReactor) = {
     // obtain termination handler (if any)
     val todo = synchronized {
       terminationHandlers.get(a) match {
@@ -60,10 +61,13 @@ private[actors] trait TerminationMonitor {
   }
 
   /** Checks whether all actors have terminated. */
-  @deprecated
-  def allTerminated: Boolean = synchronized {
+  private[actors] def allActorsTerminated: Boolean = synchronized {
     started && activeActors <= 0
   }
+  
+  /** Deprecated non-actor-private version */
+  @deprecated("this method is going to be removed in a future release")
+  def allTerminated: Boolean = allActorsTerminated
 
   /** Checks for actors that have become garbage. */
   protected def gc() {}
diff --git a/src/actors/scala/actors/scheduler/TerminationService.scala b/src/actors/scala/actors/scheduler/TerminationService.scala
new file mode 100644
index 0000000..610a763
--- /dev/null
+++ b/src/actors/scala/actors/scheduler/TerminationService.scala
@@ -0,0 +1,68 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2005-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+package scala.actors
+package scheduler
+
+import java.lang.{Thread, InterruptedException}
+
+/**
+ * The <code>TerminationService</code> class starts a new thread
+ * that is used to check regularly if the scheduler can be
+ * shut down, because all started actors are known to
+ * have terminated.
+ *
+ * @author Philipp Haller
+ */
+private[scheduler] trait TerminationService extends TerminationMonitor {
+  _: Thread with IScheduler =>
+
+  private var terminating = false
+
+  /** Indicates whether the scheduler should terminate when all
+   *  actors have terminated.
+   */
+  protected val terminate = true
+
+  protected val CHECK_FREQ = 50
+
+  def onShutdown(): Unit
+
+  override def run() {
+    try {
+      while (true) {
+        this.synchronized {
+          try {
+            wait(CHECK_FREQ)
+          } catch {
+            case _: InterruptedException =>
+          }
+
+          if (terminating || (terminate && allActorsTerminated))
+            throw new QuitControl
+
+          gc()
+        }
+      }
+    } catch {
+      case _: QuitControl =>
+        Debug.info(this+": initiating shutdown...")
+        // invoke shutdown hook
+        onShutdown()
+        // allow thread to exit
+    }
+  }
+
+  /** Shuts down the scheduler.
+   */
+  def shutdown(): Unit = synchronized {
+    terminating = true
+  }
+
+}
diff --git a/src/actors/scala/actors/scheduler/ThreadPoolConfig.scala b/src/actors/scala/actors/scheduler/ThreadPoolConfig.scala
new file mode 100644
index 0000000..87011b9
--- /dev/null
+++ b/src/actors/scala/actors/scheduler/ThreadPoolConfig.scala
@@ -0,0 +1,53 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2005-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+package scala.actors
+package scheduler
+
+import util.Properties.{ javaVersion, javaVmVendor, isJavaAtLeast, propIsSetTo, propOrNone }
+
+/**
+ * @author Erik Engbrecht
+ * @author Philipp Haller
+ */
+private[actors] object ThreadPoolConfig {
+  private val rt = Runtime.getRuntime()
+  private val minNumThreads = 4
+
+  private def getIntegerProp(propName: String): Option[Int] =
+    try propOrNone(propName) map (_.toInt)
+    catch { case _: SecurityException | _: NumberFormatException => None }
+
+  val corePoolSize = getIntegerProp("actors.corePoolSize") match {
+    case Some(i) if i > 0 => i
+    case _ => {
+      val byCores = rt.availableProcessors() * 2
+      if (byCores > minNumThreads) byCores else minNumThreads
+    }
+  }
+
+  val maxPoolSize = {
+    val preMaxSize = getIntegerProp("actors.maxPoolSize") getOrElse 256
+    if (preMaxSize >= corePoolSize) preMaxSize else corePoolSize
+  }
+
+  private[actors] def useForkJoin: Boolean =
+    try !propIsSetTo("actors.enableForkJoin", "false") &&
+      (propIsSetTo("actors.enableForkJoin", "true") || {
+        Debug.info(this+": java.version = "+javaVersion)
+        Debug.info(this+": java.vm.vendor = "+javaVmVendor)
+      
+        // on IBM J9 1.6 do not use ForkJoinPool
+        // XXX this all needs to go into Properties.
+        isJavaAtLeast("1.6") && ((javaVmVendor contains "Sun") || (javaVmVendor contains "Apple"))
+      })
+    catch {
+      case _: SecurityException => false
+    }
+}
diff --git a/src/actors/scala/actors/threadpool/AbstractExecutorService.java b/src/actors/scala/actors/threadpool/AbstractExecutorService.java
index 7953bfe..4a12aa3 100644
--- a/src/actors/scala/actors/threadpool/AbstractExecutorService.java
+++ b/src/actors/scala/actors/threadpool/AbstractExecutorService.java
@@ -120,7 +120,7 @@ public abstract class AbstractExecutorService implements ExecutorService {
         int ntasks = tasks.size();
         if (ntasks == 0)
             throw new IllegalArgumentException();
-        List futures= new ArrayList(ntasks);
+        List<Future> futures = new ArrayList<Future>(ntasks);
         ExecutorCompletionService ecs =
             new ExecutorCompletionService(this);
 
@@ -203,10 +203,10 @@ public abstract class AbstractExecutorService implements ExecutorService {
         return doInvokeAny(tasks, true, unit.toNanos(timeout));
     }
 
-    public List invokeAll(Collection tasks) throws InterruptedException {
+    public List<Future> invokeAll(Collection tasks) throws InterruptedException {
         if (tasks == null)
             throw new NullPointerException();
-        List futures = new ArrayList(tasks.size());
+        List<Future> futures = new ArrayList<Future>(tasks.size());
         boolean done = false;
         try {
             for (Iterator t = tasks.iterator(); t.hasNext();) {
@@ -235,13 +235,13 @@ public abstract class AbstractExecutorService implements ExecutorService {
         }
     }
 
-    public List invokeAll(Collection tasks,
+    public List<Future> invokeAll(Collection tasks,
                           long timeout, TimeUnit unit)
         throws InterruptedException {
         if (tasks == null || unit == null)
             throw new NullPointerException();
         long nanos = unit.toNanos(timeout);
-        List futures = new ArrayList(tasks.size());
+        List<Future> futures = new ArrayList<Future>(tasks.size());
         boolean done = false;
         try {
             for (Iterator t = tasks.iterator(); t.hasNext();)
diff --git a/src/actors/scala/actors/threadpool/BlockingQueue.java b/src/actors/scala/actors/threadpool/BlockingQueue.java
index 880c258..1b4e808 100644
--- a/src/actors/scala/actors/threadpool/BlockingQueue.java
+++ b/src/actors/scala/actors/threadpool/BlockingQueue.java
@@ -7,9 +7,10 @@
 package scala.actors.threadpool;
 
 import java.util.Collection;
+import java.util.Queue;
 
 /**
- * A {@link edu.emory.mathcs.backport.java.util.Queue} that additionally supports operations
+ * A {@link java.util.Queue} that additionally supports operations
  * that wait for the queue to become non-empty when retrieving an
  * element, and wait for space to become available in the queue when
  * storing an element.
@@ -146,8 +147,9 @@ import java.util.Collection;
  *
  * @since 1.5
  * @author Doug Lea
+ * @param <E> the type of elements held in this collection
  */
-public interface BlockingQueue extends Queue {
+public interface BlockingQueue<E> extends Queue<E> {
     /**
      * Inserts the specified element into this queue if it is possible to do
      * so immediately without violating capacity restrictions, returning
@@ -157,7 +159,7 @@ public interface BlockingQueue extends Queue {
      * use {@link #offer(Object) offer}.
      *
      * @param e the element to add
-     * @return <tt>true</tt> (as specified by {@link java.util.Collection#add})
+     * @return <tt>true</tt> (as specified by {@link Collection#add})
      * @throws IllegalStateException if the element cannot be added at this
      *         time due to capacity restrictions
      * @throws ClassCastException if the class of the specified element
@@ -166,7 +168,7 @@ public interface BlockingQueue extends Queue {
      * @throws IllegalArgumentException if some property of the specified
      *         element prevents it from being added to this queue
      */
-    boolean add(Object e);
+    boolean add(E e);
 
     /**
      * Inserts the specified element into this queue if it is possible to do
@@ -185,7 +187,7 @@ public interface BlockingQueue extends Queue {
      * @throws IllegalArgumentException if some property of the specified
      *         element prevents it from being added to this queue
      */
-    boolean offer(Object e);
+    boolean offer(E e);
 
     /**
      * Inserts the specified element into this queue, waiting if necessary
@@ -199,7 +201,7 @@ public interface BlockingQueue extends Queue {
      * @throws IllegalArgumentException if some property of the specified
      *         element prevents it from being added to this queue
      */
-    void put(Object e) throws InterruptedException;
+    void put(E e) throws InterruptedException;
 
     /**
      * Inserts the specified element into this queue, waiting up to the
@@ -219,7 +221,7 @@ public interface BlockingQueue extends Queue {
      * @throws IllegalArgumentException if some property of the specified
      *         element prevents it from being added to this queue
      */
-    boolean offer(Object e, long timeout, TimeUnit unit)
+    boolean offer(E e, long timeout, TimeUnit unit)
         throws InterruptedException;
 
     /**
@@ -229,7 +231,7 @@ public interface BlockingQueue extends Queue {
      * @return the head of this queue
      * @throws InterruptedException if interrupted while waiting
      */
-    Object take() throws InterruptedException;
+    E take() throws InterruptedException;
 
     /**
      * Retrieves and removes the head of this queue, waiting up to the
@@ -243,7 +245,7 @@ public interface BlockingQueue extends Queue {
      *         specified waiting time elapses before an element is available
      * @throws InterruptedException if interrupted while waiting
      */
-    Object poll(long timeout, TimeUnit unit)
+    E poll(long timeout, TimeUnit unit)
         throws InterruptedException;
 
     /**
@@ -313,7 +315,7 @@ public interface BlockingQueue extends Queue {
      *         queue, or some property of an element of this queue prevents
      *         it from being added to the specified collection
      */
-    int drainTo(Collection c);
+    int drainTo(Collection<? super E> c);
 
     /**
      * Removes at most the given number of available elements from
@@ -338,5 +340,5 @@ public interface BlockingQueue extends Queue {
      *         queue, or some property of an element of this queue prevents
      *         it from being added to the specified collection
      */
-    int drainTo(Collection c, int maxElements);
+    int drainTo(Collection<? super E> c, int maxElements);
 }
diff --git a/src/actors/scala/actors/threadpool/Executors.java b/src/actors/scala/actors/threadpool/Executors.java
index e74d665..49a127a 100644
--- a/src/actors/scala/actors/threadpool/Executors.java
+++ b/src/actors/scala/actors/threadpool/Executors.java
@@ -605,12 +605,12 @@ public class Executors {
         public Future submit(Runnable task, Object result) {
             return e.submit(task, result);
         }
-        public List invokeAll(Collection tasks)
+        public List<Future> invokeAll(Collection tasks)
             throws InterruptedException {
             return e.invokeAll(tasks);
         }
-        public List invokeAll(Collection tasks,
-                                             long timeout, TimeUnit unit)
+        public List<Future> invokeAll(Collection tasks,
+                                      long timeout, TimeUnit unit)
             throws InterruptedException {
             return e.invokeAll(tasks, timeout, unit);
         }
diff --git a/src/actors/scala/actors/threadpool/LinkedBlockingQueue.java b/src/actors/scala/actors/threadpool/LinkedBlockingQueue.java
index 87fecff..f434ab0 100644
--- a/src/actors/scala/actors/threadpool/LinkedBlockingQueue.java
+++ b/src/actors/scala/actors/threadpool/LinkedBlockingQueue.java
@@ -6,11 +6,13 @@
 
 package scala.actors.threadpool;
 
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.locks.Condition;
+import java.util.concurrent.locks.ReentrantLock;
+import java.util.AbstractQueue;
 import java.util.Collection;
 import java.util.Iterator;
 import java.util.NoSuchElementException;
-//import edu.emory.mathcs.backport.java.util.*;
-import scala.actors.threadpool.helpers.*;
 
 /**
  * An optionally-bounded {@linkplain BlockingQueue blocking queue} based on
@@ -41,10 +43,11 @@ import scala.actors.threadpool.helpers.*;
  *
  * @since 1.5
  * @author Doug Lea
+ * @param <E> the type of elements held in this collection
  *
  */
-public class LinkedBlockingQueue extends AbstractQueue
-        implements BlockingQueue, java.io.Serializable {
+public class LinkedBlockingQueue<E> extends AbstractQueue<E>
+        implements BlockingQueue<E>, java.io.Serializable {
     private static final long serialVersionUID = -6903933977591709194L;
 
     /*
@@ -59,43 +62,87 @@ public class LinkedBlockingQueue extends AbstractQueue
      * items have been entered since the signal. And symmetrically for
      * takes signalling puts. Operations such as remove(Object) and
      * iterators acquire both locks.
+     *
+     * Visibility between writers and readers is provided as follows:
+     *
+     * Whenever an element is enqueued, the putLock is acquired and
+     * count updated.  A subsequent reader guarantees visibility to the
+     * enqueued Node by either acquiring the putLock (via fullyLock)
+     * or by acquiring the takeLock, and then reading n = count.get();
+     * this gives visibility to the first n items.
+     *
+     * To implement weakly consistent iterators, it appears we need to
+     * keep all Nodes GC-reachable from a predecessor dequeued Node.
+     * That would cause two problems:
+     * - allow a rogue Iterator to cause unbounded memory retention
+     * - cause cross-generational linking of old Nodes to new Nodes if
+     *   a Node was tenured while live, which generational GCs have a
+     *   hard time dealing with, causing repeated major collections.
+     * However, only non-deleted Nodes need to be reachable from
+     * dequeued Nodes, and reachability does not necessarily have to
+     * be of the kind understood by the GC.  We use the trick of
+     * linking a Node that has just been dequeued to itself.  Such a
+     * self-link implicitly means to advance to head.next.
      */
 
     /**
      * Linked list node class
      */
-    static class Node {
-        /** The item, volatile to ensure barrier separating write and read */
-        volatile Object item;
-        Node next;
-        Node(Object x) { item = x; }
+    static class Node<E> {
+        E item;
+
+        /**
+         * One of:
+         * - the real successor Node
+         * - this Node, meaning the successor is head.next
+         * - null, meaning there is no successor (this is the last node)
+         */
+        Node<E> next;
+
+        Node(E x) { item = x; }
     }
 
     /** The capacity bound, or Integer.MAX_VALUE if none */
     private final int capacity;
 
     /** Current number of elements */
-    private volatile int count = 0;
+    private final AtomicInteger count = new AtomicInteger(0);
 
-    /** Head of linked list */
-    private transient Node head;
+    /**
+     * Head of linked list.
+     * Invariant: head.item == null
+     */
+    private transient Node<E> head;
 
-    /** Tail of linked list */
-    private transient Node last;
+    /**
+     * Tail of linked list.
+     * Invariant: last.next == null
+     */
+    private transient Node<E> last;
 
     /** Lock held by take, poll, etc */
-    private final Object takeLock = new SerializableLock();
+    private final ReentrantLock takeLock = new ReentrantLock();
+
+    /** Wait queue for waiting takes */
+    private final Condition notEmpty = takeLock.newCondition();
 
     /** Lock held by put, offer, etc */
-    private final Object putLock = new SerializableLock();
+    private final ReentrantLock putLock = new ReentrantLock();
+
+    /** Wait queue for waiting puts */
+    private final Condition notFull = putLock.newCondition();
 
     /**
      * Signals a waiting take. Called only from put/offer (which do not
      * otherwise ordinarily lock takeLock.)
      */
     private void signalNotEmpty() {
-        synchronized (takeLock) {
-            takeLock.notify();
+        final ReentrantLock takeLock = this.takeLock;
+        takeLock.lock();
+        try {
+            notEmpty.signal();
+        } finally {
+            takeLock.unlock();
         }
     }
 
@@ -103,34 +150,69 @@ public class LinkedBlockingQueue extends AbstractQueue
      * Signals a waiting put. Called only from take/poll.
      */
     private void signalNotFull() {
-        synchronized (putLock) {
-            putLock.notify();
+        final ReentrantLock putLock = this.putLock;
+        putLock.lock();
+        try {
+            notFull.signal();
+        } finally {
+            putLock.unlock();
         }
     }
 
     /**
      * Creates a node and links it at end of queue.
+     *
      * @param x the item
      */
-    private void insert(Object x) {
-        last = last.next = new Node(x);
+    private void enqueue(E x) {
+        // assert putLock.isHeldByCurrentThread();
+        // assert last.next == null;
+        last = last.next = new Node<E>(x);
     }
 
     /**
-     * Removes a node from head of queue,
+     * Removes a node from head of queue.
+     *
      * @return the node
      */
-    private Object extract() {
-        Node first = head.next;
+    private E dequeue() {
+        // assert takeLock.isHeldByCurrentThread();
+        // assert head.item == null;
+        Node<E> h = head;
+        Node<E> first = h.next;
+        h.next = h; // help GC
         head = first;
-        Object x = first.item;
+        E x = first.item;
         first.item = null;
         return x;
     }
 
+    /**
+     * Lock to prevent both puts and takes.
+     */
+    void fullyLock() {
+        putLock.lock();
+        takeLock.lock();
+    }
 
     /**
-     * Creates a <tt>LinkedBlockingQueue</tt> with a capacity of
+     * Unlock to allow both puts and takes.
+     */
+    void fullyUnlock() {
+        takeLock.unlock();
+        putLock.unlock();
+    }
+
+//     /**
+//      * Tells whether both locks are held by current thread.
+//      */
+//     boolean isFullyLocked() {
+//         return (putLock.isHeldByCurrentThread() &&
+//                 takeLock.isHeldByCurrentThread());
+//     }
+
+    /**
+     * Creates a {@code LinkedBlockingQueue} with a capacity of
      * {@link Integer#MAX_VALUE}.
      */
     public LinkedBlockingQueue() {
@@ -138,20 +220,20 @@ public class LinkedBlockingQueue extends AbstractQueue
     }
 
     /**
-     * Creates a <tt>LinkedBlockingQueue</tt> with the given (fixed) capacity.
+     * Creates a {@code LinkedBlockingQueue} with the given (fixed) capacity.
      *
      * @param capacity the capacity of this queue
-     * @throws IllegalArgumentException if <tt>capacity</tt> is not greater
+     * @throws IllegalArgumentException if {@code capacity} is not greater
      *         than zero
      */
     public LinkedBlockingQueue(int capacity) {
         if (capacity <= 0) throw new IllegalArgumentException();
         this.capacity = capacity;
-        last = head = new Node(null);
+        last = head = new Node<E>(null);
     }
 
     /**
-     * Creates a <tt>LinkedBlockingQueue</tt> with a capacity of
+     * Creates a {@code LinkedBlockingQueue} with a capacity of
      * {@link Integer#MAX_VALUE}, initially containing the elements of the
      * given collection,
      * added in traversal order of the collection's iterator.
@@ -160,11 +242,23 @@ public class LinkedBlockingQueue extends AbstractQueue
      * @throws NullPointerException if the specified collection or any
      *         of its elements are null
      */
-    public LinkedBlockingQueue(Collection c) {
+    public LinkedBlockingQueue(Collection<? extends E> c) {
         this(Integer.MAX_VALUE);
-        for (Iterator itr = c.iterator(); itr.hasNext();) {
-            Object e = itr.next();
-            add(e);
+        final ReentrantLock putLock = this.putLock;
+        putLock.lock(); // Never contended, but necessary for visibility
+        try {
+            int n = 0;
+            for (E e : c) {
+                if (e == null)
+                    throw new NullPointerException();
+                if (n == capacity)
+                    throw new IllegalStateException("Queue full");
+                enqueue(e);
+                ++n;
+            }
+            count.set(n);
+        } finally {
+            putLock.unlock();
         }
     }
 
@@ -177,7 +271,7 @@ public class LinkedBlockingQueue extends AbstractQueue
      * @return the number of elements in this queue
      */
     public int size() {
-        return count;
+        return count.get();
     }
 
     // this doc comment is a modified copy of the inherited doc comment,
@@ -186,15 +280,15 @@ public class LinkedBlockingQueue extends AbstractQueue
      * Returns the number of additional elements that this queue can ideally
      * (in the absence of memory or resource constraints) accept without
      * blocking. This is always equal to the initial capacity of this queue
-     * less the current <tt>size</tt> of this queue.
+     * less the current {@code size} of this queue.
      *
      * <p>Note that you <em>cannot</em> always tell if an attempt to insert
-     * an element will succeed by inspecting <tt>remainingCapacity</tt>
+     * an element will succeed by inspecting {@code remainingCapacity}
      * because it may be the case that another thread is about to
      * insert or remove an element.
      */
     public int remainingCapacity() {
-        return capacity - count;
+        return capacity - count.get();
     }
 
     /**
@@ -204,34 +298,33 @@ public class LinkedBlockingQueue extends AbstractQueue
      * @throws InterruptedException {@inheritDoc}
      * @throws NullPointerException {@inheritDoc}
      */
-    public void put(Object e) throws InterruptedException {
+    public void put(E e) throws InterruptedException {
         if (e == null) throw new NullPointerException();
-        // Note: convention in all put/take/etc is to preset
-        // local var holding count  negative to indicate failure unless set.
+        // Note: convention in all put/take/etc is to preset local var
+        // holding count negative to indicate failure unless set.
         int c = -1;
-        synchronized (putLock) {
+        final ReentrantLock putLock = this.putLock;
+        final AtomicInteger count = this.count;
+        putLock.lockInterruptibly();
+        try {
             /*
              * Note that count is used in wait guard even though it is
              * not protected by lock. This works because count can
              * only decrease at this point (all other puts are shut
              * out by lock), and we (or some other waiting put) are
-             * signalled if it ever changes from
-             * capacity. Similarly for all other uses of count in
-             * other wait guards.
+             * signalled if it ever changes from capacity. Similarly
+             * for all other uses of count in other wait guards.
              */
-            try {
-                while (count == capacity)
-                    putLock.wait();
-            } catch (InterruptedException ie) {
-                putLock.notify(); // propagate to a non-interrupted thread
-                throw ie;
+            while (count.get() == capacity) {
+                notFull.await();
             }
-            insert(e);
-            synchronized (this) { c = count++; }
+            enqueue(e);
+            c = count.getAndIncrement();
             if (c + 1 < capacity)
-                putLock.notify();
+                notFull.signal();
+        } finally {
+            putLock.unlock();
         }
-
         if (c == 0)
             signalNotEmpty();
     }
@@ -240,37 +333,32 @@ public class LinkedBlockingQueue extends AbstractQueue
      * Inserts the specified element at the tail of this queue, waiting if
      * necessary up to the specified wait time for space to become available.
      *
-     * @return <tt>true</tt> if successful, or <tt>false</tt> if
+     * @return {@code true} if successful, or {@code false} if
      *         the specified waiting time elapses before space is available.
      * @throws InterruptedException {@inheritDoc}
      * @throws NullPointerException {@inheritDoc}
      */
-    public boolean offer(Object e, long timeout, TimeUnit unit)
+    public boolean offer(E e, long timeout, TimeUnit unit)
         throws InterruptedException {
 
         if (e == null) throw new NullPointerException();
         long nanos = unit.toNanos(timeout);
         int c = -1;
-        synchronized (putLock) {
-            long deadline = Utils.nanoTime() + nanos;
-            for (;;) {
-                if (count < capacity) {
-                    insert(e);
-                    synchronized (this) { c = count++; }
-                    if (c + 1 < capacity)
-                        putLock.notify();
-                    break;
-                }
+        final ReentrantLock putLock = this.putLock;
+        final AtomicInteger count = this.count;
+        putLock.lockInterruptibly();
+        try {
+            while (count.get() == capacity) {
                 if (nanos <= 0)
                     return false;
-                try {
-                    TimeUnit.NANOSECONDS.timedWait(putLock, nanos);
-                    nanos = deadline - Utils.nanoTime();
-                } catch (InterruptedException ie) {
-                    putLock.notify(); // propagate to a non-interrupted thread
-                    throw ie;
-                }
+                nanos = notFull.awaitNanos(nanos);
             }
+            enqueue(e);
+            c = count.getAndIncrement();
+            if (c + 1 < capacity)
+                notFull.signal();
+        } finally {
+            putLock.unlock();
         }
         if (c == 0)
             signalNotEmpty();
@@ -280,7 +368,7 @@ public class LinkedBlockingQueue extends AbstractQueue
     /**
      * Inserts the specified element at the tail of this queue if it is
      * possible to do so immediately without exceeding the queue's capacity,
-     * returning <tt>true</tt> upon success and <tt>false</tt> if this queue
+     * returning {@code true} upon success and {@code false} if this queue
      * is full.
      * When using a capacity-restricted queue, this method is generally
      * preferable to method {@link BlockingQueue#add add}, which can fail to
@@ -288,18 +376,23 @@ public class LinkedBlockingQueue extends AbstractQueue
      *
      * @throws NullPointerException if the specified element is null
      */
-    public boolean offer(Object e) {
+    public boolean offer(E e) {
         if (e == null) throw new NullPointerException();
-        if (count == capacity)
+        final AtomicInteger count = this.count;
+        if (count.get() == capacity)
             return false;
         int c = -1;
-        synchronized (putLock) {
-            if (count < capacity) {
-                insert(e);
-                synchronized (this) { c = count++; }
+        final ReentrantLock putLock = this.putLock;
+        putLock.lock();
+        try {
+            if (count.get() < capacity) {
+                enqueue(e);
+                c = count.getAndIncrement();
                 if (c + 1 < capacity)
-                    putLock.notify();
+                    notFull.signal();
             }
+        } finally {
+            putLock.unlock();
         }
         if (c == 0)
             signalNotEmpty();
@@ -307,128 +400,134 @@ public class LinkedBlockingQueue extends AbstractQueue
     }
 
 
-    public Object take() throws InterruptedException {
-        Object x;
+    public E take() throws InterruptedException {
+        E x;
         int c = -1;
-        synchronized (takeLock) {
-            try {
-                while (count == 0)
-                    takeLock.wait();
-            } catch (InterruptedException ie) {
-                takeLock.notify(); // propagate to a non-interrupted thread
-                throw ie;
+        final AtomicInteger count = this.count;
+        final ReentrantLock takeLock = this.takeLock;
+        takeLock.lockInterruptibly();
+        try {
+            while (count.get() == 0) {
+                notEmpty.await();
             }
-
-            x = extract();
-            synchronized (this) { c = count--; }
+            x = dequeue();
+            c = count.getAndDecrement();
             if (c > 1)
-                takeLock.notify();
+                notEmpty.signal();
+        } finally {
+            takeLock.unlock();
         }
         if (c == capacity)
             signalNotFull();
         return x;
     }
 
-    public Object poll(long timeout, TimeUnit unit) throws InterruptedException {
-        Object x = null;
+    public E poll(long timeout, TimeUnit unit) throws InterruptedException {
+        E x = null;
         int c = -1;
         long nanos = unit.toNanos(timeout);
-        synchronized (takeLock) {
-            long deadline = Utils.nanoTime() + nanos;
-            for (;;) {
-                if (count > 0) {
-                    x = extract();
-                    synchronized (this) { c = count--; }
-                    if (c > 1)
-                        takeLock.notify();
-                    break;
-                }
+        final AtomicInteger count = this.count;
+        final ReentrantLock takeLock = this.takeLock;
+        takeLock.lockInterruptibly();
+        try {
+            while (count.get() == 0) {
                 if (nanos <= 0)
                     return null;
-                try {
-                    TimeUnit.NANOSECONDS.timedWait(takeLock, nanos);
-                    nanos = deadline - Utils.nanoTime();
-                } catch (InterruptedException ie) {
-                    takeLock.notify(); // propagate to a non-interrupted thread
-                    throw ie;
-                }
+                nanos = notEmpty.awaitNanos(nanos);
             }
+            x = dequeue();
+            c = count.getAndDecrement();
+            if (c > 1)
+                notEmpty.signal();
+        } finally {
+            takeLock.unlock();
         }
         if (c == capacity)
             signalNotFull();
         return x;
     }
 
-    public Object poll() {
-        if (count == 0)
+    public E poll() {
+        final AtomicInteger count = this.count;
+        if (count.get() == 0)
             return null;
-        Object x = null;
+        E x = null;
         int c = -1;
-        synchronized (takeLock) {
-            if (count > 0) {
-                x = extract();
-                synchronized (this) { c = count--; }
+        final ReentrantLock takeLock = this.takeLock;
+        takeLock.lock();
+        try {
+            if (count.get() > 0) {
+                x = dequeue();
+                c = count.getAndDecrement();
                 if (c > 1)
-                    takeLock.notify();
+                    notEmpty.signal();
             }
+        } finally {
+            takeLock.unlock();
         }
         if (c == capacity)
             signalNotFull();
         return x;
     }
 
-
-    public Object peek() {
-        if (count == 0)
+    public E peek() {
+        if (count.get() == 0)
             return null;
-        synchronized (takeLock) {
-            Node first = head.next;
+        final ReentrantLock takeLock = this.takeLock;
+        takeLock.lock();
+        try {
+            Node<E> first = head.next;
             if (first == null)
                 return null;
             else
                 return first.item;
+        } finally {
+            takeLock.unlock();
         }
     }
 
     /**
+     * Unlinks interior Node p with predecessor trail.
+     */
+    void unlink(Node<E> p, Node<E> trail) {
+        // assert isFullyLocked();
+        // p.next is not changed, to allow iterators that are
+        // traversing p to maintain their weak-consistency guarantee.
+        p.item = null;
+        trail.next = p.next;
+        if (last == p)
+            last = trail;
+        if (count.getAndDecrement() == capacity)
+            notFull.signal();
+    }
+
+    /**
      * Removes a single instance of the specified element from this queue,
-     * if it is present.  More formally, removes an element <tt>e</tt> such
-     * that <tt>o.equals(e)</tt>, if this queue contains one or more such
+     * if it is present.  More formally, removes an element {@code e} such
+     * that {@code o.equals(e)}, if this queue contains one or more such
      * elements.
-     * Returns <tt>true</tt> if this queue contained the specified element
+     * Returns {@code true} if this queue contained the specified element
      * (or equivalently, if this queue changed as a result of the call).
      *
      * @param o element to be removed from this queue, if present
-     * @return <tt>true</tt> if this queue changed as a result of the call
+     * @return {@code true} if this queue changed as a result of the call
      */
     public boolean remove(Object o) {
         if (o == null) return false;
-        boolean removed = false;
-        synchronized (putLock) {
-            synchronized (takeLock) {
-                Node trail = head;
-                Node p = head.next;
-                while (p != null) {
-                    if (o.equals(p.item)) {
-                        removed = true;
-                        break;
-                    }
-                    trail = p;
-                    p = p.next;
-                }
-                if (removed) {
-                    p.item = null;
-                    trail.next = p.next;
-                    if (last == p)
-                        last = trail;
-                    synchronized (this) {
-                        if (count-- == capacity)
-                            putLock.notifyAll();
-                    }
+        fullyLock();
+        try {
+            for (Node<E> trail = head, p = trail.next;
+                 p != null;
+                 trail = p, p = p.next) {
+                if (o.equals(p.item)) {
+                    unlink(p, trail);
+                    return true;
                 }
             }
+            return false;
+        } finally {
+            fullyUnlock();
         }
-        return removed;
     }
 
     /**
@@ -445,15 +544,16 @@ public class LinkedBlockingQueue extends AbstractQueue
      * @return an array containing all of the elements in this queue
      */
     public Object[] toArray() {
-        synchronized (putLock) {
-            synchronized (takeLock) {
-                int size = count;
-                Object[] a = new Object[size];
-                int k = 0;
-                for (Node p = head.next; p != null; p = p.next)
-                    a[k++] = p.item;
-                return a;
-            }
+        fullyLock();
+        try {
+            int size = count.get();
+            Object[] a = new Object[size];
+            int k = 0;
+            for (Node<E> p = head.next; p != null; p = p.next)
+                a[k++] = p.item;
+            return a;
+        } finally {
+            fullyUnlock();
         }
     }
 
@@ -467,22 +567,22 @@ public class LinkedBlockingQueue extends AbstractQueue
      * <p>If this queue fits in the specified array with room to spare
      * (i.e., the array has more elements than this queue), the element in
      * the array immediately following the end of the queue is set to
-     * <tt>null</tt>.
+     * {@code null}.
      *
      * <p>Like the {@link #toArray()} method, this method acts as bridge between
      * array-based and collection-based APIs.  Further, this method allows
      * precise control over the runtime type of the output array, and may,
      * under certain circumstances, be used to save allocation costs.
      *
-     * <p>Suppose <tt>x</tt> is a queue known to contain only strings.
+     * <p>Suppose {@code x} is a queue known to contain only strings.
      * The following code can be used to dump the queue into a newly
-     * allocated array of <tt>String</tt>:
+     * allocated array of {@code String}:
      *
      * <pre>
      *     String[] y = x.toArray(new String[0]);</pre>
      *
-     * Note that <tt>toArray(new Object[0])</tt> is identical in function to
-     * <tt>toArray()</tt>.
+     * Note that {@code toArray(new Object[0])} is identical in function to
+     * {@code toArray()}.
      *
      * @param a the array into which the elements of the queue are to
      *          be stored, if it is big enough; otherwise, a new array of the
@@ -493,29 +593,32 @@ public class LinkedBlockingQueue extends AbstractQueue
      *         this queue
      * @throws NullPointerException if the specified array is null
      */
-    public Object[] toArray(Object[] a) {
-        synchronized (putLock) {
-            synchronized (takeLock) {
-                int size = count;
-                if (a.length < size)
-                    a = (Object[])java.lang.reflect.Array.newInstance
-                        (a.getClass().getComponentType(), size);
-
-                int k = 0;
-                for (Node p = head.next; p != null; p = p.next)
-                    a[k++] = (Object)p.item;
-                if (a.length > k)
-                    a[k] = null;
-                return a;
-            }
+    @SuppressWarnings("unchecked")
+    public <T> T[] toArray(T[] a) {
+        fullyLock();
+        try {
+            int size = count.get();
+            if (a.length < size)
+                a = (T[])java.lang.reflect.Array.newInstance
+                    (a.getClass().getComponentType(), size);
+
+            int k = 0;
+            for (Node<E> p = head.next; p != null; p = p.next)
+                a[k++] = (T)p.item;
+            if (a.length > k)
+                a[k] = null;
+            return a;
+        } finally {
+            fullyUnlock();
         }
     }
 
     public String toString() {
-        synchronized (putLock) {
-            synchronized (takeLock) {
-                return super.toString();
-            }
+        fullyLock();
+        try {
+            return super.toString();
+        } finally {
+            fullyUnlock();
         }
     }
 
@@ -524,19 +627,18 @@ public class LinkedBlockingQueue extends AbstractQueue
      * The queue will be empty after this call returns.
      */
     public void clear() {
-        synchronized (putLock) {
-            synchronized (takeLock) {
-                head.next = null;
-                assert head.item == null;
-                last = head;
-                int c;
-                synchronized (this) {
-                    c = count;
-                    count = 0;
-                }
-                if (c == capacity)
-                    putLock.notifyAll();
+        fullyLock();
+        try {
+            for (Node<E> p, h = head; (p = h.next) != null; h = p) {
+                h.next = h;
+                p.item = null;
             }
+            head = last;
+            // assert head.item == null && head.next == null;
+            if (count.getAndSet(0) == capacity)
+                notFull.signal();
+        } finally {
+            fullyUnlock();
         }
     }
 
@@ -546,35 +648,8 @@ public class LinkedBlockingQueue extends AbstractQueue
      * @throws NullPointerException          {@inheritDoc}
      * @throws IllegalArgumentException      {@inheritDoc}
      */
-    public int drainTo(Collection c) {
-        if (c == null)
-            throw new NullPointerException();
-        if (c == this)
-            throw new IllegalArgumentException();
-        Node first;
-        synchronized (putLock) {
-            synchronized (takeLock) {
-                first = head.next;
-                head.next = null;
-                assert head.item == null;
-                last = head;
-                int cold;
-                synchronized (this) {
-                    cold = count;
-                    count = 0;
-                }
-                if (cold == capacity)
-                    putLock.notifyAll();
-            }
-        }
-        // Transfer the elements outside of locks
-        int n = 0;
-        for (Node p = first; p != null; p = p.next) {
-            c.add(p.item);
-            p.item = null;
-            ++n;
-        }
-        return n;
+    public int drainTo(Collection<? super E> c) {
+        return drainTo(c, Integer.MAX_VALUE);
     }
 
     /**
@@ -583,70 +658,77 @@ public class LinkedBlockingQueue extends AbstractQueue
      * @throws NullPointerException          {@inheritDoc}
      * @throws IllegalArgumentException      {@inheritDoc}
      */
-    public int drainTo(Collection c, int maxElements) {
+    public int drainTo(Collection<? super E> c, int maxElements) {
         if (c == null)
             throw new NullPointerException();
         if (c == this)
             throw new IllegalArgumentException();
-        synchronized (putLock) {
-            synchronized (takeLock) {
-                int n = 0;
-                Node p = head.next;
-                while (p != null && n < maxElements) {
+        boolean signalNotFull = false;
+        final ReentrantLock takeLock = this.takeLock;
+        takeLock.lock();
+        try {
+            int n = Math.min(maxElements, count.get());
+            // count.get provides visibility to first n Nodes
+            Node<E> h = head;
+            int i = 0;
+            try {
+                while (i < n) {
+                    Node<E> p = h.next;
                     c.add(p.item);
                     p.item = null;
-                    p = p.next;
-                    ++n;
-                }
-                if (n != 0) {
-                    head.next = p;
-                    assert head.item == null;
-                    if (p == null)
-                        last = head;
-                    int cold;
-                    synchronized (this) {
-                        cold = count;
-                        count -= n;
-                    }
-                    if (cold == capacity)
-                        putLock.notifyAll();
+                    h.next = h;
+                    h = p;
+                    ++i;
                 }
                 return n;
+            } finally {
+                // Restore invariants even if c.add() threw
+                if (i > 0) {
+                    // assert h.item == null;
+                    head = h;
+                    signalNotFull = (count.getAndAdd(-i) == capacity);
+                }
             }
+        } finally {
+            takeLock.unlock();
+            if (signalNotFull)
+                signalNotFull();
         }
     }
 
     /**
      * Returns an iterator over the elements in this queue in proper sequence.
-     * The returned <tt>Iterator</tt> is a "weakly consistent" iterator that
-     * will never throw {@link java.util.ConcurrentModificationException},
+     * The returned {@code Iterator} is a "weakly consistent" iterator that
+     * will never throw {@link java.util.ConcurrentModificationException
+     * ConcurrentModificationException},
      * and guarantees to traverse elements as they existed upon
      * construction of the iterator, and may (but is not guaranteed to)
      * reflect any modifications subsequent to construction.
      *
      * @return an iterator over the elements in this queue in proper sequence
      */
-    public Iterator iterator() {
+    public Iterator<E> iterator() {
       return new Itr();
     }
 
-    private class Itr implements Iterator {
+    private class Itr implements Iterator<E> {
         /*
-         * Basic weak-consistent iterator.  At all times hold the next
+         * Basic weakly-consistent iterator.  At all times hold the next
          * item to hand out so that if hasNext() reports true, we will
          * still have it to return even if lost race with a take etc.
          */
-        private Node current;
-        private Node lastRet;
-        private Object currentElement;
+        private Node<E> current;
+        private Node<E> lastRet;
+        private E currentElement;
 
         Itr() {
-            synchronized (putLock) {
-                synchronized (takeLock) {
-                    current = head.next;
-                    if (current != null)
-                        currentElement = current.item;
-                }
+            fullyLock();
+            try {
+                current = head.next;
+                if (current != null)
+                    currentElement = current.item;
+            } finally {
+                fullyUnlock();
             }
         }
 
@@ -654,45 +736,56 @@ public class LinkedBlockingQueue extends AbstractQueue
             return current != null;
         }
 
-        public Object next() {
-            synchronized (putLock) {
-                synchronized (takeLock) {
-                    if (current == null)
-                        throw new NoSuchElementException();
-                    Object x = currentElement;
-                    lastRet = current;
-                    current = current.next;
-                    if (current != null)
-                        currentElement = current.item;
-                    return x;
-                }
+        /**
+         * Returns the next live successor of p, or null if no such.
+         *
+         * Unlike other traversal methods, iterators need to handle both:
+         * - dequeued nodes (p.next == p)
+         * - (possibly multiple) interior removed nodes (p.item == null)
+         */
+        private Node<E> nextNode(Node<E> p) {
+            for (;;) {
+                Node<E> s = p.next;
+                if (s == p)
+                    return head.next;
+                if (s == null || s.item != null)
+                    return s;
+                p = s;
+            }
+        }
+
+        public E next() {
+            fullyLock();
+            try {
+                if (current == null)
+                    throw new NoSuchElementException();
+                E x = currentElement;
+                lastRet = current;
+                current = nextNode(current);
+                currentElement = (current == null) ? null : current.item;
+                return x;
+            } finally {
+                fullyUnlock();
             }
         }
 
         public void remove() {
             if (lastRet == null)
                 throw new IllegalStateException();
-            synchronized (putLock) {
-                synchronized (takeLock) {
-                    Node node = lastRet;
-                    lastRet = null;
-                    Node trail = head;
-                    Node p = head.next;
-                    while (p != null && p != node) {
-                        trail = p;
-                        p = p.next;
-                    }
+            fullyLock();
+            try {
+                Node<E> node = lastRet;
+                lastRet = null;
+                for (Node<E> trail = head, p = trail.next;
+                     p != null;
+                     trail = p, p = p.next) {
                     if (p == node) {
-                        p.item = null;
-                        trail.next = p.next;
-                        if (last == p)
-                            last = trail;
-                        int c;
-                        synchronized (this) { c = count--; }
-                        if (c == capacity)
-                            putLock.notifyAll();
+                        unlink(p, trail);
+                        break;
                     }
                 }
+            } finally {
+                fullyUnlock();
             }
         }
     }
@@ -701,31 +794,33 @@ public class LinkedBlockingQueue extends AbstractQueue
      * Save the state to a stream (that is, serialize it).
      *
      * @serialData The capacity is emitted (int), followed by all of
-     * its elements (each an <tt>Object</tt>) in the proper order,
+     * its elements (each an {@code Object}) in the proper order,
      * followed by a null
      * @param s the stream
      */
     private void writeObject(java.io.ObjectOutputStream s)
         throws java.io.IOException {
 
-        synchronized (putLock) {
-            synchronized (takeLock) {
-                // Write out any hidden stuff, plus capacity
-                s.defaultWriteObject();
+        fullyLock();
+        try {
+            // Write out any hidden stuff, plus capacity
+            s.defaultWriteObject();
 
-                // Write out all elements in the proper order.
-                for (Node p = head.next; p != null; p = p.next)
-                    s.writeObject(p.item);
+            // Write out all elements in the proper order.
+            for (Node<E> p = head.next; p != null; p = p.next)
+                s.writeObject(p.item);
 
-                // Use trailing null as sentinel
-                s.writeObject(null);
-            }
+            // Use trailing null as sentinel
+            s.writeObject(null);
+        } finally {
+            fullyUnlock();
         }
     }
 
     /**
      * Reconstitute this queue instance from a stream (that is,
      * deserialize it).
+     *
      * @param s the stream
      */
     private void readObject(java.io.ObjectInputStream s)
@@ -733,19 +828,16 @@ public class LinkedBlockingQueue extends AbstractQueue
         // Read in capacity, and any hidden stuff
         s.defaultReadObject();
 
-        synchronized (this) { count = 0; }
-        last = head = new Node(null);
+        count.set(0);
+        last = head = new Node<E>(null);
 
         // Read in all elements and place in queue
         for (;;) {
-            Object item = (Object)s.readObject();
+            @SuppressWarnings("unchecked")
+            E item = (E)s.readObject();
             if (item == null)
                 break;
             add(item);
         }
     }
-
-    private static class SerializableLock implements java.io.Serializable {
-        private final static long serialVersionUID = -8856990691138858668L;
-    }
 }
diff --git a/src/actors/scala/actors/threadpool/ThreadPoolExecutor.java b/src/actors/scala/actors/threadpool/ThreadPoolExecutor.java
index f41b279..11e35b0 100644
--- a/src/actors/scala/actors/threadpool/ThreadPoolExecutor.java
+++ b/src/actors/scala/actors/threadpool/ThreadPoolExecutor.java
@@ -791,7 +791,7 @@ public class ThreadPoolExecutor extends AbstractExecutorService {
      */
     private List drainQueue() {
         BlockingQueue q = workQueue;
-        List taskList = new ArrayList();
+        List<Runnable> taskList = new ArrayList<Runnable>();
         q.drainTo(taskList);
         if (!q.isEmpty()) {
             Runnable[] arr = (Runnable[])q.toArray(new Runnable[0]);
diff --git a/src/actors/scala/actors/threadpool/helpers/FIFOWaitQueue.java b/src/actors/scala/actors/threadpool/helpers/FIFOWaitQueue.java
index 6306faa..432b851 100644
--- a/src/actors/scala/actors/threadpool/helpers/FIFOWaitQueue.java
+++ b/src/actors/scala/actors/threadpool/helpers/FIFOWaitQueue.java
@@ -64,7 +64,7 @@ public class FIFOWaitQueue extends WaitQueue implements java.io.Serializable {
     }
 
     public Collection getWaitingThreads() {
-        List list = new ArrayList();
+        List<Thread> list = new ArrayList<Thread>();
         int count = 0;
         WaitNode node = head_;
         while (node != null) {
diff --git a/src/actors/scala/actors/threadpool/helpers/Utils.java b/src/actors/scala/actors/threadpool/helpers/Utils.java
index df1dbd4..d123892 100644
--- a/src/actors/scala/actors/threadpool/helpers/Utils.java
+++ b/src/actors/scala/actors/threadpool/helpers/Utils.java
@@ -41,9 +41,9 @@ public final class Utils {
     static {
         NanoTimer timer = null;
         try {
-            String nanoTimerClassName = (String)
-                AccessController.doPrivileged(new PrivilegedAction() {
-                    public Object run() {
+            String nanoTimerClassName =
+                AccessController.doPrivileged(new PrivilegedAction<String>() {
+                    public String run() {
                         return System.getProperty(providerProp);
                     }
                 });
@@ -206,9 +206,9 @@ public final class Utils {
         final Perf perf;
         final long multiplier, divisor;
         SunPerfProvider() {
-            perf = (Perf)
-                AccessController.doPrivileged(new PrivilegedAction() {
-                    public Object run() {
+            perf =
+                AccessController.doPrivileged(new PrivilegedAction<Perf>() {
+                    public Perf run() {
                         return Perf.getPerf();
                     }
                 });
diff --git a/src/actors/scala/actors/threadpool/locks/CondVar.java b/src/actors/scala/actors/threadpool/locks/CondVar.java
index 132e72f..44df1c0 100644
--- a/src/actors/scala/actors/threadpool/locks/CondVar.java
+++ b/src/actors/scala/actors/threadpool/locks/CondVar.java
@@ -17,6 +17,7 @@ import scala.actors.threadpool.*;
 import scala.actors.threadpool.helpers.*;
 
 class CondVar implements Condition, java.io.Serializable {
+    private static final long serialVersionUID = -5009898475638427940L;
 
     /** The lock **/
     protected final ExclusiveLock lock;
diff --git a/src/actors/scala/actors/threadpool/locks/FIFOCondVar.java b/src/actors/scala/actors/threadpool/locks/FIFOCondVar.java
index 7495a8a..144ac54 100644
--- a/src/actors/scala/actors/threadpool/locks/FIFOCondVar.java
+++ b/src/actors/scala/actors/threadpool/locks/FIFOCondVar.java
@@ -17,6 +17,7 @@ import scala.actors.threadpool.*;
 import scala.actors.threadpool.helpers.*;
 
 class FIFOCondVar extends CondVar implements Condition, java.io.Serializable {
+    private static final long serialVersionUID = -497497271881010475L;
 
     private static final WaitQueue.QueuedSync sync = new WaitQueue.QueuedSync() {
         public boolean recheck(WaitQueue.WaitNode node) { return false; }
diff --git a/src/actors/scala/actors/threadpool/locks/ReentrantReadWriteLock.java b/src/actors/scala/actors/threadpool/locks/ReentrantReadWriteLock.java
index 6411bbe..437af77 100644
--- a/src/actors/scala/actors/threadpool/locks/ReentrantReadWriteLock.java
+++ b/src/actors/scala/actors/threadpool/locks/ReentrantReadWriteLock.java
@@ -190,7 +190,7 @@ public class ReentrantReadWriteLock implements ReadWriteLock, java.io.Serializab
         transient int writeHolds_ = 0;
 
         /** Number of acquires on read lock by any reader thread **/
-        transient HashMap readers_ = new HashMap();
+        transient HashMap<Thread, Integer> readers_ = new HashMap<Thread, Integer>();
 
         /** cache/reuse the special Integer value one to speed up readlocks **/
         static final Integer IONE = new Integer(1);
@@ -344,7 +344,7 @@ public class ReentrantReadWriteLock implements ReadWriteLock, java.io.Serializab
         synchronized int getReadHoldCount() {
             if (activeReaders_ == 0) return 0;
             Thread t = Thread.currentThread();
-            Integer i = (Integer)readers_.get(t);
+            Integer i = readers_.get(t);
             return (i == null) ? 0 : i.intValue();
         }
 
@@ -363,7 +363,7 @@ public class ReentrantReadWriteLock implements ReadWriteLock, java.io.Serializab
             // and ensure visibility by synchronizing (all other accesses to
             // readers_ are also synchronized on "this")
             synchronized (this) {
-                readers_ = new HashMap();
+                readers_ = new HashMap<Thread, Integer>();
             }
         }
     }
@@ -372,6 +372,8 @@ public class ReentrantReadWriteLock implements ReadWriteLock, java.io.Serializab
      * Nonfair version of Sync
      */
     private static class NonfairSync extends Sync {
+        private static final long serialVersionUID = -2392241841540339773L;
+
         NonfairSync() {}
     }
 
diff --git a/src/android-library/scala/ScalaObject.scala b/src/android-library/scala/ScalaObject.scala
index 7ed66b5..10b2306 100644
--- a/src/android-library/scala/ScalaObject.scala
+++ b/src/android-library/scala/ScalaObject.scala
@@ -1,23 +1,13 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: ScalaObject.scala 16881 2009-01-09 16:28:11Z cunei $
 
 
 package scala
 
-import Predef._
-
-trait ScalaObject extends AnyRef {
-
-  /** This method is needed for optimizing pattern matching expressions
-   *  which match on constructors of case classes.
-   */
-  def $tag(): Int = 0
-
-}
+trait ScalaObject extends AnyRef
diff --git a/src/attic/README b/src/attic/README
new file mode 100644
index 0000000..9fb600a
--- /dev/null
+++ b/src/attic/README
@@ -0,0 +1,2 @@
+This is a holding area for source files which aren't used in
+trunk anymore but which we're keeping available for a time.
\ No newline at end of file
diff --git a/src/attic/scala/tools/nsc/models/Models.scala b/src/attic/scala/tools/nsc/models/Models.scala
new file mode 100644
index 0000000..3e8b6f6
--- /dev/null
+++ b/src/attic/scala/tools/nsc/models/Models.scala
@@ -0,0 +1,419 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
+ * @author  Martin Odersky
+ */
+
+package scala.tools.nsc
+package models
+
+import scala.tools.nsc.Global
+
+/** This abstract class ...
+ *
+ *  @author  Sean McDirmid
+ *  @version 1.0
+ */
+abstract class Models {
+  val global: Global
+  import global._
+
+  def acceptPrivate = true
+
+  object Kinds extends Enumeration  {
+    type Kind = Value
+    val CONSTRUCTOR = Value("Constructor")
+    val OBJECT      = Value("Object")
+    val CLASS       = Value("Class")
+    val TRAIT       = Value("Trait")
+    val DEF         = Value("Def")
+    val VAL         = Value("Val")
+    val VAR         = Value("Var")
+    val ARG         = Value("Arg")
+    val TPARAM      = Value("Type")
+  }
+  import Kinds._
+
+  def KINDS = List(CLASS, TRAIT, OBJECT, CONSTRUCTOR, TPARAM, VAL, VAR, DEF)
+
+  def labelFor(kind: Kind): String = kind.toString
+
+  def stringsFor(mods: Modifiers) = {
+    var modString: List[String] = Nil
+    if (mods.isPrivate  ) modString = "private"   :: modString
+    if (mods.isProtected) modString = "protected" :: modString
+    if (mods.isOverride ) modString = "override"  :: modString
+    if (mods.isAbstract ) modString = "abstract"  :: modString
+    if (mods.isDeferred ) modString = "abstract"  :: modString
+    if (mods.isCase     ) modString = "case"      :: modString
+    if (mods.isSealed   ) modString = "sealed"    :: modString
+    if (mods.isFinal    ) modString = "final"     :: modString
+    if (mods.isImplicit ) modString = "implicit"  :: modString
+    modString
+  }
+
+  def codeFor(kind: Kind): String = kind match {
+    case CONSTRUCTOR => codeFor(DEF)
+    case _ => labelFor(kind).toLowerCase()
+  }
+
+  def pluralFor(kind: Kind): String = kind match {
+    case CLASS  => "Classes"
+    case _ => labelFor(kind) + "s"
+  }
+
+  def kindOf(tree: Tree) = {
+    val term0 = tree.symbol;
+    if (term0 != NoSymbol) {
+      if (term0.isVariable) VAR
+      else if (term0.isValueParameter) ARG
+      else if (term0.isMethod) {
+        if (term0.nameString.equals("this")) CONSTRUCTOR
+        else DEF
+      }
+      else if (term0.isClass) {
+        if (tree.asInstanceOf[MemberDef].mods.isTrait) TRAIT
+        else CLASS
+      }
+      else if (term0.isModule) OBJECT
+      else if (term0.isValue) VAL
+      else if (term0.isTypeParameter) TPARAM
+      else if (term0.isType) TPARAM
+      else {
+        // Console.err.println("UNRECOGNIZED SYMBOL: " + term0 + " " + name);
+        null
+      }
+    } else {
+      val ddef = tree.asInstanceOf[ValOrDefDef];
+      if (ddef.mods.hasFlag(symtab.Flags.MUTABLE)) VAR;
+      else VAL;
+    }
+  }
+
+  abstract class Model
+
+  // def textFor(tp : AbsTypeDef) : String = tp.toString()
+
+  /**
+   *  @param tree ...
+   *  @return     ...
+   */
+  def textFor(tree: Tree): String = {
+    var ret = ""
+    if (tree.symbol != NoSymbol) tree.symbol.name.toString()
+    if (ret.equals("<init>")) ret = "this"
+    tree match {
+      case cdef: ClassDef =>
+        ret = ret + "[" +
+          (for (tparam <- cdef.tparams) yield textFor(tparam)) + "]";
+        cdef.mods
+      case vdef: ValOrDefDef =>
+        vdef match {
+          case ddef: DefDef =>
+          ret = ret + "[" +
+            (for (tparam <- ddef.tparams) yield textFor(tparam)) + "]";
+          for (vparams <- ddef.vparamss) {
+            ret = ret + "(" +
+              (for (vparam <- vparams) yield textFor(vparam)) + ")";
+          }
+          case _ =>
+        }
+        ret = ret + " : " + textFor(vdef.tpt)
+/* Martin to Sean: Please check whether this can be dropped or does it need to be adapted? 
+      case atd: AbsTypeDef =>
+        ret = ret + "[" + (for (tparam <- atd.tparams) yield textFor(tparam)) + "]" +
+                     ((if(atd.hi ne null) " <: " + textFor(atd.hi) else "") +
+                     (if(atd.lo ne null) " >: " + textFor(atd.lo) else ""));
+*/
+      case _ =>
+        ret = ret + tree.toString()
+    }
+    ret
+  }
+
+  def mods1(tree: Tree) = tree match {
+    case mdef: MemberDef => mdef.mods
+    case _ => NoMods
+  }
+
+  abstract class HasTree(val parent: Composite) extends Model with Ordered[HasTree] {
+    var tree : Tree = _
+    def update(tree0: Tree): Boolean = {
+      tree = tree0
+      false
+    }
+    def replacedBy(tree0: Tree): Boolean = true
+    def text: String = textFor(tree)
+    var mods0 = NoMods
+
+    def mods = if (mods0 != NoMods) mods0 else mods1(tree)
+
+    override def toString(): String = tree.toString()
+
+    def compare(that: HasTree): Int = {
+      val idx = KINDS.indexOf(kind)
+      val jdx = KINDS.indexOf(that.kind)
+      if (idx != jdx) return idx - jdx
+      val result = tree.symbol.nameString.compare(that.tree.symbol.nameString)
+      if (result != 0) result
+      else toString().compare(that.toString())
+    }
+    def compare [b >: HasTree <% Ordered[b]](that: b): Int = {
+      if (that.isInstanceOf[HasTree])
+        compare(that.asInstanceOf[HasTree])
+      else -1
+    }
+
+    def kind = kindOf(tree)
+
+    //override def    add(from: Composite, model: HasTree): Unit = { parent.add(from, model) }
+    //override def remove(from: Composite, model: HasTree): Unit = { parent.remove(from, model) }
+  }
+
+  class ImportMod(parent0: Composite) extends HasTree(parent0) {
+    def treex = tree.asInstanceOf[Import]
+
+    override def replacedBy(tree0: Tree): Boolean =
+      if (super.replacedBy(tree0) && tree0.isInstanceOf[Import]) {
+        val tree1 = tree0.asInstanceOf[Import]
+        tree1.tpe == treex.tpe
+      } else
+        false
+  }
+
+  class PackageMod(parent0: Composite) extends HasTree(parent0) {
+    def treex = tree.asInstanceOf[PackageDef]
+  }
+
+  trait Composite extends Model {
+    import scala.collection.mutable._
+
+    class Members extends HashSet[HasTree]
+    // val members = new Members
+    object members extends Members
+
+    def isMember(tree: Tree): Boolean = tree.isInstanceOf[Import] // imports welcome anywhere.
+
+    def member(tree: Tree, members: List[Tree]): Tree = tree
+
+    def update0(members1: List[Tree]): Boolean = {
+      // Console.err.println("update0 " + this + " " + members1)
+      // Martin: This is rather ugly code. We should use pattern matching here!
+      if (members1.length == 1 && members1.head.isInstanceOf[PackageDef])
+        return update0(members1.head.asInstanceOf[PackageDef].stats)
+      val marked = new HashSet[HasTree]
+      var updated = false
+      for (mmbr1 <- members1) if (mmbr1.isInstanceOf[PackageDef]) {
+        Console.err.println("PACKAGE: " + mmbr1.symbol + " " + members1.length)
+      } else if (isMember(mmbr1)) {
+        val mmbr2 = member(mmbr1, members1)
+        if (mmbr2 ne null) {
+          var found = false
+          for (mmbr <- members) if (!found && mmbr.replacedBy(mmbr2)) {
+            //Console.err.println("REPLACE: " + mmbr + " with " + mmbr2)
+            mmbr.mods0 = mods1(mmbr1)
+            found = true
+            updated = mmbr.update(mmbr2) || updated
+            marked += mmbr
+          }
+          if (!found) {
+            updated = true
+            val add = modelFor(mmbr2, this)
+            add.update(mmbr2)
+            add.mods0 = mods1(mmbr1) & 
+              ~symtab.Flags.ACCESSOR & ~symtab.Flags.SYNTHETIC
+            val sz = members.size
+            members += (add)
+            assert(members.size == sz + 1)
+            marked += add
+          }
+        }
+        // Console.err.println("update1 " + this + " " + members + " " + marked)
+      }
+      val sz = members.size
+      members.intersect(marked)
+      updated = updated || sz < members.size
+      // check if anything was removed!
+      updated
+    }
+  }
+  abstract class MemberMod(parent0: Composite) extends HasTree(parent0) {
+    def treex = tree.asInstanceOf[MemberDef]
+
+    def name: Name = treex.name
+
+    override def replacedBy(tree0: Tree): Boolean =
+      if (super.replacedBy(tree0) && tree0.isInstanceOf[MemberDef]) {
+        val tree1 = tree0.asInstanceOf[MemberDef]
+        treex.toString().equals(tree1.toString())
+      } else false
+
+    override def update(tree0: Tree): Boolean = {
+      val updated = (tree eq null) || (treex.mods != tree0.asInstanceOf[MemberDef].mods)
+      super.update(tree0) || updated;
+    }
+  }
+
+  abstract class MemberComposite(parent0: Composite) extends MemberMod(parent0) with Composite
+
+  trait HasClassObjects extends Composite {
+    override def isMember(tree: Tree): Boolean =
+      super.isMember(tree) || tree.isInstanceOf[ImplDef]
+  }
+
+  abstract class ValOrDefMod(parent0: Composite) extends MemberComposite(parent0) with HasClassObjects {
+    override def replacedBy(tree0: Tree): Boolean =
+      super.replacedBy(tree0) && tree0.isInstanceOf[ValOrDefDef]
+
+    override def update(tree0: Tree): Boolean = {
+      val tree1 = tree0.asInstanceOf[ValOrDefDef]
+      val updated = (tree eq null) || treex.tpe != tree1.tpe
+      update0(flatten(tree1.rhs, (tree2: Tree) => isMember(tree2)))
+      super.update(tree0) || updated
+    }
+  }
+
+  class ValMod(parent0: Composite) extends ValOrDefMod(parent0) {
+    def treez = tree.asInstanceOf[ValDef]
+    override def replacedBy(tree0: Tree): Boolean =
+      super.replacedBy(tree0) && tree0.isInstanceOf[ValDef]
+  }
+
+  class DefMod(parent0: Composite) extends ValOrDefMod(parent0) {
+    def treez = tree.asInstanceOf[DefDef]
+
+    override def replacedBy(tree0: Tree) : Boolean =
+      if (super.replacedBy(tree0) && tree0.isInstanceOf[DefDef]) {
+        val tree1 = tree0.asInstanceOf[DefDef]
+        if (tree1.vparamss.length == treez.vparamss.length) {
+          val tpz = for (vd <- treez.vparamss) yield for (xd <- vd) yield xd.tpe;
+          val tp1 = for (vd <- tree1.vparamss) yield for (xd <- vd) yield xd.tpe;
+          tpz == tp1
+        } else false
+      } else false
+  }
+
+  abstract class ImplMod(parent0: Composite)
+  extends MemberComposite(parent0) with HasClassObjects {
+    override def replacedBy(tree0: Tree): Boolean =
+      super.replacedBy(tree0) && tree0.isInstanceOf[ImplDef]
+    override def isMember(tree: Tree): Boolean = (super.isMember(tree) ||
+      (tree.isInstanceOf[ValOrDefDef] &&
+        (acceptPrivate || !tree.asInstanceOf[ValOrDefDef].mods.isPrivate)
+       /* && !tree.asInstanceOf[ValOrDefDef].mods.isPrivate */
+       /* && !tree.asInstanceOf[ValOrDefDef].mods.isAccessor */) ||
+      treeInfo.isAliasTypeDef(tree))
+
+    override def member(tree: Tree, members: List[Tree]): Tree = {
+      val tree0 = if (tree.isInstanceOf[DefDef]) {
+        val ddef = tree.asInstanceOf[DefDef]
+        ddef.mods
+        if (ddef.mods.isAccessor && (ddef.symbol ne null)) {
+          val sym0 = ddef.symbol;
+          if (sym0.isSetter) return null;
+          assert(sym0.isGetter);
+          val sym = sym0.accessed
+          val ret = if (sym == NoSymbol) {
+            val sym = analyzer.underlying(sym0)
+            //val name = nme.getterToSetter(sym0.name)
+            //val setter = sym0.owner.info.decl(name);
+            val isVar = sym.isVariable;
+            val mods = (ddef.mods | 
+              (if (isVar) symtab.Flags.MUTABLE else 0) | symtab.Flags.DEFERRED) &
+                ~symtab.Flags.ACCESSOR & ~symtab.Flags.SYNTHETIC
+            val tree = 
+              ValDef(mods, ddef.name, ddef.tpt, ddef.rhs).setPos(ddef.pos).setSymbol(sym);
+            tree :: Nil;
+          } else for (member <- members if member.symbol == sym) yield member
+          if (ret.isEmpty) null
+          else ret.head
+        } else tree
+      } else super.member(tree, members)
+
+      def sym = tree0.symbol
+      if ((tree0 eq null) || tree0.pos == NoPosition) null
+      else if (!acceptPrivate &&
+               tree0.isInstanceOf[ValOrDefDef] &&
+               tree.asInstanceOf[ValOrDefDef].mods.isPrivate) null
+      else tree0
+    }
+
+    def children(tree0: Tree): List[Tree] =
+      tree0.asInstanceOf[ImplDef].impl.body
+
+    override def update(tree0: Tree): Boolean = {
+      var updated = update0(children(tree0))
+      super.update(tree0) || updated
+    }
+  }
+
+  class ClassMod(parent0: Composite) extends ImplMod(parent0) {
+    def treez = tree.asInstanceOf[ClassDef]
+    override def replacedBy(tree0: Tree): Boolean =
+      super.replacedBy(tree0) && tree0.isInstanceOf[ClassDef]
+  }
+
+  class ObjectMod(parent0: Composite) extends ImplMod(parent0) {
+    def treez = tree.asInstanceOf[ModuleDef]
+    override def replacedBy(tree0: Tree): Boolean =
+      super.replacedBy(tree0) && tree0.isInstanceOf[ModuleDef]
+  }
+  class TypeMod(parent0: Composite) extends MemberMod(parent0) {
+    override def replacedBy(tree0 : Tree) : Boolean = (super.replacedBy(tree0) && tree0.isInstanceOf[TypeDef]);
+  }
+  def SourceMod(original: CompilationUnit) = new SourceMod(original)
+
+  class SourceMod(val original: CompilationUnit) extends Composite with HasClassObjects {
+    update(original)
+    //var listener : Listener = null;
+    def update(unit: CompilationUnit) = unit.body match {
+      case pdef: PackageDef => try {
+        update0(pdef.stats)
+      } catch {
+        case e: Error => members.clear; update0(pdef.stats)
+      }
+      case _ =>
+    }
+
+    override def isMember(tree: Tree): Boolean =
+      super.isMember(tree) || tree.isInstanceOf[Import]
+  }
+
+  def flatten0(exprs: List[Tree], filter: (Tree) => Boolean): List[Tree] =
+    for (expr <- exprs; t: Tree <- flatten(expr,filter)) yield t
+
+  def flatten(expr: Tree, filter: (Tree) => Boolean): List[Tree] =
+    if (filter(expr)) expr :: Nil; else expr match {
+      case Block(stats, last) =>
+        flatten0(stats, filter) ::: flatten(last, filter)
+      case If(cond, thenp, elsep) =>
+        flatten(cond,filter) ::: flatten(thenp,filter) ::: flatten(elsep,filter);
+      case Assign(lhs, rhs) =>
+        flatten(rhs, filter)
+      case CaseDef(pat, guard, body) =>
+        flatten(body, filter)
+      case Return(expr0) =>
+        flatten(expr0, filter)
+      case Throw(expr0) =>
+        flatten(expr0,filter)
+      case Try(block, catches, finalizer) =>
+        flatten(block, filter) ::: flatten(finalizer, filter) ::: flatten0(catches, filter)
+      case Match(selector, cases) =>
+        flatten(selector, filter) ::: flatten0(cases, filter)
+      case Apply(fun, args) =>
+        flatten(fun, filter) ::: flatten0(args, filter)
+      case TypeApply(fun, args) =>
+        flatten(fun, filter) ::: flatten0(args, filter)
+      case _ =>
+        Nil
+    }
+
+  def modelFor(tree: Tree, parent: Composite): HasTree = tree match {
+    case _: ValDef       => new ValMod(parent)
+    case _: DefDef       => new DefMod(parent)
+    case _: ClassDef     => new ClassMod(parent)
+    case _: ModuleDef    => new ObjectMod(parent)
+    case _: TypeDef      => new TypeMod(parent)
+    case _: Import       => new ImportMod(parent)
+  }
+
+}
diff --git a/src/attic/scala/tools/nsc/models/SemanticTokens.scala b/src/attic/scala/tools/nsc/models/SemanticTokens.scala
new file mode 100644
index 0000000..f6942d7
--- /dev/null
+++ b/src/attic/scala/tools/nsc/models/SemanticTokens.scala
@@ -0,0 +1,713 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
+ * @author  Martin Odersky
+ */
+
+package scala.tools.nsc
+package models
+
+import java.lang.Character.isJavaIdentifierPart
+import java.lang.Thread
+
+import scala.collection.mutable.{HashMap, HashSet}
+import scala.tools.nsc.Global
+import scala.tools.nsc.symtab.{Flags, Names}
+import scala.tools.nsc.symtab.Flags.DEFERRED
+import scala.tools.nsc.util.{BatchSourceFile, SourceFile}
+import scala.reflect.NameTransformer
+
+class SemanticTokens(val compiler: Global) {   
+  import compiler._  
+  object walker extends symtab.SymbolWalker {
+    lazy val global : compiler.type = compiler
+  }
+  
+  abstract class Kind {}
+  object OBJECT extends Kind
+  object CLASS  extends Kind
+  object TRAIT  extends Kind
+  object DEF    extends Kind
+  object VAL    extends Kind
+  object VAR    extends Kind
+  object ARG    extends Kind
+  object TPARAM extends Kind
+
+  type AnyClass = Class[_]
+
+  // static constants here
+
+  abstract class Token {
+    def length: Int
+    def prev: HasNext
+    def next: HasPrev
+  }
+
+  def eatKeyword(source: BatchSourceFile, pos: Int, keywords: List[String]) : Int = {
+    if (keywords.isEmpty)
+      pos
+    else if (pos == source.length)
+      -1
+    else if (source.beginsWith(pos, " "))
+      eatKeywords(source, pos + 1)
+    else if (source.beginsWith(pos, keywords.head + " "))
+      eatKeywords(source, pos + keywords.head.length + 1)
+    else
+      eatKeyword(source, pos, keywords.tail)
+  }
+
+  def eatKeywords(source: BatchSourceFile, pos: Int): Int = {
+    val keywords =
+      "package" :: "val" :: "var" :: "def" :: "class" :: "trait" :: "override" :: "case" ::
+      "object" :: "sealed" :: "private" :: "protected" :: Nil
+    if (pos != -1) eatKeyword(source, pos, keywords)
+    else pos
+  }
+
+  trait HasNext extends Token {
+    var next0: HasPrev = _
+    def next = next0
+  }
+
+  trait HasPrev extends Token {
+    var prev0: HasNext = _
+    def prev = prev0
+  }
+
+  abstract class Actual extends HasNext with HasPrev {
+    def convertToGap: (Int, Actual) = {
+      val nextGap = next.isInstanceOf[Gap]
+      val prevGap = prev.isInstanceOf[Gap]
+
+      if (prevGap) {
+        val ret = prev.length
+        val gap = prev.asInstanceOf[Gap]
+        gap.setLength(gap.length + length)
+        if (nextGap) {
+          gap.setLength(gap.length + next.length)
+          gap.next0 = next.next
+          next.next.prev0 = gap
+        } else {
+          gap.next0 = next
+          next.prev0 = gap
+        }
+        (ret, gap)
+      }
+      else if (nextGap) {
+        val gap = next.asInstanceOf[Gap]
+        gap.setLength(gap.length + length)
+        gap.prev0 = prev
+        prev.next0 = gap
+        (0, gap)
+      }
+      else {
+        prev.next0 = next
+        next.prev0 = prev
+        val gap = new Gap(prev)
+        gap.setLength(length)
+        (0, gap)
+      }
+
+    }
+    def insert(prev1: HasNext) {
+      next0 = prev1.next
+      prev0 = prev1
+      prev0.next0 = this
+      next0.prev0 = this
+    }
+
+  } // Actual
+
+  final class Gap extends Actual {
+    def this(prev1: HasNext) = {
+      this()
+      insert(prev1)
+    }
+    override def toString() = "gap-" + length
+
+    var length0: Int = -1
+    def length: Int = length0
+    def setLength(length1: Int) = length0 = length1
+
+    // already gap
+    override def convertToGap: (Int, Actual) = (0, this)
+  }
+
+  def Process(unit: CompilationUnit) = new Process(unit)
+  class Process(val unit: CompilationUnit) {
+    private var doLog = true
+    def source = unit.source
+
+    def dbg(tree: Tree) = {
+      def treePos: Position = if (tree ne null) tree.pos else NoPosition;
+      (
+        "TREE=" + tree +
+          (if (tree ne null) (" CLASS=" + tree.getClass()) else "") +
+            " SYM=" + tree.symbol +
+              " POS=" +
+                treePos.dbgString
+    )}
+
+    val symbols = new HashMap[Symbol, Info]
+
+    class Info(val symbol: Symbol) {
+      var defined : Def = _
+      val uses = new HashSet[Use]
+      symbols.update(symbol, this)
+    }
+
+    def info(symbol: Symbol): Info =
+      if (symbols.contains(symbol)) symbols(symbol)
+      else new Info(symbol)
+
+    abstract class Semantic(val symbol: Symbol) extends Actual {
+      val name = NameTransformer.decode(symbol.name.toString).trim()
+      assert(symbol != NoSymbol)
+      def myOuter = Process.this
+
+      def tpe: Type = symbol.tpe
+
+      def length = name.length()
+      def info: Info = if (symbols.contains(symbol)) symbols(symbol) else new Info(symbol)
+
+      def kind = {
+        val term0 = symbol
+        if (false) null
+        else if (term0.isVariable)       VAR
+        else if (term0.isValueParameter) ARG
+        else if (term0.isMethod)         DEF
+        else if (term0.isClass)          CLASS
+        else if (term0.isModule)         OBJECT
+        else if (term0.isValue)          VAL
+        else if (term0.isTypeParameter)  TPARAM
+        else if (term0.isType         )  TPARAM
+        else {
+          // Console.err.println("UNRECOGNIZED SYMBOL: " + term0 + " " + name);
+          null
+        }
+      }
+    }
+
+    class Def(symbol0: Symbol) extends Semantic(symbol0) {
+      info.defined = this
+      override def toString() = "def-" + name + "-" + symbol.getClass()
+    }
+    class Use(symbol0: Symbol, tpe0: Type) extends Semantic(symbol0) {
+      info.uses += this
+
+      override def tpe : Type = if (tpe0 ne null) tpe0 else super.tpe;
+      override def toString() = "use-" + name + "-" + symbol.getClass();
+    }
+    val list = new TokenList
+
+    //build(unit.body)
+    val map = new scala.collection.mutable.LinkedHashMap[Int,Symbol]
+    map.clear // populate the map.
+      class visitor extends walker.Visitor {
+      def contains(pos : Position) = map.contains(pos.point)
+      def apply(pos : Position) = map(pos.point)
+      def update(pos : Position, sym : Symbol) : Unit = if (pos.isDefined) {
+        val offset = pos.point
+        map(offset) = sym
+        val isDef = pos.point == sym.pos.point
+        list.put(offset, (if (isDef) new Def(sym) else new Use(sym, NoType)));
+      }
+    }
+    walker.walk(unit.body, new visitor)(offset => unit.source.identifier(offset, compiler))
+
+
+    // ok start building....
+    def build[T <: Tree](trees: List[T]) {
+      for (tree <- trees) build(tree)
+    }
+
+    def build(tree0: Tree): Unit = try {
+      /* if (tree0.pos != NoPosition) */ tree0 match {
+      case tree: ImplDef =>
+        val pos = eatKeywords(unit.source.asInstanceOf[BatchSourceFile], tree.pos.point)
+        if (pos == -1) {
+
+        } else buildDef(tree.symbol, eatKeywords(unit.source.asInstanceOf[BatchSourceFile], tree.pos.point));
+        tree match {
+          case cdef: ClassDef => build(cdef.tparams)
+          case _ => ;
+        }
+        build(tree.impl.parents)
+        build(tree.impl.body)
+      case tree: ValOrDefDef =>
+        if (!tree.symbol.hasFlag(Flags.ACCESSOR) || tree.symbol.hasFlag(DEFERRED)) {
+          // MO: I added !tree.symbol.hasFlag(DEFERRED) in a refactoring where
+          // getters now can be abstract whereas before they could not.
+          // Adding the condition thus keeps the old behavior. 
+          // todo: review whether this is correct, or whether abstract getters should be included.
+          {
+            val pos : Int = if (tree.name.toString().equals("<init>")) -1 else 
+              eatKeywords(unit.source.asInstanceOf[BatchSourceFile], tree.pos.point);
+          if (false) Console.err.println("VALDEF: tree=" + tree + " sym=" + tree.symbol + " pos0=" + 
+            tree.symbol.pos + " alias=" + tree.symbol.alias + " pos1=" +
+            pos + " pos2=" + tree.pos.dbgString + " " + tree.symbol.hasFlag(Flags.SYNTHETIC));
+
+          if (pos != -1 && !tree.hasFlag(Flags.SYNTHETIC)) 
+            buildDef(tree.symbol, pos);
+              }
+                
+              if (tree.isInstanceOf[DefDef]) {
+                val ddef = tree.asInstanceOf[DefDef];
+                build(ddef.tparams);
+                
+                for (l0 <- ddef.vparamss; arg <- l0) {
+                  val pos0 : Int = if (!unit.source.beginsWith(arg.pos.point, "val ")) arg.pos.point; 
+                                             else unit.source.skipWhitespace(arg.pos.point + ("val ").length());
+                  buildDef(arg.symbol, pos0);
+                  build(arg.tpt);
+                }
+              }
+          //TPT=scala.Iterator[DocGenerator.this.compiler0.CompilationUnit] 260 class scala.tools.nsc.ast.Trees$TypeTree scala.Iterator[DocGenerator.this.compiler0.CompilationUnit] class scala.tools.nsc.symtab.Types$$anon$5
+          if ((tree.tpt eq null) || (tree.tpt.tpe eq null)) {
+            //Console.err.println("BAD: " + tree.tpt + " in " + tree); 
+          } else {
+            //Console.err.println("TPT=" + tree.tpt + " " + tree.tpt.pos + " " + tree.tpt.getClass() + " " + tree.tpt.tpe + " " + tree.tpt.tpe.getClass() + " " + tree.tpt.tpe.getClass().getSuperclass());
+                  build(tree.tpt);
+          }
+        //Console.err.println("RHS: " + tree.rhs + " " + tree.rhs.getClass() + " " + tree.rhs.getClass().getSuperclass());
+              build(tree.rhs);
+            }
+      case tree: PackageDef =>
+        //Console.err.println("PACKAGE: " + tree.name);
+        if (false) {
+          val pos = eatKeywords(unit.source.asInstanceOf[BatchSourceFile], tree.pos.pointOrElse(-1))
+          if (pos != -1)
+            buildDef(tree.symbol, pos)
+        }
+        build(tree.stats)
+      case tree: Function =>
+        for (arg <- tree.vparams if arg.pos != NoPosition) {
+          val name = arg.name.toString().trim()
+          val pos: Int =
+            if (unit.source.beginsWith(arg.pos.pointOrElse(-1), "val "))
+              unit.source.skipWhitespace(arg.pos.pointOrElse(-1) + ("val ").length())
+            else if (unit.source.asInstanceOf[BatchSourceFile].content(arg.pos.point) == ':') {
+              var posx : Int = arg.pos.point
+              while (unit.source.asInstanceOf[BatchSourceFile].content(posx - 1).isWhitespace) posx = posx - 1
+              posx - name.length()
+            } else arg.pos.point
+          buildDef(arg.symbol, pos)
+          build(arg.tpt)
+        }
+        build(tree.body)
+      case tree : TypeTree =>
+        val treex = tree
+        val tree1 = if (tree.original ne null) tree.original else tree
+        def classes(clazz: AnyClass): List[AnyClass] =
+          if (clazz eq null) Nil
+          else clazz :: classes(clazz.getSuperclass())
+        if (tree.original eq null) {
+          if (false) Console.err.println("NO_ORIGINAL: " + tree + " " + tree.tpe + " " + classes(tree.tpe.getClass()));
+        }
+        if (tree.tpe ne null) buildT(tree1, tree.tpe);
+        def buildT( tree : Tree, tpe : Type) : Unit = if (tree.pos != NoPosition) tpe match {
+          case tpe0 : TypeRef => tree match {
+            case apt : AppliedTypeTree => 
+              buildUse(tpe.typeSymbol, apt.tpt.pos.pointOrElse(-1), tpe0);
+          //Console.err.println("APT: " + treex + " vs. " + treex.original);
+          //Console.err.println("APT: " + treex.pos + " vs. " + treex.original.pos + " " + unit.source.dbg(treex.original.pos));
+              //Console.err.println("APT: " + apt.tpt + " sym0=" + apt.tpt.symbol + " sym1=" + tpe0.sym + " apt.args=" + apt.args + " tpe0.args=" + tpe0.args);
+    
+              buildTs (apt.args, tpe0.args);
+            case ident : Ident => buildUse(tpe0.sym, ident.pos.pointOrElse(-1), tpe0);
+            case select : Select =>
+          if (select.symbol == NoSymbol) 
+              try {
+                // build(select);
+            buildUse(tpe0.typeSymbol, selectPos(select), tpe0);
+            //Console.err.println("QUALIFIER: " + select.qualifier + " " + unit.source.dbg(select.qualifier.pos) + " " + tpe0.prefix + " " + tpe0.prefix.getClass() + " " + tpe0.prefix.getClass().getSuperclass() +" " + tpe0.prefix.widen + " " + tpe0.prefix.toLongString);            
+                        buildT(select.qualifier, tpe0.prefix);
+          } catch {
+                        case e : Error => 
+                          Console.err.println("BUILD_SELECT: " + select + " @ " + tpe0 + " " + (select.pos).dbgString);
+                          throw e;
+              }
+            case tpt : TypeTree => 
+          if (tpt.symbol ne null) {
+            Console.err.println("SYM0 " + tpt.symbol + " " + (tpt.pos).dbgString);
+            buildUse(tpt.symbol, tpt.pos.pointOrElse(-1), tpe0);
+          } else if (tpe0.typeSymbol ne null) {
+            //Console.err.println("TYPE_SYM1 " + tpe0.symbol + " " + unit.source.dbg(tpt.pos));
+            buildUse(tpe0.typeSymbol, tpt.pos.pointOrElse(-1), tpe0);
+          } else {
+            Console.err.println("UNKNOWN TPT0: " + (tpt.pos).dbgString + " tpt=" + tpt + " " + tpt.symbol + " tpe0="+ tpe0 + " " + tpe0.typeSymbol + " tpe0.args=" + tpe0.args);
+          }
+            case sft : SelectFromTypeTree => 
+              build(sft.qualifier); // XXX: broken
+                if (false) Console.err.println("SFTT: " + sft + " sym=" + sft.symbol + " name=" + sft.name + " qual=" + sft.qualifier + " qual.sym=" +
+                          sft.qualifier.symbol + 
+                          " qual.pos=" + (sft.qualifier.pos).dbgString + " symbol=" + sft.symbol + " type=" + tpe0 + 
+                          " type.sym=" + tpe0.typeSymbol);
+            case _ => Console.err.println("UNKNOWN TPT2: " + tree + " vs. " + tpe0 + " " + tree.getClass() + " " + (tree.pos).dbgString);
+          }
+          case tpe0 : MethodType => tree match {
+            case tpt: TypeTree =>
+              if (tpt.original ne null) buildT(tpt.original, tpe);
+              else {
+                        Console.err.println("UNKNOWN TPT3: " + tree + " vs. " + tpe0 + " " + (tree.pos).dbgString);
+              }
+            case ident  : Ident  => buildT(ident,  tpe0.resultType);
+            case select : Select => buildT(select, tpe0.resultType);
+            case _ => Console.err.println("UNKNOWN TPE: " + tree + " vs. " + tpe0 + " " + tree.getClass());
+          }
+          case tpe0 : RefinedType => tree match {
+              case cpt : CompoundTypeTree => 
+                  buildTs(cpt.templ.parents, tpe0.parents);
+        
+              case _ : TypeTree => 
+                // Console.err.println("UNKNOWN TPE13: " + dbg(tree) + " tpe0=" + tpe0 + " " + tpe0.parents);
+              case _ =>
+                  if (false) Console.err.println("UNKNOWN TPE5: " + dbg(tree) + " tpe0=" + tpe0 + " " + tpe0.parents);
+          }
+          case tpe0 : ThisType => tree match {
+            case stt : SingletonTypeTree => stt.ref match {
+                case ths : This => build(ths);
+
+          case _ => Console.err.println("UNKNOWN TPE11: " + tpe0 + " " + stt + " " + stt.ref + " " + stt.ref.getClass() + " " + (tree.pos).dbgString);
+        }
+        case tt : This => 
+        case _ : Ident =>
+        case _ : Select =>
+        case tt : TypeTree => 
+          if (false) Console.err.println("UNKNOWN TPE12: " + tpe0 + " " + tree + " " + tree.getClass() + " " + (tree.pos).dbgString);
+        case _ => 
+          if (false) Console.err.println("UNKNOWN TPE10: " + tpe0 + " " + tree + " " + tree.getClass() + " " + (tree.pos).dbgString);
+          }
+        case tpe0 : SingleType => tree match {
+          case ident  : Ident  => buildUse(tpe0.sym, ident.pos.pointOrElse(-1), tpe0);
+          case select : Select =>
+            buildUse(tpe0.termSymbol, selectPos(select), tpe0);
+            //Console.err.println("QUALIFIER-0: " + select.qualifier + " " + unit.source.dbg(select.qualifier.pos) + " " + tpe0.prefix + " " + tpe0.prefix.getClass() + " " + tpe0.prefix.getClass().getSuperclass() +" " + tpe0.prefix.widen + " " + tpe0.prefix.toLongString);            
+            buildT(select.qualifier, tpe0.prefix);
+
+          case _ =>
+            if (false) Console.err.println("UNKNOWN TPE8: " + tree + " " + (tree.pos).dbgString + " TPE=" + tpe0 + " PRE=" + tpe0.pre + " SYM=" + tpe0.sym);
+              
+        }
+      case ctype : ConstantType =>
+          case ErrorType => 
+          case _ => {
+        if (false) Console.err.println("UNKNOWN TPE4: " + tree + " " + tpe + " " + tpe.getClass() + " " + (tree.pos).dbgString);
+          }
+        };
+    def buildTs(trees : List[Tree], types : List[Type]): Unit = if (!trees.isEmpty && !types.isEmpty) {
+              buildT (trees.head, types.head);
+              buildTs(trees.tail, types.tail);
+        } else if (trees.isEmpty != types.isEmpty) {
+             if (false && doLog) {
+        Console.println("" + treex + " vs. " + treex.original);
+        if (treex.original ne null)
+          Console.println("" + treex.tpe + " vs. " + treex.original.tpe);
+               logError("Tree vs. Type mismatch: " + trees + " " + types + " " + (tree.pos).dbgString, null);
+        doLog = false;
+      }
+    };
+/*
+  Martin to Sean: I don't understand why AbsTypeDef is different from AliasTypeDef.
+  Why is the order reversed? Why two buildDefs for tree.symbol vs one for AliasTypeDef?
+      case tree: AbsTypeDef =>
+        //Console.err.println("ABS: " + tree.symbol + " " + unit.source.dbg(tree.namePos) + " " + tree.pos.dbgString);
+        buildDef(tree.symbol, tree.namePos)
+        buildDef(tree.symbol, tree.pos.pointOrElse(-1))
+        build(tree.tparams); //@M
+        build(tree.lo)
+        build(tree.hi)
+*/
+      case tree: Bind =>
+        buildDef(tree.symbol, tree.pos.pointOrElse(-1))
+        build(tree.body)
+      case tree: Ident =>
+        buildUse(tree.symbol, tree.pos.pointOrElse(-1), tree.tpe)
+      case tree: Select =>
+        try {
+          build(tree.qualifier)
+            } catch {
+              case e : Error => Console.err.println("SELECTQ: " + tree + " " + tree.qualifier + " " + (tree.qualifier.pos).dbgString); throw e;
+            }
+            try {
+              if (tree.pos.isDefined && tree.pos.point >= unit.source.length) {
+                if (false) Console.err.println("BAD_SELECT_QUALIFIER " + tree + " @ " + (tree.pos).dbgString);
+          
+        } else {
+          //Console.err.println("SELECT-0: " + tree.symbol + " " + tree.pos.dbgString + " " + (tree.pos - selectPos(tree)));
+                    buildUse(tree.symbol, selectPos(tree), tree.tpe);
+              }
+            } catch {
+              case e : Error => Console.err.println("SELECTU: " + tree + " " + tree.symbol + " " + tree.pos.dbgString); throw e;
+            }
+    case tree: TypeApply =>
+      //Console.err.println("TYPE_APPLY: " + tree + " " + tree.pos.dbgString);    
+      if (!tree.args.isEmpty) {
+        //Console.err.println("ARGS: " + unit.source.dbg(tree.args0.head.pos));    
+      }
+      build(tree.fun)
+      build(tree.args)
+    case tree: Apply =>
+
+      build(tree.fun)
+      build(tree.args)
+      case tree: GenericApply =>
+
+        build(tree.fun)
+        build(tree.args)
+      case tree: Typed =>
+        build(tree.expr)
+        build(tree.tpt)
+      case tree: Block =>
+        if (false) {
+          if (!tree.stats.isEmpty)
+            Console.err.println("BLOCKS: " + tree.stats.head + " " + tree.stats.head.getClass());
+          Console.err.println("BLOCKE: " + tree.expr + " " + tree.expr.getClass())
+        }
+        build(tree.stats)
+        build(tree.expr)
+      case tree: CaseDef =>
+        build(tree.pat)
+        build(tree.guard)
+        build(tree.body)
+      case tree : Assign     => build(tree.lhs); build(tree.rhs);
+      case tree : If         => build(tree.cond); build(tree.thenp); build(tree.elsep);
+      case tree : New        => 
+        //Console.err.println("NEW: " + tree.tpt + " " + tree.tpt.getClass());
+      build(tree.tpt);
+      case tree : Match      => build(tree.selector); build(tree.cases);
+      case tree : Return     => build(tree.expr);
+      case tree : LabelDef   => build(tree.rhs);
+      case tree : Throw      => build(tree.expr);
+      case tree : Try        => build(tree.block); build(tree.catches); build(tree.finalizer);
+      case tree : Alternative => build(tree.trees);
+      case tree : This    => 
+
+        if (tree.symbol ne null) buildUse(tree.symbol, tree.pos.pointOrElse(-1), tree.tpe);
+        //Thread.dumpStack();
+      case tree : TypeDef => 
+        //Console.err.println("ALIAS: " + tree);
+        build(tree.rhs); build(tree.tparams); buildDef(tree.symbol, tree.pos.pointOrElse(-1));
+      case tree : DocDef     => build(tree.definition);
+      case tree: Import => build(tree.expr)
+      case tree: AppliedTypeTree => ;
+      case tree: Annotated => ;
+      case tree: SingletonTypeTree => ;
+      case tree: Super   => ;
+      case tree: Literal => ;
+      case EmptyTree => ;
+      case _ => ;
+        Console.err.println("BAIL: " + (tree0.pos) + " " + tree0 + " " + tree0.getClass());
+    }
+  } catch {
+    case t: Throwable =>
+      logError("Error occured at " + (tree0.pos), t)
+  }
+
+  def buildUse(term: Symbol, pos: Int, tpe: Type) = buildSym(term, pos, false, tpe)
+  def buildDef(term: Symbol, pos: Int) = buildSym(term, pos, true, null)
+
+  def buildSym(term: Symbol, pos: Int, isDef: Boolean, tpe: Type): Unit =
+    if (term.hasFlag(Flags.ACCESSOR))
+      buildSym(analyzer.underlying(term), pos, isDef, tpe)
+    else if (pos == -1) {
+      //Console.err.println("NOPOS: " + term)
+      //Thread.dumpStack()
+    }
+    else if (term != NoSymbol) {
+      val name = NameTransformer.decode(term.name.toString).trim()
+      val buf = unit.source.asInstanceOf[BatchSourceFile].content
+      val cs = name.toChars
+      var idx = 0
+      if (cs.length + pos > buf.length) return
+      else while (idx < cs.length) {
+        if (buf(pos + idx) != cs(idx)) {
+          //Console.err.println("MISMATCH: " + name + "[" + idx + "] " + unit.source.dbg(pos));
+          //Thread.dumpStack();
+          return;
+        }
+        else idx = idx + 1;
+      }
+      if (cs.length + pos + 1 < buf.length) {
+        if (isJavaIdentifierPart(buf(pos + cs.length))) {
+          //Console.err.println("MISMATCH: " + name + "[last] " + unit.source.dbg(pos));
+          return;
+        }
+      }
+      try {
+        list.put(pos, (if (isDef) new Def(term) else new Use(term, tpe)));
+      } catch {
+        case e : Error => e.printStackTrace();
+      }
+    }
+
+  def selectPos(tree: Select): Int = if (tree.pos == NoPosition) -1 else {
+    val buf = unit.source.asInstanceOf[BatchSourceFile].content
+    if (tree.pos.point >= buf.length) {
+      if (false) {
+        Console.err.println("" + tree + "@" + tree.pos + " not in " +
+                           unit.source.file.name + "[" + buf.length + "]");
+        Thread.dumpStack()
+        abort()
+      }
+      return 0
+    }
+
+    val pos : Int =
+      if (buf(tree.pos.point) != '.') tree.pos.point
+      else {
+        def f(x : Int) : Int = {
+          if (buf(x).isWhitespace) f(x + 1)
+          else x
+        }
+        f(tree.pos.point + 1)
+      }
+    pos
+  };
+
+  class TokenList {
+    object begin extends HasNext {
+      def prev = this
+      def length = 0
+    }
+    object end extends HasPrev {
+      def next = this
+      def length = 0
+    }
+    // initialize
+    begin.next0 = end
+    end.prev0 = begin
+
+    def tokenAt(offset: Int) = {
+      cursor.seek(offset)
+      if (cursor.token.isInstanceOf[Semantic]) cursor.token.asInstanceOf[Semantic]
+      else null
+    }
+
+    def put(offset: Int, tok: Actual): Unit = tok match {
+      case tok0: Semantic => put(offset, tok0)
+      case gap: Gap      =>
+    }
+
+    def put(offset: Int, tok: Semantic) {
+      cursor.seek(offset);
+      if (cursor.token == end) {
+        assert(offset >= cursor.offset);
+        if (offset > cursor.offset) {
+          // add a gap.
+          val gap = new Gap(end.prev);
+          gap.setLength(offset - cursor.offset);
+          cursor.offset = offset;
+        }
+        // append.
+        tok.insert(end.prev);
+        cursor.offset = cursor.offset + tok.length;
+      } else if (!cursor.token.isInstanceOf[Gap]) {
+        val sem = cursor.token.asInstanceOf[Semantic];
+        if (sem.symbol == tok.symbol) return;
+        if (sem.symbol != tok.symbol &&
+            sem.symbol.getClass() == tok.symbol.getClass() &&
+            sem.symbol.pos == tok.symbol.pos) return;
+      } else {
+        val gap = cursor.token.asInstanceOf[Gap];
+        if (!(offset - cursor.offset + tok.length <= gap.length)) {
+          Console.err.println("LIST  =" + this);
+          Console.err.println("OFFSET=" + offset + " " + tok + " " + tok.length);
+          Console.err.println("       " + cursor.offset + " " + gap.length);
+          gap.length0 = offset - cursor.offset + tok.length
+          //abort();
+        }
+        if (offset == cursor.offset) {
+          // replace or prepend
+          tok.prev0 = gap.prev0;
+          if (tok.length == gap.length) { // replace gap
+            tok.next0 = gap.next0;
+          } else {
+            gap.setLength(gap.length - tok.length);
+            tok.next0 = gap;
+          }
+          tok.next0.prev0 = tok;
+          tok.prev0.next0 = tok;
+          cursor.token = tok;
+        } else {
+          // append
+          val diff = (cursor.offset + gap.length) - (offset + tok.length);
+
+          gap.setLength(gap.length - tok.length - diff);
+          tok.prev0 = gap;
+          tok.next0 = gap.next;
+          tok.next0.prev0 = tok;
+          tok.prev0.next0 = tok;
+          if (diff != 0) {
+            val gap0 = new Gap(tok);
+            gap0.setLength(diff);
+          }
+        }
+      }
+    }
+
+    override def toString(): String = {
+      var node = begin.next
+      var str = ""
+      while (node != end) {
+        str = str + " " + node
+        node = node.next
+      }
+      str
+    }
+
+    object cursor {
+      var token: Token = end
+      var offset: Int = 0
+
+      def next: Unit = if (token == end) end else {
+        offset = offset + token.length
+        token  = token.next
+      }
+      def prev: Unit = if (token.prev == begin) token else {
+        offset = offset - token.prev.length
+        token = token.prev
+      }
+      def seek(soffset: Int): Unit = if (soffset == 0) {
+        token = begin.next
+        offset = 0
+      } else {
+        assert(soffset > 0)
+        while (offset                >  soffset) prev;
+        while (offset + token.length <= soffset && token != end) {
+          val len0 = offset;
+          next;
+        }
+      }
+      def convertToGap = if (token.isInstanceOf[Actual]) {
+        val ret = token.asInstanceOf[Actual].convertToGap;
+        offset  = offset - ret._1;
+        token   = ret._2;
+      }
+    }
+
+    // add or delete characters
+    def adjust(offset: Int, /* where */
+               length: Int, /* how many characters are modified */
+               to    : Int  /* length of new string */) = {
+      cursor.seek(offset)
+      if (cursor.token != end) {
+        cursor.convertToGap
+        while (cursor.offset + cursor.token.length < offset + length && cursor.token.next != end) {
+          val save = cursor.offset
+          cursor.next
+          cursor.convertToGap
+          assert(cursor.offset == save)
+        }
+         if (length != to && cursor.token != end) {
+           val diff = to - length;
+           val gap = cursor.token.asInstanceOf[Gap];
+           gap.setLength(gap.length + diff);
+         };
+      }
+    }
+
+  } // TokenList
+
+  }
+}
+
diff --git a/src/attic/scala/tools/nsc/models/Signatures.scala b/src/attic/scala/tools/nsc/models/Signatures.scala
new file mode 100644
index 0000000..d9ee195
--- /dev/null
+++ b/src/attic/scala/tools/nsc/models/Signatures.scala
@@ -0,0 +1,85 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
+ * @author  Martin Odersky
+ */
+
+package scala.tools.nsc
+package models
+
+import scala.collection.mutable.{HashMap, HashSet}
+import scala.tools.nsc.{Global => Compiler}
+import scala.tools.nsc.symtab.{Flags, Names}
+import scala.tools.nsc.util.{ Position, SourceFile }
+import scala.reflect.NameTransformer
+
+/** This class ...
+ *
+ *  @author  Sean McDirmid
+ *  @version 1.0
+ */
+class Signatures(val compiler: Compiler) {
+  import compiler._
+
+  class Signature(val name: String, val children: List[Signature]) {
+    def asString: String = name + "[" + asString0(children) + "]"
+  }
+
+  def sort(sigs: List[Signature]) = sigs sortBy (_.name) reverse
+
+  def asString0(sigs: List[Signature]): String =
+    sort(sigs) map (_.asString) mkString
+
+  def signature(unit: CompilationUnit): String =
+    asString0(signature(unit.body, Nil))
+
+  def signature(trees: List[Tree]): List[Signature] = {
+    var ret : List[Signature] = Nil
+    for (tree <- trees) ret = signature(tree, ret)
+    ret
+  }
+
+  /**
+   *  @param tree0 ...
+   *  @param rest  ...
+   *  @return      ...
+   */
+  def signature(tree0: Tree, rest: List[Signature]): List[Signature] = tree0 match {
+    case tree: MemberDef => if (!tree.mods.isPrivate) {
+      val name = "" + tree.name + "::" + 
+        (tree.mods &~ Flags.SYNTHETIC)
+      
+      val children: List[Signature] = tree match {
+          case impl: ImplDef
+            //if (!impl.name.toString.contains("$anonfun$")) =>
+            if (impl.name.pos("$anonfun$") == name.length) =>
+          val supers = new Signature("$$supers", signature(impl.impl.parents))
+          val body   = new Signature("$$body",   signature(impl.impl.body))
+          val ret = supers :: body :: Nil
+          impl match {
+            case cdef: ClassDef =>
+              new Signature("$$tparams", signature(cdef.tparams)) :: ret
+            case  _ =>
+              ret
+          }
+        case vdef: ValOrDefDef =>
+          val ret = signature(vdef.tpt, Nil)
+          vdef match {
+            case ddef : DefDef =>
+              val tparams = new Signature("$$tparams", signature(ddef.tparams))
+              var vparamss : List[Signature] = Nil
+              for (list <- ddef.vparamss)
+                vparamss = signature(list) ::: vparamss
+              new Signature("$$ret", ret) :: tparams :: vparamss
+            case _ =>
+              ret
+          }
+        case pdef: PackageDef => signature(pdef.stats)
+        case _ => Nil
+      }
+      new Signature(name, children) :: rest
+
+    } else rest
+    case tree: TypeTree => new Signature("" + tree.tpe, Nil) :: rest
+    case _ => rest
+  }
+}
diff --git a/src/attic/scala/tools/nsc/symtab/SymbolWalker.scala b/src/attic/scala/tools/nsc/symtab/SymbolWalker.scala
new file mode 100644
index 0000000..044a6dd
--- /dev/null
+++ b/src/attic/scala/tools/nsc/symtab/SymbolWalker.scala
@@ -0,0 +1,253 @@
+package scala.tools.nsc
+package symtab
+
+trait SymbolWalker {
+  val global : Global 
+  import global._
+  import scala.collection.mutable.LinkedHashSet
+  trait Visitor {
+    def update(pos : Position, sym : Symbol) : Unit
+    def contains(pos : Position) : Boolean
+    def apply(pos : Position) : Symbol
+    def putDef(sym : Symbol, pos : Position) : Unit = ()
+  }
+  import scala.collection.mutable.Map
+  /*
+  implicit def map2use(map : Map[Position,Symbol]) = new Visitor {
+    def update(pos : Position, sym : Symbol) : Unit = map.update(pos, sym)
+    def contains(pos : Position) : Boolean = map.contains(pos)
+    def apply(pos : Position) : Symbol = map.apply(pos)
+  }
+  */
+  private def validSym(t: Tree) = t.symbol != NoSymbol && t.symbol != null
+  private def validSym(tp: Type) = tp != null && tp.typeSymbol != NoSymbol && tp.typeSymbol != null
+  private def notNull(tp: Type) = tp.typeSymbol != null
+  private def isNoSymbol(t: Tree) = t.symbol eq NoSymbol
+  
+  def walk(tree: Tree, visitor : Visitor)(fid : (util.Position) => Option[String]) : Unit = {
+    val visited = new LinkedHashSet[Tree]
+    def f(t : Tree) : Unit = {
+      if (visited.add(t)) return
+      
+      def fs(l: List[Tree]) = l foreach f
+      def fss(l: List[List[Tree]]) = l foreach fs
+
+      val sym = (t, t.tpe) match {
+        case (Super(_,_),SuperType(_,supertp)) if validSym(supertp) => supertp.typeSymbol
+        case _ if validSym(t)                                       => t.symbol
+        case (t: TypeTree, tp) if validSym(tp)                      => tp.typeSymbol
+        case (t: TypeTree, tp) if validSym(tp.resultType)           => tp.resultType.typeSymbol
+        case (t, tpe: Type) if isNoSymbol(t) && tpe.termSymbol != null  =>
+          if (t.isTerm) tpe.termSymbol
+          else t.tpe match {
+            case x: TypeRef => x.sym    // XXX: looks like a bug
+            case _          => tpe.typeSymbol
+          }
+        case _  => NoSymbol
+      }
+
+      if (sym != null && sym != NoSymbol /* && !sym.hasFlag(SYNTHETIC) */) {
+        var id = fid(t.pos) 
+        val doAdd = if (id.isDefined) {
+          if (id.get.charAt(0) == '`') id = Some(id.get.substring(1, id.get.length - 1))
+          val name = sym.name.decode.trim
+          if ((name startsWith id.get) || (id.get startsWith name)) true 
+          else {
+            false
+          }
+        } else false
+        if (doAdd) {
+          
+        if (!visitor.contains(t.pos)) {
+          visitor(t.pos) = sym
+        } else {
+          val existing = visitor(t.pos)
+          if (sym.sourceFile != existing.sourceFile || sym.pos != existing.pos) {
+            (sym,existing) match {
+            case (sym,existing) if sym.pos == existing.pos => 
+            case (sym : TypeSymbol ,_ : ClassSymbol) => visitor(t.pos) = sym
+            case (_ : ClassSymbol,_ : TypeSymbol) => // nothing
+            case _ if sym.isModule && existing.isValue => // nothing
+            case _ if sym.isClass && existing.isMethod => // nothing
+            case _ =>
+              assert(true)
+            }
+          }
+        }}
+      }
+      t match {
+      case t : DefTree if t.symbol != NoSymbol =>
+        if (t.pos != NoPosition)
+          visitor.putDef(t.symbol, t.pos)
+          if (t.symbol.isClass) {
+            val factory = NoSymbol // XXX: t.symbol.caseFactory
+            if (factory != NoSymbol) {
+              visitor.putDef(factory, t.pos)
+            }
+        }
+      case t : TypeBoundsTree => f(t.lo); f(t.hi)
+      case t : TypeTree if t.original != null => 
+        def h(original : Tree, tpe : Type): Unit = try {
+          if (original.tpe == null)
+            original.tpe = tpe
+          (original) match {
+          case (AppliedTypeTree(_,trees)) if tpe.isInstanceOf[TypeRef] => 
+            val types = tpe.asInstanceOf[TypeRef].args
+            trees.zip(types).foreach{
+            case (tree,tpe) => assert(tree != null && tpe != null); h(tree, tpe)
+            }
+          case _ => 
+          }
+        }
+        if (t.original.tpe == null) {
+          val dup = t.original.duplicate
+          h(dup,t.tpe)
+          f(dup)
+        } else f(t.original)
+        ()
+      case _ =>
+      }
+      (t) match {
+      case (t : MemberDef) if t.symbol != null && t.symbol != NoSymbol => 
+        val annotated = if (sym.isModule) sym.moduleClass else sym
+        val i = t.mods.annotations.iterator
+        val j = annotated.annotations.iterator
+        while (i.hasNext && j.hasNext) {
+          val tree = i.next
+          val ainfo = j.next
+          val sym = ainfo.atp.typeSymbol
+          tree.setType(ainfo.atp)
+          tree.setSymbol(sym)
+          f(tree)
+        }
+
+      case _ =>  
+      }
+      t match {
+      case tree: ImplDef => 
+        fs(tree.impl.parents); f(tree.impl.self); fs(tree.impl.body) 
+        tree match {
+        case tree : ClassDef => fs(tree.tparams)
+        case _ =>
+        }
+      case tree: PackageDef => fs(tree.stats)
+      case tree: ValOrDefDef => 
+        f(tree.rhs); 
+        if (tree.tpt != null) {
+          f(tree.tpt)
+        }
+        tree match {
+        case tree : DefDef => fs(tree.tparams); fss(tree.vparamss)
+        case _ => 
+        }
+      case tree: Function => fs(tree.vparams); f(tree.body)
+      case tree : Bind => f(tree.body)
+      case tree : Select => 
+        val qualifier = if (tree.tpe != null && tree.qualifier.tpe == null) {
+          val pre = tree.tpe.prefix
+          val qualifier = tree.qualifier.duplicate
+          qualifier.tpe = pre
+          qualifier
+        } else tree.qualifier
+      
+        f(qualifier)
+      case tree : Annotated => f(tree.annot); f(tree.arg)
+      case tree : GenericApply => f(tree.fun); fs(tree.args)
+      case tree : UnApply => f(tree.fun); fs(tree.args)
+      case tree : AppliedTypeTree =>
+        if (tree.tpe != null) {
+          val i = tree.tpe.typeArgs.iterator
+          val j = tree.args.iterator
+          while (i.hasNext && j.hasNext) {
+            val tpe = i.next
+            val arg = j.next
+            if (arg.tpe == null) {
+              arg.tpe = tpe  
+            }
+          }
+          if (tree.tpt.tpe == null) {
+            tree.tpt.tpe = tree.tpe
+          }
+          
+        }
+        f(tree.tpt); fs(tree.args) 
+
+      case tree : ExistentialTypeTree=>
+        if (tree.tpt.tpe == null) {
+          tree.tpt.tpe = tree.tpe
+        }
+        
+        f(tree.tpt)
+        fs(tree.whereClauses)
+      case tree : SingletonTypeTree => 
+        if (tree.ref.tpe == null) {
+          val dup = tree.ref.duplicate
+          dup.tpe = tree.tpe
+          f(dup)
+        } else f(tree.ref)
+      case tree : CompoundTypeTree => 
+        if (tree.tpe != null && tree.tpe.typeSymbol != null && tree.tpe.typeSymbol.isRefinementClass) tree.tpe.typeSymbol.info match {
+        case tpe : RefinedType => 
+          tpe.parents.zip(tree.templ.parents).foreach{
+          case (tpe,tree) => 
+            if (tree.hasSymbol && (tree.symbol == NoSymbol || tree.symbol == null)) {
+              tree.symbol = tpe.typeSymbol
+            }
+          }
+        
+        case _ =>
+        }
+        
+        f(tree.templ)
+      case tree : Template => fs(tree.parents); f(tree.self); fs(tree.body)
+      case tree : SelectFromTypeTree => {
+        if (tree.qualifier.tpe == null) tree.tpe match {
+        case tpe : TypeRef =>
+          // give it a type!
+          tree.qualifier.tpe = tpe.prefix
+        case _ => 
+          // tree.tpe.pre
+        }
+        f(tree.qualifier)
+      }
+      case tree : Literal => 
+      /*
+        if (tree.tpe != null && tree.tpe.typeSymbol == definitions.ClassClass) {
+          // nothing we can do without original tree.
+        }
+      */
+      
+      case tree : Typed => f(tree.expr); f(tree.tpt)
+      case tree : Block => fs(tree.stats); f(tree.expr)
+      case tree: CaseDef => f(tree.pat);f(tree.guard);f(tree.body)
+      case tree : Assign     => f(tree.lhs); f(tree.rhs);
+      case tree : If         => f(tree.cond); f(tree.thenp); f(tree.elsep);
+      case tree : New        => f(tree.tpt);
+      case tree : Match      => f(tree.selector); fs(tree.cases);
+      case tree : Return     => f(tree.expr);
+      case tree : LabelDef   => f(tree.rhs);
+      case tree : Throw      => f(tree.expr);
+      case tree : Try        => f(tree.block); fs(tree.catches); f(tree.finalizer);
+      case tree : Alternative => fs(tree.trees);
+      case tree : TypeDef => 
+        (tree.tpe,sym) match {
+          case (null,sym : TypeSymbol) if (sym.rawInfo.isComplete) =>
+            if (tree.tparams.isEmpty) {
+              if (tree.rhs.tpe == null) tree.rhs.tpe = sym.info
+              f(tree.rhs)
+            } else {
+              val tree0 = AppliedTypeTree(tree.rhs, tree.tparams)
+              tree0.tpe = sym.info
+              f(tree0)
+            }
+          case _ => f(tree.rhs); fs(tree.tparams)
+        }
+      case tree : DocDef     => f(tree.definition);
+      case tree: Import => f(tree.expr)
+      case _ => 
+      }
+    }
+    f(tree)
+  }
+  
+}
diff --git a/src/build/four.xml b/src/build/four.xml
deleted file mode 100644
index 8d046df..0000000
--- a/src/build/four.xml
+++ /dev/null
@@ -1,470 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-
-<project name="sabbus-four">
-
-  <description>
-    SuperSabbus extension for the Scala library and compiler targeted for the JVM 1.4. THIS FILE IS NOT STAND-ALONE AND SHOULD ONLY BE USED THROUGH ENTRY POINTS IN SUPERSABBUS.
-  </description>
-  
-  <!-- TODO: Use a 1.4 Java standard library to compile against, instead of that of the JVM running the script. -->
-  <!-- TODO: Use a 1.4 Java standard library to run partests. Add a bootclasspath option to partest to allow that. -->
-  
-<!-- ===========================================================================
-PROPERTIES
-============================================================================ -->
-  
-  <property name="build-four.dir" value="${build.dir}/four"/>
-  <property name="build-four-src.dir" value="${build.dir}/four-src"/>
-  <property name="build-four-pack.dir" value="${build.dir}/four-pack"/>
-  <property name="build-four-docs.dir" value="${build.dir}/four-docs"/>
-  
-<!-- ===========================================================================
-JAVA 1.4 LIBRARY AND COMPILER BUILD (FOUR)
-============================================================================ -->
-
-  <target name="four.start"/>
-
-  <target name="four.src" depends="four.start">
-    <!-- simple sync & copy overwrite is not very nice, because overwritten files
-         will then have a new timestamp, and be recompiled -->
-    <mkdir dir="${build-four-src.dir}"/>
-    <copy todir="${build-four-src.dir}" overwrite="true">
-      <fileset dir="${src.dir}/library">
-        <and>
-          <present present="srconly" targetdir="${src.dir}/jvm14-library"/>
-          <different targetdir="${build-four-src.dir}" ignoreFileTimes="true"/>
-        </and>
-      </fileset>
-      <fileset dir="${src.dir}/jvm14-library">
-        <different targetdir="${build-four-src.dir}" ignoreFileTimes="true"/>
-      </fileset>
-    </copy>
-    <delete verbose="true">
-      <difference>
-        <fileset dir="${build-four-src.dir}"/>
-        <union>
-          <fileset dir="${build-four-src.dir}">
-            <present targetdir="${src.dir}/jvm14-library"/>
-          </fileset>
-          <fileset dir="${build-four-src.dir}">
-            <present targetdir="${src.dir}/library"/>
-          </fileset>
-        </union>
-      </difference>
-    </delete>
-    <mkdir dir="${build-four-src.dir}-actors"/>
-    <copy todir="${build-four-src.dir}-actors" overwrite="true">
-      <fileset dir="${src.dir}/actors">
-        <and>
-          <present present="srconly" targetdir="${src.dir}/jvm14-actors"/>
-          <different targetdir="${build-four-src.dir}-actors" ignoreFileTimes="true"/>
-        </and>
-      </fileset>
-      <fileset dir="${src.dir}/jvm14-actors">
-        <different targetdir="${build-four-src.dir}-actors" ignoreFileTimes="true"/>
-      </fileset>
-    </copy>
-    <delete verbose="true">
-      <difference>
-        <fileset dir="${build-four-src.dir}-actors"/>
-        <union>
-          <fileset dir="${build-four-src.dir}-actors">
-            <present targetdir="${src.dir}/jvm14-actors"/>
-          </fileset>
-          <fileset dir="${build-four-src.dir}-actors">
-            <present targetdir="${src.dir}/actors"/>
-          </fileset>
-        </union>
-      </difference>
-    </delete>
-  </target>
-
-  <target name="four.lib" depends="four.src">
-    <stopwatch name="four.lib.timer"/>
-    <mkdir dir="${build-four.dir}/classes/library"/>
-    <javac
-      srcdir="${build-four-src.dir}"
-      destdir="${build-four.dir}/classes/library"
-      classpath="${build-four.dir}/classes/library"
-      includes="**/*.java"
-      target="1.4" source="1.4"/>
-    <javac
-      srcdir="${build-four-src.dir}-actors"
-      destdir="${build-four.dir}/classes/library"
-      classpath="${build-four.dir}/classes/library"
-      includes="**/*.java"
-      target="1.4" source="1.4"/>
-    <scalac
-      srcdir="${build-four-src.dir}"
-      destdir="${build-four.dir}/classes/library"
-      classpath="${build-four.dir}/classes/library"
-      sourcepath="${build-four-src.dir}"
-      target="jvm-1.4">
-      <include name="scala/Predef.scala"/>
-    </scalac>
-    <scalac
-      srcdir="${build-four-src.dir}"
-      destdir="${build-four.dir}/classes/library"
-      classpath="${build-four.dir}/classes/library"
-      target="jvm-1.4">
-      <include name="**/*.scala"/>
-      <exclude name="scala/Predef.scala"/>
-    </scalac>
-    <scalac
-      srcdir="${build-four-src.dir}-actors"
-      destdir="${build-four.dir}/classes/library"
-      classpath="${build-four.dir}/classes/library"
-      target="jvm-1.4">
-      <include name="**/*.scala"/>
-    </scalac>
-    <scalac
-      srcdir="${src.dir}/dbc"
-      destdir="${build-four.dir}/classes/library"
-      classpath="${build-four.dir}/classes/library"
-      target="jvm-1.4">
-      <include name="**/*.scala"/>
-    </scalac>
-    <scalac
-      srcdir="${src.dir}/swing"
-      destdir="${build-four.dir}/classes/library"
-      classpath="${build-four.dir}/classes/library"
-      target="jvm-1.4">
-      <include name="**/*.scala"/>
-    </scalac>
-    <propertyfile file="${build-four.dir}/classes/library/library.properties">
-      <entry key="version.number" value="${version.number}"/>
-      <entry key="copyright.string" value="${copyright.string}"/>
-    </propertyfile>
-    <copy todir="${build-four.dir}/classes/library">
-      <fileset dir="${build-four-src.dir}">
-        <include name="**/*.tmpl"/>
-        <include name="**/*.xml"/>
-        <include name="**/*.js"/>
-        <include name="**/*.css"/>
-      </fileset>
-    </copy>
-    <stopwatch name="four.lib.timer" action="total"/>
-  </target>
-
-  <target name="four.comp" depends="four.lib">
-    <stopwatch name="four.comp.timer"/>
-    <mkdir dir="${build-four.dir}/classes/compiler"/>
-    <scalac
-      srcdir="${src.dir}/compiler"
-      destdir="${build-four.dir}/classes/compiler"
-      target="jvm-1.4">
-      <include name="**/*.scala"/>
-      <classpath>
-        <pathelement location="${build-four.dir}/classes/library"/>
-        <pathelement location="${build-four.dir}/classes/compiler"/>
-        <pathelement location="${fjbg.jar}"/>
-        <pathelement location="${msil.jar}"/>
-        <pathelement location="${jline.jar}"/>
-        <pathelement location="${ant.jar}"/>
-      </classpath>
-    </scalac>
-    <propertyfile file="${build-four.dir}/classes/compiler/compiler.properties">
-      <entry key="version.number" value="${version.number}"/>
-      <entry key="copyright.string" value="${copyright.string}"/>
-    </propertyfile>
-    <copy todir="${build-four.dir}/classes/compiler">
-      <fileset dir="${src.dir}/compiler">
-        <include name="**/*.tmpl"/>
-        <include name="**/*.xml"/>
-        <include name="**/*.js"/>
-        <include name="**/*.css"/>
-      </fileset>
-    </copy>
-    <stopwatch name="four.comp.timer" action="total"/>
-  </target>
-    
-  <target name="four.partest" depends="four.comp">
-    <stopwatch name="four.partest.timer"/>
-    <mkdir dir="${build-four.dir}/classes/partest"/>
-    <javac
-      srcdir="${src.dir}/partest"
-      destdir="${build-four.dir}/classes/partest"
-      target="1.4" source="1.4">
-      <classpath>
-      	<pathelement location="${build-four.dir}/classes/library"/>
-      	<pathelement location="${build-four.dir}/classes/compiler"/>
-      	<pathelement location="${build-four.dir}/classes/partest"/>
-      </classpath>
-      <include name="**/*.java"/>
-    </javac>
-    <scalac
-      srcdir="${src.dir}/partest"
-      destdir="${build-four.dir}/classes/partest"
-      target="jvm-1.4">
-      <include name="**/*.scala"/>
-      <classpath>
-        <pathelement location="${build-four.dir}/classes/library"/>
-        <pathelement location="${build-four.dir}/classes/compiler"/>
-        <pathelement location="${build-four.dir}/classes/partest"/>
-        <pathelement location="${ant.jar}"/>
-      </classpath>
-    </scalac>
-    <copy todir="${build-four.dir}/classes/partest">
-      <fileset dir="${src.dir}/partest">
-        <include name="**/*.xml"/>
-      </fileset>
-    </copy>
-    <stopwatch name="four.partest.timer" action="total"/>
-  </target>
-  
-  <target name="four.done" depends="four.partest"/>
-
-  <target name="four.clean" depends="four-pack.clean">
-    <delete dir="${build-four.dir}" includeemptydirs="yes" quiet="yes" failonerror="no"/>
-    <delete dir="${build-four-src.dir}" includeemptydirs="yes" quiet="yes" failonerror="no"/>
-  </target>
-
-<!-- ===========================================================================
-PACKED FOUR BUILD (FOUR-PACK)
-============================================================================ -->
-  
-  <target name="four-pack.start" depends="four.done"/>
-
-  <target name="four-pack.lib" depends="four-pack.start">
-    <mkdir dir="${build-four-pack.dir}/lib"/>
-    <jar destfile="${build-four-pack.dir}/lib/scala-library.jar">
-      <fileset dir="${build-four.dir}/classes/library">
-        <exclude name="scala/dbc/**"/>
-        <exclude name="scala/swing/**"/>
-      </fileset>
-    </jar>
-    <jar destfile="${build-four-pack.dir}/lib/scala-dbc.jar">
-      <fileset dir="${build-four.dir}/classes/library">
-        <include name="scala/dbc/**"/>
-      </fileset>
-    </jar>
-    <jar destfile="${build-four-pack.dir}/lib/scala-swing.jar">
-      <fileset dir="${build-four.dir}/classes/library">
-        <include name="scala/swing/**"/>
-      </fileset>
-    </jar>
-  </target>
-
-  <target name="four-pack.comp" depends="four-pack.lib">
-    <mkdir dir="${build-four-pack.dir}/lib"/>
-    <jar destfile="${build-four-pack.dir}/lib/scala-compiler.jar">
-      <fileset dir="${build-four.dir}/classes/compiler"/>
-      <zipfileset src="${fjbg.jar}"/>
-      <zipfileset src="${msil.jar}"/>
-    </jar>
-  </target>
-
-  <target name="four-pack.partest" depends="four-pack.comp">
-    <mkdir dir="${build-four-pack.dir}/lib"/>
-    <jar destfile="${build-four-pack.dir}/lib/scala-partest.jar">
-      <fileset dir="${build-four.dir}/classes/partest"/>
-    </jar>
-  </target>
-
-  <target name="four-pack.bin" depends="four-pack.partest">
-    <taskdef name="four-pack-bin" classname="scala.tools.ant.ScalaTool">
-      <classpath>
-      	<pathelement location="${build-four-pack.dir}/lib/scala-library.jar"/>
-      	<pathelement location="${build-four-pack.dir}/lib/scala-compiler.jar"/>
-      </classpath>
-    </taskdef>
-    <mkdir dir="${build-four-pack.dir}/bin"/>
-    <four-pack-bin
-      file="${build-four-pack.dir}/bin/scala"
-      class="scala.tools.nsc.MainGenericRunner"
-      javaFlags="${java.flags}"/>
-    <four-pack-bin
-      file="${build-four-pack.dir}/bin/scalac"
-      class="scala.tools.nsc.Main"
-      javaFlags="${java.flags}"/>
-    <four-pack-bin
-      file="${build-four-pack.dir}/bin/scaladoc"
-      class="scala.tools.nsc.ScalaDoc"
-      javaFlags="${java.flags}"/>
-    <four-pack-bin
-      file="${build-four-pack.dir}/bin/fsc"
-      class="scala.tools.nsc.CompileClient"
-      javaFlags="${java.flags}"/>
-    <chmod perm="ugo+rx" file="${build-four-pack.dir}/bin/scala"/>
-    <chmod perm="ugo+rx" file="${build-four-pack.dir}/bin/scalac"/>
-    <chmod perm="ugo+rx" file="${build-four-pack.dir}/bin/scaladoc"/>
-    <chmod perm="ugo+rx" file="${build-four-pack.dir}/bin/fsc"/>
-  </target>
-  
-  <target name="four-pack.done" depends="four-pack.bin"/>
-
-  <target name="four-pack.clean">
-    <delete dir="${build-four-pack.dir}" includeemptydirs="yes" quiet="yes" failonerror="no"/>
-  </target>
-
-<!-- ===========================================================================
-DOCUMENTATION
-============================================================================ -->
-  
-  <target name="four-docs.start" depends="four-pack.done"/>
-
-  <target name="four-docs.lib" depends="four-docs.start">
-    <stopwatch name="four-docs.lib.timer"/>
-    <mkdir dir="${build-four-docs.dir}/library"/>
-    <scaladoc
-      destdir="${build-four-docs.dir}/library"
-      windowtitle="Scala Library for JVM 1.4"
-      doctitle="Scala ${version.number} API"
-      classpathref="pack.classpath">
-      <src>
-        <files includes="${src.dir}/dbc"/>
-        <files includes="${src.dir}/swing"/>
-        <files includes="${build-four-src.dir}-actors"/>
-        <files includes="${build-four-src.dir}"/>
-      </src>
-      <include name="**/*.scala"/>
-    </scaladoc>
-    <stopwatch name="four-docs.lib.timer" action="total"/>
-  </target>
-  
-  <target name="four-docs.done" depends="four-docs.lib"/>
-
-  <target name="four-docs.clean">
-    <delete dir="${build-four-docs.dir}" includeemptydirs="yes" quiet="yes" failonerror="no"/>
-  </target>
-  
-<!-- ===========================================================================
-TEST SUITE WHEN RUN ON JVM 1.5
-================================================================================
-This tests how a compiler, library and tests that where targeted for JVM 1.4
-work on a JVM 1.5.
-============================================================================ -->
-
-  <target name="four-test.suite" depends="four-pack.done">
-    <partest showlog="yes" erroronfailed="yes" scalacopts="-target:jvm-1.4"
-	     javacmd="${java.home}/bin/java -Xmx1024M" javaccmd="${javac.cmd}">
-      <classpath>
-        <pathelement location="${build-four-pack.dir}/lib/scala-library.jar"/>
-        <pathelement location="${build-four-pack.dir}/lib/scala-compiler.jar"/>
-        <fileset dir="${test.dir}/files/lib" includes="*.jar"/>
-      </classpath>
-      <postests dir="${test.dir}/files/pos" includes="*.scala"/>
-      <negtests dir="${test.dir}/files/neg" includes="*.scala"/>
-      <runtests dir="${test.dir}/files">
-        <include name="run/**/*.scala"/>
-      </runtests>
-      <jvmtests dir="${test.dir}/files/jvm" includes="*.scala"/>
-      <residenttests dir="${test.dir}/files/res" includes="*.res"/>
-    </partest>
-  </target>
-  
-  <target name="four-test.done" depends="four-test.suite"/>
-  
-<!-- ===========================================================================
-TEST SUITE WHEN RUN ON JVM 1.4 (standalone)
-================================================================================
-This tests how a compiler, library and tests that where targeted for JVM 1.4
-work on a JVM 1.4.
-============================================================================ -->
-  
-  <target name="fourfour-test.start">
-    <echo level="info" message="Java version is ${java.vm.name} ${java.version}"/>
-    <path id="four-pack.classpath">
-      <pathelement location="${build-four-pack.dir}/lib/scala-library.jar"/>
-      <pathelement location="${build-four-pack.dir}/lib/scala-compiler.jar"/>
-      <pathelement location="${build-four-pack.dir}/lib/scala-partest.jar"/>
-      <pathelement location="${ant.jar}"/>
-    </path>
-    <taskdef resource="scala/tools/partest/antlib.xml" classpathref="four-pack.classpath"/>
-  </target>
-
-  <target name="fourfour-test.suite" depends="fourfour-test.start">
-    <partest showlog="yes" erroronfailed="yes" scalacopts="-target:jvm-1.4"
-	     javacmd="${java.home}/bin/java -Xmx1024M" javaccmd="${javac.cmd}">
-      <classpath>
-        <pathelement location="${build-four-pack.dir}/lib/scala-library.jar"/>
-        <pathelement location="${build-four-pack.dir}/lib/scala-compiler.jar"/>
-        <fileset dir="${test.dir}/files/lib" includes="*.jar"/>
-      </classpath>
-      <postests dir="${test.dir}/files/pos" includes="*.scala"/>
-      <negtests dir="${test.dir}/files/neg" includes="*.scala"/>
-      <runtests dir="${test.dir}/files">
-        <include name="run/**/*.scala"/>
-      </runtests>
-      <jvmtests dir="${test.dir}/files/jvm" includes="*.scala"/>
-      <residenttests dir="${test.dir}/files/res" includes="*.res"/>
-    </partest>
-  </target>
-  
-  <target name="fourfour-test.done" depends="fourfour-test.suite"/>
-
-<!-- ===========================================================================
-DISTRIBUTION
-============================================================================ -->
-  
-  <target name="four-dist.start" depends="four-pack.done, four-docs.done">
-    <property name="four-dist.dir" value="${dists.dir}/scala-jvm4-${version.number}"/>
-  </target>
-    
-  <target name="four-dist.base" depends="four-dist.start">
-    <mkdir dir="${four-dist.dir}/lib"/>
-    <copy toDir="${four-dist.dir}/lib">
-      <fileset dir="${build-four-pack.dir}/lib"/>
-    </copy>
-    <mkdir dir="${four-dist.dir}/bin"/>
-    <copy toDir="${four-dist.dir}/bin">
-      <fileset dir="${build-four-pack.dir}/bin"/>
-    </copy>
-    <chmod perm="ugo+rx" file="${four-dist.dir}/bin/scala"/>
-    <chmod perm="ugo+rx" file="${four-dist.dir}/bin/scalac"/>
-    <chmod perm="ugo+rx" file="${four-dist.dir}/bin/scaladoc"/>
-    <chmod perm="ugo+rx" file="${four-dist.dir}/bin/fsc"/>
-  </target>
-    
-  <target name="four-dist.doc" depends="four-dist.base">
-    <mkdir dir="${four-dist.dir}/doc/api"/>
-    <copy toDir="${four-dist.dir}/doc/api">
-      <fileset dir="${build-four-docs.dir}/library"/>
-    </copy>
-  </target>
-    
-  <target name="four-dist.src" depends="four-dist.doc">
-    <mkdir dir="${four-dist.dir}/src"/>
-    <jar destfile="${four-dist.dir}/src/scala-library-src.jar">
-      <fileset dir="${build-four-src.dir}"/>
-      <fileset dir="${build-four-src.dir}-actors"/>
-    </jar>
-    <jar destfile="${four-dist.dir}/src/scala-dbc-src.jar">
-      <fileset dir="${src.dir}/dbc"/>
-    </jar>
-    <jar destfile="${four-dist.dir}/src/scala-swing-src.jar">
-      <fileset dir="${src.dir}/swing"/>
-    </jar>
-    <jar destfile="${four-dist.dir}/src/scala-compiler-src.jar">
-      <fileset dir="${src.dir}/compiler"/>
-    </jar>
-  </target>
-  
-  <target name="four-dist.latest" depends="four-dist.src" unless="os.win">
-    <symlink link="${dists.dir}/latest-jvm4" resource="${four-dist.dir}" overwrite="yes"/>
-  </target>
-  
-  <target name="four-dist.done" depends="four-dist.latest"/>
-
-<!-- ===========================================================================
-TEST AND DISTRIBUTION BUNDLE (ALL)
-============================================================================ -->
-  
-  <target name="four-all.done" depends="four-dist.done, four-test.done"/>
-  
-  <target name="four-all.clean" depends="four-docs.clean, four.clean"/>
-
-<!-- ===========================================================================
-MISCELLANEOUS
-============================================================================ -->
-  
-  <target name="graph.init">
-    <echo message="${basedir}/lib/ant/vizant.jar"/>
-    <taskdef name="vizant" classname="vizant.Vizant" classpath="${basedir}/../../lib/ant/vizant.jar"/>
-  </target>
-  
-  <target name="graph.four" depends="graph.init">
-    <vizant antfile="${ant.file}" outfile="${ant.project.name}.dot"/>
-  </target>
-  
-</project>
diff --git a/src/build/genprod.scala b/src/build/genprod.scala
index 1eab9e7..305b0ef 100644
--- a/src/build/genprod.scala
+++ b/src/build/genprod.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: genprod.scala 16881 2009-01-09 16:28:11Z cunei $
 
 /** <p>
  *   This program generates the <code>ProductN</code>, <code>TupleN</code> <code>FunctionN</code> classes, where
@@ -17,85 +16,81 @@
  *    where <code>PATH</code> is the desired output directory
  *  </p>
  *
- *  @author  Burak Emir, Stephane Micheloud, Geoffrey Washburn
+ *  @author  Burak Emir, Stephane Micheloud, Geoffrey Washburn, Paul Phillips
  *  @version 1.1
  */
 object genprod {
-
-  /** The biggest ?? has Sup?? - 1 components/arguments */
-  val SUP_PRODUCT_ARITY  = 23
-  val SUP_TUPLE_ARITY    = 23
-  val SUP_FUNCTION_ARITY = 23
-
-  def productClassname(i: Int) = "Product"+i
-  def productFilename(i: Int) = productClassname(i)+".scala"
-
-  def tupleClassname(i: Int) = "Tuple"+i
-  def tupleFilename(i: Int) = tupleClassname(i)+".scala"
-
-  def functionClassname(i: Int) = "Function"+i
-  def functionFilename(i: Int) = functionClassname(i)+".scala"
-
-  def join(sep: String, xs: Seq[String]): String = 
-      if (xs.length == 0) "" 
-      else xs.drop(1).foldLeft(xs.first) { (acc, x) => acc + sep + x }
-      
-        
-  def targs(i: Int) =
-    for (j <- List.range(1, i+1)) yield "T" + j
-
-  def covariantArgs(i: Int) =
-    for (t <- targs(i)) yield "+" + t
-
-  def contraCoArgs(i: Int) =
-    (for (t <- targs(i)) yield  "-" + t) ::: List("+R")
-
-  def vdefs(i: Int) =
-    for (j <- List.range(1, i+1)) yield "v" + j
-
-  def mdefs(i: Int) =
-    for (j <- List.range(1, i+1)) yield "_" + j
-
-  def zippedAndCommaSeparated(left: List[String], right: List[String]): String = {
-    val sb = new StringBuilder
-    val it = (left zip right).elements
-    def append1 = {
-      val p = it.next
-      sb.append(p._1).append(':').append(p._2)
-    }
-    if (it.hasNext) {
-      append1
-      while(it.hasNext) { sb.append(", "); append1 }
-    }
-    sb.toString
+  val MAX_ARITY = 22
+  def arities = (1 to MAX_ARITY).toList
+  
+  class Group(val name: String) {
+    def className(i: Int) = name + i
+    def fileName(i: Int) = className(i) + ".scala"
   }
 
-  def fields(i: Int) = zippedAndCommaSeparated(mdefs(i), targs(i))
-
-  def funArgs(i: Int) = zippedAndCommaSeparated(vdefs(i), targs(i))
-
-  def productFiles =
-    for (i <- List.range(1, SUP_PRODUCT_ARITY)) yield ProductFile.make(i)
+  def productFiles  = arities map Product.make
+  def tupleFiles    = arities map Tuple.make
+  def functionFiles = (0 :: arities) map Function.make
+  def absFunctionFiles = (0 :: arities) map AbstractFunction.make
+  def allfiles      = productFiles ::: tupleFiles ::: functionFiles ::: absFunctionFiles
+
+  trait Arity extends Group {
+    def i: Int    // arity
+    
+    def typeArgsString(xs: Seq[String]) = xs.mkString("[", ", ", "]")
+    
+    def to              = (1 to i).toList
+    def s               = if (i == 1) "" else "s"
+    def className       = name + i
+    def fileName        = className + ".scala"
+    def targs           = to map ("T" + _)
+    def vdefs           = to map ("v" + _)
+    def xdefs           = to map ("x" + _)
+    def mdefs           = to map ("_" + _)
+    def invariantArgs   = typeArgsString(targs)
+    def covariantArgs   = typeArgsString(targs map (covariantSpecs + "+" + _))
+    def covariantSpecs  = ""
+    def contravariantSpecs = ""
+    def contraCoArgs    = typeArgsString((targs map (contravariantSpecs + "-" + _)) ::: List(covariantSpecs + "+R"))
+    def fields          = List.map2(mdefs, targs)(_ + ":" + _) mkString ","
+    def funArgs         = List.map2(vdefs, targs)(_ + ":" + _) mkString ","
+
+    def genprodString       = "// generated by genprod on %s %s %s".format(now, withFancy, withMoreMethods)
+    def now                 = new java.util.Date().toString()
+    def moreMethods         = ""
+    def descriptiveComment  = ""
+    def withFancy           = if (descriptiveComment.isEmpty) "" else "(with fancy comment)"
+    def withMoreMethods     = if (moreMethods.isEmpty) "" else "(with extra methods)"
+    def packageDef          = "scala"
+    def imports             = ""
+    
+    def header = """
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
 
-  def tupleFiles =
-    for (i <- List.range(1, SUP_TUPLE_ARITY)) yield TupleFile.make(i)
 
-  def functionFiles =
-    for (i <- List.range(0, SUP_FUNCTION_ARITY)) yield FunctionFile.make(i)
+%s
 
-  def allfiles =
-    productFiles ::: tupleFiles ::: functionFiles
+package %s
+%s
+""".trim.format(genprodString, packageDef, imports) + "\n\n"
+  }
 
   def main(args: Array[String]) {
     if (args.length != 1) {
       println("please give path of output directory")
       exit(-1)
     }
-    import java.io.{File, FileOutputStream}
-    import java.nio.channels.Channels
     val out = args(0)
-    for (node <- allfiles) {
-      val f = new File(out + File.separator + node.attributes("name"))
+    def writeFile(node: scala.xml.Node) {
+      import java.io.{File, FileOutputStream}
+      import java.nio.channels.Channels
+      val f = new File(out, node.attributes("name").toString)
       try {
         f.createNewFile
         val fos = new FileOutputStream(f)
@@ -105,84 +100,25 @@ object genprod {
         w.close
       } catch {
         case e: java.io.IOException =>
-          println(e.getMessage() + ": " + out)
+          println(e.getMessage() + ": " + f)
           exit(-1)
       }
     }
+    
+    allfiles foreach writeFile
   }
 }
+import genprod._
+
 
 /* zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz
                              F U N C T I O N
 zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz */
 
-object FunctionFile {
-  import genprod._
-  def make(i: Int) = {
-    val __typeArgs__ = contraCoArgs(i).mkString("[",", ","]")
-    val __funArgs__ = funArgs(i)
-<file name={functionFilename(i)}>
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// {"$Id: genprod.scala 16881 2009-01-09 16:28:11Z cunei $"}
-
-// generated by genprod on {new java.util.Date().toString()} {if(descriptiveComment(i).length > 0) "(with fancy comment)" else ""} {if(moreMethods(i).length > 0) "(with extra methods)" else ""}
-
-package scala
-
-
-/** <p>
- *    Function with {i} parameters.
- *  </p>
- *  {descriptiveComment(i)}
- */
-trait {functionClassname(i)}{__typeArgs__} extends AnyRef {{ self =>
-  def apply({__funArgs__}): R
-  override def toString() = "<function>"
-  {moreMethods(i)}
-}}
-</file>
-}
-
-  def moreMethods(i:Int) = i match {
-    case 1 => """
-  /** (f compose g)(x) ==  f(g(x))
-   */
-  def compose[A](g: A => T1): A => R = { x => apply(g(x)) }
-  
-  /** (f andThen g)(x) ==  g(f(x))
-   */
-  def andThen[A](g: R => A): T1 => A = { x => g(apply(x)) }
-"""
-    case _ if (i > 1) => """
-  /** f(""" + join(",", (1 to i).map(i => "x" + i)) + """)  == (f.curry)""" +  join("", (1 to i).map(i => "(x" + i + ")")) + """
-   */
-  def curry: """ + join(" => ", (1 to i).map(i => "T" + i)) + """ => R = { 
-""" +
-  (if (i < 5) {
-    "      " + join(" => ", (1 to i).map(i => "(x" + i + ": T" + i + ")")) + """ => apply(""" + join(",", (1 to i).map(i => "x" + i)) + ")\n  }"
-  } else {
-    """      (x1: T1) => ((""" + join(", ", (2 to i).map(i => "x" + i + ": T" + i)) + """) => self.apply(""" + join(",", (1 to i).map(i => "x" + i)) + ")).curry\n  }"
-  })
-    case _ => """
-"""
-
-  }
-  def descriptiveComment(i: Int) = i match {
-    case 0 => """<p>
-      In the following example the definition of
- *    <code>currentSeconds</code> is a shorthand for the anonymous class
- *    definition <code>anonfun0</code>:
- *  </p>
- *  <pre>
- *  <b>object</b> Main <b>extends</b> Application {
- *
+object FunctionZero extends Function(0) {
+  override def covariantSpecs = "@specialized "
+  override def descriptiveComment = functionNTemplate.format("currentSeconds", "anonfun0",
+""" *
  *    <b>val</b> currentSeconds = () => System.currentTimeMillis() / 1000L
  *
  *    <b>val</b> anonfun0 = <b>new</b> Function0[Long] {
@@ -190,16 +126,16 @@ trait {functionClassname(i)}{__typeArgs__} extends AnyRef {{ self =>
  *    }
  *
  *    println(currentSeconds())
- *    println(anonfun0())
- *  }</pre>"""
-    case 1 => """<p>
-      In the following example the definition of
- *    <code>succ</code> is a shorthand for the anonymous class definition
- *    <code>anonfun1</code>:
- *  </p>
- *  <pre>
- *  <b>object</b> Main <b>extends</b> Application {
- *
+ *    println(anonfun0())""")
+  override def moreMethods = ""
+}
+
+object FunctionOne extends Function(1) {
+  override def contravariantSpecs = "@specialized(scala.Int, scala.Long, scala.Float, scala.Double) "
+  override def covariantSpecs = "@specialized(scala.Unit, scala.Boolean, scala.Int, scala.Float, scala.Long, scala.Double) "
+
+  override def descriptiveComment = functionNTemplate.format("succ", "anonfun1",
+""" *
  *    <b>val</b> succ = (x: Int) => x + 1
  *
  *    <b>val</b> anonfun1 = <b>new</b> Function1[Int, Int] {
@@ -207,16 +143,25 @@ trait {functionClassname(i)}{__typeArgs__} extends AnyRef {{ self =>
  *    }
  *
  *    println(succ(0))
- *    println(anonfun1(0))
- *  }</pre>"""
-    case 2 => """<p>
-      In the following example the definition of
- *    <code>max</code> is a shorthand for the anonymous class definition
- *    <code>anonfun2</code>:
- *  </p>
- *  <pre>
- *  <b>object</b> Main <b>extends</b> Application {
- *
+ *    println(anonfun1(0))""")
+
+  override def moreMethods = """
+  /** (f compose g)(x) ==  f(g(x))
+   */
+  def compose[A](g: A => T1): A => R = { x => apply(g(x)) }
+
+  /** (f andThen g)(x) ==  g(f(x))
+   */
+  def andThen[A](g: R => A): T1 => A = { x => g(apply(x)) }
+"""  
+}
+
+object FunctionTwo extends Function(2) {
+  override def contravariantSpecs = "@specialized(scala.Int, scala.Long, scala.Double) "
+  override def covariantSpecs = "@specialized(scala.Unit, scala.Boolean, scala.Int, scala.Float, scala.Long, scala.Double) "
+
+  override def descriptiveComment = functionNTemplate.format("max", "anonfun2",
+""" *
  *    <b>val</b> max = (x: Int, y: Int) => <b>if</b> (x < y) y <b>else</b> x
  *
  *    <b>val</b> anonfun2 = <b>new</b> Function2[Int, Int, Int] {
@@ -224,107 +169,422 @@ trait {functionClassname(i)}{__typeArgs__} extends AnyRef {{ self =>
  *    }
  *
  *    println(max(0, 1))
- *    println(anonfun2(0, 1))
+ *    println(anonfun2(0, 1))""")  
+}
+
+object Function
+{
+  def make(i: Int) = apply(i)()
+  def apply(i: Int) = i match {
+    case 0    => FunctionZero
+    case 1    => FunctionOne
+    case 2    => FunctionTwo
+    case _    => new Function(i)
+  }
+}
+
+class Function(val i: Int) extends Group("Function") with Arity
+{
+  val functionNTemplate = """<p>
+ * In the following example the definition of
+ *    <code>%s</code> is a shorthand for the anonymous class
+ *    definition <code>%s</code>:
+ *  </p>
+ *  <pre>
+ *  <b>object</b> Main <b>extends</b> Application {
+%s
  *  }</pre>"""
-    case _ => ""
+  
+  def toStr() = "\"" + ("<function%d>" format i) + "\""
+  def apply() = {
+<file name={fileName}>{header}
+
+/** <p>
+ *    Function with {i} parameter{s}.
+ *  </p>
+ *  {descriptiveComment}
+ */
+trait {className}{contraCoArgs} extends AnyRef {{ self =>
+  def apply({funArgs}): R
+  override def toString() = {toStr}
+  {moreMethods}
+}}
+</file>
+}
+
+  private def commaXs = xdefs.mkString("(", ", ", ")")
+
+  // (x1: T1) => (x2: T2) => (x3: T3) => (x4: T4) => apply(x1,x2,x3,x4)
+  def shortCurry = {
+    val body = "apply" + commaXs
+    List.map2(xdefs, targs)("(%s: %s) => ".format(_, _)).mkString("", "", body)
+  }
+    
+  // (x1: T1) => ((x2: T2, x3: T3, x4: T4, x5: T5, x6: T6, x7: T7) => self.apply(x1,x2,x3,x4,x5,x6,x7)).curried
+  def longCurry = (List.map2(xdefs, targs)(_ + ": " + _) drop 1).mkString(
+    "(x1: T1) => ((",
+    ", ",
+    ") => self.apply%s).curried".format(commaXs)
+  )
+  
+  // f(x1,x2,x3,x4,x5,x6)  == (f.curried)(x1)(x2)(x3)(x4)(x5)(x6)
+  def curryComment = { """
+  /** f%s  == (f.curried)%s
+   */
+""".format(commaXs, xdefs map ("(" + _ + ")") mkString)
+  }
+  
+  def tupleMethod = {
+    def comment = """
+  /* f%s == (f.tupled)(Tuple%d%s)
+   */
+""".format(commaXs, i, commaXs)
+    def body = "case Tuple%d%s => apply%s".format(i, commaXs, commaXs)
+    
+    comment + "  def tupled: Tuple%d%s => R = {\n    %s\n  }\n".format(i, invariantArgs, body) 
+  }
+  
+  def curryMethod = {
+    val body = if (i < 5) shortCurry else longCurry
+    
+    curryComment +
+    "  def curried: %s => R = {\n    %s\n  }\n".format(
+      targs mkString " => ", body
+    ) + """  @deprecated("Use 'curried' instead")""" + "\n  def curry = curried\n"
   }
 
-} // object FunctionFile
+  override def moreMethods = curryMethod + tupleMethod
+} // object Function
+
+
 /* zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz 
                                      T U P L E
 zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz */
 
-object TupleFile {
-  import genprod._
-  def make(i: Int) = {
-    val __typeArgs__    = covariantArgs(i).mkString("[",", ","]")
-    val __typeArgRefs__ = targs(i).mkString("[",", ","]")
-    val __fields__ = fields(i)
-<file name={tupleFilename(i)}>
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// {"$Id: genprod.scala 16881 2009-01-09 16:28:11Z cunei $"}
-
-// generated by genprod on {new java.util.Date().toString()} {if(descriptiveComment(i).length > 0) "(with fancy comment)" else ""} {if(moreMethods(i).length > 0) "(with extra methods)" else ""}
+object Tuple
+{
+  def make(i: Int) = apply(i)()
+  def apply(i: Int) = i match {
+    case 1  => TupleOne
+    case 2  => TupleTwo
+    case 3  => TupleThree
+    case _  => new Tuple(i)
+  }
+}
 
-package scala
+object TupleOne extends Tuple(1)
+{
+  override def covariantSpecs = "@specialized(Int, Long, Double) "
+}
 
-/** {tupleClassname(i)} is the canonical representation of a @see {productClassname(i)} 
- *  {descriptiveComment(i)}
- */
-case class {tupleClassname(i)}{__typeArgs__}({ __fields__ }) 
-  extends {productClassname(i)}{__typeArgRefs__}  {{
-
-   override def toString() = {{
-     val sb = new StringBuilder
-     { if ({i} == 1)
-         "sb.append('(').append(_" + {i} + ").append(\",)\")"
-       else {
-         val xs = (1 to i).map(i => ".append(_" + i + ")")
-         xs.mkString("sb.append('(')", ".append(',')",".append(')')")
-       }
-     }
-     sb.toString
-   }}
-  {moreMethods(i)}
-}}
-</file>}
-  def moreMethods(i:Int) = i match {
-    case 2 => """
+object TupleTwo extends Tuple(2)
+{
+  override def imports = """
+import scala.collection.{TraversableLike, IterableLike}
+import scala.collection.generic.CanBuildFrom
+"""
+  override def covariantSpecs = "@specialized(Int, Long, Double) "
+  override def moreMethods = """
   /** Swap the elements of the tuple */
   def swap: Tuple2[T2,T1] = Tuple2(_2, _1)
+
+  def zip[Repr1, El1, El2, To](implicit w1:   T1 => TraversableLike[El1, Repr1],
+                                        w2:   T2 => Iterable[El2],
+                                        cbf1: CanBuildFrom[Repr1, (El1, El2), To]): To = {
+    val coll1: TraversableLike[El1, Repr1] = _1
+    val coll2: Iterable[El2] = _2
+    val b1 = cbf1(coll1.repr)
+    val elems2 = coll2.iterator
+
+    for(el1 <- coll1)
+      if(elems2.hasNext)
+        b1 += ((el1, elems2.next))
+
+    b1.result
+  }
+
+  /** Wraps a tuple in a `Zipped`, which supports 2-ary generalisations of map, flatMap, filter,...
+   *
+   * @see Zipped
+   * $willNotTerminateInf
+   */
+  def zipped[Repr1, El1, Repr2, El2](implicit w1: T1 => TraversableLike[El1, Repr1], w2: T2 => IterableLike[El2, Repr2]): Zipped[Repr1, El1, Repr2, El2]
+    = new Zipped[Repr1, El1, Repr2, El2](_1, _2)
+
+  class Zipped[+Repr1, +El1, +Repr2, +El2](coll1: TraversableLike[El1, Repr1], coll2: IterableLike[El2, Repr2]) { // coll2: IterableLike for filter
+    def map[B, To](f: (El1, El2) => B)(implicit cbf: CanBuildFrom[Repr1, B, To]): To = {
+      val b = cbf(coll1.repr)
+      val elems2 = coll2.iterator
+
+      for(el1 <- coll1)
+       if(elems2.hasNext)
+         b += f(el1, elems2.next)
+
+      b.result
+    }
+
+    def flatMap[B, To](f: (El1, El2) => Traversable[B])(implicit cbf: CanBuildFrom[Repr1, B, To]): To = {
+      val b = cbf(coll1.repr)
+      val elems2 = coll2.iterator
+
+      for(el1 <- coll1)
+       if(elems2.hasNext)
+         b ++= f(el1, elems2.next)
+
+      b.result
+    }
+
+    def filter[To1, To2](f: (El1, El2) => Boolean)(implicit cbf1: CanBuildFrom[Repr1, El1, To1], cbf2: CanBuildFrom[Repr2, El2, To2]): (To1, To2) = {
+      val b1 = cbf1(coll1.repr)
+      val b2 = cbf2(coll2.repr)
+      val elems2 = coll2.iterator
+
+      for(el1 <- coll1) {
+        if(elems2.hasNext) {
+          val el2 = elems2.next
+          if(f(el1, el2)) {
+            b1 += el1
+            b2 += el2
+          }
+        }
+      }
+
+      (b1.result, b2.result)
+    }
+
+    def exists(f: (El1, El2) => Boolean): Boolean = {
+      var acc = false
+      val elems2 = coll2.iterator
+
+      for(el1 <- coll1)
+       if(!acc && elems2.hasNext)
+         acc = f(el1, elems2.next)
+
+      acc
+    }
+
+    def forall(f: (El1, El2) => Boolean): Boolean = {
+      var acc = true
+      val elems2 = coll2.iterator
+
+      for(el1 <- coll1)
+       if(acc && elems2.hasNext)
+         acc = f(el1, elems2.next)
+
+      acc
+    }
+
+    def foreach[U](f: (El1, El2) => U): Unit = {
+      val elems2 = coll2.iterator
+
+      for(el1 <- coll1)
+       if(elems2.hasNext)
+         f(el1, elems2.next)
+    }
+  }
+"""  
+}
+
+object TupleThree extends Tuple(3) {
+  override def imports = """
+import scala.collection.{TraversableLike, IterableLike}
+import scala.collection.generic.CanBuildFrom
 """
-    case _ => ""
+  override def moreMethods = """
+  def zip[Repr1, El1, El2, El3, To](implicit w1:   T1 => TraversableLike[El1, Repr1],
+                                             w2:   T2 => Iterable[El2],
+                                             w3:   T3 => Iterable[El3],
+                                             cbf1: CanBuildFrom[Repr1, (El1, El2, El3), To]): To = {
+    val coll1: TraversableLike[El1, Repr1] = _1
+    val coll2: Iterable[El2] = _2
+    val coll3: Iterable[El3] = _3
+    val b1 = cbf1(coll1.repr)
+    val elems2 = coll2.iterator
+    val elems3 = coll3.iterator
+
+    for(el1 <- coll1)
+      if(elems2.hasNext && elems3.hasNext)
+        b1 += ((el1, elems2.next, elems3.next))
+
+    b1.result
+  }
+
+  /** Wraps a tuple in a `Zipped`, which supports 3-ary generalisations of map, flatMap, filter,...
+   *
+   * @see Zipped
+   * $willNotTerminateInf
+   */
+  def zipped[Repr1, El1, Repr2, El2, Repr3, El3](implicit w1: T1 => TraversableLike[El1, Repr1],
+                                                          w2: T2 => IterableLike[El2, Repr2],
+                                                          w3: T3 => IterableLike[El3, Repr3]): Zipped[Repr1, El1, Repr2, El2, Repr3, El3]
+    = new Zipped[Repr1, El1, Repr2, El2, Repr3, El3](_1, _2, _3)
+
+  class Zipped[+Repr1, +El1, +Repr2, +El2, +Repr3, +El3](coll1: TraversableLike[El1, Repr1],
+                                                         coll2: IterableLike[El2, Repr2],
+                                                         coll3: IterableLike[El3, Repr3]) {
+    def map[B, To](f: (El1, El2, El3) => B)(implicit cbf: CanBuildFrom[Repr1, B, To]): To = {
+     val b = cbf(coll1.repr)
+     val elems2 = coll2.iterator
+     val elems3 = coll3.iterator
+
+     for(el1 <- coll1)
+       if(elems2.hasNext && elems3.hasNext)
+         b += f(el1, elems2.next, elems3.next)
+
+     b.result
+    }
+
+    def flatMap[B, To](f: (El1, El2, El3) => Traversable[B])(implicit cbf: CanBuildFrom[Repr1, B, To]): To = {
+      val b = cbf(coll1.repr)
+      val elems2 = coll2.iterator
+      val elems3 = coll3.iterator
+
+      for(el1 <- coll1)
+       if(elems2.hasNext && elems3.hasNext)
+         b ++= f(el1, elems2.next, elems3.next)
+
+      b.result
+    }
+
+    def filter[To1, To2, To3](f: (El1, El2, El3) => Boolean)(
+                 implicit cbf1: CanBuildFrom[Repr1, El1, To1],
+                          cbf2: CanBuildFrom[Repr2, El2, To2],
+                          cbf3: CanBuildFrom[Repr3, El3, To3]): (To1, To2, To3) = {
+      val b1 = cbf1(coll1.repr)
+      val b2 = cbf2(coll2.repr)
+      val b3 = cbf3(coll3.repr)
+      val elems2 = coll2.iterator
+      val elems3 = coll3.iterator
+
+      for(el1 <- coll1) {
+        if(elems2.hasNext && elems3.hasNext) {
+          val el2 = elems2.next
+          val el3 = elems3.next
+          if(f(el1, el2, el3)) {
+            b1 += el1
+            b2 += el2
+            b3 += el3
+          }
+        }
+      }
+
+      (b1.result, b2.result, b3.result)
+    }
+
+    def exists(f: (El1, El2, El3) => Boolean): Boolean = {
+      var acc = false
+      val elems2 = coll2.iterator
+      val elems3 = coll3.iterator
+
+      for(el1 <- coll1)
+       if(!acc && elems2.hasNext && elems3.hasNext)
+         acc = f(el1, elems2.next, elems3.next)
+
+      acc
+    }
+
+    def forall(f: (El1, El2, El3) => Boolean): Boolean = {
+      var acc = true
+      val elems2 = coll2.iterator
+      val elems3 = coll3.iterator
+
+      for(el1 <- coll1)
+       if(acc && elems2.hasNext && elems3.hasNext)
+         acc = f(el1, elems2.next, elems3.next)
+
+      acc
+    }
+
+    def foreach[U](f: (El1, El2, El3) => U): Unit = {
+      val elems2 = coll2.iterator
+      val elems3 = coll3.iterator
+
+      for(el1 <- coll1)
+       if(elems2.hasNext && elems3.hasNext)
+         f(el1, elems2.next, elems3.next)
+    }
   }
-  def descriptiveComment(i: Int) = i match {
-    case _ => ""
+"""
+}
+
+class Tuple(val i: Int) extends Group("Tuple") with Arity
+{
+  // prettifies it a little if it's overlong
+  def mkToString() = {
+  def str(xs: List[String]) = xs.mkString(""" + "," + """)
+    if (i <= MAX_ARITY / 2) str(mdefs)
+    else {
+      val s1 = str(mdefs take (i / 2))
+      val s2 = str(mdefs drop (i / 2))
+      s1 + " +\n    \",\" + " + s2
+    }
   }
-} // object TupleFile
+    
+  def apply() = {    
+<file name={fileName}>{header}
 
+/** {className} is the canonical representation of a @see {Product.className(i)} 
+ *  {descriptiveComment}
+ */
+case class {className}{covariantArgs}({fields})
+  extends {Product.className(i)}{invariantArgs}
+{{  
+  override def toString() = "(" + {mkToString} + ")"  
+  {moreMethods}
+}}
+</file>}
+} // object Tuple
 
 
 /* zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz
                                   P R O D U C T
 zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz */
 
-object ProductFile {
-  import genprod._
-  def make(i:Int) = {
-    val __typeArgs__ = if (i==0) Nil else covariantArgs(i).mkString("[",", ","]")
-    val __refArgs__ = if (i==0) Nil else targs(i).mkString("[",", ","]")
-<file name={productFilename(i)}>
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// {"$Id: genprod.scala 16881 2009-01-09 16:28:11Z cunei $"}
-
-// generated by genprod on {new java.util.Date().toString()} {if(descriptiveComment(i).length > 0) "(with fancy comment)" else ""} {if(moreMethods(i).length > 0) "(with extra methods)" else ""}
+object Product extends Group("Product")
+{
+  def make(i: Int) = apply(i)()
+  def apply(i: Int) = i match {
+    case 1  => ProductOne
+    case 2  => ProductTwo
+    case _ => new Product(i)
+  } 
+}
 
-package scala
+object ProductOne extends Product(1)
+{
+  override def covariantSpecs = "@specialized(Int, Long, Double) "
+}
 
-import Predef._
+object ProductTwo extends Product(2)
+{
+  override def covariantSpecs = "@specialized(Int, Long, Double) "
+}
 
-object {productClassname(i)} {{
-  def unapply{__refArgs__}(x: {productClassname(i)}{__refArgs__}): Option[{productClassname(i)}{__refArgs__}] = 
+class Product(val i: Int) extends Group("Product") with Arity
+{
+  def cases = {
+    val xs = for ((x, i) <- mdefs.zipWithIndex) yield "case %d => %s".format(i, x)
+    val default = "case _ => throw new IndexOutOfBoundsException(n.toString())"
+    "\n" + ((xs ::: List(default)) map ("    " + _ + "\n") mkString)
+  }
+  def proj = {
+    List.map2(mdefs, targs)(
+      "  /** projection of this product */\n  def %s: %s\n\n".format(_, _)
+    ) mkString
+  }
+  
+  def apply() = {
+<file name={fileName}>{header}
+object {className} {{
+  def unapply{invariantArgs}(x: {className}{invariantArgs}): Option[{className}{invariantArgs}] = 
     Some(x)
 }}
 
-/** {productClassname(i)} is a cartesian product of {i} components 
- *  {descriptiveComment(i)}
+/** {className} is a cartesian product of {i} component{s}.
+ *  {descriptiveComment}
+ *  @since 2.3
  */
-trait {productClassname(i)}{__typeArgs__} extends Product {{
-
+trait {className}{covariantArgs} extends Product {{
   /**
    *  The arity of this product.
    *  @return {i}
@@ -340,21 +600,52 @@ trait {productClassname(i)}{__typeArgs__} extends Product {{
    *  @throws  IndexOutOfBoundsException
    */
   @throws(classOf[IndexOutOfBoundsException])
-  override def productElement(n: Int) = n match {{
-    {for ((m, j) <- mdefs(i).zip(List.range(0, i)))
-     yield "case "+j+" => "+m+"\n    "}case _ => throw new IndexOutOfBoundsException(n.toString())
-  }}
+  override def productElement(n: Int) = n match {{ {cases} }}  
 
-  {for ((m, t) <- mdefs(i) zip targs(i)) yield 
-    "/** projection of this product */\n  def " + m + ": " + t + "\n\n" }
+{proj}
+{moreMethods}
+}}
+</file>}
+
+}
 
-  {moreMethods(i)}
+/** Abstract functions **/
+
+object AbstractFunctionZero extends AbstractFunction(0) {
+  override def covariantSpecs = FunctionZero.covariantSpecs
+}
+
+object AbstractFunctionOne extends AbstractFunction(1) {
+  override def covariantSpecs = FunctionOne.covariantSpecs
+  override def contravariantSpecs = FunctionOne.contravariantSpecs
+}
+
+object AbstractFunctionTwo extends AbstractFunction(2) {
+  override def covariantSpecs = FunctionTwo.covariantSpecs
+  override def contravariantSpecs = FunctionTwo.contravariantSpecs
+}
+
+class AbstractFunction(val i: Int) extends Group("AbstractFunction") with Arity
+{
+  override def packageDef = "scala.runtime"
+
+  val superTypeArgs = typeArgsString(targs ::: List("R"))
+  
+  def apply() = {
+<file name={"runtime/" + fileName}>{header}
+abstract class {className}{contraCoArgs} extends Function{i}{superTypeArgs} {{
+{moreMethods}
 }}
 </file>}
-  def moreMethods(i:Int) = i match {
-    case _ => ""
-  }
-  def descriptiveComment(i: Int) = i match {
-    case _ => ""
+
+}
+object AbstractFunction
+{
+  def make(i: Int) = apply(i)()
+  def apply(i: Int) = i match {
+    case 0    => AbstractFunctionZero
+    case 1    => AbstractFunctionOne
+    case 2    => AbstractFunctionTwo
+    case _    => new AbstractFunction(i)
   }
-};
+}
diff --git a/src/build/maven/continuations-plugin-pom.xml b/src/build/maven/continuations-plugin-pom.xml
new file mode 100644
index 0000000..0277b89
--- /dev/null
+++ b/src/build/maven/continuations-plugin-pom.xml
@@ -0,0 +1,51 @@
+<project
+        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+	<modelVersion>4.0.0</modelVersion>
+	<groupId>org.scala-lang.plugins</groupId>
+	<artifactId>continuations</artifactId>
+	<packaging>jar</packaging>
+	<version>@VERSION@</version>
+	<url>http://www.scala-lang.org/</url>
+	<inceptionYear>2010</inceptionYear>
+	<organization>
+		<name>LAMP/EPFL</name>
+		<url>http://lamp.epfl.ch/</url>
+	</organization>
+	<licenses>
+		<license>
+			<name>BSD-like</name>
+			<url>http://www.scala-lang.org/downloads/license.html
+			</url>
+			<distribution>repo</distribution>
+		</license>
+	</licenses>
+	<scm>
+		<connection>scm:svn:http://lampsvn.epfl.ch/svn-repos/scala/scala/trunk</connection>
+		<url>https://lampsvn.epfl.ch/trac/scala/browser/scala/trunk</url>
+	</scm>
+	<issueManagement>
+		<system>trac</system>
+		<url>http://lampsvn.epfl.ch/trac/scala
+		</url>
+	</issueManagement>
+
+	<dependencies>
+		<dependency>
+			<groupId>org.scala-lang</groupId>
+			<artifactId>scala-compiler</artifactId>
+			<version>@VERSION@</version>
+		</dependency>
+	</dependencies>
+	<distributionManagement>
+		<repository>
+			<id>scala-tools.org</id>
+			<url>@RELEASE_REPOSITORY@</url>
+		</repository>
+		<snapshotRepository>
+			<id>scala-tools.org</id>
+			<url>@SNAPSHOT_REPOSITORY@</url>
+			<uniqueVersion>false</uniqueVersion>
+		</snapshotRepository>
+	</distributionManagement>
+</project>
diff --git a/src/build/maven/maven-deploy.xml b/src/build/maven/maven-deploy.xml
index 4a418eb..b1d75f1 100644
--- a/src/build/maven/maven-deploy.xml
+++ b/src/build/maven/maven-deploy.xml
@@ -9,8 +9,12 @@
     <!-- Pull in properties from build -->
     <property file="build.properties" />
     <!-- Initialize specific properties -->
+    <!--<property name="remote.snapshot.repository" value="http://scala-tools.org:8081/nexus/content/repositories/snapshots" />
+    <property name="remote.release.repository" value="http://scala-tools.org:8081/nexus/content/repositories/releases" />-->
+
     <property name="remote.snapshot.repository" value="http://nexus.scala-tools.org/content/repositories/snapshots" />
     <property name="remote.release.repository" value="http://nexus.scala-tools.org/content/repositories/releases" />
+
     <property name="local.snapshot.repository" value="${user.home}/.m2/repository" />
     <property name="local.release.repository" value="${user.home}/.m2/repository" />
     <property name="repository.credentials.id" value="scala-tools.org" />
@@ -41,6 +45,21 @@
         <artifact:pom id="@{name}.pom" file="@{name}/@{name}-pom-fixed.xml" />
       </sequential>
     </macrodef>
+
+    <macrodef name="make-pom-plugin">
+      <attribute name="name" />
+      <attribute name="version" />
+      <sequential>
+        <copy file="plugins/@{name}/@{name}-plugin-pom.xml" tofile="plugins/@{name}/@{name}-pom-fixed.xml" overwrite="true">
+          <filterset>
+            <filter token="VERSION" value="@{version}" />
+            <filter token="RELEASE_REPOSITORY" value="${remote.release.repository}" />
+            <filter token="SNAPSHOT_REPOSITORY" value="${remote.snapshot.repository}" />
+          </filterset>
+        </copy>
+        <artifact:pom id="plugin-@{name}.pom" file="plugins/@{name}/@{name}-pom-fixed.xml" />
+      </sequential>
+    </macrodef>
     <!-- Simply attaching documentation -->
     <macrodef name="attach-doc">
       <attribute name="name" />
@@ -68,6 +87,23 @@
       </sequential>
     </macrodef>
 
+    <!-- Deploy compiler plugins -->
+    <macrodef name="deploy-local-plugin">
+        <attribute name="name" />
+        <attribute name="version" />
+        <attribute name="repository" />
+        <element name="extra-attachments" optional="yes" />
+        <sequential>
+          <make-pom-plugin name="@{name}" version="@{version}" />
+          <artifact:install file="plugins/@{name}/@{name}.jar">
+            <artifact:pom refid="plugin-@{name}.pom" />
+            <artifact:localRepository path="@{repository}" id="${repository.credentials.id}" />
+            <extra-attachments />
+          </artifact:install>
+        </sequential>
+      </macrodef>
+
+
     <!-- Deploy all artifacts locally -->
     <macrodef name="deploy-local-all">
       <attribute name="repository" />
@@ -81,6 +117,9 @@
         <deploy-local name="scala-compiler" version="@{version}" repository="@{repository}" />
         <deploy-local name="scala-dbc" version="@{version}" repository="@{repository}" />
         <deploy-local name="scala-swing" version="@{version}" repository="@{repository}"/>
+      	<deploy-local name="scalap" version="@{version}" repository="@{repository}"/>
+      	<deploy-local name="scala-partest" version="@{version}" repository="@{repository}"/>
+        <deploy-local-plugin name="continuations" version="@{version}" repository="@{repository}"/>
         <!-- scala swing api is included in main library api
           <extra-attachments>
             <artifact:attach type="jar" file="scala-swing/scala-swing-docs.jar" classifier="javadoc" />
@@ -110,6 +149,23 @@
       </sequential>
     </macrodef>
 
+
+        <!-- Deploy compiler plugins -->
+    <macrodef name="deploy-remote-plugin">
+        <attribute name="name" />
+        <attribute name="version" />
+        <attribute name="repository" />
+        <element name="extra-attachments" optional="yes" />
+        <sequential>
+          <make-pom-plugin name="@{name}" version="@{version}" />
+          <artifact:deploy file="plugins/@{name}/@{name}.jar" settingsFile="${settings.file}">
+            <artifact:pom refid="plugin-@{name}.pom" />
+            <artifact:remoteRepository url="@{repository}" id="${repository.credentials.id}" />
+            <extra-attachments />
+          </artifact:deploy>
+        </sequential>
+      </macrodef>
+
     <!-- Deploy all artifacts locally -->
     <macrodef name="deploy-remote-all">
       <attribute name="repository" />
@@ -123,6 +179,9 @@
         <deploy-remote name="scala-compiler" version="@{version}" repository="@{repository}" />
         <deploy-remote name="scala-dbc" version="@{version}" repository="@{repository}" />
         <deploy-remote name="scala-swing" version="@{version}" repository="@{repository}"/>
+      	<deploy-remote name="scalap" version="@{version}" repository="@{repository}"/>
+      	<deploy-remote name="scala-partest" version="@{version}" repository="@{repository}"/>
+        <deploy-remote-plugin name="continuations" version="@{version}" repository="@{repository}"/> 
         <!-- scala swing api is included in main library api
           <extra-attachments>
             <artifact:attach type="jar" file="scala-swing/scala-swing-docs.jar" classifier="javadoc" />
@@ -150,4 +209,4 @@
   <target name="deploy.release" depends="deploy.remote.init" description="Deploys the bundled files as a release into the desired remote Maven repository">
     <deploy-remote-all version="${version.number}" repository="${remote.release.repository}" />
   </target>
-</project>
\ No newline at end of file
+</project>
diff --git a/src/build/maven/scala-compiler-pom.xml b/src/build/maven/scala-compiler-pom.xml
index b05a79b..01ede9b 100644
--- a/src/build/maven/scala-compiler-pom.xml
+++ b/src/build/maven/scala-compiler-pom.xml
@@ -1,5 +1,5 @@
 <project
-    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
+        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
 	<modelVersion>4.0.0</modelVersion>
 	<groupId>org.scala-lang</groupId>
@@ -36,6 +36,12 @@
 			<artifactId>scala-library</artifactId>
 			<version>@VERSION@</version>
 		</dependency>
+                <dependency>
+                        <groupId>jline</groupId>
+                        <artifactId>jline</artifactId>
+                        <version>0.9.91</version>
+                        <optional>true</optional>
+                </dependency>
 	</dependencies>
 	<distributionManagement>
 		<repository>
@@ -48,4 +54,4 @@
 			<uniqueVersion>false</uniqueVersion>
 		</snapshotRepository>
 	</distributionManagement>
-</project>
\ No newline at end of file
+</project>
diff --git a/src/build/maven/scala-dbc-pom.xml b/src/build/maven/scala-dbc-pom.xml
index 87afbfe..6c1fa45 100644
--- a/src/build/maven/scala-dbc-pom.xml
+++ b/src/build/maven/scala-dbc-pom.xml
@@ -1,5 +1,5 @@
 <project
-    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
 	<modelVersion>4.0.0</modelVersion>
 	<groupId>org.scala-lang</groupId>
@@ -47,4 +47,4 @@
 			<uniqueVersion>false</uniqueVersion>
 		</snapshotRepository>
 	</distributionManagement>
-</project>
\ No newline at end of file
+</project>
diff --git a/src/build/maven/scala-dotnet-library-pom.xml b/src/build/maven/scala-dotnet-library-pom.xml
new file mode 100644
index 0000000..3394609
--- /dev/null
+++ b/src/build/maven/scala-dotnet-library-pom.xml
@@ -0,0 +1,46 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+  <modelVersion>4.0.0</modelVersion>
+  <groupId>org.scala-lang</groupId>
+  <artifactId>scala-dotnet-library</artifactId>
+  <version>@VERSION@</version>
+  <name>Class Library</name>
+  <packaging>dotnet:library</packaging>
+  
+   <url>http://www.scala-lang.org/</url>
+   <inceptionYear>2002</inceptionYear>
+   <organization>
+      <name>LAMP/EPFL</name>
+      <url>http://lamp.epfl.ch/</url>
+   </organization>
+   <licenses>
+      <license>
+         <name>BSD-like</name>
+         <url>http://www.scala-lang.org/downloads/license.html
+         </url>
+         <distribution>repo</distribution>
+      </license>
+   </licenses>
+   <scm>
+      <connection>scm:svn:http://lampsvn.epfl.ch/svn-repos/scala/scala/trunk</connection>
+      <url>https://lampsvn.epfl.ch/trac/scala/browser/scala/trunk</url>
+   </scm>
+   <issueManagement>
+      <system>trac</system>
+      <url>http://lampsvn.epfl.ch/trac/scala
+      </url>
+   </issueManagement>
+   <distributionManagement>
+      <repository>
+         <id>scala-tools.org</id>
+         <url>@RELEASE_REPOSITORY@</url>
+      </repository>
+      <snapshotRepository>
+         <id>scala-tools.org</id>
+         <url>@SNAPSHOT_REPOSITORY@</url>
+         <uniqueVersion>false</uniqueVersion>
+      </snapshotRepository>
+   </distributionManagement>
+</project>
diff --git a/src/build/maven/scala-library-pom.xml b/src/build/maven/scala-library-pom.xml
index 449985a..836ff47 100644
--- a/src/build/maven/scala-library-pom.xml
+++ b/src/build/maven/scala-library-pom.xml
@@ -1,5 +1,5 @@
 <project
-    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
 	<modelVersion>4.0.0</modelVersion>
 	<groupId>org.scala-lang</groupId>
@@ -40,4 +40,4 @@
 			<uniqueVersion>false</uniqueVersion>
 		</snapshotRepository>
 	</distributionManagement>
-</project>
\ No newline at end of file
+</project>
diff --git a/src/build/maven/scala-partest-pom.xml b/src/build/maven/scala-partest-pom.xml
new file mode 100644
index 0000000..3dc3306
--- /dev/null
+++ b/src/build/maven/scala-partest-pom.xml
@@ -0,0 +1,51 @@
+<project
+        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
+	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+	<modelVersion>4.0.0</modelVersion>
+	<groupId>org.scala-lang</groupId>
+	<artifactId>scala-partest</artifactId>
+	<packaging>jar</packaging>
+	<version>@VERSION@</version>
+	<url>http://www.scala-lang.org/</url>
+	<inceptionYear>2002</inceptionYear>
+	<organization>
+		<name>LAMP/EPFL</name>
+		<url>http://lamp.epfl.ch/</url>
+	</organization>
+	<licenses>
+		<license>
+			<name>BSD-like</name>
+			<url>http://www.scala-lang.org/downloads/license.html
+			</url>
+			<distribution>repo</distribution>
+		</license>
+	</licenses>
+	<scm>
+		<connection>scm:svn:http://lampsvn.epfl.ch/svn-repos/scala/scala/trunk</connection>
+		<url>https://lampsvn.epfl.ch/trac/scala/browser/scala/trunk</url>
+	</scm>
+	<issueManagement>
+		<system>trac</system>
+		<url>http://lampsvn.epfl.ch/trac/scala
+		</url>
+	</issueManagement>
+
+	<dependencies>
+		<dependency>
+			<groupId>org.scala-lang</groupId>
+			<artifactId>scala-compiler</artifactId>
+			<version>@VERSION@</version>
+		</dependency>
+	</dependencies>
+	<distributionManagement>
+		<repository>
+			<id>scala-tools.org</id>
+			<url>@RELEASE_REPOSITORY@</url>
+		</repository>
+		<snapshotRepository>
+			<id>scala-tools.org</id>
+			<url>@SNAPSHOT_REPOSITORY@</url>
+			<uniqueVersion>false</uniqueVersion>
+		</snapshotRepository>
+	</distributionManagement>
+</project>
diff --git a/src/build/maven/scala-swing-pom.xml b/src/build/maven/scala-swing-pom.xml
index 199ad78..06b799c 100644
--- a/src/build/maven/scala-swing-pom.xml
+++ b/src/build/maven/scala-swing-pom.xml
@@ -1,5 +1,5 @@
 <project
-    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
 	<modelVersion>4.0.0</modelVersion>
 	<groupId>org.scala-lang</groupId>
@@ -47,4 +47,4 @@
 			<uniqueVersion>false</uniqueVersion>
 		</snapshotRepository>
 	</distributionManagement>
-</project>
\ No newline at end of file
+</project>
diff --git a/src/build/maven/scalap-pom.xml b/src/build/maven/scalap-pom.xml
new file mode 100644
index 0000000..3326e2d
--- /dev/null
+++ b/src/build/maven/scalap-pom.xml
@@ -0,0 +1,51 @@
+<project
+        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
+	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+	<modelVersion>4.0.0</modelVersion>
+	<groupId>org.scala-lang</groupId>
+	<artifactId>scalap</artifactId>
+	<packaging>jar</packaging>
+	<version>@VERSION@</version>
+	<url>http://www.scala-lang.org/</url>
+	<inceptionYear>2002</inceptionYear>
+	<organization>
+		<name>LAMP/EPFL</name>
+		<url>http://lamp.epfl.ch/</url>
+	</organization>
+	<licenses>
+		<license>
+			<name>BSD-like</name>
+			<url>http://www.scala-lang.org/downloads/license.html
+			</url>
+			<distribution>repo</distribution>
+		</license>
+	</licenses>
+	<scm>
+		<connection>scm:svn:http://lampsvn.epfl.ch/svn-repos/scala/scala/trunk</connection>
+		<url>https://lampsvn.epfl.ch/trac/scala/browser/scala/trunk</url>
+	</scm>
+	<issueManagement>
+		<system>trac</system>
+		<url>http://lampsvn.epfl.ch/trac/scala
+		</url>
+	</issueManagement>
+
+	<dependencies>
+		<dependency>
+			<groupId>org.scala-lang</groupId>
+			<artifactId>scala-compiler</artifactId>
+			<version>@VERSION@</version>
+		</dependency>
+	</dependencies>
+	<distributionManagement>
+		<repository>
+			<id>scala-tools.org</id>
+			<url>@RELEASE_REPOSITORY@</url>
+		</repository>
+		<snapshotRepository>
+			<id>scala-tools.org</id>
+			<url>@SNAPSHOT_REPOSITORY@</url>
+			<uniqueVersion>false</uniqueVersion>
+		</snapshotRepository>
+	</distributionManagement>
+</project>
diff --git a/src/build/msil.properties.SAMPLE b/src/build/msil.properties.SAMPLE
deleted file mode 100644
index e50eb8d..0000000
--- a/src/build/msil.properties.SAMPLE
+++ /dev/null
@@ -1,4 +0,0 @@
-unix.mono.home=/home/linuxsoft/apps/mono
-win.mono.home=C:/Progra~1/Mono
-
-dotnet.home=C:/Windows/Micros~1.NET/Framew~1/v2.0.50727
diff --git a/src/build/msil.xml b/src/build/msil.xml
deleted file mode 100644
index e020537..0000000
--- a/src/build/msil.xml
+++ /dev/null
@@ -1,300 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-
-<project name="sabbus-msil">
-
-  <description>
-    SuperSabbus extension for the MSIL library targeted for the dotnet framework. THIS FILE IS NOT STAND-ALONE AND SHOULD ONLY BE USED THROUGH ENTRY POINTS IN SUPERSABBUS.
-  </description>
-
-  <!-- TODO: test / make it work on Windows (use <ilasm/> task) -->
-  <!-- TODO: for separate compilation: make sure only files that have been changed
-             since last run are re-compiled -->
-  <!-- TODO: run test suite (or at least a part of it) on .NET -->
-  <!-- TODO: generate scaladoc of .NET library -->
-  <!-- TODO: (?) generate the runner scripts with scala.tools.ant.ScalaTool -->
-
-<!-- ===========================================================================
-PROPERTIES
-============================================================================ -->
-
-  <!-- contains the scala-net / scalac-net commands -->
-  <property name="src-mono.dir" value="${src.dir}/mono"/>
-
-  <!-- Loads custom properties definitions -->
-  <property file="${src.dir}/build/msil.properties"/>
-
-  <!-- Sets location of build folders -->
-  <property name="build-msil.dir" value="${build.dir}/msil"/>
-  <property name="build-msil-src.dir" value="${build.dir}/msil-src"/>
-  <property name="build-msil-pack.dir" value="${build.dir}/msil-pack"/>
-
-
-<!-- ===========================================================================
-INITIALISATION
-============================================================================ -->
-  <target name="msil.init">
-    <!-- define the "ilasm" task (and others). they are in fact already there from
-         antlib.xml, but in a deprecated version. -->
-    <!-- <taskdef resource="org/apache/ant/dotnet/antlib.xml"
-             classpath="${lib-ant.dir}/ant-dotnet-1.0.jar"/> -->
-
-    <!-- Sets ilasm command. Search in
-           - dotnet.home/ilasm.exe
-           - unix.mono.home/ilasm
-           - win.mono.home/lib/mono/2.0/ilasm.exe
-           - path
-         (the ".home"s can be set in msil.properties) -->
-    <condition property="ilasm.cmd" value="${dotnet.home}/ilasm.exe">
-      <and>
-        <os family="windows"/><isset property="dotnet.home"/>
-        <available file="${dotnet.home}/ilasm.exe"/>
-      </and>
-    </condition>
-    <condition property="ilasm.cmd" value="${unix.mono.home}/ilasm">
-      <and>
-        <os family="unix"/><isset property="unix.mono.home"/>
-        <available file="${unix.mono.home}/ilasm"/>
-      </and>
-    </condition>
-    <condition property="ilasm.cmd" value="${win.mono.home}/ilasm">
-      <and>
-        <os family="windows"/><isset property="win.mono.home"/>
-        <available file="${win.mono.home}/lib/mono/2.0/ilasm.exe"/>
-      </and>
-    </condition>
-    <condition property="ilasm.cmd" value="ilasm">
-      <and><available file="ilasm" filepath="${env.PATH}"/></and>
-    </condition>
-    <echo level="verbose" message="Found: ${ilasm.cmd}"/>
-    <fail message="Command 'ilasm' not found">
-      <condition><not><isset property="ilasm.cmd"/></not></condition>
-    </fail>
-
-    <!-- Sets ilasm arguments (either Windows or Unix) -->
-    <if>
-      <isset property="os.win"/>
-      <then>
-        <property
-          name="ilasm.args"
-          value="/quiet /dll /output="
-        />
-      </then>
-      <else>
-        <property
-          name="ilasm.args"
-          value="/dll /output:"
-        />
-      </else>
-    </if>
-  </target>
-
-
-<!-- ===========================================================================
-MSIL BUILD
-============================================================================ -->
-
-  <target name="msil.start" depends="msil.init"/>
-
-  <target name="msil.src" depends="msil.start">
-    <!-- simple sync & copy overwrite is not very nice, because overwritten files
-         will then have a new timestamp, and be recompiled -->
-    <mkdir dir="${build-msil-src.dir}"/>
-    <copy todir="${build-msil-src.dir}" overwrite="true">
-      <fileset dir="${src.dir}/library">
-        <and>
-          <present present="srconly" targetdir="${src.dir}/dotnet-library"/>
-          <different targetdir="${build-msil-src.dir}" ignoreFileTimes="true"/>
-        </and>
-      </fileset>
-      <fileset dir="${src.dir}/dotnet-library">
-        <different targetdir="${build-msil-src.dir}" ignoreFileTimes="true"/>
-      </fileset>
-    </copy>
-    <delete verbose="true">
-      <difference>
-        <fileset dir="${build-msil-src.dir}"/>
-        <union>
-          <fileset dir="${build-msil-src.dir}">
-            <present targetdir="${src.dir}/dotnet-library"/>
-          </fileset>
-          <fileset dir="${build-msil-src.dir}">
-            <present targetdir="${src.dir}/library"/>
-          </fileset>
-        </union>
-      </difference>
-    </delete>
-  </target>
-
-  <target name="msil.lib" depends="msil.src">
-    <stopwatch name="msil.lib.timer"/>
-    <mkdir dir="${build-msil.dir}/library"/>
-    <!-- <ilasm srcdir="${msil.dir}/il" includes="*.msil" outputfile="${msil.dir}/lib/predef.dll"/> -->
-
-    <scalac
-        srcdir="${build-msil-src.dir}"
-        destdir="${build-msil.dir}/library"
-        target="msil"
-        assemname="predef.msil"
-        assemrefs="${lib.dir}">
-      <include name="**/*.scala"/>
-      <exclude name="scala/ScalaObject.scala"/>
-    </scalac>
-    <stopwatch name="msil.lib.timer" action="total"/>
-  </target>
-
-  <target name="msil.done" depends="msil.lib"/>
-
-  <target name="msil.clean" depends="msil-pack.clean">
-    <delete dir="${build-msil.dir}" includeemptydirs="yes" quiet="yes" failonerror="no"/>
-    <delete dir="${build-msil-src.dir}" includeemptydirs="yes" quiet="yes" failonerror="no"/>
-  </target>
-
-<!-- ===========================================================================
-PACKED MSIL BUILD (MSIL-PACK)
-============================================================================ -->
-
-  <target name="msil-pack.start" depends="msil.done"/>
-
-  <target name="msil-pack.lib" depends="msil-pack.start">
-    <mkdir dir="${build-msil-pack.dir}/lib"/>
-    <pathconvert property="ilasm.infiles" pathsep=" ">
-      <fileset dir="${build-msil.dir}/library" includes="**/*.msil"/>
-    </pathconvert>
-    <property name="msil-pack-lib.file" value="${build-msil-pack.dir}/lib/predef.dll"/>
-    <!-- spawn="true" will prevent the ilasm command from printing anything to
-         the console. remove for debugging -->
-    <exec executable="${ilasm.cmd}"
-          vmlauncher="no">
-      <!--  spawn="true" -->
-      <arg line="${ilasm.args}${msil-pack-lib.file} ${ilasm.infiles}"/>
-    </exec>
-  </target>
-
-  <target name="msil-pack.bin" depends="msil-pack.lib">
-    <mkdir dir="${build-msil-pack.dir}/bin"/>
-    <copy todir="${build-msil-pack.dir}/bin">
-      <fileset
-        dir="${src-mono.dir}/bin"
-        includes="scala-net*"
-      />
-      <filterset>
-        <filter token="VERSION" value="${version.number}"/>
-        <filter token="COPYRIGHT" value="${copyright.string}"/>
-        <filter token="NAME" value="Scala code runner"/>
-      </filterset>
-    </copy>
-    <copy todir="${build-msil-pack.dir}/bin">
-      <fileset
-        dir="${src-mono.dir}/bin"
-        includes="scalac-net*"
-      />
-      <filterset>
-        <filter token="VERSION" value="${version.number}"/>
-        <filter token="COPYRIGHT" value="${copyright.string}"/>
-        <filter token="NAME" value="Scala compiler"/>
-      </filterset>
-    </copy>
-    <chmod perm="ugo+rx" dir="${build-msil-pack.dir}/bin"
-           includes="scala*-net*" excludes="*.bat"/>
-
-    <if>
-      <isset property="os.win"/>
-      <then>
-        <copy todir="${build-msil-pack.dir}/lib">
-          <fileset
-              dir="${lib.dir}"
-              includes="mscorlib.dll,scalaruntime.dll"/>
-          <fileset
-              dir="${build-pack.dir}/lib"
-              includes="scala-compiler.jar,scala-library.jar"/>
-        </copy>
-      </then>
-      <else>
-        <symlink
-            link="${build-msil-pack.dir}/lib/mscorlib.dll"
-            resource="${lib.dir}/mscorlib.dll"
-            overwrite="yes"/>
-        <symlink
-            link="${build-msil-pack.dir}/lib/scalaruntime.dll"
-            resource="${lib.dir}/scalaruntime.dll"
-            overwrite="yes"/>
-        <symlink
-            link="${build-msil-pack.dir}/lib/scala-compiler.jar"
-            resource="${build-pack.dir}/lib/scala-compiler.jar"
-            overwrite="yes"/>
-        <symlink
-            link="${build-msil-pack.dir}/lib/scala-library.jar"
-            resource="${build-pack.dir}/lib/scala-library.jar"
-            overwrite="yes"/>
-      </else>
-    </if>
-  </target>
-
-  <target name="msil-pack.done" depends="msil-pack.bin"/>
-
-  <target name="msil-pack.clean">
-    <delete dir="${build-msil-pack.dir}" includeemptydirs="yes" quiet="yes" failonerror="no"/>
-  </target>
-
-<!-- ===========================================================================
-DOCUMENTATION
-============================================================================ -->
-
-  <!-- see four.xml for template -->
-  <target name="msil-docs.done"/>
-
-  <target name="msil-docs.clean"/>
-
-<!-- ===========================================================================
-BOOTRAPING TEST AND TEST SUITE
-============================================================================ -->
-
-  <!-- see four.xml for template -->
-  <target name="msil-test.done"/>
-
-
-<!-- ===========================================================================
-DISTRIBUTION
-============================================================================ -->
-
-  <target name="msil-dist.start" depends="msil-pack.done">
-    <property name="msil-dist.dir" value="${dists.dir}/scala-msil-${version.number}"/>
-  </target>
-
-  <target name="msil-dist.lib" depends="msil-dist.start">
-    <mkdir dir="${msil-dist.dir}/lib"/>
-    <copy toDir="${msil-dist.dir}/lib">
-      <fileset dir="${build-msil-pack.dir}/lib"
-               includes="*.dll"/>
-      <fileset dir="${build-msil-pack.dir}/lib"
-               includes="scala-compiler.jar,scala-library.jar"/>
-    </copy>
-  </target>
-
-  <target name="msil-dist.bin" depends="msil-dist.lib">
-    <mkdir dir="${msil-dist.dir}/bin"/>
-    <copy toDir="${msil-dist.dir}/bin">
-      <fileset dir="${build-msil-pack.dir}/bin"
-               includes="scala*-net*"/>
-    </copy>
-    <chmod perm="ugo+rx" dir="${msil-dist.dir}/bin"
-           includes="scala*-net*" excludes="*.bat"/>
-  </target>
-
-  <target name="msil-dist.latest" depends="msil-dist.bin" unless="os.win">
-    <symlink link="${dists.dir}/latest-msil" resource="${msil-dist.dir}" overwrite="yes"/>
-  </target>
-
-  <target name="msil-dist.done" depends="msil-dist.latest"/>
-
-<!-- ===========================================================================
-TEST AND DISTRIBUTION BUNDLE (ALL)
-============================================================================ -->
-
-  <target name="msil-all.done" depends="msil-dist.done, msil-test.done"/>
-
-  <target name="msil-all.clean" depends="msil-docs.clean, msil.clean"/>
-
-</project>
-
-
diff --git a/src/build/old_sabbus.xml b/src/build/old_sabbus.xml
deleted file mode 100644
index f61ca84..0000000
--- a/src/build/old_sabbus.xml
+++ /dev/null
@@ -1,2012 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- $Id: old_sabbus.xml 16881 2009-01-09 16:28:11Z cunei $ -->
-
-<project name="scala-core" default="build">
-
-  <description>
-    I am SABBUS for Scala core, the build system for the Scala compiler and core
-    library. Please check the 'docs/README' file for more information about me.
-  </description>
-
-  <echo level="info" message="Running SABBUS for ${ant.project.name}..."/>
-
-<!-- ===========================================================================
-PROPERTIES
-============================================================================ -->
-
-  <property environment="env"/>
-
-  <!-- Prevents system classpath from being used -->
-  <property name="build.sysclasspath" value="ignore"/>
-
-  <!-- Defines the repository layout -->
-  <property name="docs.dir" value="${basedir}/docs"/>
-  <property name="lib.dir" value="${basedir}/lib"/>
-  <property name="src.dir" value="${basedir}/src"/>
-  <property name="test.dir" value="${basedir}/test"/>
-
-  <!-- Loads custom properties definitions -->
-  <property name="properties.file" value="${basedir}/build.properties"/>
-  <property file="${properties.file}"/>
-
-  <!-- Defines the product being built -->
-  <property name="vendor.name" value="LAMP/EPFL"/>
-  <property name="copyright.string" value="(c) 2002-2009 ${vendor.name}"/>
-  <property name="java.flags" value="-Xmx768M -Xms16M"/>
-  <property name="number.file" value="${basedir}/build.number"/>
-
-  <!-- Configuring how the compiler is run -->
-  <property name="nsc.log-files" value="no"/>
-  <property name="nsc.excludes.file" value="${basedir}/build.excludes"/>
-  <property name="nsc.params" value=""/>
-  <condition property="nsc.target" value="jvm-1.4">
-    <contains string="${ant.java.version}" substring="1.4"/>
-  </condition>
-  <property name="nsc.target" value="jvm-1.5"/>
-
-  <!-- Sets location of pre-compiled libraries -->
-  <property name="lib.starr.jar" value="${lib.dir}/scala-library.jar"/>
-  <property name="comp.starr.jar" value="${lib.dir}/scala-compiler.jar"/>
-  <property name="fjbg.jar" value="${lib.dir}/fjbg.jar"/>
-  <property name="msil.jar" value="${lib.dir}/msil.jar"/>
-  <property name="ant.jar" value="${ant.home}/lib/ant.jar"/>
-  <property name="jline.jar" value="${lib.dir}/jline.jar"/>
-  <property name="ant-contrib.jar" value="${lib.dir}/ant/ant-contrib.jar"/>
-
-  <!-- Sets location of build folders -->
-  <property name="build.dir" value="${basedir}/build"/>
-  <property name="locker.dir" value="${build.dir}/locker"/>
-  <property name="quick.dir" value="${build.dir}/quick"/>
-  <property name="strap.dir" value="${build.dir}/strap"/>
-  <property name="optimised.dir" value="${build.dir}/optimised"/>
-  <property name="api-lib.dir" value="${build.dir}/api-library"/>
-  <property name="api-comp.dir" value="${build.dir}/api-compiler"/>
-  <property name="tooldocs.dir" value="${build.dir}/tooldocs"/>
-  <property name="examples.dir" value="${build.dir}/examples"/>
-<!--  <property name="cldc.dir" value="${build.dir}/cldc"/> -->
-  <property name="android.dir" value="${build.dir}/android"/>
-  <property name="msil.dir" value="${build.dir}/msil"/>
-  <property name="mono.dir" value="${src.dir}/mono"/>
-
-  <!--  Sets location and structure of the distribution -->
-  <property name="dist.dir" value="${basedir}/dists"/>
-  <property name="lib.jar.name" value="scala-library.jar"/>
-  <property name="dbc.jar.name" value="scala-dbc.jar"/>
-  <property name="comp.jar.name" value="scala-compiler.jar"/>
-  <property name="partest.jar.name" value="scala-partest.jar"/>
-  <property name="jline.jar.name" value="jline.jar"/>
-  <property name="libsrc.jar.name" value="scala-library-src.jar"/>
-  <property name="dbcsrc.jar.name" value="scala-dbc-src.jar"/>
-  <property name="parsrc.jar.name" value="scala-partest-src.jar"/>
-  <property name="compsrc.jar.name" value="scala-compiler-src.jar"/>
-  <property name="scala.exec.name" value="scala"/>
-  <property name="scalac.exec.name" value="scalac"/>
-  <property name="scaladoc.exec.name" value="scaladoc"/>
-  <property name="fsc.exec.name" value="fsc"/>
-  <property name="comp.prop.name" value="compiler.properties"/>
-  <property name="lib.prop.name" value="library.properties"/>
-  <property name="par.prop.name" value="partest.properties"/>
-
-  <!-- if available, faster stability checking -->
-  <property name="stability.tool" value="/home/linuxsoft/apps/stability/stability"/>
-
-<!-- ===========================================================================
-ANT INITIALISATION
-============================================================================ -->
-
-  <target name="ant-init">
-  <!-- Making sure lib/ contains everything that is needed -->
-    <fail message="A required library is missing in 'lib/'. The README file describes what should be there.">
-      <condition><not><and>
-        <available file="${lib.starr.jar}"/>
-        <available file="${comp.starr.jar}"/>
-        <available file="${fjbg.jar}"/>
-        <available file="${msil.jar}"/>
-        <available file="${ant-contrib.jar}"/>
-      </and></not></condition>
-    </fail>
-  <!-- Setting-up Ant contrib tasks -->
-    <taskdef resource="net/sf/antcontrib/antlib.xml"
-             classpath="${ant-contrib.jar}"/>
-    <fail message="External library ${ant-contrib.jar} requires the optional Ant tasks to be installed">
-      <condition><not><and>
-        <available file="${ant.home}/lib/ant-nodeps.jar"/>
-      </and></not></condition>
-    </fail>
-  </target>
-
-<!-- ===========================================================================
-INITIALISATION
-============================================================================ -->
-
-  <target name="init" depends="ant-init" unless="init.avail">
-  <!-- Making sure enough memory is available -->
-    <propertyregex
-      property="memory.set" input="${env.ANT_OPTS}" select="\1"
-      regexp="-Xmx([1-9][0-9]{3,}|[6-9][0-9]{2}|5[2-9][0-9]|51[2-9])(M|m)"/>
-    <fail
-      unless="memory.set"
-      message="SABBUS requires additional memory. Please set the 'ANT_OPTS' environment property to '-Xmx512M' or more."/>
-    <propertyregex
-      property="memory.info" input="${env.ANT_OPTS}" defaultValue=""
-      select=" (raise to 600 MB for performance)"
-      regexp="-Xmx([1-5][0-9]{2})(M|m)"/>
-  <!-- This is the start time for the distribution -->
-    <stopwatch name="timer.dist"/>
-    <tstamp prefix="time">
-      <format property="human" pattern="EEEE, d MMMM yyyy, HH:mm:ss (zz)"/>
-      <format property="short" pattern="yyyyMMddHHmmss"/>
-    </tstamp>
-  <!-- Finding out what system architecture is being used -->
-    <condition property="os.win"><os family="windows"/></condition>
-    <if><isset property="os.win"/><then>
-      <exec
-        executable="cygpath" vmlauncher="no"
-        errorproperty="cygpath.err" outputproperty="cygpath.out">
-        <arg value="--windir"/>
-      </exec>
-      <condition property="os.cygwin">
-        <equals arg1="${cygpath.err}" arg2=""/>
-      </condition>
-    </then></if>
-    <condition property="os.unix"><or>
-      <os family="unix"/>
-      <os family="mac"/>
-      <isset property="os.cygwin"/>
-    </or></condition>
-    <if><isset property="os.cygwin"/>
-      <then><property name="os.type" value="Cygwin"/></then>
-      <elseif><isset property="os.win"/>
-        <then><property name="os.type" value="Windows"/></then>
-      </elseif>
-      <elseif><isset property="os.unix"/>
-        <then><property name="os.type" value="UNIX"/></then>
-      </elseif>
-      <else><fail>System environment could not be determined</fail></else>
-    </if>
-  <!-- Setting flag for Java versions 1.4.x -->
-    <condition property="java14">
-      <contains string="${java.version}" substring="1.4"/>
-    </condition>
-  <!-- Finding out SVN revision -->
-    <exec
-      executable="svn" vmlauncher="no"
-      errorproperty="svn.err" outputproperty="svn.out">
-      <arg line=" info ${basedir}"/>
-    </exec>
-    <propertyregex
-      property="svn.number" input="${svn.out}" select="\1"
-      regexp="Revision: ([0-9]+)"
-      defaultValue="x"/>
-    <property name="init.avail" value="yes"/>
-  <!-- Printing out some information about what environment I am running in -->
-    <echo level="info"
-      message="OS:     ${os.type} (${os.name} ${os.arch} ${os.version});"/>
-    <echo level="info"
-      message="Java:   ${java.vm.name} ${java.vm.version} ('${java.home}');"/>
-    <echo level="info"
-      message="Memory: ${memory.set} MB${memory.info};"/>
-    <echo level="info"
-      message="Ant:    ${ant.version}."/>
-  </target>
-
-<!-- ===========================================================================
-SETUP
-============================================================================ -->
-
-  <target name="setup.weave">
-    <!-- Sets location of RetroWeaver installation -->
-    <condition property="retroweaver.home" value="${unix.retroweaver.home}">
-      <and><os family="unix"/><isset property="unix.retroweaver.home"/></and>
-    </condition>
-    <condition property="retroweaver.home" value="${win.retroweaver.home}">
-      <and><os family="windows"/><isset property="win.retroweaver.home"/></and>
-    </condition>
-    <property name="retroweaver.home" value="${env.RETROWEAVER_HOME}"/>
-
-    <fail message="Set property 'retroweaver.home' to a valid RetroWeaver installation">
-      <condition><not><and>
-        <available file="${retroweaver.home}/lib" type="dir"/>
-        <available file="${retroweaver.home}/release" type="dir"/>
-      </and></not></condition>
-    </fail>
-    <taskdef name="retroweaver" classname="net.sourceforge.retroweaver.ant.RetroWeaverTask">
-      <classpath>
-        <fileset dir="${retroweaver.home}/lib" includes="**/*.jar"/>
-        <fileset dir="${retroweaver.home}/release" includes="**/*-all-*jar"/>
-      </classpath>
-    </taskdef>
-    <retroweaver
-      inputjar="${lib.starr.jar}"
-      outputjar="${lib.starr14.jar}"
-    />
-    <retroweaver
-      inputjar="${comp.starr.jar}"
-      outputjar="${comp.starr14.jar}"
-    />
-  </target>
-
-  <target name="setup" depends="init">
-  <!-- Creating class-pathes -->
-    <if>
-      <contains string="${java.version}" substring="1.4"/>
-      <then>
-        <mkdir dir="${build.dir}/starr"/>
-        <property name="lib.starr14.jar" value="${build.dir}/starr/scala-library-14.jar"/>
-        <property name="comp.starr14.jar" value="${build.dir}/starr/scala-compiler-14.jar"/>
-        <antcall target="setup.weave">
-          <param name="lib.starr14.jar" value="${lib.starr14.jar}"/>
-          <param name="comp.starr14.jar" value="${comp.starr14.jar}"/>
-        </antcall>
-        <path id="starr.classpath">
-          <pathelement location="${lib.starr14.jar}"/>
-          <pathelement location="${comp.starr14.jar}"/>
-          <pathelement location="${fjbg.jar}"/>
-          <pathelement location="${msil.jar}"/>
-          <pathelement location="${ant.jar}"/>
-          <pathelement location="${jline.jar}"/>
-        </path>
-      </then>
-      <else>
-        <path id="starr.classpath">
-          <pathelement location="${lib.starr.jar}"/>
-          <pathelement location="${comp.starr.jar}"/>
-          <pathelement location="${fjbg.jar}"/>
-          <pathelement location="${msil.jar}"/>
-          <pathelement location="${ant.jar}"/>
-          <pathelement location="${jline.jar}"/>
-        </path>
-      </else>
-    </if>
-  <!-- Creating boot-level tasks -->
-    <taskdef
-      name="starr"
-      classname="scala.tools.ant.Scalac"
-      classpathref="starr.classpath"/>
-    <taskdef
-      name="starrtool"
-      classname="scala.tools.ant.ScalaTool"
-      classpathref="starr.classpath" />
-  <!-- Removing any outdated stuff -->
-    <if>
-      <and>
-        <available file="${locker.dir}/complete"/>
-        <not><uptodate targetfile="${locker.dir}/complete">
-          <srcfiles dir="${lib.dir}" includes="scala-*.jar"/>
-        </uptodate></not>
-      </and>
-      <then>
-        <echo level="warning"
-          message="STARR updated: LOCKER is obsolete and will be rebuilt."/>
-        <runtarget target="clean.build"/>
-      </then>
-    </if>
-  <!-- Finding out what is available -->
-    <available property="excludes.avail" file="${nsc.excludes.file}"/>
-    <condition property="locker.avail">
-      <available file="${locker.dir}/complete"/>
-    </condition>
-  <!-- Generating version number -->
-    <property file="${number.file}"/>
-    <property
-      name="version.number"
-      value="${version.major}.${version.minor}.${version.patch}.r${svn.number}-b${time.short}"/>
-  <!-- And print-out what we are building -->
-    <echo level="info" message="Build number is '${version.number}'"/>
-    <echo level="info" message="Built ${time.human} from SVN revision ${svn.number}"/>
-  </target>
-
-  <target name="setup.locker" depends="setup, build.locker">
-    <path id="locker.classpath">
-      <pathelement location="${locker.dir}/lib/library"/>
-      <pathelement location="${locker.dir}/lib/compiler"/>
-      <pathelement location="${fjbg.jar}"/>
-      <pathelement location="${msil.jar}"/>
-    </path>
-    <taskdef
-      name="locker"
-      classname="scala.tools.ant.Scalac"
-      classpathref="locker.classpath"/>
-  </target>
-
-  <target name="setup.quick" depends="setup, build">
-    <path id="quick.classpath">
-      <pathelement location="${quick.dir}/lib/library"/>
-      <pathelement location="${quick.dir}/lib/compiler"/>
-      <pathelement location="${fjbg.jar}"/>
-      <pathelement location="${msil.jar}"/>
-    </path>
-    <taskdef
-      name="quick" classname="scala.tools.ant.Scalac"
-      classpathref="quick.classpath"/>
-    <taskdef
-      name="quicksbaz" classname="scala.tools.ant.ScalaBazaar"
-      classpathref="quick.classpath"/>
-    <taskdef
-      name="quickdoc" classname="scala.tools.ant.Scaladoc"
-      classpathref="quick.classpath"/>
-  </target>
-
-<!-- ===========================================================================
-BUILD SUPPORT MACROS
-============================================================================ -->
-
-  <macrodef name="build.support">
-    <attribute name="build.dir"/>
-    <sequential>
-      <copy todir="@{build.dir}/lib/library">
-        <fileset dir="${src.dir}/library">
-          <include name="**/*.tmpl"/>
-          <include name="**/*.xml"/>
-          <include name="**/*.js"/>
-          <include name="**/*.css"/>
-        </fileset>
-      </copy>
-      <copy todir="@{build.dir}/lib/compiler">
-        <fileset dir="${src.dir}/compiler">
-          <include name="**/*.tmpl"/>
-          <include name="**/*.xml"/>
-          <include name="**/*.js"/>
-          <include name="**/*.css"/>
-        </fileset>
-      </copy>
-    </sequential>
-  </macrodef>
-
-  <macrodef name="build.links">
-    <attribute name="build.dir"/>
-    <sequential>
-      <if><not><available file="@{build.dir}/lib/fjbg.jar"/></not><then>
-        <if><isset property="os.win"/><then>
-          <copy file="${fjbg.jar}" tofile="@{build.dir}/lib/fjbg.jar"/>
-        </then><else>
-          <symlink
-            link="@{build.dir}/lib/fjbg.jar"
-            resource="${fjbg.jar}" overwrite="yes" failonerror="no"/>
-        </else></if>
-      </then></if>
-      <if><not><available file="@{build.dir}/lib/msil.jar"/></not><then>
-        <if><isset property="os.win"/><then>
-          <copy file="${msil.jar}" tofile="@{build.dir}/lib/msil.jar"/>
-        </then><else>
-          <symlink
-            link="@{build.dir}/lib/msil.jar"
-            resource="${msil.jar}" overwrite="yes" failonerror="no"/>
-        </else></if>
-      </then></if>
-      <if><not><available file="@{build.dir}/lib/jline.jar"/></not><then>
-        <if><isset property="os.win"/><then>
-          <copy file="${jline.jar}" tofile="@{build.dir}/lib/jline.jar"/>
-        </then><else>
-          <symlink
-            link="@{build.dir}/lib/jline.jar"
-            resource="${jline.jar}" overwrite="yes" failonerror="no"/>
-        </else></if>
-      </then></if>
-    </sequential>
-  </macrodef>
-
-<!-- ===========================================================================
-BUILD LOCAL REFERENCE (LOCKER) LAYER
-============================================================================ -->
-
-  <target name="newlocker"
-    depends="clean.unfreeze, build.locker"
-    description="Rebuilds LOCKER from the current sources"/>
-
-  <target name="build.locker" depends="setup" unless="locker.avail">
-    <property name="built.locker" value="yes"/>
-    <stopwatch name="timer.locker"/>
-  <!-- Build library -->
-    <if><and>
-      <isset property="os.unix"/>
-      <isset property="build.resource"/></and>
-    <then>
-      <symlink
-        link="${build.dir}"
-        resource="${build.resource}" overwrite="yes" failonerror="no"/>
-      <touch file="${build.dir}/is_symlink" verbose="no"/>
-    </then></if>
-    <mkdir dir="${locker.dir}/lib/library"/>
-    <javac
-      srcdir="${src.dir}/library"
-      destdir="${locker.dir}/lib/library"
-      source="1.4" target="1.4" deprecation="yes"
-      classpath="${locker.dir}/lib/library"
-      includes="**/*.java"/>
-    <starr
-      srcdir="${src.dir}/library"
-      destdir="${locker.dir}/lib/library"
-      addparams="${nsc.params}" target="${nsc.target}"
-      deprecation="yes" unchecked="yes"
-      classpath="${locker.dir}/lib/library"
-      includes="scala/Predef.scala"/>
-    <starr
-      srcdir="${src.dir}/library"
-      destdir="${locker.dir}/lib/library"
-      addparams="${nsc.params}" target="${nsc.target}"
-      deprecation="yes" unchecked="yes"
-      classpath="${locker.dir}/lib/library">
-      <include name="**/*.scala"/>
-      <exclude name="scala/Predef.scala"/>
-      <exclude name="scala/dbc/**"/>
-      <exclude name="scala/actors/**"/>
-      <excludesfile name="${nsc.excludes.file}" if="excludes.avail"/>
-    </starr>
-    <echo
-      file="${locker.dir}/lib/library/${lib.prop.name}"
-      message="version.number=${version.number}${line.separator}"
-      append="false"
-    />
-    <echo
-      file="${locker.dir}/lib/library/${lib.prop.name}"
-      message="copyright.string=${copyright.string}${line.separator}"
-      append="true"
-    />
-  <!-- Build compiler -->
-    <mkdir dir="${locker.dir}/lib/compiler"/>
-    <starr
-      srcdir="${src.dir}/compiler"
-      destdir="${locker.dir}/lib/compiler"
-      addparams="${nsc.params}" target="${nsc.target}"
-      deprecation="yes" unchecked="yes">
-      <classpath>
-        <pathelement location="${locker.dir}/lib/library"/>
-        <pathelement location="${locker.dir}/lib/compiler"/>
-        <pathelement location="${fjbg.jar}"/>
-        <pathelement location="${msil.jar}"/>
-        <pathelement location="${ant.jar}"/>
-        <pathelement location="${jline.jar}"/>
-      </classpath>
-      <include name="**/*.scala"/>
-      <excludesfile name="${nsc.excludes.file}" if="excludes.avail"/>
-    </starr>
-    <echo
-      file="${locker.dir}/lib/compiler/${comp.prop.name}"
-      message="version.number=${version.number}${line.separator}"
-      append="false"
-    />
-    <echo
-      file="${locker.dir}/lib/compiler/${comp.prop.name}"
-      message="copyright.string=${copyright.string}${line.separator}"
-      append="true"
-    />
-  <!-- Timing the build -->
-    <stopwatch name="timer.locker" action="total"/>
-  <!-- Copy support files to build folder and links external libraries-->
-    <build.support build.dir="${locker.dir}"/>
-    <build.links build.dir="${locker.dir}"/>
-  <!-- Build executable files -->
-    <taskdef
-      name="lockertool"
-      classname="scala.tools.ant.ScalaTool"
-      classpathref="locker.classpath"/>
-    <mkdir dir="${locker.dir}/bin"/>
-    <lockertool
-      file="${locker.dir}/bin/${scala.exec.name}"
-      class="scala.tools.nsc.MainGenericRunner"
-      javaFlags="${java.flags}"/>
-    <lockertool
-      file="${locker.dir}/bin/${scalac.exec.name}"
-      class="scala.tools.nsc.Main"
-      javaFlags="${java.flags}"/>
-    <lockertool
-      file="${locker.dir}/bin/${scaladoc.exec.name}"
-      class="scala.tools.nsc.ScalaDoc"
-      javaFlags="${java.flags}"/>
-    <lockertool
-      file="${locker.dir}/bin/${fsc.exec.name}"
-      class="scala.tools.nsc.CompileClient"
-      javaFlags="${java.flags}"/>
-    <chmod perm="ugo+rx"
-      file="${locker.dir}/bin/${scalac.exec.name}"/>
-    <chmod perm="ugo+rx"
-      file="${locker.dir}/bin/${scala.exec.name}"/>
-    <chmod perm="ugo+rx"
-      file="${locker.dir}/bin/${scaladoc.exec.name}"/>
-    <chmod perm="ugo+rx"
-      file="${locker.dir}/bin/${fsc.exec.name}"/>
-    <fixcrlf
-      srcdir="${locker.dir}/bin"
-      eol="dos"
-      includes="**/*.bat"/>
-    <!-- Mark LOCKER as being completely built -->
-    <touch file="${locker.dir}/complete" verbose="no"/>
-  </target>
-
-<!-- ===========================================================================
-BUILD QUICK-TEST LAYER
-============================================================================ -->
-
-  <target name="build" depends="setup.locker"
-    description="Builds a quick-test (QUICK) version of the compiler">
-    <stopwatch name="timer.quick"/>
-  <!-- Build library -->
-    <mkdir dir="${quick.dir}/lib/library"/>
-    <javac
-      srcdir="${src.dir}/library"
-      destdir="${quick.dir}/lib/library"
-      source="1.4" target="1.4" deprecation="yes"
-      classpath="${quick.dir}/lib/library"
-      includes="**/*.java"/>
-    <locker
-      srcdir="${src.dir}/library"
-      destdir="${quick.dir}/lib/library"
-      addparams="${nsc.params}" target="${nsc.target}"
-      deprecation="yes" unchecked="yes"
-      scalacdebugging="${nsc.log-files}"
-      classpath="${quick.dir}/lib/library"
-      includes="scala/Predef.scala"/>
-    <locker
-      srcdir="${src.dir}/library"
-      destdir="${quick.dir}/lib/library"
-      addparams="${nsc.params}" target="${nsc.target}"
-      deprecation="yes" unchecked="yes"
-      scalacdebugging="${nsc.log-files}"
-      classpath="${quick.dir}/lib/library">
-      <include name="**/*.scala"/>
-      <exclude name="scala/Predef.scala"/>
-      <exclude name="scala/dbc/**"/>
-      <exclude name="scala/actors/**"/>
-      <excludesfile name="${nsc.excludes.file}" if="excludes.avail"/>
-    </locker>
-    <echo
-      file="${quick.dir}/lib/library/${lib.prop.name}"
-      message="version.number=${version.number}${line.separator}"
-      append="false"
-    />
-    <echo
-      file="${quick.dir}/lib/library/${lib.prop.name}"
-      message="copyright.string=${copyright.string}${line.separator}"
-      append="true"
-    />
-  <!-- Build DBC -->
-    <mkdir dir="${quick.dir}/lib/dbc"/>
-    <locker
-      srcdir="${src.dir}/dbc"
-      destdir="${quick.dir}/lib/dbc"
-      addparams="${nsc.params}" target="${nsc.target}"
-      deprecation="yes" unchecked="yes"
-      scalacdebugging="${nsc.log-files}">
-      <classpath>
-        <pathelement location="${quick.dir}/lib/library"/>
-        <pathelement location="${quick.dir}/lib/dbc"/>
-      </classpath>
-      <include name="scala/dbc/**/*.scala"/>
-      <excludesfile name="${nsc.excludes.file}" if="excludes.avail"/>
-    </locker>
-  <!-- Build actors library -->
-    <mkdir dir="${quick.dir}/lib/actors"/>
-    <javac
-      srcdir="${src.dir}/actors"
-      destdir="${quick.dir}/lib/actors"
-      source="1.4" target="1.4" deprecation="yes"
-      classpath="${quick.dir}/lib/actors"
-      includes="scala/actors/**/*.java"/>
-    <locker
-      srcdir="${src.dir}/actors"
-      destdir="${quick.dir}/lib/actors"
-      addparams="${nsc.params}" target="${nsc.target}"
-      deprecation="yes" unchecked="yes"
-      scalacdebugging="${nsc.log-files}">
-      <classpath>
-        <pathelement location="${quick.dir}/lib/library"/>
-        <pathelement location="${quick.dir}/lib/actors"/>
-      </classpath>
-      <include name="scala/actors/**/*.scala"/>
-      <excludesfile name="${nsc.excludes.file}" if="excludes.avail"/>
-    </locker>
-  <!-- Build compiler -->
-    <mkdir dir="${quick.dir}/lib/compiler"/>
-    <locker
-      srcdir="${src.dir}/compiler"
-      destdir="${quick.dir}/lib/compiler"
-      addparams="${nsc.params}" target="${nsc.target}"
-      deprecation="yes" unchecked="yes"
-      scalacdebugging="${nsc.log-files}">
-      <classpath>
-        <pathelement location="${quick.dir}/lib/library"/>
-        <pathelement location="${quick.dir}/lib/compiler"/>
-        <pathelement location="${fjbg.jar}"/>
-        <pathelement location="${msil.jar}"/>
-        <pathelement location="${ant.jar}"/>
-        <pathelement location="${jline.jar}"/>
-      </classpath>
-      <include name="**/*.scala"/>
-      <excludesfile name="${nsc.excludes.file}" if="excludes.avail"/>
-    </locker>
-    <echo
-      file="${quick.dir}/lib/compiler/${comp.prop.name}"
-      message="version.number=${version.number}${line.separator}"
-      append="false"
-    />
-    <echo
-      file="${quick.dir}/lib/compiler/${comp.prop.name}"
-      message="copyright.string=${copyright.string}${line.separator}"
-      append="true"
-    />
-  <!-- Build partest -->
-    <mkdir dir="${quick.dir}/lib/partest"/>
-    <javac
-      srcdir="${src.dir}/partest"
-      destdir="${quick.dir}/lib/partest"
-      source="1.4" target="1.4" deprecation="yes"
-      classpath="${quick.dir}/lib/partest"
-      includes="scala/tools/partest/**/*.java"/>
-    <locker
-      srcdir="${src.dir}/partest"
-      destdir="${quick.dir}/lib/partest"
-      addparams="${nsc.params}" target="${nsc.target}"
-      deprecation="yes" unchecked="yes">
-      <classpath>
-        <pathelement location="${quick.dir}/lib/library"/>
-        <pathelement location="${quick.dir}/lib/compiler"/>
-        <pathelement location="${quick.dir}/lib/actors"/>
-        <pathelement location="${ant.jar}"/>
-      </classpath>
-    </locker>
-    <echo
-      file="${quick.dir}/lib/partest/${par.prop.name}"
-      message="version.number=${version.number}${line.separator}"
-      append="false"
-    />
-    <echo
-      file="${quick.dir}/lib/partest/${par.prop.name}"
-      message="copyright.string=${copyright.string}${line.separator}"
-      append="true"
-    />
-  <!-- Timing the build -->
-    <stopwatch name="timer.quick" action="total"/>
-  <!-- Copy support files to build folder and links external libraries-->
-    <build.support build.dir="${quick.dir}"/>
-    <build.links build.dir="${quick.dir}"/>
-  <!-- Build executable files -->
-    <taskdef
-      name="quicktool"
-      classname="scala.tools.ant.ScalaTool"
-      classpathref="quick.classpath"/>
-    <mkdir dir="${quick.dir}/bin"/>
-    <quicktool
-      file="${quick.dir}/bin/${scala.exec.name}"
-      class="scala.tools.nsc.MainGenericRunner"
-      javaFlags="${java.flags}"/>
-    <quicktool
-      file="${quick.dir}/bin/${scalac.exec.name}"
-      class="scala.tools.nsc.Main"
-      javaFlags="${java.flags}"/>
-    <quicktool
-      file="${quick.dir}/bin/${scaladoc.exec.name}"
-      class="scala.tools.nsc.ScalaDoc"
-      javaFlags="${java.flags}"/>
-    <quicktool
-      file="${quick.dir}/bin/${fsc.exec.name}"
-      class="scala.tools.nsc.CompileClient"
-      javaFlags="${java.flags}"/>
-    <chmod perm="ugo+rx"
-      file="${quick.dir}/bin/${scalac.exec.name}"/>
-    <chmod perm="ugo+rx"
-      file="${quick.dir}/bin/${scala.exec.name}"/>
-    <chmod perm="ugo+rx"
-      file="${quick.dir}/bin/${scaladoc.exec.name}"/>
-    <chmod perm="ugo+rx"
-      file="${quick.dir}/bin/${fsc.exec.name}"/>
-    <fixcrlf
-      srcdir="${quick.dir}/bin"
-      eol="dos"
-      includes="**/*.bat"/>
-  </target>
-
-  <target name="test.quick" depends="build">
-    <echo level="info"
-      message="Ant test bench is not available yet."/>
-  </target>
-
-<!-- ===========================================================================
-CLDC
-============================================================================ -->
-<!--
-  <property name="cldcapi.jar" value="${lib.dir}/cldcapi10.jar"/>
-  <property name="midpapi.jar" value="${lib.dir}/midpapi10.jar"/>
-
-  <target name="cldc.sources"
-          description="Create the source directory for the J2ME (CLDC) library"
-  >
-    <mkdir dir="${cldc.dir}/src"/>
-
-    <copy todir="${cldc.dir}/src">
-      <fileset dir="${src.dir}/library" includes="**/*.scala, **/*.java">
-        <not>
-          <present targetdir="${src.dir}/cldc-library"/>
-        </not>
-        <exclude name="**/*CharSequence.scala"/>
-        <exclude name="**/jcl/**"/>
-        <exclude name="**/ref/**"/>
-        <exclude name="**/compat/**"/>
-        <exclude name="**/concurrent/**"/>
-        <exclude name="**/runtime/RichFloat.scala"/>
-        <exclude name="**/runtime/RichDouble.scala"/>
-        <exclude name="**/util/**"/>
-        <exclude name="**/xml/**"/>
-      </fileset>
-    </copy>
-
-    <copy todir="${cldc.dir}/src">
-      <fileset dir="${src.dir}/cldc-library">
-        <include name="**/*.scala"/>
-        <include name="**/*.java"/>
-      </fileset>
-    </copy>
-
-  </target>
-
-  <target name="cldc.libraries"
-    depends="setup.quick, cldc.sources"
-    description="Builds the Scala library for J2ME (CLDC)"
-  >
-    <mkdir dir="${cldc.dir}/lib/library"/>
-    <javac
-      srcdir="${cldc.dir}/src"
-      destdir="${cldc.dir}/lib/library"
-      compiler="javac1.4"
-      source="1.1"
-      target="1.1"
-      deprecation="${jc.deprecation}"
-    >
-      <bootclasspath>
-        <pathelement location="${cldcapi.jar}"/>
-      </bootclasspath>
-      <include name="**/*.java"/>
-      <exclude name="scala/runtime/FloatRef.java"/>
-      <exclude name="scala/runtime/DoubleRef.java"/>
-    </javac>
-
-    <quick
-      srcdir="${cldc.dir}/src"
-      destdir="${cldc.dir}/lib/library"
-      addparams="${nsc.params}"
-      target="cldc"
-      scalacdebugging="${nsc.log-files}"
-    >
-      <bootclasspath>
-        <pathelement location="${cldcapi.jar}"/>
-      </bootclasspath>
-      <classpath>
-        <pathelement location="${cldc.dir}"/>
-      </classpath>
-      <include name="scala/Predef.scala"/>
-    </quick>
-    <quick
-      srcdir="${cldc.dir}/src"
-      destdir="${cldc.dir}/lib/library"
-      target="cldc"
-      addparams="${nsc.params}"
-      scalacdebugging="${nsc.log-files}"
-    >
-      <bootclasspath>
-        <pathelement location="${cldcapi.jar}"/>
-      </bootclasspath>
-      <classpath>
-        <pathelement location="${cldc.dir}"/>
-      </classpath>
-      <include name="**/*.scala"/>
-      <exclude name="scala/Predef.scala"/>
-      <exclude name="scala/BigDecimal.scala"/>
-      <exclude name="scala/BigInt.scala"/>
-      <exclude name="scala/collection/mutable/JavaMapAdaptor.scala"/>
-      <exclude name="scala/collection/mutable/JavaSetAdaptor.scala"/>
-      <exclude name="scala/collection/mutable/LinkedHashSet.scala"/>
-      <exclude name="scala/util/Fluid.scala"/>
-      <exclude name="scala/runtime/BoxedFloatArray.scala"/>
-      <exclude name="scala/runtime/BoxedDoubleArray.scala"/>
-      <exclude name="scala/io/**"/>
-      <exclude name="scala/mobile/**"/>
-      <exclude name="scala/reflect/**"/>
-      <exclude name="scala/text/**"/>
-      <exclude name="scala/testing/**"/>
-      <exclude name="scala/xml/**"/>
-      <excludesfile name="${nsc.excludes}" if="excludes.avail"/>
-    </quick>
-    <macrodef name="preverify">
-      <attribute name="srcdir"/>
-      <attribute name="destdir"/>
-      <sequential>
-        <exec executable="preverify" failonerror="false">
-          <arg line="-classpath ${cldcapi.jar}${path.separator}${midpapi.jar}"/>
-          <arg line="-target cldc1.0"/>
-          <arg line="-d @{destdir}"/>
-          <arg value="@{srcdir}"/>
-        </exec>
-      </sequential>
-    </macrodef>
-    <mkdir dir="${cldc.dir}/lib/preverified"/>
-    <preverify
-      srcdir="${cldc.dir}/lib/library"
-      destdir="${cldc.dir}/lib/preverified"
-    />
-    <jar
-      destfile="${cldc.dir}/lib/scalaapi10-unverified.jar"
-      basedir="${cldc.dir}/lib/library"
-      includes="scala/**/*.class">
-      <manifest>
-        <attribute name="Created-By" value="${version.number} (${vendor.name})"/>
-      </manifest>
-    </jar>
-    <jar
-      destfile="${cldc.dir}/lib/scalaapi10.jar"
-      basedir="${cldc.dir}/lib/preverified"
-      includes="scala/**/*.class">
-      <manifest>
-        <attribute name="Created-By" value="${version.number} (${vendor.name})"/>
-        <attribute name="API-Specification-Version" value="1.0"/>
-        <attribute name="API" value="Scala CLDC"/>
-        <attribute name="API-Name" value="Scala Connected Limited Device Configuration"/>
-        <attribute name="API-Type" value="Configuration"/>
-      </manifest>
-    </jar>
-  </target>
-
-  <target name="cldc" depends="cldc.libraries">
-  </target>
--->
-
-<!-- ===========================================================================
-ANDROID
-============================================================================ -->
-
-  <target name="android.init">
-    <!-- Sets location of Android installation -->
-    <condition property="android.home" value="${unix.android.home}">
-      <and><os family="unix"/><isset property="unix.android.home"/></and>
-    </condition>
-    <condition property="android.home" value="${win.android.home}">
-      <and><os family="windows"/><isset property="win.android.home"/></and>
-    </condition>
-    <property name="android.home" value="${env.ANDROID_HOME}"/>
-
-    <fail message="Android home is not set or could not find android.jar in ${android.home}">
-      <condition><not>
-        <available file="${android.home}/android.jar"/>
-      </not></condition>
-    </fail>
-  </target>
-
-  <target name="android.sources" depends="android.init"
-          description="Create the source directory for Android library"
-  >
-    <mkdir dir="${android.dir}/src"/>
-    <copy todir="${android.dir}/src">
-      <fileset dir="${src.dir}/android-library" includes="**/*.scala, **/*.java"/>
-    </copy> 
-    <copy todir="${android.dir}/src">
-      <fileset dir="${src.dir}/library" includes="**/*.scala, **/*.java" />
-    </copy>
-  </target>
-
-  <target name="android.libraries"
-          depends="setup.quick, android.sources"
-          description="Builds the Scala library for Android">
-    <mkdir dir="${android.dir}/lib/library"/>
-    <javac
-      srcdir="${android.dir}/src"
-      destdir="${android.dir}/lib/library"
-      deprecation="${jc.deprecation}"
-    >
-      <bootclasspath>
-        <pathelement location="${android.home}/android.jar}"/>
-      </bootclasspath>
-      <include name="**/*.java"/>
-    </javac>
-
-    <quick
-      srcdir="${android.dir}/src"
-      destdir="${android.dir}/lib/library"
-      deprecation="yes" unchecked="yes"
-      addparams="${nsc.params}"
-      extdirs=""
-      scalacdebugging="${nsc.log-files}"
-    >
-      <bootclasspath>
-        <pathelement location="${android.home}/android.jar"/>
-      </bootclasspath>
-      <include name="scala/Predef.scala"/>
-    </quick>
-
-    <quick
-      srcdir="${android.dir}/src"
-      destdir="${android.dir}/lib/library"
-      deprecation="yes" unchecked="yes"
-      extdirs=""
-      addparams="${nsc.params}"
-      scalacdebugging="${nsc.log-files}"
-    >
-      <bootclasspath>
-        <pathelement location="${android.home}/android.jar"/>
-      </bootclasspath>
-      <classpath>
-        <pathelement location="${android.dir}"/>
-      </classpath>
-      <include name="**/*.scala"/>
-      <exclude name="scala/Predef.scala"/>
-      <excludesfile name="${nsc.excludes}" if="excludes.avail"/>
-    </quick>
-  </target>
-
-  <target name="android.build" depends="android.libraries"
-          description="Convert this project's .class files into .dex files">
-     <property name="dx.jar" value="${android.home}/tools/lib/dx.jar"/>
-     <java jar="${dx.jar}" fork="true" failonerror="true">
-      <jvmarg value="-Djava.ext.dirs=${android.home}${file.separator}tools${file.separator}lib"/>
-      <jvmarg value="-Xmx384M"/>
-      <arg value="--dex"/>
-      <arg value="--output=${android.dir}/lib/scala.dex"/>
-      <arg value="--locals=full"/>
-      <arg value="--positions=lines"/>
-      <arg value="--no-optimize"/>  <!-- workaround for M5-RC14 bug -->
-      <arg value="${android.dir}/lib/library"/>
-    </java>
-    <jar
-      destfile="${android.dir}/lib/scala-dex.jar"
-      basedir="${android.dir}/lib"
-      includes="scala.dex"
-    />
-    <jar
-      destfile="${android.dir}/lib/scala-android.jar"
-      basedir="${android.dir}/lib/library"
-      includes="scala/**/*.class"
-    />
-  </target>
-
-  <target name="android" depends="init">
-    <condition property="android.supported">
-      <and>
-        <not><contains string="${java.version}" substring="1.4"/></not>
-        <contains string="${java.vendor}" substring="Sun"/>
-      </and>
-    </condition>
-    <if><isset property="android.supported"/><then>
-      <antcall target="android.build"/>
-    </then><else>
-      <echo message="The Android library build requires Sun Java 1.5 or newer"/>
-    </else></if>
-  </target>
-
-<!-- ===========================================================================
-MSIL
-============================================================================ -->
-
-  <target name="msil.init" depends="ant-init">
-    <!-- Sets ilasm command (either Microsoft .NET Framework or Mono) -->
-    <condition property="ilasm.cmd" value="${msdn.home}/ilasm.exe">
-      <and>
-        <os family="windows"/><isset property="msdn.home"/>
-        <available file="${msdn.home}/ilasm.exe"/>
-      </and>
-    </condition>
-    <condition property="ilasm.cmd" value="${unix.mono.home}/ilasm">
-      <and>
-        <os family="unix"/><isset property="unix.mono.home"/>
-        <available file="${unix.mono.home}/ilasm"/>
-      </and>
-    </condition>
-    <condition property="ilasm.cmd" value="${win.mono.home}/ilasm">
-      <and>
-        <os family="windows"/><isset property="${win.mono.home}/lib/mono/2.0/ilasm.exe"/>
-        <available file="${win.mono.home}/lib/mono/2.0/ilasm.exe"/>
-      </and>
-    </condition>
-    <echo level="verbose" message="Found: ${ilasm.cmd}"/>
-    <condition property="ilasm.cmd" value="ilasm">
-      <and><available file="ilasm" filepath="${env.PATH}"/></and>
-    </condition>
-    <fail message="Command 'ilasm' not found">
-      <condition><not><isset property="ilasm.cmd"/></not></condition>
-    </fail>
-    <!-- Sets ilasm arguments (either Windows or Unix) -->
-    <property name="ilasm.outfile" value="${msil.dir}/predef.dll"/>
-    <if>
-      <isset property="os.win"/>
-      <then>
-        <property
-          name="ilasm.args"
-          value="/quiet /dll /output=${ilasm.outfile}"
-        />
-      </then>
-      <else>
-        <property
-          name="ilasm.args"
-          value="/dll /output:${ilasm.outfile}"
-        />
-      </else>
-    </if>
-  </target>
-
-  <target name="msil.sources" depends="msil.init">
-    <mkdir dir="${msil.dir}/src"/>
-    <copy todir="${msil.dir}/src">
-      <fileset dir="${src.dir}/dotnet-library" includes="**/*.scala, **/*.cs"/> 
-    </copy>
-    <copy todir="${msil.dir}/src">
-      <fileset dir="${src.dir}/library" includes="**/*.scala"/>
-    </copy>
-  </target>
-
-  <target name="msil.libraries" depends="setup.quick, msil.sources">
-      <quick srcdir="${msil.dir}/src" destdir="${msil.dir}" target="msil"
-           assemname="predef" assemrefs="${lib.dir}"
-           failonerror="false">
-      <include name="**/*.scala"/>
-      <exclude name="scala/ScalaObject.scala"/>   
-      <!--  
-      <include name="scala/Predef.scala"/>
-      <include name="scala/Either.scala"/>
-      <include name="scala/Option.scala"/>
-      <include name="scala/Pair.scala"/>
-      <include name="scala/Console.scala"/>
-      <include name="scala/Application.scala"/>
-      <include name="scala/ByNameFunction.scala"/>
-      <include name="scala/Stream.scala"/>
-      <include name="scala/*Annotation.scala"/>
-      <include name="scala/Function*.scala"/>
-      <include name="scala/Tuple*.scala"/>
-      <include name="scala/Product*.scala"/>
-      <include name="scala/List.scala"/>
-      <include name="scala/cloneable.scala"/>
-      <include name="scala/deprecated.scala"/>
-      <include name="scala/native.scala"/>
-      <include name="scala/serializable.scala"/>
-      <include name="scala/transient.scala"/>
-      <include name="scala/volatile.scala"/>
-      <include name="scala/remote.scala"/>
-      <include name="scala/throws.scala"/>
-      <include name="scala/BigInt.scala"/>
-      <include name="scala/CountedIterator.scala"/>
-      <include name="scala/collection/**/*.scala"/>
-      <include name="scala/runtime/*.scala"/>
-      <include name="scala/concurrent/*.scala"/> 
-      <include name="scala/ref/*.scala"/> 
-      <include name="scala/reflect/*.scala"/> 
-      <include name="scala/testing/*.scala"/> 
-      <include name="scala/text/*.scala"/> -->
-    </quick>
-    <pathconvert property="ilasm.infile" pathsep=" ">
-      <fileset dir="${msil.dir}" includes="*.msil"/>
-    </pathconvert>
-    <exec
-      executable="${ilasm.cmd}" vmlauncher="no">
-      <!--
-      errorproperty="ilasm.err" outputproperty="ilasm.out">
-      -->
-      <arg line="${ilasm.args} ${ilasm.infile}"/>
-    </exec>
-  </target>
-
-  <target name="msil" depends="msil.libraries">
-    <copy todir="${quick.dir}/bin">
-      <fileset
-        dir="${mono.dir}/bin"
-        includes="scala-net*"
-      />
-      <filterset>
-        <filter token="VERSION" value="${version.number}"/>
-        <filter token="COPYRIGHT" value="${copyright.string}"/>
-        <filter token="NAME" value="Scala code runner"/>
-      </filterset>
-    </copy>
-    <copy todir="${quick.dir}/bin">
-      <fileset
-        dir="${mono.dir}/bin"
-        includes="scalac-net*"
-      />
-      <filterset>
-        <filter token="VERSION" value="${version.number}"/>
-        <filter token="COPYRIGHT" value="${copyright.string}"/>
-        <filter token="NAME" value="Scala compiler"/>
-      </filterset>
-    </copy>
-    <chmod perm="ugo+rx"
-      dir="${quick.dir}/bin" includes="*-net*"/>
-    <if><isset property="os.win"/>
-      <then>
-        <copy todir="${quick.dir}/lib">
-          <fileset dir="${msil.dir}" includes="*.dll"/>
-          <fileset dir="${lib.dir}" includes="*.dll"/>
-        </copy>
-      </then>
-      <else>
-        <symlink
-          link="${quick.dir}/lib/predef.dll"
-          resource="${msil.dir}/predef.dll"
-          overwrite="yes" failonerror="no"/>
-        <symlink
-          link="${quick.dir}/lib/scalaruntime.dll"
-          resource="${lib.dir}/scalaruntime.dll"
-          overwrite="yes" failonerror="no"/>
-        <symlink
-          link="${quick.dir}/lib/mscorlib.dll"
-          resource="${lib.dir}/mscorlib.dll"
-          overwrite="yes" failonerror="no"/>
-      </else>
-    </if>
-  </target>
-  
-<!-- ===========================================================================
-OPTIMIZE
-============================================================================ -->
-  <target name="optimised" depends="build.optimised"
-    description="Build the compiler with optimizations on."/>
-
-  <!-- Build the bootstrap layer -->
-  <target name="build.optimised" depends="setup.quick">
-    <stopwatch name="timer.optimised"/>
-  <!-- Build library -->
-    <mkdir dir="${optimised.dir}/lib/library"/>
-    <javac
-      srcdir="${src.dir}/library"
-      destdir="${optimised.dir}/lib/library"
-      source="1.4" target="1.4" deprecation="yes"
-      classpath="${optimised.dir}/lib/library"
-      includes="**/*.java"/>
-    <quick
-      srcdir="${src.dir}/library"
-      destdir="${optimised.dir}/lib/library"
-      addparams="${nsc.params}" target="${nsc.target}"
-      deprecation="yes" unchecked="yes"
-      optimise="yes"
-      classpath="${optimised.dir}/lib/library"
-      includes="scala/Predef.scala"/>
-    <quick
-      srcdir="${src.dir}/library"
-      destdir="${optimised.dir}/lib/library"
-      addparams="${nsc.params}" target="${nsc.target}"
-      optimise="yes"
-      deprecation="yes" unchecked="yes"
-      classpath="${optimised.dir}/lib/library">
-      <include name="**/*.scala"/>
-      <exclude name="scala/Predef.scala"/>
-      <exclude name="scala/dbc/**"/>
-      <exclude name="scala/actors/**"/>
-      <excludesfile name="${nsc.excludes.file}" if="excludes.avail"/>
-    </quick>
-    <echo
-      file="${optimised.dir}/lib/library/${lib.prop.name}"
-      message="version.number=${version.number}${line.separator}"
-      append="false"
-    />
-    <echo
-      file="${optimised.dir}/lib/library/${lib.prop.name}"
-      message="copyright.string=${copyright.string}${line.separator}"
-      append="true"
-    />
-  <!-- Build compiler -->
-    <mkdir dir="${optimised.dir}/lib/compiler"/>
-    <quick
-      srcdir="${src.dir}"
-      destdir="${optimised.dir}/lib/compiler"
-      optimise="yes"
-      addparams="${nsc.params}" target="${nsc.target}">
-      <classpath>
-        <pathelement location="${optimised.dir}/lib/library"/>
-        <pathelement location="${optimised.dir}/lib/compiler"/>
-        <pathelement location="${fjbg.jar}"/>
-        <pathelement location="${msil.jar}"/>
-        <pathelement location="${ant.jar}"/>
-        <pathelement location="${jline.jar}"/>
-      </classpath>
-      <include name="compiler/**/*.scala"/>
-      <include name="library/scala/List.scala"/>
-      <excludesfile name="${nsc.excludes.file}" if="excludes.avail"/>
-    </quick>
-    <echo
-      file="${optimised.dir}/lib/compiler/${comp.prop.name}"
-      message="version.number=${version.number}${line.separator}"
-      append="false"
-    />
-    <echo
-      file="${optimised.dir}/lib/compiler/${comp.prop.name}"
-      message="copyright.string=${copyright.string}${line.separator}"
-      append="true"
-    />
-  <!-- Timing the build -->
-    <stopwatch name="timer.strap" action="total"/>
-  <!-- Copy support files to build folder and links external libraries-->
-    <build.support build.dir="${optimised.dir}"/>
-    <build.links build.dir="${optimised.dir}"/>
-  <!-- Build executable files -->
-    <taskdef
-      name="straptool"
-      classname="scala.tools.ant.ScalaTool"
-      classpathref="quick.classpath"/>
-    <mkdir dir="${optimised.dir}/bin"/>
-    <straptool
-      file="${optimised.dir}/bin/${scala.exec.name}"
-      class="scala.tools.nsc.MainGenericRunner"
-      javaFlags="${java.flags}"/>
-    <straptool
-      file="${optimised.dir}/bin/${scalac.exec.name}"
-      class="scala.tools.nsc.Main"
-      javaFlags="${java.flags}"/>
-    <straptool
-      file="${optimised.dir}/bin/${scaladoc.exec.name}"
-      class="scala.tools.nsc.ScalaDoc"
-      javaFlags="${java.flags}"/>
-    <straptool
-      file="${optimised.dir}/bin/${fsc.exec.name}"
-      class="scala.tools.nsc.CompileClient"
-      javaFlags="${java.flags}"/>
-    <chmod perm="ugo+rx"
-      file="${optimised.dir}/bin/${scalac.exec.name}"/>
-    <chmod perm="ugo+rx"
-      file="${optimised.dir}/bin/${scala.exec.name}"/>
-    <chmod perm="ugo+rx"
-      file="${optimised.dir}/bin/${scaladoc.exec.name}"/>
-    <chmod perm="ugo+rx"
-      file="${optimised.dir}/bin/${fsc.exec.name}"/>
-    <fixcrlf
-      srcdir="${optimised.dir}/bin"
-      eol="dos"
-      includes="**/*.bat"/>
-  </target>
-
-  
-<!-- ===========================================================================
-TEST
-============================================================================ -->
-
-  <target name="test" depends="test.stability, test.strap"
-    description="Tests the build for stability"/>
-
-  <!-- Build the bootstrap layer -->
-  <target name="build.strap" depends="setup.quick">
-    <stopwatch name="timer.strap"/>
-  <!-- Build library -->
-    <mkdir dir="${strap.dir}/lib/library"/>
-    <javac
-      srcdir="${src.dir}/library"
-      destdir="${strap.dir}/lib/library"
-      source="1.4" target="1.4" deprecation="yes"
-      classpath="${strap.dir}/lib/library"
-      includes="**/*.java"/>
-    <quick
-      srcdir="${src.dir}/library"
-      destdir="${strap.dir}/lib/library"
-      addparams="${nsc.params}" target="${nsc.target}"
-      deprecation="yes" unchecked="yes"
-      classpath="${strap.dir}/lib/library"
-      includes="scala/Predef.scala"/>
-    <quick
-      srcdir="${src.dir}/library"
-      destdir="${strap.dir}/lib/library"
-      addparams="${nsc.params}" target="${nsc.target}"
-      deprecation="yes" unchecked="yes"
-      classpath="${strap.dir}/lib/library">
-      <include name="**/*.scala"/>
-      <exclude name="scala/Predef.scala"/>
-      <exclude name="scala/dbc/**"/>
-      <exclude name="scala/actors/**"/>
-      <excludesfile name="${nsc.excludes.file}" if="excludes.avail"/>
-    </quick>
-    <echo
-      file="${strap.dir}/lib/library/${lib.prop.name}"
-      message="version.number=${version.number}${line.separator}"
-      append="false"
-    />
-    <echo
-      file="${strap.dir}/lib/library/${lib.prop.name}"
-      message="copyright.string=${copyright.string}${line.separator}"
-      append="true"
-    />
-  <!-- Build DBC -->
-    <mkdir dir="${strap.dir}/lib/dbc"/>
-    <quick
-      srcdir="${src.dir}/dbc"
-      destdir="${strap.dir}/lib/dbc"
-      addparams="${nsc.params}" target="${nsc.target}"
-      deprecation="yes" unchecked="yes">
-      <classpath>
-        <pathelement location="${strap.dir}/lib/library"/>
-        <pathelement location="${strap.dir}/lib/dbc"/>
-      </classpath>
-      <include name="scala/dbc/**/*.scala"/>
-      <excludesfile name="${nsc.excludes.file}" if="excludes.avail"/>
-    </quick>
-  <!-- Build actors library -->
-    <mkdir dir="${strap.dir}/lib/actors"/>
-    <javac
-      srcdir="${src.dir}/actors"
-      destdir="${strap.dir}/lib/actors"
-      source="1.4" target="1.4" deprecation="yes"
-      classpath="${strap.dir}/lib/actors"
-      includes="scala/actors/**/*.java"/>
-    <quick
-      srcdir="${src.dir}/actors"
-      destdir="${strap.dir}/lib/actors"
-      addparams="${nsc.params}" target="${nsc.target}">
-      <classpath>
-        <pathelement location="${strap.dir}/lib/library"/>
-        <pathelement location="${strap.dir}/lib/actors"/>
-      </classpath>
-      <include name="scala/actors/**/*.scala"/>
-      <excludesfile name="${nsc.excludes.file}" if="excludes.avail"/>
-    </quick>
-  <!-- Build compiler -->
-    <mkdir dir="${strap.dir}/lib/compiler"/>
-    <quick
-      srcdir="${src.dir}/compiler"
-      destdir="${strap.dir}/lib/compiler"
-      addparams="${nsc.params}" target="${nsc.target}">
-      <classpath>
-        <pathelement location="${strap.dir}/lib/library"/>
-        <pathelement location="${strap.dir}/lib/compiler"/>
-        <pathelement location="${fjbg.jar}"/>
-        <pathelement location="${msil.jar}"/>
-        <pathelement location="${ant.jar}"/>
-        <pathelement location="${jline.jar}"/>
-      </classpath>
-      <include name="**/*.scala"/>
-      <excludesfile name="${nsc.excludes.file}" if="excludes.avail"/>
-    </quick>
-    <echo
-      file="${strap.dir}/lib/compiler/${comp.prop.name}"
-      message="version.number=${version.number}${line.separator}"
-      append="false"
-    />
-    <echo
-      file="${strap.dir}/lib/compiler/${comp.prop.name}"
-      message="copyright.string=${copyright.string}${line.separator}"
-      append="true"
-    />
-  <!-- Build partest -->
-    <mkdir dir="${strap.dir}/lib/partest"/>
-    <javac
-      srcdir="${src.dir}/partest"
-      destdir="${strap.dir}/lib/partest"
-      source="1.4" target="1.4" deprecation="yes"
-      classpath="${strap.dir}/lib/partest"
-      includes="scala/tools/partest/**/*.java"/>
-    <quick
-      srcdir="${src.dir}/partest"
-      destdir="${strap.dir}/lib/partest"
-      addparams="${nsc.params}" target="${nsc.target}"
-      deprecation="yes" unchecked="yes">
-      <classpath>
-        <pathelement location="${strap.dir}/lib/library"/>
-        <pathelement location="${strap.dir}/lib/compiler"/>
-        <pathelement location="${strap.dir}/lib/actors"/>
-        <pathelement location="${ant.jar}"/>
-      </classpath>
-    </quick>
-    <echo
-      file="${strap.dir}/lib/partest/${par.prop.name}"
-      message="version.number=${version.number}${line.separator}"
-      append="false"
-    />
-    <echo
-      file="${strap.dir}/lib/partest/${par.prop.name}"
-      message="copyright.string=${copyright.string}${line.separator}"
-      append="true"
-    />
-  <!-- Timing the build -->
-    <stopwatch name="timer.strap" action="total"/>
-  <!-- Copy support files to build folder and links external libraries-->
-    <build.support build.dir="${strap.dir}"/>
-    <build.links build.dir="${strap.dir}"/>
-  <!-- Build executable files -->
-    <taskdef
-      name="straptool"
-      classname="scala.tools.ant.ScalaTool"
-      classpathref="quick.classpath"/>
-    <mkdir dir="${strap.dir}/bin"/>
-    <straptool
-      file="${strap.dir}/bin/${scala.exec.name}"
-      class="scala.tools.nsc.MainGenericRunner"
-      javaFlags="${java.flags}"/>
-    <straptool
-      file="${strap.dir}/bin/${scalac.exec.name}"
-      class="scala.tools.nsc.Main"
-      javaFlags="${java.flags}"/>
-    <straptool
-      file="${strap.dir}/bin/${scaladoc.exec.name}"
-      class="scala.tools.nsc.ScalaDoc"
-      javaFlags="${java.flags}"/>
-    <straptool
-      file="${strap.dir}/bin/${fsc.exec.name}"
-      class="scala.tools.nsc.CompileClient"
-      javaFlags="${java.flags}"/>
-    <chmod perm="ugo+rx"
-      file="${strap.dir}/bin/${scalac.exec.name}"/>
-    <chmod perm="ugo+rx"
-      file="${strap.dir}/bin/${scala.exec.name}"/>
-    <chmod perm="ugo+rx"
-      file="${strap.dir}/bin/${scaladoc.exec.name}"/>
-    <chmod perm="ugo+rx"
-      file="${strap.dir}/bin/${fsc.exec.name}"/>
-    <fixcrlf
-      srcdir="${strap.dir}/bin"
-      eol="dos"
-      includes="**/*.bat"/>
-  </target>
-
-  <!-- Compares quick and test level -->
-  <target name="test.stability" depends="build.strap">
-    <if><available file="${stability.tool}"/>
-    <then>                      <!-- use stability tool for fast checking -->
-      <exec executable="${stability.tool}" failonerror="true">
-        <arg value="${quick.dir}"/>
-        <arg value="${strap.dir}"/>
-      </exec>
-    </then><else>               <!-- check stability the slow way -->
-    <checksum totalproperty="quick.md5">
-      <fileset dir="${quick.dir}/lib">
-        <include name="library/**"/>
-        <include name="compiler/**"/>
-      </fileset>
-    </checksum>
-    <delete quiet="yes" failonerror="no">
-      <fileset dir="${quick.dir}" includes="**/*.MD5"/>
-    </delete>
-    <checksum totalproperty="strap.md5">
-      <fileset dir="${strap.dir}/lib">
-        <include name="library/**"/>
-        <include name="compiler/**"/>
-      </fileset>
-    </checksum>
-    <delete quiet="yes" failonerror="no">
-      <fileset dir="${strap.dir}" includes="**/*.MD5"/>
-    </delete>
-    <fail message="Build ${version.number} is not stable">
-      <condition><not>
-        <equals arg1="${quick.md5}" arg2="${strap.md5}"/>
-      </not></condition>
-    </fail>
-    <echo level="info" message="Build ${version.number} is stable."/>
-    </else></if>
-  </target>
-
-  <target name="test.strap" depends="build.strap">
-    <echo level="info" message="Ant test bench is not available yet."/>
-  </target>
-
-<!-- ===========================================================================
-DOCUMENTATION
-============================================================================ -->
-
-  <target name="docs" depends="setup.quick"
-    description="Generated the API for library sources">
-    <mkdir dir="${api-lib.dir}"/>
-    <quickdoc
-      srcdir="${src.dir}"
-      destdir="${api-lib.dir}"
-      sourcepath=""
-      deprecation="yes" unchecked="yes"
-      windowtitle="Scala Library Documentation"
-      doctitle="<div>Scala ${version.number}<br/>API Specification</div>"
-      classpath="${quick.dir}/lib/library${path.separator}${quick.dir}/lib/actors">
-      <include name="dbc/**/*.scala"/>
-      <include name="actors/**/*.scala"/>
-      <include name="library/**/*.scala"/>
-      <excludesfile name="${nsc.excludes.file}" if="excludes.avail"/>
-    </quickdoc>
-  </target>
-
-  <target name="docs.compiler" depends="setup.quick"
-    description="Generated the API for compiler sources">
-    <mkdir dir="${api-comp.dir}"/>
-    <quickdoc
-      srcdir="${src.dir}/compiler"
-      destdir="${api-comp.dir}"
-      sourcepath=""
-      windowtitle="Scala Compiler Documentation"
-      doctitle="<div>Scala ${version.number}<br/>API Specification</div>">
-      <classpath>
-        <pathelement location="${quick.dir}/lib/library"/>
-        <pathelement location="${quick.dir}/lib/compiler"/>
-        <pathelement location="${fjbg.jar}"/>
-        <pathelement location="${msil.jar}"/>
-        <pathelement location="${ant.jar}"/>
-        <pathelement location="${jline.jar}"/>
-      </classpath>
-      <include name="**/*.scala"/>
-      <excludesfile name="${nsc.excludes.file}" if="excludes.avail"/>
-    </quickdoc>
-  </target>
-
-  <target name="docs.manual" depends="setup.quick"
-    description="Generated the manual for the Scala tools">
-    <mkdir dir="${tooldocs.dir}/classes"/>
-    <path id="manual.classpath">
-      <pathelement location="${quick.dir}/lib/library"/>
-      <pathelement location="${tooldocs.dir}/classes"/>
-    </path>
-    <quick
-      srcdir="${src.dir}/manual"
-      destdir="${tooldocs.dir}/classes"
-      addparams="${nsc.params}" target="${nsc.target}"
-      deprecation="yes" unchecked="yes"
-      classpathref="manual.classpath">
-      <include name="**/*.scala"/>
-    </quick>
-    <emit command="fsc"/>
-    <emit command="sbaz"/>
-    <emit command="scala"/>
-    <emit command="scalac"/>
-    <emit command="scaladoc"/>
-    <emit command="scalap"/>
-    <fixcrlf srcdir="${tooldocs.dir}" eol="unix" includes="**/*.1"/>
-    <copy todir="${tooldocs.dir}">
-      <fileset dir="${src.dir}/manual/scala/tools/docutil/resources">
-        <include name="**/*.html"/>
-        <include name="**/*.css"/>
-        <include name="**/*.gif"/>
-        <include name="**/*.png"/>
-      </fileset>
-    </copy>
-  </target>
-
-  <macrodef name="emit">
-    <attribute name="command"/>
-    <sequential>
-      <java classname="scala.tools.docutil.EmitHtml"
-        output="${tooldocs.dir}/@{command}.html"
-        classpathref="manual.classpath"
-        fork="true" logError="yes"
-      >
-        <arg value="scala.man1.@{command}"/>
-      </java>
-      <java classname="scala.tools.docutil.EmitManPage"
-        output="${tooldocs.dir}/@{command}.1"
-        classpathref="manual.classpath"
-        fork="true" logError="yes"
-      >
-        <arg value="scala.man1.@{command}"/>
-      </java>
-    </sequential>
-  </macrodef>
-
-<!-- ===========================================================================
-GENERATES A DISTRIBUTION
-============================================================================ -->
-
-  <target name="dist.devel" depends="init">
-    <property file="${number.file}"/>
-    <property name="version.number"
-      value="${version.major}.${version.minor}.${version.patch}.r${svn.number}"/>
-    <runtarget target="pack"/>
-  </target>
-
-  <target name="dist.patch" depends="init">
-    <property file="${number.file}"/>
-    <property name="version.number"
-      value="${version.major}.${version.minor}.${version.patch}.${version.suffix}"/>
-    <runtarget target="pack"/>
-  </target>
-
-  <target name="dist.minor" depends="init">
-    <property file="${number.file}"/>
-    <property name="version.number"
-      value="${version.major}.${version.minor}.${version.patch}.${version.suffix}"/>
-    <runtarget target="pack"/>
-  </target>
-
-  <target name="dist"
-    depends="clean.build, test, build.dist"
-    description="Creates a (stability-)tested, complete Scala distribution *from scratch*"/>
-
-  <target name="pack"
-    depends="build.archive, build.sbaz"
-    description="Packs a distribution for SBaz and ZIP/TAR"/>
-
-  <target name="binaries"
-    depends="setup, build.strap"
-    description="Creates a binary Scala distribution">
-    <property name="dist.current.dir"
-              value="${dist.dir}/scala-${version.number}"/>
-    <if><and>
-      <isset property="os.unix"/>
-      <isset property="dist.resource"/></and>
-    <then>
-      <symlink
-        link="${dist.dir}"
-        resource="${dist.resource}" overwrite="yes" failonerror="no"/>
-      <touch file="${dist.dir}/is_symlink" verbose="no"/>
-    </then></if>
-    <mkdir dir="${dist.current.dir}"/>
-  <!-- Copy all requires libraries -->
-    <mkdir dir="${dist.current.dir}/lib"/>
-    <property name="ant.version.number" value="1.6.0"/>
-    <!-- see http://swik.net/Spring/Interface21+Team+Blog/Creating+OSGi+bundles/b2yoy -->
-    <propertyregex
-      property="osgi.version.number" input="${version.number}"
-      regexp="([^-]*)(-.*)?" select="\1"
-    />
-    <echo level="verbose" message="OSGi version: ${osgi.version.number}"/>
-    <jar destfile="${dist.current.dir}/lib/${comp.jar.name}">
-      <fileset dir="${strap.dir}/lib/compiler"/>
-      <zipfileset src="${fjbg.jar}"/>
-      <zipfileset src="${msil.jar}"/>
-      <manifest>
-        <attribute name="Signature-Version" value="${version.number}"/>
-        <attribute name="Built-By" value="${user.name}"/>
-        <attribute name="Main-Class" value="scala.tools.nsc.Main"/>
-        <attribute name="Class-Path" value="${lib.jar.name}"/>
-        <section name="scala/tools/nsc">
-          <attribute name="Extension-Name" value="scala.tools.nsc"/>
-          <attribute name="Specification-Title" value="Scala Compiler"/>
-          <attribute name="Specification-Version" value="${version.number}"/>
-          <attribute name="Specification-Vendor" value="${vendor.name}"/>
-          <attribute name="Implementation-Title" value="scala.tools.nsc"/>
-          <attribute name="Implementation-Version" value="${version.number}"/>
-          <attribute name="Implementation-Vendor" value="${vendor.name}"/>
-        </section>
-        <attribute name="Bundle-DocURL" value="http://www.scala-lang.org/"/>
-        <attribute name="Bundle-ManifestVersion" value="2"/>
-        <attribute name="Bundle-Name" value="Scala Compiler Bundle"/>
-        <attribute name="Bundle-SymbolicName" value="scala_compiler"/>
-        <attribute name="Bundle-Version" value="${osgi.version.number}"/>
-        <attribute name="Bundle-Vendor" value="${vendor.name}"/>
-        <attribute name="Export-Package" value="scala.tools.ant;version="${osgi.version.number}",scala.tools.nsc;version="${osgi.version.number}",scala.tools.nsc.ast;version="${osgi.version.number}",scala.tools.nsc.ast.parser;version="${osgi.version.number}",scala.tools.nsc.backend;version="${osgi.version.number}",scala.tools.nsc.doc;version="${osgi.version.number}",scala.tools.nsc.io;version="${osgi.version.number}",scala.tools.nsc [...]
-        <attribute name="Import-Package" value="org.apache.ant.tools;version="${ant.version.number}";resolution:=optional,org.apache.ant.tools.taskdefs;version="${ant.version.number}";resolution:=optional,org.apache.ant.types;version="${ant.version.number}";resolution:=optional,org.apache.ant.tools.util;version="${ant.version.number}";resolution:=optional,org.xml.sax"/>
-        <attribute name="Bundle-RequiredExecutionEnvironment" value="J2SE-1.4"/>
-      </manifest>
-    </jar>
-    <jar destfile="${dist.current.dir}/lib/${lib.jar.name}">
-      <fileset dir="${strap.dir}/lib/library"/>
-      <fileset dir="${strap.dir}/lib/actors"/>
-      <manifest>
-        <attribute name="Signature-Version" value="${version.number}"/>
-        <attribute name="Built-By" value="${user.name}"/>
-        <attribute name="Main-Class" value="scala.util.Properties"/>
-        <section name="scala">
-          <attribute name="Extension-Name" value="scala"/>
-          <attribute name="Specification-Title" value="Scala Library"/>
-          <attribute name="Specification-Version" value="${version.number}"/>
-          <attribute name="Specification-Vendor" value="${vendor.name}"/>
-          <attribute name="Implementation-Title" value="scala"/>
-          <attribute name="Implementation-Version" value="${version.number}"/>
-          <attribute name="Implementation-Vendor" value="${vendor.name}"/>
-        </section>
-        <attribute name="Bundle-DocURL" value="http://www.scala-lang.org/"/>
-        <attribute name="Bundle-ManifestVersion" value="2"/>
-        <attribute name="Bundle-Name" value="Scala Library Bundle"/>
-        <attribute name="Bundle-SymbolicName" value="scala_library"/>
-        <attribute name="Bundle-Version" value="${osgi.version.number}"/>
-        <attribute name="Bundle-Vendor" value="${vendor.name}"/>
-        <attribute name="Export-Package" value="scala;version="${osgi.version.number}",scala.actors;version="${osgi.version.number}",scala.actors.remote;version="${osgi.version.number}",scala.collection;version="${osgi.version.number}",scala.collection.immutable;version="${osgi.version.number}",scala.collection.jcl;version="${osgi.version.number}",scala.collection.mutable;version="${osgi.version.number}",scala.compat;version="${ [...]
-        <attribute name="Import-Package" value="javax.xml.parsers,org.xml.sax,org.xml.sax.helpers"/>
-        <attribute name="Bundle-RequiredExecutionEnvironment" value="J2SE-1.4"/>
-      </manifest>
-    </jar>
-    <jar destfile="${dist.current.dir}/lib/${dbc.jar.name}">
-      <fileset dir="${strap.dir}/lib/dbc"/>
-      <manifest>
-        <attribute name="Signature-Version" value="${version.number}"/>
-        <attribute name="Built-By" value="${user.name}"/>
-        <attribute name="Class-Path" value="${lib.jar.name}"/>
-        <section name="scala/dbc">
-          <attribute name="Extension-Name" value="scala.dbc"/>
-          <attribute name="Specification-Title" value="Scala DBC Library"/>
-          <attribute name="Specification-Version" value="${version.number}"/>
-          <attribute name="Specification-Vendor" value="${vendor.name}"/>
-          <attribute name="Implementation-Title" value="scala.dbc"/>
-          <attribute name="Implementation-Version" value="${version.number}"/>
-          <attribute name="Implementation-Vendor" value="${vendor.name}"/>
-        </section>
-        <attribute name="Bundle-DocURL" value="http://www.scala-lang.org/"/>
-        <attribute name="Bundle-ManifestVersion" value="2"/>
-        <attribute name="Bundle-Name" value="Scala DBC Library Bundle"/>
-        <attribute name="Bundle-SymbolicName" value="scala_dbc_library"/>
-        <attribute name="Bundle-Version" value="${osgi.version.number}"/>
-        <attribute name="Bundle-Vendor" value="${vendor.name}"/>
-        <attribute name="Export-Package" value="scala.dbc;version="${osgi.version.number}",scala.dbc.datatype;version="${osgi.version.number}",scala.dbc.exception;version="${osgi.version.number}",scala.dbc.result;version="${osgi.version.number}",scala.dbc.statement;version="${osgi.version.number}",scala.dbc.statement.expression;version="${osgi.version.number}",scala.dbc.syntax;version="${osgi.version.number}",scala.dbc.value;version [...]
-        <attribute name="Import-Package" value="scala;version="${osgi.version.number}",scala.compat;version="${osgi.version.number}""/>
-        <attribute name="Bundle-RequiredExecutionEnvironment" value="J2SE-1.4"/>
-      </manifest>
-    </jar>
-    <jar destfile="${dist.current.dir}/lib/${partest.jar.name}">
-      <fileset dir="${strap.dir}/lib/partest"/>
-      <manifest>
-        <attribute name="Signature-Version" value="${version.number}"/>
-        <attribute name="Built-By" value="${user.name}"/>
-        <attribute name="Main-Class" value="scala.tools.partest.TestRunner"/>
-        <attribute name="Class-Path" value="${lib.jar.name}"/>
-        <section name="scala/tools/partest">
-          <attribute name="Extension-Name" value="scala.tools.partest"/>
-          <attribute name="Specification-Title" value="Scala Test Utility"/>
-          <attribute name="Specification-Version" value="${version.number}"/>
-          <attribute name="Specification-Vendor" value="${vendor.name}"/>
-          <attribute name="Implementation-Title" value="scala.tools.partest"/>
-          <attribute name="Implementation-Version" value="${version.number}"/>
-          <attribute name="Implementation-Vendor" value="${vendor.name}"/>
-        </section>
-        <attribute name="Bundle-DocURL" value="http://www.scala-lang.org/"/>
-        <attribute name="Bundle-ManifestVersion" value="2"/>
-        <attribute name="Bundle-Name" value="Scala Test Bundle"/>
-        <attribute name="Bundle-SymbolicName" value="scala_compiler"/>
-        <attribute name="Bundle-Version" value="${osgi.version.number}"/>
-        <attribute name="Bundle-Vendor" value="${vendor.name}"/>
-        <attribute name="Export-Package" value="scala.tools.partest;version="${osgi.version.number}",scala.tools.partest.utils;version="${osgi.version.number}""/>
-        <attribute name="Import-Package" value="javax.swing"/>
-        <attribute name="Bundle-RequiredExecutionEnvironment" value="J2SE-1.4"/>
-      </manifest>
-    </jar>
-    <copy todir="${dist.current.dir}/lib" file="${jline.jar}"/>
-
-    <!-- build source jars -->
-    <mkdir dir="${dist.current.dir}/src"/>
-    <jar
-      destfile="${dist.current.dir}/src/${libsrc.jar.name}">
-      <fileset dir="${src.dir}/library"/>
-      <fileset dir="${src.dir}/actors"/>
-    </jar>
-    <jar
-      destfile="${dist.current.dir}/src/${dbcsrc.jar.name}"
-      basedir="${src.dir}/dbc"
-      includes="**/*.scala"
-      />
-    <jar
-      destfile="${dist.current.dir}/src/${parsrc.jar.name}"
-      basedir="${src.dir}/partest"
-      includes="**/*.scala"
-      />
-    <jar
-      destfile="${dist.current.dir}/src/${compsrc.jar.name}"
-      basedir="${src.dir}/compiler"
-      includes="**/*.scala"
-    />
-
-    <!-- Copy executable files -->
-    <mkdir dir="${dist.current.dir}/bin"/>
-    <copy todir="${dist.current.dir}/bin">
-      <fileset dir="${strap.dir}/bin"/>
-    </copy>
-    <chmod perm="ugo+rx" file="${dist.current.dir}/bin/${scalac.exec.name}"/>
-    <chmod perm="ugo+rx" file="${dist.current.dir}/bin/${scala.exec.name}"/>
-    <chmod perm="ugo+rx" file="${dist.current.dir}/bin/${scaladoc.exec.name}"/>
-    <chmod perm="ugo+rx" file="${dist.current.dir}/bin/${fsc.exec.name}"/>
-    <!-- Recreate the 'latest' link to point to this distribution -->
-    <if><isset property="os.win"/>
-      <then>
-        <copy todir="${dist.dir}/latest">
-          <fileset dir="${dist.current.dir}"/>
-        </copy>
-      </then>
-      <else>
-        <symlink
-          link="${dist.dir}/latest"
-          resource="${dist.current.dir}"
-          overwrite="yes" failonerror="no"/>
-      </else>
-    </if>
-  </target>
-
-  <target name="build.dist"
-    depends="binaries,docs,docs.manual"
-    description="Creates the latest Scala distribution">
-  <!-- Copy the API, examples and man -->
-    <copy todir="${dist.current.dir}/doc/scala">
-      <fileset dir="${docs.dir}" includes="README,LICENSE"/>
-    </copy>
-    <copy todir="${dist.current.dir}/doc/scala/api">
-      <fileset dir="${api-lib.dir}"/>
-    </copy>
-    <copy todir="${dist.current.dir}/doc/scala/examples">
-      <fileset dir="${docs.dir}/examples"/>
-    </copy>
-    <copy todir="${dist.current.dir}/man/man1">
-      <fileset dir="${tooldocs.dir}" includes="**/*.1"/>
-    </copy>
-    <copy todir="${dist.current.dir}/doc/scala/tools">
-      <fileset dir="${tooldocs.dir}">
-        <include name="**/*.html"/>
-        <include name="**/*.css"/>
-        <include name="**/*.gif"/>
-        <include name="**/*.png"/>
-      </fileset>
-    </copy>
-    <stopwatch name="timer.dist" action="total"/>
-  </target>
-
-  <!-- Create the SBaz packages -->
-  <target name="build.sbaz" depends="build.dist,msil,android">
-    <property name="sbaz.universe" value="http://www.scala-lang.org/downloads/packages"/>
-    <mkdir dir="${dist.dir}"/>
-  <!-- Create the Scala library package -->
-    <quicksbaz
-      file="${dist.dir}/scala-library-${version.number}.sbp"
-      adfile="${dist.dir}/scala-library-${version.number}.advert"
-      name="scala-library"
-      version="${version.number}"
-      desc="The Scala library. This is the minimal requirement to run any Scala program."
-      link="${sbaz.universe}/scala-library-${version.number}.sbp">
-      <libset dir="${dist.current.dir}/lib" includes="${lib.jar.name},${dbc.jar.name}"/>
-      <srcset dir="${dist.current.dir}/src" includes="${libsrc.jar.name},${dbcsrc.jar.name}"/>
-    </quicksbaz>
-  <!-- Create the Scala developer package -->
-    <quicksbaz
-      file="${dist.dir}/scala-devel-${version.number}.sbp"
-      adfile="${dist.dir}/scala-devel-${version.number}.advert"
-      name="scala-devel"
-      version="${version.number}"
-      desc="The Scala developer tools. This contains everything that is required to write, test and document new Scala programs."
-      depends="scala-library"
-      link="${sbaz.universe}/scala-devel-${version.number}.sbp">
-      <binset dir="${dist.current.dir}/bin" includes="**"/>
-      <docset dir="${dist.current.dir}/doc" includes="**" excludes="**/scala/api/**,**/scala/tools/**"/>
-      <libset dir="${dist.current.dir}/lib" includes="${comp.jar.name},${jline.jar.name}"/>
-      <manset dir="${dist.current.dir}/man" includes="**"/>
-      <srcset dir="${dist.current.dir}/src" includes="${compsrc.jar.name}"/>
-    </quicksbaz>
-  <!-- Create the Scala developer docs package -->
-    <quicksbaz
-      file="${dist.dir}/scala-devel-docs-${version.number}.sbp"
-      adfile="${dist.dir}/scala-devel-docs-${version.number}.advert"
-      name="scala-devel-docs"
-      version="${version.number}"
-      desc="The Scala developer documentation. This contains all developer documentation."
-      link="${sbaz.universe}/scala-devel-docs-${version.number}.sbp">
-      <docset dir="${dist.current.dir}/doc" includes="**/scala/api/**,**/scala/tools/**"/>
-    </quicksbaz>
-  <!-- Creates the empty umbrella Scala package -->
-    <quicksbaz
-      file="${dist.dir}/scala-${version.number}.sbp"
-      adfile="${dist.dir}/scala-${version.number}.advert"
-      name="scala"
-      version="${version.number}"
-      desc="The base Scala package that contains everything needed to start using Scala."
-      depends="scala-library,scala-devel"
-      link="${sbaz.universe}/scala-${version.number}.sbp"/>
-  <!-- Creates the Scala test package -->
-    <quicksbaz
-      file="${dist.dir}/scala-test-${version.number}.sbp"
-      adfile="${dist.dir}/scala-test-${version.number}.advert"
-      name="scala-test"
-      version="${version.number}"
-      desc="The Scala test package contains everything needed to test Scala."
-      link="${sbaz.universe}/scala-test-${version.number}.sbp">
-      <binset dir="${basedir}/test"
-        includes="clitest,diff/diff.*,diff/lib*.dll,scalatest,scalatest.bat,partest"/>
-      <miscset
-        dir="${basedir}/test"
-        includes="files/**/*.args,files/**/*.check,files/**/*.jar,files/**/*.java,files/**/*.scala,files/cli/**/*.check.*,files/jvm/*.so,files/shootout/*.javaopts,files/shootout/*.runner,files/shootout/*.txt"/>
-      <srcset dir="${dist.current.dir}/src" includes="${parsrc.jar.name}"/>
-      <libset dir="${dist.current.dir}/lib" includes="${partest.jar.name}"/>
-    </quicksbaz>
-  <!-- Creates the MSIL package -->
-    <quicksbaz
-      file="${dist.dir}/scala-msil-${version.number}.sbp"
-      adfile="${dist.dir}/scala-msil-${version.number}.advert"
-      name="scala-msil"
-      version="${version.number}"
-      desc="The Scala MSIL package contains everything needed to use Scala on .NET."
-      depends="scala-library,scala-devel"
-      link="${sbaz.universe}/scala-msil-${version.number}.sbp">
-      <binset dir="${quick.dir}/bin" includes="scala*net*"/>
-      <libset dir="${quick.dir}/lib" includes="*.dll"/>
-    </quicksbaz>
-  <!-- Creates the CLDC package -->
-<!--
-    <quicksbaz
-      file="${dist.dir}/scala-cldc-${version.number}.sbp"
-      adfile="${dist.dir}/scala-cldc-${version.number}.advert"
-      name="scala-cldc"
-      version="${version.number}"
-      desc="The Scala CLDC package contains everything needed to use Scala on CLDC devices."
-      link="${sbaz.universe}/scala-cldc-${version.number}.sbp">
-      <libset dir="${cldc.dir}/lib" includes="*.jar"/>
-    </quicksbaz>
--->
-  <!-- Creates the Android package -->
-    <if><isset property="android.supported"/><then>
-      <copy todir="${dist.current.dir}/doc/scala-android/examples">
-        <fileset dir="${docs.dir}/android-examples">
-          <exclude name="**/R.java"/>
-        </fileset>
-      </copy>
-      <quicksbaz
-        file="${dist.dir}/scala-android-${version.number}.sbp"
-        adfile="${dist.dir}/scala-android-${version.number}.advert"
-        name="scala-android"
-        version="${version.number}"
-        desc="The Scala Android package contains everything needed to use Scala on Android."
-        link="${sbaz.universe}/scala-android-${version.number}.sbp">
-        <libset dir="${android.dir}/lib" includes="*.jar"/>
-        <docset dir="${dist.current.dir}/doc/scala-android" includes="**"/>
-      </quicksbaz>
-    </then></if>
-  </target>
-
-  <target name="build.archive" depends="build.dist">
-    <tar
-      destfile="${dist.dir}/scala-${version.number}.tgz"
-      compression="gzip">
-      <tarfileset
-        prefix="scala-${version.number}"
-        dir="${dist.current.dir}"
-        includes="bin/**" mode="755"
-      />
-      <tarfileset
-        prefix="scala-${version.number}"
-        dir="${dist.current.dir}"
-        excludes="bin/**"
-      />
-    </tar>
-    <checksum
-      file="${dist.dir}/scala-${version.number}.tgz"
-      forceOverwrite="yes"
-      fileext=".md5"/>
-  <!-- Create zip archive -->
-    <zip
-      destfile="${dist.dir}/scala-${version.number}.zip">
-      <zipfileset
-        prefix="scala-${version.number}"
-        dir="${dist.current.dir}"
-      />
-    </zip>
-    <checksum
-      file="${dist.dir}/scala-${version.number}.zip"
-      forceOverwrite="yes"
-      fileext=".md5"/>
-  <!-- Create source archive -->
-    <copy todir="${dist.dir}/scala-${version.number}">
-      <fileset
-        dir="${basedir}"
-        excludes="build,build/**,dists/**"
-      />
-    </copy>
-    <tar basedir="${dist.dir}"
-      destfile="${dist.dir}/scala-${version.number}-sources.tgz"
-      compression="gzip"
-      includes="scala-${version.number}/**"
-    />
-  </target>
-
-<!-- ===========================================================================
-CLEAN
-============================================================================ -->
-
-  <macrodef name="remove">
-    <attribute name="dir"/>
-    <sequential>
-      <if>
-        <available file="@{dir}/is_symlink"/>
-      <then>
-        <delete includeemptydirs="true" quiet="yes" failonerror="no">
-          <fileset dir="@{dir}" includes="**/*"/>
-        </delete>
-      </then></if>
-      <delete dir="@{dir}" includeemptydirs="yes" quiet="yes" failonerror="no"/>
-    </sequential>
-  </macrodef>
-
-  <target name="clean" depends="ant-init" description="Removes QUICK, STRAP and API build products">
-    <remove dir="${quick.dir}"/>
-    <remove dir="${strap.dir}"/>
-    <remove dir="${api.dir}"/>
-  </target>
-
-  <target name="clean.build" depends="ant-init"
-    description="Removes all build products">
-    <remove dir="${build.dir}"/>
-  </target>
-
-  <target name="clean.msil" depends="ant-init" description="Removes all MSIL build products">
-    <remove dir="${msil.dir}"/>
-  </target>
-
-<!--
-  <target name="clean.cldc" depends="ant-init" description="Removes all CLDC build products">
-    <remove dir="${cldc.dir}"/>
-  </target>
--->
-
-  <target name="clean.all" depends="ant-init"
-    description="Removes all build products and distributions">
-    <remove dir="${build.dir}"/>
-    <remove dir="${dist.dir}"/>
-  </target>
-
-  <target name="clean.unfreeze" depends="init">
-    <delete file="${locker.dir}/complete" quiet="yes" failonerror="no"/>
-    <remove dir="${quick.dir}"/>
-  </target>
-
-</project>
diff --git a/src/build/pack.xml b/src/build/pack.xml
index bed8d1e..d75e36c 100644
--- a/src/build/pack.xml
+++ b/src/build/pack.xml
@@ -54,6 +54,10 @@ MAIN DISTRIBUTION PACKAGING
         <exclude name="dists/**"/>
         <exclude name="logs/**"/>
         <exclude name="sandbox/**"/>
+        <exclude name="test/partest"/>
+      </tarfileset>
+      <tarfileset dir="${basedir}" prefix="scala-${version.number}-sources" filemode="755">
+        <include name="test/partest"/>
       </tarfileset>
     </tar>
     <checksum file="${dists.dir}/archives/scala-${version.number}-sources.tgz" fileext=".md5"/>
@@ -97,7 +101,9 @@ MAIN DISTRIBUTION SBAZ
       <binset
           dir="${dist.dir}/bin"
           includes="scala,scala.bat,scalac,scalac.bat,scaladoc,scaladoc.bat,fsc,fsc.bat"/>
-      <libset dir="${dist.dir}/lib" includes="scala-compiler.jar"/>
+      <libset dir="${dist.dir}/lib" includes="scala-compiler.jar,jline.jar"/>
+      <miscset dir="${dist.dir}/misc/scala-devel"
+        includes="plugins/continuations.jar"/>
       <manset dir="${dist.dir}/man" includes="**"/>
       <srcset dir="${dist.dir}/src" includes="scala-compiler-src.jar"/>
     </sbaz>
@@ -114,13 +120,28 @@ MAIN DISTRIBUTION SBAZ
       <binset dir="${basedir}/test"
         includes="clitest,diff/diff.*,diff/lib*.dll,partest,partest.bat"/>
       <miscset dir="${basedir}/test"
-        includes="files/**/*.args,files/**/*.check,files/**/*.dll,files/**/*.jar,files/**/*.java,files/**/*.scala,files/**/*.flags,files/cli/**/*.check.*,files/jvm/*.so,files/shootout/*.javaopts,files/shootout/*.runner,files/shootout/*.txt"/>
+        includes="files/**/*.args,files/**/*.check,files/**/*.dll,files/**/*.jar,files/**/*.java,files/**/*.scala,files/**/*.flags,files/cli/**/*.check.*,files/jvm/*.so,files/shootout/*.javaopts,files/shootout/*.runner,files/shootout/*.txt,files/**/*.test"/>
         <!-- <srcset dir="${dist.dir}/src" includes="scala-partest-src.jar"/> -->
       <libset dir="${dist.dir}/lib" includes="scala-partest.jar"/>
+      <libset dir="${lib.dir}" includes="scalacheck.jar"/>
+    </sbaz>
+  </target>
+
+  <target name="pack-sbaz.scalap" depends="pack-sbaz.test">
+    <sbaz
+      file="${dists.dir}/sbaz/scalap-${version.number}.sbp"
+      adfile="${dists.dir}/sbaz/scalap-${version.number}.advert"
+      name="scalap"
+      version="${version.number}"
+      desc="The scalap package contains the Scala classfile decoder."
+      link="${sbaz.universe}/scalap-${version.number}.sbp">
+      <binset dir="${dist.dir}/bin"
+        includes="scalap,scalap.bat"/>
+      <libset dir="${dist.dir}/lib" includes="scalap.jar"/>
     </sbaz>
   </target>
   
-  <target name="pack-sbaz.doc" depends="pack-sbaz.test">
+  <target name="pack-sbaz.doc" depends="pack-sbaz.scalap">
     <sbaz
       file="${dists.dir}/sbaz/scala-devel-docs-${version.number}.sbp"
       adfile="${dists.dir}/sbaz/scala-devel-docs-${version.number}.advert"
@@ -172,9 +193,29 @@ MAIN DISTRIBUTION SBAZ
     <mvn-copy-lib mvn.artifact.name="scala-compiler"/>
     <mvn-copy-lib mvn.artifact.name="scala-dbc"/>
     <mvn-copy-lib mvn.artifact.name="scala-swing"/>
+    <mvn-copy-lib mvn.artifact.name="scala-partest"/>
+    <mvn-copy-lib mvn.artifact.name="scalap"/>
+  </target>
+
+  <target name="pack-maven.plugins" depends="pack-maven.start">
+    <macrodef name="mvn-copy-plugin">
+      <attribute name="mvn.artifact.name"/>
+      <sequential>
+        <mkdir dir="${dists.dir}/maven/${version.number}/plugins/@{mvn.artifact.name}"/>
+        <copy todir="${dists.dir}/maven/${version.number}/plugins/@{mvn.artifact.name}">
+          <fileset dir="${dist.dir}/misc/scala-devel/plugins/">
+            <filename name="@{mvn.artifact.name}.jar"/>
+          </fileset>
+          <fileset dir="${src.dir}/build/maven/">
+            <filename name="@{mvn.artifact.name}-plugin-pom.xml"/>
+          </fileset>
+        </copy>
+      </sequential>
+    </macrodef>
+    <mvn-copy-plugin mvn.artifact.name="continuations"/>
   </target>
 
-  <target name="pack-maven.docs" depends="pack-maven.libs">
+  <target name="pack-maven.docs" depends="pack-maven.libs, pack-maven.plugins">
     <jar destfile="${dists.dir}/maven/${version.number}/scala-library/scala-library-docs.jar"
          basedir="${build-docs.dir}/library">
       <include name="**/*"/>
@@ -241,60 +282,6 @@ JAVA FOUR DISTRIBUTION PACKAGING
   <target name="fourpack-archives.done" depends="fourpack-archives.zip"/>
 
 <!-- ===========================================================================
-MSIL DISTRIBUTION PACKAGING
-============================================================================ -->
-
-  <!-- MSIL Archive -->
-
-  <target name="msilpack-archives.start">
-    <mkdir dir="${dists.dir}/archives"/>
-  </target>
-
-  <target name="msilpack-archives.tar" depends="msilpack-archives.start">
-    <tar destfile="${dists.dir}/archives/scala-${version.number}-msil.tgz"
-         compression="gzip" longfile="gnu">
-      <tarfileset dir="${dists.dir}/scala-msil-${version.number}" prefix="scala-${version.number}-msil"
-        includes="bin/**" mode="755"/>
-      <!-- Inlcude only dll's. Using scala-msil depends on having a scala distribution -->
-      <tarfileset dir="${dists.dir}/scala-msil-${version.number}" prefix="scala-${version.number}-msil"
-        includes="lib/*.dll"/>
-    </tar>
-    <checksum file="${dists.dir}/archives/scala-${version.number}-msil.tgz" fileext=".md5"/>
-  </target>
-
-  <target name="msilpack-archives.zip" depends="msilpack-archives.tar">
-    <zip destfile="${dists.dir}/archives/scala-${version.number}-msil.zip">
-      <zipfileset dir="${dists.dir}/scala-msil-${version.number}" prefix="scala-${version.number}-msil"
-        includes="bin/**,lib/*.dll"/>
-    </zip>
-    <checksum file="${dists.dir}/archives/scala-${version.number}-msil.zip" fileext=".md5"/>
-  </target>
-  
-  <target name="msilpack-archives.done" depends="msilpack-archives.zip"/>
-
-  <!-- MSIL Sbaz package -->
-
-  <target name="msilpack-sbaz.start">
-    <mkdir dir="${dists.dir}/sbaz"/>
-  </target>
-
-  <target name="msilpack-sbaz.msil" depends="msilpack-sbaz.start">
-   <sbaz
-      file="${dists.dir}/sbaz/scala-msil-${version.number}.sbp"
-      adfile="${dists.dir}/sbaz/scala-msil-${version.number}.advert"
-      name="scala-msil"
-      version="${version.number}"
-      desc="The Scala MSIL package contains everything needed to use Scala on .NET."
-      depends="scala-library,scala-devel"
-      link="${sbaz.universe}/scala-msil-${version.number}.sbp">
-      <binset dir="${dists.dir}/scala-msil-${version.number}/bin" includes="scala*-net*"/>
-      <libset dir="${dists.dir}/scala-msil-${version.number}/lib" includes="*.dll"/>
-    </sbaz>
-  </target>
-
-  <target name="msilpack-sbaz.done" depends="msilpack-sbaz.msil"/>
-
-<!-- ===========================================================================
 MISCELLANEOUS
 ============================================================================ -->
 
@@ -302,8 +289,6 @@ MISCELLANEOUS
 
   <target name="fourpack-all.done" depends="fourpack-archives.done"/>
 
-  <target name="msilpack-all.done" depends="msilpack-archives.done, msilpack-sbaz.done"/>
-
 <!-- ===========================================================================
 MISCELLANEOUS
 ============================================================================ -->
diff --git a/src/cldc-library/scala/Array.scala b/src/cldc-library/scala/Array.scala
deleted file mode 100644
index ee6ebab..0000000
--- a/src/cldc-library/scala/Array.scala
+++ /dev/null
@@ -1,430 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: Array.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala
-
-
-import Predef._
-import compat.Platform.arraycopy
-
-/** This object contains utility methods operating on arrays.
- *
- *  @author Martin Odersky
- *  @version 1.0
- */
-object Array {
-
-  /** Copy one array to another.
-   *  Equivalent to
-   *    <code>System.arraycopy(src, srcPos, dest, destPos, length)</code>,
-   *  except that this works also for polymorphic and boxed arrays.
-   *
-   *  @param src     ...
-   *  @param srcPos  ...
-   *  @param dest    ...
-   *  @param destPos ...
-   *  @param length  ...
-   */
-  def copy(src: AnyRef, srcPos: Int, dest: AnyRef, destPos: Int, length: Int): Unit = src match {
-    case xs: runtime.BoxedArray =>
-      xs.copyTo(srcPos, dest, destPos, length)
-    case _ =>
-      dest match {
-        case xs: runtime.BoxedArray =>
-          xs.copyFrom(src, srcPos, destPos, length)
-        case _ =>
-          arraycopy(src, srcPos, dest, destPos, length)
-      }
-  }
-
-  /** Concatenate all argument arrays into a single array.
-   *
-   *  @param xs ...
-   */
-  def concat[T](xs: Array[T]*) = {
-    var len = 0
-    for (x <- xs) len += x.length
-    val result = new Array[T](len)
-    var start = 0
-    for (x <- xs) {
-      copy(x, 0, result, start, x.length)
-      start += x.length
-    }
-    result
-  }
-
-  /** Create a an array containing of successive integers.
-   *
-   *  @param from the value of the first element of the array
-   *  @param end  the value of the last element fo the array plus 1
-   *  @return the sorted array of all integers in range [from;end).
-   */
-  def range(start: Int, end: Int): Array[Int] = {
-    val result = new Array[Int](end - start)
-    for (i <- start until end) result(i - start) = i
-    result
-  }
-
-  /** Create an array with given elements.
-   *
-   *  @param xs the elements to put in the array
-   *  @return the array containing elements xs.
-   */
-  def apply[A <: AnyRef](xs: A*): Array[A] = {
-    val array = new Array[A](xs.length)
-    var i = 0
-    for (x <- xs.elements) { array(i) = x; i += 1 }
-    array
-  }
-
-
-/* The following metod clashes with the previous one, and has therefore been
- * removed. Note that this is a choice between efficiency and generality.
- * The previous factory method is more efficient than the one that has been
- * commented out. Since it is anyway possible to create a polymorphic array
- * using
- *        new Array[T]
- * it was preferred to restrict the definition of the factory method.
-
-   def Array[A](xs: A*): Array[A] = {
-    val array = new Array[A](xs.length)
-    var i = 0
-    for (x <- xs.elements) { array(i) = x; i += 1 }
-    array
-  }
-*/
-
-  def apply(xs: Boolean*): Array[Boolean] = {
-    val array = new Array[Boolean](xs.length)
-    var i = 0
-    for (x <- xs.elements) { array(i) = x; i += 1 }
-    array
-  }
-  def apply(xs: Byte*): Array[Byte] = {
-    val array = new Array[Byte](xs.length)
-    var i = 0
-    for (x <- xs.elements) { array(i) = x; i += 1 }
-    array
-  }
-  def apply(xs: Short*): Array[Short] = {
-    val array = new Array[Short](xs.length)
-    var i = 0
-    for (x <- xs.elements) { array(i) = x; i += 1 }
-    array
-  }
-  def apply(xs: Char*): Array[Char] = {
-    val array = new Array[Char](xs.length)
-    var i = 0
-    for (x <- xs.elements) { array(i) = x; i += 1 }
-    array
-  }
-  def apply(xs: Int*): Array[Int] = {
-    val array = new Array[Int](xs.length)
-    var i = 0
-    for (x <- xs.elements) { array(i) = x; i += 1 }
-    array
-  }
-  def apply(xs: Long*): Array[Long] = {
-    val array = new Array[Long](xs.length)
-    var i = 0
-    for (x <- xs.elements) { array(i) = x; i += 1 }
-    array
-  }
-  def apply(xs: Unit*): Array[Unit] = {
-    val array = new Array[Unit](xs.length)
-    var i = 0
-    for (x <- xs.elements) { array(i) = x; i += 1 }
-    array
-  }
-
-  /** Create an array containing several copies of an element.
-   *
-   *  @param n    the length of the resulting array
-   *  @param elem the element composing the resulting array
-   *  @return     an array composed of n elements all equal to elem
-   */
-  def make[A](n: Int, elem: A): Array[A] = {
-    val a = new Array[A](n)
-    var i = 0
-    while (i < n) {
-      a(i) = elem
-      i += 1
-    }
-    a
-  }
-
- /** This method is called as a result of a pattern match { case Array(...) => } or val Array(...) = ....
-   *
-   *  @param x the selector value
-   *  @return  array wrapped in an option
-   */
-   def unapplySeq[A](x: Array[A]): Option[Seq[A]] = Some(x)
-
-   trait Projection[A] extends RandomAccessSeq.MutableProjection[A] {
-     protected def newArray[B >: A](length : Int, elements : Iterator[A]) : Array[B]
-     override def toArray[B >: A] = (newArray(length, elements))//:Any).asInstanceOf[Array[B]]
-     override def force : Array[A] = toArray
-     override def drop( from: Int) = slice(from, length)
-     override def take(until: Int) = slice(0, until)
-     override def slice(from0 : Int, until0 : Int) : Projection[A] = new RandomAccessSeq.MutableSlice[A] with Projection[A] {
-       override def from = from0
-       override def until = until0
-       override def underlying = Projection.this
-       override protected def newArray[B >: A](length : Int, elements : Iterator[A]) =
-         underlying.newArray(length, elements)
-       override def slice(from0 : Int, until0 : Int) =
-         Projection.this.slice(from + from0, from + until0)
-     }
-     override def reverse : Projection[A] = new Projection[A] {
-       override protected def newArray[B >: A](length : Int, elements : Iterator[A]) =
-         Projection.this.newArray(length, elements)
-       def update(idx : Int, what : A) : Unit = Projection.this.update(length - idx - 1, what)
-       def length = Projection.this.length
-       def apply(idx : Int) = Projection.this.apply(length - idx - 1)
-       override def stringPrefix = Projection.this.stringPrefix + "R"
-     }
-   }
-   trait Array0[A] extends RandomAccessSeq.Mutable[A] {
-     override def projection : Projection[A] = throw new Error
-     override def slice(from : Int, until : Int) : Projection[A] = projection.slice(from, until)
-     override def take(until : Int) : Projection[A] = projection.take(until)
-     override def drop(from : Int) : Projection[A] = projection.drop(from)
-     override def reverse = projection.reverse
-   }
-}
-
-/** This class represents polymorphic arrays. <code>Array[T]</code> is Scala's representation
- *  for Java's <code>T[]</code>.
- *
- *  @author Martin Odersky
- *  @version 1.0
- */
-final class Array[A](_length: Int) extends Array.Array0[A] {
-
-   /** Multidimensional array creation */
-   def this(dim1: Int, dim2: Int) = {
-     this(dim1);
-     throw new Error()
-   }
-
-   /** Multidimensional array creation */
-   def this(dim1: Int, dim2: Int, dim3: Int) = {
-     this(dim1);
-     throw new Error()
-   }
-
-   /** Multidimensional array creation */
-   def this(dim1: Int, dim2: Int, dim3: Int, dim4: Int) = {
-     this(dim1);
-     throw new Error()
-   }
-
-   /** Multidimensional array creation */
-   def this(dim1: Int, dim2: Int, dim3: Int, dim4: Int, dim5: Int) = {
-     this(dim1);
-     throw new Error()
-   }
-
-   /** Multidimensional array creation */
-   def this(dim1: Int, dim2: Int, dim3: Int, dim4: Int, dim5: Int, dim6: Int) = {
-     this(dim1);
-     throw new Error()
-   }
-
-   /** Multidimensional array creation */
-   def this(dim1: Int, dim2: Int, dim3: Int, dim4: Int, dim5: Int, dim6: Int, dim7: Int) = {
-     this(dim1);
-     throw new Error()
-   }
-
-   /** Multidimensional array creation */
-   def this(dim1: Int, dim2: Int, dim3: Int, dim4: Int, dim5: Int, dim6: Int, dim7: Int, dim8: Int) = {
-     this(dim1);
-     throw new Error()
-   }
-
-   /** Multidimensional array creation */
-   def this(dim1: Int, dim2: Int, dim3: Int, dim4: Int, dim5: Int, dim6: Int, dim7: Int, dim8: Int, dim9: Int) = {
-     this(dim1);
-     throw new Error()
-   }
-
-  /** The length of the array */
-  def length: Int = throw new Error()
-
-  /** The element at given index. 
-   *  <p>
-   *    Indices start a <code>0</code>; <code>xs.apply(0)</code> is the first 
-   *    element of array <code>xs</code>.
-   *  </p>
-   *  <p>
-   *    Note the indexing syntax <code>xs(i)</code> is a shorthand for
-   *    <code>xs.apply(i)</code>.
-   *  </p>
-   *
-   *  @param i   the index
-   *  @throws ArrayIndexOutOfBoundsException if <code>i < 0</code> or
-   *          <code>length <= i</code>
-   */
-  def apply(i: Int): A = throw new Error()
-
-  /** <p>
-   *    Update the element at given index. 
-   *  </p>
-   *  <p>
-   *    Indices start a <code>0</code>; <code>xs.apply(0)</code> is the first 
-   *    element of array <code>xs</code>.
-   *  </p>
-   *  <p>
-   *    Note the indexing syntax <code>xs(i) = x</code> is a shorthand 
-   *    for <code>xs.update(i, x)</code>.
-   *  </p>
-   *
-   *  @param i   the index
-   *  @param x   the value to be written at index <code>i</code>
-   *  @throws ArrayIndexOutOfBoundsException if <code>i < 0</code> or
-   *          <code>length <= i</code>
-   */
-  override def update(i: Int, x: A): Unit = throw new Error()
-
-  /** An iterator returning the elements of this array, starting from 0.
-   */
-  override def elements: Iterator[A] = throw new Error()
-
-  /** @deprecated  use <code>slice(from,end).force</code> instead */
-  def subArray(from: Int, end: Int): Array[A] = throw new Error()
-
-  /** Returns an array consisting of all elements of this array that satisfy the
-   *  predicate <code>p</code>. The order of the elements is preserved.
-   *
-   *  @param p the predicate used to filter the array.
-   *  @return the elements of this array satisfying <code>p</code>.
-   */
-  override def filter(p: A => Boolean): Array[A] = throw new Error()
-
-  /** Returns the longest prefix of this array whose elements satisfy
-   *  the predicate <code>p</code>.
-   *
-   *  @param p the test predicate.
-   *  @return  the longest prefix of this array whose elements satisfy
-   *           the predicate <code>p</code>.
-   */
-  override def takeWhile(p: A => Boolean): Array[A] = throw new Error()
-
-  /** Returns the longest suffix of this array whose first element
-   *  does not satisfy the predicate <code>p</code>.
-   *
-   *  @param p the test predicate.
-   *  @return  the longest suffix of the array whose first element
-   *           does not satisfy the predicate <code>p</code>.
-   */
-  override def dropWhile(p: A => Boolean): Array[A] = throw new Error()
-
-  /** Returns an array consisting of all elements of this array followed
-   *  by all elements of the argument iterable.
-   */
-  override def ++[B >: A](that: Iterable[B]): Array[B] = throw new Error()
-
-  /** Returns the array resulting from applying the given function <code>f</code> to each
-   *  element of this array.
-   *
-   *  @param f function to apply to each element.
-   *  @return <code>[f(a0), ..., f(an)]</code> if this array is <code>[a0, ..., an]</code>.
-   */
-  override def map[B](f: A => B): Array[B] = throw new Error()
-
-  /** Applies the given function <code>f</code> to each element of
-   *  this array, then concatenates the results.
-   *
-   *  @param f the function to apply on each element.
-   *  @return  <code>f(a<sub>0</sub>) ::: ... ::: f(a<sub>n</sub>)</code> if
-   *           this array is <code>[a<sub>0</sub>, ..., a<sub>n</sub>]</code>.
-   */
-  override def flatMap[B](f: A => Iterable[B]): Array[B] = throw new Error()
-
-  /** Returns an array formed from this array and the specified array
-   *  <code>that</code> by associating each element of the former with
-   *  the element at the same position in the latter.
-   *  If one of the two arrays is longer than the other, its remaining elements are ignored.
-   *
-   *  @return     <code>Array({a<sub>0</sub>,b<sub>0</sub>}, ...,
-   *              {a<sub>min(m,n)</sub>,b<sub>min(m,n)</sub>})</code> when
-   *              <code>Array(a<sub>0</sub>, ..., a<sub>m</sub>)
-   *              zip Array(b<sub>0</sub>, ..., b<sub>n</sub>)</code> is invoked.
-   */
-  def zip[B](that: Array[B]): Array[Tuple2[A,B]] = throw new Error()
-
-  /** Returns an array that pairs each element of this array
-   *  with its index, counting from 0.
-   *
-   *  @return      the array <code>Array({a<sub>0</sub>,0}, {a<sub>1</sub>,1},...)</code>
-   *               where <code>a<sub>i</sub></code> are the elements of this stream.
-   */
-  def zipWithIndex: Array[Tuple2[A,Int]] = throw new Error()
-
-  /** Returns an array that contains all indices of this array */
-  def indices: Array[Int] = throw new Error()
-
-  /**
-   *  @return a deep string representation of this array.
-   */
-  def deepToString(): String = throw new Error()
-
-  /** <p>
-   *    Returns a string representation of this array object. The resulting string
-   *    begins with the string <code>start</code> and is finished by the string
-   *    <code>end</code>. Inside, the string representations of elements (w.r.t.
-   *    the method <code>deepToString()</code>) are separated by the string
-   *    <code>sep</code>. For example:
-   *  </p>
-   *  <p>
-   *    <code>Array(Array(1, 2), Array(3)).deepMkString("[", "; ", "]") = "[[1; 2]; [3]]"</code>
-   *  </p>
-   *
-   *  @param start starting string.
-   *  @param sep separator string.
-   *  @param end ending string.
-   *  @return a string representation of this array object.
-   */
-  def deepMkString(start: String, sep: String, end: String): String =
-    throw new Error()
-
-  /** Returns a string representation of this array object. The string
-   *  representations of elements (w.r.t. the method <code>deepToString()</code>)
-   *  are separated by the string <code>sep</code>.
-   *
-   *  @param sep separator string.
-   *  @return a string representation of this array object.
-   */
-  def deepMkString(sep: String): String = throw new Error()
-
-  /** <p>
-   *    Returns <code>true</code> if the two specified arrays are
-   *    <em>deeply equal</em> to one another.
-   *  </p>
-   *  <p>
-   *    Two array references are considered deeply equal if both are null,
-   *    or if they refer to arrays that contain the same number of elements
-   *    and all corresponding pairs of elements in the two arrays are deeply
-   *    equal.
-   *  </p>
-   *  <p>
-   *    See also method <code>deepEquals</code> in the Java class
-   *    <a href="http://java.sun.com/javase/6/docs/api/java/util/Arrays.html"
-   *    target="_top">java.utils.Arrays</a>
-   *  </p>
-   *
-   *  @param that the second
-   *  @return     <code>true</code> iff both arrays are deeply equal.
-   */
-  def deepEquals(that: Any): Boolean = throw new Error()
-
-}
diff --git a/src/cldc-library/scala/Console.scala b/src/cldc-library/scala/Console.scala
deleted file mode 100644
index 01adea4..0000000
--- a/src/cldc-library/scala/Console.scala
+++ /dev/null
@@ -1,96 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: Console.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala
-
-import java.io.{OutputStream, PrintStream}
-
-import Predef._
-
-
-/** The <code>Console</code> object implements functionality for
- *  printing Scala values on the terminal. There are also functions
- *  for reading specific values. <code>Console</code> also defines
- *  constants for marking up text on ANSI terminals.
- *
- *  @author  Matthias Zenger
- *  @version 1.0, 03/09/2003
- */
-object Console {
-
-  // ANSI colors foreground
-  final val BLACK      = "\033[30m"
-  final val RED        = "\033[31m"
-  final val GREEN      = "\033[32m"
-  final val YELLOW     = "\033[33m"
-  final val BLUE       = "\033[34m"
-  final val MAGENTA    = "\033[35m"
-  final val CYAN       = "\033[36m"
-  final val WHITE      = "\033[37m"
-
-  // ANSI colors background
-  final val BLACK_B    = "\033[40m"
-  final val RED_B      = "\033[41m"
-  final val GREEN_B    = "\033[42m"
-  final val YELLOW_B   = "\033[43m"
-  final val BLUE_B     = "\033[44m"
-  final val MAGENTA_B  = "\033[45m"
-  final val CYAN_B     = "\033[46m"
-  final val WHITE_B    = "\033[47m"
-
-  // ANSI styles
-  final val RESET      = "\033[0m"
-  final val BOLD       = "\033[1m"
-  final val UNDERLINED = "\033[4m"
-  final val BLINK      = "\033[5m"
-  final val REVERSED   = "\033[7m"
-  final val INVISIBLE  = "\033[8m"
-
-  var out: PrintStream = java.lang.System.out
-  val err = java.lang.System.err
-
-  /** Set the default output stream.
-   *
-   *  @param out the new output stream.
-   */
-  def setOut(out: PrintStream): Unit = this.out = out
-
-  /** Set the default output stream.
-   *
-   *  @param@ out the new output stream.
-   */
-  def setOut(out: OutputStream): Unit =
-    setOut(new PrintStream(out))
-
-  /** Print an object on the terminal.
-   *
-   *  @param obj the object to print.
-   */
-  def print(obj: Any): Unit =
-    out.print(if (null == obj) "null" else obj.toString())
-
-  /** Flush the output stream. This function is required when partial
-   *  output (i.e. output not terminated by a new line character) has
-   *  to be made visible on the terminal.
-   */
-  def flush(): Unit = out.flush()
-
-  /** Print a new line character on the terminal.
-   */
-  def println(): Unit = out.println()
-
-  /** Print out an object followed by a new line character.
-   *
-   *  @param x the object to print.
-   */
-  def println(x: Any): Unit = out.println(x)
-
-}
diff --git a/src/cldc-library/scala/List.scala b/src/cldc-library/scala/List.scala
deleted file mode 100644
index b8b3cab..0000000
--- a/src/cldc-library/scala/List.scala
+++ /dev/null
@@ -1,1244 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: List.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala
-
-import scala.collection.mutable.ListBuffer
-import Predef._
-
-/** This object provides methods for creating specialized lists, and for
- *  transforming special kinds of lists (e.g. lists of lists).
- *
- *  @author  Martin Odersky and others
- *  @version 1.0, 15/07/2003
- */
-object List {
-
-  /** Create a list with given elements.
-   *
-   *  @param xs the elements to put in the list
-   *  @return the list containing elements xs.
-   */
-  def apply[A](xs: A*): List[A] = xs.toList
-
-  /** for unapply matching
-   */
-  def unapplySeq[A](x: List[A]): Some[List[A]] = Some(x)
-
-  /** Create a sorted list of all integers in a range.
-   *
-   *  @param from the start value of the list
-   *  @param end the end value of the list
-   *  @return the sorted list of all integers in range [from;end).
-   */
-  def range(from: Int, end: Int): List[Int] =
-    range(from, end, 1)
-
-  /** Create a sorted list of all integers in a range.
-   *
-   *  @param from the start value of the list
-   *  @param end  the end value of the list
-   *  @param step the increment value of the list
-   *  @return     the sorted list of all integers in range [from;end).
-   */
-  def range(from: Int, end: Int, step: Int): List[Int] = {
-    val b = new ListBuffer[Int]
-    var i = from
-    while (i < end) {
-      b += i
-      i += step
-    }
-    b.toList
-  }
-
-  /** Create a sorted list of all integers in a range.
-   *
-   *  @param from the start value of the list
-   *  @param end  the end value of the list
-   *  @param step the increment function of the list
-   *  @return     the sorted list of all integers in range [from;end).
-   */
-  def range(from: Int, end: Int, step: Int => Int): List[Int] = {
-    val b = new ListBuffer[Int]
-    var i = from
-    while (i < end) {
-      b += i
-      i += step(i)
-    }
-    b.toList
-  }
-
-  /** Create a list containing several copies of an element.
-   *
-   *  @param n    the length of the resulting list
-   *  @param elem the element composing the resulting list
-   *  @return     a list composed of n elements all equal to elem
-   */
-  def make[A](n: Int, elem: A): List[A] = {
-    val b = new ListBuffer[A]
-    var i = 0
-    while (i < n) {
-      b += elem
-      i += 1
-    }
-    b.toList
-  }
-
-  /** Create a list by applying a function to successive integers.
-   *
-   *  @param n     the length of the resulting list
-   *  @param maker the procedure which, given an integer <code>n</code>,
-   *               returns the nth element of the resulting list, where
-   *               <code>n</code> is in interval <code>[0;n)</code>.
-   *  @return      the list obtained by applying the maker function to
-   *               successive integers from 0 to n (exclusive).
-   */
-  def tabulate[A](n: Int, maker: Int => A): List[A] = {
-    val b = new ListBuffer[A]
-    var i = 0
-    while (i < n) {
-      b += maker(i)
-      i += 1
-    }
-    b.toList
-  }
-
-  /** Concatenate all the elements of a given list of lists.
-   *
-   *  @param xss the list of lists that are to be concatenated
-   *  @return    the concatenation of all the lists
-   */
-  def flatten[A](xss: List[List[A]]): List[A] = concat(xss: _*)
-
-  /** Concatenate all the argument lists into a single list.
-   *
-   *  @param xss the lists that are to be concatenated
-   *  @return the concatenation of all the lists
-   */
-  def concat[A](xss: List[A]*): List[A] = { 
-    val b = new ListBuffer[A] 
-    for (xs <- xss) {
-      var xc = xs
-      while (!xc.isEmpty) {
-        b += xc.head
-        xc = xc.tail
-      }
-    }
-    b.toList
-  }
-
-  /** Transforms a list of pair into a pair of lists.
-   *
-   *  @param xs the list of pairs to unzip
-   *  @return a pair of lists: the first list in the pair contains the list
-   */
-  def unzip[A,B](xs: List[(A,B)]): (List[A], List[B]) = {
-    val b1 = new ListBuffer[A]
-    val b2 = new ListBuffer[B]
-    var xc = xs
-    while (!xc.isEmpty) {
-      b1 += xc.head._1
-      b2 += xc.head._2
-      xc = xc.tail
-    }
-    (b1.toList, b2.toList)
-  }
-
-  /** Converts an iterator to a list.
-   *
-   *  @param it the iterator to convert
-   *  @return   a list that contains the elements returned by successive
-   *            calls to <code>it.next</code>
-   */
-  def fromIterator[A](it: Iterator[A]): List[A] = it.toList
-
-  /** Converts an array into a list.
-   *
-   *  @param arr the array to convert
-   *  @return    a list that contains the same elements than <code>arr</code>
-   *             in the same order
-   */
-  def fromArray[A](arr: Array[A]): List[A] = fromArray(arr, 0, arr.length)
-
-  /** Converts a range of an array into a list.
-   *
-   *  @param arr   the array to convert
-   *  @param start the first index to consider
-   *  @param len   the lenght of the range to convert
-   *  @return      a list that contains the same elements than <code>arr</code>
-   *               in the same order
-   */
-  def fromArray[A](arr: Array[A], start: Int, len: Int): List[A] = {
-    var res: List[A] = Nil
-    var i = start + len
-    while (i > start) {
-      i -= 1
-      res = arr(i) :: res
-    }
-    res
-  }
-
-  /** Parses a string which contains substrings separated by a
-   *  separator character and returns a list of all substrings.
-   *
-   *  @param str       the string to parse
-   *  @param separator the separator character
-   *  @return          the list of substrings
-   */
-  def fromString(str: String, separator: Char): List[String] = {
-    var words: List[String] = Nil
-    var pos = str.length()
-    while (pos > 0) {
-      val pos1 = str.lastIndexOf(separator, pos - 1)
-      if (pos1 + 1 < pos)
-        words = str.substring(pos1 + 1, pos) :: words
-      pos = pos1
-    }
-    words
-  }
-
-  /** Returns the given string as a list of characters.
-   *
-   *  @param str the string to convert.
-   *  @return    the string as a list of characters.
-   *  @deprecated use <code>str.toList</code> instead
-   */
-  @deprecated def fromString(str: String): List[Char] =
-    str.toList
-
-  /** Returns the given list of characters as a string.
-   *
-   *  @param xs the list to convert.
-   *  @return   the list in form of a string.
-   */
-  def toString(xs: List[Char]): String = {
-    val sb = new StringBuilder()
-    var xc = xs
-    while (!xc.isEmpty) {
-      sb.append(xc.head)
-      xc = xc.tail
-    }
-    sb.toString()
-  }
-
-  /** Like xs map f, but returns <code>xs</code> unchanged if function
-   *  <code>f</code> maps all elements to themselves.
-   *
-   *  @param xs ...
-   *  @param f  ...
-   *  @return   ...
-   */
-  def mapConserve[A <: AnyRef](xs: List[A])(f: A => A): List[A] = {
-    def loop(ys: List[A]): List[A] =
-      if (ys.isEmpty) xs
-      else {
-        val head0 = ys.head
-        val head1 = f(head0)
-        if (head1 eq head0) {
-          loop(ys.tail)
-        } else {
-          val ys1 = head1 :: mapConserve(ys.tail)(f)
-          if (xs eq ys) ys1
-          else {
-            val b = new ListBuffer[A]
-            var xc = xs
-            while (xc ne ys) {
-              b += xc.head
-              xc = xc.tail
-            }
-            b.prependToList(ys1)
-          }
-        }
-      }
-    loop(xs)
-  }
-
-  /** Returns the list resulting from applying the given function <code>f</code>
-   *  to corresponding elements of the argument lists.
-   *
-   *  @param f function to apply to each pair of elements.
-   *  @return <code>[f(a0,b0), ..., f(an,bn)]</code> if the lists are 
-   *          <code>[a0, ..., ak]</code>, <code>[b0, ..., bl]</code> and
-   *          <code>n = min(k,l)</code>
-   */
-  def map2[A,B,C](xs: List[A], ys: List[B])(f: (A, B) => C): List[C] = {
-    val b = new ListBuffer[C]
-    var xc = xs
-    var yc = ys
-    while (!xc.isEmpty && !yc.isEmpty) {
-      b += f(xc.head, yc.head)
-      xc = xc.tail
-      yc = yc.tail
-    }
-    b.toList
-  }
-
-  /** Returns the list resulting from applying the given function
-   *  <code>f</code> to corresponding elements of the argument lists.
-   *
-   *  @param f function to apply to each pair of elements.
-   *  @return  <code>[f(a<sub>0</sub>,b<sub>0</sub>,c<sub>0</sub>),
-   *           ..., f(a<sub>n</sub>,b<sub>n</sub>,c<sub>n</sub>)]</code>
-   *           if the lists are <code>[a<sub>0</sub>, ..., a<sub>k</sub>]</code>,
-   *           <code>[b<sub>0</sub>, ..., b<sub>l</sub>]</code>,
-   *           <code>[c<sub>0</sub>, ..., c<sub>m</sub>]</code> and
-   *           <code>n = min(k,l,m)</code>
-   */
-  def map3[A,B,C,D](xs: List[A], ys: List[B], zs: List[C])(f: (A, B, C) => D): List[D] = {
-    val b = new ListBuffer[D]
-    var xc = xs
-    var yc = ys
-    var zc = zs
-    while (!xc.isEmpty && !yc.isEmpty && !zc.isEmpty) {
-      b += f(xc.head, yc.head, zc.head)
-      xc = xc.tail
-      yc = yc.tail
-      zc = zc.tail
-    }
-    b.toList
-  }
-
-  /** Tests whether the given predicate <code>p</code> holds 
-   *  for all corresponding elements of the argument lists.
-   *
-   *  @param p function to apply to each pair of elements.
-   *  @return  <code>(p(a<sub>0</sub>,b<sub>0</sub>) &&
-   *           ... && p(a<sub>n</sub>,b<sub>n</sub>))]</code>
-   *           if the lists are <code>[a<sub>0</sub>, ..., a<sub>k</sub>]</code>;
-   *           <code>[b<sub>0</sub>, ..., b<sub>l</sub>]</code>
-   *           and <code>n = min(k,l)</code>
-   */
-  def forall2[A,B](xs: List[A], ys: List[B])(f: (A, B) => Boolean): Boolean = {
-    var xc = xs
-    var yc = ys
-    while (!xc.isEmpty && !yc.isEmpty) {
-      if (!f(xc.head, yc.head)) return false
-      xc = xc.tail
-      yc = yc.tail
-    }
-    true
-  }
-
-  /** Tests whether the given predicate <code>p</code> holds
-   *  for some corresponding elements of the argument lists.
-   *
-   *  @param p function to apply to each pair of elements.
-   *  @return  <code>n != 0 && (p(a<sub>0</sub>,b<sub>0</sub>) ||
-   *           ... || p(a<sub>n</sub>,b<sub>n</sub>))]</code> if the lists are
-   *           <code>[a<sub>0</sub>, ..., a<sub>k</sub>]</code>,
-   *           <code>[b<sub>0</sub>, ..., b<sub>l</sub>]</code> and
-   *           <code>n = min(k,l)</code>
-   */
-  def exists2[A,B](xs: List[A], ys: List[B])(f: (A, B) => Boolean): Boolean = {
-    var xc = xs
-    var yc = ys
-    while (!xc.isEmpty && !yc.isEmpty) {
-      if (f(xc.head, yc.head)) return true
-      xc = xc.tail
-      yc = yc.tail
-    }
-    false
-  }
-
-  /** Transposes a list of lists.
-   *  pre: All element lists have the same length.
-   *
-   *  @param xss the list of lists
-   *  @return    the transposed list of lists
-   */
-  def transpose[A](xss: List[List[A]]): List[List[A]] =
-    if (xss.head.isEmpty) List()
-    else (xss map (xs => xs.head)) :: transpose(xss map (xs => xs.tail))
-
-  /** Lists with ordered elements are ordered
-  implicit def list2ordered[a <% Ordered[a]](x: List[a]): Ordered[List[a]] = new Ordered[List[a]] {
-    def compare [b >: List[a] <% Ordered[b]](y: b): Int = y match {
-      case y1: List[a] => compareLists(x, y1);
-      case _ => -(y compare x)
-    }
-    private def compareLists(xs: List[a], ys: List[a]): Int = {
-      if (xs.isEmpty && ys.isEmpty) 0
-      else if (xs.isEmpty) -1
-      else if (ys.isEmpty) 1
-      else {
-        val s = xs.head compare ys.head;
-        if (s != 0) s
-        else compareLists(xs.tail, ys.tail)
-      }
-    }
-  }
-   */
-}
-
-/** A class representing an ordered collection of elements of type
- *  <code>a</code>. This class comes with two implementing case
- *  classes <code>scala.Nil</code> and <code>scala.::</code> that
- *  implement the abstract members <code>isEmpty</code>,
- *  <code>head</code> and <code>tail</code>.
- *
- *  @author  Martin Odersky and others
- *  @version 1.0, 16/07/2003
- */
-sealed abstract class List[+A] extends Seq[A] {
-
-  /** Returns true if the list does not contain any elements.
-   *  @return <code>true</code>, iff the list is empty.
-   */
-  override def isEmpty: Boolean
-
-  /** Returns this first element of the list.
-   *
-   *  @return the first element of this list.
-   *  @throws Predef.NoSuchElementException if the list is empty.
-   */
-  def head: A
-
-  /** returns length - l, without calling length
-   */
-  override def lengthCompare(l: Int) = {
-    if (isEmpty) 0 - l
-    else if (l <= 0) 1
-    else tail.lengthCompare(l - 1)
-  }
-
-  /** Returns this list without its first element.
-   *
-   *  @return this list without its first element.
-   *  @throws Predef.NoSuchElementException if the list is empty.
-   */
-  def tail: List[A]
-
-  /** <p>
-   *    Add an element <code>x</code> at the beginning of this list.
-   *  </p>
-   *
-   *  @param x the element to append.
-   *  @return  the list with <code>x</code> appended at the beginning.
-   *  @ex <code>1 :: List(2, 3) = List(2, 3).::(1) = List(1, 2, 3)</code>
-   */
-  def ::[B >: A] (x: B): List[B] =
-    new scala.::(x, this)
-
-  /** <p>
-   *    Returns a list resulting from the concatenation of the given
-   *    list <code>prefix</code> and this list. 
-   *  </p>
-   *
-   *  @param prefix the list to concatenate at the beginning of this list.
-   *  @return the concatenation of the two lists.
-   *  @ex <code>List(1, 2) ::: List(3, 4) = List(3, 4).:::(List(1, 2)) = List(1, 2, 3, 4)</code>
-   */
-  def :::[B >: A](prefix: List[B]): List[B] =
-    if (isEmpty) prefix
-    else {
-      val b = new ListBuffer[B]
-      var those = prefix
-      while (!those.isEmpty) {
-        b += those.head
-        those = those.tail
-      }
-      b.prependToList(this)
-    }
-
-  /** Reverse the given prefix and append the current list to that.
-   *  This function is equivalent to an application of <code>reverse</code>
-   *  on the prefix followed by a call to <code>:::</code>, but more
-   *  efficient (and tail recursive).
-   *
-   *  @param prefix the prefix to reverse and then prepend
-   *  @return       the concatenation of the reversed prefix and the current list.
-   */
-  def reverse_:::[B >: A](prefix: List[B]): List[B] = {
-    var these: List[B] = this
-    var pres = prefix
-    while (!pres.isEmpty) {
-      these = pres.head :: these
-      pres = pres.tail
-    }
-    these
-  }
-
-  /** Returns the number of elements in the list.
-   *
-   *  @return the number of elements in the list.
-   */
-  def length: Int = {
-    var these = this
-    var len = 0
-    while (!these.isEmpty) {
-      len += 1
-      these = these.tail
-    }
-    len
-  }
-
-  /** Creates a list with all indices in the list. This is
-   *  equivalent to a call to <code>List.range(0, xs.length)</code>.
-   *
-   *  @return a list of all indices in the list.
-   */
-  def indices: List[Int] = {
-    val b = new ListBuffer[Int]
-    var i = 0
-    var these = this
-    while (!these.isEmpty) {
-      b += i
-      i += 1
-      these = these.tail
-    }
-    b.toList
-  }
- 
-  /** Returns the elements in the list as an iterator
-   *
-   *  @return an iterator on the list elements.
-   */
-  override def elements: Iterator[A] = new Iterator[A] {
-    var these = List.this
-    def hasNext: Boolean = !these.isEmpty
-    def next: A =
-      if (!hasNext)
-        throw new NoSuchElementException("next on empty Iterator")
-      else {
-        val result = these.head; these = these.tail; result
-      }
-    override def toList: List[A] = these
-  }
-
-  /** Overrides the method in Iterable for efficiency.
-   *
-   *  @return  the list itself
-   */
-  override def toList: List[A] = this
-
-  /** Returns the list without its last element.
-   *
-   *  @return the list without its last element.
-   *  @throws Predef.UnsupportedOperationException if the list is empty.
-   */
-  def init: List[A] =
-    if (isEmpty) throw new UnsupportedOperationException("Nil.init")
-    else {
-      val b = new ListBuffer[A]
-      var elem = head
-      var next = tail
-      while (!next.isEmpty) {
-        b += elem
-        elem = next.head
-        next = next.tail
-      }
-      b.toList
-    }
-
-  /** Returns the last element of this list.
-   *
-   *  @return the last element of the list.
-   *  @throws Predef.UnsupportedOperationException if the list is empty.
-   */
-  override def last: A =
-    if (isEmpty) throw new Predef.NoSuchElementException("Nil.last")
-    else {
-      var cur = this
-      var next = this.tail
-      while (!next.isEmpty) {
-        cur = next
-        next = next.tail
-      }
-      cur.head
-    }
-
-  /** Returns the <code>n</code> first elements of this list, or else the whole 
-   *  list, if it has less than <code>n</code> elements.
-   *
-   *  @param n the number of elements to take.
-   *  @return the <code>n</code> first elements of this list.
-   */
-  override def take(n: Int): List[A] = {
-    val b = new ListBuffer[A]
-    var i = 0
-    var these = this
-    while (!these.isEmpty && i < n) {
-      i += 1
-      b += these.head
-      these = these.tail
-    }
-    if (these.isEmpty) this
-    else b.toList
-  }
-
-  /** Returns the list with elements belonging to the given index range.
-   *
-   *  @param start the start position of the list slice.
-   *  @param end   the end position (exclusive) of the list slice.
-   *  @return the list with elements belonging to the given index range.
-   */
-  override def slice(start: Int, end: Int): List[A] = {
-    val s = start max 0
-    val e = end min this.length
-    drop(s) take (e - s)
-  }
-
-  /** Returns the list without its <code>n</code> first elements.
-   *  If this list has less than <code>n</code> elements, the empty list is returned.
-   *
-   *  @param n the number of elements to drop.
-   *  @return the list without its <code>n</code> first elements.
-   */
-  override def drop(n: Int): List[A] = {
-    var these = this
-    var count = n
-    while (!these.isEmpty && count > 0) {
-      these = these.tail
-      count -= 1
-    }
-    these
-  }
-
-  /** Returns the rightmost <code>n</code> elements from this list.
-   *
-   *  @param n the number of elements to take
-   *  @return the suffix of length <code>n</code> of the list
-   */
-  def takeRight(n: Int): List[A] = {
-    def loop(lead: List[A], lag: List[A]): List[A] = lead match {
-      case Nil => lag
-      case _ :: tail => loop(tail, lag.tail)
-    }
-    loop(drop(n), this)
-  }
-
-  /** Returns the list wihout its rightmost <code>n</code> elements.
-   *
-   *  @param n the number of elements to take
-   *  @return the suffix of length <code>n</code> of the list
-   */
-  def dropRight(n: Int): List[A] = {
-    def loop(lead: List[A], lag: List[A]): List[A] = lead match {
-      case Nil => Nil
-      case _ :: tail => lag.head :: loop(tail, lag.tail)
-    }
-    loop(drop(n), this)
-  }
-
-  /** Split the list at a given point and return the two parts thus
-   *  created.
-   *
-   *  @param n the position at which to split
-   *  @return  a pair of lists composed of the first <code>n</code>
-   *           elements, and the other elements.
-   */
-  def splitAt(n: Int): (List[A], List[A]) = {
-    val b = new ListBuffer[A]
-    var i = 0
-    var these = this
-    while (!these.isEmpty && i < n) {
-      i += 1
-      b += these.head
-      these = these.tail
-    }
-    (b.toList, these)
-  }
-
-  /** Returns the longest prefix of this list whose elements satisfy
-   *  the predicate <code>p</code>.
-   *
-   *  @param p the test predicate.
-   *  @return  the longest prefix of this list whose elements satisfy
-   *           the predicate <code>p</code>.
-   */
-  override def takeWhile(p: A => Boolean): List[A] = {
-    val b = new ListBuffer[A]
-    var these = this
-    while (!these.isEmpty && p(these.head)) {
-      b += these.head
-      these = these.tail
-    }
-    b.toList
-  }
-
-  /** Returns the longest suffix of this list whose first element
-   *  does not satisfy the predicate <code>p</code>.
-   *
-   *  @param p the test predicate.
-   *  @return  the longest suffix of the list whose first element
-   *           does not satisfy the predicate <code>p</code>.
-   */
-  override def dropWhile(p: A => Boolean): List[A] =
-    if (isEmpty || !p(head)) this
-    else tail dropWhile p
-
-  /** Returns the longest prefix of the list whose elements all satisfy
-   *  the given predicate, and the rest of the list.
-   *
-   *  @param p the test predicate
-   *  @return  a pair consisting of the longest prefix of the list whose
-   *           elements all satisfy <code>p</code>, and the rest of the list.
-   */
-  def span(p: A => Boolean): (List[A], List[A]) = {
-    val b = new ListBuffer[A]
-    var these = this
-    while (!these.isEmpty && p(these.head)) {
-      b += these.head
-      these = these.tail
-    }
-    (b.toList, these)
-  }
-
-  /** Like <code>span</code> but with the predicate inverted.
-   */
-  def break(p: A => Boolean): (List[A], List[A]) = span { x => !p(x) }
-
-  /** Returns the <code>n</code>-th element of this list. The first element
-   *  (head of the list) is at position 0.
-   *
-   *  @param n index of the element to return
-   *  @return  the element at position <code>n</code> in this list.
-   *  @throws Predef.NoSuchElementException if the list is too short.
-   */
-  def apply(n: Int): A = drop(n).head
-
-  /** Returns the list resulting from applying the given function <code>f</code> to each
-   *  element of this list.
-   *
-   *  @param f function to apply to each element.
-   *  @return <code>[f(a0), ..., f(an)]</code> if this list is <code>[a0, ..., an]</code>.
-   */
-  final override def map[B](f: A => B): List[B] = {
-    val b = new ListBuffer[B]
-    var these = this
-    while (!these.isEmpty) {
-      b += f(these.head)
-      these = these.tail
-    }
-    b.toList
-  }
-
-  /** Apply a function to all the elements of the list, and return the
-   *  reversed list of results. This is equivalent to a call to <code>map</code>
-   *  followed by a call to <code>reverse</code>, but more efficient.
-   *
-   *  @param f the function to apply to each elements.
-   *  @return  the reversed list of results.
-   */
-  def reverseMap[B](f: A => B): List[B] = {
-    def loop(l: List[A], res: List[B]): List[B] = l match {
-      case Nil => res
-      case head :: tail => loop(tail, f(head) :: res)
-    }
-    loop(this, Nil)
-  }
-
-  /** Apply the given function <code>f</code> to each element of this list
-   *  (while respecting the order of the elements).
-   *
-   *  @param f the treatment to apply to each element.
-   */
-  final override def foreach(f: A => Unit) {
-    var these = this
-    while (!these.isEmpty) {
-      f(these.head)
-      these = these.tail
-    }
-  }
-
-  /** Returns all the elements of this list that satisfy the
-   *  predicate <code>p</code>. The order of the elements is preserved.
-   *  It is guarenteed that the receiver list itself is returned iff all its
-   *  elements satisfy the predicate `p'. Hence the following equality is valid:
-   *
-   *  (xs filter p) eq xs  ==  xs forall p
-   *
-   *  @param p the predicate used to filter the list.
-   *  @return the elements of this list satisfying <code>p</code>.
-   */
-  final override def filter(p: A => Boolean): List[A] = {
-    // return same list if all elements satisfy p
-    var these = this
-    while (!these.isEmpty && p(these.head)) {
-      these = these.tail
-    }
-    if (these.isEmpty) this
-    else {
-      val b = new ListBuffer[A]
-      var these1 = this
-      while (these1 ne these) {
-        b += these1.head
-        these1 = these1.tail
-      }
-
-      these = these.tail // prevent the second evaluation of the predicate
-                         // on the element on which it first failed
-      while (!these.isEmpty) {
-        if (p(these.head)) b += these.head
-        these = these.tail
-      }
-      b.toList
-    }
-  }
-
-//  final def filterMap[B](f: PartialFunction[A, B]): List[B] = 
-//    this filter f.isDefinedAt map f
-
-  /** Removes all elements of the list which satisfy the predicate
-   *  <code>p</code>. This is like <code>filter</code> with the
-   *  predicate inversed.
-   *
-   *  @param p the predicate to use to test elements
-   *  @return  the list without all elements which satisfy <code>p</code>
-   */
-  def remove(p: A => Boolean): List[A] = filter (x => !p(x))
-
-  /** Partition the list in two sub-lists according to a predicate.
-   *
-   *  @param p the predicate on which to partition
-   *  @return  a pair of lists: the list of all elements which satisfy
-   *           <code>p</code> and the list of all elements which do not.
-   *           The relative order of the elements in the sub-lists is the
-   *           same as in the original list.
-   */
-  override def partition(p: A => Boolean): (List[A], List[A]) = {
-    val btrue = new ListBuffer[A]
-    val bfalse = new ListBuffer[A]
-    var these = this
-    while (!these.isEmpty) {
-      (if (p(these.head)) btrue else bfalse) += these.head
-      these = these.tail
-    }
-    (btrue.toList, bfalse.toList)
-  }
-
-  /** <p>
-   *    Sort the list according to the comparison function
-   *    <code><(e1: a, e2: a) => Boolean</code>,
-   *    which should be true iff <code>e1</code> is smaller than
-   *    <code>e2</code>. 
-   *  </p>
-   *
-   *  @param lt the comparison function
-   *  @return   a list sorted according to the comparison function
-   *            <code><(e1: a, e2: a) => Boolean</code>.
-   *  @ex <pre>
-   *    List("Steve", "Tom", "John", "Bob")
-   *      .sort((e1, e2) => (e1 compareTo e2) < 0) =
-   *    List("Bob", "John", "Steve", "Tom")</pre>
-   */
-  def sort(lt : (A,A) => Boolean): List[A] = {
-    /** Merge two already-sorted lists */
-    def merge(l1: List[A], l2: List[A]): List[A] = {
-      val res = new ListBuffer[A]
-      var left1 = l1
-      var left2 = l2
-
-      while (!left1.isEmpty && !left2.isEmpty) {
-	if(lt(left1.head, left2.head)) {
-	  res += left1.head
-	  left1 = left1.tail
-	} else {
-	  res += left2.head
-	  left2 = left2.tail
-	}
-      }
-
-      res ++= left1
-      res ++= left2
-
-      res.toList
-    }
-
-    /** Split a list into two lists of about the same size */
-    def split(lst: List[A]) = {
-      val res1 = new ListBuffer[A]
-      val res2 = new ListBuffer[A]
-      var left = lst
-
-      while (!left.isEmpty) {
-	res1 += left.head
-	left = left.tail
-	if (!left.isEmpty) {
-	  res2 += left.head
-	  left = left.tail
-	}
-      }
-
-      (res1.toList, res2.toList)
-    }
-
-
-    /** Merge-sort the specified list */
-    def ms(lst: List[A]): List[A] =
-      lst match {
-	case Nil => lst
-	case x :: Nil => lst
-	case x :: y :: Nil =>
-	  if (lt(x,y))
-	    lst
-	  else
-	    y :: x :: Nil
-
-	case lst =>
-          val (l1, l2) = split(lst)
-          val l1s = ms(l1)
-          val l2s = ms(l2)
-          merge(l1s, l2s)
-      }
-
-    ms(this)
-  }
-
-
-  /** Count the number of elements in the list which satisfy a predicate.
-   *
-   *  @param p the predicate for which to count
-   *  @return  the number of elements satisfying the predicate <code>p</code>.
-   */
-  def count(p: A => Boolean): Int = {
-    var cnt = 0
-    var these = this
-    while (!these.isEmpty) {
-      if (p(these.head)) cnt += 1
-      these = these.tail
-    }
-    cnt
-  }
-
-  /** Tests if the predicate <code>p</code> is satisfied by all elements
-   *  in this list.
-   *
-   *  @param p the test predicate.
-   *  @return  <code>true</code> iff all elements of this list satisfy the
-   *           predicate <code>p</code>.
-   */
-  override def forall(p: A => Boolean): Boolean = {
-    var these = this
-    while (!these.isEmpty) {
-      if (!p(these.head)) return false
-      these = these.tail
-    }
-    true
-  }
-
-  /** Tests the existence in this list of an element that satisfies the
-   *  predicate <code>p</code>.
-   *
-   *  @param p the test predicate.
-   *  @return  <code>true</code> iff there exists an element in this list that
-   *           satisfies the predicate <code>p</code>.
-   */
-  override def exists(p: A => Boolean): Boolean = {
-    var these = this
-    while (!these.isEmpty) {
-      if (p(these.head)) return true
-      these = these.tail
-    }
-    false
-  }
-
-  /** Find and return the first element of the list satisfying a
-   *  predicate, if any.
-   *
-   *  @param p the predicate
-   *  @return the first element in the list satisfying <code>p</code>,
-   *  or <code>None</code> if none exists.
-   */
-  override def find(p: A => Boolean): Option[A] = {
-    var these = this
-    while (!these.isEmpty) {
-      if (p(these.head)) return Some(these.head)
-      these = these.tail
-    }
-    None
-  }
-
-  /** Combines the elements of this list together using the binary
-   *  function <code>f</code>, from left to right, and starting with
-   *  the value <code>z</code>.
-   *
-   *  @return <code>f(... (f(f(z, a<sub>0</sub>), a<sub>1</sub>) ...),
-   *          a<sub>n</sub>)</code> if the list is
-   *          <code>[a<sub>0</sub>, a<sub>1</sub>, ..., a<sub>n</sub>]</code>.
-   */
-  override def foldLeft[B](z: B)(f: (B, A) => B): B = {
-    var acc = z
-    var these = this
-    while (!these.isEmpty) {
-      acc = f(acc, these.head)
-      these = these.tail
-    }
-    acc
-  }
-
-  /** Combines the elements of this list together using the binary
-   *  function <code>f</code>, from right to left, and starting with
-   *  the value <code>z</code>.
-   *
-   *  @return <code>f(a<sub>0</sub>, f(a<sub>1</sub>, f(..., f(a<sub>n</sub>, z)...)))</code>
-   *          if the list is <code>[a<sub>0</sub>, a1, ..., a<sub>n</sub>]</code>.
-   */
-  override def foldRight[B](z: B)(f: (A, B) => B): B = this match {
-    case Nil => z
-    case x :: xs => f(x, xs.foldRight(z)(f))
-  }
-
-  /** Combines the elements of this list together using the binary
-   *  operator <code>op</code>, from left to right
-   *  @param op  The operator to apply
-   *  @return <code>op(... op(a<sub>0</sub>,a<sub>1</sub>), ..., a<sub>n</sub>)</code> 
-      if the list has elements
-   *          <code>a<sub>0</sub>, a<sub>1</sub>, ..., a<sub>n</sub></code>.
-   *  @throws Predef.UnsupportedOperationException if the list is empty.
-   */
-  override def reduceLeft[B >: A](f: (B, B) => B): B = this match {
-    case Nil => throw new UnsupportedOperationException("Nil.reduceLeft")
-    case x :: xs => ((xs: List[B]) foldLeft (x: B))(f)
-  }
-
-  /** Combines the elements of this list together using the binary
-   *  operator <code>op</code>, from right to left
-   *  @param op  The operator to apply
-   *
-   *  @return <code>a<sub>0</sub> op (... op (a<sub>n-1</sub> op a<sub>n</sub>)...)</code>
-   *          if the list has elements <code>a<sub>0</sub>, a<sub>1</sub>, ...,
-   *          a<sub>n</sub></code>.
-   *
-   *  @throws Predef.UnsupportedOperationException if the list is empty.
-   */
-  override def reduceRight[B >: A](f: (B, B) => B): B = this match {
-    case Nil => throw new UnsupportedOperationException("Nil.reduceRight")
-    case x :: Nil => x: B
-    case x :: xs => f(x, xs reduceRight f)
-  }
-
-  /** Applies the given function <code>f</code> to each element of
-   *  this list, then concatenates the results.
-   *
-   *  @param f the function to apply on each element.
-   *  @return  <code>f(a<sub>0</sub>) ::: ... ::: f(a<sub>n</sub>)</code> if
-   *           this list is <code>[a<sub>0</sub>, ..., a<sub>n</sub>]</code>.
-   */
-  final override def flatMap[B](f: A => Iterable[B]): List[B] = {
-    val b = new ListBuffer[B]
-    var these = this
-    while (!these.isEmpty) {
-      var those = f(these.head).elements
-      while (those.hasNext) {
-        b += those.next
-      }
-      these = these.tail
-    }
-    b.toList
-  }
-
-  /** A list consisting of all elements of this list in reverse order.
-   */
-  override def reverse: List[A] = {
-    var result: List[A] = Nil
-    var these = this
-    while (!these.isEmpty) {
-      result = these.head :: result
-      these = these.tail
-    }
-    result
-  }
-
-  /** Returns a list formed from this list and the specified list
-   *  <code>that</code> by associating each element of the former with
-   *  the element at the same position in the latter.
-   *  If one of the two lists is longer than the other, its remaining elements are ignored.
-   *
-   *  @return     <code>List((a<sub>0</sub>,b<sub>0</sub>), ...,
-   *              (a<sub>min(m,n)</sub>,b<sub>min(m,n)</sub>))</code> when
-   *              <code>List(a<sub>0</sub>, ..., a<sub>m</sub>)
-   *              zip List(b<sub>0</sub>, ..., b<sub>n</sub>)</code> is invoked.
-   */
-  def zip[B](that: List[B]): List[(A, B)] = {
-    val b = new ListBuffer[(A, B)]
-    var these = this
-    var those = that
-    while (!these.isEmpty && !those.isEmpty) {
-      b += (these.head, those.head)
-      these = these.tail
-      those = those.tail
-    }
-    b.toList
-  }
-
-  /** Returns a list that pairs each element of this list
-   *  with its index, counting from 0.
-   *
-   *  @return      the list <code>List((a<sub>0</sub>,0), (a<sub>1</sub>,1), ...)</code>
-   *               where <code>a<sub>i</sub></code> are the elements of this list.
-   */
-  def zipWithIndex: List[(A, Int)] = {
-    val b = new ListBuffer[(A, Int)]
-    var these = this
-    var idx = 0
-
-    while(!these.isEmpty) {
-      b += (these.head, idx)
-      these = these.tail
-      idx += 1
-    }
-
-    b.toList
-  }
-
-  /** Returns a list formed from this list and the specified list
-   *  <code>that</code> by associating each element of the former with
-   *  the element at the same position in the latter.
-   *
-   *  @param that     list <code>that</code> may have a different length
-   *                  as the self list.
-   *  @param thisElem element <code>thisElem</code> is used to fill up the
-   *                  resulting list if the self list is shorter than
-   *                  <code>that</code>
-   *  @param thatElem element <code>thatElem</code> is used to fill up the
-   *                  resulting list if <code>that</code> is shorter than
-   *                  the self list
-   *  @return         <code>List((a<sub>0</sub>,b<sub>0</sub>), ...,
-   *                  (a<sub>n</sub>,b<sub>n</sub>), (elem,b<sub>n+1</sub>),
-   *                  ..., {elem,b<sub>m</sub>})</code>
-   *                  when <code>[a<sub>0</sub>, ..., a<sub>n</sub>] zip
-   *                  [b<sub>0</sub>, ..., b<sub>m</sub>]</code> is
-   *                  invoked where <code>m > n</code>.
-   */
-  def zipAll[B, C >: A, D >: B](that: List[B], thisElem: C, thatElem: D): List[(C, D)] = {
-    val b = new ListBuffer[(C, D)]
-    var these = this
-    var those = that
-    while (!these.isEmpty && !those.isEmpty) {
-      b += (these.head, those.head)
-      these = these.tail
-      those = those.tail
-    }
-    while (!these.isEmpty) {
-      b += (these.head, thatElem)
-      these = these.tail
-    }
-    while (!those.isEmpty) {
-      b += (thisElem, those.head)
-      those = those.tail
-    }
-    b.toList
-  }
-
-  /** Computes the union of this list and the given list
-   *  <code>that</code>.
-   *
-   *  @param that the list of elements to add to the list.
-   *  @return     a list without doubles containing the elements of this
-   *              list and those of the given list <code>that</code>.
-   */
-  def union[B >: A](that: List[B]): List[B] = {
-    val b = new ListBuffer[B]
-    var these = this
-    while (!these.isEmpty) {
-      if (!that.contains(these.head)) b += these.head
-      these = these.tail
-    }
-    b.prependToList(that)
-  }
-
-  /** Computes the difference between this list and the given list
-   *  <code>that</code>.
-   *
-   *  @param that the list of elements to remove from this list.
-   *  @return     this list without the elements of the given list
-   *              <code>that</code>.
-   */
-  def diff[B >: A](that: List[B]): List[B] = {
-    val b = new ListBuffer[B]
-    var these = this
-    while (!these.isEmpty) {
-      if (!that.contains(these.head)) b += these.head
-      these = these.tail
-    }
-    b.toList
-  }
-   
-  def flatten[B](implicit f : A => Iterable[B]) : List[B] = {
-    val buf = new ListBuffer[B]
-    foreach(f(_).foreach(buf += _))
-    buf.toList
-  }
- 
-
-  /** Computes the intersection between this list and the given list
-   *  <code>that</code>.
-   *
-   *  @param that the list to intersect.
-   *  @return     the list of elements contained both in this list and
-   *              in the given list <code>that</code>.
-   */
-  def intersect[B >: A](that: List[B]): List[B] = filter(x => that contains x)
-
-  /** Removes redundant elements from the list. Uses the method <code>==</code>
-   *  to decide if two elements are identical.
-   *
-   *  @return the list without doubles.
-   */
-  def removeDuplicates: List[A] = {
-    val b = new ListBuffer[A]
-    var these = this
-    while (!these.isEmpty) {
-      if (!these.tail.contains(these.head)) b += these.head
-      these = these.tail
-    }
-    b.toList
-  }
-   
-  override protected def stringPrefix = "List"
-  override def projection = toStream
-  override def toStream : Stream[A] = new Stream.Definite[A] {
-    override def force : List[A] = List.this
-    override def isEmpty = List.this.isEmpty
-    override def head = List.this.head
-    override def tail = List.this.tail.toStream
-    protected def addDefinedElems(buf: StringBuilder, prefix: String): StringBuilder = if (!isEmpty) {
-      var prefix0 = prefix
-      var buf1 = buf.append(prefix0).append(head)
-      prefix0 = ", "
-      var tail0 = tail
-      while (!tail0.isEmpty) {
-        buf1 = buf.append(prefix0).append(tail0.head)
-        tail0 = tail0.tail
-      }
-      buf1
-    } else buf
-  }
-
-}
-
-/** The empty list.
- *
- *  @author  Martin Odersky
- *  @version 1.0, 15/07/2003
- */
- at SerialVersionUID(0 - 8256821097970055419L)
-case object Nil extends List[Nothing] {
-  override def isEmpty = true
-  def head: Nothing =
-    throw new NoSuchElementException("head of empty list")
-  def tail: List[Nothing] =
-    throw new NoSuchElementException("tail of empty list")
-}
-
-/** A non empty list characterized by a head and a tail.
- *
- *  @author  Martin Odersky
- *  @version 1.0, 15/07/2003
- */
- at SerialVersionUID(0L - 8476791151983527571L)
-final case class ::[B](private var hd: B, private[scala] var tl: List[B]) extends List[B] {
-  def head : B = hd
-  def tail : List[B] = tl
-  override def isEmpty: Boolean = false
-}
-
diff --git a/src/cldc-library/scala/Math.scala b/src/cldc-library/scala/Math.scala
deleted file mode 100644
index 6e91d05..0000000
--- a/src/cldc-library/scala/Math.scala
+++ /dev/null
@@ -1,56 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: Math.scala 16881 2009-01-09 16:28:11Z cunei $
-
-
-package scala
-
-/** The object <code>Math</code> contains methods for performing basic numeric
- *  operations such as the elementary exponential, logarithm, square root, and
- *  trigonometric functions.
- */
-object Math {
-
-  /** The smalles possible value for scala.Byte. */
-  val MIN_BYTE   = java.lang.Byte.MIN_VALUE
-  /** The greatest possible value for scala.Byte. */
-  val MAX_BYTE   = java.lang.Byte.MAX_VALUE
-
-  /** The smalles possible value for scala.Short. */
-  val MIN_SHORT  = java.lang.Short.MIN_VALUE
-  /** The greatest possible value for scala.Short. */
-  val MAX_SHORT  = java.lang.Short.MAX_VALUE
-
-  /** The smalles possible value for scala.Char. */
-  val MIN_CHAR   = java.lang.Character.MIN_VALUE
-  /** The greatest possible value for scala.Char. */
-  val MAX_CHAR   = java.lang.Character.MAX_VALUE
-
-  /** The smalles possible value for scala.Int. */
-  val MIN_INT    = java.lang.Integer.MIN_VALUE
-  /** The greatest possible value for scala.Int. */
-  val MAX_INT    = java.lang.Integer.MAX_VALUE
-
-  /** The smalles possible value for scala.Long. */
-  val MIN_LONG   = java.lang.Long.MIN_VALUE
-  /** The greatest possible value for scala.Long. */
-  val MAX_LONG   = java.lang.Long.MAX_VALUE
-
-
-  def abs(x: Int): Int = java.lang.Math.abs(x)
-  def abs(x: Long): Long = java.lang.Math.abs(x)
-
-  def max(x: Int, y: Int): Int = java.lang.Math.max(x, y)
-  def max(x: Long, y: Long): Long = java.lang.Math.max(x, y)
-
-  def min(x: Int, y: Int): Int = java.lang.Math.min(x, y)
-  def min(x: Long, y: Long): Long  = java.lang.Math.min(x, y)
-
-  def sqrt(x: Int): Int = runtime.SquareRoot.accurateSqrt(x)
-}
diff --git a/src/cldc-library/scala/Predef.scala b/src/cldc-library/scala/Predef.scala
deleted file mode 100644
index 7855f83..0000000
--- a/src/cldc-library/scala/Predef.scala
+++ /dev/null
@@ -1,285 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: Predef.scala 16881 2009-01-09 16:28:11Z cunei $
-
-
-package scala
-
-
-/** The <code>Predef</code> object provides definitions that are
- *  accessible in all Scala compilation units without explicit
- *  qualification.
- */
-object Predef {
-
-  // classOf dummy ------------------------------------------------------
-
-  /** Return the runtime representation of a class type. */
-  def classOf[T]: Class[T] = null
-
-  // aliases ------------------------------------------------------------
-
-  type byte    = scala.Byte
-  type short   = scala.Short
-  type char    = scala.Char
-  type int     = scala.Int
-  type long    = scala.Long
-  type boolean = scala.Boolean
-  type unit    = scala.Unit
-
-  /** @deprecated use <code>Int</code> instead */
-  @deprecated type Integer = java.lang.Integer
-  /** @deprecated use <code>Char</code> instead */
-  @deprecated type Character = java.lang.Character
-
-  type String        = java.lang.String
-  type Class[T]      = java.lang.Class[T]
-  type Runnable      = java.lang.Runnable
-
-  type Throwable = java.lang.Throwable
-  type Exception = java.lang.Exception
-  type Error     = java.lang.Error
-
-  type AssertionError                  = java.lang.Error
-  type RuntimeException                = java.lang.RuntimeException
-  type NullPointerException            = java.lang.NullPointerException
-  type ClassCastException              = java.lang.ClassCastException
-  type IndexOutOfBoundsException       = java.lang.IndexOutOfBoundsException
-  type ArrayIndexOutOfBoundsException  = java.lang.ArrayIndexOutOfBoundsException
-  type StringIndexOutOfBoundsException = java.lang.StringIndexOutOfBoundsException
-  type UnsupportedOperationException   = RuntimeException //java.lang.UnsupportedOperationException
-  type IllegalArgumentException        = java.lang.IllegalArgumentException
-  type NoSuchElementException          = java.util.NoSuchElementException
-  type NumberFormatException           = java.lang.NumberFormatException
-
-  // miscelleaneous -----------------------------------------------------
-
-  //val $scope = scala.xml.TopScope
-
-  type Function[-A, +B] = Function1[A, B]
-
-  type Map[A, B] = collection.immutable.Map[A, B]
-  type Set[A] = collection.immutable.Set[A]
-
-  val Map = collection.immutable.Map
-  val Set = collection.immutable.Set
-
-  // errors and asserts -------------------------------------------------
-
-  def error(message: String): Nothing = throw new Error(message)
-
-  def exit: Nothing = exit(0)
-
-  def exit(status: Int): Nothing = {
-    java.lang.System.exit(status)
-    throw new Throwable()
-  }
-
-  def assert(assertion: Boolean) {
-    if (!assertion)
-      throw new AssertionError("assertion failed")
-  }
-
-  def assert(assertion: Boolean, message: Any) {
-    if (!assertion)
-      throw new AssertionError("assertion failed: " + message)
-  }
-
-  def assume(assumption: Boolean) {
-    if (!assumption)
-      throw new IllegalArgumentException("assumption failed")
-  }
-
-  def assume(assumption: Boolean, message: Any) {
-    if (!assumption)
-      throw new IllegalArgumentException("assumption failed: " + message)
-  }
-
-  // tupling ------------------------------------------------------------
-
-  type Pair[+A, +B] = Tuple2[A, B]
-  object Pair {
-    def apply[A, B](x: A, y: B) = Tuple2(x, y)
-    def unapply[A, B](x: Tuple2[A, B]): Option[Tuple2[A, B]] = Some(x)
-  }
-
-  type Triple[+A, +B, +C] = Tuple3[A, B, C]
-  object Triple {
-    def apply[A, B, C](x: A, y: B, z: C) = Tuple3(x, y, z)
-    def unapply[A, B, C](x: Tuple3[A, B, C]): Option[Tuple3[A, B, C]] = Some(x)
-  }
-
-  class ArrowAssoc[A](x: A) {
-    def -> [B](y: B): Tuple2[A, B] = Tuple2(x, y)
-  }
-  implicit def any2ArrowAssoc[A](x: A): ArrowAssoc[A] = new ArrowAssoc(x)
-
-  def Tuple[A1](x1: A1) = Tuple1(x1)
-  def Tuple[A1, A2](x1: A1, x2: A2) = Tuple2(x1, x2)
-  def Tuple[A1, A2, A3](x1: A1, x2: A2, x3: A3) = Tuple3(x1, x2, x3)
-  def Tuple[A1, A2, A3, A4](x1: A1, x2: A2, x3: A3, x4: A4) = Tuple4(x1, x2, x3, x4)
-  def Tuple[A1, A2, A3, A4, A5](x1: A1, x2: A2, x3: A3, x4: A4, x5: A5) = Tuple5(x1, x2, x3, x4, x5)
-  def Tuple[A1, A2, A3, A4, A5, A6](x1: A1, x2: A2, x3: A3, x4: A4, x5: A5, x6: A6) = Tuple6(x1, x2, x3, x4, x5, x6)
-  def Tuple[A1, A2, A3, A4, A5, A6, A7](x1: A1, x2: A2, x3: A3, x4: A4, x5: A5, x6: A6, x7: A7) = Tuple7(x1, x2, x3, x4, x5, x6, x7)
-  def Tuple[A1, A2, A3, A4, A5, A6, A7, A8](x1: A1, x2: A2, x3: A3, x4: A4, x5: A5, x6: A6, x7: A7, x8: A8) = Tuple8(x1, x2, x3, x4, x5, x6, x7, x8)
-  def Tuple[A1, A2, A3, A4, A5, A6, A7, A8, A9](x1: A1, x2: A2, x3: A3, x4: A4, x5: A5, x6: A6, x7: A7, x8: A8, x9: A9) = Tuple9(x1, x2, x3, x4, x5, x6, x7, x8, x9)
-
-  // printing and reading -----------------------------------------------
-
-  def print(x: Any) = Console.print(x)
-  def println() = Console.println()
-  def println(x: Any) = Console.println(x)
-
-  // views --------------------------------------------------------------
-
-  implicit def identity[A](x: A): A = x
-
-  implicit def byteWrapper(x: Byte)     = new runtime.RichByte(x)
-  implicit def shortWrapper(x: Short)   = new runtime.RichShort(x)
-  implicit def intWrapper(x: Int)       = new runtime.RichInt(x)
-  implicit def charWrapper(c: Char)     = new runtime.RichChar(c)
-  implicit def longWrapper(x: Long)     = new runtime.RichLong(x)
-
-  implicit def booleanWrapper(x: Boolean)  = new runtime.RichBoolean(x)
-
-  implicit def stringWrapper(x: String) = new runtime.RichString(x)
-  implicit def stringBuilderWrapper(x : StringBuilder) = new runtime.RichStringBuilder(x)
-
-  implicit def any2stringadd(x: Any) = new runtime.StringAdd(x)
-
-  implicit def exceptionWrapper(exc: Throwable) = new runtime.RichException(exc)
-
-  implicit def unit2ordered(x: Unit): Ordered[Unit] = new Ordered[Unit] with Proxy {
-    def self: Any = x
-    def compare(y: Unit): Int = 0
-  }
-
-  implicit def iterable2ordered[A <% Ordered[A]](xs: Iterable[A]): Ordered[Iterable[A]] =
-    new Ordered[Iterable[A]] with Proxy {
-      val self = xs
-      def compare(that: Iterable[A]): Int = {
-        var res = 0
-        val these = xs.elements
-        val those = that.elements
-        while (res == 0 && these.hasNext)
-          res = if (those.hasNext) these.next compare those.next else 1
-        if (res == 0) {
-          if (those.hasNext) -1 else 0
-        } else 
-          res
-      }
-    }
-
-  implicit def tuple22ordered[A1 <% Ordered[A1], A2 <% Ordered[A2]](x: Tuple2[A1, A2]): Ordered[Tuple2[A1, A2]] = 
-    new Ordered[Tuple2[A1, A2]] with Proxy {
-      val self = x
-      def compare(y: Tuple2[A1, A2]): Int = {
-        val res = x._1 compare y._1
-        if (res == 0) x._2 compare y._2
-        else res
-      }
-    }
-
-  implicit def tuple32ordered[A1 <% Ordered[A1], A2 <% Ordered[A2], A3 <% Ordered[A3]](x: Tuple3[A1, A2, A3]): Ordered[Tuple3[A1, A2, A3]] = 
-    new Ordered[Tuple3[A1, A2, A3]] with Proxy {
-      val self = x
-      def compare(y: Tuple3[A1, A2, A3]): Int = {
-        val res = x._1 compare y._1
-        if (res == 0) Tuple2(x._2, x._3) compare Tuple2(y._2, y._3)
-        else res
-      }
-    }
-
-  implicit def tuple42ordered[A1 <% Ordered[A1], A2 <% Ordered[A2], A3 <% Ordered[A3], A4 <% Ordered[A4]](x: Tuple4[A1, A2, A3, A4]): Ordered[Tuple4[A1, A2, A3, A4]] = 
-    new Ordered[Tuple4[A1, A2, A3, A4]] with Proxy {
-      val self = x
-      def compare(y: Tuple4[A1, A2, A3, A4]): Int = {
-        val res = x._1 compare y._1
-        if (res == 0) Tuple3(x._2, x._3, x._4) compare Tuple3(y._2, y._3, y._4)
-        else res
-      }
-    }
-
-  implicit def tuple52ordered[A1 <% Ordered[A1], A2 <% Ordered[A2], A3 <% Ordered[A3], A4 <% Ordered[A4], A5 <% Ordered[A5]](x: Tuple5[A1, A2, A3, A4, A5]): Ordered[Tuple5[A1, A2, A3, A4, A5]] = 
-    new Ordered[Tuple5[A1, A2, A3, A4, A5]] with Proxy {
-      val self = x
-      def compare(y: Tuple5[A1, A2, A3, A4, A5]): Int = {
-        val res = x._1 compare y._1
-        if (res == 0) Tuple4(x._2, x._3, x._4, x._5) compare Tuple4(y._2, y._3, y._4, y._5)
-        else res
-      }
-    }
-
-  implicit def tuple62ordered[A1 <% Ordered[A1], A2 <% Ordered[A2], A3 <% Ordered[A3], A4 <% Ordered[A4], A5 <% Ordered[A5], A6 <% Ordered[A6]](x: Tuple6[A1, A2, A3, A4, A5, A6]): Ordered[Tuple6[A1, A2, A3, A4, A5, A6]] = 
-    new Ordered[Tuple6[A1, A2, A3, A4, A5, A6]] with Proxy {
-      val self = x
-      def compare(y: Tuple6[A1, A2, A3, A4, A5, A6]): Int = {
-        val res = x._1 compare y._1
-        if (res == 0) Tuple5(x._2, x._3, x._4, x._5, x._6) compare Tuple5(y._2, y._3, y._4, y._5, y._6)
-        else res
-      }
-    }
-
-  implicit def tuple72ordered[A1 <% Ordered[A1], A2 <% Ordered[A2], A3 <% Ordered[A3], A4 <% Ordered[A4], A5 <% Ordered[A5], A6 <% Ordered[A6], A7 <% Ordered[A7]](x: Tuple7[A1, A2, A3, A4, A5, A6, A7]): Ordered[Tuple7[A1, A2, A3, A4, A5, A6, A7]] = 
-    new Ordered[Tuple7[A1, A2, A3, A4, A5, A6, A7]] with Proxy {
-      val self = x
-      def compare(y: Tuple7[A1, A2, A3, A4, A5, A6, A7]): Int = {
-        val res = x._1 compare y._1
-        if (res == 0) Tuple6(x._2, x._3, x._4, x._5, x._6, x._7) compare Tuple6(y._2, y._3, y._4, y._5, y._6, y._7)
-        else res
-      }
-    }
-
-  implicit def tuple82ordered[A1 <% Ordered[A1], A2 <% Ordered[A2], A3 <% Ordered[A3], A4 <% Ordered[A4], A5 <% Ordered[A5], A6 <% Ordered[A6], A7 <% Ordered[A7], A8 <% Ordered[A8]](x: Tuple8[A1, A2, A3, A4, A5, A6, A7, A8]): Ordered[Tuple8[A1, A2, A3, A4, A5, A6, A7, A8]] = 
-    new Ordered[Tuple8[A1, A2, A3, A4, A5, A6, A7, A8]] with Proxy {
-      val self = x
-      def compare(y: Tuple8[A1, A2, A3, A4, A5, A6, A7, A8]): Int = {
-        val res = x._1 compare y._1
-        if (res == 0) Tuple7(x._2, x._3, x._4, x._5, x._6, x._7, x._8) compare Tuple7(y._2, y._3, y._4, y._5, y._6, y._7, y._8)
-        else res
-      }
-    }
-
-  implicit def tuple92ordered[A1 <% Ordered[A1], A2 <% Ordered[A2], A3 <% Ordered[A3], A4 <% Ordered[A4], A5 <% Ordered[A5], A6 <% Ordered[A6], A7 <% Ordered[A7], A8 <% Ordered[A8], A9 <% Ordered[A9]](x: Tuple9[A1, A2, A3, A4, A5, A6, A7, A8, A9]): Ordered[Tuple9[A1, A2, A3, A4, A5, A6, A7, A8, A9]] = 
-    new Ordered[Tuple9[A1, A2, A3, A4, A5, A6, A7, A8, A9]] with Proxy {
-      val self = x
-      def compare(y: Tuple9[A1, A2, A3, A4, A5, A6, A7, A8, A9]): Int = {
-        val res = x._1 compare y._1
-        if (res == 0) Tuple8(x._2, x._3, x._4, x._5, x._6, x._7, x._8, x._9) compare Tuple8(y._2, y._3, y._4, y._5, y._6, y._7, y._8, y._9)
-        else res
-      }
-    }
-
-  implicit def byte2short(x: Byte): Short = x.toShort
-  implicit def byte2int(x: Byte): Int = x.toInt
-  implicit def byte2long(x: Byte): Long = x.toLong
-
-  implicit def short2int(x: Short): Int = x.toInt
-  implicit def short2long(x: Short): Long = x.toLong
-
-  implicit def char2int(x: Char): Int = x.toInt
-  implicit def char2long(x: Char): Long = x.toLong
-
-  implicit def int2long(x: Int): Long = x.toLong
-
-  implicit def byte2Byte(x: Byte) = new java.lang.Byte(x)
-  implicit def short2Short(x: Short) = new java.lang.Short(x)
-  implicit def char2Character(x: Char) = new java.lang.Character(x)
-  implicit def int2Integer(x: Int) = new java.lang.Integer(x)
-  implicit def long2Long(x: Long) = new java.lang.Long(x)
-  implicit def boolean2Boolean(x: Boolean) = new java.lang.Boolean(x)
-
-  /** any array projection can be automatically converted into an array */
-  implicit def forceArrayProjection[A](x: Array.Projection[A]): Array[A] = x.force
-  /** any random access character seq (including rich string can be converted into a string */
-  implicit def forceRandomAccessCharSeq(x: runtime.RichString): String = x.mkString
-
-  def currentThread = java.lang.Thread.currentThread()
-
-}
diff --git a/src/cldc-library/scala/Random.scala b/src/cldc-library/scala/Random.scala
deleted file mode 100644
index 09c92ca..0000000
--- a/src/cldc-library/scala/Random.scala
+++ /dev/null
@@ -1,41 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: Random.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala
-
-/** (see http://java.sun.com/javame/reference/apis/jsr030/)
- *
- *  @author Stephane Micheloud
- */
-class Random(val self: java.util.Random) {
-
-  /** Creates a new random number generator using a single long seed. */
-  def this(seed: Long) = this(new java.util.Random(seed))
-
-  /** Creates a new random number generator using a single integer seed. */
-  def this(seed: Int) = this(seed.toLong)
-
-  /** Creates a new random number generator. */
-  def this() = this(compat.Platform.currentTime)
-
-  /** Returns the next pseudorandom, uniformly distributed int value
-   *  from this random number generator's sequence.
-   */
-  def nextInt(): Int = self.nextInt()
-
-  /** Returns the next pseudorandom, uniformly distributed long value
-   *  from this random number generator's sequence.
-   */
-  def nextLong(): Long = self.nextLong()
-
-  def setSeed(seed: Long) { self.setSeed(seed) }
- 
-}
diff --git a/src/cldc-library/scala/StringBuilder.scala b/src/cldc-library/scala/StringBuilder.scala
deleted file mode 100644
index 4aae511..0000000
--- a/src/cldc-library/scala/StringBuilder.scala
+++ /dev/null
@@ -1,862 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: StringBuilder.scala 16881 2009-01-09 16:28:11Z cunei $
-
-
-package scala
-
-import Predef._
-
-/** <p>
- *    A mutable sequence of characters.  This class provides an API compatible
- *    with <code>java.lang.StringBuilder</code>, but with no guarantee of
- *    synchronization.
- *  </p>
- *
- *  @author Stephane Micheloud
- *  @version 1.0
- */
-final class StringBuilder(initCapacity: Int, private val initValue: String)
-extends (Int => Char) with Proxy {
-  if (initCapacity < 0) throw new IllegalArgumentException
-  if (initValue eq null) throw new NullPointerException
-
-  /** The value is used for character storage. */
-  private var value = new Array[Char](initCapacity + initValue.length)
-
-  /** The count is the number of characters used. */
-  private var count: Int = 0
-
-  /** Constructs a string builder with no characters in it and an 
-   *  initial capacity of 16 characters.
-   */
-  def this() = this(16, "")
-
-  /** Constructs a string builder with no characters in it and an 
-   *  initial capacity specified by the <code>capacity</code> argument. 
-   *
-   *  @param  capacity  the initial capacity.
-   *  @throws NegativeArraySizeException  if the <code>capacity</code>
-   *                    argument is less than <code>0</code>.
-   */
-  def this(capacity: Int) = this(capacity, "")
-
-  def this(str: String) = this(16, str)
-
-  append(initValue)
-
-  def self = this
-
-  def toArray: Array[Char] = value
-
-  def length: Int = count
-
-  def length_=(n: Int) { setLength(n) }
-
-  /** Sets the length of the character sequence.
-   *
-   *  @param  newLength  the new length
-   *  @throws IndexOutOfBoundsException  if the <code>n</code> argument is negative.
-   */
-  def setLength(n: Int) {
-    if (n < 0)
-      throw new StringIndexOutOfBoundsException(n)
-    if (n > value.length) expandCapacity(n)
-    if (count < n)
-      while (count < n) {
-        value(count) = '\0'; count += 1
-      }
-    else
-      count = n
-  }
-
-  /** Returns the current capacity. The capacity is the amount of storage 
-   *  available for newly inserted characters, beyond which an allocation 
-   *  will occur.
-   *
-   *  @return  the current capacity
-   */
-  def capacity: Int = value.length
-
-  /** Same as <code>ensureCapacity</code>. */
-  def capacity_=(n: Int) { ensureCapacity(n) }
-
-  /** <p>
-   *    Ensures that the capacity is at least equal to the specified minimum.
-   *    If the current capacity is less than the argument, then a new internal
-   *    array is allocated with greater capacity. The new capacity is the larger of: 
-   *  </p>
-   *  <ul>
-   *    <li>The <code>n</code> argument. 
-   *    <li>Twice the old capacity, plus <code>2</code>. 
-   *  </ul>
-   *  <p>
-   *    If the <code>n</code> argument is non-positive, this
-   *    method takes no action and simply returns.
-   *  </p>
-   *
-   *  @param n the minimum desired capacity.
-   */
-  def ensureCapacity(n: Int) {
-    if (n > value.length) expandCapacity(n)
-  }
-
-  private def expandCapacity(n: Int) {
-    val newCapacity = (value.length + 1) * 2
-    value = StringBuilder.copyOf(
-      value,
-      if (newCapacity < 0) Math.MAX_INT else if (n > newCapacity) n else newCapacity
-    )
-  }
- 
-  /** <p>
-   *    Returns the <code>Char</code> value in this sequence at the specified index.
-   *    The first <code>Char</code> value is at index <code>0</code>, the next at index
-   *    <code>1</code>, and so on, as in array indexing.
-   *  </p>
-   *  <p>
-   *    The index argument must be greater than or equal to
-   *    <code>0</code>, and less than the length of this sequence.
-   *  </p>
-   *
-   *  @param  index   the index of the desired <code>Char</code> value.
-   *  @return         the <code>Char</code> value at the specified index.
-   *  @throws IndexOutOfBoundsException  if <code>index</code> is 
-   *                  negative or greater than or equal to <code>length()</code>.
-   */
-  def charAt(index: Int): Char = {
-    if (index < 0 || index >= count)
-      throw new StringIndexOutOfBoundsException(index)
-    value(index)
-  }
-
-  /** Same as <code>charAt</code>. */
-  def apply(i: Int): Char = charAt(i)
-
-  /** <p>
-   *    Removes the <code>Char</code> at the specified position in this
-   *    sequence. This sequence is shortened by one <code>Char</code>.
-   *  </p>
-   *
-   *  @param  index  Index of <code>Char</code> to remove
-   *  @return        This object.
-   *  @throws StringIndexOutOfBoundsException  if the <code>index</code>
-   *	             is negative or greater than or equal to <code>length()</code>.
-   */
-  def deleteCharAt(index: Int): StringBuilder = {
-    if (index < 0 || index >= count)
-      throw new StringIndexOutOfBoundsException(index)
-    compat.Platform.arraycopy(value, index + 1, value, index, count - index - 1)
-    count -= 1
-    this
-  }
-
-  /** <p>
-   *    The character at the specified index is set to <code>ch</code>. This 
-   *    sequence is altered to represent a new character sequence that is 
-   *    identical to the old character sequence, except that it contains the 
-   *    character <code>ch</code> at position <code>index</code>. 
-   *  </p>
-   *  <p>
-   *    The index argument must be greater than or equal to 
-   *    <code>0</code>, and less than the length of this sequence. 
-   *  </p>
-   *
-   *  @param  index   the index of the character to modify.
-   *  @param  ch      the new character.
-   *  @throws IndexOutOfBoundsException  if <code>index</code> is 
-   *                  negative or greater than or equal to <code>length()</code>.
-   */
-  def setCharAt(index: Int, c: Char) {
-    if (index < 0 || index >= count)
-      throw new StringIndexOutOfBoundsException(index)
-    value(index) = c
-  }
-
-  /** Same as <code>setCharAt</code>. */
-  def update(i: Int, c: Char) { setCharAt(i, c) }
-
-  /** Returns a new <code>String</code> that contains a subsequence of
-   *  characters currently contained in this character sequence. The 
-   *  substring begins at the specified index and extends to the end of
-   *  this sequence.
-   * 
-   *  @param  start  The beginning index, inclusive.
-   *  @return        The new string.
-   *  @throws StringIndexOutOfBoundsException  if <code>start</code> is
-   *                 less than zero, or greater than the length of this object.
-   */
-  def substring(start: Int): String = substring(start, count)
-
-  /** Returns a new <code>String</code> that contains a subsequence of
-   *  characters currently contained in this sequence. The 
-   *  substring begins at the specified <code>start</code> and 
-   *  extends to the character at index <code>end - 1</code>.
-   *
-   *  @param  start  The beginning index, inclusive.
-   *  @param  end    The ending index, exclusive.
-   *  @return The new string.
-   *  @throws StringIndexOutOfBoundsException  if <code>start</code>
-   *                 or <code>end</code> are negative or greater than
-   *		     <code>length()</code>, or <code>start</code> is
-   *		     greater than <code>end</code>.
-   */
-  def substring(start: Int, end: Int): String = {
-    if (start < 0)
-      throw new StringIndexOutOfBoundsException(start)
-    if (end > count)
-      throw new StringIndexOutOfBoundsException(end)
-    if (start > end)
-      throw new StringIndexOutOfBoundsException(end - start)
-    new String(value, start, end - start)
-  }
-
-  /** <p>
-   *    Appends the string representation of the <code>Any</code> 
-   *    argument.
-   *  </p>
-   *  <p>
-   *    The argument is converted to a string as if by the method 
-   *    <code>String.valueOf</code>, and the characters of that 
-   *    string are then appended to this sequence.
-   *  </p>
-   *
-   *  @param  x   an <code>Any</code> object.
-   *  @return     a reference to this object.
-   */
-  def append(x: Any): StringBuilder =
-    append(String.valueOf(x))
-
-  /** Appends the specified string to this character sequence.
-   *
-   *  @param  s   a string.
-   *  @return     a reference to this object.
-   */
-  def append(s: String): StringBuilder = {
-    val str = if (s == null) "null" else s
-    val len = str.length
-    if (len > 0) {
-      val newCount = count + len
-      if (newCount > value.length) expandCapacity(newCount)
-      compat.Platform.arraycopy(str.toCharArray, 0, value, count, len)
-      count = newCount
-    }
-    this
-  }
-
-  /** Appends the specified string builder to this sequence.
-   *
-   *  @param sb
-   *  @return 
-   */
-  def append(sb: StringBuilder): StringBuilder =
-    if (sb == null)
-      append("null")
-    else {
-      val len = sb.length
-      val newCount = count + len
-      if (newCount > value.length) expandCapacity(newCount)
-      compat.Platform.arraycopy(sb.toArray, 0, value, count, len)
-      count = newCount
-      this
-    }
-
-  /** <p>
-   *    Appends the string representation of the <code>Char</code> sequence 
-   *    argument to this sequence.
-   *  </p>
-   *  <p>
-   *    The characters of the sequence argument are appended, in order,
-   *    to the contents of this sequence. The length of this sequence
-   *    increases by the length of the argument.
-   *  </p>
-   *
-   *  @param  x  the characters to be appended.
-   *  @return    a reference to this object.
-   */
-  def append(x: Seq[Char]): StringBuilder =
-    append(x.toArray, 0, x.length)
-
-  /** <p>
-   *    Appends the string representation of the <code>Char</code> array 
-   *    argument to this sequence.
-   *  </p>
-   *  <p>
-   *    The characters of the array argument are appended, in order, to 
-   *    the contents of this sequence. The length of this sequence
-   *    increases by the length of the argument.
-   *  </p>
-   *
-   *  @param  x  the characters to be appended.
-   *  @return    a reference to this object.
-   */
-  def append(x: Array[Char]): StringBuilder =
-    append(x, 0, x.length)
-
-  /** <p>
-   *    Appends the string representation of a subarray of the
-   *    <code>char</code> array argument to this sequence.
-   *  </p>
-   *  <p>
-   *    Characters of the <code>Char</code> array <code>x</code>, starting at
-   *    index <code>offset</code>, are appended, in order, to the contents
-   *    of this sequence. The length of this sequence increases
-   *    by the value of <code>len</code>.
-   *  </p>
-   *
-   *  @param  x      the characters to be appended.
-   *  @param  offset the index of the first <code>Char</code> to append.
-   *  @param  len    the number of <code>Char</code>s to append.
-   *  @return        a reference to this object.
-   */
-  def append(x: Array[Char], offset: Int, len: Int): StringBuilder = {
-    val newCount = count + len
-    if (newCount > value.length) expandCapacity(newCount)
-    compat.Platform.arraycopy(x, offset, value, count, len)
-    count = newCount
-    this
-  }
-
-  /** <p>
-   *    Appends the string representation of the <code>Boolean</code> 
-   *    argument to the sequence.
-   *  </p>
-   *  <p>
-   *    The argument is converted to a string as if by the method 
-   *    <code>String.valueOf</code>, and the characters of that 
-   *   string are then appended to this sequence. 
-   *  </p>
-   *
-   *   @param  x  a <code>Boolean</code>.
-   *   @return    a reference to this object.
-   */
-  def append(x: Boolean): StringBuilder = {
-    if (x) {
-      val newCount = count + 4
-      if (newCount > value.length) expandCapacity(newCount)
-      value(count) = 't'; count += 1
-      value(count) = 'r'; count += 1
-      value(count) = 'u'; count += 1
-      value(count) = 'e'; count += 1
-    } else {
-      val newCount = count + 5
-      if (newCount > value.length) expandCapacity(newCount)
-      value(count) = 'f'; count += 1
-      value(count) = 'a'; count += 1
-      value(count) = 'l'; count += 1
-      value(count) = 's'; count += 1
-      value(count) = 'e'; count += 1
-    }
-    this
-  }
-
-  def append(x: Byte): StringBuilder =
-    append(String.valueOf(x))
-
-  def append(x: Char): StringBuilder = {
-    val newCount = count + 1
-    if (newCount > value.length) expandCapacity(newCount)
-    value(count) = x; count += 1
-    this
-  }
-
-  def append(x: Short): StringBuilder =
-    append(String.valueOf(x))
-
-  def append(x: Int): StringBuilder =
-    append(String.valueOf(x))
-
-  def append(x: Long): StringBuilder =
-    append(String.valueOf(x))
-
-  /** Removes the characters in a substring of this sequence.
-   *  The substring begins at the specified <code>start</code> and extends to
-   *  the character at index <code>end - 1</code> or to the end of the
-   *  sequence if no such character exists. If
-   *  <code>start</code> is equal to <code>end</code>, no changes are made.
-   *
-   *  @param  start  The beginning index, inclusive.
-   *  @param  end    The ending index, exclusive.
-   *  @return        This object.
-   *  @throws StringIndexOutOfBoundsException  if <code>start</code>
-   *                 is negative, greater than <code>length()</code>, or
-   *		     greater than <code>end</code>.
-   */
-  def delete(start: Int, end: Int): StringBuilder = {
-    if (start < 0 || start > end)
-      throw new StringIndexOutOfBoundsException(start)
-    val end0 = if (end > count) count else end
-    val len = end0 - start
-    if (len > 0) {
-      compat.Platform.arraycopy(value, start + len, value, start, count - end0)
-      count -= len
-    }
-    this
-  }
-
-  /** Replaces the characters in a substring of this sequence
-   *  with characters in the specified <code>String</code>. The substring
-   *  begins at the specified <code>start</code> and extends to the character
-   *  at index <code>end - 1</code> or to the end of the sequence if no such
-   *  character exists. First the characters in the substring are removed and
-   *  then the specified <code>String</code> is inserted at <code>start</code>.
-   * 
-   *  @param  start  The beginning index, inclusive.
-   *  @param  end    The ending index, exclusive.
-   *  @param  str    String that will replace previous contents.
-   *  @return        This object.
-   *  @throws StringIndexOutOfBoundsException  if <code>start</code>
-   *                 is negative, greater than <code>length()</code>, or
-   *		     greater than <code>end</code>.
-   */
-  def replace(start: Int, end: Int, str: String) {
-    if (start < 0 || start > count || start > end)
-      throw new StringIndexOutOfBoundsException(start)
-
-    val end0 = if (end > count) count else end
-    val len = str.length()
-    val newCount = count + len - (end0 - start)
-    if (newCount > value.length) expandCapacity(newCount)
-
-    compat.Platform.arraycopy(value, end, value, start + len, count - end)
-    compat.Platform.arraycopy(str.toArray, 0, value, start, len)
-    count = newCount
-    this
-  }
-
-  /** Inserts the string representation of a subarray of the <code>str</code>
-   *  array argument into this sequence. The subarray begins at the specified
-   *  <code>offset</code> and extends <code>len</code> <code>char</code>s.
-   *  The characters of the subarray are inserted into this sequence at
-   *  the position indicated by <code>index</code>. The length of this
-   *  sequence increases by <code>len</code> <code>Char</code>s.
-   *
-   * @param  index   position at which to insert subarray.
-   * @param  str     a <code>Char</code> array.
-   * @param  offset  the index of the first <code>char</code> in subarray to
-   *                 be inserted.
-   * @param  len     the number of <code>Char</code>s in the subarray to
-   *                 be inserted.
-   * @return         This object
-   * @throws StringIndexOutOfBoundsException  if <code>index</code>
-   *                 is negative or greater than <code>length()</code>, or
-   *                 <code>offset</code> or <code>len</code> are negative, or
-   *                 <code>(offset+len)</code> is greater than
-   *                 <code>str.length</code>.
-   */
-  def insert(index: Int, str: Array[Char], offset: Int, len: Int): StringBuilder = {
-    if (index < 0 || index > count)
-      throw new StringIndexOutOfBoundsException(index)
-    if (offset < 0 || len < 0 || offset > str.length - len)
-      throw new StringIndexOutOfBoundsException(
-                "offset " + offset + ", len " + len +
-                ", str.length " + str.length)
-    val newCount = count + len
-    if (newCount > value.length) expandCapacity(newCount)
-    compat.Platform.arraycopy(value, index, value, index + len, count - index)
-    compat.Platform.arraycopy(str, offset, value, index, len)
-    count = newCount
-    this
-  }
-
-  /** <p>
-   *    Inserts the string representation of the <code>Any</code> 
-   *    argument into this character sequence.
-   *  </p>
-   *  <p>
-   *    The second argument is converted to a string as if by the method 
-   *    <code>String.valueOf</code>, and the characters of that 
-   *    string are then inserted into this sequence at the indicated 
-   *    offset. 
-   *  </p>
-   *  <p>
-   *    The offset argument must be greater than or equal to 
-   *    <code>0</code>, and less than or equal to the length of this 
-   *    sequence.
-   *  </p>
-   *
-   *  @param  offset  the offset.
-   *  @param  x       an <code>Any</code> value.
-   *  @return         a reference to this object.
-   *  @throws StringIndexOutOfBoundsException  if the offset is invalid.
-   */
-  def insert(at: Int, x: Any): StringBuilder =
-    insert(at, String.valueOf(x))
-
-  /** Inserts the string into this character sequence.
-   *
-   *  @param  at  the offset position.
-   *  @param  x   a string.
-   *  @return     a reference to this object.
-   *  @throws StringIndexOutOfBoundsException  if the offset is invalid.
-   */
-  def insert(at: Int, x: String): StringBuilder = {
-    if (at < 0 || at > count)
-      throw new StringIndexOutOfBoundsException(at)
-    val str = if (x == null) "null" else x
-    val len = str.length
-    val newCount = count + len
-    if (newCount > value.length) expandCapacity(newCount)
-    compat.Platform.arraycopy(value, at, value, at + len, count - at)
-    compat.Platform.arraycopy(str.toArray: Array[Char], 0, value, at, len)
-    count = newCount
-    this
-  }
-
-  /** Inserts the string representation of the <code>Char</code> sequence 
-   *  argument into this sequence.
-   *
-   *  @param  at  the offset position.
-   *  @param  x   a character sequence.
-   *  @return     a reference to this object.
-   *  @throws StringIndexOutOfBoundsException  if the offset is invalid.
-   */
-  def insert(at: Int, x: Seq[Char]): StringBuilder =
-    insert(at, x.toArray)
-
-  /** Inserts the string representation of the <code>Char</code> array 
-   *  argument into this sequence.
-   *
-   *  @param  at  the offset position.
-   *  @param  x   a character array.
-   *  @return     a reference to this object.
-   *  @throws StringIndexOutOfBoundsException  if the offset is invalid.
-   */
-  def insert(at: Int, x: Array[Char]): StringBuilder = {
-    if (at < 0 || at > count)
-      throw new StringIndexOutOfBoundsException(at)
-    val len = x.length
-    val newCount = count + len
-    if (newCount > value.length) expandCapacity(newCount)
-    compat.Platform.arraycopy(value, at, value, at + len, count - at)
-    compat.Platform.arraycopy(x, 0, value, at, len)
-    count = newCount
-    this
-  }
-
-  /** <p>
-   *    Inserts the string representation of the <code>Boolean</code> argument
-   *    into this sequence.
-   *  </p>
-   *  <p>
-   *    The offset argument must be greater than or equal to 0, and less than
-   *    or equal to the length of this sequence.
-   *  </p>
-   *
-   *  @param  at  the offset position.
-   *  @param  x   a <code>Boolean</code> value.
-   *  @return     a reference to this object.
-   */
-  def insert(at: Int, x: Boolean): StringBuilder =
-    insert(at, String.valueOf(x))
-
-  /** <p>
-   *    Inserts the string representation of the <code>Byte</code> argument
-   *    into this sequence.
-   *  </p>
-   *  <p>
-   *    The offset argument must be greater than or equal to 0, and less than
-   *    or equal to the length of this sequence.
-   *  </p>
-   *
-   *  @param  at  the offset position.
-   *  @param  x   a <code>Byte</code> value.
-   *  @return     a reference to this object.
-   */
-  def insert(at: Int, x: Byte): StringBuilder =
-    insert(at, String.valueOf(x))
-
-  /** <p>
-   *    Inserts the string representation of the <code>Char</code> argument
-   *    into this sequence.
-   *  </p>
-   *  <p>
-   *    The offset argument must be greater than or equal to 0, and less than
-   *    or equal to the length of this sequence.
-   *  </p>
-   *
-   *  @param  at  the offset position.
-   *  @param  x   a <code>Char</code> value.
-   *  @return     a reference to this object.
-   */
-  def insert(at: Int, x: Char): StringBuilder = {
-    if (at < 0 || at > count)
-      throw new StringIndexOutOfBoundsException(at)
-    val newCount = count + 1
-    if (newCount > value.length) expandCapacity(newCount)
-    compat.Platform.arraycopy(value, at, value, at + 1, count - at)
-    value(at) = x
-    count = newCount
-    this
-  }
-
-  /** <p>
-   *    Inserts the string representation of the <code>Short</code> argument
-   *    into this sequence.
-   *  </p>
-   *  <p>
-   *    The offset argument must be greater than or equal to 0, and less than
-   *    or equal to the length of this sequence.
-   *  </p>
-   *
-   *  @param  at  the offset position.
-   *  @param  x   a <code>Short</code> value.
-   *  @return     a reference to this object.
-   */
-  def insert(at: Int, x: Short): StringBuilder =
-    insert(at, String.valueOf(x))
-
-  /** <p>
-   *    Inserts the string representation of the <code>Int</code> argument
-   *    into this sequence.
-   *  </p>
-   *  <p>
-   *    The offset argument must be greater than or equal to 0, and less than
-   *    or equal to the length of this sequence.
-   *  </p>
-   *
-   *  @param  at  the offset position.
-   *  @param  x   a <code>Int</code> value.
-   *  @return     a reference to this object.
-   */
-  def insert(at: Int, x: Int): StringBuilder =
-    insert(at, String.valueOf(x))
-
-  /** <p>
-   *    Inserts the string representation of the <code>Long</code> argument
-   *    into this sequence.
-   *  </p>
-   *  <p>
-   *    The offset argument must be greater than or equal to 0, and less than
-   *    or equal to the length of this sequence.
-   *  </p>
-   *
-   *  @param  at  the offset position.
-   *  @param  x   a <code>Long</code> value.
-   *  @return     a reference to this object.
-   */
-  def insert(at: Int, x: Long): StringBuilder =
-    insert(at, String.valueOf(x))
-
-  /** <p>
-   *    Returns the index within this string of the first occurrence of the
-   *    specified substring. The integer returned is the smallest value 
-   *    <i>k</i> such that:
-   *  </p>
-   *  <blockquote><pre>
-   *  this.toString().startsWith(str, <i>k</i>)</pre>
-   *  </blockquote>
-   *  <p>
-   *    is <code>true</code>.
-   *  </p>
-   *
-   *  @param  str  any string.
-   *  @return      if the string argument occurs as a substring within this
-   *               object, then the index of the first character of the first
-   *               such substring is returned; if it does not occur as a
-   *               substring, <code>-1</code> is returned.
-   *  @throws NullPointerException if <code>str</code> is <code>null</code>.
-   */
-  def indexOf(str: String): Int = indexOf(str, 0)
-
-  /** <p>
-   *    Returns the index within this string of the first occurrence of the
-   *    specified substring, starting at the specified index. The integer
-   *    returned is the smallest value <code>k</code> for which:
-   *  </p><pre>
-   *    k >= Math.min(fromIndex, str.length()) &&
-   *                   this.toString().startsWith(str, k)</pre>
-   *  <p>
-   *    If no such value of <code>k</code> exists, then <code>-1</code>
-   *    is returned.
-   *  </p>
-   *
-   *  @param str        the substring for which to search.
-   *  @param fromIndex  the index from which to start the search.
-   *  @return           the index within this string of the first occurrence
-   *                    of the specified substring, starting at the specified index.
-   */
-  def indexOf(str: String, fromIndex: Int): Int =
-    StringBuilder.indexOf(value, 0, count, str.toArray, 0, str.length(), fromIndex)
-
-  /** <p>
-   *    Returns the index within this string of the rightmost occurrence
-   *    of the specified substring.  The rightmost empty string "" is
-   *    considered to occur at the index value <code>this.length()</code>. 
-   *    The returned index is the largest value <i>k</i> such that 
-   *  </p>
-   *  <blockquote><pre>
-   *  this.toString().startsWith(str, k)</pre>
-   *  </blockquote>
-   *  <p>
-   *    is true.
-   *  </p>
-   *
-   * @param  str  the substring to search for.
-   * @return      if the string argument occurs one or more times as a substring
-   *              within this object, then the index of the first character of
-   *              the last such substring is returned. If it does not occur as
-   *              a substring, <code>-1</code> is returned.
-   * @throws NullPointerException  if <code>str</code> is <code>null</code>.
-   */
-  def lastIndexOf(str: String): Int = lastIndexOf(str, count)
-
-  /** <p>
-   *    Returns the index within this string of the last occurrence of the
-   *    specified substring. The integer returned is the largest value
-   *    <code>k</code> such that:
-   *  </p><pre>
-   *    k <= Math.min(fromIndex, str.length()) &&
-   *                   this.toString().startsWith(str, k)</pre>
-   *  <p>
-   *    If no such value of <code>k</code> exists, then <code>-1</code>
-   *    is returned.
-   *  </p>
-   *
-   *  @param  str        the substring to search for.
-   *  @param  fromIndex  the index to start the search from.
-   *  @return            the index within this sequence of the last occurrence
-   *                     of the specified substring.
-   */
-  def lastIndexOf(str: String, fromIndex: Int): Int =
-    StringBuilder.lastIndexOf(value, 0, count, str.toArray, 0, str.length(), fromIndex)
-
-  /** <p>
-   *    Causes this character sequence to be replaced by the reverse of the
-   *    sequence. If there are any surrogate pairs included in the sequence,
-   *    these are treated as single characters for the reverse operation.
-   *    Thus, the order of the high-low surrogates is never reversed.
-   *  </p>
-   *  <p>
-   *    Let <i>n</i> be the character length of this character sequence
-   *    (not the length in <code>Char</code> values) just prior to
-   *    execution of the <code>reverse</code> method. Then the
-   *    character at index <i>k</i> in the new character sequence is
-   *    equal to the character at index <i>n-k-1</i> in the old
-   *    character sequence.
-   *  </p>
-   *
-   *  @return  a reference to this object.
-   */
-  def reverse(): StringBuilder = {
-    val n = count - 1
-    var j = (n-1) >> 1
-    while (j >= 0) {
-      val temp = value(j)
-      val temp2 = value(n - j)
-      value(j) = temp2
-      value(n - j) = temp
-      j -= 1
-    }
-    this
-  }
-
-  /** Returns a string representing the data in this sequence.
-   *  A new <code>String</code> object is allocated and initialized to 
-   *  contain the character sequence currently represented by this 
-   *  object. This <code>String</code> is then returned. Subsequent 
-   *  changes to this sequence do not affect the contents of the 
-   *  <code>String</code>.
-   *
-   *  @return  a string representation of this sequence of characters.
-   */
-  override def toString(): String = new String(value, 0, count)
-
-}
-
-
-object StringBuilder {
-
-  // method <code>java.util.Arrays.copyOf</code> exists since 1.6
-  private def copyOf(src: Array[Char], newLength: Int): Array[Char] = {
-    val dest = new Array[Char](newLength)
-    val (start, end) =
-      if (src.length < newLength) (src.length, newLength)
-      else (newLength, src.length)
-    compat.Platform.arraycopy(src, 0, dest, 0, start)
-    // For any indices that are valid in the copy but not the original,
-    // the copy will contain '\\u000'.
-    for (i <- start until end) dest(i) = '\0'
-    dest
-  }
-
-  private def indexOf(source: Array[Char], sourceOffset: Int, sourceCount: Int,
-                      target: Array[Char], targetOffset: Int, targetCount: Int,
-                      fromIndex: Int): Int =
-    if (fromIndex >= sourceCount)
-      if (targetCount == 0) sourceCount else -1
-    else {
-      val inx = if (fromIndex < 0) 0 else fromIndex
-      if (targetCount == 0)
-        inx
-      else {
-        val first  = target(targetOffset)
-        val max = sourceOffset + (sourceCount - targetCount)
-
-        var i = sourceOffset + inx
-        while (i <= max) {
-          /* Look for first character. */
-          if (source(i) != first) {
-            i += 1
-            while (i <= max && source(i) != first) i += 1
-          }
-          /* Found first character, now look at the rest of v2 */
-          if (i <= max) {
-            var j = i + 1
-            val end = j + targetCount - 1
-            var k = targetOffset + 1
-            while (j < end && source(j) == target(k)) {
-              j += 1
-              k += 1
-            }
-            if (j == end) {
-              /* Found whole string. */
-              return i - sourceOffset
-            }
-          } // if
-          i += 1
-        } // while
-        -1
-      }
-    }
-
-  private def lastIndexOf(source: Array[Char], sourceOffset: Int, sourceCount: Int,
-                          target: Array[Char], targetOffset: Int, targetCount: Int,
-                          fromIndex: Int): Int = {
-    val rightIndex = sourceCount - targetCount
-    if (fromIndex < 0) return -1
-    val inx = if (fromIndex > rightIndex) rightIndex else fromIndex
-    // Empty string always matches
-    if (targetCount == 0) return inx
-
-    val strLastIndex = targetOffset + targetCount - 1
-    val strLastChar = target(strLastIndex)
-    val min = sourceOffset + targetCount - 1
-    var i = min + fromIndex
-
-    while (true) {
-      while (i >= min && source(i) != strLastChar) i -= 1
-      if (i < min) return -1
-      var j = i - 1
-      val start = j - (targetCount - 1)
-      var k = strLastIndex - 1
-      var outerWhile = false
-      while (j > start && !outerWhile) {
-        if (source(j) != target(k)) {
-          j -= 1
-          k -= 1
-          i -= 1
-          outerWhile = true
-        }
-      }
-      if (!outerWhile) return start - sourceOffset + 1
-    }
-    -1
-  }
-}
diff --git a/src/cldc-library/scala/Symbol.scala b/src/cldc-library/scala/Symbol.scala
deleted file mode 100644
index 7066014..0000000
--- a/src/cldc-library/scala/Symbol.scala
+++ /dev/null
@@ -1,48 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: Symbol.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala
-
-/** <p>
- *    Instances of <code>Symbol</code> can be created easily with
- *    Scala's built-in quote mechanism.
- *  </p>
- *  <p>
- *    For instance, the <a href="http://scala-lang.org/" target="_top">Scala</a>
- *    term <code>'mysym</code> will invoke the constructor of the
- *    <code>Symbol</code> class in the following way:
- *    <code>new Symbol("mysym")</code>.
- *  </p>
- *  
- *  @author  Martin Odersky
- *  @version 1.7, 08/12/2003
- */
-final case class Symbol(name: String) {
-
-  /** Converts this symbol to a string.
-   */
-  override def toString(): String = {
-    "'" + name
-  }
-
-  /** <p>
-   *    Makes this symbol into a unique reference.
-   *  </p>
-   *  <p>
-   *    If two interened symbols are equal (i.e. they have the same name)
-   *    then they must be identical (wrt reference equality).
-   *  </p>
-   *
-   *  @return the unique reference to this symbol.
-   */
-  def intern: Symbol = this
-
-}
diff --git a/src/cldc-library/scala/collection/mutable/CloneableCollection.scala b/src/cldc-library/scala/collection/mutable/CloneableCollection.scala
deleted file mode 100644
index 8b73570..0000000
--- a/src/cldc-library/scala/collection/mutable/CloneableCollection.scala
+++ /dev/null
@@ -1,19 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: CloneableCollection.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala.collection.mutable
-
-/** The J2ME version of the library defined this trait with a clone method
- * to substitute for the lack of Object.clone there
- */
-trait CloneableCollection {
-  def clone(): AnyRef = Predef.error("Cloning not supported")
-}
diff --git a/src/cldc-library/scala/compat/Platform.scala b/src/cldc-library/scala/compat/Platform.scala
deleted file mode 100644
index 58a2e13..0000000
--- a/src/cldc-library/scala/compat/Platform.scala
+++ /dev/null
@@ -1,56 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: Platform.scala 16881 2009-01-09 16:28:11Z cunei $
-
-
-package scala.compat
-
-
-import java.lang.System
-import Predef._
-
-object Platform {
-
-  //type StackOverflowError = java.lang.StackOverflowError
-  type ConcurrentModificationException = java.lang.RuntimeException
-
-  /**
-   *  @param src     ..
-   *  @param srcPos  ..
-   *  @param dest    ..
-   *  @param destPos ..
-   *  @param length  ..
-   */
-  def arraycopy(src: AnyRef, srcPos: Int, dest: AnyRef, destPos: Int, length: Int): Unit =
-    System.arraycopy(src, srcPos, dest, destPos, length)
-
-  /** Create array of the same type as arrayInstance with the given
-   *  length.
-   *
-   *  @param elemClass ..
-   *  @param length    ..
-   *  @return          ..
-   */
-  def createArray(elemClass: Class[_], length: Int): AnyRef =
-    throw new RuntimeException("" + elemClass + "[" + length+ "]")
-    //java.lang.reflect.Array.newInstance(elemClass, length)
-
-  //def arrayclear(arr: Array[Int]): Unit = java.util.Arrays.fill(arr, 0)
-  def arrayclear(arr: Array[Int]): Unit = for (i <- 0 to arr.length) arr(i) = 0
-
-  def getClassForName(name: String): Class[_] = java.lang.Class.forName(name)
-
-  val EOL = "\n"
-
-  def currentTime: Long = System.currentTimeMillis()
-
-  def collectGarbage: Unit = System.gc()
-
-}
-
diff --git a/src/cldc-library/scala/runtime/BooleanRef.java b/src/cldc-library/scala/runtime/BooleanRef.java
deleted file mode 100644
index 4a7695c..0000000
--- a/src/cldc-library/scala/runtime/BooleanRef.java
+++ /dev/null
@@ -1,19 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: BooleanRef.java 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala.runtime;
-
-
-public class BooleanRef {
-    public boolean elem;
-    public BooleanRef(boolean elem) { this.elem = elem; }
-    public String toString() { return String.valueOf(elem); }
-}
diff --git a/src/cldc-library/scala/runtime/BoxedAnyArray.scala b/src/cldc-library/scala/runtime/BoxedAnyArray.scala
deleted file mode 100644
index 60110b7..0000000
--- a/src/cldc-library/scala/runtime/BoxedAnyArray.scala
+++ /dev/null
@@ -1,234 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: BoxedAnyArray.scala 16881 2009-01-09 16:28:11Z cunei $
-
-
-package scala.runtime
-
-
-import Predef._
-import compat.Platform
-
-/**
- * Arrays created by <code>new Array[T](length)</code> where <code>T</code>
- * is a type variable.
- */
- at serializable
-final class BoxedAnyArray(val length: Int) extends BoxedArray {
-
-  private var boxed = new Array[AnyRef](length)
-  private val hash = boxed.hashCode()
-  private var unboxed: AnyRef = null
-  private var elemClass: Class[_] = null
-
-  def apply(index: Int): Any = synchronized {
-    if (unboxed eq null)
-      boxed(index);
-    else if (elemClass eq classOf[Int])
-      Int.box(unboxed.asInstanceOf[Array[Int]](index))
-    else if (elemClass eq classOf[Long])
-      Long.box(unboxed.asInstanceOf[Array[Long]](index))
-    else if (elemClass eq classOf[Char])
-      Char.box(unboxed.asInstanceOf[Array[Char]](index))
-    else if (elemClass eq classOf[Byte])
-      Byte.box(unboxed.asInstanceOf[Array[Byte]](index))
-    else if (elemClass eq classOf[Short])
-      Short.box(unboxed.asInstanceOf[Array[Short]](index))
-    else if (elemClass eq classOf[Boolean])
-      Boolean.box(unboxed.asInstanceOf[Array[Boolean]](index))
-    else
-      unboxed.asInstanceOf[Array[AnyRef]](index)
-  }
-
-  def update(index: Int, _elem: Any): Unit = synchronized {
-    val elem = _elem.asInstanceOf[AnyRef]
-    if (unboxed eq null)
-      boxed(index) = elem
-    else if (elemClass eq classOf[Int])
-      unboxed.asInstanceOf[Array[Int]](index) = Int.unbox(elem)
-    else if (elemClass eq classOf[Long])
-      unboxed.asInstanceOf[Array[Long]](index) = Long.unbox(elem)
-    else if (elemClass eq classOf[Char])
-      unboxed.asInstanceOf[Array[Char]](index) = Char.unbox(elem)
-    else if (elemClass eq classOf[Byte])
-      unboxed.asInstanceOf[Array[Byte]](index) = Byte.unbox(elem)
-    else if (elemClass eq classOf[Short])
-      unboxed.asInstanceOf[Array[Short]](index) = Short.unbox(elem)
-    else if (elemClass eq classOf[Boolean])
-      unboxed.asInstanceOf[Array[Boolean]](index) = Boolean.unbox(elem)
-    else
-      unboxed.asInstanceOf[Array[AnyRef]](index) = elem
-  }
-
-  def unbox(elemTag: String): AnyRef =
-    if (elemTag eq ScalaRunTime.IntTag) unbox(classOf[Int])
-    else if (elemTag eq ScalaRunTime.LongTag) unbox(classOf[Long])
-    else if (elemTag eq ScalaRunTime.CharTag) unbox(classOf[Char])
-    else if (elemTag eq ScalaRunTime.ByteTag) unbox(classOf[Byte])
-    else if (elemTag eq ScalaRunTime.ShortTag) unbox(classOf[Short])
-    else if (elemTag eq ScalaRunTime.BooleanTag) unbox(classOf[Boolean])
-    else unbox(Platform.getClassForName(elemTag))
-
-  def unbox(elemClass: Class[_]): AnyRef = synchronized {
-    if (unboxed eq null) {
-      this.elemClass = elemClass
-      if (elemClass eq classOf[Int]) {
-        val newvalue = new Array[Int](length)
-        var i = 0
-        while (i < length) {
-          newvalue(i) = Int.unbox(boxed(i))
-          i += 1
-        }
-        unboxed = newvalue
-      } else if (elemClass eq classOf[Long]) {
-        val newvalue = new Array[Long](length)
-        var i = 0
-        while (i < length) {
-          newvalue(i) = Long.unbox(boxed(i))
-          i += 1
-        }
-        unboxed = newvalue;
-      } else if (elemClass eq classOf[Char]) {
-        val newvalue = new Array[Char](length)
-        var i = 0
-        while (i < length) {
-          newvalue(i) = Char.unbox(boxed(i))
-          i += 1
-        }
-        unboxed = newvalue
-      } else if (elemClass eq classOf[Byte]) {
-        val newvalue = new Array[Byte](length)
-        var i = 0
-        while (i < length) {
-          newvalue(i) = Byte.unbox(boxed(i))
-          i += 1
-        }
-        unboxed = newvalue
-      } else if (elemClass eq classOf[Short]) {
-        val newvalue = new Array[Short](length)
-        var i = 0
-        while (i < length) {
-          newvalue(i) = Short.unbox(boxed(i))
-          i += 1
-        }
-        unboxed = newvalue
-      } else if (elemClass eq classOf[Boolean]) {
-        val newvalue = new Array[Boolean](length)
-        var i = 0
-        while (i < length) {
-          newvalue(i) = Boolean.unbox(boxed(i))
-          i += 1
-        }
-        unboxed = newvalue;
-//       } else if (elemClass == boxed.getClass().getComponentType()) {
-//         // todo: replace with ScalaRunTime.AnyRef.class
-//         unboxed = boxed
-      } else {
-        unboxed = Platform.createArray(elemClass, length)
-        Platform.arraycopy(boxed, 0, unboxed, 0, length)
-      }
-      boxed = null
-    }
-    unboxed
-  }
-
-  override def equals(other: Any): Boolean = (
-    other.isInstanceOf[BoxedAnyArray] && (this eq (other.asInstanceOf[BoxedAnyArray])) ||
-    (if (unboxed eq null) boxed == other else unboxed == other)
-  )
-
-  override def hashCode(): Int = hash
-
-  def value: AnyRef = {
-    if (unboxed eq null) throw new NotDefinedError("BoxedAnyArray.value")
-    unboxed
-  }
-
-  private def adapt(other: AnyRef): AnyRef =
-    if (this.unboxed eq null)
-      other match {
-        case that: BoxedAnyArray =>
-          if (that.unboxed eq null) {
-            that.boxed
-          } else {
-            if (ScalaRunTime.isValueClass(that.elemClass)) unbox(that.elemClass); 
-            that.unboxed
-          }
-        case that: BoxedArray =>
-          adapt(that.value)
-        case that: Array[Int] =>
-          unbox(ScalaRunTime.IntTag); that
-        case that: Array[Long] =>
-          unbox(ScalaRunTime.LongTag); that
-        case that: Array[Char] =>
-          unbox(ScalaRunTime.CharTag); that
-        case that: Array[Short] =>
-          unbox(ScalaRunTime.ShortTag); that
-        case that: Array[Byte] =>
-          unbox(ScalaRunTime.ByteTag); that
-        case that: Array[Boolean] =>
-          unbox(ScalaRunTime.BooleanTag); that
-        case _ =>
-          other
-      }
-    else
-      other match {
-        case that: BoxedAnyArray =>
-          if (that.unboxed ne null) that.unboxed
-          else if (ScalaRunTime.isValueClass(this.elemClass)) that.unbox(this.elemClass)
-          else that.boxed
-        case that: BoxedArray =>
-          adapt(that.value)
-        case _ =>
-          other
-      }
-
-  override def copyFrom(src: AnyRef, from: Int, to: Int, len: Int) {
-    val src1 = adapt(src)
-    Array.copy(src1, from, if (unboxed ne null) unboxed else boxed, to, len)
-  }
-
-  override def copyTo(from: Int, dest: AnyRef, to: Int, len: Int) {
-    var dest1 = adapt(dest)
-    Array.copy(if (unboxed ne null) unboxed else boxed, from, dest1, to, len)
-  }
-
-  override def subArray(start: Int, end: Int): AnyRef = {
-    val result = new BoxedAnyArray(end - start);
-    Array.copy(this, start, result, 0, end - start)
-    result
-  }
-
-  final override def filter(p: Any => Boolean): BoxedArray = {
-    val include = new Array[Boolean](length)
-    var len = 0
-    var i = 0
-    while (i < length) {
-      if (p(this(i))) { include(i) = true; len += 1 }
-      i += 1
-    }
-    val result = new BoxedAnyArray(len)
-    len = 0
-    i = 0
-    while (len < result.length) {
-      if (include(i)) { result(len) = this(i); len += 1 }
-      i += 1
-    }
-    result
-  }
-  override protected def newArray(length : Int, elements : Iterator[Any]) = {
-    val result = new BoxedAnyArray(length)
-    var i = 0
-    while (elements.hasNext) {
-      result(i) = elements.next
-      i += 1
-    }
-    result
-  }
-}
diff --git a/src/cldc-library/scala/runtime/BoxedObjectArray.scala b/src/cldc-library/scala/runtime/BoxedObjectArray.scala
deleted file mode 100644
index 11f1f1f..0000000
--- a/src/cldc-library/scala/runtime/BoxedObjectArray.scala
+++ /dev/null
@@ -1,73 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: BoxedObjectArray.scala 16881 2009-01-09 16:28:11Z cunei $
-
-
-package scala.runtime
-
-
-import Predef._
-import compat.Platform.createArray
-
- at serializable
-final class BoxedObjectArray(val value: Array[AnyRef]) extends BoxedArray {
-
-  def length: Int = value.length
-
-  def apply(index: Int): Any = value(index)
-
-  def update(index: Int, elem: Any) { 
-    value(index) = elem.asInstanceOf[AnyRef] 
-  }
-
-  def unbox(elemTag: String): AnyRef = value
-  def unbox(elemClass: Class[_]): AnyRef = value
-
-  override def equals(other: Any): Boolean =
-    value == other ||
-    other.isInstanceOf[BoxedObjectArray] && value == other.asInstanceOf[BoxedObjectArray].value
-
-  override def hashCode(): Int = value.hashCode()
-
-  private def create(length: Int): Array[AnyRef] = {
-    //createArray(value.getClass().getComponentType(), length).asInstanceOf[Array[AnyRef]]
-    new Array[AnyRef](length)
-  }
-
-  override def subArray(start: Int, end: Int): Array[AnyRef] = {
-    val result = create(end - start)
-    Array.copy(value, start, result, 0, end - start)
-    result
-  }    
-
-  final override def filter(p: Any => Boolean): BoxedArray = {
-    val include = new Array[Boolean](value.length)
-    var len = 0
-    var i = 0
-    while (i < value.length) {
-      if (p(value(i))) { include(i) = true; len += 1 }
-      i += 1
-    }
-    val result = create(len)
-    len = 0
-    i = 0
-    while (len < result.length) {
-      if (include(i)) { result(len) = value(i); len += 1 }
-      i += 1
-    }
-    new BoxedObjectArray(result)
-  }
-
-  override protected def newArray(length: Int, elements: Iterator[Any]) = {
-    val result = create(length)
-    elements.map(_.asInstanceOf[AnyRef]).copyToArray(result, 0)
-    new BoxedObjectArray(result)
-  }
-}
-
diff --git a/src/cldc-library/scala/runtime/BoxedUnit.java b/src/cldc-library/scala/runtime/BoxedUnit.java
deleted file mode 100644
index cc89e4d..0000000
--- a/src/cldc-library/scala/runtime/BoxedUnit.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: BoxedUnit.java 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala.runtime;
-
-
-public final class BoxedUnit
-{
-
-    public final static BoxedUnit UNIT = new BoxedUnit();
-
-    private BoxedUnit() { }
-
-    public boolean equals(java.lang.Object other) {
-	return this == other;
-    }
-
-    public int hashCode() {
-	return 0;
-    }
-
-    public String toString() {
-	return "()";
-    }
-}
diff --git a/src/cldc-library/scala/runtime/BoxesRunTime.java b/src/cldc-library/scala/runtime/BoxesRunTime.java
deleted file mode 100644
index e610010..0000000
--- a/src/cldc-library/scala/runtime/BoxesRunTime.java
+++ /dev/null
@@ -1,361 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: BoxesRunTime.java 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala.runtime;
-
-/** An object (static class) that defines methods used for creating,
-  * reverting, and calculating with, boxed values. There are four classes
-  * of methods in this object:
-  *   - High-performance value boxing methods that feed from a pre-
-  *     computed map of instances for the most common instanciations.
-  *   - Convenience unboxing methods returning default value on null.
-  *   - The generalised comparison method to be used when an object may
-  *     be a boxed value.
-  *   - Standard value operators for boxed number and quasi-number values.
-  *
-  * @author  Gilles Dubochet
-  * @author  Martin Odersky
-  * @contributor Stepan Koltsov
-  * @version 2.0 */
-public class BoxesRunTime {
-
-    private static final int CHAR = 0, BYTE = 1, SHORT = 2, INT = 3, LONG = 4, OTHER = 7;
-    
-    private static int typeCode(Object a) {
-        if (a instanceof Integer) return INT;
-        if (a instanceof Character) return CHAR;
-        if (a instanceof Long) return LONG;
-        if (a instanceof Byte) return BYTE;
-        if (a instanceof Short) return SHORT;
-        return OTHER;
-    }
-        
-/* BOXING ... BOXING ... BOXING ... BOXING ... BOXING ... BOXING ... BOXING ... BOXING */
-    
-    private static int charLowBound = 0;
-    private static int charUpBound = 255;
-    private static Character[] charCache = new Character[charUpBound - charLowBound + 1];
-    
-    private static int byteLowBound = -128;
-    private static int byteUpBound = 127;
-    private static Byte[] byteCache = new Byte[byteUpBound - byteLowBound + 1];
-    
-    private static int shortLowBound = -128;
-    private static int shortUpBound = 127;
-    private static Short[] shortCache = new Short[shortUpBound - shortLowBound + 1];
-    
-    private static int intLowBound = -128;
-    private static int intUpBound = 1024;
-    private static Integer[] intCache = new Integer[intUpBound - intLowBound + 1];
-    
-    private static int longLowBound = -128;
-    private static int longUpBound = 1024;
-    private static Long[] longCache = new Long[longUpBound - longLowBound + 1];
-    
-    static {
-        int idx = 0;
-        while (idx <= charUpBound - charLowBound) {
-            charCache[idx] = new Character((char)(idx + charLowBound));
-            idx = idx + 1;
-        }
-        idx = 0;
-        while (idx <= byteUpBound - byteLowBound) {
-            byteCache[idx] = new Byte((byte)(idx + byteLowBound));
-            idx = idx + 1;
-        }
-        idx = 0;
-        while (idx <= shortUpBound - shortLowBound) {
-            shortCache[idx] = new Short((short)(idx + shortLowBound));
-            idx = idx + 1;
-        }
-        idx = 0;
-        while (idx <= intUpBound - intLowBound) {
-            intCache[idx] = new Integer((int)(idx + intLowBound));
-            idx = idx + 1;
-        }
-        idx = 0;
-        while (idx <= longUpBound - longLowBound) {
-            longCache[idx] = new Long((long)(idx + longLowBound));
-            idx = idx + 1;
-        }
-    }
-    
-    private static final Boolean TRUE = new Boolean(true);
-    private static final Boolean FALSE = new Boolean(false);
-    public static Boolean boxToBoolean(boolean b) {
-        return b ? TRUE : FALSE;
-    }
-    
-    public static Character boxToCharacter(char c) {
-        if (c >= charLowBound && c <= charUpBound)
-            return charCache[(int)c - charLowBound];
-        return new Character(c); 
-    }
-    
-    public static Byte boxToByte(byte b) {
-        if (b >= byteLowBound && b <= byteUpBound)
-            return byteCache[(int)b - byteLowBound];
-        return new Byte(b); 
-    }
-    
-    public static Short boxToShort(short s) {
-        if (s >= shortLowBound && s <= shortUpBound)
-            return shortCache[(int)s - shortLowBound];
-        return new Short(s); 
-    }
-    
-    public static Integer boxToInteger(int i) {
-        if (i >= intLowBound && i <= intUpBound)
-            return intCache[(int)i - intLowBound];
-        return new Integer(i); 
-    }
-    
-    public static Long boxToLong(long l) {
-        if (l >= longLowBound && l <= longUpBound)
-            return longCache[(int)l - longLowBound];
-        return new Long(l);
-    }
-        
-/* UNBOXING ... UNBOXING ... UNBOXING ... UNBOXING ... UNBOXING ... UNBOXING ... UNBOXING */
-    
-    public static boolean unboxToBoolean(Object b) {
-        return b == null ? false : ((Boolean)b).booleanValue();
-    }
-    
-    public static char unboxToChar(Object c) {
-        return c == null ? 0 : ((Character)c).charValue();
-    }
-    
-    public static byte unboxToByte(Object b) {
-        return b == null ? 0 : ((Byte)b).byteValue();
-    }
-    
-    public static short unboxToShort(Object s) {
-        return s == null ? 0 : ((Short)s).shortValue();
-    }
-
-    public static int unboxToInt(Object i) {
-        return i == null ? 0 : ((Integer)i).intValue();
-    }
-    
-    public static long unboxToLong(Object l) {
-        return l == null ? 0 : ((Long)l).longValue();
-    }
-    
-    /*
-    public static boolean unboxToBoolean(Object b) {
-        if (b == null)
-          throw new ClassCastException("null is no Boolean value");
-        return ((Boolean)b).booleanValue();
-    }
-    
-    public static char unboxToChar(Object c) {
-        if (c == null)
-          throw new ClassCastException("null is no Char value");
-        return ((Character)c).charValue();
-    }
-    
-    public static byte unboxToByte(Object b) {
-        if (b == null)
-          throw new ClassCastException("null is no Byte value");
-        return ((Byte)b).byteValue();
-    }
-    
-    public static short unboxToShort(Object s) {
-        if (s == null)
-          throw new ClassCastException("null is no Short value");
-        return ((Short)s).shortValue();
-    }
-
-    public static int unboxToInt(Object i) {
-        if (i == null)
-          throw new ClassCastException("null is no Int value");
-        return ((Integer)i).intValue();
-    }
-    
-    public static long unboxToLong(Object l) {
-        if (l == null)
-          throw new ClassCastException("null is no Long value");
-        return ((Long)l).longValue();
-    }
-    */
-        
-/* COMPARISON ... COMPARISON ... COMPARISON ... COMPARISON ... COMPARISON ... COMPARISON */
-
-    /** A rich implementation of the <code>equals</code> method that overrides the
-      * default equals because Java's boxed primitives are utterly broken. This equals
-      * is inserted instead of a normal equals by the Scala compiler (in the
-      * ICode phase, method <code>genEqEqPrimitive</code>) only when either
-      * side of the comparison is a subclass of <code>AnyVal</code>, of
-      * <code>java.lang.Number</code>, of <code>java.lang.Character</code> or
-      * is exactly <code>Any</code> or <code>AnyRef</code>. */
-    public static boolean equals(Object a, Object b) {
-        if (a == null)
-            return b == null;
-        if (b == null)
-            return false;
-        if (a.equals(b))
-            return true;
-
-        final long left =
-            (a instanceof Integer) ? ((Integer)a).intValue() :
-            (a instanceof Character) ? ((Character)a).charValue() :
-            (a instanceof Long) ? ((Long)a).longValue() :
-            (a instanceof Byte) ? ((Byte)a).byteValue() :
-            ((Short)a).shortValue();
-
-        final long right =
-            (b instanceof Integer) ? ((Integer)b).intValue() :
-            (b instanceof Character) ? ((Character)b).charValue() :
-            (b instanceof Long) ? ((Long)b).longValue() :
-            (b instanceof Byte) ? ((Byte)b).byteValue() :
-            ((Short)b).shortValue();
-
-        return left == right;
-    }
-        
-/* OPERATORS ... OPERATORS ... OPERATORS ... OPERATORS ... OPERATORS ... OPERATORS ... OPERATORS ... OPERATORS */
-        
-    /** arg1 + arg2 */
-    public static Object add(Object arg1, Object arg2) throws Error {
-        throw new Error();
-    }
-
-    /** arg1 - arg2 */
-    public static Object subtract(Object arg1, Object arg2) throws Error {
-        throw new Error();
-    }
-
-    /** arg1 * arg2 */
-    public static Object multiply(Object arg1, Object arg2) throws Error {
-        throw new Error();
-    }
-
-    /** arg1 / arg2 */
-    public static Object divide(Object arg1, Object arg2) throws Error {
-        throw new Error();
-    }
-
-    /** arg1 % arg2 */
-    public static Object takeModulo(Object arg1, Object arg2) throws Error {
-        throw new Error();
-    }
-
-    /** arg1 >> arg2 */
-    public static Object shiftSignedRight(Object arg1, Object arg2) throws Error {
-        throw new Error();
-    }
-
-    /** arg1 << arg2 */
-    public static Object shiftSignedLeft(Object arg1, Object arg2) throws Error {
-        throw new Error();
-    }
-
-    /** arg1 >>> arg2 */
-    public static Object shiftLogicalRight(Object arg1, Object arg2) throws Error {
-        throw new Error();
-    }
-        
-    /** -arg */
-    public static Object negate(Object arg) throws Error {
-        throw new Error();
-    }
-        
-    /** +arg */
-    public static Object positive(Object arg) throws Error {
-        throw new Error();
-    }
-
-    /** arg1 & arg2 */
-    public static Object takeAnd(Object arg1, Object arg2) throws Error {
-        throw new Error();
-    }
-
-    /** arg1 | arg2 */
-    public static Object takeOr(Object arg1, Object arg2) throws Error {
-        throw new Error();
-    }
-
-    /** arg1 ^ arg2 */
-    public static Object takeXor(Object arg1, Object arg2) throws Error {
-        throw new Error();
-    }
-
-    /** arg1 && arg2 */
-    public static Object takeConditionalAnd(Object arg1, Object arg2) throws Error {
-        throw new Error();
-    }
-
-    /** arg1 || arg2 */
-    public static Object takeConditionalOr(Object arg1, Object arg2) throws Error {
-        throw new Error();
-    }
-        
-    /** ~arg */
-    public static Object complement(Object arg) throws Error {
-        throw new Error();
-    }
-        
-    /** !arg */
-    public static Object takeNot(Object arg) throws Error {
-        throw new Error();
-    }
-    
-    public static Object testEqual(Object arg1, Object arg2) throws Error {
-        throw new Error();
-    }
-    
-    public static Object testNotEqual(Object arg1, Object arg2) throws Error {
-        throw new Error();
-    }
-    
-    public static Object testLessThan(Object arg1, Object arg2) throws Error {
-        throw new Error();
-    }
-    
-    public static Object testLessOrEqualThan(Object arg1, Object arg2) throws Error {
-        throw new Error();
-    }
-    
-    public static Object testGreaterOrEqualThan(Object arg1, Object arg2) throws Error {
-        throw new Error();
-    }
-    
-    public static Object testGreaterThan(Object arg1, Object arg2) throws Error {
-        throw new Error();
-    }
-        
-    /** arg.toChar */
-    public static Character toCharacter(Object arg) throws Error {
-        throw new Error();
-    }
-
-    /** arg.toByte */
-    public static Byte toByte(Object arg) throws Error {
-        throw new Error();
-    }
-
-    /** arg.toShort */
-    public static Short toShort(Object arg) throws Error {
-        throw new Error();
-    }
-
-    /** arg.toInt */
-    public static Integer toInteger(Object arg) throws Error {
-        throw new Error();
-    }
-
-    /** arg.toLong */
-    public static Long toLong(Object arg) throws Error {
-        throw new Error();
-    }
-    
-}
diff --git a/src/cldc-library/scala/runtime/BoxesUtility.java b/src/cldc-library/scala/runtime/BoxesUtility.java
deleted file mode 100644
index daf878d..0000000
--- a/src/cldc-library/scala/runtime/BoxesUtility.java
+++ /dev/null
@@ -1,147 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: BoxesUtility.java 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala.runtime;
-
-/**
- *  @author  Gilles Dubochet
- *  @version 1.0
- */
-public class BoxesUtility {
-    
-    private static int charLowBound = 0;
-    private static int charUpBound = 255;
-    private static Character[] charCache = new Character[charUpBound - charLowBound + 1];
-    
-    private static int byteLowBound = -128;
-    private static int byteUpBound = 127;
-    private static Byte[] byteCache = new Byte[byteUpBound - byteLowBound + 1];
-    
-    private static int shortLowBound = -128;
-    private static int shortUpBound = 127;
-    private static Short[] shortCache = new Short[shortUpBound - shortLowBound + 1];
-    
-    private static int intLowBound = -128;
-    private static int intUpBound = 1024;
-    private static Integer[] intCache = new Integer[intUpBound - intLowBound + 1];
-    
-    private static int longLowBound = -128;
-    private static int longUpBound = 1024;
-    private static Long[] longCache = new Long[longUpBound - longLowBound + 1];
-    
-    static {
-        int idx = 0;
-        while (idx <= charUpBound - charLowBound) {
-            charCache[idx] = new Character((char)(idx + charLowBound));
-            idx = idx + 1;
-        }
-        idx = 0;
-        while (idx <= byteUpBound - byteLowBound) {
-            byteCache[idx] = new Byte((byte)(idx + byteLowBound));
-            idx = idx + 1;
-        }
-        idx = 0;
-        while (idx <= shortUpBound - shortLowBound) {
-            shortCache[idx] = new Short((short)(idx + shortLowBound));
-            idx = idx + 1;
-        }
-        idx = 0;
-        while (idx <= intUpBound - intLowBound) {
-            intCache[idx] = new Integer((int)(idx + intLowBound));
-            idx = idx + 1;
-        }
-        idx = 0;
-        while (idx <= longUpBound - longLowBound) {
-            longCache[idx] = new Long((long)(idx + longLowBound));
-            idx = idx + 1;
-        }
-    }
-    private static final Boolean TRUE = new Boolean(true);
-    private static final Boolean FALSE = new Boolean(false);
-    public static Boolean boxToBoolean(boolean b) {
-        return b ? TRUE : FALSE;
-    }
-    
-    public static Character boxToCharacter(char c) {
-        if (c >= charLowBound && c <= charUpBound)
-            return charCache[(int)c - charLowBound];
-        else
-            return new Character(c); 
-    }
-    
-    public static Byte boxToByte(byte b) {
-        if (b >= byteLowBound && b <= byteUpBound)
-            return byteCache[(int)b - byteLowBound];
-        else
-            return new Byte(b); 
-    }
-    
-    public static Short boxToShort(short s) {
-        if (s >= shortLowBound && s <= shortUpBound)
-            return shortCache[(int)s - shortLowBound];
-        else
-            return new Short(s); 
-    }
-    
-    public static Integer boxToInteger(int i) {
-        if (i >= intLowBound && i <= intUpBound)
-            return intCache[(int)i - intLowBound];
-        else
-            return new Integer(i); 
-    }
-    
-    public static Long boxToLong(long l) {
-        if (l >= longLowBound && l <= longUpBound)
-            return longCache[(int)l - longLowBound];
-        else
-            return new Long(l);
-    }
-
-    public static boolean unboxToBoolean(Object b) {
-        return b == null ? false : ((Boolean)b).booleanValue();
-    }
-
-    public static char unboxToChar(Object c) {
-        if (c == null)
-            return 0;
-        else
-            return ((Character)c).charValue();
-    }
-
-    public static byte unboxToByte(Object b) {
-        if (b == null)
-            return 0;
-        else
-            return ((Byte)b).byteValue();
-    }
-
-    public static short unboxToShort(Object s) {
-        if (s == null)
-            return 0;
-        else
-            return ((Short)s).shortValue();
-    }
-
-    public static int unboxToInt(Object i) {
-        if (i == null)
-            return 0;
-        else
-            return ((Integer)i).intValue();
-    }
-
-    public static long unboxToLong(Object l) {
-        if (l == null)
-            return 0;
-        else
-            return ((Long)l).longValue();
-    }
-
-}
diff --git a/src/cldc-library/scala/runtime/ByteRef.java b/src/cldc-library/scala/runtime/ByteRef.java
deleted file mode 100644
index 65e0f4d..0000000
--- a/src/cldc-library/scala/runtime/ByteRef.java
+++ /dev/null
@@ -1,19 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: ByteRef.java 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala.runtime;
-
-
-public class ByteRef {
-    public byte elem;
-    public ByteRef(byte elem) { this.elem = elem; }
-    public String toString() { return String.valueOf(elem); }
-}
diff --git a/src/cldc-library/scala/runtime/CharRef.java b/src/cldc-library/scala/runtime/CharRef.java
deleted file mode 100644
index 76d6dbf..0000000
--- a/src/cldc-library/scala/runtime/CharRef.java
+++ /dev/null
@@ -1,19 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: CharRef.java 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala.runtime;
-
-
-public class CharRef {
-    public char elem;
-    public CharRef(char elem) { this.elem = elem; }
-    public String toString() { return String.valueOf(elem); }
-}
diff --git a/src/cldc-library/scala/runtime/Comparator.java b/src/cldc-library/scala/runtime/Comparator.java
deleted file mode 100644
index 2c2562d..0000000
--- a/src/cldc-library/scala/runtime/Comparator.java
+++ /dev/null
@@ -1,53 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: Comparator.java 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala.runtime;
-
-/**
- *  @author  Gilles Dubochet
- *  @author  Martin Odersky
- *  @version 1.2 */
-public class Comparator {
-
-    /** A rich implementation of the equals method that overrides the default
-     *  equals because Java's boxed primitives are utterly broken. This equals
-     *  is inserted instead of a normal equals by the Scala compiler (in the
-     *  ICode phase, method <code>genEqEqPrimitive</code>) only when either
-     *  side of the comparison is a subclass of <code>AnyVal</code>, of
-     *  <code>java.lang.Number</code>, of <code>java.lang.Character</code> or
-     *  is exactly <code>Any</code> or <code>AnyRef</code>, but when both sides
-     *  have different types. */
-    public static boolean equals(Object a, Object b) {
-        if (a == null)
-            return b == null;
-        if (b == null)
-            return false;
-        if (a.equals(b))
-            return true;
-
-        final long left =
-            (a instanceof Integer) ? ((Integer)a).intValue() :
-            (a instanceof Character) ? ((Character)a).charValue() :
-            (a instanceof Long) ? ((Long)a).longValue() :
-            (a instanceof Byte) ? ((Byte)a).byteValue() :
-            ((Short)a).shortValue();
-
-        final long right =
-            (b instanceof Integer) ? ((Integer)b).intValue() :
-            (b instanceof Character) ? ((Character)b).charValue() :
-            (b instanceof Long) ? ((Long)b).longValue() :
-            (b instanceof Byte) ? ((Byte)b).byteValue() :
-            ((Short)b).shortValue();
-
-        return left == right;
-    }
-
-}
diff --git a/src/cldc-library/scala/runtime/IntRef.java b/src/cldc-library/scala/runtime/IntRef.java
deleted file mode 100644
index 51a470b..0000000
--- a/src/cldc-library/scala/runtime/IntRef.java
+++ /dev/null
@@ -1,19 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: IntRef.java 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala.runtime;
-
-
-public class IntRef {
-    public int elem;
-    public IntRef(int elem) { this.elem = elem; }
-    public String toString() { return String.valueOf(elem); }
-}
diff --git a/src/cldc-library/scala/runtime/LongRef.java b/src/cldc-library/scala/runtime/LongRef.java
deleted file mode 100644
index 95cbc53..0000000
--- a/src/cldc-library/scala/runtime/LongRef.java
+++ /dev/null
@@ -1,19 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: LongRef.java 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala.runtime;
-
-
-public class LongRef {
-    public long elem;
-    public LongRef(long elem) { this.elem = elem; }
-    public String toString() { return String.valueOf(elem); }
-}
diff --git a/src/cldc-library/scala/runtime/ObjectRef.java b/src/cldc-library/scala/runtime/ObjectRef.java
deleted file mode 100644
index c8e70d3..0000000
--- a/src/cldc-library/scala/runtime/ObjectRef.java
+++ /dev/null
@@ -1,19 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: ObjectRef.java 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala.runtime;
-
-
-public class ObjectRef {
-    public Object elem;
-    public ObjectRef(Object elem) { this.elem = elem; }
-    public String toString() { return "" + elem; }
-}
diff --git a/src/cldc-library/scala/runtime/RichChar.scala b/src/cldc-library/scala/runtime/RichChar.scala
deleted file mode 100644
index ca13ebe..0000000
--- a/src/cldc-library/scala/runtime/RichChar.scala
+++ /dev/null
@@ -1,71 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: RichChar.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala.runtime
-
-
-import java.lang.Character
-import Predef.NoSuchElementException
-
-/** <p>
- *    For example, in the following code
- *  </p>
- *  <pre>
- *    <b>object</b> test <b>extends</b> Application {
- *      Console.println(<chr>'\40'</chr>.isWhitespace)
- *      Console.println('\011'.isWhitespace)
- *      Console.println('1'.asDigit == 1)
- *      Console.println('A'.asDigit == 10)
- *    }</pre>
- *  <p>
- *    the implicit conversions are performed using the predefined view
- *    <a href="../Predef$object.html#charWrapper(scala.Char)"
- *    target="contentFrame"><code>Predef.charWrapper</code></a>.
- *  </p>
- */
-final class RichChar(x: Char) extends Proxy with Ordered[Char] {
-
-  // Proxy.self
-  def self: Any = x
-
-  // Ordered[Char].compare
-  def compare (y: Char): Int = if (x < y) -1 else if (x > y) 1 else 0
-
-  def asDigit: Int = Character.digit(x, Character.MAX_RADIX)
-
-  //def isControl: Boolean = Character.isISOControl(x)
-  def isDigit: Boolean = Character.isDigit(x)
-  //def isLetter: Boolean = Character.isLetter(x)
-  //def isLetterOrDigit: Boolean = Character.isLetterOrDigit(x)
-  def isLowerCase: Boolean = Character.isLowerCase(x)
-  def isUpperCase: Boolean = Character.isUpperCase(x)
-  //def isWhitespace: Boolean = Character.isWhitespace(x)
-
-  def toLowerCase: Char = Character.toLowerCase(x)
-  def toUpperCase: Char = Character.toUpperCase(x)
-
-  /** Create an Iterator[Char] over the characters from 'x' to 'y' - 1
-   */
-  def until(limit: Char): Iterator[Char] = new Iterator[Char] {
-    private var ch = x
-    def hasNext: Boolean = ch < limit
-    def next: Char =
-      if (hasNext) { val j = ch; ch = (ch + 1).toChar; j }
-      else throw new NoSuchElementException("next on empty iterator")
-  }
-
-  //def until(y: Char): Iterator[Char] = to(y)
-
-  /** Create an Iterator[Char] over the characters from 'x' to 'y'
-   */
-  def to(y: Char): Iterator[Char] = until((y + 1).toChar)
-
-}
diff --git a/src/cldc-library/scala/runtime/RichException.scala b/src/cldc-library/scala/runtime/RichException.scala
deleted file mode 100644
index 7f0df60..0000000
--- a/src/cldc-library/scala/runtime/RichException.scala
+++ /dev/null
@@ -1,29 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id
-
-
-package scala.runtime
-
-import Predef._
-import compat.Platform.EOL
-
-final class RichException(exc: Throwable) {
-
-  def getStackTraceString: String = {
-    throw new UnsupportedOperationException(exc.toString)
-//     val s = new StringBuilder()
-//     for (trElem <- exc.getStackTrace()) {
-//       s.append(trElem.toString())
-//       s.append(EOL)
-//     }
-//     s.toString()
-  }
-
-}
diff --git a/src/cldc-library/scala/runtime/RichLong.scala b/src/cldc-library/scala/runtime/RichLong.scala
deleted file mode 100644
index e721118..0000000
--- a/src/cldc-library/scala/runtime/RichLong.scala
+++ /dev/null
@@ -1,30 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: RichLong.scala 16881 2009-01-09 16:28:11Z cunei $
-
-
-package scala.runtime
-
-
-final class RichLong(x: Long) extends Proxy with Ordered[Long] {
-
-  // Proxy.self
-  def self: Any = x
-
-  // Ordered[Long].compare
-  def compare(y: Long): Int = if (x < y) -1 else if (x > y) 1 else 0
-
-  def min(y: Long): Long = if (x < y) x else y
-  def max(y: Long): Long = if (x > y) x else y
-  def abs: Long = if (x < 0) -x else x
-
-  def toBinaryString: String = java.lang.Long.toString(x, 2)
-  def toHexString: String = java.lang.Long.toString(x, 16)
-  def toOctalString: String = java.lang.Long.toString(x, 8)
-}
diff --git a/src/cldc-library/scala/runtime/RichString.scala b/src/cldc-library/scala/runtime/RichString.scala
deleted file mode 100644
index 1f79cf1..0000000
--- a/src/cldc-library/scala/runtime/RichString.scala
+++ /dev/null
@@ -1,219 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: RichString.scala 16881 2009-01-09 16:28:11Z cunei $
-
-
-package scala.runtime
-
-
-import Predef._
-
-final class RichString(val self: String) extends Proxy with RandomAccessSeq[Char] with Ordered[String] {
-  import RichString._  
-  override def apply(n: Int) = self charAt n
-  override def length = self.length
-  override def toString = self
-  override def mkString = self
-
-  override def slice(from: Int, until: Int): RichString = {
-    val len = self.length
-    new RichString(
-      if (from >= until || from >= len)
-        ""
-      else {
-        val from0 = if (from < 0) 0 else from
-        val until0 = if (until > len) len else until
-        self.substring(from0, until0)
-      }
-    )
-  }
-
-  //override def ++ [B >: A](that: Iterable[B]): Seq[B] = {
-  override def ++[B >: Char](that: Iterable[B]): RandomAccessSeq[B] = that match {
-    case that: RichString => new RichString(self + that.self) 
-    case that => super.++(that)
-  }
-  
-  override def take(until: Int): RichString = slice(0, until)
-
-  override def drop(from: Int): RichString = slice(from, self.length)
-
-  override def startsWith[B](that: Seq[B]) = that match {
-    case that: RichString => self startsWith that.self
-    case that => super.startsWith(that)
-  }
-
-  override def endsWith[B](that: Seq[B]) = that match {
-    case that: RichString => self endsWith that.self
-    case that => super.endsWith(that)
-  }
-
-  override def indexOf[B](that: Seq[B]) = that match {
-    case that: RichString => self indexOf that.self
-    case that => super.indexOf(that)
-  }
-
-  override def containsSlice[B](that: Seq[B]) = that match {
-    case that: RichString => self contains that.self
-    case that => super.containsSlice(that)
-  }
-
-  override def reverse: RichString = {
-    val buf = new StringBuilder
-    var i = self.length - 1
-    while (i >= 0) {
-      buf append (self charAt i)
-      i -= 1
-    }
-    new RichString(buf.toString)
-  }
-
-  override def compare(other: String) = self compareTo other
-
-  private def isLineBreak(c: Char) = c == LF || c == FF
-
-  /** <p>
-   *    Strip trailing line end character from this string if it has one.
-   *    A line end character is one of
-   *  </p>
-   *  <ul style="list-style-type: none;">
-   *    <li>LF - line feed   (0x0A hex)</li>
-   *    <li>FF - form feed   (0x0C hex)</li>
-   *  </ul>
-   *  <p>
-   *    If a line feed character LF is preceded by a carriage return CR
-   *    (0x0D hex), the CR character is also stripped (Windows convention).
-   *  </p>
-   */
-  def stripLineEnd: String = {
-    val len = self.length
-    if (len == 0) self
-    else {
-      val last = apply(len - 1)
-      if (isLineBreak(last))
-        self.substring(0, if (last == LF && len >= 2 && apply(len - 2) == CR) len - 2 else len - 1)
-      else 
-        self
-    }
-  }
-
-  /** <p>
-   *    Return all lines in this string in an iterator, including trailing
-   *    line end characters.
-   *  </p>
-   *  <p>
-   *    The number of strings returned is one greater than the number of line
-   *    end characters in this string. For an empty string, a single empty
-   *    line is returned. A line end character is one of
-   *  </p>
-   *  <ul style="list-style-type: none;">
-   *    <li>LF - line feed   (0x0A hex)</li>
-   *    <li>FF - form feed   (0x0C hex)</li>
-   *  </ul>
-   */
-  def linesWithSeparators = new Iterator[String] {
-    val len = self.length
-    var index = 0
-    def hasNext: Boolean = index < len
-    def next(): String = {
-      if (index >= len) throw new NoSuchElementException("next on empty iterator")
-      val start = index
-      while (index < len && !isLineBreak(apply(index))) index += 1
-      index += 1
-      self.substring(start, index min len)
-    }
-  }
-
-  /** Return all lines in this string in an iterator, excluding trailing line
-   *  end characters, i.e. apply <code>.stripLineEnd</code> to all lines
-   *  returned by <code>linesWithSeparators</code>.
-   */
-  def lines: Iterator[String] = 
-    linesWithSeparators map (line => new RichString(line).stripLineEnd)
-
-  /** Returns this string with first character converted to upper case */
-  def capitalize: String =
-    if (self == null) null
-    else if (self.length == 0) ""
-    else {
-      val chars = self.toCharArray
-      chars(0) = chars(0).toUpperCase
-      new String(chars)
-    }
-
-  /** <p>
-   *    For every line in this string:
-   *  </p>
-   *  <blockquote>
-   *     Strip a leading prefix consisting of blanks or control characters
-   *     followed by <code>marginChar</code> from the line.
-   *  </blockquote>
-   */
-  def stripMargin(marginChar: Char): String = {
-    val buf = new StringBuilder()
-    for (line <- linesWithSeparators) {
-      val len = line.length
-      var index = 0
-      while (index < len && line.charAt(index) <= ' ') index += 1
-      buf append
-        (if (index < len && line.charAt(index) == marginChar) line.substring(index + 1) else line)
-    }
-    buf.toString
-  }
-
-  /** <p>
-   *    For every line in this string:
-   *  </p>
-   *  <blockquote>
-   *     Strip a leading prefix consisting of blanks or control characters
-   *     followed by <code>|</code> from the line.
-   *  </blockquote>
-   */
-  def stripMargin: String = stripMargin('|')
-/*
-  private def escape(ch: Char): String = ch match {
-    case '.' | '$' | '^' | '\\' => "\\" + ch
-    case _ => "" + ch
-  }
-
-  @throws(classOf[java.util.regex.PatternSyntaxException])
-  def split(separator: Char): Array[String] = self.split(escape(separator))
-
-  @throws(classOf[java.util.regex.PatternSyntaxException])
-  def split(separators: Array[Char]): Array[String] = {
-    val re = separators.foldLeft("[")(_+_) + "]"
-    self.split(re)
-  }
-*/
-  def toBoolean: Boolean = parseBoolean(self)
-  def toByte: Byte       = java.lang.Byte.parseByte(self)
-  def toShort: Short     = java.lang.Short.parseShort(self)
-  def toInt: Int         = java.lang.Integer.parseInt(self)
-  def toLong: Long       = java.lang.Long.parseLong(self)
-  //def toFloat: Float   = java.lang.Float.parseFloat(self)
-  //def toDouble: Double = java.lang.Double.parseDouble(self)
-}
-
-object RichString {
-  // just statics for rich string.
-  private final val LF: Char = 0x0A
-  private final val FF: Char = 0x0C
-  private final val CR: Char = 0x0D
-  private final val SU: Char = 0x1A
-
-  private def parseBoolean(s: String): Boolean =
-    if (s != null) s.toLowerCase match {
-      case "true" => true
-      case "false" => false
-      case _ => throw new NumberFormatException("For input string: \""+s+"\"")
-    }
-    else
-      throw new NumberFormatException("For input string: \"null\"")
-}
-
diff --git a/src/cldc-library/scala/runtime/ScalaRunTime.scala b/src/cldc-library/scala/runtime/ScalaRunTime.scala
deleted file mode 100644
index 19dad78..0000000
--- a/src/cldc-library/scala/runtime/ScalaRunTime.scala
+++ /dev/null
@@ -1,142 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: ScalaRunTime.scala 16881 2009-01-09 16:28:11Z cunei $
-
-
-package scala.runtime
-
-
-import Predef._
-
-/* The object <code>ScalaRunTime</code> provides ...
- */
-object ScalaRunTime {
-
-  /** Names for primitive types, used by array unboxing */
-  val ByteTag = ".Byte"
-  val ShortTag = ".Short"
-  val CharTag = ".Char"
-  val IntTag = ".Int"
-  val LongTag = ".Long"
-  val BooleanTag = ".Boolean"
-
-  def isArray(x: AnyRef): Boolean =
-    (x != null && x.getClass.isArray) || (x != null && x.isInstanceOf[BoxedArray])
-
-  def isValueTag(tag: String) = tag.charAt(0) == '.'
-
-  def isValueClass(clazz: Class[_]) =
-    clazz == classOf[Boolean] || clazz == classOf[Byte] ||
-    clazz == classOf[Short  ] || clazz == classOf[Char] ||
-    clazz == classOf[Int    ] || clazz == classOf[Long]
-
-  def checkInitialized[T <: AnyRef](x: T): T = 
-    if (x == null) throw new UninitializedError else x
-
-  abstract class Try[A] {
-    def Catch[B >: A](handler: PartialFunction[Throwable, B]): B
-    def Finally(handler: Unit): A
-  }
-
-  def Try[A](block: => A): Try[A] = new Try[A] with Runnable {
-    var result: A = _
-    var exception: Throwable = ExceptionHandling.tryCatch(this)
-
-    def run() { result = block }
-
-    def Catch[B >: A](handler: PartialFunction[Throwable, B]): B =
-      if (exception eq null)
-        result.asInstanceOf[B]
-      // !!! else if (exception is LocalReturn)
-      // !!!   // ...
-      else if (handler isDefinedAt exception)
-        handler(exception)
-      else
-        throw exception
-
-    def Finally(handler: Unit): A =
-      if (exception eq null)
-        result.asInstanceOf[A]
-      else
-        throw exception
-  }
-
-  def caseFields(x: Product): List[Any] = {
-    val arity = x.productArity
-    def fields(from: Int): List[Any] =
-      if (from == arity) List()
-      else x.productElement(from) :: fields(from + 1)
-    fields(0)
-  }
-
-  def _toString(x: Product): String =
-    caseFields(x).mkString(x.productPrefix + "(", ",", ")")
-
-  def _hashCode(x: Product): Int = {
-    var code = x.getClass().hashCode()
-    val arr =  x.productArity
-    var i = 0
-    while (i < arr) {
-      code = code * 41 + x.productElement(i).hashCode()
-      i += 1
-    }
-    code
-  }
-
-  def _equals(x: Product, y: Any): Boolean = y match {
-    case y1: Product if x.productArity == y1.productArity =>
-      val arity = x.productArity
-      var i = 0
-      while (i < arity && x.productElement(i) == y1.productElement(i))
-        i += 1
-      i == arity
-    case _ =>
-      false
-  }
-
-  def _equalsWithVarArgs(x: Product, y: Any): Boolean = y match {
-    case y1: Product if x.productArity == y1.productArity =>
-      val arity = x.productArity
-      var i = 0
-      while (i < arity - 1 && x.productElement(i) == y1.productElement(i))
-        i += 1
-      i == arity - 1 && {
-        x.productElement(i) match {
-          case xs: Seq[_] =>
-            y1.productElement(i) match {
-              case ys: Seq[_] => xs sameElements ys
-            }
-        }
-      }
-    case _ =>
-      false
-  }
-
-  //def checkDefined[T >: Null](x: T): T = 
-  //  if (x == null) throw new UndefinedException else x
-
-  def Seq[A](xs: A*): Seq[A] = null // interpreted specially by new backend.
-
-  def arrayValue(x: BoxedArray, elemTag: String): AnyRef =
-    if (x eq null) null else x.unbox(elemTag)
-
-  def arrayValue(x: BoxedArray, elemClass: Class[_]): AnyRef =
-    if (x eq null) null else x.unbox(elemClass)
-
-  def boxArray(value: AnyRef): BoxedArray = value match {
-    case x: Array[Byte] => new BoxedByteArray(x)
-    case x: Array[Short] => new BoxedShortArray(x)
-    case x: Array[Char] => new BoxedCharArray(x)
-    case x: Array[Int] => new BoxedIntArray(x)
-    case x: Array[Long] => new BoxedLongArray(x)
-    case x: Array[Boolean] => new BoxedBooleanArray(x)
-    case x: Array[AnyRef] => new BoxedObjectArray(x)
-    case x: BoxedArray => x
-  }
-}
diff --git a/src/cldc-library/scala/runtime/ShortRef.java b/src/cldc-library/scala/runtime/ShortRef.java
deleted file mode 100644
index 2e041fe..0000000
--- a/src/cldc-library/scala/runtime/ShortRef.java
+++ /dev/null
@@ -1,19 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: ShortRef.java 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala.runtime;
-
-
-public class ShortRef {
-    public short elem;
-    public ShortRef(short elem) { this.elem = elem; }
-    public String toString() { return String.valueOf(elem); }
-}
diff --git a/src/cldc-library/scala/runtime/SquareRoot.scala b/src/cldc-library/scala/runtime/SquareRoot.scala
deleted file mode 100644
index 92446cf..0000000
--- a/src/cldc-library/scala/runtime/SquareRoot.scala
+++ /dev/null
@@ -1,151 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2007-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: SquareRoot.scala 16881 2009-01-09 16:28:11Z cunei $
-
-
-package scala.runtime
-
-import Predef._
-
-/**
- * <p>
- *   Integer Square Root function (see http://atoms.alife.co.uk/sqrt/index.html).
- * </p>
- * <p>
- *   Contributors include Arne Steinarson for the basic approximation idea, Dann 
- *   Corbit and Mathew Hendry for the first cut at the algorithm, Lawrence Kirby 
- *   for the rearrangement, improvments and range optimization, Paul Hsieh 
- *   for the round-then-adjust idea, Tim Tyler, for the Java port
- *   and Jeff Lawson for a bug-fix and some code to improve accuracy.
- * </p>
- * 
- * @version v0.02 - 2003/09/07
- */
-
-/**
- * Faster replacements for <code>(int)(java.lang.Math.sqrt(integer))</code>
- */
-object SquareRoot {
-  private val table = Array(
-     0,    16,  22,  27,  32,  35,  39,  42,  45,  48,  50,  53,  55,  57,
-     59,   61,  64,  65,  67,  69,  71,  73,  75,  76,  78,  80,  81,  83,
-     84,   86,  87,  89,  90,  91,  93,  94,  96,  97,  98,  99, 101, 102,
-     103, 104, 106, 107, 108, 109, 110, 112, 113, 114, 115, 116, 117, 118,
-     119, 120, 121, 122, 123, 124, 125, 126, 128, 128, 129, 130, 131, 132,
-     133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 144, 145,
-     146, 147, 148, 149, 150, 150, 151, 152, 153, 154, 155, 155, 156, 157,
-     158, 159, 160, 160, 161, 162, 163, 163, 164, 165, 166, 167, 167, 168,
-     169, 170, 170, 171, 172, 173, 173, 174, 175, 176, 176, 177, 178, 178,
-     179, 180, 181, 181, 182, 183, 183, 184, 185, 185, 186, 187, 187, 188,
-     189, 189, 190, 191, 192, 192, 193, 193, 194, 195, 195, 196, 197, 197,
-     198, 199, 199, 200, 201, 201, 202, 203, 203, 204, 204, 205, 206, 206,
-     207, 208, 208, 209, 209, 210, 211, 211, 212, 212, 213, 214, 214, 215,
-     215, 216, 217, 217, 218, 218, 219, 219, 220, 221, 221, 222, 222, 223,
-     224, 224, 225, 225, 226, 226, 227, 227, 228, 229, 229, 230, 230, 231,
-     231, 232, 232, 233, 234, 234, 235, 235, 236, 236, 237, 237, 238, 238,
-     239, 240, 240, 241, 241, 242, 242, 243, 243, 244, 244, 245, 245, 246,
-     246, 247, 247, 248, 248, 249, 249, 250, 250, 251, 251, 252, 252, 253,
-     253, 254, 254, 255
-  )
-
-  /**
-   * <p>
-   *   A faster replacement for <code>(int)(java.lang.Math.sqrt(x))</code>.
-   *   Completely accurate for <code>x < 2147483648 (i.e. 2^31)</code>...
-   * </p>
-   * <p>
-   *   Adjusted to more closely approximate "(int)(java.lang.Math.sqrt(x) + 0.5)"
-   *   by Jeff Lawson.
-   * </p>
-   */
-  @throws(classOf[IllegalArgumentException])
-  def accurateSqrt(x: Int): Int = {
-    if (x >= 0x10000) {
-      val xn = if (x >= 0x1000000) {
-        var xn0 =
-          if (x >= 0x10000000)
-            if (x >= 0x40000000) table(x >> 24) << 8
-            else table(x >> 22) << 7
-          else
-            if (x >= 0x4000000) table(x >> 20) << 6
-            else table(x >> 18) << 5
-
-        xn0 = (xn0 + 1 + (x / xn0)) >> 1
-        (xn0 + 1 + (x / xn0)) >> 1
-      } else {
-        var xn0 =
-          if (x >= 0x100000)
-            if (x >= 0x400000) table(x >> 16) << 4
-            else table(x >> 14) << 3
-          else
-            if (x >= 0x40000) table(x >> 12) << 2
-            else table(x >> 10) << 1
-
-        (xn0 + 1 + (x / xn0)) >> 1
-      }
-      adjustment(x, xn)
-    }
-    else if (x >= 0x100) {
-      val xn =
-        if (x >= 0x1000)
-          if (x >= 0x4000) (table(x >> 8)) + 1
-          else (table(x >> 6) >> 1) + 1
-        else
-          if (x >= 0x400) (table(x >> 4) >> 2) + 1
-          else (table(x >> 2) >> 3) + 1
-
-      adjustment(x, xn)
-    }
-    else if (x >= 0) {
-      adjustment(x, table(x) >> 4)
-    }
-    else {
-      throw new IllegalArgumentException("Attempt to take the square root of negative number")
-      -1
-    }
-  }
-
-  private def adjustment(x: Int, xn: Int): Int = {
-    // Added by Jeff Lawson:
-    // need to test:
-    //   if  |xn * xn - x|  >  |x - (xn-1) * (xn-1)|  then xn-1 is more accurate
-    //   if  |xn * xn - x|  >  |(xn+1) * (xn+1) - x|  then xn+1 is more accurate
-    // or, for all cases except x == 0:
-    //    if  |xn * xn - x|  >  x - xn * xn + 2 * xn - 1 then xn-1 is more accurate
-    //    if  |xn * xn - x|  >  xn * xn + 2 * xn + 1 - x then xn+1 is more accurate
-    val xn2 = xn * xn
-
-    // |xn * xn - x|
-    var comparitor0 = xn2 - x
-    if (comparitor0 < 0) comparitor0 = -comparitor0
-
-    val twice_xn = xn << 1
-
-    // |x - (xn-1) * (xn-1)|
-    var comparitor1 = x - xn2 + twice_xn - 1
-    if (comparitor1 < 0) comparitor1 = -comparitor1 // only gets here when x == 0
-            
-    // |(xn+1) * (xn+1) - x|
-    val comparitor2 = xn2 + twice_xn + 1 - x
-            
-    if (comparitor0 > comparitor1)
-      if (comparitor1 > comparitor2) xn+1 else xn-1
-    else
-      if (comparitor0 > comparitor2) xn+1 else xn
-  }
-
-  def main(args: Array[String]) {
-    def toInt(s: String): Option[Int] =
-      try { Some(s.toInt) } catch { case e: NumberFormatException => None }
-    for (arg <- args; val x = toInt(arg); if !x.isEmpty) {
-      val n = x.get
-      println("sqrt("+n+") = "+accurateSqrt(n))
-    }
-  }
-}
diff --git a/src/cldc-library/scala/runtime/StringAdd.scala b/src/cldc-library/scala/runtime/StringAdd.scala
deleted file mode 100644
index 97b438f..0000000
--- a/src/cldc-library/scala/runtime/StringAdd.scala
+++ /dev/null
@@ -1,22 +0,0 @@
-/*                                                                      *\
-**     ________ ___   __   ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ |_|                                         **
-**                                                                      **
-\*                                                                      */
-
-// $Id: StringAdd.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala.runtime
-
-
-import Predef._
-
-final class StringAdd(self: Any) {
-
-  def +(other: String) = self.toString + other
-
-}
-
diff --git a/src/compiler/scala/tools/ant/FastScalac.scala b/src/compiler/scala/tools/ant/FastScalac.scala
index e931792..a170c4a 100644
--- a/src/compiler/scala/tools/ant/FastScalac.scala
+++ b/src/compiler/scala/tools/ant/FastScalac.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala Ant Tasks                      **
-**    / __/ __// _ | / /  / _ |    (c) 2005-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2005-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: FastScalac.scala 16894 2009-01-13 13:09:41Z cunei $
 
 package scala.tools.ant
 
@@ -66,6 +65,7 @@ class FastScalac extends Scalac {
   /** Performs the compilation. */
   override def execute() = {
     val (settings, sourceFiles, javaOnly) = initialize
+    val s = settings
 
     if (!sourceFiles.isEmpty && !javaOnly) {
       def trim(xs: List[String]) = xs filter (x => x.length > 0)
@@ -74,26 +74,31 @@ class FastScalac extends Scalac {
 
       reset.value = resetCaches
       shutdown.value = shutdownServer
+      
+      val stringSettings =
+        List(s.outdir, s.classpath, s.bootclasspath, s.extdirs, s.encoding) flatMap (x => List(x.name, x.value))
+        
+      val serverOption =
+        serverAddr.toList flatMap (x => List("-server", x))  // '-server' option
+        
+      val choiceSettings =
+        List(s.debuginfo, s.target) map (x => "%s:%s".format(x.name, x.value))
+        
+      val booleanSettings = 
+        List(s.debug, s.deprecation, s.nopredefs, s.verbose, reset, shutdown) map (x => if (x.value) List(x.name) else Nil) flatten
+        
+      val phaseSetting = {
+        val s = settings.log
+        if (s.value.isEmpty) Nil
+        else List("%s:%s".format(s.name, s.value.mkString(",")))
+      }
+      
       val cmdOptions =
-        // StringSetting
-        List.flatten(
-          List(settings.outdir, settings.classpath, settings.bootclasspath,
-               settings.extdirs, settings.encoding) map (s => List(s.name, s.value))) :::
-        // '-server' option
-        (if (serverAddr.isEmpty) Nil else List("-server", serverAddr.get)) :::
-        // ChoiceSetting
-        (List(settings.debuginfo, settings.target) map (s => s.name + ":" + s.value)) :::
-        // BooleanSetting
-        trim(
-          List(settings.debug, settings.deprecation, settings.nopredefs,
-               settings.verbose, reset, shutdown) map (s => if (s.value) s.name else "")) :::
-        // PhaseSetting
-        trim(
-          List(settings.log) map (s => if (s.value.isEmpty) "" else s.name + ":" + s.value))
+        stringSettings ::: serverOption ::: choiceSettings ::: booleanSettings ::: phaseSetting
 
       val args = (cmdOptions ::: (sourceFiles map (_.toString))).toArray
       try {
-        if(nsc.CompileClient.main0(args) > 0 && failonerror)
+        if (scala.tools.nsc.CompileClient.main0(args) > 0 && failonerror)
           error("Compile failed; see the compiler error output for details.")
       } 
       catch {
diff --git a/src/compiler/scala/tools/ant/Pack200Task.scala b/src/compiler/scala/tools/ant/Pack200Task.scala
new file mode 100644
index 0000000..dfb17fe
--- /dev/null
+++ b/src/compiler/scala/tools/ant/Pack200Task.scala
@@ -0,0 +1,184 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala Ant Tasks                      **
+**    / __/ __// _ | / /  / _ |    (c) 2005-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+// $Id$
+
+package scala.tools.ant
+
+import java.io.{BufferedOutputStream, File, FileInputStream, 
+       FileOutputStream, PipedInputStream, PipedOutputStream}
+import java.util.jar.{JarFile, JarInputStream, JarOutputStream, Pack200}
+import java.util.jar.Pack200.Packer._
+
+import org.apache.tools.ant.{BuildException, DirectoryScanner}
+import org.apache.tools.ant.taskdefs.MatchingTask
+import org.apache.tools.ant.types.FileSet
+
+/** <p>
+ *    An Ant task that applies the pack200 encoding to a JAR file.
+ *  </p><ul>
+ *  <li>destdir (mandatory),</li>
+ *  <li>dir (defaults to project's basedir),</li>
+ *  <li>effort (default 9),</li>
+ *  <li>keepFileOrder (default false),</li>
+ *  <li>keepModificationTime (default false),</li>
+ *  <li>repack (default false),</li>
+ *  <li>segmentLimit (default -1 for no limit) </li>
+ *  <li>suffix (default ".pack")</li>
+ *  </ul>
+ *
+ * @author  James Matlik
+ */
+class Pack200Task extends MatchingTask {
+  
+/*============================================================================*\
+**                             Ant user-properties                            **
+\*============================================================================*/
+
+  var destdir: Option[File] = None
+  var srcdir: Option[File] = None
+  
+  var effort = 9
+  var keepFileOrder = false
+  var keepModificationTime = false
+  var repack = false
+  var segmentLimit = -1
+
+  var packFileSuffix = ".pack"
+
+
+/*============================================================================*\
+**                             Properties setters                             **
+\*============================================================================*/
+
+  def setDir(dir: File) {
+    if (dir.exists && dir.isDirectory) srcdir = Some(dir)
+    else error("Please specify a valid directory with Jar files for packing.")
+  }
+
+  /** A level from 0 (none) to 9 (max) of effort for applying Pack200 */
+  def setEffort(x: Int) { 
+    if (effort < 10 && effort > -1) effort = x 
+    else error("The effort level must be a value from 0 to 9")
+  }
+
+  /** Set the flag to specify if file reordering should be performed. Reordering
+    * is used to remove empty packages and improve pack200 optimization.
+    * @param keep 
+    *         true to retain file ordering.
+    *         false to optimize directory structure (DEFAULT).  */ 
+  def setKeepFileOrder(x: Boolean) { keepFileOrder = x }
+
+  /** If false, a single modification time is used for all contained files */
+  def setKeepModificationTime(x: Boolean) { keepModificationTime = x }
+
+  /** A flag that tells the task to pack and then unpack the source JAR file
+    * into another JAR file.  This resulting JAR file can then be signed,
+    * packed again, compressed and distributed for securely distributed code.
+    */
+  def setRepack(r: Boolean) { repack = r }
+
+
+  def setSegmentLimit(size: Int) { segmentLimit = size }
+
+  /** Set the output directory */
+  def setDestdir(file: File) {
+    if (file != null && file.exists && file.isDirectory) destdir = Some(file)
+    else error("The destination directory is invalid: " + file.getAbsolutePath) 
+  }
+
+  def setSuffix(s: String) { packFileSuffix = s }
+
+/*============================================================================*\
+**                             Properties getters                             **
+\*============================================================================*/
+
+  /** Gets the list of individual JAR files for processing.
+    * @return The list of JAR files */
+  private def getFileList: List[File] = {
+    var files: List[File] = Nil
+    val fs = getImplicitFileSet
+    var ds = fs.getDirectoryScanner(getProject())
+    var dir = fs.getDir(getProject())
+    for (filename <- ds.getIncludedFiles() 
+         if filename.toLowerCase.endsWith(".jar")) {
+      val file = new File(dir, filename)
+      if(files.exists(file.equals(_)) == false) files = file :: files
+    }
+    files.reverse
+  }
+
+/*============================================================================*\
+**                       Compilation and support methods                      **
+\*============================================================================*/
+
+/** Generates a build error. Error location will be the current task in the  
+   * ant file.
+   * @param message A message describing the error.
+   * @throws BuildException A build error exception thrown in every case. */
+  private def error(message: String): Nothing =
+    throw new BuildException(message, getLocation())
+
+  private def makeJarOutputStream(file: File) =
+    new JarOutputStream(makeOutputStream(file))
+
+  private def makeOutputStream(file: File) =
+    new BufferedOutputStream(new FileOutputStream(file))
+
+/*============================================================================*\
+**                           The big execute method                           **
+\*============================================================================*/
+
+  /** Performs the tool creation. */
+  override def execute() = {
+    // Audits
+    val packDir = destdir.getOrElse(error("No output directory specified"))
+
+    // Setup the inherited fileset for further processing
+    fileset.setDir(srcdir.getOrElse(getProject.getBaseDir))
+
+    val files = getFileList
+    if (files.isEmpty) error("No JAR files were selected for packing.")
+
+    // Setup the packer
+    val packer = Pack200.newPacker
+    val p = packer.properties
+    p.put(EFFORT, effort.toString)
+    p.put(SEGMENT_LIMIT, segmentLimit.toString)
+    p.put(KEEP_FILE_ORDER, if(keepFileOrder) TRUE else FALSE)
+    p.put(MODIFICATION_TIME, if(keepModificationTime) LATEST else KEEP)
+
+    for (file <- files) {
+      if (repack) {
+        val repackedFile = new File(packDir, file.getName)
+        if (file.lastModified > repackedFile.lastModified) {
+          println("Repacking " + file.toString + " to " + repackedFile.toString)
+          val tmpFile = new File(packDir, file.getName + ".tmp")
+          val os = makeOutputStream(tmpFile)
+          packer.pack(new JarFile(file), os)
+          os.close()
+          val jos = makeJarOutputStream(repackedFile)
+          Pack200.newUnpacker.unpack(tmpFile, jos)
+          jos.close()
+          tmpFile.delete()
+        }
+      }
+      else {
+        val packFile: File = {
+          val name = file.getName.substring(0, file.getName.lastIndexOf("."))
+          new File(packDir, name + packFileSuffix)
+        }
+        if(file.lastModified > packFile.lastModified) {
+          println("Packing " + file.toString + " to " + packFile.toString)
+          val os = makeOutputStream(packFile)
+          packer.pack(new JarFile(file), os)
+        }
+      }
+    }
+  }
+}
diff --git a/src/compiler/scala/tools/ant/Same.scala b/src/compiler/scala/tools/ant/Same.scala
index 32197b2..8bc0372 100644
--- a/src/compiler/scala/tools/ant/Same.scala
+++ b/src/compiler/scala/tools/ant/Same.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala Ant Tasks                      **
-**    / __/ __// _ | / /  / _ |    (c) 2005-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2005-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Same.scala 16894 2009-01-13 13:09:41Z cunei $
 
 package scala.tools.ant
 
@@ -37,7 +36,7 @@ import org.apache.tools.ant.types.Mapper
 class Same extends MatchingTask {
 
   /** The unique Ant file utilities instance to use in this task. */
-  private val fileUtils = FileUtils.newFileUtils()
+  private val fileUtils = FileUtils.getFileUtils()
 
 /*============================================================================*\
 **                             Ant user-properties                            **
diff --git a/src/compiler/scala/tools/ant/ScalaBazaar.scala b/src/compiler/scala/tools/ant/ScalaBazaar.scala
index 000ea0e..4b42950 100644
--- a/src/compiler/scala/tools/ant/ScalaBazaar.scala
+++ b/src/compiler/scala/tools/ant/ScalaBazaar.scala
@@ -1,22 +1,21 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala Ant Tasks                      **
-**    / __/ __// _ | / /  / _ |    (c) 2005-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2005-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: ScalaBazaar.scala 16894 2009-01-13 13:09:41Z cunei $
 
   
 package scala.tools.ant {
   
-  import scala.collection.Map
+  import scala.collection.DefaultMap
   import scala.collection.mutable.HashMap
   import java.io.{File, FileInputStream, FileOutputStream,
                   FileWriter, StringReader}
-  import java.net.{URL, URLClassLoader}
-  import java.util.{ArrayList, Vector}
+  import java.net.URL
+  import java.util.ArrayList
   import java.util.zip.{ZipOutputStream, ZipEntry}
   
   import org.apache.tools.ant.{AntClassLoader, BuildException,
@@ -56,7 +55,7 @@ package scala.tools.ant {
   class ScalaBazaar extends Task {
     
     /** The unique Ant file utilities instance to use in this task. */
-    private val fileUtils = FileUtils.newFileUtils()
+    private val fileUtils = FileUtils.getFileUtils()
     
 /******************************************************************************\
 **                             Ant user-properties                            **
@@ -78,17 +77,17 @@ package scala.tools.ant {
     private var link: Option[String] = None
     
     /** The sets of files to include in the package */
-    private object fileSetsMap extends Map[String, List[FileSet]] {
+    private object fileSetsMap extends DefaultMap[String, List[FileSet]] {
       private var content = new HashMap[String, List[FileSet]]()
       def get(key: String): Option[List[FileSet]] = content.get(key)
-      def size: Int = content.size
-      def update(key: String, value: FileSet) = {
+      override def size: Int = content.size
+      def update(key: String, value: FileSet) {
         if (content.contains(key) && content(key) != Nil)
           content.update(key, value :: content(key))
         else content.update(key, List(value))
       }
-      def fileSets = elements.toList
-      def elements = content.elements
+      def fileSets = content.toList
+      def iterator = content.iterator
     }
     
     
@@ -125,7 +124,7 @@ package scala.tools.ant {
     /** Sets the depends attribute. Used by Ant.
       * @param input The value for <code>depends</code>. */
     def setDepends(input: String) = {
-      depends = List.fromArray(input.split(",")).flatMap { s: String =>
+      depends = input.split(",").toList.flatMap { s: String =>
         val st = s.trim()
         (if (st != "") List(st) else Nil)
       }
@@ -177,19 +176,19 @@ package scala.tools.ant {
 \******************************************************************************/
     
     /** Gets the value of the file attribute in a Scala-friendly form. 
-      * @returns The file as a file. */
+      * @return The file as a file. */
     private def getName: String =
       if (name.isEmpty) error("Name attribute must be defined first.")
       else name.get
       
     /** Gets the value of the file attribute in a Scala-friendly form. 
-      * @returns The file as a file. */
+      * @return The file as a file. */
     private def getFile: File =
       if (file.isEmpty) error("Member 'file' is empty.")
       else getProject().resolveFile(file.get.toString())
       
     /** Gets the value of the adfile attribute in a Scala-friendly form. 
-      * @returns The adfile as a file. */
+      * @return The adfile as a file. */
     private def getAdfile: File =
       if (adfile.isEmpty) error("Member 'adfile' is empty.")
       else getProject().resolveFile(adfile.get.toString())
@@ -291,7 +290,7 @@ package scala.tools.ant {
         for {
           Pair(folder, fileSets) <- fileSetsMap.fileSets
           fileSet <- fileSets
-          file <- List.fromArray(fileSet.getDirectoryScanner(getProject).getIncludedFiles)
+          file <- fileSet.getDirectoryScanner(getProject).getIncludedFiles.toList
         } yield Triple(folder, fileSet.getDir(getProject), file)
       val zip = new ZipOutputStream(new FileOutputStream(file.get, false))
       if (!zipContent.isEmpty) {
diff --git a/src/compiler/scala/tools/ant/ScalaTool.scala b/src/compiler/scala/tools/ant/ScalaTool.scala
index 2d87329..63222ab 100644
--- a/src/compiler/scala/tools/ant/ScalaTool.scala
+++ b/src/compiler/scala/tools/ant/ScalaTool.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala Ant Tasks                      **
-**    / __/ __// _ | / /  / _ |    (c) 2005-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2005-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: ScalaTool.scala 16894 2009-01-13 13:09:41Z cunei $
 
 package scala.tools.ant
 
@@ -65,10 +64,14 @@ class ScalaTool extends MatchingTask {
   /** An (optional) path to all JARs that this script depend on. Paths must be
     * relative to the scala home directory. If not set, all JAR archives and
     * folders in "lib/" are automatically added. */
-  private var classpath: Option[Path] = None
+  private var classpath: List[String] = Nil
+
+  /** An (optional) path to JARs that this script depends on relative to the
+    * ant project's basedir. */
+  private var classpathPath: Path = emptyPath
 
   /** Comma-separated Java system properties to pass to the JRE. Properties
-    * are formated as name=value. Properties scala.home, scala.tool.name and
+    * are formatted as name=value. Properties scala.home, scala.tool.name and
     * scala.tool.version are always set. */
   private var properties: List[(String, String)] = Nil
 
@@ -93,7 +96,7 @@ class ScalaTool extends MatchingTask {
 
   /** Sets the platforms attribute. */
   def setPlatforms(input: String) = {
-    platforms = List.fromArray(input.split(",")).flatMap { s: String =>
+    platforms = input.split(",").toList.flatMap { s: String =>
       val st = s.trim
       if (Platforms.isPermissible(st))
         (if (input != "") List(st) else Nil)
@@ -104,22 +107,41 @@ class ScalaTool extends MatchingTask {
     }
   }
 
-  /** Sets the classpath with which to run the tool. */
-  def setClassPath(input: Path): Unit =
-    if (classpath.isEmpty)
-      classpath = Some(input)
-    else
-      classpath.get.append(input)
-  def createClassPath: Path = {
-    if (classpath.isEmpty) classpath = Some(emptyPath)
-    classpath.get.createPath()
+  /** 
+   * Sets the classpath with which to run the tool. 
+   * Note that this mechanism of setting the classpath is generally preferred
+   * for general purpose scripts, as this does not assume all elements are
+   * relative to the ant basedir.  Additionally, the platform specific demarcation
+   * of any script variables (e.g. ${SCALA_HOME} or %SCALA_HOME%) can be specified
+   * in a platform independant way (e.g. @SCALA_HOME@) and automatically translated
+   * for you.
+   */
+  def setClassPath(input: String): Unit = {
+    classpath = classpath ::: input.split(",").toList
+  }
+
+  /**
+   * A special method that allows ant classpath path definitions to be nested
+   * within this ant task.
+   */
+  def createClassPath: Path = classpathPath.createPath()
+
+  /** 
+   * Adds an Ant Path reference to the tool's classpath.  
+   * Note that all entries in the path must exist either relative to the project
+   * basedir or with an absolute path to a file in the filesystem.  As a result,
+   * this is not a mechanism for setting the classpath for more general use scripts,
+   * such as those distributed within sbaz distribution packages.
+   */
+  def setClassPathRef(input: Reference): Unit = {
+    val tmpPath = emptyPath
+    tmpPath.setRefid(input)
+    classpath = classpath ::: tmpPath.list.toList
   }
-  def setClassPathRef(input: Reference): Unit =
-    createClassPath.setRefid(input)
 
   /** Sets JVM properties that will be set whilst running the tool. */
   def setProperties(input: String) = {
-    properties = List.fromArray(input.split(",")).flatMap { s: String =>
+    properties = input.split(",").toList.flatMap { s: String =>
       val st = s.trim
       val stArray = st.split("=", 2)
       if (stArray.length == 2) {
@@ -143,15 +165,14 @@ class ScalaTool extends MatchingTask {
 \*============================================================================*/
 
     /** Gets the value of the classpath attribute in a Scala-friendly form.
-      * @returns The class path as a list of files. */
+      * @return The class path as a list of files. */
     private def getUnixclasspath: String =
-      classpath.getOrElse(emptyPath).list.mkString("", ":", "")
+      transposeVariableMarkup(classpath.mkString("", ":", "").replace('\\', '/'), "${", "}")
 
     /** Gets the value of the classpath attribute in a Scala-friendly form.
-      * @returns The class path as a list of files. */
+      * @return The class path as a list of files. */
     private def getWinclasspath: String =
-      classpath.getOrElse(emptyPath).list.map(_.replace('/', '\\')).
-                mkString("", ";", "")
+      transposeVariableMarkup(classpath.mkString("", ";", "").replace('/', '\\'), "%", "%")
 
     private def getProperties: String =
       properties.map({
@@ -168,21 +189,41 @@ class ScalaTool extends MatchingTask {
       * @throws BuildException A build error exception thrown in every case. */
     private def error(message: String): Nothing =
       throw new BuildException(message, getLocation())
+  
+    // XXX encoding and generalize
+    private def getResourceAsCharStream(clazz: Class[_], resource: String): Stream[Char] = {
+      val stream = clazz.getClassLoader() getResourceAsStream resource
+      if (stream == null) Stream.empty
+      else Stream continually stream.read() takeWhile (_ != -1) map (_.asInstanceOf[Char])
+    }
 
-    private def readAndPatchResource(resource: String, tokens: Map[String, String]): String = {
-      val chars = new Iterator[Char] {
-        private val stream =
-          this.getClass().getClassLoader().getResourceAsStream(resource)
-        private def readStream(): Char = stream.read().asInstanceOf[Char]
-        private var buf: Char = readStream()
-        def hasNext: Boolean = (buf != (-1.).asInstanceOf[Char])
-        def next: Char = {
-          val bufbuf = buf
-          buf = readStream()
-          bufbuf
-        }
+    // Converts a variable like @SCALA_HOME@ to ${SCALA_HOME} when pre = "${" and post = "}"
+    private def transposeVariableMarkup(text: String, pre: String, post: String) : String = {
+      val chars = scala.io.Source.fromString(text)
+      val builder = new StringBuilder()
+      
+      while (chars.hasNext) {
+        val char = chars.next
+        if (char == '@') {
+          var char = chars.next
+          val token = new StringBuilder()
+          while (chars.hasNext && char != '@') {
+            token.append(char)
+            char = chars.next
+          }
+          if (token.toString == "")
+            builder.append('@')
+          else
+            builder.append(pre + token.toString + post)
+        } else builder.append(char)          
       }
+      builder.toString
+    }
+    
+    private def readAndPatchResource(resource: String, tokens: Map[String, String]): String = {
+      val chars = getResourceAsCharStream(this.getClass, resource).iterator
       val builder = new StringBuilder()
+      
       while (chars.hasNext) {
         val char = chars.next
         if (char == '@') {
@@ -212,13 +253,6 @@ class ScalaTool extends MatchingTask {
         writer.close()
       }
 
-    private def expandUnixVar(vars: Map[String,String]): Map[String,String] =
-      vars transform { (x, vari) => vari.replaceAll("#([^#]*)#", "\\$$1") }
-
-    private def expandWinVar(vars: Map[String,String]): Map[String,String] =
-      vars transform { (x, vari) => vari.replaceAll("#([^#]*)#", "%_$1%") }
-
-
 /*============================================================================*\
 **                           The big execute method                           **
 \*============================================================================*/
@@ -235,6 +269,9 @@ class ScalaTool extends MatchingTask {
       ("javaflags", javaFlags),
       ("toolflags", toolFlags)
     )
+    // Consolidate Paths into classpath
+    classpath = classpath ::: classpathPath.list.toList
+    // Generate the scripts    
     if (platforms.contains("unix")) {
       val unixPatches = patches + (("classpath", getUnixclasspath))
       val unixTemplateResource = resourceRoot + "tool-unix.tmpl"
diff --git a/src/compiler/scala/tools/ant/Scalac.scala b/src/compiler/scala/tools/ant/Scalac.scala
index 06d2042..bcff9bb 100644
--- a/src/compiler/scala/tools/ant/Scalac.scala
+++ b/src/compiler/scala/tools/ant/Scalac.scala
@@ -1,24 +1,23 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala Ant Tasks                      **
-**    / __/ __// _ | / /  / _ |    (c) 2005-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2005-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Scalac.scala 16881 2009-01-09 16:28:11Z cunei $
 
 package scala.tools.ant
 
-import java.io.File
+import java.io.{File,PrintWriter,BufferedWriter,FileWriter}
 
-import org.apache.tools.ant.{BuildException, Project}
-import org.apache.tools.ant.taskdefs.MatchingTask
+import org.apache.tools.ant.{ BuildException, Project, AntClassLoader }
+import org.apache.tools.ant.taskdefs.{MatchingTask,Java}
 import org.apache.tools.ant.types.{Path, Reference}
 import org.apache.tools.ant.util.{FileUtils, GlobPatternMapper,
                                   SourceFileScanner}
 
-import scala.tools.nsc.{Global, Settings}
+import scala.tools.nsc.{Global, Settings, CompilerCommand}
 import scala.tools.nsc.reporters.{Reporter, ConsoleReporter}
 
 /** <p>
@@ -42,6 +41,7 @@ import scala.tools.nsc.reporters.{Reporter, ConsoleReporter}
  *    <li>encoding,</li>
  *    <li>target,</li>
  *    <li>force,</li>
+ *    <li>fork,</li> 
  *    <li>logging,</li>
  *    <li>logphase,</li>
  *    <li>debuginfo,</li>
@@ -68,10 +68,10 @@ import scala.tools.nsc.reporters.{Reporter, ConsoleReporter}
  *
  * @author Gilles Dubochet, Stephane Micheloud
  */
-class Scalac extends MatchingTask {
+class Scalac extends MatchingTask with ScalacShared {
 
   /** The unique Ant file utilities instance to use in this task. */
-  private val fileUtils = FileUtils.newFileUtils()
+  private val fileUtils = FileUtils.getFileUtils()
 
 /*============================================================================*\
 **                             Ant user-properties                            **
@@ -98,13 +98,17 @@ class Scalac extends MatchingTask {
 
   /** Defines valid values for the <code>target</code> property. */
   object Target extends PermissibleValue {
-    val values = List("jvm-1.5", "jvm-1.4", "msil", "cldc")
+    val values = List("jvm-1.5", "msil")
   }
 
   /** Defines valid values for the <code>deprecation</code> and
    *  <code>unchecked</code> properties. */
   object Flag extends PermissibleValue {
-    val values = List("yes", "no", "on", "off")
+    val values = List("yes", "no", "on", "off", "true", "false")
+    def toBoolean(flag: String) =
+      if (flag == "yes" || flag == "on" || flag == "true") Some(true)
+      else if (flag == "no" || flag == "off" || flag == "false") Some(false)
+      else None
   }
 
   /** The directories that contain source files to compile. */
@@ -118,6 +122,8 @@ class Scalac extends MatchingTask {
   protected var sourcepath: Option[Path] = None
   /** The boot class path to use for this compilation. */
   protected var bootclasspath: Option[Path] = None
+  /** The path to use when finding scalac - *only used for forking!*  */
+  protected var compilerPath: Option[Path] = None
   /** The external extensions path to use for this compilation. */
   protected var extdirs: Option[Path] = None
 
@@ -129,6 +135,10 @@ class Scalac extends MatchingTask {
 
   /** Whether to force compilation of all files or not. */
   protected var force: Boolean = false
+  /** Whether to fork the execution of scalac */
+  protected var fork : Boolean = false
+  /** If forking, these are the arguments to the JVM */
+  protected var jvmArgs : Option[String] = None
   /** How much logging output to print. Either none (default),
     * verbose or debug. */
   protected var logging: Option[String] = None
@@ -156,24 +166,40 @@ class Scalac extends MatchingTask {
   /** Prints out the files being compiled by the scalac ant task
    *  (not only the number of files). */
   protected var scalacDebugging: Boolean = false
+  
+  /** Helpers */
+  private def setOrAppend(old: Option[Path], arg: Path): Option[Path] = old match {
+    case Some(x)  => x append arg ; Some(x)
+    case None     => Some(arg)
+  }
+  private def pathAsList(p: Option[Path], name: String): List[File] = p match {
+    case None     => error("Member '" + name + "' is empty.")
+    case Some(x)  => x.list.toList map nameToFile
+  }
+  private def createNewPath(getter: () => Option[Path], setter: (Option[Path]) => Unit) = {
+    if (getter().isEmpty)
+      setter(Some(new Path(getProject())))
+ 
+    getter().get.createPath()
+  }
+      
+  private def plural(xs: List[Any]) = if (xs.size > 1) "s" else ""
+  private def plural(x: Int) = if (x > 1) "s" else ""
 
 /*============================================================================*\
 **                             Properties setters                             **
 \*============================================================================*/
 
+
   /** Sets the srcdir attribute. Used by Ant.
    *  @param input The value of <code>origin</code>. */
   def setSrcdir(input: Path) {
-    if (origin.isEmpty) origin = Some(input)
-    else origin.get.append(input)
+    origin = setOrAppend(origin, input)
   }
 
   /** Sets the <code>origin</code> as a nested src Ant parameter.
    *  @return An origin path to be configured. */
-  def createSrc(): Path = {
-    if (origin.isEmpty) origin = Some(new Path(getProject()))
-    origin.get.createPath()
-  }
+  def createSrc(): Path = createNewPath(origin _, p => origin = p)
 
   /** Sets the <code>origin</code> as an external reference Ant parameter.
    *  @param input A reference to an origin path. */
@@ -187,16 +213,25 @@ class Scalac extends MatchingTask {
   /** Sets the <code>classpath</code> attribute. Used by Ant.
    *  @param input The value of <code>classpath</code>. */
   def setClasspath(input: Path) {
-    if (classpath.isEmpty) classpath = Some(input)
-    else classpath.get.append(input)
+    classpath = setOrAppend(classpath, input)
+  }
+  /** Sets the <code>compilerPath</code> attribute. Used by Ant.
+   *  @param input The value of <code>compilerPath</code>. */
+  def setCompilerPath(input : Path) {
+    compilerPath = setOrAppend(compilerPath, input)
+  }
+  
+  def createCompilerPath: Path = createNewPath(compilerPath _, p => compilerPath = p)
+
+  /** Sets the <code>compilerpathref</code> attribute. Used by Ant.
+   *  @param input The value of <code>compilerpathref</code>. */
+  def setCompilerPathRef(input: Reference) {
+    createCompilerPath.setRefid(input)
   }
 
   /** Sets the <code>classpath</code> as a nested classpath Ant parameter.
    *  @return A class path to be configured. */
-  def createClasspath(): Path = {
-    if (classpath.isEmpty) classpath = Some(new Path(getProject()))
-    classpath.get.createPath()
-  }
+  def createClasspath(): Path = createNewPath(classpath _, p => classpath = p)
 
   /** Sets the <code>classpath</code> as an external reference Ant parameter.
    *  @param input A reference to a class path. */
@@ -207,16 +242,12 @@ class Scalac extends MatchingTask {
   /** Sets the <code>sourcepath</code> attribute. Used by Ant.
    *  @param input The value of <code>sourcepath</code>. */
   def setSourcepath(input: Path) {
-    if (sourcepath.isEmpty) sourcepath = Some(input)
-    else sourcepath.get.append(input)
+    sourcepath = setOrAppend(sourcepath, input)
   }
 
   /** Sets the <code>sourcepath</code> as a nested sourcepath Ant parameter.
    *  @return A source path to be configured. */
-  def createSourcepath(): Path = {
-    if (sourcepath.isEmpty) sourcepath = Some(new Path(getProject()))
-    sourcepath.get.createPath()
-  }
+  def createSourcepath(): Path = createNewPath(sourcepath _, p => sourcepath = p)
 
   /** Sets the <code>sourcepath</code> as an external reference Ant parameter.
    *  @param input A reference to a source path. */
@@ -228,17 +259,13 @@ class Scalac extends MatchingTask {
    *
    *  @param input The value of <code>bootclasspath</code>. */
   def setBootclasspath(input: Path) {
-    if (bootclasspath.isEmpty) bootclasspath = Some(input)
-    else bootclasspath.get.append(input)
+    bootclasspath = setOrAppend(bootclasspath, input)
   }
 
   /** Sets the <code>bootclasspath</code> as a nested sourcepath Ant
    *  parameter.
    *  @return A source path to be configured. */
-  def createBootclasspath(): Path = {
-    if (bootclasspath.isEmpty) bootclasspath = Some(new Path(getProject()))
-    bootclasspath.get.createPath()
-  }
+  def createBootclasspath(): Path = createNewPath(bootclasspath _, p => bootclasspath = p)
 
   /** Sets the <code>bootclasspath</code> as an external reference Ant
    *  parameter.
@@ -249,15 +276,11 @@ class Scalac extends MatchingTask {
   /** Sets the external extensions path attribute. Used by Ant.
    *  @param input The value of <code>extdirs</code>. */
   def setExtdirs(input: Path) =
-    if (extdirs.isEmpty) extdirs = Some(input)
-    else extdirs.get.append(input)
+    extdirs = setOrAppend(extdirs, input)
 
   /** Sets the <code>extdirs</code> as a nested sourcepath Ant parameter.
    *  @return An extensions path to be configured. */
-  def createExtdirs(): Path = {
-    if (extdirs.isEmpty) extdirs = Some(new Path(getProject()))
-    extdirs.get.createPath()
-  }
+  def createExtdirs(): Path = createNewPath(extdirs _, p => extdirs = p)
 
   /** Sets the <code>extdirs</code> as an external reference Ant parameter.
    *  @param input A reference to an extensions path. */
@@ -278,7 +301,18 @@ class Scalac extends MatchingTask {
   /** Sets the <code>force</code> attribute. Used by Ant.
    *  @param input The value for <code>force</code>. */
   def setForce(input: Boolean) { force = input }
-
+  
+  /** Sets the <code>fork</code> attribute. Used by Ant.
+   *  @param input The value for <code>fork</code>. */
+  def setFork(input : Boolean) { fork = input }
+  /**
+   * Sets the <code>jvmargs</code> attribute.  Used by Ant.
+   * @param input The value for <code>jvmargs</code>
+   */
+  def setJvmargs(input : String) {
+    jvmArgs = Some(input)
+  }
+  
   /** Sets the logging level attribute. Used by Ant.
    *  @param input The value for <code>logging</code>. */
   def setLogging(input: String) {
@@ -289,7 +323,7 @@ class Scalac extends MatchingTask {
   /** Sets the <code>logphase</code> attribute. Used by Ant.
    *  @param input The value for <code>logPhase</code>. */
   def setLogPhase(input: String) {
-    logPhase = List.fromArray(input.split(",")).flatMap { s: String =>
+    logPhase = input.split(",").toList.flatMap { s: String =>
       val st = s.trim()
       if (CompilerPhase.isPermissible(st))
         (if (input != "") List(st) else Nil)
@@ -311,28 +345,19 @@ class Scalac extends MatchingTask {
   /** Set the <code>deprecation</code> info attribute.
    *  @param input One of the flags <code>yes/no</code> or <code>on/off</code>. */
   def setDeprecation(input: String) {
-    if (Flag.isPermissible(input))
-      deprecation = Some("yes" == input || "on" == input)
-    else
-      error("Unknown deprecation flag '" + input + "'")
+    deprecation = Flag toBoolean input orElse error("Unknown deprecation flag '" + input + "'")
   }
 
   /** Set the <code>optimise</code> info attribute.
    *  @param input One of the flags <code>yes/no</code> or <code>on/off</code>. */
   def setOptimise(input: String) {
-    if (Flag.isPermissible(input))
-      optimise = Some("yes" == input || "on" == input)
-    else
-      error("Unknown optimisation flag '" + input + "'")
+    optimise = Flag toBoolean input orElse error("Unknown optimisation flag '" + input + "'")
   }
 
   /** Set the <code>unchecked</code> info attribute.
    *  @param input One of the flags <code>yes/no</code> or <code>on/off</code>. */
   def setUnchecked(input: String) {
-    if (Flag.isPermissible(input))
-      unchecked = Some("yes" == input || "on" == input)
-    else
-      error("Unknown unchecked flag '" + input + "'")
+    unchecked = Flag toBoolean input orElse error("Unknown unchecked flag '" + input + "'")
   }
 
   /** Sets the <code>force</code> attribute. Used by Ant.
@@ -346,7 +371,6 @@ class Scalac extends MatchingTask {
   def setScalacdebugging(input: Boolean) { scalacDebugging = input }
 
   def setAssemname(input: String) { assemname = Some(input) }
-
   def setAssemrefs(input: String) { assemrefs = Some(input) }
 
 /*============================================================================*\
@@ -356,16 +380,12 @@ class Scalac extends MatchingTask {
   /** Gets the value of the <code>classpath</code> attribute in a
    *  Scala-friendly form.
    *  @return The class path as a list of files. */
-  protected def getClasspath: List[File] =
-    if (classpath.isEmpty) error("Member 'classpath' is empty.")
-    else List.fromArray(classpath.get.list()).map(nameToFile)
+  protected def getClasspath: List[File] = pathAsList(classpath, "classpath")
 
   /** Gets the value of the <code>origin</code> attribute in a
    *  Scala-friendly form.
    *  @return The origin path as a list of files. */
-  protected def getOrigin: List[File] =
-    if (origin.isEmpty) error("Member 'origin' is empty.")
-    else List.fromArray(origin.get.list()).map(nameToFile)
+  protected def getOrigin: List[File] = pathAsList(origin, "origin")
 
   /** Gets the value of the <code>destination</code> attribute in a
    *  Scala-friendly form.
@@ -377,33 +397,22 @@ class Scalac extends MatchingTask {
   /** Gets the value of the <code>sourcepath</code> attribute in a
    *  Scala-friendly form.
    *  @return The source path as a list of files. */
-  protected def getSourcepath: List[File] =
-    if (sourcepath.isEmpty) error("Member 'sourcepath' is empty.")
-    else List.fromArray(sourcepath.get.list()).map(nameToFile)
+  protected def getSourcepath: List[File] = pathAsList(sourcepath, "sourcepath")
 
   /** Gets the value of the <code>bootclasspath</code> attribute in a
    *  Scala-friendly form.
    *  @return The boot class path as a list of files. */
-  protected def getBootclasspath: List[File] =
-    if (bootclasspath.isEmpty) error("Member 'bootclasspath' is empty.")
-    else List.fromArray(bootclasspath.get.list()).map(nameToFile)
+  protected def getBootclasspath: List[File] = pathAsList(bootclasspath, "bootclasspath")
 
   /** Gets the value of the <code>extdirs</code> attribute in a
    *  Scala-friendly form.
    *  @return The extensions path as a list of files. */
-  protected def getExtdirs: List[File] =
-    if (extdirs.isEmpty) error("Member 'extdirs' is empty.")
-    else List.fromArray(extdirs.get.list()).map(nameToFile)
+  protected def getExtdirs: List[File] = pathAsList(extdirs, "extdirs")
 
 /*============================================================================*\
 **                       Compilation and support methods                      **
 \*============================================================================*/
 
-  /** This is forwarding method to circumvent bug #281 in Scala 2. Remove when
-   *  bug has been corrected. */
-  override protected def getDirectoryScanner(baseDir: File) =
-    super.getDirectoryScanner(baseDir)
-
   /** Transforms a string name into a file relative to the provided base
    *  directory.
    *  @param base A file pointing to the location relative to which the name
@@ -467,61 +476,57 @@ class Scalac extends MatchingTask {
 
   /** Initializes settings and source files */
   protected def initialize: (Settings, List[File], Boolean) = {
+    if (scalacDebugging)
+      log("Base directory is `%s`".format(scala.tools.nsc.io.Path("").normalize))
+
     // Tests if all mandatory attributes are set and valid.
     if (origin.isEmpty) error("Attribute 'srcdir' is not set.")
-    if (getOrigin.isEmpty) error("Attribute 'srcdir' is not set.")
     if (!destination.isEmpty && !destination.get.isDirectory())
       error("Attribute 'destdir' does not refer to an existing directory.")
     if (destination.isEmpty) destination = Some(getOrigin.head)
 
     val mapper = new GlobPatternMapper()
-    mapper.setTo("*.class")
-    mapper.setFrom("*.scala")
+    mapper setTo "*.class"
+    mapper setFrom "*.scala"
     
     var javaOnly = true
+    
+    def getOriginFiles(originDir: File) = {
+      val includedFiles = getDirectoryScanner(originDir).getIncludedFiles()
+      val javaFiles = includedFiles filter (_ endsWith ".java")
+      val scalaFiles = {
+        val xs = includedFiles filter (_ endsWith ".scala")
+        if (force) xs
+        else new SourceFileScanner(this).restrict(xs, originDir, destination.get, mapper)
+      }
 
+      javaOnly = javaOnly && (scalaFiles.length == 0)
+      val list = (scalaFiles ++ javaFiles).toList
+
+      if (scalacDebugging && !list.isEmpty)
+        log("Compiling source file%s: %s to %s".format(
+          plural(list),
+          list.mkString(", "),
+          getDestination.toString
+        ))
+      else if (!list.isEmpty) {
+        val str =
+          if (javaFiles.isEmpty) "%d source file%s".format(list.length, plural(list))
+          else "%d scala and %d java source files".format(scalaFiles.length, javaFiles.length)
+        log("Compiling %s to %s".format(str, getDestination.toString))
+      }
+      else log("No files selected for compilation", Project.MSG_VERBOSE)
+      
+      list
+    }
+    
     // Scans source directories to build up a compile lists.
     // If force is false, only files were the .class file in destination is
     // older than the .scala file will be used.
     val sourceFiles: List[File] =
-      for {
-        val originDir <- getOrigin
-        val originFiles <- {
-          val includedFiles = getDirectoryScanner(originDir).getIncludedFiles()
-          var scalaFiles = includedFiles.filter(_.endsWith(".scala"))
-          val javaFiles = includedFiles.filter(_.endsWith(".java"))
-          if (!force) {
-            scalaFiles = new SourceFileScanner(this).
-              restrict(scalaFiles, originDir, destination.get, mapper)
-          }
-          javaOnly = javaOnly && (scalaFiles.length == 0)
-          val list = scalaFiles.toList ::: javaFiles.toList
-          if (scalacDebugging && list.length > 0)
-            log(
-              list.mkString(
-                "Compiling source file" +
-                (if (list.length > 1) "s: " else ": "),
-                ", ",
-                " "
-              ) + "to " + getDestination.toString
-            )
-          else if (list.length > 0)
-            log(
-              "Compiling " + (
-                if (javaFiles.length > 0)
-                  (scalaFiles.length +" scala and "+ javaFiles.length +" java source files")
-                else
-                  (list.length +" source file"+ (if (list.length > 1) "s" else ""))
-              ) +" to "+ getDestination.toString
-            )
-          else
-            log("No files selected for compilation", Project.MSG_VERBOSE)
-          list
-        }
-      }
-      yield {
-        log(originFiles, Project.MSG_DEBUG)
-        nameToFile(originDir)(originFiles)
+      for (originDir <- getOrigin ; originFile <- getOriginFiles(originDir)) yield {
+        log(originFile, Project.MSG_DEBUG)
+        nameToFile(originDir)(originFile)
       }
 
     // Builds-up the compilation settings for Scalac with the existing Ant
@@ -555,49 +560,97 @@ class Scalac extends MatchingTask {
     if (!assemrefs.isEmpty) settings.assemrefs.value = assemrefs.get
 
     log("Scalac params = '" + addParams + "'", Project.MSG_DEBUG)
-    settings.parseParams(addParams, error)
-    (settings, sourceFiles, javaOnly)
+
+    // let CompilerCommand processes all params
+    val command = new CompilerCommand(settings.splitParams(addParams), settings)
+
+    // resolve dependenciesFile path from project's basedir, so <ant antfile ...> call from other project works.
+    // the dependenciesFile may be relative path to basedir or absolute path, in either case, the following code
+    // will return correct answer.
+    command.settings.dependenciesFile.value match {
+      case "none" =>
+      case x =>
+        val depFilePath = scala.tools.nsc.io.Path(x)
+        command.settings.dependenciesFile.value = scala.tools.nsc.io.Path(getProject.getBaseDir).normalize resolve depFilePath path
+    }
+
+    (command.settings, sourceFiles, javaOnly)
   }
 
-  /** Performs the compilation. */
   override def execute() {
     val (settings, sourceFiles, javaOnly) = initialize
-    if (sourceFiles.isEmpty || javaOnly) {
+    if (sourceFiles.isEmpty || javaOnly)
       return
-    }
-
+      
+    if (fork) executeFork(settings, sourceFiles)  // TODO - Error
+    else executeInternal(settings, sourceFiles)
+  }
+  
+  protected def executeFork(settings: Settings, sourceFiles: List[File]) {
+      val java = new Java(this)
+      java setFork true
+      // using 'setLine' creates multiple arguments out of a space-separated string
+      jvmArgs foreach { java.createJvmarg() setLine _ }
+
+      // use user-provided path or retrieve from classloader
+      // TODO - Allow user to override the compiler classpath
+      val scalacPath: Path = {
+        val path = new Path(getProject)
+        if (compilerPath.isDefined) path add compilerPath.get
+        else getClass.getClassLoader match {
+          case cl: AntClassLoader => path add new Path(getProject, cl.getClasspath)
+          case _                  => error("Cannot determine default classpath for scalac, please specify one!")
+        }
+        path
+      }
+      
+      java setClasspath scalacPath
+      java setClassname MainClass
+
+      // Write all settings to a temporary file
+      def writeSettings() : File = {
+        def escapeArgument(arg : String) = if(arg.matches(".*\\s.*")) ('"' + arg + '"') else arg
+        val file = File.createTempFile("scalac-ant-",".args")
+        file.deleteOnExit()
+        val out = new PrintWriter(new BufferedWriter(new FileWriter(file)))
+        
+        try {
+          for (setting <- settings.visibleSettings ; arg <- setting.unparse)
+            out println escapeArgument(arg)
+          for (file <- sourceFiles)
+            out println escapeArgument(file.getAbsolutePath)
+        }
+        finally out.close()
+        
+        file
+      }
+      val res = execWithArgFiles(java, List(writeSettings.getCanonicalPath))
+      if (failonerror && res != 0)
+        error("Compilation failed because of an internal compiler error;"+
+              " see the error output for details.")
+  }
+  
+  /** Performs the compilation. */
+  protected def executeInternal(settings: Settings, sourceFiles : List[File]) {
     val reporter = new ConsoleReporter(settings)
-
-    // Compiles the actual code
-    val compiler = newGlobal(settings, reporter)
-    try {
-      (new compiler.Run).compile(sourceFiles.map (_.toString))
-     }
-     catch {
-      case exception: Throwable if (exception.getMessage ne null) =>
-        exception.printStackTrace()
-        error("Compile failed because of an internal compiler error (" +
-          exception.getMessage + "); see the error output for details.")
-      case exception =>
-        exception.printStackTrace()
-        error("Compile failed because of an internal compiler error " +
-              "(no error message provided); see the error output for details.")
+    val compiler = newGlobal(settings, reporter)  // compiles the actual code
+    
+    try new compiler.Run compile (sourceFiles map (_.toString))
+    catch {
+      case ex: Throwable =>
+        ex.printStackTrace()
+        val msg = if (ex.getMessage == null) "no error message provided" else ex.getMessage
+        error("Compile failed because of an internal compiler error (" + msg + "); see the error output for details.")
     }
+
     reporter.printSummary()
     if (reporter.hasErrors) {
-      val msg =
-        "Compile failed with " +
-        reporter.ERROR.count + " error" +
-        (if (reporter.ERROR.count > 1) "s" else "") +
-        "; see the compiler error output for details."
+      val msg = "Compile failed with %d error%s; see the compiler error output for details.".format(
+        reporter.ERROR.count, plural(reporter.ERROR.count))
       if (failonerror) error(msg) else log(msg)
     }
     else if (reporter.WARNING.count > 0)
-      log(
-          "Compile suceeded with " +
-          reporter.WARNING.count + " warning" +
-          (if (reporter.WARNING.count > 1) "s" else "") +
-          "; see the compiler output for details.")
+      log("Compile succeeded with %d warning%s; see the compiler output for details.".format(
+        reporter.WARNING.count, plural(reporter.WARNING.count)))
   }
-
 }
diff --git a/src/compiler/scala/tools/ant/ScalacShared.scala b/src/compiler/scala/tools/ant/ScalacShared.scala
new file mode 100644
index 0000000..92adb36
--- /dev/null
+++ b/src/compiler/scala/tools/ant/ScalacShared.scala
@@ -0,0 +1,25 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala Ant Tasks                      **
+**    / __/ __// _ | / /  / _ |    (c) 2005-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+package scala.tools.ant
+
+import org.apache.tools.ant.Project
+import org.apache.tools.ant.taskdefs.{ MatchingTask, Java }
+import scala.tools.nsc.io
+
+trait ScalacShared extends MatchingTask { 
+  val MainClass = "scala.tools.nsc.Main"
+
+  def execWithArgFiles(java: Java, paths: List[String]) = {
+    paths foreach (p => java.createArg() setValue ("@"+ p))
+    
+    val debugString = paths map (x => " (@ = '%s')".format(io.File(x).slurp())) mkString ""
+    log(java.getCommandLine.getCommandline.mkString("", " ", debugString), Project.MSG_VERBOSE)
+    java.executeJava()
+  }
+}
diff --git a/src/compiler/scala/tools/ant/Scaladoc.scala b/src/compiler/scala/tools/ant/Scaladoc.scala
index 5cf7e2d..79cd475 100644
--- a/src/compiler/scala/tools/ant/Scaladoc.scala
+++ b/src/compiler/scala/tools/ant/Scaladoc.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala Ant Tasks                      **
-**    / __/ __// _ | / /  / _ |    (c) 2005-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2005-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Scaladoc.scala 16881 2009-01-09 16:28:11Z cunei $
 
 package scala.tools.ant
 
@@ -17,8 +16,8 @@ import org.apache.tools.ant.taskdefs.MatchingTask
 import org.apache.tools.ant.types.{Path, Reference}
 import org.apache.tools.ant.util.{FileUtils, GlobPatternMapper}
 
-import scala.tools.nsc.{Global, Settings}
-import scala.tools.nsc.doc.DefaultDocDriver
+import scala.tools.nsc.Global
+import scala.tools.nsc.doc.Settings
 import scala.tools.nsc.reporters.{Reporter, ConsoleReporter}
 
 /** <p>
@@ -40,9 +39,7 @@ import scala.tools.nsc.reporters.{Reporter, ConsoleReporter}
  *    <li>extdirs,</li>
  *    <li>extdirsref,</li>
  *    <li>encoding,</li>
- *    <li>windowtitle,</li>
  *    <li>doctitle,</li>
- *    <li>stylesheetfile,</li>
  *    <li>header,</li>
  *    <li>footer,</li>
  *    <li>top,</li>
@@ -67,7 +64,7 @@ import scala.tools.nsc.reporters.{Reporter, ConsoleReporter}
 class Scaladoc extends MatchingTask {
 
   /** The unique Ant file utilities instance to use in this task. */
-  private val fileUtils = FileUtils.newFileUtils()
+  private val fileUtils = FileUtils.getFileUtils()
 
 /*============================================================================*\
 **                             Ant user-properties                            **
@@ -103,20 +100,14 @@ class Scaladoc extends MatchingTask {
   /** The character encoding of the files to compile. */
   private var encoding: Option[String] = None
 
-  /** The window title of the generated HTML documentation. */
-  private var windowtitle: Option[String] = None
-
   /** The document title of the generated HTML documentation. */
   private var doctitle: Option[String] = None
 
-  /** The user-specified stylesheet file. */
-  private var stylesheetfile: Option[String] = None
+  /** The document version, to be added to the title. */
+  private var docversion: Option[String] = None
 
-  /** The user-specified header/footer and top/bottom texts. */
-  private var pageheader: Option[String] = None
-  private var pagefooter: Option[String] = None
-  private var pagetop   : Option[String] = None
-  private var pagebottom: Option[String] = None
+  /** Instruct the compiler to generate links to sources */
+  private var docsourceurl: Option[String] = None
 
   /** Instruct the compiler to use additional parameters */
   private var addParams: String = ""
@@ -135,9 +126,10 @@ class Scaladoc extends MatchingTask {
    *
    *  @param input The value of <code>origin</code>.
    */
-  def setSrcdir(input: Path) =
+  def setSrcdir(input: Path) {
     if (origin.isEmpty) origin = Some(input)
     else origin.get.append(input)
+  }
 
   /** Sets the <code>origin</code> as a nested src Ant parameter.
    *
@@ -152,23 +144,26 @@ class Scaladoc extends MatchingTask {
    *
    *  @param input A reference to an origin path.
    */
-  def setSrcref(input: Reference) =
+  def setSrcref(input: Reference) {
     createSrc().setRefid(input)
+  }
 
   /** Sets the <code>destdir</code> attribute. Used by Ant.
    *
    *  @param input The value of <code>destination</code>.
    */
-  def setDestdir(input: File) =
+  def setDestdir(input: File) {
     destination = Some(input)
+  }
 
   /** Sets the <code>classpath</code> attribute. Used by Ant.
    *
    *  @param input The value of <code>classpath</code>.
    */
-  def setClasspath(input: Path) =
+  def setClasspath(input: Path) {
     if (classpath.isEmpty) classpath = Some(input)
     else classpath.get.append(input)
+  }
 
   /** Sets the <code>classpath</code> as a nested classpath Ant parameter.
    *
@@ -233,16 +228,18 @@ class Scaladoc extends MatchingTask {
    *
    *  @param input A reference to a source path.
    */
-  def setBootclasspathref(input: Reference) =
+  def setBootclasspathref(input: Reference) {
     createBootclasspath().setRefid(input)
+  }
 
   /** Sets the external extensions path attribute. Used by Ant.
    *
    *  @param input The value of <code>extdirs</code>.
    */
-  def setExtdirs(input: Path): Unit =
+  def setExtdirs(input: Path) {
     if (extdirs.isEmpty) extdirs = Some(input)
     else extdirs.get.append(input)
+  }
 
   /** Sets the <code>extdirs</code> as a nested sourcepath Ant parameter.
    *
@@ -257,91 +254,71 @@ class Scaladoc extends MatchingTask {
    *
    *  @param input A reference to an extensions path.
    */
-  def setExtdirsref(input: Reference) =
+  def setExtdirsref(input: Reference) {
     createExtdirs().setRefid(input)
+  }
 
   /** Sets the <code>encoding</code> attribute. Used by Ant.
    *
    *  @param input The value of <code>encoding</code>.
    */
-  def setEncoding(input: String): Unit =
+  def setEncoding(input: String) {
     encoding = Some(input)
+  }
 
-  /** Sets the <code>windowtitle</code> attribute.
-   *
-   *  @param input The value of <code>windowtitle</code>.
-   */
-  def setWindowtitle(input: String): Unit =
-    windowtitle = Some(input)
-
-  /** Sets the <code>doctitle</code> attribute.
-   *
-   *  @param input The value of <code>doctitle</code>.
-   */
-  def setDoctitle(input: String): Unit =
-    doctitle = Some(input)
-
-  /** Sets the <code>stylesheetfile</code> attribute.
-   *
-   *  @param input The value of <code>stylesheetfile</code>.
-   */
-  def setStylesheetfile(input: String): Unit =
-    stylesheetfile = Some(input)
-
-  /** Sets the <code>header</code> attribute.
-   *
-   *  @param input The value of <code>header</code>.
-   */
-  def setHeader(input: String): Unit =
-    pageheader = Some(input)
-
-  /** Sets the <code>footer</code> attribute.
+  /** Sets the <code>docversion</code> attribute.
    *
-   *  @param input The value of <code>footer</code>.
+   *  @param input The value of <code>docversion</code>.
    */
-  def setFooter(input: String): Unit =
-    pagefooter = Some(input)
+  def setDocversion(input: String) {
+    docversion = Some(input)
+  }
 
-  /** Sets the <code>top</code> attribute.
+  /** Sets the <code>docsourceurl</code> attribute.
    *
-   *  @param input The value of <code>top</code>.
+   *  @param input The value of <code>docsourceurl</code>.
    */
-  def setTop(input: String): Unit =
-    pagetop = Some(input)
+  def setDocsourceurl(input: String) {
+    docsourceurl = Some(input)
+  }
 
-  /** Sets the <code>bottom</code> attribute.
+  /** Sets the <code>doctitle</code> attribute.
    *
-   *  @param input The value of <code>bottom</code>.
+   *  @param input The value of <code>doctitle</code>.
    */
-  def setBottom(input: String): Unit =
-    pagebottom = Some(input)
+  def setDoctitle(input: String) {
+    doctitle = Some(input)
+  }
 
   /** Set the <code>addparams</code> info attribute.
    *
    *  @param input The value for <code>addparams</code>.
    */
-  def setAddparams(input: String): Unit =
+  def setAddparams(input: String) {
     addParams = input
+  }
 
   /** Set the <code>deprecation</code> info attribute.
    *
    *  @param input One of the flags <code>yes/no</code> or <code>on/off</code>.
    */
-  def setDeprecation(input: String): Unit =
+  def setDeprecation(input: String) {
     if (Flag.isPermissible(input))
       deprecation = "yes".equals(input) || "on".equals(input)
     else
       error("Unknown deprecation flag '" + input + "'")
+  }
 
   /** Set the <code>unchecked</code> info attribute.
    *
    *  @param input One of the flags <code>yes/no</code> or <code>on/off</code>.
    */
-  def setUnchecked(input: String): Unit =
+  def setUnchecked(input: String) {
     if (Flag.isPermissible(input))
       unchecked = "yes".equals(input) || "on".equals(input)
     else
       error("Unknown unchecked flag '" + input + "'")
+  }
 
 /*============================================================================*\
 **                             Properties getters                             **
@@ -354,7 +331,7 @@ class Scaladoc extends MatchingTask {
    */
   private def getClasspath: List[File] =
     if (classpath.isEmpty) error("Member 'classpath' is empty.")
-    else List.fromArray(classpath.get.list()).map(nameToFile)
+    else classpath.get.list().toList.map(nameToFile)
 
   /** Gets the value of the <code>origin</code> attribute in a Scala-friendly
    *  form.
@@ -363,7 +340,7 @@ class Scaladoc extends MatchingTask {
    */
   private def getOrigin: List[File] =
     if (origin.isEmpty) error("Member 'origin' is empty.")
-    else List.fromArray(origin.get.list()).map(nameToFile)
+    else origin.get.list().toList.map(nameToFile)
 
   /** Gets the value of the <code>destination</code> attribute in a
    *  Scala-friendly form.
@@ -381,7 +358,7 @@ class Scaladoc extends MatchingTask {
    */
   private def getSourcepath: List[File] =
     if (sourcepath.isEmpty) error("Member 'sourcepath' is empty.")
-    else List.fromArray(sourcepath.get.list()).map(nameToFile)
+    else sourcepath.get.list().toList.map(nameToFile)
 
   /** Gets the value of the <code>bootclasspath</code> attribute in a
    *  Scala-friendly form.
@@ -390,7 +367,7 @@ class Scaladoc extends MatchingTask {
    */
   private def getBootclasspath: List[File] =
     if (bootclasspath.isEmpty) error("Member 'bootclasspath' is empty.")
-    else List.fromArray(bootclasspath.get.list()).map(nameToFile)
+    else bootclasspath.get.list().toList.map(nameToFile)
 
   /** Gets the value of the <code>extdirs</code> attribute in a
    *  Scala-friendly form.
@@ -399,7 +376,7 @@ class Scaladoc extends MatchingTask {
    */
   private def getExtdirs: List[File] =
     if (extdirs.isEmpty) error("Member 'extdirs' is empty.")
-    else List.fromArray(extdirs.get.list()).map(nameToFile)
+    else extdirs.get.list().toList.map(nameToFile)
 
 /*============================================================================*\
 **                       Compilation and support methods                      **
@@ -474,7 +451,7 @@ class Scaladoc extends MatchingTask {
 \*============================================================================*/
 
   /** Initializes settings and source files */
-  protected def initialize: Pair[scala.tools.nsc.doc.Settings, List[File]] = {
+  protected def initialize: Pair[Settings, List[File]] = {
     // Tests if all mandatory attributes are set and valid.
     if (origin.isEmpty) error("Attribute 'srcdir' is not set.")
     if (getOrigin.isEmpty) error("Attribute 'srcdir' is not set.")
@@ -495,7 +472,7 @@ class Scaladoc extends MatchingTask {
         originFile <- {
           val includedFiles =
             getDirectoryScanner(originDir).getIncludedFiles()
-          val list = List.fromArray(includedFiles)
+          val list = includedFiles.toList
           if (list.length > 0)
             log(
               "Documenting " + list.length + " source file" +
@@ -524,7 +501,7 @@ class Scaladoc extends MatchingTask {
 
     // Builds-up the compilation settings for Scalac with the existing Ant
     // parameters.
-    val docSettings = new scala.tools.nsc.doc.Settings(error)
+    val docSettings = new Settings(error)
     docSettings.outdir.value = asString(destination.get)
     if (!classpath.isEmpty)
       docSettings.classpath.value = asString(getClasspath)
@@ -536,48 +513,24 @@ class Scaladoc extends MatchingTask {
       docSettings.bootclasspath.value = asString(getBootclasspath)
     if (!extdirs.isEmpty) docSettings.extdirs.value = asString(getExtdirs)
     if (!encoding.isEmpty) docSettings.encoding.value = encoding.get
-    if (!windowtitle.isEmpty) docSettings.windowtitle.value = windowtitle.get
     if (!doctitle.isEmpty) docSettings.doctitle.value = decodeEscapes(doctitle.get)
-    if (!stylesheetfile.isEmpty) docSettings.stylesheetfile.value = stylesheetfile.get
-    if (!pageheader.isEmpty) docSettings.pageheader.value = decodeEscapes(pageheader.get)
-    if (!pagefooter.isEmpty) docSettings.pagefooter.value = decodeEscapes(pagefooter.get)
-    if (!pagetop.isEmpty) docSettings.pagetop.value = decodeEscapes(pagetop.get)
-    if (!pagebottom.isEmpty) docSettings.pagebottom.value = decodeEscapes(pagebottom.get)
+    if (!docversion.isEmpty) docSettings.docversion.value = decodeEscapes(docversion.get)
+    if (!docsourceurl.isEmpty) docSettings.docsourceurl.value =decodeEscapes(docsourceurl.get)
     docSettings.deprecation.value = deprecation
     docSettings.unchecked.value = unchecked
     log("Scaladoc params = '" + addParams + "'", Project.MSG_DEBUG)
-    var args =
-      if (addParams.trim() == "") Nil
-      else List.fromArray(addParams.trim().split(" ")).map(_.trim())
-    while (!args.isEmpty) {
-      val argsBuf = args
-      if (args.head startsWith "-") {
-        for (docSetting <- docSettings.allSettings)
-          args = docSetting.tryToSet(args);
-      } else error("Parameter '" + args.head + "' does not start with '-'.")
-      if (argsBuf eq args)
-        error("Parameter '" + args.head + "' is not recognised by Scaladoc.")
-    }
+
+    docSettings processArgumentString addParams
     Pair(docSettings, sourceFiles)
   }
 
   /** Performs the compilation. */
   override def execute() = {
-    val Pair(commandSettings, sourceFiles) = initialize
-    val reporter = new ConsoleReporter(commandSettings)
-
-    // Compiles the actual code
-    val compiler = new Global(commandSettings, reporter) {
-      override def onlyPresentation = true
-    }
+    val Pair(docSettings, sourceFiles) = initialize
+    val reporter = new ConsoleReporter(docSettings)
     try {
-      val run = new compiler.Run
-      run.compile(sourceFiles.map (_.toString))
-      object generator extends DefaultDocDriver {
-        lazy val global: compiler.type = compiler
-        lazy val settings = commandSettings
-      }
-      generator.process(run.units)
+      val docProcessor = new scala.tools.nsc.doc.DocFactory(reporter, docSettings)
+      docProcessor.document(sourceFiles.map (_.toString))
       if (reporter.ERROR.count > 0)
         error(
           "Document failed with " +
@@ -592,7 +545,7 @@ class Scaladoc extends MatchingTask {
           "; see the documenter output for details.")
       reporter.printSummary()
     } catch {
-      case exception: Throwable if (exception.getMessage ne null) =>
+      case exception: Throwable if exception.getMessage ne null =>
         exception.printStackTrace()
         error("Document failed because of an internal documenter error (" +
           exception.getMessage + "); see the error output for details.")
diff --git a/src/compiler/scala/tools/ant/antlib.xml b/src/compiler/scala/tools/ant/antlib.xml
index 347ad23..06a355d 100644
--- a/src/compiler/scala/tools/ant/antlib.xml
+++ b/src/compiler/scala/tools/ant/antlib.xml
@@ -17,4 +17,6 @@
              classname="scala.tools.ant.Same"/>
     <!--<taskdef name="scalatest"
              classname="scala.tools.ant.ScalaDoc"/>-->
+    <taskdef name="pack200"
+             classname="scala.tools.ant.Pack200Task"/>
 </antlib>
diff --git a/src/compiler/scala/tools/ant/sabbus/Break.scala b/src/compiler/scala/tools/ant/sabbus/Break.scala
index 6ac89f0..59abbfe 100644
--- a/src/compiler/scala/tools/ant/sabbus/Break.scala
+++ b/src/compiler/scala/tools/ant/sabbus/Break.scala
@@ -1,24 +1,25 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala Ant Tasks                      **
-**    / __/ __// _ | / /  / _ |    (c) 2005-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2005-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
+
 package scala.tools.ant.sabbus
 
 import org.apache.tools.ant.Task
 
 class Break extends Task {
   
-  def setId(input: String): Unit = {
+  def setId(input: String) {
     id = Some(input)
   }
   
   private var id: Option[String] = None
   
-  override def execute: Unit = {
+  override def execute {
     if (id.isEmpty) error("Attribute 'id' is not set")
     Compilers.break(id.get)
   }
diff --git a/src/compiler/scala/tools/ant/sabbus/CompilationFailure.scala b/src/compiler/scala/tools/ant/sabbus/CompilationFailure.scala
index d931810..94e2cef 100644
--- a/src/compiler/scala/tools/ant/sabbus/CompilationFailure.scala
+++ b/src/compiler/scala/tools/ant/sabbus/CompilationFailure.scala
@@ -1,11 +1,12 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala Ant Tasks                      **
-**    / __/ __// _ | / /  / _ |    (c) 2005-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2005-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
+
 package scala.tools.ant.sabbus
 
 case class CompilationFailure(message: String, cause: Exception) extends Exception(message, cause)
diff --git a/src/compiler/scala/tools/ant/sabbus/Compiler.scala b/src/compiler/scala/tools/ant/sabbus/Compiler.scala
index 47efb4a..b737790 100644
--- a/src/compiler/scala/tools/ant/sabbus/Compiler.scala
+++ b/src/compiler/scala/tools/ant/sabbus/Compiler.scala
@@ -1,35 +1,30 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala Ant Tasks                      **
-**    / __/ __// _ | / /  / _ |    (c) 2005-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2005-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
+
 package scala.tools.ant.sabbus
 
 import java.io.File
 import java.net.URL
 import java.lang.reflect.InvocationTargetException
+import scala.tools.nsc.util.ScalaClassLoader
 
-class Compiler(classpath: Array[URL], val settings: Settings) {
-  
-  private lazy val classLoader: ClassLoader =
-    new java.net.URLClassLoader(classpath, null)
-  
-  private lazy val foreignCompilerName: String =
-    "scala.tools.ant.sabbus.ForeignCompiler"
-  private lazy val foreignCompiler: AnyRef =
-    classLoader.loadClass(foreignCompilerName).newInstance.asInstanceOf[AnyRef]
-  
+class Compiler(classpath: Array[URL], val settings: Settings)
+{  
+  val foreignCompilerName: String = "scala.tools.ant.sabbus.ForeignCompiler"
+  private lazy val classLoader = ScalaClassLoader fromURLs classpath
+  private lazy val foreignCompiler: AnyRef = classLoader create foreignCompilerName
+    
   private def settingsArray: Array[String] = settings.toArgs.toArray
-  
   foreignInvoke("args_$eq", Array(classOf[Array[String]]), Array(settingsArray))
   
-  private def foreignInvoke(method: String, types: Array[Class[T] forSome { type T }] , args: Array[AnyRef]) =
-    try {
-      foreignCompiler.getClass.getMethod(method, types : _*).invoke(foreignCompiler, args : _*)
-    }
+  private def foreignInvoke(method: String, types: Array[Class[_]], args: Array[AnyRef]) =
+    try foreignCompiler.getClass.getMethod(method, types: _*).invoke(foreignCompiler, args: _*)
     catch {
       case e: InvocationTargetException => throw e.getCause
     }
@@ -42,8 +37,6 @@ class Compiler(classpath: Array[URL], val settings: Settings) {
       (result >> 16, result & 0x00FF)
     }
     catch {
-      case ex: Exception =>
-        throw CompilationFailure(ex.getMessage, ex)
+      case ex: Exception => throw CompilationFailure(ex.getMessage, ex)
     }
-  
 }
diff --git a/src/compiler/scala/tools/ant/sabbus/Compilers.scala b/src/compiler/scala/tools/ant/sabbus/Compilers.scala
index 01f2d55..0fc7953 100644
--- a/src/compiler/scala/tools/ant/sabbus/Compilers.scala
+++ b/src/compiler/scala/tools/ant/sabbus/Compilers.scala
@@ -1,26 +1,27 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala Ant Tasks                      **
-**    / __/ __// _ | / /  / _ |    (c) 2005-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2005-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
+
 package scala.tools.ant.sabbus
 
 import java.net.URL
 
-object Compilers extends collection.Map[String, Compiler] {
+object Compilers extends collection.DefaultMap[String, Compiler] {
   
   val debug = false
   
   private val container = new collection.mutable.HashMap[String, Compiler]
   
-  def elements = container.elements
+  def iterator = container.iterator	
   
   def get(id: String) = container.get(id)
   
-  def size = container.size
+  override def size = container.size
   
   def make(id: String, classpath: Array[URL], settings: Settings): Compiler = {
     val runtime = Runtime.getRuntime
@@ -41,5 +42,4 @@ object Compilers extends collection.Map[String, Compiler] {
     if (debug) println("  memory after: " + (runtime.freeMemory/1048576.).formatted("%10.2f") + " MB")
     null
   }
-  
 }
diff --git a/src/compiler/scala/tools/ant/sabbus/ForeignCompiler.scala b/src/compiler/scala/tools/ant/sabbus/ForeignCompiler.scala
index a4bdf7a..2146296 100644
--- a/src/compiler/scala/tools/ant/sabbus/ForeignCompiler.scala
+++ b/src/compiler/scala/tools/ant/sabbus/ForeignCompiler.scala
@@ -1,11 +1,12 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala Ant Tasks                      **
-**    / __/ __// _ | / /  / _ |    (c) 2005-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2005-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
+
 package scala.tools.ant.sabbus
 
 import java.io.File
@@ -17,7 +18,7 @@ class ForeignCompiler {
   
   private var argsBuffer: Array[String] = null
   def args: Array[String] = argsBuffer
-  def args_=(a: Array[String]): Unit = {
+  def args_=(a: Array[String]) {
     argsBuffer = a
     nsc
   }
@@ -30,7 +31,7 @@ class ForeignCompiler {
   
   private lazy val nsc: Global = {
     try {
-      val command = new CompilerCommand(args.toList, settings, error, false)
+      val command = new CompilerCommand(args.toList, settings)
       new Global(command.settings, reporter)
     }
     catch {
@@ -40,7 +41,7 @@ class ForeignCompiler {
   }
   
   def compile(files: Array[File]): Int = {
-    val command = new CompilerCommand(files.toList.map(_.toString), settings, error, true)
+    val command = new CompilerCommand(files.toList map (_.toString), settings)
     (new nsc.Run) compile command.files
     reporter.ERROR.count << 16 | reporter.WARNING.count
   }
diff --git a/src/compiler/scala/tools/ant/sabbus/Make.scala b/src/compiler/scala/tools/ant/sabbus/Make.scala
index ebdc4f9..9173745 100644
--- a/src/compiler/scala/tools/ant/sabbus/Make.scala
+++ b/src/compiler/scala/tools/ant/sabbus/Make.scala
@@ -1,20 +1,19 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala Ant Tasks                      **
-**    / __/ __// _ | / /  / _ |    (c) 2005-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2005-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
+
 package scala.tools.ant.sabbus
 
-import java.net.URL
 import java.io.File
 import org.apache.tools.ant.Task
-import org.apache.tools.ant.types.{Path, Reference}
 
 class Make extends Task with TaskArgs {
-  override def execute: Unit = {
+  override def execute {
     if (id.isEmpty) error("Mandatory attribute 'id' is not set.")
     if (compilerPath.isEmpty) error("Mandatory attribute 'compilerpath' is not set.")
     val settings = new Settings
@@ -23,6 +22,6 @@ class Make extends Task with TaskArgs {
     if (!compilationPath.isEmpty) settings.classpath = compilationPath.get
     if (!sourcePath.isEmpty) settings.sourcepath = sourcePath.get
     if (!params.isEmpty) settings.more = params.get
-    Compilers.make(id.get, (compilerPath.get.list.map{ path => new File(path).toURL }), settings)
+    Compilers.make(id.get, (compilerPath.get.list.map{ path => new File(path).toURI.toURL }), settings)
   }
 }
diff --git a/src/compiler/scala/tools/ant/sabbus/ScalacFork.scala b/src/compiler/scala/tools/ant/sabbus/ScalacFork.scala
index e973672..4e90977 100644
--- a/src/compiler/scala/tools/ant/sabbus/ScalacFork.scala
+++ b/src/compiler/scala/tools/ant/sabbus/ScalacFork.scala
@@ -1,77 +1,120 @@
-package scala.tools.ant.sabbus
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala Ant Tasks                      **
+**    / __/ __// _ | / /  / _ |    (c) 2005-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
 
-import java.io.File;
-import org.apache.tools.ant.Project;
-import org.apache.tools.ant.taskdefs.{MatchingTask, Java}
-import org.apache.tools.ant.util.{GlobPatternMapper, SourceFileScanner}
 
-class ScalacFork extends MatchingTask with TaskArgs {
+package scala.tools.ant
+package sabbus
+
+import java.io.File
+import java.io.FileWriter
+import org.apache.tools.ant.Project
+import org.apache.tools.ant.taskdefs.{ MatchingTask, Java }
+import org.apache.tools.ant.util.{ GlobPatternMapper, SourceFileScanner }
+import scala.tools.nsc.io
+import scala.tools.nsc.util.ScalaClassLoader
+
+class ScalacFork extends MatchingTask with ScalacShared with TaskArgs {
+  private def originOfThis: String =
+    ScalaClassLoader.originOfClass(classOf[ScalacFork]) map (_.toString) getOrElse "<unknown>"
+  
   def setSrcdir(input: File) {
     sourceDir = Some(input)
   }
 
-  def setFailOnError(input: Boolean): Unit = {
+  def setFailOnError(input: Boolean) {
     failOnError = input
   }
 
-  def setTimeout(input: Long): Unit = {
+  def setTimeout(input: Long) {
     timeout = Some(input)
   }
 
-  def setJvmArgs(input: String): Unit = {
+  def setJvmArgs(input: String) {
     jvmArgs = Some(input)
   }
 
+  def setArgfile(input: File) {
+    argfile = Some(input)
+  }
+
   private var sourceDir: Option[File] = None
   private var failOnError: Boolean = true
   private var timeout: Option[Long] = None
   private var jvmArgs: Option[String] = None
+  private var argfile: Option[File] = None
+  
+  private def createMapper() = {
+    val mapper = new GlobPatternMapper()
+    val extension = if (isMSIL) "*.msil" else "*.class"
+    mapper setTo extension
+    mapper setFrom "*.scala"
+    
+    mapper
+  }
 
   override def execute() {
-    if (compilerPath.isEmpty) error("Mandatory attribute 'compilerpath' is not set.")
-    if (sourceDir.isEmpty) error("Mandatory attribute 'srcdir' is not set.")
-    if (destinationDir.isEmpty) error("Mandatory attribute 'destdir' is not set.")
+    def plural(x: Int) = if (x > 1) "s" else ""
+    
+    log("Executing ant task scalacfork, origin: %s".format(originOfThis), Project.MSG_VERBOSE)
 
+    val compilerPath = this.compilerPath getOrElse error("Mandatory attribute 'compilerpath' is not set.")
+    val sourceDir = this.sourceDir getOrElse error("Mandatory attribute 'srcdir' is not set.")
+    val destinationDir = this.destinationDir getOrElse error("Mandatory attribute 'destdir' is not set.")
+    
     val settings = new Settings
-    settings.d = destinationDir.get
-    if (!compTarget.isEmpty) settings.target = compTarget.get
-    if (!compilationPath.isEmpty) settings.classpath = compilationPath.get
-    if (!sourcePath.isEmpty) settings.sourcepath = sourcePath.get
-    if (!params.isEmpty) settings.more = params.get
-
-    // not yet used: compilerPath, sourcedir (used in mapper), failonerror, timeout
-
-    val mapper = new GlobPatternMapper()
-    mapper.setTo("*.class")
-    mapper.setFrom("*.scala")
+    settings.d = destinationDir
+    
+    compTarget foreach (settings.target = _)
+    compilationPath foreach (settings.classpath = _)
+    sourcePath foreach (settings.sourcepath = _)
+    params foreach (settings.more = _)
+    
+    if (isMSIL)
+      settings.sourcedir = sourceDir
+    
+    val mapper = createMapper()
+    
     val includedFiles: Array[File] =
       new SourceFileScanner(this).restrict(
-        getDirectoryScanner(sourceDir.get).getIncludedFiles,
-        sourceDir.get,
-        destinationDir.get,
+        getDirectoryScanner(sourceDir).getIncludedFiles,
+        sourceDir,
+        destinationDir,
         mapper
-      ) map (new File(sourceDir.get, _))
-    if (includedFiles.size > 0) {
-      log("Compiling "+ includedFiles.size +" file"+
-            (if (includedFiles.size > 1) "s" else "") +" to "+ destinationDir.get)
+      ) map (x => new File(sourceDir, x))
+    
+    /** Nothing to do. */
+    if (includedFiles.isEmpty && argfile.isEmpty)
+      return
+      
+    if (includedFiles.nonEmpty)
+      log("Compiling %d file%s to %s".format(includedFiles.size, plural(includedFiles.size), destinationDir))
+    
+    argfile foreach (x => log("Using argfile file: @" + x))
+    
+    val java = new Java(this)  // set this as owner
+    java setFork true
+    // using 'setLine' creates multiple arguments out of a space-separated string
+    jvmArgs foreach (java.createJvmarg() setLine _)
+    timeout foreach (java setTimeout _)
+    
+    java setClasspath compilerPath
+    java setClassname MainClass
 
-      val java = new Java(this) // set this as owner
-      java.setFork(true)
-      // using 'setLine' creates multiple arguments out of a space-separated string
-      if (!jvmArgs.isEmpty) java.createJvmarg().setLine(jvmArgs.get)
-      java.setClasspath(compilerPath.get)
-      java.setClassname("scala.tools.nsc.Main")
-      if (!timeout.isEmpty) java.setTimeout(timeout.get)
-      for (arg <- settings.toArgs)
-        java.createArg().setValue(arg)
-      for (file <- includedFiles)
-        java.createArg().setFile(file)
+    // dump the arguments to a file and do "java @file"
+    val tempArgFile = io.File.makeTemp("scalacfork")
+    val tokens = settings.toArgs ++ (includedFiles map (_.getPath))
+    tempArgFile writeAll (tokens mkString " ")
+    
+    val paths = List(Some(tempArgFile.toAbsolute.path), argfile).flatten map (_.toString)
+    val res = execWithArgFiles(java, paths)
 
-      log(java.getCommandLine.getCommandline.mkString("", " ", ""), Project.MSG_VERBOSE)
-      val res = java.executeJava()
-      if (failOnError && res != 0)
-        error("Compilation failed because of an internal compiler error;"+
-              " see the error output for details.")
-    }
+    if (failOnError && res != 0)
+      error("Compilation failed because of an internal compiler error;"+
+            " see the error output for details.")
   }
 }
diff --git a/src/compiler/scala/tools/ant/sabbus/Settings.scala b/src/compiler/scala/tools/ant/sabbus/Settings.scala
index 252c8ed..8c5c612 100644
--- a/src/compiler/scala/tools/ant/sabbus/Settings.scala
+++ b/src/compiler/scala/tools/ant/sabbus/Settings.scala
@@ -1,18 +1,18 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala Ant Tasks                      **
-**    / __/ __// _ | / /  / _ |    (c) 2005-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2005-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
+
 package scala.tools.ant.sabbus
 
 import java.io.File
 
 import org.apache.tools.ant.types.{Path, Reference}
 
- at cloneable
 class Settings {
   
   private var gBf: Option[String] = None
@@ -31,6 +31,10 @@ class Settings {
   def sourcepath = sourcepathBf.get
   def sourcepath_=(p: Path): this.type = { sourcepathBf = Some(p); this }
   
+  private var sourcedirBf: Option[File] = None
+  def sourcedir = sourcedirBf.get
+  def sourcedir_=(p: File): this.type = { sourcedirBf = Some(p); this }
+  
   private var bootclasspathBf: Option[Path] = None
   def bootclasspath = bootclasspathBf.get
   def bootclasspath_=(p: Path): this.type = { bootclasspathBf = Some(p); this }
@@ -64,13 +68,14 @@ class Settings {
     (if (uncheckedBf) "-unchecked" :: Nil else Nil) :::
     (if (!classpathBf.isEmpty) "-classpath" :: classpath.toString :: Nil else Nil) :::
     (if (!sourcepathBf.isEmpty) "-sourcepath" :: sourcepath.toString :: Nil else Nil) :::
+    (if (!sourcedirBf.isEmpty) "-Xsourcedir" :: sourcedir.toString :: Nil else Nil) :::
     (if (!bootclasspathBf.isEmpty) "-bootclasspath" :: bootclasspath.toString :: Nil else Nil) :::
     (if (!extdirsBf.isEmpty) "-extdirs" :: extdirs.toString :: Nil else Nil) :::
     (if (!dBf.isEmpty) "-d" :: d.getAbsolutePath :: Nil else Nil) :::
     (if (!encodingBf.isEmpty) "-encoding" :: encoding :: Nil else Nil) :::
     (if (!targetBf.isEmpty) "-target:"+target :: Nil else Nil) :::
     (if (optimiseBf) "-optimise" :: Nil else Nil) :::
-    (if (!moreBf.isEmpty) List.fromString(more, ' ') else Nil)
+    (if (!moreBf.isEmpty) (more split ' ').toList else Nil)
   
   override def equals(that: Any): Boolean = that match {
     case cs: Settings =>
@@ -78,6 +83,7 @@ class Settings {
       this.uncheckedBf == cs.uncheckedBf &&
       this.classpathBf == cs.classpathBf &&
       this.sourcepathBf == cs.sourcepathBf &&
+      this.sourcedirBf == cs.sourcedirBf &&
       this.bootclasspathBf == cs.bootclasspathBf &&
       this.extdirsBf == cs.extdirsBf &&
       this.dBf == cs.dBf &&
diff --git a/src/compiler/scala/tools/ant/sabbus/TaskArgs.scala b/src/compiler/scala/tools/ant/sabbus/TaskArgs.scala
index b9cb25e..ebca4cf 100644
--- a/src/compiler/scala/tools/ant/sabbus/TaskArgs.scala
+++ b/src/compiler/scala/tools/ant/sabbus/TaskArgs.scala
@@ -1,27 +1,24 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala Ant Tasks                      **
+**    / __/ __// _ | / /  / _ |    (c) 2005-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
 package scala.tools.ant.sabbus
 
 import java.io.File
 import org.apache.tools.ant.Task
 import org.apache.tools.ant.types.{Path, Reference}
 
-trait TaskArgs { this: Task =>
-  
-  def setId(input: String): Unit = {
-    id = Some(input)
-  }
+trait CompilationPathProperty {
+  this: Task =>
   
-  def setParams(input: String): Unit = {
-    params = params match {
-      case None => Some(input)
-      case Some(ps) => Some(ps + " " + input)
-    }
-  }
+  protected var compilationPath: Option[Path] = None
   
-  def setTarget(input: String): Unit = {
-    compTarget = Some(input)
-  }
-
-  def setCompilationPath(input: Path): Unit = {
+  def setCompilationPath(input: Path) {
     if (compilationPath.isEmpty) compilationPath = Some(input)
     else compilationPath.get.append(input)
   }
@@ -31,11 +28,30 @@ trait TaskArgs { this: Task =>
     compilationPath.get.createPath()
   }
 
-  def setCompilationPathRef(input: Reference): Unit = {
+  def setCompilationPathRef(input: Reference) {
     createCompilationPath.setRefid(input)
   }
+}
+
+trait TaskArgs extends CompilationPathProperty {
+  this: Task =>
+  
+  def setId(input: String) {
+    id = Some(input)
+  }
+  
+  def setParams(input: String) {
+    params = params match {
+      case None => Some(input)
+      case Some(ps) => Some(ps + " " + input)
+    }
+  }
+  
+  def setTarget(input: String) {
+    compTarget = Some(input)
+  }
 
-  def setSrcPath(input: Path): Unit = {
+  def setSrcPath(input: Path) {
     if (sourcePath.isEmpty) sourcePath = Some(input)
     else sourcePath.get.append(input)
   }
@@ -45,11 +61,11 @@ trait TaskArgs { this: Task =>
     sourcePath.get.createPath()
   }
 
-  def setSrcPathRef(input: Reference): Unit = {
+  def setSrcPathRef(input: Reference) {
     createSrcPath.setRefid(input)
   }
 
-  def setCompilerPath(input: Path): Unit = {
+  def setCompilerPath(input: Path) {
     if (compilerPath.isEmpty) compilerPath = Some(input)
     else compilerPath.get.append(input)
   }
@@ -59,19 +75,20 @@ trait TaskArgs { this: Task =>
     compilerPath.get.createPath()
   }
 
-  def setCompilerPathRef(input: Reference): Unit = {
+  def setCompilerPathRef(input: Reference) {
     createCompilerPath.setRefid(input)
   }
   
-  def setDestdir(input: File): Unit = {
+  def setDestdir(input: File) {
     destinationDir = Some(input)
   }
   
   protected var id: Option[String] = None
   protected var params: Option[String] = None
   protected var compTarget: Option[String] = None
-  protected var compilationPath: Option[Path] = None
   protected var sourcePath: Option[Path] = None
   protected var compilerPath: Option[Path] = None
   protected var destinationDir: Option[File] = None
+  
+  def isMSIL = compTarget exists (_ == "msil")
 }
diff --git a/src/compiler/scala/tools/ant/sabbus/Use.scala b/src/compiler/scala/tools/ant/sabbus/Use.scala
index e228f7c..3d45502 100644
--- a/src/compiler/scala/tools/ant/sabbus/Use.scala
+++ b/src/compiler/scala/tools/ant/sabbus/Use.scala
@@ -1,11 +1,12 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala Ant Tasks                      **
-**    / __/ __// _ | / /  / _ |    (c) 2005-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2005-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
+
 package scala.tools.ant.sabbus
 
 import java.io.File
@@ -16,7 +17,7 @@ import org.apache.tools.ant.util.{GlobPatternMapper, SourceFileScanner}
 
 class Use extends MatchingTask {
   
-  def setId(input: String): Unit = {
+  def setId(input: String) {
     id = Some(input)
   }
   
@@ -24,11 +25,11 @@ class Use extends MatchingTask {
     sourceDir = Some(input)
   }
   
-  def setDestdir(input: File): Unit = {
+  def setDestdir(input: File) {
     destinationDir = Some(input)
   }
   
-  def setFailOnError(input: Boolean): Unit = {
+  def setFailOnError(input: Boolean) {
     failOnError = input
   }
   
@@ -37,7 +38,7 @@ class Use extends MatchingTask {
   private var destinationDir: Option[File] = None
   private var failOnError: Boolean = true
   
-  override def execute(): Unit = {
+  override def execute() {
     if (id.isEmpty) error("Mandatory attribute 'id' is not set.")
     if (sourceDir.isEmpty) error("Mandatory attribute 'srcdir' is not set.")
     val compiler = Compilers(id.get)
@@ -59,7 +60,7 @@ class Use extends MatchingTask {
         if (errors > 0)
           error("Compilation failed with " + errors + " error" + (if (errors > 1) "s" else "") + ".")
         else if (warnings > 0)
-          log("Compilation suceeded with " + warnings + " warning" + (if (warnings > 1) "s" else "") + ".")
+          log("Compilation succeeded with " + warnings + " warning" + (if (warnings > 1) "s" else "") + ".")
       }
       catch {
         case CompilationFailure(msg, ex) =>
diff --git a/src/compiler/scala/tools/ant/sabbus/antlib.xml b/src/compiler/scala/tools/ant/sabbus/antlib.xml
index 04cd1a8..0a598bd 100644
--- a/src/compiler/scala/tools/ant/sabbus/antlib.xml
+++ b/src/compiler/scala/tools/ant/sabbus/antlib.xml
@@ -7,4 +7,4 @@
              classname="scala.tools.ant.sabbus.Break"/>
     <taskdef name="scalacfork"
              classname="scala.tools.ant.sabbus.ScalacFork"/>
-</antlib>
\ No newline at end of file
+</antlib>
diff --git a/src/compiler/scala/tools/ant/templates/tool-unix.tmpl b/src/compiler/scala/tools/ant/templates/tool-unix.tmpl
index 936767b..b87463f 100644
--- a/src/compiler/scala/tools/ant/templates/tool-unix.tmpl
+++ b/src/compiler/scala/tools/ant/templates/tool-unix.tmpl
@@ -1,7 +1,7 @@
 #!/bin/sh
-
+#
 ##############################################################################
-# Copyright 2002-2009, LAMP/EPFL
+# Copyright 2002-2010, LAMP/EPFL
 #
 # This is free software; see the distribution for copying conditions.
 # There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A
@@ -26,8 +26,12 @@ while [ -h "$SOURCE" ]; do
         SOURCE=`dirname "$SOURCE"`/${TARGET:-.};
     fi;
 done;
-SCALA_HOME=`dirname "$SOURCE"`/..;
-SCALA_HOME=`cd "$SCALA_HOME"; pwd`;
+
+# see #2092
+SCALA_HOME=`dirname "$SOURCE"`
+SCALA_HOME=`cd "$SCALA_HOME"; pwd -P`
+SCALA_HOME=`cd "$SCALA_HOME"/..; pwd`
+
 # Remove spaces from SCALA_HOME on windows
 if $cygwin; then
     SCALA_HOME=`cygpath --windows --short-name "$SCALA_HOME"`
@@ -37,7 +41,7 @@ fi
 # Constructing the extension classpath
 TOOL_CLASSPATH="@classpath@"
 if [ -z "$TOOL_CLASSPATH" ] ; then
-    for ext in `ls -d "$SCALA_HOME"/lib/*` ; do
+    for ext in "$SCALA_HOME"/lib/* ; do
         if [ -z "$TOOL_CLASSPATH" ] ; then
             TOOL_CLASSPATH="$ext"
         else
@@ -59,8 +63,21 @@ fi
 # Reminder: substitution ${JAVA_OPTS:=-Xmx256M -Xms16M} DO NOT work on Solaris
 [ -n "$JAVA_OPTS" ] || JAVA_OPTS="@javaflags@"
 
+# break out -D options and add them to JAVA_OPTS as well so they reach the
+# underlying JVM in time to do some good.
+for i
+do
+  case "$i" in
+    -D*)
+      JAVA_OPTS="$JAVA_OPTS $i" ;;
+    *)
+      ;;
+  esac
+done 
+
+
 if [ -z "$JAVACMD" -a -n "$JAVA_HOME" -a -x "$JAVA_HOME/bin/java" ]; then
     JAVACMD="$JAVA_HOME/bin/java"
 fi
 
-exec "${JAVACMD:=java}" $JAVA_OPTS -cp "$TOOL_CLASSPATH" -Dscala.home="$SCALA_HOME" -Denv.classpath="$CLASSPATH" -Denv.emacs="$EMACS" @properties@ @class@ @toolflags@ "$@@"
+exec "${JAVACMD:=java}" $JAVA_OPTS -cp "$TOOL_CLASSPATH" -Dscala.home="$SCALA_HOME" -Denv.emacs="$EMACS" @properties@ @class@ @toolflags@ "$@@"
diff --git a/src/compiler/scala/tools/ant/templates/tool-windows.tmpl b/src/compiler/scala/tools/ant/templates/tool-windows.tmpl
index 9cd7cc9..ad72e3f 100644
--- a/src/compiler/scala/tools/ant/templates/tool-windows.tmpl
+++ b/src/compiler/scala/tools/ant/templates/tool-windows.tmpl
@@ -1,7 +1,7 @@
 @@echo off
 
 rem ##########################################################################
-rem # Copyright 2002-2009, LAMP/EPFL
+rem # Copyright 2002-2010, LAMP/EPFL
 rem #
 rem # This is free software; see the distribution for copying conditions.
 rem # There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A
@@ -47,7 +47,7 @@ if "%_TOOL_CLASSPATH%"=="" (
   )
 )
 
-set _PROPS=-Dscala.home="%_SCALA_HOME%" -Denv.classpath="%CLASSPATH%" -Denv.emacs="%EMACS%" @properties@
+set _PROPS=-Dscala.home="%_SCALA_HOME%" -Denv.emacs="%EMACS%" @properties@
 
 rem echo "%_JAVACMD%" %_JAVA_OPTS% %_PROPS% -cp "%_TOOL_CLASSPATH%" @class@ @toolflags@ %_ARGS%
 "%_JAVACMD%" %_JAVA_OPTS% %_PROPS% -cp "%_TOOL_CLASSPATH%" @class@ @toolflags@ %_ARGS%
diff --git a/src/compiler/scala/tools/cmd/CommandLine.scala b/src/compiler/scala/tools/cmd/CommandLine.scala
new file mode 100644
index 0000000..d313d0e
--- /dev/null
+++ b/src/compiler/scala/tools/cmd/CommandLine.scala
@@ -0,0 +1,91 @@
+/* NEST (New Scala Test)
+ * Copyright 2007-2010 LAMP/EPFL
+ * @author Paul Phillips
+ */
+
+package scala.tools
+package cmd
+
+import scala.collection.mutable.ListBuffer
+
+trait CommandLineConfig {
+  def enforceArity: Boolean = true
+  def onlyKnownOptions: Boolean = true
+}
+
+/** An instance of a command line, parsed according to a Spec.
+ */
+class CommandLine(val spec: Reference, val originalArgs: List[String]) extends CommandLineConfig {
+  def this(spec: Reference, line: String) = this(spec, Parser tokenize line)
+  def this(spec: Reference, args: Array[String]) = this(spec, args.toList)
+    
+  import spec.{ isAnyOption, isUnaryOption, isBinaryOption, isExpandOption }
+  
+  val Terminator = "--"
+  val ValueForUnaryOption = "true"  // so if --opt is given, x(--opt) = true
+
+  def mapForUnary(opt: String) = Map(opt -> ValueForUnaryOption)
+  def errorFn(msg: String) = println(msg)
+  
+  /** argMap is option -> argument (or "" if it is a unary argument)
+   *  residualArgs are what is left after removing the options and their args.
+   */
+  lazy val (argMap, residualArgs) = {
+    val residualBuffer = new ListBuffer[String]
+    
+    def loop(args: List[String]): Map[String, String] = {
+      def residual(xs: List[String]) = { residualBuffer ++= xs ; Map[String, String]() }
+
+      /** Returns Some(List(args)) if this option expands to an
+       *  argument list and it's not returning only the same arg.
+       */
+      def expand(s1: String) = {
+        if (isExpandOption(s1)) {
+          val s2 = spec expandArg s1
+          if (s2 == List(s1)) None
+          else Some(s2)
+        }
+        else None
+      }
+      
+      /** Assumes known options have all been ruled out already. */
+      def isUnknown(opt: String) =
+        onlyKnownOptions && (opt startsWith "-") && {
+          errorFn("Option '%s' not recognized.".format(opt))
+          true
+        }
+
+      args match {
+        case Nil              => Map()
+        case Terminator :: xs => residual(xs)
+        case x :: Nil         =>
+          expand(x) foreach (exp => return loop(exp))
+          if (isBinaryOption(x) && enforceArity)
+            errorFn("Option '%s' requires argument, found EOF instead.".format(x))
+      
+          if (isUnaryOption(x)) mapForUnary(x)
+          else if (isUnknown(x)) Map()
+          else residual(args)
+          
+        case x1 :: x2 :: xs   =>
+          expand(x1) foreach (exp => return loop(exp ++ args.tail))
+          
+          if (x2 == Terminator)         mapForUnary(x1) ++ residual(xs)
+          else if (isUnaryOption(x1))   mapForUnary(x1) ++ loop(args.tail)
+          else if (isBinaryOption(x1))  Map(x1 -> x2) ++ loop(xs)
+          else if (isUnknown(x1))       loop(args.tail)
+          else                          residual(List(x1)) ++ loop(args.tail)
+      }
+    }
+    
+    (loop(originalArgs), residualBuffer map stripQuotes toList)
+  }
+  
+  def apply(arg: String)  = argMap(arg)
+  def get(arg: String)    = argMap get arg
+  def isSet(arg: String)  = argMap contains arg
+
+  def getOrElse(arg: String, orElse: => String) = if (isSet(arg)) apply(arg) else orElse
+
+  override def toString() = argMap.toString + " " + residualArgs.toString
+}
diff --git a/src/compiler/scala/tools/cmd/Demo.scala b/src/compiler/scala/tools/cmd/Demo.scala
new file mode 100644
index 0000000..ebcd557
--- /dev/null
+++ b/src/compiler/scala/tools/cmd/Demo.scala
@@ -0,0 +1,84 @@
+/* NEST (New Scala Test)
+ * Copyright 2007-2010 LAMP/EPFL
+ * @author  Paul Phillips
+ */
+
+package scala.tools
+package cmd
+
+/** A sample command specification for illustrative purposes.
+ *  First take advantage of the meta-options:
+ *  
+ *    // this command creates an executable runner script "demo"
+ *    % scala scala.tools.cmd.Demo --self-update demo
+ *
+ *    // this one creates and sources a completion file - note backticks
+ *    % `./demo --bash`
+ *
+ *    // and now you have a runner with working completion
+ *    % ./demo --<tab>
+ *       --action           --defint           --int
+ *       --bash             --defstr           --str
+ *       --defenv           --self-update      --unary
+ *
+ *  The normal option configuration is plausibly self-explanatory.
+ */
+trait DemoSpec extends Spec with Meta.StdOpts with Interpolation {
+  lazy val referenceSpec  = DemoSpec
+  lazy val programInfo    = Spec.Info("demo", "Usage: demo [<options>]", "scala.tools.cmd.Demo")
+
+  help("""Usage: demo [<options>]""")
+  heading("Unary options:")
+
+  val optIsUnary      = "unary"         / "a unary option"              --?  ;
+  ("action" / "a body which may be run") --> println("Hello, I am the --action body.")
+  
+  heading("Binary options:")
+  val optopt          = "str"       / "an optional String"        --|
+  val optoptInt       = ("int"      / "an optional Int") .        --^[Int]
+  val optEnv          = "defenv"    / "an optional String"        defaultToEnv  "PATH"
+  val optDefault      = "defstr"    / "an optional String"        defaultTo     "default"
+  val optDefaultInt   = "defint"    / "an optional Int"           defaultTo     -1
+  val optExpand       = "alias"     / "an option which expands"   expandTo      ("--int", "15")
+}
+
+object DemoSpec extends DemoSpec with Property {
+  lazy val propMapper = new PropertyMapper(DemoSpec)
+
+  type ThisCommandLine = SpecCommandLine
+  def creator(args: List[String]) =
+    new SpecCommandLine(args) {
+      override def errorFn(msg: String) = { println("Error: " + msg) ; System.exit(0) }
+    }
+}
+
+class Demo(args: List[String]) extends {
+  val parsed = DemoSpec(args: _*)
+} with DemoSpec with Instance {
+  import java.lang.reflect._
+
+  def helpMsg = DemoSpec.helpMsg
+  def demoSpecMethods = this.getClass.getMethods.toList
+  private def isDemo(m: Method) = (m.getName startsWith "opt") && !(m.getName contains "$") && (m.getParameterTypes.isEmpty)  
+
+  def demoString(ms: List[Method]) = {
+    val longest   = ms map (_.getName.length) max
+    val formatStr = "    %-" + longest + "s: %s"
+    val xs        = ms map (m => formatStr.format(m.getName, m.invoke(this)))
+    
+    xs mkString ("Demo(\n  ", "\n  ", "\n)\n")
+  }
+    
+  override def toString = demoString(demoSpecMethods filter isDemo)
+}
+
+object Demo {
+  def main(args: Array[String]): Unit = {
+    val runner = new Demo(args.toList)
+
+    if (args.isEmpty)
+      println(runner.helpMsg)
+    
+    println(runner)
+  }
+}
diff --git a/src/compiler/scala/tools/cmd/FromString.scala b/src/compiler/scala/tools/cmd/FromString.scala
new file mode 100644
index 0000000..e747c27
--- /dev/null
+++ b/src/compiler/scala/tools/cmd/FromString.scala
@@ -0,0 +1,72 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
+ * @author  Paul Phillips
+ */
+
+package scala.tools
+package cmd
+
+import nsc.io.{ Path, File, Directory }
+import reflect.OptManifest
+
+/** A general mechanism for defining how a command line argument
+ *  (always a String) is transformed into an arbitrary type.  A few
+ *  example instances are in the companion object, but in general
+ *  either IntFromString will suffice or you'll want custom transformers.
+ */
+abstract class FromString[+T](implicit m: OptManifest[T]) extends PartialFunction[String, T] {
+  def apply(s: String): T
+  def isDefinedAt(s: String): Boolean = true
+  def zero: T = apply("")
+
+  def targetString: String = m.toString
+}
+
+object FromString {
+  // We need these because we clash with the String => Path implicits.
+  private def toFile(s: String) = new File(new java.io.File(s))
+  private def toDir(s: String)  = new Directory(new java.io.File(s))
+  
+  /** Path related stringifiers.
+   */
+  val ExistingFile: FromString[File] = new FromString[File] {
+    override def isDefinedAt(s: String) = toFile(s).isFile
+    def apply(s: String): File =
+      if (isDefinedAt(s)) toFile(s)
+      else cmd.runAndExit(println("'%s' is not an existing file." format s))
+  }
+  val ExistingDir: FromString[Directory] = new FromString[Directory] {
+    override def isDefinedAt(s: String) = toDir(s).isDirectory
+    def apply(s: String): Directory = 
+      if (isDefinedAt(s)) toDir(s)
+      else cmd.runAndExit(println("'%s' is not an existing directory." format s))
+  }
+  def ExistingDirRelativeTo(root: Directory) = new FromString[Directory] {
+    private def resolve(s: String) = toDir(s) toAbsoluteWithRoot root toDirectory
+    override def isDefinedAt(s: String) = resolve(s).isDirectory
+    def apply(s: String): Directory = 
+      if (isDefinedAt(s)) resolve(s)
+      else cmd.runAndExit(println("'%s' is not an existing directory." format resolve(s)))
+  }
+  
+  /** Argument expander, i.e. turns single argument "foo bar baz" into argument
+   *  list "foo", "bar", "baz".
+   */
+  val ArgumentsFromString: FromString[List[String]] = new FromString[List[String]] {
+    def apply(s: String) = toArgs(s)
+  }
+ 
+  /** Identity.
+   */
+  implicit val StringFromString: FromString[String] = new FromString[String] {
+    def apply(s: String): String = s
+  }
+
+  /** Implicit as the most likely to be useful as-is.
+   */
+  implicit val IntFromString: FromString[Int] = new FromString[Int] {
+    override def isDefinedAt(s: String)   = safeToInt(s).isDefined
+    def apply(s: String)                  = safeToInt(s).get
+    def safeToInt(s: String): Option[Int] = try Some(java.lang.Integer.parseInt(s)) catch { case _: NumberFormatException => None }
+  }
+}
diff --git a/src/compiler/scala/tools/cmd/Instance.scala b/src/compiler/scala/tools/cmd/Instance.scala
new file mode 100644
index 0000000..1ed4dc8
--- /dev/null
+++ b/src/compiler/scala/tools/cmd/Instance.scala
@@ -0,0 +1,24 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
+ * @author  Paul Phillips
+ */
+
+package scala.tools
+package cmd
+
+/** The trait mixed into each instance of a specification.
+ *
+ *  @see    Reference
+ */
+trait Instance extends Spec {
+  def parsed: CommandLine
+
+  protected def help(str: => String): Unit = ()
+
+  def isSet(s: String)    = parsed isSet toOpt(s)
+  def originalArgs        = parsed.originalArgs     // the full original list
+  def residualArgs        = parsed.residualArgs     // only args which were not options or args to options
+  
+  type OptionMagic = Opt.Instance
+  protected implicit def optionMagicAdditions(name: String) = new Opt.Instance(programInfo, parsed, name)
+}
diff --git a/src/compiler/scala/tools/cmd/Interpolation.scala b/src/compiler/scala/tools/cmd/Interpolation.scala
new file mode 100644
index 0000000..4e3e102
--- /dev/null
+++ b/src/compiler/scala/tools/cmd/Interpolation.scala
@@ -0,0 +1,57 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
+ * @author  Paul Phillips
+ */
+
+package scala.tools
+package cmd
+
+/** Interpolation logic for generated files.  The idea is to be
+ *  able to write in terms of @@THIS@@ and @@THAT@@ and the reference
+ *  specification knows enough to perform the substitutions.  Warrants
+ *  expansion.
+ */
+trait Interpolation {
+  self: Spec =>
+  
+  private lazy val reference = referenceSpec
+  import reference._
+  
+  object interpolate {
+    def mapper: Map[String, () => String] = Map(
+      "PROGRAM"       -> (() => programInfo.runner),
+      "ALLOPTIONS"    -> (() => options.all mkString " "),
+      "MAINCLASS"     -> (() => programInfo.mainClass)
+    )
+    
+    private def mark(key: String) = "@@" + key + "@@"
+    def apply(template: String) = mapper.foldLeft(template) { case (s, (key, f)) => s.replaceAll(mark(key), f()) }
+  }
+}
+
+object Interpolation {
+  /** A simple template for generating bash completion functions.
+   */
+  lazy val bashTemplate = """
+    |_@@PROGRAM@@()
+    |{
+    |  local cur opts base
+    |  COMPREPLY=()
+    |  cur="${COMP_WORDS[COMP_CWORD]}"
+    |  opts="@@ALLOPTIONS@@"
+    |  
+    |  COMPREPLY=($(compgen -W "${opts}" -- ${cur}))
+    |  _filedir
+    |  return 0
+    |} && complete -F _@@PROGRAM@@ @@PROGRAM@@
+  """.stripMargin
+  
+  /** A simple template for generating a runner script.
+   */
+  val runnerTemplate = """
+    |#!/bin/sh
+    |#
+    |
+    |scala @@MAINCLASS@@ "$@"
+    |""".stripMargin.trim + "\n"
+}
diff --git a/src/compiler/scala/tools/cmd/Meta.scala b/src/compiler/scala/tools/cmd/Meta.scala
new file mode 100644
index 0000000..b9627f9
--- /dev/null
+++ b/src/compiler/scala/tools/cmd/Meta.scala
@@ -0,0 +1,67 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
+ * @author  Paul Phillips
+ */
+
+package scala.tools
+package cmd
+
+import nsc.io.File
+import Interpolation._
+
+/** Meta-options for command line tools.  We could have all kinds
+ *  of additional goodness here, but for now it's completion and script
+ *  generation.  See Demo for example usage.
+ */
+object Meta {
+  trait Opt {
+    def name: String
+    def action: () => Unit
+  }
+  
+  trait StdOpts {
+    self: Spec with Interpolation =>
+    
+                                Bash.name   --> runAndExit(Bash.action())
+    val selfUpdateName  = SelfUpdate.name   --| ;
+    
+    if (selfUpdateName.isDefined)
+      runAndExit(SelfUpdate.action())
+    
+    /** I think we're as close as we can get to bundling completion with
+     *  the program given the constraints imposed by bash.  This outputs
+     *  the completion function to a tempfile and echoes ". /path/to/file"
+     *  to the console.  Place it inside backtickes like `partest --bash`
+     *  and voila, you have absorbed command completion.
+     */
+    object Bash extends Opt {
+      val name    = "bash"
+      val action  = () => {
+        val file = File.makeTemp("scala.cmd.bash")
+        file writeAll interpolate(bashTemplate)
+
+        // Would be nice to print something like this but comments are
+        // not always comments in bash, and breaking it is worse.
+        // Console println ("# Run the following line, or issue the --bash command in `backticks`.")
+        Console println (". " + file.normalize.path)
+      }
+    }
+
+    /** Generates a very basic runner script.  It's called SelfUpdate
+     *  because once it exists you can do something like
+     *
+     *    tools/scmp --self-update tools/scmp
+     *
+     *  and it will overwrite itself with the current version.  
+     */
+    object SelfUpdate extends Opt {
+      val name    = "self-update"
+      val action  = () => {
+        val file = File(selfUpdateName.get)
+        file writeAll interpolate(runnerTemplate)
+        file setExecutable true
+        ()
+      }
+    }
+  }
+}
diff --git a/src/compiler/scala/tools/cmd/Opt.scala b/src/compiler/scala/tools/cmd/Opt.scala
new file mode 100644
index 0000000..384b4fc
--- /dev/null
+++ b/src/compiler/scala/tools/cmd/Opt.scala
@@ -0,0 +1,91 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
+ * @author  Paul Phillips
+ */
+
+package scala.tools
+package cmd
+
+import nsc.Properties.envOrElse
+import Spec.Info
+
+/** Machinery for what amounts to a command line specification DSL.
+ *  It is designed so the same specification trait can be used for
+ *  two different purposes: generating a singleton specification object
+ *  (trait Reference) and providing well typed vals for every configurable
+ *  option in response to any given set of arguments (trait Instance).
+ */
+object Opt {  
+  trait Error {
+    self: Implicit =>
+    
+    protected def fail(msg: String) = runAndExit(println(programInfo.runner + ": " + msg))
+    protected def failOption(arg: String, why: String) = fail("%s: '%s' is %s".format(opt, arg, why))    
+  }
+
+  trait Implicit {
+    def name: String
+    def programInfo: Info
+    protected def opt = toOpt(name)
+    
+    def --? : Boolean                       // --opt is set
+    def --> (body: => Unit): Unit           // if --opt is set, execute body    
+    def --| : Option[String]                // --opt <arg: String> is optional, result is Option[String]
+    def --^[T: FromString] : Option[T]      // --opt <arg: T> is optional, result is Option[T]
+    
+    def optMap[T](f: String => T) = --| map f
+  
+    /** Names.
+     */
+    def defaultTo[T: FromString](default: T): T
+    def defaultToEnv(envVar: String): String
+    def choiceOf[T: FromString](choices: T*): Option[T]
+    def expandTo(args: String*): Unit
+
+    /** Help.
+     */
+    def /(descr: String): String            // --opt has help description 'descr'
+  }
+
+  class Reference(val programInfo: Info, val options: Reference.Accumulators, val name: String) extends Implicit {
+    import options._
+
+    def --?                             = { addUnary(opt) ; false }
+    def --> (body: => Unit)             = { addUnary(opt) }
+    def --|                             = { addBinary(opt) ; None }
+    def --^[T: FromString]              = { addBinary(opt) ; None }
+    
+    def defaultTo[T: FromString](default: T)  = { addBinary(opt) ; addHelpDefault(() => default.toString) ; default }
+    def defaultToEnv(envVar: String)          = { addBinary(opt) ; addHelpEnvDefault(envVar) ; "" }
+    def choiceOf[T: FromString](choices: T*)  = { addBinary(opt) ; None }
+    def expandTo(args: String*)               = { addExpand(name, args.toList) ; addHelpAlias(() => args mkString " ") }
+
+    def /(descr: String)                = returning(name)(_ => addHelp(() => helpFormatStr.format(opt, descr)))
+  }
+
+  class Instance(val programInfo: Info, val parsed: CommandLine, val name: String) extends Implicit with Error {
+    def --?                             = parsed isSet opt
+    def --> (body: => Unit)             = if (parsed isSet opt) body
+    def --|                             = parsed get opt
+    def --^[T: FromString]              = {
+      val fs = implicitly[FromString[T]]
+      --| map { arg =>
+        if (fs isDefinedAt arg) fs(arg)
+        else failOption(arg, "not a " + fs.targetString)
+      }
+    }    
+    
+    def defaultTo[T: FromString](default: T)  = --^[T] getOrElse default
+    def defaultToEnv(envVar: String)          = --| getOrElse envOrElse(envVar, "")
+    def expandTo(args: String*)               = ()
+          
+    def choiceOf[T: FromString](choices: T*) = {      
+      --^[T] map { arg =>
+        if (choices contains arg) arg
+        else failOption(arg.toString, "not a valid choice from " + choices)
+      }
+    }
+
+    def /(descr: String)                = name
+  }
+}
diff --git a/src/compiler/scala/tools/cmd/Parser.scala b/src/compiler/scala/tools/cmd/Parser.scala
new file mode 100644
index 0000000..26370ce
--- /dev/null
+++ b/src/compiler/scala/tools/cmd/Parser.scala
@@ -0,0 +1,52 @@
+/* NEST (New Scala Test)
+ * Copyright 2007-2010 LAMP/EPFL
+ * @author Paul Phillips
+ */
+
+package scala.tools
+package cmd
+
+import scala.util.parsing.combinator._
+import scala.util.parsing.input.CharArrayReader.EofCh
+
+/** A simple (overly so) command line parser.
+ *  !!! This needs a thorough test suite to make sure quoting is
+ *  done correctly and portably.
+ */
+trait ParserUtil extends Parsers {
+  class ParserPlus[+T](underlying: Parser[T]) {
+    def !~>[U](p: => Parser[U]): Parser[U] = (underlying ~! p) ^^ { case a~b  => b }
+    def <~![U](p: => Parser[U]): Parser[T] = (underlying ~! p) ^^ { case a~b  => a }
+  }
+  protected implicit def parser2parserPlus[T](p: Parser[T]): ParserPlus[T] = new ParserPlus(p)
+}
+
+object Parser extends RegexParsers with ParserUtil {
+  override def skipWhitespace = false
+  
+  def elemExcept(xs: Elem*): Parser[Elem] = elem("elemExcept", x => x != EofCh && !(xs contains x))
+  def elemOf(xs: Elem*): Parser[Elem]     = elem("elemOf", xs contains _)
+  def escaped(ch: Char): Parser[String] = "\\" + ch
+  def mkQuoted(ch: Char): Parser[String] = (
+      elem(ch) !~> rep(escaped(ch) | elemExcept(ch)) <~ ch ^^ (_.mkString)
+    | failure("Unmatched %s in input." format ch)
+  )
+  
+  /** Apparently windows can't deal with the quotes sticking around. */
+  lazy val squoted: Parser[String] = mkQuoted('\'')   // ^^ (x => "'%s'" format x)
+  lazy val dquoted: Parser[String] = mkQuoted('"')    // ^^ (x => "\"" + x + "\"")
+  lazy val token: Parser[String]   = """\S+""".r
+
+  lazy val argument: Parser[String] = squoted | dquoted | token
+  lazy val commandLine: Parser[List[String]] = phrase(repsep(argument, whiteSpace))
+  
+  class ParseException(msg: String) extends RuntimeException(msg)
+  
+  def tokenize(line: String): List[String] = tokenize(line, x => throw new ParseException(x))
+  def tokenize(line: String, errorFn: String => Unit): List[String] = {
+    parse(commandLine, line.trim) match {
+      case Success(args, _)     => args
+      case NoSuccess(msg, rest) => errorFn(msg) ; Nil
+    }
+  }
+}
diff --git a/src/compiler/scala/tools/cmd/Property.scala b/src/compiler/scala/tools/cmd/Property.scala
new file mode 100644
index 0000000..0dbcba4
--- /dev/null
+++ b/src/compiler/scala/tools/cmd/Property.scala
@@ -0,0 +1,71 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
+ * @author  Paul Phillips
+ */
+
+package scala.tools
+package cmd
+
+import nsc.io._
+import java.util.Properties
+import java.io.FileInputStream
+
+/** Contains logic for translating a property key/value pair into
+ *  equivalent command line arguments.  The default settings will
+ *  translate, given programInfo.runner == "foo" :
+ *
+ *    foo.bar=true  to  --bar       // if --bar is unary
+ *    foo.bar=quux  to  --bar quux  // if --bar is binary
+ */
+class PropertyMapper(reference: Reference) extends (((String, String)) => List[String]) {
+  import reference._
+  lazy val RunnerName = programInfo.runner
+  
+  // e.g. "partest.shootout" -> "--shootout"
+  def propNameToOptionName(key: String): Option[String] = (key split '.').toList match {
+    case List(RunnerName, name) => Some(name)
+    case _                      => None
+  }
+
+  def isPassThrough(key: String): Boolean = false                 // e.g. "partest.options" 
+  def onError(key: String, value: String): Unit = ()              // called when translate fails
+  
+  def translate(key: String, value: String): List[String] = {
+    val opt = toOpt(key)
+    
+    if (isUnaryOption(key) && isTrue(value)) List(opt)
+    else if (isBinaryOption(key)) List(opt, value)
+    else returning(Nil)(_ => onError(key, value))
+  }
+  def isTrue(value: String) = List("yes", "on", "true") contains value.toLowerCase
+  
+  def apply(kv: (String, String)): List[String] = {
+    val (k, v) = kv
+    
+    if (isPassThrough(k)) toArgs(v)
+    else propNameToOptionName(k) match {
+      case Some(optName)  => translate(optName, v)
+      case _              => Nil
+    }
+  }
+}
+
+trait Property extends Reference {
+  def propMapper: PropertyMapper
+  override def propertyArgs: List[String] = systemPropertiesToOptions
+  
+  def loadProperties(file: File): Properties  =
+    returning(new Properties)(_ load new FileInputStream(file.path))
+
+  def systemPropertiesToOptions: List[String] =
+    propertiesToOptions(System.getProperties)
+  
+  def propertiesToOptions(file: File): List[String] =
+    propertiesToOptions(loadProperties(file))
+    
+  def propertiesToOptions(props: java.util.Properties): List[String] = {
+    import collection.JavaConversions._
+    propertiesToOptions(props.toList)
+  }
+  def propertiesToOptions(props: List[(String, String)]) = props flatMap propMapper
+}
diff --git a/src/compiler/scala/tools/cmd/Reference.scala b/src/compiler/scala/tools/cmd/Reference.scala
new file mode 100644
index 0000000..c7dda5b
--- /dev/null
+++ b/src/compiler/scala/tools/cmd/Reference.scala
@@ -0,0 +1,99 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
+ * @author  Paul Phillips
+ */
+
+package scala.tools
+package cmd
+
+import collection.mutable.ListBuffer
+import nsc.Properties.envOrNone
+
+/** Mixes in the specification trait and uses the vals therein to
+ *  side-effect private accumulators.  From this emerges formatted help,
+ *  lists of unary and binary arguments, an apply which can creates
+ *  instances of the specification, and etc.
+ *
+ *  @see    Instance
+ */
+trait Reference extends Spec {
+  lazy val options = new Reference.Accumulators()
+  import options._
+
+  def helpMsg     = options.helpMsg
+  def propertyArgs: List[String] = Nil
+  
+  def isUnaryOption(s: String)  = unary contains toOpt(s)
+  def isBinaryOption(s: String) = binary contains toOpt(s)
+  def isExpandOption(s: String) = expansionMap contains toOpt(s)
+  def isAnyOption(s: String)    = isUnaryOption(s) || isBinaryOption(s) || isExpandOption(s)
+    
+  def expandArg(arg: String)      = expansionMap.getOrElse(fromOpt(arg), List(arg))
+
+  protected def help(str: => String)        = addHelp(() => str)
+  
+  type ThisCommandLine <: CommandLine
+  
+  class SpecCommandLine(args: List[String]) extends CommandLine(Reference.this, args) { }
+  protected def creator(args: List[String]): ThisCommandLine
+  final def apply(args: String*): ThisCommandLine = creator(propertyArgs ++ args flatMap expandArg)
+  
+  type OptionMagic = Opt.Reference
+  protected implicit def optionMagicAdditions(name: String) = new Opt.Reference(programInfo, options, name)
+}
+
+object Reference {
+  val MaxLine = 80
+  
+  class Accumulators() {
+    private var _help     = new ListBuffer[() => String]
+    private var _unary   = List[String]()
+    private var _binary  = List[String]()
+    private var _expand  = Map[String, List[String]]()
+    
+    def helpFormatStr     = "    %-" + longestArg + "s %s"
+    def defaultFormatStr  = (" " * (longestArg + 7)) + "%s"
+
+    def addUnary(s: String)   = _unary +:= s
+    def addBinary(s: String)  = _binary +:= s
+
+    def addExpand(opt: String, expanded: List[String]) =
+      _expand += (opt -> expanded)
+    
+    def mapHelp(g: String => String) = {
+      val idx = _help.length - 1
+      val f = _help(idx)
+      
+      _help(idx) = () => g(f())
+    }
+    
+    def addHelp(f: () => String)      = _help += f
+    def addHelpAlias(f: () => String) = mapHelp { s =>
+      val str = "alias for '%s'" format f()
+      def noHelp = (helpFormatStr.format("", "")).length == s.length
+      val str2 = if (noHelp) str else " (" + str + ")"
+      
+      s + str2
+    }
+    def addHelpDefault(f: () => String) = mapHelp { s =>
+      val str = "(default: %s)" format f()
+      
+      if (s.length + str.length < MaxLine) s + " " + str
+      else defaultFormatStr.format(s, str)
+    }
+    def addHelpEnvDefault(name: String) = mapHelp { s =>
+      val line1     = "%s (default: %s)".format(s, name)
+      val envNow    = envOrNone(name) map ("'" + _ + "'") getOrElse "unset"
+      val line2     = defaultFormatStr.format("Currently " + envNow)
+      
+      line1 + "\n" + line2
+    }
+
+    lazy val unary          = (_unary ++ _expand.keys).distinct
+    lazy val binary         = _binary.distinct
+    lazy val all            = unary ++ binary
+    lazy val expansionMap   = _expand
+    lazy val helpMsg        = _help map (f => f() + "\n") mkString
+    lazy val longestArg     = all map (_.length) max
+  }
+}
diff --git a/src/compiler/scala/tools/cmd/Spec.scala b/src/compiler/scala/tools/cmd/Spec.scala
new file mode 100644
index 0000000..4bd8317
--- /dev/null
+++ b/src/compiler/scala/tools/cmd/Spec.scala
@@ -0,0 +1,52 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
+ * @author  Paul Phillips
+ */
+
+package scala.tools
+package cmd
+
+/** This trait works together with others in scala.tools.cmd to allow
+ *  declaratively specifying a command line program, with many attendant
+ *  benefits.  See scala.tools.cmd.DemoSpec for an example.
+ */
+trait Spec {
+  def referenceSpec: Reference
+  def programInfo: Spec.Info
+  
+  protected def help(str: => String): Unit
+  protected def heading(str: => String): Unit = help("\n  " + str)
+
+  type OptionMagic <: Opt.Implicit
+  protected implicit def optionMagicAdditions(s: String): OptionMagic
+}
+
+object Spec {
+  class Info(
+    val runner: String, 
+    val usage: String,
+    val mainClass: String
+  )
+  object Info {
+    def apply(runner: String, help: String, mainClass: String): Info = new Info(runner, help, mainClass)
+  }
+  
+  class Accumulator[T: FromString]() {
+    private var _buf: List[T] = Nil
+
+    def convert(s: String)    = implicitly[FromString[T]] apply s
+    def apply(s: String): T   = returning(convert(s))(_buf +:= _)
+
+    lazy val get = _buf
+  }
+
+  class Choices[T: FromString](val xs: List[T]) {
+    def fs: FromString[T] = implicitly[FromString[T]]
+    def contains(x: T)    = xs contains x
+    override def toString = xs.mkString("{ ", ", ", " }")
+  }
+  
+  class EnvironmentVar(val name: String) {
+    override def toString = "${%s}" format name
+  }
+}
diff --git a/src/compiler/scala/tools/cmd/package.scala b/src/compiler/scala/tools/cmd/package.scala
new file mode 100644
index 0000000..3d5d06e
--- /dev/null
+++ b/src/compiler/scala/tools/cmd/package.scala
@@ -0,0 +1,28 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
+ * @author Paul Phillips
+ */
+ 
+package scala.tools
+
+package object cmd {  
+  def returning[T](x: T)(f: T => Unit): T = { f(x) ; x }
+
+  private[cmd] def debug(msg: String) = println(msg)
+  
+  def runAndExit(body: => Unit): Nothing = {
+    body    
+    System exit 0
+    error("unreachable")
+  }
+  
+  def toOpt(s: String)              = if (s startsWith "--") s else "--" + s
+  def fromOpt(s: String)            = s stripPrefix "--"
+  def toArgs(line: String)          = Parser tokenize line
+  def fromArgs(args: List[String])  = args mkString " "
+  
+  def stripQuotes(s: String) = {
+    def isQuotedBy(c: Char) = s.length > 0 && s.head == c && s.last == c
+    if (List('"', '\'') exists isQuotedBy) s.tail.init else s
+  }
+}
diff --git a/src/compiler/scala/tools/cmd/program/Scmp.scala b/src/compiler/scala/tools/cmd/program/Scmp.scala
new file mode 100644
index 0000000..b306bd0
--- /dev/null
+++ b/src/compiler/scala/tools/cmd/program/Scmp.scala
@@ -0,0 +1,59 @@
+/* NEST (New Scala Test)
+ * Copyright 2007-2010 LAMP/EPFL
+ * @author  Paul Phillips
+ */
+
+package scala.tools
+package cmd
+package program
+
+import nsc.io._
+
+object Scmp {
+  private val scmpUsage = """
+    |Usage: scmp [options] <cmd line>
+    |Example: scmp --p1 '-no-specialization -Ydebug' scalac src/library/scala/Function1.scala
+    |
+    |Note: the command line must start with a path to scalac.
+    |""".stripMargin
+  private val scmpOptions = List(
+    "p1" -> "options for the first run only",
+    "p2" -> "options for the second run only"
+  )
+  private val scmpInfo = Simple.scalaProgramInfo("scmp", scmpUsage)
+  lazy val ScmpSpec = Simple(scmpInfo, Nil, scmpOptions, x => returning(x)(_.onlyKnownOptions = false))
+  
+  def main(args0: Array[String]): Unit = {
+    if (args0.isEmpty)
+      return println(scmpUsage)
+      
+    val runner = ScmpSpec instance args0
+    import runner._
+    
+    val p1args = parsed.getOrElse("--p1", "")
+    val p2args = parsed.getOrElse("--p2", "")
+    
+    if (p1args.isEmpty && p2args.isEmpty)
+      return println("At least one of --p1 and --p2 must be given.")
+    if (residualArgs.isEmpty)
+      return println("There is no command to run.")
+    
+    def createCmd(extras: String) =
+      fromArgs(residualArgs.patch(1, toArgs(extras), 0))
+
+    def runCmd(cmd: String) = {
+      val output = Process(cmd, redirect = true).slurp()
+
+      returning(File.makeTemp())(_ writeAll output)
+    }
+
+    val cmds = List(p1args, p2args) map createCmd
+    println(cmds.mkString("Running command lines:\n  ", "\n  ", ""))
+    
+    val files = cmds map runCmd map (_.path)
+    val diff = Process("diff %s %s".format(files: _*)).slurp()
+    
+    if (diff.isEmpty) println("No differences.")
+    else println(diff)
+  }
+}
diff --git a/src/compiler/scala/tools/cmd/program/Simple.scala b/src/compiler/scala/tools/cmd/program/Simple.scala
new file mode 100644
index 0000000..7dc5cb7
--- /dev/null
+++ b/src/compiler/scala/tools/cmd/program/Simple.scala
@@ -0,0 +1,81 @@
+/* NEST (New Scala Test)
+ * Copyright 2007-2010 LAMP/EPFL
+ * @author  Paul Phillips
+ */
+
+package scala.tools
+package cmd
+package program
+
+import Spec.Info
+
+/** A boilerplate reducer for commands with simple requirements.  For examples,
+ *  see Scmp and Tokens in this package.
+ */
+object Simple {
+  type CommandLineTransform = SimpleCommandLine => SimpleCommandLine
+  
+  abstract class SimpleSpec(val programInfo: Info) extends Spec with Meta.StdOpts with Interpolation
+  
+  trait SimpleInstance extends SimpleSpec with Instance {
+    val parsed: CommandLine
+  }
+  
+  class SimpleReference(
+    programInfo: Info,
+    unary: List[(String, String)] = Nil, 
+    binary: List[(String, String)] = Nil,
+    postCreation: CommandLineTransform = null
+  ) extends SimpleSpec(programInfo) with Reference {
+
+    spec => 
+    
+    if (programInfo.usage != "") help(programInfo.usage)
+    unary foreach   { case (option, help) => option / help --? }
+    binary foreach  { case (option, help) => option / help --| }
+    
+    type ThisCommandLine = SimpleCommandLine
+  
+    def creator(args: List[String]) = new SimpleCommandLine(spec, args)
+    def instance(args: Array[String]): SimpleInstance = instance(args.toList)
+    def instance(args: List[String]): SimpleInstance =
+      new {
+        val parsed = spec(args: _*)
+      } with SimpleSpec(programInfo) with SimpleInstance {
+        lazy val referenceSpec = spec
+      }
+    
+    lazy val referenceSpec = spec    
+  }
+  
+  def apply(info: Info, unary: List[(String, String)], binary: List[(String, String)], postCreation: CommandLineTransform): SimpleReference = {
+    new SimpleReference(info, unary, binary, postCreation) {
+      override def creator(args: List[String]) = {
+        val obj = super.creator(args)
+        if (postCreation == null) obj
+        else postCreation(obj)
+      }
+    }
+  }
+  
+  def scalaProgramInfo(name: String, help: String) =
+    Spec.Info(name, help, "scala.tools.cmd.program." + name.capitalize)
+
+  /** You can't override a def with a var unless a setter exists.  We cleverly
+   *  sidestep this by mixing in a trait with dummy setters which will be
+   *  inaccessible due to the overriding var.
+   */
+  trait Ticket2338WontFixWorkaround {
+    def enforceArity_=(x: Boolean): Unit = error("unreachable")
+    def onlyKnownOptions_=(x: Boolean): Unit = error("unreachable")
+  }
+
+  /** Configurability simplicity achieved by turning defs into vars and letting
+   *  the spec creator apply a transformation.  This way there's no need to create
+   *  custom subclasses of CommandLine.
+   */
+  class SimpleCommandLine(spec: Reference, args: List[String]) extends CommandLine(spec, args) with Ticket2338WontFixWorkaround {
+    override var enforceArity: Boolean = true
+    override var onlyKnownOptions: Boolean = true
+  }
+}
diff --git a/src/compiler/scala/tools/cmd/program/Tokens.scala b/src/compiler/scala/tools/cmd/program/Tokens.scala
new file mode 100644
index 0000000..4f7fe03
--- /dev/null
+++ b/src/compiler/scala/tools/cmd/program/Tokens.scala
@@ -0,0 +1,100 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
+ * @author Paul Phillips
+ */
+
+package scala.tools
+package cmd
+package program
+
+import nsc._
+import util.Chars.char2uescape
+import io._
+import ast.parser.Tokens._
+
+/** Given paths on the command line, tokenizes any scala files found
+ *  and prints one token per line.
+ */
+object Tokens {
+  private val tokensUsage = "Usage: tokens [options] <path1 path2 ...>\n\nOptions:"
+  private val tokensUnary = List(
+    "verbose" -> "be more verbose",
+    "freq"    -> "combine token lists and sort by frequency",
+    "stats"   -> "output some stats"
+  )
+  private val tokensBinary = List(
+    "sliding" -> "print tokens in groups of given size"
+  )
+  private val tokensInfo = Simple.scalaProgramInfo("tokens", tokensUsage)
+  private lazy val TokensSpec = Simple(tokensInfo, tokensUnary, tokensBinary, null)
+  
+  def sanitize(x: Any): String = sanitize(x.toString)
+  def sanitize(str: String): String = str flatMap (x => if (x.isControl) char2uescape(x) else x.toString)
+  
+  def main(args0: Array[String]): Unit = {    
+    if (args0.isEmpty)
+      return println(TokensSpec.helpMsg)
+    
+    val runner = TokensSpec instance args0
+    import runner._
+    
+    val files = (residualArgs flatMap walk).distinct
+    if (parsed isSet "--verbose")
+      println("Tokenizing: " + (files map (_.name) mkString " "))
+    
+    if (parsed isSet "--stats")
+      println("Stats not yet implemented.")
+    
+    def raw = files flatMap fromScalaSource
+    def tokens: List[Any] =
+      if (parsed isSet "--sliding") raw sliding parsed("--sliding").toInt map (_ map sanitize mkString " ") toList
+      else raw
+    
+    def output =
+      if (parsed isSet "--freq")
+        (tokens groupBy (x => x) mapValues (_.length)).toList sortBy (-_._2) map (x => x._2 + " " + x._1)
+      else
+        tokens
+    
+    output foreach println
+  }
+  
+  def fromPaths(paths: String*): List[Any] =
+    (paths.toList flatMap walk).distinct flatMap fromScalaSource
+
+  /** Given a path, returns all .scala files underneath it.
+   */
+  private def walk(arg: String): List[File] = {
+    def traverse = Path(arg) ifDirectory (_.deepList()) getOrElse Iterator(File(arg))
+    
+    Path onlyFiles traverse filter (_ hasExtension "scala") toList
+  }
+  
+  /** Tokenizes a single scala file.
+   */
+  def fromScalaSource(file: Path): List[Any] = fromScalaSource(file.path)
+  def fromScalaSource(file: String): List[Any] = {
+    val global = new Global(new Settings())
+    import global._
+    import syntaxAnalyzer.{ UnitScanner, token2string }
+    
+    val in = new UnitScanner(new CompilationUnit(getSourceFile(file)))
+    in.init()
+
+    Iterator continually {
+      val token = in.token match {
+        case IDENTIFIER | BACKQUOTED_IDENT  => in.name
+        case CHARLIT | INTLIT | LONGLIT     => in.intVal
+        case DOUBLELIT | FLOATLIT           => in.floatVal
+        case STRINGLIT                      => "\"" + in.strVal + "\""
+        case SEMI | NEWLINE                 => ";"
+        case NEWLINES                       => ";;"
+        case COMMA                          => ","
+        case EOF                            => null
+        case x                              => token2string(x)
+      }
+      in.nextToken()
+      token
+    } takeWhile (_ != null) toList
+  }
+}
diff --git a/src/compiler/scala/tools/nsc/CompilationUnits.scala b/src/compiler/scala/tools/nsc/CompilationUnits.scala
index 3792edb..8713489 100644
--- a/src/compiler/scala/tools/nsc/CompilationUnits.scala
+++ b/src/compiler/scala/tools/nsc/CompilationUnits.scala
@@ -1,14 +1,12 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: CompilationUnits.scala 16894 2009-01-13 13:09:41Z cunei $
 
 package scala.tools.nsc
 
-import scala.tools.nsc.util.{FreshNameCreator,OffsetPosition,Position,SourceFile}
-import scala.tools.nsc.io.AbstractFile
-import scala.collection.mutable.{HashSet, HashMap}
+import util.{ FreshNameCreator,Position,NoPosition,SourceFile }
+import scala.collection.mutable.{ LinkedHashSet, HashSet, HashMap, ListBuffer }
 
 trait CompilationUnits { self: Global =>
 
@@ -16,16 +14,36 @@ trait CompilationUnits { self: Global =>
     * It typically corresponds to a single file of source code.  It includes
     * error-reporting hooks.  */
   class CompilationUnit(val source: SourceFile) extends CompilationUnitTrait {
+
     /** the fresh name creator */
     var fresh : FreshNameCreator = new FreshNameCreator.Default
 
     /** the content of the compilation unit in tree form */
     var body: Tree = EmptyTree
-
+    
+    /** representation for a source code comment, includes 
+     * '//' or '/*' '*/' in the value and the position
+     */
+    case class Comment(text: String, pos: Position)
+        
+    /** all comments found in this compilation unit */
+    val comments = new ListBuffer[Comment]
+
+//    def parseSettings() = {
+//      val argsmarker = "SCALAC_ARGS"
+//      if(comments nonEmpty) {
+//        val pragmas = comments find (_.text.startsWith("//#")) // only parse first one
+//        pragmas foreach { p =>
+//          val i = p.text.indexOf(argsmarker)
+//          if(i > 0)
+//        }
+//      }
+//    }
     /** Note: depends now contains toplevel classes.
      *  To get their sourcefiles, you need to dereference with .sourcefile
      */
     val depends = new HashSet[Symbol]
+
     /** so we can relink 
      */
     val defined = new HashSet[Symbol]
@@ -34,15 +52,22 @@ trait CompilationUnits { self: Global =>
      */
     val synthetics = new HashMap[Symbol, Tree]
 
-    /** used to track changes in a signature */
-    var pickleHash : Long = 0
+    /** things to check at end of compilation unit */
+    val toCheck = new ListBuffer[() => Unit]
 
     def position(pos: Int) = source.position(pos)
 
+    /** The position of a targeted type check
+     *  If this is different from NoPosition, the type checking
+     *  will stop once a tree that contains this position range
+     *  is fully attributed.
+     */
+    def targetPos: Position = NoPosition
+
     /** The icode representation of classes in this compilation unit.
      *  It is empty up to phase 'icode'.
      */
-    val icode: HashSet[icodes.IClass] = new HashSet
+    val icode: LinkedHashSet[icodes.IClass] = new LinkedHashSet
 
     def error(pos: Position, msg: String) =
       reporter.error(pos, msg)
@@ -61,12 +86,15 @@ trait CompilationUnits { self: Global =>
     def incompleteInputError(pos: Position, msg:String) =
       reporter.incompleteInputError(pos, msg) 
 
+    def comment(pos: Position, msg: String) =
+      reporter.comment(pos, msg)
+      
     /** Is this about a .java source file? */
     lazy val isJava = source.file.name.endsWith(".java")
     
     override def toString() = source.toString()
 
-    def clear() = {
+    def clear() {
       fresh = null
       body = null
       depends.clear
diff --git a/src/compiler/scala/tools/nsc/CompileClient.scala b/src/compiler/scala/tools/nsc/CompileClient.scala
index 4584a16..cec014a 100644
--- a/src/compiler/scala/tools/nsc/CompileClient.scala
+++ b/src/compiler/scala/tools/nsc/CompileClient.scala
@@ -1,12 +1,15 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: CompileClient.scala 17065 2009-02-09 15:30:56Z cunei $
 
 package scala.tools.nsc
 
-import java.io.{BufferedReader, File, InputStreamReader, PrintWriter}
+import java.io.{ BufferedReader, File, InputStreamReader, PrintWriter }
+import Properties.fileEndings
+import scala.tools.util.PathResolver
+import io.Path
+import util.ClassPath
 
 /** The client part of the fsc offline compiler.  Instead of compiling
  *  things itself, it send requests to a CompileServer.
@@ -14,13 +17,10 @@ import java.io.{BufferedReader, File, InputStreamReader, PrintWriter}
 class StandardCompileClient {
   def compileSocket: CompileSocket = CompileSocket  // todo: should be lazy val
 
-  val versionMsg = "Fast Scala Compiler " +
-    Properties.versionString + " -- " +
-    Properties.copyrightString
-
-  var verbose = false
-  var version = false
-  var shutdown = false
+  val versionMsg  = "Fast " + Properties.versionMsg
+  var verbose     = false
+  var version     = false
+  var shutdown    = false
 
   /** Convert a filename to an absolute path */
   def absFileName(path: String) = new File(path).getAbsolutePath()
@@ -28,22 +28,17 @@ class StandardCompileClient {
   /** Convert a sequence of filenames, separated by <code>File.pathSeparator</code>,
     * into absolute filenames.
     */
-  def absFileNames(paths: String) = {
-    val sep = File.pathSeparator
-    val pathsList = paths.split(sep).toList
-    pathsList.map(absFileName).mkString("", sep, "")
-  }
-
-  val fileEnding = Properties.fileEndingString
+  def absFileNames(paths: String) = ClassPath.map(paths, absFileName)
 
   protected def normalize(args: Array[String]): (String, String) = {
-     var i = 0
+    var i = 0
     val vmArgs = new StringBuilder
     var serverAdr = ""
+    
     while (i < args.length) {
       val arg = args(i)
-      if (fileEnding split ("\\|") exists (arg endsWith _)) {
-        args(i) = absFileName(arg)
+      if (fileEndings exists(arg endsWith _)) {
+        args(i) = Path(arg).toAbsolute.path
       } else if (arg startsWith "-J") {
         //see http://java.sun.com/j2se/1.5.0/docs/tooldocs/solaris/javac.html#J
         vmArgs append " "+arg.substring(2)
@@ -56,18 +51,17 @@ class StandardCompileClient {
         shutdown = true
       }
       i += 1
+      
       if (i < args.length) {
-        if (arg == "-classpath" ||
-            arg == "-sourcepath" ||
-            arg == "-bootclasspath" ||
-            arg == "-extdirs" ||
-            arg == "-d") {
-          args(i) = absFileNames(args(i))
-          i += 1
-        } else if (arg == "-server") {
-          serverAdr = args(i)
-          args(i-1) = ""
-          args(i) = ""
+        arg match {
+          case "-classpath" | "-sourcepath" | "-bootclasspath" | "-extdirs" | "-d"  =>
+            args(i) = PathResolver.makeAbsolute(args(i))
+            i += 1
+          case "-server"  =>
+            serverAdr = args(i)
+            args(i-1) = ""
+            args(i) = ""
+          case _          =>
         }
       }
     }
@@ -76,58 +70,51 @@ class StandardCompileClient {
 
   // used by class ant.FastScalac to skip exit statement in Ant.
   def main0(args0: Array[String]): Int = {
-    val args =
-      if (args0.exists(arg => arg == "-d"))
-        args0
-      else
-        ("-d" :: "." :: args0.toList).toArray
-
+    val args = if (args0 contains "-d") args0 else Array("-d", ".") ++ args0
     val (vmArgs, serverAdr) = normalize(args)
+    
     if (version) {
-      Console.println(versionMsg)
+      Console println versionMsg
       return 0
     }
     if (verbose) {
-      Console.println("[Server arguments: " + args.mkString("", " ", "]"))
-      Console.println("[VM arguments: " + vmArgs + "]")
+      Console println args.mkString("[Server arguments: ", " ", "]")
+      Console println "[VM arguments: %s]".format(vmArgs)
     }
-    val socket = if (serverAdr == "") compileSocket.getOrCreateSocket(vmArgs, !shutdown)
-                 else compileSocket.getSocket(serverAdr)
-    var sawerror = false
-    if (socket eq null) {
-      if (shutdown) {
-        Console.println("[No compilation server running.]")
-      } else {
-        Console.println("Compilation failed.") 
-        sawerror = true
-      }
-    } else {
-      val out = new PrintWriter(socket.getOutputStream(), true)
-      val in = new BufferedReader(new InputStreamReader(socket.getInputStream()))
-      out.println(compileSocket.getPassword(socket.getPort()))
-      out.println(args.mkString("", "\0", ""))
-      var fromServer = in.readLine()
-      while (fromServer ne null) {
-        if (compileSocket.errorPattern.matcher(fromServer).matches)
-          sawerror = true
-        Console.println(fromServer)
-        fromServer = in.readLine()
-      }
-      in.close()
-      out.close()
-      socket.close()
+    val socket =
+      if (serverAdr == "") compileSocket.getOrCreateSocket(vmArgs, !shutdown)
+      else Some(compileSocket.getSocket(serverAdr))
+    
+    val sawerror: Boolean = socket match {
+      case None =>
+        val msg = if (shutdown) "[No compilation server running.]" else "Compilation failed."
+        Console println msg
+        !shutdown
+
+      case Some(sock) =>
+        var wasError = false
+
+        sock.applyReaderAndWriter { (in, out) =>
+          out println compileSocket.getPassword(sock.getPort())
+          out println args.mkString("\0")
+          def loop: Unit = in.readLine() match {
+            case null       => ()
+            case fromServer =>
+              if (compileSocket.errorPattern matcher fromServer matches)
+                wasError = true
+            
+              Console println fromServer
+              loop
+          }
+          loop
+        }
+        wasError
     }
     if (sawerror) 1 else 0
   }
 
-  def main(args: Array[String]) {
-    try {
-      val status = main0(args)
-      exit(status)
-    } catch {
-      case e: Exception => exit(1)
-    }
-  }
+  def main(args: Array[String]): Unit =
+    exit(try main0(args) catch { case e: Exception => 1 })
 }
 
 
diff --git a/src/compiler/scala/tools/nsc/CompileServer.scala b/src/compiler/scala/tools/nsc/CompileServer.scala
index 76db2c2..d6f9c3c 100644
--- a/src/compiler/scala/tools/nsc/CompileServer.scala
+++ b/src/compiler/scala/tools/nsc/CompileServer.scala
@@ -1,16 +1,13 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: CompileServer.scala 16894 2009-01-13 13:09:41Z cunei $
 
 package scala.tools.nsc
 
-import java.io.{BufferedOutputStream, File, FileOutputStream, PrintStream}
-import java.lang.{Runtime, System, Thread}
+import java.io.{ BufferedOutputStream, FileOutputStream, PrintStream, File => JFile }
+import io.File
 
-import scala.concurrent.ops.spawn
-import scala.tools.nsc.doc.{DocDriver => DocGenerator}
 import scala.tools.nsc.reporters.{Reporter, ConsoleReporter}
 import scala.tools.nsc.util.FakePos //Position
 import scala.tools.util.SocketServer
@@ -23,7 +20,8 @@ import scala.tools.util.SocketServer
  *  @author Martin Odersky
  *  @version 1.0
  */
-class StandardCompileServer extends SocketServer {
+class StandardCompileServer extends SocketServer
+{
   def compileSocket: CompileSocket = CompileSocket // todo: make this a lazy val
 
   val versionMsg = "Fast Scala compiler " +
@@ -45,10 +43,10 @@ class StandardCompileServer extends SocketServer {
   }
 
   private val runtime = Runtime.getRuntime()
+  import runtime.{ totalMemory, freeMemory, maxMemory }
 
   var reporter: ConsoleReporter = _
 
-
   /** Create a new compiler instance */
   def newGlobal(settings: Settings, reporter: Reporter) =
     new Global(settings, reporter) {
@@ -56,97 +54,100 @@ class StandardCompileServer extends SocketServer {
     }
 
   override def timeout() {
-    if (!compileSocket.portFile(port).exists())
+    if (!compileSocket.portFile(port).exists)    
       fatal("port file no longer exists; skipping cleanup")
   }
+  
+  def printMemoryStats() {
+    System.out.println("New session, total memory = %s, max memory = %s, free memory = %s".format(
+      totalMemory, maxMemory, freeMemory))
+    System.out.flush()
+  }
+  
+  def isMemoryFullEnough() = {
+    runtime.gc()
+    (totalMemory - freeMemory).toDouble / maxMemory.toDouble > MaxCharge
+  }
 
-  protected def newOfflineCompilerCommand(
-    arguments: List[String],
-    settings: Settings,
-    error: String => Unit, 
-    interactive: Boolean) 
-  = new OfflineCompilerCommand(arguments, settings, error, interactive)
+  protected def newOfflineCompilerCommand(arguments: List[String], settings: Settings) =
+    new OfflineCompilerCommand(arguments, settings)
 
   def session() {
-    System.out.println("New session" +
-                       ", total memory = "+ runtime.totalMemory() +
-                       ", max memory = " + runtime.maxMemory() +
-                       ", free memory = " + runtime.freeMemory)
-    System.out.flush()
-    val password = compileSocket.getPassword(port)
+    printMemoryStats()
+    val password = compileSocket getPassword port
     val guessedPassword = in.readLine()
     val input = in.readLine()
-    if ((input ne null) && password == guessedPassword) {
-      val args = input.split("\0",-1).toList
-      if (args contains "-shutdown") {
-        out.println("[Compile server exited]")
-        shutDown = true
-        return
+    
+    if (input == null || password != guessedPassword)
+      return
+    
+    val args = input.split("\0", -1).toList
+    if (args contains "-shutdown") {
+      out.println("[Compile server exited]")
+      shutDown = true
+      return
+    }
+    if (args contains "-reset") {
+      out.println("[Compile server was reset]")
+      compiler = null
+      return
+    }
+    
+    def error(msg: String) {
+      out.println(FakePos("fsc"), msg + "\n  fsc -help  gives more information")
+    }
+    
+    val command = newOfflineCompilerCommand(args, new Settings(error))
+    
+    reporter = new ConsoleReporter(command.settings, in, out) {
+      // disable prompts, so that compile server cannot block
+      override def displayPrompt = ()
+    }
+    
+    if (command.shouldStopWithInfo)
+      reporter.info(null, command.getInfoMessage(newGlobal(command.settings, reporter)), true)
+    else if (command.files.isEmpty)
+      reporter.info(null, command.usageMsg, true)
+    else {
+      try {
+        if (compiler != null && command.settings == compiler.settings) {
+          compiler.settings = command.settings
+          compiler.reporter = reporter
+        }
+        else {
+          if (args contains "-verbose") {
+            val reason = if (compiler == null) "compiler is null" else "settings not equal"
+            out.println("[Starting new compile server instance because %s]".format(reason))
+          }
+          compiler = newGlobal(command.settings, reporter)
+        }
+        val c = compiler
+        val run = new c.Run()
+        run compile command.files
       }
-      if (args contains "-reset") {
-        out.println("[Compile server was reset]")
+      catch {
+        case ex @ FatalError(msg) =>
+          if (command.settings.debug.value)
+            ex.printStackTrace(out);
+        reporter.error(null, "fatal error: " + msg)
         compiler = null
-        return
-      }
-      def error(msg: String) {
-        out.println(/*new Position*/ FakePos("fsc"),
-                    msg + "\n  fsc -help  gives more information")
-      }
-      val command = newOfflineCompilerCommand(args, new Settings(error), error, false)
-      
-      reporter = new ConsoleReporter(command.settings, in, out) {
-        // disable prompts, so that compile server cannot block
-        override def displayPrompt = ()
+        case ex: Throwable =>
+          ex.printStackTrace(out);
+        reporter.error(null, "fatal error (server aborted): " + ex.getMessage())
+        shutDown = true
       }
-      
-      if (command.shouldStopWithInfo) {
-        reporter.info(null,
-                        command.getInfoMessage(newGlobal(command.settings, reporter)), true)
-        } else if (command.files.isEmpty)
-            reporter.info(null, command.usageMsg, true)
-          else {
-            try {
-              if ((compiler ne null) && settingsAreCompatible(command.settings, compiler.settings)) {
-                compiler.settings = command.settings
-                compiler.reporter = reporter
-              } else {
-                if (args contains "-verbose")
-                  out.println("[Starting new compile server instance]")
-                compiler = newGlobal(command.settings, reporter)
-              }
-              val c = compiler
-              val run = new c.Run
-              run compile command.files
-            } catch {
-              case ex @ FatalError(msg) =>
-                if (command.settings.debug.value)
-                  ex.printStackTrace(out);
-              reporter.error(null, "fatal error: " + msg)
-              compiler = null
-              case ex: Throwable =>
-                ex.printStackTrace(out);
-              reporter.error(null, "fatal error (server aborted): " + ex.getMessage())
-              shutDown = true
-            }
-            reporter.printSummary()
-            runtime.gc()
-            if ((runtime.totalMemory() - runtime.freeMemory()).toDouble / 
-                runtime.maxMemory().toDouble > MaxCharge) compiler = null
-          }
     }
+    
+    reporter.printSummary()
+    if (isMemoryFullEnough)
+      compiler = null
   }
   
   /** A directory holding redirected output */
-  private val redirectDir = new File(compileSocket.tmpDir, "output-redirects")
-  redirectDir.mkdirs
-
-  private def redirect(setter: PrintStream => Unit, filename: String) {
-    setter(
-      new PrintStream(
-        new BufferedOutputStream(
-          new FileOutputStream(
-            new File(redirectDir, filename)))))
-  }
+  private val redirectDir = (compileSocket.tmpDir / "output-redirects").createDirectory()
+
+  private def redirect(setter: PrintStream => Unit, filename: String): Unit =
+    setter(new PrintStream((redirectDir / filename).createFile().bufferedOutput()))
 
   def main(args: Array[String]) {
     redirect(System.setOut, "scala-compile-server-out.log")
diff --git a/src/compiler/scala/tools/nsc/CompileSocket.scala b/src/compiler/scala/tools/nsc/CompileSocket.scala
index e1e33bf..160dbd4 100644
--- a/src/compiler/scala/tools/nsc/CompileSocket.scala
+++ b/src/compiler/scala/tools/nsc/CompileSocket.scala
@@ -1,17 +1,19 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: CompileSocket.scala 17065 2009-02-09 15:30:56Z cunei $
 
 package scala.tools.nsc
 
-import java.lang.{Thread, System, Runtime}
-import java.lang.NumberFormatException
-import java.io.{File, IOException, PrintWriter, FileOutputStream}
-import java.io.{BufferedReader, FileReader}
+import java.io.{ IOException, FileNotFoundException, PrintWriter, FileOutputStream }
+import java.io.{ BufferedReader, FileReader }
 import java.util.regex.Pattern
 import java.net._
+import java.security.SecureRandom
+
+import io.{ File, Path, Process, Socket }
+import scala.util.control.Exception.catching
+import scala.tools.util.StringOps.splitWhere
 
 /** This class manages sockets for the fsc offline compiler.  */
 class CompileSocket {
@@ -20,22 +22,17 @@ class CompileSocket {
   /** The prefix of the port identification file, which is followed
    *  by the port number.
    */
-  protected def dirName = "scalac-compile-server-port" //todo: lazy val
-
-  protected def cmdName = Properties.cmdName //todo: lazy val
+  protected lazy val dirName = "scalac-compile-server-port"
+  protected lazy val cmdName = Properties.scalaCmd
 
   /** The vm part of the command to start a new scala compile server */
-  protected val vmCommand =
-    Properties.scalaHome match {
-      case null =>
-        cmdName
-      case dirname =>
-        val trial = new File(new File(dirname, "bin"), cmdName)
-        if (trial.canRead)
-          trial.getPath
-        else
-          cmdName
-    }
+  protected val vmCommand = Properties.scalaHome match {
+    case ""       => cmdName
+    case dirname  =>
+      val trial = File(dirname) / "bin" / cmdName
+      if (trial.canRead) trial.path
+      else cmdName
+  }
 
   /** The class name of the scala compile server */
   protected val serverClass = "scala.tools.nsc.CompileServer"
@@ -44,7 +41,7 @@ class CompileSocket {
   val errorRegex = ".*(errors? found|don't know|bad option).*"
     
   /** A Pattern object for checking compiler output for errors */
-  val errorPattern = Pattern.compile(errorRegex)
+  val errorPattern = Pattern compile errorRegex
 
   protected def error(msg: String) = System.err.println(msg)
     
@@ -58,54 +55,18 @@ class CompileSocket {
 
   /** A temporary directory to use */
   val tmpDir = {
-    val totry = List(
-        ("scala.home", List("var", "scala-devel")),
-        ("user.home", List("tmp")),
-        ("java.io.tmpdir", Nil))
-
-    /** Expand a property-extensions pair into a complete File object */
-    def expand(trial: (String, List[String])): Option[File] = {
-      val (topdirProp, extensions) = trial
-      val topdir = System.getProperty(topdirProp)
-      if (topdir eq null)
-        return None
-
-      val fulldir =
-        extensions.foldLeft[File](new File(topdir))(
-            (dir,ext) => new File(dir, ext))
-
-      Some(fulldir)
-    }
-
-    /** Try to create directory f, and then see if it can
-     *  be written into. */
-    def isDirWritable(f: File): Boolean = {
-      f.mkdirs()
-      f.isDirectory && f.canWrite
-    }
-
-    val potentials =
-      for {
-        trial <- totry
-        val expanded = expand(trial)
-        if !expanded.isEmpty
-        if isDirWritable(expanded.get)
-      }
-      yield expanded.get
-
-    if (potentials.isEmpty)
-      fatal("Could not find a directory for temporary files")
-    else {
-      val d = potentials.head
-      d.mkdirs
-      info("[Temp directory: " + d + "]")
-      d
+    val udir  = Option(Properties.userName) getOrElse "shared"
+    val f     = (Path(Properties.tmpDir) / "scala-devel" / udir).createDirectory()
+    
+    if (f.isDirectory && f.canWrite) {
+      info("[Temp directory: " + f + "]")
+      f
     }
+    else fatal("Could not find a directory for temporary files")
   }
   
   /* A directory holding port identification files */
-  val portsDir =  new File(tmpDir, dirName)
-  portsDir.mkdirs
+  val portsDir = (tmpDir / dirName).createDirectory()
 
   /** Maximum number of polls for an available port */
   private val MaxAttempts = 100
@@ -116,44 +77,29 @@ class CompileSocket {
   /** The command which starts the compile server, given vm arguments.
     *
     *  @param vmArgs  the argument string to be passed to the java or scala command
-    *                 the string must be either empty or start with a ' '.
     */
-  private def serverCommand(vmArgs: String): String =
-    vmCommand + vmArgs + " " + serverClass
+  private def serverCommand(vmArgs: Seq[String]): Seq[String] =
+    Seq(vmCommand) ++ vmArgs ++ Seq(serverClass) filterNot (_ == "")
 
   /** Start a new server; returns true iff it succeeds */
   private def startNewServer(vmArgs: String) {
-    val cmd = serverCommand(vmArgs)
-    info("[Executed command: " + cmd + "]")
-    try {
-      Runtime.getRuntime().exec(cmd)
-//      val exitVal = proc.waitFor()
-//      info("[Exit value: " + exitVal + "]")
-    } catch {
-      case ex: IOException =>
-        fatal("Cannot start compilation daemon." +
-              "\ntried command: " + cmd)
+    val cmd = serverCommand(vmArgs split " " toSeq)
+    info("[Executed command: %s]" format cmd)
+    try Process exec cmd catch {
+      case ex: IOException => fatal("Cannot start compilation daemon.\ntried command: %s" format cmd)
     }
   }
 
   /** The port identification file */
-  def portFile(port: Int) = new File(portsDir, port.toString())
+  def portFile(port: Int) = portsDir / File(port.toString)
 
   /** Poll for a server port number; return -1 if none exists yet */
-  private def pollPort(): Int = {
-    val hits = portsDir.listFiles()
-    if (hits.length == 0) -1
-    else
-      try {
-        for (i <- 1 until hits.length) hits(i).delete()
-        hits(0).getName.toInt
-      } catch {
-        case ex: NumberFormatException =>
-          fatal(ex.toString() +
-                "\nbad file in temp directory: " +
-                hits(0).getAbsolutePath() +
-                "\nplease remove the file and try again")
-      }
+  private def pollPort(): Int = portsDir.list match {
+    case it if !it.hasNext  => -1
+    case it                 =>
+      val ret = it.next.name.toInt
+      it foreach (_.delete())
+      ret
   }
 
   /** Get the port number to which a scala compile server is connected;
@@ -165,6 +111,7 @@ class CompileSocket {
 
     if (port < 0)
       startNewServer(vmArgs)
+      
     while (port < 0 && attempts < MaxAttempts) {
       attempts += 1
       Thread.sleep(sleepTime)
@@ -178,94 +125,74 @@ class CompileSocket {
 
   /** Set the port number to which a scala compile server is connected */
   def setPort(port: Int) {
-    try {
-      val f = new PrintWriter(new FileOutputStream(portFile(port)))
-      f.println(new java.security.SecureRandom().nextInt.toString)
-      f.close()
-    } catch {
-      case ex: /*FileNotFound+Security*/Exception =>
-        fatal("Cannot create file: " +
-              portFile(port).getAbsolutePath())
+    val file    = portFile(port)
+    val secret  = new SecureRandom().nextInt.toString
+    
+    try file writeAll secret catch { 
+      case e @ (_: FileNotFoundException | _: SecurityException) =>
+        fatal("Cannot create file: %s".format(file.path))
     }
   }
 
   /** Delete the port number to which a scala compile server was connected */
-  def deletePort(port: Int) { portFile(port).delete() }
+  def deletePort(port: Int) = portFile(port).delete()
 
   /** Get a socket connected to a daemon.  If create is true, then
-    * create a new daemon if necessary.  Returns null if the connection
+    * create a new daemon if necessary.  Returns None if the connection
     * cannot be established.
     */
-  def getOrCreateSocket(vmArgs: String, create: Boolean): Socket = {
-    val nAttempts = 49  // try for about 5 seconds
-    def getsock(attempts: Int): Socket =
-      if (attempts == 0) {
-        error("Unable to establish connection to compilation daemon")
-        null
-      } else {
-        val port = if(create) getPort(vmArgs) else pollPort()
-        if(port < 0) return null
-        val hostAdr = InetAddress.getLocalHost()
-        try {
-          val result = new Socket(hostAdr, port)
-          info("[Connected to compilation daemon at port " + port + "]")
-          result
-        } catch {
-          case e: /*IO+Security*/Exception =>
-            info(e.toString)
-            info("[Connecting to compilation daemon at port "  +
-                 port + " failed; re-trying...]")
+  def getOrCreateSocket(vmArgs: String, create: Boolean = true): Option[Socket] = {
+    // try for 5 seconds
+    val retryDelay = 100
+    val maxAttempts = (5 * 1000) / retryDelay
+    
+    def getsock(attempts: Int): Option[Socket] = attempts match {
+      case 0    => error("Unable to establish connection to compilation daemon") ; None
+      case num  =>
+        val port = if (create) getPort(vmArgs) else pollPort()
+        if (port < 0) return None
+    
+        Socket(InetAddress.getLocalHost(), port).either match {
+          case Right(socket)  =>
+            info("[Connected to compilation daemon at port %d]" format port)
+            Some(socket)
+          case Left(err)      =>
+            info(err.toString)
+            info("[Connecting to compilation daemon at port %d failed; re-trying...]" format port)
             
             if (attempts % 2 == 0) 
-              portFile(port).delete // 50% chance to stop trying on this port
-              
-            Thread.sleep(100) // delay before retrying
+              deletePort(port)      // 50% chance to stop trying on this port
             
+            Thread sleep retryDelay // delay before retrying
             getsock(attempts - 1)
         }
-      }
-    getsock(nAttempts)
-  }
-  
-  /** Same as getOrCreateSocket(vmArgs, true). */
-  def getOrCreateSocket(vmArgs: String): Socket =
-    getOrCreateSocket(vmArgs, true)
-
-  def getSocket(serverAdr: String): Socket = {
-    val cpos = serverAdr indexOf ':'
-    if (cpos < 0)
-      fatal("Malformed server address: " + serverAdr + "; exiting")
-    else {
-      val hostName = serverAdr.substring(0, cpos)
-      val port = try {
-        serverAdr.substring(cpos+1).toInt
-      } catch {
-        case ex: Throwable =>
-          fatal("Malformed server address: " + serverAdr + "; exiting")
-      }
-      getSocket(hostName, port)
     }
+    getsock(maxAttempts)
   }
 
+  // XXX way past time for this to be central
+  def parseInt(x: String): Option[Int] =
+    try   { Some(x.toInt) }
+    catch { case _: NumberFormatException => None }
+  
+  def getSocket(serverAdr: String): Socket = (
+    for ((name, portStr) <- splitWhere(serverAdr, _ == ':', true) ; port <- parseInt(portStr)) yield
+      getSocket(name, port)
+  ) getOrElse fatal("Malformed server address: %s; exiting" format serverAdr)
+
   def getSocket(hostName: String, port: Int): Socket =
-    try {
-      new Socket(hostName, port)
-    } catch {
-      case e: /*IO+Security*/Exception =>
-        fatal("Unable to establish connection to server " +
-              hostName + ":" + port + "; exiting")
-    }
+    Socket(hostName, port).opt getOrElse fatal("Unable to establish connection to server %s:%d; exiting".format(hostName, port))
 
   def getPassword(port: Int): String = {
-    val ff=portFile(port)
-    val f = new BufferedReader(new FileReader(ff))
+    val ff  = portFile(port)
+    val f   = ff.bufferedReader()
+
     // allow some time for the server to start up
-    var retry=50
-    while (ff.length()==0 && retry>0) {
-      Thread.sleep(100)
-      retry-=1
+    def check = {
+      Thread sleep 100
+      ff.length
     }
-    if (ff.length()==0) {
+    if (Iterator continually check take 50 find (_ > 0) isEmpty) {
       ff.delete()
       fatal("Unable to establish connection to server.")
     }
diff --git a/src/compiler/scala/tools/nsc/CompilerCommand.scala b/src/compiler/scala/tools/nsc/CompilerCommand.scala
index 09cb599..71c400e 100644
--- a/src/compiler/scala/tools/nsc/CompilerCommand.scala
+++ b/src/compiler/scala/tools/nsc/CompilerCommand.scala
@@ -1,148 +1,93 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: CompilerCommand.scala 16919 2009-01-14 14:53:47Z rytz $
 
 package scala.tools.nsc
 
+import java.io.IOException
+import scala.collection.mutable.ListBuffer
+import io.File
 
 /** A class representing command line info for scalac */
-class CompilerCommand(arguments: List[String], val settings: Settings,
-                      error: String => Unit, interactive: Boolean) {
+class CompilerCommand(arguments: List[String], val settings: Settings) {
+  def this(arguments: List[String], error: String => Unit) = this(arguments, new Settings(error))
+  type Setting = Settings#Setting
 
-  private var fs: List[String] = List()
-
-  /** All files to compile */
-  def files: List[String] = fs.reverse
+  /** file extensions of files that the compiler can process */
+  lazy val fileEndings = Properties.fileEndings
 
   /** The name of the command */
-  val cmdName = "scalac"
-
-  /** The file extension of files that the compiler can process */
-  lazy val fileEnding = Properties.fileEndingString
+  def cmdName = "scalac"
+  private def isFsc = cmdName == "fsc"
 
   private val helpSyntaxColumnWidth: Int =
-    Iterable.max(settings.allSettings map (_.helpSyntax.length))
-
-  private def format(s: String): String = {
-    val buf = new StringBuilder(s)
-    var i = s.length
-    while (i < helpSyntaxColumnWidth) { buf.append(' '); i += 1 }
-    buf.toString()
-  }
-
-  /** A message explaining usage and options */
-  def usageMsg: String = {
-    settings.allSettings
-      .filter(_.isStandard)
-      .map(setting =>
-           format(setting.helpSyntax) + "  " + setting.helpDescription)
-      .mkString("Usage: " + cmdName + " <options> <source files>\n" +
-                "where possible standard options include:\n  ",
-                "\n  ",
-                "\n")
-  }
-
-  /** A message explaining usage and options */
-  def xusageMsg: String = {
-    settings.allSettings
-      .filter(_.isAdvanced)
-      .map(setting =>
-           format(setting.helpSyntax) + "  " + setting.helpDescription)
-      .mkString("Possible advanced options include:\n  ",
-                "\n  ",
-                "\n")
-  }
-
-  /** A message explaining usage and options */
-  def yusageMsg: String = {
-    settings.allSettings
-      .filter(_.isPrivate) 
-      .map(setting =>
-           format(setting.helpSyntax) + "  " + setting.helpDescription)
-      .mkString("Possible private options include:\n  ",
-                "\n  ",
-                "\n")
-  }
-
-  // If any of these settings is set, the compiler shouldn't
-  // start; an informative message of some sort
-  // should be printed instead.
+    (settings.visibleSettings map (_.helpSyntax.length)) max
+
+  private def format(s: String): String =
+    if (s.length >= helpSyntaxColumnWidth) s
+    else s + (" " * (helpSyntaxColumnWidth - s.length))
+
+  /** Creates a help message for a subset of options based on cond */
+  def createUsageMsg(label: String, cond: (Setting) => Boolean): String =
+    settings.visibleSettings .
+      filter(cond) .
+      map(s => format(s.helpSyntax) + "  " + s.helpDescription) .
+      toList.sorted.mkString("Usage: %s <options> <source files>\n%s options include:\n  " .
+        format(cmdName, label), "\n  ", "\n")
+
+  /** Messages explaining usage and options */
+  def usageMsg    = createUsageMsg("where possible standard", _.isStandard)
+  def fscUsageMsg = createUsageMsg("where possible standard", ( st => st.isStandard || st.name == "-shutdown"))
+  def xusageMsg   = createUsageMsg("Possible advanced", _.isAdvanced)
+  def yusageMsg   = createUsageMsg("Possible private", _.isPrivate)
+
+  // If any of these settings is set, the compiler shouldn't start;
+  // an informative message of some sort should be printed instead.
   // (note: do not add "files.isEmpty" do this list)
-  val stopSettings=List[(()=>Boolean,
-                         (Global)=>String)](
-    (()=> settings.help.value, compiler =>
-      usageMsg + compiler.pluginOptionsHelp
-    ),
-    (()=> settings.Xhelp.value, compiler =>
-      xusageMsg
-    ),
-    (()=> settings.Yhelp.value, compiler =>
-      yusageMsg
-    ),
-    (()=> settings.showPlugins.value, compiler =>
-      compiler.pluginDescriptions
-    ),
-    (()=> settings.showPhases.value, compiler =>
-      compiler.phaseDescriptions
-    )
+  val stopSettings = List[(() => Boolean, (Global) => String)](
+    ((() => (settings.help.value _)() && isFsc), fscUsageMsg + _.pluginOptionsHelp),
+    (settings.help.value _,         usageMsg + _.pluginOptionsHelp),
+    (settings.Xhelp.value _,        _ => xusageMsg),
+    (settings.Yhelp.value _,        _ => yusageMsg),
+    (settings.showPlugins.value _,  _.pluginDescriptions),
+    (settings.showPhases.value _,   _.phaseDescriptions)
   )
+  def shouldStopWithInfo: Boolean = stopSettings exists { _._1() }
 
-  def shouldStopWithInfo = stopSettings.exists({pair => (pair._1)()})
-  def getInfoMessage(compiler:Global) =
-    stopSettings.find({pair => (pair._1)()}) match {
-      case Some((test,getMessage)) => getMessage(compiler)
+  def getInfoMessage(compiler: Global): String =
+    stopSettings.find(pair => (pair._1)()) match {
+      case Some((test, getMessage)) => getMessage(compiler)
       case None => ""
     }
-
-
-  /** Whether the command was processed okay */
-  var ok = true
-
-  /** Process the arguments and update the settings accordingly.
-      This method is called only once, during initialization.  */
-  protected def processArguments() {
-    // initialization
-    var args = arguments
-
-    while (!args.isEmpty && ok) {
-      if (args.head startsWith "@") {
-        try {
-          args = util.ArgumentsExpander.expandArg(args.head) ::: args.tail
-        } catch {
-          case ex: java.io.IOException =>
-            error(ex.getMessage())
-            ok = false
-        }
-      } else if (args.head startsWith "-") {
-	if (interactive) {
-          error("no options can be given in interactive mode")
-          ok = false
-        } else {
-          val args0 = args
-          for (setting <- settings.allSettings)
-            if (args eq args0)
-              args = setting.tryToSet(args)
-
-          if (args eq args0) {
-            error("bad option: '" + args.head + "'")
-            ok = false
-          }
-        }
-      } else if ((settings.script.value != "") || 
-                 (fileEnding.split("\\|") exists (args.head.endsWith(_)))) {
-        fs = args.head :: fs
-        args = args.tail
-      } else if (args.head.length == 0) {//quick fix [martin: for what?]
-        args = args.tail
-      } else {
-        error("don't know what to do with " + args.head)
-        ok = false
-      }
+  
+  /**
+   * Expands all arguments starting with @ to the contents of the
+   * file named like each argument.
+   */
+  def expandArg(arg: String): List[String] = {
+    def stripComment(s: String) = s takeWhile (_ != '#')
+    val file = File(arg stripPrefix "@")
+    if (!file.exists)
+      throw new java.io.FileNotFoundException("argument file %s could not be found" format file.name)
+    
+    settings splitParams (file.lines() map stripComment mkString " ")
+  }
+  
+  // override this if you don't want arguments processed here
+  def shouldProcessArguments: Boolean = true
+  
+  def processArguments: (Boolean, List[String]) = {
+    // expand out @filename to the contents of that filename
+    val expandedArguments = arguments flatMap {
+      case x if x startsWith "@"  => expandArg(x)
+      case x                      => List(x)
     }
-    ok &&= settings.checkDependencies
+  
+    settings.processArguments(expandedArguments, true)
   }
-
-  processArguments()
+  
+  val (ok, files) = 
+    if (shouldProcessArguments) processArguments
+    else (true, Nil)
 }
diff --git a/src/compiler/scala/tools/nsc/CompilerRun.scala b/src/compiler/scala/tools/nsc/CompilerRun.scala
index 75a49c5..9cac12d 100644
--- a/src/compiler/scala/tools/nsc/CompilerRun.scala
+++ b/src/compiler/scala/tools/nsc/CompilerRun.scala
@@ -1,8 +1,7 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: CompilerRun.scala 16894 2009-01-13 13:09:41Z cunei $
 
 package scala.tools.nsc
 
diff --git a/src/compiler/scala/tools/nsc/ConsoleWriter.scala b/src/compiler/scala/tools/nsc/ConsoleWriter.scala
index d034ad2..8c62965 100644
--- a/src/compiler/scala/tools/nsc/ConsoleWriter.scala
+++ b/src/compiler/scala/tools/nsc/ConsoleWriter.scala
@@ -1,8 +1,7 @@
 /* NSC -- new Scala compiler
- * Copyright 2006-2009 LAMP/EPFL
+ * Copyright 2006-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: ConsoleWriter.scala 16894 2009-01-13 13:09:41Z cunei $
 
 package scala.tools.nsc
 
@@ -20,7 +19,7 @@ class ConsoleWriter extends Writer {
   
   def write(cbuf: Array[Char], off: Int, len: Int) {
     if (len > 0)
-      write(new String(cbuf.subArray(off, off+len)))
+      write(new String(cbuf.slice(off, off+len)))
   }
 
   override def write(str: String) { Console.print(str) }
diff --git a/src/compiler/scala/tools/nsc/EvalLoop.scala b/src/compiler/scala/tools/nsc/EvalLoop.scala
index 973360c..d8aa779 100644
--- a/src/compiler/scala/tools/nsc/EvalLoop.scala
+++ b/src/compiler/scala/tools/nsc/EvalLoop.scala
@@ -1,27 +1,25 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: EvalLoop.scala 16881 2009-01-09 16:28:11Z cunei $
 
 package scala.tools.nsc
 
-trait EvalLoop {
+import annotation.tailrec
+import java.io.EOFException
 
+trait EvalLoop {
   def prompt: String
 
   def loop(action: (String) => Unit) {
-    Console.print(prompt)
-    try {
-      val line = Console.readLine
-      if (line.length() > 0) {
+    @tailrec def inner() {
+      Console.print(prompt)
+      val line = try Console.readLine catch { case _: EOFException => null }
+      if (line != null && line != "") {
         action(line)
-        loop(action)
+        inner()
       }
     }
-    catch {
-      case _: java.io.EOFException => //nop
-    }
+    inner()
   }
-
 }
diff --git a/src/compiler/scala/tools/nsc/FatalError.scala b/src/compiler/scala/tools/nsc/FatalError.scala
index 925cbac..145eb4c 100644
--- a/src/compiler/scala/tools/nsc/FatalError.scala
+++ b/src/compiler/scala/tools/nsc/FatalError.scala
@@ -1,9 +1,19 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: FatalError.scala 16894 2009-01-13 13:09:41Z cunei $
 
 package scala.tools.nsc
 
-case class FatalError(msg: String) extends Exception(msg)
+import scala.util.control.ControlThrowable
+
+case class FatalError(msg: String) extends Throwable(msg)
+
+class MissingRequirementError(val req: String) extends FatalError(req + " not found.")
+
+object MissingRequirementError {
+  def unapply(x: Throwable) = x match {
+    case x: MissingRequirementError => Some(x.req)
+    case _                          => None
+  }
+}
diff --git a/src/compiler/scala/tools/nsc/GenericRunnerCommand.scala b/src/compiler/scala/tools/nsc/GenericRunnerCommand.scala
index b9cd2c7..29b8395 100644
--- a/src/compiler/scala/tools/nsc/GenericRunnerCommand.scala
+++ b/src/compiler/scala/tools/nsc/GenericRunnerCommand.scala
@@ -3,78 +3,59 @@
  * @author  Lex Spoon
  */
 
-// $Id: GenericRunnerCommand.scala 15427 2008-06-24 12:45:25Z odersky $
 
 package scala.tools.nsc
 
 /** A command for ScriptRunner */
 class GenericRunnerCommand(
-  allargs: List[String], 
-  override val settings: GenericRunnerSettings,
-  error: String => Unit)
-extends CompilerCommand(allargs, settings, error, false)
-{
-  def this(allargs: List[String], error: String=>Unit) =
-    this(allargs, new GenericRunnerSettings(error), error)
-
-  def this(allargs: List[String]) = 
-    this(allargs, str => Console.println("Error: " + str))
+  args: List[String],
+  override val settings: GenericRunnerSettings)
+extends CompilerCommand(args, settings) {
+  
+  def this(args: List[String], error: String => Unit) =
+    this(args, new GenericRunnerSettings(error))
 
+  def this(args: List[String]) = 
+    this(args, str => Console.println("Error: " + str))
 
   /** name of the associated compiler command */
+  override val cmdName = "scala"
   val compCmdName = "scalac"
+  
+  // change CompilerCommand behavior
+  override def shouldProcessArguments: Boolean = false
+
+  /** thingToRun: What to run.  If it is None, then the interpreter should be started
+   *  arguments: Arguments to pass to the object or script to run
+   */
+  val (thingToRun, arguments) = settings.processArguments(args, false)._2 match {
+    case Nil      => (None, Nil)
+    case hd :: tl => (Some(hd), tl)
+  }
 
-  /** What to run.  If it is None, then the interpreter should be started */
-  var thingToRun: Option[String] = None
+  override def usageMsg = """
+%s [ <option> ]... [<torun> <arguments>]
 
-  /** Arguments to pass to the object or script to run */
-  var arguments: List[String] = Nil
+All options to %s are allowed.  See %s -help.
 
-  override protected def processArguments() {
-    var args = allargs
+<torun>, if present, is an object or script file to run.
+If no <torun> is present, run an interactive shell.
 
-    while (!args.isEmpty && ok && args.head.startsWith("-")) {
-      val args0 = args
-      for (setting <- settings.allSettings)
-        if (args eq args0)
-          args = setting.tryToSet(args)
-      if (args eq args0) {
-        error("bad option: '" + args.head + "'")
-        ok = false
-      }
-    }
+Option -howtorun allows explicitly specifying how to run <torun>:
+    script: it is a script file
+    object: it is an object name
+    guess: (the default) try to guess
 
-    if (!args.isEmpty) {
-      thingToRun = Some(args.head)
-      arguments = args.tail
-    }
-  }
+Option -i requests that a file be pre-loaded.  It is only
+meaningful for interactive shells.
 
-  processArguments()
+Option -e requests that its argument be executed as Scala code.
 
-  override def usageMsg = {
-    cmdName + " [ <option> ]... [<torun> <arguments>]\n" +
-    "\n" +
-    "All options to "+compCmdName+" are allowed.  See "+compCmdName+" -help.\n" +
-    "\n" +
-    "<torun>, if present, is an object or script file to run.\n" +
-    "If no <torun> is present, run an interactive shell.\n" +
-    "\n" +
-    "Option -howtorun allows explicitly specifying how to run <torun>:\n" +
-    "    script: it is a script file\n" +
-    "    object: it is an object name\n" +
-    "    guess: (the default) try to guess\n" +
-    "\n" +
-    "Option -i requests that a file be pre-loaded.  It is only\n" +
-    "meaningful for interactive shells.\n" +
-    "\n" +
-    "Option -e requests that its argument be executed as Scala code.\n" +
-    "\n" +
-    "Option -savecompiled requests that the compiled script be saved\n" +
-    "for future use.\n" +
-    "\n" +
-    "Option -nocompdaemon requests that the fsc offline compiler not be used.\n" +
-    "\n" +
-    "Option -Dproperty=value sets a Java system property.\n"
-  }
+Option -savecompiled requests that the compiled script be saved
+for future use.
+
+Option -nocompdaemon requests that the fsc offline compiler not be used.
+
+Option -Dproperty=value sets a Java system property.
+""".format(cmdName, compCmdName, compCmdName)
 }
diff --git a/src/compiler/scala/tools/nsc/GenericRunnerSettings.scala b/src/compiler/scala/tools/nsc/GenericRunnerSettings.scala
index b050f99..222f6e9 100644
--- a/src/compiler/scala/tools/nsc/GenericRunnerSettings.scala
+++ b/src/compiler/scala/tools/nsc/GenericRunnerSettings.scala
@@ -1,15 +1,11 @@
 /* NSC -- new Scala compiler
- * Copyright 2006-2009 LAMP/EPFL
+ * Copyright 2006-2010 LAMP/EPFL
  * @author  Lex Spoon
  */
 
-// $Id: GenericRunnerSettings.scala 16894 2009-01-13 13:09:41Z cunei $
 
 package scala.tools.nsc
 
-import java.lang.System.getProperties
-import scala.collection.mutable.Queue
-
 class GenericRunnerSettings(error: String => Unit)
 extends Settings(error) {
   val howtorun =
@@ -41,51 +37,4 @@ extends Settings(error) {
     BooleanSetting(
         "-nocompdaemon",
         "do not use the fsc compilation daemon")
-
-
-  /** For some reason, "object defines extends Setting(...)"
-   *  does not work here.  The object is present but the setting
-   *  is not added to allsettings.  Thus, 
-   */
-  class DefinesSetting extends Setting("set a Java property") {
-
-    def name = "-D<prop>"
-
-    private val props = new Queue[(String, String)]
-    
-    def value = props.toList
-    
-    def tryToSet(args: List[String]): List[String] = {
-      args match {
-        case arg0::rest
-        if arg0.startsWith("-D") =>
-          val stripD = arg0.substring(2)
-          val eqidx = stripD.indexOf('=')
-          val addition =
-            if (eqidx < 0) 
-              (stripD, "")
-            else
-              (stripD.substring(0, eqidx), stripD.substring(eqidx+1))
-          props += addition
-          rest
-
-        case _ => args
-      }
-    }
-
-    /** Apply the specified properties to the current JVM */
-    def applyToCurrentJVM = {
-      val systemProps = getProperties
-      for ((key, value) <- props.toList)
-        systemProps.setProperty(key, value)
-    }
-    
-    def unparse: List[String] =
-      (props.toList.foldLeft[List[String]]
-        (Nil)
-        ((args, prop) =>
-         ("-D" + prop._1 + "=" + prop._2) :: args))
-  }
-  
-  val defines = new DefinesSetting
 }
diff --git a/src/compiler/scala/tools/nsc/Global.scala b/src/compiler/scala/tools/nsc/Global.scala
index adb0fe0..8228196 100644
--- a/src/compiler/scala/tools/nsc/Global.scala
+++ b/src/compiler/scala/tools/nsc/Global.scala
@@ -1,52 +1,63 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: Global.scala 16894 2009-01-13 13:09:41Z cunei $
 
 package scala.tools.nsc
 
-import java.io.{File, FileOutputStream, PrintWriter}
-import java.io.{IOException, FileNotFoundException}
-import java.nio.charset._
+import java.io.{ File, FileOutputStream, PrintWriter, IOException, FileNotFoundException }
+import java.nio.charset.{ Charset, IllegalCharsetNameException, UnsupportedCharsetException }
 import compat.Platform.currentTime
-import scala.tools.nsc.io.{SourceReader, AbstractFile}
-import scala.tools.nsc.reporters._
-import scala.tools.nsc.util.{ClassPath, SourceFile, BatchSourceFile}
 
-import scala.collection.mutable.{HashSet, HashMap, ListBuffer}
+import io.{ SourceReader, AbstractFile, Path }
+import reporters.{ Reporter, ConsoleReporter }
+import util.{ ClassPath, SourceFile, Statistics, BatchSourceFile, ScriptSourceFile, returning }
+import collection.mutable.{ HashSet, HashMap, ListBuffer }
+import reflect.generic.{ PickleBuffer }
 
-import symtab._
-import symtab.classfile.{PickleBuffer, Pickler}
-import util.Statistics
+import symtab.{ Flags, SymbolTable, SymbolLoaders }
+import symtab.classfile.Pickler
+import dependencies.DependencyAnalysis
 import plugins.Plugins
 import ast._
 import ast.parser._
 import typechecker._
 import transform._
-import backend.icode.{ICodes, GenICode, Checkers}
-import backend.ScalaPrimitives
+
+import backend.icode.{ ICodes, GenICode, Checkers }
+import backend.{ ScalaPrimitives, Platform, MSILPlatform, JavaPlatform }
 import backend.jvm.GenJVM
-import backend.msil.GenMSIL
-import backend.opt.{Inliners, ClosureElimination, DeadCodeElimination}
+import backend.opt.{ Inliners, ClosureElimination, DeadCodeElimination }
 import backend.icode.analysis._
 
 class Global(var settings: Settings, var reporter: Reporter) extends SymbolTable
                                                              with CompilationUnits
                                                              with Plugins
+                                                             with PhaseAssembly
 {
   // alternate constructors ------------------------------------------
+
   def this(reporter: Reporter) =
     this(new Settings(err => reporter.error(null,err)), 
          reporter)
 
   def this(settings: Settings) =
     this(settings, new ConsoleReporter(settings))
+  
+  // platform specific elements
 
-  //def this() = this(new Settings, new ConsoleReporter)
+  type ThisPlatform = Platform[_] { val global: Global.this.type }
+  
+  lazy val platform: ThisPlatform =
+    if (forMSIL) new { val global: Global.this.type = Global.this } with MSILPlatform
+    else new { val global: Global.this.type = Global.this } with JavaPlatform
+
+  def classPath: ClassPath[_] = platform.classPath
+  def rootLoader: LazyType = platform.rootLoader
 
   // sub-components --------------------------------------------------
 
+  /** Print tree in detailed form */
   object nodePrinters extends {
     val global: Global.this.type = Global.this
   } with NodePrinters {
@@ -54,66 +65,84 @@ class Global(var settings: Settings, var reporter: Reporter) extends SymbolTable
   }
   val nodeToString = nodePrinters.nodeToString
 
+  /** Generate ASTs */
   object gen extends {
     val global: Global.this.type = Global.this
   } with TreeGen {
     def mkAttributedCast(tree: Tree, pt: Type): Tree =
-      typer.typed(mkAttributedCastUntyped(tree, pt))
+      typer.typed(mkCast(tree, pt))
   }
 
+  /** Fold constants */
   object constfold extends {
     val global: Global.this.type = Global.this
   } with ConstantFolder
 
+  /** Tree checker (used for testing and debugging) */
   object checker extends {
     val global: Global.this.type = Global.this
   } with TreeCheckers
 
+  /** ICode generator */
   object icodes extends {
     val global: Global.this.type = Global.this
   } with ICodes
 
+  /** ICode analysis for optimization */
   object analysis extends {
     val global: Global.this.type = Global.this
   } with TypeFlowAnalysis
 
+  /** Copy propagation for optimization */
   object copyPropagation extends {
     val global: Global.this.type = Global.this
   } with CopyPropagation
 
+  /** Icode verification */
   object checkers extends {
     val global: Global.this.type = Global.this
   } with Checkers
 
+  /** Some statistics (normally disabled) */
   object statistics extends {
     val global: Global.this.type = Global.this
   } with Statistics
 
+  util.Statistics.enabled = settings.Ystatistics.value
+
+  /** Computing pairs of overriding/overridden symbols */
   object overridingPairs extends {
     val global: Global.this.type = Global.this
   } with OverridingPairs
 
+  /** Representing ASTs as graphs */
   object treeBrowsers extends {
     val global: Global.this.type = Global.this
   } with TreeBrowsers
 
   val treeBrowser = treeBrowsers.create()
 
+  // ------------ Hooks for interactive mode-------------------------
 
-//  val copy = new LazyTreeCopier()
+  /** Called every time an AST node is successfully typechecked in typerPhase.
+   */ 
+  def signalDone(context: analyzer.Context, old: Tree, result: Tree) {}
 
-  val comments =
-    if (onlyPresentation) new HashMap[Symbol,String]
-    else null
-  val methodArgumentNames =
-    if (onlyPresentation) new HashMap[Symbol,List[List[Symbol]]]
-    else null
+  /** Register new context; called for every created context
+   */
+  def registerContext(c: analyzer.Context) {}
+
+  /** Register top level class (called on entering the class)
+   */
+  def registerTopLevelSym(sym: Symbol) {}
+
+// ------------------ Reporting -------------------------------------
 
-// reporting -------------------------------------------------------
-  import nsc.util.NoPosition
   def error(msg: String) = reporter.error(NoPosition, msg)
-  def warning(msg: String) = reporter.warning(NoPosition, msg)
-  def inform(msg: String) = Console.err.println(msg)
+  def warning(msg: String) =
+    if (settings.Xwarnfatal.value) reporter.error(NoPosition, msg)
+    else reporter.warning(NoPosition, msg)
+  def inform(msg: String) = reporter.info(NoPosition, msg, true)
   def inform[T](msg: String, value: T): T = { inform(msg+value); value }
 
   //reporter.info(null, msg, true)
@@ -125,38 +154,34 @@ class Global(var settings: Settings, var reporter: Reporter) extends SymbolTable
     informProgress(msg + " in " + (currentTime - start) + "ms")
 
   def log(msg: AnyRef) {
-    if (settings.logAll.value || (settings.log contains phase.name))
-      inform("[log " + phase + "] " + msg)
+    if (settings.log contains phase.name) inform("[log " + phase + "] " + msg)
   }
 
-  class ErrorWithPosition(val pos: Int, val error: Throwable) extends Error
+  class ThrowableWithPosition(val pos: Int, val error: Throwable) extends Throwable
 
-  def tryWith[T](pos: Int, body: => T): T = try {
-    body
-  } catch {
-    case e : ErrorWithPosition => throw e
-    case te: TypeError => throw te
-    case e : Error            => throw new ErrorWithPosition(pos, e)
-    case e : RuntimeException => throw new ErrorWithPosition(pos, e)
-  }
+  def tryWith[T](pos: Int, body: => T): T =
+    try body
+    catch {
+      case e : ThrowableWithPosition  => throw e
+      case te: TypeError              => throw te
+      case e : RuntimeException       => throw new ThrowableWithPosition(pos, e)
+    }
 
-  def catchWith[T](source : SourceFile, body : => T) : T = try {
-    body
-  } catch {
-    case e : ErrorWithPosition =>
-      logError("POS: " + source.dbg(e.pos), e)
-      throw e.error
-  }
+  def catchWith[T](source : SourceFile, body : => T) : T =
+    try body
+    catch {
+      case e : ThrowableWithPosition =>
+        logError("POS: " + source.dbg(e.pos), e)
+        throw e.error
+    }
 
   def logError(msg: String, t: Throwable): Unit = ()
 
-  def abort(msg: String) = throw new Error(msg)
-
-// file interface -------------------------------------------------------
+// ------------ File interface -----------------------------------------
 
   private val reader: SourceReader = {
     def stdCharset: Charset = {
-      settings.encoding.value = Properties.encodingString // A mandatory charset
+      settings.encoding.value = Properties.sourceEncoding // A mandatory charset
       Charset.forName(settings.encoding.value)
     }
     val charset =
@@ -182,33 +207,29 @@ class Global(var settings: Settings, var reporter: Reporter) extends SymbolTable
     }
   }
 
-  lazy val classPath0 = new ClassPath(false && onlyPresentation)
-
-  lazy val classPath =
-    if (forMSIL)
-      new classPath0.Build(settings.sourcepath.value, settings.outdir.value)
-    else
-      new classPath0.Build(settings.classpath.value, settings.sourcepath.value,
-                           settings.outdir.value, settings.bootclasspath.value,
-                           settings.extdirs.value, settings.Xcodebase.value)
-  /* .NET's equivalent of a classpath */
-  lazy val assemrefs = {
-    import java.util.{StringTokenizer}
-    val set = new HashSet[File]  
-    val assems = new StringTokenizer(settings.assemrefs.value, File.pathSeparator)
-    while (assems.hasMoreTokens()) 
-      set += new java.io.File(assems.nextToken())
-    set  
-  }
-                           
+  if (settings.make.value != "all")
+    settings.dependenciesFile.value match {
+      case "none" => ()
+      case x => 
+        val depFilePath = Path(x)
+        if (depFilePath.exists) {
+          /** The directory where file lookup should start */
+          val rootPath = depFilePath.parent
+          def toFile(path: String) = AbstractFile.getFile(rootPath resolve Path(path))
+          dependencyAnalysis.loadFrom(AbstractFile.getFile(depFilePath), toFile)
+        }
+    }
 
-  if (settings.verbose.value) {
-    inform("[Classpath = " + classPath + "]")
-    if (forMSIL) inform("[AssemRefs = " + settings.assemrefs.value + "]")
-  }
+  if (settings.verbose.value || settings.Ylogcp.value)
+    inform("[Classpath = " + classPath.asClasspathString + "]")
+  
+  /** True if -Xscript has been set, indicating a script run.
+   */
+  def isScriptRun = settings.script.value != ""
 
-  def getSourceFile(f: AbstractFile): SourceFile =
-    new BatchSourceFile(f, reader.read(f))
+  def getSourceFile(f: AbstractFile): BatchSourceFile =
+    if (isScriptRun) ScriptSourceFile(f, reader read f)
+    else new BatchSourceFile(f, reader read f)
 
   def getSourceFile(name: String): SourceFile = {
     val f = AbstractFile.getFile(name)
@@ -217,22 +238,11 @@ class Global(var settings: Settings, var reporter: Reporter) extends SymbolTable
     getSourceFile(f)
   }
 
-  def getSourceFile(clazz: Symbol): SourceFile = {
-    val ret = classPath.root.find(clazz.fullNameString(File.separatorChar), false)
-    if (!ret.isSourceFile) throw new FileNotFoundException(
-      "source file for " + clazz + " could not be found")
-    getSourceFile(ret.sourceFile)
-  }
-  
-  lazy val loaders : SymbolLoaders { val global : Global.this.type } = new {
+  lazy val loaders = new SymbolLoaders {
     val global: Global.this.type = Global.this
-  } with SymbolLoaders
-
-  def rootLoader: LazyType =
-    if (forMSIL) new loaders.NamespaceLoader(classPath.root)
-    else new loaders.PackageLoader(classPath.root /* getRoot() */)
+  }
 
-// Phases ------------------------------------------------------------}
+// ------------ Phases -------------------------------------------}
 
   var globalPhase: Phase = NoPhase
 
@@ -253,263 +263,405 @@ class Global(var settings: Settings, var reporter: Reporter) extends SymbolTable
     override def flatClasses: Boolean = isFlat
     private val isDevirtualized = prev.name == "devirtualize" || prev.devirtualized
     override def devirtualized: Boolean = isDevirtualized  // (part of DEVIRTUALIZE)
-
-	/** Is current phase cancelled on this unit? */
-    def cancelled(unit: CompilationUnit) = 
-      reporter.cancelled ||
-      unit.isJava && this.id > currentRun.namerPhase.id
+    private val isSpecialized = prev.name == "specialize" || prev.specialized
+    override def specialized: Boolean = isSpecialized
+
+    /** Is current phase cancelled on this unit? */
+    def cancelled(unit: CompilationUnit) = {
+      // run the typer only if in `createJavadoc` mode
+      val maxJavaPhase = if (createJavadoc) currentRun.typerPhase.id else currentRun.namerPhase.id
+      reporter.cancelled || unit.isJava && this.id > maxJavaPhase
+    }
 
     final def applyPhase(unit: CompilationUnit) {
       if (settings.debug.value) inform("[running phase " + name + " on " + unit + "]")
       val unit0 = currentRun.currentUnit
-      currentRun.currentUnit = unit
-      reporter.setSource(unit.source)
-      if (!cancelled(unit)) apply(unit)
-      currentRun.advanceUnit
-      assert(currentRun.currentUnit == unit)
-      currentRun.currentUnit = unit0
+      try {
+        currentRun.currentUnit = unit
+        if (!cancelled(unit))
+          reporter.withSource(unit.source) { apply(unit) }
+        currentRun.advanceUnit
+      } finally {
+        //assert(currentRun.currentUnit == unit)
+        currentRun.currentUnit = unit0
+      }
     }
   }
 
-  class TerminalPhase(prev: Phase) extends GlobalPhase(prev) {
-    def name = "terminal"
-    def apply(unit: CompilationUnit) {}
-  }
-
+  // phaseName = "parser"
   object syntaxAnalyzer extends {
     val global: Global.this.type = Global.this
+    val runsAfter = List[String]()
+    val runsRightAfter = None
   } with SyntaxAnalyzer
-
+ 
+  // factory method for 
+  // phaseName = "namer"
+  // phaseName = "parser"
   object analyzer extends {
     val global: Global.this.type = Global.this
   } with Analyzer
 
+  /** Switch to turn on detailed type logs */
+  var printTypings = settings.Ytyperdebug.value
+ 
+  // phaseName = "superaccessors"
   object superAccessors extends {
     val global: Global.this.type = Global.this
+    val runsAfter = List[String]("typer")
+    val runsRightAfter = None
   } with SuperAccessors
-
+ 
+  // phaseName = "pickler"
   object pickler extends {
     val global: Global.this.type = Global.this
+    val runsAfter = List[String]("superaccessors")
+    val runsRightAfter = None
   } with Pickler
-
+ 
+  // phaseName = "refchecks"
   object refchecks extends {
     val global: Global.this.type = Global.this
+    val runsAfter = List[String]("pickler")
+    val runsRightAfter = None
   } with RefChecks
-/*
-  object devirtualize extends {
-    val global: Global.this.type = Global.this
-  } with DeVirtualize
-*/
+
+//  object devirtualize extends {
+//    val global: Global.this.type = Global.this
+//  } with DeVirtualize
+
+  // phaseName = "liftcode"
   object liftcode extends {
     val global: Global.this.type = Global.this
+    val runsAfter = List[String]("refchecks")
+    val runsRightAfter = None
   } with LiftCode
-
+ 
+  // phaseName = "uncurry"
   object uncurry extends {
     val global: Global.this.type = Global.this
+    val runsAfter = List[String]("refchecks","liftcode")
+    val runsRightAfter = None
   } with UnCurry
-
+ 
+  // phaseName = "tailcalls"
   object tailCalls extends {
     val global: Global.this.type = Global.this
+    val runsAfter = List[String]("uncurry")
+    val runsRightAfter = None
   } with TailCalls
 
-//  object checkDefined extends {
-//    val global: Global.this.type = Global.this
-//  } with CheckDefined
-
+  // phaseName = "explicitouter"
   object explicitOuter extends {
     val global: Global.this.type = Global.this
+    val runsAfter = List[String]("tailcalls")
+    val runsRightAfter = None
   } with ExplicitOuter
+                                                             
+  // phaseName = "specialize"
+  object specializeTypes extends {
+    val global: Global.this.type = Global.this
+    val runsAfter = List[String]("")
+    val runsRightAfter = Some("tailcalls")
+  } with SpecializeTypes 
 
+  // phaseName = "erasure"
   object erasure extends {
     val global: Global.this.type = Global.this
+    val runsAfter = List[String]("explicitouter")
+    val runsRightAfter = Some("explicitouter")
   } with Erasure
-  
+   
+  // phaseName = "lazyvals"
   object lazyVals extends {
     val global: Global.this.type = Global.this
     final val FLAGS_PER_WORD = 32
+    val runsAfter = List[String]("erasure")
+    val runsRightAfter = None
   } with LazyVals
-
+ 
+  // phaseName = "lambdalift"
   object lambdaLift extends {
     val global: Global.this.type = Global.this
+    val runsAfter = List[String]("lazyvals")
+    val runsRightAfter = None
   } with LambdaLift
 
+  // phaseName = "detach"
+//  object detach extends {
+//    val global: Global.this.type = Global.this
+//    val runsAfter = List("lambdalift")
+//    val runsRightAfter = Some("lambdalift")
+//  } with Detach
+
+  // phaseName = "constructors"
   object constructors extends {
     val global: Global.this.type = Global.this
+    val runsAfter = List[String]("lambdalift")
+    val runsRightAfter = None
   } with Constructors
-
+ 
+  // phaseName = "flatten"
   object flatten extends {
     val global: Global.this.type = Global.this
+    val runsAfter = List[String]("constructors")
+    val runsRightAfter = None
   } with Flatten
-/*
-  object detach extends {
-    val global: Global.this.type = Global.this
-  } with Detach
-*/
+
+  // phaseName = "mixin"
   object mixer extends {
     val global: Global.this.type = Global.this
+    val runsAfter = List[String]("flatten","constructors")
+    val runsRightAfter = None
   } with Mixin
-
+ 
+  // phaseName = "cleanup"
   object cleanup extends {
     val global: Global.this.type = Global.this
+    val runsAfter = List[String]("mixin")
+    val runsRightAfter = None
   } with CleanUp
-
-  object sampleTransform extends {
-    val global: Global.this.type = Global.this
-  } with SampleTransform
-
+ 
+  // phaseName = "icode"
   object genicode extends {
     val global: Global.this.type = Global.this
+    val runsAfter = List[String]("cleanup")
+    val runsRightAfter = None
   } with GenICode
-/*
-  object icodePrinter extends backend.icode.Printers {
-    val global: Global.this.type = Global.this
-  }
-*/
+
+// object icodePrinter extends backend.icode.Printers {
+//   val global: Global.this.type = Global.this
+// }
+
+  // phaseName = "???"
   object scalaPrimitives extends {
     val global: Global.this.type = Global.this
+    val runsAfter = List[String]()
+    val runsRightAfter = None
   } with ScalaPrimitives
-
+ 
+  // phaseName = "inliner"
   object inliner extends {
     val global: Global.this.type = Global.this
+    val runsAfter = List[String]("icode")
+    val runsRightAfter = None
   } with Inliners
-
+ 
+  // phaseName = "closelim"
   object closureElimination extends {
     val global: Global.this.type = Global.this
+    val runsAfter = List[String]("inliner")
+    val runsRightAfter = None
   } with ClosureElimination
-
+ 
+  // phaseName = "dce"
   object deadCode extends {
     val global: Global.this.type = Global.this
+    val runsAfter = List[String]("closelim")
+    val runsRightAfter = None
   } with DeadCodeElimination
-
+ 
+  // phaseName = "jvm"
   object genJVM extends {
     val global: Global.this.type = Global.this
+    val runsAfter = List[String]("dce")
+    val runsRightAfter = None
   } with GenJVM
 
-  object genMSIL extends {
+  object dependencyAnalysis extends {
+    val global: Global.this.type = Global.this
+    val runsAfter = List("jvm")
+    val runsRightAfter = None
+  } with DependencyAnalysis
+
+  // phaseName = "terminal"
+  object terminal extends {
     val global: Global.this.type = Global.this
-  } with GenMSIL
+    val phaseName = "terminal"
+    val runsAfter = List[String]("jvm","msil")
+    val runsRightAfter = None
+  } with SubComponent {
+    private var cache: Option[GlobalPhase] = None
+
+    def newPhase(prev: Phase): GlobalPhase = {
+      if (cache.isEmpty) cache = Some(new TerminalPhase(prev))
+      cache.get
+    }
+
+    def reset() {
+      cache = None
+    }
+
+    class TerminalPhase(prev: Phase) extends GlobalPhase(prev) {
+      def name = "terminal"
+      def apply(unit: CompilationUnit) {}
+    }
+  }
+
+  // phaseName = "SAMPLE PHASE"
+  object sampleTransform extends {
+    val global: Global.this.type = Global.this
+    val runsAfter = List[String]()
+    val runsRightAfter = None
+  } with SampleTransform
  
   object icodeChecker extends checkers.ICodeChecker()
 
   object typer extends analyzer.Typer(
-    analyzer.NoContext.make(EmptyTree, Global.this.definitions.RootClass, newScope))
+    analyzer.NoContext.make(EmptyTree, Global.this.definitions.RootClass, new Scope))
 
-  /** The built-in components.  The full list of components, including
-   *  plugins, is computed in the Plugins trait.
+  /* Add the internal compiler phases to the phases set
    */
-  protected def builtInPhaseDescriptors: List[SubComponent] = List(
-    analyzer.namerFactory: SubComponent, // note: types are there because otherwise
-    analyzer.typerFactory: SubComponent, // consistency check after refchecks would fail.
-    superAccessors,  // add super accessors
-    pickler         // serialize symbol tables
-
-    // Desugar virtual classes
-    // if (false && settings.Xexperimental.value) List(devirtualize) else List() 
-
-  ) ::: List(
-    refchecks        // perform reference and override checking, translate nested objects
-  ) ::: (
-    if (forJVM) List(liftcode) else List() // generate reified trees
-  ) ::: List(
-    uncurry,         // uncurry, translate function values to anonymous classes
-    tailCalls,       // replace tail calls by jumps
-    explicitOuter,   // replace C.this by explicit outer pointers, eliminate pattern matching
-//    checkDefined,
-    erasure,         // erase generic types to Java 1.4 types, add interfaces for traits
-    lazyVals,        // transforms local lazy vals into vars and initialized bits
-    lambdaLift,      // move nested functions to top level
-//    detach, 
-    constructors     // move field definitions into constructors
-  ) ::: (
-    if (forMSIL) List() else List(flatten) // get rid of inner classes
-  ) ::: List(
-    mixer,           // do mixin composition, translate lazy fields
-    cleanup,         // some platform-specific cleanups
-
-    genicode,        // generate portable intermediate code
-    inliner,         // optimization: do inlining
-    closureElimination, // optimization: get rid of uncalled closures
-    deadCode,           // optimization: get rid of dead cpde
-    if (forMSIL) genMSIL else genJVM, // generate .class files
-    sampleTransform
-  )
-
-
-  private var phasesCache: Option[List[SubComponent]] = None
-
-  def phaseDescriptors = {
-    if (phasesCache.isEmpty)
-      phasesCache = Some(computePhaseDescriptors)
-    phasesCache.get
+  protected def computeInternalPhases() {
+    phasesSet += syntaxAnalyzer             // The parser
+    phasesSet += analyzer.namerFactory      //   note: types are there because otherwise
+    phasesSet += analyzer.packageObjects    //   consistency check after refchecks would fail.
+    phasesSet += analyzer.typerFactory
+    phasesSet += superAccessors			       // add super accessors
+    phasesSet += pickler			       // serialize symbol tables
+    phasesSet += refchecks			       // perform reference and override checking, translate nested objects
+    
+//    if (false && settings.YvirtClasses)
+//	phasesSet += devirtualize		       // Desugar virtual classes4
+    
+    phasesSet += uncurry                    // uncurry, translate function values to anonymous classes
+    phasesSet += tailCalls                  // replace tail calls by jumps
+    phasesSet += specializeTypes
+    phasesSet += explicitOuter              // replace C.this by explicit outer pointers, eliminate pattern matching
+    phasesSet += erasure                    // erase types, add interfaces for traits
+    phasesSet += lazyVals
+    phasesSet += lambdaLift                 // move nested functions to top level
+    // if (forJVM && settings.Xdetach.value)
+    //   phasesSet += detach                // convert detached closures
+   
+    phasesSet += constructors               // move field definitions into constructors
+    phasesSet += mixer                      // do mixin composition
+    phasesSet += cleanup                    // some platform-specific cleanups
+    phasesSet += genicode                   // generate portable intermediate code
+    phasesSet += inliner                    // optimization: do inlining
+    phasesSet += closureElimination         // optimization: get rid of uncalled closures
+    phasesSet += deadCode                   // optimization: get rid of dead cpde
+    phasesSet += terminal                   // The last phase in the compiler chain
   }
+  
+  protected def computePlatformPhases() = platform.platformPhases foreach (phasesSet += _)
 
-  /** A description of the phases that will run */
-  def phaseDescriptions: String = {
+  /* Helper method for sequncing the phase assembly
+   */
+  private def computePhaseDescriptors: List[SubComponent] = {
+    computeInternalPhases()       // Global.scala
+    computePlatformPhases()       // backend/Platform.scala
+    computePluginPhases()         // plugins/Plugins.scala
+    buildCompilerFromPhasesSet()  // PhaseAssembly.scala
+  }
+
+  /* The phase descriptor list */
+  lazy val phaseDescriptors: List[SubComponent] = computePhaseDescriptors
+ 
+  /* The set of phase objects that is the basis for the compiler phase chain */
+  protected val phasesSet : HashSet[SubComponent] = new HashSet[SubComponent]
+  
+  /** The names of the phases. */
+  lazy val phaseNames = {
     new Run // force some initialization
-    val messages =
-      for (phase <- phaseDescriptors)
-	yield phase.phaseName //todo: + " - " + phase.description
-    messages.mkString("\n")
+    phaseDescriptors map (_.phaseName)
   }
 
+  /** A description of the phases that will run */
+  def phaseDescriptions: String =     
+    phaseNames mkString "\n" // todo: + " - " + phase.description
 
-  protected def insertBefore(c: SubComponent, cs: List[SubComponent], before: SubComponent): List[SubComponent] = cs match {
-    case List() => List(c)
-    case c1 :: cs1 => if (c1 == before) c :: cs else c1 :: insertBefore(c, cs1, before)
-  }
+  // ----------- Runs ---------------------------------------
 
   private var curRun: Run = null
-  def currentRun: Run = curRun
   private var curRunId = 0
-  override def currentRunId = curRunId
 
-  private var runCount = 0
+  /** The currently active run
+   */
+  def currentRun: Run = curRun
 
-  class Run {
-    curRunId += 1
-    assert(curRunId > 0)
-    //Console.println("starting run: " + id)
-    var currentUnit: CompilationUnit = _
-    curRun = this
-    private val firstPhase = syntaxAnalyzer.newPhase(NoPhase)
-    phase = firstPhase
-    definitions.init  // needs phase to be defined != NoPhase,
-                      // that's why it is placed here.
+  /** The id of the currently active run
+   */
+  override def currentRunId = curRunId
 
-    /** Deprecation warnings occurred */
-    var deprecationWarnings: Boolean = false
-    var uncheckedWarnings: Boolean = false
+  /** A Run is a single execution of the compiler on a sets of units
+   */
+  class Run {
 
-    private var p: Phase = firstPhase
+    var isDefined = false
+
+    private val firstPhase = { 
+      // ----------- Initialization code -------------------------
+      curRunId += 1
+      assert(curRunId > 0)
+      curRun = this
+      //Console.println("starting run: " + id)
+
+      // Can not take the phaseDescriptors.head even though its the syntaxAnalyzer, this will implicitly
+      // call definitions.init which uses phase and needs it to be != NoPhase
+      val phase1 = syntaxAnalyzer.newPhase(NoPhase)
+      phase = phase1
+      definitions.init  // needs phase to be defined != NoPhase,
+                        // that's why it is placed here.
+
+      // The first phase in the compiler phase chain
+      var p: Phase = phase1
+
+      // Reset the cache in terminal, the chain could have been build before where nobody used it
+      // This happens in the interpreter
+      terminal.reset 
+
+      // Each subcomponent is asked to deliver a newPhase that is chained together. If -Ystop:phasename is
+      // given at command-line, this will stop with that phasename
+      for (pd <- phaseDescriptors.tail.takeWhile(pd => !(stopPhase(pd.phaseName))))
+        if (!(settings.skip contains pd.phaseName)) p = pd.newPhase(p)
+
+      // Ensure there is a terminal phase at the end, Normally there will then be two terminal phases at the end
+      // if -Ystop:phasename was given, this makes sure that there is a terminal phase at the end
+      p = terminal.newPhase(p)
+      
+      phase1
+    }
 
-    protected def stopPhase(name : String) = 
-      if (onlyPresentation) name == "superaccessors"
-      else settings.stop.contains(name)
-   //  protected def stopPhase(name : String) = settings.stop.contains(name)
+    // --------------- Miscellania -------------------------------
     
-    for (pd <- phaseDescriptors.takeWhile(pd => !(stopPhase(pd.phaseName))))
-      if (!(settings.skip contains pd.phaseName)) p = pd.newPhase(p)
+    /** The currently compiled unit; set from GlobalPhase */
+    var currentUnit: CompilationUnit = _
+ 
+    /** Flags indicating whether deprecation warnings occurred */
+    var deprecationWarnings: Boolean = false
+    var uncheckedWarnings: Boolean = false
 
     def cancel { reporter.cancelled = true }
 
-    // progress tracking
+    // ------------------ Progress tracking -------------------------
+    
     def progress(current: Int, total: Int) {}
 
     private var phasec: Int = 0
     private var unitc: Int = 0
+
+    /** take note that phase is completed
+     *  (for progress reporting)
+     */
     def advancePhase {
       unitc = 0
       phasec += 1
       refreshProgress
     }
+    /** take note that a phase on a unit is completed
+     *  (for progress reporting)
+     */
     def advanceUnit {
       unitc += 1
       refreshProgress
     }
     private def refreshProgress = 
-      if (fileset.size > 0)
-        progress((phasec * fileset.size) + unitc,
-                 (phaseDescriptors.length+1) * fileset.size)
+      if (compiledFiles.size > 0)
+        progress((phasec * compiledFiles.size) + unitc,
+                 (phaseDescriptors.length-1) * compiledFiles.size) // terminal phase not part of the progress display
+    
+    // ----- finding phases --------------------------------------------
 
     def phaseNamed(name: String): Phase = {
       var p: Phase = firstPhase
@@ -521,6 +673,7 @@ class Global(var settings: Settings, var reporter: Reporter) extends SymbolTable
     val typerPhase = phaseNamed("typer")
     val picklerPhase = phaseNamed("pickler")
     val refchecksPhase = phaseNamed("refchecks")
+    val uncurryPhase = phaseNamed("uncurry")
 
     val explicitOuterPhase = phaseNamed("explicitouter")
     val erasurePhase = phaseNamed("erasure")
@@ -528,22 +681,25 @@ class Global(var settings: Settings, var reporter: Reporter) extends SymbolTable
     val mixinPhase = phaseNamed("mixin")
     val icodePhase = phaseNamed("icode")
 
+    isDefined = true
+
+    /** A test whether compilation should stop at phase with given name */
+    protected def stopPhase(name : String) = settings.stop.contains(name)
+
+    // ----------- Units and top-level classes and objects --------
+
     private var unitbuf = new ListBuffer[CompilationUnit]
-    private var fileset = new HashSet[AbstractFile]
-
-    lazy val terminalPhase : Phase = {
-      //var q : Phase = firstPhase
-      //while (q != null && !stopPhase(q.name)) q = q.next
-      //if (q == null) 
-      new TerminalPhase(p)
-      //else q
-    }
+    var compiledFiles = new HashSet[String]
+
+    /** add unit to be compiled in this run */
     private def addUnit(unit: CompilationUnit) {
+//      unit.parseSettings()
       unitbuf += unit
-      fileset += unit.source.file
+      compiledFiles += unit.source.file.path
     }
 
-    def units: Iterator[CompilationUnit] = unitbuf.elements
+    /* An iterator returning all the units being compiled in this run */
+    def units: Iterator[CompilationUnit] = unitbuf.iterator
 
     /** A map from compiled top-level symbols to their source files */
     val symSource = new HashMap[Symbol, AbstractFile]
@@ -559,7 +715,18 @@ class Global(var settings: Settings, var reporter: Reporter) extends SymbolTable
       else if (sym.isModuleClass) compiles(sym.sourceModule)
       else false
 
-    def compileSources(sources: List[SourceFile]) {
+    /** Is this run allowed to redefine the given symbol? Usually this is true
+     *  if the run does not already compile `sym`, but for interactive mode
+     *  we have a more liberal interpretation.
+     */
+    def canRedefine(sym: Symbol) = !compiles(sym)
+
+    // --------------- Compilation methods ---------------------------- 
+
+    /** Compile list of source files */
+    def compileSources(_sources: List[SourceFile]) {
+      val depSources = dependencyAnalysis.filter(_sources.distinct) // bug #1268, scalac confused by duplicated filenames
+      val sources = coreClassesFirst(depSources)
       if (reporter.hasErrors)
         return  // there is a problem already, e.g. a
                 // plugin was passed a bad option
@@ -568,12 +735,12 @@ class Global(var settings: Settings, var reporter: Reporter) extends SymbolTable
       for (source <- sources) addUnit(new CompilationUnit(source))
 
       globalPhase = firstPhase
-      while (globalPhase != terminalPhase && !reporter.hasErrors) {
+      while (globalPhase != terminal.newPhase(NoPhase) && !reporter.hasErrors) {
         val startTime = currentTime
         phase = globalPhase
         globalPhase.run
-        if (settings.print contains globalPhase.name)
-          if (globalPhase.id >= icodePhase.id) writeICode()
+        if (settings.Xprint contains globalPhase.name)
+          if (settings.writeICode.value && globalPhase.id >= icodePhase.id) writeICode()
           else if (settings.Xshowtrees.value) nodePrinters.printAll() 
           else printAllUnits()
         if (settings.printLate.value && globalPhase.name == "cleanup")
@@ -583,28 +750,29 @@ class Global(var settings: Settings, var reporter: Reporter) extends SymbolTable
         informTime(globalPhase.description, startTime)
         globalPhase = globalPhase.next
 
-        if ((settings.check contains globalPhase.prev.name) ||
-	    (settings.check contains "all")) {
+        if (settings.check contains globalPhase.prev.name) {
           if (globalPhase.prev.checkable) {
             phase = globalPhase
             if (globalPhase.id >= icodePhase.id) icodeChecker.checkICodes
             else checker.checkTrees
-	  } else if (!(settings.check contains "all")) {
+          } 
+          else if (!settings.check.doAllPhases) {
             warning("It is not possible to check the result of the "+globalPhase.name+" phase")
-	  }
+          }
         }
-
-        if (settings.statistics.value) statistics.print(phase)
+        if (settings.Ystatistics.value) statistics.print(phase)
         advancePhase
       }
 
+      //println(narrowCount+" narrowings")
+
       if (settings.Xshowcls.value != "")
         showDef(newTermName(settings.Xshowcls.value), false)
       if (settings.Xshowobj.value != "")
         showDef(newTermName(settings.Xshowobj.value), true)
 
       if (reporter.hasErrors) {
-        for ((sym, file) <- symSource.elements) {
+        for ((sym, file) <- symSource.iterator) {
           sym.reset(new loaders.SourcefileLoader(file))
           if (sym.isTerm) sym.moduleClass.reset(loaders.moduleClassLoader)
         }
@@ -617,68 +785,140 @@ class Global(var settings: Settings, var reporter: Reporter) extends SymbolTable
           warning("there were unchecked warnings; re-run with " + settings.unchecked.name + " for details")
         }
       }
-      for ((sym, file) <- symSource.elements) resetPackageClass(sym.owner)
+      for ((sym, file) <- symSource.iterator) resetPackageClass(sym.owner)
       informTime("total", startTime)
-    }
 
-    def compileLate(file: AbstractFile) {
-      if (fileset eq null) {
-        val msg = "No class file for " + file +
-                  " was found\n(This file cannot be loaded as a source file)"
-        inform(msg)
-        throw new FatalError(msg)
-      }
-      else if (!(fileset contains file)) {
-        val unit = new CompilationUnit(getSourceFile(file))
-        addUnit(unit)
-        var localPhase = firstPhase.asInstanceOf[GlobalPhase]
-        while (localPhase != null && (localPhase.id < globalPhase.id || localPhase.id <= namerPhase.id) && !reporter.hasErrors) {
-          val oldSource = reporter.getSource          
-          reporter.setSource(unit.source)          
-          atPhase(localPhase)(localPhase.applyPhase(unit))
-          val newLocalPhase = localPhase.next.asInstanceOf[GlobalPhase]
-          localPhase = if (localPhase == newLocalPhase) null else newLocalPhase
-          reporter.setSource(oldSource)
+      if (!dependencyAnalysis.off) {
+        settings.dependenciesFile.value match {
+          case "none" =>
+          case x => 
+            val depFilePath = Path(x)
+            if (!depFilePath.exists)
+              dependencyAnalysis.dependenciesFile = AbstractFile.getFile(depFilePath.createFile())
+        
+            /** The directory where file lookup should start */
+            val rootPath = depFilePath.parent.normalize
+            def fromFile(file: AbstractFile): String =
+              rootPath.relativize(Path(file.file).normalize).path
+          
+            dependencyAnalysis.saveDependencies(fromFile)
         }
-        refreshProgress
       }
     }
 
+    /** Compile list of abstract files */
     def compileFiles(files: List[AbstractFile]) {
-      try {
-        compileSources(files map getSourceFile)
-      } catch {
-        case ex: IOException => error(ex.getMessage())
-      }
+      try compileSources(files map getSourceFile)
+      catch { case ex: IOException => error(ex.getMessage()) }
     }
 
+    /** Compile list of files given by their names */
     def compile(filenames: List[String]) {
       try {
-        val scriptMain = settings.script.value        
-        // Are we compiling a script?
-        if (scriptMain != "") {
-          if(filenames.length != 1)
-            error("can only compile one script at a time")
-          val scriptFile = 
-	    ScriptRunner.wrappedScript(scriptMain, filenames.head, getSourceFile)
-          compileSources(List(scriptFile))
-        // No we are compiling regular source files
-	} else {
-          compileSources(filenames map getSourceFile)
-	}
-      } catch {
-        case ex: IOException => error(ex.getMessage())
+        val sources: List[SourceFile] =
+          if (isScriptRun && filenames.size > 1) returning(Nil)(_ => error("can only compile one script at a time"))
+          else filenames map getSourceFile
+      
+        compileSources(sources)
+      }
+      catch { case ex: IOException => error(ex.getMessage()) }
+    }
+
+    /** Compile abstract file until `globalPhase`, but at least
+     *  to phase "namer".
+     */
+    def compileLate(file: AbstractFile) {
+      if (compiledFiles eq null) {
+        val msg = "No class file for " + file +
+                  " was found\n(This file cannot be loaded as a source file)"
+        inform(msg)
+        throw new FatalError(msg)
+      } else if (!(compiledFiles contains file.path)) {
+        compileLate(new CompilationUnit(getSourceFile(file)))
       }
     }
 
+    /** Compile abstract file until `globalPhase`, but at least
+     *  to phase "namer".
+     */
+    def compileLate(unit: CompilationUnit) {
+      addUnit(unit)
+      var localPhase = firstPhase.asInstanceOf[GlobalPhase]
+      while (localPhase != null && (localPhase.id  < globalPhase.id || localPhase.id < typerPhase.id)/* && !reporter.hasErrors*/) {
+        val oldSource = reporter.getSource          
+        reporter.withSource(unit.source) {
+          atPhase(localPhase)(localPhase.applyPhase(unit))
+        }
+        val newLocalPhase = localPhase.next.asInstanceOf[GlobalPhase]
+        localPhase = if (localPhase == newLocalPhase) null else newLocalPhase
+      }
+      refreshProgress
+    }
+    
+    /**
+     * Attempt to locate a source file providing the given name as a top-level
+     * definition in the given context, and add it to the run via compileLate
+     * if found.
+     */
+    def compileSourceFor(context : analyzer.Context, name : Name) = false
+
+    /**
+     * Attempt to locate a source file providing the given name as a top-level
+     * definition with the given prefix, and add it to the run via compileLate
+     * if found.
+     */
+    def compileSourceFor(qual : Tree, name : Name) = false
+
+    /** Reset package class to state at typer (not sure what this
+     *  is needed for?)
+     */
     private def resetPackageClass(pclazz: Symbol) {
       atPhase(firstPhase) {
         pclazz.setInfo(atPhase(typerPhase)(pclazz.info))
       }
       if (!pclazz.isRoot) resetPackageClass(pclazz.owner)
     }
-  } // class Run
 
+    /**
+     * Re-orders the source files to
+     *  1. ScalaObject
+     *  2. LowPriorityImplicits / StandardEmbeddings (i.e. parents of Predef)
+     *  3. the rest
+     *
+     * 1 is to avoid cyclic reference errors.
+     * 2 is due to the following. When completing "Predef" (*), typedIdent is called
+     * for its parents (e.g. "LowPriorityImplicits"). typedIdent checks wethter
+     * the symbol reallyExists, which tests if the type of the symbol after running
+     * its completer is != NoType.
+     * If the "namer" phase has not yet run for "LowPriorityImplicits", the symbol
+     * has a SourcefileLoader as type. Calling "doComplete" on it does nothing at
+     * all, because the source file is part of the files to be compiled anyway.
+     * So the "reallyExists" test will return "false".
+     * Only after the namer, the symbol has a lazy type which actually computes
+     * the info, and "reallyExists" behaves as expected.
+     * So we need to make sure that the "namer" phase is run on predef's parents
+     * before running it on predef. 
+     *
+     * (*) Predef is completed early when calling "mkAttributedRef" during the
+     *   addition of "import Predef._" to sourcefiles. So this situation can't
+     *   happen for user classes.
+     *
+     */
+    private def coreClassesFirst(files: List[SourceFile]) = {
+      def inScalaFolder(f: SourceFile) =
+        f.file.container.name == "scala"
+      var scalaObject: Option[SourceFile] = None
+      val res = new ListBuffer[SourceFile]
+      for (file <- files) file.file.name match {
+        case "ScalaObject.scala" if inScalaFolder(file) => scalaObject = Some(file)
+        case "LowPriorityImplicits.scala" if inScalaFolder(file) => file +=: res
+        case "StandardEmbeddings.scala" if inScalaFolder(file) => file +=: res
+        case _ => res += file
+      }
+      for (so <- scalaObject) so +=: res
+      res.toList
+    }
+  } // class Run
 
   def printAllUnits() {
     print("[[syntax trees at end of " + phase + "]]")
@@ -704,11 +944,11 @@ class Global(var settings: Settings, var reporter: Reporter) extends SymbolTable
     inform("" + sym.name + ":" +(if (module) sym.tpe.typeSymbol.info else sym.info))
   }
 
-  /** Returns the file with the given suffix for the given class. */
+  /** Returns the file with the given suffix for the given class. Used for icode writing. */
   def getFile(clazz: Symbol, suffix: String): File = {
-    val outdirname = settings.outdir.value
-    var outdir = new File(if (outdirname == "") "." else outdirname)
-    val filename = clazz.fullNameString('.')
+    val outdirname = settings.outputDirs.outputDirFor(clazz.sourceFile)
+    var outdir = new File(if (outdirname.path == "") "." else outdirname.path)
+    val filename = clazz.fullName
     var start = 0
     var end = filename.indexOf('.', start)
     while (end >= start) {
@@ -740,12 +980,8 @@ class Global(var settings: Settings, var reporter: Reporter) extends SymbolTable
     })
   }
 
-  def forCLDC: Boolean = settings.target.value == "cldc"
   def forJVM : Boolean = settings.target.value startsWith "jvm"
   def forMSIL: Boolean = settings.target.value == "msil"
-  def onlyPresentation = inIDE
-  private val unpickleIDEHook0 : (( => Type) => Type) = f => f
-  def unpickleIDEHook : (( => Type) => Type) = unpickleIDEHook0
-
-  def doPickleHash = false
+  def onlyPresentation = false
+  def createJavadoc = false
 }
diff --git a/src/compiler/scala/tools/nsc/IdeSupport.scala b/src/compiler/scala/tools/nsc/IdeSupport.scala
deleted file mode 100644
index a447aed..0000000
--- a/src/compiler/scala/tools/nsc/IdeSupport.scala
+++ /dev/null
@@ -1,42 +0,0 @@
-package scala.tools.nsc
-import scala.tools.nsc.io._
-trait IdeSupport extends Global with symtab.IdeSupport {
-  /** to do no dependency tracking */
-  protected def normalCompile[T](f : => T) : T = f
-  override def unpickleIDEHook : (( => Type) => Type) = f => normalCompile(f)
-  class IdeRun extends Run {
-    override def compiles(sym : Symbol) : Boolean = false // throw new Error
-    override def compileLate(file : AbstractFile) = {
-      reloadSource(file)
-      normalCompile(super.compileLate(file))
-    }
-    override def stopPhase(name : String) = 
-      name == "superaccessors" || super.stopPhase(name)
-  }
-  
-  
-  // load a source file without us caring about adapt.
-  def loadSource(file : AbstractFile) : Option[CompilationUnit] = {
-    val run = new IdeRun
-    reloadSource(file) 
-    val source = getSourceFile(file)
-    try {
-      normalCompile(run.compileSources(source :: Nil))
-      run.units.find(unit => unit.source == source)
-    } catch {
-      case e => 
-        logError("error in presentation normal compile ", e)
-        None
-    }
-  }
-  object loaders1 extends {
-    val global : IdeSupport.this.type = IdeSupport.this
-  } with scala.tools.nsc.symtab.SymbolLoaders {
-    import global._
-    protected override def completeClassfile(root : global.Symbol, loader : ClassfileLoader)(f : => Unit) : Unit = 
-      global.normalCompile(f)
-    override def computeDepends(from : PackageLoader) : global.PackageScopeDependMap = IdeSupport.this.computeDepends(from.asInstanceOf[IdeSupport.this.loaders.PackageLoader])
-  }
-  def computeDepends(from : loaders.PackageLoader) : PackageScopeDependMap = null
-  override lazy val loaders = loaders1
-}
diff --git a/src/compiler/scala/tools/nsc/Interpreter.scala b/src/compiler/scala/tools/nsc/Interpreter.scala
index d97899b..6215e31 100644
--- a/src/compiler/scala/tools/nsc/Interpreter.scala
+++ b/src/compiler/scala/tools/nsc/Interpreter.scala
@@ -1,26 +1,36 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: Interpreter.scala 17013 2009-02-02 11:59:53Z washburn $
 
 package scala.tools.nsc
 
-import java.io.{File, PrintWriter, StringWriter, Writer}
-import java.lang.{Class, ClassLoader}
-import java.net.{MalformedURLException, URL, URLClassLoader}
-
-import scala.collection.immutable.ListSet
+import Predef.{ println => _, _ }
+import java.io.{ File, PrintWriter, StringWriter, Writer }
+import File.pathSeparator
+import java.lang.{ Class, ClassLoader }
+import java.net.{ MalformedURLException, URL }
+import java.lang.reflect
+import reflect.InvocationTargetException
+
+import scala.PartialFunction.{ cond, condOpt }
+import scala.tools.util.PathResolver
+import scala.reflect.Manifest
 import scala.collection.mutable
-import scala.collection.mutable.{ListBuffer, HashSet, ArrayBuffer}
-
-//import ast.parser.SyntaxAnalyzer
-import io.{PlainFile, VirtualDirectory}
-import reporters.{ConsoleReporter, Reporter}
-import symtab.Flags
-import util.{SourceFile,BatchSourceFile,ClassPath,NameTransformer}
-import nsc.{InterpreterResults=>IR}
-import scala.tools.nsc.interpreter._
+import scala.collection.mutable.{ ListBuffer, HashSet, HashMap, ArrayBuffer }
+import scala.collection.immutable.Set
+import scala.tools.nsc.util.ScalaClassLoader
+import ScalaClassLoader.URLClassLoader
+import scala.util.control.Exception.{ Catcher, catching, ultimately, unwrapping }
+
+import io.{ PlainFile, VirtualDirectory }
+import reporters.{ ConsoleReporter, Reporter }
+import symtab.{ Flags, Names }
+import util.{ SourceFile, BatchSourceFile, ScriptSourceFile, ClassPath, Chars, stringFromWriter }
+import scala.reflect.NameTransformer
+import scala.tools.nsc.{ InterpreterResults => IR }
+import interpreter._
+import Interpreter._
 
 /** <p>
  *    An interpreter for Scala code.
@@ -47,7 +57,7 @@ import scala.tools.nsc.interpreter._
  *    all variables defined by that code.  To extract the result of an
  *    interpreted line to show the user, a second "result object" is created
  *    which imports the variables exported by the above object and then
- *    exports a single member named "result".  To accomodate user expressions
+ *    exports a single member named "scala_repl_result".  To accomodate user expressions
  *    that read from variables or methods defined in previous statements, "import"
  *    statements are used.
  *  </p>
@@ -63,84 +73,129 @@ import scala.tools.nsc.interpreter._
  * @author Lex Spoon
  */
 class Interpreter(val settings: Settings, out: PrintWriter) {
-  import symtab.Names
-
-  /* If the interpreter is running on pre-jvm-1.5 JVM, 
-     it is necessary to force the target setting to jvm-1.4 */
-  private val major = System.getProperty("java.class.version").split("\\.")(0)
-  if (major.toInt < 49) {
-    this.settings.target.value = "jvm-1.4"
+  repl =>
+  
+  def println(x: Any) = {
+    out.println(x)
+    out.flush()
   }
-
+  
+  /** construct an interpreter that reports to Console */
+  def this(settings: Settings) = this(settings, new NewLinePrintWriter(new ConsoleWriter, true))
+  def this() = this(new Settings())
+  
   /** directory to save .class files to */
   val virtualDirectory = new VirtualDirectory("(memory)", None)
+  
+  /** reporter */
+  object reporter extends ConsoleReporter(settings, null, out) {
+    override def printMessage(msg: String) {
+      out println clean(msg)
+      out.flush()
+    }
+  }
+
+  /** We're going to go to some trouble to initialize the compiler asynchronously.
+   *  It's critical that nothing call into it until it's been initialized or we will
+   *  run into unrecoverable issues, but the perceived repl startup time goes
+   *  through the roof if we wait for it.  So we initialize it with a future and
+   *  use a lazy val to ensure that any attempt to use the compiler object waits
+   *  on the future.
+   */
+  private val _compiler: Global = newCompiler(settings, reporter)
+  private def _initialize(): Boolean = {
+    val source = """
+      |// this is assembled to force the loading of approximately the
+      |// classes which will be loaded on the first expression anyway.
+      |class $repl_$init {
+      |  val x = "abc".reverse.length + (5 max 5)
+      |  scala.runtime.ScalaRunTime.stringOf(x)
+      |}
+      |""".stripMargin
+    
+    try {
+      new _compiler.Run() compileSources List(new BatchSourceFile("<init>", source))
+      if (isReplDebug || settings.debug.value)
+        println("Repl compiler initialized.")
+      true
+    } 
+    catch {
+      case MissingRequirementError(msg) => println("""
+        |Failed to initialize compiler: %s not found.
+        |** Note that as of 2.8 scala does not assume use of the java classpath.
+        |** For the old behavior pass -usejavacp to scala, or if using a Settings
+        |** object programatically, settings.usejavacp.value = true.""".stripMargin.format(msg)
+      )
+      false
+    }
+  }
+  
+  // set up initialization future
+  private var _isInitialized: () => Boolean = null
+  def initialize() = synchronized { 
+    if (_isInitialized == null)
+      _isInitialized = scala.concurrent.ops future _initialize()
+  }
 
-  /** the compiler to compile expressions with */
-  val compiler: scala.tools.nsc.Global = newCompiler(settings, reporter)
-
-  import compiler.Traverser
-  import compiler.{Tree, TermTree,
-                   ValOrDefDef, ValDef, DefDef, Assign,
-                   ClassDef, ModuleDef, Ident, Select, TypeDef,
-                   Import, MemberDef, DocDef}
-  import compiler.CompilationUnit
-  import compiler.{Symbol,Name,Type}
-  import compiler.nme
-  import compiler.newTermName
-  import compiler.nme.{INTERPRETER_VAR_PREFIX, INTERPRETER_SYNTHVAR_PREFIX}
-  import Interpreter.string2code
+  /** the public, go through the future compiler */
+  lazy val compiler: Global = {
+    initialize()
 
-  /** construct an interpreter that reports to Console */
-  def this(settings: Settings) =
-    this(settings,
-         new NewLinePrintWriter(new ConsoleWriter, true))
+    // blocks until it is ; false means catastrophic failure
+    if (_isInitialized()) _compiler
+    else null
+  }
+
+  import compiler.{ Traverser, CompilationUnit, Symbol, Name, Type, TypeRef, PolyType }
+  import compiler.{ 
+    Tree, TermTree, ValOrDefDef, ValDef, DefDef, Assign, ClassDef,
+    ModuleDef, Ident, Select, TypeDef, Import, MemberDef, DocDef,
+    ImportSelector, EmptyTree, NoType }
+  import compiler.{ nme, newTermName, newTypeName }
+  import nme.{ 
+    INTERPRETER_VAR_PREFIX, INTERPRETER_SYNTHVAR_PREFIX, INTERPRETER_LINE_PREFIX,
+    INTERPRETER_IMPORT_WRAPPER, INTERPRETER_WRAPPER_SUFFIX, USCOREkw
+  }
+  
+  import compiler.definitions
+  import definitions.{ EmptyPackage, getMember }
 
   /** whether to print out result lines */
-  private var printResults: Boolean = true
+  private[nsc] var printResults: Boolean = true
 
-  /** Be quiet.  Do not print out the results of each
-    * submitted command unless an exception is thrown.  */
-  def beQuiet = { printResults = false }
-  
   /** Temporarily be quiet */
-  def beQuietDuring[T](operation: => T): T = {
-    val wasPrinting = printResults
-    try {
+  def beQuietDuring[T](operation: => T): T = {    
+    val wasPrinting = printResults    
+    ultimately(printResults = wasPrinting) {
       printResults = false
       operation
-    } finally {
-      printResults = wasPrinting
+    }
+  }
+  
+  /** whether to bind the lastException variable */
+  private var bindLastException = true
+  
+  /** Temporarily stop binding lastException */
+  def withoutBindingLastException[T](operation: => T): T = {
+    val wasBinding = bindLastException
+    ultimately(bindLastException = wasBinding) {
+      bindLastException = false
+      operation
     }
   }
 
   /** interpreter settings */
-  lazy val isettings = new InterpreterSettings
-
-  object reporter extends ConsoleReporter(settings, null, out) {
-    //override def printMessage(msg: String) { out.println(clean(msg)) }
-    override def printMessage(msg: String) { out.print(clean(msg) + "\n"); out.flush() }
-  }
+  lazy val isettings = new InterpreterSettings(this)
 
   /** Instantiate a compiler.  Subclasses can override this to
    *  change the compiler class used by this interpreter. */
   protected def newCompiler(settings: Settings, reporter: Reporter) = {
-    val comp = new scala.tools.nsc.Global(settings, reporter)
-    comp.genJVM.outputDir = virtualDirectory
-    comp
+    settings.outputDirs setSingleOutput virtualDirectory    
+    new Global(settings, reporter)
   }
-
-
+  
   /** the compiler's classpath, as URL's */
-  val compilerClasspath: List[URL] = {
-    val classpathPart = 
-      (ClassPath.expandPath(compiler.settings.classpath.value).
-         map(s => new File(s).toURL))
-    def parseURL(s: String): Option[URL] =
-      try { Some(new URL(s)) }
-      catch { case _:MalformedURLException => None }
-    val codebasePart = (compiler.settings.Xcodebase.value.split(" ")).toList.flatMap(parseURL)
-    classpathPart ::: codebasePart
-  }
+  lazy val compilerClasspath: List[URL] = new PathResolver(settings) asURLs
 
   /* A single class loader is used for all commands interpreted by this Interpreter.
      It would also be possible to create a new class loader for each command
@@ -155,110 +210,156 @@ class Interpreter(val settings: Settings, out: PrintWriter) {
          shadow the old ones, and old code objects refer to the old
          definitions.
   */
-  /** class loader used to load compiled code */
-  private val classLoader = {
-    val parent =
-      if (parentClassLoader == null)
-        new URLClassLoader(compilerClasspath.toArray)
-      else
-         new URLClassLoader(compilerClasspath.toArray,
-                            parentClassLoader)
-    new AbstractFileClassLoader(virtualDirectory, parent)     
+  private var _classLoader: AbstractFileClassLoader = null
+  def resetClassLoader() = _classLoader = makeClassLoader()
+  def classLoader: AbstractFileClassLoader = {
+    if (_classLoader == null)
+      resetClassLoader()
+    
+    _classLoader
   }
+  private def makeClassLoader(): AbstractFileClassLoader = {
+    val parent =
+      if (parentClassLoader == null)  ScalaClassLoader fromURLs compilerClasspath
+      else                            new URLClassLoader(compilerClasspath, parentClassLoader)
 
-  /** Set the current Java "context" class loader to this
-    * interpreter's class loader */
-  def setContextClassLoader() {
-    Thread.currentThread.setContextClassLoader(classLoader)
+    new AbstractFileClassLoader(virtualDirectory, parent)
   }
+  private def loadByName(s: String): Class[_] = (classLoader tryToInitializeClass s).get
+  private def methodByName(c: Class[_], name: String): reflect.Method =
+    c.getMethod(name, classOf[Object])
+  
+  protected def parentClassLoader: ClassLoader =
+    settings.explicitParentLoader.getOrElse( this.getClass.getClassLoader() )
+
+  def getInterpreterClassLoader() = classLoader
 
-  protected def parentClassLoader: ClassLoader = this.getClass.getClassLoader()
+  // Set the current Java "context" class loader to this interpreter's class loader
+  def setContextClassLoader() = classLoader.setAsContext()
 
   /** the previous requests this interpreter has processed */
   private val prevRequests = new ArrayBuffer[Request]()
+  private val usedNameMap = new HashMap[Name, Request]()
+  private val boundNameMap = new HashMap[Name, Request]()
+  private def allHandlers = prevRequests.toList flatMap (_.handlers)
+  private def allReqAndHandlers = prevRequests.toList flatMap (req => req.handlers map (req -> _))
+  
+  def printAllTypeOf = {
+    prevRequests foreach { req =>
+      req.typeOf foreach { case (k, v) => Console.println(k + " => " + v) }
+    }
+  }
 
-  /** next line number to use */
-  private var nextLineNo = 0
+  /** Most recent tree handled which wasn't wholly synthetic. */
+  private def mostRecentlyHandledTree: Option[Tree] = {
+    for {
+      req <- prevRequests.reverse
+      handler <- req.handlers.reverse
+      name <- handler.generatesValue
+      if !isSynthVarName(name)
+    } return Some(handler.member)
 
-  /** allocate a fresh line name */
-  private def newLineName = {
-    val num = nextLineNo
-    nextLineNo += 1
-    compiler.nme.INTERPRETER_LINE_PREFIX + num
+    None
   }
-  
-  /** next result variable number to use */
-  private var nextVarNameNo = 0
 
-  /** allocate a fresh variable name */
-  private def newVarName() = {
-    val num = nextVarNameNo
-    nextVarNameNo += 1
-    INTERPRETER_VAR_PREFIX + num
-  }
+  def recordRequest(req: Request) {
+    def tripart[T](set1: Set[T], set2: Set[T]) = {
+      val intersect = set1 intersect set2
+      List(set1 -- intersect, intersect, set2 -- intersect)
+    }
 
-  /** next internal variable number to use */
-  private var nextInternalVarNo = 0
-  
-  /** allocate a fresh internal variable name */
-  private def newInternalVarName() = {
-    val num = nextVarNameNo
-    nextVarNameNo += 1
-    INTERPRETER_SYNTHVAR_PREFIX + num
+    prevRequests += req
+    req.usedNames foreach (x => usedNameMap(x) = req)
+    req.boundNames foreach (x => boundNameMap(x) = req)
+    
+    // XXX temporarily putting this here because of tricky initialization order issues
+    // so right now it's not bound until after you issue a command.
+    if (prevRequests.size == 1)
+      quietBind("settings", "scala.tools.nsc.InterpreterSettings", isettings)
+
+    // println("\n  s1 = %s\n  s2 = %s\n  s3 = %s".format(
+    //   tripart(usedNameMap.keysIterator.toSet, boundNameMap.keysIterator.toSet): _*
+    // ))
   }
   
+  private def keyList[T](x: collection.Map[T, _]): List[T] = x.keys.toList sortBy (_.toString)
+  def allUsedNames = keyList(usedNameMap)
+  def allBoundNames = keyList(boundNameMap)
+  def allSeenTypes = prevRequests.toList flatMap (_.typeOf.values.toList) distinct
+  def allValueGeneratingNames = allHandlers flatMap (_.generatesValue)
+  def allImplicits = partialFlatMap(allHandlers) {
+    case x: MemberHandler if x.definesImplicit => x.boundNames
+  }
 
-  /** Check if a name looks like it was generated by newVarName */
-  private def isGeneratedVarName(name: String): Boolean =
-    name.startsWith(INTERPRETER_VAR_PREFIX) && {
-      val suffix = name.drop(INTERPRETER_VAR_PREFIX.length)
-      suffix.forall(_.isDigit)
+  /** Generates names pre0, pre1, etc. via calls to apply method */
+  class NameCreator(pre: String) {
+    private var x = -1
+    var mostRecent: String = null
+    
+    def apply(): String = { 
+      x += 1
+      val name = pre + x.toString
+      // make sure we don't overwrite their unwisely named res3 etc.
+      mostRecent =
+        if (allBoundNames exists (_.toString == name)) apply()
+        else name
+      
+      mostRecent
     }
+    def reset(): Unit = x = -1
+    def didGenerate(name: String) =
+      (name startsWith pre) && ((name drop pre.length) forall (_.isDigit))
+  }
 
+  /** allocate a fresh line name */
+  private lazy val lineNameCreator = new NameCreator(INTERPRETER_LINE_PREFIX)
+  
+  /** allocate a fresh var name */
+  private lazy val varNameCreator = new NameCreator(INTERPRETER_VAR_PREFIX)
+  
+  /** allocate a fresh internal variable name */
+  private lazy val synthVarNameCreator = new NameCreator(INTERPRETER_SYNTHVAR_PREFIX)
 
-  /** generate a string using a routine that wants to write on a stream */
-  private def stringFrom(writer: PrintWriter => Unit): String = {
-    val stringWriter = new StringWriter()
-    val stream = new NewLinePrintWriter(stringWriter)
-    writer(stream)
-    stream.close
-    stringWriter.toString
-  }
+  /** Check if a name looks like it was generated by varNameCreator */
+  private def isGeneratedVarName(name: String): Boolean = varNameCreator didGenerate name  
+  private def isSynthVarName(name: String): Boolean = synthVarNameCreator didGenerate name
+  private def isSynthVarName(name: Name): Boolean = synthVarNameCreator didGenerate name.toString
+  
+  def getVarName = varNameCreator()
+  def getSynthVarName = synthVarNameCreator()
 
-  /** Truncate a string if it is longer than settings.maxPrintString */
+  /** Truncate a string if it is longer than isettings.maxPrintString */
   private def truncPrintString(str: String): String = {
     val maxpr = isettings.maxPrintString
-
-    if (maxpr <= 0) 
-      return str
-
-    if (str.length <= maxpr)
-      return str
-    
     val trailer = "..."
-    if (maxpr >= trailer.length+1)
-      return str.substring(0, maxpr-3) + trailer
- 
-    str.substring(0, maxpr)
+    
+    if (maxpr <= 0 || str.length <= maxpr) str
+    else str.substring(0, maxpr-3) + trailer
   }
 
-  /** Clean up a string for output */
-  private def clean(str: String) =
-    truncPrintString(Interpreter.stripWrapperGunk(str))
+  /** Clean up a string for output */  
+  private def clean(str: String) = truncPrintString(
+    if (isettings.unwrapStrings) stripWrapperGunk(str)
+    else str
+  )
 
   /** Indent some code by the width of the scala> prompt.
-   *  This way, compiler error messages read beettr.
+   *  This way, compiler error messages read better.
    */
+  private final val spaces = List.fill(7)(" ").mkString
   def indentCode(code: String) = {
-    val spaces = "       "
-
-    stringFrom(str =>
+    /** Heuristic to avoid indenting and thereby corrupting """-strings and XML literals. */
+    val noIndent = (code contains "\n") && (List("\"\"\"", "</", "/>") exists (code contains _))
+    stringFromWriter(str =>
       for (line <- code.lines) {
-        str.print(spaces)
+        if (!noIndent)
+          str.print(spaces)
+
         str.print(line + "\n")
         str.flush()
       })
   }
+  def indentString(s: String) = s split "\n" map (spaces + _ + "\n") mkString
 
   implicit def name2string(name: Name) = name.toString
 
@@ -285,149 +386,118 @@ class Interpreter(val settings: Settings, out: PrintWriter) {
    * (3) It imports multiple same-named implicits, but only the
    * last one imported is actually usable.
    */
-  private def importsCode(wanted: Set[Name]): (String, String, String) = {
+  private case class ComputedImports(prepend: String, append: String, access: String)
+  private def importsCode(wanted: Set[Name]): ComputedImports = {
     /** Narrow down the list of requests from which imports 
      *  should be taken.  Removes requests which cannot contribute
      *  useful imports for the specified set of wanted names.
      */
-    def reqsToUse: List[(Request,MemberHandler)] = {
-      /** Loop through a list of MemberHandlers and select
-       *  which ones to keep.  'wanted' is the set of
-       *  names that need to be imported, and 
-       *  'shadowed' is the list of names useless to import
-       *  because a later request will re-import it anyway.
+    case class ReqAndHandler(req: Request, handler: MemberHandler) { }
+    
+    def reqsToUse: List[ReqAndHandler] = {      
+      /** Loop through a list of MemberHandlers and select which ones to keep.
+        * 'wanted' is the set of names that need to be imported.
        */
-      def select(reqs: List[(Request,MemberHandler)], wanted: Set[Name]): 
-      List[(Request,MemberHandler)] = {
+      def select(reqs: List[ReqAndHandler], wanted: Set[Name]): List[ReqAndHandler] = {
+        val isWanted = wanted contains _
+        // Single symbol imports might be implicits! See bug #1752.  Rather than
+        // try to finesse this, we will mimic all imports for now.
+        def keepHandler(handler: MemberHandler) = handler match {
+          case _: ImportHandler => true
+          case x                => x.definesImplicit || (x.boundNames exists isWanted)
+        }
+                   
         reqs match {
-          case Nil => Nil
-
-          case (req,handler)::rest =>
-            val keepit =
-              (handler.definesImplicit ||
-               handler.importsWildcard ||
-               handler.importedNames.exists(wanted.contains(_)) ||
-               handler.boundNames.exists(wanted.contains(_)))
-
-            val newWanted =
-              if (keepit) {
-                (wanted
-                   ++ handler.usedNames
-                   -- handler.boundNames 
-                   -- handler.importedNames)
-              } else {
-                wanted
-              }
-
-            val restToKeep = select(rest, newWanted)
-
-            if(keepit)
-              (req,handler) :: restToKeep
-            else
-              restToKeep
+          case Nil                                    => Nil
+          case rh :: rest if !keepHandler(rh.handler) => select(rest, wanted)
+          case rh :: rest                             =>
+            val importedNames = rh.handler match { case x: ImportHandler => x.importedNames ; case _ => Nil }
+            import rh.handler._
+            val newWanted = wanted ++ usedNames -- boundNames -- importedNames
+            rh :: select(rest, newWanted)
         }
       }
-
-      val rhpairs = for {
-        req <- prevRequests.toList.reverse
-        handler <- req.handlers
-      } yield (req, handler)
-
-      select(rhpairs, wanted).reverse
+      
+      /** Flatten the handlers out and pair each with the original request */
+      select(allReqAndHandlers reverseMap  { case (r, h) => ReqAndHandler(r, h) }, wanted).reverse
     }
 
-    val code = new StringBuffer
-    val trailingBraces = new StringBuffer
-    val accessPath = new StringBuffer
-    val impname = compiler.nme.INTERPRETER_IMPORT_WRAPPER
-    val currentImps = mutable.Set.empty[Name]
+    val code, trailingBraces, accessPath = new StringBuffer
+    val currentImps = HashSet[Name]()
 
     // add code for a new object to hold some imports
     def addWrapper() {
-      code.append("object " + impname + "{\n")
-      trailingBraces.append("}\n")
-      accessPath.append("." + impname)
+      val impname = INTERPRETER_IMPORT_WRAPPER
+      code append "object %s {\n".format(impname)
+      trailingBraces append "}\n"
+      accessPath append ("." + impname)
+
       currentImps.clear
     }
 
     addWrapper()
 
-    // loop through previous requests, adding imports
-    // for each one
-    for ((req,handler) <- reqsToUse) {
-          // If the user entered an import, then just use it
-
-          // add an import wrapping level if the import might
-          // conflict with some other import
-          if(handler.importsWildcard ||
-             currentImps.exists(handler.importedNames.contains))
-            if(!currentImps.isEmpty)
-              addWrapper()
-      
-          if (handler.member.isInstanceOf[Import])
-            code.append(handler.member.toString + ";\n")
-
+    // loop through previous requests, adding imports for each one
+    for (ReqAndHandler(req, handler) <- reqsToUse) {
+      handler match {
+        // If the user entered an import, then just use it; add an import wrapping
+        // level if the import might conflict with some other import
+        case x: ImportHandler =>
+          if (x.importsWildcard || (currentImps exists (x.importedNames contains _)))
+            addWrapper()
+          
+          code append (x.member.toString + "\n")
+          
           // give wildcard imports a import wrapper all to their own
-          if(handler.importsWildcard) 
-            addWrapper()  
-          else
-            currentImps ++= handler.importedNames
-
-          // For other requests, import each bound variable.
-          // import them explicitly instead of with _, so that
-          // ambiguity errors will not be generated. Also, quote 
- 	  // the name of the variable, so that we don't need to 
- 	  // handle quoting keywords separately. 
-          for (imv <- handler.boundNames) {
-            if (currentImps.contains(imv))
-              addWrapper()
-            code.append("import ")
-            code.append(req.objectName + req.accessPath + ".`" + imv + "`;\n")
+          if (x.importsWildcard) addWrapper()
+          else currentImps ++= x.importedNames
+
+        // For other requests, import each bound variable.
+        // import them explicitly instead of with _, so that
+        // ambiguity errors will not be generated. Also, quote 
+        // the name of the variable, so that we don't need to 
+        // handle quoting keywords separately. 
+        case x =>
+          for (imv <- x.boundNames) {
+            if (currentImps contains imv) addWrapper()
+        
+            code append ("import %s\n" format (req fullPath imv))
             currentImps += imv
           }
+      }
     }
-
-    addWrapper() // Add one extra wrapper, to prevent warnings
-                 // in the frequent case of redefining
-                 // the value bound in the last interpreter
-                 // request.
-
-    (code.toString, trailingBraces.toString, accessPath.toString)
+    // add one extra wrapper, to prevent warnings in the common case of
+    // redefining the value bound in the last interpreter request.
+    addWrapper()
+    ComputedImports(code.toString, trailingBraces.toString, accessPath.toString)
   }
 
-  /** Parse a line into a sequence of trees. Returns None if the input
-    * is incomplete. */
-  private def parse(line: String): Option[List[Tree]] = {
+  /** Parse a line into a sequence of trees. Returns None if the input is incomplete. */
+  private def parse(line: String): Option[List[Tree]] = {    
     var justNeedsMore = false
     reporter.withIncompleteHandler((pos,msg) => {justNeedsMore = true}) {
       // simple parse: just parse it, nothing else
       def simpleParse(code: String): List[Tree] = {
         reporter.reset
-        val unit =
-          new CompilationUnit(
-            new BatchSourceFile("<console>", code.toCharArray()))
-        val scanner = new compiler.syntaxAnalyzer.UnitParser(unit);
-        val xxx = scanner.templateStatSeq(false);
-        (xxx._2) 
-      }
-      val (trees) = simpleParse(line)
-      if (reporter.hasErrors) {
-        Some(Nil) // the result did not parse, so stop
-      } else if (justNeedsMore) {
-        None
-      } else {
-        Some(trees)
+        val unit = new CompilationUnit(new BatchSourceFile("<console>", code))
+        val scanner = new compiler.syntaxAnalyzer.UnitParser(unit)
+        
+        scanner.templateStatSeq(false)._2
       }
+      val trees = simpleParse(line)
+      
+      if (reporter.hasErrors)   Some(Nil)  // the result did not parse, so stop
+      else if (justNeedsMore)   None
+      else                      Some(trees)
     }
   }
 
   /** Compile an nsc SourceFile.  Returns true if there are
-   *  no compilation errors, or false othrewise.
+   *  no compilation errors, or false otherwise.
    */
-  def compileSources(sources: List[SourceFile]): Boolean = {
-    val cr = new compiler.Run
+  def compileSources(sources: SourceFile*): Boolean = {
     reporter.reset
-    cr.compileSources(sources)
+    new compiler.Run() compileSources sources.toList
     !reporter.hasErrors
   }
 
@@ -435,28 +505,60 @@ class Interpreter(val settings: Settings, out: PrintWriter) {
    *  compilation errors, or false otherwise.
    */
   def compileString(code: String): Boolean =
-    compileSources(List(new BatchSourceFile("<script>", code.toCharArray)))
+    compileSources(new BatchSourceFile("<script>", code))
+  
+  def compileAndSaveRun(label: String, code: String) = {
+    if (isReplDebug) {
+      parse(code) match {
+        case Some(trees)  => trees foreach (t => DBG(compiler.asCompactString(t)))
+        case _            => DBG("Parse error:\n\n" + code)
+      }
+    }
+    val run = new compiler.Run()
+    run.compileSources(List(new BatchSourceFile(label, code)))
+    run
+  }
 
   /** Build a request from the user. <code>trees</code> is <code>line</code>
    *  after being parsed.
    */
-  private def buildRequest(trees: List[Tree], line: String, lineName: String): Request =
-    new Request(line, lineName)
-
-  private def chooseHandler(member: Tree): Option[MemberHandler] =
-    member match {
-      case member: DefDef =>
-          Some(new DefHandler(member))
-      case member: ValDef =>
-          Some(new ValHandler(member))
-      case member at Assign(Ident(_), _) => Some(new AssignHandler(member))
-      case member: ModuleDef => Some(new ModuleHandler(member))
-      case member: ClassDef => Some(new ClassHandler(member))
-      case member: TypeDef => Some(new TypeAliasHandler(member))
-      case member: Import => Some(new ImportHandler(member))
-      case DocDef(_, documented) => chooseHandler(documented)
-      case member => Some(new GenericHandler(member))
+  private def buildRequest(line: String, lineName: String, trees: List[Tree]): Request =
+    new Request(line, lineName, trees)
+
+  private def chooseHandler(member: Tree): MemberHandler = member match {
+    case member: DefDef               => new DefHandler(member)
+    case member: ValDef               => new ValHandler(member)
+    case member at Assign(Ident(_), _)   => new AssignHandler(member)
+    case member: ModuleDef            => new ModuleHandler(member)
+    case member: ClassDef             => new ClassHandler(member)
+    case member: TypeDef              => new TypeAliasHandler(member)
+    case member: Import               => new ImportHandler(member)
+    case DocDef(_, documented)        => chooseHandler(documented)
+    case member                       => new GenericHandler(member)
+  }
+  
+  private def requestFromLine(line: String, synthetic: Boolean): Either[IR.Result, Request] = {
+    val trees = parse(indentCode(line)) match {
+      case None         => return Left(IR.Incomplete)
+      case Some(Nil)    => return Left(IR.Error) // parse error or empty input
+      case Some(trees)  => trees
+    }
+    
+    // use synthetic vars to avoid filling up the resXX slots
+    def varName = if (synthetic) getSynthVarName else getVarName
+
+    // Treat a single bare expression specially. This is necessary due to it being hard to
+    // modify code at a textual level, and it being hard to submit an AST to the compiler.
+    if (trees.size == 1) trees.head match {
+      case _:Assign                         => // we don't want to include assignments
+      case _:TermTree | _:Ident | _:Select  => // ... but do want these as valdefs.
+        return requestFromLine("val %s =\n%s".format(varName, line), synthetic)
+      case _                                =>
     }
+        
+    // figure out what kind of request
+    Right(buildRequest(line, lineNameCreator(), trees))
+  }
 
   /** <p>
    *    Interpret one line of input.  All feedback, including parse errors
@@ -472,55 +574,34 @@ class Interpreter(val settings: Settings, out: PrintWriter) {
    *  @param line ...
    *  @return     ...
    */
-  def interpret(line: String): IR.Result = {
-    if (prevRequests.isEmpty)
-      new compiler.Run // initialize the compiler
-
-    // parse
-    val trees = parse(indentCode(line)) match {
-      case None => return IR.Incomplete
-      case (Some(Nil)) => return IR.Error // parse error or empty input
-      case Some(trees) => trees
-    }
-
-    trees match {
-      case List(_:Assign) => ()
-
-      case List(_:TermTree) | List(_:Ident) | List(_:Select) =>
-        // Treat a single bare expression specially.
-        // This is necessary due to it being hard to modify
-        // code at a textual level, and it being hard to
-        // submit an AST to the compiler.
-        return interpret("val "+newVarName()+" = \n"+line)
-
-      case _ => ()
+  def interpret(line: String): IR.Result = interpret(line, false)
+  def interpret(line: String, synthetic: Boolean): IR.Result = {
+    def loadAndRunReq(req: Request) = {
+      val (result, succeeded) = req.loadAndRun    
+      if (printResults || !succeeded)
+        out print clean(result)
+
+      // book-keeping
+      if (succeeded && !synthetic)
+        recordRequest(req)
+      
+      if (succeeded) IR.Success
+      else IR.Error
     }
-
-    val lineName = newLineName
-
-    // figure out what kind of request
-    val req = buildRequest(trees, line, lineName)
-    if (req eq null) return IR.Error  // a disallowed statement type
-
-    if (!req.compile)
-      return IR.Error  // an error happened during compilation, e.g. a type error
-
-    val (interpreterResultString, succeeded) = req.loadAndRun
-
-    if (printResults || !succeeded) {
-      // print the result
-      out.print(clean(interpreterResultString))
+    
+    if (compiler == null) IR.Error
+    else requestFromLine(line, synthetic) match {
+      case Left(result) => result
+      case Right(req)   => 
+        // null indicates a disallowed statement type; otherwise compile and
+        // fail if false (implying e.g. a type error)
+        if (req == null || !req.compile) IR.Error
+        else loadAndRunReq(req)
     }
-
-    // book-keeping
-    if (succeeded)
-      prevRequests += req
-
-    if (succeeded) IR.Success else IR.Error
   }
 
-  /** A counter used for numbering objects created by <code>bind()</code>. */
-  private var binderNum = 0
+  /** A name creator used for objects created by <code>bind()</code>. */
+  private lazy val newBinder = new NameCreator("binder")
 
   /** Bind a specified name to a specified value.  The name may
    *  later be used by expressions passed to interpret.
@@ -531,30 +612,33 @@ class Interpreter(val settings: Settings, out: PrintWriter) {
    *  @return          an indication of whether the binding succeeded
    */
   def bind(name: String, boundType: String, value: Any): IR.Result = {
-    val binderName = "binder" + binderNum
-    binderNum += 1
-
-    compileString(
-        "object " + binderName +
-        "{ var value: " + boundType + " = _; " +
-        " def set(x: Any) = value=x.asInstanceOf[" + boundType + "]; }")
+    val binderName = newBinder()
 
-    val binderObject =
-      Class.forName(binderName, true, classLoader)
-    val setterMethod =
-      (binderObject
-          .getDeclaredMethods
-          .toList
-          .find(meth => meth.getName == "set")
-          .get)
-    var argsHolder: Array[Any] = null // this roundabout approach is to try and 
-                                      // make sure the value is boxed
-    argsHolder = List(value).toArray
-    setterMethod.invoke(null, argsHolder.asInstanceOf[Array[AnyRef]]: _*)
+    compileString("""
+      |object %s {
+      |  var value: %s = _
+      |  def set(x: Any) = value = x.asInstanceOf[%s]
+      |}
+    """.stripMargin.format(binderName, boundType, boundType))
 
-    interpret("val " + name + " = " + binderName + ".value")
+    val binderObject = loadByName(binderName)
+    val setterMethod = methodByName(binderObject, "set")
+    
+    setterMethod.invoke(null, value.asInstanceOf[AnyRef])
+    interpret("val %s = %s.value".format(name, binderName))
+  }
+  
+  def quietBind(name: String, boundType: String, value: Any): IR.Result = 
+    beQuietDuring { bind(name, boundType, value) }
+
+  /** Reset this interpreter, forgetting all user-specified requests. */
+  def reset() {
+    virtualDirectory.clear
+    resetClassLoader()
+    lineNameCreator.reset()
+    varNameCreator.reset()
+    prevRequests.clear
   }
-
 
   /** <p>
    *    This instance is no longer needed, so release any resources
@@ -562,206 +646,191 @@ class Interpreter(val settings: Settings, out: PrintWriter) {
    *  </p>
    */
   def close() {
-    reporter.flush()
+    reporter.flush
   }
 
   /** A traverser that finds all mentioned identifiers, i.e. things
-   *  that need to be imported.
-   *  It might return extra names.
+   *  that need to be imported.  It might return extra names.
    */
-  private class ImportVarsTraverser(definedVars: List[Name]) extends Traverser {
+  private class ImportVarsTraverser extends Traverser {
     val importVars = new HashSet[Name]()
 
-    override def traverse(ast: Tree) {
-      ast match {
-        case Ident(name) => importVars += name
-        case _ => super.traverse(ast)
-      }
+    override def traverse(ast: Tree) = ast match {
+      // XXX this is obviously inadequate but it's going to require some effort
+      // to get right.
+      case Ident(name) if !(name.toString startsWith "x$")  => importVars += name
+      case _                                                => super.traverse(ast)
     }
   }
 
-
   /** Class to handle one member among all the members included
    *  in a single interpreter request.
    */
   private sealed abstract class MemberHandler(val member: Tree) {
-    val usedNames: List[Name] = {
-      val ivt = new ImportVarsTraverser(boundNames)
-      ivt.traverseTrees(List(member))
+    lazy val usedNames: List[Name] = {
+      val ivt = new ImportVarsTraverser()
+      ivt traverse member
       ivt.importVars.toList
     }
     def boundNames: List[Name] = Nil
-    def valAndVarNames: List[Name] = Nil
-    def defNames: List[Name] = Nil
-    val importsWildcard = false
-    val importedNames: Seq[Name] = Nil
-    val definesImplicit = 
-      member match {
-        case tree:MemberDef =>      
-          tree.mods.hasFlag(symtab.Flags.IMPLICIT)
-        case _ => false
-      }
+    val definesImplicit = cond(member) {
+      case tree: MemberDef => tree.mods hasFlag Flags.IMPLICIT
+    }    
+    def generatesValue: Option[Name] = None
 
     def extraCodeToEvaluate(req: Request, code: PrintWriter) { }
     def resultExtractionCode(req: Request, code: PrintWriter) { }
+
+    override def toString = "%s(used = %s)".format(this.getClass.toString split '.' last, usedNames)
   }
 
   private class GenericHandler(member: Tree) extends MemberHandler(member)
-
+  
   private class ValHandler(member: ValDef) extends MemberHandler(member) {
-    override lazy val boundNames = List(member.name)
-    override def valAndVarNames = boundNames
+    lazy val ValDef(mods, vname, _, _) = member    
+    lazy val prettyName = NameTransformer.decode(vname)
+    lazy val isLazy = mods hasFlag Flags.LAZY
+    
+    override lazy val boundNames = List(vname)
+    override def generatesValue = Some(vname)
     
     override def resultExtractionCode(req: Request, code: PrintWriter) {
-      val vname = member.name
-      if (member.mods.isPublic &&
-          !(isGeneratedVarName(vname) &&
-            req.typeOf(compiler.encode(vname)) == "Unit"))
-      {
-        val prettyName = NameTransformer.decode(vname)
-        code.print(" + \"" + prettyName + ": " + 
-	           string2code(req.typeOf(vname)) +
-	           " = \" + " +
-                   " { val tmp = scala.runtime.ScalaRunTime.stringOf(" +
-	           req.fullPath(vname) + 
-		   "); " +
-                   " (if(tmp.toSeq.contains('\\n')) \"\\n\" else \"\") + tmp + \"\\n\"} ")
-      }
+      val isInternal = isGeneratedVarName(vname) && req.typeOfEnc(vname) == "Unit"
+      if (!mods.isPublic || isInternal) return
+      
+      lazy val extractor = "scala.runtime.ScalaRunTime.stringOf(%s)".format(req fullPath vname)
+      
+      // if this is a lazy val we avoid evaluating it here
+      val resultString = if (isLazy) codegenln(false, "<lazy>") else extractor
+      val codeToPrint =
+        """ + "%s: %s = " + %s""".format(prettyName, string2code(req typeOf vname), resultString)
+      
+      code print codeToPrint
     }
   }
 
   private class DefHandler(defDef: DefDef) extends MemberHandler(defDef) {
-    override lazy val boundNames = List(defDef.name)
-    override def defNames = boundNames
-
-    override def resultExtractionCode(req: Request, code: PrintWriter) {
-      if (defDef.mods.isPublic)
-        code.print("+\""+string2code(defDef.name)+": "+
-		   string2code(req.typeOf(defDef.name))+"\\n\"")
-    }
+    lazy val DefDef(mods, name, _, vparamss, _, _) = defDef
+    override lazy val boundNames = List(name)
+    // true if 0-arity
+    override def generatesValue =
+      if (vparamss.isEmpty || vparamss.head.isEmpty) Some(name)
+      else None
+
+    override def resultExtractionCode(req: Request, code: PrintWriter) =
+      if (mods.isPublic) code print codegenln(name, ": ", req.typeOf(name))
   }
 
   private class AssignHandler(member: Assign) extends MemberHandler(member) {
-    val lhs = member. lhs.asInstanceOf[Ident] // an unfortunate limitation
-
-    val helperName = newTermName(newInternalVarName())
-    override val valAndVarNames = List(helperName)
+    val lhs = member.lhs.asInstanceOf[Ident] // an unfortunate limitation
+    val helperName = newTermName(synthVarNameCreator())
+    override def generatesValue = Some(helperName)
 
-    override def extraCodeToEvaluate(req: Request, code: PrintWriter) { 
-      code.println("val "+helperName+" = "+member.lhs+";")
-    }
+    override def extraCodeToEvaluate(req: Request, code: PrintWriter) =
+      code println """val %s = %s""".format(helperName, lhs)
 
     /** Print out lhs instead of the generated varName */
     override def resultExtractionCode(req: Request, code: PrintWriter) {
-      code.print(" + \"" + lhs + ": " +
-                 string2code(req.typeOf(compiler.encode(helperName))) +
-                 " = \" + " +
-		 string2code(req.fullPath(helperName))
-		 + " + \"\\n\"")
+      val lhsType = string2code(req typeOfEnc helperName)
+      val res = string2code(req fullPath helperName)
+      val codeToPrint = """ + "%s: %s = " + %s + "\n" """.format(lhs, lhsType, res)
+          
+      code println codeToPrint
     }
   }
 
   private class ModuleHandler(module: ModuleDef) extends MemberHandler(module) {
-    override lazy val boundNames = List(module.name)
+    lazy val ModuleDef(mods, name, _) = module
+    override lazy val boundNames = List(name)
+    override def generatesValue = Some(name)
 
-    override def resultExtractionCode(req: Request, code: PrintWriter) {
-      code.println(" + \"defined module " + 
-		   string2code(module.name)
-		   + "\\n\"")
-    }
+    override def resultExtractionCode(req: Request, code: PrintWriter) =
+      code println codegenln("defined module ", name)
   }
 
-  private class ClassHandler(classdef: ClassDef) 
-  extends MemberHandler(classdef) 
-  {
-    override lazy val boundNames =
-      List(classdef.name) :::
-      (if (classdef.mods.hasFlag(Flags.CASE))
-         List(classdef.name.toTermName)
-       else
-         Nil)
-
-    // TODO: MemberDef.keyword does not include "trait";
-    // otherwise it could be used here
-    def keyword: String =
-      if (classdef.mods.isTrait) "trait" else "class"
+  private class ClassHandler(classdef: ClassDef) extends MemberHandler(classdef) {
+    lazy val ClassDef(mods, name, _, _) = classdef
+    override lazy val boundNames = 
+      name :: (if (mods hasFlag Flags.CASE) List(name.toTermName) else Nil)
     
-    override def resultExtractionCode(req: Request, code: PrintWriter) {
-      code.print(
-          " + \"defined " + 
-          keyword + 
-          " " + 
-          string2code(classdef.name) + 
-          "\\n\"")
-    }
+    override def resultExtractionCode(req: Request, code: PrintWriter) =
+      code print codegenln("defined %s %s".format(classdef.keyword, name))
   }
 
-  private class TypeAliasHandler(typeDef: TypeDef) 
-  extends MemberHandler(typeDef) 
-  {
-    override lazy val boundNames =
-      if (typeDef.mods.isPublic && compiler.treeInfo.isAliasTypeDef(typeDef))
-        List(typeDef.name)
-      else
-        Nil
+  private class TypeAliasHandler(typeDef: TypeDef) extends MemberHandler(typeDef) {
+    lazy val TypeDef(mods, name, _, _) = typeDef
+    def isAlias() = mods.isPublic && compiler.treeInfo.isAliasTypeDef(typeDef)
+    override lazy val boundNames = if (isAlias) List(name) else Nil
 
-    override def resultExtractionCode(req: Request, code: PrintWriter) {
-      code.println(" + \"defined type alias " + 
-                   string2code(typeDef.name) + "\\n\"")
-    }
+    override def resultExtractionCode(req: Request, code: PrintWriter) =
+      code println codegenln("defined type alias ", name)
   }
 
   private class ImportHandler(imp: Import) extends MemberHandler(imp) {
-    override def resultExtractionCode(req: Request, code: PrintWriter) {
-      code.println("+ \"" + imp.toString + "\\n\"")
+    lazy val Import(expr, selectors) = imp
+    def targetType = stringToCompilerType(expr.toString) match {
+      case NoType => None
+      case x      => Some(x)
     }
-
+    
+    private def selectorWild    = selectors filter (_.name == USCOREkw)   // wildcard imports, e.g. import foo._
+    private def selectorMasked  = selectors filter (_.rename == USCOREkw) // masking imports, e.g. import foo.{ bar => _ }      
+    private def selectorNames   = selectors map (_.name)
+    private def selectorRenames = selectors map (_.rename) filterNot (_ == null)
+    
     /** Whether this import includes a wildcard import */
-    override val importsWildcard =
-      imp.selectors.map(_._1).contains(nme.USCOREkw)
+    val importsWildcard = selectorWild.nonEmpty
+    
+    /** Complete list of names imported by a wildcard */
+    def wildcardImportedNames: List[Name] = (
+      for (tpe <- targetType ; if importsWildcard) yield
+        tpe.nonPrivateMembers filter (x => x.isMethod && x.isPublic) map (_.name) distinct
+    ).toList.flatten
 
     /** The individual names imported by this statement */
-    override val importedNames: Seq[Name] =
-      for {
-        val (_,sel) <- imp.selectors
-        sel != null
-        sel != nme.USCOREkw
-        val name <- List(sel.toTypeName, sel.toTermName)
-      }
-      yield name
+    /** XXX come back to this and see what can be done with wildcards now that
+     *  we know how to enumerate the identifiers.
+     */
+    val importedNames: List[Name] = 
+      selectorRenames filterNot (_ == USCOREkw) flatMap (x => List(x.toTypeName, x.toTermName))
+    
+    override def resultExtractionCode(req: Request, code: PrintWriter) =
+      code println codegenln(imp.toString)
   }
 
   /** One line of code submitted by the user for interpretation */
-  private class Request(val line: String, val lineName: String) {
-    val trees = parse(line) match {
-      case Some(ts) => ts
-      case None => Nil
-    }
-
+  private class Request(val line: String, val lineName: String, val trees: List[Tree]) {
     /** name to use for the object that will compute "line" */
-    def objectName = lineName + compiler.nme.INTERPRETER_WRAPPER_SUFFIX
+    def objectName = lineName + INTERPRETER_WRAPPER_SUFFIX
 
     /** name of the object that retrieves the result from the above object */
     def resultObjectName = "RequestResult$" + objectName
 
-    val handlers: List[MemberHandler] = trees.flatMap(chooseHandler(_))
+    /** handlers for each tree in this request */
+    val handlers: List[MemberHandler] = trees map chooseHandler
 
     /** all (public) names defined by these statements */
-    val boundNames = (ListSet() ++ handlers.flatMap(_.boundNames)).toList
+    val boundNames = handlers flatMap (_.boundNames)
 
     /** list of names used by this expression */
-    val usedNames: List[Name] = handlers.flatMap(_.usedNames) 
-
-    def myImportsCode = importsCode(Set.empty ++ usedNames)
-
-    /** Code to append to objectName to access anything that
-     *  the request binds.  */
-    val accessPath = myImportsCode._3
+    val usedNames: List[Name] = handlers flatMap (_.usedNames)
+    
+    /** def and val names */
+    def defNames = partialFlatMap(handlers) { case x: DefHandler => x.boundNames }
+    def valueNames = partialFlatMap(handlers) {
+      case x: AssignHandler => List(x.helperName)
+      case x: ValHandler    => boundNames
+      case x: ModuleHandler => List(x.name)
+    }
 
+    /** Code to import bound names from previous lines - accessPath is code to
+      * append to objectName to access anything bound by request.
+      */
+    val ComputedImports(importsPreamble, importsTrailer, accessPath) =
+      importsCode(Set.empty ++ usedNames)
 
     /** Code to access a variable with the specified name */
-    def fullPath(vname: String): String =
-      objectName + accessPath + ".`" + vname + "`"
+    def fullPath(vname: String): String = "%s.`%s`".format(objectName + accessPath, vname)
 
     /** Code to access a variable with the specified name */
     def fullPath(vname: Name): String = fullPath(vname.toString)
@@ -770,186 +839,480 @@ class Interpreter(val settings: Settings, out: PrintWriter) {
     def toCompute = line
 
     /** generate the source code for the object that computes this request */
-    def objectSourceCode: String =
-      stringFrom { code =>
-        // header for the wrapper object
-        code.println("object " + objectName + " {")
-
-        val (importsPreamble, importsTrailer, _) = myImportsCode
-
-        code.print(importsPreamble)
-
-        code.println(indentCode(toCompute))
-
-        handlers.foreach(_.extraCodeToEvaluate(this,code))
-     
-        code.println(importsTrailer)
+    def objectSourceCode: String = stringFromWriter { code => 
+      val preamble = """
+        |object %s {
+        |  %s%s
+      """.stripMargin.format(objectName, importsPreamble, indentCode(toCompute))     
+      val postamble = importsTrailer + "\n}"
+
+      code println preamble
+      handlers foreach { _.extraCodeToEvaluate(this, code) }
+      code println postamble
+    }
 
-        //end the wrapper object
-        code.println(";}")
+    /** generate source code for the object that retrieves the result
+        from objectSourceCode */
+    def resultObjectSourceCode: String = stringFromWriter { code =>
+      /** We only want to generate this code when the result
+       *  is a value which can be referred to as-is.
+       */      
+      val valueExtractor = handlers.last.generatesValue match {
+        case Some(vname) if typeOf contains vname =>
+          """
+          |lazy val scala_repl_value = {
+          |  scala_repl_result
+          |  %s
+          |}""".stripMargin.format(fullPath(vname))
+        case _  => ""
       }
       
-    /** Types of variables defined by this request.  They are computed
-        after compilation of the main object */
-    var typeOf: Map[Name, String] = _
+      // first line evaluates object to make sure constructor is run
+      // initial "" so later code can uniformly be: + etc
+      val preamble = """
+      |object %s {
+      |  %s
+      |  val scala_repl_result: String = {
+      |    %s
+      |    (""
+      """.stripMargin.format(resultObjectName, valueExtractor, objectName + accessPath)
+      
+      val postamble = """
+      |    )
+      |  }
+      |}
+      """.stripMargin
+
+      code println preamble
+      handlers foreach { _.resultExtractionCode(this, code) }
+      code println postamble
+    }
 
-    /** generate source code for the object that retrieves the result
-        from objectSourceCode */
-    def resultObjectSourceCode: String =
-      stringFrom(code => {
-        code.println("object " + resultObjectName)
-        code.println("{ val result: String = {")
-        code.println(objectName + accessPath + ";")  // evaluate the object, to make sure its constructor is run
-        code.print("(\"\"")  // print an initial empty string, so later code can
-                            // uniformly be: + morestuff
-        handlers.foreach(_.resultExtractionCode(this, code))
-        code.println("\n)}")
-        code.println(";}")
-      })
+    // compile the object containing the user's code
+    lazy val objRun = compileAndSaveRun("<console>", objectSourceCode)
+
+    // compile the result-extraction object
+    lazy val extractionObjectRun = compileAndSaveRun("<console>", resultObjectSourceCode)
 
+    lazy val loadedResultObject = loadByName(resultObjectName)
+    
+    def extractionValue(): Option[AnyRef] = {
+      // ensure it has run
+      extractionObjectRun
+      
+      // load it and retrieve the value        
+      try Some(loadedResultObject getMethod "scala_repl_value" invoke loadedResultObject)
+      catch { case _: Exception => None }
+    }
 
     /** Compile the object file.  Returns whether the compilation succeeded.
      *  If all goes well, the "types" map is computed. */
     def compile(): Boolean = {
-      reporter.reset  // without this, error counting is not correct,
-                      // and the interpreter sometimes overlooks compile failures!
+      // error counting is wrong, hence interpreter may overlook failure - so we reset
+      reporter.reset
 
       // compile the main object
-      val objRun = new compiler.Run()
-      //println("source: "+objectSourceCode) //DEBUG
-      objRun.compileSources(
-        List(new BatchSourceFile("<console>", objectSourceCode.toCharArray))
-      )
-      if (reporter.hasErrors) return false
-
+      objRun
+      
+      // bail on error
+      if (reporter.hasErrors)
+        return false
 
       // extract and remember types 
-      typeOf = findTypes(objRun)
+      typeOf
 
       // compile the result-extraction object
-      new compiler.Run().compileSources(
-        List(new BatchSourceFile("<console>", resultObjectSourceCode.toCharArray))
-      )
+      extractionObjectRun
 
       // success
       !reporter.hasErrors
     }
 
-    /** Dig the types of all bound variables out of the compiler run.
-     *
-     *  @param objRun ...
-     *  @return       ...
-     */
-    def findTypes(objRun: compiler.Run): Map[Name, String] = {
-      def valAndVarNames = handlers.flatMap(_.valAndVarNames)
-      def defNames = handlers.flatMap(_.defNames)
-
-      def getTypes(names: List[Name], nameMap: Name=>Name): Map[Name, String] = {
-      /** the outermost wrapper object */
-      val outerResObjSym: Symbol =
-        compiler.definitions.getMember(compiler.definitions.EmptyPackage,
-          newTermName(objectName))
-
-      /** the innermost object inside the wrapper, found by
-        * following accessPath into the outer one. */
-      val resObjSym =
-        (accessPath.split("\\.")).foldLeft(outerResObjSym)((sym,name) =>
-          if(name == "") sym else
-            compiler.atPhase(objRun.typerPhase.next) {
-              sym.info.member(newTermName(name)) })
-
-      names.foldLeft(Map.empty[Name,String])((map, name) => {
-          val rawType =
-            compiler.atPhase(objRun.typerPhase.next) {
-              resObjSym.info.member(name).tpe
-            }
+    def atNextPhase[T](op: => T): T = compiler.atPhase(objRun.typerPhase.next)(op)
+
+    /** The outermost wrapper object */
+    lazy val outerResObjSym: Symbol = getMember(EmptyPackage, newTermName(objectName))
+
+    /** The innermost object inside the wrapper, found by
+      * following accessPath into the outer one. */
+    lazy val resObjSym =
+      accessPath.split("\\.").foldLeft(outerResObjSym) { (sym, name) =>
+        if (name == "") sym else
+        atNextPhase(sym.info member newTermName(name))
+      }
 
+    /* typeOf lookup with encoding */
+    def typeOfEnc(vname: Name) = typeOf(compiler encode vname)
+
+    /** Types of variables defined by this request. */
+    lazy val typeOf: Map[Name, String] = {
+      def getTypes(names: List[Name], nameMap: Name => Name): Map[Name, String] = {
+        names.foldLeft(Map.empty[Name, String]) { (map, name) =>
+          val tp1 = atNextPhase(resObjSym.info.nonPrivateDecl(name).tpe)
           // the types are all =>T; remove the =>
-          val cleanedType= rawType match { 
-            case compiler.PolyType(Nil, rt) => rt
-            case rawType => rawType
+          val tp2 = tp1 match {
+            case PolyType(Nil, tp)  => tp
+            case tp                 => tp
           }
+          // normalize non-public types so we don't see protected aliases like Self
+          val tp3 = compiler.atPhase(objRun.typerPhase)(tp2 match {
+            case TypeRef(_, sym, _) if !sym.isPublic  => tp2.normalize.toString
+            case tp                                   => tp.toString
+          })
 
-          map + (name -> compiler.atPhase(objRun.typerPhase.next) { cleanedType.toString })
-        })
+          map + (name -> tp3)
+        }
       }
 
-      val names1 = getTypes(valAndVarNames, n => compiler.nme.getterToLocal(n))
-      val names2 = getTypes(defNames, identity)
-      names1 ++ names2
+      getTypes(valueNames, nme.getterToLocal(_)) ++ getTypes(defNames, identity)
     }
 
     /** load and run the code using reflection */
     def loadAndRun: (String, Boolean) = {
-      val interpreterResultObject: Class[_] =
-        Class.forName(resultObjectName, true, classLoader)
-      val resultValMethod: java.lang.reflect.Method =
-        interpreterResultObject.getMethod("result")
-      try {
-        (resultValMethod.invoke(interpreterResultObject).toString(),
-             true)
-      } catch {
-        case e =>
-          def caus(e: Throwable): Throwable = 
-            if (e.getCause eq null) e else caus(e.getCause)
-          val orig = caus(e)
-          (stringFrom(str => orig.printStackTrace(str)), false)
+      val resultValMethod: reflect.Method = loadedResultObject getMethod "scala_repl_result"
+      // XXX if wrapperExceptions isn't type-annotated we crash scalac
+      val wrapperExceptions: List[Class[_ <: Throwable]] =
+        List(classOf[InvocationTargetException], classOf[ExceptionInInitializerError])
+      
+      /** We turn off the binding to accomodate ticket #2817 */
+      def onErr: Catcher[(String, Boolean)] = {
+        case t: Throwable if bindLastException =>
+          withoutBindingLastException {
+            quietBind("lastException", "java.lang.Throwable", t)
+            (stringFromWriter(t.printStackTrace(_)), false)
+          }
+      }
+      
+      catching(onErr) {
+        unwrapping(wrapperExceptions: _*) {
+          (resultValMethod.invoke(loadedResultObject).toString, true)
+        }
       }
     }
+    
+    override def toString = "Request(line=%s, %s trees)".format(line, trees.size)
   }
-}
+  
+  /** A container class for methods to be injected into the repl
+   *  in power mode.
+   */
+  object power {
+    lazy val compiler: repl.compiler.type = repl.compiler
+    import compiler.{ phaseNames, atPhase, currentRun }
+    
+    def mkContext(code: String = "") = compiler.analyzer.rootContext(mkUnit(code))
+    def mkAlias(name: String, what: String) = interpret("type %s = %s".format(name, what))
+    def mkSourceFile(code: String) = new BatchSourceFile("<console>", code)
+    def mkUnit(code: String) = new CompilationUnit(mkSourceFile(code))
+
+    def mkTree(code: String): Tree = mkTrees(code).headOption getOrElse EmptyTree
+    def mkTrees(code: String): List[Tree] = parse(code) getOrElse Nil
+    def mkTypedTrees(code: String*): List[compiler.Tree] = {
+      class TyperRun extends compiler.Run {
+        override def stopPhase(name: String) = name == "superaccessors"
+      }
 
-/** Utility methods for the Interpreter. */
-object Interpreter {
-  /** Delete a directory tree recursively.  Use with care!
+      reporter.reset
+      val run = new TyperRun
+      run compileSources (code.toList.zipWithIndex map {
+        case (s, i) => new BatchSourceFile("<console %d>".format(i), s)
+      })
+      run.units.toList map (_.body)
+    }
+    def mkTypedTree(code: String) = mkTypedTrees(code).head
+    def mkType(id: String): compiler.Type = stringToCompilerType(id)
+
+    def dump(): String = (
+      ("Names used: " :: allUsedNames) ++
+      ("\nIdentifiers: " :: unqualifiedIds)
+    ) mkString " "
+    
+    lazy val allPhases: List[Phase] = phaseNames map (currentRun phaseNamed _)
+    def atAllPhases[T](op: => T): List[(String, T)] = allPhases map (ph => (ph.name, atPhase(ph)(op)))
+    def showAtAllPhases(op: => Any): Unit =
+      atAllPhases(op.toString) foreach { case (ph, op) => Console.println("%15s -> %s".format(ph, op take 240)) }
+  }
+  
+  def unleash(): Unit = beQuietDuring {
+    interpret("import scala.tools.nsc._")
+    repl.bind("repl", "scala.tools.nsc.Interpreter", this)
+    interpret("val global: repl.compiler.type = repl.compiler")
+    interpret("val power: repl.power.type = repl.power")
+    // interpret("val replVars = repl.replVars")
+  }
+  
+  /** Artificial object demonstrating completion */
+  // lazy val replVars = CompletionAware(
+  //   Map[String, CompletionAware](
+  //     "ids" -> CompletionAware(() => unqualifiedIds, completionAware _),
+  //     "synthVars" -> CompletionAware(() => allBoundNames filter isSynthVarName map (_.toString)),
+  //     "types" -> CompletionAware(() => allSeenTypes map (_.toString)),
+  //     "implicits" -> CompletionAware(() => allImplicits map (_.toString))
+  //   )
+  // )
+
+  /** Returns the name of the most recent interpreter result.
+   *  Mostly this exists so you can conveniently invoke methods on
+   *  the previous result.
    */
-  private[nsc] def deleteRecursively(path: File) {
-    path match  {
-      case _ if !path.exists =>
-        ()
-      case _ if path.isDirectory =>
-        for (p <- path.listFiles)
-          deleteRecursively(p)
-        path.delete
-      case _ =>
-        path.delete
+  def mostRecentVar: String =
+    if (mostRecentlyHandledTree.isEmpty) ""
+    else mostRecentlyHandledTree.get match {
+      case x: ValOrDefDef           => x.name
+      case Assign(Ident(name), _)   => name
+      case ModuleDef(_, name, _)    => name
+      case _                        => onull(varNameCreator.mostRecent)
     }
+  
+  private def requestForName(name: Name): Option[Request] =
+    prevRequests.reverse find (_.boundNames contains name)
+
+  private def requestForIdent(line: String): Option[Request] = requestForName(newTermName(line))
+  
+  def stringToCompilerType(id: String): compiler.Type = {
+    // if it's a recognized identifier, the type of that; otherwise treat the
+    // String like a value (e.g. scala.collection.Map) .
+    def findType = typeForIdent(id) match {
+      case Some(x)  => definitions.getClass(newTermName(x)).tpe
+      case _        => definitions.getModule(newTermName(id)).tpe
+    }
+
+    try findType catch { case _: MissingRequirementError => NoType }
   }
+    
+  def typeForIdent(id: String): Option[String] =
+    requestForIdent(id) flatMap (x => x.typeOf get newTermName(id))
 
-  /** Heuristically strip interpreter wrapper prefixes
-   *  from an interpreter output string.
+  def methodsOf(name: String) =
+    evalExpr[List[String]](methodsCode(name)) map (x => NameTransformer.decode(getOriginalName(x)))
+  
+  def completionAware(name: String) = {
+    // XXX working around "object is not a value" crash, i.e.
+    // import java.util.ArrayList ; ArrayList.<tab>
+    clazzForIdent(name) flatMap (_ => evalExpr[Option[CompletionAware]](asCompletionAwareCode(name)))
+  }
+    
+  def extractionValueForIdent(id: String): Option[AnyRef] =
+    requestForIdent(id) flatMap (_.extractionValue)
+  
+  /** Executes code looking for a manifest of type T.
    */
-  def stripWrapperGunk(str: String): String = {
-    val wrapregex = "(line[0-9]+\\$object[$.])?(\\$iw[$.])*"
-    str.replaceAll(wrapregex, "")
+  def manifestFor[T: Manifest] =
+    evalExpr[Manifest[T]]("""manifest[%s]""".format(manifest[T]))
+
+  /** Executes code looking for an implicit value of type T.
+   */
+  def implicitFor[T: Manifest] = {
+    val s = manifest[T].toString
+    evalExpr[Option[T]]("{ def f(implicit x: %s = null): %s = x ; Option(f) }".format(s, s))
+    // We don't use implicitly so as to fail without failing.
+    // evalExpr[T]("""implicitly[%s]""".format(manifest[T]))
+  }
+  /** Executes code looking for an implicit conversion from the type
+   *  of the given identifier to CompletionAware.
+   */
+  def completionAwareImplicit[T](id: String) = {
+    val f1string = "%s => %s".format(typeForIdent(id).get, classOf[CompletionAware].getName)
+    val code = """{
+      |  def f(implicit x: (%s) = null): %s = x
+      |  val f1 = f
+      |  if (f1 == null) None else Some(f1(%s))
+      |}""".stripMargin.format(f1string, f1string, id)
+    
+    evalExpr[Option[CompletionAware]](code)
   }
 
-  /** Convert a string into code that can recreate the string.
-   *  This requires replacing all special characters by escape
-   *  codes. It does not add the surrounding " marks.  */
-  def string2code(str: String): String = {
-    /** Convert a character to a backslash-u escape */
-    def char2uescape(c: Char): String = {
-      var rest = c.toInt
-      val buf = new StringBuilder
-      for (i <- 1 to 4) {
-	buf ++= (rest % 16).toHexString
-	rest = rest / 16
+  def clazzForIdent(id: String): Option[Class[_]] =
+    extractionValueForIdent(id) flatMap (x => Option(x) map (_.getClass))
+
+  private def methodsCode(name: String) =
+    "%s.%s(%s)".format(classOf[ReflectionCompletion].getName, "methodsOf", name)
+  
+  private def asCompletionAwareCode(name: String) =
+    "%s.%s(%s)".format(classOf[CompletionAware].getName, "unapply", name)
+
+  private def getOriginalName(name: String): String =
+    nme.originalName(newTermName(name)).toString
+
+  case class InterpreterEvalException(msg: String) extends Exception(msg)
+  def evalError(msg: String) = throw InterpreterEvalException(msg)
+  
+  /** The user-facing eval in :power mode wraps an Option.
+   */
+  def eval[T: Manifest](line: String): Option[T] =
+    try Some(evalExpr[T](line))
+    catch { case InterpreterEvalException(msg) => out println indentString(msg) ; None }
+
+  def evalExpr[T: Manifest](line: String): T = {
+    // Nothing means the type could not be inferred.
+    if (manifest[T] eq Manifest.Nothing)
+      evalError("Could not infer type: try 'eval[SomeType](%s)' instead".format(line))
+    
+    val lhs = getSynthVarName
+    beQuietDuring { interpret("val " + lhs + " = { " + line + " } ") }
+    
+    // TODO - can we meaningfully compare the inferred type T with
+    //   the internal compiler Type assigned to lhs?
+    // def assignedType = prevRequests.last.typeOf(newTermName(lhs))
+
+    val req = requestFromLine(lhs, true) match {
+      case Left(result) => evalError(result.toString)
+      case Right(req)   => req
+    }
+    if (req == null || !req.compile || req.handlers.size != 1)
+      evalError("Eval error.")
+      
+    try req.extractionValue.get.asInstanceOf[T] catch {
+      case e: Exception => evalError(e.getMessage)
+    }
+  }
+  
+  def interpretExpr[T: Manifest](code: String): Option[T] = beQuietDuring {
+    interpret(code) match {
+      case IR.Success =>
+        try prevRequests.last.extractionValue map (_.asInstanceOf[T])
+        catch { case e: Exception => out println e ; None }
+      case _ => None
+    }
+  }
+
+  /** Another entry point for tab-completion, ids in scope */
+  private def unqualifiedIdNames() = partialFlatMap(allHandlers) {
+    case x: AssignHandler => List(x.helperName)
+    case x: ValHandler    => List(x.vname)
+    case x: ModuleHandler => List(x.name)
+    case x: DefHandler    => List(x.name)
+    case x: ImportHandler => x.importedNames
+  } filterNot isSynthVarName
+  
+  /** Types which have been wildcard imported, such as:
+   *    val x = "abc" ; import x._  // type java.lang.String
+   *    import java.lang.String._   // object java.lang.String
+   *
+   *  Used by tab completion.
+   *
+   *  XXX right now this gets import x._ and import java.lang.String._,
+   *  but doesn't figure out import String._.  There's a lot of ad hoc
+   *  scope twiddling which should be swept away in favor of digging
+   *  into the compiler scopes.
+   */
+  def wildcardImportedTypes(): List[Type] = {
+    val xs = allHandlers collect { case x: ImportHandler if x.importsWildcard => x.targetType }
+    xs.flatten.reverse.distinct
+  }
+  
+  /** Another entry point for tab-completion, ids in scope */
+  def unqualifiedIds() = (unqualifiedIdNames() map (_.toString)).distinct.sorted
+
+  /** For static/object method completion */ 
+  def getClassObject(path: String): Option[Class[_]] = classLoader tryToLoadClass path
+  
+  /** Parse the ScalaSig to find type aliases */
+  def aliasForType(path: String) = ByteCode.aliasForType(path)
+
+  // Coming soon  
+  // implicit def string2liftedcode(s: String): LiftedCode = new LiftedCode(s)
+  // case class LiftedCode(code: String) {
+  //   val lifted: String = {
+  //     beQuietDuring { interpret(code) }
+  //     eval2[String]("({ " + code + " }).toString")
+  //   }
+  //   def >> : String = lifted
+  // }
+  
+  // debugging
+  def isReplDebug = settings.Yrepldebug.value
+  def isCompletionDebug = settings.Ycompletion.value
+  def DBG(s: String) = if (isReplDebug) out println s else ()  
+}
+
+/** Utility methods for the Interpreter. */
+object Interpreter {
+  
+  import scala.collection.generic.CanBuildFrom
+  def partialFlatMap[A, B, CC[X] <: Traversable[X]]
+    (coll: CC[A])
+    (pf: PartialFunction[A, CC[B]])
+    (implicit bf: CanBuildFrom[CC[A], B, CC[B]]) =
+  {
+    val b = bf(coll)
+    for (x <- coll collect pf)
+      b ++= x
+
+    b.result
+  }
+  
+  object DebugParam {
+    implicit def tuple2debugparam[T](x: (String, T))(implicit m: Manifest[T]): DebugParam[T] =
+      DebugParam(x._1, x._2)
+    
+    implicit def any2debugparam[T](x: T)(implicit m: Manifest[T]): DebugParam[T] =
+      DebugParam("p" + getCount(), x)
+    
+    private var counter = 0 
+    def getCount() = { counter += 1; counter }
+  }
+  case class DebugParam[T](name: String, param: T)(implicit m: Manifest[T]) {
+    val manifest = m
+    val typeStr = {
+      val str = manifest.toString      
+      // I'm sure there are more to be discovered...
+      val regexp1 = """(.*?)\[(.*)\]""".r
+      val regexp2str = """.*\.type#"""
+      val regexp2 = (regexp2str + """(.*)""").r
+      
+      (str.replaceAll("""\n""", "")) match {
+        case regexp1(clazz, typeArgs) => "%s[%s]".format(clazz, typeArgs.replaceAll(regexp2str, ""))
+        case regexp2(clazz)           => clazz
+        case _                        => str
       }
-      "\\" + "u" + buf.toString.reverse
     }
+  }
+  // provide the enclosing type T
+  //  in order to set up the interpreter's classpath and parent class loader properly
+  def breakIf[T: Manifest](assertion: => Boolean, args: DebugParam[_]*): Unit =
+    if (assertion) break[T](args.toList)
+
+  // start a repl, binding supplied args
+  def break[T: Manifest](args: List[DebugParam[_]]): Unit = {
+    val intLoop = new InterpreterLoop
+    intLoop.settings = new Settings(Console.println)
+    intLoop.settings.embeddedDefaults[T]
+    intLoop.createInterpreter
+    intLoop.in = InteractiveReader.createDefault(intLoop.interpreter)
     
+    // rebind exit so people don't accidentally call System.exit by way of predef
+    intLoop.interpreter.beQuietDuring {
+      intLoop.interpreter.interpret("""def exit = println("Type :quit to resume program execution.")""")
+      for (p <- args) {
+        intLoop.interpreter.bind(p.name, p.typeStr, p.param)
+        Console println "%s: %s".format(p.name, p.typeStr)
+      }
+    }
+    intLoop.repl()
+    intLoop.closeInterpreter
+  }
+  
+  def codegenln(leadingPlus: Boolean, xs: String*): String = codegen(leadingPlus, (xs ++ Array("\n")): _*)
+  def codegenln(xs: String*): String = codegenln(true, xs: _*)
+
+  def codegen(xs: String*): String = codegen(true, xs: _*)
+  def codegen(leadingPlus: Boolean, xs: String*): String = {
+    val front = if (leadingPlus) "+ " else ""
+    front + (xs map string2codeQuoted mkString " + ")
+  }
+  
+  def string2codeQuoted(str: String) = "\"" + string2code(str) + "\""
 
+  /** Convert a string into code that can recreate the string.
+   *  This requires replacing all special characters by escape
+   *  codes. It does not add the surrounding " marks.  */
+  def string2code(str: String): String = {    
     val res = new StringBuilder
-    for (c <- str) {
-      if ("'\"\\" contains c) {
-	res += '\\'
-	res += c
-      } else if (!c.isControl) {
-	res += c
-      } else {
-	res ++= char2uescape(c)
-      }
+    for (c <- str) c match {
+      case '"' | '\'' | '\\'  => res += '\\' ; res += c
+      case _ if c.isControl   => res ++= Chars.char2uescape(c)
+      case _                  => res += c
     }
     res.toString
   }
diff --git a/src/compiler/scala/tools/nsc/InterpreterCommand.scala b/src/compiler/scala/tools/nsc/InterpreterCommand.scala
index 8213ccc..0ac2ef9 100644
--- a/src/compiler/scala/tools/nsc/InterpreterCommand.scala
+++ b/src/compiler/scala/tools/nsc/InterpreterCommand.scala
@@ -1,8 +1,7 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: InterpreterCommand.scala 16894 2009-01-13 13:09:41Z cunei $
 
 package scala.tools.nsc
 
@@ -11,8 +10,7 @@ package scala.tools.nsc
  *  @author  Lex Spoon
  *  @version 1.0
  */
-class InterpreterCommand(arguments: List[String], error: String => Unit)
-extends CompilerCommand(arguments, new Settings(error), error, false) {
+class InterpreterCommand(arguments: List[String], error: String => Unit) extends CompilerCommand(arguments, error) {
   override val cmdName = "scala"
-  override lazy val fileEnding = ".scalaint"
+  override lazy val fileEndings = List(".scalaint")
 }
diff --git a/src/compiler/scala/tools/nsc/InterpreterLoop.scala b/src/compiler/scala/tools/nsc/InterpreterLoop.scala
index 7dd4004..2dbe959 100644
--- a/src/compiler/scala/tools/nsc/InterpreterLoop.scala
+++ b/src/compiler/scala/tools/nsc/InterpreterLoop.scala
@@ -1,17 +1,67 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author Alexander Spoon
  */
-// $Id: InterpreterLoop.scala 16881 2009-01-09 16:28:11Z cunei $
 
 package scala.tools.nsc
 
-import java.io.{BufferedReader, File, FileReader, PrintWriter}
+import Predef.{ println => _, _ }
+import java.io.{ BufferedReader, FileReader, PrintWriter }
 import java.io.IOException
-import java.lang.{ClassLoader, System}
 
-import scala.tools.nsc.{InterpreterResults => IR}
-import scala.tools.nsc.interpreter._
+import scala.tools.nsc.{ InterpreterResults => IR }
+import scala.annotation.tailrec
+import scala.collection.mutable.ListBuffer
+import scala.concurrent.ops
+import util.{ ClassPath }
+import interpreter._
+import io.{ File, Process }
+
+// Classes to wrap up interpreter commands and their results
+// You can add new commands by adding entries to val commands
+// inside InterpreterLoop.
+trait InterpreterControl {
+  self: InterpreterLoop =>
+  
+  // the default result means "keep running, and don't record that line"
+  val defaultResult = Result(true, None)
+  
+  // a single interpreter command
+  sealed abstract class Command extends Function1[List[String], Result] {
+    def name: String
+    def help: String
+    def error(msg: String) = {
+      out.println(":" + name + " " + msg + ".")
+      Result(true, None)
+    }
+    def usage(): String
+  }
+  
+  case class NoArgs(name: String, help: String, f: () => Result) extends Command {
+    def usage(): String = ":" + name
+    def apply(args: List[String]) = if (args.isEmpty) f() else error("accepts no arguments")
+  }
+  
+  case class LineArg(name: String, help: String, f: (String) => Result) extends Command {
+    def usage(): String = ":" + name + " <line>"
+    def apply(args: List[String]) = f(args mkString " ")
+  }
+
+  case class OneArg(name: String, help: String, f: (String) => Result) extends Command {
+    def usage(): String = ":" + name + " <arg>"
+    def apply(args: List[String]) =
+      if (args.size == 1) f(args.head)
+      else error("requires exactly one argument")
+  }
+
+  case class VarArgs(name: String, help: String, f: (List[String]) => Result) extends Command {
+    def usage(): String = ":" + name + " [arg]"
+    def apply(args: List[String]) = f(args)
+  }
+
+  // the result of a single command
+  case class Result(keepRunning: Boolean, lineToRecord: Option[String])
+}
 
 /** The 
  *  <a href="http://scala-lang.org/" target="_top">Scala</a>
@@ -27,36 +77,32 @@ import scala.tools.nsc.interpreter._
  *  @author  Lex Spoon
  *  @version 1.2
  */
-class InterpreterLoop(in0: Option[BufferedReader], out: PrintWriter) {
-  def this(in0: BufferedReader, out: PrintWriter) =
-    this(Some(in0), out)
-
+class InterpreterLoop(in0: Option[BufferedReader], protected val out: PrintWriter) extends InterpreterControl {
+  def this(in0: BufferedReader, out: PrintWriter) = this(Some(in0), out)
   def this() = this(None, new PrintWriter(Console.out))
 
-  /** The input stream from which interpreter commands come */
-  var in: InteractiveReader = _  //set by main()
+  /** The input stream from which commands come, set by main() */
+  var in: InteractiveReader = _
 
   /** The context class loader at the time this object was created */
-  protected val originalClassLoader =
-    Thread.currentThread.getContextClassLoader
+  protected val originalClassLoader = Thread.currentThread.getContextClassLoader
   
-  var settings: Settings = _ // set by main()
-  var interpreter: Interpreter = null // set by createInterpreter()
-  def isettings = interpreter.isettings
+  var settings: Settings = _          // set by main()
+  var interpreter: Interpreter = _    // set by createInterpreter()
+    
+  // classpath entries added via :cp
+  var addedClasspath: String = ""
 
-  /** A reverse list of commands to replay if the user
-    * requests a :replay */
-  var replayCommandsRev: List[String] = Nil
+  /** A reverse list of commands to replay if the user requests a :replay */
+  var replayCommandStack: List[String] = Nil
 
   /** A list of commands to replay if the user requests a :replay */
-  def replayCommands = replayCommandsRev.reverse
+  def replayCommands = replayCommandStack.reverse
 
-  /** Record a command for replay should the user requset a :replay */
-  def addReplay(cmd: String) =
-    replayCommandsRev = cmd :: replayCommandsRev
+  /** Record a command for replay should the user request a :replay */
+  def addReplay(cmd: String) = replayCommandStack ::= cmd
 
-  /** Close the interpreter, if there is one, and set
-    * interpreter to <code>null</code>. */
+  /** Close the interpreter and set the var to <code>null</code>. */
   def closeInterpreter() {
     if (interpreter ne null) {
       interpreter.close
@@ -65,113 +111,157 @@ class InterpreterLoop(in0: Option[BufferedReader], out: PrintWriter) {
     }
   }
 
-  /** Create a new interpreter.  Close the old one, if there
-    * is one. */
+  /** Create a new interpreter. */
   def createInterpreter() {
-    //closeInterpreter()
-
+    if (addedClasspath != "")
+      settings.classpath append addedClasspath
+      
     interpreter = new Interpreter(settings, out) {
-      override protected def parentClassLoader = classOf[InterpreterLoop].getClassLoader
+      override protected def parentClassLoader =
+        settings.explicitParentLoader.getOrElse( classOf[InterpreterLoop].getClassLoader )
     }
     interpreter.setContextClassLoader()
+    // interpreter.quietBind("settings", "scala.tools.nsc.InterpreterSettings", interpreter.isettings)
   }
 
-  /** Bind the settings so that evaluated code can modiy them */
-  def bindSettings() {
-    interpreter.beQuietDuring {
-      interpreter.compileString(InterpreterSettings.sourceCodeForClass)
-	
-      interpreter.bind(
-        "settings",
-        "scala.tools.nsc.InterpreterSettings", 
-        isettings)
-    }
-  }
-
-
   /** print a friendly help message */
-  def printHelp {
-    printWelcome
-    out.println("Type :load followed by a filename to load a Scala file.")
-    out.println("Type :replay to reset execution and replay all previous commands.")
-    out.println("Type :quit to exit the interpreter.")
-  }
+  def printHelp() = {
+    out println "All commands can be abbreviated - for example :he instead of :help.\n"
+    val cmds = commands map (x => (x.usage, x.help))
+    val width: Int = cmds map { case (x, _) => x.length } max
+    val formatStr = "%-" + width + "s %s"
+    cmds foreach { case (usage, help) => out println formatStr.format(usage, help) }
+  } 
   
   /** Print a welcome message */
   def printWelcome() {
-    out.println("Welcome to Scala " + Properties.versionString + " (" + 
-                System.getProperty("java.vm.name") + ", Java " + System.getProperty("java.version") + ")." )
-    out.println("Type in expressions to have them evaluated.")
-    out.println("Type :help for more information.")
-    out.flush()
+    import Properties._
+    val welcomeMsg = 
+     """|Welcome to Scala %s (%s, Java %s).
+        |Type in expressions to have them evaluated.
+        |Type :help for more information.""" .
+    stripMargin.format(versionString, javaVmName, javaVersion)
+        
+    plushln(welcomeMsg)
+  }
+  
+  /** Show the history */
+  def printHistory(xs: List[String]) {
+    val defaultLines = 20
+    
+    if (in.history.isEmpty)
+      return println("No history available.")
+
+    val current = in.history.get.index
+    val count = try xs.head.toInt catch { case _: Exception => defaultLines }
+    val lines = in.historyList takeRight count
+    val offset = current - lines.size + 1
+
+    for ((line, index) <- lines.zipWithIndex)
+      println("%d %s".format(index + offset, line))
+  }
+  
+  /** Some print conveniences */
+  def println(x: Any) = out println x
+  def plush(x: Any) = { out print x ; out.flush() }
+  def plushln(x: Any) = { out println x ; out.flush() }
+  
+  /** Search the history */
+  def searchHistory(_cmdline: String) {
+    val cmdline = _cmdline.toLowerCase
+    
+    if (in.history.isEmpty)
+      return println("No history available.")
+    
+    val current = in.history.get.index
+    val offset = current - in.historyList.size + 1
+    
+    for ((line, index) <- in.historyList.zipWithIndex ; if line.toLowerCase contains cmdline)
+      println("%d %s".format(index + offset, line))
   }
   
   /** Prompt to print when awaiting input */
   val prompt = Properties.shellPromptString
 
+  // most commands do not want to micromanage the Result, but they might want
+  // to print something to the console, so we accomodate Unit and String returns.
+  object CommandImplicits {
+    implicit def u2ir(x: Unit): Result = defaultResult
+    implicit def s2ir(s: String): Result = {
+      out println s
+      defaultResult
+    }
+  }
+  
+  /** Standard commands **/
+  val standardCommands: List[Command] = {
+    import CommandImplicits._
+    List(
+       OneArg("cp", "add an entry (jar or directory) to the classpath", addClasspath),
+       NoArgs("help", "print this help message", printHelp),
+       VarArgs("history", "show the history (optional arg: lines to show)", printHistory),
+       LineArg("h?", "search the history", searchHistory),
+       OneArg("load", "load and interpret a Scala file", load),
+       NoArgs("power", "enable power user mode", power),
+       NoArgs("quit", "exit the interpreter", () => Result(false, None)),
+       NoArgs("replay", "reset execution and replay all previous commands", replay),
+       LineArg("sh", "fork a shell and run a command", runShellCmd),
+       NoArgs("silent", "disable/enable automatic printing of results", verbosity) 
+    )
+  }
+  
+  /** Power user commands */
+  var powerUserOn = false
+  val powerCommands: List[Command] = {
+    import CommandImplicits._
+    List(
+      OneArg("completions", "generate list of completions for a given String", completions),
+      NoArgs("dump", "displays a view of the interpreter's internal state", () => interpreter.power.dump())
+      
+      // VarArgs("tree", "displays ASTs for specified identifiers",
+      //   (xs: List[String]) => interpreter dumpTrees xs)
+      // LineArg("meta", "given code which produces scala code, executes the results",
+      //   (xs: List[String]) => )
+    )
+  }
+  
+  /** Available commands */
+  def commands: List[Command] = standardCommands ::: (if (powerUserOn) powerCommands else Nil)
+
   /** The main read-eval-print loop for the interpreter.  It calls
    *  <code>command()</code> for each line of input, and stops when
    *  <code>command()</code> returns <code>false</code>.
    */
   def repl() {
-    var first = true
-    while (true) {
-      out.flush()
-
-      val line =
-        if (first) {
-          /* For some reason, the first interpreted command always takes
-           * a second or two.  So, wait until the welcome message
-           * has been printed before calling bindSettings.  That way,
-           * the user can read the welcome message while this
-           * command executes.
-           */
-          val futLine = scala.concurrent.ops.future(in.readLine(prompt))
-
-          bindSettings()
-          first = false
-
-          futLine()
-      } else {
-        in.readLine(prompt)
-      }
-
-      if (line eq null)
-        return ()  // assumes null means EOF
-
-      val (keepGoing, finalLineMaybe) = command(line)
-
-      if (!keepGoing)
-        return
-        
-      finalLineMaybe match {
-        case Some(finalLine) => addReplay(finalLine)
-        case None => ()
-      }
+    def readOneLine() = {
+      out.flush
+      in readLine prompt
     }
+    // return false if repl should exit
+    def processLine(line: String): Boolean =
+      if (line eq null) false               // assume null means EOF
+      else command(line) match {
+        case Result(false, _)           => false
+        case Result(_, Some(finalLine)) => addReplay(finalLine) ; true
+        case _                          => true
+      }
+    
+    while (processLine(readOneLine)) { }
   }
 
   /** interpret all lines from a specified file */
-  def interpretAllFrom(filename: String) {
-    val fileIn = try {
-      new FileReader(filename)
-    } catch {
-      case _:IOException =>
-        out.println("Error opening file: " + filename)
-        return
-    }
+  def interpretAllFrom(file: File) {    
     val oldIn = in
-    val oldReplay = replayCommandsRev
-    try {
-      val inFile = new BufferedReader(fileIn)
-      in = new SimpleReader(inFile, out, false)
-      out.println("Loading " + filename + "...")
-      out.flush
-      repl
-    } finally {
+    val oldReplay = replayCommandStack
+    
+    try file applyReader { reader =>
+      in = new SimpleReader(reader, out, false)
+      plushln("Loading " + file + "...")
+      repl()
+    }
+    finally {
       in = oldIn
-      replayCommandsRev = oldReplay
-      fileIn.close
+      replayCommandStack = oldReplay
     }
   }
 
@@ -180,58 +270,195 @@ class InterpreterLoop(in0: Option[BufferedReader], out: PrintWriter) {
     closeInterpreter()
     createInterpreter()
     for (cmd <- replayCommands) {
-      out.println("Replaying: " + cmd)
-      out.flush()  // because maybe cmd will have its own output
+      plushln("Replaying: " + cmd)  // flush because maybe cmd will have its own output
       command(cmd)
       out.println
     }
   }
+    
+  /** fork a shell and run a command */
+  def runShellCmd(line: String) {
+    // we assume if they're using :sh they'd appreciate being able to pipeline
+    interpreter.beQuietDuring {
+      interpreter.interpret("import _root_.scala.tools.nsc.io.Process.Pipe._")
+    }
+    val p = Process(line)
+    // only bind non-empty streams
+    def add(name: String, it: Iterator[String]) =
+      if (it.hasNext) interpreter.bind(name, "scala.List[String]", it.toList)
+    
+    List(("stdout", p.stdout), ("stderr", p.stderr)) foreach (add _).tupled
+  }
+  
+  def withFile(filename: String)(action: File => Unit) {
+    val f = File(filename)
+    
+    if (f.exists) action(f)
+    else out.println("That file does not exist")
+  }
+  
+  def load(arg: String) = {
+    var shouldReplay: Option[String] = None
+    withFile(arg)(f => {
+      interpretAllFrom(f)
+      shouldReplay = Some(":load " + arg)
+    })
+    Result(true, shouldReplay)
+  }
 
-  /** Run one command submitted by the user.  Three values are returned:
+  def addClasspath(arg: String): Unit = {
+    val f = File(arg).normalize
+    if (f.exists) {
+      addedClasspath = ClassPath.join(addedClasspath, f.path)
+      val totalClasspath = ClassPath.join(settings.classpath.value, addedClasspath)
+      println("Added '%s'.  Your new classpath is:\n%s".format(f.path, totalClasspath))
+      replay()
+    }
+    else out.println("The path '" + f + "' doesn't seem to exist.")
+  }
+  
+  def completions(arg: String): Unit = {
+    val comp = in.completion getOrElse { return println("Completion unavailable.") }
+    val xs  = comp completions arg
+
+    injectAndName(xs)
+  }
+  
+  def power() {
+    val powerUserBanner =
+      """** Power User mode enabled - BEEP BOOP      **
+        |** scala.tools.nsc._ has been imported      **
+        |** New vals! Try repl, global, power        **
+        |** New cmds! :help to discover them         **
+        |** New defs! Type power.<tab> to reveal     **""".stripMargin
+
+    powerUserOn = true
+    interpreter.unleash()    
+    injectOne("history", in.historyList)
+    in.completion foreach (x => injectOne("completion", x))
+    out println powerUserBanner
+  }
+  
+  def verbosity() = {
+    val old = interpreter.printResults
+    interpreter.printResults = !old
+    out.println("Switched " + (if (old) "off" else "on") + " result printing.")
+  }
+  
+  /** Run one command submitted by the user.  Two values are returned:
     * (1) whether to keep running, (2) the line to record for replay,
     * if any. */
-  def command(line: String): (Boolean, Option[String]) = {
-    def withFile(command: String)(action: String => Unit) {
-      val spaceIdx = command.indexOf(' ')
-      if (spaceIdx <= 0) {
-        out.println("That command requires a filename to be specified.")
-        return ()
-      }
-      val filename = command.substring(spaceIdx).trim
-      if (! new File(filename).exists) {
-        out.println("That file does not exist")
-        return ()
-      }
-      action(filename)
+  def command(line: String): Result = {
+    def withError(msg: String) = {
+      out println msg
+      Result(true, None)
     }
+    def ambiguous(cmds: List[Command]) = "Ambiguous: did you mean " + cmds.map(":" + _.name).mkString(" or ") + "?"
 
-    val helpRegexp    = ":h(e(l(p)?)?)?"
-    val quitRegexp    = ":q(u(i(t)?)?)?"
-    val loadRegexp    = ":l(o(a(d)?)?)?.*"
-    val replayRegexp  = ":r(e(p(l(a(y)?)?)?)?)?.*"
-
-    var shouldReplay: Option[String] = None
+    // not a command
+    if (!line.startsWith(":")) {
+      // Notice failure to create compiler
+      if (interpreter.compiler == null) return Result(false, None)
+      else return Result(true, interpretStartingWith(line))
+    }
 
-    if (line.matches(helpRegexp))
-      printHelp
-    else if (line.matches(quitRegexp))
-      return (false, None)
-    else if (line.matches(loadRegexp)) {
-      withFile(line)(f => {
-        interpretAllFrom(f)
-        shouldReplay = Some(line)
-      })
+    val tokens = (line drop 1 split """\s+""").toList
+    if (tokens.isEmpty)
+      return withError(ambiguous(commands))
+    
+    val (cmd :: args) = tokens
+    
+    // this lets us add commands willy-nilly and only requires enough command to disambiguate
+    commands.filter(_.name startsWith cmd) match {
+      case List(x)  => x(args)
+      case Nil      => withError("Unknown command.  Type :help for help.")
+      case xs       => withError(ambiguous(xs))
     }
-    else if (line matches replayRegexp)
-      replay
-    else if (line startsWith ":")
-      out.println("Unknown command.  Type :help for help.")
-    else 
-      shouldReplay = interpretStartingWith(line)
+  }
 
-    (true, shouldReplay)
+  private val CONTINUATION_STRING = "     | "
+  private val PROMPT_STRING = "scala> "
+  
+  /** If it looks like they're pasting in a scala interpreter
+   *  transcript, remove all the formatting we inserted so we
+   *  can make some sense of it.
+   */
+  private var pasteStamp: Long = 0
+
+  /** Returns true if it's long enough to quit. */
+  def updatePasteStamp(): Boolean = {
+    /* Enough milliseconds between readLines to call it a day. */
+    val PASTE_FINISH = 1000
+
+    val prevStamp = pasteStamp
+    pasteStamp = System.currentTimeMillis
+    
+    (pasteStamp - prevStamp > PASTE_FINISH)
+  
   }
+  /** TODO - we could look for the usage of resXX variables in the transcript.
+   *  Right now backreferences to auto-named variables will break.
+   */
+  
+  /** The trailing lines complication was an attempt to work around the introduction
+   *  of newlines in e.g. email messages of repl sessions.  It doesn't work because
+   *  an unlucky newline can always leave you with a syntactically valid first line,
+   *  which is executed before the next line is considered.  So this doesn't actually
+   *  accomplish anything, but I'm leaving it in case I decide to try harder.
+   */
+  case class PasteCommand(cmd: String, trailing: ListBuffer[String] = ListBuffer[String]())
   
+  /** Commands start on lines beginning with "scala>" and each successive
+   *  line which begins with the continuation string is appended to that command.
+   *  Everything else is discarded.  When the end of the transcript is spotted,
+   *  all the commands are replayed.
+   */
+  @tailrec private def cleanTranscript(lines: List[String], acc: List[PasteCommand]): List[PasteCommand] = lines match {
+    case Nil                                    => acc.reverse      
+    case x :: xs if x startsWith PROMPT_STRING  =>
+      val first = x stripPrefix PROMPT_STRING
+      val (xs1, xs2) = xs span (_ startsWith CONTINUATION_STRING)
+      val rest = xs1 map (_ stripPrefix CONTINUATION_STRING)
+      val result = (first :: rest).mkString("", "\n", "\n")
+      
+      cleanTranscript(xs2, PasteCommand(result) :: acc)
+      
+    case ln :: lns =>
+      val newacc = acc match {
+        case Nil => Nil
+        case PasteCommand(cmd, trailing) :: accrest =>
+          PasteCommand(cmd, trailing :+ ln) :: accrest
+      }
+      cleanTranscript(lns, newacc)
+  }
+
+  /** The timestamp is for safety so it doesn't hang looking for the end
+   *  of a transcript.  Ad hoc parsing can't be too demanding.  You can
+   *  also use ctrl-D to start it parsing.
+   */
+  @tailrec private def interpretAsPastedTranscript(lines: List[String]) {
+    val line = in.readLine("")
+    val finished = updatePasteStamp()
+
+    if (line == null || finished || line.trim == PROMPT_STRING.trim) {
+      val xs = cleanTranscript(lines.reverse, Nil)
+      println("Replaying %d commands from interpreter transcript." format xs.size)
+      for (PasteCommand(cmd, trailing) <- xs) {
+        out.flush()
+        def runCode(code: String, extraLines: List[String]) {
+          (interpreter interpret code) match {
+            case IR.Incomplete if extraLines.nonEmpty =>
+              runCode(code + "\n" + extraLines.head, extraLines.tail)
+            case _ => ()
+          }
+        }
+        runCode(cmd, trailing.toList)
+      }
+    }
+    else
+      interpretAsPastedTranscript(line :: lines)
+  }
+
   /** Interpret expressions starting with the first line.
     * Read lines until a complete compilation unit is available
     * or until a syntax error has been seen.  If a full unit is
@@ -239,81 +466,149 @@ class InterpreterLoop(in0: Option[BufferedReader], out: PrintWriter) {
     * to be recorded for replay, if any.
     */
   def interpretStartingWith(code: String): Option[String] = {
-    interpreter.interpret(code) match {
-      case IR.Success => Some(code)
-      case IR.Error => None
-      case IR.Incomplete =>
+    // signal completion non-completion input has been received
+    in.completion foreach (_.resetVerbosity())
+    
+    def reallyInterpret = interpreter.interpret(code) match {
+      case IR.Error       => None
+      case IR.Success     => Some(code)
+      case IR.Incomplete  =>
         if (in.interactive && code.endsWith("\n\n")) {
           out.println("You typed two blank lines.  Starting a new command.")
           None
-        } else {
-          val nextLine = in.readLine("     | ")
-          if (nextLine == null)
-            None  // end of file
-          else
-            interpretStartingWith(code + "\n" + nextLine)
+        } 
+        else in.readLine(CONTINUATION_STRING) match {
+          case null =>
+            // we know compilation is going to fail since we're at EOF and the
+            // parser thinks the input is still incomplete, but since this is
+            // a file being read non-interactively we want to fail.  So we send
+            // it straight to the compiler for the nice error message.
+            interpreter.compileString(code)
+            None
+
+          case line => interpretStartingWith(code + "\n" + line)
         }
     }
+    
+    /** Here we place ourselves between the user and the interpreter and examine
+     *  the input they are ostensibly submitting.  We intervene in several cases:
+     * 
+     *  1) If the line starts with "scala> " it is assumed to be an interpreter paste.
+     *  2) If the line starts with "." (but not ".." or "./") it is treated as an invocation
+     *     on the previous result.
+     *  3) If the Completion object's execute returns Some(_), we inject that value
+     *     and avoid the interpreter, as it's likely not valid scala code.
+     */
+    if (code == "") None
+    else if (code startsWith PROMPT_STRING) {
+      updatePasteStamp()
+      interpretAsPastedTranscript(List(code))
+      None
+    }
+    else if (Completion.looksLikeInvocation(code) && interpreter.mostRecentVar != "") {
+      interpretStartingWith(interpreter.mostRecentVar + code)
+    }
+    else {
+      val result = for (comp <- in.completion ; res <- comp execute code) yield res
+      result match {
+        case Some(res)  => injectAndName(res) ; None   // completion took responsibility, so do not parse
+        case _          => reallyInterpret
+      }
+    }
   }
 
-  def loadFiles(settings: Settings) {
-    settings match {
-      case settings: GenericRunnerSettings =>
-        for (filename <- settings.loadfiles.value) {
-          val cmd = ":load " + filename
-          command(cmd)
-          replayCommandsRev = cmd :: replayCommandsRev
-          out.println()
-        }
-      case _ =>
-    }
+  // runs :load <file> on any files passed via -i
+  def loadFiles(settings: Settings) = settings match {
+    case settings: GenericRunnerSettings =>
+      for (filename <- settings.loadfiles.value) {
+        val cmd = ":load " + filename
+        command(cmd)
+        addReplay(cmd)
+        out.println()
+      }
+    case _ =>
   }
 
   def main(settings: Settings) {
     this.settings = settings
-
-    in = 
-      in0 match {
-        case Some(in0) =>
-          new SimpleReader(in0, out, true)
-
-        case None =>
-          val emacsShell = System.getProperty("env.emacs", "") != ""
-          //println("emacsShell="+emacsShell) //debug
-          if (settings.Xnojline.value || emacsShell)
-            new SimpleReader()
-          else
-            InteractiveReader.createDefault()
-      }
-
     createInterpreter()
+    
+    // sets in to some kind of reader depending on environmental cues
+    in = in0 match {
+      case Some(in0)  => new SimpleReader(in0, out, true)
+      case None       =>        
+        // the interpreter is passed as an argument to expose tab completion info
+        if (settings.Xnojline.value || Properties.isEmacsShell) new SimpleReader
+        else if (settings.noCompletion.value) InteractiveReader.createDefault()
+        else InteractiveReader.createDefault(interpreter)
+    }
 
     loadFiles(settings)
-
     try {
-      if (interpreter.reporter.hasErrors) {
-        return // it is broken on startup; go ahead and exit
-      }
+      // it is broken on startup; go ahead and exit
+      if (interpreter.reporter.hasErrors) return
+      
       printWelcome()
+      
+      // this is about the illusion of snappiness.  We call initialize()
+      // which spins off a separate thread, then print the prompt and try 
+      // our best to look ready.  Ideally the user will spend a
+      // couple seconds saying "wow, it starts so fast!" and by the time
+      // they type a command the compiler is ready to roll.
+      interpreter.initialize()
       repl()
-    } finally {
-      closeInterpreter()
     }
+    finally closeInterpreter()
+  }
+  
+  private def objClass(x: Any) = x.asInstanceOf[AnyRef].getClass
+  private def objName(x: Any) = {
+    val clazz = objClass(x)
+    val typeParams = clazz.getTypeParameters
+    val basename = clazz.getName
+    val tpString = if (typeParams.isEmpty) "" else "[%s]".format(typeParams map (_ => "_") mkString ", ")
+
+    basename + tpString
+  }
+
+  // injects one value into the repl; returns pair of name and class
+  def injectOne(name: String, obj: Any): Tuple2[String, String] = {
+    val className = objName(obj)
+    interpreter.quietBind(name, className, obj)
+    (name, className)
+  }
+  def injectAndName(obj: Any): Tuple2[String, String] = {
+    val name = interpreter.getVarName
+    val className = objName(obj)
+    interpreter.bind(name, className, obj)
+    (name, className)
+  }
+  
+  // injects list of values into the repl; returns summary string
+  def injectDebug(args: List[Any]): String = {
+    val strs = 
+      for ((arg, i) <- args.zipWithIndex) yield {
+        val varName = "p" + (i + 1)
+        val (vname, vtype) = injectOne(varName, arg)
+        vname + ": " + vtype
+      }
+    
+    if (strs.size == 0) "Set no variables."
+    else "Variables set:\n" + strs.mkString("\n")
   }
   
   /** process command-line arguments and do as they request */
   def main(args: Array[String]) {
-    def error1(msg: String) { out.println("scala: " + msg) }
-    val command = new InterpreterCommand(List.fromArray(args), error1)
-
-    if (!command.ok || command.settings.help.value || command.settings.Xhelp.value) {
-      // either the command line is wrong, or the user
-      // explicitly requested a help listing
-      if (command.settings.help.value) out.println(command.usageMsg)
-      if (command.settings.Xhelp.value) out.println(command.xusageMsg)
-      out.flush
+    def error1(msg: String) = out println ("scala: " + msg)
+    val command = new InterpreterCommand(args.toList, error1)
+    def neededHelp(): String =
+      (if (command.settings.help.value) command.usageMsg + "\n" else "") +
+      (if (command.settings.Xhelp.value) command.xusageMsg + "\n" else "")
+    
+    // if they asked for no help and command is valid, we call the real main
+    neededHelp() match {
+      case ""     => if (command.ok) main(command.settings) // else nothing
+      case help   => plush(help)
     }
-    else
-      main(command.settings)
   }
 }
diff --git a/src/compiler/scala/tools/nsc/InterpreterResults.scala b/src/compiler/scala/tools/nsc/InterpreterResults.scala
index dba46f3..a5d5ae6 100644
--- a/src/compiler/scala/tools/nsc/InterpreterResults.scala
+++ b/src/compiler/scala/tools/nsc/InterpreterResults.scala
@@ -1,8 +1,7 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: InterpreterResults.scala 16894 2009-01-13 13:09:41Z cunei $
 
 package scala.tools.nsc
 
diff --git a/src/compiler/scala/tools/nsc/InterpreterSettings.scala b/src/compiler/scala/tools/nsc/InterpreterSettings.scala
index e97fe32..1220a8e 100644
--- a/src/compiler/scala/tools/nsc/InterpreterSettings.scala
+++ b/src/compiler/scala/tools/nsc/InterpreterSettings.scala
@@ -1,8 +1,7 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author Alexander Spoon
  */
-// $Id: InterpreterSettings.scala 16881 2009-01-09 16:28:11Z cunei $
 
 package scala.tools.nsc
 
@@ -11,7 +10,7 @@ package scala.tools.nsc
  * @version 1.0
  * @author Lex Spoon, 2007/3/24
  **/
-class InterpreterSettings {
+class InterpreterSettings(repl: Interpreter) {
   /** A list of paths where :load should look */
   var loadPath = List(".")
 
@@ -20,26 +19,55 @@ class InterpreterSettings {
    *  more than this number of characters, then the printout is
    *  truncated.
    */
-  var maxPrintString = 390
+  var maxPrintString = 800
   
-  override def toString =
-    "InterpreterSettings {\n" +
-//    "  loadPath = " + loadPath + "\n" +
-    "  maxPrintString = " + maxPrintString + "\n" +
-    "}"
+  /** The maximum number of completion candidates to print for tab
+   *  completion without requiring confirmation.
+   */
+  var maxAutoprintCompletion = 250
+  
+  /** String unwrapping can be disabled if it is causing issues.
+   *  Settings this to false means you will see Strings like "$iw.$iw.".
+   */
+  var unwrapStrings = true
+  
+  def deprecation_=(x: Boolean) = {
+    val old = repl.settings.deprecation.value
+    repl.settings.deprecation.value = x
+    if (!old && x) println("Enabled -deprecation output.")
+    else if (old && !x) println("Disabled -deprecation output.")
+  }
+  def deprecation: Boolean = repl.settings.deprecation.value
+  
+  def allSettings = Map(
+    "maxPrintString" -> maxPrintString,
+    "maxAutoprintCompletion" -> maxAutoprintCompletion,
+    "unwrapStrings" -> unwrapStrings,
+    "deprecation" -> deprecation
+  )
+  
+  private def allSettingsString =
+    allSettings.toList sortBy (_._1) map { case (k, v) => "  " + k + " = " + v + "\n" } mkString
+    
+  override def toString = """
+    | InterpreterSettings {
+    | %s
+    | }""".stripMargin.format(allSettingsString)
 }
 
-
-
 /* Utilities for the InterpreterSettings class
  *
  * @version 1.0
  * @author Lex Spoon, 2007/5/24
  */
-object InterpreterSettings {
+object InterpreterSettings {  
   /** Source code for the InterpreterSettings class.  This is 
    *  used so that the interpreter is sure to have the code
    *  available.
+   * 
+   *  XXX I'm not seeing why this degree of defensiveness is necessary.
+   *  If files are missing the repl's not going to work, it's not as if
+   *  we have string source backups for anything else.
    */
   val sourceCodeForClass =
 """
@@ -50,7 +78,7 @@ package scala.tools.nsc
  * @version 1.0
  * @author Lex Spoon, 2007/3/24
  **/
-class InterpreterSettings {
+class InterpreterSettings(repl: Interpreter) {
   /** A list of paths where :load should look */
   var loadPath = List(".")
 
@@ -59,7 +87,15 @@ class InterpreterSettings {
    *  more than this number of characters, then the printout is
    *  truncated.
    */
-  var maxPrintString = 390
+  var maxPrintString = 2400
+  
+  def deprecation_=(x: Boolean) = {
+    val old = repl.settings.deprecation.value
+    repl.settings.deprecation.value = x
+    if (!old && x) println("Enabled -deprecation output.")
+    else if (old && !x) println("Disabled -deprecation output.")
+  }
+  def deprecation: Boolean = repl.settings.deprecation.value
   
   override def toString =
     "InterpreterSettings {\n" +
diff --git a/src/compiler/scala/tools/nsc/Main.scala b/src/compiler/scala/tools/nsc/Main.scala
index 5ecf9fd..6cdbd32 100644
--- a/src/compiler/scala/tools/nsc/Main.scala
+++ b/src/compiler/scala/tools/nsc/Main.scala
@@ -1,15 +1,18 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: Main.scala 16881 2009-01-09 16:28:11Z cunei $
 
 package scala.tools.nsc
 
 import java.io.File
+import File.pathSeparator
 
+import scala.tools.nsc.interactive.{ RefinedBuildManager, SimpleBuildManager }
+import scala.tools.nsc.io.AbstractFile
 import scala.tools.nsc.reporters.{Reporter, ConsoleReporter}
-import scala.tools.nsc.util.FakePos //{Position}
+import scala.tools.nsc.util.{ BatchSourceFile, FakePos } //{Position}
+import Properties.{ versionString, copyrightString, residentPromptString, msilLibPath }
 
 /** The main class for NSC, a compiler for the programming
  *  language Scala.
@@ -17,10 +20,10 @@ import scala.tools.nsc.util.FakePos //{Position}
 object Main extends AnyRef with EvalLoop {
 
   val versionMsg = "Scala compiler " +
-    Properties.versionString + " -- " +
-    Properties.copyrightString
+    versionString + " -- " +
+    copyrightString
 
-  val prompt = Properties.residentPromptString
+  val prompt = residentPromptString
 
   var reporter: ConsoleReporter = _
 
@@ -34,27 +37,57 @@ object Main extends AnyRef with EvalLoop {
 
   def resident(compiler: Global) {
     loop { line =>
-      val args = List.fromString(line, ' ')
-      val command = new CompilerCommand(args, new Settings(error), error, true)
-      (new compiler.Run) compile command.files
+      val args = line.split(' ').toList
+      val command = new CompilerCommand(args, new Settings(error))
+      compiler.reporter.reset
+      new compiler.Run() compile command.files
     }
   }
 
   def process(args: Array[String]) {
     val settings = new Settings(error)
     reporter = new ConsoleReporter(settings)
-    val command = new CompilerCommand(List.fromArray(args), settings, error, false)
+    val command = new CompilerCommand(args.toList, settings)
     if (command.settings.version.value)
       reporter.info(null, versionMsg, true)
-    else {
-      if (command.settings.target.value == "msil") {
-        val libpath = System.getProperty("msil.libpath")
-        if (libpath != null)
-          command.settings.assemrefs.value =
-            command.settings.assemrefs.value + File.pathSeparator + libpath
+    else if (command.settings.Yidedebug.value) {
+      command.settings.Xprintpos.value = true
+      command.settings.Yrangepos.value = true
+      val compiler = new interactive.Global(command.settings, reporter)
+      import compiler.{ reporter => _, _ }
+      
+      val sfs = command.files.map(getSourceFile(_))
+      val reloaded = new interactive.Response[Unit]
+      askReload(sfs, reloaded)
+      reloaded.get.right.toOption match {
+        case Some(ex) => reporter.cancelled = true // Causes exit code to be non-0
+        case None => reporter.reset // Causes other compiler errors to be ignored
       }
+      askShutdown
+    } else if (command.settings.Ybuilderdebug.value != "none") {
+      def fileSet(files : List[String]) = Set.empty ++ (files map AbstractFile.getFile) 
+      
+      val buildManager = if (command.settings.Ybuilderdebug.value == "simple")
+        new SimpleBuildManager(settings)
+      else 
+        new RefinedBuildManager(settings)
+  
+      buildManager.addSourceFiles(fileSet(command.files))
+  
+      // enter resident mode
+      loop { line =>
+        val args = line.split(' ').toList
+        val command = new CompilerCommand(args.toList, settings)
+        buildManager.update(fileSet(command.files), Set.empty)
+      }
+    } else {      
+      if (command.settings.target.value == "msil")
+        msilLibPath foreach (x => command.settings.assemrefs.value += (pathSeparator + x))
+
       try {
-        object compiler extends Global(command.settings, reporter)
+        val compiler = if (command.settings.Yrangepos.value) new interactive.Global(command.settings, reporter)
+        else new Global(command.settings, reporter)
+
         if (reporter.hasErrors) {
           reporter.flush()
           return
@@ -69,16 +102,16 @@ object Main extends AnyRef with EvalLoop {
             reporter.info(null, command.usageMsg, true)
             reporter.info(null, compiler.pluginOptionsHelp, true)
           } else {
-            val run = new compiler.Run
+            val run = new compiler.Run()
             run compile command.files
             reporter.printSummary()
           }
         }
       } catch {
         case ex @ FatalError(msg) =>
-          if (command.settings.debug.value)
+          if (true || command.settings.debug.value) // !!!
             ex.printStackTrace();
-        reporter.error(null, "fatal error: " + msg)
+          reporter.error(null, "fatal error: " + msg)
       }
     }
   }
diff --git a/src/compiler/scala/tools/nsc/MainGenericRunner.scala b/src/compiler/scala/tools/nsc/MainGenericRunner.scala
index 1365915..dd30928 100644
--- a/src/compiler/scala/tools/nsc/MainGenericRunner.scala
+++ b/src/compiler/scala/tools/nsc/MainGenericRunner.scala
@@ -1,182 +1,98 @@
 /* NSC -- new Scala compiler
- * Copyright 2006-2009 LAMP/EPFL
+ * Copyright 2006-2010 LAMP/EPFL
  * @author  Lex Spoon
  */
 
-// $Id: MainGenericRunner.scala 16894 2009-01-13 13:09:41Z cunei $
 
 package scala.tools.nsc
 
-import java.io.{File, IOException}
+import java.io.IOException
 import java.lang.{ClassNotFoundException, NoSuchMethodException}
 import java.lang.reflect.InvocationTargetException
-import java.net.URL
+import java.net.{ URL, MalformedURLException }
+import scala.tools.util.PathResolver
 
-import util.ClassPath
+import io.{ File, Process }
+import util.{ ClassPath, ScalaClassLoader }
+import Properties.{ versionString, copyrightString }
 
 /** An object that runs Scala code.  It has three possible
   * sources for the code to run: pre-compiled code, a script file,
   * or interactive entry.
   */
 object MainGenericRunner {
-  /** Append jars found in ${scala.home}/lib to
-   *  a specified classpath.  Also append "." if the
-   *  input classpath is empty; otherwise do not.
-   *
-   *  @param  classpath
-   *  @return ...
-   */
-  private def addClasspathExtras(classpath: String): String = {
-    val scalaHome = Properties.scalaHome
-
-    val extraClassPath =
-      if (scalaHome eq null)
-        ""
-      else {
-        def listDir(name:String):Array[File] = {
-          val libdir = new File(new File(scalaHome), name)
-          if (!libdir.exists || libdir.isFile)
-            Array()
-          else       
-            libdir.listFiles
-        }
-        {
-          val filesInLib = listDir("lib")
-          val jarsInLib = 
-            filesInLib.filter(f => 
-              f.isFile && f.getName.endsWith(".jar"))
-          jarsInLib.toList
-        } ::: {
-          val filesInClasses = listDir("classes")
-          val dirsInClasses = 
-            filesInClasses.filter(f => f.isDirectory)
-          dirsInClasses.toList
-        }
-      }.mkString("", File.pathSeparator, "")
-
-    if (classpath == "")
-      extraClassPath + File.pathSeparator + "."
-    else
-      classpath + File.pathSeparator + extraClassPath
-  }
-
-  def main(args: Array[String]) {
-    def error(str: String) = Console.println(str)
-    val command = new GenericRunnerCommand(args.toList, error)
-
-    val settings = command.settings
-    def sampleCompiler = new Global(settings)
-
-    if (!command.ok) {
-      println(command.usageMsg)
-      println(sampleCompiler.pluginOptionsHelp)
-      return
+  def main(args: Array[String]) {    
+    def errorFn(str: String) = Console println str
+    def exitSuccess: Nothing = exit(0)
+    def exitFailure(msg: Any = null): Nothing = {
+      if (msg != null) errorFn(msg.toString)
+      exit(1)
     }
-
-    settings.classpath.value =
-      addClasspathExtras(settings.classpath.value)
+    def exitCond(b: Boolean): Nothing = if (b) exitSuccess else exitFailure(null)
+    
+    val command = new GenericRunnerCommand(args.toList, errorFn _)
+    import command.settings
+    def sampleCompiler = new Global(settings)   // def so its not created unless needed
     
-    settings.defines.applyToCurrentJVM
+    if (!command.ok)                      return errorFn("%s\n%s".format(command.usageMsg, sampleCompiler.pluginOptionsHelp))
+    else if (settings.version.value)      return errorFn("Scala code runner %s -- %s".format(versionString, copyrightString))
+    else if (command.shouldStopWithInfo)  return errorFn(command getInfoMessage sampleCompiler)
 
-    if (settings.version.value) {
-      Console.println(
-        "Scala code runner " +
-        Properties.versionString + " -- " +
-        Properties.copyrightString)
-      return
-    }
+    def isE   = !settings.execute.isDefault
+    def dashe = settings.execute.value
 
-    if (command.shouldStopWithInfo) {
-      Console.println(command.getInfoMessage(sampleCompiler))
-      return
+    def isI   = !settings.loadfiles.isDefault
+    def dashi = settings.loadfiles.value
+    
+    def combinedCode  = {
+      val files   = if (isI) dashi map (file => File(file).slurp()) else Nil
+      val str     = if (isE) List(dashe) else Nil
+      
+      files ++ str mkString "\n\n"
     }
-  
-    def exitSuccess : Nothing = exit(0)
-    def exitFailure : Nothing = exit(1)
-    def exitCond(b: Boolean) : Nothing = if(b) exitSuccess else exitFailure
 
-    def fileToURL(f: File): Option[URL] =
-      try { Some(f.toURL) }
-      catch { case e => Console.println(e); None }
-
-    def paths(str: String): List[URL] =
-      for (
-        file <- ClassPath.expandPath(str) map (new File(_)) if file.exists;
-        val url = fileToURL(file); if !url.isEmpty
-      ) yield url.get
-
-    def jars(dirs: String): List[URL] =
-      for (
-        libdir <- ClassPath.expandPath(dirs) map (new File(_)) if libdir.isDirectory;
-        jarfile <- libdir.listFiles if jarfile.isFile && jarfile.getName.endsWith(".jar");
-        val url = fileToURL(jarfile); if !url.isEmpty
-      ) yield url.get
-
-    def specToURL(spec: String): Option[URL] =
-      try { Some(new URL(spec)) }
-      catch { case e => Console.println(e); None }
-
-    def urls(specs: String): List[URL] =
-      if (specs == null || specs.length == 0) Nil
-      else for (
-        spec <- specs.split(" ").toList;
-        val url = specToURL(spec); if !url.isEmpty
-      ) yield url.get
-
-    val classpath: List[URL] =
-      paths(settings.bootclasspath.value) :::
-      paths(settings.classpath.value) :::
-      jars(settings.extdirs.value) :::
-      urls(settings.Xcodebase.value)
-
-    command.thingToRun match {
-      case _ if settings.execute.value != "" =>
-        val fullArgs =
-	  command.thingToRun.toList ::: command.arguments
-        exitCond(ScriptRunner.runCommand(settings, 
-		  			 settings.execute.value,
-					 fullArgs))
-
-      case None =>
-        (new InterpreterLoop).main(settings)
+    val classpath: List[URL] = new PathResolver(settings) asURLs
+    
+    /** Was code given in a -e argument? */
+    if (isE) {
+      /** If a -i argument was also given, we want to execute the code after the
+       *  files have been included, so they are read into strings and prepended to
+       *  the code given in -e.  The -i option is documented to only make sense
+       *  interactively so this is a pretty reasonable assumption.
+       *
+       *  This all needs a rewrite though.
+       */
+      val fullArgs = command.thingToRun.toList ::: command.arguments
+
+      exitCond(ScriptRunner.runCommand(settings, combinedCode, fullArgs))
+    }
+    else command.thingToRun match {
+      case None             =>
+        // Questionably, we start the interpreter when there are no arguments.
+        new InterpreterLoop main settings
 
       case Some(thingToRun) =>
         val isObjectName =
           settings.howtorun.value match {
             case "object" => true
             case "script" => false
-            case "guess" =>
-              ObjectRunner.classExists(classpath, thingToRun)
+            case "guess"  => ScalaClassLoader.classExists(classpath, thingToRun)
           }
 
-        if (isObjectName) {
-          try {
-            ObjectRunner.run(classpath, thingToRun, command.arguments)
-          } catch {
-            case e: ClassNotFoundException =>
-              Console.println(e)
-              exitFailure
-            case e: NoSuchMethodException =>
-              Console.println(e)
-              exitFailure
+        if (isObjectName)
+          try ObjectRunner.run(classpath, thingToRun, command.arguments)
+          catch {
+            case e @ (_: ClassNotFoundException | _: NoSuchMethodException) => exitFailure(e)
             case e: InvocationTargetException =>
               e.getCause.printStackTrace
-              exitFailure
+              exitFailure()
           }
-        } else {
-          try {
-            exitCond(ScriptRunner.runScript(settings, 
-					    thingToRun, 
-					    command.arguments))
-          } catch {
-	    case e: IOException =>
-              Console.println(e.getMessage())
-              exitFailure
-            case e: SecurityException =>
-              Console.println(e)
-              exitFailure
+        else
+          try exitCond(ScriptRunner.runScript(settings, thingToRun, command.arguments))
+          catch {
+            case e: IOException       => exitFailure(e.getMessage)
+            case e: SecurityException => exitFailure(e)
           }
-        }
     }
   }
 }
diff --git a/src/compiler/scala/tools/nsc/MainInterpreter.scala b/src/compiler/scala/tools/nsc/MainInterpreter.scala
index 1a59d49..0a0d1e4 100644
--- a/src/compiler/scala/tools/nsc/MainInterpreter.scala
+++ b/src/compiler/scala/tools/nsc/MainInterpreter.scala
@@ -1,8 +1,7 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author Lex Spoon
  */
-// $Id: MainInterpreter.scala 16894 2009-01-13 13:09:41Z cunei $
 
 package scala.tools.nsc
 
diff --git a/src/compiler/scala/tools/nsc/MainTokenMetric.scala b/src/compiler/scala/tools/nsc/MainTokenMetric.scala
index 81ac2d8..c000e54 100644
--- a/src/compiler/scala/tools/nsc/MainTokenMetric.scala
+++ b/src/compiler/scala/tools/nsc/MainTokenMetric.scala
@@ -1,8 +1,7 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: MainTokenMetric.scala 16894 2009-01-13 13:09:41Z cunei $
 
 package scala.tools.nsc
 
@@ -14,27 +13,21 @@ import scala.tools.nsc.reporters.ConsoleReporter
 object MainTokenMetric {
 
   private var reporter: ConsoleReporter = _
-
-  private def tokenMetric(compiler: Global, fnames: List[String]) {
+  
+  def tokenMetric(compiler: Global, fnames: List[String]) {
     import compiler.CompilationUnit
+    import compiler.syntaxAnalyzer.UnitScanner
     import ast.parser.Tokens.EOF
     var totale = 0
     for (source <- fnames) {
-      var i = 0
-      /*
-      import compiler.syntaxAnalyzer.UnitScanner
       val s = new UnitScanner(new CompilationUnit(compiler.getSourceFile(source)))
+      s.nextToken
+      var i = 0
       while (s.token != EOF) {
         i += 1
         s.nextToken
-      }*/
-      var j = 0 ; while(j + Math.log(i) / Math.log(10) < 7) {
-        j += 1
-        Console.print(' ')
       }
-      Console.print(i.toString())
-      Console.print(" ")
-      Console.println(source)
+      Console.println(i.toString + " " + source.toString())
       totale += i
     }
     Console.println(totale.toString()+" total")
@@ -43,7 +36,7 @@ object MainTokenMetric {
   def process(args: Array[String]) {
     val settings = new Settings(error)
     reporter = new ConsoleReporter(settings)
-    val command = new CompilerCommand(List.fromArray(args), settings, error, false)
+    val command = new CompilerCommand(args.toList, settings)
     try {
       val compiler = new Global(command.settings, reporter)
       tokenMetric(compiler, command.files)
diff --git a/src/compiler/scala/tools/nsc/NewLinePrintWriter.scala b/src/compiler/scala/tools/nsc/NewLinePrintWriter.scala
index b21127e..4ced491 100644
--- a/src/compiler/scala/tools/nsc/NewLinePrintWriter.scala
+++ b/src/compiler/scala/tools/nsc/NewLinePrintWriter.scala
@@ -1,8 +1,7 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author Martin Odersky
  */
-// $Id: NewLinePrintWriter.scala 16881 2009-01-09 16:28:11Z cunei $
 
 package scala.tools.nsc
 import java.io.{Writer, PrintWriter}
diff --git a/src/compiler/scala/tools/nsc/NoPhase.scala b/src/compiler/scala/tools/nsc/NoPhase.scala
index ea31cc1..8f5e3e4 100644
--- a/src/compiler/scala/tools/nsc/NoPhase.scala
+++ b/src/compiler/scala/tools/nsc/NoPhase.scala
@@ -1,8 +1,7 @@
 /* NSC -- new Scala compiler
- * Copyright 2007-2009 LAMP/EPFL
+ * Copyright 2007-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: NoPhase.scala 16881 2009-01-09 16:28:11Z cunei $
 
 package scala.tools.nsc
 
diff --git a/src/compiler/scala/tools/nsc/ObjectRunner.scala b/src/compiler/scala/tools/nsc/ObjectRunner.scala
index beb1757..6f6662c 100644
--- a/src/compiler/scala/tools/nsc/ObjectRunner.scala
+++ b/src/compiler/scala/tools/nsc/ObjectRunner.scala
@@ -1,15 +1,13 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Lex Spoon
  */
 
-// $Id: ObjectRunner.scala 16894 2009-01-13 13:09:41Z cunei $
 
 package scala.tools.nsc
 
-import java.lang.{Class, ClassNotFoundException, NoSuchMethodException}
-import java.lang.reflect.{Method, Modifier}
-import java.net.{URL, URLClassLoader}
+import java.net.URL
+import util.ScalaClassLoader
 
 /** An object that runs another object specified by name.
  *
@@ -17,41 +15,10 @@ import java.net.{URL, URLClassLoader}
  *  @version 1.1, 2007/7/13
  */
 object ObjectRunner {
-  /** Create a class loader for the specified class path */
-  private def makeClassLoader(classpath: List[URL]) =
-    new URLClassLoader(classpath.toArray, null)
-
-  /** Look up a class with a given class path. */
-  private def findClass(loader: ClassLoader, objectName: String)
-  : Option[Class[T] forSome { type T }] = 
-  {
-    try {
-      Some(Class.forName(objectName, true, loader))
-    } catch {
-      case e: SecurityException =>
-        Console.println(e.getMessage)
-        None
-      case _: ClassNotFoundException =>
-        None
-    }
-  }
-  
   /** Check whether a class with the specified name
    *  exists on the specified class path. */
-  def classExists(classpath: List[URL], objectName: String): Boolean =
-    !findClass(makeClassLoader(classpath), objectName).isEmpty
-
-  /** Set the Java context class loader while executing an action */
-  def withContextClassLoader[T](loader: ClassLoader)(action: =>T): T = {
-    val oldLoader = Thread.currentThread.getContextClassLoader
-    try {
-      Thread.currentThread.setContextClassLoader(loader)
-      action
-    } finally {
-      Thread.currentThread.setContextClassLoader(oldLoader)
-    }
-  }
-
+  def classExists(urls: List[URL], objectName: String): Boolean =
+    ScalaClassLoader.classExists(urls, objectName)
   
   /** Run a given object, specified by name, using a
    *  specified classpath and argument list.
@@ -59,20 +26,8 @@ object ObjectRunner {
    *  @throws ClassNotFoundException   
    *  @throws NoSuchMethodError         
    *  @throws InvocationTargetException 
-   */
-  def run(classpath: List[URL], objectName: String, arguments: Seq[String]) {
-    val loader = makeClassLoader(classpath)
-    val clsToRun = findClass(loader, objectName) match {
-      case Some(cls) => cls
-      case None => throw new ClassNotFoundException(objectName)
-    }
-
-    val method = clsToRun.getMethod("main", classOf[Array[String]])
-    if ((method.getModifiers & Modifier.STATIC) == 0)
-      throw new NoSuchMethodException(objectName + ".main is not static")
-
-    withContextClassLoader(loader) {
-      method.invoke(null, List(arguments.toArray).toArray: _*)
-    }
+   */  
+  def run(urls: List[URL], objectName: String, arguments: Seq[String]) {
+    (ScalaClassLoader fromURLs urls).run(objectName, arguments)    
   }
 }
diff --git a/src/compiler/scala/tools/nsc/OfflineCompilerCommand.scala b/src/compiler/scala/tools/nsc/OfflineCompilerCommand.scala
index 11b1469..403bbad 100644
--- a/src/compiler/scala/tools/nsc/OfflineCompilerCommand.scala
+++ b/src/compiler/scala/tools/nsc/OfflineCompilerCommand.scala
@@ -1,8 +1,7 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: OfflineCompilerCommand.scala 16894 2009-01-13 13:09:41Z cunei $
 
 package scala.tools.nsc
 
@@ -12,17 +11,16 @@ package scala.tools.nsc
  */
 class OfflineCompilerCommand(
   arguments: List[String],
-  settings: Settings,
-  error: String => Unit, 
-  interactive: Boolean) 
-extends CompilerCommand(arguments, new Settings(error), error, false)
-{
+  settings: Settings)
+extends CompilerCommand(arguments, settings) {
   override val cmdName = "fsc"
-  settings.disable(settings.prompt)
-  settings.disable(settings.resident)
-  new settings.BooleanSetting("-reset", "Reset compile server caches")
-  new settings.BooleanSetting("-shutdown", "Shutdown compile server")
-  new settings.StringSetting("-server", "hostname:portnumber", 
-                             "Specify compile server socket", "")
-  new settings.BooleanSetting("-J<flag>", "Pass <flag> directly to runtime system")
+  import settings._
+  
+  disable(prompt)
+  disable(resident)
+  
+  BooleanSetting("-reset",    "Reset compile server caches")
+  BooleanSetting("-shutdown", "Shutdown compile server")
+  StringSetting ("-server",   "hostname:portnumber", "Specify compile server socket", "")
+  BooleanSetting("-J<flag>",  "Pass <flag> directly to runtime system")
 }
diff --git a/src/compiler/scala/tools/nsc/Phase.scala b/src/compiler/scala/tools/nsc/Phase.scala
index b551a88..6cb66a7 100644
--- a/src/compiler/scala/tools/nsc/Phase.scala
+++ b/src/compiler/scala/tools/nsc/Phase.scala
@@ -1,8 +1,7 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: Phase.scala 16894 2009-01-13 13:09:41Z cunei $
 
 package scala.tools.nsc
 
@@ -25,7 +24,7 @@ abstract class Phase(val prev: Phase) {
   def flagMask: Long = fmask
 
   private var nx: Phase = this
-  if (prev ne null) prev.nx = this
+  if ((prev ne null) && (prev ne NoPhase)) prev.nx = this
 
   def next: Phase = nx
 
@@ -34,8 +33,10 @@ abstract class Phase(val prev: Phase) {
   // Will running with -Ycheck:name work? 
   def checkable: Boolean = true
   def devirtualized: Boolean = false
+  def specialized: Boolean = false
   def erasedTypes: Boolean = false
   def flatClasses: Boolean = false
+  def keepsTypeParams = true
   def run: Unit
 
   override def toString() = name
diff --git a/src/compiler/scala/tools/nsc/PhaseAssembly.scala b/src/compiler/scala/tools/nsc/PhaseAssembly.scala
new file mode 100644
index 0000000..5bc0ce6
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/PhaseAssembly.scala
@@ -0,0 +1,316 @@
+/* NSC -- new Scala compiler
+ * Copyright 2007-2010 LAMP/EPFL
+ * @author Anders Bach Nielsen
+ * @version 1.0
+ */
+
+package scala.tools.nsc
+
+import scala.collection.mutable.{HashSet, HashMap}
+import java.io.{BufferedWriter, FileWriter}
+
+/** 
+ * PhaseAssembly
+ * Trait made to separate the constraint solving of the phase order from
+ * the rest of the compiler. See SIP 00002
+ *   
+ */
+trait PhaseAssembly { self: Global =>
+  
+  /**
+   * Aux datastructure for solving the constraint system
+   * The depency graph container with helper methods for node and edge creation
+   */
+  class DependencyGraph {
+
+    /**
+     * Simple edge with to and from refs
+     */
+    class Edge(var frm: Node, var to: Node, var hard: Boolean) 
+    
+    /**
+     * Simple node with name and object ref for the phase object,
+     * also sets of in and out going dependencies
+     */
+    class Node(name: String) {
+      val phasename = name
+      var phaseobj: Option[List[SubComponent]] = None
+      val after = new HashSet[Edge]()
+      var before = new HashSet[Edge]()
+      var visited = false
+      var level = 0
+
+      def allPhaseNames(): String = phaseobj match {
+        case None => phasename
+        case Some(lst) => lst.map(_.phaseName).reduceLeft(_+","+_)
+      }
+    }
+
+    val nodes = new HashMap[String,Node]()
+    val edges = new HashSet[Edge]()
+
+    /* Given a phase object, get the node for this phase object. If the
+     * node object does not exist, then create it.
+     */
+    def getNodeByPhase(phs: SubComponent): Node = {
+      var node: Node = getNodeByPhase(phs.phaseName)
+      node.phaseobj match {
+        case None =>
+          node.phaseobj = Some(List[SubComponent](phs))
+        case _ =>
+      }
+      node
+    }
+
+    /* Given the name of a phase object, get the node for that name. If the
+     * node object does not exits, then create it.
+     */
+    def getNodeByPhase(name: String): Node =
+      nodes.getOrElseUpdate(name, new Node(name))
+    
+    /* Connect the frm and to nodes with an edge and make it soft.
+     * Also add the edge object to the set of edges, and to the dependency
+     * list of the nodes
+     */
+    def softConnectNodes(frm: Node, to: Node) {
+      var e = new Edge(frm, to, false)
+      this.edges += e
+      
+      frm.after += e
+      to.before += e
+    }
+    
+    /* Connect the frm and to nodes with an edge and make it hard.
+     * Also add the edge object to the set of edges, and to the dependency
+     * list of the nodes
+     */
+    def hardConnectNodes(frm: Node, to: Node) {
+      var e = new Edge(frm, to, true)
+      this.edges += e
+      
+      frm.after += e
+      to.before += e
+    }
+
+    /* Given the entire graph, collect the phase objects at each level, where the phase
+     * names are sorted alphabetical at each level, into the compiler phase list
+     */
+    def compilerPhaseList(): List[SubComponent] =
+      nodes.values.toList filter (_.level > 0) sortBy (x => (x.level, x.phasename)) flatMap (_.phaseobj) flatten
+
+    /* Test if there are cycles in the graph, assign levels to the nodes
+     * and collapse hard links into nodes
+     */
+    def collapseHardLinksAndLevels(node: Node, lvl: Int) {
+      if (node.visited) {
+        throw new FatalError(
+          "Cycle in compiler phase dependencies detected, phase " +
+          node.phasename + " reacted twice!")
+      }
+
+      if (node.level < lvl) node.level = lvl
+      
+      var hls = Nil ++ node.before.filter(_.hard)
+      while (hls.size > 0) {
+        for (hl <- hls) {
+          node.phaseobj = Some(node.phaseobj.get ++ hl.frm.phaseobj.get)
+          node.before = hl.frm.before
+          nodes -= hl.frm.phasename
+          edges -= hl
+          for (edge <- node.before) edge.to = node
+        }
+        hls = Nil ++ node.before.filter(_.hard)
+      }
+      node.visited = true
+      
+      for (edge <- node.before) {
+        collapseHardLinksAndLevels( edge.frm, lvl + 1)
+      }
+
+      node.visited = false
+    }
+
+    /* Find all edges in the given graph that are hard links. For each hard link we
+     * need to check that its the only dependency. If not, then we will promote the
+     * other dependencies down
+     */
+    def validateAndEnforceHardlinks() {
+      var hardlinks = edges.filter(_.hard)
+      for (hl <- hardlinks) {
+        if (hl.frm.after.size > 1) {
+          throw new FatalError("phase " + hl.frm.phasename + " want to run right after " + hl.to.phasename + ", but some phase has declared to run before " + hl.frm.phasename + ". Re-run with -Xgenerate-phase-graph <filename> to better see the problem.")
+        }
+      }
+
+      var rerun = true
+      while (rerun) {
+        rerun = false
+        hardlinks = edges.filter(_.hard)
+        for (hl <- hardlinks) {
+          var sanity = Nil ++ hl.to.before.filter(_.hard)
+          if (sanity.length == 0) {
+            throw new FatalError("There is no runs right after dependency, where there should be one! This is not supposed to happen!")
+          } else if (sanity.length > 1) {
+            var msg = "Multiple phases want to run right after the phase " + sanity.head.to.phasename + "\n"
+            msg += "Phases: "
+            sanity = sanity sortBy (_.frm.phasename)
+            for (edge <- sanity) {
+              msg += edge.frm.phasename + ", "
+            }
+            msg += "\nRe-run with -Xgenerate-phase-graph <filename> to better see the problem."
+            throw new FatalError(msg)
+            
+          } else {
+            
+            var promote = hl.to.before.filter(e => (!e.hard))
+            hl.to.before.clear
+            sanity foreach (edge => hl.to.before += edge)
+            for (edge <- promote) {
+              rerun = true
+              informProgress(
+                "promote the dependency of " + edge.frm.phasename +
+                ": "  + edge.to.phasename + " => " + hl.frm.phasename)
+              edge.to = hl.frm
+              hl.frm.before += edge
+            }
+          }
+        }
+      }
+    }
+
+    /** Remove all nodes in the given graph, that have no phase object
+     *  Make sure to clean up all edges when removing the node object
+     *  <code>Inform</code> with warnings, if an external phase has a
+     *  dependency on something that is dropped.
+     */
+    def removeDanglingNodes() {
+      var dnodes = nodes.valuesIterator filter (_.phaseobj.isEmpty)
+      for (node <- dnodes) {
+        val msg = "dropping dependency on node with no phase object: "+node.phasename
+        informProgress(msg)
+        nodes -= node.phasename
+        for (edge <- node.before) {
+          edges -= edge
+          edge.frm.after -= edge
+          edge.frm.phaseobj match {
+            case Some(lsc) => if (! lsc.head.internal) warning(msg)
+            case _ => 
+          }
+        }
+      }
+    }
+    
+  }
+
+  /* Method called from computePhaseDescriptors in class Global
+   */
+  def buildCompilerFromPhasesSet(): List[SubComponent] = {
+
+    // Add all phases in the set to the graph  
+    val graph = phasesSetToDepGraph(phasesSet)
+
+    // Output the phase dependency graph at this stage
+    if (settings.genPhaseGraph.value != "")
+      graphToDotFile(graph, settings.genPhaseGraph.value + "1.dot")
+
+    // Remove nodes without phaseobj
+    graph.removeDanglingNodes() 
+
+    // Output the phase dependency graph at this stage
+    if (settings.genPhaseGraph.value != "")
+      graphToDotFile(graph, settings.genPhaseGraph.value + "2.dot")
+
+    // Validate and Enforce hardlinks / runsRightAfter and promote nodes down the tree    
+    graph.validateAndEnforceHardlinks()
+
+    // Output the phase dependency graph at this stage
+    if (settings.genPhaseGraph.value != "")
+      graphToDotFile(graph, settings.genPhaseGraph.value + "3.dot")
+
+    // test for cycles, assign levels and collapse hard links into nodes
+    graph.collapseHardLinksAndLevels(graph.getNodeByPhase("parser"), 1)
+
+    // Output the phase dependency graph at this stage
+    if (settings.genPhaseGraph.value != "")
+      graphToDotFile(graph, settings.genPhaseGraph.value + "4.dot")
+    
+    // assemble the compiler
+    graph.compilerPhaseList()
+  }
+
+  /** Given the phases set, will build a dependency graph from the phases set
+   *  Using the aux. method of the DependencyGraph to create nodes and egdes.
+   */
+  private def phasesSetToDepGraph(phsSet: HashSet[SubComponent]): DependencyGraph = {
+    val graph = new DependencyGraph()
+
+    for (phs <- phsSet) {
+      
+      var fromnode = graph.getNodeByPhase(phs)
+      
+      phs.runsRightAfter match {
+        case None =>
+          for (phsname <- phs.runsAfter) {
+            if (phsname != "terminal") {
+              val tonode = graph.getNodeByPhase(phsname)
+              graph.softConnectNodes(fromnode, tonode)
+            } else {
+              error("[phase assembly, after dependency on terminal phase not allowed: " + fromnode.phasename + " => "+ phsname + "]")            
+            }
+          }
+          for (phsname <- phs.runsBefore) {
+            if (phsname != "parser") {
+              val tonode = graph.getNodeByPhase(phsname)
+              graph.softConnectNodes(tonode, fromnode)
+            } else {
+              error("[phase assembly, before dependency on parser phase not allowed: " + phsname + " => "+ fromnode.phasename + "]")            
+            }
+          }
+        case Some(phsname) =>
+          if (phsname != "terminal") {
+            val tonode = graph.getNodeByPhase(phsname)
+            graph.hardConnectNodes(fromnode, tonode)
+          } else {
+            error("[phase assembly, right after dependency on terminal phase not allowed: " + fromnode.phasename + " => "+ phsname + "]")
+          }
+      }
+    }
+    graph
+  }
+
+  /* This is a helper method, that given a dependency graph will generate a graphviz dot
+   * file showing its structure.
+   * Plug-in supplied phases are marked as green nodes and hard links are marked as blue edges.
+   */
+  private def graphToDotFile(graph: DependencyGraph, filename: String) {
+    var sbuf = new StringBuilder
+    var extnodes = new HashSet[graph.Node]()
+    var fatnodes = new HashSet[graph.Node]()
+    sbuf.append("digraph G {\n")
+    for (edge <- graph.edges) {
+      sbuf.append("\"" + edge.frm.allPhaseNames + "(" + edge.frm.level + ")" + "\"->\"" + edge.to.allPhaseNames + "(" + edge.to.level + ")" + "\"")
+      if (! edge.frm.phaseobj.get.head.internal) {
+               extnodes += edge.frm
+      }
+      edge.frm.phaseobj match { case None => null case Some(ln) => if(ln.size > 1) fatnodes += edge.frm }
+      edge.to.phaseobj match { case None => null case Some(ln) => if(ln.size > 1) fatnodes += edge.to }
+      if (edge.hard) {
+        sbuf.append(" [color=\"#0000ff\"]\n")
+      } else {
+        sbuf.append(" [color=\"#000000\"]\n")
+      }
+    }
+    for (node <- extnodes) {
+      sbuf.append("\"" + node.allPhaseNames + "(" + node.level + ")" + "\" [color=\"#00ff00\"]\n")
+    }
+    for (node <- fatnodes) {
+      sbuf.append("\"" + node.allPhaseNames + "(" + node.level + ")" + "\" [color=\"#0000ff\"]\n")
+    }
+    sbuf.append("}\n")
+    var out = new BufferedWriter(new FileWriter(filename))
+    out.write(sbuf.toString)
+    out.flush()
+    out.close()
+  }
+
+}
diff --git a/src/compiler/scala/tools/nsc/Properties.scala b/src/compiler/scala/tools/nsc/Properties.scala
index 533a4ae..47030ef 100644
--- a/src/compiler/scala/tools/nsc/Properties.scala
+++ b/src/compiler/scala/tools/nsc/Properties.scala
@@ -1,73 +1,25 @@
 /* NSC -- new Scala compiler
- * Copyright 2006-2009 LAMP/EPFL
+ * Copyright 2006-2010 LAMP/EPFL
  * @author  Stephane Micheloud
  */
 
-// $Id: Properties.scala 16881 2009-01-09 16:28:11Z cunei $
 
 package scala.tools.nsc
 
-/** A utility to load the compiler properties from a Java properties file
- *  included in the jar.
- */
-object Properties {
-
-  /** The name of the properties file */
-  private val propFilename = "/compiler.properties"
-
-  /** The loaded properties */
-  private val props = {
-    val props = new java.util.Properties
-    val stream = classOf[Global].getResourceAsStream(propFilename)
-    if (stream != null)
-      props.load(stream)
-    props
-  }
-
-  val isWin = System.getProperty("os.name") startsWith "Windows"
-
-  /** The version number of the jar this was loaded from, or
-    * "(unknown)" if it cannot be determined.
-    */
-  val versionString: String = {
-    val defaultString = "(unknown)"
-    "version " + props.getProperty("version.number", defaultString)
-  }
+/** Loads compiler.properties from the jar. */
+object Properties extends scala.util.PropertiesTrait {
+  protected def propCategory    = "compiler"
+  protected def pickJarBasedOn  = classOf[Global]
   
-  val copyrightString: String = {
-    val defaultString = "(c) 2002-2009 LAMP/EPFL"
-    props.getProperty("copyright.string", defaultString)
-  }
-
-  val encodingString: String = {
-    val defaultString = "UTF8" //"ISO-8859-1"
-    props.getProperty("file.encoding", defaultString)
-  }
-
-  val fileEndingString: String = {
-    val defaultString = ".scala|.java"
-    props.getProperty("file.ending", defaultString)  
-  }
-
-  val residentPromptString: String = {
-    val defaultString = "\nnsc> "
-    props.getProperty("resident.prompt", defaultString)    
-  }
-
-  val shellPromptString: String = {
-    val defaultString = "\nscala> "
-    props.getProperty("shell.prompt", defaultString)    
-  }
-
-  val scalaHome: String =
-    System.getProperty("scala.home")
-
-  val envClasspath: String =
-    System.getProperty("env.classpath")
-
-  val cmdName: String =
-    if (isWin) "scala.bat" else "scala"
+  // settings based on jar properties
+  def fileEndingString      = scalaPropOrElse("file.ending", ".scala|.java")
+  def residentPromptString  = scalaPropOrElse("resident.prompt", "\nnsc> ")
+  def shellPromptString     = scalaPropOrElse("shell.prompt", "\nscala> ")
+  
+  // settings based on system properties
+  def msilLibPath           = propOrNone("msil.libpath")
 
-  val msilILasm: String =
-    System.getProperty("msil.ilasm", "")
+  // derived values
+  def isEmacsShell          = propOrEmpty("env.emacs") != ""
+  def fileEndings           = fileEndingString.split("""\|""").toList
 }
diff --git a/src/compiler/scala/tools/nsc/ScalaDoc.scala b/src/compiler/scala/tools/nsc/ScalaDoc.scala
index 02fe086..7c02ec3 100644
--- a/src/compiler/scala/tools/nsc/ScalaDoc.scala
+++ b/src/compiler/scala/tools/nsc/ScalaDoc.scala
@@ -1,92 +1,85 @@
 /* scaladoc, a documentation generator for Scala
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  * @author  Geoffrey Washburn
  */
-// $Id: ScalaDoc.scala 16881 2009-01-09 16:28:11Z cunei $
 
 package scala.tools.nsc
 
 import java.io.File
 
-import scala.tools.nsc.doc.DefaultDocDriver
 import scala.tools.nsc.reporters.{Reporter, ConsoleReporter}
 import scala.tools.nsc.util.FakePos //{Position}
+import Properties.msilLibPath
+import File.pathSeparator
 
-
-/** The main class for scaladoc, a frontend for the Scala compiler 
- * that generates documentation from source files.
+/** The main class for scaladoc, a front-end for the Scala compiler 
+ *  that generates documentation from source files.
  */
 object ScalaDoc {
 
-  val versionMsg = "Scala documentation generator " +
+  val versionMsg: String =
+    "Scaladoc " +
     Properties.versionString + " -- " +
     Properties.copyrightString
 
   var reporter: ConsoleReporter = _
-
-  def error(msg: String) {
-    reporter.error(/*new Position */FakePos("scalac"),
-                   msg + "\n  scalac -help  gives more information")
+  
+  def error(msg: String): Unit = {
+    reporter.error(FakePos("scalac"), msg + "\n  scalac -help  gives more information")
   }
 
-  def process(args: Array[String]) {
-    val docSettings : doc.Settings = new doc.Settings(error)
-    reporter = new ConsoleReporter(docSettings)
-    val command = new CompilerCommand(List.fromArray(args), docSettings, error, false)
-    if (command.settings.version.value)
-      reporter.info(null, versionMsg, true)
-    else {
-      if (command.settings.target.value == "msil") {
-        val libpath = System.getProperty("msil.libpath")
-        if (libpath != null)
-          command.settings.assemrefs.value =
-            command.settings.assemrefs.value + File.pathSeparator + libpath
+  def process(args: Array[String]): Unit = {
+    
+    val docSettings: doc.Settings =
+      new doc.Settings(error)
+    
+    reporter = new ConsoleReporter(docSettings) {
+      override def hasErrors = false // need to do this so that the Global instance doesn't trash all the symbols just because there was an error
+    }
+    
+    val command =
+      new CompilerCommand(args.toList, docSettings)
+      
+    if (!reporter.hasErrors) { // No need to continue if reading the command generated errors
+      
+      if (docSettings.version.value)
+        reporter.info(null, versionMsg, true)
+      else if (docSettings.help.value) {
+        reporter.info(null, command.usageMsg, true)
       }
-      try {
-        object compiler extends Global(command.settings, reporter) {
-	  override val onlyPresentation = true
-	}
-        if (reporter.hasErrors) {
-          reporter.flush()
-          return
-        }
-
-        if (command.settings.help.value || command.settings.Xhelp.value || command.settings.Yhelp.value) {
-          if (command.settings.help.value) {
-              reporter.info(null, command.usageMsg, true)
-            reporter.info(null, compiler.pluginOptionsHelp, true)
-          }
-          if (command.settings.Xhelp.value) 
-            reporter.info(null, command.xusageMsg, true)
-          if (command.settings.Yhelp.value) 
-            reporter.info(null, command.yusageMsg, true)
-        } else if (command.settings.showPlugins.value)
-          reporter.info(null, compiler.pluginDescriptions, true)
-        else if (command.settings.showPhases.value)
-          reporter.info(null, compiler.phaseDescriptions, true)
-        else {
-            val run = new compiler.Run
-            run compile command.files
-            val generator = new DefaultDocDriver {
-              lazy val global: compiler.type = compiler
-              lazy val settings = docSettings
-	    }
-            generator.process(run.units)
-            reporter.printSummary()
-        }
-      } catch {
+      else if (docSettings.Xhelp.value) 
+        reporter.info(null, command.xusageMsg, true)
+      else if (docSettings.Yhelp.value) 
+        reporter.info(null, command.yusageMsg, true)
+      else if (docSettings.showPlugins.value)
+        reporter.warning(null, "Plugins are not available when using Scaladoc")
+      else if (docSettings.showPhases.value)
+        reporter.warning(null, "Phases are restricted when using Scaladoc")
+      else try {
+        
+        if (docSettings.target.value == "msil")
+          msilLibPath foreach (x => docSettings.assemrefs.value += (pathSeparator + x))
+        
+        val docProcessor = new scala.tools.nsc.doc.DocFactory(reporter, docSettings)
+        docProcessor.document(command.files)
+        
+      }
+      catch {
         case ex @ FatalError(msg) =>
-          if (command.settings.debug.value)
-            ex.printStackTrace();
-        reporter.error(null, "fatal error: " + msg)
+          if (docSettings.debug.value) ex.printStackTrace();
+          reporter.error(null, "fatal error: " + msg)
+      }
+      finally {
+        reporter.printSummary()
       }
     }
+    
   }
 
-  def main(args: Array[String]) {
+  def main(args: Array[String]): Unit = {
     process(args)
     exit(if (reporter.hasErrors) 1 else 0)
   }
-
+  
 }
diff --git a/src/compiler/scala/tools/nsc/ScriptRunner.scala b/src/compiler/scala/tools/nsc/ScriptRunner.scala
index 11afa4f..d885397 100644
--- a/src/compiler/scala/tools/nsc/ScriptRunner.scala
+++ b/src/compiler/scala/tools/nsc/ScriptRunner.scala
@@ -1,21 +1,24 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: ScriptRunner.scala 16894 2009-01-13 13:09:41Z cunei $
 
 package scala.tools.nsc
 
-import java.io.{BufferedReader, File, FileInputStream, FileOutputStream,
-                FileReader, InputStreamReader, PrintWriter,
-	        FileWriter, IOException}
+import java.io.{
+  InputStream, OutputStream,
+  BufferedReader, FileInputStream, FileOutputStream,
+  FileReader, InputStreamReader, PrintWriter, FileWriter,
+  IOException
+}
+import java.io.{ File => JFile }
+import io.{ Directory, File, Path, PlainFile }
 import java.lang.reflect.InvocationTargetException
 import java.net.URL
-import java.util.jar.{JarEntry, JarOutputStream}
+import java.util.jar.{ JarEntry, JarOutputStream }
 
-import scala.tools.nsc.io.PlainFile
+import scala.tools.util.PathResolver
 import scala.tools.nsc.reporters.{Reporter,ConsoleReporter}
-import scala.tools.nsc.util.{ClassPath, CompoundSourceFile, BatchSourceFile, SourceFile, SourceFileFragment}
 
 /** An object that runs Scala code in script files.
  *
@@ -44,163 +47,85 @@ import scala.tools.nsc.util.{ClassPath, CompoundSourceFile, BatchSourceFile, Sou
  *           of stdout...
  */
 object ScriptRunner {
+  /* While I'm chasing down the fsc and script bugs. */
+  def DBG(msg: Any) {
+    System.err.println(msg.toString)
+    System.err.flush()
+  }
+  
   /** Default name to use for the wrapped script */
   val defaultScriptMain = "Main"
+  
+  private def addShutdownHook(body: => Unit) =
+    Runtime.getRuntime addShutdownHook new Thread { override def run { body } }
 
   /** Pick a main object name from the specified settings */
-  def scriptMain(settings: Settings) =
-    if (settings.script.value == "")
-      defaultScriptMain
-    else
-      settings.script.value
+  def scriptMain(settings: Settings) = settings.script.value match {
+    case "" => defaultScriptMain
+    case x  => x
+  }
+  
+  def isScript(settings: Settings) = settings.script.value != ""
 
-  /** Choose a jar filename to hold the compiled version
-   * of a script
-   */
+  /** Choose a jar filename to hold the compiled version of a script. */
   private def jarFileFor(scriptFile: String): File = {
-    val filename =
-      if (scriptFile.matches(".*\\.[^.\\\\/]*"))
-        scriptFile.replaceFirst("\\.[^.\\\\/]*$", ".jar")
-      else
-        scriptFile + ".jar"
-
-    new File(filename)
+    val name =
+      if (scriptFile endsWith ".jar") scriptFile
+      else scriptFile + ".jar"
+    
+    File(name)
+  }
+  
+  def copyStreams(in: InputStream, out: OutputStream) = {
+    val buf = new Array[Byte](10240)
+    
+    def loop: Unit = in.read(buf, 0, buf.length) match {
+      case -1 => in.close()
+      case n  => out.write(buf, 0, n) ; loop
+    }
+    
+    loop
   }
 
   /** Try to create a jar file out of all the contents
    *  of the directory <code>sourcePath</code>.
    */
-  private def tryMakeJar(jarFile: File, sourcePath: File) = {
-    try {
-      val jarFileStream = new FileOutputStream(jarFile)
-      val jar = new JarOutputStream(jarFileStream)
-      val buf = new Array[Byte](10240)
-
-      def addFromDir(dir: File, prefix: String) {
-        for (entry <- dir.listFiles) {
-          if (entry.isFile) {
-            jar.putNextEntry(new JarEntry(prefix + entry.getName))
+  private def tryMakeJar(jarFile: File, sourcePath: Directory) = {
+    def addFromDir(jar: JarOutputStream, dir: Directory, prefix: String) {
+      def addFileToJar(entry: File) = {
+        jar putNextEntry new JarEntry(prefix + entry.name)
+        copyStreams(entry.inputStream, jar)
+        jar.closeEntry
+      }
 
-            val input = new FileInputStream(entry)
-            var n = input.read(buf, 0, buf.length)
-            while (n >= 0) {
-              jar.write (buf, 0, n)
-              n = input.read(buf, 0, buf.length)
-            }
-            jar.closeEntry
-            input.close
-          } else {
-            addFromDir(entry, prefix + entry.getName + "/")
-          }
-        }
+      dir.list foreach { entry =>
+        if (entry.isFile) addFileToJar(entry.toFile)
+        else addFromDir(jar, entry.toDirectory, prefix + entry.name + "/")
       }
+    }
 
-      addFromDir(sourcePath, "")
+    try {
+      val jar = new JarOutputStream(jarFile.outputStream())
+      addFromDir(jar, sourcePath, "")
       jar.close
-    } catch {
-      case _:Error => jarFile.delete // XXX what errors to catch?
+    } 
+    catch {
+      case _: Exception => jarFile.delete()
     }
   }
 
-
   /** Read the entire contents of a file as a String. */
-  private def contentsOfFile(filename: String): String = {
-    val strbuf = new StringBuilder
-    val reader = new FileReader(filename)
-    val cbuf = new Array[Char](1024)
-    while(true) {
-      val n = reader.read(cbuf)
-      if (n <= 0)
-        return strbuf.toString
-      strbuf.append(cbuf, 0, n)
-    }
-    throw new Error("impossible")
-  }
-
-  /** Find the length of the header in the specified file, if
-    * there is one.  The header part starts with "#!" or "::#!"
-    * and ends with a line that begins with "!#" or "::!#".
-    */
-  private def headerLength(filename: String): Int = {
-    import java.util.regex._
-
-    val fileContents = contentsOfFile(filename)
-
-    if (!(fileContents.startsWith("#!") || fileContents.startsWith("::#!")))
-      return 0
-
-    val matcher =
-      (Pattern.compile("^(::)?!#.*(\\r|\\n|\\r\\n)", Pattern.MULTILINE)
-              .matcher(fileContents))
-    if (!matcher.find)
-      throw new IOException("script file does not close its header with !# or ::!#")
-    return matcher.end
-  }
+  private def contentsOfFile(filename: String) = File(filename).slurp()
 
   /** Split a fully qualified object name into a
    *  package and an unqualified object name */
-  private def splitObjectName(fullname: String):
-  (Option[String],String) =
-  {
-    val idx = fullname.lastIndexOf('.')
-    if (idx < 0)
-      (None, fullname)
-    else
-      (Some(fullname.substring(0,idx)), fullname.substring(idx+1))
-  }
-
-  /** Code that is added to the beginning of a script file to make
-   *  it a complete Scala compilation unit.
-   */
-  protected def preambleCode(objectName: String) =  {
-    val (maybePack, objName) = splitObjectName(objectName)
-
-    val packageDecl =
-      maybePack match {
-	case Some(pack) => "package " + pack + "\n"
-	case None => ""
-      }
-
-    (packageDecl +
-     "object " + objName + " {\n" +
-     "  def main(argv: Array[String]): Unit = {\n" +
-     "  val args = argv;\n" +
-     "  new AnyRef {\n")
-  }
-
-  /** Code that is added to the end of a script file to make
-   *  it a complete Scala compilation unit.
-   */
-  val endCode = "\n} \n} }\n"
-
-
-  /** Wrap a script file into a runnable object named
-   *  <code>scala.scripting.Main</code>.
-   */
-  def wrappedScript(
-    objectName: String, 
-    filename: String, 
-    getSourceFile: PlainFile => SourceFile): SourceFile = 
-  {
-    val preamble =    
-      new BatchSourceFile("<script preamble>",
-		     preambleCode(objectName).toCharArray)
-
-    val middle = {
-      val f = new File(filename)
-      val bsf = getSourceFile(new PlainFile(f)).asInstanceOf[BatchSourceFile]
-      new SourceFileFragment(
-          bsf,
-          headerLength(filename),
-          bsf.length)
-//          f.length.asInstanceOf[Int])
+  private def splitObjectName(fullname: String): (Option[String], String) =
+    (fullname lastIndexOf '.') match {
+      case -1   => (None, fullname)
+      case idx  => (Some(fullname take idx), fullname drop (idx + 1))
     }
-    val end = new BatchSourceFile("<script trailer>", endCode.toCharArray)
 
-    new CompoundSourceFile(preamble, middle, end)
-  }
-
-  /** Compile a script using the fsc compilation deamon.
+  /** Compile a script using the fsc compilation daemon.
    *
    *  @param settings     ...
    *  @param scriptFileIn ...
@@ -210,54 +135,26 @@ object ScriptRunner {
       settings: GenericRunnerSettings,
       scriptFileIn: String): Boolean =
   {
-    val scriptFile = CompileClient.absFileName(scriptFileIn)
-    for (setting:settings.StringSetting <- List(
-            settings.classpath,
-            settings.sourcepath,
-            settings.bootclasspath,
-            settings.extdirs,
-            settings.outdir))
-      setting.value = CompileClient.absFileNames(setting.value)
+    val scriptFile        = Path(scriptFileIn).toAbsolute.path
+    val compSettingNames  = new Settings(error).visibleSettings.toList map (_.name)
+    val compSettings      = settings.visibleSettings.toList filter (compSettingNames contains _.name)
+    val coreCompArgs      = compSettings flatMap (_.unparse)
+    val compArgs          = coreCompArgs ::: List("-Xscript", scriptMain(settings), scriptFile)
+    var compok            = true
+    
+    val socket = CompileSocket getOrCreateSocket "" getOrElse (return false)
+    socket.applyReaderAndWriter { (in, out) =>
+      out println (CompileSocket getPassword socket.getPort)
+      out println (compArgs mkString "\0")
       
-    val compSettingNames =
-      (new Settings(error)).allSettings.map(_.name)
-
-    val compSettings =
-      settings.allSettings.filter(stg => 
-        compSettingNames.contains(stg.name))
-
-    val coreCompArgs =
-      compSettings.foldLeft[List[String]](Nil)((args, stg) =>
-        stg.unparse ::: args)
-
-    val compArgs = 
-      (coreCompArgs :::
-        List("-Xscript", scriptMain(settings), scriptFile))
-
-    val socket = CompileSocket.getOrCreateSocket("")
-    if (socket eq null)
-      return false
-
-    val out = new PrintWriter(socket.getOutputStream(), true)
-    val in = new BufferedReader(new InputStreamReader(socket.getInputStream()))
-
-    out.println(CompileSocket.getPassword(socket.getPort))
-    out.println(compArgs.mkString("", "\0", ""))
-
-    var compok = true
-
-    var fromServer = in.readLine()
-    while (fromServer ne null) {
-      Console.err.println(fromServer)
-      if (CompileSocket.errorPattern.matcher(fromServer).matches)
-        compok = false
-
-      fromServer = in.readLine()
+      for (fromServer <- (Iterator continually in.readLine()) takeWhile (_ != null)) {
+        Console.err println fromServer
+        if (CompileSocket.errorPattern matcher fromServer matches)
+          compok = false
+      }
+      socket.close()
     }
-    in.close()
-    out.close()
-    socket.close()
-
+    
     compok
   }
 
@@ -267,180 +164,123 @@ object ScriptRunner {
   /** Compile a script and then run the specified closure with
     * a classpath for the compiled script.
     *
-    * @returns true if compilation and the handler succeeds, false otherwise.
+    * @return true if compilation and the handler succeeds, false otherwise.
     */
-  private def withCompiledScript
-        (settings: GenericRunnerSettings, scriptFile: String)
-        (handler: String => Boolean)
-        : Boolean = {
-    import Interpreter.deleteRecursively
- 
-    /* If the script is running on pre-jvm-1.5 JVM, 
-       it is necessary to force the target setting to jvm-1.4 */
-    val major = System.getProperty("java.class.version").split("\\.")(0)
-    if (major.toInt < 49) {
-      settings.target.value = "jvm-1.4"
-    }
-
-    /** Compiles the script file, and returns 
-      * the directory with the compiled class files,
-      * if the compilation succeeded.
-      */
-    def compile: Option[File] = {
-      val compiledPath = File.createTempFile("scalascript", "")
-      compiledPath.delete  // the file is created as a file; make it a directory
-      compiledPath.mkdirs
+  private def withCompiledScript(
+    settings: GenericRunnerSettings,
+    scriptFile: String)
+    (handler: String => Boolean): Boolean =
+  {
+    /** Compiles the script file, and returns the directory with the compiled
+     *  class files, if the compilation succeeded.
+     */
+    def compile: Option[Directory] = {
+      val compiledPath = Directory makeTemp "scalascript"
 
       // delete the directory after the user code has finished
-      Runtime.getRuntime.addShutdownHook(new Thread {
-	override def run { deleteRecursively(compiledPath) }})
+      addShutdownHook(compiledPath.deleteRecursively())
 
-      settings.outdir.value = compiledPath.getPath
+      settings.outdir.value = compiledPath.path
 
       if (settings.nocompdaemon.value) {
+        /** Setting settings.script.value informs the compiler this is not a
+         *  self contained compilation unit.
+         */
+        settings.script.value = scriptMain(settings)
         val reporter = new ConsoleReporter(settings)
         val compiler = newGlobal(settings, reporter)
         val cr = new compiler.Run
-	  val wrapped = 
-	    wrappedScript(
-	      scriptMain(settings), 
-	      scriptFile, 
-	      compiler.getSourceFile _)
-          cr.compileSources(List(wrapped))
-          if (!reporter.hasErrors) 
-	    Some(compiledPath) 
-	  else
-	    None
-      } else {
-        if (compileWithDaemon(settings, scriptFile))
-          Some(compiledPath)
-	else
-	  None
+        
+        cr compile List(scriptFile)
+        if (reporter.hasErrors) None else Some(compiledPath)
       }
+      else if (compileWithDaemon(settings, scriptFile)) Some(compiledPath)
+      else None  	      
     }
 
     if (settings.savecompiled.value) {
       val jarFile = jarFileFor(scriptFile)
-
-      def jarOK = (jarFile.canRead && 
-        (jarFile.lastModified > new File(scriptFile).lastModified))
-
-      if (jarOK) {
-        // pre-compiled jar is current
-        handler(jarFile.getAbsolutePath)
-      } else {
-        // The pre-compiled jar is old.  Recompile the script.
-        jarFile.delete
-
+      def jarOK   = jarFile.canRead && (jarFile isFresher File(scriptFile))
+      
+      def recompile() = {
+        jarFile.delete()
+        
         compile match {
           case Some(compiledPath) =>
             tryMakeJar(jarFile, compiledPath)
             if (jarOK) {
-	      deleteRecursively(compiledPath)  // may as well do it now
-	      handler(jarFile.getAbsolutePath)
-            } else {
-	      // jar failed; run directly from the class files
-	      handler(compiledPath.getPath)
+              compiledPath.deleteRecursively()
+              handler(jarFile.toAbsolute.path)
             }            
-	  case None => false
+            // jar failed; run directly from the class files
+            else handler(compiledPath.path)
+          case _  => false
         }
       }
-    } else {
-      // don't use a cache jar at all--just use the class files
-      compile match {
-	case Some(compiledPath) => handler(compiledPath.getPath)
-	case None => false
-      }
+
+      if (jarOK) handler(jarFile.toAbsolute.path) // pre-compiled jar is current
+      else recompile()                            // jar old - recompile the script.
     }
+    // don't use a cache jar at all--just use the class files
+    else compile map (cp => handler(cp.path)) getOrElse false
   }
 
-
   /** Run a script after it has been compiled 
    *
-   * @returns true if execution succeeded, false otherwise
+   * @return true if execution succeeded, false otherwise
    */
-  private def runCompiled(settings: GenericRunnerSettings,
-			  compiledLocation: String,
-			  scriptArgs: List[String]) : Boolean = {
-    def fileToURL(f: File): Option[URL] =
-      try { Some(f.toURL) }
-    catch { case e => Console.err.println(e); None }
-
-    def paths(str: String, expandStar: Boolean): List[URL] =
-      for (
-        file <- ClassPath.expandPath(str, expandStar) map (new File(_)) if file.exists;
-        val url = fileToURL(file); if !url.isEmpty
-      ) yield url.get
-
-    val classpath =
-      (paths(settings.bootclasspath.value, true) :::
-       paths(compiledLocation, false) :::
-       paths(settings.classpath.value, true))
-
-    try {
-      ObjectRunner.run(
-        classpath,
-        scriptMain(settings),
-        scriptArgs.toArray)
+  private def runCompiled(
+    settings: GenericRunnerSettings,
+		compiledLocation: String,
+		scriptArgs: List[String]): Boolean =
+	{	  
+	  val pr = new PathResolver(settings)
+	  val classpath = File(compiledLocation).toURL +: pr.asURLs
+
+    try { 
+      ObjectRunner.run(classpath, scriptMain(settings), scriptArgs)
       true
-    } catch {
-      case e: ClassNotFoundException =>
-        Console.println(e)
-        false
-      case e: NoSuchMethodException =>
-        Console.println(e)
+    }
+    catch {
+      case e @ (_: ClassNotFoundException | _: NoSuchMethodException) =>
+        Console println e
         false
-      case e:InvocationTargetException =>
+      case e: InvocationTargetException =>
         e.getCause.printStackTrace
         false
     }
   }
 
-
   /** Run a script file with the specified arguments and compilation
    *  settings.
    *
-   * @returns true if compilation and execution succeeded, false otherwise.
+   * @return true if compilation and execution succeeded, false otherwise.
    */
-  def runScript(settings: GenericRunnerSettings,
+  def runScript(
+    settings: GenericRunnerSettings,
 		scriptFile: String,
-		scriptArgs: List[String]) : Boolean = { 
-    val f = new File(scriptFile)
-    if (!f.isFile) {
-      throw new IOException("no such file: " + scriptFile)
-    } else {
-      try {
-	withCompiledScript(settings, scriptFile){compiledLocation =>
-	  runCompiled(settings, compiledLocation, scriptArgs)
-	}
-      } catch {
-	case e => throw e
-      }
-    }
+		scriptArgs: List[String]): Boolean =
+	{	  
+	  if (File(scriptFile).isFile)
+	    withCompiledScript(settings, scriptFile) { runCompiled(settings, _, scriptArgs) }
+	  else
+	    throw new IOException("no such file: " + scriptFile)
   }
 
   /** Run a command 
    *
-   * @returns true if compilation and execution succeeded, false otherwise.
+   * @return true if compilation and execution succeeded, false otherwise.
    */
-  def runCommand(settings: GenericRunnerSettings,
-		 command: String,
-		 scriptArgs: List[String]) : Boolean = {
-    val scriptFile = File.createTempFile("scalacmd", ".scala")
-
+  def runCommand(
+    settings: GenericRunnerSettings,
+    command: String,
+		scriptArgs: List[String]) : Boolean =
+	{    
+    val scriptFile = File.makeTemp("scalacmd", ".scala")
     // save the command to the file
-    {
-      val str = new FileWriter(scriptFile)
-      str.write(command)
-      str.close()
-    }
-
-    try {
-      withCompiledScript(settings, scriptFile.getPath){compiledLocation =>
-        runCompiled(settings, compiledLocation, scriptArgs)
-      } 
-    } catch {
-      case e => throw e
-    } finally scriptFile.delete()  // in case there was a compilation error
+    scriptFile writeAll command
+    
+    try withCompiledScript(settings, scriptFile.path) { runCompiled(settings, _, scriptArgs) }
+    finally scriptFile.delete()  // in case there was a compilation error
   }
 }
diff --git a/src/compiler/scala/tools/nsc/Settings.scala b/src/compiler/scala/tools/nsc/Settings.scala
index bc66b40..8765ad3 100644
--- a/src/compiler/scala/tools/nsc/Settings.scala
+++ b/src/compiler/scala/tools/nsc/Settings.scala
@@ -1,572 +1,14 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: Settings.scala 16919 2009-01-14 14:53:47Z rytz $
 
 package scala.tools.nsc
 
-import java.io.File
-import java.lang.System
-
-class Settings(error: String => Unit) {
+import settings.MutableSettings
 
+/** A compatibility stub.
+ */
+class Settings(errorFn: String => Unit) extends MutableSettings(errorFn) {
   def this() = this(Console.println)
-
-  private var allsettings: List[Setting] = List()
-
-  protected def getProperty(name: String): String =
-    if (System.getProperty(name) != "")
-      System.getProperty(name)
-    else null
-
-  protected val classpathDefault =
-    if (System.getProperty("env.classpath") ne null)
-      alternatePath(
-        getProperty("env.classpath"),
-        ".")
-    else getProperty("java.class.path")
-
-  protected val bootclasspathDefault =
-    alternatePath(
-      concatPath(
-        getProperty("sun.boot.class.path"),
-        guessedScalaBootClassPath),
-      "")
-
-  protected val extdirsDefault =
-    alternatePath(
-      concatPath(
-        getProperty("java.ext.dirs"),
-        guessedScalaExtDirs),
-      "")
-
-  protected val pluginsDirDefault =
-    if (Properties.scalaHome == null)
-      ""
-    else
-      new File(
-        new File(
-          new File(Properties.scalaHome, "misc"),
-          "scala-devel"),
-        "plugins").getAbsolutePath
-
-  protected def alternatePath(p1: String, p2: => String) =
-    if (p1 ne null) p1 else p2
-
-  protected def concatPath(p1: String, p2: String) =
-     if ((p1 ne null) && (p2 ne null)) p1 + File.pathSeparator + p2
-     else if (p1 ne null) p1
-     else p2
-
-  private def guessedScalaBootClassPath = {
-    val scalaHome = Properties.scalaHome
-    if (scalaHome ne null) {
-      val guessJar = new File(new File(new File(scalaHome), "lib"), "scala-library.jar")
-      if (guessJar.isFile()) guessJar.getPath()
-      else {
-        val guessDir = new File(new File(new File(scalaHome), "classes"), "library")
-        if (guessDir.isDirectory()) guessDir.getPath() else null
-      }
-    } else null
-  }
-
-  private def guessedScalaExtDirs = {
-    val scalaHome = Properties.scalaHome
-    if (scalaHome ne null) {
-      val guess = new File(new File(scalaHome), "lib")
-      if (guess.isDirectory()) guess.getPath else null
-    } else null
-  }
-
-  val debuginfo     = new DebugSetting  ("-g", "Specify level of generated debugging info", List("none", "source", "line", "vars", "notailcalls"), "vars", "vars")
-  val nowarnings    = BooleanSetting    ("-nowarn", "Generate no warnings").hideToIDE
-  val verbose       = BooleanSetting    ("-verbose", "Output messages about what the compiler is doing").hideToIDE
-  val deprecation   = BooleanSetting    ("-deprecation", "Output source locations where deprecated APIs are used").hideToIDE
-  val unchecked     = BooleanSetting    ("-unchecked", "Enable detailed unchecked warnings").hideToIDE
-  val classpath     = (new StringSetting ("-classpath", "path", "Specify where to find user class files", classpathDefault) { override val abbreviation = "-cp" }).hideToIDE
-  val sourcepath    = StringSetting     ("-sourcepath", "path", "Specify where to find input source files", "").hideToIDE
-  val bootclasspath = StringSetting     ("-bootclasspath", "path", "Override location of bootstrap class files", bootclasspathDefault).hideToIDE
-  val extdirs       = StringSetting     ("-extdirs", "dirs", "Override location of installed extensions", extdirsDefault).hideToIDE
-  val outdir        = StringSetting     ("-d", "directory", "Specify where to place generated class files", ".").hideToIDE
-  val encoding      = StringSetting     ("-encoding", "encoding", "Specify character encoding used by source files", Properties.encodingString).hideToIDE
-  val target        = ChoiceSetting     ("-target", "Specify for which target object files should be built", List("jvm-1.5", "jvm-1.4", "msil"), "jvm-1.5")
-  val printLate     = BooleanSetting    ("-print", "Print program with all Scala-specific features removed").hideToIDE
-  val XO            = BooleanSetting    ("-optimise", "Generates faster bytecode by applying optimisations to the program")
-  val explaintypes  = BooleanSetting    ("-explaintypes", "Explain type errors in more detail").hideToIDE
-  val uniqid        = BooleanSetting    ("-uniqid", "Print identifiers with unique names for debugging").hideToIDE
-  val version       = BooleanSetting    ("-version", "Print product version and exit").hideToIDE
-  val help          = BooleanSetting    ("-help", "Print a synopsis of standard options").hideToIDE
-  val Xhelp         = BooleanSetting    ("-X", "Print a synopsis of advanced options").hideToIDE
-  val argfiles      = BooleanSetting    ("@<file>", "A text file containing compiler arguments (options and source files)") // only for the help message
-
-  val assemname     = StringSetting     ("-Xassem", "file", "Name of the output assembly (only relevant with -target:msil)", "").dependsOn(target, "msil").hideToIDE
-  val assemrefs     = StringSetting     ("-Xassem-path", "path", "List of assemblies referenced by the program (only relevant with -target:msil)", ".").dependsOn(target, "msil").hideToIDE
-  val Xchecknull    = BooleanSetting    ("-Xcheck-null", "Emit warning on selection of nullable reference")
-  val checkInit     = BooleanSetting    ("-Xcheckinit", "Add runtime checks on field accessors. Uninitialized accesses result in an exception being thrown.")
-  val noassertions  = BooleanSetting    ("-Xdisable-assertions", "Generate no assertions and assumptions")
-  val Xexperimental = BooleanSetting    ("-Xexperimental", "Enable experimental extensions")
-  val XlogImplicits = BooleanSetting    ("-Xlog-implicits", "Show more info on why some implicits are not applicable")
-  val Xnojline      = new BooleanSetting("-Xnojline", "Do not use JLine for editing").hideToIDE
-  val nouescape     = BooleanSetting    ("-Xno-uescape", "Disables handling of \\u unicode escapes") 
-  val plugin        = MultiStringSetting("-Xplugin", "file", "Load a plugin from a file")
-  val disable       = MultiStringSetting("-Xplugin-disable", "plugin", "Disable a plugin")
-  val showPlugins   = BooleanSetting    ("-Xplugin-list", "Print a synopsis of loaded plugins").hideToIDE
-  val pluginOptions = new MultiStringSetting("-P", "plugin:opt", "Pass an option to a plugin") { override def helpSyntax = "-P:<plugin>:<opt>" }
-  val require       = MultiStringSetting("-Xplugin-require", "plugin", "Abort unless a plugin is available")
-  val pluginsDir    = StringSetting     ("-Xpluginsdir", "path", "Location to find compiler plugins", pluginsDirDefault)
-  val print         = PhasesSetting     ("-Xprint", "Print out program after")
-  val Xprintpos     = BooleanSetting    ("-Xprint-pos", "Print tree positions (as offsets)").hideToIDE
-  val printtypes    = BooleanSetting    ("-Xprint-types", "Print tree types (debugging option)").hideToIDE
-  val prompt        = BooleanSetting    ("-Xprompt", "Display a prompt after each error (debugging option)").hideToIDE
-  val resident      = BooleanSetting    ("-Xresident", "Compiler stays resident, files to compile are read from standard input").hideToIDE
-  val Xshowcls      = StringSetting     ("-Xshow-class", "class", "Show class info", "").hideToIDE
-  val Xshowobj      = StringSetting     ("-Xshow-object", "object", "Show object info", "").hideToIDE
-  val showPhases    = BooleanSetting    ("-Xshow-phases", "Print a synopsis of compiler phases").hideToIDE
-  val sourceReader  = StringSetting     ("-Xsource-reader", "classname", "Specify a custom method for reading source files", "scala.tools.nsc.io.SourceReader").hideToIDE
-// val migrate2_7_2  = BooleanSetting    ("-Xmigrate-to-2.7.2", "Issue warning messages to help in migration to 2.7.2")
-  val future        = BooleanSetting    ("-Xfuture", "Turn on future language features")
-  
-  val Yhelp         = BooleanSetting    ("-Y", "Print a synopsis of private options").hideToIDE
-  val browse        = PhasesSetting     ("-Ybrowse", "Browse the abstract syntax tree after")
-  val check         = PhasesSetting     ("-Ycheck", "Check the tree at the end of the given phase. Specify \"all\" to check all checkable phases")
-  val Xcloselim     = BooleanSetting    ("-Yclosure-elim", "Perform closure elimination")
-  val Xcodebase     = StringSetting     ("-Ycodebase", "codebase", "Specify the URL containing the Scala libraries", "").hideToIDE
-  val debug         = BooleanSetting    ("-Ydebug", "Output debugging messages").hideToIDE
-  val Xdce          = BooleanSetting    ("-Ydead-code", "Perform dead code elimination")
-  val Xdetach       = BooleanSetting    ("-Ydetach", "Perform detaching of remote closures")
-//  val doc           = BooleanSetting    ("-Ydoc", "Generate documentation").hideToIDE
-  val inline        = BooleanSetting    ("-Yinline", "Perform inlining when possible")
-  val Xlinearizer   = ChoiceSetting     ("-Ylinearizer", "Linearizer to use", List("normal", "dfs", "rpo", "dump"), "rpo")
-  val log           = PhasesSetting     ("-Ylog", "Log operations in")
-  val logAll        = BooleanSetting    ("-Ylog-all", "Log all operations").hideToIDE
-  val noimports     = BooleanSetting    ("-Yno-imports", "Compile without any implicit imports")
-  val nopredefs     = BooleanSetting    ("-Yno-predefs", "Compile without any implicit predefined values")
-  val Yrecursion    = IntSetting        ("-Yrecursion", "Recursion depth used when locking symbols", 0, Some(0), None).hideToIDE
-  val script        = StringSetting     ("-Xscript", "object", "Compile as a script, wrapping the code into object.main()", "").hideToIDE
-
-  val Xshowtrees    = BooleanSetting    ("-Yshow-trees", "Show detailed trees when used in connection with -print:phase").hideToIDE
-  val skip          = PhasesSetting     ("-Yskip", "Skip")
-  val Xsqueeze      = ChoiceSetting     ("-Ysqueeze", "if on, creates compact code in matching", List("on","on","off"), "on").hideToIDE 
-  val statistics    = BooleanSetting    ("-Ystatistics", "Print compiler statistics").hideToIDE
-  val stop          = PhasesSetting     ("-Ystop", "Stop after phase")
-  val Xwarndeadcode = BooleanSetting    ("-Ywarn-dead-code", "Emit warnings for dead code")
-  val Ynogenericsig = BooleanSetting    ("-Yno-generic-signatures", "Suppress generation of generic signatures for Java")
-
-  val XnoVarargsConversion = BooleanSetting("-Xno-varargs-conversion", "disable varags conversion")
-  val selfInAnnots = BooleanSetting    ("-Yself-in-annots", "Include a \"self\" identifier inside of annotations")
-
-
-  /** A list of all settings */
-  def allSettings: List[Setting] = allsettings.reverse
-  /** Disable a setting */
-  def disable(s: Setting) = {
-    allsettings = allsettings filter (s !=)
-  }
-
-  override def equals(that: Any) = that match {
-    case s:Settings =>
-      assert(this.allSettings.length == s.allSettings.length)
-      List.forall2 (
-        this.allSettings,
-        s.allSettings
-      )(_==_)
-    case _ => false
-  }
-
-  def checkDependencies: Boolean = {
-    def hasValue(s: Setting, value: String): Boolean = s match {
-      case bs: BooleanSetting => bs.value
-      case ss: StringSetting  => ss.value == value
-      case cs: ChoiceSetting  => cs.value == value
-      case _ => "" == value
-    }
-    var ok = true
-    for (setting <- allsettings if !setting.dependency.isEmpty) {
-      val (dep, value) = setting.dependency.get
-      if (! (setting.isDefault || hasValue(dep, value))) {
-        error("incomplete option " + setting.name + " (requires " + dep.name + ")")
-        ok = false
-      }
-    }
-    ok
-  }
-
-  /** Try to add additional command line parameters. */
-  def parseParams(line: String, error: String => Nothing) {
-    var args =
-      if (line.trim() == "") Nil
-      else List.fromArray(line.trim().split(" ")).map(_.trim())
-    while (!args.isEmpty) {
-      val argsBuf = args
-      if (args.head startsWith "-") {
-        for (setting <- allSettings)
-          args = setting.tryToSet(args);
-      }
-      else error("Parameter '" + args.head + "' does not start with '-'.")
-      if (argsBuf eq args)
-        error("Parameter '" + args.head + "' is not recognised by Scalac.")
-    }
-  }
-
-  /** A base class for settings of all types.
-   *  Subclasses each define a `value' field of the appropriate type.
-   */
-  abstract class Setting(descr: String) {
-
-    /** The name of the option as written on the command line, '-' included. */
-    def name: String
-
-    /** If first arg defines this setting, consume it as well as all following
-     *  args needed to define the setting. If this can be done without
-     *  error, set value field and return suffix of args else
-     *  issue error message and return the arguments unchanged.
-     *  If first arg does not define this setting return args unchanged.
-     */
-    def tryToSet(args: List[String]): List[String]
-
-    /** The syntax defining this setting in a help string */
-    def helpSyntax: String = name
-
-    /** A description of the purpose of this setting in a help string */
-    def helpDescription = descr
-
-    /** Return a list of strings that can be used to recreate
-      * the receiver's current setting.
-      */
-    def unparse: List[String]
-
-    /** override if option should be hidden from IDE.
-      */
-    var hiddenToIDE: Boolean = false
-    def hideToIDE: this.type = {
-      hiddenToIDE = true
-      this
-    }
-    def showToIDE: this.type = {
-      hiddenToIDE = false
-      this
-    }
-
-    protected var setByUser: Boolean = false
-    def isDefault: Boolean = !setByUser
-
-    protected[Settings] var dependency: Option[(Setting, String)] = None
-    def dependsOn(s: Setting, value: String): this.type = { dependency = Some((s, value)); this }
-    def dependsOn(s: Setting): this.type = dependsOn(s, "")
-
-    def isStandard: Boolean = !isAdvanced && !isPrivate && !(name eq "-Y")
-    def isAdvanced: Boolean = 
-      (name startsWith "-X") && !(name eq "-X")
-    def isPrivate: Boolean =
-      (name == "-P") || ((name startsWith "-Y") && !(name eq "-Y"))
-
-/*
-    def isDocOption: Boolean =
-      !dependency.isEmpty && dependency.get._1 == doc
-*/
-    // initialization
-    allsettings = this :: allsettings
-  }
-
-  /** A setting represented by a positive integer */
-  case class IntSetting(name: String, descr: String, default: Int, min: Option[Int], max: Option[Int]) extends Setting(descr) {
-    // Validate that min and max are consistent
-    (min, max) match {
-      case (Some(i), Some(j)) => assert(i <= j)
-      case _ => ()
-    }
-
-    // Helper to validate an input
-    private def isInputValid(k: Int): Boolean = 
-      (min, max) match {
-        case (Some(i), Some(j)) => (i <= k) && (k <= j)
-        case (Some(i), None) => (i <= k)
-        case (None, Some(j)) => (k <= j)
-        case _ => true
-      }
-
-    // Helper to generate a textual explaination of valid inputs
-    private def getValidText: String = 
-      (min, max) match {
-        case (Some(i), Some(j)) => "must be between "+i+" and "+j
-        case (Some(i), None) => "must be greater than or equal to "+i
-        case (None, Some(j)) => "must be less than or equal to "+j
-        case _ => throw new Error("this should never be used")
-      }
-
-    // Ensure that the default value is actually valid
-    assert(isInputValid(default))
-
-    protected var v: Int = default
-
-    def errorMsg = error("invalid setting for -"+name+" "+getValidText)
-
-    def value: Int = this.v
-    def value_=(s: Int) { 
-      if (!isInputValid(s)) errorMsg
-      setByUser = true; 
-      this.v = s 
-    }
-
-    def tryToSet(args: List[String]): List[String] = args match {
-      case n :: rest if (name == n) =>
-        if (rest.isEmpty) {
-          error("missing argument")
-          args
-        } else {
-          try {
-            value = rest.head.toInt
-        } catch {
-            case e: java.lang.NumberFormatException => errorMsg
-        }
-          rest.tail
-        }
-      case _ => args
-    }
-
-    def unparse: List[String] =
-      if (value == default) Nil else List(name, value.toString)
-    
-    override def equals(that: Any) = that match {
-      case is:IntSetting => this.name == is.name && this.value == is.value
-      case _ => false
-    }
-
-  }
-
-  /** A setting represented by a boolean flag (false, unless set) */
-  case class BooleanSetting(name: String, descr: String) extends Setting(descr) {
-    protected var v: Boolean = false
-
-    def value: Boolean = this.v
-    def value_=(s: Boolean) { setByUser = true; this.v = s }
-
-    def tryToSet(args: List[String]): List[String] = args match {
-      case n :: rest if (n == name) => value = true; rest
-      case _ => args
-    }
-
-    def unparse: List[String] = if (value) List(name) else Nil
-
-    override def equals(that: Any) = that match {
-      case bs:BooleanSetting => this.name == bs.name && this.value == bs.value
-      case _ => false
-    }
-
-  }
-
-  /** A setting represented by a string, (`default' unless set) */
-  case class StringSetting(name: String, arg: String, descr: String, default: String)
-  extends Setting(descr) { 
-    def abbreviation: String = null
-
-    protected var v: String = default
-
-    def value: String = this.v
-    def value_=(s: String) { setByUser = true; this.v = s }
-
-    def tryToSet(args: List[String]): List[String] = args match {
-      case n :: rest if (name == n || abbreviation == n) =>
-        if (rest.isEmpty) {
-          error("missing argument")
-          args
-        } else {
-          value = rest.head
-          rest.tail
-        }
-      case _ => args
-    }
-
-    override def helpSyntax = name + " <" + arg + ">"
-
-    def unparse: List[String] =
-      if (value == default) Nil else List(name, value)
-
-    override def equals(that: Any) = that match {
-      case ss:StringSetting => this.name == ss.name && this.value == ss.value
-      case _ => false
-    }
-
-  }
-
-  /** A setting that accumulates all strings supplied to it */
-  case class MultiStringSetting(name: String, arg: String, descr: String)
-  extends Setting(descr) {
-    hideToIDE
-    protected var v: List[String] = Nil
-    def value = v
-    def appendToValue(str: String) { v = v ::: List(str) }
-    
-    protected val nameColon = name + ":"
-    def tryToSet(args: List[String]): List[String] = args match {
-      case arg :: rest if (arg startsWith nameColon) =>
-        val toadd = arg.substring(nameColon.length())
-        if (toadd.length == 0) {
-          error("empty argument to " + nameColon)
-          args
-        } else {
-          appendToValue(toadd)
-          rest
-        }
-
-      case opt :: arg :: rest if (opt == name) =>
-        appendToValue(arg)
-        rest
-
-      case _ => args
-    }
-
-    override def helpSyntax = name + ":<" + arg + ">"
-
-    def unparse: List[String] =
-      for (opt <- value) yield nameColon+opt
-
-    override def equals(that: Any) = that match {
-      case mss:MultiStringSetting =>
-        this.name == mss.name &&
-        this.value.length == mss.value.length &&
-        List.forall2(this.value.sort(_<_), mss.value.sort(_<_))(_==_)
-      case _ => false
-    }
-
-  }
-
-  /** A setting represented by a string in a given set of <code>choices</code>,
-   *  (<code>default</code> unless set).
-   */
-  case class ChoiceSetting(name: String, descr: String, choices: List[String], default: String)
-  extends Setting(descr + choices.mkString(" (", ",", ")")) {
-    protected var v: String = default
-
-    def value: String = this.v
-    def value_=(s: String) { setByUser = true; this.v = s }
-
-    protected def argument: String = name.substring(1)
-
-    def tryToSet(args: List[String]): List[String] = args match {
-      case n :: rest if (n startsWith (name + ":")) =>
-        val choice = n.substring(name.length() + 1)
-        if (!(choices contains choice)) {
-          error(
-            if (choice == "") "missing " + argument
-            else "unknown " + argument + " '" + choice + "'")
-          args
-        } else {
-          value = choice
-          rest
-        }
-      case n :: choice :: rest if n == name => // alternative to be consistent with IDE
-        if (!(choices contains choice)) {
-          error(
-            if (choice == "") "missing " + argument
-            else "unknown " + argument + " '" + choice + "'")
-          args
-        } else {
-          value = choice
-          rest
-        }
-      case _ => args
-    }
-
-    override def helpSyntax = name + ":<" + argument + ">"
-
-    def unparse: List[String] =
-      if (value == default) Nil else List(name + ":" + value)
-
-    override def equals(that: Any) = that match {
-      case cs:ChoiceSetting => this.name == cs.name && this.value == cs.value
-      case _ => false
-    }
-
-  }
-
-  /** Same as ChoiceSetting but have a <code>level</code> int which tells the
-   *  index of the selected choice. The <code>defaultEmpty</code> is used when
-   *  this setting is used without specifying any of the available choices.
-   */
-  class DebugSetting(name: String, descr: String, choices: List[String], default: String, defaultEmpty: String)
-  extends ChoiceSetting(name, descr, choices, default) {
-
-    def indexOf[a](xs: List[a], e: a): Option[Int] = xs match {
-      case y :: ys => if (e == y) Some(0) else indexOf(ys, e) match {
-          case Some(idx) => Some(1 + idx)
-          case None => None
-        }
-      case _ => None
-    }
-    var level: Int = indexOf(choices, default).get
-
-    override def value_=(choice: String) {
-      setByUser = true
-      this.v = choice
-      this.level = indexOf(choices, choice).get
-    }
-
-    override def tryToSet(args: List[String]): List[String] = args match {
-      case n :: rest if (n startsWith (name + ":")) =>
-        val choice = n.substring(name.length() + 1)
-        if (!(choices contains choice)) {
-          error(
-              if (choice == "") "missing " + argument
-              else "unknown " + argument + " '" + choice + "'")
-          args
-        } else {
-          value = choice
-          rest
-        }
-
-      case n :: rest if (n startsWith name) =>
-        value = defaultEmpty
-        rest
-
-      case _ => args
-    }
-  }
-
-  /** A setting represented by a list of strings which should be prefixes of
-   *  phase names. This is not checked here, however.
-   *  (the empty list, unless set)
-   */
-  case class PhasesSetting(name: String, descr: String)
-  extends Setting(descr + " <phase>") { // (see -showphases)") {
-    hideToIDE
-    protected var v: List[String] = List()
-
-    def value: List[String] = this.v
-    def value_=(s: List[String]) { setByUser = true; this.v = s }
-
-    def tryToSet(args: List[String]): List[String] = args match {
-      case n :: rest if (n startsWith (name + ":")) =>
-        val phase = n.substring(name.length() + 1)
-        if (phase == "") {
-          error("missing phase")
-          args
-        } else {
-          value = value ::: List(phase)
-          rest
-        }
-      case _ => args
-    }
-
-    override def helpSyntax = name + ":<phase>"
-
-    def contains(phasename: String): Boolean =
-      value exists (str => phasename startsWith str)
-
-    def unparse: List[String] =
-      (value.foldLeft[List[String]]
-          (Nil)
-          ((args, phase) =>
-            List(name + ":" + phase) ::: args))
-
-    override def equals(that: Any) = that match {
-      case ps:PhasesSetting =>
-        this.name == ps.name &&
-        this.value.length == ps.value.length &&
-        List.forall2(this.value.sort(_<_), ps.value.sort(_<_))(_==_)
-      case _ => false
-    }
-
-  }
 }
diff --git a/src/compiler/scala/tools/nsc/SubComponent.scala b/src/compiler/scala/tools/nsc/SubComponent.scala
index 78ce3cd..445021f 100644
--- a/src/compiler/scala/tools/nsc/SubComponent.scala
+++ b/src/compiler/scala/tools/nsc/SubComponent.scala
@@ -1,8 +1,7 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author Martin Odersky
  */
-// $Id: SubComponent.scala 16894 2009-01-13 13:09:41Z cunei $
 
 package scala.tools.nsc
 
@@ -18,6 +17,22 @@ abstract class SubComponent {
   /** The name of the phase */
   val phaseName: String
 
+  /** List of phase names, this phase should run after  */
+  val runsAfter: List[String]
+
+  /** List of phase names, this phase should run before  */
+  val runsBefore: List[String] = Nil
+
+  /** Phase name this phase will attach itself to, not allowing any phase to come between it
+   * and the phase name declared  */
+  val runsRightAfter: Option[String]
+
+  /** Internal flag to tell external from internal phases */
+  val internal: Boolean = true
+
+  /** SubComponent are added to a HashSet and two phases are the same if they have the same name  */
+  override def hashCode() = phaseName.hashCode()
+
   /** New flags defined by the phase which are not valid before */
   def phaseNewFlags: Long = 0
 
@@ -40,7 +55,7 @@ abstract class SubComponent {
   }
 
   /** The phase defined by this subcomponent. Can be called only after phase is installed by newPhase. */
-//  lazy val ownPhase: Phase = global.currentRun.phaseNamed(phaseName)
+  //  lazy val ownPhase: Phase = global.currentRun.phaseNamed(phaseName)
 
   /** A standard phase template */
   abstract class StdPhase(prev: Phase) extends global.GlobalPhase(prev) {
diff --git a/src/compiler/scala/tools/nsc/ast/DocComments.scala b/src/compiler/scala/tools/nsc/ast/DocComments.scala
new file mode 100644
index 0000000..79ac89e
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/ast/DocComments.scala
@@ -0,0 +1,431 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
+ * @author  Martin Odersky
+ */
+
+package scala.tools.nsc
+package ast
+
+import symtab._
+import util.{Position, NoPosition}
+import util.DocStrings._
+import util.Chars._
+import scala.collection.mutable.{HashMap, ListBuffer, StringBuilder}
+
+/*
+ *  @author  Martin Odersky
+ *  @version 1.0
+ */
+trait DocComments { self: SymbolTable =>
+
+  /** The raw doc comment map */
+  val docComments = new HashMap[Symbol, DocComment]
+
+  /** Associate comment with symbol `sym` at position `pos`. */
+  def docComment(sym: Symbol, docStr: String, pos: Position = NoPosition) =
+    if ((sym ne null) && (sym ne NoSymbol))
+      docComments += (sym -> DocComment(docStr, pos))
+
+  /** The raw doc comment of symbol `sym`, as it appears in the source text, "" if missing.
+   */
+  def rawDocComment(sym: Symbol): String =
+    docComments get sym map (_.raw) getOrElse ""
+
+  /** The position of the raw doc comment of symbol `sym`, or NoPosition if missing
+   *  If a symbol does not have a doc comment but some overridden version of it does,
+   *  the position of the doc comment of the overridden version is returned instead.
+   */
+  def docCommentPos(sym: Symbol): Position =
+    getDocComment(sym) map (_.pos) getOrElse NoPosition
+
+  /** The raw doc comment of symbol `sym`, minus @usecase and @define sections, augmented by
+   *  missing sections of an inherited doc comment.
+   *  If a symbol does not have a doc comment but some overridden version of it does,
+   *  the doc comment of the overridden version is copied instead.
+   */
+  def cookedDocComment(sym: Symbol, docStr: String = ""): String = {
+    val ownComment = if (docStr.length == 0) docComments get sym map (_.template) getOrElse ""
+                     else DocComment(docStr).template
+    superComment(sym) match {
+      case None =>
+        ownComment
+      case Some(sc) =>
+        if (ownComment == "") sc
+        else merge(sc, ownComment, sym)
+    }
+  }
+
+  /** The cooked doc comment of symbol `sym` after variable expansion, or "" if missing.
+   *
+   *  @param sym  The symbol for which doc comment is returned
+   *  @param site The class for which doc comments are generated
+   *  @throws ExpansionLimitExceeded  when more than 10 successive expansions
+   *                                  of the same string are done, which is
+   *                                  interpreted as a recursive variable definition.
+   */
+  def expandedDocComment(sym: Symbol, site: Symbol, docStr: String = ""): String = {
+    // when parsing a top level class or module, use the (module-)class itself to look up variable definitions
+    val site1 = if ((sym.isModule || sym.isClass) && (site hasFlag Flags.PACKAGE)) sym
+                else site
+    expandVariables(cookedDocComment(sym, docStr), sym, site1)
+  }
+
+  /** The cooked doc comment of symbol `sym` after variable expansion, or "" if missing.
+   *  @param sym  The symbol for which doc comment is returned (site is always the containing class)
+   */
+  def expandedDocComment(sym: Symbol): String = expandedDocComment(sym, sym.enclClass)
+
+  /** The list of use cases of doc comment of symbol `sym` seen as a member of class
+   *  `site`. Each use case consists of a synthetic symbol (which is entered nowhere else),
+   *  of an expanded doc comment string, and of its position.
+   *
+   *  @param sym  The symbol for which use cases are returned
+   *  @param site The class for which doc comments are generated
+   *  @throws ExpansionLimitExceeded  when more than 10 successive expansions
+   *                                  of the same string are done, which is
+   *                                  interpreted as a recursive variable definition.
+   */
+  def useCases(sym: Symbol, site: Symbol): List[(Symbol, String, Position)] = {
+    def getUseCases(dc: DocComment) = {
+      for (uc <- dc.useCases; defn <- uc.expandedDefs(site)) yield
+        (defn,
+         expandVariables(merge(cookedDocComment(sym), uc.comment.raw, defn, copyFirstPara = true), sym, site),
+         uc.pos)
+    }
+    getDocComment(sym) map getUseCases getOrElse List()
+  }
+
+  def useCases(sym: Symbol): List[(Symbol, String, Position)] = useCases(sym, sym.enclClass)
+
+  /** Returns the javadoc format of doc comment string `s`, including wiki expansion
+   */
+  def toJavaDoc(s: String): String = expandWiki(s)
+
+  private val wikiReplacements = List(
+    ("""(\n\s*\*?)(\s*\n)"""    .r, """$1 <p>$2"""),
+    ("""<([^\w/])"""            .r, """<$1"""),
+    ("""([^\w/])>"""            .r, """$1>"""),
+    ("""\{\{\{(.*(?:\n.*)*)\}\}\}""".r, """<pre>$1</pre>"""),
+    ("""`([^`]*)`"""            .r, """<code>$1</code>"""),
+    ("""__([^_]*)__"""          .r, """<u>$1</u>"""),
+    ("""''([^']*)''"""          .r, """<i>$1</i>"""),
+    ("""'''([^']*)'''"""        .r, """<b>$1</b>"""),
+    ("""\^([^^]*)\^"""          .r, """<sup>$1</sup>"""),
+    (""",,([^,]*),,"""          .r, """<sub>$1</sub>"""))
+
+  /** Returns just the wiki expansion (this would correspond to
+   *  a comment in the input format of the JavaDoc tool, modulo differences
+   *  in tags.)
+   */
+  def expandWiki(str: String): String =
+    (str /: wikiReplacements) { (str1, regexRepl) => regexRepl._1 replaceAllIn(str1, regexRepl._2) }
+
+
+  private def getDocComment(sym: Symbol): Option[DocComment] = docComments get sym match {
+    case None => mapFind(sym.allOverriddenSymbols)(docComments get)
+    case some => some
+  }
+
+  /** The cooked doc comment of an overridden symbol */
+  protected def superComment(sym: Symbol): Option[String] =
+    sym.allOverriddenSymbols.view map { cookedDocComment(_) } find ("" !=)
+
+  private def mapFind[A, B](xs: Iterable[A])(f: A => Option[B]): Option[B] = {
+    var res: Option[B] = None
+    val it = xs.iterator
+    while (res.isEmpty && it.hasNext) {
+      res = f(it.next())
+    }
+    res
+  }
+
+  private def isMovable(str: String, sec: (Int, Int)): Boolean =
+    startsWithTag(str, sec, "@param") ||
+    startsWithTag(str, sec, "@tparam") ||
+    startsWithTag(str, sec, "@return")
+
+  /** Merge elements of doccomment `src` into doc comment `dst` for symbol `sym`.
+   *  In detail:
+   *  1. If `copyFirstPara` is true, copy first paragraph
+   *  2. For all parameters of `sym` if there is no @param section
+   *     in `dst` for that parameter name, but there is one on `src`, copy that section.
+   *  3. If there is no @return section in `dst` but there is one in `src`, copy it.
+   */
+  def merge(src: String, dst: String, sym: Symbol, copyFirstPara: Boolean = false): String = {
+    val srcSections = tagIndex(src)
+    val dstSections = tagIndex(dst)
+    val srcParams = paramDocs(src, "@param", srcSections)
+    val dstParams = paramDocs(dst, "@param", dstSections)
+    val srcTParams = paramDocs(src, "@tparam", srcSections)
+    val dstTParams = paramDocs(dst, "@tparam", dstSections)
+    val out = new StringBuilder
+    var copied = 0
+    var tocopy = startTag(dst, dstSections dropWhile (!isMovable(dst, _)))
+
+    if (copyFirstPara) {
+      val eop = // end of comment body (first para), which is delimited by blank line, or tag, or end of comment
+        (findNext(src, 0)(src.charAt(_) == '\n')) min startTag(src, srcSections)
+      out append src.substring(0, eop).trim
+      copied = 3
+      tocopy = 3
+    }
+
+    def mergeSection(srcSec: Option[(Int, Int)], dstSec: Option[(Int, Int)]) = dstSec match {
+      case Some((start, end)) =>
+        if (end > tocopy) tocopy = end
+      case None =>
+        srcSec match {
+          case Some((start1, end1)) =>
+            out append dst.substring(copied, tocopy).trim
+            copied = tocopy
+            out append src.substring(start1, end1).trim
+          case None =>
+        }
+    }
+
+    for (params <- sym.paramss; param <- params)
+      mergeSection(srcParams get param.name.toString, dstParams get param.name.toString)
+    for (tparam <- sym.typeParams)
+      mergeSection(srcTParams get tparam.name.toString, dstTParams get tparam.name.toString)
+    mergeSection(returnDoc(src, srcSections), returnDoc(dst, dstSections))
+
+    if (out.length == 0) dst
+    else {
+      out append dst.substring(copied)
+      out.toString
+    }
+  }
+
+  /** Maps symbols to the variable -> replacement maps that are defined
+   *  in their doc comments
+   */
+  private val defs = new HashMap[Symbol, Map[String, String]] {
+    override def default(key: Symbol) = Map()
+  }
+
+  /** Lookup definition of variable.
+   *
+   *  @param vble  The variable for which a definition is searched
+   *  @param owner The current owner in which variable definitions are searched.
+   *  @param site  The class for which doc comments are generated
+   */
+  def lookupVariable(vble: String, site: Symbol): Option[String] =
+    if (site == NoSymbol)
+      None
+    else {
+      def lookInBaseClasses = mapFind(site.info.baseClasses)(defs(_).get(vble)) match {
+        case None => lookupVariable(vble, site.owner)
+        case someStr => someStr
+      }
+      if (site.isModule)
+        defs(site).get(vble) match {
+          case Some(str) => return Some(str)
+          case None => lookInBaseClasses
+        }
+      else lookInBaseClasses
+    }
+
+  private var expandCount = 0
+  private final val expandLimit = 10
+
+  /** Expand variable occurrences in string `str', until a fix point is reached or
+   *  a expandLimit is exceeded.
+   *
+   *  @param str   The string to be expanded
+   *  @param sym   The symbol for which doc comments are generated
+   *  @param site  The class for which doc comments are generated
+   *  @return      Expanded string
+   */
+  protected def expandVariables(str: String, sym: Symbol, site: Symbol): String =
+    if (expandCount < expandLimit) {
+      try {
+        val out = new StringBuilder
+        var copied = 0
+        var idx = 0
+        while (idx < str.length) {
+          if ((str charAt idx) == '$') {
+            val vstart = idx
+            idx = skipVariable(str, idx + 1)
+            def replaceWith(repl: String) {
+              out append str.substring(copied, vstart)
+              out append repl
+              copied = idx
+            }
+            val vname = variableName(str.substring(vstart + 1, idx))
+            if (vname == "super") {
+              superComment(sym) match {
+                case Some(sc) =>
+                  val superSections = tagIndex(sc)
+                  replaceWith(sc.substring(3, startTag(sc, superSections)))
+                  for (sec @ (start, end) <- superSections)
+                    if (!isMovable(sc, sec)) out append sc.substring(start, end)
+                case None =>
+              }
+            } else if (vname.length > 0) {
+              lookupVariable(vname, site) match {
+                case Some(replacement) => replaceWith(replacement)
+                case None =>  //println("no replacement for "+vname) // DEBUG
+              }
+            } else idx += 1
+          } else idx += 1
+        }
+        if (out.length == 0) str
+        else {
+          out append str.substring(copied)
+          expandVariables(out.toString, sym, site)
+        }
+      } finally {
+        expandCount -= 1
+      }
+    } else throw new ExpansionLimitExceeded(str)
+
+
+  // !!! todo: inherit from Comment?
+  case class DocComment(raw: String, pos: Position = NoPosition) {
+
+    /** Returns:
+     *   template: the doc comment minus all @define and @usecase sections
+     *   defines : all define sections (as strings)
+     *   useCases: all usecase sections (as instances of class UseCase)
+     */
+    lazy val (template, defines, useCases) = {
+      val sections = tagIndex(raw, idx =>
+        startsWithTag(raw, idx, "@define") || startsWithTag(raw, idx, "@usecase"))
+      val (defines, usecases) = sections partition (startsWithTag(raw, _, "@define"))
+      val end = startTag(raw, sections)
+      /*
+      println("processing doc comment:")
+      println(raw)
+      println("===========>")
+      println(raw.substring(0, end))
+      println("++++++++++++++++")
+      println(sections map { case (s, e) => raw.substring(s, e) })
+      */
+      (if (end == raw.length - 2) raw else raw.substring(0, end) + "*/",
+       defines map { case (start, end) => raw.substring(start, end) },
+       usecases map { case (start, end) => decomposeUseCase(start, end) })
+    }
+
+    private def decomposeUseCase(start: Int, end: Int): UseCase = {
+      val codeStart = skipWhitespace(raw, start + "@usecase".length)
+      val codeEnd = skipToEol(raw, codeStart)
+      val code = raw.substring(codeStart, codeEnd)
+      val codePos = subPos(codeStart, codeEnd)
+      val commentStart = skipLineLead(raw, codeEnd + 1) min end
+      val comment = "/** " + raw.substring(commentStart, end) + "*/"
+      val commentPos = subPos(commentStart, end)
+      UseCase(DocComment(comment, commentPos), code, codePos)
+    }
+
+    private def subPos(start: Int, end: Int) =
+      if (pos == NoPosition) NoPosition
+      else {
+        val start1 = pos.start + start
+        val end1 = pos.end + end
+        pos withStart start1 withPoint start1 withEnd end1
+      }
+
+    def defineVariables(sym: Symbol) {
+      for (str <- defines) {
+        val start = skipWhitespace(str, "@define".length)
+        var idx = skipVariable(str, start)
+        val vble = variableName(str.substring(start, idx))
+        if (idx < str.length && isWhitespace(str charAt idx)) idx += 1
+        var end = str.lastIndexOf('\n')
+        if (end == -1) end = str.length
+        defs(sym) += vble -> str.substring(idx, end)
+      }
+      //if (defs(sym).nonEmpty) println("vars of "+sym+" = "+defs(sym))  // !!!
+    }
+  }
+
+  case class UseCase(comment: DocComment, body: String, pos: Position) {
+    var defined: List[Symbol] = List() // initialized by Typer
+    var aliases: List[Symbol] = List() // initialized by Typer
+
+    def expandedDefs(site: Symbol): List[Symbol] = {
+
+      def select(site: Type, name: Name, orElse: => Type): Type = {
+        val member = site.nonPrivateMember(name)
+        if (member.isTerm) SingleType(site, member)
+        else if (member.isType) site.memberType(member)
+        else orElse
+      }
+
+      def getSite(name: Name): Type = {
+        def findIn(sites: List[Symbol]): Type = sites match {
+          case List() => NoType
+          case site :: sites1 => select(site.thisType, name, findIn(sites1))
+        }
+        val (classes, pkgs) = site.ownerChain.span(!_.isPackageClass)
+        findIn(classes ::: List(pkgs.head, definitions.RootClass))
+      }
+
+      def getType(str: String): Type = {
+        def getParts(start: Int): List[String] = {
+          val end = skipIdent(str, start)
+          if (end == start) List()
+          else str.substring (start, end) :: {
+            if (end < str.length && (str charAt end) == '.') getParts(end + 1)
+            else List()
+          }
+        }
+        val parts = getParts(0)
+        assert(parts.length > 0, "parts is empty '" + str + "' in site " + site)
+        val partnames = (parts.init map newTermName) ::: List(newTypeName(parts.last))
+        val (start, rest) =
+          if (parts.head == "this")
+            (site.thisType, partnames.tail)
+          else if (parts.tail.nonEmpty && parts(1) == "this")
+            site.ownerChain.find(_.name.toString == parts.head) match {
+              case Some(clazz) => (clazz.thisType, partnames.drop(2))
+              case None => (NoType, List())
+            }
+          else
+            (getSite(partnames.head), partnames.tail)
+        (start /: rest)(select(_, _, NoType))
+      }
+
+      val aliasExpansions: List[Type] =
+        for (alias <- aliases) yield
+          lookupVariable(alias.name.toString.substring(1), site) match {
+            case Some(repl) =>
+              val tpe = getType(repl.trim)
+              if (tpe != NoType) tpe
+              else {
+                val alias1 = alias.cloneSymbol(definitions.RootClass)
+                alias1.name = repl.toTypeName
+                TypeRef(NoPrefix, alias1, List())
+              }
+            case None =>
+              TypeRef(NoPrefix, alias, List())
+          }
+
+      def subst(sym: Symbol, from: List[Symbol], to: List[Type]): Type =
+        if (from.isEmpty) sym.tpe
+        else if (from.head == sym) to.head
+        else subst(sym, from.tail, to.tail)
+
+      val substAliases = new TypeMap {
+        def apply(tp: Type) = mapOver(tp) match {
+          case tp1 @ TypeRef(pre, sym, args) if (sym.name.length > 1 && sym.name(0) == '$') =>
+            subst(sym, aliases, aliasExpansions) match {
+              case TypeRef(pre1, sym1, _) =>
+                TypeRef(pre1, sym1, args)
+              case _ =>
+                tp1
+            }
+          case tp1 =>
+            tp1
+        }
+      }
+
+      for (defn <- defined) yield {
+        defn.cloneSymbol.setFlag(Flags.SYNTHETIC).setInfo(
+          substAliases(defn.info).asSeenFrom(site.thisType, defn.owner))
+      }
+    }
+  }
+
+  class ExpansionLimitExceeded(str: String) extends Exception
+}
\ No newline at end of file
diff --git a/src/compiler/scala/tools/nsc/ast/NodePrinters.scala b/src/compiler/scala/tools/nsc/ast/NodePrinters.scala
index 582545a..0dbec3a 100644
--- a/src/compiler/scala/tools/nsc/ast/NodePrinters.scala
+++ b/src/compiler/scala/tools/nsc/ast/NodePrinters.scala
@@ -1,10 +1,10 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: NodePrinters.scala 16625 2008-11-25 16:04:12Z michelou $
 
-package scala.tools.nsc.ast
+package scala.tools.nsc
+package ast
 
 import compat.Platform.EOL
 import symtab.Flags._
@@ -41,13 +41,13 @@ abstract class NodePrinters {
           if (comma) buf.append(",")
           buf.append(EOL)
         }
-        def annotationInfoToString(attr: AnnotationInfo): String = {
+        def annotationInfoToString(annot: AnnotationInfo): String = {
           val str = new StringBuilder
-          str.append(attr.atp.toString())
-          if (!attr.args.isEmpty)
-            str.append(attr.args.mkString("(", ",", ")"))
-          if (!attr.assocs.isEmpty)
-            for (((name, value), index) <- attr.assocs.zipWithIndex) {
+          str.append(annot.atp.toString())
+          if (!annot.args.isEmpty)
+            str.append(annot.args.mkString("(", ",", ")"))
+          if (!annot.assocs.isEmpty)
+            for (((name, value), index) <- annot.assocs.zipWithIndex) {
               if (index > 0)
                 str.append(", ")
               str.append(name).append(" = ").append(value)
@@ -75,12 +75,11 @@ abstract class NodePrinters {
           if (sym hasFlag MUTABLE      ) buf.append(" | MUTABLE")
           if (sym hasFlag PARAM        ) buf.append(" | PARAM")
           if (sym hasFlag PACKAGE      ) buf.append(" | PACKAGE")
-          if (sym hasFlag DEPRECATED   ) buf.append(" | DEPRECATED")
 
           if (sym hasFlag COVARIANT    ) buf.append(" | COVARIANT")
           if (sym hasFlag CAPTURED     ) buf.append(" | CAPTURED")
           if (sym hasFlag BYNAMEPARAM  ) buf.append(" | BYNAMEPARAM")
-          if (sym hasFlag CONTRAVARIANT) buf.append(" | CONTRVARIANT")
+          if (sym hasFlag CONTRAVARIANT) buf.append(" | CONTRAVARIANT")
           if (sym hasFlag LABEL        ) buf.append(" | LABEL")
           if (sym hasFlag INCONSTRUCTOR) buf.append(" | INCONSTRUCTOR")
           if (sym hasFlag ABSOVERRIDE  ) buf.append(" | ABSOVERRIDE")
@@ -92,6 +91,7 @@ abstract class NodePrinters {
 
           if (sym hasFlag CASEACCESSOR ) buf.append(" | CASEACCESSOR")
           if (sym hasFlag TRAIT        ) buf.append(" | TRAIT")
+          if (sym hasFlag DEFAULTPARAM ) buf.append(" | DEFAULTPARAM")
           if (sym hasFlag BRIDGE       ) buf.append(" | BRIDGE")
           if (sym hasFlag ACCESSOR     ) buf.append(" | ACCESSOR")
 
@@ -115,13 +115,13 @@ abstract class NodePrinters {
           if (sym hasFlag TRANS_FLAG   ) buf.append(" | TRANS_FLAG")
           if (sym hasFlag LOCKED       ) buf.append(" | LOCKED")
 
-          val attrs = ", attrs=" + (
-            if (!sym.attributes.isEmpty)
-              sym.attributes.map(annotationInfoToString).mkString("[", ",", "]")
+          val annots = ", annots=" + (
+            if (!sym.annotations.isEmpty)
+              sym.annotations.map(annotationInfoToString).mkString("[", ",", "]")
             else
               tree.asInstanceOf[MemberDef].mods.annotations)
           (if (buf.length() > 2) buf.substring(3)
-          else "0") + ", // flags=" + flagsToString(sym.flags) + attrs
+          else "0") + ", // flags=" + flagsToString(sym.flags) + annots
         }
         def nodeinfo(tree: Tree): String =
           if (infolevel == InfoLevel.Quiet) ""
@@ -157,46 +157,27 @@ abstract class NodePrinters {
           }
         def nodeinfo2(tree: Tree): String =
           (if (comma) "," else "") + nodeinfo(tree)
+        
+        def applyCommon(name: String, tree: Tree, fun: Tree, args: List[Tree]) {
+          println(name + "(" + nodeinfo(tree))
+          traverse(fun, level + 1, true)
+          if (args.isEmpty)
+            println("  Nil // no argument")
+          else {
+            val n = args.length
+            println("  List( // " + n + " arguments(s)")
+            for (i <- 0 until n)
+              traverse(args(i), level + 2, i < n-1)
+            println("  )")
+          }
+          printcln(")")
+        }
+          
         tree match {
-          case AppliedTypeTree(tpt, args) =>
-            println("AppliedTypeTree(" + nodeinfo(tree))
-            traverse(tpt, level + 1, true)
-            if (args.isEmpty)
-              println("  List() // no argument")
-            else {
-              val n = args.length
-              println("  List( // " + n + " arguments(s)")
-              for (i <- 0 until n)
-                traverse(args(i), level + 2, i < n-1)
-              println("  )")
-            }
-            printcln(")")
-          case Apply(fun, args) =>
-            println("Apply(" + nodeinfo(tree))
-            traverse(fun, level + 1, true)
-            if (args.isEmpty)
-              println("  List() // no argument")
-            else {
-              val n = args.length
-              println("  List( // " + n + " argument(s)")
-              for (i <- 0 until n)
-                traverse(args(i), level + 2, i < n-1)
-              println("  )")
-            }
-            printcln(")")
-          case ApplyDynamic(fun, args) =>
-            println("ApplyDynamic(" + nodeinfo(tree))
-            traverse(fun, level + 1, true)
-            if (args.isEmpty)
-              println("  List() // no argument")
-            else {
-              val n = args.length
-              println("  List( // " + n + " argument(s)")
-              for (i <- 0 until n)
-                traverse(args(i), level + 2, i < n-1)
-              println("  )")
-            }
-            printcln(")")
+          case AppliedTypeTree(tpt, args) => applyCommon("AppliedTypeTree", tree, tpt, args)
+          case Apply(fun, args)           => applyCommon("Apply", tree, fun, args)
+          case ApplyDynamic(fun, args)    => applyCommon("ApplyDynamic", tree, fun, args)
+
           case Block(stats, expr) =>
             println("Block(" + nodeinfo(tree))
             if (stats.isEmpty)
@@ -316,8 +297,10 @@ abstract class NodePrinters {
             traverse(tpt, level + 1, true)
             traverse(rhs, level + 1, false)
             printcln(")")
-          case PackageDef(name, stats) =>
-            println("PackageDef("+name+", ")
+          case PackageDef(pid, stats) =>
+            println("PackageDef(")
+            traverse(pid, level + 1, false)
+            println(",\n")
             for (stat <- stats)
               traverse(stat, level + 1, false)
             printcln(")")
@@ -341,8 +324,6 @@ abstract class NodePrinters {
                   }
                   printcln(")")                
                 } else printcln(p.productPrefix)
-              case _ => 
-                printcln("***" + tree.getClass)
             }
         }
       }
@@ -354,16 +335,11 @@ abstract class NodePrinters {
 
   def printUnit(unit: CompilationUnit) {
     print("// Scala source: " + unit.source + "\n")
-    if (unit.body ne null) {
-      print(nodeToString(unit.body)); println()
-    } else {
-      print("<null>")
-    }
-    println()
+    println(Option(unit.body) map (x => nodeToString(x) + "\n") getOrElse "<null>")
   }
 
   def printAll() {
     print("[[syntax trees at end of " + phase + "]]")
-    for (unit <- global.currentRun.units) printUnit(unit)
+    global.currentRun.units foreach printUnit
   }
 }
diff --git a/src/compiler/scala/tools/nsc/ast/TreeBrowsers.scala b/src/compiler/scala/tools/nsc/ast/TreeBrowsers.scala
index ea5f84f..398a7b4 100644
--- a/src/compiler/scala/tools/nsc/ast/TreeBrowsers.scala
+++ b/src/compiler/scala/tools/nsc/ast/TreeBrowsers.scala
@@ -1,10 +1,10 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: TreeBrowsers.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.tools.nsc.ast
+package scala.tools.nsc
+package ast
 
 import java.awt.{List => awtList, _}
 import java.awt.event._
@@ -48,7 +48,7 @@ abstract class TreeBrowsers {
    */
   class SwingBrowser {
 
-    def browse(t: Tree): Unit = {
+    def browse(t: Tree): Tree = {
       val tm = new ASTTreeModel(t)
 
       val frame = new BrowserFrame()
@@ -59,6 +59,7 @@ abstract class TreeBrowsers {
 
       // wait for the frame to be closed
       lock.acquire
+      t
     }
 
     def browse(units: Iterator[CompilationUnit]): Unit =
@@ -110,7 +111,7 @@ abstract class TreeBrowsers {
     def isLeaf(node: Any): Boolean = packChildren(node).length == 0
 
     def removeTreeModelListener(l: TreeModelListener): Unit =
-      listeners remove (x => x == l)
+      listeners filterNot (_ == l)
 
     /** we ignore this message for now */
     def valueForPathChanged(path: TreePath, newValue: Any) = ()
@@ -138,7 +139,7 @@ abstract class TreeBrowsers {
     var splitPane: JSplitPane = _
     var treeModel: TreeModel = _
 
-    val textArea: JTextArea = new JTextArea(20, 150)
+    val textArea: JTextArea = new JTextArea(30, 120)
     val infoPanel = new TextInfoPanel()
 
     /** Create a frame that displays the AST.
@@ -201,7 +202,7 @@ abstract class TreeBrowsers {
   /**
    * Present detailed information about the selected tree node.
    */
-  class TextInfoPanel extends JTextArea(30, 40) {
+  class TextInfoPanel extends JTextArea(20, 50) {
 
     setFont(new Font("monospaced", Font.PLAIN, 12))
 
@@ -214,11 +215,20 @@ abstract class TreeBrowsers {
         case ProgramTree(_) => ()
         case UnitTree(_)    => ()
         case _ =>
-          str.append("tree.pos: ").append(t.pos)
+          str.append("tree.id: ").append(t.id)
+          str.append("\ntree.pos: ").append(t.pos)
           str.append("\nSymbol: ").append(TreeInfo.symbolText(t))
-          str.append("\nSymbol info: \n")
-          TreeInfo.symbolTypeDoc(t).format(getWidth() / getColumnWidth(), buf)
-          str.append(buf.toString())
+          str.append("\nSymbol owner: ").append(
+            if ((t.symbol ne null) && t.symbol != NoSymbol) 
+              t.symbol.owner.toString
+            else 
+              "NoSymbol has no owner")
+          if ((t.symbol ne null) && t.symbol.isType) {
+            str.append("\ntermSymbol: " + t.symbol.tpe.termSymbol
+                     + "\ntypeSymbol: " + t.symbol.tpe.typeSymbol)
+          if (t.symbol.isTypeSkolem)
+            str.append("\nSkolem of: " + t.symbol.deSkolemize)
+          }
           str.append("\nSymbol tpe: ")
           if (t.symbol ne null) {
             str.append(t.symbol.tpe).append("\n")
@@ -226,7 +236,10 @@ abstract class TreeBrowsers {
             TypePrinter.toDocument(t.symbol.tpe).format(getWidth() / getColumnWidth(), buf)
             str.append(buf.toString())
           }
-          str.append("\nSymbol Attributes: \n").append(TreeInfo.symbolAttributes(t))
+          str.append("\n\nSymbol info: \n")
+          TreeInfo.symbolTypeDoc(t).format(getWidth() / getColumnWidth(), buf)
+          str.append(buf.toString())
+          str.append("\n\nSymbol Attributes: \n").append(TreeInfo.symbolAttributes(t))
           str.append("\ntree.tpe: ")
           if (t.tpe ne null) {
             str.append(t.tpe.toString()).append("\n")
@@ -239,7 +252,6 @@ abstract class TreeBrowsers {
     }
   }
 
-
   /** Computes different information about a tree node. It
    *  is used as central place to do all pattern matching against
    *  Tree.
@@ -290,9 +302,6 @@ abstract class TreeBrowsers {
       case Block(stats, expr) =>
         ("Block", EMPTY)
 
-      case Sequence(trees) =>
-        ("Sequence", EMPTY)
-
       case Alternative(trees) =>
         ("Alternative", EMPTY)
 
@@ -356,9 +365,6 @@ abstract class TreeBrowsers {
       case Annotated(annot, arg) =>
         ("Annotated", EMPTY)
         
-      case Annotation(constr, elements) =>
-        ("Annotation", EMPTY)
-        
       case SingletonTypeTree(ref) =>
         ("SingletonType", EMPTY)
 
@@ -407,7 +413,7 @@ abstract class TreeBrowsers {
         mods.annotations ::: impl :: children
       }
 
-      case PackageDef(name, stats) =>
+      case PackageDef(pid, stats) =>
         stats
 
       case ModuleDef(mods, name, impl) =>
@@ -416,20 +422,14 @@ abstract class TreeBrowsers {
       case ValDef(mods, name, tpe, rhs) =>
         mods.annotations ::: List(tpe, rhs)
 
-      case DefDef(mods, name, tparams, vparams, tpe, rhs) => {
-        var children: List[Tree] = List()
-        children = tparams ::: children
-        children = List.flatten(vparams) ::: children
-        mods.annotations ::: tpe :: rhs :: children
-      }
+      case DefDef(mods, name, tparams, vparams, tpe, rhs) =>
+        mods.annotations ::: tpe :: rhs :: vparams.flatten ::: tparams
 
       case TypeDef(mods, name, tparams, rhs) =>
         mods.annotations ::: rhs :: tparams // @M: was List(rhs, lobound)
 
-      case Import(expr, selectors) => {
-        var children: List[Tree] = List(expr)
-        children
-      }
+      case Import(expr, selectors) =>
+        List(expr)
 
       case CaseDef(pat, guard, body) =>
         List(pat, guard, body)
@@ -443,9 +443,6 @@ abstract class TreeBrowsers {
       case Block(stats, expr) =>
         stats ::: List(expr)
 
-      case Sequence(trees) =>
-        trees
-
       case Alternative(trees) =>
         trees
 
@@ -507,10 +504,7 @@ abstract class TreeBrowsers {
         Nil
 
       case Annotated(annot, arg) =>
-        annot.constr :: annot.elements ::: List(arg)
-      
-      case Annotation(constr, elements) =>
-        constr :: elements
+        annot :: List(arg)
         
       case SingletonTypeTree(ref) =>
         List(ref)
@@ -545,12 +539,10 @@ abstract class TreeBrowsers {
 
     /** Return a textual representation of this t's symbol */
     def symbolText(t: Tree): String = {
-      var prefix = ""
-
-      if (t.hasSymbol)
-        prefix = "[has] "
-      if (t.isDef)
-        prefix = "[defines] "
+      val prefix =
+        if (t.hasSymbol)  "[has] "
+        else if (t.isDef) "[defines] "
+        else ""
 
       prefix + t.symbol
     }
@@ -573,8 +565,9 @@ abstract class TreeBrowsers {
       if ((s ne null) && (s != NoSymbol)) {
         var str = flagsToString(s.flags)
         if (s.isStaticMember) str = str + " isStatic ";
-        str
-      }
+        (str + " annotations: " + s.annotations.mkString("", " ", "")
+          + (if (s.isTypeSkolem) "\ndeSkolemized annotations: " + s.deSkolemize.annotations.mkString("", " ", "") else "")) 
+      } 
       else ""
     }
   }
@@ -626,7 +619,7 @@ abstract class TreeBrowsers {
         Document.group(
           Document.nest(4, "TypeRef(" :/: 
                         toDocument(pre) :: ", " :/:
-                        sym.name.toString() :: ", " :/:
+                        sym.name.toString() + sym.idString :: ", " :/:
                         "[ " :: toDocument(args) ::"]" :: ")")
         )
 
@@ -647,14 +640,14 @@ abstract class TreeBrowsers {
         Document.group(
           Document.nest(4,"ClassInfoType(" :/:
                         toDocument(parents) :: ", " :/:
-                        clazz.name.toString() :: ")")
+                        clazz.name.toString() + clazz.idString :: ")")
         )
 
-      case MethodType(paramtypes, result) =>
+      case MethodType(params, result) =>
         Document.group(
           Document.nest(4, "MethodType(" :/:
                         Document.group("(" :/:
-                                       toDocument(paramtypes) :/:
+                                       symsToDocument(params) :/:
                                        "), ") :/:
                         toDocument(result) :: ")")
         )
@@ -668,10 +661,10 @@ abstract class TreeBrowsers {
                         toDocument(result) :: ")")
         )
         
-      case AnnotatedType(attribs, tp, _) =>
+      case AnnotatedType(annots, tp, _) =>
         Document.group(
           Document.nest(4, "AnnotatedType(" :/:
-                        attribs.mkString("[", ",", "]") :/:
+                        annots.mkString("[", ",", "]") :/:
                         "," :/: toDocument(tp) :: ")")
         )
         
@@ -691,7 +684,7 @@ abstract class TreeBrowsers {
                         toDocument(thistpe) :/: ", " :/:
                         toDocument(supertpe) ::")"))
       case _ =>
-        throw new Error("Unknown case: " + t.toString() +", "+ t.getClass)
+        Predef.error("Unknown case: " + t.toString() +", "+ t.getClass)
     }
   }
 
diff --git a/src/compiler/scala/tools/nsc/ast/TreeDSL.scala b/src/compiler/scala/tools/nsc/ast/TreeDSL.scala
new file mode 100644
index 0000000..cac5ef6
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/ast/TreeDSL.scala
@@ -0,0 +1,267 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
+ *
+ * @author  Paul Phillips
+ */
+
+package scala.tools.nsc
+package ast
+
+import PartialFunction._
+
+/** A DSL for generating scala code.  The goal is that the
+ *  code generating code should look a lot like the code it
+ *  generates.
+ */
+
+trait TreeDSL { 
+  val global: Global
+  
+  import global._
+  import definitions._
+  import gen.{ scalaDot }
+  
+  object CODE {    
+    // Add a null check to a Tree => Tree function
+    def nullSafe[T](f: Tree => Tree, ifNull: Tree): Tree => Tree =
+      tree => IF (tree MEMBER_== NULL) THEN ifNull ELSE f(tree)
+    
+    // strip bindings to find what lies beneath
+    final def unbind(x: Tree): Tree = x match {
+      case Bind(_, y) => unbind(y)
+      case y          => y
+    }
+
+    def returning[T](x: T)(f: T => Unit): T = util.returning(x)(f)
+    
+    object LIT extends (Any => Literal) {
+      def apply(x: Any)   = Literal(Constant(x))
+      def unapply(x: Any) = condOpt(x) { case Literal(Constant(value)) => value }
+    }
+    
+    // You might think these could all be vals, but empirically I have found that
+    // at least in the case of UNIT the compiler breaks if you re-use trees.
+    // However we need stable identifiers to have attractive pattern matching.
+    // So it's inconsistent until I devise a better way.
+    val TRUE          = LIT(true)
+    val FALSE         = LIT(false)
+    val ZERO          = LIT(0)
+    def NULL          = LIT(null)
+    def UNIT          = LIT(())
+    
+    object WILD {
+      def apply(tpe: Type = null) =
+        if (tpe == null) Ident(nme.WILDCARD)
+        else Ident(nme.WILDCARD) setType tpe
+        
+      def unapply(other: Any) =
+        cond(other) { case Ident(nme.WILDCARD)  => true }
+    }
+    
+    def fn(lhs: Tree, op:   Name, args: Tree*)  = Apply(Select(lhs, op), args.toList)
+    def fn(lhs: Tree, op: Symbol, args: Tree*)  = Apply(Select(lhs, op), args.toList)
+    
+    class TreeMethods(target: Tree) {
+      private def toAnyRef(x: Tree) = x setType AnyRefClass.tpe
+      
+      /** logical/comparison ops **/
+      def OR(other: Tree) = 
+        if (target == EmptyTree) other
+        else if (other == EmptyTree) target
+        else gen.mkOr(target, other)
+        
+      def AND(other: Tree) = 
+        if (target == EmptyTree) other
+        else if (other == EmptyTree) target
+        else gen.mkAnd(target, other)
+      
+      /** Note - calling ANY_== in the matcher caused primitives to get boxed
+       *  for the comparison, whereas looking up nme.EQ does not.  See #3570 for
+       *  an example of how target.tpe can be non-null, yet it claims not to have
+       *  a mmeber called nme.EQ.  Not sure if that should happen, but we can be
+       *  robust by dragging in Any regardless.
+       */
+      def MEMBER_== (other: Tree)   = {
+        val opSym = if (target.tpe == null) NoSymbol else target.tpe member nme.EQ
+        if (opSym == NoSymbol) ANY_==(other)
+        else fn(target, opSym, other)
+      }
+      def ANY_EQ  (other: Tree)     = fn(target, nme.eq, toAnyRef(other))
+      def ANY_NE  (other: Tree)     = fn(target, nme.ne, toAnyRef(other))
+      def ANY_==  (other: Tree)     = fn(target, Any_==, other)
+      def ANY_!=  (other: Tree)     = fn(target, Any_!=, other)
+      def OBJ_==  (other: Tree)     = fn(target, Object_==, other)
+      def OBJ_!=  (other: Tree)     = fn(target, Object_!=, other)
+      def OBJ_EQ  (other: Tree)     = fn(target, Object_eq, other)
+      def OBJ_NE  (other: Tree)     = fn(target, Object_ne, other)
+      
+      def INT_|   (other: Tree)     = fn(target, getMember(IntClass, nme.OR), other)
+      def INT_&   (other: Tree)     = fn(target, getMember(IntClass, nme.AND), other)
+      def INT_>=  (other: Tree)     = fn(target, getMember(IntClass, nme.GE), other)
+      def INT_==  (other: Tree)     = fn(target, getMember(IntClass, nme.EQ), other)
+      def INT_!=  (other: Tree)     = fn(target, getMember(IntClass, nme.NE), other)
+      
+      def BOOL_&& (other: Tree)     = fn(target, getMember(BooleanClass, nme.ZAND), other)
+      def BOOL_|| (other: Tree)     = fn(target, getMember(BooleanClass, nme.ZOR), other)
+      
+      /** Apply, Select, Match **/
+      def APPLY(params: Tree*)      = Apply(target, params.toList)
+      def APPLY(params: List[Tree]) = Apply(target, params)
+      def MATCH(cases: CaseDef*)    = Match(target, cases.toList)
+      
+      def DOT(member: Name)         = SelectStart(Select(target, member))
+      def DOT(sym: Symbol)          = SelectStart(Select(target, sym))
+      
+      /** Assignment */
+      def ===(rhs: Tree)            = Assign(target, rhs)
+      
+      /** Methods for sequences **/      
+      def DROP(count: Int): Tree =
+        if (count == 0) target
+        else (target DOT nme.drop)(LIT(count))
+      
+      /** Casting & type tests -- working our way toward understanding exactly
+       *  what differs between the different forms of IS and AS.
+       *
+       *  See ticket #2168 for one illustration of AS vs. AS_ANY.
+       */
+      def AS(tpe: Type)       = TypeApply(Select(target, Any_asInstanceOf), List(TypeTree(tpe)))
+      def AS_ANY(tpe: Type)   = gen.mkAsInstanceOf(target, tpe)
+      def AS_ATTR(tpe: Type)  = gen.mkAttributedCast(target, tpe)
+
+      def IS(tpe: Type)       = gen.mkIsInstanceOf(target, tpe, true)
+      def IS_OBJ(tpe: Type)   = gen.mkIsInstanceOf(target, tpe, false)
+      
+      // XXX having some difficulty expressing nullSafe in a way that doesn't freak out value types
+      // def TOSTRING()          = nullSafe(fn(_: Tree, nme.toString_), LIT("null"))(target)
+      def TOSTRING()          = fn(target, nme.toString_)
+      def GETCLASS()          = fn(target, Object_getClass)
+    }
+    
+    case class SelectStart(tree: Select) {
+      def apply(args: Tree*) = Apply(tree, args.toList)
+    }
+    
+    class CaseStart(pat: Tree, guard: Tree) {
+      def IF(g: Tree): CaseStart    = new CaseStart(pat, g)
+      def ==>(body: Tree): CaseDef  = CaseDef(pat, guard, body)
+    }
+    
+    abstract class ValOrDefStart(sym: Symbol) {
+      def ===(body: Tree): ValOrDefDef
+    }
+    class DefStart(sym: Symbol) extends ValOrDefStart(sym) {
+      def ===(body: Tree) = DefDef(sym, body)
+    } 
+    class ValStart(sym: Symbol) extends ValOrDefStart(sym) {
+      def ===(body: Tree) = ValDef(sym, body)
+    } 
+    class IfStart(cond: Tree, thenp: Tree) {
+      def THEN(x: Tree) = new IfStart(cond, x)
+      def ELSE(elsep: Tree) = If(cond, thenp, elsep)
+      def ENDIF = If(cond, thenp, EmptyTree)
+    }
+    class TryStart(body: Tree, catches: List[CaseDef], fin: Tree) {
+      def CATCH(xs: CaseDef*) = new TryStart(body, xs.toList, fin)
+      def FINALLY(x: Tree)    = Try(body, catches, x)
+      def ENDTRY              = Try(body, catches, fin)
+    }
+
+    def CASE(pat: Tree): CaseStart  = new CaseStart(pat, EmptyTree)
+    def DEFAULT: CaseStart          = new CaseStart(WILD(), EmptyTree)    
+    
+    class NameMethods(target: Name) {
+      def BIND(body: Tree) = Bind(target, body)
+    }
+    
+    class SymbolMethods(target: Symbol) {
+      def BIND(body: Tree) = Bind(target, body)
+
+      // Option
+      def IS_DEFINED() =
+        if (target.tpe.typeSymbol == SomeClass) TRUE   // is Some[_]
+        else NOT(ID(target) DOT nme.isEmpty)           // is Option[_]
+      
+      def IS_NULL() = REF(target) ANY_EQ NULL
+      def NOT_NULL() = REF(target) ANY_NE NULL
+      
+      def GET() = fn(REF(target), nme.get)
+      
+      // name of nth indexed argument to a method (first parameter list), defaults to 1st
+      def ARG(idx: Int = 0) = Ident(target.paramss.head(idx))
+      def ARGS = target.paramss.head
+      def ARGNAMES = ARGS map Ident
+    }
+    
+    /** Top level accessible. */
+    def MATCHERROR(arg: Tree) = Throw(New(TypeTree(MatchErrorClass.tpe), List(List(arg))))
+    /** !!! should generalize null guard from match error here. */
+    def THROW(sym: Symbol): Throw = Throw(New(TypeTree(sym.tpe), List(Nil)))
+    def THROW(sym: Symbol, msg: Tree): Throw = Throw(New(TypeTree(sym.tpe), List(List(msg.TOSTRING()))))
+    
+    def NEW(tpe: Tree, args: Tree*)   = New(tpe, List(args.toList))
+    def NEW(sym: Symbol, args: Tree*) = 
+      if (args.isEmpty) New(TypeTree(sym.tpe))
+      else New(TypeTree(sym.tpe), List(args.toList))
+    
+    def VAL(sym: Symbol) = new ValStart(sym)    
+    def DEF(sym: Symbol) = new DefStart(sym)
+    def AND(guards: Tree*) =
+      if (guards.isEmpty) EmptyTree
+      else guards reduceLeft gen.mkAnd
+      
+    def OR(guards: Tree*) =
+      if (guards.isEmpty) EmptyTree
+      else guards reduceLeft gen.mkOr      
+    
+    def IF(tree: Tree)    = new IfStart(tree, EmptyTree)
+    def TRY(tree: Tree)   = new TryStart(tree, Nil, EmptyTree)
+    def BLOCK(xs: Tree*)  = Block(xs.init.toList, xs.last)
+    def NOT(tree: Tree)   = Select(tree, getMember(BooleanClass, nme.UNARY_!))
+    
+    private val _SOME     = scalaDot(nme.Some)
+    def SOME(xs: Tree*)   = Apply(_SOME, List(makeTupleTerm(xs.toList, true)))
+    
+    /** Typed trees from symbols. */
+    def THIS(sym: Symbol)             = gen.mkAttributedThis(sym)
+    def ID(sym: Symbol)               = gen.mkAttributedIdent(sym)
+    def REF(sym: Symbol)              = gen.mkAttributedRef(sym)
+    def REF(pre: Type, sym: Symbol)   = gen.mkAttributedRef(pre, sym)
+
+    /** Some of this is basically verbatim from TreeBuilder, but we do not want
+     *  to get involved with him because he's an untyped only sort.
+     */
+    private def tupleName(count: Int, f: (String) => Name = newTermName(_: String)) =
+      scalaDot(f("Tuple" + count))
+
+    def makeTupleTerm(trees: List[Tree], flattenUnary: Boolean): Tree = trees match {
+      case Nil                        => UNIT
+      case List(tree) if flattenUnary => tree
+      case _                          => Apply(tupleName(trees.length), trees)
+    }
+    def makeTupleType(trees: List[Tree], flattenUnary: Boolean): Tree = trees match {
+      case Nil                        => gen.scalaUnitConstr
+      case List(tree) if flattenUnary => tree
+      case _                          => AppliedTypeTree(tupleName(trees.length, newTypeName), trees)
+    }
+
+    /** Implicits - some of these should probably disappear **/
+    implicit def mkTreeMethods(target: Tree): TreeMethods = new TreeMethods(target)
+    implicit def mkTreeMethodsFromSymbol(target: Symbol): TreeMethods = new TreeMethods(Ident(target))
+    implicit def mkTreeMethodsFromName(target: Name): TreeMethods = new TreeMethods(Ident(target))
+    implicit def mkTreeMethodsFromString(target: String): TreeMethods = new TreeMethods(Ident(target))
+    
+    implicit def mkNameMethodsFromName(target: Name): NameMethods = new NameMethods(target)
+    implicit def mkNameMethodsFromString(target: String): NameMethods = new NameMethods(target)
+    
+    implicit def mkSymbolMethodsFromSymbol(target: Symbol): SymbolMethods = new SymbolMethods(target)
+    
+    /** (foo DOT bar) might be simply a Select, but more likely it is to be immediately
+     *  followed by an Apply.  We don't want to add an actual apply method to arbitrary
+     *  trees, so SelectStart is created with an apply - and if apply is not the next
+     *  thing called, the implicit from SelectStart -> Tree will provide the tree.
+     */
+    implicit def mkTreeFromSelectStart(ss: SelectStart): Select = ss.tree
+    implicit def mkTreeMethodsFromSelectStart(ss: SelectStart): TreeMethods = mkTreeMethods(ss.tree)
+  }
+}
diff --git a/src/compiler/scala/tools/nsc/ast/TreeGen.scala b/src/compiler/scala/tools/nsc/ast/TreeGen.scala
index 96bb48e..dcd2a26 100644
--- a/src/compiler/scala/tools/nsc/ast/TreeGen.scala
+++ b/src/compiler/scala/tools/nsc/ast/TreeGen.scala
@@ -1,38 +1,41 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: TreeGen.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.tools.nsc.ast
+package scala.tools.nsc
+package ast
 
 import scala.collection.mutable.ListBuffer
 import symtab.Flags._
 import symtab.SymbolTable
 
+/** XXX to resolve: TreeGen only assumes global is a SymbolTable, but
+ *  TreeDSL at the moment expects a Global.  Can we get by with SymbolTable?
+ */
 abstract class TreeGen {
-
   val global: SymbolTable
 
   import global._
   import definitions._
-  import posAssigner.atPos
-
-  def scalaDot(name: Name): Tree =
-    Select(Ident(nme.scala_) setSymbol ScalaPackage, name)
-  def scalaAnyRefConstr: Tree =
-    scalaDot(nme.AnyRef.toTypeName)
-  def scalaUnitConstr: Tree =
-    scalaDot(nme.Unit.toTypeName)
-  def scalaScalaObjectConstr: Tree =
-    scalaDot(nme.ScalaObject.toTypeName)
-  def productConstr: Tree = 
-    scalaDot(nme.Product.toTypeName)
-
-  def scalaFunctionConstr(argtpes: List[Tree], restpe: Tree): Tree = 
-    AppliedTypeTree(
-      scalaDot(newTypeName("Function"+argtpes.length)),
-      argtpes ::: List(restpe))
+  
+  def rootId(name: Name)          = Select(Ident(nme.ROOTPKG), name)
+  def rootScalaDot(name: Name)    = Select(rootId(nme.scala_) setSymbol ScalaPackage, name)
+  def scalaDot(name: Name)        = Select(Ident(nme.scala_) setSymbol ScalaPackage, name)
+  def scalaAnyRefConstr           = scalaDot(nme.AnyRef.toTypeName)
+  def scalaUnitConstr             = scalaDot(nme.Unit.toTypeName)
+  def scalaScalaObjectConstr      = scalaDot(nme.ScalaObject.toTypeName)
+  def productConstr               = scalaDot(nme.Product.toTypeName)
+  
+  private def isRootOrEmptyPackageClass(s: Symbol) = s.isRoot || s.isEmptyPackageClass
+  
+  def scalaFunctionConstr(argtpes: List[Tree], restpe: Tree, abstractFun: Boolean = false): Tree = {
+    val cls = if (abstractFun)
+      mkAttributedRef(AbstractFunctionClass(argtpes.length))
+    else
+      mkAttributedRef(FunctionClass(argtpes.length))
+    AppliedTypeTree(cls, argtpes ::: List(restpe))
+  }
 
   /** Builds a reference to value whose type is given stable prefix.
    *  The type must be suitable for this.  For example, it
@@ -51,7 +54,7 @@ abstract class TreeGen {
     case NoPrefix =>
       EmptyTree
     case ThisType(clazz) =>
-      if (clazz.isRoot || clazz.isEmptyPackageClass) EmptyTree
+      if (isRootOrEmptyPackageClass(clazz)) EmptyTree
       else mkAttributedThis(clazz)
     case SingleType(pre, sym) =>
       val qual = mkAttributedStableRef(pre, sym)
@@ -77,9 +80,9 @@ abstract class TreeGen {
         mkAttributedThis(sym)
       } else if (sym.isType) {
         assert(termSym != NoSymbol)
-	mkAttributedIdent(termSym) setType tpe
+        mkAttributedIdent(termSym) setType tpe
       } else {
-	mkAttributedRef(pre, sym)
+        mkAttributedRef(pre, sym)
       }
 
     case ConstantType(value) =>
@@ -96,16 +99,16 @@ abstract class TreeGen {
       mkAttributedQualifier(firstStable.get)
 
     case _ =>
-      throw new Error("bad qualifier: " + tpe)
+      abort("bad qualifier: " + tpe)
   }
 
   /** Builds a reference to given symbol with given stable prefix. */
   def mkAttributedRef(pre: Type, sym: Symbol): Tree = {
     val qual = mkAttributedQualifier(pre)
     qual match {
-      case EmptyTree => mkAttributedIdent(sym)
-      case This(clazz) if (qual.symbol.isRoot || qual.symbol.isEmptyPackageClass) => mkAttributedIdent(sym)
-      case _ => mkAttributedSelect(qual, sym)
+      case EmptyTree                                              => mkAttributedIdent(sym)
+      case This(clazz) if isRootOrEmptyPackageClass(qual.symbol)  => mkAttributedIdent(sym)
+      case _                                                      => mkAttributedSelect(qual, sym)
     }
   }
 
@@ -115,28 +118,30 @@ abstract class TreeGen {
     else mkAttributedIdent(sym)
 
   /** Replaces tree type with a stable type if possible */
-  def stabilize(tree: Tree): Tree = tree match {
-    case Ident(_) =>
-      if (tree.symbol.isStable) tree.setType(singleType(tree.symbol.owner.thisType, tree.symbol))
-      else tree
-    case Select(qual, _) =>
-      assert(tree.symbol ne null)
-      assert(qual.tpe ne null)
-      if (tree.symbol.isStable && qual.tpe.isStable)
-        tree.setType(singleType(qual.tpe, tree.symbol))
-      else tree
+  def stabilize(tree: Tree): Tree = {
+    for(tp <- stableTypeFor(tree)) tree.tpe = tp
+    tree
+  }
+
+  /** Computes stable type for a tree if possible */
+  def stableTypeFor(tree: Tree): Option[Type] = tree match {
+    case Ident(_) if tree.symbol.isStable =>
+      Some(singleType(tree.symbol.owner.thisType, tree.symbol))
+    case Select(qual, _) if   {assert((tree.symbol ne null) && (qual.tpe ne null)); 
+                            tree.symbol.isStable && qual.tpe.isStable} =>
+      Some(singleType(qual.tpe, tree.symbol))
     case _ =>
-      tree
+      None
   }
 
   /** Cast `tree' to type `pt' */
-  def mkAttributedCastUntyped(tree: Tree, pt: Type): Tree = {
+  def mkCast(tree: Tree, pt: Type): Tree = {
     if (settings.debug.value) log("casting " + tree + ":" + tree.tpe + " to " + pt)
     assert(!tree.tpe.isInstanceOf[MethodType], tree)
-    assert(pt eq pt.normalize) //@MAT only called during erasure, which already takes care of that
-    atPos(tree.pos) {
-      Apply(TypeApply(mkAttributedSelect(tree, Object_asInstanceOf), List(TypeTree(pt))), List())
-    }
+    assert(!pt.typeSymbol.isPackageClass)
+    assert(!pt.typeSymbol.isPackageObjectClass)
+    assert(pt eq pt.normalize, tree +" : "+ debugString(pt) +" ~>"+ debugString(pt.normalize)) //@MAT only called during erasure, which already takes care of that
+    atPos(tree.pos)(mkAsInstanceOf(tree, pt, false))
   }
 
   /** Builds a reference with stable type to given symbol */
@@ -149,62 +154,68 @@ abstract class TreeGen {
   def mkAttributedThis(sym: Symbol): Tree =
     This(sym.name) setSymbol sym setType sym.thisType
 
-  def mkAttributedIdent(sym: Symbol): Tree = {
+  def mkAttributedIdent(sym: Symbol): Tree =
     Ident(sym.name) setSymbol sym setType sym.tpe
-  }
 
-  def mkAttributedSelect(qual: Tree, sym: Symbol): Tree =
-    if ((qual.symbol ne null) &&
-        (qual.symbol.name.toTermName == nme.ROOT ||
-         qual.symbol.name.toTermName == nme.EMPTY_PACKAGE_NAME)) {
+  def mkAttributedSelect(qual: Tree, sym: Symbol): Tree = {
+    def tpe = qual.tpe
+    
+    def isUnqualified(n: Name)        = n match { case nme.ROOT | nme.EMPTY_PACKAGE_NAME => true ; case _ => false }
+    def hasUnqualifiedName(s: Symbol) = s != null && isUnqualified(s.name.toTermName)
+    def isInPkgObject(s: Symbol)      = s != null && s.owner.isPackageObjectClass && s.owner.owner == tpe.typeSymbol
+    
+    if (hasUnqualifiedName(qual.symbol))
       mkAttributedIdent(sym)
-    } else {
-      val result = Select(qual, sym.name) setSymbol sym
-      if (qual.tpe ne null) result setType qual.tpe.memberType(sym)
-      result
+    else {
+      val pkgQualifier            =
+        if (!isInPkgObject(sym)) qual else {
+          val obj = sym.owner.sourceModule
+          Select(qual, nme.PACKAGEkw) setSymbol obj setType singleType(tpe, obj)
+        }
+      val tree = Select(pkgQualifier, sym)
+      
+      if (pkgQualifier.tpe == null) tree
+      else tree setType (tpe memberType sym)
     }
-
-  /** Builds an instance test with given value and type. */
-  def mkIsInstanceOf(value: Tree, tpe: Type, erased: Boolean): Tree = { // buraq: we ignore erase, no rtt
-    val sym = definitions.Any_isInstanceOf
-    /*
-    val sym =
-      if (erased) definitions.Any_isInstanceOfErased
-      else definitions.Any_isInstanceOf
-        */
+  }
+  
+  private def mkTypeApply(value: Tree, tpe: Type, what: Symbol) =
     Apply(
       TypeApply(
-        mkAttributedSelect(value, sym),
-        List(TypeTree(tpe.normalize))),
-      List())
-  }
-
-  def mkIsInstanceOf(value: Tree, tpe: Type): Tree = {
-    mkIsInstanceOf(value, tpe, false/*global.phase.erasedTypes*/) // buraq: ignore which phase it is
-  }
+        mkAttributedSelect(value, what),
+        List(TypeTree(tpe.normalize))
+      ),
+      Nil
+    )
+  /** Builds an instance test with given value and type. */
+  def mkIsInstanceOf(value: Tree, tpe: Type, any: Boolean = true): Tree =
+    mkTypeApply(value, tpe, (if (any) Any_isInstanceOf else Object_isInstanceOf))
 
   /** Builds a cast with given value and type. */
-  def mkAsInstanceOf(value: Tree, tpe: Type, erased: Boolean): Tree = {
-    val sym =
-      if (erased) definitions.Any_asInstanceOfErased
-      else definitions.Any_asInstanceOf
-
-    Apply(
-      TypeApply(
-        mkAttributedSelect(value, sym),
-        List(TypeTree(tpe.normalize))),
-      List())
-  }
+  def mkAsInstanceOf(value: Tree, tpe: Type, any: Boolean = true): Tree =
+    mkTypeApply(value, tpe, (if (any) Any_asInstanceOf else Object_asInstanceOf))
 
-  def mkAsInstanceOf(value: Tree, tpe: Type): Tree =
-    mkAsInstanceOf(value, tpe, global.phase.erasedTypes)
+  /** Cast `tree' to 'pt', unless tpe is a subtype of pt, or pt is Unit.  */
+  def maybeMkAsInstanceOf(tree: Tree, pt: Type, tpe: Type, beforeRefChecks: Boolean = false): Tree =
+    if ((pt == UnitClass.tpe) || (tpe <:< pt)) {
+      log("no need to cast from " + tpe + " to " + pt)
+      tree
+    } else
+      atPos(tree.pos) {
+        if (beforeRefChecks)
+          TypeApply(mkAttributedSelect(tree, Any_asInstanceOf), List(TypeTree(pt)))
+        else
+          mkAsInstanceOf(tree, pt)
+      }
 
   def mkClassOf(tp: Type): Tree = 
-    Literal(Constant(tp)) setType Predef_classOfType(tp)
+    Literal(Constant(tp)) setType ConstantType(Constant(tp))// ClassType(tp)
 
   def mkCheckInit(tree: Tree): Tree = {
-    var tpe = tree.tpe
-    if (tpe == null && tree.hasSymbol) tpe = tree.symbol.tpe
+    val tpe =
+      if (tree.tpe != null || !tree.hasSymbol) tree.tpe
+      else tree.symbol.tpe
+
     if (!global.phase.erasedTypes && settings.Xchecknull.value && 
         tpe <:< NotNullClass.tpe && !tpe.isNotNull)
       mkRuntimeCall(nme.checkInitialized, List(tree))
@@ -214,25 +225,29 @@ abstract class TreeGen {
 
   /** Builds a list with given head and tail. */
   def mkNewCons(head: Tree, tail: Tree): Tree =
-    New(Apply(mkAttributedRef(definitions.ConsClass), List(head, tail)))
+    New(Apply(mkAttributedRef(ConsClass), List(head, tail)))
 
   /** Builds a list with given head and tail. */
-  def mkNil: Tree =
-    mkAttributedRef(definitions.NilModule)
+  def mkNil: Tree = mkAttributedRef(NilModule)
 
   /** Builds a tuple */
   def mkTuple(elems: List[Tree]): Tree =
     if (elems.isEmpty) Literal(())
     else Apply(
-      Select(mkAttributedRef(definitions.TupleClass(elems.length).caseModule), nme.apply),
+      Select(mkAttributedRef(TupleClass(elems.length).caseModule), nme.apply),
       elems)
 
-  def mkAnd(tree1: Tree, tree2: Tree) = 
+  // tree1 AND tree2
+  def mkAnd(tree1: Tree, tree2: Tree): Tree =
     Apply(Select(tree1, Boolean_and), List(tree2))
 
-  def mkOr(tree1: Tree, tree2: Tree) = 
+  // tree1 OR tree2
+  def mkOr(tree1: Tree, tree2: Tree): Tree =
     Apply(Select(tree1, Boolean_or), List(tree2))
 
+  // wrap the given expression in a SoftReference so it can be gc-ed
+  def mkSoftRef(expr: Tree): Tree = New(TypeTree(SoftReferenceClass.tpe), List(List(expr)))
+
   def mkCached(cvar: Symbol, expr: Tree): Tree = {
     val cvarRef = if (cvar.owner.isClass) Select(This(cvar.owner), cvar) else Ident(cvar)
     Block(
@@ -245,8 +260,22 @@ abstract class TreeGen {
   }
 
   // var m$: T = null; or, if class member: local var m$: T = _;
+  /*!!!
+  def mkModuleValDef(accessor: Symbol) = {
+    val mval = accessor.owner.newValue(accessor.pos.focus, nme.moduleVarName(accessor.name))
+      .setInfo(accessor.tpe.finalResultType)
+      .setFlag(LAZY);
+    if (mval.owner.isClass) {
+      mval setFlag (PRIVATE | LOCAL | SYNTHETIC)
+      mval.owner.info.decls.enter(mval)
+    } 
+    ValDef(mval, New(TypeTree(mval.tpe), List(List())))
+  }
+  */
+  
+  // var m$: T = null; or, if class member: local var m$: T = _;
   def mkModuleVarDef(accessor: Symbol) = {
-    val mvar = accessor.owner.newVariable(accessor.pos, nme.moduleVarName(accessor.name))
+    val mvar = accessor.owner.newVariable(accessor.pos.focus, nme.moduleVarName(accessor.name))
       .setInfo(accessor.tpe.finalResultType)
       .setFlag(MODULEVAR);
     if (mvar.owner.isClass) {
@@ -259,12 +288,12 @@ abstract class TreeGen {
   // def m: T = { if (m$ eq null) m$ = new m$class(...) m$ }
   // where (...) are eventual outer accessors
   def mkCachedModuleAccessDef(accessor: Symbol, mvar: Symbol) =
-    DefDef(accessor, vparamss => mkCached(mvar, newModule(accessor, mvar.tpe)))
+    DefDef(accessor, mkCached(mvar, newModule(accessor, mvar.tpe)))
 
   // def m: T = new tpe(...)
   // where (...) are eventual outer accessors
   def mkModuleAccessDef(accessor: Symbol, tpe: Type) =
-    DefDef(accessor, vparamss => newModule(accessor, tpe))
+    DefDef(accessor, newModule(accessor, tpe))
 
   private def newModule(accessor: Symbol, tpe: Type) =
     New(TypeTree(tpe), 
@@ -273,21 +302,26 @@ abstract class TreeGen {
 
   // def m: T;
   def mkModuleAccessDcl(accessor: Symbol) = 
-    DefDef(accessor setFlag lateDEFERRED, vparamss => EmptyTree)
+    DefDef(accessor setFlag lateDEFERRED, EmptyTree)
 
-  def mkRuntimeCall(meth: Name, args: List[Tree]): Tree =
+  def mkRuntimeCall(meth: Name, args: List[Tree]): Tree = {
     Apply(Select(mkAttributedRef(ScalaRunTimeModule), meth), args)
+  }
+
+  def mkRuntimeCall(meth: Name, targs: List[Type], args: List[Tree]): Tree = {
+    Apply(TypeApply(Select(mkAttributedRef(ScalaRunTimeModule), meth), targs map TypeTree), args)
+  }
 
   /** Make a synchronized block on 'monitor'. */
   def mkSynchronized(monitor: Tree, body: Tree): Tree =     
-    Apply(Select(monitor, definitions.Object_synchronized), List(body))
+    Apply(Select(monitor, Object_synchronized), List(body))
 
   def wildcardStar(tree: Tree) =
     atPos(tree.pos) { Typed(tree, Ident(nme.WILDCARD_STAR.toTypeName)) }
 
   def paramToArg(vparam: Symbol) = {
     val arg = Ident(vparam)
-    if (vparam.tpe.typeSymbol == RepeatedParamClass) wildcardStar(arg)
+    if (isRepeatedParamType(vparam.tpe)) wildcardStar(arg)
     else arg
   }
 
@@ -301,35 +335,85 @@ abstract class TreeGen {
   def mkForwarder(target: Tree, vparamss: List[List[Symbol]]) =
     (target /: vparamss)((fn, vparams) => Apply(fn, vparams map paramToArg))
     
+  /** Applies a wrapArray call to an array, making it a WrappedArray
+   */
+  def mkWrapArray(tree: Tree, elemtp: Type) = {
+    val predef = mkAttributedRef(PredefModule)
+    val meth = 
+      if ((elemtp <:< AnyRefClass.tpe) && !isPhantomClass(elemtp.typeSymbol) || 
+          isValueClass(elemtp.typeSymbol))
+        Select(predef, "wrapArray")
+      else
+        TypeApply(Select(predef, "genericWrapArray"), List(TypeTree(elemtp)))
+    Apply(meth, List(tree))
+  }
+
+  /** Try to convert Select(qual, name) to a SelectFromTypeTree.
+   */
+  def convertToSelectFromType(qual: Tree, name: Name): Tree = {
+    def selFromType(qual1: Tree) = SelectFromTypeTree(qual1 setPos qual.pos, name)
+    qual match {
+      case Select(qual1, name) => selFromType(Select(qual1, name.toTypeName))
+      case Ident(name) => selFromType(Ident(name.toTypeName))
+      case _ => EmptyTree
+    }
+  }
+
   /** Used in situations where you need to access value of an expression several times
    */
-  def evalOnce(expr: Tree, owner: Symbol, unit: CompilationUnit)(within: (() => Tree) => Tree): Tree =
+  def evalOnce(expr: Tree, owner: Symbol, unit: CompilationUnit)(within: (() => Tree) => Tree): Tree = {
+    var used = false
     if (treeInfo.isPureExpr(expr)) {
-      within(() => expr);
+      within(() => if (used) expr.duplicate else { used = true; expr })
     } else {
-      val temp = owner.newValue(expr.pos, unit.fresh.newName(expr.pos, "ev$"))
-      .setFlag(SYNTHETIC).setInfo(expr.tpe);
-      atPos(expr.pos) {
-        Block(List(ValDef(temp, expr)), within(() => Ident(temp) setType expr.tpe))
-      }
+      val temp = owner.newValue(expr.pos.makeTransparent, unit.fresh.newName(expr.pos, "ev$"))
+        .setFlag(SYNTHETIC).setInfo(expr.tpe)
+      val containing = within(() => Ident(temp) setPos temp.pos.focus setType expr.tpe)
+      ensureNonOverlapping(containing, List(expr))
+      Block(List(ValDef(temp, expr)), containing) setPos (containing.pos union expr.pos)
     }
+  }
 
   def evalOnceAll(exprs: List[Tree], owner: Symbol, unit: CompilationUnit)(within: (List[() => Tree]) => Tree): Tree = {
     val vdefs = new ListBuffer[ValDef]
     val exprs1 = new ListBuffer[() => Tree]
+    val used = new Array[Boolean](exprs.length)
+    var i = 0
     for (expr <- exprs) {
       if (treeInfo.isPureExpr(expr)) {
-        exprs1 += (() => expr)
+        exprs1 += {
+          val idx = i
+          () => if (used(idx)) expr.duplicate else { used(idx) = true; expr }
+        }
       } else {
-        val temp = owner.newValue(expr.pos, unit.fresh.newName(expr.pos))
+        val temp = owner.newValue(expr.pos.makeTransparent, unit.fresh.newName(expr.pos, "ev$"))
           .setFlag(SYNTHETIC).setInfo(expr.tpe)
         vdefs += ValDef(temp, expr)
-        exprs1 += (() => Ident(temp) setType expr.tpe)
+        exprs1 += (() => Ident(temp) setPos temp.pos.focus setType expr.tpe)
       }
+      i += 1
     }
     val prefix = vdefs.toList
-    val result = within(exprs1.toList)
-    if (prefix.isEmpty) result
-    else Block(prefix, result) setPos prefix.head.pos
+    val containing = within(exprs1.toList)
+    ensureNonOverlapping(containing, exprs)
+    if (prefix.isEmpty) containing
+    else Block(prefix, containing) setPos (prefix.head.pos union containing.pos)
+  }
+
+  /** Return a double-checked locking idiom around the syncBody tree. It guards with 'cond' and
+   *  synchronizez on 'clazz.this'. Additional statements can be included after initialization,
+   *  (outside the synchronized block).
+   *
+   *  The idiom works only if the condition is using a volatile field.
+   *  @see http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html
+   */
+  def mkDoubleCheckedLocking(clazz: Symbol, cond: Tree, syncBody: List[Tree], stats: List[Tree]): Tree = {
+    If(cond,
+       Block(
+         mkSynchronized(
+           mkAttributedThis(clazz),
+           If(cond, Block(syncBody: _*), EmptyTree)) ::
+         stats: _*),
+       EmptyTree)
   }
 }
diff --git a/src/compiler/scala/tools/nsc/ast/TreeInfo.scala b/src/compiler/scala/tools/nsc/ast/TreeInfo.scala
index f6dace5..09addb0 100644
--- a/src/compiler/scala/tools/nsc/ast/TreeInfo.scala
+++ b/src/compiler/scala/tools/nsc/ast/TreeInfo.scala
@@ -1,10 +1,10 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: TreeInfo.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.tools.nsc.ast
+package scala.tools.nsc
+package ast
 
 import symtab.Flags._
 import symtab.SymbolTable
@@ -19,6 +19,7 @@ abstract class TreeInfo {
 
   val trees: SymbolTable
   import trees._
+  import definitions.ThrowableClass
 
   def isTerm(tree: Tree): Boolean = tree.isTerm
   def isType(tree: Tree): Boolean = tree.isType
@@ -85,7 +86,12 @@ abstract class TreeInfo {
     case TypeApply(fn, _) =>
       isPureExpr(fn)
     case Apply(fn, List()) =>
-      isPureExpr(fn)
+      /* Note: After uncurry, field accesses are represented as Apply(getter, Nil),
+       * so an Apply can also be pure.
+       * However, before typing, applications of nullary functional values are also
+       * Apply(function, Nil) trees. To prevent them from being treated as pure,
+       * we check that the callee is a method. */
+      fn.symbol.isMethod && isPureExpr(fn)
     case Typed(expr, _) =>
       isPureExpr(expr)
     case Block(stats, expr) =>
@@ -96,21 +102,24 @@ abstract class TreeInfo {
 
   def mayBeVarGetter(sym: Symbol) = sym.info match {
     case PolyType(List(), _) => sym.owner.isClass && !sym.isStable
-    case _: ImplicitMethodType => sym.owner.isClass && !sym.isStable
+    case mt: MethodType => mt.isImplicit && sym.owner.isClass && !sym.isStable
     case _ => false
   }
 
-  def isVariableOrGetter(tree: Tree) = tree match {
-    case Ident(_) => 
-      tree.symbol.isVariable
-    case Select(qual, _) =>
-      tree.symbol.isVariable ||
-      (mayBeVarGetter(tree.symbol) && 
-       tree.symbol.owner.info.member(nme.getterToSetter(tree.symbol.name)) != NoSymbol)
-    case Apply(Select(qual, nme.apply), _) =>
-      qual.tpe.member(nme.update) != NoSymbol
-    case _ =>
-      false
+  def isVariableOrGetter(tree: Tree) = {
+    def sym       = tree.symbol
+    def isVar     = sym.isVariable
+    def isGetter  = mayBeVarGetter(sym) && sym.owner.info.member(nme.getterToSetter(sym.name)) != NoSymbol
+    
+    tree match {
+      case Ident(_)         => isVar
+      case Select(_, _)     => isVar || isGetter
+      case _                =>
+        methPart(tree) match {
+          case Select(qual, nme.apply)  => qual.tpe.member(nme.update) != NoSymbol
+          case _                        => false
+        }
+    }
   }
 
   /** Is tree a self constructor call?
@@ -146,20 +155,46 @@ abstract class TreeInfo {
     if (name == nme.CONSTRUCTOR || name == nme.MIXIN_CONSTRUCTOR) => constr
     case _ :: stats1 => firstConstructor(stats1)
   }
+  
+  /** The arguments to the first constructor in `stats'. */
+  def firstConstructorArgs(stats: List[Tree]): List[Tree] = firstConstructor(stats) match {
+    case DefDef(_, _, _, args :: _, _, _) => args
+    case _                                => Nil
+  }
 
   /** The value definitions marked PRESUPER in this statement sequence */
   def preSuperFields(stats: List[Tree]): List[ValDef] = 
     for (vdef @ ValDef(mods, _, _, _) <- stats if mods hasFlag PRESUPER) yield vdef
 
-  def isPreSuper(tree: Tree) = tree match {
+  def isEarlyDef(tree: Tree) = tree match {
+    case TypeDef(mods, _, _, _) => mods hasFlag PRESUPER
     case ValDef(mods, _, _, _) => mods hasFlag PRESUPER
     case _ => false
   }
 
+  def isEarlyValDef(tree: Tree) = tree match {
+    case ValDef(mods, _, _, _) => mods hasFlag PRESUPER
+    case _ => false
+  }
+
+  def isEarlyTypeDef(tree: Tree) = tree match {
+    case TypeDef(mods, _, _, _) => mods hasFlag PRESUPER
+    case _ => false
+  }
+
   /** Is type a of the form T* ? */
   def isRepeatedParamType(tpt: Tree) = tpt match {
-    case AppliedTypeTree(Select(_, rp), _) => rp == nme.REPEATED_PARAM_CLASS_NAME.toTypeName
-    case TypeTree() => tpt.tpe.typeSymbol == definitions.RepeatedParamClass
+    case AppliedTypeTree(Select(_, rp), _) => 
+      rp == nme.REPEATED_PARAM_CLASS_NAME.toTypeName ||
+      rp == nme.JAVA_REPEATED_PARAM_CLASS_NAME.toTypeName
+    case TypeTree() => definitions.isRepeatedParamType(tpt.tpe)
+    case _ => false
+  }
+
+  /** Is tpt a by-name parameter type? */
+  def isByNameParamType(tpt: Tree) = tpt match {
+    case AppliedTypeTree(Select(_, n), _) => n == nme.BYNAME_PARAM_CLASS_NAME.toTypeName
+    case TypeTree() => tpt.tpe.typeSymbol == definitions.ByNameParamClass
     case _ => false
   }
 
@@ -167,19 +202,10 @@ abstract class TreeInfo {
   def isLeftAssoc(operator: Name): Boolean =
     operator.length > 0 && operator(operator.length - 1) != ':'
 
-  private val reserved = new HashSet[Name]
+  private val reserved = new HashSet[Name]("reserved", 64)
   reserved addEntry nme.false_
   reserved addEntry nme.true_
   reserved addEntry nme.null_
-  reserved addEntry newTypeName("byte")
-  reserved addEntry newTypeName("char")
-  reserved addEntry newTypeName("short")
-  reserved addEntry newTypeName("int")
-  reserved addEntry newTypeName("long")
-  reserved addEntry newTypeName("float")
-  reserved addEntry newTypeName("double")
-  reserved addEntry newTypeName("boolean")
-  reserved addEntry newTypeName("unit")
 
   /** Is name a variable name? */
   def isVariableName(name: Name): Boolean = {
@@ -216,6 +242,16 @@ abstract class TreeInfo {
     case CaseDef(Bind(_, Ident(nme.WILDCARD)), EmptyTree, _) => true
     case _ => false
   }
+  
+  /** Does this CaseDef catch Throwable? */
+  def catchesThrowable(cdef: CaseDef) = catchesAllOf(cdef, ThrowableClass.tpe)
+  
+  /** Does this CaseDef catch everything of a certain Type? */
+  def catchesAllOf(cdef: CaseDef, threshold: Type) =
+    isDefaultCase(cdef) || (cdef.guard.isEmpty && (unbind(cdef.pat) match {
+      case Typed(Ident(nme.WILDCARD), tpt)  => (tpt.tpe != null) && (threshold <:< tpt.tpe)
+      case _                                => false
+    }))
 
   /** Is this pattern node a catch-all or type-test pattern? */
   def isCatchCase(cdef: CaseDef) = cdef match {
@@ -230,7 +266,7 @@ abstract class TreeInfo {
   private def isSimpleThrowable(tp: Type): Boolean = tp match {
     case TypeRef(pre, sym, args) =>
       (pre == NoPrefix || pre.widen.typeSymbol.isStatic) &&
-      (sym isNonBottomSubClass definitions.ThrowableClass) &&  /* bq */ !sym.isTrait
+      (sym isNonBottomSubClass ThrowableClass) &&  /* bq */ !sym.isTrait
     case _ =>
       false
   }
@@ -251,20 +287,31 @@ abstract class TreeInfo {
   /** Is this pattern node a sequence-valued pattern? */
   def isSequenceValued(tree: Tree): Boolean = tree match {
     case Bind(_, body) => isSequenceValued(body)
-    case Sequence(_) => true
     case ArrayValue(_, _) => true
     case Star(_) => true
     case Alternative(ts) => ts exists isSequenceValued
     case _ => false
   }
+  
+  /** The underlying pattern ignoring any bindings */
+  def unbind(x: Tree): Tree = x match {
+    case Bind(_, y) => unbind(y)
+    case y          => y
+  }
+  
+  /** Is this tree a Star(_) after removing bindings? */
+  def isStar(x: Tree) = unbind(x) match { 
+    case Star(_)  => true
+    case _        => false
+  }
 
   /** The method part of an application node
    */
   def methPart(tree: Tree): Tree = tree match {
-    case Apply(fn, _) => methPart(fn)
-    case TypeApply(fn, _) => methPart(fn)
+    case Apply(fn, _)           => methPart(fn)
+    case TypeApply(fn, _)       => methPart(fn)
     case AppliedTypeTree(fn, _) => methPart(fn)
-    case _ => tree
+    case _                      => tree
   }
 
   def firstArgument(tree: Tree): Tree = tree match {
@@ -291,17 +338,19 @@ abstract class TreeInfo {
       false
   }
 
-  /** Compilation unit is the predef object
+  /** Compilation unit is class or object 'name' in package 'scala'
    */
-  def isPredefUnit(tree: Tree): Boolean = tree match {
-    case PackageDef(nme.scala_, List(obj)) => isPredefObj(obj)
+  def isUnitInScala(tree: Tree, name: Name) = tree match {
+    case PackageDef(Ident(nme.scala_), defs) => isImplDef(defs, name)
     case _ => false
   }
 
-  private def isPredefObj(tree: Tree): Boolean = tree match {
-    case ModuleDef(_, nme.Predef, _) => true
-    case DocDef(_, tree1) => isPredefObj(tree1)
-    case Annotated(_, tree1) => isPredefObj(tree1)
+  private def isImplDef(trees: List[Tree], name: Name): Boolean = trees match {
+    case Import(_, _) :: xs => isImplDef(xs, name)
+    case DocDef(_, tree1) :: Nil => isImplDef(List(tree1), name)
+    case Annotated(_, tree1) :: Nil => isImplDef(List(tree1), name)
+    case ModuleDef(_, `name`, _) :: Nil => true
+    case ClassDef(_, `name`, _, _) :: Nil => true
     case _ => false
   }
 
@@ -315,4 +364,21 @@ abstract class TreeInfo {
     case TypeDef(_, _, _, _) => !isAbsTypeDef(tree)
     case _ => false
   }
+  
+  /** Some handy extractors for spotting true and false expressions
+   *  through the haze of braces.
+   */
+  abstract class SeeThroughBlocks[T] {
+    protected def unapplyImpl(x: Tree): T
+    def unapply(x: Tree): T = x match {
+      case Block(Nil, expr)         => unapply(expr)
+      case _                        => unapplyImpl(x)
+    }
+  }
+  object IsTrue extends SeeThroughBlocks[Boolean] {
+    protected def unapplyImpl(x: Tree): Boolean = x equalsStructure Literal(Constant(true))
+  }
+  object IsFalse extends SeeThroughBlocks[Boolean] {
+    protected def unapplyImpl(x: Tree): Boolean = x equalsStructure Literal(Constant(false))
+  }
 }
diff --git a/src/compiler/scala/tools/nsc/ast/TreePrinters.scala b/src/compiler/scala/tools/nsc/ast/TreePrinters.scala
index 68e4be2..6722d45 100644
--- a/src/compiler/scala/tools/nsc/ast/TreePrinters.scala
+++ b/src/compiler/scala/tools/nsc/ast/TreePrinters.scala
@@ -1,24 +1,23 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: TreePrinters.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.tools.nsc.ast
+package scala.tools.nsc
+package ast
 
 import compat.Platform.{EOL => LINE_SEPARATOR}
-import java.io.{OutputStream, PrintWriter, Writer}
+import java.io.{ OutputStream, PrintWriter, StringWriter, Writer }
 import symtab.Flags._
 import symtab.SymbolTable
 
-abstract class TreePrinters {
+trait TreePrinters { trees: SymbolTable =>
 
-  val trees: SymbolTable
-  import trees._
+  import treeInfo.{ IsTrue, IsFalse }
 
   final val showOuterTests = false
 
-  class TreePrinter(out: PrintWriter) {
+  class TreePrinter(out: PrintWriter) extends trees.AbsTreePrinter(out) {
     protected var indentMargin = 0
     protected val indentStep = 2
     protected var indentString = "                                        " // 40
@@ -27,8 +26,11 @@ abstract class TreePrinters {
 
     def indent = indentMargin += indentStep
     def undent = indentMargin -= indentStep
+    
+    protected def doPrintPositions = settings.Xprintpos.value
+    def printPosition(tree: Tree) = if (doPrintPositions) print(tree.pos.show)
 
-    def println {
+    def println() {
       out.println()
       while (indentMargin > indentString.length())
         indentString += indentString
@@ -45,8 +47,8 @@ abstract class TreePrinters {
     }
 
     def printColumn(ts: List[Tree], start: String, sep: String, end: String) {
-      print(start); indent; println
-      printSeq(ts){print}{print(sep); println}; undent; println; print(end)
+      print(start); indent; println()
+      printSeq(ts){print}{print(sep); println()}; undent; println(); print(end)
     }
 
     def printRow(ts: List[Tree], start: String, sep: String, end: String) {
@@ -57,7 +59,10 @@ abstract class TreePrinters {
 
     def printTypeParams(ts: List[TypeDef]) {
       if (!ts.isEmpty) {
-        print("["); printSeq(ts){printParam}{print(", ")}; print("]")
+        print("["); printSeq(ts){ t =>
+          printAnnotations(t)
+          printParam(t)
+        }{print(", ")}; print("]")
       }
     }
 
@@ -71,9 +76,11 @@ abstract class TreePrinters {
     def printParam(tree: Tree) {
       tree match {
         case ValDef(mods, name, tp, rhs) =>
+          printPosition(tree)
           printAnnotations(tree)
-          print(symName(tree, name)); printOpt(": ", tp)
+          print(symName(tree, name)); printOpt(": ", tp); printOpt(" = ", rhs)
         case TypeDef(mods, name, tparams, rhs) =>
+          printPosition(tree)
           print(symName(tree, name))
           printTypeParams(tparams); print(rhs)
       }
@@ -87,42 +94,47 @@ abstract class TreePrinters {
           printColumn(List(tree), "{", ";", "}")
       }
     }
-
-    def symName(tree: Tree, name: Name): String =
-      if (tree.symbol != null && tree.symbol != NoSymbol) {
-        ((if (tree.symbol.isMixinConstructor) "/*"+tree.symbol.owner.name+"*/" else "") +
-         tree.symbol.nameString)
-      } else name.toString();
+    
+    private def symNameInternal(tree: Tree, name: Name, decoded: Boolean): String = {
+      val nameToString: Name => String = if (decoded) _.decode else _.toString
+      
+      tree.symbol match {
+        case null | NoSymbol  => nameToString(name)
+        case sym =>
+          val prefix = if (sym.isMixinConstructor) "/*%s*/".format(nameToString(sym.owner.name)) else ""
+          prefix + tree.symbol.nameString
+      }
+    }
+    
+    def decodedSymName(tree: Tree, name: Name) = symNameInternal(tree, name, true)
+    def symName(tree: Tree, name: Name) = symNameInternal(tree, name, false)
 
     def printOpt(prefix: String, tree: Tree) {
       if (!tree.isEmpty) { print(prefix); print(tree) }
     }
 
     def printModifiers(tree: Tree, mods: Modifiers) {
-      if (tree.symbol == NoSymbol)
-        printFlags(mods.flags, mods.privateWithin.toString)
-      else if (tree.symbol.privateWithin == NoSymbol ||
-               tree.symbol.privateWithin == tree.symbol.owner)
-        printFlags(tree.symbol.flags, "")
-      else
-        printFlags(tree.symbol.flags, tree.symbol.privateWithin.name.toString)
+      def pw = tree.symbol.privateWithin
+      val args =
+        if (tree.symbol == NoSymbol) (mods.flags, mods.privateWithin)
+        else if (pw == NoSymbol) (tree.symbol.flags, "")
+        else (tree.symbol.flags, pw.name)
+      
+      printFlags(args._1, args._2.toString)
     }
 
     def printFlags(flags: Long, privateWithin: String) {
       var mask: Long = if (settings.debug.value) -1L else PrintableFlags
       val s = flagsToString(flags & mask, privateWithin)
-      if (s.length() != 0) print(s + " ")
+      if (s != "") print(s + " ")
     }
 
     def printAnnotations(tree: Tree) {
-      val annots = tree.symbol.attributes
-      if (!annots.isEmpty)
-        annots foreach { annot => print("@"+annot+" ") }
-      else {
-        val annots = tree.asInstanceOf[MemberDef].mods.annotations
-        if (!annots.isEmpty) 
-          annots foreach { annot => print("@"+annot+" ") }
-      }
+      val annots =
+        if (tree.symbol.rawAnnotations.nonEmpty) tree.symbol.annotations
+        else tree.asInstanceOf[MemberDef].mods.annotations
+      
+      annots foreach (annot => print("@"+annot+" "))
     }
 
     def print(str: String) { out.print(str) }
@@ -155,7 +167,7 @@ abstract class TreePrinters {
         case ValDef(mods, name, tp, rhs) =>
           printAnnotations(tree)
           printModifiers(tree, mods)
-          print(if (mods.hasFlag(MUTABLE)) "var " else "val ")
+          print(if (mods.isVariable) "var " else "val ")
           print(symName(tree, name))
           printOpt(": ", tp)
           if (!mods.hasFlag(DEFERRED)) {
@@ -172,6 +184,7 @@ abstract class TreePrinters {
 
         case TypeDef(mods, name, tparams, rhs) =>
           if (mods hasFlag (PARAM | DEFERRED)) {
+            printAnnotations(tree)
             printModifiers(tree, mods); print("type "); printParam(tree)
           } else {
             printAnnotations(tree)
@@ -184,35 +197,27 @@ abstract class TreePrinters {
 
         case Import(expr, selectors) =>
           // Is this selector remapping a name (i.e, {name1 => name2})
-          def isNotRemap(s: (Name, Name)) : Boolean = (s._1 == nme.WILDCARD || s._1 == s._2)
-          def selectorToString(s: (Name, Name)): String = 
-              if (isNotRemap(s)) s._1.toString else s._1.toString + "=>" + s._2.toString
+          def isNotRemap(s: ImportSelector) : Boolean = (s.name == nme.WILDCARD || s.name == s.rename)
+          def selectorToString(s: ImportSelector): String = 
+              if (isNotRemap(s)) s.name.toString else s.name.toString + "=>" + s.rename.toString
 
           print("import "); print(expr)
-	  print(".")
+          print(".")
           selectors match {
             case List(s) => 
               // If there is just one selector and it is not remapping a name, no braces are needed
-	      if (isNotRemap(s)) {
-		print(selectorToString(s)) 
-	      } else { 
-		print("{"); print(selectorToString(s)); print("}")
-	      }
+              if (isNotRemap(s)) {
+                print(selectorToString(s)) 
+              } else { 
+                print("{"); print(selectorToString(s)); print("}")
+              }
               // If there is more than one selector braces are always needed
-	    case many =>        
+            case many =>        
               print(many.map(selectorToString).mkString("{", ", ", "}"))
-	  }
+          }
 
         case DocDef(comment, definition) =>
-          print(comment); println; print(definition)
-
-        case Annotation(Apply(Select(New(tpt), nme.CONSTRUCTOR), args), elements) =>
-          print(tpt)
-          if (!args.isEmpty)
-            printRow(args, "(", ",", ")")
-          if (!elements.isEmpty)
-            print((for (Assign(name, value) <- elements) yield "val " + name + " = " + value).
-                  mkString("{", ",", "}"))
+          print(comment.raw); println(); print(definition)
 
         case Template(parents, self, body) =>
           val currentOwner1 = currentOwner
@@ -252,9 +257,6 @@ abstract class TreePrinters {
           print(pat); printOpt(" if ", guard)
           print(" => "); print(body)
 
-        case Sequence(trees) =>
-          printRow(trees, "[", ", ", "]")
-
         case Alternative(trees) =>
           printRow(trees, "(", "| ", ")")
 
@@ -272,15 +274,19 @@ abstract class TreePrinters {
 
         case Function(vparams, body) =>
           print("("); printValueParams(vparams); print(" => "); print(body); print(")")
+          if (settings.uniqid.value && tree.symbol != null) print("#"+tree.symbol.id)
 
         case Assign(lhs, rhs) =>
           print(lhs); print(" = "); print(rhs)
 
+        case AssignOrNamedArg(lhs, rhs) =>
+          print(lhs); print(" = "); print(rhs)
+
         case If(cond, thenp, elsep) =>
-          print("if ("); print(cond); print(")"); indent; println
+          print("if ("); print(cond); print(")"); indent; println()
           print(thenp); undent
           if (!elsep.isEmpty) {
-            println; print("else"); indent; println; print(elsep); undent
+            println(); print("else"); indent; println(); print(elsep); undent
           }
 
         case Return(expr) =>
@@ -332,26 +338,23 @@ abstract class TreePrinters {
         case Literal(x) =>
           print(x.escapedStringValue)
 
-        case TypeTree() =>
-          print(
-            if (tree.tpe eq null)
-              "<type ?>"
-            else if ((tree.tpe.typeSymbol ne null) && tree.tpe.typeSymbol.isAnonymousClass)
-              tree.tpe.typeSymbol.toString()
-            else
-              tree.tpe.toString()
-          )
-
-        case Annotated(Annotation(Apply(Select(New(tpt), nme.CONSTRUCTOR), args), elements), tree) =>
+        case tt: TypeTree =>
+          if (tree.tpe eq null) {
+            if (tt.original != null) { print("<type: "); print(tt.original); print(">") }
+            else print("<type ?>")
+          } else if ((tree.tpe.typeSymbol ne null) && tree.tpe.typeSymbol.isAnonymousClass) {
+            print(tree.tpe.typeSymbol.toString())
+          } else {
+            print(tree.tpe.toString())
+          }
+
+        case Annotated(Apply(Select(New(tpt), nme.CONSTRUCTOR), args), tree) =>
           def printAnnot() {
             print("@"); print(tpt)
             if (!args.isEmpty)
               printRow(args, "(", ",", ")")
-            if (!elements.isEmpty)
-              print((for (Assign(name, value) <- elements) yield "val " + name + " = " + value).
-                    mkString("{", ",", "}"))
           }
-          if (tree.isType) { printAnnot(); print(" "); print(tree) }
+          if (tree.isType) { print(tree); print(" "); printAnnot() }
           else { print(tree); print(": "); printAnnot() }
           
         case SingletonTypeTree(ref) =>
@@ -373,8 +376,11 @@ abstract class TreePrinters {
           print(tpt); 
           printColumn(whereClauses, " forSome { ", ";", "}")
 
-        case tree: StubTree =>
-          print(tree.toString)
+        case SelectFromArray(qualifier, name, _) =>
+          print(qualifier); print(".<arr>"); print(symName(tree, name))
+
+        case TypeTreeWithDeferredRefCheck() =>
+          print("<tree with deferred refcheck>")
 
         case tree => 
           print("<unknown tree of class "+tree.getClass+">")
@@ -385,11 +391,11 @@ abstract class TreePrinters {
     }
 
     def print(tree: Tree) {
-      if (settings.Xprintpos.value) print("[" + tree.pos + "]")
+      printPosition(tree)
       printRaw(
         if (tree.isDef && tree.symbol != NoSymbol && tree.symbol.isInitialized) {
           tree match {
-            case ClassDef(_, _, _, impl @ Template(ps, trees.emptyValDef, body)) 
+            case ClassDef(_, _, _, impl @ Template(ps, emptyValDef, body)) 
             if (tree.symbol.thisSym != tree.symbol) => 
               ClassDef(tree.symbol, Template(ps, ValDef(tree.symbol.thisSym), body))
             case ClassDef(_, _, _, impl)           => ClassDef(tree.symbol, impl)
@@ -405,32 +411,269 @@ abstract class TreePrinters {
     def print(unit: CompilationUnit) {
       print("// Scala source: " + unit.source + LINE_SEPARATOR)
       if (unit.body ne null) {
-        print(unit.body); println
+        print(unit.body); println()
       } else {
         print("<null>")
       }
-      println; flush
+      println(); flush
     }
   }
 
-  def create(writer: PrintWriter): TreePrinter = new TreePrinter(writer)
-  def create(stream: OutputStream): TreePrinter = create(new PrintWriter(stream))
-  def create(): TreePrinter = {
-    /** A writer that writes to the current Console and
-      * is sensitive to replacement of the Console's
-      * output stream.
-      */
-    object ConsoleWriter extends Writer {
-      override def write(str: String) { Console.print(str) }
-
-      def write(cbuf: Array[Char], off: Int, len: Int) {
-        val str = new String(cbuf, off, len)
-        write(str)
-      }
+  /** A tree printer which is stingier about vertical whitespace and unnecessary
+   *  punctuation than the standard one.
+   */
+  class CompactTreePrinter(out: PrintWriter) extends TreePrinter(out) {    
+    override def printRow(ts: List[Tree], start: String, sep: String, end: String) {
+      print(start)
+      printSeq(ts)(print)(print(sep))
+      print(end)
+    }
+    
+    // drill down through Blocks and pull out the real statements.
+    def allStatements(t: Tree): List[Tree] = t match {
+      case Block(stmts, expr) => (stmts flatMap allStatements) ::: List(expr)
+      case _                  => List(t)
+    }
+
+    def printLogicalOr(t1: (Tree, Boolean), t2: (Tree, Boolean)) =
+      printLogicalOp(t1, t2, "||")
+
+    def printLogicalAnd(t1: (Tree, Boolean), t2: (Tree, Boolean)) =
+      printLogicalOp(t1, t2, "&&")
 
-      def close = { /* do nothing */ }
-      def flush = { /* do nothing */ }
+    def printLogicalOp(t1: (Tree, Boolean), t2: (Tree, Boolean), op: String) = {
+      def maybenot(tvalue: Boolean) = if (tvalue) "" else "!"
+      
+      print("%s(" format maybenot(t1._2))
+      printRaw(t1._1)
+      print(") %s %s(".format(op, maybenot(t2._2)))
+      printRaw(t2._1)
+      print(")")
+    }
+
+    override def printRaw(tree: Tree): Unit = {
+      // routing supercalls through this for debugging ease
+      def s() = super.printRaw(tree)
+
+      tree match {
+        // labels used for jumps - does not map to valid scala code
+        case LabelDef(name, params, rhs) =>
+          print("labeldef %s(%s) = ".format(name, params mkString ","))
+          printRaw(rhs)
+          
+        case Ident(name) =>
+          print(decodedSymName(tree, name))
+                  
+        // target.method(arg) ==> target method arg
+        case Apply(Select(target, method), List(arg)) =>
+          if (method.decode.toString == "||")
+            printLogicalOr(target -> true, arg -> true)
+          else if (method.decode.toString == "&&")
+            printLogicalAnd(target -> true, arg -> true)
+          else (target, arg) match {
+            case (_: Ident, _: Literal | _: Ident)  => 
+              printRaw(target)
+              print(" ")
+              printRaw(Ident(method))
+              print(" ")
+              printRaw(arg)
+            case _                        => s()
+          }
+
+        // target.unary_! ==> !target
+        case Select(qualifier, name) if (name.decode startsWith "unary_") =>
+          print(name.decode drop 6)
+          printRaw(qualifier)
+
+        case Select(qualifier, name) =>
+          printRaw(qualifier)
+          print(".")
+          print(name.decode)
+
+        // target.toString() ==> target.toString
+        case Apply(fn, Nil)   => printRaw(fn)
+
+        // if a Block only continues one actual statement, just print it.
+        case Block(stats, expr) =>          
+          allStatements(tree) match {
+            case List(x)            => printRaw(x)
+            case xs                 => s()
+          }
+
+        // We get a lot of this stuff
+        case If( IsTrue(), x, _)        => printRaw(x)
+        case If(IsFalse(), _, x)        => printRaw(x)
+
+        case If(cond,  IsTrue(), elsep)   =>  printLogicalOr(cond -> true, elsep -> true)
+        case If(cond, IsFalse(), elsep)   => printLogicalAnd(cond -> false, elsep -> true)
+        case If(cond,  thenp, IsTrue())   =>  printLogicalOr(cond -> false, thenp -> true)
+        case If(cond,  thenp, IsFalse())  => printLogicalAnd(cond -> true, thenp -> true)
+
+        // If thenp or elsep has only one statement, it doesn't need more than one line.
+        case If(cond, thenp, elsep) =>
+          def ifIndented(x: Tree) = {
+            indent ; println() ; printRaw(x) ; undent
+          }
+        
+          val List(thenStmts, elseStmts) = List(thenp, elsep) map allStatements
+          print("if ("); print(cond); print(")")
+          
+          thenStmts match {
+            case List(x: If)  => ifIndented(x)
+            case List(x)      => printRaw(x)
+            case _            => printRaw(thenp)
+          }
+          
+          if (elseStmts.nonEmpty) {
+            print("else")
+            indent ; println() 
+            elseStmts match {
+              case List(x)  => printRaw(x)
+              case _        => printRaw(elsep)
+            }
+            undent ; println()
+          }
+        case _        => s()
+      }
+    }      
+  }
+  
+  /** This must guarantee not to force any evaluation, so we can learn
+   *  a little bit about trees in the midst of compilation without altering
+   *  the natural course of events.
+   */
+  class SafeTreePrinter(out: PrintWriter) extends TreePrinter(out) {
+    override def print(tree: Tree) {
+      printPosition(tree)
+      printRaw(tree)
+    }
+    private def default(t: Tree) = t.getClass.getName.reverse.takeWhile(_ != '.').reverse
+    private def params(trees: List[Tree]): String = trees map safe mkString ", "
+    
+    private def safe(name: Name): String = name.decode
+    private def safe(tree: Tree): String = tree match {
+      case Apply(fn, args)        => "%s(%s)".format(safe(fn), params(args))
+      case Select(qual, name)     => safe(qual) + "." + safe(name)
+      case This(qual)             => safe(qual) + ".this"
+      case Ident(name)            => safe(name)
+      case Literal(value)         => value.stringValue
+      case _                      => "(?: %s)".format(default(tree))
+    }
+    
+    override def printRaw(tree: Tree) { print(safe(tree)) }
+  }
+      
+  class TreeMatchTemplate {
+    // non-trees defined in Trees
+    //
+    // case class ImportSelector(name: Name, namePos: Int, rename: Name, renamePos: Int)
+    // case class Modifiers(flags: Long, privateWithin: Name, annotations: List[Tree], positions: Map[Long, Position])
+    //
+    def apply(t: Tree): Unit = t match {
+      // eliminated by typer
+      case Annotated(annot, arg)  =>
+      case AssignOrNamedArg(lhs, rhs) =>
+      case DocDef(comment, definition) =>
+      case Import(expr, selectors) =>
+      
+      // eliminated by refchecks
+      case ModuleDef(mods, name, impl) =>
+      case TypeTreeWithDeferredRefCheck() =>
+      
+      // eliminated by erasure
+      case TypeDef(mods, name, tparams, rhs) =>
+      case Typed(expr, tpt) =>
+      
+      // eliminated by cleanup
+      case ApplyDynamic(qual, args) =>
+      
+      // eliminated by explicitouter
+      case Alternative(trees) =>
+      case Bind(name, body) =>
+      case CaseDef(pat, guard, body) =>
+      case Star(elem) =>
+      case UnApply(fun, args) =>
+      
+      // eliminated by lambdalift
+      case Function(vparams, body) =>
+      
+      // eliminated by uncurry
+      case AppliedTypeTree(tpt, args) =>
+      case CompoundTypeTree(templ) =>
+      case ExistentialTypeTree(tpt, whereClauses) =>
+      case SelectFromTypeTree(qual, selector) =>
+      case SingletonTypeTree(ref) =>
+      case TypeBoundsTree(lo, hi) =>
+      
+      // survivors
+      case Apply(fun, args) =>
+      case ArrayValue(elemtpt, trees) =>
+      case Assign(lhs, rhs) =>
+      case Block(stats, expr) =>
+      case ClassDef(mods, name, tparams, impl) =>
+      case DefDef(mods, name, tparams, vparamss, tpt, rhs)  =>
+      case EmptyTree =>
+      case Ident(name) =>
+      case If(cond, thenp, elsep) =>
+      case LabelDef(name, params, rhs) =>
+      case Literal(value) =>
+      case Match(selector, cases) =>
+      case New(tpt) =>
+      case PackageDef(pid, stats) =>
+      case Return(expr) =>
+      case Select(qualifier, selector) =>
+      case Super(qual, mix) =>
+      case Template(parents, self, body) =>
+      case This(qual) =>
+      case Throw(expr) =>
+      case Try(block, catches, finalizer) =>
+      case TypeApply(fun, args) =>
+      case TypeTree() =>
+      case ValDef(mods, name, tpt, rhs) =>
+      
+      // missing from the Trees comment
+      case Parens(args) =>                          // only used during parsing
+      case SelectFromArray(qual, name, erasure) =>  // only used during erasure
+    }
+  }
+  
+  private def asStringInternal(t: Tree, f: PrintWriter => TreePrinter): String = {
+    val buffer = new StringWriter()
+    val printer = f(new PrintWriter(buffer))
+    printer.print(t)
+    printer.flush()
+    buffer.toString
+  }    
+  def asString(t: Tree): String = asStringInternal(t, newStandardTreePrinter)
+  def asCompactString(t: Tree): String = asStringInternal(t, newCompactTreePrinter)
+
+  def newStandardTreePrinter(writer: PrintWriter): TreePrinter = new TreePrinter(writer)
+  def newStandardTreePrinter(stream: OutputStream): TreePrinter = newStandardTreePrinter(new PrintWriter(stream))
+  def newStandardTreePrinter(): TreePrinter = newStandardTreePrinter(new PrintWriter(ConsoleWriter))
+  
+  def newCompactTreePrinter(writer: PrintWriter): CompactTreePrinter = new CompactTreePrinter(writer)
+  def newCompactTreePrinter(stream: OutputStream): CompactTreePrinter = newCompactTreePrinter(new PrintWriter(stream))
+  def newCompactTreePrinter(): CompactTreePrinter = newCompactTreePrinter(new PrintWriter(ConsoleWriter))
+  
+  def newTreePrinter(writer: PrintWriter): TreePrinter = 
+    if (settings.Ycompacttrees.value) newCompactTreePrinter(writer)
+    else newStandardTreePrinter(writer)
+  def newTreePrinter(stream: OutputStream): TreePrinter = newTreePrinter(new PrintWriter(stream))
+  def newTreePrinter(): TreePrinter = newTreePrinter(new PrintWriter(ConsoleWriter))
+
+  /** A writer that writes to the current Console and
+   * is sensitive to replacement of the Console's
+   * output stream.
+   */
+  object ConsoleWriter extends Writer {
+    override def write(str: String) { Console.print(str) }
+    
+    def write(cbuf: Array[Char], off: Int, len: Int) {
+      val str = new String(cbuf, off, len)
+      write(str)
     }
-    create(new PrintWriter(ConsoleWriter))
+    
+    def close = { /* do nothing */ }
+    def flush = { /* do nothing */ }
   }
 }
diff --git a/src/compiler/scala/tools/nsc/ast/Trees.scala b/src/compiler/scala/tools/nsc/ast/Trees.scala
index be4a36d..4e67991 100644
--- a/src/compiler/scala/tools/nsc/ast/Trees.scala
+++ b/src/compiler/scala/tools/nsc/ast/Trees.scala
@@ -1,25 +1,17 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: Trees.scala 16881 2009-01-09 16:28:11Z cunei $
 
-package scala.tools.nsc.ast
-
-import java.io.{PrintWriter, StringWriter}
+package scala.tools.nsc
+package ast
 
 import scala.collection.mutable.ListBuffer
-import scala.tools.nsc.symtab.{Flags, SymbolTable}
+import scala.tools.nsc.symtab.SymbolTable
 import scala.tools.nsc.symtab.Flags._
-import scala.tools.nsc.util.{FreshNameCreator, HashSet, Position, NoPosition, SourceFile}
-
-
-trait Trees { 
-  self: SymbolTable =>
+import scala.tools.nsc.util.{FreshNameCreator, HashSet, SourceFile}
 
-  //statistics
-
-  var nodeCount = 0
+trait Trees extends reflect.generic.Trees { self: SymbolTable =>
 
   trait CompilationUnitTrait {
     var body: Tree
@@ -31,115 +23,47 @@ trait Trees {
 
   // sub-components --------------------------------------------------
 
-  object treePrinters extends {
-    val trees: Trees.this.type = Trees.this
-  } with TreePrinters
-
-  lazy val treePrinter = treePrinters.create()
+  lazy val treePrinter = newTreePrinter()
 
   object treeInfo extends {
     val trees: Trees.this.type = Trees.this
   } with TreeInfo
 
-  val copy = new LazyTreeCopier()
-
-  // modifiers --------------------------------------------------------
-
-  /** @param privateWithin   the qualifier for a private (a type name)
-   *                         or nme.EMPTY.toTypeName, if none is given.
-   *  @param annotations     the annotations for the definition 
-   *                         (i.e things starting with @)  
-   */  
-  case class Modifiers(flags: Long, privateWithin: Name, annotations: List[Annotation]) {
-    def isCovariant     = hasFlag(COVARIANT    )  // marked with `+'
-    def isContravariant = hasFlag(CONTRAVARIANT)  // marked with `-'
-    def isPrivate   = hasFlag(PRIVATE  )
-    def isProtected = hasFlag(PROTECTED)
-    def isVariable  = hasFlag(MUTABLE  )
-    def isArgument  = hasFlag(PARAM    )
-    def isAccessor  = hasFlag(ACCESSOR )
-    def isOverride  = hasFlag(OVERRIDE )
-    def isAbstract  = hasFlag(ABSTRACT )
-    def isDeferred  = hasFlag(DEFERRED )
-    def isCase      = hasFlag(CASE     )
-    def isSealed    = hasFlag(SEALED   )
-    def isFinal     = hasFlag(FINAL    )
-    def isTrait     = hasFlag(TRAIT | notDEFERRED) // (part of DEVIRTUALIZE)
-    def isImplicit  = hasFlag(IMPLICIT )
-    def isPublic    = !isPrivate && !isProtected
-    def hasFlag(flag: Long) = (flag & flags) != 0
-    def & (flag: Long): Modifiers = {
-      val flags1 = flags & flag
-      if (flags1 == flags) this
-      else Modifiers(flags1, privateWithin, annotations)
-    }
-    def &~ (flag: Long): Modifiers = {
-      val flags1 = flags & (~flag)
-      if (flags1 == flags) this
-      else Modifiers(flags1, privateWithin, annotations)
-    }
-    def | (flag: Long): Modifiers = {
-      val flags1 = flags | flag
-      if (flags1 == flags) this
-      else Modifiers(flags1, privateWithin, annotations)
-    }
-    def withAnnotations(annots: List[Annotation]) = 
-      if (annots.isEmpty) this
-      else Modifiers(flags, privateWithin, annotations ::: annots)
-  }
-
-  def Modifiers(flags: Long, privateWithin: Name): Modifiers = Modifiers(flags, privateWithin, List())
-  def Modifiers(flags: Long): Modifiers = Modifiers(flags, nme.EMPTY.toTypeName)
+  val treeCopy = new LazyTreeCopier()
 
-  val NoMods = Modifiers(0)
+  implicit def treeWrapper(tree: Tree): TreeOps = new TreeOps(tree)
 
-  // @M helper method for asserts that check consistency in kinding
-  //def kindingIrrelevant(tp: Type) = (tp eq null) || phase.name == "erasure" || phase.erasedTypes 
-  
-  abstract class Tree {
-    {
-      import util.Statistics
-      if (Statistics.enabled) nodeCount += 1
-    }
+  class TreeOps(tree: Tree) {
 
-    private var rawpos: Position = NoPosition
-
-    def pos = rawpos
-
-    private[this] var rawtpe: Type = _
-
-    def tpe = rawtpe
-    def tpe_=(t: Type) = rawtpe = t
-
-    def setPos(pos: Position): this.type = { rawpos = pos; this }
-    def setType(tp: Type): this.type = { 
-      /*assert(kindingIrrelevant(tp) || !kindStar || !tp.isHigherKinded, 
-               tp+" should not be higher-kinded");*/ 
-      tpe = tp
-      this 
+    def isTerm: Boolean = tree match {
+      case _: TermTree => true
+      case Bind(name, _) => name.isTermName
+      case Select(_, name) => name.isTermName
+      case Ident(name) => name.isTermName
+      case Annotated(_, arg) => arg.isTerm
+      case DocDef(_, defn) => defn.isTerm
+      case _ => false
     }
 
-    def symbol: Symbol = null
-    def symbol_=(sym: Symbol) {
-      throw new Error("symbol_= inapplicable for " + this)
+    def isType: Boolean = tree match {
+      case _: TypTree => true
+      case Bind(name, _) => name.isTypeName
+      case Select(_, name) => name.isTypeName
+      case Ident(name) => name.isTypeName
+      case Annotated(_, arg) => arg.isType
+      case DocDef(_, defn) => defn.isType
+      case _ => false
     }
-    def setSymbol(sym: Symbol): this.type = { symbol = sym; this }
-
-    def hasSymbol = false
-    def isDef = false
-    def isTerm = false
-    def isType = false
-    def isEmpty = false
 
-    def isErroneous = (tpe ne null) && tpe.isErroneous
+    def isErroneous = (tree.tpe ne null) && tree.tpe.isErroneous
 
     /** Apply `f' to each subtree */
-    def foreach(f: Tree => Unit) { new ForeachTreeTraverser(f).traverse(this) }
+    def foreach(f: Tree => Unit) { new ForeachTreeTraverser(f).traverse(tree) }
 
     /** Find all subtrees matching predicate `p' */
     def filter(f: Tree => Boolean): List[Tree] = {
       val ft = new FilterTreeTraverser(f)
-      ft.traverse(this)
+      ft.traverse(tree)
       ft.hits.toList
     }
 
@@ -148,195 +72,44 @@ trait Trees {
      */
     def find(p: Tree => Boolean): Option[Tree] = {
       val ft = new FindTreeTraverser(p)
-      ft.traverse(this)
+      ft.traverse(tree)
       ft.result
     }
 
     /** Is there part of this tree which satisfies predicate `p'? */
     def exists(p: Tree => Boolean): Boolean = !find(p).isEmpty
 
-    override def toString(): String = {
-      val buffer = new StringWriter()
-      val printer = treePrinters.create(new PrintWriter(buffer))
-      printer.print(this)
-      printer.flush()
-      buffer.toString
-    }
-
-    override def hashCode(): Int = super.hashCode()
-
-    override def equals(that: Any): Boolean = that match {
-      case t: Tree => this eq t
-      case _ => false
-    }
-    def hashCodeStructure: Int = {
-      var hc = getClass.hashCode
-      def f(what : Any) : Unit = what match {
-      case what : Tree => hc += what.hashCodeStructure
-      case what : Iterable[_] => what.foreach(f)
-      case what : Product => g(what)
-      case null => 
-      case what => hc += what.hashCode
-      }
-      def g(what: Product) {
-        hc += what.productArity
-        var i = 0
-        while (i < what.productArity) {
-          f(what.productElement(i))
-          i += 1
+    def equalsStructure(that : Tree) = equalsStructure0(that)(_ eq _)
+    def equalsStructure0(that: Tree)(f: (Tree,Tree) => Boolean): Boolean =
+      (tree == that) || ((tree.getClass == that.getClass) && {    // XXX defining any kind of equality in terms of getClass is a mistake
+        assert(tree.productArity == that.productArity)
+        def equals0(this0: Any, that0: Any): Boolean = (this0, that0) match {
+          case (x: Tree, y: Tree)         => f(x, y) || (x equalsStructure0 y)(f)
+          case (xs: List[_], ys: List[_]) => (xs corresponds ys)(equals0)
+          case _                          => this0 == that0
         }
-      }
-      this match {
-        case p : Product => g(p)
-        case _ => 
-      }
-      hc
-    }
-    def equalsStructure(that : Tree) = equalsStructure0(that){case (t0,t1) => false}
-    def equalsStructure0(that: Tree)(f : (Tree,Tree) => Boolean): Boolean = {
-      if (this == that) return true
-      if (this.getClass != that.getClass) return false
-      val this0 = this.asInstanceOf[Product]
-      val that0 = that.asInstanceOf[Product]
-      assert(this0.productArity == that0.productArity)
-      def equals0(thiz: Any, that: Any): Boolean = thiz match {
-        case thiz: Tree => 
-          f(thiz,that.asInstanceOf[Tree]) || thiz.equalsStructure0(that.asInstanceOf[Tree])(f)
-        case thiz: List[_] =>
-          val that0 = that.asInstanceOf[List[Any]]
-          if (thiz.length != that0.length) false
-          else {
-            val results0 = for (i <- 0.until(thiz.length).toList) 
-              yield equals0(thiz(i), that0(i))
-            results0.foldLeft(true)((x,y) => x && y)
-          }
-        case thiz =>
-          thiz == that
-      }
-      val results = for (i <- 0.until(this0.productArity).toList) yield 
-        equals0(this0.productElement(i), that0.productElement(i))
-      val b = results.foldLeft(true)((x,y) => x && y)
-      if (b) (this,that) match {
-      case (this0 : TypeTree,that0 : TypeTree) if this0.original != null && that0.original != null =>  
-        this0.original.equalsStructure0(that0.original)(f)
-      case _ => true 
-      } else false
-    }
-
-    def duplicate: this.type =
-      (duplicator transform this).asInstanceOf[this.type]
-
-    def shallowDuplicate: this.type =
-      ((new ShallowDuplicator(this)) transform this).asInstanceOf[this.type]
-
-    def copyAttrs(tree: Tree): this.type = {
-      rawpos = tree.rawpos
-      tpe = tree.tpe
-      if (hasSymbol) symbol = tree.symbol
-      this
-    }
-  }
-
-  trait SymTree extends Tree {
-    override def hasSymbol = true
-    override var symbol: Symbol = NoSymbol
-  }
-
-  abstract class DefTree extends SymTree {
-    def name: Name
-    override def isDef = true
-  }
-
-  trait TermTree extends Tree {
-    override def isTerm = true
-  }
-
-  /** A tree for a type.  Note that not all type trees implement
-    * this trait; in particular, Ident's are an exception. */
-  trait TypTree extends Tree {
-    override def isType = true
-  }
-
-// ----- auxiliary objects and methods ------------------------------
-
-  private lazy val duplicator = new Transformer {
-    override val copy = new StrictTreeCopier
-  }
-
-  private class ShallowDuplicator(orig: Tree) extends Transformer {
-    override val copy = new StrictTreeCopier
-    override def transform(tree: Tree) =
-      if (tree eq orig)
-	super.transform(tree)
-      else
-	tree
-  }
-
-  private def syntheticParams(owner: Symbol, mtp: Type): List[List[Symbol]] = {
-    var cnt = 0
-    def freshName() = { cnt += 1; newTermName("x$" + cnt) }
-    def synthetics(mtp: Type): List[List[Symbol]] = mtp match {
-      case PolyType(_, restp) =>
-        synthetics(restp)
-      case MethodType(formals, restp) =>
-        (formals map (f => owner.newValueParameter(owner.pos, freshName()).setInfo(f))) ::
-          synthetics(restp)
-      case _ =>
-        List()
-    }
-    synthetics(mtp)
-  }
-
-//  def nextPhase = if (phase.id > globalPhase.id) phase else phase.next;
-
-// ----- tree node alternatives --------------------------------------
-
-  /** The empty tree */
-  case object EmptyTree extends TermTree {
-    super.tpe_=(NoType)
-    override def tpe_=(t: Type) = 
-      if (t != NoType) throw new Error("tpe_=("+t+") inapplicable for <empty>")
-    override def isEmpty = true
-  }
+        def compareOriginals() = (this, that) match {
+          case (x: TypeTree, y: TypeTree) if x.original != null && y.original != null =>
+            (x.original equalsStructure0 y.original)(f)
+          case _                          =>
+            true
+        }
+        
+        (tree.productIterator.toList corresponds that.productIterator.toList)(equals0) && compareOriginals()
+      })
 
-  abstract class MemberDef extends DefTree {
-    def mods: Modifiers
-    def keyword: String = this match {
-      case TypeDef(_, _, _, _)      => "type"
-      case ClassDef(_, _, _, _)     => "class"
-      case DefDef(_, _, _, _, _, _) => "def"
-      case ModuleDef(_, _, _)       => "object"
-      case PackageDef(_, _)         => "package"
-      case ValDef(mods, _, _, _)    => if (mods.isVariable) "var" else "val"
-      case _ => ""
-    }
-    final def hasFlag(mask: Long): Boolean = (mods.flags & mask) != 0
+    def shallowDuplicate: Tree = new ShallowDuplicator(tree) transform tree
   }
 
-  /** Package clause */
-  case class PackageDef(name: Name, stats: List[Tree])
-       extends MemberDef {
-    def mods = NoMods
-  }
+  private[scala] override def duplicateTree(tree: Tree): Tree = duplicator transform tree
 
-  def PackageDef(sym: Symbol, stats: List[Tree]): PackageDef =
-    PackageDef(sym.name, stats) setSymbol sym
+// ---- values and creators ---------------------------------------
 
-  abstract class ImplDef extends MemberDef {
-    def impl: Template
-  }
-
-  /** Class definition */
-  case class ClassDef(mods: Modifiers, name: Name, tparams: List[TypeDef], impl: Template)
-       extends ImplDef
-
-  /**
-   *  @param sym       the class symbol
-   *  @param impl      ...
-   *  @return          ...
+  /** @param sym       the class symbol
+   *  @return          the implementation template
    */
   def ClassDef(sym: Symbol, impl: Template): ClassDef =
-    posAssigner.atPos(sym.pos) {
+    atPos(sym.pos) {
       ClassDef(Modifiers(sym.flags),
                sym.name,
                sym.typeParams map TypeDef,
@@ -353,114 +126,64 @@ trait Trees {
    *  @param argss      the supercall arguments
    *  @param body       the template statements without primary constructor
    *                    and value parameter fields.
-   *  @return          ...
    */
-  def ClassDef(sym: Symbol, constrMods: Modifiers, vparamss: List[List[ValDef]], argss: List[List[Tree]], body: List[Tree]): ClassDef =
+  def ClassDef(sym: Symbol, constrMods: Modifiers, vparamss: List[List[ValDef]], argss: List[List[Tree]], body: List[Tree], superPos: Position): ClassDef =
     ClassDef(sym, 
       Template(sym.info.parents map TypeTree, 
                if (sym.thisSym == sym || phase.erasedTypes) emptyValDef else ValDef(sym.thisSym),
-               constrMods, vparamss, argss, body))
-
-  /** Singleton object definition
-   *
-   *  @param mods
-   *  @param name
-   *  @param impl
-   */
-  case class ModuleDef(mods: Modifiers, name: Name, impl: Template)
-       extends ImplDef
+               constrMods, vparamss, argss, body, superPos))
 
   /**
    *  @param sym       the class symbol
-   *  @param impl      ...
-   *  @return          ...
+   *  @param impl      the implementation template
    */
   def ModuleDef(sym: Symbol, impl: Template): ModuleDef =
-    posAssigner.atPos(sym.pos) {
+    atPos(sym.pos) {
       ModuleDef(Modifiers(sym.flags), sym.name, impl) setSymbol sym
     }
 
-  abstract class ValOrDefDef extends MemberDef {
-    def tpt: Tree
-    def rhs: Tree
-  }
-
-  /** Value definition
-   *
-   *  @param mods
-   *  @param name
-   *  @param tpt
-   *  @param rhs
-   */
-  case class ValDef(mods: Modifiers, name: Name, tpt: Tree, rhs: Tree)
-       extends ValOrDefDef {
-    assert(tpt.isType, tpt)
-    //assert(kindingIrrelevant(tpt.tpe) || !tpt.tpe.isHigherKinded, tpt.tpe) //@M a value definition should never be typed with a higher-kinded type (values must be classified by types with kind *)
-    //tpt.kindStar=true //@M turn on consistency checking in Tree
-    assert(rhs.isTerm, rhs)
-  }
-
   def ValDef(sym: Symbol, rhs: Tree): ValDef =
-    posAssigner.atPos(sym.pos) {
-      ValDef(Modifiers(sym.flags), sym.name, TypeTree(sym.tpe), rhs) setSymbol sym
+    atPos(sym.pos) {
+      ValDef(Modifiers(sym.flags), sym.name, 
+             TypeTree(sym.tpe) setPos sym.pos.focus, 
+             rhs) setSymbol sym
     }
 
   def ValDef(sym: Symbol): ValDef = ValDef(sym, EmptyTree)
 
-  object emptyValDef 
-  extends ValDef(Modifiers(PRIVATE), nme.WILDCARD, TypeTree(NoType), EmptyTree) {
+  object emptyValDef extends ValDef(Modifiers(PRIVATE), nme.WILDCARD, TypeTree(NoType), EmptyTree) {
     override def isEmpty = true
-  }
-
-  /** Method definition
-   *
-   *  @param mods
-   *  @param name
-   *  @param tparams
-   *  @param vparamss
-   *  @param tpt
-   *  @param rhs
-   */
-  case class DefDef(mods: Modifiers, name: Name, tparams: List[TypeDef],
-                    vparamss: List[List[ValDef]], tpt: Tree, rhs: Tree)
-       extends ValOrDefDef {
-    assert(tpt.isType, tpt)
-    //assert(kindingIrrelevant(tpt.tpe) || !tpt.tpe.isHigherKinded, tpt.tpe) //@M a method definition should never be typed with a higher-kinded type (values must be classified by types with kind *)
-    //tpt.kindStar=true //@M turn on consistency checking in Tree
-    assert(rhs.isTerm, rhs)
+    super.setPos(NoPosition)
+    override def setPos(pos: Position) = { assert(false); this }
   }
 
   def DefDef(sym: Symbol, mods: Modifiers, vparamss: List[List[ValDef]], rhs: Tree): DefDef =
-    posAssigner.atPos(sym.pos) {
+    atPos(sym.pos) {
       assert(sym != NoSymbol)
       DefDef(Modifiers(sym.flags),
              sym.name,
              sym.typeParams map TypeDef,
              vparamss,
-             TypeTree(sym.tpe.finalResultType),
+             TypeTree(sym.tpe.finalResultType) setPos sym.pos.focus,
              rhs) setSymbol sym
     }
 
   def DefDef(sym: Symbol, vparamss: List[List[ValDef]], rhs: Tree): DefDef =
     DefDef(sym, Modifiers(sym.flags), vparamss, rhs)
+  
+  def DefDef(sym: Symbol, mods: Modifiers, rhs: Tree): DefDef =
+    DefDef(sym, mods, sym.paramss map (_.map(ValDef)), rhs)
 
-  def DefDef(sym: Symbol, mods: Modifiers, rhs: List[List[Symbol]] => Tree): DefDef = {
-    val vparamss = syntheticParams(sym, sym.tpe)
-    DefDef(sym, mods, vparamss map (_.map(ValDef)), rhs(vparamss))
-  }
-
-  def DefDef(sym: Symbol, rhs: List[List[Symbol]] => Tree): DefDef = 
+  def DefDef(sym: Symbol, rhs: Tree): DefDef =
     DefDef(sym, Modifiers(sym.flags), rhs)
 
-  /** Abstract type, type parameter, or type alias */
-  case class TypeDef(mods: Modifiers, name: Name, tparams: List[TypeDef], rhs: Tree) 
-       extends MemberDef {
-    def namePos = pos.offset.map(n => n - name.length).getOrElse(-1)
+  def DefDef(sym: Symbol, rhs: List[List[Symbol]] => Tree): DefDef = {
+    DefDef(sym, rhs(sym.info.paramss))
   }
 
   /** A TypeDef node which defines given `sym' with given tight hand side `rhs'. */
   def TypeDef(sym: Symbol, rhs: Tree): TypeDef =
-    posAssigner.atPos(sym.pos) {
+    atPos(sym.pos) {
       TypeDef(Modifiers(sym.flags), sym.name, sym.typeParams map TypeDef, rhs) setSymbol sym
     }
 
@@ -468,84 +191,11 @@ trait Trees {
   def TypeDef(sym: Symbol): TypeDef = 
     TypeDef(sym, TypeBoundsTree(TypeTree(sym.info.bounds.lo), TypeTree(sym.info.bounds.hi)))
 
-  /** <p>
-   *    Labelled expression - the symbols in the array (must be Idents!) 
-   *    are those the label takes as argument 
-   *  </p>
-   *  <p>
-   *    The symbol that is given to the labeldef should have a MethodType
-   *    (as if it were a nested function)
-   *  </p>
-   *  <p>
-   *    Jumps are apply nodes attributed with label symbol, the arguments
-   *    will get assigned to the idents.
-   *  </p>
-   *  <p>
-   *  Note: on 2005-06-09 Martin, Iuli, Burak agreed to have forward
-   *        jumps within a Block.
-   *  </p>
-   */
-  case class LabelDef(name: Name, params: List[Ident], rhs: Tree)
-       extends DefTree with TermTree {
-    assert(rhs.isTerm)
-  }
-
-  /**
-   *  @param sym    the class symbol
-   *  @param params ...
-   *  @param rhs    ...
-   *  @return       ...
-   */
   def LabelDef(sym: Symbol, params: List[Symbol], rhs: Tree): LabelDef =
-    posAssigner.atPos(sym.pos) {
+    atPos(sym.pos) {
       LabelDef(sym.name, params map Ident, rhs) setSymbol sym
     }
 
-  /** Import clause
-   *
-   *  @param expr
-   *  @param selectors
-   */
-  case class Import(expr: Tree, selectors: List[(Name, Name)])
-       extends SymTree 
-    // The symbol of an Import is an import symbol @see Symbol.newImport
-    // It's used primarily as a marker to check that the import has been typechecked.
-
-  /** Annotation application (constructor arguments + name-value pairs) */
-  case class Annotation(constr: Tree, elements: List[Tree])
-       extends TermTree
-
-  /** Documented definition, eliminated by analyzer */
-  case class DocDef(comment: String, definition: Tree)
-       extends Tree {
-    override def symbol: Symbol = definition.symbol
-    override def symbol_=(sym: Symbol) { definition.symbol = sym }
-    // sean: seems to be important to the IDE
-    override def isDef = definition.isDef
-    override def isTerm = definition.isTerm
-    override def isType = definition.isType
-  }
-
-  /** Instantiation template of a class or trait
-   *
-   *  @param parents
-   *  @param body
-   */
-  case class Template(parents: List[Tree], self: ValDef, body: List[Tree])
-       extends SymTree {
-    // the symbol of a template is a local dummy. @see Symbol.newLocalDummy
-    // the owner of the local dummy is the enclosing trait or class.
-    // the local dummy is itself the owner of any local blocks
-    // For example:
-    //
-    // class C { 
-    //   def foo // owner is C 
-    //   { 
-    //      def bar  // owner is local dummy
-    //   }
-    // System.err.println("TEMPLATE: " + parents)
-  }
-
   /** Generates a template with constructor corresponding to 
    *
    *  constrmods (vparams1_) ... (vparams_n) preSuper { presupers }
@@ -563,434 +213,155 @@ trait Trees {
    *    body
    *  }
    */
-  def Template(parents: List[Tree], self: ValDef, constrMods: Modifiers, vparamss: List[List[ValDef]], argss: List[List[Tree]], body: List[Tree]): Template = {
+  def Template(parents: List[Tree], self: ValDef, constrMods: Modifiers, vparamss: List[List[ValDef]], argss: List[List[Tree]], body: List[Tree], superPos: Position): Template = {
     /* Add constructor to template */
     
-    // create parameters for <init>
+    // create parameters for <init> as synthetic trees.
     var vparamss1 = 
       vparamss map (vps => vps.map { vd =>
-        val ret = ValDef(
-          Modifiers(vd.mods.flags & IMPLICIT | PARAM) withAnnotations vd.mods.annotations,
-          vd.name, vd.tpt.duplicate, EmptyTree).setPos(vd.pos)
-        if (inIDE && vd.symbol != NoSymbol) 
-          ret.symbol = vd.symbol
-        ret
-       })
-    val (vdefs, rest) = body span treeInfo.isPreSuper
-    val (lvdefs, gvdefs) = List.unzip {
-      vdefs map {
-        case vdef @ ValDef(mods, name, tpt, rhs) =>
-          (copy.ValDef(vdef, Modifiers(PRESUPER), name, tpt, rhs),
-           copy.ValDef(vdef, mods, name, TypeTree(), EmptyTree))
-      }
-    }
-    val constrs = 
+        atPos(vd.pos.focus) {
+          ValDef(
+            Modifiers(vd.mods.flags & (IMPLICIT | DEFAULTPARAM | BYNAMEPARAM) | PARAM | PARAMACCESSOR) withAnnotations vd.mods.annotations,
+            vd.name, vd.tpt.duplicate, vd.rhs.duplicate)
+        }})
+    val (edefs, rest) = body span treeInfo.isEarlyDef
+    val (evdefs, etdefs) = edefs partition treeInfo.isEarlyValDef
+    val (lvdefs, gvdefs) = evdefs map {
+      case vdef @ ValDef(mods, name, tpt, rhs) =>
+        val fld = treeCopy.ValDef(
+          vdef.duplicate, mods, name, 
+          atPos(vdef.pos.focus) { TypeTree() setOriginal tpt setPos tpt.pos.focus }, // atPos in case 
+          EmptyTree)
+        val local = treeCopy.ValDef(vdef, Modifiers(PRESUPER), name, tpt, rhs)
+        (local, fld)
+    } unzip
+
+    val constrs = {
       if (constrMods.isTrait) {
         if (body forall treeInfo.isInterfaceMember) List()
         else List(
-          DefDef(NoMods, nme.MIXIN_CONSTRUCTOR, List(), List(List()), TypeTree(), Block(lvdefs, Literal(()))))
+          atPos(wrappingPos(superPos, lvdefs)) (
+            DefDef(NoMods, nme.MIXIN_CONSTRUCTOR, List(), List(List()), TypeTree(), Block(lvdefs, Literal(())))))
       } else {
         // convert (implicit ... ) to ()(implicit ... ) if its the only parameter section
         if (vparamss1.isEmpty ||
-            !vparamss1.head.isEmpty && (vparamss1.head.head.mods.flags & IMPLICIT) != 0) 
+            !vparamss1.head.isEmpty && (vparamss1.head.head.mods.flags & IMPLICIT) != 0L) 
           vparamss1 = List() :: vparamss1;
-        val superRef: Tree = Select(Super(nme.EMPTY.toTypeName, nme.EMPTY.toTypeName), nme.CONSTRUCTOR)
-        val superCall = posAssigner.atPos(parents.head.pos) { (superRef /: argss) (Apply) }
+        val superRef: Tree = atPos(superPos) {
+          Select(Super(nme.EMPTY.toTypeName, nme.EMPTY.toTypeName), nme.CONSTRUCTOR)
+        }
+        val superCall = (superRef /: argss) (Apply)
         List(
-          DefDef(constrMods, nme.CONSTRUCTOR, List(), vparamss1, TypeTree(), Block(lvdefs ::: List(superCall), Literal(()))))
+          atPos(wrappingPos(superPos, lvdefs ::: argss.flatten)) (
+            DefDef(constrMods, nme.CONSTRUCTOR, List(), vparamss1, TypeTree(), Block(lvdefs ::: List(superCall), Literal(())))))
       }
-    Template(parents, self, gvdefs ::: List.flatten(vparamss) ::: constrs ::: rest)
+    } 
+    // println("typed template, gvdefs = "+gvdefs+", parents = "+parents+", constrs = "+constrs)
+    constrs foreach (ensureNonOverlapping(_, parents ::: gvdefs))
+    // vparamss2 are used as field definitions for the class. remove defaults
+    val vparamss2 = vparamss map (vps => vps map { vd => 
+      treeCopy.ValDef(vd, vd.mods &~ DEFAULTPARAM, vd.name, vd.tpt, EmptyTree)
+    })
+    Template(parents, self, gvdefs ::: vparamss2.flatten ::: constrs ::: etdefs ::: rest)
   }
 
-  /** Block of expressions (semicolon separated expressions) */
-  case class Block(stats: List[Tree], expr: Tree)
-       extends TermTree
-
-  /** Case clause in a pattern match, eliminated by TransMatch 
-   *  (except for occurences in switch statements)
-   */
-  case class CaseDef(pat: Tree, guard: Tree, body: Tree)
-       extends Tree
-
   /** casedef shorthand */
   def CaseDef(pat: Tree, body: Tree): CaseDef = CaseDef(pat, EmptyTree, body)
-
-  /** Sequence of patterns (comma separated expressions), eliminated by the
-   *  <code>TransMatch</code> phase.
-   */
-  case class Sequence(trees: List[Tree])
-       extends TermTree
-
-  /** Alternatives of patterns, eliminated by TransMatch, except for
-   *  occurences in encoded Switch stmt (=remaining Match(CaseDef(...))
-   */
-  case class Alternative(trees: List[Tree])
-       extends TermTree
-
-  /** Repetition of pattern, eliminated by TransMatch */
-  case class Star(elem: Tree)
-       extends TermTree
-
-  /** Bind of a variable to a rhs pattern, eliminated by TransMatch
-   *
-   *  @param name
-   *  @param body
-   */
-  case class Bind(name: Name, body: Tree)
-       extends DefTree {
-    override def isTerm = name.isTermName
-    override def isType = name.isTypeName
-  }
-
+  
   def Bind(sym: Symbol, body: Tree): Bind =
     Bind(sym.name, body) setSymbol sym
 
-  case class UnApply(fun: Tree, args: List[Tree]) 
-       extends TermTree
 
-  /** Array of expressions, needs to be translated in backend,
-   */
-  case class ArrayValue(elemtpt: Tree, elems: List[Tree])
-       extends TermTree
-
-  /** Anonymous function, eliminated by analyzer */
-  case class Function(vparams: List[ValDef], body: Tree)
-       extends TermTree with SymTree 
-    // The symbol of a Function is a synthetic value of name nme.ANON_FUN_NAME
-    // It is the owner of the function's parameters.
-
-  /** Assignment */
-  case class Assign(lhs: Tree, rhs: Tree)
-       extends TermTree
-
-  /** Conditional expression */
-  case class If(cond: Tree, thenp: Tree, elsep: Tree)
-       extends TermTree
-
-  /** <p>
-   *    Pattern matching expression  (before <code>TransMatch</code>)
-   *    Switch statements            (after TransMatch)
-   *  </p>
-   *  <p>
-   *    After <code>TransMatch</code>, cases will satisfy the following
-   *    constraints:
-   *  </p>
-   *  <ul>
-   *    <li>all guards are EmptyTree,</li>
-   *    <li>all patterns will be either <code>Literal(Constant(x:Int))</code>
-   *      or <code>Alternative(lit|...|lit)</code></li>
-   *    <li>except for an "otherwise" branch, which has pattern
-   *      <code>Ident(nme.WILDCARD)</code></li>
-   *  </ul>
-   */
-  case class Match(selector: Tree, cases: List[CaseDef])
-       extends TermTree
-
-  /** Return expression */
-  case class Return(expr: Tree)
-       extends TermTree with SymTree
-    // The symbol of a Return node is the enclosing method.
-
-  case class Try(block: Tree, catches: List[CaseDef], finalizer: Tree)
-       extends TermTree
-
-  /** Throw expression */
-  case class Throw(expr: Tree)
-       extends TermTree
-
-  /** Object instantiation
-   *  One should always use factory method below to build a user level new.
-   *
-   *  @param tpt    a class type
-   */
-  case class New(tpt: Tree)
-       extends TermTree {
-    assert(tpt.isType)
-  }
-
-  /** Factory method for object creation <code><new tpt(args_1)...(args_n)></code>.
-   *  A New(t, as) is expanded to:
-   *    (new t).<init>(as)
-   *
-   *  @param tpt   ...
-   *  @param argss ...
-   *  @return      ...
+  /** Factory method for object creation `new tpt(args_1)...(args_n)`
+   *  A `New(t, as)` is expanded to: `(new t).<init>(as)`
    */
   def New(tpt: Tree, argss: List[List[Tree]]): Tree = {
     assert(!argss.isEmpty)
     val superRef: Tree = Select(New(tpt), nme.CONSTRUCTOR)
     (superRef /: argss) (Apply)
   }
-
-  /** Type annotation, eliminated by explicit outer */
-  case class Typed(expr: Tree, tpt: Tree)
-       extends TermTree
-
-  // Martin to Sean: Should GenericApply/TypeApply/Apply not be SymTree's? After all, 
-  // ApplyDynamic is a SymTree.
-  abstract class GenericApply extends TermTree {
-    val fun: Tree
-    val args: List[Tree]
-  }
-
-  /** Type application */
-  case class TypeApply(fun: Tree, args: List[Tree])
-       extends GenericApply {
-    override def symbol: Symbol = fun.symbol
-    override def symbol_=(sym: Symbol) { fun.symbol = sym }
-  }
-
-  /** Value application */
-  case class Apply(fun: Tree, args: List[Tree])
-       extends GenericApply {
-    override def symbol: Symbol = fun.symbol
-    override def symbol_=(sym: Symbol) { fun.symbol = sym }
-  }
-
-  /** Dynamic value application. 
-   *  In a dynamic application   q.f(as)
-   *   - q is stored in qual
-   *   - as is stored in args
-   *   - f is stored as the node's symbol field.
-   */
-  case class ApplyDynamic(qual: Tree, args: List[Tree]) 
-       extends TermTree with SymTree
-    // The symbol of an ApplyDynamic is the function symbol of `qual', or NoSymbol, if there is none.
-
-  /** Super reference */
-  case class Super(qual: Name, mix: Name)
-       extends TermTree with SymTree
-    // The symbol of a Super is the class _from_ which the super reference is made.
-    // For instance in C.super(...), it would be C.
-
+  
   def Super(sym: Symbol, mix: Name): Tree = Super(sym.name, mix) setSymbol sym
 
-  /** Self reference */
-  case class This(qual: Name)
-        extends TermTree with SymTree
-    // The symbol of a This is the class to which the this refers.
-    // For instance in C.this, it would be C.
-
   def This(sym: Symbol): Tree = This(sym.name) setSymbol sym
 
-  /** Designator <qualifier> . <selector> */
-  case class Select(qualifier: Tree, selector: Name)
-       extends SymTree {
-    override def isTerm = selector.isTermName
-    override def isType = selector.isTypeName
-  }
-
   def Select(qualifier: Tree, sym: Symbol): Select =
     Select(qualifier, sym.name) setSymbol sym
 
-  /** Identifier <name> */
-  case class Ident(name: Name)
-       extends SymTree {
-    override def isTerm = name.isTermName
-    override def isType = name.isTypeName
-  }
-
-  class BackQuotedIdent(name: Name) extends Ident(name)
-
   def Ident(sym: Symbol): Ident =
     Ident(sym.name) setSymbol sym
 
-  /** Literal */
-  case class Literal(value: Constant)
-        extends TermTree {
-    assert(value ne null)
+  /** Block factory that flattens directly nested blocks. 
+   */
+  def Block(stats: Tree*): Block = stats match {
+    case Seq(b @ Block(_, _)) => b
+    case Seq(stat) => Block(stats.toList, Literal(Constant(())))
+    case Seq(_, rest @ _*) => Block(stats.init.toList, stats.last)
   }
 
-  def Literal(value: Any): Literal =
-    Literal(Constant(value))
-
   /** A synthetic term holding an arbitrary type.  Not to be confused with
     * with TypTree, the trait for trees that are only used for type trees.
     * TypeTree's are inserted in several places, but most notably in
     * <code>RefCheck</code>, where the arbitrary type trees are all replaced by
     * TypeTree's. */
-  case class TypeTree() extends TypTree {
-    var original: Tree = _
+  case class TypeTree() extends AbsTypeTree {
+    private var orig: Tree = null 
+    private[Trees] var wasEmpty: Boolean = false
 
-    override def symbol = if (tpe == null) null else tpe.typeSymbol
+    def original: Tree = orig
+    def setOriginal(tree: Tree): this.type = { orig = tree; setPos(tree.pos); this }
 
-    def setOriginal(tree: Tree): this.type = {
-      original = tree
-      setPos(tree.pos)
+    override def defineType(tp: Type): this.type = {
+      wasEmpty = isEmpty
+      setType(tp)
     }
-    
-    override def isEmpty = (tpe eq null) || tpe == NoType
   }
 
-  def TypeTree(tp: Type): TypeTree = TypeTree() setType tp
-  // def TypeTree(tp: Type, tree : Tree): TypeTree = TypeTree(tree) setType tp
+  object TypeTree extends TypeTreeExtractor
 
-  /** A tree that has an attribute attached to it */
-  case class Annotated(annot: Annotation, arg: Tree) extends Tree {
-    override def isType = arg.isType
-    override def isTerm = arg.isTerm
+  def TypeTree(tp: Type): TypeTree = TypeTree() setType tp
+  
+  /** Documented definition, eliminated by analyzer */
+  case class DocDef(comment: DocComment, definition: Tree)
+       extends Tree {
+    override def symbol: Symbol = definition.symbol
+    override def symbol_=(sym: Symbol) { definition.symbol = sym }
+    // sean: seems to be important to the IDE
+    override def isDef = definition.isDef
   }
 
-  /** Singleton type, eliminated by RefCheck */
-  case class SingletonTypeTree(ref: Tree)
-        extends TypTree
-
-  /** Type selection <qualifier> # <selector>, eliminated by RefCheck */
-  case class SelectFromTypeTree(qualifier: Tree, selector: Name)
-       extends TypTree with SymTree
+  /** Either an assignment or a named argument. Only appears in argument lists,
+   *  eliminated by typecheck (doTypedApply)
+   */
+  case class AssignOrNamedArg(lhs: Tree, rhs: Tree)
+       extends TermTree
 
-  /** Intersection type <parent1> with ... with <parentN> { <decls> }, eliminated by RefCheck */
-  case class CompoundTypeTree(templ: Template)
-       extends TypTree
+  case class Parens(args: List[Tree]) extends Tree // only used during parsing
 
-  /** Applied type <tpt> [ <args> ], eliminated by RefCheck */
-  case class AppliedTypeTree(tpt: Tree, args: List[Tree])
-       extends TypTree {
-    override def symbol: Symbol = tpt.symbol
-    override def symbol_=(sym: Symbol) { tpt.symbol = sym }
-  }
+  /** emitted by typer, eliminated by refchecks **/
+  case class TypeTreeWithDeferredRefCheck()(val check: () => TypeTree) extends AbsTypeTree
 
-  case class TypeBoundsTree(lo: Tree, hi: Tree)
-       extends TypTree
+// ----- subconstructors --------------------------------------------
 
-  case class ExistentialTypeTree(tpt: Tree, whereClauses: List[Tree])
-       extends TypTree
-
-  trait StubTree extends Tree {
-    def underlying : AnyRef
-    override def equalsStructure0(that: Tree)(f : (Tree,Tree) => Boolean): Boolean = this eq that
-  }
+  class ApplyToImplicitArgs(fun: Tree, args: List[Tree]) extends Apply(fun, args)
+  
+  class ApplyImplicitView(fun: Tree, args: List[Tree]) extends Apply(fun, args)
 
-/* A standard pattern match 
-  case EmptyTree =>
-  case PackageDef(name, stats) =>
-     // package name { stats }
-  case ClassDef(mods, name, tparams, impl) =>
-     // mods class name [tparams] impl   where impl = extends parents { defs }
-  case ModuleDef(mods, name, impl) =>                             (eliminated by refcheck)
-     // mods object name impl  where impl = extends parents { defs }
-  case ValDef(mods, name, tpt, rhs) =>
-     // mods val name: tpt = rhs   
-     // note missing type information is expressed by tpt = TypeTree()
-  case DefDef(mods, name, tparams, vparamss, tpt, rhs) =>
-     // mods def name[tparams](vparams_1)...(vparams_n): tpt = rhs
-     // note missing type information is expressed by tpt = TypeTree()
-  case TypeDef(mods, name, tparams, rhs) =>                       (eliminated by erasure)
-     // mods type name[tparams] = rhs
-     // mods type name[tparams] >: lo <: hi,  where lo, hi are in a TypeBoundsTree, 
-                                              and DEFERRED is set in mods
-  case LabelDef(name, params, rhs) =>
-     // used for tailcalls and like
-     // while/do are desugared to label defs as follows:
-     // while (cond) body ==> LabelDef($L, List(), if (cond) { body; L$() } else ())
-     // do body while (cond) ==> LabelDef($L, List(), body; if (cond) L$() else ())
-  case Import(expr, selectors) =>                                 (eliminated by typecheck)
-     // import expr.{selectors}
-     // Selectors are a list of pairs of names (from, to).
-     // The last (and maybe only name) may be a nme.WILDCARD
-     // for instance
-     //   import qual.{x, y => z, _}  would be represented as
-     //   Import(qual, List(("x", "x"), ("y", "z"), (WILDCARD, null)))
-  case Annotation(constr, elements) =>                            
-     // @constr(elements) where constr = tp(args),   (an instance of Apply)
-     //                         elements = { val x1 = c1, ..., val xn = cn }
-  case DocDef(comment, definition) =>                             (eliminated by typecheck)
-     // /** comment */ definition
-  case Template(parents, self, body) =>
-     // extends parents { self => body }
-     // if self is missing it is represented as emptyValDef
-  case Block(stats, expr) =>
-     // { stats; expr }
-  case CaseDef(pat, guard, body) =>                               (eliminated by transmatch/explicitouter)
-    // case pat if guard => body
-  case Sequence(trees) =>                                         (eliminated by transmatch/explicitouter)
-    // pat1, ..., pat_n
-  case Alternative(trees) =>                                      (eliminated by transmatch/explicitouter)
-    // pat1 | ... | patn
-  case Star(elem) =>                                              (eliminated by transmatch/explicitouter)
-    // pat*
-  case Bind(name, body) =>                                        (eliminated by transmatch/explicitouter)
-    // name @ pat
-  case UnApply(fun: Tree, args)                                   (introduced by typer, eliminated by transmatch/explicitouter)
-    // used for unapply's
-  case ArrayValue(elemtpt, trees) =>                              (introduced by uncurry)
-    // used to pass arguments to vararg arguments
-    // for instance, printf("%s%d", foo, 42) is translated to after uncurry to:
-    // Apply(
-    //   Ident("printf"), 
-    //   Literal("%s%d"), 
-    //   ArrayValue(<Any>, List(Ident("foo"), Literal(42))))
-  case Function(vparams, body) =>                                 (eliminated by lambdaLift)
-    // vparams => body  where vparams:List[ValDef]
-  case Assign(lhs, rhs) =>
-    // lhs = rhs
-  case If(cond, thenp, elsep) =>
-    // if (cond) thenp else elsep
-  case Match(selector, cases) =>
-    // selector match { cases }
-  case Return(expr) =>
-    // return expr
-  case Try(block, catches, finalizer) =>
-    // try block catch { catches } finally finalizer where catches: List[CaseDef]
-  case Throw(expr) =>
-    // throw expr
-  case New(tpt) =>
-    // new tpt   always in the context: (new tpt).<init>[targs](args)
-  case Typed(expr, tpt) =>                                        (eliminated by erasure)
-    // expr: tpt
-  case TypeApply(fun, args) =>
-    // fun[args]
-  case Apply(fun, args) =>
-    // fun(args)
-    // for instance fun[targs](args)  is expressed as  Apply(TypeApply(fun, targs), args)
-  case ApplyDynamic(qual, args)                                   (introduced by erasure, eliminated by cleanup)
-    // fun(args)
-  case Super(qual, mix) =>
-    // qual.super[mix]     if qual and/or mix is empty, ther are nme.EMPTY.toTypeName
-  case This(qual) =>
-    // qual.this
-  case Select(qualifier, selector) =>
-    // qualifier.selector
-  case Ident(name) =>
-    // name
-    // note: type checker converts idents that refer to enclosing fields or methods
-    // to selects; name ==> this.name
-  case Literal(value) =>
-    // value
-  case TypeTree() =>                                              (introduced by refcheck)
-    // a type that's not written out, but given in the tpe attribute
-  case Annotated(annot, arg) =>                                   (eliminated by typer)
-    // arg @annot  for types,  arg: @annot for exprs
-  case SingletonTypeTree(ref) =>                                  (eliminated by uncurry)
-    // ref.type
-  case SelectFromTypeTree(qualifier, selector) =>                 (eliminated by uncurry)
-    // qualifier # selector, a path-dependent type p.T is expressed as p.type # T
-  case CompoundTypeTree(templ: Template) =>                       (eliminated by uncurry)
-    // parent1 with ... with parentN { refinement }
-  case AppliedTypeTree(tpt, args) =>                              (eliminated by uncurry)
-    // tpt[args]
-  case TypeBoundsTree(lo, hi) =>                                  (eliminated by uncurry)
-    // >: lo <: hi
-  case ExistentialTypeTree(tpt, whereClauses) =>                  (eliminated by uncurry)
-    // tpt forSome { whereClauses }
-
-*/
+// ----- auxiliary objects and methods ------------------------------
 
   abstract class TreeCopier {
     def ClassDef(tree: Tree, mods: Modifiers, name: Name, tparams: List[TypeDef], impl: Template): ClassDef
-    def PackageDef(tree: Tree, name: Name, stats: List[Tree]): PackageDef
+    def PackageDef(tree: Tree, pid: RefTree, stats: List[Tree]): PackageDef
     def ModuleDef(tree: Tree, mods: Modifiers, name: Name, impl: Template): ModuleDef
     def ValDef(tree: Tree, mods: Modifiers, name: Name, tpt: Tree, rhs: Tree): ValDef
     def DefDef(tree: Tree, mods: Modifiers, name: Name, tparams: List[TypeDef], vparamss: List[List[ValDef]], tpt: Tree, rhs: Tree): DefDef
     def TypeDef(tree: Tree, mods: Modifiers, name: Name, tparams: List[TypeDef], rhs: Tree): TypeDef
     def LabelDef(tree: Tree, name: Name, params: List[Ident], rhs: Tree): LabelDef
-    def Import(tree: Tree, expr: Tree, selectors: List[(Name, Name)]): Import
-    def Annotation(tree: Tree, constr: Tree, elements: List[Tree]): Annotation
-    def DocDef(tree: Tree, comment: String, definition: Tree): DocDef
+    def Import(tree: Tree, expr: Tree, selectors: List[ImportSelector]): Import
+    def DocDef(tree: Tree, comment: DocComment, definition: Tree): DocDef
     def Template(tree: Tree, parents: List[Tree], self: ValDef, body: List[Tree]): Template
     def Block(tree: Tree, stats: List[Tree], expr: Tree): Block
     def CaseDef(tree: Tree, pat: Tree, guard: Tree, body: Tree): CaseDef
-    def Sequence(tree: Tree, trees: List[Tree]): Sequence
     def Alternative(tree: Tree, trees: List[Tree]): Alternative
     def Star(tree: Tree, elem: Tree): Star
     def Bind(tree: Tree, name: Name, body: Tree): Bind
@@ -998,6 +369,7 @@ trait Trees {
     def ArrayValue(tree: Tree, elemtpt: Tree, trees: List[Tree]): ArrayValue
     def Function(tree: Tree, vparams: List[ValDef], body: Tree): Function
     def Assign(tree: Tree, lhs: Tree, rhs: Tree): Assign
+    def AssignOrNamedArg(tree: Tree, lhs: Tree, rhs: Tree): AssignOrNamedArg
     def If(tree: Tree, cond: Tree, thenp: Tree, elsep: Tree): If
     def Match(tree: Tree, selector: Tree, cases: List[CaseDef]): Match
     def Return(tree: Tree, expr: Tree): Return
@@ -1014,20 +386,22 @@ trait Trees {
     def Ident(tree: Tree, name: Name): Ident
     def Literal(tree: Tree, value: Constant): Literal
     def TypeTree(tree: Tree): TypeTree
-    def Annotated(tree: Tree, annot: Annotation, arg: Tree): Annotated
+    def TypeTreeWithDeferredRefCheck(tree: Tree): TypeTreeWithDeferredRefCheck
+    def Annotated(tree: Tree, annot: Tree, arg: Tree): Annotated
     def SingletonTypeTree(tree: Tree, ref: Tree): SingletonTypeTree
     def SelectFromTypeTree(tree: Tree, qualifier: Tree, selector: Name): SelectFromTypeTree
     def CompoundTypeTree(tree: Tree, templ: Template): CompoundTypeTree
     def AppliedTypeTree(tree: Tree, tpt: Tree, args: List[Tree]): AppliedTypeTree
     def TypeBoundsTree(tree: Tree, lo: Tree, hi: Tree): TypeBoundsTree
     def ExistentialTypeTree(tree: Tree, tpt: Tree, whereClauses: List[Tree]): ExistentialTypeTree
+    def SelectFromArray(tree: Tree, qualifier: Tree, selector: Name, erasure: Type): SelectFromArray
   }
 
   class StrictTreeCopier extends TreeCopier {
     def ClassDef(tree: Tree, mods: Modifiers, name: Name, tparams: List[TypeDef], impl: Template) =
-      new ClassDef(mods, name, tparams, impl).copyAttrs(tree);
-    def PackageDef(tree: Tree, name: Name, stats: List[Tree]) =
-      new PackageDef(name, stats).copyAttrs(tree)
+      new ClassDef(mods, name, tparams, impl).copyAttrs(tree)
+    def PackageDef(tree: Tree, pid: RefTree, stats: List[Tree]) =
+      new PackageDef(pid, stats).copyAttrs(tree)
     def ModuleDef(tree: Tree, mods: Modifiers, name: Name, impl: Template) =
       new ModuleDef(mods, name, impl).copyAttrs(tree)
     def ValDef(tree: Tree, mods: Modifiers, name: Name, tpt: Tree, rhs: Tree) =
@@ -1038,11 +412,9 @@ trait Trees {
       new TypeDef(mods, name, tparams, rhs).copyAttrs(tree)
     def LabelDef(tree: Tree, name: Name, params: List[Ident], rhs: Tree) =
       new LabelDef(name, params, rhs).copyAttrs(tree)
-    def Import(tree: Tree, expr: Tree, selectors: List[(Name, Name)]) =
+    def Import(tree: Tree, expr: Tree, selectors: List[ImportSelector]) =
       new Import(expr, selectors).copyAttrs(tree)
-    def Annotation(tree: Tree, constr: Tree, elements: List[Tree]) =
-      new Annotation(constr, elements).copyAttrs(tree)
-    def DocDef(tree: Tree, comment: String, definition: Tree) =
+    def DocDef(tree: Tree, comment: DocComment, definition: Tree) =
       new DocDef(comment, definition).copyAttrs(tree)
     def Template(tree: Tree, parents: List[Tree], self: ValDef, body: List[Tree]) =
       new Template(parents, self, body).copyAttrs(tree)
@@ -1050,8 +422,6 @@ trait Trees {
       new Block(stats, expr).copyAttrs(tree)
     def CaseDef(tree: Tree, pat: Tree, guard: Tree, body: Tree) =
       new CaseDef(pat, guard, body).copyAttrs(tree)
-    def Sequence(tree: Tree, trees: List[Tree]) =
-      new Sequence(trees).copyAttrs(tree)
     def Alternative(tree: Tree, trees: List[Tree]) =
       new Alternative(trees).copyAttrs(tree)
     def Star(tree: Tree, elem: Tree) =
@@ -1066,6 +436,8 @@ trait Trees {
       new Function(vparams, body).copyAttrs(tree)
     def Assign(tree: Tree, lhs: Tree, rhs: Tree) =
       new Assign(lhs, rhs).copyAttrs(tree)
+    def AssignOrNamedArg(tree: Tree, lhs: Tree, rhs: Tree) =
+      new AssignOrNamedArg(lhs, rhs).copyAttrs(tree)
     def If(tree: Tree, cond: Tree, thenp: Tree, elsep: Tree) =
       new If(cond, thenp, elsep).copyAttrs(tree)
     def Match(tree: Tree, selector: Tree, cases: List[CaseDef]) =
@@ -1083,7 +455,11 @@ trait Trees {
     def TypeApply(tree: Tree, fun: Tree, args: List[Tree]) =
       new TypeApply(fun, args).copyAttrs(tree)
     def Apply(tree: Tree, fun: Tree, args: List[Tree]) =
-      new Apply(fun, args).copyAttrs(tree)
+      (tree match {
+        case _: ApplyToImplicitArgs => new ApplyToImplicitArgs(fun, args)
+        case _: ApplyImplicitView => new ApplyImplicitView(fun, args)
+        case _ => new Apply(fun, args)
+      }).copyAttrs(tree)
     def ApplyDynamic(tree: Tree, qual: Tree, args: List[Tree]) =
       new ApplyDynamic(qual, args).copyAttrs(tree)
     def Super(tree: Tree, qual: Name, mix: Name) =
@@ -1098,7 +474,10 @@ trait Trees {
       new Literal(value).copyAttrs(tree)
     def TypeTree(tree: Tree) =
       new TypeTree().copyAttrs(tree)
-    def Annotated(tree: Tree, annot: Annotation, arg: Tree) =
+    def TypeTreeWithDeferredRefCheck(tree: Tree) = tree match {
+      case dc at TypeTreeWithDeferredRefCheck() => new TypeTreeWithDeferredRefCheck()(dc.check).copyAttrs(tree)
+    }
+    def Annotated(tree: Tree, annot: Tree, arg: Tree) =
       new Annotated(annot, arg).copyAttrs(tree)
     def SingletonTypeTree(tree: Tree, ref: Tree) =
       new SingletonTypeTree(ref).copyAttrs(tree)
@@ -1112,234 +491,240 @@ trait Trees {
       new TypeBoundsTree(lo, hi).copyAttrs(tree)
     def ExistentialTypeTree(tree: Tree, tpt: Tree, whereClauses: List[Tree]) =
       new ExistentialTypeTree(tpt, whereClauses).copyAttrs(tree)
+    def SelectFromArray(tree: Tree, qualifier: Tree, selector: Name, erasure: Type) =
+      new SelectFromArray(qualifier, selector, erasure).copyAttrs(tree)
   }
 
-  class LazyTreeCopier(copy: TreeCopier) extends TreeCopier {
+  class LazyTreeCopier(treeCopy: TreeCopier) extends TreeCopier {
     def this() = this(new StrictTreeCopier)
     def ClassDef(tree: Tree, mods: Modifiers, name: Name, tparams: List[TypeDef], impl: Template) = tree match {
       case t @ ClassDef(mods0, name0, tparams0, impl0)
-      if (mods0 == mods && (name0 == name) && (tparams0 == tparams) && (impl0 == impl)) => t
-      case _ => copy.ClassDef(tree, mods, name, tparams, impl)
+      if (mods0 == mods) && (name0 == name) && (tparams0 == tparams) && (impl0 == impl) => t
+      case _ => treeCopy.ClassDef(tree, mods, name, tparams, impl)
     }
-    def PackageDef(tree: Tree, name: Name, stats: List[Tree]) = tree match {
-      case t @ PackageDef(name0, stats0)
-      if (name0 == name) && (stats0 == stats) => t
-      case _ => copy.PackageDef(tree, name, stats)
+    def PackageDef(tree: Tree, pid: RefTree, stats: List[Tree]) = tree match {
+      case t @ PackageDef(pid0, stats0)
+      if (pid0 == pid) && (stats0 == stats) => t
+      case _ => treeCopy.PackageDef(tree, pid, stats)
     }
     def ModuleDef(tree: Tree, mods: Modifiers, name: Name, impl: Template) = tree match {
       case t @ ModuleDef(mods0, name0, impl0)
       if (mods0 == mods) && (name0 == name) && (impl0 == impl) => t
-      case _ => copy.ModuleDef(tree, mods, name, impl)
+      case _ => treeCopy.ModuleDef(tree, mods, name, impl)
     }
     def ValDef(tree: Tree, mods: Modifiers, name: Name, tpt: Tree, rhs: Tree) = tree match {
       case t @ ValDef(mods0, name0, tpt0, rhs0)
       if (mods0 == mods) && (name0 == name) && (tpt0 == tpt) && (rhs0 == rhs) => t
-      case _ => copy.ValDef(tree, mods, name, tpt, rhs)
+      case _ => treeCopy.ValDef(tree, mods, name, tpt, rhs)
     }
     def DefDef(tree: Tree, mods: Modifiers, name: Name, tparams: List[TypeDef], vparamss: List[List[ValDef]], tpt: Tree, rhs: Tree) = tree match {
       case t @ DefDef(mods0, name0, tparams0, vparamss0, tpt0, rhs0)
       if (mods0 == mods) && (name0 == name) && (tparams0 == tparams) &&
          (vparamss0 == vparamss) && (tpt0 == tpt) && (rhs == rhs0) => t
-      case _ => copy.DefDef(tree, mods, name, tparams, vparamss, tpt, rhs)
+      case _ => treeCopy.DefDef(tree, mods, name, tparams, vparamss, tpt, rhs)
     }
     def TypeDef(tree: Tree, mods: Modifiers, name: Name, tparams: List[TypeDef], rhs: Tree) = tree match {
       case t @ TypeDef(mods0, name0, tparams0, rhs0)
       if (mods0 == mods) && (name0 == name) && (tparams0 == tparams) && (rhs0 == rhs) => t
-      case _ => copy.TypeDef(tree, mods, name, tparams, rhs)
+      case _ => treeCopy.TypeDef(tree, mods, name, tparams, rhs)
     }
     def LabelDef(tree: Tree, name: Name, params: List[Ident], rhs: Tree) = tree match {
       case t @ LabelDef(name0, params0, rhs0)
       if (name0 == name) && (params0 == params) && (rhs0 == rhs) => t
-      case _ => copy.LabelDef(tree, name, params, rhs)
+      case _ => treeCopy.LabelDef(tree, name, params, rhs)
     }
-    def Import(tree: Tree, expr: Tree, selectors: List[(Name, Name)]) = tree match {
+    def Import(tree: Tree, expr: Tree, selectors: List[ImportSelector]) = tree match {
       case t @ Import(expr0, selectors0)
       if (expr0 == expr) && (selectors0 == selectors) => t
-      case _ => copy.Import(tree, expr, selectors)
-    }
-    def Annotation(tree: Tree, constr: Tree, elements: List[Tree]) = tree match {
-      case t @ Annotation(constr0, elements0)
-      if (constr0 == constr) && (elements0 == elements) => t
-      case _ => copy.Annotation(tree, constr, elements)
+      case _ => treeCopy.Import(tree, expr, selectors)
     }
-    def DocDef(tree: Tree, comment: String, definition: Tree) = tree match {
+    def DocDef(tree: Tree, comment: DocComment, definition: Tree) = tree match {
       case t @ DocDef(comment0, definition0)
       if (comment0 == comment) && (definition0 == definition) => t
-      case _ => copy.DocDef(tree, comment, definition)
+      case _ => treeCopy.DocDef(tree, comment, definition)
     }
     def Template(tree: Tree, parents: List[Tree], self: ValDef, body: List[Tree]) = tree match {
       case t @ Template(parents0, self0, body0)
       if (parents0 == parents) && (self0 == self) && (body0 == body) => t
-      case _ => copy.Template(tree, parents, self, body)
+      case _ => treeCopy.Template(tree, parents, self, body)
     }
     def Block(tree: Tree, stats: List[Tree], expr: Tree) = tree match {
       case t @ Block(stats0, expr0)
       if ((stats0 == stats) && (expr0 == expr)) => t
-      case _ => copy.Block(tree, stats, expr)
+      case _ => treeCopy.Block(tree, stats, expr)
     }
     def CaseDef(tree: Tree, pat: Tree, guard: Tree, body: Tree) = tree match {
       case t @ CaseDef(pat0, guard0, body0)
       if (pat0 == pat) && (guard0 == guard) && (body0 == body) => t
-      case _ => copy.CaseDef(tree, pat, guard, body)
-    }
-    def Sequence(tree: Tree, trees: List[Tree]) = tree match {
-      case t @ Sequence(trees0)
-      if trees0 == trees => t
-      case _ => copy.Sequence(tree, trees)
+      case _ => treeCopy.CaseDef(tree, pat, guard, body)
     }
     def Alternative(tree: Tree, trees: List[Tree]) = tree match {
       case t @ Alternative(trees0)
       if trees0 == trees => t
-      case _ => copy.Alternative(tree, trees)
+      case _ => treeCopy.Alternative(tree, trees)
     }
     def Star(tree: Tree, elem: Tree) = tree match {
       case t @ Star(elem0)
       if elem0 == elem => t
-      case _ => copy.Star(tree, elem)
+      case _ => treeCopy.Star(tree, elem)
     }
     def Bind(tree: Tree, name: Name, body: Tree) = tree match {
       case t @ Bind(name0, body0)
       if (name0 == name) && (body0 == body) => t
-      case _ => copy.Bind(tree, name, body)
+      case _ => treeCopy.Bind(tree, name, body)
     }
     def UnApply(tree: Tree, fun: Tree, args: List[Tree]) = tree match {
       case t @ UnApply(fun0, args0)
       if (fun0 == fun) && (args0 == args) => t
-      case _ => copy.UnApply(tree, fun, args)
+      case _ => treeCopy.UnApply(tree, fun, args)
     }
     def ArrayValue(tree: Tree, elemtpt: Tree, trees: List[Tree]) = tree match {
       case t @ ArrayValue(elemtpt0, trees0)
       if (elemtpt0 == elemtpt) && (trees0 == trees) => t
-      case _ => copy.ArrayValue(tree, elemtpt, trees)
+      case _ => treeCopy.ArrayValue(tree, elemtpt, trees)
     }
     def Function(tree: Tree, vparams: List[ValDef], body: Tree) = tree match {
       case t @ Function(vparams0, body0)
       if (vparams0 == vparams) && (body0 == body) => t
-      case _ => copy.Function(tree, vparams, body)
+      case _ => treeCopy.Function(tree, vparams, body)
     }
     def Assign(tree: Tree, lhs: Tree, rhs: Tree) = tree match {
       case t @ Assign(lhs0, rhs0)
       if (lhs0 == lhs) && (rhs0 == rhs) => t
-      case _ => copy.Assign(tree, lhs, rhs)
+      case _ => treeCopy.Assign(tree, lhs, rhs)
+    }
+    def AssignOrNamedArg(tree: Tree, lhs: Tree, rhs: Tree) = tree match {
+      case t @ AssignOrNamedArg(lhs0, rhs0)
+      if (lhs0 == lhs) && (rhs0 == rhs) => t
+      case _ => treeCopy.AssignOrNamedArg(tree, lhs, rhs)
     }
     def If(tree: Tree, cond: Tree, thenp: Tree, elsep: Tree) = tree match {
       case t @ If(cond0, thenp0, elsep0) 
       if (cond0 == cond) && (thenp0 == thenp) && (elsep0 == elsep) => t
-      case _ => copy.If(tree, cond, thenp, elsep)
+      case _ => treeCopy.If(tree, cond, thenp, elsep)
     }
     def Match(tree: Tree, selector: Tree, cases: List[CaseDef]) =  tree match {
       case t @ Match(selector0, cases0)
       if (selector0 == selector) && (cases0 == cases) => t
-      case _ => copy.Match(tree, selector, cases)
+      case _ => treeCopy.Match(tree, selector, cases)
     }
     def Return(tree: Tree, expr: Tree) = tree match {
       case t @ Return(expr0)
       if expr0 == expr => t
-      case _ => copy.Return(tree, expr)
+      case _ => treeCopy.Return(tree, expr)
     }
     def Try(tree: Tree, block: Tree, catches: List[CaseDef], finalizer: Tree) = tree match {
       case t @ Try(block0, catches0, finalizer0)
       if (block0 == block) && (catches0 == catches) && (finalizer0 == finalizer) => t
-      case _ => copy.Try(tree, block, catches, finalizer)
+      case _ => treeCopy.Try(tree, block, catches, finalizer)
     }
     def Throw(tree: Tree, expr: Tree) = tree match {
       case t @ Throw(expr0)
       if expr0 == expr => t
-      case _ => copy.Throw(tree, expr)
+      case _ => treeCopy.Throw(tree, expr)
     }
     def New(tree: Tree, tpt: Tree) = tree match {
       case t @ New(tpt0)
       if tpt0 == tpt => t
-      case _ => copy.New(tree, tpt)
+      case _ => treeCopy.New(tree, tpt)
     }
     def Typed(tree: Tree, expr: Tree, tpt: Tree) = tree match {
       case t @ Typed(expr0, tpt0)
       if (expr0 == expr) && (tpt0 == tpt) => t
-      case _ => copy.Typed(tree, expr, tpt)
+      case _ => treeCopy.Typed(tree, expr, tpt)
     }
     def TypeApply(tree: Tree, fun: Tree, args: List[Tree]) = tree match {
       case t @ TypeApply(fun0, args0)
       if (fun0 == fun) && (args0 == args) => t
-      case _ => copy.TypeApply(tree, fun, args)
+      case _ => treeCopy.TypeApply(tree, fun, args)
     }
     def Apply(tree: Tree, fun: Tree, args: List[Tree]) = tree match {
       case t @ Apply(fun0, args0)
       if (fun0 == fun) && (args0 == args) => t
-      case _ => copy.Apply(tree, fun, args)
+      case _ => treeCopy.Apply(tree, fun, args)
     }
     def ApplyDynamic(tree: Tree, qual: Tree, args: List[Tree]) = tree match {
       case t @ ApplyDynamic(qual0, args0)
       if (qual0 == qual) && (args0 == args) => t
-      case _ => copy.ApplyDynamic(tree, qual, args)
+      case _ => treeCopy.ApplyDynamic(tree, qual, args)
     }
     def Super(tree: Tree, qual: Name, mix: Name) = tree match {
       case t @ Super(qual0, mix0)
       if (qual0 == qual) && (mix0 == mix) => t
-      case _ => copy.Super(tree, qual, mix)
+      case _ => treeCopy.Super(tree, qual, mix)
     }
     def This(tree: Tree, qual: Name) = tree match {
       case t @ This(qual0)
       if qual0 == qual => t
-      case _ => copy.This(tree, qual)
+      case _ => treeCopy.This(tree, qual)
     }
     def Select(tree: Tree, qualifier: Tree, selector: Name) = tree match {
       case t @ Select(qualifier0, selector0)
       if (qualifier0 == qualifier) && (selector0 == selector) => t
-      case _ => copy.Select(tree, qualifier, selector)
+      case _ => treeCopy.Select(tree, qualifier, selector)
     }
     def Ident(tree: Tree, name: Name) = tree match {
       case t @ Ident(name0)
       if name0 == name => t
-      case _ => copy.Ident(tree, name)
+      case _ => treeCopy.Ident(tree, name)
     }
     def Literal(tree: Tree, value: Constant) = tree match {
       case t @ Literal(value0)
       if value0 == value => t
-      case _ => copy.Literal(tree, value)
+      case _ => treeCopy.Literal(tree, value)
     }
     def TypeTree(tree: Tree) = tree match {
       case t @ TypeTree() => t
-      case _ => copy.TypeTree(tree)
+      case _ => treeCopy.TypeTree(tree)
+    }
+    def TypeTreeWithDeferredRefCheck(tree: Tree) = tree match {
+      case t @ TypeTreeWithDeferredRefCheck() => t
+      case _ => treeCopy.TypeTreeWithDeferredRefCheck(tree)
     }
-    def Annotated(tree: Tree, annot: Annotation, arg: Tree) = tree match {
+    def Annotated(tree: Tree, annot: Tree, arg: Tree) = tree match {
       case t @ Annotated(annot0, arg0)
       if (annot0==annot) => t
-      case _ => copy.Annotated(tree, annot, arg)
+      case _ => treeCopy.Annotated(tree, annot, arg)
     }
     def SingletonTypeTree(tree: Tree, ref: Tree) = tree match {
       case t @ SingletonTypeTree(ref0)
       if ref0 == ref => t
-      case _ => copy.SingletonTypeTree(tree, ref)
+      case _ => treeCopy.SingletonTypeTree(tree, ref)
     }
     def SelectFromTypeTree(tree: Tree, qualifier: Tree, selector: Name) = tree match {
       case t @ SelectFromTypeTree(qualifier0, selector0)
       if (qualifier0 == qualifier) && (selector0 == selector) => t
-      case _ => copy.SelectFromTypeTree(tree, qualifier, selector)
+      case _ => treeCopy.SelectFromTypeTree(tree, qualifier, selector)
     }
     def CompoundTypeTree(tree: Tree, templ: Template) = tree match {
       case t @ CompoundTypeTree(templ0)
       if templ0 == templ => t
-      case _ => copy.CompoundTypeTree(tree, templ)
+      case _ => treeCopy.CompoundTypeTree(tree, templ)
     }
     def AppliedTypeTree(tree: Tree, tpt: Tree, args: List[Tree]) = tree match {
       case t @ AppliedTypeTree(tpt0, args0)
       if (tpt0 == tpt) && (args0 == args) => t
-      case _ => copy.AppliedTypeTree(tree, tpt, args)
+      case _ => treeCopy.AppliedTypeTree(tree, tpt, args)
     }
     def TypeBoundsTree(tree: Tree, lo: Tree, hi: Tree) = tree match {
       case t @ TypeBoundsTree(lo0, hi0)
       if (lo0 == lo) && (hi0 == hi) => t
-      case _ => copy.TypeBoundsTree(tree, lo, hi)
+      case _ => treeCopy.TypeBoundsTree(tree, lo, hi)
     }
     def ExistentialTypeTree(tree: Tree, tpt: Tree, whereClauses: List[Tree]) = tree match {
       case t @ ExistentialTypeTree(tpt0, whereClauses0)
       if (tpt0 == tpt) && (whereClauses0 == whereClauses) => t
-      case _ => copy.ExistentialTypeTree(tree, tpt, whereClauses)
+      case _ => treeCopy.ExistentialTypeTree(tree, tpt, whereClauses)
+    }
+    def SelectFromArray(tree: Tree, qualifier: Tree, selector: Name, erasure: Type) = tree match {
+      case t @ SelectFromArray(qualifier0, selector0, _)
+      if (qualifier0 == qualifier) && (selector0 == selector) => t
+      case _ => treeCopy.SelectFromArray(tree, qualifier, selector, erasure)
     }
   }
 
   abstract class Transformer {
-    val copy: TreeCopier = new LazyTreeCopier
+    val treeCopy: TreeCopier = new LazyTreeCopier
     protected var currentOwner: Symbol = definitions.RootClass
     protected def currentMethod = currentOwner.enclMethod
     protected def currentClass = currentOwner.enclClass
@@ -1347,136 +732,144 @@ trait Trees {
     def transform(tree: Tree): Tree = tree match {
       case EmptyTree =>
         tree
-      case PackageDef(name, stats) =>
-        atOwner(tree.symbol.moduleClass) {
-          copy.PackageDef(tree, name, transformStats(stats, currentOwner))
-        }
+      case PackageDef(pid, stats) =>
+        treeCopy.PackageDef(
+          tree, transform(pid).asInstanceOf[RefTree], 
+          atOwner(tree.symbol.moduleClass) {
+            transformStats(stats, currentOwner)
+          }
+        )
       case ClassDef(mods, name, tparams, impl) =>
         atOwner(tree.symbol) {
-          copy.ClassDef(tree, mods, name, transformTypeDefs(tparams), transformTemplate(impl))
+          treeCopy.ClassDef(tree, transformModifiers(mods), name,
+                            transformTypeDefs(tparams), transformTemplate(impl))
         }
       case ModuleDef(mods, name, impl) =>
         atOwner(tree.symbol.moduleClass) {
-          copy.ModuleDef(tree, mods, name, transformTemplate(impl))
+          treeCopy.ModuleDef(tree, transformModifiers(mods),
+                             name, transformTemplate(impl))
         }
       case ValDef(mods, name, tpt, rhs) =>
         atOwner(tree.symbol) {
-          copy.ValDef(tree, mods, name, transform(tpt), transform(rhs))
+          treeCopy.ValDef(tree, transformModifiers(mods),
+                          name, transform(tpt), transform(rhs))
         }
       case DefDef(mods, name, tparams, vparamss, tpt, rhs) =>
         atOwner(tree.symbol) {
-          copy.DefDef(
-            tree, mods, name, transformTypeDefs(tparams), transformValDefss(vparamss), transform(tpt), transform(rhs))
+          treeCopy.DefDef(tree, transformModifiers(mods), name,
+                          transformTypeDefs(tparams), transformValDefss(vparamss),
+                          transform(tpt), transform(rhs))
         }
       case TypeDef(mods, name, tparams, rhs) =>
         atOwner(tree.symbol) {
-          copy.TypeDef(tree, mods, name, transformTypeDefs(tparams), transform(rhs))
+          treeCopy.TypeDef(tree, transformModifiers(mods), name,
+                           transformTypeDefs(tparams), transform(rhs))
         }
       case LabelDef(name, params, rhs) =>
-        copy.LabelDef(tree, name, transformIdents(params), transform(rhs)) //bq: Martin, once, atOwner(...) works, also change `LamdaLifter.proxy'
+        treeCopy.LabelDef(tree, name, transformIdents(params), transform(rhs)) //bq: Martin, once, atOwner(...) works, also change `LamdaLifter.proxy'
       case Import(expr, selectors) =>
-        copy.Import(tree, transform(expr), selectors)
-      case Annotation(constr, elements) =>
-        copy.Annotation(tree, transform(constr), transformTrees(elements))
+        treeCopy.Import(tree, transform(expr), selectors)
       case DocDef(comment, definition) =>
-        copy.DocDef(tree, comment, transform(definition))
+        treeCopy.DocDef(tree, comment, transform(definition))
       case Template(parents, self, body) =>
-        copy.Template(tree, transformTrees(parents), transformValDef(self), transformStats(body, tree.symbol))
+        treeCopy.Template(tree, transformTrees(parents), transformValDef(self), transformStats(body, tree.symbol))
       case Block(stats, expr) =>
-        copy.Block(tree, transformStats(stats, currentOwner), transform(expr))
+        treeCopy.Block(tree, transformStats(stats, currentOwner), transform(expr))
       case CaseDef(pat, guard, body) =>
-        copy.CaseDef(tree, transform(pat), transform(guard), transform(body))
-      case Sequence(trees) =>
-        copy.Sequence(tree, transformTrees(trees))
+        treeCopy.CaseDef(tree, transform(pat), transform(guard), transform(body))
       case Alternative(trees) =>
-        copy.Alternative(tree, transformTrees(trees))
+        treeCopy.Alternative(tree, transformTrees(trees))
       case Star(elem) =>
-        copy.Star(tree, transform(elem))
+        treeCopy.Star(tree, transform(elem))
       case Bind(name, body) =>
-        copy.Bind(tree, name, transform(body))
+        treeCopy.Bind(tree, name, transform(body))
       case UnApply(fun, args) =>
-        copy.UnApply(tree, fun, transformTrees(args)) // bq: see test/.../unapplyContexts2.scala
+        treeCopy.UnApply(tree, fun, transformTrees(args)) // bq: see test/.../unapplyContexts2.scala
       case ArrayValue(elemtpt, trees) =>
-        copy.ArrayValue(tree, transform(elemtpt), transformTrees(trees))
+        treeCopy.ArrayValue(tree, transform(elemtpt), transformTrees(trees))
       case Function(vparams, body) =>
         atOwner(tree.symbol) {
-          copy.Function(tree, transformValDefs(vparams), transform(body))
+          treeCopy.Function(tree, transformValDefs(vparams), transform(body))
         }
       case Assign(lhs, rhs) =>
-        copy.Assign(tree, transform(lhs), transform(rhs))
+        treeCopy.Assign(tree, transform(lhs), transform(rhs))
+      case AssignOrNamedArg(lhs, rhs) =>
+        treeCopy.AssignOrNamedArg(tree, transform(lhs), transform(rhs))
       case If(cond, thenp, elsep) =>
-        copy.If(tree, transform(cond), transform(thenp), transform(elsep))
+        treeCopy.If(tree, transform(cond), transform(thenp), transform(elsep))
       case Match(selector, cases) =>
-        copy.Match(tree, transform(selector), transformCaseDefs(cases))
+        treeCopy.Match(tree, transform(selector), transformCaseDefs(cases))
       case Return(expr) =>
-        copy.Return(tree, transform(expr))
+        treeCopy.Return(tree, transform(expr))
       case Try(block, catches, finalizer) =>
-        copy.Try(tree, transform(block), transformCaseDefs(catches), transform(finalizer))
+        treeCopy.Try(tree, transform(block), transformCaseDefs(catches), transform(finalizer))
       case Throw(expr) =>
-        copy.Throw(tree, transform(expr))
+        treeCopy.Throw(tree, transform(expr))
       case New(tpt) =>
-        copy.New(tree, transform(tpt))
+        treeCopy.New(tree, transform(tpt))
       case Typed(expr, tpt) =>
-        copy.Typed(tree, transform(expr), transform(tpt))
+        treeCopy.Typed(tree, transform(expr), transform(tpt))
       case TypeApply(fun, args) =>
-        copy.TypeApply(tree, transform(fun), transformTrees(args))
+        treeCopy.TypeApply(tree, transform(fun), transformTrees(args))
       case Apply(fun, args) =>
-        copy.Apply(tree, transform(fun), transformTrees(args))
+        treeCopy.Apply(tree, transform(fun), transformTrees(args))
       case ApplyDynamic(qual, args) =>
-        copy.ApplyDynamic(tree, transform(qual), transformTrees(args))
+        treeCopy.ApplyDynamic(tree, transform(qual), transformTrees(args))
       case Super(qual, mix) =>
-        copy.Super(tree, qual, mix)
+        treeCopy.Super(tree, qual, mix)
       case This(qual) =>
-        copy.This(tree, qual)
+        treeCopy.This(tree, qual)
       case Select(qualifier, selector) =>
-        copy.Select(tree, transform(qualifier), selector)
+        treeCopy.Select(tree, transform(qualifier), selector)
       case Ident(name) =>
-        copy.Ident(tree, name)
+        treeCopy.Ident(tree, name)
       case Literal(value) =>
-        copy.Literal(tree, value)
+        treeCopy.Literal(tree, value)
       case TypeTree() =>
-        copy.TypeTree(tree)
+        treeCopy.TypeTree(tree)
+      case TypeTreeWithDeferredRefCheck() =>
+        treeCopy.TypeTreeWithDeferredRefCheck(tree)
       case Annotated(annot, arg) =>
-        copy.Annotated(tree, transform(annot).asInstanceOf[Annotation], transform(arg))
+        treeCopy.Annotated(tree, transform(annot), transform(arg))
       case SingletonTypeTree(ref) =>
-        copy.SingletonTypeTree(tree, transform(ref))
+        treeCopy.SingletonTypeTree(tree, transform(ref))
       case SelectFromTypeTree(qualifier, selector) =>
-        copy.SelectFromTypeTree(tree, transform(qualifier), selector)
+        treeCopy.SelectFromTypeTree(tree, transform(qualifier), selector)
       case CompoundTypeTree(templ) =>
-        copy.CompoundTypeTree(tree, transformTemplate(templ))
+        treeCopy.CompoundTypeTree(tree, transformTemplate(templ))
       case AppliedTypeTree(tpt, args) =>
-        copy.AppliedTypeTree(tree, transform(tpt), transformTrees(args))
+        treeCopy.AppliedTypeTree(tree, transform(tpt), transformTrees(args))
       case TypeBoundsTree(lo, hi) =>
-        copy.TypeBoundsTree(tree, transform(lo), transform(hi)) 
+        treeCopy.TypeBoundsTree(tree, transform(lo), transform(hi)) 
       case ExistentialTypeTree(tpt, whereClauses) =>
-        copy.ExistentialTypeTree(tree, transform(tpt), transformTrees(whereClauses))
-      case tree : StubTree => 
-        tree.symbol = NoSymbol
-        tree.tpe = null
-        tree
+        treeCopy.ExistentialTypeTree(tree, transform(tpt), transformTrees(whereClauses))
+      case SelectFromArray(qualifier, selector, erasure) =>
+        treeCopy.SelectFromArray(tree, transform(qualifier), selector, erasure)
     }
 
     def transformTrees(trees: List[Tree]): List[Tree] =
-        List.mapConserve(trees)(transform)
+        trees mapConserve (transform(_))
     def transformTemplate(tree: Template): Template =
       transform(tree: Tree).asInstanceOf[Template]
     def transformTypeDefs(trees: List[TypeDef]): List[TypeDef] =
-      List.mapConserve(trees)(tree => transform(tree).asInstanceOf[TypeDef])
+      trees mapConserve (tree => transform(tree).asInstanceOf[TypeDef])
     def transformValDef(tree: ValDef): ValDef =
       if (tree.isEmpty) tree else transform(tree).asInstanceOf[ValDef]
     def transformValDefs(trees: List[ValDef]): List[ValDef] =
-      List.mapConserve(trees)(transformValDef)
+      trees mapConserve (transformValDef(_))
     def transformValDefss(treess: List[List[ValDef]]): List[List[ValDef]] =
-      List.mapConserve(treess)(transformValDefs)
+      treess mapConserve (transformValDefs(_))
     def transformCaseDefs(trees: List[CaseDef]): List[CaseDef] =
-      List.mapConserve(trees)(tree => transform(tree).asInstanceOf[CaseDef])
+      trees mapConserve (tree => transform(tree).asInstanceOf[CaseDef])
     def transformIdents(trees: List[Ident]): List[Ident] =
-      List.mapConserve(trees)(tree => transform(tree).asInstanceOf[Ident])
+      trees mapConserve (tree => transform(tree).asInstanceOf[Ident])
     def transformStats(stats: List[Tree], exprOwner: Symbol): List[Tree] =
-      List.mapConserve(stats)(stat =>
+      stats mapConserve (stat =>
         if (exprOwner != currentOwner && stat.isTerm) atOwner(exprOwner)(transform(stat))
         else transform(stat)) filter (EmptyTree !=)
     def transformUnit(unit: CompilationUnit) { unit.body = transform(unit.body) }
+    def transformModifiers(mods: Modifiers): Modifiers =
+      Modifiers(mods.flags, mods.privateWithin, transformTrees(mods.annotations), mods.positions)
 
     def atOwner[A](owner: Symbol)(trans: => A): A = {
       val prevOwner = currentOwner
@@ -1486,140 +879,53 @@ trait Trees {
       result
     }
   }
-
-  class Traverser {
-    protected var currentOwner: Symbol = definitions.RootClass
-    def traverse(tree: Tree): Unit =  tree match {
-      case EmptyTree =>
-        ;
-      case PackageDef(name, stats) =>
-        atOwner(tree.symbol.moduleClass) {
-          traverseTrees(stats)
-        }
-      case ClassDef(mods, name, tparams, impl) =>
-        atOwner(tree.symbol) {
-          traverseTrees(mods.annotations); traverseTrees(tparams); traverse(impl)
-        }
-      case ModuleDef(mods, name, impl) =>
-        atOwner(tree.symbol.moduleClass) {
-          traverseTrees(mods.annotations); traverse(impl)
-        }
-      case ValDef(mods, name, tpt, rhs) =>
-        atOwner(tree.symbol) {
-          traverseTrees(mods.annotations); traverse(tpt); traverse(rhs)
-        }
-      case DefDef(mods, name, tparams, vparamss, tpt, rhs) =>
-        atOwner(tree.symbol) {
-          traverseTrees(mods.annotations); traverseTrees(tparams); traverseTreess(vparamss); traverse(tpt); traverse(rhs)
-        }
-      case TypeDef(mods, name, tparams, rhs) =>
-        atOwner(tree.symbol) {
-          traverseTrees(mods.annotations); traverseTrees(tparams); traverse(rhs)
-        }
-      case LabelDef(name, params, rhs) =>
-        traverseTrees(params); traverse(rhs)
-      case Import(expr, selectors) =>
-        traverse(expr)
-      case Annotation(constr, elements) =>
-        traverse(constr); traverseTrees(elements)
-      case Annotated(annot, arg) =>
-        traverse(annot); traverse(arg)
+  
+  class Traverser extends super.Traverser {
+    /** Compiler specific tree types are handled here: the remainder are in
+     *  the library's abstract tree traverser.
+     */
+    override def traverse(tree: Tree): Unit = tree match {
+      case AssignOrNamedArg(lhs, rhs) =>
+        traverse(lhs); traverse(rhs)
       case DocDef(comment, definition) =>
         traverse(definition) 
-      case Template(parents, self, body) =>
-        traverseTrees(parents)
-        if (!self.isEmpty) traverse(self)
-        traverseStats(body, tree.symbol)
-      case Block(stats, expr) =>
-        traverseTrees(stats); traverse(expr)
-      case CaseDef(pat, guard, body) =>
-        traverse(pat); traverse(guard); traverse(body)
-      case Sequence(trees) =>
-        traverseTrees(trees) 
-      case Alternative(trees) =>
-        traverseTrees(trees)
-      case Star(elem) =>
-        traverse(elem)
-      case Bind(name, body) =>
-        traverse(body)
-      case UnApply(fun, args) =>
-        traverse(fun); traverseTrees(args)
-      case ArrayValue(elemtpt, trees) =>
-        traverse(elemtpt); traverseTrees(trees)
-      case Function(vparams, body) =>
-        atOwner(tree.symbol) {
-          traverseTrees(vparams); traverse(body)
-        }
-      case Assign(lhs, rhs) =>
-        traverse(lhs); traverse(rhs)
-      case If(cond, thenp, elsep) =>
-        traverse(cond); traverse(thenp); traverse(elsep)
-      case Match(selector, cases) =>
-        traverse(selector); traverseTrees(cases)
-      case Return(expr) =>
-        traverse(expr)
-      case Try(block, catches, finalizer) =>
-        traverse(block); traverseTrees(catches); traverse(finalizer)
-      case Throw(expr) =>
-        traverse(expr)
-      case New(tpt) =>
-        traverse(tpt)
-      case Typed(expr, tpt) =>
-        traverse(expr); traverse(tpt)
-      case TypeApply(fun, args) =>
-        traverse(fun); traverseTrees(args)
-      case Apply(fun, args) =>
-        traverse(fun); traverseTrees(args)
-      case ApplyDynamic(qual, args) =>
-        traverse(qual); traverseTrees(args)
-      case Super(_, _) =>
-        ;
-      case This(_) =>
-        ;
-      case Select(qualifier, selector) =>
-        traverse(qualifier)
-      case Ident(_) =>
-        ;
-      case Literal(_) =>
-        ;
-      case TypeTree() =>
-        ;
-      case SingletonTypeTree(ref) =>
-        traverse(ref)
-      case SelectFromTypeTree(qualifier, selector) =>
-        traverse(qualifier)
-      case CompoundTypeTree(templ) =>
-        traverse(templ)
-      case AppliedTypeTree(tpt, args) =>
-        traverse(tpt); traverseTrees(args)
-      case TypeBoundsTree(lo, hi) =>
-        traverse(lo); traverse(hi)
-      case ExistentialTypeTree(tpt, whereClauses) =>
-        traverse(tpt); traverseTrees(whereClauses)
-      case tree : StubTree =>
-    }
-
-    def traverseTrees(trees: List[Tree]) {
-      trees foreach traverse
+      case Parens(ts) =>
+        traverseTrees(ts)
+      case TypeTreeWithDeferredRefCheck() => // TODO: should we traverse the wrapped tree?
+      // (and rewrap the result? how to update the deferred check? would need to store wrapped tree instead of returning it from check)
+      case _ => super.traverse(tree)
     }
-    def traverseTreess(treess: List[List[Tree]]) {
-      treess foreach traverseTrees
-    }
-    def traverseStats(stats: List[Tree], exprOwner: Symbol) {
+    
+    /** The abstract traverser is not aware of Tree.isTerm, so we override this one.
+     */
+    override def traverseStats(stats: List[Tree], exprOwner: Symbol) {
       stats foreach (stat =>
         if (exprOwner != currentOwner && stat.isTerm) atOwner(exprOwner)(traverse(stat))
-        else traverse(stat))
+        else traverse(stat)
+      )
     }
+    
+    /** Leave apply available in the generic traverser to do something else.
+     */
     def apply[T <: Tree](tree: T): T = { traverse(tree); tree }
+  }
 
-    def atOwner(owner: Symbol)(traverse: => Unit) {
-      val prevOwner = currentOwner
-      currentOwner = owner
-      traverse
-      currentOwner = prevOwner
+  private lazy val duplicator = new Transformer {
+    override val treeCopy = new StrictTreeCopier
+    override def transform(t: Tree) = {
+      val t1 = super.transform(t)
+      if ((t1 ne t) && t1.pos.isRange) t1 setPos t.pos.focus
+      t1
     }
   }
 
+  private class ShallowDuplicator(orig: Tree) extends Transformer {
+    override val treeCopy = new StrictTreeCopier
+    override def transform(tree: Tree) =
+      if (tree eq orig) super.transform(tree)
+      else tree
+  }
+
   class TreeSubstituter(from: List[Symbol], to: List[Tree]) extends Transformer {
     override def transform(tree: Tree): Tree = tree match {
       case Ident(_) =>
@@ -1633,28 +939,52 @@ trait Trees {
     }
   }
 
-  class TreeTypeSubstituter(from: List[Symbol], to: List[Type]) extends Traverser {
+  class TreeTypeSubstituter(val from: List[Symbol], val to: List[Type]) extends Traverser {
     val typeSubst = new SubstTypeMap(from, to)
     override def traverse(tree: Tree) {
       if (tree.tpe ne null) tree.tpe = typeSubst(tree.tpe)
+      if (tree.isDef) {
+        val sym = tree.symbol
+        val info1 = typeSubst(sym.info)
+        if (info1 ne sym.info) sym.setInfo(info1)
+      }
       super.traverse(tree)
     }
     override def apply[T <: Tree](tree: T): T = super.apply(tree.duplicate)
+    override def toString() = "TreeTypeSubstituter("+from+","+to+")"
   }
 
-  class TreeSymSubstituter(from: List[Symbol], to: List[Symbol]) extends Traverser {
+  lazy val EmptyTreeTypeSubstituter = new TreeTypeSubstituter(List(), List())
+
+  /** Substitute symbols in 'from' with symbols in 'to'. Returns a new
+   *  tree using the new symbols and whose Ident and Select nodes are
+   *  name-consistent with the new symbols. 
+   */
+  class TreeSymSubstituter(from: List[Symbol], to: List[Symbol]) extends Transformer {
     val symSubst = new SubstSymMap(from, to)
-    override def traverse(tree: Tree) {
+    override def transform(tree: Tree): Tree = {
       def subst(from: List[Symbol], to: List[Symbol]) {
         if (!from.isEmpty)
           if (tree.symbol == from.head) tree setSymbol to.head
           else subst(from.tail, to.tail)
       }
+
       if (tree.tpe ne null) tree.tpe = symSubst(tree.tpe)
-      if (tree.hasSymbol) subst(from, to)
-      super.traverse(tree)
+      if (tree.hasSymbol) {
+        subst(from, to)
+        tree match {
+          case Ident(name0) if tree.symbol != NoSymbol =>
+            treeCopy.Ident(tree, tree.symbol.name)
+          case Select(qual, name0) =>
+            treeCopy.Select(tree, transform(qual), tree.symbol.name)
+          case _ =>
+            super.transform(tree)
+        }
+      } else
+        super.transform(tree)
     }
-    override def apply[T <: Tree](tree: T): T = super.apply(tree.duplicate)
+    def apply[T <: Tree](tree: T): T = transform(tree).asInstanceOf[T]
+    override def toString() = "TreeSymSubstituter("+from+","+to+")"
   }
 
   class ChangeOwnerTraverser(val oldowner: Symbol, val newowner: Symbol) extends Traverser {
@@ -1681,11 +1011,12 @@ trait Trees {
         super.traverse(t)
       }
     }
-    def atPos[T <: Tree](pos: Position)(tree: T): T = {
-      this.pos = pos
-      traverse(tree)
-      tree
-    }
+  }
+
+  def atPos[T <: Tree](pos: Position)(tree: T): T = {
+    posAssigner.pos = pos
+    posAssigner.traverse(tree)
+    tree
   }
 
   class ForeachTreeTraverser(f: Tree => Unit) extends Traverser {
@@ -1723,7 +1054,8 @@ trait Trees {
 
   /** resets symbol and tpe fields in a tree, @see ResetAttrsTraverse
    */
-  def resetAttrs[A<:Tree](x:A):A = {new ResetAttrsTraverser().traverse(x); x}
+  def resetAllAttrs[A<:Tree](x:A): A = { new ResetAttrsTraverser().traverse(x); x }
+  def resetLocalAttrs[A<:Tree](x:A): A = { new ResetLocalAttrsTraverser().traverse(x); x }
   
   /** A traverser which resets symbol and tpe fields of all nodes in a given tree
    *  except for (1) TypeTree nodes, whose <code>.tpe</code> field is kept and
@@ -1732,36 +1064,46 @@ trait Trees {
    *
    *  (bq:) This traverser has mutable state and should be discarded after use
    */
-  class ResetAttrsTraverser extends Traverser {
+  private class ResetAttrsTraverser extends Traverser {
+    protected def isLocal(sym: Symbol): Boolean = true
+    protected def resetDef(tree: Tree) {
+      tree.symbol = NoSymbol
+    }
+    override def traverse(tree: Tree): Unit = {
+      tree match {
+        case _: DefTree | Function(_, _) | Template(_, _, _) =>
+          resetDef(tree)
+        case _ =>
+          if (tree.hasSymbol && isLocal(tree.symbol)) tree.symbol = NoSymbol
+      }
+      tree match {
+        case tpt: TypeTree =>
+          if (tpt.wasEmpty) tree.tpe = null
+        case EmptyTree =>
+          ;
+        case _ =>
+          tree.tpe = null
+      }
+      super.traverse(tree)
+    }
+  }
+
+  private class ResetLocalAttrsTraverser extends ResetAttrsTraverser {
     private val erasedSyms = new HashSet[Symbol](8)
+    override protected def isLocal(sym: Symbol) = 
+      erasedSyms contains sym
+    override protected def resetDef(tree: Tree) {
+      erasedSyms addEntry tree.symbol
+      super.resetDef(tree)
+    }
     override def traverse(tree: Tree): Unit = tree match {
-      case EmptyTree | TypeTree() =>
-        ;
       case Template(parents, self, body) =>
-        tree.symbol = NoSymbol
-        tree.tpe = null
         for (stat <- body)
           if (stat.isDef) erasedSyms.addEntry(stat.symbol)
         super.traverse(tree)
-      case _: DefTree =>
-        erasedSyms.addEntry(tree.symbol)
-        tree.symbol = NoSymbol
-        tree.tpe = null
-        super.traverse(tree)
       case _ =>
-        if (tree.hasSymbol && erasedSyms.contains(tree.symbol)) tree.symbol = NoSymbol
-        tree.tpe = null
         super.traverse(tree)
     }
   }
-  /* hook to memoize trees in IDE */
-  trait TreeKind {
-    def isType : Boolean
-    def isTerm : Boolean
-    def isDef : Boolean
-    def hasSymbol : Boolean
-    def isTop : Boolean
-  }
-    
 }
 
diff --git a/src/compiler/scala/tools/nsc/ast/parser/BracePair.scala b/src/compiler/scala/tools/nsc/ast/parser/BracePair.scala
new file mode 100644
index 0000000..0eb583f
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/ast/parser/BracePair.scala
@@ -0,0 +1,17 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
+ * @author  Martin Odersky
+ */
+package scala.tools.nsc
+package ast.parser
+
+/** A descriptor for a matching pair of braces.
+ *  @param loff    The offset of the opening brace (-1 means missing)
+ *  @param lindent The indentation depth of the line of the opening brace (-1 means missing)
+ *  @param roff    The offset of the closing brace (-1 means missing)
+ *  @param rindent The indentation depth of the line of the closing brace (-1 means missing)
+ *  @param nested The brace pairs nested in this one
+ */
+case class BracePair(loff: Int, lindent: Int, roff: Int, rindent: Int, nested: List[BracePair])
+
+  
diff --git a/src/compiler/scala/tools/nsc/ast/parser/BracePatch.scala b/src/compiler/scala/tools/nsc/ast/parser/BracePatch.scala
new file mode 100644
index 0000000..9c39049
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/ast/parser/BracePatch.scala
@@ -0,0 +1,13 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
+ * @author  Martin Odersky
+ */
+package scala.tools.nsc
+package ast.parser
+
+/** A patch that postulates that a brace needs to be inserted or deleted at a given position.
+ *  @param off  The offset where the brace needs to be inserted or deleted 
+ *  @param inserted  If true, brace needs to be inserted, otherwise brace needs to be deleted.
+ */
+case class BracePatch(off: Int, inserted: Boolean) 
+extends Patch(off, if (inserted) Insertion("{") else Deletion(1))
\ No newline at end of file
diff --git a/src/compiler/scala/tools/nsc/ast/parser/Change.scala b/src/compiler/scala/tools/nsc/ast/parser/Change.scala
new file mode 100644
index 0000000..12f189a
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/ast/parser/Change.scala
@@ -0,0 +1,10 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
+ * @author  Martin Odersky
+ */
+package scala.tools.nsc.ast.parser
+
+abstract class Change
+case class Insertion(text: String) extends Change
+case class Deletion(nchars: Int) extends Change
+
diff --git a/src/compiler/scala/tools/nsc/ast/parser/MarkupParsers.scala b/src/compiler/scala/tools/nsc/ast/parser/MarkupParsers.scala
index a1d6539..26424f1 100644
--- a/src/compiler/scala/tools/nsc/ast/parser/MarkupParsers.scala
+++ b/src/compiler/scala/tools/nsc/ast/parser/MarkupParsers.scala
@@ -1,75 +1,109 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author Burak Emir
  */
-// $Id: MarkupParsers.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.tools.nsc.ast.parser
+package scala.tools.nsc
+package ast.parser
 
 import scala.collection.mutable
-import scala.tools.nsc.util.{Position,NoPosition,SourceFile}
-import scala.xml.{Text, TextBuffer}
-import SourceFile.{SU,LF}
+import mutable.{ Buffer, ArrayBuffer, ListBuffer, HashMap }
+import scala.util.control.ControlThrowable
+import scala.tools.nsc.util.{SourceFile,CharArrayReader}
+import scala.xml.{ Text, TextBuffer }
+import scala.xml.Utility.{ isNameStart, isNameChar, isSpace }
+import util.Chars.{ SU, LF }
+
+// XXX/Note: many/most of the functions in here are almost direct cut and pastes
+// from another file - scala.xml.parsing.MarkupParser, it looks like.
+// (It was like that when I got here.) They used to be commented "[Duplicate]" but
+// since approximately all of them were, I snipped it as noise.  As far as I can
+// tell this wasn't for any particularly good reason, but slightly different
+// compiler and library parser interfaces meant it would take some setup.
+//
+// I rewrote most of these, but not as yet the library versions: so if you are
+// tempted to touch any of these, please be aware of that situation and try not
+// to let it get any worse.  -- paulp
 
 /** This trait ...
  *
  *  @author  Burak Emir
  *  @version 1.0
  */
-trait MarkupParsers {self: Parsers =>
-  case object MissingEndTagException extends RuntimeException {
+trait MarkupParsers 
+{
+  self: Parsers =>
+  
+  case object MissingEndTagControl extends ControlThrowable {
     override def getMessage = "start tag was here: "
   }
 
-  case object ConfusedAboutBracesException extends RuntimeException {
+  case object ConfusedAboutBracesControl extends ControlThrowable {
     override def getMessage = " I encountered a '}' where I didn't expect one, maybe this tag isn't closed <"
   }
 
-  case object TruncatedXML extends RuntimeException {
+  case object TruncatedXMLControl extends ControlThrowable {
     override def getMessage = "input ended while parsing XML"
   }
 
   import global._
-  //import posAssigner.atPos
 
-  class MarkupParser(parser: UnitParser, presWS: Boolean) /*with scala.xml.parsing.MarkupParser[Tree,Tree] */{
-
-    import Tokens.{EMPTY, LBRACE, RBRACE}
-    import parser.i2p
-
-    final val preserveWS = presWS
-    var input : ScannerInput = _
-
-    import parser.{symbXMLBuilder => handle}
-
-    def pos : Int = input.offset
+  class MarkupParser(parser: UnitParser, final val preserveWS: Boolean) extends scala.xml.parsing.MarkupParserCommon {
+
+    import Tokens.{ EMPTY, LBRACE, RBRACE }
+    
+    type PositionType = Position
+    type InputType    = CharArrayReader
+    type ElementType  = Tree
+    type AttributesType = mutable.Map[String, Tree]
+    type NamespaceType = Any  // namespaces ignored
+    
+    def mkAttributes(name: String, other: NamespaceType): AttributesType = xAttributes
+    
+    val eof = false
+    
+    def truncatedError(msg: String): Nothing = throw TruncatedXMLControl
+    def xHandleError(that: Char, msg: String) =
+      if (ch == SU) throw TruncatedXMLControl
+      else reportSyntaxError(msg)
+
+    var input : CharArrayReader = _
+    def lookahead(): BufferedIterator[Char] =
+      (input.buf drop input.charOffset).iterator.buffered
+
+    import parser.{ symbXMLBuilder => handle, o2p, r2p }
+
+    def curOffset : Int = input.charOffset - 1
     var tmppos : Position = NoPosition
-    def ch = input.head
+    def ch = input.ch
     /** this method assign the next character to ch and advances in input */
-    def nextch = input.next // { s.in.next; /*s.xNext;*/ ch = s.in.ch ; pos = s.in.cpos }
-
-    /*[Duplicate]*/ var xEmbeddedBlock = false
-
-    /** munch expected XML token, report syntax error for unexpected.
-     *
-     *  @param that ...
-     */
-    /*[Duplicate]*/ def xToken(that: Char) {
-      if (ch == that) nextch
-      else if (ch == SU)
-        throw TruncatedXML
-      else reportSyntaxError("'" + that + "' expected instead of '" + ch + "'")
+    def nextch = { val result = input.ch; input.nextChar(); result } 
+    def ch_returning_nextch = nextch
+    
+    def mkProcInstr(position: Position, name: String, text: String): Tree =
+      parser.symbXMLBuilder.procInstr(position, name, text)
+
+    var xEmbeddedBlock = false
+
+    private var debugLastStartElement = new mutable.Stack[(Int, String)]
+    private def debugLastPos = debugLastStartElement.top._1
+    private def debugLastElem = debugLastStartElement.top._2
+    
+    private def errorBraces() = {
+      reportSyntaxError("in XML content, please use '}}' to express '}'")
+      throw ConfusedAboutBracesControl
+    }
+    def errorNoEnd(tag: String) = {
+      reportSyntaxError("expected closing tag of " + tag)
+      throw MissingEndTagControl
     }
-
-    var debugLastStartElement = new mutable.Stack[(Int, String)]
 
     /** checks whether next character starts a Scala block, if yes, skip it.
      * @return true if next character starts a scala block 
      */
-    /*[Duplicate]*/ def xCheckEmbeddedBlock: Boolean = {
+    def xCheckEmbeddedBlock: Boolean = {
       // attentions, side-effect, used in xText
       xEmbeddedBlock = (ch == '{') && { nextch; (ch != '{') }
-      //Console.println("pos = "+pos+" xEmbeddedBlock returns "+xEmbeddedBlock)
       xEmbeddedBlock
     }
 
@@ -79,256 +113,105 @@ trait MarkupParsers {self: Parsers =>
      *                      | `"` { _ } `"`
      *                      | `{` scalablock `}`
      */
-    /*[Duplicate]*/ def xAttributes = {
-      var aMap = new mutable.HashMap[String, Tree]()
-      while (xml.Parsing.isNameStart(ch)) {
+    def xAttributes = {
+      val aMap = new HashMap[String, Tree]()
+      
+      while (isNameStart(ch)) {
+        val start = curOffset
         val key = xName
         xEQ
         val delim = ch
-        val pos1 = pos
-        val value: /* AttribValue[*/Tree/*]*/ = ch match {
+        val mid = curOffset
+        val value: Tree = ch match {
           case '"' | '\'' =>
-            nextch
-            val tmp = xAttributeValue(delim)
-            nextch
-            try {
-              handle.parseAttribute(pos1, tmp)
-            } catch {
-              case e => 
-                reportSyntaxError("error parsing attribute value")
-                parser.errorTermTree
+            val tmp = xAttributeValue(ch_returning_nextch)
+            
+            try handle.parseAttribute(r2p(start, mid, curOffset), tmp)
+            catch {
+              case e: RuntimeException => 
+                errorAndResult("error parsing attribute value", parser.errorTermTree)
             }
           
           case '{'  =>
             nextch
             xEmbeddedExpr
           case SU =>
-            throw TruncatedXML
+            throw TruncatedXMLControl
           case _ =>
-            reportSyntaxError("' or \" delimited attribute value" +
-                              " or '{' scala-expr '}' expected" )
-            Literal(Constant("<syntax-error>"))
+            errorAndResult("' or \" delimited attribute value or '{' scala-expr '}' expected", Literal(Constant("<syntax-error>")))
         }
         // well-formedness constraint: unique attribute names
-        if (aMap.contains(key)) {
-          reportSyntaxError( "attribute "+key+" may only be defined once" )
-        }
-        aMap.update(key, value)
-        if ((ch != '/') && (ch != '>')) {
+        if (aMap contains key)
+          reportSyntaxError("attribute %s may only be defined once" format key)
+
+        aMap(key) = value
+        if (ch != '/' && ch != '>')
           xSpace
-        }
       }
       aMap
     }
 
-    /** attribute value, terminated by either ' or ". value may not contain <.
-     *  @param endch either ' or "
-     */
-    /*[Duplicate]*/ def xAttributeValue(endCh: Char): String = {
-      val buf = new StringBuilder      
-      while (ch != endCh) {
-        if (ch == SU)
-          throw TruncatedXML
-        buf append nextch
-      }
-      val str = buf.toString()
-      
-      // @todo: normalize attribute value
-      // well-formedness constraint
-      if (str.indexOf('<') != -1) {
-        reportSyntaxError( "'<' not allowed in attrib value" ); ""
-      } else {
-        str
-      }
-    }
-
-    /** parse a start or empty tag.
-     *  [40] STag         ::= '<' Name { S Attribute } [S] 
-     *  [44] EmptyElemTag ::= '<' Name { S Attribute } [S] 
-     */
-    /*[Duplicate]*/ def xTag: (String, mutable.Map[String, Tree]) = {
-      val elemName = xName
-      xSpaceOpt
-      val aMap =
-        if (xml.Parsing.isNameStart(ch)) xAttributes
-        else new mutable.HashMap[String, Tree]()
-      (elemName, aMap)
-    }
-
-    /** [42]  '<' xmlEndTag ::=  '<' '/' Name S? '>'
-     */
-    /*[Duplicate]*/ def xEndTag(startName: String) {
-      xToken('/')
-      val endName = xName
-      if (endName != startName) {
-        reportSyntaxError("expected closing tag of " + startName)
-        throw MissingEndTagException
-      }
-      xSpaceOpt
-      xToken('>')
-    }
-
     /** '<! CharData ::= [CDATA[ ( {char} - {char}"]]>"{char} ) ']]>'
      *
      * see [15]
      */
-    /*[Duplicate]*/ def xCharData: Tree = {
-      xToken('[')
-      xToken('C')
-      xToken('D')
-      xToken('A')
-      xToken('T')
-      xToken('A')
-      xToken('[')
-      val pos1 = pos
-      val sb: StringBuilder = new StringBuilder()
-      while (true) {
-        if (ch==']' &&
-           { sb.append(ch); nextch; ch == ']' } &&
-           { sb.append(ch); nextch; ch == '>' }) {
-          sb.length = sb.length - 2
-          nextch
-          return handle.charData(pos1, sb.toString())
-        } else if (ch == SU)
-          throw TruncatedXML
-        else
-          sb.append(ch)
-        nextch
-      }
-      Predef.error("this cannot happen")
+    def xCharData: Tree = {
+      val start = curOffset
+      xToken("[CDATA[")
+      val mid = curOffset
+      xTakeUntil(handle.charData, () => r2p(start, mid, curOffset), "]]>")
     }
 
     def xUnparsed: Tree = {
-      val pos1 = pos
-      val sb: StringBuilder = new StringBuilder()
-      while (true) {
-        if (ch=='<' &&
-           { sb.append(ch); nextch; ch == '/' } &&
-           { sb.append(ch); nextch; ch == 'x' } &&
-           { sb.append(ch); nextch; ch == 'm' } &&
-           { sb.append(ch); nextch; ch == 'l' } &&
-           { sb.append(ch); nextch; ch == ':' } &&
-           { sb.append(ch); nextch; ch == 'u' } &&
-           { sb.append(ch); nextch; ch == 'n' } &&
-           { sb.append(ch); nextch; ch == 'p' } &&
-           { sb.append(ch); nextch; ch == 'a' } &&
-           { sb.append(ch); nextch; ch == 'r' } &&
-           { sb.append(ch); nextch; ch == 's' } &&
-           { sb.append(ch); nextch; ch == 'e' } &&
-           { sb.append(ch); nextch; ch == 'd' } &&
-           { sb.append(ch); nextch; ch == '>' }) {
-          sb.length = sb.length - "</xml:unparsed".length
-          nextch
-          return handle.unparsed(pos1, sb.toString())
-        } else if (ch == SU) {
-          throw TruncatedXML
-        } else sb.append(ch)
-        nextch
-      }
-      Predef.error("this cannot happen")
-    }
-
-    /** CharRef ::= "&#" '0'..'9' {'0'..'9'} ";"
-     *            | "&#x" '0'..'9'|'A'..'F'|'a'..'f' { hexdigit } ";"
-     *
-     * see [66]
-     */
-    /*[Duplicate]*/ def xCharRef: String = {
-      val hex = (ch == 'x') && { nextch; true }
-      val base = if (hex) 16 else 10
-      var i = 0
-      while (ch != ';') {
-        ch match {
-          case '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' =>
-            i = i * base + ch.asDigit
-          case 'a' | 'b' | 'c' | 'd' | 'e' | 'f'
-             | 'A' | 'B' | 'C' | 'D' | 'E' | 'F' =>
-            if (!hex)
-              reportSyntaxError("hex char not allowed in decimal char ref\n"
-                           +"Did you mean to write &#x ?");
-            else
-              i = i * base + ch.asDigit
-          case SU =>
-            throw TruncatedXML
-          case _ =>
-            reportSyntaxError("character '"+ch+"' not allowed in char ref")
-        }
-        nextch
-      }
-      new String(Array(i.asInstanceOf[Char]))
+      val start = curOffset
+      xTakeUntil(handle.unparsed, () => r2p(start, start, curOffset), "</xml:unparsed>")
     }
 
     /** Comment ::= '<!--' ((Char - '-') | ('-' (Char - '-')))* '-->'
      *
      * see [15]
      */
-    /*[Duplicate]*/ def xComment: Tree = {
-      val sb: StringBuilder = new StringBuilder()
-      xToken('-')
-      xToken('-')
-      while (true) {
-        if (ch=='-'  && { sb.append(ch); nextch; ch == '-' }) {
-          sb.length = sb.length - 1
-          nextch
-          xToken('>')
-          return handle.comment(pos, sb.toString())
-        } else if (ch == SU) {
-          throw TruncatedXML
-        } else sb.append(ch)
-        nextch
-      }
-      Predef.error("this cannot happen")
+    def xComment: Tree = {
+      val start = curOffset - 2   // Rewinding to include "<!"
+      xToken("--")
+      xTakeUntil(handle.comment, () => r2p(start, start, curOffset), "-->")
     }
 
-    /**
-     *  @param pos ...
-     *  @param ts  ...
-     *  @param txt ...
-     */
-    /*[Duplicate]*/ def appendText(pos: Position, ts: mutable.Buffer[Tree],
-                                   txt: String) {
-      if (!preserveWS) {
-        for (t <- TextBuffer.fromString(txt).toText) {
-          ts.append(handle.text(pos, t.text))
-        }
-      }
-      else
-        ts.append( handle.text(pos, txt))
+    def appendText(pos: Position, ts: Buffer[Tree], txt: String) {
+      val toAppend =
+        if (preserveWS) Seq(txt)
+        else TextBuffer.fromString(txt).toText map (_.text)
+      
+      toAppend foreach (t => ts append handle.text(pos, t))
     }
 
-    /** adds entity/character to to ts as side-effect 
+    /** adds entity/character to ts as side-effect 
      *  @precond ch == '&'
      */
-    def content_AMP(ts: mutable.ArrayBuffer[Tree]) {
+    def content_AMP(ts: ArrayBuffer[Tree]) {
       nextch
-      ch match {
+      val toAppend = ch match {
         case '#' => // CharacterRef
           nextch
           val theChar = handle.text(tmppos, xCharRef)
           xToken(';')
-          ts.append(theChar)
-        case _ => // EntityRef
+          theChar
+        case _ =>   // EntityRef
           val n = xName
           xToken(';')
-          ts.append(handle.entityRef(tmppos, n))
+          handle.entityRef(tmppos, n)
       }
+      
+      ts append toAppend
     }
 
     /**
      *  @precond ch == '{'
      *  @postcond: xEmbeddedBlock == false!
      */
-    def content_BRACE(p: Position, ts:mutable.ArrayBuffer[Tree]) {
-      if (xCheckEmbeddedBlock)
-        ts.append(xEmbeddedExpr)
-      else {
-        appendText(p, ts, xText)/*
-        val str = new StringBuilder("{")
-        str.append(xText)
-        nextch
-        appendText(p, ts, str.toString())*/
-      }
-    }
+    def content_BRACE(p: Position, ts: ArrayBuffer[Tree]): Unit =
+      if (xCheckEmbeddedBlock) ts append xEmbeddedExpr
+      else appendText(p, ts, xText)
 
     /** Returns true if it encounters an end tag (without consuming it),
      *  appends trees to ts as side-effect.
@@ -336,383 +219,236 @@ trait MarkupParsers {self: Parsers =>
      *  @param ts ...
      *  @return   ...
      */
-    private def content_LT(ts: mutable.ArrayBuffer[Tree]): Boolean = {
-      ch match {
-        case '/' =>
-          return true               // end tag
-        case '!' =>
-          nextch                    // CDATA or Comment
-          ts.append(if ('[' == ch) xCharData else xComment)
-        case '?' =>                 // PI
-          nextch
-          ts.append(xProcInstr)
-        case _   =>
-          ts.append(element)        // child node
+    private def content_LT(ts: ArrayBuffer[Tree]): Boolean = {
+      if (ch == '/')
+        return true   // end tag
+      
+      val toAppend = ch match {
+        case '!'    => nextch ; if (ch =='[') xCharData else xComment // CDATA or Comment
+        case '?'    => nextch ; xProcInstr                            // PI
+        case _      => element                                        // child node
       }
+      
+      ts append toAppend
       false
     }
 
-    /*[Duplicate]*/ def content: mutable.Buffer[Tree] = {
-      var ts = new mutable.ArrayBuffer[Tree]
-      var exit = false
-      while (!exit) {
+    def content: Buffer[Tree] = {
+      val ts = new ArrayBuffer[Tree]
+      while (true) {
         if (xEmbeddedBlock)
-          ts.append(xEmbeddedExpr)
+          ts append xEmbeddedExpr
         else {
-          tmppos = pos
+          tmppos = o2p(curOffset)
           ch match {
-            case '<' => // end tag, cdata, comment, pi or child node
-              nextch
-              exit = content_LT(ts)
-            case '{' => // either the character '{' or an embedded scala block
-              content_BRACE(tmppos, ts)
-            case '&' => // EntityRef or CharRef 
-              content_AMP(ts)
-            case SU =>
-              exit = true
-            case _ =>  // text content
-              appendText(tmppos, ts, xText)
-              // here xEmbeddedBlock might be true
+            // end tag, cdata, comment, pi or child node
+            case '<'  => nextch ; if (content_LT(ts)) return ts
+            // either the character '{' or an embedded scala block }
+            case '{'  => content_BRACE(tmppos, ts)  // }
+            // EntityRef or CharRef 
+            case '&'  => content_AMP(ts)
+            case SU   => return ts
+            // text content - here xEmbeddedBlock might be true
+            case _    => appendText(tmppos, ts, xText)
           }
         }
       }
-      ts
+      unreachable
     }
 
     /** '<' element ::= xmlTag1 '>'  { xmlExpr | '{' simpleExpr '}' } ETag
      *                | xmlTag1 '/' '>'
      */
-    /*[Duplicate]*/ def element: Tree = {
-      val pos1 = pos
-      val (qname, attrMap) = xTag
+    def element: Tree = {
+      val start = curOffset
+      val (qname, attrMap) = xTag(())
       if (ch == '/') { // empty element
-        xToken('/')
-        xToken('>')
-        handle.element(pos1, qname, attrMap, new mutable.ListBuffer[Tree])
+        xToken("/>")
+        handle.element(r2p(start, start, curOffset), qname, attrMap, new ListBuffer[Tree])
       }
       else { // handle content
         xToken('>')
         if (qname == "xml:unparsed")
           return xUnparsed
 
-        debugLastStartElement.push((pos1, qname))
+        debugLastStartElement.push((start, qname))
         val ts = content
         xEndTag(qname)
         debugLastStartElement.pop
+        val pos = r2p(start, start, curOffset)
         qname match {
-          case "xml:group" => handle.group(pos1, ts)
-          case _ => handle.element(pos1, qname, attrMap, ts)
+          case "xml:group" => handle.group(pos, ts)
+          case _ => handle.element(pos, qname, attrMap, ts)
         }
       }
     }
 
-    /** actually, Name ::= (Letter | '_' | ':') (NameChar)*  but starting with ':' cannot happen
-     *  Name ::= (Letter | '_') (NameChar)*
-     *
-     *  see  [5] of XML 1.0 specification
-     *
-     *  pre-condition:  ch != ':' // assured by definition of XMLSTART token
-     *  post-condition: name does neither start, nor end in ':'
+    /** parse character data.
+     *  precondition: xEmbeddedBlock == false (we are not in a scala block)
      */
-    /*[Duplicate]*/   def xName: String = {
-      if (ch == SU) {
-        throw TruncatedXML
-        reportSyntaxError("name expected, but char '"+ch+"' cannot start a name")
-        return ""
-      }
+    def xText: String = {
+      assert(!xEmbeddedBlock, "internal error: encountered embedded block")
       val buf = new StringBuilder
-      do {
-        buf append nextch        
-      } while (xml.Parsing.isNameChar(ch))
-      if (':' == buf.last) {
-        reportSyntaxError( "name cannot end in ':'" )
-        buf.setLength(buf.length - 1)
+      def done = buf.toString
+      
+      while (ch != SU) {
+        if (ch == '}') {
+          if (charComingAfter(nextch) == '}') nextch
+          else errorBraces
+        }
+        
+        buf append ch
+        nextch
+        if (xCheckEmbeddedBlock || ch == '<' ||  ch == '&')
+          return done
       }
-      val n = buf.toString().intern()
-      //cbuf.length = 0
-      n
+      done
     }
-
-    /** scan [S] '=' [S]*/
-    /*[Duplicate]*/   def xEQ = { xSpaceOpt; xToken('='); xSpaceOpt }
-
-    /** skip optional space S? */
-    /*[Duplicate]*/   def xSpaceOpt = { while (xml.Parsing.isSpace(ch)) { nextch }}
-
-    /** scan [3] S ::= (#x20 | #x9 | #xD | #xA)+ */
-    /*[Duplicate]*/ def xSpace =
-      if (xml.Parsing.isSpace(ch)) { nextch; xSpaceOpt }
-      else if (ch == SU)
-        throw TruncatedXML
-      else reportSyntaxError("whitespace expected")
-
-    /** '<?' ProcInstr ::= Name [S ({Char} - ({Char}'>?' {Char})]'?>'
-     *
-     * see [15]
-     */
-    /*[Duplicate]*/ def xProcInstr: Tree = {
-      val sb: StringBuilder = new StringBuilder()
-      val n = xName
-      if (xml.Parsing.isSpace(ch)) {
-        xSpace
-        while (true) {
-          if (ch == '?' && { sb.append(ch); nextch; ch == '>' }) {
-            sb.length = sb.length - 1
-            nextch
-            return handle.procInstr(tmppos, n, sb.toString)
-          } else 
-            sb.append(ch);
-          nextch
-        }
+    
+    /** Some try/catch/finally logic used by xLiteral and xLiteralPattern.  */
+    private def xLiteralCommon(f: () => Tree, ifTruncated: String => Unit): Tree = {
+      try return f()
+      catch {
+        case c @ TruncatedXMLControl  =>
+          ifTruncated(c.getMessage)
+        case c @ (MissingEndTagControl | ConfusedAboutBracesControl) =>
+          parser.syntaxError(debugLastPos, c.getMessage + debugLastElem + ">")
+        case _: ArrayIndexOutOfBoundsException =>
+          parser.syntaxError(debugLastPos, "missing end tag in XML literal for <%s>" format debugLastElem)
       }
-      xToken('?')
-      xToken('>') 
-      handle.procInstr(tmppos, n, sb.toString)
+      finally parser.in resume Tokens.XMLSTART
+      
+      EmptyTree
     }
-
-    /** parse character data.
-     *  precondition: xEmbeddedBlock == false (we are not in a scala block)
-     */
-    /*[Duplicate]*/ def xText: String = {
-      if (xEmbeddedBlock) Predef.error("internal error: encountered embedded block"); // assert
-      //Console.println("xText ch now "+ch)
-      //if( xCheckEmbeddedBlock ) {
-      //  return ""
-      //} else {
-        var exit = false
-        val buf = new StringBuilder
-        while (!exit && (ch!=SU)) {
-          buf append ch
-          val expectRBRACE = ch == '}'
-          // TODO check for "}}"
-          nextch
-          if (expectRBRACE) {
-            if (ch == '}')
-              nextch
-            else {
-              reportSyntaxError("in XML content, please use '}}' to express '}'")
-              throw ConfusedAboutBracesException
-            }
-          }
-          exit = xCheckEmbeddedBlock ||(ch == '<') || (ch == '&')
-        }
-        val str = buf.toString()
-        //cbuf.length = 0
-        str
-      //}
+      
+    /** Use a lookahead parser to run speculative body, and return the first char afterward. */
+    private def charComingAfter(body: => Unit): Char = {
+      input = input.lookaheadReader
+      body
+      val res = ch
+      input = parser.in
+      res
     }
 
-    //val cbuf = new StringBuilder()
-
-    /** append Unicode character to name buffer*/
-    //private def putChar(c: char) = cbuf.append(c)
-
     /** xLiteral = element { element }
      *  @return Scala representation of this xml literal
-     *  precondition: s.xStartsXML == true
      */
-    def xLiteral: Tree = try {
-      input = parser.in.flush
-      handle.isPattern = false
+    def xLiteral: Tree = xLiteralCommon(
+      () => {
+        input = parser.in
+        handle.isPattern = false
       
-      //val pos = s.currentPos
-      var tree:Tree = null
-      val ts = new mutable.ArrayBuffer[Tree]()
-      tmppos = (pos)    // Iuli: added this line, as it seems content_LT uses tmppos when creating trees
-      assert(nextch == '<')
-      content_LT(ts)
-      //Console.println("xLiteral:ts = "+ts.toList)
-      //lastend = s.in.bp
-      //lastch  = s.in.ch
-      //if (settings.debug.value) {
-      //  Console.println("DEBUG 1: I am getting char '"+ch+"' at lastend "+lastend+" pos = "+pos); // DEBUG 
-      //}
-      val save = input.offset
-      xSpaceOpt
-      // parse more XML ?
-      if (ch == '<') {
-        while (ch == '<') { 
-          nextch
-          ts.append(element)
+        val ts = new ArrayBuffer[Tree]
+        val start = curOffset
+        tmppos = o2p(curOffset)    // Iuli: added this line, as it seems content_LT uses tmppos when creating trees
+        content_LT(ts)
+      
+        // parse more XML ?        
+        if (charComingAfter(xSpaceOpt) == '<') {
           xSpaceOpt
+          while (ch == '<') {
+            nextch
+            ts append element
+            xSpaceOpt
+          }
+          handle.makeXMLseq(r2p(start, start, curOffset), ts)
         }
-        tree = handle.makeXMLseq((pos), ts)
-        parser.in.resume(Tokens.XMLSTART)
-      } else {
-        parser.in.seek(save, Tokens.XMLSTART)
-        assert(ts.length == 1)
-        tree = ts(0)
-      }
-      tree
-    } catch {
-      case c @ TruncatedXML =>
-        parser.incompleteInputError(c.getMessage)
-        parser.in.resume(Tokens.XMLSTART)
-        EmptyTree
-
-      case c @ (MissingEndTagException | ConfusedAboutBracesException) =>
-        parser.syntaxError((debugLastStartElement.top._1):Int,
-                           c.getMessage + debugLastStartElement.top._2+">")
-        parser.in.resume(Tokens.XMLSTART)
-        EmptyTree
-
-      case _:ArrayIndexOutOfBoundsException => 
-        parser.syntaxError((debugLastStartElement.top._1),
-                      "missing end tag in XML literal for <"
-                      +debugLastStartElement.top._2+">");
-        parser.in.resume(Tokens.XMLSTART)
-        EmptyTree
-    }
+        else {
+          assert(ts.length == 1)
+          ts(0)
+        }
+      },
+      msg => parser.incompleteInputError(msg)
+    )
 
     /** @see xmlPattern. resynchronizes after successful parse 
      *  @return this xml pattern
-     *  precondition: s.xStartsXML == true
      */
-    def xLiteralPattern: Tree = try {
-      input = parser.in.flush
-      val oldMode = handle.isPattern;
-      handle.isPattern = true
-      assert(nextch == '<')
-      var tree = xPattern; xSpaceOpt;
-      handle.isPattern = oldMode;
-      parser.in.resume(Tokens.XMLSTART)
-      tree
-    } catch {
-      case c @ TruncatedXML =>
-        parser.syntaxError(pos - 1, c.getMessage)
-        //s.nextToken
-        parser.in.resume(Tokens.XMLSTART)
-        EmptyTree
-
-      case c @ (MissingEndTagException | ConfusedAboutBracesException) =>
-        parser.syntaxError((debugLastStartElement.top._1),
-                      c.getMessage + debugLastStartElement.top._2+">")
-        EmptyTree
-
-      case _:ArrayIndexOutOfBoundsException =>
-        parser.syntaxError((debugLastStartElement.top._1),
-                      "missing end tag in XML literal for <"
-                      +debugLastStartElement.top._2+">")
-        EmptyTree
-    }
+    def xLiteralPattern: Tree = xLiteralCommon(
+      () => {
+        input = parser.in
+        saving[Boolean, Tree](handle.isPattern, handle.isPattern = _) {
+          handle.isPattern = true
+          val tree = xPattern
+          xSpaceOpt
+          tree
+        }
+      },
+      msg => parser.syntaxError(curOffset, msg)
+    )
 
-    def xEmbeddedExpr: Tree = {
+    def escapeToScala[A](op: => A, kind: String) = {
       xEmbeddedBlock = false
-      parser.in.resume(LBRACE)
-      parser.in.sepRegions = RBRACE :: parser.in.sepRegions
-      val b = parser.block() //p.expr(true,false);
-      parser.in.sepRegions = parser.in.sepRegions.tail
-      if (parser.in.token != RBRACE) {
-        input = parser.in.flush
-        reportSyntaxError(" expected end of Scala block")
-      } else {
-        input = parser.in.flush
-        assert(nextch == '}')
+      val res = saving[List[Int], A](parser.in.sepRegions, parser.in.sepRegions = _) {
+        parser.in resume LBRACE
+        op
       }
-      b
+      if (parser.in.token != RBRACE)
+        reportSyntaxError(" expected end of Scala "+kind)
+      
+      res
     }
 
+    def xEmbeddedExpr: Tree = escapeToScala(parser.block(), "block")
+
     /** xScalaPatterns  ::= patterns
      */
-    def xScalaPatterns: List[Tree] = {
-      xEmbeddedBlock = false
-      parser.in.resume(LBRACE)
-      val b = parser.patterns(true)
-      if (parser.in.token != RBRACE) {
-        input = parser.in.flush
-        reportSyntaxError(" expected end of Scala pattern")
-      } else {
-        input = parser.in.flush
-        assert(nextch == '}')
-      }
-      b
-    }
-
-    //var ch: Char = _;
-
-
-    //def lookahead = { s.xLookahead }
-    var scannerState: List[List[Int]] = Nil
-
-/*
-    private def pushScannerState {
-      scannerState = s.sepRegions :: scannerState
-      s.sepRegions = Nil
-    }
-    private def popScannerState { 
-      s.sepRegions = scannerState.head
-      scannerState = scannerState.tail
-    }
-    */
-/*
-    private def init {
-      ch = s.in.ch
-      pos = s.in.cpos
-    }
-    */
+    def xScalaPatterns: List[Tree] = escapeToScala(parser.patterns(true), "pattern")
 
+    def reportSyntaxError(pos: Int, str: String) = parser.syntaxError(pos, str)
     def reportSyntaxError(str: String) = {
-      parser.syntaxError(pos - 1, "in XML literal: " + str)
+      reportSyntaxError(curOffset, "in XML literal: " + str)
       nextch
     }
-/*
-    private def sync {
-      xEmbeddedBlock = false
-      s.xSync
-    }
-*/
+
     /** '<' xPattern  ::= Name [S] { xmlPattern | '{' pattern3 '}' } ETag
      *                  | Name [S] '/' '>'
      */
-    def xPattern: Tree = {
-      val pos1 = pos
+    def xPattern: Tree = {      
+      var start = curOffset
       val qname = xName
-      debugLastStartElement.push((pos1, qname))
+      debugLastStartElement.push((start, qname))
       xSpaceOpt
-      if (ch == '/') { // empty tag
-        nextch
-        xToken('>')
-        return handle.makeXMLpat(pos1, qname, new mutable.ArrayBuffer[Tree]())
-      }
 
-      // else: tag with content
+      val ts = new ArrayBuffer[Tree]
+      val isEmptyTag = (ch == '/') && { nextch ; true }
       xToken('>')
-      var ts = new mutable.ArrayBuffer[Tree]
-      var exit = false
-      while (! exit) {
-        val pos2 = pos
-        if (xEmbeddedBlock) {
-          ts ++= xScalaPatterns
-        } else
-          ch match {
-            case '<' => // tag
+
+      if (!isEmptyTag) {        
+        // recurses until it hits a termination condition, then returns
+        def doPattern: Boolean = {
+          val start1 = curOffset
+          if (xEmbeddedBlock) ts ++= xScalaPatterns
+          else ch match {
+            case '<'  => // tag
               nextch
-              if (ch != '/') { //child
-                ts.append(xPattern)
-              } else {
-                exit = true
-              }
-            case '{' => // embedded Scala patterns
+              if (ch != '/') ts append xPattern   // child
+              else return false                   // terminate
+              
+            case '{'  => // embedded Scala patterns
               while (ch == '{') {
                 nextch
                 ts ++= xScalaPatterns
               }
-              // postcond: xEmbeddedBlock = false;
-              if (xEmbeddedBlock) Predef.error("problem with embedded block"); // assert
-
-            case SU =>
-              throw TruncatedXML
-
-            case _ => // teMaxt 
-              appendText(pos2, ts, xText)
-              // here  xEmbeddedBlock might be true;
-              //if( xEmbeddedBlock ) throw new ApplicationError("after:"+text); // assert
+              assert(!xEmbeddedBlock, "problem with embedded block")
+              
+            case SU   =>
+              throw TruncatedXMLControl
+              
+            case _    => // text
+              appendText(r2p(start1, start1, curOffset), ts, xText)
+              // here xEmbeddedBlock might be true:
+              // if (xEmbeddedBlock) throw new ApplicationError("after:"+text); // assert
           }
+          true
+        }
+        
+        while (doPattern) { }  // call until false
+        xEndTag(qname)
+        debugLastStartElement.pop
       }
-      xEndTag(qname)
-      debugLastStartElement.pop
-      handle.makeXMLpat(pos1, qname, ts)
+      
+      handle.makeXMLpat(r2p(start, start, curOffset), qname, ts)
     }
-
   } /* class MarkupParser */
 }
diff --git a/src/compiler/scala/tools/nsc/ast/parser/NewScanners.scala b/src/compiler/scala/tools/nsc/ast/parser/NewScanners.scala
deleted file mode 100644
index 696b5c8..0000000
--- a/src/compiler/scala/tools/nsc/ast/parser/NewScanners.scala
+++ /dev/null
@@ -1,905 +0,0 @@
-/* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
- * @author  Sean McDirmid
- */
-// $Id: NewScanners.scala 16894 2009-01-13 13:09:41Z cunei $
-
-package scala.tools.nsc.ast.parser
-
-import scala.tools.nsc.util.SourceFile._
-import scala.tools.nsc.util._
-
-trait NewScanners {
-  val global : Global
-  import global._
-  import Tokens._
-  trait CoreScannerInput extends BufferedIterator[Char] {
-    private[NewScanners] val scratch = new StringBuilder
-    def readIfStartsWith(c : Char) : Boolean = 
-      if (head == c) { next; true } else false
-    def readIfStartsWith(c0 : Char, c1 : Char) : Boolean = 
-      if (head == c0 && peek(1) == c1) {
-        next; next; true
-      } else false
-    def startsWith(c0: Char, c1 : Char) : Boolean = head == c0 && peek(1) == c1
-    def isUnicode : Boolean  
-
-    def peek(idx : Int) : Char
-
-    def offset : Int
-    def error(offset : Int, msg : String) : Unit
-    def incompleteError(offset : Int, msg : String) : Unit = error(offset, msg)
-    def textFor(from : Int, until : Int) : RandomAccessSeq[Char]
-  }
-  trait ScannerInput extends CoreScannerInput {
-    def seek(offset : Int) : Unit
-  }
-  class DefaultInput(in : NewCharArrayReader) extends ScannerInput {
-    import scala.collection.mutable._
-    def seek(offset : Int) = in.seek(offset)
-    def offset = in.offset
-    def head = peek(0)
-    def next = in.next
-    def isUnicode : Boolean = in.isUnicode
-    def hasNext = in.hasNext
-    def peek(idx : Int) = {
-      val offset = in.offset
-      var jdx = idx
-      var result = in.next
-      while (jdx > 0) {
-        jdx = jdx - 1
-        result =in.next
-      }
-      in.seek(offset) // jump back to old position
-      result
-    }
-    def error(offset : Int, msg : String) : Unit = {}
-    def textFor(from : Int, until : Int) = in.buf.slice(from, until).mkString
-  }
-
-  abstract class ParserScanner extends BaseScanner {
-    def init = nextToken
-
-    private var doc : String = ""
-    var sepRegions : List[Int] = Nil
-    private val current = new TokenHolder
-    private val    next = new TokenHolder
-    implicit def in : ScannerInput
-    
-    var lastCode = EMPTY
-    next.code = EMPTY
-    current.code = EMPTY
-    def hasNext = in.hasNext || (next.code != EMPTY && next.code != EOF)
-    def flush : ScannerInput = {
-      assert(current.code != EMPTY)
-      in.seek(unadjust(current.offset))
-      current.code = EMPTY
-      next.code = EMPTY
-      in
-    }
-    def seek(offset : Int, lastCode : Int) = {
-      assert(current.code == EMPTY)
-      in.seek(unadjust(offset))
-      this.lastCode = lastCode
-      nextToken
-    }
-    def resume(lastCode : Int) = {
-      assert(current.code == EMPTY)
-      this.lastCode = lastCode
-      nextToken
-    }
-    /** read next token and return last position
-     */
-    def skipToken: Int = {
-      val p = current.offset; nextToken
-      // XXX: account for off by one error //???
-      p
-    }
-    def currentPos = {
-      assert(current.code != EMPTY)
-      current.offset
-    }
-    def fillNext : Boolean = {
-      assert(next.code == EMPTY)
-      var hasNewline = false
-      do {
-        fill(next)
-      } while (next.code match {
-        case NEWLINE|NEWLINES|WHITESPACE|COMMENT => 
-          assert((next.code != COMMENT) == (xmlOk))
-          hasNewline = hasNewline || next.code == NEWLINE || next.code == NEWLINES
-          if (next.code == COMMENT)
-            doc = next.value.asInstanceOf[Option[String]].getOrElse("")
-          true
-        case _ => false
-        })
-        hasNewline
-    }
-
-    def flushDoc = {
-      val ret = doc
-      doc = ""
-      ret
-    }
-    
-    def nextToken : Unit = {
-      if (current.code == EOF) return // nothing more.
-      var lastIsComment = false
-      lastCode = current.code match {
-      case WHITESPACE|EMPTY => lastCode
-      case COMMENT => lastIsComment = true; lastCode
-      case code => code
-      }
-      // push on braces
-      val pushOn = (current.code) match {
-      case LBRACE => RBRACE
-      case LPAREN => RPAREN
-      case LBRACKET => RBRACKET
-      case CASE => 
-        ARROW
-      case RBRACE => 
-        while (!sepRegions.isEmpty && sepRegions.head != RBRACE)
-          sepRegions = sepRegions.tail
-        if (!sepRegions.isEmpty)
-          sepRegions = sepRegions.tail
-        EMPTY
-      case code @ (ARROW) if (!sepRegions.isEmpty && sepRegions.head == code) =>  
-        sepRegions = sepRegions.tail
-        EMPTY
-      case ARROW =>
-        EMPTY
-      case code @ (RPAREN|RBRACKET) =>  
-        if (!sepRegions.isEmpty && sepRegions.head == code)
-          sepRegions = sepRegions.tail
-        EMPTY
-      case _ => EMPTY
-      }
-      if (pushOn != EMPTY) sepRegions = pushOn :: sepRegions
-      
-      if (next.code != EMPTY) {
-        current.copy(next)
-        next.code = EMPTY
-      } else fill(current)
-      
-      def currentIsNext : Unit = {
-        assert(next.code != EMPTY)
-        return nextToken
-      }
-      current.code match {
-      case CASE|SEMI => 
-        fillNext
-        (current.code,next.code) match {
-        case (CASE,OBJECT) => 
-          current.code = CASEOBJECT; next.code = EMPTY
-        case (CASE, CLASS) => current.code = CASECLASS ; next.code = EMPTY
-        case (SEMI, ELSE ) => currentIsNext
-        case _ =>
-        }
-      case WHITESPACE|COMMENT => 
-        if (current.code == COMMENT) 
-          doc = current.value.asInstanceOf[Option[String]].getOrElse("")
-        nextToken  
-      case NEWLINE | NEWLINES =>
-        assert(xmlOk)
-        val headIsRBRACE = if (sepRegions.isEmpty) true else sepRegions.head == RBRACE
-        val hasNewline = fillNext
-        if (headIsRBRACE && (inLastOfStat(lastCode) && inFirstOfStat(next.code)
-           /* This need to be commented out, otherwise line 
-              continuation in the interpreter will not work 
-	      XXX: not sure how the IDE reacts with this commented out.
-              || next.code == EOF */ )) {
-          //if (hasNewline) current.code = NEWLINES
-        } else {
-          currentIsNext
-        }
-      case _ => 
-      }
-    }
-
-    def token = {
-      assert(current.code != EMPTY)
-      current.code
-    }
-
-    def nextTokenCode = {
-      if (next.code == EMPTY) fillNext
-      next.code
-    }
-
-    def name = current.value.get.asInstanceOf[Name]
-
-    def charVal = current.value.get.asInstanceOf[Char]
-
-    def intVal(negated : Boolean) : Long = {
-      val base = current.value.asInstanceOf[Option[Int]].getOrElse(10)
-      intVal(current.offset, current.code, current.nLit(this), negated, base)
-    }
-    def intVal : Long = intVal(false)
-
-    def floatVal(negated: Boolean): Double = {
-      floatVal(current.offset, current.code, current.nLit(this), negated)
-    }
-    def floatVal : Double = floatVal(false)
-
-    def stringVal = current.value.get.asInstanceOf[String]
-  }
-  
-  class TokenHolder {
-    var offset : Int = 0
-    var code : Int = 0
-    var length : Int = 0
-    var value : Option[Any] = None
-    def copy(from : TokenHolder) = {
-      this.offset = from.offset
-      this.code   = from.code
-      this.length = from.length
-      this.value = from.value
-    }
-    def set(offset : Int, length : Int, code : Int) = {
-      this.offset = offset; this.length = length; this.code = code; this.value = None
-    }
-    def set(offset : Int, length : Int, code : Int, value : Any) = {
-      this.offset = offset; this.length = length; this.code = code; this.value = Some(value)
-    }
-    def nLit(implicit in : BaseScanner) = (in.in.textFor(in.unadjust(offset), in.unadjust(offset + length)))
-      
-  }
-
-  trait BaseScanner {
-    implicit def in : CoreScannerInput
-    ScannerConfiguration.hashCode // forces initialization
-    import ScannerConfiguration._
-    var xmlOk = true
-    
-    def iterator = new Iterator[(Int,Int,Int)] { // offset,length,code
-      val current = new TokenHolder
-      def hasNext = in.hasNext
-      def next = {
-        fill(current)
-        (current.offset, current.length, current.code)
-      }
-    }
-    // IDE hooks
-    def   adjust(offset : Int) = offset
-    def unadjust(offset : Int) = offset
-    def identifier(name : Name) = name
-
-    protected def fill(current : TokenHolder) : Unit = {
-      if (!in.hasNext) {
-        current.offset = adjust(in.offset)
-        current.code = EOF
-        return
-      }
-      val oldXmlOk = xmlOk
-      xmlOk = false
-      val offset = in.offset // call "after" next
-      def escapeCode(offset : Int) : Char = in.next match {
-      case c if simpleEscape.isDefinedAt(c) => simpleEscape(c)
-      case c if isDigit(c) =>
-        val length = in.scratch.length
-        try {
-          assert(isDigit(c))
-          in.scratch append c
-          while (isDigit(in.head)) in.scratch append in.next
-          val n = Integer.parseInt(in.scratch.drop(length).mkString, 8)
-          if (n > 0377) {
-            in.error(offset, "malformed octal character code"); 0.toChar
-          } else n.toChar
-        } catch {
-          case ex : Exception => in.error(offset, "malformed octal character code"); 0.toChar
-        } finally {
-          in.scratch.setLength(length)
-        }
-      case c => in.error(offset, "unrecognized escape code \'" + c + "\'"); c
-      }
-      def getIdentRest : Unit = in.readIf{
-      case '_' =>
-        in.scratch append '_'
-        val c = in.head
-        if (isOperatorPart(c)) getOperatorRest else getIdentRest
-      case c if isIdentifierPart(c) => 
-         in.scratch append c; getIdentRest
-      }
-      
-      val next = in.next
-      // called after everything is read.
-      def length = in.offset - offset
-      
-      def value(code : Int, value : Any) : Int = { 
-        current.value = Some(value)
-        code
-      }
-      def doOperator(c : Char) = {
-        in.scratch.setLength(0)
-        in.scratch append(c)
-        getOperatorRest
-        val name : Name = global.newTermName(in.scratch.toString)
-        value(name2token(name), (name))
-      }
-      current.offset = adjust(offset) 
-      current.value = None
-      current.code = next match {
-      case ';' => (SEMI)
-      case ',' => (COMMA)
-      case '(' => xmlOk = true; (LPAREN)
-      case ')' => (RPAREN)
-      case '{' => xmlOk = true; (LBRACE)
-      case '}' => (RBRACE)
-      case '[' => (LBRACKET)
-      case ']' => (RBRACKET)
-      case SU => EOF
-      case '\u21D2' => (ARROW)
-      case '\u2190' => (LARROW)
-      case '<' => 
-        if (oldXmlOk && (in.head match {
-        case ('!' | '?') => true
-        case c if xml.Parsing.isNameStart(c) => true
-        case _ => false
-        })) { in.next; XMLSTART }
-        else doOperator('<')
-      case ' ' | '\t' => in.readWhile(isSpace); xmlOk = true; (WHITESPACE)  
-      case '/' =>
-        if (in.readIfStartsWith('/')) {
-          while (in.hasNext && !isNewLine(in.head)) in.next
-          (COMMENT)
-        } else if (in.readIfStartsWith('*')) {
-          val emptyOrDoc = in.readIfStartsWith('*')
-          val empty = emptyOrDoc && in.readIfStartsWith('/')
-          val isDoc = emptyOrDoc && !empty
-          
-          if (isDoc) 
-            in.scratch setLength 0
-
-          var count = 0
-          if (!empty) while (count != -1) in.next match {
-          case SU => in.incompleteError(offset, "unterminated comment"); count = -1
-          case '*' if in.readIfStartsWith('/') => count -= 1
-          case '/' if in.readIfStartsWith('*') => count += 1
-          case c =>
-            if (isDoc) in.scratch append c
-          }
-          if (!isDoc) (COMMENT) else value(COMMENT, in.scratch.toString)
-        } else doOperator('/')
-      case c @ ('~' | '!' | '@' | '#' | '%' |
-                '^' | '*' | '+' | '-' | /* '<' | | '/' */ 
-                '>' | '?' | ':' | '=' | '&' | 
-                '|' | '\\') => doOperator(c)
-      case c @ 
-       ('A' | 'B' | 'C' | 'D' | 'E' |
-        'F' | 'G' | 'H' | 'I' | 'J' |
-        'K' | 'L' | 'M' | 'N' | 'O' |
-        'P' | 'Q' | 'R' | 'S' | 'T' |
-        'U' | 'V' | 'W' | 'X' | 'Y' |
-        'Z' | '$' | '_' |
-        'a' | 'b' | 'c' | 'd' | 'e' |
-        'f' | 'g' | 'h' | 'i' | 'j' |
-        'k' | 'l' | 'm' | 'n' | 'o' |
-        'p' | 'q' | 'r' | 's' | 't' |
-        'u' | 'v' | 'w' | 'x' | 'y' |
-        'z') => 
-        in.scratch.setLength(0)
-        in.scratch.append(c : Char)
-        getIdentRest
-        val name = global.newTermName(in.scratch.toString)
-        in.scratch.setLength(0)
-        val code = name2token(name)
-        if (code == IDENTIFIER) value(code, identifier(name))
-        else value(code, (name))
-      case '0' => 
-        if (in.head match {
-        case 'x' | 'X' => true
-        case _ => false
-        }) { in.next; value(getNumber(offset, 16, "0x"), 16) }
-        else value(getNumber(offset, 8, "0"), 8)
-      case '1'|'2'|'3'|'4'|'5'|'6'|'7'|'8'|'9' => getNumber(offset, 10, "")
-      case '.' => 
-        val frac = getFraction(false)
-        val code = (frac getOrElse DOT) 
-        code
-      case '\'' =>
-        def endQ(cvalue : Char) : Int = {
-          if (!in.readIfStartsWith('\'')) {
-            in.error(offset, "missing terminating quote")
-          }
-          value(CHARLIT, cvalue)
-        }
-        in.next match {
-        case CR|LF|FF|SU|EOF if !in.isUnicode => 
-          in.error(offset, "unterminated character literal")
-          value(CHARLIT, 0.toChar)
-        case '\'' => 
-          in.error(offset, "empty character literal")
-          value(CHARLIT, 0.toChar)
-        case '\\' => endQ(escapeCode(offset))
-        case c if (Character.isUnicodeIdentifierStart(c)) && in.head != '\'' => 
-          in.scratch.setLength(0)
-          in.scratch append c
-          getIdentRest
-          if (in.readIfStartsWith('\'')) in.error(offset, "unexpected quote after symbol")
-          value(SYMBOLLIT, in.scratch.toString)
-        case c if isSpecial(c) && in.head != '\'' =>  
-          in.scratch.setLength(0)
-          in.scratch append(c)
-          getOperatorRest
-          if (in.readIfStartsWith('\'')) in.error(offset, "unexpected quote after symbol")
-          value(SYMBOLLIT, in.scratch.toString)
-        case c => endQ(c)
-        }
-      case '\"' =>
-        if (in.readIfStartsWith('\"')) {
-          if (in.readIfStartsWith('\"')) {
-            // multiline
-            in.scratch setLength 0
-            while (in.next match { 
-            case SU if !in.isUnicode => in.incompleteError(offset, "unterminated multi-line string"); false
-            case '\"' if in.readIfStartsWith('\"') =>
-              if (in.readIfStartsWith('\"')) false
-              else {
-                in.scratch append "\"\""; true
-              }
-            case '\\' if false => // XXX: not for multi-line strings?
-              in.scratch append escapeCode(in.offset - 1)
-              true
-            case c => in.scratch append c; true
-            }) {}
-            val ret = value(STRINGLIT, in.scratch.toString)
-            in.scratch setLength 0
-            ret
-          } else value(STRINGLIT, "")
-        } else {
-          in.scratch setLength 0
-          while (in.next match {
-          case '\"' => false
-          case CR|LF|FF|SU if !in.isUnicode => 
-            in.error(offset, "unterminated string"); false
-          case '\\' =>
-            in.scratch append escapeCode(in.offset - 1); true
-          case c => in.scratch.append(c); true
-          }) {}
-          val ret = value(STRINGLIT, in.scratch.toString)
-          in.scratch setLength 0
-          ret
-        }
-      case '`' => 
-        in.scratch setLength 0
-        if (in.head == '`') in.error(offset, "empty quoted identifier")
-        while (in.head match {
-        case '`' => in.next; false
-        case CR | LF | FF | SU | EOF => 
-        in.error(offset, "unterminated quoted identifier")
-        false
-        case _ => true
-        }) in.scratch append in.next
-        val name = global.newTermName(in.scratch.toString)
-        value(BACKQUOTED_IDENT, (name))
-      case c if (c == CR | c == LF | c == FF) => 
-        var multiple = false
-        in.readWhile{
-        case d if isNewLine(d) =>
-          multiple = multiple || d == c; true
-        case ' ' | '\t' => true // eat the whitespace after newlines.
-        case _ => false
-        }
-        xmlOk = true
-        (if (multiple) NEWLINES else NEWLINE)
-      case c => 
-        if (Character.isUnicodeIdentifierStart(c)) {
-          in.scratch.setLength(0)
-          in.scratch append c
-          getIdentRest
-          val name = global.newTermName(in.scratch.toString)
-          in.scratch.setLength(0)
-          val code = name2token(name)
-          value(code, (name))
-        } else if (isSpecial(c)) {
-          in.scratch.setLength(0)
-          in.scratch append c
-          getOperatorRest
-          val name = global.newTermName(in.scratch.toString)
-          in.scratch.setLength(0)
-          val code = name2token(name)
-          value(code, (name))
-        } else {
-          in.error(offset, "illegal character: \'" + c + "\'")
-          (ERROR)
-        }
-      }
-      current.length = length
-    }
-    def intVal(offset : Int, token : Int, name0 : RandomAccessSeq[Char], negated: Boolean, base : Int): Long = {
-      if (name0.length == 1 && name0(0) == '0') return 0
-
-      var name = name0
-      if (name.length > 2 && name(0) == '0' && (name(1) match {
-        case 'x'|'X' => true
-        case _ => false
-      })) name = name.drop(2)
-
-      while (name.last match {
-        case 'l'|'L' => true
-        case _ => false
-      }) name = name.take(name.length - 1)
-      
-      if (token == CHARLIT && !negated) {
-        if (name.length > 0) name(0) else 0
-      } else {
-        var value: Long = 0
-        val divider = if (base == 10) 1 else 2
-        val limit: Long =
-          if (token == LONGLIT) Math.MAX_LONG else Math.MAX_INT
-        var i = 0
-        val len = name.length
-        while (i < len) {
-          val d = digit2int(name(i), base)
-          if (d < 0) {
-            in.error(offset, "malformed integer number")
-            return 0
-          }
-          if (value < 0 ||
-              limit / (base / divider) < value ||
-              limit - (d / divider) < value * (base / divider) &&
-              !(negated && limit == value * base - 1 + d)) {
-                in.error(offset, "integer number too large")
-                return 0
-              }
-          value = value * base + d
-          i += 1
-        }
-        if (negated) -value else value
-      }
-    }
-
-
-    /** convert name, base to double value
-    */
-    def floatVal(offset : Int, token : Int, name0 : RandomAccessSeq[Char], negated: Boolean): Double = {
-      var name = name0
-      while (name.last match {
-          case 'f'|'F'|'d'|'D' => true
-          case _ => false
-      }) name = name.take(name.length - 1)
-
-      val limit: Double = 
-        if (token == DOUBLELIT) Math.MAX_DOUBLE else Math.MAX_FLOAT
-      try {
-        val value: Double = java.lang.Double.valueOf(name.mkString).doubleValue()
-        if (value > limit)
-          in.error(offset, "floating point number too large")
-        if (negated) -value else value
-      } catch {
-        case _: NumberFormatException => 
-          in.error(offset, "malformed floating point number")
-          0.0
-      }
-    }
-  }
-  
-  
-  // utility functions 
-  def isSpecial(c : Char) : Boolean = {
-    val chtp = Character.getType(c)
-    chtp == Character.MATH_SYMBOL || chtp == Character.OTHER_SYMBOL
-  }
-  def isDigit(c : Char) : Boolean = digit2int(c, 10) >= 0
-
-  def isIdentifierStart(c: Char): Boolean = c match {
-  case 'A' | 'B' | 'C' | 'D' | 'E' |
-       'F' | 'G' | 'H' | 'I' | 'J' |
-       'K' | 'L' | 'M' | 'N' | 'O' |
-       'P' | 'Q' | 'R' | 'S' | 'T' |
-       'U' | 'V' | 'W' | 'X' | 'Y' |
-       'Z' | '$' | '_' |
-       'a' | 'b' | 'c' | 'd' | 'e' |
-       'f' | 'g' | 'h' | 'i' | 'j' |
-       'k' | 'l' | 'm' | 'n' | 'o' |
-       'p' | 'q' | 'r' | 's' | 't' |
-       'u' | 'v' | 'w' | 'x' | 'y' |  // scala-mode: need to understand multi-line case patterns
-       'z' => true
-  case _ => false
-  }
-  def isIdentifierPart(c: Char) : Boolean = c match {
-  case ('A' | 'B' | 'C' | 'D' | 'E' |
-        'F' | 'G' | 'H' | 'I' | 'J' |
-        'K' | 'L' | 'M' | 'N' | 'O' |
-     'P' | 'Q' | 'R' | 'S' | 'T' |
-     'U' | 'V' | 'W' | 'X' | 'Y' |
-     'Z' | '$' | '_' |
-     'a' | 'b' | 'c' | 'd' | 'e' |
-     'f' | 'g' | 'h' | 'i' | 'j' |
-     'k' | 'l' | 'm' | 'n' | 'o' |
-     'p' | 'q' | 'r' | 's' | 't' |
-     'u' | 'v' | 'w' | 'x' | 'y' |
-     'z') => true
-  case '0'|'1'|'2'|'3'|'4'|'5'|'6'|'7'|'8'|'9' => true
-  case c if Character.isUnicodeIdentifierPart(c) => true
-  case _ => false
-  }
-  //isIdentifierStart(c) || isDigit(c) || isUnicodeIdentifierPart(c)
-  def isOperatorPart(c : Char) : Boolean = c match {
-  case '~' | '!' | '@' | '#' | '%' | 
-       '^' | '*' | '+' | '-' | '<' |
-       '>' | '?' | ':' | '=' | '&' | 
-       '|' | '/' | '\\' => true
-  case c if isSpecial(c) => true
-  case _ => false
-  }
-
-  private def getOperatorRest(implicit in : CoreScannerInput) : Unit = {
-    in.readWhile{
-    case ('/') if in.startsWith('/','*') || in.startsWith('/','/') => false
-    case ('*') if in.startsWith('*','/') => false
-    case (c) if isOperatorPart(c) => in.scratch append c; true
-    case _ => false
-    }
-  }
-  private def isFraction(c0 : Char, c1 : Char) = 
-    isDigit(c0) || (c0 match {
-    case 'd'|'D'|'f'|'F' if !isIdentifierPart(c1) => true
-    case 'e'|'E' if isDigit(c1) => true
-    case _ => false  
-    })
-  private def getFraction(hasWhole : Boolean)(implicit in : CoreScannerInput) : Option[Int] = {
-    val hasDigits = in.readWhile(isDigit)
-    if (!hasDigits && !hasWhole) return None
-
-    def end(code : Int) : Option[Int] = {
-      if (!hasDigits && isIdentifierPart(in.peek(1))) None
-      else in.next; Some(code) 
-    }
-    in.head match {
-    case 'f'|'F' => return end(FLOATLIT)
-    case 'd'|'D' => return end(DOUBLELIT)
-    case 'e'|'E' if {
-        val peek = in.peek(1)
-        peek == '-' || peek == '+' || isDigit(peek)
-    } =>
-      in.next // eat the e.
-      var hasDigit = isDigit(in.next) // eat +/-/digit 
-      hasDigit = in.readWhile(isDigit) || hasDigit
-      in.readIf{ // eat an optional f or d
-      case 'f'|'F' => FLOATLIT
-      case 'd'|'D' => DOUBLELIT
-      } orElse Some(DOUBLELIT)
-    case _ if hasDigits => Some(DOUBLELIT)
-    case _ => None // we didn't read anything
-    }
-  }
-  private def getNumber(offset : Int, base : Int, prefix : String)(implicit in : CoreScannerInput) : Int = {
-    val hasBody = in.readWhile{
-    case at if at >= '0' && at <= '9' => true
-    case at if base == 16 && ((at >= 'a' && at <= 'f') || (at >= 'A' && at <= 'F')) => true
-    case _ => false
-    }
-    if (!hasBody) base match {
-      // because Java does this
-    case 16 => 
-      in.error(offset, "Invalid hex literal number")
-      return INTLIT
-    case _ => 
-    }
-    val code = if (in.head == '.') {
-      in.peek(1) match {
-      case c if isDigit(c) => in.next; getFraction(true).get
-      case 'f'|'F'|'d'|'D' if !isIdentifierPart(in.peek(2)) => in.next; getFraction(true).get
-      case 'e'|'E' if {
-        val peek = in.peek(2)
-        isDigit(peek) || peek == '-' || peek == '+'
-      } => 
-        in.next // consume the dot
-        in.next // consume the e
-        in.next // consume the +/-/digit
-        in.readWhile(isDigit) // consume remaining digits
-        in.readIf{
-        case 'f'|'F' => FLOATLIT
-        case 'd'|'D' => DOUBLELIT
-        } getOrElse DOUBLELIT
-      case c if isIdentifierStart(c) => INTLIT
-      case _ => in.next; DOUBLELIT
-      }
-    } else (in.readIf{
-    case 'l'|'L' => LONGLIT
-    case 'f'|'F' => FLOATLIT
-    case 'd'|'D' => DOUBLELIT
-    } getOrElse {
-      if (in.head == 'e' || in.head == 'E') {
-        in.next
-        if (in.head == '-' || in.head == '+') in.next
-        in.readWhile(isDigit)
-        in.readIf{
-        case 'f'|'F' => FLOATLIT
-        case 'd'|'D' => DOUBLELIT
-        } getOrElse DOUBLELIT
-      } else INTLIT
-    })
-    if (in.readWhile(isIdentifierPart))
-      in.error(offset, "Invalid literal number")
-    code
-  }
-  def inFirstOfStat(token: Int) = token match {
-  case EOF | /*CASE |*/ CATCH | ELSE | EXTENDS | FINALLY | MATCH | REQUIRES | WITH | YIELD |
-       COMMA | SEMI | NEWLINE | NEWLINES | DOT | USCORE | COLON | EQUALS | ARROW |
-       LARROW | SUBTYPE | VIEWBOUND | SUPERTYPE | HASH | // todo: add LBRACKET
-       RPAREN | RBRACKET | RBRACE => false
-  case _ => true
-  }
-  def inLastOfStat(token: Int) = token match {
-  case CHARLIT | INTLIT | LONGLIT | FLOATLIT | DOUBLELIT | STRINGLIT | SYMBOLLIT |
-       IDENTIFIER | BACKQUOTED_IDENT | THIS | NULL | TRUE | FALSE | RETURN | USCORE | 
-       TYPE | XMLSTART | RPAREN | RBRACKET | RBRACE => true
-  case _ => false
-  }
-  
-  def digit(c : Char, radix : Int) = c match {
-  case c if c >= '0' && c <= '7' => c - '0'
-  case c if c >= '8' && c <= '9' && radix >= 10 => c - '0'
-  case c if c >= '8' && c <= '9' && radix == 8 => throw new NumberFormatException("Malformed octal number")
-  case c if c >= 'a' && c <= 'f' && radix == 16 => c - 'a' + 9
-  case c if c >= 'A' && c <= 'F' && radix == 16 => c - 'A' + 9
-  }
-  private val simpleEscape : PartialFunction[Char,Char] = {
-  case 'b' => '\b'
-  case 't' => '\t'
-  case 'n' => '\n'
-  case 'f' => '\f'
-  case 'r' => '\r'
-  case '\"' => '\"'
-  case '\'' => '\''
-  case '\\' => '\\'
-  }
-
-  def digit2int(ch: Char, base: Int): Int = {
-    if ('0' <= ch && ch <= '9' && ch < '0' + base)
-      ch - '0'
-    else if ('A' <= ch && ch < 'A' + base - 10)
-      ch - 'A' + 10
-    else if ('a' <= ch && ch < 'a' + base - 10)
-      ch - 'a' + 10
-    else
-      -1
-  }
-  
-  object ScannerConfiguration {
-    private var key: Array[Byte] = _
-    private var maxKey = 0
-    private var tokenName = new Array[global.Name](128);
-    {
-      var tokenCount = 0
-      // Enter keywords
-      def enterKeyword(n: global.Name, tokenId: Int) {
-        while (tokenId >= tokenName.length) {
-          val newTokName = new Array[global.Name](tokenName.length * 2)
-          Array.copy(tokenName, 0, newTokName, 0, newTokName.length)
-          tokenName = newTokName
-        }
-        tokenName(tokenId) = n
-        if (n.start > maxKey) maxKey = n.start
-        if (tokenId >= tokenCount) tokenCount = tokenId + 1
-      }
-      import global.nme
-
-      enterKeyword(nme.ABSTRACTkw, ABSTRACT)
-      enterKeyword(nme.CASEkw, CASE)
-      enterKeyword(nme.CATCHkw, CATCH)
-      enterKeyword(nme.CLASSkw, CLASS)
-      enterKeyword(nme.DEFkw, DEF)
-      enterKeyword(nme.DOkw, DO)
-      enterKeyword(nme.ELSEkw, ELSE)
-      enterKeyword(nme.EXTENDSkw, EXTENDS)
-      enterKeyword(nme.FALSEkw, FALSE)
-      enterKeyword(nme.FINALkw, FINAL)
-      enterKeyword(nme.FINALLYkw, FINALLY)
-      enterKeyword(nme.FORkw, FOR)
-      enterKeyword(nme.FORSOMEkw, FORSOME)
-      enterKeyword(nme.IFkw, IF)
-      enterKeyword(nme.IMPLICITkw, IMPLICIT)
-      enterKeyword(nme.IMPORTkw, IMPORT)
-      enterKeyword(nme.LAZYkw, LAZY)
-      enterKeyword(nme.MATCHkw, MATCH)
-      enterKeyword(nme.NEWkw, NEW)
-      enterKeyword(nme.NULLkw, NULL)
-      enterKeyword(nme.OBJECTkw, OBJECT)
-      enterKeyword(nme.OVERRIDEkw, OVERRIDE)
-      enterKeyword(nme.PACKAGEkw, PACKAGE)
-      enterKeyword(nme.PRIVATEkw, PRIVATE)
-      enterKeyword(nme.PROTECTEDkw, PROTECTED)
-      enterKeyword(nme.REQUIRESkw, REQUIRES)
-      enterKeyword(nme.RETURNkw, RETURN)
-      enterKeyword(nme.SEALEDkw, SEALED)
-      enterKeyword(nme.SUPERkw, SUPER)
-      enterKeyword(nme.THISkw, THIS)
-      enterKeyword(nme.THROWkw, THROW)
-      enterKeyword(nme.TRAITkw, TRAIT)
-      enterKeyword(nme.TRUEkw, TRUE)
-      enterKeyword(nme.TRYkw, TRY)
-      enterKeyword(nme.TYPEkw, TYPE)
-      enterKeyword(nme.VALkw, VAL)
-      enterKeyword(nme.VARkw, VAR)
-      enterKeyword(nme.WHILEkw, WHILE)
-      enterKeyword(nme.WITHkw, WITH)
-      enterKeyword(nme.YIELDkw, YIELD)
-      enterKeyword(nme.DOTkw, DOT)
-      enterKeyword(nme.USCOREkw, USCORE)
-      enterKeyword(nme.COLONkw, COLON)
-      enterKeyword(nme.EQUALSkw, EQUALS)
-      enterKeyword(nme.ARROWkw, ARROW)
-      enterKeyword(nme.LARROWkw, LARROW)
-      enterKeyword(nme.SUBTYPEkw, SUBTYPE)
-      enterKeyword(nme.VIEWBOUNDkw, VIEWBOUND)
-      enterKeyword(nme.SUPERTYPEkw, SUPERTYPE)
-      enterKeyword(nme.HASHkw, HASH)
-      enterKeyword(nme.ATkw, AT)
-
-      // Build keyword array
-      key = new Array[Byte](maxKey + 1)
-      for (i <- 0 to maxKey)
-        key(i) = IDENTIFIER
-      for (j <- 0 until tokenCount)
-        if (tokenName(j) ne null)
-          key(tokenName(j).start) = j.asInstanceOf[Byte]
-
-    }
-//Token representation -----------------------------------------------------
-
-    /** Convert name to token */
-    def name2token(name: global.Name): Int =
-      if (name.start <= maxKey) key(name.start) else IDENTIFIER
-    
-    def isKeyword(code : Int) = code match {
-      case code if code >= IF && code <= REQUIRES => true
-      case _ => false
-    }
-
-    /** Returns the string representation of given token. */
-    def token2string(token: Int): String = token match {
-      case IDENTIFIER | BACKQUOTED_IDENT => "identifier"
-      case CHARLIT => "character literal"
-      case INTLIT => "integer literal"
-      case LONGLIT => "long literal"
-      case FLOATLIT => "float literal"
-      case DOUBLELIT => "double literal"
-      case STRINGLIT => "string literal"
-      case SYMBOLLIT => "symbol literal"
-      case LPAREN => "'('"
-      case RPAREN => "')'"
-      case LBRACE => "'{'"
-      case RBRACE => "'}'"
-      case LBRACKET => "'['"
-      case RBRACKET => "']'"
-      case EOF => "eof"
-      case ERROR => "something"
-      case SEMI => "';'"
-      case NEWLINE => "';'"
-      case NEWLINES => "';'"
-      case COMMA => "','"
-      case CASECLASS =>
-        "case class"
-      case CASEOBJECT =>
-        "case object"
-      case XMLSTART => 
-        "$XMLSTART$<"
-      case COMMENT => "cmnt"
-      case WHITESPACE => "ws"
-      case IGNORE => "ig"
-      case _ =>
-        try {
-          "'" + tokenName(token) + "'"
-        } catch {
-          case _: ArrayIndexOutOfBoundsException =>
-            "'<" + token + ">'"
-          case _: NullPointerException =>
-            "'<(" + token + ")>'"
-        }
-    }
-  }
- 
-  class UnitScanner(unit: CompilationUnit) extends ParserScanner {
-    implicit val in = 
-      new DefaultInput(new NewCharArrayReader(unit.source.content, !settings.nouescape.value, error)) {
-        override def error(offset : Int, msg : String) : Unit = UnitScanner.this.error(offset, msg)
-        override def incompleteError(offset : Int, msg : String) = 
-          unit.incompleteInputError(new OffsetPosition(unit.source, offset), msg)
-      }
-    init
-    private def error(offset : Int, msg : String) : Unit = unit.error(new OffsetPosition(unit.source,offset), msg)
-  }
-}
diff --git a/src/compiler/scala/tools/nsc/ast/parser/Parsers.scala b/src/compiler/scala/tools/nsc/ast/parser/Parsers.scala
index 3b2c967..0987ed6 100644
--- a/src/compiler/scala/tools/nsc/ast/parser/Parsers.scala
+++ b/src/compiler/scala/tools/nsc/ast/parser/Parsers.scala
@@ -1,15 +1,15 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: Parsers.scala 16894 2009-01-13 13:09:41Z cunei $
 //todo: allow infix type patterns
 
 
-package scala.tools.nsc.ast.parser
+package scala.tools.nsc
+package ast.parser
 
 import scala.collection.mutable.ListBuffer
-import scala.tools.nsc.util.{Position, OffsetPosition, NoPosition, BatchSourceFile}
+import util.{ OffsetPosition, BatchSourceFile }
 import symtab.Flags
 import Tokens._
 
@@ -50,107 +50,197 @@ import Tokens._
  *    </li>
  *  </ol>
  */
-trait Parsers extends NewScanners with MarkupParsers {
-  val global : Global 
+trait Parsers extends Scanners with MarkupParsers {
+self =>
+  val global: Global 
   import global._
 
   private val glob: global.type = global
-  import global.posAssigner.atPos
-
-  case class OpInfo(operand: Tree, operator: Name, pos: Int)
-  /** ...
-   *
-   *  @author Sean McDirmid
-   */
-  class UnitParser(val unit: global.CompilationUnit) extends Parser {
-    val in = new UnitScanner(unit)
-    def freshName(pos : Position, prefix : String) = unit.fresh.newName(pos, prefix)
-    implicit def i2p(offset : Int) : Position = new OffsetPosition(unit.source,offset)
-    def warning(pos : Int, msg : String) : Unit = unit.warning(pos, msg)
-    def incompleteInputError(msg: String) : Unit =
-      unit.incompleteInputError(unit.source.asInstanceOf[BatchSourceFile].content.length - 1, msg)
-    def deprecationWarning(pos : Int, msg : String) : Unit = unit.deprecationWarning(pos, msg)
-    def syntaxError(pos: Int, msg: String) : Unit = unit.error(pos, msg)
+
+  case class OpInfo(operand: Tree, operator: Name, offset: Offset)
+
+  class UnitParser(val unit: global.CompilationUnit, patches: List[BracePatch]) extends Parser {
+
+    def this(unit: global.CompilationUnit) = this(unit, List())
     
-    /** the markup parser */
-    def xmlp = {
-      if (xmlp0 == null) 
-        xmlp0 = new MarkupParser(this, true)
-      xmlp0
+    /** The parse starting point depends on whether the source file is self-contained:
+     *  if not, the AST will be supplemented.
+     */
+    def parseStartRule =
+      if (unit.source.isSelfContained) () => compilationUnit()
+      else () => scriptBody()
+
+    val in = new UnitScanner(unit, patches)
+    in.init()
+
+    def freshName(pos: Position, prefix: String): Name =
+      unit.fresh.newName(pos, prefix)
+
+    def o2p(offset: Int): Position = new OffsetPosition(unit.source,offset)
+    def r2p(start: Int, mid: Int, end: Int): Position = rangePos(unit.source, start, mid, end)
+
+    def warning(offset: Int, msg: String) { unit.warning(o2p(offset), msg) }
+
+    def deprecationWarning(offset: Int, 
+                           msg: String) {
+      unit.deprecationWarning(o2p(offset), msg)
+    }
+
+    var smartParsing = false
+
+    val syntaxErrors = new ListBuffer[(Int, String)]
+    
+    def incompleteInputError(msg: String) {
+      val offset = unit.source.asInstanceOf[BatchSourceFile].content.length - 1
+      if (smartParsing) syntaxErrors += ((offset, msg))
+      else unit.incompleteInputError(o2p(offset), msg)
+    }
+
+    def syntaxError(offset: Int, msg: String) { 
+      if (smartParsing) syntaxErrors += ((offset, msg))
+      else unit.error(o2p(offset), msg) 
     }
-    object symbXMLBuilder extends SymbolicXMLBuilder(treeBuilder, this, true) { // DEBUG choices
-      val global: Parsers.this.global.type = Parsers.this.global
-      def freshName(prefix: String): Name = UnitParser.this.freshName(NoPosition, prefix)
+
+    /** parse unit. If there are inbalanced braces,
+     *  try to correct them and reparse.
+     */
+    def smartParse(): Tree = try {
+      smartParsing = true
+      val firstTry = parse()
+      if (syntaxErrors.isEmpty) firstTry
+      else {
+        val patches = in.healBraces() 
+        if (patches.isEmpty) {
+          for ((offset, msg) <- syntaxErrors) unit.error(o2p(offset), msg)
+          firstTry
+        } else {
+//          println(patches)
+          new UnitParser(unit, patches).parse()
+        }
+      }
+    } finally {
+      smartParsing = false
     }
-    private var xmlp0: MarkupParser = null
+
+    /** the markup parser */
+    lazy val xmlp = new MarkupParser(this, true)
+
+    object symbXMLBuilder extends SymbolicXMLBuilder(this, true) { // DEBUG choices
+      val global: self.global.type = self.global
+      def freshName(prefix: String): Name = UnitParser.this.freshName(prefix)
+    }
+
     def xmlLiteral : Tree = xmlp.xLiteral
+
     def xmlLiteralPattern : Tree = xmlp.xLiteralPattern
   }
-  // parser constants, here so they don't pollute parser debug listing
-  private object ParserConfiguration {
-    final val Local = 0
-    final val InBlock = 1
-    final val InTemplate = 2
-    final val MINUS: Name = "-"
-    final val PLUS : Name = "+"
-    final val BANG : Name = "!"
-    final val TILDE: Name = "~"
-    final val AMP  : Name = "&"
-    final val SLASH: Name = "/"
-    final val STAR : Name = "*"
-    final val BAR  : Name = "|"
-    final val OPT  : Name = "?"
-    final val LT   : Name = "<"
-  }
+
+  final val Local = 0
+  final val InBlock = 1
+  final val InTemplate = 2
+  final val MINUS: Name = "-"
+  final val PLUS : Name = "+"
+  final val BANG : Name = "!"
+  final val TILDE: Name = "~"
+  final val AMP  : Name = "&"
+  final val SLASH: Name = "/"
+  final val STAR : Name = "*"
+  final val BAR  : Name = "|"
+  final val LT   : Name = "<"
 
   abstract class Parser {
-    ParserConfiguration.hashCode
-    import ParserConfiguration._
-    val in: ParserScanner
+    val in: Scanner
     //val unit : CompilationUnit
     //import in.ScanPosition
-    protected def freshName(pos : Position, prefix: String): Name
-    protected def posToReport: Int = in.currentPos
-    
-    protected implicit def i2p(offset : Int) : Position
-    //private implicit def p2i(pos : Position) = pos.offset.get
-    
-    private def inToken = in.token
-    private def inSkipToken = in.skipToken
-    private def inNextToken = in.nextToken
-    private def inCurrentPos = in.currentPos
-    private def inNextTokenCode : Int = in.nextTokenCode
-    private def inName = in.name
-    private def charVal = in.charVal  
-    private def intVal(isNegated : Boolean) = in.intVal(isNegated).asInstanceOf[Int]
-    private def longVal(isNegated : Boolean) = in.intVal(isNegated)
-    private def floatVal(isNegated : Boolean) = in.floatVal(isNegated).asInstanceOf[Float]
-    private def doubleVal(isNegated : Boolean) = in.floatVal(isNegated)
-    private def stringVal = in.stringVal
+    def freshName(pos: Position, prefix: String): Name
+    def freshName(prefix: String): Name = freshName(NoPosition, prefix) // todo get rid of position
 
+    def o2p(offset: Int): Position
+    def r2p(start: Int, mid: Int, end: Int): Position
+    //private implicit def p2i(pos: Position) = pos.offset.get
+    
     /** whether a non-continuable syntax error has been seen */
     //private var syntaxErrorSeen = false 
-    private var lastErrorPos : Int = -1
+
+    private var lastErrorOffset : Int = -1
 
     object treeBuilder extends TreeBuilder {
-      val global: Parsers.this.global.type = Parsers.this.global
-      def freshName(pos : Position, prefix: String): Name = Parser.this.freshName(pos, prefix)
+      val global: self.global.type = self.global
+      def freshName(prefix: String): Name = Parser.this.freshName(prefix)
+      def o2p(offset: Int) = Parser.this.o2p(offset)
+      def r2p(start: Int, point: Int, end: Int) = Parser.this.r2p(start, point, end)
     }
-    import treeBuilder._
+    import treeBuilder.{global => _, _}
 
+    /** The types of the context bounds of type parameters of the surrounding class
+     */
+    var classContextBounds: List[Tree] = Nil
 
-    /** The implicit view parameters of the surrounding class */
-    var implicitClassViews: List[Tree] = Nil
+    /** Are we inside the Scala package? Set for files that start with package scala
+     */
+    private var inScalaPackage = false
+    
+    def parseStartRule: () => Tree
 
-    /** this is the general parse method
+    /** This is the general parse entry point.
      */
     def parse(): Tree = {
-      val t = compilationUnit()
+      val t = parseStartRule()
       accept(EOF)
       t
     }
+    
+    /** This is the parse entry point for code which is not self-contained, e.g.
+     *  a script which is a series of template statements.  They will be
+     *  swaddled in Trees until the AST is equivalent to the one returned
+     *  by compilationUnit().
+     */
+    def scriptBody(): Tree = {
+      val stmts = templateStatSeq(false)._2
+      accept(EOF)
+      
+      /** Here we are building an AST representing the following source fiction,
+       *  where <moduleName> is from -Xscript (defaults to "Main") and <stmts> are
+       *  the result of parsing the script file.
+       *
+       *  object <moduleName> {
+       *    def main(argv: Array[String]): Unit = {
+       *      val args = argv
+       *      new AnyRef {
+       *        <stmts>
+       *      }
+       *    }
+       *  }
+       */
+      import definitions._
+
+      def emptyPkg    = atPos(0, 0, 0) { Ident(nme.EMPTY_PACKAGE_NAME) }
+      def emptyInit   = DefDef(
+        NoMods,
+        nme.CONSTRUCTOR,
+        Nil,
+        List(Nil),
+        TypeTree(),
+        Block(List(Apply(Select(Super("", ""), nme.CONSTRUCTOR), Nil)), Literal(Constant(())))
+      )
+
+      // def main
+      def mainParamType = AppliedTypeTree(Ident("Array".toTypeName), List(Ident("String".toTypeName)))
+      def mainParameter = List(ValDef(Modifiers(Flags.PARAM), "argv", mainParamType, EmptyTree))
+      def mainSetArgv   = List(ValDef(NoMods, "args", TypeTree(), Ident("argv")))
+      def mainNew       = makeNew(Nil, emptyValDef, stmts, List(Nil), NoPosition, NoPosition)
+      def mainDef       = DefDef(NoMods, "main", Nil, List(mainParameter), scalaDot(nme.Unit.toTypeName), Block(mainSetArgv, mainNew))
+
+      // object Main
+      def moduleName  = ScriptRunner scriptMain settings
+      def moduleBody  = Template(List(scalaScalaObjectConstr), emptyValDef, List(emptyInit, mainDef))
+      def moduleDef   = ModuleDef(NoMods, moduleName, moduleBody)
+      
+      // package <empty> { ... }
+      makePackaging(0, emptyPkg, List(moduleDef))
+    }
 
-/////////// PLACEHOLDERS ///////////////////////////////////////////////////////    
+/* --------------- PLACEHOLDERS ------------------------------------------- */
 
     /** The implicit parameters introduced by `_' in the current expression.
      *  Parameters appear in reverse order 
@@ -193,20 +283,33 @@ trait Parsers extends NewScanners with MarkupParsers {
       placeholderTypes = List()
       var t = op
       if (!placeholderTypes.isEmpty && t.isInstanceOf[AppliedTypeTree]) {
-        t = ExistentialTypeTree(t, placeholderTypes.reverse)
+        val expos = t.pos
+        ensureNonOverlapping(t, placeholderTypes)
+        t = atPos(expos) { ExistentialTypeTree(t, placeholderTypes.reverse) }
         placeholderTypes = List()
       } 
       placeholderTypes = placeholderTypes ::: savedPlaceholderTypes
       t
     }
 
-/////// ERROR HANDLING //////////////////////////////////////////////////////
+    def isWildcard(t: Tree): Boolean = t match {
+      case Ident(name1) => !placeholderParams.isEmpty && name1 == placeholderParams.head.name
+      case Typed(t1, _) => isWildcard(t1)
+      case Annotated(t1, _) => isWildcard(t1)
+      case _ => false
+    }
+
+/* ------------- ERROR HANDLING ------------------------------------------- */
+
+    var assumedClosingParens = collection.mutable.Map(RPAREN -> 0, RBRACKET -> 0, RBRACE -> 0)
 
-    protected def skip() {
+    var inFunReturnType = false
+
+    protected def skip(targetToken: Int) {
       var nparens = 0
       var nbraces = 0
       while (true) {
-        inToken match {
+        in.token match {
           case EOF =>
             return
           case SEMI =>
@@ -226,81 +329,64 @@ trait Parsers extends NewScanners with MarkupParsers {
             nbraces += 1
           case _ =>
         }
-        inNextToken
+        if (targetToken == in.token && nparens == 0 && nbraces == 0) return
+        in.nextToken()
       }
     }
-    def warning(pos : Int, msg : String) : Unit
-    def incompleteInputError(msg: String) : Unit
-    def deprecationWarning(pos : Int, msg : String) : Unit
-    private def syntaxError(pos : Position, msg : String, skipIt : Boolean) : Unit = pos.offset match {
-      case None => syntaxError(msg,skipIt)
-      case Some(offset) => syntaxError(offset, msg, skipIt)
+    def warning(offset: Int, msg: String): Unit
+    def incompleteInputError(msg: String): Unit
+    def deprecationWarning(offset: Int, msg: String): Unit
+    private def syntaxError(pos: Position, msg: String, skipIt: Boolean) {
+      syntaxError(pos pointOrElse in.offset, msg, skipIt)
     }
-    def syntaxError(pos: Int, msg: String) : Unit
+    def syntaxError(offset: Int, msg: String): Unit
     def syntaxError(msg: String, skipIt: Boolean) {
-      syntaxError(inCurrentPos, msg, skipIt)
+      syntaxError(in.offset, msg, skipIt)
     }
-    
-    def syntaxError(pos: Int, msg: String, skipIt: Boolean) {
-      if (pos > lastErrorPos) {
-        syntaxError(pos, msg)
+
+    def syntaxError(offset: Int, msg: String, skipIt: Boolean) {
+      if (offset > lastErrorOffset) {
+        syntaxError(offset, msg)
         // no more errors on this token.
-        lastErrorPos = inCurrentPos
+        lastErrorOffset = in.offset
       }
       if (skipIt) 
-        skip()
+        skip(UNDEF)
     }
-    def warning(msg: String) : Unit = warning(inCurrentPos, msg)
-    
+
+    def warning(msg: String) { warning(in.offset, msg) }
 
     def syntaxErrorOrIncomplete(msg: String, skipIt: Boolean) {
-      val inToken = this.inToken
-      if (inToken == EOF)
-        incompleteInputError(msg)
-      else
-        syntaxError(inCurrentPos, msg, skipIt)
-    }
-    // unused.
-    /* Commented out because the comment says it is unused.  
-       Probably eliminate eventually.  GAW 2008.05.01
-    def mismatch(expected: Int, found: Int) {
-      val posToReport = this.posToReport
-      val msg =
-        ScannerConfiguration.token2string(expected) + " expected but " +
-        ScannerConfiguration.token2string(found) + " found."
-
-      if (found == EOF)
+      if (in.token == EOF)
         incompleteInputError(msg)
       else
-        syntaxError(posToReport, msg, true)
+        syntaxError(in.offset, msg, skipIt)
     }
-    */
+
+    def expectedMsg(token: Int): String =
+      token2string(token) + " expected but " +token2string(in.token) + " found."
 
     /** Consume one token of the specified type, or
       * signal an error if it is not there.
       */
     def accept(token: Int): Int = {
-      val pos = inCurrentPos
-      if (inToken != token) {
-        val posToReport = 
-          //if (inCurrentPos.line(unit.source).get(0) > in.lastPos.line(unit.source).get(0))
-          //  in.lastPos
-          //else
-            inCurrentPos
-        val msg =
-          ScannerConfiguration.token2string(token) + " expected but " +
-            ScannerConfiguration.token2string(inToken) + " found."
-
-        if (inToken == EOF)
-          incompleteInputError(msg)
-        else
-          syntaxError(posToReport, msg, true)
+      val offset = in.offset
+      if (in.token != token) {
+        syntaxErrorOrIncomplete(expectedMsg(token), false)
+        if ((token == RPAREN || token == RBRACE || token == RBRACKET))
+          if (in.parenBalance(token) + assumedClosingParens(token) < 0) 
+            assumedClosingParens(token) += 1
+          else
+            skip(token)
+        else 
+          skip(UNDEF)
       }
-      if (inToken == token) inNextToken
-      pos
+      if (in.token == token) in.nextToken()
+      offset
     }
-    def surround[T](open : Int, close : Int)(f : => T, orElse : T) : T = {
-      val wasOpened = inToken == open
+
+    def surround[T](open: Int, close: Int)(f: => T, orElse: T): T = {
+      val wasOpened = in.token == open
       accept(open)
       if (wasOpened) {
         val ret = f
@@ -308,48 +394,66 @@ trait Parsers extends NewScanners with MarkupParsers {
         ret
       } else orElse
     }
-    
 
     /** semi = nl {nl} | `;' 
      *  nl  = `\n' // where allowed
      */
-    def acceptStatSep() : Boolean = {
-      if (inToken == NEWLINE || inToken == NEWLINES) { inNextToken; true }
+    def acceptStatSep(): Boolean =
+      if (in.token == NEWLINE || in.token == NEWLINES) { in.nextToken(); true }
       else {
-        val ret = inToken == SEMI
+        val ret = in.token == SEMI
         accept(SEMI)
         ret
       }
+
+    def errorTypeTree = TypeTree().setType(ErrorType).setPos(o2p(in.offset))
+    def errorTermTree = Literal(Constant(null)).setPos(o2p(in.offset))
+    def errorPatternTree = Ident(nme.WILDCARD).setPos(o2p(in.offset))
+
+    /** Check that type parameter is not by name T* */
+    def checkNotByName(t: Tree) = t match {
+      case AppliedTypeTree(Select(_, n), _) =>
+        if (n == nme.BYNAME_PARAM_CLASS_NAME.toTypeName) 
+          syntaxError(t.pos, "no by-name parameter type allowed here", false)
+        else if (n == nme.REPEATED_PARAM_CLASS_NAME.toTypeName)
+          syntaxError(t.pos, "no * parameter type allowed here", false)
+      case _ =>
     }
 
-    def errorTypeTree = TypeTree().setType(ErrorType).setPos((inCurrentPos))
-    def errorTermTree = Literal(Constant(null)).setPos((inCurrentPos))
-    def errorPatternTree = Ident(nme.WILDCARD).setPos((inCurrentPos))
+    /** Check that tree is a legal clause of a forSome */
+    def checkLegalExistential(t: Tree) = t match {
+      case TypeDef(_, _, _, TypeBoundsTree(_, _)) |
+           ValDef(_, _, _, EmptyTree) | EmptyTree =>
+             ;
+      case _ =>
+        syntaxError(t.pos, "not a legal existential clause", false) 
+    }
 
-/////// TOKEN CLASSES //////////////////////////////////////////////////////
+/* -------------- TOKEN CLASSES ------------------------------------------- */
 
-    def isModifier: Boolean = inToken match {
-      case ABSTRACT | FINAL | SEALED | PRIVATE | PROTECTED | OVERRIDE | IMPLICIT | LAZY => true
+    def isModifier: Boolean = in.token match {
+      case ABSTRACT | FINAL | SEALED | PRIVATE |
+           PROTECTED | OVERRIDE | IMPLICIT | LAZY => true
       case _ => false
     }
 
-    def isLocalModifier: Boolean = inToken match {
+    def isLocalModifier: Boolean = in.token match {
       case ABSTRACT | FINAL | SEALED | IMPLICIT | LAZY => true
       case _ => false
     }
 
-    def isDefIntro: Boolean = inToken match {
+    def isDefIntro: Boolean = in.token match {
       case VAL | VAR | DEF | TYPE | OBJECT |
            CASEOBJECT | CLASS | CASECLASS | TRAIT => true
       case _ => false
     }
 
-    def isDclIntro: Boolean = inToken match {
+    def isDclIntro: Boolean = in.token match {
       case VAL | VAR | DEF | TYPE => true
       case _ => false
     }
 
-    def isIdent = inToken == IDENTIFIER || inToken == BACKQUOTED_IDENT
+    def isIdent = in.token == IDENTIFIER || in.token == BACKQUOTED_IDENT
 
     def isExprIntroToken(token: Int): Boolean = token match {
       case CHARLIT | INTLIT | LONGLIT | FLOATLIT | DOUBLELIT |
@@ -359,32 +463,56 @@ trait Parsers extends NewScanners with MarkupParsers {
       case _ => false
     }
 
-    def isExprIntro: Boolean = isExprIntroToken(inToken)
+    def isExprIntro: Boolean = isExprIntroToken(in.token)
 
     def isTypeIntroToken(token: Int): Boolean = token match {
-      case IDENTIFIER | BACKQUOTED_IDENT | THIS | SUPER | USCORE | LPAREN | AT => true
+      case IDENTIFIER | BACKQUOTED_IDENT | THIS |
+           SUPER | USCORE | LPAREN | AT => true
       case _ => false
     }
 
-    def isTypeIntro: Boolean = isTypeIntroToken(inToken)
+    def isTypeIntro: Boolean = isTypeIntroToken(in.token)
 
     def isStatSep(token: Int): Boolean = 
       token == NEWLINE || token == NEWLINES || token == SEMI
     
-    def isStatSep: Boolean = isStatSep(inToken)
+    def isStatSep: Boolean = isStatSep(in.token)
 
 
-/////// COMMENT AND ATTRIBUTE COLLECTION //////////////////////////////////////
+/* --------- COMMENT AND ATTRIBUTE COLLECTION ----------------------------- */
 
     /** Join the comment associated with a definition
     */
     def joinComment(trees: => List[Tree]): List[Tree] = {
-      val buf = in.flushDoc
-      if ((buf ne null) && buf.length > 0) trees map (t => DocDef(buf, t) setPos t.pos)
+      val doc = in.flushDoc
+      if ((doc ne null) && doc.raw.length > 0) {
+        val joined = trees map {
+          t =>
+            val dd = DocDef(doc, t)
+            val defnPos = t.pos
+            val pos = doc.pos.withEnd(defnPos.endOrPoint)
+            dd setPos (if (defnPos.isOpaqueRange) pos else pos.makeTransparent)
+        }
+        joined.find(_.pos.isOpaqueRange) foreach {
+          main =>
+            val mains = List(main)
+            joined foreach { t => if (t ne main) ensureNonOverlapping(t, mains) }
+        }
+        joined
+      }
       else trees
     }
 
-/////// TREE CONSTRUCTION ////////////////////////////////////////////////////
+/* ---------- TREE CONSTRUCTION ------------------------------------------- */
+
+    def atPos[T <: Tree](offset: Int)(t: T): T =
+      global.atPos(r2p(offset, offset, in.lastOffset max offset))(t)
+    def atPos[T <: Tree](start: Int, point: Int)(t: T): T =
+      global.atPos(r2p(start, point, in.lastOffset max start))(t)
+    def atPos[T <: Tree](start: Int, point: Int, end: Int)(t: T): T = 
+      global.atPos(r2p(start, point, end))(t)
+    def atPos[T <: Tree](pos: Position)(t: T): T =
+      global.atPos(pos)(t)
 
     /** Convert tree to formal parameter list
     */
@@ -397,58 +525,53 @@ trait Parsers extends NewScanners with MarkupParsers {
 
     /** Convert tree to formal parameter
     */
-    def convertToParam(tree: Tree): ValDef =
-      atPos(tree.pos) {
-        def removeAsPlaceholder(name: Name) {
-          placeholderParams = placeholderParams filter (_.name != name)
-        }
-        tree match {
-          case Ident(name) =>
-            removeAsPlaceholder(name)
-            ValDef(Modifiers(Flags.PARAM), name, TypeTree(), EmptyTree)
-          case Typed(tree @ Ident(name), tpe) if (tpe.isType) => // get the ident!
-            removeAsPlaceholder(name)
-            ValDef(Modifiers(Flags.PARAM), name, tpe, EmptyTree).setPos(tree.pos)
-          case _ =>
-            syntaxError(tree.pos, "not a legal formal parameter", false)
-            ValDef(Modifiers(Flags.PARAM), nme.ERROR, errorTypeTree, EmptyTree)
-        }
+    def convertToParam(tree: Tree): ValDef = atPos(tree.pos) {
+      def removeAsPlaceholder(name: Name) {
+        placeholderParams = placeholderParams filter (_.name != name)
+      }
+      tree match {
+        case Ident(name) =>
+          removeAsPlaceholder(name)
+          ValDef(Modifiers(Flags.PARAM), name, TypeTree() setPos o2p(tree.pos.endOrPoint), EmptyTree)
+        case Typed(tree @ Ident(name), tpe) if (tpe.isType) => // get the ident!
+          removeAsPlaceholder(name)
+          ValDef(Modifiers(Flags.PARAM), name, tpe, EmptyTree)
+        case _ =>
+          syntaxError(tree.pos, "not a legal formal parameter", false)
+          ValDef(Modifiers(Flags.PARAM), nme.ERROR, errorTypeTree setPos o2p(tree.pos.endOrPoint), EmptyTree)
       }
+    }
 
     /** Convert (qual)ident to type identifier
      */
-    def convertToTypeId(tree: Tree): Tree = tree match {
-      case Ident(name) =>
-        Ident(name.toTypeName).setPos(tree.pos)
-      case Select(qual, name) =>
-        Select(qual, name.toTypeName).setPos(tree.pos)
-      case _ =>
-        syntaxError(tree.pos, "identifier expected", false)
-        errorTypeTree
+    def convertToTypeId(tree: Tree): Tree = atPos(tree.pos) {
+      tree match {
+        case Ident(name) =>
+          Ident(name.toTypeName)
+        case Select(qual, name) =>
+          Select(qual, name.toTypeName)
+        case _ =>
+          syntaxError(tree.pos, "identifier expected", false)
+          errorTypeTree
+      }
     }
 
-    /** make closure from tree staring with a `.' */
-    def makeDotClosure(tree: Tree): Tree = {
-      val pname = freshName(tree.pos, "x$")
-      def insertParam(tree: Tree): Tree = atPos(tree.pos) {
-        tree match {
-          case Ident(name) =>
-            Select(Ident(pname), name)
-          case Select(qual, name) =>
-            Select(insertParam(qual), name)
-          case Apply(fn, args) =>
-            Apply(insertParam(fn), args)
-          case TypeApply(fn, args) =>
-            TypeApply(insertParam(fn), args)
-          case _ =>
-            syntaxError(tree.pos, "cannot convert to closure", false)
-            errorTermTree
-        }
+    /** part {`,' part} */
+    def commaSeparated(part: => Tree): List[Tree] = {
+      val ts = new ListBuffer[Tree] += part
+      while (in.token == COMMA) {
+        in.nextToken()
+        ts += part
       }
-      Function(List(makeSyntheticParam(pname)), insertParam(tree))
+      ts.toList
     }
 
-/////// OPERAND/OPERATOR STACK /////////////////////////////////////////////////
+/* --------- OPERAND/OPERATOR STACK --------------------------------------- */
+
+    /** modes for infix types */
+    object InfixMode extends Enumeration {
+      val FirstOp, LeftOp, RightOp = Value
+    }
 
     var opstack: List[OpInfo] = Nil
 
@@ -479,113 +602,120 @@ trait Parsers extends NewScanners with MarkupParsers {
       if (size > max) syntaxError("too many "+kind+", maximum = "+max, false)
     }
 
-    def checkAssoc(pos: Int, op: Name, leftAssoc: Boolean) = 
+    def checkAssoc(offset: Int, op: Name, leftAssoc: Boolean) = 
       if (treeInfo.isLeftAssoc(op) != leftAssoc)
         syntaxError(
-          pos, "left- and right-associative operators with same precedence may not be mixed", false)
+          offset, "left- and right-associative operators with same precedence may not be mixed", false)
 
-    def reduceStack(isExpr: Boolean, base: List[OpInfo], top0: Tree, prec: Int, leftAssoc: Boolean): Tree = {
+    def reduceStack(isExpr: Boolean, base: List[OpInfo], top0: Tree,
+                    prec: Int, leftAssoc: Boolean): Tree = {
       var top = top0
       if (opstack != base && precedence(opstack.head.operator) == prec)
-        checkAssoc(opstack.head.pos, opstack.head.operator, leftAssoc)
+        checkAssoc(opstack.head.offset, opstack.head.operator, leftAssoc)
       while (opstack != base && 
              (prec < precedence(opstack.head.operator) ||
-              (leftAssoc && prec == precedence(opstack.head.operator)))) {
-        top = atPos(opstack.head.pos) {
-          makeBinop(isExpr, opstack.head.operand, opstack.head.operator, top)
-        }
+              leftAssoc && prec == precedence(opstack.head.operator))) {
+        val opinfo = opstack.head
         opstack = opstack.tail
+        val opPos = r2p(opinfo.offset, opinfo.offset, opinfo.offset+opinfo.operator.length)
+        val lPos = opinfo.operand.pos
+        val start = if (lPos.isDefined) lPos.startOrPoint else  opPos.startOrPoint
+        val rPos = top.pos
+        val end = if (rPos.isDefined) rPos.endOrPoint else opPos.endOrPoint
+        top = atPos(start, opinfo.offset, end) {
+          makeBinop(isExpr, opinfo.operand, opinfo.operator, top, opPos)
+        }
       }
       top
     }
 
-/////// IDENTIFIERS AND LITERALS ////////////////////////////////////////////////////////////
-
+/* -------- IDENTIFIERS AND LITERALS ------------------------------------------- */
 
-    def ident(): Name =
-      if (inToken == IDENTIFIER || inToken == BACKQUOTED_IDENT) {
-        val name = inName.encode
-        inNextToken
+    def ident(skipIt: Boolean): Name =
+      if (in.token == IDENTIFIER || in.token == BACKQUOTED_IDENT) {
+        val name = in.name.encode
+        in.nextToken()
         name
       } else {
-        accept(IDENTIFIER)
+        syntaxErrorOrIncomplete(expectedMsg(IDENTIFIER), skipIt)
         nme.ERROR
       }
 
-    def selector(t: Tree) = 
-      atPos(inCurrentPos)(Select(t, ident()))
-    
+    def ident(): Name = ident(true)
+
+    def selector(t: Tree): Tree = {
+      val point = in.offset
+      //assert(t.pos.isDefined, t)
+      Select(t, ident(false)) setPos r2p(t.pos.startOrPoint, point, in.lastOffset)
+    }
 
     /** Path       ::= StableId
      *              |  [Ident `.'] this
      *  AnnotType ::= Path [`.' type]
      */
     def path(thisOK: Boolean, typeOK: Boolean): Tree = {
+      val start = in.offset
       var t: Tree = null
-      if (inToken == THIS) {
-        t = atPos(inSkipToken) { This(nme.EMPTY.toTypeName) }
-        if (!thisOK || inToken == DOT) {
-          t =  selectors(t, typeOK, accept(DOT))
+      if (in.token == THIS) {
+        in.nextToken()
+        t = atPos(start) { This(nme.EMPTY.toTypeName) }
+        if (!thisOK || in.token == DOT) {
+          t = selectors(t, typeOK, accept(DOT))
         }
-      } else if (inToken == SUPER) {
-	      // val pos = inCurrentPos
-	val pos = inSkipToken
-        val (mix,usePos) = mixinQualifierOpt(pos)      
-        t = atPos(usePos) {
-          Super(nme.EMPTY.toTypeName, mix)
-        }
-        t = atPos(accept(DOT)) { selector(t) }
-        if (inToken == DOT)
-          t = selectors(t, typeOK, inSkipToken)
+      } else if (in.token == SUPER) {
+        in.nextToken()
+        t = atPos(start) { Super(nme.EMPTY.toTypeName, mixinQualifierOpt()) }
+        accept(DOT)
+        t = selector(t)
+        if (in.token == DOT) t = selectors(t, typeOK, in.skipToken())
       } else {
-        val i = atPos(inCurrentPos) { 
-          if (inToken == BACKQUOTED_IDENT) new BackQuotedIdent(ident())
-          else Ident(ident()) 
+        val tok = in.token
+        val name = ident()
+        t = atPos(start) {
+          if (tok == BACKQUOTED_IDENT) new BackQuotedIdent(name)
+          else Ident(name)
         }
-        t = i
-        if (inToken == DOT) {
-          val pos = inSkipToken
-          if (inToken == THIS) {
-            inNextToken
-            t = atPos(i.pos) { This(i.name.toTypeName) }
-            if (!thisOK || inToken == DOT)
+        if (in.token == DOT) {
+          val dotOffset = in.skipToken()
+          if (in.token == THIS) {
+            in.nextToken()
+            t = atPos(start) { This(name.toTypeName) }
+            if (!thisOK || in.token == DOT)
               t = selectors(t, typeOK, accept(DOT))
-          } else if (inToken == SUPER) {
-            inNextToken
-            val (mix,pos) = mixinQualifierOpt(i.pos)
-            t = atPos(pos) { Super(i.name.toTypeName, mix) }
-            t = atPos(accept(DOT)) {selector(t)}
-            if (inToken == DOT)
-              t = selectors(t, typeOK, inSkipToken)
+          } else if (in.token == SUPER) {
+            in.nextToken()
+            t = atPos(start) { Super(name.toTypeName, mixinQualifierOpt()) }
+            accept(DOT)
+            t = selector(t)
+            if (in.token == DOT) t = selectors(t, typeOK, in.skipToken())
           } else {
-            t = selectors(t, typeOK, pos)
+            t = selectors(t, typeOK, dotOffset)
           }
         }
       }
       t
     }
 
-    def selectors(t: Tree, typeOK: Boolean, pos : Int): Tree =
-      if (typeOK && inToken == TYPE) {
-        inNextToken
-        atPos(pos) { SingletonTypeTree(t) }
+    def selectors(t: Tree, typeOK: Boolean, dotOffset: Int): Tree =
+      if (typeOK && in.token == TYPE) {
+        in.nextToken()
+        atPos(t.pos.startOrPoint, dotOffset) { SingletonTypeTree(t) }
       } else {
-        val t1 = atPos(pos) { selector(t); }
-        if (inToken == DOT) { selectors(t1, typeOK, inSkipToken) }
+        val t1 = selector(t)
+        if (in.token == DOT) { selectors(t1, typeOK, in.skipToken()) }
         else t1
       }
 
     /** MixinQualifier ::= `[' Id `]'
     */
-    def mixinQualifierOpt(pos : Position): (Name,Position) =
-      if (inToken == LBRACKET) {
-        inNextToken
-        val pos = inCurrentPos
+    def mixinQualifierOpt(): Name =
+      if (in.token == LBRACKET) {
+        in.nextToken()
         val name = ident().toTypeName
         accept(RBRACKET)
-        (name,pos)
+        name
       } else {
-        (nme.EMPTY.toTypeName,pos)
+        nme.EMPTY.toTypeName
       }
 
     /** StableId ::= Id
@@ -598,105 +728,72 @@ trait Parsers extends NewScanners with MarkupParsers {
     /** QualId ::= Id {`.' Id}
     */
     def qualId(): Tree = {
-      val id = atPos(inCurrentPos) { Ident(ident()) }
-      if (inToken == DOT) { selectors(id, false, inSkipToken) }
+      val start = in.offset
+      val id = atPos(start) { Ident(ident()) }
+      if (in.token == DOT) { selectors(id, false, in.skipToken()) }
       else id
     }
 
     /** SimpleExpr    ::= literal
-    *                  | symbol
-    *                  | null
-    */
-      
-    def literal(isPattern: Boolean, isNegated: Boolean): Tree = {
-      def litToTree() = atPos(inCurrentPos) {
-        Literal(
-          inToken match {
-            case CHARLIT => Constant(charVal)
-            case INTLIT =>  Constant(intVal(isNegated))
-            case LONGLIT => Constant(longVal(isNegated))
-            case FLOATLIT =>Constant(floatVal(isNegated))
-            case DOUBLELIT => Constant(doubleVal(isNegated))
-            case STRINGLIT | SYMBOLLIT => Constant(stringVal)
-            case TRUE => Constant(true)
-            case FALSE => Constant(false)
-            case NULL => Constant(null)
-            case _ =>
-              syntaxErrorOrIncomplete("illegal literal", true)
-              null
-          })
-      }
-
-      val isSymLit = inToken == SYMBOLLIT
-      val t = litToTree()
-      val pos = inSkipToken
-      if (isSymLit) {
-        atPos(pos) {
-          var symid = scalaDot(nme.Symbol)
-          Apply(symid, List(t))
+     *                  | symbol
+     *                  | null
+     *  @note  The returned tree does not yet have a position 
+     */
+    def literal(isNegated: Boolean): Tree = {
+      val isSymLit = in.token == SYMBOLLIT
+      val t = Literal {
+        in.token match {
+          case CHARLIT   => Constant(in.charVal)
+          case INTLIT    => Constant(in.intVal(isNegated).toInt)
+          case LONGLIT   => Constant(in.intVal(isNegated))
+          case FLOATLIT  => Constant(in.floatVal(isNegated).toFloat)
+          case DOUBLELIT => Constant(in.floatVal(isNegated))
+          case STRINGLIT | SYMBOLLIT => Constant(in.strVal)
+          case TRUE      => Constant(true)
+          case FALSE     => Constant(false)
+          case NULL      => Constant(null)
+          case _ =>
+            syntaxErrorOrIncomplete("illegal literal", true)
+            Constant(null)
         }
-      } else {
-        t
       }
+      in.nextToken()
+      if (isSymLit) Apply(scalaDot(nme.Symbol), List(t)) else t
     }
 
+/* ------------- NEW LINES ------------------------------------------------- */
+
     def newLineOpt() {
-      if (inToken == NEWLINE) inNextToken
+      if (in.token == NEWLINE) in.nextToken()
     }
 
     def newLinesOpt() {
-      if (inToken == NEWLINE || inToken == NEWLINES)
-        inNextToken
+      if (in.token == NEWLINE || in.token == NEWLINES)
+        in.nextToken()
     }
 
     def newLineOptWhenFollowedBy(token: Int) {
       // note: next is defined here because current == NEWLINE
-      if (inToken == NEWLINE && inNextTokenCode == token) newLineOpt()
+      if (in.token == NEWLINE && in.next.token == token) newLineOpt()
     }
 
     def newLineOptWhenFollowing(p: Int => Boolean) {
       // note: next is defined here because current == NEWLINE
-      if (inToken == NEWLINE && p(inNextTokenCode)) newLineOpt()
+      if (in.token == NEWLINE && p(in.next.token)) newLineOpt()
     }
 
-//////// TYPES ///////////////////////////////////////////////////////////////
+/* ------------- TYPES ---------------------------------------------------- */
 
     /** TypedOpt ::= [`:' Type]
-    */
+     */
     def typedOpt(): Tree =
-      if (inToken == COLON) { inNextToken; typ() } 
+      if (in.token == COLON) { in.nextToken(); typ() } 
       else TypeTree()
 
-    /** RequiresTypedOpt ::= [requires AnnotType]
-    */
-    def requiresTypeOpt(): Tree =
-      if (inToken == REQUIRES) { 
-        deprecationWarning(in.currentPos, "`requires T' has been deprecated; use `{ self: T => ...'  instead")
-        inNextToken; annotType(false)
-      } else TypeTree()
-
     /** Types ::= Type {`,' Type} 
-     *  (also eats trailing comma if it finds one)
-     */
-    def types(isPattern: Boolean, isTypeApply: Boolean, isFuncArg: Boolean): List[Tree] = {
-      val ts = new ListBuffer[Tree] + argType(isPattern, isTypeApply, isFuncArg)
-      while (inToken == COMMA) {
-        val pos = inCurrentPos
-        inNextToken
-        if (inToken == RPAREN) {
-          deprecationWarning(pos, "Trailing commas have been deprecated")
-          return ts.toList
-        } else {
-          ts += argType(isPattern, isTypeApply, isFuncArg)
-        }
-      }
-      ts.toList
-    }
-
-    /** modes for infix types */
-    object InfixMode extends Enumeration {
-      val FirstOp, LeftOp, RightOp = Value
-    }
+     */
+    def types(isPattern: Boolean, isTypeApply: Boolean, isFuncArg: Boolean): List[Tree] =
+      commaSeparated(argType(isPattern, isTypeApply, isFuncArg))
 
     /** Type ::= InfixType `=>' Type
      *         | `(' [`=>' Type] `)' `=>' Type
@@ -707,51 +804,43 @@ trait Parsers extends NewScanners with MarkupParsers {
     def typ(): Tree = typ(false)
 
     def typ(isPattern: Boolean): Tree = placeholderTypeBoundary {
+      val start = in.offset
       val t = 
-        if (inToken == LPAREN) {
-          val pos = inSkipToken
-          if (inToken == RPAREN) {
-            inNextToken
-            atPos(accept(ARROW)) { makeFunctionTypeTree(List(), typ(isPattern)) }
-          /* Not more used
-          } else if (inToken == ARROW) {
-            inNextToken
-            val t0 = typ(isPattern)
-            accept(RPAREN)
-            atPos(accept(ARROW)) { makeByNameFunctionTypeTree(t0, typ(isPattern)) }
-          */
+        if (in.token == LPAREN) {
+          in.nextToken()
+          if (in.token == RPAREN) {
+            in.nextToken()
+            atPos(start, accept(ARROW)) { 
+              makeFunctionTypeTree(List(), typ(isPattern)) 
+            }
           } else {
             val ts = types(isPattern, false, true)
             accept(RPAREN)
-            if (inToken == ARROW) atPos(inSkipToken) { makeFunctionTypeTree(ts, typ(isPattern)) }
-            else {
-              for (t <- ts) t match {
-                case AppliedTypeTree(Select(_, n), _) 
-                if (n == nme.BYNAME_PARAM_CLASS_NAME.toTypeName) =>
-                  syntaxError(t.pos, "no by-name parameter type allowed here", false)
-                case _ =>
+            if (in.token == ARROW) 
+              atPos(start, in.skipToken()) {
+                makeFunctionTypeTree(ts, typ(isPattern))
               }
-              infixTypeRest(pos, annotTypeRest(pos, isPattern, makeTupleType(ts, true)), false, InfixMode.FirstOp)
+            else {
+              ts foreach checkNotByName
+              val tuple = atPos(start) { makeTupleType(ts, true) }
+              infixTypeRest(
+                compoundTypeRest(
+                  annotTypeRest(simpleTypeRest(tuple, isPattern)),
+                  isPattern),
+                isPattern, InfixMode.FirstOp)
             }
           }
         } else {
           infixType(isPattern, InfixMode.FirstOp)
         }
-      if (inToken == ARROW)
-        atPos(inSkipToken) { 
+      if (in.token == ARROW)
+        atPos(start, in.skipToken()) { 
           makeFunctionTypeTree(List(t), typ(isPattern)) 
         }
-      else if (inToken == FORSOME)
-        atPos(inSkipToken) {
+      else if (in.token == FORSOME)
+        atPos(start, in.skipToken()) {
           val whereClauses = refinement()
-          for (wc <- whereClauses) {
-            wc match {
-              case TypeDef(_, _, _, TypeBoundsTree(_, _)) | ValDef(_, _, _, EmptyTree) | EmptyTree =>
-                ;
-              case _ =>
-                syntaxError(wc.pos, "not a legal where clause", false) 
-            }
-          }
+          whereClauses foreach checkLegalExistential
           ExistentialTypeTree(t, whereClauses)
         }
       else t
@@ -760,24 +849,20 @@ trait Parsers extends NewScanners with MarkupParsers {
     /** InfixType ::= CompoundType {id [nl] CompoundType} 
      */
     def infixType(isPattern: Boolean, mode: InfixMode.Value): Tree = placeholderTypeBoundary {
-      infixTypeRest(inCurrentPos, infixTypeFirst(isPattern), isPattern, mode)
+      infixTypeRest(compoundType(isPattern), isPattern, mode)
     }
 
-    def infixTypeFirst(isPattern: Boolean) = 
-      if (inToken == LBRACE) scalaAnyRefConstr else annotType(isPattern)
-
-    def infixTypeRest(pos: Int, t0: Tree, isPattern: Boolean, mode: InfixMode.Value): Tree = {
-      val t = compoundTypeRest(pos, t0, isPattern)
-      if (isIdent && inName != nme.STAR) {
-        val opPos = inCurrentPos
-        val leftAssoc = treeInfo.isLeftAssoc(inName)
-        if (mode == InfixMode.LeftOp) checkAssoc(opPos, inName, true)
-        else if (mode == InfixMode.RightOp) checkAssoc(opPos, inName, false)
+    def infixTypeRest(t: Tree, isPattern: Boolean, mode: InfixMode.Value): Tree = {
+      if (isIdent && in.name != nme.STAR) {
+        val opOffset = in.offset
+        val leftAssoc = treeInfo.isLeftAssoc(in.name)
+        if (mode != InfixMode.FirstOp) checkAssoc(opOffset, in.name, mode == InfixMode.LeftOp)
         val op = ident()
+        val tycon = atPos(opOffset) { Ident(op.toTypeName) }
         newLineOptWhenFollowing(isTypeIntroToken)
-        def mkOp(t1: Tree) = atPos(opPos) { AppliedTypeTree(Ident(op.toTypeName), List(t, t1)) }
+        def mkOp(t1: Tree) = atPos(t.pos.startOrPoint, opOffset) { AppliedTypeTree(tycon, List(t, t1)) }
         if (leftAssoc)
-          infixTypeRest(inCurrentPos, mkOp(compoundType(isPattern)), isPattern, InfixMode.LeftOp)
+          infixTypeRest(mkOp(compoundType(isPattern)), isPattern, InfixMode.LeftOp)
         else
           mkOp(infixType(isPattern, InfixMode.RightOp))
       } else t
@@ -786,72 +871,93 @@ trait Parsers extends NewScanners with MarkupParsers {
     /** CompoundType ::= AnnotType {with AnnotType} [Refinement] 
      *                |  Refinement
      */  
-    def compoundType(isPattern: Boolean): Tree =
-      compoundTypeRest(inCurrentPos, infixTypeFirst(isPattern), isPattern)
+    def compoundType(isPattern: Boolean): Tree = {
+      val t = if (in.token == LBRACE) atPos(o2p(in.offset)) (scalaAnyRefConstr)
+              else annotType(isPattern)
+      compoundTypeRest(t, isPattern)
+    }
 
-    def compoundTypeRest(pos: Int, t: Tree, isPattern: Boolean): Tree = {
-      var ts = new ListBuffer[Tree] + t
-      while (inToken == WITH) {
-        inNextToken; ts += annotType(isPattern)
+    def compoundTypeRest(t: Tree, isPattern: Boolean): Tree = {
+      var ts = new ListBuffer[Tree] += t
+      while (in.token == WITH) {
+        in.nextToken(); ts += annotType(isPattern)
       }
       newLineOptWhenFollowedBy(LBRACE)
-      atPos(pos) {
-        if (inToken == LBRACE) 
+      atPos(t.pos.startOrPoint) {
+        if (in.token == LBRACE) {
+          // Warn if they are attempting to refine Unit; we can't be certain it's
+          // scala.Unit they're refining because at this point all we have is an
+          // identifier, but at a later stage we lose the ability to tell an empty
+          // refinement from no refinement at all.  See bug #284.
+          for (Ident(name) <- ts) name.toString match {
+            case "Unit" | "scala.Unit"  =>
+              warning("Detected apparent refinement of Unit; are you missing an '=' sign?")
+            case _ =>
+          }
           CompoundTypeTree(Template(ts.toList, emptyValDef, refinement()))
+        }
         else 
           makeIntersectionTypeTree(ts.toList)
       }
     }
 
     /** AnnotType        ::=  SimpleType {Annotation}
-     *  SimpleType       ::=  SimpleType TypeArgs 
+     */
+    def annotType(isPattern: Boolean): Tree = placeholderTypeBoundary {
+      annotTypeRest(simpleType(isPattern))
+    }
+
+    def annotTypeRest(t: Tree): Tree = 
+      (t /: annotations(false, false)) (makeAnnotated)
+
+    /** SimpleType       ::=  SimpleType TypeArgs 
      *                     |  SimpleType `#' Id
      *                     |  StableId
      *                     |  Path `.' type
-     *                     |  `(' Types [`,'] `)'
+     *                     |  `(' Types `)'
      *                     |  WildcardType
      */
-    def annotType(isPattern: Boolean): Tree = placeholderTypeBoundary {
-      val pos = inCurrentPos
-      
-      val t: Tree = annotTypeRest(pos, isPattern,
-        if (inToken == LPAREN) {
-          inNextToken
+    def simpleType(isPattern: Boolean): Tree = {
+      val start = in.offset
+      val t = 
+        if (in.token == LPAREN) {
+          in.nextToken()
           val ts = types(isPattern, false, false)
           accept(RPAREN)
-          atPos(pos) { makeTupleType(ts, true) }
-        } else if (inToken == USCORE) {
-          wildcardType(in.skipToken)
-        } else {
-          val r = path(false, true)
-          r match {
-            case SingletonTypeTree(_) => r
-            case _ => convertToTypeId(r)
-          }
-        })
-      (t /: annotations(false)) (makeAnnotated)
+          atPos(start) { makeTupleType(ts, true) }
+        } else if (in.token == USCORE) {
+          wildcardType(in.skipToken())
+        } else path(false, true) match {
+          case r @ SingletonTypeTree(_) => r
+          case r => convertToTypeId(r)
+        }
+      simpleTypeRest(t, isPattern)
     }
 
-    def annotTypeRest(pos: Int, isPattern: Boolean, t: Tree): Tree =
-      if (inToken == HASH) {
-        inSkipToken
-        val posId = inCurrentPos
-        val id = ident
-        annotTypeRest(pos, isPattern, atPos(posId) { SelectFromTypeTree(t, id.toTypeName) })
-      } else if (inToken == LBRACKET) {
-        val usePos = if (t.pos != NoPosition) t.pos else i2p(pos)
-        annotTypeRest(pos, isPattern, atPos(usePos) { AppliedTypeTree(t, typeArgs(isPattern, false)) })
-      }
-      else
+    def simpleTypeRest(t: Tree, isPattern: Boolean): Tree =
+      if (in.token == HASH) {
+        val hashOffset = in.skipToken()
+        val nameOffset = in.offset
+        val name = ident(false)
+        val sel = atPos(t.pos.startOrPoint, if (name == nme.ERROR) hashOffset else nameOffset) {
+          SelectFromTypeTree(t, name.toTypeName)
+        }
+        simpleTypeRest(sel, isPattern)
+      } else if (in.token == LBRACKET) {
+        simpleTypeRest(atPos(t.pos.startOrPoint) { AppliedTypeTree(t, typeArgs(isPattern, false)) }, isPattern)
+      } else {
         t
+      }
 
     /** WildcardType ::= `_' TypeBounds
      */
-    def wildcardType(pos: Int) = {
-      val pname = freshName(pos, "_$").toTypeName
-      val param = atPos(pos) { makeSyntheticTypeParam(pname, typeBounds()) }
+    def wildcardType(start: Int) = {
+      val pname = freshName(o2p(start), "_$").toTypeName
+      val t = atPos(start) { Ident(pname) }
+      val bounds = typeBounds()
+      val param = atPos(t.pos union bounds.pos) { makeSyntheticTypeParam(pname, bounds) }
       placeholderTypes = param :: placeholderTypes
-      Ident(pname) setPos pos
+      t
     }
 
     /** TypeArgs    ::= `[' ArgType {`,' ArgType} `]'
@@ -865,42 +971,37 @@ trait Parsers extends NewScanners with MarkupParsers {
 
     /** ArgType       ::=  Type
      */ 
-    def argType(isPattern: Boolean, isTypeApply: Boolean, isFuncArg: Boolean): Tree =
+    def argType(isPattern: Boolean, isTypeApply: Boolean, isFuncArg: Boolean): Tree = {
+      val start = in.offset
       if (isPattern) {
-        if (inToken == USCORE)
-          if (inToken == SUBTYPE || inToken == SUPERTYPE) wildcardType(inSkipToken)
-          else atPos(inSkipToken) { Bind(nme.WILDCARD.toTypeName, EmptyTree) }
-        else if (inToken == IDENTIFIER && treeInfo.isVariableName(inName.toTypeName))
-          atPos(inCurrentPos) { 
-            Bind(ident().toTypeName, EmptyTree) 
-          }
-        else {
+        if (in.token == USCORE) {
+          in.nextToken()
+          if (in.token == SUBTYPE || in.token == SUPERTYPE) wildcardType(start)
+          else atPos(start) { Bind(nme.WILDCARD.toTypeName, EmptyTree) }
+        } else if (in.token == IDENTIFIER && treeInfo.isVariableName(in.name.toTypeName)) {
+          atPos(start) { Bind(ident().toTypeName, EmptyTree) }
+        } else {
           typ(true) 
         }
       } else if (isFuncArg) {
         // copy-paste (with change) from def paramType
-        if (inToken == ARROW)
-          atPos(inSkipToken) {
-            AppliedTypeTree(
-                scalaDot(nme.BYNAME_PARAM_CLASS_NAME.toTypeName), List(typ()))
-          }
-        else {
+        if (in.token == ARROW) {
+          in.nextToken()
+          val tycon = atPos(start) { rootScalaDot(nme.BYNAME_PARAM_CLASS_NAME.toTypeName) }
+          atPos(start) { AppliedTypeTree(tycon, List(typ())) }
+        } else {
           val t = typ()
-          if (isIdent && inName == STAR) {
-            inNextToken
-            atPos(t.pos) { 
-              AppliedTypeTree(
-                scalaDot(nme.REPEATED_PARAM_CLASS_NAME.toTypeName), List(t))
-            }
+          if (isIdent && in.name == STAR) {
+            val tycon = atPos(in.skipToken()) { rootScalaDot(nme.REPEATED_PARAM_CLASS_NAME.toTypeName) }
+            atPos(start) { AppliedTypeTree(tycon, List(t)) }
           } else t
         }
-      } else if (isTypeApply) {
-        typ()
       } else {
         typ()
       }
-    
-//////// EXPRESSIONS ////////////////////////////////////////////////////////
+    }
+
+/* ----------- EXPRESSIONS ------------------------------------------------ */    
 
     /** EqualsExpr ::= `=' Expr
      */
@@ -909,32 +1010,29 @@ trait Parsers extends NewScanners with MarkupParsers {
       expr()
     }
 
-    /** Exprs ::= Expr {`,' Expr} 
-     *  
-     *  (also eats trailing comma if it finds one)
-     */
-    def exprs(): List[Tree] = {    
-      val ts = new ListBuffer[Tree] + expr()     
-      while (inToken == COMMA) {
-        val pos = in.currentPos
-        inNextToken
-        if (inToken == RPAREN) {
-          deprecationWarning(pos, "Trailing commas have been deprecated")
-          return ts.toList
-        } else {
-          ts += expr()
-        }
+    def condExpr(): Tree = {
+      if (in.token == LPAREN) {
+        in.nextToken()
+        val r = expr()
+        accept(RPAREN)
+        r
+      } else {
+        accept(LPAREN)
+        Literal(true)
       }
-      ts.toList
     }
 
+    /* hook for IDE, unlike expression can be stubbed
+     * don't use for any tree that can be inspected in the parser!
+     */
+    def statement(location: Int): Tree = expr(location) // !!! still needed?
 
-    /** Expr       ::= (Bindings | Id | `_')  `=>' Expr
+    /** Expr       ::= (Bindings | [`implicit'] Id | `_')  `=>' Expr
      *               | Expr1
      *  ResultExpr ::= (Bindings | Id `:' CompoundType) `=>' Block
      *               | Expr1
      *  Expr1      ::= if `(' Expr `)' {nl} Expr [[semi] else Expr]
-     *               | try `{' Block `}' [catch `{' CaseClauses `}'] [finally Expr]
+     *               | try (`{' Block `}' | Expr) [catch `{' CaseClauses `}'] [finally Expr]
      *               | while `(' Expr `)' {nl} Expr
      *               | do Expr [semi] while `(' Expr `)'
      *               | for (`(' Enumerators `)' | '{' Enumerators '}') {nl} [yield] Expr
@@ -951,144 +1049,158 @@ trait Parsers extends NewScanners with MarkupParsers {
      *               | `:' `_' `*'
      */
     def expr(): Tree = expr(Local)
-    /* hook for IDE, unlike expression can be stubbed
-     * don't use for any tree that can be inspected in the parser!
-     */
-    def statement(location: Int): Tree = expr(location)
+
     def expr(location: Int): Tree = {
-      def isWildcard(t: Tree): Boolean = t match {
-        case Ident(name1) if !placeholderParams.isEmpty && name1 == placeholderParams.head.name => true
-        case Typed(t1, _) => isWildcard(t1)
-        case Annotated(t1, _) => isWildcard(t1)
-        case _ => false
-      }
       var savedPlaceholderParams = placeholderParams
       placeholderParams = List()
-      var res = inToken match {
-        case IF =>
-          val pos = inSkipToken
-          val cond = surround(LPAREN,RPAREN)(expr(),Literal(true))
+      var res = expr0(location)
+      if (!placeholderParams.isEmpty && !isWildcard(res)) {
+        res = atPos(res.pos){ Function(placeholderParams.reverse, res) }
+        placeholderParams = List()
+      }
+      placeholderParams = placeholderParams ::: savedPlaceholderParams
+      res
+    }
+
+    def expr0(location: Int): Tree = in.token match {
+      case IF =>
+        atPos(in.skipToken()) {
+          val cond = condExpr()
           newLinesOpt()
           val thenp = expr()
-          val elsep =
-            if (inToken == ELSE) { inNextToken; expr() }
+          val elsep = if (in.token == ELSE) { in.nextToken(); expr() }
+                      else Literal(())
+          If(cond, thenp, elsep) 
+        }
+      case TRY =>
+        atPos(in.skipToken()) {
+          val body =
+            if (in.token == LBRACE) surround(LBRACE, RBRACE)(block(), Literal(()))
+            else if (in.token == LPAREN) surround(LPAREN, RPAREN)(expr(), Literal(()))
+            else expr()
+          val catches = 
+            if (in.token == CATCH) { 
+              in.nextToken()
+              surround(LBRACE, RBRACE)(caseClauses(), Nil)
+            } else Nil
+          val finalizer = 
+            if (in.token == FINALLY) { in.nextToken(); expr() }
             else EmptyTree
-          atPos(pos) { If(cond, thenp, elsep) }
-        case TRY =>
-          atPos(inSkipToken) {
-            val body = surround(LBRACE,RBRACE)(block(), Literal(()))
-            val catches = 
-              if (inToken == CATCH) { 
-                inNextToken
-                val cases = surround(LBRACE,RBRACE)(caseClauses(), Nil)
-                cases
-              } else List()
-            val finalizer = 
-              if (inToken == FINALLY) { inNextToken; expr() }
-              else EmptyTree
-            Try(body, catches, finalizer)
-          }
-        case WHILE =>
-          val pos = inSkipToken
-          val lname: Name = freshName(pos, "while$")
-          val cond = surround(LPAREN,RPAREN)(expr(),Literal(true))
+          Try(body, catches, finalizer)
+        }
+      case WHILE =>
+        val start = in.offset
+        atPos(in.skipToken()) {
+          val lname: Name = freshName(o2p(start), "while$")
+          val cond = condExpr()
           newLinesOpt()
           val body = expr()
-          atPos(pos) { makeWhile(lname, cond, body) }
-        case DO =>
-          val pos = inSkipToken
-          val lname: Name = freshName(pos, "doWhile$")
+          makeWhile(lname, cond, body) 
+        }
+      case DO =>
+        val start = in.offset
+        atPos(in.skipToken()) {
+          val lname: Name = freshName(o2p(start), "doWhile$")
           val body = expr()
-          if (isStatSep) inNextToken
+          if (isStatSep) in.nextToken()
           accept(WHILE)
-          val cond = surround(LPAREN,RPAREN)(expr(), Literal(true))
-          atPos(pos) { makeDoWhile(lname, body, cond) }
-        case FOR =>
-          atPos(inSkipToken) {
-            val startToken = inToken
-            val (open,close) = if (startToken == LBRACE) (LBRACE,RBRACE) else (LPAREN,RPAREN)
-            val enums = surround(open,close)(enumerators(), Nil)
-            newLinesOpt()
-            if (inToken == YIELD) {
-              inNextToken; makeForYield(enums, expr())
-            } else makeFor(enums, expr())
-          }
-        case RETURN =>
-          atPos(inSkipToken) {
-            Return(if (isExprIntro) expr() else Literal(()))
-          }
-        case THROW =>
-          atPos(inSkipToken) { 
-            Throw(expr()) 
+          val cond = condExpr()
+          makeDoWhile(lname, body, cond) 
+        }
+      case FOR =>
+        atPos(in.skipToken()) {
+          val (open, close) = if (in.token == LBRACE) (LBRACE, RBRACE) else (LPAREN, RPAREN)
+          val enums = surround(open, close)(enumerators(), Nil)
+          newLinesOpt()
+          if (in.token == YIELD) {
+            in.nextToken()
+            makeForYield(enums, expr())
+          } else {
+            makeFor(enums, expr())
           }
-        case DOT =>
-          deprecationWarning(in.currentPos, "`.f' has been deprecated; use `_.f'  instead")
-          atPos(inSkipToken) {
-            if (isIdent) {
-              makeDotClosure(stripParens(simpleExpr()))
-            } else {
-              syntaxErrorOrIncomplete("identifier expected", true)
-              errorTermTree 
-            }
+        }
+      case RETURN =>
+        atPos(in.skipToken()) {
+          Return(if (isExprIntro) expr() else Literal(()))
+        }
+      case THROW =>
+        atPos(in.skipToken()) { 
+          Throw(expr()) 
+        }
+      case IMPLICIT =>
+        implicitClosure(in.skipToken(), location)
+      case _ =>
+        var t = postfixExpr()
+        if (in.token == EQUALS) {
+          t match {
+            case Ident(_) | Select(_, _) | Apply(_, _) =>
+              t = atPos(t.pos.startOrPoint, in.skipToken()) { makeAssign(t, expr()) }
+            case _ => 
           }
-        case _ =>
-          var t = postfixExpr()
-          if (inToken == EQUALS) {
-            t match {
-              case Ident(_) | Select(_, _) | Apply(_, _) =>
-                t = atPos(inSkipToken) { makeAssign(t, expr()) }
-              case _ => 
-            }
-          } else if (inToken == COLON) {
-            t = stripParens(t)
-            val pos = inSkipToken
-            if (inToken == USCORE) {
-              //todo: need to handle case where USCORE is a wildcard in a type
-              val pos1 = inSkipToken
-              if (isIdent && inName == nme.STAR) {
-                inNextToken
-                t = atPos(pos) {
-                  Typed(t, atPos(pos1) { Ident(nme.WILDCARD_STAR.toTypeName) })
-                }
-              } else {
-                syntaxErrorOrIncomplete("`*' expected", true)
+        } else if (in.token == COLON) {
+          t = stripParens(t)
+          val colonPos = in.skipToken()
+          if (in.token == USCORE) {
+            //todo: need to handle case where USCORE is a wildcard in a type
+            val uscorePos = in.skipToken()
+            if (isIdent && in.name == nme.STAR) {
+              in.nextToken()
+              t = atPos(t.pos.startOrPoint, colonPos) {
+                Typed(t, atPos(uscorePos) { Ident(nme.WILDCARD_STAR.toTypeName) })
               }
-            } else if (in.token == AT) {
-              t = (t /: annotations(false)) (makeAnnotated)
             } else {
-              t = atPos(pos) { 
-                val tpt = 
-                  if (location != Local) infixType(false, InfixMode.FirstOp) 
-                  else typ()
-                if (isWildcard(t))
-                  (placeholderParams: @unchecked) match {
-                    case (vd @ ValDef(mods, name, _, _)) :: rest => 
-                      placeholderParams = copy.ValDef(vd, mods, name, tpt.duplicate, EmptyTree) :: rest
-                  }
-                // this does not correspond to syntax, but is necessary to 
-                // accept closures. We might restrict closures to be between {...} only!
-                Typed(t, tpt)
-              }
+              syntaxErrorOrIncomplete("`*' expected", true)
             }
-          } else if (inToken == MATCH) {
-            t = atPos(inSkipToken) {
-              val cases = surround(LBRACE,RBRACE)(caseClauses(), Nil)
-              Match(stripParens(t), cases)
+          } else if (in.token == AT) {
+            t = (t /: annotations(false, false)) (makeAnnotated)
+          } else {
+            t = atPos(t.pos.startOrPoint, colonPos) { 
+              val tpt = 
+                if (location == Local) typ() else infixType(false, InfixMode.FirstOp) 
+              if (isWildcard(t))
+                (placeholderParams: @unchecked) match {
+                  case (vd @ ValDef(mods, name, _, _)) :: rest => 
+                    placeholderParams = treeCopy.ValDef(vd, mods, name, tpt.duplicate, EmptyTree) :: rest
+                }
+              // this does not correspond to syntax, but is necessary to 
+              // accept closures. We might restrict closures to be between {...} only.
+              Typed(t, tpt)
             }
           }
-          if (inToken == ARROW && location != InTemplate) {
-            t = atPos(inSkipToken) {
-              Function(convertToParams(t), if (location == Local) expr() else block())
-            }
+        } else if (in.token == MATCH) {
+          t = atPos(t.pos.startOrPoint, in.skipToken()) {
+            /** For debugging pattern matcher transition issues */
+            if (settings.Ypmatnaive.value)
+              makeSequencedMatch(stripParens(t), surround(LBRACE, RBRACE)(caseClauses(), Nil))
+            else
+              Match(stripParens(t), surround(LBRACE, RBRACE)(caseClauses(), Nil))
           }
-          stripParens(t)
-      }
-      if (!placeholderParams.isEmpty && !isWildcard(res)) {
-        res = atPos(res.pos){ Function(placeholderParams.reverse, res) }
-        placeholderParams = List()
+        }
+        // in order to allow anonymous functions as statements (as opposed to expressions) inside
+        // templates, we have to disambiguate them from self type declarations - bug #1565
+        // The case still missed is unparenthesized single argument, like "x: Int => x + 1", which
+        // may be impossible to distinguish from a self-type and so remains an error.  (See #1564)
+        def lhsIsTypedParamList() = t match {
+          case Parens(xs) if xs forall (_.isInstanceOf[Typed]) => true
+          case _ => false
+        }
+        if (in.token == ARROW && (location != InTemplate || lhsIsTypedParamList)) {
+          t = atPos(t.pos.startOrPoint, in.skipToken()) {
+            Function(convertToParams(t), if (location != InBlock) expr() else block())
+          }
+        }
+        stripParens(t)
+    }
+
+    /** Expr ::= implicit Id => Expr
+     */
+    def implicitClosure(start: Int, location: Int): Tree = {
+      val param0 = convertToParam(atPos(in.offset)(Ident(ident())))
+      val param = treeCopy.ValDef(param0, param0.mods | Flags.IMPLICIT, param0.name, param0.tpt, param0.rhs)
+      atPos(start, in.offset) {
+        accept(ARROW)
+        Function(List(param), if (location != InBlock) expr() else block())
       }
-      placeholderParams = placeholderParams ::: savedPlaceholderParams
-      res
     }
 
     /** PostfixExpr   ::= InfixExpr [Id [nl]]
@@ -1098,21 +1210,29 @@ trait Parsers extends NewScanners with MarkupParsers {
     def postfixExpr(): Tree = {
       val base = opstack
       var top = prefixExpr()
+      // Various errors in XML literals can cause xmlLiteral to propagate
+      // EmptyTree's. Watch out for them here.
+      if (top == EmptyTree)
+        return EmptyTree
+
       while (isIdent) {
-        top = reduceStack(
-          true, base, top, precedence(inName), treeInfo.isLeftAssoc(inName))
-        val op = inName
-        opstack = OpInfo(top, op, inCurrentPos) :: opstack
+        top = reduceStack(true, base, top, precedence(in.name), treeInfo.isLeftAssoc(in.name))
+        val op = in.name
+        opstack = OpInfo(top, op, in.offset) :: opstack
         ident()
         newLineOptWhenFollowing(isExprIntroToken)
         if (isExprIntro) {
-          top = prefixExpr()
+          val next = prefixExpr()
+          if (next == EmptyTree)
+            return reduceStack(true, base, top, 0, true)
+          top = next
         } else {
           val topinfo = opstack.head
           opstack = opstack.tail
-          return Select(
-            stripParens(reduceStack(true, base, topinfo.operand, 0, true)),
-            topinfo.operator.encode).setPos(topinfo.pos)
+          val od = stripParens(reduceStack(true, base, topinfo.operand, 0, true))
+          return atPos(od.pos.startOrPoint, topinfo.offset) {
+            Select(od, topinfo.operator.encode)
+          }
         }
       }
       reduceStack(true, base, top, 0, true)
@@ -1122,28 +1242,20 @@ trait Parsers extends NewScanners with MarkupParsers {
     */
     def prefixExpr(): Tree = {
       def unaryOp(): Name = "unary_" + ident()
-      if (isIdent && inName == MINUS) {
-        val name = unaryOp()
-        inToken match {
-          case INTLIT | LONGLIT | FLOATLIT | DOUBLELIT => literal(false, true)
-          case _ => atPos(inCurrentPos) { Select(stripParens(simpleExpr()), name) }
+      if (isIdent && in.name == MINUS) {
+        atPos(in.offset) {
+          val name = unaryOp()
+          in.token match {
+            // Don't include double and float here else we lose -0.0
+            case INTLIT | LONGLIT => literal(true)
+            case _ => Select(stripParens(simpleExpr()), name)
+          }
+        }
+      } else if (isIdent && (in.name == PLUS || in.name == TILDE || in.name == BANG)) {
+        atPos(in.offset) {
+          val name = unaryOp()
+          Select(stripParens(simpleExpr()), name)
         }
-      } else if (isIdent && (inName == PLUS || inName == TILDE || inName == BANG)) {
-        val pos = inCurrentPos
-        val name = unaryOp()
-        atPos(pos) { Select(stripParens(simpleExpr()), name) }
-      } else if (isIdent && inName == AMP) {
-        deprecationWarning(in.currentPos, "`&f' has been deprecated; use `f _' instead")
-        val pos = inCurrentPos
-        val name = ident()
-        atPos(pos) { Typed(stripParens(simpleExpr()), Function(List(), EmptyTree)) }
-/* XX-LIFTING
-      } else if (settings.Xexperimental.value && isIdent && inName == SLASH) {
-        val pos = inSkipToken
-        val name = freshName()
-        liftedGenerators += ValFrom(pos, Bind(name, Ident(nme.WILDCARD)), simpleExpr())
-        Ident(name) setPos pos
-*/
       } else {
         simpleExpr()
       }
@@ -1156,91 +1268,119 @@ trait Parsers extends NewScanners with MarkupParsers {
      * SimpleExpr1   ::= literal
      *                |  xLiteral
      *                |  Path
-     *                |  `(' [Exprs [`,']] `)'
+     *                |  `(' [Exprs] `)'
      *                |  SimpleExpr `.' Id 
      *                |  SimpleExpr TypeArgs
      *                |  SimpleExpr1 ArgumentExprs
      */
     def simpleExpr(): Tree = {
-      var t: Tree = null
       var canApply = true
-      inToken match {
+      val t = in.token match {
         case CHARLIT | INTLIT | LONGLIT | FLOATLIT | DOUBLELIT | STRINGLIT | 
              SYMBOLLIT | TRUE | FALSE | NULL =>
-          t = literal(false, false)
-        case XMLSTART => t = xmlLiteral()
+          atPos(in.offset) { literal(false) }
+        case XMLSTART => 
+          xmlLiteral()
         case IDENTIFIER | BACKQUOTED_IDENT | THIS | SUPER =>
-          t = path(true, false)
+          path(true, false)
         case USCORE =>
-          val pos = inSkipToken
-          val pname = freshName(pos, "x$")
-          val param = atPos(pos){ makeSyntheticParam(pname) }
+          val start = in.offset
+          val pname = freshName(o2p(start), "x$")
+          in.nextToken()
+          val id = atPos(start) (Ident(pname))
+          val param = atPos(id.pos.focus){ makeSyntheticParam(pname) }
           placeholderParams = param :: placeholderParams
-          t = atPos(pos) { Ident(pname) }
+          id
         case LPAREN =>
-          val pos = inSkipToken
-          val ts = if (inToken == RPAREN) List() else exprs()
-          accept(RPAREN)
-          t = Parens(ts) setPos (pos)
+          atPos(in.skipToken()) {
+            val ts = if (in.token == RPAREN) List() else commaSeparated(expr)
+            accept(RPAREN)
+            Parens(ts)
+          }
         case LBRACE =>
-          t = blockExpr()
           canApply = false
+          blockExpr()
         case NEW =>
-          t = atPos(inSkipToken) {
-            val (parents, argss, self, stats) = template(false)
-            makeNew(parents, self, stats, argss)
-          }
           canApply = false
+          val nstart = in.skipToken()
+          val npos = r2p(nstart, nstart, in.lastOffset)
+          val tstart = in.offset
+          val (parents, argss, self, stats) = template(false)
+          val cpos = r2p(tstart, tstart, in.lastOffset max tstart)
+          makeNew(parents, self, stats, argss, npos, cpos)
         case _ =>
           syntaxErrorOrIncomplete("illegal start of simple expression", true)
-          t = errorTermTree
+          errorTermTree
       }
       simpleExprRest(t, canApply)
     }
 
     def simpleExprRest(t: Tree, canApply: Boolean): Tree = {
+      // Various errors in XML literals can cause xmlLiteral to propagate
+      // EmptyTree's. Watch out for them here (see also postfixExpr).
+      if (EmptyTree == t) return EmptyTree   // #3604 (mics)
       if (canApply) newLineOptWhenFollowedBy(LBRACE)
-      inToken match {
+      in.token match {
         case DOT =>
-          simpleExprRest(atPos(inSkipToken) { selector(stripParens(t)) }, true)
+          in.nextToken()
+          simpleExprRest(selector(stripParens(t)), true)
         case LBRACKET =>
           val t1 = stripParens(t)
           t1 match {
             case Ident(_) | Select(_, _) =>
-              val pos = if (t1.pos == NoPosition) i2p(inCurrentPos) else t1.pos
-              simpleExprRest(atPos(pos) { TypeApply(t1, typeArgs(false, true)) }, true)
+              val tapp = atPos(t1.pos.startOrPoint, in.offset) { 
+                TypeApply(t1, typeArgs(false, true))
+              }
+              simpleExprRest(tapp, true)
             case _ =>
               t1
           }
         case LPAREN | LBRACE if (canApply) =>
-          // again, position should be on idetifier, not (
-          var pos = if (t.pos == NoPosition) i2p(inCurrentPos) else t.pos
-          simpleExprRest(atPos(pos) { Apply(stripParens(t), argumentExprs()) }, true)
+          val app = atPos(t.pos.startOrPoint, in.offset) {
+            // look for anonymous function application like (f _)(x) and
+            // translate to (f _).apply(x), bug #460
+            val sel = t match {
+              case Parens(List(Typed(_, _: Function))) =>
+                Select(stripParens(t), nme.apply)
+              case _ =>
+                stripParens(t)
+            }
+            Apply(sel, argumentExprs())
+          }
+          simpleExprRest(app, true)
         case USCORE =>
-          atPos(inSkipToken) { Typed(stripParens(t), Function(List(), EmptyTree)) }
+          atPos(t.pos.startOrPoint, in.skipToken()) { 
+            Typed(stripParens(t), Function(List(), EmptyTree)) 
+          }
         case _ =>
           t
       }
     }
 
-    /** ArgumentExprs ::= `(' [Exprs [`,']] `)'
+    /** ArgumentExprs ::= `(' [Exprs] `)'
       *                 | [nl] BlockExpr
      */
     def argumentExprs(): List[Tree] = {
-      if (inToken == LBRACE) {
-        List(blockExpr())
-      } else {
-        val ts = surround(LPAREN,RPAREN)(if (inToken == RPAREN) List() else exprs(), List())
-        ts
+      def args(): List[Tree] = commaSeparated {
+        val maybeNamed = isIdent
+        expr() match {
+          case a @ Assign(id, rhs) if maybeNamed =>
+            atPos(a.pos) { AssignOrNamedArg(id, rhs) }
+          case e => e
+        }
       }
-    }
 
+      if (in.token == LBRACE)
+        List(blockExpr())
+      else
+        surround(LPAREN, RPAREN)(if (in.token == RPAREN) List() else args(), List())
+    }
+        
     /** BlockExpr ::= `{' (CaseClauses | Block) `}'
      */
     def blockExpr(): Tree = {
-      assert(inToken == LBRACE)
       val res = atPos(accept(LBRACE)) { // no need to surround
-        if (inToken == CASE) Match(EmptyTree, caseClauses())
+        if (in.token == CASE) Match(EmptyTree, caseClauses())
         else block()
       }
       accept(RBRACE)
@@ -1248,16 +1388,18 @@ trait Parsers extends NewScanners with MarkupParsers {
     }
     
     /** Block ::= BlockStatSeq
+     *  @note  Return tree does not carry position.
      */
-    def block(): Tree = 
+    def block(): Tree = {
       makeBlock(blockStatSeq(new ListBuffer[Tree]))
+    }
 
    /** CaseClauses ::= CaseClause {CaseClause} 
     */
     def caseClauses(): List[CaseDef] = {
       val ts = new ListBuffer[CaseDef]
       do { ts += caseClause()
-      } while (inToken == CASE)
+      } while (in.token == CASE)
       ts.toList
     }
 
@@ -1269,14 +1411,14 @@ trait Parsers extends NewScanners with MarkupParsers {
         val gd = guard()
         makeCaseDef(pat, gd, caseBlock())
       }
-    // IDE HOOK (so we can memoize case blocks)
+    // IDE HOOK (so we can memoize case blocks) // needed?
     def caseBlock(): Tree = 
       atPos(accept(ARROW))(block())
 
     /** Guard ::= if PostfixExpr
      */
     def guard(): Tree = 
-      if (inToken == IF) { inNextToken; stripParens(postfixExpr()) } 
+      if (in.token == IF) { in.nextToken(); stripParens(postfixExpr()) } 
       else EmptyTree
       
     /** Enumerators ::= Generator {semi Enumerator}
@@ -1285,19 +1427,19 @@ trait Parsers extends NewScanners with MarkupParsers {
      *                |  val Pattern1 `=' Expr
      */
     def enumerators(): List[Enumerator] = {
-      val newStyle = inToken != VAL // todo: deprecate old style
-      //if (!newStyle)
-      //  deprecationWarning(inCurrentPos, "for (val x <- ... ) has been deprecated; use for (x <- ... ) instead")
+      val newStyle = in.token != VAL // todo: deprecate old style
+      if (!newStyle)
+        deprecationWarning(in.offset, "for (val x <- ... ) has been deprecated; use for (x <- ... ) instead")
       val enums = new ListBuffer[Enumerator]
       generator(enums, false)
       while (isStatSep) {
-        inNextToken
+        in.nextToken()
         if (newStyle) {
-          if (inToken == IF) enums += Filter(guard())
+          if (in.token == IF) enums += makeFilter(in.offset, guard())
           else generator(enums, true)
         } else {
-          if (inToken == VAL) generator(enums, true) 
-          else enums += Filter(expr())
+          if (in.token == VAL) generator(enums, true) 
+          else enums += makeFilter(in.offset, expr())
         }
       }
       enums.toList
@@ -1306,51 +1448,40 @@ trait Parsers extends NewScanners with MarkupParsers {
     /** Generator ::= Pattern1 (`<-' | '=') Expr [Guard]
      */
     def generator(enums: ListBuffer[Enumerator], eqOK: Boolean) {
-      if (inToken == VAL) inNextToken
-      val pos = inCurrentPos;
+      val start = in.offset
+      if (in.token == VAL) in.nextToken()
       val pat = pattern1(false)
-      val tok = inToken
-      if (tok == EQUALS && eqOK) inNextToken
+      val point = in.offset
+      val tok = in.token
+      if (tok == EQUALS && eqOK) in.nextToken()
       else accept(LARROW)
-      enums += makeGenerator(pos, pat, tok == EQUALS, expr)
-      if (inToken == IF) enums += Filter(guard())
+      val rhs = expr()
+      enums += makeGenerator(r2p(start, point, in.lastOffset), pat, tok == EQUALS, rhs)
+      while (in.token == IF) enums += makeFilter(in.offset, guard())
     }
-    //def p2i(pos : ScanPosition) : Int;
 
-//////// PATTERNS ////////////////////////////////////////////////////////////
+    def makeFilter(start: Int, tree: Tree) = Filter(r2p(start, tree.pos.point, tree.pos.endOrPoint), tree)
+
+/* -------- PATTERNS ------------------------------------------- */    
 
     /**   Patterns ::= Pattern { `,' Pattern }  
      *    SeqPatterns ::= SeqPattern { `,' SeqPattern }  
-     *  
-     *  (also eats trailing comma if it finds one)
-     */
-    def patterns(seqOK: Boolean): List[Tree] = {
-      val ts = new ListBuffer[Tree] + pattern(seqOK)
-      while (inToken == COMMA) {
-        val pos = inCurrentPos
-        inNextToken 
-        if (inToken == RPAREN) {
-          deprecationWarning(pos, "Trailing commas have been deprecated")
-          return ts.toList
-        } else {
-          ts += pattern(seqOK)
-        }
-      }
-      ts.toList
-    }
+     */
+    def patterns(seqOK: Boolean): List[Tree] =
+      commaSeparated(pattern(seqOK))
 
     /**   Pattern  ::=  Pattern1 { `|' Pattern1 }
      *    SeqPattern ::= SeqPattern1 { `|' SeqPattern1 }
      */
     def pattern(seqOK: Boolean): Tree = {
-      val pos = inCurrentPos
+      val start = in.offset
       val t = pattern1(seqOK)
-      if (isIdent && inName == BAR) {
-        val ts = new ListBuffer[Tree] + t
-        while (isIdent && inName == BAR) {
-          inNextToken; ts += pattern1(seqOK)
+      if (isIdent && in.name == BAR) {
+        val ts = new ListBuffer[Tree] += t
+        while (isIdent && in.name == BAR) {
+          in.nextToken(); ts += pattern1(seqOK)
         }
-        atPos(pos) { makeAlternative(ts.toList) }
+        atPos(start) { makeAlternative(ts.toList) }
       } else t
     }
 
@@ -1364,17 +1495,13 @@ trait Parsers extends NewScanners with MarkupParsers {
      *                 |  [SeqPattern2]
      */
     def pattern1(seqOK: Boolean): Tree = {
-      //if (false && /*disabled, no regexp matching*/ seqOK && !isExprIntro) {
-        //atPos(inCurrentPos) { Sequence(List()) }
-      //} else {
-        val p = pattern2(seqOK)
-        p match {
-          case Ident(name) if (treeInfo.isVarPattern(p) && inToken == COLON) =>
-            atPos(inSkipToken) { Typed(p, compoundType(true)) }
-          case _ =>
-            p
-        }
-      //}
+      val p = pattern2(seqOK)
+      p match {
+        case Ident(name) if (treeInfo.isVarPattern(p) && in.token == COLON) =>
+          atPos(p.pos.startOrPoint, in.skipToken()) { Typed(p, compoundType(true)) }
+        case _ =>
+          p
+      }
     }
 
     /*   Pattern2    ::=  varid [ @ Pattern3 ]
@@ -1384,14 +1511,15 @@ trait Parsers extends NewScanners with MarkupParsers {
      */
     def pattern2(seqOK: Boolean): Tree = {
       val p = pattern3(seqOK)
-      if (inToken == AT) {
+      if (in.token == AT) {
         p match {
           case Ident(name) =>
             if (name == nme.WILDCARD) {
-              inNextToken; pattern3(seqOK)
+              in.nextToken() 
+              pattern3(seqOK)
             } else if (treeInfo.isVarPattern(p)) {
-              inNextToken
-              atPos(p.pos) { Bind(name, pattern3(seqOK)) }
+              in.nextToken()
+              atPos(p.pos.startOrPoint) { Bind(name, pattern3(seqOK)) }
             } else {
               p
             }
@@ -1409,115 +1537,126 @@ trait Parsers extends NewScanners with MarkupParsers {
     def pattern3(seqOK: Boolean): Tree = {
       val base = opstack
       var top = simplePattern(seqOK)
-      if (seqOK && isIdent) {
-        if (inName == STAR)
-          return atPos(inSkipToken)(Star(stripParens(top)))
-        else if (inName == PLUS)
-          return atPos(inSkipToken)(makePlus(stripParens(top)))
-        else if (inName == OPT)
-          return atPos(inSkipToken)(makeOpt(stripParens(top)))
-      }
-      while (isIdent && inName != BAR) {
+      // See ticket #3189 for the motivation for the null check.
+      // TODO: dredge out the remnants of regexp patterns.
+      // ... and now this is back the way it was because it caused #3480.
+      if (seqOK && isIdent && in.name == STAR)
+        return atPos(top.pos.startOrPoint, in.skipToken())(Star(stripParens(top)))
+          
+      while (isIdent && in.name != BAR) {
         top = reduceStack(
-          false, base, top, precedence(inName), treeInfo.isLeftAssoc(inName))
-        val op = inName
-        opstack = OpInfo(top, op, inCurrentPos) :: opstack
+          false, base, top, precedence(in.name), treeInfo.isLeftAssoc(in.name))
+        val op = in.name
+        opstack = OpInfo(top, op, in.offset) :: opstack
         ident()
         top = simplePattern(seqOK)
       }
       stripParens(reduceStack(false, base, top, 0, true))
     }
      
-    def xmlLiteralPattern() : Tree 
+    def xmlLiteralPattern(): Tree 
 
     /** SimplePattern    ::= varid
      *                    |  `_'
      *                    |  literal
      *                    |  XmlPattern
-     *                    |  StableId  [TypeArgs] [`(' [SeqPatterns [`,']] `)']
-     *                    |  `(' [Patterns [`,']] `)'
+     *                    |  StableId  [TypeArgs] [`(' [SeqPatterns] `)']
+     *                    |  `(' [Patterns] `)'
      *  SimpleSeqPattern ::= varid
      *                    |  `_'
      *                    |  literal
      *                    |  XmlPattern
      *                    |  `<' xLiteralPattern 
-     *                    |  StableId [TypeArgs] [`(' [SeqPatterns [`,']] `)']
-     *                    |  `(' [SeqPatterns [`,']] `)'
+     *                    |  StableId [TypeArgs] [`(' [SeqPatterns] `)']
+     *                    |  `(' [SeqPatterns] `)'
      * 
      * XXX: Hook for IDE
      */
-    def simplePattern(seqOK: Boolean): Tree = inToken match {
-      case IDENTIFIER | BACKQUOTED_IDENT | THIS =>
-        var t = stableId()
-        inToken match {
-          case INTLIT | LONGLIT | FLOATLIT | DOUBLELIT =>
-            t match {
-              case Ident(name) if name == nme.MINUS =>
-                return literal(true, true)
-              case _ =>
-            }
-          case _ =>
-        }
-/* not yet
-        if (inToken == LBRACKET)
-          atPos(inCurrentPos) {
-            val ts = typeArgs(true, false)
-            accept(LPAREN)
-            val ps = if (inToken == RPAREN) List() else patterns(true, false)
+    def simplePattern(seqOK: Boolean): Tree = {
+      val start = in.offset
+      in.token match {
+        case IDENTIFIER | BACKQUOTED_IDENT | THIS =>
+          var t = stableId()
+          in.token match {
+            case INTLIT | LONGLIT | FLOATLIT | DOUBLELIT =>
+              t match {
+                case Ident(name) if name == nme.MINUS =>
+                  return atPos(start) { literal(true) }
+                case _ =>
+              }
+            case _ =>
+          }
+          /* not yet
+           if (in.token == LBRACKET)
+           atPos(in.offset) {
+           val ts = typeArgs(true, false)
+           accept(LPAREN)
+           val ps = if (in.token == RPAREN) List() else patterns(true, false)
+           accept(RPAREN)
+           Apply(TypeApply(convertToTypeId(t), ts), ps)
+           }
+           else */
+          if (in.token == LPAREN)
+            atPos(start, in.offset) { Apply(t, argumentPatterns()) }
+          else t
+        case USCORE =>
+          in.nextToken()
+          atPos(start, start) { Ident(nme.WILDCARD) }
+        case CHARLIT | INTLIT | LONGLIT | FLOATLIT | DOUBLELIT |
+             STRINGLIT | SYMBOLLIT | TRUE | FALSE | NULL =>
+          atPos(start) { literal(false) }
+        case LPAREN =>
+          in.nextToken()
+          atPos(start) {
+            val ps = if (in.token == RPAREN) List() else patterns(false)
             accept(RPAREN)
-            Apply(TypeApply(convertToTypeId(t), ts), ps)
+            Parens(ps)
           }
-        else */
-        if (inToken == LPAREN) {
-          atPos(t.pos) { Apply(t, argumentPatterns()) }
-        } else t
-      case USCORE =>
-        atPos(inSkipToken) { Ident(nme.WILDCARD) }
-      case CHARLIT | INTLIT | LONGLIT | FLOATLIT | DOUBLELIT | STRINGLIT | SYMBOLLIT | TRUE | FALSE | NULL =>
-        literal(true, false)
-      case LPAREN =>
-        val pos = inSkipToken
-        val ps = if (inToken == RPAREN) List() else patterns(false)
-        accept(RPAREN)
-        Parens(ps) setPos (pos)
-      case XMLSTART => xmlLiteralPattern()
-      case _ =>
-        syntaxErrorOrIncomplete("illegal start of simple pattern", true)
-        errorPatternTree
+        case XMLSTART =>
+          xmlLiteralPattern()
+        case _ =>
+          syntaxErrorOrIncomplete("illegal start of simple pattern", true)
+          errorPatternTree
+      }
     }
 
     def argumentPatterns(): List[Tree] = {
       accept(LPAREN)
-      val ps = if (inToken == RPAREN) List() else patterns(true)
+      val ps = if (in.token == RPAREN) List() else patterns(true)
       accept(RPAREN)
       ps
     }
 
-////////// MODIFIERS and ANNOTATIONS /////////////////////////////////////////////////
+/* -------- MODIFIERS and ANNOTATIONS ------------------------------------------- */    
 
+    /** Drop `private' modifier when followed by a qualifier.
+     *  Conract `abstract' and `override' to ABSOVERRIDE
+     */
     private def normalize(mods: Modifiers): Modifiers = 
       if ((mods hasFlag Flags.PRIVATE) && mods.privateWithin != nme.EMPTY.toTypeName)
-        mods &~ Flags.PRIVATE
+        normalize(mods &~ Flags.PRIVATE)
       else if ((mods hasFlag Flags.ABSTRACT) && (mods hasFlag Flags.OVERRIDE))
-        mods &~ (Flags.ABSTRACT | Flags.OVERRIDE) | Flags.ABSOVERRIDE
+        normalize(mods &~ (Flags.ABSTRACT | Flags.OVERRIDE) | Flags.ABSOVERRIDE)
       else
         mods
 
-    private def addMod(mods: Modifiers, mod: Long): Modifiers = {
-      if (mods hasFlag mod) syntaxError(inCurrentPos, "repeated modifier", false)
-      inNextToken
-      mods | mod
+    private def addMod(mods: Modifiers, mod: Long, pos: Position): Modifiers = {
+      if (mods hasFlag mod) syntaxError(in.offset, "repeated modifier", false)
+      in.nextToken()
+      (mods | mod) withPosition (mod, pos)
     }
 
+    private def tokenRange(token: TokenData) = r2p(token.offset, token.offset, token.offset + token.name.length - 1)
+
     /** AccessQualifier ::= "[" (Id | this) "]"
      */
-    def accessQualifierOpt(mods: Modifiers) = {
+    def accessQualifierOpt(mods: Modifiers): Modifiers = {
       var result = mods
-      if (inToken == LBRACKET) {
-        inNextToken
+      if (in.token == LBRACKET) {
+        in.nextToken()
         if (mods.privateWithin != nme.EMPTY.toTypeName)
           syntaxError("duplicate private/protected qualifier", false)
-        result = if (inToken == THIS) { inNextToken; mods | Flags.LOCAL }
+        result = if (in.token == THIS) { in.nextToken(); mods | Flags.LOCAL }
                  else Modifiers(mods.flags, ident().toTypeName)
         accept(RBRACKET)
       }
@@ -1527,9 +1666,9 @@ trait Parsers extends NewScanners with MarkupParsers {
     /** AccessModifier ::= (private | protected) [AccessQualifier]
      */
     def accessModifierOpt(): Modifiers = normalize {
-      inToken match {
-        case PRIVATE => inNextToken; accessQualifierOpt(Modifiers(Flags.PRIVATE))
-        case PROTECTED => inNextToken; accessQualifierOpt(Modifiers(Flags.PROTECTED))
+      in.token match {
+        case PRIVATE => in.nextToken(); accessQualifierOpt(Modifiers(Flags.PRIVATE))
+        case PROTECTED => in.nextToken(); accessQualifierOpt(Modifiers(Flags.PROTECTED))
         case _ => NoMods
       }
     }
@@ -1540,23 +1679,26 @@ trait Parsers extends NewScanners with MarkupParsers {
      *             |  override
      */
     def modifiers(): Modifiers = normalize {
-      def loop(mods: Modifiers): Modifiers = inToken match {
+      def loop(mods: Modifiers): Modifiers = in.token match {
         case ABSTRACT =>
-          loop(addMod(mods, Flags.ABSTRACT))
+          loop(addMod(mods, Flags.ABSTRACT, tokenRange(in)))
         case FINAL =>
-          loop(addMod(mods, Flags.FINAL))
+          loop(addMod(mods, Flags.FINAL, tokenRange(in)))
         case SEALED =>
-          loop(addMod(mods, Flags.SEALED))
+          loop(addMod(mods, Flags.SEALED, tokenRange(in)))
         case PRIVATE =>
-          loop(accessQualifierOpt(addMod(mods, Flags.PRIVATE)))
+          loop(accessQualifierOpt(addMod(mods, Flags.PRIVATE, tokenRange(in))))
         case PROTECTED =>
-          loop(accessQualifierOpt(addMod(mods, Flags.PROTECTED)))
+          loop(accessQualifierOpt(addMod(mods, Flags.PROTECTED, tokenRange(in))))
         case OVERRIDE =>
-          loop(addMod(mods, Flags.OVERRIDE))
+          loop(addMod(mods, Flags.OVERRIDE, tokenRange(in)))
         case IMPLICIT =>
-          loop(addMod(mods, Flags.IMPLICIT))
+          loop(addMod(mods, Flags.IMPLICIT, tokenRange(in)))
         case LAZY =>
-          loop(addMod(mods, Flags.LAZY))
+          loop(addMod(mods, Flags.LAZY, tokenRange(in)))
+        case NEWLINE =>
+          in.nextToken()
+          loop(mods)
         case _ =>
           mods
       }
@@ -1567,150 +1709,143 @@ trait Parsers extends NewScanners with MarkupParsers {
      *  LocalModifier  ::= abstract | final | sealed | implicit | lazy
      */
     def localModifiers(): Modifiers = {
-      def loop(mods: Modifiers): Modifiers = inToken match {
+      def loop(mods: Modifiers): Modifiers = in.token match {
         case ABSTRACT =>
-          loop(addMod(mods, Flags.ABSTRACT))
+          loop(addMod(mods, Flags.ABSTRACT, tokenRange(in)))
         case FINAL =>
-          loop(addMod(mods, Flags.FINAL))
+          loop(addMod(mods, Flags.FINAL, tokenRange(in)))
         case SEALED =>
-          loop(addMod(mods, Flags.SEALED))
+          loop(addMod(mods, Flags.SEALED, tokenRange(in)))
         case IMPLICIT =>
-          loop(addMod(mods, Flags.IMPLICIT))
+          loop(addMod(mods, Flags.IMPLICIT, tokenRange(in)))
         case LAZY =>
-          loop(addMod(mods, Flags.LAZY))
+          loop(addMod(mods, Flags.LAZY, tokenRange(in)))
         case _ =>
           mods
       }
       loop(NoMods)
     }
 
-    /** Annotations   ::= {Annotation [nl]} 
-     *  Annotation    ::= `@' AnnotationExpr
+    /** Annotations      ::= {`@' SimpleType {ArgumentExprs}}
+     *  ConsrAnnotations ::= {`@' SimpleType ArgumentExprs}
      */
-    def annotations(skipNewLines: Boolean): List[Annotation] = {
-      var annots = new ListBuffer[Annotation]
-      while (inToken == AT) {
-        inNextToken
-        annots += annotationExpr()
+    def annotations(skipNewLines: Boolean, requireOneArgList: Boolean): List[Tree] = {
+      var annots = new ListBuffer[Tree]
+      while (in.token == AT) {
+        in.nextToken()
+        annots += annotationExpr(requireOneArgList)
         if (skipNewLines) newLineOpt()
       }
       annots.toList
     }
 
-    /** AnnotationExpr ::= StableId [TypeArgs] [`(' [Exprs] `)'] [[nl] `{' {NameValuePair} `}']
-     *  NameValuePair ::= val id `=' PrefixExpr
-     */
-    def annotationExpr(): Annotation = {
-      def nameValuePair(): Tree = {
-        var pos = inCurrentPos
-        accept(VAL)
-        val aname = ident()
-        accept(EQUALS)
-        val rhs = stripParens(prefixExpr())
-        atPos(pos) { ValDef(NoMods, aname, TypeTree(), rhs) }
-      }
-      val pos = inCurrentPos
-      var t: Tree = convertToTypeId(stableId())
-      if (inToken == LBRACKET)
-        t = atPos(inCurrentPos)(AppliedTypeTree(t, typeArgs(false, false)))
-      val args = if (inToken == LPAREN) argumentExprs() else List()
-      newLineOptWhenFollowedBy(LBRACE)
-      val nameValuePairs: List[Tree] = if (inToken == LBRACE) {
-        inNextToken
-        val nvps = new ListBuffer[Tree] + nameValuePair()
-        while (inToken == COMMA) {
-          inNextToken
-          nvps += nameValuePair()
-        }
-        accept(RBRACE)
-        nvps.toList
-      } else List()
-      val constr = atPos(pos) { New(t, List(args)) }
-      Annotation(constr, nameValuePairs) setPos pos
+    def annotationExpr(requireOneArgList: Boolean): Tree = {
+      atPos(in.offset) {
+        val t = simpleType(false)
+        val argss = new ListBuffer[List[Tree]]
+        if (requireOneArgList)
+          argss += argumentExprs()
+        else if (in.token == LPAREN)
+          do { argss += argumentExprs() } while (in.token == LPAREN)
+        else argss += List()
+        New(t, argss.toList)
+      }
     }
 
-//////// PARAMETERS //////////////////////////////////////////////////////////
+/* -------- PARAMETERS ------------------------------------------- */    
 
     /** ParamClauses      ::= {ParamClause} [[nl] `(' implicit Params `)']
      *  ParamClause       ::= [nl] `(' [Params] ')'
      *  Params            ::= Param {`,' Param}
-     *  Param             ::= {Annotation} Id [`:' ParamType]
+     *  Param             ::= {Annotation} Id [`:' ParamType] [`=' Expr]
      *  ClassParamClauses ::= {ClassParamClause} [[nl] `(' implicit ClassParams `)']
      *  ClassParamClause  ::= [nl] `(' [ClassParams] ')'
      *  ClassParams       ::= ClassParam {`,' ClassParam}
-     *  ClassParam        ::= {Annotation}  [{Modifier} (`val' | `var')] Id [`:' ParamType]
+     *  ClassParam        ::= {Annotation}  [{Modifier} (`val' | `var')] Id [`:' ParamType] [`=' Expr]
      */
-    def paramClauses(owner: Name, implicitViews: List[Tree], ofCaseClass: Boolean): List[List[ValDef]] = {
+    def paramClauses(owner: Name, contextBounds: List[Tree], ofCaseClass: Boolean): List[List[ValDef]] = {
       var implicitmod = 0
       var caseParam = ofCaseClass
       def param(): ValDef = {
-        var pos = inCurrentPos
-        
-        {
-          val annots = annotations(false)
-          var mods = Modifiers(Flags.PARAM)
-          if (owner.isTypeName) {
-            mods = modifiers() | Flags.PARAMACCESSOR
-            if (mods.hasFlag(Flags.LAZY)) syntaxError("lazy modifier not allowed here. Use call-by-name parameters instead", false)
-            if (inToken == VAL) {
-              inNextToken 
-            } else if (inToken == VAR) { 
-              mods = mods | Flags.MUTABLE
-              inNextToken 
-            } else {
-              if (mods.flags != Flags.PARAMACCESSOR) accept(VAL)
-              if (!(caseParam)) mods = mods | Flags.PRIVATE | Flags.LOCAL
+        val start = in.offset
+        val annots = annotations(false, false)
+        var mods = Modifiers(Flags.PARAM)
+        if (owner.isTypeName) {
+          mods = modifiers() | Flags.PARAMACCESSOR
+          if (mods.hasFlag(Flags.LAZY)) syntaxError("lazy modifier not allowed here. Use call-by-name parameters instead", false)
+          if (in.token == VAL) {
+            mods = mods withPosition (in.token, tokenRange(in))
+            in.nextToken() 
+          } else if (in.token == VAR) { 
+            mods = mods withPosition (in.token, tokenRange(in))
+            mods |= Flags.MUTABLE
+            in.nextToken() 
+          } else {
+            if (mods.flags != Flags.PARAMACCESSOR) accept(VAL)
+            if (!caseParam) {
+              mods |= Flags.PRIVATE | Flags.LOCAL
             }
-            if (caseParam) mods = mods | Flags.CASEACCESSOR
           }
-          val namePos = inCurrentPos
-          val name = ident()
-          if (name != nme.ERROR) pos = namePos
-          var bynamemod = 0
-          val tpt =
-            if (settings.Xexperimental.value && !owner.isTypeName && inToken != COLON) {
-              TypeTree()
-            } else { // XX-METHOD-INFER
-              accept(COLON)
-              if (inToken == ARROW) {
-                if (owner.isTypeName && !mods.hasFlag(Flags.LOCAL))
-                  syntaxError(
-                    inCurrentPos, 
-                    (if (mods.hasFlag(Flags.MUTABLE)) "`var'" else "`val'") +
-                    " parameters may not be call-by-name", false)
-                else bynamemod = Flags.BYNAMEPARAM
-              }
-              paramType()
+          if (caseParam) {
+            mods |= Flags.CASEACCESSOR
+          }
+        }
+        val nameOffset = in.offset
+        val name = ident()
+        var bynamemod = 0
+        val tpt =
+          if (settings.YmethodInfer.value && !owner.isTypeName && in.token != COLON) {
+            TypeTree()
+          } else { // XX-METHOD-INFER
+            accept(COLON)
+            if (in.token == ARROW) {
+              if (owner.isTypeName && !mods.hasFlag(Flags.LOCAL))
+                syntaxError(
+                  in.offset, 
+                  (if (mods.hasFlag(Flags.MUTABLE)) "`var'" else "`val'") +
+                  " parameters may not be call-by-name", false)
+              else if (implicitmod != 0)
+                syntaxError(
+                  in.offset, 
+                  "implicit parameters may not be call-by-name", false)
+              else bynamemod = Flags.BYNAMEPARAM
             }
-          atPos(pos){
-            ValDef((mods | implicitmod | bynamemod) withAnnotations annots, name, tpt, EmptyTree)
+            paramType()
           }
+        val default =
+          if (in.token == EQUALS) {
+            in.nextToken()
+            mods |= Flags.DEFAULTPARAM
+            expr()
+          } else EmptyTree
+        atPos(start, if (name == nme.ERROR) start else nameOffset) {
+          ValDef((mods | implicitmod | bynamemod) withAnnotations annots, name, tpt, default)
         }
       }
       def paramClause(): List[ValDef] = {
         val params = new ListBuffer[ValDef]
-        if (inToken != RPAREN) {
-          if (inToken == IMPLICIT) {
-            if (!implicitViews.isEmpty)
-              syntaxError("cannot have both view bounds `<%' and implicit parameters", false)
-            inNextToken
+        if (in.token != RPAREN) {
+          if (in.token == IMPLICIT) {
+            if (!contextBounds.isEmpty)
+              syntaxError("cannot have both implicit parameters and context bounds `: ...' or view bounds `<% ...' on type parameters", false)
+            in.nextToken()
             implicitmod = Flags.IMPLICIT 
           }
           params += param()
-          while (inToken == COMMA) {
-            inNextToken; params += param()
+          while (in.token == COMMA) {
+            in.nextToken(); params += param()
           }
         }
         params.toList
       }
       val vds = new ListBuffer[List[ValDef]]
-      val pos = inCurrentPos
+      val start = in.offset
       newLineOptWhenFollowedBy(LPAREN)
-      if (ofCaseClass && inToken != LPAREN)
-        deprecationWarning(in.currentPos, "case classes without a parameter list have been deprecated;\n"+
+      if (ofCaseClass && in.token != LPAREN)
+        deprecationWarning(in.offset, "case classes without a parameter list have been deprecated;\n"+
                            "use either case objects or case classes with `()' as parameter list.")
-      while (implicitmod == 0 && inToken == LPAREN) {
-        inNextToken
+      while (implicitmod == 0 && in.token == LPAREN) {
+        in.nextToken()
         vds += paramClause()
         accept(RPAREN)
         caseParam = false
@@ -1720,76 +1855,86 @@ trait Parsers extends NewScanners with MarkupParsers {
       if (owner == nme.CONSTRUCTOR && 
           (result.isEmpty || 
            (!result.head.isEmpty && result.head.head.mods.hasFlag(Flags.IMPLICIT))))
-        if (inToken == LBRACKET)
-          syntaxError(pos, "no type parameters allowed here", false)
-        else if(inToken == EOF)
+        if (in.token == LBRACKET)
+          syntaxError(in.offset, "no type parameters allowed here", false)
+        else if(in.token == EOF)
           incompleteInputError("auxiliary constructor needs non-implicit parameter list")
         else
-          syntaxError(pos, "auxiliary constructor needs non-implicit parameter list", false)
-      addImplicitViews(owner, result, implicitViews)
+          syntaxError(start, "auxiliary constructor needs non-implicit parameter list", false)
+      addEvidenceParams(owner, result, contextBounds)
     }
 
     /** ParamType ::= Type | `=>' Type | Type `*'
      */
     def paramType(): Tree =
-      if (inToken == ARROW)
-        atPos(inSkipToken) {
+      if (in.token == ARROW) {
+        atPos(in.skipToken()) {
           AppliedTypeTree(
-              scalaDot(nme.BYNAME_PARAM_CLASS_NAME.toTypeName), List(typ()))
+            rootScalaDot(nme.BYNAME_PARAM_CLASS_NAME.toTypeName), List(typ()))
         }
-      else {
+      } else {
         val t = typ()
-        if (isIdent && inName == STAR) {
-          inNextToken
-          atPos(t.pos) { 
+        if (isIdent && in.name == STAR) {
+          in.nextToken()
+          atPos(t.pos.startOrPoint, t.pos.point) { 
             AppliedTypeTree(
-              scalaDot(nme.REPEATED_PARAM_CLASS_NAME.toTypeName), List(t))
+              rootScalaDot(nme.REPEATED_PARAM_CLASS_NAME.toTypeName), List(t))
           }
         } else t
       }
 
     /** TypeParamClauseOpt    ::= [TypeParamClause]
      *  TypeParamClause       ::= `[' VariantTypeParam {`,' VariantTypeParam} `]']
-     *  VariantTypeParam      ::= [`+' | `-'] TypeParam
+     *  VariantTypeParam      ::= {Annotation} [`+' | `-'] TypeParam
      *  FunTypeParamClauseOpt ::= [FunTypeParamClause]
      *  FunTypeParamClause    ::= `[' TypeParam {`,' TypeParam} `]']
-     *  TypeParam             ::= Id TypeParamClauseOpt TypeBounds [<% Type]
+     *  TypeParam             ::= Id TypeParamClauseOpt TypeBounds {<% Type} {":" Type}
      */
-    def typeParamClauseOpt(owner: Name, implicitViewBuf: ListBuffer[Tree]): List[TypeDef] = {
-      def typeParam(): TypeDef = {
-        var mods = Modifiers(Flags.PARAM)
+    def typeParamClauseOpt(owner: Name, contextBoundBuf: ListBuffer[Tree]): List[TypeDef] = {
+      def typeParam(ms: Modifiers): TypeDef = {
+        var mods = ms | Flags.PARAM
+        val start = in.offset
         if (owner.isTypeName && isIdent) {
-          if (inName == PLUS) {
-            inNextToken
-            mods = mods | Flags.COVARIANT
-          } else if (inName == MINUS) {
-            inNextToken
-            mods = mods | Flags.CONTRAVARIANT
+          if (in.name == PLUS) {
+            in.nextToken()
+            mods |= Flags.COVARIANT
+          } else if (in.name == MINUS) {
+            in.nextToken()
+            mods |= Flags.CONTRAVARIANT
           }
         }
-        val pos = inCurrentPos
+        val nameOffset = in.offset
         val pname = 
-          (if (inToken == USCORE) { // @M! also allow underscore 
-            inNextToken
+          (if (in.token == USCORE) { // TODO AM: freshName(o2p(in.skipToken()), "_$$"), will need to update test suite
+            in.nextToken()
             nme.WILDCARD
           } else ident()).toTypeName
-        
-        val tparams = typeParamClauseOpt(pname, null) // @M TODO null --> no higher-order view bounds for now
-        val param = atPos(pos) { TypeDef(mods, pname, tparams, typeBounds()) }
-        if (inToken == VIEWBOUND && (implicitViewBuf ne null))
-          implicitViewBuf += atPos(inSkipToken) {
-            makeFunctionTypeTree(List(Ident(pname)), typ())
+        val param = atPos(start, nameOffset) {
+          val tparams = typeParamClauseOpt(pname, null) // @M TODO null --> no higher-order context bounds for now
+          TypeDef(mods, pname, tparams, typeBounds())
+        }
+        if (contextBoundBuf ne null) {
+          while (in.token == VIEWBOUND) {
+            contextBoundBuf += atPos(in.skipToken()) {
+              makeFunctionTypeTree(List(Ident(pname)), typ())
+            }
+          }
+          while (in.token == COLON) {
+            contextBoundBuf += atPos(in.skipToken()) {
+              AppliedTypeTree(typ(), List(Ident(pname)))
+            }
           }
+        }
         param
       }
       val params = new ListBuffer[TypeDef]
       newLineOptWhenFollowedBy(LBRACKET) 
-      if (inToken == LBRACKET) {
-        inNextToken
-        params += typeParam()
-        while (inToken == COMMA) {
-          inNextToken
-          params += typeParam()
+      if (in.token == LBRACKET) {
+        in.nextToken()
+        params += typeParam(NoMods.withAnnotations(annotations(true, false)))
+        while (in.token == COMMA) {
+          in.nextToken()
+          params += typeParam(NoMods.withAnnotations(annotations(true, false)))
         }
         accept(RBRACKET)
       }
@@ -1798,82 +1943,92 @@ trait Parsers extends NewScanners with MarkupParsers {
 
     /** TypeBounds ::= [`>:' Type] [`<:' Type] 
      */
-    def typeBounds(): TypeBoundsTree = 
-      TypeBoundsTree(
+    def typeBounds(): TypeBoundsTree = { 
+      val t = TypeBoundsTree(
         bound(SUPERTYPE, nme.Nothing),
         bound(SUBTYPE, nme.Any))
-
+      t setPos (wrappingPos(List(t.hi, t.lo)))
+      t
+    }
+    
     def bound(tok: Int, default: Name): Tree =
-      if (inToken == tok) { inNextToken; typ() } 
-      else scalaDot(default.toTypeName)
+      if (in.token == tok) { in.nextToken(); typ() } 
+      else atPos(o2p(in.lastOffset)) { rootScalaDot(default.toTypeName) }
 
-//////// DEFS ////////////////////////////////////////////////////////////////
+/* -------- DEFS ------------------------------------------- */    
 
 
     /** Import  ::= import ImportExpr {`,' ImportExpr}
      */
     def importClause(): List[Tree] = {
-      accept(IMPORT)
-      val ts = new ListBuffer[Tree] + importExpr()
-      while (inToken == COMMA) {
-        inNextToken; ts += importExpr()
+      val offset = accept(IMPORT)
+      commaSeparated(importExpr()) match {
+        case Nil => Nil
+        case t :: rest => 
+          // The first import should start at the position of the keyword.
+          t.setPos(t.pos.withStart(offset))
+          t :: rest
       }
-      ts.toList
     }
 
     /**  ImportExpr ::= StableId `.' (Id | `_' | ImportSelectors)
      * XXX: Hook for IDE
      */
-    def importExpr(): Tree = 
-      atPos(inCurrentPos) {
-        var t: Tree = null
-        //var pos : ScanPosition = null.asInstanceOf[ScanPosition]
-        var pos : Int = -1
-        if (inToken == THIS) {
-          t = atPos(inCurrentPos) { This(nme.EMPTY.toTypeName) }
-          t = atPos(accept(DOT)) { selector(t) }
-          pos = accept(DOT)
+    def importExpr(): Tree = {
+      val start = in.offset
+      var t: Tree = null
+      if (in.token == THIS) {
+        in.nextToken()
+        t = atPos(start) { This(nme.EMPTY.toTypeName) }
+        accept(DOT)
+        t = selector(t)
+        accept(DOT)
+      } else {
+        val id = atPos(start) { Ident(ident()) }
+        accept(DOT)
+        if (in.token == THIS) {
+          in.nextToken()
+          t = atPos(start) { This(id.name.toTypeName) }
+          accept(DOT)
+          t = selector(t)
+          accept(DOT)
         } else {
-          val i = atPos(inCurrentPos) { Ident(ident()) }
-          pos = accept(DOT)
-          if (inToken == THIS) {
-            inNextToken
-            t = atPos(i.pos) { This(i.name.toTypeName) }
-            t = atPos(accept(DOT)) { selector(t) }
-            pos = accept(DOT)
-          } else {
-            t = i
-          }
+          t = id
         }
-        def loop: Tree =
-          if (inToken == USCORE) {
-            inNextToken
-            Import(t, List((nme.WILDCARD, null)))
-          } else if (inToken == LBRACE) {
-            Import(t, importSelectors())
-          } else {
-            val identPos = inCurrentPos
-            val name = ident() // @S: use position of identifier, not dot!
-            pos = if (name == nme.ERROR) pos else identPos
-            if (inToken == DOT) {
-              t = atPos(pos) { Select(t, name) }
-              pos = accept(DOT)
-              loop
-            } else {
-              Import(t, List((name, name)))
+        t setPos t.pos.makeTransparent
+      }
+      def loop(): Tree =
+        if (in.token == USCORE) {
+          val uscoreOffset = in.offset
+          in.nextToken()
+          Import(t, List(ImportSelector(nme.WILDCARD, uscoreOffset, nme.WILDCARD, -1)))
+        } else if (in.token == LBRACE) {
+          Import(t, importSelectors())
+        } else {
+          val nameOffset = in.offset
+          val name = ident()
+          if (in.token == DOT) {
+            t = atPos(start, if (name == nme.ERROR) in.offset else nameOffset) {
+              Select(t, name)
             }
+            t setPos t.pos.makeTransparent
+            in.nextToken()
+            loop()
+          } else {
+            Import(t, List(ImportSelector(name, nameOffset, name, nameOffset)))
           }
-        loop
-      } 
-
+        }
+      atPos(start) { loop() }
+    }
+      
     /** ImportSelectors ::= `{' {ImportSelector `,'} (ImportSelector | `_') `}'
      */
-    def importSelectors(): List[(Name, Name)] = {
-      val names = new ListBuffer[(Name, Name)]
+    def importSelectors(): List[ImportSelector] = {
+      val names = new ListBuffer[ImportSelector]
       accept(LBRACE)
       var isLast = importSelector(names)
-      while (!isLast && inToken == COMMA) {
-        inNextToken
+      while (!isLast && in.token == COMMA) {
+        in.nextToken()
         isLast = importSelector(names)
       }
       accept(RBRACE)
@@ -1882,19 +2037,31 @@ trait Parsers extends NewScanners with MarkupParsers {
 
     /** ImportSelector ::= Id [`=>' Id | `=>' `_']
      */
-    def importSelector(names: ListBuffer[(Name, Name)]): Boolean =
-      if (inToken == USCORE) {
-        inNextToken; names += (nme.WILDCARD, null); true
+    def importSelector(names: ListBuffer[ImportSelector]): Boolean =
+      if (in.token == USCORE) {
+        val uscoreOffset = in.offset
+        in.nextToken(); names += ImportSelector(nme.WILDCARD, uscoreOffset, null, -1); true
       } else {
+        val nameOffset = in.offset
         val name = ident()
-        names += (
-          name,
-          if (inToken == ARROW) {
-            inNextToken
-            if (inToken == USCORE) { inNextToken; nme.WILDCARD } else ident()
+        
+        val (name1, name1Offset) =
+          if (in.token == ARROW) {
+            in.nextToken()
+            if (in.token == USCORE) {
+              val uscoreOffset = in.offset
+              in.nextToken();
+              (nme.WILDCARD, uscoreOffset)
+            } else {
+              val renameOffset = in.offset
+              val rename = ident() 
+              (rename, renameOffset)
+            }
           } else {
-            name
-          })
+            (name, nameOffset)
+          }
+        
+        names += ImportSelector(name, nameOffset, name1, name1Offset)
         false
       }
     
@@ -1908,56 +2075,50 @@ trait Parsers extends NewScanners with MarkupParsers {
      *           | def FunDcl
      *           | type [nl] TypeDcl
      */
-    def defOrDcl(mods: Modifiers): List[Tree] = {
-      if ((mods.hasFlag(Flags.LAZY)) && in.token != VAL)
+    def defOrDcl(pos: Int, mods: Modifiers): List[Tree] = {
+      if ((mods hasFlag Flags.LAZY) && in.token != VAL)
         syntaxError("lazy not allowed here. Only vals can be lazy", false)
-      inToken match {
+      in.token match {
         case VAL =>
-          patDefOrDcl(mods)
+          patDefOrDcl(pos, mods withPosition(VAL, tokenRange(in)))
         case VAR =>
-          patDefOrDcl(mods | Flags.MUTABLE)
+          patDefOrDcl(pos, (mods | Flags.MUTABLE) withPosition (VAR, tokenRange(in)))
         case DEF =>
-          List(funDefOrDcl(mods))
+          List(funDefOrDcl(pos, mods withPosition(DEF, tokenRange(in))))
         case TYPE =>
-          inNextToken
-          newLinesOpt()
-          List(typeDefOrDcl(mods))
+          List(typeDefOrDcl(pos, mods withPosition(TYPE, tokenRange(in))))
         case _ =>
-          List(tmplDef(mods))
+          List(tmplDef(pos, mods))
       }
     }
-    /** IDE hook: for non-local defs or dcls with modifiers and annotations */
+    
+    private def caseAwareTokenOffset = if (in.token == CASECLASS || in.token == CASEOBJECT) in.prev.offset else in.offset
+
     def nonLocalDefOrDcl : List[Tree] = {
-      val annots = annotations(true)
-      defOrDcl(modifiers() withAnnotations annots)
-    }
-    /** not hooked by the IDE, will not undergo stubbing. Used for early initialization blocks. */
-    def preNonLocalDefOrDcl : List[Tree] = {
-      val annots = annotations(true)
-      defOrDcl(modifiers() withAnnotations annots)
+      val annots = annotations(true, false)
+      defOrDcl(caseAwareTokenOffset, modifiers() withAnnotations annots)
     }
     
-    
     /** PatDef ::= Pattern2 {`,' Pattern2} [`:' Type] `=' Expr
      *  ValDcl ::= Id {`,' Id} `:' Type
      *  VarDef ::= PatDef | Id {`,' Id} `:' Type `=' `_'
      */
-    def patDefOrDcl(mods: Modifiers): List[Tree] = {
+    def patDefOrDcl(pos : Int, mods: Modifiers): List[Tree] = {
       var newmods = mods
       val lhsBuf = new ListBuffer[Tree]
       do {
-        inNextToken
+        in.nextToken()
         val p = pattern2(false)
         lhsBuf += stripParens(p)
-      } while (inToken == COMMA)
+      } while (in.token == COMMA)
       val lhs = lhsBuf.toList
       val tp = typedOpt()
       val rhs =
-        if (tp.isEmpty || inToken == EQUALS) {
+        if (tp.isEmpty || in.token == EQUALS) {
           accept(EQUALS)
           if (!tp.isEmpty && newmods.hasFlag(Flags.MUTABLE) && 
-              (lhs.toList forall (_.isInstanceOf[Ident])) && inToken == USCORE) {
-            inNextToken
+              (lhs.toList forall (_.isInstanceOf[Ident])) && in.token == USCORE) {
+            in.nextToken()
             newmods = newmods | Flags.DEFAULTINIT
             EmptyTree
           } else {
@@ -1967,32 +2128,27 @@ trait Parsers extends NewScanners with MarkupParsers {
           newmods = newmods | Flags.DEFERRED
           EmptyTree
         }
-      var originalUsed = false
-      def mkDefs(p: Tree): List[Tree] = {
+      def mkDefs(p: Tree, tp: Tree, rhs: Tree): List[Tree] = {
         //Console.println("DEBUG: p = "+p.toString()); // DEBUG
-        val trees =
-          makePatDef(newmods,
-                     if (tp.isEmpty)
-                       p
-                     else
-                       Typed(p, tp),
-                     if (inIDE && !originalUsed) {
-                       // because duplicates have weaker status than originals
-                       // need an original.
-                       originalUsed = true
-                       rhs
-                     } else rhs.duplicate) map atPos(p.pos)
-        if (newmods.hasFlag(Flags.DEFERRED)) {
+        val trees = 
+          makePatDef(newmods, 
+                     if (tp.isEmpty) p 
+                     else Typed(p, tp) setPos (p.pos union tp.pos), 
+                     rhs)
+        if (newmods hasFlag Flags.DEFERRED) {
           trees match {
             case List(ValDef(_, _, _, EmptyTree)) => 
-              if (mods.hasFlag(Flags.LAZY)) 
-                syntaxError(p.pos, "lazy values may not be abstract", false)
+              if (mods.hasFlag(Flags.LAZY)) syntaxError(p.pos, "lazy values may not be abstract", false)
             case _ => syntaxError(p.pos, "pattern definition may not be abstract", false)
           }
         }
         trees
       }
-      for (p <- lhs.toList; d <- mkDefs(p)) yield d
+      val trees = (lhs.toList.init flatMap (mkDefs(_, tp.duplicate, rhs.duplicate))) ::: mkDefs(lhs.last, tp, rhs)
+      val hd = trees.head
+      hd setPos hd.pos.withStart(pos)
+      ensureNonOverlapping(hd, trees.tail)
+      trees
     }
 
     /** VarDef ::= PatDef
@@ -2002,14 +2158,14 @@ trait Parsers extends NewScanners with MarkupParsers {
       var newmods = mods | Flags.MUTABLE
       val lhs = new ListBuffer[(Int, Name)]
       do {
-        inNextToken
-        lhs += (inCurrentPos, ident())
-      } while (inToken == COMMA)
+        in.nextToken()
+        lhs += (in.offset, ident())
+      } while (in.token == COMMA)
       val tp = typedOpt()
-      val rhs = if (tp.isEmpty || inToken == EQUALS) {
+      val rhs = if (tp.isEmpty || in.token == EQUALS) {
         accept(EQUALS)
-        if (!tp.isEmpty && inToken == USCORE) {
-          inNextToken
+        if (!tp.isEmpty && in.token == USCORE) {
+          in.nextToken()
           EmptyTree
         } else {
           expr()
@@ -2018,13 +2174,6 @@ trait Parsers extends NewScanners with MarkupParsers {
         newmods = newmods | Flags.DEFERRED
         EmptyTree
       }
-      var originalUsed = false
-      for ((pos, name) <- lhs.toList) yield atPos(pos) { 
-        if (inIDE && !originalUsed) {
-          originalUsed = true
-          ValDef(newmods, name, tp, rhs)
-        } else ValDef(newmods, name, tp.duplicate, rhs.duplicate)
-      }
     }
      */
 
@@ -2034,50 +2183,61 @@ trait Parsers extends NewScanners with MarkupParsers {
      *  FunDcl ::= FunSig [`:' Type]
      *  FunSig ::= id [FunTypeParamClause] ParamClauses
      */
-    def funDefOrDcl(mods: Modifiers): Tree = {
-      var pos = inSkipToken // position of `def' 
-      if (inToken == THIS) {  
-        atPos(inCurrentPos) {
-          inNextToken
-          val vparamss = paramClauses(nme.CONSTRUCTOR, implicitClassViews map (_.duplicate), false)
+    def funDefOrDcl(start : Int, mods: Modifiers): Tree = {
+      in.nextToken
+      if (in.token == THIS) {  
+        atPos(start, in.skipToken()) {
+          val vparamss = paramClauses(nme.CONSTRUCTOR, classContextBounds map (_.duplicate), false)
           newLineOptWhenFollowedBy(LBRACE)
-          val rhs = if (inToken == LBRACE) constrBlock(vparamss)
-                    else { accept(EQUALS); constrExpr(vparamss) }
+          val rhs = if (in.token == LBRACE) {
+                      atPos(in.offset) { constrBlock(vparamss) }
+                    } else { 
+                      accept(EQUALS)
+                      atPos(in.offset) { constrExpr(vparamss) }
+                    }
           DefDef(mods, nme.CONSTRUCTOR, List(), vparamss, TypeTree(), rhs)
         }
       } else {
         var newmods = mods
-        val namePos = inCurrentPos
+        val nameOffset = in.offset
         val name = ident()
-        if (name != nme.ERROR) pos = namePos
-        atPos(pos) {
-          // implicitViewBuf is for view bounded type parameters of the form
-          // [T <% B]; it contains the equivalent implicit parameter, i.e. (implicit p: T => B)
-          val implicitViewBuf = new ListBuffer[Tree]  
-          val tparams = typeParamClauseOpt(name, implicitViewBuf)
-          val vparamss = paramClauses(name, implicitViewBuf.toList, false)
+        atPos(start, if (name == nme.ERROR) start else nameOffset) {
+          // contextBoundBuf is for context bounded type parameters of the form
+          // [T : B] or [T : => B]; it contains the equivalent implicit parameter type,
+          // i.e. (B[T] or T => B)
+          val contextBoundBuf = new ListBuffer[Tree]  
+          val tparams = typeParamClauseOpt(name, contextBoundBuf)
+          val vparamss = paramClauses(name, contextBoundBuf.toList, false)
           newLineOptWhenFollowedBy(LBRACE)
-          var restype = typedOpt()
+          val savedInFunReturnType = inFunReturnType
+          var restype = try {
+            inFunReturnType = true
+            typedOpt()
+          } finally {
+            inFunReturnType = savedInFunReturnType
+          }
           val rhs =
-            if (isStatSep || inToken == RBRACE) {
+            if (isStatSep || in.token == RBRACE) {
               if (restype.isEmpty) restype = scalaUnitConstr
-              newmods = newmods | Flags.DEFERRED
+              newmods |= Flags.DEFERRED
               EmptyTree
-            } else if (restype.isEmpty && inToken == LBRACE) {
+            } else if (restype.isEmpty && in.token == LBRACE) {
               restype = scalaUnitConstr
               blockExpr()
-            } else equalsExpr()
+            } else {
+              equalsExpr()
+            }
           DefDef(newmods, name, tparams, vparamss, restype, rhs)
         }
       }
     }
-    
 
     /** ConstrExpr      ::=  SelfInvocation
      *                    |  ConstrBlock
      */
     def constrExpr(vparamss: List[List[ValDef]]): Tree =
-      if (inToken == LBRACE) constrBlock(vparamss) else Block(List(selfInvocation(vparamss)), Literal(()))
+      if (in.token == LBRACE) constrBlock(vparamss)
+      else Block(List(selfInvocation(vparamss)), Literal(()))
 
     /** SelfInvocation  ::= this ArgumentExprs {ArgumentExprs}
      */
@@ -2085,44 +2245,40 @@ trait Parsers extends NewScanners with MarkupParsers {
       atPos(accept(THIS)) {
         newLineOptWhenFollowedBy(LBRACE)
         var t = Apply(Ident(nme.CONSTRUCTOR), argumentExprs())
-        while (inToken == LPAREN || inToken == LBRACE) {
+        newLineOptWhenFollowedBy(LBRACE)
+        while (in.token == LPAREN || in.token == LBRACE) {
           t = Apply(t, argumentExprs())
           newLineOptWhenFollowedBy(LBRACE)
         }
-        if (!implicitClassViews.isEmpty) t = Apply(t, vparamss.last.map(vd => Ident(vd.name)))
-        t
+        if (classContextBounds.isEmpty) t
+        else Apply(t, vparamss.last.map(vp => Ident(vp.name)))
       }
 
     /** ConstrBlock    ::=  `{' SelfInvocation {semi BlockStat} `}' 
      */
     def constrBlock(vparamss: List[List[ValDef]]): Tree =
-      atPos(inSkipToken) {
+      atPos(in.skipToken()) {
         val statlist = new ListBuffer[Tree]
         statlist += selfInvocation(vparamss)
-        val stats = if (isStatSep) { inNextToken; blockStatSeq(statlist) } 
+        val stats = if (isStatSep) { in.nextToken(); blockStatSeq(statlist) } 
                     else statlist.toList
         accept(RBRACE)
         Block(stats, Literal(()))
       }
 
-    /** TypeDef ::= Id [TypeParamClause] `=' Type
-     *  TypeDcl ::= Id [TypeParamClause] TypeBounds
+    /** TypeDef ::= type Id [TypeParamClause] `=' Type
+     *  TypeDcl ::= type Id [TypeParamClause] TypeBounds
      */
-    def typeDefOrDcl(mods: Modifiers): Tree =
-      atPos(inCurrentPos) {
+    def typeDefOrDcl(start: Int, mods: Modifiers): Tree = {
+      in.nextToken
+      newLinesOpt()
+      atPos(start, in.offset) {
         val name = ident().toTypeName
-        
         // @M! a type alias as well as an abstract type may declare type parameters
-        val tparams = inToken match { 
-          case LBRACKET =>
-             typeParamClauseOpt(name, null)
-          case _ =>
-             Nil
-        }
-        
-        inToken match {
+        val tparams = typeParamClauseOpt(name, null)
+        in.token match {
           case EQUALS =>
-            inNextToken
+            in.nextToken()
             TypeDef(mods, name, tparams, typ())
           case SUPERTYPE | SUBTYPE | SEMI | NEWLINE | NEWLINES | COMMA | RBRACE =>
             TypeDef(mods | Flags.DEFERRED, name, tparams, typeBounds())
@@ -2131,31 +2287,33 @@ trait Parsers extends NewScanners with MarkupParsers {
             EmptyTree
         }
       }
+    }
 
     /** Hook for IDE, for top-level classes/objects */
     def topLevelTmplDef: Tree = {
-      val annots = annotations(true)
+      val annots = annotations(true, false)
+      val pos = caseAwareTokenOffset
       val mods = modifiers() withAnnotations annots
-      tmplDef(mods)
+      tmplDef(pos, mods)
     }
     
     /**  TmplDef ::= [case] class ClassDef
      *            |  [case] object ObjectDef
-     *            |  trait TraitDef
+     *            |  [override] trait TraitDef
      */
-    def tmplDef(mods: Modifiers): Tree = {
+    def tmplDef(pos: Int, mods: Modifiers): Tree = {
       if (mods.hasFlag(Flags.LAZY)) syntaxError("classes cannot be lazy", false)
-      inToken match {
+      in.token match {
         case TRAIT =>
-          classDef(mods | Flags.TRAIT | Flags.ABSTRACT)
+          classDef(pos, (mods | Flags.TRAIT | Flags.ABSTRACT) withPosition (Flags.TRAIT, tokenRange(in)))
         case CLASS =>
-          classDef(mods)
+          classDef(pos, mods)
         case CASECLASS =>
-          classDef(mods | Flags.CASE)
+          classDef(pos, (mods | Flags.CASE) withPosition (Flags.CASE, tokenRange(in.prev /*scanner skips on 'case' to 'class', thus take prev*/)))
         case OBJECT =>
-          objectDef(mods)
+          objectDef(pos, mods)
         case CASEOBJECT =>
-          objectDef(mods | Flags.CASE)
+          objectDef(pos, (mods | Flags.CASE) withPosition (Flags.CASE, tokenRange(in.prev /*scanner skips on 'case' to 'object', thus take prev*/)))
         case _ =>
           syntaxErrorOrIncomplete("expected start of definition", true)
           EmptyTree
@@ -2166,66 +2324,67 @@ trait Parsers extends NewScanners with MarkupParsers {
                      [AccessModifier] ClassParamClauses RequiresTypeOpt ClassTemplateOpt
      *  TraitDef ::= Id [TypeParamClause] RequiresTypeOpt TraitTemplateOpt
      */
-    def classDef(mods: Modifiers): ClassDef = {
-      var pos = inSkipToken 
-      var namePos = inCurrentPos
+    def classDef(start: Int, mods: Modifiers): ClassDef = {
+      in.nextToken
+      val nameOffset = in.offset
       val name = ident().toTypeName
-      if (name != nme.ERROR) pos = namePos
-      atPos(pos) {  
-        val savedViews = implicitClassViews
-        val implicitViewBuf = new ListBuffer[Tree]
-        val tparams = typeParamClauseOpt(name, implicitViewBuf)
-        implicitClassViews = implicitViewBuf.toList
-        if (!implicitClassViews.isEmpty && mods.hasFlag(Flags.TRAIT)) {
-          syntaxError("traits cannot have type parameters with <% bounds", false)
-          implicitClassViews = List()
+      atPos(start, if (name == nme.ERROR.toTypeName) start else nameOffset) {
+        val savedContextBounds = classContextBounds
+        val contextBoundBuf = new ListBuffer[Tree]
+        val tparams = typeParamClauseOpt(name, contextBoundBuf)
+        classContextBounds = contextBoundBuf.toList
+        val tstart = (in.offset::classContextBounds.map(_.pos.startOrPoint)).min 
+        if (!classContextBounds.isEmpty && mods.hasFlag(Flags.TRAIT)) {
+          syntaxError("traits cannot have type parameters with context bounds `: ...' nor view bounds `<% ...'", false)
+          classContextBounds = List()
         }
-        val constrAnnots = annotations(false)
+        val constrAnnots = annotations(false, true)
         val (constrMods, vparamss) = 
           if (mods.hasFlag(Flags.TRAIT)) (Modifiers(Flags.TRAIT), List())
-          else (accessModifierOpt(), paramClauses(name, implicitClassViews, mods.hasFlag(Flags.CASE)))
-        val thistpe = requiresTypeOpt()
-        var mods1 = if (inToken == SUBTYPE) mods | Flags.DEFERRED else mods
-        var template = templateOpt(mods1, name, constrMods withAnnotations constrAnnots, vparamss)
-        if (!thistpe.isEmpty) {
-          if (template.self.isEmpty) {
-            template = copy.Template(
-              template, template.parents, makeSelfDef(nme.WILDCARD, thistpe), template.body)
-          } else syntaxError("`requires' cannot be combined with explicit self type", false)
+          else (accessModifierOpt(), paramClauses(name, classContextBounds, mods.hasFlag(Flags.CASE)))
+        var mods1 = mods
+        if (mods hasFlag Flags.TRAIT) {
+          if (settings.YvirtClasses && in.token == SUBTYPE) mods1 |= Flags.DEFERRED
+        } else if (in.token == SUBTYPE) {
+          syntaxError("classes are not allowed to be virtual", false)
         }
+        val template = templateOpt(mods1, name, constrMods withAnnotations constrAnnots, vparamss, tstart)
         if (isInterface(mods1, template.body)) mods1 |= Flags.INTERFACE 
         val result = ClassDef(mods1, name, tparams, template)
-        implicitClassViews = savedViews
+        // Context bounds generate implicit parameters (part of the template) with types
+        // from tparams: we need to ensure these don't overlap
+        if (!classContextBounds.isEmpty)
+          ensureNonOverlapping(template, tparams)
+        classContextBounds = savedContextBounds
         result
       }
     }
 
     /** ObjectDef       ::= Id ClassTemplateOpt
      */
-    def objectDef(mods: Modifiers): ModuleDef = {
-      var pos = inSkipToken 
-      var namePos = inCurrentPos
-      val name = ident().toTermName
-      if (name != nme.ERROR) pos = namePos
-      atPos(pos) {
-        val mods1 = if (inToken == SUBTYPE) mods | Flags.DEFERRED else mods
-        val template = templateOpt(mods1, name, NoMods, List())
+    def objectDef(start: Int, mods: Modifiers): ModuleDef = {
+      in.nextToken
+      val nameOffset = in.offset
+      val name = ident()
+      val tstart = in.offset
+      atPos(start, if (name == nme.ERROR) start else nameOffset) {
+        val mods1 = if (in.token == SUBTYPE) mods | Flags.DEFERRED else mods
+        val template = templateOpt(mods1, name, NoMods, List(), tstart)
         ModuleDef(mods1, name, template)
       }
     }
-
     
-    /** ClassParents       ::= AnnotType {`(' [Exprs [`,']] `)'} {with AnnotType}
+    /** ClassParents       ::= AnnotType {`(' [Exprs] `)'} {with AnnotType}
      *  TraitParents       ::= AnnotType {with AnnotType}
      */
     def templateParents(isTrait: Boolean): (List[Tree], List[List[Tree]]) = {
-      val parents = new ListBuffer[Tree] + annotType(false)
+      val parents = new ListBuffer[Tree] += annotType(false)
       val argss = new ListBuffer[List[Tree]]
-      if (inToken == LPAREN && !isTrait)
-        do { argss += argumentExprs() } while (inToken == LPAREN)
+      if (in.token == LPAREN && !isTrait)
+        do { argss += argumentExprs() } while (in.token == LPAREN)
       else argss += List()
-      while (inToken == WITH) {
-        inNextToken
+      while (in.token == WITH) {
+        in.nextToken()
         parents += annotType(false)
       }
       (parents.toList, argss.toList)
@@ -2238,22 +2397,24 @@ trait Parsers extends NewScanners with MarkupParsers {
      */
     def template(isTrait: Boolean): (List[Tree], List[List[Tree]], ValDef, List[Tree]) = {
       newLineOptWhenFollowedBy(LBRACE)
-      if (inToken == LBRACE) {
+      if (in.token == LBRACE) {
         // @S: pre template body cannot stub like post body can!
         val (self, body) = templateBody(true) 
-        if (inToken == WITH && self.isEmpty) {
-          val vdefs: List[ValDef] = body flatMap { 
+        if (in.token == WITH && self.isEmpty) {
+          val earlyDefs: List[Tree] = body flatMap { 
             case vdef @ ValDef(mods, name, tpt, rhs) if !(mods hasFlag Flags.DEFERRED) =>
-              List(copy.ValDef(vdef, mods | Flags.PRESUPER, name, tpt, rhs))
+              List(treeCopy.ValDef(vdef, mods | Flags.PRESUPER, name, tpt, rhs))
+            case tdef @ TypeDef(mods, name, tparams, rhs) =>
+              List(treeCopy.TypeDef(tdef, mods | Flags.PRESUPER, name, tparams, rhs))
             case stat if !stat.isEmpty => 
-                syntaxError(stat.pos, "only concrete field definitions allowed in early object initialization section", false)
+              syntaxError(stat.pos, "only type definitions and concrete field definitions allowed in early object initialization section", false)
               List()
             case _ => List()
-          } 
-          inNextToken
+          }
+          in.nextToken()
           val (parents, argss) = templateParents(isTrait)
           val (self1, body1) = templateBodyOpt(isTrait)
-          (parents, argss, self1, vdefs ::: body1)
+          (parents, argss, self1, earlyDefs ::: body1)
         } else {
           (List(), List(List()), self, body)
         }
@@ -2264,44 +2425,45 @@ trait Parsers extends NewScanners with MarkupParsers {
       }
     }
 
-    def isInterface(mods: Modifiers, body: List[Tree]) =
-      (mods.hasFlag(Flags.TRAIT) && (body forall treeInfo.isInterfaceMember))
+    def isInterface(mods: Modifiers, body: List[Tree]): Boolean =
+      (mods hasFlag Flags.TRAIT) && (body forall treeInfo.isInterfaceMember)
 
-    /** ClassTemplateOpt ::= Extends ClassTemplate | [[Extends] TemplateBody] 
-     *  TraitTemplateOpt ::= Extends TraitTemplate | [[Extends] TemplateBody]
-     *  Extends          ::= extends | `<:'
+    /** ClassTemplateOpt ::= 'extends' ClassTemplate | [['extends'] TemplateBody] 
+     *  TraitTemplateOpt ::= TraitExtends TraitTemplate | [['extends'] TemplateBody] | '<:' TemplateBody
+     *  TraitExtends     ::= 'extends' | `<:'
      */
-    def templateOpt(mods: Modifiers, name: Name, constrMods: Modifiers, vparamss: List[List[ValDef]]): Template = {
-      val pos = inCurrentPos;
+    def templateOpt(mods: Modifiers, name: Name, constrMods: Modifiers,
+                    vparamss: List[List[ValDef]], tstart: Int): Template = {
       val (parents0, argss, self, body) = 
-        if (inToken == EXTENDS || settings.Xexperimental.value && (mods hasFlag Flags.TRAIT) && inToken == SUBTYPE) {
-          inNextToken
+        if (in.token == EXTENDS || settings.YvirtClasses && (mods hasFlag Flags.TRAIT) && in.token == SUBTYPE) {
+          in.nextToken()
           template(mods hasFlag Flags.TRAIT)
+        } else if ((in.token == SUBTYPE) && (mods hasFlag Flags.TRAIT)) {
+          in.nextToken()
+          template(true)
         } else {
           newLineOptWhenFollowedBy(LBRACE)
           val (self, body) = templateBodyOpt(false)
           (List(), List(List()), self, body)
         }
       var parents = parents0
-      if (name != nme.ScalaObject.toTypeName && !isInterface(mods, body)) 
+      if (!isInterface(mods, body) && !(inScalaPackage && name == nme.Array.toTypeName))
         parents = parents ::: List(scalaScalaObjectConstr)
       if (parents.isEmpty)
         parents = List(scalaAnyRefConstr)
       if (mods.hasFlag(Flags.CASE)) parents = parents ::: List(productConstr)
-      val tree = Template(parents, self, constrMods, vparamss, argss, body)
-      // @S: if nothing parsed, don't use next position!
-      // @S: if primary constructor does not always have the same position, then the IDE gets confused.
-      // @S: since build compiler is used to generate IDE files, don't set position here!
-      tree 
-      // if (pos == inCurrentPos || inIDE) tree else atPos(pos) {tree}
+      val tstart0 = if (body.isEmpty && in.lastOffset < tstart) in.lastOffset else tstart
+      atPos(tstart0) {
+        Template(parents, self, constrMods, vparamss, argss, body, o2p(tstart))
+      }
     }
-    
-////////// TEMPLATES ////////////////////////////////////////////////////////////
+
+/* -------- TEMPLATES ------------------------------------------- */        
 
     /** TemplateBody ::= [nl] `{' TemplateStatSeq `}'
      * @param isPre specifies whether in early initializer (true) or not (false) 
      */
-    def templateBody(isPre : Boolean) = {
+    def templateBody(isPre: Boolean) = {
       accept(LBRACE)
       val result @ (self, stats) = templateStatSeq(isPre)
       accept(RBRACE)
@@ -2309,16 +2471,16 @@ trait Parsers extends NewScanners with MarkupParsers {
     }
     def templateBodyOpt(traitParentSeen: Boolean): (ValDef, List[Tree]) = {
       newLineOptWhenFollowedBy(LBRACE)
-      if (inToken == LBRACE) {
+      if (in.token == LBRACE) {
         templateBody(false) 
       } else {
-        if (inToken == LPAREN) 
+        if (in.token == LPAREN) 
           syntaxError((if (traitParentSeen) "parents of traits" else "traits or objects")+
                       " may not have parameters", true)
         (emptyValDef, List())
       }
     }
-
+    
     /** Refinement ::= [nl] `{' RefineStat {semi RefineStat} `}'
      */
     def refinement(): List[Tree] = {
@@ -2328,51 +2490,82 @@ trait Parsers extends NewScanners with MarkupParsers {
       body
     }
 
-/////// STATSEQS //////////////////////////////////////////////////////////////
+/* -------- STATSEQS ------------------------------------------- */        
+
+  /** Create a tree representing a packaging */
+    def makePackaging(start: Int, pkg: Tree, stats: List[Tree]): PackageDef = 
+      atPos(start, pkg.pos.point) { PackageDef(pkg.asInstanceOf[RefTree], stats) }
+/*
+        pkg match {
+          case id @ Ident(_) =>
+            PackageDef(id, stats)
+          case Select(qual, name) => // drop this to flatten packages
+            makePackaging(start, qual, List(PackageDef(Ident(name), stats)))
+        }
+      }
+*/ 
+    
+    /** Create a tree representing a package object, converting
+     *    package object foo { ... }
+     *  to
+     *    package foo { 
+     *      object `package` { ... }
+     *    }
+     */
+    def makePackageObject(start: Int, objDef: ModuleDef): PackageDef = objDef match {
+      case ModuleDef(mods, name, impl) =>
+        makePackaging(
+          start, atPos(o2p(objDef.pos.startOrPoint)){ Ident(name) }, List(ModuleDef(mods, nme.PACKAGEkw, impl)))
+    }
 
     /** Packaging ::= package QualId [nl] `{' TopStatSeq `}'
      */
-    def packaging(): Tree = {
-      
-      val pkgPos = accept(PACKAGE)
+    def packaging(start: Int): Tree = {
       val pkg = qualId()
-      val pos = if (pkg.pos != NoPosition) pkg.pos else i2p(pkgPos)
-      atPos(pos) {
-        newLineOptWhenFollowedBy(LBRACE)
-        accept(LBRACE)
-        val stats = topStatSeq()
-        accept(RBRACE)
-        makePackaging(pkg, stats)
-      }
+      newLineOptWhenFollowedBy(LBRACE)
+      accept(LBRACE)
+      val stats = topStatSeq()
+      accept(RBRACE)
+      makePackaging(start, pkg, stats)
     }
 
     /** TopStatSeq ::= TopStat {semi TopStat}
      *  TopStat ::= Annotations Modifiers TmplDef
      *            | Packaging
+     *            | package object objectDef
      *            | Import
      *            | 
      */
     def topStatSeq(): List[Tree] = {
       val stats = new ListBuffer[Tree]
-      while (inToken != RBRACE && inToken != EOF) {
-        if (inToken == PACKAGE) {
-          stats += packaging()
-        } else if (inToken == IMPORT) {
+      while (in.token != RBRACE && in.token != EOF) {
+        if (in.token == PACKAGE) {
+          val start = in.skipToken()
+          stats ++= {
+            if (in.token == OBJECT) {
+              joinComment(List(makePackageObject(start, objectDef(in.offset, NoMods))))
+            }
+            else {
+              in.flushDoc
+              List(packaging(start))
+            }
+          }
+        } else if (in.token == IMPORT) {
+          in.flushDoc
           stats ++= importClause()
-          // XXX: IDE hook this all.
-        } else if (inToken == CLASS ||
-                   inToken == CASECLASS ||
-                   inToken == TRAIT ||
-                   inToken == OBJECT ||
-                   inToken == CASEOBJECT ||
-                   inToken == LBRACKET || //todo: remove
-                   inToken == AT ||
+        } else if (in.token == CLASS ||
+                   in.token == CASECLASS ||
+                   in.token == TRAIT ||
+                   in.token == OBJECT ||
+                   in.token == CASEOBJECT ||
+                   in.token == LBRACKET || //todo: remove
+                   in.token == AT ||
                    isModifier) {
-          stats ++ joinComment(List(topLevelTmplDef))
+          stats ++= joinComment(List(topLevelTmplDef))
         } else if (!isStatSep) {
           syntaxErrorOrIncomplete("expected class or object definition", true)
         }
-        if (inToken != RBRACE && inToken != EOF) acceptStatSep()
+        if (in.token != RBRACE && in.token != EOF) acceptStatSep()
       }
       stats.toList
     }
@@ -2390,43 +2583,42 @@ trait Parsers extends NewScanners with MarkupParsers {
       var self: ValDef = emptyValDef
       val stats = new ListBuffer[Tree]
       if (isExprIntro) {
+        in.flushDoc
         val first = expr(InTemplate) // @S: first statement is potentially converted so cannot be stubbed.
-        if (inToken == ARROW) {
+        if (in.token == ARROW) {
           first match {
             case Typed(tree @ This(name), tpt) if (name == nme.EMPTY.toTypeName) =>
-              self = makeSelfDef(nme.WILDCARD, tpt).setPos(tree.pos)
+              self = atPos(tree.pos union tpt.pos) { makeSelfDef(nme.WILDCARD, tpt) }
             case _ =>
               convertToParam(first) match {
                 case tree @ ValDef(_, name, tpt, EmptyTree) if (name != nme.ERROR) =>
-                  self = makeSelfDef(name, tpt).setPos(tree.pos)
+                  self = atPos(tree.pos union tpt.pos) { makeSelfDef(name, tpt) }
                 case _ =>
               }
           }
-          inNextToken
+          in.nextToken()
         } else {
           stats += first
           if (in.token != RBRACE && in.token != EOF/* !isStatSep(in.token)*/) acceptStatSep()
         }
       }
-      while (inToken != RBRACE && inToken != EOF) {
-        if (inToken == IMPORT) {
+      while (in.token != RBRACE && in.token != EOF) {
+        if (in.token == IMPORT) {
+          in.flushDoc
           stats ++= importClause()
         } else if (isExprIntro) {
+          in.flushDoc
           stats += statement(InTemplate)
-        } else if (isDefIntro || isModifier || inToken == LBRACKET /*todo: remove */ || inToken == AT) {
-          if (isPre) // @S: avoid caching by calling a different method that does the same thing (except in the IDE) 
-            stats ++= joinComment(preNonLocalDefOrDcl)
-          else stats ++= joinComment(nonLocalDefOrDcl)
+        } else if (isDefIntro || isModifier || in.token == LBRACKET /*todo: remove */ || in.token == AT) {
+          stats ++= joinComment(nonLocalDefOrDcl)
         } else if (!isStatSep) {
           syntaxErrorOrIncomplete("illegal start of definition", true)
         }
-        if (inToken != RBRACE && inToken != EOF) acceptStatSep()
+        if (in.token != RBRACE && in.token != EOF) acceptStatSep()
       }
       (self, stats.toList)
     }
      
-     
-
     /** RefineStatSeq    ::= RefineStat {semi RefineStat}
      *  RefineStat       ::= Dcl
      *                     | type TypeDef
@@ -2434,13 +2626,16 @@ trait Parsers extends NewScanners with MarkupParsers {
      */
     def refineStatSeq(): List[Tree] = checkNoEscapingPlaceholders {
       val stats = new ListBuffer[Tree]
-      while (inToken != RBRACE && inToken != EOF) {
+      while (in.token != RBRACE && in.token != EOF) {
         if (isDclIntro) { // don't IDE hook
-          stats ++= joinComment(defOrDcl(NoMods))
+          stats ++= joinComment(defOrDcl(in.offset, NoMods))
         } else if (!isStatSep) {
-          syntaxErrorOrIncomplete("illegal start of declaration", true)
+          syntaxErrorOrIncomplete(
+            "illegal start of declaration"+
+            (if (inFunReturnType) " (possible cause: missing `=' in front of current method body)"
+             else ""), true)
         }
-        if (inToken != RBRACE) acceptStatSep()
+        if (in.token != RBRACE) acceptStatSep()
       }
       stats.toList
     }
@@ -2449,21 +2644,25 @@ trait Parsers extends NewScanners with MarkupParsers {
      *  Here's an idea how to fill in start and end positions.
     def localDef : List[Tree] = {
       atEndPos {
-        atStartPos(inCurrentPos) {
+        atStartPos(in.offset) {
           val annots = annotations(true)
           val mods = localModifiers() withAnnotations annots
           if (!(mods hasFlag ~(Flags.IMPLICIT | Flags.LAZY))) defOrDcl(mods)
           else List(tmplDef(mods))
         }
-      } (inCurrentPos)
+      } (in.offset)
     }
     */
 
-    def localDef : List[Tree] = {
-      val annots = annotations(true)
-      val mods = localModifiers() withAnnotations annots
-      if (!(mods hasFlag ~(Flags.IMPLICIT | Flags.LAZY))) defOrDcl(mods)
-      else List(tmplDef(mods))
+    def localDef(implicitMod: Int): List[Tree] = {
+      val annots = annotations(true, false)
+      val pos = in.offset
+      val mods = (localModifiers() | implicitMod) withAnnotations annots
+      val defs = 
+        if (!(mods hasFlag ~(Flags.IMPLICIT | Flags.LAZY))) defOrDcl(pos, mods)
+        else List(tmplDef(pos, mods))
+      if (in.token != RBRACE && in.token != CASE) defs
+      else defs ::: List(Literal(()).setPos(o2p(in.offset)))
     }
 
     /** BlockStatSeq ::= { BlockStat semi } [ResultExpr]
@@ -2474,66 +2673,78 @@ trait Parsers extends NewScanners with MarkupParsers {
      *                 |
      */
     def blockStatSeq(stats: ListBuffer[Tree]): List[Tree] = checkNoEscapingPlaceholders {
-      var keepGoing = true
-      var hasError = false
-      while ((inToken != RBRACE) && (inToken != EOF) && (inToken != CASE) && keepGoing) {
-        var hasError0 = hasError
-        hasError = false
-        if (inToken == IMPORT) {
+      while ((in.token != RBRACE) && (in.token != EOF) && (in.token != CASE)) {
+        if (in.token == IMPORT) {
           stats ++= importClause()
           acceptStatSep()
         } else if (isExprIntro) {
           stats += statement(InBlock)
-          if (inToken != RBRACE && inToken != CASE) acceptStatSep()
+          if (in.token != RBRACE && in.token != CASE) acceptStatSep()
         } else if (isDefIntro || isLocalModifier || in.token == AT) {
-          stats ++= localDef
-          if (inToken == RBRACE || inToken == CASE) {
-            syntaxError("block must end in result expression, not in definition", false)
-            stats += Literal(()).setPos(inCurrentPos)
-          } else acceptStatSep()
+          if (in.token == IMPLICIT) {
+            val start = in.skipToken()
+            if (isIdent) stats += implicitClosure(start, InBlock)
+            else stats ++= localDef(Flags.IMPLICIT)
+          } else {
+            stats ++= localDef(0)
+          }
+          if (in.token != RBRACE && in.token != CASE) acceptStatSep()
         } else if (isStatSep) {
-          inNextToken
+          in.nextToken()
         } else {
-          syntaxErrorOrIncomplete("illegal start of statement", true)
-          if (hasError0) keepGoing = false else hasError = true
+          val addendum = if (isModifier) " (no modifiers allowed here)" else ""
+          syntaxErrorOrIncomplete("illegal start of statement" + addendum, true)
         }
       }
       stats.toList
     }
 
-    /** CompilationUnit ::= [package QualId semi] TopStatSeq 
+    /** CompilationUnit ::= {package QualId semi} TopStatSeq
      */
     def compilationUnit(): Tree = checkNoEscapingPlaceholders {
-      var pos = inCurrentPos;
-      {
+      def topstats(): List[Tree] = {
         val ts = new ListBuffer[Tree]
-        // @S: the IDE can insert phantom semi-colons before package during editing
-        // @S: just eat them (doesn't really change the grammar)
-        while (inToken == SEMI) inNextToken
-        if (inToken == PACKAGE) {
-          inNextToken
-          val pkg = qualId()
-          newLineOptWhenFollowedBy(LBRACE)
-          if (inToken == EOF) {
-            ts += makePackaging(pkg, List())
-          } else if (isStatSep) {
-            inNextToken
-            ts += makePackaging(pkg, topStatSeq())
+        while (in.token == SEMI) in.nextToken()
+        val start = in.offset
+        if (in.token == PACKAGE) {
+          in.nextToken()   
+          if (in.token == OBJECT) {
+            ts ++= joinComment(List(makePackageObject(start, objectDef(in.offset, NoMods))))
+            if (in.token != EOF) {
+              acceptStatSep()
+              ts ++= topStatSeq()
+            }
           } else {
-            accept(LBRACE)
-            ts += makePackaging(pkg, topStatSeq())
-            accept(RBRACE)
-            ts ++= topStatSeq()
+            in.flushDoc
+            if (in.token == IDENTIFIER && in.name.encode == nme.scala_)
+              inScalaPackage = true
+            val pkg = qualId()
+            newLineOptWhenFollowedBy(LBRACE)
+            if (in.token == EOF) {
+              ts += makePackaging(start, pkg, List())
+            } else if (isStatSep) {
+              in.nextToken()
+              ts += makePackaging(start, pkg, topstats())
+            } else {
+              accept(LBRACE)
+              ts += makePackaging(start, pkg, topStatSeq())
+              accept(RBRACE)
+              ts ++= topStatSeq()
+            }
           }
         } else {
           ts ++= topStatSeq()
         }
-        val stats = ts.toList
-        val usePos = if (stats.isEmpty || stats.head.pos == NoPosition) i2p(pos) else stats.head.pos
-        atPos(usePos) { stats match {        
-          case List(stat @ PackageDef(_, _)) => stat
-          case _ => makePackaging(Ident(nme.EMPTY_PACKAGE_NAME), stats)
-        }}
+        ts.toList
+      }
+      topstats() match {        
+        case List(stat @ PackageDef(_, _)) => stat
+        case stats =>
+          val start =
+            if (stats forall (_ == EmptyTree)) 0
+            else wrappingPos(stats).startOrPoint
+
+          makePackaging(start, atPos(start, start, start) { Ident(nme.EMPTY_PACKAGE_NAME) }, stats)
       }
     }
   }
diff --git a/src/compiler/scala/tools/nsc/ast/parser/Patch.scala b/src/compiler/scala/tools/nsc/ast/parser/Patch.scala
new file mode 100644
index 0000000..a55f841
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/ast/parser/Patch.scala
@@ -0,0 +1,8 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
+ * @author  Martin Odersky
+ */
+package scala.tools.nsc.ast.parser
+
+class Patch(off: Int, change: Change)
+
diff --git a/src/compiler/scala/tools/nsc/ast/parser/Scanners.scala b/src/compiler/scala/tools/nsc/ast/parser/Scanners.scala
index a0fb742..f3d618e 100644
--- a/src/compiler/scala/tools/nsc/ast/parser/Scanners.scala
+++ b/src/compiler/scala/tools/nsc/ast/parser/Scanners.scala
@@ -1,341 +1,211 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: Scanners.scala 16881 2009-01-09 16:28:11Z cunei $
-
-package scala.tools.nsc.ast.parser
+package scala.tools.nsc
+package ast.parser
 
 import scala.tools.nsc.util._
-import SourceFile.{LF, FF, CR, SU}
+import Chars._
 import Tokens._
+import scala.annotation.switch
+import scala.collection.mutable.{ListBuffer, ArrayBuffer}
+import scala.xml.Utility.{ isNameStart }
 
 trait Scanners {
   val global : Global
   import global._
-  abstract class AbstractTokenData {
-    def token: Int
-    type ScanPosition
-    val NoPos: ScanPosition
-    def pos: ScanPosition
-    def currentPos: ScanPosition 
-    def name: Name
-  }
 
-  /** A class for representing a token's data. */
-  trait TokenData extends AbstractTokenData {
-    type ScanPosition = Int
+  /** Offset into source character array */
+  type Offset = Int
+
+  /** An undefined offset */
+  val NoOffset: Offset = -1
+
+  trait TokenData {
 
-    val NoPos: Int = -1
     /** the next token */
     var token: Int = EMPTY
-    /** the token's position */
-    var pos: Int = 0
-    override def currentPos: Int = pos - 1
 
-    /** the first character position after the previous token */
-    var lastPos: Int = 0
+    /** the offset of the first character of the current token */
+    var offset: Offset = 0
 
-    /** the name of an identifier or token */
+    /** the offset of the character following the token preceding this one */
+    var lastOffset: Offset = 0
+
+    /** the name of an identifier */
     var name: Name = null
 
+    /** the string value of a literal */
+    var strVal: String = null
+
     /** the base of a number */
     var base: Int = 0
 
     def copyFrom(td: TokenData) = {
       this.token = td.token
-      this.pos = td.pos
-      this.lastPos = td.lastPos
+      this.offset = td.offset
+      this.lastOffset = td.lastOffset
       this.name = td.name
+      this.strVal = td.strVal
       this.base = td.base
     }
   }
+  
+  abstract class Scanner extends CharArrayReader with TokenData {
 
-  /** ...
-   */
-  abstract class AbstractScanner extends AbstractTokenData {
-    implicit def p2g(pos: Position): ScanPosition
-    implicit def g2p(pos: ScanPosition): Position
-    def warning(pos: ScanPosition, msg: String): Unit
-    def error  (pos: ScanPosition, msg: String): Unit
-    def incompleteInputError(pos: ScanPosition, msg: String): Unit
-    def deprecationWarning(pos: ScanPosition, msg: String): Unit
-    /** the last error position
-     */
-    var errpos: ScanPosition 
-    var lastPos: ScanPosition
-    def skipToken: ScanPosition
-    def nextToken: Unit
-    def next: AbstractTokenData
-    def intVal(negated: Boolean): Long
-    def floatVal(negated: Boolean): Double
-    def intVal: Long = intVal(false)
-    def floatVal: Double = floatVal(false)
-    //def token2string(token : Int) : String = configuration.token2string(token)
-    /** return recent scala doc, if any */
-    def flushDoc: String
-  }
-
-  object ScannerConfiguration {
-//  Keywords -----------------------------------------------------------------
-    /** Keyword array; maps from name indices to tokens */
-    private var key: Array[Byte] = _
-    private var maxKey = 0
-    private var tokenName = new Array[Name](128)
+    def flush = { charOffset = offset; nextChar(); this }
 
-    {
-      var tokenCount = 0
+    def resume(lastCode: Int) = {
+      token = lastCode
+      assert(next.token == EMPTY || reporter.hasErrors)
+      nextToken()
+    }
 
-      // Enter keywords
+    // things to fill in, in addition to buf, decodeUni
+    def warning(off: Offset, msg: String): Unit
+    def error  (off: Offset, msg: String): Unit
+    def incompleteInputError(off: Offset, msg: String): Unit
+    def deprecationWarning(off: Offset, msg: String): Unit
 
-      def enterKeyword(n: Name, tokenId: Int) {
-        while (tokenId >= tokenName.length) {
-          val newTokName = new Array[Name](tokenName.length * 2)
-          Array.copy(tokenName, 0, newTokName, 0, newTokName.length)
-          tokenName = newTokName
-        }
-        tokenName(tokenId) = n
-        if (n.start > maxKey) maxKey = n.start
-        if (tokenId >= tokenCount) tokenCount = tokenId + 1
-      }
+    /** the last error offset
+     */
+    var errOffset: Offset = NoOffset
 
-      enterKeyword(nme.ABSTRACTkw, ABSTRACT)
-      enterKeyword(nme.CASEkw, CASE)
-      enterKeyword(nme.CATCHkw, CATCH)
-      enterKeyword(nme.CLASSkw, CLASS)
-      enterKeyword(nme.DEFkw, DEF)
-      enterKeyword(nme.DOkw, DO)
-      enterKeyword(nme.ELSEkw, ELSE)
-      enterKeyword(nme.EXTENDSkw, EXTENDS)
-      enterKeyword(nme.FALSEkw, FALSE)
-      enterKeyword(nme.FINALkw, FINAL)
-      enterKeyword(nme.FINALLYkw, FINALLY)
-      enterKeyword(nme.FORkw, FOR)
-      enterKeyword(nme.FORSOMEkw, FORSOME)
-      enterKeyword(nme.IFkw, IF)
-      enterKeyword(nme.IMPLICITkw, IMPLICIT)
-      enterKeyword(nme.IMPORTkw, IMPORT)
-      enterKeyword(nme.LAZYkw, LAZY)
-      enterKeyword(nme.MATCHkw, MATCH)
-      enterKeyword(nme.NEWkw, NEW)
-      enterKeyword(nme.NULLkw, NULL)
-      enterKeyword(nme.OBJECTkw, OBJECT)
-      enterKeyword(nme.OVERRIDEkw, OVERRIDE)
-      enterKeyword(nme.PACKAGEkw, PACKAGE)
-      enterKeyword(nme.PRIVATEkw, PRIVATE)
-      enterKeyword(nme.PROTECTEDkw, PROTECTED)
-      enterKeyword(nme.REQUIRESkw, REQUIRES)
-      enterKeyword(nme.RETURNkw, RETURN)
-      enterKeyword(nme.SEALEDkw, SEALED)
-      enterKeyword(nme.SUPERkw, SUPER)
-      enterKeyword(nme.THISkw, THIS)
-      enterKeyword(nme.THROWkw, THROW)
-      enterKeyword(nme.TRAITkw, TRAIT)
-      enterKeyword(nme.TRUEkw, TRUE)
-      enterKeyword(nme.TRYkw, TRY)
-      enterKeyword(nme.TYPEkw, TYPE)
-      enterKeyword(nme.VALkw, VAL)
-      enterKeyword(nme.VARkw, VAR)
-      enterKeyword(nme.WHILEkw, WHILE)
-      enterKeyword(nme.WITHkw, WITH)
-      enterKeyword(nme.YIELDkw, YIELD)
-      enterKeyword(nme.DOTkw, DOT)
-      enterKeyword(nme.USCOREkw, USCORE)
-      enterKeyword(nme.COLONkw, COLON)
-      enterKeyword(nme.EQUALSkw, EQUALS)
-      enterKeyword(nme.ARROWkw, ARROW)
-      enterKeyword(nme.LARROWkw, LARROW)
-      enterKeyword(nme.SUBTYPEkw, SUBTYPE)
-      enterKeyword(nme.VIEWBOUNDkw, VIEWBOUND)
-      enterKeyword(nme.SUPERTYPEkw, SUPERTYPE)
-      enterKeyword(nme.HASHkw, HASH)
-      enterKeyword(nme.ATkw, AT)
-
-      // Build keyword array
-      key = new Array[Byte](maxKey + 1)
-      for (i <- 0 to maxKey)
-        key(i) = IDENTIFIER
-      for (j <- 0 until tokenCount)
-        if (tokenName(j) ne null)
-          key(tokenName(j).start) = j.asInstanceOf[Byte]
+    /** A character buffer for literals
+     */  
+    val cbuf = new StringBuilder
 
+    /** append Unicode character to "cbuf" buffer
+     */
+    protected def putChar(c: Char) { 
+//      assert(cbuf.size < 10000, cbuf)
+      cbuf.append(c) 
     }
-//Token representation -----------------------------------------------------
-
-  /** Convert name to token */
-  def name2token(name: Name): Int =
-    if (name.start <= maxKey) key(name.start) else IDENTIFIER
 
-  /** Returns the string representation of given token. */
-  def token2string(token: Int): String = token match {
-    case IDENTIFIER | BACKQUOTED_IDENT =>
-      "identifier"/* + \""+name+"\""*/
-    case CHARLIT =>
-      "character literal"
-    case INTLIT =>
-      "integer literal"
-    case LONGLIT =>
-      "long literal"
-    case FLOATLIT =>
-      "float literal"
-    case DOUBLELIT =>
-      "double literal"
-    case STRINGLIT =>
-      "string literal"
-    case SYMBOLLIT =>
-      "symbol literal"
-    case LPAREN =>
-      "'('"
-    case RPAREN =>
-      "')'"
-    case LBRACE =>
-      "'{'"
-    case RBRACE =>
-      "'}'"
-    case LBRACKET =>
-      "'['"
-    case RBRACKET =>
-      "']'"
-    case EOF =>
-      "eof"
-    case ERROR =>
-      "something"
-    case SEMI =>
-      "';'"
-    case NEWLINE =>
-      "';'"
-    case NEWLINES =>
-      "';'"
-    case COMMA =>
-      "','"
-    case CASECLASS =>
-      "case class"
-    case CASEOBJECT =>
-      "case object"
-    case XMLSTART =>
-      "$XMLSTART$<"
-    case _ =>
-      try {
-        "'" + tokenName(token) + "'"
-      } catch {
-        case _: ArrayIndexOutOfBoundsException =>
-          "'<" + token + ">'"
-        case _: NullPointerException =>
-          "'<(" + token + ")>'"
-      }
+    /** Clear buffer and set name and token */
+    private def finishNamed() {
+      name = newTermName(cbuf.toString)
+      token = name2token(name)
+      cbuf.clear()
     }
-  }
-  
-  
-  /** A scanner for the programming language Scala.
-   *
-   *  @author     Matthias Zenger, Martin Odersky, Burak Emir
-   *  @version    1.1
-   */
-  abstract class Scanner extends AbstractScanner with TokenData {
-    override def intVal = super.intVal
-    override def floatVal = super.floatVal
-    override var errpos: Int = NoPos
-
-    val in: CharArrayReader
-
-    /** character buffer for literals
-     */  
-    val cbuf = new StringBuilder()
-
-    /** append Unicode character to "lit" buffer
-    */
-    protected def putChar(c: Char) { cbuf.append(c) }
 
-    /** Clear buffer and set name */
-    private def setName {
-      name = newTermName(cbuf.toString())
-      cbuf.setLength(0)
+    /** Clear buffer and set string */
+    private def setStrVal() {
+      strVal = cbuf.toString
+      cbuf.clear()
     }
 
+    /** Should doc comments be built? */
+    def buildDocs: Boolean = onlyPresentation
+  
     /** buffer for the documentation comment
      */
     var docBuffer: StringBuilder = null
+    var docPos: Position = null
 
-    def flushDoc = {
-      val ret = if (docBuffer != null) docBuffer.toString else null
+    /** Return current docBuffer and set docBuffer to null */
+    def flushDoc: DocComment = {
+      val ret = if (docBuffer != null) DocComment(docBuffer.toString, docPos) else null
       docBuffer = null
       ret
     }
-  
+
     /** add the given character to the documentation buffer 
      */
     protected def putDocChar(c: Char) {
       if (docBuffer ne null) docBuffer.append(c)
     }
+      
+    protected def foundComment(value: String, start: Int, end: Int) = ()
+
+    protected def foundDocComment(value: String, start: Int, end: Int) = ()
 
     private class TokenData0 extends TokenData
 
-    /** we need one token lookahead
+    /** we need one token lookahead and one token history
      */
     val next : TokenData = new TokenData0
     val prev : TokenData = new TokenData0
 
-    /** a stack which indicates whether line-ends can be statement separators
+    /** a stack of tokens which indicates whether line-ends can be statement separators
      */
     var sepRegions: List[Int] = List()
 
-    /** A new line was inserted where in version 1.0 it would not be.
-     *  Only significant if settings.migrate.value is set
-     */
-    var newNewLine = false
-
-    /** Parser is currently skipping ahead because of an error. 
-     *  Only significant if settings.migrate.value is set
-     */
-    var skipping = false
-
 // Get next token ------------------------------------------------------------
 
-    /** read next token and return last position
+    /** read next token and return last offset
      */
-    def skipToken: Int = {
-      val p = pos; nextToken
-      // XXX: account for off by one error //???
-      (p - 1)
+    def skipToken(): Offset = {
+      val off = offset
+      nextToken()
+      off
     }
     
-    def nextToken {
-      if (token == LPAREN) {
-        sepRegions = RPAREN :: sepRegions
-      } else if (token == LBRACKET) {
-        sepRegions = RBRACKET :: sepRegions
-      } else if  (token == LBRACE) {
-        sepRegions = RBRACE :: sepRegions
-      } else if (token == CASE) {
-        sepRegions = ARROW :: sepRegions
-      } else if (token == RBRACE) {
-        while (!sepRegions.isEmpty && sepRegions.head != RBRACE)
-          sepRegions = sepRegions.tail
-        if (!sepRegions.isEmpty)
-          sepRegions = sepRegions.tail
-      } else if (token == RBRACKET || token == RPAREN || token == ARROW) {
-        if (!sepRegions.isEmpty && sepRegions.head == token)
-          sepRegions = sepRegions.tail
+    /** Produce next token, filling TokenData fields of Scanner.
+     */
+    def nextToken() {
+      val lastToken = token
+      // Adapt sepRegions according to last token 
+      (lastToken: @switch) match {
+        case LPAREN => 
+          sepRegions = RPAREN :: sepRegions
+        case LBRACKET => 
+          sepRegions = RBRACKET :: sepRegions
+        case LBRACE =>
+          sepRegions = RBRACE :: sepRegions
+        case CASE =>
+          sepRegions = ARROW :: sepRegions
+        case RBRACE =>
+          sepRegions = sepRegions dropWhile (_ != RBRACE)
+          if (!sepRegions.isEmpty) sepRegions = sepRegions.tail
+        case RBRACKET | RPAREN | ARROW =>
+          if (!sepRegions.isEmpty && sepRegions.head == lastToken)
+            sepRegions = sepRegions.tail
+        case _ =>
+      }
+      (lastToken: @switch) match {
+        case RBRACE | RBRACKET | RPAREN =>
+          docBuffer = null
+        case _ =>
       }
 
-      val lastToken = token
+      // Read a token or copy it from `next` tokenData
       if (next.token == EMPTY) {
+        lastOffset = charOffset - 1
+        if(lastOffset > 0 && buf(lastOffset) == '\n' && buf(lastOffset - 1) == '\r') {
+          lastOffset -= 1
+        }
         fetchToken()
       } else {
         this copyFrom next
         next.token = EMPTY
       }
+
+      /** Insert NEWLINE or NEWLINES if
+       *  - we are after a newline
+       *  - we are within a { ... } or on toplevel (wrt sepRegions)
+       *  - the current token can start a statement and the one before can end it
+       *  insert NEWLINES if we are past a blank line, NEWLINE otherwise
+       */
+      if (!applyBracePatch() && afterLineEnd() && inLastOfStat(lastToken) && inFirstOfStat(token) &&
+          (sepRegions.isEmpty || sepRegions.head == RBRACE)) {
+        next copyFrom this
+        offset = if (lineStartOffset <= offset) lineStartOffset else lastLineStartOffset
+        token = if (pastBlankLine()) NEWLINES else NEWLINE
+      }
+
+      // Join CASE + CLASS => CASECLASS, CASE + OBJECT => CASEOBJECT, SEMI + ELSE => ELSE
       if (token == CASE) {
         prev copyFrom this
+        val nextLastOffset = charOffset - 1
         fetchToken()
         if (token == CLASS) {
           token = CASECLASS
-          lastPos = prev.lastPos
         } else if (token == OBJECT) {
           token = CASEOBJECT
-          lastPos = prev.lastPos
         } else {
+          lastOffset = nextLastOffset
           next copyFrom this
           this copyFrom prev
         }
@@ -346,293 +216,257 @@ trait Scanners {
           next copyFrom this
           this copyFrom prev
         }
-      } else if (token == IDENTIFIER && name == nme.MIXINkw) { //todo: remove eventually
-        prev.copyFrom(this)
-        fetchToken()
-        if (token == CLASS)
-          warning(prev.pos, "`mixin' is no longer a reserved word; you should use `trait' instead of `mixin class'");
-        next.copyFrom(this)
-        this.copyFrom(prev)
-      }
+      }  
 
-      if (afterLineEnd() && inLastOfStat(lastToken) && inFirstOfStat(token) &&
-          (sepRegions.isEmpty || sepRegions.head == RBRACE)) {
-        next copyFrom this
-        pos = in.lineStartPos
-        token = if (in.lastBlankLinePos > lastPos) NEWLINES else NEWLINE
-      }
+//      print("["+this+"]")
     }
 
-    private def afterLineEnd() = (
-      lastPos < in.lineStartPos && 
-      (in.lineStartPos <= pos ||
-       lastPos < in.lastLineStartPos && in.lastLineStartPos <= pos)
-    )
+    /** Is current token first one after a newline? */
+    private def afterLineEnd(): Boolean =
+      lastOffset < lineStartOffset && 
+      (lineStartOffset <= offset || 
+       lastOffset < lastLineStartOffset && lastLineStartOffset <= offset)
 
-    /** read next token
+    /** Is there a blank line between the current token and the last one?
+     *  @pre  afterLineEnd().
      */
-    private def fetchToken() {
-      if (token == EOF) return
-      lastPos = in.cpos - 1 // Position.encode(in.cline, in.ccol)
-      //var index = bp
-      while (true) {
-        in.ch match {
-          case ' ' | '\t' | CR | LF | FF =>
-            in.next
-          case _ =>
-            pos = in.cpos // Position.encode(in.cline, in.ccol)
-            in.ch match {
-              case '\u21D2' => 
-                in.next; token = ARROW
-                return
-              case '\u2190' => 
-                in.next; token = LARROW
-                return
-              case 'A' | 'B' | 'C' | 'D' | 'E' |
-                   'F' | 'G' | 'H' | 'I' | 'J' |
-                   'K' | 'L' | 'M' | 'N' | 'O' |
-                   'P' | 'Q' | 'R' | 'S' | 'T' |
-                   'U' | 'V' | 'W' | 'X' | 'Y' |
-                   'Z' | '$' | '_' |
-                   'a' | 'b' | 'c' | 'd' | 'e' |
-                   'f' | 'g' | 'h' | 'i' | 'j' |
-                   'k' | 'l' | 'm' | 'n' | 'o' |
-                   'p' | 'q' | 'r' | 's' | 't' |
-                   'u' | 'v' | 'w' | 'x' | 'y' |  // scala-mode: need to understand multi-line case patterns
-                   'z' =>
-                putChar(in.ch)
-                in.next
-                getIdentRest  // scala-mode: wrong indent for multi-line case blocks
-                return
-
-            case '<' => // is XMLSTART?
-              val last = in.last
-              in.next
-              last match {
-              case ' '|'\t'|'\n'|'{'|'('|'>' if xml.Parsing.isNameStart(in.ch) || in.ch == '!' || in.ch == '?' =>
-                token = XMLSTART
-              case _ =>
-                // Console.println("found '<', but last is '"+in.last+"'"); // DEBUG
-                putChar('<')
-                getOperatorRest
-              }
-              return
-
-            case '~' | '!' | '@' | '#' | '%' |
-                 '^' | '*' | '+' | '-' | /*'<' | */
-                 '>' | '?' | ':' | '=' | '&' | 
-                 '|' | '\\' =>
-               putChar(in.ch)
-               in.next
-               getOperatorRest; // XXX
-               return
-              case '/' =>
-                in.next
-                if (!skipComment()) {
-                  putChar('/')
-                  getOperatorRest
-                  return
-                }
-              case '0' =>
-                putChar(in.ch)
-                in.next
-                if (in.ch == 'x' || in.ch == 'X') {
-                  in.next
-                  base = 16
-                } else {
-                  base = 8
-                }
-                getNumber
-                return   
-              case '1' | '2' | '3' | '4' |
-                   '5' | '6' | '7' | '8' | '9' =>
-                base = 10
-                getNumber
-                return
-              case '`' => 
-                in.next
-                getStringLit('`', BACKQUOTED_IDENT)
-                return
-              case '\"' => 
-                in.next
-                if (in.ch == '\"') {
-                  in.next
-                  if (in.ch == '\"') {
-                    in.next
-                    val saved = in.lineStartPos
-                    getMultiLineStringLit
-                    if (in.lineStartPos != saved) // ignore linestarts within a mulit-line string 
-                      in.lastLineStartPos = saved
-                  } else {
-                    token = STRINGLIT
-                    name = nme.EMPTY
-                  }
-                } else {
-                  getStringLit('\"', STRINGLIT)
-                }
-                return
-              case '\'' =>
-                in.next
-                in.ch match {
-                  case 'A' | 'B' | 'C' | 'D' | 'E' |
-                       'F' | 'G' | 'H' | 'I' | 'J' |
-                       'K' | 'L' | 'M' | 'N' | 'O' |
-                       'P' | 'Q' | 'R' | 'S' | 'T' |
-                       'U' | 'V' | 'W' | 'X' | 'Y' |
-                       'Z' | '$' | '_' |
-                       'a' | 'b' | 'c' | 'd' | 'e' |
-                       'f' | 'g' | 'h' | 'i' | 'j' |
-                       'k' | 'l' | 'm' | 'n' | 'o' |
-                       'p' | 'q' | 'r' | 's' | 't' |
-                       'u' | 'v' | 'w' | 'x' | 'y' |
-                       'z' | 
-                       '0' | '1' | '2' | '3' | '4' |
-                       '5' | '6' | '7' | '8' | '9' =>
-                    putChar(in.ch)
-                    in.next
-                    if (in.ch != '\'') {
-                      getIdentRest
-                      token = SYMBOLLIT
-                      return
-                    }
-                  case _ =>
-                    if (Character.isUnicodeIdentifierStart(in.ch)) {
-                      putChar(in.ch)
-                      in.next
-                      if (in.ch != '\'') {
-                        getIdentRest
-                        token = SYMBOLLIT
-                        return
-                      }
-                    } else if (isSpecial(in.ch)) {
-                      putChar(in.ch)
-                      in.next
-                      if (in.ch != '\'') {
-                        getOperatorRest
-                        token = SYMBOLLIT
-                        return
-                      }
-                    } else {
-                      getlitch()
-                    }
-                }
-                if (in.ch == '\'') {
-                  in.next
-                  token = CHARLIT
-                  setName
-                } else {
-                  syntaxError("unclosed character literal")
-                }
-                return
-              case '.' =>
-                in.next
-                if ('0' <= in.ch && in.ch <= '9') {
-                  putChar('.'); getFraction
-                } else {
-                  token = DOT
-                }
-                return
-              case ';' =>
-                in.next; token = SEMI
-                return
-              case ',' =>
-                in.next; token = COMMA
-                return
-              case '(' =>   //scala-mode: need to understand character quotes
-                in.next; token = LPAREN
-                return
-              case '{' =>
-                in.next; token = LBRACE
-                return
-              case ')' =>
-                in.next; token = RPAREN
-                return
-              case '}' =>
-                in.next; 
-                token = RBRACE
-                return
-              case '[' =>
-                in.next; token = LBRACKET
-                return
-              case ']' =>
-                in.next; token = RBRACKET
-                return
-              case SU =>
-                if (!in.hasNext) token = EOF
-                else {
-                  syntaxError("illegal character")
-                  in.next
-                }
-                return
-              case _ =>
-                if (Character.isUnicodeIdentifierStart(in.ch)) {
-                  putChar(in.ch)
-                  in.next
-                  getIdentRest
-                } else if (isSpecial(in.ch)) {
-                  putChar(in.ch)
-                  getOperatorRest
-                } else {
-                  syntaxError("illegal character")
-                  in.next
-                }
-                return
+    private def pastBlankLine(): Boolean = {
+      var idx = lastOffset
+      var ch = buf(idx)
+      val end = offset
+      while (idx < end) {
+        if (ch == LF || ch == FF) {
+          do {
+            idx += 1; ch = buf(idx)
+            if (ch == LF || ch == FF) {
+//              println("blank line found at "+lastOffset+":"+(lastOffset to idx).map(buf(_)).toList)
+              return true
             }
+          } while (idx < end && ch <= ' ')
         }
+        idx += 1; ch = buf(idx)
+      }
+      false
+    }
+
+    /** read next token, filling TokenData fields of Scanner.
+     */
+    protected final def fetchToken() {
+      offset = charOffset - 1
+      (ch: @switch) match {
+        
+        case ' ' | '\t' | CR | LF | FF =>
+          nextChar()
+          fetchToken()
+        case 'A' | 'B' | 'C' | 'D' | 'E' |
+             'F' | 'G' | 'H' | 'I' | 'J' |
+             'K' | 'L' | 'M' | 'N' | 'O' |
+             'P' | 'Q' | 'R' | 'S' | 'T' |
+             'U' | 'V' | 'W' | 'X' | 'Y' |
+             'Z' | '$' | '_' |
+             'a' | 'b' | 'c' | 'd' | 'e' |
+             'f' | 'g' | 'h' | 'i' | 'j' |
+             'k' | 'l' | 'm' | 'n' | 'o' |
+             'p' | 'q' | 'r' | 's' | 't' |
+             'u' | 'v' | 'w' | 'x' | 'y' |  // scala-mode: need to understand multi-line case patterns
+             'z' =>
+          putChar(ch)
+          nextChar()
+          getIdentRest()  // scala-mode: wrong indent for multi-line case blocks
+        case '<' => // is XMLSTART?
+          val last = if (charOffset >= 2) buf(charOffset - 2) else ' '
+          nextChar()
+          last match {
+            case ' '|'\t'|'\n'|'{'|'('|'>' if isNameStart(ch) || ch == '!' || ch == '?' =>
+              token = XMLSTART
+            case _ =>
+              // Console.println("found '<', but last is '"+in.last+"'"); // DEBUG
+              putChar('<')
+              getOperatorRest()
+          }
+        case '~' | '!' | '@' | '#' | '%' |
+             '^' | '*' | '+' | '-' | /*'<' | */
+             '>' | '?' | ':' | '=' | '&' | 
+             '|' | '\\' =>
+          putChar(ch)
+          nextChar()
+          getOperatorRest() 
+        case '/' =>
+          nextChar()
+          if (skipComment()) {
+            fetchToken()
+          } else {
+            putChar('/')
+            getOperatorRest()
+          }
+        case '0' =>
+          putChar(ch)
+          nextChar()
+          if (ch == 'x' || ch == 'X') {
+            nextChar()
+            base = 16
+          } else {
+            base = 8
+          }
+          getNumber()
+        case '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' =>
+          base = 10
+          getNumber()
+        case '`' => 
+          getBackquotedIdent()
+        case '\"' => 
+          nextChar()
+          if (ch == '\"') {
+            nextChar()
+            if (ch == '\"') {
+              nextRawChar()
+              val saved = lineStartOffset
+              getMultiLineStringLit()
+              if (lineStartOffset != saved) // ignore linestarts within a multi-line string 
+                lastLineStartOffset = saved
+            } else {
+              token = STRINGLIT
+              strVal = ""
+            }
+          } else if (getStringLit('\"')) { 
+            setStrVal()
+            token = STRINGLIT 
+          } else {
+            syntaxError("unclosed string literal")
+          }
+        case '\'' =>
+          nextChar()
+          if (isIdentifierStart(ch))
+            charLitOr(getIdentRest)
+          else if (isOperatorPart(ch) && (ch != '\\'))
+            charLitOr(getOperatorRest)
+          else {
+            getLitChar()
+            if (ch == '\'') {
+              nextChar()
+              token = CHARLIT
+              setStrVal()
+            } else {
+              syntaxError("unclosed character literal")
+            }
+          }
+        case '.' =>
+          nextChar()
+          if ('0' <= ch && ch <= '9') {
+            putChar('.'); getFraction()
+          } else {
+            token = DOT
+          }
+        case ';' =>
+          nextChar(); token = SEMI
+        case ',' =>
+          nextChar(); token = COMMA
+        case '(' =>
+          nextChar(); token = LPAREN
+        case '{' =>
+          nextChar(); token = LBRACE
+        case ')' =>
+          nextChar(); token = RPAREN
+        case '}' =>
+          nextChar(); token = RBRACE
+        case '[' =>
+          nextChar(); token = LBRACKET
+        case ']' =>
+          nextChar(); token = RBRACKET
+        case SU =>
+          if (charOffset >= buf.length) token = EOF
+          else {
+            syntaxError("illegal character")
+            nextChar()
+          }
+        case _ =>
+          if (ch == '\u21D2') {
+            nextChar(); token = ARROW
+          } else if (ch == '\u2190') {
+            nextChar(); token = LARROW
+          } else if (Character.isUnicodeIdentifierStart(ch)) {
+            putChar(ch)
+            nextChar()
+            getIdentRest()
+          } else if (isSpecial(ch)) {
+            putChar(ch)
+            nextChar()
+            getOperatorRest()
+          } else {
+            syntaxError("illegal character")
+            nextChar()
+          }
       }
     }
 
     private def skipComment(): Boolean = {
-      if (in.ch == '/') {
-        do {
-          in.next
-        } while ((in.ch != CR) && (in.ch != LF) && (in.ch != SU))
-        true
-      } else if (in.ch == '*') {
-        docBuffer = null
-        var openComments = 1
-        in.next
-        val scalaDoc = ("/**", "*/")
-        if (in.ch == '*' && onlyPresentation)
-          docBuffer = new StringBuilder(scalaDoc._1)
-        while (openComments > 0) {
+
+      if (ch == '/' || ch == '*') {
+    	  
+        val comment = new StringBuilder("/")
+        def appendToComment() = comment.append(ch)
+
+        if (ch == '/') {
           do {
+        	appendToComment()
+            nextChar()
+          } while ((ch != CR) && (ch != LF) && (ch != SU))
+        } else {
+          docBuffer = null
+          var openComments = 1
+          appendToComment()
+          nextChar()
+          appendToComment()
+          var buildingDocComment = false
+          if (ch == '*' && buildDocs) {
+            buildingDocComment = true
+            docBuffer = new StringBuilder("/**")
+          }
+          while (openComments > 0) {
             do {
-              if (in.ch == '/') {
-                in.next; putDocChar(in.ch)
-                if (in.ch == '*') {
-                  in.next; putDocChar(in.ch)
-                  openComments = openComments + 1
+              do {
+                if (ch == '/') {
+                  nextChar(); putDocChar(ch); appendToComment()
+                  if (ch == '*') {
+                    nextChar(); putDocChar(ch); appendToComment()
+                    openComments += 1
+                  }
                 }
+                if (ch != '*' && ch != SU) {
+                  nextChar(); putDocChar(ch); appendToComment()
+                }
+              } while (ch != '*' && ch != SU)
+              while (ch == '*') {
+                nextChar(); putDocChar(ch); appendToComment()
               }
-              if (in.ch != '*' && in.ch != SU) {
-                in.next; putDocChar(in.ch)
-              }
-            } while (in.ch != '*' && in.ch != SU)
-            while (in.ch == '*') {
-              in.next; putDocChar(in.ch)
-            }
-          } while (in.ch != '/' && in.ch != SU)
-          if (in.ch == '/') in.next
-          else incompleteInputError("unclosed comment")
-          openComments -= 1
+            } while (ch != '/' && ch != SU)
+            if (ch == '/') nextChar()
+            else incompleteInputError("unclosed comment")
+            openComments -= 1
+          }
+          
+          if (buildingDocComment)
+            foundDocComment(comment.toString, offset, charOffset - 2)
         }
+        
+        foundComment(comment.toString, offset, charOffset - 2)
         true
       } else {
         false
       }
     }
 
+    /** Can token start a statement? */
     def inFirstOfStat(token: Int) = token match {
-      case EOF | CASE | CATCH | ELSE | EXTENDS | FINALLY | FORSOME | MATCH |
-           REQUIRES | WITH | YIELD | COMMA | SEMI | NEWLINE | NEWLINES | DOT |
-           USCORE | COLON | EQUALS | ARROW | LARROW | SUBTYPE | VIEWBOUND |
-           SUPERTYPE | HASH | RPAREN | RBRACKET | RBRACE => // todo: add LBRACKET
+      case EOF | CATCH | ELSE | EXTENDS | FINALLY | FORSOME | MATCH | WITH | YIELD |
+           COMMA | SEMI | NEWLINE | NEWLINES | DOT | COLON | EQUALS | ARROW | LARROW | 
+           SUBTYPE | VIEWBOUND | SUPERTYPE | HASH | RPAREN | RBRACKET | RBRACE | LBRACKET =>
         false
       case _ =>
         true
     }
 
+    /** Can token end a statement? */
     def inLastOfStat(token: Int) = token match {
       case CHARLIT | INTLIT | LONGLIT | FLOATLIT | DOUBLELIT | STRINGLIT | SYMBOLLIT |
            IDENTIFIER | BACKQUOTED_IDENT | THIS | NULL | TRUE | FALSE | RETURN | USCORE | 
@@ -644,152 +478,116 @@ trait Scanners {
 
 // Identifiers ---------------------------------------------------------------
 
-    def isIdentStart(c: Char): Boolean = (
-      ('A' <= c && c <= 'Z') ||
-      ('a' <= c && c <= 'a') ||
-      (c == '_') || (c == '$') ||
-      Character.isUnicodeIdentifierStart(c)
-    )
-
-    def isIdentPart(c: Char) = (
-      isIdentStart(c) || 
-      ('0' <= c && c <= '9') ||
-      Character.isUnicodeIdentifierPart(c)
-    )
-
-    def isSpecial(c: Char) = {
-      val chtp = Character.getType(c)
-      chtp == Character.MATH_SYMBOL || chtp == Character.OTHER_SYMBOL
+    private def getBackquotedIdent(): Unit = {
+      nextChar()
+      if (getStringLit('`')) { 
+        finishNamed(); 
+        if (name.length == 0) syntaxError("empty quoted identifier")
+        token = BACKQUOTED_IDENT 
+      }
+      else syntaxError("unclosed quoted identifier")
     }
 
-    private def getIdentRest {
-      while (true) {
-        in.ch match {
-          case 'A' | 'B' | 'C' | 'D' | 'E' |
-               'F' | 'G' | 'H' | 'I' | 'J' |
-               'K' | 'L' | 'M' | 'N' | 'O' |
-               'P' | 'Q' | 'R' | 'S' | 'T' |
-               'U' | 'V' | 'W' | 'X' | 'Y' |
-               'Z' | '$' |
-               'a' | 'b' | 'c' | 'd' | 'e' |
-               'f' | 'g' | 'h' | 'i' | 'j' |
-               'k' | 'l' | 'm' | 'n' | 'o' |
-               'p' | 'q' | 'r' | 's' | 't' |
-               'u' | 'v' | 'w' | 'x' | 'y' |
-               'z' |
-               '0' | '1' | '2' | '3' | '4' |
-               '5' | '6' | '7' | '8' | '9' =>
-            putChar(in.ch)
-            in.next
-            
-          case '_' =>
-            putChar(in.ch)
-            in.next
-            getIdentOrOperatorRest
-            return
-          case SU =>
-            setName
-            token = ScannerConfiguration.name2token(name)
-            return
-          case _ =>
-            if (Character.isUnicodeIdentifierPart(in.ch)) {
-              putChar(in.ch)
-              in.next
-            } else {
-              setName
-              token = ScannerConfiguration.name2token(name)
-              return
-            }
+    private def getIdentRest(): Unit = (ch: @switch) match {
+      case 'A' | 'B' | 'C' | 'D' | 'E' |
+           'F' | 'G' | 'H' | 'I' | 'J' |
+           'K' | 'L' | 'M' | 'N' | 'O' |
+           'P' | 'Q' | 'R' | 'S' | 'T' |
+           'U' | 'V' | 'W' | 'X' | 'Y' |
+           'Z' | '$' |
+           'a' | 'b' | 'c' | 'd' | 'e' |
+           'f' | 'g' | 'h' | 'i' | 'j' |
+           'k' | 'l' | 'm' | 'n' | 'o' |
+           'p' | 'q' | 'r' | 's' | 't' |
+           'u' | 'v' | 'w' | 'x' | 'y' |
+           'z' |
+           '0' | '1' | '2' | '3' | '4' |
+           '5' | '6' | '7' | '8' | '9' =>
+        putChar(ch)
+        nextChar()
+        getIdentRest()
+      case '_' =>
+        putChar(ch)
+        nextChar()
+        getIdentOrOperatorRest()
+      case SU => // strangely enough, Character.isUnicodeIdentifierPart(SU) returns true!
+        finishNamed()
+      case _ =>
+        if (Character.isUnicodeIdentifierPart(ch)) {
+          putChar(ch)
+          nextChar()
+          getIdentRest()
+        } else {
+          finishNamed()
         }
-      }
     }
 
-    private def getOperatorRest {
-      while (true) {
-        in.ch match {
-          case '~' | '!' | '@' | '#' | '%' | 
-               '^' | '*' | '+' | '-' | '<' |
-               '>' | '?' | ':' | '=' | '&' | 
-               '|' | '\\' =>
-            putChar(in.ch)
-            in.next
-          case '/' =>
-            in.next
-            if (skipComment) {
-              setName
-              token = ScannerConfiguration.name2token(name)
-              return
-            } else putChar('/')
-          case _ =>
-            if (isSpecial(in.ch)) {
-              putChar(in.ch)
-              in.next
-            } else {
-              setName
-              token = ScannerConfiguration.name2token(name)
-              return
-            }
-        }
-      }
+    private def getOperatorRest(): Unit = (ch: @switch) match {
+      case '~' | '!' | '@' | '#' | '%' | 
+           '^' | '*' | '+' | '-' | '<' |
+           '>' | '?' | ':' | '=' | '&' | 
+           '|' | '\\' =>
+        putChar(ch); nextChar(); getOperatorRest()
+      case '/' =>
+        nextChar()
+        if (skipComment()) finishNamed()
+        else { putChar('/'); getOperatorRest() }
+      case _ =>
+        if (isSpecial(ch)) { putChar(ch); nextChar(); getOperatorRest() }
+        else finishNamed()
     }
 
-    private def getIdentOrOperatorRest {
-      if (isIdentPart(in.ch)) 
-        getIdentRest
-      else in.ch match {
+    private def getIdentOrOperatorRest() {
+      if (isIdentifierPart(ch)) 
+        getIdentRest()
+      else ch match {
         case '~' | '!' | '@' | '#' | '%' |
              '^' | '*' | '+' | '-' | '<' |
              '>' | '?' | ':' | '=' | '&' | 
              '|' | '\\' | '/' =>
-          getOperatorRest
+          getOperatorRest()
         case _ =>
-          if (isSpecial(in.ch)) getOperatorRest
-          else {               
-            setName
-            token = ScannerConfiguration.name2token(name)
-          }
+          if (isSpecial(ch)) getOperatorRest()
+          else finishNamed()
       }
     }
  
-    private def getStringLit(delimiter: Char, litType: Int) {
-      //assert((litType==STRINGLIT) || (litType==IDENTIFIER))
-      while (in.ch != delimiter && (in.isUnicode || in.ch != CR && in.ch != LF && in.ch != SU)) {
-        getlitch()
-      }
-      if (in.ch == delimiter) {
-        token = litType
-        setName
-        in.next
-      } else {
-        val typeDesc = if(litType == STRINGLIT) "string literal" else "quoted identifier"
-        syntaxError("unclosed " + typeDesc)
+    private def getStringLit(delimiter: Char): Boolean = {
+      while (ch != delimiter && (isUnicodeEscape || ch != CR && ch != LF && ch != SU)) {
+        getLitChar()
       }
+      if (ch == delimiter) { nextChar(); true }
+      else false
     }
 
-    private def getMultiLineStringLit {
-      if (in.ch == '\"') {
-        in.next
-        if (in.ch == '\"') {
-          in.next
-          if (in.ch == '\"') {
-            in.next
+    private def getMultiLineStringLit() {
+      if (ch == '\"') {
+        nextRawChar()
+        if (ch == '\"') {
+          nextRawChar()
+          if (ch == '\"') {
+            nextChar()
+            while (ch == '\"') {
+              putChar('\"')
+              nextChar()
+            }
             token = STRINGLIT
-            setName
+            setStrVal()
           } else {
             putChar('\"')
             putChar('\"')
-            getMultiLineStringLit
+            getMultiLineStringLit()
           }
         } else {
           putChar('\"')
-          getMultiLineStringLit
+          getMultiLineStringLit()
         }
-      } else if (in.ch == SU) {
+      } else if (ch == SU) {
         incompleteInputError("unclosed multi-line string literal")
       } else {
-        putChar(in.ch)
-        in.next
-        getMultiLineStringLit
+        putChar(ch)
+        nextRawChar()
+        getMultiLineStringLit()
       }
     }
 
@@ -797,24 +595,24 @@ trait Scanners {
 
     /** read next character in character or string literal:
     */
-    protected def getlitch() =
-      if (in.ch == '\\') {
-        in.next
-        if ('0' <= in.ch && in.ch <= '7') {
-          val leadch: Char = in.ch
-          var oct: Int = in.digit2int(in.ch, 8)
-          in.next
-          if ('0' <= in.ch && in.ch <= '7') {
-            oct = oct * 8 + in.digit2int(in.ch, 8)
-            in.next
-            if (leadch <= '3' && '0' <= in.ch && in.ch <= '7') {
-              oct = oct * 8 + in.digit2int(in.ch, 8)
-              in.next
+    protected def getLitChar() =
+      if (ch == '\\') {
+        nextChar()
+        if ('0' <= ch && ch <= '7') {
+          val leadch: Char = ch
+          var oct: Int = digit2int(ch, 8)
+          nextChar()
+          if ('0' <= ch && ch <= '7') {
+            oct = oct * 8 + digit2int(ch, 8)
+            nextChar()
+            if (leadch <= '3' && '0' <= ch && ch <= '7') {
+              oct = oct * 8 + digit2int(ch, 8)
+              nextChar()
             }
           }
-          putChar(oct.asInstanceOf[Char])
+          putChar(oct.toChar)
         } else {
-          in.ch match {
+          ch match {
             case 'b'  => putChar('\b')
             case 't'  => putChar('\t')
             case 'n'  => putChar('\n')
@@ -824,71 +622,77 @@ trait Scanners {
             case '\'' => putChar('\'')
             case '\\' => putChar('\\')
             case _    =>
-              syntaxError(in.cpos - 1, "invalid escape character")
-              putChar(in.ch)
+              syntaxError(charOffset - 1, "invalid escape character")
+              putChar(ch)
           }
-          in.next
+          nextChar()
         }
       } else  {
-        putChar(in.ch)
-        in.next
+        putChar(ch)
+        nextChar()
       }
 
     /** read fractional part and exponent of floating point number
      *  if one is present.
      */
-    protected def getFraction {
+    protected def getFraction() {
       token = DOUBLELIT
-      while ('0' <= in.ch && in.ch <= '9') {
-        putChar(in.ch)
-        in.next
+      while ('0' <= ch && ch <= '9') {
+        putChar(ch)
+        nextChar()
       }
-      if (in.ch == 'e' || in.ch == 'E') {
-        val lookahead = in.copy
-        lookahead.next
+      if (ch == 'e' || ch == 'E') {
+        val lookahead = lookaheadReader
+        lookahead.nextChar()
         if (lookahead.ch == '+' || lookahead.ch == '-') {
-          lookahead.next
+          lookahead.nextChar()
         }
         if ('0' <= lookahead.ch && lookahead.ch <= '9') {
-          putChar(in.ch)
-          in.next
-          if (in.ch == '+' || in.ch == '-') {
-            putChar(in.ch)
-            in.next
+          putChar(ch)
+          nextChar()
+          if (ch == '+' || ch == '-') {
+            putChar(ch)
+            nextChar()
           }
-          while ('0' <= in.ch && in.ch <= '9') {
-            putChar(in.ch)
-            in.next
+          while ('0' <= ch && ch <= '9') {
+            putChar(ch)
+            nextChar()
           }
         }
         token = DOUBLELIT
       }
-      if (in.ch == 'd' || in.ch == 'D') {
-        putChar(in.ch)
-        in.next
+      if (ch == 'd' || ch == 'D') {
+        putChar(ch)
+        nextChar()
         token = DOUBLELIT
-      } else if (in.ch == 'f' || in.ch == 'F') {
-        putChar(in.ch)
-        in.next
+      } else if (ch == 'f' || ch == 'F') {
+        putChar(ch)
+        nextChar()
         token = FLOATLIT
       }
-      setName
+      checkNoLetter()
+      setStrVal()
     }
 
-    /** convert name to long value
+    /** Convert current strVal to char value
+     */
+    def charVal: Char = if (strVal.length > 0) strVal.charAt(0) else 0
+
+    /** Convert current strVal, base to long value
+     *  This is tricky because of max negative value.
      */
     def intVal(negated: Boolean): Long = {
       if (token == CHARLIT && !negated) {
-        if (name.length > 0) name(0) else 0
+        charVal
       } else {
         var value: Long = 0
         val divider = if (base == 10) 1 else 2
         val limit: Long =
-          if (token == LONGLIT) Math.MAX_LONG else Math.MAX_INT
+          if (token == LONGLIT) Long.MaxValue else Int.MaxValue
         var i = 0
-        val len = name.length
+        val len = strVal.length
         while (i < len) {
-          val d = in.digit2int(name(i), base)
+          val d = digit2int(strVal charAt i, base)
           if (d < 0) {
             syntaxError("malformed integer number")
             return 0
@@ -907,14 +711,15 @@ trait Scanners {
       }
     }
 
+    def intVal: Long = intVal(false)
 
-    /** convert name, base to double value
+    /** Convert current strVal, base to double value
     */
     def floatVal(negated: Boolean): Double = {
       val limit: Double = 
-        if (token == DOUBLELIT) Math.MAX_DOUBLE else Math.MAX_FLOAT
+        if (token == DOUBLELIT) Double.MaxValue else Float.MaxValue
       try {
-        val value: Double = java.lang.Double.valueOf(name.toString()).doubleValue()
+        val value: Double = java.lang.Double.valueOf(strVal).doubleValue()
         if (value > limit)
           syntaxError("floating point number too large")
         if (negated) -value else value
@@ -924,70 +729,116 @@ trait Scanners {
           0.0
       }
     }
-    /** read a number into name and set base
+
+    def floatVal: Double = floatVal(false)
+
+    def checkNoLetter() {
+      if (isIdentifierPart(ch) && ch >= ' ') 
+        syntaxError("Invalid literal number")
+    }
+
+    /** Read a number into strVal and set base
     */
-    protected def getNumber {
-      while (in.digit2int(in.ch, if (base < 10) 10 else base) >= 0) {
-        putChar(in.ch)
-        in.next
+    protected def getNumber() {
+      def isDigit(c: Char) = java.lang.Character isDigit c
+      val base1 = if (base < 10) 10 else base 
+        // read 8,9's even if format is octal, produce a malformed number error afterwards.
+      while (digit2int(ch, base1) >= 0) {
+        putChar(ch)
+        nextChar()
       }
       token = INTLIT
-      if (base <= 10 && in.ch == '.') {
-        val lookahead = in.copy
-        lookahead.next
-        lookahead.ch match {
-          case '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | 
-               '8' | '9' | 'd' | 'D' | 'e' | 'E' | 'f' | 'F' =>
-            putChar(in.ch)
-            in.next
-            return getFraction
-          case _ =>
-            if (!isIdentStart(lookahead.ch)) {
-              putChar(in.ch)
-              in.next
-              return getFraction
-            }
+      
+      /** When we know for certain it's a number after using a touch of lookahead */
+      def restOfNumber() = {
+        putChar(ch)
+        nextChar()
+        getFraction()
+      }
+      def restOfUncertainToken() = {
+        def isEfd = ch match { case 'e' | 'E' | 'f' | 'F' | 'd' | 'D' => true ; case _ => false }
+        def isL   = ch match { case 'l' | 'L' => true ; case _ => false }
+        
+        if (base <= 10 && isEfd)
+          getFraction()
+        else {
+          setStrVal()
+          if (isL) {
+            nextChar()
+            token = LONGLIT
+          }
+          else checkNoLetter()
         }
-      } 
-      if (base <= 10 && 
-          (in.ch == 'e' || in.ch == 'E' ||
-           in.ch == 'f' || in.ch == 'F' ||
-           in.ch == 'd' || in.ch == 'D')) {
-        return getFraction
       }
-      setName
-      if (in.ch == 'l' || in.ch == 'L') {
-        in.next
-        token = LONGLIT
+      
+      if (base > 10 || ch != '.')
+        restOfUncertainToken()
+      else {
+        val lookahead = lookaheadReader
+        val isDefinitelyNumber = 
+          (lookahead.getc(): @switch) match {
+            /** Another digit is a giveaway. */
+            case '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'  =>
+              true
+            
+            /** Backquoted idents like 22.`foo`. */
+            case '`' =>
+              return setStrVal()  /** Note the early return **/
+
+            /** These letters may be part of a literal, or a method invocation on an Int */
+            case 'd' | 'D' | 'f' | 'F' =>
+              !isIdentifierPart(lookahead.getc())
+          
+            /** A little more special handling for e.g. 5e7 */
+            case 'e' | 'E' =>
+              val ch = lookahead.getc()
+              !isIdentifierPart(ch) || (isDigit(ch) || ch == '+' || ch == '-')
+            
+            case x  =>
+              !isIdentifierStart(x)
+          }
+        
+        if (isDefinitelyNumber) restOfNumber()
+        else restOfUncertainToken()
       }
     }
 
-// XML lexing----------------------------------------------------------------
-    def xSync = {
-      token = NEWLINE  // avoid getting NEWLINE from nextToken if last was RBRACE
-      //in.next
-      nextToken
+    /** Parse character literal if current character is followed by \',
+     *  or follow with given op and return a symbol literal token
+     */
+    def charLitOr(op: () => Unit) {
+      putChar(ch)
+      nextChar()
+      if (ch == '\'') {
+        nextChar()
+        token = CHARLIT
+        setStrVal()
+      } else {
+        op()
+        token = SYMBOLLIT
+        strVal = name.toString
+      }
     }
 
 // Errors -----------------------------------------------------------------
 
-    /** generate an error at the given position
+    /** generate an error at the given offset
     */
-    def syntaxError(pos: Int, msg: String) {
-      error(pos, msg)
+    def syntaxError(off: Offset, msg: String) {
+      error(off, msg)
       token = ERROR
-      errpos = pos
+      errOffset = off
     }
 
-    /** generate an error at the current token position
+    /** generate an error at the current token offset
     */
-    def syntaxError(msg: String) { syntaxError(pos, msg) }
+    def syntaxError(msg: String): Unit = syntaxError(offset, msg)
 
     /** signal an error where the input ended in the middle of a token */
     def incompleteInputError(msg: String) {
-      incompleteInputError(pos, msg)
+      incompleteInputError(offset, msg)
       token = EOF
-      errpos = pos
+      errOffset = offset
     }
 
     override def toString() = token match {
@@ -1004,7 +855,7 @@ trait Scanners {
       case DOUBLELIT =>
         "double(" + floatVal + ")"
       case STRINGLIT =>
-        "string(" + name + ")"
+        "string(" + strVal + ")"
       case SEMI =>
         ";"
       case NEWLINE =>
@@ -1014,26 +865,405 @@ trait Scanners {
       case COMMA =>
         ","
       case _ =>
-        ScannerConfiguration.token2string(token)
+        token2string(token)
     }
 
-    /** INIT: read lookahead character and token. 
+    // ------------- brace counting and healing ------------------------------
+ 
+    /** overridden in UnitScanners:
+     *  apply brace patch if one exists for this offset
+     *  return true if subsequent end of line handling should be suppressed.
+     */
+    def applyBracePatch(): Boolean = false
+ 
+    /** overridden in UnitScanners */
+    def parenBalance(token: Int) = 0
+    
+    /** overridden in UnitScanners */
+    def healBraces(): List[BracePatch] = List()
+
+    /** Initialization method: read first char, then first token
      */
-    def init {
-      in.next
-      nextToken
+    def init() {
+      nextChar()
+      nextToken()
+    }
+  } // end Scanner
+
+  // ------------- keyword configuration -----------------------------------
+  
+  /** Keyword array; maps from name indices to tokens */
+  private var keyCode: Array[Byte] = _
+  /** The highest name index of a keyword token */
+  private var maxKey = 0
+  /** An array of all keyword token names */
+  private var keyName = new Array[Name](128)
+  /** The highest keyword token plus one */
+  private var tokenCount = 0 
+
+  /** Enter keyword with given name and token id */
+  protected def enterKeyword(n: Name, tokenId: Int) {
+    while (tokenId >= keyName.length) {
+      val newTokName = new Array[Name](keyName.length * 2)
+      compat.Platform.arraycopy(keyName, 0, newTokName, 0, newTokName.length)
+      keyName = newTokName
     }
+    keyName(tokenId) = n
+    if (n.start > maxKey) maxKey = n.start
+    if (tokenId >= tokenCount) tokenCount = tokenId + 1
   }
 
-  /** ...
-   */   
-  class UnitScanner(unit: CompilationUnit) extends Scanner {
-    val in = new CharArrayReader(unit.source.asInstanceOf[BatchSourceFile].content, !settings.nouescape.value, syntaxError)
-    def warning(pos: Int, msg: String) = unit.warning(pos, msg)
-    def error  (pos: Int, msg: String) = unit.  error(pos, msg)
-    def incompleteInputError(pos: Int, msg: String) = unit.incompleteInputError(pos, msg)
-    def deprecationWarning(pos: Int, msg: String) = unit.deprecationWarning(pos, msg)
-    implicit def p2g(pos: Position): Int = pos.offset.getOrElse(-1)
-    implicit def g2p(pos: Int): Position = new OffsetPosition(unit.source, pos)
+  /** Enter all keywords */
+  protected def enterKeywords() {
+    enterKeyword(nme.ABSTRACTkw, ABSTRACT)
+    enterKeyword(nme.CASEkw, CASE)
+    enterKeyword(nme.CATCHkw, CATCH)
+    enterKeyword(nme.CLASSkw, CLASS)
+    enterKeyword(nme.DEFkw, DEF)
+    enterKeyword(nme.DOkw, DO)
+    enterKeyword(nme.ELSEkw, ELSE)
+    enterKeyword(nme.EXTENDSkw, EXTENDS)
+    enterKeyword(nme.FALSEkw, FALSE)
+    enterKeyword(nme.FINALkw, FINAL)
+    enterKeyword(nme.FINALLYkw, FINALLY)
+    enterKeyword(nme.FORkw, FOR)
+    enterKeyword(nme.FORSOMEkw, FORSOME)
+    enterKeyword(nme.IFkw, IF)
+    enterKeyword(nme.IMPLICITkw, IMPLICIT)
+    enterKeyword(nme.IMPORTkw, IMPORT)
+    enterKeyword(nme.LAZYkw, LAZY)
+    enterKeyword(nme.MATCHkw, MATCH)
+    enterKeyword(nme.NEWkw, NEW)
+    enterKeyword(nme.NULLkw, NULL)
+    enterKeyword(nme.OBJECTkw, OBJECT)
+    enterKeyword(nme.OVERRIDEkw, OVERRIDE)
+    enterKeyword(nme.PACKAGEkw, PACKAGE)
+    enterKeyword(nme.PRIVATEkw, PRIVATE)
+    enterKeyword(nme.PROTECTEDkw, PROTECTED)
+    enterKeyword(nme.RETURNkw, RETURN)
+    enterKeyword(nme.SEALEDkw, SEALED)
+    enterKeyword(nme.SUPERkw, SUPER)
+    enterKeyword(nme.THISkw, THIS)
+    enterKeyword(nme.THROWkw, THROW)
+    enterKeyword(nme.TRAITkw, TRAIT)
+    enterKeyword(nme.TRUEkw, TRUE)
+    enterKeyword(nme.TRYkw, TRY)
+    enterKeyword(nme.TYPEkw, TYPE)
+    enterKeyword(nme.VALkw, VAL)
+    enterKeyword(nme.VARkw, VAR)
+    enterKeyword(nme.WHILEkw, WHILE)
+    enterKeyword(nme.WITHkw, WITH)
+    enterKeyword(nme.YIELDkw, YIELD)
+    enterKeyword(nme.DOTkw, DOT)
+    enterKeyword(nme.USCOREkw, USCORE)
+    enterKeyword(nme.COLONkw, COLON)
+    enterKeyword(nme.EQUALSkw, EQUALS)
+    enterKeyword(nme.ARROWkw, ARROW)
+    enterKeyword(nme.LARROWkw, LARROW)
+    enterKeyword(nme.SUBTYPEkw, SUBTYPE)
+    enterKeyword(nme.VIEWBOUNDkw, VIEWBOUND)
+    enterKeyword(nme.SUPERTYPEkw, SUPERTYPE)
+    enterKeyword(nme.HASHkw, HASH)
+    enterKeyword(nme.ATkw, AT)
+  }
+
+  { // initialization
+    enterKeywords()
+    // Build keyword array
+    keyCode = Array.fill(maxKey + 1)(IDENTIFIER)
+    for (j <- 0 until tokenCount if keyName(j) ne null)
+      keyCode(keyName(j).start) = j.toByte
+  }
+
+  /** Convert name to token */
+  def name2token(name: Name): Int =
+    if (name.start <= maxKey) keyCode(name.start) else IDENTIFIER
+
+// Token representation ----------------------------------------------------
+
+  /** Returns the string representation of given token. */
+  def token2string(token: Int): String = (token: @switch) match {
+    case IDENTIFIER | BACKQUOTED_IDENT => "identifier"
+    case CHARLIT => "character literal"
+    case INTLIT => "integer literal"
+    case LONGLIT => "long literal"
+    case FLOATLIT => "float literal"
+    case DOUBLELIT => "double literal"
+    case STRINGLIT => "string literal"
+    case SYMBOLLIT => "symbol literal"
+    case LPAREN => "'('"
+    case RPAREN => "')'"
+    case LBRACE => "'{'"
+    case RBRACE => "'}'"
+    case LBRACKET => "'['"
+    case RBRACKET => "']'"
+    case EOF => "eof"
+    case ERROR => "something"
+    case SEMI => "';'"
+    case NEWLINE => "';'"
+    case NEWLINES => "';'"
+    case COMMA => "','"
+    case CASECLASS => "case class"
+    case CASEOBJECT => "case object"
+    case XMLSTART => "$XMLSTART$<"
+    case _ =>
+      if (token <= maxKey) "'" + keyName(token) + "'"
+      else "'<" + token + ">'"
+  }
+
+  /** A scanner over a given compilation unit
+   */
+  class UnitScanner(unit: CompilationUnit, patches: List[BracePatch]) extends Scanner {
+    def this(unit: CompilationUnit) = this(unit, List())
+    val buf = unit.source.asInstanceOf[BatchSourceFile].content
+    override val decodeUni: Boolean = !settings.nouescape.value
+
+    def warning(off: Offset, msg: String) = unit.warning(unit.position(off), msg)
+    def error  (off: Offset, msg: String) = unit.error(unit.position(off), msg)
+    def incompleteInputError(off: Offset, msg: String) = unit.incompleteInputError(unit.position(off), msg)
+    def deprecationWarning(off: Offset, msg: String) = unit.deprecationWarning(unit.position(off), msg)
+
+    private var bracePatches: List[BracePatch] = patches
+
+    lazy val parensAnalyzer = new ParensAnalyzer(unit, List())
+
+    override def parenBalance(token: Int) = parensAnalyzer.balance(token)
+
+    override def healBraces(): List[BracePatch] = {
+      var patches: List[BracePatch] = List()
+      if (!parensAnalyzer.tabSeen) {
+        var bal = parensAnalyzer.balance(RBRACE)
+        while (bal < 0) {
+          patches = new ParensAnalyzer(unit, patches).insertRBrace()
+          bal += 1
+        }
+        while (bal > 0) {
+          patches = new ParensAnalyzer(unit, patches).deleteRBrace()
+          bal -= 1
+        }
+      }
+      patches
+    }
+
+    /** Insert or delete a brace, if a patch exists for this offset */
+    override def applyBracePatch(): Boolean = {
+      if (bracePatches.isEmpty || bracePatches.head.off != offset) false
+      else {
+        val patch = bracePatches.head
+        bracePatches = bracePatches.tail
+//        println("applying brace patch "+offset)//DEBUG
+        if (patch.inserted) {
+          next copyFrom this
+          error(offset, "Missing closing brace `}' assumed here")
+          token = RBRACE
+          true
+        } else {
+          error(offset, "Unmatched closing brace '}' ignored here")
+          fetchToken()
+          false
+        }
+      }
+    }
+    
+    override def foundComment(value: String, start: Int, end: Int) {
+      val pos = new RangePosition(unit.source, start, start, end)
+    	unit.comments += unit.Comment(value, pos)
+    	unit.comment(pos, value)
+    }
+
+    override def foundDocComment(value: String, start: Int, end: Int) {
+      docPos = new RangePosition(unit.source, start, start, end)
+      unit.comment(docPos, value)
+    }
+  }
+
+  class ParensAnalyzer(unit: CompilationUnit, patches: List[BracePatch]) extends UnitScanner(unit, patches) {
+    var balance = collection.mutable.Map(RPAREN -> 0, RBRACKET -> 0, RBRACE -> 0)
+
+    init()
+    
+    /** The offset of the first token on this line, or next following line if blank
+     */
+    val lineStart = new ArrayBuffer[Int]
+
+    /** The list of matching top-level brace pairs (each of which may contain nested brace pairs).
+     */
+    val bracePairs: List[BracePair] = {
+
+      var lineCount = 1
+      var lastOffset = 0
+      var indent = 0
+      val oldBalance = collection.mutable.Map[Int, Int]()
+      def markBalance() = for ((k, v) <- balance) oldBalance(k) = v
+      markBalance()
+
+      def scan(bpbuf: ListBuffer[BracePair]): (Int, Int) = {
+        if (token != NEWLINE && token != NEWLINES) {
+          while (lastOffset < offset) {
+            if (buf(lastOffset) == LF) lineCount += 1
+            lastOffset += 1
+          }
+          while (lineCount > lineStart.length) {
+            lineStart += offset
+            // reset indentation unless there are new opening brackets or
+            // braces since last ident line and at the same time there
+            // are no new braces.
+            if (balance(RPAREN) >= oldBalance(RPAREN) &&
+                balance(RBRACKET) >= oldBalance(RBRACKET) ||
+                balance(RBRACE) != oldBalance(RBRACE)) {
+              indent = column(offset)
+              markBalance()
+            }
+          }
+        }
+
+        token match {
+          case LPAREN => 
+            balance(RPAREN) -= 1; nextToken(); scan(bpbuf) 
+          case LBRACKET => 
+            balance(RBRACKET) -= 1; nextToken(); scan(bpbuf) 
+          case RPAREN => 
+            balance(RPAREN) += 1; nextToken(); scan(bpbuf)
+          case RBRACKET => 
+            balance(RBRACKET) += 1; nextToken(); scan(bpbuf)
+          case LBRACE =>  
+            balance(RBRACE) -= 1
+            val lc = lineCount
+            val loff = offset
+            val lindent = indent
+            val bpbuf1 = new ListBuffer[BracePair]
+            nextToken()
+            val (roff, rindent) = scan(bpbuf1)
+            if (lc != lineCount)
+              bpbuf += BracePair(loff, lindent, roff, rindent, bpbuf1.toList)
+            scan(bpbuf)
+          case RBRACE =>
+            balance(RBRACE) += 1
+            val off = offset; nextToken(); (off, indent)
+          case EOF =>
+            (-1, -1)
+          case _ =>
+            nextToken(); scan(bpbuf)
+        }
+      }
+
+      val bpbuf = new ListBuffer[BracePair]
+      while (token != EOF) {
+        val (roff, rindent) = scan(bpbuf)
+        if (roff != -1) {
+          val current = BracePair(-1, -1, roff, rindent, bpbuf.toList)
+          bpbuf.clear()
+          bpbuf += current
+        }
+      }
+
+      def printBP(bp: BracePair, indent: Int) {
+        println(" "*indent+line(bp.loff)+":"+bp.lindent+" to "+line(bp.roff)+":"+bp.rindent)
+        if (bp.nested.nonEmpty) 
+          for (bp1 <- bp.nested) {
+            printBP(bp1, indent + 2)
+          }
+      }
+//      println("lineStart = "+lineStart)//DEBUG
+//      println("bracepairs = ")
+//      for (bp <- bpbuf.toList) printBP(bp, 0)
+      bpbuf.toList
+    }
+
+    var tabSeen = false
+
+    def line(offset: Int): Int = {
+      def findLine(lo: Int, hi: Int): Int = {
+        val mid = (lo + hi) / 2
+        if (offset < lineStart(mid)) findLine(lo, mid - 1)
+        else if (mid + 1 < lineStart.length && offset >= lineStart(mid + 1)) findLine(mid + 1, hi)
+        else mid
+      }
+      if (offset <= 0) 0
+      else findLine(0, lineStart.length - 1)
+    }
+
+    def column(offset: Int): Int = {
+      var col = 0
+      var i = offset - 1
+      while (i >= 0 && buf(i) != CR && buf(i) != LF) {
+        if (buf(i) == '\t') tabSeen = true
+        col += 1
+        i -= 1
+      }
+      col
+    }
+
+    def insertPatch(patches: List[BracePatch], patch: BracePatch): List[BracePatch] = patches match {
+      case List() => List(patch)
+      case bp :: bps => if (patch.off < bp.off) patch :: patches
+                        else bp :: insertPatch(bps, patch)
+    }    
+    
+    def leftColumn(offset: Int) = 
+      if (offset == -1) -1 else column(lineStart(line(offset)))
+
+    def rightColumn(offset: Int, default: Int) = 
+      if (offset == -1) -1 
+      else {
+        val rlin = line(offset)
+        if (lineStart(rlin) == offset) column(offset)
+        else if (rlin + 1 < lineStart.length) column(lineStart(rlin + 1))
+        else default
+      }
+
+    def insertRBrace(): List[BracePatch] = {
+      def insert(bps: List[BracePair]): List[BracePatch] = bps match {
+        case List() => patches
+        case (bp @ BracePair(loff, lindent, roff, rindent, nested)) :: bps1 =>
+          if (lindent <= rindent) insert(bps1)
+          else {
+//           println("patch inside "+bp+"/"+line(loff)+"/"+lineStart(line(loff))+"/"+lindent"/"+rindent)//DEBUG
+            val patches1 = insert(nested)
+            if (patches1 ne patches) patches1
+            else {
+              var lin = line(loff) + 1
+              while (lin < lineStart.length && column(lineStart(lin)) > lindent)
+                lin += 1
+              if (lin < lineStart.length) {
+                val patches1 = insertPatch(patches, BracePatch(lineStart(lin), true))
+                //println("patch for "+bp+"/"+imbalanceMeasure+"/"+new ParensAnalyzer(unit, patches1).imbalanceMeasure)
+                /*if (improves(patches1))*/ 
+                patches1 
+                /*else insert(bps1)*/
+                // (this test did not seem to work very well in practice)
+              } else patches
+            }
+          }
+      }
+      insert(bracePairs)
+    }
+      
+    def deleteRBrace(): List[BracePatch] = {
+      def delete(bps: List[BracePair]): List[BracePatch] = bps match {
+        case List() => patches
+        case BracePair(loff, lindent, roff, rindent, nested) :: bps1 =>
+          if (lindent >= rindent) delete(bps1)
+          else {
+            val patches1 = delete(nested)
+            if (patches1 ne patches) patches1
+            else insertPatch(patches, BracePatch(roff, false))
+          }
+      }
+      delete(bracePairs)
+    }    
+
+    def imbalanceMeasure: Int = {
+      def measureList(bps: List[BracePair]): Int =
+        (bps map measure).sum
+      def measure(bp: BracePair): Int = 
+        (if (bp.lindent != bp.rindent) 1 else 0) + measureList(bp.nested)
+      measureList(bracePairs)
+    }
+
+    def improves(patches1: List[BracePatch]): Boolean =
+      imbalanceMeasure > new ParensAnalyzer(unit, patches1).imbalanceMeasure
+
+    override def error(offset: Int, msg: String) {}
   }
 }
diff --git a/src/compiler/scala/tools/nsc/ast/parser/SymbolicXMLBuilder.scala b/src/compiler/scala/tools/nsc/ast/parser/SymbolicXMLBuilder.scala
index 790836d..2ca63e9 100644
--- a/src/compiler/scala/tools/nsc/ast/parser/SymbolicXMLBuilder.scala
+++ b/src/compiler/scala/tools/nsc/ast/parser/SymbolicXMLBuilder.scala
@@ -1,366 +1,251 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author Burak Emir
  */
-// $Id: SymbolicXMLBuilder.scala 16881 2009-01-09 16:28:11Z cunei $
 
-package scala.tools.nsc.ast.parser
+package scala.tools.nsc
+package ast.parser
 
-import scala.collection.mutable.{Buffer, HashMap, ListBuffer, Map}
-import scala.tools.nsc.util.Position
-import scala.xml.{EntityRef, Text}
+import collection.mutable.Map
+import xml.{ EntityRef, Text }
+import xml.XML.{ xmlns }
 import symtab.Flags.MUTABLE
+import scala.tools.util.StringOps.splitWhere
 
 /** This class builds instance of <code>Tree</code> that represent XML.
  *
+ * Note from martin: This needs to have its position info reworked. I don't understand exactly
+ * what's done here. To make validation pass, I set many positions to be transparent. Not sure this
+ * is a good idea for navigating XML trees in the IDE< but it's the best I can do right now. If someone
+ * who understands this part better wants to give it a shot, please do!
+ * 
  *  @author  Burak Emir
  *  @version 1.0
  */
-abstract class SymbolicXMLBuilder(make: TreeBuilder, p: Parsers # Parser, preserveWS: Boolean) {
-
+abstract class SymbolicXMLBuilder(p: Parsers#Parser, preserveWS: Boolean)
+{
   val global: Global
   import global._
-  import global.posAssigner.atPos
+  def freshName(prefix: String): Name
 
   var isPattern: Boolean = _
 
-  def _Attribute           = global.newTypeName("Attribute")
+  def _Comment             = global.newTypeName("Comment")
+  def _Elem                = global.newTypeName("Elem")
+  def _EntityRef           = global.newTypeName("EntityRef")
+  def _Group               = global.newTypeName("Group")
   def _MetaData            = global.newTypeName("MetaData")
   def _NamespaceBinding    = global.newTypeName("NamespaceBinding")
   def _NodeBuffer          = global.newTypeName("NodeBuffer")
-  def _Null                = global.newTermName("Null")
-  
   def _PrefixedAttribute   = global.newTypeName("PrefixedAttribute")
+  def _ProcInstr           = global.newTypeName("ProcInstr")
+  def _Text                = global.newTypeName("Text")
+  def _Unparsed            = global.newTypeName("Unparsed")
   def _UnprefixedAttribute = global.newTypeName("UnprefixedAttribute")
-  def _Elem                = global.newTypeName("Elem")
+  
   def __Elem               = global.newTermName("Elem")
-  def _Group               = global.newTypeName("Group")
-  def _Unparsed            = global.newTypeName("Unparsed")
-  def _Seq                 = global.newTypeName("Seq")
-  def _immutable           = global.newTermName("immutable")
-  def _mutable             = global.newTermName("mutable")
-  def _append              = global.newTermName("append")
+  def __Text               = global.newTermName("Text")
+  def _Null                = global.newTermName("Null")
   def _plus                = global.newTermName("$amp$plus")
-  def _collection          = global.newTermName("collection")
-  def _toList              = global.newTermName("toList")
   def _xml                 = global.newTermName("xml")
-  def _Comment             = global.newTypeName("Comment")
-  def _Node                = global.newTypeName("Node")
-  def _None                = global.newTermName("None")
-  def _Some                = global.newTypeName("Some")
-  def _ProcInstr           = global.newTypeName("ProcInstr")
-  def _Text                = global.newTypeName("Text")
-  def __Text               = global.newTermName("Text")
-  def _EntityRef           = global.newTypeName("EntityRef")
-
-  final def _buf = global.newTermName("$buf")
-  final def _md = global.newTermName("$md")
-  final def _scope = global.newTermName("$scope")
-  final def _tmpscope = global.newTermName("$tmpscope")
+  
+  final def _buf           = global.newTermName("$buf")
+  final def _md            = global.newTermName("$md")
+  final def _scope         = global.newTermName("$scope")
+  final def _tmpscope      = global.newTermName("$tmpscope")
 
   // convenience methods 
   private def LL[A](x: A*): List[List[A]] = List(List(x:_*))
-
-  private def _scala(name: Name) =
-    Select(Select(Ident(nme.ROOTPKG), nme.scala_), name)
-
-  private def _scala_Seq   = _scala(_Seq)
-  private def _scala_xml(name: Name) = Select(_scala(_xml), name)
-
+  private def const(x: Any) = Literal(Constant(x))
+  private def wild                          = Ident(nme.WILDCARD)
+  private def wildStar                      = Ident(nme.WILDCARD_STAR.toTypeName)
+  private def _scala(name: Name)            = Select(Select(Ident(nme.ROOTPKG), nme.scala_), name)
+  private def _scala_xml(name: Name)        = Select(_scala(_xml), name)
+  
+  private def _scala_xml_Comment            = _scala_xml(_Comment)
+  private def _scala_xml_Elem               = _scala_xml(_Elem)
+  private def _scala_xml_EntityRef          = _scala_xml(_EntityRef)
+  private def _scala_xml_Group              = _scala_xml(_Group)
   private def _scala_xml_MetaData           = _scala_xml(_MetaData)
   private def _scala_xml_NamespaceBinding   = _scala_xml(_NamespaceBinding)
+  private def _scala_xml_NodeBuffer         = _scala_xml(_NodeBuffer)
   private def _scala_xml_Null               = _scala_xml(_Null)
   private def _scala_xml_PrefixedAttribute  = _scala_xml(_PrefixedAttribute)
-  private def _scala_xml_UnprefixedAttribute= _scala_xml(_UnprefixedAttribute)
-  private def _scala_xml_Node               = _scala_xml(_Node)
-  private def _scala_xml_NodeBuffer         = _scala_xml(_NodeBuffer)
-  private def _scala_xml_EntityRef          = _scala_xml(_EntityRef)
-  private def _scala_xml_Comment            = _scala_xml(_Comment)
   private def _scala_xml_ProcInstr          = _scala_xml(_ProcInstr)
   private def _scala_xml_Text               = _scala_xml(_Text)
-  private def _scala_xml__Text              = _scala_xml(__Text)
-  private def _scala_xml_Elem               = _scala_xml(_Elem)
-  private def _scala_xml__Elem              = _scala_xml(__Elem)
-  private def _scala_xml_Attribute          = _scala_xml(_Attribute)
-  private def _scala_xml_Group              = _scala_xml(_Group)
   private def _scala_xml_Unparsed           = _scala_xml(_Unparsed)
+  private def _scala_xml_UnprefixedAttribute= _scala_xml(_UnprefixedAttribute)
+  private def _scala_xml__Elem              = _scala_xml(__Elem)
+  private def _scala_xml__Text              = _scala_xml(__Text)
 
-  // create scala xml tree
-
-  /**
-   *  @arg  namespace: a Tree of type defs.STRING_TYPE 
-   *  @arg  label:     a Tree of type defs.STRING_TYPE 
-   *  @todo map:       a map of attributes !!!
-   */
-
-  protected def mkXML(pos: Position, isPattern: Boolean, pre: Tree, label: Tree, attrs: /*Array[*/Tree/*]*/ , scope:Tree, children: Buffer[Tree]): Tree = {
-    if (isPattern) {
-      convertToTextPat(children)
-      atPos (pos) { //@todo maybe matching on attributes, scope?
-        Apply( _scala_xml__Elem, List( 
-          pre, label, Ident(nme.WILDCARD) /* md */ , Ident(nme.WILDCARD)) /* scope */ ::: children.toList )
-      }
-    } else {
-      var ab = List(pre, label, attrs, scope)
-      if (children.length > 0)
-        ab = ab ::: List(Typed(makeXMLseq(pos, children), Ident(nme.WILDCARD_STAR.toTypeName)));
-      atPos(pos) { New( _scala_xml_Elem, List(ab) )}
-    }
+  /** Wildly wrong documentation deleted in favor of "self-documenting code." */
+  protected def mkXML(
+    pos: Position,
+    isPattern: Boolean,
+    pre: Tree,
+    label: Tree,
+    attrs: Tree,
+    scope:Tree,
+    children: Seq[Tree]): Tree =
+  {
+    def starArgs = 
+      if (children.isEmpty) Nil
+      else List(Typed(makeXMLseq(pos, children), wildStar))
+      
+    def pat    = Apply(_scala_xml__Elem, List(pre, label, wild, wild) ::: convertToTextPat(children))
+    def nonpat = New(_scala_xml_Elem, List(List(pre, label, attrs, scope) ::: starArgs))
+    
+    atPos(pos) { if (isPattern) pat else nonpat }
   }
 
-  final def entityRef(pos: Position, n: String) = {
-    atPos(pos) { New( _scala_xml_EntityRef, LL(Literal(Constant( n )))) }
-
-  };
+  final def entityRef(pos: Position, n: String) =
+    atPos(pos)( New(_scala_xml_EntityRef, LL(const(n))) )
+  
   // create scala.xml.Text here <: scala.xml.Node
-  final def text(pos: Position, txt:String): Tree =  {
-    //makeText( isPattern, gen.mkStringLit( txt ))
-    val txt1 = Literal(Constant(txt))
-    atPos(pos) {
-      if (isPattern)
-        makeTextPat(txt1)
-      else
-        makeText1(txt1)
-    }
+  final def text(pos: Position, txt: String): Tree = atPos(pos) {
+    if (isPattern) makeTextPat(const(txt))
+    else makeText1(const(txt))
   }
-
-  // create scala.xml.Text here <: scala.xml.Node
-  def makeTextPat(txt: Tree) = Apply(_scala_xml__Text, List(txt))
-
-  def makeText1(txt: Tree) =
-    New(_scala_xml_Text, LL(txt))
-
-  // create
-  def comment(pos: Position, text: String): Tree =
-    atPos(pos) { Comment( Literal(Constant(text))) }
-
-  // create
-  def charData(pos: Position, txt: String): Tree =
-    atPos(pos) { makeText1(Literal(Constant(txt))) }; //{ CharData( Literal(Constant(txt))) };
-
-  // create scala.xml.Text here <: scala.xml.Node
-  def procInstr( pos: Position, target: String, txt: String ) =
-    atPos(pos) { ProcInstr(Literal(Constant(target)), Literal(Constant(txt))) }
-
-  protected def Comment(txt: Tree) = New(_scala_xml_Comment, LL(txt))
-
-  protected def ProcInstr(target: Tree, txt: Tree) =
-    New(_scala_xml_ProcInstr, LL(target, txt))
+  
+  def makeTextPat(txt: Tree)                = Apply(_scala_xml__Text, List(txt))
+  def makeText1(txt: Tree)                  = New(_scala_xml_Text, LL(txt))
+  def comment(pos: Position, text: String)  = atPos(pos)( Comment(const(text)) )
+  def charData(pos: Position, txt: String)  = atPos(pos)( makeText1(const(txt)) )
+  
+  def procInstr(pos: Position, target: String, txt: String) =
+    atPos(pos)( ProcInstr(const(target), const(txt)) )
+  
+  protected def Comment(txt: Tree)                  = New(_scala_xml_Comment, LL(txt))
+  protected def ProcInstr(target: Tree, txt: Tree)  = New(_scala_xml_ProcInstr, LL(target, txt))
 
   /** @todo: attributes */
-  def makeXMLpat(pos: Position, n: String, args: Buffer[Tree]): Tree = {
-    val (prepat, labpat) = n.indexOf(':') match {
-      case -1 => (Ident(nme.WILDCARD), Literal(Constant(n)))
-      //case 0  => // is erroneous, but cannot happen 
-      case i  => //if(i+1<n.length) // we ensure i+1<n.length in method xName 
-        (Literal(Constant(n.substring(0,i))), Literal(Constant(n.substring(i+1,n.length))))
-        //else { p.syntaxError(pos,"nonsensical qualified name in XML"); return Ident(nme.WILDCARD).setPos(pos)}
+  def makeXMLpat(pos: Position, n: String, args: Seq[Tree]): Tree = {
+    val (prepat, labpat) = splitPrefix(n) match {
+      case (Some(pre), rest)  => (const(pre), const(rest))
+      case _                  => (wild, const(n))
     }
-    mkXML(pos,
-          true,
-          prepat, //Ident( nme.WILDCARD ),
-          labpat, //Literal(Constant(n)),
-          null, //Array[Tree](),
-          null,
-          args);
+    mkXML(pos, true, prepat, labpat, null, null, args)
   }
 
   protected def convertToTextPat(t: Tree): Tree = t match {
-    case _:Literal => makeTextPat(t)
-    case _ => t
+    case _: Literal => makeTextPat(t)
+    case _          => t
   }
+  protected def convertToTextPat(buf: Seq[Tree]): List[Tree] = 
+    (buf map convertToTextPat).toList
 
   def parseAttribute(pos: Position, s: String): Tree = {
-    val ns = xml.Utility.parseAttributeValue(s)
-    val ts: ListBuffer[Tree] = new ListBuffer
-    val it = ns.elements
-    while (it.hasNext) it.next match {
-      case Text(s)      => ts += text(pos, s) // makeText1(Literal(Constant(s)))
-      case EntityRef(s) => ts += entityRef(pos, s)
+    val ts = xml.Utility.parseAttributeValue(s) map {
+      case Text(s)      => text(pos, s)
+      case EntityRef(s) => entityRef(pos, s)
     }
     ts.length match {
       case 0 => gen.mkNil
-      case 1 => val t = ts(0); ts.clear; t
-      case _ => makeXMLseq(pos, ts)
-    }
-  }
-
-  protected def convertToTextPat(buf: Buffer[Tree]) {
-    var i = 0; while (i < buf.length) {
-      val t1 = buf(i)
-      val t2 = convertToTextPat(t1)
-      if (!t1.eq(t2)) {
-        buf.remove(i)
-        buf.insert(i, t2)
-      }
-      i += 1
+      case 1 => ts.head
+      case _ => makeXMLseq(pos, ts.toList)
     }
   }
 
-  def freshName(prefix: String): Name
-
   def isEmptyText(t: Tree) = t match {
     case Literal(Constant("")) => true
     case _ => false
   }
 
-  // could optimize if args.length == 0, args.length == 1 AND args(0) is <: Node.
-  def makeXMLseq(pos: Position, args: Buffer[Tree] ) = {
-    //var _buffer = New( _scala_xml_NodeBuffer, List(Nil))
-
-    var as:List[Tree] = ValDef(NoMods, _buf, TypeTree(), New( _scala_xml_NodeBuffer, List(Nil)))::Nil
-    val it = args.elements
-    while (it.hasNext) {
-      val t = it.next
-      if (!isEmptyText(t)) {
-        //_buffer = Apply(Select(_buffer, _plus), List(t))
-        as = Apply(Select(Ident(_buf), _plus), List(t))::as
-      }
-    }
-    //atPos(pos) { Select(_buffer, _toList) }
-
-    atPos(pos) {
-      Block(as.reverse, Ident(_buf))
-    }
-  }
-  /** returns Some(prefix) if pre:name, None otherwise */
-  def getPrefix(name: String): Option[String] = {
-    val i = name.indexOf(':')
-    if (i != -1) Some(name.substring(0, i)) else None
+  /** could optimize if args.length == 0, args.length == 1 AND args(0) is <: Node. */
+  def makeXMLseq(pos: Position, args: Seq[Tree]) = {
+    val buffer = ValDef(NoMods, _buf, TypeTree(), New(_scala_xml_NodeBuffer, List(Nil)))
+    val applies = args filterNot isEmptyText map (t => Apply(Select(Ident(_buf), _plus), List(t)))
+    
+    atPos(pos)( Block(buffer :: applies.toList, Ident(_buf)) )
   }
 
-  def group(pos: Position, args: Buffer[Tree]): Tree = {
-    atPos(pos) { New( _scala_xml_Group, LL( makeXMLseq(pos, args))) }
+  /** Returns (Some(prefix) | None, rest) based on position of ':' */
+  def splitPrefix(name: String): (Option[String], String) = splitWhere(name, _ == ':', true) match {
+    case Some((pre, rest))  => (Some(pre), rest)
+    case _                  => (None, name)
   }
 
-  /** code that constructs an unparsed node
-  */
-  def unparsed(pos: Position, str: String): Tree = {
-    atPos(pos) { New( _scala_xml_Unparsed, LL( Literal(Constant(str)))) }
-  }
+  /** Various node constructions. */
+  def group(pos: Position, args: Seq[Tree]): Tree =
+    atPos(pos)( New(_scala_xml_Group, LL(makeXMLseq(pos, args))) )
 
-  /** makes an element */
-  def element(pos: Position, qname: String, attrMap: Map[String,Tree], args: Buffer[Tree]): Tree = {
-    //Console.println("SymbolicXMLBuilder::element("+pos+","+qname+","+attrMap+","+args+")");
-    var setNS = new HashMap[String, Tree]
+  def unparsed(pos: Position, str: String): Tree =
+    atPos(pos)( New(_scala_xml_Unparsed, LL(const(str))) )
 
-    var tlist: List[Tree] = List()
+  def element(pos: Position, qname: String, attrMap: Map[String, Tree], args: Seq[Tree]): Tree = {
+    def handleNamespaceBinding(pre: String, z: String): Tree = {
+      def mkAssign(t: Tree): Tree = Assign(
+        Ident(_tmpscope), 
+        New(_scala_xml_NamespaceBinding, LL(const(pre), t, Ident(_tmpscope)))
+      )
 
-    /* pre can be null */
-    def handleNamespaceBinding(pre: String , uri1: Tree) {
-      def mkAssign(t: Tree): Tree =
-        Assign(Ident(_tmpscope), New( _scala_xml_NamespaceBinding,
-                                      LL(Literal(Constant(pre)), t, Ident( _tmpscope))))
-      uri1 match {
-        case Apply(_, List(uri @ Literal(Constant(_)))) => //text
-          tlist = mkAssign(uri) :: tlist
-        case _ =>
-          tlist = mkAssign(uri1) :: tlist
-          //println("SymbolicXMLBuilder::handleNamespaceBinding:")
-          //println(t.toString())
+      val uri1 = attrMap(z) match {
+        case Apply(_, List(uri @ Literal(Constant(_)))) => mkAssign(uri)
+        case Select(_, nme.Nil)                         => mkAssign(const(null))  // allow for xmlns="" -- bug #1626
+        case x                                          => mkAssign(x)
       }
+      attrMap -= z
+      uri1
     }
 
-    /* DEBUG */
-    val attrIt = attrMap.keys
-    while (attrIt.hasNext) {
-      val z = attrIt.next
-      if (z startsWith "xmlns") {  // handle namespace
-        val i = z indexOf ':'
-        if (i == -1)
-          handleNamespaceBinding(null, attrMap(z))
-          //setNS.update("default", attrMap(z))
-        else {
-          val zz = z.substring(i+1, z.length())
-          //setNS.update( zz, attrMap( z ) );
-          handleNamespaceBinding(zz, attrMap(z))
+    /** Extract all the namespaces from the attribute map. */
+    val namespaces: List[Tree] =
+      for (z <- attrMap.keys.toList ; if z startsWith xmlns) yield {
+        val ns = splitPrefix(z) match {
+          case (Some(_), rest)  => rest
+          case _                => null
         }
-        attrMap -= z
+        handleNamespaceBinding(ns, z)
       }
-    }
-
-    val moreNamespaces = (0 < tlist.length)
-    val i = qname indexOf ':'
-    var newlabel = qname
-    val pre = getPrefix(qname) match {
-      case Some(p) =>
-        newlabel = qname.substring(p.length()+1, qname.length())
-        p
-      case None =>
-        null
-    }
-    var tlist2: List[Tree] = List()
-
-    // make attributes
-
-    def handlePrefixedAttribute(pre:String, key:String, value:Tree) {
-      val t = atPos(pos) {
-        Assign(Ident(_md), New( _scala_xml_PrefixedAttribute, 
-                                       LL(
-                                         Literal(Constant(pre)),
-                                         Literal(Constant(key)),
-                                         value,
-                                         Ident(_md)
-                                       )))};
-      tlist2 = t :: tlist2;
-     // Console.println("SymbolicXMLBuilder::handlePrefixed :");
-     // Console.println(t.toString());
-    }
-
-    def handleUnprefixedAttribute(key: String, value:Tree) {
-      val t = atPos(pos) { 
-        Assign(Ident(_md), New(_scala_xml_UnprefixedAttribute,
-                               LL(Literal(Constant(key)),value,Ident(_md))
-                             ))};
-      tlist2 = t :: tlist2
-    }
-
-    var it = attrMap.elements
-    while (it.hasNext) {
-      val ansk = it.next
-      getPrefix(ansk._1) match {
-        case Some(pre) =>
-          val key = ansk._1.substring(pre.length()+1, ansk._1.length())
-          handlePrefixedAttribute(pre, key, ansk._2)
-        case None      =>
-          handleUnprefixedAttribute(ansk._1, ansk._2)
+      
+    val (pre, newlabel) = splitPrefix(qname) match {
+      case (Some(p), x) => (p, x)
+      case (None, x)    => (null, x)
+    }
+
+    def mkAttributeTree(pre: String, key: String, value: Tree) = atPos(pos.makeTransparent) {
+      // XXX this is where we'd like to put Select(value, nme.toString_) for #1787
+      // after we resolve the Some(foo) situation.
+      val baseArgs = List(const(key), value, Ident(_md))
+      val (clazz, attrArgs) =
+        if (pre == null) (_scala_xml_UnprefixedAttribute, baseArgs)
+                    else (_scala_xml_PrefixedAttribute  , const(pre) :: baseArgs)
+      
+      Assign(Ident(_md), New(clazz, LL(attrArgs: _*)))
+    }
+      
+    def handlePrefixedAttribute(pre: String, key: String, value: Tree)  = mkAttributeTree(pre, key, value)
+    def handleUnprefixedAttribute(key: String, value: Tree)             = mkAttributeTree(null, key, value)
+
+    val attributes: List[Tree] =
+      for ((k, v) <- attrMap.toList.reverse) yield splitPrefix(k) match {
+        case (Some(pre), rest)  => handlePrefixedAttribute(pre, rest, v)
+        case _                  => handleUnprefixedAttribute(k, v)
+      }
+    
+    lazy val scopeDef     = ValDef(NoMods, _scope, _scala_xml_NamespaceBinding, Ident(_tmpscope))
+    lazy val tmpScopeDef  = ValDef(Modifiers(MUTABLE), _tmpscope, _scala_xml_NamespaceBinding, Ident(_scope))
+    lazy val metadataDef  = ValDef(Modifiers(MUTABLE), _md, _scala_xml_MetaData, _scala_xml_Null)
+    val makeSymbolicAttrs = if (!attributes.isEmpty) Ident(_md) else _scala_xml_Null
+    
+    val (attrResult, nsResult) =
+      (attributes.isEmpty, namespaces.isEmpty) match {
+        case (true ,  true)   => (Nil, Nil)
+        case (true , false)   => (scopeDef :: Nil, tmpScopeDef :: namespaces)
+        case (false,  true)   => (metadataDef :: attributes, Nil)
+        case (false, false)   => (scopeDef :: metadataDef :: attributes, tmpScopeDef :: namespaces)
       }
-    }
-    //  attrs
-
-    val moreAttributes = (0 < tlist2.length)
-
-    var ts: List[Tree] = tlist
-    var ts2: List[Tree] = List()
-
-    if (moreAttributes) {
-      ts2 = atPos(pos) {ValDef(Modifiers(MUTABLE),
-                              _md, 
-                              _scala_xml_MetaData, 
-                              _scala_xml_Null)} :: tlist2;
-    }
-    if (moreNamespaces) {
-      ts = atPos(pos) {
-      ValDef(Modifiers(MUTABLE),
-             _tmpscope,
-             _scala_xml_NamespaceBinding,
-             Ident(_scope))} :: ts;
-
-      ts2 = ValDef(NoMods, _scope, _scala_xml_NamespaceBinding, Ident(_tmpscope)) :: ts2
-    }
-
-    val makeSymbolicAttrs =
-      if (moreAttributes) Ident(_md) else _scala_xml_Null
-
-    var t = mkXML(pos,
-                  false,
-                  Literal(Constant(pre)) /* can be null */ ,
-                  Literal(Constant(newlabel)): Tree,
-                  makeSymbolicAttrs,
-                  Ident(_scope),
-                  args);
 
-    atPos(pos) { Block(ts, Block(ts2, t)) }
+    val body = mkXML(
+      pos.makeTransparent,
+      false,
+      const(pre),
+      const(newlabel),
+      makeSymbolicAttrs,
+      Ident(_scope),
+      args
+    )
+    
+    atPos(pos.makeTransparent)( Block(nsResult, Block(attrResult, body)) )
   }
 }
-
diff --git a/src/compiler/scala/tools/nsc/ast/parser/SyntaxAnalyzer.scala b/src/compiler/scala/tools/nsc/ast/parser/SyntaxAnalyzer.scala
index 8be94a4..c2067aa 100644
--- a/src/compiler/scala/tools/nsc/ast/parser/SyntaxAnalyzer.scala
+++ b/src/compiler/scala/tools/nsc/ast/parser/SyntaxAnalyzer.scala
@@ -1,16 +1,16 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author Martin Odersky
  */
-// $Id: SyntaxAnalyzer.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.tools.nsc.ast.parser
+package scala.tools.nsc
+package ast.parser
 
 import javac._
 
 /** An nsc sub-component.
  */ 
-abstract class SyntaxAnalyzer extends SubComponent with Parsers with MarkupParsers with NewScanners with JavaParsers with JavaScanners {
+abstract class SyntaxAnalyzer extends SubComponent with Parsers with MarkupParsers with Scanners with JavaParsers with JavaScanners {
 
   val phaseName = "parser"
 
@@ -18,11 +18,15 @@ abstract class SyntaxAnalyzer extends SubComponent with Parsers with MarkupParse
 
   class ParserPhase(prev: scala.tools.nsc.Phase) extends StdPhase(prev) {
     override val checkable = false
+    override val keepsTypeParams = false
+
     def apply(unit: global.CompilationUnit) {
       global.informProgress("parsing " + unit)
       unit.body =     
         if (unit.source.file.name.endsWith(".java")) new JavaUnitParser(unit).parse()
+        else if (!global.reporter.incompleteHandled) new UnitParser(unit).smartParse()        
         else new UnitParser(unit).parse()
+      if (global.settings.Yrangepos.value && !global.reporter.hasErrors) global.validatePositions(unit.body)
     }
   }
 }
diff --git a/src/compiler/scala/tools/nsc/ast/parser/Tokens.scala b/src/compiler/scala/tools/nsc/ast/parser/Tokens.scala
index 5f7fe37..f0239b7 100644
--- a/src/compiler/scala/tools/nsc/ast/parser/Tokens.scala
+++ b/src/compiler/scala/tools/nsc/ast/parser/Tokens.scala
@@ -1,12 +1,19 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: Tokens.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.tools.nsc.ast.parser
+package scala.tools.nsc
+package ast.parser
 
-object Tokens {
+import annotation.switch
+
+/** Common code between JavaTokens and Tokens.  Not as much (and not as concrete)
+ *  as one might like because JavaTokens for no clear reason chose new numbers for
+ *  identical token sets.
+ */
+abstract class Tokens {
+  import util.Chars._
 
   /** special tokens */
   final val EMPTY = -3
@@ -21,6 +28,23 @@ object Tokens {
   final val FLOATLIT = 4
   final val DOUBLELIT = 5
   final val STRINGLIT = 6
+
+  def LPAREN: Int
+  def RBRACE: Int
+
+  def isIdentifier(code: Int): Boolean
+  def isLiteral(code: Int): Boolean
+  def isKeyword(code: Int): Boolean
+  def isSymbol(code: Int): Boolean
+  
+  final def isSpace(at: Char)         = at == ' ' || at == '\t'  
+  final def isNewLine(at: Char)       = at == CR || at == LF || at == FF
+  final def isBrace(code : Int)       = code >= LPAREN && code <= RBRACE
+  final def isOpenBrace(code : Int)   = isBrace(code) && (code % 2 == 0)
+  final def isCloseBrace(code : Int)  = isBrace(code) && (code % 2 == 1)
+}
+
+object Tokens extends Tokens {
   final val SYMBOLLIT = 7
   def isLiteral(code : Int) =
     code >= CHARLIT && code <= SYMBOLLIT
@@ -31,16 +55,14 @@ object Tokens {
   def isIdentifier(code : Int) =
     code >= IDENTIFIER && code <= BACKQUOTED_IDENT
 
-  def canBeginExpression(code : Int) = code match {
-  case IDENTIFIER|BACKQUOTED_IDENT|USCORE => true
-  case LBRACE|LPAREN|LBRACKET|COMMENT|STRINGLIT => true
-  case IF|DO|WHILE|FOR|NEW|TRY|THROW => true
-  case NULL|THIS|TRUE|FALSE => true
-  case code if isLiteral(code) => true
-  case _ => false
+  @switch def canBeginExpression(code : Int) = code match {
+    case IDENTIFIER|BACKQUOTED_IDENT|USCORE       => true
+    case LBRACE|LPAREN|LBRACKET|COMMENT|STRINGLIT => true
+    case IF|DO|WHILE|FOR|NEW|TRY|THROW            => true
+    case NULL|THIS|TRUE|FALSE                     => true
+    case code                                     => isLiteral(code)
   }
     
-    
   /** keywords */
   final val IF = 20
   final val FOR = 21
@@ -89,15 +111,14 @@ object Tokens {
   def isKeyword(code : Int) =
     code >= IF && code <= LAZY
   
-  def isDefinition(code : Int) = code match {
-  case CLASS|TRAIT|OBJECT => true
-  case CASECLASS|CASEOBJECT => true
-  case DEF|VAL|VAR => true
-  case TYPE => true
-  case _ => false
+  @switch def isDefinition(code : Int) = code match {
+    case CLASS|TRAIT|OBJECT => true
+    case CASECLASS|CASEOBJECT => true
+    case DEF|VAL|VAR => true
+    case TYPE => true
+    case _ => false
   }
 
-
   /** special symbols */
   final val COMMA = 70
   final val SEMI = 71
@@ -126,11 +147,6 @@ object Tokens {
   final val LBRACE = 94
   final val RBRACE = 95
 
-  def isBrace(code : Int) =
-    code >= LPAREN && code <= RBRACE
-  def isOpenBrace(code : Int) = isBrace(code) && (code % 2 == 0)
-  def isCloseBrace(code : Int) = isBrace(code) && (code % 2 == 1)
-
   /** XML mode */
   final val XMLSTART = 96
   
@@ -140,15 +156,4 @@ object Tokens {
   final val WHITESPACE = 105
   final val IGNORE = 106
   final val ESCAPE = 109
-
-  def isSpace(at : Char) = at match {
-  case ' ' | '\t' => true
-  case _ => false
-  }
-  import scala.tools.nsc.util.SourceFile._
-
-  def isNewLine(at : Char) = at match {
-  case CR | LF | FF => true
-  case _ => false
-  }
 }
diff --git a/src/compiler/scala/tools/nsc/ast/parser/TreeBuilder.scala b/src/compiler/scala/tools/nsc/ast/parser/TreeBuilder.scala
index fc31c0a..97b693b 100644
--- a/src/compiler/scala/tools/nsc/ast/parser/TreeBuilder.scala
+++ b/src/compiler/scala/tools/nsc/ast/parser/TreeBuilder.scala
@@ -1,33 +1,34 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: TreeBuilder.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.tools.nsc.ast.parser
+package scala.tools.nsc
+package ast.parser
 
 import symtab.Flags._
 import scala.collection.mutable.ListBuffer
-import scala.tools.nsc.util.Position
 
+/** Methods for building trees, used in the parser.  All the trees
+ *  returned by this class must be untyped.
+ */
 abstract class TreeBuilder {
 
   val global: Global
   import global._
-  import posAssigner.atPos;
-  def freshName(pos : Position, prefix: String): Name
-  def freshName(pos : Position): Name = freshName(pos, "x$")
-
-  def scalaDot(name: Name): Tree =
-    Select(Ident(nme.scala_) setSymbol definitions.ScalaPackage, name)
-  def scalaAnyRefConstr: Tree =
-    scalaDot(nme.AnyRef.toTypeName)
-  def scalaUnitConstr: Tree =
-    scalaDot(nme.Unit.toTypeName)
-  def scalaScalaObjectConstr: Tree =
-    scalaDot(nme.ScalaObject.toTypeName)
-  def productConstr: Tree = 
-    scalaDot(nme.Product.toTypeName)
+
+  def freshName(prefix: String): Name
+  def freshName(): Name = freshName("x$")
+  def o2p(offset: Int): Position
+  def r2p(start: Int, point: Int, end: Int): Position
+
+  def rootId(name: Name)       = gen.rootId(name)
+  def rootScalaDot(name: Name) = gen.rootScalaDot(name)
+  def scalaDot(name: Name)     = gen.scalaDot(name)
+  def scalaAnyRefConstr        = gen.scalaAnyRefConstr
+  def scalaUnitConstr          = gen.scalaUnitConstr
+  def scalaScalaObjectConstr   = gen.scalaScalaObjectConstr
+  def productConstr            = gen.productConstr
 
   /** Convert all occurrences of (lower-case) variables in a pattern as follows:
    *    x                  becomes      x @ _
@@ -36,49 +37,80 @@ abstract class TreeBuilder {
   private object patvarTransformer extends Transformer {
     override def transform(tree: Tree): Tree = tree match {
       case Ident(name) if (treeInfo.isVarPattern(tree) && name != nme.WILDCARD) =>
-        atPos(tree.pos)(Bind(name, Ident(nme.WILDCARD)))
+        atPos(tree.pos)(Bind(name, atPos(tree.pos.focus) (Ident(nme.WILDCARD))))
       case Typed(id @ Ident(name), tpt) if (treeInfo.isVarPattern(id) && name != nme.WILDCARD) =>
-        Bind(name, atPos(tree.pos)(Typed(Ident(nme.WILDCARD), tpt))) setPos id.pos
+        atPos(tree.pos.withPoint(id.pos.point)) {
+          Bind(name, atPos(tree.pos.withStart(tree.pos.point)) {
+            Typed(Ident(nme.WILDCARD), tpt)
+          })
+        }
       case Apply(fn @ Apply(_, _), args) =>
-        copy.Apply(tree, transform(fn), transformTrees(args))
+        treeCopy.Apply(tree, transform(fn), transformTrees(args))
       case Apply(fn, args) =>
-        copy.Apply(tree, fn, transformTrees(args))
+        treeCopy.Apply(tree, fn, transformTrees(args))
       case Typed(expr, tpt) =>
-        copy.Typed(tree, transform(expr), tpt)
+        treeCopy.Typed(tree, transform(expr), tpt)
       case Bind(name, body) =>
-        copy.Bind(tree, name, transform(body))
-      case Sequence(_) | Alternative(_) | Star(_) =>
+        treeCopy.Bind(tree, name, transform(body))
+      case Alternative(_) | Star(_) =>
         super.transform(tree)
       case _ =>
         tree
     }
   }
 
-  /** Traverse pattern and collect all variable names with their types in buffer */ 
-  private object getvarTraverser extends Traverser {
+  /** Traverse pattern and collect all variable names with their types in buffer
+   *  The variables keep their positions; whereas the pattern is converted to be synthetic
+   *  for all nodes that contain a variable position.
+   */ 
+  class GetVarTraverser extends Traverser {
     val buf = new ListBuffer[(Name, Tree, Position)]
-    def init: Traverser = { buf.clear; this }
-    override def traverse(tree: Tree): Unit = tree match {
-      case Bind(name, Typed(tree1, tpt)) =>
-        if ((name != nme.WILDCARD) && (buf.elements forall (name !=)))
-          buf += ((name, if (treeInfo.mayBeTypePat(tpt)) TypeTree() else tpt, tree.pos))
-        traverse(tree1)
-      case Bind(name, tree1) =>
-        if ((name != nme.WILDCARD) && (buf.elements forall (name !=)))
-          buf += ((name, TypeTree(), tree.pos))
-        traverse(tree1)
-      case _ =>
-        super.traverse(tree)
+    
+    def namePos(tree: Tree, name: Name): Position =
+      if (!tree.pos.isRange || name.containsName(nme.DOLLARraw)) tree.pos.focus
+      else {
+        val start = tree.pos.start
+        val end = start + name.decode.length
+        r2p(start, start, end)
+      }
+    
+    override def traverse(tree: Tree): Unit = {
+      def seenName(name: Name)     = buf exists (_._1 == name)
+      def add(name: Name, t: Tree) = if (!seenName(name)) buf += ((name, t, namePos(tree, name)))
+      val bl = buf.length
+      
+      tree match {
+        case Bind(nme.WILDCARD, _)          =>
+          super.traverse(tree)
+        
+        case Bind(name, Typed(tree1, tpt))  =>
+          val newTree = if (treeInfo.mayBeTypePat(tpt)) TypeTree() else tpt.duplicate
+          add(name, newTree)
+          traverse(tree1)
+          
+        case Bind(name, tree1)              =>
+          // can assume only name range as position, as otherwise might overlap
+          // with binds embedded in pattern tree1
+          add(name, TypeTree())
+          traverse(tree1)
+
+        case _ =>
+          super.traverse(tree)
+      }
+      if (buf.length > bl)
+        tree setPos tree.pos.makeTransparent
+    }
+    def apply(tree: Tree) = {
+      traverse(tree)
+      buf.toList
     }
   }
 
   /** Returns list of all pattern variables, possibly with their types,
    *  without duplicates
    */
-  private def getVariables(tree: Tree): List[(Name, Tree,Position)] = {
-    getvarTraverser.init.traverse(tree)
-    getvarTraverser.buf.toList
-  }
+  private def getVariables(tree: Tree): List[(Name, Tree, Position)] =
+    new GetVarTraverser apply tree
 
   private def makeTuple(trees: List[Tree], isType: Boolean): Tree = {
     val tupString = "Tuple" + trees.length
@@ -86,13 +118,13 @@ abstract class TreeBuilder {
   }
 
   def makeTupleTerm(trees: List[Tree], flattenUnary: Boolean): Tree = trees match {
-    case List() => Literal(())
+    case Nil => Literal(())
     case List(tree) if flattenUnary => tree
     case _ => makeTuple(trees, false)
   }
 
   def makeTupleType(trees: List[Tree], flattenUnary: Boolean): Tree = trees match {
-    case List() => scalaUnitConstr
+    case Nil => scalaUnitConstr
     case List(tree) if flattenUnary => tree
     case _ => AppliedTypeTree(scalaDot(newTypeName("Tuple" + trees.length)), trees)
   }
@@ -102,7 +134,7 @@ abstract class TreeBuilder {
     case _ => t
   }
 
-  def makeAnnotated(t: Tree, annot: Annotation): Tree = Annotated(annot, t) setPos annot.pos
+  def makeAnnotated(t: Tree, annot: Tree): Tree = atPos(annot.pos union t.pos)(Annotated(annot, t))
 
   def makeSelfDef(name: Name, tpt: Tree): ValDef =
     ValDef(Modifiers(PRIVATE), name, tpt, EmptyTree)
@@ -118,61 +150,83 @@ abstract class TreeBuilder {
   }
 
   /** Create tree representing (unencoded) binary operation expression or pattern. */
-  def makeBinop(isExpr: Boolean, left: Tree, op: Name, right: Tree): Tree = {
+  def makeBinop(isExpr: Boolean, left: Tree, op: Name, right: Tree, opPos: Position): Tree = {
+    def mkNamed(args: List[Tree]) =
+      if (isExpr) args map {
+        case a @ Assign(id @ Ident(name), rhs) =>
+          atPos(a.pos) { AssignOrNamedArg(id, rhs) }
+        case e => e
+      } else args
     val arguments = right match {
-      case Parens(args) => args
+      case Parens(args) => mkNamed(args)
       case _ => List(right)
     }
     if (isExpr) {
       if (treeInfo.isLeftAssoc(op)) {
-        Apply(Select(stripParens(left), op.encode), arguments)
+        Apply(atPos(left.pos union opPos) { Select(stripParens(left), op.encode) }, arguments)
       } else {
-        val x = freshName(posAssigner.pos);
+        val x = freshName()
         Block(
           List(ValDef(Modifiers(SYNTHETIC), x, TypeTree(), stripParens(left))),
-          Apply(Select(stripParens(right), op.encode), List(Ident(x))))
+          Apply(atPos(right.pos union opPos) { Select(stripParens(right), op.encode) }, List(Ident(x))))
       }
     } else {
       Apply(Ident(op.encode), stripParens(left) :: arguments)
     }
   }
 
-  /** Create tree representing an object creation <new parents { stats }> */
-  def makeNew(parents: List[Tree], self: ValDef, stats: List[Tree], argss: List[List[Tree]]): Tree =
+  /** Create positioned tree representing an object creation <new parents { stats }
+   *  @param npos  the position of the new
+   *  @param cpos  the position of the anonymous class starting with parents
+   */
+  def makeNew(parents: List[Tree], self: ValDef, stats: List[Tree], argss: List[List[Tree]], 
+              npos: Position, cpos: Position): Tree =
     if (parents.isEmpty)
-      makeNew(List(scalaAnyRefConstr), self, stats, argss)
+      makeNew(List(scalaAnyRefConstr), self, stats, argss, npos, cpos)
     else if (parents.tail.isEmpty && stats.isEmpty)
-      New(parents.head, argss)
+      atPos(npos union cpos) { New(parents.head, argss) }
     else {
       val x = nme.ANON_CLASS_NAME.toTypeName
-      Block(
-        List(ClassDef(
-          Modifiers(FINAL), x, List(),
-          Template(parents, self, NoMods, List(List()), argss, stats))),
-        New(Ident(x), List(List())))
+      atPos(npos union cpos) {
+        Block(
+          List(
+            atPos(cpos) {
+              ClassDef(
+                Modifiers(FINAL), x, Nil,
+                Template(parents, self, NoMods, List(Nil), argss, stats, cpos.focus))
+            }),
+          atPos(npos) {
+            New(
+              Ident(x) setPos npos.focus,
+              List(Nil))
+          }
+        )
+      }
     }
 
-  /** Create a tree represeting an assignment <lhs = rhs> */
+  /** Create a tree representing an assignment <lhs = rhs> */
   def makeAssign(lhs: Tree, rhs: Tree): Tree = lhs match {
-    case Apply(fn, args) => Apply(Select(fn, nme.update), args ::: List(rhs))
-    case _ => Assign(lhs, rhs)
+    case Apply(fn, args) => 
+      Apply(atPos(fn.pos) { Select(fn, nme.update) }, args ::: List(rhs)) 
+    case _ => 
+      Assign(lhs, rhs)
   }
 
   /** A type tree corresponding to (possibly unary) intersection type */
   def makeIntersectionTypeTree(tps: List[Tree]): Tree =
     if (tps.tail.isEmpty) tps.head
-    else CompoundTypeTree(Template(tps, emptyValDef, List()))
+    else CompoundTypeTree(Template(tps, emptyValDef, Nil))
 
   /** Create tree representing a while loop */
   def makeWhile(lname: Name, cond: Tree, body: Tree): Tree = {
-    val continu = Apply(Ident(lname), List())
+    val continu = atPos(o2p(body.pos.endOrPoint)) { Apply(Ident(lname), Nil) }
     val rhs = If(cond, Block(List(body), continu), Literal(()))
     LabelDef(lname, Nil, rhs)
   }
 
   /** Create tree representing a do-while loop */
   def makeDoWhile(lname: Name, body: Tree, cond: Tree): Tree = {
-    val continu = Apply(Ident(lname), List())
+    val continu = Apply(Ident(lname), Nil)
     val rhs = Block(List(body), If(cond, continu, Literal(())))
     LabelDef(lname, Nil, rhs)
   }
@@ -193,7 +247,7 @@ abstract class TreeBuilder {
         case Some(_) =>
           rhs
         case None =>
-          atPos(pos) {
+          atPos(rhs.pos) {
             Apply(
               Select(rhs, nme.filter),
               List(
@@ -213,12 +267,12 @@ abstract class TreeBuilder {
     ValDef(Modifiers(PARAM | SYNTHETIC), pname, TypeTree(), EmptyTree)
 
   def makeSyntheticTypeParam(pname: Name, bounds: Tree) = 
-    TypeDef(Modifiers(DEFERRED | SYNTHETIC), pname, List(), bounds)
+    TypeDef(Modifiers(DEFERRED | SYNTHETIC), pname, Nil, bounds)
 
-  abstract class Enumerator
+  abstract class Enumerator { def pos: Position }
   case class ValFrom(pos: Position, pat: Tree, rhs: Tree) extends Enumerator
   case class ValEq(pos: Position, pat: Tree, rhs: Tree) extends Enumerator
-  case class Filter(test: Tree) extends Enumerator
+  case class Filter(pos: Position, test: Tree) extends Enumerator
 
   /** Create tree for for-comprehension <for (enums) do body> or
   *   <for (enums) yield body> where mapName and flatMapName are chosen
@@ -227,33 +281,33 @@ abstract class TreeBuilder {
   *
   *  1.
   *
-  *    for (val P <- G) E   ==>   G.foreach (P => E)
+  *    for (P <- G) E   ==>   G.foreach (P => E)
   *
   *     Here and in the following (P => E) is interpreted as the function (P => E)
   *     if P is a a variable pattern and as the partial function { case P => E } otherwise.
   *
   *  2.
   *
-  *    for (val P <- G) yield E  ==>  G.map (P => E)
+  *    for (P <- G) yield E  ==>  G.map (P => E)
   *
   *  3. 
   *
-  *    for (val P_1 <- G_1; val P_2 <- G_2; ...) ...
+  *    for (P_1 <- G_1; val P_2 <- G_2; ...) ...
   *      ==>
-  *    G_1.flatMap (P_1 => for (val P_2 <- G_2; ...) ...)
+  *    G_1.flatMap (P_1 => for (P_2 <- G_2; ...) ...)
   *
   *  4.
-  *
-  *    for (val P <- G; E; ...) ...
+  * 
+  *    for (P <- G; E; ...) ...
   *      =>
-  *    for (val P <- G.filter (P => E); ...) ...
+  *    for (P <- G.filter (P => E); ...) ...
   *
   *  5. For N < MaxTupleArity:
   *
-  *    for (val P_1 <- G; val P_2 = E_2; val P_N = E_N; ...)
+  *    for (P_1 <- G; val P_2 = E_2; val P_N = E_N; ...)
   *      ==>
-  *    for (val TupleN(P_1, P_2, ... P_N) <-
-  *      for (val x_1 @ P_1 <- G) yield {
+  *    for (TupleN(P_1, P_2, ... P_N) <-
+  *      for (x_1 @ P_1 <- G) yield {
   *        val x_2 @ P_2 = E_2
   *        ...
   *        val x_N & P_N = E_N
@@ -263,45 +317,76 @@ abstract class TreeBuilder {
   *    If any of the P_i are variable patterns, the corresponding `x_i @ P_i' is not generated
   *    and the variable constituting P_i is used instead of x_i
   *
+  *  @param mapName      The name to be used for maps (either map or foreach)
+  *  @param flatMapName  The name to be used for flatMaps (either flatMap or foreach)
+  *  @param enums        The enumerators in the for expression
+  *  @param body          The body of the for expression
   */
   private def makeFor(mapName: Name, flatMapName: Name, enums: List[Enumerator], body: Tree): Tree = {
 
-    def makeClosure(pat: Tree, body: Tree): Tree = matchVarPattern(pat) match {
-      case Some((name, tpt)) =>
-        Function(List(ValDef(Modifiers(PARAM), name, tpt, EmptyTree)), body)
-      case None =>
-        makeVisitor(List(CaseDef(pat, EmptyTree, body)), false)
-    }
-
-    def makeCombination(meth: Name, qual: Tree, pat: Tree, body: Tree): Tree = 
-      Apply(Select(qual, meth), List(makeClosure(pat, body)));
-
+    /** make a closure pat => body.
+     *  The closure is assigned a transparent position with the point at pos.point and
+     *  the limits given by pat and body.
+     */
+    def makeClosure(pos: Position, pat: Tree, body: Tree): Tree = {
+      def splitpos = wrappingPos(List(pat, body)).withPoint(pos.point).makeTransparent
+      matchVarPattern(pat) match {
+        case Some((name, tpt)) =>
+          Function(
+            List(atPos(pat.pos) { ValDef(Modifiers(PARAM), name, tpt, EmptyTree) }), 
+            body) setPos splitpos
+        case None =>
+          atPos(splitpos) {
+            makeVisitor(List(CaseDef(pat, EmptyTree, body)), false)
+          }
+      }
+    } 
+
+    /** Make an application  qual.meth(pat => body) positioned at `pos`.
+     */
+    def makeCombination(pos: Position, meth: Name, qual: Tree, pat: Tree, body: Tree): Tree = 
+      Apply(Select(qual, meth) setPos qual.pos, List(makeClosure(pos, pat, body))) setPos pos
+    
+    /** Optionally, if pattern is a `Bind`, the bound name, otherwise None.
+     */
     def patternVar(pat: Tree): Option[Name] = pat match {
       case Bind(name, _) => Some(name)
       case _ => None
     }
 
+    /** If `pat` is not yet a `Bind` wrap it in one with a fresh name
+     */
     def makeBind(pat: Tree): Tree = pat match {
       case Bind(_, _) => pat
-      case _ => Bind(freshName(pat.pos), pat)
+      case _ => Bind(freshName(), pat) setPos pat.pos
     }
 
+    /** A reference to the name bound in Bind `pat`.
+     */
     def makeValue(pat: Tree): Tree = pat match {
-      case Bind(name, _) => Ident(name)
+      case Bind(name, _) => Ident(name) setPos pat.pos.focus
     }
 
+    /** The position of the closure that starts with generator at position `genpos`.
+     */
+    def closurePos(genpos: Position) = {
+      val end = body.pos match {
+        case NoPosition => genpos.point
+        case bodypos => bodypos.endOrPoint
+      }
+      r2p(genpos.startOrPoint, genpos.point, end) 
+    }
+
+//    val result = 
     enums match {
       case ValFrom(pos, pat, rhs) :: Nil =>
-        atPos(pos) {
-          makeCombination(mapName, rhs, pat, body)
-        }
+        makeCombination(closurePos(pos), mapName, rhs, pat, body)
       case ValFrom(pos, pat, rhs) :: (rest @ (ValFrom(_,  _, _) :: _)) =>
-        atPos(pos) {
-          makeCombination(flatMapName, rhs, pat, makeFor(mapName, flatMapName, rest, body))
-        }
-      case ValFrom(pos, pat, rhs) :: Filter(test) :: rest =>
+        makeCombination(closurePos(pos), flatMapName, rhs, pat, 
+                        makeFor(mapName, flatMapName, rest, body))
+      case ValFrom(pos, pat, rhs) :: Filter(_, test) :: rest =>
         makeFor(mapName, flatMapName,
-                ValFrom(pos, pat, makeCombination(nme.filter, rhs, pat.duplicate, test)) :: rest,
+                ValFrom(pos, pat, makeCombination(rhs.pos union test.pos, nme.withFilter, rhs, pat.duplicate, test)) :: rest,
                 body)
       case ValFrom(pos, pat, rhs) :: rest =>
         val valeqs = rest.take(definitions.MaxTupleArity - 1).takeWhile(_.isInstanceOf[ValEq]);
@@ -309,17 +394,21 @@ abstract class TreeBuilder {
         val rest1 = rest.drop(valeqs.length)
         val pats = valeqs map { case ValEq(_, pat, _) => pat }
         val rhss = valeqs map { case ValEq(_, _, rhs) => rhs }
-        val defpats = pats map (x => makeBind(x.duplicate))
-        val pdefs = List.flatten(List.map2(defpats, rhss)(makePatDef))
-        val patX1 = makeBind(pat.duplicate);
-        val ids = (patX1 :: defpats) map makeValue
+        val defpat1 = makeBind(pat)
+        val defpats = pats map makeBind
+        val pdefs = (defpats, rhss).zipped flatMap makePatDef
+        val ids = (defpat1 :: defpats) map makeValue
         val rhs1 = makeForYield(
-          List(ValFrom(pos, patX1, rhs)), 
-          Block(pdefs, makeTupleTerm(ids, true)))
-        makeFor(mapName, flatMapName, ValFrom(pos, makeTuple(pat :: pats, false), rhs1) :: rest1, body)
+          List(ValFrom(pos, defpat1, rhs)), 
+          Block(pdefs, atPos(wrappingPos(ids)) { makeTupleTerm(ids, true) }) setPos wrappingPos(pdefs))
+        val allpats = (pat :: pats) map (_.duplicate)
+        val vfrom1 = ValFrom(r2p(pos.startOrPoint, pos.point, rhs1.pos.endOrPoint), atPos(wrappingPos(allpats)) { makeTuple(allpats, false) } , rhs1)
+        makeFor(mapName, flatMapName, vfrom1 :: rest1, body)
       case _ =>
         EmptyTree //may happen for erroneous input
     }
+//    println("made for "+result)
+//    result
   }
 
   /** Create tree for for-do comprehension <for (enums) body> */
@@ -345,40 +434,25 @@ abstract class TreeBuilder {
   /** Create tree for a pattern alternative */
   def makeAlternative(ts: List[Tree]): Tree = {
     def alternatives(t: Tree): List[Tree] = t match {
-      case Alternative(ts) => ts
-      case _ => List(t)
+      case Alternative(ts)  => ts
+      case _                => List(t)
     }
-    Alternative(for (val t <- ts; val a <- alternatives(t)) yield a)
+    Alternative(ts flatMap alternatives)
   }
 
-  /** Create tree for a pattern sequence */
-  def makeSequence(ts: List[Tree]): Tree = {
-    def elements(t: Tree): List[Tree] = t match {
-      case Sequence(ts) => ts
-      case _ => List(t)
-    }
-    Sequence(for (val t <- ts; val e <- elements(t)) yield e)
-  }
-
-  /** Create tree for the p+ regex pattern, becomes p p*  */
-  def makePlus(p: Tree): Tree =
-    makeSequence(List(p, Star(p.duplicate)))
-
-  /** Create tree for the p? regex pattern, becomes (p| )         */
-  def makeOpt(p: Tree): Tree =
-    makeAlternative(List(p, Sequence(List())))
-
   /** Create visitor <x => x match cases> */
   def makeVisitor(cases: List[CaseDef], checkExhaustive: Boolean): Tree =
     makeVisitor(cases, checkExhaustive, "x$")
 
-  private def makeUnchecked(expr: Tree): Tree =
-    Annotated(Annotation(New(scalaDot(definitions.UncheckedClass.name), List(List())), List()), expr)
+  private def makeUnchecked(expr: Tree): Tree = atPos(expr.pos) {
+    Annotated(New(scalaDot(definitions.UncheckedClass.name), List(Nil)), expr)
+  }
 
   /** Create visitor <x => x match cases> */
   def makeVisitor(cases: List[CaseDef], checkExhaustive: Boolean, prefix: String): Tree = {
-    val x = freshName(posAssigner.pos, prefix)
-    val sel = if (checkExhaustive) Ident(x) else makeUnchecked(Ident(x))
+    val x = freshName(prefix)
+    val id = Ident(x)
+    val sel = if (checkExhaustive) id else makeUnchecked(id)
     Function(List(makeSyntheticParam(x)), Match(sel, cases))
   }
 
@@ -389,11 +463,44 @@ abstract class TreeBuilder {
   /** Create tree for pattern definition <val pat0 = rhs> */
   def makePatDef(pat: Tree, rhs: Tree): List[Tree] =
     makePatDef(Modifiers(0), pat, rhs)
+  
+  /** For debugging only.  Desugar a match statement like so:
+   *  val x = scrutinee
+   *  x match {
+   *    case case1 => ...
+   *    case _ => x match {
+   *       case case2 => ...
+   *       case _ => x match ...
+   *    }
+   *  }
+   * 
+   *  This way there are never transitions between nontrivial casedefs.
+   *  Of course many things break: exhaustiveness and unreachable checking
+   *  do not work, no switches will be generated, etc.
+   */
+  def makeSequencedMatch(selector: Tree, cases: List[CaseDef]): Tree = {
+    require(cases.nonEmpty)
+    
+    val selectorName = freshName()
+    val valdef = atPos(selector.pos)(ValDef(Modifiers(PRIVATE | LOCAL | SYNTHETIC), selectorName, TypeTree(), selector))
+    val nselector = Ident(selectorName)
+    
+    def loop(cds: List[CaseDef]): Match = {
+      def mkNext = CaseDef(Ident(nme.WILDCARD), EmptyTree, loop(cds.tail))
+      
+      if (cds.size == 1) Match(nselector, cds)
+      else Match(selector, List(cds.head, mkNext))
+    }
+    
+    Block(List(valdef), loop(cases))
+  }
 
-  /** Create tree for pattern definition <mods val pat0 = rhs> */
+  /** Create tree for pattern definition <mods val pat0 = rhs> */
   def makePatDef(mods: Modifiers, pat: Tree, rhs: Tree): List[Tree] = matchVarPattern(pat) match {
     case Some((name, tpt)) =>
-      List(ValDef(mods, name, tpt, rhs).setPos(pat.pos))
+      List(atPos(pat.pos union rhs.pos) {
+        ValDef(mods, name, tpt, rhs)
+      })
 
     case None =>
       //  in case there is exactly one variable x_1 in pattern
@@ -406,20 +513,29 @@ abstract class TreeBuilder {
       //                  val/var x_N = t$._N
       val pat1 = patvarTransformer.transform(pat)
       val vars = getVariables(pat1)
-      val matchExpr = atPos(pat1.pos){
+      val matchExpr = atPos((pat1.pos union rhs.pos).makeTransparent) {
         Match(
           makeUnchecked(rhs), 
-          List(CaseDef(pat1, EmptyTree, makeTupleTerm(vars map (_._1) map Ident, true))))
+          List(
+            atPos(pat1.pos) {
+              CaseDef(pat1, EmptyTree, makeTupleTerm(vars map (_._1) map Ident, true))
+            }
+          ))
       }
       vars match {
         case List((vname, tpt, pos)) =>
-          List(ValDef(mods, vname, tpt, matchExpr).setPos(pos))
+          List(atPos(pat.pos union pos union rhs.pos) {
+            ValDef(mods, vname, tpt, matchExpr)
+          })
         case _ => 
-          val tmp = freshName(pat1.pos)
-          val firstDef = ValDef(Modifiers(PRIVATE | LOCAL | SYNTHETIC | (mods.flags & LAZY)), 
-                                tmp, TypeTree(), matchExpr)
+          val tmp = freshName()
+          val firstDef = 
+            atPos(matchExpr.pos) {
+              ValDef(Modifiers(PRIVATE | LOCAL | SYNTHETIC | (mods.flags & LAZY)), 
+                     tmp, TypeTree(), matchExpr)
+            }
           var cnt = 0
-          val restDefs = for (val (vname, tpt, pos) <- vars) yield atPos(pos) {
+          val restDefs = for ((vname, tpt, pos) <- vars) yield atPos(pos) {
             cnt = cnt + 1
             ValDef(mods, vname, tpt, Select(Ident(tmp), newTermName("_" + cnt)))
           }
@@ -429,29 +545,15 @@ abstract class TreeBuilder {
 
   /** Create a tree representing the function type (argtpes) => restpe */
   def makeFunctionTypeTree(argtpes: List[Tree], restpe: Tree): Tree =
-    AppliedTypeTree(scalaDot(newTypeName("Function" + argtpes.length)), argtpes ::: List(restpe))
+    AppliedTypeTree(rootScalaDot(newTypeName("Function" + argtpes.length)), argtpes ::: List(restpe))
 
-  /** Create a tree representing a the name function type (=> argtpe) => restpe */
-  /*
-  def makeByNameFunctionTypeTree(argtpe: Tree, restpe: Tree): Tree = 
-    AppliedTypeTree(scalaDot(newTypeName("ByNameFunction")), List(argtpe, restpe))
-  */
-
-  /** Append implicit view section if for `implicitViews' if nonempty */
-  def addImplicitViews(owner: Name, vparamss: List[List[ValDef]], implicitViews: List[Tree]): List[List[ValDef]] = {
-    val mods = Modifiers(if (owner.isTypeName) PARAMACCESSOR | LOCAL | PRIVATE else PARAM)
-    def makeViewParam(tpt: Tree) = ValDef(mods | IMPLICIT, freshName(tpt.pos, "view$"), tpt, EmptyTree)
-    if (implicitViews.isEmpty) vparamss
-    else vparamss ::: List(implicitViews map makeViewParam)
-  }
-
-  /** Create a tree representing a packaging */
-  def makePackaging(pkg: Tree, stats: List[Tree]): PackageDef = pkg match {
-    case Ident(name) =>
-      PackageDef(name, stats).setPos(pkg.pos)
-    case Select(qual, name) =>
-      makePackaging(qual, List(PackageDef(name, stats).setPos(pkg.pos)))
+  /** Append implicit parameter section if `contextBounds' nonempty */
+  def addEvidenceParams(owner: Name, vparamss: List[List[ValDef]], contextBounds: List[Tree]): List[List[ValDef]] =
+    if (contextBounds.isEmpty) vparamss
+    else {
+      val mods = Modifiers(if (owner.isTypeName) PARAMACCESSOR | LOCAL | PRIVATE else PARAM)
+      def makeEvidenceParam(tpt: Tree) = ValDef(mods | IMPLICIT, freshName(nme.EVIDENCE_PARAM_PREFIX), tpt, EmptyTree)
+      vparamss ::: List(contextBounds map makeEvidenceParam)
   }
 
-  case class Parens(args: List[Tree]) extends Tree
 }
diff --git a/src/compiler/scala/tools/nsc/backend/JavaPlatform.scala b/src/compiler/scala/tools/nsc/backend/JavaPlatform.scala
new file mode 100644
index 0000000..f28342c
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/backend/JavaPlatform.scala
@@ -0,0 +1,41 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
+ * @author  Paul Phillips
+ */
+
+package scala.tools.nsc
+package backend
+
+import io.AbstractFile
+import util.JavaClassPath
+import util.ClassPath.{ JavaContext, DefaultJavaContext }
+import scala.tools.util.PathResolver
+
+trait JavaPlatform extends Platform[AbstractFile] {
+  import global._
+  import definitions.{ BoxesRunTimeClass, getMember }
+  
+  lazy val classPath  = new PathResolver(settings).result
+  def rootLoader      = new loaders.JavaPackageLoader(classPath)
+
+  private def depAnalysisPhase = if (settings.make.value != "all") List(dependencyAnalysis) else Nil
+  def platformPhases = List(
+    flatten,    // get rid of inner classes
+    liftcode,   // generate reified trees
+    genJVM      // generate .class files
+  ) ::: depAnalysisPhase
+  
+  lazy val externalEquals = getMember(BoxesRunTimeClass, nme.equals_)
+  def externalEqualsNumNum = getMember(BoxesRunTimeClass, "equalsNumNum")
+  def externalEqualsNumChar = getMember(BoxesRunTimeClass, "equalsNumChar")
+  def externalEqualsNumObject = getMember(BoxesRunTimeClass, "equalsNumObject")
+  
+  def isMaybeBoxed(sym: Symbol): Boolean = {
+    import definitions._
+    (sym == ObjectClass) ||
+    (sym == SerializableClass) ||
+    (sym == ComparableClass) ||
+    (sym isNonBottomSubClass BoxedNumberClass) ||
+    (sym isNonBottomSubClass BoxedCharacterClass)   
+  }  
+}
diff --git a/src/compiler/scala/tools/nsc/backend/MSILPlatform.scala b/src/compiler/scala/tools/nsc/backend/MSILPlatform.scala
new file mode 100644
index 0000000..2c9243d
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/backend/MSILPlatform.scala
@@ -0,0 +1,36 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
+ * @author  Paul Phillips
+ */
+
+package scala.tools.nsc
+package backend
+
+import ch.epfl.lamp.compiler.msil.{ Type => MSILType }
+import util.MsilClassPath
+import msil.GenMSIL
+
+trait MSILPlatform extends Platform[MSILType] {
+  import global._
+  import definitions.{ ComparatorClass, BoxedNumberClass, getMember, getClass }
+
+  if (settings.verbose.value)
+    inform("[AssemRefs = " + settings.assemrefs.value + "]")
+  
+  // phaseName = "msil"
+  object genMSIL extends {
+    val global: MSILPlatform.this.global.type = MSILPlatform.this.global
+    val runsAfter = List[String]("dce")
+    val runsRightAfter = None
+  } with GenMSIL
+  
+  lazy val classPath = MsilClassPath.fromSettings(settings)
+  def rootLoader = new loaders.NamespaceLoader(classPath)
+  
+  def platformPhases = List(
+    genMSIL   // generate .msil files
+  )  
+  
+  lazy val externalEquals = getMember(ComparatorClass.companionModule, nme.equals_)
+  def isMaybeBoxed(sym: Symbol) = sym isNonBottomSubClass BoxedNumberClass
+}
diff --git a/src/compiler/scala/tools/nsc/backend/Platform.scala b/src/compiler/scala/tools/nsc/backend/Platform.scala
new file mode 100644
index 0000000..ef54c3e
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/backend/Platform.scala
@@ -0,0 +1,31 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
+ * @author  Paul Phillips
+ */
+
+package scala.tools.nsc
+package backend
+
+import util.ClassPath
+
+/** The platform dependent pieces of Global.
+ */
+trait Platform[T] {
+  val global: Global
+  import global._
+  
+  /** The compiler classpath. */
+  def classPath: ClassPath[T]
+  
+  /** The root symbol loader. */
+  def rootLoader: LazyType
+  
+  /** Any platform-specific phases. */
+  def platformPhases: List[SubComponent]
+  
+  /** Symbol for a method which compares two objects. */
+  def externalEquals: Symbol
+  
+  /** The various ways a boxed primitive might materialize at runtime. */
+  def isMaybeBoxed(sym: Symbol): Boolean
+}
diff --git a/src/compiler/scala/tools/nsc/backend/ScalaPrimitives.scala b/src/compiler/scala/tools/nsc/backend/ScalaPrimitives.scala
index b36651a..64a29af 100644
--- a/src/compiler/scala/tools/nsc/backend/ScalaPrimitives.scala
+++ b/src/compiler/scala/tools/nsc/backend/ScalaPrimitives.scala
@@ -1,11 +1,11 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
 
-// $Id: ScalaPrimitives.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.tools.nsc.backend
+package scala.tools.nsc
+package backend
 
 import scala.tools.nsc.backend.icode._
 
@@ -93,6 +93,7 @@ abstract class ScalaPrimitives {
   final val AS = 81                            // x.as[y]
   final val ISERASED = 85                      // x.is$erased[y]
   final val ASERASED = 86                      // x.as$erased[y]
+  final val HASH = 87                          // x.##
 
   // AnyRef operations
   final val SYNCHRONIZED = 90                  // x.synchronized(y)
@@ -214,8 +215,7 @@ abstract class ScalaPrimitives {
     addPrimitive(Any_!=, NE)
     addPrimitive(Any_isInstanceOf, IS)
     addPrimitive(Any_asInstanceOf, AS)
-    addPrimitive(Any_isInstanceOfErased, ISERASED)
-    addPrimitive(Any_asInstanceOfErased, ASERASED)
+    addPrimitive(Any_##, HASH)
 
     // java.lang.Object
     addPrimitive(Object_eq, ID)
@@ -237,15 +237,12 @@ abstract class ScalaPrimitives {
     // scala.Boolean
     addPrimitives(BooleanClass, nme.EQ, EQ)
     addPrimitives(BooleanClass, nme.NE, NE)
-    addPrimitive(Boolean_not, ZNOT)
-    addPrimitive(Boolean_or, ZOR)
-    addPrimitive(Boolean_and, ZAND)
+    addPrimitives(BooleanClass, nme.UNARY_!, ZNOT)
+    addPrimitives(BooleanClass, nme.ZOR, ZOR)
+    addPrimitives(BooleanClass, nme.ZAND, ZAND)
     addPrimitives(BooleanClass, nme.OR, OR)
     addPrimitives(BooleanClass, nme.AND, AND)
     addPrimitives(BooleanClass, nme.XOR, XOR)
-//    addPrimitives(BooleanClass, nme.ADD, CONCAT)
-    // unary !
-//  addPrimitives(BooleanClass, nme.UNARY_!, ZNOT)
 
     // scala.Byte
     addPrimitives(ByteClass, nme.EQ, EQ)
@@ -276,10 +273,8 @@ abstract class ScalaPrimitives {
     addPrimitives(ByteClass, nme.UNARY_-, NEG)
     addPrimitives(ByteClass, nme.UNARY_~, NOT)
     
-    if (!forCLDC) {
-      addPrimitives(ByteClass, nme.toFloat,  B2F)
-      addPrimitives(ByteClass, nme.toDouble, B2D)
-    }
+    addPrimitives(ByteClass, nme.toFloat,  B2F)
+    addPrimitives(ByteClass, nme.toDouble, B2D)
 
     // scala.Short
     addPrimitives(ShortClass, nme.EQ, EQ)
@@ -310,10 +305,8 @@ abstract class ScalaPrimitives {
     addPrimitives(ShortClass, nme.UNARY_-, NEG)
     addPrimitives(ShortClass, nme.UNARY_~, NOT)
 
-    if (!forCLDC) {
-      addPrimitives(ShortClass, nme.toFloat,  S2F)
-      addPrimitives(ShortClass, nme.toDouble, S2D)
-    }
+    addPrimitives(ShortClass, nme.toFloat,  S2F)
+    addPrimitives(ShortClass, nme.toDouble, S2D)
 
     // scala.Char
     addPrimitives(CharClass, nme.EQ, EQ)
@@ -343,10 +336,8 @@ abstract class ScalaPrimitives {
     addPrimitives(CharClass, nme.UNARY_+, POS)
     addPrimitives(CharClass, nme.UNARY_-, NEG)
     addPrimitives(CharClass, nme.UNARY_~, NOT)
-    if (!forCLDC) {
-      addPrimitives(CharClass, nme.toFloat,  C2F)
-      addPrimitives(CharClass, nme.toDouble, C2D)
-    }
+    addPrimitives(CharClass, nme.toFloat,  C2F)
+    addPrimitives(CharClass, nme.toDouble, C2D)
 
     // scala.Int
     addPrimitives(IntClass, nme.EQ, EQ)
@@ -376,10 +367,8 @@ abstract class ScalaPrimitives {
     addPrimitives(IntClass, nme.UNARY_+, POS)
     addPrimitives(IntClass, nme.UNARY_-, NEG)
     addPrimitives(IntClass, nme.UNARY_~, NOT)
-    if (!forCLDC) {
-      addPrimitives(IntClass, nme.toFloat,  I2F)
-      addPrimitives(IntClass, nme.toDouble, I2D)
-    }
+    addPrimitives(IntClass, nme.toFloat,  I2F)
+    addPrimitives(IntClass, nme.toDouble, I2D)
 
     // scala.Long
     addPrimitives(LongClass, nme.EQ, EQ)
@@ -409,62 +398,56 @@ abstract class ScalaPrimitives {
     addPrimitives(LongClass, nme.UNARY_+, POS)
     addPrimitives(LongClass, nme.UNARY_-, NEG)
     addPrimitives(LongClass, nme.UNARY_~, NOT)
-    if (!forCLDC) {
-      addPrimitives(LongClass, nme.toFloat,  L2F)
-      addPrimitives(LongClass, nme.toDouble, L2D)
-    }
-
-    if (!forCLDC) {
-      // scala.Float
-      addPrimitives(FloatClass, nme.EQ, EQ)
-      addPrimitives(FloatClass, nme.NE, NE)
-      addPrimitives(FloatClass, nme.ADD, ADD)
-      addPrimitives(FloatClass, nme.SUB, SUB)
-      addPrimitives(FloatClass, nme.MUL, MUL)
-      addPrimitives(FloatClass, nme.DIV, DIV)
-      addPrimitives(FloatClass, nme.MOD, MOD)
-      addPrimitives(FloatClass, nme.LT, LT)
-      addPrimitives(FloatClass, nme.LE, LE)
-      addPrimitives(FloatClass, nme.GT, GT)
-      addPrimitives(FloatClass, nme.GE, GE)
-      // conversions
-      addPrimitives(FloatClass, nme.toByte,   F2B)
-      addPrimitives(FloatClass, nme.toShort,  F2S)
-      addPrimitives(FloatClass, nme.toChar,   F2C)
-      addPrimitives(FloatClass, nme.toInt,    F2I)
-      addPrimitives(FloatClass, nme.toLong,   F2L)
-      addPrimitives(FloatClass, nme.toFloat,  F2F)
-      addPrimitives(FloatClass, nme.toDouble, F2D)
-      // unary methods
-      addPrimitives(FloatClass, nme.UNARY_+, POS)
-      addPrimitives(FloatClass, nme.UNARY_-, NEG)
-
-      // scala.Double
-      addPrimitives(DoubleClass, nme.EQ, EQ)
-      addPrimitives(DoubleClass, nme.NE, NE)
-      addPrimitives(DoubleClass, nme.ADD, ADD)
-      addPrimitives(DoubleClass, nme.SUB, SUB)
-      addPrimitives(DoubleClass, nme.MUL, MUL)
-      addPrimitives(DoubleClass, nme.DIV, DIV)
-      addPrimitives(DoubleClass, nme.MOD, MOD)
-      addPrimitives(DoubleClass, nme.LT, LT)
-      addPrimitives(DoubleClass, nme.LE, LE)
-      addPrimitives(DoubleClass, nme.GT, GT)
-      addPrimitives(DoubleClass, nme.GE, GE)
-      // conversions
-      addPrimitives(DoubleClass, nme.toByte,   D2B)
-      addPrimitives(DoubleClass, nme.toShort,  D2S)
-      addPrimitives(DoubleClass, nme.toChar,   D2C)
-      addPrimitives(DoubleClass, nme.toInt,    D2I)
-      addPrimitives(DoubleClass, nme.toLong,   D2L)
-      addPrimitives(DoubleClass, nme.toFloat,  D2F)
-      addPrimitives(DoubleClass, nme.toDouble, D2D)
-      // unary methods
-      addPrimitives(DoubleClass, nme.UNARY_+, POS)
-      addPrimitives(DoubleClass, nme.UNARY_-, NEG)
-    }
-    // and the type map!
-    initPrimitiveTypeMap
+    addPrimitives(LongClass, nme.toFloat,  L2F)
+    addPrimitives(LongClass, nme.toDouble, L2D)
+
+    // scala.Float
+    addPrimitives(FloatClass, nme.EQ, EQ)
+    addPrimitives(FloatClass, nme.NE, NE)
+    addPrimitives(FloatClass, nme.ADD, ADD)
+    addPrimitives(FloatClass, nme.SUB, SUB)
+    addPrimitives(FloatClass, nme.MUL, MUL)
+    addPrimitives(FloatClass, nme.DIV, DIV)
+    addPrimitives(FloatClass, nme.MOD, MOD)
+    addPrimitives(FloatClass, nme.LT, LT)
+    addPrimitives(FloatClass, nme.LE, LE)
+    addPrimitives(FloatClass, nme.GT, GT)
+    addPrimitives(FloatClass, nme.GE, GE)
+    // conversions
+    addPrimitives(FloatClass, nme.toByte,   F2B)
+    addPrimitives(FloatClass, nme.toShort,  F2S)
+    addPrimitives(FloatClass, nme.toChar,   F2C)
+    addPrimitives(FloatClass, nme.toInt,    F2I)
+    addPrimitives(FloatClass, nme.toLong,   F2L)
+    addPrimitives(FloatClass, nme.toFloat,  F2F)
+    addPrimitives(FloatClass, nme.toDouble, F2D)
+    // unary methods
+    addPrimitives(FloatClass, nme.UNARY_+, POS)
+    addPrimitives(FloatClass, nme.UNARY_-, NEG)
+
+    // scala.Double
+    addPrimitives(DoubleClass, nme.EQ, EQ)
+    addPrimitives(DoubleClass, nme.NE, NE)
+    addPrimitives(DoubleClass, nme.ADD, ADD)
+    addPrimitives(DoubleClass, nme.SUB, SUB)
+    addPrimitives(DoubleClass, nme.MUL, MUL)
+    addPrimitives(DoubleClass, nme.DIV, DIV)
+    addPrimitives(DoubleClass, nme.MOD, MOD)
+    addPrimitives(DoubleClass, nme.LT, LT)
+    addPrimitives(DoubleClass, nme.LE, LE)
+    addPrimitives(DoubleClass, nme.GT, GT)
+    addPrimitives(DoubleClass, nme.GE, GE)
+    // conversions
+    addPrimitives(DoubleClass, nme.toByte,   D2B)
+    addPrimitives(DoubleClass, nme.toShort,  D2S)
+    addPrimitives(DoubleClass, nme.toChar,   D2C)
+    addPrimitives(DoubleClass, nme.toInt,    D2I)
+    addPrimitives(DoubleClass, nme.toLong,   D2L)
+    addPrimitives(DoubleClass, nme.toFloat,  D2F)
+    addPrimitives(DoubleClass, nme.toDouble, D2D)
+    // unary methods
+    addPrimitives(DoubleClass, nme.UNARY_+, POS)
+    addPrimitives(DoubleClass, nme.UNARY_-, NEG)
   }
 
   /** Add a primitive operation to the map */
@@ -486,6 +469,18 @@ abstract class ScalaPrimitives {
   }
 
   def isCoercion(code: Int): Boolean = (code >= B2B) && (code <= D2D)
+  
+  final val typeOfArrayOp: Map[Int, TypeKind] = Map(
+    (List(ZARRAY_LENGTH, ZARRAY_GET, ZARRAY_SET) map (_ -> BOOL)) ++
+    (List(BARRAY_LENGTH, BARRAY_GET, BARRAY_SET) map (_ -> BYTE)) ++
+    (List(SARRAY_LENGTH, SARRAY_GET, SARRAY_SET) map (_ -> SHORT)) ++
+    (List(CARRAY_LENGTH, CARRAY_GET, CARRAY_SET) map (_ -> CHAR)) ++
+    (List(IARRAY_LENGTH, IARRAY_GET, IARRAY_SET) map (_ -> INT)) ++
+    (List(LARRAY_LENGTH, LARRAY_GET, LARRAY_SET) map (_ -> LONG)) ++
+    (List(FARRAY_LENGTH, FARRAY_GET, FARRAY_SET) map (_ -> FLOAT)) ++
+    (List(DARRAY_LENGTH, DARRAY_GET, DARRAY_SET) map (_ -> DOUBLE)) ++
+    (List(OARRAY_LENGTH, OARRAY_GET, OARRAY_SET) map (_ -> REFERENCE(AnyRefClass))) : _*
+  ) 
 
   /** Check whether the given operation code is an array operation. */
   def isArrayOp(code: Int): Boolean =
@@ -526,6 +521,8 @@ abstract class ScalaPrimitives {
 
     case _ => false
   }
+  def isUniversalEqualityOp(code: Int): Boolean = (code == EQ) || (code == NE)
+  def isReferenceEqualityOp(code: Int): Boolean = (code == ID) || (code == NI)
 
   def isArithmeticOp(code: Int): Boolean = code match {
     case POS | NEG | NOT => true; // unary
@@ -564,9 +561,9 @@ abstract class ScalaPrimitives {
   
   def isPrimitive(sym: Symbol): Boolean = primitives contains sym
 
-  /** Return the code for the givem symbol. */
+  /** Return the code for the given symbol. */
   def getPrimitive(sym: Symbol): Int = {
-    assert(isPrimitive(sym), "Unkown primitive " + sym)
+    assert(isPrimitive(sym), "Unknown primitive " + sym)
     primitives(sym)
   }
 
@@ -583,17 +580,23 @@ abstract class ScalaPrimitives {
     import definitions._
     val code = getPrimitive(fun)
 
-    var elem: Type = null
-    tpe match {
-      case TypeRef(_, sym, _elem :: Nil)
-           if (sym == ArrayClass) => elem = _elem
-      case _ => ()
+    def elementType = atPhase(currentRun.typerPhase) {
+      val arrayParent = tpe :: tpe.parents find {
+        case TypeRef(_, sym, _elem :: Nil)
+             if (sym == ArrayClass) => true
+        case _ => false
+      }
+      if (arrayParent.isEmpty) {
+        println(fun.fullName + " : " + tpe :: tpe.baseTypeSeq.toList)
+      }
+      val TypeRef(_, _, elem :: Nil) = arrayParent.get
+      elem
     }
 
     code match {
 
       case APPLY =>
-        toTypeKind(elem) match {
+        toTypeKind(elementType) match {
           case BOOL    => ZARRAY_GET
           case BYTE    => BARRAY_GET
           case SHORT   => SARRAY_GET
@@ -604,11 +607,11 @@ abstract class ScalaPrimitives {
           case DOUBLE  => DARRAY_GET
           case REFERENCE(_) | ARRAY(_) => OARRAY_GET
           case _ =>
-            abort("Unexpected array element type: " + elem)
+            abort("Unexpected array element type: " + elementType)
         }
 
       case UPDATE =>
-        toTypeKind(elem) match {
+        toTypeKind(elementType) match {
           case BOOL    => ZARRAY_SET
           case BYTE    => BARRAY_SET
           case SHORT   => SARRAY_SET
@@ -619,12 +622,11 @@ abstract class ScalaPrimitives {
           case DOUBLE  => DARRAY_SET
           case REFERENCE(_) | ARRAY(_) => OARRAY_SET
           case _ =>
-            abort("Unexpected array element type: " + elem)
+            abort("Unexpected array element type: " + elementType)
         }
 
       case LENGTH =>
-        assert(elem != null)
-        toTypeKind(elem) match {
+        toTypeKind(elementType) match {
           case BOOL    => ZARRAY_LENGTH
           case BYTE    => BARRAY_LENGTH
           case SHORT   => SARRAY_LENGTH
@@ -635,7 +637,7 @@ abstract class ScalaPrimitives {
           case DOUBLE  => DARRAY_LENGTH
           case REFERENCE(_) | ARRAY(_) => OARRAY_LENGTH
           case _ =>
-            abort("Unexpected array element type: " + elem)
+            abort("Unexpected array element type: " + elementType)
         }
 
       case _ =>
diff --git a/src/compiler/scala/tools/nsc/backend/WorklistAlgorithm.scala b/src/compiler/scala/tools/nsc/backend/WorklistAlgorithm.scala
index e5a813b..27f5b27 100644
--- a/src/compiler/scala/tools/nsc/backend/WorklistAlgorithm.scala
+++ b/src/compiler/scala/tools/nsc/backend/WorklistAlgorithm.scala
@@ -1,11 +1,11 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
 
-// $Id: WorklistAlgorithm.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.tools.nsc.backend
+package scala.tools.nsc
+package backend
 
 import scala.tools.nsc.ast._
 import scala.collection.mutable.Stack
diff --git a/src/compiler/scala/tools/nsc/backend/icode/BasicBlocks.scala b/src/compiler/scala/tools/nsc/backend/icode/BasicBlocks.scala
index bf046c8..833814a 100644
--- a/src/compiler/scala/tools/nsc/backend/icode/BasicBlocks.scala
+++ b/src/compiler/scala/tools/nsc/backend/icode/BasicBlocks.scala
@@ -1,15 +1,16 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
 
-// $Id: BasicBlocks.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.tools.nsc.backend.icode
+package scala.tools.nsc
+package backend
+package icode
 
 //import scala.tools.nsc.ast._
 import scala.collection.mutable.{Map, Set}
-import scala.collection.jcl.LinkedHashSet
+import scala.collection.mutable.LinkedHashSet
 import scala.tools.nsc.util.{Position,NoPosition}
 import scala.tools.nsc.backend.icode.analysis.ProgramPoint
 
@@ -38,8 +39,8 @@ trait BasicBlocks {
     def hasFlag(flag: Int): Boolean = (flags & flag) != 0
     
     /** Set the given flag. */
-    def setFlag(flag: Int): Unit = flags |= flag
-    def resetFlag(flag: Int) {
+    private def setFlag(flag: Int): Unit = flags |= flag
+    private def resetFlag(flag: Int) {
       flags &= ~flag
     }
     
@@ -57,13 +58,20 @@ trait BasicBlocks {
       if (b) setFlag(LOOP_HEADER) else resetFlag(LOOP_HEADER)
     
     /** Is this block the start block of an exception handler? */
-    def exceptionHandlerHeader = hasFlag(EX_HEADER)
-    def exceptionHandlerHeader_=(b: Boolean) = 
+    def exceptionHandlerStart = hasFlag(EX_HEADER)
+    def exceptionHandlerStart_=(b: Boolean) = 
       if (b) setFlag(EX_HEADER) else resetFlag(EX_HEADER)
 
-    /** Has this basic block been modified since the last call to 'toList'? */ 
-    private def touched = hasFlag(TOUCHED)
-    private def touched_=(b: Boolean) = if (b) setFlag(TOUCHED) else resetFlag(TOUCHED)
+    /** Has this basic block been modified since the last call to 'successors'? */
+    def touched = hasFlag(DIRTYSUCCS)
+    def touched_=(b: Boolean) = if (b) {
+      setFlag(DIRTYSUCCS | DIRTYPREDS)
+    } else {
+      resetFlag(DIRTYSUCCS | DIRTYPREDS)
+    }
+
+    // basic blocks start in a dirty state
+    setFlag(DIRTYSUCCS | DIRTYPREDS)
 
     /** Cached predecessors. */
     var preds: List[BasicBlock] = null
@@ -83,14 +91,14 @@ trait BasicBlocks {
     private var instrs: Array[Instruction] = _
 
     override def toList: List[Instruction] = {
-      if (closed && touched)
-        instructionList = List.fromArray(instrs)
-      instructionList
+      if (closed)
+        instrs.toList
+      else instructionList
     }
     
     /** Return an iterator over the instructions in this basic block. */
-    def elements: Iterator[Instruction] =
-      if (closed) instrs.elements else instructionList.reverse.elements
+    def iterator: Iterator[Instruction] =
+      if (closed) instrs.iterator else instructionList.reverse.iterator
     
     /** return the underlying array of instructions */
     def getArray: Array[Instruction] = {
@@ -99,12 +107,11 @@ trait BasicBlocks {
     }
 
     def fromList(is: List[Instruction]) {
+      code.touched = true
       instrs = toInstructionArray(is)
       closed = true
     }
 
-    // public:
-
     /** Return the index of inst. Uses reference equality.
      *  Returns -1 if not found.
      */
@@ -122,7 +129,7 @@ trait BasicBlocks {
 //    override def hashCode() = label;
 
     /** Apply a function to all the instructions of the block. */
-    override def foreach(f: Instruction => Unit) = {
+    override def foreach[U](f: Instruction => U) = {
       if (!closed) {
         dump
         global.abort("Traversing an open block!: " + label)
@@ -164,9 +171,9 @@ trait BasicBlocks {
      */
     def replaceInstruction(pos: Int, instr: Instruction): Boolean = {
       assert(closed, "Instructions can be replaced only after the basic block is closed")
-
-      instr.pos = instrs(pos).pos
+      instr.setPos(instrs(pos).pos)
       instrs(pos) = instr
+      code.touched = true
       true
     }
 
@@ -181,10 +188,11 @@ trait BasicBlocks {
       var i = 0
       var changed = false
       while (i < instrs.length && !changed) {
-        if (instrs(i) == oldInstr) {
-          newInstr.pos = oldInstr.pos
+        if (instrs(i) eq oldInstr) {
+          newInstr.setPos(oldInstr.pos)
           instrs(i) = newInstr
           changed = true
+          code.touched = true
         }
         i += 1
       }
@@ -192,7 +200,7 @@ trait BasicBlocks {
     }
 
     /** Replaces <code>iold</code> with <code>is</code>. It does not update
-     *  the position field in the newly inserted instrucitons, so it behaves
+     *  the position field in the newly inserted instructions, so it behaves
      *  differently than the one-instruction versions of this function.
      *
      *  @param iold ..
@@ -211,9 +219,11 @@ trait BasicBlocks {
       if (i < instrs.length) {
         val newInstrs = new Array[Instruction](instrs.length + is.length - 1);
         changed = true
+        code.touched = true
+
         Array.copy(instrs, 0, newInstrs, 0, i)
         var j = i
-        for (val x <- is) {
+        for (x <- is) {
           newInstrs(j) = x
           j += 1
         }
@@ -234,7 +244,7 @@ trait BasicBlocks {
         val newInstrs = new Array[Instruction](instrs.length + is.length);
         Array.copy(instrs, 0, newInstrs, 0, i)
         var j = i
-        for (val x <- is) {
+        for (x <- is) {
           newInstrs(j) = x
           j += 1
         }
@@ -242,6 +252,7 @@ trait BasicBlocks {
           Array.copy(instrs, i + 1, newInstrs, j, instrs.length - i)
         instrs = newInstrs;
       }
+      code.touched = true
     }
 
     /** Removes instructions found at the given positions.
@@ -262,6 +273,7 @@ trait BasicBlocks {
         i += 1
       }
       instrs = newInstrs
+      code.touched = true
     }
     
     /** Remove the last instruction of this basic block. It is
@@ -272,7 +284,7 @@ trait BasicBlocks {
         removeInstructionsAt(size)
       else {
         instructionList = instructionList.tail
-        touched = true
+        code.touched = true
       }
     }
 
@@ -285,7 +297,9 @@ trait BasicBlocks {
         var i = 0
         while (i < instrs.length) {
           map get instrs(i) match {
-            case Some(instr) => touched = replaceInstruction(i, instr)
+            case Some(instr) =>
+              val changed = replaceInstruction(i, instr)
+              code.touched |= changed
             case None => ()
           }
           i += 1
@@ -319,6 +333,10 @@ trait BasicBlocks {
         emit(instr, NoPosition)
     }
 
+    /** Emitting does not set touched to true. During code generation this is a hotspot and
+     *  setting the flag for each emit is a waste. Caching should happen only after a block
+     *  is closed, which sets the DIRTYSUCCS flag.
+     */
     def emit(instr: Instruction, pos: Position) {
       if (closed) {
         print()
@@ -327,8 +345,7 @@ trait BasicBlocks {
       assert(!closed || ignore, "BasicBlock closed")
 
       if (!ignore) {
-        touched = true
-        instr.pos = pos
+        instr.setPos(pos)
         instructionList = instr :: instructionList
         _lastInstruction = instr
       }
@@ -337,11 +354,25 @@ trait BasicBlocks {
     def emit(instrs: Seq[Instruction]) {
       instrs foreach (i => emit(i, i.pos))
     }
+    
+    /** The semantics of this are a little odd but it's designed to work
+     *  seamlessly with the existing code.  It emits each supplied instruction,
+     *  then closes the block.  The odd part is that if the instruction has
+     *  pos == NoPosition, it calls the 1-arg emit, but otherwise it calls
+     *  the 2-arg emit.  This way I could retain existing behavior exactly by
+     *  calling setPos on any instruction using the two arg version which
+     *  I wanted to include in a call to emitOnly.
+     */
+    def emitOnly(instrs: Instruction*) {
+      instrs foreach (i => if (i.pos == NoPosition) emit(i) else emit(i, i.pos))
+      this.close
+    }
 
     /** Close the block */
     def close {
       assert(instructionList.length > 0, "Empty block.")
       closed = true
+      setFlag(DIRTYSUCCS)
       instructionList = instructionList.reverse
       instrs = toInstructionArray(instructionList)
     }
@@ -350,6 +381,7 @@ trait BasicBlocks {
       assert(closed)
       closed = false
       ignore = false
+      touched = true
       instructionList = instructionList.reverse  // prepare for appending to the head
     }
 
@@ -394,12 +426,45 @@ trait BasicBlocks {
       array
     }
 
-    def successors : List[BasicBlock] = if (isEmpty) Nil else {
-      var res = lastInstruction match {
-        case JUMP (whereto) => List(whereto)
+    /** Cached value of successors. Must be recomputed whenver a block in the current method is changed. */
+    private var succs: List[BasicBlock] = Nil
+
+    def successors : List[BasicBlock] = {
+      if (touched) {
+        resetFlag(DIRTYSUCCS)
+        succs = if (isEmpty) Nil else {
+          var res = lastInstruction match {
+            case JUMP(whereto) => List(whereto)
+            case CJUMP(success, failure, _, _) => failure :: success :: Nil
+            case CZJUMP(success, failure, _, _) => failure :: success :: Nil
+            case SWITCH(_, labels) => labels
+            case RETURN(_) => Nil
+            case THROW() => Nil
+            case _ =>
+              if (closed) {
+                dump
+                global.abort("The last instruction is not a control flow instruction: " + lastInstruction)
+              }
+              else Nil
+          }
+          method.exh.foreach {
+            e: ExceptionHandler =>
+              if (e.covers(this)) res = e.startBlock :: res
+          }
+          val res1 = res ++ exceptionalSucc(this, res)
+          res1
+        }
+      }
+//        println("reusing cached successors for " + this + " in method " + method)
+      succs
+    }
+
+    def directSuccessors: List[BasicBlock] = {
+      if (isEmpty) Nil else lastInstruction match {
+        case JUMP(whereto) => List(whereto)
         case CJUMP(success, failure, _, _) => failure :: success :: Nil
         case CZJUMP(success, failure, _, _) => failure :: success :: Nil
-        case SWITCH(_,labels) => labels
+        case SWITCH(_, labels) => labels
         case RETURN(_) => Nil
         case THROW() => Nil
         case _ =>
@@ -409,12 +474,8 @@ trait BasicBlocks {
           }
           else Nil
       }
-      method.exh.foreach { e: ExceptionHandler =>
-        if (e.covers(this)) res = e.startBlock :: res
-      }
-      res ++ exceptionalSucc(this, res)
     }
-    
+
     /** Return a list of successors for 'b' that come from exception handlers
      *  covering b's (non-exceptional) successors. These exception handlers 
      *  might not cover 'b' itself. This situation corresponds to an 
@@ -423,20 +484,20 @@ trait BasicBlocks {
     private def exceptionalSucc(b: BasicBlock, succs: List[BasicBlock]): List[BasicBlock] = {
       def findSucc(s: BasicBlock): List[BasicBlock] = { 
         val ss = method.exh flatMap { h => 
-          if (h.covers(s)) List(h.startBlock) else Nil
+          if (h.covers(s) /*&& mayThrow(h.startBlock.firstInstruction)*/) List(h.startBlock) else Nil
         }
         ss ++ (ss flatMap findSucc)
       }
       
-      succs.flatMap(findSucc).removeDuplicates
+      succs.flatMap(findSucc).distinct
     }
 
-    /** Returns the precessors of this block, in the current 'code' chunk.
-     *  This is signifficant only if there are exception handlers, which live
-     *  in different code 'chunks' than the rest of the method.
-     */
+    /** Returns the predecessors of this block.     */
     def predecessors: List[BasicBlock] = {
-      preds = code.blocks.elements.filter (_.successors.contains(this)).toList
+      if (hasFlag(DIRTYPREDS)) {
+        resetFlag(DIRTYPREDS)
+        preds = code.blocks.iterator.filter (_.successors.contains(this)).toList
+      }
       preds
     }
 
@@ -445,14 +506,14 @@ trait BasicBlocks {
       case _ => false
     }
 
-    override def hashCode = label
+    override def hashCode = label * 41 + code.hashCode
     
     // Instead of it, rather use a printer
     def print() { print(java.lang.System.out) }
 
     def print(out: java.io.PrintStream) {
       out.println("block #"+label+" :")
-      toList.foreach(i => out.println("  " + i))
+      foreach(i => out.println("  " + i))
       out.print("Successors: ")
       successors.foreach((x: BasicBlock) => out.print(" "+x.label.toString()))
       out.println()
@@ -467,6 +528,17 @@ trait BasicBlocks {
     }
 
     override def toString(): String = "" + label
+
+    def flagsString: String =
+      ("block " + label + (
+         if (hasFlag(LOOP_HEADER)) " <loopheader> "
+         else if (hasFlag(IGNORING)) " <ignore> "
+         else if (hasFlag(EX_HEADER)) " <exheader> "
+         else if (hasFlag(CLOSED)) " <closed> "
+         else if (hasFlag(DIRTYSUCCS)) " <dirtysuccs> "
+         else if (hasFlag(DIRTYPREDS)) " <dirtypreds> "
+         else ""
+      ))
   }
 
 }
@@ -484,6 +556,9 @@ object BBFlags {
   /** This block is closed. No new instructions can be added. */
   final val CLOSED      = 0x00000008
 
-  /** This block has been changed, cached results are recomputed. */
-  final val TOUCHED     = 0x00000010
+  /** Code has been changed, recompute successors. */
+  final val DIRTYSUCCS     = 0x00000010
+
+  /** Code has been changed, recompute predecessors. */
+  final val DIRTYPREDS  = 0x00000020
 }
diff --git a/src/compiler/scala/tools/nsc/backend/icode/CheckerError.scala b/src/compiler/scala/tools/nsc/backend/icode/CheckerError.scala
deleted file mode 100644
index ae611cf..0000000
--- a/src/compiler/scala/tools/nsc/backend/icode/CheckerError.scala
+++ /dev/null
@@ -1,11 +0,0 @@
-/* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
- * @author  Martin Odersky
- */
-
-// $Id: CheckerError.scala 16894 2009-01-13 13:09:41Z cunei $
-
-package scala.tools.nsc.backend.icode
-
-class CheckerError(s: String) extends Exception(s)
-
diff --git a/src/compiler/scala/tools/nsc/backend/icode/CheckerException.scala b/src/compiler/scala/tools/nsc/backend/icode/CheckerException.scala
new file mode 100644
index 0000000..a2ba055
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/backend/icode/CheckerException.scala
@@ -0,0 +1,12 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
+ * @author  Martin Odersky
+ */
+
+
+package scala.tools.nsc
+package backend
+package icode
+
+class CheckerException(s: String) extends Exception(s)
+
diff --git a/src/compiler/scala/tools/nsc/backend/icode/Checkers.scala b/src/compiler/scala/tools/nsc/backend/icode/Checkers.scala
index f0ab07e..4eb8a6c 100644
--- a/src/compiler/scala/tools/nsc/backend/icode/Checkers.scala
+++ b/src/compiler/scala/tools/nsc/backend/icode/Checkers.scala
@@ -1,11 +1,12 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
 
-// $Id: Checkers.scala 16881 2009-01-09 16:28:11Z cunei $
 
-package scala.tools.nsc.backend.icode
+package scala.tools.nsc
+package backend
+package icode
 
 import scala.collection.mutable.{Buffer, ListBuffer, Map, HashMap}
 import scala.tools.nsc.symtab._
@@ -82,17 +83,17 @@ abstract class Checkers {
       for (f1 <- cls.fields; f2 <- cls.fields if f1 ne f2)
         if (f1.symbol.name == f2.symbol.name)
           Checkers.this.global.error("Repetitive field name: " +
-                                     f1.symbol.fullNameString);
+                                     f1.symbol.fullName);
 
       for (m1 <- cls.methods; m2 <- cls.methods if m1 ne m2)
         if (m1.symbol.name == m2.symbol.name &&
             m1.symbol.tpe =:= m2.symbol.tpe)
           Checkers.this.global.error("Repetitive method: " +
-                                     m1.symbol.fullNameString);
+                                     m1.symbol.fullName);
       clasz.methods.foreach(check)
     }
 
-    /** Apply the give funtion to each pair of the cartesian product of
+    /** Apply the give function to each pair of the cartesian product of
      * l1 x l2.
      */
     def pairwise[a](l1: List[a], l2: List[a])(f: (a, a) => Unit) =
@@ -112,12 +113,12 @@ abstract class Checkers {
 
       def append(elems: List[BasicBlock]) = elems foreach appendBlock;
       def appendBlock(bl: BasicBlock) =
-        if ( !worklist.exists(bl.==) )
-          worklist + bl;
+        if (!(worklist contains bl))
+          worklist += bl
 
       in.clear;  out.clear;
       code = c;
-      worklist + c.startBlock;
+      worklist += c.startBlock
       for (bl <- c.blocks) {
         in  += (bl -> emptyStack)
         out += (bl -> emptyStack)
@@ -149,8 +150,8 @@ abstract class Checkers {
         else if (s2 eq emptyStack) s1 
         else {
           if (s1.length != s2.length)
-            throw new CheckerError("Incompatible stacks: " + s1 + " and " + s2 + " in " + method + " at entry to block: " + bl);
-          new TypeStack(List.map2(s1.types, s2.types) (lub))
+            throw new CheckerException("Incompatible stacks: " + s1 + " and " + s2 + " in " + method + " at entry to block: " + bl);
+          new TypeStack((s1.types, s2.types).zipped map lub)
         }
       }
 
@@ -239,15 +240,15 @@ abstract class Checkers {
           receiver match {
             case REFERENCE(sym) =>
               checkBool(sym.info.member(method.name) != NoSymbol,
-                        "Method " + method + " does not exist in " + sym.fullNameString);
+                        "Method " + method + " does not exist in " + sym.fullName);
               if (method hasFlag Flags.PRIVATE)
                 checkBool(method.owner == clasz.symbol,
-                          "Cannot call private method of " + method.owner.fullNameString 
-                          + " from " + clasz.symbol.fullNameString);
+                          "Cannot call private method of " + method.owner.fullName 
+                          + " from " + clasz.symbol.fullName);
               else if (method hasFlag Flags.PROTECTED)
                 checkBool(clasz.symbol isSubClass method.owner,
-                          "Cannot call protected method of " + method.owner.fullNameString
-                          + " from " + clasz.symbol.fullNameString);
+                          "Cannot call protected method of " + method.owner.fullName
+                          + " from " + clasz.symbol.fullName);
 
             case ARRAY(_) =>
               checkBool(receiver.toType.member(method.name) != NoSymbol,
@@ -422,7 +423,7 @@ abstract class Checkers {
 
          case CALL_METHOD(method, style) =>
            style match {
-             case Dynamic =>
+             case Dynamic | InvokeDynamic =>
                checkStack(1 + method.info.paramTypes.length)
                checkMethodArgs(method)
                checkMethod(stack.pop, method)
diff --git a/src/compiler/scala/tools/nsc/backend/icode/ExceptionHandlers.scala b/src/compiler/scala/tools/nsc/backend/icode/ExceptionHandlers.scala
index 7cbca64..8e93fe6 100644
--- a/src/compiler/scala/tools/nsc/backend/icode/ExceptionHandlers.scala
+++ b/src/compiler/scala/tools/nsc/backend/icode/ExceptionHandlers.scala
@@ -3,9 +3,10 @@
  * @author  Martin Odersky
  */
 
-// $Id: ExceptionHandlers.scala 16377 2008-10-27 16:25:50Z dragos $
 
-package scala.tools.nsc.backend.icode;
+package scala.tools.nsc
+package backend
+package icode;
 
 import scala.collection._
 
@@ -28,7 +29,7 @@ trait ExceptionHandlers { self: ICodes =>
 
     def setStartBlock(b: BasicBlock) = {
       _startBlock = b;
-      b.exceptionHandlerHeader = true
+      b.exceptionHandlerStart = true
     }
     def startBlock = _startBlock;
 
diff --git a/src/compiler/scala/tools/nsc/backend/icode/GenICode.scala b/src/compiler/scala/tools/nsc/backend/icode/GenICode.scala
index 80b2b51..e47918b 100644
--- a/src/compiler/scala/tools/nsc/backend/icode/GenICode.scala
+++ b/src/compiler/scala/tools/nsc/backend/icode/GenICode.scala
@@ -1,16 +1,18 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
 
-// $Id: GenICode.scala 18854 2009-10-01 13:22:18Z dragos $
 
-package scala.tools.nsc.backend.icode
+package scala.tools.nsc
+package backend
+package icode
 
-import scala.collection.mutable.{Map, HashMap, ListBuffer, Buffer, HashSet}
+import scala.collection.{ mutable, immutable }
+import scala.collection.mutable.{ HashMap, ListBuffer, Buffer, HashSet }
 import scala.tools.nsc.symtab._
-import scala.tools.nsc.util.Position
-
+import scala.annotation.switch
+import PartialFunction._
 
 /** This class ...
  *
@@ -23,10 +25,24 @@ abstract class GenICode extends SubComponent  {
   import global._
   import icodes._
   import icodes.opcodes._
+  import definitions.{
+    ArrayClass, ObjectClass, ThrowableClass, StringClass, NothingClass, NullClass,
+    Object_equals, Object_isInstanceOf, Object_asInstanceOf, ScalaRunTimeModule,
+    BoxedNumberClass, BoxedCharacterClass,
+    getMember
+  }
+  import scalaPrimitives.{
+    isArrayOp, isComparisonOp, isLogicalOp,
+    isUniversalEqualityOp, isReferenceEqualityOp
+  }
+  import platform.isMaybeBoxed
 
   val phaseName = "icode"
 
   override def newPhase(prev: Phase) = new ICodePhase(prev)
+  
+  private def debugLog(msg: => String): Unit =
+    if (settings.debug.value) log(msg)
 
   class ICodePhase(prev: Phase) extends StdPhase(prev) {
 
@@ -34,21 +50,15 @@ abstract class GenICode extends SubComponent  {
 
     var unit: CompilationUnit = _
 
-    // We assume definitions are alread initialized
-    val STRING = REFERENCE(definitions.StringClass)
+    // We assume definitions are already initialized
+    val STRING = REFERENCE(StringClass)
 
     // this depends on the backend! should be changed.
-    val ANY_REF_CLASS = REFERENCE(definitions.ObjectClass)
+    val ANY_REF_CLASS = REFERENCE(ObjectClass)
 
-    val SCALA_ALL    = REFERENCE(definitions.NothingClass)
-    val SCALA_ALLREF = REFERENCE(definitions.NullClass)
-    val THROWABLE    = REFERENCE(definitions.ThrowableClass)
-    
-    val BoxesRunTime_equals = 
-      if (!forMSIL)
-        definitions.getMember(definitions.BoxesRunTimeClass, nme.equals_)
-      else 
-        definitions.getMember(definitions.getClass("scala.runtime.Comparator").linkedModuleOfClass, nme.equals_)
+    val SCALA_ALL    = REFERENCE(NothingClass)
+    val SCALA_ALLREF = REFERENCE(NullClass)
+    val THROWABLE    = REFERENCE(ThrowableClass)
 
     override def run {
       scalaPrimitives.init
@@ -59,7 +69,7 @@ abstract class GenICode extends SubComponent  {
     override def apply(unit: CompilationUnit): Unit = {
       this.unit = unit
       unit.icode.clear
-      log("Generating icode for " + unit)
+      informProgress("Generating icode for " + unit)
       gen(unit.body)
       this.unit = null
     }
@@ -77,17 +87,19 @@ abstract class GenICode extends SubComponent  {
     def gen(tree: Tree, ctx: Context): Context = tree match {
       case EmptyTree => ctx
 
-      case PackageDef(name, stats) =>
-        gen(stats, ctx setPackage name)
+      case PackageDef(pid, stats) =>
+        gen(stats, ctx setPackage pid.name)
 
       case ClassDef(mods, name, _, impl) =>
-        log("Generating class: " + tree.symbol.fullNameString)
+        log("Generating class: " + tree.symbol.fullName)
         val outerClass = ctx.clazz
         ctx setClass (new IClass(tree.symbol) setCompilationUnit unit)
         addClassFields(ctx, tree.symbol);
         classes += (tree.symbol -> ctx.clazz)
         unit.icode += ctx.clazz
         gen(impl, ctx)
+        ctx.clazz.methods = ctx.clazz.methods.reverse // preserve textual order
+        ctx.clazz.fields  = ctx.clazz.fields.reverse  // preserve textual order
         ctx setClass outerClass
 
       // !! modules should be eliminated by refcheck... or not?
@@ -108,7 +120,7 @@ abstract class GenICode extends SubComponent  {
 
         var ctx1 = ctx.enterMethod(m, tree.asInstanceOf[DefDef])
         addMethodParams(ctx1, vparamss)
-        m.native = m.symbol.hasAttribute(definitions.NativeAttr)
+        m.native = m.symbol.hasAnnotation(definitions.NativeAttr)
 
         if (!m.isDeferred && !m.native) {
           ctx1 = genLoad(rhs, ctx1, m.returnType);
@@ -139,14 +151,8 @@ abstract class GenICode extends SubComponent  {
         abort("Illegal tree in gen: " + tree)
     }
 
-    private def genStat(trees: List[Tree], ctx: Context): Context = {
-      var currentCtx = ctx
-
-      for (t <- trees)
-        currentCtx = genStat(t, currentCtx)
-
-      currentCtx
-    }
+    private def genStat(trees: List[Tree], ctx: Context): Context = 
+      trees.foldLeft(ctx)((currentCtx, t) => genStat(t, currentCtx))
 
     /**
      * Generate code for the given tree. The trees should contain statements
@@ -158,30 +164,296 @@ abstract class GenICode extends SubComponent  {
      * @return a new context. This is necessary for control flow instructions
      *         which may change the current basic block.
      */
-    private def genStat(tree: Tree, ctx: Context): Context = {
+    private def genStat(tree: Tree, ctx: Context): Context = tree match {
+      case Assign(lhs @ Select(_, _), rhs) =>
+        val isStatic = lhs.symbol.isStaticMember
+        var ctx1 = if (isStatic) ctx else genLoadQualifier(lhs, ctx)
+        
+        ctx1 = genLoad(rhs, ctx1, toTypeKind(lhs.symbol.info))
+        ctx1.bb.emit(STORE_FIELD(lhs.symbol, isStatic), tree.pos)
+        ctx1
 
-      tree match {
-        case Assign(lhs @ Select(_, _), rhs) =>
-          if (lhs.symbol.isStaticMember) {
-            val ctx1 = genLoad(rhs, ctx, toTypeKind(lhs.symbol.info))
-            ctx1.bb.emit(STORE_FIELD(lhs.symbol, true), tree.pos)
-            ctx1
-          } else {
-            var ctx1 = genLoadQualifier(lhs, ctx)
-            ctx1 = genLoad(rhs, ctx1, toTypeKind(lhs.symbol.info))
-            ctx1.bb.emit(STORE_FIELD(lhs.symbol, false), tree.pos)
-            ctx1
+      case Assign(lhs, rhs) =>
+        val ctx1 = genLoad(rhs, ctx, toTypeKind(lhs.symbol.info))
+        val Some(l) = ctx.method.lookupLocal(lhs.symbol)
+        ctx1.bb.emit(STORE_LOCAL(l), tree.pos)
+        ctx1
+
+      case _ =>
+        genLoad(tree, ctx, UNIT)
+    }
+    /**
+     * Generate code for primitive arithmetic operations.
+     * Returns (Context, Generated Type)
+     */
+    private def genArithmeticOp(tree: Tree, ctx: Context, code: Int): (Context, TypeKind) = {
+      val Apply(fun @ Select(larg, _), args) = tree
+      var ctx1 = ctx
+      var resKind = toTypeKind(larg.tpe)
+
+      if (settings.debug.value) {
+        assert(args.length <= 1,
+               "Too many arguments for primitive function: " + fun.symbol)
+        assert(resKind.isNumericType | resKind == BOOL,
+               resKind.toString() + " is not a numeric or boolean type " +
+               "[operation: " + fun.symbol + "]")
+      }
+
+      args match {
+        // unary operation
+        case Nil =>
+          ctx1 = genLoad(larg, ctx1, resKind)
+          code match {
+            case scalaPrimitives.POS =>
+              () // nothing 
+            case scalaPrimitives.NEG =>
+              ctx1.bb.emit(CALL_PRIMITIVE(Negation(resKind)), larg.pos)
+            case scalaPrimitives.NOT =>
+              ctx1.bb.emit(CALL_PRIMITIVE(Arithmetic(NOT, resKind)), larg.pos)
+            case _ =>
+              abort("Unknown unary operation: " + fun.symbol.fullName +
+                    " code: " + code)
           }
 
-        case Assign(lhs, rhs) =>
-          val ctx1 = genLoad(rhs, ctx, toTypeKind(lhs.symbol.info))
-          val Some(l) = ctx.method.lookupLocal(lhs.symbol)
-          ctx1.bb.emit(STORE_LOCAL(l), tree.pos)
-          ctx1
+        // binary operation
+        case rarg :: Nil =>
+          resKind = getMaxType(larg.tpe :: rarg.tpe :: Nil);
+          if (scalaPrimitives.isShiftOp(code) || scalaPrimitives.isBitwiseOp(code))
+            assert(resKind.isIntType | resKind == BOOL,
+                 resKind.toString() + " incompatible with arithmetic modulo operation: " + ctx1);
+                 
+          ctx1 = genLoad(larg, ctx1, resKind)
+          ctx1 = genLoad(rarg,
+                         ctx1, // check .NET size of shift arguments!
+                         if (scalaPrimitives.isShiftOp(code)) INT else resKind)
+                         
+          val primitiveOp = code match {
+            case scalaPrimitives.ADD    => Arithmetic(ADD, resKind)
+            case scalaPrimitives.SUB    => Arithmetic(SUB, resKind)
+            case scalaPrimitives.MUL    => Arithmetic(MUL, resKind)
+            case scalaPrimitives.DIV    => Arithmetic(DIV, resKind)
+            case scalaPrimitives.MOD    => Arithmetic(REM, resKind)
+            case scalaPrimitives.OR     => Logical(OR, resKind)
+            case scalaPrimitives.XOR    => Logical(XOR, resKind)
+            case scalaPrimitives.AND    => Logical(AND, resKind)
+            case scalaPrimitives.LSL    => Shift(LSL, resKind)
+            case scalaPrimitives.LSR    => Shift(LSR, resKind)
+            case scalaPrimitives.ASR    => Shift(ASR, resKind)
+            case _                      => abort("Unknown primitive: " + fun.symbol + "[" + code + "]")
+          }
+          ctx1.bb.emit(CALL_PRIMITIVE(primitiveOp), tree.pos)
 
         case _ =>
-          genLoad(tree, ctx, UNIT)
+          abort("Too many arguments for primitive function: " + tree)
       }
+      (ctx1, resKind)
+    }
+    
+    /** Generate primitive array operations.
+     *
+     *  @param tree ...
+     *  @param ctx  ...
+     *  @param code ...
+     *  @return     ...
+     */
+    private def genArrayOp(tree: Tree, ctx: Context, code: Int, expectedType: TypeKind): (Context, TypeKind) = {
+      import scalaPrimitives._
+      val Apply(Select(arrayObj, _), args) = tree
+      val k = toTypeKind(arrayObj.tpe)
+      val ARRAY(elem) = k
+      var ctx1 = genLoad(arrayObj, ctx, k)
+      val elementType = typeOfArrayOp.getOrElse(code, abort("Unknown operation on arrays: " + tree + " code: " + code))
+
+      var generatedType = expectedType
+
+      if (scalaPrimitives.isArrayGet(code)) {
+        // load argument on stack
+        if (settings.debug.value)
+          assert(args.length == 1,
+                 "Too many arguments for array get operation: " + tree);
+        ctx1 = genLoad(args.head, ctx1, INT)
+        generatedType = elem
+        ctx1.bb.emit(LOAD_ARRAY_ITEM(elementType), tree.pos)
+      }
+      else if (scalaPrimitives.isArraySet(code)) {
+        if (settings.debug.value)
+          assert(args.length == 2,
+                 "Too many arguments for array set operation: " + tree);
+        ctx1 = genLoad(args.head, ctx1, INT)
+        ctx1 = genLoad(args.tail.head, ctx1, toTypeKind(args.tail.head.tpe))
+        // the following line should really be here, but because of bugs in erasure
+        // we pretend we generate whatever type is expected from us.
+        //generatedType = UNIT
+
+        ctx1.bb.emit(STORE_ARRAY_ITEM(elementType), tree.pos)
+      }
+      else {
+        generatedType = INT
+        ctx1.bb.emit(CALL_PRIMITIVE(ArrayLength(elementType)), tree.pos)
+      }
+
+      (ctx1, generatedType)
+    }
+    private def genSynchronized(tree: Apply, ctx: Context, expectedType: TypeKind): (Context, TypeKind) = {
+      val Apply(fun, args) = tree
+      val monitor = ctx.makeLocal(tree.pos, ObjectClass.tpe, "monitor")
+      var monitorResult: Local = null
+
+      // if the synchronized block returns a result, store it in a local variable. just leaving
+      // it on the stack is not valid in MSIL (stack is cleaned when leaving try-blocks)
+      val argTpe = args.head.tpe
+      val hasResult = expectedType != UNIT
+      if (hasResult)
+        monitorResult = ctx.makeLocal(tree.pos, argTpe, "monitorResult")
+
+      var ctx1 = genLoadQualifier(fun, ctx)
+      ctx1.bb.emit(Seq(
+        DUP(ANY_REF_CLASS),
+        STORE_LOCAL(monitor),
+        MONITOR_ENTER() setPos tree.pos
+      ))
+      ctx1.enterSynchronized(monitor)
+      debugLog("synchronized block start")
+
+      ctx1 = ctx1.Try(
+        bodyCtx => {
+          val ctx2 = genLoad(args.head, bodyCtx, expectedType /* toTypeKind(tree.tpe.resultType) */)
+          if (hasResult)
+            ctx2.bb.emit(STORE_LOCAL(monitorResult))
+          ctx2.bb.emit(Seq(
+            LOAD_LOCAL(monitor),
+            MONITOR_EXIT() setPos tree.pos
+          ))
+          ctx2
+        }, List(
+          // tree.tpe / fun.tpe is object, which is no longer true after this transformation
+          (ThrowableClass, expectedType, exhCtx => {
+            exhCtx.bb.emit(Seq(
+              LOAD_LOCAL(monitor),
+              MONITOR_EXIT() setPos tree.pos,
+              THROW()
+            ))
+            exhCtx.bb.enterIgnoreMode
+            exhCtx
+          })), EmptyTree, tree)
+          
+      debugLog("synchronized block end with block %s closed=%s".format(ctx1.bb, ctx1.bb.closed))
+      ctx1.exitSynchronized(monitor)
+      if (hasResult)
+        ctx1.bb.emit(LOAD_LOCAL(monitorResult))
+      (ctx1, expectedType)
+    } 
+    
+    private def genLoadIf(tree: If, ctx: Context, expectedType: TypeKind): (Context, TypeKind) = {
+      val If(cond, thenp, elsep) = tree
+      
+      var thenCtx = ctx.newBlock
+      var elseCtx = ctx.newBlock
+      val contCtx = ctx.newBlock
+      
+      genCond(cond, ctx, thenCtx, elseCtx)
+      
+      val ifKind = toTypeKind(tree.tpe)
+      val thenKind = toTypeKind(thenp.tpe)
+      val elseKind = if (elsep == EmptyTree) UNIT else toTypeKind(elsep.tpe)
+
+      // we need to drop unneeded results, if one branch gives
+      // unit and the other gives something on the stack, because
+      // the type of 'if' is scala.Any, and its erasure would be Object.
+      // But unboxed units are not Objects...
+      def hasUnitBranch = thenKind == UNIT || elseKind == UNIT
+      val resKind = if (hasUnitBranch) UNIT else ifKind
+
+      if (hasUnitBranch)
+        debugLog("Will drop result from an if branch")
+
+      thenCtx = genLoad(thenp, thenCtx, resKind)
+      elseCtx = genLoad(elsep, elseCtx, resKind)
+      
+      assert(!settings.debug.value || !(hasUnitBranch && expectedType != UNIT),
+        "I produce UNIT in a context where " + expectedType + " is expected!")
+
+      thenCtx.bb.emitOnly(JUMP(contCtx.bb))
+      elseCtx.bb.emitOnly(
+        if (elsep == EmptyTree) JUMP(contCtx.bb)
+        else JUMP(contCtx.bb) setPos tree.pos
+      )
+
+      (contCtx, resKind)
+    }
+    private def genLoadTry(tree: Try, ctx: Context, setGeneratedType: TypeKind => Unit): Context = {
+      val Try(block, catches, finalizer) = tree
+      val kind = toTypeKind(tree.tpe)
+
+      val caseHandlers =
+        for (CaseDef(pat, _, body) <- catches.reverse) yield {
+          def genWildcardHandler(sym: Symbol): (Symbol, TypeKind, Context => Context) = 
+            (sym, kind, ctx => { 
+              ctx.bb.emit(DROP(REFERENCE(sym)))
+              genLoad(body, ctx, kind)
+            })
+          
+          pat match {            
+            case Typed(Ident(nme.WILDCARD), tpt)  => genWildcardHandler(tpt.tpe.typeSymbol)
+            case Ident(nme.WILDCARD)              => genWildcardHandler(ThrowableClass)
+            case Bind(name, _)                    =>
+              val exception = ctx.method addLocal new Local(pat.symbol, toTypeKind(pat.symbol.tpe), false)
+
+              (pat.symbol.tpe.typeSymbol, kind, {
+                ctx: Context =>
+                  ctx.bb.emit(STORE_LOCAL(exception), pat.pos);
+                  genLoad(body, ctx, kind);
+              })
+          }
+        }
+
+      ctx.Try(
+        bodyCtx => {
+          setGeneratedType(kind)
+          genLoad(block, bodyCtx, kind)
+        },
+        caseHandlers,
+        finalizer,
+        tree)
+    }
+    
+    private def genPrimitiveOp(tree: Apply, ctx: Context, expectedType: TypeKind): (Context, TypeKind) = {
+      val sym = tree.symbol
+      val Apply(fun @ Select(receiver, _), args) = tree
+      val code = scalaPrimitives.getPrimitive(sym, receiver.tpe)
+
+      if (scalaPrimitives.isArithmeticOp(code))
+        genArithmeticOp(tree, ctx, code)
+      else if (code == scalaPrimitives.CONCAT)
+        (genStringConcat(tree, ctx), STRING)
+      else if (code == scalaPrimitives.HASH)
+        (genScalaHash(receiver, ctx), INT)
+      else if (isArrayOp(code))
+        genArrayOp(tree, ctx, code, expectedType)
+      else if (isLogicalOp(code) || isComparisonOp(code)) {
+        val trueCtx = ctx.newBlock
+        val falseCtx = ctx.newBlock
+        val afterCtx = ctx.newBlock
+        genCond(tree, ctx, trueCtx, falseCtx)
+        trueCtx.bb.emitOnly(
+          CONSTANT(Constant(true)) setPos tree.pos,
+          JUMP(afterCtx.bb)
+        )
+        falseCtx.bb.emitOnly(
+          CONSTANT(Constant(false)) setPos tree.pos,
+          JUMP(afterCtx.bb)
+        )
+        (afterCtx, BOOL)
+      }
+      else if (code == scalaPrimitives.SYNCHRONIZED)
+        genSynchronized(tree, ctx, expectedType)
+      else if (scalaPrimitives.isCoercion(code)) {
+        val ctx1 = genLoad(receiver, ctx, toTypeKind(receiver.tpe))
+        genCoercion(tree, ctx1, code)
+        (ctx1, scalaPrimitives.generatedKind(code))
+      }
+      else abort("Primitive operation not handled yet: " + sym.fullName + "(" +
+                  fun.symbol.simpleName + ") " + " at: " + (tree.pos))
     }
 
     /**
@@ -197,188 +469,8 @@ abstract class GenICode extends SubComponent  {
     private def genLoad(tree: Tree, ctx: Context, expectedType: TypeKind): Context = {
       var generatedType = expectedType
       if (settings.debug.value)
-        log("at line: " + (tree.pos).line.map(_.toString).getOrElse(tree.pos.toString))
-
-      /**
-       * Generate code for primitive arithmetic operations.
-       */
-      def genArithmeticOp(tree: Tree, ctx: Context, code: Int): Context = {
-        val Apply(fun @ Select(larg, _), args) = tree
-        var ctx1 = ctx
-        var resKind = toTypeKind(larg.tpe)
-
-        if (settings.debug.value) {
-          assert(args.length <= 1,
-                 "Too many arguments for primitive function: " + fun.symbol)
-          assert(resKind.isNumericType | resKind == BOOL,
-                 resKind.toString() + " is not a numeric or boolean type " +
-                 "[operation: " + fun.symbol + "]")
-        }
-
-        args match {
-          // unary operation
-          case Nil =>
-            ctx1 = genLoad(larg, ctx1, resKind)
-            code match {
-              case scalaPrimitives.POS =>
-                () // nothing 
-              case scalaPrimitives.NEG =>
-                ctx1.bb.emit(CALL_PRIMITIVE(Negation(resKind)), larg.pos)
-              case scalaPrimitives.NOT =>
-                ctx1.bb.emit(CALL_PRIMITIVE(Arithmetic(NOT, resKind)), larg.pos)
-              case _ =>
-                abort("Unknown unary operation: " + fun.symbol.fullNameString +
-                      " code: " + code)
-            }
-            generatedType = resKind
-
-          // binary operation
-          case rarg :: Nil =>
-            resKind = getMaxType(larg.tpe :: rarg.tpe :: Nil);
-            if (scalaPrimitives.isShiftOp(code) || scalaPrimitives.isBitwiseOp(code))
-              assert(resKind.isIntType | resKind == BOOL,
-                   resKind.toString() + " incompatible with arithmetic modulo operation: " + ctx1);
-
-            ctx1 = genLoad(larg, ctx1, resKind);
-            ctx1 = genLoad(rarg,
-                           ctx1,  // check .NET size of shift arguments!
-                           if (scalaPrimitives.isShiftOp(code)) INT else resKind)
-
-            generatedType = resKind
-            code match {
-              case scalaPrimitives.ADD =>
-                ctx1.bb.emit(CALL_PRIMITIVE(Arithmetic(ADD, resKind)), tree.pos)
-              case scalaPrimitives.SUB =>
-                ctx1.bb.emit(CALL_PRIMITIVE(Arithmetic(SUB, resKind)), tree.pos)
-              case scalaPrimitives.MUL =>
-                ctx1.bb.emit(CALL_PRIMITIVE(Arithmetic(MUL, resKind)), tree.pos)
-              case scalaPrimitives.DIV =>
-                ctx1.bb.emit(CALL_PRIMITIVE(Arithmetic(DIV, resKind)), tree.pos)
-              case scalaPrimitives.MOD =>
-                ctx1.bb.emit(CALL_PRIMITIVE(Arithmetic(REM, resKind)), tree.pos)
-              case scalaPrimitives.OR  =>
-                ctx1.bb.emit(CALL_PRIMITIVE(Logical(OR, resKind)), tree.pos)
-              case scalaPrimitives.XOR =>
-                ctx1.bb.emit(CALL_PRIMITIVE(Logical(XOR, resKind)), tree.pos)
-              case scalaPrimitives.AND =>
-                ctx1.bb.emit(CALL_PRIMITIVE(Logical(AND, resKind)), tree.pos)
-              case scalaPrimitives.LSL =>
-                ctx1.bb.emit(CALL_PRIMITIVE(Shift(LSL, resKind)), tree.pos)
-                generatedType = resKind
-              case scalaPrimitives.LSR =>
-                ctx1.bb.emit(CALL_PRIMITIVE(Shift(LSR, resKind)), tree.pos)
-                generatedType = resKind
-              case scalaPrimitives.ASR =>
-                ctx1.bb.emit(CALL_PRIMITIVE(Shift(ASR, resKind)), tree.pos)
-                generatedType = resKind
-              case _ =>
-                abort("Unknown primitive: " + fun.symbol + "[" + code + "]")
-            }
-
-          case _ =>
-            abort("Too many arguments for primitive function: " + tree)
-        }
-        ctx1
-      }
-
-      /** Generate primitive array operations.
-       *
-       *  @param tree ...
-       *  @param ctx  ...
-       *  @param code ...
-       *  @return     ...
-       */
-      def genArrayOp(tree: Tree, ctx: Context, code: Int): Context = {
-        import scalaPrimitives._
-        val Apply(Select(arrayObj, _), args) = tree
-        val k = toTypeKind(arrayObj.tpe)
-        val ARRAY(elem) = k
-        var ctx1 = genLoad(arrayObj, ctx, k)
-
-        if (scalaPrimitives.isArrayGet(code)) {
-          // load argument on stack
-          if (settings.debug.value)
-            assert(args.length == 1,
-                   "Too many arguments for array get operation: " + tree);
-          ctx1 = genLoad(args.head, ctx1, INT)
-          generatedType = elem
-        } else if (scalaPrimitives.isArraySet(code)) {
-          if (settings.debug.value)
-            assert(args.length == 2,
-                   "Too many arguments for array set operation: " + tree);
-          ctx1 = genLoad(args.head, ctx1, INT)
-          ctx1 = genLoad(args.tail.head, ctx1, toTypeKind(args.tail.head.tpe))
-          // the following line should really be here, but because of bugs in erasure
-          // we pretend we generate whatever type is expected from us.
-          //generatedType = UNIT
-        } else
-          generatedType = INT
-
-        code match {
-          case ZARRAY_LENGTH =>
-            ctx1.bb.emit(CALL_PRIMITIVE(ArrayLength(BOOL)), tree.pos)
-          case BARRAY_LENGTH =>
-            ctx1.bb.emit(CALL_PRIMITIVE(ArrayLength(BYTE)), tree.pos)
-          case SARRAY_LENGTH =>
-            ctx1.bb.emit(CALL_PRIMITIVE(ArrayLength(SHORT)), tree.pos)
-          case CARRAY_LENGTH =>
-            ctx1.bb.emit(CALL_PRIMITIVE(ArrayLength(CHAR)), tree.pos)
-          case IARRAY_LENGTH =>
-            ctx1.bb.emit(CALL_PRIMITIVE(ArrayLength(INT)), tree.pos)
-          case LARRAY_LENGTH =>
-            ctx1.bb.emit(CALL_PRIMITIVE(ArrayLength(LONG)), tree.pos)
-          case FARRAY_LENGTH =>
-            ctx1.bb.emit(CALL_PRIMITIVE(ArrayLength(FLOAT)), tree.pos)
-          case DARRAY_LENGTH =>
-            ctx1.bb.emit(CALL_PRIMITIVE(ArrayLength(DOUBLE)), tree.pos)
-          case OARRAY_LENGTH =>
-            ctx1.bb.emit(CALL_PRIMITIVE(ArrayLength(ANY_REF_CLASS)), tree.pos)
-
-          case ZARRAY_GET =>
-            ctx1.bb.emit(LOAD_ARRAY_ITEM(BOOL), tree.pos)
-          case BARRAY_GET =>
-            ctx1.bb.emit(LOAD_ARRAY_ITEM(BYTE), tree.pos)
-          case SARRAY_GET =>
-            ctx1.bb.emit(LOAD_ARRAY_ITEM(SHORT), tree.pos)
-          case CARRAY_GET =>
-            ctx1.bb.emit(LOAD_ARRAY_ITEM(CHAR), tree.pos)
-          case IARRAY_GET =>
-            ctx1.bb.emit(LOAD_ARRAY_ITEM(INT), tree.pos)
-          case LARRAY_GET =>
-            ctx1.bb.emit(LOAD_ARRAY_ITEM(LONG), tree.pos)
-          case FARRAY_GET =>
-            ctx1.bb.emit(LOAD_ARRAY_ITEM(FLOAT), tree.pos)
-          case DARRAY_GET =>
-            ctx1.bb.emit(LOAD_ARRAY_ITEM(DOUBLE), tree.pos)
-          case OARRAY_GET =>
-            ctx1.bb.emit(LOAD_ARRAY_ITEM(ANY_REF_CLASS), tree.pos)
-
-          case ZARRAY_SET =>
-            ctx1.bb.emit(STORE_ARRAY_ITEM(BOOL), tree.pos)
-          case BARRAY_SET =>
-            ctx1.bb.emit(STORE_ARRAY_ITEM(BYTE), tree.pos)
-          case SARRAY_SET =>
-            ctx1.bb.emit(STORE_ARRAY_ITEM(SHORT), tree.pos)
-          case CARRAY_SET =>
-            ctx1.bb.emit(STORE_ARRAY_ITEM(CHAR), tree.pos)
-          case IARRAY_SET =>
-            ctx1.bb.emit(STORE_ARRAY_ITEM(INT), tree.pos)
-          case LARRAY_SET =>
-            ctx1.bb.emit(STORE_ARRAY_ITEM(LONG), tree.pos)
-          case FARRAY_SET =>
-            ctx1.bb.emit(STORE_ARRAY_ITEM(FLOAT), tree.pos)
-          case DARRAY_SET =>
-            ctx1.bb.emit(STORE_ARRAY_ITEM(DOUBLE), tree.pos)
-          case OARRAY_SET =>
-            ctx1.bb.emit(STORE_ARRAY_ITEM(ANY_REF_CLASS), tree.pos)
-
-          case _ =>
-            abort("Unknown operation on arrays: " + tree + " code: " + code)
-        }
-        ctx1
-      }
+        log("at line: " + (if (tree.pos.isDefined) tree.pos.line else tree.pos))
 
-      // genLoad
       val resCtx: Context = tree match {
         case LabelDef(name, params, rhs) =>
           val ctx1 = ctx.newBlock
@@ -408,8 +500,6 @@ abstract class GenICode extends SubComponent  {
         case ValDef(_, _, _, rhs) =>
           val sym = tree.symbol
           val local = ctx.method.addLocal(new Local(sym, toTypeKind(sym.info), false))
-          ctx.scope.add(local)
-          ctx.bb.emit(SCOPE_ENTER(local))
 
           if (rhs == EmptyTree) {
             if (settings.debug.value)
@@ -422,49 +512,15 @@ abstract class GenICode extends SubComponent  {
             ctx1 = genLoad(rhs, ctx, local.kind);
 
           ctx1.bb.emit(STORE_LOCAL(local), tree.pos)
+          ctx1.scope.add(local)
+          ctx1.bb.emit(SCOPE_ENTER(local))
           generatedType = UNIT
           ctx1
 
-        case If(cond, thenp, elsep) =>
-          var thenCtx = ctx.newBlock
-          var elseCtx = ctx.newBlock
-          val contCtx = ctx.newBlock
-            genCond(cond, ctx, thenCtx, elseCtx)
-          val ifKind = toTypeKind(tree.tpe)
-
-          val thenKind = toTypeKind(thenp.tpe)
-          val elseKind = if (elsep == EmptyTree) UNIT else toTypeKind(elsep.tpe)
-
-          generatedType = ifKind
-
-          // we need to drop unneeded results, if one branch gives
-          // unit and the other gives something on the stack, because
-          // the type of 'if' is scala.Any, and its erasure would be Object.
-          // But unboxed units are not Objects...
-          if (thenKind == UNIT || elseKind == UNIT) {
-            if (settings.debug.value)
-              log("Will drop result from an if branch");
-            thenCtx = genLoad(thenp, thenCtx, UNIT)
-            elseCtx = genLoad(elsep, elseCtx, UNIT)
-            if (settings.debug.value)
-              assert(expectedType == UNIT,
-                     "I produce UNIT in a context where " +
-                     expectedType + " is expected!")
-            generatedType = UNIT
-          } else {
-            thenCtx = genLoad(thenp, thenCtx, ifKind)
-            elseCtx = genLoad(elsep, elseCtx, ifKind)
-          }
-
-          thenCtx.bb.emit(JUMP(contCtx.bb))
-          thenCtx.bb.close
-          if (elsep == EmptyTree)
-            elseCtx.bb.emit(JUMP(contCtx.bb), tree.pos)
-          else
-            elseCtx.bb.emit(JUMP(contCtx.bb))
-          elseCtx.bb.close
-
-          contCtx
+        case t @ If(cond, thenp, elsep) =>
+          val (newCtx, resKind) = genLoadIf(t, ctx, expectedType)
+          generatedType = resKind
+          newCtx
 
         case Return(expr) =>
           val returnedKind = toTypeKind(expr.tpe)
@@ -493,47 +549,13 @@ abstract class GenICode extends SubComponent  {
           ctx1.cleanups = oldcleanups
 
           if (saved) ctx1.bb.emit(LOAD_LOCAL(tmp))
-          adapt(returnedKind, ctx.method.returnType, ctx, tree.pos)
+          adapt(returnedKind, ctx1.method.returnType, ctx1, tree.pos)
           ctx1.bb.emit(RETURN(ctx.method.returnType), tree.pos)
           ctx1.bb.enterIgnoreMode
           generatedType = expectedType
           ctx1
 
-        case Try(block, catches, finalizer) =>
-          val kind = toTypeKind(tree.tpe)
-
-          var handlers = for (CaseDef(pat, _, body) <- catches.reverse)
-            yield pat match {
-              case Typed(Ident(nme.WILDCARD), tpt) => (tpt.tpe.typeSymbol, kind, {
-                ctx: Context =>
-                  ctx.bb.emit(DROP(REFERENCE(tpt.tpe.typeSymbol)));
-                  genLoad(body, ctx, kind);
-                })
-
-              case Ident(nme.WILDCARD) => (definitions.ThrowableClass, kind, {
-                ctx: Context =>
-                  ctx.bb.emit(DROP(REFERENCE(definitions.ThrowableClass)))
-                  genLoad(body, ctx, kind)
-                })
-
-              case Bind(name, _) =>
-                val exception = ctx.method.addLocal(new Local(pat.symbol, toTypeKind(pat.symbol.tpe), false))
-
-                (pat.symbol.tpe.typeSymbol, kind, {
-                  ctx: Context =>
-                    ctx.bb.emit(STORE_LOCAL(exception), pat.pos);
-                    genLoad(body, ctx, kind);
-                })
-            }
-
-          ctx.Try(
-            bodyCtx => {
-              generatedType = kind; //toTypeKind(block.tpe);
-              genLoad(block, bodyCtx, generatedType);
-            },
-            handlers,
-            finalizer,
-            tree)
+        case t @ Try(_, _, _) => genLoadTry(t, ctx, (x: TypeKind) => generatedType = x)
 
         case Throw(expr) =>
           val ctx1 = genLoad(expr, ctx, THROWABLE)
@@ -547,35 +569,32 @@ abstract class GenICode extends SubComponent  {
 
         case Apply(TypeApply(fun, targs), _) =>
           val sym = fun.symbol
-          var ctx1 = ctx
-          var cast = false
-
-          if (sym == definitions.Object_isInstanceOf) 
-            cast = false
-          else if (sym == definitions.Object_asInstanceOf)
-            cast = true
-          else
-            abort("Unexpected type application " + fun + "[sym: " + sym.fullNameString + "]" + " in: " + tree)
+          val cast = sym match {
+            case Object_isInstanceOf  => false
+            case Object_asInstanceOf  => true
+            case _                    => abort("Unexpected type application " + fun + "[sym: " + sym.fullName + "]" + " in: " + tree)
+          }
 
           val Select(obj, _) = fun
           val l = toTypeKind(obj.tpe)
           val r = toTypeKind(targs.head.tpe)
-
-          ctx1 = genLoadQualifier(fun, ctx)
+          val ctx1 = genLoadQualifier(fun, ctx)
 
           if (l.isValueType && r.isValueType)
             genConversion(l, r, ctx1, cast)
-          else if (l.isValueType) {
+          else if (l.isValueType) {            
             ctx1.bb.emit(DROP(l), fun.pos)
             if (cast) {
-              ctx1.bb.emit(NEW(REFERENCE(definitions.getClass("ClassCastException"))))
-              ctx1.bb.emit(DUP(ANY_REF_CLASS))
-              ctx1.bb.emit(THROW())
+              ctx1.bb.emit(Seq(
+                NEW(REFERENCE(definitions.getClass("ClassCastException"))),
+                DUP(ANY_REF_CLASS),
+                THROW()
+              ))
             } else
               ctx1.bb.emit(CONSTANT(Constant(false)))
           }
           else if (r.isValueType && cast) {
-            assert(false) /* Erasure should have added an unboxing operation to prevent that. */
+            assert(false, tree) /* Erasure should have added an unboxing operation to prevent that. */
           }
           else if (r.isValueType)
             ctx.bb.emit(IS_INSTANCE(REFERENCE(definitions.boxedClass(r.toType.typeSymbol))))
@@ -616,16 +635,14 @@ abstract class GenICode extends SubComponent  {
             assert(ctor.isClassConstructor,
                    "'new' call to non-constructor: " + ctor.name)
 
-          generatedType = toTypeKind(fun.tpe.resultType)
+          generatedType = toTypeKind(tpt.tpe)
           if (settings.debug.value)
             assert(generatedType.isReferenceType || generatedType.isArrayType,
                  "Non reference type cannot be instantiated: " + generatedType)
 
-          var ctx1 = ctx
-
           generatedType match {
             case arr @ ARRAY(elem) =>
-              ctx1 = genLoadArguments(args, ctor.info.paramTypes, ctx)
+              val ctx1 = genLoadArguments(args, ctor.info.paramTypes, ctx)
               val dims = arr.dimensions
               var elemKind = arr.elementKind
               if (args.length > dims)
@@ -634,28 +651,29 @@ abstract class GenICode extends SubComponent  {
               if (args.length != dims)
                 for (i <- args.length until dims) elemKind = ARRAY(elemKind)
               ctx1.bb.emit(CREATE_ARRAY(elemKind, args.length), tree.pos)
+              ctx1
 
             case rt @ REFERENCE(cls) =>
               if (settings.debug.value)
                 assert(ctor.owner == cls,
-                       "Symbol " + ctor.owner.fullNameString + " is different than " + tpt)
+                       "Symbol " + ctor.owner.fullName + " is different than " + tpt)
               val nw = NEW(rt)
-              ctx1.bb.emit(nw, tree.pos)
-              ctx1.bb.emit(DUP(generatedType))
-              ctx1 = genLoadArguments(args, ctor.info.paramTypes, ctx)
+              ctx.bb.emit(nw, tree.pos)
+              ctx.bb.emit(DUP(generatedType))
+              val ctx1 = genLoadArguments(args, ctor.info.paramTypes, ctx)
 
               val init = CALL_METHOD(ctor, Static(true))
               nw.init = init
               ctx1.bb.emit(init, tree.pos)
+              ctx1
 
             case _ =>
               abort("Cannot instantiate " + tpt + "of kind: " + generatedType)
           }
-          ctx1
 
         case Apply(fun @ _, List(expr)) if (definitions.isBox(fun.symbol)) =>
           if (settings.debug.value)
-            log("BOX : " + fun.symbol.fullNameString);
+            log("BOX : " + fun.symbol.fullName);
           val ctx1 = genLoad(expr, ctx, toTypeKind(expr.tpe))
           val nativeKind = toTypeKind(expr.tpe)
           if (settings.Xdce.value) {
@@ -672,14 +690,14 @@ abstract class GenICode extends SubComponent  {
 
         case Apply(fun @ _, List(expr)) if (definitions.isUnbox(fun.symbol)) =>
           if (settings.debug.value)
-            log("UNBOX : " + fun.symbol.fullNameString)
+            log("UNBOX : " + fun.symbol.fullName)
           val ctx1 = genLoad(expr, ctx, toTypeKind(expr.tpe))
           val boxType = toTypeKind(fun.symbol.owner.linkedClassOfClass.tpe)
           generatedType = boxType
           ctx1.bb.emit(UNBOX(boxType), expr.pos)
           ctx1
 
-        case Apply(fun, args) =>
+        case app @ Apply(fun, args) =>
           val sym = fun.symbol
 
           if (sym.isLabel) {  // jump to a label
@@ -700,79 +718,12 @@ abstract class GenICode extends SubComponent  {
                 }
             }
             val ctx1 = genLoadLabelArguments(args, label, ctx)
-            if (label.anchored)
-              ctx1.bb.emit(JUMP(label.block), tree.pos)
-            else
-              ctx1.bb.emit(PJUMP(label), tree.pos)
-
-            ctx1.bb.close
+            ctx1.bb.emitOnly(if (label.anchored) JUMP(label.block) else PJUMP(label))
             ctx1.newBlock
           } else if (isPrimitive(sym)) { // primitive method call
-            val Select(receiver, _) = fun
-
-            val code = scalaPrimitives.getPrimitive(sym, receiver.tpe)
-            var ctx1 = ctx
-
-            if (scalaPrimitives.isArithmeticOp(code)) {
-              ctx1 = genArithmeticOp(tree, ctx1, code)
-            } else if (code == scalaPrimitives.CONCAT) {
-              ctx1 = genStringConcat(tree, ctx1)
-              generatedType = STRING
-            } else if (scalaPrimitives.isArrayOp(code)) {
-              ctx1 = genArrayOp(tree, ctx1, code)
-            } else if (scalaPrimitives.isLogicalOp(code) ||
-                       scalaPrimitives.isComparisonOp(code)) {
-
-              val trueCtx = ctx1.newBlock
-              val falseCtx = ctx1.newBlock
-              val afterCtx = ctx1.newBlock
-              genCond(tree, ctx1, trueCtx, falseCtx)
-              trueCtx.bb.emit(CONSTANT(Constant(true)), tree.pos)
-              trueCtx.bb.emit(JUMP(afterCtx.bb))
-              trueCtx.bb.close
-              falseCtx.bb.emit(CONSTANT(Constant(false)), tree.pos)
-              falseCtx.bb.emit(JUMP(afterCtx.bb))
-              falseCtx.bb.close
-              generatedType = BOOL
-              ctx1 = afterCtx
-            } else if (code == scalaPrimitives.SYNCHRONIZED) {
-              val monitor = ctx.makeLocal(tree.pos, definitions.ObjectClass.tpe, "monitor") 
-              ctx1 = genLoadQualifier(fun, ctx1)
-              ctx1.bb.emit(DUP(ANY_REF_CLASS))
-              ctx1.bb.emit(STORE_LOCAL(monitor))
-              ctx1.bb.emit(MONITOR_ENTER(), tree.pos)
-              ctx1.enterSynchronized(monitor)
-
-              if (settings.debug.value)
-                log("synchronized block start");
-
-              ctx1 = ctx1.Try(
-                bodyCtx => {
-                  val ctx1 = genLoad(args.head, bodyCtx, expectedType /* toTypeKind(tree.tpe.resultType) */)
-                  ctx1.bb.emit(LOAD_LOCAL(monitor))
-                  ctx1.bb.emit(MONITOR_EXIT(), tree.pos)
-                  ctx1
-                }, List(
-                  // tree.tpe / fun.tpe is object, which is no longer true after this transformation
-                  (NoSymbol, expectedType, exhCtx => {
-                  exhCtx.bb.emit(LOAD_LOCAL(monitor))
-                  exhCtx.bb.emit(MONITOR_EXIT(), tree.pos)
-                  exhCtx.bb.emit(THROW())
-                  exhCtx.bb.enterIgnoreMode
-                  exhCtx
-                })), EmptyTree, tree);
-              if (settings.debug.value)
-                log("synchronized block end with block " + ctx1.bb +
-                    " closed=" + ctx1.bb.closed);
-              ctx1.exitSynchronized(monitor)
-            } else if (scalaPrimitives.isCoercion(code)) {
-              ctx1 = genLoad(receiver, ctx1, toTypeKind(receiver.tpe))
-              genCoercion(tree, ctx1, code)
-              generatedType = scalaPrimitives.generatedKind(code)
-            } else
-              abort("Primitive operation not handled yet: " + sym.fullNameString + "(" +
-                    fun.symbol.simpleName + ") " + " at: " + (tree.pos));
-            ctx1
+            val (newCtx, resKind) = genPrimitiveOp(app, ctx, expectedType)
+            generatedType = resKind
+            newCtx            
           } else {  // normal method call
             if (settings.debug.value)
               log("Gen CALL_METHOD with sym: " + sym + " isStaticSymbol: " + sym.isStaticMember);
@@ -789,16 +740,25 @@ abstract class GenICode extends SubComponent  {
               else ctx
 
             ctx1 = genLoadArguments(args, sym.info.paramTypes, ctx1)
-
-            val hostClass = fun match {
-              case Select(qualifier, _)
-              if (qualifier.tpe.typeSymbol != definitions.ArrayClass) =>
-                qualifier.tpe.typeSymbol
-              case _ => sym.owner
+            val cm = CALL_METHOD(sym, invokeStyle)
+            
+            /** In a couple cases, squirrel away a little extra information in the
+             *  CALL_METHOD for use by GenJVM.
+             */
+            fun match {
+              case Select(qual, _) =>
+                val qualSym = qual.tpe.typeSymbol
+                if (qualSym == ArrayClass) cm setTargetTypeKind toTypeKind(qual.tpe)
+                else cm setHostClass qualSym
+                  
+                if (settings.debug.value) log(
+                  if (qualSym == ArrayClass) "Stored target type kind " + toTypeKind(qual.tpe) + " for " + sym.fullName
+                  else "Set more precise host class for " + sym.fullName + " host: " + qualSym
+                )
+              case _ =>
             }
-            if (settings.debug.value && hostClass != sym.owner)
-              log("Set more precise host class for " + sym.fullNameString + " host: " + hostClass);
-            ctx1.bb.emit(CALL_METHOD(sym, invokeStyle) setHostClass hostClass, tree.pos)
+            ctx1.bb.emit(cm, tree.pos)
+            
             if (sym == ctx1.method.symbol) {
               ctx1.method.recursive = true
             }
@@ -808,6 +768,13 @@ abstract class GenICode extends SubComponent  {
             ctx1
           }
 
+        case ApplyDynamic(qual, args) =>
+          ctx.clazz.bootstrapClass = Some("scala.runtime.DynamicDispatch")
+          val ctx1 = genLoad(qual, ctx, ANY_REF_CLASS)
+          genLoadArguments(args, tree.symbol.info.paramTypes, ctx1)
+          ctx1.bb.emit(CALL_METHOD(tree.symbol, InvokeDynamic), tree.pos)
+          ctx1
+          
         case This(qual) =>
           assert(tree.symbol == ctx.clazz.symbol || tree.symbol.isModuleClass,
                  "Trying to access the this of another class: " +
@@ -816,14 +783,13 @@ abstract class GenICode extends SubComponent  {
             if (settings.debug.value)
               log("LOAD_MODULE from 'This': " + tree.symbol);
             assert(!tree.symbol.isPackageClass, "Cannot use package as value: " + tree)
-            ctx.bb.emit(LOAD_MODULE(tree.symbol), tree.pos)
+            genLoadModule(ctx, tree.symbol, tree.pos)
             generatedType = REFERENCE(tree.symbol)
           } else {
             ctx.bb.emit(THIS(ctx.clazz.symbol), tree.pos)
-            if (tree.symbol == definitions.ArrayClass)
-              generatedType = REFERENCE(definitions.BoxedAnyArrayClass)
-            else
-              generatedType = REFERENCE(ctx.clazz.symbol)
+            generatedType = REFERENCE(
+              if (tree.symbol == ArrayClass) ObjectClass else ctx.clazz.symbol
+            )
           }
           ctx
 
@@ -836,7 +802,7 @@ abstract class GenICode extends SubComponent  {
             log("LOAD_MODULE from Select(<emptypackage>): " + tree.symbol);
           }
           assert(!tree.symbol.isPackageClass, "Cannot use package as value: " + tree)
-          ctx.bb.emit(LOAD_MODULE(tree.symbol), tree.pos)
+          genLoadModule(ctx, tree.symbol, tree.pos)
           ctx
 
         case Select(qualifier, selector) =>
@@ -845,9 +811,9 @@ abstract class GenICode extends SubComponent  {
 
           if (sym.isModule) {
             if (settings.debug.value)
-              log("LOAD_MODULE from Select(qualifier, selector): " + sym);
+              log("LOAD_MODULE from Select(qualifier, selector): " + sym)
             assert(!tree.symbol.isPackageClass, "Cannot use package as value: " + tree)
-            ctx.bb.emit(LOAD_MODULE(sym), tree.pos);
+            genLoadModule(ctx, sym, tree.pos)
             ctx
           } else if (sym.isStaticMember) {
             ctx.bb.emit(LOAD_FIELD(sym, true), tree.pos)
@@ -859,22 +825,22 @@ abstract class GenICode extends SubComponent  {
           }
 
         case Ident(name) =>
-          if (!tree.symbol.isPackage) {
-            if (tree.symbol.isModule) {
+          val sym = tree.symbol
+          if (!sym.isPackage) {
+            if (sym.isModule) {
               if (settings.debug.value)
-                log("LOAD_MODULE from Ident(name): " + tree.symbol);
-              assert(!tree.symbol.isPackageClass, "Cannot use package as value: " + tree)
-              ctx.bb.emit(LOAD_MODULE(tree.symbol), tree.pos)
-              generatedType = toTypeKind(tree.symbol.info)
+                log("LOAD_MODULE from Ident(name): " + sym)
+              assert(!sym.isPackageClass, "Cannot use package as value: " + tree)
+              genLoadModule(ctx, sym, tree.pos)
+              generatedType = toTypeKind(sym.info)
             } else {
               try {
-                val Some(l) = ctx.method.lookupLocal(tree.symbol)
+                val Some(l) = ctx.method.lookupLocal(sym)
                 ctx.bb.emit(LOAD_LOCAL(l), tree.pos)
                 generatedType = l.kind
               } catch {
                 case ex: MatchError => 
-                  throw new Error("symbol " + tree.symbol +
-                                  " does not exist in " + ctx.method)
+                  abort("symbol " + sym + " does not exist in " + ctx.method)
               }
             }
           }
@@ -904,10 +870,13 @@ abstract class GenICode extends SubComponent  {
           ctx1.exitScope
           ctx1
 
+        case Typed(Super(_, _), _) =>
+          genLoad(This(ctx.clazz.symbol), ctx, expectedType)
+
         case Typed(expr, _) =>
           genLoad(expr, ctx, expectedType)
 
-        case Assign(_, _) => 
+        case Assign(_, _) =>
           generatedType = UNIT
           genStat(tree, ctx)
 
@@ -941,31 +910,26 @@ abstract class GenICode extends SubComponent  {
           var tags: List[Int] = Nil
           var default: BasicBlock = afterCtx.bb
 
-          for (caze <- cases) caze match {
-            case CaseDef(Literal(value), EmptyTree, body) =>
-              tags = value.intValue :: tags
-              val tmpCtx = ctx1.newBlock
-              targets = tmpCtx.bb :: targets
-
-              caseCtx = genLoad(body, tmpCtx , generatedType)
-              caseCtx.bb.emit(JUMP(afterCtx.bb), caze.pos)
-              caseCtx.bb.close
-
-            case CaseDef(Ident(nme.WILDCARD), EmptyTree, body) =>
-              val tmpCtx = ctx1.newBlock
-              default = tmpCtx.bb
-
-              caseCtx = genLoad(body, tmpCtx , generatedType)
-              caseCtx.bb.emit(JUMP(afterCtx.bb), caze.pos)
-              caseCtx.bb.close
+          for (caze @ CaseDef(pat, guard, body) <- cases) {
+            assert(guard == EmptyTree)
+            val tmpCtx = ctx1.newBlock
+            pat match {
+              case Literal(value) =>
+                tags = value.intValue :: tags
+                targets = tmpCtx.bb :: targets                
+              case Ident(nme.WILDCARD) =>
+                default = tmpCtx.bb
+              case _ =>
+                abort("Invalid case statement in switch-like pattern match: " +
+                      tree + " at: " + (tree.pos))
+            }
 
-            case _ =>
-              abort("Invalid case statement in switch-like pattern match: " +
-                    tree + " at: " + (tree.pos))
+            caseCtx = genLoad(body, tmpCtx, generatedType)
+            caseCtx.bb.emitOnly(JUMP(afterCtx.bb) setPos caze.pos)
           }
-          ctx1.bb.emit(SWITCH(tags.reverse map (x => List(x)),
-                             (default :: targets).reverse), tree.pos)
-          ctx1.bb.close
+          ctx1.bb.emitOnly(
+            SWITCH(tags.reverse map (x => List(x)), (default :: targets).reverse) setPos tree.pos
+          )
           afterCtx
 
         case EmptyTree => 
@@ -974,13 +938,12 @@ abstract class GenICode extends SubComponent  {
           ctx
 
         case _ =>
-          abort("Unexpected tree in genLoad: " + tree + " at: " +
-                (tree.pos))
+          abort("Unexpected tree in genLoad: " + tree + " at: " + tree.pos)
       }
 
       // emit conversion
       if (generatedType != expectedType)
-        adapt(generatedType, expectedType, resCtx, tree.pos);
+        adapt(generatedType, expectedType, resCtx, tree.pos)
 
       resCtx
     }
@@ -1045,9 +1008,9 @@ abstract class GenICode extends SubComponent  {
             val Some(l) = ctx.method.lookupLocal(param.head)
             ctx1 = genLoad(arg.head, ctx1, l.kind)
             if (param.head.name == nme.THIS)
-              STORE_THIS(toTypeKind(ctx1.clazz.symbol.tpe)).setPos(arg.head.pos) +: stores
+              STORE_THIS(toTypeKind(ctx1.clazz.symbol.tpe)).setPos(arg.head.pos) +=: stores
             else {
-              STORE_LOCAL(l).setPos(arg.head.pos) +: stores
+              STORE_LOCAL(l).setPos(arg.head.pos) +=: stores
             }
         }
         arg = arg.tail
@@ -1071,6 +1034,13 @@ abstract class GenICode extends SubComponent  {
       ctx1
     }
 
+    private def genLoadModule(ctx: Context, sym: Symbol, pos: Position) {
+      if (definitions.primitiveCompanions(sym))
+        ctx.bb.emit(LOAD_MODULE(definitions.getModule("scala.runtime." + sym.name)), pos)
+      else
+        ctx.bb.emit(LOAD_MODULE(sym), pos)
+    }
+
     def genConversion(from: TypeKind, to: TypeKind, ctx: Context, cast: Boolean) = {
       if (cast) 
         ctx.bb.emit(CALL_PRIMITIVE(Conversion(from, to)))
@@ -1123,7 +1093,7 @@ abstract class GenICode extends SubComponent  {
      */
     def genCoercion(tree: Tree, ctx: Context, code: Int) = {
       import scalaPrimitives._
-      code match {
+      (code: @switch) match {
         case B2B => ()
         case B2C => ctx.bb.emit(CALL_PRIMITIVE(Conversion(BYTE, CHAR)), tree.pos)
         case B2S => ctx.bb.emit(CALL_PRIMITIVE(Conversion(BYTE, SHORT)), tree.pos)
@@ -1208,6 +1178,19 @@ abstract class GenICode extends SubComponent  {
 
       ctx1
     }
+    
+    /** Generate the scala ## method.
+     */
+    def genScalaHash(tree: Tree, ctx: Context): Context = {
+      val hashMethod = {
+        ctx.bb.emit(LOAD_MODULE(ScalaRunTimeModule))
+        getMember(ScalaRunTimeModule, "hash")
+      }
+      
+      val ctx1 = genLoad(tree, ctx, ANY_REF_CLASS)
+      ctx1.bb.emit(CALL_METHOD(hashMethod, Static(false)))
+      ctx1
+    }
 
     /**
      * Returns a list of trees that each should be concatenated, from
@@ -1225,6 +1208,12 @@ abstract class GenICode extends SubComponent  {
         List(tree)
     }
 
+    /** Some useful equality helpers.
+     */
+    def isNull(t: Tree) = cond(t) { case Literal(Constant(null)) => true }
+    
+    /* If l or r is constant null, returns the other ; otherwise null */
+    def ifOneIsNull(l: Tree, r: Tree) = if (isNull(l)) r else if (isNull(r)) l else null
 
     /**
      * Traverse the tree and store label stubs in the context. This is
@@ -1254,7 +1243,7 @@ abstract class GenICode extends SubComponent  {
             super.traverse(tree)
         }
       } traverse(tree);
-
+     
     /**
      * Generate code for conditional expressions. The two basic blocks
      * represent the continuation in case of success/failure of the
@@ -1265,25 +1254,7 @@ abstract class GenICode extends SubComponent  {
                         thenCtx: Context,
                         elseCtx: Context): Unit =
     {
-      def genComparisonOp(l: Tree, r: Tree, code: Int) {
-        // special-case reference (in)equality test for null
-        if (code == scalaPrimitives.ID || code == scalaPrimitives.NI) {
-          val expr: Tree = (l, r) match {
-            case (Literal(Constant(null)), expr) => expr
-            case (expr, Literal(Constant(null))) => expr
-            case _ => null
-          }
-          if (expr ne null) {
-            val ctx1 = genLoad(expr, ctx, ANY_REF_CLASS)
-            if (code == scalaPrimitives.ID)
-              ctx1.bb.emit(CZJUMP(thenCtx.bb, elseCtx.bb, EQ, ANY_REF_CLASS))
-            else
-              ctx1.bb.emit(CZJUMP(elseCtx.bb, thenCtx.bb, EQ, ANY_REF_CLASS))
-            ctx1.bb.close
-            return
-          }
-        }
-
+      def genComparisonOp(l: Tree, r: Tree, code: Int) {          
         val op: TestOp = code match {
           case scalaPrimitives.LT => LT
           case scalaPrimitives.LE => LE
@@ -1295,70 +1266,74 @@ abstract class GenICode extends SubComponent  {
           case _ => abort("Unknown comparison primitive: " + code)
         }
 
-        val kind = getMaxType(l.tpe :: r.tpe :: Nil)
-        var ctx1 = genLoad(l, ctx, kind);
-        ctx1 = genLoad(r, ctx1, kind);
-        ctx1.bb.emit(CJUMP(thenCtx.bb, elseCtx.bb, op, kind), r.pos)
-        ctx1.bb.close
+        // special-case reference (in)equality test for null (null eq x, x eq null)
+        lazy val nonNullSide = ifOneIsNull(l, r)
+        if (isReferenceEqualityOp(code) && nonNullSide != null) {
+          val ctx1 = genLoad(nonNullSide, ctx, ANY_REF_CLASS)
+          ctx1.bb.emitOnly(
+            CZJUMP(thenCtx.bb, elseCtx.bb, op, ANY_REF_CLASS)
+          )
+        }
+        else {
+          val kind = getMaxType(l.tpe :: r.tpe :: Nil)
+          var ctx1 = genLoad(l, ctx, kind) 
+          ctx1 = genLoad(r, ctx1, kind)
+          
+          ctx1.bb.emitOnly(
+            CJUMP(thenCtx.bb, elseCtx.bb, op, kind) setPos r.pos
+          )
+        }
       }
 
       if (settings.debug.value)
         log("Entering genCond with tree: " + tree);
-
+      
+      // the default emission
+      def default = {
+        val ctx1 = genLoad(tree, ctx, BOOL)
+        ctx1.bb.emitOnly(CZJUMP(thenCtx.bb, elseCtx.bb, NE, BOOL) setPos tree.pos)
+      }
+      
       tree match {
-        case Apply(fun, args)
-          if isPrimitive(fun.symbol) =>
-            val code = scalaPrimitives.getPrimitive(fun.symbol)
+        // The comparison symbol is in ScalaPrimitives's "primitives" map
+        case Apply(fun, args) if isPrimitive(fun.symbol) =>
+          import scalaPrimitives.{ ZNOT, ZAND, ZOR, EQ, getPrimitive }
+          
+          // lhs and rhs of test
+          lazy val Select(lhs, _) = fun
+          lazy val rhs = args.head
 
-            if (code == scalaPrimitives.ZNOT) {
-              val Select(leftArg, _) = fun
-              genCond(leftArg, ctx, elseCtx, thenCtx)
-            }
-            else if ((code == scalaPrimitives.EQ || code == scalaPrimitives.NE)) {
-              val Select(leftArg, _) = fun;
-              if (toTypeKind(leftArg.tpe).isReferenceType) {
-                if (code == scalaPrimitives.EQ)
-                  genEqEqPrimitive(leftArg, args.head, ctx, thenCtx, elseCtx)
-                else
-                  genEqEqPrimitive(leftArg, args.head, ctx, elseCtx, thenCtx)
+          def genZandOrZor(and: Boolean) = {
+            val ctxInterm = ctx.newBlock
+            
+            if (and) genCond(lhs, ctx, ctxInterm, elseCtx)
+            else genCond(lhs, ctx, thenCtx, ctxInterm)
+            
+            genCond(rhs, ctxInterm, thenCtx, elseCtx)
+          }
+          def genRefEq(isEq: Boolean) = {
+            val f = genEqEqPrimitive(lhs, rhs, ctx) _
+            if (isEq) f(thenCtx, elseCtx)
+            else f(elseCtx, thenCtx)
+          }
+          
+          getPrimitive(fun.symbol) match {
+            case ZNOT   => genCond(lhs, ctx, elseCtx, thenCtx)
+            case ZAND   => genZandOrZor(and = true)
+            case ZOR    => genZandOrZor(and = false)
+            case code   =>
+              // x == y where LHS is reference type  
+              if (isUniversalEqualityOp(code) && toTypeKind(lhs.tpe).isReferenceType) {
+                if (code == EQ) genRefEq(isEq = true)
+                else genRefEq(isEq = false)
               }
+              else if (isComparisonOp(code))
+                genComparisonOp(lhs, rhs, code)
               else
-                genComparisonOp(leftArg, args.head, code);
-            }
-            else if (scalaPrimitives.isComparisonOp(code)) {
-              val Select(leftArg, _) = fun
-              genComparisonOp(leftArg, args.head, code)
-            }
-            else {
-              code match {
-                case scalaPrimitives.ZAND =>
-                  val Select(leftArg, _) = fun
-
-                  val ctxInterm = ctx.newBlock
-                  genCond(leftArg, ctx, ctxInterm, elseCtx)
-                  genCond(args.head, ctxInterm, thenCtx, elseCtx)
-
-                case scalaPrimitives.ZOR =>
-                  val Select(leftArg, _) = fun
-
-                  val ctxInterm = ctx.newBlock
-                  genCond(leftArg, ctx, thenCtx, ctxInterm)
-                  genCond(args.head, ctxInterm, thenCtx, elseCtx)
-
-                case _ =>
-                  // TODO (maybe): deal with the equals case here
-                  // Current semantics: rich equals (from runtime.Comparator) only when == is used
-                  // See genEqEqPrimitive for implementation
-                  var ctx1 = genLoad(tree, ctx, BOOL)
-                  ctx1.bb.emit(CZJUMP(thenCtx.bb, elseCtx.bb, NE, BOOL), tree.pos)
-                  ctx1.bb.close
-              }
-            }
+                default
+          }
 
-        case _ =>
-          var ctx1 = genLoad(tree, ctx, BOOL)
-          ctx1.bb.emit(CZJUMP(thenCtx.bb, elseCtx.bb, NE, BOOL), tree.pos)
-          ctx1.bb.close
+        case _ => default
       }
     }
 
@@ -1372,106 +1347,100 @@ abstract class GenICode extends SubComponent  {
      * @param thenCtx target context if the comparison yields true
      * @param elseCtx target context if the comparison yields false
      */
-    def genEqEqPrimitive(l: Tree, r: Tree, ctx: Context,
-                         thenCtx: Context, elseCtx: Context): Unit =
-    {
-
+    def genEqEqPrimitive(l: Tree, r: Tree, ctx: Context)(thenCtx: Context, elseCtx: Context): Unit = {
+      
       def eqEqTempName: Name = "eqEqTemp$"
 
       def getTempLocal: Local = ctx.method.lookupLocal(eqEqTempName) match {
         case Some(local) => local
         case None =>
           val local = ctx.makeLocal(l.pos, definitions.AnyRefClass.typeConstructor, eqEqTempName.toString)
-          assert(l.pos.source.get == unit.source)
-          assert(r.pos.source.get == unit.source)
-          local.start = (l.pos).line.get
-          local.end   = (r.pos).line.get
+          //assert(!l.pos.source.isEmpty, "bad position, unit = "+unit+", tree = "+l+", pos = "+l.pos.source)
+          // Note - I commented these out because they were crashing the test case in ticket #2426
+          // (and I have also had to comment them out at various times while working on equality.)
+          // I don't know what purpose they are serving but it would be nice if they didn't have to
+          // crash the compiler.
+          // assert(l.pos.source == unit.source)
+          // assert(r.pos.source == unit.source)
+          local.start = (l.pos).line
+          local.end   = (r.pos).line
           local
       }
-      
+
       /** True if the equality comparison is between values that require the use of the rich equality
         * comparator (scala.runtime.Comparator.equals). This is the case when either side of the
         * comparison might have a run-time type subtype of java.lang.Number or java.lang.Character.
         * When it is statically known that both sides are equal and subtypes of Number of Character,
         * not using the rich equality is possible (their own equals method will do ok.)*/
       def mustUseAnyComparator: Boolean = {
-        def isBoxed(sym: Symbol): Boolean =
-          if (forCLDC) {
-            (sym isNonBottomSubClass definitions.ByteClass) ||
-            (sym isNonBottomSubClass definitions.ShortClass) ||
-            (sym isNonBottomSubClass definitions.CharClass) ||
-            (sym isNonBottomSubClass definitions.IntClass) ||
-            (sym isNonBottomSubClass definitions.LongClass)
-          }
-          else ((sym isNonBottomSubClass definitions.BoxedNumberClass) ||
-            (!forMSIL && (sym isNonBottomSubClass definitions.BoxedCharacterClass)))
-
-        val lsym = l.tpe.typeSymbol
-        val rsym = r.tpe.typeSymbol
-        (lsym == definitions.ObjectClass) ||
-        (rsym == definitions.ObjectClass) ||
-        (lsym != rsym) && (isBoxed(lsym) || isBoxed(rsym))
+        def areSameFinals = l.tpe.isFinalType && r.tpe.isFinalType && (l.tpe =:= r.tpe)
+        !areSameFinals && isMaybeBoxed(l.tpe.typeSymbol) && isMaybeBoxed(r.tpe.typeSymbol)
       }
 
       if (mustUseAnyComparator) {
+        // when -optimise is on we call the @inline-version of equals, found in ScalaRunTime
+        val equalsMethod =
+          if (!settings.XO.value) {
+            def default = platform.externalEquals
+            platform match {
+              case x: JavaPlatform =>
+                import x._
+                  if (l.tpe <:< BoxedNumberClass.tpe) {
+                    if (r.tpe <:< BoxedNumberClass.tpe) externalEqualsNumNum
+                    else if (r.tpe <:< BoxedCharacterClass.tpe) externalEqualsNumChar
+                    else externalEqualsNumObject
+                  }
+                  else default
+                
+              case _ => default
+            }
+          }
+          else {
+            ctx.bb.emit(LOAD_MODULE(ScalaRunTimeModule))
+            getMember(ScalaRunTimeModule, nme.inlinedEquals)
+          }
 
         val ctx1 = genLoad(l, ctx, ANY_REF_CLASS)
         val ctx2 = genLoad(r, ctx1, ANY_REF_CLASS)
-        ctx2.bb.emit(CALL_METHOD(BoxesRunTime_equals, Static(false)))
+        ctx2.bb.emit(CALL_METHOD(equalsMethod, if (settings.XO.value) Dynamic else Static(false)))
         ctx2.bb.emit(CZJUMP(thenCtx.bb, elseCtx.bb, NE, BOOL))
         ctx2.bb.close
-
       }
       else {
-
-        (l, r) match {
+        if (isNull(l))
           // null == expr -> expr eq null
-          case (Literal(Constant(null)), expr) =>
-            val ctx1 = genLoad(expr, ctx, ANY_REF_CLASS)
-            ctx1.bb.emit(CZJUMP(thenCtx.bb, elseCtx.bb, EQ, ANY_REF_CLASS))
-            ctx1.bb.close
-
-          // expr == null -> if(expr eq null) true else expr.equals(null)
-          case (expr, Literal(Constant(null))) =>
-            val eqEqTempLocal = getTempLocal
-            var ctx1 = genLoad(expr, ctx, ANY_REF_CLASS)
-            ctx1.bb.emit(DUP(ANY_REF_CLASS))
-            ctx1.bb.emit(STORE_LOCAL(eqEqTempLocal), l.pos)
-            val nonNullCtx = ctx1.newBlock
-            ctx1.bb.emit(CZJUMP(thenCtx.bb, nonNullCtx.bb, EQ, ANY_REF_CLASS))
-            ctx1.bb.close
-
-            nonNullCtx.bb.emit(LOAD_LOCAL(eqEqTempLocal), l.pos)
-            nonNullCtx.bb.emit(CONSTANT(Constant(null)), r.pos)
-            nonNullCtx.bb.emit(CALL_METHOD(definitions.Object_equals, Dynamic))
-            nonNullCtx.bb.emit(CZJUMP(thenCtx.bb, elseCtx.bb, NE, BOOL))
-            nonNullCtx.bb.close
-
+          genLoad(r, ctx, ANY_REF_CLASS).bb emitOnly CZJUMP(thenCtx.bb, elseCtx.bb, EQ, ANY_REF_CLASS)
+        else if (isNull(r)) {
+          // expr == null -> expr eq null
+          genLoad(l, ctx, ANY_REF_CLASS).bb emitOnly CZJUMP(thenCtx.bb, elseCtx.bb, EQ, ANY_REF_CLASS)
+        } else {
+          val eqEqTempLocal = getTempLocal
+          var ctx1 = genLoad(l, ctx, ANY_REF_CLASS)
+          
+          // dicey refactor section
+          lazy val nonNullCtx = ctx1.newBlock
+          
           // l == r -> if (l eq null) r eq null else l.equals(r)
-          case _ =>
-            val eqEqTempLocal = getTempLocal
-            var ctx1 = genLoad(l, ctx, ANY_REF_CLASS)
-            ctx1 = genLoad(r, ctx1, ANY_REF_CLASS)
-            val nullCtx = ctx1.newBlock
-            val nonNullCtx = ctx1.newBlock
-            ctx1.bb.emit(STORE_LOCAL(eqEqTempLocal), l.pos)
-            ctx1.bb.emit(DUP(ANY_REF_CLASS))
-            ctx1.bb.emit(CZJUMP(nullCtx.bb, nonNullCtx.bb, EQ, ANY_REF_CLASS))
-            ctx1.bb.close
-
-            nullCtx.bb.emit(DROP(ANY_REF_CLASS), l.pos) // type of AnyRef
-            nullCtx.bb.emit(LOAD_LOCAL(eqEqTempLocal))
-            nullCtx.bb.emit(CZJUMP(thenCtx.bb, elseCtx.bb, EQ, ANY_REF_CLASS))
-            nullCtx.bb.close
-
-            nonNullCtx.bb.emit(LOAD_LOCAL(eqEqTempLocal), l.pos)
-            nonNullCtx.bb.emit(CALL_METHOD(definitions.Object_equals, Dynamic))
-            nonNullCtx.bb.emit(CZJUMP(thenCtx.bb, elseCtx.bb, NE, BOOL))
-            nonNullCtx.bb.close
+          ctx1 = genLoad(r, ctx1, ANY_REF_CLASS)
+          val nullCtx = ctx1.newBlock
+          
+          ctx1.bb.emitOnly(
+            STORE_LOCAL(eqEqTempLocal) setPos l.pos,
+            DUP(ANY_REF_CLASS),
+            CZJUMP(nullCtx.bb, nonNullCtx.bb, EQ, ANY_REF_CLASS)
+          )          
+          nullCtx.bb.emitOnly(
+            DROP(ANY_REF_CLASS) setPos l.pos, // type of AnyRef
+            LOAD_LOCAL(eqEqTempLocal),
+            CZJUMP(thenCtx.bb, elseCtx.bb, EQ, ANY_REF_CLASS)
+          )
+          nonNullCtx.bb.emitOnly(
+            LOAD_LOCAL(eqEqTempLocal) setPos l.pos,
+            CALL_METHOD(Object_equals, Dynamic),
+            CZJUMP(thenCtx.bb, elseCtx.bb, NE, BOOL)
+          )
         }
-
       }
-
     }
 
     /**
@@ -1483,9 +1452,15 @@ abstract class GenICode extends SubComponent  {
         assert(ctx.clazz.symbol eq cls,
                "Classes are not the same: " + ctx.clazz.symbol + ", " + cls)
 
-      for (f <- cls.info.decls.elements)
-        if (!f.isMethod && f.isTerm) 
-          ctx.clazz.addField(new IField(f));
+      /** Non-method term members are fields, except for module members. Module
+       *  members can only happen on .NET (no flatten) for inner traits. There,
+       *  a module symbol is generated (transformInfo in mixin) which is used
+       *  as owner for the members of the implementation class (so that the
+       *  backend emits them as static).
+       *  No code is needed for this module symbol.
+       */
+      for (f <- cls.info.decls ; if !f.isMethod && f.isTerm && !f.isModule)
+        ctx.clazz addField new IField(f)
     }
 
     /**
@@ -1535,19 +1510,19 @@ abstract class GenICode extends SubComponent  {
 
       def prune0(block: BasicBlock): Unit = {
         val optCont = block.lastInstruction match {
-          case JUMP(b) if (b != block) => Some(b);
+          case JUMP(b) if (b != block) => Some(b)
           case _ => None
         }
-        if (block.size == 1 && optCont != None) {
+        if (block.size == 1 && optCont.isDefined) {
           val Some(cont) = optCont;
           val pred = block.predecessors;
           log("Preds: " + pred + " of " + block + " (" + optCont + ")");
           pred foreach { p =>
+            changed = true
             p.lastInstruction match {
-              case CJUMP(succ, fail, cond, kind) =>
+              case CJUMP(succ, fail, cond, kind) if (succ == block || fail == block) =>
                 if (settings.debug.value)
                   log("Pruning empty if branch.");
-                changed = true
                 p.replaceInstruction(p.lastInstruction,
                                      if (block == succ)
                                        if (block == fail)
@@ -1559,10 +1534,9 @@ abstract class GenICode extends SubComponent  {
                                      else
                                        abort("Could not find block in preds: " + method + " " + block + " " + pred + " " + p))
 
-              case CZJUMP(succ, fail, cond, kind) =>
+              case CZJUMP(succ, fail, cond, kind) if (succ == block || fail == block) =>
                 if (settings.debug.value)
                   log("Pruning empty ifz branch.");
-                changed = true
                 p.replaceInstruction(p.lastInstruction,
                                      if (block == succ)
                                        if (block == fail)
@@ -1574,20 +1548,22 @@ abstract class GenICode extends SubComponent  {
                                      else
                                        abort("Could not find block in preds"))
 
-              case JUMP(b) =>
+              case JUMP(b) if (b == block) =>
                 if (settings.debug.value)
                   log("Pruning empty JMP branch.");
-                changed = true
                 val replaced = p.replaceInstruction(p.lastInstruction, JUMP(cont))
                 if (settings.debug.value)
                   assert(replaced, "Didn't find p.lastInstruction")
 
-              case SWITCH(tags, labels) =>
+              case SWITCH(tags, labels) if (labels contains block) =>
                 if (settings.debug.value)
                   log("Pruning empty SWITCH branch.");
-                changed = true
                 p.replaceInstruction(p.lastInstruction,
                                      SWITCH(tags, labels map (l => if (l == block) cont else l)))
+
+              // the last instr of the predecessor `p` is not a jump to the block `block`.
+              // this happens when `block` is part of an exception handler covering `b`.
+              case _ => ()
             }
           }
           if (changed) {
@@ -1606,7 +1582,7 @@ abstract class GenICode extends SubComponent  {
       do {
         changed = false
         n += 1
-        method.code traverse prune0
+        method.code.blocks foreach prune0
       } while (changed)
 
       if (settings.debug.value)
@@ -1640,7 +1616,7 @@ abstract class GenICode extends SubComponent  {
      *  to delay it any more: they will be used at some point.
      */
     class DuplicateLabels(boundLabels: collection.Set[Symbol]) extends Transformer {
-      val labels: Map[Symbol, Symbol] = new HashMap
+      val labels: mutable.Map[Symbol, Symbol] = new HashMap
       var method: Symbol = _
       var ctx: Context = _
       
@@ -1659,8 +1635,8 @@ abstract class GenICode extends SubComponent  {
               sym.setInfo(oldLabel.tpe)
               labels(oldLabel) = sym
             }
-            val tree = copy.Apply(t, transform(fun), transformTrees(args))
-            tree.symbol = labels(t.symbol)
+            val tree = Apply(global.gen.mkAttributedRef(labels(t.symbol)), transformTrees(args)).setPos(t.pos)
+            tree.tpe = t.tpe
             tree
             
           case t @ LabelDef(name, params, rhs) =>
@@ -1671,7 +1647,7 @@ abstract class GenICode extends SubComponent  {
               sym.setInfo(oldLabel.tpe)
               labels(oldLabel) = sym
             }            
-            val tree = copy.LabelDef(t, name1, params, transform(rhs))
+            val tree = treeCopy.LabelDef(t, name1, params, transform(rhs))
             tree.symbol = labels(t.symbol)
             
             ctx.labels += (tree.symbol -> (new Label(tree.symbol) setParams(params map (_.symbol))));
@@ -1688,15 +1664,18 @@ abstract class GenICode extends SubComponent  {
 
     abstract class Cleanup;
     case class MonitorRelease(m: Local) extends Cleanup {
+      override def hashCode = m.hashCode
       override def equals(other: Any) = m == other;
     }
     case class Finalizer(f: Tree) extends Cleanup {
+      override def hashCode = f.hashCode
       override def equals(other: Any) = f == other;
     }
 
-    def duplicateFinalizer(ctx: Context, finalizer: Tree) =
-      (new DuplicateLabels(ctx.labels.keySet))(ctx, finalizer)
-
+    def duplicateFinalizer(boundLabels: collection.Set[Symbol], targetCtx: Context, finalizer: Tree) =  {
+      (new DuplicateLabels(boundLabels))(targetCtx, finalizer)
+    }
+    
     /**
      * The Context class keeps information relative to the current state
      * in code generation
@@ -1727,8 +1706,8 @@ abstract class GenICode extends SubComponent  {
       /** The current monitors or finalizers, to be cleaned up upon `return'. */
       var cleanups: List[Cleanup] = Nil
 
-      /** The current exception handler, when we generate code for one. */
-      var currentExceptionHandler: Option[ExceptionHandler] = None
+      /** The exception handlers we are currently generating code for */
+      var currentExceptionHandlers: List[ExceptionHandler] = Nil
 
       /** The current local variable scope. */
       var scope: Scope = EmptyScope
@@ -1759,7 +1738,7 @@ abstract class GenICode extends SubComponent  {
         this.handlers = other.handlers
         this.handlerCount = other.handlerCount
         this.cleanups = other.cleanups
-        this.currentExceptionHandler = other.currentExceptionHandler
+        this.currentExceptionHandlers = other.currentExceptionHandlers
         this.scope = other.scope
       }
 
@@ -1828,10 +1807,7 @@ abstract class GenICode extends SubComponent  {
       def newBlock: Context = {
         val block = method.code.newBlock
         handlers foreach (h => h addCoveredBlock block)
-        currentExceptionHandler match {
-          case Some(e) => e.addBlock(block)
-          case None    => ()
-        }
+        currentExceptionHandlers foreach (h => h.addBlock(block))
         block.varsInScope = new HashSet()
         block.varsInScope ++= scope.varsInScope
         new Context(this) setBasicBlock block
@@ -1878,12 +1854,16 @@ abstract class GenICode extends SubComponent  {
        * exception handler.
        */
       def enterHandler(exh: ExceptionHandler): Context = {
-        currentExceptionHandler = Some(exh)
+        currentExceptionHandlers = exh :: currentExceptionHandlers
         val ctx = newBlock
         exh.setStartBlock(ctx.bb)
         ctx
       }
 
+      def endHandler() {
+        currentExceptionHandlers = currentExceptionHandlers.tail
+      }
+
       /** Remove the given handler from the list of active exception handlers. */
       def removeHandler(exh: ExceptionHandler): Unit = {
         assert(handlerCount > 0 && handlers.head == exh,
@@ -1917,7 +1897,7 @@ abstract class GenICode extends SubComponent  {
        *
        * <code> ctx.Try( ctx => { 
        *   ctx.bb.emit(...) // protected block
-       * }, (definitions.ThrowableClass,
+       * }, (ThrowableClass,
        *   ctx => { 
        *     ctx.bb.emit(...); // exception handler
        *   }), (AnotherExceptionClass,
@@ -1927,7 +1907,7 @@ abstract class GenICode extends SubComponent  {
       def Try(body: Context => Context, 
               handlers: List[(Symbol, TypeKind, (Context => Context))],
               finalizer: Tree,
-              tree: Tree) = {
+              tree: Tree) = if (forMSIL) TryMsil(body, handlers, finalizer, tree) else {
 
         val outerCtx = this.dup       // context for generating exception handlers, covered by finalizer
         val finalizerCtx = this.dup   // context for generating finalizer handler
@@ -1935,7 +1915,11 @@ abstract class GenICode extends SubComponent  {
         var tmp: Local = null
         val kind = toTypeKind(tree.tpe)
         val guardResult = kind != UNIT && mayCleanStack(finalizer)
-        
+        // we need to save bound labels before any code generation is performed on
+        // the current context (otherwise, any new labels in the finalizer that need to
+        // be duplicated would be incorrectly considered bound -- see #2850).
+        val boundLabels: collection.Set[Symbol] = Set.empty ++ labels.keySet
+
         if (guardResult) {
           tmp = this.makeLocal(tree.pos, tree.tpe, "tmp")
         }
@@ -1947,11 +1931,11 @@ abstract class GenICode extends SubComponent  {
 
           if (guardResult) {
             ctx1.bb.emit(STORE_LOCAL(tmp))
-            val ctx2 = genLoad(duplicateFinalizer(ctx1, finalizer), ctx1, UNIT)
+            val ctx2 = genLoad(duplicateFinalizer(boundLabels, ctx1, finalizer), ctx1, UNIT)
             ctx2.bb.emit(LOAD_LOCAL(tmp))
             ctx2
           } else
-            genLoad(duplicateFinalizer(ctx1, finalizer), ctx1, UNIT)
+            genLoad(duplicateFinalizer(boundLabels, ctx1, finalizer), ctx1, UNIT)
         } else ctx
 
 
@@ -1959,7 +1943,7 @@ abstract class GenICode extends SubComponent  {
           val exh = outerCtx.newHandler(NoSymbol, toTypeKind(finalizer.tpe)) // finalizer covers exception handlers
           this.addActiveHandler(exh)  // .. and body aswell 
           val ctx = finalizerCtx.enterHandler(exh)
-          val exception = ctx.makeLocal(finalizer.pos, definitions.ThrowableClass.tpe, "exc")
+          val exception = ctx.makeLocal(finalizer.pos, ThrowableClass.tpe, "exc")
           if (settings.Xdce.value) ctx.bb.emit(LOAD_EXCEPTION())
           ctx.bb.emit(STORE_LOCAL(exception));
           val ctx1 = genLoad(finalizer, ctx, UNIT);
@@ -1967,6 +1951,7 @@ abstract class GenICode extends SubComponent  {
           ctx1.bb.emit(THROW());
           ctx1.bb.enterIgnoreMode;
           ctx1.bb.close
+          finalizerCtx.endHandler()
           exh
         }) else None
         
@@ -1979,6 +1964,7 @@ abstract class GenICode extends SubComponent  {
             val ctx2 = emitFinalizer(ctx1)
             ctx2.bb.emit(JUMP(afterCtx.bb))
             ctx2.bb.close
+            outerCtx.endHandler()
             exh
           }
         val bodyCtx = this.newBlock
@@ -1991,11 +1977,71 @@ abstract class GenICode extends SubComponent  {
         outerCtx.bb.emit(JUMP(bodyCtx.bb))
         outerCtx.bb.close
 
-//        exhs.reverse foreach finalCtx.removeHandler
-//        if (finalizer != EmptyTree) {
-//          finalCtx.removeFinalizer(finalizer)
-//        }
+        finalCtx.bb.emit(JUMP(afterCtx.bb))
+        finalCtx.bb.close
+
+        afterCtx
+      }
+
+
+      /** try-catch-finally blocks are actually simpler to emit in MSIL, because there
+       *  is support for `finally` in bytecode.
+       *
+       *  A
+       *    try { .. } catch { .. } finally { .. }
+       *  block is de-sugared into
+       *    try { try { ..} catch { .. } } finally { .. }
+       *
+       *  In ICode `finally` block is represented exactly the same as an exception handler,
+       *  but with `NoSymbol` as the exception class. The covered blocks are all blocks of
+       *  the `try { .. } catch { .. }`.
+       *
+       *  Also, TryMsil does not enter any Finalizers into the `cleanups', because the
+       *  CLI takes care of running the finalizer when seeing a `leave' statement inside
+       *  a try / catch.
+       */
+      def TryMsil(body: Context => Context,
+                  handlers: List[(Symbol, TypeKind, (Context => Context))],
+                  finalizer: Tree,
+                  tree: Tree) = {
+
+        val outerCtx = this.dup       // context for generating exception handlers, covered by finalizer
+        val finalizerCtx = this.dup   // context for generating finalizer handler
+        val afterCtx = outerCtx.newBlock
 
+        if (finalizer != EmptyTree) {
+          // finalizer is covers try and all catch blocks, i.e.
+          //   try { try { .. } catch { ..} } finally { .. }
+          val exh = outerCtx.newHandler(NoSymbol, UNIT)
+          this.addActiveHandler(exh)
+          val ctx = finalizerCtx.enterHandler(exh)
+          if (settings.Xdce.value) ctx.bb.emit(LOAD_EXCEPTION())
+          val ctx1 = genLoad(finalizer, ctx, UNIT)
+          // need jump for the ICode to be valid. MSIL backend will emit `Endfinally` instead.
+          ctx1.bb.emit(JUMP(afterCtx.bb))
+          ctx1.bb.close
+          finalizerCtx.endHandler()
+        }
+
+        for (handler <- handlers) {
+          val exh = this.newHandler(handler._1, handler._2)
+          var ctx1 = outerCtx.enterHandler(exh)
+          if (settings.Xdce.value) ctx1.bb.emit(LOAD_EXCEPTION())
+          ctx1 = handler._3(ctx1)
+          // msil backend will emit `Leave` to jump out of a handler
+          ctx1.bb.emit(JUMP(afterCtx.bb))
+          ctx1.bb.close
+          outerCtx.endHandler()
+        }
+
+        val bodyCtx = this.newBlock
+
+        val finalCtx = body(bodyCtx)
+
+        outerCtx.bb.emit(JUMP(bodyCtx.bb))
+        outerCtx.bb.close
+
+        // msil backend will emit `Leave` to jump out of a try-block
         finalCtx.bb.emit(JUMP(afterCtx.bb))
         finalCtx.bb.close
 
@@ -2040,7 +2086,7 @@ abstract class GenICode extends SubComponent  {
        * jumps to the given basic block.
        */
       def patch(code: Code) {
-        def substMap: Map[Instruction, Instruction] = {
+        def substMap: mutable.Map[Instruction, Instruction] = {
           val map = new HashMap[Instruction, Instruction]()
 
           toPatch foreach (i => map += (i -> patch(i)))
@@ -2048,7 +2094,7 @@ abstract class GenICode extends SubComponent  {
         }
 
         val map = substMap
-        code traverse (_.subst(map))
+        code.blocks foreach (_.subst(map))
       }
 
       /** 
@@ -2090,12 +2136,12 @@ abstract class GenICode extends SubComponent  {
     ///////////////// Fake instructions //////////////////////////
 
     /**
-     * Pseudo jump: it takes a Label instead of a basick block.
+     * Pseudo jump: it takes a Label instead of a basic block.
      * It is used temporarily during code generation. It is replaced
      * by a real JUMP instruction when all labels are resolved.
      */
     abstract class PseudoJUMP(label: Label) extends Instruction {
-      override def toString(): String = "PJUMP " + label.symbol.simpleName
+      override def toString(): String = "PJUMP " + label.symbol
 
       override def consumed = 0
       override def produced = 0
@@ -2138,7 +2184,7 @@ abstract class GenICode extends SubComponent  {
       locals -= l
       
     /** Return all locals that are in scope. */
-    def varsInScope: Buffer[Local] = outer.varsInScope ++ locals
+    def varsInScope: Buffer[Local] = outer.varsInScope.clone() ++= locals
     
     override def toString() = 
       outer.toString() + locals.mkString("[", ", ", "]")
@@ -2148,5 +2194,4 @@ abstract class GenICode extends SubComponent  {
     override def toString() = "[]"
     override def varsInScope: Buffer[Local] = new ListBuffer
   }
-  
 }
diff --git a/src/compiler/scala/tools/nsc/backend/icode/ICodes.scala b/src/compiler/scala/tools/nsc/backend/icode/ICodes.scala
index 2bada78..65e399c 100644
--- a/src/compiler/scala/tools/nsc/backend/icode/ICodes.scala
+++ b/src/compiler/scala/tools/nsc/backend/icode/ICodes.scala
@@ -1,11 +1,16 @@
 /* NSC -- new scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
+ * @author  Martin Odersky
+ */
+/* NSC -- new scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
 
-// $Id: ICodes.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.tools.nsc.backend.icode
+package scala.tools.nsc
+package backend
+package icode
 
 import java.io.PrintWriter
 
@@ -47,13 +52,23 @@ abstract class ICodes extends AnyRef
       new DumpLinearizer()
     else
       global.abort("Unknown linearizer: " + global.settings.Xlinearizer.value)
-
+    
+  /** Have to be careful because dump calls around, possibly
+   *  re-entering methods which initiated the dump (like foreach
+   *  in BasicBlocks) which leads to the icode output olympics.
+   */
+  private var alreadyDumping = false
+  
   /** Print all classes and basic blocks. Used for debugging. */
+  
   def dump {
+    if (alreadyDumping) return
+    else alreadyDumping = true
+    
     val printer = new TextPrinter(new PrintWriter(Console.out, true),
                                   new DumpLinearizer)
 
-    classes.values foreach { c => printer.printClass(c) }
+    classes.values foreach printer.printClass
   }
 
   object liveness extends Liveness {
@@ -66,13 +81,6 @@ abstract class ICodes extends AnyRef
 
   lazy val AnyRefReference: TypeKind = REFERENCE(global.definitions.ObjectClass)
 
-  import global.settings
-  if (settings.XO.value) {
-    settings.inline.value = true
-    settings.Xcloselim.value = true
-    settings.Xdce.value = true
-  }
-
   object icodeReader extends ICodeReader {
     lazy val global: ICodes.this.global.type = ICodes.this.global
   }
diff --git a/src/compiler/scala/tools/nsc/backend/icode/Linearizers.scala b/src/compiler/scala/tools/nsc/backend/icode/Linearizers.scala
index e88b851..60ce6ab 100644
--- a/src/compiler/scala/tools/nsc/backend/icode/Linearizers.scala
+++ b/src/compiler/scala/tools/nsc/backend/icode/Linearizers.scala
@@ -3,12 +3,13 @@
  * @author  Martin Odersky
  */
 
-// $Id: Linearizers.scala 15286 2008-06-06 19:28:49Z stepancheg $
 
-package scala.tools.nsc.backend.icode;
+package scala.tools.nsc
+package backend
+package icode;
 
-import scala.tools.nsc.ast._;
-import scala.collection.mutable.{Stack, HashSet, BitSet};
+import scala.tools.nsc.ast._
+import scala.collection.mutable.{Stack, HashSet, BitSet, ListBuffer}
 
 trait Linearizers { self: ICodes =>
   import opcodes._;
@@ -37,7 +38,7 @@ trait Linearizers { self: ICodes =>
       blocks = Nil;
 
       run {
-        worklist ++= (m.exh map (_.startBlock));
+        worklist pushAll (m.exh map (_.startBlock));
         worklist.push(b); 
       }
 
@@ -46,7 +47,7 @@ trait Linearizers { self: ICodes =>
     
     def linearizeAt(m: IMethod, start: BasicBlock): List[BasicBlock] = {
       blocks = Nil
-      worklist.clear
+      worklist.clear()
       linearize(start)
     }
 
@@ -82,13 +83,14 @@ trait Linearizers { self: ICodes =>
      * Prepend b to the list, if not already scheduled. 
      * TODO: use better test than linear search
      */
-    def add(b: BasicBlock) = 
+    def add(b: BasicBlock) {
       if (blocks.contains(b))
         ()
       else {
         blocks = b :: blocks;
         worklist push b;
       }
+    }
 
     def add(bs: List[BasicBlock]): Unit = bs foreach add;
   }
@@ -155,7 +157,7 @@ trait Linearizers { self: ICodes =>
       if (m.code.startBlock.predecessors eq Nil)
         blocks
       else
-        m.code.startBlock :: (blocks.remove(_ == m.code.startBlock))
+        m.code.startBlock :: (blocks.filterNot(_ == m.code.startBlock))
     }
 
     def linearizeAt(m: IMethod, start: BasicBlock): List[BasicBlock] = {
@@ -197,5 +199,143 @@ trait Linearizers { self: ICodes =>
       error("not implemented")
     }
   }
-  
+
+  /** The MSIL linearizer is used only for methods with at least one exception handler.
+   *  It makes sure that all the blocks belonging to a `try`, `catch` or `finally` block
+   *  are emitted in an order that allows the lexical nesting of try-catch-finally, just
+   *  like in the source code.
+   */
+  class MSILLinearizer extends Linearizer {
+    /** The MSIL linearizer first calls a NormalLInearizer. This is because the ILGenerator checks
+     *  the stack size before emitting instructions. For instance, to emit a `store`, there needs
+     *  to be some value on the stack. This can blow up in situations like this:
+     *       ...
+     *       jump 3
+     *    4: store_local 0
+     *       jump 5
+     *    3: load_value
+     *       jump 4
+     *    5: ...
+     *  here, 3 must be scheduled first.
+     *
+     *  The NormalLinearizer also removes dead blocks (blocks without predecessor). This is important
+     *  in the following example:
+     *     try { throw new Exception }
+     *     catch { case e => throw e }
+     *  which adds a dead block containing just a "throw" (which, again, would blow up code generation
+     *  because of the stack size; there's no value on the stack when emitting that `throw`)
+     */
+    val normalLinearizer = new NormalLinearizer()
+
+    def linearize(m: IMethod): List[BasicBlock] = {
+
+      val handlersByCovered = m.exh.groupBy(_.covered)
+
+      // number of basic blocks covered by the entire try-catch expression
+      def size(covered: collection.immutable.Set[BasicBlock]) = {
+        val hs = handlersByCovered(covered)
+        covered.size + (hs :\ 0)((h, s) => h.blocks.length + s)
+      }
+
+      val tryBlocks = handlersByCovered.keys.toList sortBy size
+
+      var result = normalLinearizer.linearize(m)
+
+      val frozen = HashSet[BasicBlock](result.head)
+      for (tryBlock <- tryBlocks) {
+        result = groupBlocks(m, result, handlersByCovered(tryBlock), frozen)
+      }
+      result
+    }
+
+    /** @param handlers a list of handlers covering the same blocks (same try, multiple catches)
+     *  @param frozen blocks can't be moved (fist block of a method, blocks directly following a try-catch)
+     */
+    def groupBlocks(method: IMethod, blocks: List[BasicBlock], handlers: List[ExceptionHandler], frozen: HashSet[BasicBlock]) = {
+      assert(blocks.head == method.code.startBlock, method)
+
+      // blocks before the try, and blocks for the try
+      val beforeAndTry = new ListBuffer[BasicBlock]()
+      // blocks for the handlers
+      val catches = handlers map (_ => new ListBuffer[BasicBlock]())
+      // blocks to be put at the end
+      val after = new ListBuffer[BasicBlock]()
+
+      var beforeTry = true
+      val head = handlers.head
+
+      for (b <- blocks) {
+        if (head covers b) {
+          beforeTry = false
+          beforeAndTry += b
+        } else {
+          val handlerIndex = handlers.indexWhere(_.blocks.contains(b))
+          if (handlerIndex >= 0) {
+            catches(handlerIndex) += b
+          } else if (beforeTry) {
+            beforeAndTry += b
+          } else {
+            after += b
+          }
+        }
+      }
+
+      // reorder the blocks in "catches" so that the "firstBlock" is actually first
+      for ((lb, handler) <- catches.zip(handlers)) {
+        lb -= handler.startBlock
+        handler.startBlock +=: lb
+      }
+
+      // The first block emitted after a try-catch must be the the one that the try / catch
+      // blocks jump to (because in msil, these jumps cannot be emitted manually)
+      var firstAfter: Option[BasicBlock] = None
+
+      // Find the (hopefully) unique successor, look at the try and all catch blocks
+      var blks = head.covered.toList :: handlers.map(_.blocks)
+      while (firstAfter.isEmpty && !blks.isEmpty) {
+        val b = blks.head
+        blks = blks.tail
+
+        val leaving = leavingBlocks(b)
+        // no leaving blocks when the try or catch ends with THROW or RET
+        if (!leaving.isEmpty) {
+          assert(leaving.size <= 1, leaving)
+          firstAfter = Some(leaving.head)
+        }
+      }
+      if (firstAfter.isDefined) {
+        val b = firstAfter.get
+        if (frozen contains b) {
+          assert(after contains b, b +", "+ method)
+        } else {
+          frozen += b
+          if (beforeAndTry contains b) {
+            beforeAndTry -= b
+          } else {
+            assert(after contains b, after)
+            after -= b
+          }
+          b +=: after
+        }
+      }
+
+      for (lb <- catches) { beforeAndTry ++= lb }
+      beforeAndTry ++= after
+      beforeAndTry.toList
+    }
+
+    /** Returns all direct successors of `blocks` wich are not part
+     *  that list, i.e. successors outside the `blocks` list.
+     */
+    private def leavingBlocks(blocks: List[BasicBlock]) = {
+      val res = new HashSet[BasicBlock]()
+      for (b <- blocks; s <- b.directSuccessors; if (!blocks.contains(s)))
+        res += s
+      res
+    }
+
+    def linearizeAt(m: IMethod, start: BasicBlock): List[BasicBlock] = {
+      error("not implemented")
+    }
+  }
 }
diff --git a/src/compiler/scala/tools/nsc/backend/icode/Members.scala b/src/compiler/scala/tools/nsc/backend/icode/Members.scala
index fb89695..a9489fe 100644
--- a/src/compiler/scala/tools/nsc/backend/icode/Members.scala
+++ b/src/compiler/scala/tools/nsc/backend/icode/Members.scala
@@ -1,11 +1,12 @@
 /* NSC -- new scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
 
-// $Id: Members.scala 16881 2009-01-09 16:28:11Z cunei $
 
-package scala.tools.nsc.backend.icode
+package scala.tools.nsc
+package backend
+package icode
 
 import java.io.PrintWriter
 
@@ -34,6 +35,14 @@ trait Members { self: ICodes =>
     var producedStack: TypeStack = null
     
     private var currentLabel: Int = 0
+    private var _touched = false
+
+    def touched = _touched
+    def touched_=(b: Boolean): Unit = if (b) {
+      blocks foreach (_.touched = true)
+      _touched = true
+    } else
+      _touched = false
 
     // Constructor code
     startBlock = newBlock
@@ -46,58 +55,17 @@ trait Members { self: ICodes =>
           assert(b.successors.length == 1,
                  "Removing start block with more than one successor.");
       }
-      
+
       if (b == startBlock)
         startBlock = b.successors.head;
       blocks -= b
-    }
+      assert(!blocks.contains(b))
+      for (handler <- method.exh if handler.covers(b))
+        handler.covered -= b
 
-    /** 
-     * Apply a function to all basic blocks, for side-effects. It starts at
-     * the given startBlock and checks that are no predecessors of the given node.
-     * Only blocks that are reachable via a path from startBlock are ever visited.
-     */
-    def traverseFrom(startBlock: BasicBlock, f: BasicBlock => Unit) = {
-      val visited: Set[BasicBlock] = new HashSet();
-
-      def traverse0(toVisit: List[BasicBlock]): Unit = toVisit match {
-        case Nil => ();
-        case b :: bs => if (!visited.contains(b)) {
-          f(b); 
-          visited += b;
-          traverse0(bs ::: b.successors);
-        } else
-          traverse0(bs);
-      }
-      assert(startBlock.predecessors == Nil,
-             "Starting traverse from a block with predecessors: " + this);
-      traverse0(startBlock :: Nil)
+      touched = true
     }
 
-    def traverse(f: BasicBlock => Unit) = blocks.toList foreach f;
-
-    /* This method applies the given function to each basic block. */
-    def traverseFeedBack(f: (BasicBlock, HashMap[BasicBlock, Boolean]) => Unit) = {
-      val visited : HashMap[BasicBlock, Boolean] = new HashMap;
-      visited ++= blocks.elements.map(x => (x, false));
-      
-      var blockToVisit: List[BasicBlock] = List(startBlock)
-      
-      while (!blockToVisit.isEmpty) {
-        blockToVisit match {
-	  case b::xs => 
-	    if (!visited(b)) {
-	      f(b, visited); 
-	      blockToVisit = b.successors ::: xs;
-	      visited += (b -> true)
-	    } else
-	      blockToVisit = xs
-          case _ => 
-            error("impossible match")
-	}
-      }
-    }
-    
     /** This methods returns a string representation of the ICode */
     override def toString() : String = "ICode '" + label + "'";
     
@@ -110,6 +78,7 @@ trait Members { self: ICodes =>
     /* Create a new block and append it to the list
      */
     def newBlock: BasicBlock = {
+      touched = true
       val block = new BasicBlock(nextLabel, method);
       blocks += block;
       block
@@ -121,6 +90,7 @@ trait Members { self: ICodes =>
     var fields: List[IField] = Nil
     var methods: List[IMethod] = Nil
     var cunit: CompilationUnit = _
+    var bootstrapClass: Option[String] = None
 
     def addField(f: IField): this.type = {
       fields = f :: fields;
@@ -137,11 +107,16 @@ trait Members { self: ICodes =>
       this
     }
 
-    override def toString() = symbol.fullNameString;
+    override def toString() = symbol.fullName
+
+    def lookupField(s: Symbol) = fields find (_.symbol == s)
+    def lookupMethod(s: Symbol) = methods find (_.symbol == s)
+    def lookupMethod(s: Name) = methods find (_.symbol.name == s)
 
-    def lookupField(s: Symbol) = fields find ((f) => f.symbol == s);
-    def lookupMethod(s: Symbol) = methods find ((m) => m.symbol == s);
-    def lookupMethod(s: Name) = methods find ((m) => m.symbol.name == s);
+    /* determines whether or not this class contains a static ctor. */
+    def containsStaticCtor: Boolean = methods.exists(_.isStaticCtor)
+    /* returns this methods static ctor if it has one. */
+    def lookupStaticCtor: Option[IMethod] = methods.find(_.isStaticCtor)
   }
 
   /** Represent a field in ICode */
@@ -221,13 +196,16 @@ trait Members { self: ICodes =>
     );
 
     def isStatic: Boolean = symbol.isStaticMember
+
+    /* determines whether or not this method is the class static constructor. */
+    def isStaticCtor: Boolean = isStatic && symbol.rawname == nme.CONSTRUCTOR
     
-    override def toString() = symbol.fullNameString
+    override def toString() = symbol.fullName
     
     import opcodes._
     def checkLocals: Unit = if (code ne null) {
       Console.println("[checking locals of " + this + "]")
-      for (bb <- code.blocks; i <- bb.toList) i match {
+      for (bb <- code.blocks; i <- bb) i match {
         case LOAD_LOCAL(l) =>
           if (!this.locals.contains(l)) 
             Console.println("Local " + l + " is not declared in " + this)
@@ -247,13 +225,13 @@ trait Members { self: ICodes =>
     def normalize: Unit = if (this.code ne null) {
       import scala.collection.mutable.{Map, HashMap}      
       val nextBlock: Map[BasicBlock, BasicBlock] = HashMap.empty
-      for (val b <- code.blocks.toList;
-        b.successors.length == 1; 
+      for (b <- code.blocks.toList
+        if b.successors.length == 1; 
         val succ = b.successors.head; 
-        succ ne b;
-        succ.predecessors.length == 1;
-        succ.predecessors.head eq b;
-        !(exh.exists { (e: ExceptionHandler) => 
+        if succ ne b;
+        if succ.predecessors.length == 1;
+        if succ.predecessors.head eq b;
+        if !(exh.exists { (e: ExceptionHandler) => 
             (e.covers(succ) && !e.covers(b)) || (e.covers(b) && !e.covers(succ)) })) {
           nextBlock(b) = succ
       }
@@ -273,7 +251,7 @@ trait Members { self: ICodes =>
           } while (nextBlock.isDefinedAt(succ))
           bb.close
         } else 
-          bb = nextBlock.keys.next
+          bb = nextBlock.keysIterator.next
       }
     }
     
@@ -301,6 +279,8 @@ trait Members { self: ICodes =>
       other.isInstanceOf[Local] &&
       other.asInstanceOf[Local].sym == this.sym
     );
+    
+    override def hashCode = sym.hashCode
 
     override def toString(): String = sym.toString()
   }
diff --git a/src/compiler/scala/tools/nsc/backend/icode/Opcodes.scala b/src/compiler/scala/tools/nsc/backend/icode/Opcodes.scala
index 02a7cdb..5991c14 100644
--- a/src/compiler/scala/tools/nsc/backend/icode/Opcodes.scala
+++ b/src/compiler/scala/tools/nsc/backend/icode/Opcodes.scala
@@ -1,12 +1,13 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
 
-// $Id: Opcodes.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.tools.nsc.backend.icode
+package scala.tools.nsc
+package backend
+package icode
 
 import scala.tools.nsc.ast._
 import scala.tools.nsc.util.{Position,NoPosition}
@@ -57,7 +58,7 @@ trait Opcodes { self: ICodes =>
   /** This class represents an instruction of the intermediate code.
    *  Each case subclass will represent a specific operation.
    */
-  abstract class Instruction {
+  abstract class Instruction extends Cloneable {
 
     /** This abstract method returns the number of used elements on the stack */
     def consumed : Int = 0
@@ -77,19 +78,31 @@ trait Opcodes { self: ICodes =>
     def difference = produced-consumed
     
     /** The corresponding position in the source file */
-    var pos: Position = NoPosition
+    private var _pos: Position = NoPosition
+
+    def pos: Position = _pos
     
     /** Used by dead code elimination. */
     var useful: Boolean = false
     
     def setPos(p: Position): this.type = {
-      pos = p
+      _pos = p
       this
     }
+
+    /** Clone this instruction. */
+    override def clone: Instruction =
+      super.clone.asInstanceOf[Instruction]
   }
 
   object opcodes {
 
+    def mayThrow(i: Instruction): Boolean = i match {
+      case LOAD_LOCAL(_) | STORE_LOCAL(_) | CONSTANT(_) | THIS(_) | CZJUMP(_, _, _, _)
+              | DROP(_) | DUP(_) | RETURN(_) | LOAD_EXCEPTION() | JUMP(_) | CJUMP(_, _, _, _) => false
+      case _ => true
+    }
+
     /** Loads "this" on top of the stack.
      * Stack: ...
      *    ->: ...:ref
@@ -156,7 +169,7 @@ trait Opcodes { self: ICodes =>
     case class LOAD_FIELD(field: Symbol, isStatic: Boolean) extends Instruction {
       /** Returns a string representation of this instruction */
       override def toString(): String = 
-        "LOAD_FIELD " + (if (isStatic) field.fullNameString else field.toString());
+        "LOAD_FIELD " + (if (isStatic) field.fullName else field.toString());
 
       override def consumed = if (isStatic) 0 else 1
       override def produced = 1
@@ -306,22 +319,25 @@ trait Opcodes { self: ICodes =>
     case class CALL_METHOD(method: Symbol, style: InvokeStyle) extends Instruction {
       /** Returns a string representation of this instruction */
       override def toString(): String =
-        "CALL_METHOD " + hostClass.fullNameString + method.fullNameString +" ("+style.toString()+")";
+        "CALL_METHOD " + hostClass.fullName + method.fullName +" ("+style.toString()+")";
 
       var hostClass: Symbol = method.owner;
       def setHostClass(cls: Symbol): this.type = { hostClass = cls; this }
+      
+      /** This is specifically for preserving the target native Array type long
+       *  enough that clone() can generate the right call.
+       */      
+      var targetTypeKind: TypeKind = UNIT // the default should never be used, so UNIT should fail fast.
+      def setTargetTypeKind(tk: TypeKind) = targetTypeKind = tk
 
-      override def consumed = {
-        var result = method.tpe.paramTypes.length;
-        result = result + (style match {
-          case Dynamic => 1
+      override def consumed = method.tpe.paramTypes.length + (
+        style match {
+          case Dynamic | InvokeDynamic => 1
           case Static(true) => 1
           case Static(false) => 0 
           case SuperCall(_) => 1
-        });
-        
-        result;
-      }
+        }
+      )
       
       override def consumedTypes = {
         val args = method.tpe.paramTypes map toTypeKind
@@ -338,7 +354,7 @@ trait Opcodes { self: ICodes =>
           0
         else 1
         
-      /** object idenity is equality for CALL_METHODs. Needed for
+      /** object identity is equality for CALL_METHODs. Needed for
        *  being able to store such instructions into maps, when more
        *  than one CALL_METHOD to the same method might exist.
        */
@@ -387,7 +403,7 @@ trait Opcodes { self: ICodes =>
       override def toString(): String ="CREATE_ARRAY "+elem.toString() + " x " + dims;
 
       override def consumed = dims;
-      override def consumedTypes = List.make(dims, INT)
+      override def consumedTypes = List.fill(dims)(INT)
       override def produced = 1;
     }
 
@@ -624,14 +640,19 @@ trait Opcodes { self: ICodes =>
       /** Returns a string representation of this style. */
       override def toString(): String = this match {
         case Dynamic =>  "dynamic"
+        case InvokeDynamic => "invoke-dynamic"
         case Static(false) => "static-class"
         case Static(true) =>  "static-instance"
         case SuperCall(mix) => "super(" + mix + ")"
       }
     }
 
+    /** Virtual calls */
     case object Dynamic extends InvokeStyle
     
+    /** InvokeDynamic a la JSR 292 (experimental). */
+    case object InvokeDynamic extends InvokeStyle
+    
     /** 
      * Special invoke. Static(true) is used for calls to private
      * members.
diff --git a/src/compiler/scala/tools/nsc/backend/icode/Primitives.scala b/src/compiler/scala/tools/nsc/backend/icode/Primitives.scala
index 621bce0..c4a13d7 100644
--- a/src/compiler/scala/tools/nsc/backend/icode/Primitives.scala
+++ b/src/compiler/scala/tools/nsc/backend/icode/Primitives.scala
@@ -1,11 +1,12 @@
 /* NSC -- new scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
 
-// $Id: Primitives.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.tools.nsc.backend.icode;
+package scala.tools.nsc
+package backend
+package icode;
 
 import java.io.PrintWriter;
 
diff --git a/src/compiler/scala/tools/nsc/backend/icode/Printers.scala b/src/compiler/scala/tools/nsc/backend/icode/Printers.scala
index 25bc51f..02e0f77 100644
--- a/src/compiler/scala/tools/nsc/backend/icode/Printers.scala
+++ b/src/compiler/scala/tools/nsc/backend/icode/Printers.scala
@@ -1,11 +1,12 @@
 /* NSC -- new scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
 
-// $Id: Printers.scala 16881 2009-01-09 16:28:11Z cunei $
 
-package scala.tools.nsc.backend.icode
+package scala.tools.nsc
+package backend
+package icode
 
 import java.io.PrintWriter
 
@@ -116,16 +117,17 @@ trait Printers { self: ICodes =>
     def printBlock(bb: BasicBlock) {
       print(bb.label)
       if (bb.loopHeader) print("[loop header]")
-      print(": "); indent; println
-      bb.toList foreach printInstruction
+      print(": ");
+      if (settings.debug.value) print("pred: " + bb.predecessors + " succs: " + bb.successors + " flags: " + bb.flagsString)
+      indent; println
+      bb foreach printInstruction
       undent; println
     }
 
     def printInstruction(i: Instruction) {
 //      if (settings.Xdce.value)
 //        print(if (i.useful) "   " else " * ");
-      if (settings.debug.value)
-        print(i.pos.line.map(_.toString).getOrElse("No line"))
+      if (i.pos.isDefined) print(i.pos.line.toString + "\t") else print("undef\t")
       println(i.toString())
     }
   }
diff --git a/src/compiler/scala/tools/nsc/backend/icode/Repository.scala b/src/compiler/scala/tools/nsc/backend/icode/Repository.scala
index 1f9ca78..9a14488 100644
--- a/src/compiler/scala/tools/nsc/backend/icode/Repository.scala
+++ b/src/compiler/scala/tools/nsc/backend/icode/Repository.scala
@@ -1,11 +1,12 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
 
-// $Id: Repository.scala 16881 2009-01-09 16:28:11Z cunei $
 
-package scala.tools.nsc.backend.icode
+package scala.tools.nsc
+package backend
+package icode
 
 import scala.collection._
 
@@ -34,6 +35,7 @@ trait Repository {
   def icode(sym: Symbol, force: Boolean): IClass = 
     if (available(sym)) icode(sym).get
     else {
+      log("loading " + sym)
       load(sym)
       assert(available(sym))
       loaded(sym)
diff --git a/src/compiler/scala/tools/nsc/backend/icode/TypeKinds.scala b/src/compiler/scala/tools/nsc/backend/icode/TypeKinds.scala
index d8b5cca..615b8f1 100644
--- a/src/compiler/scala/tools/nsc/backend/icode/TypeKinds.scala
+++ b/src/compiler/scala/tools/nsc/backend/icode/TypeKinds.scala
@@ -1,11 +1,12 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
 
-// $Id: TypeKinds.scala 16881 2009-01-09 16:28:11Z cunei $
 
-package scala.tools.nsc.backend.icode
+package scala.tools.nsc
+package backend
+package icode
 
 /* A type case
 
@@ -23,10 +24,30 @@ package scala.tools.nsc.backend.icode
 
 */
 
-import scala.collection.mutable.{Map, HashMap}
+import scala.collection.mutable.{ Map, HashMap }
 
 trait TypeKinds { self: ICodes =>
   import global._
+  import definitions.{ ArrayClass, AnyRefClass, ObjectClass, NullClass, NothingClass }
+  
+  /** A map from scala primitive Types to ICode TypeKinds */
+  lazy val primitiveTypeMap: collection.Map[Symbol, TypeKind] = {
+    import definitions._
+    collection.Map(
+      UnitClass     -> UNIT,
+      BooleanClass  -> BOOL,
+      CharClass     -> CHAR,
+      ByteClass     -> BYTE,
+      ShortClass    -> SHORT,
+      IntClass      -> INT,
+      LongClass     -> LONG,
+      FloatClass    -> FLOAT,
+      DoubleClass   -> DOUBLE
+    )
+  }
+  /** Reverse map for toType */
+  private lazy val reversePrimitiveMap: collection.Map[TypeKind, Symbol] = 
+    collection.Map(primitiveTypeMap.toList map (_.swap) : _*)
 
   /** This class represents a type kind. Type kinds
    * represent the types that the VM know (or the ICode 
@@ -34,22 +55,14 @@ trait TypeKinds { self: ICodes =>
    */
   sealed abstract class TypeKind {
 
-    def toType: Type = this match {
-      case UNIT            => definitions.UnitClass.tpe
-      case BOOL            => definitions.BooleanClass.tpe
-      case BYTE            => definitions.ByteClass.tpe
-      case SHORT           => definitions.ShortClass.tpe
-      case CHAR            => definitions.CharClass.tpe
-      case INT             => definitions.IntClass.tpe
-      case LONG            => definitions.LongClass.tpe
-      case FLOAT           => definitions.FloatClass.tpe
-      case DOUBLE          => definitions.DoubleClass.tpe
-      case REFERENCE(cls)  => typeRef(cls.typeConstructor.prefix, cls, Nil)
-      //case VALUE(cls)      => typeRef(cls.typeConstructor.prefix, cls, Nil);
-      case ARRAY(elem)     => typeRef(definitions.ArrayClass.typeConstructor.prefix,
-                                      definitions.ArrayClass,
-                                      elem.toType :: Nil)
-      case _ => abort("Unknown type kind.")
+    def toType: Type = (reversePrimitiveMap get this) match {
+      case Some(sym)  => sym.tpe
+      case None       => this match {  
+        case REFERENCE(cls)  => cls.tpe // typeRef(cls.typeConstructor.prefix, cls, Nil)
+        // case VALUE(cls)      => typeRef(cls.typeConstructor.prefix, cls, Nil)
+        case ARRAY(elem)     => typeRef(ArrayClass.typeConstructor.prefix, ArrayClass, List(elem.toType))
+        case _ => abort("Unknown type kind.")
+      }
     }
 
     def isReferenceType: Boolean = false
@@ -94,6 +107,8 @@ trait TypeKinds { self: ICodes =>
     def dimensions: Int = 0
   }
 
+  var lubs0 = 0
+
   /**
    * The least upper bound of two typekinds. They have to be either
    * REFERENCE or ARRAY kinds.
@@ -102,26 +117,27 @@ trait TypeKinds { self: ICodes =>
    */
   def lub(a: TypeKind, b: TypeKind): TypeKind = {
     def lub0(t1: Type, t2: Type): Type = {
-      val lubTpe = global.lub(t1 :: t2 :: Nil)
-      assert(lubTpe.typeSymbol.isClass,
-             "Least upper bound of " + t1 + " and " + t2 + " is not a class: " + lubTpe)
-      lubTpe
+      //lubs0 += 1
+      global.lub(t1 :: t2 :: Nil)
     }
 
-    if ((a.isReferenceType || a.isArrayType) &&
-        (b.isReferenceType || b.isArrayType))
-      toTypeKind(lub0(a.toType, b.toType))
-    else if (a == b) a
-    else if (a == REFERENCE(definitions.NothingClass)) b
-    else if (b == REFERENCE(definitions.NothingClass)) a
+    if (a == b) a
+    else if (a == REFERENCE(NothingClass)) b
+    else if (b == REFERENCE(NothingClass)) a
     else (a, b) match {
-      case (BOXED(a1), BOXED(b1)) => if (a1 == b1) a else REFERENCE(definitions.AnyRefClass)
-      case (BOXED(_), REFERENCE(_)) | (REFERENCE(_), BOXED(_)) => REFERENCE(definitions.AnyRefClass)
-      case (BOXED(_), ARRAY(_)) | (ARRAY(_), BOXED(_)) => REFERENCE(definitions.AnyRefClass)
+      case (BOXED(a1), BOXED(b1)) => if (a1 == b1) a else REFERENCE(AnyRefClass)
+      case (BOXED(_), REFERENCE(_)) | (REFERENCE(_), BOXED(_)) => REFERENCE(AnyRefClass)
+      case (BOXED(_), ARRAY(_)) | (ARRAY(_), BOXED(_)) => REFERENCE(AnyRefClass)
       case (BYTE, INT) | (INT, BYTE) => INT
       case (SHORT, INT) | (INT, SHORT) => INT
       case (CHAR, INT) | (INT, CHAR) => INT
-      case _ => throw new CheckerError("Incompatible types: " + a + " with " + b)
+      case (BOOL, INT) | (INT, BOOL) => INT
+      case _ =>
+        if ((a.isReferenceType || a.isArrayType) &&
+            (b.isReferenceType || b.isArrayType))
+          toTypeKind(lub0(a.toType, b.toType))
+        else
+          throw new CheckerException("Incompatible types: " + a + " with " + b)
     }
   }
 
@@ -129,7 +145,7 @@ trait TypeKinds { self: ICodes =>
   case object UNIT extends TypeKind {
     def maxType(other: TypeKind): TypeKind = other match {
       case UNIT => UNIT
-      case REFERENCE(a) if a == definitions.NothingClass => UNIT
+      case REFERENCE(NothingClass)  => UNIT
       case _ => abort("Uncomparable type kinds: UNIT with " + other)
     }
   }
@@ -138,7 +154,7 @@ trait TypeKinds { self: ICodes =>
   case object BOOL extends TypeKind {
     override def maxType(other: TypeKind): TypeKind = other match {
       case BOOL => BOOL
-      case REFERENCE(a) if a == definitions.NothingClass => BOOL
+      case REFERENCE(NothingClass) => BOOL
       case _ => abort("Uncomparable type kinds: BOOL with " + other)
     }
   }
@@ -147,29 +163,37 @@ trait TypeKinds { self: ICodes =>
   case object BYTE extends TypeKind {
     override def maxType(other: TypeKind): TypeKind = 
       other match {
-        case BYTE | SHORT | CHAR | INT | LONG | FLOAT | DOUBLE => other
-        case REFERENCE(a) if a == definitions.NothingClass => BYTE
+        case CHAR => INT
+        case BYTE | SHORT | INT | LONG | FLOAT | DOUBLE => other
+        case REFERENCE(NothingClass) => BYTE
         case _ => abort("Uncomparable type kinds: BYTE with " + other)
       }
   }
+  
+  /** Note that the max of Char/Byte and Char/Short is Int, because
+   *  neither strictly encloses the other due to unsignedness.
+   *  See ticket #2087 for a consequence.
+   */
 
   /** A 2-byte signed integer */
   case object SHORT extends TypeKind {
     override def maxType(other: TypeKind): TypeKind = 
       other match {
-        case BYTE | SHORT | CHAR => SHORT
-        case REFERENCE(a) if a == definitions.NothingClass => SHORT
+        case CHAR => INT
+        case BYTE | SHORT => SHORT
+        case REFERENCE(NothingClass) => SHORT
         case INT | LONG | FLOAT | DOUBLE => other
         case _ => abort("Uncomparable type kinds: SHORT with " + other)
       }
   }
 
-  /** A 2-byte signed integer */
+  /** A 2-byte UNSIGNED integer */
   case object CHAR extends TypeKind {
     override def maxType(other: TypeKind): TypeKind =
       other match {
-        case BYTE | SHORT | CHAR => CHAR
-        case REFERENCE(a) if a == definitions.NothingClass => CHAR
+        case CHAR => CHAR
+        case BYTE | SHORT => INT
+        case REFERENCE(NothingClass) => CHAR
         case INT | LONG | FLOAT | DOUBLE => other
         case _ => abort("Uncomparable type kinds: CHAR with " + other)
       }
@@ -181,7 +205,7 @@ trait TypeKinds { self: ICodes =>
     override def maxType(other: TypeKind): TypeKind =
       other match {
         case BYTE | SHORT | CHAR | INT => INT
-        case REFERENCE(a) if a == definitions.NothingClass => INT
+        case REFERENCE(NothingClass) => INT
         case LONG | FLOAT | DOUBLE => other
         case _ => abort("Uncomparable type kinds: INT with " + other)
       }
@@ -192,7 +216,7 @@ trait TypeKinds { self: ICodes =>
     override def maxType(other: TypeKind): TypeKind =
       other match {
         case BYTE | SHORT | CHAR | INT | LONG => LONG
-        case REFERENCE(a) if a == definitions.NothingClass => LONG
+        case REFERENCE(NothingClass) => LONG
         case FLOAT | DOUBLE => DOUBLE
         case _ => abort("Uncomparable type kinds: LONG with " + other)
       }
@@ -202,8 +226,8 @@ trait TypeKinds { self: ICodes =>
   case object FLOAT extends TypeKind {
     override def maxType(other: TypeKind): TypeKind = other match {
       case BYTE | SHORT | CHAR | INT | LONG | FLOAT => FLOAT
-        case REFERENCE(a) if a == definitions.NothingClass => FLOAT
-      case DOUBLE => DOUBLE
+      case REFERENCE(NothingClass)                  => FLOAT
+      case DOUBLE                                   => DOUBLE
       case _ => abort("Uncomparable type kinds: FLOAT with " + other)
     }
   }
@@ -213,7 +237,7 @@ trait TypeKinds { self: ICodes =>
     override def maxType(other: TypeKind): TypeKind =
       if (other.isNumericType) 
         DOUBLE
-      else if (other == REFERENCE(definitions.NothingClass)) DOUBLE 
+      else if (other == REFERENCE(NothingClass)) DOUBLE 
       else abort("Uncomparable type kinds: DOUBLE with " + other)
   }
 
@@ -222,7 +246,7 @@ trait TypeKinds { self: ICodes =>
   //   override def maxType(other: TypeKind): TypeKind = other match {
   //     case STRING => STRING;
   //     case _   =>
-  //       abort("Uncomparbale type kinds: STRING with " + other);
+  //       abort("Uncomparable type kinds: STRING with " + other);
   //   }
   // }
 
@@ -230,13 +254,13 @@ trait TypeKinds { self: ICodes =>
   final case class REFERENCE(cls: Symbol) extends TypeKind {
     assert(cls ne null,
            "REFERENCE to null class symbol.")
-    assert(cls != definitions.ArrayClass,
+    assert(cls != ArrayClass,
            "REFERENCE to Array is not allowed, should be ARRAY[..] instead")
     assert(cls != NoSymbol,
            "REFERENCE to NoSymbol not allowed!")
 
     override def toString(): String = 
-      "REFERENCE(" + cls.fullNameString + ")"
+      "REFERENCE(" + cls.fullName + ")"
 
     /**
      * Approximate `lub'. The common type of two references is
@@ -245,23 +269,21 @@ trait TypeKinds { self: ICodes =>
      */
     override def maxType(other: TypeKind): TypeKind =
       other match {
-        case REFERENCE(_) =>
-          REFERENCE(definitions.AnyRefClass)
-        case ARRAY(_) =>
-          REFERENCE(definitions.AnyRefClass)
+        case REFERENCE(_) | ARRAY(_) =>
+          REFERENCE(AnyRefClass)
         case _ =>
-          abort("Uncomparbale type kinds: REFERENCE with " + other)
+          abort("Uncomparable type kinds: REFERENCE with " + other)
       }
 
     /** Checks subtyping relationship. */
     override def <:<(other: TypeKind): Boolean =
-      if (cls == definitions.NothingClass)
+      if (cls == NothingClass)
         true
       else other match {
         case REFERENCE(cls2) =>
           cls.tpe <:< cls2.tpe
         case ARRAY(_) =>
-          cls == definitions.NullClass
+          cls == NullClass
         case _ => false
       }
 
@@ -283,7 +305,7 @@ trait TypeKinds { self: ICodes =>
 //       abort(toString() + " maxType " + other.toString());
 
 //     override def toString(): String =
-//       "VALUE(" + cls.fullNameString + ")";
+//       "VALUE(" + cls.fullName + ")";
 //   }
 
   def ArrayN(elem: TypeKind, dims: Int): ARRAY = {
@@ -316,11 +338,12 @@ trait TypeKinds { self: ICodes =>
     override def maxType(other: TypeKind): TypeKind =
       other match {
         case REFERENCE(_) =>
-          REFERENCE(definitions.AnyRefClass)
+          REFERENCE(AnyRefClass)
         case ARRAY(elem2) =>
-          ARRAY(elem maxType elem2)
+          if (elem == elem2) ARRAY(elem)
+          else REFERENCE(AnyRefClass)
         case _ =>
-          abort("Uncomparbale type kinds: ARRAY with " + other)
+          abort("Uncomparable type kinds: ARRAY with " + other)
       }
 
     /** Array subtyping is covariant, as in Java. Necessary for checking 
@@ -329,10 +352,8 @@ trait TypeKinds { self: ICodes =>
       other match {
         case ARRAY(elem2) =>
           elem <:< elem2
-        case REFERENCE(sym) =>
-          (sym == definitions.AnyRefClass ||
-           sym == definitions.ObjectClass) // TODO: platform dependent!
-
+        case REFERENCE(AnyRefClass | ObjectClass) =>
+          true  //  TODO: platform dependent!
         case _ => false
       }
 
@@ -356,18 +377,17 @@ trait TypeKinds { self: ICodes =>
     override def maxType(other: TypeKind): TypeKind =
       other match {
         case REFERENCE(_) | ARRAY(_) | BOXED(_) =>
-          REFERENCE(definitions.AnyRefClass)
+          REFERENCE(AnyRefClass)
         case _ =>
-          abort("Uncomparbale type kinds: ARRAY with " + other)
+          abort("Uncomparable type kinds: ARRAY with " + other)
       }
 
     /** Checks subtyping relationship. */
     override def <:<(other: TypeKind): Boolean =
       other match {
-        case REFERENCE(sym) =>
-          (sym == definitions.AnyRefClass ||
-           sym == definitions.ObjectClass) // TODO: platform dependent!
-           
+        case REFERENCE(AnyRefClass | ObjectClass) =>
+          true // TODO: platform dependent!
+                     
         case BOXED(other) =>
           kind == other
 
@@ -396,9 +416,9 @@ trait TypeKinds { self: ICodes =>
     override def maxType(other: TypeKind): TypeKind =
       other match {
         case REFERENCE(_) =>
-          REFERENCE(definitions.AnyRefClass)
+          REFERENCE(AnyRefClass)
         case _ =>
-          abort("Uncomparbale type kinds: ConcatClass with " + other)
+          abort("Uncomparable type kinds: ConcatClass with " + other)
       }
 
     /** Checks subtyping relationship. */
@@ -410,34 +430,32 @@ trait TypeKinds { self: ICodes =>
   ////////////////// Conversions //////////////////////////////
 
 
-  /** Return the TypeKind of the given type */
+  /** Return the TypeKind of the given type
+   *
+   *  Call to .normalize fixes #3003 (follow type aliases). Otherwise,
+   *  arrayOrClassType below would return AnyRefReference.
+   */
   def toTypeKind(t: Type): TypeKind = t.normalize match {
     case ThisType(sym) => 
-      if (sym == definitions.ArrayClass)
+      if (sym == ArrayClass)
         AnyRefReference
       else
         REFERENCE(sym)
 
     case SingleType(pre, sym) => 
-      primitiveTypeMap get sym match {
-        case Some(k) => k
-        case None    => REFERENCE(sym)
-      }
+      primitiveTypeMap.getOrElse(sym, REFERENCE(sym))
 
     case ConstantType(value) =>
       toTypeKind(t.underlying)
 
     case TypeRef(_, sym, args) =>
-      primitiveTypeMap get sym match {
-        case Some(k) => k
-        case None    => arrayOrClassType(sym, args)
-      }
+      primitiveTypeMap.getOrElse(sym, arrayOrClassType(sym, args))
 
     case ClassInfoType(_, _, sym) =>
       primitiveTypeMap get sym match {
         case Some(k) => k
         case None    =>
-          if (sym == definitions.ArrayClass)
+          if (sym == ArrayClass)
             abort("ClassInfoType to ArrayClass!")
           else
             REFERENCE(sym)
@@ -445,18 +463,22 @@ trait TypeKinds { self: ICodes =>
 
     case ExistentialType(tparams, t) =>
       toTypeKind(t)
+
+    case AnnotatedType(_, t, _) =>
+      toTypeKind(t)
       
     //case WildcardType => // bq: useful hack when wildcard types come here
     //  REFERENCE(definitions.ObjectClass)
 
     case _ =>
-      abort("Unknown type: " + t)
+      abort("Unknown type: " + t + ", " + t.normalize + "[" + t.getClass + ", " + t.normalize.getClass + "]" + 
+	    " TypeRef? " + t.isInstanceOf[TypeRef] + ", " + t.normalize.isInstanceOf[TypeRef]) 
   }
   
   /** Return the type kind of a class, possibly an array type.
    */
   private def arrayOrClassType(sym: Symbol, targs: List[Type]): TypeKind = {
-    if (sym == definitions.ArrayClass)
+    if (sym == ArrayClass)
       ARRAY(toTypeKind(targs.head))
     else if (sym.isClass)
         REFERENCE(sym)
@@ -466,25 +488,4 @@ trait TypeKinds { self: ICodes =>
     }
   }
 
-  /** A map from scala primitive Types to ICode TypeKinds */
-  private var primitiveTypeMap: Map[Symbol, TypeKind] = null
-
-  /** Initialize the map from scala primitive types to ICode types */
-  def initPrimitiveTypeMap = {
-    log("Initializing primitive map")
-    primitiveTypeMap = new HashMap()
-    primitiveTypeMap += (definitions.UnitClass -> UNIT)
-    primitiveTypeMap += (definitions.BooleanClass -> BOOL)
-    primitiveTypeMap += (definitions.ByteClass -> BYTE)
-    primitiveTypeMap += (definitions.ShortClass -> SHORT)
-    primitiveTypeMap += (definitions.CharClass -> CHAR)
-    primitiveTypeMap += (definitions.IntClass -> INT)
-    primitiveTypeMap += (definitions.LongClass -> LONG)
-    if (!forCLDC) {
-      primitiveTypeMap += (definitions.FloatClass -> FLOAT)
-      primitiveTypeMap += (definitions.DoubleClass -> DOUBLE)
-    }
-//    primitiveTypeMap += (definitions.StringClass -> STRING)
-  }
-  
 }
diff --git a/src/compiler/scala/tools/nsc/backend/icode/TypeStacks.scala b/src/compiler/scala/tools/nsc/backend/icode/TypeStacks.scala
index ff0d5ad..5b4b0cb 100644
--- a/src/compiler/scala/tools/nsc/backend/icode/TypeStacks.scala
+++ b/src/compiler/scala/tools/nsc/backend/icode/TypeStacks.scala
@@ -1,11 +1,12 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
 
-// $Id: TypeStacks.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.tools.nsc.backend.icode
+package scala.tools.nsc
+package backend
+package icode
 
 /** This trait ...
  *
@@ -16,7 +17,7 @@ trait TypeStacks { self: ICodes =>
   import opcodes._
   import global.{Symbol, Type, definitions}
 
-  /* This class simulates the type of the opperand
+  /* This class simulates the type of the operand
    * stack of the ICode.
    */
   type Rep = List[TypeKind]
@@ -69,36 +70,21 @@ trait TypeStacks { self: ICodes =>
     def apply(n: Int): TypeKind = types(n)
 
     /**
-     * A TypeStack aggress with another one if they have the same
+     * A TypeStack agrees with another one if they have the same
      * length and each type kind agrees position-wise. Two 
      * types agree if one is a subtype of the other.
      */
     def agreesWith(other: TypeStack): Boolean =
-      (types.length == other.types.length) &&
-      List.forall2(types, other.types) ((t1, t2) => t1 <:< t2 || t2 <:< t1)
-
-    def mergeWith(that: TypeStack): TypeStack = {
-      def merge(a: TypeStack, b: TypeStack): TypeStack = {
-        val lst = List.map2(a.types, b.types) ((k1, k2) => k1 match {
-          case REFERENCE(cls1) =>
-            val REFERENCE(cls2) = k2
-            lub(k1,k2)
-          case _ => k1
-        })
-        new TypeStack(lst)
-      }
-
-      assert(this agreesWith that,
-             "Incompatible type stacks: " + this + ", " + that)
-      merge(this, that)
-    }
+      (types corresponds other.types)((t1, t2) => t1 <:< t2 || t2 <:< t1)
 
     /* This method returns a String representation of the stack */
-    override def toString() = types.mkString("<", ",", ">")
+    override def toString() = types.mkString("\n", "\n", "\n")
 
-    override def equals(other: Any): Boolean =
-      other.isInstanceOf[TypeStack] &&
-      List.forall2(other.asInstanceOf[TypeStack].types, types)((a, b) => a == b)
+    override def hashCode() = types.hashCode()
+    override def equals(other: Any): Boolean = other match {
+      case x: TypeStack => x.types sameElements types
+      case _            => false
+    }
   }
 
 }
diff --git a/src/compiler/scala/tools/nsc/backend/icode/analysis/CompleteLattice.scala b/src/compiler/scala/tools/nsc/backend/icode/analysis/CompleteLattice.scala
index 212cd5d..cf596fe 100644
--- a/src/compiler/scala/tools/nsc/backend/icode/analysis/CompleteLattice.scala
+++ b/src/compiler/scala/tools/nsc/backend/icode/analysis/CompleteLattice.scala
@@ -1,11 +1,11 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
 
-// $Id: CompleteLattice.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.tools.nsc.backend.icode.analysis
+package scala.tools.nsc
+package backend.icode.analysis
 
 /** A complete lattice.
  */
@@ -27,7 +27,7 @@ trait CompleteLattice {
   }
 
   /** Return the least upper bound of <code>a</code> and <code>b</code> */
-  def lub2(a: Elem, b: Elem): Elem
+  def lub2(exceptional: Boolean)(a: Elem, b: Elem): Elem
 
   /** Return the top element. */
   def top: Elem
@@ -36,10 +36,10 @@ trait CompleteLattice {
   def bottom: Elem
 
   /** Compute the least upper bound of a list of elements. */
-  def lub(xs: List[Elem]): Elem = try {
-    if (xs == Nil) bottom else xs reduceLeft lub2
+  def lub(xs: List[Elem], exceptional: Boolean): Elem = try {
+    if (xs == Nil) bottom else xs reduceLeft lub2(exceptional)
   } catch {
-      case e: LubError =>
+      case e: LubException =>
         Console.println("Lub on blocks: " + xs)
         throw e
   }
diff --git a/src/compiler/scala/tools/nsc/backend/icode/analysis/CopyPropagation.scala b/src/compiler/scala/tools/nsc/backend/icode/analysis/CopyPropagation.scala
index fca2675..c8cdc69 100644
--- a/src/compiler/scala/tools/nsc/backend/icode/analysis/CopyPropagation.scala
+++ b/src/compiler/scala/tools/nsc/backend/icode/analysis/CopyPropagation.scala
@@ -1,11 +1,11 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
 
-// $Id: CopyPropagation.scala 16881 2009-01-09 16:28:11Z cunei $
 
-package scala.tools.nsc.backend.icode.analysis
+package scala.tools.nsc
+package backend.icode.analysis
 
 import scala.collection.mutable.{Map, HashMap}
 import scala.tools.nsc.symtab.Flags.DEFERRED
@@ -22,7 +22,7 @@ abstract class CopyPropagation {
   import icodes._
 
   /** Locations can be local variables, this, and fields. */
-  abstract sealed class Location;
+  abstract sealed class Location
   case class LocalVar(l: Local) extends Location
   case class Field(r: Record, sym: Symbol) extends Location
   case object This extends Location
@@ -57,18 +57,13 @@ abstract class CopyPropagation {
 
     class State(val bindings: Bindings, var stack: List[Value]) {
       override def equals(that: Any): Boolean = 
-        (this eq that.asInstanceOf[AnyRef]) ||
-        that.isInstanceOf[State] && {
-          val other = that.asInstanceOf[State]
-
+        (this eq that.asInstanceOf[AnyRef]) || (that match {
           /* comparison with bottom is reference equality! */
-          if ((other eq bottom) || (this eq bottom))
-            (this eq other)
-          else {
-            this.bindings == other.bindings &&
-            List.forall2(this.stack, other.stack) { (a, b) => a == b }
-          }
-        }
+          case other: State if (this ne bottom) && (other ne bottom) =>
+            (this.bindings == other.bindings) &&
+            (this.stack corresponds other.stack)(_ == _)  // @PP: corresponds
+          case _ => false
+        })
 
       /* Return an alias for the given local. It returns the last
        * local in the chain of aliased locals. Cycles are not allowed
@@ -121,15 +116,43 @@ abstract class CopyPropagation {
        * binding of that local.
        */
       def getFieldValue(r: Record, f: Symbol): Option[Value] = {
+        if(!r.bindings.isDefinedAt(f)) None else {
+        	var target: Value = r.bindings(f)
+        	target match {
+          	case Deref(LocalVar(l)) => Some(getBinding(l))
+          	case Deref(Field(r1, f1)) => getFieldValue(r1, f1) orElse Some(target)
+//          case Deref(This)    => Some(target)
+//          case Const(k) => Some(target)
+	          case _  => Some(target)
+          }
+        }
+      }
+      
+      /** The same as getFieldValue, but never returns Record/Field values. Use
+       *  this when you want to find a replacement for a field value (either a local,
+       *  or a constant/this value). 
+       */
+      def getFieldNonRecordValue(r: Record, f: Symbol): Option[Value] = {
         assert(r.bindings.isDefinedAt(f),
             "Record " + r + " does not contain a field " + f);
 
         var target: Value = r.bindings(f)
         target match {
-          case Deref(LocalVar(l)) => Some(Deref(LocalVar(getAlias(l))))
-          case Deref(This)    => Some(target)
-          case Const(k) => Some(target)
-          case _  => None
+          case Deref(LocalVar(l)) => 
+            val alias = getAlias(l)
+            val derefAlias = Deref(LocalVar(alias))
+            getBinding(alias) match {
+              case Record(_, _) => Some(derefAlias)
+              case Deref(Field(r1, f1)) => 
+                getFieldNonRecordValue(r1, f1) orElse Some(derefAlias)
+              case Boxed(_) => Some(derefAlias)
+              case v => Some(v) 
+            }
+          case Deref(Field(r1, f1)) => 
+            getFieldNonRecordValue(r1, f1) orElse None
+          case Deref(This) => Some(target)
+          case Const(k)    => Some(target)
+          case _           => None
         }
       }
 
@@ -150,31 +173,31 @@ abstract class CopyPropagation {
 
     val exceptionHandlerStack = Unknown :: Nil
 
-    def lub2(a: Elem, b: Elem): Elem = {
+    def lub2(exceptional: Boolean)(a: Elem, b: Elem): Elem = {
       if (a eq bottom)      b
       else if (b eq bottom) a
       else if (a == b) a
       else {
+        //assert(!(a.stack eq exceptionHandlerStack) && !(b.stack eq exceptionHandlerStack)) 
         val resStack = 
-          if (a.stack eq exceptionHandlerStack) a.stack
-          else if (b.stack eq exceptionHandlerStack) b.stack
+          if (exceptional) exceptionHandlerStack
           else {
-            if (a.stack.length != b.stack.length)
-              throw new LubError(a, b, "Invalid stacks in states: ");
-            List.map2(a.stack, b.stack) { (v1, v2) => 
+//            if (a.stack.length != b.stack.length)
+//              throw new LubException(a, b, "Invalid stacks in states: ");
+            (a.stack, b.stack).zipped map { (v1, v2) => 
               if (v1 == v2) v1 else Unknown 
             }
           }
       
 /*        if (a.stack.length != b.stack.length)
-          throw new LubError(a, b, "Invalid stacks in states: ");
+          throw new LubException(a, b, "Invalid stacks in states: ");
         val resStack = List.map2(a.stack, b.stack) { (v1, v2) => 
           if (v1 == v2) v1 else Unknown 
         }
         */
-        val commonPairs = a.bindings.toList intersect (b.bindings.toList)
         val resBindings = new HashMap[Location, Value]
-        for ((k, v) <- commonPairs)
+        
+        for ((k, v) <- a.bindings if b.bindings.isDefinedAt(k) && v == b.bindings(k))
           resBindings += (k -> v);
         new State(resBindings, resStack)
       }
@@ -218,9 +241,14 @@ abstract class CopyPropagation {
     }
 
     def blockTransfer(b: BasicBlock, in: lattice.Elem): lattice.Elem =
-      b.toList.foldLeft(in)(interpret)
+      b.foldLeft(in)(interpret)
     
     import opcodes._
+    
+    private def retain[A, B](map: Map[A, B])(p: (A, B) => Boolean) = {
+      for ((k, v) <- map ; if !p(k, v)) map -= k
+      map
+    }
 
     /** Abstract interpretation for one instruction. */
     def interpret(in: copyLattice.Elem, i: Instruction): copyLattice.Elem = {
@@ -253,7 +281,21 @@ abstract class CopyPropagation {
             val v1 = in.stack match {
               case (r @ Record(cls, bindings)) :: xs =>
                 Deref(Field(r, field))
-
+              
+              case Deref(LocalVar(l)) :: _ =>
+                in.getBinding(l) match {
+                  case r @ Record(cls, bindings) => Deref(Field(r, field))
+                  case _ => Unknown
+                }
+                
+              case Deref(Field(r, f)) :: _ =>
+                val fld = in.getFieldValue(r, f)
+                fld match {
+                  case Some(r @ Record(cls, bindings)) if bindings.isDefinedAt(f) =>
+                  	in.getFieldValue(r, f).getOrElse(Unknown)
+                  case _ => Unknown
+                }
+                
               case _ => Unknown
             }
             out.stack = v1 :: out.stack.drop(1)
@@ -304,14 +346,14 @@ abstract class CopyPropagation {
           out.stack = Unknown :: out.stack.drop(i.consumed)
 
         case CALL_METHOD(method, style) => style match {
-          case Dynamic =>
+          case Dynamic | InvokeDynamic =>
             out = simulateCall(in, method, false)
 
           case Static(onInstance) =>
             if (onInstance) {
               val obj = out.stack.drop(method.info.paramTypes.length).head
 //              if (method.isPrimaryConstructor) {
-              if (method.isPrimaryConstructor/* && isClosureClass(method.owner)*/) {
+              if (method.isPrimaryConstructor) {
                 obj match {
                   case Record(_, bindings) =>
                     for (v <- out.stack.take(method.info.paramTypes.length + 1)
@@ -417,12 +459,15 @@ abstract class CopyPropagation {
      */
     final def cleanReferencesTo(s: copyLattice.State, target: Location) {
       def cleanRecord(r: Record): Record = {
-        r.bindings retain { (loc, value) =>
-          value match {
+        retain(r.bindings) { (loc, value) =>
+          (value match {
             case Deref(loc1) if (loc1 == target) => false
             case Boxed(loc1) if (loc1 == target)  => false
             case _ => true
-          }
+          }) && (target match {
+            case Field(AllRecords, sym1) => !(loc == sym1)
+            case _ => true
+          })
         }
         r
       }
@@ -434,12 +479,12 @@ abstract class CopyPropagation {
         case _ => v
       }}
 
-      s.bindings retain { (loc, value) =>
+      retain(s.bindings) { (loc, value) =>
         (value match {
           case Deref(loc1) if (loc1 == target) => false
           case Boxed(loc1) if (loc1 == target) => false
-          case Record(_, _) => 
-            cleanRecord(value.asInstanceOf[Record]);
+          case rec @ Record(_, _) =>
+            cleanRecord(rec);
             true
           case _ => true
         }) && 
@@ -470,21 +515,32 @@ abstract class CopyPropagation {
     }
 
     /** Drop everything known about mutable record fields.
-     *
-     *  @param state ...
+     *  
+     *  A simple escape analysis would help here. Some of the records we 
+     *  track never leak to other methods, therefore they can not be changed.
+     *  We should not drop their bindings in this case. A closure object 
+     *  would be such an example. Some complications: 
+     * 
+     *   - outer pointers. An closure escapes as an outer pointer to another
+     *     nested closure.
      */
     final def invalidateRecords(state: copyLattice.State) {
+      def shouldRetain(sym: Symbol): Boolean = {
+        if (sym.hasFlag(symtab.Flags.MUTABLE))
+          log("dropping binding for " + sym.fullName)
+        !sym.hasFlag(symtab.Flags.MUTABLE)
+      }
       state.stack = state.stack map { v => v match {
         case Record(cls, bindings) =>
-          bindings.retain { (sym: Symbol, v: Value) => !sym.hasFlag(symtab.Flags.MUTABLE) }
+          retain(bindings) { (sym, _) => shouldRetain(sym) }
           Record(cls, bindings)
         case _ => v
       }}
 
-      state.bindings retain {(loc, value) =>
+      retain(state.bindings) { (loc, value) =>
         value match {
-          case Deref(Field(_, _)) => false
-          case Boxed(Field(_, _)) => false
+          case Deref(Field(rec, sym)) => shouldRetain(sym)
+          case Boxed(Field(rec, sym)) => shouldRetain(sym)
           case _ => true
         }
       }
@@ -518,7 +574,7 @@ abstract class CopyPropagation {
       // this relies on having the same order in paramAccessors and
       // the arguments on the stack. It should be the same!
       for ((p, i) <- paramAccessors.zipWithIndex) {
-//        assert(p.tpe == paramTypes(i), "In: " + ctor.fullNameString
+//        assert(p.tpe == paramTypes(i), "In: " + ctor.fullName
 //               + " having acc: " + (paramAccessors map (_.tpe))+ " vs. params" + paramTypes
 //               + "\n\t failed at pos " + i + " with " + p.tpe + " == " + paramTypes(i))
         if (p.tpe == paramTypes(i))
@@ -530,18 +586,6 @@ abstract class CopyPropagation {
       bindings
     }
 
-    /** Is <code>cls</code> a closure class?
-     *
-     *  @param cls ...
-     *  @return    ...
-     */
-    final def isClosureClass(cls: Symbol): Boolean = 
-        cls.isFinal &&
-        cls.tpe.parents.exists { t => 
-          val TypeRef(_, sym, _) = t;
-          definitions.FunctionClass exists sym.==
-        }
-
     /** Is symbol <code>m</code> a pure method?
      *
      *  @param m ...
diff --git a/src/compiler/scala/tools/nsc/backend/icode/analysis/DataFlowAnalysis.scala b/src/compiler/scala/tools/nsc/backend/icode/analysis/DataFlowAnalysis.scala
index 2036802..471bff6 100644
--- a/src/compiler/scala/tools/nsc/backend/icode/analysis/DataFlowAnalysis.scala
+++ b/src/compiler/scala/tools/nsc/backend/icode/analysis/DataFlowAnalysis.scala
@@ -1,14 +1,13 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
 
-// $Id: DataFlowAnalysis.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.tools.nsc.backend.icode.analysis
+package scala.tools.nsc
+package backend.icode.analysis
 
-import scala.collection.jcl.{HashMap, Set, HashSet, LinkedHashSet}
-import scala.collection.mutable.Map
+import scala.collection.mutable.{Map, HashMap, Set, HashSet, LinkedHashSet}
 
 /** A generic framework for data flow analysis.
  */
@@ -56,19 +55,26 @@ trait DataFlowAnalysis[L <: CompleteLattice] {
   def forwardAnalysis(f: (P, lattice.Elem) => lattice.Elem): Unit = try {
     while (!worklist.isEmpty) {
       if (stat) iterations += 1
-//      Console.println("worklist in: " + worklist);
-      val point = worklist.elements.next; worklist -= point; visited += point;
+      //Console.println("worklist in: " + worklist);
+      val point = worklist.iterator.next; worklist -= point; visited += point;
       //Console.println("taking out point: " + point + " worklist out: " + worklist);
       val output = f(point, in(point))
 
       if ((lattice.bottom == out(point)) || output != out(point)) {
-//        Console.println("Output changed at " + point + " from: " + out(point) + " to: " + output + " and they are different: " + (output != out(point)))
+//        Console.println("Output changed at " + point 
+//                        + " from: " + out(point) + " to: " + output 
+//                        + " for input: " + in(point) + " and they are different: " + (output != out(point)))
         out(point) = output
         val succs = point.successors
         succs foreach { p =>
           if (!worklist.contains(p))
             worklist += p;
-          in(p) = lattice.lub(in(p) :: (p.predecessors map out.apply))
+            if (!in.isDefinedAt(p))
+              assert(false, "Invalid successor for: " + point + " successor " + p + " does not exist")
+//          if (!p.exceptionHandlerHeader) {
+//            println("lubbing " + p.predecessors + " outs: " + p.predecessors.map(out.apply).mkString("\n", "\n", ""))
+            in(p) = lattice.lub(/*in(p) :: */(p.predecessors map out.apply), p.exceptionHandlerStart)
+//          }
         }
       }
     }
@@ -87,9 +93,9 @@ trait DataFlowAnalysis[L <: CompleteLattice] {
   def backwardAnalysis(f: (P, lattice.Elem) => lattice.Elem): Unit =
     while (!worklist.isEmpty) {
       if (stat) iterations += 1
-      val point = worklist.elements.next; worklist -= point
+      val point = worklist.iterator.next; worklist -= point
 
-      out(point) = lattice.lub(point.successors map in.apply)
+      out(point) = lattice.lub(point.successors map in.apply, false) // TODO check for exception handlers
       val input = f(point, out(point))
 
       if ((lattice.bottom == in(point)) || input != in(point)) {
diff --git a/src/compiler/scala/tools/nsc/backend/icode/analysis/Liveness.scala b/src/compiler/scala/tools/nsc/backend/icode/analysis/Liveness.scala
index 392663a..101bb81 100644
--- a/src/compiler/scala/tools/nsc/backend/icode/analysis/Liveness.scala
+++ b/src/compiler/scala/tools/nsc/backend/icode/analysis/Liveness.scala
@@ -1,11 +1,11 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
 
-// $Id: Liveness.scala 16881 2009-01-09 16:28:11Z cunei $
 
-package scala.tools.nsc.backend.icode.analysis
+package scala.tools.nsc
+package backend.icode.analysis
 
 import scala.collection.mutable.{HashMap, Map}
 import scala.collection.immutable.{Set, ListSet}
@@ -32,7 +32,7 @@ abstract class Liveness {
       override def equals(that: Any): Boolean = this eq that.asInstanceOf[AnyRef]
     }
 
-    def lub2(a: Elem, b: Elem): Elem = a ++ b
+    def lub2(exceptional: Boolean)(a: Elem, b: Elem): Elem = a ++ b
   }
 
   final class LivenessAnalysis extends DataFlowAnalysis[livenessLattice.type] {
@@ -70,7 +70,7 @@ abstract class Liveness {
     def genAndKill(b: BasicBlock): (Set[Local], Set[Local]) = {
       var genSet = new ListSet[Local]
       var killSet = new ListSet[Local]
-      for (i <- b.toList) i match {
+      for (i <- b) i match {
         case LOAD_LOCAL(local)  if (!killSet(local)) => genSet = genSet + local
         case STORE_LOCAL(local) if (!genSet(local))  => killSet = killSet + local
         case _ => ()
diff --git a/src/compiler/scala/tools/nsc/backend/icode/analysis/LubError.scala b/src/compiler/scala/tools/nsc/backend/icode/analysis/LubError.scala
deleted file mode 100644
index cf55ca3..0000000
--- a/src/compiler/scala/tools/nsc/backend/icode/analysis/LubError.scala
+++ /dev/null
@@ -1,12 +0,0 @@
-/* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
- * @author  Martin Odersky
- */
-
-// $Id: LubError.scala 16894 2009-01-13 13:09:41Z cunei $
-
-package scala.tools.nsc.backend.icode.analysis
-
-class LubError(a: Any, b: Any, msg: String) extends Exception {
-  override def toString() = "Lub error: " + msg + a + b
-}
diff --git a/src/compiler/scala/tools/nsc/backend/icode/analysis/LubException.scala b/src/compiler/scala/tools/nsc/backend/icode/analysis/LubException.scala
new file mode 100644
index 0000000..6cdee7e
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/backend/icode/analysis/LubException.scala
@@ -0,0 +1,12 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
+ * @author  Martin Odersky
+ */
+
+
+package scala.tools.nsc
+package backend.icode.analysis
+
+class LubException(a: Any, b: Any, msg: String) extends Exception {
+  override def toString() = "Lub error: " + msg + a + b
+}
diff --git a/src/compiler/scala/tools/nsc/backend/icode/analysis/ProgramPoint.scala b/src/compiler/scala/tools/nsc/backend/icode/analysis/ProgramPoint.scala
index fa633bd..a9a09a7 100644
--- a/src/compiler/scala/tools/nsc/backend/icode/analysis/ProgramPoint.scala
+++ b/src/compiler/scala/tools/nsc/backend/icode/analysis/ProgramPoint.scala
@@ -1,11 +1,11 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
 
-// $Id: ProgramPoint.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.tools.nsc.backend.icode.analysis
+package scala.tools.nsc
+package backend.icode.analysis
 
 /** Program points are locations in the program where we want to
  *  assert certain properties through data flow analysis, e.g.
@@ -14,4 +14,5 @@ package scala.tools.nsc.backend.icode.analysis
 trait ProgramPoint[a <: ProgramPoint[a]] {
   def predecessors: List[a]
   def successors: List[a]
+  def exceptionHandlerStart: Boolean
 }
diff --git a/src/compiler/scala/tools/nsc/backend/icode/analysis/ReachingDefinitions.scala b/src/compiler/scala/tools/nsc/backend/icode/analysis/ReachingDefinitions.scala
index d8e3329..a385465 100644
--- a/src/compiler/scala/tools/nsc/backend/icode/analysis/ReachingDefinitions.scala
+++ b/src/compiler/scala/tools/nsc/backend/icode/analysis/ReachingDefinitions.scala
@@ -1,14 +1,14 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
 
-// $Id: ReachingDefinitions.scala 16881 2009-01-09 16:28:11Z cunei $
 
-package scala.tools.nsc.backend.icode.analysis
+package scala.tools.nsc
+package backend.icode.analysis
 
 import scala.collection.immutable.{Set, ListSet, HashSet}
-import scala.collection.jcl.{HashMap, Map}
+import scala.collection.mutable.{HashMap, Map}
 
 /** Compute reaching definitions. We are only interested in reaching
  *  definitions for local variables, since values on the stack
@@ -37,24 +37,24 @@ abstract class ReachingDefinitions {
     }, Nil)
 
     /** The least upper bound is set inclusion for locals, and pairwise set inclusion for stacks. */
-    def lub2(a: Elem, b: Elem): Elem = 
+    def lub2(exceptional: Boolean)(a: Elem, b: Elem): Elem = 
       if (bottom == a) b
       else if (bottom == b) a
       else {
         val locals = a.vars ++ b.vars
-        val stack = if (a.stack == Nil) 
-          b.stack
-        else if (b.stack == Nil) a.stack 
-        else List.map2(a.stack, b.stack) (_ ++ _)
+        val stack =
+          if (a.stack == Nil) b.stack
+          else if (b.stack == Nil) a.stack 
+          else (a.stack, b.stack).zipped map (_ ++ _)
         
-        val res = IState(locals, stack)
-      
-//        Console.println("\tlub2: " + a + ", " + b)
-//        Console.println("\tis: " + res)
-      
-//        if (res._1 eq bottom._1) (new ListSet[Definition], Nil)
-//        else res
-        res
+        IState(locals, stack)
+        
+        // val res = IState(locals, stack)
+        // Console.println("\tlub2: " + a + ", " + b)
+        // Console.println("\tis: " + res)
+        // if (res._1 eq bottom._1) (new ListSet[Definition], Nil)
+        // else res
+        // res
       }
   }
 
@@ -104,7 +104,7 @@ abstract class ReachingDefinitions {
     def genAndKill(b: BasicBlock): (Set[Definition], Set[Local]) = {
       var genSet: Set[Definition] = new HashSet
       var killSet: Set[Local] = new HashSet
-      for (val (i, idx) <- b.toList.zipWithIndex) i match {
+      for ((i, idx) <- b.toList.zipWithIndex) i match {
         case STORE_LOCAL(local) => 
           killSet = killSet + local
           genSet  = updateReachingDefinition(b, idx, genSet)
@@ -118,7 +118,7 @@ abstract class ReachingDefinitions {
       var drops = 0
       var stackOut: List[Set[(BasicBlock, Int)]] = Nil
       
-      for (val (instr, idx) <- b.toList.zipWithIndex) {
+      for ((instr, idx) <- b.toList.zipWithIndex) {
         if (instr == LOAD_EXCEPTION()) 
           ()
         else if (instr.consumed > depth) {
@@ -132,7 +132,7 @@ abstract class ReachingDefinitions {
         var prod = instr.produced
         depth = depth + prod
         while (prod > 0) {
-          stackOut = (new collection.immutable.Set1((b, idx))) :: stackOut
+          stackOut = collection.immutable.Set((b, idx)) :: stackOut
           prod = prod - 1
         }
       }
@@ -184,7 +184,7 @@ abstract class ReachingDefinitions {
 
       var prod = instr.produced
       while (prod > 0) {
-        stack = (new collection.immutable.Set1((b, idx))) :: stack
+        stack = collection.immutable.Set((b, idx)) :: stack
         prod -= 1
       }
 
@@ -229,7 +229,7 @@ abstract class ReachingDefinitions {
     } else {
       val stack = this.in(bb).stack
       assert(stack.length >= m, "entry stack is too small, expected: " + m + " found: " + stack)
-      stack.take(m) flatMap (_.toList)
+      stack.drop(depth).take(m) flatMap (_.toList)
     }
 
     /** Return the definitions that produced the topmost 'm' elements on the stack,
diff --git a/src/compiler/scala/tools/nsc/backend/icode/analysis/TypeFlowAnalysis.scala b/src/compiler/scala/tools/nsc/backend/icode/analysis/TypeFlowAnalysis.scala
index 76711e5..b4348f3 100644
--- a/src/compiler/scala/tools/nsc/backend/icode/analysis/TypeFlowAnalysis.scala
+++ b/src/compiler/scala/tools/nsc/backend/icode/analysis/TypeFlowAnalysis.scala
@@ -1,11 +1,11 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
 
-// $Id: TypeFlowAnalysis.scala 16881 2009-01-09 16:28:11Z cunei $
 
-package scala.tools.nsc.backend.icode.analysis
+package scala.tools.nsc
+package backend.icode.analysis
 
 import scala.collection.{mutable, immutable}
 
@@ -28,7 +28,7 @@ abstract class TypeFlowAnalysis {
     def top    = Object
     def bottom = All
 
-    def lub2(a: Elem, b: Elem) =
+    def lub2(exceptional: Boolean)(a: Elem, b: Elem) =
       if (a eq bottom) b
       else if (b eq bottom) a
       else icodes.lub(a, b)
@@ -45,15 +45,14 @@ abstract class TypeFlowAnalysis {
     override val bottom = new TypeStack
     val exceptionHandlerStack: TypeStack = new TypeStack(List(REFERENCE(definitions.AnyRefClass)))
 
-    def lub2(s1: TypeStack, s2: TypeStack) = {
+    def lub2(exceptional: Boolean)(s1: TypeStack, s2: TypeStack) = {
       if (s1 eq bottom) s2
       else if (s2 eq bottom) s1
-      else if (s1 eq exceptionHandlerStack) s1
-      else if (s2 eq exceptionHandlerStack) s2
+      else if ((s1 eq exceptionHandlerStack) || (s2 eq exceptionHandlerStack)) Predef.error("merging with exhan stack") 
       else {
-        if (s1.length != s2.length)
-          throw new CheckerError("Incompatible stacks: " + s1 + " and " + s2);
-        new TypeStack(List.map2(s1.types, s2.types) (icodes.lub))
+//        if (s1.length != s2.length)
+//          throw new CheckerException("Incompatible stacks: " + s1 + " and " + s2);
+        new TypeStack((s1.types, s2.types).zipped map icodes.lub)
       }
     }
   }
@@ -80,24 +79,30 @@ abstract class TypeFlowAnalysis {
 
     override val top    = new Elem(new VarBinding, typeStackLattice.top)
     override val bottom = new Elem(new VarBinding, typeStackLattice.bottom)
-    
-    def lub2(a: Elem, b: Elem) = {
+
+//    var lubs = 0
+
+    def lub2(exceptional: Boolean)(a: Elem, b: Elem) = {
       val IState(env1, s1) = a
       val IState(env2, s2) = b
 
+//      lubs += 1
+
       val resultingLocals = new VarBinding
 
-      for (binding1 <- env1.elements) {
+      for (binding1 <- env1.iterator) {
         val tp2 = env2(binding1._1)
-        resultingLocals += (binding1._1 -> typeLattice.lub2(binding1._2, tp2))
+        resultingLocals += ((binding1._1, typeLattice.lub2(exceptional)(binding1._2, tp2)))
       }
 
-      for (binding2 <- env2.elements if resultingLocals(binding2._1) eq typeLattice.bottom) {
+      for (binding2 <- env2.iterator if resultingLocals(binding2._1) eq typeLattice.bottom) {
         val tp1 = env1(binding2._1)
-        resultingLocals += (binding2._1 -> typeLattice.lub2(binding2._2, tp1))
+        resultingLocals += ((binding2._1, typeLattice.lub2(exceptional)(binding2._2, tp1)))
       }
 
-      IState(resultingLocals, typeStackLattice.lub2(a.stack, b.stack))
+      IState(resultingLocals,
+        if (exceptional) typeStackLattice.exceptionHandlerStack
+        else typeStackLattice.lub2(exceptional)(a.stack, b.stack))
     }
   }
 
@@ -116,7 +121,7 @@ abstract class TypeFlowAnalysis {
     /** Initialize the in/out maps for the analysis of the given method. */
     def init(m: icodes.IMethod) {
       this.method = m
-
+      //typeFlowLattice.lubs = 0
       init {
         worklist += m.code.startBlock
         worklist ++= (m.exh map (_.startBlock))
@@ -124,6 +129,12 @@ abstract class TypeFlowAnalysis {
           in(b)  = typeFlowLattice.bottom
           out(b) = typeFlowLattice.bottom
         }
+
+        // start block has var bindings for each of its parameters
+        val entryBindings = new VarBinding
+        m.params.foreach(p => entryBindings += ((p, p.kind)))
+        in(m.code.startBlock) = lattice.IState(entryBindings, typeStackLattice.bottom)
+
         m.exh foreach { e =>
           in(e.startBlock) = lattice.IState(in(e.startBlock).vars, typeStackLattice.exceptionHandlerStack)
         }
@@ -160,14 +171,17 @@ abstract class TypeFlowAnalysis {
 
     def run = {
       timer.start
+//      icodes.lubs0 = 0
       forwardAnalysis(blockTransfer)
-      timer.stop
+      val t = timer.stop
       if (settings.debug.value) {
         linearizer.linearize(method).foreach(b => if (b != method.code.startBlock)
           assert(visited.contains(b), 
             "Block " + b + " in " + this.method + " has input equal to bottom -- not visited? .." + visited));
       }
-      //println("iterations: " + iterations + " for " + method.code.blocks.size)
+//      log("" + method.symbol.fullName + " ["  + method.code.blocks.size + " blocks] "
+//              + "\n\t" + iterations + " iterations: " + t + " ms."
+//              + "\n\tlubs: " + typeFlowLattice.lubs + " out of which " + icodes.lubs0 + " typer lubs")
     }
 
     def blockTransfer(b: BasicBlock, in: lattice.Elem): lattice.Elem = {
@@ -363,7 +377,7 @@ abstract class TypeFlowAnalysis {
         new TransferFunction(consumed, gens)
       }
       
-      for (val b <- blocks) {
+      for (b <- blocks) {
         flowFun = flowFun + (b -> transfer(b))
       }
     }
@@ -374,10 +388,10 @@ abstract class TypeFlowAnalysis {
       val bindings = out.vars
       val stack = out.stack
 
-//      if (settings.debug.value) {
-//        Console.println("Stack: " + stack);
-//        Console.println(i);
-//      } 
+      if (settings.debug.value) {
+        Console.println("[before] Stack: " + stack);
+        Console.println(i);
+      }
       i match {
 
         case THIS(clasz) =>
@@ -387,9 +401,13 @@ abstract class TypeFlowAnalysis {
           stack push toTypeKind(const.tpe)
 
         case LOAD_ARRAY_ITEM(kind) =>
-          val Pair(idxKind, ARRAY(elem)) = stack.pop2
-          assert(idxKind == INT || idxKind == CHAR || idxKind == SHORT || idxKind == BYTE)
-          stack.push(elem)
+          stack.pop2 match {
+            case (idxKind, ARRAY(elem)) =>
+              assert(idxKind == INT || idxKind == CHAR || idxKind == SHORT || idxKind == BYTE)
+              stack.push(elem)
+            case (_, _) =>
+              stack.push(kind)
+          }
 
         case LOAD_LOCAL(local) =>
           val t = bindings(local)
@@ -470,7 +488,7 @@ abstract class TypeFlowAnalysis {
           }
 
         case CALL_METHOD(method, style) => style match {
-          case Dynamic =>
+          case Dynamic | InvokeDynamic =>
             stack.pop(1 + method.info.paramTypes.length)
             stack.push(toTypeKind(method.info.resultType))
 
@@ -619,7 +637,7 @@ abstract class TypeFlowAnalysis {
         val stack = out.stack
         
         out.stack.pop(consumed)
-        for (val g <- gens) g match {
+        for (g <- gens) g match {
           case Bind(l, t) =>
             out.vars += (l -> t.getKind(in))
           case Push(t) =>
diff --git a/src/compiler/scala/tools/nsc/backend/jvm/GenJVM.scala b/src/compiler/scala/tools/nsc/backend/jvm/GenJVM.scala
index a7c9178..dd673df 100644
--- a/src/compiler/scala/tools/nsc/backend/jvm/GenJVM.scala
+++ b/src/compiler/scala/tools/nsc/backend/jvm/GenJVM.scala
@@ -1,22 +1,23 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Iulian Dragos
  */
 
-// $Id: GenJVM.scala 17500 2009-04-14 16:13:39Z dragos $
 
-package scala.tools.nsc.backend.jvm
+package scala.tools.nsc
+package backend.jvm
 
-import java.io.{DataOutputStream, File, OutputStream}
 import java.nio.ByteBuffer
 
 import scala.collection.immutable.{Set, ListSet}
 import scala.collection.mutable.{Map, HashMap, HashSet}
 import scala.tools.nsc.io.AbstractFile
 import scala.tools.nsc.symtab._
-import scala.tools.nsc.util.{Position, NoPosition}
+import scala.tools.nsc.symtab.classfile.ClassfileConstants._
 
 import ch.epfl.lamp.fjbg._
+import java.io.{ByteArrayOutputStream, DataOutputStream, File, OutputStream}
+import reflect.generic.{PickleFormat, PickleBuffer}
 
 /** This class ...
  *
@@ -31,35 +32,38 @@ abstract class GenJVM extends SubComponent {
 
   val phaseName = "jvm"
   
-  /**
-   * Directory where output will be written.  By default it
-   * is the directory specified by Settings.outdir.
-   */
-  var outputDir: AbstractFile = AbstractFile.getDirectory(settings.outdir.value)
-
   /** Create a new phase */
-  override def newPhase(p: Phase) = new JvmPhase(p)
+  override def newPhase(p: Phase): Phase = new JvmPhase(p)
 
   /** JVM code generation phase
    */
-  class JvmPhase(prev: Phase) extends StdPhase(prev) {
+  class JvmPhase(prev: Phase) extends ICodePhase(prev) {
 
+    def name = phaseName
     override def erasedTypes = true
     object codeGenerator extends BytecodeGenerator
 
     override def run {
       if (settings.debug.value) inform("[running phase " + name + " on icode]")
       if (settings.Xdce.value)
-        icodes.classes.retain { (sym: Symbol, cls: IClass) => !inliner.isClosureClass(sym) || deadCode.liveClosures(sym) } 
+        for ((sym, cls) <- icodes.classes ; if inliner.isClosureClass(sym) && !deadCode.liveClosures(sym))
+          icodes.classes -= sym
 
-      classes.values foreach codeGenerator.genClass
+      classes.values foreach apply
     }
 
-    override def apply(unit: CompilationUnit) {
-      abort("JVM works on icode classes, not on compilation units!")
+    override def apply(cls: IClass) {
+      codeGenerator.genClass(cls)
     }
   }
 
+  /** Return the suffix of a class name */
+  def moduleSuffix(sym: Symbol) =
+    if (sym.hasFlag(Flags.MODULE) && !sym.isMethod &&
+       !sym.isImplClass && !sym.hasFlag(Flags.JAVA)) "$"
+    else "";
+
+
   var pickledBytes = 0 // statistics
 
   /**
@@ -67,13 +71,23 @@ abstract class GenJVM extends SubComponent {
    *
    */
   class BytecodeGenerator {
+    import JAccessFlags._
+    
+    def debugLevel = settings.debuginfo.indexOfChoice
+
     val MIN_SWITCH_DENSITY = 0.7
-    val StringBuilderClass = "scala.StringBuilder"
+    val INNER_CLASSES_FLAGS =
+      (ACC_PUBLIC | ACC_PRIVATE | ACC_PROTECTED | ACC_STATIC | ACC_FINAL | ACC_INTERFACE | ACC_ABSTRACT)
+    val StringBuilderClass = definitions.getClass2("scala.StringBuilder", "scala.collection.mutable.StringBuilder").fullName
     val BoxesRunTime = "scala.runtime.BoxesRunTime"
 
     val StringBuilderType = new JObjectType(StringBuilderClass)
-    val toStringType = new JMethodType(JObjectType.JAVA_LANG_STRING, JType.EMPTY_ARRAY)
-
+    val toStringType      = new JMethodType(JObjectType.JAVA_LANG_STRING, JType.EMPTY_ARRAY)
+    val arrayCloneType    = new JMethodType(JObjectType.JAVA_LANG_OBJECT, JType.EMPTY_ARRAY)
+    val MethodTypeType    = new JObjectType("java.dyn.MethodType")
+    val JavaLangClassType = new JObjectType("java.lang.Class")
+    val MethodHandleType  = new JObjectType("java.dyn.MethodHandle")
+    
     // Scala attributes
     val SerializableAttr = definitions.SerializableAttr
     val SerialVersionUID = definitions.getClass("scala.SerialVersionUID")
@@ -81,7 +95,6 @@ abstract class GenJVM extends SubComponent {
     val TransientAtt     = definitions.getClass("scala.transient")
     val VolatileAttr     = definitions.getClass("scala.volatile")
     val RemoteAttr       = definitions.getClass("scala.remote")
-    val ThrowsAttr       = definitions.getClass("scala.throws")
     val BeanInfoAttr     = definitions.getClass("scala.reflect.BeanInfo")
     val BeanInfoSkipAttr = definitions.getClass("scala.reflect.BeanInfoSkip")
     val BeanDisplayNameAttr = definitions.getClass("scala.reflect.BeanDisplayName")
@@ -91,6 +104,16 @@ abstract class GenJVM extends SubComponent {
     lazy val RemoteInterface = definitions.getClass("java.rmi.Remote")
     lazy val RemoteException = definitions.getClass("java.rmi.RemoteException").tpe
 
+
+    val versionPickle = {
+      val vp = new PickleBuffer(new Array[Byte](16), -1, 0)
+      assert(vp.writeIndex == 0)
+      vp.writeNat(PickleFormat.MajorVersion)
+      vp.writeNat(PickleFormat.MinorVersion)
+      vp.writeNat(0)
+      vp
+    }
+
     var clasz: IClass = _
     var method: IMethod = _
     var jclass: JClass = _
@@ -99,13 +122,11 @@ abstract class GenJVM extends SubComponent {
 
     var innerClasses: Set[Symbol] = ListSet.empty // referenced inner classes
 
-    val fjbgContext =
-      if (settings.target.value == "jvm-1.5") new FJBGContext(49, 0)
-      else new FJBGContext()
+    val fjbgContext = new FJBGContext(49, 0)
 
-    val emitSource = settings.debuginfo.level >= 1
-    val emitLines  = settings.debuginfo.level >= 2
-    val emitVars   = settings.debuginfo.level >= 3
+    val emitSource = debugLevel >= 1
+    val emitLines  = debugLevel >= 2
+    val emitVars   = debugLevel >= 3
 
     /** Write a class to disk, adding the Scala signature (pickled type information) and
      *  inner classes.
@@ -114,36 +135,47 @@ abstract class GenJVM extends SubComponent {
      * @param sym    The corresponding symbol, used for looking up pickled information
      */
     def emitClass(jclass: JClass, sym: Symbol) {
-      def addScalaAttr(sym: Symbol): Unit = currentRun.symData.get(sym) match {
-        case Some(pickle) =>
-          val scalaAttr = fjbgContext.JOtherAttribute(jclass,
-                                                  jclass,
-                                                  nme.ScalaSignatureATTR.toString,
-                                                  pickle.bytes,
-                                                  pickle.writeIndex)
-          pickledBytes = pickledBytes + pickle.writeIndex
-          jclass.addAttribute(scalaAttr)
-          currentRun.symData -= sym
-          currentRun.symData -= sym.linkedSym
-          //System.out.println("Generated ScalaSig Attr for " + sym)//debug
-        case _ =>
-          val markerAttr = getMarkerAttr(jclass)
-          jclass.addAttribute(markerAttr)
-          log("Could not find pickle information for " + sym)
-      }
-      if (!(jclass.getName().endsWith("$") && sym.isModuleClass))
-        addScalaAttr(if (isTopLevelModule(sym)) sym.sourceModule else sym);
       addInnerClasses(jclass)
-
-      val outfile = getFile(jclass, ".class")
-      val outstream = new DataOutputStream(outfile.output)
+      val outfile = getFile(sym, jclass, ".class")
+      val outstream = new DataOutputStream(outfile.bufferedOutput)
       jclass.writeTo(outstream)
       outstream.close()
       informProgress("wrote " + outfile)
     }
 
-    private def getMarkerAttr(jclass: JClass): JOtherAttribute =
-      fjbgContext.JOtherAttribute(jclass, jclass, nme.ScalaATTR.toString, new Array[Byte](0), 0)
+    /** Returns the ScalaSignature annotation if it must be added to this class, none otherwise; furthermore, it adds to
+      * jclass the ScalaSig marker attribute (marking that a scala signature annotation is present) or the Scala marker
+      * attribute (marking that the signature for this class is in another file). The annotation that is returned by
+      * this method must be added to the class' annotations list when generating them.
+      * @param jclass The class file that is being readied.
+      * @param sym    The symbol for which the signature has been entered in the symData map. This is different than the
+      *               symbol that is being generated in the case of a mirror class.
+      * @return       An option that is:
+      *                - defined and contains an annotation info of the ScalaSignature type, instantiated with the
+      *                  pickle signature for sym (a ScalaSig marker attribute has been written);
+      *                - undefined if the jclass/sym couple must not contain a signature (a Scala marker attribute has
+      *                  been written). */
+    def scalaSignatureAddingMarker(jclass: JClass, sym: Symbol): Option[AnnotationInfo] =
+      currentRun.symData.get(sym) match {
+        case Some(pickle) if !jclass.getName().endsWith("$") =>
+          val scalaAttr =
+            fjbgContext.JOtherAttribute(jclass, jclass, nme.ScalaSignatureATTR.toString,
+                                        versionPickle.bytes, versionPickle.writeIndex)
+          jclass.addAttribute(scalaAttr)
+          val scalaAnnot = {
+            val sigBytes = ScalaSigBytes(pickle.bytes.take(pickle.writeIndex))
+            AnnotationInfo(sigBytes.sigAnnot, Nil, List((nme.bytes, sigBytes)))
+          }
+          pickledBytes = pickledBytes + pickle.writeIndex
+          currentRun.symData -= sym
+          currentRun.symData -= sym.companionSymbol
+          Some(scalaAnnot)
+        case _ =>
+          val markerAttr =
+            fjbgContext.JOtherAttribute(jclass, jclass, nme.ScalaATTR.toString, new Array[Byte](0), 0)
+          jclass.addAttribute(markerAttr)
+          None
+      }
     
     var serialVUID: Option[Long] = None
     var remoteClass: Boolean = false
@@ -161,21 +193,20 @@ abstract class GenJVM extends SubComponent {
       if (parents.isEmpty)
         parents = definitions.ObjectClass.tpe :: parents;
 
-      if (!forCLDC)
-        for (val attr <- c.symbol.attributes) attr match {
-          case AnnotationInfo(tp, _, _) if tp.typeSymbol == SerializableAttr =>
-            parents = parents ::: List(definitions.SerializableClass.tpe)
-          case AnnotationInfo(tp, _, _) if tp.typeSymbol == CloneableAttr =>
-            parents = parents ::: List(CloneableClass.tpe)
-          case AnnotationInfo(tp, value :: _, _) if tp.typeSymbol == SerialVersionUID =>
-            serialVUID = Some(value.constant.get.longValue)
-          case AnnotationInfo(tp, _, _) if tp.typeSymbol == RemoteAttr =>
-            parents = parents ::: List(RemoteInterface.tpe)
-            remoteClass = true
-          case _ => ()
-        }
+      for (annot <- c.symbol.annotations) annot match {
+        case AnnotationInfo(tp, _, _) if tp.typeSymbol == SerializableAttr =>
+          parents = parents ::: List(definitions.SerializableClass.tpe)
+        case AnnotationInfo(tp, _, _) if tp.typeSymbol == CloneableAttr =>
+          parents = parents ::: List(CloneableClass.tpe)
+        case AnnotationInfo(tp, Literal(const) :: _, _) if tp.typeSymbol == SerialVersionUID =>
+          serialVUID = Some(const.longValue)
+        case AnnotationInfo(tp, _, _) if tp.typeSymbol == RemoteAttr =>
+          parents = parents ::: List(RemoteInterface.tpe)
+          remoteClass = true
+        case _ => ()
+      }
 
-      parents = parents.removeDuplicates
+      parents = parents.distinct
 
       if (parents.length > 1) {
         ifaces = new Array[String](parents.length - 1)
@@ -188,41 +219,52 @@ abstract class GenJVM extends SubComponent {
                                   javaName(parents(0).typeSymbol),
                                   ifaces,
                                   c.cunit.source.toString)
-      if (jclass.getName.endsWith("$"))
-        jclass.addAttribute(getMarkerAttr(jclass))
       
-      if (isStaticModule(c.symbol) || serialVUID != None) {
+      if (isStaticModule(c.symbol) || serialVUID != None || clasz.bootstrapClass.isDefined) {
         if (isStaticModule(c.symbol))
             addModuleInstanceField;
-        addStaticInit(jclass)
+        addStaticInit(jclass, c.lookupStaticCtor)
         
         if (isTopLevelModule(c.symbol)) {
-          if (c.symbol.linkedClassOfModule == NoSymbol)
+          if (c.symbol.companionClass == NoSymbol)
             dumpMirrorClass(c.symbol, c.cunit.source.toString);
           else
             log("No mirror class for module with linked class: " +
-                c.symbol.fullNameString)
+                c.symbol.fullName)
         }
-      } /*
-	    disabling for now because it breaks compiler. Try: 
-        fsc symtab/Types.scala -- you'll get 9 errors in phase GenJVM that
-        class files are not found.
-        else if (c.symbol.linkedModuleOfClass != NoSymbol && !c.symbol.hasFlag(Flags.INTERFACE)) {
-        log("Adding forwarders to existing class " + c.symbol + " found in module " + c.symbol.linkedModuleOfClass)
-        addForwarders(jclass, c.symbol.linkedModuleOfClass.moduleClass)
-      } */
+      }
+      else {
+        if (c.containsStaticCtor) addStaticInit(jclass, c.lookupStaticCtor)
 
+        // it must be a top level class (name contains no $s)
+        def isCandidateForForwarders(sym: Symbol): Boolean =
+          atPhase (currentRun.picklerPhase.next) {
+            !(sym.name.toString contains '$') && (sym hasFlag Flags.MODULE) && !sym.isImplClass && !sym.isNestedClass
+          }
+        
+        val lmoc = c.symbol.companionModule
+        // add static forwarders if there are no name conflicts; see bugs #363 and #1735
+        if (lmoc != NoSymbol && !c.symbol.hasFlag(Flags.INTERFACE)) {
+          if (isCandidateForForwarders(lmoc) && !settings.noForwarders.value) {
+            log("Adding forwarders to existing class '%s' found in module '%s'".format(c.symbol, lmoc))
+            addForwarders(jclass, lmoc.moduleClass)
+          }
+        }
+      }
+        
+      if (clasz.bootstrapClass.isDefined) jclass.setBootstrapClass(clasz.bootstrapClass.get)
       clasz.fields foreach genField
       clasz.methods foreach genMethod
 
-      addGenericSignature(jclass, c.symbol)
-      addAnnotations(jclass, c.symbol.attributes)
-
+      val ssa = scalaSignatureAddingMarker(jclass, c.symbol)
+      addGenericSignature(jclass, c.symbol, c.symbol.owner)
+      addAnnotations(jclass, c.symbol.annotations ++ ssa)
       emitClass(jclass, c.symbol)
       
-      if (c.symbol.attributes.exists(_.atp.typeSymbol == BeanInfoAttr))
+      if (c.symbol hasAnnotation BeanInfoAttr)
         genBeanInfoClass(c) 
     }
+    
 
     /**
      * Generate a bean info class that describes the given class.
@@ -230,7 +272,7 @@ abstract class GenJVM extends SubComponent {
      * @author Ross Judson (ross.judson at soletta.com)
      */
     def genBeanInfoClass(c: IClass) {      
-      val description = c.symbol.attributes.find(_.atp.typeSymbol == BeanDescriptionAttr)
+      val description = c.symbol.annotations.find(_.atp.typeSymbol == BeanDescriptionAttr)
       // informProgress(description.toString())
 	
       val beanInfoClass = fjbgContext.JClass(javaFlags(c.symbol),
@@ -243,7 +285,7 @@ abstract class GenJVM extends SubComponent {
       for (f <- clasz.fields if f.symbol.hasGetter;
 	         val g = f.symbol.getter(c.symbol);
 	         val s = f.symbol.setter(c.symbol);
-	         if g.isPublic)
+	         if g.isPublic && !(f.symbol.name startsWith "$"))  // inserting $outer breaks the bean
         fieldList = javaName(f.symbol) :: javaName(g) :: (if (s != NoSymbol) javaName(s) else null) :: fieldList
       val methodList = 
 	     for (m <- clasz.methods 
@@ -260,17 +302,17 @@ abstract class GenJVM extends SubComponent {
       val conType = new JMethodType(JType.VOID, Array(javaType(definitions.ClassClass), stringArrayKind, stringArrayKind))
 	
       def push(lst:Seq[String]) {
-	      var fi = 0
-	      for (f <- lst) {
-    	    jcode.emitDUP()
-	        jcode.emitPUSH(fi)
-    	    if (f != null)
-	          jcode.emitPUSH(f)
-	        else
-	          jcode.emitACONST_NULL()
-	        jcode.emitASTORE(strKind)
-	        fi += 1
-	      } 
+        var fi = 0
+        for (f <- lst) {
+          jcode.emitDUP()
+          jcode.emitPUSH(fi)
+          if (f != null)
+            jcode.emitPUSH(f)
+          else
+            jcode.emitACONST_NULL()
+          jcode.emitASTORE(strKind)
+          fi += 1
+        } 
       }
 
       jcode.emitALOAD_0()
@@ -293,8 +335,8 @@ abstract class GenJVM extends SubComponent {
       jcode.emitRETURN()
       
       // write the bean information class file.
-      val outfile = getFile(beanInfoClass, ".class")
-      val outstream = new DataOutputStream(outfile.output)
+      val outfile = getFile(c.symbol, beanInfoClass, ".class")
+      val outstream = new DataOutputStream(outfile.bufferedOutput)
       beanInfoClass.writeTo(outstream)
       outstream.close()
       informProgress("wrote BeanInfo " + outfile)
@@ -309,13 +351,14 @@ abstract class GenJVM extends SubComponent {
       val buf: ByteBuffer = ByteBuffer.allocate(512)
       var nattr = 0
 
-      // put some radom value; the actual number is determined at the end
+      // put some random value; the actual number is determined at the end
       buf.putShort(0xbaba.toShort)
 
-      for (AnnotationInfo(tp, List(exc), _) <- excs.removeDuplicates if tp.typeSymbol == ThrowsAttr) {
+      for (AnnotationInfo(tp, List(exc), _) <- excs.distinct if tp.typeSymbol == definitions.ThrowsClass) {
+        val Literal(const) = exc
         buf.putShort(
           cpool.addClass(
-            javaName(exc.constant.get.typeValue.typeSymbol)).shortValue)
+            javaName(const.typeValue.typeSymbol)).shortValue)
         nattr += 1
       }
 
@@ -324,92 +367,115 @@ abstract class GenJVM extends SubComponent {
       addAttribute(jmethod, nme.ExceptionsATTR, buf)
     }
 
-    /** Whether an annotation should be emitted as a Java annotation */
-    private def shouldEmitAttribute(annot: AnnotationInfo) =
-      (annot.atp.typeSymbol.hasFlag(Flags.JAVA) &&
+    /** Whether an annotation should be emitted as a Java annotation
+     *   .initialize: if 'annot' is read from pickle, atp might be un-initialized
+     */
+    private def shouldEmitAnnotation(annot: AnnotationInfo) =
+      (annot.atp.typeSymbol.initialize.hasFlag(Flags.JAVA) &&
        annot.atp.typeSymbol.isNonBottomSubClass(definitions.ClassfileAnnotationClass) &&
-       annot.isConstant)
-	     
-
-    private def emitAttributes(cpool: JConstantPool, buf: ByteBuffer, attributes: List[AnnotationInfo]): Int = {
-//      val cpool = jclass.getConstantPool()
-
-      def emitElement(const: Constant): Unit = const.tag match {
-        case BooleanTag =>
-          buf.put('Z'.toByte)
-          buf.putShort(cpool.addInteger(if(const.booleanValue) 1 else 0).toShort)
-        case ByteTag    =>
-          buf.put('B'.toByte)
-          buf.putShort(cpool.addInteger(const.byteValue).toShort)
-        case ShortTag   =>
-          buf.put('S'.toByte)
-          buf.putShort(cpool.addInteger(const.shortValue).toShort)
-        case CharTag    =>
-          buf.put('C'.toByte)
-          buf.putShort(cpool.addInteger(const.charValue).toShort)
-        case IntTag     =>
-          buf.put('I'.toByte)
-          buf.putShort(cpool.addInteger(const.intValue).toShort)
-        case LongTag    =>
-          buf.put('J'.toByte)
-          buf.putShort(cpool.addLong(const.longValue).toShort)
-        case FloatTag   =>
-          buf.put('F'.toByte)
-          buf.putShort(cpool.addFloat(const.floatValue).toShort)
-        case DoubleTag  =>
-          buf.put('D'.toByte)
-          buf.putShort(cpool.addDouble(const.doubleValue).toShort)
-        case StringTag  =>
+       annot.args.isEmpty)
+
+    private def emitJavaAnnotations(cpool: JConstantPool, buf: ByteBuffer, annotations: List[AnnotationInfo]): Int = {
+      def emitArgument(arg: ClassfileAnnotArg): Unit = arg match {
+        case LiteralAnnotArg(const) =>
+          const.tag match {
+            case BooleanTag =>
+              buf.put('Z'.toByte)
+              buf.putShort(cpool.addInteger(if(const.booleanValue) 1 else 0).toShort)
+            case ByteTag    =>
+              buf.put('B'.toByte)
+              buf.putShort(cpool.addInteger(const.byteValue).toShort)
+            case ShortTag   =>
+              buf.put('S'.toByte)
+              buf.putShort(cpool.addInteger(const.shortValue).toShort)
+            case CharTag    =>
+              buf.put('C'.toByte)
+              buf.putShort(cpool.addInteger(const.charValue).toShort)
+            case IntTag     =>
+              buf.put('I'.toByte)
+              buf.putShort(cpool.addInteger(const.intValue).toShort)
+            case LongTag    =>
+              buf.put('J'.toByte)
+              buf.putShort(cpool.addLong(const.longValue).toShort)
+            case FloatTag   =>
+              buf.put('F'.toByte)
+              buf.putShort(cpool.addFloat(const.floatValue).toShort)
+            case DoubleTag  =>
+              buf.put('D'.toByte)
+              buf.putShort(cpool.addDouble(const.doubleValue).toShort)
+            case StringTag  =>
+              buf.put('s'.toByte)
+              buf.putShort(cpool.addUtf8(const.stringValue).toShort)
+            case ClassTag   =>
+              buf.put('c'.toByte)
+              buf.putShort(cpool.addUtf8(javaType(const.typeValue).getSignature()).toShort)
+            case EnumTag =>
+              buf.put('e'.toByte)
+              buf.putShort(cpool.addUtf8(javaType(const.tpe).getSignature()).toShort)
+              buf.putShort(cpool.addUtf8(const.symbolValue.name.toString).toShort)
+          }
+
+        case sb at ScalaSigBytes(bytes) if (!sb.isLong) =>
           buf.put('s'.toByte)
-          buf.putShort(cpool.addUtf8(const.stringValue).toShort)
-        case ClassTag   =>
-          buf.put('c'.toByte)
-          buf.putShort(cpool.addUtf8(javaType(const.typeValue).getSignature()).toShort)
-        case EnumTag =>
-          buf.put('e'.toByte)
-          buf.putShort(cpool.addUtf8(javaType(const.tpe).getSignature()).toShort)
-          buf.putShort(cpool.addUtf8(const.symbolValue.name.toString).toShort)
-        case ArrayTag =>
+          buf.putShort(cpool.addUtf8(sb.encodedBytes).toShort)
+
+        case sb at ScalaSigBytes(bytes) if (sb.isLong) =>
           buf.put('['.toByte)
-          val arr = const.arrayValue
-          buf.putShort(arr.length.toShort)
-          for (val elem <- arr) emitElement(elem)
-      }
+          val stringCount = (sb.encodedBytes.length / 65534) + 1
+          buf.putShort(stringCount.toShort)
+          for (i <- 0 until stringCount) {
+            buf.put('s'.toByte)
+            val j = i * 65535
+            val string = sb.encodedBytes.slice(j, j + 65535)
+            buf.putShort(cpool.addUtf8(string).toShort)
+          }
 
-      var nattr = 0
-      val pos = buf.position()
+        case ArrayAnnotArg(args) =>
+          buf.put('['.toByte)
+          buf.putShort(args.length.toShort)
+          args foreach emitArgument
 
-      // put some random value; the actual number of annotations is determined at the end
-      buf.putShort(0xbaba.toShort)
+        case NestedAnnotArg(annInfo) =>
+          buf.put('@'.toByte)
+          emitAnnotation(annInfo)
+      }
 
-      for (attrib at AnnotationInfo(typ, consts, nvPairs) <- attributes; 
-           if shouldEmitAttribute(attrib))
-      {
-        nattr += 1
+      def emitAnnotation(annotInfo: AnnotationInfo) {
+        val AnnotationInfo(typ, args, assocs) = annotInfo
         val jtype = javaType(typ)
         buf.putShort(cpool.addUtf8(jtype.getSignature()).toShort)
-        assert(consts.length <= 1, consts.toString)
-        buf.putShort((consts.length + nvPairs.length).toShort)
-        if (!consts.isEmpty) {
-          buf.putShort(cpool.addUtf8("value").toShort)
-          emitElement(consts.head.constant.get)
-        }
-        for ((name, value) <- nvPairs) {
+        assert(args.isEmpty, args.toString)
+        buf.putShort(assocs.length.toShort)
+        for ((name, value) <- assocs) {
           buf.putShort(cpool.addUtf8(name.toString).toShort)
-          emitElement(value.constant.get)
+          emitArgument(value)
         }
       }
 
+      var nannots = 0
+      val pos = buf.position()
+
+      // put some random value; the actual number of annotations is determined at the end
+      buf.putShort(0xbaba.toShort)
+
+      for (annot <- annotations if shouldEmitAnnotation(annot)) {
+        nannots += 1
+        emitAnnotation(annot)
+      }
+
       // save the number of annotations
-      buf.putShort(pos, nattr.toShort)
-      nattr
+      buf.putShort(pos, nannots.toShort)
+      nannots
     }
 
-    def addGenericSignature(jmember: JMember, sym: Symbol) {
-      if (settings.target.value == "jvm-1.5"
-          && !sym.hasFlag(Flags.EXPANDEDNAME | Flags.SYNTHETIC)
-          && !(sym.isMethod && sym.hasFlag(Flags.LIFTED))) {
-        erasure.javaSig(sym) match {
+    def addGenericSignature(jmember: JMember, sym: Symbol, owner: Symbol) {
+      if (!sym.hasFlag(Flags.EXPANDEDNAME | Flags.SYNTHETIC) 
+          && !(sym.isMethod && sym.hasFlag(Flags.LIFTED))
+          && !(sym.ownerChain exists (_.isImplClass))) {  // @M don't generate java generics sigs for (members of) implementation classes, as they are monomorphic (TODO: ok?)
+        val memberTpe = atPhase(currentRun.erasurePhase)(owner.thisType.memberInfo(sym))
+        // println("addGenericSignature sym: " + sym.fullName + " : " + memberTpe + " sym.info: " + sym.info)
+        // println("addGenericSignature: "+ (sym.ownerChain map (x => (x.name, x.isImplClass))))
+        erasure.javaSig(sym, memberTpe) match {
           case Some(sig) =>
             val index = jmember.getConstantPool().addUtf8(sig).toShort
             if (settings.debug.value && settings.verbose.value) 
@@ -424,31 +490,32 @@ abstract class GenJVM extends SubComponent {
       }
     }
 
-    def addAnnotations(jmember: JMember, attributes: List[AnnotationInfo]) {
-      val toEmit = attributes.filter(shouldEmitAttribute(_))
+    def addAnnotations(jmember: JMember, annotations: List[AnnotationInfo]) {
+      if (annotations.exists(_.atp.typeSymbol == definitions.DeprecatedAttr)) {
+        val attr = jmember.getContext().JOtherAttribute(
+          jmember.getJClass(), jmember, nme.DeprecatedATTR.toString,
+          new Array[Byte](0), 0)
+        jmember.addAttribute(attr)
+      }
 
+      val toEmit = annotations.filter(shouldEmitAnnotation(_))
       if (toEmit.isEmpty) return
 
       val buf: ByteBuffer = ByteBuffer.allocate(2048)
-
-      emitAttributes(jmember.getConstantPool, buf, toEmit)
-
+      emitJavaAnnotations(jmember.getConstantPool, buf, toEmit)
       addAttribute(jmember, nme.RuntimeAnnotationATTR, buf)
     }
 
-    def addParamAnnotations(pattrss: List[List[AnnotationInfo]]) {
-      val attributes = for (attrs <- pattrss) yield
-        for (attr @ AnnotationInfo(tpe, _, _) <- attrs;
-             if attr.isConstant;
-             if tpe.typeSymbol isNonBottomSubClass definitions.ClassfileAnnotationClass) yield attr;
-      if (attributes.forall(_.isEmpty)) return;
+    def addParamAnnotations(jmethod: JMethod, pannotss: List[List[AnnotationInfo]]) {
+      val annotations = pannotss map (annots => annots.filter(shouldEmitAnnotation(_)))
+      if (annotations.forall(_.isEmpty)) return;
 
       val buf: ByteBuffer = ByteBuffer.allocate(2048)
 
       // number of parameters
-      buf.put(attributes.length.toByte)
-      for (attrs <- attributes)
-        emitAttributes(jmethod.getConstantPool, buf, attrs)
+      buf.put(annotations.length.toByte)
+      for (annots <- annotations)
+        emitJavaAnnotations(jmethod.getConstantPool, buf, annots)
 
       addAttribute(jmethod, nme.RuntimeParamAnnotationATTR, buf)
     }
@@ -458,7 +525,7 @@ abstract class GenJVM extends SubComponent {
         return
 
       val length = buf.position();
-      val arr = buf.array().subArray(0, length);
+      val arr = buf.array().slice(0, length);
 
       val attr = jmember.getContext().JOtherAttribute(jmember.getJClass(),
                                                       jmember,
@@ -470,11 +537,12 @@ abstract class GenJVM extends SubComponent {
 
     def addInnerClasses(jclass: JClass) {
       def addOwnInnerClasses(cls: Symbol) {
-        for (sym <- cls.info.decls.elements if sym.isClass)
+        for (sym <- cls.info.decls.iterator if sym.isClass)
           innerClasses = innerClasses + sym;
       }
+
       // add inner classes which might not have been referenced yet
-      atPhase(currentRun.erasurePhase) {
+      atPhase(currentRun.erasurePhase.next) {
         addOwnInnerClasses(clasz.symbol)
         addOwnInnerClasses(clasz.symbol.linkedClassOfClass)
       }
@@ -483,10 +551,10 @@ abstract class GenJVM extends SubComponent {
         val innerClassesAttr = jclass.getInnerClasses()
         // sort them so inner classes succeed their enclosing class
         // to satisfy the Eclipse Java compiler
-        for (innerSym <- innerClasses.toList.sort(_.name.length < _.name.length)) {
+        for (innerSym <- innerClasses.toList sortBy (_.name.length)) {
           var outerName = javaName(innerSym.rawowner)
           // remove the trailing '$'
-          if (outerName.endsWith("$")) 
+          if (outerName.endsWith("$") && isTopLevelModule(innerSym.rawowner)) 
             outerName = outerName.substring(0, outerName.length - 1)
           var flags = javaFlags(innerSym)
           if (innerSym.rawowner.hasFlag(Flags.MODULE))
@@ -495,7 +563,7 @@ abstract class GenJVM extends SubComponent {
           innerClassesAttr.addEntry(javaName(innerSym),
               outerName,
               innerSym.rawname.toString,
-              flags);
+              (flags & INNER_CLASSES_FLAGS));
         }
       }
     }
@@ -511,10 +579,10 @@ abstract class GenJVM extends SubComponent {
 
     def genField(f: IField) {
       if (settings.debug.value)
-        log("Adding field: " + f.symbol.fullNameString);
+        log("Adding field: " + f.symbol.fullName);
       var attributes = 0
 
-      f.symbol.attributes foreach { a => a match {
+      f.symbol.annotations foreach { a => a match {
         case AnnotationInfo(tp, _, _) if tp.typeSymbol == TransientAtt =>
           attributes = attributes | JAccessFlags.ACC_TRANSIENT
         case AnnotationInfo(tp, _, _) if tp.typeSymbol == VolatileAttr =>
@@ -529,12 +597,14 @@ abstract class GenJVM extends SubComponent {
         jclass.addNewField(flags | attributes,
                            javaName(f.symbol),
                            javaType(f.symbol.tpe));
-      addGenericSignature(jfield, f.symbol)
-      addAnnotations(jfield, f.symbol.attributes)
+      addGenericSignature(jfield, f.symbol, clasz.symbol)
+      addAnnotations(jfield, f.symbol.annotations)
     }
 
     def genMethod(m: IMethod) {
-      log("Generating method " + m.symbol.fullNameString)
+      if (m.isStaticCtor) return
+
+      log("Generating method " + m.symbol.fullName)
       method = m
       endPC.clear
       computeLocalVarsIndex(m)
@@ -557,11 +627,6 @@ abstract class GenJVM extends SubComponent {
                                     javaTypes(m.params map (_.kind)),
                                     javaNames(m.params map (_.sym)));
 
-      if (m.symbol.hasFlag(Flags.BRIDGE) && settings.target.value == "jvm-1.4") {
-        jmethod.addAttribute(fjbgContext.JOtherAttribute(jclass, jmethod, "Bridge",
-                                                         new Array[Byte](0)))
-      }
-
       addRemoteException(jmethod, m.symbol)
 
       if (!jmethod.isAbstract() && !method.native) {
@@ -585,7 +650,7 @@ abstract class GenJVM extends SubComponent {
           }
         }
 
-        for (val local <- m.locals; (! m.params.contains(local))) {
+        for (local <- m.locals if ! m.params.contains(local)) {
           if (settings.debug.value)
             log("add local var: " + local);
           jmethod.addNewLocalVariable(javaType(local.kind), javaName(local.sym))
@@ -596,17 +661,17 @@ abstract class GenJVM extends SubComponent {
           genLocalVariableTable(m, jcode);
       }
       
-      addGenericSignature(jmethod, m.symbol)
-      val (excs, others) = splitAnnotations(m.symbol.attributes, ThrowsAttr)
+      addGenericSignature(jmethod, m.symbol, clasz.symbol)
+      val (excs, others) = splitAnnotations(m.symbol.annotations, definitions.ThrowsClass)
       addExceptionsAttribute(jmethod, excs)
       addAnnotations(jmethod, others)
-      addParamAnnotations(m.params.map(_.sym.attributes))
+      addParamAnnotations(jmethod, m.params.map(_.sym.annotations))
     }
     
     private def addRemoteException(jmethod: JMethod, meth: Symbol) {
       def isRemoteThrows(ainfo: AnnotationInfo) = ainfo match {
-        case AnnotationInfo(tp, List(arg), _) if tp.typeSymbol == ThrowsAttr =>
-          arg.intTree match {
+        case AnnotationInfo(tp, List(arg), _) if tp.typeSymbol == definitions.ThrowsClass =>
+          arg match {
             case Literal(Constant(tpe: Type)) if tpe.typeSymbol == RemoteException.typeSymbol => true
             case _ => false
           }
@@ -614,14 +679,13 @@ abstract class GenJVM extends SubComponent {
       }
 
       if (remoteClass ||
-          (meth.hasAttribute(RemoteAttr) 
-           && jmethod.isPublic() 
-           && !forCLDC)) {
-          val ainfo = AnnotationInfo(ThrowsAttr.tpe, List(new AnnotationArgument(Constant(RemoteException))), List())
-          if (!meth.attributes.exists(isRemoteThrows)) {
-            meth.attributes = ainfo :: meth.attributes;
-          }      
-        }
+          (meth.hasAnnotation(RemoteAttr) && jmethod.isPublic())) {
+        val c = Constant(RemoteException)
+        val ainfo = AnnotationInfo(definitions.ThrowsClass.tpe, List(Literal(c).setType(c.tpe)), List())
+        if (!meth.annotations.exists(isRemoteThrows)) {
+          meth.addAnnotation(ainfo)
+        }      
+      }
     }
     
 
@@ -651,7 +715,7 @@ abstract class GenJVM extends SubComponent {
                         jclass.getType())
     }
 
-    def addStaticInit(cls: JClass) {
+    def addStaticInit(cls: JClass, mopt: Option[IMethod]) {
       import JAccessFlags._
       val clinitMethod = cls.addNewMethod(ACC_PUBLIC | ACC_STATIC,
                                           "<clinit>",
@@ -659,13 +723,60 @@ abstract class GenJVM extends SubComponent {
                                           JType.EMPTY_ARRAY,
                                           new Array[String](0))
       val clinit = clinitMethod.getCode().asInstanceOf[JExtendedCode]
+
+      mopt match {
+       	case Some(m) =>
+          if (clasz.bootstrapClass.isDefined) legacyEmitBootstrapMethodInstall(clinit)
+          
+          val oldLastBlock = m.code.blocks.last
+          val lastBlock = m.code.newBlock
+          oldLastBlock.replaceInstruction(oldLastBlock.length - 1, JUMP(lastBlock))
+
+          if (isStaticModule(clasz.symbol)) {
+            // call object's private ctor from static ctor
+            lastBlock.emit(NEW(REFERENCE(m.symbol.enclClass)))
+            lastBlock.emit(CALL_METHOD(m.symbol.enclClass.primaryConstructor, Static(true)))
+	  }  
+           
+          // add serialVUID code
+          serialVUID match {
+            case Some(value) =>
+              import Flags._
+              import definitions._
+       	      val fieldName = "serialVersionUID"
+              val fieldSymbol = clasz.symbol.newValue(NoPosition, newTermName(fieldName))
+                                  .setFlag(STATIC | FINAL)
+                                  .setInfo(longType)
+              clasz.addField(new IField(fieldSymbol))
+              lastBlock.emit(CONSTANT(Constant(value)))
+              lastBlock.emit(STORE_FIELD(fieldSymbol, true))
+            case None => ()
+          }
+          
+          if (clasz.bootstrapClass.isDefined) {
+            // emit bootstrap method install
+            //emitBootstrapMethodInstall(block)
+          }
+          
+          lastBlock.emit(RETURN(UNIT))
+          lastBlock.close
+
+       	  method = m
+       	  jmethod = clinitMethod
+       	  genCode(m)
+       	case None =>
+	  legacyStaticInitializer(cls, clinit)
+      }
+    }
+
+    private def legacyStaticInitializer(cls: JClass, clinit: JExtendedCode) {
       if (isStaticModule(clasz.symbol)) {
         clinit.emitNEW(cls.getName())
         clinit.emitINVOKESPECIAL(cls.getName(),
                                  JMethod.INSTANCE_CONSTRUCTOR_NAME,
                                  JMethodType.ARGLESS_VOID_FUNCTION)
       }
-
+      
       serialVUID match {
         case Some(value) =>
           val fieldName = "serialVersionUID"
@@ -677,71 +788,123 @@ abstract class GenJVM extends SubComponent {
         case None => ()
       }
 
+      if (clasz.bootstrapClass.isDefined) legacyEmitBootstrapMethodInstall(clinit)
+
       clinit.emitRETURN()
     }
+    
+    /** Emit code that installs a boostrap method for invoke dynamic. It installs the default
+     *  method, found in scala.runtime.DynamicDispatch.
+     */
+    def legacyEmitBootstrapMethodInstall(jcode: JExtendedCode) {
+      jcode.emitPUSH(jclass.getType.asInstanceOf[JReferenceType])
+      jcode.emitPUSH(new JObjectType("scala.runtime.DynamicDispatch"))
+      jcode.emitPUSH("bootstrapInvokeDynamic")
+      jcode.emitGETSTATIC("java.dyn.Linkage", "BOOTSTRAP_METHOD_TYPE", MethodTypeType)
+      jcode.emitDUP
+      jcode.emitINVOKESTATIC("scala.Console", "println", new JMethodType(JType.VOID, Array(JObjectType.JAVA_LANG_OBJECT)))
+      jcode.emitINVOKESTATIC("java.dyn.MethodHandles", "findStatic", 
+                              new JMethodType(MethodHandleType, Array(JavaLangClassType, JObjectType.JAVA_LANG_STRING, MethodTypeType)))
+      jcode.emitINVOKESTATIC("java.dyn.Linkage", "registerBootstrapMethod",
+                              new JMethodType(JType.VOID, Array(JavaLangClassType, MethodHandleType)))
+    }
+
+    /** Add a forwarder for method m */
+    def addForwarder(jclass: JClass, module: Symbol, m: Symbol) {
+      import JAccessFlags._          
+      val moduleName = javaName(module) // + "$"
+      val mirrorName = moduleName.substring(0, moduleName.length() - 1)
+
+      val methodInfo = module.thisType.memberInfo(m)
+
+      val paramJavaTypes = methodInfo.paramTypes map toTypeKind
+      val paramNames: Array[String] = new Array[String](paramJavaTypes.length);
+
+      for (i <- 0 until paramJavaTypes.length)
+        paramNames(i) = "x_" + i
+
+      val mirrorMethod = jclass.addNewMethod(ACC_PUBLIC | ACC_FINAL | ACC_STATIC,
+        javaName(m),
+        javaType(methodInfo.resultType),
+        javaTypes(paramJavaTypes),
+        paramNames);
+      val mirrorCode = mirrorMethod.getCode().asInstanceOf[JExtendedCode];
+      mirrorCode.emitGETSTATIC(moduleName,
+                               nme.MODULE_INSTANCE_FIELD.toString,
+                               new JObjectType(moduleName));
+      var i = 0
+      var index = 0
+      var argTypes = mirrorMethod.getArgumentTypes()
+      while (i < argTypes.length) {
+        mirrorCode.emitLOAD(index, argTypes(i))
+        index = index + argTypes(i).getSize()
+        i += 1
+      }
+
+      mirrorCode.emitINVOKEVIRTUAL(moduleName, mirrorMethod.getName(), javaType(m).asInstanceOf[JMethodType])
+      mirrorCode.emitRETURN(mirrorMethod.getReturnType())
+
+      addRemoteException(mirrorMethod, m)
+      // only add generic signature if the method is concrete; bug #1745
+      if (!m.hasFlag(Flags.DEFERRED))
+        addGenericSignature(mirrorMethod, m, module)
+        
+      val (throws, others) = splitAnnotations(m.annotations, definitions.ThrowsClass)
+      addExceptionsAttribute(mirrorMethod, throws)
+      addAnnotations(mirrorMethod, others)
+      addParamAnnotations(mirrorMethod, m.info.params.map(_.annotations))
+    } 
 
     /** Add forwarders for all methods defined in `module' that don't conflict with 
      *  methods in the companion class of `module'. A conflict arises when a method
      *  with the same name is defined both in a class and its companion object (method
-     *  signature is not taken into account).
+     *  signature is not taken into account).  If 3rd argument cond is supplied, only
+     *  symbols for which cond(sym) is true are given forwarders.
      */
-    def addForwarders(jclass: JClass, module: Symbol) {
-      def conflictsIn(cls: Symbol, name: Name) = 
-        cls.info.nonPrivateMembers.exists(_.name == name)
+    def addForwarders(jclass: JClass, module: Symbol) { addForwarders(jclass, module, _ => true) }
+    def addForwarders(jclass: JClass, module: Symbol, cond: (Symbol) => Boolean) {
+      def conflictsIn(cls: Symbol, name: Name) =
+        cls.info.members exists (_.name == name)
       
+      /** List of parents shared by both class and module, so we don't add forwarders
+       *  for methods defined there - bug #1804 */
+      lazy val commonParents = {
+        val cps = module.info.baseClasses
+        val mps = module.companionClass.info.baseClasses
+        cps.filter(mps contains)
+      }
+      /* The setter doesn't show up in members so we inspect the name
+       * ... and clearly it helps to know how the name is encoded, see ticket #3004.
+       * This logic is grossly inadequate! Name mangling needs a devotee.
+       */
+      def conflictsInCommonParent(name: Name) =
+        commonParents exists { cp => 
+          (name startsWith (cp.name + "$")) || (name containsName ("$" + cp.name + "$"))
+        }
+             
       /** Should method `m' get a forwarder in the mirror class? */
       def shouldForward(m: Symbol): Boolean =
         atPhase(currentRun.picklerPhase) (
           m.owner != definitions.ObjectClass 
           && m.isMethod
-          && !m.hasFlag(Flags.CASE | Flags.PROTECTED)
+          && !m.hasFlag(Flags.CASE | Flags.PRIVATE | Flags.PROTECTED | Flags.DEFERRED | Flags.SPECIALIZED)
           && !m.isConstructor
           && !m.isStaticMember
           && !(m.owner == definitions.AnyClass) 
+          && !module.isSubClass(module.companionClass)
           && !conflictsIn(definitions.ObjectClass, m.name)
-          && !conflictsIn(module.linkedClassOfModule, m.name))
+          && !conflictsInCommonParent(m.name)
+          && !conflictsIn(module.companionClass, m.name)
+        )
       
-      import JAccessFlags._
       assert(module.isModuleClass)
       if (settings.debug.value)
         log("Dumping mirror class for object: " + module);
       
-      val moduleName = javaName(module) // + "$"
-      val mirrorName = moduleName.substring(0, moduleName.length() - 1)
-      
-      for (m <- atPhase(currentRun.picklerPhase)(module.tpe.nonPrivateMembers); if shouldForward(m)) {
-        val paramJavaTypes = m.tpe.paramTypes map toTypeKind
-        val paramNames: Array[String] = new Array[String](paramJavaTypes.length);
-        for (val i <- 0.until(paramJavaTypes.length))
-          paramNames(i) = "x_" + i
-        val mirrorMethod = jclass.addNewMethod(ACC_PUBLIC | ACC_FINAL | ACC_STATIC,
-          javaName(m),
-          javaType(m.tpe.resultType),
-          javaTypes(paramJavaTypes),
-          paramNames);
-        val mirrorCode = mirrorMethod.getCode().asInstanceOf[JExtendedCode];
-        mirrorCode.emitGETSTATIC(moduleName,
-                                 nme.MODULE_INSTANCE_FIELD.toString,
-                                 new JObjectType(moduleName));
-        var i = 0
-        var index = 0
-        var argTypes = mirrorMethod.getArgumentTypes()
-        while (i < argTypes.length) {
-          mirrorCode.emitLOAD(index, argTypes(i))
-          index = index + argTypes(i).getSize()
-          i += 1
-        }
-
-        mirrorCode.emitINVOKEVIRTUAL(moduleName, mirrorMethod.getName(), mirrorMethod.getType().asInstanceOf[JMethodType])
-        mirrorCode.emitRETURN(mirrorMethod.getReturnType())
-
-        addRemoteException(mirrorMethod, m)
-        addGenericSignature(mirrorMethod, m)
-        val (throws, others) = splitAnnotations(m.attributes, ThrowsAttr)
-        addExceptionsAttribute(mirrorMethod, throws)
-        addAnnotations(mirrorMethod, others)
+      for (m <- module.info.nonPrivateMembers; if shouldForward(m) ; if cond(m)) {
+        log("Adding static forwarder '%s' to '%s'".format(m, module))
+        addForwarder(jclass, module, m)
       }
-      
     }
     
     /** Dump a mirror class for a top-level module. A mirror class is a class containing
@@ -758,12 +921,43 @@ abstract class GenJVM extends SubComponent {
                                            JClass.NO_INTERFACES,
                                            sourceFile)
       addForwarders(mirrorClass, clasz)
+      val ssa = scalaSignatureAddingMarker(mirrorClass, clasz.companionSymbol)
+      addAnnotations(mirrorClass, clasz.annotations ++ ssa)
       emitClass(mirrorClass, clasz)
     }
 
     var linearization: List[BasicBlock] = Nil
-
     var isModuleInitialized = false
+    
+    private def genConstant(jcode: JExtendedCode, const: Constant) {
+      const.tag match {
+        case UnitTag    => ()
+        case BooleanTag => jcode.emitPUSH(const.booleanValue)
+        case ByteTag    => jcode.emitPUSH(const.byteValue)
+        case ShortTag   => jcode.emitPUSH(const.shortValue)
+        case CharTag    => jcode.emitPUSH(const.charValue)
+        case IntTag     => jcode.emitPUSH(const.intValue)
+        case LongTag    => jcode.emitPUSH(const.longValue)
+        case FloatTag   => jcode.emitPUSH(const.floatValue)
+        case DoubleTag  => jcode.emitPUSH(const.doubleValue)
+        case StringTag  => jcode.emitPUSH(const.stringValue)
+        case NullTag    => jcode.emitACONST_NULL()
+        case ClassTag   =>
+          val kind = toTypeKind(const.typeValue)
+          val toPush =
+            if (kind.isValueType) classLiteral(kind)
+            else javaType(kind).asInstanceOf[JReferenceType]
+          
+          jcode emitPUSH toPush
+
+        case EnumTag   =>
+          val sym = const.symbolValue
+          jcode.emitGETSTATIC(javaName(sym.owner),
+                              javaName(sym),
+                              javaType(sym.tpe.underlying))
+        case _          => abort("Unknown constant value: " + const);
+      }
+    }
 
     /**
      *  @param m ...
@@ -773,8 +967,9 @@ abstract class GenJVM extends SubComponent {
 
       def makeLabels(bs: List[BasicBlock]) = {
         if (settings.debug.value)
-          log("Making labels for: " + method);
-        HashMap.empty ++ bs.zip(bs map (b => jcode.newLabel))
+          log("Making labels for: " + method)
+          
+        HashMap(bs map (_ -> jcode.newLabel) : _*)
       }
 
       isModuleInitialized = false
@@ -786,12 +981,11 @@ abstract class GenJVM extends SubComponent {
 
       var nextBlock: BasicBlock = linearization.head
 
-    def genBlocks(l: List[BasicBlock]): Unit = l match {
-      case Nil => ()
-      case x :: Nil => nextBlock = null; genBlock(x)
-      case x :: y :: ys => nextBlock = y; genBlock(x); genBlocks(y :: ys)
-    }
-
+      def genBlocks(l: List[BasicBlock]): Unit = l match {
+        case Nil => ()
+        case x :: Nil => nextBlock = null; genBlock(x)
+        case x :: y :: ys => nextBlock = y; genBlock(x); genBlocks(y :: ys)
+      }
 
     /** Generate exception handlers for the current method. */
     def genExceptionHandlers {
@@ -806,52 +1000,49 @@ abstract class GenJVM extends SubComponent {
         var start = -1
         var end = -1
 
-        linearization foreach ((b) => {
+        linearization foreach { b =>
           if (! (covered contains b) ) {
             if (start >= 0) { // we're inside a handler range
               end = labels(b).getAnchor()
-              ranges = (start, end) :: ranges
+              ranges ::= (start, end)
               start = -1
             }
           } else {
-            if (start >= 0) { // we're inside a handler range 
-              end = endPC(b)
-            } else {
+            if (start < 0)  // we're not inside a handler range
               start = labels(b).getAnchor()
-              end   = endPC(b)
-            }
-            covered = covered - b
+
+            end = endPC(b)
+            covered -= b
           }
-        });
+        }
 
         /* Add the last interval. Note that since the intervals are 
          * open-ended to the right, we have to give a number past the actual
          * code!
          */
         if (start >= 0) {
-          ranges = (start, jcode.getPC()) :: ranges;
+          ranges ::= (start, jcode.getPC())
         }
 
-        if (covered != Nil)
+        if (!covered.isEmpty)
           if (settings.debug.value)
             log("Some covered blocks were not found in method: " + method + 
                 " covered: " + covered + " not in " + linearization);
         ranges
       }
       
-      this.method.exh foreach { e => 
-        ranges(e).sort({ (p1, p2) => p1._1 < p2._1 })
-        .foreach { p => 
-          if (p._1 < p._2) {
-            if (settings.debug.value)
-              log("Adding exception handler " + e + "at block: " + e.startBlock + " for " + method + 
-                  " from: " + p._1 + " to: " + p._2 + " catching: " + e.cls);
-            jcode.addExceptionHandler(p._1, p._2, 
-                                      labels(e.startBlock).getAnchor(),
-                                      if (e.cls == NoSymbol) null else javaName(e.cls))
-          } else 
-            log("Empty exception range: " + p)
-        }
+      for (e <- this.method.exh ; p <- ranges(e).sortBy(_._1)) {
+        if (p._1 < p._2) {
+          if (settings.debug.value)
+            log("Adding exception handler " + e + "at block: " + e.startBlock + " for " + method + 
+                " from: " + p._1 + " to: " + p._2 + " catching: " + e.cls);
+          val cls = if (e.cls == NoSymbol || e.cls == definitions.ThrowableClass) null
+                    else javaName(e.cls)
+          jcode.addExceptionHandler(p._1, p._2,
+                                    labels(e.startBlock).getAnchor(),
+                                    cls)
+        } else 
+          log("Empty exception range: " + p)
       }
     }
 
@@ -866,7 +1057,7 @@ abstract class GenJVM extends SubComponent {
       varsInBlock.clear
 
       for (instr <- b) {
-        class CompilationError(msg: String) extends Error {
+        class CompilationException(msg: String) extends Exception(msg) {
           override def toString: String = {
             msg + 
             "\nCurrent method: " + method + 
@@ -876,38 +1067,14 @@ abstract class GenJVM extends SubComponent {
             method.dump
           }
         }
-        def assert(cond: Boolean, msg: String) = if (!cond) throw new CompilationError(msg);
+        def assert(cond: Boolean, msg: String) = if (!cond) throw new CompilationException(msg)
 
         instr match {
           case THIS(clasz) =>
             jcode.emitALOAD_0()
 
           case CONSTANT(const) =>
-            const.tag match {
-              case UnitTag    => ();
-              case BooleanTag => jcode.emitPUSH(const.booleanValue)
-              case ByteTag    => jcode.emitPUSH(const.byteValue)
-              case ShortTag   => jcode.emitPUSH(const.shortValue)
-              case CharTag    => jcode.emitPUSH(const.charValue)
-              case IntTag     => jcode.emitPUSH(const.intValue)
-              case LongTag    => jcode.emitPUSH(const.longValue)
-              case FloatTag   => jcode.emitPUSH(const.floatValue)
-              case DoubleTag  => jcode.emitPUSH(const.doubleValue)
-              case StringTag  => jcode.emitPUSH(const.stringValue)
-              case NullTag    => jcode.emitACONST_NULL()
-              case ClassTag   =>
-                val kind = toTypeKind(const.typeValue);
-                if (kind.isValueType)
-                  jcode.emitPUSH(classLiteral(kind));
-                else
-                  jcode.emitPUSH(javaType(kind).asInstanceOf[JReferenceType]);
-              case EnumTag   =>
-                val sym = const.symbolValue
-                jcode.emitGETSTATIC(javaName(sym.owner),
-                                    javaName(sym),
-                                    javaType(sym.tpe.underlying))
-              case _          => abort("Unknown constant value: " + const);
-            }
+            genConstant(jcode, const)
 
           case LOAD_ARRAY_ITEM(kind) =>
             jcode.emitALOAD(javaType(kind))
@@ -933,7 +1100,7 @@ abstract class GenJVM extends SubComponent {
           case LOAD_MODULE(module) =>
 //            assert(module.isModule, "Expected module: " + module)
             if (settings.debug.value)
-              log("genearting LOAD_MODULE for: " + module + " flags: " + 
+              log("generating LOAD_MODULE for: " + module + " flags: " + 
                   Flags.flagsToString(module.flags));
             if (clasz.symbol == module.moduleClass && jmethod.getName() != nme.readResolve.toString)
               jcode.emitALOAD_0()
@@ -966,43 +1133,43 @@ abstract class GenJVM extends SubComponent {
 
           case CALL_PRIMITIVE(primitive) =>
             genPrimitive(primitive, instr.pos)
+          
+          /** Special handling to access native Array.clone() */
+          case call @ CALL_METHOD(definitions.Array_clone, Dynamic) =>
+            val target: String = javaType(call.targetTypeKind).getSignature()
+            jcode.emitINVOKEVIRTUAL(target, "clone", arrayCloneType)
 
           case call @ CALL_METHOD(method, style) =>
-            val owner: String = javaName(method.owner);
-            //reference the type of the receiver instead of the method owner (if not an interface!)
+            val owner: String = javaName(method.owner)
+            // reference the type of the receiver instead of the method owner (if not an interface!)
             val dynamicOwner =
               if (needsInterfaceCall(call.hostClass)) owner
               else javaName(call.hostClass)
+            val jname = javaName(method)
+            val jtype = javaType(method).asInstanceOf[JMethodType]
 
             style match {
+              case InvokeDynamic =>
+                jcode.emitINVOKEINTERFACE("java.dyn.Dynamic", jname, jtype)
+              
               case Dynamic =>
                 if (needsInterfaceCall(method.owner))
-                  jcode.emitINVOKEINTERFACE(owner,
-                                            javaName(method),
-                                            javaType(method).asInstanceOf[JMethodType])
+                  jcode.emitINVOKEINTERFACE(owner, jname, jtype)
                 else
-                  jcode.emitINVOKEVIRTUAL(dynamicOwner,
-                                          javaName(method),
-                                          javaType(method).asInstanceOf[JMethodType]);
+                  jcode.emitINVOKEVIRTUAL(dynamicOwner, jname, jtype)
 
               case Static(instance) =>
-                if (instance) {
-                  jcode.emitINVOKESPECIAL(owner,
-                                          javaName(method),
-                                          javaType(method).asInstanceOf[JMethodType]);
-                } else
-                  jcode.emitINVOKESTATIC(owner,
-                                          javaName(method),
-                                          javaType(method).asInstanceOf[JMethodType]);
+                if (instance)
+                  jcode.emitINVOKESPECIAL(owner, jname, jtype)
+                else
+                  jcode.emitINVOKESTATIC(owner, jname, jtype)
 
               case SuperCall(_) =>
-                  jcode.emitINVOKESPECIAL(owner,
-                                          javaName(method),
-                                          javaType(method).asInstanceOf[JMethodType]);
+                  jcode.emitINVOKESPECIAL(owner, jname, jtype)
                   // we initialize the MODULE$ field immediately after the super ctor
                   if (isStaticModule(clasz.symbol) && !isModuleInitialized &&
                       jmethod.getName() == JMethod.INSTANCE_CONSTRUCTOR_NAME &&
-                      javaName(method) == JMethod.INSTANCE_CONSTRUCTOR_NAME) {
+                      jname == JMethod.INSTANCE_CONSTRUCTOR_NAME) {
                         isModuleInitialized = true;
                         jcode.emitALOAD_0();
                         jcode.emitPUTSTATIC(jclass.getName(),
@@ -1016,11 +1183,11 @@ abstract class GenJVM extends SubComponent {
           case BOX(kind) =>
             val boxedType = definitions.boxedClass(kind.toType.typeSymbol)
             val mtype = new JMethodType(javaType(boxedType), Array(javaType(kind)))
-            jcode.emitINVOKESTATIC(BoxesRunTime, "boxTo" + boxedType.nameString, mtype)
+            jcode.emitINVOKESTATIC(BoxesRunTime, "boxTo" + boxedType.decodedName, mtype)
 
           case UNBOX(kind) =>
             val mtype = new JMethodType(javaType(kind), Array(JObjectType.JAVA_LANG_OBJECT))
-            jcode.emitINVOKESTATIC(BoxesRunTime, "unboxTo" + kind.toType.typeSymbol.nameString, mtype)
+            jcode.emitINVOKESTATIC(BoxesRunTime, "unboxTo" + kind.toType.typeSymbol.decodedName, mtype)
 
           case NEW(REFERENCE(cls)) =>
             val className = javaName(cls)
@@ -1132,12 +1299,23 @@ abstract class GenJVM extends SubComponent {
                 }
 
               case REFERENCE(_) | ARRAY(_) =>
-                if (nextBlock == success) {
-                  jcode.emitIFNONNULL(labels(failure))
-                } else {
-                  jcode.emitIFNULL(labels(success));
-                  if (nextBlock != failure)
+                val Success = success
+                val Failure = failure
+                (cond, nextBlock) match {
+                  case (EQ, Success) =>
+                    jcode.emitIFNONNULL(labels(failure))
+                  case (NE, Failure) =>
+                    jcode.emitIFNONNULL(labels(success))
+                  case (EQ, Failure) =>
+                    jcode.emitIFNULL(labels(success))
+                  case (NE, Success) =>
+                    jcode.emitIFNULL(labels(failure))
+                  case (EQ, _) =>
+                    jcode.emitIFNULL(labels(success));
                     jcode.emitGOTO_maybe_W(labels(failure), false);
+                  case (NE, _) =>
+                    jcode.emitIFNONNULL(labels(success));
+                    jcode.emitGOTO_maybe_W(labels(failure), false);                    
                 }
 
               case _ =>
@@ -1208,9 +1386,9 @@ abstract class GenJVM extends SubComponent {
 //        assert(instr.pos.source.isEmpty || instr.pos.source.get == (clasz.cunit.source), "sources don't match")
 //        val crtLine = instr.pos.line.get(lastLineNr);
         val crtLine = try {
-          (instr.pos).line.get
+          (instr.pos).line
         } catch {
-          case _: NoSuchElementException =>
+          case _: UnsupportedOperationException =>
             log("Warning: wrong position in: " + method)
             lastLineNr
         }
@@ -1229,10 +1407,10 @@ abstract class GenJVM extends SubComponent {
       }
       
       // local vars that survived this basic block 
-      for (val lv <- varsInBlock) {
+      for (lv <- varsInBlock) {
         lv.ranges = (lv.start, jcode.getPC()) :: lv.ranges
       }
-      for (val lv <- b.varsInScope) {
+      for (lv <- b.varsInScope) {
         lv.ranges = (labels(b).getAnchor(), jcode.getPC()) :: lv.ranges
       }
     }
@@ -1378,7 +1556,7 @@ abstract class GenJVM extends SubComponent {
             log("Converting from: " + src + " to: " + dst);
           if (dst == BOOL) {
             Console.println("Illegal conversion at: " + clasz +
-                            " at: " + pos.source.get + ":" + pos.line.getOrElse(-1));
+                            " at: " + pos.source + ":" + pos.line);
           } else
             jcode.emitT2T(javaType(src), javaType(dst));
 
@@ -1441,15 +1619,15 @@ abstract class GenJVM extends SubComponent {
         def emitEntry(name: String, signature: String, idx: Short, start: Short, end: Short) {
           lvTab.putShort(start)
           lvTab.putShort(end)
-          lvTab.putShort(pool.addUtf8(name).asInstanceOf[Short])
-          lvTab.putShort(pool.addUtf8(signature).asInstanceOf[Short])
+          lvTab.putShort(pool.addUtf8(name).toShort)
+          lvTab.putShort(pool.addUtf8(signature).toShort)
           lvTab.putShort(idx)
         }
 
-        lvTab.putShort(entries.asInstanceOf[Short])
+        lvTab.putShort(entries.toShort)
 
         if (!jmethod.isStatic()) {
-          emitEntry("this", jclass.getType().getSignature(), 0, 0.asInstanceOf[Short], pc.asInstanceOf[Short])
+          emitEntry("this", jclass.getType().getSignature(), 0, 0.toShort, pc.toShort)
         }
 
         for (lv <- vars) {
@@ -1458,16 +1636,16 @@ abstract class GenJVM extends SubComponent {
               "<anon" + anonCounter + ">"
             } else javaName(lv.sym)
 
-            val index = indexOf(lv).asInstanceOf[Short]
+            val index = indexOf(lv).toShort
             val tpe   = javaType(lv.kind).getSignature()
             for ((start, end) <- lv.ranges) {
-              emitEntry(name, tpe, index, start.asInstanceOf[Short], (end - start).asInstanceOf[Short])
+              emitEntry(name, tpe, index, start.toShort, (end - start).toShort)
             }
         }
         val attr =
             fjbgContext.JOtherAttribute(jclass,
                                         jmethod,
-                                        "LocalVariableTable",
+                                        nme.LocalVariableTableATTR.toString,
                                         lvTab.array())
         jcode.addAttribute(attr)
     }
@@ -1525,7 +1703,7 @@ abstract class GenJVM extends SubComponent {
 
     def indexOf(local: Local): Int = {
       assert(local.index >= 0,
-             "Invalid index for: " + local + "{" + local.hashCode + "}: ")
+             "Invalid index for: " + local + "{" + local.## + "}: ")
       local.index
     }
 
@@ -1540,7 +1718,7 @@ abstract class GenJVM extends SubComponent {
 
       for (l <- m.locals) {
         if (settings.debug.value)
-          log("Index value for " + l + "{" + l.hashCode + "}: " + idx)
+          log("Index value for " + l + "{" + l.## + "}: " + idx)
         l.index = idx
         idx += sizeOf(l.kind)
       }
@@ -1566,21 +1744,21 @@ abstract class GenJVM extends SubComponent {
      * </p>
      */
     def javaName(sym: Symbol): String = {
-      val suffix = if (sym.hasFlag(Flags.MODULE) && !sym.isMethod &&
-                        !sym.isImplClass && 
-                        !sym.hasFlag(Flags.JAVA)) "$" else "";
+      val suffix = moduleSuffix(sym)
 
       if (sym == definitions.NothingClass)
-        return "scala.runtime.Nothing$"
+        return javaName(definitions.RuntimeNothingClass)
       else if (sym == definitions.NullClass)
-        return "scala.runtime.Null$"
+        return javaName(definitions.RuntimeNullClass)
+      else if (definitions.primitiveCompanions(sym.companionModule))
+        return javaName(definitions.getModule("scala.runtime." + sym.name))
 
       if (sym.isClass && !sym.rawowner.isPackageClass && !sym.isModuleClass) {
         innerClasses = innerClasses + sym;
       }
 
       (if (sym.isClass || (sym.isModule && !sym.isMethod))
-        sym.fullNameString('/')
+        sym.fullName('/')
       else
         sym.simpleName.toString.trim()) + suffix
     }
@@ -1625,16 +1803,27 @@ abstract class GenJVM extends SubComponent {
                        && !sym.enclClass.hasFlag(Flags.INTERFACE) 
                        && !sym.isClassConstructor) ACC_FINAL else 0)
       jf = jf | (if (sym.isStaticMember) ACC_STATIC else 0)
-      if (settings.target.value == "jvm-1.5")
-        jf = jf | (if (sym hasFlag Flags.BRIDGE) ACC_BRIDGE | ACC_SYNTHETIC else 0)
+      jf = jf | (if (sym hasFlag Flags.BRIDGE) ACC_BRIDGE | ACC_SYNTHETIC else 0)
+
       if (sym.isClass && !sym.hasFlag(Flags.INTERFACE))
         jf = jf | ACC_SUPER
+
+      // constructors of module classes should be private
+      if (sym.isPrimaryConstructor && isTopLevelModule(sym.owner)) {
+        jf |= ACC_PRIVATE
+        jf &= ~ACC_PUBLIC
+      }
       jf
     }
 
     /** Calls to methods in 'sym' need invokeinterface? */
     def needsInterfaceCall(sym: Symbol): Boolean = {
-      sym.info // needed so that the type is up to date (erasure may add lateINTERFACE to traits)
+      log("checking for interface call: " + sym.fullName)
+      // the following call to 'info' may cause certain symbols to fail loading because we're
+      // too late in the compilation chain (aliases to overloaded symbols will not be properly
+      // resolved, see scala.Range, method super$++ that fails in UnPickler at LazyTypeRefAndAlias.complete
+      if (sym.isTrait) sym.info // needed so that the type is up to date (erasure may add lateINTERFACE to traits)
+
       sym.hasFlag(Flags.INTERFACE) ||
       (sym.hasFlag(Flags.JAVA) &&
        sym.isNonBottomSubClass(definitions.ClassfileAnnotationClass))
@@ -1672,16 +1861,18 @@ abstract class GenJVM extends SubComponent {
       res
     }
 
-    def getFile(cls: JClass, suffix: String): AbstractFile = {
-      var dir: AbstractFile = outputDir
+    /** Return an abstract file for the given class symbol, with the desired suffix.
+     *  Create all necessary subdirectories on the way.
+     */
+    def getFile(sym: Symbol, cls: JClass, suffix: String): AbstractFile = {
+      val sourceFile = atPhase(currentRun.flattenPhase.prev)(sym.sourceFile)
+      var dir: AbstractFile = settings.outputDirs.outputDirFor(sourceFile)
       val pathParts = cls.getName().split("[./]").toList
       for (part <- pathParts.init) {
         dir = dir.subdirectoryNamed(part)
       }
       dir.fileNamed(pathParts.last + suffix)
     }
-
-
     
     /** Merge adjacent ranges. */
     private def mergeEntries(ranges: List[(Int, Int)]): List[(Int, Int)] = 
@@ -1691,9 +1882,9 @@ abstract class GenJVM extends SubComponent {
         case _ => p :: collapsed
       }}).reverse
 
-    def assert(cond: Boolean, msg: String) = if (!cond) {
+    def assert(cond: Boolean, msg: => String) = if (!cond) {
       method.dump
-      throw new Error(msg + "\nMethod: " + method)
+      abort(msg + "\nMethod: " + method)
     }
 
     def assert(cond: Boolean) { assert(cond, "Assertion failed.") }
diff --git a/src/compiler/scala/tools/nsc/backend/msil/GenMSIL.scala b/src/compiler/scala/tools/nsc/backend/msil/GenMSIL.scala
index 8e1dec5..193c0c5 100644
--- a/src/compiler/scala/tools/nsc/backend/msil/GenMSIL.scala
+++ b/src/compiler/scala/tools/nsc/backend/msil/GenMSIL.scala
@@ -1,24 +1,21 @@
 /* NSC -- new scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author Nikolay Mihaylov
  */
 
-// $Id: GenMSIL.scala 16881 2009-01-09 16:28:11Z cunei $
 
-package scala.tools.nsc.backend.msil
+package scala.tools.nsc
+package backend.msil
 
 import java.io.{File, IOException}
 import java.nio.{ByteBuffer, ByteOrder}
 
-import scala.collection.mutable.{Map, HashMap, HashSet, Stack}
+import scala.collection.mutable.{Map, HashMap, HashSet, Stack, ListBuffer}
 import scala.tools.nsc.symtab._
-import scala.tools.nsc.util.Position
 
 import ch.epfl.lamp.compiler.msil.{Type => MsilType, _}
 import ch.epfl.lamp.compiler.msil.emit._
 
-/**
- */
 abstract class GenMSIL extends SubComponent {
   import global._
   import loaders.clrTypes
@@ -74,7 +71,7 @@ abstract class GenMSIL extends SubComponent {
     import clrTypes.{VOID => MVOID, BOOLEAN => MBOOL, UBYTE => MBYTE, SHORT => MSHORT,
                    CHAR => MCHAR, INT => MINT, LONG => MLONG, FLOAT => MFLOAT,
                    DOUBLE => MDOUBLE, OBJECT => MOBJECT, STRING => MSTRING,
-                   STRING_ARRAY => MSTRING_ARRAY, SCALA_SYMTAB_ATTR => SYMTAB_ATTRIBUTE,
+                   STRING_ARRAY => MSTRING_ARRAY,
                    SYMTAB_CONSTR => SYMTAB_ATTRIBUTE_CONSTRUCTOR,
                    SYMTAB_DEFAULT_CONSTR => SYMTAB_ATTRIBUTE_EMPTY_CONSTRUCTOR}
 
@@ -117,7 +114,7 @@ abstract class GenMSIL extends SubComponent {
     val toDouble: MethodInfo = SystemConvert.GetMethod("ToDouble", objParam)
 
     //val boxedUnit: FieldInfo = msilType(definitions.BoxedUnitModule.info).GetField("UNIT")
-    val boxedUnit: FieldInfo = fields(definitions.BoxedUnit_UNIT.asInstanceOf[clrTypes.global.Symbol])
+    val boxedUnit: FieldInfo = fields(definitions.BoxedUnit_UNIT)
 
     // Scala attributes
     // symtab.Definitions -> object (singleton..)
@@ -132,8 +129,8 @@ abstract class GenMSIL extends SubComponent {
     val dynToStatMapped: HashSet[Symbol] = new HashSet()
 
     initMappings()
-    // ********************************************************************
-    // Create the mappings
+
+    /** Create the mappings between java and .net classes and methods */
     private def initMappings() {
       mapType(definitions.AnyClass, MOBJECT)
       mapType(definitions.AnyRefClass, MOBJECT)
@@ -207,7 +204,6 @@ abstract class GenMSIL extends SubComponent {
 
     var clasz: IClass = _
     var method: IMethod = _
-    var code: Code = _
 
     var massembly: AssemblyBuilder = _
     var mmodule: ModuleBuilder = _
@@ -230,7 +226,7 @@ abstract class GenMSIL extends SubComponent {
           assemName = assemName.substring(0, assemName.length() - 1)
         } else {
           // assuming filename of first source file
-          assert(firstSourceName.endsWith(".scala"), "Source file doesn't end with .scala")
+          assert(firstSourceName.endsWith(".scala"), firstSourceName)
           assemName = firstSourceName.substring(0, firstSourceName.length() - 6)
         }
       } else {
@@ -244,13 +240,13 @@ abstract class GenMSIL extends SubComponent {
       
       outDir = new File(settings.outdir.value)
 
-      srcPath = new File(settings.sourcepath.value)
+      srcPath = new File(settings.sourcedir.value)
 
       val assemblyName = new AssemblyName()
       assemblyName.Name = assemName
       massembly = AssemblyBuilderFactory.DefineDynamicAssembly(assemblyName)
 
-      moduleName = assemName + (if (entryPoint == null) ".dll" else ".exe")
+      moduleName = assemName // + (if (entryPoint == null) ".dll" else ".exe")
       // filename here: .dll or .exe (in both parameters), second: give absolute-path
       mmodule = massembly.DefineDynamicModule(moduleName,
                                               new File(outDir, moduleName).getAbsolutePath())
@@ -262,63 +258,73 @@ abstract class GenMSIL extends SubComponent {
      * Form of the custom Attribute parameter (Ecma-335.pdf)
      *      - p. 163 for CustomAttrib Form,
      *      - p. 164 for FixedArg Form (Array and Element) (if array or not is known!)
-     *  !! least significant *byte* first if values longer than one byte !!
+     *  !! least significant byte first if values longer than one byte !!
      *
      * 1: Prolog (unsigned int16, value 0x0001) -> symtab[0] = 0x01, symtab[1] = 0x00
      * 2: FixedArgs (directly the data, get number and types from related constructor)
-     *  2.1: length of the array (unsigned int32, take care on order of the 4 bytes)
+     *  2.1: length of the array (unsigned int32, 4 bytes, least significant first)
      *  2.2: the byte array data
      * 3: NumNamed (unsigned int16, number of named fields and properties, 0x0000)
-     *
-     **/
+     */
     def addSymtabAttribute(sym: Symbol, tBuilder: TypeBuilder) {
-      currentRun.symData.get(sym) match {
-        case Some(pickle) =>
-          val symtab: Array[Byte] = new Array[Byte](pickle.writeIndex + 8)
-          symtab(0) = 1.toByte
-          var size:Int = pickle.writeIndex
-          for (i <- 2 until 6) {
-            symtab(i) = (size & 0xff).toByte
-            size = size >> 8
-          }
+      def addMarker() {
+        val markerSymtab = new Array[Byte](4)
+        markerSymtab(0) = 1.toByte
+        tBuilder.SetCustomAttribute(SYMTAB_ATTRIBUTE_EMPTY_CONSTRUCTOR, markerSymtab)
+      }
 
-          System.arraycopy(pickle.bytes, 0, symtab, 6, pickle.writeIndex)
+      // both conditions are needed (why exactly..?)
+      if (tBuilder.Name.endsWith("$") || sym.isModuleClass) {
+        addMarker()
+      } else {
+        currentRun.symData.get(sym) match {
+          case Some(pickle) =>
+            var size = pickle.writeIndex
+            val symtab = new Array[Byte](size + 8)
+            symtab(0) = 1.toByte
+            for (i <- 2 until 6) {
+              symtab(i) = (size & 0xff).toByte
+              size = size >> 8
+            }
+            System.arraycopy(pickle.bytes, 0, symtab, 6, pickle.writeIndex)
 
-          tBuilder.SetCustomAttribute(SYMTAB_ATTRIBUTE_CONSTRUCTOR, symtab)
+            tBuilder.SetCustomAttribute(SYMTAB_ATTRIBUTE_CONSTRUCTOR, symtab)
 
-          currentRun.symData -= sym
-          currentRun.symData -= sym.linkedSym
-          //log("Generated ScalaSig Attr for " + sym)//debug
-        case _ =>
-          log("Could not find pickle information for " + sym)
+            currentRun.symData -= sym
+            currentRun.symData -= sym.companionSymbol
+
+          case _ =>
+            addMarker()
+        }
       }
     }
 
-    def addAttributes(member: ICustomAttributeSetter, attributes: List[AnnotationInfo]) {
-      return // FIXME
-
+    def addAttributes(member: ICustomAttributeSetter, annotations: List[AnnotationInfo]) {
+      return // TODO: implement at some point
+    }
+/*
       if (settings.debug.value)
-        log("creating attributes: " + attributes + " for member : " + member)
-      for (attr@ AnnotationInfo(typ, annArgs, nvPairs) <- attributes ;
-           if attr.isConstant)
-           /* !typ.typeSymbol.hasFlag(Flags.JAVA) */
+        log("creating annotations: " + annotations + " for member : " + member)
+      for (annot@ AnnotationInfo(typ, annArgs, nvPairs) <- annotations ;
+           if annot.isConstant)
+           //!typ.typeSymbol.hasFlag(Flags.JAVA)
       {
 //        assert(consts.length <= 1,
-//               "too many constant arguments for attribute; "+consts.toString())
+//               "too many constant arguments for annotations; "+consts.toString())
 
-        // Problem / TODO having the symbol of the attribute type would be nicer
+        // Problem / TODO having the symbol of the annotations type would be nicer
         // (i hope that type.typeSymbol is the same as the one in types2create)
-        // AND: this will crash if the attribute Type is already compiled (-> not a typeBuilder)
+        // AND: this will crash if the annotations Type is already compiled (-> not a typeBuilder)
         // when this is solved, types2create will be the same as icodes.classes, thus superfluous
-        val attrType: TypeBuilder = getType(typ.typeSymbol).asInstanceOf[TypeBuilder]
-//        val attrType: MsilType = getType(typ.typeSymbol)
+        val annType: TypeBuilder = getType(typ.typeSymbol).asInstanceOf[TypeBuilder]
+//        val annType: MsilType = getType(typ.typeSymbol)
 
         // Problem / TODO: i have no idea which constructor is used. This
         // information should be available in AnnotationInfo.
-        attrType.CreateType() // else, GetConstructors can't be used
-        val constr: ConstructorInfo = attrType.GetConstructors()(0)
+        annType.CreateType() // else, GetConstructors can't be used
+        val constr: ConstructorInfo = annType.GetConstructors()(0)
         // prevent a second call of CreateType, only needed because there's no
-        // otehr way than GetConstructors()(0) to get the constructor, if there's
+        // other way than GetConstructors()(0) to get the constructor, if there's
         // no constructor symbol available.
 
         val args: Array[Byte] =
@@ -327,9 +333,9 @@ abstract class GenMSIL extends SubComponent {
             (for((n,v) <- nvPairs) yield (n, v.constant.get)))
         member.SetCustomAttribute(constr, args)
       }
-    }
+    } */
 
-    def getAttributeArgs(consts: List[Constant], nvPairs: List[(Name, Constant)]): Array[Byte] = {
+/*    def getAttributeArgs(consts: List[Constant], nvPairs: List[(Name, Constant)]): Array[Byte] = {
       val buf = ByteBuffer.allocate(2048) // FIXME: this may be not enough!
       buf.order(ByteOrder.LITTLE_ENDIAN)
       buf.putShort(1.toShort) // signature
@@ -430,13 +436,13 @@ abstract class GenMSIL extends SubComponent {
       }
 
       val length = buf.position()
-      buf.array().subArray(0, length)
-    }
+      buf.array().slice(0, length)
+    } */
 
     def writeAssembly() {
       if (entryPoint != null) {
-        assert(entryPoint.enclClass.isModuleClass, "main-method not defined in a module")
-        val mainMethod = methods(entryPoint.asInstanceOf[clrTypes.global.Symbol])
+        assert(entryPoint.enclClass.isModuleClass, entryPoint.enclClass)
+        val mainMethod = methods(entryPoint)
         val stringArrayTypes: Array[MsilType] = Array(MSTRING_ARRAY)
         val globalMain = mmodule.DefineGlobalMethod(
           "Main", MethodAttributes.Public | MethodAttributes.Static,
@@ -464,7 +470,7 @@ abstract class GenMSIL extends SubComponent {
     private def createTypes() {
       for (sym <- classes.keys) {
         val iclass   = classes(sym)
-        val tBuilder = types(sym.asInstanceOf[clrTypes.global.Symbol]).asInstanceOf[TypeBuilder]
+        val tBuilder = types(sym).asInstanceOf[TypeBuilder]
           
         if (settings.debug.value)
           log("Calling CreatType for " + sym + ", " + tBuilder.toString)
@@ -481,7 +487,7 @@ abstract class GenMSIL extends SubComponent {
       clasz = iclass
 
       val tBuilder = getType(sym).asInstanceOf[TypeBuilder]
-      if (isCloneable(sym)){
+      if (isCloneable(sym)) {
         // FIXME: why there's no nme.clone_ ?
         // "Clone": if the code is non-portable, "Clone" is defined, not "clone"
         // TODO: improve condition (should override AnyRef.clone)
@@ -492,7 +498,7 @@ abstract class GenMSIL extends SubComponent {
           if (settings.debug.value)
             log("auto-generating cloneable method for " + sym)
           val attrs: Short = (MethodAttributes.Public | MethodAttributes.Virtual |
-                              MethodAttributes.HideBySig)
+                              MethodAttributes.HideBySig).toShort
           val cloneMethod = tBuilder.DefineMethod("Clone", attrs, MOBJECT,
                                                   MsilType.EmptyTypes)
           val clCode = cloneMethod.GetILGenerator()
@@ -502,38 +508,19 @@ abstract class GenMSIL extends SubComponent {
         }
       }
 
-      val line = (sym.pos).line match {
-        case Some(l) => l
-        case None => 0
-      }
+      val line = sym.pos.line
       tBuilder.setPosition(line, iclass.cunit.source.file.name)
 
       if (isTopLevelModule(sym)) {
-        if (settings.debug.value)
-          log("TopLevelModule: " + sym)
-        if (sym.linkedClassOfModule == NoSymbol) {
-          if (settings.debug.value)
-            log(" no linked class: " + sym)
+        if (sym.companionClass == NoSymbol)
           dumpMirrorClass(sym)
-        } else if (!currentRun.compiles(sym.linkedClassOfModule)) {
-          if (settings.debug.value)
-            log(" not compiling linked class: " + sym)
-          dumpMirrorClass(sym)
-        }
-      }
-
-      // the pickling info is not written to the module class, but to it's
-      // linked class (the mirror class eventually dumped)
-      if (!(tBuilder.Name.endsWith("$") && sym.isModuleClass)){
-        // think the if inside could be removed, because in this case, addSymtabAttribute is
-        // called in the dumpMirrorClass method
-        addSymtabAttribute(if (isTopLevelModule(sym)) sym.sourceModule else sym, tBuilder)
-
-        // TODO: remove; check the above think:
-        assert(!isTopLevelModule(sym), "can't remove the 'if'")
+        else
+          log("No mirror class for module with linked class: " +
+              sym.fullName)
       }
 
-      addAttributes(tBuilder, sym.attributes)
+      addSymtabAttribute(sym, tBuilder)
+      addAttributes(tBuilder, sym.annotations)
 
       if (iclass.symbol != definitions.ArrayClass)
         iclass.methods foreach genMethod
@@ -549,10 +536,10 @@ abstract class GenMSIL extends SubComponent {
       localBuilders.clear
       computeLocalVarsIndex(m)
 
-      if (m.symbol.isClassConstructor){
-        mcode = constructors(m.symbol.asInstanceOf[clrTypes.global.Symbol]).asInstanceOf[ConstructorBuilder].GetILGenerator()
+      if (m.symbol.isClassConstructor) {
+        mcode = constructors(m.symbol).asInstanceOf[ConstructorBuilder].GetILGenerator()
       } else {
-        val mBuilder = methods(m.symbol.asInstanceOf[clrTypes.global.Symbol]).asInstanceOf[MethodBuilder]
+        val mBuilder = methods(m.symbol).asInstanceOf[MethodBuilder]
         if (!mBuilder.IsAbstract())
           try {
             mcode = mBuilder.GetILGenerator()
@@ -571,7 +558,7 @@ abstract class GenMSIL extends SubComponent {
       }
 
       if (mcode != null) {
-        for (local <- m.locals -- m.params) {
+        for (local <- m.locals ; if !(m.params contains local)) {
           if (settings.debug.value)
             log("add local var: " + local + ", of kind " + local.kind)
           val t: MsilType = msilType(local.kind)
@@ -584,649 +571,320 @@ abstract class GenMSIL extends SubComponent {
 
     }
 
-    var linearization: List[BasicBlock] = Nil
-    // a "ret" instruction is needed (which is not present in
-    //  icode) if there's no code after a try-catch block
-    var needAdditionalRet: Boolean = false
+    /** Special linearizer for methods with at least one exception handler. This
+     *  linearizer brings all basic blocks in the right order so that nested
+     *  try-catch and try-finally blocks can be emitted.
+     */
+    val msilLinearizer = new MSILLinearizer()
 
-    def genCode(m: IMethod) {
-      code = m.code
+    val labels: HashMap[BasicBlock, Label] = new HashMap()
 
-      labels.clear
-      linearization = linearizer.linearize(m)
-      val orderedBlocks = (if (m.exh != Nil) orderBlocksForExh(linearization, m.exh)
-                           else linearization)
-
-      makeLabels(orderedBlocks) // orderBlocksForExh may create new Blocks -> new Labels
-      genBlocks(orderedBlocks)
-      if (needAdditionalRet) {
-        mcode.Emit(OpCodes.Ret)
-        needAdditionalRet = false
-      }
-    }
+    def genCode(m: IMethod) {
 
-    abstract class ExHInstruction(handler: ExceptionHandler) { }
-    case class BeginExceptionBlock(handler: ExceptionHandler) extends ExHInstruction(handler)
-    case class BeginCatchBlock(handler: ExceptionHandler, exceptionType: MsilType) extends ExHInstruction(handler)
-    case class BeginFinallyBlock(handler: ExceptionHandler) extends ExHInstruction(handler)
-    case class EndExceptionBlock(handler: ExceptionHandler) extends ExHInstruction(handler)
-
-
-    abstract class Block {
-      var closed: Boolean = false
-      def parentBlockList: Option[BlockList0]
-      def firstBasicBlock: BasicBlock
-      def lastBasicBlock: BasicBlock
-//      def getExceptionBlock(exh: ExceptionHandler): Option[ExceptionBlock]
-      def close(): Unit
-/*      protected def findExceptionBlock(list: List[Block], exh: ExceptionHandler): Option[ExceptionBlock] = {
-        var res: Option[ExceptionBlock] = None
-        var i: Int = 0
-        while (i < list.length && res == None) {
-          val b = list(i)
-          val exB = b.getExceptionBlock(exh)
-          exB match {
-            case some: Some[ExceptionBlock] => res = some
-            case None => ()
-          }
-          i = i + 1
-        }
-        res
-      } */
-    }
-    case class CodeBlock(parent: BlockList0) extends Block {
-      var basicBlocks: List[BasicBlock] = Nil
-      def isEmpty = basicBlocks.isEmpty
-      override def firstBasicBlock: BasicBlock = {
-        if(isEmpty) null
-        else {
-          if (closed) basicBlocks.head
-          else basicBlocks.last
-        }
-      }
-      override def lastBasicBlock: BasicBlock = {
-        if(isEmpty) null
-        else {
-          if (closed) basicBlocks.last
-          else basicBlocks.head
-        }
-      }
-      override def parentBlockList = Some(parent)
-//      override def getExceptionBlock(exh: ExceptionHandler): Option[ExceptionBlock] = None
-      override def close() {
-        basicBlocks = basicBlocks.reverse
-        closed = true
-      }
-      override def toString() = {
-        var res = ""
-        res = res + TopBlock.indent + "CodeBlock(" + basicBlocks + ")\n"
-        res
-      }
-    }
-    abstract class BlockList0 extends Block {
-      var blocks: List[Block] = Nil
-      override def firstBasicBlock: BasicBlock = {
-        if(blocks.isEmpty) null
-        else {
-          if (closed) blocks.head.firstBasicBlock
-          else blocks.last.firstBasicBlock
-        }
-      }
-      override def lastBasicBlock: BasicBlock = {
-        if(blocks.isEmpty) null
-        else {
-          if (closed) blocks.last.lastBasicBlock
-          else blocks.head.lastBasicBlock
-        }
-      }
-/*      override def getExceptionBlock(exh: ExceptionHandler): Option[ExceptionBlock] = {
-        findExceptionBlock(blocks, exh)
-      } */
-      def addExceptionBlock(exh: ExceptionHandler) = {
-        if (settings.debug.value)
-          log("new exc block with " + exh + " to " + this)
-        val e = new ExceptionBlock(this, exh)
-        blocks = e :: blocks
-        e
-      }
-      def addBasicBlock(bb: BasicBlock) = {
+      def makeLabels(blocks: List[BasicBlock]) = {
         if (settings.debug.value)
-          log("adding bb " + bb + " to " + this)
-        var cb: CodeBlock = if (!blocks.isEmpty) {
-          blocks.head match {
-            case blk: CodeBlock => blk
-            case _ => null
-          }
-        } else null
-        if (cb == null) {
-          cb = new CodeBlock(this)
-          blocks = cb :: blocks
-        }
-        cb.basicBlocks = bb :: cb.basicBlocks
-      }
-      override def close() {
-        blocks.foreach(_.close)
-        blocks = blocks.reverse
-        closed = true
+          log("Making labels for: " + method)
+        for (bb <- blocks) labels(bb) = mcode.DefineLabel()
       }
-      override def toString() = {
-        var res = ""
-        res = res + TopBlock.indent + "BlockList0:\n"
-        TopBlock.indent = TopBlock.indent + "  "
-        for (b <- blocks)
-          res = res + b + "\n"
-        TopBlock.indent = TopBlock.indent.substring(0,TopBlock.indent.length-2)
-        res
-      }
-    }
-    case class BlockList(parent: Block) extends BlockList0 {
-      override def parentBlockList: Option[BlockList0] = {
-        if (parent == TopBlock)
-          Some(TopBlock)
-        else parent match {
-          case bl: BlockList => Some(bl)
-          case cb: CatchBlock => Some(cb)
-          case _ => parent.parentBlockList
-        }
-      }
-      override def toString() = {
-        var res = ""
-        res = res + TopBlock.indent + "BlockList:\n"
-        res = res + super.toString()
-        res
-      }
-    }
-    case class ExceptionBlock(parent: Block, handler: ExceptionHandler) extends Block {
-      var tryBlock: BlockList = new BlockList(this)
-      var catchBlocks: List[CatchBlock] = Nil
-      var finallyBlock: BlockList = new BlockList(this)
-      override def firstBasicBlock = {
-        tryBlock.firstBasicBlock
-      }
-      override def lastBasicBlock = {
-        if (!finallyBlock.blocks.isEmpty)
-          finallyBlock.lastBasicBlock
-        else if(!catchBlocks.isEmpty) {
-          if (closed) catchBlocks.last.lastBasicBlock
-          else catchBlocks.head.lastBasicBlock
-        } else {
-          tryBlock.lastBasicBlock
-        }
-      }
-      override def parentBlockList: Option[BlockList0] = {
-        if (parent == TopBlock)
-          Some(TopBlock)
-        else parent match {
-          case bl: BlockList => Some(bl)
-          case cb: CatchBlock => Some(cb)
-          case _ => parent.parentBlockList
-        }
-      }
-/*      override def getExceptionBlock(exh: ExceptionHandler): Option[ExceptionBlock] = {
-        if (exh == handler) Some(this)
-        else {
-          val t = if (tryBlock == null) Nil else List(tryBlock)
-          val f = if (finallyBlock == null) Nil else List(finallyBlock)
-          findExceptionBlock(t ::: catchBlocks ::: f, exh)
-        }
-      }
-*/
-      def addCatchBlock(exSym: Symbol): CatchBlock = {
-        if (settings.debug.value)
-          log("new catch block with " + exSym + " to " + this)
-        val c = new CatchBlock(this, exSym)
-        catchBlocks = c :: catchBlocks
-        c
-      }
-      override def close() {
-        tryBlock.close
-        catchBlocks.foreach(_.close)
-        catchBlocks = catchBlocks.reverse
-        finallyBlock.close
-        closed = true
-      }
-      override def toString() = {
-        var res = ""
-        res = res + TopBlock.indent + "ExceptionBlock, handler: " + handler + "\n"
-        res = res + TopBlock.indent + "  " + "try:\n"
-        TopBlock.indent = TopBlock.indent + "    "
-        res = res + tryBlock + "\n"
-        TopBlock.indent = TopBlock.indent.substring(0,TopBlock.indent.length-4)
-        res = res + TopBlock.indent + "  " + "catch:\n"
-        TopBlock.indent = TopBlock.indent + "    "
-        for (b <- catchBlocks)
-          res = res + b + "\n"
-        TopBlock.indent = TopBlock.indent.substring(0,TopBlock.indent.length-4)
-        res = res + TopBlock.indent + "  " + "finally:\n"
-        TopBlock.indent = TopBlock.indent + "    "
-        res = res + finallyBlock + "\n"
-        TopBlock.indent = TopBlock.indent.substring(0,TopBlock.indent.length-4)
-        res
-      }
-    }
-    case class CatchBlock(parent: ExceptionBlock, exSym: Symbol) extends BlockList0 {
-      override def parentBlockList: Option[BlockList0] = {
-        parent.parentBlockList
-      }
-      override def toString() = {
-        var res = ""
-        res = res + TopBlock.indent + "CatchBlock:\n"
-        res = res + super.toString()
-        res
-      }
-    }
-    case object TopBlock extends BlockList0 {
-      var indent = ""
-      override def parentBlockList = None
-      override def toString() = {
-        var res = ""
-        res = res + TopBlock.indent + "TopBlock:\n"
-        res = res + super.toString()
-        res
-      }
-    }
-
-    // for every basic block, a list of ExHInstructions to be executed:
-    //   - Begin_ are executed before the block
-    //   - EndExceptionBlock is executed after the block
-    val bb2exHInstructions: HashMap[BasicBlock, List[ExHInstruction]] = new HashMap()
-    // at the end of a try, catch or finally block, the jumps must not be emitted,
-    // the automatically generated leave (or endfinally) will do the job.
-    val omitJumpBlocks: HashSet[BasicBlock] = new HashSet()
-
-    // suposes that finalizers are the same for different handlers
-    // covering the same blocks
-    def orderBlocksForExh(blocks: List[BasicBlock], exH: List[ExceptionHandler]): List[BasicBlock] = {
-
-      var blocksToPut: List[BasicBlock] = blocks
-      var nextBlock: BasicBlock = null
-      var untreatedHandlers: List[ExceptionHandler] = exH
-      TopBlock.blocks = Nil
-      var currentBlock: BlockList0 = TopBlock
-      def addBlocks(b: List[BasicBlock]):Unit = b match {
-        case Nil => if (settings.debug.value) log("adding " + b)
-
-        case x :: xs =>
-          if (settings.debug.value) log("adding " + b)
-          // problem: block may already be added, and and needs to be moved.
-          // if nextblock NOT in b: check if nextblock in blocksToPut, if NOT, check if movable, else don't put
-          if (nextBlock != null && b.contains(nextBlock)) {
-            val blocksToAdd = nextBlock :: (b - nextBlock)
-            nextBlock = null
-            addBlocks(blocksToAdd)
-          }
-          else if (untreatedHandlers.forall(h => !(h.covers(x)))) {
-
-            if (settings.debug.value) log(" no new handler for " + x)
-            if (untreatedHandlers.forall(h => !(h.blocks.contains(x) ||
-                                                (h.finalizer != null &&
-                                                 h.finalizer.covers(x)))))
-              {
-                // the block is not part of some catch or finally code
-                currentBlock.addBasicBlock(x)
-                blocksToPut = blocksToPut - x
-                if (settings.debug.value) log(" -> addBlocks(" + xs + ")")
-                addBlocks(xs)
-              } else {
-                if (settings.debug.value) log("x is part of catch or finally block")
-
-                // check if the covered code of the handler x belongs to is empty
-                // this check is not needed for finalizers: empty try with finalizer
-                // is optimized by compiler (no try left)
-                if(untreatedHandlers.forall(h =>
-                  (!h.blocks.contains(x) || h.covered.isEmpty))) {
-                    blocksToPut = blocksToPut - x
-                    addBlocks(xs)
-                  } else
-                    addBlocks(xs ::: List(x))
-              }
-          } else { // there are new handlers for this block
-
-            var firstBlockAfter: HashMap[ExceptionHandler,BasicBlock] = new HashMap()
-            val savedCurrentBlock = currentBlock
-            /**
-             * the output blocks of this method are changed so that:
-             *  - only one block has a successor outside the set of blocks
-             *  - this block is the last of the reusulting list
-             *
-             * side-effect: it stores the successor in the hashMap
-             *  firstBlockAfter, which has to be emitted first after try/catch/finally,
-             *  because the target of the Leave-instruction will always be the first
-             *  instruction after EndExceptionBlock
-             *
-             * returns: the output blocks plus an Option containing the possibly created
-             * new block
-             **/
-            def adaptBlocks(blocks: List[BasicBlock], exh: ExceptionHandler): (List[BasicBlock], Option[BasicBlock]) = {
-              def outsideTargets(block: BasicBlock, blocks: List[BasicBlock]) = {
-                /* The catch block of the ExceptionHandler is always a successor of any block inside the try
-                 * (see successors method in BasicBlocks.scala)
-                 * Thus, this successor does not correspond to a jump outside the exception handler
-                 * and has to be ignored when computing the list of blocks leaving the exception handler.  */
-                val res = block.successors.filter(scc => !blocks.contains(scc) && scc != exh.startBlock)
-                if (settings.debug.value) log("outside of " + block + " = " + res + " succ " + block.successors)
-                res
-              }
-              // get leaving blocks and their outside targets
-              def leavingBlocks(blocks: List[BasicBlock]): List[(BasicBlock, List[BasicBlock])] = {
-                for {b <- blocks
-                     val t = outsideTargets(b, blocks)
-                     if t.length != 0 } yield (b, t)
-              }
 
-              def replaceOutJumps(blocks: List[BasicBlock], leaving: List[(BasicBlock, List[BasicBlock])], exh: ExceptionHandler): (List[BasicBlock], Option[BasicBlock]) = {
-                def replaceJump(block: BasicBlock, from: BasicBlock, to: BasicBlock) = block.lastInstruction match {
-                  case JUMP(whereto) =>
-                    //assert(from == whereto)
-                    block.replaceInstruction(block.lastInstruction, JUMP(to))
-                  case CJUMP(success, failure, cond, kind) =>
-                    if (from == success)
-                      block.replaceInstruction(block.lastInstruction, CJUMP(to, failure, cond, kind))
-                    else
-                      //assert(from == failure)
-                    if (from == failure)
-                      block.replaceInstruction(block.lastInstruction, CJUMP(success, to, cond, kind))
-                  case CZJUMP(success, failure, cond, kind) =>
-                    if (from == success)
-                      block.replaceInstruction(block.lastInstruction, CZJUMP(to, failure, cond, kind))
-                    else
-                      //assert(from == failure)
-                    if (from == failure)
-                      block.replaceInstruction(block.lastInstruction, CZJUMP(success, to, cond, kind))
-                  case SWITCH(tags, labels) => // labels: List[BasicBlock]
-                    val newLabels = labels.map(b => if (b == from) to else b)
-                    assert(newLabels.contains(to))
-                    block.replaceInstruction(block.lastInstruction, SWITCH(tags, newLabels))
-                  /*
-                  case RETURN(kind) =>
-                    if (kind != UNIT) {
-                        returnVal
-                    }
-                    block.replaceInstruction(block.lastInstructionm JUMP(to))
-                  */
-                  case _ => () //abort("expected branch at the end of block " + block)
-                }
-
-                val jumpOutBlock = blocks.last.code.newBlock
-                jumpOutBlock.emit(JUMP(firstBlockAfter(exh)))
-                jumpOutBlock.close
-                leaving.foreach(p => {
-                  val lBlock = p._1
-                  val target = p._2(0) // the elemets of p._2 are all the same, checked before
-                  replaceJump(lBlock, target, jumpOutBlock)
-                  if (settings.debug.value) log("replacing " + lBlock + " target " + target + " jump out " + jumpOutBlock)
-                })
-                (blocks ::: List(jumpOutBlock), Some(jumpOutBlock))
-              }
+      labels.clear
 
-              val leaving = leavingBlocks(blocks)
-              if (settings.debug.value) log("leaving " + leaving)
-              if (leaving.length == 0)
-                (blocks, None)
-              else if (leaving.length == 1) {
-                val outside = leaving(0)._2
-                //assert(outside.forall(b => b == outside(0)), "exception-block leaving to multiple targets")
-                if (!firstBlockAfter.isDefinedAt(exh))
-                  firstBlockAfter(exh) = outside(0)
-                //else ()
-                  //assert(firstBlockAfter(exh) == outside(0), "try/catch leaving to multiple targets: " + firstBlockAfter(exh) + ", new: " + outside(0))
-                val last = leaving(0)._1
-                ((blocks - last) ::: List(last), None)
-              } else {
-                val outside = leaving.flatMap(p => p._2)
-                //assert(outside.forall(b => b == outside(0)), "exception-block leaving to multiple targets")
-                if (!firstBlockAfter.isDefinedAt(exh))
-                  firstBlockAfter(exh) = outside(0)
-                //else
-                  //assert(firstBlockAfter(exh) == outside(0), "try/catch leaving to multiple targets")
-                replaceOutJumps(blocks, leaving, exh)
-              }
-            }
+      var linearization = if(m.exh != Nil) msilLinearizer.linearize(m)
+                          else linearizer.linearize(m)
 
-            var affectedHandlers: List[ExceptionHandler] = Nil
-            untreatedHandlers.foreach( (h) => {
-              if (h.covers(x)){
-                affectedHandlers = h :: affectedHandlers
-              }
-            })
-
-            // shorter try-catch-finally last (the ones contained in another)
-            affectedHandlers = affectedHandlers.sort({(h1, h2) => h1.covered.size > h2.covered.size})
-            affectedHandlers = affectedHandlers.filter(h => {h.covered.size == affectedHandlers(0).covered.size})
-            untreatedHandlers = untreatedHandlers -- affectedHandlers
-
-            // more than one catch produces more than one exh, but we only need one
-            var singleAffectedHandler: ExceptionHandler = affectedHandlers(0) // List[ExceptionHandler] = Nil
-            var exceptionBlock: Option[ExceptionBlock] = None
-            if (settings.debug.value) log("affected handlers " + affectedHandlers)
-            affectedHandlers.foreach(h1 => {
-              val (adaptedBlocks, newBlock) = adaptBlocks(blocksToPut.intersect(h1.blocks), singleAffectedHandler)
-              newBlock match {
-                case Some(block) =>
-                  blocksToPut = blocksToPut ::: List(block)
-                  h1.addBlock(block)
-                case None => ()
-              }
-              val orderedCatchBlocks = h1.startBlock :: (adaptedBlocks - h1.startBlock)
-
-              exceptionBlock match {
-                case Some(excBlock) =>
-                  val catchBlock = excBlock.addCatchBlock(h1.cls)
-                  currentBlock = catchBlock
-                  addBlocks(orderedCatchBlocks)
-                case None =>
-                  val excBlock = currentBlock.addExceptionBlock(singleAffectedHandler)
-                  exceptionBlock = Some(excBlock)
-
-                  val (tryBlocks, newBlock) = adaptBlocks(blocksToPut.intersect(singleAffectedHandler.covered.toList), singleAffectedHandler)
-
-                  newBlock match {
-                    case Some(block) =>
-                      blocksToPut = blocksToPut ::: List(block)
-                      singleAffectedHandler.addCoveredBlock(block)
-                    case None => ()
-                  }
-                  currentBlock = excBlock.tryBlock
-                  if (settings.debug.value) log("adding try blocks " + tryBlocks)
-                  addBlocks(tryBlocks)
-
-                  if (singleAffectedHandler.finalizer != null && singleAffectedHandler.finalizer != NoFinalizer) {
-                    val (blocks0, newBlock) = adaptBlocks(blocksToPut.intersect(singleAffectedHandler.finalizer.blocks), singleAffectedHandler)
-                    newBlock match {
-                      case Some(block) =>
-                        blocksToPut = blocksToPut ::: List(block)
-                        singleAffectedHandler.finalizer.addBlock(block)
-                      case None => ()
-                    }
-                    val blocks = singleAffectedHandler.finalizer.startBlock :: (blocks0 - singleAffectedHandler.finalizer.startBlock)
-                    currentBlock = excBlock.finallyBlock
-                    addBlocks(blocks)
-                  }
+      if (m.exh != Nil)
+        linearization = computeExceptionMaps(linearization, m)
 
-                  val catchBlock = excBlock.addCatchBlock(singleAffectedHandler.cls)
-                  currentBlock = catchBlock
-                  addBlocks(orderedCatchBlocks)
-              }
-              if (firstBlockAfter.isDefinedAt(singleAffectedHandler))
-                nextBlock = firstBlockAfter(singleAffectedHandler)
-              else
-                nextBlock = null
-            })
+      makeLabels(linearization)
 
-            currentBlock = savedCurrentBlock
+      genBlocks(linearization)
 
-            if (settings.debug.value)
-              log(" -> addBlocks(" + xs.intersect(blocksToPut) + ")")
-            addBlocks(xs.intersect(blocksToPut))
-          }
+      // RETURN inside exception blocks are replaced by Leave. The target of the
+      // leave is a `Ret` outside any exception block (generated here).
+      if (handlerReturnMethod == m) {
+        mcode.MarkLabel(handlerReturnLabel)
+        if (handlerReturnKind != UNIT)
+          mcode.Emit(OpCodes.Ldloc, handlerReturnLocal)
+        mcode.Emit(OpCodes.Ret)
       }
 
-      // begin method orderBlocksForExh
+      beginExBlock.clear()
+      beginCatchBlock.clear()
+      endExBlock.clear()
+      endFinallyLabels.clear()
+    }
 
-      if (settings.debug.value)
-        log("before: " + blocks)
-      // some blocks may have been removed by linearization
-      untreatedHandlers.foreach(h => {
-        h.blocks = h.blocks.intersect(blocksToPut)
-        h.covered = h.covered.intersect(collection.immutable.HashSet.empty ++ blocksToPut)
-        if (h.finalizer != null && h.finalizer != NoFinalizer)
-          h.finalizer.blocks = h.finalizer.blocks.intersect(blocksToPut)
-      })
-      addBlocks(blocks)
+    def genBlocks(blocks: List[BasicBlock], previous: BasicBlock = null) {
+      blocks match {
+        case Nil => ()
+        case x :: Nil => genBlock(x, prev = previous, next = null)
+        case x :: y :: ys => genBlock(x, prev = previous, next = y); genBlocks(y :: ys, previous = x)
+      }
+    }
 
-      TopBlock.close()
+    // the try blocks starting at a certain BasicBlock
+    val beginExBlock = new HashMap[BasicBlock, List[ExceptionHandler]]()
 
-      if (settings.debug.value) log("TopBlock tree is: ")
-      if (settings.debug.value) log(TopBlock)
+    // the catch blocks starting / endling at a certain BasicBlock
+    val beginCatchBlock = new HashMap[BasicBlock, ExceptionHandler]()
+    val endExBlock = new HashMap[BasicBlock, List[ExceptionHandler]]()
 
-      bb2exHInstructions.clear
-      def addExHInstruction(b: BasicBlock, ehi: ExHInstruction) = {
-        if (settings.debug.value)
-          log("adding exhinstr: " + b + " -> " + ehi)
-
-        if (bb2exHInstructions.contains(b)){
-          bb2exHInstructions(b) = ehi :: bb2exHInstructions(b)
-        } else {
-          bb2exHInstructions(b) = List(ehi)
+    /** When emitting the code (genBlock), the number of currently active try / catch
+     *  blocks. When seeing a `RETURN' inside a try / catch, we need to
+     *   - store the result in a local (if it's not UNIT)
+     *   - emit `Leave handlerReturnLabel` instead of the Return
+     *   - emit code at the end: load the local and return its value
+     */
+    var currentHandlers = new Stack[ExceptionHandler]
+    // The IMethod the Local/Label/Kind below belong to
+    var handlerReturnMethod: IMethod = _
+    // Stores the result when returning inside an exception block
+    var handlerReturnLocal: LocalBuilder = _
+    // Label for a return instruction outside any exception block
+    var handlerReturnLabel: Label = _
+    // The result kind.
+    var handlerReturnKind: TypeKind = _
+    def returnFromHandler(kind: TypeKind): (LocalBuilder, Label) = {
+      if (handlerReturnMethod != method) {
+        handlerReturnMethod = method
+        if (kind != UNIT) {
+          handlerReturnLocal = mcode.DeclareLocal(msilType(kind))
+          handlerReturnLocal.SetLocalSymInfo("$handlerReturn")
         }
+        handlerReturnLabel = mcode.DefineLabel()
+        handlerReturnKind = kind
       }
-      omitJumpBlocks.clear
-      def omitJump(blk: BasicBlock) = {
-        omitJumpBlocks += blk
-      }
-      var orderedBlocks: List[BasicBlock] = Nil
-      def flatten(block: Block) {
-        if (block == TopBlock) {
-          for (b <- TopBlock.blocks) flatten(b)
-        } else block match {
-          case cb: CodeBlock =>
-            orderedBlocks = orderedBlocks ::: cb.basicBlocks
-          case bl: BlockList =>
-            for (b <- bl.blocks) flatten(b)
-          case cb: CatchBlock =>
-            for (b <- cb.blocks) flatten(b)
-          case eb: ExceptionBlock =>
-            val handler = eb.handler
-            if (settings.debug.value) {
-              log("new exception block " + eb)
-              log("try: " + eb.tryBlock)
-            }
-            addExHInstruction(eb.tryBlock.firstBasicBlock, new BeginExceptionBlock(handler))
-            omitJump(eb.tryBlock.lastBasicBlock)
-            flatten(eb.tryBlock)
-            for (c <- eb.catchBlocks) {
-              val t: MsilType = (if (c.exSym == NoSymbol) EXCEPTION
-                                 else getType(c.exSym))
-              addExHInstruction(c.firstBasicBlock, new BeginCatchBlock(handler, t))
-              omitJump(c.lastBasicBlock)
-              flatten(c)
-            }
-            if (handler.finalizer != null && handler.finalizer != NoFinalizer) {
-              addExHInstruction(eb.finallyBlock.firstBasicBlock, new BeginFinallyBlock(handler))
-              flatten(eb.finallyBlock)
-              addExHInstruction(eb.finallyBlock.lastBasicBlock, new EndExceptionBlock(handler))
-              omitJump(eb.finallyBlock.lastBasicBlock)
-            } else {
-              addExHInstruction(eb.catchBlocks.last.lastBasicBlock, new EndExceptionBlock(handler))
+      (handlerReturnLocal, handlerReturnLabel)
+    }
+
+    /** For try/catch nested inside a finally, we can't use `Leave OutsideFinally`, the
+     *  Leave target has to be inside the finally (and it has to be the `endfinally` instruction).
+     *  So for every finalizer, we have a label which marks the place of the `endfinally`,
+     *  nested try/catch blocks will leave there.
+     */
+    val endFinallyLabels = new HashMap[ExceptionHandler, Label]()
+
+    /** Computes which blocks are the beginning / end of a try or catch block */
+    private def computeExceptionMaps(blocks: List[BasicBlock], m: IMethod): List[BasicBlock] = {
+      val visitedBlocks = new HashSet[BasicBlock]()
+
+      // handlers which have not been introduced so far
+      var openHandlers = m.exh
+
+
+      /** Example
+       *   try {
+       *     try {
+       *         // *1*
+       *     } catch {
+       *       case h1 =>
+       *     }
+       *   } catch {
+       *     case h2 =>
+       *     case h3 =>
+       *       try {
+       *
+       *       } catch {
+       *         case h4 =>  // *2*
+       *         case h5 =>
+       *       }
+       *   }
+       */
+
+      // Stack of nested try blocks. Each bloc has a List of ExceptionHandler (multiple
+      // catch statements). Example *1*: Stack(List(h2, h3), List(h1))
+      val currentTryHandlers = new Stack[List[ExceptionHandler]]()
+
+      // Stack of nested catch blocks. The head of the list is the current catch block. The
+      // tail is all following catch blocks. Example *2*: Stack(List(h3), List(h4, h5))
+      val currentCatchHandlers = new Stack[List[ExceptionHandler]]()
+
+      for (b <- blocks) {
+
+        // are we past the current catch blocks?
+        def endHandlers(): List[ExceptionHandler] = {
+          var res: List[ExceptionHandler] = Nil
+          if (!currentCatchHandlers.isEmpty) {
+            val handler = currentCatchHandlers.top.head
+            if (!handler.blocks.contains(b)) {
+              // all blocks of the handler are either visited, or not part of the linearization (i.e. dead)
+              assert(handler.blocks.forall(b => visitedBlocks.contains(b) || !blocks.contains(b)),
+                     "Bad linearization of basic blocks inside catch. Found block not part of the handler\n"+
+                     b.fullString +"\nwhile in catch-part of\n"+ handler)
+
+              val rest = currentCatchHandlers.pop.tail
+              if (rest.isEmpty) {
+                // all catch blocks of that exception handler are covered
+                res = handler :: endHandlers()
+              } else {
+                // there are more catch blocks for that try (handlers covering the same)
+                currentCatchHandlers.push(rest)
+                beginCatchBlock(b) = rest.head
+              }
             }
+          }
+          res
+        }
+        val end = endHandlers()
+        if (!end.isEmpty) endExBlock(b) = end
+
+        // are we past the current try block?
+        if (!currentTryHandlers.isEmpty) {
+          val handler = currentTryHandlers.top.head
+          if (!handler.covers(b)) {
+            // all of the covered blocks are visited, or not part of the linearization
+            assert(handler.covered.forall(b => visitedBlocks.contains(b) || !blocks.contains(b)),
+                   "Bad linearization of basic blocks inside try. Found non-covered block\n"+
+                   b.fullString +"\nwhile in try-part of\n"+ handler)
+
+            assert(handler.startBlock == b,
+                   "Bad linearization of basic blocks. The entry block of a catch does not directly follow the try\n"+
+                   b.fullString +"\n"+ handler)
+
+            val handlers = currentTryHandlers.pop
+            currentCatchHandlers.push(handlers)
+            beginCatchBlock(b) = handler
+          }
         }
-      }
-
-      flatten(TopBlock)
-
-      assert(untreatedHandlers.forall((h) => h.covered.isEmpty),
-             "untreated exception handlers left: " + untreatedHandlers)
-      // remove catch blocks from empty handlers (finally-blocks remain)
-      untreatedHandlers.foreach((h) => {
-        orderedBlocks = orderedBlocks -- h.blocks
-      })
-
-      // take care of order in which exHInstructions are executed (BeginExceptionBlock as last)
-      bb2exHInstructions.keys.foreach((b) => {
-        bb2exHInstructions(b).sort((i1, i2) => (!i1.isInstanceOf[BeginExceptionBlock]))
-      })
-
 
-      if (settings.debug.value){
-        log("after: " + orderedBlocks)
-        log(" exhInstr: " + bb2exHInstructions)
+        // are there try blocks starting at b?
+        val (newHandlers, stillOpen) = openHandlers.partition(_.covers(b))
+        openHandlers = stillOpen
+
+        val newHandlersBySize = newHandlers.groupBy(_.covered.size)
+        // big handlers first, smaller ones are nested inside the try of the big one
+        // (checked by the assertions below)
+        val sizes = newHandlersBySize.keys.toList.sortWith(_ > _)
+
+        val beginHandlers = new ListBuffer[ExceptionHandler]
+        for (s <- sizes) {
+          val sHandlers = newHandlersBySize(s)
+          for (h <- sHandlers) {
+            assert(h.covered == sHandlers.head.covered,
+                   "bad nesting of exception handlers. same size, but not covering same blocks\n"+
+                   h +"\n"+ sHandlers.head)
+            assert(h.resultKind == sHandlers.head.resultKind,
+                   "bad nesting of exception handlers. same size, but the same resultKind\n"+
+                   h +"\n"+ sHandlers.head)
+          }
+          for (bigger <- beginHandlers; h <- sHandlers) {
+            assert(h.covered.subsetOf(bigger.covered),
+                   "bad nesting of exception handlers. try blocks of smaller handler are not nested in bigger one.\n"+
+                   h +"\n"+ bigger)
+            assert(h.blocks.toSet.subsetOf(bigger.covered),
+                   "bad nesting of exception handlers. catch blocks of smaller handler are not nested in bigger one.\n"+
+                   h +"\n"+ bigger)
+          }
+          beginHandlers += sHandlers.head
+          currentTryHandlers.push(sHandlers)
+        }
+        beginExBlock(b) = beginHandlers.toList
+        visitedBlocks += b
+      }
+
+      // if there handlers left (i.e. handlers covering nothing, or a
+      // non-existent (dead) block), remove their catch-blocks.
+      val liveBlocks = if (openHandlers.isEmpty) blocks else {
+        blocks.filter(b => openHandlers.forall(h => !h.blocks.contains(b)))
+      }
+
+      /** There might be open handlers, but no more blocks. happens when try/catch end
+       *  with `throw` or `return`
+       *     def foo { try { .. throw } catch { _ => .. throw } }
+       *
+       *  In this case we need some code after the catch block for the auto-generated
+       *  `leave` instruction. So we're adding a (dead) `throw new Exception`.
+       */
+      val rest = currentCatchHandlers.map(handlers => {
+        assert(handlers.length == 1, handlers)
+        handlers.head
+      }).toList
+
+      if (rest.isEmpty) {
+        liveBlocks
+      } else {
+        val b = m.code.newBlock
+        b.emit(Seq(
+          NEW(REFERENCE(definitions.ThrowableClass)),
+          DUP(REFERENCE(definitions.ObjectClass)),
+          CALL_METHOD(definitions.ThrowableClass.primaryConstructor, Static(true)),
+          THROW()
+        ))
+        b.close
+        endExBlock(b) = rest
+        liveBlocks ::: List(b)
       }
-
-      orderedBlocks
     }
 
-    var currentBlock: BasicBlock = _
-    var lastBlock: BasicBlock = _
-    var nextBlock: BasicBlock = _
-
-    def genBlocks(l: List[BasicBlock]) {
-      l match {
-        case Nil => ()
-        case x :: Nil => currentBlock = x; nextBlock = null; genBlock(x)
-        case x :: y :: ys => currentBlock = x; nextBlock = y; genBlock(x); genBlocks(y :: ys)
-      }
-    }
+    /**
+     *  @param block the BasicBlock to emit code for
+     *  @param next  the following BasicBlock, `null` if `block` is the last one
+     */
+    def genBlock(block: BasicBlock, prev: BasicBlock, next: BasicBlock) {
+      /** Creating objects works differently on .NET. On the JVM
+       *  - NEW(type) => reference on Stack
+       *  - DUP, load arguments, CALL_METHOD(constructor)
+       *
+       * On .NET, the NEW and DUP are ignored, but we emit a special method call
+       *  - load arguments
+       *  - NewObj(constructor) => reference on stack
+       *
+       * This variable tells whether the previous instruction was a NEW,
+       * we expect a DUP which is not emitted. */
+      var previousWasNEW = false
 
-    var ignoreNextDup: Boolean = false
-    val excResultLocals: Stack[LocalBuilder] = new Stack()
+      var lastLineNr: Int = 0
 
-    def genBlock(b: BasicBlock) {
-      // at begin of the first block, there's nothing to save =>
-      //  lastBlock != null is secure
-      def saveResult(resType: MsilType) = if (resType != MVOID && lastBlock != null) {
-        lastBlock.lastInstruction match {
-          case THROW() => ()
-          case _ =>
-            val lb: LocalBuilder = excResultLocals.top
-            mcode.Emit(OpCodes.Stloc, lb)
-        }
-      }
 
-      if (bb2exHInstructions.contains(b)){
-        bb2exHInstructions(b).foreach((i) => i match {
-          case BeginExceptionBlock(handler) =>
-            if (settings.debug.value) log("begin ex blk: " + handler)
-            mcode.BeginExceptionBlock()
-            val resType = msilType(handler.resultKind)
-            if (resType != MVOID) {
-              val l = mcode.DeclareLocal(resType)
-              l.SetLocalSymInfo("$exhResult")
-              excResultLocals.push(l)
-            }
-          case BeginCatchBlock(handler, exType) =>
-            if (settings.debug.value) log("begin catch blk: " + handler + ", tpe: " + exType)
-            saveResult(msilType(handler.resultKind))
-            mcode.BeginCatchBlock(exType)
-          case BeginFinallyBlock(handler) =>
-            saveResult(msilType(handler.resultKind))
-            mcode.BeginFinallyBlock()
-          case EndExceptionBlock(handler) => ()
-          case _ => abort("unknown case: " + i)
-        })
+      // EndExceptionBlock must happen before MarkLabel because it adds the
+      // Leave instruction. Otherwise, labels(block) points to the Leave
+      // (inside the catch) instead of the instruction afterwards.
+      for (handlers <- endExBlock.get(block); exh <- handlers) {
+        currentHandlers.pop()
+        for (l <- endFinallyLabels.get(exh))
+          mcode.MarkLabel(l)
+        mcode.EndExceptionBlock()
       }
 
-      mcode.MarkLabel(labels(b))
+      mcode.MarkLabel(labels(block))
       if (settings.debug.value)
-        log("Generating code for block: " + b)
-
-      var lastLineNr: Int = 0
-
-      for (instr <- b) {
+        log("Generating code for block: " + block)
 
-        needAdditionalRet = false
+      for (handler <- beginCatchBlock.get(block)) {
+        if (!currentHandlers.isEmpty && currentHandlers.top.covered == handler.covered) {
+          currentHandlers.pop()
+          currentHandlers.push(handler)
+        }
+        if (handler.cls == NoSymbol) {
+          // `finally` blocks are represented the same as `catch`, but with no catch-type
+          mcode.BeginFinallyBlock()
+        } else {
+          val t = getType(handler.cls)
+          mcode.BeginCatchBlock(t)
+        }
+      }
+      for (handlers <- beginExBlock.get(block); exh <- handlers) {
+        currentHandlers.push(exh)
+        mcode.BeginExceptionBlock()
+      }
 
-	    val currentLineNr = (instr.pos).line match {
-          case Some(line) => line
-          case None =>
+      for (instr <- block) {
+        val currentLineNr = try {
+          instr.pos.line
+        } catch {
+          case _: UnsupportedOperationException =>
             log("Warning: wrong position in: " + method)
-          lastLineNr
-        } // if getting line number fails
+            lastLineNr
+        }
 
         if (currentLineNr != lastLineNr) {
           mcode.setPosition(currentLineNr)
           lastLineNr = currentLineNr
         }
 
+        if (previousWasNEW)
+          assert(instr.isInstanceOf[DUP], block)
+
         instr match {
           case THIS(clasz) =>
             mcode.Emit(OpCodes.Ldarg_0)
@@ -1262,9 +920,7 @@ abstract class GenMSIL extends SubComponent {
               case FLOAT          => mcode.Emit(OpCodes.Ldelem_R4)
               case DOUBLE         => mcode.Emit(OpCodes.Ldelem_R8)
               case REFERENCE(cls) => mcode.Emit(OpCodes.Ldelem_Ref)
-
-              // case ARRAY(elem) is not possible, for Array[Array[Int]], the
-              //  load will be case REFERENCE(java.lang.Object)
+              case ARRAY(elem)    => mcode.Emit(OpCodes.Ldelem_Ref)
 
               // case UNIT is not possible: an Array[Unit] will be an
               //  Array[scala.runtime.BoxedUnit] (-> case REFERENCE)
@@ -1273,30 +929,26 @@ abstract class GenMSIL extends SubComponent {
           case LOAD_LOCAL(local) =>
             if (settings.debug.value)
               log("load_local for " + local)
-            val isArg: Boolean = local.arg
+            val isArg = local.arg
             val i = local.index
-            if (isArg) {
+            if (isArg)
               loadArg(mcode)(i)
-            }
-            else {
+            else
               loadLocal(i, local, mcode)
-            }
 
           case LOAD_FIELD(field, isStatic) =>
             if (settings.debug.value)
               log("LOAD_FIELD with owner: " + field.owner +
                   " flags: " + Flags.flagsToString(field.owner.flags))
-
-            var fieldInfo: FieldInfo = fields.get(field.asInstanceOf[clrTypes.global.Symbol]) match {
+            var fieldInfo = fields.get(field) match {
               case Some(fInfo) => fInfo
               case None =>
                 val fInfo = getType(field.owner).GetField(msilName(field))
-                fields(field.asInstanceOf[clrTypes.global.Symbol]) = fInfo
+                fields(field) = fInfo
                 fInfo
             }
             mcode.Emit(if (isStatic) OpCodes.Ldsfld else OpCodes.Ldfld, fieldInfo)
 
-
           case LOAD_MODULE(module) =>
             if (settings.debug.value)
               log("Generating LOAD_MODULE for: " + showsym(module))
@@ -1313,12 +965,13 @@ abstract class GenMSIL extends SubComponent {
               case FLOAT          => mcode.Emit(OpCodes.Stelem_R4)
               case DOUBLE         => mcode.Emit(OpCodes.Stelem_R8)
               case REFERENCE(cls) => mcode.Emit(OpCodes.Stelem_Ref)
+              case ARRAY(elem)    => mcode.Emit(OpCodes.Stelem_Ref) // @TODO: test this! (occurs when calling a Array[Object]* vararg param method)
 
-              // case UNIT / ARRRAY are not possible (see comment at LOAD_ARRAY_ITEM)
+              // case UNIT not possible (see comment at LOAD_ARRAY_ITEM)
             }
 
           case STORE_LOCAL(local) =>
-            val isArg: Boolean = local.arg
+            val isArg = local.arg
             val i = local.index
             if (settings.debug.value)
               log("store_local for " + local + ", index " + i)
@@ -1348,22 +1001,20 @@ abstract class GenMSIL extends SubComponent {
             // this only works for impl classes because the self parameter comes first
             // in the method signature. If that changes, this code has to be revisited.
             mcode.Emit(OpCodes.Starg_S, 0)
-            
+
           case STORE_FIELD(field, isStatic) =>
-            val fieldInfo: FieldInfo = fields.get(field.asInstanceOf[clrTypes.global.Symbol]) match {
+            val fieldInfo = fields.get(field) match {
               case Some(fInfo) => fInfo
               case None =>
                 val fInfo = getType(field.owner).GetField(msilName(field))
-                fields(field.asInstanceOf[clrTypes.global.Symbol]) = fInfo
+                fields(field) = fInfo
                 fInfo
             }
             mcode.Emit(if (isStatic) OpCodes.Stsfld else OpCodes.Stfld, fieldInfo)
 
-
           case CALL_PRIMITIVE(primitive) =>
             genPrimitive(primitive, instr.pos)
 
-
           case CALL_METHOD(msym, style) =>
             if (msym.isClassConstructor) {
               val constructorInfo: ConstructorInfo = getConstructor(msym)
@@ -1371,6 +1022,12 @@ abstract class GenMSIL extends SubComponent {
                 // normal constructor calls are Static..
                 case Static(_) =>
                   if (method.symbol.isClassConstructor && method.symbol.owner == msym.owner)
+                    // we're generating a constructor (method: IMethod is a constructor), and we're
+                    // calling another constructor of the same class.
+
+                    // @LUC TODO: this can probably break, namely when having: class A { def this { new A() } }
+                    // instead, we should instruct the CALL_METHOD with additional information, know whether it's
+                    // an instance creation constructor call or not.
                     mcode.Emit(OpCodes.Call, constructorInfo)
                   else
                     mcode.Emit(OpCodes.Newobj, constructorInfo)
@@ -1398,8 +1055,8 @@ abstract class GenMSIL extends SubComponent {
                 mcode.Emit(OpCodes.Add) // compute length (-start + end)
               }
 
-              var doEmit: Boolean = true
-              types.get(msym.owner.asInstanceOf[clrTypes.global.Symbol]) match {
+              var doEmit = true
+              getTypeOpt(msym.owner) match {
                 case Some(typ) if (typ.IsEnum) => {
                   def negBool = {
                     mcode.Emit(OpCodes.Ldc_I4_0)
@@ -1423,12 +1080,13 @@ abstract class GenMSIL extends SubComponent {
               }
 
               // method: implicit view(FunctionX[PType0, PType1, ...,PTypeN, ResType]):DelegateType
-              val (isDelegateView, paramType, resType) = atPhase(currentRun.typerPhase){
+              val (isDelegateView, paramType, resType) = atPhase(currentRun.typerPhase) {
                 msym.tpe match {
-                  case MethodType(parameterTypes, resultType)
-                  if (parameterTypes.length == 1 && msym.name == nme.view_) =>
-                    val isDel = definitions.isCorrespondingDelegate(resultType, parameterTypes(0))
-                    (isDel, parameterTypes(0), resultType)
+                  case MethodType(params, resultType)
+                  if (params.length == 1 && msym.name == nme.view_) =>
+                    val paramType = params(0).tpe
+                    val isDel = definitions.isCorrespondingDelegate(resultType, paramType)
+                    (isDel, paramType, resultType)
                   case _ => (false, null, null)
                 }
               }
@@ -1468,7 +1126,7 @@ abstract class GenMSIL extends SubComponent {
 
               if (doEmit) {
                 val methodInfo: MethodInfo = getMethod(msym)
-                style match {
+                (style: @unchecked) match {
                   case SuperCall(_) =>
                     mcode.Emit(OpCodes.Call, methodInfo)
                   case Dynamic =>
@@ -1480,12 +1138,13 @@ abstract class GenMSIL extends SubComponent {
               }
             }
 
-          case BOX(boxType) => emitBox(mcode, boxType) //mcode.Emit(OpCodes.Box, msilType(boxType))
+          case BOX(boxType) => emitBox(mcode, boxType)
 
           case UNBOX(boxType) => emitUnbox(mcode, boxType)
 
           case NEW(REFERENCE(cls)) =>
-            ignoreNextDup = true
+            // the next instruction must be a DUP, see comment on `var previousWasNEW`
+            previousWasNEW = true
 
           // works also for arrays and reference-types
           case CREATE_ARRAY(elem, dims) =>
@@ -1501,7 +1160,6 @@ abstract class GenMSIL extends SubComponent {
             mcode.Emit(OpCodes.Ldc_I4_0)
             mcode.Emit(OpCodes.Ceq)
 
-
           // works for arrays and reference-types
           // part from the scala reference: "S <: T does not imply
           //  Array[S] <: Array[T] in Scala. However, it is possible
@@ -1509,7 +1167,6 @@ abstract class GenMSIL extends SubComponent {
           //  is permitted in the host environment."
           case CHECK_CAST(tpe) => mcode.Emit(OpCodes.Castclass, msilType(tpe))
 
-
           // no SWITCH is generated when there's
           //  - a default case ("case _ => ...") in the matching expr
           //  - OR is used ("case 1 | 2 => ...")
@@ -1518,7 +1175,7 @@ abstract class GenMSIL extends SubComponent {
             //    if the int on stack is 4, and 4 is in the second list => jump
             //    to second label
             // branches is List[BasicBlock]
-            //    the labels to jump to (the last one ist the default one)
+            //    the labels to jump to (the last one is the default one)
 
             val switchLocal = mcode.DeclareLocal(MINT)
             // several switch variables will appear with the same name in the
@@ -1526,7 +1183,7 @@ abstract class GenMSIL extends SubComponent {
             switchLocal.SetLocalSymInfo("$switch_var")
 
             mcode.Emit(OpCodes.Stloc, switchLocal)
-            var i: Int = 0
+            var i = 0
             for (l <- tags) {
               var targetLabel = labels(branches(i))
               for (i <- l) {
@@ -1537,44 +1194,40 @@ abstract class GenMSIL extends SubComponent {
               i += 1
             }
             val defaultTarget = labels(branches(i))
-            if (nextBlock != defaultTarget && !omitJumpBlocks.contains(currentBlock))
+            if (next != defaultTarget)
               mcode.Emit(OpCodes.Br, defaultTarget)
 
-
           case JUMP(whereto) =>
-            if (nextBlock != whereto && !omitJumpBlocks.contains(currentBlock))
+            val (leaveHandler, leaveFinally, lfTarget) = leavesHandler(block, whereto)
+            if (leaveHandler) {
+              if (leaveFinally) {
+                if (lfTarget.isDefined) mcode.Emit(OpCodes.Leave, lfTarget.get)
+                else mcode.Emit(OpCodes.Endfinally)
+              } else
+                mcode.Emit(OpCodes.Leave, labels(whereto))
+            } else if (next != whereto)
               mcode.Emit(OpCodes.Br, labels(whereto))
 
-
           case CJUMP(success, failure, cond, kind) =>
             // cond is TestOp (see Primitives.scala), and can take
             // values EQ, NE, LT, GE LE, GT
             // kind is TypeKind
             val isFloat = kind == FLOAT || kind == DOUBLE
-            if (nextBlock == success || omitJumpBlocks.contains(currentBlock)) {
-              emitBr(cond.negate, labels(failure), isFloat)
-            } else {
-              emitBr(cond, labels(success), isFloat)
-              if (nextBlock != failure && !omitJumpBlocks.contains(currentBlock)) {
-                mcode.Emit(OpCodes.Br, labels(failure))
-              }
-            }
+            val emit = (c: TestOp, l: Label) => emitBr(c, l, isFloat)
+            emitCondBr(block, cond, success, failure, next, emit)
 
           case CZJUMP(success, failure, cond, kind) =>
-            (kind: @unchecked) match {
-              case BOOL | REFERENCE(_) =>
-                if (nextBlock == success || omitJumpBlocks.contains(currentBlock)) {
-                  emitBrBool(cond.negate, labels(failure))
-                } else {
-                  emitBrBool(cond, labels(success))
-                  if (nextBlock != failure && !omitJumpBlocks.contains(currentBlock)) {
-                    mcode.Emit(OpCodes.Br, labels(failure))
-                  }
-                }
-            }
+            emitCondBr(block, cond, success, failure, next, emitBrBool(_, _))
 
           case RETURN(kind) =>
-            mcode.Emit(OpCodes.Ret)
+            if (currentHandlers.isEmpty)
+              mcode.Emit(OpCodes.Ret)
+            else {
+              val (local, label) = returnFromHandler(kind)
+              if (kind != UNIT)
+                mcode.Emit(OpCodes.Stloc, local)
+              mcode.Emit(OpCodes.Leave, label)
+            }
 
           case THROW() =>
             mcode.Emit(OpCodes.Throw)
@@ -1583,12 +1236,11 @@ abstract class GenMSIL extends SubComponent {
             mcode.Emit(OpCodes.Pop)
 
           case DUP(kind) =>
-            // needed to create new instances
-            if (!ignoreNextDup) {
+            // see comment on `var previousWasNEW`
+            if (!previousWasNEW)
               mcode.Emit(OpCodes.Dup)
-            } else {
-              ignoreNextDup = false
-            }
+            else
+              previousWasNEW = false
 
           case MONITOR_ENTER() =>
             mcode.Emit(OpCodes.Call, MMONITOR_ENTER)
@@ -1596,35 +1248,12 @@ abstract class GenMSIL extends SubComponent {
           case MONITOR_EXIT() =>
             mcode.Emit(OpCodes.Call, MMONITOR_EXIT)
 
-          case SCOPE_ENTER(_) | SCOPE_EXIT(_) =>
+          case SCOPE_ENTER(_) | SCOPE_EXIT(_) | LOAD_EXCEPTION() =>
             ()
         }
 
       } // end for (instr <- b) { .. }
-
-      lastBlock = b // this way, saveResult knows lastBlock
-
-      if (bb2exHInstructions.contains(b)){
-        bb2exHInstructions(b).foreach((i) => i match {
-          case BeginExceptionBlock(handler) => ()
-          case BeginCatchBlock(handler, exType) => ()
-          case BeginFinallyBlock(handler) => ()
-          case EndExceptionBlock(handler) =>
-            if (settings.debug.value) log("end ex blk: " + handler)
-            val resType = msilType(handler.resultKind)
-            if (handler.finalizer == null || handler.finalizer == NoFinalizer)
-              saveResult(resType)
-            mcode.EndExceptionBlock()
-            if (resType != MVOID) {
-              val lb: LocalBuilder = excResultLocals.pop
-              mcode.Emit(OpCodes.Ldloc, lb)
-            } else
-              needAdditionalRet = true
-          case _ => abort("unknown case: " + i)
-        })
-      }
-
-    } // end genBlock
+    }
 
     def genPrimitive(primitive: Primitive, pos: Position) {
       primitive match {
@@ -1674,8 +1303,7 @@ abstract class GenMSIL extends SubComponent {
             case DOUBLE => mcode.Emit(OpCodes.Conv_R8)
             case _ =>
               Console.println("Illegal conversion at: " + clasz +
-                              " at: " + pos.source.get + ":" +
-			    pos.line.get)
+                              " at: " + pos.source + ":" + pos.line)
           }
 
         case ArrayLength(_) =>
@@ -1748,10 +1376,85 @@ abstract class GenMSIL extends SubComponent {
           code.Emit(OpCodes.Ldloc, localBuilders(local))
     }
 
-    ////////////////////// labels ///////////////////////
+    ////////////////////// branches ///////////////////////
+
+    /** Returns a Triple (Boolean, Boolean, Option[Label])
+     *   - wether the jump leaves some exception block (try / catch / finally)
+     *   - wether the it leaves a finally handler (finally block, but not it's try / catch)
+     *   - a label where to jump for leaving the finally handler
+     *     . None to leave directly using `endfinally`
+     *     . Some(label) to emit `leave label` (for try / catch inside a finally handler)
+     */
+    def leavesHandler(from: BasicBlock, to: BasicBlock): (Boolean, Boolean, Option[Label]) =
+      if (currentHandlers.isEmpty) (false, false, None)
+      else {
+        val h = currentHandlers.head
+        val leaveHead = { h.covers(from) != h.covers(to) ||
+                          h.blocks.contains(from) != h.blocks.contains(to) }
+        if (leaveHead) {
+          // we leave the innermost exception block.
+          // find out if we also leave som e `finally` handler
+          currentHandlers.find(e => {
+            e.cls == NoSymbol && e.blocks.contains(from) != e.blocks.contains(to)
+          }) match {
+            case Some(finallyHandler) =>
+              if (h == finallyHandler) {
+                // the finally handler is the innermost, so we can emit `endfinally` directly
+                (true, true, None)
+              } else {
+                // we need to `Leave` to the `endfinally` of the next outer finally handler
+                val l = endFinallyLabels.getOrElseUpdate(finallyHandler, mcode.DefineLabel())
+                (true, true, Some(l))
+              }
+            case None =>
+              (true, false, None)
+          }
+        } else (false, false, None)
+      }
+
+    def emitCondBr(block: BasicBlock, cond: TestOp, success: BasicBlock, failure: BasicBlock,
+                   next: BasicBlock, emitBrFun: (TestOp, Label) => Unit) {
+      val (sLeaveHandler, sLeaveFinally, slfTarget) = leavesHandler(block, success)
+      val (fLeaveHandler, fLeaveFinally, flfTarget) = leavesHandler(block, failure)
 
+      if (sLeaveHandler || fLeaveHandler) {
+        val sLabelOpt = if (sLeaveHandler) {
+          val leaveSLabel = mcode.DefineLabel()
+          emitBrFun(cond, leaveSLabel)
+          Some(leaveSLabel)
+        } else {
+          emitBrFun(cond, labels(success))
+          None
+        }
 
-    val labels: HashMap[BasicBlock, Label] = new HashMap() // labels for branches
+        if (fLeaveHandler) {
+          if (fLeaveFinally) {
+            if (flfTarget.isDefined) mcode.Emit(OpCodes.Leave, flfTarget.get)
+            else mcode.Emit(OpCodes.Endfinally)
+          } else
+            mcode.Emit(OpCodes.Leave, labels(failure))
+        } else
+          mcode.Emit(OpCodes.Br, labels(failure))
+
+        sLabelOpt.map(l => {
+          mcode.MarkLabel(l)
+          if (sLeaveFinally) {
+            if (slfTarget.isDefined) mcode.Emit(OpCodes.Leave, slfTarget.get)
+            else mcode.Emit(OpCodes.Endfinally)
+          } else
+            mcode.Emit(OpCodes.Leave, labels(success))
+        })
+      } else {
+        if (next == success) {
+          emitBrFun(cond.negate, labels(failure))
+        } else {
+          emitBrFun(cond, labels(success))
+          if (next != failure) {
+            mcode.Emit(OpCodes.Br, labels(failure))
+          }
+        }
+      }
+    }
 
     def emitBr(condition: TestOp, dest: Label, isFloat: Boolean) {
       condition match {
@@ -1767,7 +1470,7 @@ abstract class GenMSIL extends SubComponent {
     def emitBrBool(cond: TestOp, dest: Label) {
       cond match {
         // EQ -> Brfalse, NE -> Brtrue; this is because we come from
-        // a CZJUMP. If the value on the stack is 0 (e.g. a boolen
+        // a CZJUMP. If the value on the stack is 0 (e.g. a boolean
         // method returned false), and we are in the case EQ, then
         // we need to emit Brfalse (EQ Zero means false). vice versa
         case EQ => mcode.Emit(OpCodes.Brfalse, dest)
@@ -1775,12 +1478,6 @@ abstract class GenMSIL extends SubComponent {
       }
     }
 
-    def makeLabels(bs: List[BasicBlock]) {
-      if (settings.debug.value)
-        log("Making labels for: " + method)
-      for (bb <- bs) labels(bb) = mcode.DefineLabel()
-    }
-
     ////////////////////// local vars ///////////////////////
 
     /**
@@ -1800,7 +1497,7 @@ abstract class GenMSIL extends SubComponent {
         idx += 1 // sizeOf(l.kind)
       }
 
-      val locvars = m.locals -- params
+      val locvars = m.locals filterNot (params contains)
       idx = 0
 
       for (l <- locvars) {
@@ -1836,9 +1533,10 @@ abstract class GenMSIL extends SubComponent {
       else if (sym == definitions.NullClass)
         return "scala.runtime.Null$"
 
-      (if (sym.isClass || (sym.isModule && !sym.isMethod))
-        sym.fullNameString
-       else
+      (if (sym.isClass || (sym.isModule && !sym.isMethod)) {
+        if (sym.isNestedClass) sym.simpleName
+        else sym.fullName
+       } else
          sym.simpleName.toString().trim()) + suffix
     }
 
@@ -1857,10 +1555,10 @@ abstract class GenMSIL extends SubComponent {
       mf = mf | (if (sym.isTrait && !sym.isImplClass) TypeAttributes.Interface else TypeAttributes.Class)
       mf = mf | (if (sym isFinal) TypeAttributes.Sealed else 0)
 
-      sym.attributes foreach { a => a match {
+      sym.annotations foreach { a => a match {
         case AnnotationInfo(SerializableAttr, _, _) =>
-          // TODO: add the Serializable TypeAttribute also if the attribute
-          // System.SerializableAttribute is present (.net attribute, not scala)
+          // TODO: add the Serializable TypeAttribute also if the annotation
+          // System.SerializableAttribute is present (.net annotation, not scala)
           //  Best way to do it: compare with
           //  definitions.getClass("System.SerializableAttribute").tpe
           //  when frontend available
@@ -1882,9 +1580,9 @@ abstract class GenMSIL extends SubComponent {
           mf = mf | FieldAttributes.Static
         else {
           mf = mf | MethodAttributes.Virtual
-          if (sym.isFinal && !types(sym.owner.asInstanceOf[clrTypes.global.Symbol]).IsInterface)
+          if (sym.isFinal && !getType(sym.owner).IsInterface)
             mf = mf | MethodAttributes.Final
-          if (sym.hasFlag(Flags.DEFERRED) || types(sym.owner.asInstanceOf[clrTypes.global.Symbol]).IsInterface)
+          if (sym.hasFlag(Flags.DEFERRED) || getType(sym.owner).IsInterface)
             mf = mf | MethodAttributes.Abstract
         }
       }
@@ -1904,10 +1602,10 @@ abstract class GenMSIL extends SubComponent {
       if (sym.isStaticMember)
         mf = mf | FieldAttributes.Static
 
-      // TRANSIENT: "not nerialized", VOLATILE: doesn't exist on .net
-      // TODO: add this attribute also if the class has the custom attribute
+      // TRANSIENT: "not serialized", VOLATILE: doesn't exist on .net
+      // TODO: add this annotation also if the class has the custom attribute
       // System.NotSerializedAttribute
-      sym.attributes.foreach( a => a match {
+      sym.annotations.foreach( a => a match {
         case AnnotationInfo(TransientAtt, _, _) =>
           mf = mf | FieldAttributes.NotSerialized
         case _ => ()
@@ -1934,7 +1632,7 @@ abstract class GenMSIL extends SubComponent {
           if (sym.tpe.paramTypes.length == 1) {
             toTypeKind(sym.tpe.paramTypes(0)) match {
               case ARRAY(elem) =>
-                if (elem.toType.typeSymbol == definitions.StringClass){
+                if (elem.toType.typeSymbol == definitions.StringClass) {
                   return true
                 }
               case _ => ()
@@ -1968,7 +1666,14 @@ abstract class GenMSIL extends SubComponent {
       case FLOAT          => MFLOAT
       case DOUBLE         => MDOUBLE
       case REFERENCE(cls) => getType(cls)
-      case ARRAY(elem)    => clrTypes.mkArrayType(msilType(elem))
+      case ARRAY(elem)    =>
+        msilType(elem) match {
+          // For type builders, cannot call "clrTypes.mkArrayType" because this looks up
+          // the type "tp" in the assembly (not in the HashMap "types" of the backend).
+          // This can fail for nested types because the biulders are not complete yet.
+          case tb: TypeBuilder => tb.MakeArrayType()
+          case tp: MsilType => clrTypes.mkArrayType(tp)
+        }
     }
 
     private def msilType(tpe: Type): MsilType = msilType(toTypeKind(tpe))
@@ -1977,40 +1682,60 @@ abstract class GenMSIL extends SubComponent {
       sym.tpe.paramTypes.map(msilType).toArray
     }
 
-    def getType(sym: Symbol): MsilType = types.get(sym.asInstanceOf[clrTypes.global.Symbol]) match {
-      case Some(typ) => typ
+    def getType(sym: Symbol) = getTypeOpt(sym).getOrElse(abort(showsym(sym)))
+
+    /**
+     * Get an MSIL type form a symbol. First look in the clrTypes.types map, then
+     * lookup the name using clrTypes.getType
+     */
+    def getTypeOpt(sym: Symbol): Option[MsilType] = types.get(sym) match {
+      case typ @ Some(_) => typ
       case None =>
-        val name = if (sym.isModuleClass && !sym.isTrait) sym.fullNameString + "$"
-                   else sym.fullNameString
+        def typeString(sym: Symbol): String = {
+          val s = if (sym.isNestedClass) typeString(sym.owner) +"+"+ sym.simpleName
+                  else sym.fullName
+          if (sym.isModuleClass && !sym.isTrait) s + "$" else s
+        }
+        val name = typeString(sym)
         val typ = clrTypes.getType(name)
         if (typ == null)
-          throw new Error(showsym(sym) + " with name " + name)
+          None
         else {
-          clrTypes.types(sym.asInstanceOf[clrTypes.global.Symbol]) = typ
-          typ
+          types(sym) = typ
+          Some(typ)
         }
     }
 
     def mapType(sym: Symbol, mType: MsilType) {
       assert(mType != null, showsym(sym))
-      types(sym.asInstanceOf[clrTypes.global.Symbol]) = mType
+      types(sym) = mType
     }
 
     def createTypeBuilder(iclass: IClass) {
+      /**
+       * First look in the clrTypes.types map, then see if it's a class we're
+       * currently compiling by looking at the icodes.classes map, then finally
+       * lookup the name using clrTypes.getType (by calling getType).
+       */
       def msilTypeFromSym(sym: Symbol): MsilType = {
-	types.get(sym.asInstanceOf[clrTypes.global.Symbol]) match {
-          case Some(mtype) => mtype
-          case None => createTypeBuilder(classes(sym)); types(sym.asInstanceOf[clrTypes.global.Symbol])
+        types.get(sym).getOrElse {
+          classes.get(sym) match {
+            case Some(iclass) =>
+              createTypeBuilder(iclass)
+              types (sym)
+            case None =>
+              getType(sym)
+          }
         }
       }
 
       val sym = iclass.symbol
-      if (types contains sym.asInstanceOf[clrTypes.global.Symbol]) return
+      if (types contains sym) return
 
       def isInterface(s: Symbol) = s.isTrait && !s.isImplClass
       val parents: List[Type] =
         if (sym.info.parents.isEmpty) List(definitions.ObjectClass.tpe)
-        else sym.info.parents.removeDuplicates
+        else sym.info.parents.distinct
 
       val superType = if (isInterface(sym)) null else msilTypeFromSym(parents.head.typeSymbol)
       if (settings.debug.value)
@@ -2019,9 +1744,9 @@ abstract class GenMSIL extends SubComponent {
       val interfaces: Array[MsilType] =
 	parents.tail.map(p => msilTypeFromSym(p.typeSymbol)).toArray
       if (parents.length > 1) {
-        if (settings.debug.value){
+        if (settings.debug.value) {
           log("interfaces:")
-          for (i <- 0.until(interfaces.length)){
+          for (i <- 0.until(interfaces.length)) {
             log("  type: " + parents(i + 1).typeSymbol + ", msil type: " + interfaces(i))
           }
         }
@@ -2056,12 +1781,12 @@ abstract class GenMSIL extends SubComponent {
       for (ifield <- iclass.fields) {
         val sym = ifield.symbol
         if (settings.debug.value)
-          log("Adding field: " + sym.fullNameString)
+          log("Adding field: " + sym.fullName)
 
         var attributes = msilFieldFlags(sym)
         val fBuilder = mtype.DefineField(msilName(sym), msilType(sym.tpe), attributes)
-        fields(sym.asInstanceOf[clrTypes.global.Symbol]) = fBuilder
-        addAttributes(fBuilder, sym.attributes)
+        fields(sym) = fBuilder
+        addAttributes(fBuilder, sym.annotations)
       }
 
       if (iclass.symbol != definitions.ArrayClass)
@@ -2069,7 +1794,7 @@ abstract class GenMSIL extends SubComponent {
         val sym = m.symbol
         if (settings.debug.value)
           log("Creating MethodBuilder for " + Flags.flagsToString(sym.flags) + " " +
-              sym.owner.fullNameString + "::" + sym.name)
+              sym.owner.fullName + "::" + sym.name)
 
         val ownerType = getType(sym.enclClass).asInstanceOf[TypeBuilder]
         assert(mtype == ownerType, "mtype = " + mtype + "; ownerType = " + ownerType)
@@ -2083,17 +1808,17 @@ abstract class GenMSIL extends SubComponent {
             constr.DefineParameter(i, ParameterAttributes.None, msilName(m.params(i).sym))
           }
           mapConstructor(sym, constr)
-          addAttributes(constr, sym.attributes)
+          addAttributes(constr, sym.annotations)
         } else {
           var resType = msilType(m.returnType)
           val method =
             ownerType.DefineMethod(getMethodName(sym), attr, resType, paramTypes)
-          for (i <- 0.until(paramTypes.length)){
+          for (i <- 0.until(paramTypes.length)) {
             method.DefineParameter(i, ParameterAttributes.None, msilName(m.params(i).sym))
           }
-          if (!methods.contains(sym.asInstanceOf[clrTypes.global.Symbol]))
+          if (!methods.contains(sym))
             mapMethod(sym, method)
-          addAttributes(method, sym.attributes)
+          addAttributes(method, sym.annotations)
           if (settings.debug.value)
             log("\t created MethodBuilder " + method)
         }
@@ -2122,7 +1847,7 @@ abstract class GenMSIL extends SubComponent {
     }
 
     private def isCloneable(sym: Symbol): Boolean = {
-      !sym.attributes.forall( a => a match {
+      !sym.annotations.forall( a => a match {
         case AnnotationInfo(CloneableAttr, _, _) => false
         case _ => true
       })
@@ -2137,7 +1862,7 @@ abstract class GenMSIL extends SubComponent {
                            (FieldAttributes.Public |
                             //FieldAttributes.InitOnly |
                             FieldAttributes.Static).toShort)
-      fields(sym.asInstanceOf[clrTypes.global.Symbol]) = fb
+      fields(sym) = fb
     }
 
 
@@ -2152,20 +1877,25 @@ abstract class GenMSIL extends SubComponent {
       // TODO: get module field for modules not defined in the
       // source currently compiling (e.g. Console)
 
-      fields get moduleClassSym.asInstanceOf[clrTypes.global.Symbol] match {
+      fields get moduleClassSym match {
         case Some(sym) => sym
         case None =>
           //val mclass = types(moduleClassSym)
-          val mClass = clrTypes.getType(moduleClassSym.fullNameString + "$")
+          val mClass = clrTypes.getType(moduleClassSym.fullName + "$")
           val mfield = mClass.GetField("MODULE$")
           assert(mfield ne null, "module not found " + showsym(moduleClassSym))
-          fields(moduleClassSym.asInstanceOf[clrTypes.global.Symbol]) = mfield
+          fields(moduleClassSym) = mfield
           mfield
       }
 
       //fields(moduleClassSym)
     }
 
+    /** Adds a static initializer which creates an instance of the module
+     *  class (calls the primary constructor). A special primary constructor
+     *  will be generated (notInitializedModules) which stores the new instance
+     *  in the MODULE$ field right after the super call.
+     */
     private def addStaticInit(sym: Symbol) {
       val tBuilder = getType(sym).asInstanceOf[TypeBuilder]
 
@@ -2176,7 +1906,7 @@ abstract class GenMSIL extends SubComponent {
 
       val sicode = staticInit.GetILGenerator()
 
-      val instanceConstructor = constructors(sym.primaryConstructor.asInstanceOf[clrTypes.global.Symbol])
+      val instanceConstructor = constructors(sym.primaryConstructor)
 
       // there are no constructor parameters. assuming the constructor takes no parameter
       // is fine: we call (in the static constructor) the constructor of the module class,
@@ -2199,7 +1929,6 @@ abstract class GenMSIL extends SubComponent {
                                                  TypeAttributes.Class |
                                                  TypeAttributes.Public |
                                                  TypeAttributes.Sealed,
-                //FIXME: an object may have a super-type (a class, not an object) -> not in mirror class?
                                                  MOBJECT,
                                                  MsilType.EmptyTypes)
 
@@ -2218,8 +1947,8 @@ abstract class GenMSIL extends SubComponent {
 
           // CHECK: verify if getMethodName is better than msilName
           val mirrorMethod = mirrorTypeBuilder.DefineMethod(getMethodName(m),
-                                                            MethodAttributes.Public |
-                                                            MethodAttributes.Static,
+                                                            (MethodAttributes.Public |
+                                                            MethodAttributes.Static).toShort,
                                                             msilType(m.tpe.resultType),
                                                             paramTypes)
 
@@ -2262,21 +1991,21 @@ abstract class GenMSIL extends SubComponent {
       val mFunctionType: MsilType = msilType(functionType)
       val anonfunField: FieldBuilder = delegateCallers.DefineField(
         "$anonfunField$$" + nbDelegateCallers, mFunctionType,
-        FieldAttributes.InitOnly | FieldAttributes.Public | FieldAttributes.Static)
+        (FieldAttributes.InitOnly | FieldAttributes.Public | FieldAttributes.Static).toShort)
       mcode.Emit(OpCodes.Stsfld, anonfunField)
 
 
       // create the static caller method and the delegate object
-      val (paramTypes, returnType) = delegateType.member(nme.apply).tpe match {
+      val (params, returnType) = delegateType.member(nme.apply).tpe match {
         case MethodType(delParams, delReturn) => (delParams, delReturn)
         case _ => abort("not a delegate type: "  + delegateType)
       }
       val caller: MethodBuilder = delegateCallers.DefineMethod(
         "$delegateCaller$$" + nbDelegateCallers,
-        MethodAttributes.Final | MethodAttributes.Public | MethodAttributes.Static,
-        msilType(returnType), paramTypes.map(msilType).toArray)
-      for (i <- 0 until paramTypes.length)
-        caller.DefineParameter(i, ParameterAttributes.None, "arg" + i)
+        (MethodAttributes.Final | MethodAttributes.Public | MethodAttributes.Static).toShort,
+        msilType(returnType), (params map (_.tpe)).map(msilType).toArray)
+      for (i <- 0 until params.length)
+        caller.DefineParameter(i, ParameterAttributes.None, "arg" + i) // FIXME: use name of parameter symbol 
       val delegCtor = msilType(delegateType).GetConstructor(Array(MOBJECT, INT_PTR))
       mcode.Emit(OpCodes.Ldnull)
       mcode.Emit(OpCodes.Ldftn, caller)
@@ -2287,9 +2016,9 @@ abstract class GenMSIL extends SubComponent {
       val functionApply: MethodInfo = getMethod(functionType.member(nme.apply))
       val dcode: ILGenerator = caller.GetILGenerator()
       dcode.Emit(OpCodes.Ldsfld, anonfunField)
-      for (i <- 0 until paramTypes.length) {
+      for (i <- 0 until params.length) {
         loadArg(dcode)(i)
-        emitBox(dcode, toTypeKind(paramTypes(i)))
+        emitBox(dcode, toTypeKind(params(i).tpe))
       }
       dcode.Emit(OpCodes.Callvirt, functionApply)
       emitUnbox(dcode, toTypeKind(returnType))
@@ -2328,7 +2057,7 @@ abstract class GenMSIL extends SubComponent {
     // #####################################################################
     // get and create methods / constructors
  
-    def getConstructor(sym: Symbol): ConstructorInfo = constructors.get(sym.asInstanceOf[clrTypes.global.Symbol]) match {
+    def getConstructor(sym: Symbol): ConstructorInfo = constructors.get(sym) match {
       case Some(constr) => constr
       case None =>
         val mClass = getType(sym.owner)
@@ -2336,7 +2065,7 @@ abstract class GenMSIL extends SubComponent {
         if (constr eq null) {
           System.out.println("Cannot find constructor " + sym.owner + "::" + sym.name)
           System.out.println("scope = " + sym.owner.tpe.decls)
-          throw new Error(sym.fullNameString)
+          abort(sym.fullName)
         }
         else {
           mapConstructor(sym, constr)
@@ -2345,7 +2074,7 @@ abstract class GenMSIL extends SubComponent {
     }
 
     def mapConstructor(sym: Symbol, cInfo: ConstructorInfo) = {
-      constructors(sym.asInstanceOf[clrTypes.global.Symbol]) = cInfo
+      constructors(sym) = cInfo
     }
 
     private def getMethod(sym: Symbol): MethodInfo = {
@@ -2360,7 +2089,7 @@ abstract class GenMSIL extends SubComponent {
 //       case SRToShort => toShort
 //       case _ =>
 
-        methods.get(sym.asInstanceOf[clrTypes.global.Symbol]) match {
+        methods.get(sym) match {
         case Some(method) => method
         case None =>
           val mClass = getType(sym.owner)
@@ -2370,7 +2099,7 @@ abstract class GenMSIL extends SubComponent {
             if (method eq null) {
               System.out.println("Cannot find method " + sym.owner + "::" + msilName(sym))
               System.out.println("scope = " + sym.owner.tpe.decls)
-              throw new Error(sym.fullNameString)
+              abort(sym.fullName)
             }
             else {
               mapMethod(sym, method)
@@ -2391,7 +2120,7 @@ abstract class GenMSIL extends SubComponent {
      */
     private def mapMethod(sym: Symbol, mInfo: MethodInfo) {
       assert (mInfo != null, mInfo)
-      methods(sym.asInstanceOf[clrTypes.global.Symbol]) = mInfo
+      methods(sym) = mInfo
     }
 
     /*
@@ -2421,7 +2150,7 @@ abstract class GenMSIL extends SubComponent {
       }
 
     /*
-     * add maping for member with name and paramTypes to member
+     * add mapping for member with name and paramTypes to member
      * newName of newClass (same parameters)
      */
     private def mapMethod(
@@ -2444,7 +2173,7 @@ abstract class GenMSIL extends SubComponent {
             alternatives.foreach(s => mapMethod(s, newClass, newName, msilParamTypes(s)))
 
           // paramTypes: List[Type], resType: Type
-          case MethodType(paramTypes, resType) =>
+          case MethodType(params, resType) =>
             mapMethod(memberSym, newClass, newName, msilParamTypes(memberSym))
 
           case _ =>
@@ -2463,12 +2192,12 @@ abstract class GenMSIL extends SubComponent {
           alternatives.find(s => {
             var i: Int = 0
             var typesOK: Boolean = true
-            if (paramTypes.length == s.tpe.paramTypes.length){
-              while(i < paramTypes.length){
+            if (paramTypes.length == s.tpe.paramTypes.length) {
+              while(i < paramTypes.length) {
                 if (paramTypes(i) != s.tpe.paramTypes(i))
                   typesOK = false
                 i += 1
-              } 
+              }
             } else {
               typesOK = false
             }
diff --git a/src/compiler/scala/tools/nsc/backend/opt/ClosureElimination.scala b/src/compiler/scala/tools/nsc/backend/opt/ClosureElimination.scala
index b7f636a..e980205 100644
--- a/src/compiler/scala/tools/nsc/backend/opt/ClosureElimination.scala
+++ b/src/compiler/scala/tools/nsc/backend/opt/ClosureElimination.scala
@@ -1,14 +1,14 @@
  /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Iulian Dragos
  */
 
-// $Id: ClosureElimination.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.tools.nsc.backend.opt;
+package scala.tools.nsc
+package backend.opt;
 
 import scala.collection.mutable.{Map, HashMap};
-import scala.tools.nsc.backend.icode.analysis.LubError;
+import scala.tools.nsc.backend.icode.analysis.LubException;
 import scala.tools.nsc.symtab._;
 
 /**
@@ -36,7 +36,7 @@ abstract class ClosureElimination extends SubComponent {
   }
 
   /** 
-   * Remove references to the environemnt through fields of a closure object. 
+   * Remove references to the environment through fields of a closure object. 
    * This has to be run after an 'apply' method has been inlined, but it still 
    * references the closure object.
    *
@@ -64,7 +64,10 @@ abstract class ClosureElimination extends SubComponent {
         case (LOAD_LOCAL(x), STORE_LOCAL(y)) =>
         	if (x eq y) Some(Nil) else None
 
-        case (LOAD_LOCAL(_), DROP(_)) =>
+//        case (STORE_LOCAL(x), LOAD_LOCAL(y)) if (x == y) =>
+//          Some(List(DUP(x.kind), STORE_LOCAL(x)))
+          
+        case (LOAD_LOCAL(_), DROP(_)) | (DUP(_), DROP(_)) =>
           Some(Nil)
 
         case (BOX(t1), UNBOX(t2)) if (t1 == t2) =>
@@ -101,16 +104,12 @@ abstract class ClosureElimination extends SubComponent {
         var info = cpp.in(bb)
         log("Cpp info at entry to block " + bb + ": " + info)
 
-        for (i <- bb.toList) {
+        for (i <- bb) {
           i match {
             case LOAD_LOCAL(l) if (info.bindings.isDefinedAt(LocalVar(l))) =>
               val t = info.getBinding(l)
               t match {
-                case Deref(LocalVar(v)) => 
-                  bb.replaceInstruction(i, valueToInstruction(t));
-                  log("replaced " + i + " with " + t)
-
-                case Deref(This) =>
+                case Deref(LocalVar(_)) | Deref(This) | Const(_) =>
                   bb.replaceInstruction(i, valueToInstruction(t));
                   log("replaced " + i + " with " + t)
 
@@ -120,31 +119,36 @@ abstract class ClosureElimination extends SubComponent {
 
               }
 
-            case LOAD_FIELD(f, false) if accessible(f, m.symbol) =>
+            case LOAD_FIELD(f, false) /* if accessible(f, m.symbol) */ =>
+              def replaceFieldAccess(r: Record) {
+                val Record(cls, bindings) = r
+                info.getFieldNonRecordValue(r, f) match {
+                	case Some(v) =>
+                		bb.replaceInstruction(i, 
+                				DROP(REFERENCE(cls)) :: valueToInstruction(v) :: Nil);
+                		log("Replaced " + i + " with " + info.getFieldNonRecordValue(r, f));
+                	case None => ();
+                }
+              }
+              
               info.stack(0) match {
-                case r @ Record(cls, bindings) if bindings.isDefinedAt(f) =>
-                  info.getFieldValue(r, f) match {
-                    case Some(v) =>
-                      bb.replaceInstruction(i, 
-                          DROP(REFERENCE(cls)) :: valueToInstruction(v) :: Nil);
-                      log("Replaced " + i + " with " + info.getBinding(r, f));
-                    case None => ();
-                  }
+                case r @ Record(_, bindings) if bindings.isDefinedAt(f) =>
+                  replaceFieldAccess(r)
 
                 case Deref(LocalVar(l)) =>
                   info.getBinding(l) match {
-                    case r @ Record(cls, bindings) if bindings.isDefinedAt(f) =>
-                      info.getFieldValue(r, f) match {
-                        case Some(v) =>
-                          bb.replaceInstruction(i, 
-                              DROP(REFERENCE(cls)) :: valueToInstruction(v) :: Nil);
-                          log("Replaced " + i + " with " + info.getBinding(r, f));
-                        case None => ();
-                      }
-                    case _ => ();
+                    case r @ Record(_, bindings) if bindings.isDefinedAt(f) =>
+                      replaceFieldAccess(r)
+                    case _ => 
+                  }
+                case Deref(Field(r1, f1)) =>
+                  info.getFieldValue(r1, f1) match {
+                    case Some(r @ Record(_, bindings)) if bindings.isDefinedAt(f) =>
+                      replaceFieldAccess(r)
+                    case _ => 
                   }
 
-                case _ => ();
+                case _ => 
               }
               
             case UNBOX(_) =>
@@ -172,7 +176,7 @@ abstract class ClosureElimination extends SubComponent {
         }
       }
     }} catch {
-      case e: LubError => 
+      case e: LubException => 
         Console.println("In method: " + m)
         Console.println(e)
         e.printStackTrace
@@ -186,14 +190,13 @@ abstract class ClosureElimination extends SubComponent {
         CONSTANT(k)
       case Deref(This) =>
         THIS(definitions.ObjectClass)
+      case Boxed(LocalVar(v)) =>
+        LOAD_LOCAL(v)
     }
     
     /** is field 'f' accessible from method 'm'? */
     def accessible(f: Symbol, m: Symbol): Boolean = 
-      f.isPublic || (f.hasFlag(Flags.PROTECTED) && (enclPackage(f) == enclPackage(m)))
-
-    private def enclPackage(sym: Symbol): Symbol = 
-      if ((sym == NoSymbol) || sym.isPackageClass) sym else enclPackage(sym.owner)
+      f.isPublic || (f.hasFlag(Flags.PROTECTED) && (f.enclosingPackageClass == m.enclosingPackageClass))
 
   } /* class ClosureElim */
 
diff --git a/src/compiler/scala/tools/nsc/backend/opt/DeadCodeElimination.scala b/src/compiler/scala/tools/nsc/backend/opt/DeadCodeElimination.scala
index 88613b3..5a41e2e 100644
--- a/src/compiler/scala/tools/nsc/backend/opt/DeadCodeElimination.scala
+++ b/src/compiler/scala/tools/nsc/backend/opt/DeadCodeElimination.scala
@@ -1,15 +1,14 @@
 /* NSC -- new scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Iulian Dragos
  */
 
-// $Id: DeadCodeElimination.scala 16881 2009-01-09 16:28:11Z cunei $
 
-package scala.tools.nsc.backend.opt
+package scala.tools.nsc
+package backend.opt
 
 import scala.collection._
 import scala.collection.immutable.{Map, HashMap, Set, HashSet}
-import scala.tools.nsc.backend.icode.analysis.LubError
 import scala.tools.nsc.symtab._
 
 /**
@@ -57,7 +56,7 @@ abstract class DeadCodeElimination extends SubComponent {
     var defs: Map[(BasicBlock, Int), Set[rdef.lattice.Definition]] = HashMap.empty
     
     /** Useful instructions which have not been scanned yet. */
-    val worklist: mutable.Set[(BasicBlock, Int)] = new jcl.LinkedHashSet
+    val worklist: mutable.Set[(BasicBlock, Int)] = new mutable.LinkedHashSet
     
     /** what instructions have been marked as useful? */
     val useful: mutable.Map[BasicBlock, mutable.BitSet] = new mutable.HashMap
@@ -81,9 +80,9 @@ abstract class DeadCodeElimination extends SubComponent {
         collectRDef(m)
         mark
         sweep(m)
-        accessedLocals = accessedLocals.removeDuplicates
-        if ((m.locals -- accessedLocals).length > 0) {
-          log("Removed dead locals: " + (m.locals -- accessedLocals))
+        accessedLocals = accessedLocals.distinct
+        if (m.locals diff accessedLocals nonEmpty) {
+          log("Removed dead locals: " + (m.locals diff accessedLocals))
           m.locals = accessedLocals.reverse
         }
       }
@@ -130,12 +129,12 @@ abstract class DeadCodeElimination extends SubComponent {
     }
 
     /** Mark useful instructions. Instructions in the worklist are each inspected and their
-     *  dependecies are marked useful too, and added to the worklist.
+     *  dependencies are marked useful too, and added to the worklist.
      */
     def mark {
 //      log("Starting with worklist: " + worklist)
       while (!worklist.isEmpty) {
-        val (bb, idx) = worklist.elements.next
+        val (bb, idx) = worklist.iterator.next
         worklist -= ((bb, idx))
         if (settings.debug.value)
           log("Marking instr: \tBB_" + bb + ": " + idx + " " + bb(idx))
@@ -217,7 +216,7 @@ abstract class DeadCodeElimination extends SubComponent {
     private def computeCompensations(m: IMethod): mutable.Map[(BasicBlock, Int), List[Instruction]] = {
       val compensations: mutable.Map[(BasicBlock, Int), List[Instruction]] = new mutable.HashMap
       
-      for (bb <- m.code.blocks.toList) {
+      for (bb <- m.code.blocks) {
         assert(bb.closed, "Open block in computeCompensations")
         for ((i, idx) <- bb.toList.zipWithIndex) {
           if (!useful(bb)(idx)) {
@@ -225,8 +224,20 @@ abstract class DeadCodeElimination extends SubComponent {
               log("Finding definitions of: " + i + "\n\t" + consumedType + " at depth: " + depth)
               val defs = rdef.findDefs(bb, idx, 1, depth)
               for (d <- defs) {
-                if (!compensations.isDefinedAt(d))
-                  compensations(d) = List(DROP(consumedType))
+                val (bb, idx) = d
+                bb(idx) match {
+                  case DUP(_) if idx > 0 =>
+                    bb(idx - 1) match {
+                      case nw @ NEW(_) =>
+                        val init = findInstruction(bb, nw.init)
+                        log("Moving DROP to after <init> call: " + nw.init)
+                        compensations(init) = List(DROP(consumedType))
+                      case _ =>
+                        compensations(d) = List(DROP(consumedType))
+                    }
+                  case _ =>
+                    compensations(d) = List(DROP(consumedType))
+                }
               }
             }
           }
diff --git a/src/compiler/scala/tools/nsc/backend/opt/Inliners.scala b/src/compiler/scala/tools/nsc/backend/opt/Inliners.scala
index c0d0980..254ae4f 100644
--- a/src/compiler/scala/tools/nsc/backend/opt/Inliners.scala
+++ b/src/compiler/scala/tools/nsc/backend/opt/Inliners.scala
@@ -1,12 +1,14 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Iulian Dragos
  */
 
-// $Id: Inliners.scala 16881 2009-01-09 16:28:11Z cunei $
 
-package scala.tools.nsc.backend.opt
+package scala.tools.nsc
+package backend.opt
 
+
+import scala.util.control.Breaks._
 import scala.collection.mutable.{Map, HashMap, Set, HashSet}
 import scala.tools.nsc.symtab._
 
@@ -19,6 +21,18 @@ abstract class Inliners extends SubComponent {
   import icodes.opcodes._
 
   val phaseName = "inliner"
+  
+  /** Debug - for timing the inliner. */
+  private def timed[T](s: String, body: => T): T = {
+    val t1 = System.currentTimeMillis()
+    val res = body
+    val t2 = System.currentTimeMillis()
+    val ms = (t2 - t1).toInt
+    if (ms >= 2000)
+      println("%s: %d milliseconds".format(s, ms))
+    
+    res
+  }
 
   /** The maximum size in basic blocks of methods considered for inlining. */
   final val MAX_INLINE_SIZE = 16
@@ -44,10 +58,10 @@ abstract class Inliners extends SubComponent {
   class Inliner {
 
     val fresh = new HashMap[String, Int]
-    
+
     /* fresh name counter */
     var count = 0
-    
+
     def freshName(s: String) = fresh.get(s) match {
       case Some(count) =>
         fresh(s) = count + 1
@@ -67,12 +81,8 @@ abstract class Inliners extends SubComponent {
                block:  BasicBlock,
                instr:  Instruction,
                callee: IMethod) {
-       log("Inlining " + callee + " in " + caller + " at pos: " + 
-           (try {
-             instr.pos.offset.get             
-           } catch {
-             case _ => "<nopos>"
-           }));
+       def posToStr(pos: util.Position) = if (pos.isDefined) pos.point.toString else "<nopos>"
+       log("Inlining " + callee + " in " + caller + " at pos: " + posToStr(instr.pos))
 
        val targetPos = instr.pos
        val a = new analysis.MethodTFA(callee)
@@ -83,7 +93,7 @@ abstract class Inliners extends SubComponent {
        /* Map 'original' blocks to the ones inlined in the caller. */
        val inlinedBlock: Map[BasicBlock, BasicBlock] = new HashMap
        
-       val varsInScope: Set[Local] = new HashSet[Local] ++ block.varsInScope.elements
+       val varsInScope: Set[Local] = HashSet() ++= block.varsInScope
 
        val instrBefore = block.toList.takeWhile {
          case i @ SCOPE_ENTER(l) => varsInScope += l
@@ -93,7 +103,7 @@ abstract class Inliners extends SubComponent {
        }
        val instrAfter  = block.toList.drop(instrBefore.length + 1);
 
-       assert(!instrAfter.isEmpty, "CALL_METHOD cannot be the last instrcution in block!");
+       assert(!instrAfter.isEmpty, "CALL_METHOD cannot be the last instruction in block!");
 
        // store the '$this' into the special local
        val inlinedThis = new Local(caller.symbol.newVariable(instr.pos, freshName("$inlThis")), REFERENCE(definitions.ObjectClass), false);
@@ -141,7 +151,7 @@ abstract class Inliners extends SubComponent {
        val afterBlock = newBlock;
        
        /** Map from nw.init instructions to their matching NEW call */
-       val pending: collection.jcl.Map[Instruction, NEW] = new collection.jcl.HashMap
+       val pending: collection.mutable.Map[Instruction, NEW] = new collection.mutable.HashMap
        
        /** Map an instruction from the callee to one suitable for the caller. */
        def map(i: Instruction): Instruction = {
@@ -196,7 +206,7 @@ abstract class Inliners extends SubComponent {
            case CALL_METHOD(meth, Static(true)) if (meth.isClassConstructor) =>
              CALL_METHOD(meth, Static(true))
              
-           case _ => i
+           case _ => i.clone
          }
          // check any pending NEW's
          if (pending isDefinedAt i) {
@@ -267,38 +277,51 @@ abstract class Inliners extends SubComponent {
        assert(pending.isEmpty, "Pending NEW elements: " + pending)
      }
 
+    /** The current iclass */
+    private var currentIClazz: IClass = _
+
     def analyzeClass(cls: IClass): Unit = if (settings.inline.value) {
       if (settings.debug.value)
       	log("Analyzing " + cls);
-      cls.methods.foreach { m => if (!m.symbol.isConstructor) analyzeMethod(m)
-     }}
-
+      this.currentIClazz = cls
+      cls.methods filterNot (_.symbol.isConstructor) foreach analyzeMethod
+    }
 
     val tfa = new analysis.MethodTFA();
-    tfa.stat = settings.statistics.value
+    tfa.stat = settings.Ystatistics.value
+
+    // how many times have we already inlined this method here?
+    private val inlinedMethods: Map[Symbol, Int] = new HashMap[Symbol, Int] {
+    	override def default(k: Symbol) = 0       
+    }
 
-    def analyzeMethod(m: IMethod): Unit = try {
+    def analyzeMethod(m: IMethod): Unit = {
       var retry = false
       var count = 0
       fresh.clear
-      // how many times have we already inlined this method here?
-      val inlinedMethods: Map[Symbol, Int] = new HashMap[Symbol, Int] {
-        override def default(k: Symbol) = 0       
-      }
-
+      inlinedMethods.clear
+      
       do {
         retry = false;
-        if (m.code ne null) {
-          if (settings.debug.value)
-            log("Analyzing " + m + " count " + count);
+        if (m.symbol.hasAnnotation(ScalaInlineAttr)) {
+          log("Not inlining into " + m.symbol.originalName.decode + " because it is marked @inline.")
+        }
+        else if (m.code ne null) {
+          log("Analyzing " + m + " count " + count + " with " + m.code.blocks.length + " blocks");
           tfa.init(m)
           tfa.run
           for (bb <- linearizer.linearize(m)) {
             var info = tfa.in(bb);
-            for (i <- bb.toList) {
+            for (i <- bb) {
               if (!retry) {
                 i match {
-                  case CALL_METHOD(msym, Dynamic) => 
+                  case CALL_METHOD(msym, Dynamic) =>
+                    def warnNoInline(reason: String) = {
+                      if (msym.hasAnnotation(ScalaInlineAttr) && !m.symbol.hasFlag(Flags.BRIDGE))
+                        currentIClazz.cunit.warning(i.pos,
+                          "Could not inline required method %s because %s.".format(msym.originalName.decode, reason))
+                    }
+
                     val receiver = info.stack.types.drop(msym.info.paramTypes.length).head match {
                       case REFERENCE(s) => s;
                       case _ => NoSymbol;
@@ -307,43 +330,41 @@ abstract class Inliners extends SubComponent {
                     if (receiver != msym.owner && receiver != NoSymbol) { 
                       if (settings.debug.value)
                         log("" + i + " has actual receiver: " + receiver);
+                      if (!concreteMethod.isEffectivelyFinal && receiver.isFinal) {
+                        concreteMethod = lookupImpl(concreteMethod, receiver)
+                        if (settings.debug.value)
+                          log("\tlooked up method: " + concreteMethod.fullName)
+                      }
                     }
-                    if (!concreteMethod.isFinal && receiver.isFinal) {
-                      concreteMethod = lookupImpl(concreteMethod, receiver)
-                      if (settings.debug.value)
-                        log("\tlooked up method: " + concreteMethod.fullNameString)
-                    } 
 
-                    if (receiver == definitions.PredefModule.moduleClass) {
-                      log("loading predef")
+                    if (shouldLoad(receiver, concreteMethod)) {
                       icodes.icode(receiver, true)
                     }
                     if (settings.debug.value)
                       log("Treating " + i 
                           + "\n\treceiver: " + receiver
                           + "\n\ticodes.available: " + icodes.available(receiver)
-                          + "\n\tconcreteMethod.isFinal: " + concreteMethod.isFinal);
+                          + "\n\tconcreteMethod.isEffectivelyFinal: " + concreteMethod.isFinal);
 
                     if (   icodes.available(receiver) 
                         && (isClosureClass(receiver)
-                            || concreteMethod.isFinal
+                            || concreteMethod.isEffectivelyFinal
                             || receiver.isFinal)) {
                       icodes.icode(receiver).get.lookupMethod(concreteMethod) match {
                         case Some(inc) =>
                           if (inc.symbol != m.symbol
-                              && (inlinedMethods(inc.symbol) < 2)
                               && (inc.code ne null)
                               && shouldInline(m, inc)
                               && isSafeToInline(m, inc, info.stack)) {
                             retry = true;
-                            if (!isClosureClass(receiver)) // only count non-closures
+                            if (!(isClosureClass(receiver) && (concreteMethod.name == nme.apply))) // only count non-closures
                                 count = count + 1;
                             inline(m, bb, i, inc);
                             inlinedMethods(inc.symbol) = inlinedMethods(inc.symbol) + 1
 
                             /* Remove this method from the cache, as the calls-private relation
                                might have changed after the inlining. */
-                            callsPrivate -= m; 
+                            usesNonPublics -= m; 
                           } else {
                             if (settings.debug.value)
                               log("inline failed for " + inc + " because:\n\tinc.symbol != m.symbol: " + (inc.symbol != m.symbol)
@@ -351,31 +372,50 @@ abstract class Inliners extends SubComponent {
                                   + "\n\tinc.code ne null: " + (inc.code ne null) + (if (inc.code ne null)
                                     "\n\tisSafeToInline(m, inc, info.stack): " + isSafeToInline(m, inc, info.stack)
                                     + "\n\tshouldInline heuristics: " + shouldInline(m, inc) else ""));
+                            warnNoInline(
+                              if (inc.code eq null) "bytecode was unavailable"
+                              else if (!isSafeToInline(m, inc, info.stack)) "it is unsafe (target may reference private fields)"
+                              else "a bug (run with -Ylog:inline -Ydebug for more information)")
                           }
                         case None =>
-                          ();
+                          warnNoInline("bytecode was not available")
+                          if (settings.debug.value)
+                            log("could not find icode\n\treceiver: " + receiver + "\n\tmethod: " + concreteMethod)
                       }
-                    }
+                    } else
+                      warnNoInline(if (icodes.available(receiver)) "it is not final" else "bytecode was not available")
 
                   case _ => ();
                 }
                 info = tfa.interpret(info, i)
               }}}
-        if (tfa.stat) log(m.symbol.fullNameString + " iterations: " + tfa.iterations + " (size: " + m.code.blocks.length + ")")
+        if (tfa.stat) log(m.symbol.fullName + " iterations: " + tfa.iterations + " (size: " + m.code.blocks.length + ")")
       }} while (retry && count < 15)
       m.normalize
-    } catch {
-      case e => 
-        Console.println("############# Caught exception: " + e + " #################");
-        Console.println("\nMethod: " + m + 
-                        "\nMethod owner: " + m.symbol.owner);
-        e.printStackTrace();
-        m.dump
-        throw e
+		}
+    
+    
+    def isMonadMethod(method: Symbol): Boolean = 
+      (method.name == nme.foreach
+      	|| method.name == nme.filter 
+      	|| method.name == nme.map
+      	|| method.name == nme.flatMap)
+
+    /** Should the given method be loaded from disk? */
+    def shouldLoad(receiver: Symbol, method: Symbol): Boolean = {
+      if (settings.debug.value) log("shouldLoad: " + receiver + "." + method)
+      ((method.isEffectivelyFinal && isMonadMethod(method) && isHigherOrderMethod(method))
+        || (receiver.enclosingPackage == definitions.ScalaRunTimeModule.enclosingPackage)
+        || (receiver == definitions.PredefModule.moduleClass)
+        || (method.hasAnnotation(ScalaInlineAttr)))
     }
     
     /** Cache whether a method calls private members. */
-    val callsPrivate: Map[IMethod, Boolean] = new HashMap;
+    val usesNonPublics: Map[IMethod, NonPublicRefs.Value] = new HashMap;
+
+    object NonPublicRefs extends Enumeration {
+      val Public, Protected, Private = Value
+    }
     
     def isRecursive(m: IMethod): Boolean = m.recursive
     
@@ -389,46 +429,65 @@ abstract class Inliners extends SubComponent {
      *    - synthetic private members are made public in this pass.
      */
     def isSafeToInline(caller: IMethod, callee: IMethod, stack: TypeStack): Boolean = {
-      var callsPrivateMember = false
+      def makePublic(f: Symbol): Boolean = 
+        if ((callee.sourceFile ne null) 
+            && (f.hasFlag(Flags.SYNTHETIC | Flags.PARAMACCESSOR))) {
+          if (settings.debug.value) log("Making not-private symbol out of synthetic: " + f)
+          f.setFlag(Flags.notPRIVATE)
+          true
+        } else false
+
+      import NonPublicRefs._
+      var callsNonPublic = Public
 
       if (callee.recursive) return false
       
-      callsPrivate get (callee) match {
+      usesNonPublics.get(callee) match {
         case Some(b) =>
-          callsPrivateMember = b
+          callsNonPublic = b
         case None =>
-          for (b <- callee.code.blocks)
-            for (i <- b.toList)
+          // Avoiding crashing the compiler if there are open blocks.
+          callee.code.blocks filterNot (_.closed) foreach { b =>
+            currentIClazz.cunit.warning(callee.symbol.pos,
+              "Encountered open block in isSafeToInline: this indicates a bug in the optimizer!\n" +
+              "  caller = " + caller + ", callee = " + callee
+            )
+            return false
+          }
+          
+          breakable {
+            for (b <- callee.code.blocks; i <- b)
               i match {
                 case CALL_METHOD(m, style) =>
                   if (m.hasFlag(Flags.PRIVATE) || 
-                      (style.isSuper && !m.isClassConstructor))
-                    callsPrivateMember = true;
+                      (style.isSuper && !m.isClassConstructor)) {
+                    callsNonPublic = Private
+                    break
+                  }
+                  if (m.hasFlag(Flags.PROTECTED)) callsNonPublic = Protected
 
                 case LOAD_FIELD(f, _) =>
-                  if (f.hasFlag(Flags.PRIVATE)) 
-                    if (f.hasFlag(Flags.SYNTHETIC) || f.hasFlag(Flags.PARAMACCESSOR)) {
-                      if (settings.debug.value)
-                        log("Making not-private symbol out of synthetic: " + f);
-                      f.setFlag(Flags.notPRIVATE)
-                    } else
-                      callsPrivateMember = true;
+                  if (f.hasFlag(Flags.PRIVATE) && !makePublic(f)) {
+                    callsNonPublic = Private;
+                    break
+                  }
+                  if (f.hasFlag(Flags.PROTECTED)) callsNonPublic = Protected
 
                 case STORE_FIELD(f, _) =>
-                  if (f.hasFlag(Flags.PRIVATE))
-                    if (f.hasFlag(Flags.SYNTHETIC) || f.hasFlag(Flags.PARAMACCESSOR)) {
-                      if (settings.debug.value)
-                        log("Making not-private symbol out of synthetic: " + f);
-                      f.setFlag(Flags.notPRIVATE)
-                    } else
-                      callsPrivateMember = true;
+                  if (f.hasFlag(Flags.PRIVATE) && !makePublic(f)) {
+                    callsNonPublic = Private;
+                    break
+                  }
+                  if (f.hasFlag(Flags.PROTECTED)) callsNonPublic = Protected
 
                 case _ => ()
               }
-          callsPrivate += (callee -> callsPrivateMember)
-        }
+          }
+          usesNonPublics += (callee -> callsNonPublic)
+      }
 
-      if (callsPrivateMember && (caller.symbol.owner != callee.symbol.owner))
+      if ((callsNonPublic == Private && (caller.symbol.owner != callee.symbol.owner))
+          || callsNonPublic == Protected && !(caller.symbol.owner.tpe <:< callee.symbol.owner.tpe))
         return false;
 
       if (stack.length > (1 + callee.symbol.info.paramTypes.length) &&
@@ -440,7 +499,7 @@ abstract class Inliners extends SubComponent {
     }
     
     private def lookupImpl(meth: Symbol, clazz: Symbol): Symbol = {
-      //println("\t\tlooking up " + meth + " in " + clazz.fullNameString + " meth.owner = " + meth.owner)
+      //println("\t\tlooking up " + meth + " in " + clazz.fullName + " meth.owner = " + meth.owner)
       if (meth.owner == clazz 
           || clazz == definitions.NullClass 
           || clazz == definitions.NothingClass) meth
@@ -454,9 +513,9 @@ abstract class Inliners extends SubComponent {
           lookupImpl(meth, clazz.tpe.parents(0).typeSymbol)
       }
     }
-    
+
     /** small method size (in blocks) */
-    val SMALL_METHOD_SIZE = 4
+    val SMALL_METHOD_SIZE = 1
     
     /** Decide whether to inline or not. Heuristics:
      *   - it's bad to make the caller larger (> SMALL_METHOD_SIZE) 
@@ -468,14 +527,14 @@ abstract class Inliners extends SubComponent {
      */
     def shouldInline(caller: IMethod, callee: IMethod): Boolean = {
        if (caller.symbol.hasFlag(Flags.BRIDGE)) return false;
-       if (callee.symbol.hasAttribute(ScalaNoInlineAttr)) return false
-       if (callee.symbol.hasAttribute(ScalaInlineAttr)) return true
+       if (callee.symbol.hasAnnotation(ScalaNoInlineAttr)) return false
+       if (callee.symbol.hasAnnotation(ScalaInlineAttr)) return true
        if (settings.debug.value)
          log("shouldInline: " + caller + " with " + callee)
        var score = 0
        if (callee.code.blocks.length <= SMALL_METHOD_SIZE) score = score + 1
        if (caller.code.blocks.length <= SMALL_METHOD_SIZE 
-           && ((caller.code.blocks.length + callee.code.blocks.length) > SMALL_METHOD_SIZE)) {
+           && ((caller.code.blocks.length + callee.code.blocks.length - 1) > SMALL_METHOD_SIZE)) {
          score -= 1
          if (settings.debug.value)
            log("shouldInline: score decreased to " + score + " because small " + caller + " would become large")
@@ -483,25 +542,29 @@ abstract class Inliners extends SubComponent {
        if (callee.code.blocks.length > MAX_INLINE_SIZE)
          score -= 1
          
-       if (callee.symbol.tpe.paramTypes.exists(t => definitions.FunctionClass.contains(t.typeSymbol))) {
-         if (settings.debug.value)
-           log("increased score to: " + score)
+       if (isMonadMethod(callee.symbol)) 
          score += 2
-       }
+       else if (isHigherOrderMethod(callee.symbol))
+         score += 1
        if (isClosureClass(callee.symbol.owner))
          score += 2
-         
+       
+       if (inlinedMethods(callee.symbol) > 2) score -= 2
+       if (settings.debug.value) log("shouldInline(" + callee + ") score: " + score)  
        score > 0
      }
   } /* class Inliner */
     
-  /** Is the given class a subtype of a function trait? */
+  /** Is the given class a closure? */
   def isClosureClass(cls: Symbol): Boolean = {
-    val res = cls.isFinal && cls.hasFlag(Flags.SYNTHETIC) &&
-        cls.tpe.parents.exists { t => 
-          val TypeRef(_, sym, _) = t;
-          definitions.FunctionClass exists sym.==
-        }
+    val res = (cls.isFinal && cls.hasFlag(Flags.SYNTHETIC)
+      && !cls.isModuleClass && cls.isAnonymousFunction)
     res
   }
+  
+  /** Does 'sym' denote a higher order method? */
+  def isHigherOrderMethod(sym: Symbol): Boolean = 
+    (sym.isMethod 
+     && atPhase(currentRun.erasurePhase.prev)(sym.info.paramTypes exists definitions.isFunctionType))
+
 } /* class Inliners */
diff --git a/src/compiler/scala/tools/nsc/dependencies/Changes.scala b/src/compiler/scala/tools/nsc/dependencies/Changes.scala
new file mode 100644
index 0000000..c2cbd9e
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/dependencies/Changes.scala
@@ -0,0 +1,211 @@
+package scala.tools.nsc
+package dependencies
+
+import symtab.Flags
+
+import collection._
+
+/** A component that describes the possible changes between successive 
+ *  compilations of a class.
+ */
+abstract class Changes {
+
+  /** A compiler instance used to compile files on demand. */
+  val compiler: Global
+
+  import compiler._
+  import symtab.Flags._
+
+  abstract class Change
+
+  private lazy val annotationsChecked =
+      List(definitions.getClass("scala.specialized")) // Any others that should be checked?
+
+  /** Are the new modifiers more restrictive than the old ones? */
+  private def moreRestrictive(from: Long, to: Long): Boolean =
+    ((((to & PRIVATE) != 0L) && (from & PRIVATE) == 0L)
+     || (((to & PROTECTED) != 0L) && (from & PROTECTED) == 0L)) ||
+    ((from & IMPLICIT) != (to & IMPLICIT))
+
+  /** An entity in source code, either a class or a member definition.
+   *  Name is fully-qualified.
+   */
+  abstract class Entity
+  case class Class(name: String) extends Entity
+  case class Definition(name: String) extends Entity
+  
+  case class Added(e: Entity) extends Change
+  case class Removed(e: Entity) extends Change
+  case class Changed(e: Entity)(implicit val reason: String) extends Change {
+    override def toString = "Changed(" + e + ")[" + reason + "]"
+  }
+  case class ParentChanged(e: Entity) extends Change
+  
+  private val changedTypeParams = new mutable.HashSet[String]
+
+  private def sameSymbol(sym1: Symbol, sym2: Symbol, simple: Boolean = false): Boolean =
+    if (simple) sym1.encodedName == sym2.encodedName else sym1.fullName == sym2.fullName
+  private def sameFlags(sym1: Symbol, sym2: Symbol): Boolean =
+    sym1.flags == sym2.flags
+  private def sameAnnotations(sym1: Symbol, sym2: Symbol): Boolean =
+    annotationsChecked.forall(a =>
+      (sym1.hasAnnotation(a) == sym2.hasAnnotation(a)))
+
+  private def sameType(tp1: Type, tp2: Type)(implicit strict: Boolean) = {
+    def typeOf(tp: Type): String = tp.toString + "[" + tp.getClass + "]"
+    val res = sameType0(tp1, tp2)
+    //if (!res) println("\t different types: " + typeOf(tp1) + " : " + typeOf(tp2))
+    res
+  }
+  
+  private def sameType0(tp1: Type, tp2: Type)(implicit strict: Boolean): Boolean = ((tp1, tp2) match {
+    /*case (ErrorType, _) => false
+    case (WildcardType, _) => false
+    case (_, ErrorType) => false
+    case (_, WildcardType) => false
+    */
+    case (NoType, _) => false
+    case (NoPrefix, NoPrefix) => true
+    case (_, NoType) => false
+    case (_, NoPrefix) => false
+
+    case (ThisType(sym1), ThisType(sym2))
+      if sameSymbol(sym1, sym2) => true
+
+    case (SingleType(pre1, sym1), SingleType(pre2, sym2))
+      if sameType(pre1, pre2) && sameSymbol(sym1, sym2) => true
+    case (ConstantType(value1), ConstantType(value2)) =>
+      value1 == value2
+    case (TypeRef(pre1, sym1, args1), TypeRef(pre2, sym2, args2)) =>
+      val testSymbols = 
+        if (!sameSymbol(sym1, sym2)) {
+          val v = (!strict && sym1.isType && sym2.isType && sameType(sym1.info, sym2.info))
+          if (v) changedTypeParams += sym1.fullName
+          v
+        } else
+          !sym1.isTypeParameter || !changedTypeParams.contains(sym1.fullName)
+
+      testSymbols && sameType(pre1, pre2) && 
+        (sym1.variance == sym2.variance) &&
+        ((tp1.isHigherKinded && tp2.isHigherKinded && tp1.normalize =:= tp2.normalize) || 
+           sameTypes(args1, args2))
+         // @M! normalize reduces higher-kinded case to PolyType's
+
+    case (RefinedType(parents1, ref1), RefinedType(parents2, ref2)) =>
+      def isSubScope(s1: Scope, s2: Scope): Boolean = s2.toList.forall {
+        sym2 =>
+          var e1 = s1.lookupEntry(sym2.name)
+          (e1 ne null) && {
+            var isEqual = false
+            while (!isEqual && (e1 ne null)) { 
+              isEqual = sameType(e1.sym.info, sym2.info)
+              e1 = s1.lookupNextEntry(e1)
+            }
+            isEqual
+          }
+      }
+      sameTypes(parents1, parents2) && isSubScope(ref1, ref2) && isSubScope(ref2, ref1)
+    case (mt1 @ MethodType(params1, res1), mt2 @ MethodType(params2, res2)) =>
+      // new dependent types: probably fix this, use substSym as done for PolyType
+      sameTypes(tp1.paramTypes, tp2.paramTypes) &&
+      (tp1.params corresponds tp2.params)((t1, t2) => sameSymbol(t1, t2, true) && sameFlags(t1, t2)) &&
+      sameType(res1, res2) &&
+      mt1.isImplicit == mt2.isImplicit
+    case (PolyType(tparams1, res1), PolyType(tparams2, res2)) =>
+      sameTypeParams(tparams1, tparams2) && sameType(res1, res2)
+    case (ExistentialType(tparams1, res1), ExistentialType(tparams2, res2)) =>
+      sameTypeParams(tparams1, tparams2)(false) && sameType(res1, res2)(false)
+    case (TypeBounds(lo1, hi1), TypeBounds(lo2, hi2)) =>
+      sameType(lo1, lo2) && sameType(hi1, hi2)
+    case (BoundedWildcardType(bounds), _) =>
+      bounds containsType tp2
+    case (_, BoundedWildcardType(bounds)) =>
+      bounds containsType tp1
+    case (AnnotatedType(_,_,_), _) =>
+      annotationsConform(tp1, tp2) && annotationsConform(tp2, tp1) &&
+      sameType(tp1.withoutAnnotations, tp2.withoutAnnotations)
+    case (_, AnnotatedType(_,_,_)) =>
+      annotationsConform(tp1, tp2) && annotationsConform(tp2, tp1) &&
+      sameType(tp1.withoutAnnotations, tp2.withoutAnnotations)
+    case (_: SingletonType, _: SingletonType) =>
+      var origin1 = tp1
+      while (origin1.underlying.isInstanceOf[SingletonType]) {
+        assert(origin1 ne origin1.underlying, origin1)
+        origin1 = origin1.underlying
+      }
+      var origin2 = tp2
+      while (origin2.underlying.isInstanceOf[SingletonType]) {
+        assert(origin2 ne origin2.underlying, origin2)
+        origin2 = origin2.underlying
+      }
+      ((origin1 ne tp1) || (origin2 ne tp2)) && sameType(origin1, origin2)
+    case _ =>
+      false
+    }) || {
+      val tp1n = normalizePlus(tp1)
+      val tp2n = normalizePlus(tp2)
+      ((tp1n ne tp1) || (tp2n ne tp2)) && sameType(tp1n, tp2n)
+    }
+
+  private def sameTypeParams(tparams1: List[Symbol], tparams2: List[Symbol])(implicit strict: Boolean) =
+    sameTypes(tparams1 map (_.info), tparams2 map (_.info)) &&
+    sameTypes(tparams1 map (_.tpe), tparams2 map (_.tpe)) &&
+    (tparams1 corresponds tparams2)((t1, t2) => sameAnnotations(t1, t2))
+
+  private def sameTypes(tps1: List[Type], tps2: List[Type])(implicit strict: Boolean) =
+    (tps1 corresponds tps2)(sameType(_, _))
+
+  /** Return the list of changes between 'from' and 'toSym.info'.
+   */
+  def changeSet(from: Type, toSym: Symbol): List[Change] = {
+    implicit val defaultReason = "types"
+    implicit val defaultStrictTypeRefTest = true
+    
+    val to = toSym.info
+    changedTypeParams.clear
+    def omitSymbols(s: Symbol): Boolean = !s.hasFlag(LOCAL | LIFTED | PRIVATE)
+    val cs = new mutable.ListBuffer[Change]
+
+    if ((from.parents zip to.parents) exists { case (t1, t2) => !sameType(t1, t2) })
+      cs += Changed(toEntity(toSym))(from.parents.zip(to.parents).toString)
+    if (!sameTypeParams(from.typeParams, to.typeParams)(false))
+      cs += Changed(toEntity(toSym))(" tparams: " + from.typeParams.zip(to.typeParams))
+
+    // new members not yet visited
+    val newMembers = mutable.HashSet[Symbol]()
+    newMembers ++= to.decls.iterator filter omitSymbols
+
+    for (o <- from.decls.iterator filter omitSymbols) {
+      val n = to.decl(o.name)
+      newMembers -= n
+
+      if (o.isClass)
+        cs ++= changeSet(o.info, n)
+      else if (n == NoSymbol)
+        cs += Removed(toEntity(o))
+      else {
+        val newSym =
+            o match {
+              case _:TypeSymbol if o.isAliasType =>
+                n.suchThat(ov => sameType(ov.info, o.info))
+              case _                             =>
+                n.suchThat(ov => sameType(ov.tpe, o.tpe))
+             }
+        if (newSym == NoSymbol || moreRestrictive(o.flags, newSym.flags))
+          cs += Changed(toEntity(o))(n + " changed from " + o.tpe + " to " + n.tpe + " flags: " + Flags.flagsToString(o.flags))
+        else
+          newMembers -= newSym
+      }
+    }: Unit // Give the type explicitly until #2281 is fixed
+
+    cs ++= (newMembers map (Added compose toEntity))
+    cs.toList
+  }
+  def removeChangeSet(sym: Symbol): Change = Removed(toEntity(sym))
+  def changeChangeSet(sym: Symbol, msg: String): Change = Changed(toEntity(sym))(msg)
+  def parentChangeSet(sym: Symbol): Change = ParentChanged(toEntity(sym))
+
+  private def toEntity(sym: Symbol): Entity =
+    if (sym.isClass) Class(sym.fullName)
+    else Definition(sym.fullName)
+}
diff --git a/src/compiler/scala/tools/nsc/dependencies/DependencyAnalysis.scala b/src/compiler/scala/tools/nsc/dependencies/DependencyAnalysis.scala
new file mode 100644
index 0000000..6c6fad9
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/dependencies/DependencyAnalysis.scala
@@ -0,0 +1,231 @@
+package scala.tools.nsc
+package dependencies
+import util.SourceFile
+import io.AbstractFile
+import collection._
+import symtab.Flags
+
+trait DependencyAnalysis extends SubComponent with Files {
+  import global._
+
+  val phaseName = "dependencyAnalysis"
+
+  def off = settings.make.value == "all"
+
+  def newPhase(prev: Phase) = new AnalysisPhase(prev) 
+
+  lazy val maxDepth = settings.make.value match {
+    case "changed" => 0 
+    case "transitive" | "transitivenocp" => Int.MaxValue
+    case "immediate" => 1 
+  }
+
+  def shouldCheckClasspath = settings.make.value != "transitivenocp"
+
+  // todo: order insensible checking and, also checking timestamp?
+  def validateClasspath(cp1: String, cp2: String): Boolean = cp1 == cp2
+
+  def nameToFile(src: AbstractFile, name: String) = 
+    settings.outputDirs.outputDirFor(src)
+      .lookupPathUnchecked(name.toString.replace(".", java.io.File.separator) + ".class", false)
+
+  private var depFile: Option[AbstractFile] = None
+
+  def dependenciesFile_=(file: AbstractFile) {
+    assert(file ne null)
+    depFile = Some(file)
+  }
+
+  def dependenciesFile: Option[AbstractFile] = depFile
+
+  def classpath = settings.classpath.value
+  def newDeps = new FileDependencies(classpath)
+
+  var dependencies = newDeps
+
+  def managedFiles = dependencies.dependencies.keySet
+  
+  /** Top level definitions per source file. */
+  val definitions: mutable.Map[AbstractFile, List[Symbol]] =
+    new mutable.HashMap[AbstractFile, List[Symbol]] {
+      override def default(f: AbstractFile) = Nil
+  }
+  
+  /** External references used by source file. */
+  val references: mutable.Map[AbstractFile, immutable.Set[String]] = 
+    new mutable.HashMap[AbstractFile, immutable.Set[String]] {
+      override def default(f: AbstractFile) = immutable.Set()
+    }
+
+  /** External references for inherited members used in the source file */
+  val inherited: mutable.Map[AbstractFile, immutable.Set[Inherited]] = 
+    new mutable.HashMap[AbstractFile, immutable.Set[Inherited]] {
+      override def default(f: AbstractFile) = immutable.Set()
+    }
+
+  /** Write dependencies to the current file. */
+  def saveDependencies(fromFile: AbstractFile => String) = 
+    if(dependenciesFile.isDefined)
+      dependencies.writeTo(dependenciesFile.get, fromFile)
+
+  /** Load dependencies from the given file and save the file reference for
+   *  future saves.
+   */
+  def loadFrom(f: AbstractFile, toFile: String => AbstractFile): Boolean = {
+    dependenciesFile = f
+    FileDependencies.readFrom(f, toFile) match {
+      case Some(fd) =>      
+        val success = if (shouldCheckClasspath) validateClasspath(fd.classpath, classpath) else true
+        dependencies = if (success) fd else {
+          if (settings.debug.value)
+            println("Classpath has changed. Nuking dependencies")
+          newDeps
+        }
+        
+        success
+      case None => false
+    }
+  }
+
+  def filter(files: List[SourceFile]): List[SourceFile] = 
+    if (off) files
+    else if (dependencies.isEmpty) {
+      println("No known dependencies. Compiling " +
+              (if (settings.debug.value) files.mkString(", ") else "everything"))
+      files
+    } else {
+      val (direct, indirect) = dependencies.invalidatedFiles(maxDepth);  
+      val filtered = files.filter(x => {
+        val f = x.file.absolute
+        direct(f) || indirect(f) || !dependencies.containsFile(f);
+      })
+      filtered match {
+        case Nil => println("No changes to recompile");
+        case x => println("Recompiling " + (
+          if(settings.debug.value) x.mkString(", ") else x.length + " files")
+        )
+      }
+      filtered
+    }
+
+  case class Inherited(qualifier: String, member: Name)
+
+  class AnalysisPhase(prev: Phase) extends StdPhase(prev) {
+      
+    override def cancelled(unit: CompilationUnit) =
+      super.cancelled(unit) && !unit.isJava
+
+    def apply(unit : global.CompilationUnit) { 
+      val f = unit.source.file.file
+      // When we're passed strings by the interpreter 
+      // they  have no source file. We simply ignore this case
+      // as irrelevant to dependency analysis.
+      if (f != null){
+        val source: AbstractFile = unit.source.file;
+        for (d <- unit.icode){
+          val name = d.toString
+          d.symbol match {
+            case s : ModuleClassSymbol =>
+              val isTopLevelModule =
+                  atPhase (currentRun.picklerPhase.next) {
+                    !s.isImplClass && !s.isNestedClass
+                  }
+              if (isTopLevelModule && (s.companionModule != NoSymbol)) {
+                dependencies.emits(source, nameToFile(unit.source.file, name))
+              }
+              dependencies.emits(source, nameToFile(unit.source.file, name + "$"))
+            case _ =>
+              dependencies.emits(source, nameToFile(unit.source.file, name))
+          }
+        }
+
+        dependencies.reset(source)
+        for (d <- unit.depends; if (d.sourceFile != null)){
+          dependencies.depends(source, d.sourceFile)
+        }
+      }
+
+      // find all external references in this compilation unit
+      val file = unit.source.file
+      references += file -> immutable.Set.empty[String]
+      inherited += file -> immutable.Set.empty[Inherited]
+
+      val buf = new mutable.ListBuffer[Symbol]
+
+      (new Traverser {
+        override def traverse(tree: Tree) {
+          if ((tree.symbol ne null)
+              && (tree.symbol != NoSymbol)
+              && (!tree.symbol.isPackage)
+              && (!tree.symbol.hasFlag(Flags.JAVA))
+              && ((tree.symbol.sourceFile eq null)
+                  || (tree.symbol.sourceFile.path != file.path))
+              && (!tree.symbol.isClassConstructor)) {
+            updateReferences(tree.symbol.fullName)
+            atPhase(currentRun.uncurryPhase.prev) {
+              checkType(tree.symbol.tpe)
+            }
+          }
+
+          tree match {
+            case cdef: ClassDef if !cdef.symbol.hasFlag(Flags.PACKAGE) &&
+                                   !cdef.symbol.isAnonymousFunction =>
+              if (cdef.symbol != NoSymbol) buf += cdef.symbol
+              atPhase(currentRun.erasurePhase.prev) {
+                for (s <- cdef.symbol.info.decls)
+                  s match {
+                    case ts: TypeSymbol if !ts.isClass =>
+                      checkType(s.tpe)
+                    case _ =>
+                  }
+              }
+              super.traverse(tree)
+
+            case ddef: DefDef =>
+              atPhase(currentRun.typerPhase.prev) {
+                checkType(ddef.symbol.tpe)
+              }
+              super.traverse(tree)
+            case a @ Select(q, n) if ((a.symbol != NoSymbol) && (q.symbol != null)) => // #2556
+              if (!a.symbol.isConstructor &&
+                  !a.symbol.owner.isPackageClass &&
+                  !isSameType(q.tpe, a.symbol.owner.tpe))
+                  inherited += file ->
+                    (inherited(file) + Inherited(q.symbol.tpe.resultType.safeToString, n))
+              super.traverse(tree)
+            case _            =>
+              super.traverse(tree)
+          }
+        }
+        
+        def checkType(tpe: Type): Unit =
+          tpe match {
+            case t: MethodType =>
+              checkType(t.resultType)
+              for (s <- t.params) checkType(s.tpe)
+            
+            case t: TypeRef    =>
+              if (t.sym.isAliasType) {
+                  updateReferences(t.typeSymbolDirect.fullName)
+                  checkType(t.typeSymbolDirect.info)
+              }
+              updateReferences(t.typeSymbol.fullName)            
+              for (tp <- t.args) checkType(tp)
+            
+            case t: PolyType   =>
+              checkType(t.resultType)
+              updateReferences(t.typeSymbol.fullName)
+            
+            case t             =>
+              updateReferences(t.typeSymbol.fullName)
+          }
+        
+        def updateReferences(s: String): Unit =
+          references += file -> (references(file) + s)
+
+      }).apply(unit.body)
+
+      definitions(unit.source.file) = buf.toList
+    }
+  }
+}
diff --git a/src/compiler/scala/tools/nsc/dependencies/Files.scala b/src/compiler/scala/tools/nsc/dependencies/Files.scala
new file mode 100644
index 0000000..8f26ae8
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/dependencies/Files.scala
@@ -0,0 +1,177 @@
+package scala.tools.nsc
+package dependencies
+
+import java.io.{InputStream, OutputStream, PrintStream, InputStreamReader, BufferedReader}
+import io.{AbstractFile, PlainFile, VirtualFile}
+
+import scala.collection._
+
+
+trait Files { self : SubComponent =>
+
+  class FileDependencies(val classpath: String) {
+    import FileDependencies._
+
+    class Tracker extends mutable.OpenHashMap[AbstractFile, mutable.Set[AbstractFile]] {
+      override def default(key: AbstractFile) = {
+        this(key) = new mutable.HashSet[AbstractFile]
+        this(key)
+      }
+    }
+
+    val dependencies = new Tracker
+    val targets =  new Tracker
+
+    def isEmpty = dependencies.isEmpty && targets.isEmpty
+
+    def emits(source: AbstractFile, result: AbstractFile) = 
+      targets(source) += result
+    def depends(from: AbstractFile, on: AbstractFile) = 
+      dependencies(from) += on
+
+    def reset(file: AbstractFile) = dependencies -= file
+    
+    def cleanEmpty = {
+      dependencies foreach {case (_, value) =>
+                               value retain (x => x.exists && (x ne removedFile))}
+      dependencies retain ((key, value) => key.exists && !value.isEmpty)
+      targets foreach {case (_, value) => value retain (_.exists)}
+      targets retain ((key, value) => key.exists && !value.isEmpty)
+    }
+
+    def containsFile(f: AbstractFile) = targets.contains(f.absolute)        
+
+    def invalidatedFiles(maxDepth: Int) = {
+      val direct = new mutable.HashSet[AbstractFile]
+
+      for ((file, products) <- targets) {
+        // This looks a bit odd. It may seem like one should invalidate a file
+        // if *any* of its dependencies are older than it. The forall is there
+        // to deal with the fact that a) Some results might have been orphaned
+        // and b) Some files might not need changing. 
+        direct(file) ||= products.forall(d => d.lastModified < file.lastModified)
+      }
+
+      val indirect = dependentFiles(maxDepth, direct)
+
+      for ((source, targets) <- targets  
+           if direct(source) || indirect(source) || (source eq removedFile)) {
+        targets foreach (_.delete)
+        targets -= source
+      }
+
+      (direct, indirect)
+    }
+
+    /** Return the set of files that depend on the given changed files.
+     *  It computes the transitive closure up to the given depth.
+     */
+    def dependentFiles(depth: Int, changed: Set[AbstractFile]): Set[AbstractFile] = {
+      val indirect = new mutable.HashSet[AbstractFile]
+      val newInvalidations = new mutable.HashSet[AbstractFile]
+
+      def invalid(file: AbstractFile) =
+        indirect(file) || changed(file) || (file eq removedFile)
+
+      def go(i: Int) : Unit = if(i > 0) {
+        newInvalidations.clear
+        for((target, depends) <- dependencies if !invalid(target);
+            d <- depends)
+          newInvalidations(target) ||= invalid(d)
+
+        indirect ++= newInvalidations
+        if (!newInvalidations.isEmpty) go(i - 1)
+      }
+
+      go(depth)
+
+      indirect --= changed
+    }
+
+    def writeTo(file: AbstractFile, fromFile: AbstractFile => String): Unit = 
+      writeToFile(file)(out => writeTo(new PrintStream(out), fromFile))
+    
+    def writeTo(print: PrintStream, fromFile: AbstractFile => String): Unit = {
+      def emit(tracker: Tracker) =
+        for ((f, ds) <- tracker; d <- ds) print.println(fromFile(f) + arrow + fromFile(d))
+      
+      cleanEmpty
+      print.println(classpath)
+      print.println(separator)
+      emit(dependencies)
+      print.println(separator)
+      emit(targets)
+    }
+  }
+
+  object FileDependencies {
+    private val separator:String = "-------"
+    private val arrow = " -> "
+    private val removedFile = new VirtualFile("removed")
+    
+    private def validLine(l: String) = (l != null) && (l != separator)
+
+    def readFrom(file: AbstractFile, toFile: String => AbstractFile): Option[FileDependencies] =
+      readFromFile(file) { in =>
+        val reader = new BufferedReader(new InputStreamReader(in))
+        val it = new FileDependencies(reader.readLine)
+        
+        def readLines(valid: Boolean)(f: (AbstractFile, AbstractFile) => Unit): Boolean = {
+          var continue = valid
+          var line: String = null
+          while (continue && {line = reader.readLine; validLine(line)}) { 
+            line.split(arrow) match {
+              case Array(from, on) => f(toFile(from), toFile(on))
+              case _ =>
+                global.inform("Parse error: Unrecognised string " + line)
+                continue = false
+            }
+          }
+          continue
+        }
+        
+        reader.readLine
+
+        val dResult = readLines(true)(
+          (_, _) match {
+            case (null, _)          => // fromFile is removed, it's ok
+            case (fromFile, null)   =>
+              // onFile is removed, should recompile fromFile
+              it.depends(fromFile, removedFile) 
+            case (fromFile, onFile) => it.depends(fromFile, onFile)
+          })
+        
+        readLines(dResult)(
+          (_, _) match {
+            case (null, null)             =>
+              // source and target are all removed, it's ok
+            case (null, targetFile)       =>
+              // source is removed, should remove relative target later
+              it.emits(removedFile, targetFile)
+            case (_, null)                =>
+              // it may has been cleaned outside, or removed during last phase
+            case (sourceFile, targetFile) => it.emits(sourceFile, targetFile)
+          })
+          
+        Some(it)
+      }
+  }
+
+  def writeToFile[T](file: AbstractFile)(f: OutputStream => T) : T = {
+    val out = file.bufferedOutput
+    try {
+      f(out) 
+    } finally {
+      out.close
+    }
+  }
+
+  def readFromFile[T](file: AbstractFile)(f: InputStream => T) : T = {
+    val in = file.input
+    try{
+      f(in)
+    } finally {
+      in.close
+    }
+  }
+}
diff --git a/src/compiler/scala/tools/nsc/doc/DefaultDocDriver.scala b/src/compiler/scala/tools/nsc/doc/DefaultDocDriver.scala
deleted file mode 100644
index 9b93f9f..0000000
--- a/src/compiler/scala/tools/nsc/doc/DefaultDocDriver.scala
+++ /dev/null
@@ -1,305 +0,0 @@
-/* NSC -- new Scala compiler
- * Copyright 2007-2009 LAMP/EPFL
- * @author  Sean McDirmid
- */
-// $Id: DefaultDocDriver.scala 16881 2009-01-09 16:28:11Z cunei $
-
-package scala.tools.nsc.doc
-
-import java.util.zip.ZipFile
-
-import scala.collection.jcl
-import symtab.Flags._
-import scala.xml._
-
-/**
- *  @author Sean McDirmid
- */
-abstract class DefaultDocDriver extends DocDriver with ModelFrames with ModelToXML {
-  import global._
-  import definitions.{AnyClass, AnyRefClass}
-
-  lazy val additions = new jcl.LinkedHashSet[Symbol]
-  lazy val additions0 = new ModelAdditions(global) {
-    override def addition(sym: global.Symbol) = {
-      super.addition(sym)
-      sym match {
-        case sym : global.ClassSymbol  => additions += sym.asInstanceOf[Symbol]
-        case sym : global.ModuleSymbol => additions += sym.asInstanceOf[Symbol]
-        case sym : global.TypeSymbol   => additions += sym.asInstanceOf[Symbol]
-        case _ =>
-      }
-    }
-    def init {}
-  }
-  
-  /** Add all top-level entities in ModelAdditions to allClasses */
-  def addAdditionsToClasses() {
-    additions0.init
-    for (sym <- additions) {
-      val packSym = sym.enclosingPackage
-      if (packSym != NoSymbol) {
-        val pack = Package(packSym)
-        if (!(allClasses contains pack)) {
-          // don't emit an addition unless its package
-          // is already being scaladoced
-        } else {
-          val addition: Option[ClassOrObject] =
-            if (sym.isClass)
-              Some(new TopLevelClass(sym))
-            else if (sym.isModule)
-              Some(new TopLevelObject(sym))
-            else if (sym == definitions.AnyRefClass) {
-              // AnyRef is the only top-level type alias, so handle
-              // it specially instead of introducing general support for
-              // top-level aliases
-              Some(new TopLevelClass(sym))
-            }
-            else
-              None
-
-          addition match {
-            case None =>
-              //println("skipping: " + sym) //DEBUG
-            case Some(addition) =>
-              allClasses(pack) += addition
-          }
-        }
-      } else {
-        //println("no package found for: "+sym) //DEBUG
-      }
-    }
-  }
-
-  def process(units: Iterator[CompilationUnit]) {
-
-    assert(global.definitions != null)
-
-    def g(pkg: Package, clazz: ClassOrObject) {
-      if (isAccessible(clazz.sym)) {
-        allClasses(pkg) += clazz
-        clazz.decls.map(_._2).foreach {
-          case clazz : ClassOrObject => g(pkg, clazz)
-          case _ =>
-        }
-      }
-    }
-    def f(pkg: Package, tree: Tree) {
-      if (tree != EmptyTree && tree.hasSymbol) {
-        val sym = tree.symbol
-        if (sym != NoSymbol && !sym.hasFlag(symtab.Flags.PRIVATE)) tree match {
-          case tree : PackageDef => 
-            val pkg1 = new Package(sym.asInstanceOf[ModuleSymbol])
-            tree.stats.foreach(stat => f(pkg1, stat))
-          case tree : ClassDef => 
-            assert(pkg != null)
-            g(pkg, new TopLevelClass(sym.asInstanceOf[ClassSymbol]))
-          case tree : ModuleDef =>
-            assert(pkg != null)
-            g(pkg, new TopLevelObject(sym.asInstanceOf[ModuleSymbol]))
-          case _ =>
-        }
-      }
-    }
-    units.foreach(unit => f(null, unit.body))
-    addAdditionsToClasses()
-
-    for (p <- allClasses; d <- p._2) {
-      symbols += d.sym
-      for (pp <- d.sym.tpe.parents) subClasses(pp.typeSymbol) += d
-    }
-    copyResources
-    lazy val packages0 = sort(allClasses.keySet)
-    new AllPackagesFrame     with Frame { def packages = packages0 }
-    new PackagesContentFrame with Frame { def packages = packages0 }
-    new NavigationFrame      with Frame { }
-    new ListClassFrame with Frame {
-      def classes = for (p <- allClasses; d <- p._2) yield d
-      object organized extends jcl.LinkedHashMap[(List[String],Boolean),List[ClassOrObject]] {
-        override def default(key : (List[String],Boolean)) = Nil;
-        classes.foreach(cls => {
-          val path = cls.path.map(_.name);
-          this((path,cls.isInstanceOf[Clazz])) = cls :: this((path,cls.isInstanceOf[Clazz]));
-        });
-      }
-      
-      def title = "List of all classes and objects"
-      def path = "all-classes"
-      def navLabel = null  // "root-page"
-      // override protected def navSuffix = ".html";
-      override def optional(cls: ClassOrObject): NodeSeq = {
-        val path = cls.path.map(_.name)
-        val key = (cls.path.map(_.name), cls.isInstanceOf[Clazz])
-        assert(!organized(key).isEmpty);
-        (if (!organized(key).tail.isEmpty) Text(" (" +{
-          //Console.println("CONFLICT: " + path + " " + organized(key));
-          val str = cls.path(0).sym.owner.fullNameString('.'); 
-          val idx = str.lastIndexOf('.');
-          if (idx == -1) str;
-          else str.substring(idx + 1);
-         }+ ")");
-         else NodeSeq.Empty) ++ super.optional(cls);
-      }
-	
-    }
-    for ((pkg0, classes0) <- allClasses) {
-      new ListClassFrame with Frame {
-        def title =
-          "List of classes and objects in package " + pkg0.fullName('.')
-        def classes = classes0
-        def path = pkgPath(pkg0.sym) + NAME_SUFFIX_PACKAGE
-        def navLabel = pkg0.fullName('.')
-      }
-      new PackageContentFrame with Frame {
-        def classes = classes0
-        def pkg = pkg0
-      }
-      for (clazz0 <- classes0) {
-        new ClassContentFrame with Frame {
-          def clazz = clazz0
-          def title =
-            clazz0.kind + " " + clazz0.name + " in " + (clazz0.sym.owner.fullNameString('.'));
-        }
-      }
-    }
-    new RootFrame with Frame
-  }
-  override def longList(entity: ClassOrObject, category: Category)(implicit from: Frame) : NodeSeq = category match {
-    case Classes | Objects => NodeSeq.Empty
-    case _ => super.longList(entity, category)
-  }
-
-  trait Frame extends super.Frame {
-    def longHeader(entity : Entity) = DefaultDocDriver.this.longHeader(entity)(this)
-    def shortHeader(entity : Entity) = DefaultDocDriver.this.shortHeader(entity)(this)
-  }
-
-  import DocUtil._
-  override def classBody(entity: ClassOrObject)(implicit from: Frame): NodeSeq = 
-    (subClasses.get(entity.sym) match {
-    case Some(symbols) => 
-      (<dl>
-      <dt style="margin:10px 0 0 20px;"><b>Direct Known Subclasses:</b></dt>
-      <dd>{symbols.mkXML("",", ","")(cls => {
-        aref(urlFor(cls.sym), cls.path.map(_.name).mkString("",".",""));
-      })}</dd>
-      </dl><hr/>);
-    case None =>
-      NodeSeq.Empty
-    })++super.classBody(entity);
-
-  protected def urlFor(sym: Symbol)(implicit frame: Frame) = frame.urlFor(sym)
-
-  override protected def decodeTag(tag: String): String = tag match {
-    case "exception"  => "Throws"
-    case "ex"         => "Examples"
-    case "param"      => "Parameters"
-    case "pre"        => "Precondition"
-    case "return"     => "Returns"
-    case "note"       => "Notes"
-    case "see"        => "See Also"
-    case tag => super.decodeTag(tag)
-  }
-
-  override protected def decodeOption(tag: String, option: String): NodeSeq = tag match {
-    case "throws" if additions0.exceptions.contains(option) => 
-      val (sym, s) = additions0.exceptions(option)
-      val path = "../" //todo: fix path
-      val href = path + sym.fullNameString('/') +
-      (if (sym.isModule || sym.isModuleClass) NAME_SUFFIX_OBJECT else "") +
-        "#" + s
-      (<a href={href}>{option}</a>) ++ {Text(" - ")};
-    case _ =>
-      super.decodeOption(tag,option)
-  }
-
-  object roots extends jcl.LinkedHashMap[String,String];
-  roots("classes") = "http://java.sun.com/j2se/1.5.0/docs/api";
-  roots("rt") = roots("classes");
-  private val SCALA_API_ROOT = "http://www.scala-lang.org/docu/files/api/";
-  roots("scala-library") = SCALA_API_ROOT;
-  
-  private def keyFor(file: ZipFile): String = {
-    var name = file.getName
-    var idx = name.lastIndexOf(java.io.File.pathSeparator)
-    if (idx == -1) idx = name.lastIndexOf('/')
-    if (idx != -1) name = name.substring(idx + 1)
-    if (name endsWith ".jar") name.substring(0, name.length - (".jar").length)
-    else null
-  }
-  
-  // <code>{Text(string + " - ")}</code>;
-  override def hasLink0(sym: Symbol): Boolean = {
-    if (sym == NoSymbol) return false;
-    if (sym == AnyRefClass) {
-      // AnyRefClass is a type alias, so the following logic
-      // does not work.  AnyClass should have a link in 
-      // the same cases as AnyRefClass, so test it instead.
-      return hasLink(AnyClass)
-    }
-    if (super.hasLink0(sym) && symbols.contains(sym))
-      return true;
-    if (SyntheticClasses contains sym)
-      return true;
-    if (sym.toplevelClass == NoSymbol) return false;
-    val clazz = sym.toplevelClass.asInstanceOf[ClassSymbol];
-    import scala.tools.nsc.io._;
-    clazz.classFile match {
-      case file : ZipArchive#FileEntry => 
-        val key = keyFor(file.archive);
-        if (key != null && roots.contains(key)) return true;
-      case null =>
-      case _ => 
-    }
-    false
-  }
-
-  def aref(href: String, label: String)(implicit frame: Frame) = 
-    frame.aref(href, "_self", label)
-
-  protected def anchor(entity: Symbol)(implicit frame: Frame): NodeSeq = 
-    (<a name={Text(frame.docName(entity))}></a>)
-  
-  object symbols extends jcl.LinkedHashSet[Symbol]
-
-  object allClasses extends jcl.LinkedHashMap[Package, jcl.LinkedHashSet[ClassOrObject]] {
-    override def default(pkg: Package): jcl.LinkedHashSet[ClassOrObject] = {
-      object ret extends jcl.LinkedHashSet[ClassOrObject]
-      this(pkg) = ret
-      ret
-    }
-  }
-
-  object subClasses extends jcl.LinkedHashMap[Symbol, jcl.LinkedHashSet[ClassOrObject]] {
-    override def default(key: Symbol) = {
-      val ret = new jcl.LinkedHashSet[ClassOrObject]
-      this(key) = ret
-      ret
-    }
-  }
-
-  override def rootFor(sym: Symbol): String = {
-    assert(sym != NoSymbol)
-    if (sym == definitions.AnyRefClass) {
-      // AnyRefClass is a type alias, so the following logic
-      // does not work.  AnyClass should have the same root,
-      // so use it instead.
-      return rootFor(definitions.AnyClass)
-    }
-    if (sym.toplevelClass == NoSymbol) return super.rootFor(sym)
-    if (symbols.contains(sym.toplevelClass)) return super.rootFor(sym)
-    if (SyntheticClasses contains sym)
-      return SCALA_API_ROOT
-    val clazz = sym.toplevelClass.asInstanceOf[ClassSymbol]
-    import scala.tools.nsc.io._;
-    clazz.classFile match {
-      case file : ZipArchive#FileEntry =>
-        val key = keyFor(file.archive)
-        if (key != null && roots.contains(key)) {
-          return roots(key) + '/'
-        }
-      case _ =>
-    }
-    super.rootFor(sym)
-  }
-}
diff --git a/src/compiler/scala/tools/nsc/doc/DocDriver.scala b/src/compiler/scala/tools/nsc/doc/DocDriver.scala
deleted file mode 100644
index e56e72e..0000000
--- a/src/compiler/scala/tools/nsc/doc/DocDriver.scala
+++ /dev/null
@@ -1,20 +0,0 @@
-/* NSC -- new Scala compiler
- * Copyright 2007-2009 LAMP/EPFL
- * @author  Sean McDirmid
- */
-// $Id: DocDriver.scala 16881 2009-01-09 16:28:11Z cunei $
-
-package scala.tools.nsc.doc
-
-/**
- *  This is an abstract class for documentation plugins.
- *
- *  @author Geoffrey Washburn
- */
-abstract class DocDriver {
- val global: Global
- import global._
- def settings: doc.Settings
-
- def process(units: Iterator[CompilationUnit]): Unit
-}
diff --git a/src/compiler/scala/tools/nsc/doc/DocFactory.scala b/src/compiler/scala/tools/nsc/doc/DocFactory.scala
new file mode 100644
index 0000000..b72281d
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/doc/DocFactory.scala
@@ -0,0 +1,66 @@
+/* NSC -- new Scala compiler -- Copyright 2007-2010 LAMP/EPFL */
+
+
+package scala.tools.nsc
+package doc
+
+import reporters.Reporter
+
+/** A documentation processor controls the process of generating Scala documentation, which is as follows.
+  *
+  * * A simplified compiler instance (with only the front-end phases enabled) is created, and additional
+  *   ''sourceless'' comments are registered.
+  * * Documentable files are compiled, thereby filling the compiler's symbol table.
+  * * A documentation model is extracted from the post-compilation symbol table.
+  * * A generator is used to transform the model into the correct final format (HTML).
+  *
+  * A processor contains a single compiler instantiated from the processor's `settings`. Each call to `document`
+  * uses the same compiler instance with the same symbol table. In particular, this implies that the scaladoc site
+  * obtained from a call to `run` will contain documentation about files compiled during previous calls to the same
+  * processor's `run` method.
+  *
+  * @param reporter The reporter to which both documentation and compilation errors will be reported.
+  * @param settings The settings to be used by the documenter and compiler for generating documentation.
+  * 
+  * @author Gilles Dubochet */
+class DocFactory(val reporter: Reporter, val settings: doc.Settings) { processor =>
+
+  /** The unique compiler instance used by this processor and constructed from its `settings`. */
+  object compiler extends Global(settings, reporter) with interactive.RangePositions {
+    override protected def computeInternalPhases() {
+      phasesSet += syntaxAnalyzer
+      phasesSet += analyzer.namerFactory
+      phasesSet += analyzer.packageObjects
+      phasesSet += analyzer.typerFactory
+      phasesSet += superAccessors
+      phasesSet += pickler
+      phasesSet += refchecks
+    }
+    override def onlyPresentation = true
+    lazy val addSourceless = {
+      val sless = new SourcelessComments { val global = compiler }
+      docComments ++= sless.comments
+    }
+  }
+
+  /** Creates a scaladoc site for all symbols defined in this call's `files`, as well as those defined in `files` of
+    * previous calls to the same processor.
+    * @param files The list of paths (relative to the compiler's source path, or absolute) of files to document. */
+  def universe(files: List[String]): Option[Universe] = {
+    (new compiler.Run()) compile files
+    compiler.addSourceless
+    assert(settings.docformat.value == "html")
+    if (!reporter.hasErrors) {
+      val modelFactory = (new model.ModelFactory(compiler, settings) with model.comment.CommentFactory with model.TreeFactory)
+      println("model contains " + modelFactory.templatesCount + " documentable templates")
+      Some(modelFactory.makeModel)
+    }
+    else None
+  }
+
+  /** Generate document(s) for all `files` containing scaladoc documenataion.
+    * @param files The list of paths (relative to the compiler's source path, or absolute) of files to document. */
+  def document(files: List[String]): Unit =
+    universe(files) foreach { docModel => (new html.HtmlFactory(docModel)).generate }
+  
+}
diff --git a/src/compiler/scala/tools/nsc/doc/DocUtil.scala b/src/compiler/scala/tools/nsc/doc/DocUtil.scala
deleted file mode 100644
index 1aa2968..0000000
--- a/src/compiler/scala/tools/nsc/doc/DocUtil.scala
+++ /dev/null
@@ -1,123 +0,0 @@
-/* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
- * @author  Sean McDirmid
- */
-// $Id: DocUtil.scala 16894 2009-01-13 13:09:41Z cunei $
-
-package scala.tools.nsc.doc
-
-import java.io.StringReader
-import org.xml.sax.InputSource
-
-import scala.collection.immutable.{ListMap, TreeSet}
-import scala.xml._
-
-object DocUtil {
-
-  //def dquote(str: String): NodeSeq =
-  //  DQUOTE :: Text(str) :: DQUOTE :: Nil
-
-  def load(str: String): NodeSeq =
-    if ((str == null) || (str.length == 0))
-      NodeSeq.Empty
-    else {
-      val xmlSrc =
-        if (str.matches("^(<!--.*-->)*<[^>]+>.*<[^>]+>(<!--.*-->)*$")) str
-        else "<div>" + str + "</div>"
-      XML.load(new StringReader(xmlSrc))
-    }
-
-  //object DQUOTE extends SpecialNode {
-   // def toString(sb: StringBuffer) = {
-   //   sb.append("\""); sb
-   // }
-   // def label = "#PCDATA"
-  //}
-
-  def br(nodes: NodeSeq): NodeSeq = nodes ++ (<br/>)
-  def hr(nodes: NodeSeq): NodeSeq = nodes ++ (<hr/>)
-
-  trait UrlContext {
-    def relative: String
-
-    def aref(href0: String, target: String, text: String): NodeSeq = {
-      if (href0 == null) return Text(text);
-      
-      val href = {
-        if (href0.startsWith("http:") || href0.startsWith("file:")) "";
-        else relative
-      } + Utility.escape(href0)
-      if ((target ne null) && target.indexOf('<') != -1) throw new Error(target)
-
-      val t0 = Text(text)
-      if (target ne null)
-        (<a href={href} target={target}>{t0}</a>);
-      else
-        (<a href={href}>{t0}</a>);
-    }
-
-    val encoding = Properties.encodingString
-    val generator = System.getProperty("doc.generator", "scaladoc (" + Properties.versionString + ")")
-    val header =
-      (<meta http-equiv="content-type" content={"text/html; charset=" + encoding}/>
-      <meta name="generator" content={generator}/>
-      <link rel="stylesheet" type="text/css" href={ relative + "style.css"}/>
-      <script type="text/javascript" src={relative + "script.js"}></script>);
-
-    def body0(hasBody: Boolean, nodes: NodeSeq): NodeSeq =
-      if (!hasBody) nodes else (<body onload="init()">{nodes}</body>);
-
-    val dtype = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">"
-
-    def page(title: String, body: NodeSeq, hasBody: Boolean): NodeSeq =
-      (<html>
-        <head><title>{Text(if (title eq null) "null title" else title)}</title>
-        {header}
-        </head>
-        {body0(hasBody, body)}
-      </html>)
-  } // UrlContext
-
-  def div0(title: String): NodeSeq =
-    (<div class="doctitle-larger">{Text(title)}</div>);
-
-  def merge[T](ts0: TreeSet[T], ts1: TreeSet[T]): TreeSet[T] = {
-    var ts = ts0
-    for (t <- ts1.toList) ts += t
-    ts
-  }
-
-  def merge[T,S <: Ordered[S]](ts0: ListMap[T,TreeSet[S]],
-                               ts1: ListMap[T,TreeSet[S]]): ListMap[T,TreeSet[S]] = {
-    var ts = ts0
-    for (t <- ts1.elements) {
-      if (!ts.contains(t._1))
-        ts = ts.update(t._1, new TreeSet[S]);
-      ts = ts.update(t._1, merge(ts(t._1), t._2))
-    }
-    ts
-  }
-  implicit def coerceIterable[T](list : Iterable[T]) = NodeWrapper(list.elements)
-  implicit def coerceIterator[T](list : Iterator[T]) = NodeWrapper(list)
-
-  case class NodeWrapper[T](list : Iterator[T]) {
-
-    def mkXML(begin: NodeSeq, separator: NodeSeq, end: NodeSeq)(f: T => NodeSeq): NodeSeq = {
-      var seq: NodeSeq = begin
-      val i = list
-      while (i.hasNext) {
-        seq = seq ++ f(i.next);
-        if (i.hasNext) seq = seq ++ separator;
-      }
-      seq ++ end
-    }
-
-    def mkXML(begin: String, separator: String, end: String)(f: T => NodeSeq): NodeSeq = {
-      this.mkXML(Text(begin),Text(separator),Text(end))(f);
-    }
-
-    def surround(open: String, close: String)(f: T => NodeSeq) =
-      if (list.hasNext) mkXML(open, ", ", close)(f)
-      else NodeSeq.Empty
-  }
-}
diff --git a/src/compiler/scala/tools/nsc/doc/ModelAdditions.scala b/src/compiler/scala/tools/nsc/doc/ModelAdditions.scala
deleted file mode 100644
index 64df484..0000000
--- a/src/compiler/scala/tools/nsc/doc/ModelAdditions.scala
+++ /dev/null
@@ -1,410 +0,0 @@
-/* NSC -- new Scala compiler
- * Copyright 2007-2009 LAMP/EPFL
- * @author  Sean McDirmid
- */
-// $Id: ModelAdditions.scala 16881 2009-01-09 16:28:11Z cunei $
-
-package scala.tools.nsc.doc
-
-/**
- *  @author Stephane Micheloud, Sean McDirmid, Geoffrey Washburn
- *  @version 1.0
- */
-class ModelAdditions(val global: Global) {
-  import global._
-  import definitions._
-  def addition(sym: global.Symbol) {}
-
-  addition(NothingClass);
-  comments(NothingClass) = """
-    <p>
-      Class <code>Nothing</code> is - together with class <a href="Null.html">
-      <code>Null</code></a> - at the bottom of the
-      <a href="http://scala-lang.org" target="_top">Scala</a> type
-      hierarchy.
-    </p>
-    <p>
-      Type <code>Nothing</code> is a subtype of every other type
-      (including <a href="Null.html"><code>Null</code></a>); there
-      exist <em>no instances</em> of this type. Even though type
-      <code>Nothing</code> is empty, it is nevertheless useful as a
-      type parameter. For instance, the <a href="http://scala-lang.org"
-      target="_top">Scala</a> library defines a value
-      <a href="Nil$object.html"><code>Nil</code></a> of type
-      <code><a href="List.html">List</a>[Nothing]</code>. Because lists
-      are covariant in <a href="http://scala-lang.org" target="_top">Scala</a>,
-      this makes <a href="Nil$object.html"><code>Nil</code></a> an
-      instance of <code><a href="List.html">List</a>[T]</code>, for
-      any element type <code>T</code>.
-    </p>"""
-
-   addition(NullClass);
-   comments(NullClass) = """
-     <p>
-       Class <code>Null</code> is - together with class <a href="Nothing.html">
-       <code>Nothing</code> - at the bottom of the
-       <a href="http://scala-lang.org" target="_top">Scala</a> type
-       hierarchy.
-     </p>
-     <p>
-       Type <code>Null</code> is a subtype of all reference types; its
-       only instance is the <code>null</code> reference.
-       Since <code>Null</code> is not a subtype of value types,
-       <code>null</code> is not a member of any such type. For instance,
-       it is not possible to assign <code>null</code> to a variable of
-       type <a href="Int.html"><code>Int</code></a>.
-     </p>"""
-
-   /*******************************************************************/
-   /* Documentation for Any */
-
-   addition(AnyClass);
-   comments(AnyClass) = """
-     <p>
-       Class <code>Any</code> is the root of the <a
-       href="http://scala-lang.org/"
-       target="_top">Scala</a> class hierarchy. Every class in a
-       <a href="http://scala-lang.org/" target="_top">Scala</a> execution
-       environment inherits directly or indirectly from this class.
-       Class <code>Any</code> has two direct subclasses:
-       <a href="AnyRef.html"><code>AnyRef</code></a> and
-       <a href="AnyVal.html"><code>AnyVal</code></a>.
-     </p>"""
-
-  addition(Any_equals);
-  comments(Any_equals) = """
-    This method is used to compare the receiver object (<code>this</code>)
-    with the argument object (<code>arg0</code>) for equivalence.  
-    
-    <p>
-    The default implementations of this method is an <a
-    href="http://en.wikipedia.org/wiki/Equivalence_relation">equivalence
-    relation</a>:
-      <ul>
-      <li>It is reflexive: for any instance <code>x</code> of type <code>Any</code>, 
-      <code>x.equals(x)</code> should return <code>true</code>.</li>
-      <li>It is symmetric: for any instances <code>x</code> and <code>y</code> of type 
-      <code>Any</code>, <code>x.equals(y)</code> should return <code>true</code> if and only 
-      if <code>y.equals(x)</code> returns <code>true</code>.</li>
-      <li>It is transitive: for any instances 
-      <code>x</code>, <code>y</code>, and <code>z</code> of type <code>AnyRef</code>
-      if <code>x.equals(y)</code> returns <code>true</code> and 
-      <code>y.equals(z)</code> returns 
-      <code>true</code>, then <code>x.equals(z)</code> should return <code>true</code>.</li>
-    </ul>
-    </p>
-
-    <p>
-    If you override this method, you should verify that
-    your implementation remains an equivalence relation.
-    Additionally, when overriding this method it is often necessary to
-    override <code>hashCode</code> to ensure that objects that are
-    "equal" (<code>o1.equals(o2)</code> returns <code>true</code>)
-    hash to the same <a href="Int.html"><code>Int</code></a>
-    (<code>o1.hashCode.equals(o2.hashCode)</code>).
-    
-    @param arg0 the object to compare against this object for equality.
-    @return <code>true</code> if the receiver object is equivalent to the argument; <code>false</code> otherwise.
-    </p>
-    """
-
-  addition(Any_==);
-  comments(Any_==) = """
-    <code>o == arg0</code> is the same as <code>o.equals(arg0)</code>.
-    <p>
-    @param arg0 the object to compare against this object for equality.
-    @return <code>true</code> if the receiver object is equivalent to the argument; <code>false</code> otherwise. 
-    </p>
-    """
-
-  addition(Any_!=);
-  comments(Any_!=) = """
-    <code>o != arg0</code> is the same as <code>!(o == (arg0))</code>.
-    <p>
-    @param arg0 the object to compare against this object for dis-equality.
-    @return <code>false</code> if the receiver object is equivalent to the argument; <code>true</code> otherwise.
-    </p>
-    """
-
-  addition(Any_toString);
-  comments(Any_toString) = """    
-    Returns a string representation of the object.  
-    <p>
-    The default representation is platform dependent.
-    
-    @return a string representation of the object. 
-    </p>
-    """
-
-  addition(Any_asInstanceOf);
-  comments(Any_asInstanceOf) = """
-    This method is used to cast the receiver object to be of type <code>T0</code>.  
-
-    <p>Note that the success of a cast at runtime is modulo Scala's
-    erasure semantics.  Therefore the expression
-    <code>1.asInstanceOf[String]</code> will throw a
-    <code>ClassCastException</code> at runtime, while the expression
-    <code>List(1).asInstanceOf[List[String]]</code> will not.  In the
-    latter example, because the type argument is erased as part of
-    compilation it is not possible to check whether the contents of
-    the list are of the requested typed.
-    
-    @throws ClassCastException if the receiver object is not an
-    instance of erasure of type <code>T0</code>.  
-    @return the receiver object.
-    </p> """
-
-  addition(Any_isInstanceOf);
-  comments(Any_isInstanceOf) = """
-    This method is used to test whether the dynamic type of the receiver object is <code>T0</code>.
-
-    <p>Note that the test result of the test is modulo Scala's erasure
-    semantics.  Therefore the expression
-    <code>1.isInstanceOf[String]</code> will return
-    <code>false</code>, while the expression
-    <code>List(1).isInstanceOf[List[String]]</code> will return
-    <code>true</code>.  In the latter example, because the type
-    argument is erased as part of compilation it is not possible to
-    check whether the contents of the list are of the requested typed.
-    
-    @return <code>true</code> if the receiver object is an
-    instance of erasure of type <code>T0</code>; <code>false</code> otherwise. 
-    """
-
-  addition(Any_hashCode);
-  comments(Any_hashCode) = """
-    Returns a hash code value for the object.  
-
-    <p>
-    The default hashing algorithm is platform dependent.  
-
-    Note that it is allowed for two objects to have identical hash
-    codes (<code>o1.hashCode.equals(o2.hashCode)</code>) yet not be
-    equal (<code>o1.equals(o2)</code> returns <code>false</code>).  A
-    degenerate implementation could always return <code>0</code>.
-    However, it is required that if two objects are equal
-    (<code>o1.equals(o2)</code> returns <code>true</code>) that they
-    have identical hash codes
-    (<code>o1.hashCode.equals(o2.hashCode)</code>).  Therefore, when
-    overriding this method, be sure to verify that the behavior is
-    consistent with the <code>equals</code> method.
-    </p>
-
-    <p>
-    @return the hash code value for the object.  
-    </p> """
-
-   /*******************************************************************/
-   /* Documentation for AnyRef */
-
-   addition(AnyRefClass);
-   comments(AnyRefClass) = """
-     <p>
-       Class <code>AnyRef</code> is the root class of all
-       <em>reference types</em>.
-     </p>"""
-
-  addition(Object_==);
-  comments(Object_==) = """
-    <code>o == arg0</code> is the same as <code>if (o eq null) arg0 eq null else o.equals(arg0)</code>.
-    <p>
-    @param arg0 the object to compare against this object for equality.
-    @return <code>true</code> if the receiver object is equivalent to the argument; <code>false</code> otherwise. 
-    </p>
-    """
-
-  addition(Object_ne);
-  comments(Object_ne) = """
-    <code>o.ne(arg0)</code> is the same as <code>!(o.eq(arg0))</code>.
-    <p>
-    @param arg0 the object to compare against this object for reference dis-equality.
-    @return <code>false</code> if the argument is not a reference to the receiver object; <code>true</code> otherwise.
-    </p>
-    """
-
-
-  addition(Object_finalize);
-  comments(Object_finalize) = """
-    This method is called by the garbage collector on the receiver object when garbage 
-    collection determines that there are no more references to the object. 
-    <p>
-    The details of when and if the <code>finalize</code> method are
-    invoked, as well as the interaction between <code>finalize</code>
-    and non-local returns and exceptions, are all platform dependent.
-    </p>
-    """
-
-  addition(Object_clone);
-  comments(Object_clone) = """
-    This method creates and returns a copy of the receiver object.
-
-    <p>
-    The default implementation of the <code>clone</code> method is platform dependent.
-
-    @return a copy of the receiver object.
-    </p>
-    """
-
-  addition(Object_getClass);
-  comments(Object_getClass) = """
-    Returns a representation that corresponds to the dynamic class of the receiver object.
-
-    <p>
-    The nature of the representation is platform dependent.
-
-    @return a representation that corresponds to the dynamic class of the receiver object.
-    </p>
-    """
-
-  addition(Object_notify);
-  comments(Object_notify) = """
-    Wakes up a single thread that is waiting on the receiver object's monitor. 
-    """
-
-  addition(Object_notifyAll);
-  comments(Object_notifyAll) = """
-    Wakes up all threads that are waiting on the receiver object's monitor. 
-    """
-
-  addition(Object_eq);
-  comments(Object_eq) = """
-    This method is used to test whether the argument (<code>arg0</code>) is a reference to the 
-    receiver object (<code>this</code>).
-    
-    <p>
-   The <code>eq</code> method implements an
-   <a href="http://en.wikipedia.org/wiki/Equivalence_relation">equivalence relation</a> on non-null instances of
-   <code>AnyRef</code>:
-    <ul>
-    <li>It is reflexive: for any non-null instance <code>x</code> of type <code>AnyRef</code>, 
-    <code>x.eq(x)</code> returns <code>true</code>.</li>
-    <li>It is symmetric: for any non-null instances <code>x</code> and <code>y</code> of type 
-    <code>AnyRef</code>, <code>x.eq(y)</code> returns <code>true</code> if and only 
-    if <code>y.eq(x)</code> returns <code>true</code>.</li>
-    <li>It is transitive: for any non-null instances 
-   <code>x</code>, <code>y</code>, and <code>z</code> of type <code>AnyRef</code>
-   if <code>x.eq(y)</code> returns <code>true</code> and 
-   <code>y.eq(z)</code> returns 
-   <code>true</code>, then <code>x.eq(z)</code> returns <code>true</code>.</li>
-   </ul>
-   Additionally, the <code>eq</code> method has three other properties.
-   <ul>
-     <li>It is consistent: for any non-null instances <code>x</code> and <code>y</code> of type <code>AnyRef</code>, 
-       multiple invocations of <code>x.eq(y)</code> consistently returns <code>true</code> 
-       or consistently returns <code>false</code>.</li>
-     <li>For any non-null instance <code>x</code> of type <code>AnyRef</code>, 
-      <code>x.eq(null)</code> and <code>null.eq(x)</code> returns <code>false</code>.</li>
-     <li><code>null.eq(null)</code> returns <code>true</code>.</li>
-   </ul>
-   </p>
-
-    <p> When overriding the <code>equals</code> or
-    <code>hashCode</code> methods, it is important to ensure that
-    their behavior is consistent with reference equality.  Therefore,
-    if two objects are references to each other (<code>o1 eq
-    o2</code>), they should be equal to each other (<code>o1 ==
-    o2</code>) and they should hash to the same value
-    (<code>o1.hashCode == o2.hashCode</code>).</p>
-    
-    @param arg0 the object to compare against this object for reference equality.
-    @return <code>true</code> if the argument is a reference to the receiver object; <code>false</code> otherwise.
-    </p>
-    """
-
-   /*******************************************************************/
-
-   addition(AnyValClass);
-   comments(AnyValClass) = """
-     <p>
-       Class <code>AnyVal</code> is the root class of all
-       <em>value types</em>.
-     </p>
-     <p>
-       <code>AnyVal</code> has a fixed number subclasses, which
-       describe values which are not implemented as objects in the
-       underlying host system.
-     </p>
-     <p>
-       Classes <a href="Double.html"><code>Double</code></a>,
-       <a href="Float.html"><code>Float</code></a>,
-       <a href="Long.html"><code>Long</code></a>,
-       <a href="Int.html"><code>Int</code></a>,
-       <a href="Char.html"><code>Char</code></a>,
-       <a href="Short.html"><code>Short</code></a>, and
-       <a href="Byte.html"><code>Byte</code></a> are together called
-       <em>numeric value types</em>.
-       Classes <a href="Byte.html"><code>Byte</code></a>,
-       <a href="Short.html"><code>Short</code></a>, or
-       <a href="Char.html"><code>Char</code></a>
-       are called <em>subrange types</em>. Subrange types, as well as
-       <a href="Int.html"><code>Int</code></a> and
-       <a href="Long.html"><code>Long</code></a> are called
-       <em>integer types</em>, whereas
-       <a href="Float.html"><code>Float</code></a> and
-       <a href="Double.html"><code>Double</code></a> are called
-       <em>floating point types</em>.
-     </p>"""
-
-   addition(BooleanClass)
-   comments(BooleanClass) = """
-    <p>
-      Class <code>Boolean</code> has only two values: <code>true</code>
-      and <code>false</code>.
-    </p>"""
-
-   def numericValDescr(sym: Symbol) = {
-     val maxValue = "MAX_" + sym.name.toString().toUpperCase()
-     val minValue = "MIN_" + sym.name.toString().toUpperCase()
-     addition(sym)
-     comments(sym) = """
-       <p>
-         Class <code>""" + sym.name + """</code> belongs to the value
-         classes whose instances are not represented as objects by the
-         underlying host system.  There is an implicit conversion from
-         instances of <code>""" + sym.name + """</code> to instances of
-         <a href="runtime/Rich""" + sym.name + """.html"><code>runtime.Rich""" + sym.name + """</code></a> which
-         provides useful non-primitive operations.  All value classes inherit 
-         from class <a href="AnyVal.html"><code>AnyVal</code></a>.
-       </p>
-       <p>
-         Values <code>""" + maxValue + """</code> and <code>""" + minValue + """</code>
-         are in defined in object <a href="Math$object.html">scala.Math</a>.
-       </p>"""
-   }
-   (ByteClass :: CharClass :: DoubleClass :: LongClass :: 
-    FloatClass :: IntClass :: ShortClass :: Nil).foreach(numericValDescr);
-
-   addition(UnitClass);
-   comments(UnitClass) = """
-     <p>
-       Class <code>Unit</code> has only one value: <code>()</code>.
-     </p>"""
-
-   addition(UnitClass);
-/*
-   def boxedValDescr(what: String) = {
-     val sym = definitions.getClass("java.lang." + what)
-     addition(sym)
-     comments(sym) = """
-       <p>
-         Class <code>""" + sym.name + """</code> implements the
-         boxing/unboxing from/to value types.
-       </p>
-       <p>
-         Boxing and unboxing enable value types to be treated as objects;
-         they provide a unified view of the type system wherein a value
-         of any type can ultimately be treated as an object.
-       </p>"""
-   };
-   //("Float" :: "Long" :: "Number" :: "Integer" :: Nil).foreach(boxedValDescr);
-*/
-   object exceptions extends collection.jcl.TreeMap[String,(Symbol,String)] {
-     def f(name: String) {
-       this("Predef." + name) = (definitions.PredefModule, name)
-     }
-     f("IndexOutOfBoundsException")
-     f("NoSuchElementException")
-     f("NullPointerException")
-     f("UnsupportedOperationException")
-   }
-}
diff --git a/src/compiler/scala/tools/nsc/doc/ModelExtractor.scala b/src/compiler/scala/tools/nsc/doc/ModelExtractor.scala
deleted file mode 100644
index 36438a6..0000000
--- a/src/compiler/scala/tools/nsc/doc/ModelExtractor.scala
+++ /dev/null
@@ -1,449 +0,0 @@
-/* NSC -- new Scala compiler
- * Copyright 2007-2009 LAMP/EPFL
- * @author  Sean McDirmid
- */
-// $Id: ModelExtractor.scala 16881 2009-01-09 16:28:11Z cunei $
-
-package scala.tools.nsc.doc
-
-import scala.collection.jcl
-import compat.Platform.{EOL => LINE_SEPARATOR}
-
-
-/** This class attempts to reverse engineer source code intent from compiler
- *  symbol objects.
- *
- * @author Sean McDirmid
- */
-trait ModelExtractor {
-  val global: Global
-  import global._
-  def settings: doc.Settings
- 
-  def assert(b: Boolean) {
-    if (!b) throw new Error
-  }
-
-  def assert(b: Boolean, message: Any) {
-    if (!b) throw new Error(message.toString)
-  }
-
-  case class Tag(tag: String, option: String, body: String)
-
-  case class Comment(body: String, attributes: List[Tag]) {
-    def decodeAttributes = {
-      val map = new jcl.LinkedHashMap[String, List[(String, String)]] {
-        override def default(key: String) = Nil
-      }
-      attributes.foreach(a => {
-        map(a.tag) = map(a.tag) ::: List((a.option, a.body))
-      });
-      map
-    }
-  }
-  protected def decode(sym: Symbol) =
-    if (sym == definitions.ScalaObjectClass || sym == definitions.ObjectClass) 
-      definitions.AnyRefClass
-    else sym match {
-      case sym: ModuleClassSymbol => sym.sourceModule
-      case sym => sym
-    }
-
-  protected def decodeComment(comment0: String): Comment = {
-    val comment = comment0 // .substring("/**".length, comment0.length - "*/".length)
-    val tok = new java.util.StringTokenizer(comment, LINE_SEPARATOR)
-    val buf = new StringBuilder
-    type AttrDescr = (String, String, StringBuilder)
-    val attributes = new collection.mutable.ListBuffer[AttrDescr]
-    var attr: AttrDescr = null
-    while (tok.hasMoreTokens) {
-      val s = tok.nextToken.replaceFirst("\\p{Space}?\\*", "")
-      val mat1 = pat1.matcher(s)
-      if (mat1.matches) {
-        attr = (mat1.group(1), null, new StringBuilder(mat1.group(2)))
-        //if (kind != CONSTRUCTOR) 
-        attributes += attr
-      } else {
-        val mat2 = pat2.matcher(s)
-        if (mat2.matches) {
-          attr = (mat2.group(1), mat2.group(2), new StringBuilder(mat2.group(3)))
-          //if (kind != CLASS) 
-          attributes += attr
-        } else if (attr ne null)
-          attr._3.append(s + LINE_SEPARATOR)
-        else
-          buf.append(s + LINE_SEPARATOR)
-      }
-    }
-    Comment(buf.toString, attributes.toList.map({x => Tag(x._1,x._2,x._3.toString)}))
-  }
-
-  sealed abstract class Entity(val sym: Symbol) {
-    private[ModelExtractor] def sym0 = sym
-    
-    override def toString = sym.toString
-    def comment: Option[String] = global.comments.get(sym)
-    // comments decoded, now what?
-    def attributes = sym.attributes
-    def decodeComment: Option[Comment] = {
-      val comment0 = this.comment
-      if (comment0.isEmpty) None
-      else Some(ModelExtractor.this.decodeComment(comment0.get.trim))
-    }
-    protected def accessQualified(core: String, qual: String) = core match {
-      case "public" => "" // assert(qual == null); "";
-      case core => core + (if (qual == null) "" else "[" + qual + "]")
-    }
-    
-    def flagsString = {
-      import symtab.Flags
-      //val isLocal = sym.hasFlag(Flags.LOCAL)
-      val x =
-        if (sym hasFlag Flags.PRIVATE) "private"
-        else if (sym hasFlag Flags.PROTECTED) "protected"
-        else "public"
-      var string = accessQualified(x,
-        if (sym hasFlag Flags.LOCAL) "this"
-        else if (sym.privateWithin != null && sym.privateWithin != NoSymbol)
-          sym.privateWithin.nameString
-        else null
-      )
-      def f(flag: Int, str: String) {
-        if (sym hasFlag flag) string = string + " " + str
-      }
-      f(Flags.IMPLICIT, "implicit")
-      f(Flags.SEALED, "sealed")
-      f(Flags.OVERRIDE, "override")
-      f(Flags.CASE, "case")
-      if (!sym.isTrait) f(Flags.ABSTRACT, "abstract")
-      if (!sym.isModule) f(Flags.FINAL, "final")
-      if (!sym.isTrait) f(Flags.DEFERRED, "abstract")
-      string.trim
-    }
-    def listName = name
-    def name = sym.nameString
-    def fullName(sep: Char) = sym.fullNameString(sep)
-    def kind: String
-    def header { }
-    def typeParams: List[TypeParam] = Nil
-    def valueParams: List[List[ValueParam]] = Nil
-    def resultType: Option[Type] = None
-    def parents: Iterable[Type] = Nil
-    def lo: Option[Type] = sym.info match {
-      case TypeBounds(lo, hi) if decode(lo.typeSymbol) != definitions.NothingClass => Some(lo)
-      case _ => None
-    }
-    def hi: Option[Type] = sym.info match {
-      case TypeBounds(lo, hi) if decode(hi.typeSymbol) != definitions.AnyClass => Some(hi)
-      case _ => None
-    }
-    def variance = {
-      import symtab.Flags._
-      if (sym hasFlag COVARIANT) "+"
-      else if (sym hasFlag CONTRAVARIANT) "-"
-      else ""
-    }
-    def overridden: Iterable[Symbol] = Nil
-  }
-
-  class ValueParam(sym: Symbol) extends Entity(sym) {
-    override def resultType = Some(sym.tpe)
-    //def kind = if (sym.isPublic) "val" else "";
-    def kind = ""
-  }
-
-  class ConstructorParam(sym: Symbol) extends ValueParam(sym) {
-    override protected def accessQualified(core: String, qual: String) = core match {
-      case "public" => "val"
-      case "protected" => super.accessQualified(core,qual) + " val"
-      case "private" if qual == "this" => ""
-      case core => super.accessQualified(core, qual)
-    }
-  }
-
-  def ValueParam(sym: Symbol) = new ValueParam(sym)
-  class TypeParam(sym: Symbol) extends Entity(sym) {
-    def kind = ""
-  }
-  def TypeParam(sym: Symbol) = new TypeParam(sym)
-  
-  trait Clazz extends ClassOrObject {
-    private def csym = sym.asInstanceOf[TypeSymbol]
-    override def typeParams = csym.typeParams.map(TypeParam)
-    override def valueParams = {
-      if (constructorArgs.isEmpty) Nil
-      else constructorArgs.values.toList :: Nil
-    }
-    def isTrait = csym.isTrait
-    override def kind = if (sym.isTrait) "trait" else "class"
-  }
-
-  trait Object extends ClassOrObject {
-    override def kind = "object"
-  }
-
-  case class Package(override val sym: Symbol) extends Entity(sym) {
-    override def kind = "package"
-    override def name = fullName('.')
-  }
-
-  trait TopLevel extends ClassOrObject
-  class TopLevelClass (sym: Symbol) extends Entity(sym) with TopLevel with Clazz
-  class TopLevelObject(sym: Symbol) extends Entity(sym) with TopLevel with Object {
-    override def attributes = sym.moduleClass.attributes
-  }
-
-  def compare(pathA: List[ClassOrObject], pathB: List[ClassOrObject]): Int = {
-    var pA = pathA
-    var pB = pathB
-    while (true) {
-      if (pA.isEmpty) return -1
-      if (pB.isEmpty) return +1
-      val diff = pA.head.name compare pB.head.name
-      if (diff != 0) return diff
-      pA = pA.tail
-      pB = pB.tail
-    }
-    0
-  }
-
-  def isAccessible(sym: Symbol): Boolean = {
-    import symtab.Flags._
-    settings.memberaccess.value match {
-      case "private"   => sym.isPublic || (sym hasFlag PROTECTED) || (sym hasFlag PRIVATE)
-      case "protected" => sym.isPublic || (sym hasFlag PROTECTED)
-      case "public"    => sym.isPublic
-      case _           => false
-    }
-  }
-
-  trait ClassOrObject extends Entity {
-    def path: List[ClassOrObject] = this :: Nil
-    override def listName = path map (_.name) mkString "."
-
-    object freshParents extends jcl.LinkedHashSet[Type] {
-      this addAll sym.tpe.parents
-      this.toList foreach (this removeAll _.parents)
-    }
-    object constructorArgs extends jcl.LinkedHashMap[Symbol, ValueParam] {
-      import symtab.Flags._
-      sym.constrParamAccessors.filter(arg => ! (arg hasFlag SYNTHETIC)).foreach(arg => {
-        val str = flagsToString(arg.flags)
-        assert((arg hasFlag PRIVATE) && (arg hasFlag LOCAL), arg)
-        val argName = arg.name.toString.trim
-        val actual = sym.tpe.decls.elements.find(e => {
-          val eName = e.name.toString.trim;
-          argName == eName && {
-            val str = flagsToString(e.flags);
-            !e.hasFlag(LOCAL);
-          }
-        });
-        val param = actual getOrElse arg
-        this(param) = new ConstructorParam(param)
-      });
-    }
-    object decls extends jcl.LinkedHashMap[Symbol, Member] {
-      sym.tpe.decls.elements.foreach(e => {
-        if (!constructorArgs.contains(e)) {
-          val m = Member(e)
-          if (!m.isEmpty && !this.contains(e)) this.put(e, m.get)
-        }
-      });
-    }
-    def members0(f: Symbol => Boolean) = decls.projection.filterKeys(f).valueSet
-    def members(c: Category): Iterable[Member] = members0(c.f)
-    object inherited extends jcl.LinkedHashMap[Symbol, List[Member]]() {
-      override def default(tpe: Symbol) = Nil
-      for (m <- sym.tpe.members if !sym.tpe.decls.elements.contains(m) && 
-          (Values.f(m) || Methods.f(m))) {
-        val o = m.overridingSymbol(sym)
-        if (o == NoSymbol) {
-          val parent = decode(m.enclClass)
-          val mo = Member(m)
-          if (!mo.isEmpty) {
-            this(parent) = mo.get :: this(parent)
-          }
-        }
-      }
-    }
-    override def parents = freshParents
-    abstract class Member(sym: Symbol) extends Entity(sym) {
-      private def overriding = sym.allOverriddenSymbols
-      override def comment = super.comment match {
-      case ret @ Some(comment) =>
-        ret
-      case None =>
-        val o = overriding.find(comments.contains)
-        o.map(comments.apply)
-      }
-    }
-    abstract class ValDef(sym: Symbol) extends Member(sym) {
-      override def resultType = Some(resultType0)
-      protected def resultType0: Type
-      override def overridden: Iterable[Symbol] = {
-        var ret: jcl.LinkedHashSet[Symbol] = null
-        for (parent <- ClassOrObject.this.parents) {
-          val sym0 = sym.overriddenSymbol(parent.typeSymbol)
-          if (sym0 != NoSymbol) {
-            if (ret == null) ret = new jcl.LinkedHashSet[Symbol];
-            ret += sym0
-          }
-        }
-        if (ret == null) Nil else ret.readOnly
-      }
-    }
-    case class Def(override val sym : TermSymbol) extends ValDef(sym) {
-      override def resultType0 = sym.tpe.finalResultType
-      override def typeParams = sym.tpe.typeParams.map(TypeParam)
-      override def valueParams = methodArgumentNames.get(sym) match {
-        case Some(argss) if argss.length > 1 || (!argss.isEmpty && !argss(0).isEmpty) => 
-          argss map (_.map(ValueParam))
-        case _ => 
-          var i = 0
-          val ret = for (tpe <- sym.tpe.paramTypes) yield {
-            val ret = sym.newValueParameter(sym.pos, newTermName("arg" + i));
-            ret setInfo tpe
-            i += 1
-            ValueParam(ret)
-          }
-          if (ret.isEmpty) Nil
-          else ret :: Nil
-      }
-      override def kind = "def"
-    }
-    case class Val(override val sym: TermSymbol) extends ValDef(sym) {
-      import symtab.Flags._
-      def resultType0: Type = sym.tpe
-      override def kind: String =
-        if (sym hasFlag ACCESSOR) {
-          val setterName = nme.getterToSetter(sym.name)
-          val setter = sym.owner.info.decl(setterName)
-          val lazyMod = if (sym hasFlag LAZY) "lazy " else ""
-          lazyMod + (if (setter == NoSymbol) "val" else "var")
-        } else {
-          assert(sym hasFlag JAVA)
-          if (sym hasFlag FINAL) "val" else "var"
-        }
-    }
-
-    case class AbstractType(override val sym: Symbol) extends Member(sym) {
-      override def kind = "type"
-    }
-
-    abstract class NestedClassOrObject(override val sym: Symbol) extends Member(sym) with ClassOrObject {
-      override def path: List[ClassOrObject] = ClassOrObject.this.path ::: super.path
-    }
-
-    case class NestedClass(override val sym: ClassSymbol) extends NestedClassOrObject(sym) with Clazz
-
-    case class NestedObject(override val sym: ModuleSymbol) extends NestedClassOrObject(sym) with Object {
-      override def attributes = sym.moduleClass.attributes
-    }
-
-    def isVisible(sym: Symbol): Boolean = {
-      import symtab.Flags._
-      if (sym.isLocalClass) return false
-      if (sym.isLocal) return false
-      if (sym.isPrivateLocal) return false
-      if (sym hasFlag PRIVATE) return !inIDE //false
-      if (sym hasFlag SYNTHETIC) return false
-      if (sym hasFlag BRIDGE) return false
-      if ((sym.nameString indexOf "$") != -1) return false
-      if ((sym hasFlag CASE) && sym.isMethod) return false
-      true
-    }
-
-    def Member(sym: Symbol): Option[Member] = {
-      import global._
-      import symtab.Flags
-      if (!isVisible(sym))
-        None
-      else if (!isAccessible(sym))
-        None
-      else if (sym hasFlag Flags.ACCESSOR) {
-        if (sym.isSetter) return None;
-        assert(sym.isGetter);
-        Some[Member](new Val(sym.asInstanceOf[TermSymbol]))
-      }
-      else if (sym.isValue && !sym.isMethod && !sym.isModule) {
-        if (!sym.hasFlag(Flags.JAVA)) {
-          Console.println("SYM: " + sym + " " + sym.fullNameString('.'))
-          Console.println("FLA: " + Flags.flagsToString(sym.flags))
-        }
-        assert(sym hasFlag Flags.JAVA)
-        Some[Member](new Val(sym.asInstanceOf[TermSymbol]))
-      }
-      else if (sym.isValue && !sym.isModule) {
-        val str = Flags.flagsToString(sym.flags)
-        assert(sym.isMethod)
-        Some[Member](new Def(sym.asInstanceOf[TermSymbol]))
-      }
-      else if (sym.isAliasType || sym.isAbstractType)
-        Some(new AbstractType(sym))
-      else if (sym.isClass)
-        Some(new NestedClass(sym.asInstanceOf[ClassSymbol]))
-      else if (sym.isModule)
-        Some(new NestedObject(sym.asInstanceOf[ModuleSymbol]))
-      else
-        None
-    }
-    
-  }
-  case class Category(label: String)(g: Symbol => Boolean) {
-    val f = g
-    def plural = label + "s"
-  }
-  val Constructors = new Category("Additional Constructor")(e => e.isConstructor && !e.isPrimaryConstructor) {
-    // override def plural = "Additional Constructors";
-  }
-  val Objects = Category("Object")(_.isModule);
-  val Classes = new Category("Class")(sym => sym.isClass || (sym == definitions.AnyRefClass)) {
-    override def plural = "Classes"
-  }
-  val Values = new Category("Value")(e => e.isValue && e.hasFlag(symtab.Flags.ACCESSOR)) {
-    override def plural = "Values and Variables"
-  }
-  val Methods = Category("Method")(e => e.isValue && e.isMethod && !e.isConstructor && !e.hasFlag(symtab.Flags.ACCESSOR));
-  val Types = Category("Type")(e => e.isAliasType || e.isAbstractType); 
-  
-  val categories = Constructors :: Types :: Values :: Methods :: Classes :: Objects :: Nil;
-
-  
-  import java.util.regex.Pattern
-  // patterns for standard tags with 1 and 2 arguments
-  private val pat1 = Pattern.compile(
-    "[ \t]*@(author|deprecated|pre|return|see|since|todo|version|ex|note)[ \t]*(.*)")
-  private val pat2 = Pattern.compile(  
-    "[ \t]*@(exception|param|throws)[ \t]+(\\p{Graph}*)[ \t]*(.*)")
-
-  def sort[E <: Entity](entities: Iterable[E]): Iterable[E] = {
-    val set = new jcl.TreeSet[E]()({eA: E => new Ordered[E] {
-      def compare(eB: E): Int = {
-        if (eA eq eB) return 0;
-        (eA, eB) match {
-          case (eA: ClassOrObject, eB: ClassOrObject) => 
-            val diff = ModelExtractor.this.compare(eA.path, eB.path)
-            if (diff!= 0) return diff
-          case _ => 
-        }
-        if (eA.getClass != eB.getClass) {
-          val diff = eA.getClass.getName.compare(eB.getClass.getName)
-          assert(diff != 0)
-          return diff
-        }
-        if (!eA.sym0.isPackage) {
-          val diff = eA.sym0.nameString compare eB.sym0.nameString
-          if (diff != 0) return diff
-        } 
-        val diff0 = eA.sym0.fullNameString compare eB.sym0.fullNameString
-        assert(diff0 != 0)
-        diff0
-      }
-      override def equals(other: Any) : Boolean = 
-        eA.equals(other) || (other match { case that: AnyRef => this.eq(that) 
-                                           case _ => false })
-    }})
-    set addAll entities;
-    set
-  }
-}
diff --git a/src/compiler/scala/tools/nsc/doc/ModelFrames.scala b/src/compiler/scala/tools/nsc/doc/ModelFrames.scala
deleted file mode 100644
index 52e0c89..0000000
--- a/src/compiler/scala/tools/nsc/doc/ModelFrames.scala
+++ /dev/null
@@ -1,395 +0,0 @@
-/* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
- * @author  Sean McDirmid
- */
-// $Id: ModelFrames.scala 16894 2009-01-13 13:09:41Z cunei $
-
-package scala.tools.nsc.doc
-
-import java.io.{File, FileWriter}
-import util.NameTransformer
-import scala.collection.jcl
-import scala.compat.Platform.{EOL => LINE_SEPARATOR}
-import scala.xml.{NodeSeq, Text, Unparsed, Utility}
-
-/** This class provides HTML document framing functionality. 
-  *
-  *  @author  Sean McDirmid, Stephane Micheloud
-  */
-trait ModelFrames extends ModelExtractor {    
-  import DocUtil._ 
-  def settings: doc.Settings
-  import global.definitions.{AnyClass, AnyRefClass}
-
-  val SyntheticClasses = new scala.collection.mutable.HashSet[global.Symbol];
-  {
-    import global.definitions._
-    global.definitions.init
-    SyntheticClasses ++= List(
-      NothingClass, NullClass, AnyClass, AnyRefClass, AnyValClass,
-      //value classes
-      BooleanClass, ByteClass, CharClass, IntClass, LongClass, ShortClass, UnitClass)
-
-    if (!global.forCLDC)
-      SyntheticClasses ++= List(FloatClass, DoubleClass)
-  }
-
-  val outdir      = settings.outdir.value
-  val windowTitle = settings.windowtitle.value
-  val docTitle    = load(settings.doctitle.value)
-
-  val stylesheetSetting = settings.stylesheetfile
-
-  def pageHeader  = load(settings.pageheader.value)
-  def pageFooter  = load(settings.pagefooter.value)
-  def pageTop     = load(settings.pagetop.value)
-  def pageBottom  = load(settings.pagebottom.value)
-
-  def contentFrame = "contentFrame"
-  def classesFrame = "classesFrame"
-  def modulesFrame = "modulesFrame"
-
-  protected val FILE_EXTENSION_HTML = ".html"
-  protected val NAME_SUFFIX_OBJECT  = "$object"
-  protected val NAME_SUFFIX_PACKAGE = "$package"
-
-  def rootTitle = (<div class="page-title">{docTitle}</div>);
-  def rootDesc =
-    (<p>{load("This document is the API specification for " + windowTitle)}</p>);
-
-  final def hasLink(sym: global.Symbol): Boolean =
-    if (sym == global.NoSymbol) false
-    else if (hasLink0(sym)) true
-    else hasLink(decode(sym.owner))
-
-  def hasLink0(sym: global.Symbol): Boolean = true
-  
-  abstract class Frame extends UrlContext {
-    { // just save.
-      save(page(title, body, hasBody));
-    }
-    def path: String // relative to outdir
-    def relative: String = {
-      if (path eq null) return "foo"
-      assert(path ne null)
-      var idx = 0
-      var ct = new StringBuilder
-      while (idx != -1) {
-        idx = path.indexOf('/', idx)
-        //System.err.println(path + " idx=" + idx)
-        ct.append(if (idx != -1) "../" else "")
-        idx += (if (idx == -1) 0 else 1)
-      }
-      ct.toString
-    }
-    def save(nodes: NodeSeq) = {
-      val path = this.path
-      if (path.startsWith("http://")) throw new Error("frame: " + this)
-      val path0 = outdir + File.separator + path + FILE_EXTENSION_HTML
-      //if (settings.debug.value) inform("Writing XML nodes to " + path0)
-      val file = new File(path0)
-      val parent = file.getParentFile()
-      if (!parent.exists()) parent.mkdirs()
-      val writer = new FileWriter(file)
-      val str = dtype + LINE_SEPARATOR + nodes.toString()
-      writer.write(str, 0, str.length())
-      writer.close()
-    }
-    protected def body: NodeSeq
-    protected def title: String
-    protected def hasBody = true
-
-    //def urlFor(entity: Entity, target: String): NodeSeq
-    def urlFor(entity: Entity): String = {
-      val ret = this.urlFor(entity.sym)
-      assert(ret != null);
-      ret
-    }
-    def link(entity: Entity, target: String) = aref(urlFor(entity), target, entity.name)
-    protected def shortHeader(entity: Entity): NodeSeq
-    protected def  longHeader(entity: Entity): NodeSeq
-    import global._
-    import symtab.Flags
-
-    def urlFor(sym: Symbol): String = sym match {
-      case psym : ModuleSymbol if psym.isPackage =>
-        urlFor0(sym, sym) + FILE_EXTENSION_HTML
-      case sym if !hasLink(sym) =>
-        null
-      case sym if sym == AnyRefClass =>
-        urlFor0(sym, sym) + FILE_EXTENSION_HTML
-      case msym: ModuleSymbol =>
-        urlFor0(sym, sym) + FILE_EXTENSION_HTML
-      case csym: ClassSymbol =>
-        urlFor0(sym, sym) + FILE_EXTENSION_HTML
-      case _ =>
-        val cnt = urlFor(decode(sym.owner))
-        if (cnt == null) null else cnt + "#" + docName(sym)
-    }
-
-    def docName(sym: Symbol): String = {
-      def javaParams(paramTypes: List[Type]): String = {
-        def javaName(pt: Type): String = {
-          val s = pt.toString
-          val matVal = patVal.matcher(s)
-          if (matVal.matches) matVal.group(1).toLowerCase
-          else s.replaceAll("\\$", ".")
-        }
-        paramTypes.map(pt => javaName(pt)).mkString("(", ",", ")")
-      }
-      def scalaParams(paramTypes: List[Type]): String = {
-        def scalaName(pt: Type): String = pt.toString.replaceAll(" ", "")
-        paramTypes.map(pt => scalaName(pt)).mkString("(", ",", ")")
-      }
-      java.net.URLEncoder.encode(sym.nameString +
-        (sym.tpe match {
-          case MethodType(paramTypes, _) =>
-            if (sym hasFlag Flags.JAVA) javaParams(paramTypes)
-            else scalaParams(paramTypes)
-          case PolyType(_, MethodType(paramTypes, _)) =>
-            if (sym hasFlag Flags.JAVA) javaParams(paramTypes)
-            else scalaParams(paramTypes)
-          case _ => ""
-        }), encoding)
-    }
-    
-    def urlFor0(sym: Symbol, orig: Symbol): String =
-      (if (sym == NoSymbol) "XXX"
-       else if (sym.owner.isPackageClass) rootFor(sym) + pkgPath(sym)
-       else urlFor0(decode(sym.owner), orig) + "." + NameTransformer.encode(Utility.escape(sym.nameString))
-      ) +
-      (sym match {
-        case msym: ModuleSymbol =>
-          if (msym hasFlag Flags.PACKAGE) NAME_SUFFIX_PACKAGE
-          else NAME_SUFFIX_OBJECT
-        case csym: ClassSymbol if csym.isModuleClass =>
-          if (csym hasFlag Flags.PACKAGE) NAME_SUFFIX_PACKAGE
-          else NAME_SUFFIX_OBJECT
-        case _ =>
-          ""
-      })
-  }
-  def pkgPath(sym : global.Symbol) = sym.fullNameString('/') match {
-    case "<empty>" => "_empty_"
-    case path => path
-  }
-  
-  protected def rootFor(sym: global.Symbol) = ""
-
-  abstract class AllPackagesFrame extends Frame {
-    override lazy val path  = "modules"
-    override lazy val title = "List of all packages"
-    def packages: Iterable[Package]
-    override def body: NodeSeq =
-      (<div>
-        <div class="doctitle-larger">{windowTitle}</div>
-        <a href="all-classes.html" target={classesFrame} onclick="resetKind();">{"All objects and classes"}</a>
-      </div>
-      <div class="kinds">Packages</div>
-      <ul class="list">{sort(packages).mkXML("","\n","")(pkg => {
-        (<li><a href={urlFor(pkg)} target={classesFrame} onclick="resetKind();">
-          {pkg.fullName('.')}</a></li>)
-      })}
-      </ul>);
-  }
-  abstract class PackagesContentFrame extends Frame {
-    lazy val path  = "root-content"
-    lazy val title = "All Packages"
-    def packages : Iterable[Package]
-    //def modules: TreeMap[String, ModuleClassSymbol]
-    def body: NodeSeq =
-      {rootTitle} ++ {rootDesc} ++ (<hr/>) ++
-      (<table cellpadding="3" class="member" summary="">
-        <tr><td colspan="2" class="title">Package Summary</td></tr> 
-        {sort(packages).mkXML("","\n","")(pkg => (<tr><td class="signature">
-          <code>package
-          {aref(pkgPath(pkg.sym) + "$content.html", "_self", pkg.fullName('.'))}
-          </code>
-        </td></tr>))}
-      </table>);
-  }
-
-  val classFrameKinds = Classes :: Objects :: Nil;
-  abstract class ListClassFrame extends Frame {
-    def classes: Iterable[ClassOrObject]
-    def navLabel: String
-    private def navPath = {
-      val p = path;
-      (if (p endsWith NAME_SUFFIX_PACKAGE)
-        p.substring(0, p.length() - NAME_SUFFIX_PACKAGE.length());
-      else p) + navSuffix;
-    }
-    protected def navSuffix = "$content.html"
-    
-    def body: NodeSeq = {
-      val nav = if (navLabel == null) NodeSeq.Empty else
-        (<table class="navigation" summary="">
-          <tr><td valign="top" class="navigation-links">
-            {aref(navPath, contentFrame, navLabel)}
-          </td></tr>
-        </table>);
-      val ids = new jcl.LinkedHashSet[String]
-      def idFor(kind: Category, t: Entity)(seq : NodeSeq): NodeSeq = {
-        val ch = t.listName.charAt(0);
-        val id = kind.plural + "_" + ch;
-        if (ids contains id) (<li>{seq}</li>);
-        else { 
-          ids += id; 
-          (<li id={id}>{seq}</li>)
-        };
-      }
-      val body = (<div>{classFrameKinds.mkXML("","\n","")(kind => {
-        val classes = sort(this.classes.filter(e => kind.f(e.sym)));
-        if (classes.isEmpty) NodeSeq.Empty; else
-        (<div id={kind.plural} class="kinds">{Text(kind.plural)}</div>
-        <ul class="list">
-        {classes.mkXML("","\n","")(cls => {
-          idFor(kind, cls)(
-            aref(urlFor(cls), contentFrame, cls.listName) ++ optional(cls)
-          );
-        })}
-        </ul>);
-      })}</div>);
-      nav ++ body
-    }
-    def optional(cls: ClassOrObject): NodeSeq = NodeSeq.Empty
-  }
-
-  abstract class PackageContentFrame extends Frame {
-    override def path = pkgPath(pkg.sym) + "$content"
-    override def title = "All classes and objects in " + pkg.fullName('.')
-    protected def pkg: Package
-    protected def classes: Iterable[ClassOrObject]
-    def body: NodeSeq =
-      {rootTitle} ++ {rootDesc} ++ {classFrameKinds.mkXML("","\n","")(kind => {
-        val classes = sort(this.classes.filter(e => kind.f(e.sym) && e.isInstanceOf[TopLevel]));
-        if (classes.isEmpty) NodeSeq.Empty else
-        (<table cellpadding="3" class="member" summary="">
-        <tr><td colspan="2" class="title">{kind.label} Summary</td></tr>
-        {classes.mkXML("","\n","")(shortHeader)}        
-        </table>)
-      })};
-  }
-
-  abstract class ClassContentFrame extends Frame {
-    def clazz: ClassOrObject
-    def body: NodeSeq =
-      (<xml:group>
-        {pageHeader}{navigation}{pageTop}
-        {header0}{longHeader(clazz)}
-        {pageBottom}{navigation}{pageFooter}
-      </xml:group>);
-    final def path = urlFor0(clazz.sym, clazz.sym)
-    private def navigation: NodeSeq =
-      (<table class="navigation" summary="">
-        <tr>
-          <td valign="top" class="navigation-links">
-            <!-- <table><tr></tr></table> -->
-          </td>
-          <td align="right" valign="top" style="white-space:nowrap;" rowspan="2">
-            <div class="doctitle-larger">{windowTitle}</div>
-          </td>
-        </tr>
-        <tr><td></td></tr>
-      </table>);
-    private def header0: NodeSeq = {
-      val owner = decode(clazz.sym.owner)
-      (<xml:group>
-      <div class="entity">
-        {aref(urlFor(owner), "_self", owner.fullNameString('.'))}
-        <br/>
-        <span class="entity">{Text(clazz.kind)}  {Text(clazz.name)}</span>
-      </div><hr/>
-      <div class="source">
-        {
-          if (SyntheticClasses contains clazz.sym)
-            Text("[Source: none]")
-          else {
-            val name = owner.fullNameString('/') + (if (owner.isPackage) "/" + clazz.name else "")
-            Text("[source: ") ++
-            (<a class={name} href=""><code>{name + ".scala"}</code></a>) ++
-            Text("]")
-          }
-        }
-      </div><hr/>
-      </xml:group>)
-    }
-  }  
-  
-  val index =
-    (<frameset cols="25%, 75%">
-    <frameset rows="50%, 28, 50%">
-    <frame src="modules.html" name={modulesFrame}></frame>
-    <frame src="nav-classes.html" name="navigationFrame"></frame>
-    <frame src="all-classes.html" name={classesFrame}></frame>
-    </frameset>
-    <frame src="root-content.html" name={contentFrame}></frame>
-    </frameset>);
-
-  val root = (<b></b>);
-  
-  abstract class RootFrame extends Frame {
-    def title = windowTitle
-    def body = index
-    def path = "index"
-    override def hasBody = false
-  }
-
-  val indexChars = 'A' :: 'B' :: 'C' :: 'D' :: 'E' :: 'G' :: 'I' :: 'L' :: 'M' :: 'P' :: 'R' :: 'T' :: 'V' :: 'X' :: Nil;
-
-  abstract class NavigationFrame extends Frame {
-    def title="navigation"
-    def path="nav-classes"
-    override def body0(hasBody: Boolean, nodes: NodeSeq): NodeSeq =
-      if (!hasBody) nodes
-      else (<body style="margin:1px 0 0 1px; padding:1px 0 0 1px;">{nodes}</body>);
-    def body =
-      (<form>
-        <select id="kinds" onchange="gotoKind()">
-          <option value="#Classes" selected="selected">Classes</option>
-          <option value="#Objects">Objects</option>
-        </select>
-        <span id="alphabet" style="font-family:Courier;word-spacing:-8px;">{
-          indexChars.mkXML("","\n","")(c => {
-          (<a href={Unparsed("javascript:gotoName(\'" + c + "\')")}>{c}</a>)
-          });
-	}
-        </span>
-      </form>)
-  }
-
-  def copyResources = {
-    import java.io._
-    val loader = this.getClass().getClassLoader()
-    def basename(path: String): String = {
-      val pos = path lastIndexOf System.getProperty("file.separator", "/")
-      if (pos != -1) path.substring(pos + 1) else path
-    }
-    def copyResource(name: String, isFile: Boolean) = try {
-      val (in, outfile) =
-        if (isFile)
-          (new FileInputStream(name), basename(name))
-        else {
-          // The name of a resource is a '/'-separated path name that identifies the resource.
-          (loader.getResourceAsStream("scala/tools/nsc/doc/" + name), name)
-        }
-      val out = new FileOutputStream(new File(outdir + File.separator + outfile))
-      val buf = new Array[Byte](1024)
-      var len = 0
-      while (len != -1) {
-        out.write(buf, 0, len)
-        len = in.read(buf)
-      }
-      in.close()
-      out.close()
-    } catch {
-      case _ =>
-        System.err.println("Resource file '" + name + "' not found")
-    }
-    copyResource(stylesheetSetting.value, !stylesheetSetting.isDefault)
-    copyResource("script.js", false)
-  }
-
-  private val patVal = java.util.regex.Pattern.compile(
-    "scala\\.(Byte|Boolean|Char|Double|Float|Int|Long|Short)")
-}
diff --git a/src/compiler/scala/tools/nsc/doc/ModelToXML.scala b/src/compiler/scala/tools/nsc/doc/ModelToXML.scala
deleted file mode 100644
index e8618cc..0000000
--- a/src/compiler/scala/tools/nsc/doc/ModelToXML.scala
+++ /dev/null
@@ -1,376 +0,0 @@
-/* NSC -- new Scala compiler
- * Copyright 2007-2009 LAMP/EPFL
- * @author  Sean McDirmid
- */
-// $Id: ModelToXML.scala 16881 2009-01-09 16:28:11Z cunei $
-
-package scala.tools.nsc.doc
-
-import scala.xml._
-
-/** This class has functionality to format source code models as XML blocks.
- *
- *  @author  Sean McDirmid, Stephane Micheloud
- */
-trait ModelToXML extends ModelExtractor {
-  import global._
-  import definitions.AnyRefClass
-  import DocUtil._
-  // decode entity into XML.
-  type Frame
-  
-  protected def urlFor(sym: Symbol)(implicit frame: Frame): String
-  protected def anchor(sym: Symbol)(implicit frame: Frame): NodeSeq
-
-  def aref(href: String, label: String)(implicit frame: Frame): NodeSeq
-/*
-  def link(entity: Symbol)(implicit frame: Frame): NodeSeq = {
-    val url = urlFor(entity)
-    // nothing to do but be verbose.
-    if (url == null)
-      Text(entity.owner.fullNameString('.') + '.' + entity.nameString)
-    else
-      aref(url, entity.nameString)
-  }
-*/
-  def link(entity: Symbol, label: String)(implicit frame: Frame): NodeSeq = {
-    val url = urlFor(entity)
-    if (url == null) { // external link (handled by script.js)
-      val (href, attr) =
-        if (entity.isClass || (entity==AnyRefClass))
-          ("", entity.owner.fullNameString('/') + '/' + entity.nameString)
-        else
-          ("#" + entity.nameString, entity.owner.fullNameString('/'))
-      val name = entity.owner.fullNameString('.') + '.' + entity.nameString
-      <a href={Utility.escape(href)} class={attr} target="contentFrame">{name}</a>;
-    }
-    else
-      aref(url, label)
-  }
-  
-  def link(entity: Symbol)(implicit frame: Frame): NodeSeq = 
-    link(entity, entity.nameString)
-  
-  def link(tpe: Type)(implicit frame: Frame): NodeSeq = {
-    if (!tpe.typeArgs.isEmpty) {
-      if (definitions.isFunctionType(tpe)) {
-        val (args,r) = tpe.normalize.typeArgs.splitAt(tpe.normalize.typeArgs.length - 1);
-        args.mkXML("(", ", ", ")")(link) ++ Text(" => ") ++ link(r.head);
-      } else if (tpe.typeSymbol == definitions.RepeatedParamClass) {
-        assert(tpe.typeArgs.length == 1)
-        link(tpe.typeArgs(0)) ++ Text("*")
-      } else if (tpe.typeSymbol == definitions.ByNameParamClass) {
-        assert(tpe.typeArgs.length == 1)
-        Text("=> ") ++ link(tpe.typeArgs(0))
-      } else if (tpe.typeSymbol.name.toString.startsWith("Tuple") &&
-                 tpe.typeSymbol.owner.name == nme.scala_.toTypeName) {
-        tpe.typeArgs.mkXML("(", ", ", ")")(link)
-      } else
-        link(decode(tpe.typeSymbol)) ++ tpe.typeArgs.surround("[", "]")(link)
-    } else tpe match {
-      case PolyType(tparams,result) =>
-        link(result) ++ tparams.surround("[", "]")(link)
-      case RefinedType(parents,_) => 
-        val parents1 =
-          if ((parents.length > 1) &&
-              (parents.head.typeSymbol eq definitions.ObjectClass)) parents.tail;
-          else parents;
-       parents1.mkXML(Text(""), <code> with </code>, Text(""))(link); 
-     case _ =>
-       if (tpe.typeSymbol == NoSymbol) {
-         throw new Error(tpe + " has no type class " + tpe.getClass)
-       }
-       link(decode(tpe.typeSymbol))
-    }
-  }
-
-  private def printIf[T](what: Option[T], before: String, after: String)(f: T => NodeSeq): NodeSeq =
-    if (what.isEmpty) Text("")
-    else Text(before) ++ f(what.get) ++ Text(after)
-
-  def bodyFor(entity: Entity)(implicit frame: Frame): NodeSeq = try {
-    var seq = {entity.typeParams.surround("[", "]")(e => {
-      Text(e.variance) ++ <em>{e.name}</em> ++
-        {printIf(e.hi, " <: ", "")(link)} ++
-        {printIf(e.lo, " >: ", "")(link)}
-    })} ++ printIf(entity.hi, " <: ", "")(link) ++
-           printIf(entity.lo, " >: ", "")(link);
-    {entity.valueParams.foreach(xs => {
-      seq = seq ++ xs.mkXML("(", ", ", ")")(arg =>
-        {
-          val str = arg.flagsString.trim
-          if (str.length == 0) NodeSeq.Empty
-          else <code>{Text(str)} </code>
-        } ++
-        <em>{arg.name}</em> ++ (try {
-          
-          Text(" : ") ++ link(arg.resultType.get)
-        } catch { 
-          case e : Throwable => System.err.println("ARG " + arg + " in " + entity); throw e 
-        })
-      );
-      seq
-    })};
-    seq ++ {printIf(entity.resultType, " : ", "")(tpe => link(tpe))}
-  } catch {
-    case e => System.err.println("generating for " + entity); throw e
-  }
-
-  def extendsFor(entity: Entity)(implicit frame: Frame): NodeSeq = {
-    if (entity.parents.isEmpty) NodeSeq.Empty
-    else <code> extends </code>++
-      entity.parents.mkXML(Text(""), <code> with </code>, Text(""))(link);
-  }
-
-  def parse(str: String): NodeSeq = {
-    new SpecialNode {
-      def label = "#PCDATA"
-      def toString(sb: StringBuilder): StringBuilder = {
-        sb.append(str.trim)
-        sb
-      }
-    }
-  }
-
-  def longHeader(entity: Entity)(implicit frame: Frame): NodeSeq = Group({
-    anchor(entity.sym) ++ <dl>
-      <dt>
-        {attrsFor(entity)}
-        <code>{Text(entity.flagsString)}</code>
-        <code>{Text(entity.kind)}</code>
-        <em>{entity.sym.nameString}</em>{bodyFor(entity)}
-      </dt>
-      <dd>{extendsFor(entity)}</dd>
-    </dl>;
-  } ++ {
-    val cmnt = entity.decodeComment
-    if (cmnt.isEmpty) NodeSeq.Empty
-    else longComment(entity, cmnt.get)
-  } ++ (entity match {
-      case entity: ClassOrObject => classBody(entity)
-      case _ => NodeSeq.Empty
-  }) ++ {
-    val overridden = entity.overridden
-    if (overridden.isEmpty)
-      NodeSeq.Empty
-    else {
-      <dl>
-        <dt style="margin:10px 0 0 20px;">
-          <b>Overrides</b>
-        </dt>
-        <dd>
-        { overridden.mkXML("",", ", "")(sym => link(decode(sym.owner)) ++ Text(".") ++ link(sym))
-        }
-        </dd>
-      </dl>
-    }
-  } ++ <hr/>);
-
-  def longComment(entity: Entity, cmnt: Comment)(implicit frame: Frame): NodeSeq = {
-    val attrs = <dl>{
-      var seq: NodeSeq = NodeSeq.Empty
-      cmnt.decodeAttributes.foreach{
-      case (tag, xs) => 
-        seq = seq ++ <dt style="margin:10px 0 0 20px;">
-        <b>{decodeTag(tag)}</b></dt> ++ {xs.flatMap{
-        case (option,body) => <dd>{
-          if (option == null) NodeSeq.Empty;
-          else decodeOption(tag, option);
-        }{ tag match {
-             case "see" => resolveSee(entity.sym, body.trim)
-             case _ => parse(body)
-           }}</dd>
-        }}
-      };
-      seq
-    }</dl>;
-    <xml:group>
-      <dl><dd>{parse(cmnt.body)}</dd></dl>
-      {attrs}
-    </xml:group>
-  }
-  
-  /**
-   * Try to be smart about @see elements. If the body looks like a link, turn it into
-   * a link. If it can be resolved in the symbol table, turn it into a link to the referenced
-   * entity.
-   */
-  private def resolveSee(owner: Symbol, body: String)(implicit frame: Frame): NodeSeq = {
-    /** find a class either in the root package, in the current class or in the current package. */
-    def findClass(clsName: String): Symbol = {
-      try { definitions.getClass(clsName) } catch {
-        case f: FatalError => 
-          try { definitions.getMember(owner, clsName.toTypeName) } catch {
-            case f: FatalError =>
-              definitions.getMember(owner.enclosingPackage, clsName.toTypeName)
-          }
-      }
-    }
-    
-    if (body.startsWith("http://")
-        || body.startsWith("https://")
-        || body.startsWith("www")) {
-      // a link
-      body.split(" ") match {
-        case Seq(href, txt, rest @ _*) => 
-          <a href={href}>{txt}{rest}</a>
-        case _ => 
-          <a href={body}>{body}</a>
-      }
-    } else try {
-      // treat it like a class or member reference
-      body.split("#") match {
-        case Seq(clazz, member) =>
-          val clazzSym = if (clazz.length == 0) owner.enclClass else findClass(clazz)
-          link(definitions.getMember(clazzSym, member), body)
-        case Seq(clazz, _*) =>
-          link(findClass(clazz), body)
-        case _ =>
-          parse(body)
-      }
-    } catch {
-      case f: FatalError =>
-        log("Error resolving @see: " + f.toString)
-        parse(body)
-    }
-  }
-  
-  def classBody(entity: ClassOrObject)(implicit from: Frame): NodeSeq =
-    <xml:group>
-      {categories.mkXML("","\n","")(c => shortList(entity, c)) : NodeSeq}
-      {categories.mkXML("","\n","")(c =>  longList(entity, c)) : NodeSeq}
-    </xml:group>;
-
-  def longList(entity: ClassOrObject, category: Category)(implicit from: Frame): NodeSeq = {
-    val xs = entity.members(category)
-    if (!xs.elements.hasNext)
-      NodeSeq.Empty
-    else Group(
-        <table cellpadding="3" class="member-detail" summary="">
-          <tr><td class="title">{Text(category.label)} Details</td></tr>
-        </table>
-        <div>{xs.mkXML("","\n","")(m => longHeader(m))}</div>)
-  }
-  
-  def shortList(entity: ClassOrObject, category: Category)(implicit from: Frame): NodeSeq = {
-    val xs = entity.members(category)
-    var seq: NodeSeq = NodeSeq.Empty
-    if (xs.elements.hasNext) {
-      // alphabetic
-      val set = new scala.collection.jcl.TreeSet[entity.Member]()(mA => new Ordered[entity.Member] {
-        def compare(mB: entity.Member): Int =
-          if (mA eq mB) 0
-          else {
-            val diff = mA.name compare mB.name
-            if (diff != 0) diff
-            else {
-              val diff0 = mA.hashCode - mB.hashCode
-              assert(diff0 != 0, mA.name)
-              diff0
-            }
-          }
-        override def equals(other: Any): Boolean =
-           other match { case that: entity.Member => compare(that) == 0
-                         case that: AnyRef => this.eq(that) 
-                         case _ => false }
-      });
-      set addAll xs;
-      seq = seq ++ <table cellpadding="3" class="member" summary="">
-      <tr><td colspan="2" class="title">{Text(category.label + " Summary")}</td></tr>
-      {set.mkXML("","\n","")(mmbr => shortHeader(mmbr))}
-      </table>
-    }
-    // list inherited members...if any.
-    for ((tpe,members) <- entity.inherited) {
-      val members0 = members.filter(m => category.f(m.sym));
-      if (!members0.isEmpty) seq = seq ++ <table cellpadding="3" class="inherited" summary="">
-        <tr><td colspan="2" class="title">
-          {Text(category.plural + " inherited from ") ++ link(tpe)}
-        </td></tr>
-        <tr><td colspan="2" class="signature">
-          {members0.mkXML((""), (", "), (""))(m => {
-            link(decode(m.sym)) ++
-              (if (m.sym.hasFlag(symtab.Flags.ABSTRACT) || m.sym.hasFlag(symtab.Flags.DEFERRED)) {
-                Text(" (abstract)");
-              } else NodeSeq.Empty);
-           })}
-        </td></tr>
-      </table>
-    }
-    seq;
-  }
-
-  protected def decodeOption(tag: String, string: String): NodeSeq =
-    <code>{Text(string + " - ")}</code>;
-
-  protected def decodeTag(tag: String): String = 
-    "" + Character.toUpperCase(tag.charAt(0)) + tag.substring(1)
-  
-  def shortHeader(entity: Entity)(implicit from: Frame): NodeSeq =
-    <tr>
-      <td valign="top" class="modifiers"> 
-        <code>{Text(entity.flagsString)} {Text(entity.kind)}</code>
-      </td>
-      <td class="signature">
-        <em>{link(decode(entity.sym))}</em>
-        {bodyFor(entity) ++ extendsFor(entity)}
-        {
-          entity.resultType match {
-            case Some(PolyType(_, ConstantType(v))) => Text(" = " + v.escapedStringValue)
-            case _ => NodeSeq.Empty
-          }
-        }
-        {
-          val cmnt = entity.decodeComment
-          if (cmnt.isEmpty) NodeSeq.Empty
-          else shortComment(cmnt.get)
-        }
-      </td>
-    </tr>
-
-  import java.util.regex.Pattern
-  // pattern detecting first line of comment (see ticket #224)
-  private val pat = Pattern.compile("[ \t]*(/\\*)[ \t]*")
-
-  /** Ticket #224
-   *  Write the first sentence as a short summary of the method, as scaladoc
-   *  automatically places it in the method summary table (and index).
-   *  (see http://java.sun.com/j2se/javadoc/writingdoccomments/)
-   */
-  def shortComment(cmnt: Comment): NodeSeq = {
-    val lines = cmnt.body split "<p>"
-    val first =
-      if (lines.length < 2)
-        lines(0)
-      else {
-        val line0 = lines(0)
-        val mat = pat matcher line0
-        if (mat.matches()) line0 + lines(1) 
-        else line0
-      }
-    <div>{parse(first/*cmnt.body*/)}</div>
-  }
-
-  def attrsFor(entity: Entity)(implicit from: Frame): NodeSeq = {
-    def attrFor(attr: AnnotationInfo): Node = {
-      val buf = new StringBuilder
-      val AnnotationInfo(tpe, args, nvPairs) = attr
-      val name = link(decode(tpe.typeSymbol))
-      if (!args.isEmpty)
-        buf.append(args.mkString("(", ",", ")"))
-      if (!nvPairs.isEmpty)
-        for (((name, value), index) <- nvPairs.zipWithIndex) {
-          if (index > 0)
-            buf.append(", ")
-          buf.append(name).append(" = ").append(value)
-        }
-      Group(name ++ Text(buf.toString))
-    }
-    if (entity.sym.hasFlag(symtab.Flags.CASE)) NodeSeq.Empty;
-    else {
-      val sep = Text("@")
-      for (attr <- entity.attributes)
-        yield Group({(sep ++ attrFor(attr) ++ <br/>)})
-    }
-  }
-}
diff --git a/src/compiler/scala/tools/nsc/doc/Settings.scala b/src/compiler/scala/tools/nsc/doc/Settings.scala
index 47d38e2..226f641 100644
--- a/src/compiler/scala/tools/nsc/doc/Settings.scala
+++ b/src/compiler/scala/tools/nsc/doc/Settings.scala
@@ -1,28 +1,38 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: Settings.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.tools.nsc.doc
+package scala.tools.nsc
+package doc
 
 import java.io.File
 import java.lang.System
 
+/** An extended version of compiler settings, with additional Scaladoc-specific options.
+  * @param error A function that prints a string to the appropriate error stream. */
 class Settings(error: String => Unit) extends scala.tools.nsc.Settings(error) {
+  
+  /** A setting that defines in which format the documentation is output. ''Note:'' this setting is currently always
+    * `html`. */
+  val docformat      = ChoiceSetting    ("-doc-format", "Selects in which format documentation is rendered", List("html"), "html")
 
-  /** scaladoc specific options */
-  val memberaccess   = ChoiceSetting    ("-access", "Show only public, protected/public (default) or all classes and members",
-                                         List("public", "protected", "private"), "protected")
-  val pagebottom     = StringSetting    ("-bottom", "pagebottom", "Include bottom text for each page", "")
-  val doccharset     = StringSetting    ("-charset", "doccharset", "Charset for cross-platform viewing of generated documentation.", "")
-  val doctitle       = StringSetting    ("-doctitle", "doctitle", "Include title for the overview page", "Scala 2<br/>API Specification")
-  val pagefooter     = StringSetting    ("-footer", "pagefooter", "Include footer text for each page", "")
-  val pageheader     = StringSetting    ("-header", "pageheader", "Include header text for each page", "")
-  val linksource     = BooleanSetting   ("-linksource", "Generate source in HTML").hideToIDE
-  val nocomment      = BooleanSetting   ("-nocomment", "Suppress description and tags, generate only declarations.").hideToIDE
-  val stylesheetfile = StringSetting    ("-stylesheetfile", "stylesheetfile", "File to change style of the generated documentation", "style.css")
-  val pagetop        = StringSetting    ("-top", "pagetop", "Include top text for each page", "")
-  val windowtitle    = StringSetting    ("-windowtitle", "windowtitle", "Specify window title of generated HTML documentation", "Scala 2")
+  /** A setting that defines the overall title of the documentation, typically the name of the library being
+    * documented. 'Note:'' This setting is currently not used. */
+  val doctitle       = StringSetting    ("-doc-title", "doc-title", "The overall name of the Scaladoc site", "")
 
+  /** A setting that defines the overall version number of the documentation, typically the version of the library being
+    * documented. 'Note:'' This setting is currently not used. */
+  val docversion     = StringSetting    ("-doc-version", "doc-version", "An optional version number, to be appended to the title", "")
+
+  /** A setting that defines a URL to be concatenated with source locations and show a link to source files.
+   * If needed the sourcepath option can be used to exclude undesired initial part of the link to sources */
+  val docsourceurl   = StringSetting    ("-doc-source-url", "url", "A URL pattern used to build links to template sources; use variables, for example: €{TPL_NAME} ('Seq'), €{TPL_OWNER} ('scala.collection'), €{FILE_PATH} ('scala/collection/Seq')", "")
+
+  val useStupidTypes = BooleanSetting   ("-Yuse-stupid-types", "Print the types of inherited members as seen from their original definition context. Hint: you don't want to do that!")
+
+  // working around issue described in r18708.
+  suppressVTWarn.value = true
+  
+  // TODO: add a new setting for whether or not to document sourceless entities (e.g., Any, Unit, etc)
 }
diff --git a/src/compiler/scala/tools/nsc/doc/SourcelessComments.scala b/src/compiler/scala/tools/nsc/doc/SourcelessComments.scala
new file mode 100644
index 0000000..d2f7154
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/doc/SourcelessComments.scala
@@ -0,0 +1,249 @@
+/* NSC -- new Scala compiler -- Copyright 2007-2010 LAMP/EPFL */
+
+package scala.tools.nsc
+package doc
+
+import scala.collection._
+
+/**
+  * A class that provides comments for all symbols which pre-exist in Scala (Any, Nothing, ...)
+  * It also contains a HashSet of the given symbols
+  * The comments are to be added to a HashMap called comments, which resides in the Global.scala file
+  * @author Manohar Jonnalagedda, Stephane Micheloud, Sean McDirmid, Geoffrey Washburn
+  * @version 1.0 */
+abstract class SourcelessComments {
+
+  val global: Global
+
+  import global._
+  import definitions._
+
+  lazy val comments = {
+    
+    val comment = mutable.HashMap.empty[Symbol, DocComment]
+
+    comment(NothingClass) = new DocComment("""
+      /** Class `Nothing` is - together with class [[scala.Null]] - at the bottom of Scala's type hierarchy.
+        *
+        * Type `Nothing` is a subtype of every other type (including [[scala.Null]]); there exist ''no instances'' of
+        * this type. Even though type `Nothing` is empty, it is nevertheless useful as a type parameter. For instance,
+        * the Scala library defines a value [[scala.collection.immutable.Nil]] of type `List[Nothing]`. Because lists
+        * are covariant in Scala, this makes [[scala.collection.immutable.Nil]] an instance of `List[T]`, for any
+        * element of type `T`. */
+      """)
+    
+     comment(NullClass) = new DocComment("""
+       /** Class `Null` is - together with class [[scala.Nothing]] - at the bottom of the Scala type hierarchy.
+         *
+         * Type `Null` is a subtype of all reference types; its only instance is the `null` reference. Since `Null` is
+         * not a subtype of value types, `null` is not a member of any such type. For instance, it is not possible to
+         * assign `null` to a variable of type [[scala.Int]]. */
+       """)
+    
+     /*******************************************************************/
+     /* Documentation for Any */
+    
+     comment(AnyClass) = new DocComment("""
+      /** Class `Any` is the root of the Scala class hierarchy. Every class in a Scala execution environment inherits
+        * directly or indirectly from this class. Class `Any` has two direct subclasses: [[scala.AnyRef]] and
+        * [[scala.AnyVal]]. */
+      """)
+    
+    comment(Any_equals) = new DocComment("""
+      /** This method is used to compare the receiver object (`this`) with the argument object (`arg0`) for equivalence.
+        *
+        * The default implementations of this method is an [http://en.wikipedia.org/wiki/Equivalence_relation equivalence
+        * relation]:
+        *  * It is reflexive: for any instance `x` of type `Any`, `x.equals(x)` should return `true`.
+        *  * It is symmetric: for any instances `x` and `y` of type `Any`, `x.equals(y)` should return `true` if and
+        *    only if `y.equals(x)` returns `true`.
+        *  * It is transitive: for any instances `x`, `y`, and `z` of type `AnyRef` if `x.equals(y)` returns `true` and
+        *    `y.equals(z)` returns `true`, then `x.equals(z)` should return `true`.
+        *
+        * If you override this method, you should verify that your implementation remains an equivalence relation.
+        * Additionally, when overriding this method it is often necessary to override `hashCode` to ensure that objects
+        * that are "equal" (`o1.equals(o2)` returns `true`) hash to the same [[scala.Int]]
+        * (`o1.hashCode.equals(o2.hashCode)`).
+        *
+        * @param arg0 the object to compare against this object for equality.
+        * @return     `true` if the receiver object is equivalent to the argument; `false` otherwise. */
+      """)
+    
+    comment(Any_==) = new DocComment("""
+      /** `o == arg0` is the same as `o.equals(arg0)`.
+        *
+        * @param arg0 the object to compare against this object for equality.
+        * @return     `true` if the receiver object is equivalent to the argument; `false` otherwise. */
+      """)
+    
+    comment(Any_!=) = new DocComment("""
+      /** `o != arg0` is the same as `!(o == (arg0))`.
+        *
+        * @param arg0 the object to compare against this object for dis-equality.
+        * @return     `false` if the receiver object is equivalent to the argument; `true` otherwise. */
+      """)
+    
+    comment(Any_toString) = new DocComment("""
+      /** Returns a string representation of the object.  
+        *
+        * The default representation is platform dependent.
+        *
+        * @return a string representation of the object. */
+      """)
+    
+    comment(Any_asInstanceOf) = new DocComment("""
+      /** This method is used to cast the receiver object to be of type `T0`.
+        *
+        * Note that the success of a cast at runtime is modulo Scala's erasure semantics.  Therefore the expression
+        * `1.asInstanceOf[String]` will throw a `ClassCastException` at runtime, while the expression
+        * `List(1).asInstanceOf[List[String]]` will not.  In the latter example, because the type argument is erased as
+        * part of compilation it is not possible to check whether the contents of the list are of the requested typed.
+        *
+        * @throws ClassCastException if the receiver object is not an instance of erasure of type `T0`.
+        * @return the receiver object. */
+      """)
+    
+    comment(Any_isInstanceOf) = new DocComment("""
+      /** This method is used to test whether the dynamic type of the receiver object is `T0`.
+        *
+        * Note that the test result of the test is modulo Scala's erasure semantics.  Therefore the expression
+        * `1.isInstanceOf[String]` will return `false`, while the expression `List(1).isInstanceOf[List[String]]` will
+        * return `true`.  In the latter example, because the type argument is erased as part of compilation it is not
+        * possible to check whether the contents of the list are of the requested typed.
+        *
+        * @return `true` if the receiver object is an instance of erasure of type `T0`; `false` otherwise. */
+      """)
+    
+    comment(Any_hashCode) = new DocComment("""
+      /** Returns a hash code value for the object.  
+        *
+        * The default hashing algorithm is platform dependent.
+        *
+        * Note that it is allowed for two objects to have identical hash codes (`o1.hashCode.equals(o2.hashCode)`) yet
+        * not be equal (`o1.equals(o2)` returns `false`).  A degenerate implementation could always return `0`.
+        * However, it is required that if two objects are equal (`o1.equals(o2)` returns `true`) that they have
+        * identical hash codes (`o1.hashCode.equals(o2.hashCode)`).  Therefore, when overriding this method, be sure
+        * to verify that the behavior is consistent with the `equals` method.
+        *
+        * @return the hash code value for the object. */
+      """)
+    
+     /*******************************************************************/
+     /* Documentation for AnyRef */
+    
+     comment(AnyRefClass) = new DocComment("""
+       /** Class `AnyRef` is the root class of all ''reference types''. */
+       """)
+    
+    comment(Object_==) = new DocComment("""
+      /** `o == arg0` is the same as `if (o eq null) arg0 eq null else o.equals(arg0)`.
+        *
+        * @param arg0 the object to compare against this object for equality.
+        * @return `true` if the receiver object is equivalent to the argument; `false` otherwise. */
+      """)
+    
+    comment(Object_ne) = new DocComment("""
+      /** `o.ne(arg0)` is the same as `!(o.eq(arg0))`.
+        *
+        * @param arg0 the object to compare against this object for reference dis-equality.
+        * @return `false` if the argument is not a reference to the receiver object; `true` otherwise. */
+      """)
+    
+    
+    comment(Object_finalize) = new DocComment("""
+      /** This method is called by the garbage collector on the receiver object when garbage collection determines that
+        * there are no more references to the object.
+        *
+        * The details of when and if the `finalize` method are invoked, as well as the interaction between `finalize`
+        * and non-local returns and exceptions, are all platform dependent. */
+      """)
+    
+    comment(Object_clone) = new DocComment("""
+      /** This method creates and returns a copy of the receiver object.
+        *
+        * The default implementation of the `clone` method is platform dependent.
+        *
+        * @return a copy of the receiver object. */
+      """)
+    
+    comment(Object_getClass) = new DocComment("""
+      /** Returns a representation that corresponds to the dynamic class of the receiver object.
+        *
+        * The nature of the representation is platform dependent.
+        *
+        * @return a representation that corresponds to the dynamic class of the receiver object. */
+      """)
+    
+    comment(Object_notify) = new DocComment("""
+      /** Wakes up a single thread that is waiting on the receiver object's monitor. */
+      """)
+    
+    comment(Object_notifyAll) = new DocComment("""
+      /** Wakes up all threads that are waiting on the receiver object's monitor. */
+      """)
+    
+    comment(Object_eq) = new DocComment("""
+      /** This method is used to test whether the argument (`arg0`) is a reference to the
+        * receiver object (`this`).
+        *
+        * The `eq` method implements an [http://en.wikipedia.org/wiki/Equivalence_relation equivalence relation] on
+        * non-null instances of `AnyRef`:
+        *  * It is reflexive: for any non-null instance `x` of type `AnyRef`, `x.eq(x)` returns `true`.
+        *  * It is symmetric: for any non-null instances `x` and `y` of type `AnyRef`, `x.eq(y)` returns `true` if and
+        *    only if `y.eq(x)` returns `true`.
+        *  * It is transitive: for any non-null instances `x`, `y`, and `z` of type `AnyRef` if `x.eq(y)` returns `true`
+        *    and `y.eq(z)` returns `true`, then `x.eq(z)` returns `true`.
+        *
+        * Additionally, the `eq` method has three other properties.
+        *  * It is consistent: for any non-null instances `x` and `y` of type `AnyRef`, multiple invocations of
+        *    `x.eq(y)` consistently returns `true` or consistently returns `false`.
+        *  * For any non-null instance `x` of type `AnyRef`, `x.eq(null)` and `null.eq(x)` returns `false`.
+        *  * `null.eq(null)` returns `true`.
+        *
+        * When overriding the `equals` or `hashCode` methods, it is important to ensure that their behavior is
+        * consistent with reference equality.  Therefore, if two objects are references to each other (`o1 eq o2`), they
+        * should be equal to each other (`o1 == o2`) and they should hash to the same value (`o1.hashCode == o2.hashCode`).
+        *
+        * @param arg0 the object to compare against this object for reference equality.
+        * @return `true` if the argument is a reference to the receiver object; `false` otherwise. */
+      """)
+    
+    /*******************************************************************/
+    
+    comment(AnyValClass) = new DocComment("""
+      /** Class `AnyVal` is the root class of all ''value types''.
+        *
+        * `AnyVal` has a fixed number of subclasses, which describe values which are not implemented as objects in the
+        * underlying host system.
+        *
+        * Classes [[scala.Double]], [[scala.Float]], [[scala.Long]], [[scala.Int]], [[scala.Char]], [[scala.Short]],
+        * and [[scala.Byte]] are together called ''numeric value types''. Classes [[scala.Byte]], [[scala.Short]], and
+        * [[scala.Char]] are called ''subrange types''. Subrange types, as well as [[scala.Int]] and [[scala.Long]] are
+        * called ''integer types'', whereas [[scala.Float]] and [[scala.Double]] are called ''floating point types''. */
+      """)
+    
+    comment(BooleanClass) = new DocComment("""
+      /** Class `Boolean` has only two values: `true` and `false`. */
+      """)
+    
+    comment(UnitClass) = new DocComment("""
+      /** Class `Unit` has only one value: `()`. */
+      """)
+    
+    List(ByteClass, CharClass, DoubleClass, LongClass, FloatClass, IntClass, ShortClass) foreach { sym =>
+      val maxValue = "MAX_" + sym.name.toString().toUpperCase()
+      val minValue = "MIN_" + sym.name.toString().toUpperCase()
+      comment(sym) = new DocComment("""
+        /** Class `""" + sym.name + """` belongs to the value classes whose instances are not represented as objects by
+          * the underlying host system.  There is an implicit conversion from instances of `""" + sym.name + """` to
+          * instances of [[scala.runtime.Rich""" + sym.name + """]] which provides useful non-primitive operations.
+          * All value classes inherit from class [[scala.AnyVal]].
+          *
+          * Values `""" + maxValue + """` and `""" + minValue + """` are defined in object [[scala.Math]]. */
+        """)
+    }
+
+    comment
+  }
+   
+}
diff --git a/src/compiler/scala/tools/nsc/doc/Universe.scala b/src/compiler/scala/tools/nsc/doc/Universe.scala
new file mode 100644
index 0000000..71b4a4a
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/doc/Universe.scala
@@ -0,0 +1,11 @@
+package scala.tools.nsc.doc
+
+/**
+ * Class to hold common dependencies across Scaladoc classes.
+ * @author Pedro Furlanetto
+ * @author Gilles Dubochet
+ */
+trait Universe {
+  def settings: Settings
+  def rootPackage: model.Package
+}
diff --git a/src/compiler/scala/tools/nsc/doc/html/HtmlFactory.scala b/src/compiler/scala/tools/nsc/doc/html/HtmlFactory.scala
new file mode 100644
index 0000000..801fddd
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/doc/html/HtmlFactory.scala
@@ -0,0 +1,79 @@
+/* NSC -- new Scala compiler
+ * Copyright 2007-2010 LAMP/EPFL
+ * @author  David Bernard, Manohar Jonnalagedda
+ */
+
+package scala.tools.nsc
+package doc
+package html
+
+import model._
+
+import java.io.{ File => JFile }
+import io.{ Streamable, Directory }
+import scala.collection._
+
+/** A class that can generate Scaladoc sites to some fixed root folder.
+  * @author David Bernard
+  * @author Gilles Dubochet */
+class HtmlFactory(val universe: Universe) {
+
+  /** The character encoding to be used for generated Scaladoc sites. This value is currently always UTF-8. */
+  def encoding: String = "UTF-8"
+
+  def siteRoot: JFile = new JFile(universe.settings.outdir.value)
+
+  /** Generates the Scaladoc site for a model into the site root. A scaladoc site is a set of HTML and related files
+    * that document a model extracted from a compiler run.
+    * @param model The model to generate in the form of a sequence of packages. */
+  def generate : Unit = {
+    
+    def copyResource(subPath: String) {
+      val bytes = new Streamable.Bytes {
+        val inputStream = getClass.getResourceAsStream("/scala/tools/nsc/doc/html/resource/" + subPath)
+        assert(inputStream != null)
+      }.toByteArray
+      val dest = Directory(siteRoot) / subPath
+      dest.parent.createDirectory()
+      val out = dest.toFile.bufferedOutput()
+      try out.write(bytes, 0, bytes.length)
+      finally out.close()
+    }
+
+    copyResource("lib/jquery.js")
+    copyResource("lib/jquery-ui.js")
+    copyResource("lib/jquery.layout.js")
+    copyResource("lib/tools.tooltip.js")
+    copyResource("lib/scheduler.js")
+    copyResource("lib/index.css")
+    copyResource("lib/index.js")
+    copyResource("lib/template.css")
+    copyResource("lib/template.js")
+    copyResource("lib/class.png")
+    copyResource("lib/class_big.png")
+    copyResource("lib/object.png")
+    copyResource("lib/object_big.png")
+    copyResource("lib/trait.png")
+    copyResource("lib/trait_big.png")
+    copyResource("lib/package.png")
+    copyResource("lib/package_big.png")
+    copyResource("lib/filter_box_left.png")
+    copyResource("lib/filter_box_right.png")
+    copyResource("lib/remove.png")
+
+    new page.Index(universe) writeFor this
+
+    val written = mutable.HashSet.empty[DocTemplateEntity]
+
+    def writeTemplate(tpl: DocTemplateEntity): Unit =
+      if (!(written contains tpl)) {
+        new page.Template(tpl) writeFor this
+        written += tpl
+        tpl.templates map (writeTemplate(_))
+      }
+
+    writeTemplate(universe.rootPackage)
+    
+  }
+  
+}
diff --git a/src/compiler/scala/tools/nsc/doc/html/HtmlPage.scala b/src/compiler/scala/tools/nsc/doc/html/HtmlPage.scala
new file mode 100644
index 0000000..e3fe25f
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/doc/html/HtmlPage.scala
@@ -0,0 +1,239 @@
+/* NSC -- new Scala compiler
+ * Copyright 2007-2010 LAMP/EPFL
+ * @author  David Bernard, Manohar Jonnalagedda
+ */
+ 
+package scala.tools.nsc
+package doc
+package html
+
+import model._
+import comment._
+
+import xml.{XML, NodeSeq}
+import xml.dtd.{DocType, PublicID}
+import scala.collection._
+import scala.reflect.NameTransformer
+import java.nio.channels.Channels
+import java.io.{FileOutputStream, File}
+
+/** An html page that is part of a Scaladoc site.
+  * @author David Bernard
+  * @author Gilles Dubochet */
+abstract class HtmlPage { thisPage =>
+  
+  /** The path of this page, relative to the API site. `path.tail` is a list of folder names leading to this page (from
+    * closest package to one-above-root package), `path.head` is the file name of this page. Note that `path` has a
+    * length of at least one. */
+  def path: List[String]
+
+  /** The title of this page. */
+  protected def title: String
+
+  /** Additional header elements (links, scripts, meta tags, etc.) required for this page. */
+  protected def headers: NodeSeq
+
+  /** The body of this page. */
+  protected def body: NodeSeq
+
+  /** Writes this page as a file. The file's location is relative to the generator's site root, and the encoding is
+    * also defined by the generator.
+    * @param generator The generator that is writing this page. */
+  def writeFor(site: HtmlFactory): Unit = {
+    val doctype =
+      DocType("html", PublicID("-//W3C//DTD XHTML 1.1//EN", "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"), Nil)
+    val html =
+      <html>
+        <head>
+          <title>{ title }</title>
+          <meta http-equiv="content-type" content={ "text/html; charset=" + site.encoding }/>
+          { headers }
+        </head>
+        { body }
+      </html>
+    val pageFile = new File(site.siteRoot, absoluteLinkTo(thisPage.path))
+    val pageFolder = pageFile.getParentFile
+    if (!pageFolder.exists) pageFolder.mkdirs()
+    val fos = new FileOutputStream(pageFile.getPath)
+    val w = Channels.newWriter(fos.getChannel, site.encoding)
+    try {
+      w.write("<?xml version='1.0' encoding='" + site.encoding + "'?>\n")
+      w.write( doctype.toString + "\n")
+      w.write(xml.Xhtml.toXhtml(html))
+    }
+    finally {
+      w.close()
+      fos.close()
+    }
+    //XML.save(pageFile.getPath, html, site.encoding, xmlDecl = false, doctype = doctype)
+  }
+
+  def templateToPath(tpl: TemplateEntity): List[String] = {
+    def doName(tpl: TemplateEntity): String =
+      NameTransformer.encode(tpl.name) + (if (tpl.isObject) "$" else "")
+    def downPacks(pack: Package): List[String] =
+      if (pack.isRootPackage) Nil else (doName(pack) :: downPacks(pack.inTemplate))
+    def downInner(nme: String, tpl: TemplateEntity): (String, Package) = {
+      tpl.inTemplate match {
+        case inPkg: Package => (nme + ".html", inPkg)
+        case inTpl => downInner(doName(inTpl) + "$" + nme, inTpl)
+      }
+    }
+    val (file, pack) =
+      tpl match {
+        case p: Package => ("package.html", p)
+        case _ => downInner(doName(tpl), tpl)
+      }
+    file :: downPacks(pack)
+  }
+
+  /** A relative link from this page to some destination class entity.
+    * @param destEntity The class or object entity that the link will point to. */
+  def relativeLinkTo(destClass: TemplateEntity): String =
+    relativeLinkTo(templateToPath(destClass))
+
+  /** A relative link from this page to some destination page in the Scaladoc site.
+    * @param destPage The page that the link will point to. */
+  def relativeLinkTo(destPage: HtmlPage): String = {
+    relativeLinkTo(destPage.path)
+  }
+
+  /** A relative link from this page to some destination path.
+    * @param destPath The path that the link will point to. */
+  def relativeLinkTo(destPath: List[String]): String = {
+    def relativize(from: List[String], to: List[String]): List[String] = (from, to) match {
+      case (f :: fs, t :: ts) if (f == t) => // both paths are identical to that point
+        relativize(fs, ts)
+      case (fss, tss) =>
+        List.fill(fss.length - 1)("..") ::: tss
+    }
+    relativize(thisPage.path.reverse, destPath.reverse).mkString("/")
+  }
+
+  def absoluteLinkTo(destPath: List[String]): String = {
+    destPath.reverse.mkString("/")
+  }
+
+  /** Transforms an optional comment into an styled HTML tree representing its body if it is defined, or into an empty
+    * node sequence if it is not. */
+  def commentToHtml(comment: Option[Comment]): NodeSeq =
+    (comment map (commentToHtml(_))) getOrElse NodeSeq.Empty
+  
+  /** Transforms a comment into an styled HTML tree representing its body. */
+  def commentToHtml(comment: Comment): NodeSeq =
+    bodyToHtml(comment.body)
+
+  def bodyToHtml(body: Body): NodeSeq =
+    body.blocks flatMap (blockToHtml(_))
+
+  def blockToHtml(block: Block): NodeSeq = block match {
+    case Title(in, 1) => <h3>{ inlineToHtml(in) }</h3>
+    case Title(in, 2) => <h4>{ inlineToHtml(in) }</h4>
+    case Title(in, 3) => <h5>{ inlineToHtml(in) }</h5>
+    case Title(in, _) => <h6>{ inlineToHtml(in) }</h6>
+    case Paragraph(in) => <p>{ inlineToHtml(in) }</p>
+    case Code(data) => <pre>{ xml.Text(data) }</pre>
+    case UnorderedList(items) =>
+      <ul>{ listItemsToHtml(items) }</ul>
+    case OrderedList(items, listStyle) =>
+      <ol class={ listStyle }>{ listItemsToHtml(items) }</ol>
+    case DefinitionList(items) =>
+      <dl>{items map { case (t, d) => <dt>{ inlineToHtml(t) }</dt><dd>{ blockToHtml(d) }</dd> } }</dl>
+    case HorizontalRule() =>
+      <hr/>
+  }
+  
+  def listItemsToHtml(items: Seq[Block]) =
+    items.foldLeft(xml.NodeSeq.Empty){ (xmlList, item) =>
+      item match {
+        case OrderedList(_, _) | UnorderedList(_) =>  // html requires sub ULs to be put into the last LI
+          xmlList.init ++ <li>{ xmlList.last.child ++ blockToHtml(item) }</li>
+        case Paragraph(inline) =>
+          xmlList :+ <li>{ inlineToHtml(inline) }</li>  // LIs are blocks, no need to use Ps
+        case block =>
+          xmlList :+ <li>{ blockToHtml(block) }</li>
+      }
+  }
+  
+  def inlineToHtml(inl: Inline): NodeSeq = inl match {
+    case Chain(items) => items flatMap (inlineToHtml(_))
+    case Italic(in) => <i>{ inlineToHtml(in) }</i>
+    case Bold(in) => <b>{ inlineToHtml(in) }</b>
+    case Underline(in) => <u>{ inlineToHtml(in) }</u>
+    case Superscript(in) => <sup>{ inlineToHtml(in) }</sup>
+    case Subscript(in) => <sub>{ inlineToHtml(in) }</sub>
+    case Link(raw, title) => <a href={ raw }>{ inlineToHtml(title) }</a>
+    case EntityLink(entity) => templateToHtml(entity)
+    case Monospace(text) => <code>{ xml.Text(text) }</code>
+    case Text(text) => xml.Text(text)
+    case Summary(in) => inlineToHtml(in)
+    case HtmlTag(tag) => xml.Unparsed(tag)
+  }
+
+  def typeToHtml(tpe: model.TypeEntity, hasLinks: Boolean): NodeSeq = {
+    val string = tpe.name
+    def toLinksOut(inPos: Int, starts: List[Int]): NodeSeq = {
+      if (starts.isEmpty && (inPos == string.length))
+        NodeSeq.Empty
+      else if (starts.isEmpty)
+        xml.Text(string.slice(inPos, string.length))
+      else if (inPos == starts.head)
+        toLinksIn(inPos, starts)
+      else {
+        xml.Text(string.slice(inPos, starts.head)) ++ toLinksIn(starts.head, starts)
+      }
+    }
+    def toLinksIn(inPos: Int, starts: List[Int]): NodeSeq = {
+      val (tpl, width) = tpe.refEntity(inPos)
+      (tpl match {
+        case dtpl:DocTemplateEntity if hasLinks =>
+          <a href={ relativeLinkTo(dtpl) } class="extype" name={ dtpl.qualifiedName }>{
+            string.slice(inPos, inPos + width)
+          }</a>
+        case tpl =>
+          <span class="extype" name={ tpl.qualifiedName }>{ string.slice(inPos, inPos + width) }</span>
+      }) ++ toLinksOut(inPos + width, starts.tail)
+    }
+    if (hasLinks)
+      toLinksOut(0, tpe.refEntity.keySet.toList)
+    else
+      xml.Text(string)
+  }
+
+  def typesToHtml(tpess: List[model.TypeEntity], hasLinks: Boolean, sep: NodeSeq): NodeSeq = tpess match {
+    case Nil         => NodeSeq.Empty
+    case tpe :: Nil  => typeToHtml(tpe, hasLinks)
+    case tpe :: tpes => typeToHtml(tpe, hasLinks) ++ sep ++ typesToHtml(tpes, hasLinks, sep)
+  }
+
+  /** Returns the HTML code that represents the template in `tpl` as a hyperlinked name. */
+  def templateToHtml(tpl: TemplateEntity) = tpl match {
+    case dTpl: DocTemplateEntity =>
+      <a href={ relativeLinkTo(dTpl) } class="extype" name={ dTpl.qualifiedName }>{ dTpl.name }</a>
+    case ndTpl: NoDocTemplate =>
+      xml.Text(ndTpl.name)
+  }
+
+  /** Returns the HTML code that represents the templates in `tpls` as a list of hyperlinked names. */
+  def templatesToHtml(tplss: List[TemplateEntity], sep: NodeSeq): NodeSeq = tplss match {
+    case Nil         => NodeSeq.Empty
+    case tpl :: Nil  => templateToHtml(tpl)
+    case tpl :: tpls => templateToHtml(tpl) ++ sep ++ templatesToHtml(tpls, sep)
+  }
+  
+  def docEntityKindToString(ety: DocTemplateEntity) = 
+  	if (ety.isTrait) "trait" 
+  	else if (ety.isCaseClass) "case class"
+  	else if (ety.isClass) "class" 
+  	else if (ety.isObject) "object" 
+  	else if (ety.isPackage) "package"
+  	else "class"	// FIXME: an entity *should* fall into one of the above categories, but AnyRef is somehow not
+
+  /** Returns the _big image name corresponding to the DocTemplate Entity (upper left icon) */
+  def docEntityKindToBigImage(ety: DocTemplateEntity) = 
+    	if (ety.isTrait) "trait_big.png" 
+    	else if (ety.isClass) "class_big.png" 
+    	else if (ety.isObject) "object_big.png" 
+    	else if (ety.isPackage) "package_big.png"
+    	else "class_big.png"	// FIXME: an entity *should* fall into one of the above categories, but AnyRef is somehow not
+}
diff --git a/src/compiler/scala/tools/nsc/doc/html/page/Index.scala b/src/compiler/scala/tools/nsc/doc/html/page/Index.scala
new file mode 100644
index 0000000..ef95a00
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/doc/html/page/Index.scala
@@ -0,0 +1,127 @@
+/* NSC -- new Scala compiler
+ * Copyright 2007-2010 LAMP/EPFL
+ * @author  David Bernard, Manohar Jonnalagedda
+ */
+
+package scala.tools.nsc
+package doc
+package html
+package page
+
+import model._
+
+import scala.collection._
+import scala.xml._
+
+class Index(universe: Universe) extends HtmlPage {
+  
+  def path = List("index.html")
+
+  def title = {
+    val s = universe.settings
+    ( if (!s.doctitle.isDefault) s.doctitle.value else "" ) +
+    ( if (!s.docversion.isDefault) (" " + s.docversion.value) else "" )
+  }
+
+  val headers =
+    <xml:group>
+      <link href={ relativeLinkTo{List("index.css", "lib")} }  media="screen" type="text/css" rel="stylesheet"/>
+      <script type="text/javascript" src={ relativeLinkTo{List("jquery.js", "lib")} }></script>
+      <script type="text/javascript" src={ relativeLinkTo{List("jquery-ui.js", "lib")} }></script>
+      <script type="text/javascript" src={ relativeLinkTo{List("jquery.layout.js", "lib")} }></script>
+      <script type="text/javascript" src={ relativeLinkTo{List("index.js", "lib")} }></script>
+      <script type="text/javascript" src={ relativeLinkTo{List("scheduler.js", "lib")} }></script>
+    </xml:group>
+
+  val body =
+    <body>
+      <div id="library">
+        <img class='class icon' width="13" height="13" src={ relativeLinkTo{List("class.png", "lib")} }/>
+        <img class='trait icon' width="13" height="13" src={ relativeLinkTo{List("trait.png", "lib")} }/>
+        <img class='object icon' width="13" height="13" src={ relativeLinkTo{List("object.png", "lib")} }/>
+        <img class='package icon' width="13" height="13" src={ relativeLinkTo{List("package.png", "lib")} }/>
+      </div>
+      { browser }
+      <div id="content" class="ui-layout-center">
+        <iframe name="template" src={ relativeLinkTo{List("package.html")} }/>
+      </div>
+    </body>
+
+  def browser =
+    <div id="browser" class="ui-layout-west">
+      <div id="filter"></div>
+      <div class="pack" id="tpl">{
+        def isExcluded(dtpl: DocTemplateEntity) = {
+          val qname = dtpl.qualifiedName
+          ( ( qname.startsWith("scala.Tuple") || qname.startsWith("scala.Product") ||
+              qname.startsWith("scala.Function") || qname.startsWith("scala.runtime.AbstractFunction")
+            ) && !(
+              qname == "scala.Tuple1" || qname == "scala.Tuple2" ||
+              qname == "scala.Product" || qname == "scala.Product1" || qname == "scala.Product2" ||
+              qname == "scala.Function" || qname == "scala.Function1" || qname == "scala.Function2" ||
+              qname == "scala.runtime.AbstractFunction0" || qname == "scala.runtime.AbstractFunction1" ||
+              qname == "scala.runtime.AbstractFunction2"
+            )
+          )
+        }
+        def packageElem(pack: model.Package): NodeSeq = {
+          <xml:group>
+            { if (!pack.isRootPackage)
+                <h3><a class="tplshow" href={ relativeLinkTo(pack) }>{ pack.qualifiedName }</a></h3>
+              else NodeSeq.Empty
+            }
+            <ol class="templates">{
+              val tpls: Map[String, Seq[DocTemplateEntity]] =
+                (pack.templates filter (t => !t.isPackage && !isExcluded(t) )) groupBy (_.name)
+              
+              val placeholderSeq: NodeSeq = <div class="placeholder"></div>
+              
+              def createLink(entity: DocTemplateEntity, includePlaceholder: Boolean, includeText: Boolean) = {
+                val entityType = docEntityKindToString(entity)
+                val linkContent = (
+                  { if (includePlaceholder) placeholderSeq else NodeSeq.Empty }
+                  ++
+                  { if (includeText) <span class="tplLink">{ Text(packageQualifiedName(entity)) }</span> else NodeSeq.Empty }
+                )
+                <a class="tplshow" href={ relativeLinkTo(entity) }><span class={ entityType }>({ Text(entityType) })</span>{ linkContent }</a>
+              }
+
+              for (tn <- tpls.keySet.toSeq sortBy (_.toLowerCase)) yield {
+                val entities = tpls(tn)
+                val row = (entities find (e => e.isPackage || e.isObject), entities find (e => e.isTrait || e.isClass))
+
+                val itemContents = row match {
+                  case (Some(obj), None) => createLink(obj, includePlaceholder = true, includeText = true)
+
+                  case (maybeObj, Some(template)) =>
+                    val firstLink = maybeObj match {
+                      case Some(obj) => createLink(obj, includePlaceholder = false, includeText = false)
+                      case None => placeholderSeq
+                    }
+
+                    firstLink ++ createLink(template, includePlaceholder = false, includeText = true)
+
+                  case _ => // FIXME: this default case should not be necessary. For some reason AnyRef is not a package, object, trait, or class
+                    val entry = entities.head
+                    placeholderSeq ++ createLink(entry, includePlaceholder = false, includeText = true)
+                }
+
+                <li title={ entities.head.qualifiedName }>{
+                  itemContents
+                }</li>
+              }
+            }</ol>
+            <ol class="packages"> {
+              for (sp <- pack.packages sortBy (_.name.toLowerCase)) yield
+                <li class="pack" title={ sp.qualifiedName }>{ packageElem(sp) }</li>
+            }</ol>
+          </xml:group>
+        }
+        packageElem(universe.rootPackage)
+      }</div>
+    </div>
+
+  def packageQualifiedName(ety: DocTemplateEntity): String =
+    if (ety.inTemplate.isPackage) ety.name else (packageQualifiedName(ety.inTemplate) + "." + ety.name)
+
+}
diff --git a/src/compiler/scala/tools/nsc/doc/html/page/Source.scala b/src/compiler/scala/tools/nsc/doc/html/page/Source.scala
new file mode 100644
index 0000000..4109d0b
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/doc/html/page/Source.scala
@@ -0,0 +1,129 @@
+/* NSC -- new Scala compiler
+ * Copyright 2007-2010 LAMP/EPFL
+ * @author  David Bernard, Manohar Jonnalagedda
+ */
+ 
+package scala.tools.nsc
+package doc
+package html
+package page
+
+import model._
+import comment._
+import xml.{NodeSeq, Unparsed}
+import java.io.File
+
+class Source(sourceFile: File) extends HtmlPage {
+
+  val path = List("source.html")
+  
+  val title = "Scaladoc: page source"
+  
+  val headers = 
+    NodeSeq.Empty
+  
+  val body = 
+    <body>
+      <h1>Page source is not implemented yet</h1>
+    </body>
+    
+    /*
+    
+
+    def readTextFromSrcDir(subPath: String) :Option[String] = {
+      readTextFromFile(new File(sourceDir, subPath))
+    }
+    
+    def readTextFromFile(f : File) :Option[String] = {
+      if (f.exists) {
+        Some(Source.fromFile(f)(Codec.default).getLines().mkString(""))
+      } else {
+        None
+      }
+    }
+    
+
+    def writeTextToFile(f : File, txt : String, header: Option[String], footer: Option[String]) {
+      val out = new FileOutputStream(f)
+      try {
+        val enc = "UTF-8"
+        header.foreach(s => out.write(s.getBytes(enc)))
+        out.write(txt.getBytes(enc))
+        footer.foreach(s => out.write(s.getBytes(enc)))
+      } finally {
+        try {
+          out.close()
+        } catch {
+          case _ => //ignore
+        }
+      }
+    }
+    
+    trait SourceHtmlizer {
+      def scalaToHtml(src :File) : Option[File]
+    }
+
+    lazy val sourceHtmlizer : SourceHtmlizer = {
+      if (cfg.htmlizeSource) {
+        new SourceHtmlizer {
+          
+          val inDir: File = cfg.sourcedir
+          val outDir: File = cfg.outputdir
+          
+          private def relativize(uri: URI, from: URI) = linkHelper.relativize(uri, from).getOrElse("__notFound__" + uri.getPath)
+        
+          def header(dest: URI) = Some("""
+          <html>
+          <head>
+            <link href='""" + relativize(new URI("site:/_highlighter/SyntaxHighlighter.css"), dest) + """' rel='stylesheet' type='text/css'/>
+            <script language='javascript' src='""" + relativize(new URI("site:/_highlighter/shAll.js"), dest) + """'></script>
+          </head>
+          <body>
+            <pre name="code" class="scala" style="width:100%">
+        """)
+        
+          def footer(dest: URI) = Some("""</pre>
+            <script language='javascript'>
+              dp.SyntaxHighlighter.ClipboardSwf = '""" + relativize(new URI("site:/_highlighter/clipboard.swf"), dest) + """';
+              dp.SyntaxHighlighter.HighlightAll('code');
+            </script>
+          </body>
+          </html>
+        """)
+        
+          //TODO: escape the source code
+          def scalaToHtml(src :File) = {
+            val dest = new File(outDir, fileHelper.relativePathUnderDir(src, inDir) + ".html")
+            if (!dest.exists || dest.lastModified < src.lastModified) {
+              
+              //we need to verify whether the directory we are trying to write to has already been created or not
+              if(!dest.getParentFile.exists) dest.getParentFile.mkdirs
+        
+              val uri = linkHelper.uriFor(dest).get
+              var txt = fileHelper.readTextFromFile(src).getOrElse("")
+              txt = txt.replace("<", "<")
+              fileHelper.writeTextToFile(dest, txt, header(uri), footer(uri))
+            }
+            Some(dest)
+          }
+        
+          def copyResources() {
+            val loader = this.getClass().getClassLoader()
+            val buf = new Array[Byte](1024)
+            def copyResource(name: String) = fileHelper.copyResource("/scala/tools/nsc/doc/html/resource/", name, outDir, loader, buf)
+            copyResource("_highlighter/clipboard.swf")
+            copyResource("_highlighter/shAll.js")
+            copyResource("_highlighter/SyntaxHighlighter.css")
+          }
+        
+          copyResources()
+        }
+      } else {
+        new SourceHtmlizer {
+          def scalaToHtml(src :File) = None
+        }
+      }
+    }
+    */
+  
+}
diff --git a/src/compiler/scala/tools/nsc/doc/html/page/Template.scala b/src/compiler/scala/tools/nsc/doc/html/page/Template.scala
new file mode 100644
index 0000000..bad03e0
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/doc/html/page/Template.scala
@@ -0,0 +1,540 @@
+/* NSC -- new Scala compiler
+ * Copyright 2007-2010 LAMP/EPFL
+ * @author  David Bernard, Manohar Jonnalagedda
+ */
+
+package scala.tools.nsc
+package doc
+package html
+package page
+
+import model._
+
+import scala.xml.{NodeSeq, Text}
+import scala.collection.mutable.HashSet
+
+class Template(tpl: DocTemplateEntity) extends HtmlPage {
+
+  val path =
+    templateToPath(tpl)
+
+  val title =
+    tpl.qualifiedName
+
+  val headers =
+    <xml:group>
+      <link href={ relativeLinkTo{List("template.css", "lib")} } media="screen" type="text/css" rel="stylesheet"/>
+      <script type="text/javascript" src={ relativeLinkTo{List("jquery.js", "lib")} }></script>
+      <script type="text/javascript" src={ relativeLinkTo{List("jquery-ui.js", "lib")} }></script>
+      <script type="text/javascript" src={ relativeLinkTo{List("template.js", "lib")} }></script>
+      <script type="text/javascript" src={ relativeLinkTo{List("tools.tooltip.js", "lib")} }></script>
+    </xml:group>
+
+  val valueMembers =
+    (tpl.methods ::: tpl.values ::: (tpl.templates filter { tpl => tpl.isObject || tpl.isPackage })) sortBy (_.name)
+  
+  val typeMembers =
+    (tpl.abstractTypes ::: tpl.aliasTypes ::: (tpl.templates filter { tpl => tpl.isTrait || tpl.isClass })) sortBy (_.name)
+  
+  val constructors = (tpl match {
+    case cls: Class => cls.constructors
+    case _ => Nil
+  }) sortBy (_.name)
+  
+  /* for body, there is a special case for AnyRef, otherwise AnyRef appears like a package/object
+   * this problem should be fixed, this implementation is just a patch 
+   */
+  val body =
+    <body class={ if (tpl.isTrait || tpl.isClass || tpl.qualifiedName == "scala.AnyRef") "type" else "value" } onload="windowTitle();">
+
+      { if (tpl.isRootPackage || tpl.inTemplate.isRootPackage)
+          NodeSeq.Empty
+        else
+          <p id="owner">{ templatesToHtml(tpl.inTemplate.toRoot.reverse.tail, xml.Text(".")) }</p>
+      }
+
+      <div id="definition">
+        <img src={ relativeLinkTo(List(docEntityKindToBigImage(tpl), "lib")) }/>
+        <h1>{ if (tpl.isRootPackage) "root package" else tpl.name }</h1>
+      </div>
+
+      { signature(tpl, true) }
+      { memberToCommentHtml(tpl, true) }
+
+      <div id="template">
+
+        <div id="mbrsel">
+          <div id='textfilter'><span class='pre'/><span class='input'><input type='text' accesskey='/'/></span><span class='post'/></div>
+          { if (tpl.linearization.isEmpty) NodeSeq.Empty else
+              <div id="order">
+                <span class="filtertype">Ordering</span>
+                <ol><li class="alpha in">Alphabetic</li><li class="inherit out">By inheritance</li></ol>
+              </div>
+          }
+          { if (tpl.linearization.isEmpty) NodeSeq.Empty else
+              <div id="ancestors">
+                <span class="filtertype">Inherited</span>
+                <ol><li class="hideall">Hide All</li><li class="showall">Show all</li></ol>
+                <ol id="linearization">{ (tpl :: tpl.linearizationTemplates) map { wte => <li class="in" name={ wte.qualifiedName }>{ wte.name }</li> } }</ol>
+              </div>
+          }
+          {
+            <div id="visbl">
+              <span class="filtertype">Visibility</span>
+              <ol><li class="public in">Public</li><li class="all out">All</li></ol>
+            </div>
+          }
+          {
+            <div id="impl">
+              <span class="filtertype">Impl.</span>
+              <ol><li class="concrete in">Concrete</li><li class="abstract in">Abstract</li></ol>
+            </div>
+          }
+        </div>
+
+        { if (constructors.isEmpty) NodeSeq.Empty else
+            <div id="constructors" class="members">
+              <h3>Instance constructors</h3>
+              <ol>{ constructors map (memberToHtml(_)) }</ol>
+            </div>
+        }
+
+        { if (typeMembers.isEmpty) NodeSeq.Empty else
+            <div id="types" class="types members">
+              <h3>Type Members</h3>
+              <ol>{ typeMembers map (memberToHtml(_)) }</ol>
+            </div>
+        }
+
+        { if (valueMembers.isEmpty) NodeSeq.Empty else
+            <div id="values" class="values members">
+              <h3>Value Members</h3>
+              <ol>{ valueMembers map (memberToHtml(_)) }</ol>
+            </div>
+        }
+
+        {
+          NodeSeq fromSeq (for ((superTpl, superType) <- tpl.linearization) yield
+            <div class="parent" name={ superTpl.qualifiedName }>
+              <h3>Inherited from {
+                if (tpl.universe.settings.useStupidTypes.value)
+                  superTpl match {
+                    case dtpl: DocTemplateEntity =>
+                      val sig = signature(dtpl, false, true) \ "_"
+                      sig
+                    case tpl: TemplateEntity =>
+                      tpl.name
+                  }
+                else
+                  typeToHtml(superType, true)
+              }</h3>
+            </div>
+          )
+        }
+
+      </div>
+      
+      <div id="tooltip" ></div>
+      
+    </body>
+
+  def boundsToString(hi: Option[TypeEntity], lo: Option[TypeEntity]): String = {
+    def bound0(bnd: Option[TypeEntity], pre: String): String = bnd match {
+      case None => ""
+      case Some(tpe) => pre ++ tpe.toString
+    }
+    bound0(hi, "<:") ++ bound0(lo, ">:")
+  }
+
+  def tparamsToString(tpss: List[TypeParam]): String =
+    if (tpss.isEmpty) "" else {
+      def tparam0(tp: TypeParam): String =
+         tp.variance + tp.name + boundsToString(tp.hi, tp.lo)
+      def tparams0(tpss: List[TypeParam]): String = (tpss: @unchecked) match {
+        case tp :: Nil => tparam0(tp)
+        case tp :: tps => tparam0(tp) ++ ", " ++ tparams0(tps)
+      }
+      "[" + tparams0(tpss) + "]"
+    }
+
+  def defParamsToString(d: MemberEntity with Def):String = {
+    val namess = for( ps <- d.valueParams ) yield
+      for( p <- ps ) yield p.resultType.name
+    tparamsToString(d.typeParams) + namess.foldLeft("") { (s,names) => s + (names mkString("(",",",")")) }
+  }
+
+  def memberToHtml(mbr: MemberEntity): NodeSeq = {
+    val defParamsString = mbr match {
+      case d:MemberEntity with Def => defParamsToString(d)      
+      case _ => ""
+    }
+    <li name={ mbr.definitionName } visbl={ if (mbr.visibility.isProtected) "prt" else "pub" }
+      data-isabs={ mbr.isAbstract.toString }>
+      <a id={ mbr.name +defParamsString +":"+ mbr.resultType.name}/>
+      { signature(mbr, false) }
+      { memberToCommentHtml(mbr, false) }
+    </li>
+  }
+  
+  def memberToCommentHtml(mbr: MemberEntity, isSelf: Boolean): NodeSeq =
+    mbr match {
+      case dte: DocTemplateEntity if isSelf =>
+        // comment of class itself
+        <div id="comment" class="fullcomment">{ memberToCommentBodyHtml(mbr, isSelf = true) }</div>
+      case dte: DocTemplateEntity if mbr.comment.isDefined =>
+        // comment of inner, documented class (only short comment, full comment is on the class' own page)
+        memberToInlineCommentHtml(mbr, isSelf)
+      case _ =>
+        // comment of non-class member or non-documentented inner class
+        val commentBody = memberToCommentBodyHtml(mbr, isSelf = false)
+        if (commentBody.isEmpty)
+          NodeSeq.Empty
+        else {
+          <xml:group>
+            { memberToShortCommentHtml(mbr, isSelf) }
+            <div class="fullcomment">{ memberToUseCaseCommentHtml(mbr, isSelf) }{ memberToCommentBodyHtml(mbr, isSelf) }</div>
+          </xml:group>
+        }
+    }
+  
+  def memberToUseCaseCommentHtml(mbr: MemberEntity, isSelf: Boolean): NodeSeq =
+    mbr match {
+      case nte: NonTemplateMemberEntity if nte.isUseCase =>
+        inlineToHtml(comment.Text("[use case] "))
+      case _ => NodeSeq.Empty
+    }
+
+  def memberToShortCommentHtml(mbr: MemberEntity, isSelf: Boolean): NodeSeq =
+    if (mbr.comment.isEmpty)
+      NodeSeq.Empty
+    else
+      <p class="shortcomment cmt">{ memberToUseCaseCommentHtml(mbr, isSelf) }{ inlineToHtml(mbr.comment.get.short) }</p>
+
+  def memberToInlineCommentHtml(mbr: MemberEntity, isSelf: Boolean): NodeSeq =
+    <p class="comment cmt">{ inlineToHtml(mbr.comment.get.short) }</p>
+  
+  def memberToCommentBodyHtml(mbr: MemberEntity, isSelf: Boolean, isReduced: Boolean = false): NodeSeq =
+    NodeSeq.Empty ++
+    { if (mbr.comment.isEmpty) NodeSeq.Empty else
+        <div class="comment cmt">{ commentToHtml(mbr.comment) }</div>
+    } ++
+    { val prs: List[ParameterEntity] = mbr match {
+        case cls: Class => cls.typeParams ::: cls.valueParams.flatten
+        case trt: Trait => trt.typeParams
+        case dfe: Def => dfe.typeParams ::: dfe.valueParams.flatten
+        case ctr: Constructor => ctr.valueParams.flatten
+        case _ => Nil
+      }
+      def mbrCmt = mbr.comment.get
+      def paramCommentToHtml(prs: List[ParameterEntity]): NodeSeq = prs match {
+        case Nil =>
+          NodeSeq.Empty
+        case (tp: TypeParam) :: rest =>
+          val paramEntry: NodeSeq = {
+            <dt class="tparam">{ tp.name }</dt><dd class="cmt">{ bodyToHtml(mbrCmt.typeParams(tp.name)) }</dd>
+          }
+          paramEntry ++ paramCommentToHtml(rest)
+        case (vp: ValueParam) :: rest  =>
+          val paramEntry: NodeSeq = {
+            <dt class="param">{ vp.name }</dt><dd class="cmt">{ bodyToHtml(mbrCmt.valueParams(vp.name)) }</dd>
+          }
+          paramEntry ++ paramCommentToHtml(rest)
+      }
+      if (mbr.comment.isEmpty) NodeSeq.Empty
+      else {
+        val cmtedPrs = prs filter {
+          case tp: TypeParam => mbrCmt.typeParams isDefinedAt tp.name
+          case vp: ValueParam => mbrCmt.valueParams isDefinedAt vp.name
+        }
+        if (cmtedPrs.isEmpty && mbrCmt.result.isEmpty) NodeSeq.Empty
+        else
+          <dl class="paramcmts block">{
+            paramCommentToHtml(cmtedPrs) ++ (
+            mbrCmt.result match {
+              case None => NodeSeq.Empty
+              case Some(cmt) =>
+                <dt>returns</dt><dd class="cmt">{ bodyToHtml(cmt) }</dd>
+            })
+          }</dl>
+      }
+    } ++
+    { val fvs: List[comment.Paragraph] = visibility(mbr).toList ::: mbr.flags
+      if (fvs.isEmpty || isReduced) NodeSeq.Empty else
+        <div class="block">
+          attributes: { fvs map { fv => { inlineToHtml(fv.text) ++ xml.Text(" ") } } }
+        </div>
+    } ++
+    { tpl.companion match {
+        case Some(companion) if (isSelf && !isReduced) =>
+          <div class="block">
+            go to: <a href={relativeLinkTo(companion)}>companion</a>
+          </div>
+        case _ =>
+          NodeSeq.Empty
+      }
+    } ++
+    { val inDefTpls = mbr.inDefinitionTemplates
+      if ((inDefTpls.tail.isEmpty && (inDefTpls.head == mbr.inTemplate)) || isReduced) NodeSeq.Empty else {
+        <div class="block">
+          definition classes: { templatesToHtml(inDefTpls, xml.Text(" → ")) }
+        </div>
+      }
+    } ++
+    { mbr match {
+        case dtpl: DocTemplateEntity if (isSelf && !dtpl.linearization.isEmpty && !isReduced) =>
+          <div class="block">
+            linear super types: { typesToHtml(dtpl.linearizationTypes, hasLinks = true, sep = xml.Text(", ")) }
+          </div>
+        case _ => NodeSeq.Empty
+      }
+    } ++
+    { mbr match {
+        case dtpl: DocTemplateEntity if (isSelf && !dtpl.subClasses.isEmpty && !isReduced) =>
+          <div class="block">
+            known subclasses: { templatesToHtml(dtpl.subClasses, xml.Text(", ")) }
+          </div>
+        case _ => NodeSeq.Empty
+      }
+    } ++
+    { mbr match {
+        case dtpl: DocTemplateEntity if (isSelf && !dtpl.selfType.isEmpty && !isReduced) =>
+          <div class="block">
+            self type: { typeToHtml(dtpl.selfType.get, hasLinks = true) }
+          </div>
+        case _ => NodeSeq.Empty
+      }
+    } ++
+    { mbr match {
+        case dtpl: DocTemplateEntity if (isSelf && dtpl.sourceUrl.isDefined && dtpl.inSource.isDefined && !isReduced) =>
+          val (absFile, line) = dtpl.inSource.get
+          <div class="block">
+            source: { <a href={ dtpl.sourceUrl.get.toString }>{ Text(absFile.file.getName) }</a> }
+          </div>
+        case _ => NodeSeq.Empty
+      }
+    } ++
+    { if (mbr.deprecation.isEmpty || isReduced) NodeSeq.Empty else
+        <div class="block"><ol>deprecated:
+          { <li>{ bodyToHtml(mbr.deprecation.get) }</li> }
+        </ol></div>
+    } ++
+    { mbr.comment match {
+        case Some(comment) =>
+          <xml:group>
+            { if(!comment.version.isEmpty && !isReduced)
+                <div class="block"><ol>version
+                  { for(body <- comment.version.toList) yield <li>{bodyToHtml(body)}</li> }
+                </ol></div>
+              else NodeSeq.Empty
+            }
+            { if(!comment.since.isEmpty && !isReduced)
+                <div class="block"><ol>since
+                  { for(body <- comment.since.toList) yield <li>{bodyToHtml(body)}</li> }
+                </ol></div>
+              else NodeSeq.Empty
+            }
+            { if(!comment.see.isEmpty && !isReduced)
+                <div class="block"><ol>see also:
+                  { val seeXml:List[scala.xml.NodeSeq]=(for(see <- comment.see ) yield <li>{bodyToHtml(see)}</li> )
+                    seeXml.reduceLeft(_ ++ Text(", ") ++ _)
+                  }
+                </ol></div>
+              else NodeSeq.Empty
+            }
+          </xml:group>
+        case None => NodeSeq.Empty
+      }
+    }
+  
+  def kindToString(mbr: MemberEntity): String = mbr match {
+    case tpl: DocTemplateEntity => docEntityKindToString(tpl)
+    case ctor: Constructor => "new"
+    case tme: MemberEntity =>
+      ( if (tme.isImplicit) "implicit " else "" ) +
+      ( if (tme.isDef) "def"
+        else if (tme.isVal) "val"
+        else if (tme.isLazyVal) "lazy val"
+        else if (tme.isVar) "var"
+        else "type")
+  }
+  
+  def boundsToHtml(hi: Option[TypeEntity], lo: Option[TypeEntity], hasLinks: Boolean): NodeSeq = {
+    def bound0(bnd: Option[TypeEntity], pre: String): NodeSeq = bnd match {
+      case None => NodeSeq.Empty
+      case Some(tpe) => xml.Text(pre) ++ typeToHtml(tpe, hasLinks)
+    }
+    bound0(lo, " >: ") ++ bound0(hi, " <: ")
+  }
+
+  def visibility(mbr: MemberEntity): Option[comment.Paragraph] = {
+    import comment._
+    import comment.{ Text => CText }
+    mbr.visibility match {
+      case PrivateInInstance() =>
+        Some(Paragraph(CText("private[this]")))
+      case PrivateInTemplate(owner) if (owner == mbr.inTemplate) =>
+        Some(Paragraph(CText("private")))
+      case PrivateInTemplate(owner) =>
+        Some(Paragraph(Chain(List(CText("private["), EntityLink(owner), CText("]")))))
+      case ProtectedInInstance() =>
+        Some(Paragraph(CText("protected[this]")))
+      case ProtectedInTemplate(owner) if (owner == mbr.inTemplate) =>
+        Some(Paragraph(CText("protected")))
+      case ProtectedInTemplate(owner) =>
+        Some(Paragraph(Chain(List(CText("protected["), EntityLink(owner), CText("]")))))
+      case Public() =>
+        None
+    }
+  }
+    
+  /** name, tparams, params, result */
+  def signature(mbr: MemberEntity, isSelf: Boolean, isReduced: Boolean = false): NodeSeq = {
+    def inside(hasLinks: Boolean): NodeSeq =
+      <xml:group>
+      <span class="kind">{ kindToString(mbr) }</span>
+      <span class="symbol">
+        <span class={"name" + (if (mbr.deprecation.isDefined) " deprecated" else "") }>{ if (mbr.isConstructor) tpl.name else mbr.name }</span>
+        {
+          def tparamsToHtml(mbr: Entity): NodeSeq = mbr match {
+            case hk: HigherKinded =>
+              val tpss = hk.typeParams
+              if (tpss.isEmpty) NodeSeq.Empty else {
+                def tparam0(tp: TypeParam): NodeSeq =
+                  <span name={ tp.name }>{ tp.variance + tp.name }{ tparamsToHtml(tp) }{ boundsToHtml(tp.hi, tp.lo, hasLinks)}</span>
+                def tparams0(tpss: List[TypeParam]): NodeSeq = (tpss: @unchecked) match {
+                  case tp :: Nil => tparam0(tp)
+                  case tp :: tps => tparam0(tp) ++ Text(", ") ++ tparams0(tps)
+                }
+                <span class="tparams">[{ tparams0(tpss) }]</span>
+              }
+              case _ => NodeSeq.Empty
+          }
+          tparamsToHtml(mbr)
+        }
+        { if (isReduced) NodeSeq.Empty else {
+          def paramsToHtml(vlsss: List[List[ValueParam]]): NodeSeq = {
+            def param0(vl: ValueParam): NodeSeq = 
+              // notice the }{ in the next lines, they are necessary to avoid a undesired withspace in output 
+              <span name={ vl.name }>{ Text(vl.name + ": ") }{ typeToHtml(vl.resultType, hasLinks) }{
+                if(!vl.defaultValue.isEmpty) {
+                  defaultValueToHtml(vl.defaultValue.get);
+                }
+                else NodeSeq.Empty
+              }</span>
+            def params0(vlss: List[ValueParam]): NodeSeq = vlss match {
+              case Nil => NodeSeq.Empty
+              case vl :: Nil => param0(vl)
+              case vl :: vls => param0(vl) ++ Text(", ") ++ params0(vls)
+            }
+            def implicitCheck(vlss: List[ValueParam]): NodeSeq = vlss match {
+              case vl :: vls => if(vl.isImplicit) { <span class="implicit">implicit </span> } else Text("")
+              case _ => Text("")
+            }
+            vlsss map { vlss => <span class="params">({implicitCheck(vlss) ++ params0(vlss) })</span> }
+          }
+          mbr match {
+            case cls: Class => paramsToHtml(cls.valueParams)
+            case ctr: Constructor => paramsToHtml(ctr.valueParams)
+            case dfe: Def => paramsToHtml(dfe.valueParams)
+            case _ => NodeSeq.Empty
+          }
+        }}
+        { if (isReduced) NodeSeq.Empty else {
+          mbr match {
+            case tpl: DocTemplateEntity if (!tpl.isPackage) =>
+              tpl.parentType match {
+                case Some(st) => <span class="result"> extends { typeToHtml(st, hasLinks) }</span>
+                case None =>NodeSeq.Empty
+              }
+            case tme: MemberEntity if (tme.isDef || tme.isVal || tme.isLazyVal || tme.isVar) =>
+              <span class="result">: { typeToHtml(tme.resultType, hasLinks) }</span>
+            case abt: AbstractType =>
+              val b2s = boundsToHtml(abt.hi, abt.lo, hasLinks)
+              if (b2s != NodeSeq.Empty)
+                <span class="result">{ b2s }</span>
+              else NodeSeq.Empty
+            case alt: AliasType =>
+              <span class="result"> = { typeToHtml(alt.alias, hasLinks) }</span>
+            case _ => NodeSeq.Empty
+          }
+        }}
+      </span>
+      </xml:group>
+    mbr match {
+      case dte: DocTemplateEntity if !isSelf =>
+        <h4 class="signature"><a href={ relativeLinkTo(dte) }>{ inside(hasLinks = false) }</a></h4>
+      case _ if isSelf =>
+        <h4 id="signature" class="signature">{ inside(hasLinks = true) }</h4>
+      case _ =>
+        <h4 class="signature">{ inside(hasLinks = true) }</h4>      
+    }
+  }
+  
+  /** */
+  def defaultValueToHtml(defVal:TreeEntity):NodeSeq = {
+    var index = 0
+    val str = defVal.expression 
+    val length = str.length
+    var myXml: NodeSeq = NodeSeq.Empty
+    for( x <- defVal.refs) {
+      val from = x._1
+      val to = x._2._2
+      if (index < from) {
+        myXml ++= stringToXml(str.substring(index,from))
+        index = from
+      }
+      
+      if (index == from) {            
+        val member:Entity = x._2._1
+        member match {
+          case mbr: DocTemplateEntity =>
+            val link = relativeLinkTo(mbr)
+            myXml ++= <span class="name"><a href={link}>{str.substring(from, to)}</a></span>
+          case mbr: MemberEntity => 
+            val anchor = "#" + mbr.name + defParamsString(mbr) + ":" + mbr.resultType.name
+            val link = relativeLinkTo(mbr.inTemplate)
+            myXml ++= <span class="name"><a href={link ++ anchor}>{str.substring(from, to)}</a></span>
+          case _ => assert(false, "unexpected case in defaultValueToHtml")
+        }
+        index = to
+      }
+    }
+    // function used in the MemberEntity case above
+    def defParamsString(mbr: Entity):String = mbr match {
+      case d:MemberEntity with Def => defParamsToString(d)      
+      case _ => ""
+    }
+    
+    if (index <= length-1) myXml ++= stringToXml(str.substring(index, length )) 
+    
+    Text(" =") ++
+    {
+      if(length< 7) <span class="symbol">{ myXml }</span>
+      else <span class="defval" name={ myXml }>{ " ..." }</span>
+    }
+  }
+  
+  /** Makes text good looking in the html page : newlines and basic indentation, 
+   * You must change this function if you want to improve pretty printing of default Values
+   */ 
+  def stringToXml(text: String): NodeSeq = {
+    var goodLookingXml: NodeSeq = NodeSeq.Empty
+    var indent = 0
+    for(c<-text) c match {
+      case '{' => indent+=1
+        goodLookingXml ++= Text("{")
+      case '}' => indent-=1
+        goodLookingXml ++= Text("}")
+      case '\n' => 
+        goodLookingXml++= <br/> ++ indentation
+      case _ => goodLookingXml ++= Text(c.toString)
+    }
+    def indentation:NodeSeq = {
+      var indentXml = NodeSeq.Empty
+      for (x<- 1 to indent) indentXml ++=  Text("  ")
+      indentXml
+    }
+    goodLookingXml
+  }
+
+}
diff --git a/src/compiler/scala/tools/nsc/doc/html/resource/lib/class.png b/src/compiler/scala/tools/nsc/doc/html/resource/lib/class.png
new file mode 100644
index 0000000..25a8b4c
Binary files /dev/null and b/src/compiler/scala/tools/nsc/doc/html/resource/lib/class.png differ
diff --git a/src/compiler/scala/tools/nsc/doc/html/resource/lib/class_big.png b/src/compiler/scala/tools/nsc/doc/html/resource/lib/class_big.png
new file mode 100644
index 0000000..51e8595
Binary files /dev/null and b/src/compiler/scala/tools/nsc/doc/html/resource/lib/class_big.png differ
diff --git a/src/compiler/scala/tools/nsc/doc/html/resource/lib/filter_box_left.png b/src/compiler/scala/tools/nsc/doc/html/resource/lib/filter_box_left.png
new file mode 100644
index 0000000..4127dbf
Binary files /dev/null and b/src/compiler/scala/tools/nsc/doc/html/resource/lib/filter_box_left.png differ
diff --git a/src/compiler/scala/tools/nsc/doc/html/resource/lib/filter_box_left.psd b/src/compiler/scala/tools/nsc/doc/html/resource/lib/filter_box_left.psd
new file mode 100644
index 0000000..4d740f3
Binary files /dev/null and b/src/compiler/scala/tools/nsc/doc/html/resource/lib/filter_box_left.psd differ
diff --git a/src/compiler/scala/tools/nsc/doc/html/resource/lib/filter_box_right.png b/src/compiler/scala/tools/nsc/doc/html/resource/lib/filter_box_right.png
new file mode 100644
index 0000000..942736e
Binary files /dev/null and b/src/compiler/scala/tools/nsc/doc/html/resource/lib/filter_box_right.png differ
diff --git a/src/compiler/scala/tools/nsc/doc/html/resource/lib/filter_box_right.psd b/src/compiler/scala/tools/nsc/doc/html/resource/lib/filter_box_right.psd
new file mode 100644
index 0000000..63a1ae8
Binary files /dev/null and b/src/compiler/scala/tools/nsc/doc/html/resource/lib/filter_box_right.psd differ
diff --git a/src/compiler/scala/tools/nsc/doc/html/resource/lib/index.css b/src/compiler/scala/tools/nsc/doc/html/resource/lib/index.css
new file mode 100644
index 0000000..aef3f34
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/doc/html/resource/lib/index.css
@@ -0,0 +1,204 @@
+* {
+	color: inherit;
+	font-size: 10pt;
+	text-decoration: none;
+	font-family: sans-serif;
+	border-width: 0px;
+	padding: 0px;
+	margin: 0px;
+}
+
+a {
+	cursor: pointer;
+}
+
+a:hover {
+	text-decoration: underline;
+}
+
+h1 {
+	display: none;
+}
+
+#library {
+    display: none;
+}
+
+#browser {
+	top: 0px;
+	left: 0px;
+	bottom: 0px;
+	width: 100%;
+	display: block;
+	position: fixed;
+}
+
+#filter {
+	position: absolute;
+	display: block;
+	padding: 5px;
+	right: 0;
+	left: 0;
+	top: 0;
+	background-color: #B78E99;
+}
+
+#textfilter {
+	position: relative;
+	display: block;
+    height: 20px;
+	margin-bottom: 5px;
+}
+
+#textfilter > .pre {
+    display: block;
+    position: absolute;
+    top: 0;
+    left: 0;
+    height: 20px;
+    width: 20px;
+    background: url("filter_box_left.png");
+}
+
+#textfilter > .input {
+	display: block;
+    position: absolute;
+    top: 0;
+    right: 20px;
+    left: 20px;
+}
+
+#textfilter > .input > input {
+	height: 16px;
+	padding: 2px;
+	font-weight: bold;
+	color: #993300;
+	background-color: white;
+    width: 100%;
+}
+
+#textfilter > .post {
+    display: block;
+    position: absolute;
+    top: 0;
+    right: 0;
+    height: 20px;
+    width: 20px;
+    background: url("filter_box_right.png");
+}
+
+#focusfilter {
+	position: relative;
+	display: block;
+	padding: 5px;
+	background-color: pink;
+}
+
+#focusfilter .focuscoll {
+	font-weight: bold;
+}
+
+#focusfilter img {
+	bottom: -2px;
+	position: relative;
+}
+
+#kindfilter {
+	position: relative;
+	display: block;
+	padding: 5px;
+	background-color: #F0F8FF;
+}
+
+#tpl {
+	display: block;
+	position: fixed;
+	overflow: auto;
+	right: 0;
+	left: 0;
+	bottom: 0;
+	top: 5px;
+	position: absolute;
+	display: block;
+}
+
+#tpl .packhide {
+	display: block;
+	float: right;
+	font-weight: normal;
+	color: white;
+	padding: 1px 4px 1px 4px;
+}
+
+#tpl .packfocus {
+	display: block;
+	float: right;
+	font-weight: normal;
+	color: white;
+	padding: 1px 0.5em 1px 4px;
+}
+
+#tpl .packages > li > h3 {
+	display: block;
+	background-color: #2C475C;
+	color: white;
+	padding: 1px 4px 1px 0.5em;
+	font-weight: bold;
+	display: block;
+}
+
+#tpl ol > li {
+	display: block;
+}
+
+#tpl .templates > li {
+  padding-left: 0.5em;
+}
+
+#tpl ol > li .icon {
+  padding-right: 5px;
+	bottom: -2px;
+	position: relative;
+}
+
+#tpl .templates div.placeholder {
+  padding-right: 5px;
+  width: 13px;
+  display: inline-block;
+}
+
+#tpl .templates span.tplLink {
+  padding-left: 8px;
+}
+
+#content {
+	border-left-width: 1px;
+	border-left-color: black;
+	border-left-style: white;
+	right: 0px;
+	left: 0px;
+	bottom: 0px;
+	top: 0px;
+	position: fixed;
+	margin-left: 300px;
+	display: block;
+}
+
+#content > iframe {
+	display: block;
+	height: 100%;
+	width: 100%;
+}
+
+.ui-layout-pane {
+    background: #FFF;
+    overflow: auto;
+}
+
+.ui-layout-resizer {
+    background: #DDD;
+}
+
+.ui-layout-toggler {
+    background: #AAA;
+}
\ No newline at end of file
diff --git a/src/compiler/scala/tools/nsc/doc/html/resource/lib/index.js b/src/compiler/scala/tools/nsc/doc/html/resource/lib/index.js
new file mode 100644
index 0000000..21c09bf
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/doc/html/resource/lib/index.js
@@ -0,0 +1,290 @@
+// © 2009–2010 EPFL/LAMP
+// code by Gilles Dubochet with contributions by Johannes Rudolph and "spiros"
+
+var topLevelTemplates = undefined;
+var topLevelPackages = undefined;
+
+var scheduler = undefined;
+var domCache = undefined;
+
+var kindFilterState = undefined;
+var focusFilterState = undefined;
+
+var title = $(document).attr('title')
+
+$(document).ready(function() {
+    $('body').layout({ west__size: '20%' });
+    $('iframe').bind("load", function(){
+        var subtitle = $(this).contents().find('title').text();
+        $(document).attr('title', (title ? title + " - " : "") + subtitle);
+    });
+
+    // workaround for IE's iframe sizing lack of smartness
+    if($.browser.msie) {
+        function fixIFrame() {
+            $('iframe').height($(window).height() )
+        }
+        $('iframe').bind("load",fixIFrame)
+        $('iframe').bind("resize",fixIFrame)
+    }
+
+    scheduler = new Scheduler();
+    scheduler.addLabel("init", 1);
+    scheduler.addLabel("focus", 2);
+    scheduler.addLabel("kind", 3);
+    scheduler.addLabel("filter", 4);
+
+    scheduler.addForAll = function(labelName, elems, fn) {
+        var idx = 0;
+        var elem = undefined;
+        while (idx < elems.length) {
+            elem = elems[idx];
+            scheduler.add(labelName, function(elem0) { fn(elem0); }, undefined, [elem]);
+            idx = idx + 1;
+        }
+    }
+
+    domCache = new DomCache();
+    domCache.update();
+
+    prepareEntityList();
+
+    configureTextFilter();
+    configureKindFilter();
+    configureEntityList();
+
+});
+
+function configureEntityList() {
+    kindFilterSync();
+    configureHideFilter();
+    configureFocusFilter();
+    textFilter();
+}
+
+/* The DomCache class holds a series of pointers to interesting parts of the page's DOM tree. Generally, any DOM
+   accessor should be reduced to the context of a relevant entity from the cache. This is crucial to maintaining
+   decent performance of the page. */
+function DomCache() {
+    var cache = this;
+    this.packs = undefined;
+    this.liPacks = undefined;
+    this.update = function() {
+        cache.packs = $(".pack");
+        cache.liPacks = cache.packs.filter("li");
+    }
+}
+
+/* Updates the list of entities (i.e. the content of the #tpl element) from the raw form generated by Scaladoc to a
+   form suitable for display. In particular, it adds class and object etc. icons, and it configures links to open in
+   the right frame. Furthermore, it sets the two reference top-level entities lists (topLevelTemplates and
+   topLevelPackages) to serve as reference for resetting the list when needed.
+   Be advised: this function should only be called once, on page load. */
+function prepareEntityList() {
+    var classIcon = $("#library > img.class");
+    var traitIcon = $("#library > img.trait");
+    var objectIcon = $("#library > img.object");
+    var packageIcon = $("#library > img.package");
+    scheduler.addForAll("init", domCache.packs, function(pack) {
+        var packTemplates = $("> ol.templates > li", pack);
+        $("> h3 > a.tplshow", pack).add("> a.tplshow", packTemplates).attr("target", "template");
+        $("span.class", packTemplates).each(function() { $(this).replaceWith(classIcon.clone()); });
+        $("span.trait", packTemplates).each(function() { $(this).replaceWith(traitIcon.clone()); });
+        $("span.object", packTemplates).each(function() { $(this).replaceWith(objectIcon.clone()); });
+        $("span.package", packTemplates).each(function() { $(this).replaceWith(packageIcon.clone()); });
+    });
+    scheduler.add("init", function() {
+        topLevelTemplates = $("#tpl > ol.templates").clone();
+        topLevelPackages = $("#tpl > ol.packages").clone();
+    });
+}
+
+/* Configures the text filter  */
+function configureTextFilter() {
+    scheduler.add("init", function() {
+        $("#filter").append("<div id='textfilter'><span class='pre'/><span class='input'><input type='text' accesskey='/'/></span><span class='post'/></div>");
+        var input = $("#textfilter input");
+        resizeFilterBlock();
+        input.bind("keyup", function(event) {
+            if (event.keyCode == 27) { // escape
+                input.attr("value", "");
+            }
+            textFilter();
+        });
+        input.focus(function(event) { input.select(); });
+    });
+    scheduler.add("init", function() {
+        $("#textfilter > .post").click(function(){
+            $("#textfilter input").attr("value", "");
+            textFilter();
+        });
+    });
+}
+
+// Filters all focused templates and packages. This function should be made less-blocking.
+//   @param query The string of the query
+function textFilter() {
+    scheduler.clear("filter");
+    scheduler.add("filter", function() {
+        var query = $("#textfilter input").attr("value")
+        var queryRegExp;
+        if (query.toLowerCase() != query) {
+            // Regexp that matches CamelCase subbits: "BiSe" is
+            // "[a-z]*Bi[a-z]*Se" and matches "BitSet", "ABitSet", ...
+            queryRegExp = new RegExp(query.replace(/([A-Z])/g,"[a-z]*$1"));
+        }
+        else { // if query is all lower case make a normal case insensitive search
+            queryRegExp = new RegExp(query, "i");
+        }
+        scheduler.addForAll("filter", domCache.packs, function(pack0) {
+            var pack = $(pack0);
+            $("> ol.templates > li", pack).each(function(){
+                var item = $(this).attr("title");
+                if (item == "" || queryRegExp.test(item)) {
+                    $(this).show();
+                    $(this).removeClass("hide");
+                }
+                else {
+                    $(this).addClass("hide");
+                    $(this).hide();
+                }
+            });
+            if ($("> ol > li:not(.hide)", pack).length > 0) {
+                pack.show();
+                pack.removeClass("hide");
+            }
+            else {
+                pack.addClass("hide");
+                pack.hide();
+            }
+            if ($("> ol.templates > li:not(.hide)", pack).length > 0) {
+                $("> h3", pack).show();
+                $("> .packhide", pack).show();
+                $("> .packfocus", pack).show();
+            }
+            else {
+                $("> h3", pack).hide();
+                $("> .packhide", pack).hide();
+                $("> .packfocus", pack).hide();
+            }
+        });
+    });
+}
+
+/* Configures the hide tool by adding the hide link to all packages. */
+function configureHideFilter() {
+    scheduler.addForAll("init", domCache.liPacks, function(pack) {
+        $(pack).prepend("<a class='packhide'>hide</a>");
+        $("> a.packhide", pack).click(function(event) {
+            var packhide = $(this)
+            var action = packhide.text();
+            if (action == "hide") {
+                $("~ ol", packhide).hide();
+                packhide.text("show");
+            }
+            else {
+                $("~ ol", packhide).show();
+                packhide.text("hide");
+            }
+            return false;
+        });
+    });
+}
+
+/* Configures the focus tool by adding the focus bar in the filter box (initially hidden), and by adding the focus
+   link to all packages. */
+function configureFocusFilter() {
+    scheduler.add("init", function() {
+        focusFilterState = null;
+        if ($("#focusfilter").length == 0) {
+            $("#filter").append("<div id='focusfilter'>focused on <span class='focuscoll'></span> <a class='focusremove'><img class='icon' src='lib/remove.png'/></a></div>");
+            $("#focusfilter > .focusremove").click(function(event) {
+                scheduler.clear("filter");
+                scheduler.add("focus", function() {
+                    $("#tpl > ol.templates").replaceWith(topLevelTemplates.clone());
+                    $("#tpl > ol.packages").replaceWith(topLevelPackages.clone());
+                    domCache.update();
+                    $("#focusfilter").hide();
+                    $("#kindfilter").show();
+                    resizeFilterBlock();
+                    focusFilterState = null;
+                    configureEntityList();
+                });
+            });
+            $("#focusfilter").hide();
+            resizeFilterBlock();
+        }
+    });
+    scheduler.addForAll("init", domCache.liPacks, function(pack) {
+        $(pack).prepend("<a class='packfocus'>focus</a>");
+        $("> a.packfocus", pack).click(function(event) {
+            focusFilter($(this).parent());
+            return false;
+        });
+    });
+}
+
+/* Focuses the entity index on a specific package. To do so, it will copy the sub-templates and sub-packages of the
+   focuses package into the top-level templates and packages position of the index. The original top-level
+     @param package The <li> element that corresponds to the package in the entity index */
+function focusFilter(package) {
+    scheduler.add("focus", function() {
+        scheduler.clear("filter");
+        var currentFocus = package.attr("title");
+        $("#focusfilter > .focuscoll").empty();
+        $("#focusfilter > .focuscoll").append(currentFocus);
+        var packTemplates = $("> ol.templates", package);
+        var packPackages = $("> ol.packages", package);
+        $("#tpl > ol.templates").replaceWith(packTemplates);
+        $("#tpl > ol.packages").replaceWith(packPackages);
+        domCache.update();
+        $("#focusfilter").show();
+        $("#kindfilter").hide();
+        resizeFilterBlock();
+        focusFilterState = package;
+        kindFilterSync();
+    });
+}
+
+function configureKindFilter() {
+    scheduler.add("init", function() {
+        kindFilterState = "all";
+        $("#filter").append("<div id='kindfilter'><a>display packages only</a></div>");
+        $("#kindfilter > a").click(function(event) { kindFilter("packs"); });
+        resizeFilterBlock();
+    });
+}
+
+function kindFilter(kind) {
+    if (kind == "packs") {
+        kindFilterState = "packs";
+        kindFilterSync();
+        $("#kindfilter > a").replaceWith("<a>display all entities</a>");
+        $("#kindfilter > a").click(function(event) { kindFilter("all"); });
+    }
+    else {
+        kindFilterState = "all";
+        kindFilterSync();
+        $("#kindfilter > a").replaceWith("<a>display packages only</a>");
+        $("#kindfilter > a").click(function(event) { kindFilter("packs"); });
+    }
+}
+
+/* Applies the kind filter. */
+function kindFilterSync() {
+    scheduler.add("kind", function () {
+        if (kindFilterState == "all" || focusFilterState != null)
+            scheduler.addForAll("kind", domCache.packs, function(pack0) {
+                $("> ol.templates", pack0).show();
+            });
+        else
+            scheduler.addForAll("kind", domCache.packs, function(pack0) {
+                $("> ol.templates", pack0).hide();
+            });
+        textFilter();
+    });
+}
+
+function resizeFilterBlock() {
+    $("#tpl").css("top", $("#filter").outerHeight(true));
+}
diff --git a/src/compiler/scala/tools/nsc/doc/html/resource/lib/jquery-ui.js b/src/compiler/scala/tools/nsc/doc/html/resource/lib/jquery-ui.js
new file mode 100644
index 0000000..c4078dd
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/doc/html/resource/lib/jquery-ui.js
@@ -0,0 +1,401 @@
+/*!
+ * jQuery UI 1.9m2
+ *
+ * Copyright (c) 2010 AUTHORS.txt (http://jqueryui.com/about)
+ * Dual licensed under the MIT (MIT-LICENSE.txt)
+ * and GPL (GPL-LICENSE.txt) licenses.
+ *
+ * http://docs.jquery.com/UI
+ */
+(function(c){c.ui=c.ui||{};if(!c.ui.version){c.extend(c.ui,{version:"1.9m2",plugin:{add:function(a,b,d){a=c.ui[a].prototype;for(var e in d){a.plugins[e]=a.plugins[e]||[];a.plugins[e].push([b,d[e]])}},call:function(a,b,d){if((b=a.plugins[b])&&a.element[0].parentNode)for(var e=0;e<b.length;e++)a.options[b[e][0]]&&b[e][1].apply(a.element,d)}},contains:function(a,b){return document.compareDocumentPosition?a.compareDocumentPosition(b)&16:a!==b&&a.contains(b)},hasScroll:function(a,b){if(c(a).c [...]
+"hidden")return false;b=b&&b=="left"?"scrollLeft":"scrollTop";var d=false;if(a[b]>0)return true;a[b]=1;d=a[b]>0;a[b]=0;return d},isOverAxis:function(a,b,d){return a>b&&a<b+d},isOver:function(a,b,d,e,f,g){return c.ui.isOverAxis(a,d,f)&&c.ui.isOverAxis(b,e,g)},keyCode:{ALT:18,BACKSPACE:8,CAPS_LOCK:20,COMMA:188,COMMAND:91,COMMAND_LEFT:91,COMMAND_RIGHT:93,CONTROL:17,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,INSERT:45,LEFT:37,MENU:93,NUMPAD_ADD:107,NUMPAD_DECIMAL:110,NUMPAD_DIVIDE:1 [...]
+NUMPAD_MULTIPLY:106,NUMPAD_SUBTRACT:109,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SHIFT:16,SPACE:32,TAB:9,UP:38,WINDOWS:91}});c.fn.extend({_focus:c.fn.focus,focus:function(a,b){return typeof a==="number"?this.each(function(){var d=this;setTimeout(function(){c(d).focus();b&&b.call(d)},a)}):this._focus.apply(this,arguments)},enableSelection:function(){return this.attr("unselectable","off").css("MozUserSelect","")},disableSelection:function(){return this.attr("unselectable","on").css("Moz [...]
+"none")},scrollParent:function(){var a;a=c.browser.msie&&/(static|relative)/.test(this.css("position"))||/absolute/.test(this.css("position"))?this.parents().filter(function(){return/(relative|absolute|fixed)/.test(c.curCSS(this,"position",1))&&/(auto|scroll)/.test(c.curCSS(this,"overflow",1)+c.curCSS(this,"overflow-y",1)+c.curCSS(this,"overflow-x",1))}).eq(0):this.parents().filter(function(){return/(auto|scroll)/.test(c.curCSS(this,"overflow",1)+c.curCSS(this,"overflow-y",1)+c.curCSS(th [...]
+1))}).eq(0);return/fixed/.test(this.css("position"))||!a.length?c(document):a},zIndex:function(a){if(a!==undefined)return this.css("zIndex",a);if(this.length){a=c(this[0]);for(var b;a.length&&a[0]!==document;){b=a.css("position");if(b=="absolute"||b=="relative"||b=="fixed"){b=parseInt(a.css("zIndex"));if(!isNaN(b)&&b!=0)return b}a=a.parent()}}return 0}});c.extend(c.expr[":"],{data:function(a,b,d){return!!c.data(a,d[3])},focusable:function(a){var b=a.nodeName.toLowerCase(),d=c.attr(a,"tab [...]
+!a.disabled:"a"==b||"area"==b?a.href||!isNaN(d):!isNaN(d))&&!c(a)["area"==b?"parents":"closest"](":hidden").length},tabbable:function(a){var b=c.attr(a,"tabindex");return(isNaN(b)||b>=0)&&c(a).is(":focusable")}})}})(jQuery);
+(function(b){var j=b.fn.remove;b.fn.remove=function(a,c){return this.each(function(){if(!c)if(!a||b.filter(a,[this]).length)b("*",this).add(this).each(function(){b(this).triggerHandler("remove")});return j.call(b(this),a,c)})};b.widget=function(a,c,d){var e=a.split(".")[0],g;a=a.split(".")[1];g=e+"-"+a;if(!d){d=c;c=b.Widget}b.expr[":"][g]=function(f){return!!b.data(f,a)};b[e]=b[e]||{};b[e][a]=function(f,i){arguments.length&&this._createWidget(f,i)};var h=new c;h.options=b.extend({},h.opt [...]
+b.extend(true,h,{namespace:e,widgetName:a,widgetEventPrefix:b[e][a].prototype.widgetEventPrefix||a,widgetBaseClass:g,base:c.prototype},d);b.widget.bridge(a,b[e][a])};b.widget.bridge=function(a,c){b.fn[a]=function(d){var e=typeof d==="string",g=Array.prototype.slice.call(arguments,1),h=this;d=!e&&g.length?b.extend.apply(null,[true,d].concat(g)):d;if(e&&d.substring(0,1)==="_")return h;e?this.each(function(){var f=b.data(this,a),i=f&&b.isFunction(f[d])?f[d].apply(f,g):f;if(i!==f&&i!==undefi [...]
+return false}}):this.each(function(){var f=b.data(this,a);if(f){d&&f.option(d);f._init()}else b.data(this,a,new c(d,this))});return h}};b.Widget=function(a,c){arguments.length&&this._createWidget(a,c)};b.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",options:{disabled:false},_createWidget:function(a,c){this.element=b(c).data(this.widgetName,this);this.options=b.extend(true,{},this.options,b.metadata&&b.metadata.get(c)[this.widgetName],a);var d=this;this.element.bind("remove." [...]
+function(){d.destroy()});this._create();this._init()},_create:function(){},_init:function(){},_super:function(a){return this.base[a].apply(this,Array.prototype.slice.call(arguments,1))},_superApply:function(a,c){return this.base[a].apply(this,c)},destroy:function(){this.element.unbind("."+this.widgetName).removeData(this.widgetName);this.widget().unbind("."+this.widgetName).removeAttr("aria-disabled").removeClass(this.widgetBaseClass+"-disabled ui-state-disabled")},widget:function(){retu [...]
+option:function(a,c){var d=a,e=this;if(arguments.length===0)return b.extend({},e.options);if(typeof a==="string"){if(c===undefined)return this.options[a];d={};d[a]=c}b.each(d,function(g,h){e._setOption(g,h)});return e},_setOption:function(a,c){this.options[a]=c;if(a==="disabled")this.widget()[c?"addClass":"removeClass"](this.widgetBaseClass+"-disabled ui-state-disabled").attr("aria-disabled",c);return this},enable:function(){return this._setOption("disabled",false)},disable:function(){re [...]
+true)},_trigger:function(a,c,d){var e=this.options[a];c=b.Event(c);c.type=(a===this.widgetEventPrefix?a:this.widgetEventPrefix+a).toLowerCase();d=d||{};if(c.originalEvent){a=b.event.props.length;for(var g;a;){g=b.event.props[--a];c[g]=c.originalEvent[g]}}this.element.trigger(c,d);return!(b.isFunction(e)&&e.call(this.element[0],c,d)===false||c.isDefaultPrevented())}}})(jQuery);
+(function(c){c.widget("ui.mouse",{options:{cancel:":input,option",distance:1,delay:0},_mouseInit:function(){var a=this;this.element.bind("mousedown."+this.widgetName,function(b){return a._mouseDown(b)}).bind("click."+this.widgetName,function(b){if(a._preventClickEvent){a._preventClickEvent=false;b.stopImmediatePropagation();return false}});this.started=false},_mouseDestroy:function(){this.element.unbind("."+this.widgetName)},_mouseDown:function(a){a.originalEvent=a.originalEvent||{};if(! [...]
+this._mouseUp(a);this._mouseDownEvent=a;var b=this,e=a.which==1,f=typeof this.options.cancel=="string"?c(a.target).parents().add(a.target).filter(this.options.cancel).length:false;if(!e||f||!this._mouseCapture(a))return true;this.mouseDelayMet=!this.options.delay;if(!this.mouseDelayMet)this._mouseDelayTimer=setTimeout(function(){b.mouseDelayMet=true},this.options.delay);if(this._mouseDistanceMet(a)&&this._mouseDelayMet(a)){this._mouseStarted=this._mouseStart(a)!==false;if(!this._mouseSta [...]
+return true}}this._mouseMoveDelegate=function(d){return b._mouseMove(d)};this._mouseUpDelegate=function(d){return b._mouseUp(d)};c(document).bind("mousemove."+this.widgetName,this._mouseMoveDelegate).bind("mouseup."+this.widgetName,this._mouseUpDelegate);c.browser.safari||a.preventDefault();return a.originalEvent.mouseHandled=true}},_mouseMove:function(a){if(c.browser.msie&&!a.button)return this._mouseUp(a);if(this._mouseStarted){this._mouseDrag(a);return a.preventDefault()}if(this._mous [...]
+this._mouseDelayMet(a))(this._mouseStarted=this._mouseStart(this._mouseDownEvent,a)!==false)?this._mouseDrag(a):this._mouseUp(a);return!this._mouseStarted},_mouseUp:function(a){c(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate);if(this._mouseStarted){this._mouseStarted=false;this._preventClickEvent=a.target==this._mouseDownEvent.target;this._mouseStop(a)}return false},_mouseDistanceMet:function(a){return Math. [...]
+a.pageX),Math.abs(this._mouseDownEvent.pageY-a.pageY))>=this.options.distance},_mouseDelayMet:function(){return this.mouseDelayMet},_mouseStart:function(){},_mouseDrag:function(){},_mouseStop:function(){},_mouseCapture:function(){return true}})})(jQuery);
+(function(d){d.widget("ui.draggable",d.ui.mouse,{widgetEventPrefix:"drag",options:{addClasses:true,appendTo:"parent",axis:false,connectToSortable:false,containment:false,cursor:"auto",cursorAt:false,grid:false,handle:false,helper:"original",iframeFix:false,opacity:false,refreshPositions:false,revert:false,revertDuration:500,scope:"default",scroll:true,scrollSensitivity:20,scrollSpeed:20,snap:false,snapMode:"both",snapTolerance:20,stack:false,zIndex:false},_create:function(){if(this.optio [...]
+"original"&&!/^(?:r|a|f)/.test(this.element.css("position")))this.element[0].style.position="relative";this.options.addClasses&&this.element.addClass("ui-draggable");this.options.disabled&&this.element.addClass("ui-draggable-disabled");this._mouseInit()},destroy:function(){if(this.element.data("draggable")){this.element.removeData("draggable").unbind(".draggable").removeClass("ui-draggable ui-draggable-dragging ui-draggable-disabled");this._mouseDestroy();return this}},_mouseCapture:func [...]
+this.options;if(this.helper||b.disabled||d(a.target).is(".ui-resizable-handle"))return false;this.handle=this._getHandle(a);if(!this.handle)return false;return true},_mouseStart:function(a){var b=this.options;this.helper=this._createHelper(a);this._cacheHelperProportions();if(d.ui.ddmanager)d.ui.ddmanager.current=this;this._cacheMargins();this.cssPosition=this.helper.css("position");this.scrollParent=this.helper.scrollParent();this.offset=this.positionAbs=this.element.offset();this.offse [...]
+this.margins.top,left:this.offset.left-this.margins.left};d.extend(this.offset,{click:{left:a.pageX-this.offset.left,top:a.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()});this.originalPosition=this.position=this._generatePosition(a);this.originalPageX=a.pageX;this.originalPageY=a.pageY;b.cursorAt&&this._adjustOffsetFromHelper(b.cursorAt);b.containment&&this._setContainment();if(this._trigger("start",a)===false){this._clear();return false}this._c [...]
+d.ui.ddmanager&&!b.dropBehaviour&&d.ui.ddmanager.prepareOffsets(this,a);this.helper.addClass("ui-draggable-dragging");this._mouseDrag(a,true);return true},_mouseDrag:function(a,b){this.position=this._generatePosition(a);this.positionAbs=this._convertPositionTo("absolute");if(!b){b=this._uiHash();if(this._trigger("drag",a,b)===false){this._mouseUp({});return false}this.position=b.position}if(!this.options.axis||this.options.axis!="y")this.helper[0].style.left=this.position.left+"px";if(!t [...]
+this.options.axis!="x")this.helper[0].style.top=this.position.top+"px";d.ui.ddmanager&&d.ui.ddmanager.drag(this,a);return false},_mouseStop:function(a){var b=false;if(d.ui.ddmanager&&!this.options.dropBehaviour)b=d.ui.ddmanager.drop(this,a);if(this.dropped){b=this.dropped;this.dropped=false}if(!this.element[0]||!this.element[0].parentNode)return false;if(this.options.revert=="invalid"&&!b||this.options.revert=="valid"&&b||this.options.revert===true||d.isFunction(this.options.revert)&&thi [...]
+b)){var c=this;d(this.helper).animate(this.originalPosition,parseInt(this.options.revertDuration,10),function(){c._trigger("stop",a)!==false&&c._clear()})}else this._trigger("stop",a)!==false&&this._clear();return false},cancel:function(){this.helper.is(".ui-draggable-dragging")?this._mouseUp({}):this._clear();return this},_getHandle:function(a){var b=!this.options.handle||!d(this.options.handle,this.element).length?true:false;d(this.options.handle,this.element).find("*").andSelf().each( [...]
+a.target)b=true});return b},_createHelper:function(a){var b=this.options;a=d.isFunction(b.helper)?d(b.helper.apply(this.element[0],[a])):b.helper=="clone"?this.element.clone():this.element;a.parents("body").length||a.appendTo(b.appendTo=="parent"?this.element[0].parentNode:b.appendTo);a[0]!=this.element[0]&&!/(fixed|absolute)/.test(a.css("position"))&&a.css("position","absolute");return a},_adjustOffsetFromHelper:function(a){if(typeof a=="string")a=a.split(" ");if(d.isArray(a))a={left:+a [...]
+0};if("left"in a)this.offset.click.left=a.left+this.margins.left;if("right"in a)this.offset.click.left=this.helperProportions.width-a.right+this.margins.left;if("top"in a)this.offset.click.top=a.top+this.margins.top;if("bottom"in a)this.offset.click.top=this.helperProportions.height-a.bottom+this.margins.top},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var a=this.offsetParent.offset();if(this.cssPosition=="absolute"&&this.scrollParent[0]!=document&&d.ui.conta [...]
+this.offsetParent[0])){a.left+=this.scrollParent.scrollLeft();a.top+=this.scrollParent.scrollTop()}if(this.offsetParent[0]==document.body||this.offsetParent[0].tagName&&this.offsetParent[0].tagName.toLowerCase()=="html"&&d.browser.msie)a={top:0,left:0};return{top:a.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:a.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if(this.cssPosition=="relative"){var a=this.element.position( [...]
+(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:a.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}else return{top:0,left:0}},_cacheMargins:function(){this.margins={left:parseInt(this.element.css("marginLeft"),10)||0,top:parseInt(this.element.css("marginTop"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var a=this.op [...]
+"parent")a.containment=this.helper[0].parentNode;if(a.containment=="document"||a.containment=="window")this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,d(a.containment=="document"?document:window).width()-this.helperProportions.width-this.margins.left,(d(a.containment=="document"?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top];if(!/^(document|window|par [...]
+a.containment.constructor!=Array){var b=d(a.containment)[0];if(b){a=d(a.containment).offset();var c=d(b).css("overflow")!="hidden";this.containment=[a.left+(parseInt(d(b).css("borderLeftWidth"),10)||0)+(parseInt(d(b).css("paddingLeft"),10)||0)-this.margins.left,a.top+(parseInt(d(b).css("borderTopWidth"),10)||0)+(parseInt(d(b).css("paddingTop"),10)||0)-this.margins.top,a.left+(c?Math.max(b.scrollWidth,b.offsetWidth):b.offsetWidth)-(parseInt(d(b).css("borderLeftWidth"),10)||0)-(parseInt(d( [...]
+10)||0)-this.helperProportions.width-this.margins.left,a.top+(c?Math.max(b.scrollHeight,b.offsetHeight):b.offsetHeight)-(parseInt(d(b).css("borderTopWidth"),10)||0)-(parseInt(d(b).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top]}}else if(a.containment.constructor==Array)this.containment=a.containment},_convertPositionTo:function(a,b){if(!b)b=this.position;a=a=="absolute"?1:-1;var c=this.cssPosition=="absolute"&&!(this.scrollParent[0]!=document&&d.ui.contains(t [...]
+this.offsetParent[0]))?this.offsetParent:this.scrollParent,f=/(html|body)/i.test(c[0].tagName);return{top:b.top+this.offset.relative.top*a+this.offset.parent.top*a-(d.browser.safari&&d.browser.version<526&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():f?0:c.scrollTop())*a),left:b.left+this.offset.relative.left*a+this.offset.parent.left*a-(d.browser.safari&&d.browser.version<526&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollPar [...]
+f?0:c.scrollLeft())*a)}},_generatePosition:function(a){var b=this.options,c=this.cssPosition=="absolute"&&!(this.scrollParent[0]!=document&&d.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,f=/(html|body)/i.test(c[0].tagName),e=a.pageX,g=a.pageY;if(this.originalPosition){if(this.containment){if(a.pageX-this.offset.click.left<this.containment[0])e=this.containment[0]+this.offset.click.left;if(a.pageY-this.offset.click.top<this.containment[1])g=t [...]
+this.offset.click.top;if(a.pageX-this.offset.click.left>this.containment[2])e=this.containment[2]+this.offset.click.left;if(a.pageY-this.offset.click.top>this.containment[3])g=this.containment[3]+this.offset.click.top}if(b.grid){g=this.originalPageY+Math.round((g-this.originalPageY)/b.grid[1])*b.grid[1];g=this.containment?!(g-this.offset.click.top<this.containment[1]||g-this.offset.click.top>this.containment[3])?g:!(g-this.offset.click.top<this.containment[1])?g-b.grid[1]:g+b.grid[1]:g;e [...]
+Math.round((e-this.originalPageX)/b.grid[0])*b.grid[0];e=this.containment?!(e-this.offset.click.left<this.containment[0]||e-this.offset.click.left>this.containment[2])?e:!(e-this.offset.click.left<this.containment[0])?e-b.grid[0]:e+b.grid[0]:e}}return{top:g-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+(d.browser.safari&&d.browser.version<526&&this.cssPosition=="fixed"?0:this.cssPosition=="fixed"?-this.scrollParent.scrollTop():f?0:c.scrollTop()),left:e-this.offset [...]
+this.offset.relative.left-this.offset.parent.left+(d.browser.safari&&d.browser.version<526&&this.cssPosition=="fixed"?0:this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():f?0:c.scrollLeft())}},_clear:function(){this.helper.removeClass("ui-draggable-dragging");this.helper[0]!=this.element[0]&&!this.cancelHelperRemoval&&this.helper.remove();this.helper=null;this.cancelHelperRemoval=false},_trigger:function(a,b,c){c=c||this._uiHash();d.ui.plugin.call(this,a,[b,c]);if(a=="drag")this.p [...]
+this._convertPositionTo("absolute");return d.Widget.prototype._trigger.call(this,a,b,c)},plugins:{},_uiHash:function(){return{helper:this.helper,position:this.position,originalPosition:this.originalPosition,offset:this.positionAbs}}});d.extend(d.ui.draggable,{version:"1.9m2"});d.ui.plugin.add("draggable","connectToSortable",{start:function(a,b){var c=d(this).data("draggable"),f=c.options,e=d.extend({},b,{item:c.element});c.sortables=[];d(f.connectToSortable).each(function(){var g=d.data( [...]
+if(g&&!g.options.disabled){c.sortables.push({instance:g,shouldRevert:g.options.revert});g._refreshItems();g._trigger("activate",a,e)}})},stop:function(a,b){var c=d(this).data("draggable"),f=d.extend({},b,{item:c.element});d.each(c.sortables,function(){if(this.instance.isOver){this.instance.isOver=0;c.cancelHelperRemoval=true;this.instance.cancelHelperRemoval=false;if(this.shouldRevert)this.instance.options.revert=true;this.instance._mouseStop(a);this.instance.options.helper=this.instance [...]
+c.options.helper=="original"&&this.instance.currentItem.css({top:"auto",left:"auto"})}else{this.instance.cancelHelperRemoval=false;this.instance._trigger("deactivate",a,f)}})},drag:function(a,b){var c=d(this).data("draggable"),f=this;d.each(c.sortables,function(){this.instance.positionAbs=c.positionAbs;this.instance.helperProportions=c.helperProportions;this.instance.offset.click=c.offset.click;if(this.instance._intersectsWith(this.instance.containerCache)){if(!this.instance.isOver){this [...]
+1;this.instance.currentItem=d(f).clone().appendTo(this.instance.element).data("sortable-item",true);this.instance.options._helper=this.instance.options.helper;this.instance.options.helper=function(){return b.helper[0]};a.target=this.instance.currentItem[0];this.instance._mouseCapture(a,true);this.instance._mouseStart(a,true,true);this.instance.offset.click.top=c.offset.click.top;this.instance.offset.click.left=c.offset.click.left;this.instance.offset.parent.left-=c.offset.parent.left-thi [...]
+this.instance.offset.parent.top-=c.offset.parent.top-this.instance.offset.parent.top;c._trigger("toSortable",a);c.dropped=this.instance.element;c.currentItem=c.element;this.instance.fromOutside=c}this.instance.currentItem&&this.instance._mouseDrag(a)}else if(this.instance.isOver){this.instance.isOver=0;this.instance.cancelHelperRemoval=true;this.instance.options.revert=false;this.instance._trigger("out",a,this.instance._uiHash(this.instance));this.instance._mouseStop(a,true);this.instanc [...]
+this.instance.options._helper;this.instance.currentItem.remove();this.instance.placeholder&&this.instance.placeholder.remove();c._trigger("fromSortable",a);c.dropped=false}})}});d.ui.plugin.add("draggable","cursor",{start:function(){var a=d("body"),b=d(this).data("draggable").options;if(a.css("cursor"))b._cursor=a.css("cursor");a.css("cursor",b.cursor)},stop:function(){var a=d(this).data("draggable").options;a._cursor&&d("body").css("cursor",a._cursor)}});d.ui.plugin.add("draggable","ifr [...]
+d(this).data("draggable").options;d(a.iframeFix===true?"iframe":a.iframeFix).each(function(){d('<div class="ui-draggable-iframeFix" style="background: #fff;"></div>').css({width:this.offsetWidth+"px",height:this.offsetHeight+"px",position:"absolute",opacity:"0.001",zIndex:1E3}).css(d(this).offset()).appendTo("body")})},stop:function(){d("div.ui-draggable-iframeFix").each(function(){this.parentNode.removeChild(this)})}});d.ui.plugin.add("draggable","opacity",{start:function(a,b){a=d(b.hel [...]
+if(a.css("opacity"))b._opacity=a.css("opacity");a.css("opacity",b.opacity)},stop:function(a,b){a=d(this).data("draggable").options;a._opacity&&d(b.helper).css("opacity",a._opacity)}});d.ui.plugin.add("draggable","scroll",{start:function(){var a=d(this).data("draggable");if(a.scrollParent[0]!=document&&a.scrollParent[0].tagName!="HTML")a.overflowOffset=a.scrollParent.offset()},drag:function(a){var b=d(this).data("draggable"),c=b.options,f=false;if(b.scrollParent[0]!=document&&b.scrollPare [...]
+"HTML"){if(!c.axis||c.axis!="x")if(b.overflowOffset.top+b.scrollParent[0].offsetHeight-a.pageY<c.scrollSensitivity)b.scrollParent[0].scrollTop=f=b.scrollParent[0].scrollTop+c.scrollSpeed;else if(a.pageY-b.overflowOffset.top<c.scrollSensitivity)b.scrollParent[0].scrollTop=f=b.scrollParent[0].scrollTop-c.scrollSpeed;if(!c.axis||c.axis!="y")if(b.overflowOffset.left+b.scrollParent[0].offsetWidth-a.pageX<c.scrollSensitivity)b.scrollParent[0].scrollLeft=f=b.scrollParent[0].scrollLeft+c.scrollS [...]
+b.overflowOffset.left<c.scrollSensitivity)b.scrollParent[0].scrollLeft=f=b.scrollParent[0].scrollLeft-c.scrollSpeed}else{if(!c.axis||c.axis!="x")if(a.pageY-d(document).scrollTop()<c.scrollSensitivity)f=d(document).scrollTop(d(document).scrollTop()-c.scrollSpeed);else if(d(window).height()-(a.pageY-d(document).scrollTop())<c.scrollSensitivity)f=d(document).scrollTop(d(document).scrollTop()+c.scrollSpeed);if(!c.axis||c.axis!="y")if(a.pageX-d(document).scrollLeft()<c.scrollSensitivity)f=d(d [...]
+c.scrollSpeed);else if(d(window).width()-(a.pageX-d(document).scrollLeft())<c.scrollSensitivity)f=d(document).scrollLeft(d(document).scrollLeft()+c.scrollSpeed)}f!==false&&d.ui.ddmanager&&!c.dropBehaviour&&d.ui.ddmanager.prepareOffsets(b,a)}});d.ui.plugin.add("draggable","snap",{start:function(){var a=d(this).data("draggable"),b=a.options;a.snapElements=[];d(b.snap.constructor!=String?b.snap.items||":data(draggable)":b.snap).each(function(){var c=d(this),f=c.offset();this!=a.element[0]&& [...]
+width:c.outerWidth(),height:c.outerHeight(),top:f.top,left:f.left})})},drag:function(a,b){for(var c=d(this).data("draggable"),f=c.options,e=f.snapTolerance,g=b.offset.left,n=g+c.helperProportions.width,m=b.offset.top,o=m+c.helperProportions.height,h=c.snapElements.length-1;h>=0;h--){var i=c.snapElements[h].left,k=i+c.snapElements[h].width,j=c.snapElements[h].top,l=j+c.snapElements[h].height;if(i-e<g&&g<k+e&&j-e<m&&m<l+e||i-e<g&&g<k+e&&j-e<o&&o<l+e||i-e<n&&n<k+e&&j-e<m&&m<l+e||i-e<n&&n<k+ [...]
+o<l+e){if(f.snapMode!="inner"){var p=Math.abs(j-o)<=e,q=Math.abs(l-m)<=e,r=Math.abs(i-n)<=e,s=Math.abs(k-g)<=e;if(p)b.position.top=c._convertPositionTo("relative",{top:j-c.helperProportions.height,left:0}).top-c.margins.top;if(q)b.position.top=c._convertPositionTo("relative",{top:l,left:0}).top-c.margins.top;if(r)b.position.left=c._convertPositionTo("relative",{top:0,left:i-c.helperProportions.width}).left-c.margins.left;if(s)b.position.left=c._convertPositionTo("relative",{top:0,left:k} [...]
+p||q||r||s;if(f.snapMode!="outer"){p=Math.abs(j-m)<=e;q=Math.abs(l-o)<=e;r=Math.abs(i-g)<=e;s=Math.abs(k-n)<=e;if(p)b.position.top=c._convertPositionTo("relative",{top:j,left:0}).top-c.margins.top;if(q)b.position.top=c._convertPositionTo("relative",{top:l-c.helperProportions.height,left:0}).top-c.margins.top;if(r)b.position.left=c._convertPositionTo("relative",{top:0,left:i}).left-c.margins.left;if(s)b.position.left=c._convertPositionTo("relative",{top:0,left:k-c.helperProportions.width} [...]
+(p||q||r||s||t))c.options.snap.snap&&c.options.snap.snap.call(c.element,a,d.extend(c._uiHash(),{snapItem:c.snapElements[h].item}));c.snapElements[h].snapping=p||q||r||s||t}else{c.snapElements[h].snapping&&c.options.snap.release&&c.options.snap.release.call(c.element,a,d.extend(c._uiHash(),{snapItem:c.snapElements[h].item}));c.snapElements[h].snapping=false}}}});d.ui.plugin.add("draggable","stack",{start:function(){var a=d(this).data("draggable").options;a=d.makeArray(d(a.stack)).sort(fun [...]
+10)||0)-(parseInt(d(f).css("zIndex"),10)||0)});if(a.length){var b=parseInt(a[0].style.zIndex)||0;d(a).each(function(c){this.style.zIndex=b+c});this[0].style.zIndex=b+a.length}}});d.ui.plugin.add("draggable","zIndex",{start:function(a,b){a=d(b.helper);b=d(this).data("draggable").options;if(a.css("zIndex"))b._zIndex=a.css("zIndex");a.css("zIndex",b.zIndex)},stop:function(a,b){a=d(this).data("draggable").options;a._zIndex&&d(b.helper).css("zIndex",a._zIndex)}})})(jQuery);
+(function(d){d.widget("ui.droppable",{widgetEventPrefix:"drop",options:{accept:"*",activeClass:false,addClasses:true,greedy:false,hoverClass:false,scope:"default",tolerance:"intersect"},_create:function(){var a=this.options,b=a.accept;this.isover=0;this.isout=1;this.accept=d.isFunction(b)?b:function(c){return c.is(b)};this.proportions={width:this.element[0].offsetWidth,height:this.element[0].offsetHeight};d.ui.ddmanager.droppables[a.scope]=d.ui.ddmanager.droppables[a.scope]||[];d.ui.ddma [...]
+a.addClasses&&this.element.addClass("ui-droppable")},destroy:function(){for(var a=d.ui.ddmanager.droppables[this.options.scope],b=0;b<a.length;b++)a[b]==this&&a.splice(b,1);this.element.removeClass("ui-droppable ui-droppable-disabled").removeData("droppable").unbind(".droppable");return this},_setOption:function(a,b){if(a=="accept")this.accept=d.isFunction(b)?b:function(c){return c.is(b)};d.Widget.prototype._setOption.apply(this,arguments)},_activate:function(a){var b=d.ui.ddmanager.curr [...]
+this.element.addClass(this.options.activeClass);b&&this._trigger("activate",a,this.ui(b))},_deactivate:function(a){var b=d.ui.ddmanager.current;this.options.activeClass&&this.element.removeClass(this.options.activeClass);b&&this._trigger("deactivate",a,this.ui(b))},_over:function(a){var b=d.ui.ddmanager.current;if(!(!b||(b.currentItem||b.element)[0]==this.element[0]))if(this.accept.call(this.element[0],b.currentItem||b.element)){this.options.hoverClass&&this.element.addClass(this.options [...]
+this._trigger("over",a,this.ui(b))}},_out:function(a){var b=d.ui.ddmanager.current;if(!(!b||(b.currentItem||b.element)[0]==this.element[0]))if(this.accept.call(this.element[0],b.currentItem||b.element)){this.options.hoverClass&&this.element.removeClass(this.options.hoverClass);this._trigger("out",a,this.ui(b))}},_drop:function(a,b){var c=b||d.ui.ddmanager.current;if(!c||(c.currentItem||c.element)[0]==this.element[0])return false;var e=false;this.element.find(":data(droppable)").not(".ui- [...]
+d.data(this,"droppable");if(g.options.greedy&&!g.options.disabled&&g.options.scope==c.options.scope&&g.accept.call(g.element[0],c.currentItem||c.element)&&d.ui.intersect(c,d.extend(g,{offset:g.element.offset()}),g.options.tolerance)){e=true;return false}});if(e)return false;if(this.accept.call(this.element[0],c.currentItem||c.element)){this.options.activeClass&&this.element.removeClass(this.options.activeClass);this.options.hoverClass&&this.element.removeClass(this.options.hoverClass);th [...]
+a,this.ui(c));return this.element}return false},ui:function(a){return{draggable:a.currentItem||a.element,helper:a.helper,position:a.position,offset:a.positionAbs}}});d.extend(d.ui.droppable,{version:"1.9m2"});d.ui.intersect=function(a,b,c){if(!b.offset)return false;var e=(a.positionAbs||a.position.absolute).left,g=e+a.helperProportions.width,f=(a.positionAbs||a.position.absolute).top,h=f+a.helperProportions.height,i=b.offset.left,k=i+b.proportions.width,j=b.offset.top,l=j+b.proportions.height;
+switch(c){case "fit":return i<e&&g<k&&j<f&&h<l;case "intersect":return i<e+a.helperProportions.width/2&&g-a.helperProportions.width/2<k&&j<f+a.helperProportions.height/2&&h-a.helperProportions.height/2<l;case "pointer":return d.ui.isOver((a.positionAbs||a.position.absolute).top+(a.clickOffset||a.offset.click).top,(a.positionAbs||a.position.absolute).left+(a.clickOffset||a.offset.click).left,j,i,b.proportions.height,b.proportions.width);case "touch":return(f>=j&&f<=l||h>=j&&h<=l||f<j&&h>l [...]
+e<=k||g>=i&&g<=k||e<i&&g>k);default:return false}};d.ui.ddmanager={current:null,droppables:{"default":[]},prepareOffsets:function(a,b){var c=d.ui.ddmanager.droppables[a.options.scope]||[],e=b?b.type:null,g=(a.currentItem||a.element).find(":data(droppable)").andSelf(),f=0;a:for(;f<c.length;f++)if(!(c[f].options.disabled||a&&!c[f].accept.call(c[f].element[0],a.currentItem||a.element))){for(var h=0;h<g.length;h++)if(g[h]==c[f].element[0]){c[f].proportions.height=0;continue a}c[f].visible=c[ [...]
+"none";if(c[f].visible){c[f].offset=c[f].element.offset();c[f].proportions={width:c[f].element[0].offsetWidth,height:c[f].element[0].offsetHeight};e=="mousedown"&&c[f]._activate.call(c[f],b)}}},drop:function(a,b){var c=false;d.each(d.ui.ddmanager.droppables[a.options.scope]||[],function(){if(this.options){if(!this.options.disabled&&this.visible&&d.ui.intersect(a,this,this.options.tolerance))c=c||this._drop.call(this,b);if(!this.options.disabled&&this.visible&&this.accept.call(this.elemen [...]
+a.element)){this.isout=1;this.isover=0;this._deactivate.call(this,b)}}});return c},drag:function(a,b){a.options.refreshPositions&&d.ui.ddmanager.prepareOffsets(a,b);d.each(d.ui.ddmanager.droppables[a.options.scope]||[],function(){if(!(this.options.disabled||this.greedyChild||!this.visible)){var c=d.ui.intersect(a,this,this.options.tolerance);if(c=!c&&this.isover==1?"isout":c&&this.isover==0?"isover":null){var e;if(this.options.greedy){var g=this.element.parents(":data(droppable):eq(0)"); [...]
+d.data(g[0],"droppable");e.greedyChild=c=="isover"?1:0}}if(e&&c=="isover"){e.isover=0;e.isout=1;e._out.call(e,b)}this[c]=1;this[c=="isout"?"isover":"isout"]=0;this[c=="isover"?"_over":"_out"].call(this,b);if(e&&c=="isout"){e.isout=0;e.isover=1;e._over.call(e,b)}}}})}}})(jQuery);
+(function(e){e.widget("ui.resizable",e.ui.mouse,{widgetEventPrefix:"resize",options:{alsoResize:false,animate:false,animateDuration:"slow",animateEasing:"swing",aspectRatio:false,autoHide:false,containment:false,ghost:false,grid:false,handles:"e,s,se",helper:false,maxHeight:null,maxWidth:null,minHeight:10,minWidth:10,zIndex:1E3},_create:function(){var b=this,a=this.options;this.element.addClass("ui-resizable");e.extend(this,{_aspectRatio:!!a.aspectRatio,aspectRatio:a.aspectRatio,original [...]
+_proportionallyResizeElements:[],_helper:a.helper||a.ghost||a.animate?a.helper||"ui-resizable-helper":null});if(this.element[0].nodeName.match(/canvas|textarea|input|select|button|img/i)){/relative/.test(this.element.css("position"))&&e.browser.opera&&this.element.css({position:"relative",top:"auto",left:"auto"});this.element.wrap(e('<div class="ui-wrapper" style="overflow: hidden;"></div>').css({position:this.element.css("position"),width:this.element.outerWidth(),height:this.element.ou [...]
+top:this.element.css("top"),left:this.element.css("left")}));this.element=this.element.parent().data("resizable",this.element.data("resizable"));this.elementIsWrapper=true;this.element.css({marginLeft:this.originalElement.css("marginLeft"),marginTop:this.originalElement.css("marginTop"),marginRight:this.originalElement.css("marginRight"),marginBottom:this.originalElement.css("marginBottom")});this.originalElement.css({marginLeft:0,marginTop:0,marginRight:0,marginBottom:0});this.originalR [...]
+this.originalElement.css("resize");this.originalElement.css("resize","none");this._proportionallyResizeElements.push(this.originalElement.css({position:"static",zoom:1,display:"block"}));this.originalElement.css({margin:this.originalElement.css("margin")});this._proportionallyResize()}this.handles=a.handles||(!e(".ui-resizable-handle",this.element).length?"e,s,se":{n:".ui-resizable-n",e:".ui-resizable-e",s:".ui-resizable-s",w:".ui-resizable-w",se:".ui-resizable-se",sw:".ui-resizable-sw", [...]
+nw:".ui-resizable-nw"});if(this.handles.constructor==String){if(this.handles=="all")this.handles="n,e,s,w,se,sw,ne,nw";var c=this.handles.split(",");this.handles={};for(var d=0;d<c.length;d++){var f=e.trim(c[d]),g=e('<div class="ui-resizable-handle '+("ui-resizable-"+f)+'"></div>');/sw|se|ne|nw/.test(f)&&g.css({zIndex:++a.zIndex});"se"==f&&g.addClass("ui-icon ui-icon-gripsmall-diagonal-se");this.handles[f]=".ui-resizable-"+f;this.element.append(g)}}this._renderAxis=function(h){h=h||this. [...]
+String)this.handles[i]=e(this.handles[i],this.element).show();if(this.elementIsWrapper&&this.originalElement[0].nodeName.match(/textarea|input|select|button/i)){var j=e(this.handles[i],this.element),k=0;k=/sw|ne|nw|se|n|s/.test(i)?j.outerHeight():j.outerWidth();j=["padding",/ne|nw|n/.test(i)?"Top":/se|sw|s/.test(i)?"Bottom":/^e$/.test(i)?"Right":"Left"].join("");h.css(j,k);this._proportionallyResize()}e(this.handles[i])}};this._renderAxis(this.element);this._handles=e(".ui-resizable-hand [...]
+this._handles.mouseover(function(){if(!b.resizing){if(this.className)var h=this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i);b.axis=h&&h[1]?h[1]:"se"}});if(a.autoHide){this._handles.hide();e(this.element).addClass("ui-resizable-autohide").hover(function(){e(this).removeClass("ui-resizable-autohide");b._handles.show()},function(){if(!b.resizing){e(this).addClass("ui-resizable-autohide");b._handles.hide()}})}this._mouseInit()},destroy:function(){this._mouseDestroy();var b=functio [...]
+if(this.elementIsWrapper){b(this.element);var a=this.element;a.after(this.originalElement.css({position:a.css("position"),width:a.outerWidth(),height:a.outerHeight(),top:a.css("top"),left:a.css("left")})).remove()}this.originalElement.css("resize",this.originalResizeStyle);b(this.originalElement);return this},_mouseCapture:function(b){var a=false;for(var c in this.handles)if(e(this.handles[c])[0]==b.target)a=true;return!this.options.disabled&&a},_mouseStart:function(b){var a=this.options [...]
+d=this.element;this.resizing=true;this.documentScroll={top:e(document).scrollTop(),left:e(document).scrollLeft()};if(d.is(".ui-draggable")||/absolute/.test(d.css("position")))d.css({position:"absolute",top:c.top,left:c.left});e.browser.opera&&/relative/.test(d.css("position"))&&d.css({position:"relative",top:"auto",left:"auto"});this._renderProxy();c=m(this.helper.css("left"));var f=m(this.helper.css("top"));if(a.containment){c+=e(a.containment).scrollLeft()||0;f+=e(a.containment).scroll [...]
+this.helper.offset();this.position={left:c,top:f};this.size=this._helper?{width:d.outerWidth(),height:d.outerHeight()}:{width:d.width(),height:d.height()};this.originalSize=this._helper?{width:d.outerWidth(),height:d.outerHeight()}:{width:d.width(),height:d.height()};this.originalPosition={left:c,top:f};this.sizeDiff={width:d.outerWidth()-d.width(),height:d.outerHeight()-d.height()};this.originalMousePosition={left:b.pageX,top:b.pageY};this.aspectRatio=typeof a.aspectRatio=="number"?a.as [...]
+this.originalSize.width/this.originalSize.height||1;a=e(".ui-resizable-"+this.axis).css("cursor");e("body").css("cursor",a=="auto"?this.axis+"-resize":a);d.addClass("ui-resizable-resizing");this._propagate("start",b);return true},_mouseDrag:function(b){var a=this.helper,c=this.originalMousePosition,d=this._change[this.axis];if(!d)return false;c=d.apply(this,[b,b.pageX-c.left||0,b.pageY-c.top||0]);if(this._aspectRatio||b.shiftKey)c=this._updateRatio(c,b);c=this._respectSize(c,b);this._pro [...]
+b);a.css({top:this.position.top+"px",left:this.position.left+"px",width:this.size.width+"px",height:this.size.height+"px"});!this._helper&&this._proportionallyResizeElements.length&&this._proportionallyResize();this._updateCache(c);this._trigger("resize",b,this.ui());return false},_mouseStop:function(b){this.resizing=false;var a=this.options,c=this;if(this._helper){var d=this._proportionallyResizeElements,f=d.length&&/textarea/i.test(d[0].nodeName);d=f&&e.ui.hasScroll(d[0],"left")?0:c.si [...]
+f={width:c.size.width-(f?0:c.sizeDiff.width),height:c.size.height-d};d=parseInt(c.element.css("left"),10)+(c.position.left-c.originalPosition.left)||null;var g=parseInt(c.element.css("top"),10)+(c.position.top-c.originalPosition.top)||null;a.animate||this.element.css(e.extend(f,{top:g,left:d}));c.helper.height(c.size.height);c.helper.width(c.size.width);this._helper&&!a.animate&&this._proportionallyResize()}e("body").css("cursor","auto");this.element.removeClass("ui-resizable-resizing"); [...]
+b);this._helper&&this.helper.remove();return false},_updateCache:function(b){this.offset=this.helper.offset();if(l(b.left))this.position.left=b.left;if(l(b.top))this.position.top=b.top;if(l(b.height))this.size.height=b.height;if(l(b.width))this.size.width=b.width},_updateRatio:function(b){var a=this.position,c=this.size,d=this.axis;if(b.height)b.width=c.height*this.aspectRatio;else if(b.width)b.height=c.width/this.aspectRatio;if(d=="sw"){b.left=a.left+(c.width-b.width);b.top=null}if(d==" [...]
+a.top+(c.height-b.height);b.left=a.left+(c.width-b.width)}return b},_respectSize:function(b){var a=this.options,c=this.axis,d=l(b.width)&&a.maxWidth&&a.maxWidth<b.width,f=l(b.height)&&a.maxHeight&&a.maxHeight<b.height,g=l(b.width)&&a.minWidth&&a.minWidth>b.width,h=l(b.height)&&a.minHeight&&a.minHeight>b.height;if(g)b.width=a.minWidth;if(h)b.height=a.minHeight;if(d)b.width=a.maxWidth;if(f)b.height=a.maxHeight;var i=this.originalPosition.left+this.originalSize.width,j=this.position.top+thi [...]
+k=/sw|nw|w/.test(c);c=/nw|ne|n/.test(c);if(g&&k)b.left=i-a.minWidth;if(d&&k)b.left=i-a.maxWidth;if(h&&c)b.top=j-a.minHeight;if(f&&c)b.top=j-a.maxHeight;if((a=!b.width&&!b.height)&&!b.left&&b.top)b.top=null;else if(a&&!b.top&&b.left)b.left=null;return b},_proportionallyResize:function(){if(this._proportionallyResizeElements.length)for(var b=this.helper||this.element,a=0;a<this._proportionallyResizeElements.length;a++){var c=this._proportionallyResizeElements[a];if(!this.borderDif){var d=[ [...]
+c.css("borderRightWidth"),c.css("borderBottomWidth"),c.css("borderLeftWidth")],f=[c.css("paddingTop"),c.css("paddingRight"),c.css("paddingBottom"),c.css("paddingLeft")];this.borderDif=e.map(d,function(g,h){g=parseInt(g,10)||0;h=parseInt(f[h],10)||0;return g+h})}e.browser.msie&&(e(b).is(":hidden")||e(b).parents(":hidden").length)||c.css({height:b.height()-this.borderDif[0]-this.borderDif[2]||0,width:b.width()-this.borderDif[1]-this.borderDif[3]||0})}},_renderProxy:function(){var b=this.op [...]
+this.element.offset();if(this._helper){this.helper=this.helper||e('<div style="overflow:hidden;"></div>');var a=e.browser.msie&&e.browser.version<7,c=a?1:0;a=a?2:-1;this.helper.addClass(this._helper).css({width:this.element.outerWidth()+a,height:this.element.outerHeight()+a,position:"absolute",left:this.elementOffset.left-c+"px",top:this.elementOffset.top-c+"px",zIndex:++b.zIndex});this.helper.appendTo("body").disableSelection()}else this.helper=this.element},_change:{e:function(b,a){ret [...]
+a}},w:function(b,a){return{left:this.originalPosition.left+a,width:this.originalSize.width-a}},n:function(b,a,c){return{top:this.originalPosition.top+c,height:this.originalSize.height-c}},s:function(b,a,c){return{height:this.originalSize.height+c}},se:function(b,a,c){return e.extend(this._change.s.apply(this,arguments),this._change.e.apply(this,[b,a,c]))},sw:function(b,a,c){return e.extend(this._change.s.apply(this,arguments),this._change.w.apply(this,[b,a,c]))},ne:function(b,a,c){return [...]
+arguments),this._change.e.apply(this,[b,a,c]))},nw:function(b,a,c){return e.extend(this._change.n.apply(this,arguments),this._change.w.apply(this,[b,a,c]))}},_propagate:function(b,a){e.ui.plugin.call(this,b,[a,this.ui()]);b!="resize"&&this._trigger(b,a,this.ui())},plugins:{},ui:function(){return{originalElement:this.originalElement,element:this.element,helper:this.helper,position:this.position,size:this.size,originalSize:this.originalSize,originalPosition:this.originalPosition}}});e.exte [...]
+{version:"1.9m2"});e.ui.plugin.add("resizable","alsoResize",{start:function(){var b=e(this).data("resizable").options,a=function(c){e(c).each(function(){var d=e(this);d.data("resizable-alsoresize",{width:parseInt(d.width(),10),height:parseInt(d.height(),10),left:parseInt(d.css("left"),10),top:parseInt(d.css("top"),10),position:d.css("position")})})};if(typeof b.alsoResize=="object"&&!b.alsoResize.parentNode)if(b.alsoResize.length){b.alsoResize=b.alsoResize[0];a(b.alsoResize)}else e.each( [...]
+function(c){a(c)});else a(b.alsoResize)},resize:function(b,a){var c=e(this).data("resizable");b=c.options;var d=c.originalSize,f=c.originalPosition,g={height:c.size.height-d.height||0,width:c.size.width-d.width||0,top:c.position.top-f.top||0,left:c.position.left-f.left||0},h=function(i,j){e(i).each(function(){var k=e(this),r=e(this).data("resizable-alsoresize"),q={},s=j&&j.length?j:k.parents(a.originalElement[0]).length?["width","height"]:["width","height","top","left"];e.each(s,function [...]
+(r[p]||0)+(g[p]||0))&&n>=0)q[p]=n||null});if(e.browser.opera&&/relative/.test(k.css("position"))){c._revertToRelativePosition=true;k.css({position:"absolute",top:"auto",left:"auto"})}k.css(q)})};typeof b.alsoResize=="object"&&!b.alsoResize.nodeType?e.each(b.alsoResize,function(i,j){h(i,j)}):h(b.alsoResize)},stop:function(){var b=e(this).data("resizable"),a=function(c){e(c).each(function(){var d=e(this);d.css({position:d.data("resizable-alsoresize").position})})};if(b._revertToRelativePos [...]
+false;typeof o.alsoResize=="object"&&!o.alsoResize.nodeType?e.each(o.alsoResize,function(c){a(c)}):a(o.alsoResize)}e(this).removeData("resizable-alsoresize")}});e.ui.plugin.add("resizable","animate",{stop:function(b){var a=e(this).data("resizable"),c=a.options,d=a._proportionallyResizeElements,f=d.length&&/textarea/i.test(d[0].nodeName),g=f&&e.ui.hasScroll(d[0],"left")?0:a.sizeDiff.height;f={width:a.size.width-(f?0:a.sizeDiff.width),height:a.size.height-g};g=parseInt(a.element.css("left" [...]
+a.originalPosition.left)||null;var h=parseInt(a.element.css("top"),10)+(a.position.top-a.originalPosition.top)||null;a.element.animate(e.extend(f,h&&g?{top:h,left:g}:{}),{duration:c.animateDuration,easing:c.animateEasing,step:function(){var i={width:parseInt(a.element.css("width"),10),height:parseInt(a.element.css("height"),10),top:parseInt(a.element.css("top"),10),left:parseInt(a.element.css("left"),10)};d&&d.length&&e(d[0]).css({width:i.width,height:i.height});a._updateCache(i);a._prop [...]
+b)}})}});e.ui.plugin.add("resizable","containment",{start:function(){var b=e(this).data("resizable"),a=b.element,c=b.options.containment;if(a=c instanceof e?c.get(0):/parent/.test(c)?a.parent().get(0):c){b.containerElement=e(a);if(/document/.test(c)||c==document){b.containerOffset={left:0,top:0};b.containerPosition={left:0,top:0};b.parentData={element:e(document),left:0,top:0,width:e(document).width(),height:e(document).height()||document.body.parentNode.scrollHeight}}else{var d=e(a),f=[ [...]
+"Right","Left","Bottom"]).each(function(i,j){f[i]=m(d.css("padding"+j))});b.containerOffset=d.offset();b.containerPosition=d.position();b.containerSize={height:d.innerHeight()-f[3],width:d.innerWidth()-f[1]};c=b.containerOffset;var g=b.containerSize.height,h=b.containerSize.width;h=e.ui.hasScroll(a,"left")?a.scrollWidth:h;g=e.ui.hasScroll(a)?a.scrollHeight:g;b.parentData={element:a,left:c.left,top:c.top,width:h,height:g}}}},resize:function(b){var a=e(this).data("resizable"),c=a.options,d [...]
+f=a.position;b=a._aspectRatio||b.shiftKey;var g={top:0,left:0},h=a.containerElement;if(h[0]!=document&&/static/.test(h.css("position")))g=d;if(f.left<(a._helper?d.left:0)){a.size.width+=a._helper?a.position.left-d.left:a.position.left-g.left;if(b)a.size.height=a.size.width/c.aspectRatio;a.position.left=c.helper?d.left:0}if(f.top<(a._helper?d.top:0)){a.size.height+=a._helper?a.position.top-d.top:a.position.top;if(b)a.size.width=a.size.height*c.aspectRatio;a.position.top=a._helper?d.top:0} [...]
+a.parentData.left+a.position.left;a.offset.top=a.parentData.top+a.position.top;c=Math.abs((a._helper?a.offset.left-g.left:a.offset.left-g.left)+a.sizeDiff.width);d=Math.abs((a._helper?a.offset.top-g.top:a.offset.top-d.top)+a.sizeDiff.height);f=a.containerElement.get(0)==a.element.parent().get(0);g=/relative|absolute/.test(a.containerElement.css("position"));if(f&&g)c-=a.parentData.left;if(c+a.size.width>=a.parentData.width){a.size.width=a.parentData.width-c;if(b)a.size.height=a.size.widt [...]
+a.size.height>=a.parentData.height){a.size.height=a.parentData.height-d;if(b)a.size.width=a.size.height*a.aspectRatio}},stop:function(){var b=e(this).data("resizable"),a=b.options,c=b.containerOffset,d=b.containerPosition,f=b.containerElement,g=e(b.helper),h=g.offset(),i=g.outerWidth()-b.sizeDiff.width;g=g.outerHeight()-b.sizeDiff.height;b._helper&&!a.animate&&/relative/.test(f.css("position"))&&e(this).css({left:h.left-d.left-c.left,width:i,height:g});b._helper&&!a.animate&&/static/.tes [...]
+e(this).css({left:h.left-d.left-c.left,width:i,height:g})}});e.ui.plugin.add("resizable","ghost",{start:function(){var b=e(this).data("resizable"),a=b.options,c=b.size;b.ghost=b.originalElement.clone();b.ghost.css({opacity:0.25,display:"block",position:"relative",height:c.height,width:c.width,margin:0,left:0,top:0}).addClass("ui-resizable-ghost").addClass(typeof a.ghost=="string"?a.ghost:"");b.ghost.appendTo(b.helper)},resize:function(){var b=e(this).data("resizable");b.ghost&&b.ghost.cs [...]
+height:b.size.height,width:b.size.width})},stop:function(){var b=e(this).data("resizable");b.ghost&&b.helper&&b.helper.get(0).removeChild(b.ghost.get(0))}});e.ui.plugin.add("resizable","grid",{resize:function(){var b=e(this).data("resizable"),a=b.options,c=b.size,d=b.originalSize,f=b.originalPosition,g=b.axis;a.grid=typeof a.grid=="number"?[a.grid,a.grid]:a.grid;var h=Math.round((c.width-d.width)/(a.grid[0]||1))*(a.grid[0]||1);a=Math.round((c.height-d.height)/(a.grid[1]||1))*(a.grid[1]|| [...]
+d.width+h;b.size.height=d.height+a}else if(/^(ne)$/.test(g)){b.size.width=d.width+h;b.size.height=d.height+a;b.position.top=f.top-a}else{if(/^(sw)$/.test(g)){b.size.width=d.width+h;b.size.height=d.height+a}else{b.size.width=d.width+h;b.size.height=d.height+a;b.position.top=f.top-a}b.position.left=f.left-h}}});var m=function(b){return parseInt(b,10)||0},l=function(b){return!isNaN(parseInt(b,10))}})(jQuery);
+(function(e){e.widget("ui.selectable",e.ui.mouse,{options:{appendTo:"body",autoRefresh:true,distance:0,filter:"*",tolerance:"touch"},_create:function(){var c=this;this.element.addClass("ui-selectable");this.dragged=false;var f;this.refresh=function(){f=e(c.options.filter,c.element[0]);f.each(function(){var d=e(this),b=d.offset();e.data(this,"selectable-item",{element:this,$element:d,left:b.left,top:b.top,right:b.left+d.outerWidth(),bottom:b.top+d.outerHeight(),startselected:false,selecte [...]
+selecting:d.hasClass("ui-selecting"),unselecting:d.hasClass("ui-unselecting")})})};this.refresh();this.selectees=f.addClass("ui-selectee");this._mouseInit();this.helper=e("<div class='ui-selectable-helper'></div>")},destroy:function(){this.selectees.removeClass("ui-selectee").removeData("selectable-item");this.element.removeClass("ui-selectable ui-selectable-disabled").removeData("selectable").unbind(".selectable");this._mouseDestroy();return this},_mouseStart:function(c){var f=this;this [...]
+c.pageY];if(!this.options.disabled){var d=this.options;this.selectees=e(d.filter,this.element[0]);this._trigger("start",c);e(d.appendTo).append(this.helper);this.helper.css({left:c.clientX,top:c.clientY,width:0,height:0});d.autoRefresh&&this.refresh();this.selectees.filter(".ui-selected").each(function(){var b=e.data(this,"selectable-item");b.startselected=true;if(!c.metaKey){b.$element.removeClass("ui-selected");b.selected=false;b.$element.addClass("ui-unselecting");b.unselecting=true;f [...]
+c,{unselecting:b.element})}});e(c.target).parents().andSelf().each(function(){var b=e.data(this,"selectable-item");if(b){var g=!c.metaKey||!b.$element.hasClass("ui-selected");b.$element.removeClass(g?"ui-unselecting":"ui-selected").addClass(g?"ui-selecting":"ui-unselecting");b.unselecting=!g;b.selecting=g;(b.selected=g)?f._trigger("selecting",c,{selecting:b.element}):f._trigger("unselecting",c,{unselecting:b.element});return false}})}},_mouseDrag:function(c){var f=this;this.dragged=true; [...]
+this.options,b=this.opos[0],g=this.opos[1],h=c.pageX,i=c.pageY;if(b>h){var j=h;h=b;b=j}if(g>i){j=i;i=g;g=j}this.helper.css({left:b,top:g,width:h-b,height:i-g});this.selectees.each(function(){var a=e.data(this,"selectable-item");if(!(!a||a.element==f.element[0])){var k=false;if(d.tolerance=="touch")k=!(a.left>h||a.right<b||a.top>i||a.bottom<g);else if(d.tolerance=="fit")k=a.left>b&&a.right<h&&a.top>g&&a.bottom<i;if(k){if(a.selected){a.$element.removeClass("ui-selected");a.selected=false}i [...]
+a.unselecting=false}if(!a.selecting){a.$element.addClass("ui-selecting");a.selecting=true;f._trigger("selecting",c,{selecting:a.element})}}else{if(a.selecting)if(c.metaKey&&a.startselected){a.$element.removeClass("ui-selecting");a.selecting=false;a.$element.addClass("ui-selected");a.selected=true}else{a.$element.removeClass("ui-selecting");a.selecting=false;if(a.startselected){a.$element.addClass("ui-unselecting");a.unselecting=true}f._trigger("unselecting",c,{unselecting:a.element})}if( [...]
+!a.startselected){a.$element.removeClass("ui-selected");a.selected=false;a.$element.addClass("ui-unselecting");a.unselecting=true;f._trigger("unselecting",c,{unselecting:a.element})}}}});return false}},_mouseStop:function(c){var f=this;this.dragged=false;e(".ui-unselecting",this.element[0]).each(function(){var d=e.data(this,"selectable-item");d.$element.removeClass("ui-unselecting");d.unselecting=false;d.startselected=false;f._trigger("unselected",c,{unselected:d.element})});e(".ui-selec [...]
+e.data(this,"selectable-item");d.$element.removeClass("ui-selecting").addClass("ui-selected");d.selecting=false;d.selected=true;d.startselected=true;f._trigger("selected",c,{selected:d.element})});this._trigger("stop",c);this.helper.remove();return false}});e.extend(e.ui.selectable,{version:"1.9m2"})})(jQuery);
+(function(d){d.widget("ui.sortable",d.ui.mouse,{widgetEventPrefix:"sort",options:{appendTo:"parent",axis:false,connectWith:false,containment:false,cursor:"auto",cursorAt:false,dropOnEmpty:true,forcePlaceholderSize:false,forceHelperSize:false,grid:false,handle:false,helper:"original",items:"> *",opacity:false,placeholder:false,revert:false,scroll:true,scrollSensitivity:20,scrollSpeed:20,scope:"default",tolerance:"intersect",zIndex:1E3},_create:function(){this.containerCache={};this.elemen [...]
+this.refresh();this.floating=this.items.length?/left|right/.test(this.items[0].item.css("float")):false;this.offset=this.element.offset();this._mouseInit()},destroy:function(){this.element.removeClass("ui-sortable ui-sortable-disabled").removeData("sortable").unbind(".sortable");this._mouseDestroy();for(var a=this.items.length-1;a>=0;a--)this.items[a].item.removeData("sortable-item");return this},_setOption:function(a,b){if(a==="disabled"){this.options[a]=b;this.widget()[b?"addClass":"re [...]
+arguments)},_mouseCapture:function(a,b){if(this.reverting)return false;if(this.options.disabled||this.options.type=="static")return false;this._refreshItems(a);var c=null,e=this;d(a.target).parents().each(function(){if(d.data(this,"sortable-item")==e){c=d(this);return false}});if(d.data(a.target,"sortable-item")==e)c=d(a.target);if(!c)return false;if(this.options.handle&&!b){var f=false;d(this.options.handle,c).find("*").andSelf().each(function(){if(this==a.target)f=true});if(!f)return f [...]
+c;this._removeCurrentsFromItems();return true},_mouseStart:function(a,b,c){b=this.options;var e=this;this.currentContainer=this;this.refreshPositions();this.helper=this._createHelper(a);this._cacheHelperProportions();this._cacheMargins();this.scrollParent=this.helper.scrollParent();this.offset=this.currentItem.offset();this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left};this.helper.css("position","absolute");this.cssPosition=this.helper.css("positio [...]
+{click:{left:a.pageX-this.offset.left,top:a.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()});this.originalPosition=this._generatePosition(a);this.originalPageX=a.pageX;this.originalPageY=a.pageY;b.cursorAt&&this._adjustOffsetFromHelper(b.cursorAt);this.domPosition={prev:this.currentItem.prev()[0],parent:this.currentItem.parent()[0]};this.helper[0]!=this.currentItem[0]&&this.currentItem.hide();this._createPlaceholder();b.containment&&this._setCont [...]
+if(b.cursor){if(d("body").css("cursor"))this._storedCursor=d("body").css("cursor");d("body").css("cursor",b.cursor)}if(b.opacity){if(this.helper.css("opacity"))this._storedOpacity=this.helper.css("opacity");this.helper.css("opacity",b.opacity)}if(b.zIndex){if(this.helper.css("zIndex"))this._storedZIndex=this.helper.css("zIndex");this.helper.css("zIndex",b.zIndex)}if(this.scrollParent[0]!=document&&this.scrollParent[0].tagName!="HTML")this.overflowOffset=this.scrollParent.offset();this._t [...]
+a,this._uiHash());this._preserveHelperProportions||this._cacheHelperProportions();if(!c)for(c=this.containers.length-1;c>=0;c--)this.containers[c]._trigger("activate",a,e._uiHash(this));if(d.ui.ddmanager)d.ui.ddmanager.current=this;d.ui.ddmanager&&!b.dropBehaviour&&d.ui.ddmanager.prepareOffsets(this,a);this.dragging=true;this.helper.addClass("ui-sortable-helper");this._mouseDrag(a);return true},_mouseDrag:function(a){this.position=this._generatePosition(a);this.positionAbs=this._convertP [...]
+if(!this.lastPositionAbs)this.lastPositionAbs=this.positionAbs;if(this.options.scroll){var b=this.options,c=false;if(this.scrollParent[0]!=document&&this.scrollParent[0].tagName!="HTML"){if(this.overflowOffset.top+this.scrollParent[0].offsetHeight-a.pageY<b.scrollSensitivity)this.scrollParent[0].scrollTop=c=this.scrollParent[0].scrollTop+b.scrollSpeed;else if(a.pageY-this.overflowOffset.top<b.scrollSensitivity)this.scrollParent[0].scrollTop=c=this.scrollParent[0].scrollTop-b.scrollSpeed; [...]
+this.scrollParent[0].offsetWidth-a.pageX<b.scrollSensitivity)this.scrollParent[0].scrollLeft=c=this.scrollParent[0].scrollLeft+b.scrollSpeed;else if(a.pageX-this.overflowOffset.left<b.scrollSensitivity)this.scrollParent[0].scrollLeft=c=this.scrollParent[0].scrollLeft-b.scrollSpeed}else{if(a.pageY-d(document).scrollTop()<b.scrollSensitivity)c=d(document).scrollTop(d(document).scrollTop()-b.scrollSpeed);else if(d(window).height()-(a.pageY-d(document).scrollTop())<b.scrollSensitivity)c=d(do [...]
+b.scrollSpeed);if(a.pageX-d(document).scrollLeft()<b.scrollSensitivity)c=d(document).scrollLeft(d(document).scrollLeft()-b.scrollSpeed);else if(d(window).width()-(a.pageX-d(document).scrollLeft())<b.scrollSensitivity)c=d(document).scrollLeft(d(document).scrollLeft()+b.scrollSpeed)}c!==false&&d.ui.ddmanager&&!b.dropBehaviour&&d.ui.ddmanager.prepareOffsets(this,a)}this.positionAbs=this._convertPositionTo("absolute");if(!this.options.axis||this.options.axis!="y")this.helper[0].style.left=th [...]
+"px";if(!this.options.axis||this.options.axis!="x")this.helper[0].style.top=this.position.top+"px";for(b=this.items.length-1;b>=0;b--){c=this.items[b];var e=c.item[0],f=this._intersectsWithPointer(c);if(f)if(e!=this.currentItem[0]&&this.placeholder[f==1?"next":"prev"]()[0]!=e&&!d.ui.contains(this.placeholder[0],e)&&(this.options.type=="semi-dynamic"?!d.ui.contains(this.element[0],e):true)){this.direction=f==1?"down":"up";if(this.options.tolerance=="pointer"||this._intersectsWithSides(c)) [...]
+c);else break;this._trigger("change",a,this._uiHash());break}}this._contactContainers(a);d.ui.ddmanager&&d.ui.ddmanager.drag(this,a);this._trigger("sort",a,this._uiHash());this.lastPositionAbs=this.positionAbs;return false},_mouseStop:function(a,b){if(a){d.ui.ddmanager&&!this.options.dropBehaviour&&d.ui.ddmanager.drop(this,a);if(this.options.revert){var c=this;b=c.placeholder.offset();c.reverting=true;d(this.helper).animate({left:b.left-this.offset.parent.left-c.margins.left+(this.offset [...]
+document.body?0:this.offsetParent[0].scrollLeft),top:b.top-this.offset.parent.top-c.margins.top+(this.offsetParent[0]==document.body?0:this.offsetParent[0].scrollTop)},parseInt(this.options.revert,10)||500,function(){c._clear(a)})}else this._clear(a,b);return false}},cancel:function(){var a=this;if(this.dragging){this._mouseUp();this.options.helper=="original"?this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper"):this.currentItem.show();for(var b=this.containers.length- [...]
+null,a._uiHash(this));if(this.containers[b].containerCache.over){this.containers[b]._trigger("out",null,a._uiHash(this));this.containers[b].containerCache.over=0}}}this.placeholder[0].parentNode&&this.placeholder[0].parentNode.removeChild(this.placeholder[0]);this.options.helper!="original"&&this.helper&&this.helper[0].parentNode&&this.helper.remove();d.extend(this,{helper:null,dragging:false,reverting:false,_noFinalSort:null});this.domPosition.prev?d(this.domPosition.prev).after(this.cu [...]
+d(this.domPosition.parent).prepend(this.currentItem);return this},serialize:function(a){var b=this._getItemsAsjQuery(a&&a.connected),c=[];a=a||{};d(b).each(function(){var e=(d(a.item||this).attr(a.attribute||"id")||"").match(a.expression||/(.+)[-=_](.+)/);if(e)c.push((a.key||e[1]+"[]")+"="+(a.key&&a.expression?e[1]:e[2]))});return c.join("&")},toArray:function(a){var b=this._getItemsAsjQuery(a&&a.connected),c=[];a=a||{};b.each(function(){c.push(d(a.item||this).attr(a.attribute||"id")||"" [...]
+_intersectsWith:function(a){var b=this.positionAbs.left,c=b+this.helperProportions.width,e=this.positionAbs.top,f=e+this.helperProportions.height,g=a.left,h=g+a.width,i=a.top,k=i+a.height,j=this.offset.click.top,l=this.offset.click.left;j=e+j>i&&e+j<k&&b+l>g&&b+l<h;return this.options.tolerance=="pointer"||this.options.forcePointerForContainers||this.options.tolerance!="pointer"&&this.helperProportions[this.floating?"width":"height"]>a[this.floating?"width":"height"]?j:g<b+this.helperPro [...]
+2&&c-this.helperProportions.width/2<h&&i<e+this.helperProportions.height/2&&f-this.helperProportions.height/2<k},_intersectsWithPointer:function(a){var b=d.ui.isOverAxis(this.positionAbs.top+this.offset.click.top,a.top,a.height);a=d.ui.isOverAxis(this.positionAbs.left+this.offset.click.left,a.left,a.width);b=b&&a;a=this._getDragVerticalDirection();var c=this._getDragHorizontalDirection();if(!b)return false;return this.floating?c&&c=="right"||a=="down"?2:1:a&&(a=="down"?2:1)},_intersectsW [...]
+d.ui.isOverAxis(this.positionAbs.top+this.offset.click.top,a.top+a.height/2,a.height);a=d.ui.isOverAxis(this.positionAbs.left+this.offset.click.left,a.left+a.width/2,a.width);var c=this._getDragVerticalDirection(),e=this._getDragHorizontalDirection();return this.floating&&e?e=="right"&&a||e=="left"&&!a:c&&(c=="down"&&b||c=="up"&&!b)},_getDragVerticalDirection:function(){var a=this.positionAbs.top-this.lastPositionAbs.top;return a!=0&&(a>0?"down":"up")},_getDragHorizontalDirection:functio [...]
+this.positionAbs.left-this.lastPositionAbs.left;return a!=0&&(a>0?"right":"left")},refresh:function(a){this._refreshItems(a);this.refreshPositions();return this},_connectWith:function(){var a=this.options;return a.connectWith.constructor==String?[a.connectWith]:a.connectWith},_getItemsAsjQuery:function(a){var b=[],c=[],e=this._connectWith();if(e&&a)for(a=e.length-1;a>=0;a--)for(var f=d(e[a]),g=f.length-1;g>=0;g--){var h=d.data(f[g],"sortable");if(h&&h!=this&&!h.options.disabled)c.push([d [...]
+h.options.items.call(h.element):d(h.options.items,h.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),h])}c.push([d.isFunction(this.options.items)?this.options.items.call(this.element,null,{options:this.options,item:this.currentItem}):d(this.options.items,this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),this]);for(a=c.length-1;a>=0;a--)c[a][0].each(function(){b.push(this)});return d(b)},_removeCurrentsFromItems:function(){for(var a=this.currentIt [...]
+b=0;b<this.items.length;b++)for(var c=0;c<a.length;c++)a[c]==this.items[b].item[0]&&this.items.splice(b,1)},_refreshItems:function(a){this.items=[];this.containers=[this];var b=this.items,c=[[d.isFunction(this.options.items)?this.options.items.call(this.element[0],a,{item:this.currentItem}):d(this.options.items,this.element),this]],e=this._connectWith();if(e)for(var f=e.length-1;f>=0;f--)for(var g=d(e[f]),h=g.length-1;h>=0;h--){var i=d.data(g[h],"sortable");if(i&&i!=this&&!i.options.disa [...]
+i.options.items.call(i.element[0],a,{item:this.currentItem}):d(i.options.items,i.element),i]);this.containers.push(i)}}for(f=c.length-1;f>=0;f--){a=c[f][1];e=c[f][0];h=0;for(g=e.length;h<g;h++){i=d(e[h]);i.data("sortable-item",a);b.push({item:i,instance:a,width:0,height:0,left:0,top:0})}}},refreshPositions:function(a){if(this.offsetParent&&this.helper)this.offset.parent=this._getParentOffset();for(var b=this.items.length-1;b>=0;b--){var c=this.items[b],e=this.options.toleranceElement?d(t [...]
+c.item):c.item;if(!a){c.width=e.outerWidth();c.height=e.outerHeight()}e=e.offset();c.left=e.left;c.top=e.top}if(this.options.custom&&this.options.custom.refreshContainers)this.options.custom.refreshContainers.call(this);else for(b=this.containers.length-1;b>=0;b--){e=this.containers[b].element.offset();this.containers[b].containerCache.left=e.left;this.containers[b].containerCache.top=e.top;this.containers[b].containerCache.width=this.containers[b].element.outerWidth();this.containers[b] [...]
+this.containers[b].element.outerHeight()}return this},_createPlaceholder:function(a){var b=a||this,c=b.options;if(!c.placeholder||c.placeholder.constructor==String){var e=c.placeholder;c.placeholder={element:function(){var f=d(document.createElement(b.currentItem[0].nodeName)).addClass(e||b.currentItem[0].className+" ui-sortable-placeholder").removeClass("ui-sortable-helper")[0];if(!e)f.style.visibility="hidden";return f},update:function(f,g){if(!(e&&!c.forcePlaceholderSize)){g.height()| [...]
+parseInt(b.currentItem.css("paddingTop")||0,10)-parseInt(b.currentItem.css("paddingBottom")||0,10));g.width()||g.width(b.currentItem.innerWidth()-parseInt(b.currentItem.css("paddingLeft")||0,10)-parseInt(b.currentItem.css("paddingRight")||0,10))}}}}b.placeholder=d(c.placeholder.element.call(b.element,b.currentItem));b.currentItem.after(b.placeholder);c.placeholder.update(b,b.placeholder)},_contactContainers:function(a){for(var b=null,c=null,e=this.containers.length-1;e>=0;e--)if(!d.ui.co [...]
+this.containers[e].element[0]))if(this._intersectsWith(this.containers[e].containerCache)){if(!(b&&d.ui.contains(this.containers[e].element[0],b.element[0]))){b=this.containers[e];c=e}}else if(this.containers[e].containerCache.over){this.containers[e]._trigger("out",a,this._uiHash(this));this.containers[e].containerCache.over=0}if(b)if(this.containers.length===1){this.containers[c]._trigger("over",a,this._uiHash(this));this.containers[c].containerCache.over=1}else if(this.currentContaine [...]
+1E4;e=null;for(var f=this.positionAbs[this.containers[c].floating?"left":"top"],g=this.items.length-1;g>=0;g--)if(d.ui.contains(this.containers[c].element[0],this.items[g].item[0])){var h=this.items[g][this.containers[c].floating?"left":"top"];if(Math.abs(h-f)<b){b=Math.abs(h-f);e=this.items[g]}}if(e||this.options.dropOnEmpty){this.currentContainer=this.containers[c];e?this._rearrange(a,e,null,true):this._rearrange(a,null,this.containers[c].element,true);this._trigger("change",a,this._ui [...]
+a,this._uiHash(this));this.options.placeholder.update(this.currentContainer,this.placeholder);this.containers[c]._trigger("over",a,this._uiHash(this));this.containers[c].containerCache.over=1}}},_createHelper:function(a){var b=this.options;a=d.isFunction(b.helper)?d(b.helper.apply(this.element[0],[a,this.currentItem])):b.helper=="clone"?this.currentItem.clone():this.currentItem;a.parents("body").length||d(b.appendTo!="parent"?b.appendTo:this.currentItem[0].parentNode)[0].appendChild(a[0] [...]
+this.currentItem[0])this._storedCSS={width:this.currentItem[0].style.width,height:this.currentItem[0].style.height,position:this.currentItem.css("position"),top:this.currentItem.css("top"),left:this.currentItem.css("left")};if(a[0].style.width==""||b.forceHelperSize)a.width(this.currentItem.width());if(a[0].style.height==""||b.forceHelperSize)a.height(this.currentItem.height());return a},_adjustOffsetFromHelper:function(a){if(typeof a=="string")a=a.split(" ");if(d.isArray(a))a={left:+a[0 [...]
+0};if("left"in a)this.offset.click.left=a.left+this.margins.left;if("right"in a)this.offset.click.left=this.helperProportions.width-a.right+this.margins.left;if("top"in a)this.offset.click.top=a.top+this.margins.top;if("bottom"in a)this.offset.click.top=this.helperProportions.height-a.bottom+this.margins.top},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var a=this.offsetParent.offset();if(this.cssPosition=="absolute"&&this.scrollParent[0]!=document&&d.ui.conta [...]
+this.offsetParent[0])){a.left+=this.scrollParent.scrollLeft();a.top+=this.scrollParent.scrollTop()}if(this.offsetParent[0]==document.body||this.offsetParent[0].tagName&&this.offsetParent[0].tagName.toLowerCase()=="html"&&d.browser.msie)a={top:0,left:0};return{top:a.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:a.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if(this.cssPosition=="relative"){var a=this.currentItem.posit [...]
+(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:a.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}else return{top:0,left:0}},_cacheMargins:function(){this.margins={left:parseInt(this.currentItem.css("marginLeft"),10)||0,top:parseInt(this.currentItem.css("marginTop"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var a [...]
+if(a.containment=="parent")a.containment=this.helper[0].parentNode;if(a.containment=="document"||a.containment=="window")this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,d(a.containment=="document"?document:window).width()-this.helperProportions.width-this.margins.left,(d(a.containment=="document"?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top];if(!/^(d [...]
+d(a.containment)[0];a=d(a.containment).offset();var c=d(b).css("overflow")!="hidden";this.containment=[a.left+(parseInt(d(b).css("borderLeftWidth"),10)||0)+(parseInt(d(b).css("paddingLeft"),10)||0)-this.margins.left,a.top+(parseInt(d(b).css("borderTopWidth"),10)||0)+(parseInt(d(b).css("paddingTop"),10)||0)-this.margins.top,a.left+(c?Math.max(b.scrollWidth,b.offsetWidth):b.offsetWidth)-(parseInt(d(b).css("borderLeftWidth"),10)||0)-(parseInt(d(b).css("paddingRight"),10)||0)-this.helperProp [...]
+this.margins.left,a.top+(c?Math.max(b.scrollHeight,b.offsetHeight):b.offsetHeight)-(parseInt(d(b).css("borderTopWidth"),10)||0)-(parseInt(d(b).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top]}},_convertPositionTo:function(a,b){if(!b)b=this.position;a=a=="absolute"?1:-1;var c=this.cssPosition=="absolute"&&!(this.scrollParent[0]!=document&&d.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,e=/(html|body)/i.test(c[0].tag [...]
+this.offset.relative.top*a+this.offset.parent.top*a-(d.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():e?0:c.scrollTop())*a),left:b.left+this.offset.relative.left*a+this.offset.parent.left*a-(d.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():e?0:c.scrollLeft())*a)}},_generatePosition:function(a){var b=this.options,c=this.cssPosition=="absolute"&&!(this.scrollParent[0]!=document&&d [...]
+this.offsetParent[0]))?this.offsetParent:this.scrollParent,e=/(html|body)/i.test(c[0].tagName);if(this.cssPosition=="relative"&&!(this.scrollParent[0]!=document&&this.scrollParent[0]!=this.offsetParent[0]))this.offset.relative=this._getRelativeOffset();var f=a.pageX,g=a.pageY;if(this.originalPosition){if(this.containment){if(a.pageX-this.offset.click.left<this.containment[0])f=this.containment[0]+this.offset.click.left;if(a.pageY-this.offset.click.top<this.containment[1])g=this.containme [...]
+if(a.pageX-this.offset.click.left>this.containment[2])f=this.containment[2]+this.offset.click.left;if(a.pageY-this.offset.click.top>this.containment[3])g=this.containment[3]+this.offset.click.top}if(b.grid){g=this.originalPageY+Math.round((g-this.originalPageY)/b.grid[1])*b.grid[1];g=this.containment?!(g-this.offset.click.top<this.containment[1]||g-this.offset.click.top>this.containment[3])?g:!(g-this.offset.click.top<this.containment[1])?g-b.grid[1]:g+b.grid[1]:g;f=this.originalPageX+Ma [...]
+this.originalPageX)/b.grid[0])*b.grid[0];f=this.containment?!(f-this.offset.click.left<this.containment[0]||f-this.offset.click.left>this.containment[2])?f:!(f-this.offset.click.left<this.containment[0])?f-b.grid[0]:f+b.grid[0]:f}}return{top:g-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+(d.browser.safari&&this.cssPosition=="fixed"?0:this.cssPosition=="fixed"?-this.scrollParent.scrollTop():e?0:c.scrollTop()),left:f-this.offset.click.left-this.offset.relative.left [...]
+(d.browser.safari&&this.cssPosition=="fixed"?0:this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():e?0:c.scrollLeft())}},_rearrange:function(a,b,c,e){c?c[0].appendChild(this.placeholder[0]):b.item[0].parentNode.insertBefore(this.placeholder[0],this.direction=="down"?b.item[0]:b.item[0].nextSibling);this.counter=this.counter?++this.counter:1;var f=this,g=this.counter;window.setTimeout(function(){g==f.counter&&f.refreshPositions(!e)},0)},_clear:function(a,b){this.reverting=false;var  [...]
+this.currentItem[0].parentNode&&this.placeholder.before(this.currentItem);this._noFinalSort=null;if(this.helper[0]==this.currentItem[0]){for(var e in this._storedCSS)if(this._storedCSS[e]=="auto"||this._storedCSS[e]=="static")this._storedCSS[e]="";this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper")}else this.currentItem.show();this.fromOutside&&!b&&c.push(function(f){this._trigger("receive",f,this._uiHash(this.fromOutside))});if((this.fromOutside||this.domPosition.pre [...]
+this.domPosition.parent!=this.currentItem.parent()[0])&&!b)c.push(function(f){this._trigger("update",f,this._uiHash())});if(!d.ui.contains(this.element[0],this.currentItem[0])){b||c.push(function(f){this._trigger("remove",f,this._uiHash())});for(e=this.containers.length-1;e>=0;e--)if(d.ui.contains(this.containers[e].element[0],this.currentItem[0])&&!b){c.push(function(f){return function(g){f._trigger("receive",g,this._uiHash(this))}}.call(this,this.containers[e]));c.push(function(f){retu [...]
+g,this._uiHash(this))}}.call(this,this.containers[e]))}}for(e=this.containers.length-1;e>=0;e--){b||c.push(function(f){return function(g){f._trigger("deactivate",g,this._uiHash(this))}}.call(this,this.containers[e]));if(this.containers[e].containerCache.over){c.push(function(f){return function(g){f._trigger("out",g,this._uiHash(this))}}.call(this,this.containers[e]));this.containers[e].containerCache.over=0}}this._storedCursor&&d("body").css("cursor",this._storedCursor);this._storedOpaci [...]
+this._storedOpacity);if(this._storedZIndex)this.helper.css("zIndex",this._storedZIndex=="auto"?"":this._storedZIndex);this.dragging=false;if(this.cancelHelperRemoval){if(!b){this._trigger("beforeStop",a,this._uiHash());for(e=0;e<c.length;e++)c[e].call(this,a);this._trigger("stop",a,this._uiHash())}return false}b||this._trigger("beforeStop",a,this._uiHash());this.placeholder[0].parentNode.removeChild(this.placeholder[0]);this.helper[0]!=this.currentItem[0]&&this.helper.remove();this.helpe [...]
+0;e<c.length;e++)c[e].call(this,a);this._trigger("stop",a,this._uiHash())}this.fromOutside=false;return true},_trigger:function(){d.Widget.prototype._trigger.apply(this,arguments)===false&&this.cancel()},_uiHash:function(a){var b=a||this;return{helper:b.helper,placeholder:b.placeholder||d([]),position:b.position,originalPosition:b.originalPosition,offset:b.positionAbs,item:b.currentItem,sender:a?a.element:null}}});d.extend(d.ui.sortable,{version:"1.9m2"})})(jQuery);
+jQuery.effects||function(f){function k(c){var a;if(c&&c.constructor==Array&&c.length==3)return c;if(a=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(c))return[parseInt(a[1],10),parseInt(a[2],10),parseInt(a[3],10)];if(a=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(c))return[parseFloat(a[1])*2.55,parseFloat(a[2])*2.55,parseFloat(a[3])*2.55];if(a=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(c))ret [...]
+16),parseInt(a[2],16),parseInt(a[3],16)];if(a=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(c))return[parseInt(a[1]+a[1],16),parseInt(a[2]+a[2],16),parseInt(a[3]+a[3],16)];if(/rgba\(0, 0, 0, 0\)/.exec(c))return l.transparent;return l[f.trim(c).toLowerCase()]}function q(c,a){var b;do{b=f.curCSS(c,a);if(b!=""&&b!="transparent"||f.nodeName(c,"body"))break;a="backgroundColor"}while(c=c.parentNode);return k(b)}function m(){var c=document.defaultView?document.defaultView.getComputedStyle(thi [...]
+a={},b,d;if(c&&c.length&&c[0]&&c[c[0]])for(var e=c.length;e--;){b=c[e];if(typeof c[b]=="string"){d=b.replace(/\-(\w)/g,function(g,h){return h.toUpperCase()});a[d]=c[b]}}else for(b in c)if(typeof c[b]==="string")a[b]=c[b];return a}function n(c){var a,b;for(a in c){b=c[a];if(b==null||f.isFunction(b)||a in r||/scrollbar/.test(a)||!/color/i.test(a)&&isNaN(parseFloat(b)))delete c[a]}return c}function s(c,a){var b={_:0},d;for(d in a)if(c[d]!=a[d])b[d]=a[d];return b}function j(c,a,b,d){if(typeo [...]
+a;b=null;a=c;c=a.effect}if(f.isFunction(a)){d=a;b=null;a={}}if(f.isFunction(b)){d=b;b=null}if(typeof a=="number"||f.fx.speeds[a]){d=b;b=a;a={}}a=a||{};b=b||a.duration;b=f.fx.off?0:typeof b=="number"?b:f.fx.speeds[b]||f.fx.speeds._default;d=d||a.complete;return[c,a,b,d]}f.effects={};f.each(["backgroundColor","borderBottomColor","borderLeftColor","borderRightColor","borderTopColor","color","outlineColor"],function(c,a){f.fx.step[a]=function(b){if(!b.colorInit){b.start=q(b.elem,a);b.end=k(b [...]
+true}b.elem.style[a]="rgb("+Math.max(Math.min(parseInt(b.pos*(b.end[0]-b.start[0])+b.start[0],10),255),0)+","+Math.max(Math.min(parseInt(b.pos*(b.end[1]-b.start[1])+b.start[1],10),255),0)+","+Math.max(Math.min(parseInt(b.pos*(b.end[2]-b.start[2])+b.start[2],10),255),0)+")"}});var l={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],dark [...]
+183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128 [...]
+165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0],transparent:[255,255,255]},o=["add","remove","toggle"],r={border:1,borderBottom:1,borderColor:1,borderLeft:1,borderRight:1,borderTop:1,borderWidth:1,margin:1,padding:1};f.effects.animateClass=function(c,a,b,d){if(f.isFunction(b)){d=b;b=null}return this.each(function(){var e=f(this),g=e.attr("style")||" ",h=n(m.call(this)),p,t=e.attr("className");f.each [...]
+i){c[i]&&e[i+"Class"](c[i])});p=n(m.call(this));e.attr("className",t);e.animate(s(h,p),a,b,function(){f.each(o,function(u,i){c[i]&&e[i+"Class"](c[i])});if(typeof e.attr("style")=="object"){e.attr("style").cssText="";e.attr("style").cssText=g}else e.attr("style",g);d&&d.apply(this,arguments)})})};f.fn.extend({_addClass:f.fn.addClass,addClass:function(c,a,b,d){return a?f.effects.animateClass.apply(this,[{add:c},a,b,d]):this._addClass(c)},_removeClass:f.fn.removeClass,removeClass:function(c [...]
+f.effects.animateClass.apply(this,[{remove:c},a,b,d]):this._removeClass(c)},_toggleClass:f.fn.toggleClass,toggleClass:function(c,a,b,d,e){return typeof a=="boolean"||a===undefined?b?f.effects.animateClass.apply(this,[a?{add:c}:{remove:c},b,d,e]):this._toggleClass(c,a):f.effects.animateClass.apply(this,[{toggle:c},a,b,d])},switchClass:function(c,a,b,d,e){return f.effects.animateClass.apply(this,[{add:a,remove:c},b,d,e])}});f.extend(f.effects,{version:"1.9m2",save:function(c,a){for(var b=0 [...]
+null&&c.data("ec.storage."+a[b],c[0].style[a[b]])},restore:function(c,a){for(var b=0;b<a.length;b++)a[b]!==null&&c.css(a[b],c.data("ec.storage."+a[b]))},setMode:function(c,a){if(a=="toggle")a=c.is(":hidden")?"show":"hide";return a},getBaseline:function(c,a){var b;switch(c[0]){case "top":b=0;break;case "middle":b=0.5;break;case "bottom":b=1;break;default:b=c[0]/a.height}switch(c[1]){case "left":c=0;break;case "center":c=0.5;break;case "right":c=1;break;default:c=c[1]/a.width}return{x:c,y: [...]
+var a={width:c.outerWidth(true),height:c.outerHeight(true),"float":c.css("float")},b=f("<div></div>").addClass("ui-effects-wrapper").css({fontSize:"100%",background:"transparent",border:"none",margin:0,padding:0});c.wrap(b);b=c.parent();if(c.css("position")=="static"){b.css({position:"relative"});c.css({position:"relative"})}else{f.extend(a,{position:c.css("position"),zIndex:c.css("z-index")});f.each(["top","left","bottom","right"],function(d,e){a[e]=c.css(e);if(isNaN(parseInt(a[e],10))) [...]
+c.css({position:"relative",top:0,left:0})}return b.css(a).show()},removeWrapper:function(c){if(c.parent().is(".ui-effects-wrapper"))return c.parent().replaceWith(c);return c},setTransition:function(c,a,b,d){d=d||{};f.each(a,function(e,g){unit=c.cssUnit(g);if(unit[0]>0)d[g]=unit[0]*b+unit[1]});return d}});f.fn.extend({effect:function(c){var a=j.apply(this,arguments);a={options:a[1],duration:a[2],callback:a[3]};var b=f.effects[c];return b&&!f.fx.off?b.call(this,a):this},_show:f.fn.show,sho [...]
+typeof c=="number"||f.fx.speeds[c])return this._show.apply(this,arguments);else{var a=j.apply(this,arguments);a[1].mode="show";return this.effect.apply(this,a)}},_hide:f.fn.hide,hide:function(c){if(!c||typeof c=="number"||f.fx.speeds[c])return this._hide.apply(this,arguments);else{var a=j.apply(this,arguments);a[1].mode="hide";return this.effect.apply(this,a)}},__toggle:f.fn.toggle,toggle:function(c){if(!c||typeof c=="number"||f.fx.speeds[c]||typeof c=="boolean"||f.isFunction(c))return t [...]
+arguments);else{var a=j.apply(this,arguments);a[1].mode="toggle";return this.effect.apply(this,a)}},cssUnit:function(c){var a=this.css(c),b=[];f.each(["em","px","%","pt"],function(d,e){if(a.indexOf(e)>0)b=[parseFloat(a),e]});return b}});f.easing.jswing=f.easing.swing;f.extend(f.easing,{def:"easeOutQuad",swing:function(c,a,b,d,e){return f.easing[f.easing.def](c,a,b,d,e)},easeInQuad:function(c,a,b,d,e){return d*(a/=e)*a+b},easeOutQuad:function(c,a,b,d,e){return-d*(a/=e)*(a-2)+b},easeInOutQ [...]
+a,b,d,e){if((a/=e/2)<1)return d/2*a*a+b;return-d/2*(--a*(a-2)-1)+b},easeInCubic:function(c,a,b,d,e){return d*(a/=e)*a*a+b},easeOutCubic:function(c,a,b,d,e){return d*((a=a/e-1)*a*a+1)+b},easeInOutCubic:function(c,a,b,d,e){if((a/=e/2)<1)return d/2*a*a*a+b;return d/2*((a-=2)*a*a+2)+b},easeInQuart:function(c,a,b,d,e){return d*(a/=e)*a*a*a+b},easeOutQuart:function(c,a,b,d,e){return-d*((a=a/e-1)*a*a*a-1)+b},easeInOutQuart:function(c,a,b,d,e){if((a/=e/2)<1)return d/2*a*a*a*a+b;return-d/2*((a-=2 [...]
+b},easeInQuint:function(c,a,b,d,e){return d*(a/=e)*a*a*a*a+b},easeOutQuint:function(c,a,b,d,e){return d*((a=a/e-1)*a*a*a*a+1)+b},easeInOutQuint:function(c,a,b,d,e){if((a/=e/2)<1)return d/2*a*a*a*a*a+b;return d/2*((a-=2)*a*a*a*a+2)+b},easeInSine:function(c,a,b,d,e){return-d*Math.cos(a/e*(Math.PI/2))+d+b},easeOutSine:function(c,a,b,d,e){return d*Math.sin(a/e*(Math.PI/2))+b},easeInOutSine:function(c,a,b,d,e){return-d/2*(Math.cos(Math.PI*a/e)-1)+b},easeInExpo:function(c,a,b,d,e){return a==0? [...]
+10*(a/e-1))+b},easeOutExpo:function(c,a,b,d,e){return a==e?b+d:d*(-Math.pow(2,-10*a/e)+1)+b},easeInOutExpo:function(c,a,b,d,e){if(a==0)return b;if(a==e)return b+d;if((a/=e/2)<1)return d/2*Math.pow(2,10*(a-1))+b;return d/2*(-Math.pow(2,-10*--a)+2)+b},easeInCirc:function(c,a,b,d,e){return-d*(Math.sqrt(1-(a/=e)*a)-1)+b},easeOutCirc:function(c,a,b,d,e){return d*Math.sqrt(1-(a=a/e-1)*a)+b},easeInOutCirc:function(c,a,b,d,e){if((a/=e/2)<1)return-d/2*(Math.sqrt(1-a*a)-1)+b;return d/2*(Math.sqrt( [...]
+a)+1)+b},easeInElastic:function(c,a,b,d,e){c=1.70158;var g=0,h=d;if(a==0)return b;if((a/=e)==1)return b+d;g||(g=e*0.3);if(h<Math.abs(d)){h=d;c=g/4}else c=g/(2*Math.PI)*Math.asin(d/h);return-(h*Math.pow(2,10*(a-=1))*Math.sin((a*e-c)*2*Math.PI/g))+b},easeOutElastic:function(c,a,b,d,e){c=1.70158;var g=0,h=d;if(a==0)return b;if((a/=e)==1)return b+d;g||(g=e*0.3);if(h<Math.abs(d)){h=d;c=g/4}else c=g/(2*Math.PI)*Math.asin(d/h);return h*Math.pow(2,-10*a)*Math.sin((a*e-c)*2*Math.PI/g)+d+b},easeIn [...]
+a,b,d,e){c=1.70158;var g=0,h=d;if(a==0)return b;if((a/=e/2)==2)return b+d;g||(g=e*0.3*1.5);if(h<Math.abs(d)){h=d;c=g/4}else c=g/(2*Math.PI)*Math.asin(d/h);if(a<1)return-0.5*h*Math.pow(2,10*(a-=1))*Math.sin((a*e-c)*2*Math.PI/g)+b;return h*Math.pow(2,-10*(a-=1))*Math.sin((a*e-c)*2*Math.PI/g)*0.5+d+b},easeInBack:function(c,a,b,d,e,g){if(g==undefined)g=1.70158;return d*(a/=e)*a*((g+1)*a-g)+b},easeOutBack:function(c,a,b,d,e,g){if(g==undefined)g=1.70158;return d*((a=a/e-1)*a*((g+1)*a+g)+1)+b}, [...]
+a,b,d,e,g){if(g==undefined)g=1.70158;if((a/=e/2)<1)return d/2*a*a*(((g*=1.525)+1)*a-g)+b;return d/2*((a-=2)*a*(((g*=1.525)+1)*a+g)+2)+b},easeInBounce:function(c,a,b,d,e){return d-f.easing.easeOutBounce(c,e-a,0,d,e)+b},easeOutBounce:function(c,a,b,d,e){return(a/=e)<1/2.75?d*7.5625*a*a+b:a<2/2.75?d*(7.5625*(a-=1.5/2.75)*a+0.75)+b:a<2.5/2.75?d*(7.5625*(a-=2.25/2.75)*a+0.9375)+b:d*(7.5625*(a-=2.625/2.75)*a+0.984375)+b},easeInOutBounce:function(c,a,b,d,e){if(a<e/2)return f.easing.easeInBounce [...]
+d,e)*0.5+b;return f.easing.easeOutBounce(c,a*2-e,0,d,e)*0.5+d*0.5+b}})}(jQuery);
+(function(b){b.effects.blind=function(c){return this.queue(function(){var a=b(this),g=["position","top","left"],f=b.effects.setMode(a,c.options.mode||"hide"),d=c.options.direction||"vertical";b.effects.save(a,g);a.show();var e=b.effects.createWrapper(a).css({overflow:"hidden"}),h=d=="vertical"?"height":"width";d=d=="vertical"?e.height():e.width();f=="show"&&e.css(h,0);var i={};i[h]=f=="show"?d:0;e.animate(i,c.duration,c.options.easing,function(){f=="hide"&&a.hide();b.effects.restore(a,g) [...]
+c.callback&&c.callback.apply(a[0],arguments);a.dequeue()})})}})(jQuery);
+(function(e){e.effects.bounce=function(b){return this.queue(function(){var a=e(this),l=["position","top","left"],h=e.effects.setMode(a,b.options.mode||"effect"),d=b.options.direction||"up",c=b.options.distance||20,m=b.options.times||5,i=b.duration||250;/show|hide/.test(h)&&l.push("opacity");e.effects.save(a,l);a.show();e.effects.createWrapper(a);var f=d=="up"||d=="down"?"top":"left";d=d=="up"||d=="left"?"pos":"neg";c=b.options.distance||(f=="top"?a.outerHeight({margin:true})/3:a.outerWid [...]
+3);if(h=="show")a.css("opacity",0).css(f,d=="pos"?-c:c);if(h=="hide")c/=m*2;h!="hide"&&m--;if(h=="show"){var g={opacity:1};g[f]=(d=="pos"?"+=":"-=")+c;a.animate(g,i/2,b.options.easing);c/=2;m--}for(g=0;g<m;g++){var j={},k={};j[f]=(d=="pos"?"-=":"+=")+c;k[f]=(d=="pos"?"+=":"-=")+c;a.animate(j,i/2,b.options.easing).animate(k,i/2,b.options.easing);c=h=="hide"?c*2:c/2}if(h=="hide"){g={opacity:0};g[f]=(d=="pos"?"-=":"+=")+c;a.animate(g,i/2,b.options.easing,function(){a.hide();e.effects.restor [...]
+b.callback&&b.callback.apply(this,arguments)})}else{j={};k={};j[f]=(d=="pos"?"-=":"+=")+c;k[f]=(d=="pos"?"+=":"-=")+c;a.animate(j,i/2,b.options.easing).animate(k,i/2,b.options.easing,function(){e.effects.restore(a,l);e.effects.removeWrapper(a);b.callback&&b.callback.apply(this,arguments)})}a.queue("fx",function(){a.dequeue()});a.dequeue()})}})(jQuery);
+(function(b){b.effects.clip=function(e){return this.queue(function(){var a=b(this),i=["position","top","left","height","width"],f=b.effects.setMode(a,e.options.mode||"hide"),c=e.options.direction||"vertical";b.effects.save(a,i);a.show();var d=b.effects.createWrapper(a).css({overflow:"hidden"});d=a[0].tagName=="IMG"?d:a;var g={size:c=="vertical"?"height":"width",position:c=="vertical"?"top":"left"};c=c=="vertical"?d.height():d.width();if(f=="show"){d.css(g.size,0);d.css(g.position,c/2)}va [...]
+f=="show"?c:0;h[g.position]=f=="show"?0:c/2;d.animate(h,{queue:false,duration:e.duration,easing:e.options.easing,complete:function(){f=="hide"&&a.hide();b.effects.restore(a,i);b.effects.removeWrapper(a);e.callback&&e.callback.apply(a[0],arguments);a.dequeue()}})})}})(jQuery);
+(function(c){c.effects.drop=function(d){return this.queue(function(){var a=c(this),h=["position","top","left","opacity"],e=c.effects.setMode(a,d.options.mode||"hide"),b=d.options.direction||"left";c.effects.save(a,h);a.show();c.effects.createWrapper(a);var f=b=="up"||b=="down"?"top":"left";b=b=="up"||b=="left"?"pos":"neg";var g=d.options.distance||(f=="top"?a.outerHeight({margin:true})/2:a.outerWidth({margin:true})/2);if(e=="show")a.css("opacity",0).css(f,b=="pos"?-g:g);var i={opacity:e= [...]
+0};i[f]=(e=="show"?b=="pos"?"+=":"-=":b=="pos"?"-=":"+=")+g;a.animate(i,{queue:false,duration:d.duration,easing:d.options.easing,complete:function(){e=="hide"&&a.hide();c.effects.restore(a,h);c.effects.removeWrapper(a);d.callback&&d.callback.apply(this,arguments);a.dequeue()}})})}})(jQuery);
+(function(j){j.effects.explode=function(a){return this.queue(function(){var c=a.options.pieces?Math.round(Math.sqrt(a.options.pieces)):3,d=a.options.pieces?Math.round(Math.sqrt(a.options.pieces)):3;a.options.mode=a.options.mode=="toggle"?j(this).is(":visible")?"hide":"show":a.options.mode;var b=j(this).show().css("visibility","hidden"),g=b.offset();g.top-=parseInt(b.css("marginTop"),10)||0;g.left-=parseInt(b.css("marginLeft"),10)||0;for(var h=b.outerWidth(true),i=b.outerHeight(true),e=0; [...]
+0;f<d;f++)b.clone().appendTo("body").wrap("<div></div>").css({position:"absolute",visibility:"visible",left:-f*(h/d),top:-e*(i/c)}).parent().addClass("ui-effects-explode").css({position:"absolute",overflow:"hidden",width:h/d,height:i/c,left:g.left+f*(h/d)+(a.options.mode=="show"?(f-Math.floor(d/2))*(h/d):0),top:g.top+e*(i/c)+(a.options.mode=="show"?(e-Math.floor(c/2))*(i/c):0),opacity:a.options.mode=="show"?0:1}).animate({left:g.left+f*(h/d)+(a.options.mode=="show"?0:(f-Math.floor(d/2))* [...]
+e*(i/c)+(a.options.mode=="show"?0:(e-Math.floor(c/2))*(i/c)),opacity:a.options.mode=="show"?1:0},a.duration||500);setTimeout(function(){a.options.mode=="show"?b.css({visibility:"visible"}):b.css({visibility:"visible"}).hide();a.callback&&a.callback.apply(b[0]);b.dequeue();j("div.ui-effects-explode").remove()},a.duration||500)})}})(jQuery);
+(function(b){b.effects.fade=function(a){return this.queue(function(){var c=b(this),d=b.effects.setMode(c,a.options.mode||"hide");c.animate({opacity:d},{queue:false,duration:a.duration,easing:a.options.easing,complete:function(){a.callback&&a.callback.apply(this,arguments);c.dequeue()}})})}})(jQuery);
+(function(c){c.effects.fold=function(a){return this.queue(function(){var b=c(this),j=["position","top","left"],d=c.effects.setMode(b,a.options.mode||"hide"),g=a.options.size||15,h=!!a.options.horizFirst,k=a.duration?a.duration/2:c.fx.speeds._default/2;c.effects.save(b,j);b.show();var e=c.effects.createWrapper(b).css({overflow:"hidden"}),f=d=="show"!=h,l=f?["width","height"]:["height","width"];f=f?[e.width(),e.height()]:[e.height(),e.width()];var i=/([0-9]+)%/.exec(g);if(i)g=parseInt(i[1] [...]
+f[d=="hide"?0:1];if(d=="show")e.css(h?{height:0,width:g}:{height:g,width:0});h={};i={};h[l[0]]=d=="show"?f[0]:g;i[l[1]]=d=="show"?f[1]:0;e.animate(h,k,a.options.easing).animate(i,k,a.options.easing,function(){d=="hide"&&b.hide();c.effects.restore(b,j);c.effects.removeWrapper(b);a.callback&&a.callback.apply(b[0],arguments);b.dequeue()})})}})(jQuery);
+(function(b){b.effects.highlight=function(c){return this.queue(function(){var a=b(this),e=["backgroundImage","backgroundColor","opacity"],d=b.effects.setMode(a,c.options.mode||"show"),f={backgroundColor:a.css("backgroundColor")};if(d=="hide")f.opacity=0;b.effects.save(a,e);a.show().css({backgroundImage:"none",backgroundColor:c.options.color||"#ffff99"}).animate(f,{queue:false,duration:c.duration,easing:c.options.easing,complete:function(){d=="hide"&&a.hide();b.effects.restore(a,e);d=="sh [...]
+this.style.removeAttribute("filter");c.callback&&c.callback.apply(this,arguments);a.dequeue()}})})}})(jQuery);
+(function(d){d.effects.pulsate=function(a){return this.queue(function(){var b=d(this),c=d.effects.setMode(b,a.options.mode||"show");times=(a.options.times||5)*2-1;duration=a.duration?a.duration/2:d.fx.speeds._default/2;isVisible=b.is(":visible");animateTo=0;if(!isVisible){b.css("opacity",0).show();animateTo=1}if(c=="hide"&&isVisible||c=="show"&&!isVisible)times--;for(c=0;c<times;c++){b.animate({opacity:animateTo},duration,a.options.easing);animateTo=(animateTo+1)%2}b.animate({opacity:ani [...]
+a.options.easing,function(){animateTo==0&&b.hide();a.callback&&a.callback.apply(this,arguments)});b.queue("fx",function(){b.dequeue()}).dequeue()})}})(jQuery);
+(function(c){c.effects.puff=function(b){return this.queue(function(){var a=c(this),e=c.effects.setMode(a,b.options.mode||"hide"),g=parseInt(b.options.percent,10)||150,h=g/100,i={height:a.height(),width:a.width()};c.extend(b.options,{fade:true,mode:e,percent:e=="hide"?g:100,from:e=="hide"?i:{height:i.height*h,width:i.width*h}});a.effect("scale",b.options,b.duration,b.callback);a.dequeue()})};c.effects.scale=function(b){return this.queue(function(){var a=c(this),e=c.extend(true,{},b.option [...]
+b.options.mode||"effect"),h=parseInt(b.options.percent,10)||(parseInt(b.options.percent,10)==0?0:g=="hide"?0:100),i=b.options.direction||"both",f=b.options.origin;if(g!="effect"){e.origin=f||["middle","center"];e.restore=true}f={height:a.height(),width:a.width()};a.from=b.options.from||(g=="show"?{height:0,width:0}:f);h={y:i!="horizontal"?h/100:1,x:i!="vertical"?h/100:1};a.to={height:f.height*h.y,width:f.width*h.x};if(b.options.fade){if(g=="show"){a.from.opacity=0;a.to.opacity=1}if(g=="h [...]
+1;a.to.opacity=0}}e.from=a.from;e.to=a.to;e.mode=g;a.effect("size",e,b.duration,b.callback);a.dequeue()})};c.effects.size=function(b){return this.queue(function(){var a=c(this),e=["position","top","left","width","height","overflow","opacity"],g=["position","top","left","overflow","opacity"],h=["width","height","overflow"],i=["fontSize"],f=["borderTopWidth","borderBottomWidth","paddingTop","paddingBottom"],k=["borderLeftWidth","borderRightWidth","paddingLeft","paddingRight"],p=c.effects.s [...]
+b.options.mode||"effect"),n=b.options.restore||false,m=b.options.scale||"both",l=b.options.origin,j={height:a.height(),width:a.width()};a.from=b.options.from||j;a.to=b.options.to||j;if(l){l=c.effects.getBaseline(l,j);a.from.top=(j.height-a.from.height)*l.y;a.from.left=(j.width-a.from.width)*l.x;a.to.top=(j.height-a.to.height)*l.y;a.to.left=(j.width-a.to.width)*l.x}var d={from:{y:a.from.height/j.height,x:a.from.width/j.width},to:{y:a.to.height/j.height,x:a.to.width/j.width}};if(m=="box"|| [...]
+d.to.y){e=e.concat(f);a.from=c.effects.setTransition(a,f,d.from.y,a.from);a.to=c.effects.setTransition(a,f,d.to.y,a.to)}if(d.from.x!=d.to.x){e=e.concat(k);a.from=c.effects.setTransition(a,k,d.from.x,a.from);a.to=c.effects.setTransition(a,k,d.to.x,a.to)}}if(m=="content"||m=="both")if(d.from.y!=d.to.y){e=e.concat(i);a.from=c.effects.setTransition(a,i,d.from.y,a.from);a.to=c.effects.setTransition(a,i,d.to.y,a.to)}c.effects.save(a,n?e:g);a.show();c.effects.createWrapper(a);a.css("overflow"," [...]
+if(m=="content"||m=="both"){f=f.concat(["marginTop","marginBottom"]).concat(i);k=k.concat(["marginLeft","marginRight"]);h=e.concat(f).concat(k);a.find("*[width]").each(function(){child=c(this);n&&c.effects.save(child,h);var o={height:child.height(),width:child.width()};child.from={height:o.height*d.from.y,width:o.width*d.from.x};child.to={height:o.height*d.to.y,width:o.width*d.to.x};if(d.from.y!=d.to.y){child.from=c.effects.setTransition(child,f,d.from.y,child.from);child.to=c.effects.se [...]
+f,d.to.y,child.to)}if(d.from.x!=d.to.x){child.from=c.effects.setTransition(child,k,d.from.x,child.from);child.to=c.effects.setTransition(child,k,d.to.x,child.to)}child.css(child.from);child.animate(child.to,b.duration,b.options.easing,function(){n&&c.effects.restore(child,h)})})}a.animate(a.to,{queue:false,duration:b.duration,easing:b.options.easing,complete:function(){a.to.opacity===0&&a.css("opacity",a.from.opacity);p=="hide"&&a.hide();c.effects.restore(a,n?e:g);c.effects.removeWrapper [...]
+b.callback.apply(this,arguments);a.dequeue()}})})}})(jQuery);
+(function(d){d.effects.shake=function(a){return this.queue(function(){var b=d(this),j=["position","top","left"];d.effects.setMode(b,a.options.mode||"effect");var c=a.options.direction||"left",e=a.options.distance||20,l=a.options.times||3,f=a.duration||a.options.duration||140;d.effects.save(b,j);b.show();d.effects.createWrapper(b);var g=c=="up"||c=="down"?"top":"left",h=c=="up"||c=="left"?"pos":"neg";c={};var i={},k={};c[g]=(h=="pos"?"-=":"+=")+e;i[g]=(h=="pos"?"+=":"-=")+e*2;k[g]=(h=="po [...]
+e*2;b.animate(c,f,a.options.easing);for(e=1;e<l;e++)b.animate(i,f,a.options.easing).animate(k,f,a.options.easing);b.animate(i,f,a.options.easing).animate(c,f/2,a.options.easing,function(){d.effects.restore(b,j);d.effects.removeWrapper(b);a.callback&&a.callback.apply(this,arguments)});b.queue("fx",function(){b.dequeue()});b.dequeue()})}})(jQuery);
+(function(c){c.effects.slide=function(d){return this.queue(function(){var a=c(this),h=["position","top","left"],e=c.effects.setMode(a,d.options.mode||"show"),b=d.options.direction||"left";c.effects.save(a,h);a.show();c.effects.createWrapper(a).css({overflow:"hidden"});var f=b=="up"||b=="down"?"top":"left";b=b=="up"||b=="left"?"pos":"neg";var g=d.options.distance||(f=="top"?a.outerHeight({margin:true}):a.outerWidth({margin:true}));if(e=="show")a.css(f,b=="pos"?-g:g);var i={};i[f]=(e=="sho [...]
+"+=":"-=":b=="pos"?"-=":"+=")+g;a.animate(i,{queue:false,duration:d.duration,easing:d.options.easing,complete:function(){e=="hide"&&a.hide();c.effects.restore(a,h);c.effects.removeWrapper(a);d.callback&&d.callback.apply(this,arguments);a.dequeue()}})})}})(jQuery);
+(function(e){e.effects.transfer=function(a){return this.queue(function(){var b=e(this),c=e(a.options.to),d=c.offset();c={top:d.top,left:d.left,height:c.innerHeight(),width:c.innerWidth()};d=b.offset();var f=e('<div class="ui-effects-transfer"></div>').appendTo(document.body).addClass(a.options.className).css({top:d.top,left:d.left,height:b.innerHeight(),width:b.innerWidth(),position:"absolute"}).animate(c,a.duration,a.options.easing,function(){f.remove();a.callback&&a.callback.apply(b[0] [...]
+b.dequeue()})})}})(jQuery);
+(function(d){d.widget("ui.accordion",{options:{active:0,animated:"slide",autoHeight:true,clearStyle:false,collapsible:false,event:"click",fillSpace:false,header:"> li > :first-child,> :not(li):even",icons:{header:"ui-icon-triangle-1-e",headerSelected:"ui-icon-triangle-1-s"},navigation:false,navigationFilter:function(){return this.href.toLowerCase()==location.href.toLowerCase()}},_create:function(){var a=this.options,b=this;this.running=0;this.element.addClass("ui-accordion ui-widget ui-h [...]
+this.element.children("li").addClass("ui-accordion-li-fix");this.headers=this.element.find(a.header).addClass("ui-accordion-header ui-helper-reset ui-state-default ui-corner-all").bind("mouseenter.accordion",function(){d(this).addClass("ui-state-hover")}).bind("mouseleave.accordion",function(){d(this).removeClass("ui-state-hover")}).bind("focus.accordion",function(){d(this).addClass("ui-state-focus")}).bind("blur.accordion",function(){d(this).removeClass("ui-state-focus")});this.headers. [...]
+if(a.navigation){var c=this.element.find("a").filter(a.navigationFilter);if(c.length){var f=c.closest(".ui-accordion-header");this.active=f.length?f:c.closest(".ui-accordion-content").prev()}}this.active=this._findActive(this.active||a.active).toggleClass("ui-state-default").toggleClass("ui-state-active").toggleClass("ui-corner-all").toggleClass("ui-corner-top");this.active.next().addClass("ui-accordion-content-active");this._createIcons();this.resize();this.element.attr("role","tablist" [...]
+"tab").bind("keydown",function(g){return b._keydown(g)}).next().attr("role","tabpanel");this.headers.not(this.active||"").attr("aria-expanded","false").attr("tabIndex","-1").next().hide();this.active.length?this.active.attr("aria-expanded","true").attr("tabIndex","0"):this.headers.eq(0).attr("tabIndex","0");d.browser.safari||this.headers.find("a").attr("tabIndex","-1");a.event&&this.headers.bind(a.event+".accordion",function(g){b._clickHandler.call(b,g,this);g.preventDefault()})},_create [...]
+this.options;if(a.icons){d("<span/>").addClass("ui-icon "+a.icons.header).prependTo(this.headers);this.active.find(".ui-icon").toggleClass(a.icons.header).toggleClass(a.icons.headerSelected);this.element.addClass("ui-accordion-icons")}},_destroyIcons:function(){this.headers.children(".ui-icon").remove();this.element.removeClass("ui-accordion-icons")},destroy:function(){var a=this.options;this.element.removeClass("ui-accordion ui-widget ui-helper-reset").removeAttr("role").unbind(".accord [...]
+this.headers.unbind(".accordion").removeClass("ui-accordion-header ui-helper-reset ui-state-default ui-corner-all ui-state-active ui-corner-top").removeAttr("role").removeAttr("aria-expanded").removeAttr("tabIndex");this.headers.find("a").removeAttr("tabIndex");this._destroyIcons();var b=this.headers.next().css("display","").removeAttr("role").removeClass("ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content ui-accordion-content-active");if(a.autoHeight||a.fillHeight)b [...]
+"");return this},_setOption:function(a,b){this._superApply("_setOption",arguments);a=="active"&&this.activate(b);if(a=="icons"){this._destroyIcons();b&&this._createIcons()}},_keydown:function(a){var b=d.ui.keyCode;if(!(this.options.disabled||a.altKey||a.ctrlKey)){var c=this.headers.length,f=this.headers.index(a.target),g=false;switch(a.keyCode){case b.RIGHT:case b.DOWN:g=this.headers[(f+1)%c];break;case b.LEFT:case b.UP:g=this.headers[(f-1+c)%c];break;case b.SPACE:case b.ENTER:this._clic [...]
+a.target);a.preventDefault()}if(g){d(a.target).attr("tabIndex","-1");d(g).attr("tabIndex","0");g.focus();return false}return true}},resize:function(){var a=this.options,b;if(a.fillSpace){if(d.browser.msie){var c=this.element.parent().css("overflow");this.element.parent().css("overflow","hidden")}b=this.element.parent().height();d.browser.msie&&this.element.parent().css("overflow",c);this.headers.each(function(){b-=d(this).outerHeight(true)});this.headers.next().each(function(){d(this).he [...]
+b-d(this).innerHeight()+d(this).height()))}).css("overflow","auto")}else if(a.autoHeight){b=0;this.headers.next().each(function(){b=Math.max(b,d(this).height())}).height(b)}return this},activate:function(a){this.options.active=a;a=this._findActive(a)[0];this._clickHandler({target:a},a);return this},_findActive:function(a){return a?typeof a=="number"?this.headers.filter(":eq("+a+")"):this.headers.not(this.headers.not(a)):a===false?d([]):this.headers.filter(":eq(0)")},_clickHandler:functio [...]
+this.options;if(!c.disabled)if(a.target){a=d(a.currentTarget||b);b=a[0]==this.active[0];c.active=c.collapsible&&b?false:d(".ui-accordion-header",this.element).index(a);if(!(this.running||!c.collapsible&&b)){this.active.removeClass("ui-state-active ui-corner-top").addClass("ui-state-default ui-corner-all").find(".ui-icon").removeClass(c.icons.headerSelected).addClass(c.icons.header);if(!b){a.removeClass("ui-state-default ui-corner-all").addClass("ui-state-active ui-corner-top").find(".ui- [...]
+a.next().addClass("ui-accordion-content-active")}e=a.next();f=this.active.next();g={options:c,newHeader:b&&c.collapsible?d([]):a,oldHeader:this.active,newContent:b&&c.collapsible?d([]):e,oldContent:f};c=this.headers.index(this.active[0])>this.headers.index(a[0]);this.active=b?d([]):a;this._toggle(e,f,g,b,c)}}else if(c.collapsible){this.active.removeClass("ui-state-active ui-corner-top").addClass("ui-state-default ui-corner-all").find(".ui-icon").removeClass(c.icons.headerSelected).addCla [...]
+this.active.next().addClass("ui-accordion-content-active");var f=this.active.next(),g={options:c,newHeader:d([]),oldHeader:c.active,newContent:d([]),oldContent:f},e=this.active=d([]);this._toggle(e,f,g)}},_toggle:function(a,b,c,f,g){var e=this.options,k=this;this.toShow=a;this.toHide=b;this.data=c;var i=function(){if(k)return k._completed.apply(k,arguments)};this._trigger("changestart",null,this.data);this.running=b.size()===0?a.size():b.size();if(e.animated){c={};c=e.collapsible&&f?{toS [...]
+toHide:b,complete:i,down:g,autoHeight:e.autoHeight||e.fillSpace}:{toShow:a,toHide:b,complete:i,down:g,autoHeight:e.autoHeight||e.fillSpace};if(!e.proxied)e.proxied=e.animated;if(!e.proxiedDuration)e.proxiedDuration=e.duration;e.animated=d.isFunction(e.proxied)?e.proxied(c):e.proxied;e.duration=d.isFunction(e.proxiedDuration)?e.proxiedDuration(c):e.proxiedDuration;f=d.ui.accordion.animations;var h=e.duration,j=e.animated;if(j&&!f[j]&&!d.easing[j])j="slide";f[j]||(f[j]=function(l){this.sli [...]
+duration:h||700})});f[j](c)}else{if(e.collapsible&&f)a.toggle();else{b.hide();a.show()}i(true)}b.prev().attr("aria-expanded","false").attr("tabIndex","-1").blur();a.prev().attr("aria-expanded","true").attr("tabIndex","0").focus()},_completed:function(a){var b=this.options;this.running=a?0:--this.running;if(!this.running){b.clearStyle&&this.toShow.add(this.toHide).css({height:"",overflow:""});this.toHide.removeClass("ui-accordion-content-active");this._trigger("change",null,this.data)}}}) [...]
+{version:"1.9m2",animations:{slide:function(a,b){a=d.extend({easing:"swing",duration:300},a,b);if(a.toHide.size())if(a.toShow.size()){var c=a.toShow.css("overflow"),f=0,g={},e={},k;b=a.toShow;k=b[0].style.width;b.width(parseInt(b.parent().width(),10)-parseInt(b.css("paddingLeft"),10)-parseInt(b.css("paddingRight"),10)-(parseInt(b.css("borderLeftWidth"),10)||0)-(parseInt(b.css("borderRightWidth"),10)||0));d.each(["height","paddingTop","paddingBottom"],function(i,h){e[h]="hide";i=(""+d.css [...]
+h)).match(/^([\d+-.]+)(.*)$/);g[h]={value:i[1],unit:i[2]||"px"}});a.toShow.css({height:0,overflow:"hidden"}).show();a.toHide.filter(":hidden").each(a.complete).end().filter(":visible").animate(e,{step:function(i,h){if(h.prop=="height")f=h.end-h.start===0?0:(h.now-h.start)/(h.end-h.start);a.toShow[0].style[h.prop]=f*g[h.prop].value+g[h.prop].unit},duration:a.duration,easing:a.easing,complete:function(){a.autoHeight||a.toShow.css("height","");a.toShow.css("width",k);a.toShow.css({overflow: [...]
+a);else a.toShow.animate({height:"show"},a)},bounceslide:function(a){this.slide(a,{easing:a.down?"easeOutBounce":"swing",duration:a.down?1E3:200})}}})})(jQuery);
+(function(e){e.widget("ui.autocomplete",{options:{minLength:1,delay:300},_create:function(){var a=this,d=this.element[0].ownerDocument;this.element.addClass("ui-autocomplete-input").attr("autocomplete","off").attr({role:"textbox","aria-autocomplete":"list","aria-haspopup":"true"}).bind("keydown.autocomplete",function(c){var b=e.ui.keyCode;switch(c.keyCode){case b.PAGE_UP:a._move("previousPage",c);break;case b.PAGE_DOWN:a._move("nextPage",c);break;case b.UP:a._move("previous",c);c.prevent [...]
+break;case b.DOWN:a._move("next",c);c.preventDefault();break;case b.ENTER:case b.NUMPAD_ENTER:a.menu.active&&c.preventDefault();case b.TAB:if(!a.menu.active)return;a.menu.select(c);break;case b.ESCAPE:a.element.val(a.term);a.close(c);break;case b.LEFT:case b.RIGHT:case b.SHIFT:case b.CONTROL:case b.ALT:case b.COMMAND:case b.COMMAND_RIGHT:case b.INSERT:case b.CAPS_LOCK:case b.END:case b.HOME:break;default:clearTimeout(a.searching);a.searching=setTimeout(function(){a.search(null,c)},a.opti [...]
+break}}).bind("focus.autocomplete",function(){a.selectedItem=null;a.previous=a.element.val()}).bind("blur.autocomplete",function(c){clearTimeout(a.searching);a.closing=setTimeout(function(){a.close(c);a._change(c)},150)});this._initSource();this.response=function(){return a._response.apply(a,arguments)};this.menu=e("<ul></ul>").addClass("ui-autocomplete").appendTo("body",d).mousedown(function(){setTimeout(function(){clearTimeout(a.closing)},13)}).menu({input:e(),focus:function(c,b){b=b.i [...]
+false!==a._trigger("focus",null,{item:b})&&/^key/.test(c.originalEvent.type)&&a.element.val(b.value)},select:function(c,b){b=b.item.data("item.autocomplete");false!==a._trigger("select",c,{item:b})&&a.element.val(b.value);a.close(c);c=a.previous;if(a.element[0]!==d.activeElement){a.element.focus();a.previous=c}a.selectedItem=b},blur:function(){a.menu.element.is(":visible")&&a.element.val(a.term)}}).zIndex(this.element.zIndex()+1).css({top:0,left:0}).hide().data("menu");e.fn.bgiframe&&thi [...]
+destroy:function(){this.element.removeClass("ui-autocomplete-input").removeAttr("autocomplete").removeAttr("role").removeAttr("aria-autocomplete").removeAttr("aria-haspopup");this.menu.element.remove();this._super("destroy")},_setOption:function(a){this._superApply("_setOption",arguments);a==="source"&&this._initSource()},_initSource:function(){var a,d;if(e.isArray(this.options.source)){a=this.options.source;this.source=function(c,b){b(e.ui.autocomplete.filter(a,c.term))}}else if(typeof  [...]
+"string"){d=this.options.source;this.source=function(c,b){e.getJSON(d,c,b)}}else this.source=this.options.source},search:function(a,d){a=a!=null?a:this.element.val();if(a.length<this.options.minLength)return this.close(d);clearTimeout(this.closing);if(this._trigger("search")!==false)return this._search(a)},_search:function(a){this.term=this.element.addClass("ui-autocomplete-loading").val();this.source({term:a},this.response)},_response:function(a){if(a.length){a=this._normalize(a);this._ [...]
+this._trigger("open")}else this.close();this.element.removeClass("ui-autocomplete-loading")},close:function(a){clearTimeout(this.closing);if(this.menu.element.is(":visible")){this._trigger("close",a);this.menu.element.hide();this.menu.deactivate()}},_change:function(a){this.previous!==this.element.val()&&this._trigger("change",a,{item:this.selectedItem})},_normalize:function(a){if(a.length&&a[0].label&&a[0].value)return a;return e.map(a,function(d){if(typeof d==="string")return{label:d,v [...]
+d.value,value:d.value||d.label},d)})},_suggest:function(a){var d=this.menu.element.empty().zIndex(this.element.zIndex()+1),c;this._renderMenu(d,a);this.menu.deactivate();this.menu.refresh();this.menu.element.show().position({my:"left top",at:"left bottom",of:this.element,collision:"none"});a=d.width("").width();c=this.element.width();d.width(Math.max(a,c))},_renderMenu:function(a,d){var c=this;e.each(d,function(b,f){c._renderItem(a,f)})},_renderItem:function(a,d){return e("<li></li>").da [...]
+d).append("<a>"+d.label+"</a>").appendTo(a)},_move:function(a,d){if(this.menu.element.is(":visible"))if(this.menu.first()&&/^previous/.test(a)||this.menu.last()&&/^next/.test(a)){this.element.val(this.term);this.menu.deactivate()}else this.menu[a](d);else this.search(null,d)},widget:function(){return this.menu.element}});e.extend(e.ui.autocomplete,{escapeRegex:function(a){return a.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi,"\\$1")},filter:function(a,d){var c=new RegExp(e.ui.autocomplet [...]
+"i");return e.grep(a,function(b){return c.test(b.label||b.value||b)})}})})(jQuery);
+(function(a){var g,i=function(b){a(":ui-button",b.target.form).each(function(){var c=a(this).data("button");setTimeout(function(){c.refresh()},1)})},h=function(b){var c=b.name,d=b.form,e=a([]);if(c)e=d?a(d).find("[name='"+c+"']"):a("[name='"+c+"']",b.ownerDocument).filter(function(){return!this.form});return e};a.widget("ui.button",{options:{text:true,label:null,icons:{primary:null,secondary:null}},_create:function(){this.element.closest("form").unbind("reset.button").bind("reset.button" [...]
+this.hasTitle=!!this.buttonElement.attr("title");var b=this,c=this.options,d=this.type==="checkbox"||this.type==="radio",e="ui-state-hover"+(!d?" ui-state-active":"");if(c.label===null)c.label=this.buttonElement.html();if(this.element.is(":disabled"))c.disabled=true;this.buttonElement.addClass("ui-button ui-widget ui-state-default ui-corner-all").attr("role","button").bind("mouseenter.button",function(){if(!c.disabled){a(this).addClass("ui-state-hover");this===g&&a(this).addClass("ui-sta [...]
+function(){c.disabled||a(this).removeClass(e)}).bind("focus.button",function(){a(this).addClass("ui-state-focus")}).bind("blur.button",function(){a(this).removeClass("ui-state-focus")});d&&this.element.bind("change.button",function(){b.refresh()});if(this.type==="checkbox")this.buttonElement.bind("click.button",function(){if(c.disabled)return false;a(this).toggleClass("ui-state-active");b.buttonElement.attr("aria-pressed",b.element[0].checked)});else if(this.type==="radio")this.buttonEle [...]
+function(){if(c.disabled)return false;a(this).addClass("ui-state-active");b.buttonElement.attr("aria-pressed",true);var f=b.element[0];h(f).not(f).map(function(){return a(this).button("widget")[0]}).removeClass("ui-state-active").attr("aria-pressed",false)});else{this.buttonElement.bind("mousedown.button",function(){if(c.disabled)return false;a(this).addClass("ui-state-active");g=this;a(document).one("mouseup",function(){g=null})}).bind("mouseup.button",function(){if(c.disabled)return fa [...]
+function(f){if(c.disabled)return false;if(f.keyCode==a.ui.keyCode.SPACE||f.keyCode==a.ui.keyCode.ENTER)a(this).addClass("ui-state-active")}).bind("keyup.button",function(){a(this).removeClass("ui-state-active")});this.buttonElement.is("a")&&this.buttonElement.keyup(function(f){f.keyCode===a.ui.keyCode.SPACE&&a(this).click()})}this._setOption("disabled",c.disabled)},_determineButtonType:function(){this.type=this.element.is(":checkbox")?"checkbox":this.element.is(":radio")?"radio":this.ele [...]
+"input":"button";if(this.type==="checkbox"||this.type==="radio"){this.buttonElement=this.element.parents().last().find("[for="+this.element.attr("id")+"]");this.element.addClass("ui-helper-hidden-accessible");var b=this.element.is(":checked");b&&this.buttonElement.addClass("ui-state-active");this.buttonElement.attr("aria-pressed",b)}else this.buttonElement=this.element},widget:function(){return this.buttonElement},destroy:function(){this.element.removeClass("ui-helper-hidden-accessible") [...]
+this.hasTitle||this.buttonElement.removeAttr("title");this._super("destroy")},_setOption:function(b,c){this._superApply("_setOption",arguments);if(b==="disabled")c?this.element.attr("disabled",true):this.element.removeAttr("disabled");this._resetButton()},refresh:function(){var b=this.element.is(":disabled");b!==this.options.disabled&&this._setOption("disabled",b);if(this.type==="radio")h(this.element[0]).each(function(){a(this).is(":checked")?a(this).button("widget").addClass("ui-state- [...]
+true):a(this).button("widget").removeClass("ui-state-active").attr("aria-pressed",false)});else if(this.type==="checkbox")this.element.is(":checked")?this.buttonElement.addClass("ui-state-active").attr("aria-pressed",true):this.buttonElement.removeClass("ui-state-active").attr("aria-pressed",false)},_resetButton:function(){if(this.type==="input")this.options.label&&this.element.val(this.options.label);else{var b=this.buttonElement.removeClass("ui-button-icons-only ui-button-icon-only ui- [...]
+c=a("<span></span>").addClass("ui-button-text").html(this.options.label).appendTo(b.empty()).text(),d=this.options.icons,e=d.primary&&d.secondary;if(d.primary||d.secondary){b.addClass("ui-button-text-icon"+(e?"s":d.primary?"-primary":"-secondary"));d.primary&&b.prepend("<span class='ui-button-icon-primary ui-icon "+d.primary+"'></span>");d.secondary&&b.append("<span class='ui-button-icon-secondary ui-icon "+d.secondary+"'></span>");if(!this.options.text){b.addClass(e?"ui-button-icons-onl [...]
+this.hasTitle||b.attr("title",c)}}else b.addClass("ui-button-text-only")}}});a.widget("ui.buttonset",{_create:function(){this.element.addClass("ui-buttonset");this._init()},_init:function(){this.refresh()},_setOption:function(b,c){b==="disabled"&&this.buttons.button("option",b,c);this._superApply("_setOption",arguments)},refresh:function(){this.buttons=this.element.find(":button, :submit, :reset, :checkbox, :radio, a, :data(button)").filter(":ui-button").button("refresh").end().not(":ui- [...]
+destroy:function(){this.element.removeClass("ui-buttonset");this.buttons.map(function(){return a(this).button("widget")[0]}).removeClass("ui-corner-left ui-corner-right").end().button("destroy");this._super("destroy")}})})(jQuery);
+(function(d){function K(){this.debug=false;this._curInst=null;this._keyEvent=false;this._disabledInputs=[];this._inDialog=this._datepickerShowing=false;this._mainDivId="ui-datepicker-div";this._inlineClass="ui-datepicker-inline";this._appendClass="ui-datepicker-append";this._triggerClass="ui-datepicker-trigger";this._dialogClass="ui-datepicker-dialog";this._disableClass="ui-datepicker-disabled";this._unselectableClass="ui-datepicker-unselectable";this._currentClass="ui-datepicker-current [...]
+"ui-datepicker-days-cell-over";this.regional=[];this.regional[""]={closeText:"Done",prevText:"Prev",nextText:"Next",currentText:"Today",monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],monthNamesShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayNamesShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],day [...]
+"Mo","Tu","We","Th","Fr","Sa"],weekHeader:"Wk",dateFormat:"mm/dd/yy",firstDay:0,isRTL:false,showMonthAfterYear:false,yearSuffix:""};this._defaults={showOn:"focus",showAnim:"fadeIn",showOptions:{},defaultDate:null,appendText:"",buttonText:"...",buttonImage:"",buttonImageOnly:false,hideIfNoPrevNext:false,navigationAsDateFormat:false,gotoCurrent:false,changeMonth:false,changeYear:false,yearRange:"c-10:c+10",showOtherMonths:false,selectOtherMonths:false,showWeek:false,calculateWeek:this.iso8 [...]
+minDate:null,maxDate:null,duration:"fast",beforeShowDay:null,beforeShow:null,onSelect:null,onChangeMonthYear:null,onClose:null,numberOfMonths:1,showCurrentAtPos:0,stepMonths:1,stepBigMonths:12,altField:"",altFormat:"",constrainInput:true,showButtonPanel:false,autoSize:false};d.extend(this._defaults,this.regional[""]);this.dpDiv=d('<div id="'+this._mainDivId+'" class="ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all ui-helper-hidden-accessible"></div>')}function  [...]
+b);for(var c in b)if(b[c]==null||b[c]==undefined)a[c]=b[c];return a}d.extend(d.ui,{datepicker:{version:"1.9m2"}});var y=(new Date).getTime();d.extend(K.prototype,{markerClassName:"hasDatepicker",log:function(){this.debug&&console.log.apply("",arguments)},_widgetDatepicker:function(){return this.dpDiv},setDefaults:function(a){E(this._defaults,a||{});return this},_attachDatepicker:function(a,b){var c=null;for(var e in this._defaults){var f=a.getAttribute("date:"+e);if(f){c=c||{};try{c[e]=e [...]
+f}}}e=a.nodeName.toLowerCase();f=e=="div"||e=="span";if(!a.id){this.uuid+=1;a.id="dp"+this.uuid}var i=this._newInst(d(a),f);i.settings=d.extend({},b||{},c||{});if(e=="input")this._connectDatepicker(a,i);else f&&this._inlineDatepicker(a,i)},_newInst:function(a,b){return{id:a[0].id.replace(/([^A-Za-z0-9_])/g,"\\\\$1"),input:a,selectedDay:0,selectedMonth:0,selectedYear:0,drawMonth:0,drawYear:0,inline:b,dpDiv:!b?this.dpDiv:d('<div class="'+this._inlineClass+' ui-datepicker ui-widget ui-widge [...]
+_connectDatepicker:function(a,b){var c=d(a);b.append=d([]);b.trigger=d([]);if(!c.hasClass(this.markerClassName)){this._attachments(c,b);c.addClass(this.markerClassName).keydown(this._doKeyDown).keypress(this._doKeyPress).keyup(this._doKeyUp).bind("setData.datepicker",function(e,f,h){b.settings[f]=h}).bind("getData.datepicker",function(e,f){return this._get(b,f)});this._autoSize(b);d.data(a,"datepicker",b)}},_attachments:function(a,b){var c=this._get(b,"appendText"),e=this._get(b,"isRTL") [...]
+b.append.remove();if(c){b.append=d('<span class="'+this._appendClass+'">'+c+"</span>");a[e?"before":"after"](b.append)}a.unbind("focus",this._showDatepicker);b.trigger&&b.trigger.remove();c=this._get(b,"showOn");if(c=="focus"||c=="both")a.focus(this._showDatepicker);if(c=="button"||c=="both"){c=this._get(b,"buttonText");var f=this._get(b,"buttonImage");b.trigger=d(this._get(b,"buttonImageOnly")?d("<img/>").addClass(this._triggerClass).attr({src:f,alt:c,title:c}):d('<button type="button"> [...]
+""?c:d("<img/>").attr({src:f,alt:c,title:c})));a[e?"before":"after"](b.trigger);b.trigger.click(function(){d.datepicker._datepickerShowing&&d.datepicker._lastInput==a[0]?d.datepicker._hideDatepicker():d.datepicker._showDatepicker(a[0]);return false})}},_autoSize:function(a){if(this._get(a,"autoSize")&&!a.inline){var b=new Date(2009,11,20),c=this._get(a,"dateFormat");if(c.match(/[DM]/)){var e=function(f){for(var h=0,i=0,g=0;g<f.length;g++)if(f[g].length>h){h=f[g].length;i=g}return i};b.se [...]
+c.match(/MM/)?"monthNames":"monthNamesShort")));b.setDate(e(this._get(a,c.match(/DD/)?"dayNames":"dayNamesShort"))+20-b.getDay())}a.input.attr("size",this._formatDate(a,b).length)}},_inlineDatepicker:function(a,b){var c=d(a);if(!c.hasClass(this.markerClassName)){c.addClass(this.markerClassName).append(b.dpDiv).bind("setData.datepicker",function(e,f,h){b.settings[f]=h}).bind("getData.datepicker",function(e,f){return this._get(b,f)});d.data(a,"datepicker",b);this._setDate(b,this._getDefaul [...]
+true);this._updateDatepicker(b);this._updateAlternate(b)}},_dialogDatepicker:function(a,b,c,e,f){a=this._dialogInst;if(!a){this.uuid+=1;this._dialogInput=d('<input type="text" id="'+("dp"+this.uuid)+'" style="position: absolute; top: -100px; width: 0px; z-index: -10;"/>');this._dialogInput.keydown(this._doKeyDown);d("body").append(this._dialogInput);a=this._dialogInst=this._newInst(this._dialogInput,false);a.settings={};d.data(this._dialogInput[0],"datepicker",a)}E(a.settings,e||{});b=b& [...]
+Date?this._formatDate(a,b):b;this._dialogInput.val(b);this._pos=f?f.length?f:[f.pageX,f.pageY]:null;if(!this._pos)this._pos=[document.documentElement.clientWidth/2-100+(document.documentElement.scrollLeft||document.body.scrollLeft),document.documentElement.clientHeight/2-150+(document.documentElement.scrollTop||document.body.scrollTop)];this._dialogInput.css("left",this._pos[0]+20+"px").css("top",this._pos[1]+"px");a.settings.onSelect=c;this._inDialog=true;this.dpDiv.addClass(this._dialo [...]
+d.blockUI&&d.blockUI(this.dpDiv);d.data(this._dialogInput[0],"datepicker",a);return this},_destroyDatepicker:function(a){var b=d(a),c=d.data(a,"datepicker");if(b.hasClass(this.markerClassName)){var e=a.nodeName.toLowerCase();d.removeData(a,"datepicker");if(e=="input"){c.append.remove();c.trigger.remove();b.removeClass(this.markerClassName).unbind("focus",this._showDatepicker).unbind("keydown",this._doKeyDown).unbind("keypress",this._doKeyPress).unbind("keyup",this._doKeyUp)}else if(e=="d [...]
+_enableDatepicker:function(a){var b=d(a),c=d.data(a,"datepicker");if(b.hasClass(this.markerClassName)){var e=a.nodeName.toLowerCase();if(e=="input"){a.disabled=false;c.trigger.filter("button").each(function(){this.disabled=false}).end().filter("img").css({opacity:"1.0",cursor:""})}else if(e=="div"||e=="span")b.children("."+this._inlineClass).children().removeClass("ui-state-disabled");this._disabledInputs=d.map(this._disabledInputs,function(f){return f==a?null:f})}},_disableDatepicker:fu [...]
+d(a),c=d.data(a,"datepicker");if(b.hasClass(this.markerClassName)){var e=a.nodeName.toLowerCase();if(e=="input"){a.disabled=true;c.trigger.filter("button").each(function(){this.disabled=true}).end().filter("img").css({opacity:"0.5",cursor:"default"})}else if(e=="div"||e=="span")b.children("."+this._inlineClass).children().addClass("ui-state-disabled");this._disabledInputs=d.map(this._disabledInputs,function(f){return f==a?null:f});this._disabledInputs[this._disabledInputs.length]=a}},_is [...]
+for(var b=0;b<this._disabledInputs.length;b++)if(this._disabledInputs[b]==a)return true;return false},_getInst:function(a){try{return d.data(a,"datepicker")}catch(b){throw"Missing instance data for this datepicker";}},_optionDatepicker:function(a,b,c){var e=this._getInst(a);if(arguments.length==2&&typeof b=="string")return b=="defaults"?d.extend({},d.datepicker._defaults):e?b=="all"?d.extend({},e.settings):this._get(e,b):null;var f=b||{};if(typeof b=="string"){f={};f[b]=c}if(e){this._cur [...]
+this._hideDatepicker();var h=this._getDateDatepicker(a,true);E(e.settings,f);this._attachments(d(a),e);this._autoSize(e);this._setDateDatepicker(a,h);this._updateDatepicker(e)}},_changeDatepicker:function(a,b,c){this._optionDatepicker(a,b,c)},_refreshDatepicker:function(a){(a=this._getInst(a))&&this._updateDatepicker(a)},_setDateDatepicker:function(a,b){if(a=this._getInst(a)){this._setDate(a,b);this._updateDatepicker(a);this._updateAlternate(a)}},_getDateDatepicker:function(a,b){(a=this. [...]
+!a.inline&&this._setDateFromField(a,b);return a?this._getDate(a):null},_doKeyDown:function(a){var b=d.datepicker._getInst(a.target),c=true,e=b.dpDiv.is(".ui-datepicker-rtl");b._keyEvent=true;if(d.datepicker._datepickerShowing)switch(a.keyCode){case 9:d.datepicker._hideDatepicker();c=false;break;case 13:c=d("td."+d.datepicker._dayOverClass,b.dpDiv).add(d("td."+d.datepicker._currentClass,b.dpDiv));c[0]?d.datepicker._selectDay(a.target,b.selectedMonth,b.selectedYear,c[0]):d.datepicker._hide [...]
+return false;case 27:d.datepicker._hideDatepicker();break;case 33:d.datepicker._adjustDate(a.target,a.ctrlKey?-d.datepicker._get(b,"stepBigMonths"):-d.datepicker._get(b,"stepMonths"),"M");break;case 34:d.datepicker._adjustDate(a.target,a.ctrlKey?+d.datepicker._get(b,"stepBigMonths"):+d.datepicker._get(b,"stepMonths"),"M");break;case 35:if(a.ctrlKey||a.metaKey)d.datepicker._clearDate(a.target);c=a.ctrlKey||a.metaKey;break;case 36:if(a.ctrlKey||a.metaKey)d.datepicker._gotoToday(a.target);c [...]
+a.metaKey;break;case 37:if(a.ctrlKey||a.metaKey)d.datepicker._adjustDate(a.target,e?+1:-1,"D");c=a.ctrlKey||a.metaKey;if(a.originalEvent.altKey)d.datepicker._adjustDate(a.target,a.ctrlKey?-d.datepicker._get(b,"stepBigMonths"):-d.datepicker._get(b,"stepMonths"),"M");break;case 38:if(a.ctrlKey||a.metaKey)d.datepicker._adjustDate(a.target,-7,"D");c=a.ctrlKey||a.metaKey;break;case 39:if(a.ctrlKey||a.metaKey)d.datepicker._adjustDate(a.target,e?-1:+1,"D");c=a.ctrlKey||a.metaKey;if(a.originalEv [...]
+a.ctrlKey?+d.datepicker._get(b,"stepBigMonths"):+d.datepicker._get(b,"stepMonths"),"M");break;case 40:if(a.ctrlKey||a.metaKey)d.datepicker._adjustDate(a.target,+7,"D");c=a.ctrlKey||a.metaKey;break;default:c=false}else if(a.keyCode==36&&a.ctrlKey)d.datepicker._showDatepicker(this);else c=false;if(c){a.preventDefault();a.stopPropagation()}},_doKeyPress:function(a){var b=d.datepicker._getInst(a.target);if(d.datepicker._get(b,"constrainInput")){b=d.datepicker._possibleChars(d.datepicker._get [...]
+var c=String.fromCharCode(a.charCode==undefined?a.keyCode:a.charCode);return a.ctrlKey||c<" "||!b||b.indexOf(c)>-1}},_doKeyUp:function(a){a=d.datepicker._getInst(a.target);if(a.input.val()!=a.lastVal)try{if(d.datepicker.parseDate(d.datepicker._get(a,"dateFormat"),a.input?a.input.val():null,d.datepicker._getFormatConfig(a))){d.datepicker._setDateFromField(a);d.datepicker._updateAlternate(a);d.datepicker._updateDatepicker(a)}}catch(b){d.datepicker.log(b)}return true},_showDatepicker:functi [...]
+a;if(a.nodeName.toLowerCase()!="input")a=d("input",a.parentNode)[0];if(!(d.datepicker._isDisabledDatepicker(a)||d.datepicker._lastInput==a)){var b=d.datepicker._getInst(a);d.datepicker._curInst&&d.datepicker._curInst!=b&&d.datepicker._curInst.dpDiv.stop(true,true);var c=d.datepicker._get(b,"beforeShow");E(b.settings,c?c.apply(a,[a,b]):{});b.lastVal=null;d.datepicker._lastInput=a;d.datepicker._setDateFromField(b);if(d.datepicker._inDialog)a.value="";if(!d.datepicker._pos){d.datepicker._po [...]
+d.datepicker._pos[1]+=a.offsetHeight}var e=false;d(a).parents().each(function(){e|=d(this).css("position")=="fixed";return!e});if(e&&d.browser.opera){d.datepicker._pos[0]-=document.documentElement.scrollLeft;d.datepicker._pos[1]-=document.documentElement.scrollTop}c={left:d.datepicker._pos[0],top:d.datepicker._pos[1]};d.datepicker._pos=null;b.dpDiv.css({position:"absolute",display:"block",top:"-1000px"});d.datepicker._updateDatepicker(b);c=d.datepicker._checkOffset(b,c,e);b.dpDiv.css({po [...]
+d.blockUI?"static":e?"fixed":"absolute",display:"none",left:c.left+"px",top:c.top+"px"});if(!b.inline){c=d.datepicker._get(b,"showAnim");var f=d.datepicker._get(b,"duration"),h=function(){d.datepicker._datepickerShowing=true;var i=d.datepicker._getBorders(b.dpDiv);b.dpDiv.find("iframe.ui-datepicker-cover").css({left:-i[0],top:-i[1],width:b.dpDiv.outerWidth(),height:b.dpDiv.outerHeight()})};b.dpDiv.zIndex(d(a).zIndex()+1);d.effects&&d.effects[c]?b.dpDiv.show(c,d.datepicker._get(b,"showOpt [...]
+h):b.dpDiv[c||"show"](c?f:null,h);if(!c||!f)h();b.input.is(":visible")&&!b.input.is(":disabled")&&b.input.focus();d.datepicker._curInst=b}}},_updateDatepicker:function(a){var b=this,c=d.datepicker._getBorders(a.dpDiv);a.dpDiv.empty().append(this._generateHTML(a)).find("iframe.ui-datepicker-cover").css({left:-c[0],top:-c[1],width:a.dpDiv.outerWidth(),height:a.dpDiv.outerHeight()}).end().find("button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a").bind("mouseout", [...]
+this.className.indexOf("ui-datepicker-prev")!=-1&&d(this).removeClass("ui-datepicker-prev-hover");this.className.indexOf("ui-datepicker-next")!=-1&&d(this).removeClass("ui-datepicker-next-hover")}).bind("mouseover",function(){if(!b._isDisabledDatepicker(a.inline?a.dpDiv.parent()[0]:a.input[0])){d(this).parents(".ui-datepicker-calendar").find("a").removeClass("ui-state-hover");d(this).addClass("ui-state-hover");this.className.indexOf("ui-datepicker-prev")!=-1&&d(this).addClass("ui-datepic [...]
+this.className.indexOf("ui-datepicker-next")!=-1&&d(this).addClass("ui-datepicker-next-hover")}}).end().find("."+this._dayOverClass+" a").trigger("mouseover").end();c=this._getNumberOfMonths(a);var e=c[1];e>1?a.dpDiv.addClass("ui-datepicker-multi-"+e).css("width",17*e+"em"):a.dpDiv.removeClass("ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4").width("");a.dpDiv[(c[0]!=1||c[1]!=1?"add":"remove")+"Class"]("ui-datepicker-multi");a.dpDiv[(this._get(a,"isRTL")?"add":"remove" [...]
+a==d.datepicker._curInst&&d.datepicker._datepickerShowing&&a.input&&a.input.is(":visible")&&!a.input.is(":disabled")&&a.input.focus()},_getBorders:function(a){var b=function(c){return{thin:1,medium:2,thick:3}[c]||c};return[parseFloat(b(a.css("border-left-width"))),parseFloat(b(a.css("border-top-width")))]},_checkOffset:function(a,b,c){var e=a.dpDiv.outerWidth(),f=a.dpDiv.outerHeight(),h=a.input?a.input.outerWidth():0,i=a.input?a.input.outerHeight():0,g=document.documentElement.clientWidt [...]
+k=document.documentElement.clientHeight+d(document).scrollTop();b.left-=this._get(a,"isRTL")?e-h:0;b.left-=c&&b.left==a.input.offset().left?d(document).scrollLeft():0;b.top-=c&&b.top==a.input.offset().top+i?d(document).scrollTop():0;b.left-=Math.min(b.left,b.left+e>g&&g>e?Math.abs(b.left+e-g):0);b.top-=Math.min(b.top,b.top+f>k&&k>f?Math.abs(f+i):0);return b},_findPos:function(a){for(var b=this._get(this._getInst(a),"isRTL");a&&(a.type=="hidden"||a.nodeType!=1);)a=a[b?"previousSibling":"n [...]
+a=d(a).offset();return[a.left,a.top]},_hideDatepicker:function(a){var b=this._curInst;if(!(!b||a&&b!=d.data(a,"datepicker")))if(this._datepickerShowing){a=this._get(b,"showAnim");var c=this._get(b,"duration"),e=function(){d.datepicker._tidyDialog(b);this._curInst=null};d.effects&&d.effects[a]?b.dpDiv.hide(a,d.datepicker._get(b,"showOptions"),c,e):b.dpDiv[a=="slideDown"?"slideUp":a=="fadeIn"?"fadeOut":"hide"](a?c:null,e);a||e();if(a=this._get(b,"onClose"))a.apply(b.input?b.input[0]:null,[ [...]
+"",b]);this._datepickerShowing=false;this._lastInput=null;if(this._inDialog){this._dialogInput.css({position:"absolute",left:"0",top:"-100px"});if(d.blockUI){d.unblockUI();d("body").append(this.dpDiv)}}this._inDialog=false}},_tidyDialog:function(a){a.dpDiv.removeClass(this._dialogClass).unbind(".ui-datepicker-calendar")},_checkExternalClick:function(a){if(d.datepicker._curInst){a=d(a.target);a[0].id!=d.datepicker._mainDivId&&a.parents("#"+d.datepicker._mainDivId).length==0&&!a.hasClass(d [...]
+!a.hasClass(d.datepicker._triggerClass)&&d.datepicker._datepickerShowing&&!(d.datepicker._inDialog&&d.blockUI)&&d.datepicker._hideDatepicker()}},_adjustDate:function(a,b,c){a=d(a);var e=this._getInst(a[0]);if(!this._isDisabledDatepicker(a[0])){this._adjustInstDate(e,b+(c=="M"?this._get(e,"showCurrentAtPos"):0),c);this._updateDatepicker(e)}},_gotoToday:function(a){a=d(a);var b=this._getInst(a[0]);if(this._get(b,"gotoCurrent")&&b.currentDay){b.selectedDay=b.currentDay;b.drawMonth=b.selecte [...]
+b.drawYear=b.selectedYear=b.currentYear}else{var c=new Date;b.selectedDay=c.getDate();b.drawMonth=b.selectedMonth=c.getMonth();b.drawYear=b.selectedYear=c.getFullYear()}this._notifyChange(b);this._adjustDate(a)},_selectMonthYear:function(a,b,c){a=d(a);var e=this._getInst(a[0]);e._selectingMonthYear=false;e["selected"+(c=="M"?"Month":"Year")]=e["draw"+(c=="M"?"Month":"Year")]=parseInt(b.options[b.selectedIndex].value,10);this._notifyChange(e);this._adjustDate(a)},_clickMonthYear:function( [...]
+a.input&&a._selectingMonthYear&&!d.browser.msie&&a.input.focus();a._selectingMonthYear=!a._selectingMonthYear},_selectDay:function(a,b,c,e){var f=d(a);if(!(d(e).hasClass(this._unselectableClass)||this._isDisabledDatepicker(f[0]))){f=this._getInst(f[0]);f.selectedDay=f.currentDay=d("a",e).html();f.selectedMonth=f.currentMonth=b;f.selectedYear=f.currentYear=c;this._selectDate(a,this._formatDate(f,f.currentDay,f.currentMonth,f.currentYear))}},_clearDate:function(a){a=d(a);this._getInst(a[0] [...]
+"")},_selectDate:function(a,b){a=this._getInst(d(a)[0]);b=b!=null?b:this._formatDate(a);a.input&&a.input.val(b);this._updateAlternate(a);var c=this._get(a,"onSelect");if(c)c.apply(a.input?a.input[0]:null,[b,a]);else a.input&&a.input.trigger("change");if(a.inline)this._updateDatepicker(a);else{this._hideDatepicker();this._lastInput=a.input[0];typeof a.input[0]!="object"&&a.input.focus();this._lastInput=null}},_updateAlternate:function(a){var b=this._get(a,"altField");if(b){var c=this._get [...]
+this._get(a,"dateFormat"),e=this._getDate(a),f=this.formatDate(c,e,this._getFormatConfig(a));d(b).each(function(){d(this).val(f)})}},noWeekends:function(a){a=a.getDay();return[a>0&&a<6,""]},iso8601Week:function(a){a=new Date(a.getTime());a.setDate(a.getDate()+4-(a.getDay()||7));var b=a.getTime();a.setMonth(0);a.setDate(1);return Math.floor(Math.round((b-a)/864E5)/7)+1},parseDate:function(a,b,c){if(a==null||b==null)throw"Invalid arguments";b=typeof b=="object"?b.toString():b+"";if(b=="")r [...]
+for(var e=(c?c.shortYearCutoff:null)||this._defaults.shortYearCutoff,f=(c?c.dayNamesShort:null)||this._defaults.dayNamesShort,h=(c?c.dayNames:null)||this._defaults.dayNames,i=(c?c.monthNamesShort:null)||this._defaults.monthNamesShort,g=(c?c.monthNames:null)||this._defaults.monthNames,k=c=-1,l=-1,u=-1,j=false,o=function(p){(p=z+1<a.length&&a.charAt(z+1)==p)&&z++;return p},m=function(p){o(p);p=new RegExp("^\\d{1,"+(p=="@"?14:p=="!"?20:p=="y"?4:p=="o"?3:2)+"}");p=b.substring(s).match(p);if( [...]
+s;s+=p[0].length;return parseInt(p[0],10)},n=function(p,w,G){p=o(p)?G:w;for(w=0;w<p.length;w++)if(b.substr(s,p[w].length)==p[w]){s+=p[w].length;return w+1}throw"Unknown name at position "+s;},r=function(){if(b.charAt(s)!=a.charAt(z))throw"Unexpected literal at position "+s;s++},s=0,z=0;z<a.length;z++)if(j)if(a.charAt(z)=="'"&&!o("'"))j=false;else r();else switch(a.charAt(z)){case "d":l=m("d");break;case "D":n("D",f,h);break;case "o":u=m("o");break;case "m":k=m("m");break;case "M":k=n("M" [...]
+case "y":c=m("y");break;case "@":var v=new Date(m("@"));c=v.getFullYear();k=v.getMonth()+1;l=v.getDate();break;case "!":v=new Date((m("!")-this._ticksTo1970)/1E4);c=v.getFullYear();k=v.getMonth()+1;l=v.getDate();break;case "'":if(o("'"))r();else j=true;break;default:r()}if(c==-1)c=(new Date).getFullYear();else if(c<100)c+=(new Date).getFullYear()-(new Date).getFullYear()%100+(c<=e?0:-100);if(u>-1){k=1;l=u;do{e=this._getDaysInMonth(c,k-1);if(l<=e)break;k++;l-=e}while(1)}v=this._daylightSa [...]
+k-1,l));if(v.getFullYear()!=c||v.getMonth()+1!=k||v.getDate()!=l)throw"Invalid date";return v},ATOM:"yy-mm-dd",COOKIE:"D, dd M yy",ISO_8601:"yy-mm-dd",RFC_822:"D, d M y",RFC_850:"DD, dd-M-y",RFC_1036:"D, d M y",RFC_1123:"D, d M yy",RFC_2822:"D, d M yy",RSS:"D, d M y",TICKS:"!",TIMESTAMP:"@",W3C:"yy-mm-dd",_ticksTo1970:(718685+Math.floor(492.5)-Math.floor(19.7)+Math.floor(4.925))*24*60*60*1E7,formatDate:function(a,b,c){if(!b)return"";var e=(c?c.dayNamesShort:null)||this._defaults.dayNames [...]
+c.dayNames:null)||this._defaults.dayNames,h=(c?c.monthNamesShort:null)||this._defaults.monthNamesShort;c=(c?c.monthNames:null)||this._defaults.monthNames;var i=function(o){(o=j+1<a.length&&a.charAt(j+1)==o)&&j++;return o},g=function(o,m,n){m=""+m;if(i(o))for(;m.length<n;)m="0"+m;return m},k=function(o,m,n,r){return i(o)?r[m]:n[m]},l="",u=false;if(b)for(var j=0;j<a.length;j++)if(u)if(a.charAt(j)=="'"&&!i("'"))u=false;else l+=a.charAt(j);else switch(a.charAt(j)){case "d":l+=g("d",b.getDate [...]
+case "D":l+=k("D",b.getDay(),e,f);break;case "o":l+=g("o",(b.getTime()-(new Date(b.getFullYear(),0,0)).getTime())/864E5,3);break;case "m":l+=g("m",b.getMonth()+1,2);break;case "M":l+=k("M",b.getMonth(),h,c);break;case "y":l+=i("y")?b.getFullYear():(b.getYear()%100<10?"0":"")+b.getYear()%100;break;case "@":l+=b.getTime();break;case "!":l+=b.getTime()*1E4+this._ticksTo1970;break;case "'":if(i("'"))l+="'";else u=true;break;default:l+=a.charAt(j)}return l},_possibleChars:function(a){for(var  [...]
+e=function(h){(h=f+1<a.length&&a.charAt(f+1)==h)&&f++;return h},f=0;f<a.length;f++)if(c)if(a.charAt(f)=="'"&&!e("'"))c=false;else b+=a.charAt(f);else switch(a.charAt(f)){case "d":case "m":case "y":case "@":b+="0123456789";break;case "D":case "M":return null;case "'":if(e("'"))b+="'";else c=true;break;default:b+=a.charAt(f)}return b},_get:function(a,b){return a.settings[b]!==undefined?a.settings[b]:this._defaults[b]},_setDateFromField:function(a,b){if(a.input.val()!=a.lastVal){var c=this. [...]
+e=a.lastVal=a.input?a.input.val():null,f,h;f=h=this._getDefaultDate(a);var i=this._getFormatConfig(a);try{f=this.parseDate(c,e,i)||h}catch(g){this.log(g);e=b?"":e}a.selectedDay=f.getDate();a.drawMonth=a.selectedMonth=f.getMonth();a.drawYear=a.selectedYear=f.getFullYear();a.currentDay=e?f.getDate():0;a.currentMonth=e?f.getMonth():0;a.currentYear=e?f.getFullYear():0;this._adjustInstDate(a)}},_getDefaultDate:function(a){return this._restrictMinMax(a,this._determineDate(a,this._get(a,"defaul [...]
+_determineDate:function(a,b,c){var e=function(h){var i=new Date;i.setDate(i.getDate()+h);return i},f=function(h){try{return d.datepicker.parseDate(d.datepicker._get(a,"dateFormat"),h,d.datepicker._getFormatConfig(a))}catch(i){}var g=(h.toLowerCase().match(/^c/)?d.datepicker._getDate(a):null)||new Date,k=g.getFullYear(),l=g.getMonth();g=g.getDate();for(var u=/([+-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g,j=u.exec(h);j;){switch(j[2]||"d"){case "d":case "D":g+=parseInt(j[1],10);break;case "w":case " [...]
+10)*7;break;case "m":case "M":l+=parseInt(j[1],10);g=Math.min(g,d.datepicker._getDaysInMonth(k,l));break;case "y":case "Y":k+=parseInt(j[1],10);g=Math.min(g,d.datepicker._getDaysInMonth(k,l));break}j=u.exec(h)}return new Date(k,l,g)};if(b=(b=b==null?c:typeof b=="string"?f(b):typeof b=="number"?isNaN(b)?c:e(b):b)&&b.toString()=="Invalid Date"?c:b){b.setHours(0);b.setMinutes(0);b.setSeconds(0);b.setMilliseconds(0)}return this._daylightSavingAdjust(b)},_daylightSavingAdjust:function(a){if(! [...]
+a.setHours(a.getHours()>12?a.getHours()+2:0);return a},_setDate:function(a,b,c){var e=!b,f=a.selectedMonth,h=a.selectedYear;b=this._restrictMinMax(a,this._determineDate(a,b,new Date));a.selectedDay=a.currentDay=b.getDate();a.drawMonth=a.selectedMonth=a.currentMonth=b.getMonth();a.drawYear=a.selectedYear=a.currentYear=b.getFullYear();if((f!=a.selectedMonth||h!=a.selectedYear)&&!c)this._notifyChange(a);this._adjustInstDate(a);if(a.input)a.input.val(e?"":this._formatDate(a))},_getDate:funct [...]
+a.input&&a.input.val()==""?null:this._daylightSavingAdjust(new Date(a.currentYear,a.currentMonth,a.currentDay))},_generateHTML:function(a){var b=new Date;b=this._daylightSavingAdjust(new Date(b.getFullYear(),b.getMonth(),b.getDate()));var c=this._get(a,"isRTL"),e=this._get(a,"showButtonPanel"),f=this._get(a,"hideIfNoPrevNext"),h=this._get(a,"navigationAsDateFormat"),i=this._getNumberOfMonths(a),g=this._get(a,"showCurrentAtPos"),k=this._get(a,"stepMonths"),l=i[0]!=1||i[1]!=1,u=this._dayli [...]
+new Date(9999,9,9):new Date(a.currentYear,a.currentMonth,a.currentDay)),j=this._getMinMaxDate(a,"min"),o=this._getMinMaxDate(a,"max");g=a.drawMonth-g;var m=a.drawYear;if(g<0){g+=12;m--}if(o){var n=this._daylightSavingAdjust(new Date(o.getFullYear(),o.getMonth()-i[0]*i[1]+1,o.getDate()));for(n=j&&n<j?j:n;this._daylightSavingAdjust(new Date(m,g,1))>n;){g--;if(g<0){g=11;m--}}}a.drawMonth=g;a.drawYear=m;n=this._get(a,"prevText");n=!h?n:this.formatDate(n,this._daylightSavingAdjust(new Date(m, [...]
+n=this._canAdjustMonth(a,-1,m,g)?'<a class="ui-datepicker-prev ui-corner-all" onclick="DP_jQuery_'+y+".datepicker._adjustDate('#"+a.id+"', -"+k+", 'M');\" title=\""+n+'"><span class="ui-icon ui-icon-circle-triangle-'+(c?"e":"w")+'">'+n+"</span></a>":f?"":'<a class="ui-datepicker-prev ui-corner-all ui-state-disabled" title="'+n+'"><span class="ui-icon ui-icon-circle-triangle-'+(c?"e":"w")+'">'+n+"</span></a>";var r=this._get(a,"nextText");r=!h?r:this.formatDate(r,this._daylightSavingAdjus [...]
+g+k,1)),this._getFormatConfig(a));f=this._canAdjustMonth(a,+1,m,g)?'<a class="ui-datepicker-next ui-corner-all" onclick="DP_jQuery_'+y+".datepicker._adjustDate('#"+a.id+"', +"+k+", 'M');\" title=\""+r+'"><span class="ui-icon ui-icon-circle-triangle-'+(c?"w":"e")+'">'+r+"</span></a>":f?"":'<a class="ui-datepicker-next ui-corner-all ui-state-disabled" title="'+r+'"><span class="ui-icon ui-icon-circle-triangle-'+(c?"w":"e")+'">'+r+"</span></a>";k=this._get(a,"currentText");r=this._get(a,"go [...]
+a.currentDay?u:b;k=!h?k:this.formatDate(k,r,this._getFormatConfig(a));h=!a.inline?'<button type="button" class="ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all" onclick="DP_jQuery_'+y+'.datepicker._hideDatepicker();">'+this._get(a,"closeText")+"</button>":"";e=e?'<div class="ui-datepicker-buttonpane ui-widget-content">'+(c?h:"")+(this._isInRange(a,r)?'<button type="button" class="ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all" onclick="D [...]
+y+".datepicker._gotoToday('#"+a.id+"');\">"+k+"</button>":"")+(c?"":h)+"</div>":"";h=parseInt(this._get(a,"firstDay"),10);h=isNaN(h)?0:h;k=this._get(a,"showWeek");r=this._get(a,"dayNames");this._get(a,"dayNamesShort");var s=this._get(a,"dayNamesMin"),z=this._get(a,"monthNames"),v=this._get(a,"monthNamesShort"),p=this._get(a,"beforeShowDay"),w=this._get(a,"showOtherMonths"),G=this._get(a,"selectOtherMonths");this._get(a,"calculateWeek");for(var L=this._getDefaultDate(a),H="",C=0;C<i[0];C+ [...]
+"",D=0;D<i[1];D++){var I=this._daylightSavingAdjust(new Date(m,g,a.selectedDay)),t=" ui-corner-all",x="";if(l){x+='<div class="ui-datepicker-group';if(i[1]>1)switch(D){case 0:x+=" ui-datepicker-group-first";t=" ui-corner-"+(c?"right":"left");break;case i[1]-1:x+=" ui-datepicker-group-last";t=" ui-corner-"+(c?"left":"right");break;default:x+=" ui-datepicker-group-middle";t="";break}x+='">'}x+='<div class="ui-datepicker-header ui-widget-header ui-helper-clearfix'+t+'">'+(/all|left/.test(t) [...]
+f:n:"")+(/all|right/.test(t)&&C==0?c?n:f:"")+this._generateMonthYearHeader(a,g,m,j,o,C>0||D>0,z,v)+'</div><table class="ui-datepicker-calendar"><thead><tr>';var A=k?'<th class="ui-datepicker-week-col">'+this._get(a,"weekHeader")+"</th>":"";for(t=0;t<7;t++){var q=(t+h)%7;A+="<th"+((t+h+6)%7>=5?' class="ui-datepicker-week-end"':"")+'><span title="'+r[q]+'">'+s[q]+"</span></th>"}x+=A+"</tr></thead><tbody>";A=this._getDaysInMonth(m,g);if(m==a.selectedYear&&g==a.selectedMonth)a.selectedDay=Ma [...]
+A);t=(this._getFirstDayOfMonth(m,g)-h+7)%7;A=l?6:Math.ceil((t+A)/7);q=this._daylightSavingAdjust(new Date(m,g,1-t));for(var N=0;N<A;N++){x+="<tr>";var O=!k?"":'<td class="ui-datepicker-week-col">'+this._get(a,"calculateWeek")(q)+"</td>";for(t=0;t<7;t++){var F=p?p.apply(a.input?a.input[0]:null,[q]):[true,""],B=q.getMonth()!=g,J=B&&!G||!F[0]||j&&q<j||o&&q>o;O+='<td class="'+((t+h+6)%7>=5?" ui-datepicker-week-end":"")+(B?" ui-datepicker-other-month":"")+(q.getTime()==I.getTime()&&g==a.selec [...]
+a._keyEvent||L.getTime()==q.getTime()&&L.getTime()==I.getTime()?" "+this._dayOverClass:"")+(J?" "+this._unselectableClass+" ui-state-disabled":"")+(B&&!w?"":" "+F[1]+(q.getTime()==u.getTime()?" "+this._currentClass:"")+(q.getTime()==b.getTime()?" ui-datepicker-today":""))+'"'+((!B||w)&&F[2]?' title="'+F[2]+'"':"")+(J?"":' onclick="DP_jQuery_'+y+".datepicker._selectDay('#"+a.id+"',"+q.getMonth()+","+q.getFullYear()+', this);return false;"')+">"+(B&&!w?"&#xa0;":J?'<span class="ui-state-def [...]
+"</span>":'<a class="ui-state-default'+(q.getTime()==b.getTime()?" ui-state-highlight":"")+(q.getTime()==I.getTime()?" ui-state-active":"")+(B?" ui-priority-secondary":"")+'" href="#">'+q.getDate()+"</a>")+"</td>";q.setDate(q.getDate()+1);q=this._daylightSavingAdjust(q)}x+=O+"</tr>"}g++;if(g>11){g=0;m++}x+="</tbody></table>"+(l?"</div>"+(i[0]>0&&D==i[1]-1?'<div class="ui-datepicker-row-break"></div>':""):"");M+=x}H+=M}H+=e+(d.browser.msie&&parseInt(d.browser.version,10)<7&&!a.inline?'<if [...]
+"");a._keyEvent=false;return H},_generateMonthYearHeader:function(a,b,c,e,f,h,i,g){var k=this._get(a,"changeMonth"),l=this._get(a,"changeYear"),u=this._get(a,"showMonthAfterYear"),j='<div class="ui-datepicker-title">',o="";if(h||!k)o+='<span class="ui-datepicker-month">'+i[b]+"</span>";else{i=e&&e.getFullYear()==c;var m=f&&f.getFullYear()==c;o+='<select class="ui-datepicker-month" onchange="DP_jQuery_'+y+".datepicker._selectMonthYear('#"+a.id+"', this, 'M');\" onclick=\"DP_jQuery_"+y+".d [...]
+a.id+"');\">";for(var n=0;n<12;n++)if((!i||n>=e.getMonth())&&(!m||n<=f.getMonth()))o+='<option value="'+n+'"'+(n==b?' selected="selected"':"")+">"+g[n]+"</option>";o+="</select>"}u||(j+=o+(h||!(k&&l)?"&#xa0;":""));if(h||!l)j+='<span class="ui-datepicker-year">'+c+"</span>";else{g=this._get(a,"yearRange").split(":");var r=(new Date).getFullYear();i=function(s){s=s.match(/c[+-].*/)?c+parseInt(s.substring(1),10):s.match(/[+-].*/)?r+parseInt(s,10):parseInt(s,10);return isNaN(s)?r:s};b=i(g[0] [...]
+i(g[1]||""));b=e?Math.max(b,e.getFullYear()):b;g=f?Math.min(g,f.getFullYear()):g;for(j+='<select class="ui-datepicker-year" onchange="DP_jQuery_'+y+".datepicker._selectMonthYear('#"+a.id+"', this, 'Y');\" onclick=\"DP_jQuery_"+y+".datepicker._clickMonthYear('#"+a.id+"');\">";b<=g;b++)j+='<option value="'+b+'"'+(b==c?' selected="selected"':"")+">"+b+"</option>";j+="</select>"}j+=this._get(a,"yearSuffix");if(u)j+=(h||!(k&&l)?"&#xa0;":"")+o;j+="</div>";return j},_adjustInstDate:function(a,b [...]
+a.drawYear+(c=="Y"?b:0),f=a.drawMonth+(c=="M"?b:0);b=Math.min(a.selectedDay,this._getDaysInMonth(e,f))+(c=="D"?b:0);e=this._restrictMinMax(a,this._daylightSavingAdjust(new Date(e,f,b)));a.selectedDay=e.getDate();a.drawMonth=a.selectedMonth=e.getMonth();a.drawYear=a.selectedYear=e.getFullYear();if(c=="M"||c=="Y")this._notifyChange(a)},_restrictMinMax:function(a,b){var c=this._getMinMaxDate(a,"min");a=this._getMinMaxDate(a,"max");b=c&&b<c?c:b;return b=a&&b>a?a:b},_notifyChange:function(a){ [...]
+"onChangeMonthYear");if(b)b.apply(a.input?a.input[0]:null,[a.selectedYear,a.selectedMonth+1,a])},_getNumberOfMonths:function(a){a=this._get(a,"numberOfMonths");return a==null?[1,1]:typeof a=="number"?[1,a]:a},_getMinMaxDate:function(a,b){return this._determineDate(a,this._get(a,b+"Date"),null)},_getDaysInMonth:function(a,b){return 32-(new Date(a,b,32)).getDate()},_getFirstDayOfMonth:function(a,b){return(new Date(a,b,1)).getDay()},_canAdjustMonth:function(a,b,c,e){var f=this._getNumberOfM [...]
+c=this._daylightSavingAdjust(new Date(c,e+(b<0?b:f[0]*f[1]),1));b<0&&c.setDate(this._getDaysInMonth(c.getFullYear(),c.getMonth()));return this._isInRange(a,c)},_isInRange:function(a,b){var c=this._getMinMaxDate(a,"min");a=this._getMinMaxDate(a,"max");return(!c||b.getTime()>=c.getTime())&&(!a||b.getTime()<=a.getTime())},_getFormatConfig:function(a){var b=this._get(a,"shortYearCutoff");b=typeof b!="string"?b:(new Date).getFullYear()%100+parseInt(b,10);return{shortYearCutoff:b,dayNamesShort [...]
+"dayNamesShort"),dayNames:this._get(a,"dayNames"),monthNamesShort:this._get(a,"monthNamesShort"),monthNames:this._get(a,"monthNames")}},_formatDate:function(a,b,c,e){if(!b){a.currentDay=a.selectedDay;a.currentMonth=a.selectedMonth;a.currentYear=a.selectedYear}b=b?typeof b=="object"?b:this._daylightSavingAdjust(new Date(e,c,b)):this._daylightSavingAdjust(new Date(a.currentYear,a.currentMonth,a.currentDay));return this.formatDate(this._get(a,"dateFormat"),b,this._getFormatConfig(a))}});d.f [...]
+function(a){if(!d.datepicker.initialized){d(document).mousedown(d.datepicker._checkExternalClick).find("body").append(d.datepicker.dpDiv);d.datepicker.initialized=true}var b=Array.prototype.slice.call(arguments,1);if(typeof a=="string"&&(a=="isDisabled"||a=="getDate"||a=="widget"))return d.datepicker["_"+a+"Datepicker"].apply(d.datepicker,[this[0]].concat(b));if(a=="option"&&arguments.length==2&&typeof arguments[1]=="string")return d.datepicker["_"+a+"Datepicker"].apply(d.datepicker,[thi [...]
+return this.each(function(){typeof a=="string"?d.datepicker["_"+a+"Datepicker"].apply(d.datepicker,[this].concat(b)):d.datepicker._attachDatepicker(this,a)})};d.datepicker=new K;d.datepicker.initialized=false;d.datepicker.uuid=(new Date).getTime();d.datepicker.version="1.9m2";window["DP_jQuery_"+y]=d})(jQuery);
+(function(c){c.widget("ui.dialog",{options:{autoOpen:true,buttons:{},closeOnEscape:true,closeText:"close",dialogClass:"",draggable:true,hide:null,height:"auto",maxHeight:false,maxWidth:false,minHeight:150,minWidth:150,modal:false,position:"center",resizable:true,show:null,stack:true,title:"",width:300,zIndex:1E3},_create:function(){this.originalTitle=this.element.attr("title");var a=this,b=a.options,d=b.title||a.originalTitle||" ",e=c.ui.dialog.getTitleId(a.element),g=(a.uiDialog=c( [...]
+b.dialogClass).css({zIndex:b.zIndex}).attr("tabIndex",-1).css("outline",0).keydown(function(i){if(b.closeOnEscape&&i.keyCode&&i.keyCode===c.ui.keyCode.ESCAPE){a.close(i);i.preventDefault()}}).attr({role:"dialog","aria-labelledby":e}).mousedown(function(i){a.moveToTop(false,i)});a.element.show().removeAttr("title").addClass("ui-dialog-content ui-widget-content").appendTo(g);var f=(a.uiDialogTitlebar=c("<div></div>")).addClass("ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-cl [...]
+h=c('<a href="#"></a>').addClass("ui-dialog-titlebar-close ui-corner-all").attr("role","button").hover(function(){h.addClass("ui-state-hover")},function(){h.removeClass("ui-state-hover")}).focus(function(){h.addClass("ui-state-focus")}).blur(function(){h.removeClass("ui-state-focus")}).click(function(i){a.close(i);return false}).appendTo(f);(a.uiDialogTitlebarCloseText=c("<span></span>")).addClass("ui-icon ui-icon-closethick").text(b.closeText).appendTo(h);c("<span></span>").addClass("ui [...]
+e).html(d).prependTo(f);if(c.isFunction(b.beforeclose)&&!c.isFunction(b.beforeClose))b.beforeClose=b.beforeclose;f.find("*").add(f).disableSelection();b.draggable&&c.fn.draggable&&a._makeDraggable();b.resizable&&c.fn.resizable&&a._makeResizable();a._createButtons(b.buttons);a._isOpen=false;c.fn.bgiframe&&g.bgiframe()},_init:function(){this.options.autoOpen&&this.open()},destroy:function(){var a=this;a.overlay&&a.overlay.destroy();a.uiDialog.hide();a.element.unbind(".dialog").removeData(" [...]
+a.uiDialog.remove();a.originalTitle&&a.element.attr("title",a.originalTitle);return a},widget:function(){return this.uiDialog},close:function(a){var b=this,d;if(false!==b._trigger("beforeClose",a)){b.overlay&&b.overlay.destroy();b.uiDialog.unbind("keypress.ui-dialog");b._isOpen=false;if(b.options.hide)b.uiDialog.hide(b.options.hide,function(){b._trigger("close",a)});else{b.uiDialog.hide();b._trigger("close",a)}c.ui.dialog.overlay.resize();if(b.options.modal){d=0;c(".ui-dialog").each(func [...]
+b.uiDialog[0])d=Math.max(d,c(this).css("z-index"))});c.ui.dialog.maxZ=d}return b}},isOpen:function(){return this._isOpen},moveToTop:function(a,b){var d=this,e=d.options;if(e.modal&&!a||!e.stack&&!e.modal)return d._trigger("focus",b);if(e.zIndex>c.ui.dialog.maxZ)c.ui.dialog.maxZ=e.zIndex;if(d.overlay){c.ui.dialog.maxZ+=1;d.overlay.$el.css("z-index",c.ui.dialog.overlay.maxZ=c.ui.dialog.maxZ)}a={scrollTop:d.element.attr("scrollTop"),scrollLeft:d.element.attr("scrollLeft")};c.ui.dialog.maxZ+ [...]
+c.ui.dialog.maxZ);d.element.attr(a);d._trigger("focus",b);return d},open:function(){if(!this._isOpen){var a=this,b=a.options,d=a.uiDialog;a.overlay=b.modal?new c.ui.dialog.overlay(a):null;d.next().length&&d.appendTo("body");a._size();a._position(b.position);d.show(b.show);a.moveToTop(true);b.modal&&d.bind("keypress.ui-dialog",function(e){if(e.keyCode===c.ui.keyCode.TAB){var g=c(":tabbable",this),f=g.filter(":first");g=g.filter(":last");if(e.target===g[0]&&!e.shiftKey){f.focus(1);return f [...]
+f[0]&&e.shiftKey){g.focus(1);return false}}});c([]).add(d.find(".ui-dialog-content :tabbable:first")).add(d.find(".ui-dialog-buttonpane :tabbable:first")).add(d).filter(":first").focus();a._trigger("open");a._isOpen=true;return a}},_createButtons:function(a){var b=this,d=false,e=c("<div></div>").addClass("ui-dialog-buttonpane ui-widget-content ui-helper-clearfix");b.uiDialog.find(".ui-dialog-buttonpane").remove();typeof a==="object"&&a!==null&&c.each(a,function(){return!(d=true)});if(d){ [...]
+function(g,f){g=c('<button type="button"></button>').text(g).click(function(){f.apply(b.element[0],arguments)}).appendTo(e);c.fn.button&&g.button()});e.appendTo(b.uiDialog)}},_makeDraggable:function(){function a(f){return{position:f.position,offset:f.offset}}var b=this,d=b.options,e=c(document),g;b.uiDialog.draggable({cancel:".ui-dialog-content, .ui-dialog-titlebar-close",handle:".ui-dialog-titlebar",containment:"document",start:function(f,h){g=d.height==="auto"?"auto":c(this).height();c [...]
+b._trigger("dragStart",f,a(h))},drag:function(f,h){b._trigger("drag",f,a(h))},stop:function(f,h){d.position=[h.position.left-e.scrollLeft(),h.position.top-e.scrollTop()];c(this).removeClass("ui-dialog-dragging").height(g);b._trigger("dragStop",f,a(h));c.ui.dialog.overlay.resize()}})},_makeResizable:function(a){function b(f){return{originalPosition:f.originalPosition,originalSize:f.originalSize,position:f.position,size:f.size}}a=a===undefined?this.options.resizable:a;var d=this,e=d.option [...]
+a=typeof a==="string"?a:"n,e,s,w,se,sw,ne,nw";d.uiDialog.resizable({cancel:".ui-dialog-content",containment:"document",alsoResize:d.element,maxWidth:e.maxWidth,maxHeight:e.maxHeight,minWidth:e.minWidth,minHeight:d._minHeight(),handles:a,start:function(f,h){c(this).addClass("ui-dialog-resizing");d._trigger("resizeStart",f,b(h))},resize:function(f,h){d._trigger("resize",f,b(h))},stop:function(f,h){c(this).removeClass("ui-dialog-resizing");e.height=c(this).height();e.width=c(this).width();d [...]
+f,b(h));c.ui.dialog.overlay.resize()}}).css("position",g).find(".ui-resizable-se").addClass("ui-icon ui-icon-grip-diagonal-se")},_minHeight:function(){var a=this.options;return a.height==="auto"?a.minHeight:Math.min(a.minHeight,a.height)},_position:function(a){var b=[],d=[0,0];a=a||c.ui.dialog.prototype.options.position;if(typeof a==="string"||typeof a==="object"&&"0"in a){b=a.split?a.split(" "):[a[0],a[1]];if(b.length===1)b[1]=b[0];c.each(["left","top"],function(e,g){if(+b[e]===b[e]){d[ [...]
+g}})}else if(typeof a==="object"){if("left"in a){b[0]="left";d[0]=a.left}else if("right"in a){b[0]="right";d[0]=-a.right}if("top"in a){b[1]="top";d[1]=a.top}else if("bottom"in a){b[1]="bottom";d[1]=-a.bottom}}(a=this.uiDialog.is(":visible"))||this.uiDialog.show();this.uiDialog.css({top:0,left:0}).position({my:b.join(" "),at:b.join(" "),offset:d.join(" "),of:window,collision:"fit",using:function(e){var g=c(this).css(e).offset().top;g<0&&c(this).css("top",e.top-g)}});a||this.uiDialog.hide( [...]
+b){var d=this,e=d.uiDialog,g=e.is(":data(resizable)"),f=false;switch(a){case "beforeclose":a="beforeClose";break;case "buttons":d._createButtons(b);break;case "closeText":d.uiDialogTitlebarCloseText.text(""+b);break;case "dialogClass":e.removeClass(d.options.dialogClass).addClass("ui-dialog ui-widget ui-widget-content ui-corner-all "+b);break;case "disabled":b?e.addClass("ui-dialog-disabled"):e.removeClass("ui-dialog-disabled");break;case "draggable":b?d._makeDraggable():e.draggable("des [...]
+case "height":f=true;break;case "maxHeight":g&&e.resizable("option","maxHeight",b);f=true;break;case "maxWidth":g&&e.resizable("option","maxWidth",b);f=true;break;case "minHeight":g&&e.resizable("option","minHeight",b);f=true;break;case "minWidth":g&&e.resizable("option","minWidth",b);f=true;break;case "position":d._position(b);break;case "resizable":g&&!b&&e.resizable("destroy");g&&typeof b==="string"&&e.resizable("option","handles",b);!g&&b!==false&&d._makeResizable(b);break;case "titl [...]
+d.uiDialogTitlebar).html(""+(b||" "));break;case "width":f=true;break}c.Widget.prototype._setOption.apply(d,arguments);f&&d._size()},_size:function(){var a=this.options,b;this.element.css({width:"auto",minHeight:0,height:0});b=this.uiDialog.css({height:"auto",width:a.width}).height();this.element.css(a.height==="auto"?{minHeight:Math.max(a.minHeight-b,0),height:"auto"}:{minHeight:0,height:Math.max(a.height-b,0)}).show();this.uiDialog.is(":data(resizable)")&&this.uiDialog.resizable(" [...]
+this._minHeight())}});c.extend(c.ui.dialog,{version:"1.9m2",uuid:0,maxZ:0,getTitleId:function(a){a=a.attr("id");if(!a){this.uuid+=1;a=this.uuid}return"ui-dialog-title-"+a},overlay:function(a){this.$el=c.ui.dialog.overlay.create(a)}});c.extend(c.ui.dialog.overlay,{instances:[],oldInstances:[],maxZ:0,events:c.map("focus,mousedown,mouseup,keydown,keypress,click".split(","),function(a){return a+".dialog-overlay"}).join(" "),create:function(a){if(this.instances.length===0){setTimeout(function [...]
+c(document).bind(c.ui.dialog.overlay.events,function(d){return c(d.target).zIndex()>=c.ui.dialog.overlay.maxZ})},1);c(document).bind("keydown.dialog-overlay",function(d){if(a.options.closeOnEscape&&d.keyCode&&d.keyCode===c.ui.keyCode.ESCAPE){a.close(d);d.preventDefault()}});c(window).bind("resize.dialog-overlay",c.ui.dialog.overlay.resize)}var b=(this.oldInstances.pop()||c("<div></div>").addClass("ui-widget-overlay")).appendTo(document.body).css({width:this.width(),height:this.height()}) [...]
+b.bgiframe();this.instances.push(b);return b},destroy:function(a){this.oldInstances.push(this.instances.splice(c.inArray(a,this.instances),1)[0]);this.instances.length===0&&c([document,window]).unbind(".dialog-overlay");a.remove();var b=0;c.each(this.instances,function(){b=Math.max(b,this.css("z-index"))});this.maxZ=b},height:function(){var a,b;if(c.browser.msie&&c.browser.version<7){a=Math.max(document.documentElement.scrollHeight,document.body.scrollHeight);b=Math.max(document.document [...]
+document.body.offsetHeight);return a<b?c(window).height()+"px":a+"px"}else return c(document).height()+"px"},width:function(){var a,b;if(c.browser.msie&&c.browser.version<7){a=Math.max(document.documentElement.scrollWidth,document.body.scrollWidth);b=Math.max(document.documentElement.offsetWidth,document.body.offsetWidth);return a<b?c(window).width()+"px":a+"px"}else return c(document).width()+"px"},resize:function(){var a=c([]);c.each(c.ui.dialog.overlay.instances,function(){a=a.add(thi [...]
+height:0}).css({width:c.ui.dialog.overlay.width(),height:c.ui.dialog.overlay.height()})}});c.extend(c.ui.dialog.overlay.prototype,{destroy:function(){c.ui.dialog.overlay.destroy(this.$el)}})})(jQuery);
+(function(c){c.widget("ui.menu",{_create:function(){var a=this;this.element.addClass("ui-menu ui-widget ui-widget-content ui-corner-all").attr({role:"listbox","aria-activedescendant":"ui-active-menuitem"}).bind("click.menu",function(b){if(a.options.disabled)return false;if(c(b.target).closest(".ui-menu-item a").length){b.preventDefault();a.select(b)}});this.refresh();if(!this.options.input)this.options.input=this.element.attr("tabIndex",0);this.options.input.bind("keydown.menu",function( [...]
+b.preventDefault();b.stopImmediatePropagation();break;case c.ui.keyCode.PAGE_DOWN:a.nextPage();b.preventDefault();b.stopImmediatePropagation();break;case c.ui.keyCode.UP:a.previous();b.preventDefault();b.stopImmediatePropagation();break;case c.ui.keyCode.DOWN:a.next();b.preventDefault();b.stopImmediatePropagation();break;case c.ui.keyCode.ENTER:a.select();b.preventDefault();b.stopImmediatePropagation();break}})},destroy:function(){c.Widget.prototype.destroy.apply(this,arguments);this.ele [...]
+this.element.children(".ui-menu-item").removeClass("ui-menu-item").removeAttr("role").children("a").removeClass("ui-corner-all").removeAttr("tabIndex").unbind(".menu")},refresh:function(){var a=this;this.element.children("li:not(.ui-menu-item):has(a)").addClass("ui-menu-item").attr("role","menuitem").children("a").addClass("ui-corner-all").attr("tabIndex",-1).bind("mouseenter.menu",function(b){a.options.disabled||a.activate(b,c(this).parent())}).bind("mouseleave.menu",function(){a.option [...]
+a.deactivate()})},activate:function(a,b){this.deactivate();if(this._hasScroll()){var d=b.offset().top-this.element.offset().top,e=this.element.attr("scrollTop"),f=this.element.height();if(d<0)this.element.attr("scrollTop",e+d);else d>f&&this.element.attr("scrollTop",e+d-f+b.height())}this.active=b.eq(0).children("a").addClass("ui-state-hover").attr("id","ui-active-menuitem").end();this._trigger("focus",a,{item:b})},deactivate:function(){if(this.active){this.active.children("a").removeCla [...]
+this._trigger("blur");this.active=null}},next:function(a){this._move("next",".ui-menu-item:first",a)},previous:function(a){this._move("prev",".ui-menu-item:last",a)},first:function(){return this.active&&!this.active.prevAll(".ui-menu-item").length},last:function(){return this.active&&!this.active.nextAll(".ui-menu-item").length},_move:function(a,b,d){if(this.active){a=this.active[a+"All"](".ui-menu-item").eq(0);a.length?this.activate(d,a):this.activate(d,this.element.children(b))}else th [...]
+this.element.children(b))},nextPage:function(a){if(this._hasScroll())if(!this.active||this.last())this.activate(a,this.element.children(":first"));else{var b=this.active.offset().top,d=this.element.height(),e=this.element.children("li").filter(function(){var f=c(this).offset().top-b-d+c(this).height();return f<10&&f>-10});e.length||(e=this.element.children(":last"));this.activate(a,e)}else this.activate(a,this.element.children(!this.active||this.last()?":first":":last"))},previousPage:fu [...]
+this.first())this.activate(a,this.element.children(":last"));else{var b=this.active.offset().top,d=this.element.height();result=this.element.children("li").filter(function(){var e=c(this).offset().top-b+d-c(this).height();return e<10&&e>-10});result.length||(result=this.element.children(":first"));this.activate(a,result)}else this.activate(a,this.element.children(!this.active||this.first()?":last":":first"))},_hasScroll:function(){return this.element.height()<this.element.attr("scrollHei [...]
+a,{item:this.active})}})})(jQuery);
+(function(c){c.ui=c.ui||{};var m=/left|center|right/,n=/top|center|bottom/,p=c.fn.position,q=c.fn.offset;c.fn.position=function(a){if(!a||!a.of)return p.apply(this,arguments);a=c.extend({},a);var b=c(a.of),d=(a.collision||"flip").split(" "),e=a.offset?a.offset.split(" "):[0,0],g,h,i;if(a.of.nodeType===9){g=b.width();h=b.height();i={top:0,left:0}}else if(a.of.scrollTo&&a.of.document){g=b.width();h=b.height();i={top:b.scrollTop(),left:b.scrollLeft()}}else if(a.of.preventDefault){a.at="left [...]
+0;i={top:a.of.pageY,left:a.of.pageX}}else{g=b.outerWidth();h=b.outerHeight();i=b.offset()}c.each(["my","at"],function(){var f=(a[this]||"").split(" ");if(f.length===1)f=m.test(f[0])?f.concat(["center"]):n.test(f[0])?["center"].concat(f):["center","center"];f[0]=m.test(f[0])?f[0]:"center";f[1]=n.test(f[1])?f[1]:"center";a[this]=f});if(d.length===1)d[1]=d[0];e[0]=parseInt(e[0],10)||0;if(e.length===1)e[1]=e[0];e[1]=parseInt(e[1],10)||0;if(a.at[0]==="right")i.left+=g;else if(a.at[0]==="cente [...]
+g/2;if(a.at[1]==="bottom")i.top+=h;else if(a.at[1]==="center")i.top+=h/2;i.left+=e[0];i.top+=e[1];return this.each(function(){var f=c(this),k=f.outerWidth(),l=f.outerHeight(),j=c.extend({},i);if(a.my[0]==="right")j.left-=k;else if(a.my[0]==="center")j.left-=k/2;if(a.my[1]==="bottom")j.top-=l;else if(a.my[1]==="center")j.top-=l/2;j.left=parseInt(j.left);j.top=parseInt(j.top);c.each(["left","top"],function(o,r){c.ui.position[d[o]]&&c.ui.position[d[o]][r](j,{targetWidth:g,targetHeight:h,ele [...]
+elemHeight:l,offset:e,my:a.my,at:a.at})});c.fn.bgiframe&&f.bgiframe();f.offset(c.extend(j,{using:a.using}))})};c.ui.position={fit:{left:function(a,b){var d=c(window);b=a.left+b.elemWidth-d.width()-d.scrollLeft();a.left=b>0?a.left-b:Math.max(0,a.left)},top:function(a,b){var d=c(window);b=a.top+b.elemHeight-d.height()-d.scrollTop();a.top=b>0?a.top-b:Math.max(0,a.top)}},flip:{left:function(a,b){if(b.at[0]!=="center"){var d=c(window);d=a.left+b.elemWidth-d.width()-d.scrollLeft();var e=b.my[0 [...]
+-b.elemWidth:b.my[0]==="right"?b.elemWidth:0,g=-2*b.offset[0];a.left+=a.left<0?e+b.targetWidth+g:d>0?e-b.targetWidth+g:0}},top:function(a,b){if(b.at[1]!=="center"){var d=c(window);d=a.top+b.elemHeight-d.height()-d.scrollTop();var e=b.my[1]==="top"?-b.elemHeight:b.my[1]==="bottom"?b.elemHeight:0,g=b.at[1]==="top"?b.targetHeight:-b.targetHeight,h=-2*b.offset[1];a.top+=a.top<0?e+b.targetHeight+h:d>0?e+g+h:0}}}};if(!c.offset.setOffset){c.offset.setOffset=function(a,b){if(/static/.test(c.curC [...]
+"relative";var d=c(a),e=d.offset(),g=parseInt(c.curCSS(a,"top",true),10)||0,h=parseInt(c.curCSS(a,"left",true),10)||0;e={top:b.top-e.top+g,left:b.left-e.left+h};"using"in b?b.using.call(a,e):d.css(e)};c.fn.offset=function(a){var b=this[0];if(!b||!b.ownerDocument)return null;if(a)return this.each(function(){c.offset.setOffset(this,a)});return q.call(this)}}})(jQuery);
+(function(b){b.widget("ui.progressbar",{options:{value:0},_create:function(){this.element.addClass("ui-progressbar ui-widget ui-widget-content ui-corner-all").attr({role:"progressbar","aria-valuemin":this._valueMin(),"aria-valuemax":this._valueMax(),"aria-valuenow":this._value()});this.valueDiv=b("<div class='ui-progressbar-value ui-widget-header ui-corner-left'></div>").appendTo(this.element);this._refreshValue()},destroy:function(){this.element.removeClass("ui-progressbar ui-widget ui- [...]
+this.valueDiv.remove();this._superApply("destroy",arguments)},value:function(a){if(a===undefined)return this._value();this._setOption("value",a);return this},_setOption:function(a,c){switch(a){case "value":this.options.value=c;this._refreshValue();this._trigger("change");break}this._superApply("_setOption",arguments)},_value:function(){var a=this.options.value;if(typeof a!=="number")a=0;if(a<this._valueMin())a=this._valueMin();if(a>this._valueMax())a=this._valueMax();return a},_valueMin: [...]
+_valueMax:function(){return 100},_refreshValue:function(){var a=this.value();this.valueDiv[a===this._valueMax()?"addClass":"removeClass"]("ui-corner-right").width(a+"%");this.element.attr("aria-valuenow",a)}});b.extend(b.ui.progressbar,{version:"1.9m2"})})(jQuery);
+(function(d){d.widget("ui.slider",d.ui.mouse,{widgetEventPrefix:"slide",options:{animate:false,distance:0,max:100,min:0,orientation:"horizontal",range:false,step:1,value:0,values:null},_create:function(){var a=this,b=this.options;this._mouseSliding=this._keySliding=false;this._animateOff=true;this._handleIndex=null;this._detectOrientation();this._mouseInit();this.element.addClass("ui-slider ui-slider-"+this.orientation+" ui-widget ui-widget-content ui-corner-all");b.disabled&&this.elemen [...]
+this.range=d([]);if(b.range){if(b.range===true){this.range=d("<div></div>");if(!b.values)b.values=[this._valueMin(),this._valueMin()];if(b.values.length&&b.values.length!==2)b.values=[b.values[0],b.values[0]]}else this.range=d("<div></div>");this.range.appendTo(this.element).addClass("ui-slider-range");if(b.range==="min"||b.range==="max")this.range.addClass("ui-slider-range-"+b.range);this.range.addClass("ui-widget-header")}d(".ui-slider-handle",this.element).length===0&&d("<a href='#'>< [...]
+if(b.values&&b.values.length)for(;d(".ui-slider-handle",this.element).length<b.values.length;)d("<a href='#'></a>").appendTo(this.element).addClass("ui-slider-handle");this.handles=d(".ui-slider-handle",this.element).addClass("ui-state-default ui-corner-all");this.handle=this.handles.eq(0);this.handles.add(this.range).filter("a").click(function(c){c.preventDefault()}).hover(function(){b.disabled||d(this).addClass("ui-state-hover")},function(){d(this).removeClass("ui-state-hover")}).focus [...]
+else{d(".ui-slider .ui-state-focus").removeClass("ui-state-focus");d(this).addClass("ui-state-focus")}}).blur(function(){d(this).removeClass("ui-state-focus")});this.handles.each(function(c){d(this).data("index.ui-slider-handle",c)});this.handles.keydown(function(c){var e=true,f=d(this).data("index.ui-slider-handle"),g,h,i;if(!a.options.disabled){switch(c.keyCode){case d.ui.keyCode.HOME:case d.ui.keyCode.END:case d.ui.keyCode.PAGE_UP:case d.ui.keyCode.PAGE_DOWN:case d.ui.keyCode.UP:case  [...]
+false;if(!a._keySliding){a._keySliding=true;d(this).addClass("ui-state-active");g=a._start(c,f);if(g===false)return}break}i=a.options.step;g=a.options.values&&a.options.values.length?(h=a.values(f)):(h=a.value());switch(c.keyCode){case d.ui.keyCode.HOME:h=a._valueMin();break;case d.ui.keyCode.END:h=a._valueMax();break;case d.ui.keyCode.PAGE_UP:h=a._trimAlignValue(g+(a._valueMax()-a._valueMin())/5);break;case d.ui.keyCode.PAGE_DOWN:h=a._trimAlignValue(g-(a._valueMax()-a._valueMin())/5);br [...]
+a._valueMax())return;h=a._trimAlignValue(g+i);break;case d.ui.keyCode.DOWN:case d.ui.keyCode.LEFT:if(g===a._valueMin())return;h=a._trimAlignValue(g-i);break}a._slide(c,f,h);return e}}).keyup(function(c){var e=d(this).data("index.ui-slider-handle");if(a._keySliding){a._keySliding=false;a._stop(c,e);a._change(c,e);d(this).removeClass("ui-state-active")}});this._refreshValue();this._animateOff=false},destroy:function(){this.handles.remove();this.range.remove();this.element.removeClass("ui-s [...]
+this._mouseDestroy();return this},_mouseCapture:function(a){var b=this.options,c,e,f,g,h,i;if(b.disabled)return false;this.elementSize={width:this.element.outerWidth(),height:this.element.outerHeight()};this.elementOffset=this.element.offset();c={x:a.pageX,y:a.pageY};e=this._normValueFromMouse(c);f=this._valueMax()-this._valueMin()+1;h=this;this.handles.each(function(j){var k=Math.abs(e-h.values(j));if(f>k){f=k;g=d(this);i=j}});if(b.range===true&&this.values(1)===b.min){i+=1;g=d(this.han [...]
+i)===false)return false;this._mouseSliding=true;h._handleIndex=i;g.addClass("ui-state-active").focus();b=g.offset();this._clickOffset=!d(a.target).parents().andSelf().is(".ui-slider-handle")?{left:0,top:0}:{left:a.pageX-b.left-g.width()/2,top:a.pageY-b.top-g.height()/2-(parseInt(g.css("borderTopWidth"),10)||0)-(parseInt(g.css("borderBottomWidth"),10)||0)+(parseInt(g.css("marginTop"),10)||0)};e=this._normValueFromMouse(c);this._slide(a,i,e);return this._animateOff=true},_mouseStart:functi [...]
+_mouseDrag:function(a){var b=this._normValueFromMouse({x:a.pageX,y:a.pageY});this._slide(a,this._handleIndex,b);return false},_mouseStop:function(a){this.handles.removeClass("ui-state-active");this._mouseSliding=false;this._stop(a,this._handleIndex);this._change(a,this._handleIndex);this._clickOffset=this._handleIndex=null;return this._animateOff=false},_detectOrientation:function(){this.orientation=this.options.orientation==="vertical"?"vertical":"horizontal"},_normValueFromMouse:functi [...]
+if(this.orientation==="horizontal"){b=this.elementSize.width;a=a.x-this.elementOffset.left-(this._clickOffset?this._clickOffset.left:0)}else{b=this.elementSize.height;a=a.y-this.elementOffset.top-(this._clickOffset?this._clickOffset.top:0)}b=a/b;if(b>1)b=1;if(b<0)b=0;if(this.orientation==="vertical")b=1-b;a=this._valueMax()-this._valueMin();return this._trimAlignValue(this._valueMin()+b*a)},_start:function(a,b){var c={handle:this.handles[b],value:this.value()};if(this.options.values&&thi [...]
+this.values(b);c.values=this.values()}return this._trigger("start",a,c)},_slide:function(a,b,c){var e;if(this.options.values&&this.options.values.length){e=this.values(b?0:1);if(this.options.values.length===2&&this.options.range===true&&(b===0&&c>e||b===1&&c<e))c=e;if(c!==this.values(b)){e=this.values();e[b]=c;a=this._trigger("slide",a,{handle:this.handles[b],value:c,values:e});this.values(b?0:1);a!==false&&this.values(b,c,true)}}else if(c!==this.value()){a=this._trigger("slide",a,{handl [...]
+value:c});a!==false&&this.value(c)}},_stop:function(a,b){var c={handle:this.handles[b],value:this.value()};if(this.options.values&&this.options.values.length){c.value=this.values(b);c.values=this.values()}this._trigger("stop",a,c)},_change:function(a,b){if(!this._keySliding&&!this._mouseSliding){var c={handle:this.handles[b],value:this.value()};if(this.options.values&&this.options.values.length){c.value=this.values(b);c.values=this.values()}this._trigger("change",a,c)}},value:function(a) [...]
+this._trimAlignValue(a);this._refreshValue();this._change(null,0)}return this._value()},values:function(a,b){var c,e,f;if(arguments.length>1){this.options.values[a]=this._trimAlignValue(b);this._refreshValue();this._change(null,a)}if(arguments.length)if(d.isArray(arguments[0])){c=this.options.values;e=arguments[0];for(f=0;f<c.length;f+=1){c[f]=this._trimAlignValue(e[f]);this._change(null,f)}this._refreshValue()}else return this.options.values&&this.options.values.length?this._values(a):t [...]
+else return this._values()},_setOption:function(a,b){var c,e=0;if(d.isArray(this.options.values))e=this.options.values.length;this._superApply("_setOption",arguments);switch(a){case "disabled":if(b){this.handles.filter(".ui-state-focus").blur();this.handles.removeClass("ui-state-hover");this.handles.attr("disabled","disabled");this.element.addClass("ui-disabled")}else{this.handles.removeAttr("disabled");this.element.removeClass("ui-disabled")}break;case "orientation":this._detectOrientat [...]
+this.orientation);this._refreshValue();break;case "value":this._animateOff=true;this._refreshValue();this._change(null,0);this._animateOff=false;break;case "values":this._animateOff=true;this._refreshValue();for(c=0;c<e;c+=1)this._change(null,c);this._animateOff=false;break}},_value:function(){var a=this.options.value;return a=this._trimAlignValue(a)},_values:function(a){var b,c;if(arguments.length){b=this.options.values[a];return b=this._trimAlignValue(b)}else{b=this.options.values.slic [...]
+0;c<b.length;c+=1)b[c]=this._trimAlignValue(b[c]);return b}},_trimAlignValue:function(a){if(a<this._valueMin())return this._valueMin();if(a>this._valueMax())return this._valueMax();var b=this.options.step>0?this.options.step:1,c=a%b;a=a-c;if(Math.abs(c)*2>=b)a+=c>0?b:-b;return parseFloat(a.toFixed(5))},_valueMin:function(){return this.options.min},_valueMax:function(){return this.options.max},_refreshValue:function(){var a=this.options.range,b=this.options,c=this,e=!this._animateOff?b.an [...]
+f,g={},h,i,j,k;if(this.options.values&&this.options.values.length)this.handles.each(function(l){f=(c.values(l)-c._valueMin())/(c._valueMax()-c._valueMin())*100;g[c.orientation==="horizontal"?"left":"bottom"]=f+"%";d(this).stop(1,1)[e?"animate":"css"](g,b.animate);if(c.options.range===true)if(c.orientation==="horizontal"){if(l===0)c.range.stop(1,1)[e?"animate":"css"]({left:f+"%"},b.animate);if(l===1)c.range[e?"animate":"css"]({width:f-h+"%"},{queue:false,duration:b.animate})}else{if(l===0 [...]
+1)[e?"animate":"css"]({bottom:f+"%"},b.animate);if(l===1)c.range[e?"animate":"css"]({height:f-h+"%"},{queue:false,duration:b.animate})}h=f});else{i=this.value();j=this._valueMin();k=this._valueMax();f=k!==j?(i-j)/(k-j)*100:0;g[c.orientation==="horizontal"?"left":"bottom"]=f+"%";this.handle.stop(1,1)[e?"animate":"css"](g,b.animate);if(a==="min"&&this.orientation==="horizontal")this.range.stop(1,1)[e?"animate":"css"]({width:f+"%"},b.animate);if(a==="max"&&this.orientation==="horizontal")th [...]
+"animate":"css"]({width:100-f+"%"},{queue:false,duration:b.animate});if(a==="min"&&this.orientation==="vertical")this.range.stop(1,1)[e?"animate":"css"]({height:f+"%"},b.animate);if(a==="max"&&this.orientation==="vertical")this.range[e?"animate":"css"]({height:100-f+"%"},{queue:false,duration:b.animate})}}});d.extend(d.ui.slider,{version:"1.9m2"})})(jQuery);
+(function(d){function s(){return++u}function v(){return++w}var u=0,w=0;d.widget("ui.tabs",{options:{add:null,ajaxOptions:null,cache:false,cookie:null,collapsible:false,disable:null,disabled:[],enable:null,event:"click",fx:null,idPrefix:"ui-tabs-",load:null,panelTemplate:"<div></div>",remove:null,select:null,show:null,spinner:"<em>Loading…</em>",tabTemplate:'<li><a href="#{href}"><span>#{label}</span></a></li>'},_create:function(){this._tabify(true)},_setOption:function(c,e){if(c==" [...]
+e==this.options.selected||this.select(e);else{this.options[c]=e;this._tabify()}},_tabId:function(c){return c.title&&c.title.replace(/\s/g,"_").replace(/[^A-Za-z0-9\-_:\.]/g,"")||this.options.idPrefix+s()},_sanitizeSelector:function(c){return c.replace(/:/g,"\\:")},_cookie:function(){var c=this.cookie||(this.cookie=this.options.cookie.name||"ui-tabs-"+v());return d.cookie.apply(null,[c].concat(d.makeArray(arguments)))},_ui:function(c,e){return{tab:c,panel:e,index:this.anchors.index(c)}},_ [...]
+d(this);c.html(c.data("label.tabs")).removeData("label.tabs")})},_tabify:function(c){function e(g,f){g.css({display:""});!d.support.opacity&&f.opacity&&g[0].style.removeAttribute("filter")}this.list=this.element.find("ol,ul").eq(0);this.lis=d("li:has(a[href])",this.list);this.anchors=this.lis.map(function(){return d("a",this)[0]});this.panels=d([]);var a=this,b=this.options,h=/^#.+/;this.anchors.each(function(g,f){var j=d(f).attr("href"),l=j.split("#")[0],p;if(l&&(l===location.toString() [...]
+(p=d("base")[0])&&l===p.href)){j=f.hash;f.href=j}if(h.test(j))a.panels=a.panels.add(a._sanitizeSelector(j));else if(j!="#"){d.data(f,"href.tabs",j);d.data(f,"load.tabs",j.replace(/#.*$/,""));j=a._tabId(f);f.href="#"+j;f=d("#"+j);if(!f.length){f=d(b.panelTemplate).attr("id",j).addClass("ui-tabs-panel ui-widget-content ui-corner-bottom").insertAfter(a.panels[g-1]||a.list);f.data("destroy.tabs",true)}a.panels=a.panels.add(f)}else b.disabled.push(g)});if(c){this.element.addClass("ui-tabs ui- [...]
+this.list.addClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all");this.lis.addClass("ui-state-default ui-corner-top");this.panels.addClass("ui-tabs-panel ui-widget-content ui-corner-bottom");if(b.selected===undefined){location.hash&&this.anchors.each(function(g,f){if(f.hash==location.hash){b.selected=g;return false}});if(typeof b.selected!="number"&&b.cookie)b.selected=parseInt(a._cookie(),10);if(typeof b.selected!="number"&&this.lis.filter(".ui-tabs-sel [...]
+this.lis.index(this.lis.filter(".ui-tabs-selected"));b.selected=b.selected||(this.lis.length?0:-1)}else if(b.selected===null)b.selected=-1;b.selected=b.selected>=0&&this.anchors[b.selected]||b.selected<0?b.selected:0;b.disabled=d.unique(b.disabled.concat(d.map(this.lis.filter(".ui-state-disabled"),function(g){return a.lis.index(g)}))).sort();d.inArray(b.selected,b.disabled)!=-1&&b.disabled.splice(d.inArray(b.selected,b.disabled),1);this.panels.addClass("ui-tabs-hide");this.lis.removeClas [...]
+if(b.selected>=0&&this.anchors.length){this.panels.eq(b.selected).removeClass("ui-tabs-hide");this.lis.eq(b.selected).addClass("ui-tabs-selected ui-state-active");a.element.queue("tabs",function(){a._trigger("show",null,a._ui(a.anchors[b.selected],a.panels[b.selected]))});this.load(b.selected)}d(window).bind("unload",function(){a.lis.add(a.anchors).unbind(".tabs");a.lis=a.anchors=a.panels=null})}else b.selected=this.lis.index(this.lis.filter(".ui-tabs-selected"));this.element[b.collapsib [...]
+"removeClass"]("ui-tabs-collapsible");b.cookie&&this._cookie(b.selected,b.cookie);c=0;for(var i;i=this.lis[c];c++)d(i)[d.inArray(c,b.disabled)!=-1&&!d(i).hasClass("ui-tabs-selected")?"addClass":"removeClass"]("ui-state-disabled");b.cache===false&&this.anchors.removeData("cache.tabs");this.lis.add(this.anchors).unbind(".tabs");if(b.event!="mouseover"){var k=function(g,f){f.is(":not(.ui-state-disabled)")&&f.addClass("ui-state-"+g)},n=function(g,f){f.removeClass("ui-state-"+g)};this.lis.bin [...]
+function(){k("hover",d(this))});this.lis.bind("mouseout.tabs",function(){n("hover",d(this))});this.anchors.bind("focus.tabs",function(){k("focus",d(this).closest("li"))});this.anchors.bind("blur.tabs",function(){n("focus",d(this).closest("li"))})}var m,o;if(b.fx)if(d.isArray(b.fx)){m=b.fx[0];o=b.fx[1]}else m=o=b.fx;var q=o?function(g,f){d(g).closest("li").addClass("ui-tabs-selected ui-state-active");f.hide().removeClass("ui-tabs-hide").animate(o,o.duration||"normal",function(){e(f,o);a._ [...]
+null,a._ui(g,f[0]))})}:function(g,f){d(g).closest("li").addClass("ui-tabs-selected ui-state-active");f.removeClass("ui-tabs-hide");a._trigger("show",null,a._ui(g,f[0]))},r=m?function(g,f){f.animate(m,m.duration||"normal",function(){a.lis.removeClass("ui-tabs-selected ui-state-active");f.addClass("ui-tabs-hide");e(f,m);a.element.dequeue("tabs")})}:function(g,f){a.lis.removeClass("ui-tabs-selected ui-state-active");f.addClass("ui-tabs-hide");a.element.dequeue("tabs")};this.anchors.bind(b.e [...]
+function(){var g=this,f=d(this).closest("li"),j=a.panels.filter(":not(.ui-tabs-hide)"),l=d(a._sanitizeSelector(this.hash));if(f.hasClass("ui-tabs-selected")&&!b.collapsible||f.hasClass("ui-state-disabled")||f.hasClass("ui-state-processing")||a._trigger("select",null,a._ui(this,l[0]))===false){this.blur();return false}b.selected=a.anchors.index(this);a.abort();if(b.collapsible)if(f.hasClass("ui-tabs-selected")){b.selected=-1;b.cookie&&a._cookie(b.selected,b.cookie);a.element.queue("tabs", [...]
+j)}).dequeue("tabs");this.blur();return false}else if(!j.length){b.cookie&&a._cookie(b.selected,b.cookie);a.element.queue("tabs",function(){q(g,l)});a.load(a.anchors.index(this));this.blur();return false}b.cookie&&a._cookie(b.selected,b.cookie);if(l.length){j.length&&a.element.queue("tabs",function(){r(g,j)});a.element.queue("tabs",function(){q(g,l)});a.load(a.anchors.index(this))}else throw"jQuery UI Tabs: Mismatching fragment identifier.";d.browser.msie&&this.blur()});this.anchors.bind [...]
+function(){return false})},destroy:function(){var c=this.options;this.abort();this.element.unbind(".tabs").removeClass("ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible").removeData("tabs");this.list.removeClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all");this.anchors.each(function(){var e=d.data(this,"href.tabs");if(e)this.href=e;var a=d(this).unbind(".tabs");d.each(["href","load","cache"],function(b,h){a.removeData(h+".tabs")})} [...]
+"destroy.tabs")?d(this).remove():d(this).removeClass("ui-state-default ui-corner-top ui-tabs-selected ui-state-active ui-state-hover ui-state-focus ui-state-disabled ui-tabs-panel ui-widget-content ui-corner-bottom ui-tabs-hide")});c.cookie&&this._cookie(null,c.cookie);return this},add:function(c,e,a){if(a===undefined)a=this.anchors.length;var b=this,h=this.options;e=d(h.tabTemplate.replace(/#\{href\}/g,c).replace(/#\{label\}/g,e));c=!c.indexOf("#")?c.replace("#",""):this._tabId(d("a",e) [...]
+true);var i=d("#"+c);i.length||(i=d(h.panelTemplate).attr("id",c).data("destroy.tabs",true));i.addClass("ui-tabs-panel ui-widget-content ui-corner-bottom ui-tabs-hide");if(a>=this.lis.length){e.appendTo(this.list);i.appendTo(this.list[0].parentNode)}else{e.insertBefore(this.lis[a]);i.insertBefore(this.panels[a])}h.disabled=d.map(h.disabled,function(k){return k>=a?++k:k});this._tabify();if(this.anchors.length==1){h.selected=0;e.addClass("ui-tabs-selected ui-state-active");i.removeClass("u [...]
+this.element.queue("tabs",function(){b._trigger("show",null,b._ui(b.anchors[0],b.panels[0]))});this.load(0)}this._trigger("add",null,this._ui(this.anchors[a],this.panels[a]));return this},remove:function(c){var e=this.options,a=this.lis.eq(c).remove(),b=this.panels.eq(c).remove();if(a.hasClass("ui-tabs-selected")&&this.anchors.length>1)this.select(c+(c+1<this.anchors.length?1:-1));e.disabled=d.map(d.grep(e.disabled,function(h){return h!=c}),function(h){return h>=c?--h:h});this._tabify(); [...]
+null,this._ui(a.find("a")[0],b[0]));return this},enable:function(c){var e=this.options;if(d.inArray(c,e.disabled)!=-1){this.lis.eq(c).removeClass("ui-state-disabled");e.disabled=d.grep(e.disabled,function(a){return a!=c});this._trigger("enable",null,this._ui(this.anchors[c],this.panels[c]));return this}},disable:function(c){var e=this.options;if(c!=e.selected){this.lis.eq(c).addClass("ui-state-disabled");e.disabled.push(c);e.disabled.sort();this._trigger("disable",null,this._ui(this.anch [...]
+select:function(c){if(typeof c=="string")c=this.anchors.index(this.anchors.filter("[href$="+c+"]"));else if(c===null)c=-1;if(c==-1&&this.options.collapsible)c=this.options.selected;this.anchors.eq(c).trigger(this.options.event+".tabs");return this},load:function(c){var e=this,a=this.options,b=this.anchors.eq(c)[0],h=d.data(b,"load.tabs");this.abort();if(!h||this.element.queue("tabs").length!==0&&d.data(b,"cache.tabs"))this.element.dequeue("tabs");else{this.lis.eq(c).addClass("ui-state-pr [...]
+if(a.spinner){var i=d("span",b);i.data("label.tabs",i.html()).html(a.spinner)}this.xhr=d.ajax(d.extend({},a.ajaxOptions,{url:h,success:function(k,n){d(e._sanitizeSelector(b.hash)).html(k);e._cleanup();a.cache&&d.data(b,"cache.tabs",true);e._trigger("load",null,e._ui(e.anchors[c],e.panels[c]));try{a.ajaxOptions.success(k,n)}catch(m){}},error:function(k,n){e._cleanup();e._trigger("load",null,e._ui(e.anchors[c],e.panels[c]));try{a.ajaxOptions.error(k,n,c,b)}catch(m){}}}));e.element.dequeue( [...]
+abort:function(){this.element.queue([]);this.panels.stop(false,true);this.element.queue("tabs",this.element.queue("tabs").splice(-2,2));if(this.xhr){this.xhr.abort();delete this.xhr}this._cleanup();return this},url:function(c,e){this.anchors.eq(c).removeData("cache.tabs").data("load.tabs",e);return this},length:function(){return this.anchors.length}});d.extend(d.ui.tabs,{version:"1.9m2"});d.extend(d.ui.tabs.prototype,{rotation:null,rotate:function(c,e){var a=this,b=this.options,h=a._rota [...]
+function(i){clearTimeout(a.rotation);a.rotation=setTimeout(function(){var k=b.selected;a.select(++k<a.anchors.length?k:0)},c);i&&i.stopPropagation()});e=a._unrotate||(a._unrotate=!e?function(i){i.clientX&&a.rotate(null)}:function(){t=b.selected;h()});if(c){this.element.bind("tabsshow",h);this.anchors.bind(b.event+".tabs",e);h()}else{clearTimeout(a.rotation);this.element.unbind("tabsshow",h);this.anchors.unbind(b.event+".tabs",e);delete this._rotate;delete this._unrotate}return this}})})( [...]
+(function(b){b(document.body).is("[role]")||b(document.body).attr("role","application");var f=0;b.widget("ui.tooltip",{options:{tooltipClass:"ui-widget-content",content:function(){return b(this).attr("title")},position:{my:"left center",at:"right center",offset:"15 0"}},_init:function(){var c=this;this.tooltip=b("<div></div>").attr("id","ui-tooltip-"+f++).attr("role","tooltip").attr("aria-hidden","true").addClass("ui-tooltip ui-widget ui-corner-all").addClass(this.options.tooltipClass).a [...]
+this.tooltipContent=b("<div></div>").addClass("ui-tooltip-content").appendTo(this.tooltip);this.opacity=this.tooltip.css("opacity");this.element.bind("focus.tooltip mouseenter.tooltip",function(a){c.open(a)}).bind("blur.tooltip mouseleave.tooltip",function(a){c.close(a)})},enable:function(){this.options.disabled=false},disable:function(){this.options.disabled=true},destroy:function(){this.tooltip.remove();b.Widget.prototype.destroy.apply(this,arguments)},widget:function(){return this.too [...]
+this.element;if(!(this.current&&this.current[0]==a[0])){var d=this;this.current=a;this.currentTitle=a.attr("title");var e=this.options.content.call(a[0],function(g){d.current==a&&d._show(c,a,g)});e&&d._show(c,a,e)}},_show:function(c,a,d){if(d){a.attr("title","");if(!this.options.disabled){this.tooltipContent.html(d);this.tooltip.css({top:0,left:0}).show().position(b.extend(this.options.position,{of:a})).hide();this.tooltip.attr("aria-hidden","false");a.attr("aria-describedby",this.toolti [...]
+if(this.tooltip.is(":animated"))this.tooltip.stop().show().fadeTo("normal",this.opacity);else this.tooltip.is(":visible")?this.tooltip.fadeTo("normal",this.opacity):this.tooltip.fadeIn();this._trigger("open",c)}}},close:function(c){if(this.current){var a=this.current.attr("title",this.currentTitle);this.current=null;if(!this.options.disabled){a.removeAttr("aria-describedby");this.tooltip.attr("aria-hidden","true");this.tooltip.is(":animated")?this.tooltip.stop().fadeTo("normal",0,functio [...]
+"")}):this.tooltip.stop().fadeOut();this._trigger("close",c)}}}})})(jQuery);
diff --git a/src/compiler/scala/tools/nsc/doc/html/resource/lib/jquery.js b/src/compiler/scala/tools/nsc/doc/html/resource/lib/jquery.js
new file mode 100644
index 0000000..7c24308
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/doc/html/resource/lib/jquery.js
@@ -0,0 +1,154 @@
+/*!
+ * jQuery JavaScript Library v1.4.2
+ * http://jquery.com/
+ *
+ * Copyright 2010, John Resig
+ * Dual licensed under the MIT or GPL Version 2 licenses.
+ * http://jquery.org/license
+ *
+ * Includes Sizzle.js
+ * http://sizzlejs.com/
+ * Copyright 2010, The Dojo Foundation
+ * Released under the MIT, BSD, and GPL Licenses.
+ *
+ * Date: Sat Feb 13 22:33:48 2010 -0500
+ */
+(function(A,w){function ma(){if(!c.isReady){try{s.documentElement.doScroll("left")}catch(a){setTimeout(ma,1);return}c.ready()}}function Qa(a,b){b.src?c.ajax({url:b.src,async:false,dataType:"script"}):c.globalEval(b.text||b.textContent||b.innerHTML||"");b.parentNode&&b.parentNode.removeChild(b)}function X(a,b,d,f,e,j){var i=a.length;if(typeof b==="object"){for(var o in b)X(a,o,b[o],f,e,d);return a}if(d!==w){f=!j&&f&&c.isFunction(d);for(o=0;o<i;o++)e(a[o],b,f?d.call(a[o],o,e(a[o],b)):d,j); [...]
+e(a[0],b):w}function J(){return(new Date).getTime()}function Y(){return false}function Z(){return true}function na(a,b,d){d[0].type=a;return c.event.handle.apply(b,d)}function oa(a){var b,d=[],f=[],e=arguments,j,i,o,k,n,r;i=c.data(this,"events");if(!(a.liveFired===this||!i||!i.live||a.button&&a.type==="click")){a.liveFired=this;var u=i.live.slice(0);for(k=0;k<u.length;k++){i=u[k];i.origType.replace(O,"")===a.type?f.push(i.selector):u.splice(k--,1)}j=c(a.target).closest(f,a.currentTarget) [...]
+j.length;n<r;n++)for(k=0;k<u.length;k++){i=u[k];if(j[n].selector===i.selector){o=j[n].elem;f=null;if(i.preType==="mouseenter"||i.preType==="mouseleave")f=c(a.relatedTarget).closest(i.selector)[0];if(!f||f!==o)d.push({elem:o,handleObj:i})}}n=0;for(r=d.length;n<r;n++){j=d[n];a.currentTarget=j.elem;a.data=j.handleObj.data;a.handleObj=j.handleObj;if(j.handleObj.origHandler.apply(j.elem,e)===false){b=false;break}}return b}}function pa(a,b){return"live."+(a&&a!=="*"?a+".":"")+b.replace(/\./g," [...]
+"&")}function qa(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function ra(a,b){var d=0;b.each(function(){if(this.nodeName===(a[d]&&a[d].nodeName)){var f=c.data(a[d++]),e=c.data(this,f);if(f=f&&f.events){delete e.handle;e.events={};for(var j in f)for(var i in f[j])c.event.add(this,j,f[j][i],f[j][i].data)}}})}function sa(a,b,d){var f,e,j;b=b&&b[0]?b[0].ownerDocument||b[0]:s;if(a.length===1&&typeof a[0]==="string"&&a[0].length<512&&b===s&&!ta.test(a[0])&&(c.support.checkClone||!ua [...]
+true;if(j=c.fragments[a[0]])if(j!==1)f=j}if(!f){f=b.createDocumentFragment();c.clean(a,b,f,d)}if(e)c.fragments[a[0]]=j?f:1;return{fragment:f,cacheable:e}}function K(a,b){var d={};c.each(va.concat.apply([],va.slice(0,b)),function(){d[this]=a});return d}function wa(a){return"scrollTo"in a&&a.document?a:a.nodeType===9?a.defaultView||a.parentWindow:false}var c=function(a,b){return new c.fn.init(a,b)},Ra=A.jQuery,Sa=A.$,s=A.document,T,Ta=/^[^<]*(<[\w\W]+>)[^>]*$|^#([\w-]+)$/,Ua=/^.[^:#\[\.,]* [...]
+Wa=/^(\s|\u00A0)+|(\s|\u00A0)+$/g,Xa=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,P=navigator.userAgent,xa=false,Q=[],L,$=Object.prototype.toString,aa=Object.prototype.hasOwnProperty,ba=Array.prototype.push,R=Array.prototype.slice,ya=Array.prototype.indexOf;c.fn=c.prototype={init:function(a,b){var d,f;if(!a)return this;if(a.nodeType){this.context=this[0]=a;this.length=1;return this}if(a==="body"&&!b){this.context=s;this[0]=s.body;this.selector="body";this.length=1;return this}if(typeof a==="string")if(( [...]
+(d[1]||!b))if(d[1]){f=b?b.ownerDocument||b:s;if(a=Xa.exec(a))if(c.isPlainObject(b)){a=[s.createElement(a[1])];c.fn.attr.call(a,b,true)}else a=[f.createElement(a[1])];else{a=sa([d[1]],[f]);a=(a.cacheable?a.fragment.cloneNode(true):a.fragment).childNodes}return c.merge(this,a)}else{if(b=s.getElementById(d[2])){if(b.id!==d[2])return T.find(a);this.length=1;this[0]=b}this.context=s;this.selector=a;return this}else if(!b&&/^\w+$/.test(a)){this.selector=a;this.context=s;a=s.getElementsByTagNam [...]
+a)}else return!b||b.jquery?(b||T).find(a):c(b).find(a);else if(c.isFunction(a))return T.ready(a);if(a.selector!==w){this.selector=a.selector;this.context=a.context}return c.makeArray(a,this)},selector:"",jquery:"1.4.2",length:0,size:function(){return this.length},toArray:function(){return R.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this.slice(a)[0]:this[a]},pushStack:function(a,b,d){var f=c();c.isArray(a)?ba.apply(f,a):c.merge(f,a);f.prevObject=this;f.context=this.c [...]
+"find")f.selector=this.selector+(this.selector?" ":"")+d;else if(b)f.selector=this.selector+"."+b+"("+d+")";return f},each:function(a,b){return c.each(this,a,b)},ready:function(a){c.bindReady();if(c.isReady)a.call(s,c);else Q&&Q.push(a);return this},eq:function(a){return a===-1?this.slice(a):this.slice(a,+a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(R.apply(this,arguments),"slice",R.call(arguments).join(","))},map:fu [...]
+function(b,d){return a.call(b,d,b)}))},end:function(){return this.prevObject||c(null)},push:ba,sort:[].sort,splice:[].splice};c.fn.init.prototype=c.fn;c.extend=c.fn.extend=function(){var a=arguments[0]||{},b=1,d=arguments.length,f=false,e,j,i,o;if(typeof a==="boolean"){f=a;a=arguments[1]||{};b=2}if(typeof a!=="object"&&!c.isFunction(a))a={};if(d===b){a=this;--b}for(;b<d;b++)if((e=arguments[b])!=null)for(j in e){i=a[j];o=e[j];if(a!==o)if(f&&o&&(c.isPlainObject(o)||c.isArray(o))){i=i&&(c.i [...]
+c.isArray(i))?i:c.isArray(o)?[]:{};a[j]=c.extend(f,i,o)}else if(o!==w)a[j]=o}return a};c.extend({noConflict:function(a){A.$=Sa;if(a)A.jQuery=Ra;return c},isReady:false,ready:function(){if(!c.isReady){if(!s.body)return setTimeout(c.ready,13);c.isReady=true;if(Q){for(var a,b=0;a=Q[b++];)a.call(s,c);Q=null}c.fn.triggerHandler&&c(s).triggerHandler("ready")}},bindReady:function(){if(!xa){xa=true;if(s.readyState==="complete")return c.ready();if(s.addEventListener){s.addEventListener("DOMConten [...]
+L,false);A.addEventListener("load",c.ready,false)}else if(s.attachEvent){s.attachEvent("onreadystatechange",L);A.attachEvent("onload",c.ready);var a=false;try{a=A.frameElement==null}catch(b){}s.documentElement.doScroll&&a&&ma()}}},isFunction:function(a){return $.call(a)==="[object Function]"},isArray:function(a){return $.call(a)==="[object Array]"},isPlainObject:function(a){if(!a||$.call(a)!=="[object Object]"||a.nodeType||a.setInterval)return false;if(a.constructor&&!aa.call(a,"construc [...]
+"isPrototypeOf"))return false;var b;for(b in a);return b===w||aa.call(a,b)},isEmptyObject:function(a){for(var b in a)return false;return true},error:function(a){throw a;},parseJSON:function(a){if(typeof a!=="string"||!a)return null;a=c.trim(a);if(/^[\],:{}\s]*$/.test(a.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,"")))return A.JSON&&A.JSON.parse?A.JSON.parse(a):(new Functi [...]
+a))();else c.error("Invalid JSON: "+a)},noop:function(){},globalEval:function(a){if(a&&Va.test(a)){var b=s.getElementsByTagName("head")[0]||s.documentElement,d=s.createElement("script");d.type="text/javascript";if(c.support.scriptEval)d.appendChild(s.createTextNode(a));else d.text=a;b.insertBefore(d,b.firstChild);b.removeChild(d)}},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,b,d){var f,e=0,j=a.length,i=j===w||c.isFunction(a);if(d) [...]
+d)===false)break}else for(;e<j;){if(b.apply(a[e++],d)===false)break}else if(i)for(f in a){if(b.call(a[f],f,a[f])===false)break}else for(d=a[0];e<j&&b.call(d,e,d)!==false;d=a[++e]);return a},trim:function(a){return(a||"").replace(Wa,"")},makeArray:function(a,b){b=b||[];if(a!=null)a.length==null||typeof a==="string"||c.isFunction(a)||typeof a!=="function"&&a.setInterval?ba.call(b,a):c.merge(b,a);return b},inArray:function(a,b){if(b.indexOf)return b.indexOf(a);for(var d=0,f=b.length;d<f;d++ [...]
+a)return d;return-1},merge:function(a,b){var d=a.length,f=0;if(typeof b.length==="number")for(var e=b.length;f<e;f++)a[d++]=b[f];else for(;b[f]!==w;)a[d++]=b[f++];a.length=d;return a},grep:function(a,b,d){for(var f=[],e=0,j=a.length;e<j;e++)!d!==!b(a[e],e)&&f.push(a[e]);return f},map:function(a,b,d){for(var f=[],e,j=0,i=a.length;j<i;j++){e=b(a[j],j,d);if(e!=null)f[f.length]=e}return f.concat.apply([],f)},guid:1,proxy:function(a,b,d){if(arguments.length===2)if(typeof b==="string"){d=a;a=d [...]
+!c.isFunction(b)){d=b;b=w}if(!b&&a)b=function(){return a.apply(d||this,arguments)};if(a)b.guid=a.guid=a.guid||b.guid||c.guid++;return b},uaMatch:function(a){a=a.toLowerCase();a=/(webkit)[ \/]([\w.]+)/.exec(a)||/(opera)(?:.*version)?[ \/]([\w.]+)/.exec(a)||/(msie) ([\w.]+)/.exec(a)||!/compatible/.test(a)&&/(mozilla)(?:.*? rv:([\w.]+))?/.exec(a)||[];return{browser:a[1]||"",version:a[2]||"0"}},browser:{}});P=c.uaMatch(P);if(P.browser){c.browser[P.browser]=true;c.browser.version=P.version}if [...]
+true;if(ya)c.inArray=function(a,b){return ya.call(b,a)};T=c(s);if(s.addEventListener)L=function(){s.removeEventListener("DOMContentLoaded",L,false);c.ready()};else if(s.attachEvent)L=function(){if(s.readyState==="complete"){s.detachEvent("onreadystatechange",L);c.ready()}};(function(){c.support={};var a=s.documentElement,b=s.createElement("script"),d=s.createElement("div"),f="script"+J();d.style.display="none";d.innerHTML="   <link/><table></table><a href='/a' style='color:red;float:left [...]
+var e=d.getElementsByTagName("*"),j=d.getElementsByTagName("a")[0];if(!(!e||!e.length||!j)){c.support={leadingWhitespace:d.firstChild.nodeType===3,tbody:!d.getElementsByTagName("tbody").length,htmlSerialize:!!d.getElementsByTagName("link").length,style:/red/.test(j.getAttribute("style")),hrefNormalized:j.getAttribute("href")==="/a",opacity:/^0.55$/.test(j.style.opacity),cssFloat:!!j.style.cssFloat,checkOn:d.getElementsByTagName("input")[0].value==="on",optSelected:s.createElement("select [...]
+parentNode:d.removeChild(d.appendChild(s.createElement("div"))).parentNode===null,deleteExpando:true,checkClone:false,scriptEval:false,noCloneEvent:true,boxModel:null};b.type="text/javascript";try{b.appendChild(s.createTextNode("window."+f+"=1;"))}catch(i){}a.insertBefore(b,a.firstChild);if(A[f]){c.support.scriptEval=true;delete A[f]}try{delete b.test}catch(o){c.support.deleteExpando=false}a.removeChild(b);if(d.attachEvent&&d.fireEvent){d.attachEvent("onclick",function k(){c.support.noCl [...]
+false;d.detachEvent("onclick",k)});d.cloneNode(true).fireEvent("onclick")}d=s.createElement("div");d.innerHTML="<input type='radio' name='radiotest' checked='checked'/>";a=s.createDocumentFragment();a.appendChild(d.firstChild);c.support.checkClone=a.cloneNode(true).cloneNode(true).lastChild.checked;c(function(){var k=s.createElement("div");k.style.width=k.style.paddingLeft="1px";s.body.appendChild(k);c.boxModel=c.support.boxModel=k.offsetWidth===2;s.body.removeChild(k).style.display="non [...]
+s.createElement("div");k="on"+k;var r=k in n;if(!r){n.setAttribute(k,"return;");r=typeof n[k]==="function"}return r};c.support.submitBubbles=a("submit");c.support.changeBubbles=a("change");a=b=d=e=j=null}})();c.props={"for":"htmlFor","class":"className",readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan",colspan:"colSpan",tabindex:"tabIndex",usemap:"useMap",frameborder:"frameBorder"};var G="jQuery"+J(),Ya=0,za={};c.extend({cache:{},expando:G,noData:{embe [...]
+applet:true},data:function(a,b,d){if(!(a.nodeName&&c.noData[a.nodeName.toLowerCase()])){a=a==A?za:a;var f=a[G],e=c.cache;if(!f&&typeof b==="string"&&d===w)return null;f||(f=++Ya);if(typeof b==="object"){a[G]=f;e[f]=c.extend(true,{},b)}else if(!e[f]){a[G]=f;e[f]={}}a=e[f];if(d!==w)a[b]=d;return typeof b==="string"?a[b]:a}},removeData:function(a,b){if(!(a.nodeName&&c.noData[a.nodeName.toLowerCase()])){a=a==A?za:a;var d=a[G],f=c.cache,e=f[d];if(b){if(e){delete e[b];c.isEmptyObject(e)&&c.rem [...]
+else a.removeAttribute&&a.removeAttribute(c.expando);delete f[d]}}}});c.fn.extend({data:function(a,b){if(typeof a==="undefined"&&this.length)return c.data(this[0]);else if(typeof a==="object")return this.each(function(){c.data(this,a)});var d=a.split(".");d[1]=d[1]?"."+d[1]:"";if(b===w){var f=this.triggerHandler("getData"+d[1]+"!",[d[0]]);if(f===w&&this.length)f=c.data(this[0],a);return f===w&&d[1]?this.data(d[0]):f}else return this.trigger("setData"+d[1]+"!",[d[0],b]).each(function(){c. [...]
+a,b)})},removeData:function(a){return this.each(function(){c.removeData(this,a)})}});c.extend({queue:function(a,b,d){if(a){b=(b||"fx")+"queue";var f=c.data(a,b);if(!d)return f||[];if(!f||c.isArray(d))f=c.data(a,b,c.makeArray(d));else f.push(d);return f}},dequeue:function(a,b){b=b||"fx";var d=c.queue(a,b),f=d.shift();if(f==="inprogress")f=d.shift();if(f){b==="fx"&&d.unshift("inprogress");f.call(a,function(){c.dequeue(a,b)})}}});c.fn.extend({queue:function(a,b){if(typeof a!=="string"){b=a; [...]
+w)return c.queue(this[0],a);return this.each(function(){var d=c.queue(this,a,b);a==="fx"&&d[0]!=="inprogress"&&c.dequeue(this,a)})},dequeue:function(a){return this.each(function(){c.dequeue(this,a)})},delay:function(a,b){a=c.fx?c.fx.speeds[a]||a:a;b=b||"fx";return this.queue(b,function(){var d=this;setTimeout(function(){c.dequeue(d,b)},a)})},clearQueue:function(a){return this.queue(a||"fx",[])}});var Aa=/[\n\t]/g,ca=/\s+/,Za=/\r/g,$a=/href|src|style/,ab=/(button|input)/i,bb=/(button|inpu [...]
+cb=/^(a|area)$/i,Ba=/radio|checkbox/;c.fn.extend({attr:function(a,b){return X(this,a,b,true,c.attr)},removeAttr:function(a){return this.each(function(){c.attr(this,a,"");this.nodeType===1&&this.removeAttribute(a)})},addClass:function(a){if(c.isFunction(a))return this.each(function(n){var r=c(this);r.addClass(a.call(this,n,r.attr("class")))});if(a&&typeof a==="string")for(var b=(a||"").split(ca),d=0,f=this.length;d<f;d++){var e=this[d];if(e.nodeType===1)if(e.className){for(var j=" "+e.cla [...]
+i=e.className,o=0,k=b.length;o<k;o++)if(j.indexOf(" "+b[o]+" ")<0)i+=" "+b[o];e.className=c.trim(i)}else e.className=a}return this},removeClass:function(a){if(c.isFunction(a))return this.each(function(k){var n=c(this);n.removeClass(a.call(this,k,n.attr("class")))});if(a&&typeof a==="string"||a===w)for(var b=(a||"").split(ca),d=0,f=this.length;d<f;d++){var e=this[d];if(e.nodeType===1&&e.className)if(a){for(var j=(" "+e.className+" ").replace(Aa," "),i=0,o=b.length;i<o;i++)j=j.replace(" "+ [...]
+" ");e.className=c.trim(j)}else e.className=""}return this},toggleClass:function(a,b){var d=typeof a,f=typeof b==="boolean";if(c.isFunction(a))return this.each(function(e){var j=c(this);j.toggleClass(a.call(this,e,j.attr("class"),b),b)});return this.each(function(){if(d==="string")for(var e,j=0,i=c(this),o=b,k=a.split(ca);e=k[j++];){o=f?o:!i.hasClass(e);i[o?"addClass":"removeClass"](e)}else if(d==="undefined"||d==="boolean"){this.className&&c.data(this,"__className__",this.className);thi [...]
+this.className||a===false?"":c.data(this,"__className__")||""}})},hasClass:function(a){a=" "+a+" ";for(var b=0,d=this.length;b<d;b++)if((" "+this[b].className+" ").replace(Aa," ").indexOf(a)>-1)return true;return false},val:function(a){if(a===w){var b=this[0];if(b){if(c.nodeName(b,"option"))return(b.attributes.value||{}).specified?b.value:b.text;if(c.nodeName(b,"select")){var d=b.selectedIndex,f=[],e=b.options;b=b.type==="select-one";if(d<0)return null;var j=b?d:0;for(d=b?d+1:e.length;j< [...]
+e[j];if(i.selected){a=c(i).val();if(b)return a;f.push(a)}}return f}if(Ba.test(b.type)&&!c.support.checkOn)return b.getAttribute("value")===null?"on":b.value;return(b.value||"").replace(Za,"")}return w}var o=c.isFunction(a);return this.each(function(k){var n=c(this),r=a;if(this.nodeType===1){if(o)r=a.call(this,k,n.val());if(typeof r==="number")r+="";if(c.isArray(r)&&Ba.test(this.type))this.checked=c.inArray(n.val(),r)>=0;else if(c.nodeName(this,"select")){var u=c.makeArray(r);c("option",t [...]
+c.inArray(c(this).val(),u)>=0});if(!u.length)this.selectedIndex=-1}else this.value=r}})}});c.extend({attrFn:{val:true,css:true,html:true,text:true,data:true,width:true,height:true,offset:true},attr:function(a,b,d,f){if(!a||a.nodeType===3||a.nodeType===8)return w;if(f&&b in c.attrFn)return c(a)[b](d);f=a.nodeType!==1||!c.isXMLDoc(a);var e=d!==w;b=f&&c.props[b]||b;if(a.nodeType===1){var j=$a.test(b);if(b in a&&f&&!j){if(e){b==="type"&&ab.test(a.nodeName)&&a.parentNode&&c.error("type proper [...]
+a[b]=d}if(c.nodeName(a,"form")&&a.getAttributeNode(b))return a.getAttributeNode(b).nodeValue;if(b==="tabIndex")return(b=a.getAttributeNode("tabIndex"))&&b.specified?b.value:bb.test(a.nodeName)||cb.test(a.nodeName)&&a.href?0:w;return a[b]}if(!c.support.style&&f&&b==="style"){if(e)a.style.cssText=""+d;return a.style.cssText}e&&a.setAttribute(b,""+d);a=!c.support.hrefNormalized&&f&&j?a.getAttribute(b,2):a.getAttribute(b);return a===null?w:a}return c.style(a,b,d)}});var O=/\.(.*)$/,db=functi [...]
+function(b){return"\\"+b})};c.event={add:function(a,b,d,f){if(!(a.nodeType===3||a.nodeType===8)){if(a.setInterval&&a!==A&&!a.frameElement)a=A;var e,j;if(d.handler){e=d;d=e.handler}if(!d.guid)d.guid=c.guid++;if(j=c.data(a)){var i=j.events=j.events||{},o=j.handle;if(!o)j.handle=o=function(){return typeof c!=="undefined"&&!c.event.triggered?c.event.handle.apply(o.elem,arguments):w};o.elem=a;b=b.split(" ");for(var k,n=0,r;k=b[n++];){j=e?c.extend({},e):{handler:d,data:f};if(k.indexOf(".")>-1) [...]
+k=r.shift();j.namespace=r.slice(0).sort().join(".")}else{r=[];j.namespace=""}j.type=k;j.guid=d.guid;var u=i[k],z=c.event.special[k]||{};if(!u){u=i[k]=[];if(!z.setup||z.setup.call(a,f,r,o)===false)if(a.addEventListener)a.addEventListener(k,o,false);else a.attachEvent&&a.attachEvent("on"+k,o)}if(z.add){z.add.call(a,j);if(!j.handler.guid)j.handler.guid=d.guid}u.push(j);c.event.global[k]=true}a=null}}},global:{},remove:function(a,b,d,f){if(!(a.nodeType===3||a.nodeType===8)){var e,j=0,i,o,k,n [...]
+C=z&&z.events;if(z&&C){if(b&&b.type){d=b.handler;b=b.type}if(!b||typeof b==="string"&&b.charAt(0)==="."){b=b||"";for(e in C)c.event.remove(a,e+b)}else{for(b=b.split(" ");e=b[j++];){n=e;i=e.indexOf(".")<0;o=[];if(!i){o=e.split(".");e=o.shift();k=new RegExp("(^|\\.)"+c.map(o.slice(0).sort(),db).join("\\.(?:.*\\.)?")+"(\\.|$)")}if(r=C[e])if(d){n=c.event.special[e]||{};for(B=f||0;B<r.length;B++){u=r[B];if(d.guid===u.guid){if(i||k.test(u.namespace)){f==null&&r.splice(B--,1);n.remove&&n.remove [...]
+null)break}}if(r.length===0||f!=null&&r.length===1){if(!n.teardown||n.teardown.call(a,o)===false)Ca(a,e,z.handle);delete C[e]}}else for(var B=0;B<r.length;B++){u=r[B];if(i||k.test(u.namespace)){c.event.remove(a,n,u.handler,B);r.splice(B--,1)}}}if(c.isEmptyObject(C)){if(b=z.handle)b.elem=null;delete z.events;delete z.handle;c.isEmptyObject(z)&&c.removeData(a)}}}}},trigger:function(a,b,d,f){var e=a.type||a;if(!f){a=typeof a==="object"?a[G]?a:c.extend(c.Event(e),a):c.Event(e);if(e.indexOf(" [...]
+e=e.slice(0,-1);a.exclusive=true}if(!d){a.stopPropagation();c.event.global[e]&&c.each(c.cache,function(){this.events&&this.events[e]&&c.event.trigger(a,b,this.handle.elem)})}if(!d||d.nodeType===3||d.nodeType===8)return w;a.result=w;a.target=d;b=c.makeArray(b);b.unshift(a)}a.currentTarget=d;(f=c.data(d,"handle"))&&f.apply(d,b);f=d.parentNode||d.ownerDocument;try{if(!(d&&d.nodeName&&c.noData[d.nodeName.toLowerCase()]))if(d["on"+e]&&d["on"+e].apply(d,b)===false)a.result=false}catch(j){}if(! [...]
+f)c.event.trigger(a,b,f,true);else if(!a.isDefaultPrevented()){f=a.target;var i,o=c.nodeName(f,"a")&&e==="click",k=c.event.special[e]||{};if((!k._default||k._default.call(d,a)===false)&&!o&&!(f&&f.nodeName&&c.noData[f.nodeName.toLowerCase()])){try{if(f[e]){if(i=f["on"+e])f["on"+e]=null;c.event.triggered=true;f[e]()}}catch(n){}if(i)f["on"+e]=i;c.event.triggered=false}}},handle:function(a){var b,d,f,e;a=arguments[0]=c.event.fix(a||A.event);a.currentTarget=this;b=a.type.indexOf(".")<0&&!a.e [...]
+if(!b){d=a.type.split(".");a.type=d.shift();f=new RegExp("(^|\\.)"+d.slice(0).sort().join("\\.(?:.*\\.)?")+"(\\.|$)")}e=c.data(this,"events");d=e[a.type];if(e&&d){d=d.slice(0);e=0;for(var j=d.length;e<j;e++){var i=d[e];if(b||f.test(i.namespace)){a.handler=i.handler;a.data=i.data;a.handleObj=i;i=i.handler.apply(this,arguments);if(i!==w){a.result=i;if(i===false){a.preventDefault();a.stopPropagation()}}if(a.isImmediatePropagationStopped())break}}}return a.result},props:"altKey attrChange at [...]
+fix:function(a){if(a[G])return a;var b=a;a=c.Event(b);for(var d=this.props.length,f;d;){f=this.props[--d];a[f]=b[f]}if(!a.target)a.target=a.srcElement||s;if(a.target.nodeType===3)a.target=a.target.parentNode;if(!a.relatedTarget&&a.fromElement)a.relatedTarget=a.fromElement===a.target?a.toElement:a.fromElement;if(a.pageX==null&&a.clientX!=null){b=s.documentElement;d=s.body;a.pageX=a.clientX+(b&&b.scrollLeft||d&&d.scrollLeft||0)-(b&&b.clientLeft||d&&d.clientLeft||0);a.pageY=a.clientY+(b&&b. [...]
+d&&d.scrollTop||0)-(b&&b.clientTop||d&&d.clientTop||0)}if(!a.which&&(a.charCode||a.charCode===0?a.charCode:a.keyCode))a.which=a.charCode||a.keyCode;if(!a.metaKey&&a.ctrlKey)a.metaKey=a.ctrlKey;if(!a.which&&a.button!==w)a.which=a.button&1?1:a.button&2?3:a.button&4?2:0;return a},guid:1E8,proxy:c.proxy,special:{ready:{setup:c.bindReady,teardown:c.noop},live:{add:function(a){c.event.add(this,a.origType,c.extend({},a,{handler:oa}))},remove:function(a){var b=true,d=a.origType.replace(O,"");c.e [...]
+"events").live||[],function(){if(d===this.origType.replace(O,""))return b=false});b&&c.event.remove(this,a.origType,oa)}},beforeunload:{setup:function(a,b,d){if(this.setInterval)this.onbeforeunload=d;return false},teardown:function(a,b){if(this.onbeforeunload===b)this.onbeforeunload=null}}}};var Ca=s.removeEventListener?function(a,b,d){a.removeEventListener(b,d,false)}:function(a,b,d){a.detachEvent("on"+b,d)};c.Event=function(a){if(!this.preventDefault)return new c.Event(a);if(a&&a.type) [...]
+a;this.type=a.type}else this.type=a;this.timeStamp=J();this[G]=true};c.Event.prototype={preventDefault:function(){this.isDefaultPrevented=Z;var a=this.originalEvent;if(a){a.preventDefault&&a.preventDefault();a.returnValue=false}},stopPropagation:function(){this.isPropagationStopped=Z;var a=this.originalEvent;if(a){a.stopPropagation&&a.stopPropagation();a.cancelBubble=true}},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=Z;this.stopPropagation()},isDefaultPrevented [...]
+isImmediatePropagationStopped:Y};var Da=function(a){var b=a.relatedTarget;try{for(;b&&b!==this;)b=b.parentNode;if(b!==this){a.type=a.data;c.event.handle.apply(this,arguments)}}catch(d){}},Ea=function(a){a.type=a.data;c.event.handle.apply(this,arguments)};c.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){c.event.special[a]={setup:function(d){c.event.add(this,b,d&&d.selector?Ea:Da,a)},teardown:function(d){c.event.remove(this,b,d&&d.selector?Ea:Da)}}});if(!c.support.submit [...]
+{setup:function(){if(this.nodeName.toLowerCase()!=="form"){c.event.add(this,"click.specialSubmit",function(a){var b=a.target,d=b.type;if((d==="submit"||d==="image")&&c(b).closest("form").length)return na("submit",this,arguments)});c.event.add(this,"keypress.specialSubmit",function(a){var b=a.target,d=b.type;if((d==="text"||d==="password")&&c(b).closest("form").length&&a.keyCode===13)return na("submit",this,arguments)})}else return false},teardown:function(){c.event.remove(this,".specialS [...]
+if(!c.support.changeBubbles){var da=/textarea|input|select/i,ea,Fa=function(a){var b=a.type,d=a.value;if(b==="radio"||b==="checkbox")d=a.checked;else if(b==="select-multiple")d=a.selectedIndex>-1?c.map(a.options,function(f){return f.selected}).join("-"):"";else if(a.nodeName.toLowerCase()==="select")d=a.selectedIndex;return d},fa=function(a,b){var d=a.target,f,e;if(!(!da.test(d.nodeName)||d.readOnly)){f=c.data(d,"_change_data");e=Fa(d);if(a.type!=="focusout"||d.type!=="radio")c.data(d,"_ [...]
+e);if(!(f===w||e===f))if(f!=null||e){a.type="change";return c.event.trigger(a,b,d)}}};c.event.special.change={filters:{focusout:fa,click:function(a){var b=a.target,d=b.type;if(d==="radio"||d==="checkbox"||b.nodeName.toLowerCase()==="select")return fa.call(this,a)},keydown:function(a){var b=a.target,d=b.type;if(a.keyCode===13&&b.nodeName.toLowerCase()!=="textarea"||a.keyCode===32&&(d==="checkbox"||d==="radio")||d==="select-multiple")return fa.call(this,a)},beforeactivate:function(a){a=a.t [...]
+"_change_data",Fa(a))}},setup:function(){if(this.type==="file")return false;for(var a in ea)c.event.add(this,a+".specialChange",ea[a]);return da.test(this.nodeName)},teardown:function(){c.event.remove(this,".specialChange");return da.test(this.nodeName)}};ea=c.event.special.change.filters}s.addEventListener&&c.each({focus:"focusin",blur:"focusout"},function(a,b){function d(f){f=c.event.fix(f);f.type=b;return c.event.handle.call(this,f)}c.event.special[b]={setup:function(){this.addEventLi [...]
+d,true)},teardown:function(){this.removeEventListener(a,d,true)}}});c.each(["bind","one"],function(a,b){c.fn[b]=function(d,f,e){if(typeof d==="object"){for(var j in d)this[b](j,f,d[j],e);return this}if(c.isFunction(f)){e=f;f=w}var i=b==="one"?c.proxy(e,function(k){c(this).unbind(k,i);return e.apply(this,arguments)}):e;if(d==="unload"&&b!=="one")this.one(d,f,e);else{j=0;for(var o=this.length;j<o;j++)c.event.add(this[j],d,i,f)}return this}});c.fn.extend({unbind:function(a,b){if(typeof a=== [...]
+!a.preventDefault)for(var d in a)this.unbind(d,a[d]);else{d=0;for(var f=this.length;d<f;d++)c.event.remove(this[d],a,b)}return this},delegate:function(a,b,d,f){return this.live(b,d,f,a)},undelegate:function(a,b,d){return arguments.length===0?this.unbind("live"):this.die(b,null,d,a)},trigger:function(a,b){return this.each(function(){c.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0]){a=c.Event(a);a.preventDefault();a.stopPropagation();c.event.trigger(a,b,this[0]);return  [...]
+toggle:function(a){for(var b=arguments,d=1;d<b.length;)c.proxy(a,b[d++]);return this.click(c.proxy(a,function(f){var e=(c.data(this,"lastToggle"+a.guid)||0)%d;c.data(this,"lastToggle"+a.guid,e+1);f.preventDefault();return b[e].apply(this,arguments)||false}))},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}});var Ga={focus:"focusin",blur:"focusout",mouseenter:"mouseover",mouseleave:"mouseout"};c.each(["live","die"],function(a,b){c.fn[b]=function(d,f,e,j){var i,o=0,k,n,r=j| [...]
+u=j?this:c(this.context);if(c.isFunction(f)){e=f;f=w}for(d=(d||"").split(" ");(i=d[o++])!=null;){j=O.exec(i);k="";if(j){k=j[0];i=i.replace(O,"")}if(i==="hover")d.push("mouseenter"+k,"mouseleave"+k);else{n=i;if(i==="focus"||i==="blur"){d.push(Ga[i]+k);i+=k}else i=(Ga[i]||i)+k;b==="live"?u.each(function(){c.event.add(this,pa(i,r),{data:f,selector:r,handler:e,origType:i,origHandler:e,preType:n})}):u.unbind(pa(i,r),e)}}return this}});c.each("blur focus focusin focusout load resize scroll unl [...]
+function(a,b){c.fn[b]=function(d){return d?this.bind(b,d):this.trigger(b)};if(c.attrFn)c.attrFn[b]=true});A.attachEvent&&!A.addEventListener&&A.attachEvent("onunload",function(){for(var a in c.cache)if(c.cache[a].handle)try{c.event.remove(c.cache[a].handle.elem)}catch(b){}});(function(){function a(g){for(var h="",l,m=0;g[m];m++){l=g[m];if(l.nodeType===3||l.nodeType===4)h+=l.nodeValue;else if(l.nodeType!==8)h+=a(l.childNodes)}return h}function b(g,h,l,m,q,p){q=0;for(var v=m.length;q<v;q++ [...]
+if(t){t=t[g];for(var y=false;t;){if(t.sizcache===l){y=m[t.sizset];break}if(t.nodeType===1&&!p){t.sizcache=l;t.sizset=q}if(t.nodeName.toLowerCase()===h){y=t;break}t=t[g]}m[q]=y}}}function d(g,h,l,m,q,p){q=0;for(var v=m.length;q<v;q++){var t=m[q];if(t){t=t[g];for(var y=false;t;){if(t.sizcache===l){y=m[t.sizset];break}if(t.nodeType===1){if(!p){t.sizcache=l;t.sizset=q}if(typeof h!=="string"){if(t===h){y=true;break}}else if(k.filter(h,[t]).length>0){y=t;break}}t=t[g]}m[q]=y}}}var f=/((?:\((?: [...]
+e=0,j=Object.prototype.toString,i=false,o=true;[0,0].sort(function(){o=false;return 0});var k=function(g,h,l,m){l=l||[];var q=h=h||s;if(h.nodeType!==1&&h.nodeType!==9)return[];if(!g||typeof g!=="string")return l;for(var p=[],v,t,y,S,H=true,M=x(h),I=g;(f.exec(""),v=f.exec(I))!==null;){I=v[3];p.push(v[1]);if(v[2]){S=v[3];break}}if(p.length>1&&r.exec(g))if(p.length===2&&n.relative[p[0]])t=ga(p[0]+p[1],h);else for(t=n.relative[p[0]]?[h]:k(p.shift(),h);p.length;){g=p.shift();if(n.relative[g]) [...]
+t=ga(g,t)}else{if(!m&&p.length>1&&h.nodeType===9&&!M&&n.match.ID.test(p[0])&&!n.match.ID.test(p[p.length-1])){v=k.find(p.shift(),h,M);h=v.expr?k.filter(v.expr,v.set)[0]:v.set[0]}if(h){v=m?{expr:p.pop(),set:z(m)}:k.find(p.pop(),p.length===1&&(p[0]==="~"||p[0]==="+")&&h.parentNode?h.parentNode:h,M);t=v.expr?k.filter(v.expr,v.set):v.set;if(p.length>0)y=z(t);else H=false;for(;p.length;){var D=p.pop();v=D;if(n.relative[D])v=p.pop();else D="";if(v==null)v=h;n.relative[D](y,v,M)}}else y=[]}y||( [...]
+g);if(j.call(y)==="[object Array]")if(H)if(h&&h.nodeType===1)for(g=0;y[g]!=null;g++){if(y[g]&&(y[g]===true||y[g].nodeType===1&&E(h,y[g])))l.push(t[g])}else for(g=0;y[g]!=null;g++)y[g]&&y[g].nodeType===1&&l.push(t[g]);else l.push.apply(l,y);else z(y,l);if(S){k(S,q,l,m);k.uniqueSort(l)}return l};k.uniqueSort=function(g){if(B){i=o;g.sort(B);if(i)for(var h=1;h<g.length;h++)g[h]===g[h-1]&&g.splice(h--,1)}return g};k.matches=function(g,h){return k(g,null,null,h)};k.find=function(g,h,l){var m,q [...]
+for(var p=0,v=n.order.length;p<v;p++){var t=n.order[p];if(q=n.leftMatch[t].exec(g)){var y=q[1];q.splice(1,1);if(y.substr(y.length-1)!=="\\"){q[1]=(q[1]||"").replace(/\\/g,"");m=n.find[t](q,h,l);if(m!=null){g=g.replace(n.match[t],"");break}}}}m||(m=h.getElementsByTagName("*"));return{set:m,expr:g}};k.filter=function(g,h,l,m){for(var q=g,p=[],v=h,t,y,S=h&&h[0]&&x(h[0]);g&&h.length;){for(var H in n.filter)if((t=n.leftMatch[H].exec(g))!=null&&t[2]){var M=n.filter[H],I,D;D=t[1];y=false;t.spli [...]
+1)!=="\\"){if(v===p)p=[];if(n.preFilter[H])if(t=n.preFilter[H](t,v,l,p,m,S)){if(t===true)continue}else y=I=true;if(t)for(var U=0;(D=v[U])!=null;U++)if(D){I=M(D,t,U,v);var Ha=m^!!I;if(l&&I!=null)if(Ha)y=true;else v[U]=false;else if(Ha){p.push(D);y=true}}if(I!==w){l||(v=p);g=g.replace(n.match[H],"");if(!y)return[];break}}}if(g===q)if(y==null)k.error(g);else break;q=g}return v};k.error=function(g){throw"Syntax error, unrecognized expression: "+g;};var n=k.selectors={order:["ID","NAME","TAG" [...]
+CLASS:/\.((?:[\w\u00c0-\uFFFF-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attr [...]
+relative:{"+":function(g,h){var l=typeof h==="string",m=l&&!/\W/.test(h);l=l&&!m;if(m)h=h.toLowerCase();m=0;for(var q=g.length,p;m<q;m++)if(p=g[m]){for(;(p=p.previousSibling)&&p.nodeType!==1;);g[m]=l||p&&p.nodeName.toLowerCase()===h?p||false:p===h}l&&k.filter(h,g,true)},">":function(g,h){var l=typeof h==="string";if(l&&!/\W/.test(h)){h=h.toLowerCase();for(var m=0,q=g.length;m<q;m++){var p=g[m];if(p){l=p.parentNode;g[m]=l.nodeName.toLowerCase()===h?l:false}}}else{m=0;for(q=g.length;m<q;m+ [...]
+l?p.parentNode:p.parentNode===h;l&&k.filter(h,g,true)}},"":function(g,h,l){var m=e++,q=d;if(typeof h==="string"&&!/\W/.test(h)){var p=h=h.toLowerCase();q=b}q("parentNode",h,m,g,p,l)},"~":function(g,h,l){var m=e++,q=d;if(typeof h==="string"&&!/\W/.test(h)){var p=h=h.toLowerCase();q=b}q("previousSibling",h,m,g,p,l)}},find:{ID:function(g,h,l){if(typeof h.getElementById!=="undefined"&&!l)return(g=h.getElementById(g[1]))?[g]:[]},NAME:function(g,h){if(typeof h.getElementsByName!=="undefined"){ [...]
+h=h.getElementsByName(g[1]);for(var m=0,q=h.length;m<q;m++)h[m].getAttribute("name")===g[1]&&l.push(h[m]);return l.length===0?null:l}},TAG:function(g,h){return h.getElementsByTagName(g[1])}},preFilter:{CLASS:function(g,h,l,m,q,p){g=" "+g[1].replace(/\\/g,"")+" ";if(p)return g;p=0;for(var v;(v=h[p])!=null;p++)if(v)if(q^(v.className&&(" "+v.className+" ").replace(/[\t\n]/g," ").indexOf(g)>=0))l||m.push(v);else if(l)h[p]=false;return false},ID:function(g){return g[1].replace(/\\/g,"")},TAG: [...]
+CHILD:function(g){if(g[1]==="nth"){var h=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(g[2]==="even"&&"2n"||g[2]==="odd"&&"2n+1"||!/\D/.test(g[2])&&"0n+"+g[2]||g[2]);g[2]=h[1]+(h[2]||1)-0;g[3]=h[3]-0}g[0]=e++;return g},ATTR:function(g,h,l,m,q,p){h=g[1].replace(/\\/g,"");if(!p&&n.attrMap[h])g[1]=n.attrMap[h];if(g[2]==="~=")g[4]=" "+g[4]+" ";return g},PSEUDO:function(g,h,l,m,q){if(g[1]==="not")if((f.exec(g[3])||"").length>1||/^\w/.test(g[3]))g[3]=k(g[3],null,null,h);else{g=k.filter(g[3],h,l,true^q);l||m [...]
+g);return false}else if(n.match.POS.test(g[0])||n.match.CHILD.test(g[0]))return true;return g},POS:function(g){g.unshift(true);return g}},filters:{enabled:function(g){return g.disabled===false&&g.type!=="hidden"},disabled:function(g){return g.disabled===true},checked:function(g){return g.checked===true},selected:function(g){return g.selected===true},parent:function(g){return!!g.firstChild},empty:function(g){return!g.firstChild},has:function(g,h,l){return!!k(l[3],g).length},header:functio [...]
+text:function(g){return"text"===g.type},radio:function(g){return"radio"===g.type},checkbox:function(g){return"checkbox"===g.type},file:function(g){return"file"===g.type},password:function(g){return"password"===g.type},submit:function(g){return"submit"===g.type},image:function(g){return"image"===g.type},reset:function(g){return"reset"===g.type},button:function(g){return"button"===g.type||g.nodeName.toLowerCase()==="button"},input:function(g){return/input|select|textarea|button/i.test(g.no [...]
+setFilters:{first:function(g,h){return h===0},last:function(g,h,l,m){return h===m.length-1},even:function(g,h){return h%2===0},odd:function(g,h){return h%2===1},lt:function(g,h,l){return h<l[3]-0},gt:function(g,h,l){return h>l[3]-0},nth:function(g,h,l){return l[3]-0===h},eq:function(g,h,l){return l[3]-0===h}},filter:{PSEUDO:function(g,h,l,m){var q=h[1],p=n.filters[q];if(p)return p(g,l,h,m);else if(q==="contains")return(g.textContent||g.innerText||a([g])||"").indexOf(h[3])>=0;else if(q=== [...]
+h[3];l=0;for(m=h.length;l<m;l++)if(h[l]===g)return false;return true}else k.error("Syntax error, unrecognized expression: "+q)},CHILD:function(g,h){var l=h[1],m=g;switch(l){case "only":case "first":for(;m=m.previousSibling;)if(m.nodeType===1)return false;if(l==="first")return true;m=g;case "last":for(;m=m.nextSibling;)if(m.nodeType===1)return false;return true;case "nth":l=h[2];var q=h[3];if(l===1&&q===0)return true;h=h[0];var p=g.parentNode;if(p&&(p.sizcache!==h||!g.nodeIndex)){var v=0; [...]
+m.nextSibling)if(m.nodeType===1)m.nodeIndex=++v;p.sizcache=h}g=g.nodeIndex-q;return l===0?g===0:g%l===0&&g/l>=0}},ID:function(g,h){return g.nodeType===1&&g.getAttribute("id")===h},TAG:function(g,h){return h==="*"&&g.nodeType===1||g.nodeName.toLowerCase()===h},CLASS:function(g,h){return(" "+(g.className||g.getAttribute("class"))+" ").indexOf(h)>-1},ATTR:function(g,h){var l=h[1];g=n.attrHandle[l]?n.attrHandle[l](g):g[l]!=null?g[l]:g.getAttribute(l);l=g+"";var m=h[2];h=h[4];return g==null?m [...]
+"="?l===h:m==="*="?l.indexOf(h)>=0:m==="~="?(" "+l+" ").indexOf(h)>=0:!h?l&&g!==false:m==="!="?l!==h:m==="^="?l.indexOf(h)===0:m==="$="?l.substr(l.length-h.length)===h:m==="|="?l===h||l.substr(0,h.length+1)===h+"-":false},POS:function(g,h,l,m){var q=n.setFilters[h[2]];if(q)return q(g,l,h,m)}}},r=n.match.POS;for(var u in n.match){n.match[u]=new RegExp(n.match[u].source+/(?![^\[]*\])(?![^\(]*\))/.source);n.leftMatch[u]=new RegExp(/(^(?:.|\r|\n)*?)/.source+n.match[u].source.replace(/\\(\d+) [...]
+h){return"\\"+(h-0+1)}))}var z=function(g,h){g=Array.prototype.slice.call(g,0);if(h){h.push.apply(h,g);return h}return g};try{Array.prototype.slice.call(s.documentElement.childNodes,0)}catch(C){z=function(g,h){h=h||[];if(j.call(g)==="[object Array]")Array.prototype.push.apply(h,g);else if(typeof g.length==="number")for(var l=0,m=g.length;l<m;l++)h.push(g[l]);else for(l=0;g[l];l++)h.push(g[l]);return h}}var B;if(s.documentElement.compareDocumentPosition)B=function(g,h){if(!g.compareDocume [...]
+!h.compareDocumentPosition){if(g==h)i=true;return g.compareDocumentPosition?-1:1}g=g.compareDocumentPosition(h)&4?-1:g===h?0:1;if(g===0)i=true;return g};else if("sourceIndex"in s.documentElement)B=function(g,h){if(!g.sourceIndex||!h.sourceIndex){if(g==h)i=true;return g.sourceIndex?-1:1}g=g.sourceIndex-h.sourceIndex;if(g===0)i=true;return g};else if(s.createRange)B=function(g,h){if(!g.ownerDocument||!h.ownerDocument){if(g==h)i=true;return g.ownerDocument?-1:1}var l=g.ownerDocument.createR [...]
+h.ownerDocument.createRange();l.setStart(g,0);l.setEnd(g,0);m.setStart(h,0);m.setEnd(h,0);g=l.compareBoundaryPoints(Range.START_TO_END,m);if(g===0)i=true;return g};(function(){var g=s.createElement("div"),h="script"+(new Date).getTime();g.innerHTML="<a name='"+h+"'/>";var l=s.documentElement;l.insertBefore(g,l.firstChild);if(s.getElementById(h)){n.find.ID=function(m,q,p){if(typeof q.getElementById!=="undefined"&&!p)return(q=q.getElementById(m[1]))?q.id===m[1]||typeof q.getAttributeNode!= [...]
+q.getAttributeNode("id").nodeValue===m[1]?[q]:w:[]};n.filter.ID=function(m,q){var p=typeof m.getAttributeNode!=="undefined"&&m.getAttributeNode("id");return m.nodeType===1&&p&&p.nodeValue===q}}l.removeChild(g);l=g=null})();(function(){var g=s.createElement("div");g.appendChild(s.createComment(""));if(g.getElementsByTagName("*").length>0)n.find.TAG=function(h,l){l=l.getElementsByTagName(h[1]);if(h[1]==="*"){h=[];for(var m=0;l[m];m++)l[m].nodeType===1&&h.push(l[m]);l=h}return l};g.innerHTM [...]
+if(g.firstChild&&typeof g.firstChild.getAttribute!=="undefined"&&g.firstChild.getAttribute("href")!=="#")n.attrHandle.href=function(h){return h.getAttribute("href",2)};g=null})();s.querySelectorAll&&function(){var g=k,h=s.createElement("div");h.innerHTML="<p class='TEST'></p>";if(!(h.querySelectorAll&&h.querySelectorAll(".TEST").length===0)){k=function(m,q,p,v){q=q||s;if(!v&&q.nodeType===9&&!x(q))try{return z(q.querySelectorAll(m),p)}catch(t){}return g(m,q,p,v)};for(var l in g)k[l]=g[l]; [...]
+(function(){var g=s.createElement("div");g.innerHTML="<div class='test e'></div><div class='test'></div>";if(!(!g.getElementsByClassName||g.getElementsByClassName("e").length===0)){g.lastChild.className="e";if(g.getElementsByClassName("e").length!==1){n.order.splice(1,0,"CLASS");n.find.CLASS=function(h,l,m){if(typeof l.getElementsByClassName!=="undefined"&&!m)return l.getElementsByClassName(h[1])};g=null}}})();var E=s.compareDocumentPosition?function(g,h){return!!(g.compareDocumentPositi [...]
+function(g,h){return g!==h&&(g.contains?g.contains(h):true)},x=function(g){return(g=(g?g.ownerDocument||g:0).documentElement)?g.nodeName!=="HTML":false},ga=function(g,h){var l=[],m="",q;for(h=h.nodeType?[h]:h;q=n.match.PSEUDO.exec(g);){m+=q[0];g=g.replace(n.match.PSEUDO,"")}g=n.relative[g]?g+"*":g;q=0;for(var p=h.length;q<p;q++)k(g,h[q],l);return k.filter(m,l)};c.find=k;c.expr=k.selectors;c.expr[":"]=c.expr.filters;c.unique=k.uniqueSort;c.text=a;c.isXMLDoc=x;c.contains=E})();var eb=/Unti [...]
+gb=/,/;R=Array.prototype.slice;var Ia=function(a,b,d){if(c.isFunction(b))return c.grep(a,function(e,j){return!!b.call(e,j,e)===d});else if(b.nodeType)return c.grep(a,function(e){return e===b===d});else if(typeof b==="string"){var f=c.grep(a,function(e){return e.nodeType===1});if(Ua.test(b))return c.filter(b,f,!d);else b=c.filter(b,f)}return c.grep(a,function(e){return c.inArray(e,b)>=0===d})};c.fn.extend({find:function(a){for(var b=this.pushStack("","find",a),d=0,f=0,e=this.length;f<e;f+ [...]
+c.find(a,this[f],b);if(f>0)for(var j=d;j<b.length;j++)for(var i=0;i<d;i++)if(b[i]===b[j]){b.splice(j--,1);break}}return b},has:function(a){var b=c(a);return this.filter(function(){for(var d=0,f=b.length;d<f;d++)if(c.contains(this,b[d]))return true})},not:function(a){return this.pushStack(Ia(this,a,false),"not",a)},filter:function(a){return this.pushStack(Ia(this,a,true),"filter",a)},is:function(a){return!!a&&c.filter(a,this).length>0},closest:function(a,b){if(c.isArray(a)){var d=[],f=thi [...]
+{},i;if(f&&a.length){e=0;for(var o=a.length;e<o;e++){i=a[e];j[i]||(j[i]=c.expr.match.POS.test(i)?c(i,b||this.context):i)}for(;f&&f.ownerDocument&&f!==b;){for(i in j){e=j[i];if(e.jquery?e.index(f)>-1:c(f).is(e)){d.push({selector:i,elem:f});delete j[i]}}f=f.parentNode}}return d}var k=c.expr.match.POS.test(a)?c(a,b||this.context):null;return this.map(function(n,r){for(;r&&r.ownerDocument&&r!==b;){if(k?k.index(r)>-1:c(r).is(a))return r;r=r.parentNode}return null})},index:function(a){if(!a||t [...]
+"string")return c.inArray(this[0],a?c(a):this.parent().children());return c.inArray(a.jquery?a[0]:a,this)},add:function(a,b){a=typeof a==="string"?c(a,b||this.context):c.makeArray(a);b=c.merge(this.get(),a);return this.pushStack(qa(a[0])||qa(b[0])?b:c.unique(b))},andSelf:function(){return this.add(this.prevObject)}});c.each({parent:function(a){return(a=a.parentNode)&&a.nodeType!==11?a:null},parents:function(a){return c.dir(a,"parentNode")},parentsUntil:function(a,b,d){return c.dir(a,"par [...]
+d)},next:function(a){return c.nth(a,2,"nextSibling")},prev:function(a){return c.nth(a,2,"previousSibling")},nextAll:function(a){return c.dir(a,"nextSibling")},prevAll:function(a){return c.dir(a,"previousSibling")},nextUntil:function(a,b,d){return c.dir(a,"nextSibling",d)},prevUntil:function(a,b,d){return c.dir(a,"previousSibling",d)},siblings:function(a){return c.sibling(a.parentNode.firstChild,a)},children:function(a){return c.sibling(a.firstChild)},contents:function(a){return c.nodeNam [...]
+a.contentDocument||a.contentWindow.document:c.makeArray(a.childNodes)}},function(a,b){c.fn[a]=function(d,f){var e=c.map(this,b,d);eb.test(a)||(f=d);if(f&&typeof f==="string")e=c.filter(f,e);e=this.length>1?c.unique(e):e;if((this.length>1||gb.test(f))&&fb.test(a))e=e.reverse();return this.pushStack(e,a,R.call(arguments).join(","))}});c.extend({filter:function(a,b,d){if(d)a=":not("+a+")";return c.find.matches(a,b)},dir:function(a,b,d){var f=[];for(a=a[b];a&&a.nodeType!==9&&(d===w||a.nodeTy [...]
+1&&f.push(a);a=a[b]}return f},nth:function(a,b,d){b=b||1;for(var f=0;a;a=a[d])if(a.nodeType===1&&++f===b)break;return a},sibling:function(a,b){for(var d=[];a;a=a.nextSibling)a.nodeType===1&&a!==b&&d.push(a);return d}});var Ja=/ jQuery\d+="(?:\d+|null)"/g,V=/^\s+/,Ka=/(<([\w:]+)[^>]*?)\/>/g,hb=/^(?:area|br|col|embed|hr|img|input|link|meta|param)$/i,La=/<([\w:]+)/,ib=/<tbody/i,jb=/<|&#?\w+;/,ta=/<script|<object|<embed|<option|<style/i,ua=/checked\s*(?:[^=]|=\s*.checked.)/i,Ma=function(a,b, [...]
+a:b+"></"+d+">"},F={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]};F.optgroup=F.option;F.tbody=F.tfoot=F.colgroup=F.caption=F.thead;F.th=F.td;if(!c.support.htmlSerialize)F._default=[1,"div<div>","</div>"];c.fn. [...]
+c(this);d.text(a.call(this,b,d.text()))});if(typeof a!=="object"&&a!==w)return this.empty().append((this[0]&&this[0].ownerDocument||s).createTextNode(a));return c.text(this)},wrapAll:function(a){if(c.isFunction(a))return this.each(function(d){c(this).wrapAll(a.call(this,d))});if(this[0]){var b=c(a,this[0].ownerDocument).eq(0).clone(true);this[0].parentNode&&b.insertBefore(this[0]);b.map(function(){for(var d=this;d.firstChild&&d.firstChild.nodeType===1;)d=d.firstChild;return d}).append(th [...]
+wrapInner:function(a){if(c.isFunction(a))return this.each(function(b){c(this).wrapInner(a.call(this,b))});return this.each(function(){var b=c(this),d=b.contents();d.length?d.wrapAll(a):b.append(a)})},wrap:function(a){return this.each(function(){c(this).wrapAll(a)})},unwrap:function(){return this.parent().each(function(){c.nodeName(this,"body")||c(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.appendChi [...]
+prepend:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,false,function(b){this.parentNode.insertBefore(b,this)});else if(arguments.length){var a=c(arguments[0]);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,false,function(b){this.pa [...]
+this.nextSibling)});else if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,c(arguments[0]).toArray());return a}},remove:function(a,b){for(var d=0,f;(f=this[d])!=null;d++)if(!a||c.filter(a,[f]).length){if(!b&&f.nodeType===1){c.cleanData(f.getElementsByTagName("*"));c.cleanData([f])}f.parentNode&&f.parentNode.removeChild(f)}return this},empty:function(){for(var a=0,b;(b=this[a])!=null;a++)for(b.nodeType===1&&c.cleanData(b.getElementsByTagName("*"));b.firstChi [...]
+return this},clone:function(a){var b=this.map(function(){if(!c.support.noCloneEvent&&!c.isXMLDoc(this)){var d=this.outerHTML,f=this.ownerDocument;if(!d){d=f.createElement("div");d.appendChild(this.cloneNode(true));d=d.innerHTML}return c.clean([d.replace(Ja,"").replace(/=([^="'>\s]+\/)>/g,'="$1">').replace(V,"")],f)[0]}else return this.cloneNode(true)});if(a===true){ra(this,b);ra(this.find("*"),b.find("*"))}return b},html:function(a){if(a===w)return this[0]&&this[0].nodeType===1?this[0].i [...]
+""):null;else if(typeof a==="string"&&!ta.test(a)&&(c.support.leadingWhitespace||!V.test(a))&&!F[(La.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Ka,Ma);try{for(var b=0,d=this.length;b<d;b++)if(this[b].nodeType===1){c.cleanData(this[b].getElementsByTagName("*"));this[b].innerHTML=a}}catch(f){this.empty().append(a)}}else c.isFunction(a)?this.each(function(e){var j=c(this),i=j.html();j.empty().append(function(){return a.call(this,e,i)})}):this.empty().append(a);return this},replaceWith [...]
+this[0].parentNode){if(c.isFunction(a))return this.each(function(b){var d=c(this),f=d.html();d.replaceWith(a.call(this,b,f))});if(typeof a!=="string")a=c(a).detach();return this.each(function(){var b=this.nextSibling,d=this.parentNode;c(this).remove();b?c(b).before(a):c(d).append(a)})}else return this.pushStack(c(c.isFunction(a)?a():a),"replaceWith",a)},detach:function(a){return this.remove(a,true)},domManip:function(a,b,d){function f(u){return c.nodeName(u,"table")?u.getElementsByTagNam [...]
+u.appendChild(u.ownerDocument.createElement("tbody")):u}var e,j,i=a[0],o=[],k;if(!c.support.checkClone&&arguments.length===3&&typeof i==="string"&&ua.test(i))return this.each(function(){c(this).domManip(a,b,d,true)});if(c.isFunction(i))return this.each(function(u){var z=c(this);a[0]=i.call(this,u,b?z.html():w);z.domManip(a,b,d)});if(this[0]){e=i&&i.parentNode;e=c.support.parentNode&&e&&e.nodeType===11&&e.childNodes.length===this.length?{fragment:e}:sa(a,this,o);k=e.fragment;if(j=k.childN [...]
+1?(k=k.firstChild):k.firstChild){b=b&&c.nodeName(j,"tr");for(var n=0,r=this.length;n<r;n++)d.call(b?f(this[n],j):this[n],n>0||e.cacheable||this.length>1?k.cloneNode(true):k)}o.length&&c.each(o,Qa)}return this}});c.fragments={};c.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){c.fn[a]=function(d){var f=[];d=c(d);var e=this.length===1&&this[0].parentNode;if(e&&e.nodeType===11&&e.childNodes.length===1&&d.length=== [...]
+return this}else{e=0;for(var j=d.length;e<j;e++){var i=(e>0?this.clone(true):this).get();c.fn[b].apply(c(d[e]),i);f=f.concat(i)}return this.pushStack(f,a,d.selector)}}});c.extend({clean:function(a,b,d,f){b=b||s;if(typeof b.createElement==="undefined")b=b.ownerDocument||b[0]&&b[0].ownerDocument||s;for(var e=[],j=0,i;(i=a[j])!=null;j++){if(typeof i==="number")i+="";if(i){if(typeof i==="string"&&!jb.test(i))i=b.createTextNode(i);else if(typeof i==="string"){i=i.replace(Ka,Ma);var o=(La.exec [...]
+""])[1].toLowerCase(),k=F[o]||F._default,n=k[0],r=b.createElement("div");for(r.innerHTML=k[1]+i+k[2];n--;)r=r.lastChild;if(!c.support.tbody){n=ib.test(i);o=o==="table"&&!n?r.firstChild&&r.firstChild.childNodes:k[1]==="<table>"&&!n?r.childNodes:[];for(k=o.length-1;k>=0;--k)c.nodeName(o[k],"tbody")&&!o[k].childNodes.length&&o[k].parentNode.removeChild(o[k])}!c.support.leadingWhitespace&&V.test(i)&&r.insertBefore(b.createTextNode(V.exec(i)[0]),r.firstChild);i=r.childNodes}if(i.nodeType)e.pu [...]
+c.merge(e,i)}}if(d)for(j=0;e[j];j++)if(f&&c.nodeName(e[j],"script")&&(!e[j].type||e[j].type.toLowerCase()==="text/javascript"))f.push(e[j].parentNode?e[j].parentNode.removeChild(e[j]):e[j]);else{e[j].nodeType===1&&e.splice.apply(e,[j+1,0].concat(c.makeArray(e[j].getElementsByTagName("script"))));d.appendChild(e[j])}return e},cleanData:function(a){for(var b,d,f=c.cache,e=c.event.special,j=c.support.deleteExpando,i=0,o;(o=a[i])!=null;i++)if(d=o[c.expando]){b=f[d];if(b.events)for(var k in b [...]
+c.event.remove(o,k):Ca(o,k,b.handle);if(j)delete o[c.expando];else o.removeAttribute&&o.removeAttribute(c.expando);delete f[d]}}});var kb=/z-?index|font-?weight|opacity|zoom|line-?height/i,Na=/alpha\([^)]*\)/,Oa=/opacity=([^)]*)/,ha=/float/i,ia=/-([a-z])/ig,lb=/([A-Z])/g,mb=/^-?\d+(?:px)?$/i,nb=/^-?\d/,ob={position:"absolute",visibility:"hidden",display:"block"},pb=["Left","Right"],qb=["Top","Bottom"],rb=s.defaultView&&s.defaultView.getComputedStyle,Pa=c.support.cssFloat?"cssFloat":"styl [...]
+function(a,b){return b.toUpperCase()};c.fn.css=function(a,b){return X(this,a,b,true,function(d,f,e){if(e===w)return c.curCSS(d,f);if(typeof e==="number"&&!kb.test(f))e+="px";c.style(d,f,e)})};c.extend({style:function(a,b,d){if(!a||a.nodeType===3||a.nodeType===8)return w;if((b==="width"||b==="height")&&parseFloat(d)<0)d=w;var f=a.style||a,e=d!==w;if(!c.support.opacity&&b==="opacity"){if(e){f.zoom=1;b=parseInt(d,10)+""==="NaN"?"":"alpha(opacity="+d*100+")";a=f.filter||c.curCSS(a,"filter")| [...]
+Na.test(a)?a.replace(Na,b):b}return f.filter&&f.filter.indexOf("opacity=")>=0?parseFloat(Oa.exec(f.filter)[1])/100+"":""}if(ha.test(b))b=Pa;b=b.replace(ia,ja);if(e)f[b]=d;return f[b]},css:function(a,b,d,f){if(b==="width"||b==="height"){var e,j=b==="width"?pb:qb;function i(){e=b==="width"?a.offsetWidth:a.offsetHeight;f!=="border"&&c.each(j,function(){f||(e-=parseFloat(c.curCSS(a,"padding"+this,true))||0);if(f==="margin")e+=parseFloat(c.curCSS(a,"margin"+this,true))||0;else e-=parseFloat(c [...]
+"border"+this+"Width",true))||0})}a.offsetWidth!==0?i():c.swap(a,ob,i);return Math.max(0,Math.round(e))}return c.curCSS(a,b,d)},curCSS:function(a,b,d){var f,e=a.style;if(!c.support.opacity&&b==="opacity"&&a.currentStyle){f=Oa.test(a.currentStyle.filter||"")?parseFloat(RegExp.$1)/100+"":"";return f===""?"1":f}if(ha.test(b))b=Pa;if(!d&&e&&e[b])f=e[b];else if(rb){if(ha.test(b))b="float";b=b.replace(lb,"-$1").toLowerCase();e=a.ownerDocument.defaultView;if(!e)return null;if(a=e.getComputedSty [...]
+a.getPropertyValue(b);if(b==="opacity"&&f==="")f="1"}else if(a.currentStyle){d=b.replace(ia,ja);f=a.currentStyle[b]||a.currentStyle[d];if(!mb.test(f)&&nb.test(f)){b=e.left;var j=a.runtimeStyle.left;a.runtimeStyle.left=a.currentStyle.left;e.left=d==="fontSize"?"1em":f||0;f=e.pixelLeft+"px";e.left=b;a.runtimeStyle.left=j}}return f},swap:function(a,b,d){var f={};for(var e in b){f[e]=a.style[e];a.style[e]=b[e]}d.call(a);for(e in b)a.style[e]=f[e]}});if(c.expr&&c.expr.filters){c.expr.filters. [...]
+a.offsetWidth,d=a.offsetHeight,f=a.nodeName.toLowerCase()==="tr";return b===0&&d===0&&!f?true:b>0&&d>0&&!f?false:c.curCSS(a,"display")==="none"};c.expr.filters.visible=function(a){return!c.expr.filters.hidden(a)}}var sb=J(),tb=/<script(.|\s)*?\/script>/gi,ub=/select|textarea/i,vb=/color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week/i,N=/=\?(&|$)/,ka=/\?/,wb=/(\?|&)_=.*?(&|$)/,xb=/^(\w+:)?\/\/([^\/?#]+)/,yb=/%20/g,zb=c.fn.load;c.fn.extend({load:funct [...]
+"string")return zb.call(this,a);else if(!this.length)return this;var f=a.indexOf(" ");if(f>=0){var e=a.slice(f,a.length);a=a.slice(0,f)}f="GET";if(b)if(c.isFunction(b)){d=b;b=null}else if(typeof b==="object"){b=c.param(b,c.ajaxSettings.traditional);f="POST"}var j=this;c.ajax({url:a,type:f,dataType:"html",data:b,complete:function(i,o){if(o==="success"||o==="notmodified")j.html(e?c("<div />").append(i.responseText.replace(tb,"")).find(e):i.responseText);d&&j.each(d,[i.responseText,o,i])}}) [...]
+serialize:function(){return c.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?c.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||ub.test(this.nodeName)||vb.test(this.type))}).map(function(a,b){a=c(this).val();return a==null?null:c.isArray(a)?c.map(a,function(d){return{name:b.name,value:d}}):{name:b.name,value:a}}).get()}});c.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess [...]
+function(a,b){c.fn[b]=function(d){return this.bind(b,d)}});c.extend({get:function(a,b,d,f){if(c.isFunction(b)){f=f||d;d=b;b=null}return c.ajax({type:"GET",url:a,data:b,success:d,dataType:f})},getScript:function(a,b){return c.get(a,null,b,"script")},getJSON:function(a,b,d){return c.get(a,b,d,"json")},post:function(a,b,d,f){if(c.isFunction(b)){f=f||d;d=b;b={}}return c.ajax({type:"POST",url:a,data:b,success:d,dataType:f})},ajaxSetup:function(a){c.extend(c.ajaxSettings,a)},ajaxSettings:{url: [...]
+global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:A.XMLHttpRequest&&(A.location.protocol!=="file:"||!A.ActiveXObject)?function(){return new A.XMLHttpRequest}:function(){try{return new A.ActiveXObject("Microsoft.XMLHTTP")}catch(a){}},accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},etag:{} [...]
+e.success.call(k,o,i,x);e.global&&f("ajaxSuccess",[x,e])}function d(){e.complete&&e.complete.call(k,x,i);e.global&&f("ajaxComplete",[x,e]);e.global&&!--c.active&&c.event.trigger("ajaxStop")}function f(q,p){(e.context?c(e.context):c.event).trigger(q,p)}var e=c.extend(true,{},c.ajaxSettings,a),j,i,o,k=a&&a.context||e,n=e.type.toUpperCase();if(e.data&&e.processData&&typeof e.data!=="string")e.data=c.param(e.data,e.traditional);if(e.dataType==="jsonp"){if(n==="GET")N.test(e.url)||(e.url+=(ka [...]
+"&":"?")+(e.jsonp||"callback")+"=?");else if(!e.data||!N.test(e.data))e.data=(e.data?e.data+"&":"")+(e.jsonp||"callback")+"=?";e.dataType="json"}if(e.dataType==="json"&&(e.data&&N.test(e.data)||N.test(e.url))){j=e.jsonpCallback||"jsonp"+sb++;if(e.data)e.data=(e.data+"").replace(N,"="+j+"$1");e.url=e.url.replace(N,"="+j+"$1");e.dataType="script";A[j]=A[j]||function(q){o=q;b();d();A[j]=w;try{delete A[j]}catch(p){}z&&z.removeChild(C)}}if(e.dataType==="script"&&e.cache===null)e.cache=false;i [...]
+false&&n==="GET"){var r=J(),u=e.url.replace(wb,"$1_="+r+"$2");e.url=u+(u===e.url?(ka.test(e.url)?"&":"?")+"_="+r:"")}if(e.data&&n==="GET")e.url+=(ka.test(e.url)?"&":"?")+e.data;e.global&&!c.active++&&c.event.trigger("ajaxStart");r=(r=xb.exec(e.url))&&(r[1]&&r[1]!==location.protocol||r[2]!==location.host);if(e.dataType==="script"&&n==="GET"&&r){var z=s.getElementsByTagName("head")[0]||s.documentElement,C=s.createElement("script");C.src=e.url;if(e.scriptCharset)C.charset=e.scriptCharset;if [...]
+false;C.onload=C.onreadystatechange=function(){if(!B&&(!this.readyState||this.readyState==="loaded"||this.readyState==="complete")){B=true;b();d();C.onload=C.onreadystatechange=null;z&&C.parentNode&&z.removeChild(C)}}}z.insertBefore(C,z.firstChild);return w}var E=false,x=e.xhr();if(x){e.username?x.open(n,e.url,e.async,e.username,e.password):x.open(n,e.url,e.async);try{if(e.data||a&&a.contentType)x.setRequestHeader("Content-Type",e.contentType);if(e.ifModified){c.lastModified[e.url]&&x.se [...]
+c.lastModified[e.url]);c.etag[e.url]&&x.setRequestHeader("If-None-Match",c.etag[e.url])}r||x.setRequestHeader("X-Requested-With","XMLHttpRequest");x.setRequestHeader("Accept",e.dataType&&e.accepts[e.dataType]?e.accepts[e.dataType]+", */*":e.accepts._default)}catch(ga){}if(e.beforeSend&&e.beforeSend.call(k,x,e)===false){e.global&&!--c.active&&c.event.trigger("ajaxStop");x.abort();return false}e.global&&f("ajaxSend",[x,e]);var g=x.onreadystatechange=function(q){if(!x||x.readyState===0||q== [...]
+d();E=true;if(x)x.onreadystatechange=c.noop}else if(!E&&x&&(x.readyState===4||q==="timeout")){E=true;x.onreadystatechange=c.noop;i=q==="timeout"?"timeout":!c.httpSuccess(x)?"error":e.ifModified&&c.httpNotModified(x,e.url)?"notmodified":"success";var p;if(i==="success")try{o=c.httpData(x,e.dataType,e)}catch(v){i="parsererror";p=v}if(i==="success"||i==="notmodified")j||b();else c.handleError(e,x,i,p);d();q==="timeout"&&x.abort();if(e.async)x=null}};try{var h=x.abort;x.abort=function(){x&&h [...]
+g("abort")}}catch(l){}e.async&&e.timeout>0&&setTimeout(function(){x&&!E&&g("timeout")},e.timeout);try{x.send(n==="POST"||n==="PUT"||n==="DELETE"?e.data:null)}catch(m){c.handleError(e,x,null,m);d()}e.async||g();return x}},handleError:function(a,b,d,f){if(a.error)a.error.call(a.context||a,b,d,f);if(a.global)(a.context?c(a.context):c.event).trigger("ajaxError",[b,a,f])},active:0,httpSuccess:function(a){try{return!a.status&&location.protocol==="file:"||a.status>=200&&a.status<300||a.status== [...]
+1223||a.status===0}catch(b){}return false},httpNotModified:function(a,b){var d=a.getResponseHeader("Last-Modified"),f=a.getResponseHeader("Etag");if(d)c.lastModified[b]=d;if(f)c.etag[b]=f;return a.status===304||a.status===0},httpData:function(a,b,d){var f=a.getResponseHeader("content-type")||"",e=b==="xml"||!b&&f.indexOf("xml")>=0;a=e?a.responseXML:a.responseText;e&&a.documentElement.nodeName==="parsererror"&&c.error("parsererror");if(d&&d.dataFilter)a=d.dataFilter(a,b);if(typeof a==="st [...]
+"json"||!b&&f.indexOf("json")>=0)a=c.parseJSON(a);else if(b==="script"||!b&&f.indexOf("javascript")>=0)c.globalEval(a);return a},param:function(a,b){function d(i,o){if(c.isArray(o))c.each(o,function(k,n){b||/\[\]$/.test(i)?f(i,n):d(i+"["+(typeof n==="object"||c.isArray(n)?k:"")+"]",n)});else!b&&o!=null&&typeof o==="object"?c.each(o,function(k,n){d(i+"["+k+"]",n)}):f(i,o)}function f(i,o){o=c.isFunction(o)?o():o;e[e.length]=encodeURIComponent(i)+"="+encodeURIComponent(o)}var e=[];if(b===w) [...]
+if(c.isArray(a)||a.jquery)c.each(a,function(){f(this.name,this.value)});else for(var j in a)d(j,a[j]);return e.join("&").replace(yb,"+")}});var la={},Ab=/toggle|show|hide/,Bb=/^([+-]=)?([\d+-.]+)(.*)$/,W,va=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];c.fn.extend({show:function(a,b){if(a||a===0)return this.animate(K("show",3),a,b);else{a=0;for(b=this.length;a<b;a++){var d=c.data(this[a], [...]
+this[a].style.display=d||"";if(c.css(this[a],"display")==="none"){d=this[a].nodeName;var f;if(la[d])f=la[d];else{var e=c("<"+d+" />").appendTo("body");f=e.css("display");if(f==="none")f="block";e.remove();la[d]=f}c.data(this[a],"olddisplay",f)}}a=0;for(b=this.length;a<b;a++)this[a].style.display=c.data(this[a],"olddisplay")||"";return this}},hide:function(a,b){if(a||a===0)return this.animate(K("hide",3),a,b);else{a=0;for(b=this.length;a<b;a++){var d=c.data(this[a],"olddisplay");!d&&d!==" [...]
+"olddisplay",c.css(this[a],"display"))}a=0;for(b=this.length;a<b;a++)this[a].style.display="none";return this}},_toggle:c.fn.toggle,toggle:function(a,b){var d=typeof a==="boolean";if(c.isFunction(a)&&c.isFunction(b))this._toggle.apply(this,arguments);else a==null||d?this.each(function(){var f=d?a:c(this).is(":hidden");c(this)[f?"show":"hide"]()}):this.animate(K("toggle",3),a,b);return this},fadeTo:function(a,b,d){return this.filter(":hidden").css("opacity",0).show().end().animate({opacit [...]
+animate:function(a,b,d,f){var e=c.speed(b,d,f);if(c.isEmptyObject(a))return this.each(e.complete);return this[e.queue===false?"each":"queue"](function(){var j=c.extend({},e),i,o=this.nodeType===1&&c(this).is(":hidden"),k=this;for(i in a){var n=i.replace(ia,ja);if(i!==n){a[n]=a[i];delete a[i];i=n}if(a[i]==="hide"&&o||a[i]==="show"&&!o)return j.complete.call(this);if((i==="height"||i==="width")&&this.style){j.display=c.css(this,"display");j.overflow=this.style.overflow}if(c.isArray(a[i])){ [...]
+j.specialEasing||{})[i]=a[i][1];a[i]=a[i][0]}}if(j.overflow!=null)this.style.overflow="hidden";j.curAnim=c.extend({},a);c.each(a,function(r,u){var z=new c.fx(k,j,r);if(Ab.test(u))z[u==="toggle"?o?"show":"hide":u](a);else{var C=Bb.exec(u),B=z.cur(true)||0;if(C){u=parseFloat(C[2]);var E=C[3]||"px";if(E!=="px"){k.style[r]=(u||1)+E;B=(u||1)/z.cur(true)*B;k.style[r]=B+E}if(C[1])u=(C[1]==="-="?-1:1)*u+B;z.custom(B,u,E)}else z.custom(B,u,"")}});return true})},stop:function(a,b){var d=c.timers;a [...]
+this.each(function(){for(var f=d.length-1;f>=0;f--)if(d[f].elem===this){b&&d[f](true);d.splice(f,1)}});b||this.dequeue();return this}});c.each({slideDown:K("show",1),slideUp:K("hide",1),slideToggle:K("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"}},function(a,b){c.fn[a]=function(d,f){return this.animate(b,d,f)}});c.extend({speed:function(a,b,d){var f=a&&typeof a==="object"?a:{complete:d||!d&&b||c.isFunction(a)&&a,duration:a,easing:d&&b||b&&!c.isFunction(b)&&b};f.duration=c.f [...]
+"number"?f.duration:c.fx.speeds[f.duration]||c.fx.speeds._default;f.old=f.complete;f.complete=function(){f.queue!==false&&c(this).dequeue();c.isFunction(f.old)&&f.old.call(this)};return f},easing:{linear:function(a,b,d,f){return d+f*a},swing:function(a,b,d,f){return(-Math.cos(a*Math.PI)/2+0.5)*f+d}},timers:[],fx:function(a,b,d){this.options=b;this.elem=a;this.prop=d;if(!b.orig)b.orig={}}});c.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this [...]
+c.fx.step._default)(this);if((this.prop==="height"||this.prop==="width")&&this.elem.style)this.elem.style.display="block"},cur:function(a){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null))return this.elem[this.prop];return(a=parseFloat(c.css(this.elem,this.prop,a)))&&a>-10000?a:parseFloat(c.curCSS(this.elem,this.prop))||0},custom:function(a,b,d){function f(j){return e.step(j)}this.startTime=J();this.start=a;this.end=b;this.unit=d||this.unit||"px";this.n [...]
+this.pos=this.state=0;var e=this;f.elem=this.elem;if(f()&&c.timers.push(f)&&!W)W=setInterval(c.fx.tick,13)},show:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.show=true;this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur());c(this.elem).show()},hide:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.hide=true;this.custom(this.cur(),0)},step:function(a){var b=J(),d=true;if(a||b>=this.options.duration+this.st [...]
+this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;for(var f in this.options.curAnim)if(this.options.curAnim[f]!==true)d=false;if(d){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;a=c.data(this.elem,"olddisplay");this.elem.style.display=a?a:this.options.display;if(c.css(this.elem,"display")==="none")this.elem.style.display="block"}this.options.hide&&c(this.elem).hide();if(this.options.hide||this.options.show)for(var e in this. [...]
+e,this.options.orig[e]);this.options.complete.call(this.elem)}return false}else{e=b-this.startTime;this.state=e/this.options.duration;a=this.options.easing||(c.easing.swing?"swing":"linear");this.pos=c.easing[this.options.specialEasing&&this.options.specialEasing[this.prop]||a](this.state,e,0,1,this.options.duration);this.now=this.start+(this.end-this.start)*this.pos;this.update()}return true}};c.extend(c.fx,{tick:function(){for(var a=c.timers,b=0;b<a.length;b++)a[b]()||a.splice(b--,1);a [...]
+c.fx.stop()},stop:function(){clearInterval(W);W=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){c.style(a.elem,"opacity",a.now)},_default:function(a){if(a.elem.style&&a.elem.style[a.prop]!=null)a.elem.style[a.prop]=(a.prop==="width"||a.prop==="height"?Math.max(0,a.now):a.now)+a.unit;else a.elem[a.prop]=a.now}}});if(c.expr&&c.expr.filters)c.expr.filters.animated=function(a){return c.grep(c.timers,function(b){return a===b.elem}).length};c.fn.offset="getBoundingClien [...]
+function(a){var b=this[0];if(a)return this.each(function(e){c.offset.setOffset(this,a,e)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);var d=b.getBoundingClientRect(),f=b.ownerDocument;b=f.body;f=f.documentElement;return{top:d.top+(self.pageYOffset||c.support.boxModel&&f.scrollTop||b.scrollTop)-(f.clientTop||b.clientTop||0),left:d.left+(self.pageXOffset||c.support.boxModel&&f.scrollLeft||b.scrollLeft)-(f.clientLeft||b.clientLeft||0)}}:fun [...]
+this[0];if(a)return this.each(function(r){c.offset.setOffset(this,a,r)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);c.offset.initialize();var d=b.offsetParent,f=b,e=b.ownerDocument,j,i=e.documentElement,o=e.body;f=(e=e.defaultView)?e.getComputedStyle(b,null):b.currentStyle;for(var k=b.offsetTop,n=b.offsetLeft;(b=b.parentNode)&&b!==o&&b!==i;){if(c.offset.supportsFixedPosition&&f.position==="fixed")break;j=e?e.getComputedStyle(b,null):b.cu [...]
+k-=b.scrollTop;n-=b.scrollLeft;if(b===d){k+=b.offsetTop;n+=b.offsetLeft;if(c.offset.doesNotAddBorder&&!(c.offset.doesAddBorderForTableAndCells&&/^t(able|d|h)$/i.test(b.nodeName))){k+=parseFloat(j.borderTopWidth)||0;n+=parseFloat(j.borderLeftWidth)||0}f=d;d=b.offsetParent}if(c.offset.subtractsBorderForOverflowNotVisible&&j.overflow!=="visible"){k+=parseFloat(j.borderTopWidth)||0;n+=parseFloat(j.borderLeftWidth)||0}f=j}if(f.position==="relative"||f.position==="static"){k+=o.offsetTop;n+=o. [...]
+f.position==="fixed"){k+=Math.max(i.scrollTop,o.scrollTop);n+=Math.max(i.scrollLeft,o.scrollLeft)}return{top:k,left:n}};c.offset={initialize:function(){var a=s.body,b=s.createElement("div"),d,f,e,j=parseFloat(c.curCSS(a,"marginTop",true))||0;c.extend(b.style,{position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"});b.innerHTML="<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></d [...]
+a.insertBefore(b,a.firstChild);d=b.firstChild;f=d.firstChild;e=d.nextSibling.firstChild.firstChild;this.doesNotAddBorder=f.offsetTop!==5;this.doesAddBorderForTableAndCells=e.offsetTop===5;f.style.position="fixed";f.style.top="20px";this.supportsFixedPosition=f.offsetTop===20||f.offsetTop===15;f.style.position=f.style.top="";d.style.overflow="hidden";d.style.position="relative";this.subtractsBorderForOverflowNotVisible=f.offsetTop===-5;this.doesNotIncludeMarginInBodyOffset=a.offsetTop!==j [...]
+c.offset.initialize=c.noop},bodyOffset:function(a){var b=a.offsetTop,d=a.offsetLeft;c.offset.initialize();if(c.offset.doesNotIncludeMarginInBodyOffset){b+=parseFloat(c.curCSS(a,"marginTop",true))||0;d+=parseFloat(c.curCSS(a,"marginLeft",true))||0}return{top:b,left:d}},setOffset:function(a,b,d){if(/static/.test(c.curCSS(a,"position")))a.style.position="relative";var f=c(a),e=f.offset(),j=parseInt(c.curCSS(a,"top",true),10)||0,i=parseInt(c.curCSS(a,"left",true),10)||0;if(c.isFunction(b))b= [...]
+d,e);d={top:b.top-e.top+j,left:b.left-e.left+i};"using"in b?b.using.call(a,d):f.css(d)}};c.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),d=this.offset(),f=/^body|html$/i.test(b[0].nodeName)?{top:0,left:0}:b.offset();d.top-=parseFloat(c.curCSS(a,"marginTop",true))||0;d.left-=parseFloat(c.curCSS(a,"marginLeft",true))||0;f.top+=parseFloat(c.curCSS(b[0],"borderTopWidth",true))||0;f.left+=parseFloat(c.curCSS(b[0],"borderLeftWidth",true))||0;return{ [...]
+f.top,left:d.left-f.left}},offsetParent:function(){return this.map(function(){for(var a=this.offsetParent||s.body;a&&!/^body|html$/i.test(a.nodeName)&&c.css(a,"position")==="static";)a=a.offsetParent;return a})}});c.each(["Left","Top"],function(a,b){var d="scroll"+b;c.fn[d]=function(f){var e=this[0],j;if(!e)return null;if(f!==w)return this.each(function(){if(j=wa(this))j.scrollTo(!a?f:c(j).scrollLeft(),a?f:c(j).scrollTop());else this[d]=f});else return(j=wa(e))?"pageXOffset"in j?j[a?"pag [...]
+"pageXOffset"]:c.support.boxModel&&j.document.documentElement[d]||j.document.body[d]:e[d]}});c.each(["Height","Width"],function(a,b){var d=b.toLowerCase();c.fn["inner"+b]=function(){return this[0]?c.css(this[0],d,false,"padding"):null};c.fn["outer"+b]=function(f){return this[0]?c.css(this[0],d,false,f?"margin":"border"):null};c.fn[d]=function(f){var e=this[0];if(!e)return f==null?null:this;if(c.isFunction(f))return this.each(function(j){var i=c(this);i[d](f.call(this,j,i[d]()))});return" [...]
+e&&e.document?e.document.compatMode==="CSS1Compat"&&e.document.documentElement["client"+b]||e.document.body["client"+b]:e.nodeType===9?Math.max(e.documentElement["client"+b],e.body["scroll"+b],e.documentElement["scroll"+b],e.body["offset"+b],e.documentElement["offset"+b]):f===w?c.css(e,d):this.css(d,typeof f==="string"?f:f+"px")}});A.jQuery=A.$=c})(window);
diff --git a/src/compiler/scala/tools/nsc/doc/html/resource/lib/jquery.layout.js b/src/compiler/scala/tools/nsc/doc/html/resource/lib/jquery.layout.js
new file mode 100644
index 0000000..4ab9976
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/doc/html/resource/lib/jquery.layout.js
@@ -0,0 +1,18 @@
+/*
+ * jquery.layout 1.3.0 - Release Candidate 29.3
+ *
+ * Copyright (c) 2010 
+ *   Fabrizio Balliano (http://www.fabrizioballiano.net)
+ *   Kevin Dalman (http://allpro.net)
+ *
+ * Dual licensed under the GPL (http://www.gnu.org/licenses/gpl.html)
+ * and MIT (http://www.opensource.org/licenses/mit-license.php) licenses.
+ *
+ * Docs: http://layout.jquery-dev.net/documentation.html
+ * Tips: http://layout.jquery-dev.net/tips.html
+ * Help: http://groups.google.com/group/jquery-ui-layout
+ *
+ * $Date: 2010-07-13 08:00:00 (Wed, 14 July 2010) $
+ * $Rev: 30293 $
+ */
+(function($){$.fn.layout=function(opts){var lang={Pane:"Pane",Open:"Open",Close:"Close",Resize:"Resize",Slide:"Slide Open",Pin:"Pin",Unpin:"Un-Pin",selector:"selector",msgNoRoom:"Not enough room to show this pane.",errContainerMissing:"UI Layout Initialization Error\n\nThe specified layout-container does not exist.",errCenterPaneMissing:"UI Layout Initialization Error\n\nThe center-pane element does not exist.\n\nThe center-pane is a required element.",errContainerHeight:"UI Layout Initi [...]
diff --git a/src/compiler/scala/tools/nsc/doc/html/resource/lib/object.png b/src/compiler/scala/tools/nsc/doc/html/resource/lib/object.png
new file mode 100644
index 0000000..886cd5c
Binary files /dev/null and b/src/compiler/scala/tools/nsc/doc/html/resource/lib/object.png differ
diff --git a/src/compiler/scala/tools/nsc/doc/html/resource/lib/object_big.png b/src/compiler/scala/tools/nsc/doc/html/resource/lib/object_big.png
new file mode 100644
index 0000000..0a483ca
Binary files /dev/null and b/src/compiler/scala/tools/nsc/doc/html/resource/lib/object_big.png differ
diff --git a/src/compiler/scala/tools/nsc/doc/html/resource/lib/package.png b/src/compiler/scala/tools/nsc/doc/html/resource/lib/package.png
new file mode 100644
index 0000000..c3eef6e
Binary files /dev/null and b/src/compiler/scala/tools/nsc/doc/html/resource/lib/package.png differ
diff --git a/src/compiler/scala/tools/nsc/doc/html/resource/lib/package_big.png b/src/compiler/scala/tools/nsc/doc/html/resource/lib/package_big.png
new file mode 100644
index 0000000..5ab05cc
Binary files /dev/null and b/src/compiler/scala/tools/nsc/doc/html/resource/lib/package_big.png differ
diff --git a/src/compiler/scala/tools/nsc/doc/html/resource/lib/remove.png b/src/compiler/scala/tools/nsc/doc/html/resource/lib/remove.png
new file mode 100644
index 0000000..4625f9d
Binary files /dev/null and b/src/compiler/scala/tools/nsc/doc/html/resource/lib/remove.png differ
diff --git a/src/compiler/scala/tools/nsc/doc/html/resource/lib/remove.psd b/src/compiler/scala/tools/nsc/doc/html/resource/lib/remove.psd
new file mode 100644
index 0000000..3764f82
Binary files /dev/null and b/src/compiler/scala/tools/nsc/doc/html/resource/lib/remove.psd differ
diff --git a/src/compiler/scala/tools/nsc/doc/html/resource/lib/scheduler.js b/src/compiler/scala/tools/nsc/doc/html/resource/lib/scheduler.js
new file mode 100644
index 0000000..4417f5b
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/doc/html/resource/lib/scheduler.js
@@ -0,0 +1,71 @@
+// © 2010 EPFL/LAMP
+// code by Gilles Dubochet
+
+function Scheduler() {
+    var scheduler = this;
+    var resolution = 0;
+    this.timeout = undefined;
+    this.queues = new Array(0); // an array of work pacakges indexed by index in the labels table.
+    this.labels = new Array(0); // an indexed array of labels indexed by priority. This should be short.
+    this.label = function(name, priority) {
+        this.name = name;
+        this.priority = priority;
+    }
+    this.work = function(fn, self, args) {
+        this.fn = fn;
+        this.self = self;
+        this.args = args;
+    }
+    this.addLabel = function(name, priority) {
+        var idx = 0;
+        while (idx < scheduler.queues.length && scheduler.labels[idx].priority <= priority) { idx = idx + 1; }
+        scheduler.labels.splice(idx, 0, new scheduler.label(name, priority));
+        scheduler.queues.splice(idx, 0, new Array(0));
+    }
+    this.clearLabel = function(name) {
+        var idx = 0;
+        while (idx < scheduler.queues.length && scheduler.labels[idx].name != name) { idx = idx + 1; }
+        if (idx < scheduler.queues.length && scheduler.labels[i].name == name) {
+            scheduler.labels.splice(idx, 1);
+            scheduler.queues.splice(idx, 1);
+        }
+    }
+    this.nextWork = function() {
+        var fn = undefined;
+        var idx = 0;
+        while (idx < scheduler.queues.length && scheduler.queues[idx].length == 0) { idx = idx + 1; }
+        if (idx < scheduler.queues.length && scheduler.queues[idx].length > 0) {
+            var fn = scheduler.queues[idx].shift();
+        }
+        return fn;
+    }
+    this.add = function(labelName, fn, self, args) {
+        var doWork = function() {
+            scheduler.timeout = setTimeout(function() {
+                var work = scheduler.nextWork();
+                if (work != undefined) {
+                    if (work.args == undefined) { work.args = new Array(0); }
+                    work.fn.apply(work.self, work.args);
+                    doWork();
+                }
+                else {
+                    scheduler.timeout = undefined;
+                }
+            }, resolution);
+        }
+        var idx = 0;
+        while (idx < scheduler.labels.length && scheduler.labels[idx].name != labelName) { idx = idx + 1; }
+        if (idx < scheduler.queues.length && scheduler.labels[idx].name == labelName) {
+            scheduler.queues[idx].push(new scheduler.work(fn, self, args));
+            if (scheduler.timeout == undefined) doWork();
+        }
+        else throw("queue for add is non existant");
+    }
+    this.clear = function(labelName) {
+        var idx = 0;
+        while (idx < scheduler.labels.length && scheduler.labels[idx].name != labelName) { idx = idx + 1; }
+        if (idx < scheduler.queues.length && scheduler.labels[idx].name == labelName) {
+            scheduler.queues[idx] = new Array();
+        }
+    }
+};
diff --git a/src/compiler/scala/tools/nsc/doc/html/resource/lib/template.css b/src/compiler/scala/tools/nsc/doc/html/resource/lib/template.css
new file mode 100644
index 0000000..de78793
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/doc/html/resource/lib/template.css
@@ -0,0 +1,496 @@
+/* Reset */
+
+html, body, div, span, object, iframe,
+h1, h2, h3, h4, h5, h6, p, blockquote, pre,
+a, abbr, acronym, address, code,
+del, dfn, em, img, q, dl, dt, dd, ol, ul, li,
+fieldset, form, label, legend, input,
+table, caption, tbody, tfoot, thead, tr, th, td {
+  margin: 0;
+  padding: 0;
+  border: 0;
+  font-weight: inherit;
+  font-style: inherit;
+  font-size: 100%;
+  font-family: inherit;
+  vertical-align: baseline;
+}
+
+body {
+  line-height: 1;
+}
+
+table { border-collapse: separate; border-spacing: 0; }
+caption, th, td { text-align: left; font-weight: normal; }
+table, td, th { vertical-align: middle; }
+
+blockquote:before, blockquote:after, q:before, q:after { content: ""; }
+blockquote, q { quotes: none; }
+
+a img { border: none; }
+
+input { border-width: 0px; }
+
+/* Page */
+
+body {
+  font-family: sans-serif;
+  font-size: 10pt;
+}
+
+a {
+  text-decoration: underline;
+  color: #69481D; /* brown */
+}
+
+a:hover {
+  text-decoration: none;
+}
+
+#owner {
+  padding: 4px;
+  font-size: 12pt;
+  display: block;
+}
+
+#owner a {
+  color: black;
+}
+
+.value #owner {
+  background-color: #7996AC;
+}
+
+.type #owner {
+  background-color: #799F5A;
+}
+
+#definition {
+  display: block;
+  padding: 6px;
+}
+
+#definition > img {
+  float: left;
+}
+
+#definition > h1 {
+  padding: 12px 0 12px 6px;
+  color: white;
+  font-size: 24pt;
+  display: inline-block;
+}
+
+#signature > span.kind {
+  font-size: 11pt;
+  display: inline;
+  float: left;
+  text-align: left;
+  width: auto;
+  padding-left: 6px;
+}
+
+#signature > span.symbol {
+  font-size: 11pt;
+  text-align: left;
+}
+
+.value #definition {
+  background-color: #2C475C;
+}
+
+.type #definition {
+  background-color: #385E1A;
+}
+
+#comment {
+  padding-right: 8px;
+  padding-left: 8px;
+}
+
+#template .values > h3 {
+  color: white;
+  padding: 4px;
+  background-color: #7996AC;
+  font-size: 12pt;
+  font-weight: bold;
+}
+
+#template .types > h3 {
+  padding: 4px;
+  color: white;
+  font-weight: bold;
+  font-size: 12pt;
+  background-color: #799F5A;
+}
+
+#constructors > h3 {
+  padding: 4px;
+  color: white;
+  font-weight: bold;
+  font-size: 12pt;
+  background-color: #333;
+}
+
+#template > div.parent > h3 {
+  color: white;
+  padding: 4px;
+  margin-top: 10px;
+  background-color: #47166D;
+  font-size: 12pt;
+  font-weight: bold;
+}
+
+#template > div.parent > h3 * {
+  color: white;
+}
+
+/* Member cells */
+
+div.members > ol {
+  background-color: white;
+  list-style: none
+}
+
+div.members > ol > li {
+  display: block;
+}
+
+/* Member signatures */
+
+#tooltip {
+  background: #EFD5B5;
+  border: 1px solid gray;
+  color: black;
+  display: none;
+  padding: 5px;
+  position: absolute;
+}
+
+.signature {
+  padding: 3px;
+  font-family: monospace;
+  font-size: 10pt;
+  clear: both;
+  display: block;
+  background-color: #E5E5E5;
+}
+
+.signature .kind {
+  text-align: right;
+  float: left;
+  display: inline-block;
+  width: 8em;
+}
+
+.signature > a > .symbol > .name {
+  text-decoration: underline;
+}
+
+.signature > a:hover > .symbol > .name {
+  text-decoration: none;
+}
+
+.signature > a {
+  text-decoration: none;
+}
+
+.signature .symbol {
+  display: inline;
+  padding-left: 0.7em;
+}
+
+.signature .name {
+  display: inline-block;
+  font-weight: bold;
+}
+
+.signature .symbol .params .implicit {
+  font-style: italic;
+}
+
+.signature .symbol .name.deprecated {
+  text-decoration: line-through;
+}
+
+.signature .symbol .params .default {
+  font-style: italic;
+}
+
+#template .values .signature .name {
+  color: blue;
+}
+
+#template .types .signature .name {
+  color: green;
+}
+
+/* Comments text formating */
+
+.cmt {}
+
+.cmt p {
+	margin-bottom: 0.4em;
+	margin-top: 0.4em;
+}
+
+.cmt h3 {
+  margin-bottom: 1em;
+  margin-top: 1em;
+  display: block;
+  text-align: left;
+  font-weight: bold;
+  font-size: x-large;
+}
+
+.cmt h4 {
+  margin-bottom: 0.6em;
+  margin-top: 0.6em;
+  display: block;
+  text-align: left;
+  font-weight: bold;
+  font-size: large;
+}
+
+.cmt h5 {
+  margin-bottom: 0.4em;
+  margin-top: 0.4em;
+  display: block;
+  text-align: left;
+  font-weight: bold;
+}
+
+.cmt h6 {
+  margin-bottom: 0.4em;
+  margin-top: 0.4em;
+  display: block;
+  text-align: left;
+  font-style: italic;
+}
+
+.cmt pre {
+  padding: 0.4em;
+  border-color: #ddd;
+  border-style: solid;
+  border-width: 1px;
+  margin-left: 0;
+  margin-bottom: 0.4em;
+  margin-right: 0;
+  margin-top: 0.4em;
+  background-color: #eee;
+  display: block;
+  font-family: monospace;
+}
+
+.cmt ul {
+  display: block;
+  list-style: circle;
+  padding-left:20px;
+}
+
+.cmt ol {
+  display: block;
+  padding-left:20px;
+}
+
+.cmt ol.decimal {
+  list-style: decimal;
+}
+
+.cmt ol.lowerAlpha {
+  list-style: lower-alpha;
+}
+
+.cmt ol.upperAlpha {
+  list-style: upper-alpha;
+}
+
+.cmt ol.lowerRoman {
+  list-style: lower-roman;
+}
+
+.cmt ol.upperRoman {
+  list-style: upper-roman;
+}
+
+.cmt li {
+  display:list-item;
+}
+
+.cmt code {
+  font-family: monospace;
+}
+
+.cmt a {
+  font-style: bold;
+}
+
+/* Comments structured layout */
+
+p.comment {
+  display: block;
+  margin-left: 8.7em;
+}
+
+p.shortcomment {
+  display: block;
+  margin-left: 8.7em;
+  cursor: pointer;
+}
+
+div.fullcomment {
+  margin: 10px 0 10px 0;
+}
+
+#template div.fullcomment {
+  display:none;
+  margin: 6px 0 6px 8.7em;
+}
+
+div.fullcomment .block {
+  padding: 2px 0 2px 0;
+  border-top: 1px solid gray;
+  border-bottom: 1px solid gray;
+}
+
+div.fullcomment div.block ol li p, 
+div.fullcomment div.block ol li {
+  display:inline
+}
+
+div.fullcomment .block + .block {
+  border-top: none;
+}
+
+div.fullcomment .block > h5 {
+  font-style: italic;
+  font-weight: normal;
+  display: inline-block;
+}
+
+div.fullcomment .comment {
+  margin: 6px 0 6px 0;
+}
+
+div.fullcomment dl.paramcmts > dt {
+  display: block;
+  float: left;
+  font-weight: bold;
+  margin: 2px 4px 2px 0;
+}
+
+div.fullcomment dl.paramcmts > dd {
+  display: block;
+  padding-left: 80px;
+  border-top: 1px dashed gray;
+  border-bottom: 1px dashed gray;
+}
+
+div.fullcomment dl.paramcmts > dt:first-child + dd {
+  border-top: none;
+}
+
+div.fullcomment dl.paramcmts > dd:last-child {
+  border-bottom: none;
+}
+
+div.fullcomment dl.paramcmts > dd + dt + dd {
+  border-top: none;
+}
+
+/* Members filter tool */
+
+#textfilter {
+	position: relative;
+	display: block;
+    height: 20px;
+	margin-bottom: 5px;
+}
+
+#textfilter > .pre {
+    display: block;
+    position: absolute;
+    top: 0;
+    left: 0;
+    height: 20px;
+    width: 20px;
+    background: url("filter_box_left.png");
+}
+
+#textfilter > .input {
+	display: block;
+    position: absolute;
+    top: 0;
+    right: 20px;
+    left: 20px;
+}
+
+#textfilter > .input > input {
+	height: 16px;
+	padding: 2px;
+	font-weight: bold;
+	color: #993300;
+	background-color: white;
+    width: 100%;
+}
+
+#textfilter > .post {
+    display: block;
+    position: absolute;
+    top: 0;
+    right: 0;
+    height: 20px;
+    width: 20px;
+    background: url("filter_box_right.png");
+}
+
+#mbrsel {
+  padding: 4px;
+  background-color: #B78E99; /* grayish pink */
+  display: block;
+  margin-bottom: 10px;
+}
+
+#mbrsel > div > span.filtertype {
+  padding: 4px;
+  float: left;
+  display: inline-block;
+  color: white;
+  width: 4.5em;
+}
+
+#mbrsel > div > ol {
+  display: inline-block;
+  background-color: white;
+}
+
+#mbrsel > div > ol#linearization {
+  display: inline;
+}
+
+#mbrsel > div > ol > li {
+  padding: 4px 8px 4px 8px;
+  background-color: white;
+  display: inline-block;
+  cursor: pointer;
+}
+
+#mbrsel > div > ol > li.in {
+  background-color: white;
+  color: #4C4C4C;
+}
+
+#mbrsel > div > ol > li.out {
+  color: #80384E;
+  background-color: #9E6A77;
+}
+
+#mbrsel .hideall {
+  color: #4C4C4C;
+  font-weight: bold;
+}
+
+#mbrsel .showall {
+  color: #4C4C4C;
+  font-weight: bold;  
+}
diff --git a/src/compiler/scala/tools/nsc/doc/html/resource/lib/template.js b/src/compiler/scala/tools/nsc/doc/html/resource/lib/template.js
new file mode 100644
index 0000000..e32c7f1
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/doc/html/resource/lib/template.js
@@ -0,0 +1,270 @@
+// © 2009–2010 EPFL/LAMP
+// code by Gilles Dubochet with contributions by Pedro Furlanetto
+
+$(document).ready(function(){
+    var prefilters = $("#ancestors > ol > li").filter(function(){
+        var name = $(this).attr("name");
+        return name == "scala.Any" || name == "scala.AnyRef";
+    });
+    prefilters.removeClass("in");
+    prefilters.addClass("out");
+    filter();
+
+    var input = $("#textfilter > input");
+    input.bind("keyup", function(event) {
+        if (event.keyCode == 27) { // escape
+            input.attr("value", "");
+        }
+        filter();
+    });
+    input.focus(function(event) { input.select(); });
+    $("#textfilter > .post").click(function(){
+        $("#textfilter > input").attr("value", "");
+        filter();
+    });
+
+    $("#ancestors > ol > li").click(function(){
+        if ($(this).hasClass("in")) {
+            $(this).removeClass("in");
+            $(this).addClass("out");
+        }
+        else if ($(this).hasClass("out")) {
+            $(this).removeClass("out");
+            $(this).addClass("in");
+        };
+        filter();
+    });
+    $("#ancestors > ol > li.hideall").click(function() {
+        $("#ancestors > ol > li.in").removeClass("in").addClass("out");
+        filter();
+    })
+    $("#ancestors > ol > li.showall").click(function() {
+        var filtered =
+            $("#ancestors > ol > li.out").filter(function() {
+                var name = $(this).attr("name");
+                return !(name == "scala.Any" || name == "scala.AnyRef");
+            });
+        filtered.removeClass("out").addClass("in");
+        filter();
+    });
+    $("#visbl > ol > li.public").click(function() {
+        if ($(this).hasClass("out")) {
+            $(this).removeClass("out").addClass("in");
+            $("#visbl > ol > li.all").removeClass("in").addClass("out");
+            filter();
+        };
+    })
+    $("#visbl > ol > li.all").click(function() {
+        if ($(this).hasClass("out")) {
+            $(this).removeClass("out").addClass("in");
+            $("#visbl > ol > li.public").removeClass("in").addClass("out");
+            filter();
+        };
+    });
+    $("#impl > ol > li.concrete").click(function() {
+        if ($(this).hasClass("out")) {
+            $(this).removeClass("out").addClass("in");            
+            $("li[data-isabs='false']").show();
+        } else {
+            $(this).removeClass("in").addClass("out");
+            $("li[data-isabs='false']").hide();
+        }
+    });
+    $("#impl > ol > li.abstract").click(function() {
+        if ($(this).hasClass("out")) {
+            $(this).removeClass("out").addClass("in");                        
+            $("li[data-isabs='true']").show();
+        } else {
+            $(this).removeClass("in").addClass("out");
+            $("li[data-isabs='true']").hide();
+        }
+    });
+    $("#order > ol > li.alpha").click(function() {
+        if ($(this).hasClass("out")) {
+            $(this).removeClass("out").addClass("in");
+            $("#order > ol > li.inherit").removeClass("in").addClass("out");
+            orderAlpha();
+        };
+    })
+    $("#order > ol > li.inherit").click(function() {
+        if ($(this).hasClass("out")) {
+            $(this).removeClass("out").addClass("in");
+            $("#order > ol > li.alpha").removeClass("in").addClass("out");
+            orderInherit();
+        };
+    });
+    initInherit();
+    //http://flowplayer.org/tools/tooltip.html
+    $(".extype").tooltip({
+        tip: "#tooltip",
+        position:"top center",
+        onBeforeShow: function(ev) {
+            $(this.getTip()).text(this.getTrigger().attr("name"));
+        }
+    });
+    $(".defval").tooltip({
+        tip: "#tooltip",
+        position:"top center",        
+        onBeforeShow: function(ev) {
+            $(this.getTip()).html(this.getTrigger().attr("name"))
+        }        
+    });   
+    var docAllSigs = $("#template .signature");
+    function commentShowFct(fullComment){
+        var vis = $(":visible", fullComment);
+        if (vis.length > 0) {
+            fullComment.slideUp(100);
+        }
+        else {
+            fullComment.slideDown(100);
+        }
+    };
+    var docShowSigs = docAllSigs.filter(function(){
+        return $("+ div.fullcomment", $(this)).length > 0;
+    });
+    docShowSigs.css("cursor", "pointer");
+    docShowSigs.click(function(){
+        commentShowFct($("+ div.fullcomment", $(this)));
+    });
+    function commentToggleFct(shortComment){
+        var vis = $("~ div.fullcomment:visible", shortComment);
+        if (vis.length > 0) {
+            shortComment.slideDown(100);
+            vis.slideUp(100);
+        }
+        else {
+            var hid = $("~ div.fullcomment:hidden", shortComment);
+            hid.slideDown(100);
+            shortComment.slideUp(100);
+        }
+    };
+    var docToggleSigs = docAllSigs.filter(function(){
+        return $("+ p.shortcomment", $(this)).length > 0;
+    });
+    docToggleSigs.css("cursor", "pointer");
+    docToggleSigs.click(function(){
+        commentToggleFct($("+ p.shortcomment", $(this)));
+    });
+    $("p.shortcomment").click(function(){
+        commentToggleFct($(this));
+    });
+});
+
+function orderAlpha() {
+    $("#template > div.parent").hide();
+    $("#ancestors").show();
+    filter();
+};
+
+function orderInherit() {
+    $("#template > div.parent").show();
+    $("#ancestors").hide();
+    filter();
+};
+
+/** Prepares the DOM for inheritance-based display. To do so it will:
+  *  - hide all statically-generated parents headings;
+  *  - copy all members from the value and type members lists (flat members) to corresponding lists nested below the
+  *    parent headings (inheritance-grouped members);
+  *  - initialises a control variable used by the filter method to control whether filtering happens on flat members
+  *    or on inheritance-grouped members. */
+function initInherit() {
+    // parents is a map from fully-qualified names to the DOM node of parent headings.
+    var parents = new Object();
+    $("#template > div.parent").each(function(){
+        parents[$(this).attr("name")] = $(this);
+    });
+    // 
+    $("#types > ol > li").each(function(){
+        var qualName = $(this).attr("name");
+        var owner = qualName.slice(0, qualName.indexOf("#"));
+        var name = qualName.slice(qualName.indexOf("#") + 1);
+        var parent = parents[owner];
+        if (parent != undefined) {
+            var types = $("> .types > ol", parent);
+            if (types.length == 0) {
+                parent.append("<div class='types members'><h3>Type Members</h3><ol></ol></div>");
+                types = $("> .types > ol", parent);
+            }
+            types.append($(this).clone());
+        }
+    });
+    $("#values > ol > li").each(function(){
+        var qualName = $(this).attr("name");
+        var owner = qualName.slice(0, qualName.indexOf("#"));
+        var name = qualName.slice(qualName.indexOf("#") + 1);
+        var parent = parents[owner];
+        if (parent != undefined) {
+            var values = $("> .values > ol", parent);
+            if (values.length == 0) {
+                parent.append("<div class='values members'><h3>Value Members</h3><ol></ol></div>");
+                values = $("> .values > ol", parent);
+            }
+            values.append($(this).clone());
+        }
+    });
+    $("#template > div.parent").each(function(){
+        if ($("> div.members", this).length == 0) { $(this).remove(); };
+    });
+    $("#template > div.parent").each(function(){
+        $(this).hide();
+    });
+};
+
+function filter() {
+    var query = $("#textfilter input").attr("value").toLowerCase();
+    var queryRegExp = new RegExp(query, "i");
+    var inheritHides = null
+    if ($("#order > ol > li.inherit").hasClass("in")) {
+        inheritHides = $("#linearization > li:gt(0)");
+    }
+    else {
+        inheritHides = $("#linearization > li.out");
+    }
+    var outOwners =
+        inheritHides.map(function(){
+            var r = $(this).attr("name");
+            return r
+        }).get();
+    var prtVisbl = $("#visbl > ol > li.all").hasClass("in");
+    $(".members > ol > li").each(function(){
+        var vis1 = $(this).attr("visbl");
+        var qualName1 = $(this).attr("name");
+        //var name1 = qualName1.slice(qualName1.indexOf("#") + 1);
+        var showByOwned = true;
+        if ($(this).parents(".parent").length == 0) {
+           // owner filtering must not happen in "inherited from" member lists
+            var owner1 = qualName1.slice(0, qualName1.indexOf("#"));
+            for (out in outOwners) {
+                if (outOwners[out] == owner1) {
+                    showByOwned = false;
+                };
+            };
+        };
+        var showByVis = true;
+        if (vis1 == "prt") {
+            showByVis = prtVisbl;
+        };
+        var showByName = true;
+        if (query != "") {
+            var content = $(this).attr("name") + $("> .fullcomment .cmt", this).text();
+            showByName = queryRegExp.test(content);
+        };
+        if (showByOwned && showByVis && showByName) {
+          $(this).show();
+        }
+        else {
+          $(this).hide();
+        };
+    });
+    $(".members").each(function(){
+        $(this).show();
+        if ($(" > ol > li:visible", this).length == 0) { $(this).hide(); }
+    });
+    return false
+};
+
+function windowTitle()
+{
+    parent.document.title=document.title;
+};
diff --git a/src/compiler/scala/tools/nsc/doc/html/resource/lib/tools.tooltip.js b/src/compiler/scala/tools/nsc/doc/html/resource/lib/tools.tooltip.js
new file mode 100644
index 0000000..0af34ec
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/doc/html/resource/lib/tools.tooltip.js
@@ -0,0 +1,14 @@
+/*
+ * tools.tooltip 1.1.3 - Tooltips done right.
+ * 
+ * Copyright (c) 2009 Tero Piirainen
+ * http://flowplayer.org/tools/tooltip.html
+ *
+ * Dual licensed under MIT and GPL 2+ licenses
+ * http://www.opensource.org/licenses
+ *
+ * Launch  : November 2008
+ * Date: ${date}
+ * Revision: ${revision} 
+ */
+(function(c){var d=[];c.tools=c.tools||{};c.tools.tooltip={version:"1.1.3",conf:{effect:"toggle",fadeOutSpeed:"fast",tip:null,predelay:0,delay:30,opacity:1,lazy:undefined,position:["top","center"],offset:[0,0],cancelDefault:true,relative:false,oneInstance:true,events:{def:"mouseover,mouseout",input:"focus,blur",widget:"focus mouseover,blur mouseout",tooltip:"mouseover,mouseout"},api:false},addEffect:function(e,g,f){b[e]=[g,f]}};var b={toggle:[function(e){var f=this.getConf(),g=this.getTi [...]
\ No newline at end of file
diff --git a/src/compiler/scala/tools/nsc/doc/html/resource/lib/trait.png b/src/compiler/scala/tools/nsc/doc/html/resource/lib/trait.png
new file mode 100644
index 0000000..b3871a0
Binary files /dev/null and b/src/compiler/scala/tools/nsc/doc/html/resource/lib/trait.png differ
diff --git a/src/compiler/scala/tools/nsc/doc/html/resource/lib/trait_big.png b/src/compiler/scala/tools/nsc/doc/html/resource/lib/trait_big.png
new file mode 100644
index 0000000..a448713
Binary files /dev/null and b/src/compiler/scala/tools/nsc/doc/html/resource/lib/trait_big.png differ
diff --git a/src/compiler/scala/tools/nsc/doc/html/resource/lib/type_tags.ai b/src/compiler/scala/tools/nsc/doc/html/resource/lib/type_tags.ai
new file mode 100644
index 0000000..b56fd1d
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/doc/html/resource/lib/type_tags.ai
@@ -0,0 +1,6020 @@
+%PDF-1.5
%����
+1 0 obj
<</Metadata 1054 0 R/Pages 2 0 R/OCProperties<</D<</RBGroups[]/ON[37 0 R 65 0 R 78 0 R 90 0 R 116 0 R 129 0 R 141 0 R 167 0 R 180 0 R 192 0 R 218 0 R 237 0 R 255 0 R 287 0 R 306 0 R 324 0 R 356 0 R 375 0 R 393 0 R 425 0 R 444 0 R 462 0 R 480 0 R 515 0 R 534 0 R 552 0 R 570 0 R 605 0 R 624 0 R 642 0 R 660 0 R 695 0 R 699 0 R 718 0 R 735 0 R 753 0 R 785 0 R 789 0 R 808 0 R 825 0 R 843 0 R 878 0 R 882 0 R 901 0 R 918 0 R 936 0 R 971 0 R 975 0 R 994 0 R 1011 0 R 1029 0 R]/OFF[15 0 R 27 0 R]/O [...]
endobj
1054 0 obj
<</Subtype/XML/Length 44482/Type/Metadata>>stream
+<?xpacket begin="" id="W5M0MpCehiHzreSzNTczkc9d"?>
+<x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="Adobe XMP Core 4.1-c036 46.277092, Fri Feb 23 2007 14:16:18        ">
+   <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
+      <rdf:Description rdf:about=""
+            xmlns:dc="http://purl.org/dc/elements/1.1/">
+         <dc:format>application/pdf</dc:format>
+         <dc:title>
+            <rdf:Alt>
+               <rdf:li xml:lang="x-default">Print</rdf:li>
+            </rdf:Alt>
+         </dc:title>
+      </rdf:Description>
+      <rdf:Description rdf:about=""
+            xmlns:xap="http://ns.adobe.com/xap/1.0/"
+            xmlns:xapGImg="http://ns.adobe.com/xap/1.0/g/img/">
+         <xap:CreatorTool>Adobe Illustrator CS3</xap:CreatorTool>
+         <xap:CreateDate>2009-11-23T17:10:12+01:00</xap:CreateDate>
+         <xap:ModifyDate>2010-04-13T20:05:12+02:00</xap:ModifyDate>
+         <xap:MetadataDate>2010-04-13T20:05:12+02:00</xap:MetadataDate>
+         <xap:Thumbnails>
+            <rdf:Alt>
+               <rdf:li rdf:parseType="Resource">
+                  <xapGImg:width>256</xapGImg:width>
+                  <xapGImg:height>208</xapGImg:height>
+                  <xapGImg:format>JPEG</xapGImg:format>
+                  <xapGImg:image>/9j/4AAQSkZJRgABAgEASABIAAD/7QAsUGhvdG9zaG9wIDMuMAA4QklNA+0AAAAAABAASAAAAAEA&#xA;AQBIAAAAAQAB/+4ADkFkb2JlAGTAAAAAAf/bAIQABgQEBAUEBgUFBgkGBQYJCwgGBggLDAoKCwoK&#xA;DBAMDAwMDAwQDA4PEA8ODBMTFBQTExwbGxscHx8fHx8fHx8fHwEHBwcNDA0YEBAYGhURFRofHx8f&#xA;Hx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8fHx8f/8AAEQgA0AEAAwER&#xA;AAIRAQMRAf/EAaIAAAAHAQEBAQEAAAAAAAAAAAQFAwIGAQAHCAkKCwEAAgIDAQEBAQEAAAAAAAAA&#xA;AQACAwQFBgcICQoLEAACAQMDAgQCBgcDBAIGAnMBAgMRBAAFIRIxQV [...]
+               </rdf:li>
+            </rdf:Alt>
+         </xap:Thumbnails>
+      </rdf:Description>
+      <rdf:Description rdf:about=""
+            xmlns:xapMM="http://ns.adobe.com/xap/1.0/mm/"
+            xmlns:stRef="http://ns.adobe.com/xap/1.0/sType/ResourceRef#">
+         <xapMM:DocumentID>uuid:89B13A64E5D9DE11BB37992E5642CB24</xapMM:DocumentID>
+         <xapMM:InstanceID>uuid:bce40ba9-528e-1a48-b1a0-2636e427f460</xapMM:InstanceID>
+         <xapMM:DerivedFrom rdf:parseType="Resource">
+            <stRef:instanceID>uuid:1052650b-0efc-4cb2-a32e-387095575b05</stRef:instanceID>
+            <stRef:documentID>uuid:6120892493BFDB11914A8590D31508C8</stRef:documentID>
+         </xapMM:DerivedFrom>
+      </rdf:Description>
+      <rdf:Description rdf:about=""
+            xmlns:illustrator="http://ns.adobe.com/illustrator/1.0/">
+         <illustrator:Type>Document</illustrator:Type>
+         <illustrator:StartupProfile>Print</illustrator:StartupProfile>
+      </rdf:Description>
+      <rdf:Description rdf:about=""
+            xmlns:xapTPg="http://ns.adobe.com/xap/1.0/t/pg/"
+            xmlns:stDim="http://ns.adobe.com/xap/1.0/sType/Dimensions#"
+            xmlns:stFnt="http://ns.adobe.com/xap/1.0/sType/Font#"
+            xmlns:xapG="http://ns.adobe.com/xap/1.0/g/">
+         <xapTPg:NPages>1</xapTPg:NPages>
+         <xapTPg:HasVisibleTransparency>False</xapTPg:HasVisibleTransparency>
+         <xapTPg:HasVisibleOverprint>False</xapTPg:HasVisibleOverprint>
+         <xapTPg:MaxPageSize rdf:parseType="Resource">
+            <stDim:w>841.889771</stDim:w>
+            <stDim:h>595.275574</stDim:h>
+            <stDim:unit>Pixels</stDim:unit>
+         </xapTPg:MaxPageSize>
+         <xapTPg:Fonts>
+            <rdf:Bag>
+               <rdf:li rdf:parseType="Resource">
+                  <stFnt:fontName>MyriadPro-Regular</stFnt:fontName>
+                  <stFnt:fontFamily>Myriad Pro</stFnt:fontFamily>
+                  <stFnt:fontFace>Regular</stFnt:fontFace>
+                  <stFnt:fontType>Open Type</stFnt:fontType>
+                  <stFnt:versionString>Version 2.007;PS 002.000;Core 1.0.38;makeotf.lib1.7.9032</stFnt:versionString>
+                  <stFnt:composite>False</stFnt:composite>
+                  <stFnt:fontFileName>MyriadPro-Regular.otf</stFnt:fontFileName>
+               </rdf:li>
+            </rdf:Bag>
+         </xapTPg:Fonts>
+         <xapTPg:PlateNames>
+            <rdf:Seq>
+               <rdf:li>Cyan</rdf:li>
+               <rdf:li>Magenta</rdf:li>
+               <rdf:li>Yellow</rdf:li>
+               <rdf:li>Black</rdf:li>
+            </rdf:Seq>
+         </xapTPg:PlateNames>
+         <xapTPg:SwatchGroups>
+            <rdf:Seq>
+               <rdf:li rdf:parseType="Resource">
+                  <xapG:groupName>Default Swatch Group</xapG:groupName>
+                  <xapG:groupType>0</xapG:groupType>
+                  <xapG:Colorants>
+                     <rdf:Seq>
+                        <rdf:li rdf:parseType="Resource">
+                           <xapG:swatchName>White</xapG:swatchName>
+                           <xapG:mode>RGB</xapG:mode>
+                           <xapG:type>PROCESS</xapG:type>
+                           <xapG:red>255</xapG:red>
+                           <xapG:green>255</xapG:green>
+                           <xapG:blue>255</xapG:blue>
+                        </rdf:li>
+                        <rdf:li rdf:parseType="Resource">
+                           <xapG:swatchName>Black</xapG:swatchName>
+                           <xapG:mode>RGB</xapG:mode>
+                           <xapG:type>PROCESS</xapG:type>
+                           <xapG:red>35</xapG:red>
+                           <xapG:green>31</xapG:green>
+                           <xapG:blue>32</xapG:blue>
+                        </rdf:li>
+                        <rdf:li rdf:parseType="Resource">
+                           <xapG:swatchName>CMYK Red</xapG:swatchName>
+                           <xapG:mode>RGB</xapG:mode>
+                           <xapG:type>PROCESS</xapG:type>
+                           <xapG:red>236</xapG:red>
+                           <xapG:green>28</xapG:green>
+                           <xapG:blue>36</xapG:blue>
+                        </rdf:li>
+                        <rdf:li rdf:parseType="Resource">
+                           <xapG:swatchName>CMYK Yellow</xapG:swatchName>
+                           <xapG:mode>RGB</xapG:mode>
+                           <xapG:type>PROCESS</xapG:type>
+                           <xapG:red>255</xapG:red>
+                           <xapG:green>241</xapG:green>
+                           <xapG:blue>0</xapG:blue>
+                        </rdf:li>
+                        <rdf:li rdf:parseType="Resource">
+                           <xapG:swatchName>CMYK Green</xapG:swatchName>
+                           <xapG:mode>RGB</xapG:mode>
+                           <xapG:type>PROCESS</xapG:type>
+                           <xapG:red>0</xapG:red>
+                           <xapG:green>165</xapG:green>
+                           <xapG:blue>81</xapG:blue>
+                        </rdf:li>
+                        <rdf:li rdf:parseType="Resource">
+                           <xapG:swatchName>CMYK Cyan</xapG:swatchName>
+                           <xapG:mode>RGB</xapG:mode>
+                           <xapG:type>PROCESS</xapG:type>
+                           <xapG:red>0</xapG:red>
+                           <xapG:green>173</xapG:green>
+                           <xapG:blue>238</xapG:blue>
+                        </rdf:li>
+                        <rdf:li rdf:parseType="Resource">
+                           <xapG:swatchName>CMYK Blue</xapG:swatchName>
+                           <xapG:mode>RGB</xapG:mode>
+                           <xapG:type>PROCESS</xapG:type>
+                           <xapG:red>46</xapG:red>
+                           <xapG:green>49</xapG:green>
+                           <xapG:blue>145</xapG:blue>
+                        </rdf:li>
+                        <rdf:li rdf:parseType="Resource">
+                           <xapG:swatchName>CMYK Magenta</xapG:swatchName>
+                           <xapG:mode>RGB</xapG:mode>
+                           <xapG:type>PROCESS</xapG:type>
+                           <xapG:red>235</xapG:red>
+                           <xapG:green>0</xapG:green>
+                           <xapG:blue>139</xapG:blue>
+                        </rdf:li>
+                        <rdf:li rdf:parseType="Resource">
+                           <xapG:swatchName>C=16 M=98 Y=92 K=7</xapG:swatchName>
+                           <xapG:mode>RGB</xapG:mode>
+                           <xapG:type>PROCESS</xapG:type>
+                           <xapG:red>194</xapG:red>
+                           <xapG:green>39</xapG:green>
+                           <xapG:blue>45</xapG:blue>
+                        </rdf:li>
+                        <rdf:li rdf:parseType="Resource">
+                           <xapG:swatchName>C=0 M=99 Y=97 K=0</xapG:swatchName>
+                           <xapG:mode>RGB</xapG:mode>
+                           <xapG:type>PROCESS</xapG:type>
+                           <xapG:red>236</xapG:red>
+                           <xapG:green>32</xapG:green>
+                           <xapG:blue>39</xapG:blue>
+                        </rdf:li>
+                        <rdf:li rdf:parseType="Resource">
+                           <xapG:swatchName>C=0 M=79 Y=96 K=0</xapG:swatchName>
+                           <xapG:mode>RGB</xapG:mode>
+                           <xapG:type>PROCESS</xapG:type>
+                           <xapG:red>240</xapG:red>
+                           <xapG:green>92</xapG:green>
+                           <xapG:blue>39</xapG:blue>
+                        </rdf:li>
+                        <rdf:li rdf:parseType="Resource">
+                           <xapG:swatchName>C=0 M=50 Y=98 K=0</xapG:swatchName>
+                           <xapG:mode>RGB</xapG:mode>
+                           <xapG:type>PROCESS</xapG:type>
+                           <xapG:red>246</xapG:red>
+                           <xapG:green>146</xapG:green>
+                           <xapG:blue>33</xapG:blue>
+                        </rdf:li>
+                        <rdf:li rdf:parseType="Resource">
+                           <xapG:swatchName>C=0 M=35 Y=87 K=0</xapG:swatchName>
+                           <xapG:mode>RGB</xapG:mode>
+                           <xapG:type>PROCESS</xapG:type>
+                           <xapG:red>250</xapG:red>
+                           <xapG:green>175</xapG:green>
+                           <xapG:blue>59</xapG:blue>
+                        </rdf:li>
+                        <rdf:li rdf:parseType="Resource">
+                           <xapG:swatchName>C=5 M=0 Y=93 K=0</xapG:swatchName>
+                           <xapG:mode>RGB</xapG:mode>
+                           <xapG:type>PROCESS</xapG:type>
+                           <xapG:red>249</xapG:red>
+                           <xapG:green>236</xapG:green>
+                           <xapG:blue>35</xapG:blue>
+                        </rdf:li>
+                        <rdf:li rdf:parseType="Resource">
+                           <xapG:swatchName>C=19 M=0 Y=98 K=0</xapG:swatchName>
+                           <xapG:mode>RGB</xapG:mode>
+                           <xapG:type>PROCESS</xapG:type>
+                           <xapG:red>216</xapG:red>
+                           <xapG:green>223</xapG:green>
+                           <xapG:blue>39</xapG:blue>
+                        </rdf:li>
+                        <rdf:li rdf:parseType="Resource">
+                           <xapG:swatchName>C=50 M=0 Y=99 K=0</xapG:swatchName>
+                           <xapG:mode>RGB</xapG:mode>
+                           <xapG:type>PROCESS</xapG:type>
+                           <xapG:red>139</xapG:red>
+                           <xapG:green>197</xapG:green>
+                           <xapG:blue>64</xapG:blue>
+                        </rdf:li>
+                        <rdf:li rdf:parseType="Resource">
+                           <xapG:swatchName>C=74 M=0 Y=99 K=0</xapG:swatchName>
+                           <xapG:mode>RGB</xapG:mode>
+                           <xapG:type>PROCESS</xapG:type>
+                           <xapG:red>61</xapG:red>
+                           <xapG:green>180</xapG:green>
+                           <xapG:blue>74</xapG:blue>
+                        </rdf:li>
+                        <rdf:li rdf:parseType="Resource">
+                           <xapG:swatchName>C=86 M=12 Y=100 K=9</xapG:swatchName>
+                           <xapG:mode>RGB</xapG:mode>
+                           <xapG:type>PROCESS</xapG:type>
+                           <xapG:red>0</xapG:red>
+                           <xapG:green>146</xapG:green>
+                           <xapG:blue>69</xapG:blue>
+                        </rdf:li>
+                        <rdf:li rdf:parseType="Resource">
+                           <xapG:swatchName>C=88 M=28 Y=95 K=32</xapG:swatchName>
+                           <xapG:mode>RGB</xapG:mode>
+                           <xapG:type>PROCESS</xapG:type>
+                           <xapG:red>0</xapG:red>
+                           <xapG:green>104</xapG:green>
+                           <xapG:blue>55</xapG:blue>
+                        </rdf:li>
+                        <rdf:li rdf:parseType="Resource">
+                           <xapG:swatchName>C=76 M=0 Y=75 K=0</xapG:swatchName>
+                           <xapG:mode>RGB</xapG:mode>
+                           <xapG:type>PROCESS</xapG:type>
+                           <xapG:red>34</xapG:red>
+                           <xapG:green>180</xapG:green>
+                           <xapG:blue>115</xapG:blue>
+                        </rdf:li>
+                        <rdf:li rdf:parseType="Resource">
+                           <xapG:swatchName>C=78 M=9 Y=46 K=0</xapG:swatchName>
+                           <xapG:mode>RGB</xapG:mode>
+                           <xapG:type>PROCESS</xapG:type>
+                           <xapG:red>3</xapG:red>
+                           <xapG:green>168</xapG:green>
+                           <xapG:blue>156</xapG:blue>
+                        </rdf:li>
+                        <rdf:li rdf:parseType="Resource">
+                           <xapG:swatchName>C=70 M=15 Y=0 K=0</xapG:swatchName>
+                           <xapG:mode>RGB</xapG:mode>
+                           <xapG:type>PROCESS</xapG:type>
+                           <xapG:red>37</xapG:red>
+                           <xapG:green>169</xapG:green>
+                           <xapG:blue>224</xapG:blue>
+                        </rdf:li>
+                        <rdf:li rdf:parseType="Resource">
+                           <xapG:swatchName>C=87 M=52 Y=0 K=0</xapG:swatchName>
+                           <xapG:mode>RGB</xapG:mode>
+                           <xapG:type>PROCESS</xapG:type>
+                           <xapG:red>16</xapG:red>
+                           <xapG:green>114</xapG:green>
+                           <xapG:blue>185</xapG:blue>
+                        </rdf:li>
+                        <rdf:li rdf:parseType="Resource">
+                           <xapG:swatchName>C=99 M=96 Y=4 K=0</xapG:swatchName>
+                           <xapG:mode>RGB</xapG:mode>
+                           <xapG:type>PROCESS</xapG:type>
+                           <xapG:red>46</xapG:red>
+                           <xapG:green>55</xapG:green>
+                           <xapG:blue>143</xapG:blue>
+                        </rdf:li>
+                        <rdf:li rdf:parseType="Resource">
+                           <xapG:swatchName>C=100 M=100 Y=26 K=25</xapG:swatchName>
+                           <xapG:mode>RGB</xapG:mode>
+                           <xapG:type>PROCESS</xapG:type>
+                           <xapG:red>38</xapG:red>
+                           <xapG:green>34</xapG:green>
+                           <xapG:blue>97</xapG:blue>
+                        </rdf:li>
+                        <rdf:li rdf:parseType="Resource">
+                           <xapG:swatchName>C=74 M=98 Y=1 K=0</xapG:swatchName>
+                           <xapG:mode>RGB</xapG:mode>
+                           <xapG:type>PROCESS</xapG:type>
+                           <xapG:red>103</xapG:red>
+                           <xapG:green>48</xapG:green>
+                           <xapG:blue>144</xapG:blue>
+                        </rdf:li>
+                        <rdf:li rdf:parseType="Resource">
+                           <xapG:swatchName>C=49 M=99 Y=1 K=0</xapG:swatchName>
+                           <xapG:mode>RGB</xapG:mode>
+                           <xapG:type>PROCESS</xapG:type>
+                           <xapG:red>146</xapG:red>
+                           <xapG:green>41</xapG:green>
+                           <xapG:blue>141</xapG:blue>
+                        </rdf:li>
+                        <rdf:li rdf:parseType="Resource">
+                           <xapG:swatchName>C=34 M=100 Y=37 K=11</xapG:swatchName>
+                           <xapG:mode>RGB</xapG:mode>
+                           <xapG:type>PROCESS</xapG:type>
+                           <xapG:red>157</xapG:red>
+                           <xapG:green>30</xapG:green>
+                           <xapG:blue>96</xapG:blue>
+                        </rdf:li>
+                        <rdf:li rdf:parseType="Resource">
+                           <xapG:swatchName>C=12 M=100 Y=49 K=1</xapG:swatchName>
+                           <xapG:mode>RGB</xapG:mode>
+                           <xapG:type>PROCESS</xapG:type>
+                           <xapG:red>211</xapG:red>
+                           <xapG:green>28</xapG:green>
+                           <xapG:blue>92</xapG:blue>
+                        </rdf:li>
+                        <rdf:li rdf:parseType="Resource">
+                           <xapG:swatchName>C=0 M=96 Y=20 K=0</xapG:swatchName>
+                           <xapG:mode>RGB</xapG:mode>
+                           <xapG:type>PROCESS</xapG:type>
+                           <xapG:red>236</xapG:red>
+                           <xapG:green>37</xapG:green>
+                           <xapG:blue>122</xapG:blue>
+                        </rdf:li>
+                        <rdf:li rdf:parseType="Resource">
+                           <xapG:swatchName>C=23 M=27 Y=40 K=0</xapG:swatchName>
+                           <xapG:mode>RGB</xapG:mode>
+                           <xapG:type>PROCESS</xapG:type>
+                           <xapG:red>198</xapG:red>
+                           <xapG:green>178</xapG:green>
+                           <xapG:blue>152</xapG:blue>
+                        </rdf:li>
+                        <rdf:li rdf:parseType="Resource">
+                           <xapG:swatchName>C=40 M=43 Y=52 K=7</xapG:swatchName>
+                           <xapG:mode>RGB</xapG:mode>
+                           <xapG:type>PROCESS</xapG:type>
+                           <xapG:red>152</xapG:red>
+                           <xapG:green>133</xapG:green>
+                           <xapG:blue>118</xapG:blue>
+                        </rdf:li>
+                        <rdf:li rdf:parseType="Resource">
+                           <xapG:swatchName>C=50 M=53 Y=61 K=23</xapG:swatchName>
+                           <xapG:mode>RGB</xapG:mode>
+                           <xapG:type>PROCESS</xapG:type>
+                           <xapG:red>117</xapG:red>
+                           <xapG:green>101</xapG:green>
+                           <xapG:blue>88</xapG:blue>
+                        </rdf:li>
+                        <rdf:li rdf:parseType="Resource">
+                           <xapG:swatchName>C=57 M=60 Y=64 K=42</xapG:swatchName>
+                           <xapG:mode>RGB</xapG:mode>
+                           <xapG:type>PROCESS</xapG:type>
+                           <xapG:red>85</xapG:red>
+                           <xapG:green>72</xapG:green>
+                           <xapG:blue>65</xapG:blue>
+                        </rdf:li>
+                        <rdf:li rdf:parseType="Resource">
+                           <xapG:swatchName>C=23 M=38 Y=63 K=1</xapG:swatchName>
+                           <xapG:mode>RGB</xapG:mode>
+                           <xapG:type>PROCESS</xapG:type>
+                           <xapG:red>197</xapG:red>
+                           <xapG:green>156</xapG:green>
+                           <xapG:blue>110</xapG:blue>
+                        </rdf:li>
+                        <rdf:li rdf:parseType="Resource">
+                           <xapG:swatchName>C=32 M=49 Y=74 K=10</xapG:swatchName>
+                           <xapG:mode>RGB</xapG:mode>
+                           <xapG:type>PROCESS</xapG:type>
+                           <xapG:red>165</xapG:red>
+                           <xapG:green>124</xapG:green>
+                           <xapG:blue>82</xapG:blue>
+                        </rdf:li>
+                        <rdf:li rdf:parseType="Resource">
+                           <xapG:swatchName>C=36 M=57 Y=84 K=23</xapG:swatchName>
+                           <xapG:mode>RGB</xapG:mode>
+                           <xapG:type>PROCESS</xapG:type>
+                           <xapG:red>139</xapG:red>
+                           <xapG:green>99</xapG:green>
+                           <xapG:blue>57</xapG:blue>
+                        </rdf:li>
+                        <rdf:li rdf:parseType="Resource">
+                           <xapG:swatchName>C=39 M=64 Y=93 K=36</xapG:swatchName>
+                           <xapG:mode>RGB</xapG:mode>
+                           <xapG:type>PROCESS</xapG:type>
+                           <xapG:red>117</xapG:red>
+                           <xapG:green>77</xapG:green>
+                           <xapG:blue>36</xapG:blue>
+                        </rdf:li>
+                        <rdf:li rdf:parseType="Resource">
+                           <xapG:swatchName>C=41 M=70 Y=96 K=49</xapG:swatchName>
+                           <xapG:mode>RGB</xapG:mode>
+                           <xapG:type>PROCESS</xapG:type>
+                           <xapG:red>97</xapG:red>
+                           <xapG:green>57</xapG:green>
+                           <xapG:blue>23</xapG:blue>
+                        </rdf:li>
+                        <rdf:li rdf:parseType="Resource">
+                           <xapG:swatchName>C=47 M=73 Y=83 K=68</xapG:swatchName>
+                           <xapG:mode>RGB</xapG:mode>
+                           <xapG:type>PROCESS</xapG:type>
+                           <xapG:red>65</xapG:red>
+                           <xapG:green>35</xapG:green>
+                           <xapG:blue>18</xapG:blue>
+                        </rdf:li>
+                     </rdf:Seq>
+                  </xapG:Colorants>
+               </rdf:li>
+               <rdf:li rdf:parseType="Resource">
+                  <xapG:groupName>Print Color Group</xapG:groupName>
+                  <xapG:groupType>1</xapG:groupType>
+                  <xapG:Colorants>
+                     <rdf:Seq>
+                        <rdf:li rdf:parseType="Resource">
+                           <xapG:swatchName>C=2 M=28 Y=72 K=0</xapG:swatchName>
+                           <xapG:mode>RGB</xapG:mode>
+                           <xapG:type>PROCESS</xapG:type>
+                           <xapG:red>246</xapG:red>
+                           <xapG:green>187</xapG:green>
+                           <xapG:blue>96</xapG:blue>
+                        </rdf:li>
+                        <rdf:li rdf:parseType="Resource">
+                           <xapG:swatchName>C=5 M=70 Y=90 K=0</xapG:swatchName>
+                           <xapG:mode>RGB</xapG:mode>
+                           <xapG:type>PROCESS</xapG:type>
+                           <xapG:red>231</xapG:red>
+                           <xapG:green>110</xapG:green>
+                           <xapG:blue>52</xapG:blue>
+                        </rdf:li>
+                        <rdf:li rdf:parseType="Resource">
+                           <xapG:swatchName>C=4 M=92 Y=77 K=0</xapG:swatchName>
+                           <xapG:mode>RGB</xapG:mode>
+                           <xapG:type>PROCESS</xapG:type>
+                           <xapG:red>229</xapG:red>
+                           <xapG:green>59</xapG:green>
+                           <xapG:blue>65</xapG:blue>
+                        </rdf:li>
+                        <rdf:li rdf:parseType="Resource">
+                           <xapG:swatchName>C=29 M=2 Y=92 K=0</xapG:swatchName>
+                           <xapG:mode>RGB</xapG:mode>
+                           <xapG:type>PROCESS</xapG:type>
+                           <xapG:red>191</xapG:red>
+                           <xapG:green>210</xapG:green>
+                           <xapG:blue>65</xapG:blue>
+                        </rdf:li>
+                        <rdf:li rdf:parseType="Resource">
+                           <xapG:swatchName>C=62 M=4 Y=93 K=0</xapG:swatchName>
+                           <xapG:mode>RGB</xapG:mode>
+                           <xapG:type>PROCESS</xapG:type>
+                           <xapG:red>109</xapG:red>
+                           <xapG:green>182</xapG:green>
+                           <xapG:blue>78</xapG:blue>
+                        </rdf:li>
+                        <rdf:li rdf:parseType="Resource">
+                           <xapG:swatchName>C=30 M=2 Y=7 K=0</xapG:swatchName>
+                           <xapG:mode>RGB</xapG:mode>
+                           <xapG:type>PROCESS</xapG:type>
+                           <xapG:red>174</xapG:red>
+                           <xapG:green>218</xapG:green>
+                           <xapG:blue>230</xapG:blue>
+                        </rdf:li>
+                        <rdf:li rdf:parseType="Resource">
+                           <xapG:swatchName>C=60 M=8 Y=5 K=0</xapG:swatchName>
+                           <xapG:mode>RGB</xapG:mode>
+                           <xapG:type>PROCESS</xapG:type>
+                           <xapG:red>85</xapG:red>
+                           <xapG:green>185</xapG:green>
+                           <xapG:blue>223</xapG:blue>
+                        </rdf:li>
+                        <rdf:li rdf:parseType="Resource">
+                           <xapG:swatchName>C=78 M=4 Y=11 K=0</xapG:swatchName>
+                           <xapG:mode>RGB</xapG:mode>
+                           <xapG:type>PROCESS</xapG:type>
+                           <xapG:red>0</xapG:red>
+                           <xapG:green>178</xapG:green>
+                           <xapG:blue>215</xapG:blue>
+                        </rdf:li>
+                     </rdf:Seq>
+                  </xapG:Colorants>
+               </rdf:li>
+               <rdf:li rdf:parseType="Resource">
+                  <xapG:groupName>Grayscale</xapG:groupName>
+                  <xapG:groupType>1</xapG:groupType>
+                  <xapG:Colorants>
+                     <rdf:Seq>
+                        <rdf:li rdf:parseType="Resource">
+                           <xapG:swatchName>K=100</xapG:swatchName>
+                           <xapG:mode>GRAY</xapG:mode>
+                           <xapG:type>PROCESS</xapG:type>
+                           <xapG:gray>255</xapG:gray>
+                        </rdf:li>
+                        <rdf:li rdf:parseType="Resource">
+                           <xapG:swatchName>K=90</xapG:swatchName>
+                           <xapG:mode>GRAY</xapG:mode>
+                           <xapG:type>PROCESS</xapG:type>
+                           <xapG:gray>229</xapG:gray>
+                        </rdf:li>
+                        <rdf:li rdf:parseType="Resource">
+                           <xapG:swatchName>K=80</xapG:swatchName>
+                           <xapG:mode>GRAY</xapG:mode>
+                           <xapG:type>PROCESS</xapG:type>
+                           <xapG:gray>203</xapG:gray>
+                        </rdf:li>
+                        <rdf:li rdf:parseType="Resource">
+                           <xapG:swatchName>K=70</xapG:swatchName>
+                           <xapG:mode>GRAY</xapG:mode>
+                           <xapG:type>PROCESS</xapG:type>
+                           <xapG:gray>178</xapG:gray>
+                        </rdf:li>
+                        <rdf:li rdf:parseType="Resource">
+                           <xapG:swatchName>K=60</xapG:swatchName>
+                           <xapG:mode>GRAY</xapG:mode>
+                           <xapG:type>PROCESS</xapG:type>
+                           <xapG:gray>152</xapG:gray>
+                        </rdf:li>
+                        <rdf:li rdf:parseType="Resource">
+                           <xapG:swatchName>K=50</xapG:swatchName>
+                           <xapG:mode>GRAY</xapG:mode>
+                           <xapG:type>PROCESS</xapG:type>
+                           <xapG:gray>127</xapG:gray>
+                        </rdf:li>
+                        <rdf:li rdf:parseType="Resource">
+                           <xapG:swatchName>K=40</xapG:swatchName>
+                           <xapG:mode>GRAY</xapG:mode>
+                           <xapG:type>PROCESS</xapG:type>
+                           <xapG:gray>101</xapG:gray>
+                        </rdf:li>
+                        <rdf:li rdf:parseType="Resource">
+                           <xapG:swatchName>K=30</xapG:swatchName>
+                           <xapG:mode>GRAY</xapG:mode>
+                           <xapG:type>PROCESS</xapG:type>
+                           <xapG:gray>76</xapG:gray>
+                        </rdf:li>
+                        <rdf:li rdf:parseType="Resource">
+                           <xapG:swatchName>K=20</xapG:swatchName>
+                           <xapG:mode>GRAY</xapG:mode>
+                           <xapG:type>PROCESS</xapG:type>
+                           <xapG:gray>50</xapG:gray>
+                        </rdf:li>
+                        <rdf:li rdf:parseType="Resource">
+                           <xapG:swatchName>K=10</xapG:swatchName>
+                           <xapG:mode>GRAY</xapG:mode>
+                           <xapG:type>PROCESS</xapG:type>
+                           <xapG:gray>25</xapG:gray>
+                        </rdf:li>
+                        <rdf:li rdf:parseType="Resource">
+                           <xapG:swatchName>K=5</xapG:swatchName>
+                           <xapG:mode>GRAY</xapG:mode>
+                           <xapG:type>PROCESS</xapG:type>
+                           <xapG:gray>12</xapG:gray>
+                        </rdf:li>
+                     </rdf:Seq>
+                  </xapG:Colorants>
+               </rdf:li>
+            </rdf:Seq>
+         </xapTPg:SwatchGroups>
+      </rdf:Description>
+   </rdf:RDF>
+</x:xmpmeta>
+                                                                                                    
+                                                                                                    
+                                                                                                    
+                                                                                                    
+                                                                                                    
+                                                                                                    
+                                                                                                    
+                                                                                                    
+                                                                                                    
+                                                                                                    
+                                                                                                    
+                                                                                                    
+                                                                                                    
+                                                                                                    
+                                                                                                    
+                                                                                                    
+                                                                                                    
+                                                                                                    
+                                                                                                    
+                                                                                                    
+                           
+<?xpacket end="w"?>
endstream
endobj
2 0 obj
<</Count 1/Type/Pages/Kids[5 0 R]>>
endobj
15 0 obj
<</Intent 16 0 R/Usage 17 0 R/Name(Class)/Type/OCG>>
endobj
27 0 obj
<</Intent 28 0 R/Usage 29 0 R/Name(Package)/Type/OCG>>
endobj
37 0 obj
<</Intent 38 0 R/Usage 39 0 R/Name(Object)/Type/OCG>>
endobj
65 0 obj
<</Intent 66 0 R/Usage 67 0 R/Name(Class)/Type/OCG>>
endobj
78 0 obj
<</Intent 79 0 R/Usage 80 0 R/Name(Package)/Type/OCG>>
endobj
90 0 obj
<</Intent 91 0 R/Usage 92 0 R/Name(Object)/Type/OCG>>
endobj
116 0 obj
<</Intent 117 0 R/Usage 118 0 R/Name(Class)/Type/OCG>>
endobj
129 0 obj
<</Intent 130 0 R/Usage 131 0 R/Name(Package)/Type/OCG>>
endobj
141 0 obj
<</Intent 142 0 R/Usage 143 0 R/Name(Object)/Type/OCG>>
endobj
167 0 obj
<</Intent 168 0 R/Usage 169 0 R/Name(Class)/Type/OCG>>
endobj
180 0 obj
<</Intent 181 0 R/Usage 182 0 R/Name(Package)/Type/OCG>>
endobj
192 0 obj
<</Intent 193 0 R/Usage 194 0 R/Name(Object)/Type/OCG>>
endobj
218 0 obj
<</Intent 219 0 R/Usage 220 0 R/Name(Class)/Type/OCG>>
endobj
237 0 obj
<</Intent 238 0 R/Usage 239 0 R/Name(Package)/Type/OCG>>
endobj
255 0 obj
<</Intent 256 0 R/Usage 257 0 R/Name(Object)/Type/OCG>>
endobj
287 0 obj
<</Intent 288 0 R/Usage 289 0 R/Name(Class)/Type/OCG>>
endobj
306 0 obj
<</Intent 307 0 R/Usage 308 0 R/Name(Package)/Type/OCG>>
endobj
324 0 obj
<</Intent 325 0 R/Usage 326 0 R/Name(Object)/Type/OCG>>
endobj
356 0 obj
<</Intent 357 0 R/Usage 358 0 R/Name(Class)/Type/OCG>>
endobj
375 0 obj
<</Intent 376 0 R/Usage 377 0 R/Name(Package)/Type/OCG>>
endobj
393 0 obj
<</Intent 394 0 R/Usage 395 0 R/Name(Object)/Type/OCG>>
endobj
425 0 obj
<</Intent 426 0 R/Usage 427 0 R/Name(Class)/Type/OCG>>
endobj
444 0 obj
<</Intent 445 0 R/Usage 446 0 R/Name(Trait)/Type/OCG>>
endobj
462 0 obj
<</Intent 463 0 R/Usage 464 0 R/Name(Package)/Type/OCG>>
endobj
480 0 obj
<</Intent 481 0 R/Usage 482 0 R/Name(Object)/Type/OCG>>
endobj
515 0 obj
<</Intent 516 0 R/Usage 517 0 R/Name(Class)/Type/OCG>>
endobj
534 0 obj
<</Intent 535 0 R/Usage 536 0 R/Name(Trait)/Type/OCG>>
endobj
552 0 obj
<</Intent 553 0 R/Usage 554 0 R/Name(Package)/Type/OCG>>
endobj
570 0 obj
<</Intent 571 0 R/Usage 572 0 R/Name(Object)/Type/OCG>>
endobj
605 0 obj
<</Intent 606 0 R/Usage 607 0 R/Name(Class)/Type/OCG>>
endobj
624 0 obj
<</Intent 625 0 R/Usage 626 0 R/Name(Trait)/Type/OCG>>
endobj
642 0 obj
<</Intent 643 0 R/Usage 644 0 R/Name(Package)/Type/OCG>>
endobj
660 0 obj
<</Intent 661 0 R/Usage 662 0 R/Name(Object)/Type/OCG>>
endobj
695 0 obj
<</Intent 696 0 R/Usage 697 0 R/Name(Base)/Type/OCG>>
endobj
699 0 obj
<</Intent 700 0 R/Usage 701 0 R/Name(Class)/Type/OCG>>
endobj
718 0 obj
<</Intent 719 0 R/Usage 720 0 R/Name(Trait)/Type/OCG>>
endobj
735 0 obj
<</Intent 736 0 R/Usage 737 0 R/Name(Package)/Type/OCG>>
endobj
753 0 obj
<</Intent 754 0 R/Usage 755 0 R/Name(Object)/Type/OCG>>
endobj
785 0 obj
<</Intent 786 0 R/Usage 787 0 R/Name(Base)/Type/OCG>>
endobj
789 0 obj
<</Intent 790 0 R/Usage 791 0 R/Name(Class)/Type/OCG>>
endobj
808 0 obj
<</Intent 809 0 R/Usage 810 0 R/Name(Trait)/Type/OCG>>
endobj
825 0 obj
<</Intent 826 0 R/Usage 827 0 R/Name(Package)/Type/OCG>>
endobj
843 0 obj
<</Intent 844 0 R/Usage 845 0 R/Name(Object)/Type/OCG>>
endobj
878 0 obj
<</Intent 879 0 R/Usage 880 0 R/Name(Base)/Type/OCG>>
endobj
882 0 obj
<</Intent 883 0 R/Usage 884 0 R/Name(Class)/Type/OCG>>
endobj
901 0 obj
<</Intent 902 0 R/Usage 903 0 R/Name(Trait)/Type/OCG>>
endobj
918 0 obj
<</Intent 919 0 R/Usage 920 0 R/Name(Package)/Type/OCG>>
endobj
936 0 obj
<</Intent 937 0 R/Usage 938 0 R/Name(Object)/Type/OCG>>
endobj
971 0 obj
<</Intent 972 0 R/Usage 973 0 R/Name(Base)/Type/OCG>>
endobj
975 0 obj
<</Intent 976 0 R/Usage 977 0 R/Name(Class)/Type/OCG>>
endobj
994 0 obj
<</Intent 995 0 R/Usage 996 0 R/Name(Trait)/Type/OCG>>
endobj
1011 0 obj
<</Intent 1012 0 R/Usage 1013 0 R/Name(Package)/Type/OCG>>
endobj
1029 0 obj
<</Intent 1030 0 R/Usage 1031 0 R/Name(Object)/Type/OCG>>
endobj
1030 0 obj
[/View/Design]
endobj
1031 0 obj
<</CreatorInfo<</Subtype/Artwork/Creator(Adobe Illustrator 13.0)>>>>
endobj
1012 0 obj
[/View/Design]
endobj
1013 0 obj
<</CreatorInfo<</Subtype/Artwork/Creator(Adobe Illustrator 13.0)>>>>
endobj
995 0 obj
[/View/Design]
endobj
996 0 obj
<</CreatorInfo<</Subtype/Artwork/Creator(Adobe Illustrator 13.0)>>>>
endobj
976 0 obj
[/View/Design]
endobj
977 0 obj
<</CreatorInfo<</Subtype/Artwork/Creator(Adobe Illustrator 13.0)>>>>
endobj
972 0 obj
[/View/Design]
endobj
973 0 obj
<</CreatorInfo<</Subtype/Artwork/Creator(Adobe Illustrator 13.0)>>>>
endobj
937 0 obj
[/View/Design]
endobj
938 0 obj
<</CreatorInfo<</Subtype/Artwork/Creator(Adobe Illustrator 13.0)>>>>
endobj
919 0 obj
[/View/Design]
endobj
920 0 obj
<</CreatorInfo<</Subtype/Artwork/Creator(Adobe Illustrator 13.0)>>>>
endobj
902 0 obj
[/View/Design]
endobj
903 0 obj
<</CreatorInfo<</Subtype/Artwork/Creator(Adobe Illustrator 13.0)>>>>
endobj
883 0 obj
[/View/Design]
endobj
884 0 obj
<</CreatorInfo<</Subtype/Artwork/Creator(Adobe Illustrator 13.0)>>>>
endobj
879 0 obj
[/View/Design]
endobj
880 0 obj
<</CreatorInfo<</Subtype/Artwork/Creator(Adobe Illustrator 13.0)>>>>
endobj
844 0 obj
[/View/Design]
endobj
845 0 obj
<</CreatorInfo<</Subtype/Artwork/Creator(Adobe Illustrator 13.0)>>>>
endobj
826 0 obj
[/View/Design]
endobj
827 0 obj
<</CreatorInfo<</Subtype/Artwork/Creator(Adobe Illustrator 13.0)>>>>
endobj
809 0 obj
[/View/Design]
endobj
810 0 obj
<</CreatorInfo<</Subtype/Artwork/Creator(Adobe Illustrator 13.0)>>>>
endobj
790 0 obj
[/View/Design]
endobj
791 0 obj
<</CreatorInfo<</Subtype/Artwork/Creator(Adobe Illustrator 13.0)>>>>
endobj
786 0 obj
[/View/Design]
endobj
787 0 obj
<</CreatorInfo<</Subtype/Artwork/Creator(Adobe Illustrator 13.0)>>>>
endobj
754 0 obj
[/View/Design]
endobj
755 0 obj
<</CreatorInfo<</Subtype/Artwork/Creator(Adobe Illustrator 13.0)>>>>
endobj
736 0 obj
[/View/Design]
endobj
737 0 obj
<</CreatorInfo<</Subtype/Artwork/Creator(Adobe Illustrator 13.0)>>>>
endobj
719 0 obj
[/View/Design]
endobj
720 0 obj
<</CreatorInfo<</Subtype/Artwork/Creator(Adobe Illustrator 13.0)>>>>
endobj
700 0 obj
[/View/Design]
endobj
701 0 obj
<</CreatorInfo<</Subtype/Artwork/Creator(Adobe Illustrator 13.0)>>>>
endobj
696 0 obj
[/View/Design]
endobj
697 0 obj
<</CreatorInfo<</Subtype/Artwork/Creator(Adobe Illustrator 13.0)>>>>
endobj
661 0 obj
[/View/Design]
endobj
662 0 obj
<</CreatorInfo<</Subtype/Artwork/Creator(Adobe Illustrator 13.0)>>>>
endobj
643 0 obj
[/View/Design]
endobj
644 0 obj
<</CreatorInfo<</Subtype/Artwork/Creator(Adobe Illustrator 13.0)>>>>
endobj
625 0 obj
[/View/Design]
endobj
626 0 obj
<</CreatorInfo<</Subtype/Artwork/Creator(Adobe Illustrator 13.0)>>>>
endobj
606 0 obj
[/View/Design]
endobj
607 0 obj
<</CreatorInfo<</Subtype/Artwork/Creator(Adobe Illustrator 13.0)>>>>
endobj
571 0 obj
[/View/Design]
endobj
572 0 obj
<</CreatorInfo<</Subtype/Artwork/Creator(Adobe Illustrator 13.0)>>>>
endobj
553 0 obj
[/View/Design]
endobj
554 0 obj
<</CreatorInfo<</Subtype/Artwork/Creator(Adobe Illustrator 13.0)>>>>
endobj
535 0 obj
[/View/Design]
endobj
536 0 obj
<</CreatorInfo<</Subtype/Artwork/Creator(Adobe Illustrator 13.0)>>>>
endobj
516 0 obj
[/View/Design]
endobj
517 0 obj
<</CreatorInfo<</Subtype/Artwork/Creator(Adobe Illustrator 13.0)>>>>
endobj
481 0 obj
[/View/Design]
endobj
482 0 obj
<</CreatorInfo<</Subtype/Artwork/Creator(Adobe Illustrator 13.0)>>>>
endobj
463 0 obj
[/View/Design]
endobj
464 0 obj
<</CreatorInfo<</Subtype/Artwork/Creator(Adobe Illustrator 13.0)>>>>
endobj
445 0 obj
[/View/Design]
endobj
446 0 obj
<</CreatorInfo<</Subtype/Artwork/Creator(Adobe Illustrator 13.0)>>>>
endobj
426 0 obj
[/View/Design]
endobj
427 0 obj
<</CreatorInfo<</Subtype/Artwork/Creator(Adobe Illustrator 13.0)>>>>
endobj
394 0 obj
[/View/Design]
endobj
395 0 obj
<</CreatorInfo<</Subtype/Artwork/Creator(Adobe Illustrator 13.0)>>>>
endobj
376 0 obj
[/View/Design]
endobj
377 0 obj
<</CreatorInfo<</Subtype/Artwork/Creator(Adobe Illustrator 13.0)>>>>
endobj
357 0 obj
[/View/Design]
endobj
358 0 obj
<</CreatorInfo<</Subtype/Artwork/Creator(Adobe Illustrator 13.0)>>>>
endobj
325 0 obj
[/View/Design]
endobj
326 0 obj
<</CreatorInfo<</Subtype/Artwork/Creator(Adobe Illustrator 13.0)>>>>
endobj
307 0 obj
[/View/Design]
endobj
308 0 obj
<</CreatorInfo<</Subtype/Artwork/Creator(Adobe Illustrator 13.0)>>>>
endobj
288 0 obj
[/View/Design]
endobj
289 0 obj
<</CreatorInfo<</Subtype/Artwork/Creator(Adobe Illustrator 13.0)>>>>
endobj
256 0 obj
[/View/Design]
endobj
257 0 obj
<</CreatorInfo<</Subtype/Artwork/Creator(Adobe Illustrator 13.0)>>>>
endobj
238 0 obj
[/View/Design]
endobj
239 0 obj
<</CreatorInfo<</Subtype/Artwork/Creator(Adobe Illustrator 13.0)>>>>
endobj
219 0 obj
[/View/Design]
endobj
220 0 obj
<</CreatorInfo<</Subtype/Artwork/Creator(Adobe Illustrator 13.0)>>>>
endobj
193 0 obj
[/View/Design]
endobj
194 0 obj
<</CreatorInfo<</Subtype/Artwork/Creator(Adobe Illustrator 13.0)>>>>
endobj
181 0 obj
[/View/Design]
endobj
182 0 obj
<</CreatorInfo<</Subtype/Artwork/Creator(Adobe Illustrator 13.0)>>>>
endobj
168 0 obj
[/View/Design]
endobj
169 0 obj
<</CreatorInfo<</Subtype/Artwork/Creator(Adobe Illustrator 13.0)>>>>
endobj
142 0 obj
[/View/Design]
endobj
143 0 obj
<</CreatorInfo<</Subtype/Artwork/Creator(Adobe Illustrator 13.0)>>>>
endobj
130 0 obj
[/View/Design]
endobj
131 0 obj
<</CreatorInfo<</Subtype/Artwork/Creator(Adobe Illustrator 13.0)>>>>
endobj
117 0 obj
[/View/Design]
endobj
118 0 obj
<</CreatorInfo<</Subtype/Artwork/Creator(Adobe Illustrator 13.0)>>>>
endobj
91 0 obj
[/View/Design]
endobj
92 0 obj
<</CreatorInfo<</Subtype/Artwork/Creator(Adobe Illustrator 13.0)>>>>
endobj
79 0 obj
[/View/Design]
endobj
80 0 obj
<</CreatorInfo<</Subtype/Artwork/Creator(Adobe Illustrator 13.0)>>>>
endobj
66 0 obj
[/View/Design]
endobj
67 0 obj
<</CreatorInfo<</Subtype/Artwork/Creator(Adobe Illustrator 13.0)>>>>
endobj
38 0 obj
[/View/Design]
endobj
39 0 obj
<</CreatorInfo<</Subtype/Artwork/Creator(Adobe Illustrator 13.0)>>>>
endobj
28 0 obj
[/View/Design]
endobj
29 0 obj
<</CreatorInfo<</Subtype/Artwork/Creator(Adobe Illustrator 13.0)>>>>
endobj
16 0 obj
[/View/Design]
endobj
17 0 obj
<</CreatorInfo<</Subtype/Artwork/Creator(Adobe Illustrator 13.0)>>>>
endobj
970 0 obj
[1029 0 R 1011 0 R 994 0 R 975 0 R 971 0 R]
endobj
5 0 obj
<</CropBox[321.5 204.775 334.5 217.775]/Parent 2 0 R/Contents 1048 0 R/BleedBox[0.0 0.0 841.89 595.276]/PieceInfo<</Illustrator 962 0 R>>/ArtBox[321.5 204.775 334.5 217.775]/MediaBox[0.0 0.0 841.89 595.276]/Thumb 1053 0 R/TrimBox[0.0 0.0 841.89 595.276]/Resources<</XObject<</Fm0 986 0 R/Fm1 993 0 R/Fm2 1003 0 R/Fm3 1010 0 R/Fm4 1020 0 R/Fm5 1028 0 R/Fm6 1038 0 R/Fm7 1045 0 R>>/ColorSpace<</CS0 982 0 R>>/Font<</T1_0 1046 0 R>>/ProcSet[/PDF/Text]/Properties<</MC0 971 0 R/MC1 975 0 R/MC2 994 [...]
endobj
1048 0 obj
<</Length 1948/Filter/FlateDecode>>stream
+H��Wˎ
5��Wx�,��巷L 	) ��X ��€�
P��K�Svw�;a$h��>eW�\/�ᄍ7wo���ͽY���9s�`�m�෺:~͇���ݗ��������&6c��
!������qqR�+u�������%�
��3����}��o�^��O��6�����Lj	eS����e�X��}��k�׭� ?:#��q��d|bU����<<-߿��ί~��>��?<|	L�j
�,�$�����HζU%��1*��|̕�D����a��-
��'�}���ü_�xr��X������ϼ��z��Y�����o������v��E��9��m
+Z���u���gIIy_���<�+i,
��}p�:���.��P���5��m
�W�!���{[��
+�Y�$�C�je
�g�-�u�G+�L�Sױ[S��A����j}l6�
+w"�)l� |IsZ����66]#�
+Pi��6y†�K�
����� ds�osP�]R�#0ḾT1� I�l� S���ӡj�V��Pl(jP`
���(CI����
�6l�d�������i���� Ǹ�%+�9�rZ��M�uaj�6�b�
>Q`La 5�s+�XTs�P
�t�y(�=dE������x��8Ǣ8 C '��G�BQ�jAӵa�E+��u߻
\
F��P��P�O���z4�E��#w��Y�_�������	��ͅF
+rHv�����F�5
nZ�1���u\���I&b,p]4MV���c�uԓ	�P�
����F%��	:H���Q�4��>	�G!�i�eH����Z
`�c�
+H��C��:P��z�
�����m�9cĐfw�
s@��~�0���_f��p.
��.7��dC�������^"'���@�"��2�L��\Ba�Pp�p]z��&����L
X��Ep��d���s�m���쓢��xf�͜+��ڋ�C?
��	�U�\�J���sc��}�����G�l��E�\8�K
G�.%C��:�wH�'���7�
��L'�%Jq�z�k�d�5m^4��s�_�025��L���tˤ�Ei}��oH+%�#��@���
>".wb�w
]N�`ͨi��9ıgE�ȄC�f�CΔ�NA�@	(K
�Z��1��ڵc�q��,��G��3*
��W�G�
+6&-ѣ�Y픪�6
��̜JC�L����t� �R�ұ��7QX�Δ�)�ȸ�ӡn���b���{;��#�6�q����'ݥ�B�f�2N��N��$�3�1���.g
+�������ƫ�c��U����;	ñ�R����`|������x���Ksu�uϦ�pD
��)>l��R�
gmډ��vҷ3�}({j\"�
W�O(�M�r�((sM�Ʊ�g)a�#���:RJ�8����ȕ�-u�=�옺
)��vk�@�r}Wv�;F������D��Y��"�ov\,
w-f
+e��!L<8��Uo�λvk��]G�Lxg��bgv
&�R;�2$�x�xƅ�N�Tg	l3��#|Xʪ�D^kE��V�%�Ie@�T7|]Δ��K��x�O�K�G��0�D�M\[�)��z��y�ۿ��r����͕��?;�j"�i.��GMr�q�)i����_'X(��L|��J_�L�GA,)}�^�+���ʽ�|�Bz${E�����O���
+��
+��oH*U
zE';����h��3�g�n/��R������ p�M�e#fP'Q�
+8�ͯv�:�������&?`��&Cw`��}�a�ٴ�i7�
6|F��
9�5i#�
g��x;.�s7���M;
�(Ϥc*
�r~g	�^�(

�xw
���S�/�i�^�o���i�kM�|	u�t����D��u��U���@����ڑ�?P\�ˡ#�W�j��CՔs\�o
�3��3
���W7�Z����E���|����m���Hg�U�R���/ �w�
endstream
endobj
1053 0 obj
<</Length 16/Filter[/ASCII85Decode/FlateDecode]/BitsPerComponent 8/ColorSpace 1051 0 R/Width 1/Height 1>>stream
+8;Xnf&7>J<fDsP~>
endstream
endobj
978 0 obj
<</OPM 1/BM/Normal/CA 1.0/OP false/SMask/None/ca 1.0/AIS false/op false/Type/ExtGState/SA true>>
endobj
1046 0 obj
<</Subtype/Type1/FontDescriptor 1047 0 R/LastChar 102/Widths[513 513 0 513 513 513 0 513 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 448 564 501 292]/BaseFont/XAMDXC+MyriadPro-Regular/FirstChar 49/Encoding/WinAnsiEncoding/Type/Font>>
endobj
1047 0 obj
<</StemV 88/FontName/XAMDXC+MyriadPro-Regular/FontStretch/Normal/FontFile3 1050 0 R/FontWeight 400/Flags 32/Descent -250/FontBBox[-157 -250 1126 952]/Ascent 952/FontFamily(Myriad Pro)/CapHeight 674/XHeight 484/Type/FontDescriptor/ItalicAngle 0>>
endobj
1050 0 obj
<</Subtype/Type1C/Length 1212/Filter/FlateDecode>>stream
+H�|SmPg�#\N��-�M��Y-�H�BR?
+((�H%t�s� LԊ�v�-��
X~P�"ZGT
���Z�"�X
$�H�K;�{�͌�����������;��Xh������̂�y;M�^e2���m)+љ�$��q~f(?;�B �˗/s	�}�}yv�H,Ǐ��0�
+�-�[�Ą����U���2]o,�X�N���ffs�o2�J�&���dz�%%l~Pff�93g*
j���JH�na3JE�2%1����3�cM��P���Y�I���L[Y�f�:-\��dg)Ǧ�zn3��X$�Q!�,
�a��#`yX)օ��|�/du�3�H-�7U��O����#�	���@�
��B�`�ĈE�A��
�7��a���D#D�#�����"���3`���ib�0z����@� jŒ�������<�b-y���w`�I��=S��شUFn}<�h;�>qM>yruc����RQ���R�Y�p{
?��?/
+��
'�q$�H"���E"بZ�`GӉCǛ;g9���� C�H�u:� �~������)֡����<#���'�E�&E���P)]�MTt\��Ü�� ���3���.�ܼ����i������
B�]��G�"�V�c�]e��v0���(֬��j��h4C��>A0 �i�Dfh
E%t���
��-m�{�m�

����f9���?��O���z����i��z���<�x�0?\�z �RR�bC�E�8o*̆�&�1��5�$� ���w
�vE6�;�"�X�5��z�
���)��)ھA�����G�	�n�L��)�.��@��ЬSmܤ��Ik.<= �W�u{h��:�c����1)��x�V� cB��{A�}ʺ��<D4��7���������1=���F��#�r~�0l����A������
)�UM�-ӞN���1�HigP��X�v��1�V,�t&��S6��%�Nj�mo�^Z��٥ѫ�q�������'���Ս��j���$�X�aI?���;�k\�A9e���@�̧%�9JD�h틅��z�+���Ŝ5W��«{?u����'��U��1VX�-H
���D�4�WB�-�#y��?ښ����n"�,�/�}�gk1S���[!���

+(����؀6�`���
+X����:�[0�.ֵב�Y_xvk�D��3�
~�
~.��  �GF"
endstream
endobj
982 0 obj
[/ICCBased 983 0 R]
endobj
983 0 obj
<</Length 2574/Filter/FlateDecode/N 3>>stream
+H���yTSw�oɞ����c
[���5la�
QIBH�ADED���2�mtFOE�.�c��}���0��8�׎�8G�Ng�����9�w���߽��� �'����0
 �֠�J��b�	 
+  2y�.-;!��K�Z�	���^�i�"L��0���-��
 @8(��r�;q��7�L��y��&�Q��q�4�j���|�9��
+�V��)g�B�0�i�W��8#�8wթ��8_�٥ʨQ����Q�j@�&�A)/��g�>'K�� �t�;\��
ӥ$պF�ZUn���
�(4T�%)뫔�0C&�����Z��i���8��bx��E���B�;�����P���ӓ̹�A�
om?�W=
+�x������- �����[��� 0�
���}��y)7ta�����>j���T�7���@���tܛ�`q�2��ʀ��&���6�Z�L�Ą?
�_
��yxg)˔z���çL�U���*�u�Sk�Se�O4?׸�c����.� �
 �� R�
߁��-��2�5������	��S�>ӣV����d�`r��n~��Y�&�+`��;�A4�� 
���A9� =�-�
t�
�
l�`;��~p����	�Gp
|	��[`L��`<� "A
�
YA�+��Cb(��R�,� *�T�2B-�
+�ꇆ�
�n���Q�t�}MA�0�a
l������S�
x	��k�&�^���>�0|>_�'��,�G
!"F$H:R��!z��F�Qd?r
9�\A&�G�
��rQ
��h������E��]�a�4z�Bg�����E#H	�*B=��0H�I��p�p�0MxJ$�D1��D, V���ĭ����KĻ�Y�dE�"E��I2���E�B�G��t�4MzN��
���r!YK� ���?%_&�#���(��0J:EAi��Q�(�()ӔWT6U@���P+���!�~��m���D
�e�Դ�!��h�Ӧh/�
�']B/����ҏӿ�?a0n�hF!��X���8����܌k�c&5S�����
6�l��Ia�2c�K�M�A�!�E�#��ƒ�d�V��(�k��e���l
����}�}�C�q�9
+N'��)�].�u�J�r�
+��
w�G�	xR^���[�oƜc
h�g�`>b���$���*~� �:����E���b��~���,m,�-��ݖ,�Y��¬�*�6X�[ݱF�=�3�뭷Y��~dó	���t�
��i
�z�f�6�~`{�v���.�Ng����#{�}�}������
��j���
���c1X6���f
m
�
��;
'
_9	�r�:�8�q�:��˜�O:ϸ8������u��Jq���nv=���M���m���R 4	�
+n�3ܣ�k�Gݯz=�
�
[=��=�<�=G</z�^�^j��^��	ޡ�Z�Q�B�0FX'�+������t���<�u�-���{���_�_�ߘ�-G�,�
}���/���Hh
8�m�W�2p[���AiA��N�#8$X�?�A�KHI�{!7�<q��W�y(!46�-���a�a���a�W��	��@�@�`l���YĎ��H,�$����(�(Y�h�7��ъ���b<b*b��<�����~�L&Y&9
��%�u�M�s�s��NpJP%�M�I
JlN<�DHJIڐtCj'�KwKg�C��%�N��d�
�|�ꙪO=��%�mL���u�v�x:H��oL��!Ȩ��C&13#s$�/Y����������=�Osbs�rn��sO�1��v�=ˏ��ϟ\�h٢���#��¼����oZ<]T�Ut}�`IÒsK��V-���Y,+>TB(�/�S�,]6*�-���W:#��7�*���e��^YDY�}U�j��AyT�`�#�D=���"�b{ų���+�ʯ [...]
چ
���k�5%4��m�7�lqlio�Z�lG+�Z�z�͹��mzy��]�����?u�u�w|�"űN���wW&���e֥ﺱ*|����j��5k��yݭ���ǯg��^y�kEk�����l�D_p߶������7Dm����o꿻1m��l�{��Mś�
n�L�l�<9��O �[����$�����h�՛B���
�����d�Ҟ@���
�����i�ءG���&����v��V�ǥ8��������n��R�ĩ7���
����u��\�ЭD���-������ �u��`�ֲK�³8���%�������y��h��Y�ѹJ�º;���.���!������
+�����z���p���g���_���X���Q���K���F���Aǿ�=ȼ�:ɹ�8ʷ�6˶�5̵�5͵�6ζ�7ϸ�9к�<Ѿ�?���D���I���N���U���\���d���l���v��ۀ�܊�ݖ�
ޢ�)߯�6��D���S���c���s����
����2��F���[���p������(��@���X���r������4���P���m��������8���W���w����)���K���m��
 ����
endstream
endobj
986 0 obj
<</Subtype/Form/Length 254/Matrix[1.0 0.0 0.0 1.0 0.0 0.0]/Group 979 0 R/Resources<</XObject<</Fm0 985 0 R>>/ColorSpace<</CS0 982 0 R>>/ExtGState<</GS0 978 0 R>>>>/BBox[155.001 324.272 210.999 268.274]>>stream
+/CS0 cs 0.29 0.486 0.133  scn
+1 i 
+/GS0 gs
+q 1 0 0 1 183 308.2725 cm
+0 0 m
+6.607 0.011 12.01 -5.392 11.999 -11.999 c
+12.01 -18.606 6.607 -24.009 0 -23.998 c
+-6.607 -24.009 -12.01 -18.606 -11.999 -11.999 c
+-12.01 -5.392 -6.607 0.011 0 0 c
+f
+Q
+q
+/Fm0 Do
+Q
+
endstream
endobj
993 0 obj
<</Subtype/Form/Length 244/Matrix[1.0 0.0 0.0 1.0 0.0 0.0]/Group 988 0 R/Resources<</XObject<</Fm0 992 0 R>>/ColorSpace<</CS0 982 0 R>>/ExtGState<</GS0 978 0 R>>>>/BBox[180.624 223.274 192.621 211.277]>>stream
+/CS0 cs 0.29 0.486 0.133  scn
+1 i 
+/GS0 gs
+q 1 0 0 1 186.627 218.2744 cm
+0 0 m
+0.544 0.003 0.995 -0.445 0.994 -1.003 c
+0.997 -1.549 0.546 -1.999 0 -1.997 c
+-0.55 -2 -1.007 -1.543 -1.003 -1.003 c
+-1.005 -0.451 -0.549 0.003 0 0 c
+f
+Q
+q
+/Fm0 Do
+Q
+
endstream
endobj
1003 0 obj
<</Subtype/Form/Length 258/Matrix[1.0 0.0 0.0 1.0 0.0 0.0]/Group 998 0 R/Resources<</XObject<</Fm0 1002 0 R>>/ColorSpace<</CS0 982 0 R>>/ExtGState<</GS0 978 0 R>>>>/BBox[306.003 319.277 362.001 263.279]>>stream
+/CS0 cs 0.29 0.486 0.133  scn
+1 i 
+/GS0 gs
+q 1 0 0 1 334.002 303.2773 cm
+0 0 m
+6.607 0.011 12.01 -5.392 11.999 -11.999 c
+12.008 -18.614 6.61 -24.008 0 -23.998 c
+-6.61 -24.008 -12.008 -18.614 -11.999 -11.999 c
+-12.01 -5.392 -6.607 0.011 0 0 c
+f
+Q
+q
+/Fm0 Do
+Q
+
endstream
endobj
1010 0 obj
<</Subtype/Form/Length 247/Matrix[1.0 0.0 0.0 1.0 0.0 0.0]/Group 1005 0 R/Resources<</XObject<</Fm0 1009 0 R>>/ColorSpace<</CS0 982 0 R>>/ExtGState<</GS0 978 0 R>>>>/BBox[321.996 217.271 334.002 205.274]>>stream
+/CS0 cs 0.29 0.486 0.133  scn
+1 i 
+/GS0 gs
+q 1 0 0 1 327.999 212.2715 cm
+0 0 m
+0.55 0.003 1.007 -0.454 1.003 -0.994 c
+1.008 -1.537 0.543 -2.002 0 -1.997 c
+-0.543 -2.002 -1.008 -1.537 -1.003 -0.994 c
+-1.007 -0.454 -0.55 0.003 0 0 c
+f
+Q
+q
+/Fm0 Do
+Q
+
endstream
endobj
1020 0 obj
<</Subtype/Form/Length 262/Matrix[1.0 0.0 0.0 1.0 0.0 0.0]/Group 1015 0 R/Resources<</XObject<</Fm0 1019 0 R>>/ColorSpace<</CS0 982 0 R>>/ExtGState<</GS0 978 0 R>>>>/BBox[295.671 461.774 351.669 405.776]>>stream
+/CS0 cs 0.196 0.322 0.616  scn
+1 i 
+/GS0 gs
+q 1 0 0 1 323.6699 445.7744 cm
+0 0 m
+6.607 0.011 12.01 -5.392 11.999 -11.999 c
+12.01 -18.606 6.607 -24.009 0 -23.998 c
+-6.615 -24.007 -12.009 -18.609 -11.999 -11.999 c
+-12.009 -5.389 -6.615 0.009 0 0 c
+f
+Q
+q
+/Fm0 Do
+Q
+
endstream
endobj
1028 0 obj
<</Subtype/Form/Length 241/Matrix[1.0 0.0 0.0 1.0 0.0 0.0]/Group 1023 0 R/Resources<</XObject<</Fm0 1027 0 R>>/ColorSpace<</CS0 982 0 R>>/ExtGState<</GS0 978 0 R>>>>/BBox[309.171 492.275 321.168 480.278]>>stream
+/CS0 cs 0.196 0.322 0.616  scn
+1 i 
+/GS0 gs
+q 1 0 0 1 315.165 487.2754 cm
+0 0 m
+0.548 0.003 1.005 -0.451 1.003 -1.003 c
+1.007 -1.542 0.55 -2 0 -1.997 c
+-0.546 -2 -0.997 -1.549 -0.994 -1.003 c
+-0.995 -0.445 -0.544 0.003 0 0 c
+f
+Q
+q
+/Fm0 Do
+Q
+
endstream
endobj
1038 0 obj
<</Subtype/Form/Length 262/Matrix[1.0 0.0 0.0 1.0 0.0 0.0]/Group 1033 0 R/Resources<</XObject<</Fm0 1037 0 R>>/ColorSpace<</CS0 982 0 R>>/ExtGState<</GS0 978 0 R>>>>/BBox[156.837 462.278 212.835 406.271]>>stream
+/CS0 cs 0.196 0.322 0.616  scn
+1 i 
+/GS0 gs
+q 1 0 0 1 184.8359 446.2783 cm
+0 0 m
+6.607 0.011 12.01 -5.392 11.999 -11.999 c
+12.008 -18.617 6.606 -24.018 0 -24.007 c
+-6.606 -24.018 -12.008 -18.617 -11.999 -11.999 c
+-12.01 -5.392 -6.607 0.011 0 0 c
+f
+Q
+q
+/Fm0 Do
+Q
+
endstream
endobj
1045 0 obj
<</Subtype/Form/Length 240/Matrix[1.0 0.0 0.0 1.0 0.0 0.0]/Group 1040 0 R/Resources<</XObject<</Fm0 1044 0 R>>/ColorSpace<</CS0 982 0 R>>/ExtGState<</GS0 978 0 R>>>>/BBox[183.873 501.023 195.879 489.026]>>stream
+/CS0 cs 0.196 0.322 0.616  scn
+1 i 
+/GS0 gs
+q 1 0 0 1 189.876 496.0234 cm
+0 0 m
+0.55 0.003 1.007 -0.455 1.003 -0.994 c
+1.005 -1.546 0.548 -2 0 -1.997 c
+-0.548 -2 -1.005 -1.546 -1.003 -0.994 c
+-1.007 -0.455 -0.55 0.003 0 0 c
+f
+Q
+q
+/Fm0 Do
+Q
+
endstream
endobj
1040 0 obj
<</I true/K false/S/Transparency/Type/Group>>
endobj
1044 0 obj
<</Subtype/Form/Length 482/Matrix[1.0 0.0 0.0 1.0 0.0 0.0]/Group 1041 0 R/Resources<</XObject<</Fm0 1043 0 R>>/ExtGState<</GS0 978 0 R>>>>/BBox[183.873 501.023 195.879 489.026]>>stream
+q
+189.876 496.023 m
+189.876 501.023 l
+193.188 501.023 195.879 498.341 195.879 495.029 c
+195.879 491.708 193.188 489.026 189.876 489.026 c
+186.564 489.026 183.873 491.708 183.873 495.029 c
+183.873 498.341 186.564 501.023 189.876 501.023 c
+189.876 496.023 l
+189.326 496.026 188.869 495.569 188.873 495.029 c
+188.871 494.478 189.328 494.023 189.876 494.026 c
+190.424 494.023 190.881 494.478 190.879 495.029 c
+190.883 495.569 190.426 496.026 189.876 496.023 c
+W n
+q
+/GS0 gs
+/Fm0 Do
+Q
+Q
+
endstream
endobj
1041 0 obj
<</I true/K false/S/Transparency/Type/Group>>
endobj
1043 0 obj
<</Subtype/Form/Length 11006/Matrix[1.0 0.0 0.0 1.0 0.0 0.0]/Group 1042 0 R/Resources<</ColorSpace<</CS0 982 0 R>>/ExtGState<</GS0 978 0 R>>>>/BBox[183.873 501.023 195.879 489.026]>>stream
+/CS0 cs 0.2 0.325 0.624  scn
+1 i 
+/GS0 gs
+q 1 0 0 1 189.876 496.0234 cm
+0 0 m
+0 5 l
+3.312 5 6.003 2.318 6.003 -0.994 c
+6.003 -4.315 3.312 -6.997 0 -6.997 c
+-3.312 -6.997 -6.003 -4.315 -6.003 -0.994 c
+-6.003 2.318 -3.312 5 0 5 c
+0 0 l
+-0.55 0.003 -1.007 -0.455 -1.003 -0.994 c
+-1.005 -1.546 -0.548 -2 0 -1.997 c
+0.548 -2 1.005 -1.546 1.003 -0.994 c
+1.007 -0.455 0.55 0.003 0 0 c
+f
+Q
+q 1 0 0 1 189.876 496.9482 cm
+0 0 m
+-0.013 -0.041 -0.073 -0.074 -0.083 -0.116 c
+-0.111 -0.248 -0.02 -0.426 0 -0.56 c
+0 -0.925 l
+-0.55 -0.922 -1.007 -1.379 -1.003 -1.919 c
+-1.005 -2.471 -0.548 -2.925 0 -2.922 c
+0.548 -2.925 1.005 -2.471 1.003 -1.919 c
+1.007 -1.379 0.55 -0.922 0 -0.925 c
+0 -0.56 l
+0.034 -0.557 0.079 -0.553 0.113 -0.55 c
+0.142 -0.55 0.184 -0.537 0.21 -0.549 c
+1.046 -1.473 l
+1.442 -2.154 1.79 -2.107 1.805 -2.105 c
+2.057 -2.065 3.182 -0.618 1.901 0.191 c
+1.598 0.383 1.274 0.41 1.132 0.395 c
+0 0 l
+0 4.075 l
+3.312 4.075 6.003 1.393 6.003 -1.919 c
+6.003 -5.24 3.312 -7.922 0 -7.922 c
+-3.312 -7.922 -6.003 -5.24 -6.003 -1.919 c
+-6.003 1.393 -3.312 4.075 0 4.075 c
+0 0 l
+f
+Q
+0.196 0.318 0.612  scn
+q 1 0 0 1 189.876 497.0903 cm
+0 0 m
+-0.03 -0.092 -0.164 -0.17 -0.185 -0.265 c
+-0.222 -0.433 -0.125 -0.678 -0.188 -0.838 c
+-0.188 -0.839 -0.237 -0.941 -0.403 -1.05 c
+-1.156 -1.54 -1.044 -2.156 -0.992 -2.333 c
+-0.807 -2.959 -0.146 -3.264 0.451 -2.999 c
+0.651 -2.909 0.79 -2.772 0.872 -2.69 c
+1.143 -2.422 1.548 -2.621 1.836 -2.412 c
+2.433 -1.979 2.576 -1.57 2.629 -1.416 c
+2.85 -0.785 2.461 0.134 1.628 0.371 c
+0.853 0.591 0.002 0.007 0 0 c
+0 3.933 l
+3.312 3.933 6.003 1.251 6.003 -2.061 c
+6.003 -5.382 3.312 -8.064 0 -8.064 c
+-3.312 -8.064 -6.003 -5.382 -6.003 -2.061 c
+-6.003 1.251 -3.312 3.933 0 3.933 c
+0 0 l
+f
+Q
+0.192 0.31 0.596  scn
+q 1 0 0 1 189.876 497.231 cm
+0 0 m
+-0.294 -0.832 -1.296 -1.347 -1.079 -2.407 c
+-0.939 -3.088 -0.171 -3.557 0.648 -3.165 c
+2.592 -2.234 2.592 -2.234 2.763 -1.674 c
+3.159 -0.375 2.125 0.263 1.731 0.384 c
+0.831 0.661 0.003 0.008 0 0 c
+0 3.792 l
+3.312 3.792 6.003 1.11 6.003 -2.202 c
+6.003 -5.522 3.312 -8.205 0 -8.205 c
+-3.312 -8.205 -6.003 -5.522 -6.003 -2.202 c
+-6.003 1.11 -3.312 3.792 0 3.792 c
+0 0 l
+f
+Q
+0.188 0.302 0.58  scn
+q 1 0 0 1 189.876 497.3701 cm
+0 0 m
+-0.353 -0.867 -1.383 -1.429 -1.146 -2.56 c
+-1.024 -3.139 -0.35 -3.806 0.712 -3.399 c
+2.444 -2.735 2.625 -2.666 2.946 -1.778 c
+2.952 -1.763 3.406 -0.235 2.053 0.316 c
+0.838 0.812 0.004 0.01 0 0 c
+0 3.653 l
+3.312 3.653 6.003 0.971 6.003 -2.341 c
+6.003 -5.662 3.312 -8.344 0 -8.344 c
+-3.312 -8.344 -6.003 -5.662 -6.003 -2.341 c
+-6.003 0.971 -3.312 3.653 0 3.653 c
+0 0 l
+f
+Q
+0.18 0.294 0.569  scn
+q 1 0 0 1 189.876 497.5073 cm
+0 0 m
+-0.193 -0.417 -0.585 -0.692 -0.795 -1.098 c
+-1.093 -1.708 l
+-1.262 -2.107 -1.291 -2.435 -1.188 -2.804 c
+-1.126 -3.032 -0.727 -4.136 0.984 -3.565 c
+4.73 -2.315 2.784 0.034 2.453 0.247 c
+1.442 0.896 0.101 0.218 0 0 c
+0 3.516 l
+3.312 3.516 6.003 0.834 6.003 -2.478 c
+6.003 -5.799 3.312 -8.481 0 -8.481 c
+-3.312 -8.481 -6.003 -5.799 -6.003 -2.478 c
+-6.003 0.834 -3.312 3.516 0 3.516 c
+0 0 l
+f
+Q
+0.176 0.286 0.553  scn
+q 1 0 0 1 189.876 497.6602 cm
+0 0 m
+-0.013 -0.025 -0.053 -0.04 -0.076 -0.058 c
+-0.365 -0.276 -0.692 -0.523 -1.173 -1.803 c
+-1.244 -1.989 -1.457 -2.557 -1.185 -3.151 c
+-0.782 -4.034 0.179 -4.205 1.672 -3.658 c
+3.872 -2.853 3.987 -0.377 2.341 0.401 c
+1.366 0.863 0.123 0.247 0 0 c
+0 3.363 l
+3.312 3.363 6.003 0.681 6.003 -2.631 c
+6.003 -5.952 3.312 -8.634 0 -8.634 c
+-3.312 -8.634 -6.003 -5.952 -6.003 -2.631 c
+-6.003 0.681 -3.312 3.363 0 3.363 c
+0 0 l
+f
+Q
+0.173 0.278 0.541  scn
+q 1 0 0 1 189.876 497.8516 cm
+0 0 m
+-0.034 -0.067 -0.142 -0.105 -0.203 -0.15 c
+-0.741 -0.551 -1.014 -1.287 -1.254 -1.937 c
+-1.386 -2.294 -1.492 -2.833 -1.246 -3.37 c
+-0.614 -4.746 1.248 -4.148 1.804 -3.932 c
+4.133 -3.027 4.261 -0.305 2.51 0.419 c
+1.108 0.999 0.006 0.012 0 0 c
+0 3.172 l
+3.312 3.172 6.003 0.49 6.003 -2.822 c
+6.003 -6.143 3.312 -8.825 0 -8.825 c
+-3.312 -8.825 -6.003 -6.143 -6.003 -2.822 c
+-6.003 0.49 -3.312 3.172 0 3.172 c
+0 0 l
+f
+Q
+0.169 0.275 0.525  scn
+q 1 0 0 1 189.876 498.0396 cm
+0 0 m
+-0.037 -0.07 -0.152 -0.104 -0.217 -0.148 c
+-0.223 -0.151 -0.766 -0.542 -1.153 -1.542 c
+-1.498 -2.429 -1.549 -2.937 -1.35 -3.481 c
+-1.145 -4.045 -0.491 -4.904 1.578 -4.323 c
+4.082 -3.621 4.629 -0.761 2.993 0.316 c
+1.701 1.166 0.079 0.148 0 0 c
+0 2.984 l
+3.312 2.984 6.003 0.302 6.003 -3.01 c
+6.003 -6.331 3.312 -9.013 0 -9.013 c
+-3.312 -9.013 -6.003 -6.331 -6.003 -3.01 c
+-6.003 0.302 -3.312 2.984 0 2.984 c
+0 0 l
+f
+Q
+0.165 0.267 0.51  scn
+q 1 0 0 1 189.876 498.2236 cm
+0 0 m
+-0.175 -0.317 -0.542 -0.437 -0.748 -0.722 c
+-1.027 -1.109 -1.128 -1.336 -1.241 -1.614 c
+-1.322 -1.817 -1.715 -2.863 -1.448 -3.592 c
+-0.849 -5.223 1.105 -4.776 1.689 -4.601 c
+4.425 -3.778 5.003 -0.758 3.22 0.385 c
+1.946 1.2 0.234 0.423 0 0 c
+0 2.8 l
+3.312 2.8 6.003 0.118 6.003 -3.194 c
+6.003 -6.515 3.312 -9.197 0 -9.197 c
+-3.312 -9.197 -6.003 -6.515 -6.003 -3.194 c
+-6.003 0.118 -3.312 2.8 0 2.8 c
+0 0 l
+f
+Q
+0.161 0.259 0.498  scn
+q 1 0 0 1 189.876 498.4546 cm
+0 0 m
+-0.06 -0.132 -0.265 -0.21 -0.386 -0.291 c
+-0.759 -0.542 -1.229 -1.473 -1.327 -1.735 c
+-1.444 -2.049 -1.803 -3.137 -1.475 -3.94 c
+-0.715 -5.801 1.956 -4.866 1.983 -4.856 c
+5.297 -3.576 5.172 -0.368 3.116 0.573 c
+1.411 1.354 0.007 0.017 0 0 c
+0 2.569 l
+3.312 2.569 6.003 -0.113 6.003 -3.425 c
+6.003 -6.746 3.312 -9.428 0 -9.428 c
+-3.312 -9.428 -6.003 -6.746 -6.003 -3.425 c
+-6.003 -0.113 -3.312 2.569 0 2.569 c
+0 0 l
+f
+Q
+0.153 0.251 0.482  scn
+q 1 0 0 1 189.876 498.7373 cm
+0 0 m
+-0.04 -0.083 -0.167 -0.135 -0.239 -0.193 c
+-0.737 -0.595 -1.131 -1.172 -1.412 -1.908 c
+-1.719 -2.716 -1.736 -3.696 -1.576 -4.141 c
+-0.861 -6.127 1.881 -5.307 1.908 -5.298 c
+5.872 -3.968 5.348 -0.494 3.424 0.518 c
+1.628 1.463 0.058 0.121 0 0 c
+0 2.286 l
+3.312 2.286 6.003 -0.396 6.003 -3.708 c
+6.003 -7.029 3.312 -9.711 0 -9.711 c
+-3.312 -9.711 -6.003 -7.029 -6.003 -3.708 c
+-6.003 -0.396 -3.312 2.286 0 2.286 c
+0 0 l
+f
+Q
+0.149 0.243 0.467  scn
+q 1 0 0 1 189.876 499.0234 cm
+0 0 m
+-0.045 -0.106 -0.21 -0.167 -0.302 -0.236 c
+-0.488 -0.374 -1.13 -0.939 -1.627 -2.442 c
+-1.764 -2.855 -1.88 -3.934 -1.545 -4.673 c
+-1.028 -5.816 0.793 -6.212 2.513 -5.554 c
+6.321 -4.099 5.738 -0.283 3.153 0.723 c
+1.353 1.423 0.007 0.017 0 0 c
+0 2 l
+3.312 2 6.003 -0.682 6.003 -3.994 c
+6.003 -7.315 3.312 -9.997 0 -9.997 c
+-3.312 -9.997 -6.003 -7.315 -6.003 -3.994 c
+-6.003 -0.682 -3.312 2 0 2 c
+0 0 l
+f
+Q
+0.145 0.235 0.455  scn
+q 1 0 0 1 189.876 499.4067 cm
+0 0 m
+-0.163 -0.362 -0.542 -0.515 -0.779 -0.805 c
+-0.948 -1.011 -1.049 -1.26 -1.205 -1.475 c
+-1.361 -1.69 -1.461 -1.951 -1.723 -2.734 c
+-2.048 -3.705 -1.823 -4.543 -1.66 -4.957 c
+-1.17 -6.199 0.623 -6.718 2.422 -6.139 c
+7.03 -4.656 5.827 -0.75 3.286 0.539 c
+1.422 1.485 0.008 0.018 0 0 c
+0 1.617 l
+3.312 1.617 6.003 -1.065 6.003 -4.377 c
+6.003 -7.698 3.312 -10.38 0 -10.38 c
+-3.312 -10.38 -6.003 -7.698 -6.003 -4.377 c
+-6.003 -1.065 -3.312 1.617 0 1.617 c
+0 0 l
+f
+Q
+0.141 0.227 0.439  scn
+q 1 0 0 1 189.876 499.8311 cm
+0 0 m
+-0.128 -0.296 -0.442 -0.404 -0.638 -0.631 c
+-0.788 -0.804 -0.893 -1.009 -1.031 -1.191 c
+-1.148 -1.346 -1.62 -2.354 -1.623 -2.361 c
+-2.171 -3.896 -2.053 -4.61 -1.842 -5.154 c
+-0.963 -7.425 1.653 -7.025 2.586 -6.68 c
+3.893 -6.196 6.611 -5.189 5.553 -2.521 c
+5.843 -3.224 6.003 -3.994 6.003 -4.802 c
+6.003 -8.123 3.312 -10.805 0 -10.805 c
+-3.312 -10.805 -6.003 -8.123 -6.003 -4.802 c
+-6.003 -1.49 -3.312 1.192 0 1.192 c
+0 0 l
+f
+Q
+0.137 0.22 0.427  scn
+q 1 0 0 1 189.876 500.2959 cm
+0 0 m
+-0.037 -0.078 -0.154 -0.129 -0.22 -0.184 c
+-1.238 -1.037 -1.832 -2.884 -1.837 -2.903 c
+-2.426 -4.762 -2.011 -5.635 -1.875 -5.921 c
+-0.599 -8.601 3.356 -7.148 3.396 -7.133 c
+4.442 -6.725 6.193 -6.042 5.899 -4.15 c
+5.967 -4.512 6.003 -4.885 6.003 -5.267 c
+6.003 -8.587 3.312 -11.27 0 -11.27 c
+-3.312 -11.27 -6.003 -8.587 -6.003 -5.267 c
+-6.003 -1.955 -3.312 0.728 0 0.728 c
+0 0 l
+f
+Q
+0.133 0.216 0.412  scn
+q 1 0 0 1 189.876 500.7388 cm
+0 0 m
+-0.038 -0.067 -0.155 -0.091 -0.221 -0.129 c
+-1.151 -0.674 -1.646 -2.172 -2.007 -3.267 c
+-2.012 -3.284 -2.546 -5.066 -2.073 -6.279 c
+-1.012 -9 2.932 -7.99 3.099 -7.945 c
+4.318 -7.622 5.989 -7.18 6.001 -5.577 c
+6.002 -5.621 6.003 -5.665 6.003 -5.709 c
+6.003 -9.03 3.312 -11.712 0 -11.712 c
+-3.312 -11.712 -6.003 -9.03 -6.003 -5.709 c
+-6.003 -2.397 -3.312 0.285 0 0.285 c
+0 0 l
+f
+Q
+0.125 0.208 0.396  scn
+q 1 0 0 1 189.876 501.0112 cm
+0 0 m
+-0.043 -0.052 -0.154 -0.029 -0.221 -0.042 c
+-0.696 -0.132 -1.348 -0.689 -1.732 -1.731 c
+-2.576 -4.014 -2.459 -5.548 -2.314 -6.26 c
+-1.78 -8.88 1.72 -8.614 1.755 -8.611 c
+4.215 -8.371 5.7 -8.227 5.951 -6.778 c
+5.561 -9.721 3.043 -11.985 0 -11.985 c
+-3.312 -11.985 -6.003 -9.303 -6.003 -5.982 c
+-6.003 -2.67 -3.312 0.012 0 0.012 c
+0 0 l
+f
+Q
+0.122 0.2 0.384  scn
+q 1 0 0 1 188.9707 500.9468 cm
+0 0 m
+-1.737 -0.589 -1.75 -4.504 -1.75 -4.544 c
+-1.745 -7.052 -0.74 -7.832 0.016 -8.2 c
+1.799 -9.068 6.088 -9.359 6.659 -7.635 c
+5.92 -10.116 3.622 -11.92 0.905 -11.92 c
+-2.407 -11.92 -5.098 -9.238 -5.098 -5.917 c
+-5.098 -2.856 -2.799 -0.333 0.165 0.031 c
+0.115 0.022 0.049 0.013 0 0 c
+f
+Q
+0.118 0.192 0.369  scn
+q 1 0 0 1 187.6411 500.5234 cm
+0 0 m
+-1.064 -0.939 -0.813 -4.868 -0.54 -5.601 c
+0.43 -8.206 2.406 -8.584 3.21 -8.625 c
+4.273 -8.681 5.3 -9.068 6.38 -8.967 c
+6.693 -8.938 7.267 -8.802 7.587 -8.217 c
+6.594 -10.165 4.569 -11.497 2.235 -11.497 c
+-1.077 -11.497 -3.768 -8.815 -3.768 -5.494 c
+-3.768 -2.81 -2 -0.54 0.432 0.225 c
+0.372 0.201 0.292 0.168 0.231 0.144 c
+0.162 0.102 0.062 0.054 0 0 c
+f
+Q
+0.204 0.333 0.639  scn
+q 1 0 0 1 191.4565 495.208 cm
+0 0 m
+-0.097 0.069 -0.097 0.069 -0.519 0.587 c
+-0.662 0.762 -0.835 0.91 -0.974 1.089 c
+-1.125 1.285 -1.232 1.593 y
+-1.227 1.612 -0.03 2.438 0.591 1.363 c
+1.026 0.61 0.244 -0.13 0.233 -0.131 c
+0.153 -0.143 0.065 -0.046 0 0 c
+f
+Q
+0.141 0.227 0.439  scn
+q 1 0 0 1 192.4463 500.4146 cm
+0 0 m
+-1.295 0.463 -2.255 -0.325 -2.57 -0.583 c
+-2.57 0.609 l
+-1.402 0.609 -0.312 0.275 0.611 -0.302 c
+0.521 -0.251 0.401 -0.185 0.312 -0.135 c
+0.218 -0.094 0.096 -0.034 0 0 c
+f
+Q
+0.208 0.337 0.655  scn
+q 1 0 0 1 191.4961 495.46 cm
+0 0 m
+-0.335 0.354 l
+-0.472 0.524 -0.626 0.679 -0.757 0.854 c
+-0.976 1.148 -1.021 1.268 -1.02 1.273 c
+-1.015 1.287 -0.029 1.7 0.33 0.953 c
+0.59 0.409 0.174 -0.12 0.167 -0.121 c
+0.106 -0.131 0.048 -0.04 0 0 c
+f
+Q
+0.137 0.22 0.427  scn
+q 1 0 0 1 191.6431 500.7461 cm
+0 0 m
+-0.651 0.121 -1.163 -0.01 -1.767 -0.45 c
+-1.767 0.277 l
+-1.038 0.277 -0.339 0.147 0.307 -0.09 c
+0.224 -0.065 0.112 -0.032 0.029 -0.006 c
+0.02 -0.004 0.009 -0.001 0 0 c
+f
+Q
+0.216 0.345 0.667  scn
+q 1 0 0 1 191.5 495.7261 cm
+0 0 m
+-0.004 0.004 -0.533 0.573 -0.71 0.862 c
+-0.568 0.875 -0.482 0.883 -0.264 0.809 c
+-0.18 0.781 -0.083 0.699 -0.025 0.631 c
+0.033 0.563 0.091 0.45 0.104 0.362 c
+0.135 0.141 0.099 0.019 0.074 -0.062 c
+0.052 -0.043 0.021 -0.021 0 0 c
+f
+Q
+0.133 0.216 0.412  scn
+q 1 0 0 1 190.7813 500.9458 cm
+0 0 m
+-0.314 -0.005 -0.487 -0.009 -0.905 -0.207 c
+-0.905 0.078 l
+-0.519 0.078 -0.142 0.041 0.225 -0.028 c
+0.157 -0.02 0.067 -0.003 0 0 c
+f
+Q
+0.125 0.208 0.396  scn
+q 1 0 0 1 189.876 501.0112 cm
+0 0 m
+0 0.012 l
+0.072 0.012 0.144 0.011 0.215 0.008 c
+0.15 0.006 0.046 -0.044 0 0 c
+f
+Q
+
endstream
endobj
1042 0 obj
<</I true/K false/S/Transparency/Type/Group>>
endobj
1033 0 obj
<</I true/K false/S/Transparency/Type/Group>>
endobj
1037 0 obj
<</Subtype/Form/Length 482/Matrix[1.0 0.0 0.0 1.0 0.0 0.0]/Group 1034 0 R/Resources<</XObject<</Fm0 1036 0 R>>/ExtGState<</GS0 978 0 R>>>>/BBox[156.837 462.278 212.835 406.271]>>stream
+q
+184.836 446.278 m
+184.836 462.278 l
+200.298 462.278 212.835 449.741 212.835 434.279 c
+212.835 418.809 200.298 406.271 184.836 406.271 c
+169.374 406.271 156.837 418.809 156.837 434.279 c
+156.837 449.741 169.374 462.278 184.836 462.278 c
+184.836 446.278 l
+178.229 446.289 172.826 440.887 172.837 434.279 c
+172.828 427.661 178.229 422.261 184.836 422.271 c
+191.442 422.261 196.844 427.661 196.835 434.279 c
+196.846 440.887 191.443 446.289 184.836 446.278 c
+W n
+q
+/GS0 gs
+/Fm0 Do
+Q
+Q
+
endstream
endobj
1034 0 obj
<</I true/K false/S/Transparency/Type/Group>>
endobj
1036 0 obj
<</Subtype/Form/Length 13533/Matrix[1.0 0.0 0.0 1.0 0.0 0.0]/Group 1035 0 R/Resources<</ColorSpace<</CS0 982 0 R>>/ExtGState<</GS0 978 0 R>>>>/BBox[156.837 462.278 212.835 406.271]>>stream
+/CS0 cs 0.208 0.337 0.655  scn
+1 i 
+/GS0 gs
+q 1 0 0 1 184.8359 446.2783 cm
+0 0 m
+0 16 l
+15.462 16 27.999 3.463 27.999 -11.999 c
+27.999 -27.47 15.462 -40.007 0 -40.007 c
+-15.462 -40.007 -27.999 -27.47 -27.999 -11.999 c
+-27.999 3.463 -15.462 16 0 16 c
+0 0 l
+-6.607 0.011 -12.01 -5.392 -11.999 -11.999 c
+-12.008 -18.617 -6.606 -24.018 0 -24.007 c
+6.606 -24.018 12.008 -18.617 11.999 -11.999 c
+12.01 -5.392 6.607 0.011 0 0 c
+f
+Q
+q 1 0 0 1 184.8359 451.4419 cm
+0 0 m
+0 -0.468 l
+0 -5.164 l
+-6.607 -5.153 -12.01 -10.555 -11.999 -17.163 c
+-12.008 -23.781 -6.606 -29.181 0 -29.17 c
+6.606 -29.181 12.008 -23.781 11.999 -17.163 c
+12.01 -10.555 6.607 -5.153 0 -5.164 c
+0 -0.468 l
+0.316 -0.694 0.738 -0.997 1.055 -1.223 c
+3.817 -3.661 7.459 -4.869 10 -7.617 c
+12.018 -9.8 13.458 -12.461 14.279 -15.528 c
+15.076 -18.507 16.901 -19.346 16.917 -19.348 c
+18.874 -19.542 24.735 -10.485 17.857 -2.241 c
+10.879 6.124 0.769 1.958 0 0 c
+0 10.836 l
+15.462 10.836 27.999 -1.701 27.999 -17.163 c
+27.999 -32.633 15.462 -45.17 0 -45.17 c
+-15.462 -45.17 -27.999 -32.633 -27.999 -17.163 c
+-27.999 -1.701 -15.462 10.836 0 10.836 c
+0 0 l
+f
+Q
+0.204 0.333 0.639  scn
+q 1 0 0 1 184.8359 453.2891 cm
+0 0 m
+-0.296 -0.712 -1.487 -1.168 -1.735 -1.898 c
+-1.987 -2.638 -2.003 -3.873 -1.53 -4.494 c
+-1.227 -4.893 -0.45 -4.945 0 -5.167 c
+0 -7.011 l
+-6.607 -7 -12.01 -12.402 -11.999 -19.01 c
+-12.008 -25.628 -6.606 -31.028 0 -31.018 c
+6.606 -31.028 12.008 -25.628 11.999 -19.01 c
+12.01 -12.402 6.607 -7 0 -7.011 c
+0 -5.167 l
+0.338 -5.201 0.788 -5.245 1.126 -5.278 c
+2.249 -5.476 12.144 -7.557 13.761 -19.538 c
+13.765 -19.565 14.171 -22.516 14.171 -22.516 c
+14.636 -23.09 15.724 -23.507 16.459 -23.43 c
+20.584 -22.993 26.416 -9.568 15.896 -1.312 c
+7.943 4.929 0.035 0.084 0 0 c
+0 8.989 l
+15.462 8.989 27.999 -3.548 27.999 -19.01 c
+27.999 -34.48 15.462 -47.018 0 -47.018 c
+-15.462 -47.018 -27.999 -34.48 -27.999 -19.01 c
+-27.999 -3.548 -15.462 8.989 0 8.989 c
+0 0 l
+f
+Q
+0.2 0.325 0.624  scn
+q 1 0 0 1 184.8359 454.4082 cm
+0 0 m
+-0.627 -1.109 -1.866 -1.525 -2.708 -2.391 c
+-4.764 -4.503 -4.447 -6.209 -4.44 -6.223 c
+-4.355 -6.386 -4.355 -6.386 0 -7.408 c
+0 -8.13 l
+-6.607 -8.119 -12.01 -13.521 -11.999 -20.129 c
+-12.008 -26.747 -6.606 -32.147 0 -32.137 c
+6.606 -32.147 12.008 -26.747 11.999 -20.129 c
+12.01 -13.521 6.607 -8.119 0 -8.13 c
+0 -7.408 l
+0.312 -7.428 0.727 -7.455 1.039 -7.475 c
+5.587 -8.118 13.156 -12.018 12.674 -22.551 c
+12.559 -25.065 12.662 -26.483 12.98 -26.764 c
+14.309 -27.938 23.357 -23.699 22.629 -14.042 c
+21.269 4.004 1.142 2.019 0 0 c
+0 7.87 l
+15.462 7.87 27.999 -4.667 27.999 -20.129 c
+27.999 -35.6 15.462 -48.137 0 -48.137 c
+-15.462 -48.137 -27.999 -35.6 -27.999 -20.129 c
+-27.999 -4.667 -15.462 7.87 0 7.87 c
+0 0 l
+f
+Q
+0.196 0.318 0.612  scn
+q 1 0 0 1 184.8359 455.3335 cm
+0 0 m
+-0.223 -0.377 -0.896 -0.494 -1.279 -0.706 c
+-3.984 -2.198 -4.352 -2.882 -7.218 -8.204 c
+-10.977 -15.407 l
+-12.034 -17.649 -12.409 -19.973 -12.123 -22.512 c
+-11.368 -29.209 -4.441 -35.048 3.701 -32.84 c
+16.505 -28.457 l
+19.639 -26.39 21.523 -23.894 22.614 -20.364 c
+24.61 -13.907 21.812 -4.74 13.674 -0.575 c
+6.26 3.219 0.029 0.049 0 0 c
+0 6.945 l
+15.462 6.945 27.999 -5.592 27.999 -21.054 c
+27.999 -36.525 15.462 -49.062 0 -49.062 c
+-15.462 -49.062 -27.999 -36.525 -27.999 -21.054 c
+-27.999 -5.592 -15.462 6.945 0 6.945 c
+0 0 l
+f
+Q
+0.192 0.31 0.596  scn
+q 1 0 0 1 184.8359 456.1333 cm
+0 0 m
+-0.174 -0.267 -0.682 -0.3 -0.974 -0.428 c
+-3.27 -1.438 -6.363 -4.313 -7.593 -6.58 c
+-13.39 -17.263 -12.999 -20.654 -12.686 -23.38 c
+-12.044 -28.948 -6.307 -36.34 3.975 -34.525 c
+32.478 -29.493 24.483 -7.887 15.417 -1.844 c
+7.621 3.352 0.038 0.059 0 0 c
+0 6.145 l
+15.462 6.145 27.999 -6.392 27.999 -21.854 c
+27.999 -37.325 15.462 -49.862 0 -49.862 c
+-15.462 -49.862 -27.999 -37.325 -27.999 -21.854 c
+-27.999 -6.392 -15.462 6.145 0 6.145 c
+0 0 l
+f
+Q
+0.188 0.302 0.58  scn
+q 1 0 0 1 184.8359 456.834 cm
+0 0 m
+-0.26 -0.393 -1.01 -0.429 -1.443 -0.612 c
+-4.281 -1.817 -7.531 -4.969 -9.346 -8.278 c
+-13.498 -15.848 -13.757 -21.086 -13.243 -24.147 c
+-12.335 -29.562 -7.257 -38.122 6.017 -35.862 c
+29.657 -31.837 27.572 -10.232 15.691 -2.188 c
+7.725 3.206 0.039 0.058 0 0 c
+0 5.444 l
+15.462 5.444 27.999 -7.093 27.999 -22.555 c
+27.999 -38.025 15.462 -50.563 0 -50.563 c
+-15.462 -50.563 -27.999 -38.025 -27.999 -22.555 c
+-27.999 -7.093 -15.462 5.444 0 5.444 c
+0 0 l
+f
+Q
+0.18 0.294 0.569  scn
+q 1 0 0 1 184.8359 457.5 cm
+0 0 m
+-0.27 -0.397 -1.042 -0.411 -1.488 -0.586 c
+-3.111 -1.225 -7.25 -3.37 -10.633 -9.471 c
+-11.685 -11.368 -15.021 -18.085 -13.796 -24.879 c
+-12.453 -32.328 -5.461 -39.37 6.714 -37.227 c
+28.951 -33.313 28.976 -11.259 15.609 -2.301 c
+7.856 2.895 0.038 0.056 0 0 c
+0 4.778 l
+15.462 4.778 27.999 -7.759 27.999 -23.221 c
+27.999 -38.691 15.462 -51.229 0 -51.229 c
+-15.462 -51.229 -27.999 -38.691 -27.999 -23.221 c
+-27.999 -7.759 -15.462 4.778 0 4.778 c
+0 0 l
+f
+Q
+0.176 0.286 0.553  scn
+q 1 0 0 1 184.8359 458.1108 cm
+0 0 m
+-0.285 -0.403 -1.085 -0.384 -1.55 -0.549 c
+-2.14 -0.758 -7.426 -2.783 -11.14 -9.4 c
+-12.536 -11.888 -15.643 -18.441 -14.343 -25.555 c
+-13.275 -31.4 -7.567 -40.72 7.05 -38.576 c
+28.069 -35.492 30.907 -13.131 16.17 -2.838 c
+7.979 2.883 0.04 0.057 0 0 c
+0 4.167 l
+15.462 4.167 27.999 -8.37 27.999 -23.832 c
+27.999 -39.302 15.462 -51.839 0 -51.839 c
+-15.462 -51.839 -27.999 -39.302 -27.999 -23.832 c
+-27.999 -8.37 -15.462 4.167 0 4.167 c
+0 0 l
+f
+Q
+0.173 0.278 0.541  scn
+q 1 0 0 1 184.8359 458.6836 cm
+0 0 m
+-0.294 -0.407 -1.113 -0.365 -1.59 -0.521 c
+-3.037 -0.996 -8.057 -3.068 -11.887 -9.807 c
+-12.95 -11.676 -16.305 -18.381 -14.886 -26.192 c
+-13.691 -32.767 -6.813 -41.832 7.241 -39.858 c
+28.692 -36.845 31.476 -13.851 16.374 -3.144 c
+8.08 2.736 0.041 0.056 0 0 c
+0 3.595 l
+15.462 3.595 27.999 -8.942 27.999 -24.404 c
+27.999 -39.875 15.462 -52.412 0 -52.412 c
+-15.462 -52.412 -27.999 -39.875 -27.999 -24.404 c
+-27.999 -8.942 -15.462 3.595 0 3.595 c
+0 0 l
+f
+Q
+0.169 0.275 0.525  scn
+q 1 0 0 1 184.8359 459.2207 cm
+0 0 m
+-0.327 -0.44 -1.224 -0.37 -1.749 -0.528 c
+-5.52 -1.667 -9.766 -5.26 -12.073 -9.267 c
+-15.394 -15.036 -16.522 -20.933 -15.426 -26.792 c
+-13.856 -35.181 -5.227 -43.019 7.675 -41.021 c
+29.387 -37.659 31.678 -13.959 16.092 -3.122 c
+8.188 2.374 0.041 0.052 0 0 c
+0 3.058 l
+15.462 3.058 27.999 -9.479 27.999 -24.941 c
+27.999 -40.412 15.462 -52.949 0 -52.949 c
+-15.462 -52.949 -27.999 -40.412 -27.999 -24.941 c
+-27.999 -9.479 -15.462 3.058 0 3.058 c
+0 0 l
+f
+Q
+0.165 0.267 0.51  scn
+q 1 0 0 1 184.8359 459.7354 cm
+0 0 m
+-0.315 -0.413 -1.169 -0.321 -1.671 -0.458 c
+-5.628 -1.543 -10.186 -5.222 -12.509 -9.206 c
+-13.794 -11.411 -17.706 -18.119 -15.958 -27.37 c
+-14.312 -36.089 -5.369 -44.235 7.962 -42.157 c
+29.829 -38.748 32.261 -15.07 16.713 -3.752 c
+8.241 2.415 0.041 0.054 0 0 c
+0 2.543 l
+15.462 2.543 27.999 -9.994 27.999 -25.456 c
+27.999 -40.927 15.462 -53.464 0 -53.464 c
+-15.462 -53.464 -27.999 -40.927 -27.999 -25.456 c
+-27.999 -9.994 -15.462 2.543 0 2.543 c
+0 0 l
+f
+Q
+0.161 0.259 0.498  scn
+q 1 0 0 1 184.8359 460.208 cm
+0 0 m
+-0.326 -0.417 -1.197 -0.297 -1.71 -0.424 c
+-5.005 -1.241 -10.022 -4.174 -13.317 -9.752 c
+-16.642 -15.38 -17.707 -21.488 -16.484 -27.905 c
+-14.771 -36.893 -5.522 -45.319 8.241 -43.229 c
+29.819 -39.954 32.248 -15.425 16.845 -4.05 c
+8.507 2.107 0.042 0.053 0 0 c
+0 2.07 l
+15.462 2.07 27.999 -10.467 27.999 -25.929 c
+27.999 -41.399 15.462 -53.937 0 -53.937 c
+-15.462 -53.937 -27.999 -41.399 -27.999 -25.929 c
+-27.999 -10.467 -15.462 2.07 0 2.07 c
+0 0 l
+f
+Q
+0.153 0.251 0.482  scn
+q 1 0 0 1 184.8359 460.6479 cm
+0 0 m
+-0.165 -0.201 -0.596 -0.119 -0.852 -0.169 c
+-6.63 -1.321 -11.086 -5.48 -13.33 -8.99 c
+-17.823 -16.018 -17.959 -22.68 -17.283 -27.032 c
+-15.528 -38.313 -5.353 -45.642 6.913 -44.456 c
+29.058 -42.316 33.217 -18.568 18.588 -5.674 c
+9.722 2.142 0.051 0.062 0 0 c
+0 1.63 l
+15.462 1.63 27.999 -10.907 27.999 -26.369 c
+27.999 -41.839 15.462 -54.376 0 -54.376 c
+-15.462 -54.376 -27.999 -41.839 -27.999 -26.369 c
+-27.999 -10.907 -15.462 1.63 0 1.63 c
+0 0 l
+f
+Q
+0.149 0.243 0.467  scn
+q 1 0 0 1 184.8359 461.0591 cm
+0 0 m
+-0.345 -0.419 -1.243 -0.245 -1.775 -0.35 c
+-5.333 -1.052 -10.598 -4.013 -13.752 -8.857 c
+-18.474 -16.108 -18.606 -22.979 -17.885 -27.466 c
+-16.272 -37.507 -7.1 -46.929 7.31 -45.507 c
+29.58 -43.31 33.524 -19.12 18.666 -5.999 c
+9.679 1.938 0.05 0.061 0 0 c
+0 1.219 l
+15.462 1.219 27.999 -11.318 27.999 -26.78 c
+27.999 -42.25 15.462 -54.788 0 -54.788 c
+-15.462 -54.788 -27.999 -42.25 -27.999 -26.78 c
+-27.999 -11.318 -15.462 1.219 0 1.219 c
+0 0 l
+f
+Q
+0.145 0.235 0.455  scn
+q 1 0 0 1 184.8359 461.4141 cm
+0 0 m
+-0.359 -0.424 -1.279 -0.213 -1.827 -0.305 c
+-2.571 -0.429 -9.239 -1.713 -14.035 -8.521 c
+-19.337 -16.049 -19.04 -23.602 -18.666 -26.5 c
+-16.79 -41.041 -4.557 -47.127 6.015 -46.629 c
+29.242 -45.535 34.043 -19.97 18.705 -6.311 c
+9.693 1.714 0.05 0.059 0 0 c
+0 0.864 l
+15.462 0.864 27.999 -11.673 27.999 -27.135 c
+27.999 -42.605 15.462 -55.143 0 -55.143 c
+-15.462 -55.143 -27.999 -42.605 -27.999 -27.135 c
+-27.999 -11.673 -15.462 0.864 0 0.864 c
+0 0 l
+f
+Q
+0.141 0.227 0.439  scn
+q 1 0 0 1 184.8359 461.7397 cm
+0 0 m
+-0.366 -0.422 -1.29 -0.183 -1.842 -0.262 c
+-5.616 -0.798 -11.203 -3.577 -14.553 -8.414 c
+-20.526 -17.037 -19.484 -25.015 -19.142 -27.636 c
+-17.325 -41.551 -4.721 -48.305 6.215 -47.597 c
+22.827 -46.52 31.839 -32.415 25.896 -16.796 c
+27.251 -20.083 27.999 -23.685 27.999 -27.46 c
+27.999 -42.931 15.462 -55.468 0 -55.468 c
+-15.462 -55.468 -27.999 -42.931 -27.999 -27.46 c
+-27.999 -11.999 -15.462 0.539 0 0.539 c
+0 0 l
+f
+Q
+0.137 0.22 0.427  scn
+q 1 0 0 1 184.8359 461.9951 cm
+0 0 m
+-0.38 -0.425 -1.322 -0.147 -1.889 -0.211 c
+-3.74 -0.417 -10.183 -1.633 -15.334 -8.604 c
+-20.12 -15.08 -20.496 -23.225 -19.964 -27.016 c
+-18.071 -40.504 -7.311 -49.146 6.811 -48.521 c
+13.567 -48.222 30.459 -42.962 27.513 -22.495 c
+27.832 -24.187 27.999 -25.932 27.999 -27.716 c
+27.999 -43.187 15.462 -55.724 0 -55.724 c
+-15.462 -55.724 -27.999 -43.187 -27.999 -27.716 c
+-27.999 -12.254 -15.462 0.283 0 0.283 c
+0 0 l
+f
+Q
+0.133 0.216 0.412  scn
+q 1 0 0 1 184.8359 462.186 cm
+0 0 m
+-0.389 -0.421 -1.333 -0.109 -1.905 -0.156 c
+-5.862 -0.48 -11.762 -2.986 -15.367 -7.721 c
+-21.456 -15.72 -21.121 -23.999 -20.694 -27.186 c
+-18.877 -40.772 -7.134 -50.361 6.621 -49.493 c
+16.365 -48.877 27.809 -42.692 27.992 -27.284 c
+27.997 -27.491 27.999 -27.699 27.999 -27.907 c
+27.999 -43.377 15.462 -55.915 0 -55.915 c
+-15.462 -55.915 -27.999 -43.377 -27.999 -27.907 c
+-27.999 -12.445 -15.462 0.092 0 0.092 c
+0 0 l
+f
+Q
+0.125 0.208 0.396  scn
+q 1 0 0 1 184.8359 462.2749 cm
+0 0 m
+-0.403 -0.423 -1.362 -0.067 -1.945 -0.096 c
+-5.653 -0.278 -11.171 -1.795 -16.407 -7.987 c
+-19.42 -11.549 -22.258 -18.906 -21.583 -25.522 c
+-19.025 -50.599 4.157 -50.427 5.143 -50.408 c
+17.394 -50.165 25.848 -43.174 27.755 -31.708 c
+25.94 -45.423 14.204 -56.003 0 -56.003 c
+-15.462 -56.003 -27.999 -43.466 -27.999 -27.996 c
+-27.999 -12.534 -15.462 0.003 0 0.003 c
+0 0 l
+f
+Q
+0.122 0.2 0.384  scn
+q 1 0 0 1 180.605 461.958 cm
+0 0 m
+-22.531 -4.551 -23.529 -35.032 -6.329 -46.266 c
+6.848 -54.872 25.64 -52.177 31.068 -35.689 c
+27.624 -47.255 16.911 -55.687 4.231 -55.687 c
+-11.231 -55.687 -23.768 -43.149 -23.768 -27.679 c
+-23.768 -13.386 -13.055 -1.592 0.778 0.109 c
+0.544 0.077 0.232 0.04 0 0 c
+f
+Q
+0.118 0.192 0.369  scn
+q 1 0 0 1 172.812 459.498 cm
+0 0 m
+-16.566 -9.064 -17.348 -40.201 9.316 -48.722 c
+16.64 -51.062 30.628 -50.199 36.986 -37.919 c
+32.357 -47.005 22.916 -53.227 12.024 -53.227 c
+-3.438 -53.227 -15.975 -40.689 -15.975 -25.219 c
+-15.975 -12.683 -7.734 -2.069 3.625 1.499 c
+3.1 1.309 2.399 1.057 1.873 0.867 c
+1.31 0.61 0.543 0.297 0 0 c
+f
+Q
+0.216 0.345 0.667  scn
+q 1 0 0 1 200.7622 436.103 cm
+0 0 m
+-1.706 2.422 -2.871 5.192 -4.806 7.466 c
+-5.581 8.375 -6.334 9.141 -7.046 9.74 c
+-7.103 9.788 -12.699 14.577 -12.706 14.929 c
+-12.708 15.035 -10.925 16.753 -10.74 16.825 c
+-10.058 17.086 -7.544 17.231 -6.875 17.166 c
+-5.111 16.992 -2.438 16.241 0.275 13.649 c
+3.79 10.293 4.269 6.382 4.332 5.263 c
+4.608 0.362 1.816 -1.552 1.125 -1.426 c
+0.589 -1.328 0.314 -0.445 0 0 c
+f
+Q
+0.22 0.353 0.682  scn
+q 1 0 0 1 200.8965 438.5967 cm
+0 0 m
+-1.97 2.883 -3.056 4.472 -4.87 6.595 c
+-5.072 6.832 -5.375 7.116 -5.591 7.34 c
+-5.844 7.601 -6.16 7.969 -6.419 8.224 c
+-6.913 8.711 -7.551 9.382 -8.074 9.839 c
+-9.724 11.281 -9.908 11.547 -9.911 11.595 c
+-9.914 11.655 -8.389 13.369 -8.295 13.411 c
+-7.711 13.674 -6.801 13.346 -6.164 13.276 c
+-2.962 12.927 -1.156 11.212 -0.476 10.566 c
+2.531 7.709 2.783 5.143 2.904 3.909 c
+2.938 3.565 2.929 0.875 2.709 0.41 c
+2.675 0.337 0.707 -0.875 0.645 -0.861 c
+0.33 -0.793 0.182 -0.267 0 0 c
+f
+Q
+0.224 0.361 0.694  scn
+q 1 0 0 1 199.9814 442.126 cm
+0 0 m
+-0.737 0.235 -1.076 1.45 -1.576 2.04 c
+-3.148 3.895 -3.148 3.895 -3.897 4.678 c
+-4.212 5.008 -4.84 5.354 -4.922 5.803 c
+-4.014 7.981 l
+-3.953 8.007 -1.427 7.15 0.33 5.083 c
+1.631 3.552 2.397 0.755 2.281 0.574 c
+1.906 -0.01 0.699 -0.197 0.037 0.011 c
+0.026 0.014 0.011 -0.003 0 0 c
+f
+Q
+0.141 0.227 0.439  scn
+q 1 0 0 1 196.8853 459.5508 cm
+0 0 m
+-5.275 2.417 -9.403 2.407 -12.049 2.189 c
+-12.049 2.728 l
+-6.604 2.728 -1.522 1.173 2.777 -1.517 c
+2.232 -1.205 1.506 -0.789 0.961 -0.477 c
+0.673 -0.334 0.292 -0.134 0 0 c
+f
+Q
+0.137 0.22 0.427  scn
+q 1 0 0 1 193.0991 461.0352 cm
+0 0 m
+-3.078 0.794 -4.478 1.111 -8.263 0.96 c
+-8.263 1.243 l
+-4.866 1.243 -1.61 0.638 1.402 -0.47 c
+0.981 -0.329 0.425 -0.126 0 0 c
+f
+Q
+0.133 0.216 0.412  scn
+q 1 0 0 1 189.0669 461.958 cm
+0 0 m
+-2.557 0.263 -2.657 0.273 -4.231 0.228 c
+-4.231 0.32 l
+-2.431 0.32 -0.671 0.15 1.035 -0.174 c
+0.724 -0.122 0.312 -0.042 0 0 c
+f
+Q
+0.125 0.208 0.396  scn
+q 1 0 0 1 184.8359 462.2749 cm
+0 0 m
+0.335 0.003 0.669 -0.002 1.001 -0.014 c
+0.701 -0.01 0.211 -0.214 0 0 c
+f
+Q
+
endstream
endobj
1035 0 obj
<</I true/K false/S/Transparency/Type/Group>>
endobj
1023 0 obj
<</I true/K false/S/Transparency/Type/Group>>
endobj
1027 0 obj
<</Subtype/Form/Length 477/Matrix[1.0 0.0 0.0 1.0 0.0 0.0]/Group 1024 0 R/Resources<</XObject<</Fm0 1026 0 R>>/ExtGState<</GS0 978 0 R>>>>/BBox[309.171 492.275 321.168 480.278]>>stream
+q
+315.165 487.275 m
+315.165 492.275 l
+318.477 492.275 321.168 489.593 321.168 486.272 c
+321.168 482.96 318.477 480.278 315.165 480.278 c
+311.853 480.278 309.171 482.96 309.171 486.272 c
+309.171 489.593 311.853 492.275 315.165 492.275 c
+315.165 487.275 l
+314.621 487.278 314.17 486.83 314.171 486.272 c
+314.168 485.727 314.619 485.276 315.165 485.278 c
+315.715 485.275 316.172 485.733 316.168 486.272 c
+316.17 486.824 315.713 487.279 315.165 487.275 c
+W n
+q
+/GS0 gs
+/Fm0 Do
+Q
+Q
+
endstream
endobj
1024 0 obj
<</I true/K false/S/Transparency/Type/Group>>
endobj
1026 0 obj
<</Subtype/Form/Length 11079/Matrix[1.0 0.0 0.0 1.0 0.0 0.0]/Group 1025 0 R/Resources<</ColorSpace<</CS0 982 0 R>>/ExtGState<</GS0 978 0 R>>>>/BBox[309.171 492.275 321.168 480.278]>>stream
+/CS0 cs 0.2 0.325 0.624  scn
+1 i 
+/GS0 gs
+q 1 0 0 1 315.165 487.2754 cm
+0 0 m
+0 5 l
+3.312 5 6.003 2.318 6.003 -1.003 c
+6.003 -4.315 3.312 -6.997 0 -6.997 c
+-3.312 -6.997 -5.994 -4.315 -5.994 -1.003 c
+-5.994 2.318 -3.312 5 0 5 c
+0 0 l
+-0.544 0.003 -0.995 -0.445 -0.994 -1.003 c
+-0.997 -1.549 -0.546 -2 0 -1.997 c
+0.55 -2 1.007 -1.542 1.003 -1.003 c
+1.005 -0.451 0.548 0.003 0 0 c
+f
+Q
+q 1 0 0 1 315.165 488.1997 cm
+0 0 m
+-0.013 -0.041 -0.073 -0.074 -0.082 -0.115 c
+-0.11 -0.248 -0.02 -0.425 0 -0.559 c
+0 -0.924 l
+-0.544 -0.921 -0.995 -1.37 -0.994 -1.927 c
+-0.997 -2.473 -0.546 -2.924 0 -2.921 c
+0.55 -2.924 1.007 -2.467 1.003 -1.927 c
+1.005 -1.375 0.548 -0.921 0 -0.924 c
+0 -0.559 l
+0.034 -0.556 0.079 -0.552 0.113 -0.549 c
+0.142 -0.549 0.183 -0.536 0.209 -0.548 c
+1.045 -1.475 l
+1.44 -2.16 1.79 -2.114 1.805 -2.112 c
+2.058 -2.072 3.187 -0.623 1.901 0.191 c
+1.597 0.384 1.274 0.411 1.13 0.396 c
+0 0 l
+0 4.076 l
+3.312 4.076 6.003 1.394 6.003 -1.927 c
+6.003 -5.239 3.312 -7.921 0 -7.921 c
+-3.312 -7.921 -5.994 -5.239 -5.994 -1.927 c
+-5.994 1.394 -3.312 4.076 0 4.076 c
+0 0 l
+f
+Q
+0.196 0.318 0.612  scn
+q 1 0 0 1 315.165 488.3418 cm
+0 0 m
+-0.03 -0.092 -0.163 -0.17 -0.184 -0.265 c
+-0.221 -0.432 -0.125 -0.677 -0.186 -0.837 c
+-0.186 -0.838 -0.235 -0.941 -0.399 -1.048 c
+-1.15 -1.539 -1.036 -2.16 -0.983 -2.339 c
+-0.8 -2.96 -0.143 -3.262 0.452 -2.998 c
+0.652 -2.908 0.791 -2.771 0.873 -2.69 c
+1.144 -2.423 1.548 -2.625 1.836 -2.417 c
+2.431 -1.985 2.564 -1.604 2.628 -1.42 c
+2.85 -0.787 2.46 0.134 1.627 0.371 c
+0.853 0.592 0.002 0.008 0 0 c
+0 3.934 l
+3.312 3.934 6.003 1.251 6.003 -2.069 c
+6.003 -5.381 3.312 -8.063 0 -8.063 c
+-3.312 -8.063 -5.994 -5.381 -5.994 -2.069 c
+-5.994 1.251 -3.312 3.934 0 3.934 c
+0 0 l
+f
+Q
+0.192 0.31 0.596  scn
+q 1 0 0 1 315.165 488.4824 cm
+0 0 m
+-0.294 -0.832 -1.287 -1.354 -1.07 -2.414 c
+-0.931 -3.09 -0.167 -3.555 0.649 -3.164 c
+1.049 -2.972 1.516 -2.957 1.889 -2.695 c
+2.243 -2.445 2.625 -2.13 2.762 -1.679 c
+3.159 -0.375 2.125 0.264 1.73 0.385 c
+0.831 0.662 0.003 0.008 0 0 c
+0 3.793 l
+3.312 3.793 6.003 1.111 6.003 -2.21 c
+6.003 -5.522 3.312 -8.204 0 -8.204 c
+-3.312 -8.204 -5.994 -5.522 -5.994 -2.21 c
+-5.994 1.111 -3.312 3.793 0 3.793 c
+0 0 l
+f
+Q
+0.188 0.302 0.58  scn
+q 1 0 0 1 315.165 488.6216 cm
+0 0 m
+-0.352 -0.867 -1.375 -1.438 -1.138 -2.566 c
+-1.017 -3.142 -0.345 -3.804 0.713 -3.398 c
+2.483 -2.719 2.628 -2.663 2.945 -1.783 c
+2.951 -1.768 3.406 -0.235 2.053 0.317 c
+0.863 0.802 0.004 0.01 0 0 c
+0 3.654 l
+3.312 3.654 6.003 0.972 6.003 -2.349 c
+6.003 -5.661 3.312 -8.343 0 -8.343 c
+-3.312 -8.343 -5.994 -5.661 -5.994 -2.349 c
+-5.994 0.972 -3.312 3.654 0 3.654 c
+0 0 l
+f
+Q
+0.18 0.294 0.569  scn
+q 1 0 0 1 315.165 488.7588 cm
+0 0 m
+-0.192 -0.416 -0.582 -0.691 -0.789 -1.097 c
+-0.793 -1.105 -1.082 -1.703 -1.083 -1.706 c
+-1.253 -2.111 -1.282 -2.441 -1.181 -2.81 c
+-1.118 -3.036 -0.72 -4.135 0.985 -3.564 c
+5.022 -2.213 2.486 0.225 2.452 0.247 c
+1.442 0.897 0.101 0.219 0 0 c
+0 3.517 l
+3.312 3.517 6.003 0.834 6.003 -2.486 c
+6.003 -5.798 3.312 -8.48 0 -8.48 c
+-3.312 -8.48 -5.994 -5.798 -5.994 -2.486 c
+-5.994 0.834 -3.312 3.517 0 3.517 c
+0 0 l
+f
+Q
+0.176 0.286 0.553  scn
+q 1 0 0 1 315.165 488.9116 cm
+0 0 m
+-0.013 -0.025 -0.053 -0.04 -0.076 -0.057 c
+-0.432 -0.327 -0.719 -0.611 -1.164 -1.801 c
+-1.234 -1.99 -1.448 -2.564 -1.178 -3.156 c
+-0.778 -4.031 0.18 -4.2 1.671 -3.658 c
+3.876 -2.856 3.991 -0.38 2.341 0.402 c
+1.366 0.864 0.123 0.248 0 0 c
+0 3.364 l
+3.312 3.364 6.003 0.682 6.003 -2.639 c
+6.003 -5.951 3.312 -8.633 0 -8.633 c
+-3.312 -8.633 -5.994 -5.951 -5.994 -2.639 c
+-5.994 0.682 -3.312 3.364 0 3.364 c
+0 0 l
+f
+Q
+0.173 0.278 0.541  scn
+q 1 0 0 1 315.165 489.1035 cm
+0 0 m
+-0.034 -0.068 -0.142 -0.105 -0.202 -0.15 c
+-0.734 -0.546 -0.993 -1.253 -1.244 -1.936 c
+-1.353 -2.232 -1.496 -2.812 -1.238 -3.374 c
+-0.612 -4.739 1.248 -4.146 1.803 -3.932 c
+4.138 -3.031 4.265 -0.308 2.51 0.419 c
+1.108 1 0.006 0.012 0 0 c
+0 3.172 l
+3.312 3.172 6.003 0.49 6.003 -2.831 c
+6.003 -6.143 3.312 -8.825 0 -8.825 c
+-3.312 -8.825 -5.994 -6.143 -5.994 -2.831 c
+-5.994 0.49 -3.312 3.172 0 3.172 c
+0 0 l
+f
+Q
+0.169 0.275 0.525  scn
+q 1 0 0 1 315.165 489.291 cm
+0 0 m
+-0.037 -0.069 -0.152 -0.103 -0.217 -0.147 c
+-0.48 -0.327 -0.918 -0.951 -1.084 -1.383 c
+-1.402 -2.209 -1.592 -2.802 -1.342 -3.486 c
+-1.138 -4.046 -0.487 -4.899 1.578 -4.322 c
+4.081 -3.623 4.628 -0.763 2.992 0.316 c
+1.701 1.167 0.079 0.149 0 0 c
+0 2.984 l
+3.312 2.984 6.003 0.302 6.003 -3.019 c
+6.003 -6.331 3.312 -9.013 0 -9.013 c
+-3.312 -9.013 -5.994 -6.331 -5.994 -3.019 c
+-5.994 0.302 -3.312 2.984 0 2.984 c
+0 0 l
+f
+Q
+0.165 0.267 0.51  scn
+q 1 0 0 1 315.165 489.4751 cm
+0 0 m
+-0.175 -0.316 -0.541 -0.436 -0.745 -0.721 c
+-1.04 -1.133 -1.134 -1.367 -1.233 -1.614 c
+-1.283 -1.739 -1.712 -2.854 -1.439 -3.598 c
+-0.844 -5.219 1.105 -4.774 1.689 -4.6 c
+4.424 -3.78 5.002 -0.76 3.22 0.385 c
+1.946 1.202 0.234 0.424 0 0 c
+0 2.8 l
+3.312 2.8 6.003 0.118 6.003 -3.203 c
+6.003 -6.515 3.312 -9.197 0 -9.197 c
+-3.312 -9.197 -5.994 -6.515 -5.994 -3.203 c
+-5.994 0.118 -3.312 2.8 0 2.8 c
+0 0 l
+f
+Q
+0.161 0.259 0.498  scn
+q 1 0 0 1 315.165 489.7065 cm
+0 0 m
+-0.06 -0.132 -0.265 -0.21 -0.385 -0.291 c
+-0.751 -0.537 -1.207 -1.436 -1.319 -1.735 c
+-1.402 -1.96 -1.802 -3.124 -1.467 -3.945 c
+-0.712 -5.795 1.956 -4.866 1.982 -4.855 c
+5.299 -3.58 5.174 -0.371 3.116 0.573 c
+1.411 1.355 0.007 0.017 0 0 c
+0 2.569 l
+3.312 2.569 6.003 -0.113 6.003 -3.434 c
+6.003 -6.746 3.312 -9.428 0 -9.428 c
+-3.312 -9.428 -5.994 -6.746 -5.994 -3.434 c
+-5.994 -0.113 -3.312 2.569 0 2.569 c
+0 0 l
+f
+Q
+0.153 0.251 0.482  scn
+q 1 0 0 1 315.165 489.9888 cm
+0 0 m
+-0.04 -0.083 -0.167 -0.135 -0.239 -0.193 c
+-0.739 -0.597 -1.12 -1.159 -1.404 -1.909 c
+-1.678 -2.633 -1.751 -3.637 -1.568 -4.146 c
+-0.856 -6.124 1.88 -5.306 1.908 -5.297 c
+5.872 -3.969 5.347 -0.495 3.422 0.519 c
+1.628 1.464 0.058 0.122 0 0 c
+0 2.287 l
+3.312 2.287 6.003 -0.396 6.003 -3.716 c
+6.003 -7.028 3.312 -9.71 0 -9.71 c
+-3.312 -9.71 -5.994 -7.028 -5.994 -3.716 c
+-5.994 -0.396 -3.312 2.287 0 2.287 c
+0 0 l
+f
+Q
+0.149 0.243 0.467  scn
+q 1 0 0 1 315.165 490.2749 cm
+0 0 m
+-0.045 -0.106 -0.209 -0.167 -0.302 -0.235 c
+-0.485 -0.372 -1.122 -0.935 -1.618 -2.443 c
+-1.723 -2.761 -1.897 -3.881 -1.538 -4.677 c
+-1.024 -5.812 0.792 -6.206 2.512 -5.554 c
+6.336 -4.105 5.75 -0.288 3.153 0.723 c
+1.353 1.423 0.007 0.017 0 0 c
+0 2 l
+3.312 2 6.003 -0.682 6.003 -4.002 c
+6.003 -7.314 3.312 -9.997 0 -9.997 c
+-3.312 -9.997 -5.994 -7.314 -5.994 -4.002 c
+-5.994 -0.682 -3.312 2 0 2 c
+0 0 l
+f
+Q
+0.145 0.235 0.455  scn
+q 1 0 0 1 315.165 490.6582 cm
+0 0 m
+-0.163 -0.361 -0.541 -0.515 -0.777 -0.805 c
+-0.945 -1.011 -1.046 -1.259 -1.201 -1.474 c
+-1.269 -1.568 -1.409 -1.763 -1.714 -2.734 c
+-2.048 -3.798 -1.784 -4.665 -1.597 -5.087 c
+-1.005 -6.421 1.188 -6.695 2.68 -6.041 c
+8.251 -3.594 4.333 0.165 2.965 0.677 c
+1.252 1.319 0.007 0.016 0 0 c
+0 1.617 l
+3.312 1.617 6.003 -1.065 6.003 -4.386 c
+6.003 -7.698 3.312 -10.38 0 -10.38 c
+-3.312 -10.38 -5.994 -7.698 -5.994 -4.386 c
+-5.994 -1.065 -3.312 1.617 0 1.617 c
+0 0 l
+f
+Q
+0.141 0.227 0.439  scn
+q 1 0 0 1 315.165 491.083 cm
+0 0 m
+-0.128 -0.296 -0.441 -0.404 -0.637 -0.631 c
+-0.787 -0.804 -0.891 -1.009 -1.028 -1.191 c
+-1.149 -1.351 -1.614 -2.354 -1.616 -2.362 c
+-2.165 -3.906 -2.034 -4.643 -1.834 -5.161 c
+-0.959 -7.42 1.653 -7.023 2.585 -6.679 c
+3.892 -6.198 6.61 -5.196 5.552 -2.522 c
+5.843 -3.227 6.003 -4 6.003 -4.811 c
+6.003 -8.123 3.312 -10.805 0 -10.805 c
+-3.312 -10.805 -5.994 -8.123 -5.994 -4.811 c
+-5.994 -1.49 -3.312 1.192 0 1.192 c
+0 0 l
+f
+Q
+0.137 0.22 0.427  scn
+q 1 0 0 1 315.165 491.5479 cm
+0 0 m
+-0.037 -0.078 -0.154 -0.129 -0.22 -0.185 c
+-1.232 -1.033 -1.806 -2.828 -1.83 -2.904 c
+-2.22 -4.142 -2.232 -5.159 -1.867 -5.927 c
+-0.58 -8.633 3.354 -7.149 3.394 -7.134 c
+4.44 -6.729 6.193 -6.052 5.898 -4.154 c
+5.967 -4.518 6.003 -4.892 6.003 -5.275 c
+6.003 -8.587 3.312 -11.27 0 -11.27 c
+-3.312 -11.27 -5.994 -8.587 -5.994 -5.275 c
+-5.994 -1.955 -3.312 0.728 0 0.728 c
+0 0 l
+f
+Q
+0.133 0.216 0.412  scn
+q 1 0 0 1 315.165 491.9907 cm
+0 0 m
+-0.038 -0.067 -0.155 -0.091 -0.221 -0.13 c
+-1.146 -0.672 -1.618 -2.109 -1.997 -3.263 c
+-2.003 -3.281 -2.538 -5.073 -2.065 -6.285 c
+-1.01 -8.991 2.93 -7.989 3.097 -7.945 c
+4.317 -7.624 5.989 -7.184 6.001 -5.584 c
+6.002 -5.628 6.003 -5.673 6.003 -5.718 c
+6.003 -9.03 3.312 -11.712 0 -11.712 c
+-3.312 -11.712 -5.994 -9.03 -5.994 -5.718 c
+-5.994 -2.397 -3.312 0.285 0 0.285 c
+0 0 l
+f
+Q
+0.125 0.208 0.396  scn
+q 1 0 0 1 315.165 492.2632 cm
+0 0 m
+-0.043 -0.052 -0.154 -0.029 -0.221 -0.042 c
+-0.695 -0.132 -1.346 -0.69 -1.729 -1.732 c
+-2.601 -4.102 -2.422 -5.693 -2.305 -6.268 c
+-1.773 -8.88 1.72 -8.614 1.755 -8.61 c
+4.215 -8.37 5.7 -8.226 5.951 -6.783 c
+5.562 -9.72 3.043 -11.985 0 -11.985 c
+-3.312 -11.985 -5.994 -9.303 -5.994 -5.991 c
+-5.994 -2.67 -3.312 0.012 0 0.012 c
+0 0 l
+f
+Q
+0.122 0.2 0.384  scn
+q 1 0 0 1 314.2603 492.1987 cm
+0 0 m
+-1.727 -0.587 -1.739 -4.385 -1.738 -4.546 c
+-1.734 -6.483 -1.193 -7.61 0.017 -8.2 c
+1.798 -9.069 6.085 -9.361 6.66 -7.637 c
+5.921 -10.115 3.622 -11.92 0.905 -11.92 c
+-2.407 -11.92 -5.089 -9.238 -5.089 -5.926 c
+-5.089 -2.857 -2.798 -0.333 0.165 0.032 c
+0.115 0.022 0.048 0.013 0 0 c
+f
+Q
+0.118 0.192 0.369  scn
+q 1 0 0 1 312.9341 491.7764 cm
+0 0 m
+-1.086 -0.961 -0.817 -4.853 -0.535 -5.61 c
+0.431 -8.208 2.403 -8.585 3.207 -8.626 c
+4.27 -8.681 5.298 -9.068 6.378 -8.967 c
+6.691 -8.938 7.264 -8.802 7.584 -8.218 c
+6.592 -10.165 4.566 -11.498 2.231 -11.498 c
+-1.081 -11.498 -3.763 -8.816 -3.763 -5.504 c
+-3.763 -2.812 -2 -0.54 0.432 0.225 c
+0.372 0.2 0.292 0.168 0.231 0.144 c
+0.161 0.102 0.062 0.054 0 0 c
+f
+Q
+0.204 0.333 0.639  scn
+q 1 0 0 1 316.7451 486.4531 cm
+0 0 m
+-0.091 0.065 -0.091 0.065 -0.52 0.593 c
+-0.662 0.769 -0.836 0.916 -0.974 1.096 c
+-1.233 1.432 -1.232 1.599 -1.232 1.6 c
+-1.226 1.62 -0.028 2.446 0.591 1.368 c
+1.026 0.611 0.245 -0.132 0.233 -0.134 c
+0.153 -0.145 0.065 -0.047 0 0 c
+f
+Q
+0.141 0.227 0.439  scn
+q 1 0 0 1 317.7354 491.6665 cm
+0 0 m
+-1.294 0.462 -2.254 -0.325 -2.57 -0.583 c
+-2.57 0.609 l
+-1.403 0.609 -0.313 0.276 0.609 -0.301 c
+0.52 -0.251 0.4 -0.185 0.31 -0.134 c
+0.217 -0.094 0.095 -0.034 0 0 c
+f
+Q
+0.208 0.337 0.655  scn
+q 1 0 0 1 316.7852 486.708 cm
+0 0 m
+-0.336 0.357 l
+-0.473 0.528 -0.628 0.683 -0.758 0.858 c
+-0.977 1.152 -1.021 1.271 -1.02 1.277 c
+-1.015 1.292 -0.028 1.706 0.328 0.955 c
+0.588 0.409 0.173 -0.121 0.167 -0.122 c
+0.106 -0.133 0.047 -0.04 0 0 c
+f
+Q
+0.137 0.22 0.427  scn
+q 1 0 0 1 316.9321 491.998 cm
+0 0 m
+-0.649 0.12 -1.161 -0.01 -1.767 -0.45 c
+-1.767 0.277 l
+-1.039 0.277 -0.34 0.147 0.306 -0.09 c
+0.223 -0.065 0.111 -0.031 0.028 -0.006 c
+0.02 -0.004 0.008 -0.001 0 0 c
+f
+Q
+0.216 0.345 0.667  scn
+q 1 0 0 1 316.7891 486.9756 cm
+0 0 m
+-0.004 0.004 -0.536 0.578 -0.712 0.865 c
+-0.569 0.878 -0.483 0.886 -0.265 0.812 c
+-0.18 0.784 -0.084 0.701 -0.026 0.633 c
+0.032 0.564 0.089 0.451 0.102 0.362 c
+0.133 0.142 0.096 0.015 0.073 -0.061 c
+0.051 -0.042 0.021 -0.02 0 0 c
+f
+Q
+0.133 0.216 0.412  scn
+q 1 0 0 1 316.0703 492.1978 cm
+0 0 m
+-0.314 -0.005 -0.486 -0.009 -0.905 -0.207 c
+-0.905 0.078 l
+-0.519 0.078 -0.142 0.041 0.224 -0.028 c
+0.157 -0.02 0.067 -0.003 0 0 c
+f
+Q
+0.125 0.208 0.396  scn
+q 1 0 0 1 315.165 492.2632 cm
+0 0 m
+0 0.012 l
+0.072 0.012 0.144 0.011 0.215 0.008 c
+0.15 0.006 0.046 -0.044 0 0 c
+f
+Q
+
endstream
endobj
1025 0 obj
<</I true/K false/S/Transparency/Type/Group>>
endobj
1015 0 obj
<</I true/K false/S/Transparency/Type/Group>>
endobj
1019 0 obj
<</Subtype/Form/Length 473/Matrix[1.0 0.0 0.0 1.0 0.0 0.0]/Group 1016 0 R/Resources<</XObject<</Fm0 1018 0 R>>/ExtGState<</GS0 978 0 R>>>>/BBox[295.671 461.774 351.669 405.776]>>stream
+q
+323.67 445.774 m
+323.67 461.774 l
+339.132 461.774 351.669 449.237 351.669 433.775 c
+351.669 418.313 339.132 405.776 323.67 405.776 c
+308.199 405.776 295.671 418.313 295.671 433.775 c
+295.671 449.237 308.199 461.774 323.67 461.774 c
+323.67 445.774 l
+317.055 445.784 311.661 440.386 311.671 433.775 c
+311.661 427.165 317.055 421.767 323.67 421.776 c
+330.277 421.766 335.68 427.168 335.669 433.775 c
+335.68 440.383 330.277 445.785 323.67 445.774 c
+W n
+q
+/GS0 gs
+/Fm0 Do
+Q
+Q
+
endstream
endobj
1016 0 obj
<</I true/K false/S/Transparency/Type/Group>>
endobj
1018 0 obj
<</Subtype/Form/Length 13391/Matrix[1.0 0.0 0.0 1.0 0.0 0.0]/Group 1017 0 R/Resources<</ColorSpace<</CS0 982 0 R>>/ExtGState<</GS0 978 0 R>>>>/BBox[295.671 461.774 351.669 405.776]>>stream
+/CS0 cs 0.208 0.337 0.655  scn
+1 i 
+/GS0 gs
+q 1 0 0 1 323.6699 445.7744 cm
+0 0 m
+0 16 l
+15.462 16 27.999 3.463 27.999 -11.999 c
+27.999 -27.461 15.462 -39.998 0 -39.998 c
+-15.471 -39.998 -27.999 -27.461 -27.999 -11.999 c
+-27.999 3.463 -15.471 16 0 16 c
+0 0 l
+-6.615 0.009 -12.009 -5.389 -11.999 -11.999 c
+-12.009 -18.609 -6.615 -24.007 0 -23.998 c
+6.607 -24.009 12.01 -18.606 11.999 -11.999 c
+12.01 -5.392 6.607 0.011 0 0 c
+f
+Q
+q 1 0 0 1 323.6699 450.936 cm
+0 0 m
+0 -0.46 l
+0 -5.162 l
+-6.615 -5.152 -12.009 -10.55 -11.999 -17.161 c
+-12.009 -23.771 -6.615 -29.169 0 -29.16 c
+6.607 -29.17 12.01 -23.768 11.999 -17.161 c
+12.01 -10.553 6.607 -5.151 0 -5.162 c
+0 -0.46 l
+0.316 -0.687 0.738 -0.99 1.054 -1.216 c
+3.814 -3.66 7.459 -4.866 10 -7.615 c
+12.018 -9.799 13.458 -12.46 14.279 -15.526 c
+15.091 -18.561 16.901 -19.341 16.918 -19.343 c
+18.873 -19.537 24.733 -10.481 17.857 -2.239 c
+10.881 6.124 0.77 1.958 0 0 c
+0 10.838 l
+15.462 10.838 27.999 -1.699 27.999 -17.161 c
+27.999 -32.623 15.462 -45.16 0 -45.16 c
+-15.471 -45.16 -27.999 -32.623 -27.999 -17.161 c
+-27.999 -1.699 -15.471 10.838 0 10.838 c
+0 0 l
+f
+Q
+0.204 0.333 0.639  scn
+q 1 0 0 1 323.6699 452.7832 cm
+0 0 m
+-0.297 -0.712 -1.488 -1.167 -1.738 -1.898 c
+-1.989 -2.637 -2.005 -3.871 -1.531 -4.492 c
+-1.227 -4.891 -0.45 -4.943 0 -5.165 c
+0 -7.009 l
+-6.615 -7 -12.009 -12.397 -11.999 -19.008 c
+-12.009 -25.618 -6.615 -31.016 0 -31.007 c
+6.607 -31.018 12.01 -25.615 11.999 -19.008 c
+12.01 -12.4 6.607 -6.998 0 -7.009 c
+0 -5.165 l
+0.338 -5.198 0.788 -5.242 1.126 -5.275 c
+2.249 -5.474 12.142 -7.557 13.761 -19.535 c
+14.172 -22.508 l
+14.637 -23.083 15.725 -23.499 16.46 -23.421 c
+20.584 -22.986 26.414 -9.565 15.896 -1.31 c
+7.945 4.929 0.035 0.084 0 0 c
+0 8.991 l
+15.462 8.991 27.999 -3.546 27.999 -19.008 c
+27.999 -34.47 15.462 -47.007 0 -47.007 c
+-15.471 -47.007 -27.999 -34.47 -27.999 -19.008 c
+-27.999 -3.546 -15.471 8.991 0 8.991 c
+0 0 l
+f
+Q
+0.2 0.325 0.624  scn
+q 1 0 0 1 323.6699 453.9038 cm
+0 0 m
+-0.627 -1.11 -1.868 -1.524 -2.71 -2.39 c
+-4.768 -4.502 -4.451 -6.209 -4.444 -6.223 c
+-4.359 -6.387 -4.359 -6.387 0 -7.407 c
+0 -8.129 l
+-6.615 -8.12 -12.009 -13.518 -11.999 -20.128 c
+-12.009 -26.739 -6.615 -32.137 0 -32.127 c
+6.607 -32.138 12.01 -26.736 11.999 -20.128 c
+12.01 -13.521 6.607 -8.119 0 -8.129 c
+0 -7.407 l
+0.312 -7.427 0.727 -7.454 1.039 -7.474 c
+5.586 -8.118 13.154 -12.018 12.674 -22.547 c
+12.56 -25.06 12.663 -26.477 12.982 -26.758 c
+14.311 -27.928 23.356 -23.682 22.629 -14.041 c
+21.27 3.998 1.142 2.018 0 0 c
+0 7.871 l
+15.462 7.871 27.999 -4.667 27.999 -20.128 c
+27.999 -35.59 15.462 -48.127 0 -48.127 c
+-15.471 -48.127 -27.999 -35.59 -27.999 -20.128 c
+-27.999 -4.667 -15.471 7.871 0 7.871 c
+0 0 l
+f
+Q
+0.196 0.318 0.612  scn
+q 1 0 0 1 323.6699 454.8291 cm
+0 0 m
+-0.223 -0.378 -0.896 -0.494 -1.28 -0.706 c
+-3.988 -2.198 -4.356 -2.882 -7.222 -8.202 c
+-10.979 -15.406 l
+-12.035 -17.648 -12.409 -19.972 -12.123 -22.51 c
+-11.368 -29.204 -4.441 -35.039 3.701 -32.831 c
+16.504 -28.45 l
+19.64 -26.383 21.524 -23.889 22.614 -20.364 c
+24.61 -13.907 21.812 -4.74 13.674 -0.575 c
+6.261 3.219 0.029 0.049 0 0 c
+0 6.945 l
+15.462 6.945 27.999 -5.592 27.999 -21.054 c
+27.999 -36.516 15.462 -49.053 0 -49.053 c
+-15.471 -49.053 -27.999 -36.516 -27.999 -21.054 c
+-27.999 -5.592 -15.471 6.945 0 6.945 c
+0 0 l
+f
+Q
+0.192 0.31 0.596  scn
+q 1 0 0 1 323.6699 455.6289 cm
+0 0 m
+-11.795 -5.181 -18.994 -27.783 -4.636 -33.729 c
+5.806 -38.053 30.469 -28.935 22.345 -10.09 c
+19.107 -2.58 10.176 3.509 0 0 c
+0 6.146 l
+15.462 6.146 27.999 -6.392 27.999 -21.854 c
+27.999 -37.315 15.462 -49.853 0 -49.853 c
+-15.471 -49.853 -27.999 -37.315 -27.999 -21.854 c
+-27.999 -6.392 -15.471 6.146 0 6.146 c
+0 0 l
+f
+Q
+0.188 0.302 0.58  scn
+q 1 0 0 1 323.6699 456.3296 cm
+0 0 m
+-0.26 -0.393 -1.011 -0.429 -1.444 -0.612 c
+-4.284 -1.815 -7.534 -4.967 -9.349 -8.277 c
+-13.499 -15.843 -13.758 -21.083 -13.244 -24.145 c
+-12.335 -29.557 -7.256 -38.113 6.018 -35.852 c
+29.65 -31.827 27.567 -10.229 15.691 -2.187 c
+7.726 3.206 0.039 0.058 0 0 c
+0 5.445 l
+15.462 5.445 27.999 -7.092 27.999 -22.554 c
+27.999 -38.016 15.462 -50.553 0 -50.553 c
+-15.471 -50.553 -27.999 -38.016 -27.999 -22.554 c
+-27.999 -7.092 -15.471 5.445 0 5.445 c
+0 0 l
+f
+Q
+0.18 0.294 0.569  scn
+q 1 0 0 1 323.6699 456.9956 cm
+0 0 m
+-0.271 -0.397 -1.043 -0.41 -1.49 -0.586 c
+-3.112 -1.224 -7.251 -3.368 -10.636 -9.471 c
+-11.688 -11.366 -15.022 -18.08 -13.796 -24.877 c
+-12.453 -32.323 -5.461 -39.361 6.714 -37.217 c
+28.943 -33.303 28.97 -11.254 15.609 -2.3 c
+7.857 2.895 0.038 0.056 0 0 c
+0 4.779 l
+15.462 4.779 27.999 -7.758 27.999 -23.22 c
+27.999 -38.682 15.462 -51.219 0 -51.219 c
+-15.471 -51.219 -27.999 -38.682 -27.999 -23.22 c
+-27.999 -7.758 -15.471 4.779 0 4.779 c
+0 0 l
+f
+Q
+0.176 0.286 0.553  scn
+q 1 0 0 1 323.6699 457.6064 cm
+0 0 m
+-0.285 -0.403 -1.086 -0.384 -1.551 -0.549 c
+-2.515 -0.89 -7.505 -2.918 -11.143 -9.4 c
+-12.539 -11.886 -15.644 -18.437 -14.343 -25.553 c
+-13.275 -31.396 -7.567 -40.711 7.05 -38.566 c
+28.064 -35.482 30.902 -13.127 16.17 -2.838 c
+7.979 2.883 0.04 0.057 0 0 c
+0 4.168 l
+15.462 4.168 27.999 -8.369 27.999 -23.831 c
+27.999 -39.293 15.462 -51.83 0 -51.83 c
+-15.471 -51.83 -27.999 -39.293 -27.999 -23.831 c
+-27.999 -8.369 -15.471 4.168 0 4.168 c
+0 0 l
+f
+Q
+0.173 0.278 0.541  scn
+q 1 0 0 1 323.6699 458.1792 cm
+0 0 m
+-0.295 -0.407 -1.114 -0.365 -1.591 -0.521 c
+-3.039 -0.995 -8.059 -3.066 -11.891 -9.807 c
+-12.952 -11.675 -16.307 -18.377 -14.887 -26.189 c
+-13.692 -32.762 -6.813 -41.823 7.243 -39.848 c
+28.687 -36.834 31.471 -13.847 16.374 -3.144 c
+8.08 2.737 0.041 0.056 0 0 c
+0 3.595 l
+15.462 3.595 27.999 -8.942 27.999 -24.404 c
+27.999 -39.866 15.462 -52.403 0 -52.403 c
+-15.471 -52.403 -27.999 -39.866 -27.999 -24.404 c
+-27.999 -8.942 -15.471 3.595 0 3.595 c
+0 0 l
+f
+Q
+0.169 0.275 0.525  scn
+q 1 0 0 1 323.6699 458.7163 cm
+0 0 m
+-0.327 -0.44 -1.225 -0.369 -1.749 -0.527 c
+-5.521 -1.665 -9.768 -5.259 -12.076 -9.267 c
+-15.396 -15.033 -16.523 -20.929 -15.426 -26.791 c
+-13.856 -35.175 -5.227 -43.009 7.675 -41.011 c
+29.382 -37.65 31.673 -13.956 16.092 -3.122 c
+8.188 2.374 0.041 0.052 0 0 c
+0 3.058 l
+15.462 3.058 27.999 -9.479 27.999 -24.941 c
+27.999 -40.403 15.462 -52.94 0 -52.94 c
+-15.471 -52.94 -27.999 -40.403 -27.999 -24.941 c
+-27.999 -9.479 -15.471 3.058 0 3.058 c
+0 0 l
+f
+Q
+0.165 0.267 0.51  scn
+q 1 0 0 1 323.6699 459.2314 cm
+0 0 m
+-0.315 -0.414 -1.17 -0.321 -1.672 -0.458 c
+-5.63 -1.542 -10.189 -5.222 -12.512 -9.206 c
+-13.797 -11.409 -17.707 -18.115 -15.958 -27.369 c
+-14.312 -36.085 -5.369 -44.227 7.962 -42.147 c
+29.823 -38.738 32.256 -15.066 16.713 -3.752 c
+8.241 2.415 0.041 0.054 0 0 c
+0 2.543 l
+15.462 2.543 27.999 -9.994 27.999 -25.456 c
+27.999 -40.918 15.462 -53.455 0 -53.455 c
+-15.471 -53.455 -27.999 -40.918 -27.999 -25.456 c
+-27.999 -9.994 -15.471 2.543 0 2.543 c
+0 0 l
+f
+Q
+0.161 0.259 0.498  scn
+q 1 0 0 1 323.6699 459.7041 cm
+0 0 m
+-0.326 -0.417 -1.198 -0.297 -1.711 -0.424 c
+-5.006 -1.24 -10.024 -4.173 -13.32 -9.752 c
+-16.644 -15.378 -17.708 -21.484 -16.484 -27.903 c
+-14.771 -36.889 -5.522 -45.311 8.242 -43.22 c
+29.813 -39.944 32.242 -15.421 16.845 -4.05 c
+8.507 2.107 0.042 0.053 0 0 c
+0 2.07 l
+15.462 2.07 27.999 -10.467 27.999 -25.929 c
+27.999 -41.391 15.462 -53.928 0 -53.928 c
+-15.471 -53.928 -27.999 -41.391 -27.999 -25.929 c
+-27.999 -10.467 -15.471 2.07 0 2.07 c
+0 0 l
+f
+Q
+0.153 0.251 0.482  scn
+q 1 0 0 1 323.6699 460.144 cm
+0 0 m
+-0.165 -0.201 -0.596 -0.119 -0.852 -0.169 c
+-6.632 -1.32 -11.089 -5.48 -13.333 -8.99 c
+-17.824 -16.015 -17.96 -22.678 -17.283 -27.031 c
+-15.529 -38.309 -5.353 -45.633 6.914 -44.447 c
+29.053 -42.307 33.213 -18.564 18.588 -5.674 c
+9.722 2.142 0.051 0.062 0 0 c
+0 1.63 l
+15.462 1.63 27.999 -10.907 27.999 -26.369 c
+27.999 -41.831 15.462 -54.368 0 -54.368 c
+-15.471 -54.368 -27.999 -41.831 -27.999 -26.369 c
+-27.999 -10.907 -15.471 1.63 0 1.63 c
+0 0 l
+f
+Q
+0.149 0.243 0.467  scn
+q 1 0 0 1 323.6699 460.5547 cm
+0 0 m
+-0.345 -0.419 -1.243 -0.245 -1.776 -0.35 c
+-5.454 -1.074 -10.584 -3.985 -13.756 -8.856 c
+-18.476 -16.104 -18.606 -22.976 -17.885 -27.465 c
+-16.272 -37.503 -7.101 -46.92 7.31 -45.498 c
+29.575 -43.3 33.52 -19.115 18.666 -5.998 c
+9.679 1.938 0.05 0.061 0 0 c
+0 1.22 l
+15.462 1.22 27.999 -11.317 27.999 -26.779 c
+27.999 -42.241 15.462 -54.778 0 -54.778 c
+-15.471 -54.778 -27.999 -42.241 -27.999 -26.779 c
+-27.999 -11.317 -15.471 1.22 0 1.22 c
+0 0 l
+f
+Q
+0.145 0.235 0.455  scn
+q 1 0 0 1 323.6699 460.9102 cm
+0 0 m
+-0.359 -0.424 -1.28 -0.213 -1.828 -0.305 c
+-2.573 -0.429 -9.242 -1.712 -14.038 -8.521 c
+-19.338 -16.045 -19.04 -23.601 -18.666 -26.5 c
+-16.79 -41.035 -4.557 -47.119 6.015 -46.621 c
+29.237 -45.525 34.039 -19.966 18.705 -6.311 c
+9.693 1.714 0.05 0.059 0 0 c
+0 0.864 l
+15.462 0.864 27.999 -11.673 27.999 -27.135 c
+27.999 -42.597 15.462 -55.134 0 -55.134 c
+-15.471 -55.134 -27.999 -42.597 -27.999 -27.135 c
+-27.999 -11.673 -15.471 0.864 0 0.864 c
+0 0 l
+f
+Q
+0.141 0.227 0.439  scn
+q 1 0 0 1 323.6699 461.2358 cm
+0 0 m
+-0.366 -0.422 -1.291 -0.183 -1.844 -0.262 c
+-5.618 -0.797 -11.206 -3.577 -14.557 -8.414 c
+-20.527 -17.033 -19.484 -25.013 -19.142 -27.635 c
+-17.325 -41.544 -4.721 -48.297 6.215 -47.587 c
+22.825 -46.511 31.838 -32.41 25.896 -16.796 c
+27.251 -20.083 27.999 -23.685 27.999 -27.46 c
+27.999 -42.922 15.462 -55.459 0 -55.459 c
+-15.471 -55.459 -27.999 -42.922 -27.999 -27.46 c
+-27.999 -11.999 -15.471 0.539 0 0.539 c
+0 0 l
+f
+Q
+0.137 0.22 0.427  scn
+q 1 0 0 1 323.6699 461.4912 cm
+0 0 m
+-0.38 -0.425 -1.323 -0.147 -1.89 -0.211 c
+-3.742 -0.417 -10.186 -1.632 -15.337 -8.604 c
+-20.121 -15.077 -20.496 -23.224 -19.964 -27.016 c
+-18.071 -40.5 -7.311 -49.138 6.811 -48.512 c
+13.567 -48.212 30.458 -42.954 27.513 -22.495 c
+27.832 -24.187 27.999 -25.932 27.999 -27.716 c
+27.999 -43.178 15.462 -55.715 0 -55.715 c
+-15.471 -55.715 -27.999 -43.178 -27.999 -27.716 c
+-27.999 -12.254 -15.471 0.283 0 0.283 c
+0 0 l
+f
+Q
+0.133 0.216 0.412  scn
+q 1 0 0 1 323.6699 461.6821 cm
+0 0 m
+-0.389 -0.422 -1.334 -0.109 -1.906 -0.156 c
+-5.864 -0.48 -11.765 -2.986 -15.37 -7.721 c
+-21.457 -15.717 -21.121 -23.997 -20.694 -27.186 c
+-18.848 -40.99 -7.359 -50.367 6.621 -49.484 c
+16.365 -48.868 27.809 -42.685 27.992 -27.284 c
+27.997 -27.491 27.999 -27.699 27.999 -27.907 c
+27.999 -43.369 15.462 -55.906 0 -55.906 c
+-15.471 -55.906 -27.999 -43.369 -27.999 -27.907 c
+-27.999 -12.445 -15.471 0.092 0 0.092 c
+0 0 l
+f
+Q
+0.125 0.208 0.396  scn
+q 1 0 0 1 323.6699 461.771 cm
+0 0 m
+-0.403 -0.423 -1.362 -0.067 -1.946 -0.096 c
+-5.655 -0.278 -11.174 -1.795 -16.41 -7.986 c
+-19.422 -11.547 -22.258 -18.903 -21.583 -25.522 c
+-19.025 -50.59 4.157 -50.418 5.143 -50.399 c
+17.394 -50.156 25.847 -43.167 27.756 -31.704 c
+25.941 -45.413 14.205 -55.995 0 -55.995 c
+-15.471 -55.995 -27.999 -43.458 -27.999 -27.996 c
+-27.999 -12.534 -15.471 0.003 0 0.003 c
+0 0 l
+f
+Q
+0.122 0.2 0.384  scn
+q 1 0 0 1 319.437 461.4541 cm
+0 0 m
+-22.531 -4.549 -23.531 -35.025 -6.331 -46.258 c
+6.847 -54.864 25.642 -52.17 31.071 -35.682 c
+27.627 -47.245 16.914 -55.678 4.233 -55.678 c
+-11.238 -55.678 -23.766 -43.141 -23.766 -27.679 c
+-23.766 -13.386 -13.062 -1.593 0.777 0.109 c
+0.544 0.077 0.232 0.04 0 0 c
+f
+Q
+0.118 0.192 0.369  scn
+q 1 0 0 1 311.6421 458.9941 cm
+0 0 m
+-16.565 -9.064 -17.346 -40.196 9.317 -48.713 c
+16.643 -51.053 30.634 -50.189 36.991 -37.91 c
+32.363 -46.995 22.921 -53.218 12.028 -53.218 c
+-3.443 -53.218 -15.971 -40.681 -15.971 -25.219 c
+-15.971 -12.684 -7.737 -2.07 3.624 1.498 c
+3.099 1.309 2.397 1.056 1.872 0.866 c
+1.309 0.609 0.542 0.297 0 0 c
+f
+Q
+0.216 0.345 0.667  scn
+q 1 0 0 1 339.5962 435.5991 cm
+0 0 m
+-1.706 2.422 -2.871 5.192 -4.806 7.466 c
+-5.581 8.375 -6.334 9.141 -7.046 9.74 c
+-7.103 9.788 -12.699 14.577 -12.705 14.929 c
+-12.707 15.035 -10.925 16.753 -10.74 16.825 c
+-10.058 17.086 -7.544 17.231 -6.875 17.166 c
+-5.111 16.992 -2.438 16.241 0.275 13.649 c
+3.79 10.293 4.269 6.382 4.332 5.263 c
+4.608 0.362 1.816 -1.553 1.125 -1.426 c
+0.589 -1.328 0.314 -0.445 0 0 c
+f
+Q
+0.22 0.353 0.682  scn
+q 1 0 0 1 339.7305 438.0928 cm
+0 0 m
+-1.97 2.883 -3.055 4.471 -4.87 6.595 c
+-5.072 6.832 -5.375 7.116 -5.591 7.34 c
+-5.844 7.601 -6.16 7.969 -6.419 8.224 c
+-6.913 8.711 -7.551 9.382 -8.074 9.839 c
+-9.724 11.281 -9.908 11.547 -9.911 11.595 c
+-9.914 11.657 -8.495 13.252 -8.295 13.411 c
+-8.132 13.541 -7.808 13.456 -7.601 13.433 c
+-5.32 13.184 -2.962 12.927 -0.476 10.566 c
+2.531 7.709 2.783 5.143 2.904 3.909 c
+2.938 3.565 2.929 0.875 2.709 0.41 c
+2.675 0.337 0.707 -0.875 0.645 -0.861 c
+0.33 -0.793 0.182 -0.267 0 0 c
+f
+Q
+0.224 0.361 0.694  scn
+q 1 0 0 1 338.8154 441.6221 cm
+0 0 m
+-0.737 0.235 -1.076 1.45 -1.576 2.04 c
+-3.148 3.894 -3.148 3.894 -3.897 4.678 c
+-4.212 5.008 -4.84 5.354 -4.922 5.803 c
+-4.014 7.981 l
+-3.953 8.007 -1.427 7.15 0.33 5.083 c
+1.631 3.552 2.397 0.755 2.281 0.574 c
+1.906 -0.01 0.699 -0.197 0.037 0.011 c
+0.026 0.014 0.011 -0.003 0 0 c
+f
+Q
+0.141 0.227 0.439  scn
+q 1 0 0 1 335.7192 459.0469 cm
+0 0 m
+-5.275 2.417 -9.403 2.407 -12.049 2.189 c
+-12.049 2.728 l
+-6.604 2.728 -1.522 1.173 2.777 -1.517 c
+2.232 -1.205 1.506 -0.789 0.961 -0.477 c
+0.673 -0.334 0.292 -0.134 0 0 c
+f
+Q
+0.137 0.22 0.427  scn
+q 1 0 0 1 331.9331 460.5313 cm
+0 0 m
+-3.078 0.794 -4.478 1.111 -8.263 0.96 c
+-8.263 1.243 l
+-4.866 1.243 -1.61 0.638 1.402 -0.47 c
+0.981 -0.329 0.425 -0.126 0 0 c
+f
+Q
+0.133 0.216 0.412  scn
+q 1 0 0 1 327.9009 461.4541 cm
+0 0 m
+-1.314 0.178 -2.48 0.278 -4.231 0.228 c
+-4.231 0.32 l
+-2.431 0.32 -0.671 0.15 1.035 -0.174 c
+0.724 -0.122 0.312 -0.042 0 0 c
+f
+Q
+0.125 0.208 0.396  scn
+q 1 0 0 1 323.6699 461.771 cm
+0 0 m
+0.335 0.003 0.669 -0.002 1.001 -0.014 c
+0.701 -0.01 0.211 -0.214 0 0 c
+f
+Q
+
endstream
endobj
1017 0 obj
<</I true/K false/S/Transparency/Type/Group>>
endobj
1005 0 obj
<</I true/K false/S/Transparency/Type/Group>>
endobj
1009 0 obj
<</Subtype/Form/Length 478/Matrix[1.0 0.0 0.0 1.0 0.0 0.0]/Group 1006 0 R/Resources<</XObject<</Fm0 1008 0 R>>/ExtGState<</GS0 978 0 R>>>>/BBox[321.996 217.271 334.002 205.274]>>stream
+q
+327.999 212.271 m
+327.999 217.271 l
+331.311 217.271 334.002 214.59 334.002 211.277 c
+334.002 207.966 331.311 205.274 327.999 205.274 c
+324.687 205.274 321.996 207.966 321.996 211.277 c
+321.996 214.59 324.687 217.271 327.999 217.271 c
+327.999 212.271 l
+327.449 212.274 326.992 211.817 326.996 211.277 c
+326.991 210.734 327.456 210.27 327.999 210.274 c
+328.542 210.27 329.007 210.734 329.002 211.277 c
+329.006 211.817 328.549 212.274 327.999 212.271 c
+W n
+q
+/GS0 gs
+/Fm0 Do
+Q
+Q
+
endstream
endobj
1006 0 obj
<</I true/K false/S/Transparency/Type/Group>>
endobj
1008 0 obj
<</Subtype/Form/Length 11068/Matrix[1.0 0.0 0.0 1.0 0.0 0.0]/Group 1007 0 R/Resources<</ColorSpace<</CS0 982 0 R>>/ExtGState<</GS0 978 0 R>>>>/BBox[321.996 217.271 334.002 205.274]>>stream
+/CS0 cs 0.294 0.494 0.133  scn
+1 i 
+/GS0 gs
+q 1 0 0 1 327.999 212.2715 cm
+0 0 m
+0 5 l
+3.312 5 6.003 2.318 6.003 -0.994 c
+6.003 -4.306 3.312 -6.997 0 -6.997 c
+-3.312 -6.997 -6.003 -4.306 -6.003 -0.994 c
+-6.003 2.318 -3.312 5 0 5 c
+0 0 l
+-0.55 0.003 -1.007 -0.454 -1.003 -0.994 c
+-1.008 -1.537 -0.543 -2.002 0 -1.997 c
+0.543 -2.002 1.008 -1.537 1.003 -0.994 c
+1.007 -0.454 0.55 0.003 0 0 c
+f
+Q
+q 1 0 0 1 327.999 213.1963 cm
+0 0 m
+-0.013 -0.041 -0.073 -0.074 -0.083 -0.115 c
+-0.111 -0.248 -0.02 -0.426 0 -0.56 c
+0 -0.925 l
+-0.55 -0.922 -1.007 -1.379 -1.003 -1.919 c
+-1.008 -2.462 -0.543 -2.927 0 -2.922 c
+0.543 -2.927 1.008 -2.462 1.003 -1.919 c
+1.007 -1.379 0.55 -0.922 0 -0.925 c
+0 -0.56 l
+0.034 -0.557 0.079 -0.553 0.113 -0.55 c
+0.142 -0.55 0.184 -0.536 0.21 -0.549 c
+1.046 -1.473 l
+1.441 -2.153 1.79 -2.106 1.805 -2.104 c
+2.057 -2.064 3.185 -0.619 1.901 0.191 c
+1.598 0.383 1.275 0.409 1.132 0.396 c
+0 0 l
+0 4.075 l
+3.312 4.075 6.003 1.394 6.003 -1.919 c
+6.003 -5.23 3.312 -7.922 0 -7.922 c
+-3.312 -7.922 -6.003 -5.23 -6.003 -1.919 c
+-6.003 1.394 -3.312 4.075 0 4.075 c
+0 0 l
+f
+Q
+0.286 0.482 0.133  scn
+q 1 0 0 1 327.999 213.3379 cm
+0 0 m
+-0.03 -0.092 -0.164 -0.17 -0.185 -0.265 c
+-0.222 -0.433 -0.125 -0.678 -0.188 -0.838 c
+-0.188 -0.839 -0.237 -0.941 -0.404 -1.049 c
+-1.156 -1.538 -1.044 -2.153 -0.992 -2.33 c
+-0.81 -2.948 -0.137 -3.26 0.449 -2.997 c
+0.649 -2.907 0.789 -2.769 0.872 -2.687 c
+1.143 -2.418 1.548 -2.618 1.836 -2.409 c
+2.434 -1.976 2.571 -1.584 2.629 -1.416 c
+2.851 -0.784 2.461 0.135 1.628 0.371 c
+0.853 0.591 0.002 0.008 0 0 c
+0 3.934 l
+3.312 3.934 6.003 1.252 6.003 -2.061 c
+6.003 -5.372 3.312 -8.063 0 -8.063 c
+-3.312 -8.063 -6.003 -5.372 -6.003 -2.061 c
+-6.003 1.252 -3.312 3.934 0 3.934 c
+0 0 l
+f
+Q
+0.278 0.471 0.129  scn
+q 1 0 0 1 327.999 213.4785 cm
+0 0 m
+-0.294 -0.83 -1.296 -1.345 -1.079 -2.404 c
+-0.955 -3.01 -0.239 -3.591 0.647 -3.163 c
+1.047 -2.97 1.515 -2.951 1.888 -2.688 c
+2.104 -2.536 2.607 -2.182 2.763 -1.673 c
+3.16 -0.374 2.125 0.264 1.731 0.385 c
+0.831 0.661 0.003 0.009 0 0 c
+0 3.793 l
+3.312 3.793 6.003 1.111 6.003 -2.201 c
+6.003 -5.513 3.312 -8.204 0 -8.204 c
+-3.312 -8.204 -6.003 -5.513 -6.003 -2.201 c
+-6.003 1.111 -3.312 3.793 0 3.793 c
+0 0 l
+f
+Q
+0.275 0.459 0.125  scn
+q 1 0 0 1 327.999 213.6182 cm
+0 0 m
+-0.352 -0.866 -1.383 -1.428 -1.146 -2.558 c
+-1.025 -3.14 -0.35 -3.809 0.711 -3.398 c
+2.484 -2.712 2.629 -2.655 2.946 -1.777 c
+2.952 -1.763 3.406 -0.234 2.053 0.316 c
+0.838 0.812 0.004 0.01 0 0 c
+0 3.653 l
+3.312 3.653 6.003 0.972 6.003 -2.341 c
+6.003 -5.652 3.312 -8.344 0 -8.344 c
+-3.312 -8.344 -6.003 -5.652 -6.003 -2.341 c
+-6.003 0.972 -3.312 3.653 0 3.653 c
+0 0 l
+f
+Q
+0.267 0.447 0.122  scn
+q 1 0 0 1 327.999 213.7549 cm
+0 0 m
+-0.193 -0.417 -0.585 -0.691 -0.795 -1.098 c
+-1.093 -1.707 l
+-1.262 -2.105 -1.291 -2.433 -1.189 -2.801 c
+-1.126 -3.029 -0.725 -4.141 0.983 -3.563 c
+5.011 -2.2 2.486 0.226 2.453 0.247 c
+1.442 0.896 0.101 0.219 0 0 c
+0 3.517 l
+3.312 3.517 6.003 0.835 6.003 -2.478 c
+6.003 -5.789 3.312 -8.48 0 -8.48 c
+-3.312 -8.48 -6.003 -5.789 -6.003 -2.478 c
+-6.003 0.835 -3.312 3.517 0 3.517 c
+0 0 l
+f
+Q
+0.259 0.439 0.118  scn
+q 1 0 0 1 327.999 213.9082 cm
+0 0 m
+-0.013 -0.025 -0.053 -0.04 -0.076 -0.058 c
+-0.364 -0.275 -0.691 -0.521 -1.173 -1.803 c
+-1.243 -1.988 -1.457 -2.555 -1.186 -3.148 c
+-0.781 -4.033 0.18 -4.204 1.671 -3.654 c
+3.863 -2.846 3.98 -0.373 2.341 0.401 c
+1.366 0.862 0.123 0.247 0 0 c
+0 3.363 l
+3.312 3.363 6.003 0.682 6.003 -2.631 c
+6.003 -5.942 3.312 -8.634 0 -8.634 c
+-3.312 -8.634 -6.003 -5.942 -6.003 -2.631 c
+-6.003 0.682 -3.312 3.363 0 3.363 c
+0 0 l
+f
+Q
+0.255 0.427 0.118  scn
+q 1 0 0 1 327.999 214.0996 cm
+0 0 m
+-0.034 -0.067 -0.142 -0.105 -0.203 -0.15 c
+-0.702 -0.521 -0.962 -1.182 -1.171 -1.711 c
+-1.281 -1.991 -1.54 -2.648 -1.288 -3.269 c
+-0.891 -4.246 0.088 -4.488 1.621 -3.988 c
+4.051 -3.195 4.189 -0.578 2.798 0.287 c
+1.588 1.039 0.134 0.266 0 0 c
+0 3.172 l
+3.312 3.172 6.003 0.49 6.003 -2.822 c
+6.003 -6.134 3.312 -8.825 0 -8.825 c
+-3.312 -8.825 -6.003 -6.134 -6.003 -2.822 c
+-6.003 0.49 -3.312 3.172 0 3.172 c
+0 0 l
+f
+Q
+0.247 0.416 0.114  scn
+q 1 0 0 1 327.999 214.2871 cm
+0 0 m
+-0.037 -0.069 -0.152 -0.104 -0.217 -0.147 c
+-0.454 -0.309 -0.887 -0.883 -1.091 -1.383 c
+-1.28 -1.846 -1.632 -2.707 -1.384 -3.387 c
+-0.994 -4.454 0.002 -4.769 1.578 -4.319 c
+4.069 -3.61 4.619 -0.754 2.993 0.316 c
+1.701 1.166 0.079 0.148 0 0 c
+0 2.984 l
+3.312 2.984 6.003 0.303 6.003 -3.01 c
+6.003 -6.321 3.312 -9.013 0 -9.013 c
+-3.312 -9.013 -6.003 -6.321 -6.003 -3.01 c
+-6.003 0.303 -3.312 2.984 0 2.984 c
+0 0 l
+f
+Q
+0.239 0.404 0.11  scn
+q 1 0 0 1 327.999 214.4717 cm
+0 0 m
+-0.176 -0.317 -0.542 -0.437 -0.748 -0.722 c
+-1.049 -1.139 -1.146 -1.381 -1.241 -1.614 c
+-1.291 -1.738 -1.721 -2.847 -1.448 -3.589 c
+-0.846 -5.228 1.105 -4.775 1.689 -4.598 c
+4.413 -3.769 4.993 -0.751 3.22 0.385 c
+1.946 1.2 0.234 0.423 0 0 c
+0 2.8 l
+3.312 2.8 6.003 0.118 6.003 -3.194 c
+6.003 -6.506 3.312 -9.197 0 -9.197 c
+-3.312 -9.197 -6.003 -6.506 -6.003 -3.194 c
+-6.003 0.118 -3.312 2.8 0 2.8 c
+0 0 l
+f
+Q
+0.235 0.392 0.106  scn
+q 1 0 0 1 327.999 214.7031 cm
+0 0 m
+-0.06 -0.133 -0.265 -0.211 -0.386 -0.291 c
+-0.759 -0.541 -1.229 -1.474 -1.327 -1.735 c
+-1.444 -2.049 -1.803 -3.136 -1.475 -3.938 c
+-0.713 -5.804 1.956 -4.863 1.982 -4.853 c
+5.283 -3.568 5.162 -0.364 3.116 0.573 c
+1.411 1.354 0.007 0.017 0 0 c
+0 2.568 l
+3.312 2.568 6.003 -0.113 6.003 -3.426 c
+6.003 -6.737 3.312 -9.429 0 -9.429 c
+-3.312 -9.429 -6.003 -6.737 -6.003 -3.426 c
+-6.003 -0.113 -3.312 2.568 0 2.568 c
+0 0 l
+f
+Q
+0.227 0.38 0.106  scn
+q 1 0 0 1 327.999 214.9854 cm
+0 0 m
+-0.04 -0.083 -0.167 -0.135 -0.239 -0.193 c
+-0.736 -0.594 -1.131 -1.171 -1.412 -1.908 c
+-1.719 -2.715 -1.736 -3.694 -1.577 -4.139 c
+-0.858 -6.132 1.881 -5.304 1.908 -5.295 c
+5.598 -4.044 5.76 -0.555 3.075 0.691 c
+1.838 1.266 0.163 0.34 0 0 c
+0 2.286 l
+3.312 2.286 6.003 -0.396 6.003 -3.708 c
+6.003 -7.02 3.312 -9.711 0 -9.711 c
+-3.312 -9.711 -6.003 -7.02 -6.003 -3.708 c
+-6.003 -0.396 -3.312 2.286 0 2.286 c
+0 0 l
+f
+Q
+0.22 0.369 0.102  scn
+q 1 0 0 1 327.999 215.2715 cm
+0 0 m
+-0.045 -0.106 -0.21 -0.167 -0.302 -0.236 c
+-0.487 -0.373 -1.13 -0.938 -1.627 -2.442 c
+-1.764 -2.854 -1.88 -3.932 -1.545 -4.67 c
+-1.027 -5.814 0.793 -6.21 2.513 -5.55 c
+6.314 -4.092 5.733 -0.28 3.153 0.723 c
+1.353 1.422 0.007 0.017 0 0 c
+0 2 l
+3.312 2 6.003 -0.682 6.003 -3.994 c
+6.003 -7.306 3.312 -9.997 0 -9.997 c
+-3.312 -9.997 -6.003 -7.306 -6.003 -3.994 c
+-6.003 -0.682 -3.312 2 0 2 c
+0 0 l
+f
+Q
+0.212 0.361 0.098  scn
+q 1 0 0 1 327.999 215.6543 cm
+0 0 m
+-0.163 -0.361 -0.542 -0.515 -0.779 -0.805 c
+-0.948 -1.011 -1.05 -1.26 -1.205 -1.475 c
+-1.369 -1.701 -1.472 -1.983 -1.723 -2.733 c
+-2.048 -3.703 -1.823 -4.541 -1.66 -4.953 c
+-1.229 -6.046 0.416 -6.786 2.422 -6.135 c
+7.014 -4.645 5.816 -0.744 3.286 0.54 c
+1.422 1.485 0.008 0.019 0 0 c
+0 1.617 l
+3.312 1.617 6.003 -1.064 6.003 -4.377 c
+6.003 -7.688 3.312 -10.38 0 -10.38 c
+-3.312 -10.38 -6.003 -7.688 -6.003 -4.377 c
+-6.003 -1.064 -3.312 1.617 0 1.617 c
+0 0 l
+f
+Q
+0.208 0.349 0.094  scn
+q 1 0 0 1 327.999 216.0791 cm
+0 0 m
+-0.128 -0.296 -0.442 -0.404 -0.638 -0.631 c
+-0.788 -0.804 -0.893 -1.01 -1.031 -1.191 c
+-1.148 -1.346 -1.62 -2.353 -1.623 -2.36 c
+-2.172 -3.895 -2.053 -4.608 -1.843 -5.151 c
+-0.961 -7.428 1.653 -7.023 2.586 -6.676 c
+3.891 -6.189 6.606 -5.178 5.553 -2.521 c
+5.843 -3.224 6.003 -3.994 6.003 -4.802 c
+6.003 -8.113 3.312 -10.805 0 -10.805 c
+-3.312 -10.805 -6.003 -8.113 -6.003 -4.802 c
+-6.003 -1.489 -3.312 1.192 0 1.192 c
+0 0 l
+f
+Q
+0.2 0.337 0.09  scn
+q 1 0 0 1 327.999 216.5439 cm
+0 0 m
+-0.037 -0.078 -0.154 -0.129 -0.22 -0.185 c
+-1.238 -1.037 -1.832 -2.884 -1.837 -2.902 c
+-2.426 -4.76 -2.011 -5.632 -1.875 -5.918 c
+-0.597 -8.6 3.355 -7.144 3.396 -7.129 c
+4.441 -6.72 6.192 -6.035 5.899 -4.15 c
+5.967 -4.512 6.003 -4.885 6.003 -5.267 c
+6.003 -8.578 3.312 -11.27 0 -11.27 c
+-3.312 -11.27 -6.003 -8.578 -6.003 -5.267 c
+-6.003 -1.954 -3.312 0.728 0 0.728 c
+0 0 l
+f
+Q
+0.192 0.325 0.09  scn
+q 1 0 0 1 327.999 216.9863 cm
+0 0 m
+-0.038 -0.066 -0.155 -0.09 -0.221 -0.129 c
+-1.15 -0.674 -1.646 -2.172 -2.007 -3.267 c
+-2.013 -3.283 -2.546 -5.064 -2.073 -6.276 c
+-1.009 -9.004 3.058 -7.952 3.099 -7.941 c
+4.318 -7.615 5.989 -7.169 6.001 -5.576 c
+6.002 -5.62 6.003 -5.664 6.003 -5.709 c
+6.003 -9.021 3.312 -11.712 0 -11.712 c
+-3.312 -11.712 -6.003 -9.021 -6.003 -5.709 c
+-6.003 -2.396 -3.312 0.285 0 0.285 c
+0 0 l
+f
+Q
+0.188 0.314 0.086  scn
+q 1 0 0 1 327.999 217.2598 cm
+0 0 m
+-0.043 -0.053 -0.154 -0.029 -0.221 -0.042 c
+-0.696 -0.133 -1.348 -0.689 -1.732 -1.73 c
+-2.577 -4.014 -2.459 -5.548 -2.314 -6.259 c
+-1.864 -8.468 0.843 -8.703 1.755 -8.611 c
+4.299 -8.355 5.7 -8.214 5.951 -6.775 c
+5.562 -9.713 3.043 -11.985 0 -11.985 c
+-3.312 -11.985 -6.003 -9.294 -6.003 -5.982 c
+-6.003 -2.67 -3.312 0.012 0 0.012 c
+0 0 l
+f
+Q
+0.18 0.302 0.082  scn
+q 1 0 0 1 327.0938 217.1953 cm
+0 0 m
+-1.738 -0.59 -1.75 -4.505 -1.75 -4.545 c
+-1.745 -7.049 -0.739 -7.83 0.017 -8.199 c
+1.798 -9.07 6.085 -9.361 6.66 -7.631 c
+5.921 -10.109 3.622 -11.921 0.905 -11.921 c
+-2.407 -11.921 -5.098 -9.229 -5.098 -5.918 c
+-5.098 -2.856 -2.799 -0.334 0.165 0.031 c
+0.115 0.021 0.049 0.013 0 0 c
+f
+Q
+0.173 0.29 0.078  scn
+q 1 0 0 1 325.7642 216.7715 cm
+0 0 m
+-1.064 -0.938 -0.813 -4.867 -0.541 -5.6 c
+0.429 -8.205 2.405 -8.584 3.209 -8.627 c
+4.272 -8.682 5.299 -9.067 6.379 -8.965 c
+6.692 -8.936 7.266 -8.798 7.587 -8.212 c
+6.594 -10.16 4.569 -11.497 2.235 -11.497 c
+-1.077 -11.497 -3.768 -8.806 -3.768 -5.494 c
+-3.768 -2.81 -2.001 -0.54 0.432 0.225 c
+0.372 0.2 0.292 0.168 0.231 0.144 c
+0.161 0.102 0.061 0.054 0 0 c
+f
+Q
+0.302 0.506 0.137  scn
+q 1 0 0 1 329.5791 211.4561 cm
+0 0 m
+-0.095 0.068 -0.095 0.068 -0.519 0.587 c
+-0.661 0.762 -0.834 0.909 -0.973 1.089 c
+-1.125 1.286 -1.231 1.594 y
+-1.226 1.612 -0.029 2.438 0.592 1.362 c
+1.027 0.609 0.245 -0.131 0.233 -0.133 c
+0.153 -0.144 0.065 -0.047 0 0 c
+f
+Q
+0.208 0.349 0.094  scn
+q 1 0 0 1 330.5688 216.6631 cm
+0 0 m
+-1.295 0.462 -2.254 -0.325 -2.57 -0.584 c
+-2.57 0.608 l
+-1.402 0.608 -0.311 0.274 0.612 -0.302 c
+0.522 -0.252 0.402 -0.186 0.312 -0.136 c
+0.219 -0.095 0.096 -0.034 0 0 c
+f
+Q
+0.306 0.518 0.141  scn
+q 1 0 0 1 329.6191 211.708 cm
+0 0 m
+-0.335 0.354 l
+-0.472 0.524 -0.626 0.68 -0.757 0.854 c
+-0.976 1.148 -1.021 1.268 -1.019 1.272 c
+-1.014 1.287 -0.028 1.7 0.33 0.952 c
+0.591 0.409 0.174 -0.12 0.167 -0.121 c
+0.106 -0.131 0.048 -0.039 0 0 c
+f
+Q
+0.2 0.337 0.09  scn
+q 1 0 0 1 329.7661 216.9941 cm
+0 0 m
+-0.649 0.12 -1.161 -0.01 -1.767 -0.45 c
+-1.767 0.277 l
+-1.038 0.277 -0.339 0.147 0.307 -0.091 c
+0.224 -0.065 0.112 -0.031 0.029 -0.007 c
+0.02 -0.005 0.009 -0.002 0 0 c
+f
+Q
+0.314 0.525 0.145  scn
+q 1 0 0 1 329.623 211.9746 cm
+0 0 m
+-0.004 0.004 -0.533 0.572 -0.71 0.861 c
+-0.568 0.874 -0.482 0.883 -0.264 0.809 c
+-0.18 0.78 -0.083 0.699 -0.025 0.631 c
+0.033 0.563 0.091 0.45 0.104 0.361 c
+0.135 0.141 0.099 0.019 0.074 -0.063 c
+0.052 -0.044 0.021 -0.021 0 0 c
+f
+Q
+0.192 0.325 0.09  scn
+q 1 0 0 1 328.9043 217.1943 cm
+0 0 m
+-0.314 -0.006 -0.487 -0.009 -0.905 -0.208 c
+-0.905 0.077 l
+-0.519 0.077 -0.142 0.041 0.225 -0.029 c
+0.157 -0.021 0.068 -0.004 0 0 c
+f
+Q
+0.188 0.314 0.086  scn
+q 1 0 0 1 327.999 217.2598 cm
+0 0 m
+0 0.012 l
+0.072 0.012 0.144 0.011 0.215 0.008 c
+0.15 0.006 0.046 -0.045 0 0 c
+f
+Q
+
endstream
endobj
1007 0 obj
<</I true/K false/S/Transparency/Type/Group>>
endobj
998 0 obj
<</I true/K false/S/Transparency/Type/Group>>
endobj
1002 0 obj
<</Subtype/Form/Length 475/Matrix[1.0 0.0 0.0 1.0 0.0 0.0]/Group 999 0 R/Resources<</XObject<</Fm0 1001 0 R>>/ExtGState<</GS0 978 0 R>>>>/BBox[306.003 319.277 362.001 263.279]>>stream
+q
+334.002 303.277 m
+334.002 319.277 l
+349.464 319.277 362.001 306.74 362.001 291.278 c
+362.001 275.808 349.464 263.279 334.002 263.279 c
+318.54 263.279 306.003 275.808 306.003 291.278 c
+306.003 306.74 318.54 319.277 334.002 319.277 c
+334.002 303.277 l
+327.395 303.288 321.992 297.886 322.003 291.278 c
+321.994 284.663 327.392 279.27 334.002 279.279 c
+340.612 279.27 346.01 284.663 346.001 291.278 c
+346.012 297.886 340.609 303.288 334.002 303.277 c
+W n
+q
+/GS0 gs
+/Fm0 Do
+Q
+Q
+
endstream
endobj
999 0 obj
<</I true/K false/S/Transparency/Type/Group>>
endobj
1001 0 obj
<</Subtype/Form/Length 13469/Matrix[1.0 0.0 0.0 1.0 0.0 0.0]/Group 1000 0 R/Resources<</ColorSpace<</CS0 982 0 R>>/ExtGState<</GS0 978 0 R>>>>/BBox[306.003 319.277 362.001 263.279]>>stream
+/CS0 cs 0.306 0.518 0.141  scn
+1 i 
+/GS0 gs
+q 1 0 0 1 334.002 303.2773 cm
+0 0 m
+0 16 l
+15.462 16 27.999 3.463 27.999 -11.999 c
+27.999 -27.47 15.462 -39.998 0 -39.998 c
+-15.462 -39.998 -27.999 -27.47 -27.999 -11.999 c
+-27.999 3.463 -15.462 16 0 16 c
+0 0 l
+-6.607 0.011 -12.01 -5.392 -11.999 -11.999 c
+-12.008 -18.614 -6.61 -24.008 0 -23.998 c
+6.61 -24.008 12.008 -18.614 11.999 -11.999 c
+12.01 -5.392 6.607 0.011 0 0 c
+f
+Q
+q 1 0 0 1 334.002 308.4409 cm
+0 0 m
+0 -0.468 l
+0 -5.164 l
+-6.607 -5.153 -12.01 -10.555 -11.999 -17.163 c
+-12.008 -23.778 -6.61 -29.171 0 -29.162 c
+6.61 -29.171 12.008 -23.778 11.999 -17.163 c
+12.01 -10.555 6.607 -5.153 0 -5.164 c
+0 -0.468 l
+0.316 -0.694 0.738 -0.996 1.055 -1.223 c
+3.817 -3.661 7.459 -4.869 10 -7.617 c
+12.018 -9.8 13.458 -12.461 14.279 -15.528 c
+15.076 -18.506 16.901 -19.345 16.917 -19.347 c
+18.874 -19.542 24.734 -10.485 17.857 -2.241 c
+10.879 6.124 0.769 1.958 0 0 c
+0 10.836 l
+15.462 10.836 27.999 -1.701 27.999 -17.163 c
+27.999 -32.633 15.462 -45.162 0 -45.162 c
+-15.462 -45.162 -27.999 -32.633 -27.999 -17.163 c
+-27.999 -1.701 -15.462 10.836 0 10.836 c
+0 0 l
+f
+Q
+0.302 0.506 0.137  scn
+q 1 0 0 1 334.002 310.2881 cm
+0 0 m
+-0.296 -0.712 -1.487 -1.168 -1.735 -1.898 c
+-1.987 -2.638 -2.003 -3.873 -1.53 -4.494 c
+-1.227 -4.893 -0.45 -4.945 0 -5.167 c
+0 -7.011 l
+-6.607 -7 -12.01 -12.402 -11.999 -19.01 c
+-12.008 -25.625 -6.61 -31.019 0 -31.009 c
+6.61 -31.019 12.008 -25.625 11.999 -19.01 c
+12.01 -12.402 6.607 -7 0 -7.011 c
+0 -5.167 l
+0.338 -5.201 0.788 -5.245 1.126 -5.278 c
+2.249 -5.476 12.144 -7.557 13.761 -19.537 c
+14.171 -22.514 l
+14.636 -23.089 15.724 -23.505 16.459 -23.428 c
+20.584 -22.992 26.416 -9.568 15.896 -1.312 c
+7.943 4.929 0.035 0.084 0 0 c
+0 8.989 l
+15.462 8.989 27.999 -3.548 27.999 -19.01 c
+27.999 -34.48 15.462 -47.009 0 -47.009 c
+-15.462 -47.009 -27.999 -34.48 -27.999 -19.01 c
+-27.999 -3.548 -15.462 8.989 0 8.989 c
+0 0 l
+f
+Q
+0.294 0.494 0.133  scn
+q 1 0 0 1 334.002 311.4072 cm
+0 0 m
+-0.627 -1.109 -1.866 -1.525 -2.708 -2.391 c
+-4.764 -4.503 -4.447 -6.209 -4.44 -6.223 c
+-4.355 -6.386 -4.355 -6.386 0 -7.408 c
+0 -8.13 l
+-6.607 -8.119 -12.01 -13.521 -11.999 -20.129 c
+-12.008 -26.744 -6.61 -32.138 0 -32.128 c
+6.61 -32.138 12.008 -26.744 11.999 -20.129 c
+12.01 -13.521 6.607 -8.119 0 -8.13 c
+0 -7.408 l
+0.312 -7.428 0.727 -7.455 1.039 -7.475 c
+5.587 -8.118 13.155 -12.018 12.674 -22.55 c
+12.559 -25.063 12.663 -26.479 12.981 -26.762 c
+14.31 -27.933 23.356 -23.69 22.629 -14.042 c
+21.27 4.006 1.142 2.02 0 0 c
+0 7.87 l
+15.462 7.87 27.999 -4.667 27.999 -20.129 c
+27.999 -35.6 15.462 -48.128 0 -48.128 c
+-15.462 -48.128 -27.999 -35.6 -27.999 -20.129 c
+-27.999 -4.667 -15.462 7.87 0 7.87 c
+0 0 l
+f
+Q
+0.286 0.482 0.133  scn
+q 1 0 0 1 334.002 312.3325 cm
+0 0 m
+-0.223 -0.377 -0.896 -0.494 -1.279 -0.706 c
+-3.984 -2.198 -4.352 -2.882 -7.218 -8.204 c
+-10.978 -15.407 l
+-12.034 -17.649 -12.409 -19.973 -12.123 -22.511 c
+-11.368 -29.203 -4.44 -35.038 3.702 -32.832 c
+16.504 -28.455 l
+19.639 -26.388 21.523 -23.893 22.614 -20.364 c
+24.61 -13.908 21.812 -4.74 13.674 -0.575 c
+6.26 3.219 0.029 0.049 0 0 c
+0 6.945 l
+15.462 6.945 27.999 -5.592 27.999 -21.054 c
+27.999 -36.525 15.462 -49.053 0 -49.053 c
+-15.462 -49.053 -27.999 -36.525 -27.999 -21.054 c
+-27.999 -5.592 -15.462 6.945 0 6.945 c
+0 0 l
+f
+Q
+0.278 0.471 0.129  scn
+q 1 0 0 1 334.002 313.1323 cm
+0 0 m
+-0.174 -0.267 -0.682 -0.3 -0.974 -0.428 c
+-3.27 -1.438 -6.363 -4.313 -7.593 -6.58 c
+-13.39 -17.263 -13 -20.654 -12.686 -23.379 c
+-12.044 -28.943 -6.306 -36.331 3.976 -34.516 c
+34.376 -29.152 23.202 -7.033 15.417 -1.844 c
+7.621 3.352 0.038 0.059 0 0 c
+0 6.145 l
+15.462 6.145 27.999 -6.392 27.999 -21.854 c
+27.999 -37.325 15.462 -49.853 0 -49.853 c
+-15.462 -49.853 -27.999 -37.325 -27.999 -21.854 c
+-27.999 -6.392 -15.462 6.145 0 6.145 c
+0 0 l
+f
+Q
+0.275 0.459 0.125  scn
+q 1 0 0 1 334.002 313.833 cm
+0 0 m
+-0.26 -0.393 -1.01 -0.429 -1.443 -0.612 c
+-4.281 -1.817 -7.531 -4.969 -9.346 -8.278 c
+-13.499 -15.849 -13.757 -21.087 -13.243 -24.146 c
+-12.334 -29.559 -7.254 -38.113 6.021 -35.853 c
+29.652 -31.827 27.567 -10.229 15.691 -2.188 c
+7.725 3.206 0.039 0.058 0 0 c
+0 5.444 l
+15.462 5.444 27.999 -7.093 27.999 -22.555 c
+27.999 -38.025 15.462 -50.554 0 -50.554 c
+-15.462 -50.554 -27.999 -38.025 -27.999 -22.555 c
+-27.999 -7.093 -15.462 5.444 0 5.444 c
+0 0 l
+f
+Q
+0.267 0.447 0.122  scn
+q 1 0 0 1 334.002 314.499 cm
+0 0 m
+-0.27 -0.397 -1.042 -0.411 -1.488 -0.586 c
+-3.111 -1.225 -7.25 -3.37 -10.633 -9.471 c
+-11.685 -11.368 -15.021 -18.085 -13.796 -24.878 c
+-12.453 -32.322 -5.461 -39.359 6.715 -37.218 c
+28.949 -33.308 28.975 -11.258 15.609 -2.301 c
+7.856 2.895 0.038 0.056 0 0 c
+0 4.778 l
+15.462 4.778 27.999 -7.759 27.999 -23.221 c
+27.999 -38.691 15.462 -51.22 0 -51.22 c
+-15.462 -51.22 -27.999 -38.691 -27.999 -23.221 c
+-27.999 -7.759 -15.462 4.778 0 4.778 c
+0 0 l
+f
+Q
+0.259 0.439 0.118  scn
+q 1 0 0 1 334.002 315.1099 cm
+0 0 m
+-0.285 -0.403 -1.085 -0.384 -1.55 -0.549 c
+-2.14 -0.758 -7.426 -2.783 -11.14 -9.4 c
+-12.536 -11.888 -15.643 -18.441 -14.343 -25.554 c
+-13.275 -31.396 -7.567 -40.71 7.05 -38.567 c
+28.067 -35.485 30.905 -13.13 16.17 -2.838 c
+7.979 2.883 0.04 0.057 0 0 c
+0 4.167 l
+15.462 4.167 27.999 -8.37 27.999 -23.832 c
+27.999 -39.302 15.462 -51.831 0 -51.831 c
+-15.462 -51.831 -27.999 -39.302 -27.999 -23.832 c
+-27.999 -8.37 -15.462 4.167 0 4.167 c
+0 0 l
+f
+Q
+0.255 0.427 0.118  scn
+q 1 0 0 1 334.002 315.6826 cm
+0 0 m
+-0.294 -0.407 -1.113 -0.365 -1.59 -0.521 c
+-3.037 -0.996 -8.057 -3.068 -11.887 -9.807 c
+-12.95 -11.677 -16.306 -18.383 -14.886 -26.191 c
+-13.691 -32.763 -6.811 -41.823 7.247 -39.848 c
+28.69 -36.835 31.472 -13.848 16.374 -3.144 c
+8.08 2.736 0.041 0.056 0 0 c
+0 3.595 l
+15.462 3.595 27.999 -8.942 27.999 -24.404 c
+27.999 -39.875 15.462 -52.403 0 -52.403 c
+-15.462 -52.403 -27.999 -39.875 -27.999 -24.404 c
+-27.999 -8.942 -15.462 3.595 0 3.595 c
+0 0 l
+f
+Q
+0.247 0.416 0.114  scn
+q 1 0 0 1 334.002 316.2197 cm
+0 0 m
+-0.327 -0.44 -1.224 -0.37 -1.749 -0.528 c
+-5.52 -1.667 -9.766 -5.26 -12.073 -9.267 c
+-15.394 -15.036 -16.522 -20.933 -15.426 -26.792 c
+-13.857 -35.175 -5.228 -43.007 7.675 -41.012 c
+29.388 -37.654 31.678 -13.959 16.092 -3.122 c
+8.188 2.374 0.041 0.052 0 0 c
+0 3.058 l
+15.462 3.058 27.999 -9.479 27.999 -24.941 c
+27.999 -40.412 15.462 -52.94 0 -52.94 c
+-15.462 -52.94 -27.999 -40.412 -27.999 -24.941 c
+-27.999 -9.479 -15.462 3.058 0 3.058 c
+0 0 l
+f
+Q
+0.239 0.404 0.11  scn
+q 1 0 0 1 334.002 316.7344 cm
+0 0 m
+-0.315 -0.413 -1.169 -0.321 -1.671 -0.458 c
+-5.628 -1.543 -10.186 -5.222 -12.509 -9.206 c
+-13.794 -11.411 -17.706 -18.119 -15.958 -27.369 c
+-14.312 -36.083 -5.369 -44.225 7.962 -42.147 c
+29.829 -38.742 32.261 -15.07 16.713 -3.752 c
+8.241 2.415 0.041 0.054 0 0 c
+0 2.543 l
+15.462 2.543 27.999 -9.994 27.999 -25.456 c
+27.999 -40.927 15.462 -53.455 0 -53.455 c
+-15.462 -53.455 -27.999 -40.927 -27.999 -25.456 c
+-27.999 -9.994 -15.462 2.543 0 2.543 c
+0 0 l
+f
+Q
+0.235 0.392 0.106  scn
+q 1 0 0 1 334.002 317.207 cm
+0 0 m
+-0.326 -0.417 -1.197 -0.297 -1.71 -0.424 c
+-5.005 -1.241 -10.022 -4.174 -13.317 -9.752 c
+-16.642 -15.38 -17.708 -21.487 -16.484 -27.904 c
+-14.771 -36.888 -5.523 -45.309 8.242 -43.221 c
+29.817 -39.947 32.246 -15.423 16.845 -4.05 c
+8.507 2.107 0.042 0.053 0 0 c
+0 2.07 l
+15.462 2.07 27.999 -10.467 27.999 -25.929 c
+27.999 -41.399 15.462 -53.928 0 -53.928 c
+-15.462 -53.928 -27.999 -41.399 -27.999 -25.929 c
+-27.999 -10.467 -15.462 2.07 0 2.07 c
+0 0 l
+f
+Q
+0.227 0.38 0.106  scn
+q 1 0 0 1 334.002 317.647 cm
+0 0 m
+-0.165 -0.201 -0.596 -0.119 -0.852 -0.169 c
+-6.63 -1.321 -11.086 -5.48 -13.33 -8.99 c
+-17.824 -16.019 -17.96 -22.681 -17.283 -27.032 c
+-15.528 -38.307 -5.35 -45.631 6.918 -44.447 c
+29.057 -42.308 33.214 -18.565 18.588 -5.674 c
+9.722 2.142 0.051 0.062 0 0 c
+0 1.63 l
+15.462 1.63 27.999 -10.907 27.999 -26.369 c
+27.999 -41.839 15.462 -54.368 0 -54.368 c
+-15.462 -54.368 -27.999 -41.839 -27.999 -26.369 c
+-27.999 -10.907 -15.462 1.63 0 1.63 c
+0 0 l
+f
+Q
+0.22 0.369 0.102  scn
+q 1 0 0 1 334.002 318.0581 cm
+0 0 m
+-0.345 -0.419 -1.243 -0.245 -1.775 -0.35 c
+-5.333 -1.052 -10.598 -4.013 -13.752 -8.857 c
+-18.474 -16.108 -18.606 -22.979 -17.885 -27.466 c
+-16.272 -37.501 -7.101 -46.918 7.31 -45.498 c
+29.578 -43.303 33.522 -19.118 18.666 -5.999 c
+9.679 1.938 0.05 0.061 0 0 c
+0 1.219 l
+15.462 1.219 27.999 -11.318 27.999 -26.78 c
+27.999 -42.25 15.462 -54.779 0 -54.779 c
+-15.462 -54.779 -27.999 -42.25 -27.999 -26.78 c
+-27.999 -11.318 -15.462 1.219 0 1.219 c
+0 0 l
+f
+Q
+0.212 0.361 0.098  scn
+q 1 0 0 1 334.002 318.4131 cm
+0 0 m
+-0.359 -0.424 -1.279 -0.213 -1.827 -0.305 c
+-2.571 -0.429 -9.239 -1.713 -14.035 -8.521 c
+-19.337 -16.049 -19.04 -23.602 -18.666 -26.5 c
+-16.791 -41.034 -4.557 -47.118 6.016 -46.62 c
+29.239 -45.526 34.04 -19.967 18.705 -6.311 c
+9.693 1.714 0.05 0.059 0 0 c
+0 0.864 l
+15.462 0.864 27.999 -11.673 27.999 -27.135 c
+27.999 -42.605 15.462 -55.134 0 -55.134 c
+-15.462 -55.134 -27.999 -42.605 -27.999 -27.135 c
+-27.999 -11.673 -15.462 0.864 0 0.864 c
+0 0 l
+f
+Q
+0.208 0.349 0.094  scn
+q 1 0 0 1 334.002 318.7388 cm
+0 0 m
+-0.366 -0.422 -1.29 -0.183 -1.842 -0.262 c
+-5.616 -0.798 -11.203 -3.577 -14.553 -8.414 c
+-20.526 -17.037 -19.484 -25.014 -19.142 -27.636 c
+-17.325 -41.544 -4.721 -48.295 6.216 -47.587 c
+22.826 -46.511 31.838 -32.411 25.896 -16.796 c
+27.251 -20.083 27.999 -23.685 27.999 -27.46 c
+27.999 -42.931 15.462 -55.459 0 -55.459 c
+-15.462 -55.459 -27.999 -42.931 -27.999 -27.46 c
+-27.999 -11.999 -15.462 0.539 0 0.539 c
+0 0 l
+f
+Q
+0.2 0.337 0.09  scn
+q 1 0 0 1 334.002 318.9941 cm
+0 0 m
+-0.38 -0.425 -1.322 -0.147 -1.889 -0.211 c
+-3.74 -0.417 -10.183 -1.633 -15.334 -8.604 c
+-20.121 -15.081 -20.497 -23.226 -19.964 -27.017 c
+-18.07 -40.5 -7.309 -49.138 6.814 -48.512 c
+13.57 -48.212 30.458 -42.954 27.513 -22.495 c
+27.832 -24.187 27.999 -25.932 27.999 -27.716 c
+27.999 -43.187 15.462 -55.715 0 -55.715 c
+-15.462 -55.715 -27.999 -43.187 -27.999 -27.716 c
+-27.999 -12.254 -15.462 0.283 0 0.283 c
+0 0 l
+f
+Q
+0.192 0.325 0.09  scn
+q 1 0 0 1 334.002 319.1851 cm
+0 0 m
+-0.389 -0.421 -1.333 -0.109 -1.905 -0.156 c
+-5.862 -0.48 -11.762 -2.986 -15.367 -7.721 c
+-21.456 -15.721 -21.121 -23.999 -20.694 -27.186 c
+-18.848 -40.988 -7.36 -50.366 6.622 -49.484 c
+16.365 -48.869 27.809 -42.686 27.992 -27.284 c
+27.997 -27.491 27.999 -27.699 27.999 -27.907 c
+27.999 -43.377 15.462 -55.906 0 -55.906 c
+-15.462 -55.906 -27.999 -43.377 -27.999 -27.907 c
+-27.999 -12.445 -15.462 0.092 0 0.092 c
+0 0 l
+f
+Q
+0.188 0.314 0.086  scn
+q 1 0 0 1 334.002 319.2739 cm
+0 0 m
+-0.403 -0.423 -1.362 -0.067 -1.945 -0.096 c
+-5.653 -0.278 -11.171 -1.795 -16.407 -7.987 c
+-19.42 -11.549 -22.258 -18.906 -21.583 -25.522 c
+-19.025 -50.59 4.157 -50.418 5.143 -50.399 c
+17.395 -50.155 25.849 -43.167 27.755 -31.707 c
+25.94 -45.421 14.205 -55.995 0 -55.995 c
+-15.462 -55.995 -27.999 -43.466 -27.999 -27.996 c
+-27.999 -12.534 -15.462 0.003 0 0.003 c
+0 0 l
+f
+Q
+0.18 0.302 0.082  scn
+q 1 0 0 1 329.771 318.957 cm
+0 0 m
+-22.534 -4.552 -23.533 -35.028 -6.33 -46.26 c
+6.848 -54.863 25.642 -52.17 31.069 -35.688 c
+27.625 -47.252 16.911 -55.678 4.231 -55.678 c
+-11.231 -55.678 -23.768 -43.149 -23.768 -27.679 c
+-23.768 -13.386 -13.055 -1.592 0.778 0.109 c
+0.544 0.077 0.232 0.04 0 0 c
+f
+Q
+0.173 0.29 0.078  scn
+q 1 0 0 1 321.978 316.4971 cm
+0 0 m
+-16.565 -9.063 -17.347 -40.195 9.314 -48.713 c
+16.64 -51.053 30.632 -50.191 36.987 -37.914 c
+32.359 -46.999 22.917 -53.218 12.024 -53.218 c
+-3.438 -53.218 -15.975 -40.689 -15.975 -25.219 c
+-15.975 -12.683 -7.734 -2.069 3.625 1.499 c
+3.1 1.309 2.399 1.057 1.873 0.867 c
+1.31 0.61 0.543 0.297 0 0 c
+f
+Q
+0.314 0.525 0.145  scn
+q 1 0 0 1 349.9282 293.1025 cm
+0 0 m
+-1.706 2.422 -2.871 5.191 -4.806 7.466 c
+-5.58 8.375 -6.333 9.14 -7.046 9.739 c
+-7.103 9.787 -12.7 14.578 -12.706 14.928 c
+-12.708 15.034 -10.925 16.753 -10.74 16.824 c
+-10.058 17.085 -7.544 17.231 -6.875 17.165 c
+-5.111 16.991 -2.438 16.24 0.275 13.649 c
+3.79 10.292 4.269 6.381 4.332 5.263 c
+4.608 0.361 1.816 -1.553 1.125 -1.426 c
+0.589 -1.328 0.314 -0.446 0 0 c
+f
+Q
+0.322 0.537 0.145  scn
+q 1 0 0 1 350.0625 295.5957 cm
+0 0 m
+-1.97 2.883 -3.056 4.472 -4.87 6.595 c
+-5.072 6.832 -5.375 7.116 -5.591 7.34 c
+-5.844 7.601 -6.16 7.969 -6.419 8.224 c
+-6.913 8.711 -7.551 9.382 -8.074 9.839 c
+-9.724 11.281 -9.908 11.547 -9.911 11.595 c
+-9.914 11.655 -8.389 13.369 -8.295 13.411 c
+-7.711 13.674 -6.801 13.346 -6.164 13.276 c
+-2.962 12.927 -1.156 11.212 -0.476 10.566 c
+2.531 7.709 2.783 5.143 2.904 3.909 c
+2.938 3.565 2.929 0.875 2.709 0.41 c
+2.675 0.337 0.707 -0.874 0.645 -0.861 c
+0.33 -0.793 0.182 -0.267 0 0 c
+f
+Q
+0.325 0.549 0.149  scn
+q 1 0 0 1 349.1475 299.125 cm
+0 0 m
+-0.737 0.235 -1.076 1.45 -1.576 2.04 c
+-3.148 3.894 -3.148 3.894 -3.897 4.678 c
+-4.212 5.008 -4.84 5.354 -4.922 5.803 c
+-4.014 7.981 l
+-3.953 8.007 -1.427 7.15 0.33 5.083 c
+1.631 3.552 2.397 0.755 2.281 0.574 c
+1.906 -0.01 0.699 -0.197 0.037 0.011 c
+0.026 0.014 0.011 -0.003 0 0 c
+f
+Q
+0.208 0.349 0.094  scn
+q 1 0 0 1 346.0513 316.5498 cm
+0 0 m
+-5.275 2.417 -9.403 2.407 -12.049 2.189 c
+-12.049 2.728 l
+-6.604 2.728 -1.522 1.173 2.777 -1.517 c
+2.232 -1.205 1.506 -0.789 0.961 -0.477 c
+0.673 -0.334 0.292 -0.134 0 0 c
+f
+Q
+0.2 0.337 0.09  scn
+q 1 0 0 1 342.2651 318.0342 cm
+0 0 m
+-3.078 0.794 -4.478 1.111 -8.263 0.96 c
+-8.263 1.243 l
+-4.866 1.243 -1.61 0.638 1.402 -0.47 c
+0.981 -0.329 0.425 -0.126 0 0 c
+f
+Q
+0.192 0.325 0.09  scn
+q 1 0 0 1 338.2329 318.957 cm
+0 0 m
+-2.557 0.263 -2.657 0.273 -4.231 0.228 c
+-4.231 0.32 l
+-2.431 0.32 -0.671 0.15 1.035 -0.174 c
+0.724 -0.122 0.312 -0.042 0 0 c
+f
+Q
+0.188 0.314 0.086  scn
+q 1 0 0 1 334.002 319.2739 cm
+0 0 m
+0.335 0.003 0.669 -0.002 1.001 -0.014 c
+0.701 -0.01 0.211 -0.214 0 0 c
+f
+Q
+
endstream
endobj
1000 0 obj
<</I true/K false/S/Transparency/Type/Group>>
endobj
988 0 obj
<</I true/K false/S/Transparency/Type/Group>>
endobj
992 0 obj
<</Subtype/Form/Length 481/Matrix[1.0 0.0 0.0 1.0 0.0 0.0]/Group 989 0 R/Resources<</XObject<</Fm0 991 0 R>>/ExtGState<</GS0 978 0 R>>>>/BBox[180.624 223.274 192.621 211.277]>>stream
+q
+186.627 218.274 m
+186.627 223.274 l
+189.939 223.274 192.621 220.593 192.621 217.271 c
+192.621 213.959 189.939 211.277 186.627 211.277 c
+183.315 211.277 180.624 213.959 180.624 217.271 c
+180.624 220.593 183.315 223.274 186.627 223.274 c
+186.627 218.274 l
+186.078 218.277 185.622 217.823 185.624 217.271 c
+185.62 216.731 186.077 216.274 186.627 216.277 c
+187.173 216.275 187.624 216.726 187.621 217.271 c
+187.622 217.829 187.171 218.277 186.627 218.274 c
+W n
+q
+/GS0 gs
+/Fm0 Do
+Q
+Q
+
endstream
endobj
989 0 obj
<</I true/K false/S/Transparency/Type/Group>>
endobj
991 0 obj
<</Subtype/Form/Length 11020/Matrix[1.0 0.0 0.0 1.0 0.0 0.0]/Group 990 0 R/Resources<</ColorSpace<</CS0 982 0 R>>/ExtGState<</GS0 978 0 R>>>>/BBox[180.624 223.274 192.621 211.277]>>stream
+/CS0 cs 0.294 0.494 0.133  scn
+1 i 
+/GS0 gs
+q 1 0 0 1 186.627 218.2744 cm
+0 0 m
+0 5 l
+3.312 5 5.994 2.318 5.994 -1.003 c
+5.994 -4.315 3.312 -6.997 0 -6.997 c
+-3.312 -6.997 -6.003 -4.315 -6.003 -1.003 c
+-6.003 2.318 -3.312 5 0 5 c
+0 0 l
+-0.549 0.003 -1.005 -0.451 -1.003 -1.003 c
+-1.007 -1.543 -0.55 -2 0 -1.997 c
+0.546 -1.999 0.997 -1.549 0.994 -1.003 c
+0.995 -0.445 0.544 0.003 0 0 c
+f
+Q
+q 1 0 0 1 186.627 219.1992 cm
+0 0 m
+-0.013 -0.041 -0.073 -0.074 -0.083 -0.115 c
+-0.111 -0.248 -0.02 -0.426 0 -0.561 c
+0 -0.925 l
+-0.549 -0.922 -1.005 -1.376 -1.003 -1.928 c
+-1.007 -2.468 -0.55 -2.925 0 -2.922 c
+0.546 -2.924 0.997 -2.474 0.994 -1.928 c
+0.995 -1.37 0.544 -0.922 0 -0.925 c
+0 -0.561 l
+0.034 -0.558 0.078 -0.553 0.112 -0.55 c
+0.141 -0.55 0.182 -0.536 0.208 -0.549 c
+1.037 -1.473 l
+1.432 -2.162 1.781 -2.116 1.796 -2.113 c
+2.048 -2.073 3.175 -0.62 1.896 0.192 c
+1.594 0.385 1.27 0.411 1.126 0.396 c
+0 0 l
+0 4.075 l
+3.312 4.075 5.994 1.394 5.994 -1.928 c
+5.994 -5.24 3.312 -7.922 0 -7.922 c
+-3.312 -7.922 -6.003 -5.24 -6.003 -1.928 c
+-6.003 1.394 -3.312 4.075 0 4.075 c
+0 0 l
+f
+Q
+0.286 0.482 0.133  scn
+q 1 0 0 1 186.627 219.3418 cm
+0 0 m
+-0.03 -0.093 -0.164 -0.171 -0.185 -0.266 c
+-0.222 -0.434 -0.125 -0.678 -0.187 -0.838 c
+-0.188 -0.839 -0.237 -0.941 -0.403 -1.05 c
+-1.157 -1.54 -1.045 -2.159 -0.993 -2.338 c
+-0.812 -2.951 -0.139 -3.261 0.448 -2.999 c
+0.646 -2.911 0.784 -2.775 0.866 -2.694 c
+1.137 -2.427 1.542 -2.629 1.829 -2.42 c
+2.42 -1.988 2.555 -1.604 2.619 -1.418 c
+2.84 -0.784 2.454 0.136 1.624 0.372 c
+0.851 0.592 0.002 0.007 0 0 c
+0 3.933 l
+3.312 3.933 5.994 1.251 5.994 -2.07 c
+5.994 -5.383 3.312 -8.064 0 -8.064 c
+-3.312 -8.064 -6.003 -5.383 -6.003 -2.07 c
+-6.003 1.251 -3.312 3.933 0 3.933 c
+0 0 l
+f
+Q
+0.278 0.471 0.129  scn
+q 1 0 0 1 186.627 219.4824 cm
+0 0 m
+-0.295 -0.834 -1.295 -1.352 -1.079 -2.413 c
+-0.941 -3.092 -0.175 -3.558 0.645 -3.166 c
+2.581 -2.241 2.581 -2.241 2.752 -1.679 c
+3.15 -0.374 2.119 0.265 1.727 0.386 c
+0.83 0.662 0.003 0.008 0 0 c
+0 3.792 l
+3.312 3.792 5.994 1.11 5.994 -2.211 c
+5.994 -5.523 3.312 -8.205 0 -8.205 c
+-3.312 -8.205 -6.003 -5.523 -6.003 -2.211 c
+-6.003 1.11 -3.312 3.792 0 3.792 c
+0 0 l
+f
+Q
+0.275 0.459 0.125  scn
+q 1 0 0 1 186.627 219.6211 cm
+0 0 m
+-0.353 -0.868 -1.382 -1.434 -1.146 -2.564 c
+-1.026 -3.142 -0.354 -3.806 0.709 -3.4 c
+2.435 -2.741 2.615 -2.673 2.848 -2.025 c
+3.232 -0.958 2.919 -0.038 2.048 0.318 c
+0.863 0.804 0.004 0.01 0 0 c
+0 3.653 l
+3.312 3.653 5.994 0.972 5.994 -2.35 c
+5.994 -5.662 3.312 -8.344 0 -8.344 c
+-3.312 -8.344 -6.003 -5.662 -6.003 -2.35 c
+-6.003 0.972 -3.312 3.653 0 3.653 c
+0 0 l
+f
+Q
+0.267 0.447 0.122  scn
+q 1 0 0 1 186.627 219.7588 cm
+0 0 m
+-0.193 -0.418 -0.584 -0.692 -0.794 -1.099 c
+-1.091 -1.709 l
+-1.261 -2.111 -1.291 -2.44 -1.189 -2.809 c
+-1.127 -3.035 -0.731 -4.134 0.979 -3.567 c
+4.729 -2.327 2.779 0.033 2.448 0.247 c
+1.441 0.897 0.102 0.218 0 0 c
+0 3.516 l
+3.312 3.516 5.994 0.834 5.994 -2.487 c
+5.994 -5.8 3.312 -8.481 0 -8.481 c
+-3.312 -8.481 -6.003 -5.8 -6.003 -2.487 c
+-6.003 0.834 -3.312 3.516 0 3.516 c
+0 0 l
+f
+Q
+0.259 0.439 0.118  scn
+q 1 0 0 1 186.627 219.9111 cm
+0 0 m
+-0.013 -0.025 -0.053 -0.04 -0.076 -0.058 c
+-0.436 -0.329 -0.724 -0.613 -1.172 -1.804 c
+-1.294 -2.128 -1.428 -2.622 -1.186 -3.154 c
+-0.786 -4.034 0.174 -4.205 1.666 -3.662 c
+3.819 -2.879 3.945 -0.361 2.337 0.402 c
+1.364 0.864 0.123 0.248 0 0 c
+0 3.363 l
+3.312 3.363 5.994 0.682 5.994 -2.64 c
+5.994 -5.952 3.312 -8.634 0 -8.634 c
+-3.312 -8.634 -6.003 -5.952 -6.003 -2.64 c
+-6.003 0.682 -3.312 3.363 0 3.363 c
+0 0 l
+f
+Q
+0.255 0.427 0.118  scn
+q 1 0 0 1 186.627 220.1025 cm
+0 0 m
+-0.034 -0.067 -0.142 -0.105 -0.203 -0.15 c
+-0.738 -0.548 -1 -1.255 -1.252 -1.938 c
+-1.385 -2.296 -1.491 -2.836 -1.247 -3.372 c
+-0.62 -4.745 1.243 -4.15 1.798 -3.936 c
+4.073 -3.057 4.215 -0.289 2.506 0.421 c
+1.109 1.002 0.006 0.013 0 0 c
+0 3.172 l
+3.312 3.172 5.994 0.49 5.994 -2.831 c
+5.994 -6.144 3.312 -8.825 0 -8.825 c
+-3.312 -8.825 -6.003 -6.144 -6.003 -2.831 c
+-6.003 0.49 -3.312 3.172 0 3.172 c
+0 0 l
+f
+Q
+0.247 0.416 0.114  scn
+q 1 0 0 1 186.627 220.291 cm
+0 0 m
+-0.037 -0.07 -0.152 -0.104 -0.217 -0.148 c
+-0.425 -0.29 -0.869 -0.842 -1.09 -1.384 c
+-1.279 -1.849 -1.632 -2.713 -1.384 -3.395 c
+-1 -4.452 -0.005 -4.766 1.573 -4.327 c
+4.077 -3.63 4.625 -0.767 2.988 0.316 c
+1.701 1.168 0.079 0.148 0 0 c
+0 2.983 l
+3.312 2.983 5.994 0.302 5.994 -3.02 c
+5.994 -6.332 3.312 -9.014 0 -9.014 c
+-3.312 -9.014 -6.003 -6.332 -6.003 -3.02 c
+-6.003 0.302 -3.312 2.983 0 2.983 c
+0 0 l
+f
+Q
+0.239 0.404 0.11  scn
+q 1 0 0 1 186.627 220.4746 cm
+0 0 m
+-0.175 -0.316 -0.542 -0.436 -0.748 -0.721 c
+-1.047 -1.138 -1.145 -1.38 -1.239 -1.615 c
+-1.289 -1.739 -1.721 -2.852 -1.448 -3.597 c
+-0.854 -5.222 1.1 -4.778 1.685 -4.604 c
+4.42 -3.787 4.999 -0.764 3.215 0.386 c
+1.946 1.203 0.235 0.424 0 0 c
+0 2.8 l
+3.312 2.8 5.994 0.118 5.994 -3.203 c
+5.994 -6.516 3.312 -9.197 0 -9.197 c
+-3.312 -9.197 -6.003 -6.516 -6.003 -3.203 c
+-6.003 0.118 -3.312 2.8 0 2.8 c
+0 0 l
+f
+Q
+0.235 0.392 0.106  scn
+q 1 0 0 1 186.627 220.7061 cm
+0 0 m
+-0.06 -0.132 -0.265 -0.211 -0.386 -0.291 c
+-0.737 -0.526 -1.203 -1.41 -1.325 -1.736 c
+-1.409 -1.96 -1.811 -3.121 -1.476 -3.944 c
+-0.72 -5.801 1.951 -4.87 1.978 -4.859 c
+5.294 -3.584 5.17 -0.372 3.113 0.574 c
+1.411 1.356 0.007 0.017 0 0 c
+0 2.568 l
+3.312 2.568 5.994 -0.113 5.994 -3.435 c
+5.994 -6.747 3.312 -9.429 0 -9.429 c
+-3.312 -9.429 -6.003 -6.747 -6.003 -3.435 c
+-6.003 -0.113 -3.312 2.568 0 2.568 c
+0 0 l
+f
+Q
+0.227 0.38 0.106  scn
+q 1 0 0 1 186.627 220.9883 cm
+0 0 m
+-0.04 -0.083 -0.167 -0.135 -0.239 -0.193 c
+-0.735 -0.593 -1.129 -1.17 -1.41 -1.909 c
+-1.685 -2.632 -1.76 -3.635 -1.577 -4.146 c
+-0.866 -6.126 1.876 -5.311 1.903 -5.301 c
+5.874 -3.976 5.345 -0.496 3.416 0.521 c
+1.627 1.465 0.058 0.121 0 0 c
+0 2.286 l
+3.312 2.286 5.994 -0.396 5.994 -3.717 c
+5.994 -7.029 3.312 -9.711 0 -9.711 c
+-3.312 -9.711 -6.003 -7.029 -6.003 -3.717 c
+-6.003 -0.396 -3.312 2.286 0 2.286 c
+0 0 l
+f
+Q
+0.22 0.369 0.102  scn
+q 1 0 0 1 186.627 221.2744 cm
+0 0 m
+-0.045 -0.106 -0.21 -0.167 -0.303 -0.236 c
+-0.487 -0.373 -1.127 -0.938 -1.625 -2.443 c
+-1.73 -2.761 -1.906 -3.878 -1.546 -4.676 c
+-1.031 -5.818 0.788 -6.214 2.508 -5.559 c
+6.319 -4.105 5.737 -0.286 3.15 0.724 c
+1.354 1.425 0.007 0.017 0 0 c
+0 2 l
+3.312 2 5.994 -0.682 5.994 -4.003 c
+5.994 -7.315 3.312 -9.997 0 -9.997 c
+-3.312 -9.997 -6.003 -7.315 -6.003 -4.003 c
+-6.003 -0.682 -3.312 2 0 2 c
+0 0 l
+f
+Q
+0.212 0.361 0.098  scn
+q 1 0 0 1 186.627 221.6582 cm
+0 0 m
+-0.163 -0.362 -0.542 -0.515 -0.779 -0.805 c
+-0.947 -1.012 -1.049 -1.261 -1.205 -1.476 c
+-1.367 -1.7 -1.47 -1.983 -1.721 -2.735 c
+-2.06 -3.745 -1.792 -4.628 -1.661 -4.961 c
+-1.172 -6.201 0.619 -6.721 2.417 -6.144 c
+7.025 -4.662 5.824 -0.754 3.284 0.539 c
+1.422 1.486 0.008 0.018 0 0 c
+0 1.616 l
+3.312 1.616 5.994 -1.065 5.994 -4.387 c
+5.994 -7.699 3.312 -10.381 0 -10.381 c
+-3.312 -10.381 -6.003 -7.699 -6.003 -4.387 c
+-6.003 -1.065 -3.312 1.616 0 1.616 c
+0 0 l
+f
+Q
+0.208 0.349 0.094  scn
+q 1 0 0 1 186.627 222.082 cm
+0 0 m
+-0.128 -0.296 -0.442 -0.404 -0.638 -0.631 c
+-0.788 -0.804 -0.893 -1.01 -1.031 -1.191 c
+-1.147 -1.346 -1.619 -2.354 -1.622 -2.361 c
+-2.173 -3.904 -2.042 -4.642 -1.843 -5.159 c
+-0.967 -7.426 1.647 -7.027 2.581 -6.683 c
+3.886 -6.201 6.602 -5.198 5.542 -2.518 c
+5.833 -3.224 5.994 -3.998 5.994 -4.811 c
+5.994 -8.123 3.312 -10.805 0 -10.805 c
+-3.312 -10.805 -6.003 -8.123 -6.003 -4.811 c
+-6.003 -1.489 -3.312 1.192 0 1.192 c
+0 0 l
+f
+Q
+0.2 0.337 0.09  scn
+q 1 0 0 1 186.627 222.5469 cm
+0 0 m
+-0.037 -0.078 -0.154 -0.129 -0.22 -0.185 c
+-1.236 -1.035 -1.83 -2.885 -1.836 -2.903 c
+-2.227 -4.14 -2.24 -5.156 -1.875 -5.925 c
+-0.602 -8.604 3.351 -7.152 3.39 -7.137 c
+4.435 -6.729 6.183 -6.049 5.89 -4.151 c
+5.958 -4.516 5.994 -4.891 5.994 -5.275 c
+5.994 -8.588 3.312 -11.27 0 -11.27 c
+-3.312 -11.27 -6.003 -8.588 -6.003 -5.275 c
+-6.003 -1.954 -3.312 0.728 0 0.728 c
+0 0 l
+f
+Q
+0.192 0.325 0.09  scn
+q 1 0 0 1 186.627 222.9893 cm
+0 0 m
+-0.038 -0.066 -0.155 -0.09 -0.221 -0.129 c
+-1.149 -0.673 -1.644 -2.171 -2.005 -3.266 c
+-2.01 -3.282 -2.546 -5.07 -2.073 -6.283 c
+-1.016 -9.001 3.053 -7.959 3.094 -7.948 c
+4.312 -7.626 5.98 -7.185 5.993 -5.583 c
+5.994 -5.628 5.994 -5.673 5.994 -5.718 c
+5.994 -9.03 3.312 -11.712 0 -11.712 c
+-3.312 -11.712 -6.003 -9.03 -6.003 -5.718 c
+-6.003 -2.396 -3.312 0.285 0 0.285 c
+0 0 l
+f
+Q
+0.188 0.314 0.086  scn
+q 1 0 0 1 186.627 223.2627 cm
+0 0 m
+-0.043 -0.052 -0.154 -0.029 -0.221 -0.042 c
+-0.696 -0.133 -1.347 -0.689 -1.732 -1.731 c
+-2.576 -4.018 -2.459 -5.555 -2.314 -6.268 c
+-1.868 -8.458 0.839 -8.7 1.752 -8.612 c
+4.209 -8.376 5.692 -8.233 5.942 -6.786 c
+5.553 -9.723 3.042 -11.985 0 -11.985 c
+-3.312 -11.985 -6.003 -9.304 -6.003 -5.991 c
+-6.003 -2.67 -3.312 0.012 0 0.012 c
+0 0 l
+f
+Q
+0.18 0.302 0.082  scn
+q 1 0 0 1 185.7217 223.1973 cm
+0 0 m
+-1.735 -0.588 -1.748 -4.507 -1.748 -4.547 c
+-1.744 -6.481 -1.201 -7.607 0.015 -8.199 c
+1.797 -9.066 6.081 -9.359 6.651 -7.642 c
+5.914 -10.117 3.621 -11.92 0.905 -11.92 c
+-2.407 -11.92 -5.098 -9.238 -5.098 -5.926 c
+-5.098 -2.855 -2.799 -0.333 0.165 0.032 c
+0.115 0.022 0.049 0.014 0 0 c
+f
+Q
+0.173 0.29 0.078  scn
+q 1 0 0 1 184.3926 222.7744 cm
+0 0 m
+-1.065 -0.939 -0.813 -4.875 -0.541 -5.608 c
+0.425 -8.204 2.403 -8.583 3.208 -8.626 c
+4.27 -8.682 5.294 -9.071 6.373 -8.972 c
+6.625 -8.948 7.249 -8.828 7.579 -8.222 c
+6.588 -10.166 4.567 -11.497 2.234 -11.497 c
+-1.078 -11.497 -3.769 -8.815 -3.769 -5.503 c
+-3.769 -2.812 -2.001 -0.54 0.432 0.225 c
+0.372 0.2 0.292 0.168 0.231 0.144 c
+0.161 0.103 0.062 0.054 0 0 c
+f
+Q
+0.302 0.506 0.137  scn
+q 1 0 0 1 188.1982 217.4531 cm
+0 0 m
+-0.089 0.064 -0.089 0.064 -0.518 0.595 c
+-0.66 0.77 -0.832 0.916 -0.969 1.096 c
+-1.153 1.336 -1.228 1.588 -1.225 1.6 c
+-1.219 1.619 -0.023 2.449 0.592 1.369 c
+1.023 0.611 0.244 -0.132 0.233 -0.134 c
+0.153 -0.145 0.065 -0.047 0 0 c
+f
+Q
+0.208 0.349 0.094  scn
+q 1 0 0 1 189.1953 222.666 cm
+0 0 m
+-1.292 0.462 -2.253 -0.325 -2.568 -0.584 c
+-2.568 0.608 l
+-1.402 0.608 -0.314 0.276 0.606 -0.3 c
+0.517 -0.25 0.397 -0.184 0.307 -0.133 c
+0.215 -0.093 0.095 -0.034 0 0 c
+f
+Q
+0.306 0.518 0.141  scn
+q 1 0 0 1 188.2393 217.709 cm
+0 0 m
+-0.336 0.357 l
+-0.471 0.528 -0.626 0.683 -0.755 0.857 c
+-0.971 1.148 -1.017 1.271 -1.015 1.275 c
+-1.01 1.29 -0.025 1.71 0.328 0.955 c
+0.583 0.408 0.172 -0.12 0.166 -0.121 c
+0.105 -0.132 0.047 -0.039 0 0 c
+f
+Q
+0.2 0.337 0.09  scn
+q 1 0 0 1 188.3931 222.9971 cm
+0 0 m
+-0.649 0.121 -1.161 -0.01 -1.766 -0.45 c
+-1.766 0.277 l
+-1.038 0.277 -0.341 0.147 0.305 -0.09 c
+0.221 -0.064 0.11 -0.031 0.027 -0.006 c
+0.019 -0.004 0.008 -0.001 0 0 c
+f
+Q
+0.314 0.525 0.145  scn
+q 1 0 0 1 188.2437 217.9775 cm
+0 0 m
+-0.004 0.005 -0.532 0.572 -0.709 0.863 c
+-0.562 0.878 -0.481 0.886 -0.263 0.812 c
+-0.178 0.783 -0.083 0.7 -0.026 0.632 c
+0.032 0.563 0.087 0.449 0.1 0.36 c
+0.13 0.142 0.09 0.006 0.071 -0.06 c
+0.049 -0.041 0.02 -0.02 0 0 c
+f
+Q
+0.192 0.325 0.09  scn
+q 1 0 0 1 187.5317 223.1973 cm
+0 0 m
+-0.313 -0.006 -0.486 -0.009 -0.905 -0.208 c
+-0.905 0.077 l
+-0.519 0.077 -0.142 0.041 0.224 -0.029 c
+0.157 -0.021 0.068 -0.004 0 0 c
+f
+Q
+0.188 0.314 0.086  scn
+q 1 0 0 1 186.627 223.2627 cm
+0 0 m
+0 0.012 l
+0.072 0.012 0.144 0.011 0.215 0.008 c
+0.15 0.006 0.046 -0.045 0 0 c
+f
+Q
+
endstream
endobj
990 0 obj
<</I true/K false/S/Transparency/Type/Group>>
endobj
979 0 obj
<</I true/K false/S/Transparency/Type/Group>>
endobj
985 0 obj
<</Subtype/Form/Length 450/Matrix[1.0 0.0 0.0 1.0 0.0 0.0]/Group 980 0 R/Resources<</XObject<</Fm0 984 0 R>>/ExtGState<</GS0 978 0 R>>>>/BBox[155.001 324.272 210.999 268.274]>>stream
+q
+183 308.272 m
+183 324.272 l
+198.462 324.272 210.999 311.735 210.999 296.273 c
+210.999 280.812 198.462 268.274 183 268.274 c
+167.538 268.274 155.001 280.812 155.001 296.273 c
+155.001 311.735 167.538 324.272 183 324.272 c
+183 308.272 l
+176.393 308.283 170.99 302.881 171.001 296.273 c
+170.99 289.666 176.393 284.264 183 284.274 c
+189.607 284.264 195.01 289.666 194.999 296.273 c
+195.01 302.881 189.607 308.283 183 308.272 c
+W n
+q
+/GS0 gs
+/Fm0 Do
+Q
+Q
+
endstream
endobj
980 0 obj
<</I true/K false/S/Transparency/Type/Group>>
endobj
984 0 obj
<</Subtype/Form/Length 13394/Matrix[1.0 0.0 0.0 1.0 0.0 0.0]/Group 981 0 R/Resources<</ColorSpace<</CS0 982 0 R>>/ExtGState<</GS0 978 0 R>>>>/BBox[155.001 324.272 210.999 268.274]>>stream
+/CS0 cs 0.306 0.518 0.141  scn
+1 i 
+/GS0 gs
+q 1 0 0 1 183 308.2725 cm
+0 0 m
+0 16 l
+15.462 16 27.999 3.463 27.999 -11.999 c
+27.999 -27.461 15.462 -39.998 0 -39.998 c
+-15.462 -39.998 -27.999 -27.461 -27.999 -11.999 c
+-27.999 3.463 -15.462 16 0 16 c
+0 0 l
+-6.607 0.011 -12.01 -5.392 -11.999 -11.999 c
+-12.01 -18.606 -6.607 -24.009 0 -23.998 c
+6.607 -24.009 12.01 -18.606 11.999 -11.999 c
+12.01 -5.392 6.607 0.011 0 0 c
+f
+Q
+q 1 0 0 1 183 313.436 cm
+0 0 m
+0 -0.468 l
+0 -5.164 l
+-6.607 -5.153 -12.01 -10.555 -11.999 -17.163 c
+-12.01 -23.77 -6.607 -29.172 0 -29.162 c
+6.607 -29.172 12.01 -23.77 11.999 -17.163 c
+12.01 -10.555 6.607 -5.153 0 -5.164 c
+0 -0.468 l
+0.316 -0.694 0.738 -0.997 1.055 -1.223 c
+3.817 -3.661 7.459 -4.869 10 -7.617 c
+12.018 -9.8 13.458 -12.461 14.279 -15.528 c
+15.091 -18.562 16.901 -19.343 16.918 -19.345 c
+18.873 -19.539 24.733 -10.483 17.857 -2.241 c
+10.879 6.124 0.769 1.958 0 0 c
+0 10.836 l
+15.462 10.836 27.999 -1.701 27.999 -17.163 c
+27.999 -32.625 15.462 -45.162 0 -45.162 c
+-15.462 -45.162 -27.999 -32.625 -27.999 -17.163 c
+-27.999 -1.701 -15.462 10.836 0 10.836 c
+0 0 l
+f
+Q
+0.302 0.506 0.137  scn
+q 1 0 0 1 183 315.2832 cm
+0 0 m
+-0.296 -0.712 -1.487 -1.168 -1.735 -1.898 c
+-1.987 -2.638 -2.003 -3.873 -1.53 -4.494 c
+-1.227 -4.893 -0.45 -4.945 0 -5.167 c
+0 -7.011 l
+-6.607 -7 -12.01 -12.402 -11.999 -19.01 c
+-12.01 -25.617 -6.607 -31.02 0 -31.009 c
+6.607 -31.02 12.01 -25.617 11.999 -19.01 c
+12.01 -12.402 6.607 -7 0 -7.011 c
+0 -5.167 l
+0.338 -5.201 0.788 -5.245 1.126 -5.278 c
+2.249 -5.476 12.142 -7.556 13.761 -19.537 c
+14.172 -22.51 l
+14.637 -23.085 15.725 -23.501 16.46 -23.424 c
+20.584 -22.987 26.414 -9.567 15.896 -1.312 c
+7.943 4.929 0.035 0.084 0 0 c
+0 8.989 l
+15.462 8.989 27.999 -3.548 27.999 -19.01 c
+27.999 -34.472 15.462 -47.009 0 -47.009 c
+-15.462 -47.009 -27.999 -34.472 -27.999 -19.01 c
+-27.999 -3.548 -15.462 8.989 0 8.989 c
+0 0 l
+f
+Q
+0.294 0.494 0.133  scn
+q 1 0 0 1 183 316.4023 cm
+0 0 m
+-0.627 -1.109 -1.866 -1.525 -2.708 -2.391 c
+-4.764 -4.503 -4.447 -6.209 -4.44 -6.223 c
+-4.355 -6.386 -4.355 -6.386 0 -7.408 c
+0 -8.13 l
+-6.607 -8.119 -12.01 -13.521 -11.999 -20.129 c
+-12.01 -26.736 -6.607 -32.139 0 -32.128 c
+6.607 -32.139 12.01 -26.736 11.999 -20.129 c
+12.01 -13.521 6.607 -8.119 0 -8.13 c
+0 -7.408 l
+0.312 -7.428 0.727 -7.455 1.039 -7.475 c
+5.586 -8.118 13.155 -12.017 12.674 -22.548 c
+12.56 -25.061 12.663 -26.477 12.982 -26.758 c
+14.311 -27.929 23.356 -23.684 22.629 -14.042 c
+21.269 4.004 1.142 2.019 0 0 c
+0 7.87 l
+15.462 7.87 27.999 -4.667 27.999 -20.129 c
+27.999 -35.591 15.462 -48.128 0 -48.128 c
+-15.462 -48.128 -27.999 -35.591 -27.999 -20.129 c
+-27.999 -4.667 -15.462 7.87 0 7.87 c
+0 0 l
+f
+Q
+0.286 0.482 0.133  scn
+q 1 0 0 1 183 317.3276 cm
+0 0 m
+-0.223 -0.377 -0.896 -0.494 -1.279 -0.706 c
+-3.983 -2.198 -4.352 -2.882 -7.218 -8.204 c
+-10.977 -15.407 l
+-12.034 -17.649 -12.409 -19.973 -12.123 -22.51 c
+-11.368 -29.204 -4.441 -35.04 3.701 -32.832 c
+16.504 -28.451 l
+19.64 -26.383 21.524 -23.889 22.614 -20.364 c
+24.61 -13.908 21.812 -4.74 13.674 -0.575 c
+6.26 3.219 0.029 0.049 0 0 c
+0 6.945 l
+15.462 6.945 27.999 -5.592 27.999 -21.054 c
+27.999 -36.516 15.462 -49.053 0 -49.053 c
+-15.462 -49.053 -27.999 -36.516 -27.999 -21.054 c
+-27.999 -5.592 -15.462 6.945 0 6.945 c
+0 0 l
+f
+Q
+0.278 0.471 0.129  scn
+q 1 0 0 1 183 318.1274 cm
+0 0 m
+-0.174 -0.267 -0.682 -0.3 -0.974 -0.428 c
+-3.27 -1.438 -6.363 -4.313 -7.593 -6.58 c
+-13.39 -17.262 -13 -20.653 -12.686 -23.377 c
+-12.045 -28.943 -6.307 -36.332 3.975 -34.516 c
+34.372 -29.149 23.201 -7.033 15.417 -1.844 c
+7.621 3.352 0.038 0.059 0 0 c
+0 6.145 l
+15.462 6.145 27.999 -6.392 27.999 -21.854 c
+27.999 -37.316 15.462 -49.853 0 -49.853 c
+-15.462 -49.853 -27.999 -37.316 -27.999 -21.854 c
+-27.999 -6.392 -15.462 6.145 0 6.145 c
+0 0 l
+f
+Q
+0.275 0.459 0.125  scn
+q 1 0 0 1 183 318.8281 cm
+0 0 m
+-0.26 -0.393 -1.01 -0.429 -1.443 -0.612 c
+-4.281 -1.816 -7.531 -4.969 -9.346 -8.278 c
+-13.498 -15.848 -13.757 -21.085 -13.244 -24.146 c
+-12.335 -29.558 -7.256 -38.113 6.018 -35.853 c
+29.65 -31.827 27.567 -10.229 15.691 -2.188 c
+7.725 3.206 0.039 0.058 0 0 c
+0 5.444 l
+15.462 5.444 27.999 -7.093 27.999 -22.555 c
+27.999 -38.017 15.462 -50.554 0 -50.554 c
+-15.462 -50.554 -27.999 -38.017 -27.999 -22.555 c
+-27.999 -7.093 -15.462 5.444 0 5.444 c
+0 0 l
+f
+Q
+0.267 0.447 0.122  scn
+q 1 0 0 1 183 319.4941 cm
+0 0 m
+-0.27 -0.397 -1.042 -0.411 -1.488 -0.586 c
+-3.111 -1.225 -7.249 -3.37 -10.633 -9.471 c
+-11.685 -11.368 -15.021 -18.084 -13.796 -24.877 c
+-12.453 -32.323 -5.461 -39.362 6.714 -37.218 c
+28.943 -33.304 28.97 -11.255 15.609 -2.301 c
+7.856 2.895 0.038 0.056 0 0 c
+0 4.778 l
+15.462 4.778 27.999 -7.759 27.999 -23.221 c
+27.999 -38.683 15.462 -51.22 0 -51.22 c
+-15.462 -51.22 -27.999 -38.683 -27.999 -23.221 c
+-27.999 -7.759 -15.462 4.778 0 4.778 c
+0 0 l
+f
+Q
+0.259 0.439 0.118  scn
+q 1 0 0 1 183 320.105 cm
+0 0 m
+-0.285 -0.403 -1.085 -0.384 -1.55 -0.549 c
+-2.14 -0.758 -7.426 -2.783 -11.14 -9.4 c
+-12.536 -11.888 -15.643 -18.441 -14.343 -25.552 c
+-13.349 -30.994 -7.597 -40.716 7.05 -38.567 c
+28.064 -35.482 30.902 -13.127 16.17 -2.838 c
+7.979 2.883 0.04 0.057 0 0 c
+0 4.167 l
+15.462 4.167 27.999 -8.37 27.999 -23.832 c
+27.999 -39.293 15.462 -51.831 0 -51.831 c
+-15.462 -51.831 -27.999 -39.293 -27.999 -23.832 c
+-27.999 -8.37 -15.462 4.167 0 4.167 c
+0 0 l
+f
+Q
+0.255 0.427 0.118  scn
+q 1 0 0 1 183 320.6777 cm
+0 0 m
+-0.294 -0.407 -1.113 -0.365 -1.59 -0.521 c
+-3.037 -0.996 -8.057 -3.068 -11.887 -9.807 c
+-12.95 -11.676 -16.306 -18.381 -14.886 -26.189 c
+-13.692 -32.763 -6.813 -41.824 7.243 -39.849 c
+28.687 -36.835 31.471 -13.847 16.374 -3.144 c
+8.08 2.736 0.041 0.056 0 0 c
+0 3.595 l
+15.462 3.595 27.999 -8.942 27.999 -24.404 c
+27.999 -39.866 15.462 -52.403 0 -52.403 c
+-15.462 -52.403 -27.999 -39.866 -27.999 -24.404 c
+-27.999 -8.942 -15.462 3.595 0 3.595 c
+0 0 l
+f
+Q
+0.247 0.416 0.114  scn
+q 1 0 0 1 183 321.2148 cm
+0 0 m
+-0.327 -0.44 -1.224 -0.37 -1.749 -0.528 c
+-5.52 -1.667 -9.765 -5.26 -12.073 -9.267 c
+-15.394 -15.036 -16.522 -20.932 -15.426 -26.791 c
+-13.856 -35.176 -5.227 -43.01 7.675 -41.012 c
+29.382 -37.65 31.673 -13.956 16.092 -3.122 c
+8.188 2.374 0.041 0.052 0 0 c
+0 3.058 l
+15.462 3.058 27.999 -9.479 27.999 -24.941 c
+27.999 -40.403 15.462 -52.94 0 -52.94 c
+-15.462 -52.94 -27.999 -40.403 -27.999 -24.941 c
+-27.999 -9.479 -15.462 3.058 0 3.058 c
+0 0 l
+f
+Q
+0.239 0.404 0.11  scn
+q 1 0 0 1 183 321.7295 cm
+0 0 m
+-0.315 -0.413 -1.169 -0.321 -1.671 -0.458 c
+-5.628 -1.543 -10.186 -5.222 -12.509 -9.206 c
+-13.794 -11.411 -17.706 -18.119 -15.958 -27.368 c
+-14.312 -36.085 -5.369 -44.227 7.962 -42.147 c
+29.823 -38.738 32.256 -15.066 16.713 -3.752 c
+8.241 2.415 0.041 0.054 0 0 c
+0 2.543 l
+15.462 2.543 27.999 -9.994 27.999 -25.456 c
+27.999 -40.918 15.462 -53.455 0 -53.455 c
+-15.462 -53.455 -27.999 -40.918 -27.999 -25.456 c
+-27.999 -9.994 -15.462 2.543 0 2.543 c
+0 0 l
+f
+Q
+0.235 0.392 0.106  scn
+q 1 0 0 1 183 322.2021 cm
+0 0 m
+-0.326 -0.417 -1.197 -0.297 -1.71 -0.424 c
+-5.005 -1.241 -10.021 -4.174 -13.317 -9.752 c
+-16.642 -15.38 -17.708 -21.487 -16.484 -27.902 c
+-14.771 -36.889 -5.522 -45.311 8.242 -43.22 c
+29.813 -39.944 32.242 -15.421 16.845 -4.05 c
+8.507 2.107 0.042 0.053 0 0 c
+0 2.07 l
+15.462 2.07 27.999 -10.467 27.999 -25.929 c
+27.999 -41.391 15.462 -53.928 0 -53.928 c
+-15.462 -53.928 -27.999 -41.391 -27.999 -25.929 c
+-27.999 -10.467 -15.462 2.07 0 2.07 c
+0 0 l
+f
+Q
+0.227 0.38 0.106  scn
+q 1 0 0 1 183 322.6421 cm
+0 0 m
+-0.165 -0.201 -0.596 -0.119 -0.851 -0.169 c
+-6.63 -1.321 -11.086 -5.48 -13.33 -8.99 c
+-17.823 -16.018 -17.96 -22.68 -17.283 -27.031 c
+-15.529 -38.308 -5.353 -45.633 6.914 -44.447 c
+29.053 -42.307 33.213 -18.564 18.588 -5.674 c
+9.722 2.142 0.051 0.062 0 0 c
+0 1.63 l
+15.462 1.63 27.999 -10.907 27.999 -26.369 c
+27.999 -41.831 15.462 -54.368 0 -54.368 c
+-15.462 -54.368 -27.999 -41.831 -27.999 -26.369 c
+-27.999 -10.907 -15.462 1.63 0 1.63 c
+0 0 l
+f
+Q
+0.22 0.369 0.102  scn
+q 1 0 0 1 183 323.0532 cm
+0 0 m
+-0.345 -0.419 -1.243 -0.245 -1.775 -0.35 c
+-5.333 -1.052 -10.598 -4.013 -13.752 -8.857 c
+-18.474 -16.108 -18.606 -22.979 -17.885 -27.465 c
+-16.272 -37.503 -7.101 -46.92 7.31 -45.499 c
+29.575 -43.3 33.52 -19.116 18.666 -5.999 c
+9.679 1.938 0.05 0.061 0 0 c
+0 1.219 l
+15.462 1.219 27.999 -11.318 27.999 -26.78 c
+27.999 -42.242 15.462 -54.779 0 -54.779 c
+-15.462 -54.779 -27.999 -42.242 -27.999 -26.78 c
+-27.999 -11.318 -15.462 1.219 0 1.219 c
+0 0 l
+f
+Q
+0.212 0.361 0.098  scn
+q 1 0 0 1 183 323.4082 cm
+0 0 m
+-0.359 -0.424 -1.279 -0.213 -1.827 -0.305 c
+-2.571 -0.429 -9.239 -1.713 -14.035 -8.521 c
+-19.337 -16.049 -19.04 -23.602 -18.666 -26.5 c
+-16.791 -41.035 -4.557 -47.119 6.015 -46.62 c
+29.237 -45.525 34.039 -19.966 18.705 -6.311 c
+9.693 1.714 0.05 0.059 0 0 c
+0 0.864 l
+15.462 0.864 27.999 -11.673 27.999 -27.135 c
+27.999 -42.597 15.462 -55.134 0 -55.134 c
+-15.462 -55.134 -27.999 -42.597 -27.999 -27.135 c
+-27.999 -11.673 -15.462 0.864 0 0.864 c
+0 0 l
+f
+Q
+0.208 0.349 0.094  scn
+q 1 0 0 1 183 323.7339 cm
+0 0 m
+-0.366 -0.422 -1.29 -0.183 -1.842 -0.262 c
+-5.616 -0.798 -11.203 -3.577 -14.553 -8.414 c
+-20.526 -17.037 -19.484 -25.015 -19.142 -27.636 c
+-17.325 -41.545 -4.721 -48.296 6.215 -47.587 c
+22.825 -46.511 31.838 -32.41 25.896 -16.796 c
+27.251 -20.083 27.999 -23.685 27.999 -27.46 c
+27.999 -42.922 15.462 -55.459 0 -55.459 c
+-15.462 -55.459 -27.999 -42.922 -27.999 -27.46 c
+-27.999 -11.999 -15.462 0.539 0 0.539 c
+0 0 l
+f
+Q
+0.2 0.337 0.09  scn
+q 1 0 0 1 183 323.9893 cm
+0 0 m
+-0.38 -0.425 -1.322 -0.147 -1.889 -0.211 c
+-3.74 -0.417 -10.183 -1.633 -15.334 -8.604 c
+-20.12 -15.081 -20.496 -23.225 -19.964 -27.016 c
+-18.071 -40.5 -7.311 -49.139 6.811 -48.512 c
+13.567 -48.212 30.458 -42.954 27.513 -22.495 c
+27.832 -24.187 27.999 -25.932 27.999 -27.716 c
+27.999 -43.178 15.462 -55.715 0 -55.715 c
+-15.462 -55.715 -27.999 -43.178 -27.999 -27.716 c
+-27.999 -12.254 -15.462 0.283 0 0.283 c
+0 0 l
+f
+Q
+0.192 0.325 0.09  scn
+q 1 0 0 1 183 324.1802 cm
+0 0 m
+-0.389 -0.421 -1.333 -0.109 -1.905 -0.156 c
+-5.862 -0.48 -11.762 -2.986 -15.367 -7.721 c
+-21.456 -15.72 -21.121 -23.999 -20.694 -27.186 c
+-18.877 -40.767 -7.134 -50.353 6.621 -49.484 c
+16.365 -48.869 27.809 -42.685 27.992 -27.284 c
+27.997 -27.491 27.999 -27.699 27.999 -27.907 c
+27.999 -43.369 15.462 -55.906 0 -55.906 c
+-15.462 -55.906 -27.999 -43.369 -27.999 -27.907 c
+-27.999 -12.445 -15.462 0.092 0 0.092 c
+0 0 l
+f
+Q
+0.188 0.314 0.086  scn
+q 1 0 0 1 183 324.269 cm
+0 0 m
+-0.403 -0.423 -1.362 -0.067 -1.945 -0.096 c
+-5.653 -0.278 -11.171 -1.795 -16.407 -7.987 c
+-19.42 -11.549 -22.258 -18.906 -21.583 -25.522 c
+-19.025 -50.59 4.157 -50.418 5.143 -50.399 c
+17.394 -50.156 25.847 -43.167 27.756 -31.704 c
+25.941 -45.414 14.205 -55.995 0 -55.995 c
+-15.462 -55.995 -27.999 -43.458 -27.999 -27.996 c
+-27.999 -12.534 -15.462 0.003 0 0.003 c
+0 0 l
+f
+Q
+0.18 0.302 0.082  scn
+q 1 0 0 1 178.769 323.9521 cm
+0 0 m
+-22.529 -4.551 -23.528 -35.026 -6.329 -46.258 c
+6.848 -54.862 25.641 -52.169 31.069 -35.683 c
+27.625 -47.245 16.912 -55.678 4.231 -55.678 c
+-11.231 -55.678 -23.768 -43.141 -23.768 -27.679 c
+-23.768 -13.386 -13.055 -1.592 0.778 0.109 c
+0.544 0.077 0.232 0.04 0 0 c
+f
+Q
+0.173 0.29 0.078  scn
+q 1 0 0 1 170.9761 321.4922 cm
+0 0 m
+-16.563 -9.063 -17.344 -40.194 9.316 -48.713 c
+16.64 -51.054 30.629 -50.189 36.987 -37.91 c
+32.359 -46.995 22.917 -53.218 12.024 -53.218 c
+-3.438 -53.218 -15.975 -40.681 -15.975 -25.219 c
+-15.975 -12.683 -7.734 -2.069 3.625 1.499 c
+3.1 1.309 2.399 1.057 1.873 0.867 c
+1.31 0.61 0.543 0.297 0 0 c
+f
+Q
+0.314 0.525 0.145  scn
+q 1 0 0 1 198.9263 298.0972 cm
+0 0 m
+-1.706 2.422 -2.871 5.192 -4.806 7.466 c
+-5.58 8.375 -6.333 9.14 -7.046 9.74 c
+-7.103 9.788 -12.7 14.579 -12.706 14.929 c
+-12.708 15.035 -10.925 16.753 -10.74 16.825 c
+-10.058 17.086 -7.544 17.231 -6.875 17.166 c
+-5.111 16.992 -2.438 16.241 0.275 13.649 c
+3.79 10.293 4.269 6.382 4.332 5.263 c
+4.608 0.362 1.816 -1.553 1.125 -1.426 c
+0.589 -1.328 0.314 -0.445 0 0 c
+f
+Q
+0.322 0.537 0.145  scn
+q 1 0 0 1 199.0605 300.5908 cm
+0 0 m
+-1.97 2.883 -3.055 4.471 -4.87 6.595 c
+-5.072 6.832 -5.375 7.116 -5.591 7.34 c
+-5.844 7.601 -6.16 7.969 -6.419 8.224 c
+-6.913 8.711 -7.551 9.382 -8.074 9.839 c
+-9.724 11.281 -9.908 11.547 -9.911 11.595 c
+-9.914 11.655 -8.389 13.369 -8.295 13.411 c
+-7.711 13.674 -6.801 13.346 -6.164 13.276 c
+-2.962 12.927 -1.156 11.212 -0.476 10.566 c
+2.531 7.709 2.783 5.143 2.904 3.909 c
+2.938 3.565 2.929 0.875 2.709 0.41 c
+2.675 0.337 0.707 -0.875 0.645 -0.861 c
+0.33 -0.793 0.182 -0.267 0 0 c
+f
+Q
+0.325 0.549 0.149  scn
+q 1 0 0 1 198.1455 304.1201 cm
+0 0 m
+-0.737 0.235 -1.076 1.45 -1.576 2.04 c
+-3.148 3.894 -3.148 3.894 -3.897 4.678 c
+-4.212 5.008 -4.84 5.354 -4.922 5.803 c
+-4.014 7.981 l
+-3.953 8.007 -1.427 7.15 0.33 5.083 c
+1.631 3.552 2.397 0.755 2.281 0.574 c
+1.906 -0.01 0.699 -0.197 0.037 0.011 c
+0.026 0.014 0.011 -0.003 0 0 c
+f
+Q
+0.208 0.349 0.094  scn
+q 1 0 0 1 195.0493 321.5449 cm
+0 0 m
+-5.275 2.417 -9.403 2.407 -12.049 2.189 c
+-12.049 2.728 l
+-6.604 2.728 -1.522 1.173 2.777 -1.517 c
+2.232 -1.205 1.506 -0.789 0.961 -0.477 c
+0.673 -0.334 0.292 -0.134 0 0 c
+f
+Q
+0.2 0.337 0.09  scn
+q 1 0 0 1 191.2632 323.0293 cm
+0 0 m
+-3.078 0.794 -4.478 1.111 -8.263 0.96 c
+-8.263 1.243 l
+-4.866 1.243 -1.61 0.638 1.402 -0.47 c
+0.981 -0.329 0.425 -0.126 0 0 c
+f
+Q
+0.192 0.325 0.09  scn
+q 1 0 0 1 187.231 323.9521 cm
+0 0 m
+-2.557 0.263 -2.657 0.273 -4.231 0.228 c
+-4.231 0.32 l
+-2.431 0.32 -0.671 0.15 1.035 -0.174 c
+0.724 -0.122 0.312 -0.042 0 0 c
+f
+Q
+0.188 0.314 0.086  scn
+q 1 0 0 1 183 324.269 cm
+0 0 m
+0.335 0.003 0.669 -0.002 1.001 -0.014 c
+0.701 -0.01 0.211 -0.214 0 0 c
+f
+Q
+
endstream
endobj
981 0 obj
<</I true/K false/S/Transparency/Type/Group>>
endobj
1051 0 obj
[/Indexed/DeviceRGB 255 1052 0 R]
endobj
1052 0 obj
<</Length 428/Filter[/ASCII85Decode/FlateDecode]>>stream
+8;X]O>EqN@%''O_@%e@?J;%+8(9e>X=MR6S?i^YgA3=].HDXF.R$lIL@"pJ+EP(%0
+b]6ajmNZn*!='OQZeQ^Y*,=]?C.B+\Ulg9dhD*"iC[;*=3`oP1[!S^)?1)IZ4dup`
+E1r!/,*0[*9.aFIR2&b-C#s<Xl5FH@[<=!#6V)uDBXnIr.F>oRZ7Dl%MLY\.?d>Mn
+6%Q2oYfNRF$$+ON<+]RUJmC0I<jlL.oXisZ;SYU[/7#<&37rclQKqeJe#,UF7Rgb1
+VNWFKf>nDZ4OTs0S!saG>GGKUlQ*Q?45:CI&4J'_2j<etJICj7e7nPMb=O6S7UOH<
+PO7r\I.Hu&e0d&E<.')fERr/l+*W,)q^D*ai5<uuLX.7g/>$XKrcYp0n+Xl_nU*O(
+l[$6Nn+Z_Nq0]s7hs]`XX1nZ8&94a\~>
endstream
endobj
962 0 obj
<</Private 963 0 R/LastModified(D:20100413200510+02'00')>>
endobj
963 0 obj
<</RoundtripVersion 13/CreatorVersion 13/ContainerVersion 11/AIMetaData 964 0 R/AIPrivateData1 965 0 R/AIPrivateData2 966 0 R/AIPrivateData3 967 0 R/AIPrivateData4 968 0 R/NumBlock 4/RoundtripStreamType 1>>
endobj
964 0 obj
<</Length 974>>stream
+%!PS-Adobe-3.0 
%%Creator: Adobe Illustrator(R) 13.0
%%AI8_CreatorVersion: 13.0.2
%%For: (Gilles Dubochet) ()
%%Title: (type_tags.ai)
%%CreationDate: 4/13/10 8:05 PM
%%BoundingBox: -227 -99 143 234
%%HiResBoundingBox: -226.5 -98.5 142.5908 233.748
%%DocumentProcessColors: Cyan Magenta Yellow Black
%AI5_FileFormat 9.0
%AI12_BuildNumber: 434
%AI3_ColorUsage: Color
%AI7_ImageSettings: 0
%%RGBProcessColor: 0 0 0 ([Registration])
%AI3_Cropmarks: -59.5 -62.5 -46.5 -49.5
%AI3_TemplateBox: 40.5 29.5 40.5 29.5
%AI3_TileBox: -239.5552 -349.6377 319.4453 433.3623
%AI3_DocumentPreview: None
%AI5_ArtSize: 841.8898 595.2756
%AI5_RulerUnits: 6
%AI9_ColorModel: 1
%AI5_ArtFlags: 0 0 0 1 0 0 1 0 0
%AI5_TargetResolution: 800
%AI5_NumLayers: 5
%AI9_OpenToView: -285.3354 49.2085 4.4426 1589 965 18 0 0 470 360 0 0 1 1 1 0 1
%AI5_OpenViewLayers: 77777
%%PageOrigin:-399 227
%AI7_GridSettings: 72 8 72 8 1 0 0.8 0.8 0.8 0.9 0.9 0.9
%AI9_Flatten: 1
%AI12_CMSettings: 00.MS
%%EndComments

endstream
endobj
965 0 obj
<</Length 7512>>stream
+%%BoundingBox: -227 -63 143 234
%%HiResBoundingBox: -226.5 -62.001 142.5908 233.748
%AI7_Thumbnail: 128 104 8
%%BeginData: 7364 Hex Bytes
%0000330000660000990000CC0033000033330033660033990033CC0033FF
%0066000066330066660066990066CC0066FF009900009933009966009999
%0099CC0099FF00CC0000CC3300CC6600CC9900CCCC00CCFF00FF3300FF66
%00FF9900FFCC3300003300333300663300993300CC3300FF333300333333
%3333663333993333CC3333FF3366003366333366663366993366CC3366FF
%3399003399333399663399993399CC3399FF33CC0033CC3333CC6633CC99
%33CCCC33CCFF33FF0033FF3333FF6633FF9933FFCC33FFFF660000660033
%6600666600996600CC6600FF6633006633336633666633996633CC6633FF
%6666006666336666666666996666CC6666FF669900669933669966669999
%6699CC6699FF66CC0066CC3366CC6666CC9966CCCC66CCFF66FF0066FF33
%66FF6666FF9966FFCC66FFFF9900009900339900669900999900CC9900FF
%9933009933339933669933999933CC9933FF996600996633996666996699
%9966CC9966FF9999009999339999669999999999CC9999FF99CC0099CC33
%99CC6699CC9999CCCC99CCFF99FF0099FF3399FF6699FF9999FFCC99FFFF
%CC0000CC0033CC0066CC0099CC00CCCC00FFCC3300CC3333CC3366CC3399
%CC33CCCC33FFCC6600CC6633CC6666CC6699CC66CCCC66FFCC9900CC9933
%CC9966CC9999CC99CCCC99FFCCCC00CCCC33CCCC66CCCC99CCCCCCCCCCFF
%CCFF00CCFF33CCFF66CCFF99CCFFCCCCFFFFFF0033FF0066FF0099FF00CC
%FF3300FF3333FF3366FF3399FF33CCFF33FFFF6600FF6633FF6666FF6699
%FF66CCFF66FFFF9900FF9933FF9966FF9999FF99CCFF99FFFFCC00FFCC33
%FFCC66FFCC99FFCCCCFFCCFFFFFF33FFFF66FFFF99FFFFCC110000001100
%000011111111220000002200000022222222440000004400000044444444
%550000005500000055555555770000007700000077777777880000008800
%000088888888AA000000AA000000AAAAAAAABB000000BB000000BBBBBBBB
%DD000000DD000000DDDDDDDDEE000000EE000000EEEEEEEE0000000000FF
%00FF0000FFFFFF0000FF00FFFFFF00FFFFFF
%524C45FD0AFFA8282F53FD7CFF06A8FF5359FD7AFFA92EA8FF537EFD7BFF
%53282E28A8FD27FF2E2828A8FD51FF847EAFFD27FF5953AFA928FD7BFF59
%2EFFA82FA8FD7AFF847E7E2E59FD7CFFA87D7DFDFCFFFDFCFFFD31FFA9FF
%FFFFA9FFFFFFA9FD76FFA9FFA9AFA9FFA9AFA9FFA9AFA9FD1AFFA87E537E
%A8FD2BFFA8A9A8AFA8FD23FFA9A9A8A9A8A9A8A9A8A9A8A9A8AFFD17FFA9
%7E282F282F282F2F7EA8FD26FFA8532F282F282F53A8FD22FFA9AFA9AFA9
%AFA9AFA9AFA9AFA9FD16FF7E2E0128062F292F292F062F7EFD23FFA85906
%28062F282F2829065384FD1FFFA8A9A8A9A8A9A8A9A8A9A8A984FD16FF84
%28062F292F292F29542F30292FA8FD21FFA853062928FD042F542F30292F
%84FD1FFFA9AFA9FFA9AFA9FFA9AFA9AFA9FD09FFA8A87DFF7DFFA8FD04FF
%A8280529282929535353292F292F292FA8FD1FFFA92F00280629062F292F
%292F292F292FA8FD1DFFA8A9A8A9A8A9A8A9A8A9A8A9A8FD04FFA87DFF7D
%FFA852275227277D27A8FFFFFF530628282F5AA9FD04FF7E302F302953FD
%1FFF7E06282FA984A82F7EA8A9847E2F302953FD1EFFA9AFA9AFA9AFA9AF
%A9AFA9A9A9FFFFFF52FF5227527D7D52527D527DF8A8FFFFA8002806297E
%FD07FF7E30292F06A8FD1DFFA905280653FFFFFFA9FD05FF7E292F0684FD
%1CFFA8A9A8A9A8A9A8A9A8A9A8A9A8AFFFFFA8527D7D27A8FD05527DFF7D
%A8FFFF5328282959FD04FFA9FD04FF7E302F2F59FD1DFF7D28282953FD0A
%FF5A292F53FD1DFFA9FFA9AFA9FFA9AFA9FFA9AFA9FD09FFA8FFA8FD06FF
%A82E002806A9FFFFFF7E067EFD04FF292F292FA8FD1CFF5300280653FD04
%FF5A5AA9FFFFFF7E2F292FA8FD1BFFA9A9A8A9A8A9A8A9A8A9A8A9A8FD14
%FF2828062FFD04FF2F2F29FD04FF542F2F28FD1DFF2E28062953FFFFFFA8
%2F067EFFFFFFA92F2F28FD1DFFA9AFA9AFA9AFA9AFA9AFA9AFA9FD12FFA8
%28052828FFFFFFA82F292FA8FFFFFF2F2F2929A8FD1BFF842805280659FF
%FFFF8407292FFFFFFF842F2929A8FD1BFFA8A9A8A9A8A9A8A9A8A9A8A9A8
%FD14FF2828062FFD04FF2F292FFD04FF54292F28FD1DFF5328282953FFFF
%FFA82F077EFFFFFFAF292F28FD1DFFA9FFA9FFA9FFA9FFA9FFA9FD15FF53
%002806A8FFFFFFA92984FFFFFFA8072F0653A8FD1CFF7D00280659FD04FF
%532FA8FFFFFF7E29282FA8FD1BFFFD04532E5353532E535353287EFD13FF
%7D2828282FFD09FF532F28297DFD1DFF7E28282853FD0AFF53282953FD1C
%FF5300280006002800060028000053FD13FFA92828060653FD07FF532928
%2828FD1FFF28280053FD09FF7E062806A8FD1CFF2E050028000600280006
%00280053FD14FFA8062828282E7E84AFA87E292F282F06A8FD1FFFA80628
%53FFFFFFA8A9FFFFA87E282F067DFD1DFF53002806280528062805280606
%53FD15FF7D0028052806280628062806280059FD21FF7D0053FFFFFF7E06
%2F28280628012EA8FD1DFF2E06002800280028002800280053FD04FFA8FF
%FFFFA8FFFFA8A8FFA8FD07FF7E06280628282806282828067EFD23FF5952
%FFFFFF7E28062828280053A8FD1EFF5300280528062805280628050653FF
%FFFF7D52FF7D52A852A852A8527DFF7D7DFD04FFA9A82828000600060028
%28A8FD24FFA8A8A9FFFF8400060028287DA8FD1FFF280600060028000600
%2800060059FFFFFFA852A8277DFF7D527DA8527D7D27A8FD07FFA87E597D
%537EA8FD2BFFA8282E7D7DFD22FF5300280528062805280628052853FFFF
%FFA87DA852527D52FF527DA852527D27FD3AFFA8FD25FF2E060028002800
%28002800280059FD04FF7DFFFFA8527D7D7DA87D7DFF7DA8FD60FF530028
%0628052806280528060653FD72FF2E05002800060028000600280053FD72
%FF5300280628052806280528060653FD72FF280000060006000600060006
%0053FD72FF7E2E532E5353532E5353532E537DFDFCFFFDFCFFFDFCFFFDFC
%FFFDFCFFFDFCFFFDFCFFFDFCFFFDFCFFFDFCFFFD9AFFCACAA8CAA8CAA8CA
%A8CAA8CAA8FD74FFFD0DCAFD18FFA8A8587C5883A8FD53FFCACAA8CAA8CA
%A8CAA8CAA8CAA8CAFD17FF7C51262D2C2D2C5151A8FD52FFFD0DCAFD15FF
%A82D2C262D2C512C2D2C2D2C7CA8FD29FFA87D5258515858A8FD1EFFA8CA
%A8CAA8CAA8CAA8CAA8CAA1FD05FFA8FFA8FD0DFFAE2D2D2D512D572D572D
%5757572C7CFD28FF7C51262D2C2D2C2D2D58A8FD1DFFCACACAFFCACACAFF
%FD05CAFFFFFFFD047DFD0DFF2D26262D2C2D2C5757582D572D572C7CFD25
%FFA82D2C262D2C2D2D572C572C2D7DFD1BFFA8CAA8CAA8CAA8CAA8CAA8CA
%A8FD04FFFD04527D7D7D275252A85252A8FFFF582C2C2D2C577CCFFD04FF
%FD04572CA8FD24FF2D2C2C51517C83FF57572D572D2D7DFD1BFFFD0DCAFF
%FFFF52A8522752FF525227A8A82752FFFFA82D042D2C2D83FD06FF572C57
%2D2D51FD23FF5126262D2CA8FFFFFF582C572C572C2D83FD19FFA8CAA8CA
%A8CAA8CAA8CAA8CAA8CAFFFFFFA8A8FFA8A87DFF7DA852A87D7DFFFFA726
%2D2D2D83FD05FFCFAE2D5757572D57A8FD21FF832D2C2D2C57A8FFFFFF58
%57335757572C7CFD1AFFCAFFCACACAFFCACACAFFCACACAFD12FF5226262D
%2DFD04FF832C572D572C572D572CA7FD21FF58042D2C51A8FD06FF7C2C57
%2D572CA8FD18FFCACAA8CAA8CAA8CAA8CAA8CAA8CAFD12FF7D042D267CFF
%FFFFCF2C572C572D572D572D2D58FD21FF272D262D2DFD07FF58572D5733
%2D7CFD19FFFD0DCAFD12FF5226262C51FFFFFF832D2C2D2C572C572C572C
%7CFD20FFA82D262D2657A7FD04FFA8A7582C572C572C58FD18FFCAFFCACA
%CAFFCACACAFFCACACAFD13FF7D262D267CFD04FF572D2C572D572D572D2D
%83FD20FFA8262D2C512D57A8FFFFFF57572D572D572D2D58FD18FFA176A1
%76A176A176A176A1769AA1FD12FF7D2D262D2CFD05FF7C7D7C572C572C2D
%2CAEFD20FF832D262D2C512CA8FFFFFF572C572D572C572C58FD18FF4BFD
%0420442020204420202076FD13FF272D262C7CFD07FF2D572D512658FD22
%FF262D2C2D2C57A8FFFFFF57572D572D572D2D7CFD18FF76204B444B204B
%444B204B444476FD13FF7C042D262C7CFD06FF572C2D2C2C7DFD21FFA851
%042D262D2CA8FFFFFF582C512C572C2D0483FD18FF4B20204B2044204B20
%44204B2076FD13FFAE52262D262D518383A8A7832D512D2C58FD23FF7C2D
%262D2C2DA7FFFFFFAEA857572D572C51AEFD18FF76204B444B204B444B20
%4B444476FD07FFA8FD0CFFA72D042D262D042C262D042D262651FD24FFAE
%2626262D047DFD05FF582C2D2C2C58FD19FF4B44204B2045204B2045204B
%2076FFFFFF7D7DFF52A87D52FF7D52A852FF527DFFFFFFA852042C262D26
%2D262D262C52FD26FFA8042D262D2CAEFD04FF512D2C2D51FD1AFF76204B
%204B444B204B444B204476FFFFFF52A87D52A8FF52A8277DA87DA85252FD
%04FFA87D27260426042604517DFD28FF7D04262626047C7D7D582D26262D
%A8FD1AFF4B442044204B2044204B20442076FFFFFFA8275252527D52A852
%27FF52A85227FD07FFA77D587D58CFFD2BFFA82D26262D262C042C262D58
%FD1CFF76204B204B444B204B444B204576FFFFFF7DA8FF7DA8FF7DFFFFA8
%FFA8FFFFA8FD3AFF7C51042D042626587DFD1DFF4B442045204B2045204B
%20452076FD4DFFCFFFA8A8A8FD20FF76204B444B204B444B204B444476FD
%72FF4B20204B2044204B2044204B2076FD72FF76204B444B204B444B204B
%444476FD72FF5244204B444B204B444B204B2076FDFCFFFDFCFFFDFCFFFD
%FCFFFDFCFFFD2FFFA8512CA8FD7BFFA82D588304A8FD2EFFAEFD4CFF27FF
%832C58FD2CFFAE5151A7FD4BFF2D517C04A8FD2CFF047D7D2C83FD4AFFA8
%7D58A8FD2DFF2DA8CF047DFD7BFF26587D26A7FD7BFFAE5158A8FD7EFFAE
%FD42FFFF
%%EndData

endstream
endobj
966 0 obj
<</Length 65536>>stream
+%AI12_CompressedDatax���$�u����?dF�-���
ܵ5���C�F�3�������G}��"������
?�Հ@Jf�$�����
����_�_����o�����l�8��_ݼ{|���ݯ.����W�>���N�~��_^�����������������o��J�z6�'�e�_���W�
�_�~����|��ˋ_��>���^=�g?���ǯ><|�����_�u7����e�.�p��jX.~�����ۏo^�|�������g�]|v
e�.�i������}|����R_���/��l9���zz��{������|�ͻ��߿�y���������Û�_?|S�y��^�����W��>mr��͇��_���ˇu��~����W��K�������~����W�/_=�c�����!G���2~u������
�A��]}>}������Ǫ�P�-��W���5_>~�P�t}i����u�F�R�����/�!�Q���ݾ{���w_��l9�h�����Gn [...]
+�����~u�7o�<��z��˗��~�}.����/�cy6n�j�����w��R��V
v�~�����
c/��
��裴������7�j�y�������O�f�/z�n��|���߽���I?���4-�E�����Q��^�e?.����]�lކ�i�틾�:ٟ썷��Om���v����o^���gS���[�����/Z�o��n��_�ٞ�;��>y=><���R;�ͯS�������wo^ܼ}-��^ι�c������7�\�[������w�����o?<���z�X���7�
�����Ջ����3�/��է/o�?��\x��{x������|�����
^v��}l�`/yн]><��v��_=���C{�m��;��u���m��6}�M_��_�k^�׼�׼�ݟ.��k��kߦ׾�׾����^��^����t�1^���o
�]������y=ޗ�?<�{%����s醗�X����ۇwr���e���ÛxU��;=���^\>�m��7�pYO��r:_�g��{����__^�]~�� [...]
+�O-�z�|��_J�����ǿ�~�`-z���[��z���֒��t������{�w�������A���y�������P_��o?��]�ty���]�������pwvh>���sw�<^��
{�i|�/���W�>�����
i���_^���!^?<'��� ����zB�)mg����|�����W?�����nw�ݝ�t��_��}
J�2}���{��������8�����.����������F�����M�������Z�
�(�tY���?||xU
���7_�s�ß�(�G_PZ��z�p*{�����ˇW/^~��e���u ������WL��{� ���ߏ�/^?~�pq*�rY� '�E9�ˇo�����/o_�0g,���z���7�<^�� /~U��W_���޾�����qԾ�b���z�SL����|{���7�>֧���ۏ�~��뷧_X@����U=��ט��xa[������������{���zz�q������n��__~|���_�ї [...]
+����������;�sƛ����c�^�������/߿n�1��F������!��yo��_׬&
6��{󏏯�~�>d��!��=����v-�T����!z>��������]|�LJo��~�㽾��Ѝ_=��8��إ���ʳ
IV;]��}�}�=L\.�ߤ��Z�\ǹ_ɮ�<�g������'�*sNj�5���O��)�4��2��6
��p=�
w�})��,e��Q��u�)��~
�2��4��2��>
��x=ތ���i��a���4O5_���j��n���n��k�\Sњ�����|5_�7��|7�/�R�q�iв.۲�
�j�9-���:�e
�i]�u��}=֫�z�Yo׻�~���ۼ-�Z��};��j��n���n�߇��cܧ}>����^_�K.x�_���~����G��G9�7:��~�c9�{�����:���渭������G�tU�U=W�U�>W�S_�W�\�}_�m���u}�����]}�_�_����
���
��u=(���z]��|�k}�k�ǵ��������������uS [...]
+�7��-�c|�k,�5�s\i���q�:���I�F�'��v
+���%�C�r���7������[���ֵ�]������<~��ie���Z��[��jc������ӽo��洺���|m��7�5�y�;
+��
����'����v:�q�.!�b�NA��c�5��
��=��XG����K��|OZ����B;,�оU{���9���X���;�9���z�Ϭ�T��QH���K��t�j���(� g��O��m�w����������ڻ��+�v%�F���L��쵓�lw�#N�r�
����-;�v�k��֓|�'�Z����z����j��\�կ3�,��\�����X����������3����
g�}v������w�www�w7w�u�8j��*֖��t�+w��������M����S��v��se�'�x[n����n��=��;���zz,uT��Qn�J��J��J���I��y����ʝ:
���
+��
+�������빲֓r�
+͆�v���m�k>����Xj'�j�/�Pχ;��M=K�N������T��
�	6T�����W���뙹�C>�9[����w�)n�}Uf�ͳ�F�kSU�u�\���wS���^�s��:׶
k
�}e�me�um�C��V͵7��O�N8�WT��^r-����Vy��
4�~T�a��������ǎ�ӶJť�����2�����+��տE��e�k��Ӵ���4��lWi�ӏm�֪֨�Ӫ�;{�~l�~�u����ݾ����{[�dM�ӵ0��8sk�������
�\�2\�a��/O�U��~*V�g�\����4�D�eh�'2�Q2�92�E"%5��A�v���L���c�M���c���o�z`'����z$d䔱s��cލEx�Y�7i�'#j����R�w��O�>yX�7i{-.Z
(#���׳�*���ޢ“��
�}-
,J��iȸk�h�x iA��5��ւ������M���q�c�n��[����j'��o/�k�����#j�� [...]
���_���%z��x�>l�[
�o�Y�����̧�K����G�~e�K���{l
�����O��C�Ӈ�%�'����i8�|�?OF�ƟL�U�#�/	y�=�gblY�O�SH?�
+�y���7���X�,��s
]�$8lt�؟"玞G7J���iΚ]i
���ۍ6�Sw=��ayZ}�zPzd���F�I��l>�#Î
<2���s���C�
B2
-z~�P4���
:"ɘ$���K22�ؤq��o��!J)�f��>.�Yu�:�%#׍�^2~�&c��b��d��}v�O:���m
��u|������͵������!o�aO�U�E�Y�IB�R�3,�ZK�s��c}h_�}����w�d�+CL��4
��2���l���-
{<�x\��N�����=��!
%=�xL�1��	�ǚ
[�ػ�q�8i_�
�'4�����c^����S���
St��`��ܕ'�5�֙���q2S.�<���-݌K�[[�M�
�N�`��.�r��0�A��'�+��F�79���,ԳQ�!��|��颏z�ZtRG��I
"5H��T�&
�,�h��Fb�kZ�J ��N��+
&
��a�X�́
����6�T��^5/����B����|��A0|{�pAc��7�n5/��-�NFOO8)N�rƴHy
�8KA�����/;cS+[[
_i�j�j�Z�.ި�7�5d�&���S��QYs]?�m�k[I�s��7=)��S$�,=u0���T�S�3��
�lz�f�)$#�|�����A��v>o�;����9�Z��;��07��\�}����Y�>N��XA 1k01i@�!�=d�N��;���UۈrE��k³錟
��h�A�� !�%A��H0r���dפHӢ�gF��C���\{�d���,�/YN���'Mw'͛,s����ӧ
so2��CG���������i��8�_s�`�f���^���
��?�{vh����
]��%�:4�����Q�:A��RrV�i5i�d�s�:'~��\���p;�f���l�J�%��5�Ԥ�GG�tz��PF���S�
���:j�1��2FK�J!g��#���2R2J�1�FH
�kO��L�<9<'>������N�� rL,��J@�d�F=J'8>uA�B
>�@ �KC���C���C���֘��.���ޮ��q�0]1�,�
� �ɯrePX�s�x\�=�?7g���q�)�OB�
&��-\��u�O�-t>�s݇�)�>u�t���ϧ��V����w�D�6��>�:
�,gQ
�z��{2�w��	>���������1�{&q�g���,��M���9�ӧ&��Y�g�:l�|1<ʱ� Yʓ�S^��%�Py��a�U��r1������\�?�M+�k0�6�-j(5�����V�>���0�[y6���>�O�?�l�\ʶ����r�?7�:��QVq���{M��v�t�����ϰ�
��%Z��,_Mw3�56�^��͋
�����~���9���=��W�<��(?���y��ϫf~^5�󪙟W������U3?���y��ϫf~^5����f�oU̿���_�������.C [...]
.�_>p��͵��$O�Ī�-�k�H��6����-�g='��A�H�te���:o}���Ђ�d��������[[(��N����`�X�H��C\��xR�ȖgN�^�B|Ǭu\�=�»]
'�0���YE�,4�H�E�
�2���C%��_+&�>"�,����s{�|t�|�f&�O&��'J�]}�3.8�%I�Ƽ�k���t�>�F�����=ֳ��=��1���~<{��ѭ$ҕ)�����lj�u�w���{
g�=?N��>���h�'�-�p�B��������H��߯Q��k�4��ڤmsvq2.M����+�d8�N:"�W&m`�k�qi�(�6MP]�7�PU$������Xoe���K�l�][vW|�ݝ�c7���*������Y
����"n��Ձ�K��9V��"s���S����f���Q{���Qg)�>��l�IN�m^�]�Xu�S�6k�w�2�:��ͷ����)v��������㋋on��������I��4R�Ş�iy�Ke*]�|�̏x�Ɉk��U��7OJ [...]
 oO�!\I��Sk�,<�G�
5i�
l��=���2,��vJ~=pK��X3�_sbUP,/�򅅇/-l�
+_V8�E���������'
n<,���d��1�]�[5�����a�`ƈD$*���`
�b9̝/���p���(ϐ׏�O��~�>{����
�����~l��G����<
�>��5Q�cy�H�)��=y��aK�{��w,:L8n�����|��l�a
+G�XFq�~�jC��>���y��,�薢��h�����X�f��V�(�!��������J�֛65�����U��x��S�?h��w��h.�IC��Z��K>b2[�g�	���W~�|�G7��׺�ĶNm�E?r��	�n�}D҇?n?�E�9�j�~g��F
�y���.n�~�7 at j���b|V��<ۏ���Eq)nr]z]�W���W���C�_���?i�?���Z�O�ů/��
/��o[��=��׵���5�nZ��\��{���ŏX��֟�k?zG/���Z�m����R?�k�;�f�K��W
�,˸�Z��U��Z��s�b=|=�:N�Y���ݦ�K�e�6Y�ђ*Y�,/��q�r=�V�d������ƶ�d{�+�I
R�X?Q�]�S���C��ݤj٦Q_2���e����]�
���Ph�������J9)�f�/��Aߦ+{
�����Q����A�')WHlR>�'ky�7�ڪ��MG�G-O5��X����U��2mZ.�l��b�yA����0���Z7-�Qζ���]�+è� �k�ڪ����!O��$���j�Qfy�v,���z��|,��bYGo����r��;�G��Ձf��l�!f���2MlS�ת�
�Z܆��}�b
��(K���2ik�eѽn�6�X�]��]�\�A6�
Ox�E��gi�E�C-���k�k�Ը[�Q�=iuP����n���d5
�����Y_s
���P����e�m�a�3���}�b'�\;�~��p멹q�y���}e����Y����sH���-em+�4�6�k梽�&��b�&����e1�Z���m���5e=t�a[�4:d��˾r
+�0K��!㝞���{��V^���p�m���W���f�CR75��
��E���hU
K�%5���4
Z^�݀V{�ls_�[�z,=�n��tR,c#]-5q�H'u�}b��K=֭�N�e^3�jվ΍tR.K#����'�"������K#����t�׭���
�N:-/=�N���N���H'����t�硑NZi�������u��t���S#�"'�ڑnY*PfH�ȯ��t�<�GO�Z�G#]-���H���k(
�j�(? 
�j��#�<�=�jݤ�w��򲭍t��
KO�Z�K�nٞ
�xC:)n�'���k#��ku�\��f�I��
+�ղ\�	�Iyz��6��P��!�����25��k��:-�=�nj���26��׫�`�:9���P��Y꤇�S��ڑ]Wi��E�x	�i�+=�on����k��PW˺mF��q�
�)[��:-�=��h���fj�S

�5��P�彡N���u5Ϙ��#�T-���r
uR.S�PW�u�uR
�=PWˣ�됮֔cۃtR�����
���ɳ�1�l

�iU�rR.(���{���d]�Qr���qR�,"
��7ۦ#�Gkރq��J�W����q�|ԁ*7��X�vb\����
r��X�q���B�j�Q��`ܼ?�(W��4/
�j��q�B���� �Z^�q� W�6g�B���ؾ�f����AN~�z��j�n�A�Z����QN�F��RN��:�RN��u3央�IA9�i��"-����i�('u�ōJ����W�xPN��r	���7��Rζ�:�i��
J9};ɔrrD��v��#Yj�rҢr(�\m�ٞ�IO����,l���ӎ'ac��v�y
�IyZ瀜t�e�:��/�o��ӓ`8rZ.G9��怜af�)��5CNae�Q�iy,9)���r��4q�����+R�*��ĵ�u���s�Z�牫T�ĵ���U�?O\��K\e����.��U�R�*圸j�,q����J9'����W��9qՃ��Z~��NG���r���O���k�J�k-u��<<M\k]���C����y�:}�Z�]�Z�O׹�k-w��\�&��.'�� [...]
]�*/ɉ����U���i�W-�%�R�W)��U�y���̉�
���N�i�:�>q��.q�ʓ�us�ZK]�Z�O�Z�%���%���$q�U]�Z�]�*ϟ'�r�����r����ĵ���u���U�牫���U�)q�槉���ĵ���U�牫l�״A���i�W}MJ\�|��j]J\��W�z牫
Ȝ�j{��Uz�y�:�.q�J��j�;K\�o��u*}�Z�OW��9qU���U�g��֥�Uϛ��*���UX�W-��UʟJ\��I�*U9q�rN\�|���S��J9'��|��֚.q�rN\�|�����gs��>qժ��J9'�R>O\ǩO\�5)q��y�*�,'�z�R�Z�O�Z�%���%���$q�U9q�Ŝ���ĵ�u����<M\k]���r����ĵ�u�k-w��>M\ǵO\ǵK\k�I�*u9q�rN\��i�*u9q�{���U�牫���5�C('���U�:%�RΉ�m�'�Z�W}����9O\�H��UZ4'����W�I)q
�>qՎw��j�L���s�*
�<q
�>q [...]
�ۄڞ�
+���N�n�C7��D�R�m��	�t��S�n׼��n׼u�H's���FJ�]��a
�횷vA]�S�+�;4q-�:��?
k��C�}
�
��.
uÓ̵Vu�k-w��<�����\��g���$s-C����e�R<�\�.g�ZN�k)O3W�˙k-w����3W�&g�iʺ�4s-��\�5)s��Y�u)s�r�\Ky�����\�=�ú�i�k�Z@�L��FGE��4o�%
-G�N�ˏ)H��sG:�F
ٔt���c�n��J9��NΚilݮY�A�k��"�]��)@�k�:?����Ux�t��s��$ڶ-X7H�:�}\�?s���u��U��n��u0��;��6��w���@ޠ���`'=�v��4�
��;�+r�����h	�
�
+�1�7�Alȓ~9��*��c���dMd�`J�A3�q�
�ʖ��� ���
���U�F���l�b<�f� _�YY^4Yz�B<If�ƽQ�ٹe����[��J2kl�lVQi٬$��Y6+�l��F�ז�N�̖~�N�Y�d���#?J:g'ɬ
Rm�N�����$�]�6g'�Ѵ�sv��Z�9;If��6g'ɬ�ۜ�&�S����c�9;Mf�~�N��misv��9;Mf�~ήOf'�e[2;=�e'Me��L˸��
�Z����aڂ{����;�I眝���A��q
�
���<`�ON���A?9�<��?���.P*E�f )�i-#���&��)�j-�R
+��6
+>w
+^^��p�R�o���O��U�����_^\~�An�z�����?����z��_^�����7�B�ާ�������S�EW����o�%�W�����'V���R��C����������
��8}r]��Bs9K�f&�*�Lꉼ�u��әI��:�u�r	kH뤏�I�Ŗ�I�̤��g&�;
6˞VHOf&�*�L*��̤2�lfR8�c++��nfR��3����̤
�43�;�������w73)<:��T
��I����r�g&�H�I!I��Զ8���&�3���ifRϧ��I9����V��I9��g&
139)&*�#����LJ]��T>��IE��̤��E���<3)��I��3���1�X)��L�[o-��r���m��I�K0׷I3�rD�i��L3���<3)_�lfR�F��
�<3�
�lfR;g���r���6;��ԶN3��_JZ"}<��Ժ�Q<aƖHOf&VifR�ifR�yf���Z��Pz�ґE�D�/ZG�@"���څ�Ч�\C�1��:�K
+�k�)v����2ͥ]`+l슓�5��w
��sڂ���*�)N=e�q�8l�
a�z�)O��.��Ą࢞�K�w�#L����)J�����)J_�ᰋ'D����9J_6�}m
�&����WN����}
,��(}/�Q<G��a3
���&^	ҏ�G���ņe���Ɇ
����Y��/��벧��5g�mj7���la���3S�
���1���,x DW̶]�j�/Ӷ� }�
�����>؜��5X�
�E=�t�J%�5p���z�f���e
���}�=��݃�>D���B�y�!�6��<D�}bM1���L�N��^�]�[��"�c\l���Y2A�G�"���kG^�5'� kO��������q]�L�O���|�ǽ��V����h���yH-��P��Z�qg����o-���t�P��V<�V�m��R��(n2��i�}jR�i��j�I�)y8-�곖�)p�\}#�Oΐ
PK�h��M׎ϴ�PKy8�c��Z�
�J at -��lA�ԢnMG|s
������GZ�a���ei1��m�
/
�Y*B@]Ϝu���"�b���2�����b�E4e!�@{[H]lWR˸��"�
�Ԭ�!���W!�#��u�]���Z^�WN4�����>���M���z�_�Q�E��X"ji
__����e��Z�N�:[Dm:���D���H"j58��F#j��!�}Ծ��-�^eH
WZH�g�8�g��Z��
ۘ&��]D-g�bs�Q�ze���Z��-�ш���D;u-�A!�^]���ԭ�m4��]lvVhH-�,�!��
+NDԵ8�v�iD�.�Q�F�R7
���a�iD�Z.sc�5��|���K75�
mSRK��������4��r�{�

+�?-MC4N��f9Fe��Fe-�8�����Q�<�������sTNԭ4��нO����ʍ�r�s����Gc��Gm,��ak,����o�c�Rѷ�
7�
+K���T���0-�L��c�ie�b�
�5D�ݏW����
Sշ�������
0���T�ʹ=�
M�p�~���R�T���/�o���t��]S�T{��5P���MA��=G�TO�}�H���vI��n U3{.
H��>� )67 U��J�T��LR)�*oY-nS�Q��)��ǨZ���aT�y]�jbK`T��c	F�j
��6�U}�t�ø�5
����N
F��6�)FW�F���K�Q�sP���-q\E��Q���R.S��D�l�5�Jw�z��OMC�l?[`
-�
{��(iG�-��©;�,N=�q�'uzu[	's��R��㛘Ϧ�+�Է�K�M�h+�D��l|V��ֽ7�iy��U�xÿoR��;	o�q�S�M�1,c�M���A7���T�nz�怛جG��&R���&���6�uB6�Mt\�6Q�w

m����h[��m��zT���-�
it#[�P���@X���=�
�-k�IJ71���
o�,�u2�jU
v�����ru
���=wt�*Y�
ݴl���M��ц���ԭ���О�#�&e���|S��S��؇�
�;�M��+=z�_[֤|�m��7�Zo�.~�	��Y��oj�[�|��46)ߤ�
���M��b?ˡ��2[O�o����vN�
��Կʲ�D؞���tq�$�l
�lh�i��.�N�k N4�
��$� \�6�N
p'`"�Z�ے	'U
;᤼Z.+�SI��
�D�ެ75-�b ƉѼ����b��BN�l�)�|��n倜���FO����{K��ll	�;�
�IY��;�T���r*v�	��S�|^�rj�[P�����T��1��Dr�, 
Љ+�
҉<�s�N:um-�
ҩ���D�v�)�����ցN�m�tb��X�o{��D���-8'��>,��Y֔�s"m���i{�M8'��l	@�N�m^t�(�����k�f��q�ͤF:��-�
Љ�=
K�N��4�T�
�tR7[s*�b:��m*'@���:}��5
+:-{��Ӫe����G�N��a�H'G҃^%�6�餇L�ґNz�bXR��0�I�=o�:�i�FH'E۫�N��L
�D�>�1@�h9� ������rd��m�J:e�8v����-H��a
�!���N�m�d
�ܲ����:�T�� 1H'ueߝtb0����N���V'~�I���ֲU)�[������-[Uy�B>%���>]��Z����t�����j�J�N%��&~�A:��-�
ҩ�>�tu�ΐN��m��U5a�NI'���Ե��lU�\�h�t�m�c�VgY�e$l�" 3��E���N�jZ��i��i�nhDV����3���̥���l��F at W�l��|U��}m��:�6
`�+>��A�s+-a���V��m k��u���Y>�T�I�ғN,ұ���HWd]m���{[
+d���X~c�+-c�tR���U�fn)�J�=��܆��jc��s�A6���t�ci�t�zy8��n�3V훖-K���1��u���X��U��d
+:%��r�ɗ�g�i��(贼�:EQ�9�mi9�������]�䬓.��:�_' �e�9�<������9���/�9�c_��z'G
�
sbA�[Ü\ݲrÜ��6��31sR.k�9ٯ]�0̉�]�d�ۺ��|�	���(�F9�dO9�n�4�kʠ\흃M�5����('���aNN�>�
���D��Sʉ����#�����r���`�e{���ez��N�ܤ�����M2�&�0��D,
<��ղ��͜��{�SpNe�\s�M� �s3,ι�4�9�n�5ppN�t9�sN
�el3sR��*�3�{
��>�sR���ӷn����/�ͱŒ)�U)s��>���
+���qN�`Q�rN��]ި�R����t�ɘd���`N:�Mr6��O��9�
+��j�Y,_n���v��0'`ٷ�9)[��0W���\��	��@�9�
X��9��mr�8W<A�97꺄5sn�F�sR�l�@�"��:�E�1�Ii��K@'J�_�Ѝ��:�D��ז�����g�bSO[�\M��tZ.}��m��J�6骠SK�&ntR��wЩ9>�K��ъ�w:�ƥ��u���:�\�O\U�=� �X[��c�N\[Y��I'J�dɭ�n�Ãt�� �ޑN��N,�co��x��X�����9
+:��!��<bm{
�k{�[�*���M:q��>�F��h��j�6#��Sz���ni�ǖ��]�aN�r��U��8椼��
+�ԭ�%��ǜ���O\��-
Ҟ���GA��K\�jn�+�8�SG��W9���WmN���Nz�b�$�tғ��%��28@�
o��V霳��v��蜓�|�}ު?L0M�9���V-��sz�4�iѮ{(�Dg������8��q��8�X�c�,�vkU�J�Xǜ�5U��jBw���Lւ�j���!'E�
Ɖ�����ǥ�T���+U�ֶ�*�T��I?E���~����.'(����F�8չ�	�Iݶ��*&��8)/���:;�q��Ɖ˺��r����[0N��%嬢�
[�\Et\q`a���/E\�Y�^
�j
��2��u�
���91N|l��rƉ�=�m��<��
��Z�*�� ��+���E�2��ZE�k[y��+$	q�g\!�qƉ�<Z~�S�zo�U��Ve
�I��e* 'u��V��>
rR��~����<��5~m�m��*Z5��**�Om��|=q�3������ZE�s
r�E�~�+�s[�R�SN���/W���J�62�>5���0M�r��]DP�)X��\E˖,��L�LV9g�قsJ��_����r)�l圖�'�U�'�.�ә�i���z�(������U
n���ijt!�H'�~y*P��
���^사�N~
�s�@���kK[7Y9;7�Iy0D�d�{iW[�
�v
�;�N��c
ԉ�=n-o�d����r�
[@�
����9\���ઓ�K�[�g)��2O��͸��u���.D
rtZ�*?Xz
}4w�l�Q'
����:Yq^�񱷱��k�dE��z2�L=k������X7�
������
�M��5f֩��V-�����S��ub_�-oC{+Kc]-/�ҳN~5khyk�����
u�֖��%-��-��U�����:>����Osu��r�[�*�9m~N~
q�z�՞��=P�	_���H�+{����x��8�42��<U������� �.��l��e���݌�t�[ƥ]pU�,
t���3K at W�|
�rn�k*�뮣�|ι�A�B�t�"{���-� �u��,� Ye�c��5\��;�A#��.d�2H&^� 0O��/��.��
����B{��d�
f��e&��@>t�L���8����k:H�_� �y� �y� 9��!�kd�@!$z!$�.���"��\�uRYtRYt��ʺB&�”
:H��Ca�NO����tSv�Ĕ��5�ع���=3�?f�\�;B�;BbƎ}0c�FH7e'FH��0Bb�΍�<g�BH�ٹsv.�tsv.�D*�BHDy.�tQ�
!�Q�!~!�B�_!!��?B�6o>H�`�6�B `H!�a� ��B�`X!g�W�N�ˋز�K4����ڰ�_�Z�N
����\���b�����f˺�9"��~�A:��|UG���^�݇b[lI��Mˢ�5Dl�+�
�.�s�C̑Z��6�;�Ĭ,�[]��I)�r�9��O���
��U�)
�JIW�Ŭ��2��L�D�Y8�oG�#�pj�B
�&��-H��{�~������qd�ߗty�őZ'c"∬_,�cz�U��ҀM�ҴG����#��q����ͭ��
��jƋ�#�ѽo��.+%�y��ҕ�#����� [...]
&K��G�%�K "���M
��Q�0�<PG�5�f�+ڲ�̑���J]
	��;ҡ�ݑ@��#�R�G:��>,u}$X��Hf��#T�G��n�t<u{$x��H��푎�n�O�
	��=��� ��# ���.�P]
���#���# u
-���v�D������<NW�G2NW�G����8]]�8]]���#�tu}$�tu}�i��=L�9�0]�
���#�tu{$�tu���f����쑌���P��`���#���#����P��<�Q��=JW�G@�j�H&�����tuy��.�d��.�����R�G:��<$u{$H��HGR�G�n��e�j�t u{��< 5y���#�Q�G��.��s{$S}ʡ�@9��L9�(g	�C!Ɍs�ġ��8��8
�A�� Ɉ� q$ �$#��a��87H2�0H �$8H2�\ o$�
�$�
��!��7��7�@�H2�PH 

+	�C!ɄC!�p�m�
+I&

+��ĹA�	�A�0H 
I&
��� q$�q$0.�C�A��A�C �q$�qn��8
�A��A�C �q$�q$0��!�d�!� 9
 �A�!�A�0HRO��L9
��
$@�$S��!�@9�s�a�dʡ�@9(�C�)�C�H�
I�
	�C#th$	tX$���a�d�a�@:,H�E�I�E�H 
IF
	��"q�!�d�!�@;$h�D�i�	�C"vH$vH$��عD�Y�F��H`
If
	�C#�uh$vh$;,`�E�i�	��"vX$v ���a�d�a� ���
I�
����!�d�a�@;,h�E�i�E�C"�vH$�vH$���!�d�!�@;�H�
I�
	��"vX$vX$;$h�D�i�D�H�
�9�H2��H�
	��#ɴ�#�v�$��$��ڡ�@;T�D;Lh�I�0I2�0I�
&	��$ɴ�$�v�$��$���a�8�I2�I���$� [...]
�e���$
�\%	عJ�s�����$��M����$
��$	ڹI�+1��h�H��M����$
��$	ڵ}��$�h�&	�s�$hW"oi�s�$h�&I�NM��un��:I`
"If
"	�C$�u�$�u�$���a�d�a� ;L`�I�a�I�C$v.�d�!��:DX�H�un�t�s�$XW��
u�t�s�$P�6I��u�u���\'	ԹN�Q�6I��m�@��$
��&	ԙM�s��#�鞑�m� ��$
��&	ҹM�JD��
�d_��e�@��$
�\&	ҍ�bB:d�L:dH�L�I2��I@
:	�C'ɬC'�u�$��$���Y�M�I2�I`
6	��&ɬ��u�$��$��֥}(��&ɨs��I�L�I2�I 
6	��&ɬ�&qֹL�s��C��$�:�
�\&�P�2I��m�@��$
��&	ԹM�s��C��$��e�@��$
�\&	ֹL�+�+w��&ɬC'�u�$��$���a� ;��
;�`�R�PJ�0J�
F	��(ɰs��a� ;��
;�`�Q�0J2�0J�
F���$���!� ;��L;�h�P�J2�\(v%��$��ء� ;��
;�`�R�PJ2�PJ
v%��$�΍X�Q��(ɨ�u%��$��ԥ}(�0J2�0J
v%��$���a� ;��
;��
B	�C(ɴC(�v.� ;��
;� [...]
��E���x�fI��͒�wn���,	ޕ�m�s+$x�fI��͒�wn���>�wf�t�s�ܙX�+��4ڹY�s�$h�fIG;7K�v�%��$���`�X�K2�K�
f	��,ɰ�,v�%��$���a�X�K2�\,�u�%���ua�d؅Z�B-w�dޅ[��.�x��d�^�B/z��$�]��.|a�d�a�@��K at _�%�}a� ��K�vI�_�%�/��_�%��%�\��%]��rI�{�n�\�|.�DbkrI�.�ty��%�ֺ^i��%]ZkzId������%���%L�]Sxn�tSxn���'9��]���3xn��
��%�
��%1���a3xn�tSxn�0��rI��\���]sxn��
��%�
��%��.�D��rI�\ў�%�\��\ �.��a�d�]�K``�%�a�8�K�`�%�!� K a�%�(�l�ȲY�����Kdeź���Hyh��R�DV[���5
��<�]�d����"�M [...]
9�,af�ls�v�?y^.��6n�Ȋ �᥮p�z�v�?YA1�;�Y��*�v���SA�)��۸Y�i^C-��h�
+Q�D��4�o�f��
[�˟�9�]���&�[!��dow����oD�]���w���c�/�>67 at V�xr�x�h��9
�.�u����O��2�P�DW0��.rRI؍Y"K��޽���%���XC-����%��F�;��%R��[��
��<j��b&Y���~8�[[�Y"岷���Z��ݓH�]�3�a��B�	ӤhY�F���~C��4WK����.B�Z}��<�k	n�Hy�]�f��0K:��YF],	��X�a�Œ���%�QK2G�+	��W
u��㨋%�Լ�`�{%����K]+	��VұԵ�`�k%S�J:��V0u�$`�^IS�J�� S��S��)V	4�*�4�*�_���b�d�b��R�P�U�Q�UJ�*��/��U�I�UI]+q�b�d�b� R�@�U�A�H�*��n�d�b��Ѵ�e-�J2F�J�(V	�*��*�X%`ԭ�LQ�(�VE�J2F�J
�X%�Q�J:��Uu�$(Z�'�E�*	��Uu���� [...]
���R��R�SJ��bNIf�bN	h[�)m�;%	m�+%��ōж�Q�Ѷ,��:7J���FI���F	t[�a.z�t[ָɂ%�mi�]30�$�mq����8��(�t�(�n%�
�$�
�a��7���7��������>Z�
��a��7���77J�F	x�(�|[�(�o�+%�mq�$�mq�����Q�7J2�7J ��F	�[�(ɀ[�(�p�%nq�$nq��-�� �ŕ�D��W_A�ō��
+�s�a�d�a�8�J 
BI&
B	�C(�q%�q�$@���d�!�8��I�
>I�
:	�C'�r�$�r�$PF at 9t��9t0�N��I2��I 
>	��'I�s��A�M�I2�I�K�M��&ɜ�&�s�$p�$s��a��9l�
:l@�N��&ɤs��a� :l�
:L@�M�I2�I ]��f���$t�$���a�d�a�@:lH�M�I�M��I 
:I&
:����a�d�a�@:�I 
6I
6	��&t�$t�$��ҡ�$�a�@:lH�MrN:l�L:l'
2	�C&ɤC&�t�$��$����@:\�L:d'
.	��%I�C%�t�$��$��ҡ�@:T�L:TH�J�pI2�pI ��$��$���I�I�s��#�ᗑ�L� ��$
��$	�
��J:3I:йI�s�$@�&I:7It�� :7I:йI�s�$H�&IG:�@�tn���$�H�&I���cs�c����$H�&I���l%H�&I��M� ��$
��$	ιJ�PI2�PI�s�$p�$s��a� :L�
:L@�I�0I2�0I 
*	�s�$q��a��9L�'�s��㜛$p�D����$
�\$	̹H�s�$c�=���{$�9�H:̹H��#	̹G�1�I`�4���k$
�\#	ʹF�s����k$A9�H�r%\�|�]�
�s�$0g
I��k$Pn
�)�H2�H�
	��"ɘ�"sX$`�$s��a��9,��9,8�F��"ɜ�"�sX$p�$s�a��9,��9,8�����n
�\"�rX$P�$S��a�@9,��9,8�I`�5�s���9x
��"�0�I`�-���[$
��"	̹E�s��Ü[$��Y�a�5��9�H�sn��J��
�H2�H�sH$��$���!� :$�:
@�C�pH2�H
t8$��$�� [...]
+	�C!ɠC!t($��$���� :
�D:'
	�� ɤs��a� :
�
:
@�A�0H2�0H 
	�� ɠ� t($:
�
:7H�
	�s�$c��a��9
��9
0�����1�}�@�0H 
I
	�� t$t$��ҡ�dҡ�8�� t$t$��
8�A�9�A�0H�
I�$`�̡�$�a��9
0�Ar�9
��9
�
	�3�$C��!� 9H��G`
���Ɍs���?��G��G`
��CɌC�q�#0}$3}ơ��8���8��?��G��G�qn��8쑌8��=�G2�G`
���
Ɍs{�a��8쑌8��>��
Ɉ�
�q�#0{$C��a� 9�
9� �����!�H�
���
r�#r�#@{�a�d�a� 9� �>�!W��@{�a�d�a�@9�0�=�1�=�G�
�H�
��C�s�#�s�#p{�a��s{$s{�9�<�G2�G 
��C
I��
u�#�w$���G
���
I�C
u�#�u$�uԡ��:ԑ�:�P�:�pG2�pG@
���
I�C
qԹ9�0G2�0G@
�H��͑un���dE��#
��
	ֹ9�څ�`��#�:WG`��#
��
	ֹ9�ss�c�[�:7G�un�t�ss$X�����Q�V� � [...]
+��F*�2�4"�5"��]�Pkd�����b�eu�ڈ�[��H-��K��7��!k����#A���̫52IǰF��j�YPkd��n�`u8/�
���:Oa�HY.Jj
��H�����mYM�7"eY���$u�|�7"e�(�ы�.&�6"U�PB�+y���ȷY0\�o<.sh#���A��P@����
	�F� �f��62���F�i
�{�k#��k�F�
7gt�C�s_��F���f#��LjO�66�7�ێ62�e��y#2�7�ü����lv�}�c�QG	��D��Xx�M��v�Ѵ91���i#EV�OM�G\p�6R����6"׷����9�7R���=g��2'm�ؒ��F���B���Ѵ���6�A�oc�H���h��[�H�ޘ���uz�7�yͱ4oD��_�IE�X#�Q���Q��(���
E��H#pi$si��5K�F2K]	��6,um�c�k#�R�F��[#
L�	��50uk���[#S� [...]
o�1�H�hh#���F
�h#����8ECq��6�0ڈc4�0�7�1�ވSm���d��6D�F�(�H�(�E�����3o���P����a�4
4�
k��H"\H#F8wF�o�$�!�8�Bq��4��҈�-���H��xCoh#oh#�
m����H��tsk��5����h�mX#mh#�
o��d�ፀ6��7��6��F��H��t�_�t��6��5ݰF��k#�nh#�
m���d��|@7��6��ڈ�-��[x#�o�8��q��7���6�x
m���H�[h#η�F�o��$��6�|
o���H�[x#��F
p��$��6�
m�	�H"\h#N8�\h#�p�8��q
7�n�i���F�p3ֈnFI���F�p3Έ3n�I���F
r3҈CnFI���F
r3ֈCn�I��]�r�k#Pnvm$Snvm��
+=����H��������s�[#t�[#�nvk��n�d�ͦ� �yk+�O�ڢ� ݼE��R�F �l�H������]�s�k#�s�k#pnvmΡ�$�a� :�@�6�I���Cth#t(�mС�dЅ6�
m�A�H]x#��F
t�4Ѕ6�
m�I�H"]h#N�m�I�H"]h#N��F�t3�H"݌7b��]q��h#	t3ڈ�nF)aq�6�@7��8�f�'݌6R:w̼'݌7⤛�Ȼ�OX#�t!�8��1҅4�H҈�.�']8#�t!�8�Bq҅4�H҈�.�']X#�th#�mҡ�dҡ�@:�'
�H&
����tX#�tX#�έ@�5�A�6��F�t�t�"�B�X�@(��ɤsm$H7��t��t�sm$@��H�ε�
:�Ftn��\�@��H�ε� �k#
�\�ҹ6�sm�#
��C�tx#�tx#�oҕ��
�uL�th#��9�8�6�
m$q.��\x#ι�F��1΅6�
m$�.�]h#%�[�@ڈ [...]

�N^�72�y�H��u@�(od�[D��@Ycx#��V�Ml`,�od����
v��qd�5�[G�Z�&�ȹ�΀8R�X����}m�H-
�u�9H��đb#D�#�֯�6&��%߲6q�X��h�I�Fő���G���^"&�����&�F'��N����?�H-kL���k�c�F��N����Ml"∜ �qDγ�6�8"�ၨ��^t���E�
�{#z�fY��H��
x#���z#r�K&�{���jz4�)
�G�2��n7��^BۗG�ۄHR���oc
6�0�)J�7"@��xe��F�}��D�W	ж��>P�9ҡ�Ց@��#�RwG:��;(uy$P��H�R�G��.�K]
�,uw$�j�H��ݑ���#�w��d���S���<���<P�G
��#��# wd�e�� c 5�j�#N�pGQ�
q��;�8
w$�4��i�#�ӐGNC
1��8M�
I4
y�i�<�0
y$�4��i�#ӐGLC
q�"�8K�GJ�G at iڃ���#��#�R�P�;�Q�<J�G@��#���#NR�H�;�Q�;JqG��t(5w$H��H��呎�&�H]
	��<ҁ��@��H��ܑ���G�
	��;r�Q�L9�(�>��G2��G��	$0�$3��@�H��G@
��s$#.�G\�#���G��qą?�C I�
��	�@b��I|�q��?2Ī~�G��q��?�x
$�-��[�#N��G�B q
@�
�$.#\�#�8��D�H�p!�8�H�B q
@R�=�G��p!�8�B qą@��@��>�q$�q$�8��?��	�C q$�q$�8��?��?��G`
�Hf
��C r$r$P��!�d�!�8��r�#�r�#P�ᏜS�$S�ʡ�@9
�L9
(�D�H2�H 
	�C"I��!t8$��$�.
�1~*�
�1~��
�D�pH�t�8�B"I�
��Q�� [...]
�˻����I
vx$��$���!� ;D�
;Dh�HR��X��I�
"	�C$ɴs�$h���/��H���Eh�
IЮD��h�"I��E����$
�\$�u��:<��:<X�G��H2��H`
"	�C$ɰC$v�$��$���a�G��#ɬ�#�ux$���	��$�X�*I������%�P�.I��e�@��$
�\&	ԹL�s�$��]�@��$�:�tޡ�ԹK�pI2�pI 
.	�C&ɤC&�t�$N:\�L:\H�K2����a]�$�n
�)��%I�
�d�t�\�!fE�%I���8:��	��Q7!�$�M�$ƺ	��Y7�$�M�$κ�I�u!�$օL�
��Y2Ib]�$κ�I�u!�$�!������7�$��e'
.	��%ɤC&�t�$��$�nr��Y�.I��]�u��`.�s��C��$�:�Iu.�t�s�$P�2I��e�u.��:wIu�t�s�$X�.I��D�ܱ�$��֡� ;|�
;|`�P�J2�J�
B	�C(I��'v� [...]
�̊;Ē�;��
^	�ڵ��
b	�C,�w�%�w�%���!�d�!��;�x�X�y�bI���xgbI�;K��y%A�iK���0ڹX�s�����%N;�h�W�i���~��ޘW��J2��J�
b	�C,ɰC,v�%��$���a�W��J2��+�ux%���ua�d؅Z�B-w�dޅ[�B.�x!�d�\�B.z!�$�[��-|�d�[��kn����%�}�-q�5���rI�_�K
M.1�5�$0��=��=ܒ
���5�Y��[�>�[wK�kqKr^�h���%���%9�u�ijZ���pK�
r	Sx�%L�!��)<���<�a�$��!�0��\�

rI��s�$f��>l��n
+�����-�9<wK�9<�Kb�咘�s����s����ݒ���-�=wK"�s�$�=wK2 qK `�%0䒌��K` r	

�$C0�� n	
�$c0�@n	$
��
�����<�(�%:�4��K�,�
v����S�Kd�JB�)�ӌ]"Ų���%2��,K�%2��K�u���k�a��dڱ�\"�m�K "����v
�ٖu�����[3�rI-/s[#�r���H'p�D'p�)������"*���"�%�\��-�q:������2�����v�؋%c�߲�ȴ�ܹ	�D�R��{%:�jN�z%:�*��{%:c�r�+��U�d�J��?��K�]p�D�lm�K�5�= ��|�����S�\�9��^�
�m�^���޹н�Z�n�W"孹����Z����kD��
k�Q�N�����mv��J��-�
�4?S
a�H�՛��d�%��6b�H�?�5�9�6k�*�srn‹Z%2!9
[h%��e1
i�����
�V"�
{X%�/��*�e|t�Yw��b����mX%c�3V�L�J\�U"����n�Բ����5�bK��J�5қ�J���l��@H�*�yI�Ȃ+����I�P�J�n�B�*��VI ԭ�@�[%��.�C]*	��T�1ԭ@jRIpԥ���.�G]*	��T�qԥ��K%R�J:��T u�$@�VIR�J�n� R���J
��$��$����OF�I2F�I�(>	�'��'�.�@Q��LQ�(�B�C�$C��� Q|�Qd �:	
u�$#���=�-BT&�E&��$ �$#��b��P�I2A�I (:	E'�E'q�b�B�&�j6I�m� ��$
A�&	��M u����$��
���d~�M�t�$��6�9?�I2ݰI�6	t�&�t�&�nf��6l��6�I@2	hC&�h�&q�!��6�I2ڐI@2	hC&�hC&m�$��e�L6d��2	`s�$s�m��MְI�^$q�ᑀ5<��5<��G��H2��H 
	d�#�d�#�l�$��E�L6DȆH�hs�$�
���@6<�D6ȆF��H2��H`[ڇ�D%��6$؆E۰H2��"mX$�
�$�
�����64��64g	l�"�l�"nX$�
�$�
��a�@7,�L7,��	pC#It�"�nX$�
��nX$�nX$�
��a�d�a�@7,��E���D�H 
I
���!�d�!�@8$�D�	�D���N8$��8$�D�H2�H�
	��";��!�?��G2��G�
��s$3���8���8��@�H2�H�
�C$S�� �?��G�P?�
��CɐCri~k���99� �=�G2�G�
���
ɔ�
�r�?uﶻI���=�����̠2��;��
m٠@J�!C�`�
���wE�oEF}�C��[2$B ;����qU
bE��@9�J9�Q{�a�T�a�@9�#@{�B{�a� 9�
+9� �>��G
+�G�
���
��
�H�
���
�r�#�r�#P{�a��!�@9�(�<R)�="�!�@9�J9�(�<�G*�G�
��C
��C
�r�#P{�R{�����' �=�r�GD9�������lv!}���CN�ȋr�F�r[�8(��
r�FrGrG^��8���8�䍼 'o$)'o$)'o�RN�GRN�HRN�ȋr�F�rk*
h�ȋr�F�r�F�rmuP�r�F�r�F�rn��'k$'mơ�Tơ��qX#0k�2k�a� 9��
+9� �5�F*�F�
���6R�5�F`
��7��5�b���d\X#�8Y#/��I��I�����4���4���4�B��'i$'i�8I#���F�p�F^��4���4���4�"���$���$\�<�ȃg'��k�Fqa�@8	#�/zm�*x�h%
���q�"q�" _��T���8��0R�0�F�8|��8|�/��E
+�P=`
��C��C�qeJd���$�@8l�-R	�-�E 
�He
���.���.�B�tkW�
+�E^��-���-���-�B�l�D�l�D�l��d�$⤋$⤋T��I��IƵ���e�T�u�"0��r}�6bB��r]���E
+�d �%� �.Y�B���d �%�T���E`\�,�d�
+���"�u�"@�K���E�
�r]�H�\�-���r]�H�"�\�'�<�J�~������! ��T�uy"@��Ibw�<�
+�.O�u�"@Q�BQ�!�rx"r�D`
���'R����D@
�HE
��+���@\��CrX"@K�BK�a� 9,�
+9, ץ�@�.M�R�K�zX"@�����D�\K�uY"�q]���D`\�%R��q]���{��SL1O�q}�ypG\�%�8,��8,�%�����pX" N�H��|C�oH"�o�D�7$�$R�$ߐD��H��|C�oH"�oH"�
I�a�T�a��7,��%�߂��&?��T���7���R����C�~H��� �D*�D����R���C�~H
j�Cp�!p�! ��#�q9�9�a� 8�
+8� �
�C*�C 
z�C��C�C 
vH%
v��q�!q�! ;�a�T�a��8��
R�
�C`
v�'�C*�C`
v������r�!P;�`9�!��9䐊9�!�
r�C��Cs�!`9�b9�!��9䐊9�0�
�C*�C�
v���o1D����B*��B�
^HbN^�
s�Bs[�80'/�9y!�9�!ɹ-'%�$�$�$��9y!/��
I��
I��
���ґ������✴���ڇ��A
+I̅��k����������򢜬(���B*��2��H+�a�T�a� 9� �R!��B�
VH�
V�C
rh!r�B`
V��
+�d\Z!ri�@��B�\Z!�si� ��B ]Z!u)����B�]J!�vi��w)� ��B*�B ^J! /��ʼ�B�^J!P)�R/���R�K+��+$�w�B�}'+�����w�j����j���l� ���꿪� �W� �}��꾆��W	!9D'!�5D'!$��$�0D'�5D'$��ԝa�N>H
��ʑ#t�Ar�N:�k�N:H�Э}� !����$���l�
��
���
�ct�Ar�N6�k�N6Hv_��d�N:ȫu'
�֝l�l�����|i�@��A*���}� �/m�
+��A�:�K
��/m �6L���
� O���J�A,�ڝ2���ε�H��Yf��
b
��Tﻵ�
+b��:��X̾ȸ Ͽ�k�
b�~Z�� ֣<� �/p���
��{��1�
�;V�A�����.�<�~nx
�� ��
���I��׬�|H��� ֓�N.��b�θ
b=��R�E
[� ���%���pÁ� !�b6))#�~b
(����"������1��L#�G:�B���B�
���M!��f"*H�~��~�b��a
���=j�	!v�� ��U�9-��/�߸b�!k�f���X�#��]?��$#���£�ؿ���+!��<����X��\Zg����B��
-��/W�<�m��F������2���bo��l�b��5lpB�5�[.h⯤��-!'��XIN�u�o9!���ƥۅ��q)�D�C�����9c�wB�[�l�ظʱ�r'�bϧ'�3�8"���>�~C��f�78!�ok���8��%�X�Z�H!��+��,*�Y���	� �� �He��@*#�JI�Jy�TFH�TFH�TFȋ�2B���$M���h*%$i*%$i*%�ES)!IS)!�TF�
�2B�2B�2B^8��8�N1B*N�B�)^<�
�<�
��� S��S�`�L�B*L�B���X�RY�K���R���R�P�J�B*J�:@�� [...]
+R�@�HQC
+H1C )f �R9�G1C�(fH)f E
I�J
y�4�8*3$9*3���0C�2C�2C^����
3�EQ�!IQ�!IQ�!�
)�C
�q�!b
^He
^�Z�C
�����B 
^H
^�C
�pC*�C 
b�C
��C
p�!����7��&/��
�t���B�^H�rp�n�!n�!�
;�a��!��7���
R�v���r��
R��
ߐC ���7���
߰C*�P;�z�C��C�p�A�A�!�@8�B8�! ?��T��@8��R	��D 
�H%
�����C*��C`
~������q�C@
~He
��C�q"��)�C�q�!b
vHe
v��
�C*�C�
v�����s�!`=�r=��9��9�8�
"�a�T�a� :�H�
RQ�
�C`
vHe�P�#�pD*�pD@
���#RH�"�PD 
�H%
��C�t("u("�E��T��u8"�G����!��:$��:$P����D*��D@
��C)���uX"�K��K�a��:,��:,X�&��D*��D�:Y"�K��K�a��:,��:,P�%�D*��D`
��C�`
�Ha
��C�pD*�pD�:X�"RY�#�pD`
�He
��C�uH"�uH"�I�!�T�!� [...]
+��E 
��C��C�t�"�]��]ҡ�@:|�J:|H�/��E*�= 
��C��C�t��N�H��8�2�PF
+�0F�
�������t2Ft2F^��1�����N��
tRF �������d�$�d�$�d��@'c$A'c$A'c�E:)#I:)#I����J:��B:�H�0"��T��u�"�]��_�ዀ:|��:|P�0�F*�$�@:�P�0RQ�0�F�:|��:|PWr��F^�|w_�E@
�����C�uX#�k��N���uX#uH#�i�!�T�!��:�P�4RQ�4�F@
�HE��H�5�d�TС| :�@�6RA�6�r
�H%
��C
u�#ux#�o��T�ፀ:�X�7RY�7�$��:đ�:��N�������tx#�o��N���tx#t�#�q�!�|�o��mС�ta�T�a�sH#`N�H�
����rX#�r�F�
��C��C�r��Pm�Rmʡ��rX#�rX#Pk�a�T�5Y#P���rM�H�\�:����]�;R!��l}9��(���5�#P�I
�rM�H�\
u [...]
+;
`�A���ARa'�$a�-,;�$��`'�$i'�$i��)���������
��d�$�d�$�d��h'�#i'�$i'��E;)$I;��B"y�NI�.$�d]�N�Y~a��ɺ�s��:9$/��!�u8$����n�U��C"uH$uH$B
	��!���!u8$������᐀:
��:I$���!�|�.
���TH`]*$�]$�vi�w)���H*�� �xi���4H*�� �z����TH*�PH�^*$�/�J�TH at _*$bIe_$�/
�I�I��d�d[Oɫ�'�$�z�m�ؓG�j��#�.mx$٣�GR{�Z׈�4���J#yuhC#���4�
��F���F�Cw�Hr�N
�k�N
Iݩw�ȝ<��ȝ$�
��H�#wI^#wIr�}0r'��5t'�$��؝T�:v'�$��d��؝L��؝L����$ɖ�L�WKO&I��dKO*I�*��&	�K��0M�I�$�L�b���4I*S%�����TI>@�߲I��?�RI���M����d�yf��K��8j�$����I��OB&�l$e�Lby�g8>Fm�$���h`�L�9�4I�#�2]V&�s$Od�$ϑ���$y���$ӓ�:&����ZV�:N6©��Jb��6�$���k;�$�7��_��"�m��s�$���a�f�D�'fg�Hb�I��@$���sd��n�w�V �܎�%�X�Ņ0I�_aiK�$�R� 2I�5S��o�R��yp�I2|���&����#�Į���a�
_骧Ib
��|�$����i����%�$���X_���� [...]
��\&IYc,M{�L�MU�1I�p��0I��e��H�Y�\"�Ve2�I��Я%��6Zm�S����GX��o�T��� RT@�KRA�KH�I )2I%)2	$�L�$�L�H*�$q&I�T&ɋ�2I��2I��2I^4�I�4�I�8�J�©Tp*�$q*���T"I�T"	8E$�8E$��$�������HLI*L1I�)&	0�$�0�$�2I`)&Ie)&	,�IJ1I*J1I@)&	(�$�(��2I �L�
+RL@�� �$� �$��$����4M�4M���p4M��h�$�h�$�)��)� RD�
+R�$p��b�T��$��$`��b�DE$�I��H"	E$���$M��0.U1.U1.]�¸tI�8�$"\�$�p�$
2	�C&I�a� 8L'����a� 8L�
+8L �IऒT����o2I��L�B7�$�
��!�T�!� 7D�HR�H�I�"I�&	|�$�o�$�ogVW	�a� 8�$�o�$�
���$�|�$�o�$�
���

�a� 8L�J8L����$���$�p�$���D�K�D�K��.M� \�$"\�$�p)��p)��p)�¥H"ĥI"ĥIR�&��&��&Ia\�$�8D!.E�¸IĸIĸI>�&Ia\�$b\�$b\�$�q针q)��r)�ʥL"�!��9d��
&	��$s�$�s�$p��a�T�a��9L8�JRA�J"�a�@:L��:DX�H�I*�$��:DP�HRQ�H�I@�D�J:LH�I�0I*�0I 
&	��$���$u�$����N&	��$u�$uX ���a�T�a�����@
&IE
&	��$u�$ui��ui��ui�֥I�K�D�K���.E�.E�.E�ºI�:L�.M���4I��4I��4I
+��$	ԥH"֥H����IĺIĺI>X�&Ia]�$b]�$b]�$�u针u)��u)�֥L"�!��:d�d
&	��$�u�$�u�$���a�T�a��:LX�JRY�J"�a��:L��:DX'��!�T�!��:D�d�D��$�$�B$I�I$y�N&I�n��b]�$/��$I��$I��$y�N&I�N&I�N&�
u2I�u2I�u2I^�����I���I�b�L�d]�C��I�b�L�d�L�d]�.K���a���0I*�0ID:D�.E�B�ID�ID�I
+�R$��$��$)�K�D�K�D�K���.M�@]�$B
"����n����M�D�K��t�$�t�$���[��T�� :d@�LRA�L�$�$�$�,��$I��$I��$y�N&I�.L��L��d�$�d�$礒�8'���$I��$���H���H��
���9�$ɹÂs�$�s�$p��!�T�a� :L@�IRI�I�0I 
&I%
&	��$�t�$�t�$���a�T�a�@:LH�IRI�I��>�t2I*�d��9L8�IR8�&�8�&�8�&I!]�$A:D@�HRA�H�I 
"I
"	��$t�$t�$���a�T�a�t�$������!�@������$)�K�D�K�D�K���.]�.e�.e����I�:dP�L���$u�$����N&	��$u�$u�$��ԡ�Tԡ�u�
u������!��:D��:DX�H�I*�$��:DP�HRQ�I�0I@
&IE
&	��$u�$u�$���a�T��$�t�$�N&I [...]
+9L �I�0I*�0I�
&	��$���s�$`��b�̭}�0I*�0I�
&	��$)�K�D�K�D�K��`.M��\�$�\�$s)�s)��s)�ΥH��w&�@�&I]�$]�$]�$ti��R$�R$)�K�D�K�D�K��ti�ҥJ"ҥJ"ҥKRX�.�X�2�X�2I�]�$�
2	�C&I��$v�$������a� ;L�
+;L`�I�PI*�PI;L`�IR`�H�I�
"I�
"	��H�I*�I�
"I�N"�
v2Iv\�d��`'�$i'�$i�1eQh'�$i'�$i'��E;�$I;�$I;�$/��I��$I��$y�N&I�.�!څI�L��]�$ɺ�=�d
&	��$�u�$�u�$��IĺI
+�I��I��I
+�R$��$��$)�K�D�K�D�K���.M�@]�$B]�$u�$"]�$"]�$�[&IA�RIĺ��v�%)�[.�p�d�n�$xK&�R&y)�$��$�zi���4I*�0I�^�$�/M�J�4I at _�$����/U�/M�&I�"I��$�d[O"ɫ�'�$�z�65�$��{I�K"I�h��W�6L����$��L�W�6L����$ɡ;�$��;�$9t'�$��d����d���]tor�N&�k�NH���$ɑ;�$��;�$9r���ȝL��НL�
��I�cw2I��
&	cw�$��a�Ա;LuhIh�!�Ԗ
"	-=DZz�$)��$��IR �L0Mp�$��$	�H".��@p�$��I��%������&�m5���{�\y%��c��L�~^V���+��<2�|�l�
�.`�����V��~��|��_
Wj%�>��@|���}���?2�$���aQ
�#�(y�F������Z_j�Xk��|��P�F�Oq6~�|3�I>.	1��� [...]
��
RK�3c���v�۞<q�ds���R����K���4�B�\{ӎ��J%�1�;tǪ?�fVl�~�O��0%\0y������0��5���U���m��w.V�ç?��J
�o�^��<�qc�V/��d<�e�Ek,+���:$�V��W�<�t4l�X�kĠk��l�_�v��e
�!�tˋ��R%�F��ud��_G,")�ľ��C�abƳ��u�,��R1�U�l�C���7,�X���4��b��p�b�����k��|���h�"7Ll,?�s�d�T�4J�7��a�tW
�e���]�'ZF(&��m�������䞊�mc������[�~^�����?��?�嗿��������m*l��qQ^𕋒𕋒��\�+%�+�E_�(I_�(I_�(/��FIۜ���@0
�T��	fa��&�,l�Y���Ia0
��`�(���Q�
���,%%���b0Rʖ:JB�B%!�BJ#�E`��$0NJ)�'%	,)%���0Z�]*_� [...]
+�r��.�8�r��º\�D��5N�:9Y��5N�:�)I:�)/�INI�a�$��S^��O��LIΡ�TΡ�$�pSu�)/�a�$��Su�)u�)�:��d���0Tu�؉X�b'u�؉P���u��IA].T"��b'��\��.�:��.v��I�
��`���T*�d��:
X��Ra���PT�
�J�
�
+�CQv(*v(*�
�
+��P���Pw*�C��C�IQ�v(*w(*�Eܡ�|�E��Eܡ��;��;�C�a�T�a�@<
���R����\J�W;�;)���N��\�D���N
+�r�!/�;�r��ż\�D�CRI�a�������CTI�a���'UeKI%���R�����CSI��SyAQ%�����CU)��TI衪$�pU^�CVI��'�^�{R�Ǻ'�^�{"��'�z�f�����rٓB�\�D�[���'�z�*�
�
+��U��CV{�*`Y�bY�a��=l��=l�����U*��U�=�*PY�RY�!�@=d�J=d�����U*��U�
�
+��V��
�J�
�
+��V{�*{�*�
�
+�CV��CV{�*`Y�b_칟�(��\��`/W>�r�a/W>)�˕O��\�D�˥O�r�a_%�����
�JbO�JRi�E=��-}��=	+/�m���^+�zRV�ؓ����%����V*�$�,��ZYԓ�򦞼�E=�@�z,�R��(`�%P�
K�T�|	�c	a�P*�X��.�=V@�ؓ����$�]��=y+�=y+�=�V^Г��Г��W*�W�
�
+�C\��C\��V�
�J�
�
+��[�zx+�zx+Pq�I\��C\z�+@q��I\yAO�JB/ĕd�ĕ�$��<y+�<y+/��[I��[I��[y1O�J2�f�$�Je
���<-��X�"�EP@
���<VA)�c�'ue!O��y�W�,慿�F��-ՕD
�JE
�J"y%����b
�J2%���R�����C`I�a����’���P�\
�@/WC�r5A/WC)�˕L�\
%������b(���E@��P
+�y, ��"�䡰�<�
+=�'�%�'���<9,�<�7�'���<9,0O
+K2O
+ˋyRX�yRX�yRX^̓’̓Ò̓��
���
��^���
K�

��a�z8,�z8,�

+
�Ca��Ca�z(,P��R�깵�s�A�\�P��P�\E���P
+�r=Q/�C�rA�E�\E��bIꡱ���Ȓ��dIꡲ���˲�Œ�Cc�ؓƒ��cI�!����ɒ�CeI��ꡲ$�pY�z�,/�a�$�raQ/F)�caA/F�X�0/5�ra�`^��R��뢈yk��\�@�E�Cf�z�,�z�,P��a�T�a�@=t���R������@=t�J=tQO6
��f���fz�,@��BO6
�Cg�y�,�y�,0�桳|2��2�桳���Y*��YD<l�'����a� <l�
+<	-�.����˥Q
+�ri/�F�ri��\E�˥Q�\e/�F�Zx-/��$�ZxX-/ࡵl-�;���;��
JK��<��
VK�� OVK��%y����
bK�.�H�r��»\#E��5R�\#�/�7Y������)�x�D���v��%R
+�[z.��ٸ 
^K%
b
�Cl�x�-�x�-��a�T�a�@<����R���"�!��<Ė�<�����[*�[�
f
��l���lz�-@��z�-z�-@��a�T�a�{�-`��r��!��=Ė�=�-p�ҕ#[!������*)�^��"��*)�{�J������{�L��^��"��$��[^�CoI��$�\^��p�p[�{�-�{�-�=��=�-o��oY����
��=	.
|2\����(����r)���R*�X.�\
+�c��
+>�:|,�"�ZJ�� �܅���R*����P\{�
M��
�Ğ
�Ğ
��一=$���R�'��!�@=$�J=$Q���T��@=
���R�����\�
�K��$����\>���K�^J.`�
s���K�;.�[�>W\�W~28�KE�+.��_�Rq~��T�����r�TC p��R�륈�k�!p��Rh�K���Z/E�S�z)�`Z.���\^ DtY
@�.�(��� ����r� ���Z��\V�7}�x���{�a���T����R;������\�5�'��=�'�%S�}�p_��pJ
�c�F�d�3���)u�Ok曭uS4�Dz)u��eS�3��,c|�o� �/��u�Q>�.�Q>�.9�'�%G�$��F�$�dW�K��d��Z�]��'�%[�]*�]���] a�.��)��B�]b*9X��K���h%��i�T��
�t�i���O���+1���'�����w�w�~��ӿ�����+����/��_���������ǿc�'+�,�����|M�b���%�l?�����=��������߶�����ϣ����%������H�/��_��?����t�
v��3&>����{
&�����c���Ok=�&�_��֏����S��x�����fkhݑ6mi߿F캣��,�i_�����~
�=��	��S�m
벎��)���4�2x^��������˧;"Ӧ��-&�͓9���w`��mӟ��xYή- [...]
{[,���C.�W��H���s�l��ʼ�� �>����rͺ
�3�Y�q�>�E{�r������.���k�.�=��y���p�_O{w����
+^�O�I�J��9���h������v�c4G��J�
Qs�gilNg�Y�ߓ���
�s*
m��Q�������y!���
����
&I�b-����J��:���W:Z��W�Ԉ�

ʠsH�ش�όy��3�X5p��r�qsѾ�}b���\��
����vW�E�|{G�h��-/�eP��|]�]h��&!��_4�h���r�,3ሹ:?�=dG.�n��q�.�=D���E��H;�헞�r�<��ҁuўS�=��������9�
��f^4۞1��׿�����
b�v��형��z|��-*O7i���7^Q��������<�Mq_6��n��,W�k�>??�,��yw}�No{�r�^��b��������>G2���s�����_�ܮ�����m�H��.��>|
+���|uK
+j� y>.?Y�����E���}�o��UyٜQ���v��g�l�#أڹ_��J ��{qݬ=3���n֞�A���gl�]7k�\����Ï.��g�\l\6k��^pg]6k�
_�/.�[uټA�
�y�&X�y��y1t��uܵD�]6�m�O�͖��'	)�P��rٚ%:D1�(
+�Hg^6o!����Y
�Z�\6o!٧Y��a�-�#\7o"y���n�D��uݺ��\7o#YΣ����������e�����o������?�wO�"읯�~�7������O����������������׿�����a��O�����������~_�{Z?
�izy&ұ[��9�������lg��G����}���o�s'������6�<\8��������k�#ol��=O����B����h�������:
G���i�XG�{�d;�����0:Z�o�C
+�6���������S!w
#d#�_����K���(�=�c�q�ڠV����G�K
��mD��p��9��� ��4�>�m^(
�`�=w���
�(g���
�1oB�����w��K
ڰ׷���~%�u��Ջ������ӮSP�Ȃ�����C��r�W]Im��#С�n�څ��š=�qp���"�.���S��>O�׽����gnQ���NѼ@��~�^�̓
g����Y�:��ҥ,�G��
]�ݡ���d���#8�
Pk�6��vp
�'�DpZp
+*�6PD�@���Ϧbw��R|�Ǽ,^�&~����b�-�e��<�g
+^[�>�n>������>	�yz�S<�0lN$����
>y�L��%]�|�/] 
[-�68A�4Gp����Nmd6~o�o��f��4���j6 ����?.�
�Z�.��0Dە;7j�
�W�
q ���{�j=UE8�\�^`祙�*���~������]�s�����܈�����'nӓm{��?���<��#�;p�W�{��!�d���&�&Xm��{��b6'�{{pi�vj-qH���q_nG��"-�}�/�YϵO
��
���D~�
$8-�,����k��;�X��%r�<�EȮ�s� ��
�>�e���kw��"l��7���gy�=�7��n�
�3��]q��SִY�3_��5�[���v���E��z��x};�Z�k�B�����{Z��RN��ljy�$�;^<�x�s�`�e�A�Y��w�Oa����m��������|�'�n�~o�_���&�%pͼ��d�z�l�k�O/Փn�}����y���GdV�wK�n'�B��
Xئw�'ʏ+r��z�K�t��wk?[gy�+I���Q

�ja1��
���Q�;�/�C��m�}{5����=[Dl�Ͱ`��?~ov������
+j~]N�F��^O�f��v�"u/5B��g�-(w���}�,f�<�ט��n�
<F3���y������
��6>�-�x�O��u���i��z�,h�l�O�q(�3���}Fͨ��U���
Z�B���"y������U��łZ�_��>/�W����c������q(x���Y����2ym������1[� �'�k��,�l���!��:���RS��'�#>��M�z�Ovzm�����߃�l�{?+�C��;_�^o^�{ȣ�a�����
oO7�
lS��`��(�U6�g����Q��}mx��:1�H��؎]�z�y����+�
�Zs��G�u�o�������޶�?���p���8�+jD��1�$^���>)�S�ݯ�^p��ւ8��þ�jEyj�zɶqr}�-?vbg��ԯ�l?�8g�Ϫ��{g�A^/�FC޳�~��}�Tg;��WQ!��e��e/��)�I"�t�t���V��S;������U��@�q�
+nc���9���O�	��E�҉]ǿ�w�{x�}l8Ԁ�h۸��viӛ3E|����?�
Nj�?op����-��ck<&�
����|��z>&OSH��i�E�ܶ��ڇ^�k�z{q[|�l@4.@�	n�q
+Ǣ<}��:J����z?���s�
�O��5�
��=>�3�T��oq������)��XoϮ�r�
�?��ϝ�{��r���Ə//{�-�݌`H�~�w�f�v���d%��M��{Z����8����N�V�a�59U��~U+����7 �.^��NpG�O
Ϩ(
�s�Գ��
+f��c�{�n\�1��7H�+{�#�E�{k~�`n���w��~�ro{� V���
�5��&�9y�769�v��;8�ѥ[~��p�ل}����![#�6�S�y'�t
gyf<#.�\�ԉ��n�
�3;��d-`+6�m��F�.�˟
_�.2<r��R��,�/�c���R*���b^�
sys�DMK�/sTk2R�a����lM�|�������B�]���D{�����`c|�S��9_�;�*��^.���n�q���}��]Y�
�z���
�Ϸ덫߭�V��3�~�>���)��>D���n�¼e� q
�^	��%�ɋ���1/U�-.��G�
�f
V+�A߁�6��Z�>�ݷ�ޤ8��*=D��~7+:�������9�zYQV
�|mF�-��.���������
�
�\t�g���]1��1���<��O��A,
��м�{m1�
����q\�\?�1�/�����8�h�X�ܹ
w��6����e����Yz�bf�hƶ1 5G~���AQvw\��b�.m(��ZPƦ����g�f��4�ո����;��.�;�`e@ݦ�@�a���k���L.|3��k���
i����`��~^`����^���
5gX�o�%��ڬ��+���y?A�	����O�dW��e��t�·���
�M��TB����1�����5���6��Q�}M@��~
�kf^�%l\vu���
����W�٨�};����F�O�|��t�����"��|����
Q�~o�
��F��4�fU7.���Q�_-h��628�h�
��}���������0���oԳ�ҭ� ?���˛Q��b at yRƟ;��I�a�>�gAK������
+����~����a��.6��e�X-�a�
U���#_9��N�_?A{�/�=�Kd�	�J�E�U/:vO�~�Ng;^��,o�g{�g��]e\��|ʯ�e�Y�Տl蒪�X4��வZ���b��'أ���γ�l�3~�>%��@�w?����
��z�0��z"�~L�=�
t'$.��._I���
����ү��vs���
�>����S�@��nݱ�\��Oo����V_���R���w�'ҫ

~Q��g̈́�ϋ�6}:4Q6�7�U&lC��ū�P�f���W����tq�6�� ����ў8�c�jSLc
���M�цK
+Ǐlk��M��e��s�B�þ�>�o�(�45\<�'чP�5 n;t@-IҺ��g0L���"��s<��
�n�?ߞ�3��6b�g؇ӝ
�y��۰)���w��1X0|��>���qX6��ŧ�{a��|f���n�&�1kת�
�9��#�o��X��{6�Ѫ�6�60gA{����
C߷=5P��s�ߟ
!���Z��
¸3b�=�����A�oz��Lz�� ���
o�+-�+y�1���`F�bG������Cʻ�߽^���9�#���2q'l*ގӏ8��~�.���>�a�n�@������Lj�f���`�+��/�_�����ɻ�Z�^�5.���k/�t��
�����Ѯ��ȯ�i���;�?�~�>8l�RO�eW�<��E

:��o\�/���4W�U�8��8f��S��y�[�%�$���Y��f��2�=��
G
�
+�ٍ�P�f�������lz����%2�=�?������_�U葫��
�f
�Z
Ʀ�}d0^�3��
r>xg�Y\�H�Ís�O���8_�]����v�4%�A������	i��~}�y��6�bCq��=�3�|{��&
�{�E���}���w�"��1������
�u%��M����3�"�ٿi�-]���8}�Ըܞﭻ}Vg!
�Nm6Xf��o n�i�����aO�>���7�Ԑ���bf5��>=�mؔwɳ��
a+����M;h팂����vm���#����h
��2�u��S��L$�3;z|��Xc����o��뽙�&�7x7.N���g~�v�����hj���������4ݰ�A�\�yEëő��Q�nX�s���
�8� �X.�n1����zA����Ե�";xm��_��q�L/��8�#��dz�R_;�V���\<����;���DJ��R���{<�>7��'�3�M�����[�C�
�ϟM�?a3�{�5{TE����?yë�
�e��ĉ_^�K��B�v�E��·'�����kA�.��l&#
�(Yh=��y �ˑ{ٷ���]�̺�C՗`�����%h�2�a/1
�›��W� ���o�	���"������,
�r��T�ƥ9}1����r���,��v=d޽�m���t�(���g��2�V��>g��eI�qm��Z o�Ik��0�]��K����0+�5 ��썶'f�Z�N
G|���,� 0)�
b��;�z�C<
Gt�}*���
7��+Hk}E��ޣYn
�!/��;�����e��5��u���l����>��D����oQ��R��u�^���
�.�|�=����o��_�i������
+���~�َG��7���5�}�~�]��{��7��W����w����'��o���Զ^5׏u��h};}.����W����/z�t�
���m=��[d�f~�+�O|����1z���{�����~�[�ݯ�o|���n��7��m�|����o�o}o��e��+��7�x��u�b�
�ﰲ��'A|U&u��?���>�+��O�+�ɋ�OC���<���	_�
��~(&����
Jz��+bO��Z��D�W���_1�{���n
+��o��WS�ƱF�l�����Z�
�O?F7u,��#���q�zB_>N�
+�q���~�11Ç^th�d������14b 潭�-�n��;ǘ�
={U[�lyصWǴg
v�H��ى�y���
&~�����^}V(���J��:p�
�j�i�=4,i=�<��$�؛[:�m�(��������u�����br	�W�R��(V�
l[���������gb<��{�.�R^<�z��-y�1ة�-��n�r4<�~�{ۨ-Ww�EZ^Ƹ\���Y�h�tnFp��S}�X,��
a_A9�O�f��z^��+���\�{myF�dž�x%h}�߯��9
/��m�9]C�ϺO�ڰ Op��v���۸c
_��j���
�%��kvF�'�
+&���
�Q�v���6c\"bs���Y��_�Lz�fKwb3v�m��%��,��b�e0��'l<!Ȟ�">
�Om[
�#nj	��Z� _9�e��v~@��1��7��K��u�G���K}�����9;G
�G�%��S��B��v�깿�A
z�pv@������������S����˲Zف��x�9'3���9�o�nβ��JX�?v�LL��s/�؁p�m���+���;8~^oQ{�,YOMo� ?<���V�y
��(|
��D�~�~y�}�3-+j�q˾b��5=�)b
��z��Vc�y��q��/�x�{�����>�cA&kJ�.�W��1\ei�ӧͶ+��S:,9_�s�K��t���Z�S_�WG<��c?]�����K,��
��_[ޱ ��6��+v���l���mh�4Z�q�G�B���佶��pK9σ�%ۏ�Ѵ�m7��l�Wq�^�'\��#������ E����͂��hrx8RI<�
��A���XAv�Ê����Ќj����y0b��V�s��,�����-��6�����M	�~�h�+��zz����XTwXJ\�@��c���nj@�	�9�������:YA���z2��c���!��Ew���#8���`^D�A$h-aޮi6���?�S��
���8��Uⵉ
�-�
+�~�l1�i��y���&�=c�q��t����
g�]"b��Ӟ
+&⶘d]۞[�92V>C�
��_�KO��Z��q��_�cM+"���6�z\�)o
+xp��ob^�5�a>�ܩ?Y����¿h>�f�i����AzGLV��+<�%A��󗈯�!�[��/�\��������t�YE�8�o
+ҙ9�Z�޲�u�]�~}�Hy�ñٮ��'�H|�궧i�b�א��g�� }�zo[�;�Wl�g���
����gܥ�X�[������ƚ#���"�ek3���=���G���.��UhzL<-�e�y���Fଅ�Y�~����f�VO�w|�Q�럜��'e�Y(ǡK���)^�C�}ܙ�Rƶ��3?�V�nR�k/c�h at r��r����t
1�k)V[~#�f]�+�Wq&�m�m�D]�T�J��/IX����x%��~]�e]iR��ʉse��zE{Ös�*xARݍ5��,a�
YSm�Ao��Fܖ�6�Fh�|ݸ�=^����U���a+Q�mc�ק�>�
6޳W�uƩ��m����z�`��1X����6k����g���+L'�����e]�c{�x0��]%�=L���s�6e|
	� �uD�D��Q�kv�.>�m~����u!c�՞;�����y����>/w+A^��o{Ǻ��]9s���nv��^ �`<�V
�νڋ����$<Iqz�<��sn��?��d�zBW8&=hk9�����S�v�_ۺ�5�
����d��o�ճ�����7�
�E��9s k�jqxId
�Ϩg0G�z �l;Í���Pb�
+�1����
+ӉyG��|��L1�|{�
+�K�aǥ՜�+��y 
+����IGm�~]|#�|q	�Rl,�c�ʰ�9��*�[/�
��7�nk_�>u |�KpD�?v��—ǸX��~���?��xr	��$˫zDc�<����H�0瞷�8��s�~�/_�'�����纂��f/C���
o
��W�1ֹ��Ƕ��8���}��ja{�:�>Y�+s�>���7��쁖��
���[�޽s��6-}�F~ާ>��<;��>���zl�����`��
{bk�;���ў��+A7�r�XI�<��,�R�	�Y����#h�ߵ�%1{����5
�bO7�3:xA	)��֖��d�.7ƍ<��&�՘�����f��+��6�x�|������:�q�zK%�S��
^
;��3���G�S��׶�Ҷ��<F-�/�-�~

z6\�Q�
��uN�,θ�2\�"->�@�qMd
�C�xm���Xr,�RI��f��:�Y���8Ze�[�ٲ���zQ��.\�~���‘��t��#h%�P�wH�?�Hz~B}1���G	2���n��s*�`@��lq�V8�
�4�_���wؗČ#xz�:�w|,�G�7TAN��
o�G�z����U[�j��=�9TeuQ�zzn�Ew�!��c��ϰ/"��
��r��O�d������ք��?�_<�ȏ�y�������
I1轂�?��&6�jLk��AZ5
�v�q�
+����m�����”N�������vo���s:b�|��ߗ0װE�{'���?�cйYa0֠����X�v3f	�c�3hێ
�	^﷽�6^�h����!��`
wI�krZ��Ry8��S��G[��
+�2q��e�yke���_
+Z�R	�"<������5� x6Wp+=��fh�Wf��5�j��M�t�zx���m'�
S"�7t�Γ`+�
�
L\��������`D��Zb��mѲ󹮫͖�Ap��
��p_�
1��U
&��!���!��f�x�itջ�.���m��
���f�ֲ�d`x�{
��Vx��ų���B��f�B��h�m���`�
�7�N
��/�E��]/��y���GPs���
+2�4�V��4�G0��~�)��T�lw�N�^N�[9�q�`6�~~lk
%���Gk'��V0�Q�9��-W���+�5c?�
�v�y���b����A�a
|x%�Mo�d���o�R����M��*nO�]
P��
S�4�V8*#zp���1���!�`�7nB�zA1�}f�Rv@�������uLcd҆
��P�GTO�?�¾��O�on}��z�x)�
.������{6
�-��Ju7���c4e��_�jO��<�
�̾)� �<X9�lxC/	�V�j�l{�l
dΘ|\A^0/3���R�j�*�b^�`�T��^<���4���2�gm�~��<����l�E�=���`�Yk���Q8Q�������on���v�n���������˭�'T㘙���Ӽ�5�//��m��
�e�v���ص������Q�t�gy����ԋ�ռ����pq^Gv��c�����k��
t
��ض�<�T��3x
����0S?���5p��r߽�
kipq|��W��Pk��

���=�}�ꡯ���mc����&���c��1�a;�n�B폵�N�~	�ߜ��ۿ��?<U��HU����tek����f�l.�=�SuxW��;ܔ�����������T
_3仪_t{	���z��?�c�9
�r�Z��챓y�id����w�x<�������|IJ���<No�ѭߨJ�F�b���g�g�~�

���7���F�va-�x�����Y<4	�]w��GL��3��l���
C;���3��N�����_Wg3_�]^e"���3�vj�wFN�.B�OPS~����z$�5M���;o�ٵ�א�A��m�>��6���������E��	<����lQ���|��¯
+3�:�t�[浌��aA��<��c�Ox�t`>4
;��@���â
�
�:�
K/�#�Ҟ�#�2{�����P��
��N`�����A���ρ���{���G���k�離z�+�E�ƽc��
�[^OՃ^�շݥ�X��#Ʒf|F��hy
�ŬLн3�ӵ�[�C����
�����([�
'��m�W�ʦ
���y��'8"+J'|�$�I�TA,��
1noA[tT��j
����������b���E��tf+�Fӄv~>:�-LF�cs��SO͌�?�����D���ū;l��srb��b����������FF��s�Gs؃��
c��*�`��q �mm�<}

'�s�
VZ�-�O�0���쀩�&�?�xub>����� `?,gl��j��Z.7L

��#���RG���L�\��x�76��yw����}a‹/�ќ���uux���z�5�(,�8�dxPC<~�Ǖ;8�q�m<�V��ȯM�B��OV�u�AM۲���R;��Rt8��\Z��<,w���~� [...]
�n;�[���Êo��u���>r�
�%��k��Ns��LL�z�1�)g�zon�E�va���S{�7��0?�Ʒ�M���I=5�1^y�>n>6��mՍ���`�M�����{�C���9c���b�Z��%�a��
5���j"�duei�x�/��un����^'o�uhd�¾�l�W�v&&��k��4y<��{�V�bRs�fb"'��@r�����)
��s̨;�a_�@��؃�J�Ê��͇��<��m���7
��s�T�yR(�Ms���-�*œU��>�}�`�5��S26��R��������P1vc1Lz�����?4��;ȇ������M�3hA%�,<���M��-;
 �2�_	�S��
����q׫�-�ߒK�G*�z�"�K�ƃ}

��������
܃Q���	.��m{���m�
�)3�#ߣK�f�����Q�>�l�v0�rػ����|��Ǔ;8�O4��O^oDN�m=-

��ݙ�s
��x&�����_����؁�
�;����9�9��IT�K�~�I��/�{�xQfƒ>j������~1�1�PfJ�WvG�G����Δљ�W۝��r����+V�
+$�{�kS
9ڝ��8-����{՛���9�#�O8�u�c�{����ה��'X����~�s�;=�܁Q_����8'_��"٬����j���c����� }�p�Ҷ��h�����]��M���z
��$�k��Syi�C�ᙧ;ovpg�
��Kv6>S�;���
��zAf�I��4<G��W�Җ��N���Eg�����2h"GQܱS�i���;��gMA
��G N�2`
�H����ɲ�k��;ف�������f�&
��ҽM3N}U�_>v4+Ո`
����`6�W%
+�Av4N}\Me�ܜSy&��m/�\���޳=ݙ�h;����Y�Yr��t��i]���W��43��n$��(�ύY�x��jy�a�c��T�* m*
�����଎0;��^���G�/�~�*im�Zpl�����Rt@�^Sc@��d���O����4|N�6
�0��mAe���SAmM�
FK��=�^'��$�[0[��A$g�'�v0�
0�:��q��ٽ�is�N�.
DV�eYn���g��_��XGS���6�/�4ȳ���p]x_�f3od�
�on
��v~��k��C��L2zŪ�5��rd��sy���
Xr�MN���)�لV�
7mR
_��S'��˓x�s�^ɩ�ѧڙ,Ȫ0�Wd�-�l�lw-���~�I+1H�c���눥?��[[ΓC�
+c^_�go#���v����6��_Ͷ�
B㙟�
���:�7C�X���������U�f���SU͛�6�GL[Tl[

6�>�*%:6f���@��[,7[�@M�t�VK�k�s��n��Gڜ
ͨ�k��n�	/
��HF�\���0���I���f�_n�O��Cϻذ�Ns�
\���f��}���o�X7v���I�51�6�o%�)O0���{�PL"��ѺϿ�U��d��>–ն�2�,H�Y�2�#�Ԟ����g7"i�DT

�~e؁�Wۯ��OP()j���ya}b8vp�
+r��ĂU�ay�
��^�J[Ƙ��n���s8S����7��]m�r�iP9�,�I󊎿�:�����%��l���4T�0�k]��5��m�x�3�Sl��u�~�4즪F�G��'M��A;�/Z��t
2�i�վ�LjX�F��*8v�f�_�GQ3� M�Co�	<�-
-�r�4\vaz���α
�޲9V�˯�5���в[�o����W���,/�i6uV��C�9r�n2��w�rznU�c�U��-;cr��
��?�c�i�

nu�}���S�`f
+ং��

��O��G�Bh����[��
7/8�m��l�9�Xrɔ�S��F����pg�6K�����Ejf+,8�	�+{T��
��k{��j�|~��JC�[�̳
��-�
0=H�趕g��UOc�!�y�����g��
��H�h �vP.a[;�E�u�'Y�ם�Dv~�4V8�v���A��|�V\o7Rm�D��n��;�=�Ɠ�"풛�y�7�
���vB
J�Zb&�Q��O>�;�Be�p�.�c�у#���,t -�g��kw?E
���Ki��6y���s���n�?�`�^�kL��s�}�H݉�2D�m���N�w
��*�Z���lؘ��gu���I7r3��R��,�J�o�f�2!����_K��=�w0����[sh���F��L�w^߅I����
t�=����<z-��-m5
��:Y��f�{��
+'qf��?�h���^m}�N�4>`���
+�mv Σ���0&�k�h�Y"�}epr\Wi�)����7]��oH�����-�x��j+e�i�ge;�!ރ
�U�̇N�sQw�F"Κ�/	��?;�G��I����s�*����뵎�����W��<�5��3Ŏ���ytj#p�wdhi$1?/w�X����
���h%U3�`=�V���_("�VG_wbkQμ�����P�c�4q|�5�W{?29Tn/J�'X�P2��5�:�v�6o��쏝��~�"�T�Xs��w��Z�/?�~Ǖ�:�@�����k���byY
P�k2h$�a۶e�
��۟�Q}�fL��Dϒ
}���a���˟���޸�s�r8����E�v���HW&#�c���n��
+�`:y
+z.n�j��k.�v������W��
R�r����D9��b��>jn�+���ұ���%��4�H��3�fm�L�X�P��8�/����۟ﳴZ��?��C�I���[~��<��
�1�9�
L ۇJ�i�梬�O_�@�y����}�^o��]��7U���W�t��
8U.���.ꕣgn��s"�����c������J>lbj|0�
��<�܆�k�v	�
��m2�}i��
+�3PW0'ք�]�s�	�q��b�G��C
`{lQȎkdx��Q
�4骘ݾsg{N0X8g-S�|+�A�G�
�BG��V+%R[�#[�,�lAyRB��
+����8�Q�=k�V���~!)R�-�.f�]4�:g�A޵^�����H���� &��1��D9__�5j�ZΆ̛�
+��'N%�� rH��!1���9dJ�Њ����^cQ6�BTV�o�Q��
���r;�
wh���]���k�����CK,ǣ1����뻥A�
��
���%��.@>�7���療��ք:�U� ���gV��w�ը�dJ�q��*��Yw�-h���A��Ƨ�je�J������5�~�RK3tv�Z����ܥM˼yP������sь��ZӤi�m�ƙ	�
��R������y�8�]�S��R�YsR���2F�ҳeAr�.���7Y�s䔳��c#]'
�W�W�پjlo��[�g�=dل^4�6C�_��
+���N2�)�2�,8�̡����������K�gR���=1���c���S
��G���`��v��SJ����9��[/~c�x�2;�=���?.c�~��J���ȏ�*c:�
+�\�Ž�D�[�G+�r0Ts�"P#��Zn8��}�$>y���*�}������Ə�J�Mv;��|�nR�}�'O�\�#��I����5������r�@��ȫ8���F���݂�ׯ)?7Vm+����>l#3V}�tY"ł�-��
R1��$ 'Urk�/��}S8(O���#f�ߣ�[K]b����bb
��}��iW���#l
�
���
+�:�p��V��Wѻ�_�J����V�
�QS��O�ѐ)����t��`#xN��g1�<'�	>��h�����w���(�i��ϗ���]U��ܯ���={��"d왶��7��5[�2���B6����
&
h#��lDiew,��ӈ�
+q�h��O���q9��J"����T�G��?�F[^CF�z��\�ŲX��|z�T<�dj
14��_��F�e=Gdۀm�8�L|�!_���k�jO�>�7��*��{=WIf
w�3-hK❔��gN��T���֜

�d�zLZ��8��.�͐���j
+�6��S�
8��zgqם7+�]Q�A����^L�Z]��ns���O����Q
Zz6O�����5�Kk�
J���U��|
X�$���EK,ݠq �J�x6Թz�
+x5w�[~U��w��#8�_���
{s��r&Ԩ���'m��&������5��D{V5�J�øV�V��֝�{G�*�,�f�n5���b��{<���^��
P5��)B�Pz�N٤cpGD�`d��
+N?��;؎|��Å���ss���g����ү��U��
OG[�1�UJ��.�&�>h=k��t��
�A�ڒD������!��� �����E���/� �Ֆ��C)
+�n����=����Y�8~?��V�
�g0~�t��������
��E^��'c]���ykӞYy�Z�'�ngw=��t/Y厎h��S坡�%ݟ\��-�����7���~Y�g;�a�#�3���?s ���*������r�� ��_���$ۑ��\+hċD��y5��[�m�?R
BD��s
��
�W�$��
&—>��Z���vnQ��2Ha%�ct�OL������@�m�
��꾕R6�e'm��{/]�� ��t��\
޷�ctn��-H��;Ke{�`5	o.��&
�u
�n�2WKC�D��ֻ�y�vl1����N�V��bqUU׽��~�uEUH�
B�(�B�Ke�V�`�j0O�J�Tޮ��*���
+Ƚw��o�8��\�)��Z�3vJ��w��v\w��9�r�%���k�^��T�Us�V4C�!����̱zK�J�0-�
�����?Ԉ�
���G`e%O��6��A}y�� �B;ת�q>��x�N],͛��Р��(���a5c�,L�[�7G'�4�,�ki�u1+��U��k�00u1kux���_[}T��CwZϗ�'R*�[k-ݫ0���1�
�w��eβ%{��AW�S)y���������-w
+A�D_��Ϳ�RR�B�rP�=��ڢWfFD%|�1�
u���d
�Oc��d�
�D�=�okF���շ�d�-S4���}��bzN�$��˷g��u�~d��+��<�^�#ra��(��_�"��~��n�R���
+ߙλ�N�'�Cn0EpF�S��pf��`���W�}{ _���)#/�#S+���-Y�
]���ș��\���b�a_+�R�Μ������o!	�~~%�8�;
���S&���,Ƙ1�ǿf2�c{��ܞ���ϯRw+]��:w��Lo��[WT��yV	m
�d��
�3�
+e�
2sf�V��ߗ�
�
;wav����9S����*��#_���ػ���Ң�*
����:��FɄ�a�^TX���IJVk�^K�;Ə�= y�xu�0������*|%<�������W_���x��.'�~e�G���6�k��w�,\޼
��x����������5����v7-*p�t�qv-Uು����nq��櫄���6t3.-j�U���u�m.%}f^��fuX�^��a`
1�m�Ϛz�����|�;���%��� ��KV��.�ͭI5�Xp��Rl�/mҴT����9u/ِn�NJ����
�[�Qֶ����F�jn���2[���9�;���Ob��s�{�-�YL/�ڼ�{�'��
���n���ȫ��Av���ږ"k�<��X��Y������y5h�2Y5�����>62kG�:�V����촸�辟$F��AP���H at 3�q-���hj�%{��>�Z�罆�ְ��Zާ�����aJ���#
���
+6��\�X�0�Y�lk�����d��
���ywN�߹��+���QW�ZK=ߙ�
+���J�u��������Ǣ7u���NV	�t�Y
/����Y`gm�T
2/ؖ9eW;��u�ˆ
k���S|d{1W�V,��
+��-���|���M�H���lgt�~Ҝ\�U�,K�U0����۞
�3�,+_�0K
��3����ZD��a>��t���hV�l�׺E+\�-���k����y�

���\i���nQ	�u�Jx��h{o*��%���\
�)�X��l�i
�g�	K
հݫ��H
x�ܽ�4y�U�<W

4�	r� h��&�(�߲bV��{��[���'�咗�C
+m��/�W
J�mm��SW
��Ϻ��
+�lOY��IRe.�4J��|�O�Ϫ�ZE|�����E젆s��sݤϠw{�2L��Oj2�lǮ��+��T�eۦ�k�
���� ��
� +���M]���m�?���}�T���v+[Dy�bd�~�(ʶg$M�a];����^>�&
�p_�u5"H���L�z�KƷs�`g1v/�
O�Rz� ����Sk�&vX�YFuc���#�W>�/I?H-��N�M��m%�jqQ�c9Y��i�
d5�W�y������b�d�-C4��%���T�n{Z���Ґ�����k��=b�*^�-�s������u�.��V7
+‹���F–y� 
��+�͝�=u�m�H%���Zq���� �g1
�k¶~
+�#���/�|g[��lk�DO��Z1������x�ל���ܐ��|<Wп
��3��Ȭ�
�eS������j�g��nY��=�]����QK�W�\l� ��p
S��Z��
^k�P�c���
+�{���^�y���X��5�l
�AKe�j|}�o��|(�y��k=�W8]��.m[+at��n�$��B�W�e7t�e=�,�y��Z��T�C��'깠��_�c�Bړ����
C�˖�3���M���6�
�$��V�T�۳���լJ� ��m~���>��Y��*�2��%=~��t�e�'�]Y�=�B�~��l
V

^k�f��Ԇ�Y�ou*}*3v0r��̙_+@�Թ�o��bo��O_y�&�2��|���������cH�<�����f�?Z��v�S�⟘:?BG�ي.Ao^p�W��`_�y׫�ܽ�P̊)
�Z
'�Ǖm�;� ��+��v�a����+���mw�ͻ�LG+������g�Uֲ�FB� �`�F�:C��F޷2f��֯l׶�|=�\�vo�#x�%�J�Ȭ�X=�Ň��[�^��d�w�nk�m,еG�;x�b�kW���~2_h�\���1H�
Ȳe������l�fxc��N��φ�R�Z��J ��sM���e��s}
j�=���d8���J�V��2�`#�{��d��g	���&������+�;��w�.�r�k�����Jdeۋ2dv�d����ι��
+�,�����m��U���s��+U��~f��}�r˄\����U�%;7-���g�E��\U&�ͦ�-�K7�:nd������<��I��N5!�{��
�a	s���B��|b	*M(?m
+g����g�K]�D��
����{��nkM�	��㪤�����_�r9��r9qҝ��.MQ6;馨8�O0.��\sQֺ��"�v���X &00�
`�5l�S䓭9!;pFF|䜨�����ߗ�ޫ-1T����MiN��Ip��F��Z�V�
+��: ���͡)
�U�mDlA���m�ٲg�zm�>�5SȬ�J���Qj�`�ڤ�)1jI4��Q���
	^�
�f5���)b��~2$l����Z׽M��k��̥�T�P3�݌�S�űU8����U#�BB;e%RL����A6���\��V1����_�m�mrY����Y�r�K�v�� D��G��R'^r3�S���i!�E[I�f����� ]��HJ����E��Z߂a��*����"*dPT"�sƺ&�X�@�$�!���"o��5�֫�t��ank�s"
���fm� WJ0�M��e�4����)��U| 3�"F
��Ls���
%��z�t����U*`1樯kD�_��d�sbn"�)�&DM��iYQw6{mkUQ�
k�k��bJ4u��5��Q�%�Nf��@�Ee,��*أ�q��V�j
u&š��Pi#�[3j��5��
+x5�%��o�
����@��C 2�(r}ײ�C�S̝�ҏF&��@;o���|�d��s��d��cP��ʆ�I=>�$K@(����Or
�f�s�f*����:���b~�rR�s�{r��-D�=k5t��p9s^QdsD0e�9�

��a >��J48
h�lX�
Sae޵,�\�j����h���l#i<ċ���b@�@��H�
�'�u�TfAb���i�V[i
+0��LW'��t�Q����3Y�_9�}BP���3�x�
TW�ۊcuѫ�m�D��:D��2��J���	`J3�tP��m)q��3��@ilu�7�TsA"�T�`���5�{���v�m�X>�U�@�ln���8��g7����)h:�*�:C'�*�\�E[)�?j4,<�x���@]ZF��K������X#2v�����lt��A�����^���-q�Y��j�3�F��H�ܤ�t*.��9�g%�l�$<��|Δ2�����h"&Zb�S��k�iI�Oռ�rp&��l�Y`%
�XVhTƟM����T����Eˢ������JV�
�/o@�Kf�٪�{��շb�^a�xG鱟� �3r{�)ggE.;ggl�^�q�A�JP+m��J�X�d���ᙣЂ
+5��L��_V��A��j�$&��5���f�*��B���@�ue5�D�j�\
+��Q9 ��D
�V�
+�s�� ;-&;��b%�]�[C���qaі.��+�@]s"���:�|�+Ɔ���k_��$�'Έ�~Eݭն��FD���QmE+
+�&��H
N���}4���	Ҡ��^_q��Z9�Ib����}m�'N�k��6�45��Ø)I
�� ��b�>�(��u%��1G
Q$E!���be���W8)������9�w���d\��U��� �~-.ʓ�1�
�"P��t���*�vd�:
+f?Uٴ�p�;��Ov
+-�}�̃�BF>M�jtRE���C�3"��%ùnmx����˂XW�� ۝m��0
�8�F�:]�2m)�T0`
�
+"�� y6{��Al�eq���!A��̮3%*#���u���� �%��yܱB��Ջ7��?o������&�W*eF<W�Y�:���Ғ�#��1�QG^tR��\�	������|S�yK��lz�[h
ꛈ�}�~r��l7e"�ܜ�L*d�>�E���$]
�Y`�mk�B;`�(��Q;��
x�o*�%��6"�ZJ������p �R
L���ņ��o^LA�䤁�+�8~Ո�/�
�h����z�΃u�X��W��b�ij�iW	�+m��6��RhV�;*G���
]�c5Q�F)2VgDt ��E[l��^%�hUǥݩDh����B�L
;<'��H��6;��9�ܳ�2+�/���2e���� �1�
��m5I�o!��r�1;�
+��á
b�D5.t�8���_��*�,�h.=�hØ3#��]�l-�)�^M�J�zj�ƼmS[
+�j�!� �s��������s�JS��<�~��C{U��0��!5�I<�
%A�����5�m� >��@0�䋡�V�dA��E���&���՗$�E;� y+��G<��� ����: y��
I!$sFk�'�w
D,g�Hm����G���	�-����M���7�J�M�
�9O'���)YA!��4b�cP�k�vN�R�s���S�fxڭ(���v�U�X�R�8
�rr*(&패�8UJ�U�C��	��4!/%Ad^i�f��a�D���� ϖ�:�ZU\�Su�]9�	75��)U"��%ҟ��͉-��.62��ӭ>I^N
����)q������a�&)��Jt��
�plqZ�F��-�Ҟ
.W�ڕ����q
�ȶJ��؅J�� 1�bvȐޜM:��ʢm �^�ֈ�) ac��bRQY)o�ƍe���FZ
�r�z4��c[F5�A�b�� �NK����XZ��#�d�ց
�q��4V�!߃<\��|��WF���+RF���m��BU��M�䴤���������3��j&%]�ej3�ݎ,�������2'r)Xt0Ȝ8�׫���g����ϖd��,�o��-&a
 ��B
~�&
,�ˡl� ��R<#��q� �>Z=��%ׯ
3#\��CA]���$���x�bD���F�%1N�Ң�i�`��+D?�ʜl��dğ�akjӜ8S/9�`NGHO at 63M
+��6�8-0���z1�Q�W�\�


2ʼk�4���[!r�i����k;�4�8p�̈x_qx�m
"Y(���Ģ<�`���=kk��m����32e,44)�7'���P�q
�C_m[+l8��Q��͗/���˅���.��u>���b�6BZe�X�0K����(���@�B��R��ڃˠOf�Զ�]P~,IJ�
+�o�Q�B�oq%��jM��/Ga4H���[
�mP7���a�Q6�DF�+��,����	��J�B��V@�Y��-
���
�◠%�'��
+�!K�����EY`Cy:-K�$*FM`Z!rPl��
����
NƆroCf�D���v�b�f�ʒ��~�5�����R�dEb`
k4�
��5�(
T
����h�US�me"�����

2аf�f+r;#��
A���laLKL����{�I�3
%(t�Z�+�~]b a ��c*
�P��X���"f�E1gmgz}�:֌���^���l��ux
f���ߙ��4�2���[X)��B�
��!v'@C���_!Φ0'#��F[P���kƱW"F0��Y[�P� E-��X�R�QВD
p:W*�E���O
+�� �і\v��ޜp�����I�����������*v!��N�T��uv��WD9�A$���
+�f���<2=�Ô㜈��Ƽ-

�"y�����y8#c�����������x���P�f>�������<��ZQ��e[�v̿��8�^�<��i��d�`�+Vv���f�+[mؕ}�bς<��IA�c�fp�v`a �P�rx�gg�nA��e5p`~�}TG�
pV"�
��A���Z0����Z!��qbc�s��
+�\!��R��
��i����{0o�Օ�B�f�Y���oe&WڢZ�b4�r��!�5������3 �������X
@q��*8� 6��\�w�B\!��@�lń'�aQ�!�J,V�̹X�/(O���YI+�Ӳ�,ݛr4/��;I`@����2����
t�vNԨ�A���3�={#Q
+IKo���ʉ��,ښ�?mW�C
^!�y�뢽B�^��!�{��	�S;��A\Qf�6P\�*�C����d�SF(?U �m�����IN�7��)hY�yۡ:%��
9lj��-"2�"j��X��(�7'�����`Q3��s��4#�I��9k�L��i�3�\����L�RW�>�,D��
��"�������`h�^��
+YM1�aw9�
�|� ��8���V��av���$�)��'��,�i� 咪�*
����u
+��DDw1�4#�"
+�[m��M��$�0��
+I��X2cf�Z!2`
:d�d
+ouq��)�+��P����K6�1
+��t0'#=�)��bg\!��
+�K���6���Cr����*u�#�H,�0�*w��Ȏ�>'#��6SX���֦�unN&�X����F@Ń����2#J`��#�A�V�s�� ӕ����W�T����=������r��Ĺg��$��4�p�S��)h
�l$}
׼%C(���:�W�l�D���q�W������c�����8No4
�'bV��
+���%����2c�h��aZh���L%�ۢm���H� :��Fy�>Y�>'��s��@���#J��Y[�XԞ��7��e�9"��'̝�#~šJa�b4o�Q�g�]!��
+�_�o�;��P��Ne��t�׮hb;�'�U=#�}�+d��G�C���8T�6-͒v�-yYQt\=�3�*C�� ���t�L�L�|qjI�̬Z�<k��&פ���2.��]8��+D��D�$y�J��Az��P���Vg����f 
Y�@�S
-uFl�
�@��
���U�
����
p��f�Q5����53�ġ�Y!XF�]niJ
v�JZ�0 	�B�A�R�E�آ�V��ABޙ{��*���AM�9����%����DԽa���y��q-���V�:�n��fLUg
�+B�Q��Y���)C䜌r�i-s������V
+�.s�׉Z�+��)2e�Q�J^7i�G��*�A4�`6�Qoy�~�
|�C0�����EE�������-�G�!�<��ì�+«�4
b�fHꄨ�R+�щ��=��ω���Q3d�+�m�
8 b
+j����D��
ԃ��y�T�,:�`�J�T�Qի4K��m �qgmg��j
մ �g����T8��G\M71�OÜ8,����qiz^X��#݄J�D�'�(�ja|J��4�@�~QK6�0p���z
�(��+M^o�}FK*ё �|F����ٛe�
+���ܠiV�uND���*��a��dv�j�Ɍ6Ҍ<�Ov).V$ �peE��珖�5_�()�2f������ꖬ�T�� �L�
���Y����
�W�1�w.s> s�}��E���HV��tV�`P+���1�-���7/X��N�1�q�xgdO� ��E��d�T笁J�&�r��
V��L�^
�
�����;'ca8x�`-�6,&g�r�W�CI
+��������L
��Na�`�I�2�m�Ξ5�
k �ch�.f�U�
�J�8!�b��-�����A����3.O*=�px�KX�;��������H���C�52�����_n/��.��==2�ۘ?x����w������_^�n����<��g���_���������˛�����'�����������wwo}�ߞ���۳E���.�^�^\��p������_w?~A�~�>���o�~}yމ_�^��]m����w���?ݐJ�P;��P�����������g��嫻�6���>�}wq��wwO	�?����ϯ���������3�|�[~`:��O���sq~��ͻ�W}l_�|���fV֛޽�������6�ѡ�ɻw�߼���>��ty��
��� ��t>�o�]m~4������櫻˻���1����o�W�o�w>�
æS�~����wg��bf�W>�
�5�M����ۋ��^��w�Ln~�/�ڄ�g"�'&r?��q΋����O��'��'�<_ݼ�=�������]�o|�]o�q.��^^��L&<�l>��c.7�_ܞ���n<��ƒ��7o��y{y�ɡ�9����7��x}��Q�;�y
��Ýѣ���Q��Eh{�oϺ|���˷G}��=���1�y|���泣�wT����Q�;�{����T�mfr�*_zr*�3zD*ߗ����껳W7?�
n�ǣ
� ��S��z�����)B�	o�^���_�g4�-T��K&����۷�g�_�|,�������׫���6����ī�(�� ���n^�~{q���it���3|D�)m�+��(�������?~�NT�
��67�j�O>÷�_�������6�x�������W�g�|���>�ֱ����}wuv����������m���m;�������
f9^|L��ivn�5:p�w[�對
�a�����s���A�rsy}�R�a���J��K���<��
{�"�N&�C�&<Q)��$94f�����͏�?��l>���D�Ld�����|"��'�K�|"��n�'�}�Z
+8�+����/g�Ҷ
ߝyv{y�ݛ��ͷ�/��|<���f���}�?^�~{A+����mY�S�?� �!C;�>{"�-�Rۘ��1b�QD
���������6v�
�Dht�6O�?�8�����͗��e���'�j�<ġ�x"�E�|uyu�y,�cT1�xs��w7W7����T�'�֞
3�<{���ٓKD<2��df�O&�v�ĵ�aۥS
2�x&Lj�c���}X��o,U
���\>~$��ӯ��q0�㫢��n<VQ����f'j������E�F���ƻ��o֍g�Xnֿn�N}�������WW��X�_��ί�=��Nr����~{������7�w<��]Fo�zW��
�v�N𿓵?�ʟ�Κ��\�C��oWV�o��g���A/(���`���m����l��
��x&�E��<��^9���z�P�חWW�D
]=��>������+����v�
,�?�ml�9��P���I��!T�����
endstream
endobj
967 0 obj
<</Length 65536>>stream
+�����!��׷7o6?9������o4msۤ����`p�I��zuyw���թ����7�����7�>
�0����׺�8�8�������7�6��x�ӧ�m,[̾
~�O<�M?��[���]_�9{�Ұ���i;�
�fw�d�a6��c�~
�a�ܻ�a9�c�d�a6��c1�<�`����=�h�#��_L˟�#
�y
|8���	��|&��n=��
�a�2����_J8�<��o�'��L
�A�q��l����<�p��g�X$�C
�9h�������m�<
�>ƪ�[�
����~�j"��#�|x��E��ϯ��G����@�x��͍e��jѓ,~��s�h[p��K�hO��ю
��������"ڑ�
:C���z�gG~�	?;
+hG~v�gG~����ܩ��v^�'��6��/ȇw<6�
��K>6O�xl���/�������ُ_o�x�Q,	��K���q�
��[P��xL�����͇�
k�
B��y)��/���ʊ��yp'>����������?�N�Z��������Py�=UQ�tv���ʆ��G/��yy��������.�~R/��~��u0{��
�
�
����l��#����c��?,�
luv���U:�D�7�߼���}�?>��-��
f/��
C��L�����?��l>��
�'����D>0��D�AO����D�#�ȏ���R/xLW��_7�Sێo/�{sq����C��c�
{L �f Gw��p'oWY�M-Gw�OM��N^_��;��N>���e.�P���х|rt!�|s{�0
G�{o��
�@ME�m�:����ut!.;xJ.�W��_��
���Y���y,�`��to�ݾ��Wە�_y�O�Nj���6���������T,v�9._;\�l����;�;5=�/n��ޝ [...]
�͋�
kh
t��þ:�
>�k����/g���?�;�X;�P��c��C�;�����ܖ+�����X��cݩ_���x��[��cͩm�@?�$jN}��٫���Eߧ����D����E
+ظ��1#�����5_��y�׏��6��x�|"�>pp������wt$n/^mŧw�mt���3�e( �է�	
�W�4^�G�A�����f�>����z~��y��l.1=����x&?\��"�P[���g��Ň#gSB�O>�a�8V�>5
����h�8XQ�=���95
��{4j
�{4j
"'?5�F�C5j�jvw�El�Q1{Ԋ��۳󻳫?�\n
�-/o�2��O<��/��S�d;���n>�Ǣ/_�|uwyw�+�\m����ڢ`��;����q����7��_[Lm�ʧ��~�qU�o��^��������>�\�^���n�c���R��I�:z�1�������a3�׷7o6?=���O�X�H�u�]t ��������6��
O颟�h�w�߼���1���
\�}�%W�uI~�#��M����
v����8��1��bǶ��#�
���(
ptS�<
7��\>{2N
+���$��L��/=>��;<��Q�ۅ[
�������Q�;*|G���=�·��rT�
���T�Ҏ*�cT�6����T���v����Q�;j|G�o��
+OE��f&���'��m1�G������W�ޞm�c�*ߣV��$"�V9����+^l��
+^|r�p,��S9V���RF
�'����;����ꂬ�,��7Wg����DH7ߟ�_���[����x���[[�D�m ��dm5��v�~O����v֣��v��s�ѷ\���Sbp�
��d�>~���m�A�
l9���6�y�������W�g�H�+/}�����i�Wd���O7:fS\�����m��>��;�;5=�/n��ޝ}(rnUY���
�>n|x����ͻ-\[���r>NO�Vٸ���U����ͳ7
L���%����d|���>>�/���ǂi{�@D�������]��䷝���������
/�B�ݣ�����Q\:�K���+eT�P^�A�8t��I�I?aY�h2?4�����͏�?��l>�T��O$
�J����O���@@�|"��n�'j����ͫ˻��]~H�||w�����wo.� 9ޝ�Ʃ���|"~wn~�
����ʇ~m [...]
+1ae����v{v���(���wj]P�1��1XCdj�D=�C~����������y����
�~|+��Ͼ�O����+��"R&�����K�˔�
+�ˋo/�����{�}��on��vq����_?s'_���ów���������=�����=w1�)�Ssq�h��E��y�S���g�FP�?~�����?�O'�p�N�x���;yE���g����y(S>i!�������F��<6�N�m~
bN����'bj�kp���+��:H�y̙�M�y�!S����R$by�R�Lt�s��k
+ϋ�Q:��9�ݟ�:q�����Do=����'?M�rz>E
j�\�������b�9��)�Y���cy
k���������:	�M����yk�
+ٻ�M�ػ�>1ѧjJ��^�Wϫ��a���-5�����
�&!E7}�>o5�:�5��ȿԗ,���LLL�}
Bbm���k(�S�/T�M۶Zx��o�
+���AɼMr_�v���=���뾑cq����Sq����
�lcZ-��-'�`��D�<�gڐ�o���OZ��}����;����>�]hC6&U�܅��sѥ��u�K&
?���J1I�-;�z�a�[���������>J^@��L>T�tb�}d
eIh�?O��b~?��[�U��<ҬdQ��4Uמ� ��
{/�������?�c2}���Ny��/E�i�f��"�
+�/���ҧ���<d���e�xQ�}�	a�d���K�?�����
���������7�Y�_���{۩H��ً�X���)���PTc4�?��ը#h�Ԍ^��>�I~����͖[�/�������s�_���Y�[R7F��� [��4a��3"��B�G��p��'b�x����?���q'��/t���M����H����>U���������_��2MA�"1�7�����y�M ���U���Ū�����<"Za�v6S���sTo��:oK��0U='�}f��E�����V*wQ�%1q�}�p*�zZ�����7�
ܺ7�I��>�R�� lf�1H�5���
�A��Y>k?�9{�T5����9���
���r�Ũ'��~�6
���N�b����
+�
�e�t���79D̆弴��`�>B�"�
I������M�r*�a�kĩ���Co�Gy@
G�G��a�_�<�AJ�l%C�u@�뛰
b�z��~��}RK��H���
<I�~�[-7e��Fa�]������w�U�������W�>��� 1���,��t������}p�>6{�}��^f���a����}P�>&2u�U�-��h�U@Գ�Ŝ>r�ҽ�R�9�Ac��>H"ԃ��J�"��9F�+����89�N�����|֫��I;�A�����Q�~�T���F��P�TMA;qA�n�{�L��.{��m�Q�����c�c)H��w:��)�Jh�Tu�I���]
+J�X��ֺ�]���.�&o@2�.����ҴV�:���]#ݳ�UA���z!F:�/T	�W!�4���ޖݤ;\^��Zb��l�^Qä��Ywډ%:]�
�j�R�}4^��X���5� ʸ;�s��֌���B�~�ZSazԧjP�ˆ
�"<^/1��<y���O�U<Ք�'��ix�s�\���u��B��VE�ZvޯD��j[N�f&�xCv�µ�[7��U(MU{e��ɪA;�=��^u���m�T['�o}]�\{[����I8<)<ީ�����4%n�E��N�~�~Y4�c:���G��T�a%-�_u)�:,�����D�����L�>�Y/U�-���ٞ���u0ٜjBe2=8��;��]����=^	�豬��vџ�N.���Y.���X�~cT��2�.,|�gѫ��k��r���~ԵS�%�1��w@;^�
>��2�^MwKHtas�Bօ��m�sb�
+��Q*#Ht��O^t��4�E(�j

+b�y�>~(d�09��N�:bN)XmD�"Y��\$�MV��
�K�7�>��P�1طit$�
+P�TSWF��.Wta*�Ѣ*�}��7[�BQi%z�0��B須Ń�ʼn�D#�
�QnJJ����0e]p�lo�>�����*~i}v�LŵPc�ם�*��‰����(B��^MS��[�9�01&��zw'B�
+�_Q�b�
�1���tſT��A�`�.q����3�D
+�M���)�
@,^>?�t]�=��k��uAC�̂B,A��6t�
��r0�����:l�N�B�mRA4�2��
�#�]O�k�@dɻ��G�o3����)�T:m�X����hdb�4����R���)�(
!5�����K��'��Ȅ�!��U��Ov�4��69x]T`N��HȺ���rj�b�� }
g
��m!�J����3ډ���M>k���E�h��
��G������>)�#C^�"L��
]2��zR-�3�&D�K?u�Y�W3��=u�.f��Ϫ������4#U�����Ⱥ�0f�R�U	Uے���U�{U�,)�[�l�%݈Sy�k���l�c��z2���[#аd
+D�p�^*�{Q
+�Y�
+)�"�T���������.ye�}��	d�
^v"kB�"�v�N����Ua#����P�U5�E
)�6�b�k��5h
 ��n��:��qUA쒂�,�
�� ���ɕIzO��c�K����/
3�G,�	WfӦ�oQ��uB�y�@,�^O)�䚕u��q�&h1����W4�bvf��34�)k�����~��:�%��h=�vշf�ޛ����
ȗ!���(Lʥ��ʄ����Ě����{t�&e"w�g;&x�4E}%��}�.�+�;f�?��^cT2]��֤T�Y������*40��pn�`��_5=�^u��h`�dհ��l?����k�D�� �#4;I�5�V�mq���ۙ��e��W/�����5W�!E�2����@�8j�*!u��i,Lqʐ0���u����	90Er��HJ��X:��
��
5��C��Y�M"N������\��
\�_�r��!t^��N��N��m-�A/��T�.+qW��#
+;���fnm���CR#����j��o��
b���$]��a*
�I�]Qu�O�a����f"�O��c
�k����nIG�Ȁ[�/b��U�/����:�/����Iqs��Ȟ�	����'�
��Pc���svr��<���<t5Gl�\�z�i�u�̸����Ȇ������;3Udzb�4x_dU��ä֗��N�ap� �I�ՉrWh�z�w\�̢���H�D�xw��:��-mf*0�N�r�=˫P�����k5��]�W��d
+�}4/�1ӂ7=:O,�t2�!v}K�]G�	n��	wn6�@dr�T��㕑��Id�
�4%�(����%myH�j��jY8e���
�&1U������ʨ���˖�ٗ	�����i���]��_#˹P���

n,wEל����[�:�9�f�S�H
��������[V"�蠋E*�G5�w%�xq���AēN���إ�&j��E('-�ɧ���x��%�-E�@Kg[$�m��%�'�%��M�R�����s��Q�T#�J����ll�e�3��
F�(�{�qF�_�.0C����ע�8�6�U�L�#��p[�!���KUA7U�ά�eӗA; �J�EL�ч�2�$�+魓W
�Z�Jt��3�tr߷EȕԐ�J�����{����)�h��

+����fA�^
<^���
�Tm�y3��
+�f�4�	��c��ld2m�JՋ�
.m�w
V�,�3!v�
A}�f�j��Y5�"�]۪N�[J�������*�	��5A̋�y�Kbh�L`���K�w�K%�uq�X ۙ�p195��9Q
Hv���V���H�R�1W��`3�@�=Xz�g�sA��\k��r�k�����P�Ⱥ!�
�†�����t)dU>���D�}�
�kƕ��8�-����&�ߟ�M����W7�\�|q{��뿜�}w���ߝ����������y��K.��|gݮ��{��^�t��9M�]gSy\�mp9=��t1��ιg�}���S+Ѵ�}=#y0_�.^}M���Ͼ���3<��_=+��-lQ/���BB�����ߝ��2��Yrь\lG��
	n�CW
;|��dM��p4����Ѭ
2cs"o���%��}�:��uy0+Q����:�],fdA�ɾ��@�Q��>��Lb���,6It��QL��Z���⊹֣��91����
w�"
+��+F@����DD�����V�*h[�-��)Y at eI�,$��1 �x{7�4���IMtN�U	N�@G��u���>�c,�*��I��/amkѱ\
��r�~�o����"���
�9�pZ~�,R�]�Y\�]
KA����>nl�}Czπ�3�E
�.�w��0�Y''�t�\
�K�rxy'�ݦAפ�)���{�Q2q릅�nʬ��t%;t�� ޛ��{1�ъvQ<��<5
Gq�ǹ�J���e
# ��Ӭ[%:����f#[
 F6��
��{��
4�`�Zk��:!�
$r��kt2���
�:�9��.�d���F䆘�!�t2G�Hꮮ�T�1"�W�c�~a"��5!`��/�\�*�?W�Z
"
+i���6�*G���w�@
����4���+��G�
�<�: ��

&�S$6
+�8��l��
�� �� U��T��SS�����wrA�K�BL�Ut1��2�=�k*���i
�4�
�b"��X|�����=t�=}-i�n�ͳ鍼2�$Ô��+��
Y|L�
���^�s�Ul���� ��q&ĕk$'lQ��;q���X�i�?�u4؛6R1��`�d9�F:#�6�J��4
i�L�� ����v �|A�c7��M�ꈑ����
.��ljv�3��	~#�)����05G"RH-����uG����m'�ɪ�㭈���
+#G��v;���L�]6ҁ�tF�#�4�Tr�p'��։S��W>Z�9��.NT�	PS��YC�H���LH�D���c� �d�j~��\�|�p�a�4��"�
�Dn���Șn���M˨wW1q���7̃�w�J��BD�(�r���J��T��]'sB�S�a/U�Q����"*:yB�|�9����g��5�7��q��\ǹ	��8d
�����
+��OZ�t
+�'ƒ*��	�
��J6�� S��o���h�Ry:�k�o��#<��:U)��i�Ê���^��ȶE�5�%:�o�<(iJ
7,�+�qY8��?�ʼ��Z����(
]�3�s�i��^�)������Tyr��]hWf�8e'��6���T�-
�X���X����6.%6�y���b"�U�KXm$+a�:�<��ʲs+�T���aF��}�X���^M֔���9���gd]� �L��'�VC�Հ�g�B.��s~RKg�z�m;"Q�+ί���S�~��*n;an�.��2To���	�!�$�#���g�鉰~S����ͬ_;(^��'4;R����m;�4$��1^��K��鉹@�R��
d��vUy���h
��I��elq�
5h"Mss� 9�7|��FmN�m�-��M�;�8
ȶ͂�V:@�;

�#�R
x�8\�8�,�ۈ��T�j8�,C	A�U��o�����
3�@���r7T��"�����B�{Cʄ�7aC�ҳZ��N7gDl�����ۧ�vw;�t\
���T��H�mF�k��T#k
|o�����,�zf��I8t� uv2�ܴ�l
</d�w(h �Bl�Pb�fHd�F��]"2�}�6�I�(9�ȪYUQV�8ym����8FQ������>��q^��Ȩ���a��3�WUa8&�L��Zfd,z��Zk5�E�_F�|u���
�u���
2��U
�$#f�i&97X��$皈�G-)|�db�~�����!9yj'Ej��)�Y,,I�!����{�b��0a5�R�4����d�ټ�$i'I_-�Q�ȝ��"x8�2V�&�m�i��
04�аO���� ��Ln:	�1��xs����M�SY�@f������A�c��^J� �!KN8'S���[��D�p,�
l��)��;�c�o�� ���4�h�ُ��Q�D�
Ґ���4�V��P�5>�ԓh*�$f�-0~[
\��N���SA��T��oL�M��6@
���uV��4g�����e�R�.�o�n��
oͦ�dXŪ��5��k��J@�,oL�[�_������螆&WN3�+<
P�8�|"W�7a�_d
�؎�{F���?���g O���N�xc�ģ<T$�YI*v������kC�s)�e��C�&U%O&I��e��b&�d��گ��a4�EU+0
��٤d�lHh�M�n#�Y8��kW4�;��,Zq1��X�>�f
�12>5�������O����p�F!2��)��]ۖ�{�ȇ�(�&�;�8��
���
l�s
�!|7�[�M�0%�i�0
��e�%�}P�Z@�S6����r��|R�5
n�P3�އ��)���&]�adr�����ψ
�"2I5��\!f|�<��u���[��=,{P�d�Jp��@��1�
վ��K�Wd���DF�?ydי� Rq�� ��,ҏ�O	�޺�v���1��q
+
+	�n���4�DX:`+��*i�o��������-񰍯��Sf������mli
�7;Fkl�fJ��	��j�����u��
E�#]?�
j��
"v(�x��d�K�����t,v>�(��1pK�
x�m��<�zlQJ|�^췤\;q��%w�99�D�
}�2�	v*"'1���<%Df�l�'����.���j���
��ml�:�2��4W��Ǿ-j]i��֑|�
 ��d��d�q#�`3�g�=sr��*I���0��.ߤi��U$
�|����8xH�Il^ B�� I]o�����a'�D��3��3����E�}Q�R�@h��C�ƶ�*ZHFϖ
K䈤-�s�!
BS�Ů�e=t��!ň!(aܫ5��NJ��������@�2
�3r���@�%5-p�½Þt̷Z�8w[l3�{�[�[���
8��d�|ޝ��VD����Z�j
f�f	y�hA�y��M�ˇ��	�ց���*C,�` 9���+Y�2����!
�h�B69��l���W����os�Dȕn�5$F�>��0ax����nڊ'D�4=�'"*�Ǖ����bv�j�΄�}��-���ߒ�������ȠP�(�cB���qa��41g���
V�
gpQ[���cF���MVM �\3Q��LӬ�D
sw��(�n��8$�d��'�=�a�G܌ޒ��ÎĿ�M�żh#�t�,Ӭ
ŠC�Fclq�
C�?��J�N�, ��^%`�1
d��2�*�
����z�tӸ��d��I���A�D�X1�o�ȵ�X_G �d�	�s��V�"��*��a=�.��>j�d#
�<7z7
=V[�
-��A��	f���6c�.b�3�e
����,[]L�t�Ã��LF��`cH�(&�g����5v�y�d��Q����Qℓ���#	���]�zkJ��<�D
+�
Z��i������}�!@>eS�^<��p�w�1'Y�`�_���=[�M{
+cVS��L^i��'��M��ş�ғ
���5e�l����Բ����1�zm;
+^0
+33#��ۏ<��h�#)�a)�
�܏���*J��4dQ����3�Q4d���BTT��mn���1i2a��NԹifC��e�LM��gd?�p�
m&:ijMOR>���r����W2�3k�;K�V*F���/j`S��v �ոi\գM��K1�Qg
��K�@�O%
/�ɳ�P�xs��
+2
�L3�9V��)���fڃ#TsNX��^cȦ�T��UIj��cCs����vn���J
+L�h�l�LVH�w�H5t�M��<�
,�������kݒi&݈ۘs?�l>��bW��
��#{#���U�_![,!]��WX�_��������M�7ûOV�(9��Ɖ�73�&ay�	���E�A5�Ħ1�.�"9�Bl
-*�ε����R*ǡ�{�:E���L�|�7	 Hh�4ҽ��Ű�wU+�P�H�M��
+r��?��c�X�|�w%�,��2
|p�Q�v��F�����t���������~D��q?/���#��H�Au����j�w&[���Ȓ�l�w��f��lڰ�U]��7K�X�њ�J%|%�Z������k/�0԰S��
�Y��˯��l�D
�%t2��T�J^��t�#�nr�F1��x6u��6���(3ӊ�41!0*[B[
�z����,�
9�D�h�e�d�f�U�^�x����J��e�
]Ņ1d�v�.c
 Pf
�Ed�
��F�K�,�DԘ�j%*�S#`05��'�E���U�M��t#[�ޕm��V6F� m
gC���l�V,d�0Z%�4k�h��H�i�h(`|5X��6�]���*�J�N8j%�����m��Т�4����+�٦8Oq�0�A�H�}[����ₕ լ$%:*�C��^��D��`�>�Qt� T�V�=���m��#9'�YC�l�$ID������>%[rV��V!x��̶K䬡ZS�m(X0� 31�a&�):E�
�� =���W�!'D)�-4+�@��ec_���DV�N���4�4xj
Q�!���*]H��jA�nB�?�v�(�6Mwk
+V����|qF���|F�k��f%���@TQ��z
�
qD�Ш�
"
���ͫU�^����SD�2!T��`2>ز�:͏�v�vZ��h��8.����]W+�� �=���
瀞�����_�%�>�*�dή��5�x�:��̣ ��^ZwD��t�f
̤N��TP�5[LdM5B�L3�U]�ɗ�	YI6���*�i,2�./�}2�3�u���	��buX�
�"ֈ�O�I������Tf���1��n�U�*�
Ge��U�B��D���'(��X����9�3��!�-��Y��"X�r5[K�@�%�>���)�
2�C��
�ƀ7�&��S��;.����<�d��JW~yv�$%
5��7;�]&*��\xD�L��Y$��]���k���"��P���,��]
�J
u�8�F�"�&�E��t6R�pq����WEQ�lmy�,F�1�2��9��Ŗ�b.�
�
j�M��DP�qTT#GF��SQ����wρ�\,*�[;�
QWQ,����
2,����e3u��d��i,���<��۳�J�&������p��Q�Q�vVSK�1��@���D6
�Qf�d�	��\���uR^�މAx���jLLK�bW&�e�E��n�� ����@,uL��a�
�
�~�y�� 	�3�l&�Y� �lH��d����V��>�Ӌ~k�{d|M�B
l�:��2��-���<��ͮ��`eW�;�h���� :^�}����&=��<;T=�^����� 5�aO��΅OR
�"�0S����>�3��=�t���+�š�?L 
����[��߫gä1��i����>�e��/͔�ώ�y���v1)�)t�=(�ζΦ�h텴)`^;cm��{�mZ��m��{!nJ�cn��{�nb��n�g���^���}�k���`N�A��	���(��n��pʷ��Ȃ{`qJ{�qb{�q]pwDN,�
����B����߯0�#2 [...]
+��
(��=A��Θ���>����^���*{ �J{a�ʱ�
�'8���0(�a����*��^8���^H���v�
+E���J{��f���K�P�����pC!7�
*=�
�E�=_v
?T
� 
+�|w
Q#k(�`({�’��(.�]�D����DQ\h<Q�b/DQ��=��x��(�k���g�,*=܃-�{���.v�E{ �B'�c
�2:�ȝqF���(�֨�̻����5�Q|�=G��s�軣��\�;*
�<
+�;�(����<�
ު�Had��N�=PH��}pHG;#��d��E�	�F*=�G��")��8O{���S����
Ȥv��&���;:)z��Z�
����0J�`
��
�S
+iuw�R���*
����x�B�
�Z�
���b�R�b/�R�vG.�
��.��a
�n�=�KM��
�t������b�����
H���=X����f
+�{�g
+�
��f/����
���#���x�����{�M�`�n
+��)N�
�濹��
,qN���H��Uv���Hx��y~�� ���kӐԯ�
J��ㄥ.'�᤟}=JO��
�Ѕ_b��g�����k'
�_,�:D0軃�.�;L0.�=���"�
*]�,=��ݷ`0�d0��=@���n��

t�G
��XC|oH�n
�>p�{
�5r��{�����3l�@���jx<�lxeDK�a{�3�0z�tx�p
x��K���_x��� �=XB��
 ��b
�� "��m
��`�����^��
,!�A��[i	K
�
�ĶK����`Wpbt��'6�� ��b
��
�R�.��)
�kg�bl�ݡ���
`���$znw,6���,
\hg�b�H��-�.�.ƃݡ�qͯ���
���bw c���� 1�w���c �qi�
el�|w0c�R;��t�46�(�i��@�!��kl]/����ݡ��������
����� Ǧ�ql�X�
ۃ%̱=�
�غ�
�xl�������m�-�����&�,A�ǃ�a����3𱉈K�c�sv?�.v�?6Qi	�l����� �&��
�l��yh;C!������[�!�nW at d��v�D�$��l����`	�lv�FFk���`gxd��l���`w�dt�;L�	{K�d{��J
`�x�;\���
�d���L6Y|�
����a�dt��lR����&�/���@�>���`
D�
���.ր�M�
J�N�L�
��l�P�
�
�<8�T٘�ΰ��a
XyƤ�XW�Kp��#��{ ���*��O����=P�C�\�-�獣G�
����g
?gYԐ:p����8#���{0�ǃUTh�/q�����)]C�
���`�=��]1��ZÉ
:��H�K[��X�s.��=
,����*�]Í
�Ѷa�;o�
��Уm���G�r�D��K
i{�D�1Uww
i�ėH�f�
Kڸ�M��;�I�F]"J�
f���S�n�%��=�Wz�@�6����Ҷ�;�K��j���f��
a]�1�,B�3m�����5
ir�i�m�x�&6�8m�s�@�6�m�;}σY��~�Ӧ��>m:������vF��m�3��vG�6���ڴ�ݑ�����Em'nw4���
+
���;"�u�3&�	&��R�fg\�ai���F�Ħ�Kt�!��O=6��ն9��c��Rm�e�SmvG��q^ê�aW�j���U[
�j����F{�V�(���x��\=
�]mf��ѫ��~�=��z��v°6�c�bm���8��a$k3�.���`
��
,����֐H�0���Ψ�fb^�Z��@�6��vF�6#����K�k{�ĸ� ��r�7���6�s�t=
,�����h��b
�vF��ݳ3���%�5
�{=���z<Xž6��;��1�%��=�
��%��黢`�ݴ����#a��w��mw��h�&v,�!�쁈=ĥ&�=X�bMe�=�ùY�
t��`���v��kh��=D�N�{�8zs���|<���Μ}�G,�’>�w�_�wLO�q�j察}\�=(��`��m�H���j~u݃�m����
�����Q�W�D�
#]`������y���=�!��
,p{�38zX�ǃ%"�ї���`�
+>zZ��7vFGk���dk���`�nvG�}�����(��`�>
�"�}�n�h���x��<(i��1Í���ރ�v�
n���vHvF��?
],č�;�8�XC���c�֐�ǃ�8
�&>XҮx��vG�cWLq
��Q���θ�&P-����v���]�z�
_��^"�ۃ%Ƹ=X���hv��.�H��`�5>F��6>��o|Lx�8n`��i����`W�q�`�<n2����c7������?>��=�����%�
+����8�6�%���b�ۃ���m�-��ǃ"����1ɭ��Q�M�Y⒏�"��
�;6�C��&�.��ǃB�Lr���i����
�Sn����
,���
�r��w�+"��܄�f��/P�!�ᖏ�~
F�v�u�D/7Io�_nvG07Io�an�Q̇p��1�K$s���X��b
��
�gn����
�in�~�j�܇
m�
ds��;b��3�@7ǃ%��ї��`�q>
,P��c�X5r�a��
��
c����e�%���1��9c?d�
���˹-yt�k��bn�����׿�~�Տo����������k���˫w'����������\���w�dJ��9O�%d4n
+IP���MU%ّ��}���y]�~�~v��[���V\�8�DF-�|R6��!rljS�@/n��&al�[�V���6k���α��>������)�?L�\�z
�/�����ݛ��ܝQ��	��}���<�f�R(��R�#�!�2E�++�+����>t7E�jU*(��]k��:?,��(��v{��{J��Z߹kHl�}A+BU%F���Y at DňX��Dϩ�M'��
A&m%25z�%bA�TV�0}��i�3���~R�r�:�O	�ɓ�3��<Z�S����sY�S�tJa�6�2c��͑D^������4{�>MZ�2R��,H�INj�5Y5�4I�b��&@��@�sF7�}Ҥ>�*!��)����bp�Q�E��G�ET��8��¢P\$�"lV0p
�F��%� �J
|� �֨p[��@�I
k����)�fY��d��&�S�cI���0ϾC���N�x��+~�A%��K,�J�P���'���L̘�:M��@䩰�D"Gb�  [...]
+n"PL
X���	w�OB�Q���I^<{}?�s'����~
�;������7�_��������77�.f��ݳ_����g'���;����mg��ܽ�y���� &1���������>��a@�`�0�"fd*g��A%ۚO�?唒i���)�>}�OY��H�*�5�E�R Y�z��D ��0�	�ùX��� Q� F
� {�Ϧf?N�J;l�&x� ��E��#b����L}3Z��X�}
�
'��x�������·7����]�˧\�[n�$��4g��TK�d
/�Xb3��=!RU`ʫ�5!ǤV��a�N��hM�	^��3eZ�
����S�M���B�%��M��l�

|W9IMD�������)#Jii9���~+��[�'���j+?U�]V��LP��
�((�j��qf�Bq"��r��<�e�w�5'x)Ai,A���T�Ȫ�I�T�kz^q��5���E%B �g٩@3&��Ț6�{	��5��g�0n�P�w��JO���2jQB���c�[p4";B����;
�"t�{�vF�`�ݛ�'lS��Ѥ��ha\�I`�|�Fq�
z*h�
���~
Ο�?��G?���Ɉ�J@B#	�&
�KTˆI8n�dȸ"XS��"rc�m���e�zko��Ug
���׺�;�Y�Z_�iܹR��m
���m�z�,4V�6-�_�|�Ͼ�L�޾q_�}��1�%�&�� �J�>c���
Ϯd-��(��X�A�;ѱ+��9=尡L�ǚ�qˎ� [...]
+
�$�H�W:�YdQ'u���69e�s ��52.V�g���P�FF;I#R|_�0�z���MU��yS92+�yz��a5�bMwE�Ra������͎���
� AH�#�!�,��$�O��<
MMiRXMn>*�v�2��k�1S�� �
�ո��
D�R2����s+ـ�\52��
y��*jhΎ��Mʁ�^$/�M�
/(w}�
m��H)|�ZZ4�!,�g=8�U�]Gڅ�oŲrI�Tŗ�)3�� M�UY��Gv�2#*ZV��2����V$���Kk at FW��D�\Bā��4>�z}�I%�H�m��aM��^�	
+Zh��<<�d;{��_�\ �<�
�)㪰<�m��}$�4e#
�����4(R�wP][�l	R�،�
��r�lY.�

]M�MZ"Nnz������ϟ��H�;&HGt5$�X��e�AIi\��
+U��mi]`�!8
�DLd�[�� �7>��"U���|����,w
�'��b_�;?)[��46e�
+a�
+c&���f�J����hƚ:�𨜓

����(1lD`6͝lq���
��
8��;�yU�$N�ؗ�$�����zNⱄIU9A����0�.�&��$��*aj�(*��:��)|֋$R�2u�Ft��q�
+��=�
/Re�Jn5Ԫ��D�'ȧ$�{�@��Qe+h�
a��Y!g+笾J6�B
F�'8�WtBߡi�Q�!X��簑+�`��+���^�yi1BZe�aHZ7�HU��[��HL �����U$f
.C���Ap�&K��zk��L�P�#�A��
4s��%
�_��V!�̪�0�U���̬���*E�eX��
�������<��
��L�c1�
��
߉Z�>5�
ы�2	z�9��,K�"���5
�JEy]�$֋��tQ�d�2�8�G5v�h��&�H	͏Zd�_j at W+kr���3�l[^ �x�H�-�_h��%�'��|� @J�_�f�J
@����:�I�Q��lS�c ��q��eRVrF���� C�$������'Q
�H��#
++��6���麙 �!=Z�so��ue���JtR���AW��t���
])�<�~�n�\E
�Ď$����ߌȬ���@C�
'�(�n��f�$�A���
�x
+�����
$ə����Q� ��&�+
�{):-
x�2q
�8驑��IcR�}���q�ٍ�G7���Gc��n�98U4Mb%6��#��cl��nE
+4�~�P����g�I��O��]S�J���|Nu:���j��Қ�
$(/�pM��S
'>���7!򾢞�� A��48�N
+��E⍬��!��U�R�rR���Yw�/n/�ڸ>;����Y���P�4v��w~���މN�>�Ӌ��
+�!W5�����Wk
�8�hQ�M*7I�2OXE���v��6����]S�����9<���@G�
+����-���g?�b����)�=�&���Y�)ҬD���%�fBɠhVؤ��|b��W�N���5�6��4�q���l��^��
����
rAq��L#��H�p��-D�6��e�'X9��gE�wpZ�
*�"�d�`�,(0�\�2x�7��b�
�
JX��E�ڸ_�KD�O���
�6���zBw��Zj[���ꪠKɡ���=��vd���VKW��.��A�q~~����_'&m�L���Mm�fo$ l1��
�

+��,��C�Dx{-R)g[��I�QѴT���ˆ�x�>u�k�
Df�`d]�K����
-Ó����ZD�H��
 ��V/����oMr
�d0���R(eAy6�w���'��O=i��!��*CT��:
�\Y$��!���5�p��
+̲?�Xa�J��#BIx޴|"d
@eqM�ACAY�U]⾘��l�v"��~D�18�P�o��$2M�b�n�Xu&�kI�:6�~��R�E{hQ"�d���R�t7�J������z9� �I&�]�r�l�}4�
y��BP�[�S��.�8	����1�W���8��^
"a��aX���:�.,��'G7�mP�ힼ��(�
=�[#�ϱ��	��"�Q9� �I�bۜT��l��|A�4e[^���Y��9(Ŕ���H�
ky�c���g���׽
�a�z�׋o/���r���{��������7�w��;�͗77W�m�Ͼ���û�Wog#�"����ͻW+��b��ΓA�C"�T%b��:��6��e2�'Z��)HF\�㤍���\I�����Վ�z�#c$�Xnw)H�f�Z��E��C�z�<�>�U�x���p��8
�i�sz�K���y)
?�6ÊQ�KG����L"J@�,U���M��L�b���4�8C��8�
+I�$J:��.&펾R��`�L^B)�H�},5�(���D�V1�e�ޗ5P�~}��1�,�&P��1>���gk�}
+ב�B1#£��Y*7�q�1|��������	��Ӂ�� f�R�򙮊z]�UA˚rL�d�M@�>�c� ʾ�y|
4u��J��k����
�dM�lw��U��M��Dvt��w�N�䥃 �Pc"��I��$ʥ�6&�M��0��r
���\б�*#0
lG�D��Qe�)2��K�+N�fT���|M�9LNB�j�����75�֦��P���,Y�u��9.D��
z������n��-8U),/Q��Ux��Zވ줸2�؈ �1tU��C^;����k��F�Q��Q�D��k'j�K�
y%%o���I���RWk E��]��5�6�Z�QIK}̙�����b���D��3!E�$8�:��j��v�y����[$T?9�8
�YMSPׇ�LfF�(����-B/�CCB�]&/+�&�Z�`�Ƚ���/�e�8D\������EK%W#�"���
+"BH^,.4 6	��bfe
��J$E=�����	of��ޏ���Q�����HBk2�\N�%������_נ�Ȣ<�̯�����:F�|f(�U}
�����L)�sʸ\��B���Y�AU߷�4H����%.�&kB��GtIE�X`���y��IKa����w�Y�Sv��65~��vK���9<���}�Z����=X�(Z�Y~�!Z��^ċ_�aϥ
$j�L���~���h�$
�C�8�70�qגU�+J��!���}��nҰ	6v�r��$EZJ���S
aN�5d[:�TR��)�� )̅�(	J�H�*8�
V��g�f�s��
R0{Ѳ�Ʀ>��Ib��X�NȀ�"*"1�Vb���׈���f��w�2�{%"���-��L�U��"��[g�"�+J
+�S�
7Qnļ�1�R�
�佔�obm��Wԩ�w%�Ë�[� ߦč������'y�Q�
+�'���k��m�F,�v�
+Yr�r^��&�3�r}����؟U)"���	���@� �婵�'Y�"���IX�V���d1 �����-
�֔�%_ŽH�;]�,�î ��'��Bf�R�&Y
"
'{��� �6�{���76�Hx
+�-�Y�Z�&")�5�B�Il��0[��`-r�u��J��.S
+
㺋����(��E"
�."�,G�5)c
+l�����s�َ8!�
?���������Ȏ�şN���{����r�
��E�n0Qz&Ÿ�N4^�=+]�Q<N
+�Ҍj=U��D��I�8�~�$v�������k�x�5[�(S�Z��&"�<\T�v���O%��O*�OI��p�i
^Ճ$R��D.9\oS�(Ec�
]��&�@�$9<�Y�� �y�f4�ux]
�$E�=�K�b�`8Qy�E=��Ȋ�J�3
S��;ɶgW - w�'���Z]b7!?;��zS �C�$6
+u"a��S�|��s5��!�Q��X��$肪
+:D?Y��B��s�E���
+���:Ą|ʦq}�.P%/���Œ�
S��N"�_���(
�Ȩ�
+�fY1"0��D� ���I#�ٙ%#�Ll�|%�����J�l7u��\5*�a�e Aof�\�΅�)����J�x�H0���2
�|�g$�:���4�LͮtC�Ҳ����B��H&��j#up���;� f�
G�����db�#�j>X�d,GЇ|qR at g� ��� g��Y�Ns�P?�Iň��
+�
Q���/���
�ɴ�
?E�jXI�����;�%�
�lҭ:R�Kb��$4�C� &�*#�g{@M: uq��V�4�͢���l��3M�hH\��-�?U�2ӳ��?�Y�%wn�x�~lֳ�6�C�Nr�W�p�H
���3Y�bx,
4&;���Z�\g������6��""Q�
+c)���kh�
+
+d^RC6Ws��j@��b�W/R�4����ԝ'�oFh(�LM��
�2�~
+
PS<�bն"}äZ���1��ޅ��}�Y��NHhTv�4.���씭C�Dà+�-Z����@V�Tf$�NG���tӆQO��X�g��Trb�$��j;M�D!�H��&�
�Dm
m�!��T_*'r��S�Il0�SO�
X��O�ac�d��:y��TO�8��{��.TW%&!���EEթ��!�%��_�DAy�Հ���
i�F���RT�T�R>o�B�0gҀ���Q"Eٙp�[G��"�Vu���
+�HEc��
�I��a��E��h/�g!�B=�d?շ+�j������Ly��yY.'��R3���H6@�
+4
x���Ŭ�N���XT3"
�� 9JlᙒŇ�
+�ԬH�ĎD8`�+�1}A�c�6��G8UK�Fκ+�H���x�r�+��&��ۊ�
�)vN>	�,Ƌ�S5섅g|�F�Q�^�q�h$|>��4�dz�#t�s��^���W��5�$V��&QvGk�
+�p|?�t5H��e�
H���%�R�}��d�S��jIԢ*��)��
�4��5�8��dTw9���*n�j
(G�����d��(�۷ ˭�*l�PmX9��Q�k�E���B�#��t������)���m�W� أuV������Ee�w�����uElXl
�4��Q#Eы+��-i�bOn���&&9��[�A�-B�����5;8���nR$^C�<GWL��(Pn�b�$6Ɯ/9�Dz)H�g�o&��OlU��}4b(�le*8��L
�u$1��
���l���-�S�Dy��r`�>����a�
G�Z�G4h�i
��V�D��&�Λ
+G:p�n�e
4���%,��(R
�bu+�)�x��Z��$�vgR�X�c�N��0CV|�;)��R�T-�R�?�V<��FW� �X��hMi�`�(�$�'x���^	
`��.M#}�h��~�b�y��$.	?�Fn���
!S
b����#%��͑KT#]���bˊX͑ED�D�֐8��*��fO^W�ܻ	
�-�C�!��Hud��T7�U�G'ɺ8r�g�q2�4Н!��K�p�&
��w��b�M��
FJ���

�������.'[�v�_����4��x��>�ق��Y�u/����v|Z�*�E�#Y��
� �O�<��iؼ4
/T�
+KD-��2��
��KW|P��1�̔�/�B�B�<�I,Aʤ~��(<�I��F>r�g��8my�ɭ;�.��T-�r�~���z�����*8��ᢟ}MG������fK�(*,E�H��g
'@Ñ��>��(��h�OX#��	�Vn��Qb,��?{o�$�qf���;�ٵ
#m�@��X�M?HP��4(�Ҵ4mc�B�HV�XU�Z���Y>�Ȫ	T
�R���������[�wθ�Gf�^�bm5����d��O�L.|���Qt"�T_@�����4�T�0*о"��[�?�w�H2
fC��Y�u1~2�0��8Ӊf
�61bx���^���1
!r&��� 
$c�]*7
�*b`��Ct^�
$Q�J7��$���C�S
���2�L���q��_�r����+A�A�t����&/#`�{��%�8����5 I�7B at s�h0��8��45-�I�/
+�3ʬ���PX���]"T����Ǯ�ƨ

�
>GA�h��o�G�7��Е��q3��̣A�3P��Z=G���M��AtS4�ƌ���������b�Z3�
+���"4�
k
�G1�J�g!:��|�^�4����O���h���P$[��de�x*9���3��㞂0b�)�ih�!%�߀I�2 M�Ȭ��/��*L� W���TX�
�a�d6χ�~�Eü����Q/�����u(� F��s�c�![TST=�c��!92�U0�a
)u��Ps�H!"!�	���R�`
���t0`͑<�nm6
�L<yI�VU���2O^w1���
?���45�il�^��To�Lk8yӠ@��n}��įT�℠8#<��
��A�ar���C�F�@Q�2�0�����[t��G�Yf��~Q8+FUv�[�wa����N�Q�y �t� j� P��
�CB�HaW�����+��������Y쯚a at t2�V�$�
�9J��H3W"�0J|���B}��0��I�{��h�Ky�X����sj+�D�p�t�}K%�
0�
Kfj7x�m�I7��tG
�n�AЄL\�k���� ��2�RHj*����C��[�E�l��I��ѻ�C�j
��)��;�Aoc��	���;�?�j�����6��ۘ=oa�����ۘ;oc켫���;�9�l伍��6�;�7�jܼ�i�Άͻ�5ocԼ�I���;�3��K [...]
����
,7S��*54�ԎZ��
ı��N�?b
�������J4$��iɍT0�'�
��V�̔�թa�,��Ȯo�dž�Iu�A�>
�c���A�8=��d�9������h
+mvq���bY|
E7�#1"[b�I�D
Lipܝz�0�n6���xh��'�&����`B�A��=tY�d"��U��D at W5��������}�0�.�,���?C�
[��ɦ�؋xZ�6"���bCĶe��AFߪ���
X�ΰ
5.wC\ DVBDr���llnA=9�iO��<�9�F�P&7b*]˸���XC1F���
+hTy ��
/0�����GW�8��Sv��ֺ
��Vr~����ٍB��[^qQuci���Z[G�,����4�6�N�Kܶ�:�����hCzc1z?Xх :�N�2���ۯ�~6�惮��p���=Y�Y�A�
!��>QՃ�l���N��.�X�U��	�
��۝b��eE�K�J��s҆0Ĩ��&�a3KԨw�I�2F�]�rOkE�e�@���8���G,V�ӷ��2�VQr�M��Lf�A�r�dY4d�u��t���F��(�$�j��h��� bzRg%�Q�;Bw�̀Dz�i�>�Jd����|��Y #�'s���i(<W�1*�1Ye��\�X@����+p��W��;gh��J��^��3���
�"ub
+y��P�}��n�l
+35���ϱ[��:�z���j�iֹ�D)d�P[�0��CuT��U�uL۫�J�7�
���n��&�
�D�e3Q3
�8���Qa�ү���
�
GWd�0��T�bO=9&a���Mai�0�A�3i@��Ƕ!#�<GP��A�H
2م��KflS9V
��{�V��O�N�f"��
�(��#8�'J��Ye�h�
|<#��H2�Npz`�4�I�\6��O��,�M��
P?qs��ʖ����
��_�јU[z��wu����\�=3�$�'
69�)���,�Y)oNd
�
���yd��
�"S��
���`c���
�C's��1a�yYh��K�ɡQ����$�ls0
n��m�7�Z妣q����c�|&��b�4d
���s�+�$ ��a��΃Ͼs 
b��k_A�ǥ��mِ�@���C%q

(	�6p�:“ի�Alhp˄h��ڳ�
��´]�\�aѧjV,�P4�!�R�q���0�~*Ҩ�7�L\�htm-P��a��x���=6`��*�U�&�G�`d
}^���k�
���
t��U+�a)H�2����pLKn�q,�.�t��]�����d ��ow��
+�[
E
I
i
.0~vd�k�
����Da@ꖕ㱛g٨�8��N]��OJז
�ۍ�!�9�����t�FW���#J��bۡe���6n\9�U�	ݒ7=~A*g����/W�N��<�$~	�5��Y0�`����]cb�X�f&a�q=�$�
+��.Z:����F0$�,�ف'A��X}�'U�r��� Nt��B�wT��,��]����-�LDд撌��$�ͽ;�*��(U-k��7��=
+��X�\M���;�<Mu�c{v���k��䫗L�2@Ƒ)�Tݏ0s��d-�]j�j�ةzT�&Ir�8�Ej��0��ۺF$���c�Y��:o��;�Mf���F�y��$�5�n�N���6
½���.s4���\6d�ڮPV�$1�mD_�ҩ�qI�U�o��7�vԢ��
�’$Y�r�h�Gzb���Μa�ƶ
��S�A��#Mo�0��~�J���d݃R�����
��H��f�P<�f��hf�ykVi
�z��X[�=�(�p1l���b��@�0xA׫��O
?�P��&���\�A�!�I�-lK���lnB��_P����U��"�D��ܨV�z�B
{���ة�l�?6�8
���ԙk��k�oI
�N~t����E􇪳n
+f��<�\���8Kw=���I�R(����H���E���<D���ƛz(huĈ�wV�-��L��Lqf�M�F��-T3��|羴@

����
��!��t��#|�1��_ce``L=::V�3(�|O��?~r�-6U}2����7��`�%~n
�l���Y�x:V-���La�0�}}�Ae����?% �(n�V�1j����m�>�D�m�g�Z2��xn�󄗙�k
+��%K��vT
)u�}���
��X�h�	
����Gk̤v�
V
���.�`���/s�&"ʪ`0��A�
́�+�<f�C�mٛ�_
���[
S�1�	HLR	�*�8���]R�(�Y�X|�c\8H�Z��{X. ��t���V�H#���6	��0j?E����@�)
+>�Epa�4�c@ɢ�$ߩQ9m>~r��B��K��Z�����I�*�
+S�0�d�b3�QB����C~�Y/h����cl�ҼC+
+��<�@ł.v���sd�}�m
i����H�6�|4w5�/T��^>��O�4D�
\G��:�K`��� b�
+�
�adi����D�g֯�`}�do�J\��7��]�6��`�ǎ���=mW��_�@��0������,�R_��Yrs,�VA^B�w����z0�3y�
���@�)�,�F�;�ڦ{1B̝��ո�/NC�m��ƙ�Y�����i�x�F�|w-o�$�h�9����$�Ŷ1��um���IW��4Z�-�R��D�
��6�����a�S��w�l�9�䦚턹RZLr�6�E�Ts�L��Ա�h�j�(�P27�>��a�x	�.��j
�
��}S�Mƽ8���#�c�W���"%/h;��X�HS�V,i�G��Ԩ��&E�o04�]&h
r1�����z��4�M4��F�f�\�yVD�X�ޢ���
#��:)��%mO��2˱<>"�I.9�u
+�Ҭ��Ɂ2v0�{���`
r�5���d���bs�}9��ZY��`���2|���~�`��g���0]��>�g?�܅�?�~���l�|�e0�x�
E�BCc`�zݮ�
���9>k�\2!C�G�3�JaؐU
�xI�!�`tuC�;��^�.���>6("���{f��E�،�a ��\/���I�U+��f�;��ޕ�@�-�3ಖS�X�&�^�Υa	�ւ��t�#;�
+.�>'��&�2�ʂ!:�foPrS	���0�� ���v�Y��eL
5μ��oɱ
���q,�w}vqt�Z������4� 
 %ن
+�~������)5

�����	
6�/=�0���U:��阫���Z���1F��5,�G$5s��$&�۬‘�T�V�-i|�7��)�R_Zyje�;@�XVwo�#Vy�hE�,=LP)�1��v"\�Y�
@�Y.���ߨЛ�
�)�j�YㅈϢ���߇��S����k����`��&CZ�����,F�QC@)X�r�ߴ!D�V�B�w�+��*\�|�"�.*n�)i�J
+��.?��+�@���1�x�( �>GB�<F�pA�9�eVN�lE^08����*�����)mn�9�Xk5(wh��0�߭���B�K�0����ѫ�C��5%�иJ�j2á��f9���
H8�%B��J���6� fU
+p `;����`pn$�V,�.��I~��yoMf��}Q��l�EPY �&�b�C$��.�$Y��2Ƀ��4~H1(�$G��.���',����*��:
m��:�m��>�+��j�Z!]�BF�2)|bLy�V
J��C�p���$��7*�ə���˚�f2q�Zx�,
k��NsS;�e�97Gq��X�;�++DJ;����7�	c�M
L�A޿8L(�`��͕$
�"��@c!�S[S�˪ ,\��j#�elN�<@8L̳���s
cj SW�

+MM��Mz�-��
���*X�,
+
2�ظl��2 =��xH)��E7�
��HldJ��HX!Q�~AZ��^�'��/�i
�wd�
�
+u;XڈA��

�vR�[������Ia���@1>����؁���ka�
�E$c�k@�Wg
���� %QS�̢HE�	��M"bS�Qc��Ѭ4�T&ï���#�����޿&�nv�A9Y3�
КRE
����2[͚�,��#)93�$J]~$�/�H7�>��f��ݜE�Lyp�I��&Ϡ7E*�,����9�D�
+4���Ym���
Av�J��Ƞd4���A#�nl�z�'�?ɤ�:脿�-�4�F�Ɯ/��TV�V��'���}l,�]�.L�h?S�I����EuU�P��
�j���9��
WC<@��ǒ'��Wq�
��94J� �SO�1pu��
g�k�e��z�$2��~*�2
9ʅ��Ш��L�a�b�@4��M��&#�`��Ra�+A����"j:�biw^��˄�����
:�!�t5�	g�e���1.�9�y��y
+k
�8���+q��Y�
	��]"64�j懛K4��Ab2��.д@#��
7��r�I5n�$8�m�(�HT#|�hUʁ�ݴ����
B�O<=��;w�͒���ښ�
��kW�U���
���~1��6�����l�����d7оƻ�7I+V��
���E=4�Q^�F`�C�˞>�����,�VJc q"eM�J���l�>�0��SkZ%��`���c##o�*̛>g��=A߫�J�'�XA�;��'��'G`IZ�s4G���/;(�N(*�Sc
�8Lm�h�
�06
�N<W][sX��
Gsg��-�&.
�FjZ��j6���&P�X#jlj/4�Ǎ���(�^d� Ŭ�T�9�Z��LcT��9^y�T�nEh;Uz�k�Q2yGWWGT=��L�����
�Hp�i*C���440{+�#�8�J �ș��t�1��b�?b�̇+��
+��Z1�߹,��4�X�4ː\LM�.�r�
0�!�ڍ��\��hZ�h�>�mgR�����$q
+:�b?��ۛ"��9�
;��g)]�PU�"�4Iy�Q`"5&����6eW��ƙ�ş:N+K&Ś��
�V�2Q�j�Z�Kj0���H\�I<Q��Τ�I��I4��B���f�0�y4x��*2K���\�Y��N;[�8��Y�8�̗�V��O�:��LQE��-�a�k��3yE�t�]� ��4�4�ˏm9�B:&y�P�kDbS���
�CDpE�uԭ,�r���u��&F��dWYW]~YBÇ�r�����g�V5M_
����x"�39‼x��!\�=��

&$a�k�
��

����6�K�X<
6k9uxRq����HO�5C��Ӱ�a�ŘR�B���
�Ya��>g��nN�1*�`{G�qet�ķ桹�s��&�������6�"a)�f<�5�{pjr�u�'Q̹������O�u���w(��Ͳ9�7K�R��Y�p�:AQ ����ɟ����S
+�َ�!�� S3��'cP�A�����4��*�X��G,H��$�Ac#{E[��f�c�Rܑ�F��+�^vM�.
�uz����g|�q`�YZ:�6�}⎂e�R
d4�ݏU×�99�2�G��e
A��T�>��
+J#��\-eB�ɪRFA�>�W�Q
�܀м�0u
+"���H2�hx$�q�P����'q�+#Q���в�Mđ�
lh~��觰
��..����`#K����꩝M�/�+n�p��2�)�_�*��
Dy�mC�|j�ێ
f1t#y���L��k&%6�_�� �
��C,�a���$�f�Ԉ��T�CL��3a+-C
,�ӻ�"��LNR�jp��/%U���@�k���Nu�](�����TgN[YW&�@�+��;�u��Q��
�Ȑ����F��sm���: ��
�
��>u� C�	�\̕�1"s�i�cE7J{�r<��k�}j�Ѓ���M����
�)B�L�J����s&l	����
�����h�*�:Rܚ�n��(}k�cdo���H�2��S�VP�Q�@#
\@��b<���=Г��~�ᎊfS�S�P���ۀ�TǰO�h3+=b�
LG�����(��PFT��,�
��e�J
+��J,�,?�s�x��m+@f�#� �����Fx˚\Ə�J��v�H%�x�ϑ�
���&�JGu
��|=IK��s0�a0D���(^��gy���u^<V ��QɅ�9�W��Ԭ;�6�j���e.Vs�7��P�����
т2Ā��l;
+�d�]�z�C>/4e�K�t!�DHK�G�š)�ehH(��kr�ln��X��*�W��g:�?�@�*I�ə��M%	�
+R�0�J�
�#�i�\�S���kCh!]�f�!MU�~��
���A���|CJ�>aMp�k_V�.��]jr��іC�/��S��)}R
�4�&mu��1��E�����U,A<N��,u##��X�.j�:Q�
��wJ�+F�
����ɺ�z�Q@�5v.qd�
+I�΀��sl�c���:� ��ټ��?+o��q
+�ÒG���g��;TW⬆�jBZ_i
��82z?ɨ�<	��[�e՝�������l�,dU"��)N#x�� +�����ը ɵlʮQ�ۍn�~A��N(0E.����_
+�
�]q��a(|icy\RPV�RxЧq��K��V���&b�9z0F
e������٣d�.�o��
�.*���mkTو�=�n
�
��{��e�
�K�D�_��H����}�W�z��n>zBV��%U��e�EڽDl��.�eg���A��)��.āחw�FM���fN���4�'S(����%K~7��*ԓ��mG T�i�u�S���P�
+k+��").)��^l׺�:�搥�r���
1��}���h�:����h���ȪQc��햚��
R{J30�Z̬YZ�<���j�V&��
�K96�84�R�Y�p�Wah��1y�����o~��������//�
�~�����ͷ�_]]�D~��U������ei,�XZ�7��y��_����:Y6�χ�`
/K��e7��� �����t�*[����C8}�;����{����݁���]}�>pW���ջw��=w�/?�k���rW��a�灆�Sa��N_�>?�����
u�����͙�q���S��Hu_�ٚ����c�
����|�Cc������P��:���n�
wQ�4{%#�B��I�iHGWyTJql\�)T4H3U�
��5pB�{YI�ת�		k�dR\�C��|P�@T
x����m�
�
+8E9�����t)}d���H�Ba�y��
+��9ʯp� P��>"�C�bZ� ^^)��ߊ�Q�4�qq��8+�B"�fS����M���8o�7[�P�GzV���>03?Eua��B��`&�g($x
+k���������%��N=��.�P�¢f��%� ��2�
�n;/8n`q6�w��9�E��a����ku+�������>_v�RX�.�9�̝����
�Yg���{�X6�(e���l�Nq���G��u�g˱��a�������^,,�mo�Td+t�O�.��ꅞ�J@S��+��B��"�|�C�2PR
咳�cO�`I��
?<cO�<�WN�Z

+�fl�
'�Xh��h�s Y����gO7VŽ�0Gޖ�q�
arY
����!�t�מCC
�m
� �D�VR��
C]2mk �@F� ��)$���!g9�ËO�*(:6s<�d^�c�JA�\ׄ��۟�#�K�4�`�夂T 	E_��S`<���	ö��r�cO��Ћ8�(�Y��#A��jME�w�l$y:��sX
¡�៥9T�l#+,T21A�eW�C�)�Ss9ɻ��B�+s�Hs
�ύHJQP�s'-�*ƪ�p�
��qlC��
-�֟nѠ���������<٬��rv��5�q��,;�����icX~��z�c0*�!
�X'�@:@�h8��%	�w����L�g!��
��S���UgT#37'�av�A��@�&��B�ρ�U����$;@2��.����S������� ��insCVg{
����e�O
+
��B�b&F>7F�������]�)̀���μ�y�vz4Vn� =��84�C��Uŷ.Y����V���C]|��Ś޸m�j
Ĭ��l#�+�	T�E3h�<
ޖ�{pI��hxW�u": � �3 �K�%�(y`��j 30���J�#ڛ5�C�f�X7cbx?�o81�H�p�=&�Œ����
k
�����|���A�g�1����S�K%5\=� ~�.�
�b��Zx�b)��N�E�c����؏��41���'
�
k!-Yw��S�	�
���f�4V�(��>�D2���J���F�3D׹�T����T�a��$�<�m��t�-Q��O�
+
"`�gD��D�ih
���0�]�t�� �U�B�$F�{�͚�
�\�r�;QiB\�aא���+� ��B�Y7�Z:1�)�U }*�O�vJ�t��8�oA����Um
��NL�@��r*��HAcG�:� f�l t���2,��h���GqH,�,�3�M�^��^LM6\0��Y�NX�:Y�$����b�% �Л�"�*�(J�?ʰ�
����S�w
�*�!M�ҽ.�a��=`Wω�X�(� ������d؇w�&{�"f3���xxP �Uǭ&_��ߺ�pN� ~
Z�����Aw�4V8�A�+*h2�
�(DRxGY"`o�!�c\��2��̢��
F�8�ɁI꡹tB��d�Ȁ��3)���u�Q�>{QCO��%�
�
���t�lJcTPc c��%Zݱ$������p��7�uQ
s�d�L����P9lfǛ��UENPC��4FR��$
ଔ����q!���Û7�i�)u��v�
�Q��
���ϔ9$1�u����F!7�G�������� [...]
 ��ѐ#�Bm�
�ʐ�Z�6Ş��MO
�Hey
Z���
+�'��(�h
��O�� ��Qb�����doj���O����?Y5�醛BBU5�(�푠
+2㔎��B��!��L
q/]	Nx� l�>�b�A
�����<g+TY�<,�}�wٌ��y�
y�J���38e'-�1��Q�=�A��;�~�Y����Xd���e3_
7%�kl
X��U"�UfQ��(;ȐR�zoET�H�%P�8�-�b����"S8.�oup9iG��@6��+e[z�$"%j�i
F�H
���y�8Z�6"�{��#�c'p�!]���b���L�[�c/���~�:����s��ƶ��֬���jp��,Fy,��'�`�\n���|`9<�-�»�K?�k�2�c�呛��Z	"�
G�[��a'hD������
�1
=�4\g%b �unL�1�J���)�n���Ǡ��1�{��ٱ>�xuymv�kH�
��@Z���;`�U

w���7�#λ������� ��b?8����҇��k�~pi�O�í�5�ƞq{ρ��
�ު��UB�D8c�I��"�I��d���m��� ��
Ϲ)tS���m�|S	2������MY�+��5p!f`@ä<�0N�#�K��J� ��

nS�zT
�i^a�,^j�n�p�Ap�B},_Q���K^���� �r\�V �=)�V�M���]�.#�#�8
+��X���ݦ���>�Ɔw�=�)�+��Nf���x��@:� F݇�"�߂��� 
+�E�k��3���T�M]NTUH^`�'� H8�����@��p- �iV��|
��9_l�qt3S:���C�����`�ca	d �A'׏�)��x��Y�pF>P�0kR�!@����ż�I\�y8�
+-x�W|��W��u�!��g�@L��'���
x;�	�
��IPy�@����^�'������X�v���)6Ӟ�Gz�BU"'����
X���G �P���B#ig}�A�gC�K�̍
����
�
.��#�Y������|Ri�����`Q~W�P����
�y^z�J�c�""Y��6�Hv��)h���C��i���A�
+&�[�(�H�\Pfn�5IZaT)��3�xʏ����[@��gu
�F Kc�$�r�� )H�
`�MH&U
+|DT� 7�)�����q8Ѩ�v�Ħ��^�;8MRoB#�0Qj%��~�fмqP�.0
m~Tw�ܱZU��|�v��ܑb<$y(i^�U�x:vc0D�B�pT
�a�uj),�o6
|��gvM�GK<>m�f{�x6��N��>�nn�������v������U:Y|lG�@����/"�n�m%�������e&h&��[�
+TGZsm���ǫ��ui��(� �7����y��én�
�:>t󴽡���nv�_��
+	"1��Ǭ��4��8{mФ��,�������Ƒ5����$�t�".\^3��}��A�Z
+X�pDG5�x�v�E
��l�#�K%@4��~�A'��/��r���
;O-"����
F����(b�n��V���gq�����6j ���5�,�>Gq����c}�X�>�>k����?!h
G�
+���D��לj���d��{Ib��:�Dpc$s%���Ѽ{�n9�x��ٴ��N����
��P��`�>�>�����)���M�E��uPG����l�V
C���Zc\7��}����r��c�׵Q�ﯭq[�}6����v���n�5:���1/}\��B11�A��ݎ���dh
�A(
4q	
d�l�b^DǓΧh�2�
hl�EY<�\��je\҃�4��a�-�-[6w+�Y���o��B�3��Aw
�5.�Gkuç�~rr��⫫["�6`�w�
+�0�t
�Q�"
:�8���94���[A*2���Q�_�=�773��
?�&Gr��UB��a�㷪�rm�k��-�e�F�m�
x�W|����n~�����fv$;5��Fs`ʁ��tدsE����-��/�ՁqGx�k[�@
�W߮
�S��j_��#gj��,�A����E4�� �O�
�*w��)����;�Y��3�������e��MMV���9�����MH�L�q������8�>[n���1]Z9ȃ4��F+�27
�p
�����{t.%\���6MF���q���G��ho
�#/�e�:S��u�5ci
+�Q
et\�Ԓ�7Z6�A�Y��
��!8�i��y��?v�}�_)�4_Bw��:�d�K;�!�Ÿz�q���
[Z�
^5���"k�~��۩ү�`1�ծr���8x*
8�h�ma+�����`���}�T1r�1Sށ?�ɧ�?�ϙ?LV��	���{�,�Rc�{�5�s�7���I�\�|�_���붑#���)l��������Ǿ?ڽϮ��z�7aF���
T�v"�͛
M�C�Z1&7�v�k��l6��^��F�~��ݜ��DX
n$T�G�q$p��O�g��y��11I��W��A�	A�
H
�f�h"��P;#���M���v�U܏p9����Ѯ~�Kp�y2�\]_{�'~�~ǔ�����R��AA��E
8�
���D�T�����Cd�r�b��V)��LO��*˦�A��L�
+a�)�m�v�<�K~�9$0uj)���y<�G
1ߓ|c�`
|�?����Dr)��nY
Ǡ���{��c`�+��x���0�W
�2�9����i�
�2^PcƉ	�C��H�`��1R{c�����ڑ3�J{�`�%
���^ Ϙ�k��qᡍ��Q���6.�Xc�Xu���
�1�'�tP �#�ݮ���)t�����{�{���S�^Ä]{��un���C?V�#��b~~��$�ft+ۛ�ZX�q!����ػ�c�k�fX������H����V� ��y�w-S�,l���4�b} ̑푿Ђ�bX-���Q�3��Ds�5
�!o))D[���r�����%ř#�$��F�B�>UDz
�ϑ�H�@"P�
W��?�����`�u��7��'v�
6���0��TX�*?Wu)��=+1()rF�[�T#�D���9�W�(G��(�_:y�>��rXB��~t�	����)w�Cm
G�E�<~~������ ��
��R�U��5d[+��N'��{!�b8�*p�n�Ę���{�*���b8d�l�1����lCFf	�.s�Պ���S2�p��n�2c���"8:��7øF-�8j�*�H�'eqP���5��h����P#�R��tca	?5ǂ]�}�
-�D�f�(�s�˚��K)+'��vUcO*�R�t	A�\
(�
g
����[,������B�nNooO�Մ�%�f�9D

�o(��ȓyޏ	�c���q at 5<l�7/
�%*~�Q�)�&�����f�rZv�wBSz&�g3��XP��#��堐*�
��$)�R7ه��}�}��ܧL/z�>N��լϪ�Ԍ�
�~ȍn��g �����͒l�Dr K��F�,E.R�#����Dp�7�ם�M�(�
c��cYS�Br4B�qj���Gف�Ed�
+ߨ��"Έy���h�5)���k�,t���S��h�$�)�?
�v����b�[`�
���
T�T'ɼ���`.�Yl��K�t�m
+�sⴕ)�1*F$�A��Aѣ�
 G���:Գ��F<�v'�s)���q�����s'��
�٣7Mmbo=�LQ|��Q�
F�:p�=�v�
+�^q�wh���U��"�@M2�
/K1vf��
+zR9 Z('�IՓ�C��mV��{OA+!Ϛx�Yh1N�Ͱ21�(i`
�CJ�Za]�I،"u�V_W����o.٥�o� �݌�!�u�F`��>
-�۫���CC�MӢ��J
&�O䋍6_���/�ܯ�1�� y�K�;��g-�@�,���gk
�筛c�d�$VZuJ%ԕ��vu>=a��-<���Ǽ��yջ�e(ø��"�V����Ӥ�$��;/sy�I%#‚���
+�-]*\�>�)?���X?ӓa�����a�)2p80�v�ZOp�C���w��H���S��Y:,
Xv]�V)�=������Y6Z����0��:\LL�hd�U�tM�
ˈX̎�@꤄z� &,*j���"��OM�eH8�N%�/��� ީ�����Y�	|G�>����&L�v/*%QO��>�"��� ݃Ze*��*f�
�ٵ���,R+ūR��U:���D
�̆���N9
>n�W�}k6�P7�f	�BQT��~����������Q��YN�Hu�4+���
+�%Տ���G���U���PXr4��
+�[��YoC�����GY2�W���.�!tLS
+Z���V�>�1
+3A��s0ʖ>j0M��-�c۴�����&-N�@�Β2�7@���s��ŭ>���D}�� �#Q�@��V��B9�!��г�%��xusTkқ@�M��E ��)�Nl���ʭ(��X�2K���
���²��|��AI���ه4Z��ΕL!�eK1
>� kx�r���ܪOÐ�drHl�ഞC���sa��(Sp��q&ں ��/����A$�z�>�ƶ1'_3]�E�ܭ8,
+"xo���\�j�޺&�M+>�������A�2�p
�
s��&v(�#Ou�r�ɸ2��+ag�&��<}X�5HW`�L�
�䇌��Ҏp�8�Э7���@NT]#����v��G�E�}�c��[
j�D�Iz����	Y�3�;+
@�K��[:�d���g^�D���<t���
n��@�x�{]�G,���&;���u�{�!>*&o
��
D�xk5�#U%�!O�@�����
똁/�5M��M]Y)�^��U�y���4��M�H����Ŝ�]��Vώ�
��l�
��#���(vxGz=K~lV;����7�̩)��o�b�>�Ӧ�͖"�l8 at 5 i.�͑�bd��)�
DD���M|����;��L�$���I��
�^W�a
�b6g��P�l�RRWN��&�w!�h����\a���,��
����w 0Yv�0}]ﺨ�D5=-F�� y;]@K(��*V�I���[� � 1�$_W����6P �uQ&BKK\��9Du���@ �S��Ǔ��ڭ��͊e��
+I�9J�I�9�ƙ�;�8D$ �9jk!�RC�z�c
!��J���

��ܚ͹ ~}�K��
%�Yh�P�5*��
�,{�;�I&!@\}�W����1s*��}�8N����FI����g�z
�
#7�3��CE�lm��\7V�L�bA�N�S;�8rv�L��E�$sG��("u���
M�ޛbT��umD��H;R�G,^

J�0�"C�r,�rւ����Ӽ;�X��1��+!L�X��5Ө"
+��[�Z�[�i��ggI����q
+�
 �c�,<M���74�Z��N�T��Tq)����sw�
+�]=>*���B|62o�`����J1$�<�{���E�N�DJV� z�]��s���
B�fP
U���uZ�b��۰F�

�X��HP���1ǩ
��p�<4��׸�w$-xj�L�vb�'	qξ����Feg�Ɋ��
T�A�Vq¬{T�I�1�������4�>�'�y��1��l��)6�c˅C`�U�T��ֈQ��T�&�d�Ab�:a!H�'50D�@Ņ��x"H����!��e����/i�
P�%��O"��D���b'AFڛ�ՠg��<�90�s��
{�"ԩ�x��`�gKA��*4�𯻤
b��V+��}��$dYP-�f���1v��er9�F�Z�$%)I��(~�D��8[�
+F�P�dN������8��")�
+�q"�-27FV�����̨�G�D���C�:��l1Z���^�5H2R �;jCK��B&�޴����2�I�q\�H��\rTO�ca�8�H{

+�uV��D�
v^�,,©�–	ZD�-�ۥ~�M��Ҭ�#H�H�Z�k�g�V�V������z"��G�cq�|��р
���?���sNNQ�!�
+��<�vJ"O����FDT������Y
o��YF�7�(ꎁ4���>:�k��U�1	�
H5��G/+���v@�8R�D��f�^��3��:8�7�P0����B[���i�df�V�{
!
�t`�E�bB
+tN�g��o<|�e�د$Q�AL%N:"HM��*
5Zt���]ko�������n�#���ςL�+�6�jm��/��r�HI�G�j�1Mȣd�4�
P�
a �&]t�M���U��fu
�V��2����	nm��dP<�l���Q4������DL�E'�A�+���U�����Yf̺���Sr��aް��+�)�
KF$��T`\i��O�E�V�("R�0��Av�T
��0�ǯ�)���k�����Q�F����6k&�2�&�C��j�r��� 6؄T����J�ڒ;�h@���̒	��*`3m���L�#�gz�IUl��1J��
�HJ0�G��b(�U�'���Ba=�%�C��<s�2<��L��aO6AV��vC~��B�����03�C�r�[L~�#���{�!l�Y��Gՠ��g
�9ݦN!4�q��t��HD˘�!�P�T�n��
���<��
�%�&GX����s!� K
slG��sq���	OJ�N�2�O�<Bk�j���pz��Q �n>�ȱ|A���cB]zt*e���>O)nd�
+�7�x:�w�
�g�	k[#c\�,�T��Aw�g.f�O�MHX(�N�1a	�c���;�I뛪
&mt
���槺?e�����q���zF'(Ea�1D�#��PmSLI�ʹZ��mDeh���#���5��Q�f{bƻD�5n��R�Sכr<T�����b�
M�}sw�1��Y�ˠ(7'�2Z� b��Ot��$T!㊥�q��
���� 6�]؉�x�G��;y�ɒ�a��"�2L���_癠�O<H�z.�a0D�dJ��9�B�s����X�\��Ex����S
�^�~*�R��k�)�W0�L�~��m�xRx����k����Y0����b�!� 1ekZ��ъM�����'i��g2��b�KSCu�V�<�&e|�}�09p`��(�!��|����U�i��(���q�!DPs�$�
�X#�˟���9�P��rM
�"�~?�蘊�"!X[#�~�^����V������-?rit�
Nɤq���I�D��t��8ᔗ 
�c�{5o�0�j�������Y�
2F2H�Z���[cvz��?�^��K��?�"
xF�

wѠ��j��Ǩ�R�8U����V�����3B�H��� �!4�����N���(կh9M�G¨���r��"�.�i���o�a %9h��
�Ŧ�5~�'�b�����W��Ř6㢶��0��p/0 d! 
+15z�����fj�7�I��)σ,ߡeEH�'�+�����
[���C_
�N�j
�y.�S�/;|�C����p�Z��R8�cZȘ̩� DE��E�d�aꁇUmZ/4����E�P�#�z8L���ɻj�S�&� ���������9
���
*���yc��!�l6>JD�d�e<l>5�gJ*���H�IsN(�9��J�X-`g.9�A�Nx�ף�`r��fu�[�w*��\�Jj+Ǔ��:�������
+��r�\��S'!YG��K��<�@	&��`��}�K*P-.���R-��j�!>�>Z��Ҙ"<C�R	��lMZ���
d����8�a:v-/e�%X�s��q���!��A��q4���Tl
+-)gj
H�hQiv��L�<��##5�t x��#g
z�c�╂ý�����)
�i���:YK�<�
�O�e=[�o)�$l
�9q��U���g2��P�Z��nW�C�mF����(������+F�
�K�q��}��B�
������Y�t6�(��C���8�q�M3sFu�SH+��ҫ�G�4��k���T���wm"�C���$L�tUJ�t�B�z�,[���nZG��a�]�CV�T�*C�Q�P(�m]1U@?t]�^�|:�iL�FWp��3"���p�L��+f��]�g�J��U=jro��Qk�aӚ����d�7����m%�
"Isj2�QÔB�Ȇ���5���e>e<�976�Q>��V��½�<	 V��
������!IF��5NBA��K�
qsE6
+�
9�.�]�)#� �4s_ͨ_�I�
��O2L+�6�Gt�Z 
�3p�i
�W�m�8��x
�Iw�U���:�ז�!��'��S���[p�TeF˙��`�C�NɖI_G�Xok�hp���&ų�v��.�6(���rM��{	"��nB7p��`8T
�S6��^8?

F��d�B�c$�+q��e+��w�M���HB O!T`�&	��u����.� R�h0��l��m�b$�y�����"k��
����c՘�'
oH+U?r��qHHE)�����k��������"���u	�A/it!	�R.)Yl��̯Cz�;wr��2Ǻi�<d�x�&
t���a[
�O
��L�F	cv�ԩ�G��D*���4-
Y!�@0\A��h+��x]�<��]Ѿq�J'L[���ݝB��5Zi��;%*k2:�)��܀ípi;��z
��,h	��w-o��x*r��4M�a��Ӫ0-o��|��+Cfj)�j��e¨��UUf�;��>։R��[ٞLΩ�U����̏�(��y4j��`(}�����ю�b��UȎ`�Y�2_3�]xgK5�I���re#|))?
��N*R��?	'\蹱�����.p�-��8��d�gC���Iҗ��"� ���d
��;3EY̜�D
+v��]c���[{�7�0[2�io�l�䣧����Mc�m#@2�?��̥�S �n`�}ZK
+W�t�zvr%��l/�����
�S�1�}�!gC��*Ш�wd����}�������k&����Q�"ꅈ��y;M%b*Q#��2a9�F�"#���B��h�����
�%g��*����k��Yr%�<+_�*.��w(-R��,�Ƌ�p3�GfY�0)�*��ܢ�X��
+��eMQ�!T>�D���ۑ0�{X;�X8C	.pdm5�|
+

��A���x6SmC�cPFa�&�r�����bφL��ب�Zc`�h2mJp^������5}��H��t�u2
��sDj���g��������]���W�3���EI���5�7b�%�*L��4ދ�0u���䳖������e�����H�z.9��C	�f��
+_��P�.Bd����8%�x|��H���^d�@cHBd(�b�5Q��o?'�(|\J��-蜨"ˤ�D���l&��y��S?6)�,l#������8��`z#�i�9�A�l�5�z���Du8��r�D�2D��f׸��c�ͯ�:�C�`���zRj�����VB��PYP��A�ir�2,�;�
��'�n+w/���m�񶏾ZV��P��E��
Y�ʼ[��QYaQh��z�� �\��
+z
��Q3ۇ�I��	��Ř�f�Q�!,x��d����Ee �N��vT��5�����q�)�5��h=�t�����_��!t�,e�z �$���I�g�#�>p�J�u��
�~�
������i���W��o���lVm��Cy
[����dg��L�]���@l,�֓(۔�
`L4t��� ^Hyܵ�*��$�s��X���9�2��g�
J��
M����7��]Wp�>��fK�!����M�@Vy� ��HNq��{����(֚"���y_�|���
��20���&��s��`
��
���`y�ڱ39xw�=�s�6���蔬������x�����nҡX���5�A��4�H�ȁ��x1�2R�T�H���],U�R��b6�a���ll�jk2~����M�#`(��5T�_�����NS.
d��I��G���k��6
+a� ��
�)VL&��,K�F�4�^%O4^-pI;A.
�&P_�KϹ[��-��� �)�tJz��)��`���J:�>8��)H�dW�g������b��@Ŷt~!�ĚJx��U�C�Y
	Q�Y� 
�t�J2a�<EEC)�9�{9\
h9�l3;ԣP�����b���t�
����!��l[ӛȔ
�B�Y�N��_�2�b�EI\j%8c�-��%W
�sJ쎲ż��^ϲ(����h$)
�8�F�_!�L��W��
]�3��%����5~�<���r�h�~O�5QfOr��)+�
��6�<R��S
�#WF��ܱ�d
~����
t1V|R�Ir���bh�˚���&��޸
F�����lh�}�q�aΑz¹jP�7
+ц�#��@2�,���G�VZ�+�m��4��Gd�E�����R�j�V�Dg�
��1,vGN���j����vx`?"��=*v�y
�@cq��x��o$&0�]��h��S-&���������*�E�n={h�,� %���b�-Gz��&���
�Q���V���q�
���D&�%�*?0,���{�c̘����Y���a ���
���L"&�6��o���I	-lOar
�#�핾�����Uև�:�j1�dƐ=��&�F��#�Y�:2l �<���s6X���Ŋ�bz��K�F;��7�T��{{�M��>(w���N
	7�7�|OBZ�[�j�\-�BQ*M:�W�d����Ҫ����
+�A�\�6��s��� +�Xbĥ�7��Yf:��95O`�P1�e�v��.&O�5sO�v�?��
�T��k�j��Y��Me3
+�ґ�0�`w���k�}i$�x���ITJ�J�0�"c��N.���u�7L�E1�\��Q��ԑ�0����3�V
j!�� ���ϒ�^�XI�&(e��SS|�����(�un
�Wơ�W�Fr��
%9
+1��[lrZNŗ�f��� ��!ĝAgUm}�1����*�{��Z�D�
+3���g��4�Q�;6�I%s
+��}��Q��(�T��B�Θ�.�/��UXN ���H�چ��2���z��+\+Z��#���i@d�15r
��a�
�����t�'��<nI)
+B΂Ԯ
�oP`
d����FF
+�^/48��
!UzjZ22X����z�f.�d �mޙ�>���>5!�j:�\����Q����L,P��z�]��Nʊo)`"��5�
��3�s��\��
�=EX�@nP��Z�
/nZ�<+�@���M
��3��$��
�ȱ�a�(8��7U�Fġ�f���o6'�����
���X�
}m�/&�K-����I�����^�V�^�}�'
���N�	I)�)��26p�<bۯt�O����pztVJ�K�Y@��S G�	�x5���RH�+ޛj��X׽j��Y�hZ_J�}_VŵjB47 [T


d2��� �H$�|iK8�`�&a����N�`����2
+�YFY���
���
(���������38 �7���]F
�ܲ�WR�Y�2O��iW
�P?��(��������Q
u�@5
D��f
C�[a0uȄiŞ�
$�~���Y&^jl��r�V��X	�#e�?a�i$�׆<EI�U|qP5F6���� P
���c���<r^s�N��v �� �u)�F�:�<E��'�:y�q� 5��>n�[}[��z:���"�H�bh�T��y{
Bb9�^?�a�����qòYX� �AhH�'e\��y�h�	��T0�ʲ&M�_Gܛ,@�.ϡ��$�,ډ���͐e?�r�V��2Ϊk�Y��PăH߱��Yu.<���v#ƐD���z�ԵT*[�9(h'H>������B0Vc�h3�Q�%��I��X���>���g�c8&M�%6A�j��9*$���#VS�/^b& ւJ?����pHa����چ��M�@ڴ�ROƋ���#�qNK��b�3Ƌ��ֆ`
�*�,^C1/rA��.��T
+�%�� p�Aa��3I���~�..t +�)��qEy8���*tjTM�Z�8��
��:X+*�Ho������:X��㬤dx
+�5�\�5gy�,& �˱X�Ycd�
y���qh���L6��6�I^�G�S��
•Z�Kל�2P*�Sq�^X0oPEan�#�\"[��@"�q�0)o��y8E�����Dd|Za��!�R7Ԥ!,3�A�� &�Ғ���
g�&au��S\0�%Ҍ*�aRcY!Bs�&���|چ׌�ý�wS at q�3����d�[��<���
+�;`\�P
�9f��he�%ވ�f
��$`Drd���x���#љp"��V�	
�d��Y#5�9�� ��F֩ȭ��H{HĔU�{Ӝ�+>5� �t��p	v��I��+e 
�i����F�W��R����[(F4&)g���J��L7	*��96W�A�,�v�\:�\aX
��U�5��<��Md0�
JmX��ډ�7Y1K7��l�9B��DpԸ�joY��B�	6��3�7���a4����-�Q�`n�����}]�0/t����ϸ-��'���Ón&��
0��V�JH,-�›ʘ5*4 ���/��"��8���F-J�ق �"��M^�mI3EƤ��5y��
�0U�<��.V������B옶`�gH������X��LF�s�)�<��:9�x�9�dâ���T7>OJ����
��묚A"�#�IHbn�#
�n���amF2w�v�=�ZzC�Q�@��M�����.�FD���9�|ԥ	a-����做O�|��$
@&jüw�D�=�<�L�#�MN�P�
���q����'Q��t��8E��E�������FI ���ut
�q��
�����1
�
_��2�
+��<r�	���e�O��U�#48&�A�8�
$^�f����W���7 	��h���@6-n���)�L}�6���ݬb
+�)gJp�&Ja*��ғjO�@B�
g:�
� �8$��}������V�o���i�ЈH2���z�u������>�!C�u6� *S��>b�)��J;��H��&
���r at U�y0Av'|n����O�Iϥ�O���(��Ae
�^1T5"�zSi���c6��0Ѻ�
o���6�$D�v-�{�o g;�*
��ۥp�Kdž�(jm����Q�0��k֪�/x�?@}�� lS����e��r%�������/�[&RE��	�b��*C��Z3ϐW( �a�V-Ǭ�P�-��
:�y��M}`�� ��C��?'��f�2���89�X���j������S�������6�]̃�#5S�g��~���篖�����yzr������z~�����ͷ�/�/��9��}y��������N|||~~�����o�N��_]]��˻���v_~w�����~�;Z��~�~���>Z�Qv�����~^]?�Qv����zu���f��/,���˧Ƿ��}��������h��o�.�����?�����j���?��1���<��.��=��|��_^_
_�^�
��>�»����#��e9�y��f������?�e�,�
�Ů[��"�T���q�E?[ں�ϖ�y�'~4��k��j�����w���֝
q�����h{��ю?x��_Eo��+��xg��執��s�?�m�q}z�-�����חؗ/���8�����\��
����F��G�H�߿�U�f�q�n��~
-���/v1��Z#�;I�
+?<�7ʏ��_w
+/�w
�vjLJ��F.��xx��>�R,�7hB�x��������������惏�������Ű��K.>��2��?��'����i����W/�o??;_��_���NP�G
����??�g��'��/��/}z|sv����ߟ~�W2����kv�dk�-qu���	�
�Q�|��Ta�&�ǟ�~�����7� J�/;���_>�}������g�������?�����q�^����~��_]�xuv��ao��c�t��w�'|}��/? �
���B�s>A
��|�n��!*������o�s{���s�
���T�}��ӟwz��?�%�=O�ú|����_/��G
����

��\�,
��N}x}���ǿ:�=���\G_�.���Ƿ�+��|��/�η�O�n~�7����?|vv�[�ᨻ�����C��ֽ�w{a������������O�$��~��h���i���ns�aH��.�kJ�Gw�+���*�����ʽ1���׺�����|����O��}u�?Օ [...]
�"|��~s6DE`�n`^�r
ƒ���Q<
�n>'2	*���.'����ckc
�䵙f��yx�L̯[�f������z~����һ'��z�ӣ�a�=�?�����������_\����_���ln/������'��z~us����W�@�8~y���o�����<{���򙾸�%��'<��l��a��v@�)��)���O�]~wvs����_O����|�ݲ.=��:�'��f�O�x{��E<q��������m���o|r��l�m��pw}r��ݯy ���������z�{}G�[$ɠ�8��3�w��9Տ�ί��|�d�6<�;�դ!����S������������?�������ӓW���>�~�r)��9� $|�N��2}ɉ{�3�^@�3�N�)����|
����qp>����xϜ�tp>�w�c:8���|
����qp>����88?	�����x߽���}
����q�>����8x���}�$��C�〻zߝ�>
����qp>����88���|
 [...]
`:(��'p ���>��Q<w�Ӕw����}	f�n��<�p��
��������������W/��9��ۏsw���]-q�����r�,�y��xYw˲89�:���n���{sw�������_����
o�p��#
o�/@	с"�H
�F�~	'�������큕y8�'�{y�
����d
��d�
Zΐ���� �-�q^w�!�z8�������^P
����-O��z8��Jdlo����r�0��J�*��%�S�
+��Z^����p
�|8
�!�������,��� �:��p���P���GS
j9�w�
\��
rpA.��9� ��
\���
r���
*:�w佨�8� oK��
|��r�A>��9� ��
|���A>;�����}pD~�����G��/��
����rS��{s������،�W/wϖ����V�)���M�6�9
�ŏ�&n�)6i6
ģ,n���VC��ު��-�o��k���E�F~�CQ��#7�
4|��-T`��Q��:���eZ���89�ޚg��/_�B�
������_6;������;'7�'{�Y̾�;��ecݼb��
��׿��2];�}<&���t��o��1��:)��P�x����מ{_��"������g���	���
k
�go��~�W�Vo���mQ|������r���o��_�i�M�G�U��
��囟~�㛶z��������������.����k_��ˋ�\�٫]�ܯ��~u����?�A�ӿ��\�=~�>z���+��L3��*~�R�,��1TS$�r��>��t����,��1�������7;d ,h�n
�G�0���oN�\��sE"s�>�׿��Px����]��������복n�Q��|�t�
c�owA��.X�ZH�Q������r�M���=��~*�ķg�W_�:���pM����{yڿ���_a&w���/O�o�
���k��;�}˔������a��
>�a��"v��]72X̎H�Ew�$3�}����D�7�ՂH�< &��ϢN��@��o�0Q��F�ӝ�q^��7.�n�8�	
o����q~4MQ��tx{�?���W��wcN>;�xy����s�z�e�6ԸZ�O���v�(���/������'���ܠ���w��i���

����e+>=>?��=� [...]
+I���ͺ_g~v�N�@���~��o�m���
&�ESO�0�����ߞ�#_�g�q�;����E ����>=��/��n�k�/�=0��m_~�����
�1�����/{��G�k)�Ժ���U��EҦ�S�~�U=z���ߜ^�
��]�AͶg�c&
���^��gCK�������-��۟-c����뻌�>q���e��
.���ь�ƥ��:�w�
�x�}䱻�հ�U
4s���W�ftU�6:�鵫��մ�U�$��[�*�
���㵫e��g��%��r7�5G�m�4��.=qLe�Q^
���W�%��&������=���k�c����׵�9rO�1V���r��������i��)v��Q
gIJMO�w��V��5�|�?�RZ����E���
�M�6�{�M5� ����Y沯K�%��@��������lʟ��w�ۉ�i`�~}�	��
�]��G�
���=���6�p]��!����{�K�d��U8J���]�=0�F�N��X��>�wz�cL6̽�3��
�Ռ5������]�Þ//fe=I}��7Q�o���Lx	S����-��3�ӭ���
٬_���ޞ��ܞ���X�n�~�q�Q�m�
\>������s���.&�l��ҷ�-8��.��iE�>�Z�h��tڅ\�og�������
�]�~
��-�a�]~)^t�.��#i95
'�³��f
"U����Z���m��cE�a��%~�ƴ׸�{-x�+�u9&~�Eޮ�v�n�%�$�X��͖���Z��e�����x)�7M�V��}�l���q�[����&7vqt]�
+i�N;��h��
�`�e] ��K*���M��$������-�m�[��
bĠ����Xcas;�⭖دk
	�� �XS���6�C�s��
%����ͱ�NV���	�M]��:.�!�Y3
�����i{K.��8�m��q��ƭ��
m�5=�v
��K������&�z����ρnxrvyz|�X�7tߏmx���k4�����q��?��!�
b~�!�P��?�n?����No[��ˏ�:�?������^��;yzu����gW�o���o��L�pA	�_�{��%b at O��qj��Vs�Y�-��w�䰐Ƽ5w��@��^-��g��%fK
7
��qk��uTO�-������V0�]
<�����i�"��}���o�	��'yp���"�w�6��lU��[���Y�$s�y��ö7&*
�[M�e!.��O7'��h���C
��c˿�eɱun�Ҷܭl�ڴ�E��zQ,���84�L�]��l~�oO����
��o�f�n~�[����2.�~��:�Y:�H��|���Q�'g7��8�L`,��j��(�^��^̉��`��QvIz����W����A�����ӳ�˯>>�z����e`�/�<���h��,��|�����]F������L}vu�
+��
�
�v.��es{QL��o�x�˫���_v����r���rn.���V�g��[��I?B��O-����������s����������w�
_��˦Jk�����g�~���j�]|���g�����
&���ᙉO�������]�Xڽ��-�����/�?�|�O�H��
g��ޙx��?;^��7Y�?�V��6���:>�7^�x��W7�Wۓ쯷���1�\��-����/������Oa��|����6�o��󳓿���(�a����ѻ�[�GC~��??�0z������a�0�Ý~�i� t�?����|�<W:~衾5_�?շ�Y�o�X
x�z~u��ON������j������{p���{v�����S����w�rC���pqz{�b1��u
�;���}��Û��͇9}�,���v-���1�^�
_~������ӫ��^�
C����;�����������	���:|˶9��S�+�~u�����_��
??;7������鋳W��No��_7tW��A~~�h���~�v�z~wςҪ�_
��(�񂥌{�yyu{�S��g�u%2��˳Gj��\����'��}���j�������ٟO�t�Y|y�ry����W�R���|��e^���Ζ<�=ݑ�u<Kg+������6$��f꿷��_^����������d���������>o���������%N���{�b����\q�/�������������O>o��~�{݌u�?��붌O��^.�����e��,�%7�����5���ӓ��G��_��_e{_Y��v��n�_���������t�D4J�7�`P�]}wz�Aӛ�7��O~�,n��ho��۳�o�^_} [...]
+�y��Թ
�w?�	�L}~ݧ���sMy�W ���
zf�{����������8�~l'�B���s�z�,H�d˖,ɒ�v����l�o��	h�Gs��{�P�	���z"ވ�!�FH�;+�7(W8}{�9Y���d�O3���c��<��
�F~+Fr�����H�
5:l��_)T���,ER���㛹'�*�k����$�l��ٓ6S��wy��XfΔ�9��
�S�ٲa
���-�dM�&��ϘQ�EM���%�l�Sd�<�^;tS�i�H@�V�h�]����V����1脈
�@�Q����0�?ip�:j0�����\��O� �u7�%P��nws�+7��3)<ݲ��i�[������i�����˕����8�{�
(��k��� �d����8y�R��
7G;g�}��ln
+R~n
+�bŸ��9���
Rn��ݩ�L6pj��������@H,.�Z^nR���J�<1{��&��������޹�_J/�{�	�ٳ�y��s�u�
��Nh��ӆ�%,�n|��.۱�́M�6�G����/�h>�.�oy��'(�SrSܟ�N��P����["6�n[!S�
KD���#z�m��$4���w�?�����M9�Sv���t_,a}6,
5x�6(�uh_�����ى��L������t� .�� nb���"BF�G�}֚-&<�ͷ�������^�h�굌�<�&��
N��N�q���s���ҏ�1�-<���.�0j�#G
AM��B��p�3}���b��^����h{�|nj
��>��GJ�1
��U����9�
cM�n�n���f}nb�|�aX���C��8	k9��c�N�EU�,aةm�4�L-(�.�Y���W�^��&]8�����0���0�V�a��R��܅T���? 
戝�Y;��>��������*����y�G���ݱV���Z�55�fs�k}M8}�(�Z�7���u���}U�|�)!�P�W�]�O�0��P�i�%n�
������%'�d*�_���s�
+����	K�|�v�L�OG��	��S��Q?���;�XNN�+�����2�������sX�&
��
׸�Y��	��o
�8�J
�ֺ~j�|
m'�W� �
ө��q�tYg�A���Q�^��5�)���V?�����Ha�u��o���_4�p�
z�
�/�!��H�RB:��!�5x������zuk�
��)��l����D�
�9{%�=��~��YT�HYU.����80�u8��w
�D�3J�3S��]%XK��Z�
�e
�Y���ϕ
�ٲǓ����p&`L
��1:�S��q�����׺��1c�r�����)�K�~f���"b~�zS_
2
�~������n��M^o���9SNMl�k<�U-�L�f���βZ���6��ƍO�^�yጟ�Y�q��C�PVs sa�_��1�r,�q��l�%����lQ
s�I$��J���/Z���Tz�SQ�)g�_
#�.�fOI
��.��Jz��ӗ:G���G�
+Z�
���o*R�����i�7��Y�ワ�pmcL��0��(aj�q��^���p�
־6`Kc���ӧ�{̐Z0cU��L�A
3�R��eb�c֟U�m+U�~��1��ƜצskB9�cR
0�}x�|���
hb,8���š��Dre,�
+�`��݈%K~��XJsRcd��2���e��7_�Xa��RԨ�*O�N�+��-������Z�_%�ٛR��0�Xz��T7=l�p��I�V�f��[�"l	
Kl��e�m�{��eK;N�G�brd�Xv|U���R�Pi��e��4&�6�������8�tڋ[�t�rJ_I�S��2�
���S��L.ku%9Ȼ��~v�,�2eeyVt)k��Nټ�ʮ
���7J導
��-��f
�U ت}���,mӣR�Oj��]��I[e�{2*���S�5N�ʷ
�U�Qp���~�TD)WVe�6RUh�êJ��R5~�fUW�ת���R5��O��O}��u��jWK.UgM�G�,Gj�)��6�K�-��U���V��
��H�����]��8�fu��v�k�sXݶ�ꞵUQ��o���_�ף�U}��-8��8��
+������x�{.q#
*i"x¶���eu��a=^�ZbxWy������~W
�w8���t��fc�F��U5���qy�AM�b���Vq�פ=����Y�4
�)����'��m�����ߚ
Ѷh�f}[�9��Z���ѺZ}�6X
����ޥ͖�3m��j�+�A;�.�څ�k�n
١���E���F˜β�wt
�'�
��.���@*���F�덧�Y�P�m6���+���|��&���P�裃�E�>g}Ų��;�d[?�cy�*� X�Ǎ�m����`�|�
�>q4D3��!�T�
U�~l�����z����m���F���ot��Cc0����ma,����]윌c�7�}�EY�*p�n�J�
d�d
+��ߦԙ\��ӳ���W���ș2m'�Y�k��f<b4{�9^:����bon�{N��.�ז��|���Y���ţ�l,��`��[���U�-�|3c��v�2�
Y͵��ꛩ���53������X�Bt[���Ħ��C6gS��E�cҖ�TT��ѶM�N�m��񬮠�����j��K{vl+ڛ{��>�'��]��r��U��k���>�q䓃��c��
�&�:��֩'�;�ǥ9��Q�Y�&rξ_
s�~|.e�lS�.�%it�C^�+�5*]
���w�g�٩>��k���o{��t2���ֲ�=5���G���1Q��>�xȄ��i��C�d��x����k�<^�~F��,=�w���c흝��y��b��
e2_>�p��"��o����U����+���u�WSː4W~��Lê[
H%dV4
�Η���&xP��샮d�
��
l�Bp��i����
��T�P,��
+U��lh���C���(l�v��a����ix�R�Ç��1��H���#��!~��G��&j6'��H�ԏ��JtL����0�Ǭ�5�:����b�����u�9�^�S��O���^���eBZ�&���6�?�N�A"�J
NS�OZJg2�(D���%�\L�-Bݹ�o�t&re��跗q�0*�SVMd�J�
�T���S+öKjۿg2h]���|�$'��9�������������b�hԟ26>�!*�u��LE2[��'kj�#ٸ^��m~O��_���_
�\d�2��e?�l�#y]���
Zy`����\]
+:ߩ[
	^�k�²��[�۱V1�J$����Q�M�����,�=��Rۭ*���
Q��`��
�o��T>��ڊc9VU��޵2�
.U���V}�^Y-�u��.�
}Mg��jQ篷��Y��m���[�f=m�Mꃲ����=c�׈�������,&Mô�j&���W=Vm��u�=�[�e��ZhR�m}��R���Ϣ������iIu<��o�l�;?��k
��]�ߜt���6^-��B�a
+쿶)}�۾8��Ο��l0����)�K⫯^or��E����R`�oV�����\c�jPƾ����
Z���0��{����8һ��Qrg_�ߗ�X�����X�=��U��k�R�k�ʤ5kU&'ä6��.->�����}>;�yL?����v�m[���+gs�+��|�
���q�(�;��zs�8
��O��� �
[:���bݶ����r���U��^�J�}�z*��o�g��
~��_���[Dܻ>�
ƛP���t���V��F��P}�
8��N��kw)����Zm��k��sg{��DB���:T���ao�r
+��E��vv�<aN����[����>�������U�AGU�#P�-76���8�w��#���
+� X���wVV�>��~���B
hsr�ɿ2��u8���9
�V

)C�-k���vX
wL9��lN�N��2��r$f�i�����43)�*k�#EW4P�i���u�%S���V�lg��1�Ա��b��L�s�wXx,X�N�F�K�'S-�B�y
�A�)a�h
Pf]��K�x���������lvT�
��/Kcģ���K�N�n�mN,l�� 0�׿�߽x#ii�#e�
�c�5ُΖ��0�WR��-8"9��Ģ��B��X$�����e�c�!���1*t��
�
���M0,a����u�jG��3�]��Wg����.�t
��8��%��^M`�_
�VN��x
?���EaIa�۬c�i�
V��,���Z��ػ�
u��_
��X�[�X|7�n��b�
+,��c�w�S"wn�y�so�i�VI�̯�֙M���[�R#��X2R�S&��oD�ۣ�x���1Ԛ}
U���p0��Ǡ�S��i{�;H�Hb����ٚl���HX�!
��N�� (���M�Y�l��!�S���S͓�Ԉ��:�`�vl�H$erџ0
�
g����{��r�Mc��{�L�p
6���37� ����Rwy�<��x��5
k�����gҬ�2�0o,��xE=-�'�}`�wU�7��Tg��ID�Z�2
�`��唹MXwO,��' ;�#�`��!Y���vc+������l��v͐Ͻ:y��L���?��;p6�ot�&���1|Ց�ƞ����'m[Qp"��>l\��F�r}$%o&Yt�M|��g
 ǎ�U�O�k�?'u��>��ԾR[�@�O'�
l_�{G(r܉QHLJ9;Zm!󈄜���_��}jB}��6/E2���l��dF&g�.�s�Nl<�6�s)�-4�P�y}P��2�^�s��B
�"��?���n
+>�.�r�����"��y�H��+����C��f�Q��prM�W��}�nHz@�9�[�`H_��m�>��UXGR ڌ'�(�b�FvL�|Վm�ޝ
��i_r�O����OM�G�
b�͘̚om�ǰ6^�

�v�q�?��[[,�|��
+1#�o�WSN�
;g�0h�E\;��5�
�%���9`)�����}�~��iX�6�M4�O��0�b�
��6F�
'zK{�V�
�4�|>c&C)�
��c�1��b
Olr6
��o�?������&Vo%S��'�fܩ��)�^=H���B
~��%n��@�n�%��g@����j����	(��諧^pT��0��
A>KP��!3�u���c�uH�&! �as����J�F%��よ�;��"����TP�P�X �8�8Lj��S�:
�,��1X>�`�����4� �:���7A�
#ʐ�j
;GQq���IPG�c	���L^DrjeOo8o"��@b1��0����Q1_�;�4�`�s�2"��$���2�t���J�1��!cY�ƅ�����_��XD��F�8�F�03fظ,DT
�*�;	üa�i��r{�d~�������
k�pf5¬Z�R".�*�{+w�A-Rj,$�#+�Ԭ>H�Dr0���w�!��vg�ז!��b�;�ǚ�gח�'����z=-��_'����xm�je���0�V~G����O��!��[�a�&�*
"���!�U0c���ܶ2���N�����nV24
(�l�F�if��%��h��������w��9dpdD���s6o�lZ��|��bcI
��ڮތ�/�m�X��o7d̏nFEM�_��w�/'����ՖC`�B-�;R���
N��������a$ ����|�
+�d�gM|�>��'Z�+x`��YE�v��
�vq�
 0��ٟ�E�\��*�@mN
����t(���!QSH���!f�¡Qv'^&���0���X��-��[�
�$2�zk�=윙яh5���3��J����ɲ�����c�G)Ugd��6�4v��U$
��K'�-���B2�0�c�9�d�R�
+:
+Ԛ�'�#bF�&B�s�*�
�,�����:�_��I0���

#~"��.�9�r�
iW����{<#�Zc��Q�X4�i �I¡��(D�*�����4k1�򒃾AE�vב�o}��Lj��;-��J
���-����ǫ�z�$��
f��56��:��
+�Ɂ���>���Kr���Hz8����̠%�X�@��,�
@O� �v�1���`
̶�DJ��_��X|�?��ҔJl�=X��hk|�!hxc�|W	��%ƅ]��ӳ_0/�#���h�
�uW�
.�z�Xty��I�W�PXc �qN
�I,��ZXN2�{�
.���x�9�����Ŝ�7�]:�

+ܿ!�
�c��lܸ�
L&�:�
Ei��9<q
1q��O���Ƚ?`%���&H�/�1��
!ʰ�Y`
,�M�KDO0/O�JXj33��oQ
���%i� X|��q�"��`�FO�ܺ�F��g�si"LK�v�
�yGb[��]��x�\����H];��ς�c1�.%�Zu����*��L~b��EIl�v�O8ڱC��'�`��n��M�����W����NxT�
+>s�FQɠ��6�����ж���P�)Ӿx��c��Դ����%�3����@�+�gk�ob�
���·t����Wj�~`5�-���
`^X�
�
��`�
@A�5�api�#uD�[0�?�
�3/�\]����bϴL�30�@k��fR���y��B����ﯰ�%sb��-�zYy"�r7<��C���y-���� �5	�f��c�/3a�i��ܳ�7��=��|6�鸊��
�0��yXE�|"<�|�!��Z#v|\�sr.�c{��N:YJ��w��C�/��j�Md��J��v\
&~����a���\�����
�ӓh
-�	����껼��%	ԡ����>l1��E�
ҫ�!\ݡ���u�j�T�|
��NU�:����^���H��%5It
+<P4:�㍆�,�h��@{��eQ����kOd�dTd2�*b,�r�05�w�!�[�:�jĽ�ڏ�5Jl� 6�&p#CSIoޙw�
Xa�Vt

Em���i@�k�%�pu��L����)��q��,=�e�-�#�g�'���a�>�u�����g@�>�D껕K<ߵ�XH��Ҍ�m�&���H�������ޏ�n��O/(�k,���?�!&��/�N!2��)�;��^��ã�@)i��|�J�j�j�L��

�ה�	m��oX=a2
Ix�Ȏ7����T�6���"�U&���2P�t�tɘ�2s�����d&l��� ��
6��X`���2.�
��vvù�o4��.�������$*�:�\@���?1g����"��O������޺*�eb!�E/�6Ҥ������<�Z�]�D3�;O�P���IJ�M_h 㚻�XꅄC�h��ks3h2���e�����8-���'�����ot
+ ��A���^O�}`����Ɨ��S#U�QB=�+��2�Z��iO�&P�\80%bt����-�Γk�G�vAD
dФd
��5�޶��˧��IFk��S��x}rXP֢ã�Il��_���
�7�d����
���j��_���
�}"���l[�-���C���_\(B5@�⬠��N�����d�1?i�д���(�Ll��}[c,�#Zꀙ^���y�X|�0R��,�`3�#P���ێ����I�!5��<�&��,m�M��lu> A-�M���#�����t$<�R�F��x�T��E��n�sW��?*�!
�VcO�\w�x�0;�tkg����b�~�C<~���i#PL��h���5����Rx�`���
p��l

��
T�K�&����e50���8����σ��yq�wN���q�V����ykܗ>_`� P��N��(�|�$桁��0��\`�^
���Y=�IY#���~`\e2���7�1��m�G�2V5����W����u�j��q{�`#�<��!E/rJ�Nwqta7�E��7k��1*�p̫$PD�m�[��C�z`f<�Ԭ9ƆJbc�7ҝ�ΎXT/	��Ǟ��u���ц�4���9��u �$���t���܆@�M~��Ѩ�R�Ҋ

���`%�I�]�Q�r߷��m0��c�0�m�㞄4
��<8��q[�t`9P!��	m���ae�+)���LYQ��� b��M�)���x9�Ó�.#a��SUejڝ�m��XS�`���*5�,����
�x�i���u�(�=
l�1��/�}j�ѻE�~��e��GOwh�ER��I�W���� ��if����<��8�s
z!;,w8�ppX�����b-4�q�������
���\�ff"�I����Blj��w��/^�2�Y����=0tA��^�+�#�S�F�͜�s0�����!ټ�\��?֮5� �7~M�]��#]���G䰅��9�p̖35O�Ӝ���I�Q��p��JY���=@�3�F�	������1U4��M�q��H kjj3�����O�g4�T�
�#'��

��=�bE8�&�UrX�����i�����QW���p�[A�5zB�xp8=u�!��jw��	a(`e�YM�#�dy�>U�����.��?�
L [...]
+�ۭ���i?_
+���O��
z�%U��kԐ�+��U�{��ts�3�
&���n&X��R�'Tl)�܉#�ZX)�B���i~�-��;Ѳ@vx�����օ����]�'%�xf)5������e2�
�.}���qZm!�����

x={���orU�z\�$��
��K�j�eE]�R��҈�a�n
H�s!����� ��ξ.Z|V��J<����
�2	P�.����5�Z�/��l|��zoK�v�Ó���,�"2���[~咴��6Dt����p��� =�p�>̫�2H��9mJ�^
�=��Y�~���16�s���+�t�%؝�l�.��?�����
hs�������y�?p%�w����܌��1�ms�a��`� �_.����@-���9 2DM���v��O"�?����
���=1��[��A��6������
��ړ���v/�#�5K

+���+��~��_��]w�
�BقdzZ
dJ8ȳ�˼��n'��j#u�
g
�R=XB��uH�8�����j��r��RS�(}�yLQ��
����~�J���H޷cYF����޼9_,��uw�F��0%�[���!�qn��
�k]r�CBT�Hx���
��D0�q���hkb�Y�E�1��8�'�+T
8�/��O�E�m\�Ÿ^gT��Xغ��[�1\�,1�3��VmM�c��:��K_~̴\�W��3^u�T���Vtج��wcI}�uv���s��-�"΄���|y�_(A95����p�T�S$<���\,�?G|�P�B�\�ԩ�e#��n�
��S�!���X��1i6� ��Gl�Ԁ,΂_
�
+��
+��)xn $����S�`zv����c�_kl3�
a.3`O}�9`���HӠ��y!��ٗv���_�5���\��S�ث
+#M{�@v`D:P�
+
+���A�Y�Ӹ0��;���Ii��s)
�T�3h�ZS�,�Խԍ�ݔ0R��g
9~�G�$.�j
6����D>&�ԣR�N�����F.Ju)J���Mc!�=7l"Mg

Q�:�"�B
+��$ŝ�6Xɽk� ��gU�u~o�z�ԵXJ[�FZ�jyH����� eV2�vx�/w
����K��H�QM
iF����`Ox�!�V-�5a�դ>rTo
BH��M � ��]J��W�,�����H��$�TI�xյ��,�T���~��G��wŤұ-m����mq�\��"�
+�O����v�:
��%W�&o��&9H�B���l�H
<�
+��������� h���-|�E�zT���
�!%lECߏ���U�X��@��T�	"��NQ��y�iB
+%���l��J�����̼����	"miw?�H���h��*�DZ~�m��!$���ěd,Fz�)���
Ѷ�i�E���e[;�'��#����
"��Y��/�c��g�Ҟ��?o��HK��m��s�,�0kމ��׍��nӖZms�H}%����@���#�i�C�F:q�yL��*�
�C�e�#-�F�@
"51H���=ބ~��Gz�k�4�K��)��)���=���ӹ� ���(��f4V�4yy���B���<Ah:�J�N�T�y�b�ѪO��d��xHO��|[�9�����
�;M4P��ȫ��G
�?��C�S��f����V�ۖ�ۥ-3¯���D/��5��1y�����{��ه
��y�{�J�n�����b%艾�9
�����x��S��}ܡ����-wQ���Iyd��(�Q���IF�׾�&j���
����mӸ�)�
�2�@��$W�	���
a\�D߶��#��ޏ�W-���R9dD߮[�D�y�@�회
�~
�T
�E��
�HG�b�t7��~��4ٞA�m*^��E��
Q�]�bq̡�D޺3�T�ps@�56��(�6i	�2��
q���2ոX�6�~'i�3�7��6Gɡ�=���D}��1�E
-�$f������m�?���LD-	����v��(A��7�wR:�ኙ������c�S
~��"ހ��#�E�N
����V��[���T�Ux��I�:]G3Gܞ�
+�A�,
�
�s�����_�H�&�k��c�"KG)��bHgl��:��Yh}�D��t�Ѩ�H��#u��
���H�R}Y�l�
�
�H��/�؃@�0H�X8c�">�đB�_����Rx�!�"���E�t
+)�}Z�S48�:��УO�D�_���v��v��}��
�q�ꔟ�s/�uGK�s/NK��
鶐:5��&B^O�p��c<���T�'r����ee�G���Q�@D��/�Eğ�&��� f'#�h�N�1�4���uK�0��j��>���.�~�Sck̴Ϭ|oL@,i�pG�(�S]nV�
Th��u(��ǬT4\�=n�ö���� �\+I�Sk��)v��W-X�E�C���h<w "9���k"�����yʘ�
�gF�����m����󧺏�@�1�B�)A,��G듲,dK�ݐ�%EA)�,����V��8;2��ҽ���;Pn���6�
�/N��
+qbqE��Q�
R\��=�gK7�˞��w�C@
%z�i7����,�S�D��ig�	Ӯk�DŶW"��к�ׇ������V����鼆>M�a䍊���F5�X4��?����ڿ4 !	�0�:,��ِ��Gz
�\��&��>Vk3����������˽1|[9����:���r�	�Btg��
�nL��;i�{�XٹJΥ�nj�M�Ϸ�uH�,�dԥ�B�	(ƞP�L(�~\`|w)��6��{�X�Bc��{IO�b���旦�A
{���+�d�~���=k�Y��nL2tF�1�f�/�ےe~Ӑ&�׵'!ޟ��rZ�X�=��Jt�͉���9*
蒸Bw�:.o��/�X<��93��%��/]�2������NF� W���P^��턗֕6b^$[�{�b��)ƕh/����Ì����9�Q;朿��d��A1�Vp�v$:K�
c)��\y�*?ƕ��Q���L��>�d
��@K�u�t����]��S'r�o�O�Ša�'���4E��&
�#�J~��) �#<��o4y����P6�Qd���@���
69u(�
2���8�牅����pͧ^@ �� � &����J�

+��N��( ���\��Ko�r@� r�}��ie�\!��
]�?���3���,<�kbQ{�N3��
'h����`�/�r�'}b%E,�,.j� +	�E�����N�m�2x����V�s�X�Jy
)_B����F�%��ls\
^�(~�Cc1=�/�Ir0.�(׽q���]�]����`


h@(R�a���oO��(p)/�6w�o�} Y���x�@�_�㑵�Yr��i8pT�ؕ�J�u �L�e�
eR9�W�_�
���������_pF�^-oE�l��6�<O���z�=_�yf��/�F��}Ol@
+\b�������" �Mܭx2��3|�W�:1]P���=ۇغ,5�V����
8*�L�b�:�JN��X^�y?��S����� 01�����,����
�'l/�Q�oR�Y�����p
��zC��Sp��@
+�ݚd��d�+p^����� 0�	�k�(�|P��
���q&Q��GN�(�T�?gC�
氼|�'�D�XN�,R��������%�y��h�5� O�D�$ab�w%Z��h7��
��DS�<A���.��\�n�? ���	I��y�y]�=�.(8�K4���WG�4Ȕ��Oq�
+\H�lB����>:�Q\�7��<�q��������
�ŐL�,	��|bf�����Z�KBV����?F?p���li�%��/�IL�<�#O����0 ��!��A�;y�{�.ӽ,p���}�WM�`|F�]pwC����~�Z�ce�����i��f�|��a�%�^�
������B{᫻���]Z����~ςr�
���!8�����*G�n(�"	�;��r��!��aO?��`
�Wr���0
Q]`x��6)M2N�:�w|�<?? �.w��%��ұ�����fb���\Zd���iгe��\���uItE�؞���ߘ��ö��Xeٕ26&G�3
��\��A�
�H)��&��E�`�g7wo�܀z ̩�
�� �y_S1Db�L-�|�0f�J�R+Bq�������\�L�.��E�ŝ�eA�ʖ;�`�]u��Z�f�;0o.%�AG���~
{{̠�e
�9�N:����Љ"Et�ق/��Igб��ɡ�Π�h}o��Ig�q��ȡ�Π��|)�N:�e
~ �N�
�[�v��r2��ś9t�tH{�C�	H��0�hI!m[<^<��"�K��^�y�A^�ɳ��

K�_�\O�7���_�:����3���r����x��d����̉�=�&
�%o|���,sN��x��G~�Ot��]�||⹒�P�

�KIs�dM�
+�����@uy)��
y�m,�4F7����U�CS�Lv�FB��D+���
c*�M�؆k%=Kv�O�
X�2%
�1M��!)^6'SX
0n����f�8>�|�'���KF/�J1�w��|)��ef
>����β��أ���p�;��$�M���?�X�E�.�,0����{�v���>��!�o�,�E�qZ����'�H�ҏ1���R%֩�P����=���
E0Ks=���'7��wz�#������2DO�ɇXf�+���x��:Xߤ��4Q��d$ڟ(�u�:������
dr��e|��f֝�k�~K�|9
 k%wG 1r
���H��32����������6�� �c� ���(`��j�K���

m����J#�0��A!钆Yi"F�ò�ʑS<Is�q�$}������#�P~
q�Ar�Ɉ�J�;��0�(M�I�܃�ψ����Dzr9��wQ}�7��{G<͎A�g:-�x<SB|	���t���
:�x��!�%.3?��$���%����IqR]���a�����Oxdr�#�f�Є�2<2�ߓ�
u��y�#ò�s�{d  �Dt�
ih��<d
�ih<��XF��<�K
A?NFz���
����J��Kuظ�r�Q�����(��hӨ���s��D2�y	T��qꀡtObz夡�1�����2q��
�c�
�ق���^�}�PEyu2��$��X����ϝ�y�K�X���-%C�*�w��g27�[λX`�g�� �O��I�ý~��_�ᄢ�+�O�ý�g�B>�T�������M��'p#�h����8�P��h?�ǿw�ʈ�t>��[>��9��j��|8�-&
endstream
endobj
968 0 obj
<</Length 48055>>stream
+v�3��Ϭ���b"(nL��n)'&�������k�j@H������;L8r�HD�P���L��H���
&׉;�
�Y�lD"��G�Cij��d"xL(����aC&���Ux�
0�ke��(vr�PB��~�^\h��
�y�}D���$BVy��S8�W�ܦ%f�x%���и^i�m�zӣ
&�I_��Ԡ�g�ڕ
a�Y�b�?e���CI�23R�ʉ
���T��d�����H�p>��
+����H�P>��
+�Ȼ�g
��!�4�� #���}.v�fC^*��
�t*
�痌��D*��|<��~K.Ťm���7R��w�d���T8���A*��L�}֕R
٢�}�T��R4VU΍�\},iyb�
�ܲ<�2
����v/�0�
�z���F��<‘���r�-���<���W����9ܼ��ÿ�j�I=��e��LoZ�!��]S�_
��H%�^�@򓍨��ʆ_�S,��4rɄe�L&�yX��~�mG���e������:�V���-�w�*���Mv
N�E��Խ4�!l/�a��v���fVQ�6���ʰ�˫�X
�Hi��g!��b�g������,
�ʄ�0�N*��n�!���
n�2�<*��s�%�}Ke�m�3����(RMa���!�K��vđ�J�iQ�w��P
i��a�f0,=j�^���B�(����W�ѥ�P�譳�PDK7+)B^7�
U�w,#䖫�w�X8gD��3�=�#T�^�:VG]b��It�Yp�8�z�d%9��#w���.IU�{�
�M��|�
��|!��Y9ɸ>���I9��	�}{VlD�����M�guFxw��Q?N>���ⅈD�]������%��o~�W���[-��e�ɼ��l:!� �_�Ϧʥ�k�x6��/^8���l:Yh���l:!POn�C6�w����i�{�Dz�r����g��r�d����M'�k�U`�\6���"O�G�鄔v��g��r�Dn�#��KK�����l:!�T�:�Nh����̦�zZS�O�tb��g���S�l:
(�������D����$s�>�M'�[��l:!  ˇ��NKx1�Ȧ\���tONF>�M�|�D6�1m�S�t�2�>�M'�K'Z��}�����b/]�$^��H%�6��ħ�f�ߵ�e��zu]��S�O׫�.���bԾD'�J�HH���T���8	
+"Y�b��uI�(�Q]�{0��.A��N�TvY�K�F�Ne�ED&�ŸQԞ;�,"��xR�\�3w��%U���2w�{�d��)s'Z]./+WIf�;�L.y�t�$�㓙Bw��U�{�SeF�K%���S�"$��e�h
F����e�ܷ'���


����mڥ'Q~�E�c!J�<�r�9�
-���>EOy`�������'L��Ƴ�^V"���f��
C� ��� �D��
Ad�:��?�J�Wa
`Vi��D��T�1
�
%vޓ�l���ʼn���I<��h( �i���h( L^D�t`3�}�||�(V����}�pd�v�Š����Lv�L������Z������1����ܭ��G
+�5z+G���.QR6�H��ޫT
���Hf�=FPKZ�b1����#�)���_�$
A���`^Tď�e�~�B�b�o�����E*��8�%���n�j
+ʍ	�n8|-V�)#��^�Q�
[2dy�߮pw˯�q�6��k���*�Ie>�����FW��H����D�*彛Ot���>JT���%���K�;�z��������j���O��
5G�z��X
�=Wsr
�6��k����w�G0��(���=W����
�G�9�6y��S8⹰�$&ųk&P��W�ۅ��ا�P@�
�0�{22�Z��o2Ә�$1i��%����1q��wʀ�ϋhS@'+C]�l�se@'�+�$1i�;���W���R�X��(�Ӿ�v�
�7n��)��%v�T
�O�&-ⷊA��Պt/�{D��Ǻ�����N�>������u
fr~���Jy�?渲��
�!#��y�+��g�
W�'���wS�`�[&� ��dšk�y��������GF�����>��#gmDIPr�|��'N^)Zc#���)�խ�]U�:l��wW$N/��w��v�L���
b�
��[��Œ�z�H�X���):V[Z��E��N,?bu��
�{&C���B�MM;k��������E�7BH8$0��
'
o���c�7�� ��pW�1>X~F�PiZ�G��������o�
'����&UG0�G�J5INd@���M�Ot���rg_��3im���
��
�����b�I0残�t�khow�LJ����̰I at T�
�q��=���7�a~b�S�xJ�ch�h��J�TRNj��Ħ�*� ���,r=I�th���=Tfꯄ�Ie��n�|#+�I�&E%����;�zu|w�5̻{�ʢH�
����"��/Ei)p�N���_����qZt
bcy�*Ջ��שǚ)3% 쬌����`�O]��5c�n8���$�^�{�3H�s-���peܟ�݄��_��z���g�{�&�|�Z���D�ŞY-�w�I@��1nЈ��|�ށ��!?f#�I����7�p'�����y�:N��~��.;T�Oԫ�:>�}�����O�pG�p�D��zo�e��dz)����=�.��_fi)��Sm��%V�>}Z���S�j���{�$R��4~2���,�<QG�b��5�2��gUt���Z [...]
+�%��h]?��|�����CU�?T ��'= �տ��LG���\>adg�
+����~�7���߬�'��%�.���~�n�n����'m�
+FA����P�$�z����@��Ku���@?�'��I�(d�y'񝟑�׺~�&���:�퍺~<6�q��q��z9=�v���4��#u�����W�u���Y�o��c��"?���& �`?P�O���k�����Ȯ������z|o���Cd�W�9
��I�=<����Z�OZ��7
|����
�z<I�[��
u�v���
����>o�F�����|k���^
������W�{�
��$�g�7<�j�V�����^]?�c����1�~]�{��T]ѷ��I�9"k��~�U�޾�������Of]?y���']���z|���I�Ǻ~O�gU�cay��ߣ+�]�O얳W��I�w�v�?���t����\�O`^XU��_���~K.�^�y�+ߨ��.��~�
����\�
+ ����V
)����~�	���v]?� �U�
�1�7Yq���+A���&+�u�d�0o��c����Dv�
+����
$�8?�K��V���KJG+7�#>��J-�y{%x*�ڕ��-rV�m�1�7��O��hT:�i�3��Y�sϝ�%�%Z8��7�y��m%��Kj����R�`>�.F��n�Y����̑�M�_mt�^�8&l��R\u�&<Xo<s�O���3�b�Xs��o�u[\S_��X��.�]�Dm݌��EO{٘��ǖn�P��z�l����&��ϣ��q�=���S�ڥ�V�ԥ=��;��_��o׾7м�r;#�F��Y����9��!�6f#���\Ls��GS;�F~���kgϪ�grvO�+�Lˆ1l5�-΂_yK{���ν=,6�WQ�Տ2��_�*
��i� 
�{	HXO�:��x��""�E�ũ�DNJ2uc�j}5"���Jj
���j3�f0�4wKŮ����Պ;�����F���3d�W�\���c0�J��4��[YCbM���*p⋜wP�d?]�xJə2f��r1�y$��u%Վ9�l�Hz����6pZ�X�|��n\{a*cw
�U|��+9�o���T������+
L�5Qf}��=!��f��`4��BIb�ۢ�}���PĻ_���
N� ��MH¨�`�>�I�퇤�L9�> 6c3&�J�2٬ݤ]o
���/��������`�*��+3���;����_
�?�v֋t��
J���n���/�د~\����7�g�1�����t�v�@���H
@��ş\��v����h�	Xɚ�;2T�(�T)XP#��l��ybf�k��6�z��
z�EOO]7k�o��=H#�-4g�����"����Ƨ򱬍{�F
+�L��
ۭY��)�Cl���f8��75�Qr�����
� �#�m(pr���;����6
'���v|H�C�Lh��c�t-[�F-{���S��ʖ}$��5
#�_�
�d���5���	IZ�,�i
�]��'��i��Q��5Ha�b���K_:�lՂ����='�����_m"�yW�aƩ�Ŭ�VC�((6
wu�ZL��:�J�'V@э�G��]:�������GxPoU��a�����+���[(.�ư>�
�Й�|d"�uչX(g��D2ܪ��`*'h &�����|�X�@�D���$�8�;���yJK�HM�L]3J/�H�jsO�P��mƈ��I���{��z���H� ��g��m�P�༹�P��Ck)I�e�0[���"�\�P�0�ڜ�'yS�r[�nH�>����b��o�A�Ah��0���ۑ
+%H�x~gP�{q��U�1����lJ2��G�6A���C򃎺
N
-��B�F��3o
tsEu���au�}*�|ڕL�0,�e�;���`����P8C�0�w�[�ޓ�.�g�d\	~V���-��
4=�i��0&���]��8t����t�3�2M�f��8��{W���YI�8�6W��<�N%~��q a _
{�`�f�&�m\G�����E+z
+6��=;�n���M�
/
����ա
?ջ��gtKT�j�J��˯��et=���9��t1�M���������ר����yqu� R����{g�&Y�a����� ��c��
+�Fz@Ĺ~�#K���}O	-����L���l�#NԬ! L��X�0F��F����.�x���mm���=�f��
+�͉��ѽW[� �

 ���k=1F8t!�}0q�E��}0���+AX�%����9 �NK�Qo�L"�hx��4�;O]�S���c�B��C$7:}dr0���>+��$��������0��d��Ƣ�s�[�_y$�66�_�ܯV�X�Ա�_Mܯ\`V��[�\�?��`s�m��ʹ�h��v����̣����b�� ��X�3a	��Ķ�
�}�ku�v�G�Û���mS�6"��#����I��$7���.&�kLݣn�¦�f����c��"
�
ׇ���w"�
l�_P��b�G��M���6��#��z*]V��Ȯ 
qN�Z=ػ9�T۞#��H��9��Ƹ-��i��J�8H[>��t���W����X��
Ù?�6�$��ԽD7��6_"�E�7C�5t�ԩ=���L���0�,G��=bv�)
��
+
�RH���Ӟ��ⶼ}���f�;�0܈y��W�ɶ3��^
7�h��%�݉���)б85!O޺�4�N
1�g�a�@Ŧ�|!%���ۀQT���MI
t�0��M�r��>)d�4o�j]ʨ���Z6u�E
F3��I̋{�˅J��,g�)Z��3
O�qݖ����#�b~{��Zj}��߀
g�v�!�U�p�Ȼ��)l�JjGh����p��43��І�n��ɸ�e��
�i(E�ƚ	�9���b�J��̾��{��l�^�ٳ� �h#{,0[�ga7Ͷ�:���)�C�w�p
�}�Y�ԲO�ZEd��^�3�+
�C�O2�X�K{����+��f4�ا�G n�8�⑃����DX��p��Kew賡`���>��[��Ձ;�_1�3��y�Q��x
9���6��Q�TB������0�>�&ʀ_4
��(;7]�EAo#V��%�C4mD �=
:�5AC1}
�����
�U��n 	���5yL%�m�(o�q�\`ƪ2����h��~���
`�������h�,����x|�aC�B��*����
4 ���p4����n��E{[1��z��IM�G?{�{p�i�
+A��Ӕ=չ:��E{�X+�4��iK���!��@�8��@�*��ʪ�����_7F��f

+�@�RNNth���v�eeΑy̾�f �͒��
r0�����_8�V�=c>�
#�_bvM$a
i�pJ��D�= ���H9~B�[��o>��33i�M�1��q�
jҶh�}���U�B ڀ{!��7`s��1̜������%��堻�i[~�@2���B�]w�2�2ɂ�, at R����'�'vȄG��ls"eRT�|����B�*��n�RT��|�*�q'W�|P ��[Uv�s��s�d��
��*��	���Bf��T!EH4��U��Mc�`��ʌ4JF�DQj,by��u�X���^(ͨ��<a �*�ݩB*$�x}'`O7�ɛ��9���L��F�|P �'t_(_3R�rց9��U�7�+����TD�j��� �8\�������
x��A�
��u
��tp�d��ׂ��h.h
k(kc
+؇q�^���X#�
.���ۋ��y�;f`^ y���(�YX�Qm:l`��1��&�
�t��^
�
zFȤzG��{/jvT{hJ�h
������ɏ�e�&�y;U{�S	|��}jC�LՊX�>�f�U��/�M^�RQ'����l.8
�Q�C��l_Kl,?�xe�(�,Vg$�=)�
��ߢy�9
�
z��j!����KE=O��|?��U�J}�*Гְ3���u�������p�ND����o�o:
QMB�q�z;joؓ�
~��b��F��
~rR�(݊
�9
g�оx�g��-n�Z�n�}��`��P �m�3�N�i�0
Z(u�v -L��@�dWZ�!
��p�����:߇�A
zT鼞οs�V�I����&x�t
�\��A���NP�7�	�a��A t{3Qg|�!-,��'��F�#ᙿ�ȅ�6ā
�K�'6���R�Ho�4?nv����(|v�������֮���|Z��v�L��������lO���������u;�]��Y��d6�s��~6���b�#/�&����d�b���%��:������֍��
�3���5hfD�!
�������	$%���>����ה�Xh�X
)U��$u$�Hw��; o�_~'F%Gݛ�EM��Ԍt
��p3č
tv�`�P��т�&�XԄϊ��}6^U��9x	��b�s����
f8 [...]
����T�FE}t
̾=�aA+�
P���C���N�$C)�/��񀜖gw��z�K2��QGײ!��TQ��U��4��Dv�nQ3
�}r�] ������
�X10��5)SA/t@Ťi����cC���NG�L�P��\M�0�~�
+!�f{��!J���(����,��w�"�I
+m���?�I
+m�
+�ӛ���l���$��Hn)�ۡ�C$.;z��w?�9�f0�M���f0ݎ�E�j؛r\��m#�lL\�`��s-� �p>��rD1`^���/G������{�F�s�
W��[y���~S �0�:��rS�5�|�P��o���<��Ӄ\�z���h����F8�V:c��Z�"� 2B(�Y2 `�
+�e
[�B�L���Ȝ �C
�����=�o�!�4����Ʉμ�
}T�E�
z���\a��3~
��ɰ��L��vq�7:�'�n��j�Wb2
�c���������}���ȍ
ѲCb^�+�@˞�?
���U���b��!!��}6ɹ��[
+�V"3z���Ej�y��T�
R�,9[��O�v������ܲ���}J����KB��J� �32Ur����g�J~����*9�؟|F/��l���JN]B��?V�Ἀ��T����N%XX>��+�
�1���U�3e�i
����!�k)
+sz꘏n�
�������"e���zt\��N	;Tf��	Rw���
o�3S�d�׾�b�:����� ��ͽ\�~m�b��ug��
+�$�
�N5~�dv~���<e��,V��$�R������GK��l�����~:f���?QP)k�S����q�>�\��{����v���'����
�k����p��^?x�O
�.1>���
+;>��Ob5������?��Q�Xhf��t��?
�m���z�y��
�q�_���|*+l���v l���9����d�=>�h�ټ>�Cg���� ����m�&�u%�
�?���.����ݲͶ0�ڕG�at���ۤfE�
��8���OV��H�d~awtf>�'n��s���ÿ���X_�����p���/��|X�T
����j|�������[zh��5��/�W�v�p��kx�!��0��)ɹc���m����|�X���_�=y��_�w�%���0n&�f�Ju
�?�����:��0rޟ���v9^`�s��k6B���2r����c�a�c^���>^��]����o����

+�/<����
+��
���g�����|������O��?������
�v��u����
����g�o�Y�k���o%�X�x��kC�@x*޾��/�,�`W~�d���?���c#� /8�ݷ�PFK�
[���7
��eay�����L�ć�P�6ި�_�x������8���55c�ø�;�Y��s��9��
3�=�w�P��z9�=ŵm��)L^~�ξf��~��z�v�/������׹6|���6�ۯ�i���؛�?���Ҏ��[���#1�;��g�'�4�l쿽ŗ���8O��T���1>p���ث�
�z����|�O�?�=3�������3�v]��ʿ�{O�s���wϡ�)RoV�����Ϲ����XJk���}|��P���[#N8������#V^V��>��su=ӗy�>�����Z
R�[���ü}��M��7������o>1�w�|�yl�x]h#7�����}m��1[!��˖�����}�aA��Gʜ|��K�x�4�cM�Xcy�
��=��We�k��9���-����>��� �ڜ3��f��:'h}4���Èk�5�$j�m}��c�!�����8���� 0�
�a�ү�u��:5=�Q����	�x�k��og3�..-�۽��o.X
?@�<~�`y�����I���ϒz��(�ǭ���.��V���!k/���׼��ߚP���#ϡ��׿������g�6��O��\�1׬�j+^���}ic1V��x(ev����
��|�\)W���@&����������-��־�X��z�
���6�������>��{jNI_1�X�+,PuɌ��dY�������#�
� ]�k��PnK�^��Lij-dN��І��zs�}���%6<&����늱��
@{J
KY�k�j��
uhm��[է.
�3�4�}+�7\82���>	&3��m��B�u�m���a&��	o2c�|:
�M=� DZH&
z\�����I(v|�JiD��H�D�
eߖ�vn�:���6�q�Ӯ)}��o)��j���c/�pL�A��tȋ��.F�Μ��-rvZ5�`�����`�V1ʒ�y��k���r��j�ѿemin�К_���
���N����-]e [...]
+���W*$�\`*��ZNJ�ZG��H}u��Һ6d\$SYKY}��Sb��i�Ш�`��Xz��[3��'f���H�.�K��
�!��.�l3
��i$����+��=7��A7�0�΄3q��im���vL�3qm4L��i
�uq(��{Auax����,�R��-G��^�؏��c��R�c)U�A���Eq��\N��KQ뾰ks����
�Tđ]���g��XX�RZ|���P�G��
+KP��ZrGk(����3�d:c~��
���ud�����m���@M���ub�,��!��n�Ō%�4�-Q���8]��3�"\2�j�p��^�\
��=a.|G�t�����Ҵzi��*P��V
�
+����}\������5�ʹ�
kg>��A�-}Nj���̶�#�[�
�e3`B���a����x�	g�X�:�x�<}�M��"�s)�fN�1��>����+�ݽ��������e@&���們�&NS,	�iS���O�L
N0�A�
�}��Jˍʾ�H�Z{Ӵz]ǂ��C#�d�J��a�@P9y�|]?�I�Ӵ��o�xt�
kK�V,�z�u�ֿd8��H�k��ގ<h�"�����z�PI
�Ew��4
�5��^*Oj�਴�k��OTz�
�x�/Faw�r�
+g����#E�2�u
c ��P�.cI�=q�<@���(k%�12�$r.�z�s����;,�4,K�Be��d�\/���u���6���z�����+5م˴�H
!h
+۔��*�0�@2e�e3m��/TθEe,8
��ƜϢ�ִ{�l}��8|
����6I��[�d�Y& �I�
&�	��Cr���-5�:�1P�O��+,�
+]X�@/f��DeY�LU��";��,YY��B�3T������c�2�x/�-xRIM��}�C;]�r�|6
a��u�CϜ
�:�9˹����:\������Ev�@a9g�’[e�@����̭���f��Z{��
+X�>�&�K�xߝ���Y���WXf�-��Ѯ��׬�p�1񪐻	K�\�0]X�_�ޠ#���
��`�p�袝uÒЁ� q�"T�u���K�=`�>���>a<5S\�9����/�K�iX��7,s�H�x�������J�a-�I<��{�me����
X��G7X����U6��r�2_C���Cm���L���O�q���g`N(d�e�v>��Rp��
[_�v�
-J�v
�M:�Ҕ"�[eԧu7]�j�@�Q6wy}Q^��,�aň�����e,�8,yR�Ø�G�|ZV�=��f,s���s�Y�-�ZR�2
��,3��Sn
+�r"�
�1�%A���������f
��Z�)�
+`�>�&��i�bYfN<���%�?1�%�}s�D-��M�13:��l2C��H�KPrQZt\�ȅ��i
+e2��R�����1�
GX_��V��4���
�`j&�
�aT��
�8����O� f��Mg/V��H7`��b���sm�	�撄]�LC��'����Z��f����o���˵N��_�A~�6	W\"��Nr�
��ӹ�Y����	�����"�8,ps6^�Ҝ&0���� �V�&��0�L^/i�'��DqUK��N��0
�)#��	��e_�.�=��K��-��Db)�d�� `9�p�L*ױ��ǙBT�u�S\��]*3/	��5P�����o��X����!�w�6	�I�-;!e=;�\�4�>�d]��m��Z*�W�
���I�y_���.�f��+%�l�)Ɇt(�%�Ფ��\��(��`_#�v'@�Dg�5s�|�\�$����f�����,�p�:��hq��ȉ�"l�ʘh+
bq����Sj	B��3���o�ء'j�i�	n�x,V��u���6	��nY��*�sy�{��ֲUN���HIɥ��Fj�%q�fa��Ӂ�1l9Qp���d�|�
o�LLeYƃ�
a�B9ٚ�b{@��%=܂�X�
���7o|
朁
úۥK��?�J�
�KG�8җ^�ʵ�&�����5���w
�
��\��c�br�Q�o��X��ZN�Ӈ�$8&�
��x��H0��a
8D�B��	�2
��P"���>���i�Ȁ��UA����*�B�O1�������:�:S(�ť�늑d�J�\� �5���.q��!�Z�e�8���>{W��߿��?�����{���!�6�'��Q���G �w-X2E
>���K,G��
�uی���Y<V���5���C9	WQ)C;�A��P'��((+��
�Q��(���J���>t��e}'��m��F�њW$���C� ��
+����,���=����.�P���5F�P=��9T Cec/=&�(`2�
+HR$p�g8`�m=J<#F
�D��.;�j(�I
+�7��b��f�� �L0JY
+�z�
����N)l�UĩX�F�Kgy��u��Ls�O���;jrj��v�#��1��O=h�$�n4'2 
�
O��}�(��H
�G�E�d��튗@��>��K��/�w繋����ue�.3c��D+�rjMtN8�뚀*�7ӡ׫�JC�%��rX:c������֤)��?�yH$.���Sd���4Aݺ�&��"i�͸�d()�I���w�1��H�f�hQئ��ԑ

VT@����%$�s� ��Iiqh"���3��A���!	���@ZV(��b�Kd0p��Zf�2a���%�L]�+P��[4L�F�O$^�[�ȆŚ��
:�-~/�4[=�
��W,���ȕ�?K2Y��KS��EFg0!�k`bDN�QΆ���t,� ��FS��0^
M��"3V���
&�ر�����p����"�>�/8?p����6��4��ʷ^pF�m��h``�d�?A�ję�2�w�R$��T
+��@]��F\e0N�R�Y�X̛��ܟ����q�	���^��LC���(�za��T$���S��ӿ�$��\�%�[���@~��r�ą�q��Չ2�u6(Jգ)�+�"�i�8�)�H|���<����iQ��"��w^G�P0V�C6��c��i|�.
+}�o�ZG{T�+L�2�@)�� =V��fUh�1��5�F����eί�6� �q)���Lڅ<�4���r}�T\$��7����#S��)–�Ζem:z*�������׋�!
V:�b*�F��Z�
�.��l8�5L[`�5t4#!6��2���cd�ɷ���u��w����V�*�)x�2d���
��R�(��I�"wE�J��9:Y��ưX��Ě���AK����F�p �=��S��i����.��2�
�u����d�Q�a�uf�՝���Z�,~���]�ݶV.�O]c3(pwWqC�*����
�
a��De��P]��*����`s�J�蘢�кU?-���,��=?r��NL��6Gi=<7���
��=��2a���J����c��ef&ME���"��A��]۫Wݪ�AQTHo!�!8C�M�J��K�u��ϦCV(�y|D+�[�
"�#�]{;G�jM#JJ\��u�N�,�ܴ��꠆��
�-X��dk���rYS��!t���� [...]
>̡����FCz��ʬ���_�9����� 4�ӏ7�y3P�xg�
��J�G�T
U{օTj)�y����z����}�ӄ�}p�v�;E�ݘ������M�-�Y�M�S03'���0,*##
��^ے�Zr�Co��&�b��n'�a<�����3��KK�(���6���Θ�����1	L��f�jd�b+��DG_�*zn��Ȓ
��|��#�ȕ܅��U0���K�Z�rb�5ę�O�#��J1V�Ize g�UL�\�F�iO��ET"�%Z
��?3G�+e��,�Rn�b���A��y�r�
xMu����N
�I9�u�BD���<���J��e��1�$�J
�!"\QL�:9�A�ą���3)��P�r�3u�RN]PZ
+�
}�x��T�vv�
�3�mF���b��Dp�@��!���v2YX���~��
\M�I���W�7au
��Ze�"S�J��DE�K��B?�g�Y��s�C̄>�V�Na��֢@���hJwd2�ӷ�����]�V�ͳ1�5����-ݽY
+i�?����2|O��!��4�B��?���������J8���Z��͌w�
+߾�u.^l�C�/��戂D�	D�dv�fvO����ؠ{wB
����<OR�H���D��'?���$"��}���}��w�|���������77�D��GFt�~;�>�;}�_-R��}����c2�����Z,�s-�����by!W���F6��`B�
1ķ�"�]w�Q]Rt]���w�b/������?���qM��G�������/���~��}�W ��ÚOM������?����͏��?������|�|���u���\���x��������������|���?��w��'��������>~��z%
�1�'��������g�����?�Z�
���_���|�%�e�������~���������?���?~�����?~���~���?�_�t�����o���N�������}/�X
+���
�4q��ꣻW_��?S��
<}q��gB�۷�D�LE(.h�uA!��:��0+.IJ�z�
1�
��U�؂�Gh�z�
I}g��lN
+>��9��I�%�>b�Bj���BZCL�P
���} ��~_P�U�u��6ŀ��"\;�����`P���9�Y�#f
W��e9-*y��I�w���e6��!4G=�E����9��t��u���5D.������}�ۻ��咕��≵�����8Q��]m�R��	a:-�*E�h�Y�
A��o�
�U���p�V��k,��e�	����/���):w1�.?�1�Rx)Y|2j�7���/��{f|���#��Z�c�ņ�r^ho�v
��A؍^��g!����m୩2p������s�������V�I��/�����@�w���3KS��Գ
�
��y{�Sς��?�+үx��ٽ���G��������Y�ki��9��-�65zn�s�
�
Tsc��L��`N�g</����VO9=�P�{{��g��
?t}
?p}
?h}
?p}.�r�����f6Q]��l��g����J-&j~�JCl�#K����̵��ʋ��D�o���R>&}�(u��y�*�
+ܨ�s
+�z�`�8h�_�́�?;�=��!o�y��
�`�Y�^~`�BQ|Mj`��
#}>!7���X}2�%�PQ��a���E�㇉�ǯ����s������r���0�PeZ s���{��]9%TQ(�P�"
~�8�Q�n�q��`��d?Ag�����^M� +�dJE]<wy�f�{0f
�$���%�oVE�0H?�^!8H�'81;�kMy�ӶgK�Ž\u`ǰ^j����݀n	�
�q�p�
M�}!,���ex,�3�ǗJ�2�M���>Kz1D�#��2������o��O:)��
<��xz8uf�B�qj�v�g�\�t�/)d^�
�΁��K���A��n��
+
�
L����)��Z܇s,��P���rU��?��Y77
��0+�zvH�ܧ�����P�(�<=$���`ǎ�{�
Q�:I�zA[1Q�Ũ����\W$�g��W����D��=�xZC��P��(�)
+7��5����� �f(Y��.Ygu��oTR�CZ�R#k����ʌ��]29'��H�!��ܷ�ڍ�(���:�ҷ����\Q��@j��	a�,G�E��p���-_76�s`3�r���|�Z���)��-ڬ]*I
+�N
+)b�i��9rQލ���ld��#�5h'8���e��՘\��"P�).�Ĭ��H�,D��|�h#1�-PO�	Bsxy��4�C�̂�2[v1����5{���BY��U��:6S/�:
��!KI���1
�%�l�d��=���
+�E{��Y`S�`�����&
+���ضn?��EX׳�P>�,�uc�R,��ֳ+R��F�Qܼ�ҳ׾�S
e�5�s����Aɖ��jM
U�k��i�\=r]y��H_2T�������^�3���1}���S
ϋ�q���)t�c�F��XK����G
�Ë�%L�2M �Zh!|	�)�a�S� 0݆�ہo�L�P��W��¯�j��d
+��滽������x\F`:y#����Զ
;Z��ګ[�]Cc�o��ٴ93�ev/kʤ�W���
�L����pnO�c
���įˇ)�p����ȜI;T��۸����Fj&�KKr��x؅5��;�&U�ٳ���8¤�u�Y9~1�.j��;1B�ϖyN�U�h�'� o�6f�|*���2�~C��#�:�����Ԡs�Qmj/+�T7���9��z9/����ȷ��Šy+�k�ٕ���OT��t+qNS��k�}����.��$�i��A:�4�S|#B_�?�d,&+
�(e��D@>{�� �.7R2{&_�2j+fS�J��[�^O�
3�m����w�����,([ݼrP_��f��J�����I��C4P7_3$(�롚b9ڡI�`��yכ��ӀޘQ
Q
,3R�e�t�L�ժѠ�&��&O�:�[��^���K�K���4i-���<c�V�
=5��f�>%G��KۂV���n26�$n45�j����_��)'_3��s`3�rr�S�}�x�!�����_[N(.v�
ڍ�a�q��3��8����B�͖L�C[��D6ԛs��*�[v|�����{�S1�-Q��jJ��t6�H����
�J�.v3Ҝ;��m�0�a����X��.���{��e�ѿ^`?����;
�:��0
Ŗb�㔶���R�W]�r�Rh�9m+���C'�
�d
��Q��5�p6�2��f���E�ޓB�Qp�����O�x�W���GIY at oJꠚ2�����JR�]
+�r�/�b�@qV�^�֤�P=|2�����
�s��z95�9
�wP���[kpź��T��yHn7ܘʋ�L�D)��;��{3E%mp�~�n�ط��d�1����b�K���:�k/���i'��B��#����K-�%���{e�;a�2k��gN/����Hє?[f�]�L@�y���W�J�ް���D����!oKs�uT|�{�26O/�:i��N��`X��%��øBo��5
�
�AֲR}햕�Z՗K�=D3����*�#���H�LMU+k�Ў:��r���]SI,O�l�Y��"L�H[�ʅ~���1ɼ�8%̹�غ�M�i�ets��bU�L��%�%�#�=����oȴNK��@v:����i{���HN�W����uFG�2v�*3����He���
+��2���+��H�do�ѬR�6��M7�MU
+F
+4���:4�������$@ؐ�
`�
px
8G�{L��p�*���M.+��,�y��Q��)!N�3��0@��O��b���/��e+�Q�����-�

u��N�r8���x�K� 1G�w����LIw��<8�
��I�e�Y�!e�2��]պ����Vas���\o����P.;�L!�q�N�Y3��!2 ��$��48������~}���Y���k���c�
���<���)?g
�
��K����E�'C��,���MT%LR�^�&�� ,|3%q�m�%v|�cAP�
�5Tś?+Y�����t
+��fx*l��\%K`��+dgu��y�焏BEOV�e
\T����[�6�P�T6{Y%
�#:�ed�G�S*�X���8�g[B��Z۳Y\3
�'D�3�A1p
��s0}R�I��>8�I+ ��Y�l���x%�-���A��.� ��U�6� �Νt
+8�6�uE^J�%E����^��!>���P�3�`�k�����M4�ܛ�k
+S(���Vc�&�w;^7 1f{ 狖x�W�V�N]D^X�j�| ��1\���?I9�KQ'SO����-���٬L	�.���'Nh49j��,A�@5��۞Su��N�酊�c�uL=
�D�7Z9R�y<��A�Q�;o �b���:
��rb�F�W
P6G���u�6��yU>�3C�4
+�����^H
��b��u�^(�t�9kJj��]���U
i(6d�*mhkQ�dBwh��<��KP���X�&X�:>";���JK��I�P۾�V|�5�%��t��	~)�
ܘ�� �9cU�a6��T�j ;r.ol����N����̫<iG
���
��
sh�pN��<�A�vg�����}���4���M����u3�Ql'x�N�MP��4�
+�w�`Rs�un'-��6!*)�ւE� ��ʲ-�>Ѳ�{ؙs�� �8_
�9��,
U�A���
��^wTI��T�<�c��s�z���T("z�Eh�H��0�w���jY �o�1
����:o/�"bu�&VG�EXWj0�n\
�n��'v��Z�'���>|3�ܑ�Of�
�@ɓE�`I&J�	0��v���eߺ���`�U!�?�7og�$�X�j2*�2�
��O֤6���"9$ts�R;�FjX�6G��d�#X&E����U\*Q�Z&�(��vD����XH�Ýmf�=�U����gs���善��A�-�l?�-cyx9��zw�_��[�*�J���i��U�uP��8��
i�?À=��h��B�J����N6�G�r !�&2�l��|�t������y��+l���Ȳ�OVۡ��Yh���$�G�bpW�%;u�>y�	��kB+��h���
Ȼ�#�J�K������°�
p��	�a��d�qD����=�7����E��~�ko})	�`���	+�_�-%���e8B�ȥ��zw
�����\Y��i�M���uݒ�����6N��(Ţ[�]��Z$�>�ҝ��d�O\ԗ2 
N9Ȗ��`�;�1���[�4�
3 � ^g}�>d�A��!f?�٢�%��h<Ѻ۝��҇L1�~��++�l�>?���t� F���x��a"���?!�z��w�������o�}�O����������>��]4,	U�~)��8�W
��绿��������}��������g?��/�~��Pj��׵�n$�G��~�gN,���0^����������������)�����;�h��<0a������
'nU*; 

�@���3/A_�n�V��!F�
+�AC/s��o'T�}Ie��|<�ŸO?�k�8ޅO��x����2���_���b�ߑ_�.����htw�Ԕ�I@��&�ԛI5�h43��	o�[7
?��M-��w_ҋ�`?�N?�C�]���Oy���j��wO'�鴏'o�t��
|��ۻ�0y�
���=���^!pa��`Wŏ�yE���㓣z��<������i����~�3�
��!���������ͧ���K?�2!>e����l�ĥ�k؎��M%�s�,"aFk(%�g�ǣr��e��,�(���G��翭�4��$��E�@u�ԕ
�Ɲ��9��b��X�����-Y�&;P�ͩ��T�4E����&�ޢ�ܹ�.bg9LCb��h�g�
S͒J��:�蟾��y�q�������/�V��YƟ����� h)�c0?�������E]J��$mB�O�HɸV�ߥX�_2�m�n�����
���b���P���S
�[��ɘ�_'�f���1�"&��Jʞ�=��,!����\�]���# [...]
+ ���KvK1R)s�SPK��Kl��^khp�\�|�<�s�J,6a
+���Nn!~�R���*���[}6���C�Pe���H��$3�Yu_v(a��kZĢ�G��FO�i��H�b)���7���{�b/��\�~l���Yt�������_��~�uBNSF� ���f%�n%��N^�L����;��z��t^��Ie�"��>�H62��
+�1�nտ�(kҕӔ���9�7�FS[�BQ�*�����#��A==�!
+0j<)�
4�&�H��o��x))�?�"L]�@pA�>�� H�0�������jq�ӍȖE��#
+;��+%�-�z��bE�nU/t;��S�́�0>T��
+������,rOI�0x�uӎU��	��
�V��G�I�Q at jP�5�c��~=��h<����Ͳ��R^����K�$i�c��	,��r�柵��N1��v��q{�������ˢ�P�,�_�o?���e���� ���d9Զ(�ĸr1P�uw�@�tV��Zס
��3��Y��D$Z���܉�M��0�[Yg<��2G�"�"ܥ�A�
����R��K��h�Q�zD�$s�#���nl�ŗ�����,Q�C�G6�s
,O�[,�E��GO�+;O��2)0�: y�>/�o�5e��FJ
N@��� ����,���)}j�X�Dh*��V�L�L�AW-*l;ʆl����l�~�qDR��)-(���j�]��`�d�	��ҽ
+w��,T7�_�
���v�=��My�hlB�p�A���V&�u`5L+��DA��O�
�����X���s�R���ű�w��2�Y{[��Zڈ�h��Z�dR2����*�R�z9��d%*�r�v��<�s�����
�pR�!D.��FL	�kw%���2Ym �t�9���U�P}a�c2fo9�޼��m��P�řL���d]�/��S!ٽ*�v֎U�A�W���o��x)7��8��4H�DG�z�����RWI]ԧܘR��-�Ѭѯ�r̦`0a}�̤6y�Y6��ݐ��B�݋����
��@tb
b�:J���;|�x=��ׇ�}*xlq��G��TA�.�kg
>��J�`�vs�`��&�C�j�f��ש�Y��v��7���B~��>#���k�o��m	�1^����)��P]�
��*3Acq�
�
+��+ݵ�J���� 
�͔CX�	jhCI���X�̇u��%Q#�,�R�g�e���(��vj�
r1z)*�������!%��?�$Ih&ae�  [...]
+�+0�P�H&E#YrT����u�nVjS��T�|���K�
��%2)�*�j$��c�3o��0�*cf9���DF �͹ɬf�|�u�:���:��"�)t<
+�������0�8F�O�l�`I���"�w��i�IF�a��	O�񽤸"�lh��Z
�X�#LlH��T��ͤ�	����@^��&㥼������R2��[�a��ר�2Kw�
����{&.�je��,���'*�"%
~�u�Fde+L��Z���L�@���
��9+�]E@��_@���t#��?�,�T_djᇡ*�$$��
�C�E�f|W��?7��˼����:��J,���l��P���oP����U02T���8��a.���t�B/�]���Б$E���%G��(��7�E
�b�h��D�F��P=g��Ԍ�K�\W�3�$آ�"�!*�&��d|?FZ�z���%Ӎ>�2��� a�9���]N���A(�%�a>�n����2B�W��o��x
��>vF
+���U˺�%�
���\���=�L�el	j8�����b�f:���a�uZ
]pD.5
�In���S�ȵu:9@���z[�5�0]�雪V��
e���0�c��6/�
�eR�fz�Q
�'��T��q��|Ϛt_��v1����j���E�����V����
�g��P��<�A�)��Dx2�t�Y�!
T'�9��QWB��-��
N���~L^C(�
�Y�ٚj~S��H1D��R�$ܠW\��$���Oߍ�$�Ї��Ap���X�
�;Q
#�ȃ �
8���i�DtE(6�*��b�w�Rm��O�6/��;	�&B=o�V,\L��ðl�
:
uj##]!*[#�4x
b��d��
�+v�������4d�,D!���k��)o�����DR��W�ą!6U.��ی����5�
+�.4&V
U�ÈN��N�^1#�L.�f���v#�G
�x�V�U���~l�P�
3�D&�(��-�2 at 4�7I,� ~�MT3�g
0���J
+�QQ
����$�0P��elf�
�q0�
't�D2���v�3��E$D�N��Ƒ=��b��^��f�3�~K� !L�4w(%NRBSȦC!}H�f�G�,��Fq�_�Vw~���!��!�d�@�=�x�2�B��$�f��O�<Q �Z�Cp�#i(_��J�oL�hC��Mu�n~��-l�-���H�+Yp�صZb
j�
�YA�~Q���,��|P�>
��s���id���{	!��.�K��N��Ãm%�)�S�.Ά���7VF�
��FZ�M���
d4Ta���jV&�?
[
�C���G�ր�!�����

Q�h�c�DC@�d]B�<
��
��B���>r��bN����hY
+�$�P'�mRT5c3�"
(`�i�
�Kz�~/c��ѓ����Y`�p�g�#1M}Ӆ�O��0���_��(r;�o�r1m!�
+Yr�MdT���$���uB��:f�֨�]��'݉w�ѳ�ش��L5 ���m�&�ɂ���P1U5|���r�!��?6G��n�X��Yoj��+�:3�D�ɰ�S(&�r��ĝ ����S��
�0
:��$T/�WA|�m~�F~g���
��*æ�!F�Qq
m'Y~x�B?DP�
+<�d.�e,cjE5�̑�2k
>HlH�N�
�v�	�)��:�gL�&�����ѹ�U9DfGUʣ�cz�VCrt.�`�Q�"�E
+ �Dd�Vg`�P_�C��2�d�VC҆��~-��NC�C�Q݌Z��9���)I��Ȅsʅ54#=.C9[0Wؤep��)��l��
Ρ$n�P���  �	q�vD*��mz-�f��!�"!:>�[���
t�MM�
��ļ�b�����AU���jj�V��@I���ee
(�>ݑ1�S�����-pFJP�3��/�̠tc
��
+Ts�CIH�F��bPmZ
�����@a��!���C� pт�9����t��Ů�J�@��i����+M���k���H��Y��
o���T_�5
>9r% hP3(�^��+�(�1�
FH�����;.&�*Zrt���X)C��O��AB��ъ:	��.��we�	+<a���<d�?��w�4PL<�
+Q�Y
�?ib�
�Ѥ���^
fx��A�bOt�
��9��j���+>T�oH�g�RJC���ЙC��-�`B*2��0/�9���F�!�����3d��mrn ���"4!�2��8����TM�&��0\�>ԑ^6D�@G�����{Q�K�@&��^��;�%���i
x[E]��
lJ�^��
+5q�Z2?�2��*s g;�{�$1�)2W�������1A��BL�|$i���2�
8��F��\����H�.h�#0�!+�c��ۄ͛%x!�$dJ��RH��#�.�޴h���:J�IO\#_�<��F쿵����b(�b�`���Zꑊ@ws�ҍ5�9�����ɦ�x���b(����Tz����!�XE�O~�a
*焲R͵�)H����,TA}5i�g{��
+��1{Yrt[
+X�J�� �6
?��V�h���
9^3DTX��~��/�+`��lQ �
u2�0�Yn�����'�W���\��t
H*�%��^N7Mw

P5�Ub[Iڼx�l7��R��g
m(����#
2/i*vÛ�#�uK�W
��?1$�����(��GT����Q|��4p����]�P=.�Ql��*_@���r��"ԣK�(
|��z�}����?���=c��{
b}
�p�w�{j)�q�I�E*�3C�����n��t	��v�����X6a��q�ĸ���"w_���x30��,
��;�I��J��6�L+T��,�
P̅��{9�?މ�)~	�n�~�������8a�݃�Q�Z�d$���=�� 
T�3p�4w�]]:�3C�e��*$R�Y�56��(P��
+��qaÖl�	��D
/vQ��k��'6�3e�#��y�؃ Xr<n��N�>�,W��M�V�&IG޹	 Gئ�k�z!�lv�
�_�;�4{i�h��c�^��S���6�2���^���X��vB?~�X�_߉�{
C�;W7�q����w��4�jHK��l_���0��ӧŸq���9��]�1�m�_�����fF|_�Y~����<YϧK~
��w�A�	��u��b�	����B��� ?��u���O_^ԕ� ��Jt�I~g/*�S�rv��*d�S��1e
k�lS����r�P�����n�!����w}��Y��Y��Y��Y�ۉ�|�33�g-�{����X;t�&��ޏ��#��G��<�8B�z��j]���\R�oZ�Eͳ،���n��|9�R�©^�R�	g
ɛ(���S]ؔg��Ȇ�٨�4m(C
��` lz(�kM������
+F��.P��6���v��\�=~��{� i��U_m3�R"���,�	��	��"q�f��'@
�����)e�� �j��3N��n�Q�BU
�6d$�)����~��*15���A�W�]P��&�j~���Ժck�T�������)��,i��i
2�]�����p�V�u�r�����b;`m^]�k�>�I��9V�#H�м�T�� �����>W�{�"NK��yK�
�ֺ��I?����������(�T���PyD�ܢ���_ٞ�|�����nNOc�T;2�Z\�k�1��VQ�
��!:�uo��Ν5u�T�Onxld��3���3;���Ƥ�Q̕����m�f0�l��^m[�
��<��V���l�Lt�s%I~L~�G

عu�Us�B�I�,[��k^
Xo��f�e,8��1�)�f��`��q��(��jn�Ʋ�T%:����D)x�W�� 6�+�+��VK��XLѦ�z_�ْ�sq
��m`�G
4AEH�Q
J��T
cc/K�3�-�
+�J��N�wZ�Z�+�^._m3�R����X�.����Ҙ�8LUM1Nþ+�Qĉ�6ʚ\��xϱ$y[�n�r7ʷ8��:���5���Œ��weM��4v��P
���϶��`
�(��He%4Fzv
�){ކ�Ȝ&
-��2M�K���
�����y)���y�:��ѳ7�F6U�\!m��v�!Ū-�әU�F#��;��(5�z@��tMfК�Y�.������5V׋Տ�v�� ��2�,T6d6�;YV�t��9?;2��!c�2���V��n:'�;
���d6�X�6��d�����W�̼�
��8��h�ێ��8�
+�l�lx
�����1[C bR�Tk�+�Yc�e�@B٘�
�#�GK��P;�vd
�(���.R֚�G�K��Z��$�f����D}%K)�(��N�1�?#Z���N���4^xZ>�6�^��f�l9�yIΎZ7 ���&;�������k���m[�j=Rw�"�8j�~��6�?Ke��/�w��𝳚j[�D���]�"�Z��|O�fL�AX�ѱ
n���tW
0,dڣ���oD�x�с{���d�.��*^l/_m3�R:���X
oJko���n���J7�<��]eu�r
+F۲�o
�T��i�nj��l����m�=R
&l��7+�t���$�m��[=	ז�i�,iȜ��B�
u�EI%^¬m�>�k�!�,u�:���K}���|���K)wN��"��ef,օ|��j3?h�2��6���Re��U
_�_�
��)�.���#&M��dYl�����,0 ���w����!Tt/1�'�#��
*Ҿ���G<�TJ�A��L&��y5��*8j+�W�${����2���^�zp��6+/��9=/�p�e���;�!�r�O�6�<4�d�	�
|5
+�
,��h5� W��u�z�XxCO�J ���]���(�
���F���3�G+�Ĉ
+xY���Y\CI��ɛ
Mѳ�Ý��͊F=I}`(0h��D�.
���O������ӃΩ
���a����
���d���55v��'����C
�����3~�Һ��,Z���z�RYh��������
��1_D3��PZ�=�
y
¬�U��\�$[��
� 
���Y
+D7�0�kzXئ���ۅ��,�
�7�l��R����Ill�͖"	��`�i2�M�n˘��<I���g�!���
�=��U�ʳ?y��b!�d	~�O �n��^s/��?�rs�Bc-.Γ0�L���B��
�wg=���P��s�ajy2�
T�h:DfT�V( q�oY0��O�,��t�3^	�o?����@g��+���Zk&s�4mu�yj��z9e�O��Sa��l�\`eb��4G(v�j�����f��T���D���� ��	•�����<d���آ4�f�A�7��DQ@���p���a�
Ԉ��"lG(U��z��w�Ns� /���{��R�YA0케_�,�sOW��P�wz��ޒՆTR�t��mA6$o�\

�D�%��c;�Q��,ioF9
D
��k�t
��V���K����LG+�F��`X�K6��UI��j]�
X|�y	�P0��$���
��Z�`����c\%ql_��Bޡ��ǑV�=�^͟��54�)Y)���p,����
C��o�OZ�g�9l��G��"B�S���6�n�4�1��lᘧ��l �J��:U at 2���ج�����C�+������-S-��։7H��
C+�r
-b�|D��D��M3
�"v�[�ǖ%������lB`,f��bj�9����R��J�\I��X<-��H�L5���hEg�E���XCU��L
+�������%�����7
_9� �,�Jd4섢� 
 l���l(�[�fU_HS�����!��3.Z+$�$\U�M3�6�
@փV��U��%O���f�	��' �Khxd]
+�5[�{ZL�S�dk�<apm��H�Y�����X�G�T2�T/�g�[9�L���d�V��D���1���줨��h�*s��� ��F����T��
��8��5��3���֛-^�����9U�2I�9o�ľHr,q�"}�
ʺ��:9�lu�dz�b��}�I�hҢ�s����� ��h�����‹:��V/�z}�����lZ�]S��
�Q9���5=Yo'Z��>�{��0����
�h5�$�yn`f;�Yؠ}�f��C�ItA��h�^KR-����V3�l6��<�X�O��4x'�A����5<YQF�ي;)6�iЛ��5�kdx�NM�0�Xu�*�^F��w;m/d
a���-&_���Y��
	G�ݍ���� ���9�x�R�U�L]C��O�b4y
�v������M
+��<������v�>V�z��+�p-N
/�Ȏ��}Q�~��Uf��|�j)�ȜR��_䩒�,����&+�1$��g��iB��g��ɻ��,�>���՘;�NJ%�D�fE
���o1�(�&�p�*������(��]l�K�v�;�>��0�0~�<� k�AX(Px"&+�y�%+�)���� Nhw0�xY#1g��L�m���C
&�Ux�p�e[�2&��V>�H���d>�}�'��L�
)�G�E�J����j�,m�x^�}��Z�<

+�c��V��T`y
+r�[���
S]��uU�b|��E
�j����vL6�sPB�I+�>6-g
/i�F����������h���Q-�8V,�!W+�I�Gy���`�G�g��V
k�k�Z>����������M-�ziRl3(�=g*(~ek��$j��$g�
Tn��4=_b~�5s|�L3�~�8{�j�� IS�Sp�D�"����W����;��!P�8}���ԝ��aO����=	y���?��-*P��܎��=]��_^��`U����a����
K��z�����Ϡ��`k-�B3�kcYM��١m&�ӱ��ϻ�ύ�
q
F��ip���w�Y��i��(��a�\U���R������;{��W����0��
�H��h�|D�L9��*���	��Ze�l��鶖L�M;��WoZ�3��t�_��i��Ѫ�>?vZ�}�scI��=���9Xu����_|����}��w����?�y�������9r
V0h��{������w�|��������Y�ݗ	�_���/����r\�7����u���	����_��
��J��{��3���f'�4��k'\�]��5��������O��7��_�1V�:��Yy?�I��Gۇr��-�����]uA@��C��.�觞���Pm
�E�o<r��,�S���T�^>�5��A�k_��aN�~
_�r\n��KY���~݌"�b.���'�I|
���-x�G��o��L��OɃr��
��:�F�f׌jӱ�G����~����7���ﶹ���g&��Ř��yfI�,�o��S������3P}
+�ظ�^�Ќ�����Ѹ���&��F?�H�@����b�ili
�ޥ==+z�0�虉{���{���{���{���{����f�lu�q,�g/�I�#mw�C<#�j5V[��h§	;��e�eS
+�}]L��eq�غ�G)�oHпt���=�R�a�O��5)���<��a�b�
+q�߫.��MR���9�⫟J��4��̖5#qL�ZT�


Gu�+Noa"lS�n�?}��z� ���"��D�W�O�"��K7�N�d�Ң�������a�T	*
(���Ȭ]��߀&��
{�)� ��ԙ��k�� ��L`$D��#��ko5tv�b����i��1�yV:��������d��ND=��O&�<�H<AR�
OlL"Ā�Q�Stێ�U9�(�rѧ!�!vؘQ��"`
+�2����x�@@DCv$�i0�0��
+tl�8`̓t�42�F�u;iJ݈�P�	�]����
+
C�6Z��%HYd'\�Z6�8�f���h��w%:����d����1���]u�&{N~覘̭�i*2�ԙ �sUe5�lѾ�Ә�DC�#�nٸRG
b�>�ćB\A@�#h���n�ȯ"��2p�?̎|�U���v+��+:�}�u�n���t

Q* ��Az������#�x��c��
CkBT��{��<8Ґ������ԙ
���U����n%�%[ ��sԥp at W�KFEf� l�&�H�Lua)���4�.���ǞiF�F2���<l|� 7[-j�_��y��>=&c��I"��g�hzSIʭ���"	��������8�M<D#���ތ� �HIM�%�h(GB@�6[��n�������ƆĄ*��nEm~���T��P���dD
��\�6,J:8�H�X�c&-�̙zϮ �RbS�PL�p�RYM��X�N$/z�N,S:���)���>��e��a���
hÍ-�T-1��漅�c���:#C�D�oG�~�O�o
��|���a
+�x��l4���1�?��If4���� J� .+z�u�5�D�U�hA�e��)��>��x��ʡ �ٹPVd�A3�ؗe�R���GK7�?�=G� Jz��x��>=�ķ���0?�c�w��b���2ቔ 
e-JT�Bu
�����ԭ�����֚Xu%�r
!<�w�P0:ey�M!��r� nR�t�Q�J�C	�@e�#�Y^R��Y��#�
D3L�s2WW$�&on���=�. ���Co��T�W�E[<
�n��)H�Z��\�I�Y�g
����,fv��׆�ˇ�����~��gO	;�e�x��U��W����8P������'�9=�t$
KmAi�D6��U\e���`,)iHLW���
�E�']
�\+��
e� �룲��G�����]%c�h��&�묊�~ ӈ�
�I�ʙ�;2�5l�v�m]�W7w�NgcdN�R��SyYH��}�|�O�<]��$�������g.n�*��Ϡ)1#ɒN�d�&H.� ���H����2�X
0���
�`���;�5@�����@)>!Č����c�K,w�r6k~#�MS���ρ�7Bb�������Z{2�D��#��ZG¿Do�в�4^
E���AbU���
�a���g����3�W�Y~��mz
–�ܝnժ���&µ]��Zi=�5��;�7l?��d
�@0�K0��Ѐ
�յ~�X6�c�3��!1c
+	�9�h)/�
+
�=(S��P�[��{j����=��
�F��%m�;�}@p��۟�c��h܊@0MtCg�*
��YF�m�wo!�9'���NErs���Ӊ�Y�셕�
�O?ܦ��k�Ow��Ry%�a��y��
+%x�|��c����q�G
�����հ�%�6֙�
��<��X&t��`vå٥y�� 30�}��*�ѥ�:��q	% ^��	��o��Y�r�[�K�
�ĕ^E�*5����+�R3�����
,���Ɵg������o��~:��u�*�x} �~�M�ؼ���s{Ιآ�m�z�<=���Ћ�G�-U[F[
A#Ʒ�"�d+7
�&��Ѕ���ȇ=�E��`I��+��B�^�k������
:�F���q�
+�ͨRb,�!J��5��‡��Dp<��
+��8i��J(M�ϸ��X���&!���,^fؕ�N+;���p
/�W[y������w�
�
��=rPf�8�N:
+�\�BBrq��_�b�X�&i�xIP��P�p�h�e���C, at xRa��X�F#�{V��Nn���b�
�>���#���1��I��{	���p�N�pW��T�
Gs��
�ty��Y��t
:� |��0Q�
+S�����0v�n�
��`�;-e���׆����8�-�0������>���1F�Z�r�\?=�V� \@�+�њ��������Z�e^&$��$��F�2��\�@p����	�Zͥ
+)HD�Yԃ��0~��4�	a�'��b
&��� �b^
�e������.}bɁ�%ii̔�
,��X�"t�`�f�\r �V���d�'9���3yY������{�p�
ïg`���z�l��C.��T�[�f-���^$pG��XO�V�����6�7�dpY^&U+�a��&���t�B�
��K�`�:�v�f�>@,�C�:Vq���@'��4��6��J	aH�@c��
+p�e�E$�wF�����p�
�x�Ӑ�F`{�5̍������V_����mz
�2�������w�aW��3�0���h
��EA�n�f�ř�>�@�ȇ6����HʆI��G݇t�
�RN����]��5eHU��!�ƴ��IT�4��!⚕�ҭe']�l��P�
c�XW�2��D�"��
��ds
���=�^�,f��#�>��n�Y�7��6�e�����ג2�5����6=b6o��m��*�iqy&[���ٴ85�2'(�hDq�c-ˊ2c����ۆ�F9�P��.#	�x�0�]�(P%f�K:�T����H�p�5D�����
�A~�d�ȥBa�#�̊�e�2I�H�*�f2��2�����ۑY�nf&^r�n@:^��8[�Y���p找�*��	ă�����-̊���Ό�j�

3$���5�
q�
ް��>j�ݒ�'R��7�MV���λ��1�+S�����|�@a����/�-
c�HV��J�B7&D�-
+��'�*�[P�
+���ΓU%
+BK��x0z&��9B	�r�U�8���83j�+ �
g���
RGsY�g���C�o�
�*�fUW����2E��^��I8�g �:����x)=Z�*
fu�:_����lp	x���9��d�$�7�0S�h1e���u:����4%�V%�$�ؤ���]PY~��!�~�+C�gH����c�_���1f�j7�M/��Ox�i��=���߮^�D�?ʩn��m&���'�X�akMpd��]�wmv��v�e��]�_g�֎�7K�U9t<�
�0�x�v�
+:;/�d�"�����%�@qd�AV63�e���9`�qd*���ՑT�r��@a-������?`��r�
NןvB�ѸdG*7�>���&���`����Gú=�8m8C���i�u�A����`�꾙9��NR�%�Hf�
L��L&�#�Xk����^D��ݭ(��ܝ���e����K�w#�y
m
�#
i��4�<�/��h
c������:�yס��#�9�����#�3~e+���7b!�خ�	9A�`�s��lV������?*�"��=��&�х�Ԏ
;K��e�^��VgI
+u׃�wZↈ[��f��S��OuJ�
+	�?��LB�U�u�i�u�mC,�L�JC�� ש<�MQ���ײnS�YN��>|�e_�v��P���,d]NJʆ�	
��� �	������-�I���b��G�%B)��҉QJ��/Y��VB���[Ae����tP�j�k�P}[�ɩ^cd�2[
�C�$����_���lG5����D��2��XFyͰ`jg���;�rN�׊�!��ސ�Vc��n�ZB�aA]����J
��cԜ�!�U���ad}y* G5��k�Y<�i]����H
��OWܱcΜ&Sנ�-Pܣ�O:��`VLF;^�V����g0>k*
�`.#�2#�O�����&�Z���a��E�g�\:'	�76�Ũ>7��L҅‚�� ��.�w�ß�P�!����4���Z�j��A-
 �0�ӉtϑTE 2Ƞkv�s��k��f�p��9c
+G,�J�۴R�g�'a� v�bB8޼�Ɩ�<3��S�`
��0�X�V/�k��!�D/
P��,
�:ʪdF��U �';*��1v6�@a
Q�����>C�s\1F9��4O��0�
�b�p0�I���Bu�s������kD]����`f�"��]?�f�
��%�����2*IMy1�
+ _US�z�ӌ
��dk��b/I;u�z:�P*epMū�31=!%
5� ����
��M%s�h����6љ�ư�9fr��;�
+g����(Yy�X�����aFc�	 b�<��)a���[����QՁ��(V��k��]����j\�d^3.�"�,����+�SA��%h������)U���DW��3����m7,�-k>4nvM`�&Y@�$���H�J^����L�k8���qb;�b���5/���=��d{d*��'s����� ��Ԓ��V����)��'����Z����Z���b�v�r���_�;4
�ޱ5��2�/�,����5�~ʗ��7� [�ܰ��(Ň�Q�����4Rj�^�z��&��p�
<ur�85X��	es4ߌ��S�2_E��)�/����
�;��sS鳚�Ci [��4�a�����8V5e�!���S=��� �
�*J�=D���G
[:��R6[𞤎�8�ciW�z}�
1�oݳ��
���S��s�
�U��&�b��~������$�裾�I�����J�>�<��y&�+>/��_�ί�f��
��
����qh"�H�e&x Q��Ԍ�%��i�u�@6�UGX�y8��A��;���@�� �߻S��i
46S�����
%)RP]0��8�G�w�.�*OY
+lcLk���g'%�o5�S��&j��Q��%2
�>`����"���ܾ���(����cQ=<X��2
{w�S��N�ܘ/�{����?==��ݠ�<��'���ƅ��-xT/�A)rD ��
+�S巡Xɺ�iQ|DZ���"��� �48� �l��i�%�d���Tþ��O6�H*#2����j�̘��T��U�Lǜ
�&r��}�
��}fz}�
ѿ��:��/Q��?]����D��+Q�8�Ǚ��Iz?���
s$�}J�������W

��-��\��gi�w�
j�ȋz�X�
Ty��������:�L�z>�!7\�՞
�@����vz
���I�
�+��q��/�"}���[ba��	ԑ"e��+w/�~]K�=�/���B��\S=!��;��[q�:�AƊ�ߟs�
?�����R����_���\�O���~�
+�.�uy/x{w��S�'�
������o���#D^D����3���
�
�
揁�-�
`$�@���!Tc�||��|��lmOC��vs
�No������a������/��
\>�錜g-�lc�!"�gG:�+����T����6�onH��Ȱ*\��V����"��{���>~�����~�a�5G�#҈f�e3r�&+G@���Ȯk��@*`JH%T�aCb���aiC�E�愷
�i ����������7R�O�T�=~�<{�0y��
���W}�MƇ�q����&��
�hCE1��
��IhDtx�)4�����4��.o]����֠���+�g�-T�[	���sq�`�w��Y��	fWD��
���P�l��Xtᇆ)v�����K�u
/����
�Nc�d�@,Sg0r�km�\b�9�O��=d�n�%����Y|
	�0w�6-��5&�k��
U5Q�o�E��.	����k��$)�`��ױ�4Q�ֽW��BR��W��.j��-1�
����W����Dl����5����gv�wPu���d 0W?DB��	�TvE�Eu6P3rđ*��dg���Zg�7`Vn��
�Y
+k$t.�E���?ʐ
�t&4�=�b++�0+O��pƖ��0i�b��י��ḹ�
���\|;<d���%�
�Cjd�"QHaJ@'�SP���M�
X(:""� �j��]�0�\Ma.�m��C=�����TK3�	֊Z�7ͪJ���L2�P�� yͰ �3�Ƚ����Ɍ�.�R�۫���Cm2�%ڰ�c���3S��R`�jR:Hx�3?�F:le0�]��5�
�}�a#��3߁�%3��K�R��]��Þ
��1�3ߔ&�Ҫ�j�f򸽐T��p���}Ҋ���
<
��
Ba����Dݔ���y�]Bug|X�|�MƷDvzl�&!�1
�#�F�"��Z�j-� �n�&L+n�l$�S5�.�O��	�.��4Dii�)�${��Dra�ȑ
+0���aI
�+���2ʺ�n�
�L
3"�~F��	��r�f;�V�y�BliSxҏ-=^p�.�����⼹�
���d|Kd`��d�8;f��Xj&~@K�
��)sS��:�%��2�*�.�;����Tv$�� l��+��xU�sw=n��ۃRX
��������E�R�@pm�|��c��ԋ�%3
�BN*j��,�cCi��W}�����e4|���z�P��o������ְ��D��h�V��rD$�pP�a��pM�U���gX4M�(�4�Y̱�\`�\841/�d��x�޵p5ͭ
H'��O��16=����Z{5C��o�9 (\��	��C딣�t�bA��b8a�A�m7>��mm����M0ꇋ�ˇ�d�����@f���L����Õ�-�Z�  [x��<��;2%jaB�y�L����\���/��F�o��s1y���T[�wٹ���vR0�l��"�D���T���H�X1m<��cݛT�Rɔ�#�%�AK
ޯ(ŕ�������u.op��:�z�P��o������Y�
� �S
�>8���
�e"G�ֈs����<�,L8k��TNt%���0ٚC�}
/Hq��&# K݈����%�ˤ� [...]
+�����[�y��`�	U���
+Y��y���
�
+ {�P��o�����
�`t�k�A��#(o��i� �Hچ+p	a�İܫ���#�+_���
��FT
+�>ˆ!�
��ʖ��W�雀Ut��t�^�&OK�B�V���Њϖ2�*bF��t+�L*�b�����������
+tl(��ʹ<�bq����'j���w���nk�i�0����%.����>����u����������*RAٰ��@U��Y�bw��5�Ip	"�k��WN�p՚0��� X&~�R�S6�q%�ۃ��u
>�є��`V��d����$[��Z���:-K���o��v$��+����^x
�>��̓Ԗ -��؆<� ��
�d^
RcB̿O���>���-���]X�3##�YgǾ�
ˇ֋�Ÿ
E�)����u�a)��b5��<b�/4QƘ�uS�!>�B� ��Ⱥ�*�����VNG�	
�̀�cK!�9k:�]���``��a��Rk�)��nY9��:�N<��fd���Ѫ�Q(kFD.���p���#Xe�
�eD�F&RŴ���J�]�Y�y�㸵y�[߷?��A�����7��:�ְ.
�|�b����>"�$�&�}��\I�d��
+�"Fz�>�&�lz;6��q��Q��Q�%�,�b�K�3y����7`�;�qy�]�r*.����5~>
�/��(��-��E���n��\�) %P�����G��J��-�
%�4� �V����Zc�����}
�;ܹS���v
��+�8P��t3b�kB
d	N	Ⱦ% �X(){`l��p��j����`,+�>S� ���*
+	��bZ�uDS�ߨ|� �5�Oh��Yz�t�T��0�����X�SbP������������/pp���Ϡ^�ѥ�Т2�c
+J�?�w�=��eo4R��}l�)��*����HŃ��ۘ�i�.3��
z�p�q���I�/May:�,��OL���U�iD�x%�r̆{�
��4� .f{���V��-��6�^������V�1?�<`�Q��:
[Uh�e��w��p<̃MӊL���������j^Q�BtY<}��
ƨTh�2�k '��⧨]��+S0t��@���H+��a��4�'�l�`2�UQ+�
"����
�3ֿ&�L
T����za:�)���4�5�Ͷ��#�4
�Q �.C?[�q��J�ܞ9�o�2:)u�{E�^BU��
�UnR��<U��H�yo��qP�`x�{�6V�BU�֦�g�Z�^�
��B��T?N��f���܂[Q��J�:�(h�饪KϚ�0v��^6�:X�`��o��Lj4�H�$�bF�����}eȘDY����6��%[�)�
ڃ�
5��3��?ӻ"�d�Z�̀@�av{��
+������Q�g�55z�
�i�e
�
���
��y%������׎��
+Q6��x$�b��X���
+hԛ么�fI;x_Ed&|�".�eY/�(����%zVh�U�
���3He/��s
�)+�W���6�(��$m����=��!��n�v,cZ�b�R��[BӪb�fWT{Ӥh���z*7DI!'�ܦ-A���Zވ
�܊�N�w��ڣ�����Ղv��.��w:P�]�'�6�ݔ
`*d�EAZ�����dɚ��
b��vb���ư]Ŭ����nOa\
+�
�@���
�n
�	��4��
+^O��a8H�D�Z+�����anO�I,G���8���
+���5���[�/M�4̢.:]��e?<�M� Z��t�F�v*����"�%^+��$��
����f�˲��
u�!�N�ݦ1����,.��c�M��8`�t҄�	Bp�h8�D��g�<1��$ �Wx�]�>k3�<-
��X�JO2?I6��u6{H��??��"�/��V��^�j6Y��ql��k�O׷�J�;�`pP�X�2%;~��Jo�8��
+�21<��i-/V4P��1��
w�d�]5�O�Q�PU�
�.������{;�g�O
����"N: Y�&�
c��ц7���6�Q\�e�%O�ng�dQa�b��O���
+��]t�[x��@=�?׬�~S��n��}d�
?�ນ��5�t���z�'������F5h��v��]���׵`mػ��Ȱ$c��n�4�{&�RX�L�Q�ol���dϞ"��O��P�E~���{��7��rŻ��]���+;s���~d�P�Z�{�����)T')�	>��|������qwb|jdĵB�d�1��
��=T@��Xݰ~\$s�J��|x�^+�P�n֘�@a{!K�Z�_��EǏ����x�ȶ�{��ҰAU  [���˚�i� 7��Y�om��[`�|�TC2M	�DC�d%�c�0z
u.��(���q/��l΄O�*C�_�eid�6I{���zT�E�;ԋM�E�/Y�THsXx��Y�#.�kX-�}���R�����U�!�4��f�6�uޅ[���ݤE)և����jm��Z���O�t0?p���Օ�}��.~�ӻ�~����}���O������ӷ���KJ�i�t���֡���B���������x��zQ������w�_��G�_��wۇ�9������oO�L�lF�����o��M��}����o~�?ů���a��z�Hu��؆QP�^�BQ=���fW�D��G�3(J��a�x�F�7�*�05�
����BR i�\
+}3�p5�8����\
���՜�Y���Q�"v��(K8�C�baB'>��X��b�%| �W
+��
'|I�)6@/����}�T
f(�?��)"��c8�˴.����
׭�����1_�g9|�����F\ݮ�m}uw}���1�^�]�5h�ǻp
菏�,]�D}�(�
�^`��a��Ӣ�ʭ^ �f
~~��Q4���ϼy���y���y���y����{��\[�}�$��6cY�F�f�hNJlsJ��.���<g��D
�
u(���S�
c���p�(<��i��Dž{h��9V���G��J��ʡ
��I@��B�%��
�'�Y�(�&-r�`Єw���J�Ik>"�6>���H������K�L�|:�H�!}ڗ��n]+�?=W�y�.|�l]��ٺ�}������M

.�tXL����3x��M�|��1lɻ�r*�

+�r\J.(ј���]
�h�ſ�7h(�h; Rb���6OGv�I�
+�x<���'T���,ɕ�;-p��
+
���s��d�k����"
h��t�-ᐜ��4C%�<hډ���J���p��с�+�Dz���.5��9R�D�b���U����r�F��j��W�->����1֗
\'�^xVe�7�x��@J�]�|*��������h���\S��{�
�l��
=�ɚ�Y=�iN�HQ�}��xY����bË2d)M���=�(��E�i%�QD������	��К\���i�1�'a��,|k�˯~�*�ʒ\Y�}���ޖn�A�5
+�q��d�H��o"���N`�=���Ѐ*��NĻ9�E߄A	�2��W	�l��THQ�����eϱ\��8Y�
9o��[F
�S�2�~a
���0
9�wF�#��5֙EdWN���T.�E[=�
�l�e
=\	="��0k.}�
7�&�#@�*]J
+|
HrUZjF��p�*���3;<0�?el�]V��a~n�a�5-:I�Ԟ4�͇���32�\�_�f�:ʌ�)�F1��'���
�&�S�
0�JFx�p��0�I��>����t�Mf�^��Y��"��Ac�x�U�<��k��)��R|��o����&HO���e[xM���zj5|�n��y�0�
�@�Q(�(a���
Eu�����8񒷎�);�����<��SZ����5b5uqr�0
y`$�<<����P�8=����):<Q8[84*���o����p%�,�ݛ�4 �
+�媯jz&FB��D!��!R'�J�J�_�����Q4T��xq/7Wd^���r��݆8�pݩ�Q�铍�fo7q��O�G�
ڋ[[Z������؅�́��S�*l.y�{b�n
�����R���l+H]"21�1F�:
 B}�V�
~��W�����Zӫ�M՜rJ�
U̻O�'�Ճٖc=���-�Y�7�
�
E��,b֫�#�~����K��__
_���c�
�`��k���)4��!�$��������8
�@�q*�h�Dz]H|v܄��.L��P7�1,WԄפI�¿���s�+���ΕS����=�
+C�&�
Qj�I�OcЌ�[+<�&D_j��8�Y?c��c6Ѳ�ku��稫-�yk����?�
�l7�;=]x >�PG��(��m8�fw@ңO�
�y�6��BQ��6��W����S�Z��R�,�%�H���ڌ	�	�3�D�4q��WB����!���=
+�[F�3�L5�Ao�+8º��p�q��4�\���s�]�}=4�y
g�2n��h)g��WV�r{�D���'��Fl�'����v4_@�q�D{o��
��*z5�NŎ�,�
+
�߀���AfY1���覓i����8�T��1�P���o�r�2Q۲�-Pcs�i�O�0���*���U��k�]�4�I�����k����U2�"
�a3�9�����j��Ӛ�����&��?�
�l��Z=]����ɼB�D1�d���{n�
N�n1��#�m*<�s��ÈQ$��
�8v�4t{Y����ĢX��$�և��@#NUx�^��ڌ_��f�X�������th{�1����:��	���U`}7dȨMw)eC{W����|�v�JW�r{Ū����Ö�/fj=yc���J3?�`�n6f�$x:%r� orK��}�@�_ɶFK
bz
�jZyVK,�I�%ۀM� K�}LI��7B������]T���$�QJ��\�RQݛ嫪�
1���g�6��i�k�a,�#���
��P��>Z��~�Am�(�w,�F䮧�N�C%����=kẄaB��߽��c`��
�Q
�C�C�&��
�q( ׫��T��Ev>"RB�e�^�5�wF��Kd8o�j�B�
�3�<��-�X��2
�8\Y3�>�贤�� :pN��>�%Ω��ˍq�i��8�m�ѹ��_��roS
��O/�-�m�aO/
�
yX
M���d�#հRW`������2�`C̓H�(s2�
5b�ӥGYl} �D�u)��X�
�(�ME�/��؄Z�w�
�2Te��f��t���H��i�E,C-�B��JC
e'�dY���ƂLt{���N�-,+���16=^���%[�
֟\[�۰ʞ���^*GM�k�~��p�D�}XDF��ܼ��2���y��، 7�Y�TѦ��\袀%�Ք��h�%օ;h��QDJt[s��N�EF_�:n(�P�P��M� BF��U� >���sL�Z���M���}F;���j-�{�G��`lu/w���0�\[�۰Ҟ~�$v�J)�VV�A�Y�+�OFZ����灲@���Q������`sD(H�_a������ƠDȼ�wPVȋ�(*-� 볲.	�/�*
@���D,���d.���8-(�T��rR��uګɆ���Dz�(����~޴��OB�(^���rز݈���ie�ɍG��$
5�'���U‚���S���T;�78jJ�����b�=	�=�8 �|n� <��g笛.���
��L倊\�d&��V�qN �jؔ{T�?�W�/��o�A3�~�`����nGu�d
��"筃J�'8�#
�؃�(���qċJ]�mhiO��qi����	�aȫ�4G0V�" 2��o�V�v($���Pĺ�u�7w[#�E�۠O#�%>3?��l���,�Y7��
+�!=�e
�ӈ�tz��
Z+�s�(�hB�J������UOC����=7	�Ӝ���X�C�3�y~\XD���
+fnCb{�)�Lt,:ʨp��٥GX���
+�R-�9�*�
��d�b���:l�w��r��=�q��<?�w��穀N�K]���܆��P�!���͆Ai��Ԡ��ÎQ< bXx������G���
Q]0+lv^�P�{�|I2��=_צz��MӁ�Bh�!6->��&��ڈ�U�	�
�F�%È�=f+�K}٤C�6�d<�� ��(NV���-11\�+�/K��a�]�GR4
���])�"��h����U9�t@�-��+;�bQ��5~�(�h��L��/.l"�x!���GzH	A#2�����
�t�ܶ�n�
+���Ao1�����n/�䙻�³�<0���9ޚQl���0�����D�d����"�S�?S.O�\�Q�{��F������}�xyo�y˒�!1� �Ԙ�GԻR���IcPК��&
!�l,�<c
����7
Ա���
Q��y
�N�k`��2cX��FW,���i}�ޗ��T8 lU�Q�2]�-EV��(i�*JTj��m�	��-��(�Y��IP��(W����'�f>dg
v�\;�@��b+���t��',��KO�Vh�4�������A\P8G�ڦ�hG7t+9u,�
\�>4?�A!s����熈�>	��
)���#��፡�V�Z�����_
��<7�b7�z��!Ƨ��Q
5�C�o��>g}��ƙQ'w��b_cWY�����a������\�i	�^���F�����(��
R�M�.粉I���-`��cU2
�����G�E��
x�9Pٓ퐜خ��F�O���.8�O�����y��}��D��hqM�2xXV=PD�t>�H�F@�
�+��,3E��O����`/�&kBc����X��I5�<YQ�!
.U�a.ۧ[0l��UobN
%�PlH�h���~������
^��va��@<&o�'�;��1��g��G�k~U6H!?�ǧ!�6����+�Y#����}�O�q���vb^f�@)X�nc�rq�'��E�KaS�B�
(aY<jvI^Ƌ���4
9.b����8_>�jN
}0�d	�a��܊N�ԭlǀ�c�H�+�c��f�9�xe�L!��
+w�=d
K�����xETkv����5ˁ�H_�-��� ���(2
+�]m�W%3Z�$ҎA���4ij��AQ];+A�խ��M�q��������(�j^+���0��ud�
K��pہ
��ؒ'��U�ݪ�L��TD���Ѿc�
_	����F
�z��
Q/�Ѭ�B� 
+���(s��ukt?o֍����PT�@m
`y���y
ӸFt
�\k�������0�LG�:2w�{�]
k����cl td
V
���Oq��)�R�>�)�de3������6L�,��G[
�;{��Ƶ3-2ΫJ{B�Xk�r��9�5�V�)7��F����"�Q� �,q�	��Q��[���yU|�
�6���%
�8zeD�/����ұ���.�ɀ�{�+��
]Ӥ�}l	3K�m�j0|��3Xࡩ�"��ցz�nõ�D,�S
�^vU�V���վ<�9��}�
�C
+�5��j�����6
�Z�{�VV4P!B�+�z�-� !��Y���&��Ąf��\��vK��%a
'[�@W���+����࿯�\8=ˏ�x�	c��'������1/�@@��_]�.������������߀����ש�i��.b��Y�.D�d�V�
H��Ұ1�}�ov��gH±����LۜGx���C\�uL
�)��aZ�R�&Z%
+
A�ϭG�=~RpV��Ie>	;m'��0����	by:���TFX�g�g8G0�ϡ�YO��Wh,!|(μV�
+�Xd��<���,������~�:�ˇ$g�?�/8|��߫ ���A�)�k'�2�{�g��aH�d�El6C_Ps�7��S�����Ô��?�xy[��]V�@⨎�Z$���ɤ�H�[���8���!��㽲&�Q��$�C����D
+�pur���������QXllٺV��7/�+3Ks;~��ʬ�,���\�ߔ_h���ýz�
+�2����5��1��=]��+`8C���u`]���U��K�_b�w���� �XO��G�L5
9B2grM
��hr��\
Q��(�}�Ӕ��W�� �-����N,���TN�>I<@p~�7�ݦ7�ݦ7�ߦ7�ܦ��y���u^S&5%T�
��8�
�i�bE(E)�0�
~�d��Y�Ir�
+�K��@�X�����
+�1��娑�A�-k�kM�u�H��T�
#hQ$�D=C��6�4
D�9�⯘�����*/ j!�F2z	������X|~Vkn��O�U�o��8�<Oq�y��|���uz>��~��|��!��M�R��/�K�4��-;$Z|��&L��M_-�~��=�	�u�8	����8��m=2^�6ߌ$��o��f8�;�4$�j?ʈ
o3)M����4
r��ڔ]֧��'���'}��`<��� �,cD���@��w��fC�HA����U��o�X���)��jZ�p�If͊� )m�		 
ݬ
��YJ���Ղ*
I�Wx��KV�1ɗ��gx�1�N��{��a��G+��t3������cǸ�a/١ q
��������e����
��O,k�!"�
�
�(Z[���v"º.Z�:
�4F�gO/\p>$@�*�<�B#�3V-C������U�]���� W�a#�b|�nE�?D�� �-X��X8I�C��j6�=j�N܎dڐu��h��LJ�%RK5
�rڧ���,�/��v���Иe�P�d쫱��g�]�><�uZ�K33sX�rƀ$�N�s9�i�PN��V�b{R�����
+�:݌�m�n�qYBld4}m�ԃ^�5�
�9�2p�&q�!��Rd�&�P�DO�5r��e$U�?
+�V�B�R�s�)d��n�������'[
���K�Bs�A[�R���i���7�:��d,��eQ&�a��\
���]�Y�G��
+�:݌�m�n
�H�J�A�b-�Jq�
X�(�q�2�0�4��I�W.^�b�4�T�"%O�63�9]u�MN{5

0 N$g�Ԍ2�i\����-�\B�iMfo$sPPi�u]�j�ი�Y1�D}�t�Byg�'
t��[�����^�m.�7.W���f�l�u�[���!��aDj2�`�f�;E���Z�!-?���a����LL!�jUh�̱۬5w({�^\�f3E����ࣙ`�p��ԛ��miq
+�t��@f���9q�<��H=Z�|C�/͋Y�Uڻv?��[�n�r�x}/vב����rl�nC��_��e�Mi��U/��<
+�K\
��7vXJ���ư�[J)�9m��.�
�A�(I4ֽ��W��Ll���.iCHf�
�٬�
���d�'�Qhi��=Όz��g�tw� G�Qj:��tw�
���j@�2AL���L����֪���rl�n���_q�����{�9�eњ�Y����`�R���E$��E��g��Uo�"���R��᳛.#O�.�A͎6
��+00۫�b
+Uf�P����K_�� ��Џf堇�V��� ���^o<�����>�qJ��1���^li
�|ؠ�\[��1����.5W�#k�BqOiC�޵lo�HDƮ�[7F�S�ͬ�HF�Cs�[��]JYA�چg��

��^�˴������f-�����H��BI�;�2PN(
1�Fy&��6�n,F�ޡ1�67���	�������˵���� |�ؾ\[�[��-m���P����{%�f�Q��2���ݢȉU�R�X�N*���M��F��V�
�)��l."8�v
+k��(��lY�ۜz�ϭDs7�p�w$���-�9[�Rt�&쎕�,�vv2.�"��:�#�?^ًme
�
���u���~�c1�!�l
[�Źknf����RH�8t"J]�RF����s�;���H��?��qK;;��Z���K?�@���B$9s��}
�	Hd��)LO
�cl�$:��B�脚M�q���H�dS%��ƕ�W�bggK8�/W@�t+δc���M��Gk�G'C;
d�6%�Bx������'�,�$�M�,�N�2L��ÓnJ�E�
��q�C1�"3Xi�6�1�[=��v�>�%��n��Z�bU����A�3A.~h�!�Pؙe�����&VD�R��@�J��~&���n��vS&��>O�m�r�D����z(
-������>.��TT�|e��=m&Ed��
>�M�Y��t4;��f(���/��v@(
Fvxz):<{�s/��C�M�T���
��
+i��4h������qo ��
m)T�|Ux�G�
AV�"=��c�8��o>˗Z#5��̮
�,π�t�c=�\�.r�x
�[1��?���V	fb��6xg�î�	�d�T[�
^��pʼ>�f儀����c�
��
€���Y'	���W=y
�\I��|+�D˹�hpK��=�Uf��O�%yx �U�5�	�2V��
��L�qŖ�3c��G� [...]
+�l�%�V9L
ؖ$<)�ٞ����i�G���obT��(���U�F�"����s����
1��*KT��X���#���q	�9~,�k�_X/ʭH�����[3�k�xR�A2�GEf��r�A�� 
���#
�����<�/_�
``lܪ[F�����
i�#���jJ�f�7J��k3�h�����
�k���I����j�Y�b����	� 7Q�W�!A�7�/�Z���j����/l/��mʶ��i���/%ɸ�(,2�Z<�/�s}x4G�J�xR-��K�K
�+
2M�{��.䶔K/�W��
�!�
|�{�FQ���'�����,	�t��s��ZOG�rCnD�F���N&y��7(3�VGf�D�5���Y�
+
+��#� �
>'_b$��n^�����M���o�z=�0�F���p��>�	i��Q��
�
�m+̀��
ܙ{��) ���3>��W�h
+�*,�k}�є{������9\�sD���IQ�ϛ����t�f��3�C�`�S|�����[y�Z�<���iG������|�J�J�i����&�j\�����F�D~P��fk��
��,�X�jkVOhl`�a
 ��u��j)λ�c����%�*����	���1�����0^Hج��PMW���=�hܳ
n	Y!�y!oF&4�"`� [�}E����C@
����"�@g�=.�!
3U`|��
/!ʪ�T贘�a �֘�Q��U�5�i� �RI��fx���\�(���Ru����h1
��9��ˑ�v�g�BĆ)
��,�[�ph��5��1���`= 1�t��Ԭ�m�쪀�����65Y7
��L����:
+�Z�P�:���
g��˘��0�U$�!�`5���g���ɹ� �:ϡ�U{�̓,�Ϋv+'Г�zD
��C0k�θVЌ��?���u
�S��OL6�v��P̌�c���g����H):�%��-�x�������7sY����
�>���V1�����Xع�
+��
�bc���^f�ҩ�-񞓷7��ͼ�����{����Bm����K�x��t#c+�fu[�5ͩ�ja��}��y

gV3
=���D�j�N�f�+T��i���8�d/�=,�ع��GVc(��BJ� {�n������K��
��>
�
�Sѷ�Þu�wDD�zk��
-�����'�3��Ӟ�?o�����.�1i�2��=/�J%��-u�xT������k(� ��ػ��h�Ŗ�������=�q�P��Β���L����-~!���k�ۘ����C~��u���#c�R	��ؼt�~`d^y��c���C
�¬��$��|�5�R���r�*��]d�#��[Y,�J����<��
�p/+�pSKc���!Y�
E
(G����.u1\���� <��$k����lUXw3��Eno�4O��kd����YN"��}�dtf�)룜��p�M�z/���s�0�;���������O�>��/��~�姯?��ۯ
�w��O�~��/_}��|s����������?|���������߿���/�����������;_8���
~��2��}W��_m����� ��!V�?.U��o���=�{_�y��߆�O�{��{hD�ms6����i����w��C��W�5����ˮ�1�u���:%
����~ [...]
endstream
endobj
1049 0 obj
<</CreationDate(D:20091123171012+01'00')/Creator(Adobe Illustrator CS3)/ModDate(D:20100413200512+02'00')/Title(Print)>>
endobj
xref
0 1055
0000000003 65535 f
+0000000016 00000 n
+0000045544 00000 n
+0000000004 00000 f
+0000000006 00000 f
+0000055744 00000 n
+0000000007 00000 f
+0000000008 00000 f
+0000000009 00000 f
+0000000010 00000 f
+0000000011 00000 f
+0000000012 00000 f
+0000000013 00000 f
+0000000014 00000 f
+0000000018 00000 f
+0000045595 00000 n
+0000055567 00000 n
+0000055598 00000 n
+0000000019 00000 f
+0000000020 00000 f
+0000000021 00000 f
+0000000022 00000 f
+0000000023 00000 f
+0000000024 00000 f
+0000000025 00000 f
+0000000026 00000 f
+0000000030 00000 f
+0000045664 00000 n
+0000055451 00000 n
+0000055482 00000 n
+0000000031 00000 f
+0000000032 00000 f
+0000000033 00000 f
+0000000034 00000 f
+0000000035 00000 f
+0000000036 00000 f
+0000000040 00000 f
+0000045735 00000 n
+0000055335 00000 n
+0000055366 00000 n
+0000000041 00000 f
+0000000042 00000 f
+0000000043 00000 f
+0000000044 00000 f
+0000000045 00000 f
+0000000046 00000 f
+0000000047 00000 f
+0000000048 00000 f
+0000000049 00000 f
+0000000050 00000 f
+0000000051 00000 f
+0000000052 00000 f
+0000000053 00000 f
+0000000054 00000 f
+0000000055 00000 f
+0000000056 00000 f
+0000000057 00000 f
+0000000058 00000 f
+0000000059 00000 f
+0000000060 00000 f
+0000000061 00000 f
+0000000062 00000 f
+0000000063 00000 f
+0000000064 00000 f
+0000000068 00000 f
+0000045805 00000 n
+0000055219 00000 n
+0000055250 00000 n
+0000000069 00000 f
+0000000070 00000 f
+0000000071 00000 f
+0000000072 00000 f
+0000000073 00000 f
+0000000074 00000 f
+0000000075 00000 f
+0000000076 00000 f
+0000000077 00000 f
+0000000081 00000 f
+0000045874 00000 n
+0000055103 00000 n
+0000055134 00000 n
+0000000082 00000 f
+0000000083 00000 f
+0000000084 00000 f
+0000000085 00000 f
+0000000086 00000 f
+0000000087 00000 f
+0000000088 00000 f
+0000000089 00000 f
+0000000093 00000 f
+0000045945 00000 n
+0000054987 00000 n
+0000055018 00000 n
+0000000094 00000 f
+0000000095 00000 f
+0000000096 00000 f
+0000000097 00000 f
+0000000098 00000 f
+0000000099 00000 f
+0000000100 00000 f
+0000000101 00000 f
+0000000102 00000 f
+0000000103 00000 f
+0000000104 00000 f
+0000000105 00000 f
+0000000106 00000 f
+0000000107 00000 f
+0000000108 00000 f
+0000000109 00000 f
+0000000110 00000 f
+0000000111 00000 f
+0000000112 00000 f
+0000000113 00000 f
+0000000114 00000 f
+0000000115 00000 f
+0000000119 00000 f
+0000046015 00000 n
+0000054869 00000 n
+0000054901 00000 n
+0000000120 00000 f
+0000000121 00000 f
+0000000122 00000 f
+0000000123 00000 f
+0000000124 00000 f
+0000000125 00000 f
+0000000126 00000 f
+0000000127 00000 f
+0000000128 00000 f
+0000000132 00000 f
+0000046087 00000 n
+0000054751 00000 n
+0000054783 00000 n
+0000000133 00000 f
+0000000134 00000 f
+0000000135 00000 f
+0000000136 00000 f
+0000000137 00000 f
+0000000138 00000 f
+0000000139 00000 f
+0000000140 00000 f
+0000000144 00000 f
+0000046161 00000 n
+0000054633 00000 n
+0000054665 00000 n
+0000000145 00000 f
+0000000146 00000 f
+0000000147 00000 f
+0000000148 00000 f
+0000000149 00000 f
+0000000150 00000 f
+0000000151 00000 f
+0000000152 00000 f
+0000000153 00000 f
+0000000154 00000 f
+0000000155 00000 f
+0000000156 00000 f
+0000000157 00000 f
+0000000158 00000 f
+0000000159 00000 f
+0000000160 00000 f
+0000000161 00000 f
+0000000162 00000 f
+0000000163 00000 f
+0000000164 00000 f
+0000000165 00000 f
+0000000166 00000 f
+0000000170 00000 f
+0000046234 00000 n
+0000054515 00000 n
+0000054547 00000 n
+0000000171 00000 f
+0000000172 00000 f
+0000000173 00000 f
+0000000174 00000 f
+0000000175 00000 f
+0000000176 00000 f
+0000000177 00000 f
+0000000178 00000 f
+0000000179 00000 f
+0000000183 00000 f
+0000046306 00000 n
+0000054397 00000 n
+0000054429 00000 n
+0000000184 00000 f
+0000000185 00000 f
+0000000186 00000 f
+0000000187 00000 f
+0000000188 00000 f
+0000000189 00000 f
+0000000190 00000 f
+0000000191 00000 f
+0000000195 00000 f
+0000046380 00000 n
+0000054279 00000 n
+0000054311 00000 n
+0000000196 00000 f
+0000000197 00000 f
+0000000198 00000 f
+0000000199 00000 f
+0000000200 00000 f
+0000000201 00000 f
+0000000202 00000 f
+0000000203 00000 f
+0000000204 00000 f
+0000000205 00000 f
+0000000206 00000 f
+0000000207 00000 f
+0000000208 00000 f
+0000000209 00000 f
+0000000210 00000 f
+0000000211 00000 f
+0000000212 00000 f
+0000000213 00000 f
+0000000214 00000 f
+0000000215 00000 f
+0000000216 00000 f
+0000000217 00000 f
+0000000221 00000 f
+0000046453 00000 n
+0000054161 00000 n
+0000054193 00000 n
+0000000222 00000 f
+0000000223 00000 f
+0000000224 00000 f
+0000000225 00000 f
+0000000226 00000 f
+0000000227 00000 f
+0000000228 00000 f
+0000000229 00000 f
+0000000230 00000 f
+0000000231 00000 f
+0000000232 00000 f
+0000000233 00000 f
+0000000234 00000 f
+0000000235 00000 f
+0000000236 00000 f
+0000000240 00000 f
+0000046525 00000 n
+0000054043 00000 n
+0000054075 00000 n
+0000000241 00000 f
+0000000242 00000 f
+0000000243 00000 f
+0000000244 00000 f
+0000000245 00000 f
+0000000246 00000 f
+0000000247 00000 f
+0000000248 00000 f
+0000000249 00000 f
+0000000250 00000 f
+0000000251 00000 f
+0000000252 00000 f
+0000000253 00000 f
+0000000254 00000 f
+0000000258 00000 f
+0000046599 00000 n
+0000053925 00000 n
+0000053957 00000 n
+0000000259 00000 f
+0000000260 00000 f
+0000000261 00000 f
+0000000262 00000 f
+0000000263 00000 f
+0000000264 00000 f
+0000000265 00000 f
+0000000266 00000 f
+0000000267 00000 f
+0000000268 00000 f
+0000000269 00000 f
+0000000270 00000 f
+0000000271 00000 f
+0000000272 00000 f
+0000000273 00000 f
+0000000274 00000 f
+0000000275 00000 f
+0000000276 00000 f
+0000000277 00000 f
+0000000278 00000 f
+0000000279 00000 f
+0000000280 00000 f
+0000000281 00000 f
+0000000282 00000 f
+0000000283 00000 f
+0000000284 00000 f
+0000000285 00000 f
+0000000286 00000 f
+0000000290 00000 f
+0000046672 00000 n
+0000053807 00000 n
+0000053839 00000 n
+0000000291 00000 f
+0000000292 00000 f
+0000000293 00000 f
+0000000294 00000 f
+0000000295 00000 f
+0000000296 00000 f
+0000000297 00000 f
+0000000298 00000 f
+0000000299 00000 f
+0000000300 00000 f
+0000000301 00000 f
+0000000302 00000 f
+0000000303 00000 f
+0000000304 00000 f
+0000000305 00000 f
+0000000309 00000 f
+0000046744 00000 n
+0000053689 00000 n
+0000053721 00000 n
+0000000310 00000 f
+0000000311 00000 f
+0000000312 00000 f
+0000000313 00000 f
+0000000314 00000 f
+0000000315 00000 f
+0000000316 00000 f
+0000000317 00000 f
+0000000318 00000 f
+0000000319 00000 f
+0000000320 00000 f
+0000000321 00000 f
+0000000322 00000 f
+0000000323 00000 f
+0000000327 00000 f
+0000046818 00000 n
+0000053571 00000 n
+0000053603 00000 n
+0000000328 00000 f
+0000000329 00000 f
+0000000330 00000 f
+0000000331 00000 f
+0000000332 00000 f
+0000000333 00000 f
+0000000334 00000 f
+0000000335 00000 f
+0000000336 00000 f
+0000000337 00000 f
+0000000338 00000 f
+0000000339 00000 f
+0000000340 00000 f
+0000000341 00000 f
+0000000342 00000 f
+0000000343 00000 f
+0000000344 00000 f
+0000000345 00000 f
+0000000346 00000 f
+0000000347 00000 f
+0000000348 00000 f
+0000000349 00000 f
+0000000350 00000 f
+0000000351 00000 f
+0000000352 00000 f
+0000000353 00000 f
+0000000354 00000 f
+0000000355 00000 f
+0000000359 00000 f
+0000046891 00000 n
+0000053453 00000 n
+0000053485 00000 n
+0000000360 00000 f
+0000000361 00000 f
+0000000362 00000 f
+0000000363 00000 f
+0000000364 00000 f
+0000000365 00000 f
+0000000366 00000 f
+0000000367 00000 f
+0000000368 00000 f
+0000000369 00000 f
+0000000370 00000 f
+0000000371 00000 f
+0000000372 00000 f
+0000000373 00000 f
+0000000374 00000 f
+0000000378 00000 f
+0000046963 00000 n
+0000053335 00000 n
+0000053367 00000 n
+0000000379 00000 f
+0000000380 00000 f
+0000000381 00000 f
+0000000382 00000 f
+0000000383 00000 f
+0000000384 00000 f
+0000000385 00000 f
+0000000386 00000 f
+0000000387 00000 f
+0000000388 00000 f
+0000000389 00000 f
+0000000390 00000 f
+0000000391 00000 f
+0000000392 00000 f
+0000000396 00000 f
+0000047037 00000 n
+0000053217 00000 n
+0000053249 00000 n
+0000000397 00000 f
+0000000398 00000 f
+0000000399 00000 f
+0000000400 00000 f
+0000000401 00000 f
+0000000402 00000 f
+0000000403 00000 f
+0000000404 00000 f
+0000000405 00000 f
+0000000406 00000 f
+0000000407 00000 f
+0000000408 00000 f
+0000000409 00000 f
+0000000410 00000 f
+0000000411 00000 f
+0000000412 00000 f
+0000000413 00000 f
+0000000414 00000 f
+0000000415 00000 f
+0000000416 00000 f
+0000000417 00000 f
+0000000418 00000 f
+0000000419 00000 f
+0000000420 00000 f
+0000000421 00000 f
+0000000422 00000 f
+0000000423 00000 f
+0000000424 00000 f
+0000000428 00000 f
+0000047110 00000 n
+0000053099 00000 n
+0000053131 00000 n
+0000000429 00000 f
+0000000430 00000 f
+0000000431 00000 f
+0000000432 00000 f
+0000000433 00000 f
+0000000434 00000 f
+0000000435 00000 f
+0000000436 00000 f
+0000000437 00000 f
+0000000438 00000 f
+0000000439 00000 f
+0000000440 00000 f
+0000000441 00000 f
+0000000442 00000 f
+0000000443 00000 f
+0000000447 00000 f
+0000047182 00000 n
+0000052981 00000 n
+0000053013 00000 n
+0000000448 00000 f
+0000000449 00000 f
+0000000450 00000 f
+0000000451 00000 f
+0000000452 00000 f
+0000000453 00000 f
+0000000454 00000 f
+0000000455 00000 f
+0000000456 00000 f
+0000000457 00000 f
+0000000458 00000 f
+0000000459 00000 f
+0000000460 00000 f
+0000000461 00000 f
+0000000465 00000 f
+0000047254 00000 n
+0000052863 00000 n
+0000052895 00000 n
+0000000466 00000 f
+0000000467 00000 f
+0000000468 00000 f
+0000000469 00000 f
+0000000470 00000 f
+0000000471 00000 f
+0000000472 00000 f
+0000000473 00000 f
+0000000474 00000 f
+0000000475 00000 f
+0000000476 00000 f
+0000000477 00000 f
+0000000478 00000 f
+0000000479 00000 f
+0000000483 00000 f
+0000047328 00000 n
+0000052745 00000 n
+0000052777 00000 n
+0000000484 00000 f
+0000000485 00000 f
+0000000486 00000 f
+0000000487 00000 f
+0000000488 00000 f
+0000000489 00000 f
+0000000490 00000 f
+0000000491 00000 f
+0000000492 00000 f
+0000000493 00000 f
+0000000494 00000 f
+0000000495 00000 f
+0000000496 00000 f
+0000000497 00000 f
+0000000498 00000 f
+0000000499 00000 f
+0000000500 00000 f
+0000000501 00000 f
+0000000502 00000 f
+0000000503 00000 f
+0000000504 00000 f
+0000000505 00000 f
+0000000506 00000 f
+0000000507 00000 f
+0000000508 00000 f
+0000000509 00000 f
+0000000510 00000 f
+0000000511 00000 f
+0000000512 00000 f
+0000000513 00000 f
+0000000514 00000 f
+0000000518 00000 f
+0000047401 00000 n
+0000052627 00000 n
+0000052659 00000 n
+0000000519 00000 f
+0000000520 00000 f
+0000000521 00000 f
+0000000522 00000 f
+0000000523 00000 f
+0000000524 00000 f
+0000000525 00000 f
+0000000526 00000 f
+0000000527 00000 f
+0000000528 00000 f
+0000000529 00000 f
+0000000530 00000 f
+0000000531 00000 f
+0000000532 00000 f
+0000000533 00000 f
+0000000537 00000 f
+0000047473 00000 n
+0000052509 00000 n
+0000052541 00000 n
+0000000538 00000 f
+0000000539 00000 f
+0000000540 00000 f
+0000000541 00000 f
+0000000542 00000 f
+0000000543 00000 f
+0000000544 00000 f
+0000000545 00000 f
+0000000546 00000 f
+0000000547 00000 f
+0000000548 00000 f
+0000000549 00000 f
+0000000550 00000 f
+0000000551 00000 f
+0000000555 00000 f
+0000047545 00000 n
+0000052391 00000 n
+0000052423 00000 n
+0000000556 00000 f
+0000000557 00000 f
+0000000558 00000 f
+0000000559 00000 f
+0000000560 00000 f
+0000000561 00000 f
+0000000562 00000 f
+0000000563 00000 f
+0000000564 00000 f
+0000000565 00000 f
+0000000566 00000 f
+0000000567 00000 f
+0000000568 00000 f
+0000000569 00000 f
+0000000573 00000 f
+0000047619 00000 n
+0000052273 00000 n
+0000052305 00000 n
+0000000574 00000 f
+0000000575 00000 f
+0000000576 00000 f
+0000000577 00000 f
+0000000578 00000 f
+0000000579 00000 f
+0000000580 00000 f
+0000000581 00000 f
+0000000582 00000 f
+0000000583 00000 f
+0000000584 00000 f
+0000000585 00000 f
+0000000586 00000 f
+0000000587 00000 f
+0000000588 00000 f
+0000000589 00000 f
+0000000590 00000 f
+0000000591 00000 f
+0000000592 00000 f
+0000000593 00000 f
+0000000594 00000 f
+0000000595 00000 f
+0000000596 00000 f
+0000000597 00000 f
+0000000598 00000 f
+0000000599 00000 f
+0000000600 00000 f
+0000000601 00000 f
+0000000602 00000 f
+0000000603 00000 f
+0000000604 00000 f
+0000000608 00000 f
+0000047692 00000 n
+0000052155 00000 n
+0000052187 00000 n
+0000000609 00000 f
+0000000610 00000 f
+0000000611 00000 f
+0000000612 00000 f
+0000000613 00000 f
+0000000614 00000 f
+0000000615 00000 f
+0000000616 00000 f
+0000000617 00000 f
+0000000618 00000 f
+0000000619 00000 f
+0000000620 00000 f
+0000000621 00000 f
+0000000622 00000 f
+0000000623 00000 f
+0000000627 00000 f
+0000047764 00000 n
+0000052037 00000 n
+0000052069 00000 n
+0000000628 00000 f
+0000000629 00000 f
+0000000630 00000 f
+0000000631 00000 f
+0000000632 00000 f
+0000000633 00000 f
+0000000634 00000 f
+0000000635 00000 f
+0000000636 00000 f
+0000000637 00000 f
+0000000638 00000 f
+0000000639 00000 f
+0000000640 00000 f
+0000000641 00000 f
+0000000645 00000 f
+0000047836 00000 n
+0000051919 00000 n
+0000051951 00000 n
+0000000646 00000 f
+0000000647 00000 f
+0000000648 00000 f
+0000000649 00000 f
+0000000650 00000 f
+0000000651 00000 f
+0000000652 00000 f
+0000000653 00000 f
+0000000654 00000 f
+0000000655 00000 f
+0000000656 00000 f
+0000000657 00000 f
+0000000658 00000 f
+0000000659 00000 f
+0000000663 00000 f
+0000047910 00000 n
+0000051801 00000 n
+0000051833 00000 n
+0000000664 00000 f
+0000000665 00000 f
+0000000666 00000 f
+0000000667 00000 f
+0000000668 00000 f
+0000000669 00000 f
+0000000670 00000 f
+0000000671 00000 f
+0000000672 00000 f
+0000000673 00000 f
+0000000674 00000 f
+0000000675 00000 f
+0000000676 00000 f
+0000000677 00000 f
+0000000678 00000 f
+0000000679 00000 f
+0000000680 00000 f
+0000000681 00000 f
+0000000682 00000 f
+0000000683 00000 f
+0000000684 00000 f
+0000000685 00000 f
+0000000686 00000 f
+0000000687 00000 f
+0000000688 00000 f
+0000000689 00000 f
+0000000690 00000 f
+0000000691 00000 f
+0000000692 00000 f
+0000000693 00000 f
+0000000694 00000 f
+0000000698 00000 f
+0000047983 00000 n
+0000051683 00000 n
+0000051715 00000 n
+0000000702 00000 f
+0000048054 00000 n
+0000051565 00000 n
+0000051597 00000 n
+0000000703 00000 f
+0000000704 00000 f
+0000000705 00000 f
+0000000706 00000 f
+0000000707 00000 f
+0000000708 00000 f
+0000000709 00000 f
+0000000710 00000 f
+0000000711 00000 f
+0000000712 00000 f
+0000000713 00000 f
+0000000714 00000 f
+0000000715 00000 f
+0000000716 00000 f
+0000000717 00000 f
+0000000721 00000 f
+0000048126 00000 n
+0000051447 00000 n
+0000051479 00000 n
+0000000722 00000 f
+0000000723 00000 f
+0000000724 00000 f
+0000000725 00000 f
+0000000726 00000 f
+0000000727 00000 f
+0000000728 00000 f
+0000000729 00000 f
+0000000730 00000 f
+0000000731 00000 f
+0000000732 00000 f
+0000000733 00000 f
+0000000734 00000 f
+0000000738 00000 f
+0000048198 00000 n
+0000051329 00000 n
+0000051361 00000 n
+0000000739 00000 f
+0000000740 00000 f
+0000000741 00000 f
+0000000742 00000 f
+0000000743 00000 f
+0000000744 00000 f
+0000000745 00000 f
+0000000746 00000 f
+0000000747 00000 f
+0000000748 00000 f
+0000000749 00000 f
+0000000750 00000 f
+0000000751 00000 f
+0000000752 00000 f
+0000000756 00000 f
+0000048272 00000 n
+0000051211 00000 n
+0000051243 00000 n
+0000000757 00000 f
+0000000758 00000 f
+0000000759 00000 f
+0000000760 00000 f
+0000000761 00000 f
+0000000762 00000 f
+0000000763 00000 f
+0000000764 00000 f
+0000000765 00000 f
+0000000766 00000 f
+0000000767 00000 f
+0000000768 00000 f
+0000000769 00000 f
+0000000770 00000 f
+0000000771 00000 f
+0000000772 00000 f
+0000000773 00000 f
+0000000774 00000 f
+0000000775 00000 f
+0000000776 00000 f
+0000000777 00000 f
+0000000778 00000 f
+0000000779 00000 f
+0000000780 00000 f
+0000000781 00000 f
+0000000782 00000 f
+0000000783 00000 f
+0000000784 00000 f
+0000000788 00000 f
+0000048345 00000 n
+0000051093 00000 n
+0000051125 00000 n
+0000000792 00000 f
+0000048416 00000 n
+0000050975 00000 n
+0000051007 00000 n
+0000000793 00000 f
+0000000794 00000 f
+0000000795 00000 f
+0000000796 00000 f
+0000000797 00000 f
+0000000798 00000 f
+0000000799 00000 f
+0000000800 00000 f
+0000000801 00000 f
+0000000802 00000 f
+0000000803 00000 f
+0000000804 00000 f
+0000000805 00000 f
+0000000806 00000 f
+0000000807 00000 f
+0000000811 00000 f
+0000048488 00000 n
+0000050857 00000 n
+0000050889 00000 n
+0000000812 00000 f
+0000000813 00000 f
+0000000814 00000 f
+0000000815 00000 f
+0000000816 00000 f
+0000000817 00000 f
+0000000818 00000 f
+0000000819 00000 f
+0000000820 00000 f
+0000000821 00000 f
+0000000822 00000 f
+0000000823 00000 f
+0000000824 00000 f
+0000000828 00000 f
+0000048560 00000 n
+0000050739 00000 n
+0000050771 00000 n
+0000000829 00000 f
+0000000830 00000 f
+0000000831 00000 f
+0000000832 00000 f
+0000000833 00000 f
+0000000834 00000 f
+0000000835 00000 f
+0000000836 00000 f
+0000000837 00000 f
+0000000838 00000 f
+0000000839 00000 f
+0000000840 00000 f
+0000000841 00000 f
+0000000842 00000 f
+0000000846 00000 f
+0000048634 00000 n
+0000050621 00000 n
+0000050653 00000 n
+0000000847 00000 f
+0000000848 00000 f
+0000000849 00000 f
+0000000850 00000 f
+0000000851 00000 f
+0000000852 00000 f
+0000000853 00000 f
+0000000854 00000 f
+0000000855 00000 f
+0000000856 00000 f
+0000000857 00000 f
+0000000858 00000 f
+0000000859 00000 f
+0000000860 00000 f
+0000000861 00000 f
+0000000862 00000 f
+0000000863 00000 f
+0000000864 00000 f
+0000000865 00000 f
+0000000866 00000 f
+0000000867 00000 f
+0000000868 00000 f
+0000000869 00000 f
+0000000870 00000 f
+0000000871 00000 f
+0000000872 00000 f
+0000000873 00000 f
+0000000874 00000 f
+0000000875 00000 f
+0000000876 00000 f
+0000000877 00000 f
+0000000881 00001 f
+0000048707 00000 n
+0000050503 00000 n
+0000050535 00000 n
+0000000885 00000 f
+0000048778 00000 n
+0000050385 00000 n
+0000050417 00000 n
+0000000886 00000 f
+0000000887 00000 f
+0000000888 00000 f
+0000000889 00000 f
+0000000890 00000 f
+0000000891 00000 f
+0000000892 00000 f
+0000000893 00000 f
+0000000894 00000 f
+0000000895 00000 f
+0000000896 00000 f
+0000000897 00000 f
+0000000898 00000 f
+0000000899 00000 f
+0000000900 00000 f
+0000000904 00000 f
+0000048850 00000 n
+0000050267 00000 n
+0000050299 00000 n
+0000000905 00000 f
+0000000906 00000 f
+0000000907 00000 f
+0000000908 00000 f
+0000000909 00000 f
+0000000910 00000 f
+0000000911 00000 f
+0000000912 00000 f
+0000000913 00000 f
+0000000914 00000 f
+0000000915 00000 f
+0000000916 00000 f
+0000000917 00000 f
+0000000921 00000 f
+0000048922 00000 n
+0000050149 00000 n
+0000050181 00000 n
+0000000922 00000 f
+0000000923 00000 f
+0000000924 00000 f
+0000000925 00000 f
+0000000926 00000 f
+0000000927 00000 f
+0000000928 00000 f
+0000000929 00000 f
+0000000930 00000 f
+0000000931 00000 f
+0000000932 00000 f
+0000000933 00000 f
+0000000934 00000 f
+0000000935 00000 f
+0000000939 00000 f
+0000048996 00000 n
+0000050031 00000 n
+0000050063 00000 n
+0000000940 00000 f
+0000000941 00000 f
+0000000942 00000 f
+0000000943 00000 f
+0000000944 00000 f
+0000000945 00000 f
+0000000946 00000 f
+0000000947 00000 f
+0000000948 00000 f
+0000000949 00000 f
+0000000950 00000 f
+0000000951 00000 f
+0000000952 00000 f
+0000000953 00000 f
+0000000954 00000 f
+0000000955 00000 f
+0000000956 00000 f
+0000000957 00001 f
+0000000958 00000 f
+0000000959 00000 f
+0000000960 00000 f
+0000000961 00000 f
+0000000969 00000 f
+0000174447 00000 n
+0000174523 00000 n
+0000174747 00000 n
+0000175772 00000 n
+0000183336 00000 n
+0000248925 00000 n
+0000314514 00000 n
+0000000974 00001 f
+0000055683 00000 n
+0000049069 00000 n
+0000049913 00000 n
+0000049945 00000 n
+0000000987 00001 f
+0000049140 00000 n
+0000049795 00000 n
+0000049827 00000 n
+0000058541 00000 n
+0000159418 00000 n
+0000160143 00000 n
+0000173817 00000 n
+0000060510 00000 n
+0000060547 00000 n
+0000160206 00000 n
+0000159481 00000 n
+0000063196 00000 n
+0000000997 00001 f
+0000147299 00000 n
+0000148055 00000 n
+0000159355 00000 n
+0000148118 00000 n
+0000147362 00000 n
+0000063689 00000 n
+0000049212 00000 n
+0000049677 00000 n
+0000049709 00000 n
+0000001004 00001 f
+0000132732 00000 n
+0000133484 00000 n
+0000147235 00000 n
+0000133547 00000 n
+0000132795 00000 n
+0000064172 00000 n
+0000001014 00001 f
+0000120560 00000 n
+0000121317 00000 n
+0000132668 00000 n
+0000121381 00000 n
+0000120624 00000 n
+0000064671 00000 n
+0000049284 00000 n
+0000049557 00000 n
+0000049590 00000 n
+0000001021 00001 f
+0000106070 00000 n
+0000106822 00000 n
+0000120496 00000 n
+0000106886 00000 n
+0000106134 00000 n
+0000065160 00000 n
+0000001022 00001 f
+0000001032 00001 f
+0000093888 00000 n
+0000094644 00000 n
+0000106006 00000 n
+0000094708 00000 n
+0000093952 00000 n
+0000065664 00000 n
+0000049361 00000 n
+0000049437 00000 n
+0000049470 00000 n
+0000001039 00001 f
+0000079247 00000 n
+0000080008 00000 n
+0000093824 00000 n
+0000080072 00000 n
+0000079311 00000 n
+0000066147 00000 n
+0000000000 00001 f
+0000067133 00000 n
+0000067894 00000 n
+0000079183 00000 n
+0000067958 00000 n
+0000067197 00000 n
+0000066651 00000 n
+0000058655 00000 n
+0000058947 00000 n
+0000056363 00000 n
+0000362622 00000 n
+0000059211 00000 n
+0000173880 00000 n
+0000173932 00000 n
+0000058383 00000 n
+0000000982 00000 n
+trailer
<</Size 1055/Root 1 0 R/Info 1049 0 R/ID[<DFAD564605F549E3ABF1FC747EBA5A34><45AB28F93CAE4209BAB0B0278EBC9323>]>>
startxref
362760
%%EOF
\ No newline at end of file
diff --git a/src/compiler/scala/tools/nsc/doc/html/resource/lib/versions.txt b/src/compiler/scala/tools/nsc/doc/html/resource/lib/versions.txt
new file mode 100644
index 0000000..17d1cae
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/doc/html/resource/lib/versions.txt
@@ -0,0 +1 @@
+jquery=1.4.2
diff --git a/src/compiler/scala/tools/nsc/doc/model/Entity.scala b/src/compiler/scala/tools/nsc/doc/model/Entity.scala
new file mode 100644
index 0000000..b0aac82
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/doc/model/Entity.scala
@@ -0,0 +1,190 @@
+/* NSC -- new Scala compiler
+ * Copyright 2007-2010 LAMP/EPFL
+ * @author  Manohar Jonnalagedda
+ */
+
+package scala.tools.nsc
+package doc
+package model
+
+import scala.collection._
+import comment._
+
+/** Some entity of the Scaladoc model. */
+trait Entity {
+  def name : String
+  def inTemplate: TemplateEntity
+  def toRoot: List[Entity]
+  def qualifiedName: String
+  override def toString = qualifiedName
+  def universe: Universe
+}
+
+/** A class, trait, object or package. A package is represented as an instance
+  * of the `Package` subclass. A class, trait, object or package may be
+  * directly an instance of `WeakTemplateEntity` if it is not ''documentable''
+  * (that is, if there is no documentation page for it in the current site),
+  * otherwise, it will be represented as an instance of the `TemplateEntity`
+  * subclass. */
+trait TemplateEntity extends Entity {
+  def isPackage: Boolean
+  def isRootPackage: Boolean
+  def isTrait: Boolean
+  def isClass: Boolean
+  def isObject: Boolean
+  def isDocTemplate: Boolean
+  def isCaseClass: Boolean
+  def selfType : Option[TypeEntity]
+}
+trait NoDocTemplate extends TemplateEntity
+
+/** A member of a class, trait, object or package. */
+trait MemberEntity extends Entity {
+  def comment: Option[Comment]
+  def inTemplate: DocTemplateEntity
+  def toRoot: List[MemberEntity]
+  def inDefinitionTemplates: List[TemplateEntity]
+  def definitionName: String
+  def visibility: Visibility
+  def flags: List[Paragraph]
+  def deprecation: Option[Body]
+  def inheritedFrom: List[TemplateEntity]
+  def resultType: TypeEntity
+  def isDef: Boolean
+  def isVal: Boolean
+  def isLazyVal: Boolean
+  def isVar: Boolean
+  def isImplicit: Boolean
+  def isAbstract: Boolean
+  def isConstructor: Boolean
+  def isAliasType: Boolean
+  def isAbstractType: Boolean
+  def isTemplate: Boolean
+}
+
+trait HigherKinded extends Entity {
+  def typeParams: List[TypeParam]
+}
+
+/** A ''documentable'' class, trait or object (that is, a documentation page
+  * will be generated for it in the current site). */
+trait DocTemplateEntity extends TemplateEntity with MemberEntity {
+  def toRoot: List[DocTemplateEntity]
+  def inSource: Option[(io.AbstractFile, Int)]
+  def sourceUrl: Option[java.net.URL]
+  def parentType: Option[TypeEntity]
+  def linearization: List[(TemplateEntity, TypeEntity)]
+  def linearizationTemplates: List[TemplateEntity]
+  def linearizationTypes: List[TypeEntity]
+  def subClasses: List[DocTemplateEntity]
+  def members: List[MemberEntity]
+  def templates: List[DocTemplateEntity]
+  def methods: List[Def]
+  def values: List[Val]
+  def abstractTypes: List[AbstractType]
+  def aliasTypes: List[AliasType]
+  def companion: Option[DocTemplateEntity]
+}
+
+/** A ''documentable'' trait. */
+trait Trait extends DocTemplateEntity with HigherKinded
+
+/** A ''documentable'' class. */
+trait Class extends Trait with HigherKinded {
+  def primaryConstructor: Option[Constructor]
+  def constructors: List[Constructor]
+  def valueParams: List[List[ValueParam]]
+}
+
+/** A ''documentable'' object. */
+trait Object extends DocTemplateEntity
+
+/** A package that contains at least one ''documentable'' class, trait,
+  * object or package. */
+trait Package extends Object {
+  def inTemplate: Package
+  def toRoot: List[Package]
+  def packages: List[Package]
+}
+
+/** A package represent the root of Entities hierarchy */
+trait RootPackage extends Package 
+
+trait NonTemplateMemberEntity extends MemberEntity {
+  def isUseCase: Boolean
+}
+
+/** A method (`def`) of a ''documentable'' class, trait or object. */
+trait Def extends NonTemplateMemberEntity with HigherKinded {
+  def valueParams : List[List[ValueParam]]
+}
+
+trait Constructor extends NonTemplateMemberEntity {
+  def isPrimary: Boolean
+  def valueParams : List[List[ValueParam]]
+}
+
+/** A value (`val`), lazy val (`lazy val`) or variable (`var`) of a
+  * ''documentable'' class, trait or object. */
+trait Val extends NonTemplateMemberEntity
+
+/** An abstract type of a ''documentable'' class, trait or object. */
+trait AbstractType extends NonTemplateMemberEntity with HigherKinded {
+  def lo: Option[TypeEntity]
+  def hi: Option[TypeEntity]
+}
+
+/** An abstract type of a ''documentable'' class, trait or object. */
+trait AliasType extends NonTemplateMemberEntity with HigherKinded {
+  def alias: TypeEntity
+}
+
+trait ParameterEntity extends Entity {
+  def isTypeParam: Boolean
+  def isValueParam: Boolean
+}
+
+/** A type parameter to a class or trait or to a method. */
+trait TypeParam extends ParameterEntity with HigherKinded {
+  def variance: String
+  def lo: Option[TypeEntity]
+  def hi: Option[TypeEntity]
+}
+
+/** A value parameter to a constructor or to a method. */
+trait ValueParam extends ParameterEntity {
+  def resultType: TypeEntity
+  def defaultValue: Option[TreeEntity]
+  def isImplicit: Boolean
+}
+
+/** An type that represents visibility of members. */
+sealed trait Visibility {
+  def isProtected: Boolean = false
+  def isPublic: Boolean = false
+}
+
+/** The visibility of `private[this]` members. */
+case class PrivateInInstance() extends Visibility
+
+/** The visibility of `protected[this]` members. */
+case class ProtectedInInstance() extends Visibility {
+  override def isProtected = true
+}
+
+/** The visibility of `private[owner]` members. An unqualified private members
+  * is encoded with `owner` equal to the members's `inTemplate`. */
+case class PrivateInTemplate(owner: TemplateEntity) extends Visibility
+
+/** The visibility of `protected[owner]` members. An unqualified protected
+  * members is encoded with `owner` equal to the members's `inTemplate`.
+  * Note that whilst the member is visible in any template owned by `owner`,
+  * it is only visible in subclasses of the member's `inTemplate`. */
+case class ProtectedInTemplate(owner: TemplateEntity) extends Visibility {
+  override def isProtected = true
+}
+
+/** The visibility of public members. */
+case class Public() extends Visibility {
+  override def isPublic = true
+}
diff --git a/src/compiler/scala/tools/nsc/doc/model/ModelFactory.scala b/src/compiler/scala/tools/nsc/doc/model/ModelFactory.scala
new file mode 100644
index 0000000..b0b27c4
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/doc/model/ModelFactory.scala
@@ -0,0 +1,572 @@
+/* NSC -- new Scala compiler -- Copyright 2007-2010 LAMP/EPFL */
+
+package scala.tools.nsc
+package doc
+package model
+
+import comment._
+
+import scala.collection._
+import scala.util.matching.Regex
+
+import symtab.Flags
+
+import model.{ RootPackage => RootPackageEntity }
+
+/** This trait extracts all required information for documentation from compilation units */
+class ModelFactory(val global: Global, val settings: doc.Settings) { thisFactory: ModelFactory with CommentFactory with TreeFactory =>
+
+  import global._
+  import definitions.{ ObjectClass, ScalaObjectClass, RootPackage, EmptyPackage, NothingClass, AnyClass, AnyRefClass }
+
+  private var droppedPackages = 0
+  def templatesCount = templatesCache.size - droppedPackages
+
+  private var modelFinished = false
+  private var universe: Universe = null
+  
+  /**  */
+  def makeModel: Universe = {
+    val universe = new Universe { thisUniverse =>
+      thisFactory.universe = thisUniverse
+      val settings = thisFactory.settings
+      val rootPackage =
+        makeRootPackage getOrElse { throw new Error("no documentable class found in compilation units") }
+    }
+    modelFinished = true
+    thisFactory.universe = null
+    universe
+  }
+
+  /** */
+  protected val templatesCache =
+    new mutable.LinkedHashMap[Symbol, DocTemplateImpl]
+
+  def findTemplate(query: String): Option[DocTemplateImpl] = {
+    if (!modelFinished) throw new Error("cannot find template in unfinished universe")
+    templatesCache.values find { tpl => tpl.qualifiedName == query && !tpl.isObject }
+  }
+
+  def optimize(str: String): String =
+    if (str.length < 16) str.intern else str
+
+  /* ============== IMPLEMENTATION PROVIDING ENTITY TYPES ============== */
+
+  /** Provides a default implementation for instances of the `Entity` type. */
+  abstract class EntityImpl(val sym: Symbol, inTpl: => TemplateImpl) extends Entity {
+    val name = optimize(sym.nameString)
+    def inTemplate: TemplateImpl = inTpl
+    def toRoot: List[EntityImpl] = this :: inTpl.toRoot
+    def qualifiedName = name
+    val universe = thisFactory.universe
+  }
+
+  /** Provides a default implementation for instances of the `WeakTemplateEntity` type. It must be instantiated as a
+    * `SymbolicEntity` to access the compiler symbol that underlies the entity. */
+  trait TemplateImpl extends EntityImpl with TemplateEntity {
+    override def qualifiedName: String =
+      if (inTemplate.isRootPackage) name else optimize(inTemplate.qualifiedName + "." + name)
+    def isPackage = sym.isPackage
+    def isTrait = sym.isTrait
+    def isClass = sym.isClass && !sym.isTrait
+    def isObject = sym.isModule && !sym.isPackage
+    def isCaseClass = sym.isClass && sym.hasFlag(Flags.CASE)
+    def isRootPackage = false
+    def selfType = if (sym.thisSym eq sym) None else Some(makeType(sym.thisSym.typeOfThis, this))
+  }
+
+  /** Provides a default implementation for instances of the `WeakTemplateEntity` type. It must be instantiated as a
+    * `SymbolicEntity` to access the compiler symbol that underlies the entity. */
+  class NoDocTemplateImpl(sym: Symbol, inTpl: => TemplateImpl) extends EntityImpl(sym, inTpl) with TemplateImpl with NoDocTemplate {
+    def isDocTemplate = false
+  }
+
+  /** Provides a default implementation for instances of the `MemberEntity` type. It must be instantiated as a
+    * `SymbolicEntity` to access the compiler symbol that underlies the entity. */
+  abstract class MemberImpl(sym: Symbol, inTpl: => DocTemplateImpl) extends EntityImpl(sym, inTpl) with MemberEntity {
+    lazy val comment =
+      if (inTpl == null) None else thisFactory.comment(sym, inTpl)
+    override def inTemplate = inTpl
+    override def toRoot: List[MemberImpl] = this :: inTpl.toRoot
+    def inDefinitionTemplates =
+      if (inTpl == null)
+        makeRootPackage.toList
+      else
+        makeTemplate(sym.owner) :: (sym.allOverriddenSymbols map { inhSym => makeTemplate(inhSym.owner) })
+    def visibility = {
+      if (sym.isPrivateLocal) PrivateInInstance()
+      else if (sym.isProtectedLocal) ProtectedInInstance()
+      else {
+        val qual =
+          if (sym.privateWithin != null && sym.privateWithin != NoSymbol)
+            Some(makeTemplate(sym.privateWithin))
+          else None
+        if (sym.isPrivate) PrivateInTemplate(inTpl)
+        else if (sym.isProtected) ProtectedInTemplate(qual getOrElse inTpl)
+        else if (qual.isDefined) PrivateInTemplate(qual.get)
+        else Public()
+      }
+    }
+    def flags = {
+      val fgs = mutable.ListBuffer.empty[Paragraph]
+      if (sym.isImplicit) fgs += Paragraph(Text("implicit"))
+      if (sym hasFlag Flags.SEALED) fgs += Paragraph(Text("sealed"))
+      if (!sym.isTrait && (sym hasFlag Flags.ABSTRACT)) fgs += Paragraph(Text("abstract"))
+      if (!sym.isTrait && (sym hasFlag Flags.DEFERRED)) fgs += Paragraph(Text("abstract"))
+      if (!sym.isModule && (sym hasFlag Flags.FINAL)) fgs += Paragraph(Text("final"))
+      fgs.toList
+    }
+    def deprecation =
+      if (sym.isDeprecated)
+        Some(sym.deprecationMessage match {
+          case Some(msg) => parseWiki(msg, NoPosition)
+          case None =>Body(Nil)
+        })
+      else
+        comment flatMap { _.deprecated }
+    def inheritedFrom =
+      if (inTemplate.sym == this.sym.owner || inTemplate.sym.isPackage) Nil else
+        makeTemplate(this.sym.owner) :: (sym.allOverriddenSymbols map { os => makeTemplate(os.owner) })
+    def resultType = {
+      def resultTpe(tpe: Type): Type = tpe match { // similar to finalResultType, except that it leaves singleton types alone
+        case PolyType(_, res) => resultTpe(res)
+        case MethodType(_, res) => resultTpe(res)
+        case _ => tpe
+      }
+      makeType(resultTpe(sym.tpe), inTemplate, sym)
+    }
+    def isDef = false
+    def isVal = false
+    def isLazyVal = false
+    def isVar = false
+    def isImplicit = sym.isImplicit
+    def isConstructor = false
+    def isAliasType = false
+    def isAbstractType = false
+    def isAbstract =
+      ((!sym.isTrait && ((sym hasFlag Flags.ABSTRACT) || (sym hasFlag Flags.DEFERRED))) || 
+      sym.isAbstractClass || sym.isAbstractType) && !sym.isSynthetic
+    def isTemplate = false
+  }
+
+  /** Provides a default implementation for instances of the `TemplateEntity` type. It must be instantiated as a
+    * `TemplateSymbolicEntity` to access the compiler symbol that underlies the entity and to be registered with the
+    * `templatesCache` at the very start of its instantiation.
+    *
+    * The instantiation of `TemplateImpl` triggers the creation of the following entities.
+    * * The owner of the template (as a full template);
+    * * All ancestors of the template (as weak templates);
+    * * All non-package members (including other templates, as full templates). */
+  abstract class DocTemplateImpl(sym: Symbol, inTpl: => DocTemplateImpl) extends MemberImpl(sym, inTpl) with TemplateImpl with HigherKindedImpl with DocTemplateEntity {
+    //if (inTpl != null) println("mbr " + sym + " in " + (inTpl.toRoot map (_.sym)).mkString(" > "))
+    templatesCache += (sym -> this)
+    lazy val definitionName = optimize(inDefinitionTemplates.head.qualifiedName + "." + name)
+    override def toRoot: List[DocTemplateImpl] = this :: inTpl.toRoot
+    def inSource = if (sym.sourceFile != null) Some(sym.sourceFile, sym.pos.line) else None
+    def sourceUrl = {
+      def fixPath(s: String) = s.replaceAll("\\" + java.io.File.separator, "/")
+      val assumedSourceRoot: String = {
+        val fixed = fixPath(settings.sourcepath.value)
+        if (fixed endsWith "/") fixed.dropRight(1) else fixed
+      }
+      if (!settings.docsourceurl.isDefault)
+        inSource map { case (file, _) =>
+          val filePath = fixPath(file.path).replaceFirst("^" + assumedSourceRoot, "").stripSuffix(".scala")
+          val tplOwner = this.inTemplate.qualifiedName
+          val tplName = this.name
+          val patches = new Regex("""€\{(FILE_PATH|TPL_OWNER|TPL_NAME)\}""")
+          val patchedString = patches.replaceAllIn(settings.docsourceurl.value, { m => m.group(1) match {
+              case "FILE_PATH" => filePath
+              case "TPL_OWNER" => tplOwner
+              case "TPL_NAME" => tplName
+            }
+          })
+          new java.net.URL(patchedString)
+        }
+      else None
+    }
+    def parentType = {
+      if (sym.isPackage) None else {
+        val tps =
+          (sym.tpe.parents filter (_ != ScalaObjectClass.tpe)) map { _.asSeenFrom(sym.thisType, sym) }
+        Some(makeType(RefinedType(tps, EmptyScope), inTpl))
+      }
+    }
+    val linearization: List[(TemplateEntity, TypeEntity)] = {
+      val acs = sym.ancestors filter { _ != ScalaObjectClass }
+      val tps = acs map { cls => makeType(sym.info.baseType(cls), this) }
+      val tpls = acs map { makeTemplate(_) }
+      tpls map {
+          case dtpl: DocTemplateImpl => dtpl.registerSubClass(this)
+          case _ => 
+      }
+      tpls zip tps
+    }
+    def linearizationTemplates = linearization map { _._1 }
+    def linearizationTypes = linearization map { _._2 }
+    private lazy val subClassesCache = mutable.Buffer.empty[DocTemplateEntity]
+    def registerSubClass(sc: DocTemplateEntity): Unit = {
+      assert(subClassesCache != null)
+      subClassesCache += sc
+    }
+    def subClasses = subClassesCache.toList
+    protected lazy val memberSyms =
+       // Only this class's constructors are part of its members, inherited constructors are not.
+      sym.info.members.filter(s => localShouldDocument(s) && (!s.isConstructor || s.owner == sym))
+    val members       = memberSyms flatMap (makeMember(_, this))
+    val templates     = members collect { case c: DocTemplateEntity => c }
+    val methods       = members collect { case d: Def => d }
+    val values        = members collect { case v: Val => v }
+    val abstractTypes = members collect { case t: AbstractType => t }
+    val aliasTypes    = members collect { case t: AliasType => t }
+    override def isTemplate = true
+    def isDocTemplate = true
+    def companion = sym.companionSymbol match {
+      case NoSymbol => None
+      case comSym if !isEmptyJavaObject(comSym) => Some(makeDocTemplate(comSym, inTpl))
+      case _ => None
+    }
+  }
+
+  abstract class PackageImpl(sym: Symbol, inTpl: => PackageImpl) extends DocTemplateImpl(sym, inTpl) with Package {
+    override def inTemplate = inTpl
+    override def toRoot: List[PackageImpl] = this :: inTpl.toRoot
+    val packages = members collect { case p: Package => p }
+  }
+
+  abstract class RootPackageImpl(sym: Symbol) extends PackageImpl(sym, null) with RootPackageEntity
+  
+  abstract class NonTemplateMemberImpl(sym: Symbol, inTpl: => DocTemplateImpl) extends MemberImpl(sym, inTpl) with NonTemplateMemberEntity {
+    override def qualifiedName = optimize(inTemplate.qualifiedName + "#" + name)
+    lazy val definitionName = optimize(inDefinitionTemplates.head.qualifiedName + "#" + name)
+    def isUseCase = sym.isSynthetic
+  }
+  
+  abstract class NonTemplateParamMemberImpl(sym: Symbol, inTpl: => DocTemplateImpl) extends NonTemplateMemberImpl(sym, inTpl) {
+    def valueParams =
+      sym.paramss map { ps => (ps.zipWithIndex) map { case (p, i) =>
+        if (p.nameString contains "$") makeValueParam(p, inTpl, optimize("arg" + i)) else makeValueParam(p, inTpl)
+      }}
+  }
+
+  abstract class ParameterImpl(sym: Symbol, inTpl: => TemplateImpl) extends EntityImpl(sym, inTpl) with ParameterEntity {
+    override def inTemplate = inTpl
+  }
+  
+  private trait TypeBoundsImpl extends EntityImpl {    
+    def lo = sym.info.bounds match {
+      case TypeBounds(lo, hi) if lo.typeSymbol != NothingClass =>
+        Some(makeType(appliedType(lo, sym.info.typeParams map {_.tpe}), inTemplate))
+      case _ => None
+    }
+    def hi = sym.info.bounds match {
+      case TypeBounds(lo, hi) if hi.typeSymbol != AnyClass =>
+        Some(makeType(appliedType(hi, sym.info.typeParams map {_.tpe}), inTemplate))
+      case _ => None
+    }
+  }
+
+  trait HigherKindedImpl extends EntityImpl with HigherKinded {
+    def typeParams =
+      sym.typeParams map (makeTypeParam(_, inTemplate))
+  }
+
+  /* ============== MAKER METHODS ============== */
+
+  /** */
+  def normalizeTemplate(aSym: Symbol): Symbol = aSym match {
+    case null | EmptyPackage | NoSymbol =>
+      normalizeTemplate(RootPackage)
+    case ScalaObjectClass | ObjectClass =>
+      normalizeTemplate(AnyRefClass)
+    case _ if aSym.isModuleClass || aSym.isPackageObject =>
+      normalizeTemplate(aSym.sourceModule)
+    case _ =>
+      aSym
+  }
+
+  def makeRootPackage: Option[PackageImpl] =
+    makePackage(RootPackage, null)
+
+  /** Creates a package entity for the given symbol or returns `None` if the symbol does not denote a package that
+    * contains at least one ''documentable'' class, trait or object. Creating a package entity */
+  def makePackage(aSym: Symbol, inTpl: => PackageImpl): Option[PackageImpl] = {
+    val bSym = normalizeTemplate(aSym)
+    if (templatesCache isDefinedAt (bSym))
+      Some(templatesCache(bSym) match {case p: PackageImpl => p})
+    else {
+      val pack =
+        if (bSym == RootPackage)
+          new RootPackageImpl(bSym) {
+            override val name = "root"
+            override def inTemplate = this
+            override def toRoot = this :: Nil
+            override def qualifiedName = "_root_"
+            override def inheritedFrom = Nil
+            override def isRootPackage = true
+            override protected lazy val memberSyms =
+              (bSym.info.members ++ EmptyPackage.info.members) filter { s =>
+                s != EmptyPackage && s != RootPackage
+              }
+          }
+        else
+          new PackageImpl(bSym, inTpl) {}
+      if (pack.templates.isEmpty) {
+        droppedPackages += 1
+        None
+      }
+      else Some(pack)
+    }
+
+  }
+
+  /** */
+  def makeTemplate(aSym: Symbol): TemplateImpl = {
+    val bSym = normalizeTemplate(aSym)
+    if (bSym == RootPackage)
+      makeRootPackage.get
+    else if (bSym.isPackage)
+      makeTemplate(bSym.owner) match {
+        case inPkg: PackageImpl => makePackage(bSym, inPkg) getOrElse (new NoDocTemplateImpl(bSym, inPkg))
+        case _ => throw new Error("'" + bSym + "' must be in a package")
+      }
+    else if (templateShouldDocument(bSym))
+      makeTemplate(bSym.owner) match {
+        case inDTpl: DocTemplateImpl => makeDocTemplate(bSym, inDTpl)
+        case _ => throw new Error("'" + bSym + "' must be in documentable template")
+      }
+    else
+      new NoDocTemplateImpl(bSym, makeTemplate(bSym.owner))
+  }
+
+  /** */
+  def makeDocTemplate(aSym: Symbol, inTpl: => DocTemplateImpl): DocTemplateImpl = {
+    val bSym = normalizeTemplate(aSym)
+    val minimumInTpl =
+      if (bSym.owner != inTpl.sym)
+        makeTemplate(aSym.owner) match {
+          case inDTpl: DocTemplateImpl => inDTpl
+          case inNDTpl => throw new Error("'" + bSym + "' is owned by '" + inNDTpl + "' which is not documented")
+        }
+      else
+        inTpl
+    if (templatesCache isDefinedAt (bSym))
+      templatesCache(bSym)
+    else if (bSym.isModule || (bSym.isAliasType && bSym.tpe.typeSymbol.isModule))
+      new DocTemplateImpl(bSym, minimumInTpl) with Object
+    else if (bSym.isTrait || (bSym.isAliasType && bSym.tpe.typeSymbol.isTrait))
+      new DocTemplateImpl(bSym, minimumInTpl) with Trait
+    else if (bSym.isClass || (bSym.isAliasType && bSym.tpe.typeSymbol.isClass))
+      new DocTemplateImpl(bSym, minimumInTpl) with Class {
+        def valueParams =
+          // we don't want params on a class (non case class) signature
+          if (isCaseClass) List(sym.constrParamAccessors map (makeValueParam(_, this)))
+          else List.empty
+        val constructors =
+          members collect { case d: Constructor => d }
+        def primaryConstructor = constructors find { _.isPrimary }
+      }
+    else
+      throw new Error("'" + bSym + "' that isn't a class, trait or object cannot be built as a documentable template")
+  }
+
+  /** */
+  def makeMember(aSym: Symbol, inTpl: => DocTemplateImpl): List[MemberImpl] = {
+
+    def makeMember0(bSym: Symbol): Option[MemberImpl] = {
+      if (bSym.isGetter && bSym.isLazy)
+        Some(new NonTemplateMemberImpl(bSym, inTpl) with Val {
+          override def isLazyVal = true
+        })
+      else if (bSym.isGetter && bSym.accessed.isMutable)
+        Some(new NonTemplateMemberImpl(bSym, inTpl) with Val {
+          override def isVar = true
+        })
+      else if (bSym.isMethod && !bSym.isGetterOrSetter && !bSym.isConstructor && !bSym.isModule)
+        Some(new NonTemplateParamMemberImpl(bSym, inTpl) with HigherKindedImpl with Def {
+          override def isDef = true
+        })
+      else if (bSym.isConstructor)
+        Some(new NonTemplateParamMemberImpl(bSym, inTpl) with Constructor {
+          override def isConstructor = true
+          def isPrimary = sym.isPrimaryConstructor
+        })
+      else if (bSym.isGetter) // Scala field accessor or Java field
+        Some(new NonTemplateMemberImpl(bSym, inTpl) with Val {
+          override def isVal = true
+        })
+      else if (bSym.isAbstractType)
+        Some(new NonTemplateMemberImpl(bSym, inTpl) with TypeBoundsImpl with HigherKindedImpl with AbstractType {
+          override def isAbstractType = true
+        })
+      else if (bSym.isAliasType)
+        Some(new NonTemplateMemberImpl(bSym, inTpl) with HigherKindedImpl with AliasType {
+          override def isAliasType = true
+          def alias = makeType(sym.tpe.dealias, inTpl, sym)
+        })
+      else if (bSym.isPackage)
+        inTpl match { case inPkg: PackageImpl =>  makePackage(bSym, inPkg) }
+      else if ((bSym.isClass || bSym.isModule) && templateShouldDocument(bSym))
+        Some(makeDocTemplate(bSym, inTpl))
+      else
+        None
+    }
+
+    if (!localShouldDocument(aSym) || aSym.isModuleClass || aSym.isPackageObject || aSym.isMixinConstructor)
+      Nil
+    else {
+      val allSyms = useCases(aSym, inTpl.sym) map { case (bSym, bComment, bPos) =>
+        addCommentBody(bSym, inTpl, bComment, bPos)
+      }
+      (allSyms :+ aSym) flatMap { makeMember0(_) }
+    }
+    
+  }
+
+  /** */
+  def makeTypeParam(aSym: Symbol, inTpl: => TemplateImpl): TypeParam =
+    new ParameterImpl(aSym, inTpl) with TypeBoundsImpl with HigherKindedImpl with TypeParam {
+      def isTypeParam = true
+      def isValueParam = false
+      def variance: String = {
+        if (sym hasFlag Flags.COVARIANT) "+"
+        else if (sym hasFlag Flags.CONTRAVARIANT) "-"
+        else ""
+      }
+    }
+
+  /** */
+  def makeValueParam(aSym: Symbol, inTpl: => DocTemplateImpl): ValueParam = {
+    makeValueParam(aSym, inTpl, aSym.nameString)
+  }
+
+  /** */
+  def makeValueParam(aSym: Symbol, inTpl: => DocTemplateImpl, newName: String): ValueParam =
+    new ParameterImpl(aSym, inTpl) with ValueParam {
+      override val name = newName
+      def isTypeParam = false
+      def isValueParam = true
+      def defaultValue =
+        if (aSym.hasDefault)
+          // units.filter should return only one element
+          (currentRun.units filter (_.source.file == aSym.sourceFile)).toList match {
+            case List(unit) =>
+              (unit.body find (_.symbol == aSym)) match {
+                case Some(ValDef(_,_,_,rhs)) => 
+                  Some(makeTree(rhs))
+                case _ => None
+              }
+            case _ => None
+          }
+        else None
+      def resultType =
+        makeType(sym.tpe, inTpl, sym)
+      def isImplicit = aSym.isImplicit
+    }
+
+  /** */
+  def makeType(aType: Type, inTpl: => TemplateImpl, dclSym: Symbol): TypeEntity = {
+    def ownerTpl(sym: Symbol): Symbol =
+      if (sym.isClass || sym.isModule || sym == NoSymbol) sym else ownerTpl(sym.owner)
+    val tpe =
+      if (thisFactory.settings.useStupidTypes.value) aType else {
+        def ownerTpl(sym: Symbol): Symbol =
+          if (sym.isClass || sym.isModule || sym == NoSymbol) sym else ownerTpl(sym.owner)
+        val fixedSym = if (inTpl.sym.isModule) inTpl.sym.moduleClass else inTpl.sym
+        aType.asSeenFrom(fixedSym.thisType, ownerTpl(dclSym))
+      }
+    makeType(tpe, inTpl)
+  }
+  
+  /** */
+  def makeType(aType: Type, inTpl: => TemplateImpl): TypeEntity =
+    new TypeEntity {
+      private val nameBuffer = new StringBuilder
+      private var refBuffer = new immutable.TreeMap[Int, (TemplateEntity, Int)]
+      private def appendTypes0(types: List[Type], sep: String): Unit = types match {
+        case Nil =>
+        case tp :: Nil =>
+          appendType0(tp)
+        case tp :: tps =>
+          appendType0(tp)
+          nameBuffer append sep
+          appendTypes0(tps, sep)
+      }
+      private def checkFunctionType(tpe: TypeRef): Boolean = {
+        val TypeRef(_, sym, args) = tpe
+        (args.length > 0) && (args.length - 1 <= definitions.MaxFunctionArity) &&
+        (sym == definitions.FunctionClass(args.length - 1))
+      }
+      private def appendType0(tpe: Type): Unit = tpe match {
+        /* Type refs */
+        case tp: TypeRef if (checkFunctionType(tp)) =>
+          nameBuffer append '('
+          appendTypes0(tp.args.init, ", ")
+          nameBuffer append ") ⇒ "
+          appendType0(tp.args.last)
+        case tp: TypeRef if (tp.typeSymbol == definitions.RepeatedParamClass) =>
+          appendType0(tp.args.head)
+          nameBuffer append '*'
+        case tp: TypeRef if (tp.typeSymbol == definitions.ByNameParamClass) =>
+          nameBuffer append "⇒ "
+          appendType0(tp.args.head)
+        case tp: TypeRef if (definitions.isTupleType(tp)) =>
+          nameBuffer append '('
+          appendTypes0(tp.args, ", ")
+          nameBuffer append ')'
+        case TypeRef(pre, aSym, targs) =>
+          val bSym = normalizeTemplate(aSym)
+          if (bSym.isNonClassType)
+            nameBuffer append bSym.name
+          else {
+            val tpl = makeTemplate(bSym)
+            val pos0 = nameBuffer.length
+            refBuffer += pos0 -> (tpl, tpl.name.length)
+            nameBuffer append tpl.name
+          }
+          if (!targs.isEmpty) {
+            nameBuffer append '['
+            appendTypes0(targs, ", ")
+            nameBuffer append ']'
+          }
+        /* Refined types */
+        case RefinedType(parents, defs) =>
+          appendTypes0((if (parents.length > 1) parents filterNot (_ == ObjectClass.tpe) else parents), " with ")
+          if (!defs.isEmpty) {
+            nameBuffer append " {...}" // TODO: actually print the refinement
+          }
+        /* Polymorphic types */
+        case PolyType(tparams, result) if tparams nonEmpty =>
+//          throw new Error("Polymorphic type '" + tpe + "' cannot be printed as a type")
+          def typeParamsToString(tps: List[Symbol]): String = if(tps isEmpty) "" else
+            tps.map{tparam =>
+              tparam.varianceString + tparam.name + typeParamsToString(tparam.typeParams)
+            }.mkString("[", ", ", "]")
+          nameBuffer append typeParamsToString(tparams)
+          appendType0(result)
+        case PolyType(tparams, result) if (tparams.isEmpty) =>
+          nameBuffer append '⇒'
+          appendType0(result)
+        case tpen =>
+          nameBuffer append tpen.toString
+      }
+      appendType0(aType)
+      val refEntity = refBuffer
+      val name = optimize(nameBuffer.toString)
+    }
+
+  def templateShouldDocument(aSym: Symbol): Boolean = {
+  	// TODO: document sourceless entities (e.g., Any, etc), based on a new Setting to be added
+  	(aSym.isPackageClass || (aSym.sourceFile != null)) && localShouldDocument(aSym) &&
+    ( aSym.owner == NoSymbol || templateShouldDocument(aSym.owner) ) && !isEmptyJavaObject(aSym)
+  }
+
+  def isEmptyJavaObject(aSym: Symbol): Boolean = {
+    def hasMembers = aSym.info.members.exists(s => localShouldDocument(s) && (!s.isConstructor || s.owner == aSym))
+    aSym.isModule && aSym.hasFlag(Flags.JAVA) && !hasMembers
+  }
+
+  def localShouldDocument(aSym: Symbol): Boolean = {
+    !aSym.isPrivate && (aSym.isProtected || aSym.privateWithin == NoSymbol) && !aSym.isSynthetic
+  }
+}
diff --git a/src/compiler/scala/tools/nsc/doc/model/TreeEntity.scala b/src/compiler/scala/tools/nsc/doc/model/TreeEntity.scala
new file mode 100644
index 0000000..7a0c8c7
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/doc/model/TreeEntity.scala
@@ -0,0 +1,16 @@
+
+
+
+/** we create a TreeEntity to store some text and some hyperLinks to make on entities in it */
+
+package scala.tools.nsc
+package doc
+package model
+
+import scala.collection.immutable.TreeMap
+
+
+class TreeEntity {
+  var expression:String = ""
+  var refs = new TreeMap[Int, (Entity, Int)] // start, (Entity to be linked to , end)
+}
\ No newline at end of file
diff --git a/src/compiler/scala/tools/nsc/doc/model/TreeFactory.scala b/src/compiler/scala/tools/nsc/doc/model/TreeFactory.scala
new file mode 100644
index 0000000..67ec166
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/doc/model/TreeFactory.scala
@@ -0,0 +1,89 @@
+package scala.tools.nsc
+package doc
+package model
+
+/** The goal of this trait is , using makeTree, 
+  * to browse a tree to 
+  * 1- have the String of the complete tree (tree.expression)
+  * 2- fill references to create hyperLinks later in html.pageTemplate
+  * 
+  * It is applied in ModelFactory => makeTree
+  * 
+  */
+ 
+trait TreeFactory {
+  thisTreeFactory: ModelFactory with TreeFactory => 
+  val global:Global
+  
+  import global._
+  
+  def makeTree(rhs:Tree):TreeEntity = {
+    val printSteps:Boolean = false
+    val tree = new TreeEntity
+    val firstIndex = rhs.pos.startOrPoint
+    
+    /** Gets the full string of the right hand side of a parameter, without links */
+    def makeExpression(rhs:Tree){
+      val start = rhs.pos.startOrPoint
+      val end = rhs.pos.endOrPoint
+      var expr = ""
+      for (i <- start until end) expr += rhs.pos.source.content.apply(i)
+      rhs match {
+        case Block(r,s) => expr += "}"
+        case _ =>
+      }
+      tree.expression += expr 
+    }
+    
+    val traverser = new Traverser{
+      /** Finds the Entity on which we will later create a link on, 
+        * stores it in tree.refs with its position
+        */
+      def makeLink(rhs:Tree){
+        var start = rhs.pos.point - firstIndex
+        val end = rhs.pos.endOrPoint - firstIndex
+        if(start != end) {
+          var asym = rhs.symbol
+          if (asym.isClass) makeTemplate(asym) match{
+            case docTmpl: DocTemplateImpl => 
+              tree.refs += ((start,(docTmpl,end)))
+            case _ => 
+          }
+          else if (asym.isTerm && asym.owner.isClass){
+            if (asym.isSetter) asym = asym.getter(asym.owner)
+            makeTemplate(asym.owner) match {
+              case docTmpl:DocTemplateImpl =>
+                val mbrs:List[MemberImpl] = makeMember(asym,docTmpl)
+                mbrs foreach {mbr =>
+                  tree.refs += ((start,(mbr,end)))
+                }
+              case _ =>
+            }
+          }
+        }
+      }
+      /**
+        * Goes through the tree and makes links when a Select occurs, 
+        * The case of New(_) is ignored because the object we want to create a link on
+        * will be reached with recursivity and we don't want a link on the "new" string
+        * If a link is not created, its case is probably not defined in here
+        */
+      override def traverse(tree:Tree) = tree match {
+        case Select(qualifier, name) => 
+          qualifier match {
+            case New(_) => 
+            case _ => makeLink(tree)
+          }
+          traverse(qualifier)
+        case Ident(_) => makeLink(tree)
+        case _ => 
+          super.traverse(tree)
+      }
+    }
+
+    makeExpression(rhs)
+    traverser.traverse(rhs)
+    return tree
+  }
+     
+}
diff --git a/src/compiler/scala/tools/nsc/doc/model/TypeEntity.scala b/src/compiler/scala/tools/nsc/doc/model/TypeEntity.scala
new file mode 100644
index 0000000..19db05d
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/doc/model/TypeEntity.scala
@@ -0,0 +1,25 @@
+/* NSC -- new Scala compiler
+ * Copyright 2007-2010 LAMP/EPFL
+ * @author  Manohar Jonnalagedda
+ */
+
+package scala.tools.nsc
+package doc
+package model
+
+import scala.collection._
+
+abstract class TypeEntity {
+  
+  /** A string representation of this type. */
+  def name: String
+  
+  /** Maps which parts of this type's name reference other entities. The map is indexed by the position of the first
+    * character that reference some entity, and contains the entity and the position of the last referenced
+    * character. The referenced character ranges do not to overlap or nest. The map is sorted by position. */
+  def refEntity: SortedMap[Int, (TemplateEntity, Int)]
+  
+  override def toString =
+    name
+  
+}
diff --git a/src/compiler/scala/tools/nsc/doc/model/comment/Body.scala b/src/compiler/scala/tools/nsc/doc/model/comment/Body.scala
new file mode 100644
index 0000000..255c610
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/doc/model/comment/Body.scala
@@ -0,0 +1,73 @@
+/* NSC -- new Scala compiler -- Copyright 2007-2010 LAMP/EPFL */
+
+package scala.tools.nsc
+package doc
+package model
+package comment
+
+import scala.collection._
+
+import java.net.URL
+
+/** A body of text. A comment has a single body, which is composed of at least one block. Inside every body is exactly
+  * one summary (see [[scala.tools.nsc.doc.model.comment.Summary]]). */
+final case class Body(blocks: Seq[Block]) {
+
+  /** The summary text of the comment body. */
+  lazy val summary: Option[Inline] = {
+    def summaryInBlock(block: Block): Seq[Inline] = block match {
+      case Title(text, _)        => summaryInInline(text)
+      case Paragraph(text)       => summaryInInline(text)
+      case UnorderedList(items)  => items flatMap { summaryInBlock(_) }
+      case OrderedList(items, _) => items flatMap { summaryInBlock(_) }
+      case DefinitionList(items) => items.values.toSeq flatMap { summaryInBlock(_) }
+      case _                     => Nil
+    }
+    def summaryInInline(text: Inline): Seq[Inline] = text match {
+      case Summary(text)     => List(text)
+      case Chain(items)      => items flatMap { summaryInInline(_) }
+      case Italic(text)      => summaryInInline(text)
+      case Bold(text)        => summaryInInline(text)
+      case Underline(text)   => summaryInInline(text)
+      case Superscript(text) => summaryInInline(text)
+      case Subscript(text)   => summaryInInline(text)
+      case Link(_, title)    => summaryInInline(title)
+      case _                 => Nil
+    }
+    (blocks flatMap { summaryInBlock(_) }).toList match {
+      case Nil => None
+      case inline :: Nil => Some(inline)
+      case inlines => Some(Chain(inlines))
+    }
+  }
+
+}
+
+/** A block-level element of text, such as a paragraph or code block. */
+sealed abstract class Block
+
+final case class Title(text: Inline, level: Int) extends Block
+final case class Paragraph(text: Inline) extends Block
+final case class Code(data: String) extends Block
+final case class UnorderedList(items: Seq[Block]) extends Block
+final case class OrderedList(items: Seq[Block], style: String) extends Block
+final case class DefinitionList(items: SortedMap[Inline, Block]) extends Block
+final case class HorizontalRule() extends Block
+
+/** An section of text inside a block, possibly with formatting. */
+sealed abstract class Inline
+
+final case class Chain(items: Seq[Inline]) extends Inline
+final case class Italic(text: Inline) extends Inline
+final case class Bold(text: Inline) extends Inline
+final case class Underline(text: Inline) extends Inline
+final case class Superscript(text: Inline) extends Inline
+final case class Subscript(text: Inline) extends Inline
+final case class Link(target: String, title: Inline) extends Inline
+final case class EntityLink(target: TemplateEntity) extends Inline
+final case class Monospace(text: String) extends Inline
+final case class Text(text: String) extends Inline
+final case class HtmlTag(data: String) extends Inline
+
+/** The summary of a comment, usually its first sentence. There must be exactly one summary per body. */
+final case class Summary(text: Inline) extends Inline
diff --git a/src/compiler/scala/tools/nsc/doc/model/comment/Comment.scala b/src/compiler/scala/tools/nsc/doc/model/comment/Comment.scala
new file mode 100644
index 0000000..9af583d
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/doc/model/comment/Comment.scala
@@ -0,0 +1,77 @@
+/* NSC -- new Scala compiler -- Copyright 2007-2010 LAMP/EPFL */
+
+package scala.tools.nsc
+package doc
+package model
+package comment
+
+import scala.collection._
+
+/** A Scaladoc comment and all its tags.
+  * 
+  * '''Note:''' the only instantiation site of this class is in [[CommentFactory]].
+  * 
+  * @author Gilles Dubochet
+  * @author Manohar Jonnalagedda */
+abstract class Comment {
+  
+  /** The main body of the comment that describes what the entity does and is.  */
+  def body: Body
+
+  /** A shorter version of the body. Usually, this is the first sentence of the body. */
+  def short: Inline = body.summary getOrElse Text("")
+  
+  /** A list of authors. The empty list is used when no author is defined. */
+  def authors: List[Body]
+
+  /** A list of other resources to see, including links to other entities or to external documentation. The empty list
+    * is used when no other resource is mentionned. */
+  def see: List[Body]
+  
+  /** A description of the result of the entity. Typically, this provides additional information on the domain of the
+    * result, contractual post-conditions, etc. */
+  def result: Option[Body]
+  
+  /** A map of exceptions that the entity can throw when accessed, and a description of what they mean. */
+  def throws: Map[String, Body]
+  
+  /** A map of value parameters, and a description of what they are. Typically, this provides additional information on
+    * the domain of the parameters, contractual pre-conditions, etc. */
+  def valueParams: Map[String, Body]
+
+  /** A map of type parameters, and a description of what they are. Typically, this provides additional information on
+    * the domain of the parameters. */
+  def typeParams: Map[String, Body]
+  
+  /** The version number of the entity. There is no formatting or further meaning attached to this value. */
+  def version: Option[Body]
+  
+  /** A version number of a containing entity where this member-entity was introduced. */
+  def since: Option[Body]
+  
+  /** An annotation as to expected changes on this entity. */
+  def todo: List[Body]
+  
+  /** Whether the entity is deprecated. Using the "@deprecated" Scala attribute is prefereable to using this Scaladoc
+    * tag. */
+  def deprecated: Option[Body]
+
+  /** An additional note concerning the contract of the entity. */
+  def note: List[Body]
+
+  /** A usage example related to the entity. */
+  def example: List[Body]
+
+  /** The comment as it appears in the source text. */
+  def source: Option[String]
+  
+  /** A description for the primary constructor */
+  def constructor: Option[Body]
+  
+  override def toString =
+    body.toString + "\n" +
+    (authors map ("@author " + _.toString)).mkString("\n") +
+    (result map ("@return " + _.toString)).mkString("\n") +
+    (version map ("@version " + _.toString)).mkString
+  
+}
diff --git a/src/compiler/scala/tools/nsc/doc/model/comment/CommentFactory.scala b/src/compiler/scala/tools/nsc/doc/model/comment/CommentFactory.scala
new file mode 100644
index 0000000..2938fc1
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/doc/model/comment/CommentFactory.scala
@@ -0,0 +1,865 @@
+/* NSC -- new Scala compiler -- Copyright 2007-2010 LAMP/EPFL */
+
+package scala.tools.nsc
+package doc
+package model
+package comment
+
+import reporters.Reporter
+import scala.collection._
+import scala.util.matching.Regex
+import scala.annotation.switch
+import util.{NoPosition, Position}
+
+/** The comment parser transforms raw comment strings into `Comment` objects. Call `parse` to run the parser. Note that
+  * the parser is stateless and should only be built once for a given Scaladoc run.
+  *
+  * @param reporter The reporter on which user messages (error, warnings) should be printed.
+  *
+  * @author Manohar Jonnalagedda
+  * @author Gilles Dubochet */
+trait CommentFactory { thisFactory: ModelFactory with CommentFactory =>
+
+  val global: Global
+  import global.reporter
+
+  protected val commentCache = mutable.HashMap.empty[(global.Symbol, TemplateImpl), Comment]
+
+  def addCommentBody(sym: global.Symbol, inTpl: => TemplateImpl, docStr: String, docPos: global.Position): global.Symbol = {
+    commentCache += (sym, inTpl) -> parse(docStr, docStr, docPos)
+    sym
+  }
+
+  def comment(sym: global.Symbol, inTpl: => DocTemplateImpl): Option[Comment] = {
+    val key = (sym, inTpl)
+    if (commentCache isDefinedAt key)
+      Some(commentCache(key))
+    else { // not reached for use-case comments
+      val c = defineComment(sym, inTpl)
+      if (c isDefined) commentCache += (sym, inTpl) -> c.get
+      c
+    }
+  }
+
+  /** A comment is usualy created by the parser, however for some special cases we have to give
+    * some inTpl comments (parent class for example) to the comment of the symbol
+    * This function manages some of those cases : Param accessor and Primary constructor */
+  def defineComment(sym: global.Symbol, inTpl: => DocTemplateImpl):Option[Comment] =
+    //param accessor case
+    // We just need the @param argument, we put it into the body
+    if( sym.isParamAccessor &&
+        inTpl.comment.isDefined &&
+        inTpl.comment.get.valueParams.isDefinedAt(sym.encodedName)) {
+      val comContent = Some(inTpl.comment.get.valueParams(sym.encodedName))
+      Some(createComment(body0=comContent))
+    }
+
+    // Primary constructor case
+    // We need some content of the class definition : @constructor for the body,
+    // @param and @deprecated, we can add some more if necessary
+    else if (sym.isPrimaryConstructor && inTpl.comment.isDefined ) {
+      val tplComment = inTpl.comment.get
+      // If there is nothing to put into the comment there is no need to create it
+      if(tplComment.constructor.isDefined ||
+        tplComment.throws != Map.empty ||
+        tplComment.valueParams != Map.empty ||
+        tplComment.typeParams != Map.empty ||
+        tplComment.deprecated.isDefined
+        )
+        Some(createComment( body0 = tplComment.constructor,
+                            throws0 = tplComment.throws,
+                            valueParams0 = tplComment.valueParams,
+                            typeParams0 = tplComment.typeParams,
+                            deprecated0 = tplComment.deprecated
+                            ))
+      else None
+    }
+    //other comment cases
+    // parse function will make the comment
+    else {
+      val rawComment = global.expandedDocComment(sym, inTpl.sym).trim
+      if (rawComment != "") {
+        val c = parse(rawComment, global.rawDocComment(sym), global.docCommentPos(sym))
+        Some(c)
+      }
+      else None
+    }
+
+  /* Creates comments with necessary arguments */
+  def createComment(body0:        Option[Body]     = None,
+                    authors0:     List[Body]       = List.empty,
+                    see0:         List[Body]       = List.empty,
+                    result0:      Option[Body]     = None,
+                    throws0:      Map[String,Body] = Map.empty,
+                    valueParams0: Map[String,Body] = Map.empty,
+                    typeParams0:  Map[String,Body] = Map.empty,
+                    version0:     Option[Body]     = None,
+                    since0:       Option[Body]     = None,
+                    todo0:        List[Body]       = List.empty,
+                    deprecated0:  Option[Body]     = None,
+                    note0:        List[Body]       = List.empty,
+                    example0:     List[Body]       = List.empty,
+                    constructor0: Option[Body]     = None,
+                    source0:      Option[String]   = None
+                    ):Comment =
+    new Comment{
+      val body        = if(body0 isDefined) body0.get else Body(Seq.empty)
+      val authors     = authors0
+      val see         = see0
+      val result      = result0
+      val throws      = throws0
+      val valueParams = valueParams0
+      val typeParams  = typeParams0
+      val version     = version0
+      val since       = since0
+      val todo        = todo0
+      val deprecated  = deprecated0
+      val note        = note0
+      val example     = example0
+      val constructor = constructor0
+      val source      = source0
+
+  }
+
+  protected val endOfText = '\u0003'
+  protected val endOfLine = '\u000A'
+
+  /** Something that should not have happened, happened, and Scaladoc should exit. */
+  protected def oops(msg: String): Nothing =
+    throw FatalError("program logic: " + msg)
+
+  /** The body of a line, dropping the (optional) start star-marker, one leading whitespace and all trailing whitespace. */
+  protected val CleanCommentLine =
+    new Regex("""(?:\s*\*\s?)?(.*)""")
+
+  /** Dangerous HTML tags that should be replaced by something safer, such as wiki syntax, or that should be dropped. */
+  protected val DangerousTags =
+    new Regex("""<(/?(div|ol|ul|li|h[1-6]|p))( [^>]*)?/?>|<!--.*-->""")
+
+  /** Maps a dangerous HTML tag to a safe wiki replacement, or an empty string if it cannot be salvaged. */
+  protected def htmlReplacement(mtch: Regex.Match): String = mtch.group(1) match {
+    case "p" | "div" => "\n\n"
+    case "h1"  => "\n= "
+    case "/h1" => " =\n"
+    case "h2"  => "\n== "
+    case "/h2" => " ==\n"
+    case "h3"  => "\n=== "
+    case "/h3" => " ===\n"
+    case "h4" | "h5" | "h6" => "\n==== "
+    case "/h4" | "/h5" | "/h6" => " ====\n"
+    case "li" => "\n *  - "
+    case _ => ""
+  }
+
+  /** Javadoc tags that should be replaced by something useful, such as wiki syntax, or that should be dropped. */
+  protected val JavadocTags =
+    new Regex("""\{\@(code|docRoot|inheritDoc|link|linkplain|literal|value)([^}]*)\}""")
+
+  /** Maps a javadoc tag to a useful wiki replacement, or an empty string if it cannot be salvaged. */
+  protected def javadocReplacement(mtch: Regex.Match): String = mtch.group(1) match {
+    case "code" => "`" + mtch.group(2) + "`"
+    case "docRoot"  => ""
+    case "inheritDoc" => ""
+    case "link"  => "`" + mtch.group(2) + "`"
+    case "linkplain" => "`" + mtch.group(2) + "`"
+    case "literal"  => mtch.group(2)
+    case "value" => "`" + mtch.group(2) + "`"
+    case _ => ""
+  }
+
+  /** Safe HTML tags that can be kept. */
+  protected val SafeTags =
+    new Regex("""((<code( [^>]*)?>.*</code>)|(</?(abbr|acronym|address|area|a|bdo|big|blockquote|br|button|b|caption|cite|col|colgroup|dd|del|dfn|em|fieldset|form|hr|img|input|ins|i|kbd|label|legend|link|map|object|optgroup|option|param|pre|q|samp|select|small|span|strong|sub|sup|table|tbody|td|textarea|tfoot|th|thead|tr|tt|var)( [^>]*)?/?>))""")
+
+  protected val safeTagMarker = '\u000E'
+
+  /** A Scaladoc tag not linked to a symbol. Returns the name of the tag, and the rest of the line. */
+  protected val SimpleTag =
+    new Regex("""\s*@(\S+)\s+(.*)""")
+
+  /** A Scaladoc tag linked to a symbol. Returns the name of the tag, the name of the symbol, and the rest of the
+    * line. */
+  protected val SymbolTag =
+    new Regex("""\s*@(param|tparam|throws)\s+(\S*)\s*(.*)""")
+
+  /** The start of a scaladoc code block */
+  protected val CodeBlockStart =
+    new Regex("""(.*)\{\{\{(.*)""")
+
+  /** The end of a scaladoc code block */
+  protected val CodeBlockEnd =
+    new Regex("""(.*)\}\}\}(.*)""")
+
+  /** A key used for a tag map. The key is built from the name of the tag and from the linked symbol if the tag has one.
+    * Equality on tag keys is structural. */
+  protected sealed abstract class TagKey {
+    def name: String
+  }
+
+  protected final case class SimpleTagKey(name: String) extends TagKey
+  protected final case class SymbolTagKey(name: String, symbol: String) extends TagKey
+
+  /** Parses a raw comment string into a `Comment` object.
+    * @param comment The expanded comment string (including start and end markers) to be parsed.
+    * @param src     The raw comment source string.
+    * @param pos     The position of the comment in source. */
+  protected def parse(comment: String, src: String, pos: Position): Comment = {
+
+    /** The cleaned raw comment as a list of lines. Cleaning removes comment start and end markers, line start markers
+      * and unnecessary whitespace. */
+    def clean(comment: String): List[String] = {
+      def cleanLine(line: String): String = {
+        //replaceAll removes trailing whitespaces
+        line.replaceAll("""\s+$""", "") match {
+          case CleanCommentLine(ctl) => ctl
+          case tl => tl
+        }
+      }
+      val strippedComment = comment.trim.stripPrefix("/*").stripSuffix("*/")
+      val safeComment = DangerousTags.replaceAllIn(strippedComment, { htmlReplacement(_) })
+      val javadoclessComment = JavadocTags.replaceAllIn(safeComment, { javadocReplacement(_) })
+      val markedTagComment =
+        SafeTags.replaceAllIn(javadoclessComment, { mtch =>
+          java.util.regex.Matcher.quoteReplacement(safeTagMarker + mtch.matched + safeTagMarker)
+        })
+      markedTagComment.lines.toList map (cleanLine(_))
+    }
+
+    /** Parses a comment (in the form of a list of lines) to a Comment instance, recursively on lines. To do so, it
+      * splits the whole comment into main body and tag bodies, then runs the `WikiParser` on each body before creating
+      * the comment instance.
+      *
+      * @param docBody     The body of the comment parsed until now.
+      * @param tags        All tags parsed until now.
+      * @param lastTagKey  The last parsed tag, or `None` if the tag section hasn't started. Lines that are not tagged
+      *                    are part of the previous tag or, if none exists, of the body.
+      * @param remaining   The lines that must still recursively be parsed.
+      * @param inCodeBlock Whether the next line is part of a code block (in which no tags must be read). */
+    def parse0(docBody: String, tags: Map[TagKey, List[String]], lastTagKey: Option[TagKey], remaining: List[String], inCodeBlock: Boolean): Comment = {
+      remaining match {
+
+        case CodeBlockStart(before, after) :: ls if (!inCodeBlock) =>
+          if (before.trim != "")
+            parse0(docBody, tags, lastTagKey, before :: ("{{{" + after) :: ls, false)
+          else if (after.trim != "")
+            parse0(docBody, tags, lastTagKey, "{{{" :: after :: ls, true)
+          else
+            parse0(docBody + endOfLine + "{{{", tags, lastTagKey, ls, true)
+
+        case CodeBlockEnd(before, after) :: ls =>
+          if (before.trim != "")
+            parse0(docBody, tags, lastTagKey, before :: ("}}}" + after) :: ls, true)
+          else if (after.trim != "")
+            parse0(docBody, tags, lastTagKey, "}}}" :: after :: ls, false)
+          else
+            parse0(docBody + endOfLine + "}}}", tags, lastTagKey, ls, false)
+
+        case SymbolTag(name, sym, body) :: ls if (!inCodeBlock) =>
+          val key = SymbolTagKey(name, sym)
+          val value = body :: tags.getOrElse(key, Nil)
+          parse0(docBody, tags + (key -> value), Some(key), ls, inCodeBlock)
+
+        case SimpleTag(name, body) :: ls if (!inCodeBlock) =>
+          val key = SimpleTagKey(name)
+          val value = body :: tags.getOrElse(key, Nil)
+          parse0(docBody, tags + (key -> value), Some(key), ls, inCodeBlock)
+
+        case line :: ls if (lastTagKey.isDefined) =>
+          val key = lastTagKey.get
+          val value =
+            ((tags get key): @unchecked) match {
+              case Some(b :: bs) => (b + endOfLine + line) :: bs
+              case None => oops("lastTagKey set when no tag exists for key")
+            }
+          parse0(docBody, tags + (key -> value), lastTagKey, ls, inCodeBlock)
+
+        case line :: ls =>
+          val newBody = if (docBody == "") line else docBody + endOfLine + line
+          parse0(newBody, tags, lastTagKey, ls, inCodeBlock)
+
+        case Nil =>
+
+          val bodyTags: mutable.Map[TagKey, List[Body]] =
+            mutable.Map(tags mapValues (_ map (parseWiki(_, pos))) toSeq: _*)
+
+          def oneTag(key: SimpleTagKey): Option[Body] =
+            ((bodyTags remove key): @unchecked) match {
+              case Some(r :: rs) =>
+                if (!rs.isEmpty) reporter.warning(pos, "Only one '@" + key.name + "' tag is allowed")
+                Some(r)
+              case None => None
+            }
+
+          def allTags(key: SimpleTagKey): List[Body] =
+            (bodyTags remove key) getOrElse Nil
+
+          def allSymsOneTag(key: TagKey): Map[String, Body] = {
+            val keys: Seq[SymbolTagKey] =
+              bodyTags.keys.toSeq flatMap {
+                case stk: SymbolTagKey if (stk.name == key.name) => Some(stk)
+                case stk: SimpleTagKey if (stk.name == key.name) =>
+                  reporter.warning(pos, "Tag '@" + stk.name + "' must be followed by a symbol name")
+                  None
+                case _ => None
+              }
+            val pairs: Seq[(String, Body)] =
+              for (key <- keys) yield {
+                val bs = (bodyTags remove key).get
+                if (bs.length > 1)
+                  reporter.warning(pos, "Only one '@" + key.name + "' tag for symbol " + key.symbol + " is allowed")
+                (key.symbol, bs.head)
+              }
+            Map.empty[String, Body] ++ pairs
+          }
+
+          val com = createComment (
+            body0        = Some(parseWiki(docBody, pos)),
+            authors0     = allTags(SimpleTagKey("author")),
+            see0         = allTags(SimpleTagKey("see")),
+            result0      = oneTag(SimpleTagKey("return")),
+            throws0      = allSymsOneTag(SimpleTagKey("throws")),
+            valueParams0 = allSymsOneTag(SimpleTagKey("param")),
+            typeParams0  = allSymsOneTag(SimpleTagKey("tparam")),
+            version0     = oneTag(SimpleTagKey("version")),
+            since0       = oneTag(SimpleTagKey("since")),
+            todo0        = allTags(SimpleTagKey("todo")),
+            deprecated0  = oneTag(SimpleTagKey("deprecated")),
+            note0        = allTags(SimpleTagKey("note")),
+            example0     = allTags(SimpleTagKey("example")),
+            constructor0 = oneTag(SimpleTagKey("constructor")),
+            source0      = Some(clean(src).mkString("\n"))
+          )
+
+          for ((key, _) <- bodyTags)
+            reporter.warning(pos, "Tag '@" + key.name + "' is not recognised")
+
+          com
+
+      }
+    }
+
+    parse0("", Map.empty, None, clean(comment), false)
+
+  }
+
+  /** Parses a string containing wiki syntax into a `Comment` object. Note that the string is assumed to be clean:
+    *  - Removed Scaladoc start and end markers.
+    *  - Removed start-of-line star and one whitespace afterwards (if present).
+    *  - Removed all end-of-line whitespace.
+    *  - Only `endOfLine` is used to mark line endings. */
+  def parseWiki(string: String, pos: Position): Body =
+    new WikiParser(string.toArray, pos).document()
+
+  /** TODO
+    *
+    * @author Ingo Maier
+    * @author Manohar Jonnalagedda
+    * @author Gilles Dubochet */
+  protected final class WikiParser(val buffer: Array[Char], pos: Position) extends CharReader(buffer) { wiki =>
+
+    var summaryParsed = false
+
+    def document(): Body = {
+      nextChar()
+      val blocks = new mutable.ListBuffer[Block]
+      while(char != endOfText)
+        blocks += block()
+      Body(blocks.toList)
+    }
+
+    /* BLOCKS */
+
+    /** {{{ block ::= code | title | hrule | para }}} */
+    def block(): Block = {
+      if (checkSkipInitWhitespace("{{{"))
+        code()
+      else if (checkSkipInitWhitespace("="))
+        title()
+      else if (checkSkipInitWhitespace("----"))
+        hrule()
+      else if (checkList)
+        listBlock
+      else {
+        para()
+      }
+    }
+
+    /** listStyle ::= '-' spc | '1.' spc | 'I.' spc | 'i.' spc | 'A.' spc | 'a.' spc
+      * Characters used to build lists and their constructors */
+    protected val listStyles = Map[String, (Seq[Block] => Block)]( // TODO Should this be defined at some list companion?
+      "- "  -> ( UnorderedList(_) ),
+      "1. " -> ( OrderedList(_,"decimal") ),
+      "I. " -> ( OrderedList(_,"upperRoman") ),
+      "i. " -> ( OrderedList(_,"lowerRoman") ),
+      "A. " -> ( OrderedList(_,"upperAlpha") ),
+      "a. " -> ( OrderedList(_,"lowerAlpha") )
+    )
+
+    /** Checks if the current line is formed with more than one space and one the listStyles */
+    def checkList =
+      (countWhitespace > 0) && (listStyles.keys exists { checkSkipInitWhitespace(_) })
+
+    /** {{{
+      * nListBlock ::= nLine { mListBlock }
+      *      nLine ::= nSpc listStyle para '\n'
+      * }}}
+      * Where n and m stand for the number of spaces. When m > n, a new list is nested. */
+    def listBlock: Block = {
+
+      /** Consumes one list item block and returns it, or None if the block is not a list or a different list. */
+      def listLine(indent: Int, style: String): Option[Block] =
+        if (countWhitespace > indent && checkList)
+          Some(listBlock)
+        else if (countWhitespace != indent || !checkSkipInitWhitespace(style))
+          None
+        else {
+          jumpWhitespace()
+          jump(style)
+          val p = Paragraph(inline(false))
+          blockEnded("end of list line ")
+          Some(p)
+        }
+
+      /** Consumes all list item blocks (possibly with nested lists) of the same list and returns the list block. */
+      def listLevel(indent: Int, style: String): Block = {
+        val lines = mutable.ListBuffer.empty[Block]
+        var line: Option[Block] = listLine(indent, style)
+        while (line.isDefined) {
+          lines += line.get
+          line = listLine(indent, style)
+        }
+        val constructor = listStyles(style)
+        constructor(lines)
+      }
+
+      val indent = countWhitespace
+      val style = (listStyles.keys find { checkSkipInitWhitespace(_) }).getOrElse(listStyles.keys.head)
+      listLevel(indent, style)
+
+    }
+
+    def code(): Block = {
+      jumpWhitespace()
+      jump("{{{")
+      readUntil("}}}")
+      if (char == endOfText)
+        reportError(pos, "unclosed code block")
+      else
+        jump("}}}")
+      blockEnded("code block")
+      Code(getRead)
+    }
+
+    /** {{{ title ::= ('=' inline '=' | "==" inline "==" | ...) '\n' }}} */
+    def title(): Block = {
+      jumpWhitespace()
+      val inLevel = repeatJump("=")
+      val text = inline(check(Array.fill(inLevel)('=')))
+      val outLevel = repeatJump("=", inLevel)
+      if (inLevel != outLevel)
+        reportError(pos, "unbalanced or unclosed heading")
+      blockEnded("heading")
+      Title(text, inLevel)
+    }
+
+    /** {{{ hrule ::= "----" { '-' } '\n' }}} */
+    def hrule(): Block = {
+      jumpWhitespace()
+      repeatJump("-")
+      blockEnded("horizontal rule")
+      HorizontalRule()
+    }
+
+    /** {{{ para ::= inline '\n' }}} */
+    def para(): Block = {
+      val p =
+        if (summaryParsed)
+          Paragraph(inline(false))
+        else {
+          val s = summary()
+          val r =
+            if (checkParaEnded) List(s) else List(s, inline(false))
+          summaryParsed = true
+          Paragraph(Chain(r))
+        }
+      while (char == endOfLine && char != endOfText)
+        nextChar()
+      p
+    }
+
+    /* INLINES */
+
+    def inline(isInlineEnd: => Boolean): Inline = {
+
+      def inline0(): Inline = {
+        if (char == safeTagMarker) htmlTag()
+        else if (check("'''")) bold()
+        else if (check("''")) italic()
+        else if (check("`"))  monospace()
+        else if (check("__")) underline()
+        else if (check("^"))  superscript()
+        else if (check(",,")) subscript()
+        else if (check("[[")) link()
+        else {
+          readUntil { char == safeTagMarker || check("''") || char == '`' || check("__") || char == '^' || check(",,") || check("[[") || isInlineEnd || checkParaEnded || char == endOfLine }
+          Text(getRead())
+        }
+      }
+
+      val inlines: List[Inline] = {
+        val iss = mutable.ListBuffer.empty[Inline]
+        iss += inline0()
+        while(!isInlineEnd && !checkParaEnded) {
+          if (char == endOfLine) nextChar()
+          val current = inline0()
+          (iss.last, current) match {
+            case (Text(t1), Text(t2)) =>
+              iss.update(iss.length - 1, Text(t1 + endOfLine + t2))
+            case _ => iss += current
+          }
+        }
+        iss.toList
+      }
+
+      inlines match {
+        case Nil => Text("")
+        case i :: Nil => i
+        case is => Chain(is)
+      }
+
+    }
+
+    def htmlTag(): Inline = {
+      jump(safeTagMarker)
+      readUntil(safeTagMarker)
+      if (char != endOfText) jump(safeTagMarker)
+      var read = getRead
+      HtmlTag(read)
+    }
+
+    def bold(): Inline = {
+      jump("'''")
+      val i = inline(check("'''"))
+      jump("'''")
+      Bold(i)
+    }
+
+    def italic(): Inline = {
+      jump("''")
+      val i = inline(check("''"))
+      jump("''")
+      Italic(i)
+    }
+
+    def monospace(): Inline = {
+      jump("`")
+      readUntil { char == '`' }
+      jump("`")
+      Monospace(getRead())
+    }
+
+    def underline(): Inline = {
+      jump("__")
+      val i = inline(check("__"))
+      jump("__")
+      Underline(i)
+    }
+
+    def superscript(): Inline = {
+      jump("^")
+      val i = inline(check("^"))
+      jump("^")
+      Superscript(i)
+    }
+
+    def subscript(): Inline = {
+      jump(",,")
+      val i = inline(check(",,"))
+      jump(",,")
+      Subscript(i)
+    }
+
+    def summary(): Inline = {
+      val i = inline(check("."))
+      Summary(
+        if (jump("."))
+          Chain(List(i, Text(".")))
+        else
+          i
+      )
+    }
+
+    def entityLink(query: String): Inline = findTemplate(query) match {
+      case Some(tpl) =>
+        EntityLink(tpl)
+      case None =>
+        Text(query)
+    }
+
+    def link(): Inline = {
+      val SchemeUri = new Regex("""([^:]+:.*)""")
+      jump("[[")
+      readUntil { check("]]") || check(" ") }
+      val target = getRead()
+      val title =
+        if (!check("]]")) Some({
+          jump(" ")
+          inline(check("]]"))
+        })
+        else None
+      jump("]]")
+      (target, title) match {
+        case (SchemeUri(uri), Some(title)) =>
+          Link(uri, title)
+        case (SchemeUri(uri), None) =>
+          Link(uri, Text(uri))
+        case (qualName, None) =>
+          entityLink(qualName)
+        case (qualName, Some(text)) =>
+          reportError(pos, "entity link to " + qualName + " cannot have a custom title'" + text + "'")
+          entityLink(qualName)
+      }
+
+    }
+
+    /* UTILITY */
+
+    /** {{{ eol ::= { whitespace } '\n' }}} */
+    def blockEnded(blockType: String): Unit = {
+      if (char != endOfLine && char != endOfText) {
+        reportError(pos, "no additional content on same line after " + blockType)
+        jumpUntil(endOfLine)
+      }
+      while (char == endOfLine)
+        nextChar()
+    }
+
+    def checkParaEnded(): Boolean = {
+      (char == endOfText) ||
+      ((char == endOfLine) && {
+        val poff = offset
+        val pc = char
+        nextChar() // read EOL
+        val ok = {
+          checkSkipInitWhitespace(Array(endOfLine)) ||
+          checkSkipInitWhitespace(Array('=')) ||
+          checkSkipInitWhitespace(Array('{', '{', '{')) ||
+          checkList ||
+          checkSkipInitWhitespace(Array('\u003D'))
+        }
+        offset = poff
+        char = pc
+        ok
+      })
+    }
+
+    def reportError(pos: Position, message: String): Unit =
+      reporter.warning(pos, message)
+
+  }
+
+  protected sealed class CharReader(buffer: Array[Char]) { reader =>
+
+    var char: Char = _
+    var offset: Int = 0
+
+    final def nextChar(): Unit = {
+      if (offset >= buffer.length)
+        char = endOfText
+      else {
+        char = buffer(offset)
+        offset += 1
+      }
+    }
+
+    implicit def strintToChars(s: String): Array[Char] = s.toArray
+
+    def store(body: => Unit): String = {
+      val pre = offset
+      body
+      val post = offset
+      buffer.toArray.slice(pre, post).toString
+    }
+
+    final def check(chars: Array[Char]): Boolean = {
+      val poff = offset
+      val pc = char
+      val ok = jump(chars)
+      offset = poff
+      char = pc
+      ok
+    }
+
+    def checkSkipInitWhitespace(chars: Array[Char]): Boolean = {
+      val poff = offset
+      val pc = char
+      jumpWhitespace()
+      val (ok0, chars0) =
+        if (chars.head == ' ')
+          (offset > poff, chars.tail)
+        else
+          (true, chars)
+      val ok = ok0 && jump(chars0)
+      offset = poff
+      char = pc
+      ok
+    }
+
+    def countWhitespace: Int = {
+      var count = 0
+      val poff = offset
+      val pc = char
+      while (isWhitespace(char) && char != endOfText) {
+        nextChar()
+        count += 1
+      }
+      offset = poff
+      char = pc
+      count
+    }
+
+    /* JUMPERS */
+
+    /** jumps a character and consumes it
+      * @return true only if the correct character has been jumped */
+    final def jump(ch: Char): Boolean = {
+      if (char == ch) {
+        nextChar()
+        true
+      }
+      else false
+    }
+
+    /** jumps all the characters in chars, consuming them in the process.
+      * @return true only if the correct characters have been jumped */
+    final def jump(chars: Array[Char]): Boolean = {
+      var index = 0
+      while (index < chars.length && char == chars(index) && char != endOfText) {
+        nextChar()
+        index += 1
+      }
+      index == chars.length
+    }
+
+    final def checkedJump(chars: Array[Char]): Boolean = {
+      val poff = offset
+      val pc = char
+      val ok = jump(chars)
+      if (!ok) {
+        offset = poff
+        char = pc
+      }
+      ok
+    }
+
+    final def repeatJump(chars: Array[Char], max: Int): Int = {
+      var count = 0
+      var more = true
+      while (more && count < max) {
+        if (!checkedJump(chars))
+          more = false
+        else
+          count += 1
+      }
+      count
+    }
+
+    final def repeatJump(chars: Array[Char]): Int = {
+      var count = 0
+      var more = true
+      while (more) {
+        if (!checkedJump(chars))
+          more = false
+        else
+          count += 1
+      }
+      count
+    }
+
+    final def jumpUntil(ch: Char): Int = {
+      var count = 0
+      while(char != ch && char != endOfText) {
+        nextChar()
+        count=count+1
+      }
+      count
+    }
+
+    final def jumpUntil(chars: Array[Char]): Int = {
+      assert(chars.length > 0)
+      var count = 0
+      val c = chars(0)
+      while(!check(chars) && char != endOfText) {
+        nextChar()
+        while (char != c && char != endOfText) {
+          nextChar()
+          count += 1
+        }
+      }
+      count
+    }
+
+    final def jumpUntil(pred: => Boolean): Int = {
+      var count = 0
+      while (!pred && char != endOfText) {
+        nextChar()
+        count += 1
+      }
+      count
+    }
+
+    def jumpWhitespace() = jumpUntil(!isWhitespace(char))
+
+    /* READERS */
+
+    private val readBuilder = new mutable.StringBuilder
+
+    final def getRead(): String = {
+      val bld = readBuilder.toString
+      readBuilder.clear()
+      if (bld.length < 6) bld.intern else bld
+    }
+
+    final def readUntil(ch: Char): Int = {
+      var count = 0
+      while(char != ch && char != endOfText) {
+        readBuilder += char
+        nextChar()
+      }
+      count
+    }
+
+    final def readUntil(chars: Array[Char]): Int = {
+      assert(chars.length > 0)
+      var count = 0
+      val c = chars(0)
+      while(!check(chars) && char != endOfText) {
+        readBuilder += char
+        nextChar()
+        while (char != c && char != endOfText) {
+          readBuilder += char
+          nextChar()
+        }
+      }
+      count
+    }
+
+    final def readUntil(pred: => Boolean): Int = {
+      var count = 0
+      while (!pred && char != endOfText) {
+        readBuilder += char
+        nextChar()
+      }
+      count
+    }
+
+    /* CHARS CLASSES */
+
+    def isWhitespace(c: Char) = (c: @switch) match {
+      case ' ' | '\t' => true
+      case _ => false
+    }
+
+  }
+
+}
diff --git a/src/compiler/scala/tools/nsc/doc/script.js b/src/compiler/scala/tools/nsc/doc/script.js
deleted file mode 100644
index cbe8e2d..0000000
--- a/src/compiler/scala/tools/nsc/doc/script.js
+++ /dev/null
@@ -1,112 +0,0 @@
-<!--
-// NSC -- new Scala compiler
-// Copyright 2005-2009 LAMP/EPFL
-// @author  Stephane Micheloud
-
-// $Id: script.js 19317 2009-10-28 12:51:02Z cunei $
-
-function setWindowTitle(title) {
-  parent.document.title = title;
-}
-
-var java_api_root = 'http://java.sun.com/javase/6/docs/api/';
-//var java_api_root = 'http://java.sun.com/j2se/1.5.0/docs/api/';
-//var java_api_root = 'http://lamp.epfl.ch/~linuxsoft/java/jdk1.5/docs/api/';
-
-var javax_servlet_api_root = 'http://java.sun.com/products/servlet/2.3/javadoc/';
-
-var scala_doc_url = parent.document.URL;
-var scala_api_root = scala_doc_url.substring(0, scala_doc_url.lastIndexOf("/")+1);
-
-var ant_api_root = 'http://lamp.epfl.ch/~linuxsoft/ant/manual/api/';
-//var ant_api_root = 'http://www.net-freaks.org/doc/ant-1.6.5/manual/api/';
-
-var eclipse_api_root = 'http://help.eclipse.org/help32/topic/org.eclipse.platform.doc.isv/reference/api/';
-
-var fjbg_api_root = 'http://lamp.epfl.ch/~linuxsoft/fjbg/api/';
-
-var liftweb_api_root = 'http://lamp.epfl.ch/~linuxsoft/liftweb/apidocs/';
-
-function get_api_root(key) {
-  root = null;
-  if      (key.indexOf("ch/epfl/lamp/fjbg/") == 0) { root = fjbg_api_root; }
-  else if (key.indexOf("java/"             ) == 0) { root = java_api_root; }
-  else if (key.indexOf("javax/"            ) == 0) { root = java_api_root; }
-  else if (key.indexOf("javax/servlet/"    ) == 0) { root = javax_servlet_api_root; }
-  else if (key.indexOf("scala/"            ) == 0) { root = scala_api_root; }
-  else if (key.indexOf("org/apache/tools/" ) == 0) { root = ant_api_root; }
-  else if (key.indexOf("org/eclipse/"      ) == 0) { root = eclipse_api_root; }
-  else if (key.indexOf("net/liftweb/"      ) == 0) { root = liftweb_api_root; }
-  return root;
-}
-
-var scala_src_root = 'http://lampsvn.epfl.ch/trac/scala/browser/scala/tags/R_2_7_7_final/';
-var lib_src_root = scala_src_root + 'src/library/';
-var comp_src_root = scala_src_root + 'src/compiler/';
-var actors_src_root = scala_src_root + 'src/actors/';
-var dbc_src_root = scala_src_root + 'src/dbc/';
-var swing_src_root = scala_src_root + 'src/swing/';
-
-//var liftweb_src_root = 'http://liftweb.googlecode.com/svn/trunk/liftweb/lift/src/main/scala/';
-
-function get_src_root(key) {
-  root = null;
-  if      (key.indexOf("scala/actors/") == 0) { root = actors_src_root; }
-  else if (key.indexOf("scala/dbc/"   ) == 0) { root = dbc_src_root; }
-  else if (key.indexOf("scala/swing/" ) == 0) { root = swing_src_root; }
-  else if (key.indexOf("scala/tools/" ) == 0) { root = comp_src_root; }
-  else if (key.indexOf("scala/"       ) == 0) { root = lib_src_root; }
-  //else if (key.indexOf("net/liftweb/" ) == 0) { root = liftweb_src_root; }
-  return root;
-}
-
-function init() {
-  elems = document.getElementsByTagName('a');
-  for (i = 0; i < elems.length; i++) {
-    try {
-      key = elems[i].getAttribute('class');
-      href = elems[i].getAttribute('href');
-      api_root = get_api_root(key);
-      if (api_root != null) {
-        href1 = href.substring(href.lastIndexOf("#"))
-        value = api_root + key + ".html" + href1;
-        elems[i].setAttribute('href', value);
-      }
-      src_root = get_src_root(key);
-      if (src_root != null) {
-        value = src_root + key + '.scala?view=markup';
-        elems[i].setAttribute('href', value);
-        elems[i].setAttribute('target' , '_top');
-      }
-    }
-    catch (e) {
-      // do nothing
-    }
-  }
-}
-
-function getLocation() {
-  kinds = parent.navigationFrame.document.getElementById("kinds");
-  oldLocation = parent.classesFrame.window.location.href;
-  //alert("oldLocation="+oldLocation);
-  pos = oldLocation.lastIndexOf("#");
-  classesURL = (pos > 0) ? oldLocation.substring(0, pos) : oldLocation;
-  newLocation = classesURL + kinds.options[kinds.selectedIndex].value;
-  //alert("newLocation="+newLocation);
-  return newLocation;
-}
-
-function gotoKind() {
-  parent.classesFrame.window.location = getLocation();
-}
-
-function resetKind() {
-  kinds = parent.navigationFrame.document.getElementById("kinds");
-  kinds.selectedIndex = 0;
-}
-
-function gotoName(letter) {
-  parent.classesFrame.window.location = getLocation() + "_" + letter;
-}
--->
-
diff --git a/src/compiler/scala/tools/nsc/doc/style.css b/src/compiler/scala/tools/nsc/doc/style.css
deleted file mode 100644
index e243249..0000000
--- a/src/compiler/scala/tools/nsc/doc/style.css
+++ /dev/null
@@ -1,148 +0,0 @@
-/* Scaladoc style sheet */
-
-a:link {
-	color: #0000ee;
-}
-
-a:visited {
-	color: #551a8b;
-}
-
-a:active {
-	color: #0000ee;
-}
-
-body {
-	background-color: #ffffff;
-}
-
-div.entity {
-	margin: 18px 0px 18px 0px;
-	font-size: x-large;
-	font-weight: bold;
-}
-
-div.doctitle {
-	font-weight: bold;
-	font-style: italic;
-}
-
-div.doctitle-larger {
-	margin: 0px 0px 10px 0px;
-	font-size: larger;
-	font-weight: bold;
-}
-
-div.kinds {
-	margin: 0.6em 0 0 0; /* top right bottom left */
-	font-weight: bold;
-}
-
-div.page-title {
-	margin: 15px 0px 15px 0px;
-	font-size: x-large;
-	font-weight: bold;
-	text-align: center;
-}
-
-div.source {
-	font-size: smaller;
-	color: gray;
-}
-
-span.entity {
-	color: #ff6666;
-}
-
-table.member {
-	margin: 0 0 1.2em 0; /* top rigth bottom left */
-	border-collapse: collapse;
-	border: 2px inset #888888;
-	width: 100%;
-}
-
-table.member td.title {
-	border: 2px inset #888888;
-	background-color: #ccccff;
-	font-size: x-large;
-	font-weight: bold;
-}
-
-table.inherited {
-	margin: 0 0 1.2em 0; /* top rigth bottom left */
-	border-collapse: collapse;
-	border: 2px inset #888888;
-	width: 100%;
-}
-
-table.inherited td.title {
-	background-color: #eeeeff;
-	font-weight: bold;
-}
-
-table.member-detail {
-	margin: 10px 0px 0px 0px;
-	border-collapse: collapse;
-	border: 2px inset #888888;
-	background-color: #ffffff;
-	width: 100%;
-}
-
-table.member-detail td.title {
-	border: 2px inset #888888;
-	background-color: #ccccff;
-	font-size: x-large;
-	font-weight: bold;
-}
-
-table.navigation {
-	border-collapse: collapse;
-	width: 100%;
-	font-family: Arial,Helvetica,Sans-Serif;
-}
-
-td.inherited-members {
-	border-top: 2px inset #888888;
-	border-right: 0px;
-}
-
-td.inherited-owner {
-	background-color: #eeeeff;
-	font-weight: bold;
-}
-
-td.modifiers {
-	border-top: 2px inset #888888;
-        border-right: 2px inset #888888;
-	width: 50px;
-	text-align: right;
-}
-
-td.navigation-enabled {
-	font-weight: bold;
-	color: #000000;
-	background-color: #eeeeff;
-}
-
-td.navigation-links {
-	width: 100%;
-	background-color: #eeeeff;
-}
-
-td.navigation-selected {
-	font-weight: bold;
-	color: #ffffff;
-	background-color: #00008b;
-}
-
-td.signature {
-	border-top: 2px inset #888888;
-	width: 90%;
-}
-
-ul.list {
-	margin: 0;
-	padding: 0;
-	list-style: none;
-}
-
diff --git a/src/compiler/scala/tools/nsc/interactive/BuildManager.scala b/src/compiler/scala/tools/nsc/interactive/BuildManager.scala
new file mode 100644
index 0000000..ab1ab6a
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/interactive/BuildManager.scala
@@ -0,0 +1,87 @@
+package scala.tools.nsc
+package interactive
+
+import scala.collection._
+
+import scala.tools.nsc.reporters.{Reporter, ConsoleReporter}
+import util.FakePos
+
+import dependencies._
+import io.AbstractFile
+
+trait BuildManager {
+
+  /** Add the given source files to the managed build process. */
+  def addSourceFiles(files: Set[AbstractFile])
+
+  /** Remove the given files from the managed build process. */
+  def removeFiles(files: Set[AbstractFile])
+
+  /** The given files have been modified by the user. Recompile
+   *  them and their dependent files.
+   */
+  def update(added: Set[AbstractFile], removed: Set[AbstractFile])
+
+  /** Notification that the supplied set of files is being built */
+  def buildingFiles(included: Set[AbstractFile]) {}
+  
+  /** Load saved dependency information. */
+  def loadFrom(file: AbstractFile, toFile: String => AbstractFile) : Boolean
+  
+  /** Save dependency information to `file'. */
+  def saveTo(file: AbstractFile, fromFile: AbstractFile => String)
+
+  def compiler: scala.tools.nsc.Global
+
+  /** Delete classfiles derived from the supplied set of sources */
+  def deleteClassfiles(sources : Set[AbstractFile]) {
+    val targets = compiler.dependencyAnalysis.dependencies.targets
+    for(source <- sources; cf <- targets(source))
+      cf.delete
+  }
+}
+
+
+/** Simple driver for testing the build manager. It presents
+ *  the user to a 'resident compiler' prompt. Each line is
+ *  interpreted as a set of files that have changed. The builder
+ *  then derives the dependent files and recompiles them.
+ */
+object BuildManagerTest extends EvalLoop {
+
+  def prompt = "builder > "
+
+  def error(msg: String) {
+    println(msg + "\n  scalac -help  gives more information")
+  }
+
+  def main(args: Array[String]) {
+    implicit def filesToSet(fs: List[String]): Set[AbstractFile] = {
+      def partition(s: String, r: Tuple2[List[AbstractFile], List[String]])= {
+	    val v = AbstractFile.getFile(s)
+        if (v == null) (r._1, s::r._2) else (v::r._1, r._2)
+      }
+      val result =  fs.foldRight((List[AbstractFile](), List[String]()))(partition)
+      if (!result._2.isEmpty)
+        Console.err.println("No such file(s): " + result._2.mkString(","))
+      Set.empty ++ result._1
+    }
+
+    val settings = new Settings(error)
+    settings.Ybuildmanagerdebug.value = true
+    val command = new CompilerCommand(args.toList, settings)
+//    settings.make.value = "off"
+//    val buildManager: BuildManager = new SimpleBuildManager(settings)
+    val buildManager: BuildManager = new RefinedBuildManager(settings)
+
+    buildManager.addSourceFiles(command.files)
+
+    // enter resident mode
+    loop { line =>
+      val args = line.split(' ').toList
+      val command = new CompilerCommand(args, settings)
+      buildManager.update(command.files, Set.empty)
+    }
+
+  }
+}
diff --git a/src/compiler/scala/tools/nsc/interactive/CompilerControl.scala b/src/compiler/scala/tools/nsc/interactive/CompilerControl.scala
new file mode 100644
index 0000000..92dd91a
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/interactive/CompilerControl.scala
@@ -0,0 +1,157 @@
+package scala.tools.nsc
+package interactive
+
+import scala.util.control.ControlThrowable
+import scala.tools.nsc.io.AbstractFile
+import scala.tools.nsc.util.{SourceFile, Position, WorkScheduler}
+import scala.tools.nsc.symtab._
+import scala.tools.nsc.ast._
+
+/** Interface of interactive compiler to a client such as an IDE
+ */
+trait CompilerControl { self: Global =>
+
+  abstract class WorkItem extends (() => Unit)
+
+  /** Info given for every member found by completion
+   */
+  abstract class Member {
+    val sym: Symbol 
+    val tpe: Type
+    val accessible: Boolean
+  }
+
+  case class TypeMember(
+    sym: Symbol, 
+    tpe: Type, 
+    accessible: Boolean, 
+    inherited: Boolean, 
+    viaView: Symbol) extends Member
+
+  case class ScopeMember(
+    sym: Symbol, 
+    tpe: Type, 
+    accessible: Boolean, 
+    viaImport: Tree) extends Member
+
+  type Response[T] = scala.tools.nsc.interactive.Response[T]
+
+  /** The scheduler by which client and compiler communicate
+   *  Must be initialized before starting compilerRunner
+   */
+  protected val scheduler = new WorkScheduler
+  
+  /** The compilation unit corresponding to a source file
+   *  if it does not yet exist creat a new one atomically
+   */
+  def unitOf(s: SourceFile): RichCompilationUnit = unitOfFile.synchronized {
+    unitOfFile get s.file match {
+      case Some(unit) => 
+        unit
+      case None => 
+        val unit = new RichCompilationUnit(s)
+        unitOfFile(s.file) = unit
+        unit
+    }
+  }
+  
+  /** The compilation unit corresponding to a position */
+  def unitOf(pos: Position): RichCompilationUnit = unitOf(pos.source)
+
+  /** Remove the CompilationUnit corresponding to the given SourceFile
+   *  from consideration for recompilation.
+   */
+  def removeUnitOf(s: SourceFile) = unitOfFile remove s.file
+
+  /* returns the top level classes and objects that were deleted
+   * in the editor since last time recentlyDeleted() was called.
+   */
+  def recentlyDeleted(): List[Symbol] = deletedTopLevelSyms.synchronized {
+    val result = deletedTopLevelSyms
+    deletedTopLevelSyms.clear()
+    result.toList
+  }
+
+  /** Locate smallest tree that encloses position
+   */
+  def locateTree(pos: Position): Tree = 
+    new Locator(pos) locateIn unitOf(pos).body
+
+  /** Locates smallest context that encloses position as an optional value.
+   */
+  def locateContext(pos: Position): Option[Context] =
+    locateContext(unitOf(pos).contexts, pos)
+
+  /** Returns the smallest context that contains given `pos`, throws FatalError if none exists.
+   */
+  def doLocateContext(pos: Position): Context = locateContext(pos) getOrElse {
+    throw new FatalError("no context found for "+pos)
+  }
+    
+  /** Make sure a set of compilation units is loaded and parsed.
+   *  Return () to syncvar `result` on completion.
+   */
+  def askReload(sources: List[SourceFile], result: Response[Unit]) = 
+    scheduler postWorkItem new WorkItem {
+      def apply() = reload(sources, result)
+      override def toString = "reload "+sources
+    }
+
+  /** Set sync var `result` to the smallest fully attributed tree that encloses position `pos`.
+   */
+  def askTypeAt(pos: Position, result: Response[Tree]) = 
+    scheduler postWorkItem new WorkItem {
+      def apply() = self.getTypedTreeAt(pos, result)
+      override def toString = "typeat "+pos.source+" "+pos.show
+    }
+
+  /** Set sync var `result` to the fully attributed & typechecked tree contained in `source`.
+   */
+  def askType(source: SourceFile, forceReload: Boolean, result: Response[Tree]) =
+    scheduler postWorkItem new WorkItem {
+      def apply() = self.getTypedTree(source, forceReload, result)
+      override def toString = "typecheck"
+  }
+  
+  /** Set sync var `result' to list of members that are visible
+   *  as members of the tree enclosing `pos`, possibly reachable by an implicit.
+   */
+  def askTypeCompletion(pos: Position, result: Response[List[Member]]) = 
+    scheduler postWorkItem new WorkItem {
+      def apply() = self.getTypeCompletion(pos, result)
+      override def toString = "type completion "+pos.source+" "+pos.show
+    }
+
+  /** Set sync var `result' to list of members that are visible
+   *  as members of the scope enclosing `pos`.
+   */
+  def askScopeCompletion(pos: Position, result: Response[List[Member]]) = 
+    scheduler postWorkItem new WorkItem {
+      def apply() = self.getScopeCompletion(pos, result)
+      override def toString = "scope completion "+pos.source+" "+pos.show
+    }
+
+  /** Ask to do unit first on present and subsequent type checking passes */
+  def askToDoFirst(f: SourceFile) = {
+    scheduler postWorkItem new WorkItem {
+      def apply() = moveToFront(List(f))
+      override def toString = "dofirst "+f
+    }
+  }
+
+  /** Cancel current compiler run and start a fresh one where everything will be re-typechecked
+   *  (but not re-loaded).
+   */
+  def askReset() = scheduler raise FreshRunReq
+
+  /** Tell the compile server to shutdown, and do not restart again */
+  def askShutdown() = scheduler raise ShutdownReq
+
+  /** Ask for a computation to be done quickly on the presentation compiler thread */
+  def ask[A](op: () => A): A = scheduler doQuickly op
+
+  // ---------------- Interpreted exceptions -------------------
+
+  object FreshRunReq extends ControlThrowable
+  object ShutdownReq extends ControlThrowable
+}
diff --git a/src/compiler/scala/tools/nsc/interactive/ContextTrees.scala b/src/compiler/scala/tools/nsc/interactive/ContextTrees.scala
new file mode 100644
index 0000000..2f32450
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/interactive/ContextTrees.scala
@@ -0,0 +1,146 @@
+package scala.tools.nsc
+package interactive
+
+import collection.mutable.ArrayBuffer
+import util.Position
+
+trait ContextTrees { self: Global =>
+
+  type Context = analyzer.Context
+  lazy val NoContext = analyzer.NoContext
+  type Contexts = ArrayBuffer[ContextTree]
+
+  /** A context tree contains contexts that are indexed by positions.
+   *  It satisfies the following properties:
+   *  1. All context come from compiling the same unit.
+   *  2. Child contexts have parent contexts in their outer chain.
+   *  3. The `pos` field of a context is the same as `context.tree.pos`, unless that
+   *     position is transparent. In that case, `pos` equals the position of
+   *     one of the solid descendants of `context.tree`.
+   *  4. Children of a context have non-overlapping increasing positions.
+   *  5. No context in the tree has a transparent position. 
+   */
+  class ContextTree(val pos: Position, val context: Context, val children: ArrayBuffer[ContextTree]) {
+    def this(pos: Position, context: Context) = this(pos, context, new ArrayBuffer[ContextTree])
+    override def toString = "ContextTree("+pos+", "+children+")"
+  }
+
+  /** Optionally returns the smallest context that contains given `pos`, or None if none exists.
+   */
+  def locateContext(contexts: Contexts, pos: Position): Option[Context] = synchronized {
+    def locateNearestContextTree(contexts: Contexts, pos: Position, recent: Array[ContextTree]): Option[ContextTree] = {
+      locateContextTree(contexts, pos) match {
+        case Some(x) =>
+          recent(0) = x
+          locateNearestContextTree(x.children, pos, recent)
+        case None => recent(0) match {
+            case null => None
+            case x => Some(x)
+          }
+      }
+    }
+    locateNearestContextTree(contexts, pos, new Array[ContextTree](1)) map (_.context)
+  }
+
+  def locateContextTree(contexts: Contexts, pos: Position): Option[ContextTree] = {
+    if (contexts.isEmpty) None
+    else {
+      val hi = contexts.length - 1
+      if ((contexts(hi).pos properlyPrecedes pos) || (pos properlyPrecedes contexts(0).pos)) None
+      else {
+        def loop(lo: Int, hi: Int): Option[ContextTree] = {
+          val mid = (lo + hi) / 2
+          val midpos = contexts(mid).pos
+          if ((pos precedes midpos) && (mid < hi))
+            loop(lo, mid)
+          else if ((midpos precedes pos) && (lo < mid))
+            loop(mid, hi)
+          else if (midpos includes pos) 
+            Some(contexts(mid))
+          else if (contexts(mid+1).pos includes pos)
+            Some(contexts(mid+1))
+          else None
+        }
+        loop(0, hi)
+      }
+    }
+  }
+
+  /** Insert a context at correct position into a buffer of context trees.
+   *  If the `context` has a transparent position, add it multiple times
+   *  at the positions of all its solid descendant trees.
+   */
+  def addContext(contexts: Contexts, context: Context): Unit = {
+    val cpos = context.tree.pos
+    if (cpos.isTransparent)
+      for (t <- context.tree.children flatMap solidDescendants)
+        addContext(contexts, context, t.pos)
+    else
+      addContext(contexts, context, cpos)
+  }
+
+  /** Insert a context with non-transparent position `cpos`
+   *  at correct position into a buffer of context trees.
+   */
+  def addContext(contexts: Contexts, context: Context, cpos: Position): Unit = synchronized {
+    try {
+      if (!cpos.isRange) {}
+      else if (contexts.isEmpty) contexts += new ContextTree(cpos, context)
+      else {
+        val hi = contexts.length - 1
+        if (contexts(hi).pos precedes cpos)
+          contexts += new ContextTree(cpos, context)
+        else if (contexts(hi).pos properlyIncludes cpos) // fast path w/o search
+          addContext(contexts(hi).children, context, cpos)
+        else if (cpos precedes contexts(0).pos)
+          new ContextTree(cpos, context) +=: contexts
+        else {
+          def insertAt(idx: Int): Boolean = {
+            val oldpos = contexts(idx).pos
+            if (oldpos sameRange cpos) {
+              contexts(idx) = new ContextTree(cpos, context, contexts(idx).children)
+              true
+            } else if (oldpos includes cpos) {
+              addContext(contexts(idx).children, context, cpos)
+              true
+            } else if (cpos includes oldpos) {
+              val start = contexts.indexWhere(cpos includes _.pos)
+              val last = contexts.lastIndexWhere(cpos includes _.pos)
+              contexts(start) = new ContextTree(cpos, context, contexts.slice(start, last + 1))
+              contexts.remove(start + 1, last - start)
+              true
+            } else false
+          }
+          def loop(lo: Int, hi: Int) {
+            if (hi - lo > 1) {
+              val mid = (lo + hi) / 2
+              val midpos = contexts(mid).pos
+              if (cpos precedes midpos)
+                loop(lo, mid)
+              else if (midpos precedes cpos) 
+                loop(mid, hi)
+              else
+                addContext(contexts(mid).children, context, cpos)
+            } else if (!insertAt(lo) && !insertAt(hi)) {
+              val lopos = contexts(lo).pos
+              val hipos = contexts(hi).pos
+              if ((lopos precedes cpos) && (cpos precedes hipos))
+                contexts.insert(hi, new ContextTree(cpos, context))
+              else 
+                inform("internal error? skewed positions: "+lopos+" !< "+cpos+" !< "+hipos)
+            }
+          }
+          loop(0, hi)
+        }
+      }
+    } catch {
+      case ex: Throwable =>
+        println(ex)
+        ex.printStackTrace()
+        println("failure inserting "+cpos+" into "+contexts+"/"+contexts(contexts.length - 1).pos+"/"+
+                (contexts(contexts.length - 1).pos includes cpos))
+        throw ex
+    }
+  }
+}
+        
diff --git a/src/compiler/scala/tools/nsc/interactive/Global.scala b/src/compiler/scala/tools/nsc/interactive/Global.scala
new file mode 100644
index 0000000..797586e
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/interactive/Global.scala
@@ -0,0 +1,627 @@
+package scala.tools.nsc
+package interactive
+
+import java.io.{ PrintWriter, StringWriter }
+
+import scala.collection.mutable
+import mutable.{LinkedHashMap, SynchronizedMap,LinkedHashSet, SynchronizedSet}
+import scala.concurrent.SyncVar
+import scala.util.control.ControlThrowable
+import scala.tools.nsc.io.AbstractFile
+import scala.tools.nsc.util.{SourceFile, Position, RangePosition, NoPosition, WorkScheduler}
+import scala.tools.nsc.reporters._
+import scala.tools.nsc.symtab._
+import scala.tools.nsc.ast._
+
+/** The main class of the presentation compiler in an interactive environment such as an IDE
+ */
+class Global(settings: Settings, reporter: Reporter) 
+  extends scala.tools.nsc.Global(settings, reporter) 
+     with CompilerControl 
+     with RangePositions
+     with ContextTrees 
+     with RichCompilationUnits { 
+self =>
+
+  import definitions._
+
+  val debugIDE = false
+
+  override def onlyPresentation = true
+
+  /** A list indicating in which order some units should be typechecked.
+   *  All units in firsts are typechecked before any unit not in this list
+   *  Modified by askToDoFirst, reload, typeAtTree.
+   */
+  var firsts: List[SourceFile] = List()
+
+  /** A map of all loaded files to the rich compilation units that correspond to them.
+   */ 
+  val unitOfFile = new LinkedHashMap[AbstractFile, RichCompilationUnit] with
+                       SynchronizedMap[AbstractFile, RichCompilationUnit]
+
+  /** The currently active typer run */
+  private var currentTyperRun: TyperRun = _
+
+  /** Is a background compiler run needed?
+   *  Note: outOfDate is true as long as there is a backgroud compile scheduled or going on.
+   */
+  private var outOfDate = false
+
+  /** Units compiled by a run with id >= minRunId are considered up-to-date  */
+  private[interactive] var minRunId = 1
+
+  private val NoResponse: Response[_] = new Response[Any]
+  private var pendingResponse: Response[_] = NoResponse 
+
+  /** Is a reload/background compiler currently running? */
+  private var acting = false
+
+  // ----------- Overriding hooks in nsc.Global -----------------------
+  
+  /** Called from typechecker, which signal hereby that a node has been completely typechecked.
+   *  If the node is included in unit.targetPos, abandons run and returns newly attributed tree.
+   *  Otherwise, if there's some higher priority work to be done, also abandons run with a FreshRunReq.
+   *  @param  context  The context that typechecked the node
+   *  @param  old      The original node
+   *  @param  result   The transformed node
+   */
+  override def signalDone(context: Context, old: Tree, result: Tree) {
+    def integrateNew() {
+      context.unit.body = new TreeReplacer(old, result) transform context.unit.body
+    }
+    if (activeLocks == 0) {
+      if (context.unit != null && 
+          result.pos.isOpaqueRange && 
+          (result.pos includes context.unit.targetPos)) {
+        integrateNew()
+        var located = new Locator(context.unit.targetPos) locateIn result
+        if (located == EmptyTree) {
+          println("something's wrong: no "+context.unit+" in "+result+result.pos)
+          located = result
+        }
+        throw new TyperResult(located)
+      }
+      val typerRun = currentTyperRun
+      
+      while(true) 
+        try {
+          try {
+            pollForWork()
+	  } catch {
+            case ex : Throwable =>
+	      if (context.unit != null) integrateNew()
+              throw ex
+	  }
+          if (typerRun == currentTyperRun)
+            return
+         
+          // @Martin
+          // Guard against NPEs in integrateNew if context.unit == null here.
+          // But why are we doing this at all? If it was non-null previously
+          // integrateNew will already have been called. If it was null previously
+          // it will still be null now?
+          if (context.unit != null)          
+            integrateNew()
+          throw FreshRunReq
+        }
+        catch {
+          case ex : ValidateException => // Ignore, this will have been reported elsewhere
+        }
+    }
+  }
+
+  /** Called from typechecker every time a context is created.
+   *  Registers the context in a context tree
+   */
+  override def registerContext(c: Context) = c.unit match {
+    case u: RichCompilationUnit => addContext(u.contexts, c)
+    case _ =>
+  }
+
+  /** The top level classes and objects currently seen in the presentation compiler
+   */
+  private val currentTopLevelSyms = new mutable.LinkedHashSet[Symbol]
+
+  /** The top level classes and objects no longer seen in the presentation compiler
+   */
+  val deletedTopLevelSyms = new mutable.LinkedHashSet[Symbol] with mutable.SynchronizedSet[Symbol]
+
+  /** Called from typechecker every time a top-level class or object is entered.
+   */
+  override def registerTopLevelSym(sym: Symbol) { currentTopLevelSyms += sym }
+
+  // ----------------- Polling ---------------------------------------
+
+  /** Called from runner thread and signalDone:
+   *  Poll for interrupts and execute them immediately.
+   *  Then, poll for exceptions and execute them. 
+   *  Then, poll for work reload/typedTreeAt/doFirst commands during background checking.
+   */
+  def pollForWork() {
+    scheduler.pollInterrupt() match {
+      case Some(ir) =>
+        ir.execute(); pollForWork()
+      case _ =>
+    }
+    if (pendingResponse.isCancelled)
+      throw CancelException
+    scheduler.pollThrowable() match {
+      case Some(ex @ FreshRunReq) => 
+        currentTyperRun = newTyperRun
+        minRunId = currentRunId
+        if (outOfDate) throw ex 
+        else outOfDate = true
+      case Some(ex: Throwable) => throw ex
+      case _ =>
+    }
+    scheduler.nextWorkItem() match {
+      case Some(action) =>
+        try {
+          acting = true
+          if (debugIDE) println("picked up work item: "+action)
+          action()
+          if (debugIDE) println("done with work item: "+action)
+        } finally {
+          if (debugIDE) println("quitting work item: "+action)
+          acting = false
+        }
+      case None =>
+    }
+  }    
+
+  def debugInfo(source : SourceFile, start : Int, length : Int): String = {
+    println("DEBUG INFO "+source+"/"+start+"/"+length)
+    val end = start+length
+    val pos = rangePos(source, start, start, end)
+
+    val tree = locateTree(pos)
+    val sw = new StringWriter
+    val pw = new PrintWriter(sw)
+    newTreePrinter(pw).print(tree)
+    pw.flush
+    
+    val typed = new Response[Tree]
+    askTypeAt(pos, typed)
+    val typ = typed.get.left.toOption match {
+      case Some(tree) =>
+        val sw = new StringWriter
+        val pw = new PrintWriter(sw)
+        newTreePrinter(pw).print(tree)
+        pw.flush
+        sw.toString
+      case None => "<None>"      
+    }
+
+    val completionResponse = new Response[List[Member]]
+    askTypeCompletion(pos, completionResponse)
+    val completion = completionResponse.get.left.toOption match {
+      case Some(members) =>
+        members mkString "\n"
+      case None => "<None>"      
+    }
+    
+    source.content.view.drop(start).take(length).mkString+" : "+source.path+" ("+start+", "+end+
+    ")\n\nlocateTree:\n"+sw.toString+"\n\naskTypeAt:\n"+typ+"\n\ncompletion:\n"+completion
+  }
+
+  // ----------------- The Background Runner Thread -----------------------
+
+  /** The current presentation compiler runner */
+  private var compileRunner = newRunnerThread
+
+  private var threadId = 1
+
+  /** Create a new presentation compiler runner.
+   */
+  def newRunnerThread: Thread = new Thread("Scala Presentation Compiler V"+threadId) {
+    override def run() {
+      try {
+        while (true) {
+          scheduler.waitForMoreWork()
+          pollForWork()
+          while (outOfDate) {
+            try {
+              backgroundCompile()
+              outOfDate = false
+            } catch {
+              case FreshRunReq => 
+            }
+          }
+        }
+      } catch {
+        case ShutdownReq => 
+          ;
+        case ex => 
+          outOfDate = false
+          compileRunner = newRunnerThread
+          ex match {
+            case FreshRunReq =>   // This shouldn't be reported
+            case _ : ValidateException => // This will have been reported elsewhere
+            case _ => ex.printStackTrace(); inform("Fatal Error: "+ex)
+          }
+      }
+    }
+    threadId += 1
+    start()
+  }
+
+  /** Compile all given units
+   */ 
+  private def backgroundCompile() {
+    if (debugIDE) inform("Starting new presentation compiler type checking pass")
+    reporter.reset
+
+    // remove any files in first that are no longer maintained by presentation compiler (i.e. closed)
+    firsts = firsts filter (s => unitOfFile contains (s.file))
+
+    val prefix = firsts map unitOf
+
+    val units = prefix ::: (unitOfFile.values.toList diff prefix) filter (!_.isUpToDate)
+
+    recompile(units)
+
+    if (debugIDE) inform("Everything is now up to date")
+  }
+
+  /** Reset unit to just-parsed state */
+  def reset(unit: RichCompilationUnit): Unit =
+    if (unit.status > JustParsed) {
+      unit.depends.clear()
+      unit.defined.clear()
+      unit.synthetics.clear()
+      unit.toCheck.clear()
+      unit.targetPos = NoPosition
+      unit.contexts.clear()
+      unit.body = EmptyTree
+      unit.status = NotLoaded
+    }
+
+  /** Parse unit and create a name index. */
+  def parse(unit: RichCompilationUnit): Unit = {
+    currentTyperRun.compileLate(unit)
+    if (!reporter.hasErrors) validatePositions(unit.body)
+    //println("parsed: [["+unit.body+"]]")
+    unit.status = JustParsed
+  }
+
+  /** Make sure symbol and type attributes are reset and recompile units. 
+   */
+  def recompile(units: List[RichCompilationUnit]) {
+    for (unit <- units) {
+      reset(unit)
+      if (debugIDE) inform("parsing: "+unit)
+      parse(unit)
+    }
+    for (unit <- units) {
+      if (debugIDE) inform("type checking: "+unit)
+      activeLocks = 0
+      currentTyperRun.typeCheck(unit)
+      unit.status = currentRunId
+      if (!unit.isJava) syncTopLevelSyms(unit)
+    }
+  }
+
+  def syncTopLevelSyms(unit: RichCompilationUnit) {
+    val deleted = currentTopLevelSyms filter { sym =>
+      sym.sourceFile == unit.source.file && runId(sym.validTo) < currentRunId 
+    }
+    for (d <- deleted) {
+      d.owner.info.decls unlink d
+      deletedTopLevelSyms += d
+      currentTopLevelSyms -= d
+    }
+  }
+      
+  /** Move list of files to front of firsts */
+  def moveToFront(fs: List[SourceFile]) {
+    firsts = fs ::: (firsts diff fs)
+  }
+
+  // ----------------- Implementations of client commands -----------------------
+  
+  def respond[T](result: Response[T])(op: => T): Unit = 
+    respondGradually(result)(Stream(op))
+
+  def respondGradually[T](response: Response[T])(op: => Stream[T]): Unit = {
+    val prevResponse = pendingResponse
+    try {
+      pendingResponse = response
+      if (!response.isCancelled) {
+        var results = op
+        while (!response.isCancelled && results.nonEmpty) {
+          val result = results.head
+          results = results.tail
+          if (results.isEmpty) response set result
+          else response setProvisionally result
+        }
+      }
+    } catch {
+      case CancelException =>
+        ;
+      case ex @ FreshRunReq =>
+        scheduler.postWorkItem(() => respondGradually(response)(op))
+        throw ex
+      case ex =>
+        response raise ex
+        throw ex
+    } finally {
+      pendingResponse = prevResponse
+    }
+  }
+
+  /** Make sure a set of compilation units is loaded and parsed */
+  def reloadSources(sources: List[SourceFile]) {
+    currentTyperRun = newTyperRun
+    for (source <- sources) {
+      val unit = new RichCompilationUnit(source)
+      unitOfFile(source.file) = unit
+      parse(unit)
+    }
+    moveToFront(sources)
+  }
+
+  /** Make sure a set of compilation units is loaded and parsed */
+  def reload(sources: List[SourceFile], response: Response[Unit]) {
+    respond(response)(reloadSources(sources))
+    if (outOfDate) throw FreshRunReq // cancel background compile
+    else outOfDate = true            // proceed normally and enable new background compile
+  }
+
+  /** A fully attributed tree located at position `pos`  */
+  def typedTreeAt(pos: Position): Tree = {
+    val unit = unitOf(pos)
+    val sources = List(unit.source)
+    if (unit.status == NotLoaded) reloadSources(sources)
+    moveToFront(sources)
+    val typedTree = currentTyperRun.typedTreeAt(pos)
+    new Locator(pos) locateIn typedTree
+  }
+
+  /** A fully attributed tree corresponding to the entire compilation unit  */
+  def typedTree(source: SourceFile, forceReload: Boolean): Tree = {
+    val unit = unitOf(source)
+    val sources = List(source)
+    if (unit.status == NotLoaded || forceReload) reloadSources(sources)
+    moveToFront(sources)
+    currentTyperRun.typedTree(unitOf(source))
+  }
+
+  /** Set sync var `response` to a fully attributed tree located at position `pos`  */
+  def getTypedTreeAt(pos: Position, response: Response[Tree]) {
+    respond(response)(typedTreeAt(pos))
+  }
+
+  /** Set sync var `response` to a fully attributed tree corresponding to the entire compilation unit  */
+  def getTypedTree(source : SourceFile, forceReload: Boolean, response: Response[Tree]) {
+    respond(response)(typedTree(source, forceReload))
+  }
+
+  def stabilizedType(tree: Tree): Type = tree match {
+    case Ident(_) if tree.symbol.isStable => singleType(NoPrefix, tree.symbol)
+    case Select(qual, _) if qual.tpe != null && tree.symbol.isStable => singleType(qual.tpe, tree.symbol)
+    case Import(expr, selectors) =>
+      tree.symbol.info match {
+        case analyzer.ImportType(expr) => expr match {
+          case s at Select(qual, name) => singleType(qual.tpe, s.symbol)
+          case i : Ident => i.tpe
+          case _ => tree.tpe
+        }
+        case _ => tree.tpe
+      }
+    
+    case _ => tree.tpe
+  }
+
+  import analyzer.{SearchResult, ImplicitSearch}
+
+  def getScopeCompletion(pos: Position, response: Response[List[Member]]) {
+    respond(response) { scopeMembers(pos) }
+  }
+
+  val Dollar = newTermName("$")
+
+  /** Return all members visible without prefix in context enclosing `pos`. */
+  def scopeMembers(pos: Position): List[ScopeMember] = {
+    typedTreeAt(pos) // to make sure context is entered
+    val context = doLocateContext(pos)
+    val locals = new LinkedHashMap[Name, ScopeMember]
+    def addScopeMember(sym: Symbol, pre: Type, viaImport: Tree) =
+      if (!sym.name.decode.containsName(Dollar) &&  
+          !sym.hasFlag(Flags.SYNTHETIC) &&
+          !locals.contains(sym.name)) {
+        //println("adding scope member: "+pre+" "+sym)
+        locals(sym.name) = new ScopeMember(
+          sym, 
+          pre.memberType(sym), 
+          context.isAccessible(sym, pre, false),
+          viaImport)
+      }
+    var cx = context
+    while (cx != NoContext) {
+      for (sym <- cx.scope)
+        addScopeMember(sym, NoPrefix, EmptyTree)
+      if (cx == cx.enclClass) {
+	val pre = cx.prefix
+	for (sym <- pre.members) 
+	  addScopeMember(sym, pre, EmptyTree)
+      }
+      cx = cx.outer
+    }
+
+    for (imp <- context.imports) {
+      val pre = imp.qual.tpe
+      for (sym <- imp.allImportedSymbols) {
+        addScopeMember(sym, pre, imp.qual)
+      }
+    }
+    val result = locals.values.toList
+    if (debugIDE) for (m <- result) println(m)
+    result
+  }
+
+  def getTypeCompletion(pos: Position, response: Response[List[Member]]) {
+    respondGradually(response) { typeMembers(pos) }
+    if (debugIDE) scopeMembers(pos)
+  }
+
+  def typeMembers(pos: Position): Stream[List[TypeMember]] = {
+    var tree = typedTreeAt(pos)
+
+    // Let's say you have something like val x: List[Int] and ypu want to get completion after List
+    // Then the tree found at first is a TypeTree, ????
+    tree match {
+      case tt : TypeTree if tt.original != null => tree = tt.original // ??? 
+      case _ => 
+    }
+
+    // if tree consists of just x. or x.fo where fo is not yet a full member name
+    // ignore the selection and look in just x.
+    tree match {
+      case Select(qual, name) if tree.tpe == ErrorType => tree = qual
+      case _ => 
+    }
+
+    val context = doLocateContext(pos)
+
+    if (tree.tpe == null)
+      tree = analyzer.newTyper(context).typedQualifier(tree)
+      
+    println("typeMembers at "+tree+" "+tree.tpe)
+
+    val superAccess = tree.isInstanceOf[Super]
+    val scope = new Scope
+    val members = new LinkedHashMap[Symbol, TypeMember]
+
+    def addTypeMember(sym: Symbol, pre: Type, inherited: Boolean, viaView: Symbol) {
+      val symtpe = pre.memberType(sym)
+      if (scope.lookupAll(sym.name) forall (sym => !(members(sym).tpe matches symtpe))) {
+        scope enter sym
+        members(sym) = new TypeMember(
+          sym,
+          symtpe,
+          context.isAccessible(sym, pre, superAccess && (viaView == NoSymbol)),
+          inherited,
+          viaView)
+      }
+    }        
+
+    /** Create a fucntion application of  a given view function to `tree` and typechecked it.
+     */
+    def viewApply(view: SearchResult): Tree = {
+      assert(view.tree != EmptyTree)
+      try {
+        analyzer.newTyper(context.makeImplicit(reportAmbiguousErrors = false))
+          .typed(Apply(view.tree, List(tree)) setPos tree.pos)
+      } catch {
+        case ex: TypeError => EmptyTree
+      }
+    }
+
+    val pre = stabilizedType(tree)
+    val ownerTpe = if (tree.tpe != null) tree.tpe else pre
+
+    for (sym <- ownerTpe.decls)
+      addTypeMember(sym, pre, false, NoSymbol)
+    members.values.toList #:: {
+      for (sym <- ownerTpe.members)
+        addTypeMember(sym, pre, true, NoSymbol)
+      members.values.toList #:: {
+        val applicableViews: List[SearchResult] = 
+          new ImplicitSearch(tree, functionType(List(ownerTpe), AnyClass.tpe), isView = true, context.makeImplicit(reportAmbiguousErrors = false))
+            .allImplicits
+        for (view <- applicableViews) {
+          val vtree = viewApply(view)
+          val vpre = stabilizedType(vtree)
+          for (sym <- vtree.tpe.members) {
+            addTypeMember(sym, vpre, false, view.tree.symbol)
+          }
+        }
+        Stream(members.values.toList)
+      }
+    }
+  }
+
+  // ---------------- Helper classes ---------------------------
+
+  /** A transformer that replaces tree `from` with tree `to` in a given tree */
+  class TreeReplacer(from: Tree, to: Tree) extends Transformer {
+    override def transform(t: Tree): Tree = {
+      if (t == from) to
+      else if ((t.pos includes from.pos) || t.pos.isTransparent) super.transform(t)
+      else t
+    }
+  }
+
+  /** The typer run */
+  class TyperRun extends Run {
+    // units is always empty
+
+    /** canRedefine is used to detect double declarations in multiple source files.
+     *  Since the IDE rechecks units several times in the same run, these tests
+     *  are disabled by always returning true here.
+     */
+    override def canRedefine(sym: Symbol) = true
+
+    def typeCheck(unit: CompilationUnit): Unit = {
+      applyPhase(typerPhase, unit)
+    }
+
+    def enterNames(unit: CompilationUnit): Unit = {
+      applyPhase(namerPhase, unit)
+    }
+
+    /** Return fully attributed tree at given position
+     *  (i.e. largest tree that's contained by position)
+     */
+    def typedTreeAt(pos: Position): Tree = {
+      println("starting typedTreeAt")
+      val tree = locateTree(pos)
+      println("at pos "+pos+" was found: "+tree+tree.pos.show)
+      if (stabilizedType(tree) ne null) {
+        println("already attributed")
+        tree
+      } else {
+        val unit = unitOf(pos)
+        assert(unit.isParsed)
+        unit.targetPos = pos
+        try {
+          println("starting targeted type check")
+          typeCheck(unit)
+          throw new FatalError("tree not found")
+        } catch {
+          case ex: TyperResult => 
+            ex.tree
+        } finally {
+          unit.targetPos = NoPosition
+        }
+      }
+    } 
+
+    def typedTree(unit: RichCompilationUnit): Tree = {
+      assert(unit.isParsed)
+      unit.targetPos = NoPosition
+      typeCheck(unit)
+      unit.body
+    } 
+
+    /** Apply a phase to a compilation unit
+     *  @return true iff typechecked correctly
+     */
+    private def applyPhase(phase: Phase, unit: CompilationUnit) {
+      val oldSource = reporter.getSource          
+      reporter.withSource(unit.source) {
+        atPhase(phase) { phase.asInstanceOf[GlobalPhase] applyPhase unit }
+      }
+    }
+  }
+  
+  def newTyperRun = new TyperRun
+
+  class TyperResult(val tree: Tree) extends ControlThrowable
+  
+  assert(globalPhase.id == 0)
+}
+
+object CancelException extends Exception
+
diff --git a/src/compiler/scala/tools/nsc/interactive/REPL.scala b/src/compiler/scala/tools/nsc/interactive/REPL.scala
new file mode 100644
index 0000000..014acb5
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/interactive/REPL.scala
@@ -0,0 +1,128 @@
+package scala.tools.nsc
+package interactive
+
+import scala.concurrent.SyncVar
+import scala.tools.nsc.util._
+import scala.tools.nsc.symtab._
+import scala.tools.nsc.ast._
+import scala.tools.nsc.reporters._
+import scala.tools.nsc.io._
+
+/** Interface of interactive compiler to a client such as an IDE
+ */
+object REPL {
+
+  val versionMsg = "Scala compiler " +
+    Properties.versionString + " -- " +
+    Properties.copyrightString
+
+  val prompt = "> "
+
+  var reporter: ConsoleReporter = _
+
+  def error(msg: String) {
+    reporter.error(/*new Position */FakePos("scalac"),
+                   msg + "\n  scalac -help  gives more information")
+  }
+
+  def process(args: Array[String]) {
+    val settings = new Settings(error)
+    reporter = new ConsoleReporter(settings)
+    val command = new CompilerCommand(args.toList, settings)
+    if (command.settings.version.value)
+      reporter.info(null, versionMsg, true)
+    else {
+      try {
+        object compiler extends Global(command.settings, reporter) {
+//          printTypings = true
+        } 
+        if (reporter.hasErrors) {
+          reporter.flush()
+          return
+        }
+        if (command.shouldStopWithInfo) {
+          reporter.info(null, command.getInfoMessage(compiler), true)
+        } else {
+          run(compiler)
+        }
+      } catch {
+        case ex @ FatalError(msg) =>
+          if (true || command.settings.debug.value) // !!!
+            ex.printStackTrace();
+        reporter.error(null, "fatal error: " + msg)
+      }
+    }
+  }
+
+  def main(args: Array[String]) {
+    process(args)
+    exit(if (reporter.hasErrors) 1 else 0)
+  }
+
+  def loop(action: (String) => Unit) {
+    Console.print(prompt)
+    try {
+      val line = Console.readLine
+      if (line.length() > 0) {
+        action(line)
+      }
+      loop(action)
+    }
+    catch {
+      case _: java.io.EOFException => //nop
+    }
+  }
+
+  /** Commands:
+   *
+   *  reload file1 ... fileN
+   *  typeat file off1 off2?
+   *  complete file off1 off2?
+   */
+  def run(comp: Global) {
+    val reloadResult = new Response[Unit]
+    val typeatResult = new Response[comp.Tree]
+    val completeResult = new Response[List[comp.Member]]
+    def makePos(file: String, off1: String, off2: String) = {
+      val source = toSourceFile(file)
+      comp.rangePos(source, off1.toInt, off1.toInt, off2.toInt)
+    }
+    def doTypeAt(pos: Position) {
+      comp.askTypeAt(pos, typeatResult)
+      show(typeatResult)
+    }
+    def doComplete(pos: Position) {
+      comp.askTypeCompletion(pos, completeResult)
+      show(completeResult)
+    }
+    loop { line =>
+      (line split " ").toList match {
+        case "reload" :: args => 
+          comp.askReload(args map toSourceFile, reloadResult)
+          show(reloadResult)
+        case List("typeat", file, off1, off2) =>
+          doTypeAt(makePos(file, off1, off2))
+        case List("typeat", file, off1) =>
+          doTypeAt(makePos(file, off1, off1))
+        case List("complete", file, off1, off2) =>
+          doComplete(makePos(file, off1, off2))
+        case List("complete", file, off1) =>
+          doComplete(makePos(file, off1, off1))
+        case List("quit") =>
+          System.exit(1)
+        case _ =>
+          println("unrecongized command")
+      }
+    }
+  }
+
+  def toSourceFile(name: String) = new BatchSourceFile(new PlainFile(new java.io.File(name)))
+
+  def show[T](svar: Response[T]) {
+    svar.get match {
+      case Left(result) => println("==> "+result)
+      case Right(exc) => exc.printStackTrace; println("ERROR: "+exc)
+    }
+    svar.clear()
+  }
+}
diff --git a/src/compiler/scala/tools/nsc/interactive/RangePositions.scala b/src/compiler/scala/tools/nsc/interactive/RangePositions.scala
new file mode 100644
index 0000000..52d2b63
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/interactive/RangePositions.scala
@@ -0,0 +1,270 @@
+package scala.tools.nsc
+package interactive
+
+import ast.Trees
+import symtab.Positions
+import scala.tools.nsc.util.{SourceFile, Position, RangePosition, NoPosition, WorkScheduler}
+import scala.collection.mutable.ListBuffer
+
+/** Handling range positions
+ *  atPos, the main method in this trait, will add positions to a tree,
+ *  and will ensure the following properties:
+ *
+ *    1. All nodes between the root of the tree and nodes that already have positions
+ *       will be assigned positions.
+ *    2. No node which already has a position will be assigned a different range; however
+ *       a RangePosition might become a TransparentPosition.
+ *    3. The position of each assigned node includes the positions of each of its children.
+ *    4. The positions of all solid descendants of children of an assigned node
+ *       are mutually non-overlapping.
+ *
+ * Here, the solid descendant of a node are:
+ *
+ *   If the node has a TransparentPosition, the solid descendants of all its children
+ *   Otherwise, the singleton consisting of the node itself.
+ */
+trait RangePositions extends Trees with Positions { 
+self: scala.tools.nsc.Global =>
+
+  case class Range(pos: Position, tree: Tree) {
+    def isFree = tree == EmptyTree
+  }
+
+  override def rangePos(source: SourceFile, start: Int, point: Int, end: Int) = 
+    new RangePosition(source, start, point, end)
+
+  /** A position that wraps a set of trees.
+   *  The point of the wrapping position is the point of the default position.
+   *  If some of the trees are ranges, returns a range position enclosing all ranges
+   *  Otherwise returns default position.
+   */
+  override def wrappingPos(default: Position, trees: List[Tree]): Position = {
+    val ranged = trees filter (_.pos.isRange)
+    if (ranged.isEmpty) default.focus
+    else new RangePosition(default.source, (ranged map (_.pos.start)).min, default.point, (ranged map (_.pos.end)).max)
+  }
+
+  /** A position that wraps a non-empty set of trees.
+   *  The point of the wrapping position is the point of the first trees' position.
+   *  If some of the trees are ranges, returns a range position enclosing all ranges
+   *  Otherwise returns first tree's position.
+   */
+  override def wrappingPos(trees: List[Tree]): Position = {
+    val headpos = trees.head.pos
+    if (headpos.isDefined) wrappingPos(headpos, trees) else headpos
+  }
+
+/*
+  override def integratePos(tree: Tree, pos: Position) = 
+    if (pos.isSynthetic && !tree.pos.isSynthetic) tree.syntheticDuplicate 
+    else tree
+*/
+
+  // -------------- ensuring no overlaps -------------------------------
+
+  def solidDescendants(tree: Tree): List[Tree] = 
+    if (tree.pos.isTransparent) tree.children flatMap solidDescendants 
+    else List(tree)
+
+  /** A free range from `lo` to `hi` */
+  private def free(lo: Int, hi: Int): Range = 
+    Range(new RangePosition(null, lo, lo, hi), EmptyTree)
+
+  /** The maximal free range */
+  private lazy val maxFree: Range = free(0, Int.MaxValue)
+
+  /** A singleton list of a non-empty range from `lo` to `hi`, or else the empty List */ 
+  private def maybeFree(lo: Int, hi: Int) = 
+    if (lo < hi) List(free(lo, hi)) 
+    else List()
+
+  /** Insert `pos` into ranges `rs` if possible;
+   *  otherwise add conflicting trees to `conflicting`.
+   */
+  private def insert(rs: List[Range], t: Tree, conflicting: ListBuffer[Tree]): List[Range] = rs match {
+    case List() =>
+      assert(conflicting.nonEmpty)
+      rs
+    case r :: rs1 =>
+      assert(!t.pos.isTransparent)
+      if (r.isFree && (r.pos includes t.pos)) {
+//      println("subdividing "+r+"/"+t.pos)
+        maybeFree(t.pos.end, r.pos.end) ::: List(Range(t.pos, t)) ::: maybeFree(r.pos.start, t.pos.start) ::: rs1
+      } else {
+        if (!r.isFree && (r.pos overlaps t.pos)) conflicting += r.tree 
+        r :: insert(rs1, t, conflicting)
+      }
+  }
+
+  /** Replace elem `t` of `ts` by `replacement` list. */
+  private def replace(ts: List[Tree], t: Tree, replacement: List[Tree]): List[Tree] = 
+    if (ts.head == t) replacement ::: ts.tail
+    else ts.head :: replace(ts.tail, t, replacement)
+
+  /** Ensure that given tree has no positions that overlap with
+   *  any of the positions of `others`. This is done by
+   *  shortening the range or assigning TransparentPositions
+   *  to some of the nodes in `tree`.
+   */
+  override def ensureNonOverlapping(tree: Tree, others: List[Tree]) {
+    def isOverlapping(pos: Position) = 
+      pos.isRange && (others exists (pos overlaps _.pos))
+    if (isOverlapping(tree.pos)) {
+      val children = tree.children
+      children foreach (ensureNonOverlapping(_, others))
+      if (tree.pos.isOpaqueRange) {
+        val wpos = wrappingPos(tree.pos.focus, children)
+        tree setPos (if (isOverlapping(wpos)) tree.pos.makeTransparent else wpos)
+      }
+    }
+  }
+
+  /** Does given list of trees have mutually non-overlapping positions?
+   *  pre: None of the trees is transparent
+   */
+  def findOverlapping(cts: List[Tree]): List[(Tree, Tree)] = {
+    var ranges = List(maxFree)
+    for (ct <- cts) {
+      if (ct.pos.isOpaqueRange) {
+        val conflicting = new ListBuffer[Tree]
+        ranges = insert(ranges, ct, conflicting)
+        if (conflicting.nonEmpty) return conflicting.toList map (t => (t, ct))
+      }
+    }
+    List()
+  }
+
+  // -------------- setting positions -------------------------------
+
+  /** Set position of all children of a node
+   *  @param  pos   A target position.
+   *                Uses the point of the position as the point of all positions it assigns.
+   *                Uses the start of this position as an Offset position for unpositioed trees
+   *                without children.
+   *  @param  trees  The children to position. All children must be positionable. 
+   */
+  private def setChildrenPos(pos: Position, trees: List[Tree]): Unit = try {
+    for (tree <- trees) {
+      if (!tree.isEmpty && tree.pos == NoPosition) {
+        val children = tree.children
+        if (children.isEmpty) {
+          tree setPos pos.focus
+        } else {
+          setChildrenPos(pos, children)
+          tree setPos wrappingPos(pos, children)
+        }
+      }
+    }
+  } catch {
+    case ex: Exception =>
+      println("error while set children pos "+pos+" of "+trees)
+      throw ex
+  }
+
+  /** Position a tree.
+   *  This means: Set position of a node and position all its unpositioned children.
+   */
+  override def atPos[T <: Tree](pos: Position)(tree: T): T =
+    if (pos.isOpaqueRange) {
+      if (!tree.isEmpty && tree.pos == NoPosition) {
+        tree.setPos(pos)
+        val children = tree.children
+        if (children.nonEmpty) {
+          if (children.tail.isEmpty) atPos(pos)(children.head)
+          else setChildrenPos(pos, children)
+        }
+      }
+      tree
+    } else {
+      super.atPos(pos)(tree)
+    }
+
+  // ---------------- Validating positions ----------------------------------
+
+  override def validatePositions(tree: Tree) {
+    def reportTree(prefix : String, tree : Tree) {
+      val source = if (tree.pos.isDefined) tree.pos.source else ""
+      inform("== "+prefix+" tree ["+tree.id+"] of type "+tree.productPrefix+" at "+tree.pos.show+source)
+      inform("")
+      inform(tree.toString)
+      inform("")
+    }
+    
+    def error(msg: String)(body : => Unit) {
+      inform("======= Bad positions: "+msg)
+      inform("")
+      body
+      inform("=== While validating")
+      inform("")
+      inform(tree.toString)
+      inform("")
+      inform("=======")
+      throw new ValidateException(msg)
+    }
+    
+    def validate(tree: Tree, encltree: Tree): Unit = {
+      if (!tree.isEmpty) {
+        if (!tree.pos.isDefined) 
+          error("Unpositioned tree ["+tree.id+"]") { reportTree("Unpositioned", tree) }
+        if (tree.pos.isRange) {
+          if (!encltree.pos.isRange)
+            error("Synthetic tree ["+encltree.id+"] contains nonsynthetic tree ["+tree.id+"]") {
+            reportTree("Enclosing", encltree)
+            reportTree("Enclosed", tree)
+            }
+          if (!(encltree.pos includes tree.pos))
+            error("Enclosing tree ["+encltree.id+"] does not include tree ["+tree.id+"]") {
+              reportTree("Enclosing", encltree)
+              reportTree("Enclosed", tree)
+            }
+          
+          findOverlapping(tree.children flatMap solidDescendants) match {
+            case List() => ;
+            case xs => {
+              error("Overlapping trees "+xs.map { case (x, y) => (x.id, y.id) }.mkString("", ", ", "")) {
+                reportTree("Ancestor", tree)
+                for((x, y) <- xs) {
+                  reportTree("First overlapping", x)
+                  reportTree("Second overlapping", y)
+                }
+              }
+            }
+          }
+        }
+        for (ct <- tree.children flatMap solidDescendants) validate(ct, tree)
+      }
+    }
+
+    validate(tree, tree)
+  }
+
+  class ValidateException(msg : String) extends Exception(msg)
+
+  // ---------------- Locating trees ----------------------------------
+
+  /** A locator for trees with given positions.
+   *  Given a position `pos`, locator.apply returns
+   *  the smallest tree that encloses `pos`.
+   */
+  class Locator(pos: Position) extends Traverser {
+    var last: Tree = _
+    def locateIn(root: Tree): Tree = {
+      this.last = EmptyTree
+      traverse(root)
+      this.last
+    }
+    override def traverse(t: Tree) {
+      if (t.pos includes pos) {
+        if (!t.pos.isTransparent) last = t
+        super.traverse(t)
+      } else if (t.symbol != null) {
+        for(annot <- t.symbol.annotations if (annot.pos includes pos) && !annot.pos.isTransparent) {
+          last = Annotated(TypeTree(annot.atp) setPos annot.pos, t)
+          last.setType(annot.atp)
+          last.setPos(annot.pos)
+          traverseTrees(annot.args)
+        }
+      }
+    }
+  }
+}
diff --git a/src/compiler/scala/tools/nsc/interactive/RefinedBuildManager.scala b/src/compiler/scala/tools/nsc/interactive/RefinedBuildManager.scala
new file mode 100644
index 0000000..3339c9c
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/interactive/RefinedBuildManager.scala
@@ -0,0 +1,351 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
+ * @author  Martin Odersky
+ */
+
+package scala.tools.nsc
+package interactive
+
+import scala.collection._
+import scala.tools.nsc.reporters.{Reporter, ConsoleReporter}
+import scala.util.control.Breaks._
+import scala.tools.nsc.symtab.Flags
+
+import dependencies._
+import util.FakePos
+import io.AbstractFile
+
+/** A more defined build manager, based on change sets. For each
+ *  updated source file, it computes the set of changes to its
+ *  definitions, then checks all dependent units to see if the
+ *  changes require a compilation. It repeats this process until
+ *  a fixpoint is reached.
+ */
+class RefinedBuildManager(val settings: Settings) extends Changes with BuildManager {
+
+  class BuilderGlobal(settings: Settings, reporter : Reporter) extends scala.tools.nsc.Global(settings, reporter)  {
+    
+    def this(settings: Settings) =
+      this(settings, new ConsoleReporter(settings))
+
+    override def computeInternalPhases() {
+      super.computeInternalPhases
+      phasesSet += dependencyAnalysis
+    }
+    
+    def newRun() = new Run()
+  }
+
+  protected def newCompiler(settings: Settings) = new BuilderGlobal(settings) 
+  
+  val compiler = newCompiler(settings)
+  import compiler.{Symbol, Type, atPhase, currentRun}
+  import compiler.dependencyAnalysis.Inherited
+  
+  private case class SymWithHistory(sym: Symbol, befErasure: Type)
+
+  /** Managed source files. */
+  private val sources: mutable.Set[AbstractFile] = new mutable.HashSet[AbstractFile]
+
+  private val definitions: mutable.Map[AbstractFile, List[SymWithHistory]] = 
+    new mutable.HashMap[AbstractFile, List[SymWithHistory]] {
+      override def default(key: AbstractFile) = Nil
+    }
+
+  /** External references used by source file. */
+  private var references: mutable.Map[AbstractFile, immutable.Set[String]] = _
+  
+  /** External references for inherited members */
+  private var inherited: mutable.Map[AbstractFile, immutable.Set[Inherited]] = _
+  
+  /** Reverse of definitions, used for caching */
+  private var classes: mutable.Map[String, AbstractFile] = 
+    new mutable.HashMap[String, AbstractFile] {
+      override def default(key: String) = null
+  }
+
+  /** Add the given source files to the managed build process. */
+  def addSourceFiles(files: Set[AbstractFile]) {
+    sources ++= files
+    update(files)
+  }
+
+  /** Remove the given files from the managed build process. */
+  def removeFiles(files: Set[AbstractFile]) {
+    sources --= files
+    deleteClassfiles(files)
+    update(invalidatedByRemove(files))
+  }
+
+  /** Return the set of invalidated files caused by removing the given files.
+   */
+  private def invalidatedByRemove(files: Set[AbstractFile]): Set[AbstractFile] = {
+    val changes = new mutable.HashMap[Symbol, List[Change]]
+    for (f <- files; SymWithHistory(sym, _) <- definitions(f))
+      changes += sym -> List(Removed(Class(sym.fullName)))
+    invalidated(files, changes)
+  }
+
+  def update(added: Set[AbstractFile], removed: Set[AbstractFile]) {
+    sources --= removed
+    deleteClassfiles(removed)
+    update(added ++ invalidatedByRemove(removed))
+  }
+
+  /** The given files have been modified by the user. Recompile
+   *  them and all files that depend on them. Only files that
+   *  have been previously added as source files are recompiled.
+   *  Files that were already compiled are taken out from the result
+   *  of the dependency analysis.
+   */
+  private def update(files: Set[AbstractFile]) = {
+    val coll: mutable.Map[AbstractFile, immutable.Set[AbstractFile]] =
+        mutable.HashMap[AbstractFile, immutable.Set[AbstractFile]]()
+    compiler.reporter.reset
+        
+    // See if we really have corresponding symbols, not just those
+    // which share the name
+    def isCorrespondingSym(from: Symbol, to: Symbol): Boolean =
+      (from.hasFlag(Flags.TRAIT) == to.hasFlag(Flags.TRAIT)) &&
+      (from.hasFlag(Flags.MODULE) == to.hasFlag(Flags.MODULE))
+      
+    // For testing purposes only, order irrelevant for compilation
+    def toStringSet(set: Set[AbstractFile]): String =
+      set.toList sortBy (_.name) mkString("Set(", ", ", ")")
+
+    def update0(files: Set[AbstractFile]): Unit = if (!files.isEmpty) {
+      deleteClassfiles(files)
+      val run = compiler.newRun()
+      if (settings.Ybuildmanagerdebug.value)
+        compiler.inform("compiling " + toStringSet(files))
+      buildingFiles(files)
+
+      run.compileFiles(files.toList)
+      if (compiler.reporter.hasErrors) {
+        return
+      }
+
+      // Deterministic behaviour required by partest
+      val changesOf = new mutable.HashMap[Symbol, List[Change]] {
+          override def toString: String = {
+            val changesOrdered =
+              toList.map(e => {
+                e._1.toString + " -> " +
+                e._2.sortBy(_.toString).mkString("List(", ", ", ")")
+              })
+            changesOrdered.sorted.mkString("Map(", ", ", ")")
+          }
+      }
+      val additionalDefs: mutable.HashSet[AbstractFile] = mutable.HashSet.empty
+
+      val defs = compiler.dependencyAnalysis.definitions
+      for (src <- files) {
+        if (definitions(src).isEmpty)
+          additionalDefs ++= compiler.dependencyAnalysis.
+                             dependencies.dependentFiles(1, mutable.Set(src))
+        else {
+          val syms = defs(src)
+          for (sym <- syms) {
+            definitions(src).find(
+               s => (s.sym.fullName == sym.fullName) &&
+                    isCorrespondingSym(s.sym, sym)) match {
+              case Some(SymWithHistory(oldSym, info)) =>
+                val changes = changeSet(oldSym.info, sym)
+                val changesErasure =
+                    atPhase(currentRun.erasurePhase.prev) {
+                        changeSet(info, sym)
+                    }
+                changesOf(oldSym) = (changes ++ changesErasure).distinct 
+              case _ =>
+                // a new top level definition
+                changesOf(sym) =
+                    sym.info.parents.filter(_.typeSymbol hasFlag Flags.SEALED).map(
+                      p => changeChangeSet(p.typeSymbol,
+                                           sym+" extends a sealed "+p.typeSymbol))
+            }
+          }
+          // Create a change for the top level classes that were removed
+          val removed = definitions(src) filterNot ((s:SymWithHistory) =>
+            syms.find(_.fullName == (s.sym.fullName)) != None)
+          for (s <- removed) {
+            changesOf(s.sym) = List(removeChangeSet(s.sym))
+          }
+        }
+      }
+      if (settings.Ybuildmanagerdebug.value)
+        compiler.inform("Changes: " + changesOf)
+      updateDefinitions(files)
+      val invalid = invalidated(files, changesOf, additionalDefs)
+      update0(checkCycles(invalid, files, coll))
+    }
+
+    update0(files)
+  }
+
+  // Attempt to break the cycling reference deps as soon as possible and reduce
+  // the number of compilations to minimum without having too coarse grained rules
+  private def checkCycles(files: Set[AbstractFile], initial: Set[AbstractFile],
+                          collect: mutable.Map[AbstractFile, immutable.Set[AbstractFile]]):
+    Set[AbstractFile] = {
+      def followChain(set: Set[AbstractFile], rest: immutable.Set[AbstractFile]):
+        immutable.Set[AbstractFile] = {
+        val deps:Set[AbstractFile] = set.flatMap(
+              s => collect.get(s) match {
+                     case Some(x) => x
+                     case _ => Set[AbstractFile]()
+              })
+          val newDeps = deps -- rest
+          if (newDeps.isEmpty) rest else followChain(newDeps, rest ++ newDeps)
+      }
+      var res:Set[AbstractFile] = mutable.Set()
+      files.foreach( f => 
+        if (collect contains f) {
+          val chain = followChain(Set(f), immutable.Set()) ++ files
+          chain.foreach((fc: AbstractFile) => collect += fc -> chain)
+          res ++= chain
+        } else 
+          res += f
+       )
+
+      initial.foreach((f: AbstractFile) => collect += (f -> (collect.getOrElse(f, immutable.Set()) ++ res)))
+      if (res.subsetOf(initial)) Set() else res
+  }  
+  
+  /** Return the set of source files that are invalidated by the given changes. */
+  def invalidated(files: Set[AbstractFile], changesOf: collection.Map[Symbol, List[Change]],
+                  processed: Set[AbstractFile] = Set.empty):
+    Set[AbstractFile] = {
+    val buf = new mutable.HashSet[AbstractFile]
+    val newChangesOf = new mutable.HashMap[Symbol, List[Change]]
+    var directDeps = 
+      compiler.dependencyAnalysis.dependencies.dependentFiles(1, files)
+
+    def invalidate(file: AbstractFile, reason: String, change: Change) = {
+      if (settings.Ybuildmanagerdebug.value)
+        compiler.inform("invalidate " + file + " because " + reason + " [" + change + "]")
+      buf += file
+      directDeps -= file
+      for (syms <- definitions(file))     // fixes #2557
+        newChangesOf(syms.sym) = List(change, parentChangeSet(syms.sym))
+      break
+    }
+    
+    for ((oldSym, changes) <- changesOf; change <- changes) {
+      def checkParents(cls: Symbol, file: AbstractFile) {
+        val parentChange = cls.info.parents.exists(_.typeSymbol.fullName == oldSym.fullName)
+          // if (settings.buildmanagerdebug.value)
+          //   compiler.inform("checkParents " + cls + " oldSym: " + oldSym + " parentChange: " + parentChange + " " + cls.info.parents)
+        change match {
+          case Changed(Class(_)) if parentChange =>
+            invalidate(file, "parents have changed", change)
+
+          case Changed(Definition(_)) if parentChange =>
+            invalidate(file, "inherited method changed", change)
+
+          case Added(Definition(_)) if parentChange =>
+            invalidate(file, "inherited new method", change)
+
+          case Removed(Definition(_)) if parentChange =>
+            invalidate(file, "inherited method removed", change)
+
+          case _ => ()
+        }
+      }
+      
+      def checkInterface(cls: Symbol, file: AbstractFile) {
+        change match {
+          case Added(Definition(name)) =>
+            if (cls.info.decls.iterator.exists(_.fullName == name))
+              invalidate(file, "of new method with existing name", change)
+          case Changed(Class(name)) =>
+            if (cls.info.typeSymbol.fullName == name)
+              invalidate(file, "self type changed", change)
+          case _ =>
+            ()
+        }
+      }
+
+      def checkReferences(file: AbstractFile) {
+        //if (settings.buildmanagerdebug.value)
+        //  compiler.inform(file + ":" + references(file))
+        val refs = references(file)
+        if (refs.isEmpty)
+          invalidate(file, "it is a direct dependency and we don't yet have finer-grained dependency information", change)
+        else {
+          change match {
+            case Removed(Definition(name)) if refs(name) =>
+              invalidate(file, "it references deleted definition", change)
+            case Removed(Class(name)) if (refs(name)) =>
+              invalidate(file, "it references deleted class", change)
+            case Changed(Class(name)) if (refs(name)) =>
+              invalidate(file, "it references changed class", change)
+            case Changed(Definition(name)) if (refs(name)) =>
+              invalidate(file, "it references changed definition", change)
+            case Added(Definition(name)) if (refs(name)) =>
+              invalidate(file, "it references added definition", change)
+            case _ => ()
+          }
+        }
+      }
+      
+      def checkInheritedReferences(file: AbstractFile) {
+        val refs = inherited(file)
+        if (!refs.isEmpty)
+          change match {
+            case ParentChanged(Class(name)) =>
+              for (Inherited(q, member) <- refs.find(p => (p != null && p.qualifier == name));
+                   classFile <- classes.get(q);
+                   defs <- definitions.get(classFile);
+                   s <- defs.find(p => p.sym.fullName == q)
+                     if ((s.sym).tpe.nonPrivateMember(member) == compiler.NoSymbol))
+                invalidate(file, "it references invalid (no longer inherited) definition", change)
+              ()
+            case _ => ()
+        }
+      }
+
+        for (file <- directDeps) {
+          breakable {
+            for (cls <- definitions(file)) checkParents(cls.sym, file)
+            for (cls <- definitions(file)) checkInterface(cls.sym, file)
+            checkReferences(file)
+            checkInheritedReferences(file)
+          }
+        }
+    }
+    if (buf.isEmpty)
+      processed
+    else
+      invalidated(buf.clone() --= processed, newChangesOf, processed ++ buf)
+  }
+
+  /** Update the map of definitions per source file */
+  private def updateDefinitions(files: Set[AbstractFile]) {
+    for (src <- files; val localDefs = compiler.dependencyAnalysis.definitions(src)) {
+      definitions(src) = (localDefs map (s => {
+        this.classes += s.fullName -> src
+        SymWithHistory(
+          s.cloneSymbol,
+          atPhase(currentRun.erasurePhase.prev) {
+            s.info.cloneInfo(s)
+          })
+      }))
+    }
+    this.references = compiler.dependencyAnalysis.references
+    this.inherited = compiler.dependencyAnalysis.inherited
+  }
+
+  /** Load saved dependency information. */
+  def loadFrom(file: AbstractFile, toFile: String => AbstractFile) : Boolean = {
+    val success = compiler.dependencyAnalysis.loadFrom(file, toFile)
+    if (success)
+      sources ++= compiler.dependencyAnalysis.managedFiles
+    success
+  }
+  
+  /** Save dependency information to `file'. */
+  def saveTo(file: AbstractFile, fromFile: AbstractFile => String) {
+    compiler.dependencyAnalysis.dependenciesFile = file
+    compiler.dependencyAnalysis.saveDependencies(fromFile)
+  }
+}
diff --git a/src/compiler/scala/tools/nsc/interactive/Response.scala b/src/compiler/scala/tools/nsc/interactive/Response.scala
new file mode 100644
index 0000000..f3cbf54
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/interactive/Response.scala
@@ -0,0 +1,97 @@
+package scala.tools.nsc
+package interactive
+
+/** Typical interaction, given a predicate <user-input>, a function <display>,
+ *  and an exception handler <handle>:
+ *
+ *  val TIMEOUT = 100 // (milliseconds) or something like that
+ *  val r = new Response()
+ *  while (!r.isComplete && !r.isCancelled) {
+ *    if (<user-input>) r.cancel()
+ *    else r.get(TIMEOUT) match {
+ *      case Some(Left(data)) => <display>(data)
+ *      case Some(Right(exc)) => <handle>(exc)
+ *      case None =>
+ *    }
+ *  } 
+ */ 
+class Response[T] {
+
+  private var data: Option[Either[T, Throwable]] = None
+  private var complete = false
+  private var cancelled = false
+
+  /** Set provisional data, more to come
+   */
+  def setProvisionally(x: T) = synchronized {
+    data = Some(Left(x))
+  }
+
+  /** Set final data, and mark response as complete.
+   */
+  def set(x: T) = synchronized {
+    data = Some(Left(x))
+    complete = true
+    notifyAll()
+  }
+
+  /** Store raised exception in data, and mark response as complete.
+   */
+  def raise(exc: Throwable) = synchronized {
+    data = Some(Right(exc))
+    complete = true
+    notifyAll()
+  }
+
+  /** Get final data, wait as long as necessary.
+   *  When interrupted will return with Right(InterruptedException)
+   */
+  def get: Either[T, Throwable] = synchronized {
+    while (!complete) { 
+      try {
+        wait()
+      } catch { 
+        case exc: InterruptedException => raise(exc)
+      }
+    }
+    data.get
+  } 
+
+  /** Optionally get data within `timeout` milliseconds.
+   *  When interrupted will return with Some(Right(InterruptedException))
+   *  When timeout ends, will return last stored provisional result,
+   *  or else None if no provisional result was stored.
+   */
+  def get(timeout: Long): Option[Either[T, Throwable]] = {
+    val start = System.currentTimeMillis
+    var current = start
+    while (!complete && start + timeout > current) {
+      try {
+        wait(timeout - (current - start))
+      } catch { 
+        case exc: InterruptedException => raise(exc)
+      } 
+      current = System.currentTimeMillis
+    }
+    data
+  }
+
+  /** Final data set was stored
+   */ 
+  def isComplete = synchronized { complete }
+
+  /** Cancel action computing this response (Only the
+   *  party that calls get on a response may cancel).
+   */
+  def cancel() = synchronized { cancelled = true }
+
+  /** A cancel request for this response has been issued
+   */
+  def isCancelled = synchronized { cancelled }
+
+  def clear() = synchronized {
+    data = None
+    complete = false
+    cancelled = false
+  }
+}
diff --git a/src/compiler/scala/tools/nsc/interactive/RichCompilationUnits.scala b/src/compiler/scala/tools/nsc/interactive/RichCompilationUnits.scala
new file mode 100644
index 0000000..b1ef945
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/interactive/RichCompilationUnits.scala
@@ -0,0 +1,44 @@
+package scala.tools.nsc
+package interactive
+
+import scala.tools.nsc.util.{SourceFile, Position, NoPosition}
+
+trait RichCompilationUnits { self: Global =>
+
+  /** The status value of a unit that has not yet been loaded */
+  final val NotLoaded = -1
+
+  /** The status value of a unit that has not yet been typechecked */
+  final val JustParsed = 0
+
+  class RichCompilationUnit(source: SourceFile) extends CompilationUnit(source) {
+    
+    /** The runid of the latest compiler run that typechecked this unit,
+     *  or else @see NotLoaded, JustParsed
+     */
+    var status: Int = NotLoaded
+
+    /** Unit has been parsed */
+    def isParsed: Boolean = status >= JustParsed
+
+    /** Unit has been typechecked, but maybe not in latest runs */
+    def isTypeChecked: Boolean = status > JustParsed
+
+    /** Unit has been typechecked and is up to date */
+    def isUpToDate: Boolean = status >= minRunId
+    
+    /** the current edit point offset */
+    var editPoint: Int = -1
+    
+    /** The position of a targeted type check
+     *  If this is different from NoPosition, the type checking
+     *  will stop once a tree that contains this position range
+     *  is fully attributed.
+     */
+    var _targetPos: Position = NoPosition
+    override def targetPos: Position = _targetPos
+    def targetPos_=(p: Position) { _targetPos = p }
+    
+    var contexts: Contexts = new Contexts
+  }
+}
diff --git a/src/compiler/scala/tools/nsc/interactive/SimpleBuildManager.scala b/src/compiler/scala/tools/nsc/interactive/SimpleBuildManager.scala
new file mode 100644
index 0000000..8dae8d4
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/interactive/SimpleBuildManager.scala
@@ -0,0 +1,99 @@
+package scala.tools.nsc
+package interactive
+
+import scala.collection._
+
+import scala.tools.nsc.reporters.{Reporter, ConsoleReporter}
+import dependencies._
+
+import util.FakePos
+import io.AbstractFile
+
+/** A simple build manager, using the default scalac dependency tracker.
+ *  The transitive closure of all dependent files on a modified file
+ *  is recompiled at once.
+ *
+ *  It is equivalent to using a resident compiler mode with the
+ *  '-make:transitive' option.
+ */
+class SimpleBuildManager(val settings: Settings) extends BuildManager {
+
+  class BuilderGlobal(settings: Settings, reporter : Reporter) extends scala.tools.nsc.Global(settings, reporter)  {
+
+    def this(settings: Settings) =
+      this(settings, new ConsoleReporter(settings))
+    
+    def newRun() = new Run()
+  }
+  
+  protected def newCompiler(settings: Settings) = new BuilderGlobal(settings) 
+
+  val compiler = newCompiler(settings)
+
+  /** Managed source files. */
+  private val sources: mutable.Set[AbstractFile] = new mutable.HashSet[AbstractFile]
+
+  /** Add the given source files to the managed build process. */
+  def addSourceFiles(files: Set[AbstractFile]) {
+    sources ++= files
+    update(files)
+  }
+
+  /** Remove the given files from the managed build process. */
+  def removeFiles(files: Set[AbstractFile]) {
+    sources --= files
+    deleteClassfiles(files)
+    update(invalidatedByRemove(files))
+  }
+
+
+  /** Return the set of invalidated files caused by removing the given files. */
+  private def invalidatedByRemove(files: Set[AbstractFile]): Set[AbstractFile] = {
+    val deps = compiler.dependencyAnalysis.dependencies
+    deps.dependentFiles(Int.MaxValue, files)
+  }
+
+  def update(added: Set[AbstractFile], removed: Set[AbstractFile]) {
+    sources --= removed
+    deleteClassfiles(removed)
+    update(added ++ invalidatedByRemove(removed))
+  }
+
+  /** The given files have been modified by the user. Recompile
+   *  them and all files that depend on them. Only files that
+   *  have been previously added as source files are recompiled.
+   */
+  def update(files: Set[AbstractFile]) {
+    deleteClassfiles(files)
+    
+    val deps = compiler.dependencyAnalysis.dependencies
+    val run = compiler.newRun()
+    compiler.inform("compiling " + files)
+
+    val toCompile = 
+      (files ++ deps.dependentFiles(Int.MaxValue, files)) intersect sources
+    
+
+    compiler.inform("Recompiling " + 
+                    (if(settings.debug.value) toCompile.mkString(", ")
+                     else toCompile.size + " files"))
+    
+    buildingFiles(toCompile)
+
+    run.compileFiles(files.toList)
+  }
+
+  /** Load saved dependency information. */
+  def loadFrom(file: AbstractFile, toFile: String => AbstractFile) : Boolean = {
+    val success = compiler.dependencyAnalysis.loadFrom(file, toFile)
+    if (success)
+      sources ++= compiler.dependencyAnalysis.managedFiles
+    success
+  }
+  
+  /** Save dependency information to `file'. */
+  def saveTo(file: AbstractFile, fromFile: AbstractFile => String) {
+    compiler.dependencyAnalysis.dependenciesFile = file
+    compiler.dependencyAnalysis.saveDependencies(fromFile)
+  }
+}
diff --git a/src/compiler/scala/tools/nsc/interpreter/AbstractFileClassLoader.scala b/src/compiler/scala/tools/nsc/interpreter/AbstractFileClassLoader.scala
index f00265e..2232def 100644
--- a/src/compiler/scala/tools/nsc/interpreter/AbstractFileClassLoader.scala
+++ b/src/compiler/scala/tools/nsc/interpreter/AbstractFileClassLoader.scala
@@ -1,9 +1,12 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  */
-// $Id$
-package scala.tools.nsc.interpreter
+
+package scala.tools.nsc
+package interpreter
+
 import scala.tools.nsc.io.AbstractFile
+import util.ScalaClassLoader
 
 /**
  * A class loader that loads files from a {@link scala.tools.nsc.io.AbstractFile}.
@@ -11,22 +14,23 @@ import scala.tools.nsc.io.AbstractFile
  * @author Lex Spoon
  */
 class AbstractFileClassLoader(root: AbstractFile, parent: ClassLoader)
-extends ClassLoader(parent)
+    extends ClassLoader(parent)
+    with ScalaClassLoader
 {
-  override def findClass(name: String): Class[_] = {
+  def getBytesForClass(name: String): Array[Byte] = {
+    def onull[T](x: T): T = if (x == null) throw new ClassNotFoundException(name) else x
     var file: AbstractFile = root
     val pathParts = name.split("[./]").toList
-    for (dirPart <- pathParts.init) {
-      file = file.lookupName(dirPart, true)
-      if (file == null) {
-        throw new ClassNotFoundException(name)
-      }
-    }
-    file = file.lookupName(pathParts.last+".class", false)
-    if (file == null) {
-      throw new ClassNotFoundException(name)
-    }
-    val bytes = file.toByteArray
+    
+    for (dirPart <- pathParts.init)
+      file = onull(file.lookupName(dirPart, true))
+      
+    file = onull(file.lookupName(pathParts.last+".class", false))
+    file.toByteArray
+  }
+  
+  override def findClass(name: String): Class[_] = {
+    val bytes = getBytesForClass(name)
     defineClass(name, bytes, 0, bytes.length)
   }
 }
diff --git a/src/compiler/scala/tools/nsc/interpreter/ByteCode.scala b/src/compiler/scala/tools/nsc/interpreter/ByteCode.scala
new file mode 100644
index 0000000..ad074e3
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/interpreter/ByteCode.scala
@@ -0,0 +1,64 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
+ * @author Paul Phillips
+ */
+
+package scala.tools.nsc
+package interpreter
+
+import java.io.File
+import java.lang.reflect
+import java.util.jar.{ JarEntry, JarFile }
+import java.util.concurrent.ConcurrentHashMap
+import util.ScalaClassLoader
+import ScalaClassLoader.getSystemLoader
+
+object ByteCode {
+  /** Until I figure out why I can't get scalap onto the classpath such
+   *  that the compiler will bootstrap, we have to use reflection.
+   */
+  private lazy val DECODER: Option[AnyRef] =
+    for (clazz <- getSystemLoader.tryToLoadClass[AnyRef]("scala.tools.scalap.Decode$")) yield
+      clazz.getField("MODULE$").get()
+  
+  private def decoderMethod(name: String, args: Class[_]*): Option[reflect.Method] = {
+    for (decoder <- DECODER ; m <- Option(decoder.getClass.getMethod(name, args: _*))) yield m
+  }   
+
+  private lazy val aliasMap = {
+    for (module <- DECODER ; method <- decoderMethod("typeAliases", classOf[String])) yield
+      method.invoke(module, _: String).asInstanceOf[Option[Map[String, String]]]
+  }
+  
+  /** Scala sig bytes.
+   */
+  def scalaSigBytesForPath(path: String) =
+    for {
+      module <- DECODER
+      method <- decoderMethod("scalaSigAnnotationBytes", classOf[String])
+      names <- method.invoke(module, path).asInstanceOf[Option[Array[Byte]]]
+    }
+    yield names  
+  
+  /** Attempts to retrieve case parameter names for given class name.
+   */
+  def caseParamNamesForPath(path: String) =
+    for {
+      module <- DECODER
+      method <- decoderMethod("caseParamNames", classOf[String])
+      names <- method.invoke(module, path).asInstanceOf[Option[List[String]]]
+    }
+    yield names
+
+  def aliasesForPackage(pkg: String) = aliasMap flatMap (_(pkg))
+  
+  /** Attempts to find type aliases in package objects.
+   */
+  def aliasForType(path: String): Option[String] = {
+    val (pkg, name) = (path lastIndexOf '.') match {
+      case -1   => return None
+      case idx  => (path take idx, path drop (idx + 1))
+    }
+    aliasesForPackage(pkg) flatMap (_ get name)
+  }
+}
diff --git a/src/compiler/scala/tools/nsc/interpreter/Completion.scala b/src/compiler/scala/tools/nsc/interpreter/Completion.scala
new file mode 100644
index 0000000..8573ca2
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/interpreter/Completion.scala
@@ -0,0 +1,366 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
+ * @author Paul Phillips
+ */
+
+
+package scala.tools.nsc
+package interpreter
+
+import jline._
+import java.util.{ List => JList }
+import util.returning
+
+object Completion {  
+  def looksLikeInvocation(code: String) = (
+        (code != null)
+    &&  (code startsWith ".")
+    && !(code == ".")
+    && !(code startsWith "./")
+    && !(code startsWith "..")
+  )
+  
+  object Forwarder {
+    def apply(forwardTo: () => Option[CompletionAware]): CompletionAware = new CompletionAware {
+      def completions(verbosity: Int) = forwardTo() map (_ completions verbosity) getOrElse Nil
+      override def follow(s: String) = forwardTo() flatMap (_ follow s)
+    }
+  }
+}
+import Completion._
+
+// REPL completor - queries supplied interpreter for valid
+// completions based on current contents of buffer.
+class Completion(val repl: Interpreter) extends CompletionOutput {
+  // verbosity goes up with consecutive tabs
+  private var verbosity: Int = 0
+  def resetVerbosity() = verbosity = 0
+  
+  def isCompletionDebug = repl.isCompletionDebug
+  def DBG(msg: => Any) = if (isCompletionDebug) println(msg.toString)
+  def debugging[T](msg: String): T => T = (res: T) => returning[T](res)(x => DBG(msg + x))
+  
+  lazy val global: repl.compiler.type = repl.compiler
+  import global._
+  import definitions.{ PredefModule, RootClass, AnyClass, AnyRefClass, ScalaPackage, JavaLangPackage }
+
+  // XXX not yet used.
+  lazy val dottedPaths = {
+    def walk(tp: Type): scala.List[Symbol] = {
+      val pkgs = tp.nonPrivateMembers filter (_.isPackage)
+      pkgs ++ (pkgs map (_.tpe) flatMap walk)
+    }
+    walk(RootClass.tpe)
+  }
+  
+  def getType(name: String, isModule: Boolean) = {
+    val f = if (isModule) definitions.getModule(_: Name) else definitions.getClass(_: Name)
+    try Some(f(name).tpe)
+    catch { case _: MissingRequirementError => None }
+  }
+  
+  def typeOf(name: String) = getType(name, false)
+  def moduleOf(name: String) = getType(name, true)
+    
+  trait CompilerCompletion {
+    def tp: Type
+    def effectiveTp = tp match {
+      case MethodType(Nil, resType) => resType
+      case PolyType(Nil, resType)   => resType
+      case _                        => tp
+    }
+
+    // for some reason any's members don't show up in subclasses, which
+    // we need so 5.<tab> offers asInstanceOf etc.
+    private def anyMembers = AnyClass.tpe.nonPrivateMembers
+    def anyRefMethodsToShow = List("isInstanceOf", "asInstanceOf", "toString")
+
+    def tos(sym: Symbol) = sym.name.decode.toString
+    def memberNamed(s: String) = members find (x => tos(x) == s)
+    def hasMethod(s: String) = methods exists (x => tos(x) == s)
+
+    // XXX we'd like to say "filterNot (_.isDeprecated)" but this causes the
+    // compiler to crash for reasons not yet known.
+    def members     = (effectiveTp.nonPrivateMembers ++ anyMembers) filter (_.isPublic)
+    def methods     = members filter (_.isMethod)
+    def packages    = members filter (_.isPackage)
+    def aliases     = members filter (_.isAliasType)
+
+    def memberNames   = members map tos
+    def methodNames   = methods map tos
+    def packageNames  = packages map tos
+    def aliasNames    = aliases map tos
+  }
+
+  object TypeMemberCompletion {
+    def apply(tp: Type): TypeMemberCompletion = {
+      if (tp.typeSymbol.isPackageClass) new PackageCompletion(tp)
+      else new TypeMemberCompletion(tp)
+    }
+    def imported(tp: Type) = new ImportCompletion(tp)
+  }
+
+  class TypeMemberCompletion(val tp: Type) extends CompletionAware
+                                              with CompilerCompletion {
+    def excludeEndsWith: List[String] = Nil
+    def excludeStartsWith: List[String] = List("<") // <byname>, <repeated>, etc.
+    def excludeNames: List[String] =
+      anyref.methodNames.filterNot(anyRefMethodsToShow contains) ++ List("_root_")
+    
+    def methodSignatureString(sym: Symbol) = {
+      def asString = new MethodSymbolOutput(sym).methodString()
+      
+      if (isCompletionDebug)
+        repl.power.showAtAllPhases(asString)
+
+      atPhase(currentRun.typerPhase)(asString)
+    }
+
+    def exclude(name: String): Boolean = (
+      (name contains "$") ||
+      (excludeNames contains name) ||
+      (excludeEndsWith exists (name endsWith _)) ||
+      (excludeStartsWith exists (name startsWith _))
+    )
+    def filtered(xs: List[String]) = xs filterNot exclude distinct
+
+    def completions(verbosity: Int) =
+      debugging(tp + " completions ==> ")(filtered(memberNames))
+    
+    override def follow(s: String): Option[CompletionAware] =
+      debugging(tp + " -> '" + s + "' ==> ")(memberNamed(s) map (x => TypeMemberCompletion(x.tpe)))      
+    
+    override def alternativesFor(id: String): List[String] =
+      debugging(id + " alternatives ==> ") {
+        val alts = members filter (x => x.isMethod && tos(x) == id) map methodSignatureString
+
+        if (alts.nonEmpty) "" :: alts else Nil
+      }
+
+    override def toString = "TypeMemberCompletion(%s)".format(tp)
+  }
+  
+  class PackageCompletion(tp: Type) extends TypeMemberCompletion(tp) {
+    override def excludeNames = anyref.methodNames
+  }
+
+  class LiteralCompletion(lit: Literal) extends TypeMemberCompletion(lit.value.tpe) {
+    override def completions(verbosity: Int) = verbosity match {
+      case 0    => filtered(memberNames)
+      case _    => memberNames
+    }
+  }
+  
+  class ImportCompletion(tp: Type) extends TypeMemberCompletion(tp) {
+    override def completions(verbosity: Int) = verbosity match {
+      case 0    => filtered(members filterNot (_.isSetter) map tos)
+      case _    => super.completions(verbosity)
+    }
+  }
+  
+  // not for completion but for excluding
+  object anyref extends TypeMemberCompletion(AnyRefClass.tpe) { }
+  
+  // the unqualified vals/defs/etc visible in the repl
+  object ids extends CompletionAware {
+    override def completions(verbosity: Int) = repl.unqualifiedIds ::: List("classOf")
+    // we try to use the compiler and fall back on reflection if necessary
+    // (which at present is for anything defined in the repl session.)
+    override def follow(id: String) =
+      if (completions(0) contains id) {
+        for (clazz <- repl clazzForIdent id) yield {
+          // XXX The isMemberClass check is a workaround for the crasher described
+          // in the comments of #3431.  The issue as described by iulian is:
+          //
+          // Inner classes exist as symbols
+          // inside their enclosing class, but also inside their package, with a mangled
+          // name (A$B). The mangled names should never be loaded, and exist only for the
+          // optimizer, which sometimes cannot get the right symbol, but it doesn't care
+          // and loads the bytecode anyway.
+          //
+          // So this solution is incorrect, but in the short term the simple fix is
+          // to skip the compiler any time completion is requested on a nested class.
+          if (clazz.isMemberClass) new InstanceCompletion(clazz)
+          else (typeOf(clazz.getName) map TypeMemberCompletion.apply) getOrElse new InstanceCompletion(clazz)
+        }
+      }
+      else None
+  }
+
+  // wildcard imports in the repl like "import global._" or "import String._"
+  private def imported = repl.wildcardImportedTypes map TypeMemberCompletion.imported
+
+  // literal Ints, Strings, etc.
+  object literals extends CompletionAware {    
+    def simpleParse(code: String): Tree = {
+      val unit    = new CompilationUnit(new util.BatchSourceFile("<console>", code))
+      val scanner = new syntaxAnalyzer.UnitParser(unit)
+      val tss     = scanner.templateStatSeq(false)._2
+
+      if (tss.size == 1) tss.head else EmptyTree
+    }
+  
+    def completions(verbosity: Int) = Nil
+    
+    override def follow(id: String) = simpleParse(id) match {
+      case x: Literal   => Some(new LiteralCompletion(x))
+      case _            => None
+    }
+  }
+
+  // top level packages
+  object rootClass extends TypeMemberCompletion(RootClass.tpe) { }
+  // members of Predef
+  object predef extends TypeMemberCompletion(PredefModule.tpe) {
+    override def excludeEndsWith    = super.excludeEndsWith ++ List("Wrapper", "ArrayOps")
+    override def excludeStartsWith  = super.excludeStartsWith ++ List("wrap")
+    override def excludeNames       = anyref.methodNames
+    
+    override def exclude(name: String) = super.exclude(name) || (
+      (name contains "2")
+    )
+    
+    override def completions(verbosity: Int) = verbosity match {
+      case 0    => Nil
+      case _    => super.completions(verbosity)
+    }
+  }
+  // members of scala.*
+  object scalalang extends PackageCompletion(ScalaPackage.tpe) {
+    def arityClasses = List("Product", "Tuple", "Function")
+    def skipArity(name: String) = arityClasses exists (x => name != x && (name startsWith x))
+    override def exclude(name: String) = super.exclude(name) || (
+      skipArity(name)
+    )
+    
+    override def completions(verbosity: Int) = verbosity match {
+      case 0    => filtered(packageNames ++ aliasNames)
+      case _    => super.completions(verbosity)
+    }
+  }
+  // members of java.lang.*
+  object javalang extends PackageCompletion(JavaLangPackage.tpe) {
+    override lazy val excludeEndsWith   = super.excludeEndsWith ++ List("Exception", "Error")
+    override lazy val excludeStartsWith = super.excludeStartsWith ++ List("CharacterData")
+    
+    override def completions(verbosity: Int) = verbosity match {
+      case 0    => filtered(packageNames)
+      case _    => super.completions(verbosity)
+    }
+  }
+
+  // the list of completion aware objects which should be consulted
+  lazy val topLevelBase: List[CompletionAware] = List(ids, rootClass, predef, scalalang, javalang, literals)
+  def topLevel = topLevelBase ++ imported
+  
+  // the first tier of top level objects (doesn't include file completion)
+  def topLevelFor(parsed: Parsed) = topLevel flatMap (_ completionsFor parsed)
+
+  // the most recent result
+  def lastResult = Forwarder(() => ids follow repl.mostRecentVar)
+
+  def lastResultFor(parsed: Parsed) = {
+    /** The logic is a little tortured right now because normally '.' is
+     *  ignored as a delimiter, but on .<tab> it needs to be propagated.
+     */
+    val xs = lastResult completionsFor parsed
+    if (parsed.isEmpty) xs map ("." + _) else xs
+  }
+
+  // chasing down results which won't parse
+  def execute(line: String): Option[Any] = {
+    val parsed = Parsed(line)
+    def noDotOrSlash = line forall (ch => ch != '.' && ch != '/')
+    
+    if (noDotOrSlash) None  // we defer all unqualified ids to the repl.
+    else {
+      (ids executionFor parsed) orElse
+      (rootClass executionFor parsed) orElse
+      (FileCompletion executionFor line)
+    }
+  }
+  
+  // generic interface for querying (e.g. interpreter loop, testing)
+  def completions(buf: String): List[String] =
+    topLevelFor(Parsed.dotted(buf + ".", buf.length + 1))
+
+  // jline's entry point
+  lazy val jline: ArgumentCompletor =
+    returning(new ArgumentCompletor(new JLineCompletion, new JLineDelimiter))(_ setStrict false)
+
+  /** This gets a little bit hairy.  It's no small feat delegating everything
+   *  and also keeping track of exactly where the cursor is and where it's supposed
+   *  to end up.  The alternatives mechanism is a little hacky: if there is an empty
+   *  string in the list of completions, that means we are expanding a unique
+   *  completion, so don't update the "last" buffer because it'll be wrong.
+   */
+  class JLineCompletion extends Completor {
+    // For recording the buffer on the last tab hit
+    private var lastBuf: String = ""
+    private var lastCursor: Int = -1
+
+    // Does this represent two consecutive tabs?
+    def isConsecutiveTabs(buf: String, cursor: Int) =
+      cursor == lastCursor && buf == lastBuf
+
+    // Longest common prefix
+    def commonPrefix(xs: List[String]) =
+      if (xs.isEmpty) ""
+      else xs.reduceLeft(_ zip _ takeWhile (x => x._1 == x._2) map (_._1) mkString)
+
+    // This is jline's entry point for completion.
+    override def complete(_buf: String, cursor: Int, candidates: JList[String]): Int = {
+      val buf = onull(_buf)
+      verbosity = if (isConsecutiveTabs(buf, cursor)) verbosity + 1 else 0
+      DBG("\ncomplete(%s, %d) last = (%s, %d), verbosity: %s".format(buf, cursor, lastBuf, lastCursor, verbosity))
+
+      // we don't try lower priority completions unless higher ones return no results.
+      def tryCompletion(p: Parsed, completionFunction: Parsed => List[String]): Option[Int] = {
+        completionFunction(p) match {
+          case Nil  => None
+          case xs   =>
+            // modify in place and return the position
+            xs foreach (candidates add _)
+
+            // update the last buffer unless this is an alternatives list
+            if (xs contains "") Some(p.cursor)
+            else {
+              val advance = commonPrefix(xs)            
+              lastCursor = p.position + advance.length
+              lastBuf = (buf take p.position) + advance
+  
+              DBG("tryCompletion(%s, _) lastBuf = %s, lastCursor = %s, p.position = %s".format(p, lastBuf, lastCursor, p.position))
+              Some(p.position) 
+            }
+        }
+      }
+      
+      def mkDotted      = Parsed.dotted(buf, cursor) withVerbosity verbosity
+      def mkUndelimited = Parsed.undelimited(buf, cursor) withVerbosity verbosity
+
+      // a single dot is special cased to completion on the previous result
+      def lastResultCompletion =
+        if (!looksLikeInvocation(buf)) None            
+        else tryCompletion(Parsed.dotted(buf drop 1, cursor), lastResultFor)
+
+      def regularCompletion = tryCompletion(mkDotted, topLevelFor)
+      def fileCompletion    = tryCompletion(mkUndelimited, FileCompletion completionsFor _.buffer)
+      
+      /** This is the kickoff point for all manner of theoretically possible compiler
+       *  unhappiness - fault may be here or elsewhere, but we don't want to crash the
+       *  repl regardless.  Hopefully catching Exception is enough, but because the
+       *  compiler still throws some Errors it may not be.
+       */
+      try {
+        (lastResultCompletion orElse regularCompletion orElse fileCompletion) getOrElse cursor
+      }
+      catch {
+        case ex: Exception =>
+          DBG("Error: complete(%s, %s, _) provoked %s".format(_buf, cursor, ex))
+          candidates add " "
+          candidates add "<completion error>"
+          cursor
+      }
+    }
+  }
+}
diff --git a/src/compiler/scala/tools/nsc/interpreter/CompletionAware.scala b/src/compiler/scala/tools/nsc/interpreter/CompletionAware.scala
new file mode 100644
index 0000000..35ab13e
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/interpreter/CompletionAware.scala
@@ -0,0 +1,130 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
+ * @author Paul Phillips
+ */
+ 
+package scala.tools.nsc
+package interpreter
+
+import scala.reflect.NameTransformer
+
+/** An interface for objects which are aware of tab completion and
+ *  will supply their own candidates and resolve their own paths.
+ */
+trait CompletionAware {
+  /** The delimiters which are meaningful when this CompletionAware
+   *  object is in control.
+   */
+  // TODO
+  // def delimiters(): List[Char] = List('.')
+
+  /** The complete list of unqualified Strings to which this
+   *  object will complete.
+   */
+  def completions(verbosity: Int): List[String]
+  
+  /** Default filter to apply to completions.
+   */
+  def filterNotFunction(s: String): Boolean = false
+  
+  /** Default sort.
+   */
+  def sortFunction(s1: String, s2: String): Boolean = s1 < s2
+  
+  /** Default map.
+   */
+  def mapFunction(s: String) = NameTransformer decode s
+  
+  /** The next completor in the chain.
+   */
+  def follow(id: String): Option[CompletionAware] = None
+  
+  /** What to return if this completion is given as a command.  It
+   *  returns None by default, which means to allow the repl to interpret
+   *  the line normally.  Returning Some(_) means the line will never
+   *  reach the scala interpreter.
+   */
+  def execute(id: String): Option[Any] = None
+
+  /** A list of useful information regarding a specific uniquely
+   *  identified completion.  This is specifically written for the
+   *  following situation, but should be useful elsewhere too:
+   *
+   *    x.y.z.methodName<tab>
+   *
+   *  If "methodName" is among z's completions, and verbosity > 0
+   *  indicating tab has been pressed twice consecutively, then we
+   *  call alternativesFor and show a list of overloaded method
+   *  signatures.
+   */
+  def alternativesFor(id: String): List[String] = Nil
+  
+  /** Given string 'buf', return a list of all the strings
+   *  to which it can complete.  This may involve delegating
+   *  to other CompletionAware objects.
+   */
+  def completionsFor(parsed: Parsed): List[String] = {
+    import parsed._
+    
+    val comps = completions(verbosity) filter (_ startsWith buffer)
+    val results =    
+      if (isEmpty) comps
+      else if (isUnqualified && !isLastDelimiter) {
+        if (verbosity > 0 && (comps contains buffer)) alternativesFor(buffer)
+        else comps
+      }
+      else follow(bufferHead) map (_ completionsFor bufferTail) getOrElse Nil
+  
+    results filterNot filterNotFunction map mapFunction sortWith (sortFunction _)
+  }
+  
+  /** TODO - unify this and completionsFor under a common traverser.
+   */
+  def executionFor(parsed: Parsed): Option[Any] = {
+    import parsed._
+    
+    if (isUnqualified && !isLastDelimiter && (completions(verbosity) contains buffer)) execute(buffer)
+    else if (!isQualified) None
+    else follow(bufferHead) flatMap (_ executionFor bufferTail)
+  }
+}
+
+object CompletionAware {
+  val Empty = new CompletionAware { def completions(verbosity: Int) = Nil }
+  
+  // class Forwarder(underlying: CompletionAware) extends CompletionAware {
+  //   override def completions() = underlying.completions()
+  //   override def filterNotFunction(s: String) = underlying.filterNotFunction(s)
+  //   override def sortFunction(s1: String, s2: String) = underlying.sortFunction(s1, s2)
+  //   override def mapFunction(s: String) = underlying.mapFunction(s)
+  //   override def follow(id: String) = underlying.follow(id)
+  //   override def execute(id: String) = underlying.execute(id)
+  //   override def completionsFor(parsed: Parsed) = underlying.completionsFor(parsed)
+  //   override def executionFor(parsed: Parsed) = underlying.executionFor(parsed)
+  // } 
+  //
+  
+  def unapply(that: Any): Option[CompletionAware] = that match {
+    case x: CompletionAware => Some((x))
+    case _                  => None
+  }
+  
+  /** Create a CompletionAware object from the given functions.
+   *  The first should generate the list of completions whenever queried,
+   *  and the second should return Some(CompletionAware) object if
+   *  subcompletions are possible.
+   */
+  def apply(terms: () => List[String], followFunction: String => Option[CompletionAware]): CompletionAware =
+    new CompletionAware {
+      def completions = terms()
+      def completions(verbosity: Int) = completions
+      override def follow(id: String) = followFunction(id)
+    }
+
+  /** Convenience factories.
+   */
+  def apply(terms: () => List[String]): CompletionAware = apply(terms, _ => None)
+  def apply(map: collection.Map[String, CompletionAware]): CompletionAware =
+    apply(() => map.keys.toList, map.get _)
+}
+
diff --git a/src/compiler/scala/tools/nsc/interpreter/CompletionOutput.scala b/src/compiler/scala/tools/nsc/interpreter/CompletionOutput.scala
new file mode 100644
index 0000000..d2939fd
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/interpreter/CompletionOutput.scala
@@ -0,0 +1,88 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
+ * @author Paul Phillips
+ */
+
+package scala.tools.nsc
+package interpreter
+
+/** This has a lot of duplication with other methods in Symbols and Types,
+ *  but repl completion utility is very sensitive to precise output.  Best
+ *  thing would be to abstract an interface for how such things are printed,
+ *  as is also in progress with error messages.
+ */
+trait CompletionOutput {
+  self: Completion =>
+  
+  import global._
+  import definitions.{ NothingClass, AnyClass, isTupleType, isFunctionType, isRepeatedParamType }
+  
+  /** Reducing fully qualified noise for some common packages.
+   */
+  val typeTransforms = List(
+    "java.lang." -> "",
+    "scala.collection.immutable." -> "immutable.",
+    "scala.collection.mutable." -> "mutable.",
+    "scala.collection.generic." -> "generic."
+  )
+    
+  def quietString(tp: String): String =
+    typeTransforms.foldLeft(tp) {
+      case (str, (prefix, replacement)) =>
+        if (str startsWith prefix) replacement + (str stripPrefix prefix)
+        else str
+    }
+  
+  class MethodSymbolOutput(method: Symbol) {
+    val pkg       = method.ownerChain find (_.isPackageClass) map (_.fullName) getOrElse ""
+    
+    def relativize(str: String): String = quietString(str stripPrefix (pkg + "."))
+    def relativize(tp: Type): String    = relativize(tp.normalize.toString)
+    def relativize(sym: Symbol): String = relativize(sym.info)
+    
+    def braceList(tparams: List[String]) = if (tparams.isEmpty) "" else (tparams map relativize).mkString("[", ", ", "]")
+    def parenList(params: List[Any])  = params.mkString("(", ", ", ")")
+    
+    def methodTypeToString(mt: MethodType) =
+      (mt.paramss map paramsString mkString "") + ": " + relativize(mt.finalResultType)
+    
+    def typeToString(tp: Type): String = relativize(
+      tp match {
+        case x if isFunctionType(x)           => functionString(x)
+        case x if isTupleType(x)              => tupleString(x)
+        case x if isRepeatedParamType(x)      => typeToString(x.typeArgs.head) + "*"
+        case mt @ MethodType(_, _)            => methodTypeToString(mt)
+        case x                                => x.toString
+      }
+    )
+
+    def tupleString(tp: Type) = parenList(tp.normalize.typeArgs map relativize)
+    def functionString(tp: Type) = tp.normalize.typeArgs match {
+      case List(t, r) => t + " => " + r
+      case xs         => parenList(xs.init) + " => " + xs.last
+    }
+
+    def tparamsString(tparams: List[Symbol])  = braceList(tparams map (_.defString))
+    def paramsString(params: List[Symbol])    = {
+      def paramNameString(sym: Symbol)  = if (sym.isSynthetic) "" else sym.nameString + ": "
+      def paramString(sym: Symbol)      = paramNameString(sym) + typeToString(sym.info.normalize)
+
+      val isImplicit = params.nonEmpty && params.head.isImplicit
+      val strs = (params map paramString) match {
+        case x :: xs if isImplicit  => ("implicit " + x) :: xs
+        case xs                     => xs
+      }
+      parenList(strs)
+    }    
+
+    def methodString() =
+      method.keyString + " " + method.nameString + (method.info.normalize match {
+        case PolyType(Nil, resType)             => ": " + typeToString(resType) // nullary method
+        case PolyType(tparams, resType)         => tparamsString(tparams) + typeToString(resType)
+        case mt @ MethodType(_, _)              => methodTypeToString(mt)
+        case x                                  => 
+          DBG("methodString(): %s / %s".format(x.getClass, x))            
+          x.toString
+      })
+  }  
+}
diff --git a/src/compiler/scala/tools/nsc/interpreter/Delimited.scala b/src/compiler/scala/tools/nsc/interpreter/Delimited.scala
new file mode 100644
index 0000000..1f0456d
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/interpreter/Delimited.scala
@@ -0,0 +1,36 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
+ * @author Paul Phillips
+ */
+ 
+package scala.tools.nsc
+package interpreter
+
+import jline.ArgumentCompletor.{ ArgumentDelimiter, ArgumentList }
+
+class JLineDelimiter extends ArgumentDelimiter {
+  def delimit(buffer: String, cursor: Int) = Parsed(buffer, cursor).asJlineArgumentList
+  def isDelimiter(buffer: String, cursor: Int) = Parsed(buffer, cursor).isDelimiter
+}
+
+trait Delimited {
+  self: Parsed =>
+  
+  def delimited: Char => Boolean
+  def escapeChars: List[Char] = List('\\')
+  def quoteChars: List[(Char, Char)] = List(('\'', '\''), ('"', '"'))
+  
+  /** Break String into args based on delimiting function.
+   */
+  protected def toArgs(s: String): List[String] = 
+    if (s == "") Nil
+    else (s indexWhere isDelimiterChar) match {
+      case -1   => List(s)
+      case idx  => (s take idx) :: toArgs(s drop (idx + 1))
+    }
+  
+  def isDelimiterChar(ch: Char) = delimited(ch)
+  def isEscapeChar(ch: Char): Boolean = escapeChars contains ch
+  def isQuoteStart(ch: Char): Boolean = quoteChars map (_._1) contains ch
+  def isQuoteEnd(ch: Char): Boolean = quoteChars map (_._2) contains ch
+}
diff --git a/src/compiler/scala/tools/nsc/interpreter/FileCompletion.scala b/src/compiler/scala/tools/nsc/interpreter/FileCompletion.scala
new file mode 100644
index 0000000..3d519de
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/interpreter/FileCompletion.scala
@@ -0,0 +1,54 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
+ * @author Paul Phillips
+ */
+ 
+package scala.tools.nsc
+package interpreter
+
+/** TODO
+ *  Spaces, dots, and other things in filenames are not correctly handled.
+ *  space-escaping, knowing when we're inside quotes, etc. would be nice.
+ */
+
+import io.{ Directory, Path }
+
+/** This isn't 100% clean right now, but it works and is simple.  Rather
+ *  than delegate to new objects on each '/' in the path, we treat the
+ *  buffer like a path and process it directly.
+ */
+object FileCompletion {  
+  def executionFor(buffer: String): Option[Path] = {
+    val p = Path(buffer)
+    if (p.exists) Some(p) else None
+  }
+
+  private def fileCompletionForwarder(buffer: String, where: Directory): List[String] = {
+    completionsFor(where.path + buffer) map (_ stripPrefix where.path) toList
+  }
+  
+  private def homeCompletions(buffer: String): List[String] = {
+    require(buffer startsWith "~/")
+    val home = Directory.Home getOrElse (return Nil)
+    fileCompletionForwarder(buffer.tail, home) map ("~" + _)
+  }
+  private def cwdCompletions(buffer: String): List[String] = {
+    require(buffer startsWith "./")
+    val cwd = Directory.Current getOrElse (return Nil)
+    fileCompletionForwarder(buffer.tail, cwd) map ("." + _)
+  }
+  
+  def completionsFor(buffer: String): List[String] =
+    if (buffer startsWith "~/") homeCompletions(buffer)
+    else if (buffer startsWith "./") cwdCompletions(buffer)
+    else {
+      val p = Path(buffer)
+      val (dir, stub) =
+        // don't want /foo/. expanding "."
+        if (p.name == ".") (p.parent, ".")
+        else if (p.isDirectory) (p.toDirectory, "")
+        else (p.parent, p.name)
+
+      dir.list filter (_.name startsWith stub) map (_.path) toList
+    }
+}
\ No newline at end of file
diff --git a/src/compiler/scala/tools/nsc/interpreter/History.scala b/src/compiler/scala/tools/nsc/interpreter/History.scala
new file mode 100644
index 0000000..00d0f27
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/interpreter/History.scala
@@ -0,0 +1,36 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
+ * @author Paul Phillips
+ */
+
+package scala.tools.nsc
+package interpreter
+
+import java.io.File
+import jline.{ ConsoleReader, History => JHistory }
+import scala.collection.JavaConversions.asBuffer
+import Properties.userHome
+
+/** Primarily, a wrapper for JLine's History.
+ */
+class History(val jhistory: JHistory) {
+  def asJavaList = jhistory.getHistoryList
+  def asList: List[String] = asBuffer(asJavaList).toList
+  def index = jhistory.getCurrentIndex
+
+  def grep(s: String) = asList filter (_ contains s)
+}
+
+object History {
+  val ScalaHistoryFile = ".scala_history"
+  
+  def apply(reader: ConsoleReader): History =
+    if (reader == null) apply()
+    else new History(reader.getHistory)
+  
+  def apply(): History = new History(
+    try new JHistory(new File(userHome, ScalaHistoryFile))
+    // do not store history if error
+    catch { case _: Exception => new JHistory() }
+  )  
+}
diff --git a/src/compiler/scala/tools/nsc/interpreter/InteractiveReader.scala b/src/compiler/scala/tools/nsc/interpreter/InteractiveReader.scala
index e8f954a..c33a56f 100644
--- a/src/compiler/scala/tools/nsc/interpreter/InteractiveReader.scala
+++ b/src/compiler/scala/tools/nsc/interpreter/InteractiveReader.scala
@@ -1,10 +1,11 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author Stepan Koltsov
  */
-// $Id: InteractiveReader.scala 16881 2009-01-09 16:28:11Z cunei $
 
-package scala.tools.nsc.interpreter
+package scala.tools.nsc
+package interpreter
+import scala.util.control.Exception._
 
 /** Reads lines from an input stream */
 trait InteractiveReader {
@@ -14,35 +15,41 @@ trait InteractiveReader {
   protected def readOneLine(prompt: String): String
   val interactive: Boolean
   
-  def readLine(prompt: String): String = 
-    try {
-      readOneLine(prompt)
-    }
-    catch {
+  def readLine(prompt: String): String = {
+    def handler: Catcher[String] = {
       case e: IOException if restartSystemCall(e) => readLine(prompt)
-      case e => throw e
     }
+    catching(handler) { readOneLine(prompt) }
+  }
+  
+  // override if history is available
+  def history: Option[History] = None
+  def historyList = history map (_.asList) getOrElse Nil
+  
+  // override if completion is available
+  def completion: Option[Completion] = None
     
+  // hack necessary for OSX jvm suspension because read calls are not restarted after SIGTSTP
   private def restartSystemCall(e: Exception): Boolean =
-    (vendor startsWith "Apple") && (e.getMessage == msgEINTR)
+    Properties.isMac && (e.getMessage == msgEINTR)
 }
 
 
 object InteractiveReader {
-  // hacks necessary for OSX jvm suspension because read calls are not restarted after SIGTSTP
-  val vendor = System.getProperty("java.vendor", "")
   val msgEINTR = "Interrupted system call"
+  private val exes = List(classOf[Exception], classOf[NoClassDefFoundError])
+  
+  def createDefault(): InteractiveReader = createDefault(null)
   
   /** Create an interactive reader.  Uses <code>JLineReader</code> if the
-   *  library is available, but otherwise uses a 
-   *  <code>SimpleReaderi</code>. */
-  def createDefault(): InteractiveReader =
-    try {
-      new JLineReader
-    } catch {
-      case e =>
-        //out.println("jline is not available: " + e) //debug
-        new SimpleReader()
+   *  library is available, but otherwise uses a <code>SimpleReader</code>. 
+   */
+  def createDefault(interpreter: Interpreter): InteractiveReader =
+    try new JLineReader(interpreter)
+    catch {
+      case e @ (_: Exception | _: NoClassDefFoundError) =>
+        // println("Failed to create JLineReader(%s): %s".format(interpreter, e))
+        new SimpleReader
     }
 }
 
diff --git a/src/compiler/scala/tools/nsc/interpreter/JLineReader.scala b/src/compiler/scala/tools/nsc/interpreter/JLineReader.scala
index 8d0e0a5..158733c 100644
--- a/src/compiler/scala/tools/nsc/interpreter/JLineReader.scala
+++ b/src/compiler/scala/tools/nsc/interpreter/JLineReader.scala
@@ -1,28 +1,34 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author Stepan Koltsov
  */
-// $Id: JLineReader.scala 16894 2009-01-13 13:09:41Z cunei $
 
+package scala.tools.nsc
+package interpreter
 
-package scala.tools.nsc.interpreter
 import java.io.File
+import jline.{ ConsoleReader, ArgumentCompletor, History => JHistory }
 
 /** Reads from the console using JLine */
-class JLineReader extends InteractiveReader {
+class JLineReader(interpreter: Interpreter) extends InteractiveReader {
+  def this() = this(null)
+  
+  override lazy val history = Some(History(consoleReader))
+  override lazy val completion = Option(interpreter) map (x => new Completion(x))
+  
   val consoleReader = {
-    val history = try {
-      new jline.History(new File(System.getProperty("user.home"), ".scala_history"))
-    } catch {
-      // do not store history if error
-      case _ => new jline.History()
-    }
     val r = new jline.ConsoleReader()
-    r.setHistory(history)
-    r.setBellEnabled(false)
+    r setHistory (History().jhistory)
+    r setBellEnabled false 
+    completion foreach { c =>
+      r addCompletor c.jline
+      r setAutoprintThreshhold 250
+    }
+
     r
   }
-  def readOneLine(prompt: String) = consoleReader.readLine(prompt) 
+  
+  def readOneLine(prompt: String) = consoleReader readLine prompt
   val interactive = true
 }
 
diff --git a/src/compiler/scala/tools/nsc/interpreter/Parsed.scala b/src/compiler/scala/tools/nsc/interpreter/Parsed.scala
new file mode 100644
index 0000000..9808a92
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/interpreter/Parsed.scala
@@ -0,0 +1,68 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
+ * @author Paul Phillips
+ */
+ 
+package scala.tools.nsc
+package interpreter
+
+import jline.ArgumentCompletor.{ ArgumentDelimiter, ArgumentList }
+import util.returning
+
+/** One instance of a command buffer.
+ */
+class Parsed private (
+  val buffer: String,
+  val cursor: Int,
+  val delimited: Char => Boolean
+) extends Delimited {
+  def isEmpty       = args.isEmpty
+  def isUnqualified = args.size == 1
+  def isQualified   = args.size > 1
+  def isAtStart     = cursor <= 0
+  
+  private var _verbosity = 0
+  def verbosity = _verbosity
+  def withVerbosity(v: Int): this.type = returning[this.type](this)(_ => _verbosity = v)
+
+  def args = toArgs(buffer take cursor).toList
+  def bufferHead = args.head
+  def headLength = bufferHead.length + 1
+  def bufferTail = new Parsed(buffer drop headLength, cursor - headLength, delimited) withVerbosity verbosity
+  
+  def prev = new Parsed(buffer, cursor - 1, delimited) withVerbosity verbosity
+  def next = new Parsed(buffer, cursor + 1, delimited) withVerbosity verbosity
+  def currentChar = buffer(cursor)
+  def currentArg = args.last
+  def position =
+    if (isEmpty) 0
+    else if (isLastDelimiter) cursor
+    else cursor - currentArg.length
+  
+  def isFirstDelimiter  = !isEmpty && isDelimiterChar(buffer.head)
+  def isLastDelimiter   = !isEmpty && isDelimiterChar(buffer.last)
+  def firstIfDelimiter  = if (isFirstDelimiter) buffer.head.toString else ""
+  def lastIfDelimiter   = if (isLastDelimiter) buffer.last.toString else ""
+  
+  def isQuoted = false // TODO
+  def isEscaped = !isAtStart && isEscapeChar(currentChar) && !isEscapeChar(prev.currentChar)
+  def isDelimiter = !isQuoted && !isEscaped && isDelimiterChar(currentChar)  
+  
+  def asJlineArgumentList =
+    if (isEmpty) new ArgumentList(Array[String](), 0, 0, cursor)
+    else new ArgumentList(args.toArray, args.size - 1, currentArg.length, cursor)
+  
+  override def toString = "Parsed(%s / %d)".format(buffer, cursor)
+}
+
+object Parsed {
+  def apply(s: String): Parsed = apply(onull(s), onull(s).length)
+  def apply(s: String, cursor: Int): Parsed = apply(onull(s), cursor, "{},`; \t" contains _)
+  def apply(s: String, cursor: Int, delimited: Char => Boolean): Parsed =
+    new Parsed(onull(s), cursor, delimited)
+
+  def dotted(s: String): Parsed = dotted(onull(s), onull(s).length)
+  def dotted(s: String, cursor: Int): Parsed = new Parsed(onull(s), cursor, _ == '.')
+  
+  def undelimited(s: String, cursor: Int): Parsed = new Parsed(onull(s), cursor, _ => false)
+}
diff --git a/src/compiler/scala/tools/nsc/interpreter/ProductCompletion.scala b/src/compiler/scala/tools/nsc/interpreter/ProductCompletion.scala
new file mode 100644
index 0000000..2bccd3a
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/interpreter/ProductCompletion.scala
@@ -0,0 +1,44 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
+ * @author Paul Phillips
+ */
+ 
+package scala.tools.nsc
+package interpreter
+
+class SeqCompletion[T](elems: Seq[T]) extends CompletionAware {  
+  lazy val completions = elems.indices.toList map ("(%d)" format _)
+  def completions(verbosity: Int) = completions
+  private def elemAt(name: String) =
+    if (completions contains name) Some(elems(name drop 1 dropRight 1 toInt)) else None
+  
+  override def execute(name: String) = elemAt(name)
+  override def follow(name: String) = elemAt(name) map (x => ProductCompletion(x))
+}
+
+/** TODO - deal with non-case products by giving them _1 _2 etc. */
+class ProductCompletion(root: Product) extends CompletionAware {
+  lazy val caseFields: List[Any] = root.productIterator.toList
+  lazy val caseNames: List[String] = ByteCode caseParamNamesForPath root.getClass.getName getOrElse Nil
+  private def isValid = caseFields.length == caseNames.length
+  
+  private def fieldForName(s: String) = (completions indexOf s) match {
+    case idx if idx > -1 && isValid => Some(caseFields(idx))
+    case _                          => None
+  }
+
+  lazy val completions = caseNames
+  def completions(verbosity: Int) = completions
+  override def execute(name: String) = fieldForName(name)    
+  override def follow(name: String) = fieldForName(name) map (x => ProductCompletion(x))
+}
+
+object ProductCompletion {
+  /** TODO: other traversables. */
+  def apply(elem: Any): CompletionAware = elem match {
+    case x: Seq[_]    => new SeqCompletion[Any](x)
+    case x: Product   => new ProductCompletion(x)
+    // case x: Map[_, _] =>
+    case _            => CompletionAware.Empty
+  }
+}
diff --git a/src/compiler/scala/tools/nsc/interpreter/ReflectionCompletion.scala b/src/compiler/scala/tools/nsc/interpreter/ReflectionCompletion.scala
new file mode 100644
index 0000000..5e69fcb
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/interpreter/ReflectionCompletion.scala
@@ -0,0 +1,112 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
+ * @author Paul Phillips
+ */
+ 
+package scala.tools.nsc
+package interpreter
+
+import java.lang.reflect
+import reflect.{ Modifier, AccessibleObject }
+import Modifier.{ isPrivate, isProtected, isStatic }
+import scala.reflect.NameTransformer
+import scala.collection.mutable.HashMap
+import ReflectionCompletion._
+
+trait ReflectionCompletion extends CompletionAware {
+  def clazz: Class[_]
+  protected def visibleMembers: List[AccessibleObject]
+  protected def memberCompletions = visibleMembers filter isPublic map reflectName
+  
+  def reflectName(m: AccessibleObject) = m match {
+    case x: reflect.Method  => x.getName
+    case x: reflect.Field   => x.getName
+    case x                  => error(x.toString)
+  }
+  def isPublic(m: AccessibleObject) = m match {
+    case x: reflect.Method  => Modifier isPublic x.getModifiers
+    case x: reflect.Field   => Modifier isPublic x.getModifiers
+    case x                  => error(x.toString)
+  }    
+  
+  lazy val (staticMethods, instanceMethods) = clazz.getMethods.toList partition (x => isStatic(x.getModifiers))
+  lazy val (staticFields, instanceFields) = clazz.getFields.toList partition (x => isStatic(x.getModifiers))  
+  
+  /** Oops, mirror classes don't descend from scalaobject.
+   */
+  def isScalaClazz(cl: Class[_]) = {
+    (allInterfacesFor(cl) exists (_.getName == "scala.ScalaObject")) ||
+    (classForName(cl.getName + "$").isDefined)
+  }
+  def allInterfacesFor(cl: Class[_]): List[Class[_]] = allInterfacesFor(cl, Nil)
+
+  private def allInterfacesFor(cl: Class[_], acc: List[Class[_]]): List[Class[_]] = {
+    if (cl == null) acc.distinct
+    else allInterfacesFor(cl.getSuperclass, acc ::: cl.getInterfaces.toList)
+  }
+}
+
+/** A completion aware object representing a single instance of some class.
+ *  It completes to instance fields and methods, and delegates to another
+ *  InstanceCompletion object if it can determine the result type of the element.
+ */
+class InstanceCompletion(val clazz: Class[_]) extends ReflectionCompletion {  
+  protected def visibleMembers = instanceMethods ::: instanceFields
+  def extras = List("isInstanceOf", "asInstanceOf", "toString")
+  lazy val completions = memberCompletions ::: extras
+  def completions(verbosity: Int) = completions
+
+  val (zeroArg, otherArg) = instanceMethods partition (_.getParameterTypes.size == 0)
+  override def follow(id: String) = {
+    val nextClazz = zeroArg find (m => m.getName == id) map (_.getReturnType)
+    if (nextClazz.isDefined) nextClazz map (x => new InstanceCompletion(x))
+    else instanceFields find (_.getName == id) map (x => new InstanceCompletion(x.getType))
+  }
+}
+
+/** The complementary class to InstanceCompletion.  It has logic to deal with
+ *  java static members and scala companion object members.
+ */
+class StaticCompletion(val clazz: Class[_]) extends ReflectionCompletion {
+  protected def visibleMembers = whichMethods ::: whichFields
+  lazy val completions = memberCompletions
+  def completions(verbosity: Int) = completions
+  
+  private def aliasForPath(path: String) = ByteCode aliasForType path flatMap (x => classForName(x + "$"))
+  def className = clazz.getName
+  def isJava = !isScalaClazz(clazz)
+
+  private def whichMethods = if (isJava) staticMethods else instanceMethods
+  private def whichFields = if (isJava) staticFields else instanceFields
+  val (zeroArg, otherArg) = whichMethods partition (_.getParameterTypes.size == 0)  
+  
+  override def follow(id: String) = {
+    val nextClazz = zeroArg find (m => m.getName == id) map (_.getReturnType)
+    if (nextClazz.isDefined) nextClazz map (x => new InstanceCompletion(x))
+    else staticFields find (_.getName == id) map (x => new InstanceCompletion(x.getType))
+  }
+
+  override def toString = "StaticCompletion(%s) => %s".format(clazz.getName, completions)
+}
+
+object ReflectionCompletion {
+  import java.io.File
+  import java.util.jar.{ JarEntry, JarFile }
+  import scala.tools.nsc.io.Streamable
+
+  // XXX at the moment this is imperfect because scala's protected semantics
+  // differ from java's, so protected methods appear public via reflection;
+  // yet scala enforces the protection.  The result is that protected members
+  // appear in completion yet cannot actually be called.  Fixing this 
+  // properly requires a scala.reflect.* API.  Fixing it uglily is possible
+  // too (cast to structural type!) but I deem poor use of energy.
+  private def skipModifiers(m: reflect.Method) = {
+    import java.lang.reflect.Modifier._
+    val flags = STATIC | PRIVATE | PROTECTED
+    (m.getModifiers & flags) == 0
+  }
+  private def getAnyClass(x: Any): Class[_] = x.asInstanceOf[AnyRef].getClass
+
+  def methodsOf(target: Any): List[String] =
+    getAnyClass(target).getMethods filter skipModifiers map (_.getName) toList
+}
diff --git a/src/compiler/scala/tools/nsc/interpreter/SimpleReader.scala b/src/compiler/scala/tools/nsc/interpreter/SimpleReader.scala
index cd1cc69..77f13a5 100644
--- a/src/compiler/scala/tools/nsc/interpreter/SimpleReader.scala
+++ b/src/compiler/scala/tools/nsc/interpreter/SimpleReader.scala
@@ -1,12 +1,13 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author Stepan Koltsov
  */
-// $Id: SimpleReader.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.tools.nsc.interpreter
-import java.io.{BufferedReader, PrintWriter}
+package scala.tools.nsc
+package interpreter
 
+import java.io.{ BufferedReader, PrintWriter }
+import io.{ Path, File, Directory }
 
 /** Reads using standard JDK API */
 class SimpleReader(
@@ -15,8 +16,10 @@ class SimpleReader(
   val interactive: Boolean)
 extends InteractiveReader {
   def this() = this(Console.in, new PrintWriter(Console.out), true)
+  def this(in: File, out: PrintWriter, interactive: Boolean) = this(in.bufferedReader(), out, interactive)
 
-  def readOneLine(prompt: String) = {
+  def close() = in.close()
+  def readOneLine(prompt: String): String = {
     if (interactive) {
       out.print(prompt)
       out.flush()
diff --git a/src/compiler/scala/tools/nsc/interpreter/XMLCompletion.scala b/src/compiler/scala/tools/nsc/interpreter/XMLCompletion.scala
new file mode 100644
index 0000000..67249a8
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/interpreter/XMLCompletion.scala
@@ -0,0 +1,44 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
+ * @author Paul Phillips
+ */
+ 
+package scala.tools.nsc
+package interpreter
+
+import xml.{ XML, Group, Node, NodeSeq }
+import XMLCompletion._
+import scala.collection.mutable.HashMap
+
+class XMLCompletion(root: Node) extends CompletionAware {  
+  private val nodeCache = new HashMap[String, Node]
+  private def getNode(s: String): Option[Node] = {
+    completions // make sure cache is populated
+    nodeCache get s
+  }
+  
+  lazy val completions: List[String] = {
+    def children = root.child.toList
+    def uniqueTags = children groupBy (_.label) filter (_._2.size == 1) map (_._1)
+    val uniqs = uniqueTags.toList
+    
+    children.foldLeft(List[String]())((res, node) => {
+      val name = node.label
+      def count = res filter (_ startsWith (name + "[")) size  // ]
+      val suffix = if (uniqs contains name) "" else "[%d]" format (count + 1)
+      val s = name + suffix
+      
+      nodeCache(s) = node
+      
+      s :: res
+    }).sorted
+  }
+  def completions(verbosity: Int) = completions
+  
+  override def execute(id: String)  = getNode(id)
+  override def follow(id: String)   = getNode(id) map (x => new XMLCompletion(x))
+}
+
+object XMLCompletion {
+  def apply(x: Node) = new XMLCompletion(x)
+}
diff --git a/src/compiler/scala/tools/nsc/interpreter/package.scala b/src/compiler/scala/tools/nsc/interpreter/package.scala
new file mode 100644
index 0000000..c10477d
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/interpreter/package.scala
@@ -0,0 +1,30 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
+ * @author Paul Phillips
+ */
+ 
+package scala.tools.nsc
+
+package object interpreter {
+  /** Tracing */
+  def tracing[T](msg: String)(x: T): T = { println("(" + msg + ") " + x) ; x }
+  
+  /** Frequency counter */
+  def freq[T](seq: Seq[T]) = seq groupBy identity mapValues (_.length)
+  
+  /** null becomes "", otherwise identity */
+  def onull(s: String) = if (s == null) "" else s
+  
+  /** Heuristically strip interpreter wrapper prefixes
+   *  from an interpreter output string.
+   */
+  def stripWrapperGunk(str: String): String = {
+    val wrapregex = """(line[0-9]+\$object[$.])?(\$iw[$.])*"""
+    str.replaceAll(wrapregex, "")
+  }
+  
+  /** Class objects */
+  def classForName(name: String): Option[Class[_]] =
+    try Some(Class forName name)
+    catch { case _: ClassNotFoundException | _: SecurityException => None }  
+}
diff --git a/src/compiler/scala/tools/nsc/io/AbstractFile.scala b/src/compiler/scala/tools/nsc/io/AbstractFile.scala
index 55f230d..e8faf34 100644
--- a/src/compiler/scala/tools/nsc/io/AbstractFile.scala
+++ b/src/compiler/scala/tools/nsc/io/AbstractFile.scala
@@ -1,14 +1,15 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: AbstractFile.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.tools.nsc.io
+package scala.tools.nsc
+package io
 
-import java.io.{File, FileOutputStream, IOException, InputStream, OutputStream}
+import java.io.{ File => JFile, FileOutputStream, IOException, InputStream, OutputStream, BufferedOutputStream }
 import java.net.URL
+import PartialFunction._
 
 import scala.collection.mutable.ArrayBuffer
 
@@ -16,21 +17,21 @@ import scala.collection.mutable.ArrayBuffer
  * @author Philippe Altherr
  * @version 1.0, 23/03/2004
  */
-object AbstractFile {
-
+object AbstractFile
+{
   /** Returns "getFile(new File(path))". */
-  def getFile(path: String): AbstractFile = getFile(new File(path))
+  def getFile(path: String): AbstractFile = getFile(Path(path))
+  def getFile(path: Path): AbstractFile = getFile(path.toFile)
 
   /**
    * If the specified File exists and is a regular file, returns an
    * abstract regular file backed by it. Otherwise, returns <code>null</code>.
    */
   def getFile(file: File): AbstractFile =
-    if (file.isFile() && file.exists()) new PlainFile(file) else null
-
+    if (file.isFile) new PlainFile(file) else null
 
   /** Returns "getDirectory(new File(path))". */
-  def getDirectory(path: String): AbstractFile = getDirectory(new File(path))
+  def getDirectory(path: Path): AbstractFile = getDirectory(path.toFile)
 
   /**
    * If the specified File exists and is either a directory or a
@@ -40,15 +41,10 @@ object AbstractFile {
    * @param file ...
    * @return     ...
    */
-  def getDirectory(file: File): AbstractFile = {
-    if (file.isDirectory() && file.exists()) return new PlainFile(file)
-    if (file.isFile() && file.exists()) {
-      val path = file.getPath()
-      if (path.endsWith(".jar") || path.endsWith(".zip"))
-        return ZipArchive.fromFile(file);
-    }
-    null
-  }
+  def getDirectory(file: File): AbstractFile =
+    if (file.isDirectory) new PlainFile(file)
+    else if (file.isFile && Path.isJarOrZip(file)) ZipArchive fromFile file
+    else null
 
   /**
    * If the specified URL exists and is a readable zip or jar archive,
@@ -59,15 +55,7 @@ object AbstractFile {
    * @return     ...
    */
   def getURL(url: URL): AbstractFile =
-    if (url ne null) {
-      val path = url.getPath()
-      if (path.endsWith(".jar") || path.endsWith(".zip"))
-        ZipArchive.fromURL(url)
-      else
-        null
-    }
-    else
-      null
+    Option(url) collect { case url: URL if Path.isJarOrZip(url.getPath) => ZipArchive fromURL url } orNull
 }
 
 /**
@@ -101,12 +89,34 @@ abstract class AbstractFile extends AnyRef with Iterable[AbstractFile] {
 
   /** Returns the path of this abstract file. */
   def path: String
+  
+  /** Checks extension case insensitively. */
+  def hasExtension(other: String) = Path(path) hasExtension other
+
+  /** The absolute file, if this is a relative file. */
+  def absolute: AbstractFile
 
   /** Returns the containing directory of this abstract file */
   def container : AbstractFile
   
   /** Returns the underlying File if any and null otherwise. */
-  def file: File
+  def file: JFile
+  def sfile = Option(file) map (x => File(x)) // XXX
+  
+  /** An underlying source, if known.  Mostly, a zip/jar file. */
+  def underlyingSource: Option[AbstractFile] = None
+
+  /** Does this abstract file denote an existing file? */
+  def exists: Boolean = (file eq null) || file.exists
+
+  /** Does this abstract file represent something which can contain classfiles? */
+  def isClassContainer = isDirectory || (sfile exists (Path isJarOrZip _))
+
+  /** Create a file on disk, if one does not exist already. */
+  def create: Unit
+
+  /** Delete the underlying file or directory (recursively). */
+  def delete: Unit
 
   /** Is this abstract file a directory? */
   def isDirectory: Boolean
@@ -119,6 +129,9 @@ abstract class AbstractFile extends AnyRef with Iterable[AbstractFile] {
   
   /** Returns an output stream for writing the file */
   def output: OutputStream
+  
+  /** Returns a buffered output stream for writing the file - defaults to out */
+  def bufferedOutput: BufferedOutputStream = new BufferedOutputStream(output)
 
   /** size of this file if it is a concrete file. */
   def sizeOption: Option[Int] = None
@@ -151,7 +164,7 @@ abstract class AbstractFile extends AnyRef with Iterable[AbstractFile] {
   }
 
   /** Returns all abstract subfiles of this abstract directory. */
-  def elements: Iterator[AbstractFile]
+  def iterator: Iterator[AbstractFile]
 
   /** Returns the abstract file in this abstract directory with the specified
    *  name. If there is no such file, returns <code>null</code>. The argument
@@ -164,6 +177,11 @@ abstract class AbstractFile extends AnyRef with Iterable[AbstractFile] {
    */
   def lookupName(name: String, directory: Boolean): AbstractFile
 
+  /** Returns an abstract file with the given name. It does not
+   *  check that it exists.
+   */
+  def lookupNameUnchecked(name: String, directory: Boolean): AbstractFile
+
   /** Returns the abstract file in this abstract directory with the specified
    *  path relative to it, If there is no such file, returns null. The argument
    *  <code>directory</code> tells whether to look for a directory or a regular
@@ -174,16 +192,31 @@ abstract class AbstractFile extends AnyRef with Iterable[AbstractFile] {
    *  @return          ...
    */
   def lookupPath(path: String, directory: Boolean): AbstractFile = {
+    lookup((f, p, dir) => f.lookupName(p, dir), path, directory)
+  }
+
+  /** Return an abstract file that does not check that `path' denotes
+   *  an existing file.
+   */
+  def lookupPathUnchecked(path: String, directory: Boolean): AbstractFile = {
+    lookup((f, p, dir) => f.lookupNameUnchecked(p, dir), path, directory)
+  }
+
+  private def lookup(getFile: (AbstractFile, String, Boolean) => AbstractFile,
+                     path0: String,
+                     directory: Boolean): AbstractFile = {    
+    val separator = JFile.separatorChar
+    // trim trailing '/'s
+    val path: String = if (path0.last == separator) path0 dropRight 1 else path0
     val length = path.length()
-    val separator = File.separatorChar
-    assert(0 < length && path.lastIndexOf(separator) < length - 1, path)
+    assert(length > 0 && !(path.last == separator), path)
     var file = this
     var start = 0
     while (true) {
       val index = path.indexOf(separator, start)
       assert(index < 0 || start < index)
       val name = path.substring(start, if (index < 0) length else index)
-      file = file.lookupName(name, if (index < 0) directory else true)
+      file = getFile(file, name, if (index < 0) directory else true)
       if ((file eq null) || index < 0) return file
       start = index + 1
     }
@@ -195,15 +228,8 @@ abstract class AbstractFile extends AnyRef with Iterable[AbstractFile] {
    * creating an empty file if it does not already existing.
    */
   def fileNamed(name: String): AbstractFile = {
-    assert(isDirectory)
-    val existing = lookupName(name, false)
-    if (existing == null) {
-      val newFile = new File(file, name)
-      newFile.createNewFile()
-      new PlainFile(newFile)
-    } else {
-      existing
-    }
+    assert(isDirectory, "Tried to find '%s' in '%s' but it is not a directory".format(name, path))
+    Option(lookupName(name, false)) getOrElse new PlainFile((sfile.get / name).createFile())
   }
   
   /**
@@ -211,17 +237,13 @@ abstract class AbstractFile extends AnyRef with Iterable[AbstractFile] {
    * does not already exist.
    */
   def subdirectoryNamed(name: String): AbstractFile = {
-    assert (isDirectory)
-    val existing = lookupName(name, true)
-    if (existing == null) {
-      val dir = new File(file, name)
-      dir.mkdir()
-      new PlainFile(dir)
-    } else {
-      existing
-    }
+    assert (isDirectory, "Tried to find '%s' in '%s' but it is not a directory".format(name, path))
+    Option(lookupName(name, true)) getOrElse new PlainFile((sfile.get / name).createDirectory())
   }
   
+  protected def unsupported(): Nothing = unsupported(null)
+  protected def unsupported(msg: String): Nothing = throw new UnsupportedOperationException(msg)
+  
   /** Returns the path of this abstract file. */
   override def toString() = path
 
diff --git a/src/compiler/scala/tools/nsc/io/Directory.scala b/src/compiler/scala/tools/nsc/io/Directory.scala
new file mode 100644
index 0000000..0976aaf
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/io/Directory.scala
@@ -0,0 +1,87 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+package scala.tools.nsc
+package io
+
+import java.io.{ File => JFile }
+
+object Directory {
+  import scala.util.Properties.{ tmpDir, userHome, userDir }
+  
+  private def normalizePath(s: String) = Some(apply(Path(s).normalize))
+  def Current: Option[Directory]  = if (userDir == "") None else normalizePath(userDir)
+  def Home: Option[Directory]     = if (userHome == "") None else normalizePath(userHome)
+  def TmpDir: Option[Directory]   = if (tmpDir == "") None else normalizePath(tmpDir)
+    
+  def apply(path: Path): Directory = path.toDirectory
+  
+  // Like File.makeTemp but creates a directory instead
+  def makeTemp(prefix: String = Path.randomPrefix, suffix: String = null, dir: JFile = null): Directory = {
+    val path = File.makeTemp(prefix, suffix, dir)
+    path.delete()
+    path.createDirectory()
+  }
+}
+import Path._
+
+/** An abstraction for directories.
+ *
+ *  @author  Paul Phillips
+ *  @since   2.8
+ */
+class Directory(jfile: JFile) extends Path(jfile) {  
+  override def toAbsolute: Directory = if (isAbsolute) this else super.toAbsolute.toDirectory
+  override def toDirectory: Directory = this
+  override def toFile: File = new File(jfile)
+  override def isValid = jfile.isDirectory() || !jfile.exists()
+  override def normalize: Directory = super.normalize.toDirectory  
+  
+  /** An iterator over the contents of this directory.
+   */
+  def list: Iterator[Path] =
+    jfile.listFiles match {
+      case null   => Iterator.empty
+      case xs     => xs.iterator map Path.apply
+    }
+  
+  def dirs: Iterator[Directory] = list collect { case x: Directory => x }
+  def files: Iterator[File] = list collect { case x: File => x }
+  
+  override def walkFilter(cond: Path => Boolean): Iterator[Path] =
+    list filter cond flatMap (_ walkFilter cond)
+
+  def deepDirs: Iterator[Directory] = Path.onlyDirs(deepList())
+  def deepFiles: Iterator[File] = Path.onlyFiles(deepList())
+  
+  /** If optional depth argument is not given, will recurse
+   *  until it runs out of contents.
+   */
+  def deepList(depth: Int = -1): Iterator[Path] =
+    if (depth < 0) list ++ (dirs flatMap (_ deepList (depth)))
+    else if (depth == 0) Iterator.empty
+    else list ++ (dirs flatMap (_ deepList (depth - 1)))
+  
+  /** An iterator over the directories underneath this directory,
+   *  to the (optionally) given depth.
+   */
+  def subdirs(depth: Int = 1): Iterator[Directory] = 
+    deepList(depth) collect { case x: Directory => x }
+    
+  /** Deletes the directory recursively. Returns false on failure.
+   *  Use with caution!
+   */
+  def deleteRecursively(): Boolean = deleteRecursively(jfile)
+  private def deleteRecursively(f: JFile): Boolean = {
+    if (f.isDirectory) f.listFiles match { 
+      case null =>
+      case xs   => xs foreach deleteRecursively
+    }
+    f.delete()
+  }
+}
diff --git a/src/compiler/scala/tools/nsc/io/File.scala b/src/compiler/scala/tools/nsc/io/File.scala
new file mode 100644
index 0000000..a649621
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/io/File.scala
@@ -0,0 +1,157 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+package scala.tools.nsc
+package io
+
+import java.io.{ 
+  FileInputStream, FileOutputStream, BufferedReader, BufferedWriter, InputStreamReader, OutputStreamWriter, 
+  BufferedInputStream, BufferedOutputStream, IOException, PrintStream, File => JFile }
+import java.nio.channels.{ Channel, FileChannel }
+import scala.io.Codec
+
+object File {
+  def pathSeparator = JFile.pathSeparator
+  def separator = JFile.separator
+  
+  def apply(path: Path)(implicit codec: Codec) = new File(path.jfile)(codec)
+
+  // Create a temporary file
+  def makeTemp(prefix: String = Path.randomPrefix, suffix: String = null, dir: JFile = null) =
+    apply(JFile.createTempFile(prefix, suffix, dir))
+    
+  type Closeable = { def close(): Unit }
+  def closeQuietly(target: Closeable) {
+    try target.close() catch { case e: IOException => }
+  }
+  
+  // this is a workaround for http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6503430
+  // we are using a static initializer to statically initialize a java class so we don't
+  // trigger java.lang.InternalErrors later when using it concurrently.  We ignore all
+  // the exceptions so as not to cause spurious failures when no write access is available,
+  // e.g. google app engine.
+  try {
+    val tmp = JFile.createTempFile("bug6503430", null, null)
+    val in = new FileInputStream(tmp).getChannel()
+    val out = new FileOutputStream(tmp, true).getChannel()
+    out.transferFrom(in, 0, 0)
+    tmp.delete()
+  }
+  catch {
+    case _: IllegalArgumentException | _: IllegalStateException | _: IOException | _: SecurityException => ()
+  }
+}
+import File._
+import Path._
+
+/** An abstraction for files.  For character data, a Codec
+ *  can be supplied at either creation time or when a method
+ *  involving character data is called (with the latter taking
+ *  precedence if supplied.) If neither is available, the value
+ *  of scala.io.Codec.default is used.
+ *
+ *  @author  Paul Phillips
+ *  @since   2.8
+ */
+class File(jfile: JFile)(implicit constructorCodec: Codec) extends Path(jfile) with Streamable.Chars {
+  override val creationCodec = constructorCodec
+  def withCodec(codec: Codec): File = new File(jfile)(codec)
+
+  override def addExtension(ext: String): File = super.addExtension(ext).toFile
+  override def toAbsolute: File = if (isAbsolute) this else super.toAbsolute.toFile
+  override def toDirectory: Directory = new Directory(jfile)
+  override def toFile: File = this
+  override def normalize: File = super.normalize.toFile
+  override def isValid = jfile.isFile() || !jfile.exists()
+  override def length = super[Path].length
+  override def walkFilter(cond: Path => Boolean): Iterator[Path] =
+    if (cond(this)) Iterator.single(this) else Iterator.empty
+
+  /** Obtains an InputStream. */
+  def inputStream() = new FileInputStream(jfile)
+
+  /** Obtains a OutputStream. */
+  def outputStream(append: Boolean = false) = new FileOutputStream(jfile, append)
+  def bufferedOutput(append: Boolean = false) = new BufferedOutputStream(outputStream(append))
+  def printStream(append: Boolean = false) = new PrintStream(outputStream(append), true)
+
+  /** Obtains an OutputStreamWriter wrapped around a FileOutputStream.
+   *  This should behave like a less broken version of java.io.FileWriter,
+   *  in that unlike the java version you can specify the encoding.
+   */
+  def writer(): OutputStreamWriter = writer(false)
+  def writer(append: Boolean): OutputStreamWriter = writer(append, creationCodec)
+  def writer(append: Boolean, codec: Codec): OutputStreamWriter =
+    new OutputStreamWriter(outputStream(append), codec.charSet)
+  
+  /** Wraps a BufferedWriter around the result of writer().
+   */
+  def bufferedWriter(): BufferedWriter = bufferedWriter(false)
+  def bufferedWriter(append: Boolean): BufferedWriter = bufferedWriter(append, creationCodec)
+  def bufferedWriter(append: Boolean, codec: Codec): BufferedWriter =
+    new BufferedWriter(writer(append, codec))
+  
+  /** Creates a new file and writes all the Strings to it. */
+  def writeAll(strings: String*): Unit = {    
+    val out = bufferedWriter()
+    try strings foreach (out write _)
+    finally out close
+  }
+  
+  def appendAll(strings: String*): Unit = {
+    val out = bufferedWriter(append = true)
+    try strings foreach (out write _)
+    finally out close
+  }
+
+  def copyTo(destPath: Path, preserveFileDate: Boolean = false): Boolean = {
+    val CHUNK = 1024 * 1024 * 16  // 16 MB
+    val dest = destPath.toFile
+    if (!isValid) fail("Source %s is not a valid file." format name)
+    if (this.normalize == dest.normalize) fail("Source and destination are the same.")
+    if (!dest.parent.exists) fail("Destination cannot be created.")
+    if (dest.exists && !dest.canWrite) fail("Destination exists but is not writable.")
+    if (dest.isDirectory) fail("Destination exists but is a directory.")
+
+    lazy val in_s = inputStream()
+    lazy val out_s = dest.outputStream()
+    lazy val in = in_s.getChannel()
+    lazy val out = out_s.getChannel()
+
+    try {      
+      val size = in.size()
+      var pos, count = 0L
+      while (pos < size) {
+        count = (size - pos) min CHUNK
+        pos += out.transferFrom(in, pos, count)
+      }
+    }
+    finally List[Closeable](out, out_s, in, in_s) foreach closeQuietly
+    
+    if (this.length != dest.length)
+      fail("Failed to completely copy %s to %s".format(name, dest.name))
+    
+    if (preserveFileDate)
+      dest.lastModified = this.lastModified
+    
+    true
+  }
+  
+  /** Reflection since we're into the java 6+ API.
+   */
+  def setExecutable(executable: Boolean, ownerOnly: Boolean = true): Boolean = {
+    type JBoolean = java.lang.Boolean
+    val method =
+      try classOf[JFile].getMethod("setExecutable", classOf[Boolean], classOf[Boolean])
+      catch { case _: NoSuchMethodException => return false }
+    
+    try method.invoke(jfile, executable: JBoolean, ownerOnly: JBoolean).asInstanceOf[JBoolean].booleanValue
+    catch { case _: Exception => false }
+  }
+}
diff --git a/src/compiler/scala/tools/nsc/io/FileOperationException.scala b/src/compiler/scala/tools/nsc/io/FileOperationException.scala
new file mode 100644
index 0000000..2863a48
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/io/FileOperationException.scala
@@ -0,0 +1,13 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+package scala.tools.nsc
+package io
+
+case class FileOperationException(msg: String) extends RuntimeException(msg)
diff --git a/src/compiler/scala/tools/nsc/io/NullPrintStream.scala b/src/compiler/scala/tools/nsc/io/NullPrintStream.scala
new file mode 100644
index 0000000..9340796
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/io/NullPrintStream.scala
@@ -0,0 +1,19 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
+ * @author Paul Phillips
+ */
+
+package scala.tools.nsc
+package io
+
+import java.io.{ PrintStream, ByteArrayOutputStream }
+
+/** A sink for when you want to discard all output.
+ */
+class NullPrintStream extends PrintStream(new ByteArrayOutputStream()) { }
+
+object NullPrintStream extends NullPrintStream {
+  def setOut() = Console setOut this
+  def setErr() = Console setErr this
+  def setOutAndErr() = { setOut() ; setErr() }
+}
diff --git a/src/compiler/scala/tools/nsc/io/Path.scala b/src/compiler/scala/tools/nsc/io/Path.scala
new file mode 100644
index 0000000..be17ac2
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/io/Path.scala
@@ -0,0 +1,258 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
+ */
+
+package scala.tools.nsc
+package io
+
+import java.io.{ 
+  FileInputStream, FileOutputStream, BufferedReader, BufferedWriter, InputStreamReader, OutputStreamWriter, 
+  BufferedInputStream, BufferedOutputStream, RandomAccessFile, File => JFile }
+import java.net.{ URI, URL }
+import scala.util.Random.alphanumeric
+
+/** An abstraction for filesystem paths.  The differences between
+ *  Path, File, and Directory are primarily to communicate intent.
+ *  Since the filesystem can change at any time, there is no way to
+ *  reliably associate Files only with files and so on.  Any Path
+ *  can be converted to a File or Directory (and thus gain access to
+ *  the additional entity specific methods) by calling toFile or
+ *  toDirectory, which has no effect on the filesystem.
+ *
+ *  Also available are createFile and createDirectory, which attempt
+ *  to create the path in question.
+ *
+ *  @author  Paul Phillips
+ *  @since   2.8
+ */
+
+object Path
+{
+  private val ZipMagicNumber = List[Byte](80, 75, 3, 4)
+  
+  /** If examineFile is true, it will look at the first four bytes of the file
+   *  and see if the magic number indicates it may be a jar or zip.
+   */
+  private def magicNumberIsZip(f: Path) = f.isFile && (f.toFile.bytes().take(4).toList == ZipMagicNumber)
+  def isJarOrZip(f: Path): Boolean = isJarOrZip(f, false)
+  def isJarOrZip(f: Path, examineFile: Boolean): Boolean =
+    f.hasExtension("zip", "jar") || (examineFile && magicNumberIsZip(f))
+
+  // not certain these won't be problematic, but looks good so far
+  implicit def string2path(s: String): Path = apply(s)
+  implicit def jfile2path(jfile: JFile): Path = apply(jfile)
+    
+  // java 7 style, we don't use it yet
+  // object AccessMode extends Enumeration("AccessMode") {
+  //   val EXECUTE, READ, WRITE = Value
+  // }
+  // def checkAccess(modes: AccessMode*): Boolean = {
+  //   modes foreach {
+  //     case EXECUTE  => throw new Exception("Unsupported") // can't check in java 5
+  //     case READ     => if (!jfile.canRead()) return false
+  //     case WRITE    => if (!jfile.canWrite()) return false
+  //   }
+  //   true
+  // }
+  
+  def onlyDirs(xs: Iterator[Path]): Iterator[Directory] = xs filter (_.isDirectory) map (_.toDirectory)
+  def onlyDirs(xs: List[Path]): List[Directory] = xs filter (_.isDirectory) map (_.toDirectory)
+  def onlyFiles(xs: Iterator[Path]): Iterator[File] = xs filter (_.isFile) map (_.toFile)
+  def onlyFiles(xs: List[Path]): List[File] = xs filter (_.isFile) map (_.toFile)
+  
+  def roots: List[Path] = JFile.listRoots().toList map Path.apply
+
+  def apply(segments: Seq[String]): Path = apply(segments mkString JFile.separator)
+  def apply(path: String): Path = apply(new JFile(path))
+  def apply(jfile: JFile): Path =
+    if (jfile.isFile) new File(jfile)
+    else if (jfile.isDirectory) new Directory(jfile)
+    else new Path(jfile)
+
+  /** Avoiding any shell/path issues by only using alphanumerics. */
+  private[io] def randomPrefix = alphanumeric take 6 mkString
+  private[io] def fail(msg: String) = throw FileOperationException(msg)
+}
+import Path._
+
+/** The Path constructor is private so we can enforce some
+ *  semantics regarding how a Path might relate to the world.
+ */
+class Path private[io] (val jfile: JFile) {
+  val separator = JFile.separatorChar
+  val separatorStr = JFile.separator
+
+  // Validation: this verifies that the type of this object and the
+  // contents of the filesystem are in agreement.  All objects are
+  // valid except File objects whose path points to a directory and
+  // Directory objects whose path points to a file.
+  def isValid: Boolean = true
+
+  // conversions
+  def toFile: File = new File(jfile)
+  def toDirectory: Directory = new Directory(jfile)
+  def toAbsolute: Path = if (isAbsolute) this else Path(jfile.getAbsolutePath())
+  def toURI: URI = jfile.toURI()
+  def toURL: URL = toURI.toURL()
+  /** If this path is absolute, returns it: otherwise, returns an absolute
+   *  path made up of root / this.
+   */
+  def toAbsoluteWithRoot(root: Path) = if (isAbsolute) this else root.toAbsolute / this
+  
+  /** Creates a new Path with the specified path appended.  Assumes
+   *  the type of the new component implies the type of the result.
+   */  
+  def /(child: Path): Path = if (isEmpty) child else new Path(new JFile(jfile, child.path))
+  def /(child: Directory): Directory = /(child: Path).toDirectory
+  def /(child: File): File = /(child: Path).toFile
+  
+  /** If this path is a container, recursively iterate over its contents.
+   *  The supplied condition is a filter which is applied to each element,
+   *  with that branch of the tree being closed off if it is true.  So for
+   *  example if the condition is true for some subdirectory, nothing
+   *  under that directory will be in the Iterator; but otherwise each
+   *  file and subdirectory underneath it will appear.
+   */
+  def walkFilter(cond: Path => Boolean): Iterator[Path] =
+    if (isFile) toFile walkFilter cond
+    else if (isDirectory) toDirectory walkFilter cond
+    else Iterator.empty
+  
+  /** Equivalent to walkFilter(_ => false).
+   */
+  def walk: Iterator[Path] = walkFilter(_ => true)
+
+  // identity
+  def name: String = jfile.getName()
+  def path: String = jfile.getPath()
+  def normalize: Path = Path(jfile.getCanonicalPath())
+  def isRootPath: Boolean = roots exists (_ isSame this)
+  
+  def resolve(other: Path) = if (other.isAbsolute || isEmpty) other else /(other)
+  def relativize(other: Path) = {
+    assert(isAbsolute == other.isAbsolute, "Paths not of same type: "+this+", "+other)
+
+    def createRelativePath(baseSegs: List[String], otherSegs: List[String]) : String = {
+      (baseSegs, otherSegs) match {
+        case (b :: bs, o :: os) if b == o => createRelativePath(bs, os)
+        case (bs, os) => ((".."+separator)*bs.length)+os.mkString(separatorStr)
+      }
+    }
+  
+    Path(createRelativePath(segments, other.segments))
+  }
+  
+  // derived from identity
+  def root: Option[Path] = roots find (this startsWith _)
+  def segments: List[String] = (path split separator).toList filterNot (_.length == 0)
+  /**
+   * @return The path of the parent directory, or root if path is already root
+   */
+  def parent: Directory = path match {
+    case "" | "." => Directory("..")
+    case _        =>
+      // the only solution <-- a comment which could have used elaboration
+      if (segments.nonEmpty && segments.last == "..")
+        (path / "..").toDirectory
+      else jfile.getParent match {
+        case null =>
+          if (isAbsolute) toDirectory // it should be a root. BTW, don't need to worry about relative pathed root
+          else Directory(".")         // a dir under pwd
+        case x    =>
+          Directory(x)
+      }
+  }
+  def parents: List[Directory] = {
+    val p = parent
+    if (p isSame this) Nil else p :: p.parents
+  }
+  // if name ends with an extension (e.g. "foo.jpg") returns the extension ("jpg"), otherwise ""
+  def extension: String = (name lastIndexOf '.') match {
+    case -1   => ""
+    case idx  => name drop (idx + 1)
+  }
+  // compares against extensions in a CASE INSENSITIVE way.
+  def hasExtension(ext: String, exts: String*) = {
+    val xs = (ext +: exts) map (_.toLowerCase)
+    xs contains extension.toLowerCase
+  }
+  // returns the filename without the extension.
+  def stripExtension: String = name stripSuffix ("." + extension)
+  // returns the Path with the extension.
+  def addExtension(ext: String): Path = Path(path + "." + ext)
+  // changes the existing extension out for a new one
+  def changeExtension(ext: String): Path = Path((path stripSuffix extension) + ext)
+  
+  // conditionally execute
+  def ifFile[T](f: File => T): Option[T] = if (isFile) Some(f(toFile)) else None
+  def ifDirectory[T](f: Directory => T): Option[T] = if (isDirectory) Some(f(toDirectory)) else None
+
+  // Boolean tests
+  def canRead = jfile.canRead()
+  def canWrite = jfile.canWrite()
+  def exists = jfile.exists()  
+  def notExists = try !jfile.exists() catch { case ex: SecurityException => false }
+
+  def isFile = jfile.isFile()
+  def isDirectory = jfile.isDirectory()
+  def isAbsolute = jfile.isAbsolute()
+  def isHidden = jfile.isHidden()
+  def isSymlink = {    
+    val x = parent / name
+    x.normalize != x.toAbsolute
+  }
+  def isEmpty = path.length == 0 
+  
+  // Information
+  def lastModified = jfile.lastModified()
+  def lastModified_=(time: Long) = jfile setLastModified time // should use setXXX function?
+  def length = jfile.length()
+  
+  // Boolean path comparisons
+  def endsWith(other: Path) = segments endsWith other.segments
+  def startsWith(other: Path) = segments startsWith other.segments
+  def isSame(other: Path) = normalize == other.normalize
+  def isFresher(other: Path) = lastModified > other.lastModified
+
+  // creations
+  def createDirectory(force: Boolean = true, failIfExists: Boolean = false): Directory = {
+    val res = if (force) jfile.mkdirs() else jfile.mkdir()
+    if (!res && failIfExists && exists) fail("Directory '%s' already exists." format name)
+    else if (isDirectory) toDirectory
+    else new Directory(jfile)
+  }
+  def createFile(failIfExists: Boolean = false): File = {
+    val res = jfile.createNewFile()
+    if (!res && failIfExists && exists) fail("File '%s' already exists." format name)
+    else if (isFile) toFile
+    else new File(jfile)
+  }
+  
+  // deletions
+  def delete() = jfile.delete()
+  def deleteIfExists() = if (jfile.exists()) delete() else false
+  def truncate() =
+    isFile && {
+      val raf = new RandomAccessFile(jfile, "rw")
+      raf setLength 0
+      raf.close()
+      length == 0
+    }
+  
+  def touch(modTime: Long = System.currentTimeMillis) = {
+    createFile()
+    if (isFile)
+      lastModified = modTime
+  }
+
+  // todo
+  // def copyTo(target: Path, options ...): Boolean
+  // def moveTo(target: Path, options ...): Boolean
+  
+  override def toString() = path
+  override def equals(other: Any) = other match {
+    case x: Path  => path == x.path
+    case _        => false
+  }  
+  override def hashCode() = path.hashCode()
+}
diff --git a/src/compiler/scala/tools/nsc/io/PlainFile.scala b/src/compiler/scala/tools/nsc/io/PlainFile.scala
index b68e474..8b02d65 100644
--- a/src/compiler/scala/tools/nsc/io/PlainFile.scala
+++ b/src/compiler/scala/tools/nsc/io/PlainFile.scala
@@ -1,65 +1,62 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: PlainFile.scala 16881 2009-01-09 16:28:11Z cunei $
 
 
-package scala.tools.nsc.io
+package scala.tools.nsc
+package io
 
-import java.io.{File, FileInputStream, FileOutputStream, IOException}
+import java.io.{ File => JFile, FileInputStream, FileOutputStream, IOException }
+import PartialFunction._
 
 object PlainFile {
   /**
    * If the specified File exists, returns an abstract file backed
    * by it. Otherwise, returns null.
    */
-  def fromFile(file: File): AbstractFile =
-    if (file.exists()) new PlainFile(file) else null
-
+  def fromPath(file: Path): PlainFile =
+    if (file.exists) new PlainFile(file) else null
 }
 
 /** This class implements an abstract file backed by a File. 
  */
-class PlainFile(val file: File) extends AbstractFile {
-  private val fpath = try { file.getCanonicalPath }
-                      catch { case _: IOException => file.getAbsolutePath }
+class PlainFile(val givenPath: Path) extends AbstractFile {
+  assert(path ne null)
 
-  assert(file ne null)
-  assert(file.exists(), "non-existent file: " + file)
+  val file = givenPath.jfile
+  override def underlyingSource = Some(this)
+  
+  private val fpath = try givenPath.normalize catch { case _: IOException => givenPath.toAbsolute }
 
   /** Returns the name of this abstract file. */
-  def name = file.getName()
+  def name = givenPath.name
 
   /** Returns the path of this abstract file. */
-  def path = file.getPath()
-  
-  override def container : AbstractFile = new PlainFile(file.getParentFile)
-
-  override def input = new FileInputStream(file)
-  override def output = new FileOutputStream(file)
-  
-  override def sizeOption = Some(file.length.toInt)
+  def path = givenPath.path
+
+  /** The absolute file. */
+  def absolute = new PlainFile(givenPath.normalize)
+    
+  override def container: AbstractFile = new PlainFile(givenPath.parent)
+  override def input = givenPath.toFile.inputStream()
+  override def output = givenPath.toFile.outputStream()
+  override def sizeOption = Some(givenPath.length.toInt)
   
   override def hashCode(): Int = fpath.hashCode
-
   override def equals(that: Any): Boolean =
-    that.isInstanceOf[PlainFile] &&
-      fpath.equals(that.asInstanceOf[PlainFile].fpath)
+    cond(that) { case other: PlainFile  => fpath == other.fpath }
 
   /** Is this abstract file a directory? */
-  def isDirectory: Boolean = file.isDirectory()
+  def isDirectory: Boolean = givenPath.isDirectory
 
   /** Returns the time that this abstract file was last modified. */
-  def lastModified: Long = file.lastModified()
+  def lastModified: Long = givenPath.lastModified
 
   /** Returns all abstract subfiles of this abstract directory. */
-  def elements: Iterator[AbstractFile] = {
-    assert(isDirectory, "not a directory '" + this + "'")
-    val names: Array[String] = file.list()
-    if ((names eq null) || names.length == 0) Iterator.empty
-    else names.elements.map { name: String => new File(file, name) }
-      .filter(_.exists).map(file => new PlainFile(file))
+  def iterator: Iterator[AbstractFile] = {
+    if (!isDirectory) Iterator.empty
+    else givenPath.toDirectory.list filter (_.exists) map (new PlainFile(_))
   }
 
   /**
@@ -73,11 +70,22 @@ class PlainFile(val file: File) extends AbstractFile {
    * @return          ...
    */
   def lookupName(name: String, directory: Boolean): AbstractFile = {
-    //assert(isDirectory, "not a directory '" + this + "'")
-    val child = new File(file, name)
-    if (!child.exists() || (directory != child.isDirectory) ||
-        directory == child.isFile()) null
-    else new PlainFile(child)
+    val child = givenPath / name
+    if ((child.isDirectory && directory) || (child.isFile && !directory)) new PlainFile(child)
+    else null
   }
 
+  /** Does this abstract file denote an existing file? */
+  def create: Unit = if (!exists) givenPath.createFile()
+
+  /** Delete the underlying file or directory (recursively). */
+  def delete: Unit =
+    if (givenPath.isFile) givenPath.delete()
+    else if (givenPath.isDirectory) givenPath.toDirectory.deleteRecursively()
+
+  /** Returns a plain file with the given name. It does not
+   *  check that it exists.
+   */
+  def lookupNameUnchecked(name: String, directory: Boolean): AbstractFile =
+    new PlainFile(givenPath / name)
 }
diff --git a/src/compiler/scala/tools/nsc/io/Process.scala b/src/compiler/scala/tools/nsc/io/Process.scala
new file mode 100644
index 0000000..aeb083e
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/io/Process.scala
@@ -0,0 +1,201 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
+ */
+
+package scala.tools.nsc
+package io
+
+import concurrent.ThreadRunner
+import scala.annotation.tailrec
+import scala.util.Properties.{ isWin, isMac, lineSeparator }
+import scala.util.control.Exception.catching
+import java.lang.{ Process => JProcess, ProcessBuilder => JProcessBuilder }
+import java.io.{ IOException, InputStream, OutputStream, BufferedReader, InputStreamReader, PrintWriter, File => JFile }
+import java.util.concurrent.LinkedBlockingQueue
+
+/** The <code>Process</code> object contains convenience functions
+ *  for running external processes.
+ *
+ *  An example usage:
+ *  <pre>
+ *    io.Process("ls", cwd = io.File("/")) foreach println
+ *  </pre>
+ *
+ *  See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4109888
+ *  for a dated list of the many obstacles to a clean interface.
+ *
+ *  This is not finished!! Do not rely upon it yet.
+ * 
+ *  TODO - remove requirement that process complete before we 
+ *  can get an iterator.
+ *
+ *  @author   Paul Phillips
+ *  @since    2.8
+ */
+ 
+object Process
+{
+  def javaVmArguments: List[String] = {
+    import collection.JavaConversions._
+
+    java.lang.management.ManagementFactory.getRuntimeMXBean().getInputArguments().toList
+  }
+  lazy val runtime = Runtime.getRuntime()
+  
+  class Pipe[T](xs: Seq[T], stringify: T => String) {
+    def |(cmd: String): Seq[String] = {
+      val p = Process(cmd)
+      xs foreach (x => p.stdin println stringify(x))
+      p.stdin.close()
+      p.stdout.toList
+    }
+  }
+    
+  object Pipe {
+    /* After importing this implicit you can say for instance
+     *   xs | "grep foo" | "grep bar"
+     * and it will execute shells and pipe input/output.  You can
+     * also implicitly or explicitly supply a function which translates
+     * the opening sequence into Strings; if none is given toString is used.
+     *
+     * Also, once you use :sh in the repl, this is auto-imported.
+     */
+    implicit def seqToPipelinedProcess[T]
+      (xs: Seq[T])
+      (implicit stringify: T => String = (x: T) => x.toString): Pipe[T] =
+    {
+      new Pipe(xs, stringify)
+    }
+  }
+  
+  private[Process] class ProcessBuilder(val pb: JProcessBuilder) {
+    def this(cmd: String*) = this(new JProcessBuilder(cmd: _*))
+    def start() = new Process(() => pb.start())
+
+    def withOnlyEnv(env: Map[String, String]): this.type = {
+      pb.environment.clear()
+      withEnv(env)
+    }
+
+    def withEnv(env: Map[String,String]): this.type = {
+      if (env != null) {
+        val jmap = pb.environment()
+        for ((k, v) <- env) jmap.put(k, v)
+      }
+      this
+    }
+
+    def withCwd(cwd: Path): this.type = {
+      if (cwd != null)
+        pb directory cwd.jfile
+
+      this
+    }
+    def withRedirectedErrorStream(merged: Boolean): this.type = {
+      pb redirectErrorStream merged
+      this
+    }
+
+    override def toString() = "ProcessBuilder(%s)" format pb.command()
+  }
+  
+  // This can be fleshed out if more variations come up
+  private val shell: String => Array[String] =
+    if (isWin) Array("cmd.exe", "/C", _)
+    else Array("sh", "-c", _)
+  
+  /** Executes the given command line in a shell.
+   *
+   *  @param    command   the command line
+   *  @return             a Process object
+   */
+  def apply(
+    command: String,
+    env: Map[String, String] = null,
+    cwd: Path = null,
+    redirect: Boolean = false
+  ): Process =
+      exec(shell(command), env, cwd, redirect)
+
+  /** Executes the given command line.
+   *
+   *  @param    command   the command line
+   *  @return             a Process object
+   */
+  def exec(
+    command: Seq[String],
+    env: Map[String, String] = null,
+    cwd: Path = null,
+    redirect: Boolean = false
+  ): Process =
+      new ProcessBuilder(command: _*) withEnv env withCwd cwd withRedirectedErrorStream redirect start
+}
+import Process._
+
+class Process(processCreator: () => JProcess) extends Iterable[String] {
+  lazy val process = processCreator()
+  
+  def exitValue(): Option[Int] =
+    catching(classOf[IllegalThreadStateException]) opt process.exitValue()
+    
+  def waitFor() = process.waitFor()
+  def destroy() = process.destroy()
+  def rerun()   = new Process(processCreator)
+  
+  def slurp()   = _out.slurp()
+  def stdout    = iterator
+  def iterator  = _out.iterator
+  def stderr    = _err.iterator
+  lazy val stdin = new PrintWriter(_in, true)
+  
+  class StreamedConsumer(in: InputStream) extends Thread with Iterable[String] {
+    private val queue   = new LinkedBlockingQueue[String]
+    private val reader  = new BufferedReader(new InputStreamReader(in))
+    
+    private def finish() {
+      // make sure this thread is complete
+      join()
+    }
+    
+    def slurp(): String = {
+      finish()
+      queue.toArray map (_ + lineSeparator) mkString
+    }
+
+    def iterator = {
+      finish()
+      new Iterator[String] {
+        val it = queue.iterator()
+        def hasNext = it.hasNext
+        def next = it.next
+      }
+    }
+    override final def run() {
+      @tailrec def loop() {      
+        reader.readLine match { 
+          case null =>
+            reader.close()
+          case x    =>
+            queue put x
+            loop()
+        }
+      }
+      
+      try loop()
+      catch { case _: IOException => () }
+    }
+  }
+  
+  private val _err = createConsumer(process.getErrorStream)
+  private val _out = createConsumer(process.getInputStream)
+  private val _in  = process.getOutputStream()
+  
+  private def createConsumer(in: InputStream) = {
+    val t = new StreamedConsumer(in)
+    t.start()
+    t
+  }
+  
+  override def toString() = "Process(%s)" format process.toString()
+}
+
diff --git a/src/compiler/scala/tools/nsc/io/Socket.scala b/src/compiler/scala/tools/nsc/io/Socket.scala
new file mode 100644
index 0000000..4396d96
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/io/Socket.scala
@@ -0,0 +1,46 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
+ * @author  Paul Phillips
+ */
+
+package scala.tools.nsc
+package io
+
+import java.io.{ IOException, InputStreamReader, BufferedReader, PrintWriter }
+import java.net.{ URL, MalformedURLException }
+import java.net.{ InetAddress, Socket => JSocket }
+import scala.util.control.Exception._
+
+/** A skeletal only-as-much-as-I-need Socket wrapper.
+ */
+object Socket
+{
+  private val socketExceptions = List(classOf[IOException], classOf[SecurityException])
+  
+  class SocketBox(f: () => Socket) {
+    def either: Either[Throwable, Socket] = catching(socketExceptions: _*) either f()
+    def opt: Option[Socket] = catching(socketExceptions: _*) opt f()
+  } 
+  
+  def apply(host: InetAddress, port: Int) = new SocketBox(() => new Socket(new JSocket(host, port)))
+  def apply(host: String, port: Int) = new SocketBox(() => new Socket(new JSocket(host, port)))  
+}
+
+class Socket(jsocket: JSocket) {
+  def getOutputStream() = jsocket.getOutputStream()
+  def getInputStream() = jsocket.getInputStream()
+  def getPort() = jsocket.getPort()
+  def close() = jsocket.close()
+  
+  /** Creates an InputStream and applies the closure, automatically closing it on completion.
+   */
+  def applyReaderAndWriter[T](f: (BufferedReader, PrintWriter) => T): T = {
+    val out = new PrintWriter(getOutputStream(), true)
+    val in = new BufferedReader(new InputStreamReader(getInputStream()))
+    try f(in, out)
+    finally {
+      in.close()
+      out.close()
+    }
+  }  
+}
\ No newline at end of file
diff --git a/src/compiler/scala/tools/nsc/io/SourceReader.scala b/src/compiler/scala/tools/nsc/io/SourceReader.scala
index cce8717..c5cf660 100644
--- a/src/compiler/scala/tools/nsc/io/SourceReader.scala
+++ b/src/compiler/scala/tools/nsc/io/SourceReader.scala
@@ -1,13 +1,13 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: SourceReader.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.tools.nsc.io
+package scala.tools.nsc
+package io
 
-import java.io.{File, FileInputStream, InputStream, IOException}
+import java.io.{ FileInputStream, InputStream, IOException, File => JFile }
 import java.nio.{ByteBuffer, CharBuffer}
 import java.nio.channels.{FileChannel, ReadableByteChannel, Channels}
 import java.nio.charset.{CharsetDecoder, CoderResult}
@@ -28,7 +28,7 @@ class SourceReader(decoder: CharsetDecoder, reporter: Reporter) {
   private var chars: CharBuffer = CharBuffer.allocate(0x4000)
 
   private def reportEncodingError(filename:String) = {
-    reporter.error(nsc.util.NoPosition, 
+    reporter.error(util.NoPosition, 
                    "IO error while decoding "+filename+" with "+decoder.charset()+"\n"+
                    "Please try specifying another one using the -encoding option")
   }
@@ -37,10 +37,10 @@ class SourceReader(decoder: CharsetDecoder, reporter: Reporter) {
   // Public Methods
 
   /** Reads the file with the specified name. */
-  def read(filename: String): Array[Char]= read(new File(filename))
+  def read(filename: String): Array[Char]= read(new JFile(filename))
 
   /** Reads the specified file. */
-  def read(file: File): Array[Char] = {
+  def read(file: JFile): Array[Char] = {
     val c = new FileInputStream(file).getChannel
     try {
       read(c)
@@ -64,23 +64,19 @@ class SourceReader(decoder: CharsetDecoder, reporter: Reporter) {
       case p:PlainFile =>
         read(p.file)                                                     // bq: (!!!)
       case z:ZipArchive#FileEntry => 
-        val c = Channels.newChannel(z.getArchive.getInputStream(z.entry))
+        val c = Channels.newChannel(z.archive.getInputStream(z.entry))
         read(c)
       case _ =>
-        throw new IOException(file.toString()+" is neither plain file nor ZipArchive#FileEntry")
+        val b = ByteBuffer.wrap(file.toByteArray)
+        try {
+          read(b)
+        } catch {
+          case e:Exception =>
+            if (true) e.printStackTrace
+            reportEncodingError(file.toString())
+            new Array[Char](0)
+        }
     }
-    /*
-    val decoder: CharsetDecoder = this.decoder.reset();
-    val bytes: ByteBuffer = ByteBuffer.wrap(file.read);
-    val chars: CharBuffer = this.chars; chars.clear();
-    try {
-      terminate(flush(decoder, decode(decoder, bytes, chars, true)));
-    } catch {
-      case e:Exception => 
-        reportEncodingError(file.toString())
-        new Array[Char](0)
-    }
-    */
   }
 
   /** Reads the specified byte channel. */
@@ -97,6 +93,13 @@ class SourceReader(decoder: CharsetDecoder, reporter: Reporter) {
     terminate(flush(decoder, chars))
   }
 
+  /** Reads the specified byte buffer. */
+  protected def read(bytes: ByteBuffer): Array[Char] = {
+    val decoder: CharsetDecoder = this.decoder.reset()
+    val chars: CharBuffer = this.chars; chars.clear()
+    terminate(flush(decoder, decode(decoder, bytes, chars, true)))
+  }
+
   //########################################################################
   // Private Methods
 
diff --git a/src/compiler/scala/tools/nsc/io/Streamable.scala b/src/compiler/scala/tools/nsc/io/Streamable.scala
new file mode 100644
index 0000000..e6cb958
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/io/Streamable.scala
@@ -0,0 +1,109 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
+ */
+
+package scala.tools.nsc
+package io
+
+import java.net.{ URI, URL }
+import java.io.{ BufferedInputStream, InputStream, PrintStream, File => JFile }
+import java.io.{ BufferedReader, InputStreamReader }
+import scala.io.{ Codec, BufferedSource, Source }
+
+import collection.mutable.ArrayBuffer
+import Path.fail
+
+/** Traits for objects which can be represented as Streams.
+ *
+ *  @author Paul Phillips
+ *  @since  2.8
+ */
+
+object Streamable
+{
+  /** Traits which can be viewed as a sequence of bytes.  Source types
+   *  which know their length should override def length: Long for more
+   *  efficient method implementations.
+   */
+  trait Bytes {
+    def inputStream(): InputStream
+    def length: Long = -1
+    
+    def bufferedInput() = new BufferedInputStream(inputStream())
+    def bytes(): Iterator[Byte] = bytesAsInts() map (_.toByte)
+    def bytesAsInts(): Iterator[Int] = {
+      val in = bufferedInput()
+      Iterator continually in.read() takeWhile (_ != -1)
+    }
+
+    /** This method aspires to be the fastest way to read
+     *  a stream of known length into memory.
+     */
+    def toByteArray(): Array[Byte] = {
+      // if we don't know the length, fall back on relative inefficiency
+      if (length == -1L)
+        return (new ArrayBuffer[Byte]() ++= bytes()).toArray
+      
+      val arr = new Array[Byte](length.toInt)
+      val len = arr.length
+      lazy val in = bufferedInput()
+      var offset = 0
+    
+      def loop() {
+        if (offset < len) {
+          val read = in.read(arr, offset, len - offset)
+          if (read >= 0) {
+            offset += read
+            loop()
+          }
+        }
+      }
+      try loop()
+      finally in.close()
+    
+      if (offset == arr.length) arr
+      else fail("Could not read entire source (%d of %d bytes)".format(offset, len))
+    }
+  }
+
+  /** For objects which can be viewed as Chars.
+   */
+  trait Chars extends Bytes {
+    /** Calls to methods requiring byte<->char transformations should be offered
+     *  in a form which allows specifying the codec.  When it is not specified,
+     *  the one discovered at creation time will be used, which will always find the
+     *  one in scala.io.Codec if no other is available.  This can be overridden
+     *  to use a different default.
+     */
+    def creationCodec: Codec = implicitly[Codec]
+
+    def chars(): BufferedSource = chars(creationCodec)
+    def chars(codec: Codec): BufferedSource = Source.fromInputStream(inputStream())(codec)
+    
+    def lines(): Iterator[String] = lines(creationCodec)
+    def lines(codec: Codec): Iterator[String] = chars(codec).getLines()
+  
+    /** Obtains an InputStreamReader wrapped around a FileInputStream.
+     */
+    def reader(): InputStreamReader = reader(creationCodec)
+    def reader(codec: Codec): InputStreamReader = new InputStreamReader(inputStream, codec.charSet)
+  
+    /** Wraps a BufferedReader around the result of reader().
+     */
+    def bufferedReader(): BufferedReader = bufferedReader(creationCodec)
+    def bufferedReader(codec: Codec) = new BufferedReader(reader(codec))
+    
+    /** Creates a BufferedReader and applies the closure, automatically closing it on completion.
+     */
+    def applyReader[T](f: BufferedReader => T): T = {
+      val in = bufferedReader()
+      try f(in)
+      finally in.close()
+    }
+  
+    /** Convenience function to import entire file into a String.
+     */
+    def slurp(): String = slurp(creationCodec)
+    def slurp(codec: Codec) = chars(codec).mkString
+  }
+}
diff --git a/src/compiler/scala/tools/nsc/io/VirtualDirectory.scala b/src/compiler/scala/tools/nsc/io/VirtualDirectory.scala
index 4009429..8cb07f0 100644
--- a/src/compiler/scala/tools/nsc/io/VirtualDirectory.scala
+++ b/src/compiler/scala/tools/nsc/io/VirtualDirectory.scala
@@ -1,9 +1,11 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  */
-// $Id$
-package scala.tools.nsc.io
-import scala.collection.{mutable=>mut}
+
+package scala.tools.nsc
+package io
+
+import scala.collection.mutable
 
 /**
  * An in-memory directory.
@@ -17,51 +19,52 @@ extends AbstractFile {
       case None => name
       case Some(parent) => parent.path+'/'+ name
     }
+
+  def absolute = this
+
   def container = maybeContainer.get
   def isDirectory = true
   var lastModified: Long = System.currentTimeMillis
-  private def updateLastModified {
-    lastModified = System.currentTimeMillis
-  }
+
   override def file = null
   override def input = error("directories cannot be read")
   override def output = error("directories cannot be written")
+
+  /** Does this abstract file denote an existing file? */
+  def create { unsupported }
+
+  /** Delete the underlying file or directory (recursively). */
+  def delete { unsupported }
+
+  /** Returns an abstract file with the given name. It does not
+   *  check that it exists.
+   */
+  def lookupNameUnchecked(name: String, directory: Boolean): AbstractFile = unsupported
   
-  private val files = mut.Map.empty[String, AbstractFile]
+  private val files = mutable.Map.empty[String, AbstractFile]
 
   // the toList is so that the directory may continue to be
   // modified while its elements are iterated
-  def elements = files.values.toList.elements
+  def iterator = files.values.toList.iterator
   
-  override def lookupName(name: String, directory: Boolean): AbstractFile = {
-    files.get(name) match {
-      case None => null
-      case Some(file) =>
-        if (file.isDirectory == directory)
-          file
-        else
-          null
-    }
-  }
+  override def lookupName(name: String, directory: Boolean): AbstractFile =
+    files get name filter (_.isDirectory == directory) orNull
     
-  override def fileNamed(name: String): AbstractFile = {
-    val existing = lookupName(name, false)
-    if (existing == null) {
+  override def fileNamed(name: String): AbstractFile =
+    Option(lookupName(name, false)) getOrElse {
       val newFile = new VirtualFile(name, path+'/'+name)
       files(name) = newFile
       newFile
-    } else {
-      existing
     }
-  }
   
-  override def subdirectoryNamed(name: String): AbstractFile = {
-    val existing = lookupName(name, true)
-    if (existing == null) {
+  override def subdirectoryNamed(name: String): AbstractFile =
+    Option(lookupName(name, true)) getOrElse {
       val dir = new VirtualDirectory(name, Some(this))
+      files(name) = dir
       dir
-    } else {
-      existing
     }
+
+  def clear() {
+    files.clear();
   }
 }
diff --git a/src/compiler/scala/tools/nsc/io/VirtualFile.scala b/src/compiler/scala/tools/nsc/io/VirtualFile.scala
index a493ed7..28fc537 100644
--- a/src/compiler/scala/tools/nsc/io/VirtualFile.scala
+++ b/src/compiler/scala/tools/nsc/io/VirtualFile.scala
@@ -1,22 +1,22 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: VirtualFile.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.tools.nsc.io
+package scala.tools.nsc
+package io
 
-import java.io.{ByteArrayInputStream, ByteArrayOutputStream,
-                File, InputStream, OutputStream}
+import java.io.{ ByteArrayInputStream, ByteArrayOutputStream, InputStream, OutputStream, File => JFile }
+import PartialFunction._
 
 /** This class implements an in-memory file.
  *
  *  @author  Philippe Altherr
  *  @version 1.0, 23/03/2004
  */
-class VirtualFile(val name: String, _path: String) extends AbstractFile {
-
+class VirtualFile(val name: String, _path: String) extends AbstractFile
+{
   assert((name ne null) && (path ne null), name + " - " + path)
 
   //########################################################################
@@ -31,12 +31,8 @@ class VirtualFile(val name: String, _path: String) extends AbstractFile {
    */
   def this(name: String) = this(name, name)
   
-  override def hashCode = name.hashCode
-  override def equals(that : Any) = that match {
-  case that : VirtualFile => name == that.name
-  case _ => false
-  }
-
+  override def hashCode = name.##
+  override def equals(that: Any) = cond(that) { case x: VirtualFile => x.name == name }
   
   //########################################################################
   // Private data
@@ -47,8 +43,10 @@ class VirtualFile(val name: String, _path: String) extends AbstractFile {
 
   def path = _path
 
+  def absolute = this
+
   /** Returns null. */
-  final def file: File = null
+  final def file: JFile = null
   
   override def sizeOption: Option[Int] = Some(content.size)
   
@@ -63,19 +61,25 @@ class VirtualFile(val name: String, _path: String) extends AbstractFile {
     }
   }
   
-  def container : AbstractFile = throw new Error("not supported")
+  def container: AbstractFile =  unsupported
 
   /** Is this abstract file a directory? */
   def isDirectory: Boolean = false
 
   /** Returns the time that this abstract file was last modified. */
-  def lastModified: Long = Math.MIN_LONG
+  def lastModified: Long = Long.MinValue
 
   /** Returns all abstract subfiles of this abstract directory. */
-  def elements: Iterator[AbstractFile] = {
+  def iterator: Iterator[AbstractFile] = {
     assert(isDirectory, "not a directory '" + this + "'")
     Iterator.empty
-  }
+  }	
+
+  /** Does this abstract file denote an existing file? */
+  def create { unsupported }
+
+  /** Delete the underlying file or directory (recursively). */
+  def delete { unsupported }
 
   /**
    * Returns the abstract file in this abstract directory with the
@@ -92,5 +96,10 @@ class VirtualFile(val name: String, _path: String) extends AbstractFile {
     null
   }
 
+  /** Returns an abstract file with the given name. It does not
+   *  check that it exists.
+   */
+  def lookupNameUnchecked(name: String, directory: Boolean) = unsupported
+
   //########################################################################
 }
diff --git a/src/compiler/scala/tools/nsc/io/ZipArchive.scala b/src/compiler/scala/tools/nsc/io/ZipArchive.scala
index 514c4b2..5d73113 100644
--- a/src/compiler/scala/tools/nsc/io/ZipArchive.scala
+++ b/src/compiler/scala/tools/nsc/io/ZipArchive.scala
@@ -1,34 +1,28 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: ZipArchive.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.tools.nsc.io
+package scala.tools.nsc
+package io
 
-import java.io.{File, IOException, InputStream}
 import java.net.URL
 import java.util.Enumeration
-import java.util.zip.{ZipEntry, ZipFile, ZipInputStream}
+import java.io.{ File => JFile, IOException, InputStream, BufferedInputStream, ByteArrayInputStream }
+import java.util.zip.{ ZipEntry, ZipFile, ZipInputStream }
+import PartialFunction._
 
-import scala.collection.mutable.{Map, HashMap}
+import scala.collection.mutable.{ Map, HashMap }
+import scala.collection.JavaConversions.asIterator
 
 /**
  * @author  Philippe Altherr
  * @version 1.0, 23/03/2004
  */
-object ZipArchive {
-
-  //########################################################################
-
-  /**
-   * ...
-   *
-   * @param path ...
-   *  @return     ...
-   */
-  def fromPath(path: String): AbstractFile = fromFile(new File(path))
+object ZipArchive
+{
+  def fromPath(path: Path): ZipArchive = fromFile(path.toFile)
 
   /**
    * If the specified file <code>file</code> exists and is a readable
@@ -38,56 +32,115 @@ object ZipArchive {
    * @param file ...
    * @return     ...
    */
-  def fromFile(file: File): AbstractFile =
-    try { new ZipArchive(file, new ZipFile(file)) }
+  def fromFile(file: File): ZipArchive =
+    try new ZipArchive(file, new ZipFile(file.jfile))
     catch { case _: IOException => null }
 
   /**
    * Returns an abstract directory backed by the specified archive.
-   *
-   * @param archive ...
-   * @return        ...
    */
-  def fromArchive(archive: ZipFile): AbstractFile =
-    new ZipArchive(new File(archive.getName()), archive)
+  def fromArchive(archive: ZipFile): ZipArchive =
+    new ZipArchive(File(archive.getName()), archive)
 
   /**
    * Returns an abstract directory backed by the specified archive.
-   *
-   * @param url ...
-   * @return    ...
    */
-  def fromURL(url: URL): AbstractFile =
-    new URLZipArchive(url)
+  def fromURL(url: URL): AbstractFile = new URLZipArchive(url)
+  
+  private[io] class ZipEntryTraversableClass(in: InputStream) extends Traversable[ZipEntry] {
+    val zis = new ZipInputStream(in)
+
+    def foreach[U](f: ZipEntry => U) = {
+      def loop(x: ZipEntry): Unit = if (x != null) {
+        f(x)
+        zis.closeEntry()
+        loop(zis.getNextEntry())
+      }
+      loop(zis.getNextEntry())
+    }
+  }
 }
 
-/**
- * This class implements an abstract directory backed by a zip
- * archive. We let the encoding be <code>null</code>, because we behave like
- * a directory.
- *
- * @author  Philippe Altherr
- * @version 1.0, 23/03/2004
+/** This abstraction aims to factor out the common code between
+ *  ZipArchive (backed by a zip file) and URLZipArchive (backed
+ *  by an InputStream.)
  */
-final class ZipArchive(file: File, val archive: ZipFile) extends PlainFile(file) {
-
-  assert(archive ne null)
-  //########################################################################
-  // Private Fields
+private[io] trait ZipContainer extends AbstractFile
+{
+  /** Abstract types */
+  type SourceType             // InputStream or AbstractFile
+  type CreationType           // InputStream or ZipFile
+  type ZipTrav = Traversable[ZipEntry] { def zis: ZipInputStream }
+  
+  /** Abstract values */
+  protected val creationSource: CreationType
+  protected val root: DirEntryInterface
+  protected def DirEntryConstructor: (AbstractFile, String, String) => DirEntryInterface
+  protected def FileEntryConstructor: (SourceType, String, String, ZipEntry) => FileEntryInterface
+  protected def ZipTravConstructor: CreationType => ZipTrav
+  
+  protected[io] trait EntryInterface extends VirtualFile {
+    def name: String
+    def path: String
+  }
+  
+  protected[io] trait DirEntryInterface extends EntryInterface {
+    def source: SourceType
+    val entries: Map[String, EntryInterface] = new HashMap()
+    var entry: ZipEntry = _
 
-  /** The root directory or null if not yet initialized */
-  private var root: DirEntry = _
+    override def input = throw new Error("cannot read directories")
+    override def lastModified: Long =
+      if (entry ne null) entry.getTime() else super.lastModified
+    
+    override def isDirectory = true
+    override def iterator: Iterator[AbstractFile] = entries.valuesIterator
+    override def lookupName(name: String, directory: Boolean): AbstractFile = {
+      def slashName = if (directory) name + "/" else name
+      entries.getOrElse(slashName, null)
+    }    
+  }
+  
+  protected[io] trait FileEntryInterface extends EntryInterface {
+    def entry: ZipEntry
 
-  //########################################################################
-  // Public Methods
+    override def lastModified: Long = entry.getTime()
+    override def sizeOption = Some(entry.getSize().toInt)
+  }
+  
+  class ZipRootCreator(f: ZipRootCreator => SourceType) {
+    val root = DirEntryConstructor(ZipContainer.this, "<root>", "/")
+
+    // Map from paths to DirEntries
+    val dirs = HashMap[String, DirEntryInterface]("/" -> root)
+    val traverser = ZipTravConstructor(creationSource)
+    private[this] var _parent: DirEntryInterface = _
+    def parent = _parent
+
+    def addEntry(entry: ZipEntry) {
+      val path = entry.getName
+      if (entry.isDirectory) {
+        val dir: DirEntryInterface = getDir(dirs, path)
+        if (dir.entry == null) dir.entry = entry
+      }
+      else {
+        val (home, name) = splitPath(path)
+        _parent = getDir(dirs, home)
+        _parent.entries(name) = FileEntryConstructor(f(this), name, path, entry)
+      }
+    }
 
-  /** Returns true. */
-  override def isDirectory = true
+    def apply() = {
+      traverser foreach addEntry
+      root
+    }
+  }
 
-  /** Returns all abstract subfiles of this abstract directory. */
-  override def elements: Iterator[AbstractFile] = {
-    if (root eq null) load()
-    root.elements
+  protected def splitPath(path: String): (String, String) = {
+    (path lastIndexOf '/') match {
+      case -1   => ("/", path)
+      case idx  => path splitAt (idx + 1)
+    }
   }
 
   /**
@@ -96,119 +149,96 @@ final class ZipArchive(file: File, val archive: ZipFile) extends PlainFile(file)
    * argument "directory" tells whether to look for a directory or
    * or a regular file.
    */
-  override def lookupName(name: String, directory: Boolean): AbstractFile = {
-    if (root eq null) load()
+  override def lookupName(name: String, directory: Boolean): AbstractFile =
     root.lookupName(name, directory)
-  }
-
-  //########################################################################
-  // Private Methods
+      
+  /** Returns an abstract file with the given name. It does not
+   *  check that it exists.
+   */
+  override def lookupNameUnchecked(name: String, directory: Boolean) = unsupported
 
-  /** Loads the archive and creates the root directory. */
-  private def load() {
-    this.root = new DirEntry(this, "<root>", "/")
-    // A path to DirEntry map
-    val dirs: Map[String, DirEntry] = new HashMap()
-    dirs.update("/", root)
-    val entries = archive.entries()
-    while (entries.hasMoreElements()) {
-      val entry = entries.nextElement().asInstanceOf[ZipEntry]
-      val path = entry.getName()
-      assert(entry.isDirectory() == path.endsWith("/"),
-             this.toString() + " - " + path);
-      if (entry.isDirectory()) {
-        val dir: DirEntry = getDir(dirs, path)
-        // this assertion causes an unnecessary bomb if a directory is twice listed in the jar
-        // assert(dir.entry eq null, this.toString() + " - " + path)
-        if (dir.entry eq null) dir.entry = entry
-      } else {
-        val index = path.lastIndexOf('/')
-        val name = if (index < 0) path else path.substring(index + 1)
-        val home = if (index < 0) "/"  else path.substring(0, index + 1)
-        val parent: DirEntry = getDir(dirs, home)
-        // OLD: assert(!parent.entries.contains(path))
-        // MAYBE: assert(!parent.entries.contains(name))
-        //if (parent.entries.contains(name))
-        //  Console.println("XXX: " + this.toString() + " - " + home + "/" + name)
-        parent.entries.update(name, new FileEntry(parent, name, path, entry))
-      }
-    }
-  }
+  /** Returns all abstract subfiles of this abstract directory. */
+  override def iterator: Iterator[AbstractFile] = root.iterator
 
   /**
-   * Lookups the specified table for a DirEntry with the specified
-   * path. If successful, returns the found DirEntry. Otherwise
-   * creates a new DirEntry, enters it into the table and in the
-   * table of its parent ZipDir and returns it.
+   * Looks up the path in the given map and returns if found.
+   * If not present, creates a new DirEntry, adds to both given
+   * map and parent.entries, and returns it.
    */
-  private def getDir(dirs: Map[String,DirEntry], path: String): DirEntry =
-    dirs.get(path) match {
-      case Some(dir) => dir
-      case None => 
-        val index = path.lastIndexOf('/', path.length() - 2);
-        val name = if (index < 0) path else path.substring(index + 1);
-        val home = if (index < 0) "/"  else path.substring(0, index + 1);
-        val parent: DirEntry = getDir(dirs, home);
-        val dir = new DirEntry(parent, name.substring(0, name.length() - 1), path);
-        parent.entries.update(name, dir);
-        dirs.update(path, dir);
-        dir
-   }
-  
-  //########################################################################
-  // Private Class - Entry
-
-  /** Superclass of archive entries */
-  abstract class Entry(override val container : AbstractFile, name: String, path: String) 
-    extends VirtualFile(name, path) {
-    final override def path = ZipArchive.this.toString() + "(" + pathInArchive + ")"
-    final def getArchive = ZipArchive.this.archive
-    def pathInArchive = super.path
-    override def hashCode = super.hashCode + container.hashCode
-    override def equals(that : Any) = super.equals(that) && (that match {
-    case entry : Entry => container == entry.container
-    case _ => false
+  protected def getDir(dirs: Map[String, DirEntryInterface], path: String): DirEntryInterface =
+    dirs.getOrElseUpdate(path, {
+      val (home, name) = splitPath(path init)
+      val parent = getDir(dirs, home)
+      val dir = DirEntryConstructor(parent, name, path)
+      parent.entries(name + path.last) = dir
+      dir
     })
-  }
 
-  //########################################################################
-  // Private Class - DirEntry
+  override def isDirectory = true
+}
 
-  /** A directory archive entry */
-  private final class DirEntry(container : AbstractFile, name: String, path: String)
-                extends Entry(container, name, path)
+/**
+ * This class implements an abstract directory backed by a zip
+ * archive. We let the encoding be <code>null</code>, because we behave like
+ * a directory.
+ *
+ * @author  Philippe Altherr
+ * @version 1.0, 23/03/2004
+ */
+final class ZipArchive(file: File, val archive: ZipFile) extends PlainFile(file) with ZipContainer
+{
+  self =>
+  
+  type SourceType = AbstractFile
+  type CreationType = ZipFile
+  
+  protected val creationSource        = archive
+  protected lazy val root             = new ZipRootCreator(_.parent)()
+  protected def DirEntryConstructor   = new DirEntry(_, _, _)
+  protected def FileEntryConstructor  = new FileEntry(_, _, _, _)
+  protected def ZipTravConstructor    = zipTraversableFromZipFile _
+
+  abstract class Entry(
+    override val container: AbstractFile,
+    name: String,
+    path: String
+  ) extends VirtualFile(name, path)
   {
-
-    val entries: Map[String, Entry] = new HashMap()
-
-    var entry: ZipEntry = _
-
-    override def isDirectory = true
-    override def input = throw new Error("cannot read directories")
-
-    override def lastModified: Long =
-      if (entry ne null) entry.getTime() else super.lastModified
-
-    override def elements: Iterator[AbstractFile] = entries.values
-
-    override def lookupName(name: String, directory: Boolean): AbstractFile =
-      entries.get(if (directory) name + "/" else name) match {
-        case Some(dir) => dir
-        case None => null
-    }
+    override def underlyingSource = Some(self)
+    final override def path = "%s(%s)".format(self, super.path)    
+    final def archive = self.archive
+    
+    override def hashCode = super.hashCode + container.hashCode
+    override def equals(that : Any) =
+      super.equals(that) && (cond(that) {
+        case e: Entry => container == e.container
+      })
   }
 
-  //########################################################################
-  // Private Class - FileEntry
+  final class DirEntry(
+    container: AbstractFile,
+    name: String,
+    path: String
+  ) extends Entry(container, name, path) with DirEntryInterface
+  {
+    def source = container
+  }
 
-  /** A regular file archive entry */
-  final class FileEntry(container : AbstractFile, name: String, path: String, val entry: ZipEntry)
-        extends Entry(container, name, path) {
-    def archive = ZipArchive.this.archive
-    override def lastModified: Long = entry.getTime()
-    override def input = archive.getInputStream(entry)
-    override def sizeOption = Some(entry.getSize().toInt)
+  final class FileEntry(
+    container: AbstractFile,
+    name: String,
+    path: String,
+    val entry: ZipEntry
+  ) extends Entry(container, name, path) with FileEntryInterface
+  {
+    override def input = archive getInputStream entry
   }
+  
+  private def zipTraversableFromZipFile(z: ZipFile): ZipTrav =
+    new Iterable[ZipEntry] {
+      def zis: ZipInputStream = null    // not valid for this type
+      def iterator = asIterator(z.entries())
+    }
 }
 
 /**
@@ -218,126 +248,55 @@ final class ZipArchive(file: File, val archive: ZipFile) extends PlainFile(file)
  * @author  Stephane Micheloud
  * @version 1.0, 29/05/2007
  */
-final class URLZipArchive(url: URL) extends AbstractFile {
-  assert(url ne null)
-
-  private var root: DirEntry = _
-
-  def container = throw new Error("unsupported")
+final class URLZipArchive(url: URL) extends AbstractFile with ZipContainer
+{
+  type SourceType   = InputStream
+  type CreationType = InputStream
+  
+  protected lazy val creationSource = input
+  protected lazy val root = new ZipRootCreator(x => byteInputStream(x.traverser.zis))()
+  
+  protected def DirEntryConstructor   = (_, name, path) => new DirEntry(name, path)
+  protected def FileEntryConstructor  = new FileEntry(_, _, _, _)
+  protected def ZipTravConstructor    = new ZipArchive.ZipEntryTraversableClass(_)
 
   def name: String = url.getFile()
-
   def path: String = url.getPath()
-
-  def file: File = null
-
-  def isDirectory: Boolean = true
-
-  def lastModified: Long =
-    try { url.openConnection().getLastModified() }
-    catch { case _ => 0 }
-
   def input: InputStream = url.openStream()
+  def absolute: AbstractFile = this
+  def lastModified: Long =
+    try url.openConnection().getLastModified()
+    catch { case _: IOException => 0 }
   
-  def output = throw new Error("unsupported")
-
-  override def elements: Iterator[AbstractFile] = {
-    if (root eq null) load()
-    root.elements
-  }
-
-  override def lookupName(name: String, directory: Boolean): AbstractFile = {
-    if (root eq null) load()
-    root.lookupName(name, directory)
+  /** Methods we don't support but have to implement because of the design */
+  def file: JFile = null
+  def create: Unit = unsupported
+  def delete: Unit = unsupported
+  def output = unsupported
+  def container = unsupported
+
+  abstract class Entry(name: String, path: String) extends VirtualFile(name, path) {
+    final override def path = "%s(%s)".format(URLZipArchive.this, super.path)
+    override def container = URLZipArchive.this
   }
-
-  private def load() {
-    def getEntryInputStream(in: InputStream): InputStream = {
-      val buf = new scala.collection.mutable.ArrayBuffer[Byte]
-      val data = new Array[Byte](1024)
-      var n = in.read(data)
-      while (n > 0) {
-        buf.++=(data, 0, n)
-        n = in.read(data)
-      }
-      new java.io.ByteArrayInputStream(buf.toArray)
-    }
-    this.root = new DirEntry("<root>", "/")
-    // A path to DirEntry map
-    val dirs: Map[String, DirEntry] = new HashMap()
-    dirs.update("/", root)
-    val zis = new ZipInputStream(input)
-    var entry = zis.getNextEntry()
-    while (entry ne null) {
-      val path = entry.getName()
-      assert(entry.isDirectory() == path.endsWith("/"),
-             this.toString() + " - " + path);
-      if (entry.isDirectory()) {
-        val dir: DirEntry = getDir(dirs, path)
-        assert(dir.entry eq null, this.toString() + " - " + path)
-        dir.entry = entry
-      } else {
-        val index = path.lastIndexOf('/')
-        val name = if (index < 0) path else path.substring(index + 1)
-        val home = if (index < 0) "/"  else path.substring(0, index + 1)
-        val parent: DirEntry = getDir(dirs, home)
-        assert(!parent.entries.contains(path), this.toString() + " - " + path)
-        val in = getEntryInputStream(zis)
-        parent.entries.update(name, new FileEntry(name, path, entry, in))
-      }
-      zis.closeEntry()
-      entry = zis.getNextEntry()
-    }
-  }
-
-  private def getDir(dirs: Map[String, DirEntry], path: String): DirEntry =
-    dirs.get(path) match {
-      case Some(dir) => dir
-      case None =>
-        val index = path.lastIndexOf('/', path.length() - 2)
-        val name = if (index < 0) path else path.substring(index + 1)
-        val home = if (index < 0) "/"  else path.substring(0, index + 1)
-        val parent: DirEntry = getDir(dirs, home)
-        val dir = new DirEntry(name.substring(0, name.length() - 1), path)
-        parent.entries.update(name, dir)
-        dirs.update(path, dir)
-        dir
-    }
-
-  /** Superclass of archive entries */
-  abstract class Entry(name: String, path: String)
-  extends VirtualFile(name, path) {
-    final override def path = URLZipArchive.this.toString() + "(" + super.path + ")"
-    //final def getArchive = URLZipArchive.this.archive
+  final class DirEntry(name: String, path: String) extends Entry(name, path) with DirEntryInterface {
+    def source = input
   }
-
-  /** A directory archive entry */
-  private final class DirEntry(name: String, path: String)
-  extends Entry(name, path)
+  final class FileEntry(
+    val in: InputStream,
+    name: String,
+    path: String,
+    val entry: ZipEntry
+  ) extends Entry(name, path) with FileEntryInterface
   {
-    val entries: Map[String, Entry] = new HashMap()
-    var entry: ZipEntry = _
-
-    override def isDirectory = true
-    override def input = throw new Error("cannot read directories")
-
-    override def lastModified: Long =
-      if (entry ne null) entry.getTime() else super.lastModified
-
-    override def elements: Iterator[AbstractFile] = entries.values
-
-    override def lookupName(name: String, directory: Boolean): AbstractFile =
-      entries.get(if (directory) name + "/" else name) match {
-        case Some(dir) => dir
-        case None => null
-      }
+    override def input = in    
   }
 
-  final class FileEntry(name: String, path: String,
-                        val entry: ZipEntry, val in: InputStream)
-        extends Entry(name, path) {
-    override def lastModified: Long = entry.getTime()
-    override def input = in
-    override def sizeOption = Some(entry.getSize().toInt)
+  /** Private methods **/
+  private def byteInputStream(in: InputStream): InputStream = {
+    val minusOne = (-1).toByte
+    val buf = new BufferedInputStream(in)
+    val bytes = Iterator continually in.read().toByte takeWhile (_ != minusOne)
+    new ByteArrayInputStream(bytes.toSeq.toArray)
   }
 }
diff --git a/src/compiler/scala/tools/nsc/javac/JavaParsers.scala b/src/compiler/scala/tools/nsc/javac/JavaParsers.scala
index 68c2249..5bed51b 100644
--- a/src/compiler/scala/tools/nsc/javac/JavaParsers.scala
+++ b/src/compiler/scala/tools/nsc/javac/JavaParsers.scala
@@ -1,14 +1,14 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: Parsers.scala 15004 2008-05-13 16:37:33Z odersky $
 //todo: allow infix type patterns
 
 
-package scala.tools.nsc.javac
+package scala.tools.nsc
+package javac
 
-import scala.tools.nsc.util.{Position, OffsetPosition, NoPosition, BatchSourceFile}
+import scala.tools.nsc.util.{OffsetPosition, BatchSourceFile}
 import scala.collection.mutable.ListBuffer
 import symtab.Flags
 import JavaTokens._
@@ -16,7 +16,6 @@ import JavaTokens._
 trait JavaParsers extends JavaScanners {
   val global : Global 
   import global._
-  import posAssigner.atPos
   import definitions._
 
   case class JavaOpInfo(operand: Tree, operator: Name, pos: Int)
@@ -24,7 +23,7 @@ trait JavaParsers extends JavaScanners {
   class JavaUnitParser(val unit: global.CompilationUnit) extends JavaParser {
     val in = new JavaUnitScanner(unit)
     def freshName(pos : Position, prefix : String) = unit.fresh.newName(pos, prefix)
-    implicit def i2p(offset : Int) : Position = new OffsetPosition(unit.source,offset)
+    implicit def i2p(offset : Int) : Position = new OffsetPosition(unit.source, offset)
     def warning(pos : Int, msg : String) : Unit = unit.warning(pos, msg)
     def syntaxError(pos: Int, msg: String) : Unit = unit.error(pos, msg)
   }
@@ -35,7 +34,7 @@ trait JavaParsers extends JavaScanners {
     protected def posToReport: Int = in.currentPos
     protected def freshName(pos : Position, prefix : String): Name
     protected implicit def i2p(offset : Int) : Position
-    private implicit def p2i(pos : Position): Int = pos.offset.getOrElse(-1)
+    private implicit def p2i(pos : Position): Int = if (pos.isDefined) pos.point else -1
 
     /** The simple name of the package of the currently parsed file */
     private var thisPackageName: Name = nme.EMPTY
@@ -99,11 +98,7 @@ trait JavaParsers extends JavaScanners {
 
     // --------- tree building -----------------------------
 
-    def rootId(name: Name) = 
-      Select(Ident(nme.ROOTPKG), name)
-
-    def scalaDot(name: Name): Tree =
-      Select(rootId(nme.scala_) setSymbol ScalaPackage, name)
+    import gen.{ rootId, scalaDot }
 
     def javaDot(name: Name): Tree = 
       Select(rootId(nme.java), name)
@@ -118,12 +113,8 @@ trait JavaParsers extends JavaScanners {
 
     def blankExpr = Ident(nme.WILDCARD)
 
-    def makePackaging(pkg: Tree, stats: List[Tree]): PackageDef = pkg match {
-      case Ident(name) =>
-        PackageDef(name, stats).setPos(pkg.pos)
-      case Select(qual, name) =>
-        makePackaging(qual, List(PackageDef(name, stats).setPos(pkg.pos)))
-    }
+    def makePackaging(pkg: RefTree, stats: List[Tree]): PackageDef = 
+      atPos(pkg.pos) {  PackageDef(pkg, stats) }
 
     def makeTemplate(parents: List[Tree], stats: List[Tree]) =
       Template(
@@ -220,7 +211,7 @@ trait JavaParsers extends JavaScanners {
       }
 
     def repsep[T <: Tree](p: () => T, sep: Int): List[T] = {
-      val buf = new ListBuffer[T] + p()
+      val buf = ListBuffer[T](p())
       while (in.token == sep) {
         in.nextToken
         buf += p()
@@ -244,8 +235,8 @@ trait JavaParsers extends JavaScanners {
 
     // -------------------- specific parsing routines ------------------
 
-    def qualId(): Tree = {
-      var t: Tree = atPos(in.currentPos) { Ident(ident()) }
+    def qualId(): RefTree = {
+      var t: RefTree = atPos(in.currentPos) { Ident(ident()) }
       while (in.token == DOT) { 
         in.nextToken
         t = atPos(in.currentPos) { Select(t, ident()) }
@@ -331,8 +322,8 @@ trait JavaParsers extends JavaScanners {
       } else t
     }
 
-    def annotations(): List[Annotation] = {
-      //var annots = new ListBuffer[Annotation]
+    def annotations(): List[Tree] = {
+      //var annots = new ListBuffer[Tree]
       while (in.token == AT) {
         in.nextToken
         annotation()
@@ -344,7 +335,7 @@ trait JavaParsers extends JavaScanners {
      */
     def annotation() {
       val pos = in.currentPos
-      var t = typ()
+      var t = qualId()
       if (in.token == LPAREN) { skipAhead(); accept(RPAREN) }
       else if (in.token == LBRACE) { skipAhead(); accept(RBRACE) }
     }
@@ -386,8 +377,10 @@ trait JavaParsers extends JavaScanners {
 
     def modifiers(inInterface: Boolean): Modifiers = {
       var flags: Long = Flags.JAVA
+      // assumed true unless we see public/private/protected - see bug #1240
       var privateWithin: Name =
         if (inInterface) nme.EMPTY.toTypeName else thisPackageName
+
       while (true) {
         in.token match {
           case AT if (in.lookaheadToken != INTERFACE) => 
@@ -398,7 +391,7 @@ trait JavaParsers extends JavaScanners {
             in.nextToken
           case PROTECTED => 
             flags |= Flags.PROTECTED
-            privateWithin = thisPackageName
+            //privateWithin = thisPackageName
             in.nextToken
           case PRIVATE =>
             flags |= Flags.PRIVATE
@@ -416,10 +409,26 @@ trait JavaParsers extends JavaScanners {
           case NATIVE | SYNCHRONIZED | TRANSIENT | VOLATILE | STRICTFP =>
             in.nextToken
           case _ =>
+            // XXX both these checks are definitely necessary, which would
+            // seem to indicate the empty package situation needs review
+            // def isEmptyPkg() =
+            //   privateWithin == nme.EMPTY.toTypeName ||
+            //   privateWithin == nme.EMPTY_PACKAGE_NAME_tn
+            // XXX I think this test should just be "if (defaultAccess)"
+            // but then many cases like pos/t1176 fail because scala code
+            // with no package cannot access java code with no package.          
+            // if (defaultAccess && !isEmptyPkg)
+            //   flags |= Flags.PROTECTED    // package private
+            
+            // my every attempt so far has left some combination of
+            // #1240, #1840, #1842, or other java/scala mixes failing.
+            // Reverting to original code, which means #1240 won't
+            // work but other variations should.
+            
             return Modifiers(flags, privateWithin)
         }
       }
-      throw new Error("should not be here")
+      abort("should not be here")
     }
 
     def typeParams(): List[TypeDef] =
@@ -446,7 +455,7 @@ trait JavaParsers extends JavaScanners {
 
     def bound(): Tree = 
       atPos(in.currentPos) {
-        val buf = new ListBuffer[Tree] + typ()
+        val buf = ListBuffer[Tree](typ())
         while (in.token == AMP) {
           in.nextToken
           buf += typ()
@@ -470,7 +479,7 @@ trait JavaParsers extends JavaScanners {
       if (in.token == DOTDOTDOT) {
         in.nextToken
         t = atPos(t.pos) {
-          AppliedTypeTree(scalaDot(nme.REPEATED_PARAM_CLASS_NAME.toTypeName), List(t))
+          AppliedTypeTree(scalaDot(nme.JAVA_REPEATED_PARAM_CLASS_NAME.toTypeName), List(t))
         }
       }
      varDecl(in.currentPos, Modifiers(Flags.JAVA | Flags.PARAM), t, ident())
@@ -531,11 +540,9 @@ trait JavaParsers extends JavaScanners {
               if (parentToken == AT && in.token == DEFAULT) {
                 val annot = 
                   atPos(pos) {
-                    Annotation(
-                      New(rootId(nme.AnnotationDefaultATTR.toTypeName), List(List())),
-                      List())
+                    New(Select(scalaDot(newTermName("runtime")), nme.AnnotationDefaultATTR.toTypeName), List(List()))
                   }
-                mods1 = Modifiers(mods1.flags, mods1.privateWithin, annot :: mods1.annotations)
+                mods1 = Modifiers(mods1.flags, mods1.privateWithin, annot :: mods1.annotations, mods1.positions)
                 skipTo(SEMI)
                 accept(SEMI)
                 blankExpr
@@ -569,7 +576,7 @@ trait JavaParsers extends JavaScanners {
      *  these potential definitions are real or not.
      */
     def fieldDecls(pos: Position, mods: Modifiers, tpt: Tree, name: Name): List[Tree] = {
-      val buf = new ListBuffer[Tree] + varDecl(pos, mods, tpt, name)
+      val buf = ListBuffer[Tree](varDecl(pos, mods, tpt, name))
       val maybe = new ListBuffer[Tree] // potential variable definitions.
       while (in.token == COMMA) {
         in.nextToken
@@ -622,32 +629,55 @@ trait JavaParsers extends JavaScanners {
 
     def importCompanionObject(cdef: ClassDef): Tree =
       atPos(cdef.pos) {
-        Import(Ident(cdef.name.toTermName), List((nme.WILDCARD, null)))
-      }
-
-    def addCompanionObject(statics: List[Tree], cdef: ClassDef): List[Tree] = 
-      if (statics.isEmpty) List(cdef)
-      else List(makeCompanionObject(cdef, statics), importCompanionObject(cdef), cdef)
+        Import(Ident(cdef.name.toTermName), List(ImportSelector(nme.WILDCARD, -1, null, -1)))
+      }
+
+    // Importing the companion object members cannot be done uncritically: see
+    // ticket #2377 wherein a class contains two static inner classes, each of which
+    // has a static inner class called "Builder" - this results in an ambiguity error
+    // when each performs the import in the enclosing class's scope.
+    //
+    // To address this I moved the import Companion._ inside the class, as the first
+    // statement.  This should work without compromising the enclosing scope, but may (?)
+    // end up suffering from the same issues it does in scala - specifically that this
+    // leaves auxiliary constructors unable to access members of the companion object
+    // as unqualified identifiers.
+    def addCompanionObject(statics: List[Tree], cdef: ClassDef): List[Tree] = {      
+      def implWithImport(importStmt: Tree) = {
+        import cdef.impl._
+        treeCopy.Template(cdef.impl, parents, self, importStmt :: body)
+      }
+      // if there are no statics we can use the original cdef, but we always
+      // create the companion so import A._ is not an error (see ticket #1700)
+      val cdefNew =
+        if (statics.isEmpty) cdef
+        else treeCopy.ClassDef(cdef, cdef.mods, cdef.name, cdef.tparams, implWithImport(importCompanionObject(cdef)))
+      
+      List(makeCompanionObject(cdefNew, statics), cdefNew)
+    }
 
     def importDecl(): List[Tree] = {
       accept(IMPORT)
       val pos = in.currentPos
       val buf = new ListBuffer[Name]
-      def collectIdents() {
+      def collectIdents() : Int = {
         if (in.token == ASTERISK) {
+          val starOffset = in.pos
           in.nextToken
           buf += nme.WILDCARD
+          starOffset
         } else {
+          val nameOffset = in.pos
           buf += ident()
           if (in.token == DOT) {
             in.nextToken
             collectIdents()
-          }
+          } else nameOffset
         }
       }
       if (in.token == STATIC) in.nextToken
       else buf += nme.ROOTPKG
-      collectIdents()
+      val lastnameOffset = collectIdents()
       accept(SEMI)
       val names = buf.toList
       if (names.length < 2) {
@@ -658,8 +688,8 @@ trait JavaParsers extends JavaScanners {
         val lastname = names.last
         List {
           atPos(pos) {
-            if (lastname == nme.WILDCARD) Import(qual, List((lastname, null)))
-            else Import(qual, List((lastname, lastname)))
+            if (lastname == nme.WILDCARD) Import(qual, List(ImportSelector(lastname, lastnameOffset, null, -1)))
+            else Import(qual, List(ImportSelector(lastname, lastnameOffset, lastname, lastnameOffset)))
           }
         }
       }
@@ -686,7 +716,7 @@ trait JavaParsers extends JavaScanners {
           javaLangObject()
         }
       val interfaces = interfacesOpt()
-      val (statics, body) = typeBody(CLASS) 
+      val (statics, body) = typeBody(CLASS, name) 
       addCompanionObject(statics, atPos(pos) {
         ClassDef(mods, name, tparams, makeTemplate(superclass :: interfaces, body))
       })
@@ -704,7 +734,7 @@ trait JavaParsers extends JavaScanners {
         } else {
           List(javaLangObject)
         }
-      val (statics, body) = typeBody(INTERFACE)
+      val (statics, body) = typeBody(INTERFACE, name)
       addCompanionObject(statics, atPos(pos) {
         ClassDef(mods | Flags.TRAIT | Flags.INTERFACE | Flags.ABSTRACT, 
                  name, tparams, 
@@ -712,14 +742,14 @@ trait JavaParsers extends JavaScanners {
       })
     }
 
-    def typeBody(leadingToken: Int): (List[Tree], List[Tree]) = {
+    def typeBody(leadingToken: Int, parentName: Name): (List[Tree], List[Tree]) = {
       accept(LBRACE)
-      val defs = typeBodyDecls(leadingToken)
+      val defs = typeBodyDecls(leadingToken, parentName)
       accept(RBRACE)
       defs
     }
  
-    def typeBodyDecls(parentToken: Int): (List[Tree], List[Tree]) = {
+    def typeBodyDecls(parentToken: Int, parentName: Name): (List[Tree], List[Tree]) = {
       val inInterface = definesInterface(parentToken)
       val statics = new ListBuffer[Tree]
       val members = new ListBuffer[Tree]
@@ -739,7 +769,18 @@ trait JavaParsers extends JavaScanners {
              members) ++= decls
         }
       }
-      (statics.toList, members.toList)
+      def forwarders(sdef: Tree): List[Tree] = sdef match {
+        case ClassDef(mods, name, tparams, _) if (parentToken == INTERFACE) =>
+          val tparams1: List[TypeDef] = tparams map (_.duplicate)
+          var rhs: Tree = Select(Ident(parentName.toTermName), name)
+          if (!tparams1.isEmpty) rhs = AppliedTypeTree(rhs, tparams1 map (tp => Ident(tp.name)))
+          List(TypeDef(Modifiers(Flags.PROTECTED), name, tparams1, rhs))
+        case _ =>
+          List()
+      }
+      val sdefs = statics.toList
+      val idefs = members.toList ::: (sdefs flatMap forwarders)
+      (sdefs, idefs)
     }
       
     def annotationDecl(mods: Modifiers): List[Tree] = {
@@ -750,7 +791,7 @@ trait JavaParsers extends JavaScanners {
       val parents = List(scalaDot(newTypeName("Annotation")), 
                          Select(javaLangDot(newTermName("annotation")), newTypeName("Annotation")),
                          scalaDot(newTypeName("ClassfileAnnotation")))
-      val (statics, body) = typeBody(AT)
+      val (statics, body) = typeBody(AT, name)
       def getValueMethodType(tree: Tree) = tree match {
         case DefDef(_, nme.value, _, _, tpt, _) => Some(tpt.duplicate)
         case _ => None
@@ -785,7 +826,7 @@ trait JavaParsers extends JavaScanners {
       val (statics, body) = 
         if (in.token == SEMI) {
           in.nextToken
-          typeBodyDecls(ENUM)
+          typeBodyDecls(ENUM, name)
         } else {
           (List(), List())
         }
@@ -839,7 +880,7 @@ trait JavaParsers extends JavaScanners {
      */
     def compilationUnit(): Tree = {
       var pos = in.currentPos;
-      val pkg = 
+      val pkg: RefTree = 
         if (in.token == AT || in.token == PACKAGE) {
           annotations()
           pos = in.currentPos
diff --git a/src/compiler/scala/tools/nsc/javac/JavaScanners.scala b/src/compiler/scala/tools/nsc/javac/JavaScanners.scala
index 1cca2ac..0060a9f 100644
--- a/src/compiler/scala/tools/nsc/javac/JavaScanners.scala
+++ b/src/compiler/scala/tools/nsc/javac/JavaScanners.scala
@@ -1,14 +1,17 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
 
-package scala.tools.nsc.javac
+package scala.tools.nsc
+package javac
 
 import scala.tools.nsc.util._
-import SourceFile.{LF, FF, CR, SU}
+import Chars._
 import JavaTokens._
+import scala.annotation.switch
 
+// Todo merge these better with Scanners
 trait JavaScanners {
   val global : Global
   import global._
@@ -70,7 +73,7 @@ trait JavaScanners {
     def floatVal: Double = floatVal(false)
     //def token2string(token : Int) : String = configuration.token2string(token)
     /** return recent scala doc, if any */
-    def flushDoc: String
+    def flushDoc: DocComment
     def currentPos: Position
   }
 
@@ -155,7 +158,7 @@ trait JavaScanners {
         key(i) = IDENTIFIER
       for (j <- 0 until tokenCount)
         if (tokenName(j) ne null)
-          key(tokenName(j).start) = j.asInstanceOf[Byte]
+          key(tokenName(j).start) = j.toByte
 
     }
 
@@ -253,7 +256,7 @@ trait JavaScanners {
     override var errpos: Int = NoPos
     def currentPos: Position = g2p(pos - 1)
 
-    var in: CharArrayReader = _
+    var in: JavaCharArrayReader = _
 
     def dup: JavaScanner = {
       val dup = clone().asInstanceOf[JavaScanner]
@@ -279,8 +282,8 @@ trait JavaScanners {
      */
     var docBuffer: StringBuilder = null
 
-    def flushDoc = {
-      val ret = if (docBuffer != null) docBuffer.toString else null
+    def flushDoc: DocComment = {
+      val ret = if (docBuffer != null) DocComment(docBuffer.toString, NoPosition) else null
       docBuffer = null
       ret
     }
@@ -347,7 +350,7 @@ trait JavaScanners {
             in.next
           case _ =>
             pos = in.cpos // Position.encode(in.cline, in.ccol)
-            in.ch match {
+            (in.ch: @switch) match {
               case 'A' | 'B' | 'C' | 'D' | 'E' |
                    'F' | 'G' | 'H' | 'I' | 'J' |
                    'K' | 'L' | 'M' | 'N' | 'O' |
@@ -682,27 +685,9 @@ trait JavaScanners {
 
 // Identifiers ---------------------------------------------------------------
 
-    def isIdentStart(c: Char): Boolean = (
-      ('A' <= c && c <= 'Z') ||
-      ('a' <= c && c <= 'a') ||
-      (c == '_') || (c == '$') ||
-      Character.isUnicodeIdentifierStart(c)
-    )
-
-    def isIdentPart(c: Char) = (
-      isIdentStart(c) || 
-      ('0' <= c && c <= '9') ||
-      Character.isUnicodeIdentifierPart(c)
-    )
-
-    def isSpecial(c: Char) = {
-      val chtp = Character.getType(c)
-      chtp == Character.MATH_SYMBOL || chtp == Character.OTHER_SYMBOL
-    }
-
     private def getIdentRest {
       while (true) {
-        in.ch match {
+        (in.ch: @switch) match {
           case 'A' | 'B' | 'C' | 'D' | 'E' |
                'F' | 'G' | 'H' | 'I' | 'J' |
                'K' | 'L' | 'M' | 'N' | 'O' |
@@ -751,13 +736,13 @@ trait JavaScanners {
         in.next
         if ('0' <= in.ch && in.ch <= '7') {
           val leadch: Char = in.ch
-          var oct: Int = in.digit2int(in.ch, 8)
+          var oct: Int = digit2int(in.ch, 8)
           in.next
           if ('0' <= in.ch && in.ch <= '7') {
-            oct = oct * 8 + in.digit2int(in.ch, 8)
+            oct = oct * 8 + digit2int(in.ch, 8)
             in.next
             if (leadch <= '3' && '0' <= in.ch && in.ch <= '7') {
-              oct = oct * 8 + in.digit2int(in.ch, 8)
+              oct = oct * 8 + digit2int(in.ch, 8)
               in.next
             }
           }
@@ -833,11 +818,11 @@ trait JavaScanners {
         var value: Long = 0
         val divider = if (base == 10) 1 else 2
         val limit: Long =
-          if (token == LONGLIT) Math.MAX_LONG else Math.MAX_INT
+          if (token == LONGLIT) Long.MaxValue else Int.MaxValue
         var i = 0
         val len = name.length
         while (i < len) {
-          val d = in.digit2int(name(i), base)
+          val d = digit2int(name(i), base)
           if (d < 0) {
             syntaxError("malformed integer number")
             return 0
@@ -861,7 +846,7 @@ trait JavaScanners {
     */
     def floatVal(negated: Boolean): Double = {
       val limit: Double = 
-        if (token == DOUBLELIT) Math.MAX_DOUBLE else Math.MAX_FLOAT
+        if (token == DOUBLELIT) Double.MaxValue else Float.MaxValue
       try {
         val value: Double = java.lang.Double.valueOf(name.toString()).doubleValue()
         if (value > limit)
@@ -876,7 +861,7 @@ trait JavaScanners {
     /** read a number into name and set base
     */
     protected def getNumber {
-      while (in.digit2int(in.ch, if (base < 10) 10 else base) >= 0) {
+      while (digit2int(in.ch, if (base < 10) 10 else base) >= 0) {
         putChar(in.ch)
         in.next
       }
@@ -891,7 +876,7 @@ trait JavaScanners {
             in.next
             return getFraction
           case _ =>
-            if (!isIdentStart(lookahead.ch)) {
+            if (!isIdentifierStart(lookahead.ch)) {
               putChar(in.ch)
               in.next
               return getFraction
@@ -966,13 +951,13 @@ trait JavaScanners {
   /** ...
    */   
   class JavaUnitScanner(unit: CompilationUnit) extends JavaScanner {
-    in = new CharArrayReader(unit.source.asInstanceOf[BatchSourceFile].content, !settings.nouescape.value, syntaxError)
+    in = new JavaCharArrayReader(unit.source.asInstanceOf[BatchSourceFile].content, !settings.nouescape.value, syntaxError)
     init
     def warning(pos: Int, msg: String) = unit.warning(pos, msg)
     def error  (pos: Int, msg: String) = unit.  error(pos, msg)
     def incompleteInputError(pos: Int, msg: String) = unit.incompleteInputError(pos, msg)
     def deprecationWarning(pos: Int, msg: String) = unit.deprecationWarning(pos, msg)
-    implicit def p2g(pos: Position): Int = pos.offset.getOrElse(-1)
+    implicit def p2g(pos: Position): Int = if (pos.isDefined) pos.point else -1
     implicit def g2p(pos: Int): Position = new OffsetPosition(unit.source, pos)
   }
 }
diff --git a/src/compiler/scala/tools/nsc/javac/JavaTokens.scala b/src/compiler/scala/tools/nsc/javac/JavaTokens.scala
index f953047..8a8f7d5 100644
--- a/src/compiler/scala/tools/nsc/javac/JavaTokens.scala
+++ b/src/compiler/scala/tools/nsc/javac/JavaTokens.scala
@@ -1,26 +1,13 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: Tokens.scala 12886 2007-09-17 16:36:10Z mcdirmid $
 
-package scala.tools.nsc.javac
+package scala.tools.nsc
+package javac
 
-object JavaTokens {
+object JavaTokens extends ast.parser.Tokens {
 
-  /** special tokens */
-  final val EMPTY = -3
-  final val UNDEF = -2
-  final val ERROR = -1
-  final val EOF = 0
-
-  /** literals */
-  final val CHARLIT = 1
-  final val INTLIT = 2
-  final val LONGLIT = 3
-  final val FLOATLIT = 4
-  final val DOUBLELIT = 5
-  final val STRINGLIT = 6
   def isLiteral(code : Int) =
     code >= CHARLIT && code <= STRINGLIT
 
@@ -138,20 +125,4 @@ object JavaTokens {
   final val RBRACKET = 118
   final val LBRACE = 119
   final val RBRACE = 120
-
-  def isBrace(code : Int) =
-    code >= LPAREN && code <= RBRACE
-  def isOpenBrace(code : Int) = isBrace(code) && (code % 2 == 0)
-  def isCloseBrace(code : Int) = isBrace(code) && (code % 2 == 1)
-
-  def isSpace(at : Char) = at match {
-    case ' ' | '\t' => true
-    case _ => false
-  }
-  import scala.tools.nsc.util.SourceFile._
-
-  def isNewLine(at : Char) = at match {
-    case CR | LF | FF => true
-    case _ => false
-  }
 }
diff --git a/src/compiler/scala/tools/nsc/matching/CodeFactory.scala b/src/compiler/scala/tools/nsc/matching/CodeFactory.scala
deleted file mode 100644
index 4a0773c..0000000
--- a/src/compiler/scala/tools/nsc/matching/CodeFactory.scala
+++ /dev/null
@@ -1,191 +0,0 @@
-/* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
- * @author Burak Emir
- */
-// $Id: CodeFactory.scala 16894 2009-01-13 13:09:41Z cunei $
-                                                                      
-package scala.tools.nsc.matching
-
-import scala.tools.nsc.util.Position
-
-/** Helper methods that build trees for pattern matching.
- *
- *  @author Burak Emir
- */
-trait CodeFactory { 
-  self: transform.ExplicitOuter with PatternNodes =>
-
-  import global.{typer => _, _}
-  import analyzer.Typer;
-
-  import definitions._             // standard classes and methods
-  import posAssigner.atPos         // for filling in tree positions
-  import Code._
-
-  /** Methods to simplify code generation
-   */
-  object Code {
-    // function application
-    def fn(lhs: Tree, op:   Name, args: Tree*)  = Apply(Select(lhs, op), args.toList)
-    def fn(lhs: Tree, op: Symbol, args: Tree*)  = Apply(Select(lhs, op), args.toList)
-
-    val AND   = definitions.Boolean_and
-    val NOT   = definitions.Boolean_not
-    val SEQ   = definitions.SeqClass
-    val SOME  = definitions.SomeClass
-    val TRUE  = Const(true)
-    val FALSE = Const(false)
-    val NULL  = Const(null)
-
-    object Const {
-      def apply(x: Any) = Literal(Constant(x))
-      def unapply(x: Any) = x match { 
-        case Literal(Constant(value)) => Some(value)
-        case _ => None
-      }
-    }    
-  }
-
-  final def typedValDef(x: Symbol, rhs: Tree)(implicit typer: Typer) = x.tpe match {
-    case WildcardType =>
-      rhs setType null
-      x setInfo typer.typed(rhs).tpe
-      typer.typed(ValDef(x, rhs))
-    case _ =>
-      typer.typed(ValDef(x, typer.typed(rhs, x.tpe)))
-  }
-
-  final def mkIdent(sym: Symbol)  = Ident(sym) setType sym.tpe
-  final def mk_(tpe: Type)        = Ident(nme.WILDCARD) setType tpe
-
-  /** returns A for T <: Sequence[ A ]
-   */
-  final def getElemType_Sequence(tpe: Type): Type = {
-    val tpe1 = tpe.widen.baseType(SEQ)
-    if (tpe1 == NoType)
-      Predef.error("arg " + tpe + " not subtype of Seq[A]")
-
-    tpe1.typeArgs(0)
-  }
-
-  // Option fullness check
-  final def nonEmptinessCheck(vsym: Symbol) =
-    if (vsym.tpe.typeSymbol == SOME) TRUE           // is Some[_]
-    else Not(Select(mkIdent(vsym), nme.isEmpty))    // is Option[_]
-
-  /** for tree of sequence type, returns tree that drops first i elements */
-  final def seqDrop(sel:Tree, ix: Int)(implicit typer : Typer) =
-    if (ix == 0) sel else 
-    typer.typed(Select(fn(sel, nme.drop, Const(ix)), nme.toSeq))
-
-  /** for tree of sequence type, returns tree that represents element at index i */
-  final def seqElement(sel:Tree, ix: Int)(implicit typer : Typer) =
-    typer.typed(fn(sel, sel.tpe.member(nme.apply), Const(ix)))
-  
-  /** for tree of sequence type, returns boolean tree testing that the sequence has length i */
-  final def seqHasLength(sel: Tree, ntpe: Type, i: Int)(implicit typer : Typer) = 
-    typer.typed( Equals(fn(sel, ntpe.member(nme.lengthCompare), Const(i)), Const(0)) )     // defs.Seq_length ?
-
-  /** for tree of sequence type sel, returns boolean tree testing that length >= i
-   */
-  final def seqLongerThan(sel:Tree, tpe:Type, i:Int)(implicit typer : Typer) = {
-    val cmp = fn(sel, tpe.member(nme.lengthCompare), Const(i))
-    GTE(typer.typed(cmp), typer.typed(Const(0)))  // defs.Seq_length instead of tpe.member?
-  }
-  
-  final def Equals  (left: Tree, right: Tree): Tree = fn(left, nme.EQ, right)
-  final def Eq      (left: Tree, right: Tree): Tree = fn(left, nme.eq, right)
-  final def GTE     (left: Tree, right: Tree): Tree = fn(left, nme.GE, right) // >=
-  final def And     (left: Tree, right: Tree): Tree = fn(left, AND, right)
-  final def Not                   (arg: Tree): Tree = Select(arg, NOT)
-
-  final def ThrowMatchError(pos: Position, obj: Tree) = atPos(pos) {
-    Throw( New(TypeTree(MatchErrorClass.tpe), List(List(obj))) )
-  }
-
-  final def NotNull(tree: Tree)(implicit typer : Typer) = typer.typed(fn(tree, nme.ne, NULL))
-  final def Get(tree: Tree) = fn(tree, nme.get)
-
-  // statistics
-  var nremoved = 0
-  var nsubstituted = 0
-
-  final def squeezedBlock(vds: List[Tree], exp: Tree)(implicit theOwner: Symbol): Tree = 
-    if (settings_squeeze)
-      squeezedBlock1(vds, exp)
-    else
-      Block(vds,exp)
-  
-  final def squeezedBlock1(vds: List[Tree], exp: Tree)(implicit theOwner: Symbol): Tree = {
-    val tpe = exp.tpe
-
-    class RefTraverser(sym: Symbol) extends Traverser {
-      var nref = 0
-      var nsafeRef = 0
-      override def traverse(tree: Tree) = tree match {
-        case t:Ident if t.symbol eq sym => 
-          nref += 1
-          if(sym.owner == currentOwner)  { // oldOwner should match currentOwner
-            nsafeRef += 1
-          } 
-        case LabelDef(_,args,rhs) =>
-          var args1 = args; while(args1 ne Nil) {
-            if(args1.head.symbol eq sym) {
-              nref += 2   // will abort traversal, cannot substitute this one
-              args1 = Nil // break
-            } else {
-              args1 = args1.tail
-            }
-          }
-          traverse(rhs)
-        case t if nref > 1 =>
-          // abort, no story to tell
-        case t =>
-          super.traverse(t)
-      }
-    }
-
-    class Subst(sym: Symbol, rhs: Tree) extends Transformer {
-      var stop = false
-      override def transform(tree: Tree) = tree match {
-        case t:Ident if t.symbol == sym => 
-          stop = true
-          rhs
-        case t if stop =>
-          t
-        case t => 
-          super.transform(t)
-      }
-    }
-    vds match {
-      case Nil =>
-        exp
-      case (vd:ValDef) :: rest =>
-        // recurse
-        val exp1 = squeezedBlock(rest, exp)
-
-        val sym = vd.symbol
-        val rt = new RefTraverser(sym)
-        rt.atOwner (theOwner) (rt.traverse(exp1))
-        rt.nref match {
-          case 0 =>
-            nremoved += 1 
-            exp1
-          case 1 if rt.nsafeRef == 1 =>
-            nsubstituted += 1
-            new Subst(sym, vd.rhs).transform(exp1)
-          case _ => 
-            exp1 match {
-              case Block(vds2, exp2) => Block(vd::vds2, exp2)  
-              case exp2              => Block(vd::Nil,  exp2)  
-            }
-        }
-      case x::xs => 
-        squeezedBlock(xs, exp) match {
-          case Block(vds2, exp2) => Block(x::vds2, exp2) 
-          case exp2              => Block(x::Nil,  exp2) 
-        }
-    }
-  }
-}
-
diff --git a/src/compiler/scala/tools/nsc/matching/MatchSupport.scala b/src/compiler/scala/tools/nsc/matching/MatchSupport.scala
new file mode 100644
index 0000000..2cff458
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/matching/MatchSupport.scala
@@ -0,0 +1,141 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
+ * Author: Paul Phillips
+ */
+
+package scala.tools.nsc
+package matching
+
+import transform.ExplicitOuter
+import ast.{ TreePrinters, Trees }
+import java.io.{ StringWriter, PrintWriter }
+
+/** Ancillary bits of ParallelMatching which are better off
+ *  out of the way.
+ */
+trait MatchSupport extends ast.TreeDSL { self: ParallelMatching =>
+  
+  import global.{ typer => _, _ }
+  import CODE._
+  
+  /** Debugging support: enable with -Ypmat-debug **/
+  private final def trace = settings.Ypmatdebug.value
+  
+  def impossible:           Nothing = abort("this never happens")
+  
+  object Types {
+    import definitions._
+    implicit def enrichType(x: Type): RichType = new RichType(x)
+    
+    // A subtype test which creates fresh existentials for type
+    // parameters on the right hand side.
+    private[matching] def matches(arg1: Type, arg2: Type) =
+      decodedEqualsType(arg1) matchesPattern decodedEqualsType(arg2)
+
+    class RichType(undecodedTpe: Type) {
+      def tpe = decodedEqualsType(undecodedTpe)
+      def isAnyRef = tpe <:< AnyRefClass.tpe
+      
+      // These tests for final classes can inspect the typeSymbol
+      private def is(s: Symbol) = tpe.typeSymbol eq s
+      def      isByte = is(ByteClass)
+      def     isShort = is(ShortClass)
+      def       isInt = is(IntClass)
+      def      isChar = is(CharClass)
+      def   isBoolean = is(BooleanClass)
+      def   isNothing = is(NothingClass)
+      def     isArray = is(ArrayClass)
+    }
+  }
+  
+  object Debug {
+    def typeToString(t: Type): String = t match {
+      case NoType => "x"
+      case x      => x.toString
+    }
+    def symbolToString(s: Symbol): String = s match {
+      case x  => x.toString
+    }
+    def treeToString(t: Tree): String = unbind(t) match {
+      case EmptyTree            => "?"
+      case WILD()               => "_"
+      case Literal(Constant(x)) => "LIT(%s)".format(x)
+      case Apply(fn, args)      => "%s(%s)".format(treeToString(fn), args map treeToString mkString ",")
+      case Typed(expr, tpt)     => "%s: %s".format(treeToString(expr), treeToString(tpt))
+      case x                    =>  x.toString + " (" + x.getClass + ")"
+    }
+    
+    // Formatting for some error messages
+    private val NPAD = 15
+    def pad(s: String): String = "%%%ds" format (NPAD-1) format s
+    def pad(s: Any): String = pad(s match {
+      case x: Tree    => treeToString(x)
+      case x          => x.toString
+    })
+    
+    // pretty print for debugging
+    def pp(x: Any): String = pp(x, false)
+    def pp(x: Any, newlines: Boolean): String = {
+      val stripStrings = List("""java\.lang\.""", """\$iw\.""")
+      
+      def clean(s: String): String =
+        stripStrings.foldLeft(s)((s, x) => s.replaceAll(x, ""))
+      
+      def pplist(xs: List[Any]): String =
+        if (newlines) (xs map ("    " + _ + "\n")).mkString("\n", "", "")
+        else xs.mkString("(", ", ", ")")
+
+      pp(x match {
+        case s: String      => return clean(s)
+        case x: Tree        => asCompactString(x)
+        case xs: List[_]    => pplist(xs map pp)
+        case x: Tuple2[_,_] => "%s -> %s".format(pp(x._1), pp(x._2))
+        case x              => x.toString
+      })
+    }
+    
+    def ifDebug(body: => Unit): Unit          = { if (settings.debug.value) body }
+    def DBG(msg: => String): Unit             = { ifDebug(println(msg)) }
+
+    // @elidable(elidable.FINE)
+    def TRACE(f: String, xs: Any*): Unit      = {
+      if (trace) {
+        val msg = if (xs.isEmpty) f else f.format(xs map pp: _*)
+        println(msg)
+      }
+    }
+
+    def tracing2[T](x: T)(category: String, xs: String*) = {
+      val preamble = "[" + """%10s""".format(category) + "]  "
+      if (xs.isEmpty) TRACE(preamble, x)
+      else TRACE(preamble + xs.head, xs.tail: _*) 
+
+      x
+    }
+
+    def tracing[T](s: String, x: T): T = {
+      val format = "[" + """%10s""".format(s) + "]  %s"
+      TRACE(format, x)
+      x
+    }
+    def traceCategory(cat: String, f: String, xs: Any*) = {
+      val format = "[" + """%10s""".format(cat) + "]  " + f
+      TRACE(format, xs: _*)
+    }
+
+    def indent(s: Any) = s.toString() split "\n" map ("  " + _) mkString "\n"
+    def indentAll(s: Seq[Any]) = s map ("  " + _.toString() + "\n") mkString
+  }
+  
+  /** Drops the 'i'th element of a list.
+   */
+  def dropIndex[T](xs: List[T], n: Int) = {
+    val (l1, l2) = xs splitAt n
+    l1 ::: (l2 drop 1)
+  }
+  
+  /** Extract the nth element of a list and return it and the remainder.
+   */
+  def extractIndex[T](xs: List[T], n: Int): (T, List[T]) =
+    (xs(n), dropIndex(xs, n))
+}
diff --git a/src/compiler/scala/tools/nsc/matching/MatchUtil.scala b/src/compiler/scala/tools/nsc/matching/MatchUtil.scala
deleted file mode 100644
index 7ebeba4..0000000
--- a/src/compiler/scala/tools/nsc/matching/MatchUtil.scala
+++ /dev/null
@@ -1,95 +0,0 @@
-/* NSC -- new Scala compiler
- */
-
-package scala.tools.nsc.matching
-
-/**
- *  Utility classes, most of which probably belong somewhere else.
- */
-object MatchUtil
-{
-  import collection.mutable.ListBuffer
-  
-  def impossible:           Nothing = abort("this never happens")
-  def abort(msg: String):   Nothing = throw new RuntimeException(msg)
-  
-  // def classifyPatString(pat: Tree) = pat match {
-  //   case _: Alternative                 => "Alternative"
-  //   case Typed(Strip2(_: UnApply), _)   => "Typed"
-  //   case Ident_Or_Empty()               => "Ident(_)|EmptyTree"
-  //   case _: Ident                       => "Ident"
-  //   case _: Select                      => "Select"
-  //   case UnApply_TypeApply(_, _)        => "Unapply(...TypeApply...)"
-  //   case UnApply(_: Apply, _)           => "Unapply(Apply())"
-  //   case Apply_Function(_)              => "Apply !isCaseClass"
-  //   case Apply_Value(_, _)              => "Apply_Value"
-  //   case Apply_CaseClass_NoArgs(_)      => "Apply_CaseClass_NoArgs"
-  //   case Apply_CaseClass_WithArgs()     => "Apply_CaseClass_WithArgs"
-  //   case _: ArrayValue                  => "ArrayValue"
-  //   case _                              => "Unknown!"        
-  // }  
-  
-  object Implicits {
-    implicit def listPlusOps[T](xs: List[T]) = new ListPlus(xs)
-  }
-  
-  // object Flags {
-  //   import symtab.Flags
-  //   import symtab.Symbols
-  // }
-  
-  class ListPlus[A](list: List[A]) {
-    /** Returns the list without the element at index <code>n</code>.
-     *  If this list has fewer than <code>n</code> elements, the same list is returned.
-     *
-     * @param n the index of the element to drop.
-     * @return the list without the <code>n</code>th element.
-     */
-    def dropIndex(n: Int) = list.take(n) ::: list.drop(n + 1)
-  
-    /** Returns a list formed from this list and the specified lists <code>list2</code> 
-     *  and <code>list3</code> by associating each element of the first list with
-     *  the elements at the same positions in the other two.
-     *  If any of the lists is shorter than the others, later elements in the other two are ignored.
-     *
-     *  @return     <code>List((a<sub>0</sub>,b<sub>0</sub>), ...,
-     *              (a<sub>min(m,n)</sub>,b<sub>min(m,n)</sub>))</code> when
-     *              <code>List(a<sub>0</sub>, ..., a<sub>m</sub>)
-     *              zip List(b<sub>0</sub>, ..., b<sub>n</sub>)</code> is invoked.
-     */
-    def zip3[B, C](list2: List[B], list3: List[C]): List[(A, B, C)] = {
-      val b = new ListBuffer[(A, B, C)]
-      var xs1 = list
-      var xs2 = list2
-      var xs3 = list3
-      while (!xs1.isEmpty && !xs2.isEmpty && !xs3.isEmpty) {
-        b += ((xs1.head, xs2.head, xs3.head))
-        xs1 = xs1.tail
-        xs2 = xs2.tail
-        xs3 = xs3.tail
-      }
-      b.toList
-    }
-  }
-
-  object ListPlus {
-    /** Transforms a list of triples into a triple of lists.
-     *
-     *  @param xs the list of triples to unzip
-     *  @return a triple of lists.
-     */
-    def unzip3[A,B,C](xs: List[(A,B,C)]): (List[A], List[B], List[C]) = {
-      val b1 = new ListBuffer[A]
-      val b2 = new ListBuffer[B]
-      val b3 = new ListBuffer[C]
-      var xc = xs
-      while (!xc.isEmpty) {
-        b1 += xc.head._1
-        b2 += xc.head._2
-        b3 += xc.head._3
-        xc = xc.tail
-      }
-      (b1.toList, b2.toList, b3.toList)
-    }
-  }
-}
diff --git a/src/compiler/scala/tools/nsc/matching/Matrix.scala b/src/compiler/scala/tools/nsc/matching/Matrix.scala
new file mode 100644
index 0000000..5aa4ae9
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/matching/Matrix.scala
@@ -0,0 +1,210 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
+ * Author: Paul Phillips
+ */
+
+package scala.tools.nsc
+package matching
+
+import transform.ExplicitOuter
+import symtab.Flags
+
+trait Matrix extends MatrixAdditions {
+  self: ExplicitOuter with ParallelMatching =>
+
+  import global.{ typer => _, _ }
+  import analyzer.Typer
+  import CODE._
+  import Debug._
+  import Flags.{ TRANS_FLAG, SYNTHETIC }
+
+  /** Translation of match expressions.
+   *
+   *  `p':  pattern
+   *  `g':  guard
+   *  `bx': body index
+   *
+   *   internal representation is (tvars:List[Symbol], rows:List[Row])
+   *
+   *         tmp1      tmp_n
+   *    Row( p_11  ...  p_1n   g_1  b_1 ) + subst
+   *
+   *    Row( p_m1  ...  p_mn   g_m  b_m ) + subst
+   *
+   * Implementation based on the algorithm described in
+   *
+   *   "A Term Pattern-Match Compiler Inspired by Finite Automata Theory"
+   *   Mikael Pettersson
+   *   ftp://ftp.ida.liu.se/pub/labs/pelab/papers/cc92pmc.ps.gz
+   *
+   *  @author Burak Emir
+   */
+
+  /** "The Mixture Rule"
+
+        {v=pat1, pats1 .. } {q1} 
+  match {..               } {..} 
+        {v=patn, patsn .. } {qn} 
+
+  The is the real work-horse of the algorithm. There is some column whose top-most pattern is a 
+  constructor. (Forsimplicity, itisdepicted above asthe left-most column, but anycolumn will do.) 
+  The goal is to build a test state with the variablevand some outgoing arcs (one for each construc- 
+  tor and possibly a default arc). Foreach constructor in the selected column, its arc is defined as 
+  follows: 
+
+  Let {i1,...,ij} be the rows-indices of the patterns in the column that match c. Since the pat- 
+  terns are viewed as regular expressions, this will be the indices of the patterns that either 
+  have the same constructor c, or are wildcards. 
+
+  Let {pat1,...,patj} be the patterns in the column corresponding to the indices computed 
+  above, and let nbe the arity of the constructor c, i.e. the number of sub-patterns it has. For 
+  eachpati, its n sub-patterns are extracted; if pat i is a wildcard, nwildcards are produced 
+  instead, each tagged with the right path variable. This results in a pattern matrix with n 
+  columns and j rows. This matrix is then appended to the result of selecting, from each col- 
+  umn in the rest of the original matrix, those rows whose indices are in {i1,...,ij}. Finally 
+  the indices are used to select the corresponding final states that go with these rows. Note 
+  that the order of the indices is significant; selected rows do not change their relative orders. 
+  The arc for the constructor c is now defined as (c’,state), where c’ is cwith any 
+  immediate sub-patterns replaced by their path variables (thus c’ is a simple pattern), and 
+  state is the result of recursively applying match to the new matrix and the new sequence 
+  of final states. 
+
+  Finally, the possibility for matching failure is considered. If the set of constructors is exhaustive, 
+  then no more arcs are computed. Otherwise, a default arc(_,state)is the last arc. If there are 
+  any wildcard patterns in the selected column, then their rows are selected from the rest of the 
+  matrix and the final states, and the state is the result of applying match to the new matrix and 
+  states. Otherwise,the error state is used after its reference count has been incremented. 
+  **/
+
+  case class MatrixContext(
+    handleOuter: Tree => Tree,    // for outer pointer
+    typer: Typer,                 // a local typer
+    owner: Symbol,                // the current owner
+    matchResultType: Type)        // the expected result type of the whole match
+      extends Squeezer
+  {
+    private def ifNull[T](x: T, alt: T) = if (x == null) alt else x
+    
+    // TRANS_FLAG communicates there should be no exhaustiveness checking
+    private def flags(checked: Boolean) = if (checked) Nil else List(TRANS_FLAG)
+
+    case class MatrixInit(
+      roots: List[PatternVar],
+      cases: List[CaseDef],
+      default: Tree
+    ) {
+      def tvars = roots map (_.lhs)
+      def valDefs = roots map (_.valDef)
+      override def toString() = "MatrixInit(roots = %s, %d cases)".format(pp(roots), cases.size)
+    }
+    
+    implicit def pvlist2pvgroup(xs: List[PatternVar]): PatternVarGroup =
+      PatternVarGroup(xs)
+    
+    object PatternVarGroup {
+      def apply(xs: PatternVar*) = new PatternVarGroup(xs.toList)
+      def apply(xs: List[PatternVar]) = new PatternVarGroup(xs)
+      
+      // XXX - transitional
+      def fromBindings(vlist: List[Binding], freeVars: List[Symbol] = Nil) = {
+        def vmap(v: Symbol): Option[Binding] = vlist find (_.pvar eq v)
+        val info = 
+          if (freeVars.isEmpty) vlist
+          else (freeVars map vmap).flatten
+        
+        val xs =
+          for (Binding(lhs, rhs) <- info) yield
+            new PatternVar(lhs, Ident(rhs) setType lhs.tpe, !(rhs hasFlag TRANS_FLAG))
+        
+        new PatternVarGroup(xs)
+      }
+    }
+      
+    val emptyPatternVarGroup = PatternVarGroup()
+    class PatternVarGroup(val pvs: List[PatternVar]) {
+      def syms = pvs map (_.sym)
+      def valDefs = pvs map (_.valDef)
+      def idents = pvs map (_.ident)
+      
+      def extractIndex(index: Int): (PatternVar, PatternVarGroup) = {
+        val (t, ts) = self.extractIndex(pvs, index)
+        (t, PatternVarGroup(ts))
+      } 
+      
+      def isEmpty = pvs.isEmpty
+      def size = pvs.size
+      def head = pvs.head
+      def ::(t: PatternVar) = PatternVarGroup(t :: pvs)
+      def :::(ts: List[PatternVar]) = PatternVarGroup(ts ::: pvs)
+      def ++(other: PatternVarGroup) = PatternVarGroup(pvs ::: other.pvs)
+      
+      def apply(i: Int) = pvs(i)
+      def zipWithIndex = pvs.zipWithIndex
+      def indices = pvs.indices
+      def map[T](f: PatternVar => T) = pvs map f
+      def filter(p: PatternVar => Boolean) = PatternVarGroup(pvs filter p)
+      
+      override def toString() = pp(pvs)
+    }
+
+    /** Every temporary variable allocated is put in a PatternVar.
+     */
+    class PatternVar(val lhs: Symbol, val rhs: Tree, val checked: Boolean) {
+      def sym = lhs
+      def valsym = valDef.symbol
+      // XXX how will valsym.tpe differ from sym.tpe ?
+      def tpe = valsym.tpe
+
+      lazy val ident  = ID(lhs)
+      lazy val valDef = tracing("typedVal", typer typedValDef (VAL(lhs) === rhs) setPos lhs.pos)
+
+      override def toString() = "%s: %s = %s".format(lhs, lhs.info, rhs)
+    }
+    // val NoPatternVar = PatternVar(NoSymbol, EmptyTree, false)
+    
+    /** Sets the rhs to EmptyTree, which makes the valDef ignored in Scrutinee.
+     */
+    def specialVar(lhs: Symbol, checked: Boolean) =
+      new PatternVar(lhs, EmptyTree, checked)
+    
+    /** Given a tree, creates a new synthetic variable of the same type
+     *  and assigns the tree to it.
+     */
+    def copyVar(
+      root: Tree,
+      checked: Boolean,
+      _tpe: Type = null,
+      label: String = "temp"): PatternVar =
+    {
+      val tpe   = ifNull(_tpe, root.tpe)
+      val name  = newName(root.pos, label)
+      val sym   = newVar(root.pos, tpe, flags(checked), name)
+
+      tracing("copy", new PatternVar(sym, root, checked))
+    }
+    
+    /** Creates a new synthetic variable of the specified type and
+     *  assigns the result of f(symbol) to it.
+     */
+    def createVar(tpe: Type, f: Symbol => Tree, checked: Boolean) = {
+      val lhs = newVar(owner.pos, tpe, flags(checked))
+      val rhs = f(lhs)
+      
+      tracing("create", new PatternVar(lhs, rhs, checked))
+    }      
+
+    private def newVar(
+      pos: Position,
+      tpe: Type,
+      flags: List[Long] = Nil,
+      name: Name = null): Symbol =
+    {
+      val n: Name = if (name == null) newName(pos, "temp") else name
+      // careful: pos has special meaning 
+      owner.newVariable(pos, n) setInfo tpe setFlag (SYNTHETIC.toLong /: flags)(_|_)      
+    }
+    
+    def typedValDef(x: Symbol, rhs: Tree) =
+      tracing("typedVal", typer typedValDef (VAL(x) === rhs))
+  }
+}
\ No newline at end of file
diff --git a/src/compiler/scala/tools/nsc/matching/MatrixAdditions.scala b/src/compiler/scala/tools/nsc/matching/MatrixAdditions.scala
new file mode 100644
index 0000000..d077e6c
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/matching/MatrixAdditions.scala
@@ -0,0 +1,236 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
+ * Author: Paul Phillips
+ */
+
+package scala.tools.nsc
+package matching
+
+import transform.ExplicitOuter
+import PartialFunction._
+
+/** Traits which are mixed into MatchMatrix, but separated out as
+ *  (somewhat) independent components to keep them on the sidelines.
+ */
+trait MatrixAdditions extends ast.TreeDSL
+{
+  self: ExplicitOuter with ParallelMatching =>
+  
+  import global.{ typer => _, _ }
+  import symtab.Flags
+  import CODE._
+  import Debug._
+  import treeInfo.{ IsTrue, IsFalse }
+
+  /** The Squeezer, responsible for all the squeezing.
+   */
+  private[matching] trait Squeezer {
+    self: MatrixContext =>
+    
+    def squeezedBlockPVs(pvs: List[PatternVar], exp: Tree): Tree =
+      squeezedBlock(pvs map (_.valDef), exp)
+
+    /** Compresses multiple Blocks. */
+    def mkBlock(stats: List[Tree], expr: Tree): Tree = expr match {
+      case Block(stats1, expr1) if stats.isEmpty  => mkBlock(stats1, expr1)
+      case _                                      => Block(stats, expr)
+    }
+
+    def squeezedBlock(vds: List[Tree], exp: Tree): Tree =
+      if (settings_squeeze) mkBlock(Nil, squeezedBlock1(vds, exp))
+      else                  mkBlock(vds, exp)
+
+    private def squeezedBlock1(vds: List[Tree], exp: Tree): Tree = {
+      class RefTraverser(sym: Symbol) extends Traverser {
+        var nref, nsafeRef = 0
+        override def traverse(tree: Tree) = tree match {
+          case t: Ident if t.symbol eq sym => 
+            nref += 1
+            if (sym.owner == currentOwner) // oldOwner should match currentOwner
+              nsafeRef += 1
+
+          case LabelDef(_, args, rhs) =>
+            (args dropWhile(_.symbol ne sym)) match {
+              case Nil  => 
+              case _    => nref += 2  // cannot substitute this one
+            }
+            traverse(rhs)
+          case t if nref > 1 =>       // abort, no story to tell
+          case t =>
+            super.traverse(t)
+        }
+      }
+
+      class Subst(sym: Symbol, rhs: Tree) extends Transformer {
+        var stop = false
+        override def transform(tree: Tree) = tree match {
+          case t: Ident if t.symbol == sym => 
+            stop = true
+            rhs
+          case _ => if (stop) tree else super.transform(tree)
+        }
+      }
+
+      lazy val squeezedTail = squeezedBlock(vds.tail, exp)
+      def default = squeezedTail match {
+        case Block(vds2, exp2) => Block(vds.head :: vds2, exp2)  
+        case exp2              => Block(vds.head :: Nil,  exp2)  
+      }
+
+      if (vds.isEmpty) exp 
+      else vds.head match {
+        case vd: ValDef =>
+          val sym = vd.symbol
+          val rt = new RefTraverser(sym)
+          rt.atOwner (owner) (rt traverse squeezedTail)
+
+          rt.nref match {
+            case 0                      => squeezedTail
+            case 1 if rt.nsafeRef == 1  => new Subst(sym, vd.rhs) transform squeezedTail
+            case _                      => default
+          }
+        case _          =>
+          default
+      }
+    }
+  }
+  
+  /** The Optimizer, responsible for some of the optimizing.
+   */
+  private[matching] trait MatchMatrixOptimizer {
+    self: MatchMatrix =>
+    
+    import self.context._
+    
+    final def optimize(tree: Tree): Tree = {
+      object lxtt extends Transformer {
+        override def transform(tree: Tree): Tree = tree match {
+          case blck @ Block(vdefs, ld @ LabelDef(name, params, body)) =>
+            def shouldInline(t: FinalState) = t.isReachedOnce && (t.labelSym eq ld.symbol)
+          
+            if (targets exists shouldInline) squeezedBlock(vdefs, body)
+            else blck
+
+          case t =>
+            super.transform(t match {
+              // note - it is too early for any other true/false related optimizations
+              case If(cond, IsTrue(), IsFalse())  => cond
+                          
+              case If(cond1, If(cond2, thenp, elsep1), elsep2) if (elsep1 equalsStructure elsep2) => 
+                IF (cond1 AND cond2) THEN thenp ELSE elsep1
+              case If(cond1, If(cond2, thenp, Apply(jmp, Nil)), ld: LabelDef) if jmp.symbol eq ld.symbol => 
+                IF (cond1 AND cond2) THEN thenp ELSE ld
+              case t => t
+          })
+        }
+      }
+      object resetTraverser extends Traverser {
+        import Flags._
+        def reset(vd: ValDef) =
+          if (vd.symbol hasFlag SYNTHETIC) vd.symbol resetFlag (TRANS_FLAG|MUTABLE)
+          
+        override def traverse(x: Tree): Unit = x match {
+          case vd: ValDef => reset(vd)
+          case _          => super.traverse(x)
+        }
+      }
+
+      returning(lxtt transform tree)(resetTraverser traverse _)
+    }
+  }
+  
+  /** The Exhauster.
+   */
+  private[matching] trait MatrixExhaustiveness {
+    self: MatchMatrix =>
+    
+    import self.context._
+  
+    /** Exhaustiveness checking requires looking for sealed classes
+     *  and if found, making sure all children are covered by a pattern.
+     */
+    class ExhaustivenessChecker(rep: Rep) {
+      val Rep(tvars, rows) = rep
+
+      import Flags.{ MUTABLE, ABSTRACT, SEALED, TRANS_FLAG }
+
+      private case class Combo(index: Int, sym: Symbol) {
+        // is this combination covered by the given pattern?
+        def isCovered(p: Pattern) = {
+          def cmpSymbols(t1: Type, t2: Type)  = t1.typeSymbol eq t2.typeSymbol
+          def coversSym = {
+            val tpe = decodedEqualsType(p.tpe)
+            lazy val lmoc = sym.companionModule
+            val symtpe = 
+              if ((sym hasFlag Flags.MODULE) && (lmoc ne NoSymbol))
+                singleType(sym.tpe.prefix, lmoc)   // e.g. None, Nil
+              else sym.tpe
+
+            /** Note to Martin should you come through this way: this
+             *  logic looks way overcomplicated for the intention, but a little
+             *  experimentation showed that at least most of it is serving
+             *  some necessary purpose.  It doesn't seem like much more than
+             *  "sym.tpe matchesPattern tpe" ought to be necessary though.
+             *
+             *  For the time being I tacked the matchesPattern test onto the
+             *  end to address #3097.
+             */
+            (tpe.typeSymbol == sym) ||
+            (symtpe <:< tpe) ||
+            (symtpe.parents exists (x => cmpSymbols(x, tpe))) || // e.g. Some[Int] <: Option[&b]
+            ((tpe.prefix memberType sym) <:< tpe) ||  // outer, see combinator.lexical.Scanner
+            (symtpe matchesPattern tpe)
+          }
+
+          cond(p.tree) {
+            case _: UnApply | _: ArrayValue => true
+            case x                          => p.isDefault || coversSym
+          }
+        }
+      }
+
+      /* True if the patterns in 'row' cover the given type symbol combination, and has no guard. */
+      private def rowCoversCombo(row: Row, combos: List[Combo]) =
+        row.guard.isEmpty && (combos forall (c => c isCovered row.pats(c.index)))
+
+      private def requiresExhaustive(s: Symbol) =
+         (s hasFlag MUTABLE) &&                 // indicates that have not yet checked exhaustivity
+        !(s hasFlag TRANS_FLAG) &&              // indicates @unchecked
+         (s.tpe.typeSymbol.isSealed) &&
+         { s resetFlag MUTABLE ; true }         // side effects MUTABLE flag
+
+      private lazy val inexhaustives: List[List[Combo]] = {
+        val collected =
+          for ((pv, i) <- tvars.zipWithIndex ; val sym = pv.lhs ; if requiresExhaustive(sym)) yield
+            i -> sym.tpe.typeSymbol.sealedDescendants
+
+        val folded =
+          collected.foldRight(List[List[Combo]]())((c, xs) => {
+            val (i, syms) = c match { case (i, set) => (i, set.toList) }
+            xs match {
+              case Nil  => syms map (s => List(Combo(i, s)))
+              case _    => for (s <- syms ; rest <- xs) yield Combo(i, s) :: rest
+            }
+          })
+
+        folded filterNot (combo => rows exists (r => rowCoversCombo(r, combo)))
+      }
+
+      private def mkPad(xs: List[Combo], i: Int): String = xs match {
+        case Nil                    => pad("*")
+        case Combo(j, sym) :: rest  => if (j == i) pad(sym.name.toString) else mkPad(rest, i)
+      }
+      private def mkMissingStr(open: List[Combo]) =
+        "missing combination %s\n" format tvars.indices.map(mkPad(open, _)).mkString
+
+      /** The only public method. */
+      def check = {
+        def errMsg = (inexhaustives map mkMissingStr).mkString
+        if (inexhaustives.nonEmpty)
+          cunit.warning(tvars.head.lhs.pos, "match is not exhaustive!\n" + errMsg)
+
+        rep
+      }
+    }
+  }
+}
\ No newline at end of file
diff --git a/src/compiler/scala/tools/nsc/matching/ParallelMatching.scala b/src/compiler/scala/tools/nsc/matching/ParallelMatching.scala
index 4c2f600..0398aae 100644
--- a/src/compiler/scala/tools/nsc/matching/ParallelMatching.scala
+++ b/src/compiler/scala/tools/nsc/matching/ParallelMatching.scala
@@ -1,1023 +1,923 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * Copyright 2007 Google Inc. All Rights Reserved.
  * Author: bqe at google.com (Burak Emir)
  */
-// $Id: ParallelMatching.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.tools.nsc.matching
+package scala.tools.nsc
+package matching
 
 import util.Position
+import transform.ExplicitOuter
+import symtab.Flags
 import collection._
-import mutable.BitSet
+import mutable.ListBuffer
 import immutable.IntMap
-import MatchUtil.ListPlus._
-import MatchUtil.Implicits._
-import MatchUtil._
-
-/** Translation of match expressions.
- *
- *  `p':  pattern
- *  `g':  guard
- *  `bx': body index
- *
- *   internal representation is (temp:List[Symbol], row:List[Row])
- *
- *         tmp1      tmp_n
- *    Row( p_11  ...  p_1n   g_1  b_1 ) + subst
- *
- *    Row( p_m1  ...  p_mn   g_m  b_m ) + subst
- *
- */
-trait ParallelMatching  {
-  self: transform.ExplicitOuter with PatternNodes with CodeFactory =>
-
-  import global.{typer => _, _}
-  import analyzer.Typer;
-  import symtab.Flags
+import annotation.elidable
+
+trait ParallelMatching extends ast.TreeDSL
+      with MatchSupport
+      with Matrix
+      with Patterns
+      with PatternBindings
+{
+  self: ExplicitOuter =>
+
+  import global.{ typer => _, _ }
+  import definitions.{ AnyRefClass, IntClass, BooleanClass, getProductArgs, productProj }
+  import CODE._
   import Types._
-  import Code.{ fn, Const }
-  
-  class Scrutinee(val sym: Symbol) {
-    import definitions._
-    
-    def mkList(xs: List[Symbol]) = sym :: xs
-    def mkList(prefix: List[Symbol], suffix: List[Symbol]) = prefix ::: sym :: suffix
-    def isDefined = sym ne NoSymbol
-    def accessors = sym.caseFieldAccessors
-    def id = mkIdent(sym)
-    def tpe = sym.tpe
-    def pos = sym.pos
-    def isChar = tpe.widen.isChar
-    def isSimple = isChar || tpe.widen.isInt
-    lazy val sequenceType = tpe.widen.baseType(SeqClass)
-    lazy val elementType = sequenceType match {
-      case NoType => Predef.error("arg " + tpe + " not subtype of Seq[A]")
-      case _      => tpe.typeArgs(0)
-    }
-    // for propagating "unchecked" to synthetic vars
-    def flags: List[Long] = if (sym hasFlag Flags.TRANS_FLAG) List(Flags.TRANS_FLAG) else Nil
+  import Debug._
+  import Flags.{ TRANS_FLAG }
+  import PartialFunction._
 
-    def assertIsSubtype(other: Type) = assert(isSubType(tpe, other), "problem "+tpe+" not <: "+other)
-    def casted(headType: Type)(implicit theOwner: Symbol) =
-      if (tpe =:= headType) this
-      else new Scrutinee(newVar(pos, headType, flags))
-  }
+  /** Transition **/
+  def toPats(xs: List[Tree]): List[Pattern] = xs map Pattern.apply  
   
-  case class Pattern(tree: Tree) {
-    implicit def mkPattern(t: Tree) = Pattern(t)
-    import definitions._
-    lazy val    sym = tree.symbol
-    lazy val    tpe = tree.tpe
-    lazy val symtpe = sym.tpe
-    lazy val prefix = tpe.prefix
-    lazy val stripped   = strip2
-    lazy val tpeIfHead  = stripped.tree match {
-      case p @ (_:Ident | _:Select) => singleType(stripped.prefix, stripped.sym) //should be singleton object
-      case __UnApply(_,argtpe,_)    => argtpe
-      case _                        => tpe
-    }
-    
-    // true if this pattern allows for a simple switch statement to be generated
-    lazy val isSimpleSwitchCandidate = stripped.tree match {
-      case Literal(const : Constant) if isNumeric(const.tag) =>
-        const.tag match {
-          case FloatTag | DoubleTag | LongTag => false
-          case _ => true
-        }
-      case _ => false
-    }
-    
-    /** returns if pattern can be considered a no-op test ??for expected type?? */
-    final def isDefault: Boolean = tree match {
-      case Bind(_, t)             => t.isDefault
-      case EmptyTree              => true // dummy
-      case Ident(nme.WILDCARD)    => true
-      case _                      => false
-    // -- what about the following? still have to test "ne null" :/
-    //  case Typed(nme.WILDCARD,_) => pattern.tpe <:< scrut.tpe
-    }
-    
-    final def isEquals = tpe match {
-      case TypeRef(_, sym, _) => sym eq EqualsPatternClass
-      case _                  => false
-    }
+  /** The umbrella matrix class. **/  
+  abstract class MatchMatrix(val context: MatrixContext) extends MatchMatrixOptimizer with MatrixExhaustiveness {
+    import context._
     
-    final def isAlternative: Boolean = tree match { 
-      case Bind(_, t)         => t.isAlternative
-      case _: Alternative     => true 
-      case _                  => false
-    }
-    
-    final def getAlternativeBranches: List[Tree] = {
-      def get_BIND(pctx: Tree => Tree, p: Tree): List[Tree] = p match { 
-        case b @ Bind(n, p)   => get_BIND((x: Tree) => pctx(copy.Bind(b, n, x) setType x.tpe), p)
-        case Alternative(ps)  => ps map pctx
-      }
-      get_BIND(x => x, tree)
-    }
+    def data: MatrixContext#MatrixInit
 
-    /** returns all variables that are binding the given pattern 
-     *  @param   x a pattern
-     *  @return  vs variables bound, p pattern proper
+    lazy val MatrixInit(roots, cases, failTree)  = data
+    lazy val ExpandedMatrix(rows, targets)       = expand(roots, cases)
+    lazy val expansion: Rep                      = make(roots, rows)
+
+    val shortCuts   = new ListBuffer[Symbol]()
+
+    final def shortCut(theLabel: Symbol): Int = {
+      shortCuts += theLabel
+      -shortCuts.length
+    }
+     
+    /** first time bx is requested, a LabelDef is returned. next time, a jump.
+     *  the function takes care of binding
      */
-    final def strip: (immutable.Set[Symbol], Pattern) = tree match {
-      case b @ Bind(_, t)   => val (vs, p) = Pattern(t).strip ; (vs + b.symbol, p)
-      case _                => (emptySymbolSet, this)
+    final def requestBody(bx: Int, subst: Bindings): Tree = {
+      // shortcut
+      if (bx < 0)
+        return Apply(ID(shortCuts(-bx-1)), Nil)
+      
+      val pvgroup = PatternVarGroup.fromBindings(subst.get(), targets(bx).freeVars)
+      val target = targets(bx)
+      
+      // first time this bx is requested - might be bound elsewhere
+      if (target.isNotReached) target.createLabelBody(bx, pvgroup)
+      // call label "method" if possible
+      else target.getLabelBody(pvgroup)
     }
-    final def strip1: Set[Symbol] = strip._1
-    final def strip2: Pattern     = strip._2
-
-    final def definedVars: List[Symbol] = {
-      implicit def listToStream[T](xs: List[T]): Stream[T] = xs.toStream
-      def definedVars1(x: Tree): Stream[Symbol] = x match {
-        case Apply(_, args)     => definedVars2(args)
-        case b @ Bind(_,p)      => Stream.cons(b.symbol, definedVars1(p))
-        case Typed(p,_)         => definedVars1(p)    // otherwise x @ (_:T)
-        case UnApply(_,args)    => definedVars2(args)
-        case ArrayValue(_,xs)   => definedVars2(xs)   
-        case _                  => Nil
-      }
-      def definedVars2(args: Stream[Tree]): Stream[Symbol] = args flatMap definedVars1
 
-      definedVars1(tree).reverse.toList
-    }
+    /** the injection here handles alternatives and unapply type tests */
+    final def make(tvars: PatternVarGroup, row1: List[Row]): Rep = {
+      // TRACE("make(%s%s)", pp(tvars.pvs, 1, true), pp(row1, 1, true))
+      def classifyPat(opat: Pattern, j: Int): Pattern = opat simplify tvars(j)
 
-    /** returns true if pattern tests an object */
-    final def isObjectTest(head: Type) =
-      (sym ne null) && (sym != NoSymbol) && prefix.isStable && (head =:= singleType(prefix, sym))
-  }
-  
-  case class Patterns(scrut: Scrutinee, ps: List[Pattern]) {
-    private lazy val column = ps.map(_.tree)
-    lazy val head = ps.head
-    lazy val tail = Patterns(scrut, ps.tail)
-    lazy val last = ps.last
-    lazy val headType = head.tpeIfHead
-    lazy val isCaseHead = headType.isCaseClass
-    lazy val dummies = if (isCaseHead) getDummies(headType.typeSymbol.caseFieldAccessors.length) else Nil
-    lazy val size = ps.length
-    
-    def apply(i: Int): Tree = ps(i).tree
-    def zip() = column.zipWithIndex
-    def zip[T](ys: List[T]) = column.zip(ys)
-    
-    def isObjectTest(pat: Pattern)  = pat.isObjectTest(headType)
-    def isObjectTest(pat: Tree)     = Pattern(pat).isObjectTest(headType)
-    // an unapply for which we don't need a type test
-    def isUnapplyHead = head.tree match {
-      case __UnApply(_,argtpe,_)  => scrut.tpe <:< argtpe
-      case _                      => false
+      val rows = row1 flatMap (_ expandAlternatives classifyPat)
+      if (rows.length != row1.length) make(tvars, rows)  // recursive call if any change
+      else Rep(tvars, rows).checkExhaustive
     }
     
-    def isSimpleSwitch: Boolean =
-      scrut.isSimple && ps.init.forall(_.isSimpleSwitchCandidate) &&
-      // TODO: This needs to also allow the case that the last is a compatible type pattern.
-      (last.isSimpleSwitchCandidate || last.isDefault)
-    
-    def mkRule(rest: Rep)(implicit rep: RepFactory): RuleApplication = head match {
-      case x if x.isEquals          => new MixEquals(this, rest)
-      case Pattern(x: ArrayValue)   => if (isRightIgnoring(x)) new MixSequenceStar(this, rest)
-                                       else new MixSequence(this, rest)
-      case _ if isSimpleSwitch      => new MixLiterals(this, rest)
-      case _ if isUnapplyHead       => new MixUnapply(this, rest)
-      case _                        => new MixTypes(this, rest)
-    }
-  }
-  
-  case class Guard(tree: Tree) {
-    def isEmpty = tree eq EmptyTree
-    def duplicate = Guard(tree.duplicate)
+    override def toString() = "MatchMatrix(%s) { %s }".format(matchResultType, indentAll(targets))
     
-    def mkIf(thenPart: Tree, elsePart: Tree) = If(tree.duplicate, thenPart, elsePart)
-  }
-  val NoGuard = Guard(EmptyTree)
-
-  /** picks which rewrite rule to apply
-   *  @precondition: column does not contain alternatives (ensured by initRep)
-   */
-  def MixtureRule(scrut: Scrutinee, column: List[Tree], rest: Rep)(implicit rep: RepFactory): RuleApplication =
-    Patterns(scrut, column map Pattern) mkRule rest
-
-  sealed abstract class RuleApplication(rep: RepFactory) {
-    def scrut: Scrutinee
-    implicit def typer = rep.typer
-
-    // used in MixEquals and MixSequence
-    final protected def repWithoutHead(pats: Patterns, rest: Rep)(implicit theOwner: Symbol): Rep = {
-      val nfailrow = List.map2(pats.tail.ps, rest.row.tail)((p, r) => r.insert(p))
-      rep.make(scrut.mkList(rest.temp), nfailrow)
-    }
-
-    /** translate outcome of the rule application into code (possible involving recursive application of rewriting) */
-    def tree(implicit theOwner: Symbol, failTree: Tree): Tree 
-  }
+    /**
+     * Encapsulates a symbol being matched on.  It is created from a
+     * PatternVar, which encapsulates the symbol's creation and assignment.
+     * 
+     * We never match on trees directly - a temporary variable is created
+     * (in a PatternVar) for any expression being matched on.
+     */ 
+    class Scrutinee(val pv: PatternVar) {
+      import definitions._
+
+      // presenting a face of our symbol
+      def sym   = pv.sym      
+      def tpe   = sym.tpe
+      def pos   = sym.pos
+      def id    = ID(sym) setPos pos  // attributed ident
+      
+      def accessors     = if (isCaseClass) sym.caseFieldAccessors else Nil
+      def accessorTypes = accessors map (x => (tpe memberType x).resultType)
+      
+      lazy val accessorPatternVars  = PatternVarGroup(
+        for ((accessor, tpe) <- accessors zip accessorTypes) yield
+          createVar(tpe, _ => fn(id, accessor))
+      )
+      
+      private def extraValDefs = if (pv.rhs.isEmpty) Nil else List(pv.valDef)
+      def allValDefs = extraValDefs ::: accessorPatternVars.valDefs
 
-  case class ErrorRule(implicit rep:RepFactory) extends RuleApplication(rep) {
-    def scrut: Scrutinee = impossible
-    final def tree(implicit theOwner: Symbol, failTree: Tree) = failTree
-  }
+      // tests
+      def isDefined   = sym ne NoSymbol
+      def isSimple    = tpe.isByte || tpe.isShort || tpe.isChar || tpe.isInt
+      def isCaseClass = tpe.typeSymbol hasFlag Flags.CASE
 
-  /**  {case ... if guard => bx} else {guardedRest} */
-  case class VariableRule(subst: Bindings, guard: Guard, guardedRest: Rep, bx: Int)(implicit rep:RepFactory) extends RuleApplication(rep) {
-    def scrut: Scrutinee = impossible
-    final def tree(implicit theOwner: Symbol, failTree: Tree): Tree = {
-      val body = typer.typed { rep.requestBody(bx, subst) }
-      lazy val vdefs = subst.targetParams
-      lazy val typedElse = repToTree(guardedRest)
-      lazy val typedIf = typer.typed(guard.mkIf(body, typedElse))
-
-      if (guard.isEmpty) body
-      else typer.typed(squeezedBlock(vdefs, typedIf))
-    }
-  } 
+      // sequences
+      def seqType         = tpe.widen baseType SeqClass
+      def elemType        = tpe typeArgs 0
+      
+      private def elemAt(i: Int)  = (id DOT (tpe member nme.apply))(LIT(i))
+      private def createElemVar(i: Int)   = createVar(elemType, _ => elemAt(i))
+      private def createSeqVar(drop: Int) = createVar(seqType, _ => id DROP drop)
+          
+      def createSequenceVars(count: Int): List[PatternVar] =
+        (0 to count).toList map (i => if (i < count) createElemVar(i) else createSeqVar(i))
 
-  /** superclass of mixture rules for case classes and literals (both translated to switch on an integer)
-   */
-  abstract class CaseRuleApplication(rep: RepFactory) extends RuleApplication(rep) {
-    val pats:   Patterns
-    val rest:   Rep
+      // for propagating "unchecked" to synthetic vars
+      def isChecked = !(sym hasFlag TRANS_FLAG)
+      def flags: List[Long] = List(TRANS_FLAG) filter (sym hasFlag _)
+      
+      // this is probably where this actually belongs
+      def createVar(tpe: Type, f: Symbol => Tree) = context.createVar(tpe, f, isChecked)
 
-    // e.g. (1,1) (1,3) (42,2) for column { case ..1.. => ;; case ..42..=> ;; case ..1.. => }
-    var defaultV: immutable.Set[Symbol] = emptySymbolSet
-    var defaultIndexSet = new BitSet(pats.size)
+      def castedTo(headType: Type) =
+        if (tpe =:= headType) this
+        else new Scrutinee(createVar(headType, lhs => id AS_ANY lhs.tpe))
+      
+      override def toString() = "(%s: %s)".format(id, tpe)
+    }
+    
+    def isPatternSwitch(scrut: Scrutinee, ps: List[Pattern]): Option[PatternSwitch] = {
+      def isSwitchableConst(x: Pattern) = cond(x) { case x: LiteralPattern if x.isSwitchable => true }
+      def isSwitchableDefault(x: Pattern) = isSwitchableConst(x) || x.isDefault
+      
+      // TODO - scala> (5: Any) match { case 5 => 5 ; case 6 => 7 }
+      // ... should compile to a switch.  It doesn't because the scrut isn't Int/Char, but
+      // that could be handle in an if/else since every pattern requires an Int.
+      // More immediately, Byte and Short scruts should also work.
+      if (!scrut.isSimple) None
+      else {
+        val (_lits, others) = ps span isSwitchableConst
+        val lits = _lits collect { case x: LiteralPattern => x }
     
-    def insertDefault(tag: Int, vs: Set[Symbol]) {
-      defaultIndexSet += tag
-      defaultV = defaultV ++ vs
+        condOpt(others) {
+          case Nil                                => new PatternSwitch(scrut, lits, None)
+          // TODO: This needs to also allow the case that the last is a compatible type pattern.
+          case List(x) if isSwitchableDefault(x)  => new PatternSwitch(scrut, lits, Some(x))
+        } 
+      }
     }
 
-    def haveDefault: Boolean          = !defaultIndexSet.isEmpty 
-    def defaultRows: List[Row]   = defaultIndexSet.toList reverseMap grabRow
-
-    protected var tagIndices = IntMap.empty[List[Int]]
-    protected def grabRow(index: Int): Row = {
-      val r = rest.row(index)
-      if (defaultV.isEmpty) r
-      else r.insert2(Nil, strip1(pats(index)), scrut.sym)  // get vars
+    class PatternSwitch(
+      scrut: Scrutinee,
+      override val ps: List[LiteralPattern],
+      val defaultPattern: Option[Pattern]
+    ) extends PatternMatch(scrut, ps) {
+      require(scrut.isSimple && (ps forall (_.isSwitchable)))
     }
 
-    /** inserts row indices using in to list of tagIndices */
-    protected def tagIndicesToReps(implicit theOwner: Symbol) : List[(Int, Rep)] = 
-      tagIndices map { case (k, v) => (k, rep.make(rest.temp, v.reverseMap(grabRow) ::: defaultRows)) } toList
-
-    protected def defaultsToRep(implicit theOwner: Symbol) = rep.make(rest.temp, defaultRows)
-
-    protected def insertTagIndexPair(tag: Int, index: Int) =
-      tagIndices = tagIndices.update(tag, index :: tagIndices.getOrElse(tag, Nil))
-
-    /** returns 
-     *  @return list of continuations, 
-     *  @return variables bound to default continuation,  
-     *  @return optionally, a default continuation
-     **/
-    def getTransition(implicit theOwner: Symbol): (List[(Int,Rep)], Set[Symbol], Option[Rep]) =
-      (tagIndicesToReps, defaultV, if (haveDefault) Some(defaultsToRep) else None)
-  }
-
-  /** mixture rule for literals
-   */
-  class MixLiterals(val pats: Patterns, val rest:Rep)(implicit rep:RepFactory) extends CaseRuleApplication(rep) {
-    val Patterns(scrut, patterns) = pats
-    
-    val varMap: List[(Int, List[Symbol])] =
-      (for ((x, i) <- pats.zip) yield strip2(x) match {
-        case p @ Const(c: Int)        => insertTagIndexPair(c, i)       ; Some(c,       definedVars(x))
-        case p @ Const(c: Char)       => insertTagIndexPair(c.toInt, i) ; Some(c.toInt, definedVars(x))
-        case p if isDefaultPattern(p) => insertDefault(i, strip1(x))    ; None
-      }) . flatMap(x => x) . reverse
-
-    // lazy
-    private def bindVars(Tag: Int, orig: Bindings): Bindings  = {
-      def myBindVars(rest:List[(Int,List[Symbol])], bnd: Bindings): Bindings  = rest match {
-        case Nil => bnd
-        case (Tag,vs)::xs => myBindVars(xs, bnd.add(vs, scrut.sym))
-        case (_,  vs)::xs => myBindVars(xs, bnd)
+    case class PatternMatch(scrut: Scrutinee, ps: List[Pattern]) {
+      def head = ps.head
+      def tail = ps.tail
+      def size = ps.length
+      
+      def headType = head.necessaryType
+      def isCaseHead = head.isCaseClass
+      private val dummyCount = if (isCaseHead) headType.typeSymbol.caseFieldAccessors.length else 0
+      def dummies = emptyPatterns(dummyCount)
+
+      def apply(i: Int): Pattern = ps(i)
+      def pzip() = ps.zipWithIndex
+      def pzip[T](others: List[T]) = {
+        assert(ps.size == others.size, "Internal error: ps = %s, others = %s".format(ps, others))
+        ps zip others
       }
-      myBindVars(varMap, orig)
-    }
 
-    final def tree(implicit theOwner: Symbol, failTree: Tree): Tree = {
-      val (branches, defaultV, defaultRep) = this.getTransition // tag body pairs
-      val cases = for ((tag, r) <- branches) yield {
-        val r2 = rep.make(r.temp, r.row.map(x => x.rebind(bindVars(tag, x.subst))))
-        CaseDef(Literal(tag), EmptyTree, repToTree(r2))
+      // Any unapply - returns Some(true) if a type test is needed before the unapply can
+      // be called (e.g. def unapply(x: Foo) = { ... } but our scrutinee is type Any.)
+      object AnyUnapply {
+        def unapply(x: Pattern): Option[Boolean] = condOpt(x.tree) {
+          case UnapplyParamType(tpe) => !(scrut.tpe <:< tpe)
+        }
       }
-      lazy val ndefault = defaultRep.map(repToTree) getOrElse failTree
-      lazy val casesWithDefault = cases ::: List(CaseDef(mk_(definitions.IntClass.tpe), EmptyTree, ndefault))
       
-      cases match {
-        case CaseDef(lit,_,body) :: Nil   => If(Equals(scrut.id, lit), body, ndefault)
-        case _ if scrut.isChar            => Match(Select(scrut.id, nme.toInt), casesWithDefault) // chars to ints
-        case _                            => Match(scrut.id, casesWithDefault)
-      }
-    }
-  }
-  
-  /** mixture rule for unapply pattern
-   */
-  class MixUnapply(val pats: Patterns, val rest: Rep)(implicit rep: RepFactory)
-  extends RuleApplication(rep) {
-    val Patterns(scrut, patterns) = pats
-    val Strip(vs, unapp) = pats.head.tree
-    lazy val ua @ UnApply(app @ Apply(fxn, appargs), args) = unapp
-
-    def newVarCapture(pos: Position,tpe: Type)(implicit theOwner:Symbol) = newVar(pos, tpe, scrut.flags)
-
-    /** returns (unapply-call, success-rep, optional fail-rep*/
-    final def getTransition(implicit theOwner: Symbol): (Tree, List[Tree], Rep, Option[Rep]) = {
-      object sameUnapplyCall {
-        def unapply(t: Tree) = t match {
-          case UnApply(Apply(fn1,_), differentArgs) if (fxn.symbol == fn1.symbol) && fxn.equalsStructure(fn1) =>
-            Some(differentArgs)
-          case _ => 
-            None
+      object TypedUnapply {
+        def unapply(x: Tree): Option[Boolean] = condOpt(x) {
+          case Typed(UnapplyParamType(tpe), tpt) => !(tpt.tpe <:< tpe)
         }
       }
-      val ures = newVarCapture(ua.pos, app.tpe)
-      val rhs = Apply(fxn, scrut.id :: appargs.tail) setType ures.tpe
-      val uacall = typedValDef(ures, rhs)
-      val zipped = pats.zip(rest.row)
-      val nrowsOther = zipped.tail flatMap
-        { case (Strip2(sameUnapplyCall(_)), _) => Nil ; case (pat, r) => List(r.insert(pat)) }
-        
-      val nrepFail = 
-        if (nrowsOther.isEmpty) None
-        else Some(rep.make(scrut.mkList(rest.temp), nrowsOther))
-        
-      def mkTransition(vdefs: List[Tree], ntemps: List[Symbol], nrows: List[Row]) =
-        (uacall, vdefs, rep.make(scrut.mkList(ntemps, rest.temp), nrows), nrepFail)          
-        
-      // Second argument is number of dummies to prepend in the default case
-      def mkNewRows(sameFilter: (List[Tree]) => List[Tree], dum: Int) =
-        for ((pat @ Strip(vs, p), r) <- zipped) yield p match {
-          case sameUnapplyCall(args)  => r.insert2(sameFilter(args) ::: List(EmptyTree), vs, scrut.sym)
-          case _                      => r.insert(getDummies(dum) ::: List(pat))
-        }
+
+      def mkRule(rest: Rep): RuleApplication = {
+        tracing("Rule", head match {
+          case x if isEquals(x.tree.tpe)        => new MixEquals(this, rest)
+          case x: SequencePattern               => new MixSequence(this, rest, x)
+          case AnyUnapply(false)                => new MixUnapply(this, rest, false)
+          case _ =>
+            isPatternSwitch(scrut, ps) match {
+              case Some(x)  => new MixLiteralInts(x, rest)
+              case _        => new MixTypes(this, rest)
+            }
+        })
+      }
+      override def toString() = "%s match {%s}".format(scrut, indentAll(ps))
+    } // PatternMatch
+  
+    /** picks which rewrite rule to apply
+     *  @precondition: column does not contain alternatives
+     */
+    def MixtureRule(scrut: Scrutinee, column: List[Pattern], rest: Rep): RuleApplication =
+      PatternMatch(scrut, column) mkRule rest
+
+    /**
+     * Class encapsulating a guard expression in a pattern match:
+     *   case ... if(tree) => ...
+     */ 
+    case class Guard(tree: Tree) {
+      def isEmpty   = tree.isEmpty
+      def duplicate = Guard(tree.duplicate)
+      override def toString() = if (isEmpty) "" else " // if %s" format tree
+    }
+    val NoGuard = Guard(EmptyTree)
+
+    /***** Rule Applications *****/
+
+    sealed abstract class RuleApplication {
+      // def isFinal = false
+      // def body = tree
+      // def freeVars = (scrut.pv :: rest.tvars).syms
       
-      args.length match {
-        case 0  => // special case for unapply(), app.tpe is boolean
-          mkTransition(Nil, Nil, mkNewRows((xs) => Nil, 0))
-          
-        case 1 => // special case for unapply(p), app.tpe is Option[T]
-          val vtpe = app.tpe.typeArgs(0)
-          val vsym = newVarCapture(ua.pos, vtpe)
-          val nrows = mkNewRows((xs) => List(xs.head), 1)
-          val vdef = typedValDef(vsym, Get(mkIdent(ures)))
-          mkTransition(List(vdef), List(vsym), nrows)
-                  
-        case _ => // app.tpe is Option[? <: ProductN[T1,...,Tn]]
-          val uresGet = newVarCapture(ua.pos, app.tpe.typeArgs(0))
-          val vdefHead = typedValDef(uresGet, Get(mkIdent(ures)))
-          val ts = definitions.getProductArgs(uresGet.tpe).get
-          val nrows = mkNewRows(identity, ts.size)
-          val (vdefs: List[Tree], vsyms: List[Symbol]) = List.unzip(
-            for ((vtpe, i) <- ts.zip((1 to ts.size).toList)) yield {
-              val vchild = newVarCapture(ua.pos, vtpe)
-              val accSym = definitions.productProj(uresGet, i)
-              val rhs = typer.typed(Code.fn(mkIdent(uresGet), accSym))
-
-              (typedValDef(vchild, rhs), vchild)
-            })
-          mkTransition(vdefHead :: vdefs, vsyms, nrows)
+      def pmatch: PatternMatch
+      def rest: Rep
+      def cond: Tree
+      def success: Tree
+      def failure: Tree
+      
+      lazy val PatternMatch(scrut, patterns) = pmatch
+      lazy val head = pmatch.head
+      def codegen: Tree = IF (cond) THEN (success) ELSE (failure)
+      
+      def mkFail(xs: List[Row]): Tree =
+        if (xs.isEmpty) failTree
+        else remake(xs).toTree
+      
+      def remake(
+        rows: List[Row],
+        pvgroup: PatternVarGroup = emptyPatternVarGroup,
+        includeScrut: Boolean = true): Rep =
+      {
+        val scrutpvs = if (includeScrut) List(scrut.pv) else Nil
+        make(pvgroup.pvs ::: scrutpvs ::: rest.tvars, rows)  
       }
-    } /* def getTransition(...) */
 
-    final def tree(implicit theOwner: Symbol, failTree: Tree) = {
-      val (uacall, vdefs, srep, frep) = this.getTransition
-      val succ = repToTree(srep)
-      val fail = frep.map(repToTree) getOrElse failTree
-      val cond = 
-        if (uacall.symbol.tpe.isBoolean) typer.typed(mkIdent(uacall.symbol))
-        else nonEmptinessCheck(uacall.symbol)
-
-      typer.typed( squeezedBlock(List(rep.handleOuter(uacall)), If(cond,squeezedBlock(vdefs,succ),fail)) )
+      /** translate outcome of the rule application into code (possible involving recursive application of rewriting) */
+      def tree(): Tree
+      
+      override def toString =       
+        "Rule/%s (%s =^= %s)".format(getClass.getSimpleName, scrut, head)
     }
-  }
 
-  /** handle sequence pattern and ArrayValue (but not star patterns)
-   */
-  sealed class MixSequence(val pats: Patterns, val rest: Rep)(implicit rep: RepFactory) extends RuleApplication(rep) {
-    val Patterns(scrut, patterns) = pats
-        
-    final def removeStar(xs: List[Tree]): List[Tree] = 
-      xs.init ::: makeBind(strip1(xs.last).toList, mk_(scrut.sequenceType)) :: Nil
-    
-    protected def getSubPatterns(len:Int, x:Tree):Option[List[Tree]] = x match {
-      case av @ ArrayValue(_,xs) if (!isRightIgnoring(av) && xs.length == len)   => Some(xs ::: List(EmptyTree))
-      case av @ ArrayValue(_,xs) if ( isRightIgnoring(av) && xs.length == len+1) => Some(removeStar(xs)) // (*) 
-      case EmptyTree | Ident(nme.WILDCARD)                                       => Some(getDummies(len+1))
-      case _                                                                     => None
+    /** {case ... if guard => bx} else {guardedRest} */
+    /** VariableRule: The top-most rows has only variable (non-constructor) patterns. */
+    case class VariableRule(subst: Bindings, guard: Guard, guardedRest: Rep, bx: Int) extends RuleApplication {
+      def pmatch: PatternMatch = impossible
+      def rest: Rep = guardedRest
+      
+      lazy val cond     = if (guard.isEmpty) TRUE else guard.duplicate.tree
+      lazy val success  = requestBody(bx, subst)
+      lazy val failure  = guardedRest.toTree
+      
+      lazy val pvgroup  = PatternVarGroup.fromBindings(subst.get())
+      
+      final def tree(): Tree = 
+        if (guard.isEmpty) success
+        else squeezedBlock(pvgroup.valDefs, codegen)
     }
 
-    protected def makeSuccRep(vs: List[Symbol], tail: Symbol, nrows: List[Row])(implicit theOwner: Symbol) =
-      rep.make(vs ::: tail :: rest.temp, nrows)
-        
-    /** True if x must be checked even if y failed to match after passing its length test
-      * (the conditional supplied by getCond)
-      */
-    protected def mustCheck(x:Tree, y:Tree): Boolean =
-      isDefaultPattern(x) || ((x, y) match {
-        case (av @ ArrayValue(_,xs), bv @ ArrayValue(_,ys)) => 
-          // if they are both right-ignoring, x must be more general if it has fewer literals - bug #889
-          if (isRightIgnoring(av) && isRightIgnoring(bv) && xs.length < ys.length) true
-          // otherwise, x is more general only if it is y plus a star      
-          else isRightIgnoring(av) && !isRightIgnoring(bv) && xs.length == ys.length+1                   // see (*) 
-        case _ => 
-          false
-      })
-    // context (to be used in IF), success and failure Rep 
-    def getTransition(implicit theOwner: Symbol): (Tree => Tree => Tree, Rep, Rep) = { 
-      scrut.assertIsSubtype(pats.head.tpe)
-      val treeAsSeq = scrut.id                // scrut.tpe <:< column.head.tpe confirmed by assertion
-      val av @ ArrayValue(_, xs) = pats.head.tree
-      val ys = if (isRightIgnoring(av)) xs.init else xs
-      val vs = ys map(y => newVar(strip2(y).pos, scrut.elementType))
-      
-      lazy val tail = newVar(scrut.pos, scrut.sequenceType)
-      lazy val lastBinding = if (ys.size > 0) seqDrop(treeAsSeq.duplicate, ys.size) else scrut.id
-      val bindings = 
-        (for ((v, i) <- vs.zipWithIndex) yield typedValDef(v, seqElement(treeAsSeq.duplicate, i))) :::
-        List(typedValDef(tail, lastBinding))
+    /** Mixture rule for all literal ints (and chars) i.e. hopefully a switch
+     *  will be emitted on the JVM.
+     */
+    class MixLiteralInts(val pmatch: PatternSwitch, val rest: Rep) extends RuleApplication
+    {
+      val literals = pmatch.ps
+      val defaultPattern = pmatch.defaultPattern
+      
+      private lazy val casted: Tree =
+        if (!scrut.tpe.isInt) scrut.id DOT nme.toInt else scrut.id      
               
-      val (nrows, frows) = List.unzip(
-        for ((c, row) <- pats.zip(rest.row)) yield getSubPatterns(ys.size, c) match {
-          case Some(ps) => (Some(row.insert(ps)), if (mustCheck(c, av)) Some(row.insert(c)) else None)
-          case None     => (None, Some(row.insert(c)))
-        })
-
-      val succRep = makeSuccRep(vs, tail, nrows.flatMap(x => x))
-      val failRep = rep.make(scrut.mkList(rest.temp), frows.flatMap(x => x))
+      // creates a row transformer for injecting the default case bindings at a given index
+      private def addDefaultVars(index: Int): Row => Row =
+        if (defaultVars.isEmpty) identity
+        else rebindAll(_, pmatch(index).boundVariables, scrut.sym)
       
-      // fixed length
-      val cond = getCond(treeAsSeq, xs.length)
-      return ({thenp:Tree => {elsep:Tree => 
-        If(cond, squeezedBlock(bindings, thenp), elsep)}}, succRep, failRep)
-    }
-
-    // lengthArg is exact length
-    protected def getCond(tree:Tree, lengthArg:Int) = seqHasLength(tree.duplicate, pats.head.tpe, lengthArg)
-
-    final def tree(implicit theOwner: Symbol, failTree: Tree) = {
-      val (cx,srep,frep) = this.getTransition
-      val succ = repToTree(srep)
-      val fail = repToTree(frep)
-      cx(succ)(fail)
-    }    
-  }
-
-  /** handle sequence pattern and ArrayValue with star patterns
-   */
-  final class MixSequenceStar(pats: Patterns, rest:Rep)(implicit rep:RepFactory) extends MixSequence(pats, rest) {    
-    // in principle, we could optimize more, but variable binding gets complicated (@todo use finite state methods instead)
-    override def getSubPatterns(minlen:Int, x:Tree) = x match {
-      case av @ ArrayValue(_,xs) if (!isRightIgnoring(av) && xs.length   == minlen) =>  // Seq(p1,...,pN)
-        Some(xs ::: gen.mkNil :: EmptyTree :: Nil)
-      case av @ ArrayValue(_,xs) if ( isRightIgnoring(av) && xs.length-1 == minlen) =>  // Seq(p1,...,pN,_*)
-        Some(                                   removeStar(xs) ::: EmptyTree :: Nil)
-      case av @ ArrayValue(_,xs) if ( isRightIgnoring(av) && xs.length-1  < minlen) =>  // Seq(p1..,pJ,_*)   J < N
-        Some(                                  getDummies(minlen + 1) ::: x :: Nil)
-      case EmptyTree | Ident(nme.WILDCARD)      => 
-        Some(                                  getDummies(minlen + 1          + 1))
-      case _                                    => 
-        None
-
-    }
-
-    override protected def makeSuccRep(vs:List[Symbol], tail:Symbol, nrows:List[Row])(implicit theOwner: Symbol) =
-      rep.make(scrut.mkList(vs ::: List(tail), rest.temp), nrows)
+      // add bindings for all the given vs to the given tvar
+      private def rebindAll(r: Row, vs: Iterable[Symbol], tvar: Symbol) =
+        r rebind r.subst.add(vs, tvar)
+ 
+      private def bindVars(Tag: Int, orig: Bindings): Bindings = {
+        def myBindVars(rest: List[(Int, List[Symbol])], bnd: Bindings): Bindings = rest match {
+          case Nil => bnd
+          case (Tag,vs)::xs => myBindVars(xs, bnd.add(vs, scrut.sym))
+          case (_,  vs)::xs => myBindVars(xs, bnd)
+        }
+        myBindVars(varMap, orig)
+      }
 
-    // lengthArg is minimal length
-    override protected def getCond(tree:Tree, lengthArg:Int) = seqLongerThan(tree.duplicate, pats.head.tpe, lengthArg - 1)
-  }
+      // bound vars and rows for default pattern (only one row, but a list is easier to use later)
+      lazy val (defaultVars, defaultRows) = defaultPattern match {
+        case None                 => (Nil, Nil)
+        case Some(Pattern(_, vs)) => (vs, List(rebindAll(rest rows literals.size, vs, scrut.sym)))
+      }
+      // literalMap is a map from each literal to a list of row indices.
+      // varMap is a list from each literal to a list of the defined vars.
+      lazy val (literalMap, varMap) = {
+        val tags    = literals map (_.intValue)
+        val varMap  = tags zip (literals map (_.deepBoundVariables))
+        val litMap  =
+          tags.zipWithIndex.reverse.foldLeft(IntMap.empty[List[Int]]) {
+            // we reverse before the fold so the list can be built with :: 
+            case (map, (tag, index)) => map.updated(tag, index :: map.getOrElse(tag, Nil))
+          }
+        
+        (litMap, varMap)
+      }
+      
+      lazy val cases =
+        for ((tag, indices) <- literalMap.toList) yield {
+          val newRows = indices map (i => addDefaultVars(i)(rest rows i))
+          val r   = remake(newRows ::: defaultRows, includeScrut = false)
+          val r2  = make(r.tvars, r.rows map (x => x rebind bindVars(tag, x.subst)))
 
-  
-  // @todo: equals test for same constant
-  class MixEquals(val pats: Patterns, val rest: Rep)(implicit rep: RepFactory) extends RuleApplication(rep) {
-    val Patterns(scrut, patterns) = pats
-    val head = pats.head
-    
-    /** condition (to be used in IF), success and failure Rep */
-    final def getTransition(implicit theOwner: Symbol): (Tree, Rep, Symbol, Rep) = {
-      val vlue = (head.tpe: @unchecked) match {
-        case TypeRef(_,_,List(SingleType(pre,sym))) => gen.mkAttributedRef(pre,sym)
-        case TypeRef(_,_,List(PseudoType(o)))       => o.duplicate
+          CASE(Literal(tag)) ==> r2.toTree
+        }
+      
+      lazy val defaultTree  = remake(defaultRows, includeScrut = false).toTree
+      def casesWithDefault  = cases ::: List(CASE(WILD(IntClass.tpe)) ==> defaultTree)
+      
+      // cond/success/failure only used if there is exactly one case.
+      lazy val (cond, success) = cases match {
+        case List(CaseDef(lit, _, body))  => (scrut.id MEMBER_== lit, body)
       }
-      assert(vlue.tpe ne null, "value tpe is null")
-      val vs        = head.strip1.toList
-      val nsuccFst  = rest.row.head.insert2(List(EmptyTree), vs, scrut.sym)
-      val fLabel    = theOwner.newLabel(scrut.pos, cunit.fresh.newName(scrut.pos, "failCont%")) // warning, untyped
-      val sx        = rep.shortCut(fLabel) // register shortcut
-      val nsuccRow  = nsuccFst :: Row(getDummies( 1 /* scrutinee */ + rest.temp.length), NoBinding, NoGuard, sx) :: Nil
-
-      // todo: optimize if no guard, and no further tests
-      val nsucc = rep.make(scrut.mkList(rest.temp), nsuccRow)
-      val nfail = repWithoutHead(pats, rest)
-      
-      (typer.typed(Equals(scrut.id, vlue)), nsucc, fLabel, nfail) 
+      lazy val failure = defaultTree
+      
+      // only one case becomes if/else, otherwise match
+      def tree() = 
+        if (cases.size == 1) codegen
+        else casted MATCH (casesWithDefault: _*)      
     }
 
-    final def tree(implicit theOwner: Symbol, failTree: Tree) = {
-      val (cond, srep, fLabel, frep) = this.getTransition
-      val cond2 = typer.typed( rep.handleOuter(cond) )
-      val fail = typer.typed( repToTree(frep) )
-      fLabel setInfo MethodType(Nil, fail.tpe)
-
-      typer.typed( If(cond2, repToTree(srep), LabelDef(fLabel, Nil, fail)) )
-    }
-  }
+    /** mixture rule for unapply pattern
+     */
+    class MixUnapply(val pmatch: PatternMatch, val rest: Rep, typeTest: Boolean) extends RuleApplication {
+      val uapattern = head match { case x: UnapplyPattern => x ; case _ => abort("XXX") }
+      val ua @ UnApply(app, args) = head.tree
 
-  /** mixture rule for type tests
-  **/
-  class MixTypes(val pats: Patterns, val rest: Rep)(implicit rep: RepFactory) extends RuleApplication(rep) {
-    val Patterns(scrut, patterns) = pats
-  
-    private def subpatterns(p: Tree): List[Tree] = p match {
-      case Bind(_, p)                                                 => subpatterns(p)
-      case app @ Apply(fn, ps) if app.tpe.isCaseClass && fn.isType    => if (pats.isCaseHead) ps else pats.dummies
-      case Apply(fn, xs) if !xs.isEmpty || fn.isType                  => abort("strange Apply")
-      case _                                                          => pats.dummies
-    }
+      // Note: trailingArgs is not necessarily Nil, because unapply can take implicit parameters.      
+      val Apply(fxn, _ :: trailingArgs) = app
+      private def reapply = Apply(fxn, scrut.id :: trailingArgs)
+      
+      private lazy val zipped      = pmatch pzip rest.rows
+      
+      lazy val unapplyResult: PatternVar =
+        scrut.createVar(app.tpe, lhs => reapply setType lhs.tpe)
 
-    // moreSpecific: more specific patterns
-    //     subsumed: more general patterns (subsuming current), row index and subpatterns
-    //    remaining: remaining, row index and pattern
-    def join[T](xs: List[Option[T]]): List[T] = xs.flatMap(x => x)
-    val (moreSpecific, subsumed, remaining) : (List[Tree], List[(Int, List[Tree])], List[(Int, Tree)]) = unzip3(
-      for ((pat @ Strip2(spat), j) <- pats.zip) yield {
-        def eqHead(tpe: Type) = pats.headType =:= tpe
-        def alts(yes: Tree, no: Tree) = if (eqHead(pat.tpe)) yes else no
-
-        lazy val isDef                = isDefaultPattern(pat)
-        lazy val cmp: TypeComparison  = spat.tpe.cmp(pats.headType)  // contains type info about pattern's type vs. head pattern
-        lazy val dummy                = (j, pats.dummies)
-        lazy val pass                 = (j, pat)
-        lazy val subs                 = (j, subpatterns(pat))
-        
-        import cmp._  // imports xIsaY, etc.
-        
-        // each pattern will yield a triple of options corresponding to the three lists,
-        // which will be flattened down to the values
-        implicit def mkOpt[T](x: T): Option[T] = Some(x)    // limits noise from Some(value)
-        (spat match {
-          case Const(null) if !eqHead(spat.tpe)           => (None, None, pass)           // special case for constant null
-          case _ if pats.isObjectTest(pat)                => (EmptyTree, dummy, None)     // matching an object
-          case Typed(p @ Strip2(_: UnApply), _) if xIsaY  => (p, dummy, None)             // <:< is never <equals>
-          case q @ Typed(pp, _) if xIsaY                  => (alts(pp, q), dummy, None)   // never =:= for <equals>
-          case z: UnApply                                 => (None, None, pass)            
-          case _ if erased.xIsaY || xIsaY && !isDef       => (alts(EmptyTree, pat), subs, None) // never =:= for <equals>          
-          case _ if erased.yIsaX || yIsaX || isDef        => (EmptyTree, dummy, pass)     // subsuming (matched *and* remaining pattern)
-          case _                                          => (None, None, pass)
-        }) : (Option[Tree], Option[(Int, List[Tree])], Option[(Int, Tree)])
-      }
-    ) match { case (x,y,z) => (join(x), join(y), join(z)) }    
+      // XXX in transition.
+      object sameUnapplyCall {
+        private def sameFunction(fn1: Tree) = fxn.symbol == fn1.symbol && (fxn equalsStructure fn1)
 
-    override def toString = {
-      "MixTypes("+scrut+":"+scrut.tpe+") {\n  moreSpecific:"+moreSpecific+"\n  subsumed:"+subsumed+"\n  remaining"+remaining+"\n}"
-    }
-    
-    /** returns casted symbol, success matrix and optionally fail matrix for type test on the top of this column */
-    final def getTransition(implicit theOwner: Symbol): (Scrutinee, Rep, Option[Rep]) = {
-      val casted = scrut.casted(pats.headType)
-      
-      // succeeding => transition to translate(subsumed) (taking into account more specific)
-      val nmatrix = {
-        val ms = moreSpecific.exists(_ != EmptyTree)
-        val accessorTemps = 
-          if (!pats.isCaseHead) Nil 
-          else casted.accessors.map(meth => newVar(scrut.pos, casted.tpe.memberType(meth).resultType, scrut.flags))
-        val subtestTemps = if (!ms) Nil else List(casted.sym)
-        val subtests =
-          if (!ms) subsumed
-          else moreSpecific.zip(subsumed) map { case (mspat, (j, pats)) => (j, mspat::pats) }
-        val ntriples = for ((j, ps) <- subtests) yield {
-          val (vs, thePat) = strip(pats(j))
-          rest.row(j).insert2(ps, vs, casted.sym)
+        def unapply(p: Pattern) = condOpt(p) {
+          case Pattern(UnApply(Apply(fn1, _), args), _) if sameFunction(fn1)  =>
+            tracing("sameUnapply", args)
+        }
+      }      
+      object SameUnapply {
+        def unapply(p: Pattern) = p match {
+          case x: UnapplyPattern if uapattern isSameUnapply x => Some(args)
+          case _                                              => None
         }
-        rep.make(subtestTemps ::: accessorTemps ::: rest.temp, ntriples)
       }
+      def isSameUnapply(p: Pattern) = SameUnapply.unapply(p).isDefined
       
-      // fails      => transition to translate(remaining)
-      val nmatrixFail: Option[Rep] = {
-        val ntemps   = scrut.mkList(rest.temp)
-        val ntriples = for ((j, pat) <- remaining) yield rest.row(j).insert(pat)          
-        if (ntriples.isEmpty) None else Some(rep.make(ntemps, ntriples))
-      }
+      lazy val cond: Tree =
+        if (unapplyResult.tpe.isBoolean) ID(unapplyResult.valsym)
+        else unapplyResult.valsym IS_DEFINED
+
+      lazy val failure = 
+        mkFail(zipped.tail filterNot (x => isSameUnapply(x._1)) map { case (pat, r) => r insert pat })
       
-      (casted, nmatrix, nmatrixFail)
-    }
+      private def doSuccess: (List[PatternVar], List[PatternVar], List[Row]) = {
+        // pattern variable for the unapply result of Some(x).get
+        lazy val pv = scrut.createVar(
+          app.tpe typeArgs 0,
+          _ => fn(ID(unapplyResult.lhs), nme.get)
+        )
+        def tuple = pv.lhs
 
-    final def tree(implicit theOwner: Symbol, failTree: Tree): Tree = {
-      val (casted, srep, frep) = this.getTransition
-      val cond = condition(casted.tpe, scrut)
-      val succ = repToTree(srep)
-      val fail = frep.map(repToTree) getOrElse failTree
+        // at this point it's Some[T1,T2...]
+        lazy val tpes  = getProductArgs(tuple.tpe).get
       
-      // dig out case field accessors that were buried in (***)
-      val cfa       = if (!pats.isCaseHead) Nil else casted.accessors
-      val caseTemps = srep.temp match { case x :: xs if x == casted.sym => xs ; case x => x }
+        // one pattern variable per tuple element
+        lazy val tuplePVs =
+          for ((tpe, i) <- tpes.zipWithIndex) yield
+            scrut.createVar(tpe, _ => fn(ID(tuple), productProj(tuple, i + 1)))
             
-      var vdefs = for ((tmp, accessorMethod) <- caseTemps.zip(cfa)) yield {
-        val untypedAccess = Code.fn(casted.id, accessorMethod)
-        val typedAccess = typer.typed(untypedAccess)
-        typedValDef(tmp, typedAccess)
+        // the filter prevents infinite unapply recursion
+        def mkNewRows(sameFilter: (List[Tree]) => List[Tree]) = {
+          val dum = if (args.length <= 1) args.length else tpes.size
+          for ((pat, r) <- zipped) yield pat match {
+            case sameUnapplyCall(xs)  => r.insert2(toPats(sameFilter(xs)) ::: List(NoPattern), pat.boundVariables, scrut.sym)
+            case _                    => r insert (emptyPatterns(dum) ::: List(pat))
+          }
+        }
+
+        // 0 is Boolean, 1 is Option[T], 2+ is Option[(T1,T2,...)]
+        args.length match {
+          case 0  => (Nil, Nil, mkNewRows((xs) => Nil))
+          case 1  => (List(pv), List(pv), mkNewRows(xs => List(xs.head)))
+          case _  => (pv :: tuplePVs, tuplePVs, mkNewRows(identity))
+        }
+      }
+
+      lazy val success = {
+        val (squeezePVs, pvs, rows) = doSuccess
+        val srep = remake(rows, pvs).toTree
+        
+        squeezedBlockPVs(squeezePVs, srep)
       }
       
-      if (casted.sym ne scrut.sym)
-        vdefs = ValDef(casted.sym, gen.mkAsInstanceOf(scrut.id, casted.tpe)) :: vdefs
-      
-      typer.typed( If(cond, squeezedBlock(vdefs, succ), fail) )
+      final def tree() =
+        squeezedBlock(List(handleOuter(unapplyResult.valDef)), codegen)
     }
-  }
 
-  /** converts given rep to a tree - performs recursive call to translation in the process to get sub reps
-   */
-  final def repToTree(r: Rep)(implicit theOwner: Symbol, failTree: Tree, rep: RepFactory): Tree =
-    r.applyRule.tree
+    /** Handle Sequence patterns (including Star patterns.)
+     *  Note: pivot == head, just better typed.
+     */
+    sealed class MixSequence(val pmatch: PatternMatch, val rest: Rep, pivot: SequencePattern) extends RuleApplication {
+      require(scrut.tpe <:< head.tpe)
 
-  case class Row(pat: List[Tree], subst: Bindings, guard: Guard, bx: Int) {
-    def insert(h: Tree)                               = Row(h :: pat, subst, guard, bx)
-    def insert(hs: List[Tree])                        = Row(hs ::: pat, subst, guard, bx)           // prepends supplied tree
-    def replace(hs: List[Tree])                       = Row(hs, subst, guard, bx)                   // substitutes for patterns
-    def rebind(b: Bindings)                           = Row(pat, b, guard, bx)                      // substitutes for bindings
-    def insert2(hs: List[Tree], vs: Iterable[Symbol], temp: Symbol) =                               // prepends and prepends
-      Row(hs ::: pat, subst.add(vs, temp), guard, bx)
+      def hasStar = pivot.hasStar
+      private def pivotLen    = pivot.nonStarLength
+      private def seqDummies  = emptyPatterns(pivot.elems.length + 1)
       
-    def insert(p: Pattern)                            = Row(p.tree :: pat, subst, guard, bx)        // transitioning to patterns
-    
-    /** returns true if the patterns in this row cover a type symbols "combination" and there is no guard
-     *  @param comb pairs of (column index, type symbol)
-     */
-    def covers(comb: List[(Int, Symbol)]) = {
-      lazy val results = for ((i, sym) <- comb ; val p = strip2(pat(i))) yield p match {
-        case _ if isDefaultPattern(p)   => true
-        case _: UnApply | _: ArrayValue => true
-        case _                          => p.tpe.coversSym(sym)
-      }
+      // one pattern var per sequence element up to elemCount, and one more for the rest of the sequence
+      lazy val pvs = scrut createSequenceVars pivotLen
       
-      guard.isEmpty && results.forall(_ == true)
-    }    
+      // Should the given pattern join the expanded pivot in the success matrix? If so,
+      // this partial function will be defined for the pattern, and the result of the apply
+      // is the expanded sequence of new patterns.
+      lazy val successMatrixFn = new PartialFunction[Pattern, List[Pattern]] {
+        private def seqIsDefinedAt(x: SequenceLikePattern) = (hasStar, x.hasStar) match {
+          case (true, true)   => true
+          case (true, false)  => pivotLen <= x.nonStarLength
+          case (false, true)  => pivotLen >= x.nonStarLength
+          case (false, false) => pivotLen == x.nonStarLength
+        }
 
-    // returns this row with alternatives expanded
-    def expand(classifyPat: (Tree, Int) => Tree): List[Row] = {
-      def isAlternative(p: Tree): Boolean = p match { 
-        case Bind(_,p)       => isAlternative(p)
-        case Alternative(ps) => true 
-        case _               => false
-      }
-      def getAlternativeBranches(p: Tree): List[Tree] = {
-        def get_BIND(pctx:Tree => Tree, p:Tree): List[Tree] = p match { 
-          case b @ Bind(n,p)   => get_BIND((x: Tree) => pctx(copy.Bind(b, n, x) setType x.tpe), p)
-          case Alternative(ps) => ps map pctx
+        def isDefinedAt(pat: Pattern) = pat match {
+          case x: SequenceLikePattern => seqIsDefinedAt(x)
+          case WildcardPattern()      => true
+          case _                      => false
+        }
+                
+        def apply(pat: Pattern): List[Pattern] = pat match {
+          case x: SequenceLikePattern =>
+            def isSameLength  = pivotLen == x.nonStarLength
+            def rebound       = x.nonStarPatterns :+ (x.elemPatterns.last rebindTo WILD(scrut.seqType))
+          
+            (pivot.hasStar, x.hasStar, isSameLength) match {
+              case (true, true, true)   => rebound :+ NoPattern
+              case (true, true, false)  => (seqDummies drop 1) :+ x
+              case (true, false, true)  => x.elemPatterns ++ List(NilPattern, NoPattern)
+              case (false, true, true)  => rebound
+              case (false, false, true) => x.elemPatterns :+ NoPattern
+              case _                    => seqDummies
+            }
+
+          case _  => seqDummies
         }
-        get_BIND(x => x, p)
       }
+
+      // Should the given pattern be in the fail matrix? This is true of any sequences
+      // as long as the result of the length test on the pivot doesn't make it impossible:
+      // for instance if neither sequence is right ignoring and they are of different
+      // lengths, the later one cannot match since its length must be wrong.
+      def failureMatrixFn(c: Pattern) = (pivot ne c) && (c match {
+        case x: SequenceLikePattern =>
+          (hasStar, x.hasStar) match {
+            case (_, true)      => true
+            case (true, false)  => pivotLen > x.nonStarLength
+            case (false, false) => pivotLen != x.nonStarLength
+          }
+        case WildcardPattern()      => true
+        case _                      => false
+      })
       
-      val indexOfAlternative            = pat findIndexOf isAlternative      
-      val pats: List[Tree]              = List.map2(pat, pat.indices)(classifyPat)
-      lazy val (prefix, alts :: suffix) = pats.splitAt(indexOfAlternative)
-      lazy val alternativeBranches      = getAlternativeBranches(alts) map { p => replace(prefix ::: p :: suffix) }
+      // divide the remaining rows into success/failure branches, expanding subsequences of patterns
+      val successRows = pmatch pzip rest.rows collect {
+        case (c, row) if successMatrixFn isDefinedAt c => row insert successMatrixFn(c)
+      }
+      val failRows = pmatch pzip rest.rows collect {
+        case (c, row) if failureMatrixFn(c) => row insert c
+      }
 
-      if (indexOfAlternative == -1) List(replace(pats)) else alternativeBranches
-    }
-  }
-  case class Columns(cols: Column*)
-  case class Column(pat: Tree, index: Int)
-
-  class RepFactory(val handleOuter: Tree => Tree)(implicit val typer : Typer) {
-    var vss: List[List[Symbol]] = _
-    var labels: Array[Symbol] = new Array[Symbol](4)
-    var targets: List[Tree] = _
-    var reached: BitSet = _ 
-    var shortCuts: List[Symbol] = Nil
-
-    final def make(temp:List[Symbol], row:List[Row], targets: List[Tree], vss:List[List[Symbol]])(implicit theOwner: Symbol): Rep = {
-      // ensured that labels(i) eq null for all i, cleanup() has to be called after translation
-      this.targets      = targets
-      if (targets.length > labels.length) 
-        this.labels     = new Array[Symbol](targets.length)
-      this.vss          = vss
-      this.reached      = new BitSet(targets.length)
-      make(temp, row)
+      // the discrimination test for sequences is a call to lengthCompare.  Note that
+      // this logic must be fully consistent wiith successMatrixFn and failureMatrixFn above:
+      // any inconsistency will (and frequently has) manifested as pattern matcher crashes.
+      lazy val cond = {
+        // the method call symbol
+        val methodOp: Symbol                = head.tpe member nme.lengthCompare
+        
+        // the comparison to perform.  If the pivot is right ignoring, then a scrutinee sequence
+        // of >= pivot length could match it; otherwise it must be exactly equal.
+        val compareOp: (Tree, Tree) => Tree = if (hasStar) _ INT_>= _ else _ INT_== _
+        
+        // scrutinee.lengthCompare(pivotLength) [== | >=] 0
+        val compareFn: Tree => Tree         = (t: Tree) => compareOp((t DOT methodOp)(LIT(pivotLen)), ZERO)
+        
+        // wrapping in a null check on the scrutinee
+        nullSafe(compareFn, FALSE)(scrut.id)
+      }
+      lazy val success  = squeezedBlockPVs(pvs, remake(successRows, pvs, hasStar).toTree)
+      lazy val failure  = remake(failRows).toTree
+            
+      final def tree(): Tree = codegen
     }
 
-    final def shortCut(theLabel:Symbol): Int = {
-      shortCuts = shortCuts ::: List(theLabel)
-      -shortCuts.length
-    }
+    // @todo: equals test for same constant
+    class MixEquals(val pmatch: PatternMatch, val rest: Rep) extends RuleApplication {        
+      private lazy val labelBody =
+        remake((rest.rows.tail, pmatch.tail).zipped map (_ insert _)).toTree
+        
+      private lazy val rhs =
+        decodedEqualsType(head.tpe) match {
+          case SingleType(pre, sym) => REF(pre, sym)
+          case PseudoType(o)        => o.duplicate
+        }      
+
+      lazy val label =
+        owner.newLabel(scrut.pos, newName(scrut.pos, "failCont%")) setInfo MethodType(Nil, labelBody.tpe)
+      
+      lazy val cond =
+        handleOuter(scrut.id MEMBER_== rhs)
 
-    final def cleanup(tree: Tree)(implicit theOwner: Symbol): Tree = { 
-      object lxtt extends Transformer {
-        override def transform(tree:Tree): Tree = tree match {
-          case blck @ Block(vdefs, ld @ LabelDef(name,params,body)) =>
-            val bx = labelIndex(ld.symbol)
-            if (bx >= 0 && !isReachedTwice(bx)) squeezedBlock(vdefs,body)
-            else blck
-
-          case If(cond, Const(true), Const(false)) => 
-            super.transform(cond)
-          case If(cond1, If(cond2, thenp, elsep1), elsep2) if (elsep1 equalsStructure elsep2) => 
-            super.transform(If(And(cond1,cond2), thenp, elsep1))
-          case If(cond1, If(cond2, thenp, Apply(jmp,List())), ld:LabelDef) if (jmp.symbol eq ld.symbol) => 
-            super.transform(If(And(cond1,cond2), thenp, ld))
-
-          case t => super.transform(t)
-        }
-      }
-      val res = lxtt.transform(tree)
-      cleanup()
-      res
-    }
-    
-    final def cleanup() {
-      for (i <- 0 until targets.length) labels(i) = null
-      reached = null
-      shortCuts = Nil
+      lazy val success = remake(List(
+        rest.rows.head.insert2(List(NoPattern), head.boundVariables, scrut.sym),
+        Row(emptyPatterns(1 + rest.tvars.size), NoBinding, NoGuard, shortCut(label))
+      )).toTree
+ 
+      lazy val failure = LabelDef(label, Nil, labelBody)
+
+      final def tree() = codegen
+      override def toString() = "MixEquals(%s == %s)".format(scrut, head)
     }
-    final def isReached(bx:Int)   = labels(bx) ne null
-    final def markReachedTwice(bx:Int) { reached += bx }
-    /** @pre bx < 0 || labelIndex(bx) != -1 */
-    final def isReachedTwice(bx: Int) = (bx < 0) || reached(bx)
-    /* @returns bx such that labels(bx) eq label, -1 if no such bx exists */
-    final def labelIndex(label: Symbol): Int = labels.findIndexOf(_ eq label)
 
-    /** first time bx is requested, a LabelDef is returned. next time, a jump.
-     *  the function takes care of binding
+    /** Mixture rule for type tests.
+     *  moreSpecific: more specific patterns
+     *      subsumed: more general patterns (subsuming current), rows index and subpatterns
+     *     remaining: remaining, rows index and pattern
      */
-    final def requestBody(bx: Int, subst: Bindings)(implicit theOwner: Symbol): Tree = {
-      if (bx < 0) { // is shortcut
-        val jlabel = shortCuts(-bx-1)
-        return Apply(mkIdent(jlabel), Nil)
-      }
-      if (!isReached(bx)) { // first time this bx is requested
-        // might be bound elsewhere ( see `x @ unapply' ) <-- this comment refers to null check
-        val (vsyms, argts, vdefs) : (List[Symbol], List[Type], List[Tree]) = unzip3(
-          for (v <- vss(bx) ; substv <- subst(v)) yield 
-            (v, v.tpe, typedValDef(v, substv))
-        )
-              
-        val body  = targets(bx)
-        // @bug: typer is not able to digest a body of type Nothing being assigned result type Unit
-        val tpe = if (body.tpe.isNothing) body.tpe else resultType
-        val label = theOwner.newLabel(body.pos, "body%"+bx) setInfo MethodType(argts, tpe)
-        // TODO - newLabel doesn't get a fresh name, is that okay? or should it be more like this:
-        // val label = theOwner.newLabel(body.pos, cunit.fresh.newName(body.pos, "body%"+bx)) setInfo MethodType(argts, tpe)
-        labels(bx) = label
-
-        return body match {
-          case _: Throw | _: Literal  => squeezedBlock(vdefs, body.duplicate setType tpe)
-          case _                      => squeezedBlock(vdefs.reverse, LabelDef(label, vsyms, body setType tpe))
+    class MixTypes(val pmatch: PatternMatch, val rest: Rep) extends RuleApplication {
+      case class Yes(bx: Int, moreSpecific: Pattern, subsumed: List[Pattern])
+      case class No(bx: Int, remaining: Pattern)
+      
+      val (yeses, noes) = {
+        val _ys = new ListBuffer[Yes]
+        val _ns = new ListBuffer[No]
+        
+        for ((pattern, j) <- pmatch.pzip()) {
+          // scrutinee, head of pattern group
+          val (s, p) = (pattern.tpe, head.necessaryType)
+          
+          def isEquivalent  = head.necessaryType =:= pattern.tpe
+          def isObjectTest  = pattern.isObject && (p =:= pattern.necessaryType)          
+          
+          def sMatchesP = matches(s, p)
+          def pMatchesS = matches(p, s)
+
+          def ifEquiv(yes: Pattern): Pattern = if (isEquivalent) yes else pattern
+          
+          def passl(p: Pattern = NoPattern, ps: List[Pattern] = pmatch.dummies) = Some(Yes(j, p, ps))
+          def passr()                                                           = Some( No(j, pattern))
+          
+          def typed(pp: Tree) = passl(ifEquiv(Pattern(pp)))
+          def subs()          = passl(ifEquiv(NoPattern), pattern subpatterns pmatch)
+          
+          val (oneY, oneN) = pattern match {
+            case Pattern(LIT(null), _) if !(p =:= s)        => (None, passr)      // (1)
+            case x if isObjectTest                          => (passl(), None)    // (2)
+            case Pattern(Typed(pp, _), _)     if sMatchesP  => (typed(pp), None)  // (4)
+            // The next line used to be this which "fixed" 1697 but introduced
+            // numerous regressions including #3136.
+            // case Pattern(_: UnApply, _)                     => (passl(), passr)
+            case Pattern(_: UnApply, _)                     => (None, passr)
+            case x if !x.isDefault && sMatchesP             => (subs(), None)
+            case x if  x.isDefault || pMatchesS             => (passl(), passr)
+            case _                                          => (None, passr)              
+          }
+          oneY map (_ys +=)
+          oneN map (_ns +=)
         }
+        (_ys.toList, _ns.toList)
       }
- 
-      // if some bx is not reached twice, its LabelDef is replaced with body itself
-      markReachedTwice(bx) 
-      val args: List[Ident] = vss(bx).flatMap(subst(_))
-      val label = labels(bx)
-      val body = targets(bx)
-      val MethodType(fmls, _) = label.tpe
-
-      // sanity checks
-      if (fmls.length != args.length) {
-        cunit.error(body.pos, "consistency problem in target generation ! I have args "+
-          args+" and need to jump to a label with fmls "+fmls)
-        throw FatalError("consistency problem")
+      
+      val moreSpecific = yeses map (_.moreSpecific)
+      val subsumed = yeses map (x => (x.bx, x.subsumed))
+      val remaining = noes map (x => (x.bx, x.remaining))
+      
+      // temporary checks so we're less crashy while we determine what to implement.
+      def checkErroneous(scrut: Scrutinee): Type = {
+        scrut.tpe match {
+          case tpe @ ThisType(_) if tpe.termSymbol == NoSymbol        =>
+            cunit.error(scrut.pos, "self type test in anonymous class forbidden by implementation.")
+            ErrorType
+          case x => x
+        }
       }
-      fmls.zip(args).find(x => !(x._2.tpe <:< x._1)) match {
-        case Some(Tuple2(f, a)) => cunit.error(body.pos, "consistency problem ! "+a.tpe+" "+f) ; throw FatalError("consistency problem")
-        case None =>
+      
+      private def mkZipped =
+        for (Yes(j, moreSpecific, subsumed) <- yeses) yield
+          j -> (moreSpecific :: subsumed)
+      
+      lazy val casted = scrut castedTo pmatch.headType
+      lazy val cond   = condition(checkErroneous(casted), scrut, head.boundVariables.nonEmpty)
+      
+      private def isAnyMoreSpecific = yeses exists (x => !x.moreSpecific.isEmpty)
+      lazy val (subtests, subtestVars) =
+        if (isAnyMoreSpecific)  (mkZipped, List(casted.pv))
+        else                    (subsumed, Nil)
+      
+      lazy val newRows =
+        for ((j, ps) <- subtests) yield 
+          (rest rows j).insert2(ps, pmatch(j).boundVariables, casted.sym)
+      
+      lazy val success = {
+        val srep = remake(newRows, subtestVars ::: casted.accessorPatternVars, includeScrut = false)
+        squeezedBlock(casted.allValDefs, srep.toTree)
       }
+      
+      lazy val failure =
+        mkFail(remaining map { case (p1, p2) => rest rows p1 insert p2 })
 
-      body match {
-        case _: Throw | _: Literal =>       // might be bound elsewhere (see `x @ unapply')
-          val vdefs = for (v <- vss(bx) ; substv <- subst(v)) yield typedValDef(v, substv)
-          squeezedBlock(vdefs, body.duplicate setType resultType)
-        case _ =>
-          Apply(mkIdent(label),args)
-      }
+      final def tree(): Tree = codegen
     }
 
-    /** the injection here handles alternatives and unapply type tests */
-    final def make(temp: List[Symbol], row1: List[Row])(implicit theOwner: Symbol): Rep = {
-      // equals check: call singleType(NoPrefix, o.symbol) `stpe'. Then we could also return 
-      // `typeRef(definitions.ScalaPackageClass.tpe, definitions.EqualsPatternClass, List(stpe))'
-      // and force an equality check. However, exhaustivity checking would not work anymore.
-      // so first, extend exhaustivity check to equalspattern
-      def sType(o: Tree) = singleType(o.tpe.prefix, o.symbol)
-      def equalsCheck(o: Tree) = if (o.symbol.isValue) singleType(NoPrefix, o.symbol) else sType(o)
-      def isModule(o: Tree) = o.symbol.isModule || o.tpe.termSymbol.isModule
-      def applyType(o: Tree, fn: Tree): Type = fn match { 
-        case _ if isModule(o)     => sType(o)
-        case Select(path, sym)    => (path, path.tpe) match {
-          case (_, t: ThisType)     => singleType(t, o.symbol)            // cases 2/3 are e.g. `case Some(p._2)' in s.c.jcl.Map
-          case (_: Apply, _)        => PseudoType(o)                      // outer-matching: test/files/pos/t154.scala
-          case (_, _)               => singleType(sType(path), o.symbol)  // old
-        }
-        case o: Ident             => equalsCheck(o)
+    /*** States, Rows, Etc. ***/
+
+    case class Row(pats: List[Pattern], subst: Bindings, guard: Guard, bx: Int) {
+      private def nobindings = subst.get().isEmpty
+      private def bindstr = if (nobindings) "" else pp(subst)
+      if (pats exists (p => !p.isDefault))
+        traceCategory("Row", "%s%s", pats, bindstr)
+      
+      /** Extracts the 'i'th pattern. */
+      def extractColumn(i: Int) = {
+        val (x, xs) = extractIndex(pats, i)
+        (x, copy(pats = xs))
       }
-    
-      def classifyPat(opat: Tree, j: Int): Tree = {
-        val (vs, strippedPat) = strip(opat) match { case (vset, pat) => (vset.toList, pat) }
-        // @todo: rewrite UnApply(Apply(fn, _), _) case, using __UnApply instead of UnApply like so:
-        // case  ua @ __UnApply(_,argtpe,_) =>
-        //   val ua = prepat
-        //   val npat = (if (temp(j).tpe <:< argtpe) ua else Typed(ua,TypeTree(argtpe)).setType(argtpe))
-        //   pats = (makeBind(vs, npat) setType argtpe)::pats
-                
-        strippedPat match {
-          case _: Alternative                       => opat
-          case Typed(p @ Strip2(_: UnApply), tpt)   => if (temp(j).tpe <:< tpt.tpe) makeBind(vs, p)
-                                                       else opat
-          // case Ident_Or_Empty()                     => opat    // this doesn't work - see notes in PatternNode
-          case Ident(nme.WILDCARD) | EmptyTree      => opat
-          case _: Literal | _: Typed                => opat
-          case o: Ident                             => mkTypedBind(vs, equalsCheck(o))  // Ident(_) != nme.WILDCARD
-          case o: Select                            => mkTypedBind(vs, equalsCheck(o))
-          // @pre for UnApply_TypeApply: is not right-ignoring (no star pattern) ; no exhaustivity check
-          case UnApply_TypeApply(tptArg, xs)        => temp(j) setFlag Flags.TRANS_FLAG
-                                                       makeBind(vs, normalizedListPattern(xs, tptArg.tpe))
-          case ua @ UnApply(Apply(fn, _), _)        => val MethodType(List(argtpe, _*), _) = fn.tpe
-                                                       val npat = if (temp(j).tpe <:< argtpe) ua 
-                                                                  else Typed(ua, TypeTree(argtpe)) setType argtpe
-                                                       makeBind(vs, npat) setType argtpe
-          case o @ Apply_Function(fn)               => val stpe = applyType(o, fn)
-                                                       val ttst = mkEqualsRef(List(stpe))
-                                                       makeBind(vs, Typed(mk_(ttst), TypeTree(stpe)) setType ttst)
-          case Apply_Value(pre, sym)                => mkEmptyTreeBind(vs, mkEqualsRef(List(singleType(pre, sym))))            
-          case Apply_CaseClass_NoArgs(tpe)          => mkEmptyTreeBind(vs, tpe)
-          case Apply_CaseClass_WithArgs()           => opat
-          case _: ArrayValue                        => opat
-          case x                                    => throw new Exception("Unexpected pattern: " + x.getClass + " => " + x)
-        }
+      
+      /** Replaces the 'i'th pattern with the argument. */
+      def replaceAt(i: Int, p: Pattern) = {
+        val newps = (pats take i) ::: p :: (pats drop (i + 1))
+        copy(pats = newps)
       }
-            
-      val row = row1 flatMap { _.expand(classifyPat) }
-      if (row.length != row1.length) make(temp, row)  // recursive call if any change
-      else Rep(temp, row).init
-    }
-  }
+      
+      def insert(h: Pattern)              = copy(pats = h :: pats)
+      def insert(hs: List[Pattern])       = copy(pats = hs ::: pats)  // prepends supplied pattern
+      def rebind(b: Bindings)             = copy(subst = b)           // substitutes for bindings
+        
+      def insert2(hs: List[Pattern], vs: Iterable[Symbol], tvar: Symbol) =
+        tracing("insert2", copy(pats = hs ::: pats, subst = subst.add(vs, tvar)))
 
-  case class Rep(val temp: List[Symbol], val row: List[Row]) {
-    private def setsToCombine: List[(Int, immutable.Set[Symbol])] = for {
-      (sym, i) <- temp.zipWithIndex
-      if sym hasFlag Flags.MUTABLE          // indicates that have not yet checked exhaustivity
-      if !(sym hasFlag Flags.TRANS_FLAG)    // indicates @unchecked
-      if sym.tpe.typeSymbol hasFlag Flags.SEALED
-    } yield {
-      sym resetFlag Flags.MUTABLE
-      // this should enumerate all cases... however, also the superclass is taken if it is not abstract
-      def candidates(tpesym: Symbol): immutable.Set[Symbol] = {
-        def countCandidates(x: Symbol) = if (x hasFlag Flags.ABSTRACT) candidates(x) else candidates(x) + x          
-        if (tpesym hasFlag Flags.SEALED) tpesym.children.flatMap(countCandidates)
-        else emptySymbolSet
+      // returns this rows with alternatives expanded
+      def expandAlternatives(classifyPat: (Pattern, Int) => Pattern): List[Row] = {
+        def isNotAlternative(p: Pattern) = !cond(p.tree) { case _: Alternative => true }
+        
+        // classify all the top level patterns - alternatives come back unaltered
+        val newPats: List[Pattern] = pats.zipWithIndex map classifyPat.tupled
+        // see if any alternatives were in there
+        val (ps, others) = newPats span isNotAlternative
+        // make a new row for each alternative, with it spliced into the original position
+        if (others.isEmpty) List(copy(pats = ps))
+        else extractBindings(others.head) map (x => replaceAt(ps.size, x))
+      }
+      override def toString() = {
+        val bs = if (nobindings) "" else "\n" + bindstr
+        "Row(%d)(%s%s)".format(bx, pp(pats), bs)
       }
-      (i, candidates(sym.tpe.typeSymbol))
     }
-     
-    // computes cartesian product, keeps indices available
-    private def combine(colcom: List[(Int, Set[Symbol])]): List[List[(Int, Symbol)]] = colcom match {
-      case Nil => Nil
-      case (i,syms)::Nil => syms.toList.map { sym => List((i,sym)) }
-      case (i,syms)::cs  => for (s <- syms.toList; rest <- combine(cs)) yield (i,s) :: rest
+    
+    object ExpandedMatrix {
+      def unapply(x: ExpandedMatrix) = Some((x.rows, x.targets))
+      def apply(rowz: List[(Row, FinalState)]) =
+        new ExpandedMatrix(rowz map (_._1), rowz map (_._2))
     }
-                
-    private def comboCovers(combo: List[(Int, Symbol)]) = row exists { r => r.covers(combo) }
-
-    def init: this.type = {
-      val allcomb = combine(setsToCombine)
-      if (allcomb forall comboCovers) return this
+    
+    class ExpandedMatrix(val rows: List[Row], val targets: List[FinalState]) {
+      require(rows.size == targets.size)
       
-      // if we reach here, patterns were not exhaustive
-      def mkPad(xs: List[(Int, Symbol)], i: Int): String = xs match {
-        case Nil                  => pad("*")
-        case (j, sym) :: rest     => if (j == i) pad(sym.name.toString) else mkPad(rest, i)
+      override def toString() = {        
+        def vprint(vs: List[Any]) = if (vs.isEmpty) "" else ": %s".format(pp(vs))
+        def rprint(r: Row) = pp(r)
+        def tprint(t: FinalState) = 
+          if (t.freeVars.isEmpty) " ==> %s".format(pp(t.body))
+          else " ==>\n        %s".format(pp(t.freeVars -> t.body))
+          
+        val xs = rows zip targets map { case (r,t) => rprint(r) + tprint(t) }
+        val ppstr = pp(xs, newlines = true)
+                    
+        "ExpandedMatrix(%d rows)".format(rows.size) + ppstr
       }
-      def mkMissingStr(open: List[(Int, Symbol)]) =
-        "missing combination " + temp.indices.map(mkPad(open, _)).mkString + "\n"
+    }
+    
+    abstract class State {
+      def body: Tree
+      def freeVars: List[Symbol]
+      def isFinal: Boolean
+    }
         
-      val missingCombos = allcomb
-        . filter(open => row.forall(!_.covers(open)))
-        . map(mkMissingStr)
-        . mkString
+    case class FinalState(bx: Int, body: Tree, freeVars: List[Symbol]) extends State {
+      private var referenceCount = 0      
+      private var _label: LabelDef = null
+      private var _labelSym: Symbol = null
+      
+      def labelSym = _labelSym
+      def label = _label
+      
+      // @bug: typer is not able to digest a body of type Nothing being assigned result type Unit
+      def bodyTpe = if (body.tpe.isNothing) body.tpe else matchResultType
+      def duplicate = body.duplicate setType bodyTpe
+      
+      def isFinal = true
+      def isLabellable = !cond(body)  { case _: Throw | _: Literal => true }
+      def isNotReached = referenceCount == 0
+      def isReachedOnce = referenceCount == 1
+      def isReachedTwice = referenceCount > 1
+      
+      // arguments to pass to this body%xx
+      def labelParamTypes = label.tpe.paramTypes
+      
+      private def consistencyFailure(idents: List[Tree], vdefs: List[Tree]) = {
+        val LabelDef(name, params, rhs) = label
         
-      cunit.warning(temp.head.pos, "match is not exhaustive!\n" + missingCombos)
-      this
-    }
+        val msg = "Consistency failure in generated block %s(%s):\n  idents = %s\n  vdefs = %s\n"
+        abort(msg.format(name, pp(labelParamTypes), pp(idents), pp(vdefs)))
+      }
+      
+      def createLabelBody(index: Int, pvgroup: PatternVarGroup) = {
+        val args = pvgroup.syms
+        val vdefs = pvgroup.valDefs
         
-    /*   internal representation is (temp:List[Symbol], row:List[Row])
-     *   
-     *         tmp1       tmp_m
-     */
-    final def applyRule(implicit theOwner: Symbol, rep: RepFactory): RuleApplication = row match {
-      case Nil                              => ErrorRule()
-      case Row(pats, subst, g, bx) :: xs    => 
-        var bnd = subst
-        for (((rpat, t), px) <- pats.zip(temp).zipWithIndex) {
-          val (vs, p) = strip(rpat)
-          if (isDefaultPattern(p)) bnd = bnd.add(vs, t)
-          else {
-            // Row( _  ... _ p_1i  ...  p_1n   g_m  b_m ) :: rows
-            // cut out column px that contains the non-default pattern
-            val column    = rpat :: row.tail.map(_.pat(px))
-            val restTemp  = temp.dropIndex(px)
-            val restRows  = row.map(r => r.replace(r.pat.dropIndex(px)))
-            val mr        = MixtureRule(new Scrutinee(t), column, rep.make(restTemp, restRows))
-            DBG("\n---\nmixture rule is = " + mr.getClass)
-            return mr
-          }
+        val name = "body%" + index
+        require(_labelSym == null)
+        referenceCount += 1
+
+        if (isLabellable) {
+          val mtype = MethodType(freeVars, bodyTpe)
+          _labelSym = owner.newLabel(body.pos, name) setInfo mtype
+          
+          TRACE("Creating index %d: mtype = %s".format(bx, mtype))
+          _label = typer typedLabelDef LabelDef(_labelSym, freeVars, body setType bodyTpe)
+          TRACE("[New label] def %s%s: %s = %s".format(name, pp(freeVars), bodyTpe, body))
         }
-        // Row(   _   ...   _     g_1  b_1 ) :: rows     it's all default patterns
-        val rest = if (g.isEmpty) null else rep.make(temp, xs)    // TODO - why null?
-        DBG("\n---\nmixture rule is = VariableRule")
-        VariableRule (bnd, g, rest, bx)
+        
+        ifLabellable(vdefs, squeezedBlock(vdefs, label))
+      }
+      
+      def getLabelBody(pvgroup: PatternVarGroup): Tree = {
+        val idents = pvgroup map (_.rhs)
+        val vdefs = pvgroup.valDefs
+        referenceCount += 1
+        // if (idents.size != labelParamTypes.size)
+        //   consistencyFailure(idents, vdefs)
+
+        ifLabellable(vdefs, ID(labelSym) APPLY (idents))
+      }
+      
+      private def ifLabellable(vdefs: List[Tree], t: => Tree) =
+        if (isLabellable) t
+        else squeezedBlock(vdefs, duplicate)
+      
+      override def toString() = pp("Final%d%s".format(bx, pp(freeVars)) -> body)
     }
 
-    // a fancy toString method for debugging
-    override final def toString = {
-      val tempStr = temp.map(t => pad(t.name)).mkString + "\n"
-      val rowStr = row.map(r => (r.pat ::: List(r.subst, r.guard, r.bx)).map(pad).mkString + "\n").mkString      
-      tempStr + rowStr
-    }
-     
-    private val NPAD = 15
-    private def pad(s: Any): String = pad(s.toString)
-    private def pad(s: String): String = List.make(NPAD - s.length - 1, " ").mkString + s
-  } 
-  
-  /** creates initial clause matrix
-   */
-  final def initRep(roots: List[Symbol], cases: List[Tree], rep: RepFactory)(implicit theOwner: Symbol) = {
-    // communicate whether exhaustiveness-checking is enabled via some flag
-    val (rows, targets, vss): (List[Option[Row]], List[Tree], List[List[Symbol]]) = unzip3(
-      for ((CaseDef(pat, g, b), bx) <- cases.zipWithIndex) yield {  // stash away pvars and bodies for later
-        def rowForPat: Option[Row] = pat match {
-          case _ if roots.length <= 1 => Some(Row(List(pat), NoBinding, Guard(g), bx))
-          case Apply(fn, pargs)       => Some(Row(pargs, NoBinding, Guard(g), bx))
-          case Ident(nme.WILDCARD)    => Some(Row(getDummies(roots.length), NoBinding, Guard(g), bx))
-          case _                      => None
-        }
-        (rowForPat, b, definedVars(pat))
+    case class Rep(val tvars: PatternVarGroup, val rows: List[Row]) {      
+      lazy val Row(pats, subst, guard, index) = rows.head
+      lazy val guardedRest        = if (guard.isEmpty) NoRep else make(tvars, rows.tail)
+      lazy val (defaults, others) = pats span (_.isDefault)
+      
+      /** Sealed classes. */
+      def checkExhaustive = new ExhaustivenessChecker(this).check
+      
+      /** Cut out the column containing the non-default pattern. */
+      class Cut(index: Int) {
+        /** The first two separate out the 'i'th pattern in each row from the remainder. */        
+        private val (_column, _rows) = rows map (_ extractColumn index) unzip
+        
+        /** Now the 'i'th tvar is separated out and used as a new Scrutinee. */
+        private val (_pv, _tvars) = tvars extractIndex index
+        
+        /** The non-default pattern (others.head) replaces the column head. */
+        private val (_ncol, _nrep) =
+          (others.head :: _column.tail, make(_tvars, _rows))
+        
+        def mix = MixtureRule(new Scrutinee(specialVar(_pv.sym, _pv.checked)), _ncol, _nrep)
       }
-    )
+      
+      /** Converts this to a tree - recursively acquires subreps. */
+      final def toTree(): Tree = tracing("toTree", typer typed applyRule())
+      
+      /** The VariableRule. */
+      private def variable() = {                
+        val binding = (defaults map (_.boundVariables) zip tvars.pvs) .
+          foldLeft(subst)((b, pair) => b.add(pair._1, pair._2.lhs))
+        
+        VariableRule(binding, guard, guardedRest, index)
+      }
+      
+      /** The MixtureRule. */
+      def mixture() = new Cut(defaults.size) mix
+      
+      /** Applying the rule will result in one of:
+        *
+        *   VariableRule - if all patterns are default patterns
+        *    MixtureRule - if one or more patterns are not default patterns
+        *          Error - no rows remaining
+        */
+      final def applyRule(): Tree =
+        if (rows.isEmpty) failTree
+        else if (others.isEmpty) variable.tree()
+        else mixture.tree()
+      
+      def ppn(x: Any) = pp(x, newlines = true)
+      override def toString() =
+        if (tvars.size == 0) "Rep(%d) = %s".format(rows.size, ppn(rows))
+        else "Rep(%dx%d)%s%s".format(tvars.size, rows.size, ppn(tvars), ppn(rows))
+    }
     
-    // flatMap the list of options yields the list of values
-    rep.make(roots, rows.flatMap(x => x), targets, vss)
-  }
+    val NoRep = Rep(Nil, Nil)
+    /** Expands the patterns recursively. */
+    final def expand(roots: List[PatternVar], cases: List[CaseDef]) =
+      tracing("Expanded", ExpandedMatrix(
+        for ((CaseDef(pat, guard, body), index) <- cases.zipWithIndex) yield {
+          def mkRow(ps: List[Tree]) = Row(toPats(ps), NoBinding, Guard(guard), index)
+          
+          val pattern = Pattern(pat)
+          val row = mkRow(pat match {
+            case x if roots.length <= 1 => List(x)
+            case Apply(_, args)         => args
+            case WILD()                 => emptyTrees(roots.length)
+          })
+          
+          row -> FinalState(index, body, pattern.deepBoundVariables)
+        })
+      )
 
-  final def newVar(pos: Position, name: Name, tpe: Type, flags: List[Long])(implicit theOwner: Symbol): Symbol = {
-    assert(tpe ne null, "newVar("+name+", null)")
-    val sym = theOwner.newVariable(pos, name) // careful: pos has special meaning
-    sym setInfo tpe
-    sym setFlag flags.foldLeft(Flags.SYNTHETIC.toLong)(_|_)
-  }
-  
-  final def newVar(pos: Position, tpe: Type, flags: List[Long])(implicit theOwner: Symbol): Symbol =
-    newVar(pos, cunit.fresh.newName(pos, "temp"), tpe, flags)
-  
-  final def newVar(pos: Position, tpe: Type)(implicit theOwner: Symbol): Symbol =
-    newVar(pos, tpe, Nil)
-  
-  /** returns the condition in "if (cond) k1 else k2" 
-   */
-  final def condition(tpe: Type, scrut: Scrutinee)(implicit typer: Typer, theOwner: Symbol, rep: RepFactory): Tree = {
-    assert(scrut.isDefined)
-    val cond = rep.handleOuter(typer.typed(condition(tpe, scrut.id)))
+    /** returns the condition in "if (cond) k1 else k2" 
+     */
+    final def condition(tpe: Type, scrut: Scrutinee, isBound: Boolean): Tree = {
+      assert(scrut.isDefined)
+      val cond = handleOuter(condition(tpe, scrut.id, isBound))
     
-    if (!needsOuterTest(tpe, scrut.tpe, theOwner)) cond
-    else addOuterCondition(cond, tpe, scrut.id, rep.handleOuter)
-  }
+      if (!needsOuterTest(tpe, scrut.tpe, owner)) cond
+      else addOuterCondition(cond, tpe, scrut.id)
+    }
 
-  final def condition(tpe: Type, scrutTree: Tree)(implicit typer : Typer): Tree = {
-    assert((tpe ne NoType) && (scrutTree.tpe ne NoType))
-    lazy val equalsRef      = Equals(gen.mkAttributedRef(tpe.termSymbol), scrutTree)
-    lazy val isInst         = gen.mkIsInstanceOf(scrutTree, tpe)
-
-    tpe match {
-      case _: SingletonType if !tpe.isInstanceOf[ConstantType] =>
-        if (tpe.termSymbol.isModule)                            equalsRef               // object
-        else if (tpe.prefix ne NoPrefix)                        typer.typed(isInst)
-        else                                                    typer.typed(equalsRef)
-      case ct: ConstantType => ct.value match {                                         // constant
-          case v @ Constant(null) if scrutTree.tpe.isAnyRef     => Eq(scrutTree, Literal(v))
-          case v                                                => Equals(scrutTree, Literal(v))
-        }
-      case _ if scrutTree.tpe <:< tpe && tpe.isAnyRef           => NotNull(scrutTree)
-      case _                                                    => gen.mkIsInstanceOf(scrutTree, tpe)
+    final def condition(tpe: Type, scrutTree: Tree, isBound: Boolean): Tree = {
+      assert((tpe ne NoType) && (scrutTree.tpe ne NoType))    
+      def useEqTest     = tpe.termSymbol.isModule || (tpe.prefix eq NoPrefix)
+
+      //         case SingleType(_, _) | ThisType(_) | SuperType(_, _) =>
+      //           val cmpOp = if (targ.tpe <:< AnyValClass.tpe) Any_equals else Object_eq
+      // Apply(Select(qual, cmpOp), List(gen.mkAttributedQualifier(targ.tpe)))
+      
+      typer typed (tpe match {
+        case ct: ConstantType => ct.value match {
+            case v @ Constant(null) if scrutTree.tpe.isAnyRef   => scrutTree ANY_EQ NULL
+            case v                                              => scrutTree MEMBER_== Literal(v)
+          }
+        case _: SingletonType if useEqTest                      =>
+          val eqTest = REF(tpe.termSymbol) MEMBER_== scrutTree
+
+          // See ticket #1503 for the motivation behind checking for a binding.
+          // The upshot is that it is unsound to assume equality means the right
+          // type, but if the value doesn't appear on the right hand side of the
+          // match that's unimportant; so we add an instance check only if there
+          // is a binding.
+          if (isBound) {
+            if (settings.Xmigration28.value) {
+              cunit.warning(scrutTree.pos, "A bound pattern such as 'x @ Pattern' now matches fewer cases than the same pattern with no binding.")
+            }
+            eqTest AND (scrutTree IS tpe.widen)
+          }
+          else eqTest
+                  
+        case _ if scrutTree.tpe <:< tpe && tpe.isAnyRef         => scrutTree OBJ_!= NULL
+        case _                                                  => scrutTree IS tpe
+      })
     }
-  }
 
-  /** adds a test comparing the dynamic outer to the static outer */
-  final def addOuterCondition(cond: Tree, tpe2test: Type, scrut: Tree, handleOuter: Tree=>Tree) = {
-    val theRef = handleOuter(tpe2test match {
-      case TypeRef(NoPrefix, _, _)          => abort("assertion failed: NoPrefix")
-      case TypeRef(ThisType(clazz), _, _)   => gen.mkAttributedThis(clazz)
-      case TypeRef(prefix, _, _)            => gen.mkAttributedRef(prefix.prefix, prefix.termSymbol)
-    })
-    
-    outerAccessor(tpe2test.typeSymbol) match {
-      case NoSymbol => if (settings.debug.value) cunit.warning(scrut.pos, "no outer acc for "+tpe2test.typeSymbol) ; cond
-      case outerAcc => And(cond, Eq(Code.fn(gen.mkAsInstanceOf(scrut, tpe2test, true), outerAcc), theRef))
+    /** adds a test comparing the dynamic outer to the static outer */
+    final def addOuterCondition(cond: Tree, tpe2test: Type, scrut: Tree) = {
+      val TypeRef(prefix, _, _) = tpe2test
+      val theRef = handleOuter(prefix match {
+        case NoPrefix         => abort("assertion failed: NoPrefix")
+        case ThisType(clazz)  => THIS(clazz)
+        case pre              => REF(pre.prefix, pre.termSymbol)
+      })
+
+      outerAccessor(tpe2test.typeSymbol) match {
+        case NoSymbol => ifDebug(cunit.warning(scrut.pos, "no outer acc for " + tpe2test.typeSymbol)) ; cond
+        case outerAcc => cond AND (((scrut AS_ANY tpe2test) DOT outerAcc)() ANY_EQ theRef)
+      }
     }
   }
-  
 }
diff --git a/src/compiler/scala/tools/nsc/matching/PatternBindings.scala b/src/compiler/scala/tools/nsc/matching/PatternBindings.scala
new file mode 100644
index 0000000..ab46188
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/matching/PatternBindings.scala
@@ -0,0 +1,153 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
+ * Author: Paul Phillips
+ */
+
+package scala.tools.nsc
+package matching
+
+import transform.ExplicitOuter
+import collection.immutable.TreeMap
+import PartialFunction._
+
+trait PatternBindings extends ast.TreeDSL
+{ 
+  self: ExplicitOuter with ParallelMatching =>
+  
+  import global.{ typer => _, _ }
+  import definitions.{ EqualsPatternClass }
+  import CODE._
+  import Debug._
+  
+  /** EqualsPattern **/
+  def isEquals(tpe: Type)           = cond(tpe) { case TypeRef(_, EqualsPatternClass, _) => true }
+  def mkEqualsRef(tpe: Type)        = typeRef(NoPrefix, EqualsPatternClass, List(tpe))
+  def decodedEqualsType(tpe: Type)  = condOpt(tpe) { case TypeRef(_, EqualsPatternClass, List(arg)) => arg } getOrElse (tpe)
+  
+  // used as argument to `EqualsPatternClass'
+  case class PseudoType(o: Tree) extends SimpleTypeProxy {
+    override def underlying: Type = o.tpe
+    override def safeToString: String = "PseudoType("+o+")"
+  }
+
+  // If the given pattern contains alternatives, return it as a list of patterns.
+  // Makes typed copies of any bindings found so all alternatives point to final state.
+  def extractBindings(p: Pattern): List[Pattern] =
+    toPats(_extractBindings(p.boundTree, identity))
+  
+  private def _extractBindings(p: Tree, prevBindings: Tree => Tree): List[Tree] = {
+    def newPrev(b: Bind) = (x: Tree) => treeCopy.Bind(b, b.name, x) setType x.tpe
+
+    p match {
+      case b @ Bind(_, body)  => _extractBindings(body, newPrev(b))
+      case Alternative(ps)    => ps map prevBindings
+    }
+  }
+  
+  trait PatternBindingLogic {
+    self: Pattern =>
+    
+    // This is for traversing the pattern tree - pattern types which might have
+    // bound variables beneath them return a list of said patterns for flatMapping.
+    def subpatternsForVars: List[Pattern] = Nil
+    
+    private def shallowBoundVariables = strip(boundTree)
+    private def otherBoundVariables = subpatternsForVars flatMap (_.deepBoundVariables)
+    
+    def deepBoundVariables: List[Symbol] = shallowBoundVariables ::: otherBoundVariables
+    // An indiscriminate deep search would be:
+    //
+    // def deepBoundVariables = deepstrip(boundTree)
+    
+    lazy val boundVariables = {
+      val res = shallowBoundVariables
+      val deep = deepBoundVariables
+      
+      if (res.size != deep.size)
+        TRACE("deep variable list %s is larger than bound %s", deep, res)
+
+      res
+    }
+    
+    // XXX only a var for short-term experimentation.
+    private var _boundTree: Bind = null
+    def boundTree = if (_boundTree == null) tree else _boundTree
+    def withBoundTree(x: Bind): this.type = {
+      _boundTree = x
+      tracing[this.type]("Bound", this)
+    }
+    
+    // If a tree has bindings, boundTree looks something like
+    //   Bind(v3, Bind(v2, Bind(v1, tree)))
+    // This takes the given tree and creates a new pattern
+    //   using the same bindings.
+    def rebindTo(t: Tree): Pattern = {
+      if (boundVariables.size < deepBoundVariables.size)
+        TRACE("ALERT: rebinding %s is losing %s", this, otherBoundVariables)
+        
+      Pattern(wrapBindings(boundVariables, t))
+    }
+
+    // Wrap this pattern's bindings around (_: Type)
+    def rebindToType(tpe: Type, annotatedType: Type = null): Pattern = {
+      val aType = if (annotatedType == null) tpe else annotatedType
+      rebindTo(Typed(WILD(tpe), TypeTree(aType)) setType tpe)
+    }
+    
+    // Wrap them around _
+    def rebindToEmpty(tpe: Type): Pattern =
+      rebindTo(Typed(EmptyTree, TypeTree(tpe)) setType tpe)
+    
+    // Wrap them around a singleton type for an EqualsPattern check.
+    def rebindToEqualsCheck(): Pattern =
+      rebindToType(equalsCheck)
+    
+    // Like rebindToEqualsCheck, but subtly different.  Not trying to be
+    // mysterious -- I haven't sorted it all out yet.
+    def rebindToObjectCheck(): Pattern = {
+      val sType = sufficientType
+      rebindToType(mkEqualsRef(sType), sType)
+    }
+       
+    /** Helpers **/    
+    private def wrapBindings(vs: List[Symbol], pat: Tree): Tree = vs match {
+      case Nil      => pat
+      case x :: xs  => Bind(x, wrapBindings(xs, pat)) setType pat.tpe
+    }
+    private def strip(t: Tree): List[Symbol] = t match {
+      case b @ Bind(_, pat) => b.symbol :: strip(pat)
+      case _                => Nil
+    }
+    private def deepstrip(t: Tree): List[Symbol] =
+      t filter { case _: Bind => true ; case _ => false } map (_.symbol)
+  }
+
+  case class Binding(pvar: Symbol, tvar: Symbol) {
+    // see bug #1843 for the consequences of not setting info.
+    // there is surely a better way to do this, especially since
+    // this looks to be the only usage of containsTp anywhere
+    // in the compiler, but it suffices for now.
+    if (tvar.info containsTp WildcardType)
+      tvar setInfo pvar.info
+
+    override def toString() = pp(pvar -> tvar)
+  }
+
+  class Bindings(private val vlist: List[Binding]) {
+    if (!vlist.isEmpty)
+      traceCategory("Bindings", this.toString)
+
+    def get() = vlist
+    
+    def add(vs: Iterable[Symbol], tvar: Symbol): Bindings = {
+      val newBindings = vs.toList map (v => Binding(v, tvar))
+      new Bindings(newBindings ++ vlist)
+    }
+
+    override def toString() = 
+      if (vlist.isEmpty) "No Bindings"
+      else "%d Bindings(%s)".format(vlist.size, pp(vlist))
+  }
+
+  val NoBinding: Bindings = new Bindings(Nil)
+}
\ No newline at end of file
diff --git a/src/compiler/scala/tools/nsc/matching/PatternNodes.scala b/src/compiler/scala/tools/nsc/matching/PatternNodes.scala
deleted file mode 100644
index 1085882..0000000
--- a/src/compiler/scala/tools/nsc/matching/PatternNodes.scala
+++ /dev/null
@@ -1,246 +0,0 @@
-/* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
- * @author Burak Emir
- */
-// $Id: PatternNodes.scala 16894 2009-01-13 13:09:41Z cunei $
-
-package scala.tools.nsc.matching
-
-import scala.tools.nsc.util.{Position, NoPosition}
-
-/**
- *  @author Burak Emir
- */
-trait PatternNodes { 
-  self: transform.ExplicitOuter =>
-  
-  import global.{ typer => _, _ }
-  import analyzer.Typer
-  import symtab.Flags
-  import Types._
-  
-  case class TypeComparison(x: Type, y: Type) {
-    def xIsaY = x <:< y
-    def yIsaX = y <:< x
-    def xEqY  = y =:= x
-    def xIgnY = !xIsaY && !yIsaX && !xEqY
-    def eqSymbol = cmpSymbols(x, y)
-    def eqPrefix = x.prefix =:= y.prefix
-    
-    private def cmpSymbols(t1: Type, t2: Type) = t1.typeSymbol eq t2.typeSymbol
-    // true if t2 is a parent of t1.  Should this be rather: tpe.baseTypes.exists...?
-    private def  parenthood(t1: Type, t2: Type) = t1.parents.exists(p => cmpSymbols(p, t2))
-    // true if t1 is direct subtype of t2 (can't use just <:< cause have to take variance into account)
-    private def subtypehood(t1: Type, t2: Type) = t1.parents.exists(p => cmpSymbols(p, t2) && p <:< t2)
-    
-    def yParentsX = parenthood(x, y) 
-    def xParentsY = parenthood(y, x)    
-    def xExtendsY = subtypehood(x, y)
-    def yExtendsX = subtypehood(y, x)
-    
-    object erased {
-      import Types._
-      /** an approximation of _tp1 <:< tp2 that ignores _ types. this code is wrong,
-       *  ideally there is a better way to do it, and ideally defined in Types.scala
-       */
-      private def cmpErased(t1: Type, t2: Type) = (t1, t2) match {
-        case (_: TypeRef, _: TypeRef) => (eqPrefix && eqSymbol && !t1.isArray) || parenthood(t1, t2)
-        case _ => false
-      }
-      
-      def xIsaY = cmpErased(x, y)
-      def yIsaX = cmpErased(y, x)
-    }
-  }
-
-  object Types {
-    import definitions._
-    implicit def enrichType(_tpe: Type): RichType = new RichType(_tpe)
-    
-    class RichType(_tpe: Type) {
-      /* equality checks for named constant patterns like "Foo()" are encoded as "_:<equals>[Foo().type]"
-       * and later compiled to "if(Foo() == scrutinee) ...". This method extracts type information from
-       * such an encoded type, which is used in optimization. If the argument is not an encoded equals
-       * test, it is returned as is.
-       */      
-      private def tpeWRTEquality(t: Type) = t match {
-        case TypeRef(_, sym, arg::Nil) if sym eq EqualsPatternClass => arg
-        case _                                                      => t
-      }
-      lazy val tpe = tpeWRTEquality(_tpe)
-      
-      // The several different logics in these tests are intentionally grouped here to
-      // draw attention to them.  To the extent that the differences are intentional,
-      // the thinking behind the distinctions needs to be documented.
-      def       isInt = tpe =:= IntClass.tpe
-      def      isChar = tpe =:= CharClass.tpe
-      def    isAnyRef = tpe <:< AnyRefClass.tpe
-      def   isBoolean = tpe.typeSymbol eq BooleanClass
-      def     isArray = tpe.typeSymbol eq ArrayClass
-      def   isNothing = tpe.typeSymbol eq NothingClass      
-      def isCaseClass = tpe.typeSymbol hasFlag Flags.CASE
-            
-      def cmp(other: Type): TypeComparison = TypeComparison(tpe, tpeWRTEquality(other))
-      
-      def coversSym(sym: Symbol) = {
-        val symtpe = 
-          if ((sym hasFlag Flags.MODULE) && (sym.linkedModuleOfClass ne NoSymbol))
-            singleType(sym.tpe.prefix, sym.linkedModuleOfClass)   // e.g. None, Nil
-          else sym.tpe
-
-        (tpe.typeSymbol == sym) ||
-        (symtpe <:< tpe) ||
-        (symtpe.parents.exists(_.typeSymbol eq tpe.typeSymbol)) || // e.g. Some[Int] <: Option[&b]
-        (tpe.prefix.memberType(sym) <:< tpe)  // outer, see combinator.lexical.Scanner
-      }
-    }
-  
-    // used as argument to `EqualsPatternClass'
-    case class PseudoType(o: Tree) extends SimpleTypeProxy {
-      override def underlying: Type = o.tpe
-      override def safeToString: String = "PseudoType("+o+")"
-    }
-  }
-
-  final def DBG(x: => String)   = if (settings.debug.value) Console.println(x)
-    
-  final def getDummies(i: Int): List[Tree] = List.make(i, EmptyTree)
-
-  def makeBind(vs:List[Symbol], pat:Tree): Tree = 
-    if (vs eq Nil) pat else Bind(vs.head, makeBind(vs.tail, pat)) setType pat.tpe
-    
-  def mkTypedBind(vs: List[Symbol], tpe: Type) =
-    makeBind(vs, Typed(mk_(tpe), TypeTree(tpe)) setType tpe)  
-    
-  def mkEmptyTreeBind(vs: List[Symbol], tpe: Type) =
-    makeBind(vs, Typed(EmptyTree, TypeTree(tpe)) setType tpe)
-    
-  def mkEqualsRef(xs: List[Type]) = typeRef(NoPrefix, definitions.EqualsPatternClass, xs)
-
-  def normalizedListPattern(pats:List[Tree], tptArg:Type): Tree = pats match {
-    case Nil   => gen.mkNil
-    case (sp @ Strip(_, _: Star)) :: xs => makeBind(definedVars(sp), mk_(sp.tpe))
-    case x::xs => 
-      var resType: Type = null;
-      val consType: Type = definitions.ConsClass.primaryConstructor.tpe match {
-        case mt @ MethodType(args, res @ TypeRef(pre,sym,origArgs)) =>
-          val listType = TypeRef(pre, definitions.ListClass, List(tptArg))
-               resType = TypeRef(pre, sym                  , List(tptArg))
-        
-          MethodType(List(tptArg, listType), resType)
-      }
-      Apply(TypeTree(consType), List(x,normalizedListPattern(xs,tptArg))) setType resType
-  }
-
-  object Apply_Value {
-    def unapply(x: Apply) = if (!x.fun.isType && x.args.isEmpty) Some(x.tpe.prefix, x.symbol) else None
-  }
-  
-  object Apply_Function {
-    def isApplyFunction(o: Apply) = !o.tpe.isCaseClass || !Apply_Value.unapply(o).isEmpty /*see t301*/
-    def unapply(x: Apply) = if (x.args.isEmpty && isApplyFunction(x)) Some(x.fun) else None    
-  }
-                   
-  object Apply_CaseClass_NoArgs {
-    def unapply(x: Apply) = if (x.fun.isType && x.args.isEmpty) Some(x.tpe) else None
-  }
-  object Apply_CaseClass_WithArgs {
-    def unapply(x: Apply) = x.fun.isType
-  }
-  
-  // TODO - this doesn't work! For some reason this sometimes returns false when encapsulated
-  // in an object like this, when it returns true if the same logic is applied literally in
-  // the classifyPat match in ParallelMatching.  I couldn't figure out why, and it concerns
-  // me - if this isn't working maybe other unapply objects aren't working right either.  The big
-  // problem with using unapply and type matching is that if something's amiss, it will simply fail
-  // silently, with the bug most likely manifesting at some unknown later point.
-  object Ident_Or_Empty {
-    def unapply(x: Any) = x match {
-      case Ident(nme.WILDCARD) | EmptyTree | _: Typed | _: Literal => true
-      // this returns false, and then a line identical the one above will match
-      // back in PM.scala.
-      case _ => false   
-    }
-  }
-
-  object UnApply_TypeApply {
-    def unapply(x: UnApply) = x match {
-      case UnApply(Apply(TypeApply(sel @ Select(stor, nme.unapplySeq), List(tptArg)), _), ArrayValue(_, xs)::Nil)
-        if (stor.symbol eq definitions.ListModule)  => Some(tptArg, xs)
-      case _                                        => None
-    }
-  }
-    
-  object __UnApply {
-    private def paramType(fn: Tree) = fn.tpe match { case m: MethodType => m.paramTypes.head }
-    def unapply(x: Tree) = x match {
-      case Strip(vs, UnApply(Apply(fn, _), args)) => Some(vs, paramType(fn), args)
-      case _                                      => None
-    }
-  }
-
-  /** returns if pattern can be considered a no-op test ??for expected type?? */
-  final def isDefaultPattern(pattern: Tree): Boolean = pattern match {
-    case Bind(_, p)            => isDefaultPattern(p)
-    case EmptyTree             => true // dummy
-    case Ident(nme.WILDCARD)   => true
-    case _                     => false
-// -- what about the following? still have to test "ne null" :/
-//  case Typed(nme.WILDCARD,_) => pattern.tpe <:< scrut.tpe
-  }
-
-  /** returns all variables that are binding the given pattern 
-   *  @param   x a pattern
-   *  @return  vs variables bound, p pattern proper
-   */
-  final def strip(x: Tree): (Set[Symbol], Tree) = x match {
-    case b @ Bind(_,pat) => val (vs, p) = strip(pat); (vs + b.symbol, p)
-    case _               => (emptySymbolSet, x)
-  }
-  final def strip1(x: Tree): Set[Symbol] = strip(x)._1
-  final def strip2(x: Tree): Tree = strip(x)._2;
-  
-  object Strip  { def unapply(x: Tree): Option[(Set[Symbol], Tree)] = Some(strip(x))  }
-  object Strip1 { def unapply(x: Tree): Option[Set[Symbol]]         = Some(strip1(x)) }
-  object Strip2 { def unapply(x: Tree): Option[Tree]                = Some(strip2(x)) }
-
-  final def definedVars(x: Tree): List[Symbol] = {
-    implicit def listToStream[T](xs: List[T]): Stream[T] = xs.toStream
-    def definedVars1(x: Tree): Stream[Symbol] = x match {
-      case Apply(_, args)     => definedVars2(args)
-      case b @ Bind(_,p)      => Stream.cons(b.symbol, definedVars1(p))
-      case Typed(p,_)         => definedVars1(p)    // otherwise x @ (_:T)
-      case UnApply(_,args)    => definedVars2(args)
-      case ArrayValue(_,xs)   => definedVars2(xs)   
-      case _                  => Nil
-    }
-    def definedVars2(args: Stream[Tree]): Stream[Symbol] = args flatMap definedVars1
-  
-    definedVars1(x).reverse.toList
-  }
-  
-  /** pvar: the symbol of the pattern variable
-   *  temp: the temp variable that holds the actual value
-   */
-  case class Binding(pvar: Symbol, temp: Symbol)
-  
-  case class Bindings(bindings: Binding*) extends Function1[Symbol, Option[Ident]] {
-    def add(vs: Iterable[Symbol], temp: Symbol): Bindings =
-      Bindings(vs.toList.map(Binding(_, temp)) ++ bindings : _*)
-       
-    def apply(v: Symbol): Option[Ident] = bindings.find(_.pvar eq v) match {
-      case Some(b)  => Some(Ident(b.temp) setType v.tpe)
-      case None     => None // abort("Symbol " + v + " has no binding in " + bindings)
-    }
-
-    /**
-     * The corresponding list of value definitions.
-     */
-    final def targetParams(implicit typer: Typer): List[ValDef] = 
-      bindings.toList.map{ case Binding(v, t) => ValDef(v,  
-        typer.typed{if(t.tpe <:< v.tpe) mkIdent(t)  
-                    else gen.mkAsInstanceOf(mkIdent(t), v.tpe)})}
-  }
-
-  val NoBinding: Bindings = Bindings()
-}
diff --git a/src/compiler/scala/tools/nsc/matching/Patterns.scala b/src/compiler/scala/tools/nsc/matching/Patterns.scala
new file mode 100644
index 0000000..dfbcdab
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/matching/Patterns.scala
@@ -0,0 +1,531 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
+ * Author: Paul Phillips
+ */
+
+package scala.tools.nsc
+package matching
+
+import symtab.Flags
+import scala.reflect.NameTransformer.decode
+import PartialFunction._
+
+/** Patterns are wrappers for Trees with enhanced semantics.
+ *
+ *  @author Paul Phillips
+ */
+
+trait Patterns extends ast.TreeDSL {
+  self: transform.ExplicitOuter =>
+
+  import global.{ typer => _, _ }
+  import definitions._
+  import CODE._
+  import Debug._
+  import treeInfo.{ unbind, isStar, isVarPattern, isVariableName }
+  
+  type PatternMatch       = MatchMatrix#PatternMatch
+  private type PatternVar = MatrixContext#PatternVar
+  
+  // Fresh patterns
+  def emptyPatterns(i: Int): List[Pattern] = List.fill(i)(NoPattern)
+  def emptyTrees(i: Int): List[Tree] = List.fill(i)(EmptyTree)
+  
+  // An empty pattern
+  def NoPattern = WildcardPattern()
+  
+  // The constant null pattern
+  def NullPattern = LiteralPattern(NULL)
+  
+  // The Nil pattern
+  def NilPattern = Pattern(gen.mkNil)
+  
+  // 8.1.1
+  case class VariablePattern(tree: Ident) extends NamePattern {
+    val Ident(name) = tree
+    require(isVarPattern(tree) && name != nme.WILDCARD)
+    
+    override def irrefutableFor(tpe: Type) = true
+    override def description = "%s".format(name)
+  }
+  
+  // 8.1.1 (b)
+  case class WildcardPattern() extends Pattern {
+    val tree = EmptyTree
+    override def irrefutableFor(tpe: Type) = true
+    override def isDefault = true
+    override def description = "_"
+  }
+  
+  // 8.1.2
+  case class TypedPattern(tree: Typed) extends Pattern {
+    private val Typed(expr, tpt) = tree
+    
+    override def subpatternsForVars: List[Pattern] = List(Pattern(expr))
+    
+    override def irrefutableFor(tpe: Type) = tpe <:< tree.tpe
+    override def simplify(pv: PatternVar) = Pattern(expr) match {
+      case ExtractorPattern(ua) if pv.sym.tpe <:< tpt.tpe  => this rebindTo expr
+      case _                                                => this
+    }
+    override def description = "Typ(%s: %s)".format(Pattern(expr), tpt)
+  }
+  
+  // 8.1.3
+  case class LiteralPattern(tree: Literal) extends Pattern {
+    val Literal(const @ Constant(value)) = tree
+    
+    def isSwitchable = cond(const.tag) { case ByteTag | ShortTag | IntTag | CharTag => true }
+    def intValue = const.intValue
+    override def description = {
+      val s = if (value == null) "null" else value.toString() 
+      "Lit(%s)".format(s)
+    }
+  }
+  
+  // 8.1.4 (a)
+  case class ApplyIdentPattern(tree: Apply) extends ApplyPattern with NamePattern {
+    // XXX - see bug 3411 for code which violates this assumption
+    // require (!isVarPattern(fn) && args.isEmpty)
+    val ident @ Ident(name) = fn
+
+    override def sufficientType = Pattern(ident).equalsCheck
+    override def simplify(pv: PatternVar) = this.rebindToObjectCheck()
+    override def description = "Id(%s)".format(name)
+  }
+  // 8.1.4 (b)
+  case class ApplySelectPattern(tree: Apply) extends ApplyPattern with SelectPattern {
+    require (args.isEmpty)
+    val Apply(select: Select, _) = tree
+    
+    override def sufficientType = mkSingletonFromQualifier
+    override def simplify(pv: PatternVar) = this.rebindToObjectCheck()
+    override def description = backticked match {
+      case Some(s)  => "this." + s
+      case _        => "Sel(%s.%s)".format(Pattern(qualifier), name)
+    }
+      
+  }
+  // 8.1.4 (c)
+  case class StableIdPattern(tree: Select) extends SelectPattern {
+    def select = tree
+    override def description = "St(%s)".format(printableSegments.mkString(" . "))
+    private def printableSegments = 
+      pathSegments filter (x => !x.isEmpty && (x.toString != "$iw"))
+  }
+  // 8.1.4 (d)
+  case class ObjectPattern(tree: Apply) extends ApplyPattern {  // NamePattern?
+    require(!fn.isType && isModule)
+    
+    override def sufficientType = tpe.narrow
+    override def simplify(pv: PatternVar) = this.rebindToObjectCheck()
+    override def description = "Obj(%s)".format(fn)
+  }
+  // 8.1.4 (e)
+  case class SimpleIdPattern(tree: Ident) extends NamePattern {
+    val Ident(name) = tree
+    override def description = "Id(%s)".format(name)
+  }
+
+  // 8.1.5
+  case class ConstructorPattern(tree: Apply) extends ApplyPattern with NamePattern {
+    require(fn.isType && this.isCaseClass)
+    def name = tpe.typeSymbol.name
+    def cleanName = tpe.typeSymbol.decodedName
+    def hasPrefix = tpe.prefix.prefixString != ""
+    def prefixedName =
+      if (hasPrefix) "%s.%s".format(tpe.prefix.prefixString, cleanName)
+      else cleanName
+      
+    private def isColonColon = cleanName == "::"
+
+    override def subpatterns(pm: MatchMatrix#PatternMatch) = 
+      if (pm.head.isCaseClass) toPats(args)
+      else super.subpatterns(pm)
+    
+    override def simplify(pv: PatternVar) =
+      if (args.isEmpty) this rebindToEmpty tree.tpe
+      else this
+    
+    override def description = {
+      if (isColonColon) "%s :: %s".format(Pattern(args(0)), Pattern(args(1)))
+      else "%s(%s)".format(name, toPats(args).mkString(", "))
+    }
+      
+    // XXX todo
+    // override def irrefutableFor(tpe: Type) = false
+  }  
+  // 8.1.6
+  case class TuplePattern(tree: Apply) extends ApplyPattern {
+    // XXX todo
+    // override def irrefutableFor(tpe: Type) = false
+    override def description = "((%s))".format(args.size, toPats(args).mkString(", "))
+  }
+  
+  // 8.1.7
+  case class ExtractorPattern(tree: UnApply) extends UnapplyPattern {
+    private val Apply(fn, _) = unfn
+    private val MethodType(List(arg, _*), _) = fn.tpe
+    private def uaTyped = Typed(tree, TypeTree(arg.tpe)) setType arg.tpe
+
+    override def necessaryType = arg.tpe
+    
+    override def simplify(pv: PatternVar) =
+      if (pv.sym.tpe <:< arg.tpe) this
+      else this rebindTo uaTyped
+      
+    override def description = "UnApp(%s => %s)".format(necessaryType, resTypesString)
+  }
+  
+  // 8.1.8 (unapplySeq calls)
+  case class SequenceExtractorPattern(tree: UnApply) extends UnapplyPattern with SequenceLikePattern {
+    
+    lazy val UnApply(
+      Apply(TypeApply(Select(_, nme.unapplySeq), List(tptArg)), _),
+      List(ArrayValue(_, elems))
+    ) = tree
+    
+    /** For folding a list into a well-typed x :: y :: etc :: tree. */
+    private def listFolder = {
+      val tpe = tptArg.tpe
+      val MethodType(_, TypeRef(pre, sym, _)) = ConsClass.primaryConstructor.tpe
+      val consRef                             = typeRef(pre, sym, List(tpe))
+      val listRef                             = typeRef(pre, ListClass, List(tpe))
+
+      def fold(x: Tree, xs: Tree) = unbind(x) match {
+        case _: Star  => Pattern(x) rebindTo WILD(x.tpe) boundTree  // this is using boundVariables instead of deepBoundVariables
+        case _        =>
+          val dummyMethod = new TermSymbol(NoSymbol, NoPosition, "matching$dummy")
+          val consType    = MethodType(dummyMethod newSyntheticValueParams List(tpe, listRef), consRef)
+
+          Apply(TypeTree(consType), List(x, xs)) setType consRef
+      }
+
+      fold _
+    }
+
+    // @pre: is not right-ignoring (no star pattern) ; no exhaustivity check
+    override def simplify(pv: PatternVar) = {
+      pv.sym setFlag Flags.TRANS_FLAG
+      this rebindTo elems.foldRight(gen.mkNil)(listFolder)
+    }
+    override def description = "UnSeq(%s => %s)".format(tptArg, resTypesString)
+  }
+  
+  trait SequenceLikePattern extends Pattern {
+    def elems: List[Tree]
+    def elemPatterns = toPats(elems)
+
+    def nonStarPatterns: List[Pattern] = if (hasStar) elemPatterns.init else elemPatterns
+    def nonStarLength = nonStarPatterns.length
+    def isAllDefaults = nonStarPatterns forall (_.isDefault)
+    
+    def isShorter(other: SequenceLikePattern) = nonStarLength < other.nonStarLength
+    def isSameLength(other: SequenceLikePattern) = nonStarLength == other.nonStarLength
+  }
+  
+  // 8.1.8 (b) (literal ArrayValues)
+  case class SequencePattern(tree: ArrayValue) extends Pattern with SequenceLikePattern {
+    lazy val ArrayValue(elemtpt, elems) = tree
+    
+    override def subpatternsForVars: List[Pattern] = elemPatterns
+    override def description = "Seq(%s)".format(elemPatterns mkString ", ")
+  }
+  
+  // 8.1.8 (c)
+  case class StarPattern(tree: Star) extends Pattern {
+    val Star(elem) = tree
+    override def description = "_*"
+  }
+  // XXX temporary?
+  case class ThisPattern(tree: This) extends NamePattern {
+    val This(name) = tree
+    override def description = "this"
+  }
+  
+  // 8.1.9
+  // InfixPattern ... subsumed by Constructor/Extractor Patterns
+  
+  // 8.1.10  
+  case class AlternativePattern(tree: Alternative) extends Pattern { 
+    private lazy val Alternative(subtrees) = tree
+    private def alts = toPats(subtrees)
+    override def description = "Alt(%s)".format(alts mkString " | ")
+  }
+  
+  // 8.1.11
+  // XMLPattern ... for now, subsumed by SequencePattern, but if we want
+  //   to make it work right, it probably needs special handling.
+
+  private def abortUnknownTree(tree: Tree) =
+    abort("Unknown Tree reached pattern matcher: %s/%s".format(tree, tree.getClass))
+
+  object Pattern {
+    // a small tree -> pattern cache
+    private val cache = new collection.mutable.HashMap[Tree, Pattern]
+    
+    def unadorn(x: Tree): Tree = x match {
+      case Typed(expr, _) => unadorn(expr)
+      case Bind(_, x)     => unadorn(x)
+      case _              => x
+    }
+
+    def isRightIgnoring(t: Tree) = cond(unadorn(t)) {
+      case ArrayValue(_, xs) if !xs.isEmpty => isStar(unadorn(xs.last))
+    }
+    
+    def apply(tree: Tree): Pattern = {
+      if (cache contains tree)
+        return cache(tree)
+      
+      val p = tree match {
+        case x: Bind              => apply(unbind(tree)) withBoundTree x
+        case EmptyTree            => WildcardPattern()
+        case Ident(nme.WILDCARD)  => WildcardPattern()
+        case x @ Alternative(ps)  => AlternativePattern(x)
+        case x: Apply             => ApplyPattern(x)
+        case x: Typed             => TypedPattern(x)
+        case x: Literal           => LiteralPattern(x)
+        case x: UnApply           => UnapplyPattern(x)
+        case x: Ident             => if (isVarPattern(x)) VariablePattern(x) else SimpleIdPattern(x)
+        case x: ArrayValue        => SequencePattern(x)
+        case x: Select            => StableIdPattern(x)
+        case x: Star              => StarPattern(x)
+        case x: This              => ThisPattern(x) // XXX ?
+        case _                    => abortUnknownTree(tree)
+      }
+      cache(tree) = p
+      
+      // limiting the trace output
+      p match {
+        case WildcardPattern()  => p
+        case _: LiteralPattern  => p
+        case _                  => tracing("Pattern", p)
+      }
+    }
+    def unapply(other: Any): Option[(Tree, List[Symbol])] = other match {
+      case x: Tree    => unapply(Pattern(x))
+      case x: Pattern => Some((x.tree, x.boundVariables))
+      case _          => None
+    }
+  }
+  
+  object UnapplyPattern {
+    private object UnapplySeq {
+      private object TypeApp {
+        def unapply(x: Any) = condOpt(x) { 
+          case TypeApply(sel @ Select(stor, nme.unapplySeq), List(tpe)) if stor.symbol eq ListModule => tpe
+        }
+      }
+      def unapply(x: UnApply) = condOpt(x) {
+        case UnApply(Apply(TypeApp(tptArg), _), List(ArrayValue(_, xs))) => (tptArg, xs)
+      }
+    }
+
+    def apply(x: UnApply): Pattern = {
+      x match {
+        case UnapplySeq(_, _) => SequenceExtractorPattern(x)
+        case _                => ExtractorPattern(x)
+      }
+    }
+  }
+  
+  // right now a tree like x @ Apply(fn, Nil) where !fn.isType
+  // is handled by creating a singleton type: 
+  //
+  //    val stype = Types.singleType(x.tpe.prefix, x.symbol)
+  //
+  // and then passing that as a type argument to EqualsPatternClass:
+  //
+  //    val tpe = typeRef(NoPrefix, EqualsPatternClass, List(stype))
+  //
+  // then creating a Typed pattern and rebinding.
+  //
+  //    val newpat = Typed(EmptyTree, TypeTree(tpe)) setType tpe)
+  //
+  // This is also how Select(qual, name) is handled.
+  object ApplyPattern {
+    def apply(x: Apply): Pattern = {
+      val Apply(fn, args) = x
+      def isModule  = x.symbol.isModule || x.tpe.termSymbol.isModule
+      def isTuple   = isTupleType(fn.tpe)
+
+      if (fn.isType) {
+        if (isTuple) TuplePattern(x)
+        else ConstructorPattern(x)
+      }
+      else if (args.isEmpty) {
+        if (isModule) ObjectPattern(x)
+        else fn match {
+          case _: Ident   => ApplyIdentPattern(x)
+          case _: Select  => ApplySelectPattern(x)
+        }
+      }
+      else abortUnknownTree(x)
+    }
+  }
+
+  /** Some intermediate pattern classes with shared structure **/
+  
+  sealed trait SelectPattern extends NamePattern {
+    def select: Select
+    lazy val Select(qualifier, name) = select
+    def pathSegments = getPathSegments(tree)
+    def backticked: Option[String] = qualifier match {
+      case _: This if isVariableName(name)  => Some("`%s`".format(name))
+      case _                                => None
+    }
+    
+    protected def getPathSegments(t: Tree): List[Name] = t match {
+      case Select(q, name)  => name :: getPathSegments(q)
+      case Apply(f, Nil)    => getPathSegments(f)
+      case _                => Nil
+    }
+    protected def mkSingletonFromQualifier = {
+      def pType = qualifier match {
+        case _: Apply => PseudoType(tree)
+        case _        => singleType(Pattern(qualifier).necessaryType, sym)
+      }
+      qualifier.tpe match {
+        case t: ThisType  => singleType(t, sym) // this.X
+        case _            => pType
+      }
+    }
+  }  
+  
+  sealed trait NamePattern extends Pattern {
+    def name: Name
+    override def sufficientType = tpe.narrow
+    override def simplify(pv: PatternVar) = this.rebindToEqualsCheck()
+    override def description = name.toString()
+  }
+  
+  sealed trait UnapplyPattern extends Pattern {
+    lazy val UnApply(unfn, args) = tree
+    override def subpatternsForVars: List[Pattern] = toPats(args)
+    
+    def resTypes = analyzer.unapplyTypeList(unfn.symbol, unfn.tpe)
+    def resTypesString = resTypes match {
+      case Nil  => "Boolean"
+      case xs   => xs.mkString(", ")
+    }
+    
+    private def isSameFunction(f1: Tree, f2: Tree) =
+      (f1.symbol == f2.symbol) && (f1 equalsStructure f2)
+      
+    // XXX args
+    def isSameUnapply(other: UnapplyPattern) =
+      isSameFunction(unfn, other.unfn)
+  }
+
+  sealed trait ApplyPattern extends Pattern {
+    protected lazy val Apply(fn, args) = tree
+    override def subpatternsForVars: List[Pattern] = toPats(args)
+    
+    override def dummies =
+      if (!this.isCaseClass) Nil
+      else emptyPatterns(sufficientType.typeSymbol.caseFieldAccessors.size)
+
+    def isConstructorPattern = fn.isType    
+  }
+  
+  sealed abstract class Pattern extends PatternBindingLogic {
+    val tree: Tree
+
+    // returns either a simplification of this pattern or identity.
+    def simplify(pv: PatternVar): Pattern = this
+    def simplify(): Pattern = this simplify null
+    
+    // the right number of dummies for this pattern
+    def dummies: List[Pattern] = Nil
+    
+    // 8.1.13
+    // A pattern p is irrefutable for type T if any of the following applies:
+    //   1) p is a variable pattern
+    //   2) p is a typed pattern x: T', and T <: T'
+    //   3) p is a constructor pattern C(p1,...,pn), the type T is an instance of class C,
+    //      the primary constructor of type T has argument types T1,...,Tn and and each
+    //      pi is irrefutable for Ti.
+    def irrefutableFor(tpe: Type) = false
+    
+    // does this pattern completely cover that pattern (i.e. latter cannot be matched)
+    def completelyCovers(second: Pattern) = false
+    
+    // Is this a default pattern (untyped "_" or an EmptyTree inserted by the matcher)
+    def isDefault = false
+    
+    // what type must a scrutinee have to have any chance of matching this pattern?
+    def necessaryType = tpe
+    
+    // what type could a scrutinee have which would automatically indicate a match?
+    // (nullness and guards will still be checked.)
+    def sufficientType = tpe
+    
+    // XXX have to determine if this can be made useful beyond an extractor barrier.
+    // Default sufficient type might be NothingClass.tpe, tpe.narrow, ...
+    
+    // the subpatterns for this pattern (at the moment, that means constructor arguments)
+    def subpatterns(pm: MatchMatrix#PatternMatch): List[Pattern] = pm.dummies
+    
+    def    sym  = tree.symbol
+    def    tpe  = tree.tpe
+    def prefix  = tpe.prefix
+    def isEmpty = tree.isEmpty
+
+    def isSymValid = (sym != null) && (sym != NoSymbol)
+    def isModule = sym.isModule || tpe.termSymbol.isModule
+    def isCaseClass = tpe.typeSymbol hasFlag Flags.CASE
+    def isObject = isSymValid && prefix.isStable  // XXX not entire logic
+    
+    def unadorn(t: Tree): Tree = Pattern unadorn t
+    
+    private def isStar(x: Tree) = cond(unadorn(x)) { case Star(_) => true }
+    private def endsStar(xs: List[Tree]) = xs.nonEmpty && isStar(xs.last)
+    
+    def isStarSequence = isSequence && hasStar
+    def isSequence = cond(unadorn(tree)) {
+      case ArrayValue(_, _) => true
+    }
+    def hasStar = cond(unadorn(tree)) {
+      case ArrayValue(_, xs) if endsStar(xs)  => true
+    }
+
+    def setType(tpe: Type): this.type = {
+      tree setType tpe
+      this
+    }
+
+    def equalsCheck =
+      tracing("equalsCheck",
+        if (sym.isValue) singleType(NoPrefix, sym)
+        else tpe.narrow
+      )
+    
+    /** Standard methods **/
+    override def equals(other: Any) = other match {
+      case x: Pattern => this.boundTree == x.boundTree
+      case _          => super.equals(other)
+    }
+    override def hashCode() = boundTree.hashCode()
+    def description = super.toString()
+    def bindingsDescription =
+      if (boundTree.isEmpty) ""
+      else (boundVariables map (_.name)).mkString("", ", ", " @ ")
+
+    final override def toString() = {
+      if (boundVariables.isEmpty) description
+      else "%s%s".format(bindingsDescription, description)
+    }
+    def toTypeString() = "%s <: x <: %s".format(necessaryType, sufficientType)
+  }
+  
+  /*** Extractors ***/
+  
+  object UnapplyParamType {
+    def unapply(x: Tree): Option[Type] = condOpt(unbind(x)) {
+      case UnApply(Apply(fn, _), _) => fn.tpe match {
+        case m: MethodType => m.paramTypes.head
+      }
+    }
+  }
+}
\ No newline at end of file
diff --git a/src/compiler/scala/tools/nsc/matching/TransMatcher.scala b/src/compiler/scala/tools/nsc/matching/TransMatcher.scala
index acea85b..6710a7c 100644
--- a/src/compiler/scala/tools/nsc/matching/TransMatcher.scala
+++ b/src/compiler/scala/tools/nsc/matching/TransMatcher.scala
@@ -1,104 +1,91 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * Copyright 2007 Google Inc. All Rights Reserved.
  * Author: bqe at google.com (Burak Emir)
  */
-// $Id: TransMatcher.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.tools.nsc.matching
+package scala.tools.nsc
+package matching
+
+import symtab.SymbolTable
+import transform.ExplicitOuter
+import java.io.{ StringWriter, PrintWriter }
+import scala.reflect.NameTransformer.decode
+import PartialFunction._
 
 /** Translation of pattern matching
  *
  *  @author Burak Emir
  */
-trait TransMatcher { self: transform.ExplicitOuter with PatternNodes with ParallelMatching with CodeFactory => 
+trait TransMatcher extends ast.TreeDSL {
+  self: ExplicitOuter with ParallelMatching  => 
 
   import global.{ typer => _, _ }
-  import analyzer.Typer;
+  import analyzer.Typer
   import definitions._
-  import symtab.Flags
-
-  var cunit: CompilationUnit = _  // memory leak?
-  var resultType: Type = _
-
-  // cache these
-  final val settings_debug       = settings.debug.value
-  final val settings_squeeze     = settings.Xsqueeze.value == "on"
-
-  // check special case Seq(p1,...,pk,_*) 
-  protected def isRightIgnoring(p: ArrayValue): Boolean = {
-    def isDefaultStar(tree: Tree): Boolean = tree match {
-      case Bind(_, q)                 => isDefaultStar(q)
-      case Star(Ident(nme.WILDCARD))  => true
-      case _                          => false
-    }
+  import CODE._
+  import Debug.{ TRACE, tracing }
 
-    !p.elems.isEmpty && isDefaultStar(p.elems.last)
-  }
+  // cunit is set to the current unit in ExplicitOuter's transformUnit,
+  // and nulled out afterward to avoid leaking.
+  var cunit: CompilationUnit = _
+  
+  def newName(pos: Position, s: String) = cunit.fresh.newName(pos, s)
 
-  /** handles all translation of pattern matching
+  final val settings_squeeze = settings.Xsqueeze.value == "on"
+  
+  /** Handles all translation of pattern matching.
    */
-  def handlePattern(selector: Tree, cases: List[CaseDef], doCheckExhaustive: Boolean, owner: Symbol, handleOuter: Tree => Tree)(implicit typer : Typer): Tree = {
-    DBG("****")
-    DBG("**** initalize, selector = "+selector+" selector.tpe = "+selector.tpe)
-    DBG("****    doCheckExhaustive == "+doCheckExhaustive)
+  def handlePattern(
+    selector: Tree,         // tree being matched upon (called scrutinee after this)
+    cases: List[CaseDef],   // list of cases in the match
+    isChecked: Boolean,     // whether exhaustiveness checking is enabled (disabled with @unchecked)
+    context: MatrixContext): Tree =
+  {
+    import context._
     
-    implicit val theOwner = owner
-    implicit val rep = new RepFactory(handleOuter)
-    val flags = if (doCheckExhaustive) Nil else List(Flags.TRANS_FLAG)
-    
-    def caseIsOk(c: CaseDef) = c match {
-      case CaseDef(_: Apply, _, _)            => true
-      case CaseDef(Ident(nme.WILDCARD), _, _) => true
-      case _                                  => false
+    def matchError(obj: Tree) = atPos(selector.pos)(MATCHERROR(obj))
+    def caseIsOk(c: CaseDef)  = cond(c.pat) { case _: Apply | Ident(nme.WILDCARD) => true }
+    def rootTypes             = selector.tpe.typeArgs
+
+    // this appears to be an attempt at optimizing when all case defs are constructor
+    // patterns, but I don't think it's correct.
+    def doApply(fn: Tree): Boolean =
+      (fn.symbol eq (selector.tpe.decls lookup nme.CONSTRUCTOR)) &&
+      (cases forall caseIsOk)
+      
+    // For x match { ... we start with a single root
+    def singleMatch(): MatrixInit = {
+      val v = copyVar(selector, isChecked)
+      context.MatrixInit(List(v), cases, matchError(v.ident))
     }
-    def doApply(fn: Tree) = (fn.symbol eq selector.tpe.decls.lookup(nme.CONSTRUCTOR)) && (cases forall caseIsOk)
     
-    def processApply(app: Apply): (List[Symbol], List[Tree], Tree) = {
+    // For (x, y, z) match { ... we start with multiple roots, called tpXX.
+    def tupleMatch(app: Apply): MatrixInit = {
       val Apply(fn, args) = app
-      val (tmps, vds) = List.unzip(
-        for ((ti, i) <- args.zipWithIndex) yield {
-          // These type parameter vars were not being set as synthetic.
-          // Temporarily noted on the off chance it was intentional.
-          val v = newVar(ti.pos, cunit.fresh.newName(ti.pos, "tp"), selector.tpe.typeArgs(i), flags)
-          (v, typedValDef(v, ti))
-        }
-      )
-      (tmps, vds, ThrowMatchError(selector.pos, copy.Apply(app, fn, tmps map mkIdent)))
-    }
+      val vs = args zip rootTypes map { case (arg, tpe) => copyVar(arg, isChecked, tpe, "tp") }      
+      def merror = matchError(treeCopy.Apply(app, fn, vs map (_.ident)))
       
-    // sets temporaries, variable declarations, and the fail tree
-    val (tmps, vds, theFailTree) = selector match {
-      case app @ Apply(fn, _) if isTupleType(selector.tpe) && doApply(fn) => processApply(app)
-      case _ => 
-        val root: Symbol      = newVar(selector.pos, selector.tpe, flags)
-        val vdef: Tree        = typer.typed(ValDef(root, selector))
-        val failTree: Tree    = ThrowMatchError(selector.pos, mkIdent(root))
-        (List(root), List(vdef), failTree)
+      context.MatrixInit(vs, cases, merror)
     }
+
+    // sets up top level variables and algorithm input
+    val matrixInit = tracing("matrixInit", selector match {
+      case app @ Apply(fn, _) if isTupleType(selector.tpe) && doApply(fn) => tupleMatch(app)
+      case _                                                              => singleMatch()
+    })
     
-    implicit val fail: Tree = theFailTree
-    val irep                = initRep(tmps, cases, rep)
-    val mch                 = typer.typed(repToTree(irep))
-    var dfatree             = typer.typed(Block(vds, mch))
+    val matrix  = new MatchMatrix(context) { lazy val data = matrixInit }
+    val rep     = matrix.expansion                            // expands casedefs and assigns name
+    val mch     = typer typed rep.toTree                      // executes algorithm, converts tree to DFA
+    val dfatree = typer typed Block(matrixInit.valDefs, mch)  // packages into a code block
 
-    // cannot use squeezedBlock because of side-effects, see t275     
-    for ((cs, bx) <- cases.zipWithIndex)
-      if (!rep.isReached(bx)) cunit.error(cs.body.pos, "unreachable code")
-      
-    dfatree = rep.cleanup(dfatree)
-    resetTrav.traverse(dfatree)
-    dfatree
-  }
-                    
-  object resetTrav extends Traverser {
-    override def traverse(x: Tree): Unit = x match {
-      case (vd: ValDef) => if (vd.symbol hasFlag Flags.SYNTHETIC) {
-        vd.symbol resetFlag Flags.TRANS_FLAG
-        vd.symbol resetFlag Flags.MUTABLE
-      }
-      case _ =>
-        super.traverse(x)
-    }
+    // redundancy check
+    matrix.targets filter (_.isNotReached) foreach (cs => cunit.error(cs.body.pos, "unreachable code"))
+    // optimize performs squeezing and resets any remaining TRANS_FLAGs
+    val res = matrix optimize dfatree
+    TRACE("handlePattern(%s, ...) = %s", selector, res)
+    res
   }
 }
+
diff --git a/src/compiler/scala/tools/nsc/models/Models.scala b/src/compiler/scala/tools/nsc/models/Models.scala
deleted file mode 100644
index 25867ae..0000000
--- a/src/compiler/scala/tools/nsc/models/Models.scala
+++ /dev/null
@@ -1,423 +0,0 @@
-/* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
- * @author  Martin Odersky
- */
-// $Id: Models.scala 16894 2009-01-13 13:09:41Z cunei $
-
-package scala.tools.nsc.models
-
-import scala.tools.nsc.Global
-import scala.tools.nsc.util.{Position,NoPosition}
-
-/** This abstract class ...
- *
- *  @author  Sean McDirmid
- *  @version 1.0
- */
-abstract class Models {
-  val global: Global
-  import global._
-
-  def acceptPrivate = true
-
-  object Kinds extends Enumeration  {
-    type Kind = Value
-    val CONSTRUCTOR = Value("Constructor")
-    val OBJECT      = Value("Object")
-    val CLASS       = Value("Class")
-    val TRAIT       = Value("Trait")
-    val DEF         = Value("Def")
-    val VAL         = Value("Val")
-    val VAR         = Value("Var")
-    val ARG         = Value("Arg")
-    val TPARAM      = Value("Type")
-  }
-  import Kinds._
-
-  def KINDS = List(CLASS, TRAIT, OBJECT, CONSTRUCTOR, TPARAM, VAL, VAR, DEF)
-
-  def labelFor(kind: Kind): String = kind.toString
-
-  def stringsFor(mods: Modifiers) = {
-    var modString: List[String] = Nil
-    if (mods.isPrivate  ) modString = "private"   :: modString
-    if (mods.isProtected) modString = "protected" :: modString
-    if (mods.isOverride ) modString = "override"  :: modString
-    if (mods.isAbstract ) modString = "abstract"  :: modString
-    if (mods.isDeferred ) modString = "abstract"  :: modString
-    if (mods.isCase     ) modString = "case"      :: modString
-    if (mods.isSealed   ) modString = "sealed"    :: modString
-    if (mods.isFinal    ) modString = "final"     :: modString
-    if (mods.isImplicit ) modString = "implicit"  :: modString
-    modString
-  }
-
-  def codeFor(kind: Kind): String = kind match {
-    case CONSTRUCTOR => codeFor(DEF)
-    case _ => labelFor(kind).toLowerCase()
-  }
-
-  def pluralFor(kind: Kind): String = kind match {
-    case CLASS  => "Classes"
-    case _ => labelFor(kind) + "s"
-  }
-
-  def kindOf(tree: Tree) = {
-    val term0 = tree.symbol;
-    if (term0 != NoSymbol) {
-      if (term0.isVariable) VAR
-      else if (term0.isValueParameter) ARG
-      else if (term0.isMethod) {
-        if (term0.nameString.equals("this")) CONSTRUCTOR
-        else DEF
-      }
-      else if (term0.isClass) {
-        if (tree.asInstanceOf[MemberDef].mods.isTrait) TRAIT
-        else CLASS
-      }
-      else if (term0.isModule) OBJECT
-      else if (term0.isValue) VAL
-      else if (term0.isTypeParameter) TPARAM
-      else if (term0.isType) TPARAM
-      else {
-        // Console.err.println("UNRECOGNIZED SYMBOL: " + term0 + " " + name);
-        null
-      }
-    } else {
-      val ddef = tree.asInstanceOf[ValOrDefDef];
-      if (ddef.mods.hasFlag(symtab.Flags.MUTABLE)) VAR;
-      else VAL;
-    }
-  }
-
-  abstract class Model
-
-  // def textFor(tp : AbsTypeDef) : String = tp.toString()
-
-  /**
-   *  @param tree ...
-   *  @return     ...
-   */
-  def textFor(tree: Tree): String = {
-    var ret = ""
-    if (tree.symbol != NoSymbol) tree.symbol.name.toString()
-    if (ret.equals("<init>")) ret = "this"
-    tree match {
-      case cdef: ClassDef =>
-        ret = ret + "[" +
-          (for (val tparam <- cdef.tparams) yield textFor(tparam)) + "]";
-        cdef.mods
-      case vdef: ValOrDefDef =>
-        vdef match {
-          case ddef: DefDef =>
-          ret = ret + "[" +
-            (for (val tparam <- ddef.tparams) yield textFor(tparam)) + "]";
-          for (val vparams <- ddef.vparamss) {
-            ret = ret + "(" +
-              (for (val vparam <- vparams) yield textFor(vparam)) + ")";
-          }
-          case _ =>
-        }
-        ret = ret + " : " + textFor(vdef.tpt)
-/* Martin to Sean: Please check whether this can be dropped or does it need to be adapted? 
-      case atd: AbsTypeDef =>
-        ret = ret + "[" + (for (val tparam <- atd.tparams) yield textFor(tparam)) + "]" +
-                     ((if(atd.hi ne null) " <: " + textFor(atd.hi) else "") +
-                     (if(atd.lo ne null) " >: " + textFor(atd.lo) else ""));
-*/
-      case _ =>
-        ret = ret + tree.toString()
-    }
-    ret
-  }
-
-  def mods1(tree: Tree) = tree match {
-    case mdef: MemberDef => mdef.mods
-    case _ => NoMods
-  }
-
-  abstract class HasTree(val parent: Composite) extends Model with Ordered[HasTree] {
-    var tree : Tree = _
-    def update(tree0: Tree): Boolean = {
-      tree = tree0
-      false
-    }
-    def replacedBy(tree0: Tree): Boolean = true
-    def text: String = textFor(tree)
-    var mods0 = NoMods
-
-    def mods = if (mods0 != NoMods) mods0 else mods1(tree)
-
-    override def toString(): String = tree.toString()
-
-    def compare(that: HasTree): Int = {
-      val idx = KINDS.indexOf(kind)
-      val jdx = KINDS.indexOf(that.kind)
-      if (idx != jdx) return idx - jdx
-      val result = tree.symbol.nameString.compare(that.tree.symbol.nameString)
-      if (result != 0) result
-      else toString().compare(that.toString())
-    }
-    def compare [b >: HasTree <% Ordered[b]](that: b): Int = {
-      if (that.isInstanceOf[HasTree])
-        compare(that.asInstanceOf[HasTree])
-      else -1
-    }
-
-    def kind = kindOf(tree)
-
-    //override def    add(from: Composite, model: HasTree): Unit = { parent.add(from, model) }
-    //override def remove(from: Composite, model: HasTree): Unit = { parent.remove(from, model) }
-  }
-
-  class ImportMod(parent0: Composite) extends HasTree(parent0) {
-    def treex = tree.asInstanceOf[Import]
-
-    override def replacedBy(tree0: Tree): Boolean =
-      if (super.replacedBy(tree0) && tree0.isInstanceOf[Import]) {
-        val tree1 = tree0.asInstanceOf[Import]
-        tree1.tpe == treex.tpe
-      } else
-        false
-  }
-
-  class PackageMod(parent0: Composite) extends HasTree(parent0) {
-    def treex = tree.asInstanceOf[PackageDef]
-  }
-
-  trait Composite extends Model {
-    import scala.collection.mutable._
-
-    class Members extends HashSet[HasTree]
-    // val members = new Members
-    object members extends Members
-
-    def isMember(tree: Tree): Boolean = tree.isInstanceOf[Import] // imports welcome anywhere.
-
-    def member(tree: Tree, members: List[Tree]): Tree = tree
-
-    def update0(members1: List[Tree]): Boolean = {
-      // Console.err.println("update0 " + this + " " + members1)
-      if (members1.length == 1 && members1.head.isInstanceOf[PackageDef])
-        return update0(members1.head.asInstanceOf[PackageDef].stats)
-
-      val marked = new HashSet[HasTree]
-      var updated = false
-      for (val mmbr1 <- members1) if (mmbr1.isInstanceOf[PackageDef]) {
-        Console.err.println("PACKAGE: " + mmbr1.symbol + " " + members1.length)
-      } else if (isMember(mmbr1)) {
-        val mmbr2 = member(mmbr1, members1)
-        if (mmbr2 ne null) {
-          var found = false
-          for (val mmbr <- members) if (!found && mmbr.replacedBy(mmbr2)) {
-            //Console.err.println("REPLACE: " + mmbr + " with " + mmbr2)
-            mmbr.mods0 = mods1(mmbr1)
-            found = true
-            updated = mmbr.update(mmbr2) || updated
-            marked += mmbr
-          }
-          if (!found) {
-            updated = true
-            val add = modelFor(mmbr2, this)
-            add.update(mmbr2)
-            add.mods0 = mods1(mmbr1) & 
-              ~symtab.Flags.ACCESSOR & ~symtab.Flags.SYNTHETIC
-            val sz = members.size
-            members += (add)
-            assert(members.size == sz + 1)
-            marked += add
-          }
-        }
-        // Console.err.println("update1 " + this + " " + members + " " + marked)
-      }
-      val sz = members.size
-      members.intersect(marked)
-      updated = updated || sz < members.size
-      // check if anything was removed!
-      updated
-    }
-  }
-  abstract class MemberMod(parent0: Composite) extends HasTree(parent0) {
-    def treex = tree.asInstanceOf[MemberDef]
-
-    def name: Name = treex.name
-
-    override def replacedBy(tree0: Tree): Boolean =
-      if (super.replacedBy(tree0) && tree0.isInstanceOf[MemberDef]) {
-        val tree1 = tree0.asInstanceOf[MemberDef]
-        treex.toString().equals(tree1.toString())
-      } else false
-
-    override def update(tree0: Tree): Boolean = {
-      val updated = (tree eq null) || (treex.mods != tree0.asInstanceOf[MemberDef].mods)
-      super.update(tree0) || updated;
-    }
-  }
-
-  abstract class MemberComposite(parent0: Composite) extends MemberMod(parent0) with Composite
-
-  trait HasClassObjects extends Composite {
-    override def isMember(tree: Tree): Boolean =
-      super.isMember(tree) || tree.isInstanceOf[ImplDef]
-  }
-
-  abstract class ValOrDefMod(parent0: Composite) extends MemberComposite(parent0) with HasClassObjects {
-    def treey = tree.asInstanceOf[ValOrDefDef]
-    override def replacedBy(tree0: Tree): Boolean =
-      super.replacedBy(tree0) && tree0.isInstanceOf[ValOrDefDef]
-
-    override def update(tree0: Tree): Boolean = {
-      val tree1 = tree0.asInstanceOf[ValOrDefDef]
-      val updated = (tree eq null) || treex.tpe != tree1.tpe
-      update0(flatten(tree1.rhs, (tree2: Tree) => isMember(tree2)))
-      super.update(tree0) || updated
-    }
-  }
-
-  class ValMod(parent0: Composite) extends ValOrDefMod(parent0) {
-    def treez = tree.asInstanceOf[ValDef]
-    override def replacedBy(tree0: Tree): Boolean =
-      super.replacedBy(tree0) && tree0.isInstanceOf[ValDef]
-  }
-
-  class DefMod(parent0: Composite) extends ValOrDefMod(parent0) {
-    def treez = tree.asInstanceOf[DefDef]
-
-    override def replacedBy(tree0: Tree) : Boolean =
-      if (super.replacedBy(tree0) && tree0.isInstanceOf[DefDef]) {
-        val tree1 = tree0.asInstanceOf[DefDef]
-        if (tree1.vparamss.length == treez.vparamss.length) {
-          val tpz = for (val vd <- treez.vparamss) yield for (val xd <- vd) yield xd.tpe;
-          val tp1 = for (val vd <- tree1.vparamss) yield for (val xd <- vd) yield xd.tpe;
-          tpz == tp1
-        } else false
-      } else false
-  }
-
-  abstract class ImplMod(parent0: Composite)
-  extends MemberComposite(parent0) with HasClassObjects {
-    def treey = tree.asInstanceOf[ImplDef]
-    override def replacedBy(tree0: Tree): Boolean =
-      super.replacedBy(tree0) && tree0.isInstanceOf[ImplDef]
-    override def isMember(tree: Tree): Boolean = (super.isMember(tree) ||
-      (tree.isInstanceOf[ValOrDefDef] &&
-        (acceptPrivate || !tree.asInstanceOf[ValOrDefDef].mods.isPrivate)
-       /* && !tree.asInstanceOf[ValOrDefDef].mods.isPrivate */
-       /* && !tree.asInstanceOf[ValOrDefDef].mods.isAccessor */) ||
-      treeInfo.isAliasTypeDef(tree))
-
-    override def member(tree: Tree, members: List[Tree]): Tree = {
-      val tree0 = if (tree.isInstanceOf[DefDef]) {
-        val ddef = tree.asInstanceOf[DefDef]
-        ddef.mods
-        if (ddef.mods.isAccessor && (ddef.symbol ne null)) {
-          val sym0 = ddef.symbol;
-          if (sym0.isSetter) return null;
-          assert(sym0.isGetter);
-          val sym = sym0.accessed
-          val ret = if (sym == NoSymbol) {
-            val sym = analyzer.underlying(sym0)
-            //val name = nme.getterToSetter(sym0.name)
-            //val setter = sym0.owner.info.decl(name);
-            val isVar = sym.isVariable;
-            val mods = (ddef.mods | 
-              (if (isVar) symtab.Flags.MUTABLE else 0) | symtab.Flags.DEFERRED) &
-                ~symtab.Flags.ACCESSOR & ~symtab.Flags.SYNTHETIC
-            val tree = 
-              ValDef(mods, ddef.name, ddef.tpt, ddef.rhs).setPos(ddef.pos).setSymbol(sym);
-            tree :: Nil;
-          } else for (val member <- members; member.symbol == sym) yield member
-          if (ret.isEmpty) null
-          else ret.head
-        } else tree
-      } else super.member(tree, members)
-
-      def sym = tree0.symbol
-      if ((tree0 eq null) || tree0.pos == NoPosition) null
-      else if (!acceptPrivate &&
-               tree0.isInstanceOf[ValOrDefDef] &&
-               tree.asInstanceOf[ValOrDefDef].mods.isPrivate) null
-      else tree0
-    }
-
-    def children(tree0: Tree): List[Tree] =
-      tree0.asInstanceOf[ImplDef].impl.body
-
-    override def update(tree0: Tree): Boolean = {
-      var updated = update0(children(tree0))
-      super.update(tree0) || updated
-    }
-  }
-
-  class ClassMod(parent0: Composite) extends ImplMod(parent0) {
-    def treez = tree.asInstanceOf[ClassDef]
-    override def replacedBy(tree0: Tree): Boolean =
-      super.replacedBy(tree0) && tree0.isInstanceOf[ClassDef]
-  }
-
-  class ObjectMod(parent0: Composite) extends ImplMod(parent0) {
-    def treez = tree.asInstanceOf[ModuleDef]
-    override def replacedBy(tree0: Tree): Boolean =
-      super.replacedBy(tree0) && tree0.isInstanceOf[ModuleDef]
-  }
-  class TypeMod(parent0: Composite) extends MemberMod(parent0) {
-    def treey = tree.asInstanceOf[TypeDef];
-    override def replacedBy(tree0 : Tree) : Boolean = (super.replacedBy(tree0) && tree0.isInstanceOf[TypeDef]);
-  }
-  def SourceMod(original: CompilationUnit) = new SourceMod(original)
-
-  class SourceMod(val original: CompilationUnit) extends Composite with HasClassObjects {
-    update(original)
-    //var listener : Listener = null;
-    def update(unit: CompilationUnit) = unit.body match {
-      case pdef: PackageDef => try {
-        update0(pdef.stats)
-      } catch {
-        case e: Error => members.clear; update0(pdef.stats)
-      }
-      case _ =>
-    }
-
-    override def isMember(tree: Tree): Boolean =
-      super.isMember(tree) || tree.isInstanceOf[Import]
-  }
-
-  def flatten0(exprs: List[Tree], filter: (Tree) => Boolean): List[Tree] =
-    for (val expr <- exprs; val t: Tree <- flatten(expr,filter)) yield t
-
-  def flatten(expr: Tree, filter: (Tree) => Boolean): List[Tree] =
-    if (filter(expr)) expr :: Nil; else expr match {
-      case Block(stats, last) =>
-        flatten0(stats, filter) ::: flatten(last, filter)
-      case If(cond, thenp, elsep) =>
-        flatten(cond,filter) ::: flatten(thenp,filter) ::: flatten(elsep,filter);
-      case Assign(lhs, rhs) =>
-        flatten(rhs, filter)
-      case CaseDef(pat, guard, body) =>
-        flatten(body, filter)
-      case Return(expr0) =>
-        flatten(expr0, filter)
-      case Throw(expr0) =>
-        flatten(expr0,filter)
-      case Try(block, catches, finalizer) =>
-        flatten(block, filter) ::: flatten(finalizer, filter) ::: flatten0(catches, filter)
-      case Match(selector, cases) =>
-        flatten(selector, filter) ::: flatten0(cases, filter)
-      case Apply(fun, args) =>
-        flatten(fun, filter) ::: flatten0(args, filter)
-      case TypeApply(fun, args) =>
-        flatten(fun, filter) ::: flatten0(args, filter)
-      case _ =>
-        Nil
-    }
-
-  def modelFor(tree: Tree, parent: Composite): HasTree = tree match {
-    case _: ValDef       => new ValMod(parent)
-    case _: DefDef       => new DefMod(parent)
-    case _: ClassDef     => new ClassMod(parent)
-    case _: ModuleDef    => new ObjectMod(parent)
-    case _: TypeDef      => new TypeMod(parent)
-    case _: Import       => new ImportMod(parent)
-  }
-
-}
diff --git a/src/compiler/scala/tools/nsc/models/SemanticTokens.scala b/src/compiler/scala/tools/nsc/models/SemanticTokens.scala
deleted file mode 100644
index 4722396..0000000
--- a/src/compiler/scala/tools/nsc/models/SemanticTokens.scala
+++ /dev/null
@@ -1,718 +0,0 @@
-/* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
- * @author  Martin Odersky
- */
-// $Id: SemanticTokens.scala 16894 2009-01-13 13:09:41Z cunei $
-
-package scala.tools.nsc.models
-
-import java.lang.Character.isJavaIdentifierPart
-import java.lang.Thread
-
-import scala.collection.mutable.{HashMap, HashSet}
-import scala.tools.nsc.Global
-import scala.tools.nsc.symtab.{Flags, Names}
-import scala.tools.nsc.symtab.Flags.DEFERRED
-import scala.tools.nsc.util.{BatchSourceFile, NameTransformer, NoPosition, Position, SourceFile}
-
-class SemanticTokens(val compiler: Global) {   
-  import compiler._  
-  object walker extends symtab.SymbolWalker {
-    lazy val global : compiler.type = compiler
-  }
-  
-  abstract class Kind {}
-  object OBJECT extends Kind
-  object CLASS  extends Kind
-  object TRAIT  extends Kind
-  object DEF    extends Kind
-  object VAL    extends Kind
-  object VAR    extends Kind
-  object ARG    extends Kind
-  object TPARAM extends Kind
-
-  type AnyClass = Class[_]
-
-  // static constants here
-
-  abstract class Token {
-    def length: Int
-    def prev: HasNext
-    def next: HasPrev
-  }
-
-  def eatKeyword(source: BatchSourceFile, pos: Int, keywords: List[String]) : Int = {
-    if (keywords.isEmpty)
-      pos
-    else if (pos == source.length)
-      -1
-    else if (source.beginsWith(pos, " "))
-      eatKeywords(source, pos + 1)
-    else if (source.beginsWith(pos, keywords.head + " "))
-      eatKeywords(source, pos + keywords.head.length + 1)
-    else
-      eatKeyword(source, pos, keywords.tail)
-  }
-
-  def eatKeywords(source: BatchSourceFile, pos: Int): Int = {
-    val keywords =
-      "package" :: "val" :: "var" :: "def" :: "class" :: "trait" :: "override" :: "case" ::
-      "object" :: "sealed" :: "private" :: "protected" :: Nil
-    if (pos != -1) eatKeyword(source, pos, keywords)
-    else pos
-  }
-
-  trait HasNext extends Token {
-    var next0: HasPrev = _
-    def next = next0
-  }
-
-  trait HasPrev extends Token {
-    var prev0: HasNext = _
-    def prev = prev0
-  }
-
-  abstract class Actual extends HasNext with HasPrev {
-    def convertToGap: (Int, Actual) = {
-      val nextGap = next.isInstanceOf[Gap]
-      val prevGap = prev.isInstanceOf[Gap]
-
-      if (prevGap) {
-        val ret = prev.length
-        val gap = prev.asInstanceOf[Gap]
-        gap.setLength(gap.length + length)
-        if (nextGap) {
-          gap.setLength(gap.length + next.length)
-          gap.next0 = next.next
-          next.next.prev0 = gap
-        } else {
-          gap.next0 = next
-          next.prev0 = gap
-        }
-        (ret, gap)
-      }
-      else if (nextGap) {
-        val gap = next.asInstanceOf[Gap]
-        gap.setLength(gap.length + length)
-        gap.prev0 = prev
-        prev.next0 = gap
-        (0, gap)
-      }
-      else {
-        prev.next0 = next
-        next.prev0 = prev
-        val gap = new Gap(prev)
-        gap.setLength(length)
-        (0, gap)
-      }
-
-    }
-    def insert(prev1: HasNext) {
-      next0 = prev1.next
-      prev0 = prev1
-      prev0.next0 = this
-      next0.prev0 = this
-    }
-
-  } // Actual
-
-  final class Gap extends Actual {
-    def this(prev1: HasNext) = {
-      this()
-      insert(prev1)
-    }
-    override def toString() = "gap-" + length
-
-    var length0: Int = -1
-    def length: Int = length0
-    def setLength(length1: Int) = length0 = length1
-
-    // already gap
-    override def convertToGap: (Int,Actual) = (0, this)
-  }
-
-  def Process(unit: CompilationUnit) = new Process(unit)
-  class Process(val unit: CompilationUnit) {
-    private var doLog = true
-    def source = unit.source
-
-    def dbg(tree : Tree) = {
-      def treePos : Position = if (tree ne null) tree.pos else NoPosition;
-      (
-        "TREE=" + tree +
-          (if (tree ne null) (" CLASS=" + tree.getClass()) else "") +
-            " SYM=" + tree.symbol +
-              " POS=" +
-                treePos.dbgString
-    )}
-
-    val symbols = new HashMap[Symbol, Info]
-
-    class Info(val symbol: Symbol) {
-      var defined : Def = _
-      val uses = new HashSet[Use]
-      symbols.update(symbol, this)
-    }
-
-    def info(symbol: Symbol): Info =
-      if (symbols.contains(symbol)) symbols(symbol)
-      else new Info(symbol)
-
-    abstract class Semantic(val symbol: Symbol) extends Actual {
-      val name = NameTransformer.decode(symbol.name.toString).trim()
-      assert(symbol != NoSymbol)
-      def myOuter = Process.this
-
-      def tpe: Type = symbol.tpe
-
-      def length = name.length()
-      def info: Info = if (symbols.contains(symbol)) symbols(symbol) else new Info(symbol)
-
-      def kind = {
-        val term0 = symbol
-        if (false) null
-        else if (term0.isVariable)       VAR
-        else if (term0.isValueParameter) ARG
-        else if (term0.isMethod)         DEF
-        else if (term0.isClass)          CLASS
-        else if (term0.isModule)         OBJECT
-        else if (term0.isValue)          VAL
-        else if (term0.isTypeParameter)  TPARAM
-        else if (term0.isType         )  TPARAM
-        else {
-          // Console.err.println("UNRECOGNIZED SYMBOL: " + term0 + " " + name);
-          null
-        }
-      }
-    }
-
-    class Def(symbol0: Symbol) extends Semantic(symbol0) {
-      info.defined = this
-      override def toString() = "def-" + name + "-" + symbol.getClass()
-    }
-    class Use(symbol0: Symbol, tpe0: Type) extends Semantic(symbol0) {
-      info.uses += this
-
-      override def tpe : Type = if (tpe0 ne null) tpe0 else super.tpe;
-      override def toString() = "use-" + name + "-" + symbol.getClass();
-    }
-    val list = new TokenList
-
-    //build(unit.body)
-    val map = new scala.collection.jcl.LinkedHashMap[Int,Symbol]
-    map.clear // populate the map.
-      class visitor extends walker.Visitor {
-      def contains(pos : Position) = map.contains(pos.offset.get)
-      def apply(pos : Position) = map(pos.offset.get)
-      def update(pos : Position, sym : Symbol) : Unit = if (pos.offset.isDefined) {
-        val offset = pos.offset.get
-        map(offset) = sym
-        val isDef = pos.offset == sym.pos.offset
-        list.put(offset, (if (isDef) new Def(sym) else new Use(sym, NoType)));
-      }
-    }
-    walker.walk(unit.body, new visitor)(offset => unit.source.identifier(offset, compiler))
-
-
-    // ok start building....
-    def build[T <: Tree](trees : List[T]) : Unit =
-      for (val tree : T <- trees) build(tree)
-
-    def build(tree0: Tree) : Unit = try {
-      /* if (tree0.pos != NoPosition) */ tree0 match {
-      case tree: ImplDef =>
-        val pos = eatKeywords(unit.source.asInstanceOf[BatchSourceFile], tree.pos.offset.get)
-        if (pos == -1) {
-
-        } else buildDef(tree.symbol, eatKeywords(unit.source.asInstanceOf[BatchSourceFile], tree.pos.offset.get));
-        tree match {
-          case cdef: ClassDef => build(cdef.tparams)
-          case _ => ;
-        }
-        build(tree.impl.parents)
-        build(tree.impl.body)
-      case tree: ValOrDefDef =>
-        if (!tree.symbol.hasFlag(Flags.ACCESSOR) || tree.symbol.hasFlag(DEFERRED)) {
-          // MO: I added !tree.symbol.hasFlag(DEFERRED) in a refactoring where
-          // getters now can be abstract whereas before they could not.
-          // Adding the condition thus keeps the old behavior. 
-          // todo: review whether this is correct, or whether abstract getters should be included.
-          {
-            val pos : Int = if (tree.name.toString().equals("<init>")) -1 else 
-              eatKeywords(unit.source.asInstanceOf[BatchSourceFile], tree.pos.offset.get);
-          if (false) Console.err.println("VALDEF: tree=" + tree + " sym=" + tree.symbol + " pos0=" + 
-            tree.symbol.pos + " alias=" + tree.symbol.alias + " pos1=" +
-            pos + " pos2=" + tree.pos.dbgString + " " + tree.symbol.hasFlag(Flags.SYNTHETIC));
-
-          if (pos != -1 && !tree.hasFlag(Flags.SYNTHETIC)) 
-            buildDef(tree.symbol, pos);
-              }
-                
-              if (tree.isInstanceOf[DefDef]) {
-                val ddef = tree.asInstanceOf[DefDef];
-                build(ddef.tparams);
-                
-                for (val l0 <- ddef.vparamss; val arg <- l0) {
-                  val pos0 : Int = if (!unit.source.beginsWith(arg.pos.offset.get, "val ")) arg.pos.offset.get; 
-                                             else unit.source.skipWhitespace(arg.pos.offset.get + ("val ").length());
-                  buildDef(arg.symbol, pos0);
-                  build(arg.tpt);
-                }
-              }
-              try {
-          //TPT=scala.Iterator[DocGenerator.this.compiler0.CompilationUnit] 260 class scala.tools.nsc.ast.Trees$TypeTree scala.Iterator[DocGenerator.this.compiler0.CompilationUnit] class scala.tools.nsc.symtab.Types$$anon$5
-          if ((tree.tpt eq null) || (tree.tpt.tpe eq null)) {
-            //Console.err.println("BAD: " + tree.tpt + " in " + tree); 
-          } else {
-            //Console.err.println("TPT=" + tree.tpt + " " + tree.tpt.pos + " " + tree.tpt.getClass() + " " + tree.tpt.tpe + " " + tree.tpt.tpe.getClass() + " " + tree.tpt.tpe.getClass().getSuperclass());
-                  build(tree.tpt);
-          }
-              } catch {
-                case e: Error =>
-                  Console.err.println("VALDEF: " + tree + " " + tree.tpt + " " + tree.pos + " " + tree.tpt.pos);
-                  throw e;
-              }
-        //Console.err.println("RHS: " + tree.rhs + " " + tree.rhs.getClass() + " " + tree.rhs.getClass().getSuperclass());
-              build(tree.rhs);
-            }
-      case tree: PackageDef =>
-        //Console.err.println("PACKAGE: " + tree.name);
-        if (false) {
-          val pos = eatKeywords(unit.source.asInstanceOf[BatchSourceFile], tree.pos.offset.getOrElse(-1))
-          if (pos != -1)
-            buildDef(tree.symbol, pos)
-        }
-        build(tree.stats)
-      case tree: Function =>
-        for (val arg <- tree.vparams) if (arg.pos != NoPosition) {
-          val name = arg.name.toString().trim()
-          val pos: Int =
-            if (unit.source.beginsWith(arg.pos.offset.getOrElse(-1), "val "))
-              unit.source.skipWhitespace(arg.pos.offset.getOrElse(-1) + ("val ").length())
-            else if (unit.source.asInstanceOf[BatchSourceFile].content(arg.pos.offset.get) == ':') {
-              var posx : Int = arg.pos.offset.get
-              while (unit.source.asInstanceOf[BatchSourceFile].content(posx - 1).isWhitespace) posx = posx - 1
-              posx - name.length()
-            } else arg.pos.offset.get
-          buildDef(arg.symbol, pos)
-          build(arg.tpt)
-        }
-        build(tree.body)
-      case tree : TypeTree =>
-        val treex = tree
-        val tree1 = if (tree.original ne null) tree.original else tree
-        def classes(clazz: AnyClass): List[AnyClass] =
-          if (clazz eq null) Nil
-          else clazz :: classes(clazz.getSuperclass())
-        if (tree.original eq null) {
-          if (false) Console.err.println("NO_ORIGINAL: " + tree + " " + tree.tpe + " " + classes(tree.tpe.getClass()));
-        }
-        if (tree.tpe ne null) buildT(tree1, tree.tpe);
-        def buildT( tree : Tree, tpe : Type) : Unit = if (tree.pos != NoPosition) tpe match {
-          case tpe0 : TypeRef => tree match {
-            case apt : AppliedTypeTree => 
-              buildUse(tpe.typeSymbol, apt.tpt.pos.offset.getOrElse(-1), tpe0);
-          //Console.err.println("APT: " + treex + " vs. " + treex.original);
-          //Console.err.println("APT: " + treex.pos + " vs. " + treex.original.pos + " " + unit.source.dbg(treex.original.pos));
-              //Console.err.println("APT: " + apt.tpt + " sym0=" + apt.tpt.symbol + " sym1=" + tpe0.sym + " apt.args=" + apt.args + " tpe0.args=" + tpe0.args);
-    
-              buildTs (apt.args, tpe0.args);
-            case ident : Ident => buildUse(tpe0.sym, ident.pos.offset.getOrElse(-1), tpe0);
-            case select : Select =>
-          if (select.symbol == NoSymbol) 
-              try {
-                // build(select);
-            buildUse(tpe0.typeSymbol, selectPos(select), tpe0);
-            //Console.err.println("QUALIFIER: " + select.qualifier + " " + unit.source.dbg(select.qualifier.pos) + " " + tpe0.prefix + " " + tpe0.prefix.getClass() + " " + tpe0.prefix.getClass().getSuperclass() +" " + tpe0.prefix.widen + " " + tpe0.prefix.toLongString);            
-                        buildT(select.qualifier, tpe0.prefix);
-          } catch {
-                        case e : Error => 
-                          Console.err.println("BUILD_SELECT: " + select + " @ " + tpe0 + " " + (select.pos).dbgString);
-                          throw e;
-              }
-            case tpt : TypeTree => 
-          if (tpt.symbol ne null) {
-            Console.err.println("SYM0 " + tpt.symbol + " " + (tpt.pos).dbgString);
-            buildUse(tpt.symbol, tpt.pos.offset.getOrElse(-1), tpe0);
-          } else if (tpe0.typeSymbol ne null) {
-            //Console.err.println("TYPE_SYM1 " + tpe0.symbol + " " + unit.source.dbg(tpt.pos));
-            buildUse(tpe0.typeSymbol, tpt.pos.offset.getOrElse(-1), tpe0);
-          } else {
-            Console.err.println("UNKNOWN TPT0: " + (tpt.pos).dbgString + " tpt=" + tpt + " " + tpt.symbol + " tpe0="+ tpe0 + " " + tpe0.typeSymbol + " tpe0.args=" + tpe0.args);
-          }
-            case sft : SelectFromTypeTree => 
-              build(sft.qualifier); // XXX: broken
-                if (false) Console.err.println("SFTT: " + sft + " sym=" + sft.symbol + " selector=" + sft.selector + " qual=" + sft.qualifier + " qual.sym=" +
-                          sft.qualifier.symbol + 
-                          " qual.pos=" + (sft.qualifier.pos).dbgString + " symbol=" + sft.symbol + " type=" + tpe0 + 
-                          " type.sym=" + tpe0.typeSymbol);
-            case _ => Console.err.println("UNKNOWN TPT2: " + tree + " vs. " + tpe0 + " " + tree.getClass() + " " + (tree.pos).dbgString);
-          }
-          case tpe0 : MethodType => tree match {
-            case tpt: TypeTree =>
-              if (tpt.original ne null) buildT(tpt.original, tpe);
-              else {
-                        Console.err.println("UNKNOWN TPT3: " + tree + " vs. " + tpe0 + " " + (tree.pos).dbgString);
-              }
-            case ident  : Ident  => buildT(ident,  tpe0.resultType);
-            case select : Select => buildT(select, tpe0.resultType);
-            case _ => Console.err.println("UNKNOWN TPE: " + tree + " vs. " + tpe0 + " " + tree.getClass());
-          }
-          case tpe0 : RefinedType => tree match {
-              case cpt : CompoundTypeTree => 
-                  buildTs(cpt.templ.parents, tpe0.parents);
-        
-              case _ : TypeTree => 
-                // Console.err.println("UNKNOWN TPE13: " + dbg(tree) + " tpe0=" + tpe0 + " " + tpe0.parents);
-              case _ =>
-                  if (false) Console.err.println("UNKNOWN TPE5: " + dbg(tree) + " tpe0=" + tpe0 + " " + tpe0.parents);
-          }
-          case tpe0 : ThisType => tree match {
-            case stt : SingletonTypeTree => stt.ref match {
-                case ths : This => build(ths);
-
-          case _ => Console.err.println("UNKNOWN TPE11: " + tpe0 + " " + stt + " " + stt.ref + " " + stt.ref.getClass() + " " + (tree.pos).dbgString);
-        }
-        case tt : This => 
-        case _ : Ident =>
-        case _ : Select =>
-        case tt : TypeTree => 
-          if (false) Console.err.println("UNKNOWN TPE12: " + tpe0 + " " + tree + " " + tree.getClass() + " " + (tree.pos).dbgString);
-        case _ => 
-          if (false) Console.err.println("UNKNOWN TPE10: " + tpe0 + " " + tree + " " + tree.getClass() + " " + (tree.pos).dbgString);
-          }
-        case tpe0 : SingleType => tree match {
-          case ident  : Ident  => buildUse(tpe0.sym, ident.pos.offset.getOrElse(-1), tpe0);
-          case select : Select =>
-            buildUse(tpe0.termSymbol, selectPos(select), tpe0);
-            //Console.err.println("QUALIFIER-0: " + select.qualifier + " " + unit.source.dbg(select.qualifier.pos) + " " + tpe0.prefix + " " + tpe0.prefix.getClass() + " " + tpe0.prefix.getClass().getSuperclass() +" " + tpe0.prefix.widen + " " + tpe0.prefix.toLongString);            
-            buildT(select.qualifier, tpe0.prefix);
-
-          case _ =>
-            if (false) Console.err.println("UNKNOWN TPE8: " + tree + " " + (tree.pos).dbgString + " TPE=" + tpe0 + " PRE=" + tpe0.pre + " SYM=" + tpe0.sym);
-              
-        }
-      case ctype : ConstantType =>
-          case ErrorType => 
-          case _ => {
-        if (false) Console.err.println("UNKNOWN TPE4: " + tree + " " + tpe + " " + tpe.getClass() + " " + (tree.pos).dbgString);
-          }
-        };
-    def buildTs(trees : List[Tree], types : List[Type]): Unit = if (!trees.isEmpty && !types.isEmpty) {
-              buildT (trees.head, types.head);
-              buildTs(trees.tail, types.tail);
-        } else if (trees.isEmpty != types.isEmpty) {
-             if (false && doLog) {
-        Console.println("" + treex + " vs. " + treex.original);
-        if (treex.original ne null)
-          Console.println("" + treex.tpe + " vs. " + treex.original.tpe);
-               logError("Tree vs. Type mismatch: " + trees + " " + types + " " + (tree.pos).dbgString, null);
-        doLog = false;
-      }
-    };
-/*
-  Martin to Sean: I don't understand why AbsTypeDef is different from AliasTypeDef.
-  Why is the order reversed? Why two buildDefs for tree.symbol vs one for AliasTypeDef?
-      case tree: AbsTypeDef =>
-        //Console.err.println("ABS: " + tree.symbol + " " + unit.source.dbg(tree.namePos) + " " + tree.pos.dbgString);
-        buildDef(tree.symbol, tree.namePos)
-        buildDef(tree.symbol, tree.pos.offset.getOrElse(-1))
-        build(tree.tparams); //@M
-        build(tree.lo)
-        build(tree.hi)
-*/
-      case tree: Bind =>
-        buildDef(tree.symbol, tree.pos.offset.getOrElse(-1))
-        build(tree.body)
-      case tree: Ident =>
-        buildUse(tree.symbol, tree.pos.offset.getOrElse(-1), tree.tpe)
-      case tree: Select =>
-        try {
-          build(tree.qualifier)
-            } catch {
-              case e : Error => Console.err.println("SELECTQ: " + tree + " " + tree.qualifier + " " + (tree.qualifier.pos).dbgString); throw e;
-            }
-            try {
-              if (tree.pos.offset.isDefined && tree.pos.offset.get >= unit.source.length) {
-                if (false) Console.err.println("BAD_SELECT_QUALIFIER " + tree + " @ " + (tree.pos).dbgString);
-          
-        } else {
-          //Console.err.println("SELECT-0: " + tree.symbol + " " + tree.pos.dbgString + " " + (tree.pos - selectPos(tree)));
-                    buildUse(tree.symbol, selectPos(tree), tree.tpe);
-              }
-            } catch {
-              case e : Error => Console.err.println("SELECTU: " + tree + " " + tree.symbol + " " + tree.pos.dbgString); throw e;
-            }
-    case tree: TypeApply =>
-      //Console.err.println("TYPE_APPLY: " + tree + " " + tree.pos.dbgString);    
-      if (!tree.args.isEmpty) {
-        //Console.err.println("ARGS: " + unit.source.dbg(tree.args0.head.pos));    
-      }
-      build(tree.fun)
-      build(tree.args)
-    case tree: Apply =>
-
-      build(tree.fun)
-      build(tree.args)
-      case tree: GenericApply =>
-
-        build(tree.fun)
-        build(tree.args)
-      case tree: Typed =>
-        build(tree.expr)
-        build(tree.tpt)
-      case tree: Block =>
-        if (false) {
-          if (!tree.stats.isEmpty)
-            Console.err.println("BLOCKS: " + tree.stats.head + " " + tree.stats.head.getClass());
-          Console.err.println("BLOCKE: " + tree.expr + " " + tree.expr.getClass())
-        }
-        build(tree.stats)
-        build(tree.expr)
-      case tree: CaseDef =>
-        build(tree.pat)
-        build(tree.guard)
-        build(tree.body)
-      case tree : Sequence   => build(tree.trees);
-      case tree : Assign     => build(tree.lhs); build(tree.rhs);
-      case tree : If         => build(tree.cond); build(tree.thenp); build(tree.elsep);
-      case tree : New        => 
-        //Console.err.println("NEW: " + tree.tpt + " " + tree.tpt.getClass());
-      build(tree.tpt);
-      case tree : Match      => build(tree.selector); build(tree.cases);
-      case tree : Return     => build(tree.expr);
-      case tree : LabelDef   => build(tree.rhs);
-      case tree : Throw      => build(tree.expr);
-      case tree : Try        => build(tree.block); build(tree.catches); build(tree.finalizer);
-      case tree : Alternative => build(tree.trees);
-      case tree : This    => 
-
-        if (tree.symbol ne null) buildUse(tree.symbol, tree.pos.offset.getOrElse(-1), tree.tpe);
-        //Thread.dumpStack();
-      case tree : TypeDef => 
-        //Console.err.println("ALIAS: " + tree);
-        build(tree.rhs); build(tree.tparams); buildDef(tree.symbol, tree.pos.offset.getOrElse(-1));
-      case tree : DocDef     => build(tree.definition);
-      case tree: Import => build(tree.expr)
-      case tree: AppliedTypeTree => ;
-      case tree: Annotated => ;
-      case tree: SingletonTypeTree => ;
-      case tree: Super   => ;
-      case tree: Literal => ;
-      case EmptyTree => ;
-      case _ => ;
-        Console.err.println("BAIL: " + (tree0.pos) + " " + tree0 + " " + tree0.getClass());
-    }
-  } catch {
-    case t: Throwable =>
-      logError("Error occured at " + (tree0.pos), t)
-  }
-
-  def buildUse(term: Symbol, pos: Int, tpe: Type) = buildSym(term, pos, false, tpe)
-  def buildDef(term: Symbol, pos: Int) = buildSym(term, pos, true, null)
-
-  def buildSym(term: Symbol, pos: Int, isDef: Boolean, tpe: Type): Unit =
-    if (term.hasFlag(Flags.ACCESSOR))
-      buildSym(analyzer.underlying(term), pos, isDef, tpe)
-    else if (pos == -1) {
-      //Console.err.println("NOPOS: " + term)
-      //Thread.dumpStack()
-    }
-    else if (term != NoSymbol) {
-      val name = NameTransformer.decode(term.name.toString).trim()
-      val buf = unit.source.asInstanceOf[BatchSourceFile].content
-      val cs = name.toChars
-      var idx = 0
-      if (cs.length + pos > buf.length) return
-      else while (idx < cs.length) {
-        if (buf(pos + idx) != cs(idx)) {
-          //Console.err.println("MISMATCH: " + name + "[" + idx + "] " + unit.source.dbg(pos));
-          //Thread.dumpStack();
-          return;
-        }
-        else idx = idx + 1;
-      }
-      if (cs.length + pos + 1 < buf.length) {
-        if (isJavaIdentifierPart(buf(pos + cs.length))) {
-          //Console.err.println("MISMATCH: " + name + "[last] " + unit.source.dbg(pos));
-          return;
-        }
-      }
-      try {
-        list.put(pos, (if (isDef) new Def(term) else new Use(term, tpe)));
-      } catch {
-        case e : Error => e.printStackTrace();
-      }
-    }
-
-  def selectPos(tree: Select): Int = if (tree.pos == NoPosition) -1 else {
-    val buf = unit.source.asInstanceOf[BatchSourceFile].content
-    if (tree.pos.offset.get >= buf.length) {
-      if (false) {
-        Console.err.println("" + tree + "@" + tree.pos + " not in " +
-                           unit.source.file.name + "[" + buf.length + "]");
-        Thread.dumpStack()
-        throw new Error()
-      }
-      return 0
-    }
-
-    val pos : Int =
-      if (buf(tree.pos.offset.get) != '.') tree.pos.offset.get
-      else {
-        def f(x : Int) : Int = {
-          if (buf(x).isWhitespace) f(x + 1)
-          else x
-        }
-        f(tree.pos.offset.get + 1)
-      }
-    pos
-  };
-
-  class TokenList {
-    object begin extends HasNext {
-      def prev = this
-      def length = 0
-    }
-    object end extends HasPrev {
-      def next = this
-      def length = 0
-    }
-    // initialize
-    begin.next0 = end
-    end.prev0 = begin
-
-    def tokenAt(offset: Int) = {
-      cursor.seek(offset)
-      if (cursor.token.isInstanceOf[Semantic]) cursor.token.asInstanceOf[Semantic]
-      else null
-    }
-
-    def put(offset: Int, tok: Actual): Unit = tok match {
-      case tok0: Semantic => put(offset, tok0)
-      case gap: Gap      =>
-    }
-
-    def put(offset: Int, tok: Semantic) {
-      cursor.seek(offset);
-      if (cursor.token == end) {
-        assert(offset >= cursor.offset);
-        if (offset > cursor.offset) {
-          // add a gap.
-          val gap = new Gap(end.prev);
-          gap.setLength(offset - cursor.offset);
-          cursor.offset = offset;
-        }
-        // append.
-        tok.insert(end.prev);
-        cursor.offset = cursor.offset + tok.length;
-      } else if (!cursor.token.isInstanceOf[Gap]) {
-        val sem = cursor.token.asInstanceOf[Semantic];
-        if (sem.symbol == tok.symbol) return;
-        if (sem.symbol != tok.symbol &&
-            sem.symbol.getClass() == tok.symbol.getClass() &&
-            sem.symbol.pos == tok.symbol.pos) return;
-      } else {
-        val gap = cursor.token.asInstanceOf[Gap];
-        if (!(offset - cursor.offset + tok.length <= gap.length)) {
-          Console.err.println("LIST  =" + this);
-          Console.err.println("OFFSET=" + offset + " " + tok + " " + tok.length);
-          Console.err.println("       " + cursor.offset + " " + gap.length);
-          gap.length0 = offset - cursor.offset + tok.length
-          //throw new Error();
-        }
-        if (offset == cursor.offset) {
-          // replace or prepend
-          tok.prev0 = gap.prev0;
-          if (tok.length == gap.length) { // replace gap
-            tok.next0 = gap.next0;
-          } else {
-            gap.setLength(gap.length - tok.length);
-            tok.next0 = gap;
-          }
-          tok.next0.prev0 = tok;
-          tok.prev0.next0 = tok;
-          cursor.token = tok;
-        } else {
-          // append
-          val diff = (cursor.offset + gap.length) - (offset + tok.length);
-
-          gap.setLength(gap.length - tok.length - diff);
-          tok.prev0 = gap;
-          tok.next0 = gap.next;
-          tok.next0.prev0 = tok;
-          tok.prev0.next0 = tok;
-          if (diff != 0) {
-            val gap0 = new Gap(tok);
-            gap0.setLength(diff);
-          }
-        }
-      }
-    }
-
-    override def toString(): String = {
-      var node = begin.next
-      var str = ""
-      while (node != end) {
-        str = str + " " + node
-        node = node.next
-      }
-      str
-    }
-
-    object cursor {
-      var token: Token = end
-      var offset: Int = 0
-
-      def next: Unit = if (token == end) end else {
-        offset = offset + token.length
-        token  = token.next
-      }
-      def prev: Unit = if (token.prev == begin) token else {
-        offset = offset - token.prev.length
-        token = token.prev
-      }
-      def seek(soffset: Int): Unit = if (soffset == 0) {
-        token = begin.next
-        offset = 0
-      } else {
-        assert(soffset > 0)
-        while (offset                >  soffset) prev;
-        while (offset + token.length <= soffset && token != end) {
-          val len0 = offset;
-          next;
-        }
-      }
-      def convertToGap = if (token.isInstanceOf[Actual]) {
-        val ret = token.asInstanceOf[Actual].convertToGap;
-        offset  = offset - ret._1;
-        token   = ret._2;
-      }
-    }
-
-    // add or delete characters
-    def adjust(offset: Int, /* where */
-               length: Int, /* how many characters are modified */
-               to    : Int  /* length of new string */) = {
-      cursor.seek(offset)
-      if (cursor.token != end) {
-        cursor.convertToGap
-        while (cursor.offset + cursor.token.length < offset + length && cursor.token.next != end) {
-          val save = cursor.offset
-          cursor.next
-          cursor.convertToGap
-          assert(cursor.offset == save)
-        }
-         if (length != to && cursor.token != end) {
-           val diff = to - length;
-           val gap = cursor.token.asInstanceOf[Gap];
-           gap.setLength(gap.length + diff);
-         };
-      }
-    }
-
-  } // TokenList
-
-  }
-}
-
diff --git a/src/compiler/scala/tools/nsc/models/Signatures.scala b/src/compiler/scala/tools/nsc/models/Signatures.scala
deleted file mode 100644
index ab7103e..0000000
--- a/src/compiler/scala/tools/nsc/models/Signatures.scala
+++ /dev/null
@@ -1,88 +0,0 @@
-/* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
- * @author  Martin Odersky
- */
-// $Id: Signatures.scala 16894 2009-01-13 13:09:41Z cunei $
-
-package scala.tools.nsc.models
-
-import scala.collection.mutable.{HashMap, HashSet}
-import scala.tools.nsc.{Global => Compiler}
-import scala.tools.nsc.symtab.{Flags, Names}
-import scala.tools.nsc.util.{NameTransformer, Position, SourceFile}
-
-/** This class ...
- *
- *  @author  Sean McDirmid
- *  @version 1.0
- */
-class Signatures(val compiler: Compiler) {
-  import compiler._
-
-  class Signature(val name: String, val children: List[Signature]) {
-    def asString: String = name + "[" + asString0(children) + "]"
-  }
-
-  def sort(sigs: List[Signature]) =
-    sigs.sort((l0,l1) => l0.name.compareTo(l1.name) > 0)
-
-  def asString0(sigs: List[Signature]): String = {
-    var ret = ""
-    for (sig <- sort(sigs)) ret = ret + sig.asString
-    ret
-  }
-
-  def signature(unit: CompilationUnit): String =
-    asString0(signature(unit.body, Nil))
-
-  def signature(trees: List[Tree]): List[Signature] = {
-    var ret : List[Signature] = Nil
-    for (tree <- trees) ret = signature(tree, ret)
-    ret
-  }
-
-  /**
-   *  @param tree0 ...
-   *  @param rest  ...
-   *  @return      ...
-   */
-  def signature(tree0: Tree, rest: List[Signature]): List[Signature] = tree0 match {
-    case tree: MemberDef => if (!tree.mods.isPrivate) {
-      val name = "" + tree.name + "::" + 
-        (tree.mods &~ Flags.SYNTHETIC)
-      
-      val children: List[Signature] = tree match {
-          case impl: ImplDef
-            //if (!impl.name.toString.contains("$anonfun$")) =>
-            if (impl.name.pos("$anonfun$") == name.length) =>
-          val supers = new Signature("$$supers", signature(impl.impl.parents))
-          val body   = new Signature("$$body",   signature(impl.impl.body))
-          val ret = supers :: body :: Nil
-          impl match {
-            case cdef: ClassDef =>
-              new Signature("$$tparams", signature(cdef.tparams)) :: ret
-            case  _ =>
-              ret
-          }
-        case vdef: ValOrDefDef =>
-          val ret = signature(vdef.tpt, Nil)
-          vdef match {
-            case ddef : DefDef =>
-              val tparams = new Signature("$$tparams", signature(ddef.tparams))
-              var vparamss : List[Signature] = Nil
-              for (list <- ddef.vparamss)
-                vparamss = signature(list) ::: vparamss
-              new Signature("$$ret", ret) :: tparams :: vparamss
-            case _ =>
-              ret
-          }
-        case pdef: PackageDef => signature(pdef.stats)
-        case _ => Nil
-      }
-      new Signature(name, children) :: rest
-
-    } else rest
-    case tree: TypeTree => new Signature("" + tree.tpe, Nil) :: rest
-    case _ => rest
-  }
-}
diff --git a/src/compiler/scala/tools/nsc/plugins/Plugin.scala b/src/compiler/scala/tools/nsc/plugins/Plugin.scala
index c58d39f..420b825 100644
--- a/src/compiler/scala/tools/nsc/plugins/Plugin.scala
+++ b/src/compiler/scala/tools/nsc/plugins/Plugin.scala
@@ -1,12 +1,12 @@
 /* NSC -- new Scala compiler
- * Copyright 2007-2009 LAMP/EPFL
+ * Copyright 2007-2010 LAMP/EPFL
  * @author Lex Spoon
  */
-// $Id: Plugin.scala 16881 2009-01-09 16:28:11Z cunei $
 
-package scala.tools.nsc.plugins
+package scala.tools.nsc
+package plugins
 
-import java.io.File
+import io.{ File, Path }
 import java.net.URLClassLoader
 import java.util.jar.JarFile
 import java.util.zip.ZipException
@@ -63,90 +63,90 @@ abstract class Plugin {
  *  @version 1.0, 2007-5-21
  */
 object Plugin {
+
+  private val PluginXML = "scalac-plugin.xml"
+
   /** Create a class loader with the specified file plus
    *  the loader that loaded the Scala compiler.
    */
-  private def loaderFor(jarfiles: Seq[File]): ClassLoader = {
+  private def loaderFor(jarfiles: Seq[Path]): ClassLoader = {
     val compilerLoader = classOf[Plugin].getClassLoader
-    val jarurls = jarfiles.map(_.toURL).toArray
-    new URLClassLoader(jarurls, compilerLoader)
+    val jarurls = jarfiles map (_.toURL)
+    
+    new URLClassLoader(jarurls.toArray, compilerLoader)
   }
 
   /** Try to load a plugin description from the specified
-   *  file, returning None if it does not work. */
-  private def loadDescription(jarfile: File): Option[PluginDescription] = {
-    if (!jarfile.exists) return None
+   *  file, returning <code>None</code> if it does not work.
+   */
+  private def loadDescription(jarfile: Path): Option[PluginDescription] =
+    // XXX Return to this once we have some ARM support
+    if (!jarfile.exists) None
+    else try {
+      val jar = new JarFile(jarfile.jfile)
 
-    try {
-      val jar = new JarFile(jarfile)
       try {
-	val ent = jar.getEntry("scalac-plugin.xml")
-	if(ent == null) return None
-
-	val inBytes = jar.getInputStream(ent)
-	val packXML = XML.load(inBytes)
-	inBytes.close()
-        
-	PluginDescription.fromXML(packXML)
-      } finally {
-	jar.close()
+        jar getEntry PluginXML match {
+          case null  => None
+          case entry =>
+            val in = jar getInputStream entry
+            val packXML = XML load in
+            in.close()
+
+            PluginDescription fromXML packXML
+        }
       }
-    } catch {
-      case _:ZipException => None
+      finally jar.close()
+    }
+    catch {
+      case _: ZipException => None
     }
-  }
 
   type AnyClass = Class[_]
 
-  /** Loads a plugin class from the named jar file.  Returns None
-   *  if the jar file has no plugin in it or if the plugin
-   *  is badly formed.
+  /** Loads a plugin class from the named jar file.
+
+   *  @return <code>None</code> if the jar file has no plugin in it or
+   *                            if the plugin is badly formed.
    */
-  def loadFrom(jarfile: File, loader: ClassLoader): Option[AnyClass] = {
-    val pluginInfo = loadDescription(jarfile).get
-
-    try {
-      Some(loader.loadClass(pluginInfo.classname))
-    } catch {
-      case _:ClassNotFoundException =>
-	println("Warning: class not found for plugin in " + jarfile +
-                " (" + pluginInfo.classname + ")")
-      None
-    } 
-  }
+  def loadFrom(jarfile: Path, loader: ClassLoader): Option[AnyClass] =
+    loadDescription(jarfile) match {
+      case None => None
+      case Some(pdesc) =>
+        try Some(loader loadClass pdesc.classname) catch {
+        case _: Exception =>
+          println("Warning: class not found for plugin in %s (%s)".format(jarfile, pdesc.classname))
+          None
+      }
+    }
 
   /** Load all plugins found in the argument list, both in the
    *  jar files explicitly listed, and in the jar files in the
    *  directories specified. Skips all plugins in <code>ignoring</code>.
    *  A single classloader is created and used to load all of them.
    */
-  def loadAllFrom(jars: List[File], 
-		  dirs: List[File], 
-		  ignoring: List[String]): List[AnyClass] = 
+  def loadAllFrom(
+    jars: List[Path], 
+    dirs: List[Path], 
+    ignoring: List[String]): List[AnyClass] =
   {
-    val alljars = new ListBuffer[File]
-
-    alljars ++= jars
-
-    for {
+    val alljars = (jars ::: (for {
       dir <- dirs if dir.isDirectory
-      entries = dir.listFiles
-      if entries ne null
-      entry <- entries.toList.sort((f1, f2) => f1.getName <= f2.getName)
-      if entry.toString.toLowerCase endsWith ".jar"
+      entry <- dir.toDirectory.files.toList sortBy (_.name)
+      if entry.extension == "jar"
       pdesc <- loadDescription(entry)
       if !(ignoring contains pdesc.name)
-    } alljars += entry
-
-    val loader = loaderFor(alljars.toList)
-    alljars.toList.map(f => loadFrom(f,loader)).flatMap(x => x)
+    } yield entry)).distinct
+ 
+    val loader = loaderFor(alljars)
+    alljars map (loadFrom(_, loader)) flatten
   }
 
   /** Instantiate a plugin class, given the class and
    *  the compiler it is to be used in.
    */
   def instantiate(clazz: AnyClass, global: Global): Plugin = {
-    val constructor = clazz.getConstructor(classOf[Global])
-    constructor.newInstance(global).asInstanceOf[Plugin]
+    val constructor = clazz getConstructor classOf[Global]
+    (constructor newInstance global).asInstanceOf[Plugin]
   }
 }
diff --git a/src/compiler/scala/tools/nsc/plugins/PluginComponent.scala b/src/compiler/scala/tools/nsc/plugins/PluginComponent.scala
index 4e26693..b4f72ab 100644
--- a/src/compiler/scala/tools/nsc/plugins/PluginComponent.scala
+++ b/src/compiler/scala/tools/nsc/plugins/PluginComponent.scala
@@ -1,17 +1,25 @@
 /* NSC -- new Scala compiler
- * Copyright 2007-2009 LAMP/EPFL
+ * Copyright 2007-2010 LAMP/EPFL
  * @author Lex Spoon
+ * Updated by Anders Bach Nielsen
  */
-// $Id: PluginComponent.scala 16881 2009-01-09 16:28:11Z cunei $
 
-package scala.tools.nsc.plugins
+package scala.tools.nsc
+package plugins
 
 /** A component that is part of a Plugin.
  *
- * @author Lex Spoon
- * @version 1.0, 2007/5/29
+ * @author Lex Spoon 
+ * @version 1.1, 2009/1/2
+ * Updated 2009/1/2 by Anders Bach Nielsen: Added features to implement SIP 00002
  */
 abstract class PluginComponent extends SubComponent {
-  /** the phase this plugin wants to run after */
-  val runsAfter: String
+
+  /** Internal flag to tell external from internal phases */
+  final override val internal = false
+
+  /** Phases supplied by plugins should not have give the runsRightAfter constraint,
+   * but can override it */
+  val runsRightAfter: Option[String] = None
+
 }
diff --git a/src/compiler/scala/tools/nsc/plugins/PluginDescription.scala b/src/compiler/scala/tools/nsc/plugins/PluginDescription.scala
index e616952..2498d84 100644
--- a/src/compiler/scala/tools/nsc/plugins/PluginDescription.scala
+++ b/src/compiler/scala/tools/nsc/plugins/PluginDescription.scala
@@ -1,10 +1,10 @@
 /* NSC -- new Scala compiler
- * Copyright 2007-2009 LAMP/EPFL
+ * Copyright 2007-2010 LAMP/EPFL
  * @author Lex Spoon
  */
-// $Id: PluginDescription.scala 16881 2009-01-09 16:28:11Z cunei $
 
-package scala.tools.nsc.plugins
+package scala.tools.nsc
+package plugins
 
 import java.io.File
 
diff --git a/src/compiler/scala/tools/nsc/plugins/PluginLoadException.scala b/src/compiler/scala/tools/nsc/plugins/PluginLoadException.scala
index c81f482..f040280 100644
--- a/src/compiler/scala/tools/nsc/plugins/PluginLoadException.scala
+++ b/src/compiler/scala/tools/nsc/plugins/PluginLoadException.scala
@@ -1,10 +1,10 @@
 /* NSC -- new Scala compiler
- * Copyright 2007-2009 LAMP/EPFL
+ * Copyright 2007-2010 LAMP/EPFL
  * @author Lex Spoon
  */
-// $Id: PluginLoadException.scala 16881 2009-01-09 16:28:11Z cunei $
 
-package scala.tools.nsc.plugins
+package scala.tools.nsc
+package plugins
 
 /** ...
  *
diff --git a/src/compiler/scala/tools/nsc/plugins/Plugins.scala b/src/compiler/scala/tools/nsc/plugins/Plugins.scala
index 2b3a06d..1d0c171 100644
--- a/src/compiler/scala/tools/nsc/plugins/Plugins.scala
+++ b/src/compiler/scala/tools/nsc/plugins/Plugins.scala
@@ -1,44 +1,41 @@
 /* NSC -- new Scala compiler
- * Copyright 2007-2009 LAMP/EPFL
+ * Copyright 2007-2010 LAMP/EPFL
  * @author Lex Spoon
+ * Updated by Anders Bach Nielsen
  */
-// $Id: Plugins.scala 16881 2009-01-09 16:28:11Z cunei $
 
-package scala.tools.nsc.plugins
+package scala.tools.nsc
+package plugins
 
-import java.io.File
+import io.{ File, Path }
 
 /** Support for run-time loading of compiler plugins.
  *
- *  @author Lex Spoon
- *  @version 1.0, 2007-5-21
+ *  @author Lex Spoon 
+ *  @version 1.1, 2009/1/2
+ *  Updated 2009/1/2 by Anders Bach Nielsen: Added features to implement SIP 00002
  */
-trait Plugins { self: Global =>
+trait Plugins
+{
+  self: Global =>
 
   /** Load a rough list of the plugins.  For speed, it
    *  does not instantiate a compiler run.  Therefore it cannot
    *  test for same-named phases or other problems that are
-   *  filtered from the final list of plugins. */
+   *  filtered from the final list of plugins.
+   */
   protected def loadRoughPluginsList(): List[Plugin] = {
-    val jars = settings.plugin.value.map(new File(_))
-    val dirs =
-      for (name <- settings.pluginsDir.value.split(File.pathSeparator).toList)
-	yield new File(name)
-
-    for (plugClass <- Plugin.loadAllFrom(jars, dirs, settings.disable.value))
-    yield Plugin.instantiate(plugClass, this)
+    val jars = settings.plugin.value map Path.apply
+    val dirs = (settings.pluginsDir.value split File.pathSeparator).toList map Path.apply
+    val classes = Plugin.loadAllFrom(jars, dirs, settings.disable.value)
+    
+    // Lach plugin must only be instantiated once. A common pattern
+    // is to register annotation checkers during object construction, so
+    // creating multiple plugin instances will leave behind stale checkers.
+    classes map (Plugin.instantiate(_, this))
   }
 
-  private var roughPluginsListCache: Option[List[Plugin]] = None
-
-  protected def roughPluginsList: List[Plugin] =
-    roughPluginsListCache match {
-      case Some(list) => list
-      case None =>
-	roughPluginsListCache = Some(loadRoughPluginsList)
-        roughPluginsListCache.get
-    }
-
+  protected lazy val roughPluginsList: List[Plugin] = loadRoughPluginsList
 
   /** Load all available plugins.  Skips plugins that
    *  either have the same name as another one, or which
@@ -51,140 +48,70 @@ trait Plugins { self: Global =>
       plugNames: Set[String], 
       phaseNames: Set[String]): List[Plugin] =
     {
-      plugins match {
-	case Nil => Nil
-	case plug :: rest =>
-	  val plugPhaseNames = Set.empty ++ plug.components.map(_.phaseName)
-	  def withoutPlug = pick(rest, plugNames, plugPhaseNames)
-	  def withPlug =
-	    (plug :: 
-	     pick(rest, 
-		  plugNames+plug.name,
-		  phaseNames++plugPhaseNames))
-
-	  if (plugNames.contains(plug.name)) {
-	    if (settings.verbose.value)
-	      inform("[skipping a repeated plugin: " + plug.name + "]")
-	    withoutPlug
-	  } else if (settings.disable.value contains(plug.name)) {
-	    if (settings.verbose.value)
-	      inform("[disabling plugin: " + plug.name + "]")
-	    withoutPlug
-	  } else {
-	    val commonPhases = phaseNames.intersect(plugPhaseNames)
-	    if (!commonPhases.isEmpty) {
-	      if (settings.verbose.value)
-		inform("[skipping plugin " + plug.name +
-		       "because it repeats phase names: " +
-		       commonPhases.mkString(", ") + "]")
-	      withoutPlug
-	    } else {
-	      if (settings.verbose.value)
-		inform("[loaded plugin " + plug.name + "]")
-	      withPlug
-	    }
-	  }
+      if (plugins.isEmpty) return Nil // early return
+      
+      val plug :: tail      = plugins
+      val plugPhaseNames    = Set(plug.components map (_.phaseName): _*)
+      def withoutPlug       = pick(tail, plugNames, plugPhaseNames)
+      def withPlug          = plug :: pick(tail, plugNames + plug.name, phaseNames ++ plugPhaseNames)
+      lazy val commonPhases = phaseNames intersect plugPhaseNames
+      
+      def note(msg: String): Unit = if (settings.verbose.value) inform(msg format plug.name)
+      def fail(msg: String)       = { note(msg) ; withoutPlug }
+      
+      if (plugNames contains plug.name)
+        fail("[skipping a repeated plugin: %s]")
+      else if (settings.disable.value contains plug.name)
+        fail("[disabling plugin: %s]")
+      else if (!commonPhases.isEmpty)
+        fail("[skipping plugin %s because it repeats phase names: " + (commonPhases mkString ", ") + "]")
+      else {
+        note("[loaded plugin %s]")
+        withPlug
       }
     }
 
-    val plugs =
-    pick(roughPluginsList,
-	 Set.empty,
-	 Set.empty ++ builtInPhaseDescriptors.map(_.phaseName))
-
-    for (req <- settings.require.value; if !plugs.exists(p => p.name==req))
+    val plugs = pick(roughPluginsList, Set(), phasesSet map (_.phaseName) toSet)
+    
+    /** Verify requirements are present. */
+    for (req <- settings.require.value ; if !(plugs exists (_.name == req)))
       error("Missing required plugin: " + req)
 
-    
-    for (plug <- plugs) {
-      val nameColon = plug.name + ":"
-      val opts = for {
-	raw <- settings.pluginOptions.value
-	if raw.startsWith(nameColon)
-      } yield raw.substring(nameColon.length)
+    /** Process plugin options. */
+    def namec(plug: Plugin) = plug.name + ":"
+    def optList(xs: List[String], p: Plugin) = xs filter (_ startsWith namec(p))
+    def doOpts(p: Plugin): List[String] =
+      optList(settings.pluginOptions.value, p) map (_ stripPrefix namec(p))
 
+    for (p <- plugs) {
+      val opts = doOpts(p)
       if (!opts.isEmpty)
-	plug.processOptions(opts, error)
+        p.processOptions(opts, error)
     }
-
-    for {
-      opt <- settings.pluginOptions.value
-      if !plugs.exists(p => opt.startsWith(p.name + ":"))
-    } error("bad option: -P:" + opt)
+      
+    /** Verify no non-existent plugin given with -P */      
+    for (opt <- settings.pluginOptions.value ; if plugs forall (p => optList(List(opt), p).isEmpty))
+      error("bad option: -P:" + opt)
 
     plugs
   }
 
-
-  private var pluginsCache: Option[List[Plugin]] = None
-
-  def plugins: List[Plugin] = {
-    if (pluginsCache.isEmpty)
-      pluginsCache = Some(loadPlugins)
-    pluginsCache.get
-  }
-
+  lazy val plugins: List[Plugin] = loadPlugins
 
   /** A description of all the plugins that are loaded */
-  def pluginDescriptions: String = {
-    val messages =
-      for (plugin <- roughPluginsList)
-	yield plugin.name + " - " + plugin.description
-    messages.mkString("\n")
-  }
-
-
-  /** Compute a full list of phase descriptors, including
-   *  both built-in phases and those coming from plugins. */
-  protected def computePhaseDescriptors: List[SubComponent] = {
-    def insert(descs: List[SubComponent], component: PluginComponent)
-    :List[SubComponent] =
-    {
-      descs match {
-	case Nil => assert(false); Nil
-        case hd::rest if "parser" == component.runsAfter =>
-          component :: hd :: rest
-	case hd::rest if hd.phaseName == component.runsAfter =>
-	  hd :: component :: rest
-	case hd :: rest =>
-	  hd :: (insert(rest, component))
-      }
-    }
-
-    var descriptors = builtInPhaseDescriptors
-    var plugsLeft = plugins.flatMap(_.components)
-
-    // Insert all the plugins, one by one.  Note that
-    // plugins are allowed to depend on each other, thus
-    // complicating the algorithm.	  
+  def pluginDescriptions: String =
+    roughPluginsList map (x => "%s - %s".format(x.name, x.description)) mkString "\n"
 
-    while (!plugsLeft.isEmpty) {
-      val nextPlug = plugsLeft.find(plug =>
-        plug.runsAfter == "parser" || 
-        descriptors.exists(d => d.phaseName == plug.runsAfter))
-      nextPlug match {
-	case None =>
-	  error("Failed to load some plugin phases:")
-	  for (plug <- plugsLeft)
-	    error (plug.phaseName + " depends on " + plug.runsAfter)
-	  return descriptors
-	case Some(nextPlug) =>
-	  descriptors = insert(descriptors, nextPlug)
-          plugsLeft = plugsLeft.filter(p => !(p eq nextPlug))
-      }
-    }
-
-    descriptors
-  }
+  /**
+   * Extract all phases supplied by plugins and add them to the phasesSet.
+   * @see phasesSet
+   */
+  protected def computePluginPhases(): Unit =
+    phasesSet ++= (plugins flatMap (_.components))
 
   /** Summary of the options for all loaded plugins */
-  def pluginOptionsHelp: String = {
-    val buf = new StringBuffer
-    for (plug <- roughPluginsList; help <- plug.optionsHelp) {
-      buf append ("Options for plugin " + plug.name + ":\n")
-      buf append help
-      buf append "\n"
-    }
-    buf.toString
-  }
+  def pluginOptionsHelp: String =
+    (for (plug <- roughPluginsList ; help <- plug.optionsHelp) yield {
+      "Options for plugin %s:\n%s\n".format(plug.name, help)
+    }) mkString
 }
diff --git a/src/compiler/scala/tools/nsc/reporters/AbstractReporter.scala b/src/compiler/scala/tools/nsc/reporters/AbstractReporter.scala
index 4e8dc72..f2151ff 100644
--- a/src/compiler/scala/tools/nsc/reporters/AbstractReporter.scala
+++ b/src/compiler/scala/tools/nsc/reporters/AbstractReporter.scala
@@ -1,10 +1,10 @@
 /* NSC -- new Scala compiler
- * Copyright 2002-2009 LAMP/EPFL
+ * Copyright 2002-2010 LAMP/EPFL
  * @author Martin Odersky
  */
-// $Id: AbstractReporter.scala 16881 2009-01-09 16:28:11Z cunei $
 
-package scala.tools.nsc.reporters
+package scala.tools.nsc
+package reporters
 
 import scala.collection.mutable.HashMap
 import scala.tools.nsc.Settings
@@ -16,7 +16,7 @@ import scala.tools.nsc.util.Position
 abstract class AbstractReporter extends Reporter {
   private val positions = new HashMap[Position, Severity]
   
-  override def reset = {
+  override def reset {
     super.reset
     positions.clear
   }
@@ -26,15 +26,19 @@ abstract class AbstractReporter extends Reporter {
   def display(pos: Position, msg: String, severity: Severity): Unit
   def displayPrompt: Unit
 
-  protected def info0(pos: Position, msg: String, severity: Severity, force: Boolean) {
+  protected def info0(pos: Position, msg: String, _severity: Severity, force: Boolean) {
+    val severity = 
+      if (settings.Xwarnfatal.value && _severity == WARNING) ERROR
+      else _severity
+    
     severity match {
-      case INFO    =>
+      case INFO =>
         if (force || settings.verbose.value) display(pos, msg, severity)
       case WARNING =>
         val hidden = testAndLog(pos, severity)
         if (!settings.nowarnings.value) {
-	  if (!hidden || settings.prompt.value) display(pos, msg, severity)
-	  if (settings.prompt.value) displayPrompt
+          if (!hidden || settings.prompt.value) display(pos, msg, severity)
+          if (settings.prompt.value) displayPrompt
         }
       case ERROR =>
         val hidden = testAndLog(pos, severity)
@@ -44,16 +48,17 @@ abstract class AbstractReporter extends Reporter {
   }
 
   /** Logs a position and returns <code>true</code> if it was already logged.
+   *  @note  Two positions are considered identical for logging if they have the same point.
    *
    *  @param pos ...
    *  @return    <code>true</code> if <code>pos</code> was already logged.
    */
-  private def testAndLog(pos: Position, severity: Severity): Boolean = {
-    if (pos eq null) return false
-    if (pos.offset.isEmpty) return false
-    if ((positions contains pos) && positions(pos) >= severity) return true
-    positions += (pos -> severity)
-    false
-  }
-
+  private def testAndLog(pos: Position, severity: Severity): Boolean =
+    pos != null && pos.isDefined && { 
+      val fpos = pos.focus
+      (positions get fpos) match {
+        case Some(level) if level >= severity => true
+        case _                                => positions += (fpos -> severity) ; false
+      }
+    }
 }
diff --git a/src/compiler/scala/tools/nsc/reporters/ConsoleReporter.scala b/src/compiler/scala/tools/nsc/reporters/ConsoleReporter.scala
index cb91793..4c1d850 100644
--- a/src/compiler/scala/tools/nsc/reporters/ConsoleReporter.scala
+++ b/src/compiler/scala/tools/nsc/reporters/ConsoleReporter.scala
@@ -1,10 +1,10 @@
 /* NSC -- new Scala compiler
- * Copyright 2002-2009 LAMP/EPFL
+ * Copyright 2002-2010 LAMP/EPFL
  * @author Martin Odersky
  */
-// $Id: ConsoleReporter.scala 16881 2009-01-09 16:28:11Z cunei $
 
-package scala.tools.nsc.reporters
+package scala.tools.nsc
+package reporters
 
 import java.io.{BufferedReader, InputStreamReader, IOException, PrintWriter}
 import util._
@@ -48,27 +48,20 @@ class ConsoleReporter(val settings: Settings, reader: BufferedReader, writer: Pr
 
   /** Prints the message with the given position indication. */
   def printMessage(posIn: Position, msg: String) {
-    if (posIn ne null) {
-      val pos = posIn.inUltimateSource(posIn.source.getOrElse(null))
-      val buf = new StringBuilder(msg)
-      if (!pos.source.isEmpty) {
-        buf.insert(0, " ")
-        buf.insert(0, pos.line.map(ln => ":" + pos.line.get + ":").getOrElse(":"))
-      }
-      //println(getSource.file)
-      pos match {
-        case FakePos(msg) =>
-          buf.insert(0, msg + " ")
-        case _ if !pos.source.isEmpty =>
-          val file = pos.source.get.file
-          buf.insert(0, if (shortname) file.name else file.path)
-        case _ =>
-      }
-      printMessage(buf.toString())
-      if (!pos.line.isEmpty)
+    val pos = if (posIn eq null) NoPosition
+              else if (posIn.isDefined) posIn.inUltimateSource(posIn.source)
+              else posIn
+    pos match {
+      case FakePos(fmsg) =>
+        printMessage(fmsg+" "+msg)
+      case NoPosition =>
+        printMessage(msg)
+      case _ =>
+        val buf = new StringBuilder(msg)
+        val file = pos.source.file
+        printMessage((if (shortname) file.name else file.path)+":"+pos.line+": "+msg)
         printSourceLine(pos)
-    } else
-      printMessage(msg)
+    }
   }
 
   def print(pos: Position, msg: String, severity: Severity) {
@@ -87,16 +80,8 @@ class ConsoleReporter(val settings: Settings, reader: BufferedReader, writer: Pr
    *
    *  @param pos ...
    */
-  def printColumnMarker(pos: Position) = if (!pos.column.isEmpty) {
-    val buffer = new StringBuilder(pos.column.get)
-    var i = 1
-    while (i < pos.column.get) {
-      buffer.append(' ')
-      i += 1
-    }
-    if (pos.column.get > 0) buffer.append('^')
-    printMessage(buffer.toString())
-  }
+  def printColumnMarker(pos: Position) = 
+    if (pos.isDefined) { printMessage(" " * (pos.column - 1) + "^") }
   
   /** Prints the number of errors and warnings if their are non-zero. */
   def printSummary() {
@@ -117,18 +102,21 @@ class ConsoleReporter(val settings: Settings, reader: BufferedReader, writer: Pr
       writer.flush()
       var line = reader.readLine()
       if (line ne null) {
-	line = line.toLowerCase()
-	if ("abort" startsWith line)
-            throw new Error("user abort")
-	if ("resume" startsWith line) continue = false
+	      line = line.toLowerCase()
+	      if ("abort" startsWith line)
+          abort("user abort")
+	      if ("resume" startsWith line)
+	        continue = false
       }
     }
-  } catch {
+  } 
+  catch {
     case ex: IOException => {
       ex.printStackTrace()
-      throw new Error("input read error")
+      abort("input read error")
     }
   }
 
+  private def abort(msg: String) = throw new Error(msg)
   override def flush() { writer.flush() }
 }
diff --git a/src/compiler/scala/tools/nsc/reporters/Reporter.scala b/src/compiler/scala/tools/nsc/reporters/Reporter.scala
index 42395f5..2dfe529 100644
--- a/src/compiler/scala/tools/nsc/reporters/Reporter.scala
+++ b/src/compiler/scala/tools/nsc/reporters/Reporter.scala
@@ -1,10 +1,10 @@
 /* NSC -- new Scala compiler
- * Copyright 2002-2009 LAMP/EPFL
+ * Copyright 2002-2010 LAMP/EPFL
  * @author Martin Odersky
  */
-// $Id: Reporter.scala 16881 2009-01-09 16:28:11Z cunei $
 
-package scala.tools.nsc.reporters
+package scala.tools.nsc
+package reporters
 
 import scala.tools.nsc.util._
 
@@ -22,7 +22,7 @@ abstract class Reporter {
   val WARNING = new Severity(1)
   val ERROR = new Severity(2)
 
-  def reset: Unit = {
+  def reset {
     INFO.count = 0
     ERROR.count   = 0
     WARNING.count = 0
@@ -30,7 +30,8 @@ abstract class Reporter {
   }
 
   var cancelled: Boolean = false
-  def hasErrors: Boolean = ERROR.count != 0 || cancelled
+  def hasErrors: Boolean = ERROR.count > 0 || cancelled
+  def hasWarnings: Boolean = WARNING.count > 0
 
   /** Flush all output */
   def flush() { }
@@ -40,11 +41,22 @@ abstract class Reporter {
   private var source: SourceFile = _
   def setSource(source: SourceFile) { this.source = source }
   def getSource: SourceFile = source
-  
-  def    info(pos: Position, msg: String, force: Boolean): Unit = info0(pos, msg,    INFO, force)
-  def warning(pos: Position, msg: String                ): Unit = info0(pos, msg, WARNING, false)
-  def   error(pos: Position, msg: String                ): Unit = info0(pos, msg,   ERROR, false)
-  
+  def withSource[A](src: SourceFile)(op: => A) = {
+    val oldSource = source
+    try {
+      source = src
+      op 
+    } finally { 
+      source = oldSource 
+    }
+  }
+
+  def    info(pos: Position, msg: String, force: Boolean) { info0(pos, msg,    INFO, force) }
+  def warning(pos: Position, msg: String                ) { info0(pos, msg, WARNING, false) }
+  def   error(pos: Position, msg: String                ) { info0(pos, msg,   ERROR, false) }
+
+  def comment(pos: Position, msg: String) {}
+
   /** An error that could possibly be fixed if the unit were longer.
    *  This is used only when the interpreter tries
    *  to distinguish fatal errors from those that are due to
@@ -53,14 +65,18 @@ abstract class Reporter {
    * Should be re-factored into a subclass.
    */
   var incompleteInputError: (Position, String) => Unit = error
+  var incompleteHandled: Boolean = false
   
   def withIncompleteHandler[T](handler: (Position, String) => Unit)(thunk: => T) = {
     val savedHandler = incompleteInputError
+    val savedHandled = incompleteHandled
     try {
       incompleteInputError = handler
+      incompleteHandled = true
       thunk
     } finally {
       incompleteInputError = savedHandler
+      incompleteHandled = savedHandled
     }
   }
   
diff --git a/src/compiler/scala/tools/nsc/reporters/ReporterTimer.scala b/src/compiler/scala/tools/nsc/reporters/ReporterTimer.scala
index 80dd18a..56f904a 100644
--- a/src/compiler/scala/tools/nsc/reporters/ReporterTimer.scala
+++ b/src/compiler/scala/tools/nsc/reporters/ReporterTimer.scala
@@ -1,10 +1,10 @@
 /* NSC -- new Scala compiler
- * Copyright 2002-2009 LAMP/EPFL
+ * Copyright 2002-2010 LAMP/EPFL
  * @author Martin Odersky
  */
-// $Id: ReporterTimer.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.tools.nsc.reporters
+package scala.tools.nsc
+package reporters
 
 import scala.tools.util.AbstractTimer
 
diff --git a/src/compiler/scala/tools/nsc/reporters/StoreReporter.scala b/src/compiler/scala/tools/nsc/reporters/StoreReporter.scala
index 83a8b8e..e473629 100644
--- a/src/compiler/scala/tools/nsc/reporters/StoreReporter.scala
+++ b/src/compiler/scala/tools/nsc/reporters/StoreReporter.scala
@@ -1,10 +1,10 @@
 /* NSC -- new Scala compiler
- * Copyright 2002-2009 LAMP/EPFL
+ * Copyright 2002-2010 LAMP/EPFL
  * @author Martin Odersky
  */
-// $Id: StoreReporter.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.tools.nsc.reporters
+package scala.tools.nsc
+package reporters
 
 import java.io.{BufferedReader, InputStreamReader, IOException, PrintWriter}
 
diff --git a/src/compiler/scala/tools/nsc/settings/AbsScalaSettings.scala b/src/compiler/scala/tools/nsc/settings/AbsScalaSettings.scala
new file mode 100644
index 0000000..3cff347
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/settings/AbsScalaSettings.scala
@@ -0,0 +1,40 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
+ * @author  Paul Phillips
+ */
+
+package scala.tools.nsc
+package settings
+
+trait AbsScalaSettings {
+  self: AbsSettings =>
+  
+  type BooleanSetting     <: AbsSetting { type T = Boolean }
+  type ChoiceSetting      <: AbsSetting { type T = String }
+  type DefinesSetting     <: AbsSetting { type T = List[(String, String)] }
+  type IntSetting         <: AbsSetting { type T = Int }
+  type MultiStringSetting <: AbsSetting { type T = List[String] }
+  type PathSetting        <: AbsSetting { type T = String }
+  type PhasesSetting      <: AbsSetting { type T = List[String] }
+  type StringSetting      <: AbsSetting { type T = String }
+
+  type OutputDirs
+  type OutputSetting <: AbsSetting
+  
+  def BooleanSetting(name: String, descr: String): BooleanSetting
+  def ChoiceSetting(name: String, descr: String, choices: List[String], default: String): ChoiceSetting
+  def DefinesSetting(): DefinesSetting
+  def IntSetting(name: String, descr: String, default: Int, range: Option[(Int, Int)], parser: String => Option[Int]): IntSetting
+  def MultiStringSetting(name: String, arg: String, descr: String): MultiStringSetting
+  def OutputSetting(outputDirs: OutputDirs, default: String): OutputSetting
+  def PathSetting(name: String, arg: String, descr: String, default: String): PathSetting
+  def PhasesSetting(name: String, descr: String): PhasesSetting
+  def StringSetting(name: String, arg: String, descr: String, default: String): StringSetting
+  
+  /** **/
+  abstract class SettingGroup(val prefix: String) extends AbsSetting {
+    def name = prefix
+    def helpDescription: String = error("todo")
+    def unparse: List[String] = List(name)
+  }
+}
diff --git a/src/compiler/scala/tools/nsc/settings/AbsSettings.scala b/src/compiler/scala/tools/nsc/settings/AbsSettings.scala
new file mode 100644
index 0000000..48775e1
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/settings/AbsSettings.scala
@@ -0,0 +1,137 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
+ * @author  Paul Phillips
+ */
+
+package scala.tools.nsc
+package settings
+
+import io.AbstractFile
+
+/** A Settings abstraction boiled out of the original highly mutable Settings
+ *  class with the intention of creating an ImmutableSettings which can be used
+ *  interchangeably.   Except of course without the mutants.
+ */
+
+trait AbsSettings {
+  type Setting <: AbsSetting      // Fix to the concrete Setting type
+  type ResultOfTryToSet           // List[String] in mutable, (Settings, List[String]) in immutable
+  def errorFn: String => Unit
+  protected def allSettings: collection.Set[Setting]
+  
+  // settings minus internal usage settings
+  def visibleSettings = allSettings filterNot (_.isInternalOnly)
+  
+  // only settings which differ from default
+  def userSetSettings = visibleSettings filterNot (_.isDefault)
+  
+  // an argument list which (should) be usable to recreate the Settings
+  def recreateArgs = userSetSettings.toList flatMap (_.unparse)
+  
+  // checks both name and any available abbreviations
+  def lookupSetting(cmd: String): Option[Setting] = allSettings find (_ respondsTo cmd)
+  
+  // two AbsSettings objects are equal if their visible settings are equal.
+  override def hashCode() = visibleSettings.hashCode
+  override def equals(that: Any) = that match {
+    case s: AbsSettings => this.visibleSettings == s.visibleSettings
+    case _              => false
+  }
+  override def toString() = "Settings {\n%s}\n" format (userSetSettings map ("  " + _ + "\n") mkString)
+  def toConciseString = userSetSettings.mkString("(", " ", ")")
+
+  def checkDependencies =
+    visibleSettings filterNot (_.isDefault) forall (setting => setting.dependencies forall {
+      case (dep, value) =>
+        (Option(dep.value) exists (_.toString == value)) || {
+          errorFn("incomplete option %s (requires %s)".format(setting.name, dep.name))
+          false
+        }
+    })
+
+  implicit lazy val SettingOrdering: Ordering[Setting] = Ordering.ordered
+  
+  trait AbsSettingValue {
+    type T <: Any
+    def value: T
+    def isDefault: Boolean
+  }
+
+  trait AbsSetting extends Ordered[Setting] with AbsSettingValue {    
+    def name: String
+    def helpDescription: String
+    def unparse: List[String]     // A list of Strings which can recreate this setting.
+    
+    /* For tools which need to populate lists of available choices */
+    def choices : List[String] = Nil
+    
+    /** In mutable Settings, these return the same object with a var set.
+     *  In immutable, of course they will return a new object, which means
+     *  we can't use "this.type", at least not in a non-casty manner, which
+     *  is unfortunate because we lose type information without it.
+     *
+     *  ...but now they're this.type because of #3462.  The immutable
+     *  side doesn't exist yet anyway.
+     */
+    def withAbbreviation(name: String): this.type
+    def withHelpSyntax(help: String): this.type
+
+    def helpSyntax: String = name
+    def abbreviations: List[String] = Nil
+    def dependencies: List[(Setting, String)] = Nil
+    def respondsTo(label: String) = (name == label) || (abbreviations contains label)
+    
+    /** If the setting should not appear in help output, etc. */
+    def isInternalOnly = false
+
+    /** Issue error and return */
+    def errorAndValue[T](msg: String, x: T): T = { errorFn(msg) ; x }
+    
+    /** After correct Setting has been selected, tryToSet is called with the
+     *  remainder of the command line.  It consumes any applicable arguments and
+     *  returns the unconsumed ones.
+     */
+    protected[nsc] def tryToSet(args: List[String]): Option[ResultOfTryToSet]
+
+    /** Commands which can take lists of arguments in form -Xfoo:bar,baz override
+     *  this method and accept them as a list.  It returns List[String] for
+     *  consistency with tryToSet, and should return its incoming arguments
+     *  unmodified on failure, and Nil on success.
+     */
+    protected[nsc] def tryToSetColon(args: List[String]): Option[ResultOfTryToSet] =
+      errorAndValue("'%s' does not accept multiple arguments" format name, None)
+
+    /** Commands which take properties in form -Dfoo=bar or -Dfoo
+     */
+    protected[nsc] def tryToSetProperty(args: List[String]): Option[ResultOfTryToSet] =
+      errorAndValue("'%s' does not accept property style arguments" format name, None)
+
+    /** Attempt to set from a properties file style property value.
+     */
+    def tryToSetFromPropertyValue(s: String): Unit = tryToSet(s :: Nil)
+
+    /** These categorizations are so the help output shows -X and -P among
+     *  the standard options and -Y among the advanced options.
+     */
+    def isAdvanced  = name match { case "-Y" => true ; case "-X" => false ; case _  => name startsWith "-X" }
+    def isPrivate   = name match { case "-Y" => false ; case _  => name startsWith "-Y" }
+    def isStandard  = !isAdvanced && !isPrivate
+
+    def compare(that: Setting): Int = name compare that.name
+
+    /** Equality tries to sidestep all the drama and define it simply and
+     *  in one place: two AbsSetting objects are equal if their names and
+     *  values compare equal.
+     */
+    override def equals(that: Any) = that match {
+      case x: AbsSettings#AbsSetting  => (name == x.name) && (value == x.value)
+      case _                          => false
+    }
+    override def hashCode() = (name, value).hashCode
+    override def toString() = "%s = %s".format(name, value)
+  }
+  
+  trait InternalSetting extends AbsSetting {
+    override def isInternalOnly = true
+  }
+}
\ No newline at end of file
diff --git a/src/compiler/scala/tools/nsc/settings/AdvancedScalaSettings.scala b/src/compiler/scala/tools/nsc/settings/AdvancedScalaSettings.scala
new file mode 100644
index 0000000..2c82650
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/settings/AdvancedScalaSettings.scala
@@ -0,0 +1,76 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
+ * @author  Paul Phillips
+ */
+
+package scala.tools.nsc
+package settings
+
+trait AdvancedScalaSettings {
+  self: AbsScalaSettings =>
+  
+  abstract class X extends SettingGroup("-X") {
+    val assemextdirs: StringSetting
+    val assemname: StringSetting
+    val assempath: StringSetting
+    val checkinit: BooleanSetting
+    val disableassertions: BooleanSetting
+    val elidebelow: IntSetting
+    val experimental: BooleanSetting
+    val future: BooleanSetting
+    val generatephasegraph: StringSetting
+    val logimplicits: BooleanSetting
+    val migration: BooleanSetting
+    val noforwarders: BooleanSetting
+    val nojline: BooleanSetting
+    val nouescape: BooleanSetting
+    val plugin: MultiStringSetting
+    val plugindisable: MultiStringSetting
+    val pluginlist: BooleanSetting
+    val pluginrequire: MultiStringSetting
+    val pluginsdir: StringSetting
+    val print: PhasesSetting
+    val printicode: BooleanSetting
+    val printpos: BooleanSetting
+    val printtypes: BooleanSetting
+    val prompt: BooleanSetting
+    val resident: BooleanSetting
+    val script: StringSetting
+    val showclass: StringSetting
+    val showobject: StringSetting
+    val showphases: BooleanSetting
+    val sourcedir: StringSetting
+    val sourcereader: StringSetting
+  }  
+  // def Xexperimental = X.experimental  
+  // def Xmigration28 = X.migration
+  // def Xnojline = X.nojline
+  // def Xprint = X.print
+  // def Xprintpos = X.printpos
+  // def Xshowcls = X.showclass
+  // def Xshowobj = X.showobject
+  // def assemextdirs = X.assemextdirs
+  // def assemname = X.assemname
+  // def assemrefs = X.assempath
+  // def checkInit = X.checkinit
+  // def disable = X.plugindisable
+  // def elideLevel = X.elidelevel
+  // def future = X.future
+  // def genPhaseGraph = X.generatephasegraph
+  // def logimplicits = X.logimplicits
+  // def noForwarders = X.noforwarders
+  // def noassertions = X.disableassertions
+  // def nouescape = X.nouescape
+  // def plugin = X.plugin
+  // def pluginsDir = X.pluginsdir
+  // def printtypes = X.printtypes
+  // def prompt = X.prompt
+  // def require = X.require
+  // def resident = X.resident
+  // def script = X.script
+  // def showPhases = X.showphases
+  // def showPlugins = X.pluginlist
+  // def sourceReader = X.sourcereader
+  // def sourcedir = X.sourcedir
+  // def writeICode = X.printicode
+}
\ No newline at end of file
diff --git a/src/compiler/scala/tools/nsc/settings/ImmutableSettings.scala b/src/compiler/scala/tools/nsc/settings/ImmutableSettings.scala
new file mode 100644
index 0000000..a673860
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/settings/ImmutableSettings.scala
@@ -0,0 +1,11 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
+ * @author  Paul Phillips
+ */
+
+package scala.tools.nsc
+package settings
+
+/** TODO.
+ */
+class ImmutableSettings
diff --git a/src/compiler/scala/tools/nsc/settings/MutableSettings.scala b/src/compiler/scala/tools/nsc/settings/MutableSettings.scala
new file mode 100644
index 0000000..fad4c67
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/settings/MutableSettings.scala
@@ -0,0 +1,599 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
+ * @author  Martin Odersky
+ */
+// $Id$
+
+package scala.tools
+package nsc
+package settings
+
+import io.{AbstractFile, VirtualDirectory}
+import scala.tools.util.StringOps
+import scala.collection.mutable.ListBuffer
+import scala.io.Source
+
+/** A mutable Settings object.
+ */
+class MutableSettings(val errorFn: String => Unit) extends AbsSettings with ScalaSettings with Mutable {  
+  type ResultOfTryToSet = List[String]
+
+  /** Iterates over the arguments applying them to settings where applicable.
+   *  Then verifies setting dependencies are met.
+   * 
+   *  This temporarily takes a boolean indicating whether to keep
+   *  processing if an argument is seen which is not a command line option.
+   *  This is an expedience for the moment so that you can say
+   *
+   *    scalac -d /tmp foo.scala -optimise
+   *
+   *  while also allowing
+   * 
+   *    scala Program opt opt
+   *
+   *  to get their arguments. 
+   *
+   *  Returns (success, List of unprocessed arguments)
+   */
+  def processArguments(arguments: List[String], processAll: Boolean): (Boolean, List[String]) = {
+    var args = arguments
+    val residualArgs = new ListBuffer[String]
+
+    while (args.nonEmpty) {
+      if (args.head startsWith "-") {
+        val args0 = args
+        args = this parseParams args
+        if (args eq args0) {
+          errorFn("bad option: '" + args.head + "'")
+          return ((false, args))
+        }
+      }
+      else if (args.head == "") {   // discard empties, sometimes they appear because of ant or etc.
+        args = args.tail
+      }
+      else {
+        if (!processAll)
+          return ((checkDependencies, args))
+          
+        residualArgs += args.head
+        args = args.tail
+      }
+    }
+    
+    ((checkDependencies, residualArgs.toList))
+  }
+  def processArgumentString(params: String) = processArguments(splitParams(params), true)
+
+  /** Create a new Settings object, copying all user-set values.
+   */
+  def copy(): Settings = {
+    val s = new Settings()
+    val xs = userSetSettings flatMap (_.unparse)
+    s.processArguments(xs.toList, true)
+    s
+  }
+
+  /** A list pairing source directories with their output directory.
+   *  This option is not available on the command line, but can be set by
+   *  other tools (IDEs especially). The command line specifies a single
+   *  output directory that is used for all source files, denoted by a
+   *  '*' in this list.
+   */
+  lazy val outputDirs = new OutputDirs
+
+  /** Split the given line into parameters.
+   */
+  def splitParams(line: String) = cmd.Parser.tokenize(line, errorFn)
+
+  /** Returns any unprocessed arguments.
+   */
+  def parseParams(args: List[String]): List[String] = {
+    // verify command exists and call setter
+    def tryToSetIfExists(
+      cmd: String,
+      args: List[String],
+      setter: (Setting) => (List[String] => Option[List[String]])
+    ): Option[List[String]] =
+      lookupSetting(cmd) match {
+        case None       => errorFn("Parameter '" + cmd + "' is not recognised by Scalac.") ; None          
+        case Some(cmd)  => setter(cmd)(args)
+      }
+
+    // if arg is of form -Xfoo:bar,baz,quux
+    def parseColonArg(s: String): Option[List[String]] = {
+      val (p, args) = StringOps.splitWhere(s, _ == ':', true) getOrElse (return None)
+
+      // any non-Nil return value means failure and we return s unmodified
+      tryToSetIfExists(p, args split "," toList, (s: Setting) => s.tryToSetColon _)
+    }
+    // if arg is of form -Dfoo=bar or -Dfoo (name = "-D")
+    def isPropertyArg(s: String) = lookupSetting(s take 2) match {
+      case Some(x: DefinesSetting)  => true
+      case _                        => false
+    }
+    def parsePropertyArg(s: String): Option[List[String]] = {
+      val (p, args) = (s take 2, s drop 2)
+
+      tryToSetIfExists(p, List(args), (s: Setting) => s.tryToSetProperty _)
+    }
+
+    // if arg is of form -Xfoo or -Xfoo bar (name = "-Xfoo")
+    def parseNormalArg(p: String, args: List[String]): Option[List[String]] =
+      tryToSetIfExists(p, args, (s: Setting) => s.tryToSet _)
+
+    def doArgs(args: List[String]): List[String] = {
+      if (args.isEmpty) return Nil
+      val arg :: rest = args
+      if (arg == "") {
+        // it looks like Ant passes "" sometimes
+        rest
+      }
+      else if (!arg.startsWith("-")) {
+        errorFn("Argument '" + arg + "' does not start with '-'.")
+        args
+      }
+      else if (arg == "-") {
+        errorFn("'-' is not a valid argument.")
+        args
+      }
+      else
+        // we dispatch differently based on the appearance of p:
+        // 1) If it has a : it is presumed to be -Xfoo:bar,baz
+        // 2) If the first two chars are the name of a command, -Dfoo=bar
+        // 3) Otherwise, the whole string should be a command name
+        //
+        // Internally we use Option[List[String]] to discover error,
+        // but the outside expects our arguments back unchanged on failure
+        if (isPropertyArg(arg)) parsePropertyArg(arg) match {
+          case Some(_)  => rest
+          case None     => args
+        }
+        else if (arg contains ":") parseColonArg(arg) match {
+          case Some(_)  => rest
+          case None     => args
+        }
+        else parseNormalArg(arg, rest) match {
+          case Some(xs) => xs
+          case None     => args
+        }
+    }
+
+    doArgs(args)
+  }
+  
+  /** Initializes these settings for embedded use by type `T`.
+  * The class loader defining `T` should provide resources `app.class.path`
+  * and `boot.class.path`.  These resources should contain the application
+  * and boot classpaths in the same form as would be passed on the command line.*/
+  def embeddedDefaults[T: Manifest]: Unit =
+    embeddedDefaults(implicitly[Manifest[T]].erasure.getClassLoader)
+    
+  /** Initializes these settings for embedded use by a class from the given class loader.
+  * The class loader for `T` should provide resources `app.class.path`
+  * and `boot.class.path`.  These resources should contain the application
+  * and boot classpaths in the same form as would be passed on the command line.*/
+  def embeddedDefaults(loader: ClassLoader) {
+    explicitParentLoader = Option(loader) // for the Interpreter parentClassLoader
+    getClasspath("app", loader) foreach { classpath.value = _ }
+    getClasspath("boot", loader) foreach { bootclasspath append _ }
+  }
+  
+  /** The parent loader to use for the interpreter.*/
+  private[nsc] var explicitParentLoader: Option[ClassLoader] = None
+  
+  /** Retrieves the contents of resource "${id}.class.path" from `loader`
+  * (wrapped in Some) or None if the resource does not exist.*/
+  private def getClasspath(id: String, loader: ClassLoader): Option[String] =
+    Option(loader).flatMap(ld => Option(ld.getResource(id + ".class.path"))).map { cp =>
+       Source.fromURL(cp).mkString
+    }
+
+  // a wrapper for all Setting creators to keep our list up to date
+  private def add[T <: Setting](s: T): T = {
+    allSettings += s
+    s
+  }
+
+  def BooleanSetting(name: String, descr: String) = add(new BooleanSetting(name, descr))
+  def ChoiceSetting(name: String, descr: String, choices: List[String], default: String) =
+    add(new ChoiceSetting(name, descr, choices, default))
+  def DefinesSetting() = add(new DefinesSetting())
+  def IntSetting(name: String, descr: String, default: Int, range: Option[(Int, Int)], parser: String => Option[Int]) = add(new IntSetting(name, descr, default, range, parser))
+  def MultiStringSetting(name: String, arg: String, descr: String) = add(new MultiStringSetting(name, arg, descr))
+  def OutputSetting(outputDirs: OutputDirs, default: String) = add(new OutputSetting(outputDirs, default))
+  def PhasesSetting(name: String, descr: String) = add(new PhasesSetting(name, descr))
+  def StringSetting(name: String, arg: String, descr: String, default: String) = add(new StringSetting(name, arg, descr, default))
+  def PathSetting(name: String, arg: String, descr: String, default: String): PathSetting = {
+    val prepend = new StringSetting(name + "/p", "", "", "") with InternalSetting
+    val append = new StringSetting(name + "/a", "", "", "") with InternalSetting
+
+    add[StringSetting](prepend)
+    add[StringSetting](append)
+    add(new PathSetting(name, arg, descr, default, prepend, append))
+  }
+
+  // basically this is a value which remembers if it's been modified
+  trait SettingValue extends AbsSettingValue {
+    protected var v: T
+    protected var setByUser: Boolean = false
+    def postSetHook(): Unit
+    
+    def isDefault: Boolean = !setByUser
+    def value: T = v
+    def value_=(arg: T) = {
+      setByUser = true
+      v = arg
+      postSetHook()
+    }
+  }
+
+  /** A class for holding mappings from source directories to
+   *  their output location. This functionality can be accessed
+   *  only programmatically. The command line compiler uses a
+   *  single output location, but tools may use this functionality
+   *  to set output location per source directory.
+   */
+  class OutputDirs {
+    /** Pairs of source directory - destination directory. */
+    private var outputDirs: List[(AbstractFile, AbstractFile)] = Nil
+
+    /** If this is not None, the output location where all
+     *  classes should go.
+     */
+    private var singleOutDir: Option[AbstractFile] = None
+
+    /** Add a destination directory for sources found under srcdir.
+     *  Both directories should exits.
+     */
+    def add(srcDir: String, outDir: String): Unit =
+      add(checkDir(AbstractFile.getDirectory(srcDir), srcDir),
+          checkDir(AbstractFile.getDirectory(outDir), outDir))
+
+    /** Check that dir is exists and is a directory. */
+    private def checkDir(dir: AbstractFile, name: String): AbstractFile = {
+      if ((dir eq null) || !dir.isDirectory)
+        throw new FatalError(name + " does not exist or is not a directory")
+      dir
+    }
+
+    /** Set the single output directory. From now on, all files will
+     *  be dumped in there, regardless of previous calls to 'add'.
+     */
+    def setSingleOutput(outDir: String) {
+      val dst = AbstractFile.getDirectory(outDir)
+      setSingleOutput(checkDir(dst, outDir))
+    }
+
+    /** Set the single output directory. From now on, all files will
+     *  be dumped in there, regardless of previous calls to 'add'.
+     */
+    def setSingleOutput(dir: AbstractFile) {
+      singleOutDir = Some(dir)
+    }
+
+    def add(src: AbstractFile, dst: AbstractFile) {
+      singleOutDir = None
+      outputDirs ::= (src, dst)
+    }
+
+    /** Return the list of source-destination directory pairs. */
+    def outputs: List[(AbstractFile, AbstractFile)] = outputDirs
+
+    /** Return the output directory for the given file.
+     */
+    def outputDirFor(src: AbstractFile): AbstractFile = {
+      def isBelow(srcDir: AbstractFile, outDir: AbstractFile) =
+        src.path.startsWith(srcDir.path)
+
+      singleOutDir match {
+        case Some(d) => d
+        case None =>
+          (outputs find (isBelow _).tupled) match {
+            case Some((_, d)) => d
+            case _ =>
+              throw new FatalError("Could not find an output directory for "
+                                   + src.path + " in " + outputs)
+          }
+      }
+    }
+    
+    /** Return the source file path(s) which correspond to the given
+     *  classfile path and SourceFile attribute value, subject to the
+     *  condition that source files are arranged in the filesystem
+     *  according to Java package layout conventions.
+     *  
+     *  The given classfile path must be contained in at least one of
+     *  the specified output directories. If it does not then this
+     *  method returns Nil.
+     *  
+     *  Note that the source file is not required to exist, so assuming
+     *  a valid classfile path this method will always return a list
+     *  containing at least one element.
+     *  
+     *  Also that if two or more source path elements target the same
+     *  output directory there will be two or more candidate source file
+     *  paths. 
+     */
+    def srcFilesFor(classFile : AbstractFile, srcPath : String) : List[AbstractFile] = {
+      def isBelow(srcDir: AbstractFile, outDir: AbstractFile) =
+        classFile.path.startsWith(outDir.path)
+
+      singleOutDir match {
+        case Some(d) =>
+          d match {
+              case _: VirtualDirectory => Nil
+              case _                   => List(d.lookupPathUnchecked(srcPath, false))
+          }
+        case None =>
+          (outputs filter (isBelow _).tupled) match {
+            case Nil => Nil
+            case matches => matches.map(_._1.lookupPathUnchecked(srcPath, false))
+          }
+      }
+    }
+  }
+
+  /** A base class for settings of all types.
+   *  Subclasses each define a `value' field of the appropriate type.
+   */
+  abstract class Setting(val name: String, val helpDescription: String) extends AbsSetting with SettingValue with Mutable {
+    /** Will be called after this Setting is set for any extra work. */
+    private var _postSetHook: this.type => Unit = (x: this.type) => ()
+    def postSetHook(): Unit = _postSetHook(this)
+    def withPostSetHook(f: this.type => Unit): this.type = { _postSetHook = f ; this }
+
+    /** The syntax defining this setting in a help string */
+    private var _helpSyntax = name
+    override def helpSyntax: String = _helpSyntax
+    def withHelpSyntax(s: String): this.type    = { _helpSyntax = s ; this }
+    
+    /** Abbreviations for this setting */
+    private var _abbreviations: List[String] = Nil
+    override def abbreviations = _abbreviations
+    def withAbbreviation(s: String): this.type  = { _abbreviations ++= List(s) ; this }
+
+    /** Optional dependency on another setting */
+    private var dependency: Option[(Setting, String)] = None
+    override def dependencies = dependency.toList
+    def dependsOn(s: Setting, value: String): this.type = { dependency = Some((s, value)); this }
+  }
+
+  /** A setting represented by an integer */
+  class IntSetting private[nsc](
+    name: String,
+    descr: String,
+    val default: Int,
+    val range: Option[(Int, Int)],
+    parser: String => Option[Int])
+  extends Setting(name, descr) {
+    type T = Int
+    protected var v = default
+
+    // not stable values!
+    val IntMin = Int.MinValue
+    val IntMax = Int.MaxValue
+    def min = range map (_._1) getOrElse IntMin
+    def max = range map (_._2) getOrElse IntMax
+
+    override def value_=(s: Int) =
+      if (isInputValid(s)) super.value_=(s) else errorMsg
+
+    // Validate that min and max are consistent
+    assert(min <= max)
+
+    // Helper to validate an input
+    private def isInputValid(k: Int): Boolean = (min <= k) && (k <= max)
+
+    // Helper to generate a textual explaination of valid inputs
+    private def getValidText: String = (min, max) match {
+      case (IntMin, IntMax)   => "can be any integer"
+      case (IntMin, x)        => "must be less than or equal to "+x
+      case (x, IntMax)        => "must be greater than or equal to "+x
+      case _                  => "must be between %d and %d".format(min, max)
+    }
+
+    // Ensure that the default value is actually valid
+    assert(isInputValid(default))
+
+    def parseArgument(x: String): Option[Int] = {
+      parser(x) orElse {
+        try   { Some(x.toInt) }
+        catch { case _: NumberFormatException => None }
+      }
+    }
+
+    def errorMsg = errorFn("invalid setting for -"+name+" "+getValidText)
+
+    def tryToSet(args: List[String]) =
+      if (args.isEmpty) errorAndValue("missing argument", None)
+      else parseArgument(args.head) match {
+        case Some(i)  => value = i ; Some(args.tail)
+        case None     => errorMsg ; None
+      }
+
+    def unparse: List[String] =
+      if (value == default) Nil
+      else List(name, value.toString)
+  }
+
+  /** A setting represented by a boolean flag (false, unless set) */
+  class BooleanSetting private[nsc](
+    name: String,
+    descr: String)
+  extends Setting(name, descr) {
+    type T = Boolean
+    protected var v = false
+
+    def tryToSet(args: List[String]) = { value = true ; Some(args) }
+    def unparse: List[String] = if (value) List(name) else Nil
+    override def tryToSetFromPropertyValue(s : String) {
+      value = s.equalsIgnoreCase("true")
+    }
+  }
+
+  /** A setting represented by a string, (`default' unless set) */
+  class StringSetting private[nsc](
+    name: String,
+    val arg: String,
+    descr: String,
+    val default: String)
+  extends Setting(name, descr) {
+    type T = String
+    protected var v = default
+
+    def tryToSet(args: List[String]) = args match {
+      case Nil      => errorAndValue("missing argument", None)
+      case x :: xs  => value = x ; Some(xs)
+    }
+    def unparse: List[String] = if (value == default) Nil else List(name, value)
+
+    withHelpSyntax(name + " <" + arg + ">")
+  }
+  
+  class PathSetting private[nsc](
+    name: String,
+    arg: String,
+    descr: String,
+    default: String,
+    prependPath: StringSetting,
+    appendPath: StringSetting)
+  extends StringSetting(name, arg, descr, default) {
+    import util.ClassPath.join
+    def prepend(s: String) = prependPath.value = join(s, prependPath.value)
+    def append(s: String) = appendPath.value = join(appendPath.value, s)
+    
+    override def value = join(
+      prependPath.value,
+      super.value,
+      appendPath.value
+    )
+  }
+
+  /** Set the output directory. */
+  class OutputSetting private[nsc](
+    outputDirs: OutputDirs,
+    default: String)
+    extends StringSetting("-d", "directory", "Specify where to place generated class files", default) {
+      value = default
+      override def value_=(str: String) {
+        super.value_=(str)
+        outputDirs.setSingleOutput(str)
+      }
+  }
+
+  /** A setting that accumulates all strings supplied to it,
+   *  until it encounters one starting with a '-'. */
+  class MultiStringSetting private[nsc](
+    name: String,
+    val arg: String,
+    descr: String)
+  extends Setting(name, descr) {
+    type T = List[String]
+    protected var v: List[String] = Nil
+    def appendToValue(str: String) { value ++= List(str) }
+
+    def tryToSet(args: List[String]) = {
+      val (strings, rest) = args span (x => !x.startsWith("-"))
+      strings foreach appendToValue
+
+      Some(rest)
+    }
+    override def tryToSetColon(args: List[String]) = tryToSet(args)
+    override def tryToSetFromPropertyValue(s: String) = tryToSet(s.trim.split(" +").toList)
+    def unparse: List[String] = value map { name + ":" + _ }
+
+    withHelpSyntax(name + ":<" + arg + ">")
+  }
+
+  /** A setting represented by a string in a given set of <code>choices</code>,
+   *  (<code>default</code> unless set).
+   */
+  class ChoiceSetting private[nsc](
+    name: String,
+    descr: String,
+    override val choices: List[String],
+    val default: String)
+  extends Setting(name, descr + choices.mkString(" (", ",", ")")) {
+    type T = String
+    protected var v: String = default
+    protected def argument: String = name drop 1
+    def indexOfChoice: Int = choices indexOf value
+
+    def tryToSet(args: List[String]) = { value = default ; Some(args) }
+
+    override def tryToSetColon(args: List[String]) = args match {
+      case Nil                            => errorAndValue("missing " + argument, None)
+      case List(x) if choices contains x  => value = x ; Some(Nil)
+      case List(x)                        => errorAndValue("'" + x + "' is not a valid choice for '" + name + "'", None)
+      case xs                             => errorAndValue("'" + name + "' does not accept multiple arguments.", None)
+    }
+    def unparse: List[String] =
+      if (value == default) Nil else List(name + ":" + value)
+
+    withHelpSyntax(name + ":<" + argument + ">")
+  }
+
+  /** A setting represented by a list of strings which should be prefixes of
+   *  phase names. This is not checked here, however.  Alternatively the string
+   *  "all" can be used to represent all phases.
+   *  (the empty list, unless set)
+   */
+  class PhasesSetting private[nsc](
+    name: String,
+    descr: String)
+  extends Setting(name, descr + " <phase> or \"all\"") {
+    type T = List[String]
+    protected var v: List[String] = Nil
+    override def value = if (v contains "all") List("all") else super.value
+
+    def tryToSet(args: List[String]) = errorAndValue("missing phase", None)
+    override def tryToSetColon(args: List[String]) = args match {
+      case Nil  => errorAndValue("missing phase", None)
+      case xs   => value = (value ++ xs).distinct.sorted ; Some(Nil)
+    }
+    // we slightly abuse the usual meaning of "contains" here by returning
+    // true if our phase list contains "all", regardless of the incoming argument
+    def contains(phasename: String): Boolean =
+      doAllPhases || (value exists { phasename startsWith _ } )
+
+    def doAllPhases() = value contains "all"
+    def unparse: List[String] = value map { name + ":" + _ }
+
+    withHelpSyntax(name + ":<phase>")
+  }
+
+  /** A setting for a -D style property definition */
+  class DefinesSetting private[nsc] extends Setting("-D", "set a Java property") {
+    type T = List[(String, String)]
+    protected var v: T = Nil
+    withHelpSyntax(name + "<prop>")
+
+    // given foo=bar returns Some(foo, bar), or None if parse fails
+    def parseArg(s: String): Option[(String, String)] = {
+      if (s == "") return None
+      val idx = s indexOf '='
+      
+      if (idx < 0) Some(s, "")
+      else Some(s take idx, s drop (idx + 1))
+    }
+
+    protected[nsc] override def tryToSetProperty(args: List[String]): Option[List[String]] =
+      tryToSet(args)
+
+    def tryToSet(args: List[String]) =
+      if (args.isEmpty) None
+      else parseArg(args.head) match {
+        case None         => None
+        case Some((a, b)) => value = value ++ List((a, b)) ; Some(args.tail)
+      }
+
+    def unparse: List[String] =
+      value map { case (k,v) => "-D" + k + (if (v == "") "" else "=" + v) }
+    
+    /** Apply the specified properties to the current JVM and returns them. */
+    def applyToJVM() = {
+      value foreach { case (k, v) => System.getProperties.setProperty(k, v) }
+      value
+    }
+  }
+}
diff --git a/src/compiler/scala/tools/nsc/settings/ScalaSettings.scala b/src/compiler/scala/tools/nsc/settings/ScalaSettings.scala
new file mode 100644
index 0000000..1a02b4c
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/settings/ScalaSettings.scala
@@ -0,0 +1,163 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
+ * @author  Martin Odersky
+ */
+// $Id$
+
+package scala.tools
+package nsc
+package settings
+
+import annotation.elidable
+import scala.tools.util.PathResolver.Defaults
+import scala.collection.mutable.HashSet
+
+trait ScalaSettings extends AbsScalaSettings with StandardScalaSettings {
+  self: MutableSettings =>
+  
+  import Defaults.scalaUserClassPath
+
+  /** Set of settings */
+  protected lazy val allSettings = HashSet[Setting]()
+
+  /** Disable a setting */
+  def disable(s: Setting) = allSettings -= s
+
+  /**
+   *  Temporary Settings
+   */
+  val suppressVTWarn = BooleanSetting    ("-Ysuppress-vt-typer-warnings", "Suppress warnings from the typer when testing the virtual class encoding, NOT FOR FINAL!")
+
+  /**
+   *  Standard settings
+   */
+  // argfiles is only for the help message
+  val argfiles      = BooleanSetting    ("@<file>", "A text file containing compiler arguments (options and source files)")
+  val classpath     = PathSetting       ("-classpath", "path", "Specify where to find user class files", scalaUserClassPath) .
+                                            withAbbreviation ("-cp")
+  val d             = OutputSetting     (outputDirs, ".")
+  val defines       = DefinesSetting()
+  val optimise      = BooleanSetting    ("-optimise", "Generates faster bytecode by applying optimisations to the program") . 
+                                            withAbbreviation("-optimize") .
+                                            withPostSetHook(_ => List(inline, Xcloselim, Xdce) foreach (_.value = true))
+  val nospecialization = BooleanSetting    ("-no-specialization", "Ignore @specialize annotations.")
+
+
+  /**
+   * -X "Advanced" settings
+   */
+  val Xhelp         = BooleanSetting    ("-X", "Print a synopsis of advanced options")
+  val assemname     = StringSetting     ("-Xassem-name", "file", "Name of the output assembly (only relevant with -target:msil)", "").dependsOn(target, "msil")
+  val assemrefs     = StringSetting     ("-Xassem-path", "path", "List of assemblies referenced by the program (only relevant with -target:msil)", ".").dependsOn(target, "msil")
+  val assemextdirs  = StringSetting     ("-Xassem-extdirs", "dirs", "List of directories containing assemblies, defaults to `lib'", Defaults.scalaLibDir.path).dependsOn(target, "msil")
+  val sourcedir     = StringSetting     ("-Xsourcedir", "directory", "When -target:msil, the source folder structure is mirrored in output directory.", ".").dependsOn(target, "msil")
+  val checkInit     = BooleanSetting    ("-Xcheckinit", "Add runtime checks on field accessors. Uninitialized accesses result in an exception being thrown.")
+  val noassertions  = BooleanSetting    ("-Xdisable-assertions", "Generate no assertions and assumptions")
+  val elidebelow    = IntSetting        ("-Xelide-below", "Generate calls to @elidable-marked methods only if method priority is greater than argument.",
+                                                elidable.ASSERTION, None, elidable.byName.get(_))
+  val noForwarders  = BooleanSetting    ("-Xno-forwarders", "Do not generate static forwarders in mirror classes")
+  val future        = BooleanSetting    ("-Xfuture", "Turn on future language features")
+  val genPhaseGraph = StringSetting     ("-Xgenerate-phase-graph", "file", "Generate the phase graphs (outputs .dot files) to fileX.dot", "")
+  val XlogImplicits = BooleanSetting    ("-Xlog-implicits", "Show more info on why some implicits are not applicable")
+  val Xmigration28  = BooleanSetting    ("-Xmigration", "Warn about constructs whose behavior may have changed between 2.7 and 2.8")
+  val nouescape     = BooleanSetting    ("-Xno-uescape", "Disables handling of \\u unicode escapes")
+  val Xnojline      = BooleanSetting    ("-Xnojline", "Do not use JLine for editing")
+  val plugin        = MultiStringSetting("-Xplugin", "file", "Load a plugin from a file")
+  val disable       = MultiStringSetting("-Xplugin-disable", "plugin", "Disable a plugin")
+  val showPlugins   = BooleanSetting    ("-Xplugin-list", "Print a synopsis of loaded plugins")
+  val require       = MultiStringSetting("-Xplugin-require", "plugin", "Abort unless a plugin is available")
+  val pluginsDir    = StringSetting     ("-Xpluginsdir", "path", "Path to search compiler plugins", Defaults.scalaPluginPath)
+  val Xprint        = PhasesSetting     ("-Xprint", "Print out program after")
+  val writeICode    = BooleanSetting    ("-Xprint-icode", "Log internal icode to *.icode files")
+  val Xprintpos     = BooleanSetting    ("-Xprint-pos", "Print tree positions (as offsets)")
+  val printtypes    = BooleanSetting    ("-Xprint-types", "Print tree types (debugging option)")
+  val prompt        = BooleanSetting    ("-Xprompt", "Display a prompt after each error (debugging option)")
+  val resident      = BooleanSetting    ("-Xresident", "Compiler stays resident, files to compile are read from standard input")
+  val script        = StringSetting     ("-Xscript", "object", "Compile as a script, wrapping the code into object.main()", "")
+  val Xshowcls      = StringSetting     ("-Xshow-class", "class", "Show class info", "")
+  val Xshowobj      = StringSetting     ("-Xshow-object", "object", "Show object info", "")
+  val showPhases    = BooleanSetting    ("-Xshow-phases", "Print a synopsis of compiler phases")
+  val sourceReader  = StringSetting     ("-Xsource-reader", "classname", "Specify a custom method for reading source files", "scala.tools.nsc.io.SourceReader")
+
+  val Xwarnfatal    = BooleanSetting    ("-Xfatal-warnings", "Fail the compilation if there are any warnings.")
+  val Xwarninit     = BooleanSetting    ("-Xwarninit", "Warn about possible changes in initialization semantics")
+  val Xchecknull    = BooleanSetting    ("-Xcheck-null", "Emit warning on selection of nullable reference")
+
+  // Experimental Extensions
+  val Xexperimental = BooleanSetting    ("-Xexperimental", "Enable experimental extensions") .
+                          withPostSetHook(_ => List(YdepMethTpes, YmethodInfer) foreach (_.value = true)) //YvirtClasses, 
+  val YdepMethTpes  = BooleanSetting    ("-Ydependent-method-types", "Allow dependent method types")
+  val YmethodInfer  = BooleanSetting    ("-Yinfer-argument-types", "Infer types for arguments of overriden methods")
+  val YvirtClasses  = false // too embryonic to even expose as a -Y //BooleanSetting    ("-Yvirtual-classes", "Support virtual classes")
+
+  /** Compatibility stubs for options whose value name did
+   *  not previously match the option name.
+   */
+  def XO = optimise
+  def debuginfo = g
+  def dependenciesFile = dependencyfile
+  def nowarnings = nowarn
+  def outdir = d
+  def printLate = print
+
+  /**
+   * -Y "Private" settings
+   */
+  val Yhelp         = BooleanSetting    ("-Y", "Print a synopsis of private options")
+  val browse        = PhasesSetting     ("-Ybrowse", "Browse the abstract syntax tree after")
+  val check         = PhasesSetting     ("-Ycheck", "Check the tree at the end of")
+  val Xcloselim     = BooleanSetting    ("-Yclosure-elim", "Perform closure elimination")
+  val Ycompacttrees = BooleanSetting    ("-Ycompact-trees", "Use compact tree printer when displaying trees")
+  val noCompletion  = BooleanSetting    ("-Yno-completion", "Disable tab-completion in the REPL")
+  val Xdce          = BooleanSetting    ("-Ydead-code", "Perform dead code elimination")
+  val debug         = BooleanSetting    ("-Ydebug", "Output debugging messages")
+  val Xdetach       = BooleanSetting    ("-Ydetach", "Perform detaching of remote closures")
+  // val doc           = BooleanSetting    ("-Ydoc", "Generate documentation")
+  val inline        = BooleanSetting    ("-Yinline", "Perform inlining when possible")
+  val Xlinearizer   = ChoiceSetting     ("-Ylinearizer", "Linearizer to use", List("normal", "dfs", "rpo", "dump"), "rpo") .
+                                          withHelpSyntax("-Ylinearizer:<which>")
+  val log           = PhasesSetting     ("-Ylog", "Log operations in")
+  val Ylogcp        = BooleanSetting    ("-Ylog-classpath", "Output information about what classpath is being applied.")
+  val Ynogenericsig = BooleanSetting    ("-Yno-generic-signatures", "Suppress generation of generic signatures for Java")
+  val noimports     = BooleanSetting    ("-Yno-imports", "Compile without any implicit imports")
+  val nopredefs     = BooleanSetting    ("-Yno-predefs", "Compile without any implicit predefined values")
+  val Yrecursion    = IntSetting        ("-Yrecursion", "Recursion depth used when locking symbols", 0, Some(0, Int.MaxValue), (_: String) => None)
+  val selfInAnnots  = BooleanSetting    ("-Yself-in-annots", "Include a \"self\" identifier inside of annotations")
+  val Xshowtrees    = BooleanSetting    ("-Yshow-trees", "Show detailed trees when used in connection with -print:phase")
+  val skip          = PhasesSetting     ("-Yskip", "Skip")
+  val Xsqueeze      = ChoiceSetting     ("-Ysqueeze", "if on, creates compact code in matching", List("on","off"), "on") .
+                                          withHelpSyntax("-Ysqueeze:<enabled>")
+  val Ystatistics   = BooleanSetting    ("-Ystatistics", "Print compiler statistics")
+  val stop          = PhasesSetting     ("-Ystop", "Stop after phase")
+  val refinementMethodDispatch =
+                      ChoiceSetting     ("-Ystruct-dispatch", "Selects dispatch method for structural refinement method calls",
+                        List("no-cache", "mono-cache", "poly-cache", "invoke-dynamic"), "poly-cache") .
+                        withHelpSyntax("-Ystruct-dispatch:<method>")
+  val Yrangepos     = BooleanSetting    ("-Yrangepos", "Use range positions for syntax trees.")
+  val Yidedebug     = BooleanSetting    ("-Yide-debug", "Generate, validate and output trees using the interactive compiler.")
+  val Ybuilderdebug = ChoiceSetting     ("-Ybuilder-debug", "Compile using the specified build manager", List("none", "refined", "simple"), "none") .
+                        withHelpSyntax("-Ybuilder-debug:<method>")
+  val Ybuildmanagerdebug = 
+                      BooleanSetting    ("-Ybuild-manager-debug", "Generate debug information for the Refined Build Manager compiler.")
+  val Ytyperdebug   = BooleanSetting    ("-Ytyper-debug", "Trace all type assignements")
+  val Ypmatdebug    = BooleanSetting    ("-Ypmat-debug", "Trace all pattern matcher activity.")
+  val Yrepldebug    = BooleanSetting    ("-Yrepl-debug", "Trace all repl activity.")
+  val Ycompletion   = BooleanSetting    ("-Ycompletion-debug", "Trace all tab completion activity.")
+  val Ypmatnaive    = BooleanSetting    ("-Ypmat-naive", "Desugar matches as naively as possible..")
+  // val Yjenkins      = BooleanSetting    ("-Yjenkins-hashCodes", "Use jenkins hash algorithm for case class generated hashCodes.")
+  val Ynotnull      = BooleanSetting    ("-Ynotnull", "Enable the experimental and incomplete scala.NotNull")
+
+  // Warnings
+  val Ywarndeadcode = BooleanSetting    ("-Ywarn-dead-code", "Emit warnings for dead code")
+
+  /**
+   * "fsc-specific" settings.
+   */
+  val fscShutdown   = BooleanSetting    ("-shutdown", "Shutdown the fsc daemon")
+
+  /**
+   * -P "Plugin" settings
+   */
+  val pluginOptions = MultiStringSetting("-P", "plugin:opt", "Pass an option to a plugin") .
+                        withHelpSyntax("-P:<plugin>:<opt>")
+}
diff --git a/src/compiler/scala/tools/nsc/settings/StandardScalaSettings.scala b/src/compiler/scala/tools/nsc/settings/StandardScalaSettings.scala
new file mode 100644
index 0000000..fe29b36
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/settings/StandardScalaSettings.scala
@@ -0,0 +1,54 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
+ * @author  Paul Phillips
+ */
+
+package scala.tools.nsc
+package settings
+
+import scala.tools.util.PathResolver.Defaults
+
+/** Settings which aren't behind a -X, -Y, or -P option.
+ *  When possible, the val and the option have identical names.
+ *  The abstract settings are commented as to why they are as yet
+ *  implemented in MutableSettings rather than mutation-generically.
+ */
+trait StandardScalaSettings {
+  self: AbsScalaSettings =>
+  
+  /** Path related settings.
+   */
+  val bootclasspath =     PathSetting ("-bootclasspath", "path", "Override location of bootstrap class files", Defaults.scalaBootClassPath)
+  val classpath:          PathSetting // is mutated directly in various places (thus inspiring this very effort)
+  val d:                OutputSetting // depends on mutable OutputDirs class
+  val extdirs =           PathSetting ("-extdirs", "dirs", "Override location of installed extensions", Defaults.scalaExtDirs)
+  val javabootclasspath = PathSetting ("-javabootclasspath", "path", "Override java boot classpath.", Defaults.javaBootClassPath)
+  val javaextdirs =       PathSetting ("-javaextdirs", "path", "Override java extdirs classpath.", Defaults.javaExtDirs)
+  val sourcepath =      StringSetting ("-sourcepath", "path", "Specify where to find input source files", "")
+
+  /** Other settings.
+   */
+  val dependencyfile =  StringSetting ("-dependencyfile", "file", "Specify the file in which dependencies are tracked", ".scala_dependencies")
+  val deprecation =    BooleanSetting ("-deprecation", "Output source locations where deprecated APIs are used")
+  val encoding =        StringSetting ("-encoding", "encoding", "Specify character encoding used by source files", Properties.sourceEncoding)
+  val explaintypes =   BooleanSetting ("-explaintypes", "Explain type errors in more detail")
+  val g =               ChoiceSetting ("-g", "Specify level of generated debugging info", List("none", "source", "line", "vars", "notailcalls"), "vars")
+  val help =           BooleanSetting ("-help", "Print a synopsis of standard options")
+  val make =            ChoiceSetting ("-make", "Specify recompilation detection strategy", List("all", "changed", "immediate", "transitive", "transitivenocp"), "all") .
+                                          withHelpSyntax("-make:<strategy>")
+  val nowarn =         BooleanSetting ("-nowarn", "Generate no warnings")
+  val optimise:        BooleanSetting // depends on post hook which mutates other settings
+  val print =          BooleanSetting ("-print", "Print program with all Scala-specific features removed")
+  val target =          ChoiceSetting ("-target", "Specify for which target object files should be built", List("jvm-1.5", "msil"), "jvm-1.5")
+  val unchecked =      BooleanSetting ("-unchecked", "Enable detailed unchecked warnings")
+  val uniqid =         BooleanSetting ("-uniqid", "Print identifiers with unique names for debugging")
+  val usejavacp =      BooleanSetting ("-usejavacp", "Utilize the java.class.path in classpath resolution.")
+  val verbose =        BooleanSetting ("-verbose", "Output messages about what the compiler is doing")
+  val version =        BooleanSetting ("-version", "Print product version and exit")
+
+  /** These are @<file> and -Dkey=val style settings, which don't
+   *  nicely map to identifiers.
+   */
+  val argfiles: BooleanSetting  // exists only to echo help message, should be done differently
+  val defines: DefinesSetting   // not entirely clear that DefinesSetting makes sense as a Setting
+}
diff --git a/src/compiler/scala/tools/nsc/symtab/AnnotationCheckers.scala b/src/compiler/scala/tools/nsc/symtab/AnnotationCheckers.scala
index d865b28..95b4134 100644
--- a/src/compiler/scala/tools/nsc/symtab/AnnotationCheckers.scala
+++ b/src/compiler/scala/tools/nsc/symtab/AnnotationCheckers.scala
@@ -1,10 +1,10 @@
 /* NSC -- new Scala compiler
- * Copyright 2007-2009 LAMP/EPFL
+ * Copyright 2007-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: AnnotationCheckers.scala 16881 2009-01-09 16:28:11Z cunei $
 
-package scala.tools.nsc.symtab
+package scala.tools.nsc
+package symtab
 
 /** Additions to the type checker that can be added at
  *  run time.  Typically these are added by
@@ -20,9 +20,33 @@ trait AnnotationCheckers {
     /** Check the annotations on two types conform. */
     def annotationsConform(tpe1: Type, tpe2: Type): Boolean
 
+    /** Refine the computed least upper bound of a list of types. 
+     *  All this should do is add annotations. */
+    def annotationsLub(tp: Type, ts: List[Type]): Type = tp
+
+    /** Refine the computed greatest lower bound of a list of types. 
+     *  All this should do is add annotations. */
+    def annotationsGlb(tp: Type, ts: List[Type]): Type = tp
+
+    /** Refine the bounds on type parameters to the given type arguments. */
+    def adaptBoundsToAnnotations(bounds: List[TypeBounds],
+      tparams: List[Symbol], targs: List[Type]): List[TypeBounds] = bounds
+
     /** Modify the type that has thus far been inferred
      *  for a tree.  All this should do is add annotations. */
     def addAnnotations(tree: Tree, tpe: Type): Type = tpe
+    
+    /** Decide whether this annotation checker can adapt a tree
+     *  that has an annotated type to the given type tp, taking
+     *  into account the given mode (see method adapt in trait Typers).*/
+    def canAdaptAnnotations(tree: Tree, mode: Int, pt: Type): Boolean = false
+
+    /** Adapt a tree that has an annotated type to the given type tp,
+     *  taking into account the given mode (see method adapt in trait Typers).
+     *  An implementation cannot rely on canAdaptAnnotations being called
+     *  before. If the implementing class cannot do the adaptiong, it
+     *  should return the tree unchanged.*/
+    def adaptAnnotations(tree: Tree, mode: Int, pt: Type): Tree = tree
   }
 
   /** The list of annotation checkers that have been registered */
@@ -43,18 +67,54 @@ trait AnnotationCheckers {
   /** Check that the annotations on two types conform.  To do
    *  so, consult all registered annotation checkers. */
   def annotationsConform(tp1: Type, tp2: Type): Boolean = {
-    /* Finish quickly if there are no attributes */
-    if (tp1.attributes.isEmpty && tp2.attributes.isEmpty)
+    /* Finish quickly if there are no annotations */
+    if (tp1.annotations.isEmpty && tp2.annotations.isEmpty)
       true
     else
      annotationCheckers.forall(
        _.annotationsConform(tp1,tp2))
   }
 
+  /** Refine the computed least upper bound of a list of types. 
+   *  All this should do is add annotations. */
+  def annotationsLub(tpe: Type, ts: List[Type]): Type = {
+    annotationCheckers.foldLeft(tpe)((tpe, checker) => 
+      checker.annotationsLub(tpe, ts))
+  }
+
+  /** Refine the computed greatest lower bound of a list of types. 
+   *  All this should do is add annotations. */
+  def annotationsGlb(tpe: Type, ts: List[Type]): Type = {
+    annotationCheckers.foldLeft(tpe)((tpe, checker) => 
+      checker.annotationsGlb(tpe, ts))
+  }
+
+  /** Refine the bounds on type parameters to the given type arguments. */
+  def adaptBoundsToAnnotations(bounds: List[TypeBounds],
+    tparams: List[Symbol], targs: List[Type]): List[TypeBounds] = {
+      annotationCheckers.foldLeft(bounds)((bounds, checker) => 
+        checker.adaptBoundsToAnnotations(bounds, tparams, targs))
+  }
+
   /** Let all annotations checkers add extra annotations
    *  to this tree's type. */
   def addAnnotations(tree: Tree, tpe: Type): Type = {
     annotationCheckers.foldLeft(tpe)((tpe, checker) => 
       checker.addAnnotations(tree, tpe))
   }
+
+  /** Find out whether any annotation checker can adapt a tree
+   *  to a given type. Called by Typers.adapt. */
+  def canAdaptAnnotations(tree: Tree, mode: Int, pt: Type): Boolean = {
+    annotationCheckers.exists(_.canAdaptAnnotations(tree, mode, pt))
+  }
+
+  /** Let registered annotation checkers adapt a tree
+   *  to a given type (called by Typers.adapt). Annotation checkers
+   *  that cannot do the adaption should pass the tree through
+   *  unchanged. */
+  def adaptAnnotations(tree: Tree, mode: Int, pt: Type): Tree = {
+    annotationCheckers.foldLeft(tree)((tree, checker) => 
+      checker.adaptAnnotations(tree, mode, pt))
+  }
 }
diff --git a/src/compiler/scala/tools/nsc/symtab/AnnotationInfos.scala b/src/compiler/scala/tools/nsc/symtab/AnnotationInfos.scala
index 2ae67d4..2429f53 100644
--- a/src/compiler/scala/tools/nsc/symtab/AnnotationInfos.scala
+++ b/src/compiler/scala/tools/nsc/symtab/AnnotationInfos.scala
@@ -1,118 +1,150 @@
 /* NSC -- new Scala compiler
- * Copyright 2007-2009 LAMP/EPFL
+ * Copyright 2007-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: AnnotationInfos.scala 16881 2009-01-09 16:28:11Z cunei $
 
-package scala.tools.nsc.symtab
+package scala.tools.nsc
+package symtab
 
 import scala.tools.nsc.transform.Reifiers
 import util._
 
 /** AnnotationInfo and its helpers */
-trait AnnotationInfos {
-  self: SymbolTable =>
-
-  /** Convert a tree to a Constant, if possible */
-  private def tree2cons(tree: Tree): Option[Constant] =
-    tree match {
-      case Literal(v) => Some(v)
-
-      case Apply(
-        TypeApply(
-          meth at Select(_,_),
-	  List(elemType)),
-	members)
-      if (definitions.ArrayModule_apply.alternatives contains meth.symbol) =>
-	trees2consArray(members, tree.tpe)
-			    
-
-      case Apply(meth, members) 
-      if (definitions.ArrayModule_apply.alternatives contains meth.symbol) =>
- 	trees2consArray(members, tree.tpe)
-
-      case Typed(t, _) => tree2cons(t)
-        
-      case tree =>
-        //println("could not convert: " + tree);
-        None
-    }
-  
-  private def trees2consArray(trees: Seq[Tree], arrayType:Type)
-  : Option[Constant] =
-  {
-    val mems = trees.map(tree2cons)
-
-    if (mems.exists(_.isEmpty))
-      None
-    else
-      Some(new ArrayConstant(
-	mems.map(_.get).toArray,
-	arrayType))
-  }
-
-
-  /** An argument to an annotation.  It includes a parse tree,
-   *  and it includes a compile-time constant for the tree if possible.
+trait AnnotationInfos extends reflect.generic.AnnotationInfos { self: SymbolTable =>
+
+  /** Arguments to classfile annotations (which are written to
+   *  bytecode as java annotations) are either:
+   *  <ul>
+   *   <li>constants</li>
+   *   <li>arrays of constants</li>
+   *   <li>or nested classfile annotations</li>
+   *  </ul>
    */
-  class AnnotationArgument(val intTree: Tree) {
-    def this(cons: Constant) = this(
-      Literal(cons).setType(cons.tpe))
-
+  abstract class ClassfileAnnotArg
 
-    @deprecated
-    lazy val tree = {
-      object reifiers extends {
-	val symbols: AnnotationInfos.this.type = AnnotationInfos.this
-      } with Reifiers
+  /** Represents a compile-time Constant (Boolean, Byte, Short,
+   *  Char, Int, Long, Float, Double, String, java.lang.Class or
+   *  an instance of a Java enumeration value).
+   */
+  case class LiteralAnnotArg(const: Constant)
+  extends ClassfileAnnotArg {
+    override def toString = const.escapedStringValue
+  }
 
-      reifiers.reify(intTree) 
-    }
+  object LiteralAnnotArg extends LiteralAnnotArgExtractor
 
-    val constant: Option[Constant] = tree2cons(intTree)
+  /** Represents an array of classfile annotation arguments */
+  case class ArrayAnnotArg(args: Array[ClassfileAnnotArg])
+  extends ClassfileAnnotArg {
+    override def toString = args.mkString("[", ", ", "]")
+  }
 
-    def isConstant = !constant.isEmpty
+  object ArrayAnnotArg extends ArrayAnnotArgExtractor
+
+  /** A specific annotation argument that encodes an array of bytes as an array of `Long`. The type of the argument
+    * declared in the annotation must be `String`. This specialised class is used to encode scala signatures for
+    * reasons of efficiency, both in term of class-file size and in term of compiler performance. */
+  case class ScalaSigBytes(bytes: Array[Byte]) extends ClassfileAnnotArg {
+    override def toString = (bytes map { byte => (byte & 0xff).toHexString }).mkString("[ ", " ", " ]")
+    lazy val encodedBytes =
+      reflect.generic.ByteCodecs.encode(bytes)
+    def isLong: Boolean = (encodedBytes.length > 65535)
+    def sigAnnot: Type =
+      if (this.isLong)
+        definitions.ScalaLongSignatureAnnotation.tpe
+      else
+        definitions.ScalaSignatureAnnotation.tpe
+  }
 
-    override def toString: String =
-      constant match { 
-        case Some(cons) => cons.escapedStringValue
-        case None => intTree.toString
-      }
+  /** Represents a nested classfile annotation */
+  case class NestedAnnotArg(annInfo: AnnotationInfo)
+  extends ClassfileAnnotArg {
+    // The nested annotation should not have any Scala annotation arguments
+    assert(annInfo.args.isEmpty, annInfo.args)
+    override def toString = annInfo.toString
   }
 
-  /** Typed information about an annotation.  It can be attached to
-   *  either a symbol or an annotated type.
+  object NestedAnnotArg extends NestedAnnotArgExtractor
+
+  class AnnotationInfoBase
+
+  /** <p>
+   *    Typed information about an annotation. It can be attached to
+   *    either a symbol or an annotated type.
+   *  </p>
+   *  <p>
+   *    Annotations are written to the classfile as java annotations
+   *    if <code>atp</code> conforms to <code>ClassfileAnnotation</code>
+   *    (the classfile parser adds this interface to any Java annotation
+   *    class).
+   *  </p>
+   *  <p>
+   *    Annotations are pickled (written to scala symtab attribute
+   *    in the classfile) if <code>atp</code> inherits form
+   *    <code>StaticAnnotation</code>.
+   *  </p>
+   *  <p>
+   *    <code>args</code> stores arguments to Scala annotations,
+   *    represented as  typed trees. Note that these trees are not
+   *    transformed by any phases following the type-checker.
+   *  </p>
+   *  <p>
+   *    <code>assocs</code> stores arguments to classfile annotations
+   *    as name-value pairs.
+   *  </p>
    */
-  case class AnnotationInfo(
-    atp: Type,
-    args: List[AnnotationArgument], 
-    assocs: List[(Name, AnnotationArgument)])
-  {
-    override def toString: String =
-      atp +
-      (if (args.isEmpty) "" 
-       else args.mkString("(", ", ", ")")) +
-      (if (assocs.isEmpty) "" 
-       else (assocs map { case (x, y) => x+" = "+y } mkString ("{", ", ", "}")))
-
-    /** Check whether all arguments and assocations are constants */
-    def isConstant =
-      ((args forall (_.isConstant)) &&
-       (assocs map (_._2) forall (_.isConstant)))
+  case class AnnotationInfo(atp: Type, args: List[Tree],
+                            assocs: List[(Name, ClassfileAnnotArg)])
+  extends AnnotationInfoBase {
+
+    // Classfile annot: args empty. Scala annot: assocs empty.
+    assert(args.isEmpty || assocs.isEmpty)
+
+    private var rawpos: Position = NoPosition
+    def pos = rawpos
+    def setPos(pos: Position): this.type = {
+      rawpos = pos
+      this
+    }
+
+    override def toString: String = atp +
+      (if (!args.isEmpty) args.mkString("(", ", ", ")") else "") +
+      (if (!assocs.isEmpty) (assocs map { case (x, y) => x+" = "+y } mkString ("(", ", ", ")")) else "")
 
     /** Check whether the type or any of the arguments are erroneous */
-    def isErroneous = atp.isErroneous || args.exists(_.intTree.isErroneous)
+    def isErroneous = atp.isErroneous || args.exists(_.isErroneous)
 
     /** Check whether any of the arguments mention a symbol */
     def refsSymbol(sym: Symbol) =
-      args.exists(_.intTree.exists(_.symbol == sym))
+      args.exists(_.exists(_.symbol == sym))
 
     /** Change all ident's with Symbol "from" to instead use symbol "to" */
     def substIdentSyms(from: Symbol, to: Symbol) = {
       val subs = new TreeSymSubstituter(List(from), List(to))
-      AnnotationInfo(atp,
-		     args.map(arg => new AnnotationArgument(subs(arg.intTree))),
-		     assocs)
+      AnnotationInfo(atp, args.map(subs(_)), assocs).setPos(pos)
     }
+
+    // !!! when annotation arguments are not literal strings, but any sort of
+    // assembly of strings, there is a fair chance they will turn up here not as
+    // Literal(const) but some arbitrary AST.
+    def stringArg(index: Int): Option[String] = if(args.size > index) Some(args(index) match {
+      case Literal(const) => const.stringValue
+      case x              => x.toString // should not be necessary, but better than silently ignoring an issue
+    }) else None
+
+    def intArg(index: Int): Option[Int] = if(args.size > index) Some(args(index)) collect {
+      case Literal(Constant(x: Int)) => x
+    } else None
   }
+
+  object AnnotationInfo extends AnnotationInfoExtractor
+
+  lazy val classfileAnnotArgManifest: ClassManifest[ClassfileAnnotArg] =
+    reflect.ClassManifest.classType(classOf[ClassfileAnnotArg])
+
+  /** Symbol annotations parsed in Namer (typeCompleter of
+   *  definitions) have to be lazy (#1782)
+   */
+  case class LazyAnnotationInfo(annot: () => AnnotationInfo)
+  extends AnnotationInfoBase
 }
diff --git a/src/compiler/scala/tools/nsc/symtab/BaseTypeSeqs.scala b/src/compiler/scala/tools/nsc/symtab/BaseTypeSeqs.scala
index 5d5b77f..f8ddf31 100644
--- a/src/compiler/scala/tools/nsc/symtab/BaseTypeSeqs.scala
+++ b/src/compiler/scala/tools/nsc/symtab/BaseTypeSeqs.scala
@@ -1,11 +1,14 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-package scala.tools.nsc.symtab
+package scala.tools.nsc
+package symtab
 
-import scala.collection.mutable.ListBuffer
-import Math.max
+// todo implement in terms of BitSet
+import scala.collection.mutable.{ListBuffer, BitSet}
+import math.max
+import util.Statistics._
 
 /** A base type sequence (BaseTypeSeq) is an ordered sequence spanning all the base types
  *  of a type. It characterized by the following two laws:
@@ -27,54 +30,68 @@ trait BaseTypeSeqs {
   import definitions._
 
   class BaseTypeSeq(parents: List[Type], elems: Array[Type]) {
+  self =>
+    incCounter(baseTypeSeqCount)
+    incCounter(baseTypeSeqLenTotal, elems.length)
 
     /** The number of types in the sequence */
     def length: Int = elems.length
 
+    // #3676 shows why we can't store NoType in elems to mark cycles
+    // (while NoType is in there to indicate a cycle in this BTS, during the execution of
+    //  the mergePrefixAndArgs below, the elems get copied without the pending map,
+    //  so that NoType's are seen instead of the original type --> spurious compile error)
+    val pending = new BitSet(length)
+
     /** The type at i'th position in this sequence; lazy types are returned evaluated. */
-    def apply(i: Int): Type = elems(i) match {
-      case NoType =>
-        elems(i) = AnyClass.tpe
-        throw CyclicInheritance 
-      case rtp @ RefinedType(variants, decls) =>
-        // can't assert decls.isEmpty; see t0764
-        //if (!decls.isEmpty) assert(false, "computing closure of "+this+":"+this.isInstanceOf[RefinedType]+"/"+closureCache(j))
-        //Console.println("compute closure of "+this+" => glb("+variants+")")
-        elems(i) = NoType
-        try {
-          mergePrefixAndArgs(variants, -1, lubDepth(variants)) match {
-            case Some(tp0) => 
-              elems(i) = tp0
-              tp0
-            case None => 
-              typeError(
-                "no common type instance of base types "+(variants mkString ", and ")+" exists.")
-          }
-        } catch {
-          case CyclicInheritance =>
-            typeError(
-              "computing the common type instance of base types "+(variants mkString ", and ")+" leads to a cycle.")
-        } 
-      case tp =>
-        tp
-    }
+    def apply(i: Int): Type =
+      if(pending contains i) {
+        pending.clear()
+        throw CyclicInheritance
+      } else
+        elems(i) match {
+          case rtp @ RefinedType(variants, decls) =>
+            // can't assert decls.isEmpty; see t0764
+            //if (!decls.isEmpty) assert(false, "computing closure of "+this+":"+this.isInstanceOf[RefinedType]+"/"+closureCache(j))
+            //Console.println("compute closure of "+this+" => glb("+variants+")")
+            pending += i
+            try {
+              mergePrefixAndArgs(variants, -1, lubDepth(variants)) match {
+                case Some(tp0) =>
+                  pending(i) = false
+                  elems(i) = tp0
+                  tp0
+                case None =>
+                  typeError(
+                    "no common type instance of base types "+(variants mkString ", and ")+" exists.")
+              }
+            } catch {
+              case CyclicInheritance =>
+                typeError(
+                  "computing the common type instance of base types "+(variants mkString ", and ")+" leads to a cycle.")
+            }
+          case tp =>
+            tp
+        }
 
     def rawElem(i: Int) = elems(i)
 
     /** The type symbol of the type at i'th position in this sequence;
      *  no evaluation needed.
      */
-    def typeSymbol(i: Int): Symbol = elems(i) match {
-      case RefinedType(v :: vs, _) => v.typeSymbol
-      case tp => tp.typeSymbol
+    def typeSymbol(i: Int): Symbol = {
+      elems(i) match {
+        case RefinedType(v :: vs, _) => v.typeSymbol
+        case tp => tp.typeSymbol
+      }
     }
 
     /** Return all evaluated types in this sequence as a list */
     def toList: List[Type] = elems.toList
 
-    private def copy(head: Type, offset: Int): BaseTypeSeq = {
+    protected def copy(head: Type, offset: Int): BaseTypeSeq = {
       val arr = new Array[Type](elems.length + offset)
-      Array.copy(elems, 0, arr, offset, elems.length)
+      compat.Platform.arraycopy(elems, 0, arr, offset, elems.length)
       arr(0) = head
       new BaseTypeSeq(parents, arr)
     }
@@ -99,39 +116,31 @@ trait BaseTypeSeqs {
       new BaseTypeSeq(parents, arr)
     }
 
-    def exists(p: Type => Boolean): Boolean = elems exists p
-//      (0 until length) exists (i => p(this(i)))
-
-    def normalize(parents: List[Type]) {}
-/*
-      var j = 0
-      while (j < elems.length) {
-        elems(j) match {
-          case RefinedType(variants, decls) =>
-            // can't assert decls.isEmpty; see t0764
-            //if (!decls.isEmpty) assert(false, "computing closure of "+this+":"+this.isInstanceOf[RefinedType]+"/"+closureCache(j))
-            //Console.println("compute closure of "+this+" => glb("+variants+")")
-            elems(j) = mergePrefixAndArgs(variants, -1, maxBaseTypeSeqDepth(variants) + LubGlbMargin) match {
-              case Some(tp0) => tp0
-              case None => throw new TypeError(
-                "the type intersection "+(parents mkString " with ")+" is malformed"+
-                "\n --- because ---"+
-                "\n no common type instance of base types "+(variants mkString ", and ")+" exists.")
-            }
-          case _ =>
-        }
-        j += 1
-      }
+    def lateMap(f: Type => Type): BaseTypeSeq = new BaseTypeSeq(parents map f, elems) {
+      override def apply(i: Int) = f(self.apply(i))
+      override def rawElem(i: Int) = f(self.rawElem(i))
+      override def typeSymbol(i: Int) = self.typeSymbol(i)
+      override def toList = self.toList map f
+      override protected def copy(head: Type, offset: Int) = (self map f).copy(head, offset)
+      override def map(g: Type => Type) = lateMap(g)
+      override def lateMap(g: Type => Type) = self.lateMap(x => g(f(x)))
+      override def exists(p: Type => Boolean) = elems exists (x => p(f(x)))
+      override protected def maxDepthOfElems: Int = elems map (x => maxDpth(f(x))) max
+      override def toString = elems.mkString("MBTS(", ",", ")")
     }
-*/
-    lazy val maxDepth: Int = {
+
+    def exists(p: Type => Boolean): Boolean = elems exists p
+
+    lazy val maxDepth: Int = maxDepthOfElems
+
+    protected def maxDepthOfElems = {
       var d = 0
-      for (i <- 0 until length) d = Math.max(d, maxDpth(elems(i)))
+      for (i <- 0 until length) d = max(d, maxDpth(elems(i)))
       d
     }
 
     /** The maximum depth of type `tp' */ 
-    private def maxDpth(tp: Type): Int = tp match {
+    protected def maxDpth(tp: Type): Int = tp match {
       case TypeRef(pre, sym, args) => 
         max(maxDpth(pre), maxDpth(args) + 1)
       case RefinedType(parents, decls) =>
@@ -172,7 +181,7 @@ trait BaseTypeSeqs {
   def baseTypeSingletonSeq(tp: Type): BaseTypeSeq = new BaseTypeSeq(List(), Array(tp))
 
   /** Create the base type sequence of a compound type wuth given tp.parents */
-  def compoundBaseTypeSeq(tp: Type/*tsym: Symbol, parents: List[Type]*/): BaseTypeSeq = {
+  def compoundBaseTypeSeq(tp: Type): BaseTypeSeq = {
     val tsym = tp.typeSymbol
     val parents = tp.parents
 //    Console.println("computing baseTypeSeq of " + tsym.tpe + " " + parents)//DEBUG
diff --git a/src/compiler/scala/tools/nsc/symtab/Constants.scala b/src/compiler/scala/tools/nsc/symtab/Constants.scala
deleted file mode 100644
index 99ab953..0000000
--- a/src/compiler/scala/tools/nsc/symtab/Constants.scala
+++ /dev/null
@@ -1,244 +0,0 @@
-/* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
- * @author  Martin Odersky
- */
-// $Id: Constants.scala 16894 2009-01-13 13:09:41Z cunei $
-
-package scala.tools.nsc.symtab
-
-
-import java.lang.Integer.toOctalString
-
-import classfile.PickleFormat._
-
-trait Constants { 
-  self: SymbolTable =>
-
-  import definitions._
-
-  final val NoTag      = LITERAL - LITERAL
-  final val UnitTag    = LITERALunit - LITERAL
-  final val BooleanTag = LITERALboolean - LITERAL
-  final val ByteTag    = LITERALbyte - LITERAL
-  final val ShortTag   = LITERALshort - LITERAL
-  final val CharTag    = LITERALchar - LITERAL
-  final val IntTag     = LITERALint - LITERAL
-  final val LongTag    = LITERALlong - LITERAL
-  final val FloatTag   = LITERALfloat - LITERAL
-  final val DoubleTag  = LITERALdouble - LITERAL
-  final val StringTag  = LITERALstring - LITERAL
-  final val NullTag    = LITERALnull - LITERAL
-  final val ClassTag   = LITERALclass - LITERAL
-  final val EnumTag    = ClassTag + 1
-  final val ArrayTag   = EnumTag + 1
-  final val AnnotationTag = ArrayTag + 1
-
-  def isNumeric(tag: Int) = ByteTag <= tag && tag <= DoubleTag 
-
-  case class Constant(value: Any) {
-
-    val tag: Int =
-      if (value.isInstanceOf[Unit]) UnitTag
-      else if (value.isInstanceOf[Boolean]) BooleanTag
-      else if (value.isInstanceOf[Byte]) ByteTag
-      else if (value.isInstanceOf[Short]) ShortTag
-      else if (value.isInstanceOf[Char]) CharTag
-      else if (value.isInstanceOf[Int]) IntTag
-      else if (value.isInstanceOf[Long]) LongTag
-      else if (value.isInstanceOf[Float]) FloatTag
-      else if (value.isInstanceOf[Double]) DoubleTag
-      else if (value.isInstanceOf[String]) StringTag
-      else if (value.isInstanceOf[Type]) ClassTag
-      else if (value.isInstanceOf[Symbol]) EnumTag
-      else if (value.isInstanceOf[Array[Constant]]) ArrayTag
-      else if (value == null) NullTag
-      else throw new Error("bad constant value: " + value)
-
-    def tpe: Type = tag match {
-      case UnitTag    => UnitClass.tpe
-      case BooleanTag => BooleanClass.tpe
-      case ByteTag    => ByteClass.tpe
-      case ShortTag   => ShortClass.tpe
-      case CharTag    => CharClass.tpe
-      case IntTag     => IntClass.tpe
-      case LongTag    => LongClass.tpe
-      case FloatTag   => FloatClass.tpe
-      case DoubleTag  => DoubleClass.tpe
-      case StringTag  => StringClass.tpe
-      case NullTag    => NullClass.tpe
-      case ClassTag   => Predef_classOfType(value.asInstanceOf[Type])
-      case EnumTag    => symbolValue.owner.linkedClassOfClass.tpe
-      case AnnotationTag => AnnotationClass.tpe  // what should it be?
-    }
-
-    /** We need the equals method to take account of tags as well as values.
-     *
-     *  @param other ...
-     *  @return      ...
-     */
-    override def equals(other: Any): Boolean = other match {
-      case that: Constant => this.value == that.value && this.tag == that.tag
-      case _ => false
-    }
-
-    def booleanValue: Boolean = 
-      if (tag == BooleanTag) value.asInstanceOf[Boolean]
-      else throw new Error("value " + value + " is not a boolean");
-
-    def byteValue: Byte = tag match {
-      case ByteTag   => value.asInstanceOf[Byte]
-      case ShortTag  => value.asInstanceOf[Short].asInstanceOf[Byte]
-      case CharTag   => value.asInstanceOf[Char].asInstanceOf[Byte]
-      case IntTag    => value.asInstanceOf[Int].asInstanceOf[Byte]
-      case LongTag   => value.asInstanceOf[Long].asInstanceOf[Byte]
-      case FloatTag  => value.asInstanceOf[Float].asInstanceOf[Byte]
-      case DoubleTag => value.asInstanceOf[Double].asInstanceOf[Byte]
-      case _         => throw new Error("value " + value + " is not a Byte")
-    }
-
-    def shortValue: Short = tag match {
-      case ByteTag   => value.asInstanceOf[Byte].asInstanceOf[Short]
-      case ShortTag  => value.asInstanceOf[Short]
-      case CharTag   => value.asInstanceOf[Char].asInstanceOf[Short]
-      case IntTag    => value.asInstanceOf[Int].asInstanceOf[Short]
-      case LongTag   => value.asInstanceOf[Long].asInstanceOf[Short]
-      case FloatTag  => value.asInstanceOf[Float].asInstanceOf[Short]
-      case DoubleTag => value.asInstanceOf[Double].asInstanceOf[Short]
-      case _         => throw new Error("value " + value + " is not a Short")
-    }
-
-    def charValue: Char = tag match {
-      case ByteTag   => value.asInstanceOf[Byte].asInstanceOf[Char]
-      case ShortTag  => value.asInstanceOf[Short].asInstanceOf[Char]
-      case CharTag   => value.asInstanceOf[Char]
-      case IntTag    => value.asInstanceOf[Int].asInstanceOf[Char]
-      case LongTag   => value.asInstanceOf[Long].asInstanceOf[Char]
-      case FloatTag  => value.asInstanceOf[Float].asInstanceOf[Char]
-      case DoubleTag => value.asInstanceOf[Double].asInstanceOf[Char]
-      case _         => throw new Error("value " + value + " is not a Char")
-    }
-
-    def intValue: Int = tag match {
-      case ByteTag   => value.asInstanceOf[Byte].asInstanceOf[Int]
-      case ShortTag  => value.asInstanceOf[Short].asInstanceOf[Int]
-      case CharTag   => value.asInstanceOf[Char].asInstanceOf[Int]
-      case IntTag    => value.asInstanceOf[Int]
-      case LongTag   => value.asInstanceOf[Long].asInstanceOf[Int]
-      case FloatTag  => value.asInstanceOf[Float].asInstanceOf[Int]
-      case DoubleTag => value.asInstanceOf[Double].asInstanceOf[Int]
-      case _         => throw new Error("value " + value + " is not an Int")
-    }
-
-    def longValue: Long = tag match {
-      case ByteTag   => value.asInstanceOf[Byte].asInstanceOf[Long]
-      case ShortTag  => value.asInstanceOf[Short].asInstanceOf[Long]
-      case CharTag   => value.asInstanceOf[Char].asInstanceOf[Long]
-      case IntTag    => value.asInstanceOf[Int].asInstanceOf[Long]
-      case LongTag   => value.asInstanceOf[Long]
-      case FloatTag  => value.asInstanceOf[Float].asInstanceOf[Long]
-      case DoubleTag => value.asInstanceOf[Double].asInstanceOf[Long]
-      case _         => throw new Error("value " + value + " is not a Long")
-    }
-
-    def floatValue: Float = tag match {
-      case ByteTag   => value.asInstanceOf[Byte].asInstanceOf[Float]
-      case ShortTag  => value.asInstanceOf[Short].asInstanceOf[Float]
-      case CharTag   => value.asInstanceOf[Char].asInstanceOf[Float]
-      case IntTag    => value.asInstanceOf[Int].asInstanceOf[Float]
-      case LongTag   => value.asInstanceOf[Long].asInstanceOf[Float]
-      case FloatTag  => value.asInstanceOf[Float]
-      case DoubleTag => value.asInstanceOf[Double].asInstanceOf[Float]
-      case _         => throw new Error("value " + value + " is not a Float")
-    }
-
-    def doubleValue: Double = tag match {
-      case ByteTag   => value.asInstanceOf[Byte].asInstanceOf[Double]
-      case ShortTag  => value.asInstanceOf[Short].asInstanceOf[Double]
-      case CharTag   => value.asInstanceOf[Char].asInstanceOf[Double]
-      case IntTag    => value.asInstanceOf[Int].asInstanceOf[Double]
-      case LongTag   => value.asInstanceOf[Long].asInstanceOf[Double]
-      case FloatTag  => value.asInstanceOf[Float].asInstanceOf[Double]
-      case DoubleTag => value.asInstanceOf[Double]
-      case _         => throw new Error("value " + value + " is not a Double")
-    }
-
-    /** Convert constant value to conform to given type.
-     *
-     *  @param pt ...
-     *  @return   ...
-     */
-    def convertTo(pt: Type): Constant = {
-      val target = pt.typeSymbol
-      if (target == tpe.typeSymbol)
-        this
-      else if (target == ByteClass && ByteTag <= tag && tag <= IntTag &&
-          -128 <= intValue && intValue <= 127) 
-        Constant(byteValue)
-      else if (target == ShortClass && ByteTag <= tag && tag <= IntTag &&
-               -32768 <= intValue && intValue <= 32767) 
-        Constant(shortValue)
-      else if (target == CharClass && ByteTag <= tag && tag <= IntTag  &&
-               0 <= intValue && intValue <= 65635)
-        Constant(charValue)
-      else if (target == IntClass && ByteTag <= tag && tag <= IntTag)
-        Constant(intValue)
-      else if (target == LongClass && ByteTag <= tag && tag <= LongTag)
-        Constant(longValue)
-      else if (target == FloatClass && ByteTag <= tag && tag <= FloatTag)
-        Constant(floatValue)
-      else if (target == DoubleClass && ByteTag <= tag && tag <= DoubleTag)
-        Constant(doubleValue)
-      else {
-        null
-      }
-    }
-
-    def stringValue: String =
-      if (value == null) "null"
-      else if (tag == ClassTag) signature(typeValue)
-      else value.toString()
-
-    def escapedStringValue: String = {
-      def escape(text: String): String = {
-        val buf = new StringBuilder
-        for (c <- text.elements)
-          if (c.isControl)
-            buf.append("\\0" + toOctalString(c.asInstanceOf[Int]))
-          else
-            buf.append(c)
-        buf.toString
-      }
-      tag match {
-        case NullTag   => "null"
-        case StringTag => "\"" + escape(stringValue) + "\""
-        case ClassTag  => "classOf[" + signature(typeValue) + "]"
-        case CharTag   => escape("\'" + charValue + "\'")
-        case LongTag   => longValue.toString() + "L"
-        case _         => value.toString()
-      }
-    }
-
-    def typeValue: Type = value.asInstanceOf[Type]
-
-    def symbolValue: Symbol = value.asInstanceOf[Symbol]
-
-    def arrayValue: Array[Constant] =
-      throw new Error("value " + value + " is not an array")
-
-    override def hashCode(): Int =
-      if (value == null) 0 else value.hashCode() * 41 + 17
-  }
-
-  class ArrayConstant(override val arrayValue: Array[Constant],
-                      override val tpe: Type)
-  extends Constant(arrayValue) {
-    override def toString() = arrayValue.mkString("Constant(", "," , ")")
-  }
-
-  /** A place-holder for annotation constants.  The contents of 
-   *  the constant are not read. */
-  class AnnotationConstant()
-  extends Constant(null) {
-    override val tag = AnnotationTag
-  }
-}
diff --git a/src/compiler/scala/tools/nsc/symtab/Definitions.scala b/src/compiler/scala/tools/nsc/symtab/Definitions.scala
index 2999bd4..29a3d9a 100644
--- a/src/compiler/scala/tools/nsc/symtab/Definitions.scala
+++ b/src/compiler/scala/tools/nsc/symtab/Definitions.scala
@@ -1,159 +1,288 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: Definitions.scala 17474 2009-04-13 20:11:37Z milessabin $
 
-package scala.tools.nsc.symtab
+package scala.tools.nsc
+package symtab
 
 import scala.collection.mutable.{HashMap, HashSet}
-import scala.tools.nsc.util.{Position, NoPosition}
+import scala.tools.nsc.util.NoPosition
 import Flags._
+import PartialFunction._
 
-trait Definitions {
+trait Definitions extends reflect.generic.StandardDefinitions {
   self: SymbolTable =>
 
-  object definitions {
+  object definitions extends AbsDefinitions {
     def isDefinitionsInitialized = isInitialized
 
-    // root packages and classes
-    lazy val RootPackage: Symbol = NoSymbol.newValue(NoPosition, nme.ROOTPKG)
-          .setFlag(FINAL | MODULE | PACKAGE | JAVA)
-          .setInfo(PolyType(List(), RootClass.tpe))
-    lazy val RootClass: Symbol = {
-      NoSymbol.newClass(NoPosition, nme.ROOT.toTypeName)
-        .setFlag(FINAL | MODULE | PACKAGE | JAVA).setInfo(rootLoader)
-    }
-    lazy val EmptyPackage: Symbol = RootClass.newPackage(NoPosition, nme.EMPTY_PACKAGE_NAME).setFlag(FINAL)
-
-    lazy val EmptyPackageClass: Symbol = EmptyPackage.moduleClass
-
+    // symbols related to packages
     var emptypackagescope: Scope = null //debug
+    
+    lazy val RootPackage: Symbol = {
+      val rp=NoSymbol.newValue(NoPosition, nme.ROOTPKG)
+        .setFlag(FINAL | MODULE | PACKAGE | JAVA)
+        .setInfo(PolyType(List(), RootClass.tpe))
+      RootClass.sourceModule = rp
+      rp
+    }
+    lazy val RootClass: ModuleClassSymbol = NoSymbol.newModuleClass(NoPosition, nme.ROOT.toTypeName)
+          .setFlag(FINAL | MODULE | PACKAGE | JAVA).setInfo(rootLoader)
 
-    lazy val JavaLangPackage: Symbol = getModule(sn.JavaLang)
-    lazy val ScalaPackage: Symbol = getModule("scala")
-    lazy val ScalaPackageClass: Symbol = ScalaPackage.tpe.typeSymbol
+    lazy val EmptyPackage       = RootClass.newPackage(NoPosition, nme.EMPTY_PACKAGE_NAME).setFlag(FINAL)
+    lazy val EmptyPackageClass  = EmptyPackage.moduleClass
 
-    var AnyClass: Symbol = _
-    var AnyValClass: Symbol = _
-    var AnyRefClass: Symbol = _
-    lazy val ObjectClass: Symbol = getClass(sn.Object)
+    lazy val JavaLangPackage    = getModule(sn.JavaLang)
+    lazy val ScalaPackage       = getModule("scala")
+    lazy val ScalaPackageClass  = ScalaPackage.tpe.typeSymbol
 
-    lazy val anyrefparam = List(AnyRefClass.typeConstructor)
+    lazy val ScalaCollectionImmutablePackage: Symbol = getModule("scala.collection.immutable")
+    lazy val ScalaCollectionImmutablePackageClass: Symbol = ScalaCollectionImmutablePackage.tpe.typeSymbol
 
-    var NullClass: Symbol = _
-    var NothingClass: Symbol = _
-    var SingletonClass: Symbol = _
-    lazy val uncheckedStableClass = getClass("scala.annotation.unchecked.uncheckedStable")
-    lazy val uncheckedVarianceClass = getClass("scala.annotation.unchecked.uncheckedVariance") 
+    // convenient one-argument parameter lists
+    lazy val anyparam     = List(AnyClass.typeConstructor)
+    lazy val anyvalparam  = List(AnyValClass.typeConstructor)
+    lazy val anyrefparam  = List(AnyRefClass.typeConstructor)
+    
+    // private parameter conveniences
+    private def booltype = BooleanClass.typeConstructor
+    private def boolparam = List(booltype)
+    private def bytetype = ByteClass.typeConstructor
+    private def byteparam = List(bytetype)
+    private def shorttype = ShortClass.typeConstructor
+    private def shortparam = List(shorttype)
+    private def inttype = IntClass.typeConstructor
+    private def intparam = List(inttype)
+    private def longtype = LongClass.typeConstructor
+    private def longparam = List(longtype)
+    private def floattype = FloatClass.typeConstructor
+    private def floatparam = List(floattype)
+    private def doubletype = DoubleClass.typeConstructor
+    private def doubleparam = List(doubletype)
+    private def chartype = CharClass.typeConstructor
+    private def charparam = List(chartype)
+    private def stringtype = StringClass.typeConstructor
+    
+    // top types
+    lazy val AnyClass     = newClass(ScalaPackageClass, nme.Any, Nil) setFlag (ABSTRACT)
+    lazy val AnyValClass  = newClass(ScalaPackageClass, nme.AnyVal, anyparam) setFlag (ABSTRACT | SEALED)
+    lazy val AnyRefClass  = newAlias(ScalaPackageClass, nme.AnyRef, ObjectClass.typeConstructor)
+    lazy val ObjectClass  = getClass(sn.Object)
 
-    lazy val ClassClass: Symbol = getClass(sn.Class)
-    lazy val StringClass: Symbol = getClass(sn.String)
-    lazy val ThrowableClass: Symbol = getClass(sn.Throwable)
-    lazy val NullPointerExceptionClass: Symbol = getClass(sn.NPException)
-    lazy val NonLocalReturnExceptionClass: Symbol = getClass(sn.NLRException)
-    lazy val InvocationTargetExceptionClass: Symbol =
-      getClass("java.lang.reflect.InvocationTargetException") // java is hard coded because only used by structural values
+    // bottom types
+    lazy val NullClass    = newClass(ScalaPackageClass, nme.Null, anyrefparam) setFlag (ABSTRACT | TRAIT | FINAL)
+    lazy val NothingClass = newClass(ScalaPackageClass, nme.Nothing, anyparam) setFlag (ABSTRACT | TRAIT | FINAL)
+    lazy val RuntimeNothingClass  = getClass("scala.runtime.Nothing$")
+    lazy val RuntimeNullClass     = getClass("scala.runtime.Null$")
 
-    // System.ValueType
-    lazy val ValueTypeClass: Symbol = getClass(sn.ValueType)
-    // System.MulticastDelegate
-    lazy val DelegateClass: Symbol = getClass(sn.Delegate)
-    var Delegate_scalaCallers: List[Symbol] = List()
-    // Symbol -> (Symbol, Type): scalaCaller -> (scalaMethodSym, DelegateType)
-    // var Delegate_scalaCallerInfos: HashMap[Symbol, (Symbol, Type)] = _
-    lazy val Delegate_scalaCallerTargets: HashMap[Symbol, Symbol] = new HashMap()
+    lazy val AnyValCompanionClass = getClass("scala.runtime.AnyValCompanion").setFlag(SEALED | ABSTRACT | TRAIT)
 
     // the scala value classes
-    var UnitClass: Symbol = _
-    var BooleanClass: Symbol = _
-      def Boolean_not = getMember(BooleanClass, nme.UNARY_!)
+    lazy val UnitClass    =                             
+      newClass(ScalaPackageClass, nme.Unit, anyvalparam).setFlag(ABSTRACT | FINAL)
+    
+    lazy val ByteClass    = newValueClass(nme.Byte, 'B', 2)
+    lazy val ShortClass   = newValueClass(nme.Short, 'S', 4)
+    lazy val CharClass    = newValueClass(nme.Char, 'C', 3)
+    lazy val IntClass     = newValueClass(nme.Int, 'I', 12)
+    lazy val LongClass    = newValueClass(nme.Long, 'L', 24)
+    lazy val FloatClass   = newValueClass(nme.Float, 'F', 48)
+    lazy val DoubleClass  = newValueClass(nme.Double, 'D', 96)    
+    lazy val BooleanClass = newValueClass(nme.Boolean, 'Z', 0)
       def Boolean_and = getMember(BooleanClass, nme.ZAND)
       def Boolean_or  = getMember(BooleanClass, nme.ZOR)
-    var ByteClass: Symbol = _
-    var ShortClass: Symbol = _
-    var CharClass: Symbol = _
-    var IntClass: Symbol = _
-      def Int_Or  = definitions.getMember(definitions.IntClass, nme.OR)
-      def Int_And = definitions.getMember(definitions.IntClass, nme.AND)
-      def Int_==  = definitions.getMember(definitions.IntClass, nme.EQ)
-      def Int_!=  = definitions.getMember(definitions.IntClass, nme.NE)
-
-    var LongClass: Symbol = _
-    var FloatClass: Symbol = _
-    var DoubleClass: Symbol = _
-
-    // the scala reference classes
-    lazy val ScalaObjectClass: Symbol = getClass("scala.ScalaObject")
-      def ScalaObjectClass_tag = getMember(ScalaObjectClass, nme.tag)
-    lazy val AnnotationClass: Symbol = getClass("scala.Annotation")
-    lazy val ClassfileAnnotationClass: Symbol = getClass("scala.ClassfileAnnotation")
-    lazy val StaticAnnotationClass: Symbol = getClass("scala.StaticAnnotation")
-    lazy val TypeConstraintClass: Symbol = getClass("scala.TypeConstraint")
-    lazy val ManifestClass: Symbol = getClass("scala.reflect.Manifest")
-    lazy val ManifestModule: Symbol = getModule("scala.reflect.Manifest")
-
-    var CodeClass: Symbol = _
-    var CodeModule: Symbol = _
-      def Code_lift = getMember(CodeModule, nme.lift_)
-    lazy val PartialFunctionClass: Symbol = getClass("scala.PartialFunction")
-    /*
-    lazy val ByNameFunctionClass: Symbol = getClass("scala.ByNameFunction")
-    */
-    lazy val IterableClass: Symbol = getClass("scala.Iterable")
-      def Iterable_next = getMember(IterableClass, nme.next)
-      def Iterable_hasNext = getMember(IterableClass, nme.hasNext)
-    lazy val IteratorClass: Symbol = getClass("scala.Iterator")
-    lazy val SeqClass: Symbol = getClass("scala.Seq")
-    lazy val RandomAccessSeqMutableClass: Symbol = getMember(getModule("scala.RandomAccessSeq"), nme.Mutable)
-    def Seq_length = getMember(SeqClass, nme.length)
-      
-    lazy val ListClass: Symbol = getClass("scala.List")
-      def List_isEmpty = getMember(ListClass, nme.isEmpty)
-      def List_head = getMember(ListClass, nme.head)
-      def List_tail = getMember(ListClass, nme.tail)
-    lazy val ListModule: Symbol = getModule("scala.List")
-      def List_apply = getMember(ListModule, nme.apply)
-    lazy val ArrayClass: Symbol = getClass("scala.Array")
-      def Array_apply = getMember(ArrayClass, nme.apply)
-    lazy val ArrayModule: Symbol = getModule("scala.Array")
-      def ArrayModule_apply = getMember(ArrayModule, nme.apply)
-    lazy val SerializableClass: Symbol = getClass(sn.Serializable)
+
+    def ScalaValueClasses = List(
+      UnitClass, ByteClass, ShortClass, IntClass, LongClass,
+      CharClass, FloatClass, DoubleClass, BooleanClass
+    )
+    
+    // exceptions and other throwables
+    lazy val ThrowableClass                 = getClass(sn.Throwable)
+    lazy val NullPointerExceptionClass      = getClass(sn.NPException)
+    lazy val NonLocalReturnControlClass   = getClass(sn.NLRControl)
+    lazy val IndexOutOfBoundsExceptionClass = getClass(sn.IOOBException)
+    lazy val UninitializedErrorClass        = getClass("scala.UninitializedFieldError")
+    lazy val MatchErrorClass                = getClass("scala.MatchError")
+    // java is hard coded because only used by structural values
+    lazy val InvocationTargetExceptionClass = getClass("java.lang.reflect.InvocationTargetException")
+    lazy val NoSuchMethodExceptionClass     = getClass("java.lang.NoSuchMethodException")
+    
+    // annotations
+    lazy val AnnotationClass            = getClass("scala.Annotation")
+    lazy val ClassfileAnnotationClass   = getClass("scala.ClassfileAnnotation")
+    lazy val StaticAnnotationClass      = getClass("scala.StaticAnnotation")
+    lazy val uncheckedStableClass       = getClass("scala.annotation.unchecked.uncheckedStable") 
+    lazy val uncheckedVarianceClass     = getClass("scala.annotation.unchecked.uncheckedVariance")
+    lazy val UncheckedClass             = getClass("scala.unchecked")
+    lazy val ThrowsClass                = getClass("scala.throws")
+    lazy val TailrecClass               = getClass("scala.annotation.tailrec")
+    lazy val SwitchClass                = getClass("scala.annotation.switch")
+    lazy val ElidableMethodClass        = getClass("scala.annotation.elidable")
+    lazy val ImplicitNotFoundClass      = getClass("scala.annotation.implicitNotFound")
+    lazy val FieldTargetClass           = getClass("scala.annotation.target.field")
+    lazy val GetterTargetClass          = getClass("scala.annotation.target.getter")
+    lazy val SetterTargetClass          = getClass("scala.annotation.target.setter")
+    lazy val BeanGetterTargetClass      = getClass("scala.annotation.target.beanGetter")
+    lazy val BeanSetterTargetClass      = getClass("scala.annotation.target.beanSetter")
+    lazy val ParamTargetClass           = getClass("scala.annotation.target.param")
+    lazy val SpecializedClass           = definitions.getClass("scala.specialized")
+
+
+    // fundamental reference classes
+    lazy val ScalaObjectClass     = getClass("scala.ScalaObject")
+    lazy val PartialFunctionClass = getClass("scala.PartialFunction")
+    lazy val SymbolClass          = getClass("scala.Symbol")
+    lazy val StringClass          = getClass(sn.String)
+    lazy val ClassClass           = getClass(sn.Class)
+      def Class_getMethod = getMember(ClassClass, nme.getMethod_)
+
+    // fundamental modules
     lazy val PredefModule: Symbol = getModule("scala.Predef")
       def Predef_classOf = getMember(PredefModule, nme.classOf)
-      def Predef_classOfType(classType: Type): Type =
-        if (!ClassClass.unsafeTypeParams.isEmpty && !phase.erasedTypes)
-          appliedType(ClassClass.tpe, List(classType))
-        else ClassClass.tpe
-      def Predef_identity = getMember(PredefModule, nme.identity)
       def Predef_error    = getMember(PredefModule, nme.error)
+      def Predef_identity = getMember(PredefModule, nme.identity)
+      def Predef_conforms = getMember(PredefModule, nme.conforms)
     lazy val ConsoleModule: Symbol = getModule("scala.Console")
-    lazy val MatchErrorClass: Symbol = getClass("scala.MatchError")
-    lazy val UninitializedErrorClass: Symbol = getClass("scala.UninitializedFieldError")
-    //var MatchErrorModule: Symbol = _
-    //  def MatchError_fail = getMember(MatchErrorModule, nme.fail)
-    //  def MatchError_report = getMember(MatchErrorModule, nme.report)
-    lazy val IndexOutOfBoundsExceptionClass: Symbol = getClass(sn.IOOBException)
     lazy val ScalaRunTimeModule: Symbol = getModule("scala.runtime.ScalaRunTime")
-      def SeqFactory = getMember(ScalaRunTimeModule, nme.Seq);
-      def checkDefinedMethod = getMember(ScalaRunTimeModule, "checkDefined")
-      def isArrayMethod = getMember(ScalaRunTimeModule, "isArray")
-    lazy val NotNullClass: Symbol = getClass("scala.NotNull")
-    var RepeatedParamClass: Symbol = _
-    var ByNameParamClass: Symbol = _
-    //var UnsealedClass: Symbol = _
-    lazy val UncheckedClass: Symbol = getClass("scala.unchecked")
-
-    var EqualsPatternClass: Symbol = _
-
-    val MaxTupleArity = 22
-    val TupleClass: Array[Symbol] = new Array(MaxTupleArity + 1)
+    lazy val SymbolModule: Symbol = getModule("scala.Symbol") 
+      def SeqFactory = getMember(ScalaRunTimeModule, nme.Seq)
+      def arrayApplyMethod = getMember(ScalaRunTimeModule, "array_apply")
+      def arrayUpdateMethod = getMember(ScalaRunTimeModule, "array_update")
+      def arrayLengthMethod = getMember(ScalaRunTimeModule, "array_length")
+      def arrayCloneMethod = getMember(ScalaRunTimeModule, "array_clone")
+      def scalaRuntimeHash = getMember(ScalaRunTimeModule, "hash")
+      def scalaRuntimeSameElements = getMember(ScalaRunTimeModule, nme.sameElements)
+    
+    // classes with special meanings
+    lazy val NotNullClass         = getClass("scala.NotNull")
+    lazy val TypeConstraintClass  = getClass("scala.TypeConstraint")
+    lazy val SingletonClass       = newClass(ScalaPackageClass, nme.Singleton, anyparam) setFlag (ABSTRACT | TRAIT | FINAL)
+    lazy val SerializableClass    = getClass(sn.Serializable)
+    lazy val ComparableClass      = getClass("java.lang.Comparable")
+    
+    lazy val RepeatedParamClass = newCovariantPolyClass(
+      ScalaPackageClass,
+      nme.REPEATED_PARAM_CLASS_NAME, 
+      tparam => seqType(tparam.typeConstructor)
+    )
+
+    lazy val JavaRepeatedParamClass = newCovariantPolyClass(
+      ScalaPackageClass,
+      nme.JAVA_REPEATED_PARAM_CLASS_NAME, 
+      tparam => arrayType(tparam.typeConstructor)
+    )
+
+    def isRepeatedParamType(tp: Type) = 
+      tp.typeSymbol == RepeatedParamClass || tp.typeSymbol == JavaRepeatedParamClass
+
+    lazy val ByNameParamClass = newCovariantPolyClass(
+      ScalaPackageClass,
+      nme.BYNAME_PARAM_CLASS_NAME,
+      tparam => AnyClass.typeConstructor
+    )
+    lazy val EqualsPatternClass = {
+      val clazz = newClass(ScalaPackageClass, nme.EQUALS_PATTERN_NAME, Nil) 
+      clazz setInfo PolyType(List(newTypeParam(clazz, 0)), ClassInfoType(anyparam, new Scope, clazz))
+
+      clazz
+    }    
+      
+    // collections classes
+    lazy val IteratorClass        = getClass2("scala.Iterator", "scala.collection.Iterator")
+    lazy val TraversableClass     = getClass("scala.collection.Traversable")
+    lazy val IterableClass        = getClass2("scala.Iterable", "scala.collection.Iterable")
+      def Iterable_next     = getMember(IterableClass, nme.next)
+      def Iterable_hasNext  = getMember(IterableClass, nme.hasNext)
+    
+    lazy val SeqClass   = getClass2("scala.Seq", "scala.collection.Seq")
+    lazy val SeqModule  = getModule2("scala.Seq", "scala.collection.Seq")
+      def Seq_length = getMember(SeqClass, nme.length)
+    lazy val RandomAccessSeqMutableClass = getMember(
+      getModule2("scala.RandomAccessSeq", "scala.collection.IndexedSeq"), nme.Mutable)
+      
+    lazy val ListModule   = getModule2("scala.List", "scala.collection.immutable.List")
+      def List_apply = getMember(ListModule, nme.apply)
+    lazy val ListClass    = getClass2("scala.List", "scala.collection.immutable.List")
+      def List_isEmpty  = getMember(ListClass, nme.isEmpty)
+      def List_head     = getMember(ListClass, nme.head)
+      def List_tail     = getMember(ListClass, nme.tail)
+    lazy val ConsClass    = getClass2("scala.$colon$colon", "scala.collection.immutable.$colon$colon")
+    lazy val NilModule    = getModule2("scala.Nil", "scala.collection.immutable.Nil")
+      
+    lazy val ArrayClass   = getClass("scala.Array")
+      def Array_apply   = getMember(ArrayClass, nme.apply)
+      def Array_update  = getMember(ArrayClass, nme.update)
+      def Array_length  = getMember(ArrayClass, nme.length)
+      lazy val Array_clone   = getMember(ArrayClass, nme.clone_)
+    lazy val ArrayModule  = getModule("scala.Array")
+    
+    // reflection / structural types
+    lazy val SoftReferenceClass     = getClass("java.lang.ref.SoftReference")
+    lazy val WeakReferenceClass     = getClass("java.lang.ref.WeakReference")
+    lazy val MethodClass            = getClass(sn.MethodAsObject)
+      def methodClass_setAccessible = getMember(MethodClass, nme.setAccessible)
+    lazy val EmptyMethodCacheClass  = getClass("scala.runtime.EmptyMethodCache")
+    lazy val MethodCacheClass       = getClass("scala.runtime.MethodCache")
+      def methodCache_find  = getMember(MethodCacheClass, nme.find_)
+      def methodCache_add   = getMember(MethodCacheClass, nme.add_)
+
+    // scala.reflect
+    lazy val PartialManifestClass = getClass("scala.reflect.ClassManifest")
+    lazy val PartialManifestModule       = getModule("scala.reflect.ClassManifest")
+    lazy val FullManifestClass   = getClass("scala.reflect.Manifest")
+    lazy val FullManifestModule  = getModule("scala.reflect.Manifest")
+    lazy val OptManifestClass     = getClass("scala.reflect.OptManifest")
+    lazy val NoManifest           = getModule("scala.reflect.NoManifest")
+    lazy val CodeClass            = getClass(sn.Code)
+    lazy val CodeModule           = getModule(sn.Code)
+      def Code_lift = getMember(CodeModule, nme.lift_)
+
+    lazy val ScalaSignatureAnnotation = getClass("scala.reflect.ScalaSignature")
+    lazy val ScalaLongSignatureAnnotation = getClass("scala.reflect.ScalaLongSignature")
+    
+    // invoke dynamic support
+    lazy val LinkageModule = getModule("java.dyn.Linkage")
+      lazy val Linkage_invalidateCallerClass = getMember(LinkageModule, "invalidateCallerClass")
+    lazy val DynamicDispatchClass = getModule("scala.runtime.DynamicDispatch")
+      lazy val DynamicDispatch_DontSetTarget = getMember(DynamicDispatchClass, "DontSetTarget")
+
+    // Option classes
+    lazy val OptionClass: Symbol  = getClass("scala.Option")
+    lazy val SomeClass: Symbol    = getClass("scala.Some")
+    lazy val NoneModule: Symbol    = getModule("scala.None")
+
+    def isOptionType(tp: Type)  = cond(tp.normalize) { case TypeRef(_, OptionClass, List(_)) => true }
+    def isSomeType(tp: Type)    = cond(tp.normalize) { case TypeRef(_,   SomeClass, List(_)) => true }
+    def isNoneType(tp: Type)    = cond(tp.normalize) { case TypeRef(_,   NoneModule, List(_)) => true }
+
+    def optionType(tp: Type)    = typeRef(OptionClass.typeConstructor.prefix, OptionClass, List(tp))
+    def someType(tp: Type)      = typeRef(SomeClass.typeConstructor.prefix, SomeClass, List(tp))
+    def symbolType              = typeRef(SymbolClass.typeConstructor.prefix, SymbolClass, List()) 
+    def longType                = typeRef(LongClass.typeConstructor.prefix, LongClass, List()) 
+    
+    // Product, Tuple, Function
+    private def mkArityArray(name: String, arity: Int, countFrom: Int = 1) = {
+      val list = (countFrom to arity).toList map (i => getClass(("scala." + name + i): Name))
+      if (countFrom == 0) list.toArray
+      else (NoSymbol :: list).toArray
+    } 
+    
+    val MaxTupleArity, MaxProductArity, MaxFunctionArity = 22
+    /** The maximal dimensions of a generic array creation.
+     *  I.e. new Array[Array[Array[Array[Array[T]]]]] creates a 5 times
+     *  nested array. More is not allowed.
+     */
+    val MaxArrayDims = 5
+    lazy val TupleClass     = mkArityArray("Tuple", MaxTupleArity)
+    lazy val ProductClass   = mkArityArray("Product", MaxProductArity)
+    lazy val FunctionClass  = mkArityArray("Function", MaxFunctionArity, 0)
+    lazy val AbstractFunctionClass = mkArityArray("runtime.AbstractFunction", MaxFunctionArity, 0)
+    
       def tupleField(n: Int, j: Int) = getMember(TupleClass(n), "_" + j)
-      def isTupleType(tp: Type): Boolean = tp.normalize match {
-        case TypeRef(_, sym, elems) =>
-          elems.length <= MaxTupleArity && sym == TupleClass(elems.length)
-        case _ =>
-          false
+      def isTupleType(tp: Type): Boolean = cond(tp.normalize) {
+        case TypeRef(_, sym, elems) => elems.length <= MaxTupleArity && sym == TupleClass(elems.length)
       }
       def tupleType(elems: List[Type]) =
         if (elems.length <= MaxTupleArity) {
@@ -164,19 +293,18 @@ trait Definitions {
     lazy val ProductRootClass: Symbol = getClass("scala.Product")
       def Product_productArity = getMember(ProductRootClass, nme.productArity)
       def Product_productElement = getMember(ProductRootClass, nme.productElement)
+      // def Product_productElementName = getMember(ProductRootClass, nme.productElementName)
       def Product_productPrefix = getMember(ProductRootClass, nme.productPrefix)
-    val MaxProductArity = 22
-    /* <unapply> */
-    val ProductClass: Array[Symbol] = new Array(MaxProductArity + 1)
+      def Product_canEqual = getMember(ProductRootClass, nme.canEqual_)
+      
       def productProj(z:Symbol, j: Int): Symbol = getMember(z, nme.Product_(j))
       def productProj(n: Int,   j: Int): Symbol = productProj(ProductClass(n), j)
-    /** returns true if this type is exactly ProductN[T1,...,Tn], not some subclass */
-      def isExactProductType(tp: Type): Boolean = tp.normalize match {
-        case TypeRef(_, sym, elems) =>
-          elems.length <= MaxProductArity && sym == ProductClass(elems.length)
-        case _ =>
-          false
+      
+      /** returns true if this type is exactly ProductN[T1,...,Tn], not some subclass */
+      def isExactProductType(tp: Type): Boolean = cond(tp.normalize) {
+        case TypeRef(_, sym, elems) => elems.length <= MaxProductArity && sym == ProductClass(elems.length)
       }
+
       def productType(elems: List[Type]) =
         if (elems.isEmpty)
           UnitClass.tpe
@@ -187,84 +315,77 @@ trait Definitions {
 
     /** if tpe <: ProductN[T1,...,TN], returns Some(T1,...,TN) else None */
     def getProductArgs(tpe: Type): Option[List[Type]] = 
-      tpe.baseClasses.find { x => definitions.isExactProductType(x.tpe) } match {
+      tpe.baseClasses.find(x => isExactProductType(x.tpe)) match {
         case Some(p) => Some(tpe.baseType(p).typeArgs)
         case _       => None
       }
 
-    lazy val OptionClass: Symbol = getClass("scala.Option")
-
-    lazy val SomeClass: Symbol = getClass("scala.Some")
-    lazy val NoneClass: Symbol = getModule("scala.None")
-
-    def isOptionType(tp: Type) = tp.normalize match {
-      case TypeRef(_, sym, List(_)) if sym == OptionClass => true
-      case _ => false
-    }
-    def isOptionOrSomeType(tp: Type) = tp.normalize match {
-      case TypeRef(_, sym, List(_)) => sym == OptionClass || sym == SomeClass
-      case _ => false
-    }
-    def optionType(tp: Type) =
-      typeRef(OptionClass.typeConstructor.prefix, OptionClass, List(tp))
-
-    def isSomeType(tp: Type) = tp.normalize match {
-      case TypeRef(_, sym, List(_)) if sym == SomeClass => true
-      case _ => false
-    }
-    def someType(tp: Type) =
-      typeRef(SomeClass.typeConstructor.prefix, SomeClass, List(tp))
-
-    def isNoneType(tp: Type) = tp.normalize match {
-      case TypeRef(_, sym, List(_)) if sym == NoneClass => true
-      case _ => false
-    }
-
     def unapplyUnwrap(tpe:Type) = (tpe match {
       case PolyType(_,MethodType(_, res)) => res
       case MethodType(_, res)             => res
       case tpe                            => tpe
     }).normalize
     
-    /* </unapply> */
-    val MaxFunctionArity = 22
-    val FunctionClass: Array[Symbol] = new Array(MaxFunctionArity + 1)
-      def functionApply(n: Int) = getMember(FunctionClass(n), nme.apply)
-      def functionType(formals: List[Type], restpe: Type) =
-        if (formals.length <= MaxFunctionArity) {
-          val sym = FunctionClass(formals.length)
-          typeRef(sym.typeConstructor.prefix, sym, formals ::: List(restpe))
-        } else NoType;
-      def isFunctionType(tp: Type): Boolean = tp.normalize match {
-        case TypeRef(_, sym, args) =>
-          (args.length > 0) && (args.length - 1 <= MaxFunctionArity) &&
-          (sym == FunctionClass(args.length - 1))
-        case _ =>
-          false
-      }
+    def functionApply(n: Int) = getMember(FunctionClass(n), nme.apply)
+    def functionType(formals: List[Type], restpe: Type) =
+      if (formals.length <= MaxFunctionArity) {
+        val sym = FunctionClass(formals.length)
+        typeRef(sym.typeConstructor.prefix, sym, formals ::: List(restpe))
+      } else NoType
+  
+    def abstractFunctionForFunctionType(tp: Type) = tp.normalize match {
+      case tr @ TypeRef(_, _, args) if isFunctionType(tr) =>
+        val sym = AbstractFunctionClass(args.length - 1)
+        typeRef(sym.typeConstructor.prefix, sym, args)
+      case _ =>
+        NoType
+    }
+
+    def isFunctionType(tp: Type): Boolean = tp.normalize match {
+      case TypeRef(_, sym, args) =>
+        (args.length > 0) && (args.length - 1 <= MaxFunctionArity) &&
+        (sym == FunctionClass(args.length - 1))
+      case _ =>
+        false
+    }
+    
+    def seqType(arg: Type) = typeRef(SeqClass.typeConstructor.prefix, SeqClass, List(arg))
+    def arrayType(arg: Type) = typeRef(ArrayClass.typeConstructor.prefix, ArrayClass, List(arg))
 
+    def ClassType(arg: Type) = 
+      if (phase.erasedTypes || forMSIL) ClassClass.tpe
+      else appliedType(ClassClass.tpe, List(arg))
+
+    //
+    // .NET backend
+    //
+    
+    lazy val ComparatorClass = getClass("scala.runtime.Comparator")    
+    // System.ValueType
+    lazy val ValueTypeClass: Symbol = getClass(sn.ValueType)
+    // System.MulticastDelegate
+    lazy val DelegateClass: Symbol = getClass(sn.Delegate)
+    var Delegate_scalaCallers: List[Symbol] = List()
+    // Symbol -> (Symbol, Type): scalaCaller -> (scalaMethodSym, DelegateType)
+    // var Delegate_scalaCallerInfos: HashMap[Symbol, (Symbol, Type)] = _
+    lazy val Delegate_scalaCallerTargets: HashMap[Symbol, Symbol] = new HashMap()
+    
     def isCorrespondingDelegate(delegateType: Type, functionType: Type): Boolean = {
       isSubType(delegateType, DelegateClass.tpe) &&
       (delegateType.member(nme.apply).tpe match {
-	case MethodType(delegateParams, delegateReturn) =>
-	  isFunctionType(functionType) &&
-	  (functionType.normalize match {
-	    case TypeRef(_, _, args) =>
-	      (delegateParams.map(pt => {
-                if (pt == AnyClass.tpe) definitions.ObjectClass.tpe else pt})
-	       ::: List(delegateReturn)) == args
-	    case _ => false
-	  })
+      	case MethodType(delegateParams, delegateReturn) =>
+      	  isFunctionType(functionType) &&
+      	  (functionType.normalize match {
+      	    case TypeRef(_, _, args) =>
+      	      (delegateParams.map(pt => {
+                      if (pt == AnyClass.tpe) definitions.ObjectClass.tpe else pt})
+      	       ::: List(delegateReturn)) == args
+      	    case _ => false
+      	  })
         case _ => false
       })
     }
 
-    def seqType(arg: Type) =
-      typeRef(SeqClass.typeConstructor.prefix, SeqClass, List(arg))
-
-    def NilModule: Symbol = getModule("scala.Nil")
-    def ConsClass: Symbol = getClass("scala.$colon$colon")
-
     // members of class scala.Any
     var Any_==          : Symbol = _
     var Any_!=          : Symbol = _
@@ -273,17 +394,22 @@ trait Definitions {
     var Any_toString    : Symbol = _
     var Any_isInstanceOf: Symbol = _
     var Any_asInstanceOf: Symbol = _
-    var Any_isInstanceOfErased: Symbol = _
-    var Any_asInstanceOfErased: Symbol = _
+    var Any_##          : Symbol = _
 
     // members of class java.lang.{Object, String}
     var Object_eq          : Symbol = _
     var Object_ne          : Symbol = _
     var Object_==          : Symbol = _
     var Object_!=          : Symbol = _
+    var Object_##          : Symbol = _
     var Object_synchronized: Symbol = _
-    var Object_isInstanceOf: Symbol = _
-    var Object_asInstanceOf: Symbol = _
+    lazy val Object_isInstanceOf = newPolyMethod(
+      ObjectClass, "$isInstanceOf",
+      tparam => MethodType(List(), booltype)) setFlag FINAL
+    lazy val Object_asInstanceOf = newPolyMethod(
+      ObjectClass, "$asInstanceOf",
+      tparam => MethodType(List(), tparam.typeConstructor)) setFlag FINAL
+
     def Object_getClass  = getMember(ObjectClass, nme.getClass_)
     def Object_clone     = getMember(ObjectClass, nme.clone_)
     def Object_finalize  = getMember(ObjectClass, nme.finalize_)
@@ -295,37 +421,73 @@ trait Definitions {
 
     var String_+           : Symbol = _
 
-    // members of class scala.Iterator
-    var Iterator_next      : Symbol = _
-    var Iterator_hasNext   : Symbol = _
-
-    // pattern wildcard
-    var PatternWildcard: Symbol = _
-
     // boxed classes
-    lazy val BoxesRunTimeClass = getModule("scala.runtime.BoxesRunTime")
-    lazy val BoxedArrayClass = getClass("scala.runtime.BoxedArray")
-    lazy val BoxedAnyArrayClass = getClass("scala.runtime.BoxedAnyArray")
-    lazy val BoxedObjectArrayClass = getClass("scala.runtime.BoxedObjectArray")
-    lazy val BoxedUnitClass = getClass("scala.runtime.BoxedUnit")
-    lazy val BoxedNumberClass = getClass(sn.BoxedNumber)
-    lazy val BoxedCharacterClass = getClass(sn.BoxedCharacter)
-    lazy val BoxedBooleanClass = getClass(sn.BoxedBoolean)
-    lazy val BoxedUnitModule = getModule("scala.runtime.BoxedUnit")
+    lazy val ObjectRefClass         = getClass("scala.runtime.ObjectRef")
+    lazy val VolatileObjectRefClass = getClass("scala.runtime.VolatileObjectRef")
+    lazy val BoxesRunTimeClass      = getModule("scala.runtime.BoxesRunTime")
+    lazy val BoxedNumberClass       = getClass(sn.BoxedNumber)
+    lazy val BoxedCharacterClass    = getClass(sn.BoxedCharacter)
+    lazy val BoxedBooleanClass      = getClass(sn.BoxedBoolean)
+    lazy val BoxedByteClass         = getClass("java.lang.Byte")
+    lazy val BoxedShortClass        = getClass("java.lang.Short")
+    lazy val BoxedIntClass          = getClass("java.lang.Integer")
+    lazy val BoxedLongClass         = getClass("java.lang.Long")
+    lazy val BoxedFloatClass        = getClass("java.lang.Float")
+    lazy val BoxedDoubleClass       = getClass("java.lang.Double")
+    
+    lazy val BoxedUnitClass         = getClass("scala.runtime.BoxedUnit")
+    lazy val BoxedUnitModule        = getModule("scala.runtime.BoxedUnit")
       def BoxedUnit_UNIT = getMember(BoxedUnitModule, "UNIT")
-    lazy val ObjectRefClass = getClass("scala.runtime.ObjectRef")
+      def BoxedUnit_TYPE = getMember(BoxedUnitModule, "TYPE")
 
     // special attributes
     lazy val SerializableAttr: Symbol = getClass("scala.serializable")
     lazy val DeprecatedAttr: Symbol = getClass("scala.deprecated")
+    lazy val MigrationAnnotationClass: Symbol = getClass("scala.annotation.migration")
+    lazy val TraitSetterAnnotationClass: Symbol = getClass("scala.runtime.TraitSetter")
     lazy val BeanPropertyAttr: Symbol = getClass(sn.BeanProperty)
-    var AnnotationDefaultAttr: Symbol = _
+    lazy val BooleanBeanPropertyAttr: Symbol = getClass(sn.BooleanBeanProperty)
+    
+    lazy val AnnotationDefaultAttr: Symbol = {
+      val RuntimePackageClass = getModule("scala.runtime").tpe.typeSymbol
+      val attr = newClass(RuntimePackageClass, nme.AnnotationDefaultATTR, List(AnnotationClass.typeConstructor))
+      // This attribute needs a constructor so that modifiers in parsed Java code make sense
+      attr.info.decls enter (attr newConstructor NoPosition setInfo MethodType(Nil, attr.tpe))
+      attr
+    }
+    
     lazy val NativeAttr: Symbol = getClass("scala.native")
     lazy val VolatileAttr: Symbol = getClass("scala.volatile")
 
     def getModule(fullname: Name): Symbol = getModuleOrClass(fullname, true)
+    def getModule2(name1: Name, name2: Name) = try {
+      getModuleOrClass(name1, true)
+    } catch {
+      case ex1: FatalError => 
+        try {
+          getModuleOrClass(name2, true)
+        } catch {
+          case ex2: FatalError => throw ex1
+        }
+    }
 
-    def getClass(fullname: Name): Symbol = getModuleOrClass(fullname, false)
+    def getClass(fullname: Name): Symbol = {
+      var result = getModuleOrClass(fullname, false)
+      while (result.isAliasType) result = result.info.typeSymbol
+      result
+    }
+
+    def getClass2(name1: Name, name2: Name) = try {
+      var result = getModuleOrClass(name1, false)
+      if (result.isAliasType) getClass(name2) else result
+    } catch {
+      case ex1: FatalError => 
+        try {
+          getModuleOrClass(name2, false)
+        } catch {
+          case ex2: FatalError => throw ex1
+        }
+    }
 
     def getMember(owner: Symbol, name: Name): Symbol = {
       if (owner == NoSymbol) return NoSymbol
@@ -338,7 +500,7 @@ trait Definitions {
 
     private def getModuleOrClass(fullname: Name, module: Boolean): Symbol = {
       if (fullname == nme.NOSYMBOL) return NoSymbol
-      var sym = RootClass
+      var sym:Symbol = RootClass
       var i = 0
       var j = fullname.pos('.', i)
       while (j < fullname.length) {
@@ -351,15 +513,15 @@ trait Definitions {
         else sym.info.member(fullname.subName(i, j).toTypeName)
       if (result == NoSymbol) {
         if (settings.debug.value)
-          { Console.println(sym.info); Console.println(sym.info.members) }//debug
-        throw new FatalError((if (module) "object " else "class ") + fullname + " not found.")
+          { log(sym.info); log(sym.info.members) }//debug
+        throw new MissingRequirementError((if (module) "object " else "class ") + fullname)
       }
       result
     }
 
     private def newClass(owner: Symbol, name: Name, parents: List[Type]): Symbol = {
       val clazz = owner.newClass(NoPosition, name.toTypeName)
-      clazz.setInfo(ClassInfoType(parents, newClassScope(clazz), clazz))
+      clazz.setInfo(ClassInfoType(parents, new Scope, clazz))
       owner.info.decls.enter(clazz) 
       clazz
     }
@@ -377,7 +539,7 @@ trait Definitions {
       clazz.setInfo(
         PolyType(
           List(tparam),
-          ClassInfoType(List(p), newClassScope(clazz), clazz)))
+          ClassInfoType(List(AnyRefClass.tpe, p), new Scope, clazz)))
     }
 
     private def newAlias(owner: Symbol, name: Name, alias: Type): Symbol = {
@@ -393,13 +555,21 @@ trait Definitions {
       msym
     }
 
-    private def newMethod(owner: Symbol, name: Name, formals: List[Type], restpe: Type): Symbol =
-      newMethod(owner, name).setInfo(MethodType(formals, restpe))
+    private def newMethod(owner: Symbol, name: Name, formals: List[Type], restpe: Type): Symbol = {
+      val msym = newMethod(owner, name)
+      val params = msym.newSyntheticValueParams(formals)
+      msym.setInfo(MethodType(params, restpe))
+    }
 
-    private def newPolyMethod(owner: Symbol, name: Name, tcon: Symbol => Type): Symbol = {
+    /** tcon receives the type parameter symbol as argument */
+    private def newPolyMethod(owner: Symbol, name: Name, tcon: Symbol => Type): Symbol =
+      newPolyMethodCon(owner, name, tparam => msym => tcon(tparam))
+
+    /** tcon receives the type parameter symbol and the method symbol as arguments */
+    private def newPolyMethodCon(owner: Symbol, name: Name, tcon: Symbol => Symbol => Type): Symbol = {
       val msym = newMethod(owner, name)
       val tparam = newTypeParam(msym, 0)
-      msym.setInfo(PolyType(List(tparam), tcon(tparam)))
+      msym.setInfo(PolyType(List(tparam), tcon(tparam)(msym)))
     }
 
     private def newParameterlessMethod(owner: Symbol, name: Name, restpe: Type) =
@@ -407,59 +577,64 @@ trait Definitions {
 
     private def newTypeParam(owner: Symbol, index: Int): Symbol =
       owner.newTypeParameter(NoPosition, "T" + index)
-        .setInfo(mkTypeBounds(NothingClass.typeConstructor, AnyClass.typeConstructor))
+        .setInfo(TypeBounds(NothingClass.typeConstructor, AnyClass.typeConstructor))
 
     val boxedClass = new HashMap[Symbol, Symbol]
+    val boxedModule = new HashMap[Symbol, Symbol]
     val unboxMethod = new HashMap[Symbol, Symbol] // Type -> Method
     val boxMethod = new HashMap[Symbol, Symbol] // Type -> Method
-    val boxedArrayClass = new HashMap[Symbol, Symbol]
+    val primitiveCompanions = new HashSet[Symbol]
 
-    def isUnbox(m: Symbol) = m.name == nme.unbox && {
-      m.tpe match {
-        case MethodType(_, restpe) => (unboxMethod get restpe.typeSymbol) match {
-          case Some(`m`) => true
-          case _ => false
-        }
-        case _ => false
-      }
-    }
+    def isUnbox(m: Symbol) = unboxMethod.valuesIterator contains m
+    def isBox(m: Symbol) = boxMethod.valuesIterator contains m
 
-    /** Test whether a method symbol is that of a boxing method. */
-    def isBox(m: Symbol) = (boxMethod.values contains m) && {
-      m.tpe match {
-        case MethodType(List(argtpe), _) => (boxMethod get argtpe.typeSymbol) match {
-          case Some(`m`) => true
-          case _ => false
-        }
-        case _ => false
+    val refClass = new HashMap[Symbol, Symbol]
+    val volatileRefClass = new HashMap[Symbol, Symbol]
+    val abbrvTag = new HashMap[Symbol, Char]
+    private val numericWeight = new HashMap[Symbol, Int]
+    
+    def isNumericSubClass(sub: Symbol, sup: Symbol) = 
+      numericWeight get sub match {
+        case Some(w1) =>
+          numericWeight get sup match {
+            case Some(w2) => w2 % w1 == 0
+            case None => false
+          }
+        case None => false
       }
-    }
 
-    val refClass = new HashMap[Symbol, Symbol]
-    private val abbrvTag = new HashMap[Symbol, Char]
+    /** Create a companion object for scala.Unit.
+     */
+    private def initUnitCompanionObject() {
+      val module = ScalaPackageClass.newModule(NoPosition, "Unit")
+      ScalaPackageClass.info.decls.enter(module)
+      val mclass = module.moduleClass
+      mclass.setInfo(ClassInfoType(List(AnyRefClass.tpe, AnyValCompanionClass.tpe), new Scope, mclass))
+      module.setInfo(mclass.tpe)
+      primitiveCompanions += module
+    }
 
-    private def newValueClass(name: Name, tag: Char): Symbol = {
+    private[symtab] def newValueClass(name: Name, tag: Char, weight: Int): Symbol = {
       val boxedName = sn.Boxed(name)
 
-      val clazz =
-        newClass(ScalaPackageClass, name, List(AnyValClass.typeConstructor))
-        .setFlag(ABSTRACT | FINAL)
+      val clazz = newClass(ScalaPackageClass, name, anyvalparam) setFlag (ABSTRACT | FINAL)
       boxedClass(clazz) = getClass(boxedName)
-      boxedArrayClass(clazz) = getClass("scala.runtime.Boxed" + name + "Array")
+      boxedModule(clazz) = getModule(boxedName)
       refClass(clazz) = getClass("scala.runtime." + name + "Ref")
+      volatileRefClass(clazz) = getClass("scala.runtime.Volatile" + name + "Ref")
       abbrvTag(clazz) = tag
+      if (weight > 0) numericWeight(clazz) = weight
 
       val module = ScalaPackageClass.newModule(NoPosition, name)
       ScalaPackageClass.info.decls.enter(module)
       val mclass = module.moduleClass
-      mclass.setInfo(ClassInfoType(List(), newClassScope(mclass), mclass))
+      mclass.setInfo(ClassInfoType(List(AnyRefClass.tpe, AnyValCompanionClass.tpe), new Scope, mclass))
       module.setInfo(mclass.tpe)
+      primitiveCompanions += module
 
-      val box = newMethod(mclass, nme.box, List(clazz.typeConstructor),
-                          ObjectClass.typeConstructor)
+      val box = newMethod(mclass, nme.box, List(clazz.typeConstructor), boxedClass(clazz).tpe)
       boxMethod(clazz) = box
-      val unbox = newMethod(mclass, nme.unbox, List(ObjectClass.typeConstructor),
-                            clazz.typeConstructor)
+      val unbox = newMethod(mclass, nme.unbox, List(ObjectClass.typeConstructor), clazz.typeConstructor)
       unboxMethod(clazz) = unbox
 
       clazz
@@ -468,56 +643,25 @@ trait Definitions {
     /** Sets-up symbols etc. for value classes, and their boxed versions. This
       * method is called once from within the body of init. */
     private def initValueClasses() {
-      val booltype = BooleanClass.typeConstructor
-      val boolparam = List(booltype)
-      val bytetype = ByteClass.typeConstructor
-      val byteparam = List(bytetype)
-      val chartype = CharClass.typeConstructor
-      val charparam = List(chartype)
-      val shorttype = ShortClass.typeConstructor
-      val shortparam = List(shorttype)
-      val inttype = IntClass.typeConstructor
-      val intparam = List(inttype)
-      val longtype = LongClass.typeConstructor
-      val longparam = List(longtype)
-
-      val floattype = if (forCLDC) null else FloatClass.typeConstructor
-      val floatparam = if (forCLDC) null else List(floattype)
-      val doubletype = if (forCLDC) null else DoubleClass.typeConstructor
-      val doubleparam = if (forCLDC) null else List(doubletype)
-
-      val stringtype = StringClass.typeConstructor
-
       // init scala.Boolean
       newParameterlessMethod(BooleanClass, nme.UNARY_!, booltype)
-      newMethod(BooleanClass, nme.EQ,   boolparam, booltype)
-      newMethod(BooleanClass, nme.NE,   boolparam, booltype)
-      newMethod(BooleanClass, nme.ZOR,  boolparam, booltype)
-      newMethod(BooleanClass, nme.ZAND, boolparam, booltype)
-      newMethod(BooleanClass, nme.OR,   boolparam, booltype)
-      newMethod(BooleanClass, nme.AND,  boolparam, booltype)
-      newMethod(BooleanClass, nme.XOR,  boolparam, booltype)
+      List(nme.EQ, nme.NE, nme.ZOR, nme.ZAND, nme.OR, nme.AND, nme.XOR) foreach {
+        newMethod(BooleanClass, _, boolparam, booltype)
+      }
 
       def initValueClass(clazz: Symbol, isCardinal: Boolean) {
         assert (clazz ne null)
+        val boolBinOps  = List(nme.EQ, nme.NE, nme.LT, nme.LE, nme.GT, nme.GE)
+        val otherBinOps = List(nme.ADD, nme.SUB, nme.MUL, nme.DIV, nme.MOD)
+        val cardBinOps  = List(nme.OR, nme.AND, nme.XOR)
+        val shiftOps    = List(nme.LSL, nme.LSR, nme.ASR)        
 
         def addBinops(params: List[Type], restype: Type, isCardinal: Boolean) = {
-          newMethod(clazz, nme.EQ,  params, booltype)
-          newMethod(clazz, nme.NE,  params, booltype)
-          newMethod(clazz, nme.LT,  params, booltype)
-          newMethod(clazz, nme.LE,  params, booltype)
-          newMethod(clazz, nme.GT,  params, booltype)
-          newMethod(clazz, nme.GE,  params, booltype)
-          newMethod(clazz, nme.ADD, params, restype)
-          newMethod(clazz, nme.SUB, params, restype)
-          newMethod(clazz, nme.MUL, params, restype)
-          newMethod(clazz, nme.DIV, params, restype)
-          newMethod(clazz, nme.MOD, params, restype)
-          if (isCardinal) {
-            newMethod(clazz, nme.OR, params, restype)
-            newMethod(clazz, nme.AND, params, restype)
-            newMethod(clazz, nme.XOR, params, restype)
-          }
+          boolBinOps foreach  (x => newMethod(clazz, x, params, booltype))
+          otherBinOps foreach (x => newMethod(clazz, x, params, restype))
+          
+          if (isCardinal)
+            cardBinOps foreach (x => newMethod(clazz, x, params, restype))
         }
 
         // conversion methods
@@ -526,31 +670,22 @@ trait Definitions {
         newParameterlessMethod(clazz, nme.toChar,   chartype)
         newParameterlessMethod(clazz, nme.toInt,    inttype)
         newParameterlessMethod(clazz, nme.toLong,   longtype)
-
-        if (!forCLDC) {
-          newParameterlessMethod(clazz, nme.toFloat,  floattype)
-          newParameterlessMethod(clazz, nme.toDouble, doubletype)
-        }
+        newParameterlessMethod(clazz, nme.toFloat,  floattype)
+        newParameterlessMethod(clazz, nme.toDouble, doubletype)
 
         // def +(s: String): String
         newMethod(clazz, nme.ADD, List(stringtype), stringtype)
-
-        val restype =
-          if ((clazz eq LongClass) ||
-              (clazz eq FloatClass) ||
-              (clazz eq DoubleClass))
-            clazz.typeConstructor
-          else inttype
+        
+        def isLongFloatOrDouble = clazz match {
+          case LongClass | FloatClass | DoubleClass => true
+          case _                                    => false
+        }        
+        val restype = if (isLongFloatOrDouble) clazz.typeConstructor else inttype
 
         // shift operations
-        if (isCardinal) {
-          newMethod(clazz, nme.LSL, intparam,  restype)
-          newMethod(clazz, nme.LSL, longparam, restype)
-          newMethod(clazz, nme.LSR, intparam,  restype)
-          newMethod(clazz, nme.LSR, longparam, restype)
-          newMethod(clazz, nme.ASR, intparam,  restype)
-          newMethod(clazz, nme.ASR, longparam, restype)
-        }
+        if (isCardinal)
+          for (op <- shiftOps ; param <- List(intparam, longparam))
+            newMethod(clazz, op, param, restype)
 
         // unary operations
         newParameterlessMethod(clazz, nme.UNARY_+, restype)
@@ -561,31 +696,20 @@ trait Definitions {
         }
 
         // binary operations
-        val restype2 = if (isCardinal) longtype else restype
-        addBinops(byteparam,   restype,    isCardinal)
-        addBinops(shortparam,  restype,    isCardinal)
-        addBinops(charparam,   restype,    isCardinal)
-        addBinops(intparam,    restype,    isCardinal)
-        addBinops(longparam,   restype2,   isCardinal)
-        if (!forCLDC) {
-          val restype3 = if (clazz eq DoubleClass) doubletype else floattype
-          addBinops(floatparam,  restype3,   false)
-          addBinops(doubleparam, doubletype, false)
-        }
+        List(byteparam, shortparam, charparam, intparam) .
+          foreach (x => addBinops(x, restype, isCardinal))
+          
+        addBinops(longparam,   (if (isCardinal) longtype else restype),               isCardinal)
+        addBinops(floatparam,  (if (clazz eq DoubleClass) doubletype else floattype), false     )
+        addBinops(doubleparam, doubletype,                                            false     )
       }
 
-      initValueClass(ByteClass,   true)
-      initValueClass(ShortClass,  true)
-      initValueClass(CharClass,   true)
-      initValueClass(IntClass,    true)
-      initValueClass(LongClass,   true)
-      if (!forCLDC) {
-        initValueClass(FloatClass,  false)
-        initValueClass(DoubleClass, false)
-      }
+      List(ByteClass, ShortClass, CharClass, IntClass, LongClass) foreach (x => initValueClass(x, true))
+      List(FloatClass, DoubleClass)                               foreach (x => initValueClass(x, false))
+
       def addModuleMethod(clazz: Symbol, name: Name, value: Any) {
         val owner = clazz.linkedClassOfClass
-        newParameterlessMethod(owner, name, mkConstantType(Constant(value)))
+        newParameterlessMethod(owner, name, ConstantType(Constant(value)))
       }
       addModuleMethod(ByteClass,  "MinValue",  java.lang.Byte.MIN_VALUE)
       addModuleMethod(ByteClass,  "MaxValue",  java.lang.Byte.MAX_VALUE)
@@ -598,38 +722,40 @@ trait Definitions {
       addModuleMethod(LongClass,  "MinValue",  java.lang.Long.MIN_VALUE)
       addModuleMethod(LongClass,  "MaxValue",  java.lang.Long.MAX_VALUE)
 
-      if (!forCLDC) {
-        addModuleMethod(FloatClass, "MinValue", -java.lang.Float.MAX_VALUE)
-        addModuleMethod(FloatClass, "MaxValue",  java.lang.Float.MAX_VALUE)
-        addModuleMethod(FloatClass, "Epsilon",   java.lang.Float.MIN_VALUE)
-        addModuleMethod(FloatClass, "NaN",       java.lang.Float.NaN)
-        addModuleMethod(FloatClass, "PositiveInfinity", java.lang.Float.POSITIVE_INFINITY)
-        addModuleMethod(FloatClass, "NegativeInfinity", java.lang.Float.NEGATIVE_INFINITY)
-
-        addModuleMethod(DoubleClass, "MinValue", -java.lang.Double.MAX_VALUE)
-        addModuleMethod(DoubleClass, "MaxValue",  java.lang.Double.MAX_VALUE)
-        addModuleMethod(DoubleClass, "Epsilon",   java.lang.Double.MIN_VALUE)
-        addModuleMethod(DoubleClass, "NaN",       java.lang.Double.NaN)
-        addModuleMethod(DoubleClass, "PositiveInfinity", java.lang.Double.POSITIVE_INFINITY)
-        addModuleMethod(DoubleClass, "NegativeInfinity", java.lang.Double.NEGATIVE_INFINITY)
-      }
+      addModuleMethod(FloatClass, "MinValue", -java.lang.Float.MAX_VALUE)
+      addModuleMethod(FloatClass, "MaxValue",  java.lang.Float.MAX_VALUE)
+      addModuleMethod(FloatClass, "Epsilon",   java.lang.Float.MIN_VALUE)
+      addModuleMethod(FloatClass, "NaN",       java.lang.Float.NaN)
+      addModuleMethod(FloatClass, "PositiveInfinity", java.lang.Float.POSITIVE_INFINITY)
+      addModuleMethod(FloatClass, "NegativeInfinity", java.lang.Float.NEGATIVE_INFINITY)
+
+      addModuleMethod(DoubleClass, "MinValue", -java.lang.Double.MAX_VALUE)
+      addModuleMethod(DoubleClass, "MaxValue",  java.lang.Double.MAX_VALUE)
+      addModuleMethod(DoubleClass, "Epsilon",   java.lang.Double.MIN_VALUE)
+      addModuleMethod(DoubleClass, "NaN",       java.lang.Double.NaN)
+      addModuleMethod(DoubleClass, "PositiveInfinity", java.lang.Double.POSITIVE_INFINITY)
+      addModuleMethod(DoubleClass, "NegativeInfinity", java.lang.Double.NEGATIVE_INFINITY)
     }
 
+    /** Is symbol a phantom class for which no runtime representation exists? */
+    def isPhantomClass(sym: Symbol) = 
+      sym == AnyClass || sym == AnyValClass || sym == NullClass || sym == NothingClass
+
     /** Is symbol a value class? */
     def isValueClass(sym: Symbol): Boolean =
       (sym eq UnitClass) || (boxedClass contains sym)
 
-    /** Is symbol a value class? */
+    /** Is symbol a numeric value class? */
     def isNumericValueClass(sym: Symbol): Boolean =
-      (sym ne BooleanClass) && (boxedClass contains sym)
+      numericWeight contains sym
 
-    def isValueType(sym: Symbol) =
-      isValueClass(sym) || unboxMethod.contains(sym)
-
-    /** Is symbol a value or array class? */
-    def isUnboxedClass(sym: Symbol): Boolean =
-      isValueType(sym) || sym == ArrayClass
+    /** Is symbol a numeric value class? */
+    def isNumericValueType(tp: Type): Boolean = tp match {
+      case TypeRef(_, sym, _) => isNumericValueClass(sym)
+      case _ => false
+    }
 
+    // todo: reconcile with javaSignature!!!
     def signature(tp: Type): String = {
       def erasure(tp: Type): Type = tp match {
         case st: SubType => erasure(st.supertype)
@@ -637,7 +763,7 @@ trait Definitions {
         case _ => tp
       }
       def flatNameString(sym: Symbol, separator: Char): String =
-        if (sym.owner.isPackageClass) sym.fullNameString('.') + (if (sym.isModuleClass) "$" else "")
+        if (sym.owner.isPackageClass) sym.fullName('.') + (if (sym.isModuleClass) "$" else "")
         else flatNameString(sym.owner, separator) + "$" + sym.simpleName;
       def signature1(etp: Type): String = {
         if (etp.typeSymbol == ArrayClass) "[" + signature1(erasure(etp.normalize.typeArgs.head))
@@ -655,114 +781,66 @@ trait Definitions {
       if (isInitialized) return
       isInitialized = true
 
-      EmptyPackageClass.setInfo(ClassInfoType(List(), newClassScope(EmptyPackageClass), EmptyPackageClass))
+      EmptyPackageClass.setInfo(ClassInfoType(Nil, new Scope, EmptyPackageClass))
       EmptyPackage.setInfo(EmptyPackageClass.tpe)
       RootClass.info.decls.enter(EmptyPackage)
       RootClass.info.decls.enter(RootPackage)
 
-      AnyClass = newClass(ScalaPackageClass, nme.Any, List()).setFlag(ABSTRACT)
-      val any = List(AnyClass.typeConstructor)
-
-      AnyValClass = newClass(ScalaPackageClass, nme.AnyVal, any)
-        .setFlag(FINAL | SEALED)
-      AnyRefClass =
-        newAlias(ScalaPackageClass, nme.AnyRef, ObjectClass.typeConstructor)
-
-      NullClass = newClass(ScalaPackageClass, nme.Null, anyrefparam)
-        .setFlag(ABSTRACT | TRAIT | FINAL)
-
-      NothingClass = newClass(ScalaPackageClass, nme.Nothing, any)
-        .setFlag(ABSTRACT | TRAIT | FINAL)
-
-      SingletonClass = newClass(ScalaPackageClass, nme.Singleton, any)
-        .setFlag(ABSTRACT | TRAIT | FINAL)
-
-      UnitClass =
-        newClass(ScalaPackageClass, nme.Unit, List(AnyValClass.typeConstructor))
-        .setFlag(ABSTRACT | FINAL)
       abbrvTag(UnitClass) = 'V'
 
-      BooleanClass = newValueClass(nme.Boolean, 'Z')
-      ByteClass =    newValueClass(nme.Byte, 'B')
-      ShortClass =   newValueClass(nme.Short, 'S')
-      CharClass =    newValueClass(nme.Char, 'C')
-      IntClass =     newValueClass(nme.Int, 'I')
-      LongClass =    newValueClass(nme.Long, 'L')
-      if (!forCLDC) {
-        FloatClass =   newValueClass(nme.Float, 'F')
-        DoubleClass =  newValueClass(nme.Double, 'D')
-      }
-
-      CodeClass = getClass(sn.Code)
-      CodeModule = getModule(sn.Code)
-      RepeatedParamClass = newCovariantPolyClass(
-        ScalaPackageClass, nme.REPEATED_PARAM_CLASS_NAME,
-        tparam => typeRef(SeqClass.typeConstructor.prefix, SeqClass, List(tparam.typeConstructor)))
-      ByNameParamClass = newCovariantPolyClass(
-        ScalaPackageClass, nme.BYNAME_PARAM_CLASS_NAME, tparam => AnyClass.typeConstructor)
-
-      EqualsPatternClass = newClass(ScalaPackageClass, nme.EQUALS_PATTERN_NAME, List());
-      { 
-        val tparam = newTypeParam(EqualsPatternClass, 0)
-        EqualsPatternClass.setInfo(
-          PolyType(
-            List(tparam),
-            ClassInfoType(List(AnyClass.typeConstructor), newClassScope(EqualsPatternClass), EqualsPatternClass)))
-      }
-      
-      /* <unapply> */
-      //UnsealedClass = getClass("scala.unsealed") //todo: remove once 2.4 is out.
-
-      for (i <- 1 to MaxTupleArity) {
-        TupleClass(i)   = getClass(  "scala.Tuple" + i)
-      }
-      for (i <- 1 to MaxProductArity) {
-        ProductClass(i) = getClass("scala.Product" + i)
-      }
-      /* </unapply> */
-      for (i <- 0 to MaxFunctionArity) {
-        FunctionClass(i) = getClass("scala.Function" + i)
-      }
       initValueClasses()
-      val booltype = BooleanClass.typeConstructor
+      initUnitCompanionObject()
 
       // members of class scala.Any
-      Any_== = newMethod(AnyClass, nme.EQ, any, booltype) setFlag FINAL
-      Any_!= = newMethod(AnyClass, nme.NE, any, booltype) setFlag FINAL
-      Any_equals = newMethod(AnyClass, nme.equals_, any, booltype)
-      Any_hashCode = newMethod(
-        AnyClass, nme.hashCode_, List(), IntClass.typeConstructor)
-      Any_toString = newMethod(
-        AnyClass, nme.toString_, List(), StringClass.typeConstructor)
+      Any_== = newMethod(AnyClass, nme.EQ, anyparam, booltype) setFlag FINAL
+      Any_!= = newMethod(AnyClass, nme.NE, anyparam, booltype) setFlag FINAL
+      Any_equals = newMethod(AnyClass, nme.equals_, anyparam, booltype)
+      Any_hashCode = newMethod(AnyClass, nme.hashCode_, Nil, inttype)
+      Any_toString = newMethod(AnyClass, nme.toString_, Nil, stringtype)
+      Any_## = newMethod(AnyClass, nme.HASHHASH, Nil, inttype) setFlag FINAL
 
       Any_isInstanceOf = newPolyMethod(
         AnyClass, nme.isInstanceOf_, tparam => booltype) setFlag FINAL
       Any_asInstanceOf = newPolyMethod(
         AnyClass, nme.asInstanceOf_, tparam => tparam.typeConstructor) setFlag FINAL
-      Any_isInstanceOfErased = newPolyMethod(
-        AnyClass, nme.isInstanceOfErased, tparam => booltype) setFlag FINAL
-      //todo: do we need this?
-      Any_asInstanceOfErased = newPolyMethod(
-        AnyClass, nme.asInstanceOfErased, tparam => tparam.typeConstructor) setFlag FINAL
 
-      // members of class java.lang.{Object, String}
+      // members of class java.lang.{ Object, String }
+      Object_## = newMethod(ObjectClass, nme.HASHHASH, Nil, inttype) setFlag FINAL
       Object_== = newMethod(ObjectClass, nme.EQ, anyrefparam, booltype) setFlag FINAL
       Object_!= = newMethod(ObjectClass, nme.NE, anyrefparam, booltype) setFlag FINAL
       Object_eq = newMethod(ObjectClass, nme.eq, anyrefparam, booltype) setFlag FINAL
       Object_ne = newMethod(ObjectClass, "ne", anyrefparam, booltype) setFlag FINAL
-      Object_synchronized = newPolyMethod(
+      Object_synchronized = newPolyMethodCon(
         ObjectClass, nme.synchronized_,
-        tparam => MethodType(List(tparam.typeConstructor), tparam.typeConstructor)) setFlag FINAL
-      Object_isInstanceOf = newPolyMethod(
-        ObjectClass, "$isInstanceOf",
-        tparam => MethodType(List(), booltype)) setFlag FINAL
-      Object_asInstanceOf = newPolyMethod(
-        ObjectClass, "$asInstanceOf",
-        tparam => MethodType(List(), tparam.typeConstructor)) setFlag FINAL
-      String_+ = newMethod(
-        StringClass, "+", any, StringClass.typeConstructor) setFlag FINAL
+        tparam => msym => MethodType(msym.newSyntheticValueParams(List(tparam.typeConstructor)), tparam.typeConstructor)) setFlag FINAL
 
-      PatternWildcard = NoSymbol.newValue(NoPosition, "_").setInfo(NothingClass.typeConstructor)
+      String_+ = newMethod(
+        StringClass, "+", anyparam, stringtype) setFlag FINAL
+
+      val forced = List( // force initialization of every symbol that is entered as a side effect
+        AnnotationDefaultAttr, // #2264
+        RepeatedParamClass,
+        JavaRepeatedParamClass,
+        ByNameParamClass,
+        UnitClass,
+        ByteClass,
+        ShortClass,
+        CharClass,
+        IntClass,
+        LongClass,
+        FloatClass,
+        DoubleClass,
+        BooleanClass,
+        AnyClass,
+        AnyRefClass,
+        AnyValClass,
+        NullClass,
+        NothingClass,
+        SingletonClass,
+        EqualsPatternClass,
+        Object_isInstanceOf,
+        Object_asInstanceOf
+      )
 
       if (forMSIL) {
         val intType = IntClass.typeConstructor
@@ -775,9 +853,10 @@ trait Definitions {
 
         // additional methods of Object
         newMethod(ObjectClass, "clone", List(), AnyRefClass.typeConstructor)
-        newMethod(ObjectClass, "wait", List(), unitType)
-        newMethod(ObjectClass, "wait", List(longType), unitType)
-        newMethod(ObjectClass, "wait", List(longType, intType), unitType)
+        // wait in Java returns void, on .NET Wait returns boolean. by putting
+        //  `booltype` the compiler adds a `drop` after calling wait.
+        newMethod(ObjectClass, "wait", List(), booltype)
+        newMethod(ObjectClass, "wait", List(longType), booltype)
         newMethod(ObjectClass, "notify", List(), unitType)
         newMethod(ObjectClass, "notifyAll", List(), unitType)
 
@@ -803,24 +882,14 @@ trait Definitions {
         newMethod(StringClass, "trim", List(), stringType)
         newMethod(StringClass, "intern", List(), stringType)
         newMethod(StringClass, "replace", List(charType, charType), stringType)
-        newMethod(StringClass, "toCharArray", List(),
-                  appliedType(ArrayClass.typeConstructor, List(charType)))
+        newMethod(StringClass, "toCharArray", List(), arrayType(charType))
       }
-
-      AnnotationDefaultAttr = newClass(RootClass,
-                                       nme.AnnotationDefaultATTR,
-                                       List(AnnotationClass.typeConstructor))
-      // This attribute needs a constructor so that modifiers in parsed
-      // Java code make sense
-      AnnotationDefaultAttr.info.decls.enter(
-        AnnotationDefaultAttr.newConstructor(NoPosition)
-          .setInfo(MethodType(List(), AnnotationDefaultAttr.tpe)))
     } //init
 
     var nbScalaCallers: Int = 0
     def newScalaCaller(delegateType: Type): Symbol = {
       assert(forMSIL, "scalaCallers can only be created if target is .NET")
-      // object: reference to object on which to call (scala-)metod
+      // object: reference to object on which to call (scala-)method
       val paramTypes: List[Type] = List(ObjectClass.tpe)
       val name: String =  "$scalaCaller$$" + nbScalaCallers
       // tparam => resultType, which is the resultType of PolyType, i.e. the result type after applying the
diff --git a/src/compiler/scala/tools/nsc/symtab/Flags.scala b/src/compiler/scala/tools/nsc/symtab/Flags.scala
index d182b73..673f685 100644
--- a/src/compiler/scala/tools/nsc/symtab/Flags.scala
+++ b/src/compiler/scala/tools/nsc/symtab/Flags.scala
@@ -1,90 +1,18 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: Flags.scala 16894 2009-01-13 13:09:41Z cunei $
-
-package scala.tools.nsc.symtab
-
-object Flags extends Enumeration {
-
-  // modifiers
-  final val IMPLICIT      = 0x00000001   
-  final val FINAL         = 0x00000002
-  final val PRIVATE       = 0x00000004
-  final val PROTECTED     = 0x00000008
-
-  final val SEALED        = 0x00000010
-  final val OVERRIDE      = 0x00000020
-  final val CASE          = 0x00000040
-  final val ABSTRACT      = 0x00000080    // abstract class, or used in conjunction
-                                          // with abstract override.
-                                          // Note difference to DEFERRED!
-
-  final val DEFERRED      = 0x00000100    // was `abstract' for members
-  final val METHOD        = 0x00000200    // a method
-  final val MODULE        = 0x00000400    // symbol is module or class implementing a module
-  final val INTERFACE     = 0x00000800    // symbol is an interface (i.e. a trait which defines only abstract methods)
-
-  final val MUTABLE       = 0x00001000    // symbol is a mutable variable.
-  final val PARAM         = 0x00002000    // symbol is a (value or type) parameter to a method
-  final val PACKAGE       = 0x00004000    // symbol is a java package
-  final val DEPRECATED    = 0x00008000    // symbol is deprecated.
-
-  final val COVARIANT     = 0x00010000    // symbol is a covariant type variable
-  final val CAPTURED      = 0x00010000    // variable is accessed from nested function.
-                                          // Set by LambdaLift
-  final val BYNAMEPARAM   = 0x00010000    // parameter is by name
-  final val CONTRAVARIANT = 0x00020000    // symbol is a contravariant type variable
-  final val LABEL         = 0x00020000    // method symbol is a label. Set by TailCall
-  final val DEFAULTINIT   = 0x00020000    // field is initialized to the default value (used by checkinit)
-  final val INCONSTRUCTOR = 0x00020000    // class symbol is defined in this/superclass
-                                          // constructor.
-  final val ABSOVERRIDE   = 0x00040000    // combination of abstract & override
-  final val LOCAL         = 0x00080000    // symbol is local to current class.
-                                          // pre: PRIVATE or PROTECTED are also set
-  final val JAVA          = 0x00100000    // symbol was defined by a Java class
-  final val SYNTHETIC     = 0x00200000    // symbol is compiler-generated
-  final val STABLE        = 0x00400000    // functions that are assumed to be stable
-                                          // (typically, access methods for valdefs)
-                                          // or classes that do not contain abstract types.
-  final val STATIC        = 0x00800000    // static field, method or class
-
-  final val CASEACCESSOR  = 0x01000000    // symbol is a case parameter (or its accessor)
-  final val TRAIT         = 0x02000000    // symbol is a trait
-  final val BRIDGE        = 0x04000000    // function is a bridge method. Set by Erasure
-  final val ACCESSOR      = 0x08000000    // a value or variable accessor
-
-  final val SUPERACCESSOR = 0x10000000    // a super accessor
-  final val PARAMACCESSOR = 0x20000000    // for value definitions: is an access method
-                                          // for a final val parameter
-                                          // for parameters: is a val parameter
-  final val MODULEVAR     = 0x40000000    // for variables: is the variable caching a module value
-  final val SYNTHETICMETH = 0x40000000    // for methods: synthetic method, but without SYNTHETIC flag
-  final val MONOMORPHIC   = 0x40000000    // for type symbols: does not have type parameters
-  final val LAZY          = 0x80000000L   // symbol is a lazy val. can't have MUTABLE unless transformed by typer
-
-  final val IS_ERROR      = 0x100000000L  // symbol is an error symbol
-  final val OVERLOADED    = 0x200000000L  // symbol is overloaded
-  final val LIFTED        = 0x400000000L  // class has been lifted out to package level
-                                          // local value has been lifted out to class level
-                                          // todo: make LIFTED = latePRIVATE?
-  final val MIXEDIN       = 0x800000000L  // term member has been mixed in
-  final val EXISTENTIAL   = 0x800000000L  // type is an existential parameter or skolem
-
-  final val EXPANDEDNAME  = 0x1000000000L // name has been expanded with class suffix
-  final val IMPLCLASS     = 0x2000000000L // symbol is an implementation class
-  final val PRESUPER      = 0x2000000000L // value is evaluated before super call
-  final val TRANS_FLAG    = 0x4000000000L // transient flag guaranteed to be reset
-                                          // after each phase.
-
-  final val LOCKED        = 0x8000000000L // temporary flag to catch cyclic dependencies
-
-  final val InitialFlags  = 0x000000FFFFFFFFFFL // flags that are enabled from phase 1.
-  final val LateFlags     = 0x000FFF0000000000L // flags that override flags in 0xFFF.
-  final val AntiFlags     = 0x7FF0000000000000L // flags that cancel flags in 0x7FF
-  final val LateShift     = 40L
-  final val AntiShift     = 52L
+
+package scala.tools.nsc
+package symtab
+
+object Flags extends reflect.generic.Flags {
+
+  final val InitialFlags  = 0x0001FFFFFFFFFFFFL // flags that are enabled from phase 1.
+  final val LateFlags     = 0x00FE000000000000L // flags that override flags in 0x1FC.
+  final val AntiFlags     = 0x7F00000000000000L // flags that cancel flags in 0x07F
+  final val LateShift     = 47L
+  final val AntiShift     = 56L
 
   // late flags (set by a transformer phase)
   final val latePRIVATE   = (PRIVATE: Long) << LateShift
@@ -103,7 +31,6 @@ object Flags extends Enumeration {
   final val notOVERRIDE   = (OVERRIDE: Long) << AntiShift
   final val notMETHOD     = (METHOD: Long) << AntiShift
 
-
   // masks
   /** This flags can be set when class or module symbol is first created. */
   final val TopLevelCreationFlags: Long =
@@ -117,39 +44,48 @@ object Flags extends Enumeration {
   /** These modifiers appear in TreePrinter output. */
   final val PrintableFlags: Long =
     ExplicitFlags | LOCAL | SYNTHETIC | STABLE | CASEACCESSOR |
-    ACCESSOR | SUPERACCESSOR | PARAMACCESSOR | BRIDGE | STATIC
+    ACCESSOR | SUPERACCESSOR | PARAMACCESSOR | BRIDGE | STATIC | VBRIDGE | SPECIALIZED
+
+  /** The two bridge flags */
+  final val BRIDGES = BRIDGE | VBRIDGE
 
   final val FieldFlags: Long =
     MUTABLE | CASEACCESSOR | PARAMACCESSOR | STATIC | FINAL | PRESUPER | LAZY
 
-  final val AccessFlags: Long   = PRIVATE | PROTECTED
+  final val AccessFlags: Long   = PRIVATE | PROTECTED | LOCAL
   final val VARIANCES     = COVARIANT | CONTRAVARIANT
   final val ConstrFlags: Long   = JAVA
-  final val PickledFlags: Long  = 0xFFFFFFFFL
 
   /** Module flags inherited by their module-class */
   final val ModuleToClassFlags: Long = AccessFlags | MODULE | PACKAGE | CASE | SYNTHETIC | JAVA
 
+  def getterFlags(fieldFlags: Long): Long = 
+    ACCESSOR + 
+    (if ((fieldFlags & MUTABLE) != 0) fieldFlags & ~MUTABLE & ~PRESUPER else fieldFlags & ~PRESUPER | STABLE)
+
+  def setterFlags(fieldFlags: Long): Long = 
+    getterFlags(fieldFlags) & ~STABLE & ~CASEACCESSOR
+
   private def listToString(ss: List[String]): String =
     ss.filter("" !=).mkString("", " ", "")
 
   def flagsToString(flags: Long): String =
-    listToString(for (i <- List.range(0, 63)) yield flagToString(flags & (1L << i)))
+    listToString(for (mask <- pickledListOrder) yield flagToString(flags & mask))
 
   def flagsToString(flags: Long, privateWithin: String): String = {
     var f = flags
     val pw =
       if (privateWithin == "") {
-        if ((flags & (PRIVATE | LOCAL)) == (PRIVATE | LOCAL)) {
+        if ((flags & (PRIVATE | LOCAL)) == (PRIVATE | LOCAL).toLong) {
           f = f & ~(PRIVATE | LOCAL)
           "private[this]"
-        } else if ((flags & (PROTECTED | LOCAL)) == (PROTECTED | LOCAL)) {
+        } else if ((flags & (PROTECTED | LOCAL)) == (PROTECTED | LOCAL).toLong) {
           f = f & ~(PROTECTED | LOCAL)
           "protected[this]"
         } else {
           ""
         }
-      } else if ((f & PROTECTED) != 0) {
+      } else if ((f & PROTECTED) != 0L) {
         f = f & ~PROTECTED
         "protected[" + privateWithin + "]"
       } else {
@@ -168,7 +104,8 @@ object Flags extends Enumeration {
     else if (flag == TRANS_FLAG  ) "<trans-flag>"
     else if (flag == LOCKED      ) "<locked>"
     else if (flag == LAZY        ) "lazy"
-    else flag.asInstanceOf[Int] match {
+    else if (flag == SPECIALIZED ) "<specialized>"
+    else flag.toInt match {
       case IMPLICIT      => "implicit"
       case FINAL         => "final"
       case PRIVATE       => "private"
@@ -187,7 +124,6 @@ object Flags extends Enumeration {
       case MUTABLE       => "<mutable>"
       case PARAM         => "<param>"
       case PACKAGE       => "<package>"
-      case DEPRECATED    => "<deprecated>"
 
       case COVARIANT     => "<covariant/captured/byname>"
       case CONTRAVARIANT => "<contravariant/label/inconstr/defaultinit>"
@@ -206,47 +142,16 @@ object Flags extends Enumeration {
 
       case SUPERACCESSOR => "<superaccessor>"
       case PARAMACCESSOR => "<paramaccessor>"
+      case VBRIDGE        => "<...bridge>"
 
       case _ => ""
     }
   }
 
   class Flag(mods: Long) {
-    def isPrivate   = (mods & PRIVATE  ) != 0
-    def isProtected = (mods & PROTECTED) != 0
-    def isVariable  = (mods &   MUTABLE) != 0
+    def isPrivate   = (mods & PRIVATE  ) != 0L
+    def isProtected = (mods & PROTECTED) != 0L
+    def isVariable  = (mods &   MUTABLE) != 0L
     def isPublic    = !isPrivate && !isProtected
   }
-  case class FlagEnum(mask: Long) extends Val(maskToBit(mask), flagToString(mask))
-
-  val Implicit      = FlagEnum(IMPLICIT)
-  val Final         = FlagEnum(FINAL)
-  val Private       = FlagEnum(PRIVATE)
-  val Protected     = FlagEnum(PROTECTED)
-  val Sealed        = FlagEnum(SEALED)
-  val Override      = FlagEnum(OVERRIDE)
-  val Case          = FlagEnum(CASE)
-  val Abstract      = FlagEnum(ABSTRACT)
-  val Deferred      = FlagEnum(DEFERRED)
-  val Method        = FlagEnum(METHOD)
-  val Module        = FlagEnum(MODULE)
-  val Interface     = FlagEnum(INTERFACE)
-  val Mutable       = FlagEnum(MUTABLE)
-  val Param         = FlagEnum(PARAM)
-  val Package       = FlagEnum(PACKAGE)
-  val Deprecated    = FlagEnum(DEPRECATED)
-  val Covariant     = FlagEnum(COVARIANT)
-  val Contravariant = FlagEnum(CONTRAVARIANT)
-  val AbsOverride   = FlagEnum(ABSOVERRIDE)
-  val Local         = FlagEnum(LOCAL) 
-  val Synthetic     = FlagEnum(SYNTHETIC)
-  val Stable        = FlagEnum(STABLE) 
-  val CaseAccessor  = FlagEnum(CASEACCESSOR)  
-  val Trait         = FlagEnum(TRAIT)
-  val Bridge        = FlagEnum(BRIDGE)  
-  val Accessor      = FlagEnum(ACCESSOR) 
-  val SuperAccessor = FlagEnum(SUPERACCESSOR)
-  val ParamAccessor = FlagEnum(PARAMACCESSOR)  
-  val ModuleVar     = FlagEnum(MODULEVAR)
-
 }
diff --git a/src/compiler/scala/tools/nsc/symtab/IdeSupport.scala b/src/compiler/scala/tools/nsc/symtab/IdeSupport.scala
deleted file mode 100644
index 9e5cc9a..0000000
--- a/src/compiler/scala/tools/nsc/symtab/IdeSupport.scala
+++ /dev/null
@@ -1,665 +0,0 @@
-package scala.tools.nsc.symtab 
-import scala.tools.nsc.util._   
-import scala.collection.jcl._
-import scala.collection.jcl
-import scala.tools.nsc.io._
-
-trait IdeSupport extends SymbolTable { // added to global, not analyzers.
-  trait ScopeClient {
-    def changed : Unit = {} 
-    def addTo(set : => LinkedHashSet[ScopeClient]) = set += this
-    def notify(name : Name, scope : HookedScope) : Boolean = false
-    def notify(name : Name, sym : Symbol) : Unit = {}
-    def verifyAndPrioritize[T](verify : Symbol => Symbol)(pt : Type)(f : => T) : T = f
-    def makeNoChanges : Boolean = false
-  }
-  def check(condition : Boolean, msg : => String) = {
-    assert(condition)
-    condition
-  }
-
-  override def inIDE = true
-  import CompatibleResult._
-  trait TrackedPosition extends Position with ReallyHasClients {
-    // symbols without scopes!
-    def asOffset : Option[(Int,AbstractFile)]
-    private var recycled : List[Symbol] = Nil
-    def recycle(sym : Symbol) : Symbol = {
-      recycled.foreach{existing => compatible(existing,sym) match {
-      case NotCompatible => false
-      case GoResult(existing) => return existing
-      }}
-      recycled = sym :: recycled; sym
-    }
-    private var scopes : List[((ScopeKind,AnyRef),PersistentScope)] = Nil
-    def scopeFor(key : (ScopeKind,AnyRef)) : PersistentScope = 
-      scopes.find{
-      case (key0,scope) if key == key0 => true
-      case _ => false
-      } match {
-      case Some((_,scope)) => reuse(scope)
-      case None => 
-        val scope = new PersistentScope(key,this)
-        scopes = (key,scope) :: scopes
-        scope
-      }
-  }
-  // dynamic context
-  private object NullClient extends ScopeClient {
-    override def addTo(clients : => LinkedHashSet[ScopeClient]) = {}
-  }
-  
-  def currentClient : ScopeClient = NullClient
-  abstract class HookedScope(entry : ScopeEntry) extends Scope(entry) {
-    def record(client : ScopeClient, name : Name) = {}
-    override def lookupEntry(name : Name) = {
-      val client = currentClient
-      if (client.notify(name, this)) null // not found
-      else {
-        record(client, name)
-        super.lookupEntry(name)
-      }
-    }
-  }
-  private val topDefs = new LinkedHashMap[AbstractFile,LinkedHashSet[ClassSymbol]] {
-    override def default(what : AbstractFile) = {
-      val set = new LinkedHashSet[ClassSymbol]
-      this(what) = set; set
-    }
-  }
-  private val emptySet = new jcl.LinkedList[Symbol]
-  val reuseMap = new LinkedHashMap[PersistentScope,jcl.LinkedList[Symbol]] {
-    override def default(key : PersistentScope) = emptySet
-  }
-  def reuse(scope : PersistentScope, sym : Symbol) = {
-    var e = scope.lookupEntry(sym.name)
-    var delete = List[Symbol]()
-    while (e != null && e.sym != sym) {
-      if (false && !e.sym.rawInfo.isComplete) {
-
-        delete = e.sym :: delete
-      }
-      e = scope.lookupNextEntry(e)
-    }
-    delete.foreach(scope.unlink)
-    if (e != null && e.sym == sym) {
-      
-      val list = reuseMap.get(scope) match {
-      case Some(list) => list
-      case None =>
-        val list = new jcl.LinkedList[Symbol]
-        reuseMap(scope) = list; list
-      }
-      check(!sym.isPackage, "" +sym)
-      import symtab.Flags._
-      // if def is abstract, will only unlink its name
-      if (sym.isGetter) {
-        val setter = scope lookup nme.getterToSetter(sym.name)
-        if (setter != NoSymbol && setter.isSetter) {
-          list += setter
-          scope unlink setter
-          //Console.println("RS-UNLINK: " + setter)
-        }
-      } else if (sym.hasGetter) { 
-        e = scope lookupEntry nme.getterName(sym.name)
-        while (e != null && !e.sym.isGetter && (!e.sym.hasFlag(ACCESSOR) || e.sym.accessed != sym)) { 
-          e = scope lookupNextEntry e
-        }
-        if (e != null && check(e.sym.accessed == sym, "accessed" + e.sym.accessed +" vs. " + sym) && check(!e.sym.isSetter, "setter: " + e.sym)) {
-          val getter = e.sym
-          check(e.sym.accessed == sym && !e.sym.isSetter, e.sym.toString)
-          list += getter
-          scope unlink getter
-          //Console.println("RS-UNLINK: " + getter)
-          e = scope lookupEntry nme.getterToSetter(getter.name)
-          while (e != null && !e.sym.isSetter) e = scope lookupNextEntry e
-          if (e != null) {
-            check(getter.accessed == sym, "" + getter + " vs. " + sym)
-            val setter = e.sym
-            list += setter
-            scope unlink setter
-            //Console.println("RS-UNLINK: " + setter)
-          }
-        }
-      } else if (sym.hasFlag(Flags.LAZY)) {
-        val getter = sym.lazyAccessor
-        if (getter != NoSymbol) {
-          list += getter
-          scope unlink getter
-        }
-      }
-      //Console.println("RS-UNLINK: " + sym)
-      list += sym
-      scope unlink sym // clear from scope.
-    }
-  }
-  private def reuse(scope : PersistentScope) : PersistentScope = {
-    if (currentClient.makeNoChanges) return scope
-    val buf = new jcl.LinkedList[Symbol]
-    scope.toList.foreach{sym =>
-      if (false && sym.hasFlag(Flags.CASE) && sym.hasFlag(Flags.SYNTHETIC)) {
-        check(sym != null, "")
-      } else {
-        buf add sym
-        scope unlink sym
-      }
-    }
-    if (!buf.isEmpty) {
-
-      reuseMap.get(scope) match {
-      case Some(buf0) => buf.foreach(buf0.+=)
-      case None => reuseMap(scope) = buf
-      }
-    }
-    scope
-  }
-  
-  def reloadSource(file : AbstractFile) = {
-    
-    if (!currentClient.makeNoChanges) topDefs.removeKey(file) match {
-  case None => 
-  case Some(symbols) => symbols.foreach{sym =>
-      def f(sym : Symbol) = sym.owner.info.decls match {
-      case scope : PersistentScope => reuse(scope, (sym))
-        case scope => 
-          check(false, scope + " is not persistent")
-      }
-      if (sym.isModuleClass) { 
-        if (check(sym.name.isTypeName,"") && sym.hasRawInfo)
-          if (sym.linkedModuleOfClass != NoSymbol) f(sym.linkedModuleOfClass)
-      } else {
-        if (check(sym.name.isTypeName, ""))
-          f(sym)
-      }
-    }
-  }
-  }
-  override def attachSource(clazz : ClassSymbol, file : io.AbstractFile) = {
-    topDefs(file) += clazz
-    super.attachSource(clazz, file)
-  }
-  def finishTyping = {
-    val clear = reuseMap.toList
-    reuseMap.clear
-    clear.foreach{
-    case (scope,old) => old.foreach{
-    case NoSymbol => 
-    case sym => 
-      // note that we didn't unlink them
-      val scope0 = scope
-      Console.println("RECYCLE: " + sym + ":" + sym.id + " in " + sym.owner); // + " " + scope0 + " " + scope0.key); 
-      scope0.invalidate(sym.name)
-    }}
-    reuseMap.clear
-    tracedTypes.toList.foreach{case (sym,oldType) =>
-      if (sym.rawInfo != NoType && !sym.rawInfo.isComplete) {
-        Console.println("XXX uncompleted: " + sym)
-      }
-      val syminfo = try {
-        sym.info
-      } catch {
-        case e => check(false, ""+e); NoType
-      }
-      
-      val resetType = syminfo == NoType || hasError(syminfo)
-      if (!resetType && !compareTypes(syminfo, oldType,Nil)(sym => tracedTypes.get(sym) match {
-      case None => syminfo 
-      case Some(oldType) => oldType
-      })) (trackedTypes.removeKey(sym) match {
-      case Some(set) => set.foreach(_.changed)
-      case None =>  
-      }) 
-      if (resetType) {
-
-        sym.setInfo(oldType) // restore old good type.
-      }
-    }
-    tracedTypes.clear
-  }
-  def oldTypeFor(sym : Symbol) = tracedTypes.get(sym) match {
-  case Some(tpe) => tpe
-  case None => NoType
-  }
-  
-  private def compare0(newP : Any, oldP : Any, syms : List[Symbol])(implicit oldType : Symbol => Type) : Boolean = ((newP,oldP) match {
-  case (newP:AnyRef,oldP:AnyRef) if newP eq oldP => true
-  case (newP:Type,oldP:Type) => compareTypes(newP,oldP, syms)
-  case (newS:Symbol,oldS:Symbol) if compareSyms(newS,oldS,syms) => true  
-  case (newL:List[a],oldL:List[b]) =>
-    var va = newL; var vb = oldL
-    while (!va.isEmpty && !vb.isEmpty) {
-      if (!compare0(va.head,vb.head,syms)) return false
-      va = va.tail; vb = vb.tail
-    }
-    va.isEmpty && vb.isEmpty
-  case (newS:Scope,oldS:Scope) =>
-    val set = new LinkedHashSet[Symbol]
-    set addAll newS.toList
-    oldS.toList.forall{oldS => if (!set.remove(oldS)) {
-      var other = newS.lookupEntry(oldS.name)
-      while (other != null && !compareTypes(other.sym.info,oldType(oldS), syms))
-        other = newS.lookupNextEntry(other)
-      other != null
-    } else true}
-  case (newP,oldP) => newP == oldP
-  })
-  private def compareSyms(newS : Symbol, oldS : Symbol, syms : List[Symbol])(implicit oldType : Symbol => Type) = 
-    if (oldS eq newS) {
-      if (syms.contains(oldS)) true
-      else {
-        compareTypes(newS.info, oldType(oldS), newS :: syms)
-      }
-    } else {
-      if (syms.contains(oldS) && syms.contains(newS)) true
-      else newS.name == oldS.name && newS.owner == oldS.owner && newS.flags == oldS.flags &&
-        compareTypes(newS.info,oldType(oldS), newS :: oldS :: syms)
-    }
-
-  def hasError(infoA : Type) : Boolean = {
-    if (infoA == ErrorType) return true
-    infoA match {
-    case MethodType(args,ret) => hasError(ret) || args.exists(hasError)
-    case PolyType(params,ret) => hasError(ret)
-    case TypeBounds(lo,hi) => hasError(lo) || hasError(hi)
-    case TypeRef(pre,_,args) => hasError(pre) || args.exists(hasError)
-    case _ => false
-    }
-  }
-  def compareTypes(newInfo : Type, oldInfo : Type, syms : List[Symbol])(implicit oldType : Symbol => Type) : Boolean = (newInfo eq oldInfo) || (newInfo.getClass == oldInfo.getClass && ((newInfo,oldInfo) match {
-  case (newInfo:ThisType,oldInfo:ThisType) if compare0(newInfo.typeSymbol,oldInfo.typeSymbol,syms) => true 
-  case (newInfo:Product, oldInfo:Product) =>
-    (0 until newInfo.productArity).forall(i => 
-      compare0(newInfo.productElement(i), oldInfo.productElement(i),syms))
-  }))
-  
-  trait HasClients {
-    def record(client : ScopeClient, name : Name) : Unit 
-    def record(client : Function1[PersistentScope,Unit]) : Unit
-    def invalidate(from : PersistentScope, name : Name) : Unit
-  }
-  
-  trait ReallyHasClients extends HasClients {
-    private var clients : Map = null
-    private var anyClients : LinkedHashSet[Function1[PersistentScope,Unit]] = null
-    private class Map extends LinkedHashMap[Int,LinkedHashSet[ScopeClient]] {
-      override def default(hash : Int) = {
-        val set = new LinkedHashSet[ScopeClient]
-        this(hash) = set; set
-      }
-    }
-    def record(client : ScopeClient, name : Name) : Unit = 
-      client.addTo({
-        if (clients eq null) clients = new Map
-        clients(name.start)
-      })
-    def record(client : Function1[PersistentScope,Unit]) = {
-      if (anyClients == null) anyClients = new LinkedHashSet[Function1[PersistentScope,Unit]]
-      anyClients += client
-    }
-    
-    override def invalidate(from : PersistentScope, name : Name) : Unit = {
-      if (clients ne null) clients.removeKey(name.start) match {
-      case Some(clients) => clients.foreach(_.changed)
-      case None =>
-      }
-      if (anyClients != null) {
-        var c = anyClients
-        anyClients = null
-        c.foreach(_.apply(from))
-      }
-    }
-  }
-    
-  
-  class PersistentScope(val key : AnyRef, val owner : HasClients) extends HookedScope(null) {
-    override def record(client : ScopeClient, name : Name) = 
-      owner.record(client, name)
-    override def invalidate(name : Name) : Unit = owner.invalidate(this,name)
-    override def enter(symbol : Symbol) : Symbol = {
-      if (currentClient.makeNoChanges) { // might have unpickles.
-        return if (lookupEntry(symbol.name) == null) 
-          super.enter(symbol)
-        else symbol
-      }
-      def finish(symbol : Symbol) = {
-        if (symbol.isTypeSkolem) {
-
-        }
-        if (symbol.owner.isPackageClass && !symbol.isPackageClass && symbol.sourceFile != null) {
-
-          topDefs(symbol.sourceFile) += (symbol match {
-            case symbol : ClassSymbol => symbol
-            case symbol : ModuleSymbol => symbol.moduleClass.asInstanceOf[ClassSymbol]
-          })
-        }
-        super.enter(symbol)
-      }
-      def nuke(existing: Symbol) : Unit = {
-        if (existing.isMonomorphicType) existing.resetFlag(Flags.MONOMORPHIC)
-        assert(!existing.isPackage)
-        existing.attributes = Nil // reset attributes, we don't look at these.
-        if (existing.isModuleClass) {
-          //Console.println("NUKE_N: " + existing + " " + existing.id)
-        } else {
-          existing.setInfo(if (symbol.hasRawInfo) symbol.rawInfo else NoType)
-        }
-        if (existing.isModule && existing.moduleClass != NoSymbol){
-          //Console.println("NUKE_0: " + existing + " " + existing.id)
-          //Console.println("NUKE_1: " + existing.moduleClass + " " + existing.moduleClass.id)
-          existing.moduleClass.setInfo(if (symbol.moduleClass.hasRawInfo) symbol.moduleClass.rawInfo else NoType)
-        }
-      }
-      
-      def reuse(existing : Symbol) : Symbol = {
-        def record(existing : Symbol) = if (existing.hasRawInfo && 
-          existing.rawInfo.isComplete && existing.rawInfo != NoType && !hasError(existing.rawInfo)) {
-          tracedTypes(existing) = existing.info
-        }
-        record(existing)
-        nuke(existing)
-        if (existing.pos == NoPosition) {
-
-        }
-        
-        finish(existing)
-      }
-      val symX = lookup(symbol.name)
-      if (symX != NoSymbol) {
-        if (symX == symbol) return (symX)
-        if (!symbol.hasRawInfo && symX.hasRawInfo && symX.rawInfo.isComplete && 
-            symbol.pos.isInstanceOf[TrackedPosition] && symX.pos.isInstanceOf[TrackedPosition] &&
-            symbol.pos == symX.pos) compatible(symX, symbol) match {
-        case NotCompatible => // do nothing
-        case code at GoResult(existing0) =>
-          val existing = existing0
-          if (code.isInstanceOf[Updated]) {
-            invalidate(existing.name)
-          }
-          nuke(existing)
-          return (existing)
-        }
-      }
-      if (symbol == NoSymbol) return symbol
-      // catch double defs.
-      record(currentClient, symbol.name)
-      val i = reuseMap(this).elements
-      while (i.hasNext) {
-        var existing = i.next
-        if (existing == symbol) return {
-
-          i.remove
-          finish(existing)
-        } 
-        else if ({
-          if (existing.hasFlag(symtab.Flags.SYNTHETIC) && existing.name == symbol.name) true
-          else (symbol.pos,existing.pos) match {
-          case (apos : TrackedPosition, bpos : TrackedPosition) => apos == bpos
-          case (apos : OffsetPosition , bpos : OffsetPosition) => apos == bpos
-          case _ => existing.name == symbol.name
-          }
-        }) {
-          if (check(existing != NoSymbol,"")) {
-            val oldName = existing.name
-            compatible(existing, symbol) match {
-              case NotCompatible =>
-
-              case code at GoResult(existing0) =>
-                i.remove
-                existing = existing0
-                if (code.isInstanceOf[Updated]) {
-                  invalidate(oldName)
-                  invalidate(existing.name)
-                }
-                return (reuse(existing))
-            }
-          }
-        }
-      }
-      invalidate(symbol.name)
-      return finish(symbol)
-    }
-  }
-  private val tops = new LinkedHashMap[OffsetPosition,Symbol]
-  
-  protected def compatible(existing : Symbol, symbol : Symbol) : Result = {
-    import scala.tools.nsc.symtab.Flags._
-    if (existing.hasRawInfo && symbol.hasRawInfo) {
-      
-      
-    }
-
-    
-    if (existing.getClass != symbol.getClass) (existing,symbol) match {
-    case (existing:TypeSkolem,symbol:TypeSymbol) => 
-      val other = existing.deSkolemize
-      return if (!other.isSkolem)
-        compatible(other,symbol)
-      else NotCompatible
-    case _ => return NotCompatible
-    }
-    if (existing.isGetter != symbol.isGetter) return NotCompatible
-    if (existing.isSetter != symbol.isSetter) return NotCompatible
-    if (existing.owner != symbol.owner) return NotCompatible
-    if (existing.name != symbol.name || existing.name.length != symbol.name.length) {
-      val ret = (!existing.name.toString.contains('$') && 
-        !symbol.name.toString.contains('$') &&
-          !(existing hasFlag SYNTHETIC) && !(symbol hasFlag SYNTHETIC) && {
-        existing.name.isTypeName == symbol.name.isTypeName &&
-          nme.isSetterName(existing.name) == nme.isSetterName(symbol.name) &&
-            nme.isLocalName(existing.name) == nme.isLocalName(symbol.name)
-      })
-      if (!ret) return NotCompatible
-    }
-    // because module var shares space with monomorphic.
-    if (existing.isModuleVar != symbol.isModuleVar) return NotCompatible
-    if ((existing.flags|LOCKED|INTERFACE|MONOMORPHIC|DEFERRED|ABSTRACT|PRIVATE|PROTECTED|FINAL|SEALED|CASE|SYNTHETIC) != 
-        (symbol.  flags|LOCKED|INTERFACE|MONOMORPHIC|DEFERRED|ABSTRACT|PRIVATE|PROTECTED|FINAL|SEALED|CASE|SYNTHETIC)) {
-      return NotCompatible
-    }
-    if (((existing.flags&(MONOMORPHIC|INTERFACE)) != 0) ||
-        ((symbol  .flags&(MONOMORPHIC|INTERFACE)) != 0)) {
-
-    }
-    val ret = (existing.owner == symbol.owner || {
-      existing.owner.name == symbol.owner.name && // why????
-        (existing.owner.name == nme.ANON_FUN_NAME||symbol.owner.name == nme.ANON_FUN_NAME) &&
-          existing.owner.pos == symbol.owner.pos
-    })
-    if (!ret) return NotCompatible
-    existing.setPos(symbol.pos) // not significant for updating purposes.
-    if ((existing.privateWithin != symbol.privateWithin || 
-        existing.name != symbol.name || ((existing.flags|LOCKED|MONOMORPHIC|INTERFACE) != (symbol.flags|LOCKED|MONOMORPHIC|INTERFACE)))) {
-      existing.name = (symbol.name)
-      // don't reset the monomorphic bit until we reset the type.
-      existing.flags = symbol.flags
-      existing.privateWithin = symbol.privateWithin
-      return new Updated(existing)
-    }
-    return new Compatible(existing)
-  }
-  protected object CompatibleResult {
-    abstract class Result {
-      def map(symbol : Symbol) : Result = this
-    }
-    case object NotCompatible extends Result
-    case class GoResult(val symbol : Symbol) extends Result {
-    }
-    class Compatible(override val symbol : Symbol) extends GoResult(symbol) {
-      override def map(symbol : Symbol) = new Compatible(symbol)
-    }
-    class Updated(override val symbol : Symbol) extends GoResult(symbol) {
-      override def map(symbol : Symbol) = new Updated(symbol)
-    }
-  }
-  
-  private class DefInfo extends ReallyHasClients {
-    var ref : scala.ref.WeakReference[Symbol] = _
-    var scopes : List[(PersistentScope)] = Nil
-    def scope(kind : ScopeKind) = scopes.find(_.key == kind) match {
-    case Some(scope) => scope
-    case None => 
-      val scope = new PersistentScope(kind,this)
-      check(scope.key == kind, ""+scope.key + " " + scope.toString)
-      scopes = (scope) :: scopes
-      scope
-    }
-  }
-  
-  private val defMap = new WeakHashMap[Symbol,DefInfo] {
-    override def default(clazz : Symbol) = {
-      val ref = new scala.ref.WeakReference(clazz)
-      val info = new DefInfo
-      this(clazz) = info
-      info.ref = ref
-      info
-    }
-  }
-  override def newClassScope(clazz : Symbol) = {
-    newDefScope0({
-      if (clazz.isModuleClass && !clazz.isPackageClass) {
-
-        clazz
-      } else if (clazz.isModule && !clazz.isPackage) {
-
-        clazz.moduleClass
-      } else clazz
-    }, ClassKind)
-  }
-  private lazy val ClassKind = allocateScopeKind("class")
-  private def newDefScope0(sym : Symbol, key : ScopeKind) = reuse(defMap(sym).scope(key))
-
-  override def recycle(sym : Symbol) = sym.pos match {
-  case pos : TrackedPosition => pos.recycle(sym)
-  case _ => super.recycle(sym)
-  }
-  override def newLocalDummy(clazz : Symbol, pos : util.Position) = 
-    recycle(super.newLocalDummy(clazz,pos)).asInstanceOf[TermSymbol]
-
-  def newScope(pos : Position, key : (ScopeKind,AnyRef), old : Option[Scope]) : Scope = pos match {
-  case pos : TrackedPosition => pos.scopeFor(key)
-  case _ if old.isEmpty => newScope(null : ScopeEntry)
-  case _ => super.scopeFor(old.get, null,key._1)
-  }
-  
-  private def scopeFor00(tree : Tree, old : Option[Scope], kind : ScopeKind) = (tree,tree.symbol) match {
-  case (_,null|NoSymbol) => newScope(tree.pos, (kind,tree.getClass), (old))
-  case (tree : DefTree, sym) => newDefScope0((sym),kind) // indexed by symbol 
-  case _ => newScope(tree.pos, (kind,tree.getClass), old)
-  }
-  
-  override def scopeFor(old : Scope, tree : Tree, kind : ScopeKind) = scopeFor00(tree, Some(old), kind)
-  override def scopeFor(tree : Tree, kind : ScopeKind) = scopeFor00(tree, None, kind)
-  override def newScope(initElements : ScopeEntry) : Scope = {
-    object owner extends ReallyHasClients
-    new PersistentScope(null, owner)
-  }
-  import scala.collection.jcl
-  override def newPackageScope(depends0 : PackageScopeDependMap) : PackageScope = {
-    object owner extends ReallyHasClients
-    object myPackageScope extends PersistentScope(null, owner) with PackageScope {
-      val depends = depends0
-    }
-    myPackageScope
-  }
-  
-  
-  override def newTempScope : Scope = new TemporaryScope
-  private class TemporaryScope extends HookedScope(null) {
-    override def hashCode = toList.map(_.hashCode).foldLeft(0)(_ + _)
-    override def equals(that : Any) = that match {
-    case that : TemporaryScope if this eq that => true
-    case that : TemporaryScope => // do a brute force comparison
-      val l0 = this.toList
-      val l1 = that.toList
-      l0.size == l1.size && l0.forall(l1.contains)
-    case _ => false
-    }
-  } 
-  private class ThrowAwayScope(decls : List[Symbol]) extends HookedScope(null:ScopeEntry) {
-    decls.foreach(d => enter(d))
-  }
-  override def newThrowAwayScope(decls : List[Symbol]) : Scope= new ThrowAwayScope(decls)
-  
-  private val trackedTypes = new LinkedHashMap[Symbol,LinkedHashSet[ScopeClient]] {
-    override def default(sym : Symbol) = {
-      val set = new LinkedHashSet[ScopeClient]
-      this(sym) = set; set
-    }
-  }
-  // trace symbols whose types are watched!
-  private val tracedTypes = new LinkedHashMap[Symbol,Type]
-
-  override def trackTypeIDE(sym : Symbol): Boolean = if (sym != NoSymbol && !sym.isPackageClass && !sym.isPackage) {
-    // will wind up watching a lot of stuff!
-    currentClient.addTo(trackedTypes(sym))
-    super.trackTypeIDE(sym)
-  } else super.trackTypeIDE(sym)
-  override def mkConstantType(value: Constant): ConstantType = {
-    super.mkConstantType(Constant(value.value match {
-    case _ : Int => 0 : Int
-    case _ : Long => 0 : Long
-    case _ : Byte => 0 : Byte
-    case _ : Char => 0 : Char
-    case _ : Short => 0 : Short
-    case _ : Float => 0 : Float
-    case _ : Double => 0 : Double
-    case _ : String => "string"
-    case _ : scala.Symbol => Symbol("symbol")
-    case value => value
-    }))
-  }
-  // mostly intellisense hacks. 
-  override def verifyAndPrioritize[T](verify : Symbol => Symbol)(pt : Type)(f : => T) : T = {
-    try {
-    currentClient.verifyAndPrioritize(verify)(pt)(f)
-    } catch {case e : Error=>
-      throw e
-    }
-  }
-  override def compare(sym : Symbol, name : Name) = {
-    val client = currentClient
-    sym.info.decls match {
-    case scope : HookedScope => 
-      scope.record(client, name)
-    case _ => 
-    }
-    client.notify(name, sym)
-    super.compare(sym, name)
-  } 
-  override def notifyImport(what : Name, container : Type, from : Name, to : Name) : Unit = {
-    super.notifyImport(what, container, from, to)
-    // sanity checking.
-    if ((container eq null) || 
-        (what      eq null) ||
-        (from      eq null) ||
-        (currentClient eq null)) return   
-    val from0 = if (what.isTypeName) from.toTypeName else from.toTermName
-    val result = container.member(from0)
-    if (result != NoSymbol)
-      currentClient.notify(what, result)
-  }
-  
-  object lightDuplicator extends Transformer {
-    override val copy = new StrictTreeCopier
-  }
-  // make the trees less detailed.
-  override def sanitize(tree : Tree) : Tree = lightDuplicator.transform(tree match {
-  case Template(_,vdef,_) => Template(Nil, sanitize(vdef).asInstanceOf[ValDef], Nil)
-  case PackageDef(nme, _) => PackageDef(nme, Nil)
-  case DefDef(mods, _, _, _, _:TypeTree, _) => DefDef(NoMods, nme.ERROR, Nil, Nil, TypeTree(), Literal(()))
-  case DefDef(mods, _, _, _, restpt, _) => DefDef(NoMods, nme.ERROR, Nil, Nil, sanitize(restpt), Literal(()))
-  case ValDef(_, _, _ : TypeTree, _) => ValDef(NoMods, nme.ERROR, TypeTree(), EmptyTree)
-  case ValDef(_, _, restpt, _) => ValDef(NoMods, nme.ERROR, sanitize(restpt), EmptyTree)
-  case ModuleDef(_, _, impl) =>
-    ModuleDef(NoMods, nme.ERROR, sanitize(impl).asInstanceOf[Template])
-  case ClassDef(_, _, tparams, impl) =>
-    ClassDef(NoMods, nme.ERROR.toTypeName, Nil, sanitize(impl).asInstanceOf[Template])
-  case DocDef(_, definition) => sanitize(definition)
-  case CaseDef(x, y, z) => CaseDef(Literal(()), EmptyTree, Literal(()))
-  case Block(_, _) => Block(Nil, Literal(()))
-  case Function(vparams,body) => 
-    Function(vparams.map(sanitize).asInstanceOf[List[ValDef]],Literal(())) 
-  case _ => tree
-  }).setPos(tree.pos)
-
-}
diff --git a/src/compiler/scala/tools/nsc/symtab/InfoTransformers.scala b/src/compiler/scala/tools/nsc/symtab/InfoTransformers.scala
index 2bda0ba..95dcb07 100644
--- a/src/compiler/scala/tools/nsc/symtab/InfoTransformers.scala
+++ b/src/compiler/scala/tools/nsc/symtab/InfoTransformers.scala
@@ -1,10 +1,10 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: InfoTransformers.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.tools.nsc.symtab
+package scala.tools.nsc
+package symtab
 
 trait InfoTransformers {
   self: SymbolTable =>
diff --git a/src/compiler/scala/tools/nsc/symtab/Names.scala b/src/compiler/scala/tools/nsc/symtab/Names.scala
index bab217b..a5fa712 100644
--- a/src/compiler/scala/tools/nsc/symtab/Names.scala
+++ b/src/compiler/scala/tools/nsc/symtab/Names.scala
@@ -1,13 +1,13 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: Names.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.tools.nsc.symtab
+package scala.tools.nsc
+package symtab
 
-import scala.tools.nsc.util.NameTransformer
-import scala.tools.util.UTF8Codec
+import scala.reflect.NameTransformer
+import scala.io.Codec
 import java.security.MessageDigest
 
 /** The class <code>Names</code> ...
@@ -15,7 +15,7 @@ import java.security.MessageDigest
  *  @author  Martin Odersky
  *  @version 1.0, 05/02/2005
  */
-class Names {
+trait Names extends reflect.generic.Names { 
 
 // Operations -------------------------------------------------------------
 
@@ -74,7 +74,7 @@ class Names {
     while (i < len) {
       if (nc + i == chrs.length) {
         val newchrs = new Array[Char](chrs.length * 2)
-        Array.copy(chrs, 0, newchrs, 0, chrs.length)
+        compat.Platform.arraycopy(chrs, 0, newchrs, 0, chrs.length)
         chrs = newchrs
       }
       chrs(nc + i) = cs(offset + i)
@@ -86,24 +86,18 @@ class Names {
 
   private lazy val md5 = MessageDigest.getInstance("MD5")
 
-  private def toMD5(s: String, prefixSuffixLen: Int) = {
-//  println("COMPACTIFY "+s)
-    val cs: Array[Char] = s.toCharArray
-    val bytes = new Array[Byte](cs.length * 4)
-    val len = UTF8Codec.encode(cs, 0, bytes, 0, cs.length)
-    md5.update(bytes, 0, len)
-    val hash = md5.digest()
-    val sb = new StringBuilder
-    sb.append(cs, 0, prefixSuffixLen)
-    sb.append("$$$$")
-    for (i <- 0 until hash.length) {
-      val b = hash(i)
-      sb.append(((b >> 4) & 0xF).toHexString)
-      sb.append((b & 0xF).toHexString)
-    }
-    sb.append("$$$$")
-    sb.append(cs, len - prefixSuffixLen, prefixSuffixLen)
-    sb.toString
+  /** "COMPACTIFY" */
+  private def toMD5(s: String, edge: Int) = {
+    val prefix = s take edge
+    val suffix = s takeRight edge
+    val marker = "$$$$"
+    
+    val cs = s.toArray
+    val bytes = Codec fromUTF8 cs
+    md5 update bytes
+    val md5chars = md5.digest() map (b => (b & 0xFF).toHexString) mkString
+    
+    prefix + marker + md5chars + marker + suffix
   }
 
   def compactify(s: String): String =
@@ -141,11 +135,8 @@ class Names {
    *  @param len    ...
    *  @return       the created term name
    */
-  def newTermName(bs: Array[Byte], offset: Int, len: Int): Name = {
-    val cs = new Array[Char](bs.length)
-    val nchrs = UTF8Codec.decode(bs, offset, cs, 0, len)
-    newTermName(cs, 0, nchrs)
-  }
+  def newTermName(bs: Array[Byte], offset: Int, len: Int): Name =
+    newTermName(Codec toUTF8 bs.slice(offset, offset + len) mkString)
 
   /** Create a type name from the characters in <code>cs[offset..offset+len-1]</code>.
    *
@@ -172,6 +163,8 @@ class Names {
   def newTypeName(bs: Array[Byte], offset: Int, len: Int): Name =
     newTermName(bs, offset, len).toTypeName
 
+  def mkTermName(name: Name) = name.toTermName
+  def mkTypeName(name: Name) = name.toTypeName
 
   def nameChars: Array[Char] = chrs
 
@@ -208,7 +201,7 @@ class Names {
      *  @param offset ...
      */
     final def copyChars(cs: Array[Char], offset: Int) =
-      Array.copy(chrs, index, cs, offset, len)
+      compat.Platform.arraycopy(chrs, index, cs, offset, len)
 
     /** return the ascii representation of this name
      */
@@ -227,8 +220,11 @@ class Names {
      *  Array must have enough remaining space for all bytes 
      *  (i.e. maximally 3*length bytes).
      */
-    final def copyUTF8(bs: Array[Byte], offset: Int): Int =
-      UTF8Codec.encode(chrs, index, bs, offset, len)
+    final def copyUTF8(bs: Array[Byte], offset: Int): Int = {
+      val bytes = Codec fromUTF8 chrs.slice(index, index + len)
+      compat.Platform.arraycopy(bytes, 0, bs, offset, bytes.length)
+      offset + bytes.length
+    }
 
     /** return the hash value of this name
      */
@@ -348,6 +344,13 @@ class Names {
       i > suffix.length
     }
 
+    final def containsName(subname: Name): Boolean = {
+      var start = 0
+      val last = len - subname.length
+      while (start <= last && !startsWith(subname, start)) start += 1
+      start <= last
+    }
+
     /** Return the subname with characters from start to end-1.
      *
      *  @param from ...
@@ -389,6 +392,8 @@ class Names {
     def decode: String = (
       NameTransformer.decode(toString()) +
       (if (nameDebug && isTypeName) "!" else ""))//debug
+    
+    def isOperatorName: Boolean = decode != toString
   }
 
   private class TermName(index: Int, len: Int, hash: Int) extends Name(index, len) {
diff --git a/src/compiler/scala/tools/nsc/symtab/Positions.scala b/src/compiler/scala/tools/nsc/symtab/Positions.scala
new file mode 100644
index 0000000..bb678e0
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/symtab/Positions.scala
@@ -0,0 +1,39 @@
+package scala.tools.nsc
+package symtab
+
+import ast.Trees
+import scala.tools.nsc.util.{SourceFile, Position, RangePosition, OffsetPosition, NoPosition, WorkScheduler}
+import scala.collection.mutable.ListBuffer
+
+trait Positions { 
+self: scala.tools.nsc.symtab.SymbolTable =>
+
+  def rangePos(source: SourceFile, start: Int, point: Int, end: Int) = 
+    new OffsetPosition(source, point)
+
+  /** A position that wraps a set of trees.
+   *  The point of the wrapping position is the point of the default position.
+   *  If some of the trees are ranges, returns a range position enclosing all ranges
+   *  Otherwise returns default position.
+   */
+  def wrappingPos(default: Position, trees: List[Tree]): Position = default
+
+  /** A position that wraps the non-empty set of trees.
+   *  The point of the wrapping position is the point of the first trees' position.
+   *  If all some the trees are non-synthetic, returns a range position enclosing the non-synthetic trees
+   *  Otherwise returns a synthetic offset position to point.
+   */
+  def wrappingPos(trees: List[Tree]): Position = trees.head.pos
+
+  /** Ensure that given tree has no positions that overlap with
+   *  any of the positions of `others`. This is done by
+   *  shortening the range or assigning TransparentPositions
+   *  to some of the nodes in `tree`.
+   */
+  def ensureNonOverlapping(tree: Tree, others: List[Tree]) {}
+
+  def validatePositions(tree: Tree) {}
+
+  type Position = scala.tools.nsc.util.Position
+  val NoPosition = scala.tools.nsc.util.NoPosition
+}
diff --git a/src/compiler/scala/tools/nsc/symtab/Scopes.scala b/src/compiler/scala/tools/nsc/symtab/Scopes.scala
index dabecde..ea5d0d7 100644
--- a/src/compiler/scala/tools/nsc/symtab/Scopes.scala
+++ b/src/compiler/scala/tools/nsc/symtab/Scopes.scala
@@ -1,18 +1,27 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: Scopes.scala 16894 2009-01-13 13:09:41Z cunei $
-
-package scala.tools.nsc.symtab
 
+package scala.tools.nsc
+package symtab
+
+// Martin: I am about 1/4 way on a cleanup of scopes.
+// The most important change is that scopes are now Iterables.
+// This removed the need for the various iterators on ScopeEntries.
+// ScopeEntries are conceptually an internal representation detail,
+// so it's better not to return them in public iterators.
+// It's true that other code also references ScopeEntries but that's
+// done for performance (and could be reviewed).
+// Another addition is a lookupAll method that returns all symbols with
+// a name in a scopein an iterator.
 trait Scopes {
   self: SymbolTable =>
 
   class ScopeEntry(val sym: Symbol, val owner: Scope) {
     /** the next entry in the hash bucket
      */
-    var tail: ScopeEntry = _
+    var tail: ScopeEntry = null
 
     /** the next entry in this scope
      */
@@ -27,90 +36,18 @@ trait Scopes {
    *  @param owner ...
    *  @return      ...
    */
-  def newScopeEntry(sym: Symbol, owner: Scope): ScopeEntry = {
+  private def newScopeEntry(sym: Symbol, owner: Scope): ScopeEntry = {
     val e = new ScopeEntry(sym, owner)
     e.next = owner.elems
     owner.elems = e
     e
   }
 
-  object NoScopeEntry extends ScopeEntry(NoSymbol, null)
-
-  /**
-   *  @param initElems ...
-   *  @return          ...
-   */
-  def newScope(initElems: ScopeEntry): Scope = new NormalScope(initElems)
-  final def newScope: Scope = newScope(null: ScopeEntry)
-  trait PackageScopeDependMap {
-    def createDepend(from : Symbol, name : Name) : Unit
-  }
-  
-  def newPackageScope(depends0 : PackageScopeDependMap) : PackageScope = {
-    object MyPackageScope extends NormalScope(null : ScopeEntry) with PackageScope {
-      val depends = depends0
-    }
-    MyPackageScope
-  }
-   
-  def newTempScope = newScope(null : ScopeEntry)
-  class ScopeKind(name : String) { override def toString = name }
-  def allocateScopeKind(name : String) = new ScopeKind(name)
-  lazy val Constructor0ScopeKind : ScopeKind = allocateScopeKind("constructors0")
-  lazy val Constructor1ScopeKind : ScopeKind = allocateScopeKind("constructors1")
-  lazy val InnerScopeKind : ScopeKind = allocateScopeKind("inner")
-  lazy val FinishWithScopeKind : ScopeKind = allocateScopeKind("finishWith")
-  lazy val TypeSigScopeKind : ScopeKind = allocateScopeKind("typeSig")
-  lazy val PolyTypeCompleterScopeKind : ScopeKind = allocateScopeKind("polyType")
-  lazy val CompoundTreeScopeKind : ScopeKind = allocateScopeKind("compoundTree")
-  lazy val FreshArgScopeKind : ScopeKind = allocateScopeKind("freshArgs")
-  lazy val LabelScopeKind : ScopeKind = allocateScopeKind("label")
-  lazy val TypedCasesScopeKind : ScopeKind = allocateScopeKind("typedCases")
-  lazy val TypedDefScopeKind : ScopeKind = allocateScopeKind("typedDef")
-  //lazy val ParentTypesScopeKind : ScopeKind = allocateScopeKind("parentType")
-  lazy val TypedScopeKind : ScopeKind = allocateScopeKind("typed")
-  // have to sometimes use constructor depth unfortunately.
-  case class ParentTypesScopeKind(clazz : Symbol) extends ScopeKind("parentType") { override def toString = super.toString + "-" + clazz }
-  case class BlockScopeKind(depth : Int) extends ScopeKind("block") { override def toString = super.toString + "-" + depth }
-  
-  def newClassScope(clazz : Symbol) = newScope // for use in ClassInfoType creation
-  def scopeFor(             tree : Tree, kind : ScopeKind) : Scope = newScope
-  def scopeFor(old : Scope, tree : Tree, kind : ScopeKind) : Scope = newScope(old)
-  
-  final def newScope(base: Scope) : Scope = newScope(base.elems)
-  final def newScope(decls: List[Symbol]) : Scope = {
-    val ret = newScope
-    decls.foreach(d => ret.enter(d))
-    ret
-  }
-  def newThrowAwayScope(decls : List[Symbol]) : Scope = newScope(decls)
-  // for symbols that don't exist in scopes! 
-  def recycle(sym : Symbol) : Symbol = sym
-  def newLocalDummy(clazz : Symbol, pos : util.Position) = clazz.newLocalDummy(pos)
-
-  private class NormalScope(initElems: ScopeEntry) extends Scope(initElems)
-
-  trait PackageScope extends Scope {
-    val depends : PackageScopeDependMap
-    override def lookupEntryWithContext(name : Name)(from : Symbol) = {
-      if (from != NoSymbol && depends != null) {
-        depends.createDepend(from,name)
-      }
-      super.lookupEntryWithContext(name)(from)
-    }
-    override def lookupWithContext(name : Name)(from : Symbol) = {
-      if (from != NoSymbol && depends != null) {
-        depends.createDepend(from,name)
-      }
-      super.lookupWithContext(name)(from)
-    }
-  }
-  
-  abstract class Scope(initElems: ScopeEntry)  {
+  class Scope(initElems: ScopeEntry) extends AbsScope {
 
     var elems: ScopeEntry = initElems
 
-    /** The number of times this scope is neted in another
+    /** The number of times this scope is nested in another
      */
     private var nestinglevel = 0
 
@@ -138,39 +75,26 @@ trait Scopes {
 
     def this(base: Scope) = {
       this(base.elems)
-/*
-      if (base.hashtable ne null) {
-        this.hashtable = new Array[ScopeEntry](HASHSIZE)
-        System.arraycopy(base.hashtable, 0, this.hashtable, 0, HASHSIZE)
-      }
-*/
       nestinglevel = base.nestinglevel + 1
     }
 
     def this(decls: List[Symbol]) = {
       this()
-      decls.foreach(sym => enter(sym))
+      decls foreach enter
     }
 
     /** Returns a new scope with the same content as this one. */
     def cloneScope: Scope = {
-      val clone = newScope
-      this.toList.foreach(sym => clone.enter(sym))
+      val clone = new Scope()
+      this.toList foreach (clone enter _)
       clone
     }
-    /* clear the contents of this scope */
-    def clear = {
-      elems = null
-      elemsCache = null
-      hashtable = null
-    }
-    
 
     /** is the scope empty? */
-    def isEmpty: Boolean = elems eq null
+    override def isEmpty: Boolean = elems eq null
 
     /** the number of entries in this scope */
-    def size: Int = {
+    override def size: Int = {
       var s = 0
       var e = elems
       while (e ne null) {
@@ -199,7 +123,7 @@ trait Scopes {
      *
      *  @param sym ...
      */
-    def enter(sym: Symbol) : Symbol = { enter(newScopeEntry(sym, this)); sym }
+    def enter(sym: Symbol): Symbol = { enter(newScopeEntry(sym, this)); sym }
 
     /** enter a symbol, asserting that no symbol with same name exists in scope
      *
@@ -292,15 +216,19 @@ trait Scopes {
       val e = lookupEntry(name)
       if (e eq null) NoSymbol else e.sym
     }
-    /** Can lookup symbols and trace who the client is. 
+
+    /** Returns an iterator yielding every symbol with given name in this scope.
      */
-    def lookupEntryWithContext(name : Name)(from : Symbol) : ScopeEntry = lookupEntry(name)
-    def lookupWithContext(name : Name)(from : Symbol) : Symbol = lookup(name)
+    def lookupAll(name: Name): Iterator[Symbol] = new Iterator[Symbol] {
+      var e = lookupEntry(name)
+      def hasNext: Boolean = e ne null
+      def next: Symbol = { val r = e.sym; e = lookupNextEntry(e); r }
+    }
 
     /** lookup a symbol entry matching given name.
-     *
-     *  @param name ...
-     *  @return     ...
+     *  @note from Martin: I believe this is a hotspot or will be one
+     *  in future versions of the type system. I have reverted the previous
+     *  change to use iterators as too costly.
      */
     def lookupEntry(name: Name): ScopeEntry = {
       var e: ScopeEntry = null
@@ -318,11 +246,15 @@ trait Scopes {
       e
     }
 
-    /** lookup next entry with same name as this one */
-    def lookupNextEntry(entry: ScopeEntry): ScopeEntry = {
+    /** lookup next entry with same name as this one 
+     *  @note from Martin: I believe this is a hotspot or will be one
+     *  in future versions of the type system. I have reverted the previous
+     *  change to use iterators as too costly.
+     */
+    def lookupNextEntry(entry: ScopeEntry): ScopeEntry = {      
       var e = entry
-      if (hashtable ne null) //debug
-      do { e = e.tail } while ((e ne null) && e.sym.name != entry.sym.name)
+      if (hashtable ne null)
+        do { e = e.tail } while ((e ne null) && e.sym.name != entry.sym.name)
       else
         do { e = e.next } while ((e ne null) && e.sym.name != entry.sym.name);
       e
@@ -330,7 +262,7 @@ trait Scopes {
 
     /** Return all symbols as a list in the order they were entered in this scope.
      */
-    def toList: List[Symbol] = {
+    override def toList: List[Symbol] = {
       if (elemsCache eq null) {
         elemsCache = Nil
         var e = elems
@@ -342,46 +274,63 @@ trait Scopes {
       elemsCache
     }
 
-    /** Return all symbols as an interator in the order they were entered in this scope.
+    /** Return the nesting level of this scope, i.e. the number of times this scope
+     *  was nested in another */
+    def nestingLevel = nestinglevel
+
+    /** Return all symbols as an iterator in the order they were entered in this scope.
+     */
+    def iterator: Iterator[Symbol] = toList.iterator
+    
+/*
+    /** Does this scope contain an entry for `sym`?
      */
-    def elements: Iterator[Symbol] = toList.elements
+    def contains(sym: Symbol): Boolean = lookupAll(sym.name) contains sym
 
-    def filter(p: Symbol => Boolean): Scope =
-      if (!(toList forall p)) newScope(toList filter p) else this
+    /** A scope that contains all symbols of this scope and that also contains `sym`.
+     */
+    def +(sym: Symbol): Scope =
+      if (contains(sym)) this 
+      else {
+        val result = cloneScope
+        result enter sym
+        result
+      }
 
-    def mkString(start: String, sep: String, end: String) =
+    /** A scope that contains all symbols of this scope except `sym`.
+     */
+    def -(sym: Symbol): Scope =
+      if (!contains(sym)) this 
+      else {
+        val result = cloneScope
+        result unlink sym
+        result
+      }
+*/
+    override def foreach[U](p: Symbol => U): Unit = toList foreach p
+
+    override def filter(p: Symbol => Boolean): Scope =
+      if (!(toList forall p)) new Scope(toList filter p) else this
+
+    override def mkString(start: String, sep: String, end: String) =
       toList.map(_.defString).mkString(start, sep, end)
 
-    override def toString(): String = mkString("{\n  ", ";\n  ", "\n}")
+    override def toString(): String = mkString("Scope{\n  ", ";\n  ", "\n}")
 
-    /** Return the nesting level of this scope, i.e. the number of times this scope
-     *  was nested in another */
-    def nestingLevel = nestinglevel
-    
-    def invalidate(name : Name) = {}
   }
 
+  def newScope: Scope = new Scope
+
   /** The empty scope (immutable).
    */
   object EmptyScope extends Scope {
     override def enter(e: ScopeEntry) {
-      throw new Error("EmptyScope.enter")
+      abort("EmptyScope.enter")
     }
   }
 
   /** The error scope.
    */
-  class ErrorScope(owner: Symbol) extends Scope(null: ScopeEntry) {
-    override def lookupEntry(name: Name): ScopeEntry = {
-      val e = super.lookupEntry(name)
-      if (e != NoSymbol) e
-      else {
-        enter(if (name.isTermName) owner.newErrorValue(name)
-              else owner.newErrorClass(name))
-        super.lookupEntry(name)
-      }
-    }
-  }
-  
+  class ErrorScope(owner: Symbol) extends Scope(null: ScopeEntry)
 }
 
diff --git a/src/compiler/scala/tools/nsc/symtab/StdNames.scala b/src/compiler/scala/tools/nsc/symtab/StdNames.scala
index f5a7061..aef4ae7 100644
--- a/src/compiler/scala/tools/nsc/symtab/StdNames.scala
+++ b/src/compiler/scala/tools/nsc/symtab/StdNames.scala
@@ -1,17 +1,17 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: StdNames.scala 16881 2009-01-09 16:28:11Z cunei $
 
-package scala.tools.nsc.symtab
+package scala.tools.nsc
+package symtab
 
-import scala.tools.nsc.util.NameTransformer
+import scala.reflect.NameTransformer
+import util.Chars.isOperatorPart
 
-trait StdNames {
-  self: SymbolTable =>
+trait StdNames extends reflect.generic.StdNames { self: SymbolTable =>
 
-  object nme {
+  object nme extends StandardNames {
 
     // Scala keywords; enter them first to minimize scanner.maxKey
     val ABSTRACTkw = newTermName("abstract")
@@ -37,6 +37,7 @@ trait StdNames {
     val NULLkw = newTermName("null")
     val OBJECTkw = newTermName("object")
     val OUTER = newTermName("$outer")
+    val OUTER_LOCAL = newTermName("$outer ")
     val OVERRIDEkw = newTermName("override")
     val PACKAGEkw = newTermName("package")
     val PRIVATEkw = newTermName("private")
@@ -49,6 +50,7 @@ trait StdNames {
     val THROWkw = newTermName("throw")
     val TRAITkw = newTermName("trait")
     val TRUEkw = newTermName("true")
+    val TYPE_ = newTermName("TYPE")
     val TRYkw = newTermName("try")
     val TYPEkw = newTermName("type")
     val VALkw = newTermName("val")
@@ -70,7 +72,6 @@ trait StdNames {
 
     val LOCALDUMMY_PREFIX_STRING = "<local "
     val SUPER_PREFIX_STRING = "super$"
-    val EXPAND_SEPARATOR_STRING = "$$"
     val TRAIT_SETTER_SEPARATOR_STRING = "$_setter_$"
     val TUPLE_FIELD_PREFIX_STRING = "_"
     val CHECK_IF_REFUTABLE_STRING = "check$ifrefutable$"
@@ -80,19 +81,20 @@ trait StdNames {
     val INTERPRETER_VAR_PREFIX = "res"
     val INTERPRETER_IMPORT_WRAPPER = "$iw"
     val INTERPRETER_SYNTHVAR_PREFIX = "synthvar$"
+    val EVIDENCE_PARAM_PREFIX = "evidence$"
 
     def LOCAL(clazz: Symbol) = newTermName(LOCALDUMMY_PREFIX_STRING + clazz.name+">")
     def TUPLE_FIELD(index: Int) = newTermName(TUPLE_FIELD_PREFIX_STRING + index)
 
-    val LOCAL_SUFFIX = newTermName(" ")
+    val LOCAL_SUFFIX = newTermName(LOCAL_SUFFIX_STRING)
     val SETTER_SUFFIX = encode("_=")
     val IMPL_CLASS_SUFFIX = newTermName("$class")
     val MODULE_SUFFIX = newTermName("$module")
     val LOCALDUMMY_PREFIX = newTermName(LOCALDUMMY_PREFIX_STRING)
-    val THIS_SUFFIX = newTermName(".this")
     val SELECTOR_DUMMY = newTermName("<unapply-selector>")
-    
+
     val MODULE_INSTANCE_FIELD = newTermName("MODULE$")
+    val SPECIALIZED_INSTANCE  = newTermName("specInstance$")
 
     def isLocalName(name: Name) = name.endsWith(LOCAL_SUFFIX)
     def isSetterName(name: Name) = name.endsWith(SETTER_SUFFIX)
@@ -100,22 +102,16 @@ trait StdNames {
     def isTraitSetterName(name: Name) = isSetterName(name) && name.pos(TRAIT_SETTER_SEPARATOR_STRING) < name.length
     def isOpAssignmentName(name: Name) = 
       name(name.length - 1) == '=' &&
-      isOperatorCharacter(name(0)) &&
+      isOperatorPart(name(0)) &&
       name(0) != '=' && name != NEraw && name != LEraw && name != GEraw
-      
-    def isOperatorCharacter(c: Char) = c match {
-      case '~' | '!' | '@' | '#' | '%' | 
-           '^' | '*' | '+' | '-' | '<' |
-           '>' | '?' | ':' | '=' | '&' | 
-           '|' | '\\'| '/' => true
-      case _ =>
-        val chtp = Character.getType(c)
-        chtp == Character.MATH_SYMBOL || chtp == Character.OTHER_SYMBOL
-      }
+
+    /** The expanded setter name of `name' relative to this class `base` 
+     */
+    def expandedSetterName(name: Name, base: Symbol): Name =
+      expandedName(name, base, separator = TRAIT_SETTER_SEPARATOR_STRING)
 
     /** If `name' is an expandedName name, the original name. 
      *  Otherwise `name' itself.
-     *  @see Symbol.expandedName
      */
     def originalName(name: Name): Name = {
       var i = name.length
@@ -126,6 +122,26 @@ trait StdNames {
       } else name
     }
 
+    /** Return the original name and the types on which this name
+     *  is specialized. For example,
+     *  {{{
+     *     splitSpecializedName("foo$mIcD$sp") == ('foo', "I", "D")
+     *  }}}
+     *  `foo$mIcD$sp` is the name of a method specialized on two type
+     *  parameters, the first one belonging to the method itself, on Int,
+     *  and another one belonging to the enclosing class, on Double.
+     */
+    def splitSpecializedName(name: Name): (Name, String, String) =
+      if (name.endsWith("$sp")) {
+        val name1 = name.subName(0, name.length - 3)
+        val idxC = name1.lastPos('c')
+        val idxM = name1.lastPos('m', idxC)
+        (name1.subName(0, idxM - 1).toString,
+         name1.subName(idxC + 1, name1.length).toString,
+         name1.subName(idxM + 1, idxC).toString)
+      } else
+        (name, "", "")
+
     def localToGetter(name: Name): Name = {
       assert(isLocalName(name))//debug
       name.subName(0, name.length - LOCAL_SUFFIX.length)
@@ -169,7 +185,7 @@ trait StdNames {
       
     /** The name of an accessor for protected symbols. */
     def protName(name: Name): Name = newTermName(PROTECTED_PREFIX + name)
-      
+
     /** The name of a setter for protected symbols. Used for inherited Java fields. */
     def protSetterName(name: Name): Name = newTermName(PROTECTED_PREFIX + "set" + name)
     
@@ -177,31 +193,16 @@ trait StdNames {
     def bitmapName(n: Int): Name = newTermName("bitmap$" + n)
 
     val ERROR = newTermName("<error>")
-    val ERRORtype = newTypeName("<error>")
     val LOCALCHILD = newTypeName("<local child>")
 
     val NOSYMBOL = newTermName("<none>")
-    val EMPTY = newTermName("")
     val ANYNAME = newTermName("<anyname>")
     val WILDCARD = newTermName("_")
     val WILDCARD_STAR = newTermName("_*")
-    val COMPOUND_NAME = newTermName("<ct>")
-
-    val ANON_CLASS_NAME = newTermName("$anon")
-    val ANON_CLASS_NAME_tn = ANON_CLASS_NAME.toTypeName
-    val ANON_FUN_NAME = newTermName("$anonfun")
-    val ANON_FUN_NAME_tn = ANON_FUN_NAME.toTypeName
-    val REFINE_CLASS_NAME = newTermName("<refinement>")
-    val REFINE_CLASS_NAME_tn = REFINE_CLASS_NAME.toTypeName
-    val EMPTY_PACKAGE_NAME = newTermName("<empty>")
-    val EMPTY_PACKAGE_NAME_tn = EMPTY_PACKAGE_NAME.toTypeName
-    val IMPORT = newTermName("<import>")
-    val ZERO = newTermName("<zero>")
+
     val STAR = newTermName("*")
-    val ROOT = newTermName("<root>")
-    val ROOT_tn = ROOT.toTypeName
-    val ROOTPKG = newTermName("_root_")
     val REPEATED_PARAM_CLASS_NAME = newTermName("<repeated>")
+    val JAVA_REPEATED_PARAM_CLASS_NAME = newTermName("<repeated...>")
     val BYNAME_PARAM_CLASS_NAME = newTermName("<byname>")
     val EQUALS_PATTERN_NAME = newTermName("<equals>")
     val SELF = newTermName("$this")
@@ -224,6 +225,7 @@ trait StdNames {
     val PERCENT = encode("%")
     val EQL = encode("=")
     val USCOREEQL = encode("_=")
+    val HASHHASH = encode("##")
 
     val Nothing = newTermName("Nothing")
     val Null = newTermName("Null")
@@ -231,19 +233,18 @@ trait StdNames {
     val AnyVal = newTermName("AnyVal")
     val AnyRef = newTermName("AnyRef")
     val Array = newTermName("Array")
+    val Boolean = newTermName("Boolean")
     val Byte = newTermName("Byte")
     val Catch = newTermName("Catch")
     val Char = newTermName("Char")
-    val Boolean = newTermName("Boolean")
     val Do = newTermName("Do")
     val Double = newTermName("Double")
-    val Element = newTermName("Element")
     val Finally = newTermName("Finally")
     val Float = newTermName("Float")
     val Function = newTermName("Function")
     val Function1 = newTermName("Function1")
     val Int = newTermName("Int")
-    val Labelled = newTermName("Labelled")
+    val List = newTermName("List")
     val Long = newTermName("Long")
     val Nil = newTermName("Nil")
     val Object = newTermName("Object")
@@ -257,53 +258,43 @@ trait StdNames {
     val Short = newTermName("Short")
     val Singleton = newTermName("Singleton")
     val Some = newTermName("Some")
-    val SourceFile = newTermName("SourceFile")
     val String = newTermName("String")
     val Symbol = newTermName("Symbol")
-    val Synthetic = newTermName("Synthetic")
     val System = newTermName("System")
-    val Text = newTermName("Text")
     val Throwable = newTermName("Throwable")
     val Try = newTermName("Try")
     val Tuple = newTermName("Tuple")
-    val Type = newTermName("Type")
     val Tuple2 = newTermName("Tuple2")
     val Unit = newTermName("Unit")
-    val While = newTermName("While")
 
     val apply = newTermName("apply")
-    val array = newTermName("array")
     val arrayValue = newTermName("arrayValue")
     val arraycopy = newTermName("arraycopy")
     val assert_ = newTermName("assert")
     val assume_ = newTermName("assume")
     val asInstanceOf_ = newTermName("asInstanceOf")
-    val asInstanceOfErased = newTermName("asInstanceOf$erased")
-    val bind = newTermName("bind")
-    val booleanValue = newTermName("booleanValue")
     val box = newTermName("box")
-    val boxArray = newTermName("boxArray")
-    val forceBoxedArray = newTermName("forceBoxedArray")
+    val bytes = newTermName("bytes")
+    val canEqual_ = newTermName("canEqual")
     val checkInitialized = newTermName("checkInitialized")
     val classOf = newTermName("classOf")
-    val coerce = newTermName("coerce")
-    val defaultValue = newTermName("defaultValue")
-    val detach = newTermName("detach")
+    val identity = newTermName("identity")
+    val conforms = newTermName("conforms")
+    val copy = newTermName("copy")
     val dottype = newTermName(".type")
     val drop = newTermName("drop")
-    val dummy = newTermName("$dummy")
     val elem = newTermName("elem")
-    val elements = newTermName("elements")
     val eq = newTermName("eq")
     val equals_ = newTermName("equals")
     val _equals = newTermName("_equals")
-    val _equalsWithVarArgs = newTermName("_equalsWithVarArgs")
+    val inlinedEquals = newTermName("inlinedEquals")
     val error = newTermName("error")
     val ex = newTermName("ex")
-    val fail = newTermName("fail")
+    val add_ = newTermName("add")
     val false_ = newTermName("false")
     val filter = newTermName("filter")
     val finalize_ = newTermName("finalize")
+    val find_ = newTermName("find")
     val flatMap = newTermName("flatMap")
     val forName = newTermName(if (forMSIL) "GetType" else "forName")
     val foreach = newTermName("foreach")
@@ -311,15 +302,13 @@ trait StdNames {
     val getCause = newTermName("getCause")
     val getClass_ = newTermName("getClass")
     val getMethod_ = newTermName("getMethod")
-    val hasAsInstance = newTermName("hasAsInstance")
+    val hash_ = newTermName("hash")
     val hashCode_ = newTermName("hashCode")
     val hasNext = newTermName("hasNext")
     val head = newTermName("head")
-    val identity = newTermName("identity")
-    val intern = newTermName("intern")
     val invoke_ = newTermName("invoke")
+    val isArray = newTermName("isArray")
     val isInstanceOf_ = newTermName("isInstanceOf")
-    val isInstanceOfErased = newTermName("isInstanceOf$erased")
     val isDefinedAt = newTermName("isDefinedAt")
     val isEmpty = newTermName("isEmpty")
     val java = newTermName("java")
@@ -327,51 +316,44 @@ trait StdNames {
     val length = newTermName("length")
     val lengthCompare = newTermName("lengthCompare")
     val lift_ = newTermName("lift")
+    val main = newTermName("main")
     val map = newTermName("map")
     val Mutable = newTypeName("Mutable")
-    val n = newTermName("n")
     val ne = newTermName("ne")
-    val nobinding = newTermName("nobinding")
-    val next = newTermName("next")
     val newArray = newTermName("newArray")
+    val next = newTermName("next")
     val notify_ = newTermName("notify")
     val notifyAll_ = newTermName("notifyAll")
     val null_ = newTermName("null")
-    val predef = newTermName("predef")
+    val ofDim = newTermName("ofDim")
     val print = newTermName("print")
     val productArity = newTermName("productArity")
     val productElement = newTermName("productElement")
+    // val productElementName = newTermName("productElementName")
     val productPrefix = newTermName("productPrefix")
     val readResolve = newTermName("readResolve")
-    val receive = newTermName("receive")
-    val report = newTermName("report")
-    val runtime = newTermName("runtime")
     val sameElements = newTermName("sameElements")
     val scala_ = newTermName("scala")
-    val scala_tn = scala_.toTypeName
     val self = newTermName("self")
+    val setAccessible = newTermName("setAccessible")
     val synchronized_ = newTermName("synchronized")
-    val tag = newTermName("$tag")
     val tail = newTermName("tail")
+    val toArray = newTermName("toArray")
     val toList = newTermName("toList")
     val toSeq = newTermName("toSeq")
     val toString_ = newTermName("toString")
     val clone_ = newTermName("clone")
-    val that = newTermName("that")
-    val that1 = newTermName("that1")
     val this_ = newTermName("this")
     val throw_ = newTermName("throw")
     val true_ = newTermName("true")
     val unapply = newTermName("unapply")
     val unapplySeq = newTermName("unapplySeq")
-    val unbind = newTermName("unbind")
     val unbox = newTermName("unbox")
-    val unreferenced = newTermName("unreferenced")
     val update = newTermName("update")
     val value = newTermName("value")
     val view_ = newTermName("view")
     val wait_ = newTermName("wait")
-    val xml = newTermName("xml")
+    val withFilter = newTermName("withFilter")
     val zip = newTermName("zip")
 
     val ZAND = encode("&&")
@@ -405,6 +387,7 @@ trait StdNames {
     val NEraw = newTermName("!=")
     val LEraw = newTermName("<=")
     val GEraw = newTermName(">=")
+    val DOLLARraw = newTermName("$")  
 
     // value-conversion methods
     val toByte = newTermName("toByte")
@@ -428,10 +411,12 @@ trait StdNames {
     val JacoMetaATTR = newTermName("JacoMeta")
     val SignatureATTR = newTermName("Signature")
     val ScalaSignatureATTR = newTermName("ScalaSig")
-    val JavaInterfaceATTR = newTermName("JacoInterface")
     val AnnotationDefaultATTR = newTermName("AnnotationDefault")
+    // Stores Java annotations with RetentionPolicy.RUNTIME
     val RuntimeAnnotationATTR = newTermName("RuntimeVisibleAnnotations")
+    // Stores Java annotations with RetentionPolicy.CLASS. Currently not used (Apr 2009).
     val ClassfileAnnotationATTR = newTermName("RuntimeInvisibleAnnotations")
+    // Stores Java annotations on parameters with RetentionPolicy.RUNTIME
     val RuntimeParamAnnotationATTR = newTermName("RuntimeVisibleParameterAnnotations")
     val ScalaATTR = newTermName("Scala")
   }
@@ -445,16 +430,18 @@ trait StdNames {
     val String       : Name
     val Throwable    : Name
     val NPException  : Name // NullPointerException
-    val NLRException : Name = newTermName("scala.runtime.NonLocalReturnException")
+    val NLRControl   : Name = newTermName("scala.runtime.NonLocalReturnControl")
     val ValueType    : Name
     val Serializable : Name
     val BeanProperty : Name
+    val BooleanBeanProperty: Name
     val Delegate     : Name
     val IOOBException: Name // IndexOutOfBoundsException
     val Code         : Name
     val BoxedNumber  : Name
     val BoxedCharacter : Name
     val BoxedBoolean : Name
+    val MethodAsObject : Name
 
     import scala.collection.mutable.HashMap
     val Boxed = new HashMap[Name, Name]
@@ -472,16 +459,24 @@ trait StdNames {
     final val IOOBException = newTermName("java.lang.IndexOutOfBoundsException")
     final val BoxedNumber   = newTermName("java.lang.Number")
     final val BoxedCharacter = newTermName("java.lang.Character")
-    final val BoxedBoolean = newTermName("java.lang.Boolean")
-
-    Boxed += (nme.Boolean -> newTermName("java.lang.Boolean"))
-    Boxed += (nme.Byte    -> newTermName("java.lang.Byte"))
-    Boxed += (nme.Char    -> newTermName("java.lang.Character"))
-    Boxed += (nme.Short   -> newTermName("java.lang.Short"))
-    Boxed += (nme.Int     -> newTermName("java.lang.Integer"))
-    Boxed += (nme.Long    -> newTermName("java.lang.Long"))
-    Boxed += (nme.Float   -> newTermName("java.lang.Float"))
-    Boxed += (nme.Double  -> newTermName("java.lang.Double"))
+    final val BoxedBoolean  = newTermName("java.lang.Boolean")
+    final val BoxedByte     = newTermName("java.lang.Byte")
+    final val BoxedShort    = newTermName("java.lang.Short")
+    final val BoxedInteger  = newTermName("java.lang.Integer")
+    final val BoxedLong     = newTermName("java.lang.Long")
+    final val BoxedFloat    = newTermName("java.lang.Float")
+    final val BoxedDouble   = newTermName("java.lang.Double")    
+    
+    final val MethodAsObject = newTermName("java.lang.reflect.Method")
+
+    Boxed += (nme.Boolean -> BoxedBoolean)
+    Boxed += (nme.Byte    -> BoxedByte)
+    Boxed += (nme.Char    -> BoxedCharacter)
+    Boxed += (nme.Short   -> BoxedShort)
+    Boxed += (nme.Int     -> BoxedInteger)
+    Boxed += (nme.Long    -> BoxedLong)
+    Boxed += (nme.Float   -> BoxedFloat)
+    Boxed += (nme.Double  -> BoxedDouble)
   }
 
   private class MSILNames extends SymbolNames {
@@ -494,12 +489,14 @@ trait StdNames {
     final val ValueType     = newTermName("System.ValueType")
     final val Serializable  = nme.NOSYMBOL
     final val BeanProperty  = nme.NOSYMBOL
+    final val BooleanBeanProperty = nme.NOSYMBOL
     final val Delegate      = newTermName("System.MulticastDelegate")
     final val IOOBException = newTermName("System.IndexOutOfRangeException")
     final val Code          = nme.NOSYMBOL
     final val BoxedNumber   = newTermName("System.IConvertible")
     final val BoxedCharacter = newTermName("System.IConvertible")
     final val BoxedBoolean = newTermName("System.IConvertible")
+    final val MethodAsObject = nme.NOSYMBOL // TODO: is there something like Method in MSIL?
 
     Boxed += (nme.Boolean -> newTermName("System.Boolean"))
     Boxed += (nme.Byte    -> newTermName("System.Byte"))
@@ -514,20 +511,11 @@ trait StdNames {
   private class J2SENames extends JavaNames {
     final val Serializable  = newTermName("java.io.Serializable")
     final val BeanProperty  = newTermName("scala.reflect.BeanProperty")
+    final val BooleanBeanProperty  = newTermName("scala.reflect.BooleanBeanProperty")
     final val Code          = newTermName("scala.reflect.Code")
   }
-
-  private class CLDCNames extends JavaNames {
-    final val Serializable  = nme.NOSYMBOL
-    final val BeanProperty  = nme.NOSYMBOL
-    final val Code          = nme.NOSYMBOL
-  }
-
-  private var sn0 : SymbolNames = _
-  def sn: SymbolNames = {
-    if (sn0 == null) sn0 = if (forMSIL) new MSILNames
-    else if (forCLDC) new CLDCNames
+  
+  lazy val sn: SymbolNames = 
+    if (forMSIL) new MSILNames
     else new J2SENames
-    sn0
-  }
 }
diff --git a/src/compiler/scala/tools/nsc/symtab/SymbolLoaders.scala b/src/compiler/scala/tools/nsc/symtab/SymbolLoaders.scala
index 2888b70..b04a881 100644
--- a/src/compiler/scala/tools/nsc/symtab/SymbolLoaders.scala
+++ b/src/compiler/scala/tools/nsc/symtab/SymbolLoaders.scala
@@ -1,22 +1,24 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: SymbolLoaders.scala 16881 2009-01-09 16:28:11Z cunei $
 
-package scala.tools.nsc.symtab
+package scala.tools.nsc
+package symtab
  
 import java.io.{File, IOException} 
  
 import ch.epfl.lamp.compiler.msil.{Type => MSILType, Attribute => MSILAttribute}
 
-import scala.collection.mutable.{HashMap, HashSet}
+import scala.collection.mutable.{HashMap, HashSet, ListBuffer}
 import scala.compat.Platform.currentTime
 import scala.tools.nsc.io.AbstractFile
-import scala.tools.nsc.util.{Position, NoPosition}
+import scala.tools.nsc.util.{ ClassPath, JavaClassPath }
 import classfile.ClassfileParser
 import Flags._
 
+import util.Statistics._
+
 /** This class ...
  *
  *  @author  Martin Odersky
@@ -26,61 +28,42 @@ abstract class SymbolLoaders {
   val global: Global
   import global._
 
-  /** A lazy type that completes itself by calling parameter doComplete.
-   *  Any linked modules/classes or module classes are also initialized.
-   *
-   *  @param doComplete    The type completion procedure to be run.
-   *                       It takes symbol to compkete as parameter and returns
-   *                       name of file loaded for completion as a result.
-   *                       Can throw an IOException on error.
+  /**
+   * A lazy type that completes itself by calling parameter doComplete.
+   * Any linked modules/classes or module classes are also initialized.
    */
   abstract class SymbolLoader extends LazyType {
 
     /** Load source or class file for `root', return */
     protected def doComplete(root: Symbol): Unit
+    
+    protected def sourcefile: Option[AbstractFile] = None
 
-    /** The kind of file that's processed by this loader */
-    protected def kindString: String
+    /**
+     * Description of the resource (ClassPath, AbstractFile, MSILType)
+     * being processed by this loader
+     */
+    protected def description: String
 
     private var ok = false
 
-    def sourceFile: AbstractFile = null
-    protected def sourceString: String
-
+    private def setSource(sym: Symbol) {
+      sourcefile map (sf => sym match {
+        case cls: ClassSymbol => cls.sourceFile = sf
+        case mod: ModuleSymbol => mod.moduleClass.sourceFile = sf
+        case _ => ()
+      })
+    }
     override def complete(root: Symbol) : Unit = {
-      if (inIDE && root.owner != NoSymbol) {
-        assert(root.rawInfo == this)
-        if (root.isModuleClass) {
-          val clazz = root.sourceModule.linkedClassOfModule
-          assert(root.rawInfo == this)
-          if (clazz != NoSymbol && !clazz.rawInfo.isInstanceOf[SymbolLoader]) {
-            // bail
-            root.setInfo(ErrorType)
-            Console.println("ditch " + root)
-            return
-          }
-        } else if (root.isClass) {
-          val module = root.linkedModuleOfClass
-          assert(root.rawInfo == this)
-          if (module != NoSymbol && !module.rawInfo.isInstanceOf[SymbolLoader]) {
-            root.setInfo(ErrorType)
-            Console.println("ditch " + root)
-            return
-          }
-        } else {
-          assert(root.isModule)
-        }
-      }
       try {
         val start = currentTime
         val currentphase = phase
         doComplete(root)
         phase = currentphase
-        def source = kindString + " " + sourceString
-        informTime("loaded " + source, start)
-        //if (root.rawInfo == this && root.linkedSym.rawInfo == this)
-        //  throw new TypeError(source + " does not define " + root)
+        informTime("loaded " + description, start)
         ok = true
+        setSource(root)
+        setSource(root.companionSymbol) // module -> class, class -> module
       } catch {
         case ex: IOException =>
           ok = false
@@ -91,7 +74,7 @@ abstract class SymbolLoaders {
             else "error while loading " + root.name + ", " + msg);
       }
       initRoot(root)
-      if (!root.isPackageClass) initRoot(root.linkedSym)
+      if (!root.isPackageClass) initRoot(root.companionSymbol)
     }
 
     override def load(root: Symbol) { complete(root) }
@@ -106,216 +89,185 @@ abstract class SymbolLoaders {
     }
   }
 
-  /** Load contents of a package
+  /**
+   * Load contents of a package
    */
-  class PackageLoader(val directory: global.classPath0.Context) extends SymbolLoader {
-
-    // XXX: for IDE.
-    protected def sourceString = directory.toString()
-
-    protected def kindString: String = "directory path"
-
-    protected def newPackageLoader(dir: global.classPath0.Context): PackageLoader =
-      new PackageLoader(dir)
-
-    protected def checkSource(name: String, source: AbstractFile): Boolean = true
-
-    var root: Symbol = _
-
-    def enterPackage(name: String, completer: SymbolLoader) {
-      if (inIDE && root.info.decls.lookup(newTermName(name)) != NoSymbol) {
-        return // refresh
-      }
+  abstract class PackageLoader[T](classpath: ClassPath[T]) extends SymbolLoader {
+    protected def description = "package loader "+ classpath.name
+
+    def enterPackage(root: Symbol, name: String, completer: SymbolLoader) {
+      val preExisting = root.info.decls.lookup(newTermName(name))
+      if (preExisting != NoSymbol)
+        throw new TypeError(
+          root+" contains object and package with same name: "+name+"\none of them needs to be removed from classpath")
       val pkg = root.newPackage(NoPosition, newTermName(name))
       pkg.moduleClass.setInfo(completer)
       pkg.setInfo(pkg.moduleClass.tpe)
       root.info.decls.enter(pkg)
     }
-    // @return - the symbol of the class
-    def enterClassAndModule(name: String, completer: SymbolLoader): Symbol = {
+
+    def enterClassAndModule(root: Symbol, name: String, completer: SymbolLoader) {
       val owner = if (root.isRoot) definitions.EmptyPackageClass else root
       val className = newTermName(name)
-      assert(owner.info.decls.lookup(name) == NoSymbol, owner.fullNameString + "." + name)
-      var clazz = owner.newClass(NoPosition, name.toTypeName)
-      var module = owner.newModule(NoPosition, name)
+      assert(owner.info.decls.lookup(name) == NoSymbol, owner.fullName + "." + name)
+      val clazz = owner.newClass(NoPosition, name.toTypeName)
+      val module = owner.newModule(NoPosition, name)
       clazz setInfo completer
       module setInfo completer
       module.moduleClass setInfo moduleClassLoader
-      clazz = (owner.info.decls enter clazz).asInstanceOf[ClassSymbol]
-      module = (owner.info.decls enter module).asInstanceOf[ModuleSymbol]
-      assert(clazz.linkedModuleOfClass == module, module)
-      assert(module.linkedClassOfModule == clazz, clazz)
-      clazz
-    }
-    def checkAdd(name0 : String) = {
-      var name = name0
-      while ((name indexOf '$') != -1) {
-        name = name.substring(0, name indexOf '$')
-      }
+      owner.info.decls enter clazz
+      owner.info.decls enter module
+      assert(clazz.companionModule == module, module)
+      assert(module.companionClass == clazz, clazz)
     }
-    lazy val scope = newPackageScope(computeDepends(this))
+
+    /**
+     * Tells whether a class with both a binary and a source representation
+     * (found in classpath and in sourcepath) should be re-compiled. Behaves
+     * similar to javac, i.e. if the source file is newer than the classfile,
+     * a re-compile is triggered.
+     */
+    protected def needCompile(bin: T, src: AbstractFile): Boolean
+
+    /**
+     * Tells whether a class should be loaded and entered into the package
+     * scope. On .NET, this method returns `false' for all synthetic classes
+     * (anonymous classes, implementation classes, module classes), their
+     * symtab is encoded in the pickle of another class.
+     */
+    protected def doLoad(cls: classpath.AnyClassRep): Boolean
+
+    protected def newClassLoader(bin: T): SymbolLoader
+
+    protected def newPackageLoader(pkg: ClassPath[T]): SymbolLoader
+
     protected def doComplete(root: Symbol) {
       assert(root.isPackageClass, root)
-      this.root = root
-      root.setInfo(new PackageClassInfoType(scope, root, this))
-      refresh
-    }
-    def refresh = {
-      /** Is the given name a valid input file base name? */
-      def isValid(name: String): Boolean =
-        name.length() > 0 && !name.endsWith("$class") && (/*settings.XO.value*/true ||
-          (name.indexOf("$anon") == -1));
-
-      val classes  = new HashMap[String, global.classPath0.Context]
-      val packages = new HashMap[String, global.classPath0.Context]
-      for (dir <- directory.entries) if ((dir.location ne null) && (!inIDE || dir.location.isDirectory)) {
-        for (file <- dir.location) {
-          if (file.isDirectory && directory.validPackage(file.name) && !packages.isDefinedAt(file.name))
-            packages(file.name) = directory.find(file.name, true);
-          else if (!global.forMSIL && !file.isDirectory && file.name.endsWith(".class")) {
-            val name = file.name.substring(0, file.name.length() - (".class").length());
-            if (isValid(name) && !classes.isDefinedAt(name)) {
-              val clazz = directory.find(name, false)
-              if (clazz ne null) classes(name) = clazz
-            }
-          }
+      root.setInfo(new PackageClassInfoType(new Scope(), root))
+
+      val sourcepaths = classpath.sourcepaths
+      for (classRep <- classpath.classes if doLoad(classRep)) {
+        if (classRep.binary.isDefined && classRep.source.isDefined) {
+          val (bin, src) = (classRep.binary.get, classRep.source.get)
+          val loader = if (needCompile(bin, src)) new SourcefileLoader(src)
+                       else newClassLoader(bin)
+          enterClassAndModule(root, classRep.name, loader)
+        } else if (classRep.binary.isDefined) {
+          enterClassAndModule(root, classRep.name, newClassLoader(classRep.binary.get))
+        } else if (classRep.source.isDefined) {
+          enterClassAndModule(root, classRep.name, new SourcefileLoader(classRep.source.get))
         }
       }
-      for (dir <- directory.entries) if (dir.source ne null) {
-        for (file <- dir.source.location) {
-          if (file.isDirectory && directory.validPackage(file.name) && !packages.isDefinedAt(file.name))
-            packages(file.name) = directory.find(file.name, true)
-          else if (dir.source.compile && !file.isDirectory && file.name.endsWith(".scala")) {
-            val name = file.name.substring(0, file.name.length() - (".scala").length())
-            if (isValid(name) && !classes.isDefinedAt(name)) {
-              val source = directory.find(name, false)
-              if ((source ne null) && (source.sourceFile ne null))
-                if (checkSource(name, source.sourceFile))
-                  classes(name) = source
-                else if (settings.debug.value)
-                  Console.println("Skipping source file " + source.sourceFile)
-            }
-          }
-        }
+
+      for (pkg <- classpath.packages) {
+        enterPackage(root, pkg.name, newPackageLoader(pkg))
       }
 
-      // do classes first
-      for ((name, file) <- classes.elements) {
-        val loader = if (!file.isSourceFile) {
-          new ClassfileLoader(file.classFile, file.sourceFile, file.sourcePath)
-        } else {
-          assert(file.sourceFile ne null)
-          new SourcefileLoader(file.sourceFile)
-        }
-        enterClassAndModule(name, loader)
+      // if there's a $member object, enter its members as well.
+      val pkgModule = root.info.decl(nme.PACKAGEkw)
+      if (pkgModule.isModule && !pkgModule.rawInfo.isInstanceOf[SourcefileLoader]) {
+        //println("open "+pkgModule)//DEBUG
+        openPackageModule(pkgModule)()
       }
-      for ((name, file) <- packages.elements)
-        enterPackage(name, newPackageLoader(file))
     }
   }
 
-  class NamespaceLoader(directory: global.classPath0.Context) extends PackageLoader(directory) {
-
-    override protected def kindString: String = "namespace " + namespace
-
-    override protected def sourceString = ""
-
-    override def newPackageLoader(dir: global.classPath0.Context): PackageLoader =
-      new NamespaceLoader(dir)
-
-    val types = new HashMap[String, MSILType]()
-
-    val namespaces = new HashSet[String]()
-
-    def namespace: String = if (root.isRoot) "" else root.fullNameString
+  def openPackageModule(module: Symbol)(packageClass: Symbol = module.owner): Unit = {
+    // unlink existing symbols in the package
+    for (member <- module.info.decls.iterator) {
+      if (!member.hasFlag(PRIVATE) && !member.isConstructor) {
+        // todo: handle overlapping definitions in some way: mark as errors
+        // or treat as abstractions. For now the symbol in the package module takes precedence.
+        for (existing <- packageClass.info.decl(member.name).alternatives)
+          packageClass.info.decls.unlink(existing)
+      }
+    }
+    // enter non-private decls the class
+    for (member <- module.info.decls.iterator) {
+      if (!member.hasFlag(PRIVATE) && !member.isConstructor) {
+        packageClass.info.decls.enter(member)
+      }
+    }
+    // enter decls of parent classes
+    for (pt <- module.info.parents; val p = pt.typeSymbol) {
+      if (p != definitions.ObjectClass && p != definitions.ScalaObjectClass) {
+        openPackageModule(p)(packageClass)
+      }
+    }
+  }
 
-    // TODO: Add check whether the source is newer than the assembly
-    override protected def checkSource(name: String, source: AbstractFile): Boolean =
-      !types.contains(name)
+  class JavaPackageLoader(classpath: ClassPath[AbstractFile]) extends PackageLoader(classpath) {    
+    protected def needCompile(bin: AbstractFile, src: AbstractFile) =
+      (src.lastModified >= bin.lastModified)
 
-    override protected def doComplete(root: Symbol) {
-      clrTypes.collectMembers(root, types, namespaces)
+    protected def doLoad(cls: classpath.AnyClassRep) = true
 
-      super.doComplete(root)
+    protected def newClassLoader(bin: AbstractFile) =
+      new ClassfileLoader(bin)
 
-      for (namespace <- namespaces.elements) {
-        val oldPkg = root.info.decls lookup newTermName(namespace)
-        if (oldPkg == NoSymbol)
-          enterPackage(namespace, new NamespaceLoader(new classPath0.Context(List())))
-        //else System.out.println("PackageLoader: package already in scope: " + oldPkg.fullNameString)
-      }
+    protected def newPackageLoader(pkg: ClassPath[AbstractFile]) =
+      new JavaPackageLoader(pkg)
+  }
 
-      // import the CLR types contained in the package (namespace)
-      for ((name, typ) <- types.elements) {
-        assert(namespace == typ.Namespace, typ.FullName)
+  class NamespaceLoader(classpath: ClassPath[MSILType]) extends PackageLoader(classpath) {
+    protected def needCompile(bin: MSILType, src: AbstractFile) =
+      false // always use compiled file on .net
 
+    protected def doLoad(cls: classpath.AnyClassRep) = {
+      if (cls.binary.isDefined) {
+        val typ = cls.binary.get
         if (typ.IsDefined(clrTypes.SCALA_SYMTAB_ATTR, false)) {
           val attrs = typ.GetCustomAttributes(clrTypes.SCALA_SYMTAB_ATTR, false)
           assert (attrs.length == 1, attrs.length)
           val a = attrs(0).asInstanceOf[MSILAttribute]
-          if (a.getConstructor() == clrTypes.SYMTAB_CONSTR)
-            enterClassAndModule(name, new MSILTypeLoader(typ))
-        } 
-        else
-          enterClassAndModule(name, new MSILTypeLoader(typ))
-      }
+          // symtab_constr takes a byte array argument (the pickle), i.e. typ has a pickle.
+          // otherwise, symtab_default_constr was used, which marks typ as scala-synthetic.
+          a.getConstructor() == clrTypes.SYMTAB_CONSTR
+        } else true // always load non-scala types
+      } else true // always load source
     }
-  }  // NamespaceLoader
 
-  class MSILTypeLoader(typ: MSILType) extends SymbolLoader {
-    private object typeParser extends clr.TypeParser {
-      val global: SymbolLoaders.this.global.type = SymbolLoaders.this.global
-    } 
-    protected def doComplete(root: Symbol) {
-      typeParser.parse(typ, root.asInstanceOf[typeParser.global.loaders.clrTypes.global.Symbol]) // don't check this  
-    } 
-    protected def kindString: String = typ.FullName
-    protected def sourceString = typ.Assembly.FullName
-  }
-  // IDE hook.
-  protected def completeClassfile(root : Symbol, loader : ClassfileLoader)(f : => Unit) : Unit = f
-  import scala.collection.jcl
-  // incremental builder hook
-  protected def computeDepends(loader : PackageLoader) : PackageScopeDependMap = {
-    null
+    protected def newClassLoader(bin: MSILType) =
+      new MSILTypeLoader(bin)
+
+    protected def newPackageLoader(pkg: ClassPath[MSILType]) =
+      new NamespaceLoader(pkg)
+
   }
 
-  class ClassfileLoader(val classFile: AbstractFile, override val sourceFile: AbstractFile, sourcePath0: AbstractFile) extends SymbolLoader {
+  class ClassfileLoader(val classfile: AbstractFile) extends SymbolLoader {
     private object classfileParser extends ClassfileParser {
       val global: SymbolLoaders.this.global.type = SymbolLoaders.this.global
-      override def sourcePath = sourcePath0 /* could be null */
     }
+    
+    protected def description = "class file "+ classfile.toString
+
     protected def doComplete(root: Symbol) {
-      completeClassfile(root, this) {
-        classfileParser.parse(classFile, root)
-      }
-      root match {
-        case clazz: ClassSymbol => 
-          if ((sourceFile ne null) && (clazz.sourceFile eq null)) 
-            clazz.sourceFile = sourceFile
-        case module: ModuleSymbol if module.moduleClass.isInstanceOf[ClassSymbol] =>
-          val clazz = module.moduleClass.asInstanceOf[ClassSymbol]
-          if ((sourceFile ne null) && (clazz.sourceFile eq null)) 
-            clazz.sourceFile = sourceFile
-        case _ =>   
-      }
-      if (root.sourceFile ne null) 
-        prepareReset(root, this)
+      val start = startTimer(classReadNanos)
+      classfileParser.parse(classfile, root)
+      stopTimer(classReadNanos, start)
     }
-    protected def kindString: String = "class file"
-    protected def sourceString = classFile.toString()
+    override protected def sourcefile = classfileParser.srcfile
+  }
+
+  class MSILTypeLoader(typ: MSILType) extends SymbolLoader {
+    private object typeParser extends clr.TypeParser {
+      val global: SymbolLoaders.this.global.type = SymbolLoaders.this.global
+    }
+
+    protected def description = "MSILType "+ typ.FullName + ", assembly "+ typ.Assembly.FullName
+    protected def doComplete(root: Symbol) { typeParser.parse(typ, root) }
   }
 
-  class SourcefileLoader(override val sourceFile: AbstractFile) extends SymbolLoader {
-    protected def doComplete(root: Symbol): Unit = global.currentRun.compileLate(sourceFile)
-    protected def kindString: String = "source file"
-    protected def sourceString = sourceFile.toString()
+  class SourcefileLoader(val srcfile: AbstractFile) extends SymbolLoader {
+    protected def description = "source file "+ srcfile.toString
+    override protected def sourcefile = Some(srcfile)
+    protected def doComplete(root: Symbol): Unit = global.currentRun.compileLate(srcfile)
   }
 
   object moduleClassLoader extends SymbolLoader {
+    protected def description = "module class loader"
     protected def doComplete(root: Symbol) { root.sourceModule.initialize }
-    protected def kindString: String = ""
-    protected def sourceString = ""
   }
 
   object clrTypes extends clr.CLRTypes {
@@ -323,4 +275,7 @@ abstract class SymbolLoaders {
     if (global.forMSIL) init()
   }
 
+  /** used from classfile parser to avoid cyclies */
+  var parentsLevel = 0
+  var pendingLoadActions: List[() => Unit] = Nil
 }
diff --git a/src/compiler/scala/tools/nsc/symtab/SymbolTable.scala b/src/compiler/scala/tools/nsc/symtab/SymbolTable.scala
index 528f8a9..adeef71 100644
--- a/src/compiler/scala/tools/nsc/symtab/SymbolTable.scala
+++ b/src/compiler/scala/tools/nsc/symtab/SymbolTable.scala
@@ -1,33 +1,37 @@
 /* NSC -- new scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: SymbolTable.scala 16881 2009-01-09 16:28:11Z cunei $
 
-package scala.tools.nsc.symtab
-import nsc.ast.Trees
+package scala.tools.nsc
+package symtab
+
+import ast.{Trees, TreePrinters, DocComments}
 
 import util._
 
-abstract class SymbolTable extends Names
+abstract class SymbolTable extends reflect.generic.Universe
+                              with Names
                               with Symbols
                               with Types
                               with Scopes
                               with Definitions
-                              with Constants
+                              with reflect.generic.Constants
                               with BaseTypeSeqs
                               with InfoTransformers
                               with StdNames
                               with AnnotationInfos
                               with AnnotationCheckers
                               with Trees
+                              with TreePrinters
+                              with Positions
+                              with DocComments
 {
   def settings: Settings
   def rootLoader: LazyType
   def log(msg: AnyRef)
-
-  /** Are we compiling for the J2ME CLDC platform ? */
-  def forCLDC: Boolean
+  def abort(msg: String) = throw new Error(msg)
+  def abort() = throw new Error()
 
   /** Are we compiling for Java SE ? */
   def forJVM: Boolean
@@ -35,8 +39,6 @@ abstract class SymbolTable extends Names
   /** Are we compiling for .NET ? */
   def forMSIL: Boolean
 
-  /** are we in a lampion presentation compiler? cannot get inIDE flag from global */
-  def inIDE : Boolean = false
   protected def trackTypeIDE(sym : Symbol) : Boolean = true
   def compare(sym : Symbol, name : Name) = sym.name == name
   def verifyAndPrioritize[T](g : Symbol => Symbol)(pt : Type)(f : => T) = f
@@ -45,12 +47,6 @@ abstract class SymbolTable extends Names
   }
   def notifyImport(what : Name, container : Type, from : Name, to : Name) : Unit = {}
   def sanitize(tree : Tree) : Tree = tree
-  def attachSource(symbol : ClassSymbol, file : io.AbstractFile) : Unit = {
-    assert(symbol != null)
-  }
-  def prepareReset(symbol : Symbol, tpe : LazyType) : Unit = {
-    assert(symbol != null)
-  }
 
   /** A period is an ordinal number for a phase in a run.
    *  Phases in later runs have higher periods than phases in earlier runs.
@@ -102,11 +98,18 @@ abstract class SymbolTable extends Names
   /** Perform given operation at given phase */
   final def atPhase[T](ph: Phase)(op: => T): T = {
     val current = phase
-    phase = ph
-    val result = op
-    phase = current
-    result
+    try {
+      phase = ph
+      op
+    } finally {
+      phase = current
+    }
   }
+  
+  /** Break into repl debugger if assertion is true */
+  // def breakIf(assertion: => Boolean, args: Any*): Unit =
+  //   if (assertion)
+  //     Interpreter.break(args.toList)
 
   /** The set of all installed infotransformers */
   var infoTransformers = new InfoTransformer {
diff --git a/src/compiler/scala/tools/nsc/symtab/SymbolWalker.scala b/src/compiler/scala/tools/nsc/symtab/SymbolWalker.scala
deleted file mode 100644
index f98b57f..0000000
--- a/src/compiler/scala/tools/nsc/symtab/SymbolWalker.scala
+++ /dev/null
@@ -1,254 +0,0 @@
-package scala.tools.nsc.symtab
-
-trait SymbolWalker {
-  val global : Global 
-  import scala.tools.nsc.util._
-  import global._
-  import scala.collection.jcl._
-  trait Visitor {
-    def update(pos : Position, sym : Symbol) : Unit
-    def contains(pos : Position) : Boolean
-    def apply(pos : Position) : Symbol
-    def putDef(sym : Symbol, pos : Position) : Unit = ()
-  }
-  import scala.collection.mutable.Map
-  /*
-  implicit def map2use(map : Map[Position,Symbol]) = new Visitor {
-    def update(pos : Position, sym : Symbol) : Unit = map.update(pos, sym)
-    def contains(pos : Position) : Boolean = map.contains(pos)
-    def apply(pos : Position) : Symbol = map.apply(pos)
-  }
-  */
-  def walk(tree: Tree, visitor : Visitor)(fid : (util.Position) => Option[String]) : Unit = {
-    val visited = new LinkedHashSet[Tree]
-    def f(t : Tree) : Unit = {
-      if (!visited.add(t)) return
-      def fs(l : List[Tree]) : Unit = {
-        val i = l.elements
-        while (i.hasNext) f(i.next)
-      }
-      def fss(l : List[List[Tree]]) : Unit = {
-        val i = l.elements
-        while (i.hasNext) fs(i.next)
-      }
-      if (t.isInstanceOf[StubTree]) return
-      def asTypeRef = t.tpe.asInstanceOf[TypeRef]
-      val sym = (t,t.tpe) match {
-        case (Super(_,_),SuperType(_,supertp)) if supertp.typeSymbol != NoSymbol && supertp.typeSymbol != null => supertp.typeSymbol
-        case _ if t.symbol != NoSymbol && t.symbol != null => t.symbol
-        case (t : TypeTree, tp) if tp != null && tp.typeSymbol != null && tp.typeSymbol != NoSymbol => tp.typeSymbol 
-        case (t : TypeTree, tp) if tp != null && tp.resultType != null && tp.resultType.typeSymbol != null => tp.resultType.typeSymbol 
-        case (t, tpe : Type) if tpe != null && (t.symbol eq NoSymbol) && t.isTerm && tpe.termSymbol != null => 
-          tpe.termSymbol
-        case (t, tpe : Type) if tpe != null && (t.symbol eq NoSymbol) && tpe.typeSymbol != null => 
-              if (t.tpe.isInstanceOf[TypeRef]) asTypeRef.sym // XXX: looks like a bug
-             else tpe.typeSymbol 
-        case _ => NoSymbol
-      }
-      if (sym != null && sym != NoSymbol /* && !sym.hasFlag(SYNTHETIC) */) {
-        var id = fid(t.pos) 
-        val doAdd = if (id.isDefined) {
-          if (id.get.charAt(0) == '`') id = Some(id.get.substring(1, id.get.length - 1))
-          val name = sym.name.decode.trim
-          if ((name startsWith id.get) || (id.get startsWith name)) true 
-          else {
-            false
-          }
-        } else false
-        if (doAdd) {
-          
-        if (!visitor.contains(t.pos)) {
-          visitor(t.pos) = sym
-        } else {
-          val existing = visitor(t.pos)
-          if (sym.sourceFile != existing.sourceFile || sym.pos != existing.pos) {
-            (sym,existing) match {
-            case (sym,existing) if sym.pos == existing.pos => 
-            case (sym : TypeSymbol ,_ : ClassSymbol) => visitor(t.pos) = sym
-            case (_ : ClassSymbol,_ : TypeSymbol) => // nothing
-            case _ if sym.isModule && existing.isValue => // nothing
-            case _ if sym.isClass && existing.isMethod => // nothing
-            case _ =>
-              assert(true)
-            }
-          }
-        }}
-      }
-      t match {
-      case t : DefTree if t.symbol != NoSymbol =>
-        if (t.pos != NoPosition)
-          visitor.putDef(t.symbol, t.pos)
-          if (t.symbol.isClass) {
-            val factory = NoSymbol // XXX: t.symbol.caseFactory
-            if (factory != NoSymbol) {
-              visitor.putDef(factory, t.pos)
-            }
-        }
-      case t : TypeBoundsTree => f(t.lo); f(t.hi)
-      case t : TypeTree if t.original != null => 
-        def h(original : Tree, tpe : Type): Unit = try {
-          if (original.tpe == null)
-            original.tpe = tpe
-          (original) match {
-          case (AppliedTypeTree(_,trees)) if tpe.isInstanceOf[TypeRef] => 
-            val types = tpe.asInstanceOf[TypeRef].args
-            trees.zip(types).foreach{
-            case (tree,tpe) => assert(tree != null && tpe != null); h(tree, tpe)
-            }
-          case _ => 
-          }
-        }
-        if (t.original.tpe == null) {
-          val dup = t.original.duplicate
-          h(dup,t.tpe)
-          f(dup)
-        } else f(t.original)
-        ()
-      case _ =>
-      }
-      (t) match {
-      case (t : MemberDef) if t.symbol != null && t.symbol != NoSymbol => 
-        val annotated = if (sym.isModule) sym.moduleClass else sym
-        val i = t.mods.annotations.elements
-        val j = annotated.attributes.elements
-        while (i.hasNext && j.hasNext) {
-          val tree = i.next.constr
-          val ainfo = j.next
-          val sym = ainfo.atp.typeSymbol
-          tree.setType(ainfo.atp)
-          tree.setSymbol(sym)
-          f(tree)
-        }
-
-      case _ =>  
-      }
-      t match {
-      case tree: ImplDef => 
-        fs(tree.impl.parents); f(tree.impl.self); fs(tree.impl.body) 
-        tree match {
-        case tree : ClassDef => fs(tree.tparams)
-        case _ =>
-        }
-      case tree: PackageDef => fs(tree.stats)
-      case tree: ValOrDefDef => 
-        f(tree.rhs); 
-        if (tree.tpt != null) {
-          f(tree.tpt)
-        }
-        tree match {
-        case tree : DefDef => fs(tree.tparams); fss(tree.vparamss)
-        case _ => 
-        }
-      case tree: Function => fs(tree.vparams); f(tree.body)
-      case tree : Bind => f(tree.body)
-      case tree : Select => 
-        val qualifier = if (tree.tpe != null && tree.qualifier.tpe == null) {
-          val pre = tree.tpe.prefix
-          val qualifier = tree.qualifier.duplicate
-          qualifier.tpe = pre
-          qualifier
-        } else tree.qualifier
-      
-        f(qualifier)
-      case tree : Annotation => f(tree.constr)
-      case tree : Annotated => f(tree.annot); f(tree.arg)
-      case tree : GenericApply => f(tree.fun); fs(tree.args)
-      case tree : UnApply => f(tree.fun); fs(tree.args)
-      case tree : AppliedTypeTree =>
-        if (tree.tpe != null) {
-          val i = tree.tpe.typeArgs.elements
-          val j = tree.args.elements
-          while (i.hasNext && j.hasNext) {
-            val tpe = i.next
-            val arg = j.next
-            if (arg.tpe == null) {
-              arg.tpe = tpe  
-            }
-          }
-          if (tree.tpt.tpe == null) {
-            tree.tpt.tpe = tree.tpe
-          }
-          
-        }
-        f(tree.tpt); fs(tree.args) 
-
-      case tree : ExistentialTypeTree=>
-        if (tree.tpt.tpe == null) {
-          tree.tpt.tpe = tree.tpe
-        }
-        
-        f(tree.tpt)
-        fs(tree.whereClauses)
-      case tree : SingletonTypeTree => 
-        if (tree.ref.tpe == null) {
-          val dup = tree.ref.duplicate
-          dup.tpe = tree.tpe
-          f(dup)
-        } else f(tree.ref)
-      case tree : CompoundTypeTree => 
-        if (tree.tpe != null && tree.tpe.typeSymbol != null && tree.tpe.typeSymbol.isRefinementClass) tree.tpe.typeSymbol.info match {
-        case tpe : RefinedType => 
-          tpe.parents.zip(tree.templ.parents).foreach{
-          case (tpe,tree) => 
-            if (tree.hasSymbol && (tree.symbol == NoSymbol || tree.symbol == null)) {
-              tree.symbol = tpe.typeSymbol
-            }
-          }
-        
-        case _ =>
-        }
-        
-        f(tree.templ)
-      case tree : Template => fs(tree.parents); f(tree.self); fs(tree.body)
-      case tree : SelectFromTypeTree => {
-        if (tree.qualifier.tpe == null) tree.tpe match {
-        case tpe : TypeRef =>
-          // give it a type!
-          tree.qualifier.tpe = tpe.prefix
-        case _ => 
-          // tree.tpe.pre
-        }
-        f(tree.qualifier)
-      }
-      case tree : Literal => 
-      /*
-        if (tree.tpe != null && tree.tpe.typeSymbol == definitions.ClassClass) {
-          // nothing we can do without original tree.
-        }
-      */
-      
-      case tree : Typed => f(tree.expr); f(tree.tpt)
-      case tree : Block => fs(tree.stats); f(tree.expr)
-      case tree: CaseDef => f(tree.pat);f(tree.guard);f(tree.body)
-      case tree : Sequence   => fs(tree.trees);
-      case tree : Assign     => f(tree.lhs); f(tree.rhs);
-      case tree : If         => f(tree.cond); f(tree.thenp); f(tree.elsep);
-      case tree : New        => f(tree.tpt);
-      case tree : Match      => f(tree.selector); fs(tree.cases);
-      case tree : Return     => f(tree.expr);
-      case tree : LabelDef   => f(tree.rhs);
-      case tree : Throw      => f(tree.expr);
-      case tree : Try        => f(tree.block); fs(tree.catches); f(tree.finalizer);
-      case tree : Alternative => fs(tree.trees);
-      case tree : TypeDef => 
-        (tree.tpe,sym) match {
-          case (null,sym : TypeSymbol) if (sym.rawInfo.isComplete) =>
-            if (tree.tparams.isEmpty) {
-              if (tree.rhs.tpe == null) tree.rhs.tpe = sym.info
-              f(tree.rhs)
-            } else {
-              val tree0 = AppliedTypeTree(tree.rhs, tree.tparams)
-              tree0.tpe = sym.info
-              f(tree0)
-            }
-          case _ => f(tree.rhs); fs(tree.tparams)
-        }
-      case tree : DocDef     => f(tree.definition);
-      case tree: Import => f(tree.expr)
-      case _ => 
-      }
-    }
-    f(tree)
-  }
-  
-}
diff --git a/src/compiler/scala/tools/nsc/symtab/Symbols.scala b/src/compiler/scala/tools/nsc/symtab/Symbols.scala
index e0c46f3..928a9f4 100644
--- a/src/compiler/scala/tools/nsc/symtab/Symbols.scala
+++ b/src/compiler/scala/tools/nsc/symtab/Symbols.scala
@@ -1,37 +1,41 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: Symbols.scala 16931 2009-01-16 16:24:37Z phaller $
 
-package scala.tools.nsc.symtab
+
+package scala.tools.nsc
+package symtab
 
 import scala.collection.mutable.ListBuffer
 import scala.collection.immutable.Map
-import scala.tools.nsc.io.AbstractFile
-import scala.tools.nsc.util.{Position, NoPosition, BatchSourceFile}
+import io.AbstractFile
+import util.{Position, NoPosition, BatchSourceFile}
+import util.Statistics._
 import Flags._
 
 //todo: get rid of MONOMORPHIC flag
 
-trait Symbols {
-  self: SymbolTable =>
+trait Symbols extends reflect.generic.Symbols { self: SymbolTable =>
   import definitions._
 
   private var ids = 0
-
-  //for statistics:
-  def symbolCount = ids
-  var typeSymbolCount = 0
-  var classSymbolCount = 0
+  def symbolCount = ids // statistics
 
   val emptySymbolArray = new Array[Symbol](0)
-  val emptySymbolSet = Set.empty[Symbol]
 
+  /** Used for deciding in the IDE whether we can interrupt the compiler */
+  protected var activeLocks = 0
 
   /** Used to keep track of the recursion depth on locked symbols */
   private var recursionTable = Map.empty[Symbol, Int]
 
+  private var nextexid = 0
+  private def freshExistentialName() = {
+    nextexid += 1
+    "_"+nextexid
+  }
+
 /*                                 
   type Position;
   def NoPos : Position;
@@ -44,13 +48,15 @@ trait Symbols {
   }
   */
   /** The class for all symbols */
-  abstract class Symbol(initOwner: Symbol, initPos: Position, initName: Name) {
+  abstract class Symbol(initOwner: Symbol, initPos: Position, initName: Name) extends AbsSymbol {
 
     var rawowner = initOwner
     var rawname = initName
     var rawflags: Long = 0
     private var rawpos = initPos
-    val id = { ids += 1; ids }
+
+    val id = { ids += 1; ids } // identity displayed when -uniqid
+    
 //    assert(id != 7498, initName+"/"+initOwner)
 
     var validTo: Period = NoPeriod
@@ -59,7 +65,7 @@ trait Symbols {
     def setPos(pos: Position): this.type = { this.rawpos = pos; this }
  
     def namePos(source: BatchSourceFile) = {
-      val pos: Int = this.pos.offset.getOrElse(-1)
+      val pos: Int = this.pos.pointOrElse(-1)
       val buf = source.content
       if (pos == -1) -1
       else if (isTypeParameter) pos - name.length
@@ -89,31 +95,87 @@ trait Symbols {
       else -1
     }
 
-    var attributes: List[AnnotationInfo] = List()
+// annotations
 
-    def setAttributes(attrs: List[AnnotationInfo]): this.type = { this.attributes = attrs; this }
-    
-    /** Does this symbol have an attribute of the given class? */
-    def hasAttribute(cls: Symbol): Boolean = 
-      attributes.exists { 
-        case AnnotationInfo(tp, _, _) if tp.typeSymbol == cls => true
-        case _ => false
+    private var rawannots: List[AnnotationInfoBase] = Nil
+
+    /* Used in namer to check whether annotations were already assigned or not */
+    def rawAnnotations:List[AnnotationInfoBase] = rawannots
+
+    /** After the typer phase (before, look at the definition's Modifiers), contains
+     *  the annotations attached to member a definition (class, method, type, field).
+     */
+    def annotations: List[AnnotationInfo] = {
+      // .initialize: the type completer of the symbol parses the annotations,
+      // see "def typeSig" in Namers
+      val annots1 = initialize.rawannots map {
+        case LazyAnnotationInfo(annot) => annot()
+        case a @ AnnotationInfo(_, _, _) => a
+      } filter { a => !a.atp.isError }
+      rawannots = annots1
+      annots1
+    }
+
+    def setAnnotations(annots: List[AnnotationInfoBase]): this.type = {
+      this.rawannots = annots
+      this
+    }
+
+    override def addAnnotation(annot: AnnotationInfo) {
+      setAnnotations(annot :: this.rawannots)
     }
 
-    var privateWithin: Symbol = _
+    /** Does this symbol have an annotation of the given class? */
+    def hasAnnotation(cls: Symbol) = 
+      getAnnotation(cls).isDefined
+
+    def getAnnotation(cls: Symbol): Option[AnnotationInfo] = 
+      annotations find (_.atp.typeSymbol == cls)
+      
+    /** Remove all annotations matching the given class. */
+    def removeAnnotation(cls: Symbol): Unit = 
+      setAnnotations(annotations filterNot (_.atp.typeSymbol == cls))
+
+    /** set when symbol has a modifier of the form private[X], NoSymbol otherwise.
+     *  Here's some explanation how privateWithin gets combined with access flags:
+     * 
+     * PRIVATE    means class private, as in Java.
+     * PROTECTED  means protected as in Java, except that access within
+     *            the same package is not automatically allowed.
+     * LOCAL      should only be set with PRIVATE or PROTECTED. 
+     *            It means that access is restricted to be from the same object.
+     * 
+     * Besides these, there's the privateWithin field in Symbols which gives a visibility barrier,
+     * where privateWithin == NoSymbol means no barrier. privateWithin is incompatible with
+     * PRIVATE and LOCAL. If it is combined with PROTECTED, the two are additive. I.e.
+     * the symbol is then accessible from within the privateWithin region as well
+     * as from all subclasses. Here's a tanslation of Java's accessibility modifiers:
+     * Java private:   PRIVATE flag set, privateWithin == NoSymbol
+     * Java package:   no flag set, privateWithin == enclosing package
+     * Java protected:  PROTECTED flag set, privateWithin == enclosing package
+     * Java public:   no flag set, privateWithin == NoSymbol
+     */
+    private[this] var _privateWithin: Symbol = _  
+    def privateWithin = _privateWithin
+    override def privateWithin_=(sym: Symbol) { _privateWithin = sym }
 
 // Creators -------------------------------------------------------------------
 
     final def newValue(pos: Position, name: Name) = 
       new TermSymbol(this, pos, name)
+    final def newValue(name: Name, pos: Position = NoPosition) = 
+      new TermSymbol(this, pos, name)
     final def newVariable(pos: Position, name: Name) =
       newValue(pos, name).setFlag(MUTABLE)
     final def newValueParameter(pos: Position, name: Name) =
       newValue(pos, name).setFlag(PARAM)
-    final def newLocalDummy(pos: Position) =
+    /** Create local dummy for template (owner of local blocks) */
+    final def newLocalDummy(pos: Position) = 
       newValue(pos, nme.LOCAL(this)).setInfo(NoType)
     final def newMethod(pos: Position, name: Name) =
-      newValue(pos, name).setFlag(METHOD)
+      new MethodSymbol(this, pos, name).setFlag(METHOD)
+    final def newMethod(name: Name, pos: Position = NoPosition) =
+      new MethodSymbol(this, pos, name).setFlag(METHOD)
     final def newLabel(pos: Position, name: Name) =
       newMethod(pos, name).setFlag(LABEL)
     final def newConstructor(pos: Position) =
@@ -121,6 +183,9 @@ trait Symbols {
     final def newModule(pos: Position, name: Name, clazz: ClassSymbol) =
       new ModuleSymbol(this, pos, name).setFlag(MODULE | FINAL)
         .setModuleClass(clazz)
+    final def newModule(name: Name, clazz: Symbol, pos: Position = NoPosition) =
+      new ModuleSymbol(this, pos, name).setFlag(MODULE | FINAL)
+        .setModuleClass(clazz.asInstanceOf[ClassSymbol])
     final def newModule(pos: Position, name: Name) = {
       val m = new ModuleSymbol(this, pos, name).setFlag(MODULE | FINAL)
       m.setModuleClass(new ModuleClassSymbol(m))
@@ -135,11 +200,31 @@ trait Symbols {
       newValue(pos, nme.this_).setFlag(SYNTHETIC)
     final def newImport(pos: Position) =
       newValue(pos, nme.IMPORT)
+
+    /** @param pre   type relative to which alternatives are seen.
+     *  for instance:
+     *  class C[T] {
+     *    def m(x: T): T
+     *    def m'(): T
+     *  }
+     *  val v: C[Int]
+     *
+     *  Then v.m  has symbol TermSymbol(flags = {OVERLOADED},
+     *                                  tpe = OverloadedType(C[Int], List(m, m')))
+     *  You recover the type of m doing a
+     *
+     *    m.tpe.asSeenFrom(pre, C)   (generally, owner of m, which is C here).
+     *
+     *  or:
+     *
+     *    pre.memberType(m)
+     */
     final def newOverloaded(pre: Type, alternatives: List[Symbol]): Symbol =
       newValue(alternatives.head.pos, alternatives.head.name)
       .setFlag(OVERLOADED)
       .setInfo(OverloadedType(pre, alternatives))
 
+    /** for explicit outer phase */
     final def newOuterAccessor(pos: Position) = {
       val sym = newMethod(pos, nme.OUTER) 
       sym setFlag (STABLE | SYNTHETIC)
@@ -151,128 +236,210 @@ trait Symbols {
 
     final def newErrorValue(name: Name) =
       newValue(pos, name).setFlag(SYNTHETIC | IS_ERROR).setInfo(ErrorType)
+
+    /** Symbol of a type definition  type T = ...
+     */
     final def newAliasType(pos: Position, name: Name) =
       new TypeSymbol(this, pos, name)
+    final def newAliasType(name: Name, pos: Position = NoPosition) =
+      new TypeSymbol(this, pos, name)
+    
+    /** Symbol of an abstract type  type T >: ... <: ...
+     */
     final def newAbstractType(pos: Position, name: Name) =
       new TypeSymbol(this, pos, name).setFlag(DEFERRED)
+    final def newAbstractType(name: Name, pos: Position = NoPosition) =
+      new TypeSymbol(this, pos, name).setFlag(DEFERRED)
+
+    /** Symbol of a type parameter
+     */
     final def newTypeParameter(pos: Position, name: Name) =
       newAbstractType(pos, name).setFlag(PARAM)
+
+    /** Synthetic value parameters when parameter symbols are not available
+     */
+    final def newSyntheticValueParamss(argtypess: List[List[Type]]): List[List[Symbol]] = {
+      var cnt = 0
+      def freshName() = { cnt += 1; newTermName("x$" + cnt) }
+      def param(tp: Type) =
+        newValueParameter(owner.pos.focus, freshName()).setFlag(SYNTHETIC).setInfo(tp)
+      argtypess map (_.map(param))
+    }
+
+    /** Make an existential variable.
+     *  @param name    suffix to be appended to the freshly generated name
+     *                 It's ususally "", except for type variables abstracting
+     *                 over values, where it is ".type".
+     *  @param owner   The owner of the variable
+     *  @param bounds  The variable's bounds
+     */
+    final def newExistential(pos: Position, name: Name): Symbol = 
+      newAbstractType(pos, name.toTypeName).setFlag(EXISTENTIAL)
+
+    final def freshExistential(suffix: String): Symbol = 
+      newExistential(pos, freshExistentialName()+suffix)
+
+    /** Synthetic value parameters when parameter symbols are not available.
+     *  Calling this method multiple times will re-use the same parameter names.
+     */
+    final def newSyntheticValueParams(argtypes: List[Type]): List[Symbol] =
+      newSyntheticValueParamss(List(argtypes)).head
+
+    /** Synthetic value parameter when parameter symbol is not available.
+     *  Calling this method multiple times will re-use the same parameter name.
+     */
+    final def newSyntheticValueParam(argtype: Type): Symbol =
+      newSyntheticValueParams(List(argtype)).head
+    
+    /** Type skolems are type parameters ``seen from the inside''
+     *  Assuming a polymorphic method m[T], its type is a PolyType which has a TypeParameter
+     *  with name `T' in its typeParams list. While type checking the parameters, result type and
+     *  body of the method, there's a local copy of `T' which is a TypeSkolem.
+     */
     final def newTypeSkolem: Symbol =
       new TypeSkolem(owner, pos, name, this)
         .setFlag(flags)
+
     final def newClass(pos: Position, name: Name) =
       new ClassSymbol(this, pos, name)
+    final def newClass(name: Name, pos: Position = NoPosition) =
+      new ClassSymbol(this, pos, name)
+
     final def newModuleClass(pos: Position, name: Name) =
       new ModuleClassSymbol(this, pos, name)
+    final def newModuleClass(name: Name, pos: Position = NoPosition) =
+      new ModuleClassSymbol(this, pos, name)
+
     final def newAnonymousClass(pos: Position) =
       newClass(pos, nme.ANON_CLASS_NAME.toTypeName)
+
     final def newAnonymousFunctionClass(pos: Position) =
       newClass(pos, nme.ANON_FUN_NAME.toTypeName)
+
+    /** Refinement types P { val x: String; type T <: Number }
+     *  also have symbols, they are refinementClasses
+     */
     final def newRefinementClass(pos: Position) =
       newClass(pos, nme.REFINE_CLASS_NAME.toTypeName)
+
+    /** Create a new getter for current symbol (which must be a field)
+     */
+    final def newGetter: Symbol = {
+      val getter = owner.newMethod(pos.focus, nme.getterName(name)).setFlag(getterFlags(flags))
+      getter.privateWithin = privateWithin
+      getter.setInfo(MethodType(List(), tpe))
+    }
+
     final def newErrorClass(name: Name) = {
       val clazz = newClass(pos, name).setFlag(SYNTHETIC | IS_ERROR)
       clazz.setInfo(ClassInfoType(List(), new ErrorScope(this), clazz))
       clazz
     }
+
     final def newErrorSymbol(name: Name): Symbol =
       if (name.isTypeName) newErrorClass(name) else newErrorValue(name)
 
 // Locking and unlocking ------------------------------------------------------
 
-  // True if the symbol is unlocked. 
-  // True if the symbol is locked but still below the allowed recursion depth.
-  // False otherwise
-  def lockOK: Boolean = {
-    ((rawflags & LOCKED) == 0) ||
-    ((settings.Yrecursion.value != 0) &&
-     (recursionTable get this match {
-       case Some(n) => (n <= settings.Yrecursion.value)
-       case None => true }))
-  }
+    // True if the symbol is unlocked. 
+    // True if the symbol is locked but still below the allowed recursion depth.
+    // False otherwise
+    def lockOK: Boolean = {
+      ((rawflags & LOCKED) == 0L) ||
+      ((settings.Yrecursion.value != 0) &&
+       (recursionTable get this match {
+         case Some(n) => (n <= settings.Yrecursion.value)
+         case None => true }))
+    }
 
-  // Lock a symbol, using the handler if the recursion depth becomes too great.
-  def lock(handler: => Unit) = {
-    if ((rawflags & LOCKED) != 0) {
-      if (settings.Yrecursion.value != 0) {
-        recursionTable get this match {
-          case Some(n) =>
-            if (n > settings.Yrecursion.value) {
-	      handler
-	    } else {
-              recursionTable += (this -> (n + 1))
-	    }
-          case None =>
-            recursionTable += (this -> 1)
-        }
-      } else { handler }
-    } else { rawflags |= LOCKED }
-  }
+    // Lock a symbol, using the handler if the recursion depth becomes too great.
+    def lock(handler: => Unit) = {
+      if ((rawflags & LOCKED) != 0L) {
+        if (settings.Yrecursion.value != 0) {
+          recursionTable get this match {
+            case Some(n) =>
+              if (n > settings.Yrecursion.value) {
+                handler
+              } else {
+                recursionTable += (this -> (n + 1))
+              }
+            case None =>
+              recursionTable += (this -> 1)
+          }
+        } else { handler }
+      } else { 
+        rawflags |= LOCKED 
+        activeLocks += 1
+      }
+    }
 
-  // Unlock a symbol
-  def unlock() = {
-    rawflags = rawflags & ~LOCKED
-    if (settings.Yrecursion.value != 0)
-      recursionTable -= this
-  }
+    // Unlock a symbol
+    def unlock() = {
+      if ((rawflags & LOCKED) != 0L) {
+        activeLocks -= 1
+        rawflags = rawflags & ~LOCKED
+        if (settings.Yrecursion.value != 0)
+          recursionTable -= this
+      }
+    }
 
 // Tests ----------------------------------------------------------------------
 
-    def isTerm   = false         //to be overridden
-    def isType   = false         //to be overridden
-    def isClass  = false         //to be overridden
-    def isTypeMember = false     //to be overridden
-    def isAliasType = false      //to be overridden
-    def isAbstractType = false   //to be overridden
-    def isSkolem = false         //to be overridden
+    /** Is this symbol a type but not a class? */
+    def isNonClassType = false 
 
+    /** Term symbols with the exception of static parts of Java classes and packages.
+     */
     final def isValue = isTerm && !(isModule && hasFlag(PACKAGE | JAVA))
+
     final def isVariable  = isTerm && hasFlag(MUTABLE) && !isMethod
+    
+    // interesting only for lambda lift. Captured variables are accessed from inner lambdas.
     final def isCapturedVariable  = isVariable && hasFlag(CAPTURED)
 
     final def isGetter = isTerm && hasFlag(ACCESSOR) && !nme.isSetterName(name)
     final def isSetter = isTerm && hasFlag(ACCESSOR) && nme.isSetterName(name)
        //todo: make independent of name, as this can be forged.
+
     final def hasGetter = isTerm && nme.isLocalName(name)
+
     final def isValueParameter = isTerm && hasFlag(PARAM)
     final def isLocalDummy = isTerm && nme.isLocalDummyName(name)
-    final def isMethod = isTerm && hasFlag(METHOD)
-    final def isSourceMethod = isTerm && (flags & (METHOD | STABLE)) == METHOD
     final def isLabel = isMethod && !hasFlag(ACCESSOR) && hasFlag(LABEL)
     final def isInitializedToDefault = !isType && (getFlag(DEFAULTINIT | ACCESSOR) == (DEFAULTINIT | ACCESSOR))
     final def isClassConstructor = isTerm && (name == nme.CONSTRUCTOR)
     final def isMixinConstructor = isTerm && (name == nme.MIXIN_CONSTRUCTOR)
     final def isConstructor = isTerm && (name == nme.CONSTRUCTOR) || (name == nme.MIXIN_CONSTRUCTOR)
-    final def isModule = isTerm && hasFlag(MODULE)
     final def isStaticModule = isModule && isStatic && !isMethod
-    final def isPackage = isModule && hasFlag(PACKAGE)
     final def isThisSym = isTerm && owner.thisSym == this
     //final def isMonomorphicType = isType && hasFlag(MONOMORPHIC)
     final def isError = hasFlag(IS_ERROR)
     final def isErroneous = isError || isInitialized && tpe.isErroneous
-    final def isTrait = isClass & hasFlag(TRAIT | notDEFERRED)     // A virtual class becomes a trait (part of DEVIRTUALIZE)
+    override final def isTrait: Boolean = isClass && hasFlag(TRAIT | notDEFERRED)     // A virtual class becomes a trait (part of DEVIRTUALIZE)
     final def isTypeParameterOrSkolem = isType && hasFlag(PARAM)
     final def isTypeSkolem            = isSkolem && hasFlag(PARAM)
-    final def isTypeParameter         = isTypeParameterOrSkolem && !isSkolem
-    final def isExistential           = isType && hasFlag(EXISTENTIAL)
-    final def isExistentialSkolem     = isSkolem && hasFlag(EXISTENTIAL)
-    final def isExistentialQuantified = isExistential && !isSkolem
+    // a type symbol bound by an existential type, for instance the T in
+    // List[T] forSome { type T }
+    final def isExistentialSkolem     = isExistentiallyBound && isSkolem
+    final def isExistentialQuantified = isExistentiallyBound && !isSkolem
+
+    // class C extends D( { class E { ... } ... } ). Here, E is a class local to a constructor
     final def isClassLocalToConstructor = isClass && hasFlag(INCONSTRUCTOR)
-    final def isAnonymousClass = isClass && (originalName startsWith nme.ANON_CLASS_NAME)
-      // startsWith necessary because name may grow when lifted and also because of anonymous function classes
-    def isAnonymousFunction = hasFlag(SYNTHETIC) && (originalName startsWith nme.ANON_FUN_NAME)
-    final def isRefinementClass = isClass && name == nme.REFINE_CLASS_NAME.toTypeName; // no lifting for refinement classes
-    final def isModuleClass = isClass && hasFlag(MODULE)
-    final def isPackageClass = isClass && hasFlag(PACKAGE)
-    final def isRoot = isPackageClass && name == nme.ROOT.toTypeName
-    final def isRootPackage = isPackage && name == nme.ROOTPKG
-    final def isEmptyPackage = isPackage && name == nme.EMPTY_PACKAGE_NAME
-    final def isEmptyPackageClass = isPackageClass && name == nme.EMPTY_PACKAGE_NAME.toTypeName
-    final def isPredefModule = isModule && name == nme.Predef // not printed as a prefix
-    final def isScalaPackage = isPackage && name == nme.scala_ // not printed as a prefix
-    final def isScalaPackageClass = isPackageClass && name == nme.scala_.toTypeName // not printed as a prefix
+
+    final def isAnonymousClass = isClass && (originalName startsWith nme.ANON_CLASS_NAME) // todo: find out why we can't use containsName here.
+    final def isAnonymousFunction = hasFlag(SYNTHETIC) && (name containsName nme.ANON_FUN_NAME)
+
+    final def isClassOfModule = isModuleClass || isClass && nme.isLocalName(name)
+    final def isPackageObject = isModule && name == nme.PACKAGEkw && owner.isPackageClass
+    final def isPackageObjectClass = isModuleClass && name.toTermName == nme.PACKAGEkw && owner.isPackageClass
+    final def definedInPackage  = owner.isPackageClass || owner.isPackageObjectClass
+    final def isPredefModule = isModule && name == nme.Predef && owner.isScalaPackageClass // not printed as a prefix
+    final def isScalaPackage = isPackage && name == nme.scala_ && owner.isRoot || // not printed as a prefix
+                               isPackageObject && owner.isScalaPackageClass
+    final def isScalaPackageClass: Boolean = isPackageClass && owner.isRoot && name == nme.scala_.toTypeName ||
+                                    isPackageObjectClass && owner.isScalaPackageClass // not printed as a prefix
     
-    /** Is symbol a monomophic type?
+    /** Is symbol a monomorphic type?
      *  assumption: if a type starts out as monomorphic, it will not acquire 
      *  type parameters in later phases.
      */
@@ -285,8 +452,17 @@ trait Symbols {
         }
       }
 
-    def isDeprecated = 
-      attributes exists (attr => attr.atp.typeSymbol == DeprecatedAttr)
+    def isDeprecated        = hasAnnotation(DeprecatedAttr)
+    def deprecationMessage  = getAnnotation(DeprecatedAttr) flatMap { _.stringArg(0) }
+    // !!! when annotation arguments are not literal strings, but any sort of 
+    // assembly of strings, there is a fair chance they will turn up here not as
+    // Literal(const) but some arbitrary AST.  However nothing in the compiler
+    // prevents someone from writing a @migration annotation with a calculated
+    // string.  So this needs attention.  For now the fact that migration is
+    // private[scala] ought to provide enough protection.
+    def migrationMessage    = getAnnotation(MigrationAnnotationClass) flatMap { _.stringArg(2) }
+    def elisionLevel        = getAnnotation(ElidableMethodClass) flatMap { _.intArg(0) }
+    def implicitNotFoundMsg = getAnnotation(ImplicitNotFoundClass) flatMap { _.stringArg(0) }
 
     /** Does this symbol denote a wrapper object of the interpreter or its class? */
     final def isInterpreterWrapper = 
@@ -295,21 +471,26 @@ trait Symbols {
       name.toString.startsWith(nme.INTERPRETER_LINE_PREFIX) &&
       name.toString.endsWith(nme.INTERPRETER_WRAPPER_SUFFIX)
 
+    override def isEffectiveRoot = super.isEffectiveRoot || isInterpreterWrapper
+
     /** Is this symbol an accessor method for outer? */
     final def isOuterAccessor = {
       hasFlag(STABLE | SYNTHETIC) &&
       originalName == nme.OUTER 
     }
 
+    /** Is this symbol an accessor method for outer? */
+    final def isOuterField = {
+      hasFlag(SYNTHETIC) &&
+      originalName == nme.OUTER_LOCAL
+    }
+
     /** Does this symbol denote a stable value? */
     final def isStable =
       isTerm && 
       !hasFlag(MUTABLE) && 
       (!hasFlag(METHOD | BYNAMEPARAM) || hasFlag(STABLE)) && 
-      !(tpe.isVolatile && getAttributes(uncheckedStableClass).isEmpty)
-
-    def isDeferred = 
-      hasFlag(DEFERRED) && !isClass
+      !(tpe.isVolatile && !hasAnnotation(uncheckedStableClass))
 
     def isVirtualClass = 
       hasFlag(DEFERRED) && isClass
@@ -318,30 +499,19 @@ trait Symbols {
       hasFlag(DEFERRED) && isTrait
 
     /** Is this symbol a public */
-    final def isPublic: Boolean =
-      !hasFlag(PRIVATE | PROTECTED) && privateWithin == NoSymbol
-
-    /** Is this symbol a private local */
-    final def isPrivateLocal = 
-      hasFlag(PRIVATE) && hasFlag(LOCAL)
-
-    /** Is this symbol a protected local */
-    final def isProtectedLocal = 
-      hasFlag(PROTECTED) && hasFlag(LOCAL)
 
     /** Does this symbol denote the primary constructor of its enclosing class? */
     final def isPrimaryConstructor =
       isConstructor && owner.primaryConstructor == this
+      
+    /** Does this symbol denote an auxiliary constructor of its enclosing class? */
+    final def isAuxiliaryConstructor =
+      isConstructor && !isPrimaryConstructor
 
     /** Is this symbol a synthetic apply or unapply method in a companion object of a case class? */
     final def isCaseApplyOrUnapply = 
       isMethod && hasFlag(CASE) && hasFlag(SYNTHETIC)
 
-    /** Is this symbol an implementation class for a mixin? */
-    final def isImplClass: Boolean = isClass && hasFlag(IMPLCLASS)
-
-    /** Is thhis symbol early initialized */
-    final def isEarly: Boolean = isTerm && hasFlag(PRESUPER)
 
     /** Is this symbol a trait which needs an implementation class? */
     final def needsImplClass: Boolean =
@@ -369,16 +539,9 @@ trait Symbols {
     final def isStaticOwner: Boolean =
       isPackageClass || isModuleClass && isStatic
 
-    /** Is this symbol final?*/
-    final def isFinal: Boolean = (
-      hasFlag(FINAL) ||
-      isTerm && (
-        hasFlag(PRIVATE) || isLocal || owner.isClass && owner.hasFlag(FINAL | MODULE))
-    )
-
-    /** Is this symbol a sealed class?*/
-    final def isSealed: Boolean =
-      isClass && (hasFlag(SEALED) || isUnboxedClass(this))
+    /** Is this symbol effectively final? I.e, it cannot be overridden */
+    final def isEffectivelyFinal: Boolean = isFinal || isTerm && (
+      hasFlag(PRIVATE) || isLocal || owner.isClass && owner.hasFlag(FINAL | MODULE))
 
     /** Is this symbol locally defined? I.e. not accessed from outside `this' instance */
     final def isLocal: Boolean = owner.isTerm
@@ -405,11 +568,22 @@ trait Symbols {
     final def isLocalClass: Boolean =
       isClass && (isAnonymousClass || isRefinementClass || isLocal ||
                   !owner.isPackageClass && owner.isLocalClass)
+    
+    /** Is this class or type defined as a structural refinement type?
+     */
+    final def isStructuralRefinement: Boolean =
+      (isClass || isType || isModule) && info.normalize/*.underlying*/.isStructuralRefinement
+    
+
+    /** Is this symbol a member of class `clazz'
+     */
+    def isMemberOf(clazz: Symbol) =
+      clazz.info.member(name).alternatives contains this
 
     /** A a member of class `base' is incomplete if
      *  (1) it is declared deferred or
      *  (2) it is abstract override and its super symbol in `base' is
-     *      nonexistent or inclomplete.
+     *      nonexistent or incomplete.
      *
      *  @param base ...
      *  @return     ...
@@ -421,6 +595,8 @@ trait Symbols {
         supersym == NoSymbol || supersym.isIncompleteIn(base)
       }
 
+    // Does not always work if the rawInfo is a SourcefileLoader, see comment
+    // in "def coreClassesFirst" in Global.
     final def exists: Boolean =
       this != NoSymbol && (!owner.isPackageClass || { rawInfo.load(this); rawInfo != NoType })
 
@@ -440,9 +616,6 @@ trait Symbols {
       isClass && (hasFlag(STABLE) || checkStable())
     }
 
-    final def isCovariant: Boolean = isType && hasFlag(COVARIANT)
-
-    final def isContravariant: Boolean = isType && hasFlag(CONTRAVARIANT)
 
     /** The variance of this symbol as an integer */
     final def variance: Int =
@@ -450,21 +623,20 @@ trait Symbols {
       else if (isContravariant) -1
       else 0
 
-    def isSerializable: Boolean = isMethod || {
-      val typeSym = info.typeSymbol
-      isValueType(typeSym) ||
-      typeSym.hasAttribute(SerializableAttr) ||
-      (info.baseClasses exists { bc => (bc hasAttribute SerializableAttr) || (bc == SerializableClass) }) ||
-      (isClass && info.members.forall(_.isSerializable))
-    }
-
 // Flags, owner, and name attributes --------------------------------------------------------------
 
     def owner: Symbol = rawowner
-    final def owner_=(owner: Symbol) { rawowner = owner }
+    override final def owner_=(owner: Symbol) { rawowner = owner }
 
     def ownerChain: List[Symbol] = this :: owner.ownerChain
 
+    def ownersIterator: Iterator[Symbol] = new Iterator[Symbol] {
+      private var current = Symbol.this
+      def hasNext = current ne NoSymbol
+      def next = { val r = current; current = current.owner; r }
+    }
+
+    // same as ownerChain contains sym, but more efficient
     def hasTransOwner(sym: Symbol) = {
       var o = this
       while ((o ne sym) && (o ne NoSymbol)) o = o.owner
@@ -495,18 +667,19 @@ trait Symbols {
       val fs = rawflags & phase.flagMask
       (fs | ((fs & LateFlags) >>> LateShift)) & ~(fs >>> AntiShift)
     }
-    final def flags_=(fs: Long) = rawflags = fs
+    override final def flags_=(fs: Long) = rawflags = fs
     final def setFlag(mask: Long): this.type = { rawflags = rawflags | mask; this }
     final def resetFlag(mask: Long): this.type = { rawflags = rawflags & ~mask; this }
     final def getFlag(mask: Long): Long = flags & mask
-    final def hasFlag(mask: Long): Boolean = (flags & mask) != 0
     final def resetFlags { rawflags = rawflags & TopLevelCreationFlags }
 
+    final def hasAccessBoundary = (privateWithin != null) && (privateWithin != NoSymbol)
+
     /** The class or term up to which this symbol is accessible,
-     *  or RootClass if it is public
+     *  or RootClass if it is public.
      */
     def accessBoundary(base: Symbol): Symbol = {
-      if (hasFlag(PRIVATE) || owner.isTerm) owner
+      if (hasFlag(PRIVATE) || isLocal) owner
       else if (privateWithin != NoSymbol && !phase.erasedTypes) privateWithin
       else if (hasFlag(PROTECTED)) base
       else RootClass
@@ -528,40 +701,47 @@ trait Symbols {
     private[Symbols] var infos: TypeHistory = null
 
     /** Get type. The type of a symbol is:
-     *  for a type symbol, the type corresponding to the symbol itself
+     *  for a type symbol, the type corresponding to the symbol itself, 
+     *    @M you should use tpeHK for a type symbol with type parameters if
+     *       the kind of the type need not be *, as tpe introduces dummy arguments
+     *       to generate a type of kind *
      *  for a term symbol, its usual type
      */
-    def tpe: Type = info
+    override def tpe: Type = info
 
     /** Get type info associated with symbol at current phase, after
      *  ensuring that symbol is initialized (i.e. type is completed).
      */
-    def info: Type = try {
+    override def info: Type = try {
       var cnt = 0 
       while (validTo == NoPeriod) {
         //if (settings.debug.value) System.out.println("completing " + this);//DEBUG
-        if (inIDE && (infos eq null)) return ErrorType
         assert(infos ne null, this.name)
         assert(infos.prev eq null, this.name)
         val tp = infos.info
         //if (settings.debug.value) System.out.println("completing " + this.rawname + tp.getClass());//debug
-	lock {
-          setInfo(ErrorType)
-          throw CyclicReference(this, tp)
+        if ((rawflags & LOCKED) != 0L) { // rolled out once for performance
+          lock {
+            setInfo(ErrorType)
+            throw CyclicReference(this, tp)
+          }
+        } else {
+          rawflags |= LOCKED 
+          activeLocks += 1
         }
         val current = phase
         try {
           phase = phaseOf(infos.validFrom)
           tp.complete(this)
           // if (settings.debug.value && runId(validTo) == currentRunId) System.out.println("completed " + this/* + ":" + info*/);//DEBUG
-	  unlock()
+          unlock()
         } finally {
           phase = current
         }
         cnt += 1
         // allow for two completions:
         //   one: sourceCompleter to LazyType, two: LazyType to completed type
-        if (cnt == 3) throw new Error("no progress in completing " + this + ":" + tp)
+        if (cnt == 3) abort("no progress in completing " + this + ":" + tp)
       }
       val result = rawInfo
       result
@@ -571,25 +751,24 @@ trait Symbols {
         throw ex
     }
 
-    /** Set initial info. */
-    def setInfo(info: Type): this.type = {
+    override def info_=(info: Type) {
       assert(info ne null)
       infos = TypeHistory(currentPeriod, info, null)
-      if (info.isComplete) {
-	  unlock()
-        validTo = currentPeriod
-      } else {
-	  unlock()
-        validTo = NoPeriod
-      }
-      this
+      unlock()
+      validTo = if (info.isComplete) currentPeriod else NoPeriod
     }
 
+    /** Set initial info. */
+    def setInfo(info: Type): this.type = { info_=(info); this }
+
+    def setInfoOwnerAdjusted(info: Type): this.type = setInfo(info.atOwner(this))
+
     /** Set new info valid from start of this phase. */
     final def updateInfo(info: Type): Symbol = {
       assert(phaseId(infos.validFrom) <= phase.id)
       if (phaseId(infos.validFrom) == phase.id) infos = infos.prev
       infos = TypeHistory(currentPeriod, info, infos)
+      validTo = if (info.isComplete) currentPeriod else NoPeriod
       this
     }
 
@@ -598,12 +777,11 @@ trait Symbols {
     /** Return info without checking for initialization or completing */
     def rawInfo: Type = {
       var infos = this.infos
-      assert(infos != null, name)
+      assert(infos != null)
       val curPeriod = currentPeriod
       val curPid = phaseId(curPeriod)
 
-      if (!inIDE && validTo != NoPeriod) { // IDE doesn't adapt.
-
+      if (validTo != NoPeriod) {
         // skip any infos that concern later phases
         while (curPid < phaseId(infos.validFrom) && infos.prev != null) 
           infos = infos.prev
@@ -637,10 +815,11 @@ trait Symbols {
             phase = current
           }
         }
-      }            
+      }
       infos.info
     }
 
+    // adapt to new run in fsc.
     private def adaptInfos(infos: TypeHistory): TypeHistory =
       if (infos == null || runId(infos.validFrom) == currentRunId) {
         infos
@@ -677,14 +856,43 @@ trait Symbols {
       infos ne null
     }
 
+    /** Was symbol's type updated during given phase? */
+    final def hasTypeAt(pid: Phase#Id): Boolean = {
+      var infos = this.infos
+      while ((infos ne null) && phaseId(infos.validFrom) > pid) infos = infos.prev
+      infos ne null
+    }
+
+    /** Modify term symbol's type so that a raw type C is converted to an existential C[_]
+     *
+     * This is done in checkAccessible and overriding checks in refchecks
+     * We can't do this on class loading because it would result in infinite cycles.
+     */
+    private var triedCooking: Boolean = false
+    final def cookJavaRawInfo() {
+      // println("cookJavaRawInfo: "+(rawname, triedCooking))
+      if(triedCooking) return else triedCooking = true // only try once...
+      doCookJavaRawInfo()
+    }
+
+    protected def doCookJavaRawInfo(): Unit
+
+
     /** The type constructor of a symbol is:
      *  For a type symbol, the type corresponding to the symbol itself,
      *  excluding parameters.
      *  Not applicable for term symbols.
      */
     def typeConstructor: Type =
-      throw new Error("typeConstructor inapplicable for " + this)
-
+      abort("typeConstructor inapplicable for " + this)
+
+    /** @M -- tpe vs tpeHK:
+     * Symbol::tpe creates a TypeRef that has dummy type arguments to get a type of kind *
+     * Symbol::tpeHK creates a TypeRef without type arguments, but with type params --> higher-kinded if non-empty list of tpars
+     * calling tpe may hide errors or introduce spurious ones 
+     *   (e.g., when deriving a type from the symbol of a type argument that must be higher-kinded)
+     * as far as I can tell, it only makes sense to call tpe in conjunction with a substitution that replaces the generated dummy type arguments by their actual types 
+     */
     def tpeHK = if (isType) typeConstructor else tpe // @M! used in memberType
 
     /** The type parameters of this symbol, without ensuring type completion.
@@ -692,20 +900,51 @@ trait Symbols {
      *  type parameters later.
      */
     def unsafeTypeParams: List[Symbol] = 
-      if (isMonomorphicType) List() else rawInfo.typeParams 
+      if (isMonomorphicType) List() 
+      else {
+        val current = phase
+        try {
+          while ((phase.prev ne NoPhase) && phase.prev.keepsTypeParams) phase = phase.prev
+//          while (phase.keepsTypeParams && (phase.prev ne NoPhase))        phase = phase.prev
+          if (phase ne current) phase = phase.next
+          if (settings.debug.value && (phase ne current))
+            log("checking unsafeTypeParams(" + this + ") at: " + current + " reading at: " + phase)
+          rawInfo.typeParams
+        } finally {
+          phase = current
+        }
+      }
 
     /** The type parameters of this symbol.
      *  assumption: if a type starts out as monomorphic, it will not acquire 
      *  type parameters later.
      */
     def typeParams: List[Symbol] =
-      if (isMonomorphicType) List() else { rawInfo.load(this); rawInfo.typeParams }
-
-    def getAttributes(clazz: Symbol): List[AnnotationInfo] =
-      attributes.filter(_.atp.typeSymbol.isNonBottomSubClass(clazz))
+      if (isMonomorphicType) 
+        List() 
+      else { 
+        if (validTo == NoPeriod) {
+          val current = phase
+          try {
+            phase = phaseOf(infos.validFrom)
+            rawInfo.load(this)
+          } finally {
+            phase = current
+          }
+        }
+        rawInfo.typeParams 
+      }
+    
+    /** The value parameter sections of this symbol.
+     */
+    def paramss: List[List[Symbol]] = info.paramss
 
     /** The least proper supertype of a class; includes all parent types
-     *  and refinement where needed 
+     *  and refinement where needed. You need to compute that in a situation like this:
+     *  {
+     *    class C extends P { ... }
+     *    new C
+     *  }
      */
     def classBound: Type = {
       val tp = refinedType(info.parents, owner)
@@ -737,13 +976,13 @@ trait Symbols {
      */
     def existentialBound: Type = 
       if (this.isClass) 
-         polyType(this.typeParams, mkTypeBounds(NothingClass.tpe, this.classBound))
+         polyType(this.typeParams, TypeBounds(NothingClass.tpe, this.classBound))
       else if (this.isAbstractType) 
          this.info
       else if (this.isTerm) 
-         mkTypeBounds(NothingClass.tpe, intersectionType(List(this.tpe, SingletonClass.tpe)))
+         TypeBounds(NothingClass.tpe, intersectionType(List(this.tpe, SingletonClass.tpe)))
       else 
-        throw new Error("unexpected alias type: "+this)
+        abort("unexpected alias type: "+this)
 
     /** Reset symbol to initial state
      */
@@ -808,16 +1047,13 @@ trait Symbols {
         else if (alts1.isEmpty) NoSymbol
         else if (alts1.tail.isEmpty) alts1.head
         else owner.newOverloaded(info.prefix, alts1)
-      } else if (cond(this)) this
-      else NoSymbol
+      } else if (this == NoSymbol || cond(this)) {
+        this
+      } else NoSymbol
 
     def suchThat(cond: Symbol => Boolean): Symbol = {
       val result = filter(cond)
-      // @S: seems like NoSymbol has the overloaded flag????
-      if (inIDE && (this eq result) && result != NoSymbol && (result hasFlag OVERLOADED)) {
-        return result         
-      }
-      if (!inIDE) assert(!(result hasFlag OVERLOADED), result.alternatives)
+      assert(!(result hasFlag OVERLOADED), result.alternatives)
       result
     }
 
@@ -828,9 +1064,12 @@ trait Symbols {
       cloneSymbol(owner)
 
     /** A clone of this symbol, but with given owner */
-    final def cloneSymbol(owner: Symbol): Symbol =
-      cloneSymbolImpl(owner).setInfo(info.cloneInfo(this))
-        .setFlag(this.rawflags).setAttributes(this.attributes)
+    final def cloneSymbol(owner: Symbol): Symbol = {
+      val newSym = cloneSymbolImpl(owner)
+      newSym.privateWithin = privateWithin
+      newSym.setInfo(info.cloneInfo(newSym))
+        .setFlag(this.rawflags).setAnnotations(this.annotations)
+    }
 
     /** Internal method to clone a symbol's implementation without flags or type
      */
@@ -838,12 +1077,6 @@ trait Symbols {
 
 // Access to related symbols --------------------------------------------------
 
-    /** The next enclosing class */
-    def enclClass: Symbol = if (isClass) this else owner.enclClass
-
-    /** The next enclosing method */
-    def enclMethod: Symbol = if (isSourceMethod) this else owner.enclMethod
-
     /** The primary constructor of a class */
     def primaryConstructor: Symbol = {
       var c = info.decl(
@@ -862,24 +1095,50 @@ trait Symbols {
     /** The type of `this' in a class, or else the type of the symbol itself. */
     def typeOfThis = thisSym.tpe
 
-    /** Sets the type of `this' in a class */
-    def typeOfThis_=(tp: Type): Unit =
-      throw new Error("typeOfThis cannot be set for " + this)
-
     /** If symbol is a class, the type <code>this.type</code> in this class,
      * otherwise <code>NoPrefix</code>.
+     * We always have: thisType <:< typeOfThis
      */
     def thisType: Type = NoPrefix
 
-    /** Return every accessor of a primary constructor parameter in this case class
-      */
-    final def caseFieldAccessors: List[Symbol] =
-      info.decls.toList filter (sym => !(sym hasFlag PRIVATE) && sym.hasFlag(CASEACCESSOR))
+    /** Return every accessor of a primary constructor parameter in this case class.
+     *  The scope declarations may be out of order because fields with less than private
+     *  access are first given a regular getter, then a new renamed getter which comes
+     *  later in the declaration list.  For this reason we have to pinpoint the
+     *  right accessors by starting with the original fields (which will be in the right
+     *  order) and looking for getters with applicable names.  The getters may have the
+     *  standard name "foo" or may have been renamed to "foo$\d+" in SyntheticMethods.
+     *  See ticket #1373.
+     */
+    final def caseFieldAccessors: List[Symbol] = {
+      val allWithFlag = info.decls.toList filter (_ hasFlag CASEACCESSOR)
+      val (accessors, fields) = allWithFlag partition (_.isMethod)
+      
+      def findAccessor(field: Symbol): Symbol = {
+        // There is another renaming the field may have undergone, for instance as in
+        // ticket #2175: case class Property[T](private var t: T), t becomes Property$$t.
+        // So we use the original name everywhere.
+        val getterName    = nme.getterName(field.originalName)
+        
+        // Note this is done in two passes intentionally, to ensure we pick up the original
+        // getter if present before looking for the renamed getter.
+        def origGetter    = accessors find (_.originalName == getterName)
+        def renamedGetter = accessors find (_.originalName startsWith (getterName + "$"))
+        val accessorName  = origGetter orElse renamedGetter
+        
+        // This fails more gracefully rather than throw an Error as it used to because
+        // as seen in #2625, we can reach this point with an already erroneous tree.
+        accessorName getOrElse NoSymbol
+        // throw new Error("Could not find case accessor for %s in %s".format(field, this))
+      }
+      
+      fields map findAccessor
+    }
 
     final def constrParamAccessors: List[Symbol] =
       info.decls.toList filter (sym => !sym.isMethod && sym.hasFlag(PARAMACCESSOR))
 
-    /** The symbol accessed by this accessor function.
+    /** The symbol accessed by this accessor (getter or setter) function.
      */
     final def accessed: Symbol = {
       assert(hasFlag(ACCESSOR))
@@ -899,10 +1158,11 @@ trait Symbols {
       else owner.outerClass
 
     /** For a paramaccessor: a superclass paramaccessor for which this symbol
-     *  is an alias, NoSymbol for all others */
+     *  is an alias, NoSymbol for all others
+     */
     def alias: Symbol = NoSymbol
-
-    /** For a lazy value, it's lazy accessor. NoSymbol for all others */
+    
+    /** For a lazy value, its lazy accessor. NoSymbol for all others */
     def lazyAccessor: Symbol = NoSymbol
 
     /** For an outer accessor: The class from which the outer originates.
@@ -915,26 +1175,36 @@ trait Symbols {
 
     /** The directly or indirectly inherited mixins of this class
      *  except for mixin classes inherited by the superclass. Mixin classes appear
-     *  in linearlization order.
+     *  in linearization order.
      */
     def mixinClasses: List[Symbol] = {
       val sc = superClass
-      info.baseClasses.tail.takeWhile(sc ne)
+      ancestors takeWhile (sc ne)
     }
+    
+    /** All directly or indirectly inherited classes.
+     */
+    def ancestors: List[Symbol] = info.baseClasses drop 1
 
-    /** The package containing this symbol, or NoSymbol if there
+    /** The package class containing this symbol, or NoSymbol if there
      *  is not one. */
-    def enclosingPackage: Symbol =
+    def enclosingPackageClass: Symbol =
       if (this == NoSymbol) this else {
         var packSym = this.owner
         while ((packSym != NoSymbol)
                && !packSym.isPackageClass) 
           packSym = packSym.owner
-        if (packSym != NoSymbol)
-          packSym = packSym.linkedModuleOfClass
         packSym
       }
 
+    /** The package containing this symbol, or NoSymbol if there
+     *  is not one. */
+    def enclosingPackage: Symbol = {
+      val packSym = enclosingPackageClass
+      if (packSym != NoSymbol) packSym.companionModule
+      else packSym
+    }
+
     /** The top-level class containing this symbol */
     def toplevelClass: Symbol =
       if (owner.isPackageClass) {
@@ -951,44 +1221,106 @@ trait Symbols {
           (that.sourceFile eq null) ||
           (this.sourceFile eq that.sourceFile) ||
           (this.sourceFile == that.sourceFile)
+
+        // recognize companion object in separate file and fail, else compilation
+        // appears to succeed but highly opaque errors come later: see bug #1286
+        if (res == false) {
+          val (f1, f2) = (this.sourceFile, that.sourceFile)
+          if (f1 != null && f2 != null && f1.path != f2.path)          
+            throw FatalError("Companions '" + this + "' and '" + that + "' must be defined in same file.")
+        }
+        
         res
       }
+    
+    /** @PP: Added diagram because every time I come through here I end up
+     *       losing my train of thought.  [Renaming occurs.] This diagram is a 
+     *       bit less necessary since the renaming, but leaving in place
+     *       due to high artistic merit.
+     *
+     * class Foo  <
+     *  ^  ^ (2)   \
+     *  |  |  |     \
+     *  | (5) |     (3)
+     *  |  |  |       \
+     * (1) v  v        \
+     * object Foo (4)-> > class Foo$
+     *
+     * (1) companionClass
+     * (2) companionModule
+     * (3) linkedClassOfClass
+     * (4) moduleClass
+     * (5) companionSymbol
+     */  
 
     /** The class with the same name in the same package as this module or
-     *  case class factory
+     *  case class factory.
+     *  Note: does not work for classes owned by methods, see
+     *  Namers.companionClassOf
      */
-    final def linkedClassOfModule: Symbol = {
+    final def companionClass: Symbol = {
       if (this != NoSymbol)
-        owner.info.decl(name.toTypeName).suchThat(_ isCoDefinedWith this)
+        flatOwnerInfo.decl(name.toTypeName).suchThat(_ isCoDefinedWith this)
       else NoSymbol
     }
 
+    /** A helper method that factors the common code used the discover a companion module of a class. If a companion
+      * module exists, its symbol is returned, otherwise, `NoSymbol` is returned. The method assumes that `this`
+      * symbol has already been checked to be a class (using `isClass`). */
+    private final def companionModule0: Symbol =
+      flatOwnerInfo.decl(name.toTermName).suchThat(
+          sym => (sym hasFlag MODULE) && (sym isCoDefinedWith this))
+
     /** The module or case class factory with the same name in the same
      *  package as this class.
+     *  Note: does not work for modules owned by methods, see
+     *  Namers.companionModuleOf
      */
-    final def linkedModuleOfClass: Symbol =
-      if (this.isClass && !this.isAnonymousClass && !this.isRefinementClass) {
-        owner.rawInfo.decl(name.toTermName).suchThat(
-          sym => (sym hasFlag MODULE) && (sym isCoDefinedWith this))
-      } else NoSymbol
+    final def companionModule: Symbol =
+      if (this.isClass && !this.isAnonymousClass && !this.isRefinementClass)
+        companionModule0
+      else NoSymbol
 
     /** For a module its linked class, for a class its linked module or case
      *  factory otherwise.
+     *  Note: does not work for modules owned by methods, see
+     *  Namers.companionModuleOf / Namers.companionClassOf
      */
-    final def linkedSym: Symbol =
-      if (isTerm) linkedClassOfModule
-      else if (isClass) owner.info.decl(name.toTermName).suchThat(_ isCoDefinedWith this)
+    final def companionSymbol: Symbol =
+      if (isTerm) companionClass
+      else if (isClass)
+        companionModule0
       else NoSymbol
 
-    /** For a module class its linked class, for a plain class
-     *  the module class of its linked module.
+    /** For a module class: its linked class
+     *   For a plain class: the module class of its linked module.
+     *
+     *  Then object Foo has a `moduleClass' (invisible to the user, the backend calls it Foo$
+     *  linkedClassOfClass goes from class Foo$ to class Foo, and back.
      */
     final def linkedClassOfClass: Symbol =
-      if (isModuleClass) linkedClassOfModule else linkedModuleOfClass.moduleClass
+      if (isModuleClass) companionClass else companionModule.moduleClass
+      
+    /**
+     * Returns the rawInfo of the owner. If the current phase has flat classes, it first
+     * applies all pending type maps to this symbol.
+     *
+     * assume this is the ModuleSymbol for B in the following definition:
+     *   package p { class A { object B { val x = 1 } } }
+     *
+     * The owner after flatten is "package p" (see "def owner"). The flatten type map enters
+     * symbol B in the decls of p. So to find a linked symbol ("object B" or "class B")
+     * we need to apply flatten to B first. Fixes #2470.
+     */
+    private final def flatOwnerInfo: Type = {
+      if (phase.flatClasses && rawowner != NoSymbol && !rawowner.isPackageClass)
+        info
+      owner.rawInfo
+    }
 
     /** If this symbol is an implementation class, its interface, otherwise the symbol itself
      *  The method follows two strategies to determine the interface.
-     *   - during or after erasure, it takes the last parent of the implementatation class
+     *   - during or after erasure, it takes the last parent of the implementation class
      *     (which is always the interface, by convention)
      *   - before erasure, it looks up the interface name in the scope of the owner of the class.
      *     This only works for implementation classes owned by other classes or traits.
@@ -1006,11 +1338,6 @@ trait Symbols {
         result
       } else this
 
-    /** The module corresponding to this module class (note that this
-     *  is not updated when a module is cloned).
-     */
-    def sourceModule: Symbol = NoSymbol
-
     /** The module class corresponding to this module.
      */
     def moduleClass: Symbol = NoSymbol
@@ -1027,31 +1354,32 @@ trait Symbols {
 
     /** The non-private member of `site' whose type and name match the type of this symbol
      */
-    final def matchingSymbol(site: Type): Symbol =
-      site.nonPrivateMember(name).filter(sym =>
+    final def matchingSymbol(site: Type, admit: Long = 0L): Symbol =
+      site.nonPrivateMemberAdmitting(name, admit).filter(sym =>
         !sym.isTerm || (site.memberType(this) matches site.memberType(sym)))
 
-    /** The symbol overridden by this symbol in given class `ofclazz' */
+    /** The symbol overridden by this symbol in given class `ofclazz'.
+     *  @pre 'ofclazz' is a base class of this symbol's owner.
+     */
     final def overriddenSymbol(ofclazz: Symbol): Symbol =
       if (isClassConstructor) NoSymbol else matchingSymbol(ofclazz, owner.thisType)
 
-    /** The symbol overriding this symbol in given subclass `ofclazz' */
+    /** The symbol overriding this symbol in given subclass `ofclazz'
+     *  @pre: `ofclazz' is a subclass of this symbol's owner
+     */
     final def overridingSymbol(ofclazz: Symbol): Symbol =
       if (isClassConstructor) NoSymbol else matchingSymbol(ofclazz, ofclazz.thisType)
 
     final def allOverriddenSymbols: List[Symbol] =
-      if (owner.isClass && !owner.info.baseClasses.isEmpty)
-        for { bc <- owner.info.baseClasses.tail
-              val s = overriddenSymbol(bc)
-              if s != NoSymbol } yield s
-      else List()
+      if (!owner.isClass) Nil
+      else owner.ancestors map overriddenSymbol filter (_ != NoSymbol)
 
     /** The virtual classes overridden by this virtual class (excluding `clazz' itself)
      *  Classes appear in linearization order (with superclasses before subclasses)
      */
     final def overriddenVirtuals: List[Symbol] = 
       if (isVirtualTrait && hasFlag(OVERRIDE))
-        this.owner.info.baseClasses.tail 
+        this.owner.ancestors 
           .map(_.info.decl(name)) 
           .filter(_.isVirtualTrait)
           .reverse
@@ -1085,7 +1413,7 @@ trait Symbols {
 
     final def setter(base: Symbol, hasExpandedName: Boolean): Symbol = {
       var sname = nme.getterToSetter(nme.getterName(name))
-      if (hasExpandedName) sname = base.expandedSetterName(sname)
+      if (hasExpandedName) sname = nme.expandedSetterName(sname, base)
       base.info.decl(sname) filter (_.hasFlag(ACCESSOR))
     }
 
@@ -1095,7 +1423,7 @@ trait Symbols {
     final def caseModule: Symbol = {
       var modname = name.toTermName
       if (privateWithin.isClass && !privateWithin.isModuleClass && !hasFlag(EXPANDEDNAME))
-        modname = privateWithin.expandedName(modname)
+        modname = nme.expandedName(modname, privateWithin)
       initialize.owner.info.decl(modname).suchThat(_.isModule)
     }
 
@@ -1113,7 +1441,7 @@ trait Symbols {
     final def makeNotPrivate(base: Symbol) {
       if (this hasFlag PRIVATE) {
         setFlag(notPRIVATE)
-        if (isTerm && !isDeferred) setFlag(lateFINAL)
+        if (isMethod && !isDeferred) setFlag(lateFINAL)
         if (!isStaticModule && !isClassConstructor) {
           expandName(base)
           if (isModule) moduleClass.makeNotPrivate(base)
@@ -1133,53 +1461,46 @@ trait Symbols {
           getter(owner).expandName(base)
           setter(owner).expandName(base)
         }
-        name = base.expandedName(name)
+        name = nme.expandedName(name, base)
         if (isType) name = name.toTypeName
       }
     }
 
-    def expandedSetterName(simpleSetterName: Name): Name =
-      newTermName(fullNameString('$') + nme.TRAIT_SETTER_SEPARATOR_STRING + simpleSetterName)
-
-    /** The expanded name of `name' relative to this class as base
-     */
-    def expandedName(name: Name): Name = {
-        newTermName(fullNameString('$') + nme.EXPAND_SEPARATOR_STRING + name)
-    }
-
-    def sourceFile: AbstractFile = {
-      var ret = (if (isModule) moduleClass else toplevelClass).sourceFile
-      if (ret == null && inIDE && !isModule) this match {
-        case sym : ModuleSymbol if sym.referenced != null =>
-          ret = sym.referenced.sourceFile
-        case _ => 
-      }
-      ret
-    }
+    def sourceFile: AbstractFile =
+      (if (isModule) moduleClass else toplevelClass).sourceFile
 
     def sourceFile_=(f: AbstractFile) {
-      throw new Error("sourceFile_= inapplicable for " + this)
+      abort("sourceFile_= inapplicable for " + this)
     }
 
     def isFromClassFile: Boolean =
       (if (isModule) moduleClass else toplevelClass).isFromClassFile
 
     /** If this is a sealed class, its known direct subclasses. Otherwise Set.empty */
-    def children: Set[Symbol] = emptySymbolSet
-
-    /** Declare given subclass `sym' of this sealed class */
-    def addChild(sym: Symbol) {
-      throw new Error("addChild inapplicable for " + this)
-    }
+    def children: List[Symbol] = Nil
+    
+    /** Recursively finds all sealed descendants and returns a sorted list. */
+    def sealedDescendants: List[Symbol] = {
+      val kids = children flatMap (_.sealedDescendants)
+      val all = if (this hasFlag ABSTRACT) kids else this :: kids
       
+      all.distinct sortBy (_.sealedSortName)
+    }
 
 // ToString -------------------------------------------------------------------
 
     /** A tag which (in the ideal case) uniquely identifies class symbols */
-    final def tag: Int = fullNameString.hashCode()
+    final def tag: Int = fullName.hashCode()
 
     /** The simple name of this Symbol */
     final def simpleName: Name = name
+    
+    /** The String used to order otherwise identical sealed symbols.
+     *  This uses data which is stable across runs and variable classpaths
+     *  (the initial Name) before falling back on id, which varies depending
+     *  on exactly when a symbol is loaded.
+     */
+    final def sealedSortName: String = initName.toString + "#" + id
 
     /** String representation of symbol's definition key word */
     final def keyString: String =
@@ -1190,7 +1511,7 @@ trait Symbols {
       else if (isVariable) "var"
       else if (isPackage) "package"
       else if (isModule) "object"
-      else if (isMethod) "def"
+      else if (isSourceMethod) "def"
       else if (isTerm && (!hasFlag(PARAM) || hasFlag(PARAMACCESSOR))) "val"
       else ""
 
@@ -1200,7 +1521,7 @@ trait Symbols {
         if (settings.debug.value) "package class" else "package"
       else if (isModuleClass) 
         if (settings.debug.value) "singleton class" else "object"
-      else if (isAnonymousClass) "template"
+      else if (isAnonymousClass) "anonymous class"
       else if (isRefinementClass) ""
       else if (isTrait) "trait"
       else if (isClass) "class"
@@ -1219,35 +1540,16 @@ trait Symbols {
      *  E.g. $eq => =.
      *  If settings.uniquId adds id.
      */
-    def nameString: String = {
-      var s = simpleName.decode
-      if (s endsWith nme.LOCAL_SUFFIX) 
-        s = s.substring(0, s.length - nme.LOCAL_SUFFIX.length)
-      s + idString
-    }
+    def nameString: String = decodedName + idString
 
-    /** String representation of symbol's full name with <code>separator</code>
-     *  between class names.
-     *  Never translates expansions of operators back to operator symbol.
-     *  Never adds id.
+    /** The name of the symbol before decoding, e.g. `$eq$eq` instead of `==`.
      */
-    final def fullNameString(separator: Char): String = {
-      if (this == NoSymbol) return "<NoSymbol>"
-      assert(owner != NoSymbol, this)
-      var str =
-        if (owner.isRoot || 
-            owner.isEmptyPackageClass || 
-            owner.isInterpreterWrapper) simpleName.toString
-        else owner.enclClass.fullNameString(separator) + separator + simpleName
-      if (str.charAt(str.length - 1) == ' ') str = str.substring(0, str.length - 1)
-      str
-    }
-
-    final def fullNameString: String = fullNameString('.')
-
+    def encodedName: String = name.toString
+    
     /** If settings.uniqid is set, the symbol's id, else "" */
     final def idString: String =
-      if (settings.uniqid.value) "#"+id else ""
+      if (settings.uniqid.value) "#"+id // +" in "+owner.name+"#"+owner.id // DEBUG
+      else ""
 
     /** String representation, including symbol's kind
      *  e.g., "class Foo", "method Bar".
@@ -1255,12 +1557,20 @@ trait Symbols {
     override def toString(): String =
       if (isValueParameter && owner.isSetter)
         "parameter of setter "+owner.nameString
+      else if (isPackageObject || isPackageObjectClass)
+        "package object "+owner.nameString
       else 
         compose(List(kindString, 
                      if (isClassConstructor) owner.simpleName.decode+idString else nameString))
 
+    /** If owner is a package object, its owner, else the normal owner.
+     */
+    def ownerSkipPackageObject = 
+      if (owner.isPackageObjectClass) owner.owner else owner
+
     /** String representation of location. */
-    def locationString: String =
+    def locationString: String = {
+      val owner = ownerSkipPackageObject
       if (owner.isClass &&
           ((!owner.isAnonymousClass && 
             !owner.isRefinementClass && 
@@ -1268,6 +1578,7 @@ trait Symbols {
             !owner.isRoot &&
             !owner.isEmptyPackageClass) || settings.debug.value))
         " in " + owner else ""
+    }
 
     /** String representation of symbol's definition following its name */
     final def infoString(tp: Type): String = {
@@ -1297,8 +1608,8 @@ trait Symbols {
         tp match {
           case PolyType(tparams, res) =>
             typeParamsString + infoString(res)
-          case MethodType(pts, res) =>
-            pts.mkString("(", ",", ")") + infoString(res)
+          case MethodType(params, res) =>
+           params.map(_.defString).mkString("(", ",", ")") + infoString(res)
           case _ =>
             ": " + tp
         }
@@ -1341,35 +1652,33 @@ trait Symbols {
   extends Symbol(initOwner, initPos, initName) {
     override def isTerm = true
 
-/*
-    val marker = initName.toString match {
-      case "forCLDC" => new MarkForCLDC
-      case _ => null
-    }
-*/
     privateWithin = NoSymbol
 
     protected var referenced: Symbol = NoSymbol
 
-    def cloneSymbolImpl(owner: Symbol): Symbol = {
-      val clone = new TermSymbol(owner, pos, name)
-      clone.referenced = referenced
-      clone
+    def cloneSymbolImpl(owner: Symbol): Symbol = 
+      new TermSymbol(owner, pos, name).copyAttrsFrom(this)
+
+    def copyAttrsFrom(original: TermSymbol): this.type = {
+      referenced = original.referenced
+      this
     }
 
+    private val validAliasFlags = SUPERACCESSOR | PARAMACCESSOR | MIXEDIN | SPECIALIZED
+    
     override def alias: Symbol =
-      if (hasFlag(SUPERACCESSOR | PARAMACCESSOR | MIXEDIN)) initialize.referenced
+      if (hasFlag(validAliasFlags)) initialize.referenced
       else NoSymbol
 
     def setAlias(alias: Symbol): TermSymbol = {
       assert(alias != NoSymbol, this)
       assert(!(alias hasFlag OVERLOADED), alias)
 
-      assert(hasFlag(SUPERACCESSOR | PARAMACCESSOR | MIXEDIN), this)
+      assert(hasFlag(validAliasFlags), this)
       referenced = alias
       this
     }
-
+    
     override def outerSource: Symbol = 
       if (name endsWith nme.OUTER) initialize.referenced
       else NoSymbol
@@ -1384,14 +1693,8 @@ trait Symbols {
     }
     
     def setLazyAccessor(sym: Symbol): TermSymbol = {
-      // @S: in IDE setLazyAccessor can be called multiple times on same sym
-      if (inIDE && referenced != NoSymbol && referenced != sym) {
-        // do nothing
-        recycle(referenced)
-      } else {
-        assert(hasFlag(LAZY) && (referenced == NoSymbol || referenced == sym), this)
-        referenced = sym
-      }
+      assert(hasFlag(LAZY) && (referenced == NoSymbol || referenced == sym), this)
+      referenced = sym
       this
     }
     
@@ -1399,12 +1702,41 @@ trait Symbols {
       assert(hasFlag(LAZY), this)
       referenced
     }
+
+    protected def doCookJavaRawInfo() {
+      def cook(sym: Symbol) {
+        require(sym hasFlag JAVA)
+        // @M: I think this is more desirable, but Martin prefers to leave raw-types as-is as much as possible
+        // object rawToExistentialInJava extends TypeMap {
+        //   def apply(tp: Type): Type = tp match {
+        //     // any symbol that occurs in a java sig, not just java symbols
+        //     // see http://lampsvn.epfl.ch/trac/scala/ticket/2454#comment:14
+        //     case TypeRef(pre, sym, List()) if !sym.typeParams.isEmpty =>
+        //       val eparams = typeParamsToExistentials(sym, sym.typeParams)
+        //       existentialAbstraction(eparams, TypeRef(pre, sym, eparams map (_.tpe)))
+        //     case _ =>
+        //       mapOver(tp)
+        //   }
+        // }
+        val tpe1 = rawToExistential(sym.tpe)
+        // println("cooking: "+ sym +": "+ sym.tpe +" to "+ tpe1)
+        if (tpe1 ne sym.tpe) {
+          sym.setInfo(tpe1)
+        }
+      }
+
+      if (hasFlag(JAVA))
+        cook(this)
+      else if (hasFlag(OVERLOADED))
+        for (sym2 <- alternatives)
+          if (sym2 hasFlag JAVA)
+            cook(sym2)
+    }    
   }
 
   /** A class for module symbols */
   class ModuleSymbol(initOwner: Symbol, initPos: Position, initName: Name)
   extends TermSymbol(initOwner, initPos, initName) {
-
     private var flatname = nme.EMPTY
 
     override def owner: Symbol =
@@ -1416,16 +1748,41 @@ trait Symbols {
       if (phase.flatClasses && !hasFlag(METHOD) &&
           rawowner != NoSymbol && !rawowner.isPackageClass) {
         if (flatname == nme.EMPTY) {
-          assert(rawowner.isClass)
+          assert(rawowner.isClass, "fatal: %s has owner %s, but a class owner is required".format(rawname, rawowner))
           flatname = newTermName(compactify(rawowner.name.toString() + "$" + rawname))
         }
         flatname
       } else rawname
 
-    override def cloneSymbolImpl(owner: Symbol): Symbol = {
-      val clone = new ModuleSymbol(owner, pos, name)
-      clone.referenced = referenced
-      clone
+    override def cloneSymbolImpl(owner: Symbol): Symbol = 
+      new ModuleSymbol(owner, pos, name).copyAttrsFrom(this)
+  }
+
+  /** A class for method symbols */
+  class MethodSymbol(initOwner: Symbol, initPos: Position, initName: Name)
+  extends TermSymbol(initOwner, initPos, initName) {
+
+    private var mtpePeriod = NoPeriod
+    private var mtpePre: Type = _
+    private var mtpeResult: Type = _
+    private var mtpeInfo: Type = _
+
+    override def cloneSymbolImpl(owner: Symbol): Symbol = 
+      new MethodSymbol(owner, pos, name).copyAttrsFrom(this)
+
+    def typeAsMemberOf(pre: Type): Type = {
+      if (mtpePeriod == currentPeriod) {
+        if ((mtpePre eq pre) && (mtpeInfo eq info)) return mtpeResult
+      } else if (isValid(mtpePeriod)) {
+        mtpePeriod = currentPeriod
+        if ((mtpePre eq pre) && (mtpeInfo eq info)) return mtpeResult
+      }
+      val res = pre.computeMemberType(this)
+      mtpePeriod = currentPeriod
+      mtpePre = pre
+      mtpeInfo = info
+      mtpeResult = res
+      res
     }
   }
 
@@ -1441,10 +1798,19 @@ trait Symbols {
     private var tpePeriod = NoPeriod
 
     override def isType = true
-    override def isTypeMember = true
+    override def isNonClassType = true
     override def isAbstractType = isDeferred
     override def isAliasType = !isDeferred
 
+    /** Let's say you have a type definition
+     *
+     *    type T <: Number
+     *
+     *  and tsym is the symbol corresponding to T. Then
+     *
+     *    tsym.info = TypeBounds(Nothing, Number)
+     *    tsym.tpe  = TypeRef(NoPrefix, T, List())
+     */
     override def tpe: Type = {
       if (tpeCache eq NoType) throw CyclicReference(this, typeConstructor)
       if (tpePeriod != currentPeriod) {
@@ -1466,6 +1832,9 @@ trait Symbols {
       tpeCache
     }
 
+    // needed for experimental code for early types as type parameters
+    // def refreshType() { tpePeriod = NoPeriod }
+
     override def typeConstructor: Type = {
       if ((tyconCache eq null) || tyconRunId != currentRunId) {
         tyconCache = typeRef(if (hasFlag(PARAM | EXISTENTIAL)) NoPrefix else owner.thisType, 
@@ -1476,7 +1845,7 @@ trait Symbols {
       tyconCache
     }
 
-    override def setInfo(tp: Type): this.type = {
+    override def info_=(tp: Type) {
       tpePeriod = NoPeriod
       tyconCache = null
       if (tp.isComplete)
@@ -1485,8 +1854,7 @@ trait Symbols {
           case NoType | AnnotatedType(_, _, _) => ;
           case _ => setFlag(MONOMORPHIC)
         }
-      super.setInfo(tp)
-      this
+      super.info_=(tp)
     }
 
     override def reset(completer: Type) {
@@ -1495,13 +1863,39 @@ trait Symbols {
       tyconRunId = NoRunId
     }
 
+    /*** example:
+     * public class Test3<T> {}
+     * public class Test1<T extends Test3> {}
+     * info for T in Test1 should be >: Nothing <: Test3[_]
+     */
+    protected def doCookJavaRawInfo() {
+      // don't require hasFlag(JAVA), since T in the above example does not have that flag
+      val tpe1 = rawToExistential(info)
+      // println("cooking type: "+ this +": "+ info +" to "+ tpe1)
+      if (tpe1 ne info) {
+        setInfo(tpe1)
+      }
+    }
+    
     def cloneSymbolImpl(owner: Symbol): Symbol =
       new TypeSymbol(owner, pos, name)
 
-    if (util.Statistics.enabled) typeSymbolCount = typeSymbolCount + 1
+    incCounter(typeSymbolCount)
   }
 
-  /** A class for type parameters viewed from inside their scopes */
+  /** A class for type parameters viewed from inside their scopes
+   *
+   *  @param origin  Can be either a tree, or a symbol, or null.
+   *  If skolem got created from newTypeSkolem (called in Namers), origin denotes
+   *  the type parameter from which the skolem was created. If it got created from
+   *  skolemizeExistential, origin is either null or a Tree. If it is a Tree, it indicates
+   *  where the skolem was introduced (this is important for knowing when to pack it
+   *  again into ab Existential). origin is `null' only in skolemizeExistentials called
+   *  from <:< or isAsSpecific, because here its value does not matter.
+   *  I elieve the following invariant holds:
+   * 
+   *     origin.isInstanceOf[Symbol] == !hasFlag(EXISTENTIAL)
+   */
   class TypeSkolem(initOwner: Symbol, initPos: Position,
                    initName: Name, origin: AnyRef)
   extends TypeSymbol(initOwner, initPos, initName) {
@@ -1510,15 +1904,21 @@ trait Symbols {
     val level = skolemizationLevel
 
     override def isSkolem = true
+
+    /** If typeskolem comes from a type parameter, that parameter, otherwise skolem itself */
     override def deSkolemize = origin match {
       case s: Symbol => s
       case _ => this
     }
+
+    /** If type skolem comes from an existential, the tree where it was created */
     override def unpackLocation = origin
+
     override def typeParams = info.typeParams //@M! (not deSkolemize.typeParams!!), also can't leave superclass definition: use info, not rawInfo
-    override def cloneSymbolImpl(owner: Symbol): Symbol = {
-      throw new Error("should not clone a type skolem")
-    }
+
+    override def cloneSymbolImpl(owner: Symbol): Symbol =
+      new TypeSkolem(owner, pos, name, origin)
+
     override def nameString: String = 
       if (settings.debug.value) (super.nameString + "&" + level)
       else super.nameString
@@ -1537,7 +1937,6 @@ trait Symbols {
       if (owner.isPackageClass) source else super.sourceFile
     override def sourceFile_=(f: AbstractFile) {
       //System.err.println("set source file of " + this + ": " + f);
-      attachSource(this, f)
       source = f
     }
     override def isFromClassFile = {
@@ -1548,7 +1947,7 @@ trait Symbols {
     private var thissym: Symbol = this
 
     override def isClass: Boolean = true
-    override def isTypeMember = false
+    override def isNonClassType = false
     override def isAbstractType = false
     override def isAliasType = false
 
@@ -1564,11 +1963,11 @@ trait Symbols {
       else rawowner
 
     override def name: Name =
-      if ((rawflags & notDEFERRED) != 0 && phase.devirtualized && !phase.erasedTypes) {
+      if ((rawflags & notDEFERRED) != 0L && phase.devirtualized && !phase.erasedTypes) {
         newTypeName(rawname+"$trait") // (part of DEVIRTUALIZE)
       } else if (phase.flatClasses && rawowner != NoSymbol && !rawowner.isPackageClass) {
         if (flatname == nme.EMPTY) {
-          assert(rawowner.isClass)
+          assert(rawowner.isClass, "fatal: %s has owner %s, but a class owner is required".format(rawname+idString, rawowner))
           flatname = newTypeName(compactify(rawowner.name.toString() + "$" + rawname))
         }
         flatname
@@ -1582,7 +1981,7 @@ trait Symbols {
       val period = thisTypePeriod
       if (period != currentPeriod) {
         thisTypePeriod = currentPeriod
-        if (!isValid(period)) thisTypeCache = mkThisType(this)
+        if (!isValid(period)) thisTypeCache = ThisType(this)
       }
       thisTypeCache
     }
@@ -1590,8 +1989,10 @@ trait Symbols {
     /** A symbol carrying the self type of the class as its type */
     override def thisSym: Symbol = thissym
 
+    /** the self type of an object foo is foo.type, not class<foo>.this.type
+     */
     override def typeOfThis: Type =
-      if (getFlag(MODULE | IMPLCLASS) == MODULE && owner != NoSymbol)
+      if (getFlag(MODULE | IMPLCLASS) == MODULE.toLong && owner != NoSymbol)
         singleType(owner.thisType, sourceModule)
       else thissym.tpe
 
@@ -1601,7 +2002,6 @@ trait Symbols {
     }
 
     override def cloneSymbolImpl(owner: Symbol): Symbol = {
-      assert(!isModuleClass)
       val clone = new ClassSymbol(owner, pos, name)
       if (thisSym != this) {
         clone.typeOfThis = typeOfThis
@@ -1611,13 +2011,13 @@ trait Symbols {
     }
 
     override def sourceModule =
-      if (isModuleClass) linkedModuleOfClass else NoSymbol
+      if (isModuleClass) companionModule else NoSymbol
 
-    private var childSet: Set[Symbol] = emptySymbolSet
-    override def children: Set[Symbol] = childSet
+    private var childSet: Set[Symbol] = Set()
+    override def children: List[Symbol] = childSet.toList sortBy (_.sealedSortName)
     override def addChild(sym: Symbol) { childSet = childSet + sym }
 
-    if (util.Statistics.enabled) classSymbolCount = classSymbolCount + 1
+    incCounter(classSymbolCount)
   }
 
   /** A class for module class symbols
@@ -1630,38 +2030,41 @@ trait Symbols {
     def this(module: TermSymbol) = {
       this(module.owner, module.pos, module.name.toTypeName)
       setFlag(module.getFlag(ModuleToClassFlags) | MODULE | FINAL)
-      setSourceModule(module)
+      sourceModule = module
     }
     override def sourceModule = module
-    def setSourceModule(module: Symbol) { this.module = module }
+    lazy val implicitMembers = info.implicitMembers
+    override def sourceModule_=(module: Symbol) { this.module = module }
   }
 
-  /** An object repreesenting a missing symbol */
+  /** An object representing a missing symbol */
   object NoSymbol extends Symbol(null, NoPosition, nme.NOSYMBOL) {
     setInfo(NoType)
     privateWithin = this
-    override def setInfo(info: Type): this.type = {
+    override def info_=(info: Type) {
       infos = TypeHistory(1, NoType, null)
       unlock()
       validTo = currentPeriod
-      this
     }
     override def defString: String = toString
     override def locationString: String = ""
     override def enclClass: Symbol = this
     override def toplevelClass: Symbol = this
     override def enclMethod: Symbol = this
-    override def owner: Symbol = throw new Error("no-symbol does not have owner")
+    override def owner: Symbol = abort("no-symbol does not have owner")
     override def sourceFile: AbstractFile = null
     override def ownerChain: List[Symbol] = List()
+    override def ownersIterator: Iterator[Symbol] = Iterator.empty
     override def alternatives: List[Symbol] = List()
     override def reset(completer: Type) {}
     override def info: Type = NoType
     override def rawInfo: Type = NoType
+    protected def doCookJavaRawInfo() {}
     override def accessBoundary(base: Symbol): Symbol = RootClass
-    def cloneSymbolImpl(owner: Symbol): Symbol = throw new Error()
+    def cloneSymbolImpl(owner: Symbol): Symbol = abort()
   }
 
+
   def cloneSymbols(syms: List[Symbol]): List[Symbol] = {
     val syms1 = syms map (_.cloneSymbol)
     for (sym1 <- syms1) sym1.setInfo(sym1.info.substSym(syms, syms1))
@@ -1676,7 +2079,9 @@ trait Symbols {
 
   /** An exception for cyclic references of symbol definitions */
   case class CyclicReference(sym: Symbol, info: Type)
-  extends TypeError("illegal cyclic reference involving " + sym)
+  extends TypeError("illegal cyclic reference involving " + sym) {
+    // printStackTrace() // debug
+  }
 
   /** A class for type histories */
   private sealed case class TypeHistory(var validFrom: Period, info: Type, prev: TypeHistory) {
@@ -1685,17 +2090,4 @@ trait Symbols {
     override def toString() =
       "TypeHistory(" + phaseOf(validFrom)+":"+runId(validFrom) + "," + info + "," + prev + ")"
   }
-/*
-  var occs = 0
-
-class MarkForCLDC {
-  val atRun: Int = currentRunId
-  occs += 1
-  println("new "+getClass+" at "+atRun+" ("+occs+" total)")
-  override def finalize() {
-    occs -=1 
-    println("drop "+getClass+" from "+atRun+" ("+occs+" total)")
-  }
-}
-*/
 }
diff --git a/src/compiler/scala/tools/nsc/symtab/Types.scala b/src/compiler/scala/tools/nsc/symtab/Types.scala
index 0c670f9..fed8ccd 100644
--- a/src/compiler/scala/tools/nsc/symtab/Types.scala
+++ b/src/compiler/scala/tools/nsc/symtab/Types.scala
@@ -1,18 +1,19 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
 // 
 
-package scala.tools.nsc.symtab
+package scala.tools.nsc
+package symtab
 
 import scala.collection.immutable
-import scala.collection.mutable.{ListBuffer, HashMap}
-import scala.compat.Platform.currentTime
-import scala.tools.nsc.ast.TreeGen
-import scala.tools.nsc.util.{HashSet, Position, NoPosition}
-import scala.collection.jcl.WeakHashMap
+import scala.collection.mutable.{ListBuffer, HashMap, WeakHashMap}
+import ast.TreeGen
+import util.{HashSet, Position, NoPosition}
+import util.Statistics._
 import Flags._
+import scala.util.control.ControlThrowable
  
 /* A standard type pattern match:
   case ErrorType =>
@@ -31,8 +32,8 @@ import Flags._
     // pre.sym[targs]
   case RefinedType(parents, defs) =>
     // parent1 with ... with parentn { defs }
-  case AnnotatedType(attribs, tp, selfsym) =>
-    // tp @attribs
+  case AnnotatedType(annots, tp, selfsym) =>
+    // tp @annots
 
   // the following are non-value types; you cannot write them down in Scala source.
 
@@ -59,27 +60,20 @@ import Flags._
   case DeBruijnIndex(level, index)
 */
 
-trait Types { 
-  self: SymbolTable =>
+trait Types extends reflect.generic.Types { self: SymbolTable =>
   import definitions._
   
   
   //statistics
-  var singletonBaseTypeSeqCount = 0
-  var compoundBaseTypeSeqCount = 0
-  var typerefBaseTypeSeqCount = 0
-  var findMemberCount = 0
-  var noMemberCount = 0
-  var multMemberCount = 0
-  var findMemberMillis = 0l
-  var subtypeCount = 0
-  var subtypeMillis = 0l
+  def uniqueTypeCount = if (uniques == null) 0 else uniques.size
 
   private var explainSwitch = false
-  private var checkMalformedSwitch = false // todo: it's now always false. Remove all code that depends on this switch.
+
+  private final val alternativeNarrow = false
 
   private final val LogPendingSubTypesThreshold = 50
   private final val LogPendingBaseTypesThreshold = 50
+  private final val LogVolatileThreshold = 50
 
   /** A don't care value for the depth parameter in lubs/glbs and related operations */
   private final val AnyDepth = -3
@@ -97,15 +91,53 @@ trait Types {
   /** A log of type variable with their original constraints. Used in order
    *  to undo constraints in the case of isSubType/isSameType failure.
    */
-  type UndoLog = List[(TypeVar, TypeConstraint)]
-  var undoLog: UndoLog = List()
+  object undoLog {
+    private type UndoLog = List[(TypeVar, TypeConstraint)]
+    private var log: UndoLog = List()
+
+    /** Undo all changes to constraints to type variables upto `limit'
+     */
+    private def undoTo(limit: UndoLog) {
+      while ((log ne limit) && log.nonEmpty) {
+        val (tv, constr) = log.head
+        tv.constr = constr
+        log = log.tail
+      }
+    }
+
+    private[Types] def record(tv: TypeVar) = {log = (tv, tv.constr.cloneInternal) :: log}
+    private[Types] def clear {log = List()}
+
+    // `block` should not affect constraints on typevars
+    def undo[T](block: => T): T = {
+      val before = log
+      val result = try {
+        block
+      } finally {
+        undoTo(before)
+      }
+      result
+    }
+
+    // if `block` evaluates to false, it should not affect constraints on typevars
+    def undoUnless(block: => Boolean): Boolean = {
+      val before = log
+      var result = false
+      try {
+        result = block
+      } finally {
+        if(!result) undoTo(before)
+      }
+      result
+    }
+  }
 
   /** A map from lists to compound types that have the given list as parents.
    *  This is used to avoid duplication in the computation of base type sequences and baseClasses.
    *  It makes use of the fact that these two operations depend only on the parents,
    *  not on the refinement.
    */
-  var intersectionWitness = new WeakHashMap[List[Type], Type]
+  val intersectionWitness = new WeakHashMap[List[Type], Type]
 
   private object gen extends {
     val global : Types.this.type = Types.this
@@ -115,15 +147,15 @@ trait Types {
 
   // @M toString that is safe during debugging (does not normalize, ...)
   def debugString(tp: Type): String = tp match { 
-    case TypeRef(pre, sym, args) => "TypeRef"+(debugString(pre), sym, args map debugString) 
-    case ThisType(sym) => "ThisType("+sym+")"
-    case SingleType(pre, sym) => "SingleType"+(debugString(pre), sym)
-    case RefinedType(parents, defs) => "RefinedType"+(parents map debugString, defs.toList)
-    case ClassInfoType(parents, defs, clazz) =>  "ClassInfoType"+(parents map debugString, defs.toList, clazz)
-    case PolyType(tparams, result) => "PolyType"+(tparams, debugString(result))
-    case TypeBounds(lo, hi) => "TypeBounds "+debugString(lo)+","+debugString(hi)
-    case TypeVar(origin, constr) => "TypeVar "+origin+","+constr
-    case ExistentialType(tparams, qtpe) => "ExistentialType("+(tparams map (_.defString))+","+debugString(qtpe)+")"
+    case TypeRef(pre, sym, args) =>  debugString(pre) +"."+ sym.nameString + (args map debugString).mkString("[",", ","]") 
+    case ThisType(sym) => sym.nameString+".this"
+    case SingleType(pre, sym) => debugString(pre) +"."+ sym.nameString +".type"
+    case RefinedType(parents, defs) => (parents map debugString).mkString("", " with ", "") + defs.toList.mkString(" {", " ;\n ", "}") 
+    case ClassInfoType(parents, defs, clazz) =>  "class "+ clazz.nameString + (parents map debugString).mkString("", " with ", "") + defs.toList.mkString("{", " ;\n ", "}") 
+    case PolyType(tparams, result) => tparams.mkString("[", ", ", "] ") + debugString(result)
+    case TypeBounds(lo, hi) => ">: "+ debugString(lo) +" <: "+ debugString(hi)
+    case tv : TypeVar => tv.toString
+    case ExistentialType(tparams, qtpe) => "forsome "+ tparams.mkString("[", ", ", "] ") + debugString(qtpe)
     case _ => tp.toString
   }
 
@@ -139,6 +171,7 @@ trait Types {
     // Important to keep this up-to-date when new operations are added!
     override def isTrivial = underlying.isTrivial
     override def isHigherKinded: Boolean = underlying.isHigherKinded
+    override def typeConstructor: Type = underlying.typeConstructor 
     override def isNotNull = underlying.isNotNull
     override def isError = underlying.isError
     override def isErroneous = underlying.isErroneous
@@ -146,6 +179,8 @@ trait Types {
     override def isVolatile = underlying.isVolatile
     override def finalResultType = underlying.finalResultType
     override def paramSectionCount = underlying.paramSectionCount
+    override def paramss = underlying.paramss
+    override def params = underlying.params
     override def paramTypes = underlying.paramTypes
     override def termSymbol = underlying.termSymbol
     override def termSymbolDirect = underlying.termSymbolDirect
@@ -167,7 +202,7 @@ trait Types {
 
   /** A proxy for a type (identified by field `underlying') that forwards most 
    *  operations to it. Every operation that is overridden for some kind of types is
-   *  forwarded here. Some opererations are rewrapped again.
+   *  forwarded here. Some operations are rewrapped again.
    */
   trait RewrappingTypeProxy extends SimpleTypeProxy {
     protected def maybeRewrap(newtp: Type) = if (newtp eq underlying) this else rewrap(newtp)
@@ -182,23 +217,27 @@ trait Types {
     override def resultType(actuals: List[Type]) = maybeRewrap(underlying.resultType(actuals))
     override def finalResultType = maybeRewrap(underlying.finalResultType)
     override def paramSectionCount = 0
+    override def paramss: List[List[Symbol]] = List()
+    override def params: List[Symbol] = List()
     override def paramTypes: List[Type] = List()
     override def typeArgs = underlying.typeArgs
     override def notNull = maybeRewrap(underlying.notNull)
     override def instantiateTypeParams(formals: List[Symbol], actuals: List[Type]) = underlying.instantiateTypeParams(formals, actuals)
     override def skolemizeExistential(owner: Symbol, origin: AnyRef) = underlying.skolemizeExistential(owner, origin)
     override def normalize = maybeRewrap(underlying.normalize)
+    override def dealias = maybeRewrap(underlying.dealias)
     override def cloneInfo(owner: Symbol) = maybeRewrap(underlying.cloneInfo(owner))
+    override def atOwner(owner: Symbol) = maybeRewrap(underlying.atOwner(owner))
     override def prefixString = underlying.prefixString
     override def isComplete = underlying.isComplete
     override def complete(sym: Symbol) = underlying.complete(sym)
     override def load(sym: Symbol) { underlying.load(sym) }
-    override def withAttributes(attribs: List[AnnotationInfo]) = maybeRewrap(underlying.withAttributes(attribs))
-    override def withoutAttributes = maybeRewrap(underlying.withoutAttributes)
+    override def withAnnotations(annots: List[AnnotationInfo]) = maybeRewrap(underlying.withAnnotations(annots))
+    override def withoutAnnotations = maybeRewrap(underlying.withoutAnnotations)
   }
 
   /** The base class for all types */
-  abstract class Type {
+  abstract class Type extends AbsType {
     
     /** Types for which asSeenFrom always is the identity, no matter what
      *  prefix or owner.
@@ -222,9 +261,20 @@ trait Types {
     /** Is this type guaranteed not to have `null' as a value? */
     def isNotNull: Boolean = false
 
+    /** Is this type a structural refinement type (it 'refines' members that have not been inherited) */
+    def isStructuralRefinement: Boolean = false
+
+    /** Does this type depend immediately on an enclosing method parameter? 
+      * i.e., is it a singleton type whose termSymbol refers to an argument of the symbol's owner (which is a method)
+      */
+    def isImmediatelyDependent: Boolean = false
+
     /** Does this depend on an enclosing method parameter? */
     def isDependent: Boolean = IsDependentCollector.collect(this)
- 
+
+    /** True for WildcardType or BoundedWildcardType */
+    def isWildcard = false
+
     /** The term symbol associated with the type
       * Note that the symbol of the normalized type is returned (@see normalize)
       */
@@ -261,10 +311,15 @@ trait Types {
     def typeOfThis: Type = typeSymbol.typeOfThis
 
     /** Map to a singleton type which is a subtype of this type.
+     *  todo: change to singleton type of an existentially defined variable
+     *  of the right type instead of making this a `this` of a refined type.
      */
     def narrow: Type =
       if (phase.erasedTypes) this
-      else {
+      else if (alternativeNarrow) { // investigate why this does not work!
+        val tparam = commonOwner(this) freshExistential ".type" setInfo singletonBounds(this)
+        tparam.tpe
+      } else {
         val cowner = commonOwner(this)
         refinedType(List(this), cowner, EmptyScope, cowner.pos).narrow
       }
@@ -273,7 +328,7 @@ trait Types {
      *  for a reference denoting an abstract type, its bounds,
      *  for all other types, a TypeBounds type all of whose bounds are this type.
      */
-    def bounds: TypeBounds = mkTypeBounds(this, this)
+    def bounds: TypeBounds = TypeBounds(this, this)
 
     /** For a class or intersection type, its parents.
      *  For a TypeBounds type, the parents of its hi bound.
@@ -291,6 +346,9 @@ trait Types {
       case _ => List()
     }
 
+    /** This type, without its type arguments @M */
+    def typeConstructor: Type = this
+
     /** For a typeref, its arguments. The empty list for all other types */
     def typeArgs: List[Type] = List()
 
@@ -300,7 +358,12 @@ trait Types {
 
     def resultType(actuals: List[Type]) = this
 
-    def resultApprox: Type = ApproximateDeBruijnMap(resultType)
+    /** If this is a TypeRef `clazz`[`T`], return the argument `T`
+     *  otherwise return this type
+     */
+    def remove(clazz: Symbol): Type = this
+
+    def resultApprox: Type = if(settings.YdepMethTpes.value) ApproximateDependentMap(resultType) else resultType
 
     /** For a curried method or poly type its non-method result type, 
      *  the type itself for all other types */
@@ -310,10 +373,18 @@ trait Types {
      *  0 for all other types */
     def paramSectionCount: Int = 0
 
+    /** For a method or poly type, a list of its value parameter sections,
+     *  the empty list for all other types */
+    def paramss: List[List[Symbol]] = List()
+
+    /** For a method or poly type, its first value parameter section,
+     *  the empty list for all other types */
+    def params: List[Symbol] = List()
+
     /** For a method or poly type, the types of its first value parameter section,
      *  the empty list for all other types */
     def paramTypes: List[Type] = List()
-
+    
     /** For a (potentially wrapped) poly type, its type parameters,
      *  the empty list for all other types */
     def typeParams: List[Symbol] = List()
@@ -322,21 +393,38 @@ trait Types {
      *  the empty list for all other types */
     def boundSyms: List[Symbol] = List()
 
-    /** Mixin a NotNull trait unless type already has one */
-    def notNull: Type = 
-      if (isNotNull || phase.erasedTypes) this else NotNullType(this)
+    /** Mixin a NotNull trait unless type already has one
+     *  ...if the option is given, since it is causing typing bugs.
+     */
+    def notNull: Type =
+      if (!settings.Ynotnull.value || isNotNull || phase.erasedTypes) this
+      else NotNullType(this)
     
     /** Replace formal type parameter symbols with actual type arguments. 
      *
-     * Amounts to substitution except for higher-kinded types. (See overridden method in TypeRef) -- @M (contact adriaan.moors at cs.kuleuven.be)
+     * Amounts to substitution except for higher-kinded types. (See overridden method in TypeRef) -- @M
      */
-    def instantiateTypeParams(formals: List[Symbol], actuals: List[Type]): Type = this.subst(formals, actuals)
+    def instantiateTypeParams(formals: List[Symbol], actuals: List[Type]): Type =
+      if(formals.length == actuals.length) this.subst(formals, actuals) else ErrorType
 
+    /** If this type is an existential, turn all existentially bound variables to type skolems.
+     *  @param  owner    The owner of the created type skolems
+     *  @param  origin   The tree whose type was an existential for which the skolem was created.
+     */
     def skolemizeExistential(owner: Symbol, origin: AnyRef): Type = this
+
+    
+    /** A simple version of skolemizeExistential for situations where
+     *  owner or unpack location do not matter (typically used in subtype tests)
+     */
+    def skolemizeExistential: Type = skolemizeExistential(NoSymbol, null)
     
     /** Reduce to beta eta-long normal form. Expands type aliases and converts higher-kinded TypeRef's to PolyTypes. @M */
     def normalize = this // @MAT
     
+    /** Expands type aliases. */
+    def dealias = this
+    
     /** Is this type produced as a repair for an error? */
     def isError: Boolean = typeSymbol.isError || termSymbol.isError
 
@@ -367,33 +455,47 @@ trait Types {
      *  Members appear in linearization order of their owners.
      *  Members with the same owner appear in reverse order of their declarations.
      */
-    def members: List[Symbol] = findMember(nme.ANYNAME, 0, 0, false)(NoSymbol).alternatives
+    def members: List[Symbol] = findMember(nme.ANYNAME, 0, 0, false).alternatives
 
     /** A list of all non-private members of this type (defined or inherited) */
     def nonPrivateMembers: List[Symbol] =
-      findMember(nme.ANYNAME, PRIVATE | BRIDGE, 0, false)(NoSymbol).alternatives
+      findMember(nme.ANYNAME, PRIVATE | BRIDGES, 0, false).alternatives
+
+    /** A list of all non-private members of this type  (defined or inherited),
+     *  admitting members with given flags `admit`
+     */
+    def nonPrivateMembersAdmitting(admit: Long): List[Symbol] =
+      findMember(nme.ANYNAME, (PRIVATE | BRIDGES) & ~admit, 0, false).alternatives
 
     /** A list of all implicit symbols of this type  (defined or inherited) */
     def implicitMembers: List[Symbol] =
-      findMember(nme.ANYNAME, BRIDGE, IMPLICIT, false)(NoSymbol).alternatives
+      findMember(nme.ANYNAME, BRIDGES, IMPLICIT, false).alternatives
 
     /** A list of all deferred symbols of this type  (defined or inherited) */
     def deferredMembers: List[Symbol] =
-      findMember(nme.ANYNAME, BRIDGE, DEFERRED, false)(NoSymbol).alternatives
+      findMember(nme.ANYNAME, BRIDGES, DEFERRED, false).alternatives
 
     /** The member with given name, 
      *  an OverloadedSymbol if several exist, NoSymbol if none exist */
-    def member(name: Name): Symbol = findMember(name, BRIDGE, 0, false)(NoSymbol)
+    def member(name: Name): Symbol = findMember(name, BRIDGES, 0, false)
 
     /** The non-private member with given name,
-     *  an OverloadedSymbol if several exist, NoSymbol if none exist */
+     *  an OverloadedSymbol if several exist, NoSymbol if none exist.
+     *  Bridges are excluded from the result
+     */
     def nonPrivateMember(name: Name): Symbol =
-      findMember(name, PRIVATE | BRIDGE, 0, false)(NoSymbol)
+      findMember(name, PRIVATE | BRIDGES, 0, false)
+  
+    /** The non-private member with given name, admitting members with given flags `admit`
+     *  an OverloadedSymbol if several exist, NoSymbol if none exist
+     */
+    def nonPrivateMemberAdmitting(name: Name, admit: Long): Symbol =
+      findMember(name, (PRIVATE | BRIDGES) & ~admit, 0, false)
   
     /** The non-local member with given name,
      *  an OverloadedSymbol if several exist, NoSymbol if none exist */
-    def nonLocalMember(name: Name)(from : Symbol): Symbol =
-      findMember(name, LOCAL | BRIDGE, 0, false)(from)
+    def nonLocalMember(name: Name): Symbol =
+      findMember(name, LOCAL | BRIDGES, 0, false)
 
     /** The least type instance of given class which is a supertype
      *  of this type */
@@ -408,41 +510,34 @@ trait Types {
      */
     def asSeenFrom(pre: Type, clazz: Symbol): Type =
       if (!isTrivial && (!phase.erasedTypes || pre.typeSymbol == ArrayClass)) {
+        incCounter(asSeenFromCount)
+        val start = startTimer(asSeenFromNanos)
         val m = new AsSeenFromMap(pre.normalize, clazz)
         val tp = m apply this
-        existentialAbstraction(m.capturedParams, tp)
+        val result = existentialAbstraction(m.capturedParams, tp)
+        stopTimer(asSeenFromNanos, start)
+        result
       } else this
 
     /** The info of `sym', seen as a member of this type.
      */
-    def memberInfo(sym: Symbol): Type =
+    def memberInfo(sym: Symbol): Type = {
       sym.info.asSeenFrom(this, sym.owner)
+    }
 
     /** The type of `sym', seen as a member of this type. */
-    def memberType(sym: Symbol): Type = {
-      trackTypeIDE(sym)
-      //@M don't prematurely instantiate higher-kinded types, they will be instantiated by transform, typedTypeApply, etc. when really necessary
-     sym.tpeHK match { 
-        case ov @ OverloadedType(pre, alts) =>
-          OverloadedType(this, alts)
-/*
-          val pre1 = pre match {
-            case ClassInfoType(_, _, clazz) => clazz.tpe
-            case _ => pre
-          }
-          if (this =:= pre1) ov
-          else if (this =:= pre1.narrow) OverloadedType(this, alts)
-          else {
-            Console.println("bad memberType of overloaded symbol: "+this+"/"+pre1+"/"+pre1.narrow)
-            assert(false)
-            ov
-          }
-*/
-        case tp =>
-          val res = tp.asSeenFrom(this, sym.owner)
-//          if (sym.name.toString == "emitSWITCH") println(this + ".memberType(" + sym +":" + sym.tpe +")" + sym.ownerChain + " = " + res);//debug
-          res
-      }
+    def memberType(sym: Symbol): Type = sym match {
+      case meth: MethodSymbol =>
+        meth.typeAsMemberOf(this)
+      case _ =>
+        computeMemberType(sym)
+    }
+
+    def computeMemberType(sym: Symbol): Type = sym.tpeHK match { //@M don't prematurely instantiate higher-kinded types, they will be instantiated by transform, typedTypeApply, etc. when really necessary
+      case OverloadedType(_, alts) =>
+        OverloadedType(this, alts)
+      case tp =>
+        tp.asSeenFrom(this, sym.owner)
     }
 
     /** Substitute types `to' for occurrences of references to
@@ -483,6 +578,11 @@ trait Types {
     /** Apply `f' to each part of this type */
     def foreach(f: Type => Unit) { new ForEachTypeTraverser(f).traverse(this) }
 
+    /** Apply `f' to each part of this type; children get mapped before their parents */
+    def map(f: Type => Type): Type = new TypeMap {
+      def apply(x: Type) = f(mapOver(x))
+    } apply this
+
     /** Is there part of this type which satisfies predicate `p'? */
     def exists(p: Type => Boolean): Boolean = !find(p).isEmpty
 
@@ -494,17 +594,66 @@ trait Types {
 
     /** Is this type a subtype of that type? */
     def <:<(that: Type): Boolean = {
-      if (util.Statistics.enabled) subtypeCount += 1 
-      val startTime = if (util.Statistics.enabled) currentTime else 0l
+      if (util.Statistics.enabled) stat_<:<(that)
+      else {
+        (this eq that) ||
+        (if (explainSwitch) explain("<:", isSubType, this, that)
+         else isSubType(this, that, AnyDepth))
+      }
+    }
+    
+    /** Can this type only be subtyped by bottom types?
+     *  This is assessed to be the case if the class is final,
+     *  and all type parameters (if any) are invariant.
+     */
+    def isFinalType = (
+      typeSymbol.isFinal &&
+      (typeSymbol.typeParams forall (_.variance == 0))
+    )
+    
+    /** Is this type a subtype of that type in a pattern context?
+     *  Any type arguments on the right hand side are replaced with
+     *  fresh existentials, except for Arrays.
+     *
+     *  See bug1434.scala for an example of code which would fail
+     *  if only a <:< test were applied.
+     */     
+    def matchesPattern(that: Type): Boolean = {
+      (this <:< that) || ((this, that) match {        
+        case (TypeRef(_, ArrayClass, List(arg1)), TypeRef(_, ArrayClass, List(arg2))) if arg2.typeSymbol.typeParams.nonEmpty =>
+          arg1 matchesPattern arg2
+        case (_, TypeRef(_, _, args)) =>
+          val newtp = existentialAbstraction(args map (_.typeSymbol), that)
+          !(that =:= newtp) && (this <:< newtp)
+        case _ =>
+          false
+      })
+    }
+    
+    def stat_<:<(that: Type): Boolean = {
+      incCounter(subtypeCount)
+      val start = startTimer(subtypeNanos)
+      val result = 
+        (this eq that) ||
+        (if (explainSwitch) explain("<:", isSubType, this, that)
+         else isSubType(this, that, AnyDepth))
+      stopTimer(subtypeNanos, start)
+      result
+    }
+
+    /** Is this type a weak subtype of that type? True also for numeric types, i.e. Int weak_<:< Long.
+     */
+    def weak_<:<(that: Type): Boolean = {
+      incCounter(subtypeCount)
+      val start = startTimer(subtypeNanos)
       val result =
         ((this eq that) ||
-         (if (explainSwitch) explain("<", isSubType, this, that)
-          else isSubType(this, that, AnyDepth)))
-      if (util.Statistics.enabled)
-        subtypeMillis = subtypeMillis + currentTime - startTime
+         (if (explainSwitch) explain("weak_<:", isWeakSubType, this, that)
+          else isWeakSubType(this, that)))
+      stopTimer(subtypeNanos, start)
       result
     }
-  
+
     /** Is this type equivalent to that type? */
     def =:=(that: Type): Boolean = (
       (this eq that) ||
@@ -574,16 +723,20 @@ trait Types {
         if (sym == btssym) return mid
         else if (sym isLess btssym) hi = mid - 1
         else if (btssym isLess sym) lo = mid + 1
-        else throw new Error()
+        else abort()
       }
       -1
     }
 
-    /** If this is a polytype, a copy with cloned type parameters owned
-     *  by `owner'. Identity for all other types.
+    /** If this is a poly- or methodtype, a copy with cloned type / value parameters
+     *  owned by `owner'. Identity for all other types.
      */
     def cloneInfo(owner: Symbol) = this
 
+    /** Make sure this type is correct as the info of given owner; clone it if not.
+     */
+    def atOwner(owner: Symbol) = this
+
     protected def objectPrefix = "object "
     protected def packagePrefix = "package "
 
@@ -605,7 +758,7 @@ trait Types {
     /** A test whether a type contains any unification type variables */
     def isGround: Boolean = this match {
       case TypeVar(_, constr) => 
-        constr.inst != NoType && constr.inst.isGround
+        constr.instValid && constr.inst.isGround
       case TypeRef(pre, sym, args) =>
         sym.isPackageClass || pre.isGround && (args forall (_.isGround))
       case SingleType(pre, sym) =>
@@ -616,12 +769,9 @@ trait Types {
         typeVarToOriginMap(this) eq this
     }
 
-    /** Is this type completed (i.e. not a lazy type)?
+    /** Is this type a varargs parameter?
      */
-    def isComplete: Boolean = true
-
-    /** If this is a lazy type, assign a new type to `sym'. */
-    def complete(sym: Symbol) {}
+    def isVarargs: Boolean = typeSymbol == RepeatedParamClass
 
     /** If this is a symbol loader type, load and assign a new type to
      *  `sym'.
@@ -654,28 +804,32 @@ trait Types {
      *  @param excludedFlags  Returned members do not have these flags
      *  @param requiredFlags  Returned members do have these flags
      *  @param stableOnly     If set, return only members that are types or stable values
-     *  @param from           ??
      */
     //TODO: use narrow only for modules? (correct? efficiency gain?)
-    def findMember(name: Name, excludedFlags: Int, requiredFlags: Long, stableOnly: Boolean)(from:Symbol): Symbol = {
-      // if this type contains type variables, get rid of them;
+    def findMember(name: Name, excludedFlags: Long, requiredFlags: Long, stableOnly: Boolean): Symbol = {
+      val suspension = TypeVar.Suspension
+      // if this type contains type variables, put them to sleep for a while -- don't just wipe them out by
+      // replacing them by the corresponding type parameter, as that messes up (e.g.) type variables in type refinements
       // without this, the matchesType call would lead to type variables on both sides
       // of a subtyping/equality judgement, which can lead to recursive types being constructed.
       // See (t0851) for a situation where this happens.
-      if (!this.isGround)
-        return typeVarToOriginMap(this).findMember(name, excludedFlags, requiredFlags, stableOnly)(from)
-      if (inIDE) trackTypeIDE(typeSymbol)
-      if (util.Statistics.enabled) findMemberCount += 1
-      val startTime = if (util.Statistics.enabled) currentTime else 0l
+      if (!this.isGround) {
+        // make each type var in this type use its original type for comparisons instead of collecting constraints
+        for(tv at TypeVar(_, _) <- this) {
+          suspension suspend tv
+        } 
+      }
+
+      incCounter(findMemberCount)
+      val start = startTimer(findMemberNanos)
 
       //Console.println("find member " + name.decode + " in " + this + ":" + this.baseClasses)//DEBUG
       var members: Scope = null
       var member: Symbol = NoSymbol
       var excluded = excludedFlags | DEFERRED
-      var self: Type = null
       var continue = true
-      var savedCheckMalformedSwitch = checkMalformedSwitch
-      checkMalformedSwitch = false
+      var self: Type = null
+      var membertpe: Type = null
       while (continue) {
         continue = false
         val bcs0 = baseClasses
@@ -683,20 +837,19 @@ trait Types {
         while (!bcs.isEmpty) {
           val decls = bcs.head.info.decls
           var entry =
-            if (name == nme.ANYNAME) decls.elems else decls.lookupEntryWithContext(name)(from)
+            if (name == nme.ANYNAME) decls.elems else decls.lookupEntry(name)
           while (entry ne null) {
             val sym = entry.sym
             if (sym.getFlag(requiredFlags) == requiredFlags) {
               val excl = sym.getFlag(excluded)
-              if (excl == 0 && 
+              if (excl == 0L && 
                   (// omit PRIVATE LOCALS unless selector class is contained in class owning the def.
                    (bcs eq bcs0) || 
-                   sym.getFlag(PRIVATE | LOCAL) != (PRIVATE | LOCAL) ||
+                   sym.getFlag(PRIVATE | LOCAL) != (PRIVATE | LOCAL).toLong ||
                    (bcs0.head.hasTransOwner(bcs.head)))) {
                 if (name.isTypeName || stableOnly && sym.isStable) {
-                  checkMalformedSwitch = savedCheckMalformedSwitch
-                  if (util.Statistics.enabled)
-                    findMemberMillis = findMemberMillis + currentTime - startTime
+                  stopTimer(findMemberNanos, start)
+                  suspension.resumeAll
                   return sym
                 } else if (member == NoSymbol) {
                   member = sym
@@ -705,19 +858,20 @@ trait Types {
                       !(member == sym ||
                         member.owner != sym.owner &&
                         !sym.hasFlag(PRIVATE) && {
-                          if (self eq null) self = this.narrow;
-                          (self.memberType(member) matches self.memberType(sym))
+                          if (self eq null) self = this.narrow
+                          if (membertpe eq null) membertpe = self.memberType(member)
+                          (membertpe matches self.memberType(sym))
                         })) {
-                    members = newThrowAwayScope(List(member, sym))
+                    members = new Scope(List(member, sym))
                   }
                 } else {
-                  var prevEntry = members.lookupEntryWithContext(sym.name)(from)
+                  var prevEntry = members.lookupEntry(sym.name)
                   while ((prevEntry ne null) &&
                          !(prevEntry.sym == sym ||
                            prevEntry.sym.owner != sym.owner &&
                            !sym.hasFlag(PRIVATE) && {
-                             if (self eq null) self = this.narrow;
-                             (self.memberType(prevEntry.sym) matches self.memberType(sym))
+                             if (self eq null) self = this.narrow
+                             self.memberType(prevEntry.sym) matches self.memberType(sym)
                            })) {
                     prevEntry = members lookupNextEntry prevEntry
                   }
@@ -725,7 +879,7 @@ trait Types {
                     members enter sym
                   }
                 }
-              } else if (excl == DEFERRED) {
+              } else if (excl == DEFERRED.toLong) {
                 continue = true
               }
             }
@@ -736,20 +890,18 @@ trait Types {
         } // while (!bcs.isEmpty)
         excluded = excludedFlags
       } // while (continue)
-      checkMalformedSwitch = savedCheckMalformedSwitch
-      if (util.Statistics.enabled)
-        findMemberMillis = findMemberMillis + currentTime - startTime
+      stopTimer(findMemberNanos, start)
+      suspension.resumeAll
       if (members eq null) {
-        if (util.Statistics.enabled) if (member == NoSymbol) noMemberCount += 1;
+        if (member == NoSymbol) incCounter(noMemberCount)
         member
       } else {
-        if (util.Statistics.enabled) multMemberCount += 1;
-        //val pre = if (this.typeSymbol.isClass) this.typeSymbol.thisType else this;
-        (baseClasses.head.newOverloaded(this, members.toList))
+        incCounter(multMemberCount)
+        baseClasses.head.newOverloaded(this, members.toList)
       }
     }
 
-    /** The existential skolems and existentially quantifed variables which are free in this type */
+    /** The existential skolems and existentially quantified variables which are free in this type */
     def existentialSkolems: List[Symbol] = {
       var boundSyms: List[Symbol] = List()
       var skolems: List[Symbol] = List()
@@ -766,21 +918,24 @@ trait Types {
       skolems
     }
 
-    /** Return the attributes on this type */
-    val attributes: List[AnnotationInfo] = Nil
+    /** Return the annotations on this type. */
+    def annotations: List[AnnotationInfo] = Nil
 
-    /** Add an attribute to this type */
-    def withAttribute(attrib: AnnotationInfo) = withAttributes(List(attrib))
+    /** Test for the presence of an annotation */
+    def hasAnnotation(clazz: Symbol) = annotations exists { _.atp.typeSymbol == clazz }
+
+    /** Add an annotation to this type */
+    def withAnnotation(annot: AnnotationInfo) = withAnnotations(List(annot))
     
-    /** Add a number of attributes to this type */
-    def withAttributes(attribs: List[AnnotationInfo]): Type =
-      attribs match {
+    /** Add a number of annotations to this type */
+    def withAnnotations(annots: List[AnnotationInfo]): Type =
+      annots match {
         case Nil => this
-        case _ => AnnotatedType(attribs, this, NoSymbol)
+        case _ => AnnotatedType(annots, this, NoSymbol)
       }
       
     /** Remove any annotations from this type */
-    def withoutAttributes = this
+    def withoutAnnotations = this
 
     /** Remove any annotations from this type and from any
      *  types embedded in this type. */
@@ -795,30 +950,14 @@ trait Types {
 
     /** The kind of this type; used for debugging */
     def kind: String = "unknown type of class "+getClass()
-
-    override def toString: String =
-      if (tostringRecursions >= maxTostringRecursions)
-        "..."
-      else
-        try {
-          tostringRecursions += 1
-          safeToString
-        } finally {
-          tostringRecursions -= 1
-        }
-
-    def safeToString: String = super.toString
   }
 
-  private final val maxTostringRecursions = 50
-  private var tostringRecursions = 0
-
 // Subclasses ------------------------------------------------------------
 
   trait UniqueType {
-    private val hashcode = { val h = super.hashCode(); if (h < 0) -h else h }
-    override def hashCode() = hashcode
+    override lazy val hashCode: Int = super.hashCode()
   }
+
  /** A base class for types that defer some operations
    *  to their immediate supertype.
    */
@@ -829,11 +968,7 @@ trait Types {
     override def baseType(clazz: Symbol): Type = supertype.baseType(clazz)
     override def baseTypeSeq: BaseTypeSeq = supertype.baseTypeSeq
     override def baseTypeSeqDepth: Int = supertype.baseTypeSeqDepth
-    override def baseClasses: List[Symbol] = {
-      val supertype = this.supertype
-      if (inIDE && supertype == null) Nil
-      else supertype.baseClasses
-    }
+    override def baseClasses: List[Symbol] = supertype.baseClasses
     override def isNotNull = supertype.isNotNull
   }
 
@@ -857,13 +992,14 @@ trait Types {
     override def isVolatile = underlying.isVolatile
     override def widen: Type = underlying.widen
     override def baseTypeSeq: BaseTypeSeq = {
-      if (util.Statistics.enabled) singletonBaseTypeSeqCount += 1
+      incCounter(singletonBaseTypeSeqCount)
       underlying.baseTypeSeq prepend this
     }
+    override def isHigherKinded = false // singleton type classifies objects, thus must be kind *
     override def safeToString: String = prefixString + "type"
 /*
     override def typeOfThis: Type = typeSymbol.typeOfThis
-    override def bounds: TypeBounds = mkTypeBounds(this, this)
+    override def bounds: TypeBounds = TypeBounds(this, this)
     override def prefix: Type = NoType
     override def typeArgs: List[Type] = List()
     override def typeParams: List[Symbol] = List()
@@ -875,8 +1011,7 @@ trait Types {
     // todo see whether we can do without
     override def isError: Boolean = true
     override def decls: Scope = new ErrorScope(NoSymbol)
-    override def findMember(name: Name, excludedFlags: Int,
-                            requiredFlags: Long, stableOnly: Boolean)(from : Symbol): Symbol = {
+    override def findMember(name: Name, excludedFlags: Long, requiredFlags: Long, stableOnly: Boolean): Symbol = {
       var sym = decls lookup name
       if (sym == NoSymbol) {
         sym = NoSymbol.newErrorSymbol(name)
@@ -893,12 +1028,14 @@ trait Types {
 
   /** An object representing an unknown type */
   case object WildcardType extends Type {
+    override def isWildcard = true
     override def safeToString: String = "?"
     // override def isNullable: Boolean = true
     override def kind = "WildcardType"
   }
 
   case class BoundedWildcardType(override val bounds: TypeBounds) extends Type {
+    override def isWildcard = true
     override def safeToString: String = "?" + bounds
     override def kind = "BoundedWildcardType"
   }
@@ -923,18 +1060,19 @@ trait Types {
 
   /** A class for this-types of the form <sym>.this.type 
    */
-  case class ThisType(sym: Symbol) extends SingletonType {
+  abstract case class ThisType(sym: Symbol) extends SingletonType {
     //assert(sym.isClass && !sym.isModuleClass || sym.isRoot, sym)
     override def isTrivial: Boolean = sym.isPackageClass
     override def isNotNull = true
     override def typeSymbol = sym
     override def underlying: Type = sym.typeOfThis
     override def isVolatile = false
+    override def isHigherKinded = sym.isRefinementClass && underlying.isHigherKinded
     override def prefixString =
       if (settings.debug.value) sym.nameString + ".this."
       else if (sym.isRoot || sym.isEmptyPackageClass || sym.isInterpreterWrapper || sym.isScalaPackageClass) ""
       else if (sym.isAnonymousClass || sym.isRefinementClass) "this."
-      else if (sym.isModuleClass) sym.fullNameString + "."
+      else if (sym.isModuleClass) sym.fullName + "."
       else sym.nameString + ".this."
     override def safeToString: String =
       if (sym.isRoot) "<root>"
@@ -944,14 +1082,21 @@ trait Types {
     override def kind = "ThisType"
   }
 
-  case class DeBruijnIndex(level: Int, paramId: Int) extends Type {
-    override def isTrivial = true
-    override def isStable = true
-    override def safeToString = "<param "+level+"."+paramId+">"
-    override def kind = "DeBruijnIndex"
-    // todo: this should be a subtype, which forwards to underlying
+  object ThisType extends ThisTypeExtractor {
+    def apply(sym: Symbol): Type = 
+      if (!phase.erasedTypes) unique(new ThisType(sym) with UniqueType)
+      else if (sym.isImplClass) sym.typeOfThis
+      else sym.tpe
   }
 
+  // case class DeBruijnIndex(level: Int, paramId: Int) extends Type {
+  //   override def isTrivial = true
+  //   override def isStable = true
+  //   override def safeToString = "<param "+level+"."+paramId+">"
+  //   override def kind = "DeBruijnIndex"
+  //   // todo: this should be a subtype, which forwards to underlying
+  // }
+
   /** A class for singleton types of the form <prefix>.<sym.name>.type.
    *  Cannot be created directly; one should always use
    *  `singleType' for creation.
@@ -960,22 +1105,24 @@ trait Types {
     override val isTrivial: Boolean = pre.isTrivial
     // override def isNullable = underlying.isNullable
     override def isNotNull = underlying.isNotNull
-    private var underlyingCache: Type = _
+    private var underlyingCache: Type = NoType
     private var underlyingPeriod = NoPeriod
     override def underlying: Type = {
-      // this kind of caching here won't work in the IDE
-      if (inIDE) return pre.memberType(sym).resultType
       val period = underlyingPeriod
       if (period != currentPeriod) {
         underlyingPeriod = currentPeriod
         if (!isValid(period)) {
           underlyingCache = pre.memberType(sym).resultType;
+          assert(underlyingCache ne this, this)
         }
       }
-      assert(underlyingCache ne this, this)
       underlyingCache
     }
 
+    // more precise conceptually, but causes cyclic errors:    (paramss exists (_ contains sym))
+    override def isImmediatelyDependent = (sym ne NoSymbol) && (sym.owner.isMethod && sym.isValueParameter)
+
+    override def isVolatile : Boolean = underlying.isVolatile && (!sym.isStable)
 /*
     override def narrow: Type = {
       if (phase.erasedTypes) this
@@ -999,7 +1146,9 @@ trait Types {
     override def kind = "SingleType"
   }
 
-  case class SuperType(thistpe: Type, supertpe: Type) extends SingletonType {
+  object SingleType extends SingleTypeExtractor
+
+  abstract case class SuperType(thistpe: Type, supertpe: Type) extends SingletonType {
     override val isTrivial: Boolean = thistpe.isTrivial && supertpe.isTrivial
     override def isNotNull = true;
     override def typeSymbol = thistpe.typeSymbol
@@ -1013,9 +1162,15 @@ trait Types {
     override def kind = "SuperType"
   }
 
+  object SuperType extends SuperTypeExtractor {
+    def apply(thistp: Type, supertp: Type): Type =
+      if (phase.erasedTypes) supertp
+      else unique(new SuperType(thistp, supertp) with UniqueType)
+  }
+
   /** A class for the bounds of abstract types and type parameters
    */
-  case class TypeBounds(lo: Type, hi: Type) extends SubType {
+  abstract case class TypeBounds(lo: Type, hi: Type) extends SubType {
     def supertype = hi
     override val isTrivial: Boolean = lo.isTrivial && hi.isTrivial
     override def bounds: TypeBounds = this
@@ -1028,6 +1183,11 @@ trait Types {
     override def kind = "TypeBoundsType"
   }
 
+  object TypeBounds extends TypeBoundsExtractor {
+    def apply(lo: Type, hi: Type): TypeBounds =
+      unique(new TypeBounds(lo, hi) with UniqueType)
+  }
+
   /** A common base class for intersection types and class types 
    */
   abstract class CompoundType extends Type {
@@ -1042,15 +1202,49 @@ trait Types {
       if (period != currentPeriod) { // no caching in IDE
         baseTypeSeqPeriod = currentPeriod
         if (!isValidForBaseClasses(period)) {
-          if (util.Statistics.enabled)
-            compoundBaseTypeSeqCount += 1
-          baseTypeSeqCache = undetBaseTypeSeq
-          baseTypeSeqCache = memo(compoundBaseTypeSeq(this/*typeSymbol, parents*/))(_.baseTypeSeq updateHead typeSymbol.tpe)
-//          println("normalizing baseTypeSeq of "+typeSymbol+"/"+parents+": "+baseTypeSeqCache)//DEBUG
-          baseTypeSeqCache.normalize(parents)
-//          println("normalized baseTypeSeq of "+typeSymbol+"/"+parents+": "+baseTypeSeqCache)//DEBUG
+          if (parents.exists(_.exists(_.isInstanceOf[TypeVar]))) {
+            // rename type vars to fresh type params, take base type sequence of
+            // resulting type, and rename back all the entries in that sequence
+            var tvs = Set[TypeVar]()
+            for (p <- parents)
+              for (t <- p) t match {
+                case tv: TypeVar => tvs += tv
+                case _ =>
+              }
+            val varToParamMap: Map[Type, Symbol] = tvs map (tv => tv -> tv.origin.typeSymbol.cloneSymbol) toMap 
+            val paramToVarMap = varToParamMap map (_.swap)
+            val varToParam = new TypeMap {
+              def apply(tp: Type) = varToParamMap get tp match {
+                case Some(sym) => sym.tpe
+                case _ => mapOver(tp)
+              }
+            }
+            val paramToVar = new TypeMap {
+              def apply(tp: Type) = tp match {
+                case TypeRef(_, tsym, _) if paramToVarMap.isDefinedAt(tsym) => paramToVarMap(tsym)
+                case _ => mapOver(tp)
+              }
+            }
+            val bts = copyRefinedType(this.asInstanceOf[RefinedType], parents map varToParam, varToParam mapOver decls).baseTypeSeq
+            baseTypeSeqCache = bts lateMap paramToVar
+          } else {
+            incCounter(compoundBaseTypeSeqCount)
+            baseTypeSeqCache = undetBaseTypeSeq
+            baseTypeSeqCache = if (typeSymbol.isRefinementClass)
+              memo(compoundBaseTypeSeq(this))(_.baseTypeSeq updateHead typeSymbol.tpe)
+            else
+              compoundBaseTypeSeq(this)
+            // [Martin] suppressing memo-ization solves the problem with "same type after erasure" errors
+            // when compiling with 
+            // scalac scala.collection.IterableViewLike.scala scala.collection.IterableLike.scala
+            // I have not yet figured out precisely why this is the case.
+            // My current assumption is that taking memos forces baseTypeSeqs to be computed
+            // at stale types (i.e. the underlying typeSymbol has already another type).
+            // I do not yet see precisely why this would cause a problem, but it looks
+            // fishy in any case.
+          }
         }
-        //Console.println("baseTypeSeq(" + typeSymbol + ") = " + List.fromArray(baseTypeSeqCache));//DEBUG
+        //Console.println("baseTypeSeq(" + typeSymbol + ") = " + baseTypeSeqCache.toList);//DEBUG
       }
       if (baseTypeSeqCache eq undetBaseTypeSeq)
         throw new TypeError("illegal cyclic inheritance involving " + typeSymbol)
@@ -1060,7 +1254,6 @@ trait Types {
     override def baseTypeSeqDepth: Int = baseTypeSeq.maxDepth
 
     override def baseClasses: List[Symbol] = {
-      if (inIDE) trackTypeIDE(typeSymbol)
       def computeBaseClasses: List[Symbol] =
         if (parents.isEmpty) List(typeSymbol)
         else {
@@ -1103,23 +1296,22 @@ trait Types {
     def memo[A](op1: => A)(op2: Type => A) = intersectionWitness get parents match {
       case Some(w) =>
         if (w eq this) op1 else op2(w)
-      case None => 
+      case none => 
         intersectionWitness(parents) = this
         op1
     }
 
     override def baseType(sym: Symbol): Type = {
-      if (inIDE) { trackTypeIDE(sym); trackTypeIDE(typeSymbol); }
       val index = baseTypeIndex(sym)
       if (index >= 0) baseTypeSeq(index) else NoType
     }
 
-    override def narrow: Type = {
-      if (inIDE) trackTypeIDE(typeSymbol)
-      typeSymbol.thisType
-    }
-
+    override def narrow: Type = typeSymbol.thisType
     override def isNotNull: Boolean = parents exists (_.isNotNull)
+    
+    override def isStructuralRefinement: Boolean =
+      (typeSymbol.isRefinementClass || typeSymbol.isAnonymousClass) &&
+        (decls.toList exists { entry => !entry.isConstructor && entry.allOverriddenSymbols.isEmpty })
 
     // override def isNullable: Boolean =
     // parents forall (p => p.isNullable && !p.typeSymbol.isAbstractType);
@@ -1145,25 +1337,30 @@ trait Types {
       if (isHigherKinded) parents.head.typeParams
       else super.typeParams
 
-    private def higherKindedArgs = 
-      typeParams map (_.typeConstructor) 
+    //@M may result in an invalid type (references to higher-order args become dangling )
+    override def typeConstructor = 
+      copyRefinedType(this, parents map (_.typeConstructor), decls)
+    
+    private def dummyArgs = typeParams map (_.typeConstructor)
 
-	/* MO to AM: This is probably not correct
+    /* MO to AM: This is probably not correct
      * If they are several higher-kinded parents with different bounds we need
-	 * to take the intersection of their bounds
+     * to take the intersection of their bounds
      */
-    override def normalize = 
-      if (isHigherKinded)
+    override def normalize = {
+      if (isHigherKinded) {
         PolyType(
-          typeParams, 
-          refinementOfClass(
-            typeSymbol, 
+          typeParams,
+          RefinedType(
             parents map {
-              case TypeRef(pre, sym, List()) => TypeRef(pre, sym, higherKindedArgs)
+              case TypeRef(pre, sym, List()) => TypeRef(pre, sym, dummyArgs)
               case p => p
             },
-            decls))
+            decls,
+            typeSymbol))
+      }
       else super.normalize
+    }
 
     /** A refined type P1 with ... with Pn { decls } is volatile if
      *  one of the parent types Pi is an abstract type, and
@@ -1180,20 +1377,26 @@ trait Types {
       def contributesAbstractMembers(p: Type) = 
         p.deferredMembers exists isVisible
 
-      (parents exists (_.isVolatile)) ||
-      (parents dropWhile (! _.typeSymbol.isAbstractType) match {
-        case ps @ (_ :: ps1) => 
-          (ps ne parents) ||
-          (ps1 exists contributesAbstractMembers) ||
-          (decls.elements exists (m => m.isDeferred && isVisible(m)))
-        case _ =>
-          false
-       })
+      ((parents exists (_.isVolatile)) 
+       ||
+       (parents dropWhile (! _.typeSymbol.isAbstractType) match {
+         case ps @ (_ :: ps1) => 
+           (ps ne parents) ||
+           (ps1 exists contributesAbstractMembers) ||
+           (decls.iterator exists (m => m.isDeferred && isVisible(m)))
+         case _ =>
+           false
+       }))
     }
 
     override def kind = "RefinedType"
   }
 
+  object RefinedType extends RefinedTypeExtractor {
+    def apply(parents: List[Type], decls: Scope, clazz: Symbol) = 
+      new RefinedType(parents, decls) { override def typeSymbol = clazz }
+  }
+
   /** A class representing a class info
    */
   case class ClassInfoType(
@@ -1244,7 +1447,7 @@ trait Types {
      */
     private def getRefs(which: Int, from: Symbol): Set[Symbol] = refs(which) get from match {
       case Some(set) => set
-      case None => Set()
+      case none => Set()
     }
 
     /** Augment existing refs map with reference <pre>from -> to</pre> 
@@ -1305,7 +1508,7 @@ trait Types {
       val lastRefs = Array(refs(0), refs(1))
       state = Initialized
       var change = false
-      for ((from, targets) <- refs(NonExpansive).elements)
+      for ((from, targets) <- refs(NonExpansive).iterator)
         for (target <- targets) {
           var thatInfo = classInfo(target)
           if (thatInfo.state != Initialized) 
@@ -1313,9 +1516,11 @@ trait Types {
           addRefs(NonExpansive, from, thatInfo.getRefs(NonExpansive, target))
           addRefs(Expansive, from, thatInfo.getRefs(Expansive, target))
         }
-      for ((from, targets) <- refs(Expansive).elements)
+      for ((from, targets) <- refs(Expansive).iterator)
         for (target <- targets) {
           var thatInfo = classInfo(target)
+          if (thatInfo.state != Initialized) 
+            change = change | thatInfo.propagate()
           addRefs(Expansive, from, thatInfo.getRefs(NonExpansive, target))
         }
       change = change || refs(0) != lastRefs(0) || refs(1) != lastRefs(1)
@@ -1332,16 +1537,16 @@ trait Types {
     override def kind = "ClassInfoType"
   }
 
-  class PackageClassInfoType(decls: Scope, clazz: Symbol, val lazyLoader : LazyType)
-  extends ClassInfoType(List(), decls, clazz) {
-    def reset = clazz.setInfo(lazyLoader)
-  }
+  object ClassInfoType extends ClassInfoTypeExtractor
+
+  class PackageClassInfoType(decls: Scope, clazz: Symbol)
+  extends ClassInfoType(List(), decls, clazz)
 
   /** A class representing a constant type.
    *
    *  @param value ...
    */
-  case class ConstantType(value: Constant) extends SingletonType {
+  abstract case class ConstantType(value: Constant) extends SingletonType {
     override def underlying: Type = value.tpe
     assert(underlying.typeSymbol != UnitClass)
     override def isTrivial: Boolean = true
@@ -1354,59 +1559,99 @@ trait Types {
     override def kind = "ConstantType"
   }
 
+  object ConstantType extends ConstantTypeExtractor {
+    def apply(value: Constant): ConstantType = {
+      class UniqueConstantType extends ConstantType(value) with UniqueType {
+        /** Save the type of 'value'. For Java enums, it depends on finding the linked class,
+         *  which might not be found after 'flatten'. */
+        private lazy val _tpe: Type = value.tpe
+        override def underlying: Type = _tpe
+      }
+      unique(new UniqueConstantType)
+    }
+  }
+
+  private var volatileRecursions: Int = 0
+  private val pendingVolatiles = new collection.mutable.HashSet[Symbol]
+
   /** A class for named types of the form
    *  `<prefix>.<sym.name>[args]'
    *  Cannot be created directly; one should always use `typeRef'
    *  for creation. (@M: Otherwise hashing breaks)
    *
-   * @M: Higher-kinded types are represented as TypeRefs with a symbol that has type parameters, but with args==List()
+   * @M: a higher-kinded type is represented as a TypeRef with sym.info.typeParams.nonEmpty, but args.isEmpty
    *  @param pre  ...
    *  @param sym  ...
    *  @param args ...
    */
-  case class TypeRef(pre: Type, sym: Symbol, args: List[Type]) extends Type {
-//    assert(!checkMalformedSwitch || !sym.isAbstractType || pre.isStable || pre.isError)
+  abstract case class TypeRef(pre: Type, sym: Symbol, args: List[Type]) extends Type {
+//    assert(!sym.isAbstractType || pre.isStable || pre.isError)
 //    assert(!pre.isInstanceOf[ClassInfoType], this)
 //    assert(!(sym hasFlag (PARAM | EXISTENTIAL)) || pre == NoPrefix, this)
 //    assert(args.isEmpty || !sym.info.typeParams.isEmpty, this)
-
+//    assert(args.isEmpty || ((sym ne AnyClass) && (sym ne NothingClass))
     private var parentsCache: List[Type] = _
     private var parentsPeriod = NoPeriod
     private var baseTypeSeqCache: BaseTypeSeq = _
     private var baseTypeSeqPeriod = NoPeriod
 
     override def isStable: Boolean = {
+      sym == NothingClass ||
       sym == SingletonClass ||
       sym.isAliasType && normalize.isStable ||
       sym.isAbstractType && (bounds.hi.typeSymbol isSubClass SingletonClass)
     }
 
-    override def isVolatile: Boolean =
+    override def isVolatile: Boolean = {
       sym.isAliasType && normalize.isVolatile ||
-      sym.isAbstractType && bounds.hi.isVolatile 
+      sym.isAbstractType && {
+        // need to be careful not to fall into an infinite recursion here
+        // because volatile checking is done before all cycles are detected.
+        // the case to avoid is an abstract type directly or
+        // indirectly upper-bounded by itself. See #2918
+        try {
+          volatileRecursions += 1
+          if (volatileRecursions < LogVolatileThreshold)
+            bounds.hi.isVolatile
+          else if (pendingVolatiles contains sym)
+            true // we can return true here, because a cycle will be detected
+                 // here afterwards and an error will result anyway.
+          else 
+            try {
+              pendingVolatiles += sym
+              bounds.hi.isVolatile
+            } finally {
+              pendingVolatiles -= sym
+            }
+        } finally {
+          volatileRecursions -= 1
+        }
+      }
+    }
 
     override val isTrivial: Boolean =
-      pre.isTrivial && !sym.isTypeParameter && args.forall(_.isTrivial)
+      !sym.isTypeParameter && pre.isTrivial && args.forall(_.isTrivial)
 
     override def isNotNull = 
       sym.isModuleClass || sym == NothingClass || isValueClass(sym) || super.isNotNull
 
     // @M: propagate actual type params (args) to `tp', by replacing formal type parameters with actual ones
+    // if tp is higher kinded, the "actual" type arguments are types that simply reference the corresponding type parameters  (unbound type variables) 
     def transform(tp: Type): Type = {
-      val args = argsMaybeDummy
-      if (args.length == sym.typeParams.length)
-        tp.asSeenFrom(pre, sym.owner).instantiateTypeParams(sym.typeParams, argsMaybeDummy)
-      else { assert(sym.typeParams.isEmpty || (args exists (_.isError)), tp); tp }
-      // @M TODO maybe we shouldn't instantiate type params if isHigherKinded -- probably needed for partial type application though
+      val res = tp.asSeenFrom(pre, sym.owner)
+      if (sym.typeParams.isEmpty || (args exists (_.isError)) || isRaw(sym, args)/*#2266/2305*/) res
+      else res.instantiateTypeParams(sym.typeParams, typeArgsOrDummies)
     }
 
     //@M! use appliedType on the polytype that represents the bounds (or if aliastype, the rhs)
-    def transformInfo(tp: Type): Type =
-      appliedType(tp.asSeenFrom(pre, sym.owner), argsMaybeDummy)
-      // TODO: argsMaybeDummy --> ok? or don't instantiate type params if isHigherKinded
+    def transformInfo(tp: Type): Type = appliedType(tp.asSeenFrom(pre, sym.owner), typeArgsOrDummies)
 
-    def thisInfo     = if (sym.isTypeMember) transformInfo(sym.info) else sym.info
-    def relativeInfo = if (sym.isTypeMember) transformInfo(pre.memberInfo(sym)) else pre.memberInfo(sym)
+    def thisInfo     = 
+      if (sym.isAliasType) normalize
+      else if (sym.isNonClassType) transformInfo(sym.info) 
+      else sym.info
+
+    def relativeInfo = if (sym.isNonClassType) transformInfo(pre.memberInfo(sym)) else pre.memberInfo(sym)
 
     override def typeSymbol = if (sym.isAliasType) normalize.typeSymbol else sym
     override def termSymbol = if (sym.isAliasType) normalize.termSymbol else super.termSymbol
@@ -1423,7 +1668,7 @@ A type's typeSymbol should never be inspected directly.
 */
 
     override def bounds: TypeBounds =
-      if (sym.isAbstractType) transform(thisInfo.bounds).asInstanceOf[TypeBounds] // ??? seems to be doing asSeenFrom twice
+      if (sym.isAbstractType) thisInfo.bounds // transform(thisInfo.bounds).asInstanceOf[TypeBounds] // ??? seems to be doing asSeenFrom twice
       else super.bounds
 
     override def parents: List[Type] = {
@@ -1432,6 +1677,8 @@ A type's typeSymbol should never be inspected directly.
         parentsPeriod = currentPeriod
         if (!isValidForBaseClasses(period)) {
           parentsCache = thisInfo.parents map transform
+        } else if (parentsCache == null) { // seems this can happen if things are currupted enough, see #2641
+          parentsCache = List(AnyClass.tpe)
         }
       }
       parentsCache
@@ -1455,48 +1702,95 @@ A type's typeSymbol should never be inspected directly.
       else pre
 
     override def typeArgs: List[Type] = args
+    private def typeArgsOrDummies = if (!isHigherKinded) args else dummyArgs
+
+    // @MAT was typeSymbol.unsafeTypeParams, but typeSymbol normalizes now 
+    private def typeParamsDirect = sym.unsafeTypeParams
 
-    override def typeParams: List[Symbol] =
-      if (args.isEmpty) sym.unsafeTypeParams else List()
-         // @MAT was typeSymbol.unsafeTypeParams, but typeSymbol normalizes now 
+    // placeholders derived from type params
+    private def dummyArgs = typeParamsDirect map (_.typeConstructor) //@M must be .typeConstructor
 
-    override def instantiateTypeParams(formals: List[Symbol], actuals: List[Type]): Type = 
+    // (!result.isEmpty) IFF isHigherKinded
+    override def typeParams: List[Symbol] = if (isHigherKinded) typeParamsDirect else List()
+
+    override def typeConstructor = TypeRef(pre, sym, List())
+
+    // a reference (in a Scala program) to a type that has type parameters, but where the reference does not include type arguments
+    // note that it doesn't matter whether the symbol refers to a java or scala symbol,
+    // it does matter whether it occurs in java or scala code
+    // typerefs w/o type params that occur in java signatures/code are considered raw types, and are represented as existential types
+    override def isHigherKinded = (args.isEmpty && !typeParamsDirect.isEmpty)
+
+    override def instantiateTypeParams(formals: List[Symbol], actuals: List[Type]): Type =
       if (isHigherKinded) {
         val substTps = formals.intersect(typeParams)
-      
-        if (substTps.length == typeParams.length) 
+
+        if (substTps.length == typeParams.length)
           typeRef(pre, sym, actuals)
-        else // partial application (needed in infer when bunching type arguments from classes and methods together)
-          typeRef(pre, sym, higherKindedArgs).subst(formals, actuals)
-      } 
-      else 
+        else if(formals.length == actuals.length) // partial application (needed in infer when bunching type arguments from classes and methods together)
+          typeRef(pre, sym, dummyArgs).subst(formals, actuals)
+        else ErrorType
+      }
+      else
         super.instantiateTypeParams(formals, actuals)
 
-    override def isHigherKinded = !typeParams.isEmpty  //@M args.isEmpty is checked in typeParams
 
-    private def higherKindedArgs = typeParams map (_.typeConstructor) //@M must be .typeConstructor
-    private def argsMaybeDummy = if (isHigherKinded) higherKindedArgs else args 
+    private var normalized: Type = null
 
-    override def normalize = 
-      if (sym.isAliasType) { // beta-reduce 
-        if (sym.info.typeParams.length == args.length || !isHigherKinded) { 
-/* !isHigherKinded && sym.info.typeParams.length != args.length only happens when compiling e.g., 
-  `val x: Class' with -Xgenerics, while `type Class = java.lang.Class' had already been compiled without -Xgenerics */
-          val xform = transform(sym.info.resultType)
-          assert(xform ne this, this)
-          xform.normalize // cycles have been checked in typeRef
-        } else PolyType(typeParams, transform(sym.info.resultType).normalize)  // eta-expand
-        // @M TODO: should not use PolyType, as that's the type of a polymorphic value -- we really want a type *function*
-      } else if (isHigherKinded) { 
-        // @M TODO: should not use PolyType, as that's the type of a polymorphic value -- we really want a type *function*
-		// @M: initialize needed (see test/files/pos/ticket0137.scala)
-        PolyType(typeParams, typeRef(pre, sym.initialize, higherKindedArgs))         
-      } else if (sym.isRefinementClass) {
-        sym.info.normalize // @MO to AM: OK?
-      } else {
-        super.normalize
+    @inline private def betaReduce: Type = {
+      assert(sym.info.typeParams.length == typeArgs.length, this)
+      // isHKSubType0 introduces synthetic type params so that betaReduce can first apply sym.info to typeArgs before calling asSeenFrom
+      // asSeenFrom then skips synthetic type params, which are used to reduce HO subtyping to first-order subtyping, but which can't be instantiated from the given prefix and class
+      // appliedType(sym.info, typeArgs).asSeenFrom(pre, sym.owner) // this crashes pos/depmet_implicit_tpbetareduce.scala
+      transform(sym.info.resultType)
+    }
+
+    // @M TODO: should not use PolyType, as that's the type of a polymorphic value -- we really want a type *function*
+    // @M: initialize (by sym.info call) needed (see test/files/pos/ticket0137.scala)
+    @inline private def etaExpand: Type = {
+      val tpars = sym.info.typeParams // must go through sym.info for typeParams to initialise symbol
+      PolyType(tpars, typeRef(pre, sym, tpars map (_.tpeHK))) // todo: also beta-reduce?
+    }
+
+    override def dealias: Type = 
+      if (sym.isAliasType && sym.info.typeParams.length == args.length) {
+        betaReduce.dealias
+      } else this
+
+    def normalize0: Type =
+      if (pre eq WildcardType) WildcardType // arises when argument-dependent types are approximated (see def depoly in implicits)
+      else if (isHigherKinded) etaExpand   // eta-expand, subtyping relies on eta-expansion of higher-kinded types
+      else if (sym.isAliasType && sym.info.typeParams.length == args.length) 
+                               betaReduce.normalize // beta-reduce, but don't do partial application -- cycles have been checked in typeRef
+      else if (sym.isRefinementClass) 
+                               sym.info.normalize // I think this is okay, but see #1241 (r12414), #2208, and typedTypeConstructor in Typers
+      // else if (args nonEmpty) {
+      //   val argsNorm = args mapConserve (_.dealias)
+      //   if(argsNorm ne args) TypeRef(pre, sym, argsNorm)
+      //   else this
+      // } 
+      else {
+        if(sym.isAliasType) ErrorType //println("!!error: "+(pre, sym, sym.info, sym.info.typeParams, args))
+        else super.normalize
       }
 
+   // track number of type parameters that we saw when caching normalization,
+   // so we can refresh our cache when the known list of type parameters changes (due to further class file loading)
+   // TODO: this would not be necessary if we could replace the call to sym.unsafeTypeParams in typeParamsDirect
+   // by a call to sym.typeParams, but need to verify that that does not lead to spurious "illegal cycle" errors
+   // the need for refreshing the cache is illustrated by #2278
+   // TODO: test case that is compiled  in a specific order and in different runs
+    private var normalizeTyparCount = -1
+
+    override def normalize: Type = {
+      if (phase.erasedTypes) normalize0
+      else if (normalized == null || typeParamsDirect.length != normalizeTyparCount) {
+        normalizeTyparCount = typeParamsDirect.length
+        normalized = normalize0
+        normalized
+      } else normalized
+    }
+
     override def decls: Scope = {
       sym.info match {
         case TypeRef(_, sym1, _) =>
@@ -1532,13 +1826,11 @@ A type's typeSymbol should never be inspected directly.
       if (period != currentPeriod) {
         baseTypeSeqPeriod = currentPeriod
         if (!isValidForBaseClasses(period)) {
-          if (util.Statistics.enabled)
-            typerefBaseTypeSeqCount += 1
+          incCounter(typerefBaseTypeSeqCount)
           baseTypeSeqCache = undetBaseTypeSeq
           baseTypeSeqCache =
             if (sym.isAbstractType) transform(bounds.hi).baseTypeSeq prepend this
             else sym.info.baseTypeSeq map transform
-            
         }
       }
       if (baseTypeSeqCache == undetBaseTypeSeq)
@@ -1567,16 +1859,30 @@ A type's typeSymbol should never be inspected directly.
           if (normed ne this) return normed.toString
         }
       }
-      var str = (pre.prefixString + sym.nameString +
-                 (if (args.isEmpty) "" else args.mkString("[", ",", "]")))
+      val monopart = 
+        if (!settings.debug.value && 
+            (shorthands contains sym.fullName) &&
+            (sym.ownerChain forall (_.isClass))) // ensure that symbol is not a local copy with a name coincidence 
+          sym.name.toString
+        else 
+          pre.prefixString + sym.nameString
+      
+      var str = monopart + (if (args.isEmpty) "" else args.mkString("[", ",", "]"))
       //if (sym.nameString startsWith "moduleType")
       //  str += ("_in_"+sym.ownerChain)
       if (sym.isPackageClass)
         packagePrefix + str
       else if (sym.isModuleClass)
         objectPrefix + str
-      else if (sym.isAnonymousClass && sym.isInitialized && !settings.debug.value)
-        thisInfo.parents.mkString("", " with ", "{ ... }")
+      else if (sym.isAnonymousClass && sym.isInitialized && !settings.debug.value && !phase.erasedTypes)
+        thisInfo.parents.mkString(" with ") + {
+          if (sym.isStructuralRefinement)
+            ((decls.toList filter { entry =>
+              !entry.isConstructor && entry.allOverriddenSymbols.isEmpty && !entry.hasFlag(PRIVATE)
+            }) map { entry => entry.defString }).mkString("{", "; ", "}") 
+          else
+            ""
+        }
       else if (sym.isRefinementClass && sym.isInitialized)
         thisInfo.toString
       else str
@@ -1589,7 +1895,7 @@ A type's typeSymbol should never be inspected directly.
                sym.isAnonymousClass || sym.isRefinementClass || sym.isScalaPackageClass) 
         ""
       else if (sym.isPackageClass) 
-        sym.fullNameString + "."
+        sym.fullName + "."
       else if (isStable && (sym.name.toString endsWith ".type")) 
         sym.name.toString.substring(0, sym.name.length - 4)
       else 
@@ -1598,51 +1904,85 @@ A type's typeSymbol should never be inspected directly.
       override def kind = "TypeRef"
   }
 
+  object TypeRef extends TypeRefExtractor {
+    def apply(pre: Type, sym: Symbol, args: List[Type]): Type = {
+      class rawTypeRef extends TypeRef(pre, sym, args) with UniqueType
+      unique(new rawTypeRef)
+    }
+  }
+
   /** A class representing a method type with parameters.
    */
-  case class MethodType(override val paramTypes: List[Type],
+  case class MethodType(override val params: List[Symbol],
                         override val resultType: Type) extends Type {
-    override val isTrivial: Boolean =
-      paramTypes.forall(_.isTrivial) && resultType.isTrivial
+    override def isTrivial: Boolean = isTrivial0
+    private lazy val isTrivial0 =
+      resultType.isTrivial && params.forall{p => p.tpe.isTrivial &&  (
+        !settings.YdepMethTpes.value || !(params.exists(_.tpe.contains(p)) || resultType.contains(p)))
+      }
+
+    def isImplicit = params.nonEmpty && params.head.isImplicit
+    def isJava = false // can we do something like for implicits? I.e. do Java methods without parameters need to be recognized?
 
     //assert(paramTypes forall (pt => !pt.typeSymbol.isImplClass))//DEBUG
     override def paramSectionCount: Int = resultType.paramSectionCount + 1
 
-    override def resultType(actuals: List[Type]) = {
-      val map = new InstantiateDeBruijnMap(actuals)
-      val rawResTpe = map.apply(resultType)
+    override def paramss: List[List[Symbol]] = params :: resultType.paramss
+    
+    override def paramTypes = params map (_.tpe)
 
-      if (phase.erasedTypes)
-	rawResTpe
-      else
-	existentialAbstraction(map.existentialsNeeded, rawResTpe)
+    override def boundSyms = params ::: resultType.boundSyms
+    
+    // this is needed for plugins to work correctly, only TypeConstraint annotations are supposed to be carried over
+    // TODO: this should probably be handled in a more structured way in adapt -- remove this map in resultType and watch the continuations tests fail
+    object dropNonContraintAnnotations extends TypeMap {
+      override val dropNonConstraintAnnotations = true
+      def apply(x: Type) = mapOver(x)
     }
 
+    override def resultType(actuals: List[Type]) = 
+      if(isTrivial) dropNonContraintAnnotations(resultType)
+      else {
+        if(actuals.length == params.length)  {
+          val idm = new InstantiateDependentMap(params, actuals)
+          val res = idm(resultType)
+          // println("resultTypeDep "+(params, actuals, resultType, idm.existentialsNeeded, "\n= "+ res))
+          existentialAbstraction(idm.existentialsNeeded, res)
+        } else {
+          // Thread.dumpStack()
+          // println("resultType "+(params, actuals, resultType))
+          if (phase.erasedTypes) resultType
+          else existentialAbstraction(params, resultType)
+        }
+      }
+
+    // implicit args can only be depended on in result type: TODO this may be generalised so that the only constraint is dependencies are acyclic
+    def approximate: MethodType = MethodType(params, resultApprox)
+
     override def finalResultType: Type = resultType.finalResultType
 
-    protected def paramPrefix = "("
+    override def safeToString: String =
+      params.map(_.defString).mkString("(", ",", ")") + resultType
 
-    private def dependentToString(base: Int): String = {
-      val params = for ((pt, n) <- paramTypes.zipWithIndex) yield "x$"+n+":"+pt
-      val res = resultType match {
-        case mt: MethodType => mt.dependentToString(base + params.length)
-        case rt => rt.toString
-      }
-      params.mkString(paramPrefix, ",", ")")+res
+    override def cloneInfo(owner: Symbol) = {
+      val vparams = cloneSymbols(params, owner)
+      copyMethodType(this, vparams, resultType.substSym(params, vparams).cloneInfo(owner))
     }
 
-    override def safeToString: String =
-      if (resultType.isDependent) dependentToString(0)
-      else paramTypes.mkString(paramPrefix, ",", ")") + resultType
+    override def atOwner(owner: Symbol) = 
+      if ((params exists (_.owner != owner)) || (resultType.atOwner(owner) ne resultType))
+        cloneInfo(owner) 
+      else
+        this
 
     override def kind = "MethodType"
   }
 
-  class ImplicitMethodType(pts: List[Type], rt: Type) extends MethodType(pts, rt) {
-    override protected def paramPrefix = "(implicit "
-  }
+  object MethodType extends MethodTypeExtractor
 
-  class JavaMethodType(pts: List[Type], rt: Type) extends MethodType(pts, rt)
+  class JavaMethodType(ps: List[Symbol], rt: Type) extends MethodType(ps, rt) {
+    override def isJava = true
+  }
 
   /** A class representing a polymorphic type or, if tparams.length == 0,
    *  a parameterless method type.
@@ -1655,14 +1995,17 @@ A type's typeSymbol should never be inspected directly.
    */
   case class PolyType(override val typeParams: List[Symbol], override val resultType: Type)
        extends Type {
+    // assert(!(typeParams contains NoSymbol), this)
 
     override def paramSectionCount: Int = resultType.paramSectionCount
+    override def paramss: List[List[Symbol]] = resultType.paramss
+    override def params: List[Symbol] = resultType.params
     override def paramTypes: List[Type] = resultType.paramTypes
     override def parents: List[Type] = resultType.parents
     override def decls: Scope = resultType.decls
     override def termSymbol: Symbol = resultType.termSymbol
     override def typeSymbol: Symbol = resultType.typeSymbol
-    override def boundSyms: List[Symbol] = typeParams
+    override def boundSyms: List[Symbol] = typeParams ::: resultType.boundSyms
     override def prefix: Type = resultType.prefix
     override def baseTypeSeq: BaseTypeSeq = resultType.baseTypeSeq
     override def baseTypeSeqDepth: Int = resultType.baseTypeSeqDepth
@@ -1670,11 +2013,6 @@ A type's typeSymbol should never be inspected directly.
     override def baseType(clazz: Symbol): Type = resultType.baseType(clazz)
     override def narrow: Type = resultType.narrow
     override def isVolatile = resultType.isVolatile
-    
-    override def deconst = 
-      if (inIDE) PolyType(typeParams, resultType.deconst)
-      else super.deconst
-
     override def finalResultType: Type = resultType.finalResultType
 
     /** @M: abstractTypeSig now wraps a TypeBounds in a PolyType 
@@ -1693,12 +2031,20 @@ A type's typeSymbol should never be inspected directly.
 
     override def cloneInfo(owner: Symbol) = {
       val tparams = cloneSymbols(typeParams, owner)
-      PolyType(tparams, resultType.substSym(typeParams, tparams))
+      PolyType(tparams, resultType.substSym(typeParams, tparams).cloneInfo(owner))
     }
 
+    override def atOwner(owner: Symbol) = 
+      if ((typeParams exists (_.owner != owner)) || (resultType.atOwner(owner) ne resultType))
+        cloneInfo(owner) 
+      else
+        this
+
     override def kind = "PolyType"
   }
 
+  object PolyType extends PolyTypeExtractor 
+
   case class ExistentialType(quantified: List[Symbol], 
                              override val underlying: Type) extends RewrappingTypeProxy
   {
@@ -1711,6 +2057,10 @@ A type's typeSymbol should never be inspected directly.
     override def boundSyms: List[Symbol] = quantified
     override def prefix = maybeRewrap(underlying.prefix)
     override def typeArgs = underlying.typeArgs map maybeRewrap
+    override def params = underlying.params mapConserve { param =>
+      val tpe1 = rewrap(param.tpe)
+      if (tpe1 eq param.tpe) param else param.cloneSymbol.setInfo(tpe1)
+    }
     override def paramTypes = underlying.paramTypes map maybeRewrap
     override def instantiateTypeParams(formals: List[Symbol], actuals: List[Type]) = {
 //      maybeRewrap(underlying.instantiateTypeParams(formals, actuals))
@@ -1741,7 +2091,7 @@ A type's typeSymbol should never be inspected directly.
     }
 
     private def wildcardArgsString(available: Set[Symbol], args: List[Type]): List[String] = args match {
-      case TypeRef(_, sym, _) :: args1 if (quantified contains sym) =>
+      case TypeRef(_, sym, _) :: args1 if (available contains sym) =>
         ("_"+sym.infoString(sym.info)) :: wildcardArgsString(available - sym, args1)
       case arg :: args1 if !(quantified exists (arg contains _)) =>
         arg.toString :: wildcardArgsString(available, args1) 
@@ -1774,20 +2124,26 @@ A type's typeSymbol should never be inspected directly.
       ExistentialType(tparams, underlying.substSym(quantified, tparams))
     }
 
+    override def atOwner(owner: Symbol) = 
+      if (quantified exists (_.owner != owner)) cloneInfo(owner) else this
+
     override def kind = "ExistentialType"
 
     def withTypeVars(op: Type => Boolean): Boolean = withTypeVars(op, AnyDepth)
 
     def withTypeVars(op: Type => Boolean, depth: Int): Boolean = {
-      val tvars = quantified map (tparam => new TypeVar(tparam.tpe, new TypeConstraint))
-      val underlying1 = underlying.instantiateTypeParams(quantified, tvars)
+      val quantifiedFresh = cloneSymbols(quantified)
+      val tvars = quantifiedFresh map (tparam => TypeVar(tparam))
+      val underlying1 = underlying.instantiateTypeParams(quantified, tvars) // fuse subst quantified -> quantifiedFresh -> tvars
       op(underlying1) && {
-        solve(tvars, quantified, quantified map (x => 0), false, depth) &&
-        isWithinBounds(NoPrefix, NoSymbol, quantified, tvars map (_.constr.inst))
+        solve(tvars, quantifiedFresh, quantifiedFresh map (x => 0), false, depth) &&
+        isWithinBounds(NoPrefix, NoSymbol, quantifiedFresh, tvars map (_.constr.inst))
       }
     }
   }
 
+  object ExistentialType extends ExistentialTypeExtractor 
+
   /** A class containing the alternatives and type prefix of an overloaded symbol.
    *  Not used after phase `typer'.
    */
@@ -1805,111 +2161,291 @@ A type's typeSymbol should never be inspected directly.
   case class AntiPolyType(pre: Type, targs: List[Type]) extends Type {
     override def safeToString =
       pre.toString + targs.mkString("(with type arguments ", ",", ")");
-    override def memberType(sym: Symbol) = pre.memberType(sym) match {
-      case PolyType(tparams, restp) => restp.subst(tparams, targs)
-      case ErrorType => ErrorType
-    }
+    override def memberType(sym: Symbol) = appliedType(pre.memberType(sym), targs)
+//     override def memberType(sym: Symbol) = pre.memberType(sym) match {
+//       case PolyType(tparams, restp) => 
+//         restp.subst(tparams, targs)
+// /* I don't think this is needed, as existential types close only over value types
+//       case ExistentialType(tparams, qtpe) => 
+//         existentialAbstraction(tparams, qtpe.memberType(sym))
+// */ 
+//       case ErrorType => 
+//         ErrorType
+//     }
     override def kind = "AntiPolyType"
   }
 
   //private var tidCount = 0  //DEBUG
 
+  //@M 
+  // a TypeVar used to be a case class with only an origin and a constr
+  // then, constr became mutable (to support UndoLog, I guess), but pattern-matching returned the original constr0 (a bug)
+  // now, pattern-matching returns the most recent constr
+  object TypeVar {
+    // encapsulate suspension so we can automatically link the suspension of cloned typevars to their original if this turns out to be necessary
+    def Suspension = new Suspension
+    class Suspension {
+      private val suspended = collection.mutable.HashSet[TypeVar]()
+      def suspend(tv: TypeVar): Unit = {
+        tv.suspended = true
+        suspended += tv
+      }
+      def resumeAll: Unit = {
+        for(tv <- suspended) {
+          tv.suspended = false
+        }
+        suspended.clear
+      }
+    }
+
+    def unapply(tv: TypeVar): Some[(Type, TypeConstraint)] = Some((tv.origin, tv.constr))
+    def apply(origin: Type, constr: TypeConstraint) = new TypeVar(origin, constr, List(), List())
+    def apply(tparam: Symbol) = new TypeVar(tparam.tpeHK, new TypeConstraint, List(), tparam.typeParams) // TODO why not initialise TypeConstraint with bounds of tparam?
+    def apply(origin: Type, constr: TypeConstraint, args: List[Type], params: List[Symbol]) = new TypeVar(origin, constr, args, params)
+  }
+  
   /** A class representing a type variable 
-   *  Not used after phase `typer'.
+   * Not used after phase `typer'.
+   * A higher-kinded type variable has type arguments (a list of Type's) and type parameters (list of Symbols)
+   * A TypeVar whose list of args is non-empty can only be instantiated by a higher-kinded type that can be applied to these args   
+   * a typevar is much like a typeref, except it has special logic for type equality/subtyping
    */
-  case class TypeVar(origin: Type, constr0: TypeConstraint) extends Type {
-
+  class TypeVar(val origin: Type, val constr0: TypeConstraint, override val typeArgs: List[Type], override val params: List[Symbol]) extends Type {
+    // params are needed to keep track of variance (see mapOverArgs in SubstMap)
+    assert(typeArgs.isEmpty || typeArgs.length == params.length)
     // var tid = { tidCount += 1; tidCount } //DEBUG
 
     /** The constraint associated with the variable */
     var constr = constr0
+    def instValid = constr.instValid
     
-    /** The variable's skolemizatuon level */
+    /** The variable's skolemization level */
     val level = skolemizationLevel
 
+    /**
+     *  two occurrences of a higher-kinded typevar, e.g. ?CC[Int] and ?CC[String], correspond to 
+     *  *two instances* of TypeVar that share the *same* TypeConstraint
+     *  constr for ?CC only tracks type constructors anyway, so when ?CC[Int] <:< List[Int] and ?CC[String] <:< Iterable[String]
+     *  ?CC's hibounds contains List and Iterable
+     */
+    def applyArgs(newArgs: List[Type]): TypeVar =
+      if(newArgs.isEmpty) this // SubstMap relies on this (though this check is redundant when called from appliedType...)
+      else TypeVar(origin, constr, newArgs, params) // @M TODO: interaction with undoLog??
+        // newArgs.length may differ from args.length (could've been empty before)
+      // example: when making new typevars, you start out with C[A], then you replace C by ?C, which should yield ?C[A], then A by ?A, ?C[?A]
+      // we need to track a TypeVar's arguments, and map over them (see TypeMap::mapOver)
+      // TypeVars get applied to different arguments over time (in asSeenFrom)
+       // -- see pos/tcpoly_infer_implicit_tuplewrapper.scala
+      // thus: make new TypeVar's for every application of a TV to args,
+      // inference may generate several TypeVar's for a single type parameter that must be inferred,
+      // only one of them is in the set of tvars that need to be solved, but
+      // they share the same TypeConstraint instance
+
+
     def setInst(tp: Type) {
 //      assert(!(tp containsTp this), this)
       constr.inst = tp
     }
 
-    def tryInstantiate(tp: Type): Boolean = 
-      if (constr.lobounds.forall(_ <:< tp) && constr.hibounds.forall(tp <:< _)) {
-        setInst(tp)
-        true
-      } else false
-
-    override def typeSymbol = origin.typeSymbol
-    override def safeToString: String = {
-      def varString = "?"+(if (settings.explaintypes.value) level else "")+origin// +"#"+tid //DEBUG
-      if (constr.inst eq null) "<null " + origin + ">"
-      else if (settings.debug.value) varString+constr.toString
-      else if (constr.inst eq NoType) varString
-      else constr.inst.toString
+    def addLoBound(tp: Type, numBound: Boolean = false) {
+      assert(tp != this) // implies there is a cycle somewhere (?)
+      //println("addLoBound: "+(safeToString, debugString(tp))) //DEBUG
+      constr.addLoBound(tp, numBound)
     }
-    override def isStable = origin.isStable
-    override def isVolatile = origin.isVolatile
-    override def kind = "TypeVar"
-  }
 
-  /** A type carrying some annotations.  The annotations have
-    * no significance to the core compiler, but can be observed
-    * by type-system plugins.  The core compiler does take care
-    * to propagate annotations and to save them in the symbol
-    * tables of object files.
-    *
-    * @param attributes the list of annotations on the type
-    * @param underlying the type without the annotation
-    * @param selfsym a "self" symbol with type <code>underlying</code>;
-    *                only available if -Yself-in-annots is
-    *                turned on.  Can be NoSymbol if it is not used.
-    */
-  case class AnnotatedType(override val attributes: List[AnnotationInfo], 
-                           override val underlying: Type,
-			   override val selfsym: Symbol) 
-  extends RewrappingTypeProxy {
+    def addHiBound(tp: Type, numBound: Boolean = false) {
+      // assert(tp != this)
+      //println("addHiBound: "+(safeToString, debugString(tp))) //DEBUG
+      constr.addHiBound(tp, numBound)
+    }
 
-    assert(!attributes.isEmpty)
+    // ignore subtyping&equality checks while true -- see findMember
+    private[TypeVar] var suspended = false
 
-    override protected def rewrap(tp: Type) = AnnotatedType(attributes, tp, selfsym)
+    /** Called from isSubtype0 when a TypeVar is involved in a subtyping check.
+     * if isLowerBound is true,
+     *   registerBound returns whether this TypeVar could plausibly be a supertype of tp and, 
+     *     if so, tracks tp as a lower bound of this type variable
+     *
+     * if isLowerBound is false,
+     *   registerBound returns whether this TypeVar could plausibly be a subtype of tp and, 
+     *     if so, tracks tp as a upper bound of this type variable
+     */
+    def registerBound(tp: Type, isLowerBound: Boolean, numBound: Boolean = false): Boolean = { //println("regBound: "+(safeToString, debugString(tp), isLowerBound)) //@MDEBUG
+      if(isLowerBound) assert(tp != this)
 
-    override def safeToString: String = {
-      val attString =
-        if (attributes.isEmpty)
-          ""
+      undoLog record this
+      
+      def checkSubtype(tp1: Type, tp2: Type) = 
+        if (numBound)
+          if (isLowerBound) tp1 weak_<:< tp2 
+          else              tp2 weak_<:< tp1
         else
-          attributes.mkString(" @", " @", "")
+          if(isLowerBound) tp1 <:< tp2 
+          else             tp2 <:< tp1
 
-      underlying + attString
+      def addBound(tp: Type) = { 
+        if (isLowerBound) addLoBound(tp, numBound)
+        else addHiBound(tp, numBound)
+        // println("addedBound: "+(this, tp)) // @MDEBUG
+      }
+
+      def checkArgs(args1: List[Type], args2: List[Type], params: List[Symbol]) =
+        if(isLowerBound) isSubArgs(args1, args2, params)
+        else             isSubArgs(args2, args1, params)
+
+      if (suspended) checkSubtype(tp, origin)
+      else if (constr.instValid) // type var is already set
+        checkSubtype(tp, constr.inst)
+      else isRelatable(tp) && { 
+        if(params.isEmpty) { // type var has kind *
+          addBound(tp)
+          true
+        } else { // higher-kinded type var with same arity as tp
+          def unifyHK(tp: Type) =
+            (typeArgs.length == tp.typeArgs.length) && {
+              // register type constructor (the type without its type arguments) as bound
+              addBound(tp.typeConstructor)
+              // check subtyping of higher-order type vars
+              // use variances as defined in the type parameter that we're trying to infer (the result is sanity-checked later)
+              checkArgs(tp.typeArgs, typeArgs, params)
+            }
+          unifyHK(tp) || unifyHK(tp.dealias)
+        }
+      }
     }
-    
-    /** Add a number of attributes to this type */
-    override def withAttributes(attribs: List[AnnotationInfo]): Type =
-      AnnotatedType(attribs:::this.attributes, this, selfsym)
 
-    /** Remove any attributes from this type */
-    override def withoutAttributes = underlying.withoutAttributes
+    def registerTypeEquality(tp: Type, typeVarLHS: Boolean): Boolean = { //println("regTypeEq: "+(safeToString, debugString(tp), typeVarLHS)) //@MDEBUG
+      def checkIsSameType(tp: Type) = 
+        if(typeVarLHS) constr.inst =:= tp
+        else           tp          =:= constr.inst
 
-    /** Set the self symbol */
-    override def withSelfsym(sym: Symbol) = 
-      AnnotatedType(attributes, underlying, sym)
+      if (suspended) tp =:= origin
+      else if (constr.instValid) checkIsSameType(tp)
+      else isRelatable(tp) && {
+        undoLog record this
 
-    /** Drop the annotations on the bounds, unless but the low and high bounds are
-     *  exactly tp. */
-    override def bounds: TypeBounds = {
-       val oftp = underlying.bounds
-       oftp match {
-         case TypeBounds(lo, hi) if ((lo eq this) && (hi eq this)) => mkTypeBounds(this,this)
-         case _ => oftp
-       }
+        val newInst = wildcardToTypeVarMap(tp)
+        if (constr.isWithinBounds(newInst)) {
+          setInst(tp)
+          true
+        } else false
+      }
     }
 
-    // ** Replace formal type parameter symbols with actual type arguments. * /
-    override def instantiateTypeParams(formals: List[Symbol], actuals: List[Type]) = {
-      val attributes1 = attributes.map(info => AnnotationInfo(info.atp.instantiateTypeParams(
-          formals, actuals), info.args, info.assocs))
+    /**
+     * ?A.T =:= tp is rewritten as the constraint ?A <: {type T = tp}
+     *
+     * TODO: make these constraints count (incorporate them into implicit search in applyImplicitArgs)
+     * (T corresponds to @param sym)
+     */
+    def registerTypeSelection(sym: Symbol, tp: Type): Boolean = {
+      val bound = refinedType(List(WildcardType), NoSymbol)
+      val bsym = bound.typeSymbol.newAliasType(NoPosition, sym.name)
+      bsym setInfo tp
+      bound.decls enter bsym
+      registerBound(bound, false)
+    }
+
+    /** Can this variable be related in a constraint to type `tp'?
+     *  This is not the case if `tp' contains type skolems whose
+     *  skolemization level is higher than the level of this variable.
+     */
+    def isRelatable(tp: Type): Boolean =
+      !tp.exists { t =>
+        t.typeSymbol match {
+          case ts: TypeSkolem => ts.level > level
+          case _ => false
+        }
+      }
+
+    override val isHigherKinded = typeArgs.isEmpty && !params.isEmpty
+
+    override def normalize: Type =
+      if  (constr.instValid) constr.inst
+      else if (isHigherKinded) {  // get here when checking higher-order subtyping of the typevar by itself (TODO: check whether this ever happens?)
+        // @M TODO: should not use PolyType, as that's the type of a polymorphic value -- we really want a type *function*
+        PolyType(params, applyArgs(params map (_.typeConstructor)))
+      } else {
+        super.normalize
+      }
+
+    override def typeSymbol = origin.typeSymbol
+    override def safeToString: String = {
+      def varString = "?"+(if (settings.explaintypes.value) level else "")+
+                          origin+
+                          (if(typeArgs.isEmpty) "" else (typeArgs map (_.safeToString)).mkString("[ ", ", ", " ]")) // +"#"+tid //DEBUG
+      if (constr.inst eq null) "<null " + origin + ">"
+      else if (settings.debug.value) varString+"(@"+constr.## +")"+constr.toString
+      else if (constr.inst eq NoType) varString
+      else constr.inst.toString
+    }
+    override def isStable = origin.isStable
+    override def isVolatile = origin.isVolatile
+    override def kind = "TypeVar"
+
+    def cloneInternal = {
+      assert(!suspended) // cloning a suspended type variable when it's suspended will cause the clone to never be resumed with the current implementation 
+      TypeVar(origin, constr cloneInternal, typeArgs, params) // @M TODO: clone args/params?
+    }
+  }
+
+  /** A type carrying some annotations. Created by the typechecker
+   *  when eliminating ``Annotated'' trees (see typedAnnotated).
+   *
+   *  @param annotations the list of annotations on the type
+   *  @param underlying the type without the annotation
+   *  @param selfsym a "self" symbol with type <code>underlying</code>;
+   *    only available if -Yself-in-annots is turned on. Can be NoSymbol
+   *    if it is not used.
+   */
+  case class AnnotatedType(override val annotations: List[AnnotationInfo], 
+                           override val underlying: Type,
+                           override val selfsym: Symbol) 
+  extends RewrappingTypeProxy {
+
+    assert(!annotations.isEmpty)
+
+    override protected def rewrap(tp: Type) = AnnotatedType(annotations, tp, selfsym)
+
+    override def safeToString: String = {
+      val attString =
+        if (annotations.isEmpty)
+          ""
+        else
+          annotations.mkString(" @", " @", "")
+
+      underlying + attString
+    }
+    
+    /** Add a number of annotations to this type */
+    override def withAnnotations(annots: List[AnnotationInfo]): Type =
+      copy(annots:::this.annotations)
+
+    /** Remove any annotations from this type */
+    override def withoutAnnotations = underlying.withoutAnnotations
+
+    /** Set the self symbol */
+    override def withSelfsym(sym: Symbol) = 
+      AnnotatedType(annotations, underlying, sym)
+
+    /** Drop the annotations on the bounds, unless but the low and high bounds are
+     *  exactly tp. */
+    override def bounds: TypeBounds = {
+       val oftp = underlying.bounds
+       oftp match {
+         case TypeBounds(lo, hi) if ((lo eq this) && (hi eq this)) => TypeBounds(this,this)
+         case _ => oftp
+       }
+    }
+
+    // ** Replace formal type parameter symbols with actual type arguments. * /
+    override def instantiateTypeParams(formals: List[Symbol], actuals: List[Type]) = {
+      val annotations1 = annotations.map(info => AnnotationInfo(info.atp.instantiateTypeParams(
+          formals, actuals), info.args, info.assocs).setPos(info.pos))
       val underlying1 = underlying.instantiateTypeParams(formals, actuals)
-      if ((attributes1 eq attributes) && (underlying1 eq underlying)) this
-      else AnnotatedType(attributes1, underlying1, selfsym)
+      if ((annotations1 eq annotations) && (underlying1 eq underlying)) this
+      else AnnotatedType(annotations1, underlying1, selfsym)
     }
 
     /** Return the base type sequence of tp, dropping the annotations, unless the base type sequence of tp
@@ -1925,12 +2461,19 @@ A type's typeSymbol should never be inspected directly.
     override def kind = "AnnotatedType"
   }
 
+  object AnnotatedType extends AnnotatedTypeExtractor
+
+  /** A class representing types with a name. When an application uses
+   *  named arguments, the named argument types for calling isApplicable
+   *  are represented as NamedType.
+   */
+  case class NamedType(name: Name, tp: Type) extends Type {
+    override def safeToString: String = name.toString +": "+ tp
+  }
+
   /** A class representing an as-yet unevaluated type.
    */
-  abstract class LazyType extends Type {
-    override def isComplete: Boolean = false
-    override def complete(sym: Symbol)
-    override def safeToString = "<?>"
+  abstract class LazyType extends Type with AbsLazyType {
     override def kind = "LazyType"
   }
 
@@ -1941,7 +2484,7 @@ A type's typeSymbol should never be inspected directly.
    */
   private def rebind(pre: Type, sym: Symbol): Symbol = {
     val owner = sym.owner
-    if (owner.isClass && owner != pre.typeSymbol && !sym.isFinal && !sym.isClass) {
+    if (owner.isClass && owner != pre.typeSymbol && !sym.isEffectivelyFinal && !sym.isClass) {
       //Console.println("rebind "+pre+" "+sym)//DEBUG
       val rebind = pre.nonPrivateMember(sym.name).suchThat(sym => sym.isType || sym.isStable)
       if (rebind == NoSymbol) sym 
@@ -1957,56 +2500,24 @@ A type's typeSymbol should never be inspected directly.
    */
   private def removeSuper(tp: Type, sym: Symbol): Type = tp match {
     case SuperType(thistp, _) =>
-      if (sym.isFinal || sym.isDeferred) thistp
+      if (sym.isEffectivelyFinal || sym.isDeferred) thistp
       else tp
     case _ =>
       tp
   }
 
-  /** The canonical creator for this-types */
-  def mkThisType(sym: Symbol): Type = {
-    class UniqueThisType extends ThisType(sym) with UniqueType
-    if (phase.erasedTypes) sym.tpe else unique(new UniqueThisType)
-  }
-
   /** The canonical creator for single-types */
   def singleType(pre: Type, sym: Symbol): Type = {
     if (phase.erasedTypes)
       sym.tpe.resultType
     else if (sym.isRootPackage)
-      mkThisType(RootClass)
+      ThisType(RootClass)
     else {
       var sym1 = rebind(pre, sym)
       val pre1 = removeSuper(pre, sym1)
       if (pre1 ne pre) sym1 = rebind(pre1, sym1)
-      if (checkMalformedSwitch && !pre1.isStable && !pre1.isError)
-        throw new MalformedType(pre, sym.nameString)
-      else {
-        class UniqueSingleType extends SingleType(pre1, sym1) with UniqueType
-        unique(new UniqueSingleType)
-      }
-    }
-  }
-
-  /** The canonical creator for super-types */
-  def mkSuperType(thistp: Type, supertp: Type): Type =
-    if (phase.erasedTypes) supertp
-    else {
-      class UniqueSuperType extends SuperType(thistp, supertp) with UniqueType
-      unique(new UniqueSuperType)
+      unique(new SingleType(pre1, sym1) with UniqueType)
     }
-
-  /** The canonical creator for type bounds */
-  def mkTypeBounds(lo: Type, hi: Type): TypeBounds = {
-    class UniqueTypeBounds extends TypeBounds(lo, hi) with UniqueType
-    unique(new UniqueTypeBounds)
-  }
-
-  def refinementOfClass(clazz: Symbol, parents: List[Type], decls: Scope) = {
-    class RefinementOfClass extends RefinedType(parents, decls) {
-      override def typeSymbol: Symbol = clazz 
-    }
-    new RefinementOfClass
   }
 
   /** the canonical creator for a refined type with a given scope */
@@ -2014,13 +2525,10 @@ A type's typeSymbol should never be inspected directly.
     if (phase.erasedTypes)
       if (parents.isEmpty) ObjectClass.tpe else parents.head
     else { 
-      val clazz = recycle(owner.newRefinementClass(if (inIDE) pos else NoPosition))
-      if (!inIDE || !parents.isEmpty) {
-        val result = refinementOfClass(clazz, parents, decls)
-        clazz.setInfo(result)
-        result
-      } else clazz.info
-      //result
+      val clazz = owner.newRefinementClass(NoPosition)
+      val result = RefinedType(parents, decls, clazz)
+      clazz.setInfo(result)
+      result
     }
   }
 
@@ -2031,7 +2539,7 @@ A type's typeSymbol should never be inspected directly.
    *  @return        ...
    */
   def refinedType(parents: List[Type], owner: Symbol): Type =
-    refinedType(parents, owner, newTempScope, owner.pos)
+    refinedType(parents, owner, new Scope, owner.pos)
 
   def copyRefinedType(original: RefinedType, parents: List[Type], decls: Scope) =
     if ((parents eq original.parents) && (decls eq original.decls)) original
@@ -2048,67 +2556,60 @@ A type's typeSymbol should never be inspected directly.
       result
     }
 
-  /** the canonical creator for a constant type */
-  def mkConstantType(value: Constant): ConstantType = {
-    class UniqueConstantType extends ConstantType(value) with UniqueType {
-      /** Save the type of 'value'. For Java enums, it depends on finding the linked class,
-       *  which might not be found after 'flatten'. */
-      private lazy val _tpe: Type = value.tpe
-      override def underlying: Type = _tpe
-    }
-    unique(new UniqueConstantType)
-  }
-
   /** The canonical creator for typerefs 
    *  todo: see how we can clean this up a bit
    */
   def typeRef(pre: Type, sym: Symbol, args: List[Type]): Type = {
-    var sym1 = if (sym.isAbstractType) rebind(pre, sym) else sym
-    def transform(tp: Type): Type = 
+    def rebindTR(pre: Type, sym: Symbol): Symbol = {
+      if(sym.isAbstractType) rebind(pre, sym) else sym
+         // type alias selections are rebound in TypeMap ("coevolved", actually -- see #3731)
+         // e.g., when type parameters that are referenced by the alias are instantiated in the prefix
+         // see pos/depmet_rebind_typealias
+    }
+    val sym1 = rebindTR(pre, sym)
+
+    def transform(tp: Type): Type =
       tp.resultType.asSeenFrom(pre, sym1.owner).instantiateTypeParams(sym1.typeParams, args)
+
     if (sym1.isAliasType && sym1.info.typeParams.length == args.length) {
+      if (!sym1.lockOK)
+        throw new TypeError("illegal cyclic reference involving " + sym1)
       // note: we require that object is initialized,
       // that's why we use info.typeParams instead of typeParams.
+/*
       sym1.lock {
         throw new TypeError("illegal cyclic reference involving " + sym1)
       }
       transform(sym1.info) // check there are no cycles
       sym1.unlock()
- 
-      rawTypeRef(pre, sym1, args) // don't expand type alias (cycles checked above)
+*/ 
+      TypeRef(pre, sym1, args) // don't expand type alias (cycles checked above)
     } else {
       val pre1 = removeSuper(pre, sym1)
       if (pre1 ne pre) {
-        if (sym1.isAbstractType) sym1 = rebind(pre1, sym1)
-        typeRef(pre1, sym1, args)
-      } else if (checkMalformedSwitch && !pre.isStable && !pre.isError &&
-                 (sym1.isAbstractType /* || !pre.widen.typeSymbol.isStableClass*/)) {
-        throw new MalformedType(pre, sym1.nameString)
-      } else if (sym1.isClass && pre.isInstanceOf[CompoundType]) {
+        typeRef(pre1, rebindTR(pre1, sym1), args)
+      } 
+      else if (sym1.isClass && pre.isInstanceOf[CompoundType]) {
         // sharpen prefix so that it is maximal and still contains the class.
         var p = pre.parents.reverse
         while (!p.isEmpty && p.head.member(sym1.name) != sym1) p = p.tail
-        if (p.isEmpty) rawTypeRef(pre, sym1, args)
+        if (p.isEmpty) TypeRef(pre, sym1, args)
         else typeRef(p.head, sym1, args)
       } else {
-        rawTypeRef(pre, sym1, args)
+        TypeRef(pre, sym1, args)
       }
     }
   }
 
-  /** create a type-ref as found, without checks or rebinds */
-  def rawTypeRef(pre: Type, sym: Symbol, args: List[Type]): Type = {
-    class rawTypeRef extends TypeRef(pre, sym, args) with UniqueType
-    unique(new rawTypeRef)
-  }
-
   /** The canonical creator for implicit method types */
-  def ImplicitMethodType(paramTypes: List[Type], resultType: Type): ImplicitMethodType =
-    new ImplicitMethodType(paramTypes, resultType) // don't unique this!
+  def JavaMethodType(params: List[Symbol], resultType: Type): JavaMethodType =
+    new JavaMethodType(params, resultType) // don't unique this!
 
-  /** The canonical creator for implicit method types */
-  def JavaMethodType(paramTypes: List[Type], resultType: Type): JavaMethodType =
-    new JavaMethodType(paramTypes, resultType) // don't unique this!
+  /** Create a new MethodType of the same class as tp, i.e. keep JavaMethodType */
+  def copyMethodType(tp: Type, params: List[Symbol], restpe: Type): Type = tp match {
+    case _: JavaMethodType => JavaMethodType(params, restpe)
+    case _ => MethodType(params, restpe)
+  }
 
   /** A creator for intersection type where intersections of a single type are
    *  replaced by the type itself, and repeated parent classes are merged.
@@ -2146,13 +2647,18 @@ A type's typeSymbol should never be inspected directly.
   def appliedType(tycon: Type, args: List[Type]): Type =  
     if (args.isEmpty) tycon //@M! `if (args.isEmpty) tycon' is crucial (otherwise we create new types in phases after typer and then they don't get adapted (??))
     else tycon match { 
-      case TypeRef(pre, sym, _) => typeRef(pre, sym, args)
+      case TypeRef(pre, sym, _) => 
+        val args1 = if(sym == NothingClass || sym == AnyClass) List() else args //@M drop type args to Any/Nothing
+        typeRef(pre, sym, args1)
       case PolyType(tparams, restpe) => restpe.instantiateTypeParams(tparams, args)
       case ExistentialType(tparams, restpe) => ExistentialType(tparams, appliedType(restpe, args))
-      case ErrorType => tycon
       case st: SingletonType => appliedType(st.widen, args) // @M TODO: what to do? see bug1
       case RefinedType(parents, decls) => RefinedType(parents map (appliedType(_, args)), decls) // MO to AM: please check
-      case _ => throw new Error(debugString(tycon))
+      case TypeBounds(lo, hi) => TypeBounds(appliedType(lo, args), appliedType(hi, args))
+      case tv at TypeVar(_, constr) => tv.applyArgs(args)
+      case ErrorType => tycon
+      case WildcardType => tycon // needed for neg/t0226
+      case _ => abort(debugString(tycon))
     }
 
   /** A creator for type parameterizations 
@@ -2175,26 +2681,30 @@ A type's typeSymbol should never be inspected directly.
    *  (minus any SingletonClass markers),
    *  type variables in `tparams' occurring in contravariant positions are replaced by upper bounds,
    *  provided the resulting type is legal wrt to stability, and does not contain any
-   *  type varianble in `tparams'.
+   *  type variable in `tparams'.
    *  The abstraction drops all type parameters that are not directly or indirectly 
    *  referenced by type `tpe1'.
    *  If there are no remaining type parameters, simply returns result type `tpe'. 
    */
-  def existentialAbstraction(tparams: List[Symbol], tpe: Type): Type = 
-    if (tparams.isEmpty) tpe
+  def existentialAbstraction(tparams: List[Symbol], tpe0: Type): Type = 
+    if (tparams.isEmpty) tpe0
     else {
       var occurCount = emptySymCount ++ (tparams map (_ -> 0))
-      for (t <- tpe) {
-        t match {
-          case TypeRef(_, sym, _) =>
-            occurCount get sym match {
-              case Some(count) => occurCount += (sym -> (count + 1))
-              case None =>
-            }
-          case _ =>
+      val tpe = deAlias(tpe0)
+      def countOccs(tp: Type) =
+        for (t <- tp) {
+          t match {
+            case TypeRef(_, sym, _) =>
+              occurCount get sym match {
+                case Some(count) => occurCount += (sym -> (count + 1))
+                case none =>
+              }
+            case _ =>
+          }
         }
-      }
-	  
+      countOccs(tpe)
+      for (tparam <- tparams) countOccs(tparam.info)
+          
       val extrapolate = new TypeMap {
         variance = 1
         def apply(tp: Type): Type = {
@@ -2205,29 +2715,35 @@ A type's typeSymbol should never be inspected directly.
               //println("eliminate "+sym+"/"+repl+"/"+occurCount(sym)+"/"+(tparams exists (repl.contains)))//DEBUG
               if (repl.typeSymbol != NothingClass && repl.typeSymbol != NullClass && 
                   occurCount(sym) == 1 && !(tparams exists (repl.contains)))
-		repl
+                repl
               else tp1
             case _ =>
               tp1
           }
         }
-	override def mapOver(tree: Tree) = 
-	  tree match {
-	    case tree:Ident
-	    if tree.tpe.isStable
-	    =>
+        override def mapOver(tp: Type): Type = tp match {
+          case SingleType(pre, sym) =>
+            if (sym.isPackageClass) tp // short path
+            else {
+              val pre1 = this(pre)
+              if ((pre1 eq pre) || !pre1.isStable) tp
+              else singleType(pre1, sym)
+            }
+          case _ => super.mapOver(tp)
+        }
+
+        override def mapOver(tree: Tree) = 
+          tree match {
+            case tree:Ident if tree.tpe.isStable =>
               // Do not discard the types of existential ident's.
-	      // The symbol of the Ident itself cannot be listed
+              // The symbol of the Ident itself cannot be listed
               // in the existential's parameters, so the
-	      // resulting existential type would be ill-formed.
-	      Some(tree)
-
-	    case _ =>
-	      super.mapOver(tree)
-	  }
-
-
+              // resulting existential type would be ill-formed.
+              Some(tree)
 
+            case _ =>
+              super.mapOver(tree)
+          }
       }
       val tpe1 = extrapolate(tpe)
       var tparams0 = tparams
@@ -2246,6 +2762,16 @@ A type's typeSymbol should never be inspected directly.
       }
     }
 
+  /** Remove any occurrences of type aliases from this type */
+  object deAlias extends TypeMap {
+    def apply(tp: Type): Type = mapOver {
+      tp match {
+        case TypeRef(pre, sym, args) if sym.isAliasType => tp.normalize
+        case _ => tp
+      }
+    }
+  }
+
   /** Remove any occurrence of type <singleton> from this type and its parents */
   object dropSingletonType extends TypeMap {
     def apply(tp: Type): Type = {
@@ -2265,44 +2791,81 @@ A type's typeSymbol should never be inspected directly.
   
 // Hash consing --------------------------------------------------------------
 
+  private val initialUniquesCapacity = 4096
   private var uniques: HashSet[AnyRef] = _
   private var uniqueRunId = NoRunId
 
-  def uniqueTypeCount = uniques.size // for statistics
-
   private def unique[T <: AnyRef](tp: T): T = {
+    incCounter(rawTypeCount)
     if (uniqueRunId != currentRunId) {
-      uniques = new HashSet(20000)
+      uniques = new HashSet("uniques", initialUniquesCapacity)
       uniqueRunId = currentRunId
     }
-    val tp1 = uniques.findEntry(tp)
-    if (tp1 eq null) {
-      uniques.addEntry(tp); tp
-    } else {
-      tp1.asInstanceOf[T]
-    }
+    (uniques findEntryOrUpdate tp).asInstanceOf[T]
   }
 
 // Helper Classes ---------------------------------------------------------
 
-  /** A class expressing upper and lower bounds constraints 
-   *  for type variables, as well as their instantiations */
-  class TypeConstraint(lo: List[Type], hi: List[Type]) {
-    //var self: Type = _ //DEBUG
+  /** A class expressing upper and lower bounds constraints of type variables, 
+   * as well as their instantiations.
+   */
+  class TypeConstraint(lo0: List[Type], hi0: List[Type], numlo0: Type, numhi0: Type) { 
+    def this(lo0: List[Type], hi0: List[Type]) = this(lo0, hi0, NoType, NoType)
     def this() = this(List(), List())
-    var lobounds: List[Type] = lo
-    var hibounds: List[Type] = hi
-    var inst: Type = NoType
 
-    def duplicate = {
-      val tc = new TypeConstraint(lo, hi)
+    private var lobounds = lo0
+    private var hibounds = hi0
+    private var numlo = numlo0
+    private var numhi = numhi0
+
+    def loBounds: List[Type] = if (numlo == NoType) lobounds else numlo :: lobounds
+    def hiBounds: List[Type] = if (numhi == NoType) hibounds else numhi :: hibounds
+
+/* not needed 
+    def numLoBound: Type = numlo
+    def numHiBound: Type = numhi
+    def nonNumLoBounds: List[Type] = lobounds
+    def nonNumHiBounds: List[Type] = hibounds
+*/
+
+    def addLoBound(tp: Type, numBound: Boolean = false) {
+      if (numBound && isNumericValueType(tp)) { 
+        if (numlo == NoType || isNumericSubType(numlo, tp)) numlo = tp
+        else if (!isNumericSubType(tp, numlo)) numlo = IntClass.tpe
+      } else {
+        lobounds = tp :: lobounds
+      }
+    }
+
+    def addHiBound(tp: Type, numBound: Boolean = false) {
+      if (numBound && isNumericValueType(tp)) {
+        if (numhi == NoType || isNumericSubType(tp, numhi)) numhi = tp
+        else if (!isNumericSubType(numhi, tp)) numhi = intersectionType(List(ByteClass.tpe, CharClass.tpe), ScalaPackageClass)
+      } else {
+        hibounds = tp :: hibounds
+      }
+    }
+
+    def isWithinBounds(tp: Type): Boolean =
+      lobounds.forall(_ <:< tp) && 
+      hibounds.forall(tp <:< _) &&
+      (numlo == NoType || (numlo weak_<:< tp)) &&
+      (numhi == NoType || (tp weak_<:< numhi))
+
+    var inst: Type = NoType // @M reduce visibility?
+
+    def instValid = (inst ne null) && (inst ne NoType)
+
+    def cloneInternal = {
+      val tc = new TypeConstraint(lobounds, hibounds, numlo, numhi)
       tc.inst = inst
       tc
     }
-
+    
     override def toString =
-      lobounds.mkString("[ _>:(", ",", ") ") +
-      hibounds.mkString("| _<:(", ",", ") ] _= ") + inst
+      (loBounds map (_.safeToString)).mkString("[ _>:(", ",", ") ") +
+      (hiBounds map (_.safeToString)).mkString("| _<:(", ",", ") ] _= ") + 
+      inst.safeToString
   }
 
   /** A prototype for mapping a function over all possible types
@@ -2324,23 +2887,50 @@ A type's typeSymbol should never be inspected directly.
     /** Check whether two lists have elements that are eq-equal */
     def allEq[T <: AnyRef](l1: List[T], l2: List[T]): Boolean =
       (l1, l2) match {
-	case (Nil, Nil) => true
-	case (hd1::tl1, hd2::tl2) =>
-	  if (!(hd1 eq hd2))
-	    return false
-	  allEq(tl1, tl2)
-	case _ => false
+        case (Nil, Nil) => true
+        case (hd1::tl1, hd2::tl2) =>
+          if (!(hd1 eq hd2))
+            return false
+          allEq(tl1, tl2)
+        case _ => false
       }
 
+    // #3731: return sym1 for which holds: pre bound sym.name to sym and pre1 now binds sym.name to sym1, conceptually exactly the same symbol as sym
+    // the selection of sym on pre must be updated to the selection of sym1 on pre1,
+    // since sym's info was probably updated by the TypeMap to yield a new symbol sym1 with transformed info
+    // @returns sym1
+    protected def coevolveSym(pre: Type, pre1: Type, sym: Symbol): Symbol =
+      if((pre ne pre1) && sym.isAliasType) // only need to rebind type aliases here, as typeRef already handles abstract types (they are allowed to be rebound more liberally)
+        (pre, pre1) match {
+          case (RefinedType(_, decls), RefinedType(_, decls1)) => // don't look at parents -- it would be an error to override alias types anyway
+            //val sym1 =
+            decls1.lookup(sym.name)
+//            assert(decls.lookupAll(sym.name).toList.length == 1)
+//            assert(decls1.lookupAll(sym.name).toList.length == 1)
+//            assert(sym1.isAliasType)
+//            println("coevolved "+ sym +" : "+ sym.info +" to "+ sym1 +" : "+ sym1.info +" with "+ pre +" -> "+ pre1)
+//            sym1
+          case _ => // TODO: is there another way a typeref's symbol can refer to a symbol defined in its pre?
+//            val sym1 = pre1.nonPrivateMember(sym.name).suchThat(sym => sym.isAliasType)
+//            println("??coevolve "+ sym +" : "+ sym.info +" to "+ sym1 +" : "+ sym1.info +" with "+ pre +" -> "+ pre1)
+            sym
+        }
+      else sym
+
     /** Map this function over given type */
     def mapOver(tp: Type): Type = tp match {
-      case ErrorType => tp
-      case WildcardType => tp
-      case NoType => tp
-      case NoPrefix => tp
+      case TypeRef(pre, sym, args) =>
+        val pre1 = this(pre)
+        //val args1 = args mapConserve this(_)
+        val args1 = if (args.isEmpty) args
+                    else {
+                      val tparams = sym.typeParams
+                      if (tparams.isEmpty) args
+                      else mapOverArgs(args, tparams)
+                    }
+        if ((pre1 eq pre) && (args1 eq args)) tp
+        else typeRef(pre1, coevolveSym(pre, pre1, sym), args1) 
       case ThisType(_) => tp
-      case ConstantType(_) => tp
-      case DeBruijnIndex(_, _) => tp
       case SingleType(pre, sym) =>
         if (sym.isPackageClass) tp // short path
         else {
@@ -2348,60 +2938,45 @@ A type's typeSymbol should never be inspected directly.
           if (pre1 eq pre) tp
           else singleType(pre1, sym)
         }
+      case MethodType(params, result) =>
+        variance = -variance
+        val params1 = mapOver(params)
+        variance = -variance
+        val result1 = this(result)
+        if ((params1 eq params) && (result1 eq result)) tp
+        // for new dependent types: result1.substSym(params, params1)?
+        else copyMethodType(tp, params1, result1.substSym(params, params1))
+      case PolyType(tparams, result) =>
+        variance = -variance
+        val tparams1 = mapOver(tparams)
+        variance = -variance
+        var result1 = this(result)
+        if ((tparams1 eq tparams) && (result1 eq result)) tp
+        else PolyType(tparams1, result1.substSym(tparams, tparams1))
+      case ConstantType(_) => tp
+      // case DeBruijnIndex(_, _) => tp
       case SuperType(thistp, supertp) =>
         val thistp1 = this(thistp)
         val supertp1 = this(supertp)
         if ((thistp1 eq thistp) && (supertp1 eq supertp)) tp
-        else mkSuperType(thistp1, supertp1)
-      case TypeRef(pre, sym, args) =>
-        val pre1 = this(pre)
-        //val args1 = List.mapConserve(args)(this)
-        val args1 = if (args.isEmpty) args
-                    else {
-                      val tparams = sym.typeParams
-                      if (tparams.isEmpty) args
-                      else mapOverArgs(args, tparams)
-                    }
-        if ((pre1 eq pre) && (args1 eq args)) tp
-        else typeRef(pre1, sym, args1)
+        else SuperType(thistp1, supertp1)
       case TypeBounds(lo, hi) =>
         variance = -variance
         val lo1 = this(lo)
         variance = -variance
         val hi1 = this(hi)
         if ((lo1 eq lo) && (hi1 eq hi)) tp
-        else mkTypeBounds(lo1, hi1)
+        else TypeBounds(lo1, hi1)
       case BoundedWildcardType(bounds) =>
         val bounds1 = this(bounds)
         if (bounds1 eq bounds) tp
         else BoundedWildcardType(bounds1.asInstanceOf[TypeBounds])
       case rtp @ RefinedType(parents, decls) =>
-        val parents1 = List.mapConserve(parents)(this)
+        val parents1 = parents mapConserve (this)
         val decls1 = mapOver(decls)
         //if ((parents1 eq parents) && (decls1 eq decls)) tp
         //else refinementOfClass(tp.typeSymbol, parents1, decls1)
         copyRefinedType(rtp, parents1, decls1)
-/*
-      case ClassInfoType(parents, decls, clazz) =>
-        val parents1 = List.mapConserve(parents)(this);
-        val decls1 = mapOver(decls);
-        if ((parents1 eq parents) && (decls1 eq decls)) tp
-        else cloneDecls(ClassInfoType(parents1, new Scope(), clazz), tp, decls1)
-*/
-      case MethodType(paramtypes, result) =>
-        variance = -variance
-        val paramtypes1 = List.mapConserve(paramtypes)(this)
-        variance = -variance
-        val result1 = this(result)
-        if ((paramtypes1 eq paramtypes) && (result1 eq result)) tp
-        else copyMethodType(tp, paramtypes1, result1)
-      case PolyType(tparams, result) =>
-        variance = -variance
-        val tparams1 = mapOver(tparams)
-        variance = -variance
-        var result1 = this(result)
-        if ((tparams1 eq tparams) && (result1 eq result)) tp
-        else PolyType(tparams1, result1.substSym(tparams, tparams1))
       case ExistentialType(tparams, result) =>
         val tparams1 = mapOver(tparams)
         var result1 = this(result)
@@ -2413,12 +2988,12 @@ A type's typeSymbol should never be inspected directly.
         else OverloadedType(pre1, alts)
       case AntiPolyType(pre, args) =>
         val pre1 = this(pre)
-        val args1 = List.mapConserve(args)(this)
+        val args1 = args mapConserve (this)
         if ((pre1 eq pre) && (args1 eq args)) tp
         else AntiPolyType(pre1, args1)
-      case TypeVar(_, constr) =>
-        if (constr.inst != NoType) this(constr.inst)
-        else tp
+      case tv at TypeVar(_, constr) =>
+        if (constr.instValid) this(constr.inst)
+        else tv.applyArgs(mapOverArgs(tv.typeArgs, tv.params))  //@M !args.isEmpty implies !typeParams.isEmpty 
       case NotNullType(tp) =>
         val tp1 = this(tp)
         if (tp1 eq tp) tp
@@ -2429,6 +3004,12 @@ A type's typeSymbol should never be inspected directly.
         if ((annots1 eq annots) && (atp1 eq atp)) tp
         else if (annots1.isEmpty) atp1
         else AnnotatedType(annots1, atp1, selfsym)
+/*
+      case ErrorType => tp
+      case WildcardType => tp
+      case NoType => tp
+      case NoPrefix => tp
+*/
       case _ =>
         tp
         // throw new Error("mapOver inapplicable for " + tp);
@@ -2445,11 +3026,11 @@ A type's typeSymbol should never be inspected directly.
       }
 
     /** Map this function over given scope */
-    private def mapOver(scope: Scope): Scope = {
+    def mapOver(scope: Scope): Scope = {
       val elems = scope.toList
       val elems1 = mapOver(elems)
       if (elems1 eq elems) scope
-      else newScope(elems1)
+      else new Scope(elems1)
     }
 
     /** Map this function over given list of symbols */
@@ -2465,10 +3046,9 @@ A type's typeSymbol should never be inspected directly.
       else { // map is not the identity --> do cloning properly
         val clonedSyms = origSyms map (_.cloneSymbol)
         val clonedInfos = clonedSyms map (_.info.substSym(origSyms, clonedSyms))
-        val transformedInfos = List.mapConserve(clonedInfos)(this)
-        List.map2(clonedSyms, transformedInfos) { 
-          ((newSym, newInfo) => newSym.setInfo(newInfo)) 
-        }
+        val transformedInfos = clonedInfos mapConserve (this)
+        (clonedSyms, transformedInfos).zipped map (_ setInfo _)
+        
         clonedSyms
       }
     }
@@ -2478,61 +3058,42 @@ A type's typeSymbol should never be inspected directly.
     : List[AnnotationInfo] = {
       val newAnnots = annots.flatMap(mapOver(_))
       if (allEq(newAnnots, annots))
-	annots
+        annots
       else
-	newAnnots
+        newAnnots
     }
 
-
     def mapOver(annot: AnnotationInfo): Option[AnnotationInfo] = {
       val AnnotationInfo(atp, args, assocs) = annot
 
       if (dropNonConstraintAnnotations &&
-	  !(atp.typeSymbol isNonBottomSubClass TypeConstraintClass))
-	return None
+          !(atp.typeSymbol isNonBottomSubClass TypeConstraintClass))
+        return None
 
       val atp1 = mapOver(atp)
-      val args1 = mapOverAnnotationArgs(args)
-      // there is no need to rewrite assocs, as they should be constants
+      val args1 = mapOverAnnotArgs(args)
+      // there is no need to rewrite assocs, as they are constants
 
       if ((args eq args1) && (atp eq atp1))
-	Some(annot)
+        Some(annot)
       else if (args1.length == args.length)
-	Some(AnnotationInfo(atp1, args1, assocs))
+        Some(AnnotationInfo(atp1, args1, assocs).setPos(annot.pos))
       else
-	None
+        None
     }
 
     /** Map over a set of annotation arguments.  If any
      *  of the arguments cannot be mapped, then return Nil.  */
-    def mapOverAnnotationArgs(args: List[AnnotationArgument])
-    : List[AnnotationArgument] = {
+    def mapOverAnnotArgs(args: List[Tree]): List[Tree] = {
       val args1 = args.flatMap(mapOver(_))
       if (args1.length != args.length)
-	Nil
+        Nil
       else if (allEq(args, args1))
-	args
+        args
       else
-	args1
-    }
-
-
-    def mapOver(arg: AnnotationArgument): Option[AnnotationArgument] = {
-      if (arg.isConstant)
-	Some(arg)
-      else {
-	mapOver(arg.intTree) match {
-	  case None => None
-
-	  case Some(tree1)
-	  if (tree1 eq arg.intTree) => Some(arg)
-
-	  case Some(tree1) => Some(new AnnotationArgument(tree1))
-	}
-      }
+        args1
     }
 
-
     def mapOver(tree: Tree): Option[Tree] =
       Some(mapOver(tree, ()=>return None))
 
@@ -2551,17 +3112,11 @@ A type's typeSymbol should never be inspected directly.
         val tree1 = super.transform(tree)
         val tpe1 = TypeMap.this(tree1.tpe)
         if ((tree eq tree1) && (tree.tpe eq tpe1))
-	  tree
-	else
-	  tree1.shallowDuplicate.setType(tpe1)
+          tree
+        else
+          tree1.shallowDuplicate.setType(tpe1)
       }
     }
-
-    protected def copyMethodType(tp: Type, formals: List[Type], restpe: Type): Type = tp match {
-      case _: ImplicitMethodType => ImplicitMethodType(formals, restpe)
-      case _: JavaMethodType => JavaMethodType(formals, restpe)
-      case _ => MethodType(formals, restpe)
-    }
   }
 
   /** A type map that always returns the input type unchanged */
@@ -2586,30 +3141,28 @@ A type's typeSymbol should never be inspected directly.
   private val emptySymMap = scala.collection.immutable.Map[Symbol, Symbol]() 
   private val emptySymCount = scala.collection.immutable.Map[Symbol, Int]() 
 
-  /** Make an existential variable.
-   *  @param suffix  A suffix to be appended to the freshly generated name
-   *                 It's ususally "", except for type variables abstracting
-   *                 over values, where it is ".type".
-   *  @param owner   The owner of the variable
-   *  @param bounds  The variable's bounds
-   */
-  def makeExistential(name: String, owner: Symbol, bounds: TypeBounds): Symbol = 
-    recycle(
-      owner.newAbstractType(owner.pos, newTypeName(name)).setFlag(EXISTENTIAL)
-    ).setInfo(bounds)
-
-  /** Make an existential variable with a fresh name. */
-  def makeFreshExistential(suffix: String, owner: Symbol, bounds: TypeBounds): Symbol = 
-    makeExistential(freshName()+suffix, owner, bounds)
-
   def typeParamsToExistentials(clazz: Symbol, tparams: List[Symbol]): List[Symbol] = {
     val eparams = for ((tparam, i) <- tparams.zipWithIndex) yield {
-      makeExistential("?"+i, clazz, tparam.info.bounds)
+      clazz.newExistential(clazz.pos, "?"+i).setInfo(tparam.info.bounds)
     }
-    for (val tparam <- eparams) tparam setInfo tparam.info.substSym(tparams, eparams)
+    for (tparam <- eparams) tparam setInfo tparam.info.substSym(tparams, eparams)
     eparams
   }
+  
+  //  note: it's important to write the two tests in this order,
+  //  as only typeParams forces the classfile to be read. See #400
+  private def isRawIfWithoutArgs(sym: Symbol) =
+    sym.isClass && !sym.typeParams.isEmpty && sym.hasFlag(JAVA)
 
+  def isRaw(sym: Symbol, args: List[Type]) = 
+    !phase.erasedTypes && isRawIfWithoutArgs(sym) && args.isEmpty
+  
+  /** Is type tp a ``raw type''? */
+  def isRawType(tp: Type) = tp match {
+    case TypeRef(_, sym, args) => isRaw(sym, args)
+    case _ => false
+  }
+      
   /** The raw to existential map converts a ``raw type'' to an existential type.
    *  It is necessary because we might have read a raw type of a 
    *  parameterized Java class from a class file. At the time we read the type
@@ -2620,9 +3173,7 @@ A type's typeSymbol should never be inspected directly.
    */
   object rawToExistential extends TypeMap {
     def apply(tp: Type): Type = tp match {
-      case TypeRef(pre, sym, List()) if !sym.typeParams.isEmpty && sym.hasFlag(JAVA) =>
-        //  note: it's important to write the two tests in this order,
-        //  as only typeParams forces the classfile to be read. See #400
+      case TypeRef(pre, sym, List()) if isRawIfWithoutArgs(sym) =>
         val eparams = typeParamsToExistentials(sym, sym.typeParams)
         existentialAbstraction(eparams, TypeRef(pre, sym, eparams map (_.tpe)))
       case _ =>
@@ -2631,7 +3182,7 @@ A type's typeSymbol should never be inspected directly.
   }
 
   def singletonBounds(hi: Type) = {
-    mkTypeBounds(NothingClass.tpe, intersectionType(List(hi, SingletonClass.tpe)))
+    TypeBounds(NothingClass.tpe, intersectionType(List(hi, SingletonClass.tpe)))
   }
 
   /** A map to compute the asSeenFrom method  */
@@ -2642,46 +3193,42 @@ A type's typeSymbol should never be inspected directly.
 
     override def mapOver(tree: Tree, giveup: ()=>Nothing): Tree = {
       object annotationArgRewriter extends TypeMapTransformer {
-	/** Rewrite "this" trees as needed for asSeenFrom */
-	def rewriteThis(tree: Tree): Tree =
-	  tree match {
-	    case This(_)
-	    if (tree.symbol isNonBottomSubClass clazz) &&
-	       (pre.widen.typeSymbol isNonBottomSubClass tree.symbol) =>
-  	      if (pre.isStable) {
-		val termSym =
-		  pre.typeSymbol.owner.newValue(
-		    pre.typeSymbol.pos,
-		    pre.typeSymbol.name).setInfo(pre)  // what symbol should really be used?
-		mkAttributedQualifier(pre, termSym)
-	      } else
-		giveup()
-	    
-	    case tree => tree
-	  }
-
-	override def transform(tree: Tree): Tree = {
-	  val tree1 = rewriteThis(super.transform(tree))
-	  tree1
-	}
+        /** Rewrite "this" trees as needed for asSeenFrom */
+        def rewriteThis(tree: Tree): Tree =
+          tree match {
+            case This(_)
+            if (tree.symbol isNonBottomSubClass clazz) &&
+               (pre.widen.typeSymbol isNonBottomSubClass tree.symbol) =>
+              if (pre.isStable) {
+                val termSym =
+                  pre.typeSymbol.owner.newValue(
+                    pre.typeSymbol.pos,
+                    pre.typeSymbol.name).setInfo(pre)  // what symbol should really be used?
+                mkAttributedQualifier(pre, termSym)
+              } else
+                giveup()
+            
+            case tree => tree
+          }
+
+        override def transform(tree: Tree): Tree = {
+          val tree1 = rewriteThis(super.transform(tree))
+          tree1
+        }
       }
 
       annotationArgRewriter.transform(tree)
-    } 
+    }
 
     var capturedPre = emptySymMap
 
-    def stabilize(pre: Type, clazz: Symbol): Type = {
-      capturedPre get clazz match {
-        case None =>
-          val qvar = makeFreshExistential(".type", clazz, singletonBounds(pre))
+    def stabilize(pre: Type, clazz: Symbol): Type =
+      capturedPre.getOrElse(clazz, {
+          val qvar = clazz freshExistential ".type" setInfo singletonBounds(pre)
           capturedPre += (clazz -> qvar)
           capturedParams = qvar :: capturedParams
           qvar
-        case Some(qvar) =>
-          qvar
-      }
-    }.tpe
+      }).tpe
 
     /** Return pre.baseType(clazz), or if that's NoType and clazz is a refinement, pre itself.
      *  See bug397.scala for an example where the second alternative is needed.
@@ -2694,6 +3241,7 @@ A type's typeSymbol should never be inspected directly.
       if (b == NoType && clazz.isRefinementClass) pre
       else b
     }
+
     def apply(tp: Type): Type = 
       if ((pre eq NoType) || (pre eq NoPrefix) || !clazz.isClass) tp
       else tp match {
@@ -2713,7 +3261,9 @@ A type's typeSymbol should never be inspected directly.
               } else {
                 pre1
               }
-            } else toPrefix(base(pre, clazz).prefix, clazz.owner);
+            } else {
+              toPrefix(base(pre, clazz).prefix, clazz.owner);
+            }
           toPrefix(pre, clazz)
         case SingleType(pre, sym) =>
           if (sym.isPackageClass) tp // short path
@@ -2728,22 +3278,16 @@ A type's typeSymbol should never be inspected directly.
             if ((pre eq NoType) || (pre eq NoPrefix) || !clazz.isClass) mapOver(tp) 
             //@M! see test pos/tcpoly_return_overriding.scala why mapOver is necessary
             else {
-              def throwError : Nothing = 
-                // IDE: in the IDE, this will occur because we complete everything
-                //      too eagerly. It doesn't matter, the error will be fixed when
-                //      the node is re-typed.
-                if (inIDE) throw new TypeError("internal error: " + tp + " in " + sym.owner +
-                  " cannot be instantiated from " + pre.widen)
-                     else throw new Error("" + tp + sym.locationString +
-                                     " cannot be instantiated from " + pre.widen)
+              def throwError = abort("" + tp + sym.locationString + " cannot be instantiated from " + pre.widen)
+                                    
               def instParam(ps: List[Symbol], as: List[Type]): Type = 
                 if (ps.isEmpty) throwError
                 else if (sym eq ps.head)  
                   // @M! don't just replace the whole thing, might be followed by type application
-                  appliedType(as.head, List.mapConserve(args)(this)) // @M: was as.head   
+                  appliedType(as.head, args mapConserve (this)) // @M: was as.head   
                 else instParam(ps.tail, as.tail);
               val symclazz = sym.owner
-              if (symclazz == clazz && (pre.widen.typeSymbol isNonBottomSubClass symclazz)) {
+              if (symclazz == clazz && !pre.isInstanceOf[TypeVar] && (pre.widen.typeSymbol isNonBottomSubClass symclazz)) {
                 pre.baseType(symclazz) match {
                   case TypeRef(_, basesym, baseargs) =>
                     //Console.println("instantiating " + sym + " from " + basesym + " with " + basesym.typeParams + " and " + baseargs+", pre = "+pre+", symclazz = "+symclazz);//DEBUG
@@ -2772,24 +3316,29 @@ A type's typeSymbol should never be inspected directly.
 
   /** A base class to compute all substitutions */
   abstract class SubstMap[T](from: List[Symbol], to: List[T]) extends TypeMap {
+    assert(from.length == to.length, "Unsound substitution from "+ from +" to "+ to)
+
     /** Are `sym' and `sym1' the same.
      *  Can be tuned by subclasses.
      */
     protected def matches(sym: Symbol, sym1: Symbol): Boolean = sym eq sym1
 
     /** Map target to type, can be tuned by subclasses */
-    protected def toType(fromtp: Type, t: T): Type
-
-      def subst(tp: Type, sym: Symbol, from: List[Symbol], to: List[T]): Type =
-        if (from.isEmpty) tp
-        else if (to.isEmpty && inIDE) throw new TypeError(NoPosition, "type parameter list problem");
-        else if (matches(from.head, sym)) toType(tp, to.head)
-        else subst(tp, sym, from.tail, to.tail)
-
-    private def renameBoundSyms(tp: Type) = tp match {
+    protected def toType(fromtp: Type, tp: T): Type
+
+    def subst(tp: Type, sym: Symbol, from: List[Symbol], to: List[T]): Type =
+      if (from.isEmpty) tp
+      // else if (to.isEmpty) error("Unexpected substitution on '%s': from = %s but to == Nil".format(tp, from))
+      else if (matches(from.head, sym)) toType(tp, to.head)
+      else subst(tp, sym, from.tail, to.tail)
+
+    protected def renameBoundSyms(tp: Type): Type = tp match {
+      case MethodType(ps, restp) =>
+        val ps1 = cloneSymbols(ps)
+        copyMethodType(tp, ps1, renameBoundSyms(restp.substSym(ps, ps1)))
       case PolyType(bs, restp) =>
         val bs1 = cloneSymbols(bs)
-        PolyType(bs1, restp.substSym(bs, bs1))
+        PolyType(bs1, renameBoundSyms(restp.substSym(bs, bs1)))
       case ExistentialType(bs, restp) =>
         val bs1 = cloneSymbols(bs)
         ExistentialType(bs1, restp.substSym(bs, bs1))
@@ -2816,13 +3365,7 @@ A type's typeSymbol should never be inspected directly.
         // (must not recurse --> loops)
         // 3) replacing m by List in m[Int] should yield List[Int], not just List
         case TypeRef(NoPrefix, sym, args) =>
-          subst(tp, sym, from, to) match {
-            case r @ TypeRef(pre1, sym1, args1) => 
-              if (args.isEmpty) r
-              else rawTypeRef(pre1, sym1, args)
-            case r =>
-              r
-          }
+          appliedType(subst(tp, sym, from, to), args) // if args.isEmpty, appliedType is the identity
         case SingleType(NoPrefix, sym) =>
           subst(tp, sym, from, to)
         case _ =>
@@ -2841,12 +3384,14 @@ A type's typeSymbol should never be inspected directly.
     override def apply(tp: Type): Type = if (from.isEmpty) tp else {
       def subst(sym: Symbol, from: List[Symbol], to: List[Symbol]): Symbol =
         if (from.isEmpty) sym
+        // else if (to.isEmpty) error("Unexpected substitution on '%s': from = %s but to == Nil".format(sym, from))
         else if (matches(from.head, sym)) to.head
         else subst(sym, from.tail, to.tail)
       tp match {
         case TypeRef(pre, sym, args) if !(pre eq NoPrefix) =>
-          mapOver(typeRef(pre, subst(sym, from, to), args)) 
-            //@M TODO subst args? List.mapConserve(args)(this)
+          val newSym = subst(sym, from, to)
+          // assert(newSym.typeParams.length == sym.typeParams.length, "typars mismatch in SubstSymMap: "+(sym, sym.typeParams, newSym, newSym.typeParams))
+          mapOver(typeRef(pre, newSym, args)) // mapOver takes care of subst'ing in args
         case SingleType(pre, sym) if !(pre eq NoPrefix) =>
           mapOver(singleType(pre, subst(sym, from, to)))
         case _ =>
@@ -2858,29 +3403,29 @@ A type's typeSymbol should never be inspected directly.
     override def mapOver(tree: Tree, giveup: ()=>Nothing): Tree = {
       object trans extends TypeMapTransformer {
 
-	def termMapsTo(sym: Symbol) =
-	  if (from contains sym)
-	    Some(to(from.indexOf(sym)))
-	  else
-	    None
-
-	override def transform(tree: Tree) = 
-	  tree match {
-	    case tree at Ident(_) =>
-	      termMapsTo(tree.symbol) match {
-		case Some(tosym) =>
-		  if (tosym.info.bounds.hi.typeSymbol isSubClass SingletonClass) {
-		    Ident(tosym.existentialToString)
-		      .setSymbol(tosym)
-		      .setPos(tosym.pos)
-		      .setType(dropSingletonType(tosym.info.bounds.hi))
-		  } else {
-		    giveup()
-		  }
-		case None => super.transform(tree)
-	      }
-	    case tree => super.transform(tree)
-	  }
+        def termMapsTo(sym: Symbol) =
+          if (from contains sym)
+            Some(to(from.indexOf(sym)))
+          else
+            None
+
+        override def transform(tree: Tree) = 
+          tree match {
+            case tree at Ident(_) =>
+              termMapsTo(tree.symbol) match {
+                case Some(tosym) =>
+                  if (tosym.info.bounds.hi.typeSymbol isSubClass SingletonClass) {
+                    Ident(tosym.existentialToString)
+                      .setSymbol(tosym)
+                      .setPos(tosym.pos)
+                      .setType(dropSingletonType(tosym.info.bounds.hi))
+                  } else {
+                    giveup()
+                  }
+                case none => super.transform(tree)
+              }
+            case tree => super.transform(tree)
+          }
       }
       trans.transform(tree)
     }
@@ -2891,25 +3436,20 @@ A type's typeSymbol should never be inspected directly.
   extends SubstMap(from, to) {
     protected def toType(fromtp: Type, tp: Type) = tp 
 
-
     override def mapOver(tree: Tree, giveup: ()=>Nothing): Tree = {
       object trans extends TypeMapTransformer {
-	override def transform(tree: Tree) = 
-	  tree match {
-	    case tree at Ident(_) if from contains tree.symbol =>
-	      val totpe = to(from.indexOf(tree.symbol))
-	      if (!totpe.isStable) {
-		giveup()
-	      } else {
-		tree.duplicate.setType(totpe)
-	      }
-
-	    case _ => super.transform(tree)
-	  }
+        override def transform(tree: Tree) = 
+          tree match {
+            case Ident(name) if from contains tree.symbol =>
+              val totpe = to(from.indexOf(tree.symbol))
+              if (!totpe.isStable) giveup()
+              else Ident(name).setPos(tree.pos).setSymbol(tree.symbol).setType(totpe)
+
+            case _ => super.transform(tree)
+          }
       }
       trans.transform(tree)
-      }
-
+    }
 
   }
 
@@ -2928,8 +3468,10 @@ A type's typeSymbol should never be inspected directly.
   class SubstWildcardMap(from: List[Symbol]) extends TypeMap { 
     def apply(tp: Type): Type = try {
       tp match {
-        case TypeRef(_, sym, _) if (from contains sym) => WildcardType
-        case _ => mapOver(tp)
+        case TypeRef(_, sym, _) if (from contains sym) => 
+          BoundedWildcardType(sym.info.bounds)
+        case _ => 
+          mapOver(tp)
       }
     } catch {
       case ex: MalformedType =>
@@ -2937,85 +3479,94 @@ A type's typeSymbol should never be inspected directly.
     }
   }
 
-  /** Most of the implementation for MethodType.resultType.  The
-   *  caller also needs to existentially quantify over the
-   *  variables in existentialsNeeded.
-   */
-  class InstantiateDeBruijnMap(actuals: List[Type]) extends TypeMap {
+// dependent method types
+  object IsDependentCollector extends TypeCollector(false) {
+    def traverse(tp: Type) {
+      if(tp isImmediatelyDependent) result = true
+      else if (!result) mapOver(tp)
+    }
+  }
+
+  object ApproximateDependentMap extends TypeMap {
+    def apply(tp: Type): Type = 
+      if(tp isImmediatelyDependent) WildcardType
+      else mapOver(tp)
+  }
+
+  class InstantiateDependentMap(params: List[Symbol], actuals: List[Type]) extends TypeMap {
     override val dropNonConstraintAnnotations = true
 
+    object ParamWithActual {
+      def unapply(sym: Symbol): Option[Type] = {
+        val pid = params indexOf sym
+        if(pid != -1) Some(actuals(pid)) else None
+      }
+    }
+
+    def apply(tp: Type): Type =
+      mapOver(tp) match {
+        case SingleType(NoPrefix, ParamWithActual(arg)) if arg isStable => arg // unsound to replace args by unstable actual #3873
+        // (soundly) expand type alias selections on implicit arguments, see depmet_implicit_oopsla* test cases -- typically, `param.isImplicit`
+        case tp1 at TypeRef(SingleType(NoPrefix, param at ParamWithActual(arg)), sym, targs) =>
+          val res = typeRef(arg, sym, targs)
+          if(res.typeSymbolDirect isAliasType) res.dealias
+          else tp1
+        case tp1 => tp1 // don't return the original `tp`, which may be different from `tp1`, due to `dropNonConstraintAnnotations`
+      }
+
+    def existentialsNeeded: List[Symbol] = existSyms.filter(_ ne null).toList
 
-    private var existSyms = immutable.Map.empty[Int, Symbol]
-    def existentialsNeeded: List[Symbol] = existSyms.values.toList
+    private val existSyms: Array[Symbol] = new Array(actuals.length)
+    private def haveExistential(i: Int) = {assert((i >= 0) && (i <= actuals.length)); existSyms(i) ne null}
 
-    /* Return the type symbol for referencing a parameter index 
-     * inside the existential quantifier.  */
-    def existSymFor(actualIdx: Int, oldSym: Symbol) =
-      if (existSyms.isDefinedAt(actualIdx))
-	existSyms(actualIdx)
+    /* Return the type symbol for referencing a parameter inside the existential quantifier. 
+     * (Only needed if the actual is unstable.)
+     */
+    def existSymFor(actualIdx: Int) =
+      if (haveExistential(actualIdx)) existSyms(actualIdx)
       else {
-	val symowner = oldSym.owner // what should be used??
+        val oldSym = params(actualIdx)
+        val symowner = oldSym.owner
         val bound = singletonBounds(actuals(actualIdx))
 
-        val sym =
-	  symowner.newAbstractType(oldSym.pos, oldSym.name+".type")
-
-	sym.setInfo(bound)
+        val sym = symowner.newExistential(oldSym.pos, oldSym.name+".type")
+        sym.setInfo(bound)
         sym.setFlag(oldSym.flags)
-	sym.setFlag(EXISTENTIAL)
 
-
-	existSyms = existSyms + (actualIdx -> sym)
-	sym
+        existSyms(actualIdx) = sym
+        sym
       }
 
-    def apply(tp: Type): Type = tp match {
-      case DeBruijnIndex(level, pid) =>
-        if (level == 1) 
-          if (pid < actuals.length) actuals(pid) else tp
-        else DeBruijnIndex(level - 1, pid)
-      case _ =>
-        mapOver(tp)
-    }
-
+    //AM propagate more info to annotations -- this seems a bit ad-hoc... (based on code by spoon)
     override def mapOver(arg: Tree, giveup: ()=>Nothing): Tree = {
-      object treeTrans extends TypeMapTransformer {
-	override def transform(tree: Tree): Tree =
-	  tree match {
-	    case tree at Ident(name) =>
-	      tree.tpe.withoutAttributes match {
-		case DeBruijnIndex(level, pid) =>
-		  if (level == 1) {
-		    if (actuals(pid).isStable)
-		      mkAttributedQualifier(actuals(pid), tree.symbol)
-		    else {
-		      val sym = existSymFor(pid, tree.symbol)
-                      (Ident(tree.symbol.name)
-		       copyAttrs tree
-		       setType typeRef(NoPrefix, sym, Nil))
-		    }
-		  } else
-		    tree.duplicate.setType(
-		      DeBruijnIndex(level-1, pid))
-		case _ => super.transform(tree)
-
-	      }
-	    case _ => super.transform(tree)
-	  }
+      object treeTrans extends Transformer {
+        override def transform(tree: Tree): Tree = {
+          tree match {
+            case RefParamAt(pid) =>
+              if(actuals(pid) isStable) mkAttributedQualifier(actuals(pid), tree.symbol)
+              else {
+                val sym = existSymFor(pid)
+                (Ident(sym.name)
+                 copyAttrs tree
+                 setType typeRef(NoPrefix, sym, Nil))
+              }
+            case _ => super.transform(tree)
+          }
+        }
+        object RefParamAt {
+          def unapply(tree: Tree): Option[(Int)] = tree match {
+            case Ident(_) =>
+              val pid = params indexOf tree.symbol
+              if(pid != -1) Some((pid)) else None
+            case _ => None
+          }
+        }
       }
 
       treeTrans.transform(arg)
     }
   }
 
-  object ApproximateDeBruijnMap extends TypeMap {
-    def apply(tp: Type): Type = tp match {
-      case DeBruijnIndex(level, pid) =>
-        WildcardType
-      case _ =>
-        mapOver(tp)
-    }
-  }
 
   object StripAnnotationsMap extends TypeMap {
     def apply(tp: Type): Type = tp match {
@@ -3062,9 +3613,9 @@ A type's typeSymbol should never be inspected directly.
 
     override def mapOver(arg: Tree) = {
       for (t <- arg) {
-	traverse(t.tpe)
-	if (t.symbol == sym)
-	  result = true
+        traverse(t.tpe)
+        if (t.symbol == sym)
+          result = true
       }
       Some(arg)
     }
@@ -3080,7 +3631,7 @@ A type's typeSymbol should never be inspected directly.
     }
     override def mapOver(arg: Tree) = {
       for (t <- arg) {
-	traverse(t.tpe)
+        traverse(t.tpe)
       }
       Some(arg)
     }
@@ -3121,15 +3672,6 @@ A type's typeSymbol should never be inspected directly.
     }
   }
 
-  object IsDependentCollector extends TypeCollector(false) {
-    def traverse(tp: Type) {
-      tp match {
-        case DeBruijnIndex(_, _) => result = true
-        case _ => if (!result) mapOver(tp)
-      }
-    }
-  }
-
   /** A map to compute the most deeply nested owner that contains all the symbols
    *  of thistype or prefixless typerefs/singletype occurrences in given type.
    */
@@ -3156,16 +3698,23 @@ A type's typeSymbol should never be inspected directly.
     }
   }
 
+  class MissingAliasControl extends ControlThrowable
+  val missingAliasException = new MissingAliasControl
+  class MissingTypeControl extends ControlThrowable
+
   object adaptToNewRunMap extends TypeMap {
     private def adaptToNewRun(pre: Type, sym: Symbol): Symbol = {
-      if (inIDE) sym // dependecies adapted at a finer granularity in IDE
-      else if (sym.isModuleClass && !phase.flatClasses) {
+      if (sym.isModuleClass && !phase.flatClasses) {
         adaptToNewRun(pre, sym.sourceModule).moduleClass
       } else if ((pre eq NoPrefix) || (pre eq NoType) || sym.owner.isPackageClass) {
         sym
       } else {
-        var rebind0 = pre.findMember(sym.name, BRIDGE, 0, true)(NoSymbol)
-        if (rebind0 == NoSymbol) { assert(false, ""+pre+"."+sym+" does no longer exist, phase = "+phase) }
+        var rebind0 = pre.findMember(sym.name, BRIDGE, 0, true)
+        if (rebind0 == NoSymbol) {
+          if (sym.isAliasType) throw missingAliasException
+          throw new MissingTypeControl // For build manager purposes
+          //assert(false, pre+"."+sym+" does no longer exist, phase = "+phase)
+        }
         /** The two symbols have the same fully qualified name */
         def corresponds(sym1: Symbol, sym2: Symbol): Boolean =
           sym1.name == sym2.name && (sym1.isPackageClass || corresponds(sym1.owner, sym2.owner))
@@ -3189,7 +3738,7 @@ A type's typeSymbol should never be inspected directly.
     def apply(tp: Type): Type = tp match {
       case ThisType(sym) if (sym.isModuleClass) =>
         val sym1 = adaptToNewRun(sym.owner.thisType, sym)
-        if (sym1 == sym) tp else mkThisType(sym1)
+        if (sym1 == sym) tp else ThisType(sym1)
       case SingleType(pre, sym) =>
         if (sym.isPackage) tp
         else {
@@ -3202,29 +3751,43 @@ A type's typeSymbol should never be inspected directly.
         if (sym.isPackageClass) tp
         else {
           val pre1 = this(pre)
-          val args1 = List.mapConserve(args)(this)
-          val sym1 = adaptToNewRun(pre1, sym)
-          if ((pre1 eq pre) && (sym1 eq sym) && (args1 eq args)/* && sym.isExternal*/) tp
-          else typeRef(pre1, sym1, args1)
+          val args1 = args mapConserve (this)
+          try {
+            val sym1 = adaptToNewRun(pre1, sym)
+            if ((pre1 eq pre) && (sym1 eq sym) && (args1 eq args)/* && sym.isExternal*/) tp
+            else typeRef(pre1, sym1, args1)
+          } catch {
+            case ex: MissingAliasControl =>
+              apply(tp.dealias)
+            case _: MissingTypeControl =>
+              NoType
+          }
         }
+      case MethodType(params, restp) =>
+        val restp1 = this(restp)
+        if (restp1 eq restp) tp
+        else copyMethodType(tp, params, restp1)
       case PolyType(tparams, restp) =>
         val restp1 = this(restp)
         if (restp1 eq restp) tp
         else PolyType(tparams, restp1)
+
+      // Lukas: we need to check (together) whether we should also include parameter types
+      // of PolyType and MethodType in adaptToNewRun
+      
       case ClassInfoType(parents, decls, clazz) =>
         if (clazz.isPackageClass) tp
         else {
-          val parents1 = List.mapConserve(parents)(this)
+          val parents1 = parents mapConserve (this)
           if (parents1 eq parents) tp
           else ClassInfoType(parents1, decls, clazz)
         }
       case RefinedType(parents, decls) =>
-        val parents1 = List.mapConserve(parents)(this)
+        val parents1 = parents mapConserve (this)
         if (parents1 eq parents) tp
         else refinedType(parents1, tp.typeSymbol.owner, decls, tp.typeSymbol.owner.pos)
       case SuperType(_, _) => mapOver(tp)
       case TypeBounds(_, _) => mapOver(tp)
-      case MethodType(_, _) => mapOver(tp)
       case TypeVar(_, _) => mapOver(tp)
       case AnnotatedType(_,_,_) => mapOver(tp)
       case NotNullType(_) => mapOver(tp)
@@ -3246,12 +3809,6 @@ A type's typeSymbol should never be inspected directly.
 
 // Helper Methods  -------------------------------------------------------------
 
-  private var nextid = 0
-  private def freshName() = {
-    nextid += 1
-    "_"+nextid
-  }
-
   final val LubGlbMargin = 0
 
   /** The maximum allowable depth of lubs or glbs over types `ts'
@@ -3260,7 +3817,7 @@ A type's typeSymbol should never be inspected directly.
     */
   def lubDepth(ts: List[Type]) = {
     var d = 0
-    for (tp <- ts) d = Math.max(d, tp.baseTypeSeqDepth)
+    for (tp <- ts) d = math.max(d, tp.baseTypeSeqDepth)
     d + LubGlbMargin
   }
 
@@ -3283,36 +3840,20 @@ A type's typeSymbol should never be inspected directly.
     }
   }
 
-  /** Can variable `tv' be related in a constraint to type `tp'?
-   *  This is not the case if `tp' contains type skolems whose
-   *  skolemization level is higher than the level of `tv'.
-   */
-  private def isRelatable(tv: TypeVar, tp: Type): Boolean = {
-    var ok = true
-    for (t <- tp) {
-      t.typeSymbol match {
-        case ts: TypeSkolem => if (ts.level > tv.level) ok = false
-        case _ =>
-      }
-    }
-    if (ok) undoLog = (tv, tv.constr.duplicate) :: undoLog
-    ok
-  }
-
   /** Is intersection of given types populated? That is,
    *  for all types tp1, tp2 in intersection
    *    for all common base classes bc of tp1 and tp2
    *      let bt1, bt2 be the base types of tp1, tp2 relative to class bc
    *      Then:
    *        bt1 and bt2 have the same prefix, and
-   *        any correspondiong non-variant type arguments of bt1 and bt2 are the same
+   *        any corresponding non-variant type arguments of bt1 and bt2 are the same
    */
   def isPopulated(tp1: Type, tp2: Type): Boolean = {
     def isConsistent(tp1: Type, tp2: Type): Boolean = (tp1, tp2) match {
       case (TypeRef(pre1, sym1, args1), TypeRef(pre2, sym2, args2)) =>
         assert(sym1 == sym2)
         pre1 =:= pre2 &&
-        !(List.map3(args1, args2, sym1.typeParams) {
+        ((args1, args2, sym1.typeParams).zipped forall {
           (arg1, arg2, tparam) => 
             //if (tparam.variance == 0 && !(arg1 =:= arg2)) Console.println("inconsistent: "+arg1+"!="+arg2)//DEBUG
           if (tparam.variance == 0) arg1 =:= arg2
@@ -3323,16 +3864,20 @@ A type's typeSymbol should never be inspected directly.
             // also: think what happens if there are embedded typevars?
             if (tparam.variance < 0) arg1 <:< arg2 else arg2 <:< arg1
           else true
-        } contains false)
+        })
       case (et: ExistentialType, _) =>
         et.withTypeVars(isConsistent(_, tp2))
       case (_, et: ExistentialType) =>
         et.withTypeVars(isConsistent(tp1, _))
     }    
-    if (tp1.typeSymbol.isClass && tp1.typeSymbol.hasFlag(FINAL)) 
-      tp1 <:< tp2 || isNumericValueClass(tp1.typeSymbol) && isNumericValueClass(tp2.typeSymbol)
-    else tp1.baseClasses forall (bc => 
-      tp2.baseTypeIndex(bc) < 0 || isConsistent(tp1.baseType(bc), tp2.baseType(bc)))
+
+    def check(tp1: Type, tp2: Type) = 
+      if (tp1.typeSymbol.isClass && tp1.typeSymbol.hasFlag(FINAL)) 
+        tp1 <:< tp2 || isNumericValueClass(tp1.typeSymbol) && isNumericValueClass(tp2.typeSymbol)
+      else tp1.baseClasses forall (bc => 
+        tp2.baseTypeIndex(bc) < 0 || isConsistent(tp1.baseType(bc), tp2.baseType(bc)))
+
+    check(tp1, tp2)/* && check(tp2, tp1)*/ // need to investgate why this can't be made symmetric -- neg/gadts1 fails, and run/existials also.
   }
 
   /** Does a pattern of type `patType' need an outer test when executed against
@@ -3373,57 +3918,63 @@ A type's typeSymbol should never be inspected directly.
     }
   }
 
-  /** Undo all changes to constraints to type variables upto `limit'
-   */
-  private def undoTo(limit: UndoLog) {
-    while (undoLog ne limit)/* && !undoLog.isEmpty*/ { // @M added `&& !undoLog.isEmpty`
-                    // Martin: I don't think the addition is necessary?
-// @M TODO: I had an example, but seem to have misplaced it :-)
-      val (tv, constr) = undoLog.head
-      undoLog = undoLog.tail
-      tv.constr = constr
-    }
-  }
-
   private var subsametypeRecursions: Int = 0
 
   private def isUnifiable(pre1: Type, pre2: Type) =
-    (beginsWithTypeVar(pre1) || beginsWithTypeVar(pre2)) && (pre1 =:= pre2)
+    (beginsWithTypeVarOrIsRefined(pre1) || beginsWithTypeVarOrIsRefined(pre2)) && (pre1 =:= pre2)
+
+  /** Returns true iff we are past phase specialize,
+   *  sym1 and sym2 are two existential skolems with equal names and bounds,
+   *  and pre1 and pre2 are equal prefixes
+   */
+  private def isSameSpecializedSkolem(sym1: Symbol, sym2: Symbol, pre1: Type, pre2: Type) = {
+    sym1.isExistentialSkolem && sym2.isExistentialSkolem && 
+    sym1.name == sym2.name && 
+    phase.specialized &&
+    sym1.info =:= sym2.info &&
+    pre1 =:= pre2
+  }
 
   private def equalSymsAndPrefixes(sym1: Symbol, pre1: Type, sym2: Symbol, pre2: Type): Boolean =
-    if (sym1 == sym2) phase.erasedTypes || pre1 =:= pre2
+    if (sym1 == sym2) sym1.hasFlag(PACKAGE) || phase.erasedTypes || pre1 =:= pre2
     else (sym1.name == sym2.name) && isUnifiable(pre1, pre2)
 
   /** Do `tp1' and `tp2' denote equivalent types?
    */
   def isSameType(tp1: Type, tp2: Type): Boolean = try {
+    incCounter(sametypeCount)
     subsametypeRecursions += 1
-    val lastUndoLog = undoLog
-    val result = isSameType0(tp1, tp2)
-    if (!result) undoTo(lastUndoLog)
-    result
+    undoLog undoUnless {
+      isSameType1(tp1, tp2) 
+    }
   } finally {
     subsametypeRecursions -= 1
-    if (subsametypeRecursions == 0) undoLog = List()
+    if (subsametypeRecursions == 0) undoLog.clear
   }
 
   def isDifferentType(tp1: Type, tp2: Type): Boolean = try {
     subsametypeRecursions += 1
-    val lastUndoLog = undoLog
-    val result = isSameType0(tp1, tp2)
-    undoTo(lastUndoLog)
-    !result
+    undoLog undo { // undo type constraints that arise from operations in this block
+      !isSameType1(tp1, tp2)
+    }
   } finally {
     subsametypeRecursions -= 1
-    if (subsametypeRecursions == 0) undoLog = List()
+    if (subsametypeRecursions == 0) undoLog.clear
   }
 
-  def normalizePlus(tp: Type) = tp match {
-    case TypeRef(pre, sym, List()) if (sym.isInitialized && sym.hasFlag(JAVA) && !sym.typeParams.isEmpty) =>
-      rawToExistential(tp)
-    case _ => tp.normalize
+  def isDifferentTypeConstructor(tp1: Type, tp2: Type): Boolean = tp1 match {
+    case TypeRef(pre1, sym1, _) => 
+      tp2 match {
+        case TypeRef(pre2, sym2, _) => sym1 != sym2 || isDifferentType(pre1, pre2)
+        case _ => true
+      }
+    case _ => true
   }
 
+  def normalizePlus(tp: Type) = 
+    if (isRawType(tp)) rawToExistential(tp)
+    else tp.normalize
+
   /*
   todo: change to:
   def normalizePlus(tp: Type) = tp match {
@@ -3434,8 +3985,9 @@ A type's typeSymbol should never be inspected directly.
     case _ => tp.normalize
   }
   */
-
-  private def isSameType0(tp1: Type, tp2: Type): Boolean = 
+/*
+  private def isSameType0(tp1: Type, tp2: Type): Boolean = {
+    if (tp1 eq tp2) return true
     ((tp1, tp2) match {
       case (ErrorType, _) => true
       case (WildcardType, _) => true
@@ -3451,7 +4003,7 @@ A type's typeSymbol should never be inspected directly.
       if (sym1 == sym2) =>
         true
       case (SingleType(pre1, sym1), SingleType(pre2, sym2))
-      if equalSymsAndPrefixes(sym1, pre1, sym2, pre2) =>
+      if (equalSymsAndPrefixes(sym1, pre1, sym2, pre2)) =>
         true
 /*
       case (SingleType(pre1, sym1), ThisType(sym2))
@@ -3488,37 +4040,32 @@ A type's typeSymbol should never be inspected directly.
         }
         //Console.println("is same? " + tp1 + " " + tp2 + " " + tp1.typeSymbol.owner + " " + tp2.typeSymbol.owner)//DEBUG
         isSameTypes(parents1, parents2) && isSubScope(ref1, ref2) && isSubScope(ref2, ref1)
-      case (MethodType(pts1, res1), MethodType(pts2, res2)) =>
-        (pts1.length == pts2.length &&
-         isSameTypes(pts1, pts2) &&
+      case (MethodType(params1, res1), MethodType(params2, res2)) =>
+        // new dependent types: probably fix this, use substSym as done for PolyType
+        (isSameTypes(tp1.paramTypes, tp2.paramTypes) &&
          res1 =:= res2 &&
-         tp1.isInstanceOf[ImplicitMethodType] == tp2.isInstanceOf[ImplicitMethodType])
-      case (PolyType(tparams1, res1), PolyType(tparams2, res2)) =>
-        (tparams1.length == tparams2.length &&
-         List.forall2(tparams1, tparams2)
-           ((p1, p2) => p1.info =:= p2.info.substSym(tparams2, tparams1)) &&
-         res1 =:= res2.substSym(tparams2, tparams1))
+         tp1.isImplicit == tp2.isImplicit)
+      case (PolyType(tparams1, res1), PolyType(tparams2, res2)) => 
+        // assert((tparams1 map (_.typeParams.length)) == (tparams2 map (_.typeParams.length)))
+        (tparams1.length == tparams2.length) && (tparams1 corresponds tparams2)(_.info =:= _.info.substSym(tparams2, tparams1)) && // @M looks like it might suffer from same problem as #2210 
+          res1 =:= res2.substSym(tparams2, tparams1)
       case (ExistentialType(tparams1, res1), ExistentialType(tparams2, res2)) =>
-        (tparams1.length == tparams2.length &&
-         List.forall2(tparams1, tparams2)
-           ((p1, p2) => p1.info =:= p2.info.substSym(tparams2, tparams1)) &&
-         res1 =:= res2.substSym(tparams2, tparams1))
+        (tparams1.length == tparams2.length) && (tparams1 corresponds tparams2)(_.info =:= _.info.substSym(tparams2, tparams1)) && // @M looks like it might suffer from same problem as #2210
+          res1 =:= res2.substSym(tparams2, tparams1)
       case (TypeBounds(lo1, hi1), TypeBounds(lo2, hi2)) =>
         lo1 =:= lo2 && hi1 =:= hi2
       case (BoundedWildcardType(bounds), _) =>
         bounds containsType tp2
       case (_, BoundedWildcardType(bounds)) =>
         bounds containsType tp1
-      case (tv1 @ TypeVar(_, constr1), _) =>
-        if (constr1.inst != NoType) constr1.inst =:= tp2
-        else isRelatable(tv1, tp2) && (tv1 tryInstantiate wildcardToTypeVarMap(tp2))
-      case (_, tv2 @ TypeVar(_, constr2)) =>
-        if (constr2.inst != NoType) tp1 =:= constr2.inst
-        else isRelatable(tv2, tp1) && (tv2 tryInstantiate wildcardToTypeVarMap(tp1))
+      case (tv @ TypeVar(_,_), tp) =>
+        tv.registerTypeEquality(tp, true)
+      case (tp, tv @ TypeVar(_,_)) =>
+        tv.registerTypeEquality(tp, false)
       case (AnnotatedType(_,_,_), _) =>
-        annotationsConform(tp1, tp2) && annotationsConform(tp2, tp1) && tp1.withoutAttributes =:= tp2.withoutAttributes
+        annotationsConform(tp1, tp2) && annotationsConform(tp2, tp1) && tp1.withoutAnnotations =:= tp2.withoutAnnotations
       case (_, AnnotatedType(_,_,_)) =>
-        annotationsConform(tp1, tp2) && annotationsConform(tp2, tp1) && tp1.withoutAttributes =:= tp2.withoutAttributes
+        annotationsConform(tp1, tp2) && annotationsConform(tp2, tp1) && tp1.withoutAnnotations =:= tp2.withoutAnnotations
       case (_: SingletonType, _: SingletonType) =>
         var origin1 = tp1
         while (origin1.underlying.isInstanceOf[SingletonType]) {
@@ -3538,24 +4085,190 @@ A type's typeSymbol should never be inspected directly.
       val tp2n = normalizePlus(tp2)
       ((tp1n ne tp1) || (tp2n ne tp2)) && isSameType(tp1n, tp2n)
     }
+  }
+*/
+  private def isSameType1(tp1: Type, tp2: Type): Boolean = {
+    if ((tp1 eq tp2) || 
+        (tp1 eq ErrorType) || (tp1 eq WildcardType) ||
+        (tp2 eq ErrorType) || (tp2 eq WildcardType))
+      true
+    else if ((tp1 eq NoType) || (tp2 eq NoType))
+      false
+    else if (tp1 eq NoPrefix) 
+      tp2.typeSymbol.isPackageClass
+    else if (tp2 eq NoPrefix)
+      tp1.typeSymbol.isPackageClass
+    else {
+      isSameType2(tp1, tp2) || {
+        val tp1n = normalizePlus(tp1)
+        val tp2n = normalizePlus(tp2)
+        ((tp1n ne tp1) || (tp2n ne tp2)) && isSameType(tp1n, tp2n)
+      }
+    }
+  }
+  
+  def isSameType2(tp1: Type, tp2: Type): Boolean = {
+    tp1 match {
+      case tr1: TypeRef =>
+        tp2 match {
+          case tr2: TypeRef =>
+            return (equalSymsAndPrefixes(tr1.sym, tr1.pre, tr2.sym, tr2.pre) &&
+              ((tp1.isHigherKinded && tp2.isHigherKinded && tp1.normalize =:= tp2.normalize) || 
+               isSameTypes(tr1.args, tr2.args))) ||
+               ((tr1.pre, tr2.pre) match {
+                 case (tv @ TypeVar(_,_), _) => tv.registerTypeSelection(tr1.sym, tr2)
+                 case (_, tv @ TypeVar(_,_)) => tv.registerTypeSelection(tr2.sym, tr1)
+                 case _ => false
+               })
+          case _ =>
+        }
+      case tt1: ThisType =>
+        tp2 match {
+          case tt2: ThisType =>
+            if (tt1.sym == tt2.sym) return true
+          case _ =>
+        }
+      case st1: SingleType =>
+        tp2 match {
+          case st2: SingleType =>
+            if (equalSymsAndPrefixes(st1.sym, st1.pre, st2.sym, st2.pre)) return true
+          case _ =>
+        }
+      case ct1: ConstantType =>
+        tp2 match {
+          case ct2: ConstantType =>
+            return (ct1.value == ct2.value)
+          case _ =>
+        }
+      case rt1: RefinedType =>
+        tp2 match {
+          case rt2: RefinedType => // 
+            def isSubScope(s1: Scope, s2: Scope): Boolean = s2.toList.forall {
+              sym2 =>
+                var e1 = s1.lookupEntry(sym2.name)
+                (e1 ne null) && {
+                  val substSym = sym2.info.substThis(sym2.owner, e1.sym.owner.thisType)
+                  var isEqual = false
+                  while (!isEqual && (e1 ne null)) { 
+                    isEqual = e1.sym.info =:= substSym
+                    e1 = s1.lookupNextEntry(e1)
+                  }
+                  isEqual
+                }
+            }
+            //Console.println("is same? " + tp1 + " " + tp2 + " " + tp1.typeSymbol.owner + " " + tp2.typeSymbol.owner)//DEBUG
+            return isSameTypes(rt1.parents, rt2.parents) && {
+              val decls1 = rt1.decls
+              val decls2 = rt2.decls
+              isSubScope(decls1, decls2) && isSubScope(decls2, decls1)
+            }
+          case _ =>
+        }
+      case mt1: MethodType =>
+        tp2 match {
+          case mt2: MethodType =>
+            // DEPMETTODO new dependent types: probably fix this, use substSym as done for PolyType
+            return isSameTypes(mt1.paramTypes, mt2.paramTypes) &&
+              mt1.resultType =:= mt2.resultType &&
+              mt1.isImplicit == mt2.isImplicit
+          case _ =>
+        }
+      case PolyType(tparams1, res1) =>
+        tp2 match {
+          case PolyType(tparams2, res2) =>
+//            assert((tparams1 map (_.typeParams.length)) == (tparams2 map (_.typeParams.length)))
+              // @M looks like it might suffer from same problem as #2210
+              return (
+                (tparams1.length == tparams2.length) && // corresponds does not check length of two sequences before checking the predicate
+                (tparams1 corresponds tparams2)(_.info =:= _.info.substSym(tparams2, tparams1)) && 
+                res1 =:= res2.substSym(tparams2, tparams1)
+              )
+          case _ =>
+        }
+      case ExistentialType(tparams1, res1) =>
+        tp2 match {
+          case ExistentialType(tparams2, res2) =>
+            // @M looks like it might suffer from same problem as #2210
+            return (
+              (tparams1.length == tparams2.length) && // corresponds does not check length of two sequences before checking the predicate -- faster & needed to avoid crasher in #2956
+              (tparams1 corresponds tparams2)(_.info =:= _.info.substSym(tparams2, tparams1)) && 
+              res1 =:= res2.substSym(tparams2, tparams1)
+            )
+          case _ =>
+        }
+      case TypeBounds(lo1, hi1) =>
+        tp2 match {
+          case TypeBounds(lo2, hi2) =>
+            return lo1 =:= lo2 && hi1 =:= hi2
+          case _ =>
+        }
+      case BoundedWildcardType(bounds) =>
+        return bounds containsType tp2
+      case _ =>
+    }
+    tp2 match {
+      case BoundedWildcardType(bounds) =>
+        return bounds containsType tp1
+      case _ =>
+    }
+    tp1 match {
+      case tv @ TypeVar(_,_) =>
+        return tv.registerTypeEquality(tp2, true)
+      case _ =>
+    }
+    tp2 match {
+      case tv @ TypeVar(_,_) =>
+        return tv.registerTypeEquality(tp1, false)
+      case _ =>
+    }
+    tp1 match {
+      case _: AnnotatedType =>
+        return annotationsConform(tp1, tp2) && annotationsConform(tp2, tp1) && tp1.withoutAnnotations =:= tp2.withoutAnnotations
+      case _ =>
+    }
+    tp2 match {
+      case _: AnnotatedType =>
+        return annotationsConform(tp1, tp2) && annotationsConform(tp2, tp1) && tp1.withoutAnnotations =:= tp2.withoutAnnotations
+      case _ =>
+    }
+    tp1 match {
+      case _: SingletonType =>
+        tp2 match {
+          case _: SingletonType =>
+            var origin1 = tp1
+            while (origin1.underlying.isInstanceOf[SingletonType]) {
+              assert(origin1 ne origin1.underlying, origin1)
+              origin1 = origin1.underlying
+            }
+            var origin2 = tp2
+            while (origin2.underlying.isInstanceOf[SingletonType]) {
+              assert(origin2 ne origin2.underlying, origin2)
+              origin2 = origin2.underlying
+            }
+            ((origin1 ne tp1) || (origin2 ne tp2)) && (origin1 =:= origin2)
+          case _ =>
+            false
+        }
+      case _ =>
+        false
+    }
+  }
 
   /** Are `tps1' and `tps2' lists of pairwise equivalent
    *  types?
    */
-  def isSameTypes(tps1: List[Type], tps2: List[Type]): Boolean =
-    tps1.length == tps2.length &&
-    List.forall2(tps1, tps2)((tp1, tp2) => tp1 =:= tp2)
+  def isSameTypes(tps1: List[Type], tps2: List[Type]): Boolean = (tps1 corresponds tps2)(_ =:= _)
 
-  private var pendingSubTypes = new collection.mutable.HashSet[SubTypePair]
+  private val pendingSubTypes = new collection.mutable.HashSet[SubTypePair]
   private var basetypeRecursions: Int = 0
-  private var pendingBaseTypes = new collection.mutable.HashSet[Type]
+  private val pendingBaseTypes = new collection.mutable.HashSet[Type]
 
   def isSubType(tp1: Type, tp2: Type): Boolean = isSubType(tp1, tp2, AnyDepth)
 
   def isSubType(tp1: Type, tp2: Type, depth: Int): Boolean = try {
     subsametypeRecursions += 1
-    val lastUndoLog = undoLog
-    val result = 
+
+    undoLog undoUnless { // if subtype test fails, it should not affect constraints on typevars
       if (subsametypeRecursions >= LogPendingSubTypesThreshold) {
         val p = new SubTypePair(tp1, tp2)
         if (pendingSubTypes contains p) 
@@ -3563,27 +4276,31 @@ A type's typeSymbol should never be inspected directly.
         else 
           try {
             pendingSubTypes += p
-            isSubType0(tp1, tp2, depth)
+            isSubType2(tp1, tp2, depth)
           } finally {
             pendingSubTypes -= p
           }
       } else {
-        isSubType0(tp1, tp2, depth)
+        isSubType2(tp1, tp2, depth)
       }
-    if (!result) undoTo(lastUndoLog)
-    result
+    }
   } finally {
     subsametypeRecursions -= 1
-    if (subsametypeRecursions == 0) undoLog = List()
+    if (subsametypeRecursions == 0) undoLog clear
   }
 
-
-  /** Does this type have a prefix that begins with a type variable */
-  def beginsWithTypeVar(tp: Type): Boolean = tp match {
+  /** Does this type have a prefix that begins with a type variable,
+   *  or is it a refinement type? For type prefixes that fulfil this condition,
+   *  type selections with the same name of equal (wrt) =:= prefixes are
+   *  considered equal wrt =:=
+   */
+  def beginsWithTypeVarOrIsRefined(tp: Type): Boolean = tp match {
     case SingleType(pre, sym) =>
-      !(sym hasFlag PACKAGE) && beginsWithTypeVar(pre)
-    case TypeVar(_, constr) =>
-      constr.inst == NoType || beginsWithTypeVar(constr.inst)
+      !(sym hasFlag PACKAGE) && beginsWithTypeVarOrIsRefined(pre)
+    case tv at TypeVar(_, constr) =>
+      !tv.instValid || beginsWithTypeVarOrIsRefined(constr.inst)
+    case RefinedType(_, _) => 
+      true
     case _ =>
       false
   }
@@ -3599,158 +4316,264 @@ A type's typeSymbol should never be inspected directly.
       tp
   }
 
+  def isErrorOrWildcard(tp: Type) = (tp eq ErrorType) || (tp eq WildcardType)
+
+  def isSingleType(tp: Type) = tp match {
+    case ThisType(_) | SuperType(_, _) | SingleType(_, _) => true
+    case _ => false
+  }
+
+  def isConstantType(tp: Type) = tp match {
+    case ConstantType(_) => true
+    case _ => false
+  }
+
+  // @assume tp1.isHigherKinded || tp2.isHigherKinded
+  def isHKSubType0(tp1: Type, tp2: Type, depth: Int): Boolean = (
+    tp1.typeSymbol == NothingClass 
+    ||
+    tp2.typeSymbol == AnyClass // @M Any and Nothing are super-type resp. subtype of every well-kinded type
+    || // @M! normalize reduces higher-kinded case to PolyType's
+    ((tp1.normalize, tp2.normalize) match {
+      case (PolyType(tparams1, res1), PolyType(tparams2, res2)) => // @assume tp1.isHigherKinded && tp2.isHigherKinded (as they were both normalized to PolyType)
+        tparams1.length == tparams2.length && {
+          if (tparams1.isEmpty) res1 <:< res2 // fast-path: monomorphic nullary method type
+          else if (tparams1.head.owner.isMethod) {  // fast-path: polymorphic method type -- type params cannot be captured
+            (tparams1 corresponds tparams2)((p1, p2) => p2.info.substSym(tparams2, tparams1) <:< p1.info) &&
+            res1 <:< res2.substSym(tparams2, tparams1)
+          } else { // normalized higher-kinded type
+            //@M for an example of why we need to generate fresh symbols, see neg/tcpoly_ticket2101.scala
+            val tpsFresh = cloneSymbols(tparams1)
+
+            (tparams1 corresponds tparams2)((p1, p2) =>
+              p2.info.substSym(tparams2, tpsFresh) <:< p1.info.substSym(tparams1, tpsFresh)) &&   // @PP: corresponds
+            res1.substSym(tparams1, tpsFresh) <:< res2.substSym(tparams2, tpsFresh)
+
+            //@M the forall in the previous test could be optimised to the following,
+            // but not worth the extra complexity since it only shaves 1s from quick.comp
+            //   (List.forall2(tpsFresh/*optimisation*/, tparams2)((p1, p2) =>
+            //   p2.info.substSym(tparams2, tpsFresh) <:< p1.info /*optimisation, == (p1 from tparams1).info.substSym(tparams1, tpsFresh)*/) &&
+            // this optimisation holds because inlining cloneSymbols in `val tpsFresh = cloneSymbols(tparams1)` gives:
+            // val tpsFresh = tparams1 map (_.cloneSymbol)
+            // for (tpFresh <- tpsFresh) tpFresh.setInfo(tpFresh.info.substSym(tparams1, tpsFresh))
+        }
+      }
+      case (_, _) => false // @assume !tp1.isHigherKinded || !tp2.isHigherKinded 
+      // --> thus, cannot be subtypes (Any/Nothing has already been checked)
+    }))
+
+  def isSubArgs(tps1: List[Type], tps2: List[Type], tparams: List[Symbol]): Boolean = (
+    tps1.isEmpty && tps2.isEmpty
+    ||
+    !tps1.isEmpty && !tps2.isEmpty &&
+    (tparams.head.isCovariant || (tps2.head <:< tps1.head)) &&
+    (tparams.head.isContravariant || (tps1.head <:< tps2.head)) &&
+    isSubArgs(tps1.tail, tps2.tail, tparams.tail)
+  )
+
+  def differentOrNone(tp1: Type, tp2: Type) = if (tp1 eq tp2) NoType else tp1
+
   /** Does type `tp1' conform to `tp2'?
    */
-  private def isSubType0(tp1: Type, tp2: Type, depth: Int): Boolean = {
-    ((tp1, tp2) match {
-      case (ErrorType, _)    => true
-      case (WildcardType, _) => true
-      case (_, ErrorType)    => true
-      case (_, WildcardType) => true
-
-      case (NoType, _)   => false
-      case (NoPrefix, _) => tp2 == NoPrefix || tp2.typeSymbol.isPackageClass
-      case (_, NoType)   => false
-      case (_, NoPrefix) => tp1 == NoPrefix || tp1.typeSymbol.isPackageClass
-
-      case (ThisType(_), ThisType(_))           => tp1 =:= tp2
-      case (ThisType(_), SingleType(_, _))      => tp1 =:= tp2
-      case (SingleType(_, _), ThisType(_))      => tp1 =:= tp2
-      case (SingleType(_, _), SingleType(_, _)) => tp1 =:= tp2
-      case (ConstantType(_), ConstantType(_))   => tp1 =:= tp2
-      case (TypeRef(pre1, sym1: TypeSkolem, args1), TypeRef(pre2, sym2: TypeSkolem, args2)) 
-      if (inIDE && args1 == args2 && pre1 == pre2 && sym1.deSkolemize == sym2.deSkolemize) => true
-      case (TypeRef(pre1, sym1, args1), TypeRef(pre2, sym2, args2)) 
-      if !(tp1.isHigherKinded || tp2.isHigherKinded) =>         
-        //Console.println("isSubType " + tp1 + " " + tp2);//DEBUG
-        if (inIDE) { trackTypeIDE(sym1); trackTypeIDE(sym2); }
-        
-        def isSubArgs(tps1: List[Type], tps2: List[Type],
-                      tparams: List[Symbol]): Boolean = (
-          tps1.isEmpty && tps2.isEmpty
-          ||
-          !tps1.isEmpty && !tps2.isEmpty &&
-          (tparams.head.isCovariant || (tps2.head <:< tps1.head)) &&
-          (tparams.head.isContravariant || (tps1.head <:< tps2.head)) &&
-          isSubArgs(tps1.tail, tps2.tail, tparams.tail)
-        );
-        ((if (sym1 == sym2) phase.erasedTypes || pre1 <:< pre2
-          else (sym1.name == sym2.name) && isUnifiable(pre1, pre2)) &&
-         (sym2 == AnyClass || isSubArgs(args1, args2, sym1.typeParams)) //@M: Any is kind-polymorphic
-         ||
-         sym1.isAbstractType && isDifferentType(tp1, tp1.bounds.hi) && (tp1.bounds.hi <:< tp2)
-         ||
-         sym2.isAbstractType && isDifferentType(tp2, tp2.bounds.lo) && (tp1 <:< tp2.bounds.lo)
-         ||
-         sym2.isClass &&
-         ({ val base = tp1 baseType sym2; !(base eq tp1) && (base <:< tp2) })
-         ||
-         sym1 == NothingClass
-         ||
-         //{ Console.println("last chance " + sym1 + " " + sym2 + " " + sym2.isClass + " " + (sym2 isSubClass ObjectClass)); true } &&
-         sym1 == NullClass && 
-         sym2.isClass && (sym2 isNonBottomSubClass ObjectClass) && (!(tp2.normalize.typeSymbol isNonBottomSubClass NotNullClass)) 
-         ||
-         {
-           val tp1n = normalizePlus(tp1)
-           val tp2n = normalizePlus(tp2)
-           ((tp1n ne tp1) || (tp2n ne tp2)) && isSubType(tp1n, tp2n, depth)
-         })
-      case (MethodType(pts1, res1), MethodType(pts2, res2)) =>
-        (pts1.length == pts2.length && 
-         matchingParams(pts1, pts2, tp1.isInstanceOf[JavaMethodType], tp2.isInstanceOf[JavaMethodType]) && 
-         (res1 <:< res2) &&
-         tp1.isInstanceOf[ImplicitMethodType] == tp2.isInstanceOf[ImplicitMethodType])
-      case (PolyType(tparams1, res1), PolyType(tparams2, res2)) =>
-        (tparams1.length == tparams2.length &&
-         List.forall2(tparams1, tparams2) 
-           ((p1, p2) => p2.info.substSym(tparams2, tparams1) <:< p1.info) &&
-         res1 <:< res2.substSym(tparams2, tparams1))
-      case (TypeBounds(lo1, hi1), TypeBounds(lo2, hi2)) =>
-        lo2 <:< lo1 && hi1 <:< hi2
-      case (AnnotatedType(_,_,_), _) =>
-        annotationsConform(tp1, tp2) && tp1.withoutAttributes <:< tp2.withoutAttributes
-      case (_, AnnotatedType(_,_,_)) =>
-        annotationsConform(tp1, tp2) && tp1.withoutAttributes <:< tp2.withoutAttributes
-      case (BoundedWildcardType(bounds), _) =>
-        bounds.lo <:< tp2
-      case (_, BoundedWildcardType(bounds)) =>
+  private def isSubType2(tp1: Type, tp2: Type, depth: Int): Boolean = {
+    if (tp1 eq tp2) return true
+    if (isErrorOrWildcard(tp1)) return true
+    if (isErrorOrWildcard(tp2)) return true
+    if (tp1 eq NoType) return false
+    if (tp2 eq NoType) return false
+    if (tp1 eq NoPrefix) return (tp2 eq NoPrefix) || tp2.typeSymbol.isPackageClass
+    if (tp2 eq NoPrefix) return (tp1 eq NoPrefix) || tp1.typeSymbol.isPackageClass
+    if (isSingleType(tp1) && isSingleType(tp2) ||
+        isConstantType(tp1) && isConstantType(tp2)) return tp1 =:= tp2
+    if (tp1.isHigherKinded || tp2.isHigherKinded) return isHKSubType0(tp1, tp2, depth)
+
+    /** First try, on the right:
+     *   - unwrap Annotated types, BoundedWildcardTypes,
+     *   - bind TypeVars  on the right, if lhs is not Annotated nor BoundedWildcard
+     *   - handle common cases for first-kind TypeRefs on both sides as a fast path.
+     */
+    def firstTry = { incCounter(ctr1); tp2 match {
+      // fast path: two typerefs, none of them HK
+      case tr2: TypeRef =>
+        tp1 match {
+          case tr1: TypeRef =>
+            val sym1 = tr1.sym
+            val sym2 = tr2.sym
+            val pre1 = tr1.pre
+            val pre2 = tr2.pre
+            (((if (sym1 == sym2) phase.erasedTypes || pre1 <:< pre2
+               else (sym1.name == sym2.name && 
+                     (isUnifiable(pre1, pre2) || isSameSpecializedSkolem(sym1, sym2, pre1, pre2)))) &&
+                    isSubArgs(tr1.args, tr2.args, sym1.typeParams))
+             ||
+             sym2.isClass && {
+               val base = tr1 baseType sym2
+               (base ne tr1) && base <:< tr2
+             }
+             ||
+             thirdTryRef(tr1, tr2))
+          case _ =>
+            secondTry
+        }
+      case AnnotatedType(_, _, _) =>
+        tp1.withoutAnnotations <:< tp2.withoutAnnotations && annotationsConform(tp1, tp2)
+      case BoundedWildcardType(bounds) =>
         tp1 <:< bounds.hi
-      case (_, tv2 @ TypeVar(_, constr2)) =>
-        if (constr2.inst != NoType) tp1 <:< constr2.inst
-        else isRelatable(tv2, tp1) && { constr2.lobounds = tp1 :: constr2.lobounds; true }
-      case (tv1 @ TypeVar(_, constr1), _) =>
-        if (constr1.inst != NoType) constr1.inst <:< tp2 
-        else isRelatable(tv1, tp2) && { constr1.hibounds = tp2 :: constr1.hibounds; true }
-      case (_, _)  if (tp1.isHigherKinded || tp2.isHigherKinded) =>
-        (tp1.typeSymbol == NothingClass 
-         ||
-         tp2.typeSymbol == AnyClass // @M Any and Nothing are super-type resp. subtype of every well-kinded type
-         || // @M! normalize reduces higher-kinded case to PolyType's
-         (tp1.isHigherKinded && tp2.isHigherKinded) && isSubType0(tp1.normalize, tp2.normalize, depth))
-      case (_, TypeRef(pre2, sym2, args2)) 
-      if (sym2.isAbstractType && isDifferentType(tp2, tp2.bounds.lo) && (tp1 <:< tp2.bounds.lo) && 
-            (if (!inIDE) true else trackTypeIDE(sym2)) ||
-          sym2 == NotNullClass && tp1.isNotNull) => 
-        true
-      case (_, TypeRef(pre2, sym2, args2)) 
-      if (sym2 == SingletonClass && tp1.isStable) =>
-        true
-      case (_, RefinedType(parents2, ref2)) =>
-        (parents2 forall (tp2 => tp1 <:< tp2)) &&
-        (ref2.toList forall tp1.specializes) /* &&
- removed, replaced by stricter condition on stable values.
-        (tp1.typeSymbol != NullClass || !parents2.exists(_.typeSymbol.isAbstractType))
-*/
-      case (ExistentialType(_, _), _) =>
+      case tv2 @ TypeVar(_, constr2) =>
+        tp1 match {
+          case AnnotatedType(_, _, _) | BoundedWildcardType(_) =>
+            secondTry
+          case _ =>
+            tv2.registerBound(tp1, true)
+        }
+      case _ =>
+        secondTry
+    }}
+
+    /** Second try, on the left:
+     *   - unwrap AnnotatedTypes, BoundedWildcardTypes,
+     *   - bind typevars,
+     *   - handle existential types by skolemization.
+     */
+    def secondTry = { incCounter(ctr2); tp1 match {
+      case AnnotatedType(_, _, _) =>
+        tp1.withoutAnnotations <:< tp2.withoutAnnotations && annotationsConform(tp1, tp2)
+      case BoundedWildcardType(bounds) =>
+        tp1.bounds.lo <:< tp2
+      case tv @ TypeVar(_,_) =>
+        tv.registerBound(tp2, false)
+      case ExistentialType(_, _) =>
         try { 
           skolemizationLevel += 1
-          tp1.skolemizeExistential(NoSymbol, null) <:< tp2
+          tp1.skolemizeExistential <:< tp2
         } finally {
           skolemizationLevel -= 1
         }
-      case (_, et: ExistentialType) if et.withTypeVars(tp1 <:< _, depth) =>
-        true
-      case (RefinedType(parents1, ref1), _) =>
+      case _ =>
+        thirdTry
+    }}
+
+    def thirdTryRef(tp1: Type, tp2: TypeRef): Boolean = { 
+      incCounter(ctr3); 
+      val sym2 = tp2.sym
+      sym2 match {
+        case _: ClassSymbol =>
+          if (sym2 == NotNullClass)
+            tp1.isNotNull
+          else if (sym2 == SingletonClass)
+            tp1.isStable || fourthTry
+          else if (isRaw(sym2, tp2.args))
+            isSubType(tp1, rawToExistential(tp2), depth)
+          else if (sym2.name == nme.REFINE_CLASS_NAME.toTypeName)
+            isSubType(tp1, sym2.info, depth)
+          else
+            fourthTry
+        case _: TypeSymbol =>
+          if (sym2 hasFlag DEFERRED) {
+            val tp2a = tp2.bounds.lo
+            isDifferentTypeConstructor(tp2, tp2a) && tp1 <:< tp2a || fourthTry
+          } else {
+            isSubType(tp1.normalize, tp2.normalize, depth)
+          }
+        case _ =>
+          fourthTry
+      }
+    }
+    
+    /** Third try, on the right:
+     *   - decompose refined types.
+     *   - handle typerefs, existentials, and notnull types.
+     *   - handle left+right method types, polytypes, typebounds
+     */
+    def thirdTry = { incCounter(ctr3); tp2 match {
+      case tr2: TypeRef =>
+        thirdTryRef(tp1, tr2)
+      case rt2: RefinedType =>
+        (rt2.parents forall (tp1 <:< _)) &&
+        (rt2.decls.toList forall tp1.specializes)
+      case et2: ExistentialType =>
+        et2.withTypeVars(tp1 <:< _, depth) || fourthTry
+      case nn2: NotNullType =>
+        tp1.isNotNull && tp1 <:< nn2.underlying
+      case mt2: MethodType =>
+        tp1 match {
+          case mt1 @ MethodType(params1, res1) =>
+            val params2 = mt2.params
+            val res2 = mt2.resultType
+            (params1.length == params2.length &&
+             matchingParams(params1, params2, mt1.isJava, mt2.isJava) && 
+             (res1 <:< res2) &&
+             mt1.isImplicit == mt2.isImplicit)
+          case _ =>
+            false
+        }
+      case pt2 @ PolyType(List(), _) =>
+        tp1 match {
+          case pt1 @ PolyType(List(), _) =>
+            // other polytypes were already checked in isHKSubType
+            pt1.resultType <:< pt2.resultType
+          case _ =>
+            false
+        }
+      case TypeBounds(lo2, hi2) =>
+        tp1 match {
+          case TypeBounds(lo1, hi1) =>
+            lo2 <:< lo1 && hi1 <:< hi2
+          case _ =>
+            false
+        }
+      case _ =>
+        fourthTry
+    }}
+
+    /** Fourth try, on the left:
+     *   - handle typerefs, refined types, notnull and singleton types. 
+     */
+    def fourthTry = { incCounter(ctr4); tp1 match {
+      case tr1 @ TypeRef(_, sym1, _) =>
+        sym1 match {
+          case _: ClassSymbol =>
+            if (sym1 == NothingClass) 
+              true
+            else if (sym1 == NullClass)
+              tp2 match {
+                case TypeRef(_, sym2, _) =>
+                  sym2.isClass && (sym2 isNonBottomSubClass ObjectClass) &&
+                  !(tp2.normalize.typeSymbol isNonBottomSubClass NotNullClass)
+                case _ =>
+                  isSingleType(tp2) && tp1 <:< tp2.widen
+              }
+            else if (isRaw(sym1, tr1.args)) 
+              isSubType(rawToExistential(tp1), tp2, depth)
+            else 
+              sym1.name == nme.REFINE_CLASS_NAME.toTypeName &&
+              isSubType(sym1.info, tp2, depth)
+          case _: TypeSymbol =>
+            if (sym1 hasFlag DEFERRED) {
+              val tp1a = tp1.bounds.hi
+              isDifferentTypeConstructor(tp1, tp1a) && tp1a <:< tp2
+            } else {
+              isSubType(tp1.normalize, tp2.normalize, depth)
+            } 
+          case _ =>
+            false
+        }
+      case RefinedType(parents1, _) =>
         parents1 exists (_ <:< tp2)
-      
-      /* todo: replace following with 
-      case (ThisType(_), _) 
-         | {SingleType(_, _), _}
-         | {ConstantType(_), _} =>
-         once patern matching bug is fixed */
-      case (_, NotNullType(ntp2)) =>
-        tp1.isNotNull && tp1 <:< ntp2
-      case (NotNullType(ntp1), _) =>
-        ntp1 <:< tp2
-      case (ThisType(_), _) => tp1.underlying <:< tp2
-      case (SingleType(_, _), _) => tp1.underlying <:< tp2
-      case (ConstantType(_), _) => 
+      case _: SingletonType | _: NotNullType =>
         tp1.underlying <:< tp2
-
-      case (TypeRef(pre1, sym1, args1), _) =>
-        if (inIDE) trackTypeIDE(sym1)
-        (sym1 == NothingClass && tp2 <:< AnyClass.tpe
-         ||
-         sym1 == NullClass && tp2.isInstanceOf[SingletonType] && (tp1 <:< tp2.widen)
-         ||
-         sym1.isAbstractType && (tp1.bounds.hi <:< tp2))
       case _ =>
         false
-    }) || {
-      val tp1n = normalizePlus(tp1)
-      val tp2n = normalizePlus(tp2)
-      ((tp1n ne tp1) || (tp2n ne tp2)) && isSubType0(tp1n, tp2n, depth)
-    }
+    }}
+
+    firstTry
   }
 
   /** Are `tps1' and `tps2' lists of equal length such
    *  that all elements of `tps1' conform to corresponding elements
    *  of `tps2'?
    */
-  def isSubTypes(tps1: List[Type], tps2: List[Type]): Boolean =
-    tps1.length == tps2.length &&
-    List.forall2(tps1, tps2)((tp1, tp2) => tp1 <:< tp2)
+  def isSubTypes(tps1: List[Type], tps2: List[Type]): Boolean = (tps1 corresponds tps2)(_ <:< _)
 
   /** Does type `tp' implement symbol `sym' with same or
    *  stronger type? Exact only if `sym' is a member of some
@@ -3769,21 +4592,84 @@ A type's typeSymbol should never be inspected directly.
     val info1 = tp1.memberInfo(sym1)
     val info2 = tp2.memberInfo(sym2).substThis(tp2.typeSymbol, tp1)
     //System.out.println("specializes "+tp1+"."+sym1+":"+info1+sym1.locationString+" AND "+tp2+"."+sym2+":"+info2)//DEBUG
-    sym2.isTerm && (info1 <:< info2) ||
-    sym2.isAbstractType && info2.bounds.containsType(tp1.memberType(sym1)) ||
+    sym2.isTerm && (info1 <:< info2) /*&& (!sym2.isStable || sym1.isStable) */ ||
+    sym2.isAbstractType && {
+      val memberTp1 = tp1.memberType(sym1)
+      // println("kinds conform? "+(memberTp1, tp1, sym2, kindsConform(List(sym2), List(memberTp1), tp2, sym2.owner)))
+      info2.bounds.containsType(memberTp1) && 
+      kindsConform(List(sym2), List(memberTp1), tp1, sym1.owner) 
+    } ||
     sym2.isAliasType && tp2.memberType(sym2).substThis(tp2.typeSymbol, tp1) =:= tp1.memberType(sym1) //@MAT ok
   }
 
   /** A function implementing `tp1' matches `tp2' */
-  def matchesType(tp1: Type, tp2: Type, alwaysMatchSimple: Boolean): Boolean = {
+  final def matchesType(tp1: Type, tp2: Type, alwaysMatchSimple: Boolean): Boolean = {
+    def matchesQuantified(tparams1: List[Symbol], tparams2: List[Symbol], res1: Type, res2: Type): Boolean = 
+      tparams1.length == tparams2.length &&
+      matchesType(res1, res2.substSym(tparams2, tparams1), alwaysMatchSimple)
+    def lastTry = 
+      tp2 match {
+        case ExistentialType(_, res2) if alwaysMatchSimple =>
+          matchesType(tp1, res2, true)
+        case MethodType(_, _) =>
+          false
+        case PolyType(tparams2, res2) =>
+          tparams2.isEmpty && matchesType(tp1, res2, alwaysMatchSimple)
+        case _ =>
+          alwaysMatchSimple || tp1 =:= tp2
+      }
+    tp1 match {
+      case mt1 @ MethodType(params1, res1) =>
+        tp2 match {
+          case mt2 @ MethodType(params2, res2) =>
+            params1.length == params2.length && // useful pre-screening optimization 
+            matchingParams(params1, params2, mt1.isJava, mt2.isJava) && 
+            matchesType(res1, res2, alwaysMatchSimple) &&
+            mt1.isImplicit == mt2.isImplicit
+          case PolyType(List(), res2) => 
+            if (params1.isEmpty) matchesType(res1, res2, alwaysMatchSimple)
+            else matchesType(tp1, res2, alwaysMatchSimple)
+          case ExistentialType(_, res2) =>
+            alwaysMatchSimple && matchesType(tp1, res2, true)
+          case _ =>
+            false
+        }
+      case PolyType(tparams1, res1) =>
+        tp2 match {
+          case PolyType(tparams2, res2) =>
+            matchesQuantified(tparams1, tparams2, res1, res2)
+          case MethodType(List(), res2) if (tparams1.isEmpty) =>
+            matchesType(res1, res2, alwaysMatchSimple)
+          case ExistentialType(_, res2) =>
+            alwaysMatchSimple && matchesType(tp1, res2, true)
+          case _ =>
+            tparams1.isEmpty && matchesType(res1, tp2, alwaysMatchSimple)
+        }
+      case ExistentialType(tparams1, res1) =>
+        tp2 match {
+          case ExistentialType(tparams2, res2) =>
+            matchesQuantified(tparams1, tparams2, res1, res2)
+          case _ =>
+            if (alwaysMatchSimple) matchesType(res1, tp2, true)
+            else lastTry
+        }
+      case _ =>
+        lastTry
+    }
+  }
+
+/** matchesType above is an optimized version of the following implementation:
+
+  def matchesType2(tp1: Type, tp2: Type, alwaysMatchSimple: Boolean): Boolean = {
     def matchesQuantified(tparams1: List[Symbol], tparams2: List[Symbol], res1: Type, res2: Type): Boolean = 
       tparams1.length == tparams2.length &&
       matchesType(res1, res2.substSym(tparams2, tparams1), alwaysMatchSimple)
     (tp1, tp2) match {
-      case (MethodType(pts1, res1), MethodType(pts2, res2)) =>
-        matchingParams(pts1, pts2, tp1.isInstanceOf[JavaMethodType], tp2.isInstanceOf[JavaMethodType]) && 
+      case (MethodType(params1, res1), MethodType(params2, res2)) =>
+        params1.length == params2.length && // useful pre-secreening optimization 
+        matchingParams(params1, params2, tp1.isInstanceOf[JavaMethodType], tp2.isInstanceOf[JavaMethodType]) && 
         matchesType(res1, res2, alwaysMatchSimple) &&
-        tp1.isInstanceOf[ImplicitMethodType] == tp2.isInstanceOf[ImplicitMethodType]
+        tp1.isImplicit == tp2.isImplicit
       case (PolyType(tparams1, res1), PolyType(tparams2, res2)) =>
         matchesQuantified(tparams1, tparams2, res1, res2)
       case (PolyType(List(), rtp1), MethodType(List(), rtp2)) => 
@@ -3808,14 +4694,25 @@ A type's typeSymbol should never be inspected directly.
         alwaysMatchSimple || tp1 =:= tp2
     }
   }
+*/
 
-  /** Are `tps1' and `tps2' lists of pairwise equivalent types? */
-  private def matchingParams(tps1: List[Type], tps2: List[Type], tps1isJava: Boolean, tps2isJava: Boolean): Boolean =
-    tps1.length == tps2.length &&
-    List.forall2(tps1, tps2)((tp1, tp2) =>
-      (tp1 =:= tp2) || 
-      tps1isJava && tp2.typeSymbol == ObjectClass && tp1.typeSymbol == AnyClass ||
-      tps2isJava && tp1.typeSymbol == ObjectClass && tp2.typeSymbol == AnyClass)
+  /** Are `syms1' and `syms2' parameter lists with pairwise equivalent types? */
+  private def matchingParams(syms1: List[Symbol], syms2: List[Symbol], syms1isJava: Boolean, syms2isJava: Boolean): Boolean = syms1 match {
+    case Nil =>
+      syms2.isEmpty
+    case sym1 :: rest1 =>
+      syms2 match {
+        case Nil =>
+          false
+        case sym2 :: rest2 =>
+          val tp1 = sym1.tpe
+          val tp2 = sym2.tpe
+          (tp1 =:= tp2 || 
+           syms1isJava && tp2.typeSymbol == ObjectClass && tp1.typeSymbol == AnyClass ||
+           syms2isJava && tp1.typeSymbol == ObjectClass && tp2.typeSymbol == AnyClass) &&
+          matchingParams(rest1, rest2, syms1isJava, syms2isJava)
+      }
+  }
 
   /** like map2, but returns list `xs' itself - instead of a copy - if function
    *  `f' maps all elements to themselves.
@@ -3850,58 +4747,59 @@ A type's typeSymbol should never be inspected directly.
         val up = if (variance != CONTRAVARIANT) upper else !upper
         tvar.constr.inst = null
         val bound: Type = if (up) tparam.info.bounds.hi else tparam.info.bounds.lo
-        // Console.println("solveOne0 "+tvar+" "+config+" "+bound);//DEBUG
+        //Console.println("solveOne0(tv, tp, v, b)="+(tvar, tparam, variance, bound))
         var cyclic = bound contains tparam
         for ((tvar2, (tparam2, variance2)) <- config) {
           if (tparam2 != tparam &&
               ((bound contains tparam2) ||
-               up && (tparam2.info.bounds.lo =:= tparam.tpe) ||  //@M TODO: might be affected by change to tpe in Symbol
-               !up && (tparam2.info.bounds.hi =:= tparam.tpe))) {  //@M TODO: might be affected by change to tpe in Symbol
+               up && (tparam2.info.bounds.lo =:= tparam.tpe) ||
+               !up && (tparam2.info.bounds.hi =:= tparam.tpe))) {
             if (tvar2.constr.inst eq null) cyclic = true
             solveOne(tvar2, tparam2, variance2)
           }
         }
         if (!cyclic) {
           if (up) {
-            if (bound.typeSymbol != AnyClass) {
-              tvar.constr.hibounds =
-                bound.instantiateTypeParams(tparams, tvars) :: tvar.constr.hibounds
-            }
+            if (bound.typeSymbol != AnyClass)
+              tvar addHiBound bound.instantiateTypeParams(tparams, tvars)
             for (tparam2 <- tparams)
-              if (tparam2.info.bounds.lo =:= tparam.tpe)  //@M TODO: might be affected by change to tpe in Symbol
-                tvar.constr.hibounds =
-                  tparam2.tpe.instantiateTypeParams(tparams, tvars) :: tvar.constr.hibounds
+              tparam2.info.bounds.lo.dealias match {
+                case TypeRef(_, `tparam`, _) =>
+                  tvar addHiBound tparam2.tpe.instantiateTypeParams(tparams, tvars)
+                case _ =>
+              }
           } else {
             if (bound.typeSymbol != NothingClass && bound.typeSymbol != tparam) {
-              tvar.constr.lobounds =
-                bound.instantiateTypeParams(tparams, tvars) :: tvar.constr.lobounds
+              tvar addLoBound bound.instantiateTypeParams(tparams, tvars)
             }
             for (tparam2 <- tparams)
-              if (tparam2.info.bounds.hi =:= tparam.tpe)  //@M TODO: might be affected by change to tpe in Symbol
-                tvar.constr.lobounds =
-                  tparam2.tpe.instantiateTypeParams(tparams, tvars) :: tvar.constr.lobounds 
+              tparam2.info.bounds.hi.dealias match {
+                case TypeRef(_, `tparam`, _) => 
+                  tvar addLoBound tparam2.tpe.instantiateTypeParams(tparams, tvars)
+                case _ =>
+              }
           }
         }
         tvar.constr.inst = NoType // necessary because hibounds/lobounds may contain tvar
+
+        //println("solving "+tvar+" "+up+" "+(if (up) (tvar.constr.hiBounds) else tvar.constr.loBounds)+((if (up) (tvar.constr.hiBounds) else tvar.constr.loBounds) map (_.widen)))
+
         tvar setInst (
           if (up) {
-            if (depth != AnyDepth) glb(tvar.constr.hibounds, depth) else glb(tvar.constr.hibounds)
+            if (depth != AnyDepth) glb(tvar.constr.hiBounds, depth) else glb(tvar.constr.hiBounds)
           } else {
-            if (depth != AnyDepth) lub(tvar.constr.lobounds, depth) else lub(tvar.constr.lobounds)
+            if (depth != AnyDepth) lub(tvar.constr.loBounds, depth) else lub(tvar.constr.loBounds)
           })
-        //Console.println("solving "+tvar+" "+up+" "+(if (up) (tvar.constr.hibounds) else tvar.constr.lobounds)+((if (up) (tvar.constr.hibounds) else tvar.constr.lobounds) map (_.widen))+" = "+tvar.constr.inst)//DEBUG"
+
+        //Console.println("solving "+tvar+" "+up+" "+(if (up) (tvar.constr.hiBounds) else tvar.constr.loBounds)+((if (up) (tvar.constr.hiBounds) else tvar.constr.loBounds) map (_.widen))+" = "+tvar.constr.inst)//@MDEBUG
       }
-    }
+    }    
+    
+    // println("solving "+tvars+"/"+tparams+"/"+(tparams map (_.info)))
     for ((tvar, (tparam, variance)) <- config)
       solveOne(tvar, tparam, variance)
 
-    var ok = true
-    for (tvar <- tvars)
-      if (!(tvar.constr.lobounds forall (_ <:< tvar.constr.inst)) ||
-          !(tvar.constr.hibounds forall (tvar.constr.inst <:< _))) {
-        ok = false
-      }
-    ok
+    tvars forall (tvar => tvar.constr.isWithinBounds(tvar.constr.inst))
   }
 
   /** Do type arguments `targs' conform to formal parameters
@@ -3912,8 +4810,10 @@ A type's typeSymbol should never be inspected directly.
    *  @return        ...
    */
   def isWithinBounds(pre: Type, owner: Symbol, tparams: List[Symbol], targs: List[Type]): Boolean = {
-    val bounds = instantiatedBounds(pre, owner, tparams, targs)
-    !(List.map2(bounds, targs)((bound, targ) => bound containsType targ) contains false)
+    var bounds = instantiatedBounds(pre, owner, tparams, targs)
+    if (targs.exists(_.annotations.nonEmpty))
+      bounds = adaptBoundsToAnnotations(bounds, tparams, targs)
+    (bounds corresponds targs)(_ containsType _)  // @PP: corresponds
   }
 
   def instantiatedBounds(pre: Type, owner: Symbol, tparams: List[Symbol], targs: List[Type]): List[TypeBounds] = 
@@ -3999,7 +4899,7 @@ A type's typeSymbol should never be inspected directly.
     val ts0 = elimSub0(ts)
     if (ts0.length <= 1) ts0
     else {
-      val ts1 = List.mapConserve(ts0)(t => elimAnonymousClass(t.underlying))
+      val ts1 = ts0 mapConserve (t => elimAnonymousClass(t.underlying))
       if (ts1 eq ts0) ts0
       else elimSub(ts1, depth)
     }
@@ -4014,97 +4914,168 @@ A type's typeSymbol should never be inspected directly.
       case ExistentialType(_, res) => 
         res
       case TypeVar(_, constr) => 
-        if ((constr.inst ne null) && (constr.inst ne NoType)) constr.inst
-        else throw new Error("trying to do lub/glb of typevar "+tp)
+        if (constr.instValid) constr.inst
+        else abort("trying to do lub/glb of typevar "+tp)
       case t => t
     }
-    val strippedTypes = List.mapConserve(ts)(stripType)
+    val strippedTypes = ts mapConserve (stripType)
     (strippedTypes, quantified)
   }
 
-  def lub(ts: List[Type]): Type = lub(ts, lubDepth(ts))
-    
+  def weakLub(ts: List[Type]) = 
+    if (ts.nonEmpty && (ts forall isNumericValueType)) (numericLub(ts), true)
+    else if (ts.nonEmpty && (ts exists (_.annotations.nonEmpty)))
+      (annotationsLub(lub(ts map (_.withoutAnnotations)), ts), true)
+    else (lub(ts), false)
+
+  def weakGlb(ts: List[Type]) = {
+    if (ts.nonEmpty && (ts forall isNumericValueType)) {
+      val nglb = numericGlb(ts)
+      if (nglb != NoType) (nglb, true)
+      else (glb(ts), false)
+    } else if (ts.nonEmpty && (ts exists (_.annotations.nonEmpty))) {
+      (annotationsGlb(glb(ts map (_.withoutAnnotations)), ts), true)
+    } else (glb(ts), false)
+  }
+
+  def numericLub(ts: List[Type]) =
+    ts reduceLeft ((t1, t2) => 
+      if (isNumericSubType(t1, t2)) t2 
+      else if (isNumericSubType(t2, t1)) t1
+      else IntClass.tpe)
+
+  def numericGlb(ts: List[Type]) =
+    ts reduceLeft ((t1, t2) => 
+      if (isNumericSubType(t1, t2)) t1 
+      else if (isNumericSubType(t2, t1)) t2
+      else NoType)
+
+  def isWeakSubType(tp1: Type, tp2: Type) = 
+    tp1.deconst.normalize match {
+      case TypeRef(_, sym1, _) if isNumericValueClass(sym1) =>
+        tp2.deconst.normalize match {
+          case TypeRef(_, sym2, _) if isNumericValueClass(sym2) =>
+            isNumericSubClass(sym1, sym2)
+          case tv2 @ TypeVar(_, _) =>
+            tv2.registerBound(tp1, isLowerBound = true, numBound = true)
+          case _ =>
+            isSubType(tp1, tp2)
+        }
+      case tv1 @ TypeVar(_, _) =>
+        tp2.deconst.normalize match {
+          case TypeRef(_, sym2, _) if isNumericValueClass(sym2) =>
+            tv1.registerBound(tp2, isLowerBound = false, numBound = true)
+          case _ =>
+            isSubType(tp1, tp2)
+        }
+      case _ =>
+        isSubType(tp1, tp2)
+    }
+
+  def isNumericSubType(tp1: Type, tp2: Type) =
+    isNumericValueType(tp1) && isNumericValueType(tp2) &&  
+    isNumericSubClass(tp1.typeSymbol, tp2.typeSymbol)
+
+  private val lubResults = new HashMap[(Int, List[Type]), Type]
+  private val glbResults = new HashMap[(Int, List[Type]), Type]
+
+  def lub(ts: List[Type]): Type = try {
+    lub(ts, lubDepth(ts))
+  } finally {
+    lubResults.clear()
+    glbResults.clear()
+  }
+ 
   /** The least upper bound wrt <:< of a list of types */
   def lub(ts: List[Type], depth: Int): Type = {
     def lub0(ts0: List[Type]): Type = elimSub(ts0, depth) match {
       case List() => NothingClass.tpe
       case List(t) => t
       case ts @ PolyType(tparams, _) :: _ =>
-        PolyType(
-          List.map2(tparams, List.transpose(matchingBounds(ts, tparams)))
-            ((tparam, bounds) => tparam.cloneSymbol.setInfo(glb(bounds, depth))),
-          lub0(matchingInstTypes(ts, tparams)))
-      case ts @ MethodType(pts, _) :: rest =>
-        MethodType(pts, lub0(matchingRestypes(ts, pts)))
+        val tparams1 = (tparams, matchingBounds(ts, tparams).transpose).zipped map
+          ((tparam, bounds) => tparam.cloneSymbol.setInfo(glb(bounds, depth)))
+        PolyType(tparams1, lub0(matchingInstTypes(ts, tparams1)))
+      case ts @ MethodType(params, _) :: rest =>
+        MethodType(params, lub0(matchingRestypes(ts, params map (_.tpe))))
       case ts @ TypeBounds(_, _) :: rest =>
-        mkTypeBounds(glb(ts map (_.bounds.lo), depth), lub(ts map (_.bounds.hi), depth))
-      case ts0 =>
-        val (ts, tparams) = stripExistentialsAndTypeVars(ts0)
-        val bts: List[BaseTypeSeq] = ts map (_.baseTypeSeq)
-        val lubBaseTypes: List[Type] = lubBaseTypeSeq(bts, depth)
-        val lubParents = spanningTypes(lubBaseTypes)
-        val lubOwner = commonOwner(ts)
-        val lubBase = intersectionType(lubParents, lubOwner)
-        val lubType =
-          if (phase.erasedTypes || depth == 0) lubBase
-          else {
-            val lubRefined = refinedType(lubParents, lubOwner)
-            val lubThisType = lubRefined.typeSymbol.thisType
-            val narrowts = ts map (_.narrow)
-            def lubsym(proto: Symbol): Symbol = {
-              val prototp = lubThisType.memberInfo(proto)
-              val syms = narrowts map (t =>
-                t.nonPrivateMember(proto.name).suchThat(sym =>
-                  sym.tpe matches prototp.substThis(lubThisType.typeSymbol, t)))
-              if (syms contains NoSymbol) NoSymbol
+        TypeBounds(glb(ts map (_.bounds.lo), depth), lub(ts map (_.bounds.hi), depth))
+      case ts =>
+        lubResults get (depth, ts) match {
+          case Some(lubType) => 
+            lubType
+          case None => 
+            lubResults((depth, ts)) = AnyClass.tpe
+            val res = if (depth < 0) AnyClass.tpe else lub1(ts)
+            lubResults((depth, ts)) = res
+            res
+        }
+    }
+    def lub1(ts0: List[Type]): Type = {
+      val (ts, tparams) = stripExistentialsAndTypeVars(ts0)
+      val bts: List[BaseTypeSeq] = ts map (_.baseTypeSeq)
+      val lubBaseTypes: List[Type] = lubBaseTypeSeq(bts, depth)
+      val lubParents = spanningTypes(lubBaseTypes)
+      val lubOwner = commonOwner(ts)
+      val lubBase = intersectionType(lubParents, lubOwner)
+      val lubType =
+        if (phase.erasedTypes || depth == 0) lubBase
+        else {
+          val lubRefined = refinedType(lubParents, lubOwner)
+          val lubThisType = lubRefined.typeSymbol.thisType
+          val narrowts = ts map (_.narrow)
+          def lubsym(proto: Symbol): Symbol = {
+            val prototp = lubThisType.memberInfo(proto)
+            val syms = narrowts map (t =>
+              t.nonPrivateMember(proto.name).suchThat(sym =>
+                sym.tpe matches prototp.substThis(lubThisType.typeSymbol, t)))
+            if (syms contains NoSymbol) NoSymbol
+            else {
+              val symtypes =
+                (narrowts, syms).zipped map ((t, sym) => t.memberInfo(sym).substThis(t.typeSymbol, lubThisType))
+              if (proto.isTerm) // possible problem: owner of info is still the old one, instead of new refinement class
+                proto.cloneSymbol(lubRefined.typeSymbol).setInfoOwnerAdjusted(lub(symtypes, decr(depth)))
+              else if (symtypes.tail forall (symtypes.head =:=))
+                proto.cloneSymbol(lubRefined.typeSymbol).setInfoOwnerAdjusted(symtypes.head)
               else {
-                val symtypes =
-                  (List.map2(narrowts, syms)
-                     ((t, sym) => t.memberInfo(sym).substThis(t.typeSymbol, lubThisType)));
-                if (proto.isTerm)
-                  proto.cloneSymbol(lubRefined.typeSymbol).setInfo(lub(symtypes, decr(depth)))
-                else if (symtypes.tail forall (symtypes.head =:=))
-                  proto.cloneSymbol(lubRefined.typeSymbol).setInfo(symtypes.head)
-                else {
-                  def lubBounds(bnds: List[TypeBounds]): TypeBounds =
-                    mkTypeBounds(glb(bnds map (_.lo), decr(depth)), lub(bnds map (_.hi), decr(depth)))
-                  recycle(lubRefined.typeSymbol.newAbstractType(proto.pos, proto.name))
-                    .setInfo(lubBounds(symtypes map (_.bounds)))
-                }
+                def lubBounds(bnds: List[TypeBounds]): TypeBounds =
+                  TypeBounds(glb(bnds map (_.lo), decr(depth)), lub(bnds map (_.hi), decr(depth)))
+                lubRefined.typeSymbol.newAbstractType(proto.pos, proto.name)
+                  .setInfoOwnerAdjusted(lubBounds(symtypes map (_.bounds)))
               }
             }
-            def refines(tp: Type, sym: Symbol): Boolean = {
-              val syms = tp.nonPrivateMember(sym.name).alternatives;
-              !syms.isEmpty && (syms forall (alt =>
-                // todo alt != sym is strictly speaking not correct, but without it we lose 
-                // efficiency.
-                alt != sym && !specializesSym(lubThisType, sym, tp, alt)))
-            }
-            for (sym <- lubBase.nonPrivateMembers) {
-              // add a refinement symbol for all non-class members of lubBase
-              // which are refined by every type in ts.
-              if (!sym.isClass && !sym.isConstructor && (narrowts forall (t => refines(t, sym))))
-                try {
-                  val lsym = lubsym(sym)
-                  if (lsym != NoSymbol) addMember(lubThisType, lubRefined, lubsym(sym))
-                } catch {
-                  case ex: NoCommonType =>
-                }
-            }
-            if (lubRefined.decls.isEmpty) lubBase 
-            else {
+          }
+          def refines(tp: Type, sym: Symbol): Boolean = {
+            val syms = tp.nonPrivateMember(sym.name).alternatives;
+            !syms.isEmpty && (syms forall (alt =>
+              // todo alt != sym is strictly speaking not correct, but without it we lose 
+              // efficiency.
+              alt != sym && !specializesSym(lubThisType, sym, tp, alt)))
+          }
+          for (sym <- lubBase.nonPrivateMembers) {
+            // add a refinement symbol for all non-class members of lubBase
+            // which are refined by every type in ts.
+            if (!sym.isClass && !sym.isConstructor && (narrowts forall (t => refines(t, sym))))
+              try {
+                val lsym = lubsym(sym)
+                if (lsym != NoSymbol) addMember(lubThisType, lubRefined, lubsym(sym))
+              } catch {
+                case ex: NoCommonType =>
+              }
+          }
+          if (lubRefined.decls.isEmpty) lubBase 
+          else {
 //            println("refined lub of "+ts+"/"+narrowts+" is "+lubRefined+", baseclasses = "+(ts map (_.baseTypeSeq) map (_.toList)))
-              lubRefined
-            }
+            lubRefined
           }
-        existentialAbstraction(tparams, lubType)
+        }
+      existentialAbstraction(tparams, lubType)
     }
     if (printLubs) {
       println(indent + "lub of " + ts + " at depth "+depth)//debug
       indent = indent + "  "
       assert(indent.length <= 100)
     }
-    val res = if (depth < 0) AnyClass.tpe else lub0(ts)
+    val res = lub0(ts)
     if (printLubs) {
       indent = indent.substring(0, indent.length() - 2)
       println(indent + "lub of " + ts + " is " + res)//debug
@@ -4115,7 +5086,7 @@ A type's typeSymbol should never be inspected directly.
   val GlbFailure = new Throwable
 
   /** A global counter for glb calls in the `specializes' query connected to the `addMembers'
-   *  call in `glb'. There's a possible inifinite recursion when `specializes' calls
+   *  call in `glb'. There's a possible infinite recursion when `specializes' calls
    *  memberType, which calls baseTypeSeq, which calls mergePrefixAndArgs, which calls glb.
    *  The counter breaks this recursion after two calls.
    *  If the recursion is broken, no member is added to the glb.
@@ -4123,7 +5094,12 @@ A type's typeSymbol should never be inspected directly.
   private var globalGlbDepth = 0
   private final val globalGlbLimit = 2
 
-  def glb(ts: List[Type]): Type = glb(ts, lubDepth(ts))
+  def glb(ts: List[Type]): Type = try {
+    glb(ts, lubDepth(ts))
+  } finally {
+    lubResults.clear()
+    glbResults.clear()
+  }
 
   /** The greatest lower bound wrt <:< of a list of types */
   private def glb(ts: List[Type], depth: Int): Type = {
@@ -4131,100 +5107,106 @@ A type's typeSymbol should never be inspected directly.
       case List() => AnyClass.tpe
       case List(t) => t
       case ts @ PolyType(tparams, _) :: _ =>
-        PolyType(
-          List.map2(tparams, List.transpose(matchingBounds(ts, tparams)))
-          ((tparam, bounds) => tparam.cloneSymbol.setInfo(lub(bounds, depth))),
-          glb0(matchingInstTypes(ts, tparams)))
-      case ts @ MethodType(pts, _) :: rest =>
-        MethodType(pts, glb0(matchingRestypes(ts, pts)))
+        val tparams1 = (tparams, matchingBounds(ts, tparams).transpose).zipped map
+          ((tparam, bounds) => tparam.cloneSymbol.setInfo(lub(bounds, depth)))
+        PolyType(tparams1, glb0(matchingInstTypes(ts, tparams1)))
+      case ts @ MethodType(params, _) :: rest =>
+        MethodType(params, glb0(matchingRestypes(ts, params map (_.tpe))))
       case ts @ TypeBounds(_, _) :: rest =>
-        mkTypeBounds(lub(ts map (_.bounds.lo), depth), glb(ts map (_.bounds.hi), depth))
-      case ts0 =>
-        try {
-          val (ts, tparams) = stripExistentialsAndTypeVars(ts0)
-          val glbOwner = commonOwner(ts)
-          def refinedToParents(t: Type): List[Type] = t match {
-            case RefinedType(ps, _) => ps flatMap refinedToParents
-            case _ => List(t)
-          }
-          def refinedToDecls(t: Type): List[Scope] = t match {
-            case RefinedType(ps, decls) => 
-              val dss = ps flatMap refinedToDecls
-              if (decls.isEmpty) dss else decls :: dss
-            case _ => List()
-          }
-          val ts1 = ts flatMap refinedToParents 
-          val glbBase = intersectionType(ts1, glbOwner)
-          val glbType = 
-            if (phase.erasedTypes || depth == 0) glbBase
-            else {
-              val glbRefined = refinedType(ts1, glbOwner)
-              val glbThisType = glbRefined.typeSymbol.thisType
-              def glbsym(proto: Symbol): Symbol = {
-                val prototp = glbThisType.memberInfo(proto)
-                val syms = for {
-                  val t <- ts
-                  val alt <- t.nonPrivateMember(proto.name).alternatives
-                  glbThisType.memberInfo(alt) matches prototp
-                } yield alt
-                val symtypes = syms map glbThisType.memberInfo
-                assert(!symtypes.isEmpty)
-                proto.cloneSymbol(glbRefined.typeSymbol).setInfo(
-                  if (proto.isTerm) glb(symtypes, decr(depth))
-                  else {
-                    def isTypeBound(tp: Type) = tp match {
-                      case TypeBounds(_, _) => true
-                      case _ => false 
-                    }
-                    def glbBounds(bnds: List[Type]): TypeBounds = {
-                      val lo = lub(bnds map (_.bounds.lo), decr(depth))
-                      val hi = glb(bnds map (_.bounds.hi), decr(depth))
-                      if (lo <:< hi) mkTypeBounds(lo, hi)
-                      else throw GlbFailure
-                    }
-                    val symbounds = symtypes filter isTypeBound
-                    var result: Type =
-                      if (symbounds.isEmpty)
-                        mkTypeBounds(NothingClass.tpe, AnyClass.tpe)
-                      else glbBounds(symbounds)
-                    for (t <- symtypes if !isTypeBound(t))
-                      if (result.bounds containsType t) result = t
-                      else throw GlbFailure
-                    result
-                  })
-              }
-              if (globalGlbDepth < globalGlbLimit)
-                try {
-                  globalGlbDepth += 1
-                  val dss = ts flatMap refinedToDecls
-                  for (ds <- dss; val sym <- ds.elements) 
-                    if (globalGlbDepth < globalGlbLimit && !(glbThisType specializes sym))
-                      try {
-                        addMember(glbThisType, glbRefined, glbsym(sym))
-                      } catch {
-                        case ex: NoCommonType =>
-                      } 
-                } finally {
-                  globalGlbDepth -= 1
-                }
-              if (glbRefined.decls.isEmpty) glbBase else glbRefined
-            }
-          existentialAbstraction(tparams, glbType)
-        } catch {
-          case GlbFailure =>
-            if (ts forall (t => NullClass.tpe <:< t)) NullClass.tpe
-            else NothingClass.tpe
+        TypeBounds(lub(ts map (_.bounds.lo), depth), glb(ts map (_.bounds.hi), depth))
+      case ts =>
+        glbResults get (depth, ts) match {
+          case Some(glbType) =>
+            glbType
+          case _ =>
+            glbResults((depth, ts)) = NothingClass.tpe
+            val res = if (depth < 0) NothingClass.tpe else glb1(ts)
+            glbResults((depth, ts)) = res
+            res
         }
     }
-    if (settings.debug.value) {
-      println(indent + "glb of " + ts + " at depth "+depth)//debug
-      indent = indent + "  "
-    }
-    val res = if (depth < 0) NothingClass.tpe else glb0(ts)
-    if (settings.debug.value) {
-      indent = indent.substring(0, indent.length() - 2)
-      log(indent + "glb of " + ts + " is " + res)//debug
+    def glb1(ts0: List[Type]): Type = {
+      try {
+        val (ts, tparams) = stripExistentialsAndTypeVars(ts0)
+        val glbOwner = commonOwner(ts)
+        def refinedToParents(t: Type): List[Type] = t match {
+          case RefinedType(ps, _) => ps flatMap refinedToParents
+          case _ => List(t)
+        }
+        def refinedToDecls(t: Type): List[Scope] = t match {
+          case RefinedType(ps, decls) => 
+            val dss = ps flatMap refinedToDecls
+            if (decls.isEmpty) dss else decls :: dss
+          case _ => List()
+        }
+        val ts1 = ts flatMap refinedToParents 
+        val glbBase = intersectionType(ts1, glbOwner)
+        val glbType = 
+          if (phase.erasedTypes || depth == 0) glbBase
+          else {
+            val glbRefined = refinedType(ts1, glbOwner)
+            val glbThisType = glbRefined.typeSymbol.thisType
+            def glbsym(proto: Symbol): Symbol = {
+              val prototp = glbThisType.memberInfo(proto)
+              val syms = for (t <- ts;
+                    alt <- (t.nonPrivateMember(proto.name).alternatives);
+                if glbThisType.memberInfo(alt) matches prototp
+              ) yield alt
+              val symtypes = syms map glbThisType.memberInfo
+              assert(!symtypes.isEmpty)
+              proto.cloneSymbol(glbRefined.typeSymbol).setInfoOwnerAdjusted(
+                if (proto.isTerm) glb(symtypes, decr(depth))
+                else {
+                  def isTypeBound(tp: Type) = tp match {
+                    case TypeBounds(_, _) => true
+                    case _ => false 
+                  }
+                  def glbBounds(bnds: List[Type]): TypeBounds = {
+                    val lo = lub(bnds map (_.bounds.lo), decr(depth))
+                    val hi = glb(bnds map (_.bounds.hi), decr(depth))
+                    if (lo <:< hi) TypeBounds(lo, hi)
+                    else throw GlbFailure
+                  }
+                  val symbounds = symtypes filter isTypeBound
+                  var result: Type =
+                    if (symbounds.isEmpty)
+                      TypeBounds(NothingClass.tpe, AnyClass.tpe)
+                    else glbBounds(symbounds)
+                  for (t <- symtypes if !isTypeBound(t))
+                    if (result.bounds containsType t) result = t
+                    else throw GlbFailure
+                  result
+                })
+            }
+            if (globalGlbDepth < globalGlbLimit)
+              try {
+                globalGlbDepth += 1
+                val dss = ts flatMap refinedToDecls
+                for (ds <- dss; val sym <- ds.iterator) 
+                  if (globalGlbDepth < globalGlbLimit && !(glbThisType specializes sym))
+                    try {
+                      addMember(glbThisType, glbRefined, glbsym(sym))
+                    } catch {
+                      case ex: NoCommonType =>
+                    } 
+              } finally {
+                globalGlbDepth -= 1
+              }
+            if (glbRefined.decls.isEmpty) glbBase else glbRefined
+          }
+        existentialAbstraction(tparams, glbType)
+      } catch {
+        case GlbFailure =>
+          if (ts forall (t => NullClass.tpe <:< t)) NullClass.tpe
+          else NothingClass.tpe
+      }
     }
+    // if (settings.debug.value) { println(indent + "glb of " + ts + " at depth "+depth); indent = indent + "  " } //DEBUG
+
+    val res = glb0(ts)
+
+    // if (settings.debug.value) { indent = indent.substring(0, indent.length() - 2); log(indent + "glb of " + ts + " is " + res) }//DEBUG
+
     if (ts exists (_.isNotNull)) res.notNull else res
   }
 
@@ -4242,7 +5224,7 @@ A type's typeSymbol should never be inspected directly.
    *  of types.
    */
   private def commonOwner(tps: List[Type]): Symbol = {
-    if (settings.debug.value) log("computing common owner of types " + tps)//debug
+    // if (settings.debug.value) log("computing common owner of types " + tps)//DEBUG
     commonOwnerMap.init
     tps foreach { tp => commonOwnerMap.apply(tp); () }
     commonOwnerMap.result
@@ -4252,42 +5234,47 @@ A type's typeSymbol should never be inspected directly.
    *  of types `tps'. All types in `tps' are typerefs or singletypes
    *  with the same symbol.
    *  Return `Some(x)' if the computation succeeds with result `x'.
-   *  Return `None' if the computuation fails.
+   *  Return `None' if the computation fails.
    */
   def mergePrefixAndArgs(tps: List[Type], variance: Int, depth: Int): Option[Type] = tps match {
     case List(tp) =>
       Some(tp)
     case TypeRef(_, sym, _) :: rest =>
-      val pres = tps map (_.prefix)
+      val pres = tps map (_.prefix) // prefix normalizes automatically
       val pre = if (variance == 1) lub(pres, depth) else glb(pres, depth)
-      val argss = tps map (_.typeArgs)
+      val argss = tps map (_.normalize.typeArgs) // symbol equality (of the tp in tps) was checked using typeSymbol, which normalizes, so should normalize before retrieving arguments
       val capturedParams = new ListBuffer[Symbol]
-      val args = List.map2(sym.typeParams, List.transpose(argss)) {
-        (tparam, as) =>
-          if (depth == 0)
-            if (tparam.variance == variance) AnyClass.tpe
-            else if (tparam.variance == -variance) NothingClass.tpe
-            else NoType
-          else
-            if (tparam.variance == variance) lub(as, decr(depth))
-            else if (tparam.variance == -variance) glb(as, decr(depth))
-            else {
-              val l = lub(as, decr(depth))
-              val g = glb(as, decr(depth))
-              if (l <:< g) l 
+      try {
+        val args = (sym.typeParams, argss.transpose).zipped map {
+          (tparam, as) =>
+            if (depth == 0)
+              if (tparam.variance == variance) AnyClass.tpe
+              else if (tparam.variance == -variance) NothingClass.tpe
+              else NoType
+            else
+              if (tparam.variance == variance) lub(as, decr(depth))
+              else if (tparam.variance == -variance) glb(as, decr(depth))
               else {
-                val owner = commonOwner(as)
-                val qvar = makeFreshExistential("", commonOwner(as), mkTypeBounds(g, l))
-                capturedParams += qvar
-                qvar.tpe
+                val l = lub(as, decr(depth))
+                val g = glb(as, decr(depth))
+                if (l <:< g) l
+                else { // Martin: I removed this, because incomplete. Not sure there is a good way to fix it. For the moment we
+                       // just err on the conservative side, i.e. with a bound that is too high.
+                       // if(!(tparam.info.bounds contains tparam)){ //@M can't deal with f-bounds, see #2251
+                  val qvar = commonOwner(as) freshExistential "" setInfo TypeBounds(g, l)
+                  capturedParams += qvar
+                  qvar.tpe
+                }
               }
-            }
-      } 
-      try {
+        }
         if (args contains NoType) None
         else Some(existentialAbstraction(capturedParams.toList, typeRef(pre, sym, args)))
       } catch {
         case ex: MalformedType => None
+        case ex: IndexOutOfBoundsException =>  // transpose freaked out because of irregular argss
+        // catching just in case (shouldn't happen, but also doesn't cost us)
+        if (settings.debug.value) log("transposed irregular matrix!?"+ (tps, argss))
+        None
       }
     case SingleType(_, sym) :: rest =>
       val pres = tps map (_.prefix)
@@ -4308,7 +5295,7 @@ A type's typeSymbol should never be inspected directly.
    */
   def addMember(thistp: Type, tp: Type, sym: Symbol) {
     assert(sym != NoSymbol)
-    if (settings.debug.value) log("add member " + sym+":"+sym.info+" to "+thistp)
+    // if (settings.debug.value) log("add member " + sym+":"+sym.info+" to "+thistp) //DEBUG
     if (!(thistp specializes sym)) {
       if (sym.isTerm)
         for (alt <- tp.nonPrivateDecl(sym.name).alternatives)
@@ -4349,23 +5336,130 @@ A type's typeSymbol should never be inspected directly.
    */
   private def matchingRestypes(tps: List[Type], pts: List[Type]): List[Type] =
     tps map {
-      case MethodType(pts1, res) if (isSameTypes(pts1, pts)) =>
+      case MethodType(params1, res) if (isSameTypes(params1 map (_.tpe), pts)) =>
         res
       case _ =>
         throw new NoCommonType(tps)
     }
 
+
+// TODO: this desperately needs to be cleaned up
+// plan: split into kind inference and subkinding
+// every Type has a (cached) Kind
+  def kindsConform(tparams: List[Symbol], targs: List[Type], pre: Type, owner: Symbol): Boolean = checkKindBounds0(tparams, targs, pre, owner, false).isEmpty
+
+  /** Check well-kindedness of type application (assumes arities are already checked) -- @M
+   * 
+   * This check is also performed when abstract type members become concrete (aka a "type alias") -- then tparams.length==1
+   * (checked one type member at a time -- in that case, prefix is the name of the type alias)
+   *
+   * Type application is just like value application: it's "contravariant" in the sense that 
+   * the type parameters of the supplied type arguments must conform to the type parameters of 
+   * the required type parameters:
+   *   - their bounds must be less strict
+   *   - variances must match (here, variances are absolute, the variance of a type parameter does not influence the variance of its higher-order parameters)     
+   *   - @M TODO: are these conditions correct,sufficient&necessary?
+   *
+   *  e.g. class Iterable[t, m[+x <: t]] --> the application Iterable[Int, List] is okay, since 
+   *       List's type parameter is also covariant and its bounds are weaker than <: Int
+   */
+  def checkKindBounds0(tparams: List[Symbol], targs: List[Type], pre: Type, owner: Symbol, explainErrors: Boolean): List[(Type, Symbol, List[(Symbol, Symbol)], List[(Symbol, Symbol)], List[(Symbol, Symbol)])] = {
+    var error = false
+
+    def transform(tp: Type, clazz: Symbol): Type = tp.asSeenFrom(pre, clazz) // instantiate type params that come from outside the abstract type we're currently checking
+    def transformedBounds(p: Symbol, o: Symbol) = transform(p.info.instantiateTypeParams(tparams, targs).bounds, o)
+
+    /** Check whether <arg>sym1</arg>'s variance conforms to <arg>sym2</arg>'s variance
+     *
+     * If <arg>sym2</arg> is invariant, <arg>sym1</arg>'s variance is irrelevant. Otherwise they must be equal.
+     */
+    def variancesMatch(sym1: Symbol, sym2: Symbol): Boolean = (sym2.variance==0 || sym1.variance==sym2.variance)
+
+    // check that the type parameters <arg>hkargs</arg> to a higher-kinded type conform to the expected params <arg>hkparams</arg>
+    def checkKindBoundsHK(hkargs: List[Symbol], arg: Symbol, param: Symbol, paramowner: Symbol, underHKParams: List[Symbol], withHKArgs: List[Symbol]): (List[(Symbol, Symbol)], List[(Symbol, Symbol)], List[(Symbol, Symbol)]) = {
+      def bindHKParams(tp: Type) = tp.substSym(underHKParams, withHKArgs)
+      // @M sometimes hkargs != arg.typeParams, the symbol and the type may have very different type parameters
+      val hkparams = param.typeParams
+
+      if(settings.debug.value) {
+        println("checkKindBoundsHK expected: "+ param +" with params "+ hkparams +" by definition in "+ paramowner)
+        println("checkKindBoundsHK supplied: "+ arg +" with params "+ hkargs +" from "+ owner)
+        println("checkKindBoundsHK under params: "+ underHKParams +" with args "+ withHKArgs)
+      }
+
+      if(hkargs.length != hkparams.length) {
+        if(arg == AnyClass || arg == NothingClass) (Nil, Nil, Nil) // Any and Nothing are kind-overloaded
+        else {error = true; (List((arg, param)), Nil, Nil)} // shortcut: always set error, whether explainTypesOrNot
+      } else {
+        val _arityMismatches = if(explainErrors) new ListBuffer[(Symbol, Symbol)] else null
+        val _varianceMismatches = if(explainErrors) new ListBuffer[(Symbol, Symbol)] else null
+        val _stricterBounds = if(explainErrors)new ListBuffer[(Symbol, Symbol)] else null
+        def varianceMismatch(a: Symbol, p: Symbol) { if(explainErrors) _varianceMismatches += ((a, p)) else error = true}
+        def stricterBound(a: Symbol, p: Symbol) { if(explainErrors) _stricterBounds += ((a, p)) else error = true }
+        def arityMismatches(as: Iterable[(Symbol, Symbol)]) { if(explainErrors) _arityMismatches ++= as }
+        def varianceMismatches(as: Iterable[(Symbol, Symbol)]) { if(explainErrors) _varianceMismatches ++= as }
+        def stricterBounds(as: Iterable[(Symbol, Symbol)]) { if(explainErrors) _stricterBounds ++= as }
+
+        for ((hkarg, hkparam) <- hkargs zip hkparams) { 
+          if (hkparam.typeParams.isEmpty) { // base-case: kind *
+            if (!variancesMatch(hkarg, hkparam))
+              varianceMismatch(hkarg, hkparam)                                         
+
+            // instantiateTypeParams(tparams, targs) --> higher-order bounds may contain references to type arguments
+            // substSym(hkparams, hkargs) --> these types are going to be compared as types of kind * 
+            //    --> their arguments use different symbols, but are conceptually the same 
+            //        (could also replace the types by polytypes, but can't just strip the symbols, as ordering is lost then)
+            if (!(bindHKParams(transformedBounds(hkparam, paramowner)) <:< transform(hkarg.info.bounds, owner)))
+              stricterBound(hkarg, hkparam)
+
+            if(settings.debug.value) {
+              println("checkKindBoundsHK base case: "+ hkparam +" declared bounds: "+ transformedBounds(hkparam, paramowner) +" after instantiating earlier hkparams: "+ bindHKParams(transformedBounds(hkparam, paramowner)))
+              println("checkKindBoundsHK base case: "+ hkarg +" has bounds: "+ transform(hkarg.info.bounds, owner))
+            }
+          } else {
+            if(settings.debug.value) println("checkKindBoundsHK recursing to compare params of "+ hkparam +" with "+ hkarg)
+            val (am, vm, sb) = checkKindBoundsHK(hkarg.typeParams, hkarg, hkparam, paramowner, underHKParams ++ hkparam.typeParams, withHKArgs ++ hkarg.typeParams)
+            arityMismatches(am)
+            varianceMismatches(vm)
+            stricterBounds(sb)
+          }
+          if(!explainErrors && error) return (Nil, Nil, Nil) // stop as soon as we encountered an error
+        }
+        if(!explainErrors) (Nil, Nil, Nil)
+        else (_arityMismatches.toList, _varianceMismatches.toList, _stricterBounds.toList)
+      }    
+    }
+
+    val errors = new ListBuffer[(Type, Symbol, List[(Symbol, Symbol)], List[(Symbol, Symbol)], List[(Symbol, Symbol)])]
+    (tparams zip targs).foreach{ case (tparam, targ) if (targ.isHigherKinded || !tparam.typeParams.isEmpty) => 
+      // @M must use the typeParams of the type targ, not the typeParams of the symbol of targ!!
+      val tparamsHO =  targ.typeParams
+
+      val (arityMismatches, varianceMismatches, stricterBounds) = 
+        checkKindBoundsHK(tparamsHO, targ.typeSymbolDirect, tparam, tparam.owner, tparam.typeParams, tparamsHO) // NOTE: *not* targ.typeSymbol, which normalizes
+    
+      if(!explainErrors) {if(error) return List((NoType, NoSymbol, Nil, Nil, Nil))}
+      else if (arityMismatches.nonEmpty || varianceMismatches.nonEmpty || stricterBounds.nonEmpty) {
+        errors += ((targ, tparam, arityMismatches, varianceMismatches, stricterBounds))
+      }
+     // case (tparam, targ) => println("no check: "+(tparam, targ, tparam.typeParams.isEmpty))                                                             
+     case _ =>
+    }
+  
+    errors.toList
+  }
+
 // Errors and Diagnostics -----------------------------------------------------
 
-  /** An exception signalling a type error */
-  class TypeError(val pos: Position, val msg: String) extends java.lang.Error(msg) {
+  /** A throwable signalling a type error */
+  class TypeError(var pos: Position, val msg: String) extends Throwable(msg) {
     def this(msg: String) = this(NoPosition, msg)
   }
 
-  class NoCommonType(tps: List[Type]) extends java.lang.Error(
-    "lub/glb of incompatible types: " + tps.mkString("", " and ", ""))
+  class NoCommonType(tps: List[Type]) extends Throwable(
+    "lub/glb of incompatible types: " + tps.mkString("", " and ", "")) with ControlThrowable
 
-  /** An exception signalling a malformed type */
+  /** A throwable signalling a malformed type */
   class MalformedType(msg: String) extends TypeError(msg) {
     def this(pre: Type, tp: String) = this("malformed type: " + pre + "#" + tp)
   }
@@ -4409,12 +5503,17 @@ A type's typeSymbol should never be inspected directly.
     try { explainSwitch = true; op } finally { explainSwitch = s }
   }
 
-  def withoutMalformedChecks[T](op: => T): T = {
-    val s = checkMalformedSwitch
-    try { checkMalformedSwitch = false; op } finally { checkMalformedSwitch = s }
-  }
-
   def objToAny(tp: Type): Type =
     if (!phase.erasedTypes && tp.typeSymbol == ObjectClass) AnyClass.tpe
     else tp
+
+  val shorthands = Set(
+    "scala.collection.immutable.List", 
+    "scala.collection.immutable.Nil",
+    "scala.collection.Seq",
+    "scala.collection.Traversable",
+    "scala.collection.Iterable",
+    "scala.collection.mutable.StringBuilder",
+    "scala.collection.IndexedSeq",
+    "scala.collection.Iterator")
 }
diff --git a/src/compiler/scala/tools/nsc/symtab/classfile/AbstractFileReader.scala b/src/compiler/scala/tools/nsc/symtab/classfile/AbstractFileReader.scala
index e923928..b119071 100644
--- a/src/compiler/scala/tools/nsc/symtab/classfile/AbstractFileReader.scala
+++ b/src/compiler/scala/tools/nsc/symtab/classfile/AbstractFileReader.scala
@@ -1,11 +1,12 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: AbstractFileReader.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.tools.nsc.symtab.classfile
+package scala.tools.nsc
+package symtab
+package classfile
 
 import java.lang.Float.intBitsToFloat
 import java.lang.Double.longBitsToDouble
@@ -38,22 +39,21 @@ class AbstractFileReader(val file: AbstractFile) {
   @throws(classOf[IndexOutOfBoundsException])
   def nextByte: Byte = {
     val b = buf(bp)
-    bp = bp + 1
+    bp += 1
     b
   }
 
   /** read some bytes
    */
   def nextBytes(len: Int): Array[Byte] = {
-    bp = bp + len
-    buf.subArray(bp - len, bp)
+    bp += len
+    buf.slice(bp - len, bp)
   }
 
   /** read a character
    */
-  def nextChar: Char = {
+  def nextChar: Char =
     (((nextByte & 0xff) << 8) + (nextByte & 0xff)).toChar
-  }
 
   /** read an integer
    */
diff --git a/src/compiler/scala/tools/nsc/symtab/classfile/ClassfileConstants.scala b/src/compiler/scala/tools/nsc/symtab/classfile/ClassfileConstants.scala
index 6da0247..2cd7a7a 100644
--- a/src/compiler/scala/tools/nsc/symtab/classfile/ClassfileConstants.scala
+++ b/src/compiler/scala/tools/nsc/symtab/classfile/ClassfileConstants.scala
@@ -1,10 +1,11 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: ClassfileConstants.scala 16881 2009-01-09 16:28:11Z cunei $
 
-package scala.tools.nsc.symtab.classfile
+package scala.tools.nsc
+package symtab
+package classfile
 
 object ClassfileConstants {
 
@@ -75,7 +76,7 @@ object ClassfileConstants {
   final val CONSTANT_INTFMETHODREF = 11
   final val CONSTANT_NAMEANDTYPE   = 12
 
-  // tags desribing the type of a literal in attribute values
+  // tags describing the type of a literal in attribute values
   final val BYTE_TAG   = 'B'
   final val CHAR_TAG   = 'C'
   final val DOUBLE_TAG = 'D'
@@ -91,6 +92,9 @@ object ClassfileConstants {
   final val VOID_TAG   = 'V'
   final val TVAR_TAG   = 'T'
   final val ANNOTATION_TAG = '@'
+  final val SCALA_NOTHING = "scala.runtime.Nothing$"
+  final val SCALA_NULL = "scala.runtime.Null$"
+
   
   // tags describing the type of newarray
   final val T_BOOLEAN = 4
diff --git a/src/compiler/scala/tools/nsc/symtab/classfile/ClassfileParser.scala b/src/compiler/scala/tools/nsc/symtab/classfile/ClassfileParser.scala
index 3c442e5..1e68ea2 100644
--- a/src/compiler/scala/tools/nsc/symtab/classfile/ClassfileParser.scala
+++ b/src/compiler/scala/tools/nsc/symtab/classfile/ClassfileParser.scala
@@ -1,19 +1,20 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: ClassfileParser.scala 16881 2009-01-09 16:28:11Z cunei $
 
-package scala.tools.nsc.symtab.classfile
+package scala.tools.nsc
+package symtab
+package classfile
 
-import java.io.IOException
+import java.io.{ File, IOException }
 import java.lang.Integer.toHexString
 
 import scala.collection.immutable.{Map, ListMap}
 import scala.collection.mutable.{ListBuffer, ArrayBuffer}
 import scala.tools.nsc.io.AbstractFile
-import scala.tools.nsc.util.{Position, NoPosition}
- 
+import scala.annotation.switch
+import reflect.generic.PickleBuffer
 
 /** This abstract class implements a class file parser.
  *
@@ -21,8 +22,6 @@ import scala.tools.nsc.util.{Position, NoPosition}
  *  @version 1.0
  */
 abstract class ClassfileParser {
-  def sourcePath : AbstractFile = null
-
   val global: Global
   import global._
 
@@ -36,11 +35,15 @@ abstract class ClassfileParser {
   protected var staticDefs: Scope = _       // the scope of all static definitions
   protected var pool: ConstantPool = _      // the classfile's constant pool
   protected var isScala: Boolean = _        // does class file describe a scala class?
+  protected var isScalaAnnot: Boolean = _   // does class file describe a scala class with its pickled info in an annotation?
   protected var isScalaRaw: Boolean = _     // this class file is a scala class with no pickled info
   protected var hasMeta: Boolean = _        // does class file contain jaco meta attribute?s
-  protected var busy: Boolean = false       // lock to detect recursive reads
+  protected var busy: Option[Symbol] = None // lock to detect recursive reads
   private var   externalName: Name = _      // JVM name of the current class
   protected var classTParams = Map[Name,Symbol]()
+  protected var srcfile0 : Option[AbstractFile] = None
+  
+  def srcfile = srcfile0
 
   private object metaParser extends MetaParser {
     val global: ClassfileParser.this.global.type = ClassfileParser.this.global
@@ -51,16 +54,25 @@ abstract class ClassfileParser {
   }
 
   def parse(file: AbstractFile, root: Symbol) = try {
+    def handleMissing(e: MissingRequirementError) = {
+      if (settings.debug.value) e.printStackTrace
+      throw new IOException("Missing dependency '" + e.req + "', required by " + in.file)
+    }
+      
     def handleError(e: Exception) = {
-      if (e.isInstanceOf[AssertionError] || settings.debug.value)
-        e.printStackTrace()
+      if (settings.debug.value) e.printStackTrace()
       throw new IOException("class file '" + in.file + "' is broken\n(" + {
         if (e.getMessage() != null) e.getMessage()
         else e.getClass.toString
       } + ")")
     }
-    assert(!busy, "internal error: illegal class file dependency")
-    busy = true
+    assert(!busy.isDefined, {
+      val (s1, s2) = (busy.get, root)
+      if (s1 eq s2) "unsatisfiable cyclic dependency in '%s'".format(s1)
+      else "illegal class file dependency between '%s' and '%s'".format(s1, s2)
+    })
+      
+    busy = Some(root)
     /*root match {
       case cs: ClassSymbol =>
         cs.classFile = file
@@ -72,11 +84,11 @@ abstract class ClassfileParser {
 */
     this.in = new AbstractFileReader(file)
     if (root.isModule) {
-      this.clazz = root.linkedClassOfModule
+      this.clazz = root.companionClass
       this.staticModule = root
     } else {
       this.clazz = root
-      this.staticModule = root.linkedModuleOfClass
+      this.staticModule = root.companionModule
     }
     this.isScala = false
     this.hasMeta = false
@@ -84,12 +96,13 @@ abstract class ClassfileParser {
       parseHeader
       this.pool = new ConstantPool
       parseClass()
-    } catch {
-      case e: FatalError => handleError(e)
-      case e: RuntimeException => handleError(e)
+    }
+    catch {
+      case e: MissingRequirementError => handleMissing(e)
+      case e: RuntimeException        => handleError(e)
     }
   } finally {
-    busy = false
+    busy = None
   }
 
   protected def statics: Symbol = staticModule.moduleClass
@@ -100,8 +113,8 @@ abstract class ClassfileParser {
       throw new IOException("class file '" + in.file + "' "
                             + "has wrong magic number 0x" + toHexString(magic)
                             + ", should be 0x" + toHexString(JAVA_MAGIC))
-    val minorVersion = in.nextChar
-    val majorVersion = in.nextChar
+    val minorVersion = in.nextChar.toInt
+    val majorVersion = in.nextChar.toInt
     if ((majorVersion < JAVA_MAJOR_VERSION) ||
         ((majorVersion == JAVA_MAJOR_VERSION) &&
          (minorVersion < JAVA_MINOR_VERSION)))
@@ -122,7 +135,7 @@ abstract class ClassfileParser {
       while (i < starts.length) {
         starts(i) = in.bp
         i += 1
-        in.nextByte match {
+        (in.nextByte.toInt: @switch) match {
           case CONSTANT_UTF8 | CONSTANT_UNICODE =>
             in.skip(in.nextChar)
           case CONSTANT_CLASS | CONSTANT_STRING =>
@@ -145,7 +158,7 @@ abstract class ClassfileParser {
       var name = values(index).asInstanceOf[Name]
       if (name eq null) {
         val start = starts(index)
-        if (in.buf(start) != CONSTANT_UTF8) errorBadTag(start)
+        if (in.buf(start).toInt != CONSTANT_UTF8) errorBadTag(start)
         name = newTermName(in.buf, start + 3, in.getChar(start + 1))
         values(index) = name
       }
@@ -166,7 +179,7 @@ abstract class ClassfileParser {
       var c = values(index).asInstanceOf[Symbol]
       if (c eq null) {
         val start = starts(index)
-        if (in.buf(start) != CONSTANT_CLASS) errorBadTag(start)
+        if (in.buf(start).toInt != CONSTANT_CLASS) errorBadTag(start)
         val name = getExternalName(in.getChar(start + 1))
         if (name.endsWith("$"))
           c = definitions.getModule(name.subName(0, name.length - 1))
@@ -182,7 +195,7 @@ abstract class ClassfileParser {
      */
     def getClassName(index: Int): Name = {
       val start = starts(index)
-      if (in.buf(start) != CONSTANT_CLASS) errorBadTag(start)
+      if (in.buf(start).toInt != CONSTANT_CLASS) errorBadTag(start)
       getExternalName(in.getChar(start + 1))
     }
     
@@ -200,30 +213,46 @@ abstract class ClassfileParser {
       var f = values(index).asInstanceOf[Symbol]
       if (f eq null) {
         val start = starts(index)
-        if (in.buf(start) != CONSTANT_FIELDREF &&
-            in.buf(start) != CONSTANT_METHODREF &&
-            in.buf(start) != CONSTANT_INTFMETHODREF) errorBadTag(start)
+        val first = in.buf(start).toInt
+        if (first != CONSTANT_FIELDREF &&
+            first != CONSTANT_METHODREF &&
+            first != CONSTANT_INTFMETHODREF) errorBadTag(start)
         val ownerTpe = getClassOrArrayType(in.getChar(start + 1))
         if (settings.debug.value)
           log("getMemberSymbol(static: " + static + "): owner type: " + ownerTpe + " " + ownerTpe.typeSymbol.originalName)
-        val (name, tpe) = getNameAndType(in.getChar(start + 3), ownerTpe)
+        val (name0, tpe0) = getNameAndType(in.getChar(start + 3), ownerTpe)
         if (settings.debug.value)
-          log("getMemberSymbol: name and tpe: " + name + ": " + tpe)
+          log("getMemberSymbol: name and tpe: " + name0 + ": " + tpe0)
+
+        forceMangledName(tpe0.typeSymbol.name, false)
+        val (name, tpe) = getNameAndType(in.getChar(start + 3), ownerTpe)
+//        println("new tpe: " + tpe + " at phase: " + phase)
+
         if (name == nme.MODULE_INSTANCE_FIELD) {
           val index = in.getChar(start + 1)
           val name = getExternalName(in.getChar(starts(index) + 1))
           //assert(name.endsWith("$"), "Not a module class: " + name)
-          f = definitions.getModule(name.subName(0, name.length - 1))
+          f = forceMangledName(name.subName(0, name.length - 1), true)
+          if (f == NoSymbol)
+            f = definitions.getModule(name.subName(0, name.length - 1))
         } else {
+          val origName = nme.originalName(name)
           val owner = if (static) ownerTpe.typeSymbol.linkedClassOfClass else ownerTpe.typeSymbol
 //          println("\t" + owner.info.member(name).tpe.widen + " =:= " + tpe)
-          f = owner.info.member(name).suchThat(_.tpe.widen =:= tpe)
+          f = owner.info.member(origName).suchThat(_.tpe.widen =:= tpe)
           if (f == NoSymbol)
-            f = owner.info.member(newTermName(name.toString + nme.LOCAL_SUFFIX)).suchThat(_.tpe =:= tpe)
+            f = owner.info.member(newTermName(origName.toString + nme.LOCAL_SUFFIX)).suchThat(_.tpe =:= tpe)
           if (f == NoSymbol) {
             // if it's an impl class, try to find it's static member inside the class
-            assert(ownerTpe.typeSymbol.isImplClass, "Not an implementation class: " + owner + " couldn't find " + name + ": " + tpe + " inside: \n" + ownerTpe.members);
-            f = ownerTpe.member(name).suchThat(_.tpe =:= tpe)
+            if (ownerTpe.typeSymbol.isImplClass) {
+//              println("impl class, member: " + owner.tpe.member(origName) + ": " + owner.tpe.member(origName).tpe)
+              f = ownerTpe.member(origName).suchThat(_.tpe =:= tpe)
+            } else {
+              log("Couldn't find " + name + ": " + tpe + " inside: \n" + ownerTpe)
+              f = if (tpe.isInstanceOf[MethodType]) owner.newMethod(owner.pos, name).setInfo(tpe)
+                  else owner.newValue(owner.pos, name).setInfo(tpe).setFlag(MUTABLE)
+              log("created fake member " + f.fullName)
+            }
 //            println("\townerTpe.decls: " + ownerTpe.decls)
 //            println("Looking for: " + name + ": " + tpe + " inside: " + ownerTpe.typeSymbol + "\n\tand found: " + ownerTpe.members)
           }
@@ -234,18 +263,27 @@ abstract class ClassfileParser {
       f 
     }
     
-    def getNameAndType(index: Int, ownerTpe: Type): (Name, Type) = {
+    /** Return a name and a type at the given index. If the type is a method
+     *  type, a dummy symbol is created in 'ownerTpe', which is used as the
+     *  owner of its value parameters. This might lead to inconsistencies,
+     *  if a symbol of the given name already exists, and has a different
+     *  type. 
+     */
+    private def getNameAndType(index: Int, ownerTpe: Type): (Name, Type) = {
       if (index <= 0 || len <= index) errorBadIndex(index)
       var p = values(index).asInstanceOf[(Name, Type)]
       if (p eq null) {
         val start = starts(index)
-        if (in.buf(start) != CONSTANT_NAMEANDTYPE) errorBadTag(start)
-        val name = getName(in.getChar(start + 1))
-        var tpe  = getType(in.getChar(start + 3))
+        if (in.buf(start).toInt != CONSTANT_NAMEANDTYPE) errorBadTag(start)
+        val name = getName(in.getChar(start + 1).toInt)
+        // create a dummy symbol for method types
+        val dummySym = ownerTpe.typeSymbol.newMethod(ownerTpe.typeSymbol.pos, name)
+        var tpe  = getType(dummySym, in.getChar(start + 3).toInt)
+
+        // fix the return type, which is blindly set to the class currently parsed
         if (name == nme.CONSTRUCTOR)
           tpe match {
             case MethodType(formals, restpe) =>
-              assert(restpe.typeSymbol == definitions.UnitClass)
               tpe = MethodType(formals, ownerTpe)
           }
 
@@ -264,7 +302,7 @@ abstract class ClassfileParser {
       var c: Type = null
       if (value eq null) {
         val start = starts(index)
-        if (in.buf(start) != CONSTANT_CLASS) errorBadTag(start)
+        if (in.buf(start).toInt != CONSTANT_CLASS) errorBadTag(start)
         val name = getExternalName(in.getChar(start + 1))
         if (name(0) == ARRAY_TAG) {
           c = sigToType(null, name)
@@ -284,8 +322,10 @@ abstract class ClassfileParser {
       c
     }
 
-    def getType(index: Int): Type =
-      sigToType(null, getExternalName(index))
+    def getType(index: Int): Type = getType(null, index)
+    
+    def getType(sym: Symbol, index: Int): Type =
+      sigToType(sym, getExternalName(index))
 
     def getSuperClass(index: Int): Symbol =
       if (index == 0) definitions.AnyClass else getClassSymbol(index)
@@ -295,9 +335,9 @@ abstract class ClassfileParser {
       var value = values(index)
       if (value eq null) {
         val start = starts(index)
-        value = in.buf(start) match {
+        value = (in.buf(start).toInt: @switch) match {
           case CONSTANT_STRING =>
-            Constant(getName(in.getChar(start + 1)).toString())
+            Constant(getName(in.getChar(start + 1).toInt).toString())
           case CONSTANT_INTEGER =>
             Constant(in.getInt(start + 1))
           case CONSTANT_FLOAT =>
@@ -320,6 +360,42 @@ abstract class ClassfileParser {
       }
     }
 
+    def getBytes(index: Int): Array[Byte] = {
+      if (index <= 0 || len <= index) errorBadIndex(index)
+      var value = values(index).asInstanceOf[Array[Byte]]
+      if (value eq null) {
+        val start = starts(index)
+        if (in.buf(start).toInt != CONSTANT_UTF8) errorBadTag(start)
+        val len = in.getChar(start + 1)
+        val bytes = new Array[Byte](len)
+        Array.copy(in.buf, start + 3, bytes, 0, len)
+        val decodedLength = reflect.generic.ByteCodecs.decode(bytes)
+        value = bytes.take(decodedLength)
+        values(index) = value
+      }
+      value
+    }
+
+    def getBytes(indices: List[Int]): Array[Byte] = {
+      assert(!indices.isEmpty)
+      var value = values(indices.head).asInstanceOf[Array[Byte]]
+      if (value eq null) {
+        val bytesBuffer = ArrayBuffer.empty[Byte]
+        for (index <- indices) {
+          if (index <= 0 || ConstantPool.this.len <= index) errorBadIndex(index)
+          val start = starts(index)
+          if (in.buf(start).toInt != CONSTANT_UTF8) errorBadTag(start)
+          val len = in.getChar(start + 1)
+          bytesBuffer ++= in.buf.view(start + 3, start + 3 + len)
+        }
+        val bytes = bytesBuffer.toArray
+        val decodedLength = reflect.generic.ByteCodecs.decode(bytes)
+        value = bytes.take(decodedLength)
+        values(indices.head) = value
+      }
+      value
+    }
+
     /** Throws an exception signaling a bad constant index. */
     private def errorBadIndex(index: Int) =
       throw new RuntimeException("bad constant pool index: " + index + " at pos: " + in.bp)
@@ -329,14 +405,72 @@ abstract class ClassfileParser {
       throw new RuntimeException("bad constant pool tag " + in.buf(start) + " at byte " + start)
   }
 
+  /** Try to force the chain of enclosing classes for the given name. Otherwise
+   *  flatten would not lift classes that were not referenced in the source code.
+   */
+  def forceMangledName(name: Name, module: Boolean): Symbol = {
+    val parts = name.decode.toString.split(Array('.', '$'))
+    var sym: Symbol = definitions.RootClass
+    atPhase(currentRun.flattenPhase.prev) {
+      for (part0 <- parts; if !(part0 == ""); val part = newTermName(part0)) {
+        val sym1 = atPhase(currentRun.icodePhase) {
+          sym.linkedClassOfClass.info
+          sym.info.decl(part.encode)
+        }//.suchThat(module == _.isModule)
+        if (sym1 == NoSymbol)
+          sym = sym.info.decl(part.encode.toTypeName)
+        else
+          sym = sym1
+      }
+    }
+//    println("found: " + sym)
+    sym
+  }
 
   /** Return the class symbol of the given name. */
   def classNameToSymbol(name: Name): Symbol = {
-    def lookupClass(name: Name) = 
+    def loadClassSymbol(name: Name) = {
+      val s = name.toString
+      val file = global.classPath findSourceFile s getOrElse {
+        throw new MissingRequirementError("class " + s)
+      }
+      val completer = new global.loaders.ClassfileLoader(file)
+      var owner: Symbol = definitions.RootClass
+      var sym: Symbol = NoSymbol
+      var ss: String = null
+      var start = 0
+      var end = s indexOf '.'
+      while (end > 0) {
+        ss = s.substring(start, end)
+        sym = owner.info.decls lookup ss
+        if (sym == NoSymbol) {
+          sym = owner.newPackage(NoPosition, ss) setInfo completer
+          sym.moduleClass setInfo completer
+          owner.info.decls enter sym
+        }
+        owner = sym.moduleClass
+        start = end + 1
+        end = s.indexOf('.', start)
+      }
+      ss = s substring start
+      sym = owner.info.decls lookup ss
+      if (sym == NoSymbol) {
+        sym = owner.newClass(NoPosition, ss) setInfo completer
+        owner.info.decls enter sym
+        if (settings.debug.value && settings.verbose.value)
+          println("loaded "+sym+" from file "+file)
+      }
+      sym
+    }
+
+    def lookupClass(name: Name) = try {
       if (name.pos('.') == name.length)
         definitions.getMember(definitions.EmptyPackageClass, name.toTypeName)
       else
-        definitions.getClass(name)
+        definitions.getClass(name) // see tickets #2464, #3756
+    } catch { 
+      case _: FatalError => loadClassSymbol(name) 
+    }
     
     innerClasses.get(name) match {
       case Some(entry) =>
@@ -354,35 +488,51 @@ abstract class ClassfileParser {
   
   def parseClass() {
     val jflags = in.nextChar
-    val isAnnotation = (jflags & JAVA_ACC_ANNOTATION) != 0
+    val isAnnotation = hasAnnotation(jflags)
     var sflags = transFlags(jflags, true)
     var nameIdx = in.nextChar
     externalName = pool.getClassName(nameIdx)
     val c = if (externalName.toString.indexOf('$') < 0) pool.getClassSymbol(nameIdx) else clazz
+
+    /** Parse parents for Java classes. For Scala, return AnyRef, since the real type will be unpickled.
+     *  Updates the read pointer of 'in'. */
+    def parseParents: List[Type] = {
+      if (isScala) {
+        in.nextChar              // skip superclass
+        val ifaces = in.nextChar
+        in.bp += ifaces * 2     // .. and iface count interfaces
+        List(definitions.AnyRefClass.tpe) // dummy superclass, will be replaced by pickled information
+      } else {
+        try {
+          loaders.parentsLevel += 1
+          val superType = if (isAnnotation) { in.nextChar; definitions.AnnotationClass.tpe }
+                          else pool.getSuperClass(in.nextChar).tpe
+          val ifaceCount = in.nextChar
+          var ifaces = for (i <- List.range(0, ifaceCount)) yield pool.getSuperClass(in.nextChar).tpe
+          if (isAnnotation) ifaces = definitions.ClassfileAnnotationClass.tpe :: ifaces
+          superType :: ifaces
+        } finally {
+          loaders.parentsLevel -= 1
+        }
+      }
+    }
+
     if (c != clazz && externalName.toString.indexOf("$") < 0) {
-      if ((clazz eq NoSymbol) && (c ne NoSymbol)) { // XXX: needed for build compiler, so can't protect with inIDE
-        clazz = c
-      } else if (inIDE) {
-        Console.println("WRONG CLASS: expected: " + clazz + " found " + c)
-      } else throw new IOException("class file '" + in.file + "' contains wrong " + c)
+      if ((clazz eq NoSymbol) && (c ne NoSymbol)) clazz = c
+      else throw new IOException("class file '" + in.file + "' contains wrong " + c)
     }
-    
+
     addEnclosingTParams(clazz)
-    parseInnerClasses()
-    val superType = if (isAnnotation) { in.nextChar; definitions.AnnotationClass.tpe }
-                    else pool.getSuperClass(in.nextChar).tpe
-    val ifaceCount = in.nextChar
-    var ifaces = for (i <- List.range(0, ifaceCount)) yield pool.getSuperClass(in.nextChar).tpe
-    if (isAnnotation) ifaces = definitions.ClassfileAnnotationClass.tpe :: ifaces
-    val parents = superType :: ifaces
-    // get the class file parser to reuse scopes. 
-    instanceDefs = newClassScope(clazz)
-    staticDefs = newClassScope(statics)
-    val classInfo = ClassInfoType(parents, instanceDefs, clazz)
+    parseInnerClasses() // also sets the isScala / isScalaRaw / hasMeta flags, see r15956
+    // get the class file parser to reuse scopes.
+    instanceDefs = new Scope
+    staticDefs = new Scope
+    
+    val classInfo = ClassInfoType(parseParents, instanceDefs, clazz)
     val staticInfo = ClassInfoType(List(), staticDefs, statics)
 
     if (!isScala && !isScalaRaw) {
-      //println("Entering inner classes for " + clazz)
+//      println("Entering inner classes for " + clazz)
       enterOwnInnerClasses
     }
     val curbp = in.bp
@@ -402,34 +552,32 @@ abstract class ClassfileParser {
       // attributes now depend on having infos set already
       parseAttributes(clazz, classInfo) 
 
-      in.bp = curbp
-      val fieldCount = in.nextChar
-      for (i <- 0 until fieldCount) parseField()
-      sawPrivateConstructor = false
-      val methodCount = in.nextChar
-      for (i <- 0 until methodCount) parseMethod()
-      if (!sawPrivateConstructor &&
-          (instanceDefs.lookup(nme.CONSTRUCTOR) == NoSymbol &&
-           (sflags & INTERFACE) == 0))
-        {
-          //Console.println("adding constructor to " + clazz);//DEBUG
-          instanceDefs.enter(
-            clazz.newConstructor(NoPosition)
-            .setFlag(clazz.flags & ConstrFlags)
-            .setInfo(MethodType(List(), clazz.tpe)))
-
-          // If the annotation has an attribute with name 'value'
-          // add a constructor for it
-          if (isAnnotation) {
-            val value = instanceDefs.lookup(nme.value)
-            if (value != NoSymbol) {
-              instanceDefs.enter(
-                clazz.newConstructor(NoPosition)
-                .setFlag(clazz.flags & ConstrFlags)
-                .setInfo(MethodType(List(value.tpe.resultType), clazz.tpe)))
-            }
+      loaders.pendingLoadActions = { () =>
+        in.bp = curbp
+        val fieldCount = in.nextChar
+        for (i <- 0 until fieldCount) parseField()
+        sawPrivateConstructor = false
+        val methodCount = in.nextChar
+        for (i <- 0 until methodCount) parseMethod()
+        if (!sawPrivateConstructor &&
+            (instanceDefs.lookup(nme.CONSTRUCTOR) == NoSymbol &&
+             (sflags & INTERFACE) == 0L))
+          {
+            //Console.println("adding constructor to " + clazz);//DEBUG
+            instanceDefs.enter(
+              clazz.newConstructor(NoPosition)
+              .setFlag(clazz.flags & ConstrFlags)
+              .setInfo(MethodType(List(), clazz.tpe)))
           }
+        ()
+      } :: loaders.pendingLoadActions
+      if (loaders.parentsLevel == 0) {
+        while (!loaders.pendingLoadActions.isEmpty) {
+          val item = loaders.pendingLoadActions.head
+          loaders.pendingLoadActions = loaders.pendingLoadActions.tail
+          item()
         }
+      }
     } else
       parseAttributes(clazz, classInfo)
   }
@@ -450,15 +598,15 @@ abstract class ClassfileParser {
   def parseField() {
     val jflags = in.nextChar
     var sflags = transFlags(jflags, false)
-    if ((sflags & FINAL) == 0) sflags = sflags | MUTABLE
-    if ((sflags & PRIVATE) != 0 && !global.settings.XO.value) {
+    if ((sflags & FINAL) == 0L) sflags = sflags | MUTABLE
+    if ((sflags & PRIVATE) != 0L && !global.settings.XO.value) {
       in.skip(4); skipAttributes()
     } else {
       val name = pool.getName(in.nextChar)
       val info = pool.getType(in.nextChar)
       val sym = getOwner(jflags)
         .newValue(NoPosition, name).setFlag(sflags)
-      sym.setInfo(if ((jflags & JAVA_ACC_ENUM) == 0) info else mkConstantType(Constant(sym)))
+      sym.setInfo(if ((jflags & JAVA_ACC_ENUM) == 0) info else ConstantType(Constant(sym)))
       setPrivateWithin(sym, jflags)
       parseAttributes(sym, info)
       getScope(jflags).enter(sym)
@@ -466,9 +614,9 @@ abstract class ClassfileParser {
   }
 
   def parseMethod() {
-    val jflags = in.nextChar
+    val jflags = in.nextChar.toInt
     var sflags = transFlags(jflags, false)
-    if ((jflags & JAVA_ACC_PRIVATE) != 0 && !global.settings.XO.value) {
+    if (isPrivate(jflags) && !global.settings.XO.value) {
       val name = pool.getName(in.nextChar)
       if (name == nme.CONSTRUCTOR)
         sawPrivateConstructor = true
@@ -476,27 +624,26 @@ abstract class ClassfileParser {
     } else {
       if ((jflags & JAVA_ACC_BRIDGE) != 0) 
         sflags |= BRIDGE
-      if ((sflags & PRIVATE) != 0 && global.settings.XO.value) {
+      if ((sflags & PRIVATE) != 0L && global.settings.XO.value) {
         in.skip(4); skipAttributes()
       } else {
         val name = pool.getName(in.nextChar)
-        var info = pool.getType(in.nextChar)
+        val sym = getOwner(jflags).newMethod(NoPosition, name).setFlag(sflags)
+        var info = pool.getType(sym, (in.nextChar))
         if (name == nme.CONSTRUCTOR)
           info match {
-            case MethodType(formals, restpe) =>
-              assert(restpe.typeSymbol == definitions.UnitClass)
+            case MethodType(params, restpe) =>
               // if this is a non-static inner class, remove the explicit outer parameter
-              val newFormals = innerClasses.get(externalName) match {
-                case Some(entry) if !isScalaRaw && (entry.jflags & JAVA_ACC_STATIC) == 0 =>
-                  assert(formals.head.typeSymbol == clazz.owner, formals.head.typeSymbol + ": " + clazz.owner)
-                  formals.tail
+              val newParams = innerClasses.get(externalName) match {
+                case Some(entry) if !isScalaRaw && !isStatic(entry.jflags) =>
+                  assert(params.head.tpe.typeSymbol == clazz.owner, params.head.tpe.typeSymbol + ": " + clazz.owner)
+                  params.tail
                 case _ =>
-                  formals
+                  params
               }
-              info = MethodType(newFormals, clazz.tpe)
+              info = MethodType(newParams, clazz.tpe)
           }
-        val sym = getOwner(jflags)
-          .newMethod(NoPosition, name).setFlag(sflags).setInfo(info)
+        sym.setInfo(info)
         setPrivateWithin(sym, jflags)
         parseAttributes(sym, info)
         if ((jflags & JAVA_ACC_VARARGS) != 0) {
@@ -507,15 +654,23 @@ abstract class ClassfileParser {
     }
   }
 
-  /** Convert repeated parameters to arrays if they occur as part of a Java method 
+  /** Convert array parameters denoting a repeated parameter of a Java method
+   *  to JavaRepeatedParamClass types.
    */
   private def arrayToRepeated(tp: Type): Type = tp match {
-    case MethodType(formals, rtpe) =>
+    case MethodType(params, rtpe) =>
+      val formals = tp.paramTypes
       assert(formals.last.typeSymbol == definitions.ArrayClass)
-      MethodType(
-        formals.init ::: 
-        List(appliedType(definitions.RepeatedParamClass.typeConstructor, List(formals.last.typeArgs.head))),
-        rtpe)
+      val method = params.last.owner
+      val elemtp = formals.last.typeArgs.head match {
+        case RefinedType(List(t1, t2), _) if (t1.typeSymbol.isAbstractType && t2.typeSymbol == definitions.ObjectClass) => 
+          t1 // drop intersection with Object for abstract types in varargs. UnCurry can handle them.
+        case t => 
+          t
+      }
+      val newParams = method.newSyntheticValueParams(
+        formals.init ::: List(appliedType(definitions.JavaRepeatedParamClass.typeConstructor, List(elemtp))))
+      MethodType(newParams, rtpe)
     case PolyType(tparams, rtpe) =>
       PolyType(tparams, arrayToRepeated(rtpe))
   }
@@ -532,6 +687,8 @@ abstract class ClassfileParser {
       while (!isDelimiter(sig(index))) { index += 1 }
       sig.subName(start, index)
     }
+    def existentialType(tparams: List[Symbol], tp: Type): Type = 
+      if (tparams.isEmpty) tp else ExistentialType(tparams, tp)
     def sig2type(tparams: Map[Name,Symbol], skiptvs: Boolean): Type = {
       val tag = sig(index); index += 1
       tag match {
@@ -563,16 +720,16 @@ abstract class ClassfileParser {
                     case variance @ ('+' | '-' | '*') =>
                       index += 1
                       val bounds = variance match {
-                        case '+' => mkTypeBounds(definitions.NothingClass.tpe,
-                                                 sig2type(tparams, skiptvs))
-                        case '-' => mkTypeBounds(sig2type(tparams, skiptvs),
-                                                 definitions.AnyClass.tpe)
-                        case '*' => mkTypeBounds(definitions.NothingClass.tpe,
-                                                 definitions.AnyClass.tpe)
+                        case '+' => TypeBounds(definitions.NothingClass.tpe,
+                                               sig2type(tparams, skiptvs))
+                        case '-' => TypeBounds(sig2type(tparams, skiptvs),
+                                               definitions.AnyClass.tpe)
+                        case '*' => TypeBounds(definitions.NothingClass.tpe,
+                                               definitions.AnyClass.tpe)
                       }
-                      val newtparam = makeExistential("?"+i, sym, bounds)
+                      val newtparam = sym.newExistential(sym.pos, "?"+i) setInfo bounds
                       existentials += newtparam
-                      xs += newtparam.tpe
+                      xs += newtparam.tpe //@M should probably be .tpeHK
                       i += 1
                     case _ => 
                       xs += sig2type(tparams, skiptvs)
@@ -580,15 +737,16 @@ abstract class ClassfileParser {
                 } 
                 accept('>')
                 assert(xs.length > 0)
-                existentialAbstraction(existentials.toList, TypeRef(pre, classSym, xs.toList))
+                existentialType(existentials.toList, TypeRef(pre, classSym, xs.toList))
               } else if (classSym.isMonomorphicType) {
                 tp
               } else {
                 // raw type - existentially quantify all type parameters
                 val eparams = typeParamsToExistentials(classSym, classSym.unsafeTypeParams)            
                 val t = TypeRef(pre, classSym, eparams.map(_.tpe))
-                val res = existentialAbstraction(eparams, t)
-                if (settings.debug.value && settings.verbose.value) println("raw type " + classSym + " -> " + res)
+                val res = existentialType(eparams, t)
+                if (settings.debug.value && settings.verbose.value)
+                  println("raw type " + classSym + " -> " + res)
                 res
               }
             case tp => 
@@ -609,19 +767,27 @@ abstract class ClassfileParser {
           tpe
         case ARRAY_TAG =>
           while ('0' <= sig(index) && sig(index) <= '9') index += 1
-          appliedType(definitions.ArrayClass.tpe, List(sig2type(tparams, skiptvs)))
+          var elemtp = sig2type(tparams, skiptvs)
+          // make unbounded Array[T] where T is a type variable into Array[T with Object]
+          // (this is necessary because such arrays have a representation which is incompatible
+          // with arrays of primitive types.
+          if (elemtp.typeSymbol.isAbstractType && !(elemtp <:< definitions.ObjectClass.tpe))
+            elemtp = intersectionType(List(elemtp, definitions.ObjectClass.tpe))
+          appliedType(definitions.ArrayClass.tpe, List(elemtp))
         case '(' =>
+          // we need a method symbol. given in line 486 by calling getType(methodSym, ..)
+          assert(sym ne null)
           val paramtypes = new ListBuffer[Type]()
           while (sig(index) != ')') {
             paramtypes += objToAny(sig2type(tparams, skiptvs))
           }
           index += 1
-          val restype = if (sym != null && sym.isConstructor) {
+          val restype = if (sym != null && sym.isClassConstructor) {
             accept('V')
             clazz.tpe
           } else
             sig2type(tparams, skiptvs)
-          JavaMethodType(paramtypes.toList, restype)
+          JavaMethodType(sym.newSyntheticValueParams(paramtypes.toList), restype)
         case 'T' =>
           val n = subName(';'.==).toTypeName
           index += 1
@@ -637,7 +803,7 @@ abstract class ClassfileParser {
         if (sig(index) != ':') // guard against empty class bound
           ts += objToAny(sig2type(tparams, skiptvs))
       }
-      mkTypeBounds(definitions.NothingClass.tpe, intersectionType(ts.toList, sym))
+      TypeBounds(definitions.NothingClass.tpe, intersectionType(ts.toList, sym))
     } 
 
     var tparams = classTParams
@@ -694,7 +860,7 @@ abstract class ClassfileParser {
       val attrLen = in.nextInt
       attrName match {
         case nme.SignatureATTR =>
-          if (!isScala && !isScalaRaw && global.settings.target.value == "jvm-1.5") {
+          if (!isScala && !isScalaRaw) {
             val sig = pool.getExternalName(in.nextChar)
             val newType = sigToType(sym, sig)
             sym.setInfo(newType)
@@ -710,123 +876,197 @@ abstract class ClassfileParser {
           sym.setFlag(BRIDGE)
           in.skip(attrLen)
         case nme.DeprecatedATTR =>
-          sym.setFlag(DEPRECATED)
+          val arg = Literal(Constant("see corresponding Javadoc for more information."))
+          sym.addAnnotation(AnnotationInfo(definitions.DeprecatedAttr.tpe, List(arg), List()))
           in.skip(attrLen)
         case nme.ConstantValueATTR =>
           val c = pool.getConstant(in.nextChar)
           val c1 = convertTo(c, symtype)
-          if (c1 ne null) sym.setInfo(mkConstantType(c1))
+          if (c1 ne null) sym.setInfo(ConstantType(c1))
           else println("failure to convert " + c + " to " + symtype); //debug
         case nme.ScalaSignatureATTR =>
-          unpickler.unpickle(in.buf, in.bp, clazz, staticModule, in.file.toString())
+          if (!isScalaAnnot) {
+            if (settings.debug.value)
+              global.inform("warning: symbol " + sym.fullName + " has pickled signature in attribute")
+            unpickler.unpickle(in.buf, in.bp, clazz, staticModule, in.file.toString())
+          }
           in.skip(attrLen)
-          this.isScala = true
         case nme.ScalaATTR =>
           isScalaRaw = true
         case nme.JacoMetaATTR =>
           val meta = pool.getName(in.nextChar).toString().trim()
           metaParser.parse(meta, sym, symtype)
           this.hasMeta = true
-        case nme.SourceFileATTR =>
-          assert(attrLen == 2)
-          val source = pool.getName(in.nextChar)
-          if (sourcePath ne null) {
-            val sourceFile0 = sourcePath.lookupPath(source.toString(), false)
-            if ((sourceFile0 ne null) && (clazz.sourceFile eq null)) {
-              clazz.sourceFile = sourceFile0
-            }
-            // XXX: removing only in IDE test. Also needs to be tested in the build compiler.
-            if (staticModule.moduleClass != NoSymbol) {
-              staticModule.moduleClass.sourceFile = clazz.sourceFile
-            }
-          }
+         // Attribute on methods of java annotation classes when that method has a default
         case nme.AnnotationDefaultATTR =>
-          sym.attributes =
-            AnnotationInfo(definitions.AnnotationDefaultAttr.tpe, List(), List()) :: sym.attributes
+          sym.addAnnotation(AnnotationInfo(definitions.AnnotationDefaultAttr.tpe, List(), List()))
           in.skip(attrLen)
+        // Java annotations on classes / methods / fields with RetentionPolicy.RUNTIME
         case nme.RuntimeAnnotationATTR =>
-          parseAnnotations(attrLen)
-          if (settings.debug.value)
-            global.inform("" + sym + "; attributes = " + sym.attributes)
+          if (isScalaAnnot || !isScala) {
+            val scalaSigAnnot = parseAnnotations(attrLen)
+            if (isScalaAnnot)
+              scalaSigAnnot match {
+                case Some(san: AnnotationInfo) =>
+                  val bytes =
+                    san.assocs.find({ _._1 == nme.bytes }).get._2.asInstanceOf[ScalaSigBytes].bytes
+                  unpickler.unpickle(bytes, 0, clazz, staticModule, in.file.toString())
+                case None =>
+                  throw new RuntimeException("Scala class file does not contain Scala annotation")
+              }
+            if (settings.debug.value)
+              global.inform("" + sym + "; annotations = " + sym.rawAnnotations)
+          } else
+            in.skip(attrLen)
+
+        // TODO 1: parse runtime visible annotations on parameters
+        // case nme.RuntimeParamAnnotationATTR
+
+        // TODO 2: also parse RuntimeInvisibleAnnotation / RuntimeInvisibleParamAnnotation,
+        // i.e. java annotations with RetentionPolicy.CLASS?
+
+        case nme.ExceptionsATTR if (!isScala) =>
+          parseExceptions(attrLen)
+          
+        case nme.SourceFileATTR =>
+          val srcfileLeaf = pool.getName(in.nextChar).toString.trim
+          val srcpath = sym.enclosingPackage match {
+            case NoSymbol => srcfileLeaf
+            case definitions.EmptyPackage => srcfileLeaf
+            case pkg => pkg.fullName(File.separatorChar)+File.separator+srcfileLeaf
+          }
+          srcfile0 = settings.outputDirs.srcFilesFor(in.file, srcpath).find(_.exists)
         case _ =>
           in.skip(attrLen)
       }
     }
-    def parseTaggedConstant: Constant = {
-      val tag = in.nextByte
+
+    def parseAnnotArg: Option[ClassfileAnnotArg] = {
+      val tag = in.nextByte.toChar
       val index = in.nextChar
       tag match {
-        case STRING_TAG => Constant(pool.getName(index).toString())
-        case BOOL_TAG   => pool.getConstant(index)
-        case BYTE_TAG   => pool.getConstant(index)
-        case CHAR_TAG   => pool.getConstant(index)
-        case SHORT_TAG  => pool.getConstant(index)
-        case INT_TAG    => pool.getConstant(index)
-        case LONG_TAG   => pool.getConstant(index)
-        case FLOAT_TAG  => pool.getConstant(index)
-        case DOUBLE_TAG => pool.getConstant(index)
-        case CLASS_TAG  => Constant(pool.getType(index))
+        case STRING_TAG =>
+          Some(LiteralAnnotArg(Constant(pool.getName(index).toString())))
+        case BOOL_TAG | BYTE_TAG | CHAR_TAG | SHORT_TAG | INT_TAG |
+             LONG_TAG | FLOAT_TAG | DOUBLE_TAG =>
+          Some(LiteralAnnotArg(pool.getConstant(index)))
+        case CLASS_TAG  =>
+          Some(LiteralAnnotArg(Constant(pool.getType(index))))
         case ENUM_TAG   =>
           val t = pool.getType(index)
           val n = pool.getName(in.nextChar)
-          val s = t.typeSymbol.linkedModuleOfClass.info.decls.lookup(n)
+          val s = t.typeSymbol.companionModule.info.decls.lookup(n)
           assert(s != NoSymbol, t)
-          Constant(s)
+          Some(LiteralAnnotArg(Constant(s)))
         case ARRAY_TAG  =>
-          val arr = new ArrayBuffer[Constant]()
-          for (i <- 0 until index) {
-            arr += parseTaggedConstant
-          }
-          new ArrayConstant(arr.toArray,
-              appliedType(definitions.ArrayClass.typeConstructor, List(arr(0).tpe)))
-	case ANNOTATION_TAG =>
-	  parseAnnotation(index)  // skip it
-	  new AnnotationConstant()
+          val arr = new ArrayBuffer[ClassfileAnnotArg]()
+          var hasError = false
+          for (i <- 0 until index)
+            parseAnnotArg match {
+              case Some(c) => arr += c
+              case None => hasError = true
+            }
+          if (hasError) None
+          else Some(ArrayAnnotArg(arr.toArray))
+        case ANNOTATION_TAG =>
+          parseAnnotation(index) map (NestedAnnotArg(_))
       }
     }
 
-    /** Parse and return a single annotation.  If it is malformed,
-     *  or it contains a nested annotation, return None.
-     */
-    def parseAnnotation(attrNameIndex: Char): Option[AnnotationInfo] = 
-      try {
-        val attrType = pool.getType(attrNameIndex)
-        val nargs = in.nextChar
-        val nvpairs = new ListBuffer[(Name,AnnotationArgument)]
-        var nestedAnnot = false  // if a nested annotation is seen,
-                                 // then skip this annotation
-        for (i <- 0 until nargs) {
-          val name = pool.getName(in.nextChar)
-          val argConst = parseTaggedConstant
-          if (argConst.tag == AnnotationTag)
-            nestedAnnot = true
-          else
-            nvpairs += ((name, new AnnotationArgument(argConst)))
+    def parseScalaSigBytes: Option[ScalaSigBytes] = {
+      val tag = in.nextByte.toChar
+      assert(tag == STRING_TAG)
+      Some(ScalaSigBytes(pool.getBytes(in.nextChar)))
+    }
+
+    def parseScalaLongSigBytes: Option[ScalaSigBytes] = try {
+      val tag = in.nextByte.toChar
+      assert(tag == ARRAY_TAG)
+      val stringCount = in.nextChar
+      val entries =
+        for (i <- 0 until stringCount) yield {
+          val stag = in.nextByte.toChar
+          assert(stag == STRING_TAG)
+          in.nextChar.toInt
         }
+      Some(ScalaSigBytes(pool.getBytes(entries.toList)))
+    }
+    catch {
+      case e: Throwable =>
+        e.printStackTrace
+        throw e
+    }
 
-        if (nestedAnnot)
-          None
+    /** Parse and return a single annotation.  If it is malformed,
+     *  return None.
+     */
+    def parseAnnotation(attrNameIndex: Char): Option[AnnotationInfo] = try {
+      val attrType = pool.getType(attrNameIndex)
+      val nargs = in.nextChar
+      val nvpairs = new ListBuffer[(Name, ClassfileAnnotArg)]
+      var hasError = false
+      for (i <- 0 until nargs) {
+        val name = pool.getName(in.nextChar)
+        // The "bytes: String" argument of the ScalaSignature attribute is parsed specially so that it is
+        // available as an array of bytes (the pickled Scala signature) instead of as a string. The pickled signature
+        // is encoded as a string because of limitations in the Java class file format.
+        if ((attrType == definitions.ScalaSignatureAnnotation.tpe) && (name == nme.bytes))
+          parseScalaSigBytes match {
+            case Some(c) => nvpairs += ((name, c))
+            case None => hasError = true
+          }
+        else if ((attrType == definitions.ScalaLongSignatureAnnotation.tpe) && (name == nme.bytes))
+          parseScalaLongSigBytes match {
+            case Some(c) => nvpairs += ((name, c))
+            case None => hasError = true
+          }
         else
-          Some(AnnotationInfo(attrType, List(), nvpairs.toList))
-      } catch {
-        case f: FatalError => throw f // don't eat fatal errors, they mean a class was not found
-        case ex: Throwable => None // ignore malformed annotations ==> t1135
+          parseAnnotArg match {
+            case Some(c) => nvpairs += ((name, c))
+            case None => hasError = true
+          }
       }
+      if (hasError) None
+      else Some(AnnotationInfo(attrType, List(), nvpairs.toList))
+    } catch {
+      case f: FatalError => throw f // don't eat fatal errors, they mean a class was not found
+      case ex: Throwable =>
+        if (settings.debug.value)
+          global.inform("dropping annotation on " + sym +
+                        ", an error occured during parsing (e.g. annotation  class not found)")
+        None // ignore malformed annotations ==> t1135
+    }
 
-    /** Parse a sequence of annotations and attach them to the
-     *  current symbol sym.
+    /**
+     * Parse the "Exceptions" attribute which denotes the exceptions
+     * thrown by a method.
      */
-    def parseAnnotations(len: Int) {
+    def parseExceptions(len: Int) {
+      val nClasses = in.nextChar
+      for (n <- 0 until nClasses) {
+        val cls = pool.getClassSymbol(in.nextChar.toInt)
+        sym.addAnnotation(AnnotationInfo(definitions.ThrowsClass.tpe,
+                                         Literal(Constant(cls.tpe)) :: Nil,
+                                         Nil))
+      }
+    }
+
+    /** Parse a sequence of annotations and attaches them to the
+     *  current symbol sym, except for the ScalaSignature annotation that it returns, if it is available. */
+    def parseAnnotations(len: Int): Option[AnnotationInfo] =  {
       val nAttr = in.nextChar
+      var scalaSigAnnot: Option[AnnotationInfo] = None
       for (n <- 0 until nAttr)
         parseAnnotation(in.nextChar) match {
-          case None =>
-            if (settings.debug.value)
-              global.inform("dropping annotation on " +
-                              sym + " that has a nested annotation")
+          case Some(scalaSig) if (scalaSig.atp == definitions.ScalaSignatureAnnotation.tpe) =>
+            scalaSigAnnot = Some(scalaSig)
+          case Some(scalaSig) if (scalaSig.atp == definitions.ScalaLongSignatureAnnotation.tpe) =>
+            scalaSigAnnot = Some(scalaSig)
           case Some(annot) =>
-            sym.attributes = annot :: sym.attributes
+            sym.addAnnotation(annot)
+          case None =>
         }
+      scalaSigAnnot
     }
 
     // begin parseAttributes
@@ -848,35 +1088,31 @@ abstract class ClassfileParser {
 
       val innerClass = getOwner(jflags).newClass(NoPosition, name.toTypeName).setInfo(completer).setFlag(sflags)
       val innerModule = getOwner(jflags).newModule(NoPosition, name).setInfo(completer).setFlag(sflags)
-      innerClass.moduleClass.setInfo(global.loaders.moduleClassLoader)
-	
+      innerModule.moduleClass.setInfo(global.loaders.moduleClassLoader)
+
       getScope(jflags).enter(innerClass)
       getScope(jflags).enter(innerModule)
       
-      // the 1.4 library misses entries in the InnerClasses attributes (see HashMap$Entry in LinkedHashMap)
-      // TODO: remove this test when we drop support for 1.4
-      if (settings.target.value != "jvm-1.4") {
-        val decls = innerClass.enclosingPackage.info.decls
-        val e = decls.lookupEntry(className(entry.externalName))
-        if (e ne null) {
-          //println("removing " + e)
-          decls.unlink(e)
-        }
-        val e1 = decls.lookupEntry(className(entry.externalName).toTypeName)
-        if (e1 ne null) {
-          //println("removing " + e1)
-          decls.unlink(e1)
-        }
+      val decls = innerClass.enclosingPackage.info.decls
+      val e = decls.lookupEntry(className(entry.externalName))
+      if (e ne null) {
+        //println("removing " + e)
+        decls.unlink(e)
+      }
+      val e1 = decls.lookupEntry(className(entry.externalName).toTypeName)
+      if (e1 ne null) {
+        //println("removing " + e1)
+        decls.unlink(e1)
       }
     }
     
     for (entry <- innerClasses.values) {
       // create a new class member for immediate inner classes
       if (entry.outerName == externalName) {
-        val file = global.classPath.lookupPath(
-          entry.externalName.replace('.', java.io.File.separatorChar).toString, false)
-        assert(file ne null, entry.externalName)
-        enterClassAndModule(entry, new global.loaders.ClassfileLoader(file, null, null), entry.jflags)
+        val file = global.classPath.findSourceFile(entry.externalName.toString) getOrElse {
+          throw new AssertionError(entry.externalName)
+        }
+        enterClassAndModule(entry, new global.loaders.ClassfileLoader(file), entry.jflags)
       }
     }
   }
@@ -895,7 +1131,7 @@ abstract class ClassfileParser {
       val attrLen = in.nextInt
       attrName match {
         case nme.SignatureATTR =>
-          if (!isScala && global.settings.target.value == "jvm-1.5")
+          if (!isScala)
             hasMeta = true
           in.skip(attrLen)
         case nme.JacoMetaATTR =>
@@ -903,16 +1139,20 @@ abstract class ClassfileParser {
           in.skip(attrLen)
         case nme.ScalaSignatureATTR =>
           isScala = true
+          val pbuf = new PickleBuffer(in.buf, in.bp, in.bp + attrLen)
+          pbuf.readNat; pbuf.readNat;
+          if (pbuf.readNat == 0) // a scala signature attribute with no entries means that the actual scala signature
+            isScalaAnnot = true    // is in a ScalaSignature annotation.
           in.skip(attrLen)
         case nme.ScalaATTR =>
           isScalaRaw = true
         case nme.InnerClassesATTR if !isScala =>
           val entries = in.nextChar.toInt
           for (i <- 0 until entries) {
-            val innerIndex = in.nextChar
-            val outerIndex = in.nextChar
-            val nameIndex = in.nextChar
-            val jflags = in.nextChar
+            val innerIndex = in.nextChar.toInt
+            val outerIndex = in.nextChar.toInt
+            val nameIndex = in.nextChar.toInt
+            val jflags = in.nextChar.toInt
             if (innerIndex != 0 && outerIndex != 0 && nameIndex != 0) {
               val entry = InnerClassEntry(innerIndex, outerIndex, nameIndex, jflags)
               innerClasses += (pool.getClassName(innerIndex) -> entry)
@@ -957,25 +1197,41 @@ abstract class ClassfileParser {
      */
     def classSymbol(externalName: Name): Symbol = {
       /** Return the symbol of `innerName', having the given `externalName'. */
-      def innerSymbol(externalName: Name, innerName: Name, static: Boolean): Symbol = 
+      def innerSymbol(externalName: Name, innerName: Name, static: Boolean): Symbol = {
+        def getMember(sym: Symbol, name: Name): Symbol =
+          if (static)
+            if (sym == clazz) staticDefs.lookup(name)
+            else sym.companionModule.info.member(name)
+          else
+            if (sym == clazz) instanceDefs.lookup(name)
+            else sym.info.member(name)
+
         innerClasses.get(externalName) match {
           case Some(entry) =>
-            val sym = classSymbol(entry.outerName)
-            if (static) {
-              val s = sym.linkedModuleOfClass.info.member(innerName.toTypeName)
-              assert(s ne NoSymbol, sym)
-              s
-            } else
-              sym.info.member(innerName.toTypeName)
+            val outerName =
+              if (entry.outerName.endsWith("$")) entry.outerName.subName(0, entry.outerName.length - 1)
+              else entry.outerName
+            val sym = classSymbol(outerName)
+            val s = 
+              // if loading during initialization of `definitions' typerPhase is not yet set.
+              // in that case we simply load the member at the current phase
+              if (currentRun.typerPhase != null)
+                atPhase(currentRun.typerPhase)(getMember(sym, innerName.toTypeName))
+              else 
+                getMember(sym, innerName.toTypeName)
+            assert(s ne NoSymbol, sym + "." + innerName + " linkedModule: " + sym.companionModule + sym.companionModule.info.members)
+            s
+
           case None =>
             val cls = classNameToSymbol(externalName)
             cls
-            //if (static) cls.linkedClassOfModule else cls
+            //if (static) cls.companionClass else cls
         }
+      }
 
       get(externalName) match {
         case Some(entry) =>
-          val clazz = innerSymbol(entry.externalName, entry.originalName, (entry.jflags & JAVA_ACC_STATIC) != 0)
+          val clazz = innerSymbol(entry.externalName, entry.originalName, isStatic(entry.jflags))
           clazz
         case None =>
           classNameToSymbol(externalName)
@@ -990,16 +1246,6 @@ abstract class ClassfileParser {
       sym.setInfo(polyType(tparams1, alias.tpe.substSym(alias.typeParams, tparams1)))
     }
   }
-
-  /** A lazy type that represents a Java inner class. */
-  class LazyInnerClassType(innerEntry: InnerClassEntry) extends LazyType {
-    override def complete(sym: Symbol) {
-//      println("completing " + sym)
-      val clazz = innerClasses.classSymbol(innerEntry.externalName)
-//      println("found symbol: " + clazz)
-      sym.setInfo(clazz.info)
-    }
-  }
   
   def skipAttributes() {
     val attrCount = in.nextChar
@@ -1022,10 +1268,10 @@ abstract class ClassfileParser {
   }
 
   protected def getOwner(flags: Int): Symbol =
-    if ((flags & JAVA_ACC_STATIC) != 0) statics else clazz
+    if (isStatic(flags)) statics else clazz
 
   protected def getScope(flags: Int): Scope =
-    if ((flags & JAVA_ACC_STATIC) != 0) staticDefs else instanceDefs
+    if (isStatic(flags)) staticDefs else instanceDefs
 
   protected def transFlags(flags: Int, isClass: Boolean): Long = {
     var res = 0l
@@ -1044,7 +1290,7 @@ abstract class ClassfileParser {
       res = res | SYNTHETIC
     if ((flags & JAVA_ACC_STATIC) != 0)
       res = res | STATIC
-    if (isClass && ((res & DEFERRED) != 0))
+    if (isClass && ((res & DEFERRED) != 0L))
         res = res & ~DEFERRED | ABSTRACT
 
     res | JAVA
@@ -1052,6 +1298,16 @@ abstract class ClassfileParser {
 
   private def setPrivateWithin(sym: Symbol, jflags: Int) {
     if ((jflags & (JAVA_ACC_PRIVATE | JAVA_ACC_PROTECTED | JAVA_ACC_PUBLIC)) == 0)
-      sym.privateWithin = sym.toplevelClass.owner
+      // See ticket #1687 for an example of when topLevelClass is NoSymbol: it
+      // apparently occurs when processing v45.3 bytecode.
+      if (sym.toplevelClass != NoSymbol)
+        sym.privateWithin = sym.toplevelClass.owner
   }
+  
+  @inline final private def isPrivate(flags: Int) =
+    (flags & JAVA_ACC_PRIVATE) != 0
+  @inline final private def isStatic(flags: Int) =
+    (flags & JAVA_ACC_STATIC) != 0
+  @inline final private def hasAnnotation(flags: Int) =
+    (flags & JAVA_ACC_ANNOTATION) != 0
 }
diff --git a/src/compiler/scala/tools/nsc/symtab/classfile/ICodeReader.scala b/src/compiler/scala/tools/nsc/symtab/classfile/ICodeReader.scala
index c43b2cf..4f69bd0 100644
--- a/src/compiler/scala/tools/nsc/symtab/classfile/ICodeReader.scala
+++ b/src/compiler/scala/tools/nsc/symtab/classfile/ICodeReader.scala
@@ -1,10 +1,11 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author Iulian Dragos
  */
-// $Id: ICodeReader.scala 16881 2009-01-09 16:28:11Z cunei $
 
-package scala.tools.nsc.symtab.classfile
+package scala.tools.nsc
+package symtab
+package classfile
 
 import java.io.IOException
 
@@ -12,7 +13,6 @@ import scala.collection.mutable._
 import scala.tools.nsc._
 import scala.tools.nsc.backend.icode._
 import scala.tools.nsc.io._
-import scala.tools.nsc.util.{Position,NoPosition}
 
 import ClassfileConstants._
 import Flags._
@@ -32,8 +32,8 @@ abstract class ICodeReader extends ClassfileParser {
   var method: IMethod = _                  // the current IMethod
 
   val OBJECT: TypeKind = REFERENCE(definitions.ObjectClass)
-  val nothingName = newTermName("scala.runtime.Nothing$")
-  val nullName    = newTermName("scala.runtime.Null$")
+  val nothingName = newTermName(SCALA_NOTHING)
+  val nullName    = newTermName(SCALA_NULL)
   var isScalaModule = false
 
   /** Read back bytecode for the given class symbol. It returns
@@ -44,21 +44,15 @@ abstract class ICodeReader extends ClassfileParser {
     var classFile: AbstractFile = null;
     var sym = cls
     sym.info // ensure accurate type information
+    
     isScalaModule = cls.isModule && !cls.hasFlag(JAVA)
     log("Reading class: " + cls + " isScalaModule?: " + isScalaModule)
-    val name = cls.fullNameString(java.io.File.separatorChar) + (if (sym.hasFlag(MODULE)) "$" else "")
-    val entry = classPath.root.find(name, false)
-    if (entry ne null) {
-      classFile = entry.classFile
-//      if (isScalaModule)
-//        sym = cls.linkedClassOfModule
-      assert(classFile ne null, "No classfile for " + cls)
-
-//    for (s <- cls.info.members) 
-//      Console.println("" + s + ": " + s.tpe)
-      parse(classFile, sym)
-    } else
-      log("Could not find: " + cls)
+    val name = cls.fullName('.') + (if (sym.hasFlag(MODULE)) "$" else "")
+    
+    classPath.findSourceFile(name) match {
+      case Some(classFile)  => parse(classFile, sym)
+      case _                => log("Could not find: " + cls)
+    }
 
     (staticCode, instanceCode)
   }
@@ -66,11 +60,9 @@ abstract class ICodeReader extends ClassfileParser {
   /** If we're parsing a scala module, the owner of members is always
    *  the module symbol.
    */
-  override def getOwner(jflags: Int): Symbol = {
-    if (isScalaModule) {
-      this.staticModule
-    } else super.getOwner(jflags)
-  }
+  override def getOwner(jflags: Int): Symbol =
+    if (isScalaModule) this.staticModule
+    else super.getOwner(jflags)
 
   override def parseClass() {
     this.instanceCode = new IClass(clazz)
@@ -78,7 +70,7 @@ abstract class ICodeReader extends ClassfileParser {
     val jflags = in.nextChar
     val isAttribute = (jflags & JAVA_ACC_ANNOTATION) != 0
     var sflags = transFlags(jflags, true)
-    if ((sflags & DEFERRED) != 0) sflags = sflags & ~DEFERRED | ABSTRACT
+    if ((sflags & DEFERRED) != 0L) sflags = sflags & ~DEFERRED | ABSTRACT
     val c = pool.getClassSymbol(in.nextChar)
 
     parseInnerClasses()
@@ -102,32 +94,38 @@ abstract class ICodeReader extends ClassfileParser {
   private def parseMember(field: Boolean): (Int, Symbol) = {
     val jflags = in.nextChar
     val name = pool.getName(in.nextChar)
-    var tpe  = pool.getType(in.nextChar)
-    if (name == nme.CONSTRUCTOR)
-      tpe match {
-        case MethodType(formals, restpe) =>
-          assert(restpe.typeSymbol == definitions.UnitClass)
-          tpe = MethodType(formals, getOwner(jflags).tpe)
-      }
 
-    if ("<clinit>" == name.toString) 
-      (jflags, NoSymbol)
-    else {
-      val owner = getOwner(jflags)
-      var sym = owner.info.member(name).suchThat(old => sameType(old.tpe, tpe));
-      if (sym == NoSymbol)
-        sym = owner.info.member(newTermName(name.toString + nme.LOCAL_SUFFIX)).suchThat(old => old.tpe =:= tpe);
-      if (sym == NoSymbol) {
-        log("Could not find symbol for " + name + ": " + tpe/* + " in " + owner.info.decls*/)
-        log(owner.info.member(name).tpe + " : " + tpe)
-        if (field)
-          sym = owner.newValue(owner.pos, name).setInfo(tpe).setFlag(MUTABLE | javaToScalaFlags(jflags))
-        else
-          sym = owner.newMethod(owner.pos, name).setInfo(tpe).setFlag(javaToScalaFlags(jflags))
-        owner.info.decls.enter(sym)
-        log("added " + sym + ": " + sym.tpe)
+    val owner = getOwner(jflags)
+    val dummySym = owner.newMethod(owner.pos, name).setFlag(javaToScalaFlags(jflags))
+
+    try {
+      val ch = in.nextChar
+      var tpe  = pool.getType(dummySym, ch)
+
+      if ("<clinit>" == name.toString)
+        (jflags, NoSymbol)
+      else {
+        val owner = getOwner(jflags)
+        var sym = owner.info.member(name).suchThat(old => sameType(old.tpe, tpe));
+        if (sym == NoSymbol)
+          sym = owner.info.member(newTermName(name.toString + nme.LOCAL_SUFFIX)).suchThat(old => old.tpe =:= tpe);
+        if (sym == NoSymbol) {
+          log("Could not find symbol for " + name + ": " + tpe + " in " + owner.info.decls)
+          log(owner.info.member(name).tpe + " : " + tpe)
+          if (name.toString() == "toMap")
+            tpe = pool.getType(dummySym, ch)
+          if (field)
+            sym = owner.newValue(owner.pos, name).setInfo(tpe).setFlag(MUTABLE | javaToScalaFlags(jflags))
+          else
+            sym = dummySym.setInfo(tpe)
+          owner.info.decls.enter(sym)
+          log("added " + sym + ": " + sym.tpe)
+        }
+        (jflags, sym)
       }
-      (jflags, sym)
+    } catch {
+      case e: MissingRequirementError =>
+        (jflags, NoSymbol)
     }
   }
 
@@ -144,34 +142,39 @@ abstract class ICodeReader extends ClassfileParser {
     res
   }
   
-  /** Checks if tp1 is the same type as tp2, modulo implict methods.
-   *  We don't care about the distinction between implcit and explicit
+  /** Checks if tp1 is the same type as tp2, modulo implicit methods.
+   *  We don't care about the distinction between implicit and explicit
    *  methods as this point, and we can't get back the information from
    *  bytecode anyway.
    */
   private def sameType(tp1: Type, tp2: Type): Boolean = (tp1, tp2) match {
-    case (MethodType(args1, resTpe1), MethodType(args2, resTpe2)) =>
-      if (tp1.isInstanceOf[ImplicitMethodType] || tp2.isInstanceOf[ImplicitMethodType]) {
-        MethodType(args1, resTpe1) =:= MethodType(args2, resTpe2)
-      } else
-        tp1 =:= tp2
-    case _ => tp1 =:= tp2
+    case (mt1 @ MethodType(args1, resTpe1), mt2 @ MethodType(args2, resTpe2)) if mt1.isImplicit || mt2.isImplicit =>
+      MethodType(args1, resTpe1) =:= MethodType(args2, resTpe2)
+    case _ =>
+      tp1 =:= tp2
   }
   
   override def parseMethod() {
     val (jflags, sym) = parseMember(false)
-    if (sym != NoSymbol) {
-      log("Parsing method " + sym.fullNameString + ": " + sym.tpe);
-      this.method = new IMethod(sym);
-      this.method.returnType = toTypeKind(sym.tpe.resultType)
-      getCode(jflags).addMethod(this.method)
-      if ((jflags & JAVA_ACC_NATIVE) != 0)
-        this.method.native = true
-      val attributeCount = in.nextChar
-      for (i <- 0 until attributeCount) parseAttribute()
-    } else {
-      if (settings.debug.value) log("Skipping non-existent method.");
-      skipAttributes();
+    var beginning = in.bp
+    try {
+      if (sym != NoSymbol) {
+        log("Parsing method " + sym.fullName + ": " + sym.tpe);
+        this.method = new IMethod(sym);
+        this.method.returnType = toTypeKind(sym.tpe.resultType)
+        getCode(jflags).addMethod(this.method)
+        if ((jflags & JAVA_ACC_NATIVE) != 0)
+          this.method.native = true
+        val attributeCount = in.nextChar
+        for (i <- 0 until attributeCount) parseAttribute()
+      } else {
+        if (settings.debug.value) log("Skipping non-existent method.");
+        skipAttributes();
+      }
+    } catch {
+      case e: MissingRequirementError =>
+        in.bp = beginning; skipAttributes
+        if (settings.debug.value) log("Skipping non-existent method. " + e.msg);
     }
   }
 
@@ -186,21 +189,28 @@ abstract class ICodeReader extends ClassfileParser {
     }
   }
 
-  override def classNameToSymbol(name: Name) = { 
+  override def classNameToSymbol(name: Name) = {
     val sym = if (name == nothingName)
       definitions.NothingClass
     else if (name == nullName)
       definitions.NullClass
     else if (name.endsWith("$class")) {
       val iface = definitions.getClass(name.subName(0, name.length - "$class".length))
-      log("forcing " + iface)
-      iface.info // force the mixin type-transformer
+      log("forcing " + iface.owner + " at phase: " + phase + " impl: " + iface.implClass)
+      iface.owner.info // force the mixin type-transformer
       definitions.getClass(name)
-    } else if (name.endsWith("$"))
-      definitions.getModule(name.subName(0, name.length - 1))
-    else
-      definitions.getClass(name)
-        //super.classNameToSymbol(name)
+    } else if (name.endsWith("$")) {
+      val sym = forceMangledName(name.subName(0, name.length -1).decode, true)
+//      println("classNameToSymbol: " + name + " sym: " + sym)
+      if (name.toString == "scala.collection.immutable.Stream$$hash$colon$colon$")
+        print("")
+      if (sym == NoSymbol)
+        definitions.getModule(name.subName(0, name.length - 1))
+      else sym
+    } else {
+      forceMangledName(name, false)
+      atPhase(currentRun.flattenPhase.next)(definitions.getClass(name))
+    }
     if (sym.isModule)
       sym.moduleClass
     else
@@ -230,7 +240,7 @@ abstract class ICodeReader extends ClassfileParser {
       /** Parse 16 bit jump target. */
       def parseJumpTarget = {
         size = size + 2
-        val offset = in.nextChar.asInstanceOf[Short]
+        val offset = in.nextChar.toShort
         val target = pc + offset
         assert(target >= 0 && target < codeLength, "Illegal jump target: " + target)
         target
@@ -275,7 +285,7 @@ abstract class ICodeReader extends ClassfileParser {
         case JVM.fload       => code.emit(LOAD_LOCAL(code.getLocal(in.nextByte, FLOAT)));  size += 1
         case JVM.dload       => code.emit(LOAD_LOCAL(code.getLocal(in.nextByte, DOUBLE))); size += 1
         case JVM.aload       => 
-          val local = in.nextByte; size += 1
+          val local = in.nextByte.toInt; size += 1
           if (local == 0 && !method.isStatic)
             code.emit(THIS(method.symbol.owner));
           else
@@ -336,7 +346,11 @@ abstract class ICodeReader extends ClassfileParser {
         case JVM.dstore_1    => code.emit(STORE_LOCAL(code.getLocal(1, DOUBLE)))
         case JVM.dstore_2    => code.emit(STORE_LOCAL(code.getLocal(2, DOUBLE)))
         case JVM.dstore_3    => code.emit(STORE_LOCAL(code.getLocal(3, DOUBLE)))
-        case JVM.astore_0    => code.emit(STORE_LOCAL(code.getLocal(0, OBJECT)))
+        case JVM.astore_0    =>
+          if (method.isStatic)
+            code.emit(STORE_LOCAL(code.getLocal(0, OBJECT)))
+          else
+            code.emit(STORE_THIS(OBJECT))
         case JVM.astore_1    => code.emit(STORE_LOCAL(code.getLocal(1, OBJECT)))
         case JVM.astore_2    => code.emit(STORE_LOCAL(code.getLocal(2, OBJECT)))
         case JVM.astore_3    => code.emit(STORE_LOCAL(code.getLocal(3, OBJECT)))
@@ -462,7 +476,7 @@ abstract class ICodeReader extends ClassfileParser {
           size += 8
           assert(low <= high, "Value low not <= high for tableswitch.")
 
-          val tags = List.tabulate(high - low + 1, n => List(low + n))
+          val tags = List.tabulate(high - low + 1)(n => List(low + n))
           val targets = for (_ <- tags) yield parseJumpTargetW
           code.emit(LSWITCH(tags, targets ::: List(default)))
 
@@ -599,9 +613,9 @@ abstract class ICodeReader extends ClassfileParser {
 
     // add parameters
     var idx = if (method.isStatic) 0 else 1
-    for (t <- method.symbol.tpe.paramTypes) {
-      this.method.addParam(code.enterParam(idx, toTypeKind(t)))
-      idx += 1
+    for (t <- method.symbol.tpe.paramTypes; val kind = toTypeKind(t)) {
+      this.method.addParam(code.enterParam(idx, kind))
+      idx += (if (kind.isWideType) 2 else 1)
     }
     
     pc = 0
@@ -629,11 +643,17 @@ abstract class ICodeReader extends ClassfileParser {
     }
     if (code.containsNEW) code.resolveNEWs
   }
-
-  /** TODO: move in Definitions and remove obsolete isBox/isUnbox found there. */
+  
+  /** Note: these methods are different from the methods of the same name found
+   *  in Definitions.  These test whether a symbol represents one of the boxTo/unboxTo
+   *  methods found in BoxesRunTime.  The others test whether a symbol represents a
+   *  synthetic method from one of the fake companion classes of the primitive types,
+   *  such as Int.box(5).
+   */
   def isBox(m: Symbol): Boolean = 
     (m.owner == definitions.BoxesRunTimeClass.moduleClass
         && m.name.startsWith("boxTo"))
+
   def isUnbox(m: Symbol): Boolean = 
     (m.owner == definitions.BoxesRunTimeClass.moduleClass
         && m.name.startsWith("unboxTo"))
@@ -643,7 +663,8 @@ abstract class ICodeReader extends ClassfileParser {
    */
   def getCode(flags: Int): IClass =
     if (isScalaModule) staticCode
-    else if ((flags & JAVA_ACC_STATIC) != 0) staticCode else instanceCode
+    else if ((flags & JAVA_ACC_STATIC) != 0) staticCode
+    else instanceCode
 
   class LinearCode {
     var instrs: ListBuffer[(Int, Instruction)] = new ListBuffer
@@ -681,7 +702,7 @@ abstract class ICodeReader extends ClassfileParser {
       var otherBlock: BasicBlock = null
       var disableJmpTarget = false
       
-      for ((pc, instr) <- instrs.elements) {
+      for ((pc, instr) <- instrs.iterator) {
 //        Console.println("> " + pc + ": " + instr);
         if (jmpTargets contains pc) {
           otherBlock = blocks(pc)
@@ -926,16 +947,19 @@ abstract class ICodeReader extends ClassfileParser {
         for ((i, idx) <- bb.toList.zipWithIndex) i match {
           case CALL_METHOD(m, Static(true)) if m.isClassConstructor =>
             val defs = rdef.findDefs(bb, idx, 1, m.info.paramTypes.length)
-            //println("ctor: " + i + " found defs: " + defs)
-            assert(defs.length == 1)
+            if (settings.debug.value) log("ctor: " + i + " found defs: " + defs)
+            assert(defs.length == 1, "wrong defs at bb " + bb + "\n" + method.dump + rdef)
             val (bb1, idx1) = defs.head
             var producer = bb1(idx1)
             while (producer.isInstanceOf[DUP]) {
               val (bb2, idx2) = rdef.findDefs(bb1, idx1, 1).head
               producer = bb2(idx2)
             }
-            assert(producer.isInstanceOf[NEW], producer)
-            producer.asInstanceOf[NEW].init = i.asInstanceOf[CALL_METHOD]
+            producer match {
+              case nw: NEW => nw.init = i.asInstanceOf[CALL_METHOD]
+              case _: THIS => () // super constructor call
+              case _ => assert(false, producer + "\n" + method.dump)
+            }
           case _ =>
         }
       }
diff --git a/src/compiler/scala/tools/nsc/symtab/classfile/MetaParser.scala b/src/compiler/scala/tools/nsc/symtab/classfile/MetaParser.scala
index 845cac0..ed13b1b 100644
--- a/src/compiler/scala/tools/nsc/symtab/classfile/MetaParser.scala
+++ b/src/compiler/scala/tools/nsc/symtab/classfile/MetaParser.scala
@@ -1,15 +1,15 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: MetaParser.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.tools.nsc.symtab.classfile
+package scala.tools.nsc
+package symtab
+package classfile
 
 import java.util.{StringTokenizer, NoSuchElementException}
 
 import scala.collection.mutable.ListBuffer
-import scala.tools.nsc.util.{Position,NoPosition}
 
 abstract class MetaParser{
 
@@ -76,7 +76,7 @@ abstract class MetaParser{
     val hi =
       if (token == "<") { nextToken(); parseType() }
       else definitions.AnyClass.tpe
-    sym.setInfo(mkTypeBounds(lo, hi))
+    sym.setInfo(TypeBounds(lo, hi))
     locals enter sym;
     sym
   }
@@ -108,7 +108,7 @@ abstract class MetaParser{
   }
 
   protected def parseClass() {
-    locals = newScope
+    locals = new Scope
     def parse(): Type = {
       nextToken()
       if (token == "[") {
@@ -130,11 +130,14 @@ abstract class MetaParser{
 
   protected def parseMethod() {
     val globals = locals
-    locals = if (locals eq null) newScope else newScope(locals)
+    locals = if (locals eq null) new Scope else new Scope(locals)
     def parse(): Type = {
       nextToken();
       if (token == "[") PolyType(parseTypeParams(), parse())
-      else if (token == "(") MethodType(parseParams(), parse())
+      else if (token == "(") {
+        val formals = parseParams()
+        MethodType(owner.newSyntheticValueParams(formals), parse())
+      }
       else parseType()
     }
     owner.setInfo(parse())
@@ -151,7 +154,10 @@ abstract class MetaParser{
   protected def parseConstr() {
     def parse(): Type = {
       nextToken()
-      if (token == "(") MethodType(parseParams(), parse())
+      if (token == "(") {
+        val formals = parseParams()
+        MethodType(owner.newSyntheticValueParams(formals), parse())
+      }
       else owner.owner.tpe
     }
     owner.setInfo(parse())
diff --git a/src/compiler/scala/tools/nsc/symtab/classfile/PickleBuffer.scala b/src/compiler/scala/tools/nsc/symtab/classfile/PickleBuffer.scala
deleted file mode 100644
index 63f226b..0000000
--- a/src/compiler/scala/tools/nsc/symtab/classfile/PickleBuffer.scala
+++ /dev/null
@@ -1,148 +0,0 @@
-/* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
- * @author  Martin Odersky
- */
-// $Id: PickleBuffer.scala 16894 2009-01-13 13:09:41Z cunei $
-
-package scala.tools.nsc.symtab.classfile
-
-/** Variable length byte arrays, with methods for basic pickling and unpickling.
- *
- *  @param data The initial buffer
- *  @param from The first index where defined data are found
- *  @param to   The first index where new data can be written
- */
-class PickleBuffer(data: Array[Byte], from: Int, to: Int) {
-
-  var bytes = data
-  var readIndex = from
-  var writeIndex = to
-
-  /** Double bytes array */
-  private def dble() {
-    val bytes1 = new Array[Byte](bytes.length * 2)
-    Array.copy(bytes, 0, bytes1, 0, writeIndex)
-    bytes = bytes1
-  }
-
-  def ensureCapacity(capacity: Int) =
-    while (bytes.length < writeIndex + capacity) dble()
-
-  // -- Basic output routines --------------------------------------------
-
-  /** Write a byte of data */
-  def writeByte(b: Int) {
-    if (writeIndex == bytes.length) dble()
-    bytes(writeIndex) = b.asInstanceOf[Byte]
-    writeIndex += 1
-  }
-
-  /** Write a natural number in big endian format, base 128.
-   *  All but the last digits have bit 0x80 set.
-   */
-  def writeNat(x: Int) {
-    def writeNatPrefix(x: Int) {
-      val y = x >>> 7
-      if (y != 0) writeNatPrefix(y)
-      writeByte((x & 0x7f) | 0x80)
-    }
-    val y = x >>> 7
-    if (y != 0) writeNatPrefix(y)
-    writeByte(x & 0x7f)
-  }
-
-  /** Write a natural number <code>x</code> at position <code>pos</code>.
-   *  If number is more than one byte, shift rest of array to make space.
-   *
-   *  @param pos ...
-   *  @param x   ...
-   */
-  def patchNat(pos: Int, x: Int) {
-    def patchNatPrefix(x: Int) {
-      writeByte(0)
-      Array.copy(bytes, pos, bytes, pos+1, writeIndex - (pos+1))
-      bytes(pos) = ((x & 0x7f) | 0x80).asInstanceOf[Byte]
-      val y = x >>> 7
-      if (y != 0) patchNatPrefix(y)
-    }
-    bytes(pos) = (x & 0x7f).asInstanceOf[Byte]
-    val y = x >>> 7
-    if (y != 0) patchNatPrefix(y)
-  }
-
-  /** Write a long number <code>x</code> in signed big endian format, base 256.
-   *
-   *  @param x The long number to be written.
-   */
-  def writeLong(x: Long) {
-    val y = x >> 8
-    val z = x & 0xff
-    if (-y != (z >> 7)) writeLong(y)
-    writeByte(z.asInstanceOf[Int])
-  }
-
-  // -- Basic input routines --------------------------------------------
-
-  /** Peek at the current byte without moving the read index */
-  def peekByte(): Int = bytes(readIndex)
-
-  /** Read a byte */
-  def readByte(): Int = {
-    val x = bytes(readIndex); readIndex += 1; x
-  }
-
-  /** Read a natural number in big endian format, base 128.
-   *  All but the last digits have bit 0x80 set.*/
-  def readNat(): Int = {
-    var b = 0
-    var x = 0
-    do {
-      b = readByte()
-      x = (x << 7) + (b & 0x7f)
-    } while ((b & 0x80) != 0);
-    x
-  }
-
-  /** Read a long number in signed big endian format, base 256. */
-  def readLong(len: Int): Long = {
-    var x = 0L
-    var i = 0
-    while (i < len) {
-      x = (x << 8) + (readByte() & 0xff)
-      i += 1
-    }
-    val leading = 64 - (len << 3)
-    x << leading >> leading
-  }
-
-  /** Perform operation <code>op</code> until the condition
-   *  <code>readIndex == end</code> is satisfied.
-   *  Concatenate results into a list.
-   *
-   *  @param end ...
-   *  @param op  ...
-   *  @return    ...
-   */
-  def until[T](end: Int, op: () => T): List[T] =
-    if (readIndex == end) List() else op() :: until(end, op);
-
-  /** Perform operation <code>op</code> the number of
-   *  times specified.  Concatenate the results into a list.
-   */
-  def times[T](n: Int, op: ()=>T): List[T] =
-    if (n == 0) List() else op() :: times(n-1, op)
-
-  /** Create an index.
-   *
-   *  @return ...
-   */
-  def createIndex: Array[Int] = {
-    val index = new Array[Int](readNat())
-    for (i <- 0 until index.length) {
-      index(i) = readIndex
-      readByte()
-      readIndex = readNat() + readIndex
-    }
-    index
-  }
-}
diff --git a/src/compiler/scala/tools/nsc/symtab/classfile/PickleFormat.scala b/src/compiler/scala/tools/nsc/symtab/classfile/PickleFormat.scala
deleted file mode 100644
index ab68685..0000000
--- a/src/compiler/scala/tools/nsc/symtab/classfile/PickleFormat.scala
+++ /dev/null
@@ -1,244 +0,0 @@
-/* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
- * @author  Martin Odersky
- */
-// $Id: PickleFormat.scala 16894 2009-01-13 13:09:41Z cunei $
-
-package scala.tools.nsc.symtab.classfile
-
-/** This object provides constants for pickling attributes.
- *
- *  If you extend the format, be sure to increase the
- *  version minor number.
- *
- *  @author Martin Odersky
- *  @version 1.0
- */
-object PickleFormat {
-
-/***************************************************
- * Symbol table attribute format:
- *   Symtab         = nentries_Nat {Entry}
- *   Entry          = 1 TERMNAME len_Nat NameInfo
- *                  | 2 TYPENAME len_Nat NameInfo
- *                  | 3 NONEsym len_Nat
- *                  | 4 TYPEsym len_Nat SymbolInfo
- *                  | 5 ALIASsym len_Nat SymbolInfo
- *                  | 6 CLASSsym len_Nat SymbolInfo [thistype_Ref]
- *                  | 7 MODULEsym len_Nat SymbolInfo
- *                  | 8 VALsym len_Nat SymbolInfo [alias_Ref]
- *                  | 9 EXTref len_Nat name_Ref [owner_Ref]
- *                  | 10 EXTMODCLASSref len_Nat name_Ref [owner_Ref]
- *                  | 11 NOtpe len_Nat
- *                  | 12 NOPREFIXtpe len_Nat
- *                  | 13 THIStpe len_Nat sym_Ref
- *                  | 14 SINGLEtpe len_Nat type_Ref sym_Ref
- *                  | 15 CONSTANTtpe len_Nat type_Ref constant_Ref
- *                  | 16 TYPEREFtpe len_Nat type_Ref sym_Ref {targ_Ref}
- *                  | 17 TYPEBOUNDStpe len_Nat tpe_Ref tpe_Ref
- *                  | 18 REFINEDtpe len_Nat classsym_Ref {tpe_Ref}
- *                  | 19 CLASSINFOtpe len_Nat classsym_Ref {tpe_Ref}
- *                  | 20 METHODtpe len_Nat tpe_Ref {tpe_Ref} 
- *                  | 21 POLYTtpe len_Nat tpe_Ref {sym_Ref} 
- *                  | 22 IMPLICITMETHODtpe len_Nat tpe_Ref {tpe_Ref}
- *                  | 24 LITERALunit len_Nat
- *                  | 25 LITERALboolean len_Nat value_Long
- *                  | 26 LITERALbyte len_Nat value_Long
- *                  | 27 LITERALshort len_Nat value_Long
- *                  | 28 LITERALchar len_Nat value_Long
- *                  | 29 LITERALint len_Nat value_Long
- *                  | 30 LITERALlong len_Nat value_Long
- *                  | 31 LITERALfloat len_Nat value_Long
- *                  | 32 LITERALdouble len_Nat value_Long
- *                  | 33 LITERALstring len_Nat name_Ref
- *                  | 34 LITERALnull len_Nat
- *                  | 35 LITERALclass len_Nat type_Ref
- *                  | 40 ATTRIBUTE len_Nat sym_Ref info_Ref {constant_Ref} {nameRef constantRef}
- *                  | 41 CHILDREN len_Nat sym_Ref {sym_Ref} 
- *                  | 42 ANNOTATEDtpe len_Nat tpe_Ref {attribtree_Ref}
- *                  | 51 ANNOTATEDWSELFtpe len_Nat tpe_Ref sym_Ref {attribtree_Ref}
- *                  | 43 ANNOTINFO attarg_Ref len_Nat attarg_Ref {constant_Ref attarg_Ref}
- *                  | 47 DEBRUIJNINDEXtpe len_Nat level_Nat index_Nat
- *                  | 48 EXISTENTIALtpe len_Nat type_Ref {symbol_Ref}
- *                  | 49 TREE len_Nat 1 EMPTYtree
- *                  | 49 TREE len_Nat 2 PACKAGEtree type_Ref sym_Ref mods_Ref name_Ref {tree_Ref}
- *                  | 49 TREE len_Nat 3 CLASStree type_Ref sym_Ref mods_Ref name_Ref tree_Ref {tree_Ref}
- *                  | 49 TREE len_Nat 4 MODULEtree type_Ref sym_Ref mods_Ref name_Ref tree_Ref
- *                  | 49 TREE len_Nat 5 VALDEFtree type_Ref sym_Ref mods_Ref name_Ref tree_Ref tree_Ref
- *                  | 49 TREE len_Nat 6 DEFDEFtree type_Ref sym_Ref mods_Ref name_Ref numtparams_Nat {tree_Ref} numparamss_Nat {numparams_Nat {tree_Ref}} tree_Ref tree_Ref
- *                  | 49 TREE len_Nat 7 TYPEDEFtree type_Ref sym_Ref mods_Ref name_Ref tree_Ref {tree_Ref}
- *                  | 49 TREE len_Nat 8 LABELtree type_Ref sym_Ref tree_Ref {tree_Ref}
- *                  | 49 TREE len_Nat 9 IMPORTtree type_Ref sym_Ref tree_Ref {name_Ref name_Ref}
- *                  | 49 TREE len_Nat 10 ANNOTATIONtree type_Ref sym_Ref tree_Ref {tree_Ref}
- *                  | 49 TREE len_Nat 11 DOCDEFtree type_Ref sym_Ref string_Ref tree_Ref
- *                  | 49 TREE len_Nat 12 TEMPLATEtree type_Ref sym_Ref numparents_Nat {tree_Ref} tree_Ref {tree_Ref}
- *                  | 49 TREE len_Nat 13 BLOCKtree type_Ref tree_Ref {tree_Ref}
- *                  | 49 TREE len_Nat 14 CASEtree type_Ref tree_Ref tree_Ref tree_Ref
- *                  | 49 TREE len_Nat 15 SEQUENCEtree type_Ref {tree_Ref}
- *                  | 49 TREE len_Nat 16 ALTERNATIVEtree type_Ref {tree_Ref}
- *                  | 49 TREE len_Nat 17 STARtree type_Ref {tree_Ref}
- *                  | 49 TREE len_Nat 18 BINDtree type_Ref sym_Ref name_Ref tree_Ref
- *                  | 49 TREE len_Nat 19 UNAPPLYtree type_Ref tree_Ref {tree_Ref} 
- *                  | 49 TREE len_Nat 20 ARRAYVALUEtree type_Ref tree_Ref {tree_Ref} 
- *                  | 49 TREE len_Nat 21 FUNCTIONtree type_Ref sym_Ref tree_Ref {tree_Ref} 
- *                  | 49 TREE len_Nat 22 ASSIGNtree type_Ref tree_Ref tree_Ref 
- *                  | 49 TREE len_Nat 23 IFtree type_Ref tree_Ref tree_Ref tree_Ref 
- *                  | 49 TREE len_Nat 24 MATCHtree type_Ref tree_Ref {tree_Ref} 
- *                  | 49 TREE len_Nat 25 RETURNtree type_Ref sym_Ref tree_Ref
- *                  | 49 TREE len_Nat 26 TREtree type_Ref tree_Ref tree_Ref {tree_Ref} 
- *                  | 49 TREE len_Nat 27 THROWtree type_Ref tree_Ref 
- *                  | 49 TREE len_Nat 28 NEWtree type_Ref tree_Ref 
- *                  | 49 TREE len_Nat 29 TYPEDtree type_Ref tree_Ref tree_Ref 
- *                  | 49 TREE len_Nat 30 TYPEAPPLYtree type_Ref tree_Ref {tree_Ref} 
- *                  | 49 TREE len_Nat 31 APPLYtree type_Ref tree_Ref {tree_Ref} 
- *                  | 49 TREE len_Nat 32 APPLYDYNAMICtree type_Ref sym_Ref tree_Ref {tree_Ref} 
- *                  | 49 TREE len_Nat 33 SUPERtree type_Ref sym_Ref tree_Ref name_Ref
- *                  | 49 TREE len_Nat 34 THIStree type_Ref sym_Ref  name_Ref
- *                  | 49 TREE len_Nat 35 SELECTtree type_Ref sym_Ref tree_Ref name_Ref
- *                  | 49 TREE len_Nat 36 IDENTtree type_Ref sym_Ref name_Ref
- *                  | 49 TREE len_Nat 37 LITERALtree type_Ref constant_Ref 
- *                  | 49 TREE len_Nat 38 TYPEtree type_Ref 
- *                  | 49 TREE len_Nat 39 ANNOTATEDtree type_Ref tree_Ref tree_Ref
- *                  | 49 TREE len_Nat 40 SINGLETONTYPEtree type_Ref tree_Ref 
- *                  | 49 TREE len_Nat 41 SELECTFROMTYPEtree type_Ref tree_Ref name_Ref 
- *                  | 49 TREE len_Nat 42 COMPOUNDTYPEtree type_Ref tree_Ref 
- *                  | 49 TREE len_Nat 43 APPLIEDTYPEtree type_Ref tree_Ref {tree_Ref} 
- *                  | 49 TREE len_Nat 44 TYPEBOUNDStree type_Ref tree_Ref tree_Ref
- *                  | 49 TREE len_Nat 45 EXISTENTIALTYPEtree type_Ref tree_Ref {tree_Ref} 
- *                  | 50 MODIFIERS len_Nat flags_Long privateWithin_Ref {Annotation_Ref}
- *                  | 68 PosTYPEsym len_Nat pos_Nat SymbolInfo
- *                  | 69 PosALIASsym len_Nat pos_Nat SymbolInfo
- *                  | 70 PosCLASSsym len_Nat pos_Nat SymbolInfo [thistype_Ref]
- *                  | 71 PosMODULEsym len_Nat pos_Nat SymbolInfo
- *                  | 72 PosVALsym len_Nat pos_Nat SymbolInfo [alias_Ref]
- *   SymbolInfo     = name_Ref owner_Ref flags_Nat [privateWithin_Ref] info_Ref
- *   NameInfo       = <character sequence of length len_Nat in Utf8 format>
- *   NumInfo        = <len_Nat-byte signed number in big endian format>
- *   Ref            = Nat
- *   Attarg         = Refltree | Constant
- *
- *   len is remaining length after `len'.
- */
-  val MajorVersion = 4
-  val MinorVersion = 1
-
-  final val TERMname = 1
-  final val TYPEname = 2
-  final val NONEsym = 3
-  final val TYPEsym = 4
-  final val ALIASsym = 5
-  final val CLASSsym = 6
-  final val MODULEsym = 7
-  final val VALsym = 8
-  final val EXTref = 9
-  final val EXTMODCLASSref = 10
-  final val NOtpe = 11
-  final val NOPREFIXtpe = 12
-  final val THIStpe = 13
-  final val SINGLEtpe = 14
-  final val CONSTANTtpe = 15
-  final val TYPEREFtpe = 16
-  final val TYPEBOUNDStpe = 17
-  final val REFINEDtpe = 18
-  final val CLASSINFOtpe = 19
-  final val METHODtpe = 20
-  final val POLYtpe = 21
-  final val IMPLICITMETHODtpe = 22
-
-  final val LITERAL = 23   // base line for literals
-  final val LITERALunit = 24
-  final val LITERALboolean = 25
-  final val LITERALbyte = 26
-  final val LITERALshort = 27
-  final val LITERALchar = 28
-  final val LITERALint = 29
-  final val LITERALlong = 30
-  final val LITERALfloat = 31
-  final val LITERALdouble = 32
-  final val LITERALstring = 33
-  final val LITERALnull = 34
-  final val LITERALclass = 35
-  final val ATTRIBUTE = 40  // an attribute with constants
-  final val CHILDREN = 41
-
-  final val ANNOTATEDtpe = 42
-  final val ANNOTINFO = 43  // an annotation with trees
-  final val REFLTREE = 44  // prefix saying that a reflect tree is coming  
-                           // support dropped in September of 2007
-
-  final val REFLTYPE = 45   // prefix code that means a reflect type is coming
-                           // support dropped in September of 2007
-
-  final val REFLSYM = 46   // prefix code that means a reflect symbol is coming
-                           // support dropped in September of 2007
-
-  final val DEBRUIJNINDEXtpe = 47
-  final val EXISTENTIALtpe = 48
-
-  final val TREE = 49      // prefix code that means a tree is coming
-    final val EMPTYtree = 1
-    final val PACKAGEtree = 2
-    final val CLASStree = 3
-    final val MODULEtree = 4
-    final val VALDEFtree = 5
-    final val DEFDEFtree = 6
-    final val TYPEDEFtree = 7
-    final val LABELtree = 8
-    final val IMPORTtree = 9
-    final val ANNOTATIONtree = 10
-    final val DOCDEFtree = 11
-    final val TEMPLATEtree = 12
-    final val BLOCKtree = 13
-    final val CASEtree = 14
-    final val SEQUENCEtree = 15
-    final val ALTERNATIVEtree = 16
-    final val STARtree = 17
-    final val BINDtree = 18
-    final val UNAPPLYtree = 19
-    final val ARRAYVALUEtree = 20
-    final val FUNCTIONtree = 21
-    final val ASSIGNtree = 22
-    final val IFtree = 23
-    final val MATCHtree = 24
-    final val RETURNtree = 25
-    final val TREtree = 26
-    final val THROWtree = 27
-    final val NEWtree = 28
-    final val TYPEDtree = 29
-    final val TYPEAPPLYtree = 30
-    final val APPLYtree = 31
-    final val APPLYDYNAMICtree = 32
-    final val SUPERtree = 33
-    final val THIStree = 34
-    final val SELECTtree = 35
-    final val IDENTtree = 36
-    final val LITERALtree = 37
-    final val TYPEtree = 38
-    final val ANNOTATEDtree = 39
-    final val SINGLETONTYPEtree = 40
-    final val SELECTFROMTYPEtree = 41
-    final val COMPOUNDTYPEtree = 42
-    final val APPLIEDTYPEtree = 43
-    final val TYPEBOUNDStree = 44
-    final val EXISTENTIALTYPEtree = 45
-
-  final val MODIFIERS = 50
-  final val ANNOTATEDWSELFtpe = 51 // annotated type with selfsym
-
-  final val firstSymTag = NONEsym
-  final val lastSymTag = VALsym
-  final val lastExtSymTag = EXTMODCLASSref
-
-
-  //The following two are no longer accurate, because ATTRIBUTEDtpe
-  //is not in the same range as the other types
-  //final val firstTypeTag = NOtpe
-  //final val lastTypeTag = POLYtpe
-
-  final val PosOffset = 64
-  final val PosTYPEsym  = PosOffset + TYPEsym 
-  final val PosALIASsym = PosOffset + ALIASsym
-  final val PosCLASSsym = PosOffset + CLASSsym 
-  final val PosMODULEsym = PosOffset + MODULEsym 
-  final val PosVALsym = PosOffset + VALsym
-}
diff --git a/src/compiler/scala/tools/nsc/symtab/classfile/Pickler.scala b/src/compiler/scala/tools/nsc/symtab/classfile/Pickler.scala
index 1dd39c6..785c545 100644
--- a/src/compiler/scala/tools/nsc/symtab/classfile/Pickler.scala
+++ b/src/compiler/scala/tools/nsc/symtab/classfile/Pickler.scala
@@ -1,15 +1,18 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: Pickler.scala 18740 2009-09-22 16:22:14Z cunei $
 
-package scala.tools.nsc.symtab.classfile
+package scala.tools.nsc
+package symtab
+package classfile
 
 import java.lang.{Float, Double}
-import scala.tools.nsc.util.{Position, NoPosition, ShowPickled}
-import Flags._
+import util.{ Position, NoPosition, ShowPickled }
+import collection.mutable.Set
+import reflect.generic.{ PickleBuffer, PickleFormat }
 import PickleFormat._
+import Flags._
 
 /**
  * Serialize a top-level module and/or class.
@@ -47,16 +50,8 @@ abstract class Pickler extends SubComponent {
             val sym = tree.symbol
             val pickle = new Pickle(sym, sym.name.toTermName, sym.owner)
             add(sym, pickle)
-            add(sym.linkedSym, pickle)
+            add(sym.companionSymbol, pickle)
             pickle.finish
-            val doPickleHash = global.doPickleHash
-            if (doPickleHash) {
-              var i = 0
-              while (i < pickle.writeIndex) {
-                unit.pickleHash += pickle.bytes(i).toLong // toLong needed to work around bug
-                i += 1
-              }
-            }
           case _ =>
         }
       }
@@ -66,31 +61,42 @@ abstract class Pickler extends SubComponent {
 
   private class Pickle(root: Symbol, rootName: Name, rootOwner: Symbol)
         extends PickleBuffer(new Array[Byte](4096), -1, 0) {
-    import scala.collection.jcl.LinkedHashMap
+    import scala.collection.mutable.LinkedHashMap
     private var entries = new Array[AnyRef](256)
     private var ep = 0
     private val index = new LinkedHashMap[AnyRef, Int]
 
+    // collect higher-order type params
+    //private var locals: Set[Symbol] = Set()
+
 //    private var boundSyms: List[Symbol] = Nil
 
+    private def isRootSym(sym: Symbol) = 
+      sym.name.toTermName == rootName && sym.owner == rootOwner
+
     /** Returns usually symbol's owner, but picks classfile root instead
      *  for existentially bound variables that have a non-local owner.
      *  Question: Should this be done for refinement class symbols as well?
      */
     private def localizedOwner(sym: Symbol) = 
-      if (sym.isAbstractType && sym.hasFlag(EXISTENTIAL) && !isLocal(sym.owner)) root 
+      if (isLocal(sym) && !isRootSym(sym) && !isLocal(sym.owner)) root 
       else sym.owner
 
     /** Is root in symbol.owner*, or should it be treated as a local symbol
-     *  anyway? This is the case if symbol is a refinement class or
-     *  an existentially bound variable.
+     *  anyway? This is the case if symbol is a refinement class,
+     *  an existentially bound variable, or a higher-order type parameter.
      */
     private def isLocal(sym: Symbol): Boolean =
-      !sym.isPackageClass &&
-      (sym.name.toTermName == rootName && sym.owner == rootOwner ||
-       sym != NoSymbol && isLocal(sym.owner) ||
+      !sym.isPackageClass && sym != NoSymbol &&
+      (isRootSym(sym) ||
        sym.isRefinementClass ||
-       sym.isAbstractType && sym.hasFlag(EXISTENTIAL))
+       sym.isAbstractType && sym.hasFlag(EXISTENTIAL) || // existential param
+       (sym hasFlag PARAM) || 
+       isLocal(sym.owner))
+
+    private def staticAnnotations(annots: List[AnnotationInfo]) =
+      annots filter(ann =>
+        ann.atp.typeSymbol isNonBottomSubClass definitions.StaticAnnotationClass)
 
     // Phase 1 methods: Populate entries/index ------------------------------------
 
@@ -105,7 +111,7 @@ abstract class Pickler extends SubComponent {
       case None =>
         if (ep == entries.length) {
           val entries1 = new Array[AnyRef](ep * 2)
-          Array.copy(entries, 0, entries1, 0, ep)
+          System.arraycopy(entries, 0, entries1, 0, ep)
           entries = entries1
         }
         entries(ep) = entry
@@ -138,12 +144,10 @@ abstract class Pickler extends SubComponent {
                 localChildDummy.setInfo(ClassInfoType(List(sym.tpe), EmptyScope, localChildDummy))
                 localChildDummy :: globals
               }
-            putChildren(sym, children.sort((x, y) => x isLess y))
-          }
-          for (attr <- sym.attributes.reverse) {
-            if (attr.atp.typeSymbol isNonBottomSubClass definitions.StaticAnnotationClass)
-              putAnnotation(sym, attr)
+            putChildren(sym, children sortBy (_.sealedSortName))
           }
+          for (annot <- staticAnnotations(sym.annotations.reverse))
+            putAnnotation(sym, annot)
         } else if (sym != NoSymbol) {
           putEntry(if (sym.isModuleClass) sym.name.toTermName else sym.name)
           if (!sym.owner.isRoot) putSymbol(sym.owner)
@@ -154,20 +158,23 @@ abstract class Pickler extends SubComponent {
     private def putSymbols(syms: List[Symbol]) =
       syms foreach putSymbol
 
-    /** Store type and everythig it refers to in map <code>index</code>.
+    /** Store type and everything it refers to in map <code>index</code>.
      *
      *  @param tp ...
      */
     private def putType(tp: Type): Unit = if (putEntry(tp)) {
       tp match {
-        case NoType | NoPrefix | DeBruijnIndex(_, _) =>
+        case NoType | NoPrefix /*| DeBruijnIndex(_, _) */ =>
           ;
         case ThisType(sym) =>
           putSymbol(sym)
         case SingleType(pre, sym) =>
           putType(pre); putSymbol(sym)
+        case SuperType(thistpe, supertpe) =>
+          putType(thistpe)
+          putType(supertpe)
         case ConstantType(value) =>
-	  putConstant(value)
+          putConstant(value)
         case TypeRef(pre, sym, args) =>
 //          if (sym.isAbstractType && (sym hasFlag EXISTENTIAL))
 //            if (!(boundSyms contains sym))
@@ -177,17 +184,22 @@ abstract class Pickler extends SubComponent {
           putType(lo); putType(hi)
         case RefinedType(parents, decls) =>
           val rclazz = tp.typeSymbol
-          for (m <- decls.elements)
+          for (m <- decls.iterator)
             if (m.owner != rclazz) assert(false, "bad refinement member "+m+" of "+tp+", owner = "+m.owner)
           putSymbol(rclazz); putTypes(parents); putSymbols(decls.toList)
         case ClassInfoType(parents, decls, clazz) =>
           putSymbol(clazz); putTypes(parents); putSymbols(decls.toList)
-        case MethodType(formals, restpe) =>
-          putType(restpe); putTypes(formals)
+        case MethodType(params, restpe) =>
+          putType(restpe); putSymbols(params)
         case PolyType(tparams, restpe) =>
+          /** no longer needed since all params are now local 
+          tparams foreach { tparam => 
+            if (!isLocal(tparam)) locals += tparam // similar to existential types, these tparams are local
+          }
+          */
           putType(restpe); putSymbols(tparams)
         case ExistentialType(tparams, restpe) =>
-//          val savedBoundSyms = boundSyms
+//          val savedBoundSyms = boundSyms // boundSyms are known to be local based on the EXISTENTIAL flag  (see isLocal)
 //          boundSyms = tparams ::: boundSyms
 //          try {
             putType(restpe); 
@@ -195,9 +207,10 @@ abstract class Pickler extends SubComponent {
 //            boundSyms = savedBoundSyms
 //          }
           putSymbols(tparams)
-        case AnnotatedType(attribs, tp, selfsym) =>
-          putType(tp); putAnnotations(attribs)
-	  if (settings.selfInAnnots.value) putSymbol(selfsym)
+        case AnnotatedType(annotations, underlying, selfsym) =>
+          putType(underlying)
+          if (settings.selfInAnnots.value) putSymbol(selfsym)
+          putAnnotations(staticAnnotations(annotations))
         case _ =>
           throw new FatalError("bad type: " + tp + "(" + tp.getClass + ")")
       }
@@ -206,264 +219,266 @@ abstract class Pickler extends SubComponent {
 
     private def putTree(tree: Tree): Unit = if (putEntry(tree)) {
       if (tree != EmptyTree)
-	putType(tree.tpe)
+        putType(tree.tpe)
       if (tree.hasSymbol)
-	putSymbol(tree.symbol)
+        putSymbol(tree.symbol)
 
       tree match {
-	case EmptyTree =>
+        case EmptyTree =>
 
-	case tree at PackageDef(name, stats) =>
-	  putEntry(name)
+        case tree at PackageDef(pid, stats) =>
+          putTree(pid)
           putTrees(stats)
 
-	case ClassDef(mods, name, tparams, impl) =>
-	  putMods(mods)
-	  putEntry(name)
+        case ClassDef(mods, name, tparams, impl) =>
+          putMods(mods)
+          putEntry(name)
           putTree(impl)
-	  putTrees(tparams)
-	  
-	case ModuleDef(mods, name, impl) =>
-	  putMods(mods)
-	  putEntry(name)
-	  putTree(impl)
-  
-	case ValDef(mods, name, tpt, rhs) =>
-	  putMods(mods)
-	  putEntry(name)
-	  putTree(tpt)
-	  putTree(rhs)
-	
-	case DefDef(mods, name, tparams, vparamss, tpt, rhs) =>
-	  putMods(mods)
-	  putEntry(name)
-	  putTrees(tparams)
-	  putTreess(vparamss)
-	  putTree(tpt)
-	  putTree(rhs)
-  
-
-	case TypeDef(mods, name, tparams, rhs) =>
-	  putMods(mods)
-	  putEntry(name)
-	  putTree(rhs)
-	  putTrees(tparams)
-
-
-	case LabelDef(name, params, rhs) =>
-	  putTree(rhs)
-	  putTrees(params)
-
-
-	case Import(expr, selectors) =>
-	  putTree(expr)
-	  for ((from,to) <- selectors) {
-	    putEntry(from)
-	    putEntry(to)
-	  }
-
-	case Annotation(constr, elements) =>                            
-	  putTree(constr)
-	  putTrees(elements)
-
-	case DocDef(comment, definition) =>
-	  putConstant(Constant(comment))
-	  putTree(definition)
-
-	case Template(parents, self, body) =>
+          putTrees(tparams)
+
+        case ModuleDef(mods, name, impl) =>
+          putMods(mods)
+          putEntry(name)
+          putTree(impl)
+
+        case ValDef(mods, name, tpt, rhs) =>
+          putMods(mods)
+          putEntry(name)
+          putTree(tpt)
+          putTree(rhs)
+
+        case DefDef(mods, name, tparams, vparamss, tpt, rhs) =>
+          putMods(mods)
+          putEntry(name)
+          putTrees(tparams)
+          putTreess(vparamss)
+          putTree(tpt)
+          putTree(rhs)
+
+        case TypeDef(mods, name, tparams, rhs) =>
+          putMods(mods)
+          putEntry(name)
+          putTree(rhs)
+          putTrees(tparams)
+
+        case LabelDef(name, params, rhs) =>
+          putEntry(name)
+          putTree(rhs)
+          putTrees(params)
+
+        case Import(expr, selectors) =>
+          putTree(expr)
+          for (ImportSelector(from, _, to, _) <- selectors) {
+            putEntry(from)
+            putEntry(to)
+          }
+/*
+        case DocDef(comment, definition) =>  should not be needed
+          putConstant(Constant(comment))
+          putTree(definition)
+*/
+        case Template(parents, self, body) =>
           writeNat(parents.length)
-	  putTrees(parents)
-	  putTree(self)
-	  putTrees(body)
+          putTrees(parents)
+          putTree(self)
+          putTrees(body)
+
+        case Block(stats, expr) =>
+          putTree(expr)
+          putTrees(stats)
 
-	case Block(stats, expr) =>
-	  putTree(expr)
-	  putTrees(stats)
+        case CaseDef(pat, guard, body) =>
+          putTree(pat)
+          putTree(guard)
+          putTree(body)
 
-	case CaseDef(pat, guard, body) =>
-	  putTree(pat)
-	  putTree(guard)
-	  putTree(body)
+        case Alternative(trees) =>
+          putTrees(trees)
 
-	case Sequence(trees) =>
-	  putTrees(trees)
+        case Star(elem) =>
+          putTree(elem)
 
-	case Alternative(trees) =>
-	  putTrees(trees)
+        case Bind(name, body) =>
+          putEntry(name)
+          putTree(body)
 
-	case Star(elem) =>
-	  putTree(elem)
+        case UnApply(fun: Tree, args) =>
+          putTree(fun)
+          putTrees(args)
 
-	case Bind(name, body) =>
-	  putEntry(name)
-	  putTree(body)
+        case ArrayValue(elemtpt, trees) =>
+          putTree(elemtpt)
+          putTrees(trees)
 
-	case UnApply(fun: Tree, args) =>
-	  putTree(fun)
-	  putTrees(args)
 
-	case ArrayValue(elemtpt, trees) =>
-	  putTree(elemtpt)
-	  putTrees(trees)
+        case Function(vparams, body) =>
+          putTree(body)
+          putTrees(vparams)
 
+        case Assign(lhs, rhs) =>
+          putTree(lhs)
+          putTree(rhs)
 
-	case Function(vparams, body) =>
-	  putTree(body)
-	  putTrees(vparams)
+        case If(cond, thenp, elsep) =>
+          putTree(cond)
+          putTree(thenp)
+          putTree(elsep)
 
-	case Assign(lhs, rhs) =>
-	  putTree(lhs)
-	  putTree(rhs)
+        case Match(selector, cases) =>
+          putTree(selector)
+          putTrees(cases)
 
-	case If(cond, thenp, elsep) =>
-	  putTree(cond)
-	  putTree(thenp)
-	  putTree(elsep)
+        case Return(expr) =>
+          putTree(expr)
 
-	case Match(selector, cases) =>
-	  putTree(selector)
-	  putTrees(cases)
+        case Try(block, catches, finalizer) =>
+          putTree(block)
+          putTree(finalizer)
+          putTrees(catches)
 
-	case Return(expr) =>
-	  putTree(expr)
+        case Throw(expr) =>
+          putTree(expr)
 
-	case Try(block, catches, finalizer) =>
-	  putTree(block)
-	  putTree(finalizer)
-	  putTrees(catches)
+        case New(tpt) =>
+          putTree(tpt)
 
-	case Throw(expr) =>
-	  putTree(expr)
+        case Typed(expr, tpt) =>
+          putTree(expr)
+          putTree(tpt)
 
-	case New(tpt) =>
-	  putTree(tpt)
-  
-	case Typed(expr, tpt) =>
-	  putTree(expr)
-	  putTree(tpt)
+        case TypeApply(fun, args) =>
+          putTree(fun)
+          putTrees(args)
 
-	case TypeApply(fun, args) =>
-	  putTree(fun)
-	  putTrees(args)
-	  
-	case Apply(fun, args) =>
-	  putTree(fun)
-	  putTrees(args)
+        case Apply(fun, args) =>
+          putTree(fun)
+          putTrees(args)
 
-	case ApplyDynamic(qual, args) =>
-	  writeEntry(qual)
-	  putTrees(args)
+        case ApplyDynamic(qual, args) =>
+          putTree(qual)
+          putTrees(args)
 
-	case Super(qual, mix) =>
-	  putEntry(qual:Name)
-	  putEntry(mix:Name)
+        case Super(qual, mix) =>
+          putEntry(qual:Name)
+          putEntry(mix:Name)
 
         case This(qual) =>
-	  putEntry(qual)
+          putEntry(qual)
 
         case Select(qualifier, selector) =>
-	  putTree(qualifier)
-	  putEntry(selector)
+          putTree(qualifier)
+          putEntry(selector)
 
-	case Ident(name) =>
-	  putEntry(name)
+        case Ident(name) =>
+          putEntry(name)
 
-	case Literal(value) =>
-	  putEntry(value)
+        case Literal(value) =>
+          putEntry(value)
 
-	case TypeTree() =>
+        case TypeTree() =>
 
-	case Annotated(annot, arg) =>
-	  putTree(annot)
-	  putTree(arg)
+        case Annotated(annot, arg) =>
+          putTree(annot)
+          putTree(arg)
 
-	case SingletonTypeTree(ref) =>
-	  putTree(ref)
+        case SingletonTypeTree(ref) =>
+          putTree(ref)
 
-	case SelectFromTypeTree(qualifier, selector) =>
-	  putTree(qualifier)
-	  putEntry(selector)
+        case SelectFromTypeTree(qualifier, selector) =>
+          putTree(qualifier)
+          putEntry(selector)
 
-	case CompoundTypeTree(templ: Template) =>
-	  putTree(templ)
+        case CompoundTypeTree(templ: Template) =>
+          putTree(templ)
 
-	case AppliedTypeTree(tpt, args) =>
-	  putTree(tpt)
-	  putTrees(args)
+        case AppliedTypeTree(tpt, args) =>
+          putTree(tpt)
+          putTrees(args)
 
-	case TypeBoundsTree(lo, hi) =>
-	  putTree(lo)
-	  putTree(hi)
+        case TypeBoundsTree(lo, hi) =>
+          putTree(lo)
+          putTree(hi)
 
-	case ExistentialTypeTree(tpt, whereClauses) =>
-	  putTree(tpt)
-	  putTrees(whereClauses)
+        case ExistentialTypeTree(tpt, whereClauses) =>
+          putTree(tpt)
+          putTrees(whereClauses)
       }
     }
 
-    private def putTrees(trees: List[Tree]) =
-      trees.foreach(putTree _)
-
-    private def putTreess(treess: List[List[Tree]]) =
-      treess.foreach(putTrees _)
+    private def putTrees(trees: List[Tree]) = trees foreach putTree
+    private def putTreess(treess: List[List[Tree]]) = treess foreach putTrees
 
+    /** only used when pickling trees, i.e. in an
+     *  argument of some Annotation */
     private def putMods(mods: Modifiers) = if (putEntry(mods)) {
-      val Modifiers(flags, privateWithin, annotations) = mods
+      // annotations in Modifiers are removed by the typechecker
+      val Modifiers(flags, privateWithin, Nil, _) = mods
       putEntry(privateWithin)
-      putTrees(annotations)
     }
 
     /** Store a constant in map <code>index</code> along with
      *  anything it references.
      */
-    private def putConstant(c: Constant) =
+    private def putConstant(c: Constant) {
       if (putEntry(c)) {
         if (c.tag == StringTag) putEntry(newTermName(c.stringValue))
         else if (c.tag == ClassTag) putType(c.typeValue)
+        else if (c.tag == EnumTag) putSymbol(c.symbolValue)
       }
+    }
 
     private def putChildren(sym: Symbol, children: List[Symbol]) {
       assert(putEntry((sym, children)))
       children foreach putSymbol
     }
 
+    /** used in putSymbol only, i.e. annotations on definitions, not on types */
     private def putAnnotation(sym: Symbol, annot: AnnotationInfo) {
       // if an annotation with the same arguments is applied to the
       // same symbol multiple times, it's only pickled once.
-      if (putEntry((sym, annot))) {
-        val AnnotationInfo(atp, args, assocs) = annot
-        putType(atp)
-        args foreach putAnnotationArg
-        for ((name, c) <- assocs) { putEntry(name); putAnnotationArg(c) }
-      }
+      if (putEntry((sym, annot)))
+        putAnnotationBody(annot)
     }
 
-    private def putAnnotation(annot: AnnotationInfo) {
-      if (putEntry(annot)) {
-        val AnnotationInfo(tpe, args, assocs) = annot
-        putType(tpe)
-        args foreach putAnnotationArg
-        for ((name, rhs) <- assocs) { putEntry(name); putAnnotationArg(rhs) }
-      }
+    /** used in AnnotatedType only, i.e. annotations on types */
+    private def putAnnotations(annots: List[AnnotationInfo]) {
+      annots foreach putAnnotation
     }
-    
-    private def putAnnotationArg(arg: AnnotationArgument) {
-      if (putEntry(arg)) {
-        arg.constant match {
-	  case Some(c) => putConstant(c)
-	  case _ => putTree(arg.intTree)
-	}
-      }
+    private def putAnnotation(annot: AnnotationInfo) {
+      if (putEntry(annot))
+        putAnnotationBody(annot)
     }
 
-    private def putAnnotations(annots: List[AnnotationInfo]) {
-      annots foreach putAnnotation
+    /** Puts the members of an AnnotationInfo */
+    private def putAnnotationBody(annot: AnnotationInfo) {
+      def putAnnotArg(arg: Tree) {
+        arg match {
+          case Literal(c) => putConstant(c)
+          case _ => putTree(arg)
+        }
+      }
+      def putClassfileAnnotArg(carg: ClassfileAnnotArg) {
+        carg match {
+          case LiteralAnnotArg(const) =>
+            putConstant(const)
+          case ArrayAnnotArg(args) =>
+            if (putEntry(carg))
+              args foreach putClassfileAnnotArg
+          case NestedAnnotArg(annInfo) =>
+            putAnnotation(annInfo)
+        }
+      }
+      val AnnotationInfo(tpe, args, assocs) = annot
+      putType(tpe)
+      args foreach putAnnotArg
+      assocs foreach { asc =>
+        putEntry(asc._1)
+        putClassfileAnnotArg(asc._2)
+      }
     }
 
     // Phase 2 methods: Write all entries to byte array ------------------------------
 
-    private val buf = new PickleBuffer(new Array[Byte](4096), -1, 0)
-
     /** Write a reference to object, i.e., the object's number in the map
      *  <code>index</code>.
      *
@@ -471,28 +486,56 @@ abstract class Pickler extends SubComponent {
      */
     private def writeRef(ref: AnyRef) { writeNat(index(ref)) }
     private def writeRefs(refs: List[AnyRef]) { refs foreach writeRef }
+    private def writeRefsWithLength(refs: List[AnyRef]) { 
+      writeNat(refs.length)
+      writeRefs(refs)
+    }
 
     /** Write name, owner, flags, and info of a symbol.
-     *
-     *  @param sym ...
-     *  @return    the position offset
      */
-    private def writeSymInfo(sym: Symbol): Int = {
-      var posOffset = 0
+    private def writeSymInfo(sym: Symbol) {
       writeRef(sym.name)
       writeRef(localizedOwner(sym))
-      writeNat((sym.flags & PickledFlags).asInstanceOf[Int])
+      writeLongNat((rawFlagsToPickled(sym.flags & PickledFlags)))
       if (sym.privateWithin != NoSymbol) writeRef(sym.privateWithin)
       writeRef(sym.info)
-      posOffset
     }
 
     /** Write a name in UTF8 format. */
-    def writeName(name: Name) {
+    private def writeName(name: Name) {
       ensureCapacity(name.length * 3)
       writeIndex = name.copyUTF8(bytes, writeIndex)
     }
 
+    /** Write an annotation */
+    private def writeAnnotation(annot: AnnotationInfo) {
+      def writeAnnotArg(arg: Tree) {
+        arg match {
+          case Literal(c) => writeRef(c)
+          case _ => writeRef(arg)
+        }
+      }
+
+      writeRef(annot.atp)
+      annot.args foreach writeAnnotArg
+      annot.assocs foreach { asc =>
+        writeRef(asc._1)
+        writeClassfileAnnotArg(asc._2)
+      }
+    }
+
+    /** Write a ClassfileAnnotArg (argument to classfile annotation) */
+    def writeClassfileAnnotArg(carg: ClassfileAnnotArg) {
+      carg match {
+        case LiteralAnnotArg(const) =>
+          writeRef(const)
+        case ArrayAnnotArg(args) =>
+          writeRef(carg)
+        case NestedAnnotArg(annInfo) =>
+          writeRef(annInfo)
+      }
+    }
+
     /** Write an entry */
     private def writeEntry(entry: AnyRef) {
       def writeBody(entry: AnyRef): Int = entry match {
@@ -511,16 +554,16 @@ abstract class Pickler extends SubComponent {
           if (!sym.owner.isRoot) writeRef(sym.owner)
           tag
         case sym: ClassSymbol =>
-          val posOffset = writeSymInfo(sym)
+          writeSymInfo(sym)
           if (sym.thisSym.tpe != sym.tpe) writeRef(sym.typeOfThis)
-          CLASSsym + posOffset
+          CLASSsym
         case sym: TypeSymbol =>
-          val posOffset = writeSymInfo(sym)
-          (if (sym.isAbstractType) TYPEsym else ALIASsym) + posOffset
+          writeSymInfo(sym)
+          if (sym.isAbstractType) TYPEsym else ALIASsym
         case sym: TermSymbol =>
-          val posOffset = writeSymInfo(sym)
+          writeSymInfo(sym)
           if (sym.alias != NoSymbol) writeRef(sym.alias)
-          (if (sym.isModule) MODULEsym else VALsym) + posOffset
+          if (sym.isModule) MODULEsym else VALsym
         case NoType =>
           NOtpe
         case NoPrefix =>
@@ -529,6 +572,8 @@ abstract class Pickler extends SubComponent {
           writeRef(sym); THIStpe
         case SingleType(pre, sym) =>
           writeRef(pre); writeRef(sym); SINGLEtpe
+        case SuperType(thistpe, supertpe) =>
+          writeRef(thistpe); writeRef(supertpe); SUPERtpe
         case ConstantType(value) =>
           writeRef(value); CONSTANTtpe
         case TypeRef(pre, sym, args) =>
@@ -539,16 +584,16 @@ abstract class Pickler extends SubComponent {
           writeRef(tp.typeSymbol); writeRefs(parents); REFINEDtpe
         case ClassInfoType(parents, decls, clazz) =>
           writeRef(clazz); writeRefs(parents); CLASSINFOtpe
-        case MethodType(formals, restpe) =>
+        case mt @ MethodType(formals, restpe) =>
           writeRef(restpe); writeRefs(formals)
-          if (entry.isInstanceOf[ImplicitMethodType]) IMPLICITMETHODtpe
+          if (mt.isImplicit) IMPLICITMETHODtpe
           else METHODtpe
         case PolyType(tparams, restpe) =>
           writeRef(restpe); writeRefs(tparams); POLYtpe
         case ExistentialType(tparams, restpe) =>
           writeRef(restpe); writeRefs(tparams); EXISTENTIALtpe
-        case DeBruijnIndex(l, i) =>
-          writeNat(l); writeNat(i); DEBRUIJNINDEXtpe
+        // case DeBruijnIndex(l, i) =>
+        //   writeNat(l); writeNat(i); DEBRUIJNINDEXtpe
         case c @ Constant(_) =>
           if (c.tag == BooleanTag) writeLong(if (c.booleanValue) 1 else 0)
           else if (ByteTag <= c.tag && c.tag <= LongTag) writeLong(c.longValue)
@@ -556,399 +601,370 @@ abstract class Pickler extends SubComponent {
           else if (c.tag == DoubleTag) writeLong(Double.doubleToLongBits(c.doubleValue))
           else if (c.tag == StringTag) writeRef(newTermName(c.stringValue))
           else if (c.tag == ClassTag) writeRef(c.typeValue)
-          LITERAL + c.tag
-        case AnnotatedType(attribs, tp, selfsym) => 
-	  if (settings.selfInAnnots.value) {
-	    writeRef(tp)
-	    writeRef(selfsym)
-	    writeRefs(attribs)
-	    ANNOTATEDWSELFtpe
-	  } else {
+          else if (c.tag == EnumTag) writeRef(c.symbolValue)
+          LITERAL + c.tag // also treats UnitTag, NullTag; no value required
+        case AnnotatedType(annotations, tp, selfsym) =>
+          val staticAnnots = staticAnnotations(annotations)
+          if (staticAnnots isEmpty) {
+            writeBody(tp) // write the underlying type if there are no annotations
+          } else {
+            if (settings.selfInAnnots.value && selfsym != NoSymbol)
+              writeRef(selfsym)
             writeRef(tp)
-            writeRefs(attribs)
+            writeRefs(staticAnnots)
             ANNOTATEDtpe
-	  }
-        case (target: Symbol, attr @ AnnotationInfo(atp, args, assocs)) =>
+          }
+
+        // annotations attached to a symbol (i.e. annots on terms)
+        case (target: Symbol, annot at AnnotationInfo(_, _, _)) =>
           writeRef(target)
-          writeRef(atp)
-          for (c <- args) writeRef(c)
-          for ((name, c) <- assocs) { writeRef(name); writeRef(c) }
-          ATTRIBUTE
+          writeAnnotation(annot)
+          SYMANNOT
+
+        case ArrayAnnotArg(args) =>
+          args foreach writeClassfileAnnotArg
+          ANNOTARGARRAY
+
         case (target: Symbol, children: List[_]) =>
           writeRef(target)
-          for (c <- children) writeRef(c.asInstanceOf[Symbol])
+          writeRefs(children.asInstanceOf[List[Symbol]])
           CHILDREN
 
-	case EmptyTree =>
-	  writeNat(EMPTYtree)
-	  TREE
+        case EmptyTree =>
+          writeNat(EMPTYtree)
+          TREE
 
-	case tree at PackageDef(name, stats) =>
-	  writeNat(PACKAGEtree)
-	  writeRef(tree.tpe)
-	  writeRef(tree.symbol)
-	  writeRef(tree.mods)
-	  writeRef(name)
+        case tree at PackageDef(pid, stats) =>
+          writeNat(PACKAGEtree)
+          writeRef(tree.tpe)
+          writeRef(tree.symbol)
+          writeRef(tree.mods)
+          writeRef(pid)
           writeRefs(stats)
-	  TREE
-
-	case tree at ClassDef(mods, name, tparams, impl) =>
-	  writeNat(CLASStree)
-	  writeRef(tree.tpe)
-	  writeRef(tree.symbol)
-	  writeRef(mods)
-	  writeRef(name)
+          TREE
+
+        case tree at ClassDef(mods, name, tparams, impl) =>
+          writeNat(CLASStree)
+          writeRef(tree.tpe)
+          writeRef(tree.symbol)
+          writeRef(mods)
+          writeRef(name)
           writeRef(impl)
-	  writeRefs(tparams)
-	  TREE
-	  
-	case tree at ModuleDef(mods, name, impl) =>
-	  writeNat(MODULEtree)
-	  writeRef(tree.tpe)
-	  writeRef(tree.symbol)
-	  writeRef(mods)
-	  writeRef(name)
-	  writeRef(impl)
-	  TREE
-  
-	case tree at ValDef(mods, name, tpt, rhs) =>
+          writeRefs(tparams)
+          TREE
+
+        case tree at ModuleDef(mods, name, impl) =>
+          writeNat(MODULEtree)
+          writeRef(tree.tpe)
+          writeRef(tree.symbol)
+          writeRef(mods)
+          writeRef(name)
+          writeRef(impl)
+          TREE
+
+        case tree at ValDef(mods, name, tpt, rhs) =>
           writeNat(VALDEFtree)
-	  writeRef(tree.tpe)
-	  writeRef(tree.symbol)
-	  writeRef(mods)
-	  writeRef(name)
-	  writeRef(tpt)
-	  writeRef(rhs)
-	  TREE
-
-	
-	case tree at DefDef(mods, name, tparams, vparamss, tpt, rhs) =>
+          writeRef(tree.tpe)
+          writeRef(tree.symbol)
+          writeRef(mods)
+          writeRef(name)
+          writeRef(tpt)
+          writeRef(rhs)
+          TREE
+
+        case tree at DefDef(mods, name, tparams, vparamss, tpt, rhs) =>
           writeNat(DEFDEFtree)
-	  writeRef(tree.tpe)
-	  writeRef(tree.symbol)
-	  writeRef(mods)
-	  writeRef(name)
-	  writeNat(tparams.length)
-	  writeRefs(tparams)
-	  writeNat(vparamss.length)
-	  for(vparams <- vparamss) {
-	    writeNat(vparams.length)
-	    writeRefs(vparams)
-	  }
-	  writeRef(tpt)
-	  writeRef(rhs)
-	  TREE
-  
-
-	case tree at TypeDef(mods, name, tparams, rhs) =>
-	  writeNat(TYPEDEFtree)
-	  writeRef(tree.tpe)
-	  writeRef(tree.symbol)
-	  writeRef(mods)
-	  writeRef(name)
-	  writeRef(rhs)
-	  writeRefs(tparams)
-	  TREE
-
-
-	case tree at LabelDef(name, params, rhs) =>
-	  writeNat(LABELtree)
-	  writeRef(tree.tpe)
-	  writeRef(tree.symbol)
-	  writeRef(rhs)
-	  writeRefs(params)
-	  TREE
-
-
-	case tree at Import(expr, selectors) =>
-	  writeNat(IMPORTtree)
-	  writeRef(tree.tpe)
-	  writeRef(tree.symbol)
-	  writeRef(expr)
-	  for ((from, to) <- selectors) {
-	    writeRef(from)
-	    writeRef(to)
-	  }
-	  TREE
-
-
-	case tree at Annotation(constr, elements) =>                            
-	  writeNat(ANNOTATIONtree)
-	  writeRef(tree.tpe)
-	  writeRef(constr)
-	  writeRefs(elements)
-	  TREE
-
-	case tree at DocDef(comment, definition) =>
+          writeRef(tree.tpe)
+          writeRef(tree.symbol)
+          writeRef(mods)
+          writeRef(name)
+          writeRefsWithLength(tparams)
+          writeNat(vparamss.length)
+          vparamss foreach writeRefsWithLength
+          writeRef(tpt)
+          writeRef(rhs)
+          TREE
+
+        case tree at TypeDef(mods, name, tparams, rhs) =>
+          writeNat(TYPEDEFtree)
+          writeRef(tree.tpe)
+          writeRef(tree.symbol)
+          writeRef(mods)
+          writeRef(name)
+          writeRef(rhs)
+          writeRefs(tparams)
+          TREE
+
+        case tree at LabelDef(name, params, rhs) =>
+          writeNat(LABELtree)
+          writeRef(tree.tpe)
+          writeRef(tree.symbol)
+          writeRef(name)
+          writeRef(rhs)
+          writeRefs(params)
+          TREE
+
+        case tree at Import(expr, selectors) =>
+          writeNat(IMPORTtree)
+          writeRef(tree.tpe)
+          writeRef(tree.symbol)
+          writeRef(expr)
+          for (ImportSelector(from, _, to, _) <- selectors) {
+            writeRef(from)
+            writeRef(to)
+          }
+          TREE
+
+        case tree at DocDef(comment, definition) =>
           writeNat(DOCDEFtree)
-	  writeRef(tree.tpe)
-	  writeRef(Constant(comment))
-	  writeRef(definition)
-	  TREE
+          writeRef(tree.tpe)
+          writeRef(Constant(comment))
+          writeRef(definition)
+          TREE
 
-	case tree at Template(parents, self, body) =>
+        case tree at Template(parents, self, body) =>
           writeNat(TEMPLATEtree)
-	  writeRef(tree.tpe)
+          writeRef(tree.tpe)
           writeRef(tree.symbol)
-          writeNat(parents.length)
-	  writeRefs(parents)
-	  writeRef(self)
-	  writeRefs(body)
-	  TREE
+          writeRefsWithLength(parents)
+          writeRef(self)
+          writeRefs(body)
+          TREE
 
-	case tree at Block(stats, expr) =>
+        case tree at Block(stats, expr) =>
           writeNat(BLOCKtree)
-	  writeRef(tree.tpe)
-	  writeRef(expr)
-	  writeRefs(stats)
-	  TREE
-
-	case tree at CaseDef(pat, guard, body) =>
-	  writeNat(CASEtree)
-	  writeRef(tree.tpe)
-	  writeRef(pat)
-	  writeRef(guard)
-	  writeRef(body)
-	  TREE
-
-	case tree at Sequence(trees) =>
-          writeNat(SEQUENCEtree)
-	  writeRef(tree.tpe)
-	  writeRefs(trees)
-	  TREE
-
-	case tree at Alternative(trees) =>
-	  writeNat(ALTERNATIVEtree)
-	  writeRef(tree.tpe)
-	  writeRefs(trees)
-	  TREE
-
-	case tree at Star(elem) =>
+          writeRef(tree.tpe)
+          writeRef(expr)
+          writeRefs(stats)
+          TREE
+
+        case tree at CaseDef(pat, guard, body) =>
+          writeNat(CASEtree)
+          writeRef(tree.tpe)
+          writeRef(pat)
+          writeRef(guard)
+          writeRef(body)
+          TREE
+
+        case tree at Alternative(trees) =>
+          writeNat(ALTERNATIVEtree)
+          writeRef(tree.tpe)
+          writeRefs(trees)
+          TREE
+
+        case tree at Star(elem) =>
           writeNat(STARtree)
-	  writeRef(tree.tpe)
-	  writeRef(elem)
-	  TREE
-
-	case tree at Bind(name, body) =>
-	  writeNat(BINDtree)
-	  writeRef(tree.tpe)
-	  writeRef(tree.symbol)
-	  writeRef(name)
-	  writeRef(body)
-	  TREE
-
-	case tree at UnApply(fun: Tree, args) =>
-	  writeNat(UNAPPLYtree)
-	  writeRef(tree.tpe)
-	  writeRef(fun)
-	  writeRefs(args)
-	  TREE
-
-	case tree at ArrayValue(elemtpt, trees) =>
-	  writeNat(ARRAYVALUEtree)
-	  writeRef(tree.tpe)
-	  writeRef(elemtpt)
-	  writeRefs(trees)
-	  TREE
-
-
-	case tree at Function(vparams, body) =>
+          writeRef(tree.tpe)
+          writeRef(elem)
+          TREE
+
+        case tree at Bind(name, body) =>
+          writeNat(BINDtree)
+          writeRef(tree.tpe)
+          writeRef(tree.symbol)
+          writeRef(name)
+          writeRef(body)
+          TREE
+
+        case tree at UnApply(fun: Tree, args) =>
+          writeNat(UNAPPLYtree)
+          writeRef(tree.tpe)
+          writeRef(fun)
+          writeRefs(args)
+          TREE
+
+        case tree at ArrayValue(elemtpt, trees) =>
+          writeNat(ARRAYVALUEtree)
+          writeRef(tree.tpe)
+          writeRef(elemtpt)
+          writeRefs(trees)
+          TREE
+
+        case tree at Function(vparams, body) =>
           writeNat(FUNCTIONtree)
-	  writeRef(tree.tpe)
-	  writeRef(tree.symbol)
-	  writeRef(body)
-	  writeRefs(vparams)
-	  TREE
+          writeRef(tree.tpe)
+          writeRef(tree.symbol)
+          writeRef(body)
+          writeRefs(vparams)
+          TREE
 
-	case tree at Assign(lhs, rhs) =>
+        case tree at Assign(lhs, rhs) =>
           writeNat(ASSIGNtree)
-	  writeRef(tree.tpe)
-	  writeRef(lhs)
-	  writeRef(rhs)
-	  TREE
+          writeRef(tree.tpe)
+          writeRef(lhs)
+          writeRef(rhs)
+          TREE
 
-	case tree at If(cond, thenp, elsep) =>
+        case tree at If(cond, thenp, elsep) =>
           writeNat(IFtree)
           writeRef(tree.tpe)
-	  writeRef(cond)
-	  writeRef(thenp)
-	  writeRef(elsep)
-	  TREE
+          writeRef(cond)
+          writeRef(thenp)
+          writeRef(elsep)
+          TREE
 
-	case tree at Match(selector, cases) =>
+        case tree at Match(selector, cases) =>
           writeNat(MATCHtree)
-	  writeRef(tree.tpe)
-	  writeRef(selector)
-	  writeRefs(cases)
-	  TREE
-
-	case tree at Return(expr) =>
-	  writeNat(RETURNtree)
-	  writeRef(tree.tpe)
-	  writeRef(tree.symbol)
-	  writeRef(expr)
-	  TREE
-
-	case tree at Try(block, catches, finalizer) =>
+          writeRef(tree.tpe)
+          writeRef(selector)
+          writeRefs(cases)
+          TREE
+
+        case tree at Return(expr) =>
+          writeNat(RETURNtree)
+          writeRef(tree.tpe)
+          writeRef(tree.symbol)
+          writeRef(expr)
+          TREE
+
+        case tree at Try(block, catches, finalizer) =>
           writeNat(TREtree)
-	  writeRef(tree.tpe)
-	  writeRef(block)
-	  writeRef(finalizer)
-	  writeRefs(catches)
-	  TREE
-
-	case tree at Throw(expr) =>
-	  writeNat(THROWtree)
-	  writeRef(tree.tpe)
-	  writeRef(expr)
-	  TREE
-
-	case tree at New(tpt) =>
-	  writeNat(NEWtree)
-	  writeRef(tree.tpe)
-	  writeRef(tpt)
-	  TREE
-  
-	case tree at Typed(expr, tpt) =>
-	  writeNat(TYPEDtree)
-	  writeRef(tree.tpe)
-	  writeRef(expr)
-	  writeRef(tpt)
-	  TREE
-
-	case tree at TypeApply(fun, args) =>
-	  writeNat(TYPEAPPLYtree)
-	  writeRef(tree.tpe)
-	  writeRef(fun)
-	  writeRefs(args)
-	  TREE
-	  
-	case tree at Apply(fun, args) =>
-	  writeNat(APPLYtree)
-	  writeRef(tree.tpe)
-	  writeRef(fun)
-	  writeRefs(args)
-	  TREE
-
-	case tree at ApplyDynamic(qual, args) =>
-	  writeNat(APPLYDYNAMICtree)
-	  writeRef(tree.tpe)
-	  writeRef(tree.symbol)
-	  writeRef(qual)
-	  writeRefs(args)
-	  TREE
-
-	case tree at Super(qual, mix) =>
-	  writeNat(SUPERtree)
-	  writeRef(tree.tpe)
-	  writeRef(tree.symbol)
-	  writeRef(qual)
-	  writeRef(mix)
-	  TREE
+          writeRef(tree.tpe)
+          writeRef(block)
+          writeRef(finalizer)
+          writeRefs(catches)
+          TREE
+
+        case tree at Throw(expr) =>
+          writeNat(THROWtree)
+          writeRef(tree.tpe)
+          writeRef(expr)
+          TREE
+
+        case tree at New(tpt) =>
+          writeNat(NEWtree)
+          writeRef(tree.tpe)
+          writeRef(tpt)
+          TREE
+
+        case tree at Typed(expr, tpt) =>
+          writeNat(TYPEDtree)
+          writeRef(tree.tpe)
+          writeRef(expr)
+          writeRef(tpt)
+          TREE
+
+        case tree at TypeApply(fun, args) =>
+          writeNat(TYPEAPPLYtree)
+          writeRef(tree.tpe)
+          writeRef(fun)
+          writeRefs(args)
+          TREE
+
+        case tree at Apply(fun, args) =>
+          writeNat(APPLYtree)
+          writeRef(tree.tpe)
+          writeRef(fun)
+          writeRefs(args)
+          TREE
+
+        case tree at ApplyDynamic(qual, args) =>
+          writeNat(APPLYDYNAMICtree)
+          writeRef(tree.tpe)
+          writeRef(tree.symbol)
+          writeRef(qual)
+          writeRefs(args)
+          TREE
+
+        case tree at Super(qual, mix) =>
+          writeNat(SUPERtree)
+          writeRef(tree.tpe)
+          writeRef(tree.symbol)
+          writeRef(qual)
+          writeRef(mix)
+          TREE
 
         case tree at This(qual) =>
-	  writeNat(THIStree)
-	  writeRef(tree.tpe)
-	  writeRef(tree.symbol)
-	  writeRef(qual)
-	  TREE
+          writeNat(THIStree)
+          writeRef(tree.tpe)
+          writeRef(tree.symbol)
+          writeRef(qual)
+          TREE
 
         case tree at Select(qualifier, selector) =>
-	  writeNat(SELECTtree)
-	  writeRef(tree.tpe)
-	  writeRef(tree.symbol)
-	  writeRef(qualifier)
-	  writeRef(selector)
-	  TREE
-
-	case tree at Ident(name) =>
-	  writeNat(IDENTtree)
-	  writeRef(tree.tpe)
-	  writeRef(tree.symbol)
-	  writeRef(name)
-	  TREE
-
-	case tree at Literal(value) =>
-	  writeNat(LITERALtree)
-	  writeRef(tree.tpe)
-	  writeRef(value)
-	  TREE
-
-	case tree at TypeTree() =>
-	  writeNat(TYPEtree)
-	  writeRef(tree.tpe)
-	  TREE
-
-	case tree at Annotated(annot, arg) =>
-	  writeNat(ANNOTATEDtree)
-	  writeRef(tree.tpe)
-	  writeRef(annot)
-	  writeRef(arg)
-	  TREE
-
-	case tree at SingletonTypeTree(ref) =>
-	  writeNat(SINGLETONTYPEtree)
-	  writeRef(tree.tpe)
-	  writeRef(ref)
-	  TREE
-
-	case tree at SelectFromTypeTree(qualifier, selector) =>
-	  writeNat(SELECTFROMTYPEtree)
-	  writeRef(tree.tpe)
-	  writeRef(qualifier)
-	  writeRef(selector)
-	  TREE
-
-	case tree at CompoundTypeTree(templ: Template) =>
-	  writeNat(COMPOUNDTYPEtree)
-	  writeRef(tree.tpe)
-	  writeRef(templ)
-	  TREE
-
-	case tree at AppliedTypeTree(tpt, args) =>
-	  writeNat(APPLIEDTYPEtree)
-	  writeRef(tree.tpe)
-	  writeRef(tpt)
-	  writeRefs(args)
-	  TREE
-
-	case tree at TypeBoundsTree(lo, hi) =>
-	  writeNat(TYPEBOUNDStree)
-	  writeRef(tree.tpe)
-	  writeRef(lo)
-	  writeRef(hi)
-	  TREE
-
-	case tree at ExistentialTypeTree(tpt, whereClauses) =>
-	  writeNat(EXISTENTIALTYPEtree)
-	  writeRef(tree.tpe)
-	  writeRef(tpt)
-	  writeRefs(whereClauses)
-	  TREE
-
-
-	case Modifiers(flags, privateWithin, annotations) =>
-	  writeNat((flags >> 32).toInt)
-	  writeNat((flags & 0xFFFFFFFF).toInt)
-	  writeRef(privateWithin)
-          writeRefs(annotations)
-	  MODIFIERS
-
-        case AnnotationInfo(atp, args, assocs) =>
-          writeRef(atp)
-          writeNat(args.length)
-          for (arg <- args) writeRef(arg)
-          for ((name, arg) <- assocs) {
-            writeRef(name);
-            writeRef(arg)
-          }
-          ANNOTINFO
+          writeNat(SELECTtree)
+          writeRef(tree.tpe)
+          writeRef(tree.symbol)
+          writeRef(qualifier)
+          writeRef(selector)
+          TREE
 
-	case arg:AnnotationArgument =>
-	  arg.constant match {
-	    case Some(c) => writeBody(c)
-	    case None => writeBody(arg.intTree)
-	  }
+        case tree at Ident(name) =>
+          writeNat(IDENTtree)
+          writeRef(tree.tpe)
+          writeRef(tree.symbol)
+          writeRef(name)
+          TREE
+
+        case tree at Literal(value) =>
+          writeNat(LITERALtree)
+          writeRef(tree.tpe)
+          writeRef(value)
+          TREE
+
+        case tree at TypeTree() =>
+          writeNat(TYPEtree)
+          writeRef(tree.tpe)
+          TREE
+
+        case tree at Annotated(annot, arg) =>
+          writeNat(ANNOTATEDtree)
+          writeRef(tree.tpe)
+          writeRef(annot)
+          writeRef(arg)
+          TREE
+
+        case tree at SingletonTypeTree(ref) =>
+          writeNat(SINGLETONTYPEtree)
+          writeRef(tree.tpe)
+          writeRef(ref)
+          TREE
+
+        case tree at SelectFromTypeTree(qualifier, selector) =>
+          writeNat(SELECTFROMTYPEtree)
+          writeRef(tree.tpe)
+          writeRef(qualifier)
+          writeRef(selector)
+          TREE
+
+        case tree at CompoundTypeTree(templ: Template) =>
+          writeNat(COMPOUNDTYPEtree)
+          writeRef(tree.tpe)
+          writeRef(templ)
+          TREE
+
+        case tree at AppliedTypeTree(tpt, args) =>
+          writeNat(APPLIEDTYPEtree)
+          writeRef(tree.tpe)
+          writeRef(tpt)
+          writeRefs(args)
+          TREE
+
+        case tree at TypeBoundsTree(lo, hi) =>
+          writeNat(TYPEBOUNDStree)
+          writeRef(tree.tpe)
+          writeRef(lo)
+          writeRef(hi)
+          TREE
+
+        case tree at ExistentialTypeTree(tpt, whereClauses) =>
+          writeNat(EXISTENTIALTYPEtree)
+          writeRef(tree.tpe)
+          writeRef(tpt)
+          writeRefs(whereClauses)
+          TREE
+
+        case Modifiers(flags, privateWithin, _, _) =>
+          val pflags = rawFlagsToPickled(flags)
+          writeNat((pflags >> 32).toInt)
+          writeNat((pflags & 0xFFFFFFFF).toInt)
+          writeRef(privateWithin)
+          MODIFIERS
+
+        // annotations on types (not linked to a symbol)
+        case annot at AnnotationInfo(_, _, _) =>
+          writeAnnotation(annot)
+          ANNOTINFO
 
         case _ =>
           throw new FatalError("bad entry: " + entry + " " + entry.getClass)
@@ -956,6 +972,7 @@ abstract class Pickler extends SubComponent {
 
       // begin writeEntry
       val startpos = writeIndex
+      // reserve some space so that the patchNat's most likely won't need to shift
       writeByte(0); writeByte(0)
       patchNat(startpos, writeBody(entry))
       patchNat(startpos + 1, writeIndex - (startpos + 2))
@@ -1017,15 +1034,16 @@ abstract class Pickler extends SubComponent {
           print("REFINEDtpe "); printRef(tp.typeSymbol); printRefs(parents); 
         case ClassInfoType(parents, decls, clazz) =>
           print("CLASSINFOtpe "); printRef(clazz); printRefs(parents); 
-        case MethodType(formals, restpe) =>
-          print(if (entry.isInstanceOf[ImplicitMethodType]) "IMPLICITMETHODtpe " else "METHODtpe ");
+        case mt @ MethodType(formals, restpe) =>
+          print(if (mt.isImplicit) "IMPLICITMETHODtpe " else "METHODtpe ");
           printRef(restpe); printRefs(formals)
         case PolyType(tparams, restpe) =>
           print("POLYtpe "); printRef(restpe); printRefs(tparams); 
         case ExistentialType(tparams, restpe) =>
           print("EXISTENTIALtpe "); printRef(restpe); printRefs(tparams); 
-        case DeBruijnIndex(l, i) =>
-          print("DEBRUIJNINDEXtpe "); print(l+" "+i)
+          print("||| "+entry)
+        // case DeBruijnIndex(l, i) =>
+        //   print("DEBRUIJNINDEXtpe "); print(l+" "+i)
         case c @ Constant(_) =>
           print("LITERAL ")
           if (c.tag == BooleanTag) print("Boolean "+(if (c.booleanValue) 1 else 0))
@@ -1038,27 +1056,31 @@ abstract class Pickler extends SubComponent {
           else if (c.tag == DoubleTag) print("Double "+c.doubleValue)
           else if (c.tag == StringTag) { print("String "); printRef(newTermName(c.stringValue)) }
           else if (c.tag == ClassTag) { print("Class "); printRef(c.typeValue) }
-        case AnnotatedType(attribs, tp, selfsym) => 
-	  if (settings.selfInAnnots.value) {
+          else if (c.tag == EnumTag) { print("Enum "); printRef(c.symbolValue) }
+        case AnnotatedType(annots, tp, selfsym) => 
+          if (settings.selfInAnnots.value) {
             print("ANNOTATEDWSELFtpe ")
-	    printRef(tp)
-	    printRef(selfsym)
-	    printRefs(attribs)
-	  } else {
+            printRef(tp)
+            printRef(selfsym)
+            printRefs(annots)
+          } else {
             print("ANNOTATEDtpe ")
             printRef(tp)
-            printRefs(attribs)
-	  }
-        case (target: Symbol, attr @ AnnotationInfo(atp, args, assocs)) =>
-          print("ATTRIBUTE ")
+            printRefs(annots)
+          }
+        case (target: Symbol, AnnotationInfo(atp, args, Nil)) =>
+          print("SYMANNOT ")
           printRef(target)
           printRef(atp)
           for (c <- args) printRef(c)
-          for ((name, c) <- assocs) { printRef(name); printRef(c) }
         case (target: Symbol, children: List[_]) =>
           print("CHILDREN ")
           printRef(target)
           for (c <- children) printRef(c.asInstanceOf[Symbol])
+        case AnnotationInfo(atp, args, Nil) =>
+          print("ANNOTINFO")
+          printRef(atp)
+          for (c <- args) printRef(c)
         case _ =>
           throw new FatalError("bad entry: " + entry + " " + entry.getClass)
       }
@@ -1075,7 +1097,7 @@ abstract class Pickler extends SubComponent {
         println("Pickled info for "+rootName+" V"+MajorVersion+"."+MinorVersion)
       }
       for (i <- 0 until ep) {
-        if (showSig) {
+        if (showSig/* || rootName.toString == "StaticCompletion"*/) {
           print((i formatted "%3d: ")+(writeIndex formatted "%5d: "))
           printEntry(entries(i))
         }
diff --git a/src/compiler/scala/tools/nsc/symtab/classfile/UnPickler.scala b/src/compiler/scala/tools/nsc/symtab/classfile/UnPickler.scala
index 7446f14..2a2847f 100644
--- a/src/compiler/scala/tools/nsc/symtab/classfile/UnPickler.scala
+++ b/src/compiler/scala/tools/nsc/symtab/classfile/UnPickler.scala
@@ -1,794 +1,80 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: UnPickler.scala 16881 2009-01-09 16:28:11Z cunei $
 
-package scala.tools.nsc.symtab.classfile
+package scala.tools.nsc
+package symtab
+package classfile
 
 import java.io.IOException
 import java.lang.{Float, Double}
 
-import scala.tools.nsc.util.{Position, NoPosition}
-import scala.tools.util.UTF8Codec
-
 import Flags._
-import PickleFormat._
+import scala.reflect.generic.PickleFormat._
 import collection.mutable.{HashMap, ListBuffer}
+import annotation.switch
 
-/** This abstract class implements ..
- *
- *  @author Martin Odersky
+/** @author Martin Odersky
  *  @version 1.0
  */
-abstract class UnPickler {
+abstract class UnPickler extends reflect.generic.UnPickler {
   val global: Global
   import global._
 
-  /** Unpickle symbol table information descending from a class and/or module root
-   *  from an array of bytes.
-   *  @param bytes      bytearray from which we unpickle
-   *  @param offset     offset from which unpickling starts
-   *  @param classroot  the top-level class which is unpickled, or NoSymbol if unapplicable
-   *  @param moduleroot the top-level module which is unpickled, or NoSymbol if unapplicable
-   *  @param filename   filename associated with bytearray, only used for error messages
-   */
-  def unpickle(bytes: Array[Byte], offset: Int, classRoot: Symbol, moduleRoot: Symbol, filename: String) {
-    try {
-      new UnPickle(bytes, offset, classRoot, moduleRoot)
-    } catch {
-      case ex: IOException =>
-        throw ex
-      case ex: Throwable =>
-        if (settings.debug.value) ex.printStackTrace()
-        throw new RuntimeException("error reading Scala signature of "+filename+": "+ex.getMessage())
-    }
-  }
-
-  private class UnPickle(bytes: Array[Byte], offset: Int, classRoot: Symbol, moduleRoot: Symbol) extends PickleBuffer(bytes, offset, -1) {
-    if (settings.debug.value) global.log("unpickle " + classRoot + " and " + moduleRoot)
-    checkVersion()
-
-    /** A map from entry numbers to array offsets */
-    private val index = createIndex
-    
-    /** A map from entry numbers to symbols, types, or annotations */
-    private val entries = new Array[AnyRef](index.length)
-    
-    /** A map from symbols to their associated `decls' scopes */
-    private val symScopes = new HashMap[Symbol, Scope]
-
-    for (i <- 0 until index.length) {
-      if (isSymbolEntry(i)) { at(i, readSymbol); {} }
-      else if (isAnnotationEntry(i)) { at(i, readAnnotation); {} }
-    }
-
-    if (settings.debug.value) global.log("unpickled " + classRoot + ":" + classRoot.rawInfo + ", " + moduleRoot + ":" + moduleRoot.rawInfo);//debug
-
-    private def checkVersion() {
-      val major = readNat()
-      val minor = readNat()
-      if (major != MajorVersion || minor > MinorVersion)
-        throw new IOException("Scala signature " + classRoot.name + 
-                              " has wrong version\n expected: " + 
-                              MajorVersion + "." + MinorVersion + 
-                              "\n found: " + major + "." + minor)
-    }
-
-    /** The `decls' scope associated with given symbol */
-    private def symScope(sym: Symbol, isTemp : Boolean) = symScopes.get(sym) match {
-      case None => 
-        val s = if (isTemp) newTempScope
-                else if (sym.isClass || sym.isModuleClass || sym.isModule) newClassScope(sym);
-                else newScope
-      
-        symScopes(sym) = s; s
-      case Some(s) => s
-    }
-    private def symScope(sym : Symbol) : Scope = symScope(sym, false)
-
-    /** Does entry represent an (internal) symbol */
-    private def isSymbolEntry(i: Int): Boolean = {
-      val tag = bytes(index(i)) % PosOffset
-      (firstSymTag <= tag && tag <= lastSymTag &&
-       (tag != CLASSsym || !isRefinementSymbolEntry(i)))
-    }
-
-    /** Does entry represent an (internal or external) symbol */
-    private def isSymbolRef(i: Int): Boolean = {
-      val tag = bytes(index(i)) % PosOffset
-      (firstSymTag <= tag && tag <= lastExtSymTag)
-    }
-
-    /** Does entry represent a name? */
-    private def isNameEntry(i: Int): Boolean = {
-      val tag = bytes(index(i))
-      tag == TERMname || tag == TYPEname
-    }
-
-    /** Does entry represent a symbol attribute? */
-    private def isAnnotationEntry(i: Int): Boolean = {
-      val tag = bytes(index(i))
-      tag == ATTRIBUTE || tag == CHILDREN
-    }
-
-    /** Does entry represent a refinement symbol? 
-     *  pre: Entry is a class symbol
-     */
-    private def isRefinementSymbolEntry(i: Int): Boolean = {
-      val savedIndex = readIndex
-      readIndex = index(i)
-      val tag = readByte()
-      if (tag % PosOffset != CLASSsym) assert(false)
-      readNat(); // read length
-      if (tag > PosOffset) readNat(); // read position
-      val result = readNameRef() == nme.REFINE_CLASS_NAME.toTypeName
-      readIndex = savedIndex
-      result
-    }
-
-    /** If entry at <code>i</code> is undefined, define it by performing
-     *  operation <code>op</code> with <code>readIndex at start of i'th
-     *  entry. Restore <code>readIndex</code> afterwards.
-     */
-    private def at[T <: AnyRef](i: Int, op: () => T): T = {
-      var r = entries(i)
-      if (r eq null) {
-        val savedIndex = readIndex
-        readIndex = index(i)
-        r = op()
-        assert(entries(i) eq null, entries(i))
-        entries(i) = r
-        readIndex = savedIndex
-      }
-      r.asInstanceOf[T]
-    }
-
-    /** Read a name */
-    private def readName(): Name = {
-      val tag = readByte()
-      val len = readNat()
-      tag match {
-        case TERMname => newTermName(bytes, readIndex, len)
-        case TYPEname => newTypeName(bytes, readIndex, len)
-        case _ => errorBadSignature("bad name tag: " + tag)
-      }
-    }
-
-    /** Read a symbol */
-    private def readSymbol(): Symbol = {
-      val tag = readByte()
-      val end = readNat() + readIndex
-      var sym: Symbol = NoSymbol
-      tag match {
-        case EXTref | EXTMODCLASSref =>
-          val name = readNameRef()
-          val owner = if (readIndex == end) definitions.RootClass else readSymbolRef()
-          sym = if (name.toTermName == nme.ROOT) definitions.RootClass
-                else if (name == nme.ROOTPKG) definitions.RootPackage
-                else if (tag == EXTref) owner.info.decl(name)
-                else owner.info.decl(name).moduleClass
-          if (sym == NoSymbol) {
-            errorBadSignature(
-              "reference " + (if (name.isTypeName) "type " else "value ") +
-              name.decode + " of " + owner + " refers to nonexisting symbol.")
-          }
-        case NONEsym =>
-          sym = NoSymbol
-        case _ =>
-          val unusedPos : Int = {
-            if (tag > PosOffset) readNat
-            else -1
-          }
-          val name = readNameRef()
-          val owner = readSymbolRef()
-          val flags = readNat()
-          var privateWithin: Symbol = NoSymbol
-          var inforef = readNat()
-          if (isSymbolRef(inforef)) {
-            privateWithin = at(inforef, readSymbol)
-            inforef = readNat()
-          }
-          (tag % PosOffset) match {
-            case TYPEsym =>
-              sym = owner.newAbstractType(NoPosition, name)
-            case ALIASsym =>
-              sym = owner.newAliasType(NoPosition, name)
-            case CLASSsym =>
-              sym = 
-                if (name == classRoot.name && owner == classRoot.owner)
-                  (if ((flags & MODULE) != 0) moduleRoot.moduleClass
-                   else classRoot)
-                else 
-                  if ((flags & MODULE) != 0) owner.newModuleClass(NoPosition, name)
-                  else owner.newClass(NoPosition, name)
-              if (readIndex != end) sym.typeOfThis = new LazyTypeRef(readNat())
-            case MODULEsym =>
-              val clazz = at(inforef, readType).typeSymbol
-              sym = 
-                if (name == moduleRoot.name && owner == moduleRoot.owner) moduleRoot
-                else {
-                  assert(clazz.isInstanceOf[ModuleClassSymbol], clazz)
-                  val mclazz = clazz.asInstanceOf[ModuleClassSymbol]
-                  val m = owner.newModule(NoPosition, name, mclazz)
-                  mclazz.setSourceModule(m)
-                  m
-                }
-            case VALsym =>
-              sym = if (name == moduleRoot.name && owner == moduleRoot.owner) moduleRoot.resetFlag(MODULE)
-                    else owner.newValue(NoPosition, name)
-            case _ =>
-              errorBadSignature("bad symbol tag: " + tag)
-          }
-          sym.setFlag(flags.toLong & PickledFlags)
-          sym.privateWithin = privateWithin
-          if (readIndex != end) assert(sym hasFlag (SUPERACCESSOR | PARAMACCESSOR), sym)
-          if (sym hasFlag SUPERACCESSOR) assert(readIndex != end)
-          sym.setInfo(
-            if (readIndex != end) new LazyTypeRefAndAlias(inforef, readNat())
-            else new LazyTypeRef(inforef))
-          if (sym.owner.isClass && sym != classRoot && sym != moduleRoot && 
-              !sym.isModuleClass && !sym.isRefinementClass && !sym.isTypeParameter && !sym.isExistential)
-            symScope(sym.owner) enter sym
-      }
-      sym
-    }
-
-    /** Read a type */
-    private def readType(): Type = {
-      val tag = readByte()
-      val end = readNat() + readIndex
-      tag match {
-        case NOtpe =>
-          NoType
-        case NOPREFIXtpe =>
-          NoPrefix
-        case THIStpe =>
-          mkThisType(readSymbolRef())
-        case SINGLEtpe =>
-          singleType(readTypeRef(), readSymbolRef())
-        case CONSTANTtpe =>
-          mkConstantType(readConstantRef())
-        case TYPEREFtpe =>
-          val pre = readTypeRef()
-          val sym = readSymbolRef()
-          var args = until(end, readTypeRef)
-          if ((sym hasFlag JAVA) && sym.typeParams.isEmpty && global.settings.target.value != "jvm-1.5") {
-            // forget arguments, we are compiling for 1.4; see #1144
-            args = List()
-          }
-          rawTypeRef(pre, sym, args)
-        case TYPEBOUNDStpe =>
-          mkTypeBounds(readTypeRef(), readTypeRef())
-        case REFINEDtpe =>
-          val clazz = readSymbolRef()
-/*
-          val ps = until(end, readTypeRef)
-          val dcls = symScope(clazz)
-          new RefinedType(ps, dcls) { override def symbol = clazz }
-*/
-         new RefinedType(until(end, readTypeRef), symScope(clazz, true)) {
-           override def typeSymbol = clazz
-          }
-        case CLASSINFOtpe =>
-          val clazz = readSymbolRef()
-          ClassInfoType(until(end, readTypeRef), symScope(clazz), clazz)
-        case METHODtpe =>
-          val restpe = readTypeRef()
-          MethodType(until(end, readTypeRef), restpe)
-        case IMPLICITMETHODtpe =>
-          val restpe = readTypeRef()
-          ImplicitMethodType(until(end, readTypeRef), restpe)
-        case POLYtpe =>
-          val restpe = readTypeRef()
-          PolyType(until(end, readSymbolRef), restpe)
-        case EXISTENTIALtpe =>
-          val restpe = readTypeRef()
-          ExistentialType(until(end, readSymbolRef), restpe)
-        case ANNOTATEDtpe | ANNOTATEDWSELFtpe =>
-          val tp = readTypeRef()
-	  val selfsym = if (tag == ANNOTATEDWSELFtpe) readSymbolRef()
-                        else NoSymbol
-          val attribs = until(end, readTreeAttribRef)
-          if (settings.selfInAnnots.value || (selfsym eq NoSymbol))
-            AnnotatedType(attribs, tp, selfsym)
-          else
-            tp // drop annotations with a self symbol unless
-               // -Yself-in-annots is on
-        case DEBRUIJNINDEXtpe =>
-          DeBruijnIndex(readNat(), readNat())
-        case _ =>
-          errorBadSignature("bad type tag: " + tag)
-      }
-    }
+  def scan(bytes: Array[Byte], offset: Int, classRoot: Symbol, moduleRoot: Symbol, filename: String) = 
+    new CompileScan(bytes, offset, classRoot, moduleRoot, filename).run()
 
-    /** Read a constant */
-    private def readConstant(): Constant = {
-      val tag = readByte()
-      val len = readNat()
-      tag match {
-        case LITERALunit    => Constant(())
-        case LITERALboolean => Constant(if (readLong(len) == 0) false else true)
-        case LITERALbyte    => Constant(readLong(len).asInstanceOf[Byte])
-        case LITERALshort   => Constant(readLong(len).asInstanceOf[Short])
-        case LITERALchar    => Constant(readLong(len).asInstanceOf[Char])
-        case LITERALint     => Constant(readLong(len).asInstanceOf[Int])
-        case LITERALlong    => Constant(readLong(len))
-        case LITERALfloat   => Constant(Float.intBitsToFloat(readLong(len).asInstanceOf[Int]))
-        case LITERALdouble  => Constant(Double.longBitsToDouble(readLong(len)))
-        case LITERALstring  => Constant(readNameRef().toString())
-        case LITERALnull    => Constant(null)
-        case LITERALclass   => Constant(readTypeRef())
-        case _              => errorBadSignature("bad constant tag: " + tag)
-      }
-    }
-
-    /** Read an annotation argument.  It can use either Constant's or
-     *  Tree's for its arguments.  If a reflect tree is seen, it
-     *  prints a warning and returns an empty tree.
-     */
-    private def readAnnotationArg(): AnnotationArgument = {
-      if (peekByte() == REFLTREE) {
-        reflectAnnotationWarning()
-	new AnnotationArgument(EmptyTree)
-      } else if (peekByte() == TREE) {
-	val tree = readTree()
-	new AnnotationArgument(tree)
-      } else {
-        val const = readConstant()
-        new AnnotationArgument(const)        
-      }
-    }
-
-    /** Read an annotation abstract syntax tree. */
-    private def readAnnotationTree(): Annotation = {
-      val tag = readByte()
-      val end = readNat() + readIndex
-      val tpe = readTypeRef()
-      val constr = readTreeRef()
-      val elements = until(end, readTreeRef)
-      Annotation(constr, elements).setType(tpe)
-    }
+  class CompileScan(bytes: Array[Byte], offset: Int, classRoot: Symbol, moduleRoot: Symbol, filename: String) 
+  extends Scan(bytes, offset, classRoot, moduleRoot, filename) {
 
-    /** Read an attribute and as a side effect store it into
-     *  the symbol it requests. */
-    private def readAnnotation(): AnyRef = {
-      val tag = readByte()
-      val end = readNat() + readIndex
-      val target = readSymbolRef()
-      if (tag == ATTRIBUTE) {
-        val attrType = readTypeRef()
-        val args = new ListBuffer[AnnotationArgument]
-        val assocs = new ListBuffer[(Name, AnnotationArgument)]
-        while (readIndex != end) {
-          val argref = readNat()
-          if (isNameEntry(argref))
-            assocs += ((at(argref, readName), readAnnotationArgRef))
-          else
-            args += at(argref, readAnnotationArg)
-        }
-        val attr = AnnotationInfo(attrType, args.toList, assocs.toList)
-        target.attributes = attr :: target.attributes
-      } else if (tag == CHILDREN) {
-        while (readIndex != end) target addChild readSymbolRef()
-      }
-      null
-    }
-
-    /** Read an annotation and return it. */
-    private def readTreeAttrib(): AnnotationInfo = {
-      val tag = readByte()
-      if(tag != ANNOTINFO)
-        errorBadSignature("tree-based annotation expected (" + tag + ")")
-      val end = readNat() + readIndex
-
-      val atp = readTypeRef()
-      val numargs = readNat()
-      val args = times(numargs, readAnnotationArgRef)
-      val assocs =
-        until(end, {() =>
-          val name = readNameRef()
-          val tree = readAnnotationArgRef()
-          (name,tree)})
-      AnnotationInfo(atp, args, assocs)
-    }
+    protected override def debug = settings.debug.value
 
-    /* Read an abstract syntax tree */
-    private def readTree(): Tree = {
-      val outerTag = readByte()
-      if (outerTag != TREE)
-	errorBadSignature("tree expected (" + outerTag + ")")
-      val end = readNat() + readIndex
-      val tag = readByte()
-      val tpe = 
-	if (tag != EMPTYtree)
-	  readTypeRef()
-	else
-	  NoType
+    // override def noSuchTypeTag(tag: Int, end: Int): Type = {
+    //   tag match {
+    //     case DEBRUIJNINDEXtpe =>
+    //       DeBruijnIndex(readNat(), readNat())
+    //     case _ =>
+    //       super.noSuchTypeTag(tag, end)
+    //   }
+    // }
 
-      tag match {
-	case EMPTYtree =>
-	  EmptyTree
+    override protected def errorMissingRequirement(name: Name, owner: Symbol) = 
+      errorMissingRequirement(
+        "reference " + (if (name.isTypeName) "type " else "value ") +
+        name.decode + " of " + owner.tpe.widen + " refers to nonexisting symbol.")
 
-	case PACKAGEtree =>
-	  val symbol = readSymbolRef()
-	  val name = readNameRef()
-	  val stats = until(end, readTreeRef)
-	  
-	  PackageDef(name, stats) setType tpe
+    def inferMethodAlternative(fun: Tree, argtpes: List[Type], restpe: Type) = 
+      typer.infer.inferMethodAlternative(fun, List(), argtpes, restpe)
 
-	case CLASStree =>
-	  val symbol = readSymbolRef() 
-          val mods = readModifiersRef()
-	  val name = readNameRef()
-	  val impl = readTemplateRef()
-	  val tparams = until(end, readTypeDefRef)
-	  (ClassDef(mods, name, tparams, impl).
-	   setSymbol(symbol).
-	   setType(tpe))
-
-	case MODULEtree =>
-	  val symbol = readSymbolRef()
-	  val mods = readModifiersRef()
-	  val name = readNameRef()
-	  val impl = readTemplateRef()
-	  (ModuleDef(mods, name, impl).
-	   setSymbol(symbol).
-	   setType(tpe))
-
-	case VALDEFtree =>
-	  val symbol = readSymbolRef()
-	  val mods = readModifiersRef()
-	  val name = readNameRef()
-	  val tpt = readTreeRef()
-	  val rhs = readTreeRef()
-
-	  (ValDef(mods, name, tpt, rhs).
-	   setSymbol(symbol).
-	   setType(tpe))
-	
-	case DEFDEFtree =>
-	  val symbol = readSymbolRef()
-	  val mods = readModifiersRef()
-	  val name = readNameRef()
-	  val numTparams = readNat()
-	  val tparams = times(numTparams, readTypeDefRef)
-	  val numVparamss = readNat
-	  val vparamss = times(numVparamss, () => {
-	    val len = readNat()
-	    times(len, readValDefRef)})
-	  val tpt = readTreeRef()
-	  val rhs = readTreeRef()
-
-	  (DefDef(mods, name, tparams, vparamss, tpt, rhs).
-  	   setSymbol(symbol).
-	   setType(tpe))
-
-	case TYPEDEFtree =>
-          val symbol = readSymbolRef()
-	  val mods = readModifiersRef()
-	  val name = readNameRef()
-	  val rhs = readTreeRef()
-	  val tparams = until(end, readTypeDefRef)
-	
-	  (TypeDef(mods, name, tparams, rhs).
-  	   setSymbol(symbol).
-	   setType(tpe))
-
-
-	case LABELtree =>
-	  val symbol = readSymbolRef()
-	  val rhs = readTreeRef()
-	  val params = until(end, readIdentRef)
-          (LabelDef(name, params, rhs).
-  	   setSymbol(symbol).
-	   setType(tpe))
-
-	case IMPORTtree =>
-          val symbol = readSymbolRef()
-	  val expr = readTreeRef()
- 	  val selectors = until(end, () => {
-	    val from = readNameRef()
-	    val to = readNameRef()
-	    (from, to)
-	  })
-	  (Import(expr, selectors).
-  	   setSymbol(symbol).
-	   setType(tpe))
-
-	case ANNOTATIONtree =>
-	  val constr = readTreeRef()
-	  val elements = until(end, readTreeRef)
-	  (Annotation(constr, elements).setType(tpe))
-
-	case DOCDEFtree =>
-	  val comment = readConstantRef match {
-	    case Constant(com: String) => com
-	    case other =>
-	      errorBadSignature("Document comment not a string (" + other + ")")
-	  }
-	  val definition = readTreeRef()
-	  (DocDef(comment, definition).setType(tpe))
-
-	case TEMPLATEtree =>
-	  val symbol = readSymbolRef()
-          val numParents = readNat()
-	  val parents = times(numParents, readTreeRef)
-	  val self = readValDefRef()
-	  val body = until(end, readTreeRef)
-
-	  (Template(parents, self, body).
-	   setSymbol(symbol).
-	   setType(tpe))
-
-	case BLOCKtree =>
-	  val expr = readTreeRef()
-	  val stats = until(end, readTreeRef)
-	  Block(stats, expr).setType(tpe)
-
-	case CASEtree =>
-	  val pat = readTreeRef()
-	  val guard = readTreeRef()
-	  val body = readTreeRef()
-	  CaseDef(pat, guard, body).setType(tpe)
-
-	case SEQUENCEtree =>
-	  val trees = until(end, readTreeRef)
-	  Sequence(trees).setType(tpe)
-
-	case ALTERNATIVEtree =>
-	  val trees = until(end, readTreeRef)
-	  Alternative(trees).setType(tpe)
-
-	case STARtree =>
-	  val elem = readTreeRef()
-	  Star(elem).setType(tpe)
-
-	case BINDtree =>
-	  val symbol = readSymbolRef()
-	  val name = readNameRef()
-	  val body = readTreeRef()
-	  (Bind(name, body).
-	   setSymbol(symbol).
-	   setType(tpe))
-
-	case UNAPPLYtree =>
-	  val fun = readTreeRef()
-	  val args = until(end, readTreeRef)
-          (UnApply(fun: Tree, args).setType(tpe))
-
-	case ARRAYVALUEtree =>
-	  val elemtpt = readTreeRef()
-	  val trees = until(end, readTreeRef)
-	  (ArrayValue(elemtpt, trees).setType(tpe))
-
-	case FUNCTIONtree =>
-	  val symbol = readSymbolRef()
-	  val body = readTreeRef()
-	  val vparams = until(end, readValDefRef)
-	  (Function(vparams, body).
-	   setSymbol(symbol).
-	   setType(tpe))
-
-	case ASSIGNtree =>
-          val lhs = readTreeRef()
-          val rhs = readTreeRef()
-	  Assign(lhs, rhs).setType(tpe)
-	
-	case IFtree =>
-          val cond = readTreeRef()
-          val thenp = readTreeRef()
-          val elsep = readTreeRef()
-	  If(cond, thenp, elsep).setType(tpe)
-
-	case MATCHtree =>
-          val selector = readTreeRef()
-          val cases = until(end, readCaseDefRef)
-	  Match(selector, cases).setType(tpe)
-
-	case RETURNtree =>
-	  val symbol = readSymbolRef()
-	  val expr = readTreeRef()
-	  (Return(expr).
-	   setSymbol(symbol).
-	   setType(tpe))
-
-	case TREtree =>
-          val block = readTreeRef()
-	  val finalizer = readTreeRef()
-	  val catches = until(end, readCaseDefRef)
-	  Try(block, catches, finalizer).setType(tpe)
-
-	case THROWtree =>
-	  val expr = readTreeRef()
-	  Throw(expr).setType(tpe)
-
-	case NEWtree =>
-	  val tpt = readTreeRef()
-	  New(tpt).setType(tpe)
-	  
-	case TYPEDtree =>
-	  val expr = readTreeRef()
-	  val tpt = readTreeRef()
-          Typed(expr, tpt).setType(tpe)
-
-	case TYPEAPPLYtree =>
-	  val fun = readTreeRef()
-	  val args = until(end, readTreeRef)
-	  TypeApply(fun, args).setType(tpe)	  
-	  
-	case APPLYtree =>
-	  val fun = readTreeRef()
-          val args = until(end, readTreeRef)
-	  Apply(fun, args).setType(tpe)
-	  
-
-	case APPLYDYNAMICtree =>
-	  val symbol = readSymbolRef()
-	  val qual = readTreeRef()
-          val args = until(end, readTreeRef)
-	  ApplyDynamic(qual, args).setSymbol(symbol).setType(tpe)
-
-	case SUPERtree =>
-	  val symbol = readSymbolRef()
-	  val qual = readNameRef()
-	  val mix = readNameRef()
-	  Super(qual, mix).setSymbol(symbol).setType(tpe)
-
-        case THIStree =>
-	  val symbol = readSymbolRef()
-	  val qual = readNameRef()
-	  This(qual).setSymbol(symbol).setType(tpe)
-
-        case SELECTtree =>
-	  val symbol = readSymbolRef()
-	  val qualifier = readTreeRef()
-	  val selector = readNameRef()
-	  Select(qualifier, selector).setSymbol(symbol).setType(tpe)
-
-	case IDENTtree =>
-	  val symbol = readSymbolRef()
-	  val name = readNameRef()
-	  Ident(name).setSymbol(symbol).setType(tpe)
-	  
-	case LITERALtree =>
-	  val value = readConstantRef()
-	  Literal(value).setType(tpe)
-
-	case TYPEtree =>
-	  TypeTree().setType(tpe)
-	  
-	case ANNOTATEDtree =>
-          val annot = readAnnotationTreeRef()
-          val arg = readTreeRef()
-	  Annotated(annot, arg).setType(tpe)
-	  
-	case SINGLETONTYPEtree =>
-	  val ref = readTreeRef()
-	  SingletonTypeTree(ref).setType(tpe)
-
-	case SELECTFROMTYPEtree =>
-          val qualifier = readTreeRef()
-          val selector = readNameRef()
-	  SelectFromTypeTree(qualifier, selector).setType(tpe)
-
-	case COMPOUNDTYPEtree =>
-	  val templ = readTemplateRef()
-	  CompoundTypeTree(templ: Template).setType(tpe)
-	  
-	case APPLIEDTYPEtree =>
-	  val tpt = readTreeRef()
-          val args = until(end, readTreeRef)
-	  AppliedTypeTree(tpt, args).setType(tpe)
-	  
-	case TYPEBOUNDStree =>
-	  val lo = readTreeRef()
-	  val hi = readTreeRef()
-	  TypeBoundsTree(lo, hi).setType(tpe)
-	  
-	case EXISTENTIALTYPEtree =>
-	  val tpt = readTreeRef()
-	  val whereClauses = until(end, readTreeRef)
-	  ExistentialTypeTree(tpt, whereClauses).setType(tpe)
-	  
-	case _ =>
-          errorBadSignature("unknown tree type (" + tag + ")")
-      }
-    }
-
-    def readModifiers(): Modifiers = {
-      val tag = readNat()
-      if (tag != MODIFIERS)
-	errorBadSignature("expected a modifiers tag (" + tag + ")")
-      val end = readNat() + readIndex
-      val flagsHi = readNat()
-      val flagsLo = readNat()
-      val flags = (flagsHi.toLong << 32) + flagsLo
-      val privateWithin = readNameRef()
-      val annotations = until(end, readAnnotationTreeRef)
-      Modifiers(flags, privateWithin, annotations)
-    }
-
-    /* Read a reference to a pickled item */
-    private def readNameRef(): Name = at(readNat(), readName)
-    private def readSymbolRef(): Symbol = at(readNat(), readSymbol)
-    private def readTypeRef(): Type = at(readNat(), readType)
-    private def readConstantRef(): Constant = at(readNat(), readConstant)
-    private def readAnnotationArgRef(): AnnotationArgument =
-      at(readNat(), readAnnotationArg)
-    private def readTreeAttribRef(): AnnotationInfo =
-      at(readNat(), readTreeAttrib)
-    private def readAnnotationTreeRef(): Annotation =
-      at(readNat(), readAnnotationTree)
-    private def readModifiersRef(): Modifiers =
-      at(readNat(), readModifiers)
-    private def readTreeRef(): Tree =
-      at(readNat(), readTree)
-
-    private def readTemplateRef(): Template =
-      readTreeRef() match {
-	case templ:Template => templ
-	case other =>
-          errorBadSignature("expected a template (" + other + ")")
-      }
-    private def readCaseDefRef(): CaseDef =
-      readTreeRef() match {
-	case tree:CaseDef => tree
-	case other =>
-          errorBadSignature("expected a case def (" + other + ")")
-      }
-    private def readValDefRef(): ValDef =
-      readTreeRef() match {
-	case tree:ValDef => tree
-	case other =>
-          errorBadSignature("expected a ValDef (" + other + ")")
-      }
-    private def readIdentRef(): Ident =
-      readTreeRef() match {
-	case tree:Ident => tree
-	case other =>
-          errorBadSignature("expected an Ident (" + other + ")")
-      }
-    private def readTypeDefRef(): TypeDef =
-      readTreeRef() match {
-	case tree:TypeDef => tree
-	case other =>
-          errorBadSignature("expected an TypeDef (" + other + ")")
-      }
-
-
-    private def errorBadSignature(msg: String) =
-      if (inIDE) throw new TypeError(msg)
-      else throw new RuntimeException("malformed Scala signature of " + classRoot.name + " at " + readIndex + "; " + msg)
-
-    private var printedReflectAnnotationWarning = false
-    private def reflectAnnotationWarning() {
-      if (!printedReflectAnnotationWarning) {
-	global.warning(
-	  "warning: dropping a legacy format annotation in " + classRoot.name)
-	printedReflectAnnotationWarning = true
-      }
-    }
+    def newLazyTypeRef(i: Int): LazyType = new LazyTypeRef(i)
+    def newLazyTypeRefAndAlias(i: Int, j: Int): LazyType = new LazyTypeRefAndAlias(i, j)
 
+    /** A lazy type which when completed returns type at index `i`. */
     private class LazyTypeRef(i: Int) extends LazyType {
       private val definedAtRunId = currentRunId
-      // In IDE, captures class files dependencies so they can be reloaded when their dependencies change.
-      private val ideHook = unpickleIDEHook
+      private val p = phase
       override def complete(sym: Symbol) : Unit = {
-        if (sym.rawInfo != this && inIDE) return
-        val tp = ideHook(at(i, readType))
-        sym setInfo tp
-        if (!inIDE && currentRunId != definedAtRunId) sym.setInfo(adaptToNewRunMap(tp))
+        val tp = at(i, readType)
+        if (p != phase) atPhase(p) (sym setInfo tp) 
+        else sym setInfo tp
+        if (currentRunId != definedAtRunId) sym.setInfo(adaptToNewRunMap(tp))
       }
       override def load(sym: Symbol) { complete(sym) }
     }
 
+    /** A lazy type which when completed returns type at index `i` and sets alias
+     *  of completed symbol to symbol at index `j`.
+     */
     private class LazyTypeRefAndAlias(i: Int, j: Int) extends LazyTypeRef(i) {
       override def complete(sym: Symbol) {
         super.complete(sym)
         var alias = at(j, readSymbol)
-        if (alias hasFlag OVERLOADED)
-          alias = alias suchThat (alt => sym.tpe =:= sym.owner.thisType.memberType(alt))
+        if (alias hasFlag OVERLOADED) {
+          atPhase(currentRun.picklerPhase) {
+            alias = alias suchThat (alt => sym.tpe =:= sym.owner.thisType.memberType(alt))
+          }
+        }
         sym.asInstanceOf[TermSymbol].setAlias(alias)
       }
     }
diff --git a/src/compiler/scala/tools/nsc/symtab/clr/CLRTypes.scala b/src/compiler/scala/tools/nsc/symtab/clr/CLRTypes.scala
index 75d708d..d4aa98e 100644
--- a/src/compiler/scala/tools/nsc/symtab/clr/CLRTypes.scala
+++ b/src/compiler/scala/tools/nsc/symtab/clr/CLRTypes.scala
@@ -1,10 +1,11 @@
 /* NSC -- new scala compiler
- * Copyright 2004-2009 LAMP/EPFL
+ * Copyright 2004-2010 LAMP/EPFL
  */
 
-// $Id: CLRTypes.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.tools.nsc.symtab.clr
+package scala.tools.nsc
+package symtab
+package clr
 
 import java.io.File
 import java.util.{Comparator, StringTokenizer}
@@ -61,20 +62,11 @@ abstract class CLRTypes {
   val fields: Map[Symbol, FieldInfo] = new HashMap
   val sym2type: Map[Type,Symbol] = new HashMap
 
-  private var alltypes: Array[Type] = _
 
   def init() = try { // initialize
-/*
-    val assems = new StringTokenizer(global.settings.assemrefs.value, File.pathSeparator)
-    while (assems.hasMoreTokens()) {
-      assemrefs += new File(assems.nextToken())
-    }
-    */
-
-    val mscorlib = findAssembly("mscorlib.dll")
-    Type.initMSCORLIB(mscorlib)
-    findAssembly("scalaruntime.dll")
-    findAllAssemblies()
+    // the MsilClasspath (nsc/util/Classpath.scala) initializes the msil-library by calling
+    // Assembly.LoadFrom("mscorlib.dll"), so this type should be found
+    Type.initMSCORLIB(getTypeSafe("System.String").Assembly)
 
     BYTE     = getTypeSafe("System.SByte")
     UBYTE    = getTypeSafe("System.Byte")
@@ -102,38 +94,20 @@ abstract class CLRTypes {
     SYMTAB_CONSTR = SCALA_SYMTAB_ATTR.GetConstructor(bytearray)
     SYMTAB_DEFAULT_CONSTR = SCALA_SYMTAB_ATTR.GetConstructor(Type.EmptyTypes)
 
-    //assert(SCALA_SYMTAB_ATTR != null)
-
     val delegate: Type = getTypeSafe("System.Delegate")
     val dargs: Array[Type] = Array(delegate, delegate)
     DELEGATE_COMBINE = delegate.GetMethod("Combine", dargs)
     DELEGATE_REMOVE = delegate.GetMethod("Remove", dargs)
-    //assert(DELEGATE_COMBINE != null)
-    //assert(DELEGATE_REMOVE != null)
-
-
-    var alltypes: Array[Type] = Type.EmptyTypes
-    for (assem <- assemblies) {
-      val atypes = assem.GetTypes().filter((typ: Type) => typ.DeclaringType == null)
-      alltypes = Array.concat(alltypes, atypes)
-    }
-
-    Sorting.stableSort(alltypes, (t1: Type, t2: Type) => (t1.FullName compareTo t2.FullName) < 0)
-    this.alltypes = alltypes
   }
   catch {
     case e: RuntimeException =>
       Console.println(e.getMessage)
-      // no bloody exits! exit(1)
+      throw e
   }
 
   //##########################################################################
   // type mapping and lookup
 
-//   private class MyHashMap[A, B <: AnyRef] extends HashMap[A, B] {
-//     override def default(key: A): B = null;
-//   }
-
   def getType(name: String): Type = Type.GetType(name)
 
   def getTypeSafe(name: String): Type = {
@@ -145,107 +119,4 @@ abstract class CLRTypes {
   def mkArrayType(elemType: Type): Type = getType(elemType.FullName + "[]")
 
   def isDelegateType(t: Type): Boolean = { t.BaseType() == DELEGATE }
-
-  //##########################################################################
-  // assembly loading methods
-
-  // a list of all loaded assemblies
-  private var assemblies: ListBuffer[Assembly] = new ListBuffer()
-
-  // a set of all directories and assembly files
-  //private var assemrefs: Set[File] = new HashSet()
-  
-  //def assembly(file : File) = assemrefs += file
-
-  /** Load the assembly with the given name
-   */
-  private def findAssembly(name: String): Assembly = {
-    // see if the assembly is referenced directly
-    for (file <- global.assemrefs.elements if file.getName() == name) {
-      val assem = Assembly.LoadFrom(file.getPath())
-      if (assem != null) {
-	global.assemrefs -= file
-	assemblies += assem
-	return assem
-      }
-    }
-    // look in directories specified with the '-r' option
-    for (dir <- global.assemrefs.elements if dir.isDirectory()) {
-      val file = new File(dir, name)
-      if (file.exists()) {
-	val assem = Assembly.LoadFrom(file.getPath())
-	if (assem != null) {
-	  assemblies += assem
-	  return assem
-	}
-      }
-    }
-    // try in the current directory
-    val file = new File(".", name)
-    if (file.exists()) {
-      val assem = Assembly.LoadFrom(file.getPath())
-      if (assem != null) {
-	assemblies += assem
-	return assem
-      }
-    }
-    throw new RuntimeException(
-      "cannot find assembly " + name + "; use the -Xassem-path option to specify its location")
-  }
-
-  /** Load the rest of the assemblies specified with the '-r' option
-   */
-  private def findAllAssemblies() {
-    for (file <- global.assemrefs.elements) {
-      if (file.isFile()) {
-        //System.out.println("Loading assembly " + file)
-	val assem = Assembly.LoadFrom(file.getPath())
-	if (assem != null) {
-	  assemblies += assem
-	}
-      }
-    }
-    global.assemrefs.clear
-  }
-
-  //##########################################################################
-  // collect the members contained in a given namespace
-
-  /** Find the position of the first type whose name starts with
-   *  the given prefix; return the length of the types array if no match
-   *  is found so the result canbe used to terminate loop conditions
-   */
-  private def findFirst(prefix: String): Int = {
-    var m = 0
-    var n = alltypes.length - 1
-    while (m < n) {
-      val l = (m + n) / 2
-      val res = alltypes(l).FullName.compareTo(prefix)
-      if (res < 0) m = l + 1
-      else n = l
-    }
-    if (alltypes(m).FullName.startsWith(prefix)) m else alltypes.length
-  }
-
-  /** Collects the members contained in the given Scala package (namespace)
-   */
-  def collectMembers(pakage: Symbol, typesMap: Map[String,Type], namespacesSet: Set[String]) = {
-    val namespace = if (pakage.isRoot) "" else pakage.fullNameString + "."
-    val nl = namespace.length()
-    var i = findFirst(namespace)
-    while (i < alltypes.length && alltypes(i).FullName.startsWith(namespace)) {
-      val typ = alltypes(i)
-      if (typ.FullName != "java.lang.Object" && typ.FullName != "java.lang.String") {
-	val k = typ.FullName.indexOf(".", nl)
-	if (k < 0) {
-	  typesMap.update(typ.Name, typ)
-	} else {
-	  namespacesSet += (typ.Namespace.substring(nl, k))
-	}
-      }
-      i += 1
-    }
-  }
-
-    //##########################################################################
 }  // CLRTypes
diff --git a/src/compiler/scala/tools/nsc/symtab/clr/TypeParser.scala b/src/compiler/scala/tools/nsc/symtab/clr/TypeParser.scala
index 0709872..a90fb8b 100644
--- a/src/compiler/scala/tools/nsc/symtab/clr/TypeParser.scala
+++ b/src/compiler/scala/tools/nsc/symtab/clr/TypeParser.scala
@@ -1,17 +1,17 @@
 /* NSC -- new scala compiler
- * Copyright 2004-2009 LAMP/EPFL
+ * Copyright 2004-2010 LAMP/EPFL
  */
 
-// $Id: TypeParser.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.tools.nsc.symtab.clr
+package scala.tools.nsc
+package symtab
+package clr
 
 import java.io.IOException
 
 import ch.epfl.lamp.compiler.msil.{Type => MSILType, Attribute => MSILAttribute, _}
 
 import scala.collection.mutable.{HashMap, HashSet}
-import scala.tools.nsc.util.{Position, NoPosition}
 import classfile.UnPickler
 
 /**
@@ -20,8 +20,9 @@ import classfile.UnPickler
 abstract class TypeParser {
 
   val global: Global
-  import global.loaders.clrTypes
-  import clrTypes.global._
+
+  import global._
+  import loaders.clrTypes
 
   //##########################################################################
 
@@ -40,7 +41,7 @@ abstract class TypeParser {
 
   def parse(typ: MSILType, root: Symbol) {
 
-    def handleError(e: Exception) = {
+    def handleError(e: Throwable) = {
       if (settings.debug.value) e.printStackTrace()  //debug
       throw new IOException("type '" + typ.FullName + "' is broken\n(" + e.getMessage() + ")")
     }
@@ -48,11 +49,11 @@ abstract class TypeParser {
     busy = true
 
     if (root.isModule) {
-      this.clazz = root.linkedClassOfModule
+      this.clazz = root.companionClass
       this.staticModule = root
     } else {
       this.clazz = root
-      this.staticModule = root.linkedModuleOfClass
+      this.staticModule = root.companionModule
     }
     try {
       parseClass(typ)
@@ -74,8 +75,7 @@ abstract class TypeParser {
       val a = attrs(0).asInstanceOf[MSILAttribute];
       assert (a.getConstructor() == clrTypes.SYMTAB_CONSTR);
       val symtab = a.getConstructorArguments()(0).asInstanceOf[Array[Byte]]
-      unpickler.unpickle(symtab, 0, clazz.asInstanceOf[unpickler.global.Symbol], 
-                                    staticModule.asInstanceOf[unpickler.global.Symbol], typ.FullName);
+      unpickler.unpickle(symtab, 0, clazz, staticModule, typ.FullName);
       val mClass = clrTypes.getType(typ.FullName + "$");
       if (mClass != null) {
         clrTypes.types(statics) = mClass;
@@ -91,8 +91,8 @@ abstract class TypeParser {
                     else  if (typ.IsInterface()) definitions.ObjectClass.tpe
                     else definitions.AnyClass.tpe; // this is System.Object
     val parents = superType :: ifaces.map(getCLRType).toList
-    instanceDefs = newClassScope(clazz)
-    staticDefs = newClassScope(staticModule)
+    instanceDefs = new Scope
+    staticDefs = new Scope
 
     val classInfo = ClassInfoType(parents, instanceDefs, clazz)
     val staticInfo = ClassInfoType(List(), staticDefs, statics)
@@ -110,7 +110,7 @@ abstract class TypeParser {
 				            || ntype.IsNestedFamANDAssem)
 				          || ntype.IsInterface)
       {
-	val loader = new global.loaders.MSILTypeLoader(ntype)
+	val loader = new loaders.MSILTypeLoader(ntype)
 	val nclazz = statics.newClass(NoPosition, ntype.Name.toTypeName)
 	val nmodule = statics.newModule(NoPosition, ntype.Name)
 	nclazz.setInfo(loader)
@@ -118,8 +118,8 @@ abstract class TypeParser {
 	staticDefs.enter(nclazz)
 	staticDefs.enter(nmodule)
 
-	assert(nclazz.linkedModuleOfClass == nmodule, nmodule)
-	assert(nmodule.linkedClassOfModule == nclazz, nclazz)
+	assert(nclazz.companionModule == nmodule, nmodule)
+	assert(nmodule.companionClass == nclazz, nclazz)
       }
 
     val fields = typ.getFields()
@@ -159,10 +159,11 @@ abstract class TypeParser {
 	    gparamsLength = gparams.length;
 	    val name: Name = if (gparamsLength == 0) prop.Name else nme.apply;
 	    val flags = translateAttributes(getter);
-	    val mtype: Type = if (gparamsLength == 0) PolyType(List(), propType)
-                              else methodType(getter, getter.ReturnType);
 	    val owner: Symbol = if (getter.IsStatic) statics else clazz;
-	    val methodSym = owner.newMethod(NoPosition, name).setFlag(flags).setInfo(mtype);
+	    val methodSym = owner.newMethod(NoPosition, name).setFlag(flags)
+	    val mtype: Type = if (gparamsLength == 0) PolyType(List(), propType)
+                              else methodType(getter, getter.ReturnType)(methodSym)
+        methodSym.setInfo(mtype);
 	    methodSym.setFlag(Flags.ACCESSOR);
 	    (if (getter.IsStatic) staticDefs else instanceDefs).enter(methodSym)
 	    clrTypes.methods(methodSym) = getter;
@@ -181,9 +182,10 @@ abstract class TypeParser {
 	    val name: Name = if (gparamsLength == 0) nme.getterToSetter(prop.Name)
 			     else nme.update;
 	    val flags = translateAttributes(setter);
-	    val mtype: Type = methodType(setter, definitions.UnitClass.tpe);
+	    val mtype = methodType(setter, definitions.UnitClass.tpe);
 	    val owner: Symbol = if (setter.IsStatic) statics else clazz;
-	    val methodSym = owner.newMethod(NoPosition, name).setFlag(flags).setInfo(mtype);
+	    val methodSym = owner.newMethod(NoPosition, name).setFlag(flags)
+        methodSym.setInfo(mtype(methodSym))
 	    methodSym.setFlag(Flags.ACCESSOR);
 	    (if (setter.IsStatic) staticDefs else instanceDefs).enter(methodSym);
 	    clrTypes.methods(methodSym) = setter;
@@ -222,7 +224,7 @@ abstract class TypeParser {
 	}
     } */
 
-    for (method <- methodsSet.elements)
+    for (method <- methodsSet.iterator)
       if (!method.IsPrivate() && !method.IsAssembly() && !method.IsFamilyAndAssembly())
         createMethod(method);
 
@@ -234,13 +236,13 @@ abstract class TypeParser {
 
     // create the box/unbox methods for value types
     if (typ.IsValueType) {
-      val box = statics.newMethod(NoPosition, nme.box).
-        setInfo(MethodType(List(clazz.tpe), definitions.ObjectClass.tpe));
-      definitions.boxMethod(clazz) = box;
-      val unbox = statics.newMethod(NoPosition, nme.unbox).
-        setInfo(MethodType(List(definitions.ObjectClass.tpe), clazz.tpe));
-      definitions.unboxMethod(clazz) = unbox;
-      //Console.println(typ.FullName + " : " + parents);
+      val box = statics.newMethod(NoPosition, nme.box)
+      box.setInfo(MethodType(box.newSyntheticValueParams(List(clazz.tpe)), definitions.ObjectClass.tpe))
+      definitions.boxMethod(clazz) = box
+      val unbox = statics.newMethod(NoPosition, nme.unbox)
+      unbox.setInfo(MethodType(unbox.newSyntheticValueParams(List(definitions.ObjectClass.tpe)), clazz.tpe))
+      definitions.unboxMethod(clazz) = unbox
+      //Console.println(typ.FullName + " : " + parents)
     }
 
     // for enumerations introduce comparison and bitwise logical operations;
@@ -253,17 +255,17 @@ abstract class TypeParser {
 
       val flags = Flags.JAVA | Flags.FINAL
       for (cmpName <- ENUM_CMP_NAMES) {
-	val enumCmpType: Type = JavaMethodType(List(clazz.tpe), definitions.BooleanClass.tpe);
-	val enumCmp: Symbol = clazz.newMethod(NoPosition, cmpName);
-	enumCmp.setFlag(flags).setInfo(enumCmpType)
-	instanceDefs.enter(enumCmp);
+        val enumCmp = clazz.newMethod(NoPosition, cmpName)
+        val enumCmpType = JavaMethodType(enumCmp.newSyntheticValueParams(List(clazz.tpe)), definitions.BooleanClass.tpe)
+        enumCmp.setFlag(flags).setInfo(enumCmpType)
+        instanceDefs.enter(enumCmp)
       }
 
       for (bitLogName <- ENUM_BIT_LOG_NAMES) {
-	val enumBitLogType = JavaMethodType(List(clazz.tpe), classInfo);
-	val enumBitLog = clazz.newMethod(NoPosition, bitLogName);
-	enumBitLog.setFlag(flags).setInfo(enumBitLogType);
-	instanceDefs.enter(enumBitLog);
+        val enumBitLog = clazz.newMethod(NoPosition, bitLogName)
+        val enumBitLogType = JavaMethodType(enumBitLog.newSyntheticValueParams(List(clazz.tpe)), classInfo)
+        enumBitLog.setFlag(flags).setInfo(enumBitLogType)
+        instanceDefs.enter(enumBitLog)
       }
     }
 
@@ -277,8 +279,8 @@ abstract class TypeParser {
     if (mtype == null) return;
     val flags = translateAttributes(method);
     val owner = if (method.IsStatic()) statics else clazz;
-    val methodSym = owner.newMethod(NoPosition, getName(method)).setFlag(flags).
-    setInfo(mtype);
+    val methodSym = owner.newMethod(NoPosition, getName(method)).setFlag(flags)
+    methodSym.setInfo(mtype(methodSym))
     (if (method.IsStatic()) staticDefs else instanceDefs).enter(methodSym);
     if (method.IsConstructor())
       clrTypes.constructors(methodSym) = method.asInstanceOf[ConstructorInfo]
@@ -286,17 +288,17 @@ abstract class TypeParser {
   }
 
   private def createMethod(name: Name, flags: Long, args: Array[MSILType], retType: MSILType, method: MethodInfo, statik: Boolean): Symbol = {
-    val mtype: Type = methodType(args, getCLSType(retType));
-    assert(mtype != null);
+    val mtype = methodType(args, getCLSType(retType))
+    assert(mtype != null)
     createMethod(name, flags, mtype, method, statik)
   }
 
-  private def createMethod(name: Name, flags: Long, mtype: Type, method: MethodInfo, statik: Boolean): Symbol = {
-    val methodSym: Symbol = (if (statik)  statics else clazz).newMethod(NoPosition, name);
-    methodSym.setFlag(flags).setInfo(mtype);
-    (if (statik) staticDefs else instanceDefs).enter(methodSym);
+  private def createMethod(name: Name, flags: Long, mtype: Symbol => Type, method: MethodInfo, statik: Boolean): Symbol = {
+    val methodSym: Symbol = (if (statik)  statics else clazz).newMethod(NoPosition, name)
+    methodSym.setFlag(flags).setInfo(mtype(methodSym))
+    (if (statik) staticDefs else instanceDefs).enter(methodSym)
     if (method != null)
-      clrTypes.methods(methodSym)  = method;
+      clrTypes.methods(methodSym)  = method
     methodSym
   }
 
@@ -312,12 +314,12 @@ abstract class TypeParser {
     // create the forward view: delegate => function
     val delegateParamTypes: List[Type] = List(typClrType);
     // not ImplicitMethodType, this is for methods with implicit parameters (not implicit methods)
-    val forwardViewMethodType = JavaMethodType(delegateParamTypes, funType);
+    val forwardViewMethodType = (msym: Symbol) => JavaMethodType(msym.newSyntheticValueParams(delegateParamTypes), funType)
     val fmsym = createMethod(nme.view_, flags, forwardViewMethodType, null, true);
 
     // create the backward view: function => delegate
     val functionParamTypes: List[Type] = List(funType);
-    val backwardViewMethodType = JavaMethodType(functionParamTypes, typClrType);
+    val backwardViewMethodType = (msym: Symbol) => JavaMethodType(msym.newSyntheticValueParams(functionParamTypes), typClrType)
     val bmsym = createMethod(nme.view_, flags, backwardViewMethodType, null, true);
   }
 
@@ -350,23 +352,23 @@ abstract class TypeParser {
 
   //##########################################################################
 
-  private def methodType(method: MethodBase, rettype: MSILType): Type = {
+  private def methodType(method: MethodBase, rettype: MSILType): Symbol => Type = {
     val rtype = getCLSType(rettype);
     if (rtype == null) null else methodType(method, rtype);
   }
 
   /** Return a method type for the given method. */
-  private def methodType(method: MethodBase, rettype: Type): Type =
+  private def methodType(method: MethodBase, rettype: Type): Symbol => Type =
     methodType(method.GetParameters().map(_.ParameterType), rettype);
 
   /** Return a method type for the provided argument types and return type. */
-  private def methodType(argtypes: Array[MSILType], rettype: Type): Type = {
+  private def methodType(argtypes: Array[MSILType], rettype: Type): Symbol => Type = {
     def paramType(typ: MSILType): Type =
       if (typ eq clrTypes.OBJECT) definitions.AnyClass.tpe
       else getCLSType(typ);
     val ptypes = argtypes.map(paramType).toList;
     if (ptypes.contains(null)) null
-    else JavaMethodType(ptypes, rettype);
+    else method => JavaMethodType(method.newSyntheticValueParams(ptypes), rettype);
   }
 
     //##########################################################################
diff --git a/src/compiler/scala/tools/nsc/transform/AddInterfaces.scala b/src/compiler/scala/tools/nsc/transform/AddInterfaces.scala
index 1cb6b22..77d0fda 100644
--- a/src/compiler/scala/tools/nsc/transform/AddInterfaces.scala
+++ b/src/compiler/scala/tools/nsc/transform/AddInterfaces.scala
@@ -1,10 +1,10 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author Martin Odersky
  */
-// $Id: AddInterfaces.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.tools.nsc.transform
+package scala.tools.nsc
+package transform
 
 import symtab._
 import Flags._
@@ -13,7 +13,6 @@ import collection.mutable.{HashMap, ListBuffer}
 abstract class AddInterfaces extends InfoTransform {
   import global._                  // the global environment
   import definitions._             // standard classes and methods
-  import posAssigner.atPos         // for filling in tree positions 
 
   /** <p>
    *    The phase sets <code>lateINTERFACE</code> for non-interface traits
@@ -77,11 +76,17 @@ abstract class AddInterfaces extends InfoTransform {
       atPhase(implClassPhase) {
         val implName = nme.implClassName(iface.name)
         var impl = if (iface.owner.isClass) iface.owner.info.decl(implName) else NoSymbol
+        if (impl != NoSymbol && settings.XO.value) {
+          log("unlinking impl class " + impl)
+          iface.owner.info.decls.unlink(impl)
+          impl = NoSymbol
+        }
         if (impl == NoSymbol) {
           impl = iface.cloneSymbolImpl(iface.owner)
           impl.name = implName
+          impl.sourceFile = iface.sourceFile
           if (iface.owner.isClass)
-            iface.owner.info.decls enter impl 
+            iface.owner.info.decls enter impl
         }
         if (currentRun.compiles(iface)) currentRun.symSource(impl) = iface.sourceFile
         impl setPos iface.pos
@@ -110,7 +115,7 @@ abstract class AddInterfaces extends InfoTransform {
    *  </p>
    *  <ul>
    *    <li>
-   *      for every interface member of <code>iface</code> its implemention
+   *      for every interface member of <code>iface</code> its implementation
    *      method, if one is needed.
    *    </li>
    *    <li>
@@ -128,14 +133,14 @@ abstract class AddInterfaces extends InfoTransform {
      *  @return           ...
      */
     private def implDecls(implClass: Symbol, ifaceDecls: Scope): Scope = {
-      val decls = newScope
+      val decls = new Scope
       if ((ifaceDecls lookup nme.MIXIN_CONSTRUCTOR) == NoSymbol)
         decls enter (implClass.newMethod(implClass.pos, nme.MIXIN_CONSTRUCTOR) 
                      setInfo MethodType(List(), UnitClass.tpe))
-      for (val sym <- ifaceDecls.elements) {
+      for (sym <- ifaceDecls.iterator) {
         if (isInterfaceMember(sym)) {
           if (needsImplMethod(sym)) {
-            val impl = sym.cloneSymbol(implClass).setInfo(sym.info).resetFlag(lateDEFERRED)
+            val impl = sym.cloneSymbol(implClass).resetFlag(lateDEFERRED)
             if (currentRun.compiles(implClass)) implMethodMap(sym) = impl
             decls enter impl
             sym setFlag lateDEFERRED
@@ -154,9 +159,10 @@ abstract class AddInterfaces extends InfoTransform {
     override def complete(sym: Symbol) {
       def implType(tp: Type): Type = tp match {
         case ClassInfoType(parents, decls, _) =>
-          assert(phase == implClassPhase, sym)
+          assert(phase == implClassPhase)
           ClassInfoType(
-            ObjectClass.tpe :: (parents.tail map mixinToImplClass) ::: List(iface.tpe),
+            ObjectClass.tpe :: (parents.tail map mixinToImplClass filter (_.typeSymbol != ObjectClass))
+              ::: List(iface.tpe),
             implDecls(sym, decls),
             sym)
         case PolyType(tparams, restpe) =>
@@ -225,11 +231,11 @@ abstract class AddInterfaces extends InfoTransform {
 
   private def ifaceMemberDef(tree: Tree): Tree =
     if (!tree.isDef || !isInterfaceMember(tree.symbol)) EmptyTree
-    else if (needsImplMethod(tree.symbol)) DefDef(tree.symbol, vparamss => EmptyTree)
+    else if (needsImplMethod(tree.symbol)) DefDef(tree.symbol, EmptyTree)
     else tree
 
   private def ifaceTemplate(templ: Template): Template =
-    copy.Template(templ, templ.parents, emptyValDef, templ.body map ifaceMemberDef)
+    treeCopy.Template(templ, templ.parents, emptyValDef, templ.body map ifaceMemberDef)
 
   private def implMethodDef(tree: Tree, ifaceMethod: Symbol): Tree =
     implMethodMap.get(ifaceMethod) match {
@@ -237,7 +243,7 @@ abstract class AddInterfaces extends InfoTransform {
         tree.symbol = implMethod
         new ChangeOwnerAndReturnTraverser(ifaceMethod, implMethod)(tree)
       case None =>
-        throw new Error("implMethod missing for " + ifaceMethod)
+        abort("implMethod missing for " + ifaceMethod)
     }
 
   private def implMemberDef(tree: Tree): Tree =
@@ -251,7 +257,7 @@ abstract class AddInterfaces extends InfoTransform {
    */
   private def addMixinConstructorDef(clazz: Symbol, stats: List[Tree]): List[Tree] = 
     if (treeInfo.firstConstructor(stats) != EmptyTree) stats
-    else DefDef(clazz.primaryConstructor, vparamss => Block(List(), Literal(()))) :: stats
+    else DefDef(clazz.primaryConstructor, Block(List(), Literal(()))) :: stats
     
   private def implTemplate(clazz: Symbol, templ: Template): Template = atPos(templ.pos) {
     val templ1 = atPos(templ.pos) {
@@ -265,7 +271,7 @@ abstract class AddInterfaces extends InfoTransform {
 
   def implClassDefs(trees: List[Tree]): List[Tree] = {
     val buf = new ListBuffer[Tree]
-    for (val tree <- trees)
+    for (tree <- trees)
       tree match {
         case ClassDef(_, _, _, impl) =>
           if (tree.symbol.needsImplClass)
@@ -288,15 +294,16 @@ abstract class AddInterfaces extends InfoTransform {
       Apply(Select(This(clazz), impl.primaryConstructor), List())
     }
     val mixinConstructorCalls: List[Tree] = {
-      for (val mc <- clazz.mixinClasses.reverse;
-           mc.hasFlag(lateINTERFACE) && mc != ScalaObjectClass)
+      for (mc <- clazz.mixinClasses.reverse
+           if mc.hasFlag(lateINTERFACE) && mc != ScalaObjectClass)
       yield mixinConstructorCall(implClass(mc))
     }
     (tree: @unchecked) match {
       case Block(stats, expr) =>
-        val (presuper, supercall :: rest) = stats span (_.symbol.hasFlag(PRESUPER))
+        // needs `hasSymbol' check because `supercall' could be a block (named / default args)
+        val (presuper, supercall :: rest) = stats span (t => t.hasSymbol && t.symbol.hasFlag(PRESUPER))
         //assert(supercall.symbol.isClassConstructor, supercall)
-        copy.Block(tree, presuper ::: (supercall :: mixinConstructorCalls ::: rest), expr)
+        treeCopy.Block(tree, presuper ::: (supercall :: mixinConstructorCalls ::: rest), expr)
     }
   }
 
@@ -309,14 +316,14 @@ abstract class AddInterfaces extends InfoTransform {
       val tree1 = tree match {
         case ClassDef(mods, name, tparams, impl) if (sym.needsImplClass) =>
           implClass(sym).initialize // to force lateDEFERRED flags
-          copy.ClassDef(tree, mods | INTERFACE, name, tparams, ifaceTemplate(impl))
+          treeCopy.ClassDef(tree, mods | INTERFACE, name, tparams, ifaceTemplate(impl))
         case DefDef(mods, name, tparams, vparamss, tpt, rhs) 
         if (sym.isClassConstructor && sym.isPrimaryConstructor && sym.owner != ArrayClass) =>
-          copy.DefDef(tree, mods, name, tparams, vparamss, tpt, 
+          treeCopy.DefDef(tree, mods, name, tparams, vparamss, tpt, 
                       addMixinConstructorCalls(rhs, sym.owner)) // (3)
         case Template(parents, self, body) =>
           val parents1 = sym.owner.info.parents map (t => TypeTree(t) setPos tree.pos)
-          copy.Template(tree, parents1, emptyValDef, body)
+          treeCopy.Template(tree, parents1, emptyValDef, body)
         case This(_) =>
           if (sym.needsImplClass) {
             val impl = implClass(sym)
@@ -338,7 +345,7 @@ abstract class AddInterfaces extends InfoTransform {
               else mix
             }
           if (sym.needsImplClass) Super(implClass(sym), mix1) setPos tree.pos
-          else copy.Super(tree, qual, mix1)
+          else treeCopy.Super(tree, qual, mix1)
 */
         case _ =>
           tree
diff --git a/src/compiler/scala/tools/nsc/transform/CleanUp.scala b/src/compiler/scala/tools/nsc/transform/CleanUp.scala
index c59c036..1a77e14 100644
--- a/src/compiler/scala/tools/nsc/transform/CleanUp.scala
+++ b/src/compiler/scala/tools/nsc/transform/CleanUp.scala
@@ -1,20 +1,19 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyrights 2005-2010 LAMP/EPFL
  * @author Martin Odersky
  */
-// $Id: CleanUp.scala 17454 2009-04-07 16:11:31Z odersky $
 
-package scala.tools.nsc.transform
+package scala.tools.nsc
+package transform
 
 import symtab._
 import Flags._
-import scala.tools.nsc.util.Position
-import scala.collection.mutable.{ListBuffer, HashMap}
+import scala.collection._
 
-abstract class CleanUp extends Transform {
+abstract class CleanUp extends Transform with ast.TreeDSL {
   import global._
   import definitions._
-  import posAssigner.atPos
+  import CODE._
 
   /** the following two members override abstract members in Transform */
   val phaseName: String = "cleanup"
@@ -23,172 +22,60 @@ abstract class CleanUp extends Transform {
     new CleanUpTransformer(unit)
 
   class CleanUpTransformer(unit: CompilationUnit) extends Transformer {
-
-    private val MethodClass = if (forCLDC || forMSIL) null
-                              else definitions.getClass("java.lang.reflect.Method")
-    private val newDefs = new ListBuffer[Tree]
-    private val classConstantMeth = new HashMap[String, Symbol]
-
-    // a map from the symbols of the Scala primitive types to the symbols
-    // of the modules of the Java box classes
-    private val javaBoxClassModule = new HashMap[Symbol, Symbol]
-
-    if (!forMSIL) {
-      javaBoxClassModule(BooleanClass) = getModule("java.lang.Boolean")
-      javaBoxClassModule(ByteClass)    = getModule("java.lang.Byte")
-      javaBoxClassModule(ShortClass)   = getModule("java.lang.Short")
-      javaBoxClassModule(IntClass)     = getModule("java.lang.Integer")
-      javaBoxClassModule(CharClass)    = getModule("java.lang.Character")
-      javaBoxClassModule(LongClass)    = getModule("java.lang.Long")
-      if (!forCLDC) {
-        javaBoxClassModule(FloatClass)   = getModule("java.lang.Float")
-        javaBoxClassModule(DoubleClass)  = getModule("java.lang.Double")
-        javaBoxClassModule(UnitClass)    = getModule("java.lang.Void")
-      }
-    }
+    private val newStaticMembers = mutable.Buffer.empty[Tree]
+    private val newStaticInits = mutable.Buffer.empty[Tree]
+    private val symbolsStoredAsStatic = mutable.Map.empty[String, Symbol]
+    
+    //private val classConstantMeth = new HashMap[String, Symbol]
+    //private val symbolStaticFields = new HashMap[String, (Symbol, Tree, Tree)]
 
     private var localTyper: analyzer.Typer = null
 
-    private def classConstantMethod(pos: Position, sig: String): Symbol = classConstantMeth.get(sig) match {
-      case Some(meth) =>
-        meth
-      case None =>
-        val forName = getMember(ClassClass.linkedModuleOfClass, nme.forName)
-        val owner = currentOwner.enclClass
-
-        val cvar = owner.newVariable(pos, unit.fresh.newName(pos, "class$Cache"))
-          .setFlag(PRIVATE | STATIC | MUTABLE | SYNTHETIC).setInfo(ClassClass.tpe)
-        owner.info.decls.enter(cvar)
-        val cdef =
-          localTyper.typed {
-            atPos(pos) {
-              ValDef(cvar, Literal(Constant(null)))
-            }
-          }
-
-        val meth = owner.newMethod(pos, unit.fresh.newName(pos, "class$Method"))
-          .setFlag(PRIVATE | STATIC | SYNTHETIC).setInfo(MethodType(List(), ClassClass.tpe))
-        owner.info.decls.enter(meth)
-        val mdef = 
-          localTyper.typed {
-            atPos(pos) {
-              DefDef(meth, vparamss =>
-                gen.mkCached(
-                  cvar,
-                  Apply(
-                    gen.mkAttributedRef(forName), List(Literal(sig)))))
-            }
-          }
+    private lazy val serializableAnnotation =
+      AnnotationInfo(SerializableAttr.tpe, Nil, Nil)
+    private lazy val serialVersionUIDAnnotation = {
+      val attr = definitions.getClass("scala.SerialVersionUID")
+      AnnotationInfo(attr.tpe, List(Literal(Constant(0))), List())
+    }
 
-        newDefs.append(cdef, mdef);
-        classConstantMeth.update(sig, meth)
-        meth
+    private object MethodDispatchType extends scala.Enumeration {
+      val NO_CACHE, MONO_CACHE, POLY_CACHE = Value
     }
-    
-    private val existingReflectiveMethodCache = new HashMap[(String, List[Type]), Symbol]
-        
-    /* Transforms a list of types into a list of trees representing these types
-     * as java.lang.Class instances. */
-    private def paramTypeClasses(paramTypes: List[Type]): List[Tree] =
-      paramTypes map { pt => Literal(Constant(pt)) }
-    
-    private def reflectiveMethodCache(pos: Position, method: String, paramTypes: List[Type]): Symbol =
-      existingReflectiveMethodCache.get((method, paramTypes)) match {
-        case Some(cache) => cache
-        case None =>
-          val owner = currentOwner.enclClass
-          
-          val rmvar = owner.newVariable(pos, unit.fresh.newName(pos, "reflMethod$Cache"))
-            .setFlag(PRIVATE | STATIC | MUTABLE | SYNTHETIC)
-            .setInfo(MethodClass.tpe)
-          owner.info.decls.enter(rmvar)
-          val rmdef =
-            localTyper.typed {
-              atPos(pos) {
-                ValDef(rmvar, Literal(Constant(null)))
-              }
-            }
-          
-          val rmcvar = owner.newVariable(pos, unit.fresh.newName(pos, "reflClass$Cache"))
-            .setFlag(PRIVATE | STATIC | MUTABLE | SYNTHETIC)
-            .setInfo(ClassClass.tpe)
-          owner.info.decls.enter(rmcvar)
-          val rmcdef =
-            localTyper.typed {
-              atPos(pos) {
-                ValDef(rmcvar, Literal(Constant(null)))
-              }
-            }
-          
-          val rmmeth = owner.newMethod(pos, unit.fresh.newName(pos, "reflMethod$Method"))
-            .setFlag(STATIC | SYNTHETIC)
-            .setInfo(MethodType(List(ClassClass.tpe), MethodClass.tpe))
-          owner.info.decls.enter(rmmeth)
-          val rmmdef = 
-            localTyper.typed {
-              atPos(pos) {
-                DefDef(rmmeth, { vparamss =>
-                  val callClass = vparamss(0)(0)
-                  Block(
-                    List(
-                      If(
-                        gen.mkOr(
-                          Apply(Select(Select(This(owner), rmvar), nme.eq), List(Literal(Constant(null)))),
-                          Apply(Select(Select(This(owner), rmcvar), nme.ne), List(gen.mkAttributedRef(callClass)))
-                        ),
-                        Block(
-                          List(
-                            Assign(
-                              Select(This(owner), rmvar),
-                              Apply(
-                                Select(
-                                  gen.mkAttributedRef(callClass),
-                                  ClassClass.tpe.member(nme.getMethod_)
-                                ),
-                                List(
-                                  Literal(Constant(method)),
-                                  ArrayValue(TypeTree(ClassClass.tpe), paramTypeClasses(paramTypes))
-                                )
-                              )
-                            ),
-                            Assign(Select(This(owner), rmcvar), gen.mkAttributedRef(callClass))
-                          ),
-                          Literal(Constant(()))
-                        ),
-                        EmptyTree
-                      )
-                    ),
-                    Select(This(owner), rmvar)
-                  )
-                })
-              }
-            }
-          
-          newDefs.append(transform(rmdef), transform(rmcdef), transform(rmmdef));
-          existingReflectiveMethodCache.update((method, paramTypes), rmmeth)
-          rmmeth
-      }
-    
+    import MethodDispatchType.{ NO_CACHE, MONO_CACHE, POLY_CACHE }
+    private def dispatchType() = settings.refinementMethodDispatch.value match {
+      case "no-cache"   => NO_CACHE
+      case "mono-cache" => MONO_CACHE
+      case "poly-cache" => POLY_CACHE
+    }
+      
+    private def typedWithPos(pos: Position)(tree: Tree) =
+      localTyper typed { atPos(pos)(tree) }
+
     override def transformUnit(unit: CompilationUnit) =
       unit.body = transform(unit.body)
         
     /** A value class is defined to be only Java-compatible values: unit is
       * not part of it, as opposed to isValueClass in definitions. scala.Int is
       * a value class, java.lang.Integer is not. */
-    def isValueClass(sym: Symbol) = boxedClass contains sym
+    def isJavaValueClass(sym: Symbol) = boxedClass contains sym
+    def isJavaValueType(tp: Type) = isJavaValueClass(tp.typeSymbol)
+    
+    /** The boxed type if it's a primitive; identity otherwise.
+     */
+    def toBoxedType(tp: Type) = if (isJavaValueType(tp)) boxedClass(tp.typeSymbol).tpe else tp
 
     override def transform(tree: Tree): Tree = tree match {
         
       /* Transforms dynamic calls (i.e. calls to methods that are undefined
        * in the erased type space) to -- dynamically -- unsafe calls using
        * reflection. This is used for structural sub-typing of refinement
-       * types.
+       * types, but may be used for other dynamic calls in the future.
        * For 'a.f(b)' it will generate something like:
        * 'a.getClass().
        * '  getMethod("f", Array(classOf[b.type])).
        * '  invoke(a, Array(b)) 
        * plus all the necessary casting/boxing/etc. machinery required
-       * for type-compatibility (see fixResult and fixParams).
+       * for type-compatibility (see fixResult).
        * 
        * USAGE CONTRACT:
        * There are a number of assumptions made on the way a dynamic apply
@@ -198,345 +85,470 @@ abstract class CleanUp extends Transform {
        *   that an argument tree typed as AnyVal has already been extended
        *   with the necessary boxing calls. This implies that passed
        *   arguments might not be strictly compatible with the method's
-       *   parameter types (a boxed integeer while int is expected).
+       *   parameter types (a boxed integer while int is expected).
        * - The expected return type is an AnyRef, even when the method's
        *   return type is an AnyVal. This means that the tree containing the
        *   call has already been extended with the necessary unboxing calls
-       *   (or keeps the boxed type).
+       *   (or is happy with the boxed type).
        * - The type-checker has prevented dynamic applies on methods which
        *   parameter's erased types are not statically known at the call site.
        *   This is necessary to allow dispatching the call to the correct
-       *   method (dispatching on paramters is static in Scala). In practice,
+       *   method (dispatching on parameters is static in Scala). In practice,
        *   this limitation only arises when the called method is defined as a
        *   refinement, where the refinement defines a parameter based on a
        *   type variable. */
-      case ad at ApplyDynamic(qual, params) =>
+      case ad at ApplyDynamic(qual0, params) =>        
+        def mkName(s: String = "") =
+          if (s == "") unit.fresh newName ad.pos
+          else unit.fresh.newName(ad.pos, s)
+        def mkTerm(s: String = "") = newTermName(mkName(s))
+        val typedPos = typedWithPos(ad.pos) _
+        
         assert(ad.symbol.isPublic)
+        var qual: Tree = qual0
+          
+        /* ### CREATING THE METHOD CACHE ### */
         
-        val testForNumber: Tree =
-          gen.mkOr(
-            Apply(
-              TypeApply(
-                gen.mkAttributedSelect(qual, definitions.Object_isInstanceOf),
-                List(TypeTree(BoxedNumberClass.tpe.normalize))
-              ),
-              List()
-            ),
-            Apply(
-              TypeApply(
-                gen.mkAttributedSelect(qual, definitions.Object_isInstanceOf),
-                List(TypeTree(BoxedCharacterClass.tpe.normalize))
-              ),
-              List()
-            )
-          )
+        def addStaticVariableToClass(forName: String, forType: Type, forInit: Tree, isFinal: Boolean): Symbol = {
+          val varSym = currentClass.newVariable(ad.pos, mkName(forName))
+            .setFlag(PRIVATE | STATIC | MUTABLE | SYNTHETIC)
+            .setInfo(forType)
+          if (isFinal) varSym setFlag FINAL else varSym addAnnotation AnnotationInfo(VolatileAttr.tpe, Nil, Nil)
+          currentClass.info.decls enter varSym
+          
+          val varDef = typedPos( VAL(varSym) === forInit )
+          newStaticMembers append transform(varDef)
+          
+          val varInit = typedPos( REF(varSym) === forInit )
+          newStaticInits append transform(varInit)
+          
+          varSym
+        }
         
-        val testForBoolean: Tree =
-          Apply(
-            TypeApply(
-              gen.mkAttributedSelect(qual, definitions.Object_isInstanceOf),
-              List(TypeTree(BoxedBooleanClass.tpe.normalize))
-            ),
-            List()
-          )
+        def addStaticMethodToClass(forName: String, forArgsTypes: List[Type], forResultType: Type)
+                                  (forBody: Pair[Symbol, List[Symbol]] => Tree): Symbol = {
+          val methSym = currentClass.newMethod(ad.pos, mkName(forName))
+            .setFlag(STATIC | SYNTHETIC)
+            
+          methSym.setInfo(MethodType(methSym.newSyntheticValueParams(forArgsTypes), forResultType))
+          currentClass.info.decls enter methSym
+          
+          val methDef = typedPos( DefDef(methSym, { forBody(Pair(methSym, methSym.paramss(0))) }) )
+          newStaticMembers append transform(methDef)
+          
+          methSym
+        }
+        
+        def fromTypesToClassArrayLiteral(paramTypes: List[Type]): Tree =
+          ArrayValue(TypeTree(ClassClass.tpe), paramTypes map LIT)
         
-        val testForNumberOrBoolean: Tree = gen.mkOr(testForNumber, testForBoolean)
+        def theTypeClassArray =
+          TypeRef(ArrayClass.tpe.prefix, ArrayClass, List(ClassClass.tpe))
         
-        def getPrimitiveReplacementForStructuralCall: PartialFunction[Name, (Symbol, Tree)] = {
-        /* Unary arithmetic */
-          case nme.UNARY_+ =>
-            (definitions.getMember(definitions.BoxesRunTimeClass, newTermName("positive")), testForNumber)
-          case nme.UNARY_- =>
-            (definitions.getMember(definitions.BoxesRunTimeClass, newTermName("negate")), testForNumber)
-        /* Unary logic */
-          case nme.UNARY_~ =>
-            (definitions.getMember(definitions.BoxesRunTimeClass, newTermName("complement")), testForNumber)
-          case nme.UNARY_! =>
-            (definitions.getMember(definitions.BoxesRunTimeClass, newTermName("takeNot")), testForBoolean)
-        /* Binary arithmetic */
-          case nme.ADD =>
-            (definitions.getMember(definitions.BoxesRunTimeClass, newTermName("add")), testForNumber)
-          case nme.SUB =>
-            (definitions.getMember(definitions.BoxesRunTimeClass, newTermName("subtract")), testForNumber)
-          case nme.MUL =>
-            (definitions.getMember(definitions.BoxesRunTimeClass, newTermName("multiply")), testForNumber)
-          case nme.DIV =>
-            (definitions.getMember(definitions.BoxesRunTimeClass, newTermName("divide")), testForNumber)
-          case nme.MOD =>
-            (definitions.getMember(definitions.BoxesRunTimeClass, newTermName("takeModulo")), testForNumber)
-        /* Binary logic */
-          case nme.OR =>
-            (definitions.getMember(definitions.BoxesRunTimeClass, newTermName("takeOr")), testForNumberOrBoolean)
-          case nme.XOR =>
-            (definitions.getMember(definitions.BoxesRunTimeClass, newTermName("takeXor")), testForNumberOrBoolean)
-          case nme.AND =>
-            (definitions.getMember(definitions.BoxesRunTimeClass, newTermName("takeAnd")), testForNumberOrBoolean)
-          case nme.ZOR =>
-            (definitions.getMember(definitions.BoxesRunTimeClass, newTermName("takeConditionalOr")), testForBoolean)
-          case nme.ZAND =>
-            (definitions.getMember(definitions.BoxesRunTimeClass, newTermName("takeConditionalAnd")), testForBoolean)
-        /* Shifting */
-          case nme.LSL =>
-            (definitions.getMember(definitions.BoxesRunTimeClass, newTermName("shiftSignedLeft")), testForNumber)
-          case nme.LSR =>
-            (definitions.getMember(definitions.BoxesRunTimeClass, newTermName("shiftSignedRight")), testForNumber)
-          case nme.ASR =>
-            (definitions.getMember(definitions.BoxesRunTimeClass, newTermName("shiftLogicalRight")), testForNumber)
-          case nme.EQ => 
-            (definitions.getMember(definitions.BoxesRunTimeClass, newTermName("testEqual")), testForNumberOrBoolean)
-          case nme.NE => 
-            (definitions.getMember(definitions.BoxesRunTimeClass, newTermName("testNotEqual")), testForNumberOrBoolean)
-          case nme.LT => 
-            (definitions.getMember(definitions.BoxesRunTimeClass, newTermName("testLessThan")), testForNumber)
-          case nme.LE => 
-            (definitions.getMember(definitions.BoxesRunTimeClass, newTermName("testLessOrEqualThan")), testForNumber)
-          case nme.GE => 
-            (definitions.getMember(definitions.BoxesRunTimeClass, newTermName("testGreaterOrEqualThan")), testForNumber)
-          case nme.GT => 
-            (definitions.getMember(definitions.BoxesRunTimeClass, newTermName("testGreaterThan")), testForNumber)
-        /* Conversions */
-          case nme.toByte =>
-            (definitions.getMember(definitions.BoxesRunTimeClass, newTermName("toByte")), testForNumber)
-          case nme.toShort =>
-            (definitions.getMember(definitions.BoxesRunTimeClass, newTermName("toShort")), testForNumber)
-          case nme.toChar =>
-            (definitions.getMember(definitions.BoxesRunTimeClass, newTermName("toCharacter")), testForNumber)
-          case nme.toInt =>
-            (definitions.getMember(definitions.BoxesRunTimeClass, newTermName("toInteger")), testForNumber)
-          case nme.toLong =>
-            (definitions.getMember(definitions.BoxesRunTimeClass, newTermName("toLong")), testForNumber)
-          case nme.toFloat =>
-            (definitions.getMember(definitions.BoxesRunTimeClass, newTermName("toFloat")), testForNumber)
-          case nme.toDouble =>
-            (definitions.getMember(definitions.BoxesRunTimeClass, newTermName("toDouble")), testForNumber)
+        /* ... */
+        def reflectiveMethodCache(method: String, paramTypes: List[Type]): Symbol = dispatchType match {
+          case NO_CACHE =>
+              
+              /* Implementation of the cache is as follows for method "def xyz(a: A, b: B)":
+                
+                var reflParams$Cache: Array[Class[_]] = Array[JClass](classOf[A], classOf[B])
+                
+                def reflMethod$Method(forReceiver: JClass[_]): JMethod =
+                  forReceiver.getMethod("xyz", reflParams$Cache)
+              
+              */
+
+              val reflParamsCacheSym: Symbol =
+                addStaticVariableToClass("reflParams$Cache", theTypeClassArray, fromTypesToClassArrayLiteral(paramTypes), true)
+              
+              addStaticMethodToClass("reflMethod$Method", List(ClassClass.tpe), MethodClass.tpe) {
+                case Pair(reflMethodSym, List(forReceiverSym)) =>
+                  (REF(forReceiverSym) DOT Class_getMethod)(LIT(method), REF(reflParamsCacheSym))
+              }
+              
+            case MONO_CACHE =>
+              
+              /* Implementation of the cache is as follows for method "def xyz(a: A, b: B)"
+                 (but with a SoftReference wrapping reflClass$Cache, similarly in the poly Cache) :
+                
+                var reflParams$Cache: Array[Class[_]] = Array[JClass](classOf[A], classOf[B])
+              
+                var reflMethod$Cache: JMethod = null
+                
+                var reflClass$Cache: JClass[_] = null
+                
+                def reflMethod$Method(forReceiver: JClass[_]): JMethod = {
+                  if (reflClass$Cache != forReceiver) {
+                    reflMethod$Cache = forReceiver.getMethod("xyz", reflParams$Cache)
+                    reflClass$Cache = forReceiver
+                  }
+                  reflMethod$Cache
+                }
+              
+              */
+              
+              val reflParamsCacheSym: Symbol =
+                addStaticVariableToClass("reflParams$Cache", theTypeClassArray, fromTypesToClassArrayLiteral(paramTypes), true)
+              
+              val reflMethodCacheSym: Symbol =
+                addStaticVariableToClass("reflMethod$Cache", MethodClass.tpe, NULL, false)
+              
+              val reflClassCacheSym: Symbol =
+                addStaticVariableToClass("reflClass$Cache", SoftReferenceClass.tpe, NULL, false)
+                
+              def getMethodSym = ClassClass.tpe member nme.getMethod_
+              
+              def isCacheEmpty(receiver: Symbol): Tree =
+                reflClassCacheSym.IS_NULL() OR (reflClassCacheSym.GET() ANY_NE REF(receiver))
+              
+              addStaticMethodToClass("reflMethod$Method", List(ClassClass.tpe), MethodClass.tpe) {
+                case Pair(reflMethodSym, List(forReceiverSym)) =>
+                  BLOCK(
+                    IF (isCacheEmpty(forReceiverSym)) THEN BLOCK(
+                      REF(reflMethodCacheSym) === ((REF(forReceiverSym) DOT getMethodSym)(LIT(method), REF(reflParamsCacheSym))) ,
+                      REF(reflClassCacheSym) === gen.mkSoftRef(REF(forReceiverSym)),
+                      UNIT
+                    ) ENDIF,
+                    REF(reflMethodCacheSym)
+                  )
+              }
+              
+            case POLY_CACHE =>
+              
+              /* Implementation of the cache is as follows for method "def xyz(a: A, b: B)"
+                 (SoftReference so that it does not interfere with classloader garbage collection, see ticket
+                 #2365 for details):
+                
+                var reflParams$Cache: Array[Class[_]] = Array[JClass](classOf[A], classOf[B])
+              
+                var reflPoly$Cache: SoftReference[scala.runtime.MethodCache] = new SoftReference(new EmptyMethodCache())
+                
+                def reflMethod$Method(forReceiver: JClass[_]): JMethod = {
+                  var method: JMethod = reflPoly$Cache.find(forReceiver)
+                  if (method != null)
+                    return method
+                  else {
+                    method = forReceiver.getMethod("xyz", reflParams$Cache)
+                    method.setAccessible(true) // issue #2381
+                    reflPoly$Cache = new SoftReference(reflPoly$Cache.get.add(forReceiver, method))
+                    return method
+                  }
+                }
+              
+              */
+              
+              val reflParamsCacheSym: Symbol =
+                addStaticVariableToClass("reflParams$Cache", theTypeClassArray, fromTypesToClassArrayLiteral(paramTypes), true)
+              
+              def mkNewPolyCache = gen.mkSoftRef(NEW(TypeTree(EmptyMethodCacheClass.tpe)))
+              val reflPolyCacheSym: Symbol = addStaticVariableToClass("reflPoly$Cache", SoftReferenceClass.tpe, mkNewPolyCache, false)
+              def getPolyCache = fn(REF(reflPolyCacheSym), nme.get) AS_ATTR MethodCacheClass.tpe
+              
+              addStaticMethodToClass("reflMethod$Method", List(ClassClass.tpe), MethodClass.tpe)
+                { case Pair(reflMethodSym, List(forReceiverSym)) =>
+                  val methodSym = reflMethodSym.newVariable(ad.pos, mkTerm("method")) setInfo MethodClass.tpe
+                  
+                  BLOCK(
+                    IF (getPolyCache ANY_EQ NULL) THEN (REF(reflPolyCacheSym) === mkNewPolyCache) ENDIF,
+                    VAL(methodSym) === ((getPolyCache DOT methodCache_find)(REF(forReceiverSym))) ,
+                    IF (REF(methodSym) OBJ_!= NULL) .
+                      THEN (Return(REF(methodSym)))
+                    ELSE {
+                      def methodSymRHS  = ((REF(forReceiverSym) DOT Class_getMethod)(LIT(method), REF(reflParamsCacheSym)))
+                      def cacheRHS      = ((getPolyCache DOT methodCache_add)(REF(forReceiverSym), REF(methodSym)))
+                      BLOCK(
+                        REF(methodSym)        === methodSymRHS,
+                        (REF(methodSym) DOT methodClass_setAccessible)(LIT(true)),
+                        REF(reflPolyCacheSym) === gen.mkSoftRef(cacheRHS),
+                        Return(REF(methodSym))
+                      )
+                    }
+                  )
+                }
         }
         
+        /* ### HANDLING METHODS NORMALLY COMPILED TO OPERATORS ### */
+        
+        val testForNumber: Tree     = (qual IS_OBJ BoxedNumberClass.tpe) OR (qual IS_OBJ BoxedCharacterClass.tpe)
+        val testForBoolean: Tree    = (qual IS_OBJ BoxedBooleanClass.tpe)
+        val testForNumberOrBoolean  = testForNumber OR testForBoolean
+        
+        val getPrimitiveReplacementForStructuralCall: PartialFunction[Name, (Symbol, Tree)] = {
+          val testsForNumber = Map() ++ List(
+            nme.UNARY_+ -> "positive",
+            nme.UNARY_- -> "negate",
+            nme.UNARY_~ -> "complement",
+            nme.ADD     -> "add",
+            nme.SUB     -> "subtract",
+            nme.MUL     -> "multiply",
+            nme.DIV     -> "divide",
+            nme.MOD     -> "takeModulo",
+            nme.LSL     -> "shiftSignedLeft",
+            nme.LSR     -> "shiftLogicalRight",
+            nme.ASR     -> "shiftSignedRight",
+            nme.LT      -> "testLessThan",
+            nme.LE      -> "testLessOrEqualThan",
+            nme.GE      -> "testGreaterOrEqualThan",
+            nme.GT      -> "testGreaterThan",
+            nme.toByte  -> "toByte",
+            nme.toShort -> "toShort",
+            nme.toChar  -> "toCharacter",
+            nme.toInt   -> "toInteger",
+            nme.toLong  -> "toLong",
+            nme.toFloat -> "toFloat",
+            nme.toDouble-> "toDouble"
+          )
+          val testsForBoolean = Map() ++ List(
+            nme.UNARY_! -> "takeNot",
+            nme.ZOR     -> "takeConditionalOr",
+            nme.ZAND    -> "takeConditionalAnd"
+          )
+          val testsForNumberOrBoolean = Map() ++ List(
+            nme.OR      -> "takeOr",
+            nme.XOR     -> "takeXor",
+            nme.AND     -> "takeAnd",
+            nme.EQ      -> "testEqual",
+            nme.NE      -> "testNotEqual"
+          )
+          def get(name: String) = getMember(BoxesRunTimeClass, name)
+          
+          /** Begin partial function. */
+          {
+            case x if testsForNumber contains x           => (get(testsForNumber(x)), testForNumber)
+            case x if testsForBoolean contains x          => (get(testsForBoolean(x)), testForBoolean)
+            case x if testsForNumberOrBoolean contains x  => (get(testsForNumberOrBoolean(x)), testForNumberOrBoolean)
+          }
+        }
+        
+        /* ### BOXING PARAMS & UNBOXING RESULTS ### */
+        
         /* Transforms the result of a reflective call (always an AnyRef) to
          * the actual result value (an AnyRef too). The transformation
          * depends on the method's static return type.
          * - for units (void), the reflective call will return null: a new
          *   boxed unit is generated.
-         * - for arrays, the reflective call will return an unboxed array:
-         *   the resulting array is boxed.
          * - otherwise, the value is simply casted to the expected type. This
          *   is enough even for value (int et al.) values as the result of
          *   a dynamic call will box them as a side-effect. */
-        def fixResult(resType: Type)(tree: Tree): Tree =
-          localTyper.typed {
-            if (resType.typeSymbol == UnitClass)
-              Block (
-                List(tree),
-                gen.mkAttributedRef(BoxedUnit_UNIT)
-              )
-            else if (resType.typeSymbol == ArrayClass) {
-              val sym = currentOwner.newValue(tree.pos, newTermName(unit.fresh.newName(tree.pos))) setInfo ObjectClass.tpe
-              Block(
-                List(ValDef(sym, tree)),
-                If(
-                  Apply(Select(Literal(Constant(null)), Any_==), List(gen.mkAttributedRef(sym))),
-                  Literal(Constant(null)),
-                  Apply(
-                    Select(
-                      gen.mkAttributedRef(ScalaRunTimeModule),
-                      ScalaRunTimeModule.tpe.member(nme.boxArray)
-                    ),
-                    List(gen.mkAttributedRef(sym))
-                  )
-                )
-              )
-            }
-            else if (resType.typeSymbol == ObjectClass) // TODO: remove the cast always when unnecessary.
-              tree
-            else
-              gen.mkAttributedCast(tree, resType)
-          }
         
-        /* Transforms the parameters of a dynamic apply (always AnyRefs) to
-         * something compatible with reclective calls. The transformation depends
-         * on the method's static parameter types.
-         * - for (unboxed) arrays, the (non-null) value is tested for its erased
-         *   type. If it is a boxed array, the array is unboxed. If it is an
-         *   unboxed array, it is left alone. */
-        def fixParams(params: List[Tree], paramTypes: List[Type]): List[Tree] =
-          (params zip paramTypes) map { case (param, paramType) =>
-            localTyper.typed {
-              if (paramType.typeSymbol == ArrayClass) {
-                val sym = currentOwner.newValue(tree.pos, newTermName(unit.fresh.newName(tree.pos))) setInfo ObjectClass.tpe
-                val arrayType = {
-                  assert(paramType.typeArgs.length == 1)
-                  paramType.typeArgs(0).normalize
-                }
-                Block(
-                  List(ValDef(sym, param)),
-                  If(
-                    Apply(Select(Literal(Constant(null)), Any_==), List(gen.mkAttributedRef(sym))),
-                    Literal(Constant(null)),
-                    If(
-                      Apply(
-                        TypeApply(
-                          gen.mkAttributedSelect(gen.mkAttributedRef(sym), definitions.Object_isInstanceOf),
-                          List(TypeTree(BoxedArrayClass.tpe.normalize))
-                        ),
-                        List()
-                      ),
-                      Apply(
-                        Select(gen.mkAttributedCast(gen.mkAttributedRef(sym), BoxedArrayClass.tpe), getMember(BoxedArrayClass, nme.unbox)),
-                        List(Literal(Constant(arrayType)))
-                      ),
-                      gen.mkAttributedRef(sym)
-                    )
-                  )
-                )
-              }
-              else
-                param
+        /* ### CALLING THE APPLY ### */
+        def callAsReflective(paramTypes: List[Type], resType: Type): Tree = {
+          /* Some info about the type of the method being called. */
+          val methSym       = ad.symbol
+          val boxedResType  = toBoxedType(resType)      // Int -> Integer
+          val resultSym     = boxedResType.typeSymbol
+          // If this is a primitive method type (like '+' in 5+5=10) then the
+          // parameter types and the (unboxed) result type should all be primitive types,
+          // and the method name should be in the primitive->structural map.
+          def isJavaValueMethod = (
+            (resType :: paramTypes forall isJavaValueType) && // issue #1110
+            (getPrimitiveReplacementForStructuralCall isDefinedAt methSym.name)
+          )
+          // Erasure lets Unit through as Unit, but a method returning Any will have an
+          // erased return type of Object and should also allow Unit.
+          def isDefinitelyUnit  = (resultSym == UnitClass)
+          def isMaybeUnit       = (resultSym == ObjectClass) || isDefinitelyUnit
+          // If there's any chance this signature could be met by an Array.
+          val isArrayMethodSignature = {
+            def typesMatchApply = paramTypes match {
+              case List(tp) => tp <:< IntClass.tpe
+              case _        => false
+            }
+            def typesMatchUpdate = paramTypes match {
+              case List(tp1, tp2) => (tp1 <:< IntClass.tpe) && isMaybeUnit
+              case _              => false
             }
+                        
+            (methSym.name == nme.length && params.isEmpty) ||
+            (methSym.name == nme.clone_ && params.isEmpty) ||
+            (methSym.name == nme.apply  && typesMatchApply) ||
+            (methSym.name == nme.update && typesMatchUpdate)
           }
+
+          /* Some info about the argument at the call site. */
+          val qualSym           = qual.tpe.typeSymbol
+          val args              = qual :: params
+          def isDefinitelyArray = (qualSym == ArrayClass)
+          def isMaybeArray      = (qualSym == ObjectClass) || isDefinitelyArray
+          def isMaybeBoxed      = platform isMaybeBoxed qualSym
           
-        def callAsOperator(paramTypes: List[Type], resType: Type): Tree = localTyper.typed {
-          if (getPrimitiveReplacementForStructuralCall isDefinedAt ad.symbol.name) {
-            val (operator, test) = getPrimitiveReplacementForStructuralCall(ad.symbol.name)
-            If(
-              test,
-              Apply(
-                gen.mkAttributedRef(operator),
-                qual :: fixParams(params, paramTypes)
-              ),
-              callAsMethod(paramTypes, resType)
-            )
+          // This is complicated a bit by trying to handle Arrays correctly.
+          // Under normal circumstances if the erased return type is Object then
+          // we're not going to box it to Unit, but that is the situation with
+          // a signature like def f(x: { def update(x: Int, y: Long): Any })
+          //
+          // However we only want to do that boxing if it has been determined
+          // to be an Array and a method returning Unit.  But for this fixResult
+          // could be called in one place: instead it is called separately from the
+          // unconditional outcomes (genValueCall, genArrayCall, genDefaultCall.)
+          def fixResult(tree: Tree, mustBeUnit: Boolean = false) =
+            if (mustBeUnit || resultSym == UnitClass) BLOCK(tree, REF(BoxedUnit_UNIT))  // boxed unit
+            else if (resultSym == ObjectClass) tree                                     // no cast necessary
+            else tree AS_ATTR boxedResType                                              // cast to expected type
+          
+          /** Normal non-Array call */
+          def genDefaultCall = {
+            // reflective method call machinery
+            val invokeName  = MethodClass.tpe member nme.invoke_                                // reflect.Method.invoke(...)
+            def cache       = REF(reflectiveMethodCache(ad.symbol.name.toString, paramTypes))   // cache Symbol
+            def lookup      = Apply(cache, List(qual GETCLASS))                                 // get Method object from cache
+            def invokeArgs  = ArrayValue(TypeTree(ObjectClass.tpe), params)                     // args for invocation
+            def invocation  = (lookup DOT invokeName)(qual, invokeArgs)                         // .invoke(qual, ...)
+            
+            // exception catching machinery
+            val invokeExc   = currentOwner.newValue(ad.pos, mkTerm()) setInfo InvocationTargetExceptionClass.tpe
+            def catchVar    = Bind(invokeExc, Typed(Ident(nme.WILDCARD), TypeTree(InvocationTargetExceptionClass.tpe)))
+            def catchBody   = Throw(Apply(Select(Ident(invokeExc), nme.getCause), Nil))
+          
+            // try { method.invoke } catch { case e: InvocationTargetExceptionClass => throw e.getCause() }
+            fixResult(TRY (invocation) CATCH { CASE (catchVar) ==> catchBody } ENDTRY)
           }
-          else callAsMethod(paramTypes, resType)
-        }
-        
-        def callAsMethod(paramTypes: List[Type], resType: Type): Tree = localTyper.typed {
-          val invokeExc =
-            currentOwner.newValue(tree.pos, newTermName(unit.fresh.newName(tree.pos))) setInfo InvocationTargetExceptionClass.tpe
-          Try(
-            Apply(
-              Select(
-                Apply(
-                  gen.mkAttributedRef(reflectiveMethodCache(tree.pos, ad.symbol.name.toString, paramTypes)),
-                  List(Apply(Select(qual, ObjectClass.tpe.member(nme.getClass_)), Nil))
-                ),
-                MethodClass.tpe.member(nme.invoke_)
-              ),
-              List(
-                qual,
-                ArrayValue(TypeTree(ObjectClass.tpe), fixParams(params, paramTypes))
-              )
-            ),
-            List(CaseDef(
-              Bind(invokeExc, Typed(Ident(nme.WILDCARD), TypeTree(InvocationTargetExceptionClass.tpe))),
-              EmptyTree,
-              Throw(Apply(Select(Ident(invokeExc), nme.getCause), Nil))
-            )),
-            EmptyTree
+          
+          /** A possible primitive method call, represented by methods in BoxesRunTime. */
+          def genValueCall(operator: Symbol) = fixResult(REF(operator) APPLY args)
+          def genValueCallWithTest = {
+            val (operator, test)  = getPrimitiveReplacementForStructuralCall(methSym.name)
+            IF (test) THEN genValueCall(operator) ELSE genDefaultCall
+          }
+
+          /** A native Array call. */
+          def genArrayCall = fixResult(
+            methSym.name match {
+              case nme.length => REF(boxMethod(IntClass)) APPLY (REF(arrayLengthMethod) APPLY args)
+              case nme.update => REF(arrayUpdateMethod) APPLY List(args(0), (REF(unboxMethod(IntClass)) APPLY args(1)), args(2))
+              case nme.apply  => REF(arrayApplyMethod) APPLY List(args(0), (REF(unboxMethod(IntClass)) APPLY args(1)))
+              case nme.clone_ => REF(arrayCloneMethod) APPLY List(args(0))
+            },
+            mustBeUnit = methSym.name == nme.update
+          )
+
+          /** A conditional Array call, when we can't determine statically if the argument is
+           *  an Array, but the structural type method signature is consistent with an Array method
+           *  so we have to generate both kinds of code.
+           */
+          def genArrayCallWithTest =
+            IF ((qual GETCLASS()) DOT nme.isArray) THEN genArrayCall ELSE genDefaultCall
+
+          localTyper typed (
+            if (isMaybeBoxed && isJavaValueMethod) genValueCallWithTest
+            else if (isArrayMethodSignature && isDefinitelyArray) genArrayCall
+            else if (isArrayMethodSignature && isMaybeArray) genArrayCallWithTest
+            else genDefaultCall
           )
         }
         
-        def mayRequirePrimitiveReplacement: Boolean = {
-        
-          def isBoxed(sym: Symbol): Boolean =
-            if (forCLDC) {
-              (sym isNonBottomSubClass ByteClass) ||
-              (sym isNonBottomSubClass ShortClass) ||
-              (sym isNonBottomSubClass CharClass) ||
-              (sym isNonBottomSubClass IntClass) ||
-              (sym isNonBottomSubClass LongClass)
-            }
-            else ((sym isNonBottomSubClass BoxedNumberClass) ||
-              (!forMSIL && (sym isNonBottomSubClass BoxedCharacterClass)))
+        if (settings.refinementMethodDispatch.value == "invoke-dynamic") {
+/*          val guardCallSite: Tree = {
+            val cachedClass = addStaticVariableToClass("cachedClass", definitions.ClassClass.tpe, EmptyTree)
+            val tmpVar = currentOwner.newVariable(ad.pos, unit.fresh.newName(ad.pos, "x")).setInfo(definitions.AnyRefClass.tpe)
+            atPos(ad.pos)(Block(List(
+              ValDef(tmpVar, transform(qual))),
+              If(Apply(Select(gen.mkAttributedRef(cachedClass), nme.EQ), List(getClass(Ident(tmpVar)))),
+                 Block(List(Assign(gen.mkAttributedRef(cachedClass), getClass(Ident(tmpVar)))),
+                       treeCopy.ApplyDynamic(ad, Ident(tmpVar), transformTrees(params))),
+                 EmptyTree)))
+          }
+          //println(guardCallSite)
+*/      
+          localTyper.typed(treeCopy.ApplyDynamic(ad, transform(qual), transformTrees(params)))
+        }
+        else {
           
-          val sym = qual.tpe.typeSymbol
-          (sym == definitions.ObjectClass) || isBoxed(sym)
+          /* ### BODY OF THE TRANSFORMATION -> remember we're in case ad at ApplyDynamic(qual, params) ### */
           
-        }
-        
-        /* This creates the tree that does the reflective call (see general comment
-         * on the apply-dynamic tree for its format). This tree is simply composed
-         * of three succesive calls, first to getClass on the callee, then to
-         * getMethod on the classs, then to invoke on the method.
-         * - getMethod needs an array of classes for choosing one amongst many
-         *   overloaded versions of the method. This is provided by paramTypeClasses
-         *   and must be done on the static type as Scala's dispatching is static on
-         *   the parameters.
-         * - invoke needs an array of AnyRefs that are the method's arguments. The
-         *   erasure phase guarantees that any parameter passed to a dynamic apply
-         *   is compatible (through boxing). Boxed ints et al. is what invoke expects
-         *   when the applied method expects ints, hence no change needed there.
-         *   On the other hand, arrays must be dealt with as they must be entered
-         *   unboxed in the parameter array of invoke. fixParams is responsible for 
-         *   that.
-         * - in the end, the result of invoke must be fixed, again to deal with arrays.
-         *   This is provided by fixResult. fixResult will cast the invocation's result
-         *   to the method's return type, which is generally ok, except when this type
-         *   is a value type (int et al.) in which case it must cast to the boxed version
-         *   because invoke only returns object and erasure made sure the result is
-         *   expected to be an AnyRef. */
-        val t: Tree = ad.symbol.tpe match {
-          case MethodType(paramTypes, resType) =>
-            assert(params.length == paramTypes.length)
-            atPos(tree.pos)(localTyper.typed {
-              fixResult(if (isValueClass(resType.typeSymbol)) boxedClass(resType.typeSymbol).tpe else resType) {
-                if (mayRequirePrimitiveReplacement)
-                  callAsOperator(paramTypes, resType)
-                else
-                  callAsMethod(paramTypes, resType)
+          /* This creates the tree that does the reflective call (see general comment
+           * on the apply-dynamic tree for its format). This tree is simply composed
+           * of three successive calls, first to getClass on the callee, then to
+           * getMethod on the class, then to invoke on the method.
+           * - getMethod needs an array of classes for choosing one amongst many
+           *   overloaded versions of the method. This is provided by paramTypeClasses
+           *   and must be done on the static type as Scala's dispatching is static on
+           *   the parameters.
+           * - invoke needs an array of AnyRefs that are the method's arguments. The
+           *   erasure phase guarantees that any parameter passed to a dynamic apply
+           *   is compatible (through boxing). Boxed ints et al. is what invoke expects
+           *   when the applied method expects ints, hence no change needed there.
+           * - in the end, the result of invoke must be fixed, again to deal with arrays.
+           *   This is provided by fixResult. fixResult will cast the invocation's result
+           *   to the method's return type, which is generally ok, except when this type
+           *   is a value type (int et al.) in which case it must cast to the boxed version
+           *   because invoke only returns object and erasure made sure the result is
+           *   expected to be an AnyRef. */
+          val t: Tree = ad.symbol.tpe match {
+            case MethodType(mparams, resType) =>
+              assert(params.length == mparams.length)
+              typedPos {
+                val sym = currentOwner.newValue(ad.pos, mkTerm("qual")) setInfo qual0.tpe
+                qual = REF(sym)     
+                           
+                BLOCK(
+                  VAL(sym) === qual0,
+                  callAsReflective(mparams map (_.tpe), resType)
+                )
               }
-            })
-        }
-        
-        /* For testing purposes, the dynamic application's condition
-         * can be printed-out in great detail. Remove? */
-        if (settings.debug.value) {
-          Console.println(
-            "Dynamically applying '" + qual + "." + ad.symbol.name +
-            "(" + params.map(_.toString).mkString(", ") + ")' with"
-          )
-          ad.symbol.tpe match {
-            case MethodType(paramTypes, resType) =>
-              Console.println(
-                "  - declared parameters' types: " +
-                (paramTypes.map(_.toString)).mkString("'",", ","'"))
-              Console.println(
-                "  - passed arguments' types:    " +
-                (params.map(_.toString)).mkString("'",", ","'"))
-              Console.println(
-                "  - result type:                '" +
-                resType.toString + "'")
           }
-          Console.println("  - resulting code:    '" + t + "'")
+          
+          /* For testing purposes, the dynamic application's condition
+           * can be printed-out in great detail. Remove? */
+          if (settings.debug.value) {
+            def paramsToString(xs: Any*) = xs map (_.toString) mkString ", "
+            val mstr = ad.symbol.tpe match {
+              case MethodType(mparams, resType) =>
+                """|  with
+                   |  - declared parameter types: '%s'
+                   |  - passed argument types:    '%s'
+                   |  - result type:              '%s'""" .
+                  stripMargin.format(
+                     paramsToString(mparams),
+                     paramsToString(params),
+                     resType.toString
+                  )
+              case _ => ""
+            }
+            Console.printf("""Dynamically application '%s.%s(%s)' %s - resulting code: '%s'""",
+                List(qual, ad.symbol.name, paramsToString(params), mstr, t) map (_.toString) : _*
+            )
+          }
+        
+          /* We return the dynamic call tree, after making sure no other
+           * clean-up transformation are to be applied on it. */
+          transform(t)
         }
-
-        /* We return the dynamic call tree, after making sure no other
-         * clean-up transformation are to be applied on it. */
-        transform(t)
-
-      /* end of dynamic call transformer. */
-
+        /* ### END OF DYNAMIC APPLY TRANSFORM ### */
+      
+      /* Some cleanup transformations add members to templates (classes, traits, etc).
+       * When inside a template (i.e. the body of one of its members), two maps
+       * (newStaticMembers and newStaticInits) are available in the tree transformer. Any mapping from
+       * a symbol to a MemberDef (DefDef, ValDef, etc.) that is in newStaticMembers once the
+       * transformation of the template is finished will be added as a member to the
+       * template. Any mapping from a symbol to a tree that is in newStaticInits, will be added
+       * as a statement of the form "symbol = tree" to the beginning of the default
+       * constructor. */
       case Template(parents, self, body) =>
-        localTyper = typer.atOwner(tree, currentOwner)
-        if (!forMSIL) {
-          classConstantMeth.clear
-          newDefs.clear
-          val body1 = transformTrees(body)
-          copy.Template(tree, parents, self, newDefs.toList ::: body1)
-        }
-        else super.transform(tree)
+        localTyper = typer.atOwner(tree, currentClass)
+        newStaticMembers.clear
+        newStaticInits.clear
+        symbolsStoredAsStatic.clear
+        val transformedTemplate: Template =
+          if (!forMSIL) {
+            var newBody =
+              transformTrees(body)
+            treeCopy.Template(tree, parents, self, transformTrees(newStaticMembers.toList) ::: newBody)
+          }
+          else super.transform(tree).asInstanceOf[Template]
+        addStaticInits(transformedTemplate) // postprocess to include static ctors
 
       case Literal(c) if (c.tag == ClassTag) && !forMSIL=>
         val tpe = c.typeValue
-        atPos(tree.pos) {
-          localTyper.typed {
-            if ((isValueClass(tpe.typeSymbol) || tpe.typeSymbol == definitions.UnitClass) 
-                && !forCLDC)
-              Select(gen.mkAttributedRef(javaBoxClassModule(tpe.typeSymbol)), "TYPE")
-            else if (settings.target.value != "jvm-1.5" && !forMSIL)
-              Apply(
-                gen.mkAttributedRef(classConstantMethod(tree.pos, signature(tpe))),
-                List())
-            else tree
+        typedWithPos(tree.pos) {
+          if (isValueClass(tpe.typeSymbol)) {
+            if (tpe.typeSymbol == UnitClass)
+              Select(REF(BoxedUnit_TYPE), BoxedUnit_TYPE)
+            else
+              Select(REF(boxedModule(tpe.typeSymbol)), nme.TYPE_)
           }
+
+          else tree
         }
 
       /* MSIL requires that the stack is empty at the end of a try-block.
@@ -548,34 +560,138 @@ abstract class CleanUp extends Transform {
         val tpe = theTry.tpe.widen
         val tempVar = currentOwner.newValue(theTry.pos, unit.fresh.newName(theTry.pos, "exceptionResult"))
           .setInfo(tpe).setFlag(Flags.MUTABLE)
-
-        val newBlock = super.transform(Block(Nil, Assign(Ident(tempVar), transform(block))))
-        val newCatches = for (CaseDef(pattern, guard, body) <- catches) yield {
-          CaseDef(
-            super.transform(pattern),
-            super.transform(guard),
-            Block(Nil, Assign(Ident(tempVar), super.transform(body)))
-          )
-        }
-        val newTry = Try(newBlock, newCatches, super.transform(finalizer))
-        val res = Block(List(ValDef(tempVar, EmptyTree), newTry), Ident(tempVar))
-        localTyper.typed(res)
+        def assignBlock(rhs: Tree) = super.transform(BLOCK(Ident(tempVar) === transform(rhs)))
+        
+        val newBlock    = assignBlock(block)
+        val newCatches  = for (CaseDef(pattern, guard, body) <- catches) yield
+          (CASE(super.transform(pattern)) IF (super.transform(guard))) ==> assignBlock(body)
+        val newTry      = Try(newBlock, newCatches, super.transform(finalizer))
+                
+        localTyper typed { BLOCK(VAL(tempVar) === EmptyTree, newTry, Ident(tempVar)) }
         
       /* Adds @serializable annotation to anonymous function classes */
       case cdef @ ClassDef(mods, name, tparams, impl) =>
-        if (settings.target.value == "jvm-1.4" || settings.target.value == "jvm-1.5") {
+        if (settings.target.value == "jvm-1.5") {
           val sym = cdef.symbol
           // is this an anonymous function class?
-          if (sym.hasFlag(SYNTHETIC) && (sym.name.toString.indexOf("anonfun") != -1) &&
-              !sym.hasAttribute(SerializableAttr))
-            sym.attributes =
-              AnnotationInfo(definitions.SerializableAttr.tpe, List(), List()) :: sym.attributes
+          if (sym.isAnonymousFunction && !sym.hasAnnotation(SerializableAttr)) {
+            sym addAnnotation serializableAnnotation
+            sym addAnnotation serialVersionUIDAnnotation
+          }
         }
         super.transform(tree)
 
+     /*
+      * This transformation should identify Scala symbol invocations in the tree and replace them
+      * with references to a static member. Also, whenever a class has at least a single symbol invocation
+      * somewhere in its methods, a new static member should be created and initialized for that symbol.
+      * For instance, say we have a Scala class:
+      * 
+      * class Cls {
+      *   // ...
+      *   def someSymbol = `symbolic
+      *   // ...
+      * }
+      * 
+      * After transformation, this class looks like this:
+      * 
+      * class Cls {
+      *   private "static" val <some_name>$symbolic = Symbol("symbolic")
+      *   // ...
+      *   def someSymbol = <some_name>$symbolic
+      *   // ...
+      * }
+      * 
+      * The reasoning behind this transformation is the following. Symbols get interned - they are stored
+      * in a global map which is protected with a lock. The reason for this is making equality checks
+      * quicker. But calling Symbol.apply, although it does return a unique symbol, accesses a locked object,
+      * making symbol access slow. To solve this, the unique symbol from the global symbol map in Symbol
+      * is accessed only once during class loading, and after that, the unique symbol is in the static
+      * member. Hence, it is cheap to both reach the unique symbol and do equality checks on it.
+      * 
+      * And, finally, be advised - scala symbol literal and the Symbol class of the compiler
+      * have little in common.
+      */
+      case symapp @ Apply(Select(Select(a @ Ident(nme.scala_), b @ nme.Symbol), nme.apply),
+                          List(Literal(Constant(symname: String)))) => 
+        // add the symbol name to a map if it's not there already
+        val rhs = gen.mkCast(Apply(gen.scalaDot(nme.Symbol), List(Literal(Constant(symname)))), symbolType)
+        val staticFieldSym = getSymbolStaticField(symapp.pos, symname, rhs, symapp)
+        
+        // create a reference to a static field
+        val ntree = typedWithPos(symapp.pos)(REF(staticFieldSym))
+        
+        super.transform(ntree)
       case _ =>
         super.transform(tree)
     }
+
+    /* Returns the symbol and the tree for the symbol field interning a reference to a symbol 'synmname'.
+     * If it doesn't exist, i.e. the symbol is encountered the first time,
+     * it creates a new static field definition and initialization and returns it.
+     */
+    private def getSymbolStaticField(pos: Position, symname: String, rhs: Tree, tree: Tree): Symbol =
+      symbolsStoredAsStatic.getOrElseUpdate(symname, {
+        val freshname = unit.fresh.newName(pos, "symbol$")
+        val theTyper = typer.atOwner(tree, currentClass)
+        
+        // create a symbol for the static field
+        val stfieldSym = currentClass.newVariable(pos, freshname)
+          .setFlag(PRIVATE | STATIC | SYNTHETIC | FINAL)
+          .setInfo(symbolType)
+        currentClass.info.decls enter stfieldSym
+        
+        // create field definition and initialization
+        val stfieldDef = theTyper.typed { atPos(pos)(VAL(stfieldSym) === rhs) }
+        val stfieldInit = theTyper.typed { atPos(pos)(REF(stfieldSym) === rhs) }
+        
+        // add field definition to new defs
+        newStaticMembers append stfieldDef
+        newStaticInits append stfieldInit
+        
+        stfieldSym
+      })
+
+    /* finds the static ctor DefDef tree within the template if it exists. */
+    private def findStaticCtor(template: Template): Option[Tree] =
+      template.body find { 
+        case defdef @ DefDef(mods, nme.CONSTRUCTOR, tparam, vparam, tp, rhs) => defdef.symbol hasFlag STATIC
+        case _ => false
+      }
+
+    /* changes the template for the class so that it contains a static constructor with symbol fields inits,
+     * augments an existing static ctor if one already existed.
+     */
+    private def addStaticInits(template: Template): Template =
+      if (newStaticInits.isEmpty)
+        template
+      else {
+        val newCtor = findStaticCtor(template) match {
+          // in case there already were static ctors - augment existing ones
+          // currently, however, static ctors aren't being generated anywhere else
+          case Some(ctor @ DefDef(mods, name, tparams, vparamss, tpt, rhs)) =>
+            // modify existing static ctor
+            val newBlock = rhs match {
+              case block @ Block(stats, expr) =>
+                // need to add inits to existing block
+                treeCopy.Block(block, newStaticInits.toList ::: stats, expr)
+              case term: TermTree =>
+                // need to create a new block with inits and the old term
+                treeCopy.Block(term, newStaticInits.toList, term)
+            }
+            treeCopy.DefDef(ctor, mods, name, tparams, vparamss, tpt, newBlock)
+          case None =>
+            // create new static ctor
+            val staticCtorSym = currentClass.newConstructor(template.pos)
+                                  .setFlag(STATIC)
+                                  .setInfo(UnitClass.tpe)
+            val rhs = Block(newStaticInits.toList, Literal(()))
+            val staticCtorTree = DefDef(staticCtorSym, rhs)
+            localTyper.typed { atPos(template.pos)(staticCtorTree) }
+        }
+        treeCopy.Template(template, template.parents, template.self, newCtor :: template.body)
+      }
+
   } // CleanUpTransformer
 
 }
diff --git a/src/compiler/scala/tools/nsc/transform/Constructors.scala b/src/compiler/scala/tools/nsc/transform/Constructors.scala
index 6be1353..3adb45b 100644
--- a/src/compiler/scala/tools/nsc/transform/Constructors.scala
+++ b/src/compiler/scala/tools/nsc/transform/Constructors.scala
@@ -1,10 +1,10 @@
-/* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+/*  NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
  * @author
  */
-// $Id: Constructors.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.tools.nsc.transform
+package scala.tools.nsc
+package transform
 
 import scala.collection.mutable.ListBuffer
 import symtab.Flags._
@@ -13,10 +13,10 @@ import util.TreeSet
 /** This phase converts classes with parameters into Java-like classes with 
  *  fields, which are assigned to from constructors.
  */  
-abstract class Constructors extends Transform {
+abstract class Constructors extends Transform with ast.TreeDSL {
   import global._
   import definitions._
-  import posAssigner.atPos
+  import collection.mutable
 
   /** the following two members override abstract members in Transform */
   val phaseName: String = "constructors"
@@ -24,12 +24,18 @@ abstract class Constructors extends Transform {
   protected def newTransformer(unit: CompilationUnit): Transformer =
     new ConstructorTransformer(unit)
 
+  private val guardedCtorStats: mutable.Map[Symbol, List[Tree]] = new mutable.HashMap[Symbol, List[Tree]]
+  private val ctorParams: mutable.Map[Symbol, List[Symbol]] = new mutable.HashMap[Symbol, List[Symbol]]
+
   class ConstructorTransformer(unit: CompilationUnit) extends Transformer {
 
     def transformClassTemplate(impl: Template): Template = {
       val clazz = impl.symbol.owner  // the transformed class
       val stats = impl.body          // the transformed template body
-      val localTyper = typer.atOwner(impl, clazz) 
+      val localTyper = typer.atOwner(impl, clazz)
+
+      val specializedFlag: Symbol = clazz.info.decl(nme.SPECIALIZED_INSTANCE)
+      val shouldGuard = (specializedFlag != NoSymbol) && !clazz.hasFlag(SPECIALIZED)
 
       var constr: DefDef = null      // The primary constructor
       var constrParams: List[Symbol] = null // ... and its parameters
@@ -68,25 +74,32 @@ abstract class Constructors extends Transform {
       }
 
       var thisRefSeen: Boolean = false
+      var usesSpecializedField: Boolean = false
 
       // A transformer for expressions that go into the constructor
       val intoConstructorTransformer = new Transformer {
+        def isParamRef(sym: Symbol) = 
+          (sym hasFlag PARAMACCESSOR) && 
+          sym.owner == clazz &&
+          !(sym.isGetter && sym.accessed.isVariable) &&
+          !sym.isSetter
         override def transform(tree: Tree): Tree = tree match {
           case Apply(Select(This(_), _), List()) =>
             // references to parameter accessor methods of own class become references to parameters
             // outer accessors become references to $outer parameter 
-            if ((tree.symbol hasFlag PARAMACCESSOR) && tree.symbol.owner == clazz)
+            if (isParamRef(tree.symbol))
               gen.mkAttributedIdent(parameter(tree.symbol.accessed)) setPos tree.pos
             else if (tree.symbol.outerSource == clazz && !clazz.isImplClass)
               gen.mkAttributedIdent(parameterNamed(nme.OUTER)) setPos tree.pos
             else 
               super.transform(tree)
-          case Select(This(_), _)
-          if ((tree.symbol hasFlag PARAMACCESSOR) && !tree.symbol.isSetter && tree.symbol.owner == clazz) =>
+          case Select(This(_), _) if (isParamRef(tree.symbol)) => 
             // references to parameter accessor field of own class become references to parameters
             gen.mkAttributedIdent(parameter(tree.symbol)) setPos tree.pos
           case Select(_, _) =>
             thisRefSeen = true
+            if (specializeTypes.specializedTypeVars(tree.symbol).nonEmpty)
+              usesSpecializedField = true
             super.transform(tree)
           case This(_) =>
             thisRefSeen = true
@@ -108,40 +121,39 @@ abstract class Constructors extends Transform {
       def canBeMoved(tree: Tree) = tree match {
         //todo: eliminate thisRefSeen
         case ValDef(mods, _, _, _) => 
-          if (settings.Xexperimental.value)
+          if (settings.Xwarninit.value)
             if (!(mods hasFlag PRESUPER | PARAMACCESSOR) && !thisRefSeen &&
                 { val g = tree.symbol.getter(tree.symbol.owner);
                  g != NoSymbol && !g.allOverriddenSymbols.isEmpty 
                })
               unit.warning(tree.pos, "the semantics of this definition has changed;\nthe initialization is no longer be executed before the superclass is called")
-          (mods hasFlag PRESUPER | PARAMACCESSOR) || !thisRefSeen && (!settings.future.value && !settings.checkInit.value)
+          (mods hasFlag PRESUPER | PARAMACCESSOR)// || !thisRefSeen && (!settings.future.value && !settings.checkInit.value)
         case _ => false
       }
 
       // Create an assignment to class field `to' with rhs `from'
       def mkAssign(to: Symbol, from: Tree): Tree =
         localTyper.typed {
-          atPos(to.pos) {
-            Assign(Select(This(clazz), to), from)
-          }
+          //util.trace("compiling "+unit+" ") {
+            atPos(to.pos) {
+              Assign(Select(This(clazz), to), from)
+            }
+          //}
         }
 
       // Create code to copy parameter to parameter accessor field. 
       // If parameter is $outer, check that it is not null.
       def copyParam(to: Symbol, from: Symbol): Tree = {
+        import CODE._
         var result = mkAssign(to, Ident(from))
         if (from.name == nme.OUTER)
           result =
             atPos(to.pos) {
               localTyper.typed {
-                If(
-                  Apply(
-                    Select(Ident(from), nme.eq), 
-                    List(Literal(Constant(null)))),
-                  Throw(New(TypeTree(NullPointerExceptionClass.tpe), List(List()))),
-                  result)
+                IF (from ANY_EQ NULL) THEN THROW(NullPointerExceptionClass) ELSE result
               }
             }
+            
         result
       }
 
@@ -178,7 +190,7 @@ abstract class Constructors extends Transform {
           // all methods except the primary constructor go into template
           stat.symbol.tpe match {
             case MethodType(List(), tp @ ConstantType(c)) =>
-              defBuf += copy.DefDef(
+              defBuf += treeCopy.DefDef(
                 stat, mods, name, tparams, vparamss, tpt,
                 Literal(c) setPos rhs.pos setType tp)
             case _ =>
@@ -197,7 +209,7 @@ abstract class Constructors extends Transform {
               (if (canBeMoved(stat)) constrPrefixBuf else constrStatBuf) += mkAssign(
                 stat.symbol, rhs1)
             }
-            defBuf += copy.ValDef(stat, mods, name, tpt, EmptyTree)
+            defBuf += treeCopy.ValDef(stat, mods, name, tpt, EmptyTree)
           }
         case ClassDef(_, _, _, _) =>
           // classes are treated recursively, and left in the template
@@ -218,7 +230,7 @@ abstract class Constructors extends Transform {
       // Could symbol's definition be omitted, provided it is not accessed?
       // This is the case if the symbol is defined in the current class, and
       // ( the symbol is an object private parameter accessor field, or
-      //   the symbol is an outer accessor of a final class which does not override another outer accesser. )
+      //   the symbol is an outer accessor of a final class which does not override another outer accessor. )
       def maybeOmittable(sym: Symbol) = 
         (sym.owner == clazz &&
          ((sym hasFlag PARAMACCESSOR) && sym.isPrivateLocal ||
@@ -247,7 +259,7 @@ abstract class Constructors extends Transform {
 
       // first traverse all definitions except outeraccesors 
       // (outeraccessors are avoided in accessTraverser)
-      for (stat <- defBuf.elements) accessTraverser.traverse(stat) 
+      for (stat <- defBuf.iterator) accessTraverser.traverse(stat) 
 
       // then traverse all bodies of outeraccessors which are accessed themselves
       // note: this relies on the fact that an outer accessor never calls another
@@ -255,16 +267,151 @@ abstract class Constructors extends Transform {
       for ((accSym, accBody) <- outerAccessors) 
         if (mustbeKept(accSym)) accessTraverser.traverse(accBody)
 
+      // Conflicting symbol list from parents: see bug #1960.
+      // It would be better to mangle the constructor parameter name since
+      // it can only be used internally, but I think we need more robust name
+      // mangling before we introduce more of it.
+      val parentSymbols = Map((for {
+        p <- impl.parents
+        if p.symbol.isTrait
+        sym <- p.symbol.info.nonPrivateMembers
+        if sym.isGetter && !sym.isOuterField
+      } yield sym.name -> p): _*)
+
       // Initialize all parameters fields that must be kept.
-      val paramInits = for (acc <- paramAccessors if mustbeKept(acc))
-                       yield copyParam(acc, parameter(acc))
-      
+      val paramInits = 
+        for (acc <- paramAccessors if mustbeKept(acc)) yield {          
+          if (parentSymbols contains acc.name)
+            unit.error(acc.pos, "parameter '%s' requires field but conflicts with %s in '%s'".format(
+              acc.name, acc.name, parentSymbols(acc.name)))
+          
+          copyParam(acc, parameter(acc))
+        }
+
+      /** Return a single list of statements, merging the generic class constructor with the
+       *  specialized stats. The original statements are retyped in the current class, and
+       *  assignments to generic fields that have a corresponding specialized assignment in
+       *  `specializedStats` are replaced by the specialized assignment.
+       */
+      def mergeConstructors(genericClazz: Symbol, originalStats: List[Tree], specializedStats: List[Tree]): List[Tree] = {
+        val specBuf = new ListBuffer[Tree]
+        specBuf ++= specializedStats
+
+        def specializedAssignFor(sym: Symbol): Option[Tree] =
+          specializedStats.find {
+            case Assign(sel @ Select(This(_), _), rhs) if sel.symbol.hasFlag(SPECIALIZED) =>
+              val (generic, _, _) = nme.splitSpecializedName(nme.localToGetter(sel.symbol.name))
+              generic == nme.localToGetter(sym.name)
+            case _ => false
+          }
+
+        /** Rewrite calls to ScalaRunTime.array_update to the proper apply method in scala.Array.
+         *  Erasure transforms Array.update to ScalaRunTime.update when the element type is a type
+         *  variable, but after specialization this is a concrete primitive type, so it would
+         *  be an error to pass it to array_update(.., .., Object).
+         */
+        def rewriteArrayUpdate(tree: Tree): Tree = {
+          val array_update = definitions.ScalaRunTimeModule.info.member("array_update")
+          val adapter = new Transformer {
+            override def transform(t: Tree): Tree = t match {
+              case Apply(fun @ Select(receiver, method), List(xs, idx, v)) if fun.symbol == array_update =>
+                localTyper.typed(Apply(gen.mkAttributedSelect(xs, definitions.Array_update), List(idx, v)))
+              case _ => super.transform(t)
+            }
+          }
+          adapter.transform(tree)
+        }
+
+        log("merging: " + originalStats.mkString("\n") + "\nwith\n" + specializedStats.mkString("\n"))
+        val res = for (s <- originalStats; val stat = s.duplicate) yield {
+          log("merge: looking at " + stat)
+          val stat1 = stat match {
+            case Assign(sel @ Select(This(_), field), _) =>
+              specializedAssignFor(sel.symbol).getOrElse(stat)
+            case _ => stat
+          }
+          if (stat1 ne stat) {
+            log("replaced " + stat + " with " + stat1)
+            specBuf -= stat1
+          }
+
+          if (stat1 eq stat) {
+            assert(ctorParams(genericClazz).length == constrParams.length)
+            // this is just to make private fields public
+            (new specializeTypes.ImplementationAdapter(ctorParams(genericClazz), constrParams, null, true))(stat1)
+
+            val stat2 = rewriteArrayUpdate(stat1)
+            // statements coming from the original class need retyping in the current context
+            if (settings.debug.value) log("retyping " + stat2)
+            
+            val d = new specializeTypes.Duplicator
+            d.retyped(localTyper.context1.asInstanceOf[d.Context],
+                      stat2,
+                      genericClazz,
+                      clazz,
+                      Map.empty)
+          } else
+            stat1
+        }
+        if (specBuf.nonEmpty)
+          println("residual specialized constructor statements: " + specBuf)
+        res
+      }
+
+      /** Add an 'if' around the statements coming after the super constructor. This
+       *  guard is necessary if the code uses specialized fields. A specialized field is
+       *  initialized in the subclass constructor, but the accessors are (already) overridden
+       *  and pointing to the (empty) fields. To fix this, a class with specialized fields
+       *  will not run its constructor statements if the instance is specialized. The specialized
+       *  subclass includes a copy of those constructor statements, and runs them. To flag that a class
+       *  has specialized fields, and their initialization should be deferred to the subclass, method
+       *  'specInstance$' is added in phase specialize.
+       */
+      def guardSpecializedInitializer(stats0: List[Tree]): List[Tree] = if (settings.nospecialization.value) stats0 else {
+        // split the statements in presuper and postsuper
+        var (prefix, postfix) = stats0.span(tree => !((tree.symbol ne null) && tree.symbol.isConstructor))
+        if (postfix.nonEmpty) {
+          prefix = prefix :+ postfix.head
+          postfix = postfix.tail
+        }
+
+        if (usesSpecializedField && shouldGuard && postfix.nonEmpty) {
+          // save them for duplication in the specialized subclass
+          guardedCtorStats(clazz) = postfix
+          ctorParams(clazz) = constrParams
+
+          val tree =
+            If(
+              Apply(
+                Select(
+                  Apply(gen.mkAttributedRef(specializedFlag), List()),
+                  definitions.getMember(definitions.BooleanClass, nme.UNARY_!)),
+                List()),
+              Block(postfix, Literal(())),
+              EmptyTree)
+
+          prefix ::: List(localTyper.typed(tree))
+        } else if (clazz.hasFlag(SPECIALIZED)) {
+          // add initialization from its generic class constructor
+          val (genericName, _, _) = nme.splitSpecializedName(clazz.name)
+          val genericClazz = clazz.owner.info.decl(genericName.toTypeName)
+          assert(genericClazz != NoSymbol)
+
+          guardedCtorStats.get(genericClazz) match {
+            case Some(stats1) =>
+              val merged = mergeConstructors(genericClazz, stats1, postfix)
+              prefix ::: merged
+            case None => stats0
+          }
+        } else stats0
+      }
+
       // Assemble final constructor
-      defBuf += copy.DefDef(
+      defBuf += treeCopy.DefDef(
         constr, constr.mods, constr.name, constr.tparams, constr.vparamss, constr.tpt,
-        copy.Block(
+        treeCopy.Block(
           constrBody,
-          paramInits ::: constrPrefixBuf.toList ::: constrStatBuf.toList,
+          paramInits ::: constrPrefixBuf.toList ::: guardSpecializedInitializer(constrStatBuf.toList),
           constrBody.expr));
 
       // Unlink all fields that can be dropped from class scope
@@ -272,14 +419,14 @@ abstract class Constructors extends Transform {
         if (!mustbeKept(sym)) clazz.info.decls unlink sym
 
       // Eliminate all field definitions that can be dropped from template
-      copy.Template(impl, impl.parents, impl.self, 
-                    defBuf.toList filter (stat => mustbeKept(stat.symbol)))
+      treeCopy.Template(impl, impl.parents, impl.self, 
+        defBuf.toList filter (stat => mustbeKept(stat.symbol)))
     } // transformClassTemplate
 
     override def transform(tree: Tree): Tree = 
       tree match {
         case ClassDef(mods, name, tparams, impl) if !tree.symbol.hasFlag(INTERFACE) =>
-          copy.ClassDef(tree, mods, name, tparams, transformClassTemplate(impl))
+          treeCopy.ClassDef(tree, mods, name, tparams, transformClassTemplate(impl))
         case _ =>
           super.transform(tree)
       }
diff --git a/src/compiler/scala/tools/nsc/transform/Erasure.scala b/src/compiler/scala/tools/nsc/transform/Erasure.scala
index 69491e8..fdf7f56 100644
--- a/src/compiler/scala/tools/nsc/transform/Erasure.scala
+++ b/src/compiler/scala/tools/nsc/transform/Erasure.scala
@@ -1,33 +1,88 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author Martin Odersky
  */
-// $Id: Erasure.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.tools.nsc.transform
+package scala.tools.nsc
+package transform
 
 import scala.tools.nsc.symtab.classfile.ClassfileConstants._
 import scala.collection.mutable.{HashMap,ListBuffer}
-import scala.tools.nsc.util.Position
+import scala.collection.immutable.Set
+import scala.util.control.ControlThrowable
 import symtab._
 import Flags._
 
-abstract class Erasure extends AddInterfaces with typechecker.Analyzer {
+abstract class Erasure extends AddInterfaces with typechecker.Analyzer with ast.TreeDSL
+{
   import global._                  // the global environment
   import definitions._             // standard classes and methods
-  // @S: XXX: why is this here? earsure is a typer, if you comment this
+  // @S: XXX: why is this here? erasure is a typer, if you comment this
   //          out erasure still works, uses its own typed methods.
   lazy val typerXXX = this.typer
   import typerXXX.{typed}             // methods to type trees
-  import posAssigner.atPos         // for filling in tree positions 
+  
+  import CODE._
+  def typedPos(pos: Position)(tree: Tree) = typed { atPos(pos)(tree) }
 
   val phaseName: String = "erasure"
 
   def newTransformer(unit: CompilationUnit): Transformer =
     new ErasureTransformer(unit)
 
+  override def keepsTypeParams = false
+
 // -------- erasure on types --------------------------------------------------------
 
+  /** An extractor objec for generic arrays */
+  object GenericArray {
+    
+    /** Is `tp` an unbounded generic type (i.e. which could be instantiated
+     *  with primitive as well as class types)?. 
+     */
+    private def genericCore(tp: Type): Type = tp.normalize match {
+      case TypeRef(_, argsym, _) if (argsym.isAbstractType && !(argsym.owner hasFlag JAVA)) => 
+        tp
+      case ExistentialType(tparams, restp) => 
+        genericCore(restp)
+      case _ => 
+        NoType
+    }
+
+    /** If `tp` is of the form Array[...Array[T]...] where `T` is an abstract type
+     *  then Some(N, T) where N is the number of Array constructors enclosing `T`,
+     *  otherwise None. Existentials on any level are ignored.
+     */
+    def unapply(tp: Type): Option[(Int, Type)] = tp.normalize match {
+      case TypeRef(_, ArrayClass, List(arg)) =>
+        genericCore(arg) match {
+          case NoType => 
+            unapply(arg) match {
+              case Some((level, core)) => Some((level + 1, core))
+              case None => None
+            }
+          case core => 
+            Some(1, core)
+        }
+      case ExistentialType(tparams, restp) =>
+        unapply(restp)
+      case _ =>
+        None
+    }
+  }
+
+  private def unboundedGenericArrayLevel(tp: Type): Int = tp match {
+    case GenericArray(level, core) if !(core <:< AnyRefClass.tpe) => level
+    case _ => 0
+  }
+
+  // @M #2585 when generating a java generic signature that includes a selection of an inner class p.I,  (p = `pre`, I = `cls`)
+  // must rewrite to p'.I, where p' refers to the class that directly defines the nested class I
+  // see also #2585 marker in javaSig: there, type arguments must be included (use pre.baseType(cls.owner))
+  // requires cls.isClass
+  @inline private def rebindInnerClass(pre: Type, cls: Symbol): Type =
+    if(cls.owner.isClass) cls.owner.tpe else pre // why not cls.isNestedClass?
+
   /** <p>
    *    The erasure <code>|T|</code> of a type <code>T</code>. This is:
    *  </p>
@@ -37,13 +92,13 @@ abstract class Erasure extends AddInterfaces with typechecker.Analyzer {
    *    <li>For every other singleton type, the erasure of its supertype.</li>
    *    <li>
    *      For a typeref <code>scala.Array+[T]</code> where <code>T</code> is
-   *      an abstract type, <code>scala.runtime.BoxedArray</code>.
+   *      an abstract type, <code>AnyRef</code>.
    *    </li>
    *    <li>
    *   - For a typeref scala.Array+[T] where T is not an abstract type, scala.Array+[|T|].
    *   - For a typeref scala.Any or scala.AnyVal, java.lang.Object.
    *   - For a typeref scala.Unit, scala.runtime.BoxedUnit.
-   *   - For a typeref P.C[Ts] where C refers to a class, |P|.C.
+   *   - For a typeref P.C[Ts] where C refers to a class, |P|.C. (Where P is first rebound to the class that directly defines C.)
    *   - For a typeref P.C[Ts] where C refers to an alias type, the erasure of C's alias.
    *   - For a typeref P.C[Ts] where C refers to an abstract type, the
    *     erasure of C's upper bound.
@@ -62,51 +117,66 @@ abstract class Erasure extends AddInterfaces with typechecker.Analyzer {
    *  </ul>
    */
   val erasure = new TypeMap {
-    def apply(tp: Type): Type = { 
+
+    // Compute the dominant part of the intersection type with given `parents` according to new spec.
+    def intersectionDominator(parents: List[Type]): Type =
+      if (parents.isEmpty) ObjectClass.tpe
+      else {
+        val psyms = parents map (_.typeSymbol)
+        if (psyms contains ArrayClass) {
+          // treat arrays specially
+          arrayType(
+            intersectionDominator(
+              parents filter (_.typeSymbol == ArrayClass) map (_.typeArgs.head)))
+        } else {
+          // implement new spec for erasure of refined types.
+          def isUnshadowed(psym: Symbol) =
+            !(psyms exists (qsym => (psym ne qsym) && (qsym isNonBottomSubClass psym)))
+          val cs = parents.iterator.filter { p => // isUnshadowed is a bit expensive, so try classes first
+            val psym = p.typeSymbol
+            psym.isClass && !psym.isTrait && isUnshadowed(psym)
+          }
+          (if (cs.hasNext) cs else parents.iterator.filter(p => isUnshadowed(p.typeSymbol))).next()
+        }
+      }
+
+    def apply(tp: Type): Type = {
       tp match {
         case ConstantType(_) =>
           tp
         case st: SubType =>
           apply(st.supertype)
         case TypeRef(pre, sym, args) =>
-          def isGeneric(tp: Type): Boolean = tp match {
-            case TypeRef(pre, sym, args) =>
-              sym.isAbstractType && !(sym.owner hasFlag JAVA) ||
-              sym == ArrayClass && args.length == 1 && isGeneric(args.head) 
-            case ExistentialType(tparams, restp) =>
-              isGeneric(restp)
-            case _ =>
-              false
-          }
           if (sym == ArrayClass)
-            if (isGeneric(tp)) erasedTypeRef(BoxedArrayClass)
+            if (unboundedGenericArrayLevel(tp) == 1) ObjectClass.tpe
+            else if (args.head.typeSymbol == NothingClass || args.head.typeSymbol == NullClass) arrayType(ObjectClass.tpe)
             else typeRef(apply(pre), sym, args map this)
-          else if (sym == AnyClass || sym == AnyValClass || sym == SingletonClass) erasedTypeRef(ObjectClass)
+          else if (sym == AnyClass || sym == AnyValClass || sym == SingletonClass || sym == NotNullClass) erasedTypeRef(ObjectClass)
           else if (sym == UnitClass) erasedTypeRef(BoxedUnitClass)
-          else if (sym.isClass) 
-            typeRef(apply(if (sym.owner.isClass) sym.owner.tpe else pre), sym, List())
-          else apply(sym.info)
+          else if (sym.isRefinementClass) apply(intersectionDominator(tp.parents))
+          else if (sym.isClass) typeRef(apply(rebindInnerClass(pre, sym)), sym, List())  // #2585
+          else apply(sym.info) // alias type or abstract type
         case PolyType(tparams, restpe) =>
           apply(restpe)
         case ExistentialType(tparams, restpe) =>
           apply(restpe)
-        case mt @ MethodType(formals, restpe) =>
+        case mt @ MethodType(params, restpe) =>
           MethodType(
-            formals map apply,
+            cloneSymbols(params) map (p => p.setInfo(apply(p.tpe))),
             if (restpe.typeSymbol == UnitClass) 
               erasedTypeRef(UnitClass) 
-            else if (settings.Xexperimental.value)
-              apply(mt.resultType(formals)) // this gets rid of DeBruijnTypes
+            else if (settings.YdepMethTpes.value)
+              // this replaces each typeref that refers to an argument by the type `p.tpe` of the actual argument p (p in params)
+              apply(mt.resultType(params map (_.tpe)))
             else
               apply(restpe))
         case RefinedType(parents, decls) =>
-          if (parents.isEmpty) erasedTypeRef(ObjectClass) 
-          else apply(parents.head)
-	case AnnotatedType(_, atp, _) =>
-	  apply(atp)
+          apply(intersectionDominator(parents))
+        case AnnotatedType(_, atp, _) =>
+          apply(atp)
         case ClassInfoType(parents, decls, clazz) =>
           ClassInfoType(
-            if ((clazz == ObjectClass) || (isValueType(clazz))) List() 
+            if ((clazz == ObjectClass) || (isValueClass(clazz))) List() 
             else if (clazz == ArrayClass) List(erasedTypeRef(ObjectClass))
             else removeDoubleObject(parents map this),
             decls, clazz)
@@ -124,7 +194,8 @@ abstract class Erasure extends AddInterfaces with typechecker.Analyzer {
             traverse(st.supertype)
           case TypeRef(pre, sym, args) =>
             if (sym == ArrayClass) args foreach traverse
-            else if (sym.isTypeParameterOrSkolem || sym.isExistential || !args.isEmpty) result = true
+            else if (sym.isTypeParameterOrSkolem || sym.isExistentiallyBound || !args.isEmpty) result = true
+            else if (sym.isClass) traverse(rebindInnerClass(pre, sym)) // #2585
             else if (!sym.owner.isPackageClass) traverse(pre)
           case PolyType(_, _) | ExistentialType(_, _) =>
             result = true
@@ -143,7 +214,7 @@ abstract class Erasure extends AddInterfaces with typechecker.Analyzer {
 
   private def needsJavaSig(tp: Type) = !settings.Ynogenericsig.value && NeedsSigCollector.collect(tp)
 
-  private lazy val tagOfClass = new HashMap[Symbol,Char] + (
+  private lazy val tagOfClass = Map[Symbol,Char](
     ByteClass -> BYTE_TAG,
     CharClass -> CHAR_TAG,
     DoubleClass -> DOUBLE_TAG,
@@ -155,12 +226,15 @@ abstract class Erasure extends AddInterfaces with typechecker.Analyzer {
     UnitClass -> VOID_TAG
   )
 
-  def javaSig(sym: Symbol): Option[String] = atPhase(currentRun.erasurePhase) {
+  /** The Java signature of type 'info', for symbol sym. The symbol is used to give the right return
+   *  type for constructors.
+   */
+  def javaSig(sym0: Symbol, info: Type): Option[String] = atPhase(currentRun.erasurePhase) {
 
     def jsig(tp: Type): String = jsig2(false, List(), tp)
 
     def jsig2(toplevel: Boolean, tparams: List[Symbol], tp0: Type): String = {
-      val tp = tp0.normalize 
+      val tp = tp0.dealias 
       tp match {
         case st: SubType =>
           jsig2(toplevel, tparams, st.supertype)
@@ -182,23 +256,33 @@ abstract class Erasure extends AddInterfaces with typechecker.Analyzer {
               }
             }
           def classSig: String = 
-            "L"+atPhase(currentRun.icodePhase)(sym.fullNameString).replace('.', '/')
+            "L"+atPhase(currentRun.icodePhase)(sym.fullName + global.genJVM.moduleSuffix(sym)).replace('.', '/')
           def classSigSuffix: String = 
             "."+sym.name
           if (sym == ArrayClass)
-            ARRAY_TAG.toString+(args map jsig).mkString
-          else if (sym.isTypeParameterOrSkolem)
+            if (unboundedGenericArrayLevel(tp) == 1) jsig(ObjectClass.tpe)
+            else ARRAY_TAG.toString+(args map jsig).mkString
+          else if (sym.isTypeParameterOrSkolem &&
+                  // only refer to type params that will actually make it into the sig, this excludes:
+                  !sym.owner.isTypeParameterOrSkolem && // higher-order type parameters (!sym.owner.isTypeParameterOrSkolem), and parameters of methods
+                  (!sym0.isClass || sym.owner.isClass) // if we're generating the sig for a class, type params must be owned by a class (not a method -- #3249)
+                  )
             TVAR_TAG.toString+sym.name+";"
           else if (sym == AnyClass || sym == AnyValClass || sym == SingletonClass) 
             jsig(ObjectClass.tpe)
           else if (sym == UnitClass) 
             jsig(BoxedUnitClass.tpe)
+          else if (sym == NothingClass)
+            jsig(RuntimeNothingClass.tpe)
+          else if (sym == NullClass)
+            jsig(RuntimeNullClass.tpe)
           else if (isValueClass(sym)) 
             tagOfClass(sym).toString
           else if (sym.isClass)
-            { 
-              if (needsJavaSig(pre)) {
-                val s = jsig(pre) 
+            {
+              val preRebound = pre.baseType(sym.owner) // #2585
+              if (needsJavaSig(preRebound)) {
+                val s = jsig(preRebound)
                 if (s.charAt(0) == 'L') s.substring(0, s.length - 1) + classSigSuffix
                 else classSig
               } else classSig
@@ -222,25 +306,28 @@ abstract class Erasure extends AddInterfaces with typechecker.Analyzer {
           assert(!tparams.isEmpty)
           def paramSig(tsym: Symbol) = tsym.name+boundSig(hiBounds(tsym.info.bounds))
           (if (toplevel) "<"+(tparams map paramSig).mkString+">" else "")+jsig(restpe) 
-        case MethodType(formals, restpe) =>
-          "("+(formals map jsig).mkString+")"+
-          (if (restpe.typeSymbol == UnitClass || sym.isConstructor) VOID_TAG.toString else jsig(restpe))
+        case MethodType(params, restpe) =>
+          "("+(params map (_.tpe) map jsig).mkString+")"+
+          (if (restpe.typeSymbol == UnitClass || sym0.isConstructor) VOID_TAG.toString else jsig(restpe))
         case RefinedType(parents, decls) if (!parents.isEmpty) =>
           jsig(parents.head)
         case ClassInfoType(parents, _, _) =>
           (parents map jsig).mkString
         case AnnotatedType(_, atp, _) =>
           jsig(atp)
+        case BoundedWildcardType(bounds) =>
+          println("something's wrong: "+sym0+":"+sym0.tpe+" has a bounded wildcard type")
+          jsig(bounds.hi)
         case _ =>
           val etp = erasure(tp)
           if (etp eq tp) throw new UnknownSig
           else jsig(etp)
       }
     }
-    if (needsJavaSig(sym.info)) {
+    if (needsJavaSig(info)) {
       try {
-        //println("Java sig of "+sym+" is "+jsig2(true, List(), sym.info))//DEBUG
-        Some(jsig2(true, List(), sym.info))
+        //println("Java sig of "+sym0+" is "+jsig2(true, List(), sym0.info))//DEBUG
+        Some(jsig2(true, List(), info))
       } catch {
         case ex: UnknownSig => None
       }
@@ -254,9 +341,7 @@ abstract class Erasure extends AddInterfaces with typechecker.Analyzer {
   def erasedTypeRef(sym: Symbol): Type =
     typeRef(erasure(sym.owner.tpe), sym, List())
 
-  /** Remove duplicate references to class Object in a list of parent classes
-   * todo: needed?
-   */
+  /** Remove duplicate references to class Object in a list of parent classes */
   private def removeDoubleObject(tps: List[Type]): List[Type] = tps match {
     case List() => List()
     case tp :: tps1 => 
@@ -294,21 +379,31 @@ abstract class Erasure extends AddInterfaces with typechecker.Analyzer {
     else if (sym == Object_isInstanceOf || sym == ArrayClass) 
       PolyType(sym.info.typeParams, erasure(sym.info.resultType))
     else if (sym.isAbstractType) 
-      mkTypeBounds(WildcardType, WildcardType)
+      TypeBounds(WildcardType, WildcardType)
     else if (sym.isTerm && sym.owner == ArrayClass) {
       if (sym.isClassConstructor)
         tp match {
-          case MethodType(formals, TypeRef(pre, sym, args)) =>
-            MethodType(formals map erasure, typeRef(erasure(pre), sym, args))
+          case MethodType(params, TypeRef(pre, sym, args)) =>
+            MethodType(cloneSymbols(params) map (p => p.setInfo(erasure(p.tpe))),
+                       typeRef(erasure(pre), sym, args))
         }
       else if (sym.name == nme.apply) 
         tp
       else if (sym.name == nme.update)
         tp match {
           case MethodType(List(index, tvar), restpe) =>
-            MethodType(List(erasure(index), tvar), erasedTypeRef(UnitClass))
+            MethodType(List(index.cloneSymbol.setInfo(erasure(index.tpe)), tvar),
+                       erasedTypeRef(UnitClass))
         }
       else erasure(tp)
+    } else if (
+      sym.owner != NoSymbol &&
+      sym.owner.owner == ArrayClass &&
+      sym == Array_update.paramss.head(1)) {
+      // special case for Array.update: the non-erased type remains, i.e. (Int,A)Unit
+      // since the erasure type map gets applied to every symbol, we have to catch the
+      // symbol here
+      tp
     } else {
 /*
       val erased = 
@@ -328,9 +423,6 @@ abstract class Erasure extends AddInterfaces with typechecker.Analyzer {
    }
   }
 
-  private def isSeqClass(sym: Symbol) =
-    (SeqClass isNonBottomSubClass sym) && (sym != ObjectClass)
-
   /** The symbol which is called by a bridge;
    *  @pre phase > erasure
    */
@@ -341,10 +433,28 @@ abstract class Erasure extends AddInterfaces with typechecker.Analyzer {
              sym.tpe.resultType <:< bridge.tpe.resultType
     }
 
-// -------- boxing/unboxing --------------------------------------------------------
+// -------- erasure on trees ------------------------------------------
 
   override def newTyper(context: Context) = new Eraser(context)
 
+  /** An extractor object for boxed expressions
+  object Boxed {
+    def unapply(tree: Tree): Option[Tree] = tree match {
+      case LabelDef(name, params, Boxed(rhs)) =>
+        Some(treeCopy.LabelDef(tree, name, params, rhs) setType rhs.tpe)
+      case Select(_, _) if tree.symbol == BoxedUnit_UNIT =>
+        Some(Literal(()) setPos tree.pos setType UnitClass.tpe)
+      case Block(List(unboxed), ret @ Select(_, _)) if ret.symbol == BoxedUnit_UNIT =>
+        Some(if (unboxed.tpe.typeSymbol == UnitClass) tree
+             else Block(List(unboxed), Literal(()) setPos tree.pos setType UnitClass.tpe))
+      case Apply(fn, List(unboxed)) if isBox(fn.symbol) =>
+        Some(unboxed)
+      case _ =>
+        None
+    }
+  }
+   */
+
   /** The modifier typer which retypes with erased types. */
   class Eraser(context: Context) extends Typer(context) {
   
@@ -352,38 +462,23 @@ abstract class Erasure extends AddInterfaces with typechecker.Analyzer {
     private def box(tree: Tree): Tree = tree match {
       case LabelDef(name, params, rhs) =>
         val rhs1 = box(rhs)
-        copy.LabelDef(tree, name, params, rhs1) setType rhs1.tpe
+        treeCopy.LabelDef(tree, name, params, rhs1) setType rhs1.tpe
       case _ =>
-        typed {
-          atPos(tree.pos) {
-            val sym = tree.tpe.typeSymbol;
-            if (sym == UnitClass) {
-              if (treeInfo.isPureExpr(tree)) gen.mkAttributedRef(BoxedUnit_UNIT)
-              else Block(List(tree), gen.mkAttributedRef(BoxedUnit_UNIT))
-            } else if (sym == ArrayClass) {
-              val elemClass = tree.tpe.typeArgs.head.typeSymbol;
-              val boxedClass = if (isValueClass(elemClass)) boxedArrayClass(elemClass)
-                               else BoxedObjectArrayClass;
-              Apply(Select(New(TypeTree(boxedClass.tpe)), nme.CONSTRUCTOR), List(tree))
-            } else {
-              Apply(gen.mkAttributedRef(boxMethod(tree.tpe.typeSymbol)), List(tree)).
-                setPos(tree.pos) setType ObjectClass.tpe
+        typedPos(tree.pos)(tree.tpe.typeSymbol match {
+          case UnitClass  =>
+            if (treeInfo isPureExpr tree) REF(BoxedUnit_UNIT)
+            else BLOCK(tree, REF(BoxedUnit_UNIT))
+          case x          =>
+            assert(x != ArrayClass)
+            tree match {
+              case Apply(boxFun, List(arg)) if (isUnbox(tree.symbol)) =>
+                log("boxing an unbox: " + tree)
+                log("replying with " + arg)
+                arg
+              case _ =>
+                (REF(boxMethod(x)) APPLY tree) setPos (tree.pos) setType ObjectClass.tpe
             }
-          }
-        }
-    }
-
-    /** generate  ScalaRuntime.boxArray(tree) */
-    private def boxArray(tree: Tree): Tree = tree match {
-      case LabelDef(name, params, rhs) =>
-        val rhs1 = boxArray(rhs)
-        copy.LabelDef(tree, name, params, rhs1) setType rhs1.tpe
-      case _ =>
-        typed {
-          atPos(tree.pos) {
-            gen.mkRuntimeCall(nme.boxArray, List(tree))
-          }
-        }
+        })
     }
 
     /** Unbox <code>tree</code> of boxed type to expected type <code>pt</code>.
@@ -393,116 +488,30 @@ abstract class Erasure extends AddInterfaces with typechecker.Analyzer {
      *  @return     the unboxed tree
      */
     private def unbox(tree: Tree, pt: Type): Tree = tree match {
+/*
+      case Boxed(unboxed) =>
+        println("unbox shorten: "+tree) // this never seems to kick in during build and test; therefore disabled.
+        adaptToType(unboxed, pt)
+ */
       case LabelDef(name, params, rhs) =>
         val rhs1 = unbox(rhs, pt)
-        copy.LabelDef(tree, name, params, rhs1) setType rhs1.tpe
+        treeCopy.LabelDef(tree, name, params, rhs1) setType rhs1.tpe
       case _ =>
-        typed {
-          atPos(tree.pos) {
-            if (pt.typeSymbol == UnitClass) {
-              if (treeInfo.isPureExpr(tree)) Literal(())
-              else Block(List(tree), Literal(()))
-            }
-            else if (pt.typeSymbol == ArrayClass) {
-              val tree1 = adaptToType(tree, BoxedArrayClass.tpe)
-              gen.mkRuntimeCall(nme.arrayValue, List(tree1, Literal(pt.typeArgs.head)))
-            }
-            else {
-              atPos(tree.pos) {
-                Apply(gen.mkAttributedRef(unboxMethod(pt.typeSymbol)), List(tree)) setType pt
-              }
-            }
-          }
-        }
+        typedPos(tree.pos)(pt.typeSymbol match {
+          case UnitClass  =>
+            if (treeInfo isPureExpr tree) UNIT
+            else BLOCK(tree, UNIT)
+          case x          =>
+            assert(x != ArrayClass)
+            (REF(unboxMethod(pt.typeSymbol)) APPLY tree) setType pt
+        })
     }
 
-    /** <p>
-     *    Generate a cast operation from <code>tree.tpe</code> to <code>pt</code>.
-     *    The following cases need to be treated specially:
-     *  </p>
-     *  <table>
-     *    <tr>
-     *      <td><code>Object -> Array</code></td>
-     *      <td>(might be a boxedarray)</td>
-     *    </tr>
-     *    <tr>
-     *      <td><code>Object -> Boxed*Array</code></td>
-     *      <td>(might be an array, which nees to be boxed)</td>
-     *    </tr>
-     *    <tr>
-     *      <td><code>Object -> Seq, Iterable</code></td>
-     *      <td>(might be an array, which needs to be boxed)</td>
-     *    </tr>
-     *  </table>
+    /**   Generate a synthetic cast operation from <code>tree.tpe</code> to <code>pt</code>.
+     * @pre pt eq pt.normalize
      */
-    private def cast(tree: Tree, pt: Type): Tree = {
-      assert(pt eq pt.normalize)
-
-      if (tree.tpe.typeSymbol == ObjectClass) {
-        if (pt.typeSymbol == ArrayClass)
-          typed {
-            atPos(tree.pos) {
-              gen.evalOnce(tree, context.owner, context.unit) { x =>
-                gen.mkAttributedCast(
-                  If(
-                    Apply(
-                      TypeApply(
-                        Select(x(), Object_isInstanceOf),
-                        List(TypeTree(BoxedArrayClass.tpe))),
-                      List()),
-                    unbox(gen.mkAttributedCast(x(), BoxedArrayClass.tpe), pt),
-                    x()),
-                  pt)
-              }
-            }
-          }
-        else if (pt.typeSymbol isNonBottomSubClass BoxedArrayClass)
-          typed {
-            atPos(tree.pos) {
-              gen.evalOnce(tree, context.owner, context.unit) { x =>
-                gen.mkAttributedCast(
-                  If(
-                    Apply(
-                      TypeApply(
-                        Select(x(), Object_isInstanceOf),
-                        List(TypeTree(BoxedArrayClass.tpe))),
-                      List()),
-                    x(),
-                    boxArray(x())),
-                  pt)
-              }
-            }
-          }
-        else if (isSeqClass(pt.typeSymbol))
-          typed {
-            atPos(tree.pos) {
-              gen.evalOnce(tree, context.owner, context.unit) { x =>
-                gen.mkAttributedCast(
-                  If(
-                    Apply(
-                      TypeApply(
-                        Select(x(), Object_isInstanceOf),
-                        List(TypeTree(pt))),
-                      List()),
-                    x(),
-                    boxArray(x())),
-                  pt)
-              }
-            }
-          }
-        else gen.mkAttributedCast(tree, pt)
-      } else gen.mkAttributedCast(tree, pt)
-    }
-    
-    /** Is symbol a member of unboxed arrays (which will be expanded directly
-     *  later)?
-     *
-     *  @param sym ..
-     *  @return    <code>true</code> if .. 
-     */
-    private def isUnboxedArrayMember(sym: Symbol) =
-      sym.name == nme.apply || sym.name == nme.length || sym.name == nme.update ||
-      sym.owner == ObjectClass
+    private def cast(tree: Tree, pt: Type): Tree =
+      tree AS_ATTR pt
 
     private def isUnboxedValueMember(sym: Symbol) =
       sym != NoSymbol && isValueClass(sym.owner)
@@ -510,7 +519,7 @@ abstract class Erasure extends AddInterfaces with typechecker.Analyzer {
     /** Adapt <code>tree</code> to expected type <code>pt</code>.
      *
      *  @param tree the given tree
-     *  @param pt   the expected type.
+     *  @param pt   the expected type
      *  @return     the adapted tree
      */
     private def adaptToType(tree: Tree, pt: Type): Tree = {
@@ -518,14 +527,14 @@ abstract class Erasure extends AddInterfaces with typechecker.Analyzer {
         log("adapting " + tree + ":" + tree.tpe + " : " +  tree.tpe.parents + " to " + pt)//debug
       if (tree.tpe <:< pt)
         tree
-      else if (isUnboxedClass(tree.tpe.typeSymbol) && !isUnboxedClass(pt.typeSymbol))
+      else if (isValueClass(tree.tpe.typeSymbol) && !isValueClass(pt.typeSymbol))
         adaptToType(box(tree), pt)
-      else if (tree.tpe.isInstanceOf[MethodType] && tree.tpe.paramTypes.isEmpty) {
+      else if (tree.tpe.isInstanceOf[MethodType] && tree.tpe.params.isEmpty) {
         if (!tree.symbol.isStable) assert(false, "adapt "+tree+":"+tree.tpe+" to "+pt)
         adaptToType(Apply(tree, List()) setPos tree.pos setType tree.tpe.resultType, pt)
       } else if (pt <:< tree.tpe) 
         cast(tree, pt)
-      else if (isUnboxedClass(pt.typeSymbol) && !isUnboxedClass(tree.tpe.typeSymbol))
+      else if (isValueClass(pt.typeSymbol) && !isValueClass(tree.tpe.typeSymbol))
         adaptToType(unbox(tree, pt), pt)
       else 
         cast(tree, pt)
@@ -590,14 +599,8 @@ abstract class Erasure extends AddInterfaces with typechecker.Analyzer {
     private def adaptMember(tree: Tree): Tree = {
       //Console.println("adaptMember: " + tree);
       tree match {
-        case Apply(Select(New(tpt), name), args) if (tpt.tpe.typeSymbol == BoxedArrayClass) =>
-          assert(name == nme.CONSTRUCTOR);
-          atPos(tree.pos) {
-            Typed(Apply(Select(New(TypeTree(BoxedAnyArrayClass.tpe)), name), args), tpt)
-          }
-        case Apply(TypeApply(sel @ Select(qual, name), List(targ)), List()) 
-        if ((tree.symbol == Any_asInstanceOf || tree.symbol == Any_asInstanceOfErased)) =>
-          val qual1 = typedQualifier(qual)
+        case Apply(TypeApply(sel @ Select(qual, name), List(targ)), List()) if tree.symbol == Any_asInstanceOf =>
+          val qual1 = typedQualifier(qual, NOmode, ObjectClass.tpe) // need to have an expected type, see #3037
           val qualClass = qual1.tpe.typeSymbol
           val targClass = targ.tpe.typeSymbol
 /*
@@ -606,41 +609,39 @@ abstract class Erasure extends AddInterfaces with typechecker.Analyzer {
             atPos(tree.pos)(Apply(Select(qual1, "to" + targClass.name), List()))
           else 
 */
-          if (isValueType(targClass) ||
-                   (targClass == ArrayClass && (qualClass isNonBottomSubClass BoxedArrayClass)))
-            unbox(qual1, targ.tpe)
-          else if (targClass == ArrayClass && qualClass == ObjectClass || isSeqClass(targClass))
-            cast(qual1, targ.tpe)
-          else 
-            tree
+          if (isValueClass(targClass)) unbox(qual1, targ.tpe)
+          else tree
         case Select(qual, name) if (name != nme.CONSTRUCTOR) =>
           if (tree.symbol == NoSymbol)
             tree
-          else if (tree.symbol == Any_asInstanceOf || tree.symbol == Any_asInstanceOfErased)
+          else if (tree.symbol == Any_asInstanceOf)
             adaptMember(atPos(tree.pos)(Select(qual, Object_asInstanceOf)))
-          else if (tree.symbol == Any_isInstanceOf || tree.symbol == Any_isInstanceOfErased)
+          else if (tree.symbol == Any_isInstanceOf)
             adaptMember(atPos(tree.pos)(Select(qual, Object_isInstanceOf)))
           else if (tree.symbol.owner == AnyClass)
             adaptMember(atPos(tree.pos)(Select(qual, getMember(ObjectClass, name))))
           else {
-            var qual1 = typedQualifier(qual);
-            if ((isValueType(qual1.tpe.typeSymbol) && !isUnboxedValueMember(tree.symbol)) || 
-                (qual1.tpe.typeSymbol == ArrayClass && !isUnboxedArrayMember(tree.symbol)))
-              qual1 = box(qual1);
-            else if (!isValueType(qual1.tpe.typeSymbol) && isUnboxedValueMember(tree.symbol))
+            var qual1 = typedQualifier(qual)
+            if ((isValueClass(qual1.tpe.typeSymbol) && !isUnboxedValueMember(tree.symbol)))
+              qual1 = box(qual1)
+            else if (!isValueClass(qual1.tpe.typeSymbol) && isUnboxedValueMember(tree.symbol))
               qual1 = unbox(qual1, tree.symbol.owner.tpe)
-            else if (tree.symbol.owner == ArrayClass && qual1.tpe.typeSymbol == ObjectClass)
-              qual1 = cast(qual1, BoxedArrayClass.tpe)
             
-            if (isUnboxedClass(tree.symbol.owner) && !isUnboxedClass(qual1.tpe.typeSymbol))
+            if (isValueClass(tree.symbol.owner) && !isValueClass(qual1.tpe.typeSymbol))
               tree.symbol = NoSymbol
-            else if (qual1.tpe.isInstanceOf[MethodType] && qual1.tpe.paramTypes.isEmpty) {
+            else if (qual1.tpe.isInstanceOf[MethodType] && qual1.tpe.params.isEmpty) {
               assert(qual1.symbol.isStable, qual1.symbol);
-              qual1 = Apply(qual1, List()) setPos qual1.pos setType qual1.tpe.resultType;
-            } else if (!(qual1.isInstanceOf[Super] || (qual1.tpe.typeSymbol isSubClass tree.symbol.owner)))
-              qual1 = cast(qual1, tree.symbol.owner.tpe);
-            copy.Select(tree, qual1, name)
+              qual1 = Apply(qual1, List()) setPos qual1.pos setType qual1.tpe.resultType
+            } else if (!(qual1.isInstanceOf[Super] || (qual1.tpe.typeSymbol isSubClass tree.symbol.owner))) {
+              assert(tree.symbol.owner != ArrayClass)
+              qual1 = cast(qual1, tree.symbol.owner.tpe)
+            }
+            treeCopy.Select(tree, qual1, name)
           }
+        case SelectFromArray(qual, name, erasure) =>
+          var qual1 = typedQualifier(qual)
+          if (!(qual1.tpe <:< erasure)) qual1 = cast(qual1, erasure)
+          Select(qual1, name) copyAttrs tree 
         case _ =>
           tree
       }
@@ -653,7 +654,7 @@ abstract class Erasure extends AddInterfaces with typechecker.Analyzer {
      *  @param pt   ...
      *  @return     the adapted tree
      */
-    override protected def adapt(tree: Tree, mode: Int, pt: Type): Tree =
+    override protected def adapt(tree: Tree, mode: Int, pt: Type, original: Tree = EmptyTree): Tree =
       adaptToType(tree, pt)
 
     /** A replacement for the standard typer's `typed1' method */
@@ -669,21 +670,22 @@ abstract class Erasure extends AddInterfaces with typechecker.Analyzer {
           Console.println("exception when typing " + tree)
           Console.println(er.msg + " in file " + context.owner.sourceFile)
           er.printStackTrace
-          throw new Error
+          abort()
       }
       def adaptCase(cdef: CaseDef): CaseDef = {
         val body1 = adaptToType(cdef.body, tree1.tpe)
-        copy.CaseDef(cdef, cdef.pat, cdef.guard, body1) setType body1.tpe
+        treeCopy.CaseDef(cdef, cdef.pat, cdef.guard, body1) setType body1.tpe
       }
       def adaptBranch(branch: Tree): Tree =
         if (branch == EmptyTree) branch else adaptToType(branch, tree1.tpe);
+
       tree1 match {
         case If(cond, thenp, elsep) =>
-          copy.If(tree1, cond, adaptBranch(thenp), adaptBranch(elsep))
+          treeCopy.If(tree1, cond, adaptBranch(thenp), adaptBranch(elsep))
         case Match(selector, cases) =>
-          copy.Match(tree1, selector, cases map adaptCase)
+          treeCopy.Match(tree1, selector, cases map adaptCase)
         case Try(block, catches, finalizer) =>
-          copy.Try(tree1, adaptBranch(block), catches map adaptCase, finalizer)
+          treeCopy.Try(tree1, adaptBranch(block), catches map adaptCase, finalizer)
         case Ident(_) | Select(_, _) =>
           if (tree1.symbol hasFlag OVERLOADED) {
             val first = tree1.symbol.alternatives.head
@@ -725,20 +727,22 @@ abstract class Erasure extends AddInterfaces with typechecker.Analyzer {
      */
     private def checkNoDoubleDefs(root: Symbol) {
       def doubleDefError(sym1: Symbol, sym2: Symbol) {
-        val tpe1 = atPhase(currentRun.refchecksPhase.next)(root.thisType.memberType(sym1))
-        val tpe2 = atPhase(currentRun.refchecksPhase.next)(root.thisType.memberType(sym2))
+        // the .toString must also be computed at the earlier phase
+        def atRefc[T](op: => T) = atPhase[T](currentRun.refchecksPhase.next)(op)
+        val tpe1 = atRefc(root.thisType.memberType(sym1))
+        val tpe2 = atRefc(root.thisType.memberType(sym2))
         if (!tpe1.isErroneous && !tpe2.isErroneous)
           unit.error(
           if (sym1.owner == root) sym1.pos else root.pos,
           (if (sym1.owner == sym2.owner) "double definition:\n"
            else if (sym1.owner == root) "name clash between defined and inherited member:\n"
            else "name clash between inherited members:\n") +
-          sym1 + ":" + tpe1 + 
+          sym1 + ":" + atRefc(tpe1.toString) +
             (if (sym1.owner == root) "" else sym1.locationString) + " and\n" +
-          sym2 + ":" + tpe2 + 
-            (if (sym2.owner == root) " at line " + (sym2.pos).line.get else sym2.locationString) +
-          "\nhave same type" + 
-          (if (tpe1 =:= tpe2) "" else " after erasure: " + atPhase(phase.next)(sym1.tpe)))
+          sym2 + ":" + atRefc(tpe2.toString) +
+            (if (sym2.owner == root) " at line " + (sym2.pos).line else sym2.locationString) +
+          "\nhave same type" +
+          (if (atRefc(tpe1 =:= tpe2)) "" else " after erasure: " + atPhase(phase.next)(sym1.tpe)))
         sym1.setInfo(ErrorType)
       }
 
@@ -757,7 +761,10 @@ abstract class Erasure extends AddInterfaces with typechecker.Analyzer {
 
       val opc = new overridingPairs.Cursor(root) {
         override def exclude(sym: Symbol): Boolean =
-          !sym.isTerm || sym.hasFlag(PRIVATE) || super.exclude(sym)
+          (!sym.isTerm || sym.hasFlag(PRIVATE) || super.exclude(sym) 
+           // specialized members have no type history before 'specialize', causing double def errors for curried defs
+           || !sym.hasTypeAt(currentRun.refchecksPhase.id)) 
+
         override def matches(sym1: Symbol, sym2: Symbol): Boolean =
           atPhase(phase.next)(sym1.tpe =:= sym2.tpe)
       }
@@ -770,16 +777,16 @@ abstract class Erasure extends AddInterfaces with typechecker.Analyzer {
                      opc.overriding.infosString +
                      opc.overridden.locationString + " " +
                      opc.overridden.infosString)
-            doubleDefError(opc.overriding, opc.overridden)
+          doubleDefError(opc.overriding, opc.overridden)
         }
         opc.next
       }
     }
 
 /*
-      for (val bc <- root.info.baseClasses.tail; val other <- bc.info.decls.toList) {
+      for (bc <- root.info.baseClasses.tail; other <- bc.info.decls.toList) {
         if (other.isTerm && !other.isConstructor && !(other hasFlag (PRIVATE | BRIDGE))) {
-          for (val member <- root.info.nonPrivateMember(other.name).alternatives) {
+          for (member <- root.info.nonPrivateMember(other.name).alternatives) {
             if (member != other && 
                 !(member hasFlag BRIDGE) && 
                 atPhase(phase.next)(member.tpe =:= other.tpe) && 
@@ -810,11 +817,12 @@ abstract class Erasure extends AddInterfaces with typechecker.Analyzer {
      *    with the erased type of <code>m1</code> in the template.
      *  </p>
      */
-    private def bridgeDefs(owner: Symbol): List[Tree] = {  
-      //Console.println("computing bridges for " + owner)//DEBUG
+    private def bridgeDefs(owner: Symbol): (List[Tree], Set[Symbol]) = {  
+      var toBeRemoved: Set[Symbol] = Set()
+      //println("computing bridges for " + owner)//DEBUG
       assert(phase == currentRun.erasurePhase)
       val site = owner.thisType
-      val bridgesScope = newScope
+      val bridgesScope = new Scope
       val bridgeTarget = new HashMap[Symbol, Symbol]
       var bridges: List[Tree] = List()
       val opc = atPhase(currentRun.explicitOuterPhase) {     
@@ -828,7 +836,7 @@ abstract class Erasure extends AddInterfaces with typechecker.Analyzer {
         val member = opc.overriding
         val other = opc.overridden
         //Console.println("bridge? " + member + ":" + member.tpe + member.locationString + " to " + other + ":" + other.tpe + other.locationString);//DEBUG
-        if (!atPhase(currentRun.explicitOuterPhase)(member.isDeferred)) {
+        if (atPhase(currentRun.explicitOuterPhase)(!member.isDeferred)) {
           val otpe = erasure(other.tpe);
           val bridgeNeeded = atPhase(phase.next) (
             !(other.tpe =:= member.tpe) &&
@@ -844,19 +852,25 @@ abstract class Erasure extends AddInterfaces with typechecker.Analyzer {
               .setPos(owner.pos)
               .setFlag(member.flags | BRIDGE)
               .resetFlag(ACCESSOR | DEFERRED | LAZY | lateDEFERRED)
-              .setInfo(otpe);
+            // the parameter symbols need to have the new owner
+            bridge.setInfo(otpe.cloneInfo(bridge))
             bridgeTarget(bridge) = member
             atPhase(phase.next) { owner.info.decls.enter(bridge) }
+            if (other.owner == owner) {
+              //println("bridge to same: "+other+other.locationString)//DEBUG
+              atPhase(phase.next) { owner.info.decls.unlink(other) }
+              toBeRemoved += other
+            }
             bridgesScope enter bridge
             bridges =
               atPhase(phase.next) {
                 atPos(bridge.pos) {
                   val bridgeDef =
-                    DefDef(bridge, vparamss =>
+                    DefDef(bridge,
                       member.tpe match {
                         case MethodType(List(), ConstantType(c)) => Literal(c)
                         case _ => 
-                          (((Select(This(owner), member): Tree) /: vparamss)
+                          (((Select(This(owner), member): Tree) /: bridge.paramss)
                              ((fun, vparams) => Apply(fun, vparams map Ident)))
                       });
                   if (settings.debug.value)
@@ -868,12 +882,12 @@ abstract class Erasure extends AddInterfaces with typechecker.Analyzer {
         }
         opc.next
       }
-      bridges
+      (bridges, toBeRemoved)
     }
 /*
-      for (val bc <- site.baseClasses.tail; val other <- bc.info.decls.toList) {
+      for (bc <- site.baseClasses.tail; other <- bc.info.decls.toList) {
         if (other.isMethod && !other.isConstructor) {
-          for (val member <- site.nonPrivateMember(other.name).alternatives) {
+          for (member <- site.nonPrivateMember(other.name).alternatives) {
             if (member != other &&
                 !(member hasFlag DEFERRED) && 
                 (site.memberType(member) matches site.memberType(other)) &&
@@ -887,8 +901,9 @@ abstract class Erasure extends AddInterfaces with typechecker.Analyzer {
     def addBridges(stats: List[Tree], base: Symbol): List[Tree] =
       if (base.isTrait) stats
       else {
-        val bridges = bridgeDefs(base)
-        if (bridges.isEmpty) stats else stats ::: bridges
+        val (bridges, toBeRemoved) = bridgeDefs(base)
+        if (bridges.isEmpty) stats 
+        else (stats filterNot (stat => toBeRemoved contains stat.symbol)) ::: bridges
       }
 
     /** <p>
@@ -920,147 +935,154 @@ abstract class Erasure extends AddInterfaces with typechecker.Analyzer {
      *  </ul>
      */
     private val preTransformer = new Transformer {
-      override def transform(tree: Tree): Tree = {
-        if (tree.symbol == ArrayClass && !tree.isType) return tree
-        val tree1 = tree match {
-          case ClassDef(mods, name, tparams, impl) =>
-            if (settings.debug.value)
-              log("defs of " + tree.symbol + " = " + tree.symbol.info.decls)
-            copy.ClassDef(tree, mods, name, List(), impl)
-          case DefDef(mods, name, tparams, vparamss, tpt, rhs) =>
-            copy.DefDef(tree, mods, name, List(), vparamss, tpt, rhs)
-          case TypeDef(_, _, _, _) =>
-            EmptyTree
-          case TypeApply(fun, args) if (fun.symbol.owner != AnyClass && 
-                                        fun.symbol != Object_asInstanceOf &&
-                                        fun.symbol != Object_isInstanceOf) =>
-            // leave all other type tests/type casts, remove all other type applications
-            fun
-          case Apply(fn, args) =>
-            def isGenericArray(tpe: Type): Boolean = erasure(tpe).typeSymbol == BoxedArrayClass
-            if (fn.hasSymbol &&
-                fn.symbol.name == nme.arraycopy && 
-                fn.symbol.owner.name == nme.System.toTypeName && 
-                fn.symbol.owner.owner == JavaLangPackage.tpe.typeSymbol &&
-                args.length == 5 &&
-                (isGenericArray(args(0).tpe) || isGenericArray(args(2).tpe))) 
-              unit.warning(tree.pos, 
-                           "System.arraycopy should be applied only to arrays with fixed element types;\n" + 
-                           "use Array.copy instead")
-            if (fn.symbol == Any_asInstanceOf || fn.symbol == Any_asInstanceOfErased)
-              fn match {
-                case TypeApply(Select(qual, _), List(targ)) =>
-                  if (qual.tpe <:< targ.tpe) {
-                    atPos(tree.pos) { Typed(qual, TypeTree(targ.tpe)) }
-                  } else if (isNumericValueClass(qual.tpe.typeSymbol) && 
-                             isNumericValueClass(targ.tpe.typeSymbol)) {
-                    // convert numeric type casts
-                    val cname = newTermName("to" + targ.tpe.typeSymbol.name)
-                    val csym = qual.tpe.member(cname)
-                    assert(csym != NoSymbol)
-                    atPos(tree.pos) { Apply(Select(qual, csym), List()) }
-                  } else 
-                    tree
+      def preErase(tree: Tree): Tree = tree match {
+        case ClassDef(mods, name, tparams, impl) =>
+          if (settings.debug.value)
+            log("defs of " + tree.symbol + " = " + tree.symbol.info.decls)
+          treeCopy.ClassDef(tree, mods, name, List(), impl)
+        case DefDef(mods, name, tparams, vparamss, tpt, rhs) =>
+          treeCopy.DefDef(tree, mods, name, List(), vparamss, tpt, rhs)
+        case TypeDef(_, _, _, _) =>
+          EmptyTree
+        case Apply(instanceOf @ TypeApply(fun @ Select(qual, name), args @ List(arg)), List()) // !!! todo: simplify by having GenericArray also extract trees
+              if ((fun.symbol == Any_isInstanceOf || fun.symbol == Object_isInstanceOf) &&
+                  unboundedGenericArrayLevel(arg.tpe) > 0) =>
+          val level = unboundedGenericArrayLevel(arg.tpe)
+          def isArrayTest(arg: Tree) = 
+            gen.mkRuntimeCall("isArray", List(arg, Literal(Constant(level))))
+          typedPos(tree.pos) {
+            if (level == 1) isArrayTest(qual)
+            else
+              gen.evalOnce(qual, currentOwner, unit) { qual1 =>
+                gen.mkAnd(
+                  Apply(TypeApply(Select(qual1(), fun.symbol), 
+                                  List(TypeTree(erasure(arg.tpe)))), 
+                        List()),
+                  isArrayTest(qual1()))
               }
-              // todo: get rid of instanceOfErased
-              // todo: also handle the case where the singleton type is buried in a compound
-            else if (fn.symbol == Any_isInstanceOf || fn.symbol == Any_isInstanceOfErased)
-              fn match {
-                case TypeApply(sel @ Select(qual, name), List(targ)) =>
-                  def mkIsInstanceOf(q: () => Tree)(tp: Type): Tree =
-                    Apply(
-                      TypeApply(
-                        Select(q(), Object_isInstanceOf) setPos sel.pos, 
-                        List(TypeTree(tp) setPos targ.pos)) setPos fn.pos,
-                      List()) setPos tree.pos
-                  targ.tpe match {
-                    case SingleType(_, _) | ThisType(_) | SuperType(_, _) =>
-                      val cmpOp = if (targ.tpe <:< AnyValClass.tpe) Any_equals else Object_eq
+          }
+        case TypeApply(fun, args) if (fun.symbol.owner != AnyClass && 
+                                      fun.symbol != Object_asInstanceOf &&
+                                      fun.symbol != Object_isInstanceOf) =>
+          // leave all other type tests/type casts, remove all other type applications
+          preErase(fun)
+        case Apply(fn @ Select(qual, name), args) if (fn.symbol.owner == ArrayClass) => 
+          if (unboundedGenericArrayLevel(qual.tpe.widen) == 1) 
+            // convert calls to apply/update/length on generic arrays to
+            // calls of ScalaRunTime.array_xxx method calls
+            typedPos(tree.pos) { gen.mkRuntimeCall("array_"+name, qual :: args) }
+          else
+            // store exact array erasure in map to be retrieved later when we might
+            // need to do the cast in adaptMember
+            treeCopy.Apply(
+              tree,
+              SelectFromArray(qual, name, erasure(qual.tpe)).copyAttrs(fn),
+              args)
+
+        case Apply(fn @ Select(qual, _), Nil) if (fn.symbol == Any_## || fn.symbol == Object_##) =>
+          Apply(gen.mkAttributedRef(scalaRuntimeHash), List(qual))
+
+        case Apply(fn, args) =>
+          if (fn.symbol == Any_asInstanceOf)
+            fn match {
+              case TypeApply(Select(qual, _), List(targ)) =>
+                if (qual.tpe <:< targ.tpe) {
+                  atPos(tree.pos) { Typed(qual, TypeTree(targ.tpe)) }
+                } else if (isNumericValueClass(qual.tpe.typeSymbol) && 
+                           isNumericValueClass(targ.tpe.typeSymbol)) {
+                  // convert numeric type casts
+                  val cname = newTermName("to" + targ.tpe.typeSymbol.name)
+                  val csym = qual.tpe.member(cname)
+                  assert(csym != NoSymbol)
+                  atPos(tree.pos) { Apply(Select(qual, csym), List()) }
+                } else 
+                  tree
+            }
+            // todo: also handle the case where the singleton type is buried in a compound
+          else if (fn.symbol == Any_isInstanceOf)
+            fn match {
+              case TypeApply(sel @ Select(qual, name), List(targ)) =>
+                def mkIsInstanceOf(q: () => Tree)(tp: Type): Tree =
+                  Apply(
+                    TypeApply(
+                      Select(q(), Object_isInstanceOf) setPos sel.pos, 
+                      List(TypeTree(tp) setPos targ.pos)) setPos fn.pos,
+                    List()) setPos tree.pos
+                targ.tpe match {
+                  case SingleType(_, _) | ThisType(_) | SuperType(_, _) =>
+                    val cmpOp = if (targ.tpe <:< AnyValClass.tpe) Any_equals else Object_eq
+                    atPos(tree.pos) {
+                      Apply(Select(qual, cmpOp), List(gen.mkAttributedQualifier(targ.tpe)))
+                    }
+                  case RefinedType(parents, decls) if (parents.length >= 2) =>
+                    gen.evalOnce(qual, currentOwner, unit) { q =>
                       atPos(tree.pos) {
-                        Apply(Select(qual, cmpOp), List(gen.mkAttributedQualifier(targ.tpe)))
-                      }
-                    case RefinedType(parents, decls) if (parents.length >= 2) =>
-                      gen.evalOnce(qual, currentOwner, unit) { q =>
-                        atPos(tree.pos) {
-                          parents map mkIsInstanceOf(q) reduceRight gen.mkAnd
-                        }
+                        parents map mkIsInstanceOf(q) reduceRight gen.mkAnd
                       }
-                    case _ =>
-                      if (isSeqClass(targ.tpe.typeSymbol)) { 
-                        atPos(tree.pos) {
-                          gen.evalOnce(qual, currentOwner, unit) { q =>
-                            gen.mkOr(
-                              mkIsInstanceOf(q)(targ.tpe), 
-                              atPos(tree.pos) {
-                                Apply(gen.mkAttributedRef(isArrayMethod), List(q()))
-                              })
-                          }
-                        }
-                      } else tree
-                  }
-                case _ => tree
-              }
-            else {
-              def doDynamic(fn: Tree, qual: Tree): Tree = {
-                if (fn.symbol.owner.isRefinementClass && fn.symbol.allOverriddenSymbols.isEmpty)
-                  ApplyDynamic(qual, args) setSymbol fn.symbol setPos tree.pos
-                else tree
-              }
-              fn match {
-                case Select(qual, _) => doDynamic(fn, qual)
-                case TypeApply(fni at Select(qual, _), _) => doDynamic(fni, qual)// type parameters are irrelevant in case of dynamic call
-                case _ =>    
-                  tree
-              }
+                    }
+                  case _ =>
+                    tree
+                }
+              case _ => tree
             }
-
-          case Select(_, _) =>
-            if (tree.symbol.owner.isRefinementClass) {
-              val overridden = tree.symbol.allOverriddenSymbols
-              assert(!overridden.isEmpty, tree.symbol)
-              tree.symbol = overridden.head
+          else {
+            def doDynamic(fn: Tree, qual: Tree): Tree = {
+              if (fn.symbol.owner.isRefinementClass && fn.symbol.allOverriddenSymbols.isEmpty)
+                ApplyDynamic(qual, args) setSymbol fn.symbol setPos tree.pos
+              else tree
             }
-            tree
+            fn match {
+              case Select(qual, _) => doDynamic(fn, qual)
+              case TypeApply(fni at Select(qual, _), _) => doDynamic(fni, qual)// type parameters are irrelevant in case of dynamic call
+              case _ =>
+                tree
+            }
+          }
 
-          case Template(parents, self, body) =>
-            assert(!currentOwner.isImplClass)
-            //Console.println("checking no dble defs " + tree)//DEBUG
-            checkNoDoubleDefs(tree.symbol.owner)
-            copy.Template(tree, parents, emptyValDef, addBridges(body, currentOwner))
+        case Select(_, _) =>
+          // println("preXform: "+ (tree, tree.symbol, tree.symbol.owner, tree.symbol.owner.isRefinementClass))
+          if (tree.symbol.owner.isRefinementClass) {
+            val overridden = tree.symbol.allOverriddenSymbols
+            assert(!overridden.isEmpty, tree.symbol)
+            tree.symbol = overridden.head
+          }
+          tree
 
-          case Match(selector, cases) =>
-            Match(Typed(selector, TypeTree(selector.tpe)), cases)
+        case Template(parents, self, body) =>
+          assert(!currentOwner.isImplClass)
+          //Console.println("checking no dble defs " + tree)//DEBUG
+          checkNoDoubleDefs(tree.symbol.owner)
+          treeCopy.Template(tree, parents, emptyValDef, addBridges(body, currentOwner))
 
-          case Literal(ct) if ct.tag == ClassTag 
-                           && ct.typeValue.typeSymbol != definitions.UnitClass =>
-            copy.Literal(tree, Constant(erasure(ct.typeValue)))
-            
-          case _ =>
-            tree
-        }
-        tree1 match {
-          case EmptyTree | TypeTree() =>
-            tree1 setType erasure(tree1.tpe)
-          case DefDef(mods, name, tparams, vparamss, tpt, rhs) =>
-            val result = super.transform(tree1) setType null
-            tpt.tpe = erasure(tree.symbol.tpe).resultType
-            result
-          case _ =>
-            case class MyError(count : Int, ex : AssertionError) extends Error(ex.getMessage)
-            try {
+        case Match(selector, cases) =>
+          Match(Typed(selector, TypeTree(selector.tpe)), cases)
+
+        case Literal(ct) if ct.tag == ClassTag 
+                         && ct.typeValue.typeSymbol != definitions.UnitClass =>
+          treeCopy.Literal(tree, Constant(erasure(ct.typeValue)))
+
+        case _ =>
+          tree
+      }
+
+      override def transform(tree: Tree): Tree =
+        if (tree.symbol == ArrayClass && !tree.isType) tree // !!! needed?
+        else {
+          val tree1 = preErase(tree)
+          // println("preErase: "+ tree +" = "+ tree1)
+          val res = tree1 match {
+            case EmptyTree | TypeTree() =>
+              tree1 setType erasure(tree1.tpe)
+            case DefDef(mods, name, tparams, vparamss, tpt, rhs) =>
+              val result = super.transform(tree1) setType null
+              tpt.tpe = erasure(tree1.symbol.tpe).resultType
+              result
+            case _ =>
               super.transform(tree1) setType null
-            } catch {
-              case e @ MyError(n, ex) if n > 5 =>  throw e
-              case MyError(n,ex) =>
-                Console.println(tree1)
-                throw MyError(n + 1, ex)
-              case ex : AssertionError => 
-                Console.println(tree1)
-                throw MyError(0, ex)
-              case ex => throw ex
-            }
+          }
+          // println("xform: "+ res)
+          res
         }
-      }
     }
 
     /** The main transform function: Pretransfom the tree, and then
@@ -1068,7 +1090,7 @@ abstract class Erasure extends AddInterfaces with typechecker.Analyzer {
      */
     override def transform(tree: Tree): Tree = {
       val tree1 = preTransformer.transform(tree)
-      atPhase(phase.next) { 
+      atPhase(phase.next) {
         val tree2 = mixinTransformer.transform(tree1)
         if (settings.debug.value) log("tree after addinterfaces: \n" + tree2)
         newTyper(rootContext(unit, tree, true)).typed(tree2)
diff --git a/src/compiler/scala/tools/nsc/transform/ExplicitOuter.scala b/src/compiler/scala/tools/nsc/transform/ExplicitOuter.scala
index 145f50e..08d49c8 100644
--- a/src/compiler/scala/tools/nsc/transform/ExplicitOuter.scala
+++ b/src/compiler/scala/tools/nsc/transform/ExplicitOuter.scala
@@ -1,25 +1,31 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author Martin Odersky
  */
-// $Id: ExplicitOuter.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.tools.nsc.transform
+package scala.tools.nsc
+package transform
 
 import symtab._
-import Flags._
-import scala.collection.mutable.{HashMap, ListBuffer}
-import matching.{TransMatcher, PatternNodes, CodeFactory, ParallelMatching}
+import Flags.{ CASE => _, _ }
+import scala.collection.mutable.ListBuffer
+import matching.{ TransMatcher, Patterns, ParallelMatching }
 
 /** This class ...
  *
  *  @author  Martin Odersky
  *  @version 1.0
  */
-abstract class ExplicitOuter extends InfoTransform with TransMatcher with PatternNodes with CodeFactory with ParallelMatching with TypingTransformers {
+abstract class ExplicitOuter extends InfoTransform
+      with TransMatcher
+      with Patterns
+      with ParallelMatching
+      with TypingTransformers
+      with ast.TreeDSL
+{
   import global._
   import definitions._
-  import posAssigner.atPos
+  import CODE._
 
   /** The following flags may be set by this phase: */
   override def phaseNewFlags: Long = notPRIVATE | notPROTECTED | lateFINAL
@@ -49,21 +55,23 @@ abstract class ExplicitOuter extends InfoTransform with TransMatcher with Patter
   }
 
   private def outerField(clazz: Symbol): Symbol = {
-    val result = clazz.info.member(nme.getterToLocal(nme.OUTER))
-    if (result == NoSymbol)
-      assert(false, "no outer field in "+clazz+clazz.info.decls+" at "+phase)
+    val result = clazz.info.member(nme getterToLocal nme.OUTER)
+    assert(result != NoSymbol, "no outer field in "+clazz+clazz.info.decls+" at "+phase)
+    
     result
   }
 
+  /** Issue a migration warning for instance checks which might be on an Array and
+   *  for which the type parameter conforms to Seq, because these answers changed in 2.8.
+   */
+  def isArraySeqTest(lhs: Type, rhs: Type) =
+    ArrayClass.tpe <:< lhs.widen && rhs.widen.matchesPattern(SeqClass.tpe)
+
   def outerAccessor(clazz: Symbol): Symbol = {
-    val firstTry = clazz.info.decl(clazz.expandedName(nme.OUTER))
+    val firstTry = clazz.info.decl(nme.expandedName(nme.OUTER, clazz))
     if (firstTry != NoSymbol && firstTry.outerSource == clazz) firstTry
-    else {
-      var e = clazz.info.decls.elems
-      while ((e ne null) && e.sym.outerSource != clazz) e = e.next
-      if (e ne null) e.sym else NoSymbol
-    }
-  }
+    else clazz.info.decls find (_.outerSource == clazz) getOrElse NoSymbol
+   }
 
   /** <p>
    *    The type transformation method:
@@ -81,7 +89,7 @@ abstract class ExplicitOuter extends InfoTransform with TransMatcher with Patter
    *      <p>
    *        Add an outer accessor <code>$outer$$C</code> to every inner class
    *        with fully qualified name <code>C</code> that is not an interface.
-   *        The outer accesssor is abstract for traits, concrete for other
+   *        The outer accessor is abstract for traits, concrete for other
    *        classes.
    *      </p>
    *      <p>
@@ -100,45 +108,45 @@ abstract class ExplicitOuter extends InfoTransform with TransMatcher with Patter
    *  </ol>
    */
   def transformInfo(sym: Symbol, tp: Type): Type = tp match {
-    case MethodType(formals, restpe1) =>
+    case MethodType(params, restpe1) =>
       val restpe = transformInfo(sym, restpe1)
-      if (sym.owner.isTrait && ((sym hasFlag SUPERACCESSOR) || sym.isModule)) { // 5 
+      if (sym.owner.isTrait && ((sym hasFlag (ACCESSOR | SUPERACCESSOR)) || sym.isModule)) { // 5 
         sym.makeNotPrivate(sym.owner)
       }
-      // moved form the term transformer
-      if (sym.owner.isTrait && (sym hasFlag (ACCESSOR | SUPERACCESSOR)))
-        sym.makeNotPrivate(sym.owner); //(2)
       if (sym.owner.isTrait && (sym hasFlag PROTECTED)) sym setFlag notPROTECTED // 6
-      if (sym.isClassConstructor && isInner(sym.owner)) // 1
-        MethodType(sym.owner.outerClass.thisType :: formals, restpe)
-      else if (restpe ne restpe1)
-        MethodType(formals, restpe)
+      if (sym.isClassConstructor && isInner(sym.owner)) { // 1
+        val p = sym.newValueParameter(sym.pos, "arg" + nme.OUTER)
+                   .setInfo(sym.owner.outerClass.thisType)
+        MethodType(p :: params, restpe)
+      } else if (restpe ne restpe1)
+        MethodType(params, restpe)
       else tp
     case ClassInfoType(parents, decls, clazz) =>
       var decls1 = decls
       if (isInner(clazz) && !(clazz hasFlag INTERFACE)) {
-        decls1 = newScope(decls.toList)
+        decls1 = new Scope(decls.toList)
         val outerAcc = clazz.newMethod(clazz.pos, nme.OUTER) // 3
-        outerAcc.expandName(clazz)
+        outerAcc expandName clazz
+        
         val restpe = if (clazz.isTrait) clazz.outerClass.tpe else clazz.outerClass.thisType
-        decls1 enter clazz.newOuterAccessor(clazz.pos).setInfo(MethodType(List(), restpe))
+        decls1 enter (clazz.newOuterAccessor(clazz.pos) setInfo MethodType(Nil, restpe))
         if (hasOuterField(clazz)) { //2
           val access = if (clazz.isFinal) PRIVATE | LOCAL else PROTECTED
           decls1 enter (
-            clazz.newValue(clazz.pos, nme.getterToLocal(nme.OUTER))
+            clazz.newValue(clazz.pos, nme getterToLocal nme.OUTER)
             setFlag (SYNTHETIC | PARAMACCESSOR | access)
-            setInfo clazz.outerClass.thisType)
+            setInfo clazz.outerClass.thisType
+          )
         }
       }
       if (!clazz.isTrait && !parents.isEmpty) {
-        for (val mc <- clazz.mixinClasses) {
+        for (mc <- clazz.mixinClasses) {
           val mixinOuterAcc: Symbol = atPhase(phase.next)(outerAccessor(mc))
           if (mixinOuterAcc != NoSymbol) {
-            if (decls1 eq decls) decls1 = newScope(decls.toList)
+            if (decls1 eq decls) decls1 = new Scope(decls.toList)
             val newAcc = mixinOuterAcc.cloneSymbol(clazz) 
-            newAcc.resetFlag(DEFERRED)
-            newAcc.setInfo(clazz.thisType.memberType(mixinOuterAcc))
-            decls1 enter newAcc 
+            newAcc resetFlag DEFERRED setInfo (clazz.thisType memberType mixinOuterAcc)
+            decls1 enter newAcc
           }
         }
       }
@@ -148,7 +156,14 @@ abstract class ExplicitOuter extends InfoTransform with TransMatcher with Patter
       if (restp eq restp1) tp else PolyType(tparams, restp1)
 
     case _ =>
-        tp
+      // Local fields of traits need to be unconditionally unprivatized.
+      // Reason: Those fields might need to be unprivatized if referenced by an inner class.
+      // On the other hand, mixing in the trait into a separately compiled
+      // class needs to have a common naming scheme, independently of whether
+      // the field was accessed from an inner class or not. See #2946
+      if (sym.owner.isTrait && (sym hasFlag LOCAL) && (sym.getter(sym.owner.toInterface) == NoSymbol))
+        sym.makeNotPrivate(sym.owner)
+      tp
   }
 
   /** A base class for transformers that maintain <code>outerParam</code>
@@ -156,7 +171,6 @@ abstract class ExplicitOuter extends InfoTransform with TransMatcher with Patter
    *  The class provides methods for referencing via outer.
    */
   abstract class OuterPathTransformer(unit: CompilationUnit) extends TypingTransformer(unit) {
-
     /** The directly enclosing outer parameter, if we are in a constructor */
     protected var outerParam: Symbol = NoSymbol
 
@@ -164,8 +178,8 @@ abstract class ExplicitOuter extends InfoTransform with TransMatcher with Patter
      *  The result is typed but not positioned.
      */
     protected def outerValue: Tree =
-      if (outerParam != NoSymbol) gen.mkAttributedIdent(outerParam)
-      else outerSelect(gen.mkAttributedThis(currentClass))
+      if (outerParam != NoSymbol) ID(outerParam)
+      else outerSelect(THIS(currentClass))
 
     /** Select and apply outer accessor from 'base'
      *  The result is typed but not positioned.
@@ -182,13 +196,14 @@ abstract class ExplicitOuter extends InfoTransform with TransMatcher with Patter
         if (outerAcc.owner == currentClass && 
             base.tpe =:= currentClass.thisType &&
             outerAcc.owner.isFinal) 
-          outerField(currentClass).suchThat(_.owner == currentClass)
+          outerField(currentClass) suchThat (_.owner == currentClass)
         else
           NoSymbol
       val path = 
         if (outerFld != NoSymbol) Select(base, outerFld)
-        else Apply(Select(base, outerAcc), List())
-      localTyper.typed(path)
+        else Apply(Select(base, outerAcc), Nil)
+        
+      localTyper typed path
     }
 
     /** The path
@@ -222,14 +237,8 @@ abstract class ExplicitOuter extends InfoTransform with TransMatcher with Patter
           case _ =>
         }
         super.transform(tree)
-      } catch {//debug
-        case ex: Throwable =>
-          Console.println("exception when transforming " + tree)
-          //Console.println(ex.getMessage)
-          //Console.println(ex.printStackTrace())
-          //System.exit(-1);
-          throw ex
-      } finally {
+      }
+      finally {
         outerParam = savedOuterParam
       }
     }
@@ -291,25 +300,19 @@ abstract class ExplicitOuter extends InfoTransform with TransMatcher with Patter
    *  </p>
    */
   class ExplicitOuterTransformer(unit: CompilationUnit) extends OuterPathTransformer(unit) {
-
     /** The definition tree of the outer accessor of current class
      */
-    def outerFieldDef: Tree = {
-      val outerFld = outerField(currentClass)
-      ValDef(outerFld, EmptyTree)
-    }
+    def outerFieldDef: Tree = VAL(outerField(currentClass)) === EmptyTree
 
     /** The definition tree of the outer accessor of current class
      */
     def outerAccessorDef: Tree = {
       val outerAcc = outerAccessor(currentClass)
-      var rhs = if (outerAcc.isDeferred) EmptyTree
-                else Select(This(currentClass), outerField(currentClass))
-      localTyper.typed {
-        atPos(currentClass.pos) {
-          DefDef(outerAcc, {vparamss => rhs})
-        }
-      }
+      var rhs: Tree =
+        if (outerAcc.isDeferred) EmptyTree
+        else This(currentClass) DOT outerField(currentClass)
+                
+      typedPos(currentClass.pos)(DEF(outerAcc) === rhs)
     }
 
     /** The definition tree of the outer accessor for class
@@ -320,29 +323,101 @@ abstract class ExplicitOuter extends InfoTransform with TransMatcher with Patter
      *  @pre mixinClass is an inner class
      */
     def mixinOuterAccessorDef(mixinClass: Symbol): Tree = {
-      val outerAcc = outerAccessor(mixinClass).overridingSymbol(currentClass)
+      val outerAcc = outerAccessor(mixinClass) overridingSymbol currentClass
       assert(outerAcc != NoSymbol)
       val path = 
-        if (mixinClass.owner.isTerm) gen.mkAttributedThis(mixinClass.owner.enclClass)
-        else gen.mkAttributedQualifier(currentClass.thisType.baseType(mixinClass).prefix)
-      val rhs = ExplicitOuterTransformer.this.transform(path)
-      rhs.setPos(currentClass.pos) // see note below
-      localTyper.typed {
-        atPos(currentClass.pos) {  
-          // @S: atPos not good enough because of nested atPos in DefDef method, which gives position from wrong class!
-          DefDef(outerAcc, {vparamss=>rhs}).setPos(currentClass.pos)
+        if (mixinClass.owner.isTerm) THIS(mixinClass.owner.enclClass)
+        else gen.mkAttributedQualifier(currentClass.thisType baseType mixinClass prefix)
+      // Need to cast for nested outer refs in presence of self-types. See ticket #3274.
+      val rhs = gen.mkAsInstanceOf(ExplicitOuterTransformer.this.transform(path), 
+          outerAcc.info.resultType)
+      
+      // @S: atPos not good enough because of nested atPos in DefDef method, which gives position from wrong class!
+      rhs setPos currentClass.pos
+      typedPos(currentClass.pos) { (DEF(outerAcc) === rhs) setPos currentClass.pos }
+    }
+    
+    /** If FLAG is set on symbol, sets notFLAG (this exists in anticipation of generalizing). */
+    def setNotFlags(sym: Symbol, flags: Int*) {
+      val notMap = Map(
+        PRIVATE -> notPRIVATE,
+        PROTECTED -> notPROTECTED
+      )
+      for (f <- flags ; notFlag <- notMap get f ; if sym hasFlag f)
+        sym setFlag notFlag
+    }
+    
+    def matchTranslation(tree: Match) = {
+      val Match(selector, cases) = tree
+      var nselector = transform(selector)
+
+      def makeGuardDef(vs: List[Symbol], guard: Tree) = {
+        val gdname = newName(guard.pos, "gd")
+        val method = currentOwner.newMethod(tree.pos, gdname) setFlag SYNTHETIC
+        val fmls   = vs map (_.tpe)
+        val tpe    = new MethodType(method newSyntheticValueParams fmls, BooleanClass.tpe)
+        method setInfo tpe
+        
+        localTyper typed (DEF(method) === {
+          new ChangeOwnerTraverser(currentOwner, method) traverse guard
+          new TreeSymSubstituter(vs, method.paramss.head) transform (guard)
+        })
+      }
+      
+      val nguard = new ListBuffer[Tree]
+      val ncases =
+        for (CaseDef(p, guard, b) <- cases) yield {
+          val gdcall = 
+            if (guard == EmptyTree) EmptyTree
+            else {
+              val vs       = Pattern(p).deepBoundVariables
+              val guardDef = makeGuardDef(vs, guard)
+              nguard       += transform(guardDef) // building up list of guards
+              
+              localTyper typed (Ident(guardDef.symbol) APPLY (vs map Ident))
+            }
+          
+          (CASE(transform(p)) IF gdcall) ==> transform(b)
         }
+      
+      def isUncheckedAnnotation(tpe: Type) = tpe hasAnnotation UncheckedClass
+      def isSwitchAnnotation(tpe: Type) = tpe hasAnnotation SwitchClass
+      
+      val (checkExhaustive, requireSwitch) = nselector match {
+        case Typed(nselector1, tpt) =>
+          val unchecked = isUncheckedAnnotation(tpt.tpe)
+          if (unchecked)
+            nselector = nselector1
+            
+          (!unchecked, isSwitchAnnotation(tpt.tpe))
+        case _  =>
+          (true, false)
+      }
+
+      val t = atPos(tree.pos) {
+        val context     = MatrixContext(transform, localTyper, currentOwner, tree.tpe)
+        val t_untyped   = handlePattern(nselector, ncases, checkExhaustive, context)
+        
+        /* if @switch annotation is present, verify the resulting tree is a Match */
+        if (requireSwitch) t_untyped match {
+          case Block(_, Match(_, _))  => // ok
+          case _                      => 
+            unit.error(tree.pos, "could not emit switch for @switch annotated match")
+        }
+        
+        localTyper.typed(t_untyped, context.matchResultType) 
       }
-    }
 
+      if (nguard.isEmpty) t
+      else Block(nguard.toList, t) setType t.tpe
+    }
+    
     /** The main transformation method */
     override def transform(tree: Tree): Tree = {
-
       val sym = tree.symbol
-      if ((sym ne null) && sym.isType) {//(9)
-        if (sym hasFlag PRIVATE) sym setFlag notPRIVATE
-        if (sym hasFlag PROTECTED) sym setFlag notPROTECTED
-      }
+      if (sym != null && sym.isType)  //(9)
+        setNotFlags(sym, PRIVATE, PROTECTED)
+
       tree match {
         case Template(parents, self, decls) =>
           val newDefs = new ListBuffer[Tree]
@@ -354,13 +429,13 @@ abstract class ExplicitOuter extends InfoTransform with TransMatcher with Patter
                 newDefs += outerAccessorDef // (1)
               }
               if (!currentClass.isTrait)
-                for (val mc <- currentClass.mixinClasses)
+                for (mc <- currentClass.mixinClasses)
                   if (outerAccessor(mc) != NoSymbol)
                     newDefs += mixinOuterAccessorDef(mc)
             }
           }
           super.transform(
-            copy.Template(tree, parents, self, 
+            treeCopy.Template(tree, parents, self, 
                           if (newDefs.isEmpty) decls else decls ::: newDefs.toList)
           )
         case DefDef(mods, name, tparams, vparamss, tpt, rhs) =>
@@ -376,7 +451,7 @@ abstract class ExplicitOuter extends InfoTransform with TransMatcher with Patter
                       sym.newValueParameter(sym.pos, nme.OUTER) setInfo outerField(clazz).info
                     ((ValDef(outerParam) setType NoType) :: vparamss.head) :: vparamss.tail
                   } else vparamss
-                super.transform(copy.DefDef(tree, mods, name, tparams, vparamss1, tpt, rhs))
+                super.transform(treeCopy.DefDef(tree, mods, name, tparams, vparamss1, tpt, rhs))
             }
           } else
             super.transform(tree)
@@ -394,93 +469,33 @@ abstract class ExplicitOuter extends InfoTransform with TransMatcher with Patter
             sym setFlag notPROTECTED
           super.transform(tree)
 
-        case Apply(sel @ Select(qual, name), args)
-          if (name == nme.CONSTRUCTOR && isInner(sel.symbol.owner)) =>
-            val outerVal = atPos(tree.pos) {
-              if (qual.isInstanceOf[This]) { // it's a call between constructors of same class
-                assert(outerParam != NoSymbol)
-                outerValue
-              } else {
-                var pre = qual.tpe.prefix
-                if (pre == NoPrefix) pre = sym.owner.outerClass.thisType
-                gen.mkAttributedQualifier(pre)
-              }
-            }
-            super.transform(copy.Apply(tree, sel, outerVal :: args))
-
-        case mch @ Match(selector, cases) => // <----- transmatch hook
-          val tid = if (settings.debug.value) {
-            val q = unit.fresh.newName(mch.pos, "tidmark")
-            Console.println("transforming patmat with tidmark "+q+" ncases = "+cases.length)
-            q
-          } else null
-
-
-          var nselector = transform(selector)
-
-          def makeGuardDef(vs:List[Symbol], guard:Tree) = {
-            import symtab.Flags._
-            val gdname = cunit.fresh.newName(guard.pos, "gd")
-            val fmls = new ListBuffer[Type]
-            val method = currentOwner.newMethod(mch.pos, gdname) setFlag (SYNTHETIC) 
-            var vs1 = vs; while (vs1 ne Nil) {
-              fmls += vs1.head.tpe
-              vs1 = vs1.tail
-            }
-            val tpe    = new MethodType(fmls.toList, definitions.BooleanClass.tpe)
-            method setInfo tpe
-            localTyper.
-            typed { 
-              DefDef(method, 
-                     {vparamss => 
-                        new ChangeOwnerTraverser(currentOwner, method).traverse(guard);
-                        new TreeSymSubstituter(vs, vparamss.head).traverse(guard);guard})}
-          }
-
-          val nguard = new ListBuffer[Tree]
-          val ncases = new ListBuffer[CaseDef] 
-          var cs = cases; while (cs ne Nil) {
-            cs.head match {
-              case CaseDef(p,EmptyTree,b) => 
-                ncases += CaseDef(transform(p), EmptyTree, transform(b))
-              case CaseDef(p, guard, b) => 
-                val vs       = definedVars(p)
-                val guardDef = makeGuardDef(vs, guard)
-                nguard += transform(guardDef)
-                val gdcall = localTyper.typed{Apply(Ident(guardDef.symbol),vs.map {Ident(_)})}
-                ncases += CaseDef(transform(p), gdcall, transform(b))
-            }
-            cs = cs.tail
-          }
-
-          var checkExhaustive = true
-          def isUncheckedAnnotation(tpe: Type) = tpe match {
-            case AnnotatedType(List(AnnotationInfo(atp, _, _)), _, _) if atp.typeSymbol == UncheckedClass =>
-              true
-            case _ =>
-              false
-          }
-          nselector match {
-            case Typed(nselector1, tpt) if isUncheckedAnnotation(tpt.tpe) =>
-              nselector = nselector1
-              checkExhaustive = false
-            case _ =>
-          }
-
-          ExplicitOuter.this.resultType = tree.tpe
-
-          val t = atPos(tree.pos) { 
-            val t_untyped = handlePattern(nselector, ncases.toList, checkExhaustive, currentOwner, transform)(localTyper)
-            localTyper.typed(t_untyped, resultType) 
+        case Apply(sel @ Select(qual, name), args) if (name == nme.CONSTRUCTOR && isInner(sel.symbol.owner)) =>
+          val outerVal = atPos(tree.pos)(qual match {
+            // it's a call between constructors of same class
+            case _: This  => 
+              assert(outerParam != NoSymbol)
+              outerValue
+            case _        =>
+              gen.mkAttributedQualifier(qual.tpe.prefix match {
+                case NoPrefix => sym.owner.outerClass.thisType
+                case x        => x
+              })
+          })
+          super.transform(treeCopy.Apply(tree, sel, outerVal :: args))
+
+        // TransMatch hook
+        case mch: Match =>
+          matchTranslation(mch)
+          
+        case _ =>
+          if (settings.Xmigration28.value) tree match {
+            case TypeApply(fn @ Select(qual, _), args) if fn.symbol == Object_isInstanceOf || fn.symbol == Any_isInstanceOf =>
+              if (isArraySeqTest(qual.tpe, args.head.tpe))
+                unit.warning(tree.pos, "An Array will no longer match as Seq[_].")
+            case _ => ()
           }
 
-          if (settings.debug.value)
-            Console.println("finished translation of " + tid)
-
-          if(nguard.isEmpty) {t} else Block(nguard.toList, t) setType t.tpe
-        case _ =>
           val x = super.transform(tree)
-
           if (x.tpe eq null) x
           else x setType transformInfo(currentOwner, x.tpe)
       }
@@ -490,6 +505,7 @@ abstract class ExplicitOuter extends InfoTransform with TransMatcher with Patter
     override def transformUnit(unit: CompilationUnit) {
       cunit = unit
       atPhase(phase.next) { super.transformUnit(unit) }
+      cunit = null
     }
   }
 
diff --git a/src/compiler/scala/tools/nsc/transform/Flatten.scala b/src/compiler/scala/tools/nsc/transform/Flatten.scala
index 885ae2d..60f51fd 100644
--- a/src/compiler/scala/tools/nsc/transform/Flatten.scala
+++ b/src/compiler/scala/tools/nsc/transform/Flatten.scala
@@ -1,10 +1,10 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author Martin Odersky
  */
-// $Id: Flatten.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.tools.nsc.transform
+package scala.tools.nsc
+package transform
 
 import symtab._
 import Flags._
@@ -13,7 +13,6 @@ import scala.collection.mutable.{HashMap, ListBuffer}
 abstract class Flatten extends InfoTransform {
   import global._
   import definitions._
-  import posAssigner.atPos
 
   /** the following two members override abstract members in Transform */
   val phaseName: String = "flatten"
@@ -39,14 +38,14 @@ abstract class Flatten extends InfoTransform {
         typeRef(sym.toplevelClass.owner.thisType, sym, args)
       case ClassInfoType(parents, decls, clazz) =>
         var parents1 = parents
-        val decls1 = newScope
+        val decls1 = new Scope
         if (clazz.isPackageClass) {
           atPhase(phase.next)(decls.toList foreach (sym => decls1 enter sym))
         } else {
           val oldowner = clazz.owner
           atPhase(phase.next)(oldowner.info)
-          parents1 = List.mapConserve(parents)(this)
-          for (val sym <- decls.toList) {
+          parents1 = parents mapConserve (this)
+          for (sym <- decls.toList) {
             if (sym.isTerm && !sym.isStaticModule) {
               decls1 enter sym
               if (sym.isModule) sym.moduleClass setFlag LIFTED
@@ -57,6 +56,9 @@ abstract class Flatten extends InfoTransform {
           }
         }
         ClassInfoType(parents1, decls1, clazz)
+      case MethodType(params, restp) =>
+        val restp1 = apply(restp)
+        if (restp1 eq restp) tp else copyMethodType(tp, params, restp1)
       case PolyType(tparams, restp) =>
         val restp1 = apply(restp);
         if (restp1 eq restp) tp else PolyType(tparams, restp1)
@@ -78,6 +80,8 @@ abstract class Flatten extends InfoTransform {
       tree match {
         case PackageDef(_, _) =>
           liftedDefs(tree.symbol.moduleClass) = new ListBuffer
+        case Template(_, _, _) if (tree.symbol.owner.hasFlag(PACKAGE)) =>
+          liftedDefs(tree.symbol.owner) = new ListBuffer
         case _ =>
       }
       postTransform(super.transform(tree))
diff --git a/src/compiler/scala/tools/nsc/transform/InfoTransform.scala b/src/compiler/scala/tools/nsc/transform/InfoTransform.scala
index b029565..fa93a9b 100644
--- a/src/compiler/scala/tools/nsc/transform/InfoTransform.scala
+++ b/src/compiler/scala/tools/nsc/transform/InfoTransform.scala
@@ -1,10 +1,10 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author
  */
-// $Id: InfoTransform.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.tools.nsc.transform
+package scala.tools.nsc
+package transform
 
 /** <p>
  *    A base class for transforms.
@@ -22,8 +22,11 @@ trait InfoTransform extends Transform {
     new Phase(prev)
 
   protected def changesBaseClasses = true
+  protected def keepsTypeParams = true
 
   class Phase(prev: scala.tools.nsc.Phase) extends super.Phase(prev) {
+    override val keepsTypeParams = InfoTransform.this.keepsTypeParams
+
     if (infoTransformers.nextFrom(id).pid != id) {
       // this phase is not yet in the infoTransformers
       val infoTransformer = new InfoTransformer {
diff --git a/src/compiler/scala/tools/nsc/transform/LambdaLift.scala b/src/compiler/scala/tools/nsc/transform/LambdaLift.scala
index 3e6d725..3a0f938 100644
--- a/src/compiler/scala/tools/nsc/transform/LambdaLift.scala
+++ b/src/compiler/scala/tools/nsc/transform/LambdaLift.scala
@@ -1,22 +1,20 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author
  */
-// $Id: LambdaLift.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.tools.nsc.transform
+package scala.tools.nsc
+package transform
 
 import symtab._
 import Flags._
 import util.TreeSet
-import scala.collection.mutable.{HashMap, ListBuffer}
-import scala.tools.nsc.util.{Position, NoPosition}
+import scala.collection.mutable.{HashMap, LinkedHashMap, ListBuffer}
 
 abstract class LambdaLift extends InfoTransform {
   import global._
   import definitions._
   import typer.{typed, typedOperator}
-  import posAssigner.atPos
 
   /** the following two members override abstract members in Transform */
   val phaseName: String = "lambdalift"
@@ -29,7 +27,7 @@ abstract class LambdaLift extends InfoTransform {
           typeRef(apply(sym.owner.enclClass.thisType), sym, args)
         } else mapOver(tp)
       case ClassInfoType(parents, decls, clazz) =>
-        val parents1 = List.mapConserve(parents)(this)
+        val parents1 = parents mapConserve (this)
         if (parents1 eq parents) tp
         else ClassInfoType(parents1, decls, clazz)
       case _ =>
@@ -45,13 +43,13 @@ abstract class LambdaLift extends InfoTransform {
   class LambdaLifter(unit: CompilationUnit) extends explicitOuter.OuterPathTransformer(unit) {
 
     /** A map storing free variables of functions and classes */
-    private val free = new HashMap[Symbol, SymSet]
+    private val free = new LinkedHashMap[Symbol, SymSet]
 
     /** A map storing the free variable proxies of functions and classes */
-    private val proxies = new HashMap[Symbol, List[Symbol]]
+    private val proxies = new LinkedHashMap[Symbol, List[Symbol]]
 
     /** A hashtable storing calls between functions */
-    private val called = new HashMap[Symbol, SymSet]
+    private val called = new LinkedHashMap[Symbol, SymSet]
 
     /** The set of symbols that need to be renamed. */
     private val renamable = newSymSet
@@ -60,13 +58,13 @@ abstract class LambdaLift extends InfoTransform {
     private var changedFreeVars: Boolean = _
 
     /** Buffers for lifted out classes and methods */
-    private val liftedDefs = new HashMap[Symbol, ListBuffer[Tree]]
+    private val liftedDefs = new LinkedHashMap[Symbol, ListBuffer[Tree]]
 
     private type SymSet = TreeSet[Symbol]
 
     private def newSymSet = new TreeSet[Symbol]((x, y) => x.isLess(y))
 
-    private def symSet(f: HashMap[Symbol, SymSet], sym: Symbol): SymSet = f.get(sym) match {
+    private def symSet(f: LinkedHashMap[Symbol, SymSet], sym: Symbol): SymSet = f.get(sym) match {
       case Some(ss) => ss
       case None => val ss = newSymSet; f(sym) = ss; ss
     }
@@ -102,9 +100,8 @@ abstract class LambdaLift extends InfoTransform {
       def localToConstr(sym: Symbol) =
         if (sym.isLocalDummy) sym.owner.primaryConstructor else sym;
       var encl = localToConstr(sym)
-      while (!encl.isMethod && !encl.isClass) {
-        encl = localToConstr(outer(encl));
-      } 
+      while (!encl.isMethod && !encl.isClass)
+        encl = localToConstr(outer(encl))
       encl
     }
 
@@ -148,6 +145,15 @@ abstract class LambdaLift extends InfoTransform {
         if (!(ss contains sym)) {
           ss addEntry sym
           renamable addEntry sym
+          atPhase(currentRun.picklerPhase) {
+            // The param symbol in the MethodType should not be renamed, only the symbol in scope. This way,
+            // parameter names for named arguments are not changed. Example: without cloning the MethodType,
+            //     def closure(x: Int) = { () => x }
+            // would have the signature
+            //     closure: (x$1: Int)() => Int
+            if (sym.hasFlag(PARAM) && sym.owner.info.paramss.exists(_.contains(sym)))
+              sym.owner.setInfo(sym.owner.info.cloneInfo(sym.owner))
+          }
           changedFreeVars = true
           if (settings.debug.value) log("" + sym + " is free in " + owner);
           if (sym.isVariable && !(sym hasFlag CAPTURED)) {
@@ -155,7 +161,11 @@ abstract class LambdaLift extends InfoTransform {
             val symClass = sym.tpe.typeSymbol;
             atPhase(phase.next) {
               sym updateInfo (
-                if (isValueClass(symClass)) refClass(symClass).tpe else ObjectRefClass.tpe)
+                if (sym.hasAnnotation(VolatileAttr))
+                  if (isValueClass(symClass)) volatileRefClass(symClass).tpe else VolatileObjectRefClass.tpe
+                else
+                  if (isValueClass(symClass)) refClass(symClass).tpe else ObjectRefClass.tpe
+              )
             }
           }
         }
@@ -182,7 +192,7 @@ abstract class LambdaLift extends InfoTransform {
     }
 */
     def freeVars(sym: Symbol): Iterator[Symbol] = free.get(sym) match {
-      case Some(ss) => ss.elements
+      case Some(ss) => ss.iterator
       case None => Iterator.empty
     }
 
@@ -237,13 +247,13 @@ abstract class LambdaLift extends InfoTransform {
 
       do {
         changedFreeVars = false
-        for (caller <- called.keys;
-             callee <- called(caller).elements;
+        for (caller <- called.keysIterator;
+             callee <- called(caller).iterator;
              fv <- freeVars(callee))
           markFree(fv, caller)
       } while (changedFreeVars);
 
-      for (sym <- renamable.elements) {
+      for (sym <- renamable.iterator) {
         val base =
           if (sym.isAnonymousFunction && sym.owner.isMethod)
             sym.name.toString() + "$" + sym.owner.name.toString() + "$"
@@ -254,11 +264,11 @@ abstract class LambdaLift extends InfoTransform {
       }
 
       atPhase(phase.next) {
-        for (owner <- free.keys) {
+        for (owner <- free.keysIterator) {
           if (settings.debug.value)
-            log("free(" + owner + owner.locationString + ") = " + free(owner).elements.toList);
+            log("free(" + owner + owner.locationString + ") = " + free(owner).iterator.toList);
           proxies(owner) =
-            for (fv <- free(owner).elements.toList) yield {
+            for (fv <- free(owner).iterator.toList) yield {
               val proxy = owner.newValue(owner.pos, fv.name)
                 .setFlag(if (owner.isClass) PARAMACCESSOR | PRIVATE | LOCAL else PARAM)
                 .setFlag(SYNTHETIC)
@@ -319,19 +329,65 @@ abstract class LambdaLift extends InfoTransform {
         val freeParams = ps map (p => ValDef(p) setPos tree.pos setType NoType);
         tree match {
           case DefDef(mods, name, tparams, List(vparams), tpt, rhs) =>
+            val addParams = cloneSymbols(ps).map(_.setFlag(PARAM))            
             sym.updateInfo(
-              lifted(MethodType(sym.info.paramTypes ::: (ps map (_.tpe)), sym.info.resultType)));
-            copy.DefDef(tree, mods, name, tparams, List(vparams ::: freeParams), tpt, rhs)
+              lifted(MethodType(sym.info.params ::: addParams, sym.info.resultType)))
+            treeCopy.DefDef(tree, mods, name, tparams, List(vparams ::: freeParams), tpt, rhs)
           case ClassDef(mods, name, tparams, impl @ Template(parents, self, body)) =>
-            copy.ClassDef(tree, mods, name, tparams,
-                          copy.Template(impl, parents, self, body ::: freeParams))
+            // Disabled attempt to to add getters to freeParams
+            // this does not work yet. Problem is that local symbols need local names
+            // and references to local symbols need to be transformed into
+            // method calls to setters.
+            // def paramGetter(param: Symbol): Tree = {
+            //   val getter = param.newGetter setFlag TRANS_FLAG resetFlag PARAMACCESSOR // mark because we have to add them to interface
+            //   sym.info.decls.enter(getter)
+            //   val rhs = Select(gen.mkAttributedThis(sym), param) setType param.tpe
+            //   DefDef(getter, rhs) setPos tree.pos setType NoType
+            // }
+            // val newDefs = if (sym.isTrait) freeParams ::: (ps map paramGetter) else freeParams
+            treeCopy.ClassDef(tree, mods, name, tparams,
+                              treeCopy.Template(impl, parents, self, body ::: freeParams))
         }
       case None =>
         tree
     }
-
+    
+/*  Something like this will be necessary to eliminate the implementation
+ *  restiction from paramGetter above:
+ *  We need to pass getters to the interface of an implementation class.
+    private def fixTraitGetters(lifted: List[Tree]): List[Tree] = 
+      for (stat <- lifted) yield stat match {
+        case ClassDef(mods, name, tparams, templ @ Template(parents, self, body)) 
+        if stat.symbol.isTrait && !stat.symbol.isImplClass =>
+          val iface = stat.symbol
+          lifted.find(l => l.symbol.isImplClass && l.symbol.toInterface == iface) match {
+            case Some(implDef) =>
+              val impl = implDef.symbol
+              val implGetters = impl.info.decls.toList filter (_ hasFlag TRANS_FLAG)
+              if (implGetters.nonEmpty) {
+                val ifaceGetters = implGetters map { ig =>
+                  ig resetFlag TRANS_FLAG
+                  val getter = ig cloneSymbol iface setFlag DEFERRED
+                  iface.info.decls enter getter
+                  getter
+                }
+                val ifaceGetterDefs = ifaceGetters map (DefDef(_, EmptyTree) setType NoType)
+                treeCopy.ClassDef(
+                  stat, mods, name, tparams,
+                  treeCopy.Template(templ, parents, self, body ::: ifaceGetterDefs))
+              } else 
+                stat
+            case None =>
+              stat
+          }
+        case _ =>
+          stat
+      }
+*/
     private def liftDef(tree: Tree): Tree = {
       val sym = tree.symbol
+      if (sym.owner.isAuxiliaryConstructor && sym.isMethod)  // # bug 1909 
+    	  sym setFlag STATIC
       sym.owner = sym.owner.enclClass
       if (sym.isClass) sym.owner = sym.owner.toInterface
       if (sym.isMethod) sym setFlag LIFTED
@@ -359,20 +415,20 @@ abstract class LambdaLift extends InfoTransform {
                   Apply(Select(New(TypeTree(sym.tpe)), nme.CONSTRUCTOR), List(rhs))
                 }
               }
-            copy.ValDef(tree, mods, name, tpt1, rhs1)
+            treeCopy.ValDef(tree, mods, name, tpt1, rhs1)
           } else tree
         case Return(Block(stats, value)) =>
-          Block(stats, copy.Return(tree, value)) setType tree.tpe setPos tree.pos
+          Block(stats, treeCopy.Return(tree, value)) setType tree.tpe setPos tree.pos
         case Return(expr) =>
           assert(sym == currentMethod, sym)
           tree
         case Apply(fn, args) =>
-          copy.Apply(tree, fn, addFreeArgs(tree.pos, sym, args))
+          treeCopy.Apply(tree, fn, addFreeArgs(tree.pos, sym, args))
         case Assign(Apply(TypeApply(sel @ Select(qual, _), _), List()), rhs) =>
           // eliminate casts introduced by selecting a captured variable field
           // on the lhs of an assignment.
           assert(sel.symbol == Object_asInstanceOf)
-          copy.Assign(tree, qual, rhs)
+          treeCopy.Assign(tree, qual, rhs)
         case Ident(name) =>
           val tree1 =
             if (sym != NoSymbol && sym.isTerm && !sym.isLabel)
@@ -401,11 +457,14 @@ abstract class LambdaLift extends InfoTransform {
     override def transformStats(stats: List[Tree], exprOwner: Symbol): List[Tree] = {
       def addLifted(stat: Tree): Tree = stat match {
         case ClassDef(mods, name, tparams, impl @ Template(parents, self, body)) =>
-          val lifted = liftedDefs(stat.symbol).toList map addLifted
-          val result = copy.ClassDef(
-            stat, mods, name, tparams, copy.Template(impl, parents, self, body ::: lifted))
+          val lifted = /*fixTraitGetters*/(liftedDefs(stat.symbol).toList map addLifted)
+          val result = treeCopy.ClassDef(
+            stat, mods, name, tparams, treeCopy.Template(impl, parents, self, body ::: lifted))
           liftedDefs -= stat.symbol
           result
+        case DefDef(mods, name, tp, vp, tpt, Block(Nil, expr))
+        if !stat.symbol.isConstructor =>
+          treeCopy.DefDef(stat, mods, name, tp, vp, tpt, expr)
         case _ =>
           stat
       }
diff --git a/src/compiler/scala/tools/nsc/transform/LazyVals.scala b/src/compiler/scala/tools/nsc/transform/LazyVals.scala
index edb0fac..1c427f6 100644
--- a/src/compiler/scala/tools/nsc/transform/LazyVals.scala
+++ b/src/compiler/scala/tools/nsc/transform/LazyVals.scala
@@ -1,36 +1,26 @@
-package scala.tools.nsc.transform;
+package scala.tools.nsc
+package transform;
 
 import scala.tools.nsc._
 import scala.collection.mutable.HashMap
 
-abstract class LazyVals extends Transform {
+abstract class LazyVals extends Transform with TypingTransformers with ast.TreeDSL {
   // inherits abstract value `global' and class `Phase' from Transform
 
   import global._                  // the global environment
   import definitions._             // standard classes and methods
   import typer.{typed, atOwner}    // methods to type trees
-  import posAssigner.atPos         // for filling in tree positions 
+  import CODE._
 
   val phaseName: String = "lazyvals"
 
   def newTransformer(unit: CompilationUnit): Transformer =
     new LazyValues(unit)
 
-  /** Create a new phase which applies transformer */
-  override def newPhase(prev: scala.tools.nsc.Phase): StdPhase = new Phase(prev)
-
-  /** The phase defined by this transform */
-  class Phase(prev: scala.tools.nsc.Phase) extends StdPhase(prev) {
-    def apply(unit: global.CompilationUnit): Unit =
-        newTransformer(unit).transformUnit(unit);
-  }
-
   /**
    * Transform local lazy accessors to check for the initialized bit.
    */
-  class LazyValues(unit: CompilationUnit) extends Transformer {
-    
-    import definitions.{Int_And, Int_Or, Int_==}    
+  class LazyValues(unit: CompilationUnit) extends TypingTransformer(unit) {    
     /** map from method symbols to the number of lazy values it defines. */
     private val lazyVals = new HashMap[Symbol, Int] {
       override def default(meth: Symbol) = 0
@@ -49,8 +39,10 @@ abstract class LazyVals extends Transform {
      */
     override def transform(tree: Tree): Tree = {
       val sym = tree.symbol
+      curTree = tree
+      
       tree match {
-        case DefDef(mods, name, tparams, vparams, tpt, rhs) =>
+        case DefDef(mods, name, tparams, vparams, tpt, rhs) => atOwner(tree.symbol) {
           val res = if (!sym.owner.isClass && sym.hasFlag(LAZY)) {
             val enclosingDummyOrMethod = 
               if (sym.enclMethod == NoSymbol) sym.owner else sym.enclMethod
@@ -61,10 +53,11 @@ abstract class LazyVals extends Transform {
             rhs1
           } else
             super.transform(rhs)
-          copy.DefDef(tree, mods, name, tparams, vparams, tpt, 
-                      typed(addBitmapDefs(sym, res)))
+          treeCopy.DefDef(tree, mods, name, tparams, vparams, tpt, 
+                          typed(addBitmapDefs(sym, res)))
+        }
 
-        case Template(parents, self, body) =>
+        case Template(parents, self, body) => atOwner(currentOwner) {
           val body1 = super.transformTrees(body)
           var added = false
           val stats = 
@@ -72,33 +65,40 @@ abstract class LazyVals extends Transform {
               case Block(_, _) if !added => 
                 added = true
                 typed(addBitmapDefs(sym, stat))
-              case ValDef(mods, name, tpt, b @ Block(_, _)) =>
-                typed(copy.ValDef(stat, mods, name, tpt, addBitmapDefs(stat.symbol, b)))
+              case ValDef(mods, name, tpt, rhs) =>
+                typed(treeCopy.ValDef(stat, mods, name, tpt, addBitmapDefs(stat.symbol, rhs)))
               case _ => 
                 stat
             }
-          copy.Template(tree, parents, self, stats)
+          treeCopy.Template(tree, parents, self, stats)
+        }
           
         case _ => super.transform(tree)
       }
     }
 
     /** Add the bitmap definitions to the rhs of a method definition.
-     *  If the rhs has been tail-call trasnformed, insert the bitmap
+     *  If the rhs has been tail-call transformed, insert the bitmap
      *  definitions inside the top-level label definition, so that each
      *  iteration has the lazy values un-initialized. Otherwise add them
      *  at the very beginning of the method.
      */
     private def addBitmapDefs(methSym: Symbol, rhs: Tree): Tree = {
-      val bmps = bitmaps(methSym) map { b => ValDef(b, Literal(Constant(0))) }
+      def prependStats(stats: List[Tree], tree: Tree): Block = tree match {
+        case Block(stats1, res) => Block(stats ::: stats1, res)
+        case _ => Block(stats, tree)
+      }
+
+      val bmps = bitmaps(methSym) map (ValDef(_, ZERO))
+
+      def isMatch(params: List[Ident]) = (params.tail corresponds methSym.tpe.params)(_.tpe == _.tpe)
+
       if (bmps.isEmpty) rhs else rhs match {
         case Block(assign, l @ LabelDef(name, params, rhs1))
-          if (name.toString.equals("_" + methSym.name)
-              && List.forall2(params.tail, methSym.tpe.paramTypes) { (ident, tpe) => ident.tpe == tpe }) =>
-            val sym = l.symbol
-            Block(assign, copy.LabelDef(l, name, params, typed(Block(bmps, rhs1))))
+          if name.toString == ("_" + methSym.name) && isMatch(params) =>
+            Block(assign, treeCopy.LabelDef(l, name, params, typed(prependStats(bmps, rhs1))))
 
-        case _ => Block(bmps, rhs)
+        case _ => prependStats(bmps, rhs)
       }
     }
     
@@ -121,7 +121,7 @@ abstract class LazyVals extends Transform {
      *  }
      *  where bitmap$n is an int value acting as a bitmap of initialized values. It is
      *  the 'n' is (offset / 32), the MASK is (1 << (offset % 32)). If the value has type
-     *  unit, no field is used to chache the value, so the resulting code is:
+     *  unit, no field is used to cache the value, so the resulting code is:
      *  {
      *    if ((bitmap$n & MASK) == 0) {
      *       <rhs>;
@@ -130,33 +130,27 @@ abstract class LazyVals extends Transform {
      *    ()
      *  }
      */
-    private def mkLazyDef(meth: Symbol, tree: Tree, offset: Int): Tree = {
-      val bitmapSym = getBitmapFor(meth, offset)
-      val mask = Literal(Constant(1 << (offset % FLAGS_PER_WORD)))
-      
+    private def mkLazyDef(meth: Symbol, tree: Tree, offset: Int): Tree = {      
+      val bitmapSym           = getBitmapFor(meth, offset)
+      val mask                = LIT(1 << (offset % FLAGS_PER_WORD))
+      def mkBlock(stmt: Tree) = BLOCK(stmt, mkSetFlag(bitmapSym, mask), UNIT)
+
       val (block, res) = tree match {
-        case Block(List(assignment), res) =>
-          (Block(List(assignment, mkSetFlag(bitmapSym, mask)), Literal(Constant(()))), res)
-        case rhs =>
-          assert(meth.tpe.finalResultType.typeSymbol == definitions.UnitClass)
-          (Block(List(rhs, mkSetFlag(bitmapSym, mask)), Literal(Constant(()))), Literal(()))
-      }
-      
-      val result = atPos(tree.pos) {
-        If(Apply(
-            Select(
-              Apply(Select(Ident(bitmapSym), Int_And), 
-                    List(mask)),
-              Int_==),
-            List(Literal(Constant(0)))), block, EmptyTree)
+        case Block(List(assignment), res) => (mkBlock(assignment),  res)
+        case rhs                          => (mkBlock(rhs),         UNIT)          
       }
-      typed(Block(List(result), res))
+      assert(res != UNIT || meth.tpe.finalResultType.typeSymbol == UnitClass)
+
+      val cond = (Ident(bitmapSym) INT_& mask) INT_== ZERO
+
+      atPos(tree.pos)(localTyper.typed {
+        def body = gen.mkDoubleCheckedLocking(meth.enclClass, cond, List(block), Nil)
+        BLOCK(body, res)
+      })
     }
      
-    private def mkSetFlag(bmp: Symbol, mask: Tree): Tree = 
-      Assign(Ident(bmp),
-        Apply(Select(Ident(bmp), Int_Or), List(mask)))
-    
+    private def mkSetFlag(bmp: Symbol, mask: Tree): Tree =
+      Ident(bmp) === (Ident(bmp) INT_| mask)
     
     final val FLAGS_PER_WORD = 32
     val bitmaps = new HashMap[Symbol, List[Symbol]] {
@@ -173,6 +167,10 @@ abstract class LazyVals extends Transform {
         bmps(n)
       else {
         val sym = meth.newVariable(meth.pos, nme.bitmapName(n)).setInfo(IntClass.tpe)
+        atPhase(currentRun.typerPhase) {
+          sym addAnnotation AnnotationInfo(VolatileAttr.tpe, Nil, Nil)
+        }
+        
         bitmaps(meth) = (sym :: bmps).reverse
         sym
       }
diff --git a/src/compiler/scala/tools/nsc/transform/LiftCode.scala b/src/compiler/scala/tools/nsc/transform/LiftCode.scala
index b7a4af5..410c3a2 100644
--- a/src/compiler/scala/tools/nsc/transform/LiftCode.scala
+++ b/src/compiler/scala/tools/nsc/transform/LiftCode.scala
@@ -1,10 +1,10 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author Gilles Dubochet
  */
-// $Id: LiftCode.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.tools.nsc.transform
+package scala.tools.nsc
+package transform
 
 import symtab._
 import Flags._
@@ -24,7 +24,6 @@ abstract class LiftCode extends Transform with Reifiers {
   import global._                  // the global environment
   import definitions._             // standard classes and methods
   import typer.{typed, atOwner}    // methods to type trees
-  import posAssigner.atPos         // for filling in tree positions
 
   val symbols: global.type = global
 
@@ -64,7 +63,7 @@ abstract class LiftCode extends Transform with Reifiers {
     }
 
     def objectName(value: Any): String = value match {
-      case Nil                => "scala.Nil"
+      case Nil                => "scala.collection.immutable.Nil"
       case reflect.NoSymbol   => "scala.reflect.NoSymbol"
       case reflect.RootSymbol => "scala.reflect.RootSymbol"
       case reflect.NoPrefix   => "scala.reflect.NoPrefix"
@@ -79,7 +78,7 @@ abstract class LiftCode extends Transform with Reifiers {
           gen.mkAttributedRef(definitions.getModule(name))
         else {
           val name = className(c)
-          if (name.length() == 0) throw new Error("don't know how to inject " + value)
+          if (name.length() == 0) abort("don't know how to inject " + value)
           val injectedArgs = new ListBuffer[Tree]
           for (i <- 0 until c.productArity)
             injectedArgs += inject(c.productElement(i))
@@ -103,7 +102,7 @@ abstract class LiftCode extends Transform with Reifiers {
         case null =>
           gen.mkAttributedRef(definitions.getModule("scala.reflect.NoType"))
         case _ =>
-          throw new Error("don't know how to inject " + value)
+          abort("don't know how to inject " + value)
       }
     }
   } // Injector
@@ -121,7 +120,7 @@ abstract class LiftCode extends Transform with Reifiers {
 
 // case EmptyTree =>
 // case LiftPoint(tree) =>
-// case PackageDef(name, stats) => 
+// case PackageDef(pid, stats) => 
 // case ClassDef(mods, name, tparams, impl) => 
 // case ValDef(mods, name, tpt, rhs) => 
 // case DefDef(mods, name, tparams, vparamss, tpt, rhs) =>
@@ -148,7 +147,6 @@ abstract class LiftCode extends Transform with Reifiers {
 // case TypeTree() =>
 // /* Pattern matching */
 // case CaseDef(pat, guard, body) =>
-// case Sequence(trees) =>
 // case Alternative(trees) =>
 // case Star(elem) =>
 // case Bind(name, body) =>
diff --git a/src/compiler/scala/tools/nsc/transform/Mixin.scala b/src/compiler/scala/tools/nsc/transform/Mixin.scala
index 4abf8ef..2e67464 100644
--- a/src/compiler/scala/tools/nsc/transform/Mixin.scala
+++ b/src/compiler/scala/tools/nsc/transform/Mixin.scala
@@ -1,26 +1,24 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author Martin Odersky
  */
-// $Id: Mixin.scala 19071 2009-10-13 07:45:55Z dragos $
 
-package scala.tools.nsc.transform
+package scala.tools.nsc
+package transform
 
 import symtab._
 import Flags._
-import scala.collection.mutable.ListBuffer
-import scala.tools.nsc.util.{Position,NoPosition}
-import scala.collection.mutable.HashMap
+import collection.mutable.{ListBuffer, HashMap}
 
-abstract class Mixin extends InfoTransform {
+abstract class Mixin extends InfoTransform with ast.TreeDSL {
   import global._
   import definitions._
-  import posAssigner.atPos
+  import CODE._
 
   /** The name of the phase: */
   val phaseName: String = "mixin"
 
-  /** The phase might set the fiollowing new flags: */
+  /** The phase might set the following new flags: */
   override def phaseNewFlags: Long = lateMODULE | notABSTRACT
 
   /** This map contains a binding (class -> info) if
@@ -98,14 +96,14 @@ abstract class Mixin extends InfoTransform {
       var sym: Symbol = NoSymbol
       if (settings.debug.value)
         log("starting rebindsuper " + base + " " + member + ":" + member.tpe +
-            " " + mixinClass + " " + base.info.baseClasses)
+            " " + mixinClass + " " + base.info.baseClasses + "/" + bcs)
       while (!bcs.isEmpty && sym == NoSymbol) {
         if (settings.debug.value) {
           val other = bcs.head.info.nonPrivateDecl(member.name);
           log("rebindsuper " + bcs.head + " " + other + " " + other.tpe +
               " " + other.isDeferred)
         }
-        sym = member.overridingSymbol(bcs.head).suchThat(sym => !sym.hasFlag(DEFERRED | BRIDGE))
+        sym = member.matchingSymbol(bcs.head, base.thisType).suchThat(sym => !sym.hasFlag(DEFERRED | BRIDGE))
         bcs = bcs.tail
       }
       assert(sym != NoSymbol, member)
@@ -139,16 +137,15 @@ abstract class Mixin extends InfoTransform {
     member setFlag MIXEDIN
   }
 
-  def needsExpandedSetterName(field: Symbol) = 
-    settings.Xexperimental.value && !field.hasFlag(LAZY | MUTABLE)
+  def needsExpandedSetterName(field: Symbol) =
+    !(field hasFlag LAZY) &&
+    (if (field.isMethod) (field hasFlag STABLE) else !(field hasFlag MUTABLE))
 
   /** Add getters and setters for all non-module fields of an implementation
    *  class to its interface unless they are already present. This is done
    *  only once per class. The mixedin flag is used to remember whether late
    *  members have been added to an interface.
    *    - lazy fields don't get a setter.
-   *  
-   *  @param clazz ...
    */
   def addLateInterfaceMembers(clazz: Symbol) {
     if ((treatedClassInfos get clazz) != Some(clazz.info)) {
@@ -157,19 +154,26 @@ abstract class Mixin extends InfoTransform {
 
       /** Create a new getter. Getters are never private or local. They are
        *  always accessors and deferred. */
-      def newGetter(field: Symbol): Symbol =
+      def newGetter(field: Symbol): Symbol = {
+        //println("creating new getter for "+field+field.locationString+(field hasFlag MUTABLE))
         clazz.newMethod(field.pos, nme.getterName(field.name))
-          .setFlag(field.flags & ~(PRIVATE | LOCAL) | ACCESSOR | lateDEFERRED)
+          .setFlag(field.flags & ~(PRIVATE | LOCAL) | ACCESSOR | lateDEFERRED | 
+                     (if (field hasFlag MUTABLE) 0 else STABLE))
           .setInfo(MethodType(List(), field.info))
+      }
 
       /** Create a new setter. Setters are never private or local. They are
        *  always accessors and deferred. */
       def newSetter(field: Symbol): Symbol = {
+        //println("creating new setter for "+field+field.locationString+(field hasFlag MUTABLE))
         val setterName = nme.getterToSetter(nme.getterName(field.name))
         val setter = clazz.newMethod(field.pos, setterName)
           .setFlag(field.flags & ~(PRIVATE | LOCAL) | ACCESSOR | lateDEFERRED)
-          .setInfo(MethodType(List(field.info), UnitClass.tpe))
-        if (needsExpandedSetterName(field)) setter.name = clazz.expandedSetterName(setter.name)
+        setter.setInfo(MethodType(setter.newSyntheticValueParams(List(field.info)), UnitClass.tpe))
+        if (needsExpandedSetterName(field)) {
+          //println("creating expanded setter from "+field)
+          setter.name = nme.expandedSetterName(setter.name, clazz)
+        }
         setter
       }
 
@@ -177,7 +181,7 @@ abstract class Mixin extends InfoTransform {
       val impl = implClass(clazz)
       assert(impl != NoSymbol)
 
-      for (val member <- impl.info.decls.toList) {
+      for (member <- impl.info.decls.toList) {
         if (!member.isMethod && !member.isModule && !member.isModuleVar) {
           assert(member.isTerm && !member.isDeferred, member)
           if (member.getter(impl) hasFlag PRIVATE) {
@@ -205,7 +209,7 @@ abstract class Mixin extends InfoTransform {
    *      - if a member M of T is forwarded to the implementation class, add
    *        a forwarder for M unless one exists already.
    *        The alias of the forwarder is the static member it forwards to.
-   *      - for every abstract accessor in T, add a field and an implementation for that acessor
+   *      - for every abstract accessor in T, add a field and an implementation for that accessor
    *      - for every super accessor in T, add an implementation of that accessor
    *      - for every module in T, add a module
    */
@@ -224,15 +228,30 @@ abstract class Mixin extends InfoTransform {
       /** Mix in members of implementation class mixinClass into class clazz */
       def mixinImplClassMembers(impl: Symbol, iface: Symbol) {
         assert (impl.isImplClass)
-        for (val member <- impl.info.decls.toList) {
+        for (member <- impl.info.decls.toList) {
           if (isForwarded(member)) {
             val imember = member.overriddenSymbol(iface)
-            //Console.println("mixin member "+member+":"+member.tpe+member.locationString+" "+imember+" "+imember.overridingSymbol(clazz)+" to "+clazz+" with scope "+clazz.info.decls)//DEBUG
+            // atPhase(currentRun.erasurePhase){ 
+            //   println(""+(clazz, iface, clazz.typeParams, iface.typeParams, imember, clazz.thisType.baseType(iface), clazz.thisType.baseType(iface).memberInfo(imember), imember.info substSym(iface.typeParams, clazz.typeParams)  ))
+            // }
+            // Console.println("mixin member "+member+":"+member.tpe+member.locationString+" "+imember+" "+imember.overridingSymbol(clazz)+" to "+clazz+" with scope "+clazz.info.decls)//DEBUG
             if (imember.overridingSymbol(clazz) == NoSymbol &&
-                clazz.info.findMember(member.name, 0, lateDEFERRED, false)(NoSymbol).alternatives.contains(imember)) {
+                clazz.info.findMember(member.name, 0, lateDEFERRED, false).alternatives.contains(imember)) {
+                  val newSym = atPhase(currentRun.erasurePhase){
+                      val res = imember.cloneSymbol(clazz)
+                      // since we used the member (imember) from the interface that represents the trait that's being mixed in, 
+                      // have to instantiate the interface type params (that may occur in imember's info) as they are seen from the class
+                      // we can't use the member that we get from the implementation class, as it's a clone that was made after erasure, 
+                      // and thus it does not know its info at the beginning of erasure anymore
+                      // optimize: no need if iface has no typeparams
+                      if(iface.typeParams nonEmpty) res.setInfo(clazz.thisType.baseType(iface).memberInfo(imember)) 
+                      res
+                    } // clone before erasure got rid of type info we'll need to generate a javaSig
+                  // now we'll have the type info at (the beginning of) erasure in our history,
+                  newSym.updateInfo(imember.info.cloneInfo(newSym)) // and now newSym has the info that's been transformed to fit this period (no need for asSeenFrom as phase.erasedTypes)
                   val member1 = addMember(
                     clazz,
-                    member.cloneSymbol(clazz) setPos clazz.pos resetFlag (DEFERRED | lateDEFERRED))
+                    newSym setPos clazz.pos resetFlag (DEFERRED | lateDEFERRED))
                   member1.asInstanceOf[TermSymbol] setAlias member;
                 }
           }
@@ -245,7 +264,7 @@ abstract class Mixin extends InfoTransform {
        */
       def mixinTraitMembers(mixinClass: Symbol) {
         // For all members of a trait's interface do:
-        for (val member <- mixinClass.info.decls.toList) {
+        for (member <- mixinClass.info.decls.toList) {
           if (isConcreteAccessor(member)) {
             if (isOverriddenAccessor(member, clazz.info.baseClasses)) {
               if (settings.debug.value) println("!!! is overridden val: "+member)
@@ -263,21 +282,23 @@ abstract class Mixin extends InfoTransform {
               }
               if (!member.isSetter)
                 member.tpe match {
-                  case MethodType(List(), ConstantType(_)) =>
+                  case MethodType(Nil, ConstantType(_)) =>
                     // member is a constant; only getter is needed
                     ;
-                  case MethodType(List(), TypeRef(_, tpeSym, _))
-                    if tpeSym == definitions.UnitClass =>
+                  case MethodType(Nil, TypeRef(_, UnitClass, _)) =>
                     // member is a value of type unit. No field needed
                     ;
                   case _ =>
+                    // atPhase: the private field is moved to the implementation class by erasure,
+                    // so it can no longer be found in the member's owner (the trait)
+                    val accessed = atPhase(currentRun.picklerPhase)(member.accessed)
                     // otherwise mixin a field as well
                     addMember(clazz,
                               clazz.newValue(member.pos, nme.getterToLocal(member.name))
                               setFlag (LOCAL | PRIVATE | member.getFlag(MUTABLE | LAZY))
                               setFlag (if (!member.hasFlag(STABLE)) MUTABLE else 0)
                               setInfo member.tpe.resultType
-                              setAttributes member.attributes)
+                              setAnnotations accessed.annotations)
                 }
             }
           } else if (member hasFlag SUPERACCESSOR) { // mixin super accessors
@@ -295,7 +316,7 @@ abstract class Mixin extends InfoTransform {
         }
       }
 
-      for (val mc <- clazz.mixinClasses)
+      for (mc <- clazz.mixinClasses)
         if (mc hasFlag lateINTERFACE) {
           // @SEAN: adding trait tracking so we don't have to recompile transitive closures
           unit.depends += mc
@@ -335,26 +356,71 @@ abstract class Mixin extends InfoTransform {
           sourceModule setInfo sym.tpe
           assert(clazz.sourceModule != NoSymbol)//debug
           parents1 = List()
-          decls1 = newScope(decls.toList filter isImplementedStatically)
+          decls1 = new Scope(decls.toList filter isImplementedStatically)
         } else if (!parents.isEmpty) {
           parents1 = parents.head :: (parents.tail map toInterface)
         }
       }
-      //decls1 = atPhase(phase.next)(newScope(decls1.toList))//debug
+      //decls1 = atPhase(phase.next)(new Scope(decls1.toList))//debug
       if ((parents1 eq parents) && (decls1 eq decls)) tp
       else ClassInfoType(parents1, decls1, clazz)
 
-    case MethodType(formals, restp) =>
+    case MethodType(params, restp) =>
       toInterfaceMap(
-        if (isImplementedStatically(sym))
-          MethodType(toInterface(sym.owner.typeOfThis) :: formals, restp)
-        else
+        if (isImplementedStatically(sym)) {
+          val ownerParam = sym.newSyntheticValueParam(toInterface(sym.owner.typeOfThis))
+          MethodType(ownerParam :: params, restp)
+        } else
           tp)
 
     case _ =>
       tp
   }
 
+  import scala.collection._
+
+  /** Return a map of single-use fields to the lazy value that uses them during initialization.
+   *  Each field has to be private and defined in the enclosing class, and there must
+   *  be exactly one lazy value using it.
+   *
+   *  Such fields will be nulled after the initializer has memoized the lazy value.
+   */
+  def singleUseFields(templ: Template): collection.Map[Symbol, List[Symbol]] = {
+    val usedIn = new mutable.HashMap[Symbol, List[Symbol]] {
+      override def default(key: Symbol) = Nil
+    }
+
+    object SingleUseTraverser extends Traverser {
+      override def traverse(tree: Tree) {
+        tree match {
+          case Assign(lhs, rhs) => traverse(rhs) // assignments don't count
+          case _ =>
+            if (tree.hasSymbol && tree.symbol != NoSymbol) {
+              val sym = tree.symbol
+              if ((sym.hasFlag(ACCESSOR) || (sym.isTerm && !sym.isMethod))
+                  && sym.hasFlag(PRIVATE)
+                  && !(currentOwner.isGetter && currentOwner.accessed == sym) // getter
+                  && !definitions.isValueClass(sym.tpe.resultType.typeSymbol)
+                  && sym.owner == templ.symbol.owner
+                  && !tree.isDef) {
+                log("added use in: " + currentOwner + " -- " + tree)
+                usedIn(sym) ::= currentOwner
+
+              }
+            }
+            super.traverse(tree)          
+        }
+      }
+    }
+    SingleUseTraverser(templ)
+    log("usedIn: " + usedIn)
+    usedIn filter { pair =>
+      val member = pair._2.head
+      (member.isValue
+         && member.hasFlag(LAZY)
+         && pair._2.tail.isEmpty) }
+  }
+
 // --------- term transformation -----------------------------------------------
 
   protected def newTransformer(unit: CompilationUnit): Transformer =
@@ -369,11 +435,15 @@ abstract class Mixin extends InfoTransform {
 
     /** The rootContext used for typing */
     private val rootContext =
-      erasure.NoContext.make(EmptyTree, RootClass, newScope)
+      erasure.NoContext.make(EmptyTree, RootClass, new Scope)
 
     /** The typer */
     private var localTyper: erasure.Typer = _
-    
+    private def typedPos(pos: Position)(tree: Tree) = localTyper typed { atPos(pos)(tree) }
+
+    /** Map lazy values to the fields they should null after initialization. */
+    private var lazyValNullables: mutable.MultiMap[Symbol, Symbol] = _
+
     import scala.collection._
     
     /** Map a field symbol to a unique integer denoting its position in the class layout.
@@ -405,16 +475,23 @@ abstract class Mixin extends InfoTransform {
           if (!currentOwner.isTrait) addMixedinMembers(currentOwner,unit)
           else if (currentOwner hasFlag lateINTERFACE) addLateInterfaceMembers(currentOwner)
           tree
-        case DefDef(mods, name, tparams, List(vparams), tpt, rhs) if currentOwner.isImplClass =>
-          if (isImplementedStatically(sym)) {
-            sym setFlag notOVERRIDE
-            self = sym.newValue(sym.pos, nme.SELF) 
-              .setFlag(PARAM)
-              .setInfo(toInterface(currentOwner.typeOfThis));
-            val selfdef = ValDef(self) setType NoType
-            copy.DefDef(tree, mods, name, tparams, List(selfdef :: vparams), tpt, rhs)
+        case DefDef(mods, name, tparams, List(vparams), tpt, rhs) =>
+          if (currentOwner.isImplClass) {
+            if (isImplementedStatically(sym)) {
+              sym setFlag notOVERRIDE
+              self = sym.newValue(sym.pos, nme.SELF) 
+                .setFlag(PARAM)
+                .setInfo(toInterface(currentOwner.typeOfThis));
+              val selfdef = ValDef(self) setType NoType
+              treeCopy.DefDef(tree, mods, name, tparams, List(selfdef :: vparams), tpt, rhs)
+            } else {
+              EmptyTree
+            }
           } else {
-            EmptyTree
+            if (currentOwner.isTrait && sym.isSetter && !atPhase(currentRun.picklerPhase)(sym.isDeferred)) {
+              sym.addAnnotation(AnnotationInfo(TraitSetterAnnotationClass.tpe, List(), List()))
+            }
+            tree
           }
         case Apply(tapp @ TypeApply(fn, List(arg)), List()) =>
           if (arg.tpe.typeSymbol.isImplClass) {
@@ -449,14 +526,14 @@ abstract class Mixin extends InfoTransform {
     /** Create a static reference to given symbol <code>sym</code> of the
      *  form <code>M.sym</code> where M is the symbol's implementation module.
      */
-    private def staticRef(sym: Symbol) = {
+    private def staticRef(sym: Symbol): Tree = {
       sym.owner.info  //todo: needed?
       sym.owner.owner.info //todo: needed?
       if (sym.owner.sourceModule == NoSymbol) {
         assert(false, "" + sym + " in " + sym.owner + " in " + sym.owner.owner +
                       " " + sym.owner.owner.info.decls.toList)//debug
       }
-      Select(gen.mkAttributedRef(sym.owner.sourceModule), sym)
+      REF(sym.owner.sourceModule) DOT sym
     }
 
     /** Add all new definitions to a non-trait class 
@@ -481,7 +558,7 @@ abstract class Mixin extends InfoTransform {
       /** Attribute given tree and anchor at given position */
       def attributedDef(pos: Position, tree: Tree): Tree = {
         if (settings.debug.value) log("add new def to " + clazz + ": " + tree)
-        localTyper.typed { atPos(pos) { tree } }
+        typedPos(pos)(tree)
       }
 
       /** The position of given symbol, or, if this is undefined, 
@@ -501,7 +578,7 @@ abstract class Mixin extends InfoTransform {
        *               right-hand side
        */
       def addDefDef(sym: Symbol, rhs: List[Symbol] => Tree) {
-        addDef(position(sym), DefDef(sym, vparamss => rhs(vparamss.head)))
+        addDef(position(sym), DefDef(sym, rhs(sym.paramss.head)))
       }
 
       /** Add `newdefs' to `stats', removing any abstract method definitions
@@ -512,7 +589,7 @@ abstract class Mixin extends InfoTransform {
         val newSyms = newDefs map (_.symbol)
         def isNotDuplicate(tree: Tree) = tree match {
           case DefDef(_, _, _, _, _, _) =>
-            val sym = tree.symbol;
+            val sym = tree.symbol
             !(sym.isDeferred &&
               (newSyms exists (nsym => nsym.name == sym.name && (nsym.tpe matches sym.tpe))))
           case _ =>
@@ -532,16 +609,14 @@ abstract class Mixin extends InfoTransform {
       def completeSuperAccessor(stat: Tree) = stat match {
         case DefDef(mods, name, tparams, List(vparams), tpt, EmptyTree)
         if (stat.symbol hasFlag SUPERACCESSOR) =>
-          val rhs0 =
-            Apply(Select(Super(clazz, nme.EMPTY.toTypeName), stat.symbol.alias),
-                  vparams map (vparam => Ident(vparam.symbol)))
+          val rhs0 = (Super(clazz, nme.EMPTY.toTypeName) DOT stat.symbol.alias)(vparams map (v => Ident(v.symbol)): _*)
           val rhs1 = localTyper.typed(atPos(stat.pos)(rhs0), stat.symbol.tpe.resultType)
           val rhs2 = atPhase(currentRun.mixinPhase)(transform(rhs1))
           if (settings.debug.value)
             log("complete super acc " + stat.symbol + stat.symbol.locationString +
                 " " + rhs1 + " " + stat.symbol.alias + stat.symbol.alias.locationString +
                 "/" + stat.symbol.alias.owner.hasFlag(lateINTERFACE))//debug
-          copy.DefDef(stat, mods, name, tparams, List(vparams), tpt, rhs2)
+          treeCopy.DefDef(stat, mods, name, tparams, List(vparams), tpt, rhs2)
         case _ =>
           stat
       }
@@ -554,35 +629,39 @@ abstract class Mixin extends InfoTransform {
         assert(!sym.hasFlag(OVERLOADED))
         if (sym == NoSymbol) {
           sym = clazz.newVariable(clazz.pos, nme.bitmapName(offset / FLAGS_PER_WORD))
-                       .setInfo(definitions.IntClass.tpe)
+                       .setInfo(IntClass.tpe)
                        .setFlag(PROTECTED)
           atPhase(currentRun.typerPhase) {
-            sym.attributes = AnnotationInfo(definitions.VolatileAttr.tpe, List(), List()) :: sym.attributes
+            sym addAnnotation AnnotationInfo(VolatileAttr.tpe, Nil, Nil)
           }
           clazz.info.decls.enter(sym)
-          addDef(clazz.pos, ValDef(sym, Literal(Constant(0))))
+          addDef(clazz.pos, VAL(sym) === ZERO)
         }
         sym
       }
 
       /** Return an (untyped) tree of the form 'Clazz.this.bmp = Clazz.this.bmp | mask'. */
       def mkSetFlag(clazz: Symbol, offset: Int): Tree = {
-        val bmp = bitmapFor(clazz, offset)
-        val mask = Literal(Constant(1 << (offset % FLAGS_PER_WORD)))
-
-        Assign(Select(This(clazz), bmp),
-          Apply(Select(Select(This(clazz), bmp), Int_Or), List(mask)))
+        val bmp   = bitmapFor(clazz, offset)
+        val mask  = LIT(1 << (offset % FLAGS_PER_WORD))
+        def x     = This(clazz) DOT bmp
+        
+        x === (x INT_| mask)
       }
       
       /** Return an (untyped) tree of the form 'clazz.this.bitmapSym & mask (==|!=) 0', the
        *  precise comparison operator depending on the value of 'equalToZero'.
        */
-      def mkTest(clazz: Symbol, mask: Tree, bitmapSym: Symbol, equalToZero: Boolean): Tree = 
-        Apply(Select(Apply(Select(Select(This(clazz), bitmapSym), Int_And), List(mask)),
-                     if (equalToZero) Int_== else Int_!=), 
-              List(Literal(Constant(0))))
+      def mkTest(clazz: Symbol, mask: Tree, bitmapSym: Symbol, equalToZero: Boolean): Tree = {
+        def lhs = (This(clazz) DOT bitmapSym) INT_& mask
+        if (equalToZero)  lhs INT_== ZERO
+        else              lhs INT_!= ZERO
+      }
 
-      /** return a 'lazified' version of rhs. 
+      /** return a 'lazified' version of rhs. It uses double-checked locking to ensure
+       *  initialization is performed at most once. Private fields used only in this
+       *  initializer are subsequently set to null.
+       * 
        *  @param clazz The class symbol
        *  @param init The tree which initializes the field ( f = <rhs> )
        *  @param fieldSym The symbol of this lazy field
@@ -591,44 +670,48 @@ abstract class Mixin extends InfoTransform {
        *  The result will be a tree of the form
        *  {
        *    if ((bitmap$n & MASK) == 0) {
-       *       synhronized(this) {
+       *       synchronized(this) {
        *         if ((bitmap$n & MASK) == 0) {
-       *           synhronized(this) {
-       *             init // l$ = <rhs>
-       *           }
+       *           init // l$ = <rhs>
        *           bitmap$n = bimap$n | MASK
-       *         }}}
+       *         }
+       *       }
+       *       this.f1 = null
+       *       ... this.fn = null 
+       *    }
        *    l$
        *  }
        *  where bitmap$n is an int value acting as a bitmap of initialized values. It is
        *  the 'n' is (offset / 32), the MASK is (1 << (offset % 32)).
        */
-      def mkLazyDef(clazz: Symbol, init: Tree, retVal: Tree, offset: Int): Tree = {
+      def mkLazyDef(clazz: Symbol, lzyVal: Symbol, init: List[Tree], retVal: Tree, offset: Int): Tree = {
+        def nullify(sym: Symbol): Tree = {
+          val sym1 = if (sym.hasFlag(ACCESSOR)) sym.accessed else sym
+          Select(This(clazz), sym1) === LIT(null)
+        }
+
 
         val bitmapSym = bitmapFor(clazz, offset)
-        
-        val mask = Literal(Constant(1 << (offset % FLAGS_PER_WORD)))
-        val result = 
-          If(mkTest(clazz, mask, bitmapSym, true),
-             gen.mkSynchronized(gen.mkAttributedThis(clazz),
-               If(mkTest(clazz, mask, bitmapSym, true),
-                  Block(List(init, 
-                        mkSetFlag(clazz, offset)), 
-                        Literal(Constant(()))), 
-                 EmptyTree)), 
-             EmptyTree)
-        localTyper.typed(atPos(init.pos)(Block(List(result), retVal)))
+        val mask      = LIT(1 << (offset % FLAGS_PER_WORD))
+        def cond      = mkTest(clazz, mask, bitmapSym, true)
+        val nulls     = (lazyValNullables(lzyVal).toList sortBy (_.id) map nullify)
+        def syncBody  = init ::: List(mkSetFlag(clazz, offset), UNIT)
+
+        log("nulling fields inside " + lzyVal + ": " + nulls)
+        val result    = gen.mkDoubleCheckedLocking(clazz, cond, syncBody, nulls)
+        typedPos(init.head.pos)(BLOCK(result, retVal))
       }
-      
+
       def mkCheckedAccessor(clazz: Symbol, retVal: Tree, offset: Int, pos: Position): Tree = {
         val bitmapSym = bitmapFor(clazz, offset)
-        val mask = Literal(Constant(1 << (offset % FLAGS_PER_WORD)))
-        val msg = "Uninitialized field: " + unit.source + ": " + pos.line.get
-        val result = 
-          If(mkTest(clazz, mask, bitmapSym, false),
-             retVal, 
-             Throw(New(TypeTree(definitions.UninitializedErrorClass.tpe), List(List(Literal(Constant(msg))))))) 
-        localTyper.typed(atPos(pos)(Block(List(result), retVal)))
+        val mask      = LIT(1 << (offset % FLAGS_PER_WORD))
+        val msg       = "Uninitialized field: " + unit.source + ": " + pos.line
+        val result    = 
+          IF (mkTest(clazz, mask, bitmapSym, false)) .
+            THEN (retVal) .
+            ELSE (THROW(UninitializedErrorClass, LIT(msg)))
+        
+        typedPos(pos)(BLOCK(result, retVal))
       }
        
       /** Complete lazy field accessors. Applies only to classes, for it's own (non inherited) lazy fields.
@@ -636,54 +719,56 @@ abstract class Mixin extends InfoTransform {
        *  the class constructor is changed to set the initialized bits.
        */
       def addCheckedGetters(clazz: Symbol, stats: List[Tree]): List[Tree] = {
+        def findLazyAssignment(stats: List[Tree]): Tree = (
+          for (s @ Assign(lhs, _) <- stats ; if lhs.symbol hasFlag LAZY) yield s
+        ) head // if there's no assignment then it's a bug and we crash
+
         val stats1 = for (stat <- stats; sym = stat.symbol) yield stat match {
           case DefDef(mods, name, tp, vp, tpt, rhs) 
             if sym.hasFlag(LAZY) && rhs != EmptyTree && !clazz.isImplClass =>
               assert(fieldOffset.isDefinedAt(sym))
-              val rhs1 = if (sym.tpe.resultType.typeSymbol == definitions.UnitClass) 
-                mkLazyDef(clazz, rhs, Literal(()), fieldOffset(sym))
+              val rhs1 = if (sym.tpe.resultType.typeSymbol == UnitClass) 
+                mkLazyDef(clazz, sym, List(rhs), UNIT, fieldOffset(sym))
               else {
-                val Block(List(assignment), res) = rhs
-                mkLazyDef(clazz, assignment, Select(This(clazz), res.symbol), fieldOffset(sym))
+                val Block(stats, res) = rhs
+                mkLazyDef(clazz, sym, stats, Select(This(clazz), res.symbol), fieldOffset(sym))
               }
-              copy.DefDef(stat, mods, name, tp, vp, tpt, rhs1)
+              treeCopy.DefDef(stat, mods, name, tp, vp, tpt, rhs1)
               
           case DefDef(mods, name, tp, vp, tpt, rhs) 
             if needsInitFlag(sym) && rhs != EmptyTree && !clazz.isImplClass && !clazz.isTrait =>
               assert(fieldOffset.isDefinedAt(sym))
 
-              val rhs1 = if (sym.tpe.resultType.typeSymbol == definitions.UnitClass) 
-                mkCheckedAccessor(clazz, Literal(()), fieldOffset(sym), stat.pos)
-              else {
-                mkCheckedAccessor(clazz, rhs, fieldOffset(sym), stat.pos)
-              }
-              copy.DefDef(stat, mods, name, tp, vp, tpt, rhs1)
+              val rhs1 = (mkCheckedAccessor(clazz, _: Tree, fieldOffset(sym), stat.pos))(
+                if (sym.tpe.resultType.typeSymbol == UnitClass) UNIT else rhs
+              )
+              treeCopy.DefDef(stat, mods, name, tp, vp, tpt, rhs1)
               
           case DefDef(mods, name, tp, vp, tpt, rhs) if sym.isConstructor =>
-            copy.DefDef(stat, mods, name, tp, vp, tpt, addInitBits(clazz, rhs))
+            treeCopy.DefDef(stat, mods, name, tp, vp, tpt, addInitBits(clazz, rhs))
 
           case _ => stat
         }
         stats1
       }
 
-      /** Does this field require an intialized bit? */
+      /** Does this field require an initialized bit? */
       def needsInitFlag(sym: Symbol) = {
         val res = (settings.checkInit.value 
            && sym.isGetter 
            && !sym.isInitializedToDefault
-           && !sym.hasFlag(PARAMACCESSOR)
+           && !sym.hasFlag(PARAMACCESSOR | SPECIALIZED)
            && !sym.accessed.hasFlag(PRESUPER)
            && !sym.isOuterAccessor)
         
-        if (settings.debug.value) {
-          log("needsInitFlag(" + sym.fullNameString + "): " + res)
-          log("\tsym.isGetter: " + sym.isGetter) 
-          log("\t!isInitializedToDefault: " + !sym.isInitializedToDefault + sym.hasFlag(DEFAULTINIT) + sym.hasFlag(ACCESSOR) + sym.isTerm)
-          log("\t!sym.hasFlag(PARAMACCESSOR): " + !sym.hasFlag(PARAMACCESSOR))
-          //println("\t!sym.accessed.hasFlag(PRESUPER): " + !sym.accessed.hasFlag(PRESUPER))
-          log("\t!sym.isOuterAccessor: " + !sym.isOuterAccessor)
-        }
+//        if (settings.debug.value) {
+//          log("needsInitFlag(" + sym.fullName + "): " + res)
+//          log("\tsym.isGetter: " + sym.isGetter)
+//          log("\t!isInitializedToDefault: " + !sym.isInitializedToDefault + sym.hasFlag(DEFAULTINIT) + sym.hasFlag(ACCESSOR) + sym.isTerm)
+//          log("\t!sym.hasFlag(PARAMACCESSOR): " + !sym.hasFlag(PARAMACCESSOR))
+//          //println("\t!sym.accessed.hasFlag(PRESUPER): " + !sym.accessed.hasFlag(PRESUPER))
+//          log("\t!sym.isOuterAccessor: " + !sym.isOuterAccessor)
+//        }
         
         res
       }
@@ -735,7 +820,7 @@ abstract class Mixin extends InfoTransform {
         // parents != baseClasses.map(_.tpe): bug #1535
         val fields = for {
           sc <- clazz.info.baseClasses.map(_.tpe)
-          field <- sc.decls.elements.toList
+          field <- sc.decls.iterator.toList
           if needsBitmapField(sc, field)
         } yield field
         
@@ -750,8 +835,8 @@ abstract class Mixin extends InfoTransform {
        */
       def buildFieldPositions(clazz: Symbol) {
         var fields = usedBits(clazz)
-        for (val f <- clazz.info.decls.elements if needsInitFlag(f) || f.hasFlag(LAZY)) {
-          if (settings.debug.value) log(f.fullNameString + " -> " + fields)
+        for (f <- clazz.info.decls.iterator if needsInitFlag(f) || f.hasFlag(LAZY)) {
+          if (settings.debug.value) log(f.fullName + " -> " + fields)
           fieldOffset(f) = fields
           fields += 1
         }
@@ -762,7 +847,7 @@ abstract class Mixin extends InfoTransform {
       var stats1 = addCheckedGetters(clazz, stats)
 
       // for all symbols `sym' in the class definition, which are mixed in:
-      for (val sym <- clazz.info.decls.toList) {
+      for (sym <- clazz.info.decls.toList) {
         if (sym hasFlag MIXEDIN) {
           if (clazz hasFlag lateINTERFACE) {
             // if current class is a trait interface, add an abstract method for accessor `sym'
@@ -779,25 +864,25 @@ abstract class Mixin extends InfoTransform {
                     // if it is a mixed-in lazy value, complete the accessor
                     if (sym.hasFlag(LAZY) && sym.isGetter) {
                       val rhs1 = 
-                        if (sym.tpe.resultType.typeSymbol == definitions.UnitClass)
-                          mkLazyDef(clazz, Apply(staticRef(initializer(sym)), List(gen.mkAttributedThis(clazz))), Literal(()), fieldOffset(sym))
+                        if (sym.tpe.resultType.typeSymbol == UnitClass)
+                          mkLazyDef(clazz, sym, List(Apply(staticRef(initializer(sym)), List(gen.mkAttributedThis(clazz)))), UNIT, fieldOffset(sym))
                         else {
                           val assign = atPos(sym.pos) {
                             Assign(Select(This(sym.accessed.owner), sym.accessed) /*gen.mkAttributedRef(sym.accessed)*/ ,
                                 Apply(staticRef(initializer(sym)), gen.mkAttributedThis(clazz) :: Nil))
                           }
-                          mkLazyDef(clazz, assign, Select(This(clazz), sym.accessed), fieldOffset(sym))
+                          mkLazyDef(clazz, sym, List(assign), Select(This(clazz), sym.accessed), fieldOffset(sym))
                         }
                       rhs1
-                    } else if (sym.getter(sym.owner).tpe.resultType.typeSymbol == definitions.UnitClass) {
-                      Literal(())
+                    } else if (sym.getter(sym.owner).tpe.resultType.typeSymbol == UnitClass) {
+                      UNIT
                     } else {
                       Select(This(clazz), sym.accessed)
                     }
                 }
                 if (sym.isSetter) {
                   val isOverriddenSetter = 
-                    settings.Xexperimental.value && nme.isTraitSetterName(sym.name) && {
+                    nme.isTraitSetterName(sym.name) && {
                       sym.allOverriddenSymbols match {
                         case other :: _ => 
                           isOverriddenAccessor(other.getter(other.owner), clazz.info.baseClasses)
@@ -805,13 +890,13 @@ abstract class Mixin extends InfoTransform {
                           false
                       }
                     }
-                  if (isOverriddenSetter) Literal(())
+                  if (isOverriddenSetter) UNIT
                   else accessedRef match {
                     case Literal(_) => accessedRef
                     case _ =>
                       val init = Assign(accessedRef, Ident(vparams.head)) 
                       if (settings.checkInit.value && needsInitFlag(sym.getter(clazz))) {
-                        Block(List(init, mkSetFlag(clazz, fieldOffset(sym.getter(clazz)))), Literal(()))
+                        Block(List(init, mkSetFlag(clazz, fieldOffset(sym.getter(clazz)))), UNIT)
                       } else
                         init
                   }
@@ -845,6 +930,22 @@ abstract class Mixin extends InfoTransform {
       stats1
     }
 
+    private def nullableFields(templ: Template) = {
+      val nullables = new mutable.HashMap[Symbol, mutable.Set[Symbol]] with mutable.MultiMap[Symbol, Symbol] {
+        override def default(key: Symbol) = mutable.Set.empty
+      }
+
+      // if there are no lazy fields, take the fast path and save a traversal of the whole AST
+      if (templ.symbol.owner.info.decls.exists(_.hasFlag(LAZY))) {
+        // check what fields can be nulled for
+        val uses = singleUseFields(templ)
+        for ((field, users) <- uses; lazyFld <- users) {
+          nullables.addBinding(lazyFld, field)
+        }
+      }
+      nullables
+    }
+
     /** The transform that gets applied to a tree after it has been completely
      *  traversed and possible modified by a preTransform.
      *  This step will
@@ -874,10 +975,11 @@ abstract class Mixin extends InfoTransform {
           // change parents of templates to conform to parents in the symbol info
           val parents1 = currentOwner.info.parents map (t => TypeTree(t) setPos tree.pos)
 
+          lazyValNullables = nullableFields(tree.asInstanceOf[Template])
           // add all new definitions to current class or interface
           val body1 = addNewDefs(currentOwner, body)
 
-          copy.Template(tree, parents1, self, body1)
+          treeCopy.Template(tree, parents1, self, body1)
 
         case Apply(TypeApply(sel @ Select(qual, name), List(targ)), List())
         if (tree.symbol == Object_asInstanceOf && (qual.tpe <:< targ.tpe)) =>
@@ -897,11 +999,8 @@ abstract class Mixin extends InfoTransform {
           def staticCall(target: Symbol) = {
             if (target == NoSymbol)
               assert(false, "" + sym + ":" + sym.tpe + " " + sym.owner + " " + implClass(sym.owner) + " " + implClass(sym.owner).info.member(sym.name) + " " + atPhase(phase.prev)(implClass(sym.owner).info.member(sym.name).tpe) + " " + phase);//debug
-            localTyper.typed {
-              atPos(tree.pos) {
-                Apply(staticRef(target), transformSuper(qual) :: args)
-              }
-            }
+            
+            typedPos(tree.pos)(Apply(staticRef(target), transformSuper(qual) :: args))
           }
           if (isStaticOnly(sym)) {
             // change calls to methods which are defined only in implementation
@@ -911,7 +1010,7 @@ abstract class Mixin extends InfoTransform {
             case Super(_, mix) =>
               // change super calls to methods in implementation classes to static calls.
               // Transform references super.m(args) as follows:
-              //  - if `m' refers to a trait, insert a static call to the correspondign static
+              //  - if `m' refers to a trait, insert a static call to the corresponding static
               //    implementation
               //  - otherwise return tree unchanged
               if (mix == nme.EMPTY.toTypeName && currentOwner.enclClass.isImplClass)
@@ -920,12 +1019,9 @@ abstract class Mixin extends InfoTransform {
                 if (sym.hasFlag(ACCESSOR)) {
                   assert(args.isEmpty)
                   val sym1 = sym.overridingSymbol(currentOwner.enclClass)
-                  localTyper.typed {
-                    atPos(tree.pos) {
-                      Apply(Select(transformSuper(qual), sym1), List())
-                    }
-                  }
-                } else {
+                  typedPos(tree.pos)((transformSuper(qual) DOT sym1)())
+                }
+                else {
                   staticCall(atPhase(phase.prev)(sym.overridingSymbol(implClass(sym.owner))))
                 }
               } else {
@@ -945,39 +1041,25 @@ abstract class Mixin extends InfoTransform {
           tree
 
         case Select(qual, name) if sym.owner.isImplClass && !isStaticOnly(sym) =>
+          assert(!sym.isMethod, "no method allowed here: %s%s %s".format(sym, sym.isImplOnly, flagsToString(sym.flags)))
+
           // refer to fields in some implementation class via an abstract
           // getter in the interface.
-          
-          if (sym.isMethod)
-            assert(false, "no method allowed here: " + sym + sym.isImplOnly +
-                          " " + flagsToString(sym.flags))
           val iface = toInterface(sym.owner.tpe).typeSymbol
           val getter = sym.getter(iface)
           assert(getter != NoSymbol)
-          localTyper.typed {
-            atPos(tree.pos) {
-              Apply(Select(qual, getter), List())
-            }
-          }
+          typedPos(tree.pos)((qual DOT getter)())
 
         case Assign(Apply(lhs @ Select(qual, _), List()), rhs) =>
           // assign to fields in some implementation class via an abstract
           // setter in the interface.
-          localTyper.typed {
-            // println(lhs.symbol)
-            // println(lhs.symbol.owner.info.decls)
-            // println(needsExpandedSetterName(lhs.symbol))
-            // util.trace("generating tree: ") {
-            atPos(tree.pos) {
-              Apply(
-                Select(
-                  qual, 
-                  lhs.symbol.setter(
-                    toInterface(lhs.symbol.owner.tpe).typeSymbol, 
-                    needsExpandedSetterName(lhs.symbol))) setPos lhs.pos, 
-                List(rhs))
-            }
-          } //}
+          def setter = lhs.symbol.setter(
+            toInterface(lhs.symbol.owner.tpe).typeSymbol, 
+            needsExpandedSetterName(lhs.symbol)
+          ) setPos lhs.pos
+          
+          typedPos(tree.pos) { (qual DOT setter)(rhs) }
+
         case _ =>
           tree
       }
diff --git a/src/compiler/scala/tools/nsc/transform/OverridingPairs.scala b/src/compiler/scala/tools/nsc/transform/OverridingPairs.scala
index 37bcf17..59da1e0 100644
--- a/src/compiler/scala/tools/nsc/transform/OverridingPairs.scala
+++ b/src/compiler/scala/tools/nsc/transform/OverridingPairs.scala
@@ -1,17 +1,20 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author Martin Odersky
  */
-// $Id: OverridingPairs.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.tools.nsc.transform
+package scala.tools.nsc
+package transform
 
 import collection.mutable.HashMap
 import symtab.Flags._
 import util.HashSet
+import annotation.tailrec
 
-/** This abstract class ...
- *
+/** A class that yields a kind of iterator (`Cursor`),
+ *  which yields all pairs of overriding/overridden symbols
+ *  that are visible in some baseclass, unless there's a parent class
+ *  that already contains the same pairs.
  *  @author Martin Odersky
  *  @version 1.0
  */
@@ -20,18 +23,35 @@ abstract class OverridingPairs {
   val global: Global
   import global._
 
+  /** The cursor class
+   *  @param base   the base class that contains the overriding pairs
+   */
   class Cursor(base: Symbol) {
 
     private val self = base.thisType
 
+    /** Symbols to exclude: Here these are constructors, private locals,
+     *  and bridges. But it may be refined in subclasses.
+     * 
+     */
     protected def exclude(sym: Symbol): Boolean = 
       sym.isConstructor || sym.isPrivateLocal || sym.hasFlag(BRIDGE)
 
+    /** The parents of base (may also be refined).
+     */
     protected def parents: List[Type] = base.info.parents
 
+    /** Does `sym1` match `sym2` so that it qualifies as overriding.
+     *  Types always match. Term symbols match if their membertypes
+     *  relative to <base>.this do
+     */
     protected def matches(sym1: Symbol, sym2: Symbol): Boolean =
       sym1.isType || (self.memberType(sym1) matches self.memberType(sym2))
 
+    /** An implementation of BitSets as arrays (maybe consider collection.BitSet
+     *  for that?) The main purpose of this is to implement
+     *  intersectionContainsElement efficiently.
+     */
     private type BitSet = Array[Int]
 
     private def newBitSet(size: Int): BitSet = new Array((size + 31) >> 5)
@@ -42,36 +62,51 @@ abstract class OverridingPairs {
       bs(nshifted) = bs(nshifted) | nmask
     }
 
-    private def intersectionContainsElementLeq(bs1: BitSet, bs2: BitSet,
-                                               n: Int): Boolean =
-    {
+    /** Implements `bs1 * bs2 * {0..n} != 0.
+     *  Used in hasCommonParentAsSubclass */
+    private def intersectionContainsElementLeq(bs1: BitSet, bs2: BitSet, n: Int): Boolean = {
       val nshifted = n >> 5
-      val nmask = 1 << (n & 31);
-      ((List.range(0, nshifted) exists (i => (bs1(i) & bs2(i)) != 0)) ||
-       ((bs1(nshifted) & bs2(nshifted) & (nmask | nmask - 1)) != 0))
+      val nmask = 1 << (n & 31)
+      var i = 0
+      while (i < nshifted) {
+        if ((bs1(i) & bs2(i)) != 0) return true
+        i += 1
+      }
+      (bs1(nshifted) & bs2(nshifted) & (nmask | nmask - 1)) != 0
     }
 
-    private val decls = newScope
+    /** The symbols that can take part in an overriding pair */
+    private val decls = new Scope
 
+    // fill `decls` with overriding shadowing overridden */
     { def fillDecls(bcs: List[Symbol], deferredflag: Int) {
         if (!bcs.isEmpty) {
           fillDecls(bcs.tail, deferredflag)
           var e = bcs.head.info.decls.elems;
           while (e ne null) {
-            if (e.sym.getFlag(DEFERRED) == deferredflag && !exclude(e.sym))
+            if (e.sym.getFlag(DEFERRED) == deferredflag.toLong && !exclude(e.sym))
               decls enter e.sym;
             e = e.next
           }
         }
       }
+      // first, deferred (this wil need to change if we change lookup rules!
       fillDecls(base.info.baseClasses, DEFERRED)
+      // then, concrete.
       fillDecls(base.info.baseClasses, 0)
     }
 
     private val size = base.info.baseClasses.length
 
+    /** A map from baseclasses of <base> to ints, with smaller ints meaning lower in
+     *  linearization order.
+     */
     private val index = new HashMap[Symbol, Int]
 
+    // Note: overridingPairs can be called at odd instances by the Eclipse plugin
+    // Soemtimes symbols are not yet defined and we get missing keys.
+    // The implementation here is hardened so that it does not crash on a missing key.
+
     { var i = 0
       for (bc <- base.info.baseClasses) {
         index(bc) = i
@@ -79,63 +114,114 @@ abstract class OverridingPairs {
       }
     }
 
+    /** A mapping from all base class indices to a bitset
+     *  which indicates whether parents are subclasses.
+     *
+     *   i \in subParents(j)   iff
+     *   exists p \in parents, b \in baseClasses:
+     *     i = index(p)
+     *     j = index(b)
+     *     p isSubClass b
+     *     p.baseType(b) == self.baseType(b)
+     */
     private val subParents = new Array[BitSet](size)
 
     { for (i <- List.range(0, size))
         subParents(i) = new BitSet(size);
       for (p <- parents) {
-        val pIndex = index(p.typeSymbol)
-        for (bc <- p.baseClasses) include(subParents(index(bc)), pIndex)
+        index get p.typeSymbol match {
+          case Some(pIndex) =>
+            for (bc <- p.baseClasses) 
+              if (p.baseType(bc) =:= self.baseType(bc))
+                index get bc match {
+                  case Some(bcIndex) =>
+                    include(subParents(bcIndex), pIndex)
+                  case None =>
+                }
+              else if (settings.debug.value)
+                log("SKIPPING "+p+" -> "+p.baseType(bc)+" / "+self.baseType(bc)+" from "+base)
+          case None =>
+        }
+      }
+   }
+
+    /** Do `sym1` and `sym2` have a common subclass in `parents`?
+     *  In that case we do not follow their overriding pairs
+     */
+    private def hasCommonParentAsSubclass(sym1: Symbol, sym2: Symbol) = {
+      index get sym1.owner match {
+        case Some(index1) =>
+          index get sym2.owner match {
+            case Some(index2) =>
+              intersectionContainsElementLeq(subParents(index1), subParents(index2), index1 min index2)
+            case None =>
+              false
+          }
+        case None =>
+          false
       }
     }
 
+    /** The scope entries that have already been visited as overridden
+     *  (maybe excluded because of hasCommonParentAsSubclass).
+     *  These will not appear as overriding
+     */
+    private val visited = new HashSet[ScopeEntry]("visited", 64)
 
-    private def hasCommonParent(sym1: Symbol, sym2: Symbol) = {
-      //assert(index.get(sym1.owner) != None, "" + base + " " + sym1 + " " + sym1.owner);//DEBUG
-      //assert(index.get(sym2.owner) != None, "" + base + " " + sym2 + " " + sym2.owner);//DEBUG
-      val index1 = index(sym1.owner)
-      val index2 = index(sym2.owner)
-      val minindex = if (index1 < index2) index1 else index2
-      intersectionContainsElementLeq(subParents(index1), subParents(index2), minindex)
-    }
-
-    private val visited = new HashSet[ScopeEntry](256)
+    /** The current entry candidate for overriding
+     */
     private var curEntry = decls.elems
+
+    /** The current entry candidate for overridden */
     private var nextEntry = curEntry
 
+    /** The current candidate symbol for overriding */
     var overriding: Symbol = _
+
+    /** If not null: The symbol overridden by overriding */
     var overridden: Symbol = _
 
-    //@M: note that next is called once during object initialisation
+    //@M: note that next is called once during object initialization
     def hasNext: Boolean = curEntry ne null
 
-    def next {
+    @tailrec
+    final def next {
       if (curEntry ne null) {
         overriding = curEntry.sym
         if (nextEntry ne null) {
-          do {
-            nextEntry = decls.lookupNextEntry(nextEntry);
-          } while ((nextEntry ne null) &&
-                   ((nextEntry.sym hasFlag PRIVATE) ||
-                    (overriding.owner == nextEntry.sym.owner) ||
-                    (!matches(overriding, nextEntry.sym)) ||
-                    (hasCommonParent(overriding, nextEntry.sym)) ||
-                    (exclude(overriding))))
-        }
-        if (nextEntry ne null) {
-          overridden = nextEntry.sym;
-          //Console.println("yield: " + overriding + overriding.locationString + " / " + overridden + overridden.locationString);//DEBUG
-          visited addEntry nextEntry
-        } else {
-          do {
-            curEntry = curEntry.next
-          } while ((curEntry ne null) && (visited contains curEntry));
-          nextEntry = curEntry
-          next
+          do { 
+            do {
+              nextEntry = decls.lookupNextEntry(nextEntry);
+              /* DEBUG
+              if ((nextEntry ne null) &&
+                  !(nextEntry.sym hasFlag PRIVATE) &&
+                  !(overriding.owner == nextEntry.sym.owner) &&
+                  !matches(overriding, nextEntry.sym))
+                println("skipping "+overriding+":"+self.memberType(overriding)+overriding.locationString+" to "+nextEntry.sym+":"+self.memberType(nextEntry.sym)+nextEntry.sym.locationString)
+              */
+              } while ((nextEntry ne null) &&
+                     ((nextEntry.sym hasFlag PRIVATE) ||
+                      (overriding.owner == nextEntry.sym.owner) ||
+                      (!matches(overriding, nextEntry.sym)) ||
+                      (exclude(overriding))))
+            if (nextEntry ne null) visited addEntry nextEntry
+            // skip nextEntry if a class in `parents` is a subclass of the owners of both
+            // overriding and nextEntry.sym
+          } while ((nextEntry ne null) && (hasCommonParentAsSubclass(overriding, nextEntry.sym)))
+          if (nextEntry ne null) {
+            overridden = nextEntry.sym;
+            //Console.println("yield: " + overriding + overriding.locationString + " / " + overridden + overridden.locationString);//DEBUG
+          } else {
+            do {
+              curEntry = curEntry.next
+            } while ((curEntry ne null) && (visited contains curEntry));
+            nextEntry = curEntry
+            next
+          }
         }
       }
     }
 
-    next //@M: ATTN! this method gets called during construction!
+    next
   }
 }
diff --git a/src/compiler/scala/tools/nsc/transform/Reifiers.scala b/src/compiler/scala/tools/nsc/transform/Reifiers.scala
index 03b193a..ba9897e 100644
--- a/src/compiler/scala/tools/nsc/transform/Reifiers.scala
+++ b/src/compiler/scala/tools/nsc/transform/Reifiers.scala
@@ -1,4 +1,5 @@
-package scala.tools.nsc.transform
+package scala.tools.nsc
+package transform
 import scala.tools.nsc.symtab.SymbolTable
 import scala.reflect
 import collection.mutable.HashMap
@@ -17,11 +18,14 @@ trait Reifiers {
     if (sym.isClass) reflect.Class(fullname)
     else if (sym.isType) reflect.TypeField(fullname, reify(sym.info))
     else if (sym.isMethod) reflect.Method(fullname, reify(sym.info))
+    else if (sym.isValueParameter) reflect.LocalValue(reflect.NoSymbol, fullname, reify(sym.info))
     else reflect.Field(fullname, reify(sym.info));
 
   def reify(sym: Symbol): reflect.Symbol = {
     if (sym.isRoot || sym.isRootPackage || sym.isEmptyPackageClass || sym.isEmptyPackage)
       reflect.RootSymbol
+    else if (sym.isValueParameter)
+      mkGlobalSymbol(sym.name.toString, sym)
     else if (sym.owner.isTerm) 
       reflect.NoSymbol
     else reify(sym.owner) match {
@@ -60,9 +64,9 @@ trait Reifiers {
       val rsym = reify(sym)
       val rargs = args map reify
       val beforeArgs = reflect.PrefixedType(rpre, rsym)
-      if(rargs.isEmpty)
+      if (rargs.isEmpty)
 	beforeArgs
-      else if(beforeArgs == NoType)
+      else if (rpre == reflect.NoType || rsym == reflect.NoSymbol)
 	beforeArgs
       else
 	reflect.AppliedType(beforeArgs, rargs)
@@ -72,8 +76,8 @@ trait Reifiers {
       if (_log_reify_type_) println("cannot handle RefinedType "+tp); reflect.NoType
     case ClassInfoType(parents, defs, clazz) =>
       if (_log_reify_type_) println("cannot handle ClassInfoType "+tp); reflect.NoType
-    case MethodType(paramtypes, result) =>
-      reflect.MethodType(paramtypes.map(reify), reify(result))
+    case MethodType(params, result) =>
+      reflect.MethodType(params.map(reify), reify(result))
     case PolyType(tparams, result) =>
       val boundss =
 	for {
@@ -86,7 +90,7 @@ trait Reifiers {
 	boundss,
 	reify(result))
       //todo: treat ExistentialType
-    case AnnotatedType(attribs, tp, _) =>
+    case AnnotatedType(annots, tp, _) =>
       reify(tp)
     case _ =>
       println("could not reify: " + tp)
@@ -139,8 +143,8 @@ trait Reifiers {
 	  appliedType(untpe, args.map(unreify))
       case reflect.TypeBounds(lo, hi) => 
 	TypeBounds(unreify(lo), unreify(hi))
-      case reflect.MethodType(formals, restpe) =>
-	MethodType(formals.map(unreify), unreify(restpe))
+      case reflect.MethodType(params, restpe) =>
+	MethodType(params.map(unreify), unreify(restpe))
       case reflect.PolyType(typeParams, typeBounds, resultType) =>
 	PolyType(typeParams.map(unreify), unreify(resultType))
       //todo: treat ExistentialType
@@ -188,7 +192,7 @@ trait Reifiers {
         case Some(tgt) => tgt
       }
     def hasAllTargets: Boolean =
-      targets.elements.map(_._2).forall {
+      targets.iterator.map(_._2).forall {
         case Some(_) => true
         case None => false
       }
@@ -215,8 +219,6 @@ trait Reifiers {
         if (rsym == reflect.NoSymbol) throw new TypeError("cannot reify symbol: " + tree.symbol)
         else reflect.Select(reify(qual), reify(tree.symbol))
 
-      case _ : StubTree => reflect.Literal(0)
-
       case Literal(constant) =>
         reflect.Literal(constant.value)
 
diff --git a/src/compiler/scala/tools/nsc/transform/SampleTransform.scala b/src/compiler/scala/tools/nsc/transform/SampleTransform.scala
index 771e827..6661543 100644
--- a/src/compiler/scala/tools/nsc/transform/SampleTransform.scala
+++ b/src/compiler/scala/tools/nsc/transform/SampleTransform.scala
@@ -1,10 +1,10 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author Martin Odersky
  */
-// $Id: SampleTransform.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.tools.nsc.transform
+package scala.tools.nsc
+package transform
 
 /** A sample transform.
  */
@@ -14,7 +14,6 @@ abstract class SampleTransform extends Transform {
   import global._                  // the global environment
   import definitions._             // standard classes and methods
   import typer.{typed, atOwner}    // methods to type trees
-  import posAssigner.atPos         // for filling in tree positions 
 
   /** the following two members override abstract members in Transform */
   val phaseName: String = "sample-phase"
@@ -31,7 +30,7 @@ abstract class SampleTransform extends Transform {
           expr
         case Block(defs, sup @ Super(qual, mix)) => // A hypthothetic transformation, which replaces
                                                     // {super} by {super.sample}
-          copy.Block(                           // `copy' is the usual lazy tree copier
+          treeCopy.Block(                           // `copy' is the usual lazy tree copier
             tree1, defs,
             typed(                              // `typed' assigns types to its tree argument
               atPos(tree1.pos)(                 // `atPos' fills in position of its tree argument
diff --git a/src/compiler/scala/tools/nsc/transform/SpecializeTypes.scala b/src/compiler/scala/tools/nsc/transform/SpecializeTypes.scala
new file mode 100644
index 0000000..732cccf
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/transform/SpecializeTypes.scala
@@ -0,0 +1,1478 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
+ * @author Iulian Dragos
+ */
+
+package scala.tools.nsc
+package transform
+
+import scala.tools.nsc.symtab.Flags
+import scala.tools.nsc.util.FreshNameCreator
+
+import scala.collection.{mutable, immutable}
+import immutable.Set
+
+/** Specialize code on types.
+ */
+abstract class SpecializeTypes extends InfoTransform with TypingTransformers {
+  import global._
+  import Flags._
+  /** the name of the phase: */
+  val phaseName: String = "specialize"
+  
+  /** This phase changes base classes. */
+  override def changesBaseClasses = true
+  override def keepsTypeParams = true
+
+  /** Concrete types for specialization */
+//  final lazy val concreteTypes = List(definitions.IntClass.tpe, definitions.DoubleClass.tpe)
+  
+  type TypeEnv = immutable.Map[Symbol, Type]
+  def emptyEnv: TypeEnv = immutable.ListMap.empty[Symbol, Type]
+
+  import definitions.SpecializedClass
+  object TypeEnv {
+    /** Return a new type environment binding specialized type parameters of sym to
+     *  the given args. Expects the lists to have the same length.
+     */
+    def fromSpecialization(sym: Symbol, args: List[Type]): TypeEnv = {
+      assert(sym.info.typeParams.length == args.length, sym + " args: " + args)
+      var env = emptyEnv
+      for ((tvar, tpe) <- sym.info.typeParams.zip(args) if tvar.hasAnnotation(SpecializedClass))
+        env = env + ((tvar, tpe))
+      env
+    }
+    
+    /** Is this typeenv included in `other'? All type variables in this environment
+     *  are defined in `other' and bound to the same type.
+     */
+    def includes(t1: TypeEnv, t2: TypeEnv) = {
+      t1 forall { kv =>
+        t2.get(kv._1) match {
+          case Some(v2) => v2 == kv._2
+          case _ => false
+        }
+      }
+    }
+    
+    /** Reduce the given environment to contain mappings only for type variables in tps. */
+    def restrict(env: TypeEnv, tps: immutable.Set[Symbol]): TypeEnv = {
+      env filter { kv => tps.contains(kv._1)}
+    }
+
+    /** Is the given environment a valid specialization for sym?
+     *  It is valid if each binding is from a @specialized type parameter in sym (or its owner)
+     *  to a type for which `sym' is specialized.
+     */
+    def isValid(env: TypeEnv, sym: Symbol): Boolean = {
+      def validBinding(tvar: Symbol, tpe: Type, sym: Symbol) = 
+        (tvar.hasAnnotation(SpecializedClass) 
+         && sym.typeParams.contains(tvar)
+         && concreteTypes(tvar).contains(tpe))
+      env forall { binding =>
+        val (tvar, tpe) = binding
+//         log("isValid: " + env + " sym: " + sym + " sym.tparams: " + sym.typeParams)
+//         log("Flag " + tvar + ": " + tvar.hasAnnotation(SpecializedClass))
+//         log("tparams contains: " + sym.typeParams.contains(tvar))
+//         log("concreteTypes: " + concreteTypes.contains(tpe)) 
+        (validBinding(tvar, tpe, sym)
+         || ((sym.owner != definitions.RootClass)
+             && validBinding(tvar, tpe, sym.owner)))
+      }
+    }
+  }
+  
+  /** For a given class and concrete type arguments, give its specialized class */
+  val specializedClass: mutable.Map[(Symbol, TypeEnv), Symbol] = new mutable.LinkedHashMap
+
+  /** Returns the generic class that was specialized to 'cls', or
+   *  'cls' itself if cls is not a specialized subclass.
+   */
+  def genericClass(cls: Symbol): Symbol =
+    if (cls.hasFlag(SPECIALIZED))
+      cls.info.parents.head.typeSymbol
+    else
+      cls
+
+  /** Map a method symbol to a list of its specialized overloads in the same class. */
+  private val overloads: mutable.Map[Symbol, List[Overload]] = new mutable.HashMap[Symbol, List[Overload]] {
+    override def default(key: Symbol): List[Overload] = Nil
+  }
+  
+  case class Overload(sym: Symbol, env: TypeEnv) {
+    override def toString: String =
+      "specialized overload " + sym + " in " + env
+  } 
+    
+  protected def newTransformer(unit: CompilationUnit): Transformer =
+    new SpecializationTransformer(unit)
+
+  abstract class SpecializedInfo {
+    def target: Symbol
+
+    /** Are type bounds of @specialized type parameters of 'target' now in 'env'? */
+    def typeBoundsIn(env: TypeEnv) = false
+
+    /** A degenerated method has @specialized type parameters that appear only in
+     *  type bounds of other @specialized type parameters (and not in its result type).
+     */
+    def degenerate = false
+
+    def isAccessor = false
+  }
+
+  /** Symbol is a special overloaded method of 'original', in the environment env. */
+  case class SpecialOverload(original: Symbol, env: TypeEnv) extends SpecializedInfo {
+    def target = original
+  }
+
+  /** Symbol is a method that should be forwarded to 't' */
+  case class Forward(t: Symbol) extends SpecializedInfo {
+    def target = t
+  }
+  
+  /** Symbol is a specialized accessor for the `target' field. */
+  case class SpecializedAccessor(target: Symbol) extends SpecializedInfo {
+    override def isAccessor = true
+  }
+
+  /** Symbol is a specialized method whose body should be the target's method body. */
+  case class Implementation(target: Symbol) extends SpecializedInfo
+
+  /** Symbol is a specialized override paired with `target'. */
+  case class SpecialOverride(target: Symbol) extends SpecializedInfo
+
+  /** An Inner class that specializes on a type parameter of the enclosing class. */
+  case class SpecializedInnerClass(target: Symbol, env: TypeEnv) extends SpecializedInfo
+
+  /** Symbol is a normalized member of 'target'. */
+  case class NormalizedMember(target: Symbol) extends SpecializedInfo {
+
+    /** Type bounds of a @specialized type var are now in the environment. */
+    override def typeBoundsIn(env: TypeEnv): Boolean = {
+      target.info.typeParams exists { tvar => 
+        (tvar.hasAnnotation(SpecializedClass)
+         && (specializedTypeVars(tvar.info.bounds) exists env.isDefinedAt))
+      }
+    }
+
+    override lazy val degenerate = {
+      log("degenerate: " + target + 
+              " stv tparams: " + specializedTypeVars(target.info.typeParams map (_.info)) + 
+              " stv info: " + specializedTypeVars(target.info.resultType))
+      !(specializedTypeVars(target.info.typeParams map (_.info))
+        -- specializedTypeVars(target.info.resultType)).isEmpty
+    }
+  }
+  
+  /** Map a symbol to additional information on specialization. */
+  private val info: mutable.Map[Symbol, SpecializedInfo] = new mutable.HashMap[Symbol, SpecializedInfo]
+  
+  /** Has `clazz' any type parameters that need be specialized? */
+  def hasSpecializedParams(clazz: Symbol): Boolean =
+    !specializedParams(clazz).isEmpty
+  
+  /** Return specialized type parameters. */
+  def specializedParams(sym: Symbol): List[Symbol] = 
+    splitParams(sym.info.typeParams)._1
+  
+  def splitParams(tps: List[Symbol]) = 
+    tps.partition(_.hasAnnotation(SpecializedClass))
+  
+  def unspecializedArgs(sym: Symbol, args: List[Type]): List[Type] = 
+    for ((tvar, tpe) <- sym.info.typeParams.zip(args) if !tvar.hasAnnotation(SpecializedClass))
+      yield tpe
+  
+  val specializedType = new TypeMap {
+    override def apply(tp: Type): Type = tp match {
+      case TypeRef(pre, sym, args) if !args.isEmpty =>
+        val pre1 = this(pre)
+        val args1 = args// map this
+        val unspecArgs = unspecializedArgs(sym, args)
+        specializedClass.get((sym, TypeEnv.fromSpecialization(sym, args1))) match {
+          case Some(sym1) =>
+            assert(sym1.info.typeParams.length == unspecArgs.length, sym1)
+            typeRef(pre1, sym1, unspecArgs)
+          case None => 
+            typeRef(pre1, sym, args1)
+        } 
+      case _ => tp // mapOver(tp)
+    }
+  }
+
+  /** Return the specialized overload of sym in the given env, if any. */
+  def overload(sym: Symbol, env: TypeEnv) = 
+    overloads(sym).find(ov => TypeEnv.includes(ov.env, env))
+  
+  /** Return the specialized name of 'sym' in the given environment. It
+   *  guarantees the same result regardless of the map order by sorting 
+   *  type variables alphabetically.
+   */
+  private def specializedName(sym: Symbol, env: TypeEnv): Name = {
+    val tvars = if (sym.isClass) env.keySet 
+                else specializedTypeVars(sym).intersect(env.keySet)
+    val (methparams, others) = tvars.toList.partition(_.owner.isMethod)
+    val tvars1 = methparams sortBy (_.name.toString)
+    val tvars2 = others sortBy (_.name.toString)
+    if (settings.debug.value) log("specName(%s) env: %s tvars: %s ".format(sym, env, (tvars1, tvars2)))
+    specializedName(sym.name, tvars1 map env, tvars2 map env)
+  }
+
+  /** Specialize name for the two list of types. The first one denotes
+   *  specialization on method type parameters, the second on outer environment.
+   */
+  private def specializedName(name: Name, types1: List[Type], types2: List[Type]): Name = {
+    if (nme.INITIALIZER == name || (types1.isEmpty && types2.isEmpty))
+      name
+    else if (nme.isSetterName(name))
+      nme.getterToSetter(specializedName(nme.setterToGetter(name), types1, types2))
+    else if (nme.isLocalName(name))
+      nme.getterToLocal(specializedName(nme.localToGetter(name), types1, types2))
+    else {
+      val (base, cs, ms) = nme.splitSpecializedName(name)
+      newTermName(base.toString + "$"
+                  + "m" + ms + types1.map(t => definitions.abbrvTag(t.typeSymbol)).mkString("", "", "")
+                  + "c" + cs + types2.map(t => definitions.abbrvTag(t.typeSymbol)).mkString("", "", "$sp"))
+    }
+  }
+
+  lazy val primitiveTypes = List(
+    definitions.UnitClass.tpe,
+    definitions.BooleanClass.tpe,
+    definitions.ByteClass.tpe,
+    definitions.ShortClass.tpe,
+    definitions.CharClass.tpe,
+    definitions.IntClass.tpe,
+    definitions.LongClass.tpe,
+    definitions.FloatClass.tpe,
+    definitions.DoubleClass.tpe)
+
+   /** Return the concrete types `sym' should be specialized at.
+   */
+  def concreteTypes(sym: Symbol): List[Type] = 
+    sym.getAnnotation(SpecializedClass) match {
+      case Some(AnnotationInfo(_, args, _)) => 
+        args match {
+          case Nil =>
+            log(sym + " specialized on everything")
+            primitiveTypes.toList
+          case _ =>
+            val tpes = args.map(_.symbol.companionClass.tpe)
+            log(sym + " specialized on " + tpes)
+            tpes
+        }
+      case _ =>
+        Nil
+    }
+
+  /** Return a list of all type environments for all specializations 
+   *  of @specialized types in `tps'.
+   */
+  private def specializations(tps: List[Symbol]): List[TypeEnv] = {
+    val stps = tps filter (_.hasAnnotation(SpecializedClass))
+    val env = immutable.HashMap.empty[Symbol, Type]
+    count(stps, concreteTypes _) map { tps =>
+      immutable.HashMap.empty[Symbol, Type] ++ (stps zip tps)
+    }
+  }  
+  
+  /** Generate all arrangements with repetitions from the list of values, 
+   *  with 'pos' positions. For example, count(2, List(1, 2)) yields
+   *  List(List(1, 1), List(1, 2), List(2, 1), List(2, 2))
+   */
+  private def count[A, V](xs: List[A], values: A => List[V]): List[List[V]] = {
+    if (xs.isEmpty) Nil
+    else if (xs.tail.isEmpty) values(xs.head) map (_ :: Nil)
+    else for (v <- values(xs.head); vs <- count(xs.tail, values)) yield v :: vs
+  }     
+    
+  /** Does the given tpe need to be specialized in the environment 'env'?
+   *  Specialization is needed for
+   *    - members with specialized type parameters found in the given environment
+   *    - constructors of specialized classes
+   *    - normalized members whose type bounds appear in the environment
+   */
+  private def needsSpecialization(env: TypeEnv, sym: Symbol): Boolean = {
+    (specializedTypeVars(sym).intersect(env.keySet).nonEmpty
+     || (sym.isClassConstructor && sym.enclClass.typeParams.exists(_.hasAnnotation(SpecializedClass)))
+     || (isNormalizedMember(sym) && info(sym).typeBoundsIn(env)))
+
+  }
+  
+  def isNormalizedMember(m: Symbol): Boolean =
+    (m.hasFlag(SPECIALIZED) && (info.get(m) match {
+      case Some(NormalizedMember(_)) => true
+      case _ => false
+    }))
+      
+  
+  def specializedTypeVars(tpe: List[Type]): immutable.Set[Symbol] =
+    tpe.foldLeft(immutable.ListSet.empty[Symbol]: immutable.Set[Symbol]) { 
+      (s, tp) => s ++ specializedTypeVars(tp) 
+    }
+
+  def specializedTypeVars(sym: Symbol): immutable.Set[Symbol] =
+    atPhase(currentRun.typerPhase)(specializedTypeVars(sym.info))
+  
+  /** Return the set of @specialized type variables mentioned by the given type.
+   *  It only counts type variables that appear:
+   *    - naked
+   *    - as arguments to type constructors in @specialized positions
+   *      (arrays ar considered as Array[@specialized T]
+   */
+  def specializedTypeVars(tpe: Type): immutable.Set[Symbol] = tpe match {
+    case TypeRef(pre, sym, args) =>
+      if (sym.isAliasType)
+        specializedTypeVars(tpe.normalize)
+      else if (   sym.isTypeParameter && sym.hasAnnotation(SpecializedClass)
+               || (sym.isTypeSkolem && sym.deSkolemize.hasAnnotation(SpecializedClass)))
+        immutable.ListSet.empty + sym
+      else if (sym == definitions.ArrayClass)
+        specializedTypeVars(args)
+      else {
+        val extra = for ((tp, arg) <- sym.typeParams.zip(args) if tp.hasAnnotation(SpecializedClass))
+          yield specializedTypeVars(arg).toList
+        immutable.ListSet.empty[Symbol] ++ extra.flatten
+      }
+
+    case PolyType(tparams, resTpe) =>
+      specializedTypeVars(tparams map (_.info)) ++ specializedTypeVars(resTpe)
+
+    case MethodType(argSyms, resTpe) =>
+      specializedTypeVars(argSyms map (_.tpe)) ++ specializedTypeVars(resTpe)
+
+    case ExistentialType(_, res) => specializedTypeVars(res)
+    case AnnotatedType(_, tp, _) => specializedTypeVars(tp)
+    case TypeBounds(hi, lo) => specializedTypeVars(hi) ++ specializedTypeVars(lo)
+    case _ => immutable.ListSet.empty[Symbol]
+  }
+  
+  /** Specialize 'clazz', in the environment `outerEnv`. The outer
+   *  environment contains bindings for specialized types of enclosing
+   *  classes.
+   * 
+   *  A class C is specialized w.r.t to its own specialized type params
+   *  `stps`, by specializing its members, and creating a new class for
+   *  each combination of `stps`.
+   */
+  def specializeClass(clazz: Symbol, outerEnv: TypeEnv): List[Symbol] = {
+    def specializedClass(env: TypeEnv, normMembers: List[Symbol]): Symbol = {
+      val cls = clazz.owner.newClass(clazz.pos, specializedName(clazz, env))
+                              .setFlag(SPECIALIZED | clazz.flags)
+                              .resetFlag(CASE)
+      cls.sourceFile = clazz.sourceFile
+      currentRun.symSource(cls) = clazz.sourceFile // needed later on by mixin
+      
+      typeEnv(cls) = env
+      this.specializedClass((clazz, env)) = cls
+
+      // declarations of the newly specialized class 'cls'
+      val decls1 = new Scope
+
+      // original unspecialized type parameters
+      var oldClassTParams: List[Symbol] = Nil
+
+      // unspecialized type parameters of 'cls' (cloned)
+      var newClassTParams: List[Symbol] = Nil
+
+      // has to be a val in order to be computed early. It is later called
+      // within 'atPhase(next)', which would lead to an infinite cycle otherwise 
+      val specializedInfoType: Type = {
+        val (_, unspecParams) = splitParams(clazz.info.typeParams)
+        oldClassTParams = unspecParams
+        newClassTParams = cloneSymbols(unspecParams, cls) map subst(env)
+
+        def applyContext(tpe: Type) =
+          subst(env, tpe).subst(unspecParams, newClassTParams map (_.tpe))
+
+        /** Return a list of specialized parents to be re-mixed in a specialized subclass.
+         *  Assuming env = [T -> Int] and
+         *    class Integral[@specialized T] extends Numeric[T]
+         *  and Numeric[U] is specialized on U, this produces List(Numeric$mcI).
+         *
+         *  so that class Integral$mci extends Integral[Int] with Numeric$mcI.
+         */
+        def specializedParents(parents: List[Type]): List[Type] = {
+          val res = new mutable.ListBuffer[Type]
+          for (p <- parents) {
+            val stp = atPhase(phase.next)(specializedType(p))
+            if (stp != p)
+              if (p.typeSymbol.isTrait) res += stp
+              else if (currentRun.compiles(clazz))
+                reporter.warning(clazz.pos, p.typeSymbol + " must be a trait. Specialized version of "
+                  + clazz + " will inherit generic " + p)
+          }
+          res.reverse.toList
+        }
+
+        var parents = List(applyContext(atPhase(currentRun.typerPhase)(clazz.tpe)))
+        if (parents.head.typeSymbol.isTrait)
+          parents = parents.head.parents.head :: parents
+        val extraSpecializedMixins = specializedParents(clazz.info.parents.map(applyContext))
+        log("extraSpecializedMixins: " + extraSpecializedMixins)
+        val infoType = ClassInfoType(parents ::: extraSpecializedMixins, decls1, cls)
+        if (newClassTParams.isEmpty) infoType else PolyType(newClassTParams, infoType)
+      }
+
+      log("specializedClass " + cls + ": " + specializedInfoType)
+      atPhase(phase.next)(cls.setInfo(specializedInfoType))
+      
+      val fullEnv = outerEnv ++ env
+
+      /** Enter 'sym' in the scope of the current specialized class. It's type is
+       *  mapped through the active environment, binding type variables to concrete
+       *  types. The existing typeEnv for `sym' is composed with the current active
+       *  environment
+       */
+      def enterMember(sym: Symbol): Symbol = {
+        typeEnv(sym) = fullEnv ++ typeEnv(sym) // append the full environment
+        sym.setInfo(sym.info.substThis(clazz, ThisType(cls)).subst(oldClassTParams, newClassTParams map (_.tpe)))
+        decls1.enter(subst(fullEnv)(sym))
+      }
+
+      /** Create and enter in scope an overridden symbol m1 for `m' that forwards
+       *  to `om'. `om' is a fresh, special overload of m1 that is an implementation
+       *  of `m'. For example, for a
+       *
+       *  class Foo[@specialized A] {
+       *    def m(x: A) = <body>
+       *  }
+       *  , for class Foo$I extends Foo[Int], this method enters two new symbols in
+       *  the scope of Foo$I:
+       *
+       *    def m(x: Int) = m$I(x)
+       *    def m$I(x: Int) = <body>/adapted to env {A -> Int}
+       */
+      def forwardToOverload(m: Symbol): Symbol = {
+        val specMember = enterMember(m.cloneSymbol(cls)).setFlag(OVERRIDE | SPECIALIZED).resetFlag(DEFERRED | CASEACCESSOR)          
+        val om = specializedOverload(cls, m, env).setFlag(OVERRIDE)
+        
+        var original = info.get(m) match {
+          case Some(NormalizedMember(tg)) => tg
+          case _ => m
+        }
+
+        info(specMember)  = Forward(om)
+        info(om) = if (original.isDeferred) Forward(original) else Implementation(original)
+        typeEnv(om) = env ++ typeEnv(m) // add the environment for any method tparams
+        overloads(specMember) = Overload(om, typeEnv(om)) :: overloads(specMember)
+        
+        enterMember(om)
+      }
+
+      log("specializedClass: " + cls)
+      for (m <- normMembers if needsSpecialization(outerEnv ++ env, m) && satisfiable(fullEnv)) {
+        if (settings.debug.value) log(" * looking at: " + m)
+        if (!m.isDeferred) concreteSpecMethods += m
+
+        // specialized members have to be overridable.
+        if (m.hasFlag(PRIVATE))
+          m.resetFlag(PRIVATE).setFlag(PROTECTED)
+        
+        if (m.isConstructor) {
+          val specCtor = enterMember(m.cloneSymbol(cls).setFlag(SPECIALIZED))
+          info(specCtor) = Forward(m)
+
+        } else if (isNormalizedMember(m)) {  // methods added by normalization
+          val NormalizedMember(original) = info(m)
+          if (!conflicting(env ++ typeEnv(m))) {
+            if (info(m).degenerate) {
+              if (settings.debug.value) log("degenerate normalized member " + m + " info(m): " + info(m))
+              val specMember = enterMember(m.cloneSymbol(cls)).setFlag(SPECIALIZED).resetFlag(DEFERRED)
+              info(specMember) = Implementation(original)
+              typeEnv(specMember) = env ++ typeEnv(m)
+            } else {
+              val om = forwardToOverload(m)
+              if (settings.debug.value) log("normalizedMember " + m + " om: " + om + " typeEnv(om): " + typeEnv(om))
+            }
+          } else 
+            log("conflicting env for " + m + " env: " + env)
+
+        } else if (m.isDeferred) { // abstract methods
+          val specMember = enterMember(m.cloneSymbol(cls)).setFlag(SPECIALIZED).resetFlag(DEFERRED)
+          if (settings.debug.value) log("deferred " + specMember.fullName + " is forwarded")
+            
+          info(specMember) = new Forward(specMember) {
+            override def target = m.owner.info.member(specializedName(m, env))
+          }
+
+        } else if (m.isMethod && !m.hasFlag(ACCESSOR)) { // other concrete methods
+          forwardToOverload(m)
+
+        } else if (m.isValue && !m.isMethod) { // concrete value definition
+          def mkAccessor(field: Symbol, name: Name) = {
+            val sym = cls.newMethod(field.pos, name)
+                .setFlag(SPECIALIZED | m.getter(clazz).flags)
+                .resetFlag(LOCAL | PARAMACCESSOR | CASEACCESSOR | LAZY) // we rely on the super class to initialize param accessors
+            info(sym) = SpecializedAccessor(field)
+            sym
+          }
+            
+          def overrideIn(clazz: Symbol, sym: Symbol) = {
+            val sym1 = sym.cloneSymbol(clazz)
+                          .setFlag(OVERRIDE | SPECIALIZED)
+                          .resetFlag(DEFERRED | CASEACCESSOR | PARAMACCESSOR | LAZY)
+            sym1.setInfo(sym1.info.asSeenFrom(clazz.tpe, sym1.owner))
+          }
+            
+          val specVal = specializedOverload(cls, m, env)
+
+          concreteSpecMethods += m
+          specVal.asInstanceOf[TermSymbol].setAlias(m)
+
+          enterMember(specVal)
+          // create accessors
+          if (settings.debug.value)
+            log("m: " + m + " isLocal: " + nme.isLocalName(m.name) + " specVal: " + specVal.name + " isLocal: " + nme.isLocalName(specVal.name))
+          if (nme.isLocalName(m.name)) {
+            val specGetter = mkAccessor(specVal, nme.localToGetter(specVal.name)).setInfo(MethodType(List(), specVal.info))
+            val origGetter = overrideIn(cls, m.getter(clazz))
+            info(origGetter) = Forward(specGetter)
+            enterMember(specGetter)
+            enterMember(origGetter)
+            if (settings.debug.value) log("created accessors: " + specGetter + " orig: " + origGetter)
+
+            clazz.caseFieldAccessors.find(_.name.startsWith(m.name)) foreach { cfa =>
+              val cfaGetter = overrideIn(cls, cfa)
+              info(cfaGetter) = SpecializedAccessor(specVal)
+              enterMember(cfaGetter)
+              if (settings.debug.value) log("found case field accessor for " + m + " added override " + cfaGetter);
+            }                                                                       
+
+            if (specVal.isVariable && m.setter(clazz) != NoSymbol) {
+              val specSetter = mkAccessor(specVal, nme.getterToSetter(specGetter.name))
+                .resetFlag(STABLE)
+              specSetter.setInfo(MethodType(specSetter.newSyntheticValueParams(List(specVal.info)), 
+                                            definitions.UnitClass.tpe))
+              val origSetter = overrideIn(cls, m.setter(clazz))
+              info(origSetter) = Forward(specSetter)
+              enterMember(specSetter)
+              enterMember(origSetter)
+            }
+          } else { // if there are no accessors, specialized methods will need to access this field in specialized subclasses
+            m.resetFlag(PRIVATE)
+            specVal.resetFlag(PRIVATE)
+          }
+        } else if (m.isClass) {
+          val specClass: Symbol = m.cloneSymbol(cls).setFlag(SPECIALIZED)
+          typeEnv(specClass) = fullEnv
+          specClass.name = specializedName(specClass, fullEnv)
+          enterMember(specClass)
+          log("entered specialized class " + specClass.fullName)
+          info(specClass) = SpecializedInnerClass(m, fullEnv)
+        }
+      }
+      cls
+    }
+
+    log("specializeClass " + clazz.fullName)
+    val decls1 = (clazz.info.decls.toList flatMap { m: Symbol =>
+      if (m.isAnonymousClass) List(m) else {
+        normalizeMember(m.owner, m, outerEnv) flatMap { normalizedMember =>
+          val ms = specializeMember(m.owner, normalizedMember, outerEnv, clazz.info.typeParams)
+//          atPhase(currentRun.typerPhase)(println("normalizedMember.info: " + normalizedMember.info)) // bring the info to the typer phase
+          // interface traits have concrete members now
+          if (ms.nonEmpty && clazz.isTrait && clazz.isInterface)
+            clazz.resetFlag(INTERFACE)
+
+          if (normalizedMember.isMethod) {
+            val newTpe = subst(outerEnv, normalizedMember.info)
+            if (newTpe != normalizedMember.info) // only do it when necessary, otherwise the method type might be at a later phase already
+              normalizedMember.updateInfo(newTpe) :: ms
+            else
+              normalizedMember :: ms
+          } else
+            normalizedMember :: ms
+        }
+      }
+    })
+    
+    var hasSubclasses = false
+    for (env <- specializations(clazz.info.typeParams) if satisfiable(env)) {
+      val spc = specializedClass(env, decls1)
+      log("entered " + spc + " in " + clazz.owner)
+      hasSubclasses = true
+      atPhase(phase.next)(clazz.owner.info.decls enter spc) //!! assumes fully specialized classes
+    }
+    if (hasSubclasses) clazz.resetFlag(FINAL)
+    decls1
+  }
+
+  /** Expand member `sym' to a set of normalized members. Normalized members
+   *  are monomorphic or polymorphic only in non-specialized types.
+   *
+   *  Given method m[@specialized T, U](x: T, y: U) it returns
+   *     m[T, U](x: T, y: U),
+   *     m$I[ U](x: Int, y: U),
+   *     m$D[ U](x: Double, y: U)
+   */
+  private def normalizeMember(owner: Symbol, sym: Symbol, outerEnv: TypeEnv): List[Symbol] = {
+    if (settings.debug.value) log("normalizeMember: " + sym.fullName)
+    if (sym.isMethod && !atPhase(currentRun.typerPhase)(sym.typeParams.isEmpty)) {
+      var (stps, tps) = splitParams(sym.info.typeParams)
+      val unusedStvars = stps filterNot (specializedTypeVars(sym.info).toList contains)
+      if (unusedStvars.nonEmpty && currentRun.compiles(sym) && !sym.isSynthetic) {
+        reporter.warning(sym.pos, "%s %s unused or used in non-specializable positions."
+          .format(unusedStvars.mkString("", ", ", ""), if (unusedStvars.length == 1) "is" else "are"))
+        unusedStvars foreach (_.removeAnnotation(SpecializedClass))
+        stps = stps filterNot (unusedStvars contains)
+        tps = sym.info.typeParams filterNot (_.hasAnnotation(SpecializedClass))
+      }
+      val res = sym :: (for (env <- specializations(stps) if needsSpecialization(env, sym)) yield {
+        val keys = env.keysIterator.toList; 
+        val vals = env.valuesIterator.toList
+        val specMember =  sym.cloneSymbol(owner).setFlag(SPECIALIZED).resetFlag(DEFERRED)
+        specMember.name = specializedName(sym, env)
+
+        typeEnv(specMember) = outerEnv ++ env
+        val tps1 = cloneSymbols(tps) 
+        for (tp <- tps1) tp.setInfo(tp.info.subst(keys, vals))
+        // the cloneInfo is necessary so that method parameter symbols are cloned at the new owner
+        val methodType = sym.info.resultType.subst(keys ::: tps, vals ::: (tps1 map (_.tpe))).cloneInfo(specMember)
+
+        specMember.setInfo(polyType(tps1, methodType))
+
+        if (settings.debug.value) log("expanded member: " + sym  + ": " + sym.info + " -> " + specMember + ": " + specMember.info + " env: " + env)
+        info(specMember) = NormalizedMember(sym)
+        overloads(sym) = Overload(specMember, env) :: overloads(sym)
+        specMember
+      })
+      //stps foreach (_.removeAttribute(SpecializedClass))
+      res
+    } else List(sym)
+  }
+  
+  /** Specialize member `m' w.r.t. to the outer environment and the type
+   *  parameters of the innermost enclosing class.
+   * 
+   *  Turns 'private' into 'protected' for members that need specialization.
+   * 
+   *  Return a list of symbols that are specializations of 'sym', owned by 'owner'.
+   */
+  private def specializeMember(owner: Symbol, sym: Symbol, outerEnv: TypeEnv, tps: List[Symbol]): List[Symbol] = {
+    def specializeOn(tparams: List[Symbol]): List[Symbol] =
+      for (spec <- specializations(tparams)) yield {
+        if (sym.hasFlag(PRIVATE)) sym.resetFlag(PRIVATE).setFlag(PROTECTED)
+        sym.resetFlag(FINAL)
+        val specMember = subst(outerEnv)(specializedOverload(owner, sym, spec))
+        typeEnv(specMember) = typeEnv(sym) ++ outerEnv ++ spec
+        if (settings.debug.value) log("added specialized overload: %s in env: %s".format(specMember, typeEnv(specMember)))
+        overloads(sym) = Overload(specMember, spec) :: overloads(sym)
+        specMember
+      }
+
+    if (sym.isMethod) {
+      if (settings.debug.value) log("specializeMember %s with tps: %s stvars(sym): %s".format(sym, tps, specializedTypeVars(sym)))
+      val tps1 = if (sym.isConstructor) tps filter (tp => sym.info.paramTypes.contains(tp)) else tps
+      val tps2 = tps1 intersect specializedTypeVars(sym).toList
+      if (!sym.isDeferred) concreteSpecMethods += sym 
+
+      specializeOn(tps2) map {m => info(m) = SpecialOverload(sym, typeEnv(m)); m}
+    } else
+      List()
+  }
+  
+  /** Return the specialized overload of `m', in the given environment. */
+  private def specializedOverload(owner: Symbol, sym: Symbol, env: TypeEnv): Symbol = {
+    val specMember = sym.cloneSymbol(owner) // this method properly duplicates the symbol's info
+    specMember.name = specializedName(sym, env)
+
+    specMember.setInfo(subst(env, specMember.info.asSeenFrom(owner.thisType, sym.owner)))
+      .setFlag(SPECIALIZED)
+      .resetFlag(DEFERRED | CASEACCESSOR | ACCESSOR | LAZY)
+  }
+
+  /** For each method m that overrides inherited method m', add a special
+   *  overload method `om' that overrides the corresponding overload in the
+   *  superclass. For the following example:
+   * 
+   *  class IntFun extends Function1[Int, Int] {
+   *     def apply(x: Int): Int = ..
+   *  }
+   * 
+   *  this method will return List('apply$spec$II')
+   */
+  private def specialOverrides(clazz: Symbol): List[Symbol] = {
+    log("specialOverrides(" + clazz + ")")
+
+    /** Return the overridden symbol in syms that needs a specialized overriding symbol,
+     *  together with its specialization environment. The overridden symbol may not be
+     *  the closest to 'overriding', in a given hierarchy.
+     *
+     *  An method m needs a special override if
+     *    * m overrides a method whose type contains specialized type variables
+     *    * there is a valid specialization environment that maps the overridden method type to m's type. 
+     */
+    def needsSpecialOverride(overriding: Symbol, syms: List[Symbol]): (Symbol, TypeEnv) = {
+      def missingSpecializations(baseTvar: Symbol, derivedTvar: Symbol): Set[Type] = {
+        val baseSet = concreteTypes(baseTvar).toSet
+        val derivedSet = concreteTypes(derivedTvar).toSet
+        baseSet diff derivedSet
+      }
+
+      def checkOverriddenTParams(overridden: Symbol) {
+        if (currentRun.compiles(overriding))
+          for ((baseTvar, derivedTvar) <- overridden.info.typeParams.zip(overriding.info.typeParams);
+               val missing = missingSpecializations(baseTvar, derivedTvar)
+               if missing.nonEmpty)
+          reporter.error(derivedTvar.pos,
+            "Type parameter has to be specialized at least for the same types as in the overridden method. Missing " +
+                    "types: " + missing.mkString("", ", ", ""))        
+      }
+
+      for (overridden <- syms) {
+        if (settings.debug.value)
+          log("Overridden: " + overridden.fullName + ": " + overridden.info
+             + "\n by " + overriding.fullName + ": " + overriding.info)
+        val stvars = specializedTypeVars(overridden.info)
+        if (!stvars.isEmpty) {
+          if (settings.debug.value) log("\t\tspecializedTVars: " + stvars)
+          checkOverriddenTParams(overridden)
+
+          val env = unify(overridden.info, overriding.info, emptyEnv)
+          if (settings.debug.value)
+            log("\t\tenv: " + env + "isValid: " + TypeEnv.isValid(env, overridden)
+                  + "found: " + atPhase(phase.next)(overridden.owner.info.decl(specializedName(overridden, env))))
+          if (!TypeEnv.restrict(env, stvars).isEmpty
+              && TypeEnv.isValid(env, overridden)
+              && atPhase(phase.next)(overridden.owner.info.decl(specializedName(overridden, env))) != NoSymbol)
+            return (overridden, env)
+        }
+      }
+      (NoSymbol, emptyEnv)
+    }
+
+    val oms = new mutable.ListBuffer[Symbol]
+    for  (overriding <- clazz.info.decls;
+          val (overridden, env) = needsSpecialOverride(overriding, overriding.allOverriddenSymbols)
+          if overridden != NoSymbol) {
+      val om = specializedOverload(clazz, overridden, env)
+      log("Added specialized overload for %s in env: %s with type: %s".format(overriding.fullName, env, om.info))
+      typeEnv(om) = env
+      concreteSpecMethods += overriding
+      if (!overriding.isDeferred) {  // concrete method
+        // if the override is a normalized member, 'om' gets the implementation from
+        // its original target, and adds the environment of the normalized member (that is,
+        // any specialized /method/ type parameter bindings)
+        info(om) = info.get(overriding) match {
+          case Some(NormalizedMember(target)) =>
+            typeEnv(om) = env ++ typeEnv(overriding)
+            SpecialOverride(target)
+          case _ => SpecialOverride(overriding)
+        }
+        info(overriding)  = Forward(om)
+        om setPos overriding.pos
+      } else { // abstract override
+        if (settings.debug.value) log("abstract override " + overriding.fullName + " with specialized " + om.fullName)
+        info(om) = Forward(overriding)
+      }
+      overloads(overriding) = Overload(om, env) :: overloads(overriding)
+      oms += om
+      atPhase(phase.next)(
+        assert(overridden.owner.info.decl(om.name) != NoSymbol,
+               "Could not find " + om.name + " in " + overridden.owner.info.decls))
+    }
+    oms.toList
+  }
+  
+  /** Return the most general type environment that specializes tp1 to tp2.
+   *  It only allows binding of type parameters annotated with @specialized.
+   *  Fails if such an environment cannot be found.
+   */
+  private def unify(tp1: Type, tp2: Type, env: TypeEnv): TypeEnv = {
+//    println("\tunify \t" + tp1 + "\n\t\t" + tp2)
+    (tp1, tp2) match {
+    case (TypeRef(_, sym1, _), _) if sym1.hasAnnotation(SpecializedClass) =>
+      if (definitions.isValueClass(tp2.typeSymbol))
+        env + ((sym1, tp2))
+      else 
+        env
+    case (TypeRef(_, sym1, args1), TypeRef(_, sym2, args2)) =>
+      unify(args1, args2, env)
+    case (TypeRef(_, sym1, _), _) if sym1.isTypeParameterOrSkolem =>
+      env
+    case (MethodType(params1, res1), MethodType(params2, res2)) =>
+      unify(res1 :: (params1 map (_.tpe)), res2 :: (params2 map (_.tpe)), env)
+    case (PolyType(tparams1, res1), PolyType(tparams2, res2)) =>
+      unify(res1, res2, env)
+    case (PolyType(_, res), other) =>
+      unify(res, other, env)
+    case (ThisType(_), ThisType(_)) => env
+    case (_, SingleType(_, _)) => unify(tp1, tp2.underlying, env)
+    case (SingleType(_, _), _) => unify(tp1.underlying, tp2, env)
+    case (ThisType(_), _) => unify(tp1.widen, tp2, env)
+    case (_, ThisType(_)) => unify(tp1, tp2.widen, env)
+    case (RefinedType(_, _), RefinedType(_, _)) => env
+    case (AnnotatedType(_, tp1, _), tp2) => unify(tp2, tp1, env)
+    case (ExistentialType(_, res1), _) => unify(tp2, res1, env)
+    case _ =>
+      log("don't know how to unify %s [%s] with %s [%s]".format(tp1, tp1.getClass, tp2, tp2.getClass))
+      env
+  }
+  }
+  
+  private def unify(tp1: List[Type], tp2: List[Type], env: TypeEnv): TypeEnv = 
+    tp1.zip(tp2).foldLeft(env) { (env, args) =>
+      unify(args._1, args._2, env)
+    }
+  
+  private def specializedTypes(tps: List[Symbol]) = tps.filter(_.hasAnnotation(SpecializedClass))
+  
+  /** Map class symbols to the type environments where they were created. */
+  val typeEnv: mutable.Map[Symbol, TypeEnv] = new mutable.HashMap[Symbol, TypeEnv] {
+    override def default(key: Symbol) = emptyEnv
+  }
+
+  /** Apply type bindings in the given environment `env' to all declarations.  */
+  private def subst(env: TypeEnv, decls: List[Symbol]): List[Symbol] =
+    decls map subst(env)
+
+  /** Apply the type environment 'env' to the given type. All type
+   *  bindings are supposed to be to primitive types. A type variable
+   *  that is annotated with 'uncheckedVariance' is mapped to the corresponding
+   *  primitive type losing the annotation. 
+   */
+  private def subst(env: TypeEnv, tpe: Type): Type = {
+    class FullTypeMap(from: List[Symbol], to: List[Type]) extends SubstTypeMap(from, to) {
+
+      override def mapOver(tp: Type): Type = tp match {
+        case ClassInfoType(parents, decls, clazz) =>
+          val parents1 = parents mapConserve (this);
+          val declsList = decls.toList
+          val decls1 = mapOver(declsList);
+          if ((parents1 eq parents) && (decls1 eq declsList)) tp
+          else ClassInfoType(parents1, new Scope(decls1), clazz)
+        case AnnotatedType(annots, atp, selfsym) =>
+          val annots1 = mapOverAnnotations(annots)
+          val atp1 = this(atp)
+          if ((annots1 eq annots) && (atp1 eq atp)) tp
+          else if (annots1.isEmpty) atp1
+          else if (atp1 ne atp) {
+            val annots2 = annots1.filter(_.atp.typeSymbol != definitions.uncheckedVarianceClass)
+            if (annots2.isEmpty) atp1
+            else AnnotatedType(annots2, atp1, selfsym)
+          } else
+            AnnotatedType(annots1, atp1, selfsym)
+
+        case _ => super.mapOver(tp)
+      }
+    }
+    // disabled because of bugs in std. collections
+    //val (keys, values) = env.iterator.toList.unzip
+    val keys = env.keysIterator.toList
+    val values = env.valuesIterator.toList
+    (new FullTypeMap(keys, values))(tpe)
+//    tpe.subst(keys, values)
+  }
+
+  private def subst(env: TypeEnv)(decl: Symbol): Symbol = {
+    val tpe = subst(env, decl.info)
+    decl.setInfo(if (decl.isConstructor) tpe match {
+      case MethodType(args, resTpe) => MethodType(args, decl.owner.tpe)
+    } else tpe)
+  }
+  
+  /** Type transformation. It is applied to all symbols, compiled or loaded.
+   *  If it is a 'no-specialization' run, it is applied only to loaded symbols.  
+   */
+  override def transformInfo(sym: Symbol, tpe: Type): Type = {
+    val res = if (!settings.nospecialization.value || !currentRun.compiles(sym)) tpe match {
+      case PolyType(targs, ClassInfoType(base, decls, clazz))
+              if clazz != definitions.RepeatedParamClass
+              && clazz != definitions.JavaRepeatedParamClass
+              && !clazz.hasFlag(JAVA) =>
+        val parents = base map specializedType
+        if (settings.debug.value) log("transformInfo (poly) " + clazz + " with parents1: " + parents + " ph: " + phase)
+//        if (clazz.name.toString == "$colon$colon")
+//          (new Throwable).printStackTrace
+        PolyType(targs, ClassInfoType(parents,
+          new Scope(specializeClass(clazz, typeEnv(clazz)) ::: specialOverrides(clazz)),
+          clazz))
+
+      case ClassInfoType(base, decls, clazz) if !clazz.isPackageClass && !clazz.hasFlag(JAVA) =>
+        atPhase(phase.next)(base.map(_.typeSymbol.info))
+        val parents = base map specializedType
+        if (settings.debug.value) log("transformInfo " + clazz + " with parents1: " + parents + " ph: " + phase)
+        val res = ClassInfoType(base map specializedType,
+          new Scope(specializeClass(clazz, typeEnv(clazz)) ::: specialOverrides(clazz)),
+          clazz)
+        res
+        
+      case _ =>
+        tpe
+    } else tpe
+    res
+
+  }
+
+  def conflicting(env: TypeEnv): Boolean = {
+    val silent = (pos: Position, str: String) => ()
+    conflicting(env, silent)
+  }
+
+  /** Is any type variable in `env' conflicting with any if its type bounds, when
+   *  type bindings in `env' are taken into account?
+   *
+   *  A conflicting type environment could still be satisfiable.
+   */
+  def conflicting(env: TypeEnv, warn: (Position, String) => Unit): Boolean = 
+    env exists { case (tvar, tpe) =>
+      if (!((subst(env, tvar.info.bounds.lo) <:< tpe)
+            && (tpe <:< subst(env, tvar.info.bounds.hi)))) {
+        warn(tvar.pos, "Bounds prevent specialization for " + tvar)
+        true
+      } else false
+  }
+
+  /** The type environment is sound w.r.t. to all type bounds or only soft
+   *  conflicts appear. An environment is sound if all bindings are within
+   *  the bounds of the given type variable. A soft conflict is a binding
+   *  that does not fall within the bounds, but whose bounds contain
+   *  type variables that are @specialized, (that could become satisfiable).
+   */
+  def satisfiable(env: TypeEnv, warn: (Position, String) => Unit): Boolean = {
+    def matches(tpe1: Type, tpe2: Type): Boolean = {
+      val t1 = subst(env, tpe1)
+      val t2 = subst(env, tpe2)
+      ((t1 <:< t2)
+        || !specializedTypeVars(t1).isEmpty 
+        || !specializedTypeVars(t2).isEmpty)
+     }
+
+    env forall { case (tvar, tpe) => 
+      ((matches(tvar.info.bounds.lo, tpe)
+       && matches(tpe, tvar.info.bounds.hi))
+       || { warn(tvar.pos, "Bounds prevent specialization of " + tvar); 
+             log("specvars: "
+                     + tvar.info.bounds.lo + ": " + specializedTypeVars(tvar.info.bounds.lo)
+                     + " " + subst(env, tvar.info.bounds.hi) + ": " + specializedTypeVars(subst(env, tvar.info.bounds.hi)))
+            false })
+    }
+  }
+
+  def satisfiable(env: TypeEnv): Boolean = {
+    val silent = (pos: Position, str: String) => ()
+    satisfiable(env, silent)
+  }
+
+  class Duplicator extends {
+    val global: SpecializeTypes.this.global.type = SpecializeTypes.this.global
+  } with typechecker.Duplicators
+
+  /** A tree symbol substituter that substitutes on type skolems.
+   *  If a type parameter is a skolem, it looks for the original
+   *  symbol in the 'from' and maps it to the corresponding new
+   *  symbol. The new symbol should probably be a type skolem as
+   *  well (not enforced).
+   *
+   *  All private members are made protected in order to be accessible from
+   *  specialized classes.
+   */
+  class ImplementationAdapter(from: List[Symbol],
+                              to: List[Symbol],
+                              targetClass: Symbol,
+                              addressFields: Boolean) extends TreeSymSubstituter(from, to) {
+    override val symSubst = new SubstSymMap(from, to) {
+      override def matches(sym1: Symbol, sym2: Symbol) =
+        if (sym2.isTypeSkolem) sym2.deSkolemize eq sym1
+        else sym1 eq sym2
+    }
+
+    private def isAccessible(sym: Symbol): Boolean =
+      (currentClass == sym.owner.enclClass) && (currentClass != targetClass)
+
+    private def shouldMakePublic(sym: Symbol): Boolean =
+      sym.hasFlag(PRIVATE | PROTECTED) && (addressFields || !nme.isLocalName(sym.name))
+
+    /** All private members that are referenced are made protected,
+     *  in order to be accessible from specialized subclasses.
+     */
+    override def transform(tree: Tree): Tree = tree match {
+      case Select(qual, name) =>
+        val sym = tree.symbol
+        if (sym.hasFlag(PRIVATE))
+          if (settings.debug.value)
+            log("seeing private member %s, currentClass: %s, owner: %s, isAccessible: %b, isLocalName: %b"
+                    .format(sym, currentClass, sym.owner.enclClass, isAccessible(sym), nme.isLocalName(sym.name)))
+        if (shouldMakePublic(sym) && !isAccessible(sym)) {
+          if (settings.debug.value) log("changing private flag of " + sym)
+          sym.makeNotPrivate(sym.owner)
+        }
+        super.transform(tree)
+
+      case _ =>
+        super.transform(tree)
+    }
+  }
+  
+  def specializeCalls(unit: CompilationUnit) = new TypingTransformer(unit) {
+    /** Map a specializable method to it's rhs, when not deferred. */
+    val body: mutable.Map[Symbol, Tree] = new mutable.HashMap
+  
+    /** Map a specializable method to its value parameter symbols. */
+    val parameters: mutable.Map[Symbol, List[List[Symbol]]] = new mutable.HashMap
+    
+    /** Collect method bodies that are concrete specialized methods.
+     */
+    class CollectMethodBodies extends Traverser {
+      override def traverse(tree: Tree) = tree match {
+        case  DefDef(mods, name, tparams, vparamss, tpt, rhs) =>
+          if (concreteSpecMethods(tree.symbol) || tree.symbol.isConstructor) {
+            if (settings.debug.value) log("adding body of " + tree.symbol)
+            body(tree.symbol) = rhs
+            //          body(tree.symbol) = tree // whole method
+            parameters(tree.symbol) = vparamss map (_ map (_.symbol))
+          } // no need to descend further down inside method bodies
+
+        case ValDef(mods, name, tpt, rhs) if concreteSpecMethods(tree.symbol) =>
+          body(tree.symbol) = rhs
+          //super.traverse(tree)
+        case _ =>
+          super.traverse(tree)
+      }
+    }
+
+    override def transform(tree: Tree): Tree = { 
+      val symbol = tree.symbol
+
+      /** The specialized symbol of 'tree.symbol' for tree.tpe, if there is one */
+      def specSym(qual: Tree): Option[Symbol] = {
+        val env = unify(symbol.tpe, tree.tpe, emptyEnv)
+        log("[specSym] checking for rerouting: %s with \n\tsym.tpe: %s, \n\ttree.tpe: %s \n\tenv: %s \n\tname: %s"
+                .format(tree, symbol.tpe, tree.tpe, env, specializedName(symbol, env)))
+        if (!env.isEmpty) {  // a method?
+          val specMember = qual.tpe.member(specializedName(symbol, env))
+          if (specMember ne NoSymbol)
+            if (typeEnv(specMember) == env) Some(specMember)
+            else {
+              log("wrong environments for specialized member: \n\ttypeEnv(%s) = %s\n\tenv = %s".format(specMember, typeEnv(specMember), env))
+              None
+            }
+          else None
+        } else None
+      }
+
+      def maybeTypeApply(fun: Tree, targs: List[Tree]) = 
+        if (targs.isEmpty) fun else TypeApply(fun, targs)
+
+      curTree = tree
+      tree match {
+        case Apply(Select(New(tpt), nme.CONSTRUCTOR), args) =>
+          if (findSpec(tpt.tpe).typeSymbol ne tpt.tpe.typeSymbol) {
+            log("** instantiated specialized type: " + findSpec(tpt.tpe))
+            atPos(tree.pos)(
+              localTyper.typed(
+                Apply(
+                  Select(New(TypeTree(findSpec(tpt.tpe))), nme.CONSTRUCTOR),
+                  transformTrees(args))))
+          } else super.transform(tree)
+          
+        case TypeApply(Select(qual, name), targs)
+                if (!specializedTypeVars(symbol.info).isEmpty && name != nme.CONSTRUCTOR) =>
+          if (settings.debug.value) log("checking typeapp for rerouting: " + tree + " with sym.tpe: " + symbol.tpe + " tree.tpe: " + tree.tpe)
+          val qual1 = transform(qual)
+          specSym(qual1) match {
+            case Some(specMember) =>
+              if (settings.debug.value) log("found " + specMember.fullName)
+              assert(symbol.info.typeParams.length == targs.length)
+              val env = typeEnv(specMember)
+              val residualTargs = 
+                for ((tvar, targ) <- symbol.info.typeParams.zip(targs) if !env.isDefinedAt(tvar)) 
+                  yield targ
+              assert(residualTargs.length == specMember.info.typeParams.length,
+                "residual: %s, tparams: %s, env: %s".format(residualTargs, symbol.info.typeParams, env))
+              val tree1 = maybeTypeApply(Select(qual1, specMember), residualTargs)
+              log("rewrote " + tree + " to " + tree1)
+              localTyper.typedOperator(atPos(tree.pos)(tree1)) // being polymorphic, it must be a method
+
+            case None => super.transform(tree)
+          }
+
+        case Select(qual, name) =>
+          if (settings.debug.value)
+            log("[%s] looking at Select: %s sym: %s: %s [tree.tpe: %s]".format(tree.pos.line, tree, symbol, symbol.info, tree.tpe))
+
+          if (!specializedTypeVars(symbol.info).isEmpty && name != nme.CONSTRUCTOR) {
+            val env = unify(symbol.tpe, tree.tpe, emptyEnv)
+            if (settings.debug.value) log("checking for rerouting: " + tree + " with sym.tpe: " + symbol.tpe + " tree.tpe: " + tree.tpe + " env: " + env)
+            if (!env.isEmpty) {
+              val specMember = overload(symbol, env)
+              if (specMember.isDefined) {
+                log("** routing " + tree + " to " + specMember.get.sym.fullName)
+                localTyper.typedOperator(atPos(tree.pos)(Select(transform(qual), specMember.get.sym.name)))
+              } else {
+                val qual1 = transform(qual)
+                val specMember = qual1.tpe.member(specializedName(symbol, env)).suchThat(_.tpe matches subst(env, symbol.tpe))
+                if (specMember ne NoSymbol) {
+                  log("** using spec member " + specMember + ": " + specMember.tpe)
+                  val tree1 = atPos(tree.pos)(Select(qual1, specMember))
+                  if (specMember.isMethod)
+                    localTyper.typedOperator(tree1)
+                  else
+                    localTyper.typed(tree1)
+                } else
+                  treeCopy.Select(tree, qual1, name)
+              }
+            } else
+              super.transform(tree)
+          } else overloads(symbol).find(_.sym.info =:= symbol.info) match {
+              case Some(specMember) =>
+                val qual1 = transform(qual)
+                if (settings.debug.value) log("** routing " + tree + " to " + specMember.sym.fullName + " tree: " + Select(qual1, specMember.sym.name))
+                localTyper.typedOperator(atPos(tree.pos)(Select(qual1, specMember.sym.name)))
+              case None =>
+                super.transform(tree)
+          }
+
+        case PackageDef(pid, stats) =>
+          tree.symbol.info // make sure specializations have been performed
+          atOwner(tree, symbol) {
+            val specMembers = implSpecClasses(stats) map localTyper.typed
+            treeCopy.PackageDef(tree, pid, transformStats(stats ::: specMembers, symbol.moduleClass))
+          }
+          
+        case Template(parents, self, body) =>
+          val specMembers = makeSpecializedMembers(tree.symbol.enclClass) ::: (implSpecClasses(body) map localTyper.typed)
+          if (!symbol.isPackageClass)
+            (new CollectMethodBodies)(tree)
+          val parents1 = currentOwner.info.parents.zipWithIndex.map {
+            case (tpe, idx) => TypeTree(tpe) setPos parents(idx).pos
+          }
+          treeCopy.Template(tree,
+            parents1    /*currentOwner.info.parents.map(tpe => TypeTree(tpe) setPos parents.head.pos)*/ ,
+            self,
+            atOwner(currentOwner)(transformTrees(body ::: specMembers)))
+        
+        case ddef @ DefDef(mods, name, tparams, vparamss, tpt, rhs) if info.isDefinedAt(symbol) =>
+          if (symbol.isConstructor) {
+            val t = atOwner(symbol) {
+              val superRef: Tree = Select(Super(nme.EMPTY.toTypeName, nme.EMPTY.toTypeName), nme.CONSTRUCTOR)
+              forwardCtorCall(tree.pos, superRef, vparamss, symbol.owner)
+            }
+            if (symbol.isPrimaryConstructor) localTyper typed {
+                atPos(symbol.pos)(treeCopy.DefDef(tree, mods, name, tparams, vparamss, tpt, Block(List(t), Literal(()))))
+            } else {
+              // duplicate the original constructor
+              duplicateBody(ddef, info(symbol).target)
+            }
+          } else info(symbol) match {
+            
+            case Implementation(target) =>
+              assert(body.isDefinedAt(target), "sym: " + symbol.fullName + " target: " + target.fullName)
+              // we have an rhs, specialize it
+              val tree1 = duplicateBody(ddef, target)
+              if (settings.debug.value) log("implementation: " + tree1)
+              val DefDef(mods, name, tparams, vparamss, tpt, rhs) = tree1
+              treeCopy.DefDef(tree1, mods, name, tparams, vparamss, tpt, transform(rhs))
+
+            case NormalizedMember(target) =>
+              if (target.isDeferred || conflicting(typeEnv(symbol))) {
+                treeCopy.DefDef(tree, mods, name, tparams, vparamss, tpt,
+                  localTyper.typed(
+                    Apply(gen.mkAttributedRef(definitions.Predef_error),
+                          List(Literal("boom! you stepped on a bug. This method should never be called.")))))
+              } else {
+                // we have an rhs, specialize it
+                val tree1 = duplicateBody(ddef, target)
+                if (settings.debug.value) log("implementation: " + tree1)
+                val DefDef(mods, name, tparams, vparamss, tpt, rhs) = tree1
+                treeCopy.DefDef(tree1, mods, name, tparams, vparamss, tpt, transform(rhs))
+              }
+
+            case SpecialOverride(target) =>
+              assert(body.isDefinedAt(target), "sym: " + symbol.fullName + " target: " + target.fullName)
+              if (settings.debug.value) log("moving implementation: " + body(target))
+              // we have an rhs, specialize it
+              val tree1 = addBody(ddef, target)
+              (new ChangeOwnerTraverser(target, tree1.symbol))(tree1.rhs)
+              if (settings.debug.value)
+                println("changed owners, now: " + tree1)
+              val DefDef(mods, name, tparams, vparamss, tpt, rhs) = tree1
+              treeCopy.DefDef(tree1, mods, name, tparams, vparamss, tpt, transform(rhs))
+
+
+            case SpecialOverload(original, env) =>
+              if (settings.debug.value) log("completing specialized " + symbol.fullName + " calling " + original)
+              val t = DefDef(symbol, { vparamss => 
+                val fun = Apply(Select(This(symbol.owner), original),
+                                makeArguments(original, vparamss.head))
+
+                gen.maybeMkAsInstanceOf(fun,
+                  symbol.owner.thisType.memberType(symbol).finalResultType,
+                  symbol.owner.thisType.memberType(original).finalResultType)
+              })
+              if (settings.debug.value) log("created " + t)
+              localTyper.typed(t)
+              
+            case fwd @ Forward(_) =>
+              val rhs1 = forwardCall(tree.pos, gen.mkAttributedRef(symbol.owner.thisType, fwd.target), vparamss)
+              if (settings.debug.value)
+                log("completed forwarder to specialized overload: " + fwd.target + ": " + rhs1)
+              localTyper.typed(treeCopy.DefDef(tree, mods, name, tparams, vparamss, tpt, rhs1))
+              
+            case SpecializedAccessor(target) =>
+              val rhs1 = if (symbol.isGetter)
+                gen.mkAttributedRef(target)
+              else 
+                Assign(gen.mkAttributedRef(target), Ident(vparamss.head.head.symbol))
+              localTyper.typed(treeCopy.DefDef(tree, mods, name, tparams, vparamss, tpt, rhs1))
+          }
+
+        case ValDef(mods, name, tpt, rhs) if symbol.hasFlag(SPECIALIZED) && !symbol.hasFlag(PARAMACCESSOR) =>
+          assert(body.isDefinedAt(symbol.alias))
+          val tree1 = treeCopy.ValDef(tree, mods, name, tpt, body(symbol.alias).duplicate)
+          if (settings.debug.value) log("now typing: " + tree1 + " in " + tree.symbol.owner.fullName)
+          val d = new Duplicator
+          val tree2 = d.retyped(localTyper.context1.asInstanceOf[d.Context],
+                    tree1,
+                    symbol.alias.enclClass,
+                    symbol.enclClass,
+                    typeEnv(symbol.alias) ++ typeEnv(tree.symbol))
+          val ValDef(mods1, name1, tpt1, rhs1) = tree2
+          treeCopy.ValDef(tree1, mods1, name1, tpt1, transform(rhs1))
+        
+//          val tree1 =
+//            treeCopy.ValDef(tree, mods, name, tpt,
+//              localTyper.typed(
+//                Apply(Select(Super(currentClass, nme.EMPTY), symbol.alias.getter(symbol.alias.owner)),
+//                      List())))
+//          if (settings.debug.value) log("replaced ValDef: " + tree1 + " in " + tree.symbol.owner.fullName)
+//          tree1
+
+        case Apply(sel @ Select(sup @ Super(qual, name), name1), args)
+          if (sup.symbol.info.parents != atPhase(phase.prev)(sup.symbol.info.parents)) =>
+
+          def parents = sup.symbol.info.parents
+          if (settings.debug.value) log(tree + " parents changed from: " + atPhase(phase.prev)(parents) + " to: " + parents)
+
+          val res = localTyper.typed(
+            Apply(Select(Super(qual, name) setPos sup.pos, name1) setPos sel.pos, transformTrees(args)) setPos tree.pos)
+          if (settings.debug.value) log("retyping call to super, from: " + symbol + " to " + res.symbol)
+          res
+
+        case _ =>
+          super.transform(tree)
+      }
+    }
+    
+    private def reskolemize(tparams: List[TypeDef]): (List[Symbol], List[Symbol]) = {
+      val tparams1 = tparams map (_.symbol)
+      localTyper.namer.skolemize(tparams)
+      (tparams1, tparams map (_.symbol))
+    }
+
+
+    private def duplicateBody(tree: DefDef, source: Symbol) = {
+      val symbol = tree.symbol
+      val meth = addBody(tree, source)
+      if (settings.debug.value) log("now typing: " + meth + " in " + symbol.owner.fullName)
+      val d = new Duplicator
+      try {
+      d.retyped(localTyper.context1.asInstanceOf[d.Context],
+                meth,
+                source.enclClass,
+                symbol.enclClass,
+                typeEnv(source) ++ typeEnv(symbol))
+      } catch {
+        case e => 
+          println("error compiling %s [%s]".format(unit, tree.pos))
+          throw e
+      }
+    }
+
+
+    /** Put the body of 'source' as the right hand side of the method 'tree'.
+     *  The destination method gets fresh symbols for type and value parameters,
+     *  and the body is updated to the new symbols, and owners adjusted accordingly.
+     *  However, if the same source tree is used in more than one place, full re-typing
+     *  is necessary. @see method duplicateBody
+     */
+    private def addBody(tree: DefDef, source: Symbol): DefDef = {
+      val symbol = tree.symbol
+      if (settings.debug.value) log("specializing body of" + symbol.fullName + ": " + symbol.info)
+      val DefDef(mods, name, tparams, vparamss, tpt, _) = tree
+//      val (_, origtparams) = splitParams(source.typeParams)
+      val boundTvars = typeEnv(symbol).keySet
+      val origtparams = source.typeParams.filter(!boundTvars(_))
+      if (settings.debug.value) log("substituting " + origtparams + " for " + symbol.typeParams)
+
+      // skolemize type parameters
+      val (oldtparams, newtparams) = reskolemize(tparams)
+
+      // create fresh symbols for value parameters to hold the skolem types
+      val vparamss1 = List(for (vdef <- vparamss.head; param = vdef.symbol) yield {
+        ValDef(param.cloneSymbol(symbol).setInfo(param.info.substSym(oldtparams, newtparams)))
+      })
+
+      // replace value and type parameters of the old method with the new ones
+      val symSubstituter = new ImplementationAdapter(
+        parameters(source).flatten ::: origtparams,
+        vparamss1.flatten.map(_.symbol) ::: newtparams,
+        source.enclClass,
+        false) // don't make private fields public
+      val tmp = symSubstituter(body(source).duplicate)
+      tpt.tpe = tpt.tpe.substSym(oldtparams, newtparams)
+
+      treeCopy.DefDef(tree, mods, name, tparams, vparamss1, tpt, tmp)
+    }
+
+    def warn(clazz: Symbol)(pos: Position, err: String) = 
+      if (!clazz.hasFlag(SPECIALIZED))
+        unit.warning(pos, err)
+
+    /** Create trees for specialized members of 'cls', based on the
+     *  symbols that are already there.
+     */
+    private def makeSpecializedMembers(cls: Symbol): List[Tree] = {
+      // add special overrides first
+//      if (!cls.hasFlag(SPECIALIZED))
+//        for (m <- specialOverrides(cls)) cls.info.decls.enter(m)
+      val mbrs = new mutable.ListBuffer[Tree]
+      var hasSpecializedFields = false
+
+      for (m <- cls.info.decls.toList 
+             if m.hasFlag(SPECIALIZED)
+                 && (m.sourceFile ne null)
+                 && satisfiable(typeEnv(m), warn(cls))) {
+        log("creating tree for " + m.fullName)
+        if (m.isMethod)  {
+          if (info(m).target.isGetterOrSetter) hasSpecializedFields = true
+          if (m.isClassConstructor) {
+            val origParamss = parameters(info(m).target)
+
+            val vparams = 
+              for ((tp, sym) <- m.info.paramTypes zip origParamss(0))
+                yield m.newValue(sym.pos, specializedName(sym, typeEnv(cls)))
+                       .setInfo(tp)
+                       .setFlag(sym.flags)
+
+            // param accessors for private members (the others are inherited from the generic class)
+            if (m.isPrimaryConstructor)
+              for (param <- vparams if cls.info.nonPrivateMember(param.name) == NoSymbol;
+                   val acc = param.cloneSymbol(cls).setFlag(PARAMACCESSOR | PRIVATE)) {
+                cls.info.decls.enter(acc)
+                mbrs += ValDef(acc, EmptyTree).setType(NoType).setPos(m.pos)
+              }
+            
+            // ctor
+            mbrs += atPos(m.pos)(DefDef(m, Modifiers(m.flags), List(vparams) map (_ map ValDef), EmptyTree))
+          } else {
+            mbrs += atPos(m.pos)(DefDef(m, { paramss => EmptyTree }))
+          }
+        } else if (m.isValue) {
+          mbrs += ValDef(m, EmptyTree).setType(NoType).setPos(m.pos)
+        } else if (m.isClass) {
+//           mbrs  +=
+//              ClassDef(m, Template(m.info.parents map TypeTree, emptyValDef, List())
+//                         .setSymbol(m.newLocalDummy(m.pos)))
+//            log("created synthetic class: " + m.fullName)
+        }
+      }
+      if (hasSpecializedFields) {
+        import definitions.BooleanClass
+
+        val isSpecializedInstance = cls.hasFlag(SPECIALIZED) || cls.info.parents.exists(_.typeSymbol.hasFlag(SPECIALIZED))
+        val sym = cls.newMethod(nme.SPECIALIZED_INSTANCE, cls.pos)
+                     .setInfo(MethodType(Nil, BooleanClass.tpe))
+        cls.info.decls.enter(sym)
+        mbrs += atPos(sym.pos) {
+          DefDef(sym, Literal(isSpecializedInstance).setType(BooleanClass.tpe)).setType(NoType)
+        }
+      }
+      mbrs.toList
+    }
+    
+    /** Create specialized class definitions */
+    def implSpecClasses(trees: List[Tree]): List[Tree] = {
+      val buf = new mutable.ListBuffer[Tree]
+      for (tree <- trees)
+        tree match {
+          case ClassDef(_, _, _, impl) =>
+            tree.symbol.info // force specialization
+            for (((sym1, env), specCls) <- specializedClass if sym1 == tree.symbol) {
+              val parents = specCls.info.parents.map(TypeTree)
+              buf +=
+                ClassDef(specCls, atPos(impl.pos)(Template(parents, emptyValDef, List()))
+                           .setSymbol(specCls.newLocalDummy(sym1.pos))) setPos tree.pos
+              log("created synthetic class: " + specCls + " of " + sym1 + " in env: " + env)
+            }
+          case _ =>
+        }
+      buf.toList
+    }
+  }
+  
+  private def forwardCall(pos: util.Position, receiver: Tree, paramss: List[List[ValDef]]): Tree = {
+    val argss = paramss map (_ map (x => Ident(x.symbol)))
+    atPos(pos) { (receiver /: argss) (Apply) }
+  }
+
+  private def forwardCtorCall(pos: util.Position, receiver: Tree, paramss: List[List[ValDef]], clazz: Symbol): Tree = {
+    val argss = paramss map (_ map (x =>
+      if (x.name.endsWith("$sp") && clazz.info.member(nme.originalName(x.name)).isPublic)
+        gen.mkAsInstanceOf(Literal(Constant(null)), x.symbol.tpe)
+      else
+        Ident(x.symbol))
+    )
+    atPos(pos) { (receiver /: argss) (Apply) }
+  }
+
+  /** Concrete methods that use a specialized type, or override such methods. */
+  private val concreteSpecMethods: mutable.Set[Symbol] = new mutable.HashSet
+  
+  /** Instantiate polymorphic function `target' with type parameters from `from'.
+   *  For each type parameter `tp' in `target', its argument is:
+   *    - a corresponding type parameter of `from', if tp is not bound in
+   *      typeEnv(from)
+   *    - the upper bound of tp, if the binding conflicts with tp's bounds
+   *    - typeEnv(from)(tp), if the binding is not conflicting in its bounds
+   */
+  private def makeTypeArguments(from: Symbol, target: Symbol): List[Type] = {
+    val owner = from.owner
+    val env = typeEnv(from)
+    for (tp <- owner.info.memberType(target).typeParams) 
+      yield 
+        if (!env.isDefinedAt(tp)) 
+          typeRef(NoPrefix, from.info.typeParams.find(_.name == tp.name).get, Nil)
+        else if ((env(tp) <:< tp.info.bounds.hi) && (tp.info.bounds.lo <:< env(tp))) 
+          env(tp)
+        else tp.info.bounds.hi
+  }
+
+  private def makeArguments(fun: Symbol, vparams: List[Symbol]): List[Tree] = {
+    def needsCast(tp1: Type, tp2: Type): Boolean = 
+      !(tp1 <:< tp2)
+    
+    //! TODO: make sure the param types are seen from the right prefix
+    for ((tp, arg) <- fun.info.paramTypes zip vparams) yield {
+      if (needsCast(arg.tpe, tp)) {
+        //log("tp: " + tp + " " + tp.typeSymbol.owner)
+        gen.mkAsInstanceOf(Ident(arg), tp)
+      } else Ident(arg)
+    }
+  }
+
+  private def findSpec(tp: Type): Type = tp match {
+    case TypeRef(pre, sym, args) =>
+      if (args.isEmpty) tp
+      else {
+        specializedType(tp)
+        /*log("looking for " + specializedName(sym.name, args) + " in " + pre)
+        val sym1 = pre.member(specializedName(sym.name, args))
+        assert(sym1 != NoSymbol, "pre: " + pre.typeSymbol + " ph: " + phase + " with: " + pre.members)
+        TypeRef(pre, sym1, Nil)*/
+      }
+    case _ => tp
+  }
+
+  class SpecializationTransformer(unit: CompilationUnit) extends Transformer {
+    informProgress("specializing " + unit)
+    override def transform(tree: Tree) =
+      if (settings.nospecialization.value) tree
+      else atPhase(phase.next) {
+        val res = specializeCalls(unit).transform(tree)
+        res
+      }
+  }
+  
+}
diff --git a/src/compiler/scala/tools/nsc/transform/TailCalls.scala b/src/compiler/scala/tools/nsc/transform/TailCalls.scala
index 7ad0d49..6088ca0 100644
--- a/src/compiler/scala/tools/nsc/transform/TailCalls.scala
+++ b/src/compiler/scala/tools/nsc/transform/TailCalls.scala
@@ -1,10 +1,10 @@
 /* NSC -- new scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author Iulian Dragos
  */
-// $Id: TailCalls.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.tools.nsc.transform
+package scala.tools.nsc
+package transform
 
 import scala.tools.nsc.symtab.Flags
 
@@ -20,7 +20,6 @@ abstract class TailCalls extends Transform
   import global._                  // the global environment
   import definitions._             // standard classes and methods
   import typer.{typed, atOwner}    // methods to type trees
-  import posAssigner.atPos         // for filling in tree positions 
 
   val phaseName: String = "tailcalls"
 
@@ -69,7 +68,7 @@ abstract class TailCalls extends Transform
    *   are optimized. Since 'this' is not a local variable, a dummy local val
    *   is added and used as a label parameter. The backend knows to load
    *   the corresponding argument in the 'this' (local at index 0). This dummy local
-   *   is never used and should be cleand up by dead code elmination (when enabled).
+   *   is never used and should be cleand up by dead code elimination (when enabled).
    * </p>
    * <p>
    *   This phase has been moved before pattern matching to catch more
@@ -101,6 +100,9 @@ abstract class TailCalls extends Transform
 
       /** Tells whether we are in a (possible) tail position */
       var tailPos = false
+      
+      /** The reason this method could not be optimized. */
+      var tailrecFailReason = "it contains a recursive call not in tail position"
 
       /** Is the label accessed? */
       var accessed = false
@@ -135,7 +137,8 @@ abstract class TailCalls extends Transform
       t
     }
 
-    private var ctx: Context = new Context()
+    private var ctx: Context      = new Context()
+    private def enclosingType     = ctx.currentMethod.enclClass.typeOfThis
 
     /** Rewrite this tree to contain no tail recursive calls */
     def transform(tree: Tree, nctx: Context): Tree = {
@@ -147,54 +150,101 @@ abstract class TailCalls extends Transform
     }
 
     override def transform(tree: Tree): Tree = {
+      /** A possibly polymorphic apply to be considered for tail call transformation.
+       */
+      def rewriteApply(target: Tree, fun: Tree, targs: List[Tree], args: List[Tree]) = {
+        def isRecursiveCall   = ctx.currentMethod eq fun.symbol
+        def isMandatory       = ctx.currentMethod hasAnnotation TailrecClass 
+        def isEligible        = ctx.currentMethod.isEffectivelyFinal             
+        def transformArgs     = transformTrees(args, mkContext(ctx, false))
+        def matchesTypeArgs   = ctx.tparams sameElements (targs map (_.tpe.typeSymbol))
+        def defaultTree       = treeCopy.Apply(tree, target, transformArgs)
+        
+        def sameTypeOfThis(receiver: Tree) =
+          receiver.tpe.widen =:= enclosingType.widen
+
+        /** Records failure reason in Context for reporting.
+         */
+        def cannotRewrite(reason: String) = {
+          if (isMandatory)
+            ctx.tailrecFailReason = reason
+            
+          defaultTree
+        }
+        def rewriteTailCall(receiver: Tree, otherArgs: List[Tree]): Tree = {
+          log("Rewriting tail recursive method call at: " + fun.pos)
+
+          ctx.accessed = true
+          typed { atPos(fun.pos)(Apply(Ident(ctx.label), receiver :: otherArgs)) }
+        }
+
+        if (!isRecursiveCall)           defaultTree
+        else if (!isEligible)           cannotRewrite("it is neither private nor final so can be overridden")
+        else if (!ctx.tailPos)          cannotRewrite("it contains a recursive call not in tail position")
+        else if (!matchesTypeArgs)      cannotRewrite("it is called recursively with different type arguments")
+        else fun match {
+          case Select(_, _) if forMSIL                  => cannotRewrite("it cannot be optimized on MSIL")
+          case Select(qual, _) if !sameTypeOfThis(qual) => cannotRewrite("it changes type of 'this' on a polymorphic recursive call")
+          case Select(qual, _)                          => rewriteTailCall(qual, transformArgs)
+          case _                                        => rewriteTailCall(This(currentClass), transformArgs)
+        }
+      }
+      
       tree match {
 
-        case DefDef(mods, name, tparams, vparams, tpt, rhs) =>
+        case dd @ DefDef(mods, name, tparams, vparams, tpt, rhs) =>
           log("Entering DefDef: " + name)
           val newCtx = mkContext(ctx)
           newCtx.currentMethod = tree.symbol
           newCtx.makeLabel()
-          newCtx.label.setInfo(MethodType(currentClass.tpe :: tree.symbol.tpe.paramTypes, tree.symbol.tpe.finalResultType))
+          val currentClassParam = tree.symbol.newSyntheticValueParam(currentClass.typeOfThis)
+          newCtx.label.setInfo(MethodType(currentClassParam :: tree.symbol.tpe.params, tree.symbol.tpe.finalResultType))
           newCtx.tailPos = true
 
-          val t1 = if (newCtx.currentMethod.isFinal ||
-                       newCtx.currentMethod.enclClass.hasFlag(Flags.MODULE)) {
+          val isEligible  = newCtx.currentMethod.isEffectivelyFinal
+          val isMandatory = dd.symbol.hasAnnotation(TailrecClass) && !forMSIL  // @tailrec annotation indicates mandatory transformation
+
+          if (isEligible) {            
             newCtx.tparams = Nil
             log("  Considering " + name + " for tailcalls")
             tree.symbol.tpe match {
               case PolyType(tpes, restpe) =>
                 newCtx.tparams = tparams map (_.symbol)
                 newCtx.label.setInfo(
-                  newCtx.label.tpe.substSym(tpes, tparams map (_.symbol)))
-              case _ => ()
+                newCtx.label.tpe.substSym(tpes, tparams map (_.symbol)))
+              case _ =>
             }
-
-            //println("label.tpe: " + newCtx.label.tpe)
-            var newRHS = transform(rhs, newCtx);
-            if (newCtx.accessed) {
-              log("Rewrote def " + newCtx.currentMethod)
-
-              val newThis = newCtx.currentMethod.newValue(tree.pos, nme.THIS)
-                 .setInfo(currentClass.tpe)
-                 .setFlag(Flags.SYNTHETIC)
-              newRHS =
-                  typed(atPos(tree.pos)(Block(List(
-                    ValDef(newThis, This(currentClass))),
-                    LabelDef(newCtx.label, 
-                             newThis :: (List.flatten(vparams) map (_.symbol)), 
-                             newRHS))));
-              copy.DefDef(tree, mods, name, tparams, vparams, tpt, newRHS);
-            } else
-              copy.DefDef(tree, mods, name, tparams, vparams, tpt, newRHS);
-          } else {
-            copy.DefDef(tree, mods, name, tparams, vparams, tpt, transform(rhs, newCtx))
           }
+          
+          val t1 = treeCopy.DefDef(tree, mods, name, tparams, vparams, tpt, {
+            val transformed = transform(rhs, newCtx)
+            
+            transformed match {
+              case newRHS if isEligible && newCtx.accessed =>
+                log("Rewrote def " + newCtx.currentMethod)                  
+                val newThis = newCtx.currentMethod
+                  . newValue (tree.pos, nme.THIS)
+                  . setInfo (currentClass.typeOfThis)
+                  . setFlag (Flags.SYNTHETIC)
+                
+                typed(atPos(tree.pos)(Block(
+                  List(ValDef(newThis, This(currentClass))),
+                  LabelDef(newCtx.label, newThis :: (vparams.flatten map (_.symbol)), newRHS)
+                )))              
+              case rhs =>
+                if (isMandatory)
+                  unit.error(dd.pos, "could not optimize @tailrec annotated method: " + newCtx.tailrecFailReason)
+                
+                rhs
+            }
+          })
+            
           log("Leaving DefDef: " + name)
           t1
 
         case EmptyTree => tree
 
-        case PackageDef(name, stats) =>
+        case PackageDef(_, _) =>
           super.transform(tree)
 
         case ClassDef(_, name, _, _) =>
@@ -210,15 +260,14 @@ abstract class TailCalls extends Transform
           super.transform(tree)
 
         case Block(stats, expr) =>
-          copy.Block(tree,
-                     transformTrees(stats, mkContext(ctx, false)),
-                     transform(expr))
+          treeCopy.Block(tree,
+                         transformTrees(stats, mkContext(ctx, false)),
+                         transform(expr))
 
         case CaseDef(pat, guard, body) =>
-          copy.CaseDef(tree, pat, guard, transform(body))
+          treeCopy.CaseDef(tree, pat, guard, transform(body))
 
-        case Sequence(_) | Alternative(_) |
-             Star(_)     | Bind(_, _) =>
+        case Alternative(_) | Star(_) | Bind(_, _) =>
           throw new RuntimeException("We should've never gotten inside a pattern")
 
         case Function(vparams, body) =>
@@ -229,67 +278,33 @@ abstract class TailCalls extends Transform
           super.transform(tree)
 
         case If(cond, thenp, elsep) =>
-          copy.If(tree, cond, transform(thenp), transform(elsep))
+          treeCopy.If(tree, cond, transform(thenp), transform(elsep))
 
         case Match(selector, cases) => //super.transform(tree);
-          copy.Match(tree, transform(selector, mkContext(ctx, false)), transformTrees(cases).asInstanceOf[List[CaseDef]])
+          treeCopy.Match(tree, transform(selector, mkContext(ctx, false)), transformTrees(cases).asInstanceOf[List[CaseDef]])
 
         case Return(expr) => super.transform(tree)
         case Try(block, catches, finalizer) => 
            // no calls inside a try are in tail position, but keep recursing for nested functions
-          copy.Try(tree, transform(block, mkContext(ctx, false)),
-                   transformTrees(catches, mkContext(ctx, false)).asInstanceOf[List[CaseDef]],
-                   transform(finalizer, mkContext(ctx, false)))
+          treeCopy.Try(tree, transform(block, mkContext(ctx, false)),
+                       transformTrees(catches, mkContext(ctx, false)).asInstanceOf[List[CaseDef]],
+                       transform(finalizer, mkContext(ctx, false)))
 
         case Throw(expr) => super.transform(tree)
         case New(tpt) => super.transform(tree)
         case Typed(expr, tpt) => super.transform(tree)
 
         case Apply(tapply @ TypeApply(fun, targs), vargs) =>
-          lazy val defaultTree = copy.Apply(tree, tapply, transformTrees(vargs, mkContext(ctx, false)))
-          if ( ctx.currentMethod.isFinal &&
-               ctx.tailPos &&
-               isSameTypes(ctx.tparams, targs map (_.tpe.typeSymbol)) &&
-               isRecursiveCall(fun)) {
-            fun match {
-              case Select(receiver, _) =>
-                val recTpe = receiver.tpe.widen
-                val enclTpe = ctx.currentMethod.enclClass.typeOfThis
-                // make sure the type of 'this' doesn't change through this polymorphic recursive call
-                if (!forMSIL && 
-                    (receiver.tpe.typeParams.isEmpty || 
-                      (receiver.tpe.widen == ctx.currentMethod.enclClass.typeOfThis))) 
-                  rewriteTailCall(fun, receiver :: transformTrees(vargs, mkContext(ctx, false))) 
-                else 
-                  defaultTree
-              case _ => rewriteTailCall(fun, This(currentClass) :: transformTrees(vargs, mkContext(ctx, false)))
-            }
-          } else
-            defaultTree
-
+          rewriteApply(tapply, fun, targs, vargs)
+          
         case TypeApply(fun, args) => 
           super.transform(tree)
-
-        case Apply(fun, args) if (fun.symbol == definitions.Boolean_or ||
-                                  fun.symbol == definitions.Boolean_and) =>
-          copy.Apply(tree, fun, transformTrees(args))
-          
+        
         case Apply(fun, args) =>
-          lazy val defaultTree = copy.Apply(tree, fun, transformTrees(args, mkContext(ctx, false)))
-          if (ctx.currentMethod.isFinal && 
-              ctx.tailPos && 
-              isRecursiveCall(fun)) {
-            fun match {
-              case Select(receiver, _) =>
-                if (!forMSIL) 
-                  rewriteTailCall(fun, receiver :: transformTrees(args, mkContext(ctx, false))) 
-                else 
-                  defaultTree
-              case _ => rewriteTailCall(fun, This(currentClass) :: transformTrees(args, mkContext(ctx, false)))
-            }
-          } else
-            defaultTree
-            
+          if (fun.symbol == Boolean_or || fun.symbol == Boolean_and)
+            treeCopy.Apply(tree, fun, transformTrees(args))
+          else
+            rewriteApply(fun, fun, Nil, args)
 
         case Super(qual, mix) =>
           tree
@@ -310,33 +325,5 @@ abstract class TailCalls extends Transform
 
     def transformTrees(trees: List[Tree], nctx: Context): List[Tree] =
       trees map ((tree) => transform(tree, nctx))
-
-    private def rewriteTailCall(fun: Tree, args: List[Tree]): Tree = {
-      log("Rewriting tail recursive method call at: " +
-                      (fun.pos))
-      ctx.accessed = true
-      //println("fun: " + fun + " args: " + args)
-      val t = atPos(fun.pos)(Apply(Ident(ctx.label), args))
-      //println(t)
-      typed(t)
-    }
-
-    private def isSameTypes(ts1: List[Symbol], ts2: List[Symbol]): Boolean = {
-      def isSameType(t1: Symbol, t2: Symbol) = {
-        t1 == t2
-      }
-      List.forall2(ts1, ts2)(isSameType)
-    }
-
-    /** Returns <code>true</code> if the fun tree refers to the same method as
-     *  the one saved in <code>ctx</code>.
-     * 
-     *  @param fun the expression that is applied
-     *  @return    <code>true</code> if the tree symbol refers to the innermost 
-     *             enclosing method
-     */
-    private def isRecursiveCall(fun: Tree): Boolean =
-      (fun.symbol eq ctx.currentMethod)
   }
-
 }
diff --git a/src/compiler/scala/tools/nsc/transform/Transform.scala b/src/compiler/scala/tools/nsc/transform/Transform.scala
index c2c5938..2fc3eee 100644
--- a/src/compiler/scala/tools/nsc/transform/Transform.scala
+++ b/src/compiler/scala/tools/nsc/transform/Transform.scala
@@ -1,10 +1,10 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author Martin Odersky
  */
-// $Id: Transform.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.tools.nsc.transform
+package scala.tools.nsc
+package transform
 
 /** <p>
  *    A base class for transforms.
diff --git a/src/compiler/scala/tools/nsc/transform/TypingTransformers.scala b/src/compiler/scala/tools/nsc/transform/TypingTransformers.scala
index f6afa66..b091706 100644
--- a/src/compiler/scala/tools/nsc/transform/TypingTransformers.scala
+++ b/src/compiler/scala/tools/nsc/transform/TypingTransformers.scala
@@ -1,10 +1,10 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author Martin Odersky
  */
-// $Id: TypingTransformers.scala 16881 2009-01-09 16:28:11Z cunei $
 
-package scala.tools.nsc.transform
+package scala.tools.nsc
+package transform
 
 import scala.collection.mutable.{Map, HashMap}
 
@@ -17,18 +17,23 @@ trait TypingTransformers {
   import global._
 
   abstract class TypingTransformer(unit: CompilationUnit) extends Transformer {
-    var localTyper: analyzer.Typer = analyzer.newTyper(
-      analyzer.rootContext(unit, EmptyTree, true))
+    var localTyper: analyzer.Typer =
+      if (phase.erasedTypes)
+        erasure.newTyper(erasure.rootContext(unit, EmptyTree, true)).asInstanceOf[analyzer.Typer]
+      else
+        analyzer.newTyper(analyzer.rootContext(unit, EmptyTree, true))
     protected var curTree: Tree = _
+    protected def typedPos(pos: Position)(tree: Tree) = localTyper typed { atPos(pos)(tree) }
 
     /** a typer for each enclosing class */
-    var typers: Map[Symbol, analyzer.Typer] = new HashMap
+    val typers: Map[Symbol, analyzer.Typer] = new HashMap
     
     override def atOwner[A](owner: Symbol)(trans: => A): A = atOwner(curTree, owner)(trans)
 
     def atOwner[A](tree: Tree, owner: Symbol)(trans: => A): A = {
       val savedLocalTyper = localTyper
-      localTyper = localTyper.atOwner(tree, owner)
+//      println("transformer atOwner: " + owner + " isPackage? " + owner.isPackage)
+      localTyper = localTyper.atOwner(tree, if (owner.isModule) owner.moduleClass else owner)
       typers += Pair(owner, localTyper)
       val result = super.atOwner(owner)(trans)
       localTyper = savedLocalTyper
@@ -42,6 +47,8 @@ trait TypingTransformers {
         case Template(_, _, _) =>
           // enter template into context chain
           atOwner(currentOwner) { super.transform(tree) }
+        case PackageDef(_, _) =>
+          atOwner(tree.symbol) { super.transform(tree) }
         case _ =>
           super.transform(tree)
       }
diff --git a/src/compiler/scala/tools/nsc/transform/UnCurry.scala b/src/compiler/scala/tools/nsc/transform/UnCurry.scala
index 9a56b4f..c6e3597 100644
--- a/src/compiler/scala/tools/nsc/transform/UnCurry.scala
+++ b/src/compiler/scala/tools/nsc/transform/UnCurry.scala
@@ -1,14 +1,13 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author
  */
-// $Id: UnCurry.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.tools.nsc.transform
+package scala.tools.nsc
+package transform
 
 import symtab.Flags._
 import scala.collection.mutable.{HashMap, HashSet}
-import scala.tools.nsc.util.Position
 
 /*<export>*/
 /** - uncurry all symbol and tree types (@see UnCurryPhase)
@@ -21,11 +20,15 @@ import scala.tools.nsc.util.Position
  *  - for every argument to a def parameter `x: => T': 
  *      if argument is not a reference to a def parameter:
  *        convert argument `e' to (expansion of) `() => e'
- *  - for every repeated parameter `x: T*' --> x: Seq[T].
- *  - for every argument list that corresponds to a repeated parameter
+ *  - for every repeated Scala parameter `x: T*' --> x: Seq[T].
+ *  - for every repeated Java parameter `x: T...' --> x: Array[T], except:
+ *    if T is an unbounded abstract type, replace --> x: Array[Object]
+ *  - for every argument list that corresponds to a repeated Scala parameter
  *       (a_1, ..., a_n) => (Seq(a_1, ..., a_n))
+ *  - for every argument list that corresponds to a repeated Java parameter
+ *       (a_1, ..., a_n) => (Array(a_1, ..., a_n))
  *  - for every argument list that is an escaped sequence
- *       (a_1:_*) => (a_1)g
+ *       (a_1:_*) => (a_1) (possibly converted to sequence or array, as needed)
  *  - convert implicit method types to method types
  *  - convert non-trivial catches in try statements to matches
  *  - convert non-local returns to throws with enclosing try statements.
@@ -34,7 +37,6 @@ import scala.tools.nsc.util.Position
 abstract class UnCurry extends InfoTransform with TypingTransformers {
   import global._                  // the global environment
   import definitions._             // standard classes and methods
-  import posAssigner.atPos         // for filling in tree positions 
 
   val phaseName: String = "uncurry"
 
@@ -43,39 +45,63 @@ abstract class UnCurry extends InfoTransform with TypingTransformers {
 
 // ------ Type transformation --------------------------------------------------------
 
-//@MAT: uncurry and uncurryType fully expand type aliases in their input and output
-// note: don't normalize higher-kined types -- @M TODO: maybe split those uses of normalize? 
-// OTOH, should be a problem as calls to normalize only occur on types with kind * in principle (in well-typed programs)
+// uncurry and uncurryType expand type aliases
   private def expandAlias(tp: Type): Type = if (!tp.isHigherKinded) tp.normalize else tp
+
+  private def isUnboundedGeneric(tp: Type) = tp match {
+    case t @ TypeRef(_, sym, _) => sym.isAbstractType && !(t <:< AnyRefClass.tpe) 
+    case _ => false
+  }
   
   private val uncurry: TypeMap = new TypeMap {
     def apply(tp0: Type): Type = {
       val tp = expandAlias(tp0)
       tp match {
-        case MethodType(formals, MethodType(formals1, restpe)) =>
-          apply(MethodType(formals ::: formals1, restpe))
-        case MethodType(formals, ExistentialType(tparams, restpe @ MethodType(_, _))) =>
-          assert(false, "unexpected curried method types with intervening exitential") 
+        case MethodType(params, MethodType(params1, restpe)) =>
+          apply(MethodType(params ::: params1, restpe))
+        case MethodType(params, ExistentialType(tparams, restpe @ MethodType(_, _))) =>
+          assert(false, "unexpected curried method types with intervening existential") 
           tp0
-        case mt: ImplicitMethodType =>
-          apply(MethodType(mt.paramTypes, mt.resultType))
-        case PolyType(List(), restpe) =>
+        case MethodType(h :: t, restpe) if h.isImplicit =>
+          apply(MethodType(h.cloneSymbol.resetFlag(IMPLICIT) :: t, restpe))
+        case PolyType(List(), restpe) => // nullary method type
           apply(MethodType(List(), restpe))
-        case PolyType(tparams, restpe) =>
+        case PolyType(tparams, restpe) => // polymorphic nullary method type, since it didn't occur in a higher-kinded position
           PolyType(tparams, apply(MethodType(List(), restpe)))
-        /*
-         case TypeRef(pre, sym, List(arg1, arg2)) if (arg1.typeSymbol == ByNameParamClass) =>
-         assert(sym == FunctionClass(1))
-         apply(typeRef(pre, definitions.ByNameFunctionClass, List(expandAlias(arg1.typeArgs(0)), arg2)))
-         */
-        case TypeRef(pre, sym, List(arg)) if (sym == ByNameParamClass) =>
+        case TypeRef(pre, ByNameParamClass, List(arg)) =>
           apply(functionType(List(), arg))
-        case TypeRef(pre, sym, args) if (sym == RepeatedParamClass) =>
-          apply(rawTypeRef(pre, SeqClass, args))
+        case TypeRef(pre, RepeatedParamClass, args) =>
+          apply(appliedType(SeqClass.typeConstructor, args))
+        case TypeRef(pre, JavaRepeatedParamClass, args) =>
+          apply(arrayType(
+            if (isUnboundedGeneric(args.head)) ObjectClass.tpe else args.head))
         case _ =>
           expandAlias(mapOver(tp))
       }
     }
+
+//@M TODO: better fix for the gross hack that conflates polymorphic nullary method types with type functions
+// `[tpars] tref` (PolyType(tpars, tref)) could uncurry to either:
+//   - `[tpars]() tref` (PolyType(tpars, MethodType(List(), tref)) 
+//         a nullary method types uncurry to a method with an empty argument list
+//   - `[tpars] tref`   (PolyType(tpars, tref))
+//         a proper type function -- see mapOverArgs: can only occur in args of TypeRef (right?))
+// the issue comes up when a partial type application gets normalised to a polytype, like `[A] Function1[X, A]`
+// should not apply the uncurry transform to such a type
+// see #2594 for an example
+
+    // decide whether PolyType represents a nullary method type (only if type has kind *)
+    // for higher-kinded types, leave PolyType intact
+    override def mapOverArgs(args: List[Type], tparams: List[Symbol]): List[Type] =
+      map2Conserve(args, tparams) { (arg, tparam) =>
+        arg match {
+          // is this a higher-kinded position? (TODO: confirm this is the only case)
+          case PolyType(tparams, restpe) if tparam.typeParams.nonEmpty =>  // higher-kinded type param
+            PolyType(tparams, apply(restpe)) // could not be a nullary method type
+          case _ =>
+            this(arg)
+        }
+      }
   }
 
   private val uncurryType = new TypeMap {
@@ -83,7 +109,7 @@ abstract class UnCurry extends InfoTransform with TypingTransformers {
       val tp = expandAlias(tp0)
       tp match {
         case ClassInfoType(parents, decls, clazz) =>
-          val parents1 = List.mapConserve(parents)(uncurry)
+          val parents1 = parents mapConserve (uncurry)
           if (parents1 eq parents) tp
           else ClassInfoType(parents1, decls, clazz) // @MAT normalize in decls??
         case PolyType(_, _) =>
@@ -94,31 +120,13 @@ abstract class UnCurry extends InfoTransform with TypingTransformers {
     }
   }
 
-  /** Convert repeated parameters to arrays if they occur as part of a Java method 
-   */
-  private def repeatedToArray(tp: Type): Type = tp match {
-    case MethodType(formals, rtpe) 
-    if (!formals.isEmpty && formals.last.typeSymbol == RepeatedParamClass) =>
-      MethodType(formals.init ::: 
-                 List(appliedType(ArrayClass.typeConstructor, List(formals.last.typeArgs.head))),
-                 rtpe)
-    case PolyType(tparams, rtpe) =>
-      val rtpe1 = repeatedToArray(rtpe)
-      if (rtpe1 eq rtpe) tp
-      else PolyType(tparams, rtpe1)
-    case _ =>
-      tp
-  }
-  
   /** - return symbol's transformed type, 
    *  - if symbol is a def parameter with transformed type T, return () => T
    *
    * @MAT: starting with this phase, the info of every symbol will be normalized
    */
   def transformInfo(sym: Symbol, tp: Type): Type = 
-    if (sym.isType) uncurryType(tp) 
-    else if (sym.isMethod && sym.hasFlag(JAVA)) uncurry(repeatedToArray(tp))
-    else uncurry(tp)
+    if (sym.isType) uncurryType(tp) else uncurry(tp)
 
   /** Traverse tree omitting local method definitions.
    *  If a `return' is encountered, set `returnFound' to true.
@@ -151,15 +159,21 @@ abstract class UnCurry extends InfoTransform with TypingTransformers {
       freeLocalsTraverser(unit.body)
       unit.body = transform(unit.body)
     }
+
+    private var nprinted = 0
+
     override def transform(tree: Tree): Tree = try { //debug
       postTransform(mainTransform(tree))
     } catch {
       case ex: Throwable =>
-        Console.println("exception when traversing " + tree)
+        if (nprinted < 10) {
+          Console.println("exception when traversing " + tree)
+          nprinted += 1
+        }
         throw ex
     }
 
-    /* Is tree a reference `x' to a call by name parameter that neeeds to be converted to 
+    /* Is tree a reference `x' to a call by name parameter that needs to be converted to 
      * x.apply()? Note that this is not the case if `x' is used as an argument to another
      * call by name parameter.
      */
@@ -173,8 +187,8 @@ abstract class UnCurry extends InfoTransform with TypingTransformers {
      *  additional parameter sections of a case class are skipped.
      */
     def uncurryTreeType(tp: Type): Type = tp match {
-      case MethodType(formals, MethodType(formals1, restpe)) if (inPattern) =>
-        uncurryTreeType(MethodType(formals, restpe))
+      case MethodType(params, MethodType(params1, restpe)) if (inPattern) =>
+        uncurryTreeType(MethodType(params, restpe))
       case _ =>
         uncurry(tp)
     }
@@ -183,7 +197,7 @@ abstract class UnCurry extends InfoTransform with TypingTransformers {
 
     /** The type of a non-local return expression with given argument type */
     private def nonLocalReturnExceptionType(argtype: Type) =
-      appliedType(NonLocalReturnExceptionClass.typeConstructor, List(argtype))
+      appliedType(NonLocalReturnControlClass.typeConstructor, List(argtype))
 
     /** A hashmap from method symbols to non-local return keys */
     private val nonLocalReturnKeys = new HashMap[Symbol, Symbol]
@@ -201,7 +215,9 @@ abstract class UnCurry extends InfoTransform with TypingTransformers {
     /** Generate a non-local return throw with given return expression from given method.
      *  I.e. for the method's non-local return key, generate:
      *
-     *    throw new NonLocalReturnException(key, expr)
+     *    throw new NonLocalReturnControl(key, expr)
+     *  todo: maybe clone a pre-existing exception instead?
+     *  (but what to do about exceptions that miss their targets?)
      */
     private def nonLocalReturnThrow(expr: Tree, meth: Symbol) =
       localTyper.typed {
@@ -218,7 +234,7 @@ abstract class UnCurry extends InfoTransform with TypingTransformers {
      *    try { 
      *      body 
      *    } catch {
-     *      case ex: NonLocalReturnException[_] => 
+     *      case ex: NonLocalReturnControl[_] => 
      *        if (ex.key().eq(key)) ex.value()
      *        else throw ex
      *    }
@@ -230,7 +246,7 @@ abstract class UnCurry extends InfoTransform with TypingTransformers {
         val ex = meth.newValue(body.pos, nme.ex) setInfo extpe
         val pat = Bind(ex, 
                        Typed(Ident(nme.WILDCARD), 
-                             AppliedTypeTree(Ident(NonLocalReturnExceptionClass),
+                             AppliedTypeTree(Ident(NonLocalReturnControlClass),
                                              List(Bind(nme.WILDCARD.toTypeName,
                                                        EmptyTree)))))
         val rhs =
@@ -279,11 +295,11 @@ abstract class UnCurry extends InfoTransform with TypingTransformers {
      *    new $anon()
      *
      *  transform a function node (x => body) of type PartialFunction[T, R] where
-     *    body = x match { case P_i if G_i => E_i }_i=1..n
+     *    body = expr match { case P_i if G_i => E_i }_i=1..n
      *  to:
      *
      *    class $anon() extends Object() with PartialFunction[T, R] with ScalaObject {
-     *      def apply(x: T): R = (x: @unchecked) match {
+     *      def apply(x: T): R = (expr: @unchecked) match {
      *        { case P_i if G_i => E_i }_i=1..n
      *      def isDefinedAt(x: T): boolean = (x: @unchecked) match {
      *        case P_1 if G_1 => true
@@ -300,118 +316,182 @@ abstract class UnCurry extends InfoTransform with TypingTransformers {
      */
     def transformFunction(fun: Function): Tree = {
       val fun1 = deEta(fun)
+      def owner = fun.symbol.owner
+      def targs = fun.tpe.typeArgs
+      def isPartial = fun.tpe.typeSymbol == PartialFunctionClass
+      
       if (fun1 ne fun) fun1
       else {
-        val anonClass = fun.symbol.owner.newAnonymousFunctionClass(fun.pos) 
-          .setFlag(FINAL | SYNTHETIC | inConstructorFlag)
-        val formals = fun.tpe.typeArgs.init
-        val restpe = fun.tpe.typeArgs.last
-        anonClass setInfo ClassInfoType(
-          List(ObjectClass.tpe, fun.tpe, ScalaObjectClass.tpe), newScope, anonClass);
-        val applyMethod = anonClass.newMethod(fun.pos, nme.apply)
-          .setFlag(FINAL).setInfo(MethodType(formals, restpe));
-        anonClass.info.decls enter applyMethod;
-        for (vparam <- fun.vparams) vparam.symbol.owner = applyMethod;
-        new ChangeOwnerTraverser(fun.symbol, applyMethod).traverse(fun.body);
-        def applyMethodDef(body: Tree) = 
-          DefDef(Modifiers(FINAL), nme.apply, List(), List(fun.vparams), TypeTree(restpe), body)
-            .setSymbol(applyMethod)
-/*
-        def toStringMethodDefs = fun match {
-          case etaExpansion(_, fn, _) if (fn.hasSymbol) => 
-            List(
-              DefDef(Modifiers(FINAL | OVERRIDE), nme.toString_, List(), List(List()), TypeTree(StringClass.tpe), 
-                     Literal(fn.symbol.name)))
-          case _ =>
-            List()
+        val (formals, restpe) = (targs.init, targs.last)
+        val anonClass = owner newAnonymousFunctionClass fun.pos setFlag (FINAL | SYNTHETIC | inConstructorFlag)
+        def parents =
+          if (isFunctionType(fun.tpe)) List(abstractFunctionForFunctionType(fun.tpe))
+          else List(ObjectClass.tpe, fun.tpe)
+          
+        anonClass setInfo ClassInfoType(parents, new Scope, anonClass)
+        val applyMethod = anonClass.newMethod(fun.pos, nme.apply) setFlag FINAL
+        applyMethod setInfo MethodType(applyMethod newSyntheticValueParams formals, restpe)
+        anonClass.info.decls enter applyMethod
+        
+        fun.vparams foreach (_.symbol.owner = applyMethod)
+        new ChangeOwnerTraverser(fun.symbol, applyMethod) traverse fun.body
+
+        def mkUnchecked(tree: Tree) = {
+          def newUnchecked(expr: Tree) = Annotated(New(gen.scalaDot(UncheckedClass.name), List(Nil)), expr)
+          tree match {
+            case Match(selector, cases) => atPos(tree.pos) { Match(newUnchecked(selector), cases) }
+            case _                      => tree
+          }
         }
-*/
-        def mkUnchecked(tree: Tree) = tree match {
-          case Match(selector, cases) =>
-            atPos(tree.pos) {
-              Match(
-                Annotated(Annotation(New(TypeTree(UncheckedClass.tpe), List(List())), List()), selector),
-                cases)
-            }
-          case _ =>
-            tree
+        
+        def applyMethodDef() = {
+          val body = if (isPartial) mkUnchecked(fun.body) else fun.body
+          DefDef(Modifiers(FINAL), nme.apply, Nil, List(fun.vparams), TypeTree(restpe), body) setSymbol applyMethod
         }
-        val members = {
-          if (fun.tpe.typeSymbol == PartialFunctionClass) {
-            val isDefinedAtMethod = anonClass.newMethod(fun.pos, nme.isDefinedAt)
-              .setFlag(FINAL).setInfo(MethodType(formals, BooleanClass.tpe))
-            anonClass.info.decls enter isDefinedAtMethod
-            def idbody(idparam: Symbol) = fun.body match {
-              case Match(_, cases) =>
-                val substParam = new TreeSymSubstituter(List(fun.vparams.head.symbol), List(idparam));
-                def transformCase(cdef: CaseDef): CaseDef =
-                  substParam(
-                    resetAttrs(
-                      CaseDef(cdef.pat.duplicate, cdef.guard.duplicate, Literal(true))))
-                if (cases exists treeInfo.isDefaultCase) Literal(true)
-                else 
-                  Match(
-                    Ident(idparam),
-                    (cases map transformCase) ::: 
-                      List(CaseDef(Ident(nme.WILDCARD), EmptyTree, Literal(false))))
-            }
-            List(applyMethodDef(mkUnchecked(fun.body)),
-                 DefDef(isDefinedAtMethod, vparamss => mkUnchecked(idbody(vparamss.head.head))))
-          } else {
-            List(applyMethodDef(fun.body))
-          } 
-        } /* ::: toStringMethodDefs */
+        def isDefinedAtMethodDef() = {
+          val m = anonClass.newMethod(fun.pos, nme.isDefinedAt) setFlag FINAL
+          m setInfo MethodType(m newSyntheticValueParams formals, BooleanClass.tpe)
+          anonClass.info.decls enter m
+          
+          val Match(selector, cases) = fun.body
+          val vparam = fun.vparams.head.symbol
+          val idparam = m.paramss.head.head
+          val substParam = new TreeSymSubstituter(List(vparam), List(idparam))
+          def substTree[T <: Tree](t: T): T = substParam(resetLocalAttrs(t))
+          
+          def transformCase(cdef: CaseDef): CaseDef =
+            substTree(CaseDef(cdef.pat.duplicate, cdef.guard.duplicate, Literal(true)))
+          def defaultCase = CaseDef(Ident(nme.WILDCARD), EmptyTree, Literal(false))
+          
+          DefDef(m, mkUnchecked(
+            if (cases exists treeInfo.isDefaultCase) Literal(true)
+            else Match(substTree(selector.duplicate), (cases map transformCase) ::: List(defaultCase))
+          ))
+        }
+          
+        val members =
+          if (isPartial) List(applyMethodDef, isDefinedAtMethodDef)
+          else List(applyMethodDef)
+
         localTyper.typed {
           atPos(fun.pos) {
             Block(
-              List(ClassDef(anonClass, NoMods, List(List()), List(List()), members)),
+              List(ClassDef(anonClass, NoMods, List(List()), List(List()), members, fun.pos)),
               Typed(
                 New(TypeTree(anonClass.tpe), List(List())),
                 TypeTree(fun.tpe)))
-            
           }
         }
       }
     }
+ 
+    def transformArgs(pos: Position, fun: Symbol, args: List[Tree], formals: List[Type]) = {
+      val isJava = fun hasFlag JAVA
+      val args1 = formals.lastOption match {
+        case Some(lastFormal) if isRepeatedParamType(lastFormal) =>
+
+          def mkArrayValue(ts: List[Tree], elemtp: Type) =
+            ArrayValue(TypeTree(elemtp), ts) setType arrayType(elemtp)
+
+          // when calling into scala varargs, make sure it's a sequence.
+          def arrayToSequence(tree: Tree, elemtp: Type) = {
+            atPhase(phase.next) {
+              localTyper.typedPos(pos) {
+                val predef = gen.mkAttributedRef(PredefModule)
+                val meth = 
+                  if ((elemtp <:< AnyRefClass.tpe) && !isPhantomClass(elemtp.typeSymbol))
+                    TypeApply(Select(predef, "wrapRefArray"), List(TypeTree(elemtp)))
+                  else if (isValueClass(elemtp.typeSymbol))
+                    Select(predef, "wrap"+elemtp.typeSymbol.name+"Array")
+                  else
+                    TypeApply(Select(predef, "genericWrapArray"), List(TypeTree(elemtp)))
+                val pt = arrayType(elemtp)
+                val adaptedTree = // might need to cast to Array[elemtp], as arrays are not covariant
+                  if (tree.tpe <:< pt) tree
+                  else gen.mkCast(
+                    if (elemtp.typeSymbol == AnyClass && isValueClass(tree.tpe.typeArgs.head.typeSymbol))
+                      gen.mkRuntimeCall("toObjectArray", List(tree))
+                    else 
+                      tree,
+                    arrayType(elemtp))
+                Apply(meth, List(adaptedTree))
+              }
+            } 
+          }
 
-    def transformArgs(pos: Position, args: List[Tree], formals: List[Type]) = {
-      if (formals.isEmpty) {
-        assert(args.isEmpty); List()
-      } else {
-        val args1 =
-          formals.last match {
-            case TypeRef(pre, sym, List(elempt)) if (sym == RepeatedParamClass) =>
-              def mkArrayValue(ts: List[Tree]) =
-                atPos(pos)(ArrayValue(TypeTree(elempt), ts) setType formals.last);
-
-              if (args.isEmpty)
-                List(mkArrayValue(args))
-              else {
-                val suffix: Tree = args.last match {
-                  case Typed(arg, Ident(name)) if name == nme.WILDCARD_STAR.toTypeName =>
-                    arg /*setType seqType(arg.tpe)*/
-                  case _ => 
-                    mkArrayValue(args.drop(formals.length - 1))
-                }
-                args.take(formals.length - 1) ::: List(suffix)
+          // when calling into java varargs, make sure it's an array - see bug #1360
+          def sequenceToArray(tree: Tree) = {
+            val toArraySym = tree.tpe member nme.toArray
+            assert(toArraySym != NoSymbol)
+            def getManifest(tp: Type): Tree = {
+              val manifestOpt = localTyper.findManifest(tp, false)
+              if (!manifestOpt.tree.isEmpty) manifestOpt.tree
+              else if (tp.bounds.hi ne tp) getManifest(tp.bounds.hi)
+              else localTyper.getManifestTree(tree.pos, tp, false)
+            }
+            atPhase(phase.next) {
+              localTyper.typedPos(pos) {
+                Apply(gen.mkAttributedSelect(tree, toArraySym), List(getManifest(tree.tpe.typeArgs.head)))
               }
-            case _ => args
+            }
           }
-        List.map2(formals, args1) { (formal, arg) =>
-          if (formal.typeSymbol != ByNameParamClass) {
-            arg
-          } else if (isByNameRef(arg)) {
-            byNameArgs.addEntry(arg)
-            arg setType functionType(List(), arg.tpe)
-          } else {
-            val fun = localTyper.typed(
-              Function(List(), arg) setPos arg.pos).asInstanceOf[Function];
-            new ChangeOwnerTraverser(currentOwner, fun.symbol).traverse(arg);
-            transformFunction(fun)
+
+          val lastElemType = lastFormal.typeArgs.head
+          var suffix: Tree =
+            if (!args.isEmpty && (treeInfo isWildcardStarArg args.last)) {
+              val Typed(tree, _) = args.last; 
+              if (isJava)
+                if (tree.tpe.typeSymbol == ArrayClass) tree
+                else sequenceToArray(tree)
+              else 
+                if (tree.tpe.typeSymbol isSubClass TraversableClass) tree
+                else arrayToSequence(tree, lastElemType)
+            } else {
+              val tree = mkArrayValue(args drop (formals.length - 1), lastElemType)
+              if (isJava || inPattern) tree
+              else arrayToSequence(tree, lastElemType)
+            }
+
+          atPhase(phase.next) {
+            if (isJava && 
+                suffix.tpe.typeSymbol == ArrayClass &&
+                isValueClass(suffix.tpe.typeArgs.head.typeSymbol) &&
+                { val lastFormal2 = fun.tpe.params.last.tpe
+                  lastFormal2.typeSymbol == ArrayClass &&
+                  lastFormal2.typeArgs.head.typeSymbol == ObjectClass
+                })
+              suffix = localTyper.typedPos(pos) {
+                gen.mkRuntimeCall("toObjectArray", List(suffix))
+              }
           }
+          args.take(formals.length - 1) ::: List(suffix setType lastFormal)
+        case _ =>
+          args
+      }
+      (formals, args1).zipped map { (formal, arg) =>
+        if (formal.typeSymbol != ByNameParamClass) {
+          arg
+        } else if (isByNameRef(arg)) {
+          byNameArgs.addEntry(arg)
+          arg setType functionType(List(), arg.tpe)
+        } else {
+          val fun = localTyper.typed(
+            Function(List(), arg) setPos arg.pos).asInstanceOf[Function];
+          new ChangeOwnerTraverser(currentOwner, fun.symbol).traverse(arg);
+          transformFunction(fun)
         }
       }
     }
+    
+    /** For removing calls to specially designated methods.
+     */  
+    def elideIntoUnit(tree: Tree): Tree = Literal(()) setPos tree.pos setType UnitClass.tpe
+    def isElidable(tree: Tree) = {
+      val sym = tree.symbol
+      // XXX settings.noassertions.value temporarily retained to avoid
+      // breakage until a reasonable interface is settled upon.
+      sym != null && sym.elisionLevel.exists(x => x < settings.elidebelow.value || settings.noassertions.value)
+    }
 
 // ------ The tree transformers --------------------------------------------------------
 
@@ -429,7 +509,7 @@ abstract class UnCurry extends InfoTransform with TypingTransformers {
        *  return statements. These are disallowed in the CLR. By lifting
        *  such returns will be converted to throws.
        */
-      def shouldBeLiftedAnyway(tree: Tree) =
+      def shouldBeLiftedAnyway(tree: Tree) = false && // buggy, see #1981
         forMSIL && lookForReturns.found(tree)
 
       /** Transform tree `t' to { def f = t; f } where `f' is a fresh name
@@ -469,9 +549,9 @@ abstract class UnCurry extends InfoTransform with TypingTransformers {
                     val rest = stats drop presupers.length
                     val supercalls = rest take 1 map transformInConstructor
                     val others = rest drop 1 map transform
-                    copy.Block(rhs, presupers ::: supercalls ::: others, transform(expr))
+                    treeCopy.Block(rhs, presupers ::: supercalls ::: others, transform(expr))
                 }
-                copy.DefDef(
+                treeCopy.DefDef(
                   tree, mods, name, transformTypeDefs(tparams),
                   transformValDefss(vparamss), transform(tpt), rhs1)
               }
@@ -509,28 +589,23 @@ abstract class UnCurry extends InfoTransform with TypingTransformers {
           inPattern = false
           val fn1 = transform(fn)
           inPattern = true
-          val args1 = transformTrees(
-            if (fn.symbol.name == nme.unapply)
-              args
-            else if (fn.symbol.name == nme.unapplySeq)
-              transformArgs(tree.pos, args, analyzer.unapplyTypeListFromReturnTypeSeq(fn.tpe))
-            else { assert(false,"internal error: UnApply node has wrong symbol"); null })
-          copy.UnApply(tree, fn1, args1)
+          val args1 = transformTrees(fn.symbol.name match {
+            case nme.unapply    => args
+            case nme.unapplySeq => transformArgs(tree.pos, fn.symbol, args, analyzer.unapplyTypeListFromReturnTypeSeq(fn.tpe))
+            case _              => Predef.error("internal error: UnApply node has wrong symbol")
+          })
+          treeCopy.UnApply(tree, fn1, args1)
 
         case Apply(fn, args) =>
-          if (settings.noassertions.value &&
-              (fn.symbol ne null) &&
-              (fn.symbol.name == nme.assert_ || fn.symbol.name == nme.assume_) &&
-              fn.symbol.owner == PredefModule.moduleClass) {
-            Literal(()).setPos(tree.pos).setType(UnitClass.tpe)
-          } else if (fn.symbol == Object_synchronized && shouldBeLiftedAnyway(args.head)) {
-            transform(copy.Apply(tree, fn, List(liftTree(args.head))))
-          } else {
+          if (isElidable(fn))
+            elideIntoUnit(tree)
+          else if (fn.symbol == Object_synchronized && shouldBeLiftedAnyway(args.head))
+            transform(treeCopy.Apply(tree, fn, List(liftTree(args.head))))
+          else
             withNeedLift(true) {
-              val formals = fn.tpe.paramTypes;
-              copy.Apply(tree, transform(fn), transformTrees(transformArgs(tree.pos, args, formals)))
+              val formals = fn.tpe.paramTypes
+              treeCopy.Apply(tree, transform(fn), transformTrees(transformArgs(tree.pos, fn.symbol, args, formals)))
             }
-          }
 
         case Assign(Select(_, _), _) =>
           withNeedLift(true) { super.transform(tree) }
@@ -545,7 +620,7 @@ abstract class UnCurry extends InfoTransform with TypingTransformers {
           inPattern = true
           val pat1 = transform(pat)
           inPattern = false
-          copy.CaseDef(tree, pat1, transform(guard), transform(body))
+          treeCopy.CaseDef(tree, pat1, transform(guard), transform(body))
 
         case fun @ Function(_, _) =>
           mainTransform(transformFunction(fun))
@@ -569,23 +644,28 @@ abstract class UnCurry extends InfoTransform with TypingTransformers {
     } setType uncurryTreeType(tree.tpe)
 
     def postTransform(tree: Tree): Tree = atPhase(phase.next) {
-      def applyUnary(tree: Tree): Tree = 
-        if (tree.symbol.isMethod && 
-            (!tree.tpe.isInstanceOf[PolyType] || tree.tpe.typeParams.isEmpty)) {
-          if (!tree.tpe.isInstanceOf[MethodType]) tree.tpe = MethodType(List(), tree.tpe);
-          atPos(tree.pos)(Apply(tree, List()) setType tree.tpe.resultType)
-        } else if (tree.isType) {
-          TypeTree(tree.tpe) setPos tree.pos
-        } else {
-          tree
+      def applyUnary(): Tree = {
+        def needsParens = tree.symbol.isMethod && (!tree.tpe.isInstanceOf[PolyType] || tree.tpe.typeParams.isEmpty)
+        def repair = {
+          if (!tree.tpe.isInstanceOf[MethodType])
+            tree.tpe = MethodType(Nil, tree.tpe)
+          
+          atPos(tree.pos)(Apply(tree, Nil) setType tree.tpe.resultType)
         }
+        
+        if (isElidable(tree)) elideIntoUnit(tree) // was not seen in mainTransform
+        else if (needsParens) repair
+        else if (tree.isType) TypeTree(tree.tpe) setPos tree.pos
+        else tree
+      }
+      
       tree match {
         case DefDef(mods, name, tparams, vparamss, tpt, rhs) =>
           val rhs1 = nonLocalReturnKeys.get(tree.symbol) match {
             case None => rhs
             case Some(k) => atPos(rhs.pos)(nonLocalReturnTry(rhs, k, tree.symbol))
           }
-          copy.DefDef(tree, mods, name, tparams, List(List.flatten(vparamss)), tpt, rhs1)
+          treeCopy.DefDef(tree, mods, name, tparams, List(vparamss.flatten), tpt, rhs1)
         case Try(body, catches, finalizer) =>
           if (catches forall treeInfo.isCatchCase) tree
           else {
@@ -610,24 +690,15 @@ abstract class UnCurry extends InfoTransform with TypingTransformers {
             if (settings.debug.value) log("rewrote try: " + catches + " ==> " + catchall);
             val catches1 = localTyper.typedCases(
               tree, List(catchall), ThrowableClass.tpe, WildcardType);
-            copy.Try(tree, body, catches1, finalizer)
+            treeCopy.Try(tree, body, catches1, finalizer)
           }
         case Apply(Apply(fn, args), args1) =>
-          copy.Apply(tree, fn, args ::: args1)
+          treeCopy.Apply(tree, fn, args ::: args1)
         case Ident(name) =>
           assert(name != nme.WILDCARD_STAR.toTypeName)
-          applyUnary(tree);
-        case Select(qual, name) =>
-          /* Function1.apply to ByNameFunction.apply if qualifier is a ByNameFunction */
-          /*
-          if (qual.tpe.typeSymbol == ByNameFunctionClass) {
-            assert(tree.symbol.name == nme.apply && tree.symbol.owner == FunctionClass(1), tree.symbol)
-            tree.symbol = getMember(ByNameFunctionClass, nme.apply)
-          }
-          */
-          applyUnary(tree)
-        case TypeApply(_, _) =>
-          applyUnary(tree)
+          applyUnary()
+        case Select(_, _) | TypeApply(_, _) =>
+          applyUnary()
         case Return(expr) if (tree.symbol != currentOwner.enclMethod || currentOwner.hasFlag(LAZY)) =>
           if (settings.debug.value) log("non local return in "+tree.symbol+" from "+currentOwner.enclMethod)
           atPos(tree.pos)(nonLocalReturnThrow(expr, tree.symbol))
diff --git a/src/compiler/scala/tools/nsc/typechecker/Analyzer.scala b/src/compiler/scala/tools/nsc/typechecker/Analyzer.scala
index c5650e6..d90a3ab 100644
--- a/src/compiler/scala/tools/nsc/typechecker/Analyzer.scala
+++ b/src/compiler/scala/tools/nsc/typechecker/Analyzer.scala
@@ -1,10 +1,12 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: Analyzer.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.tools.nsc.typechecker
+package scala.tools.nsc
+package typechecker
+
+import util.Statistics._
 
 /** The main attribution phase.
  */ 
@@ -13,10 +15,13 @@ trait Analyzer extends AnyRef
             with Namers
             with Typers
             with Infer
+            with Implicits
             with Variances
             with EtaExpansion
             with SyntheticMethods 
             with Unapplies
+            with NamesDefaults
+            with TypeDiagnostics
 {
   val global : Global
   import global._
@@ -24,21 +29,65 @@ trait Analyzer extends AnyRef
   object namerFactory extends SubComponent {
     val global: Analyzer.this.global.type = Analyzer.this.global
     val phaseName = "namer"
+    val runsAfter = List[String]("parser")
+    val runsRightAfter = None
     def newPhase(_prev: Phase): StdPhase = new StdPhase(_prev) {
       override val checkable = false
+      override def keepsTypeParams = false
+
       def apply(unit: CompilationUnit) {
         newNamer(rootContext(unit)).enterSym(unit.body)
       }
     }
   }
 
+  object packageObjects extends SubComponent {
+    val global: Analyzer.this.global.type = Analyzer.this.global
+    val phaseName = "packageobjects"
+    val runsAfter = List[String]()
+    val runsRightAfter= Some("namer")
+
+    def newPhase(_prev: Phase): StdPhase = new StdPhase(_prev) {
+      import global._
+
+      val openPackageObjectsTraverser = new Traverser {
+        override def traverse(tree: Tree): Unit = tree match {
+          case ModuleDef(_, _, _) =>
+            if (tree.symbol.name == nme.PACKAGEkw) {
+              loaders.openPackageModule(tree.symbol)()
+            }
+          case ClassDef(_, _, _, _) => () // make it fast
+          case _ => super.traverse(tree)
+        }
+      }
+
+      def apply(unit: CompilationUnit) {
+        openPackageObjectsTraverser(unit.body)
+      }
+    }
+  }
+
   object typerFactory extends SubComponent {
     val global: Analyzer.this.global.type = Analyzer.this.global
     val phaseName = "typer"
+    val runsAfter = List[String]()
+    val runsRightAfter = Some("packageobjects")
     def newPhase(_prev: Phase): StdPhase = new StdPhase(_prev) {
-      if (!inIDE) resetTyper()
+      override def keepsTypeParams = false
+      resetTyper() // this does not in fact to the reset for each compilation run!
+      override def run { 
+        val start = startTimer(typerNanos)
+        currentRun.units foreach applyPhase
+        stopTimer(typerNanos, start)
+      }
       def apply(unit: CompilationUnit) {
-        unit.body = newTyper(rootContext(unit)).typed(unit.body)
+        try {
+          unit.body = newTyper(rootContext(unit)).typed(unit.body)
+          if (global.settings.Yrangepos.value && !global.reporter.hasErrors) global.validatePositions(unit.body)
+          for (workItem <- unit.toCheck) workItem()
+        } finally {
+          unit.toCheck.clear()
+        }
       }
     }
   }
diff --git a/src/compiler/scala/tools/nsc/typechecker/ConstantFolder.scala b/src/compiler/scala/tools/nsc/typechecker/ConstantFolder.scala
index 7c6b0d6..92308c1 100644
--- a/src/compiler/scala/tools/nsc/typechecker/ConstantFolder.scala
+++ b/src/compiler/scala/tools/nsc/typechecker/ConstantFolder.scala
@@ -1,10 +1,10 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: ConstantFolder.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.tools.nsc.typechecker
+package scala.tools.nsc
+package typechecker
 
 
 import java.lang.ArithmeticException
@@ -33,7 +33,7 @@ abstract class ConstantFolder {
    *  @param tree ...
    *  @param pt ...
    */
-  def apply(tree: Tree, pt: Type): Tree = fold(tree, tree.tpe match {
+  def apply(tree: Tree, pt: Type): Tree = fold(apply(tree), tree.tpe match {
     case ConstantType(x) => x convertTo pt
     case _ => null
   })
@@ -41,11 +41,11 @@ abstract class ConstantFolder {
   private def fold(tree: Tree, compX: => Constant): Tree =
     try {
       val x = compX
-      if ((x ne null) && x.tag != UnitTag) tree setType mkConstantType(x) 
+      if ((x ne null) && x.tag != UnitTag) tree setType ConstantType(x) 
       else tree
     } catch {
       case _: ArithmeticException => tree   // the code will crash at runtime,
-	                                   // but that is better than the
+                                           // but that is better than the
                                            // compiler itself crashing
     }
 
@@ -68,104 +68,105 @@ abstract class ConstantFolder {
     case _ => null
   }
 
-  private def foldBinop(op: Name, x: Constant, y: Constant): Constant = try {
-    val optag = if (x.tag == y.tag) x.tag
-                else if (isNumeric(x.tag) && isNumeric(y.tag))
-                  if (x.tag > y.tag) x.tag else y.tag
-                else NoTag
-    optag match {
-      case BooleanTag =>
-	op match {
-	  case nme.ZOR  => Constant(x.booleanValue | y.booleanValue)
-	  case nme.OR   => Constant(x.booleanValue | y.booleanValue)
-	  case nme.XOR  => Constant(x.booleanValue ^ y.booleanValue)
-	  case nme.ZAND => Constant(x.booleanValue & y.booleanValue)
-	  case nme.AND  => Constant(x.booleanValue & y.booleanValue)
-	  case nme.EQ   => Constant(x.booleanValue == y.booleanValue)
-	  case nme.NE   => Constant(x.booleanValue != y.booleanValue)
-	  case _ => null
-	}
-      case ByteTag | ShortTag | CharTag | IntTag =>
-	op match {
-	  case nme.OR  => Constant(x.intValue | y.intValue)
-	  case nme.XOR => Constant(x.intValue ^ y.intValue)
-	  case nme.AND => Constant(x.intValue & y.intValue)
-	  case nme.LSL => Constant(x.intValue << y.intValue)
-	  case nme.LSR => Constant(x.intValue >>> y.intValue)
-	  case nme.ASR => Constant(x.intValue >> y.intValue)
-	  case nme.EQ  => Constant(x.intValue == y.intValue)
-	  case nme.NE  => Constant(x.intValue != y.intValue)
-	  case nme.LT  => Constant(x.intValue < y.intValue)
-	  case nme.GT  => Constant(x.intValue > y.intValue)
-	  case nme.LE  => Constant(x.intValue <= y.intValue)
-	  case nme.GE  => Constant(x.intValue >= y.intValue)
-	  case nme.ADD => Constant(x.intValue + y.intValue)
-	  case nme.SUB => Constant(x.intValue - y.intValue)
-	  case nme.MUL => Constant(x.intValue * y.intValue)
-	  case nme.DIV => Constant(x.intValue / y.intValue)
-	  case nme.MOD => Constant(x.intValue % y.intValue)
-	  case _ => null
-	}
-      case LongTag =>
-	op match {
-	  case nme.OR  => Constant(x.longValue | y.longValue)
-	  case nme.XOR => Constant(x.longValue ^ y.longValue)
-	  case nme.AND => Constant(x.longValue & y.longValue)
-	  case nme.LSL => Constant(x.longValue << y.longValue)
-	  case nme.LSR => Constant(x.longValue >>> y.longValue)
-	  case nme.ASR => Constant(x.longValue >> y.longValue)
-	  case nme.EQ  => Constant(x.longValue == y.longValue)
-	  case nme.NE  => Constant(x.longValue != y.longValue)
-	  case nme.LT  => Constant(x.longValue < y.longValue)
-	  case nme.GT  => Constant(x.longValue > y.longValue)
-	  case nme.LE  => Constant(x.longValue <= y.longValue)
-	  case nme.GE  => Constant(x.longValue >= y.longValue)
-	  case nme.ADD => Constant(x.longValue + y.longValue)
-	  case nme.SUB => Constant(x.longValue - y.longValue)
-	  case nme.MUL => Constant(x.longValue * y.longValue)
-	  case nme.DIV => Constant(x.longValue / y.longValue)
-	  case nme.MOD => Constant(x.longValue % y.longValue)
-	  case _ => null
-	}
-      case FloatTag =>
-	op match {
-	  case nme.EQ  => Constant(x.floatValue == y.floatValue)
-	  case nme.NE  => Constant(x.floatValue != y.floatValue)
-	  case nme.LT  => Constant(x.floatValue < y.floatValue)
-	  case nme.GT  => Constant(x.floatValue > y.floatValue)
-	  case nme.LE  => Constant(x.floatValue <= y.floatValue)
-	  case nme.GE  => Constant(x.floatValue >= y.floatValue)
-	  case nme.ADD => Constant(x.floatValue + y.floatValue)
-	  case nme.SUB => Constant(x.floatValue - y.floatValue)
-	  case nme.MUL => Constant(x.floatValue * y.floatValue)
-	  case nme.DIV => Constant(x.floatValue / y.floatValue)
-	  case nme.MOD => Constant(x.floatValue % y.floatValue)
-	  case _ => null
-	}
-      case DoubleTag =>
-	op match {
-	  case nme.EQ  => Constant(x.doubleValue == y.doubleValue)
-	  case nme.NE  => Constant(x.doubleValue != y.doubleValue)
-	  case nme.LT  => Constant(x.doubleValue < y.doubleValue)
-	  case nme.GT  => Constant(x.doubleValue > y.doubleValue)
-	  case nme.LE  => Constant(x.doubleValue <= y.doubleValue)
-	  case nme.GE  => Constant(x.doubleValue >= y.doubleValue)
-	  case nme.ADD => Constant(x.doubleValue + y.doubleValue)
-	  case nme.SUB => Constant(x.doubleValue - y.doubleValue)
-	  case nme.MUL => Constant(x.doubleValue * y.doubleValue)
-	  case nme.DIV => Constant(x.doubleValue / y.doubleValue)
-	  case nme.MOD => Constant(x.doubleValue % y.doubleValue)
-	  case _ => null
-	}
-      case StringTag =>
-	op match {
-	  case nme.ADD => Constant(x.stringValue + y.stringValue)
-	  case _ => null
-	}
-      case _ =>
-	null
+  /** These are local helpers to keep foldBinop from overly taxing the
+   *  optimizer.
+   */
+  private def foldBooleanOp(op: Name, x: Constant, y: Constant): Constant = op match {
+    case nme.ZOR  => Constant(x.booleanValue | y.booleanValue)
+    case nme.OR   => Constant(x.booleanValue | y.booleanValue)
+    case nme.XOR  => Constant(x.booleanValue ^ y.booleanValue)
+    case nme.ZAND => Constant(x.booleanValue & y.booleanValue)
+    case nme.AND  => Constant(x.booleanValue & y.booleanValue)
+    case nme.EQ   => Constant(x.booleanValue == y.booleanValue)
+    case nme.NE   => Constant(x.booleanValue != y.booleanValue)
+    case _ => null
+  }
+  private def foldSubrangeOp(op: Name, x: Constant, y: Constant): Constant = op match {
+    case nme.OR  => Constant(x.intValue | y.intValue)
+    case nme.XOR => Constant(x.intValue ^ y.intValue)
+    case nme.AND => Constant(x.intValue & y.intValue)
+    case nme.LSL => Constant(x.intValue << y.intValue)
+    case nme.LSR => Constant(x.intValue >>> y.intValue)
+    case nme.ASR => Constant(x.intValue >> y.intValue)
+    case nme.EQ  => Constant(x.intValue == y.intValue)
+    case nme.NE  => Constant(x.intValue != y.intValue)
+    case nme.LT  => Constant(x.intValue < y.intValue)
+    case nme.GT  => Constant(x.intValue > y.intValue)
+    case nme.LE  => Constant(x.intValue <= y.intValue)
+    case nme.GE  => Constant(x.intValue >= y.intValue)
+    case nme.ADD => Constant(x.intValue + y.intValue)
+    case nme.SUB => Constant(x.intValue - y.intValue)
+    case nme.MUL => Constant(x.intValue * y.intValue)
+    case nme.DIV => Constant(x.intValue / y.intValue)
+    case nme.MOD => Constant(x.intValue % y.intValue)
+    case _ => null
+  }
+  private def foldLongOp(op: Name, x: Constant, y: Constant): Constant = op match {
+    case nme.OR  => Constant(x.longValue | y.longValue)
+    case nme.XOR => Constant(x.longValue ^ y.longValue)
+    case nme.AND => Constant(x.longValue & y.longValue)
+    case nme.LSL => Constant(x.longValue << y.longValue)
+    case nme.LSR => Constant(x.longValue >>> y.longValue)
+    case nme.ASR => Constant(x.longValue >> y.longValue)
+    case nme.EQ  => Constant(x.longValue == y.longValue)
+    case nme.NE  => Constant(x.longValue != y.longValue)
+    case nme.LT  => Constant(x.longValue < y.longValue)
+    case nme.GT  => Constant(x.longValue > y.longValue)
+    case nme.LE  => Constant(x.longValue <= y.longValue)
+    case nme.GE  => Constant(x.longValue >= y.longValue)
+    case nme.ADD => Constant(x.longValue + y.longValue)
+    case nme.SUB => Constant(x.longValue - y.longValue)
+    case nme.MUL => Constant(x.longValue * y.longValue)
+    case nme.DIV => Constant(x.longValue / y.longValue)
+    case nme.MOD => Constant(x.longValue % y.longValue)
+    case _ => null
+  }  
+  private def foldFloatOp(op: Name, x: Constant, y: Constant): Constant = op match {
+    case nme.EQ  => Constant(x.floatValue == y.floatValue)
+    case nme.NE  => Constant(x.floatValue != y.floatValue)
+    case nme.LT  => Constant(x.floatValue < y.floatValue)
+    case nme.GT  => Constant(x.floatValue > y.floatValue)
+    case nme.LE  => Constant(x.floatValue <= y.floatValue)
+    case nme.GE  => Constant(x.floatValue >= y.floatValue)
+    case nme.ADD => Constant(x.floatValue + y.floatValue)
+    case nme.SUB => Constant(x.floatValue - y.floatValue)
+    case nme.MUL => Constant(x.floatValue * y.floatValue)
+    case nme.DIV => Constant(x.floatValue / y.floatValue)
+    case nme.MOD => Constant(x.floatValue % y.floatValue)
+    case _ => null
+  }
+  private def foldDoubleOp(op: Name, x: Constant, y: Constant): Constant = op match {
+    case nme.EQ  => Constant(x.doubleValue == y.doubleValue)
+    case nme.NE  => Constant(x.doubleValue != y.doubleValue)
+    case nme.LT  => Constant(x.doubleValue < y.doubleValue)
+    case nme.GT  => Constant(x.doubleValue > y.doubleValue)
+    case nme.LE  => Constant(x.doubleValue <= y.doubleValue)
+    case nme.GE  => Constant(x.doubleValue >= y.doubleValue)
+    case nme.ADD => Constant(x.doubleValue + y.doubleValue)
+    case nme.SUB => Constant(x.doubleValue - y.doubleValue)
+    case nme.MUL => Constant(x.doubleValue * y.doubleValue)
+    case nme.DIV => Constant(x.doubleValue / y.doubleValue)
+    case nme.MOD => Constant(x.doubleValue % y.doubleValue)
+    case _ => null
+  }
+
+  private def foldBinop(op: Name, x: Constant, y: Constant): Constant = {
+    val optag =
+      if (x.tag == y.tag) x.tag
+      else if (x.isNumeric && y.isNumeric) math.max(x.tag, y.tag)
+      else NoTag
+      
+    try optag match {
+      case BooleanTag                               => foldBooleanOp(op, x, y)
+      case ByteTag | ShortTag | CharTag | IntTag    => foldSubrangeOp(op, x, y)
+      case LongTag                                  => foldLongOp(op, x, y)
+      case FloatTag                                 => foldFloatOp(op, x, y)
+      case DoubleTag                                => foldDoubleOp(op, x, y)
+      case StringTag if op == nme.ADD               => Constant(x.stringValue + y.stringValue)
+      case _                                        => null
+    }
+    catch {
+      case ex: ArithmeticException => null
     }
-  } catch {
-    case ex: ArithmeticException => null
   }
 }
diff --git a/src/compiler/scala/tools/nsc/typechecker/Contexts.scala b/src/compiler/scala/tools/nsc/typechecker/Contexts.scala
index 2f1997c..2f1fe5e 100644
--- a/src/compiler/scala/tools/nsc/typechecker/Contexts.scala
+++ b/src/compiler/scala/tools/nsc/typechecker/Contexts.scala
@@ -1,14 +1,14 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: Contexts.scala 16881 2009-01-09 16:28:11Z cunei $
 
-package scala.tools.nsc.typechecker
+package scala.tools.nsc
+package typechecker
 
 import symtab.Flags._
-import scala.tools.nsc.util.{Position,NoPosition}
 import scala.collection.mutable.ListBuffer
+import annotation.tailrec
 
 /** This trait ...
  *
@@ -45,7 +45,9 @@ trait Contexts { self: Analyzer =>
       if (!unit.isJava) {
         assert(ScalaPackage ne null, "Scala package is null")
         imps += ScalaPackage
-        if (!(treeInfo.isPredefUnit(unit.body) || treeInfo.containsLeadingPredefImport(List(unit.body))))
+        if (!(treeInfo.isUnitInScala(unit.body, nme.Predef) ||
+              treeInfo.isUnitInScala(unit.body, nme.ScalaObject) ||
+              treeInfo.containsLeadingPredefImport(List(unit.body))))
           imps += PredefModule
       }
     }
@@ -62,7 +64,7 @@ trait Contexts { self: Analyzer =>
       assert(pkg ne null)
       val qual = gen.mkAttributedStableRef(pkg)
       sc = sc.makeNewImport(
-        Import(qual, List((nme.WILDCARD, null)))
+        Import(qual, List(ImportSelector(nme.WILDCARD, -1, null, -1)))
         .setSymbol(NoSymbol.newImport(NoPosition).setFlag(SYNTHETIC).setInfo(ImportType(qual)))
         .setType(NoType))
       sc.depth += 1
@@ -100,14 +102,18 @@ trait Contexts { self: Analyzer =>
                                                     // not inherited to child contexts
     var depth: Int = 0
     var imports: List[ImportInfo] = List()   // currently visible imports
-    var openImplicits: List[Type] = List()   // types for which implicit arguments
+    var openImplicits: List[(Type,Symbol)] = List()   // types for which implicit arguments
                                              // are currently searched
+    // for a named application block (Tree) the corresponding NamedApplyInfo
+    var namedApplyBlockInfo: Option[(Tree, NamedApplyInfo)] = None
     var prefix: Type = NoPrefix
     var inConstructorSuffix = false         // are we in a secondary constructor
                                             // after the this constructor call?
     var returnsSeen = false                 // for method context: were returns encountered?
+    var inSelfSuperCall = false             // is this a context for a constructor self or super call?
     var reportAmbiguousErrors = false
     var reportGeneralErrors = false
+    var diagnostic: List[String] = Nil      // these messages are printed when issuing an error
     var implicitsEnabled = false
     var checking = false
     var retyping = false
@@ -115,101 +121,18 @@ trait Contexts { self: Analyzer =>
     var savedTypeBounds: List[(Symbol, Type)] = List() // saved type bounds
        // for type parameters which are narrowed in a GADT
 
-    def intern0 : Context = {
-      if (this eq NoContext) return this
-      val txt = new Context
-      txt.unit = unit
-      txt.tree = tree
-      txt.owner = owner
-      txt.scope = scope
-      assert(outer ne this) // stupid
-      txt.outer = outer // already interned
-      def fix(what : Context) = 
-        if (what eq this) txt
-        else what
-      txt.enclClass = fix(enclClass)
-      txt.enclMethod = fix(enclMethod)
-      txt.implicitsEnabled = implicitsEnabled
-      txt.variance = variance
-      txt._undetparams = _undetparams
-      txt.depth = depth
-      txt.imports = imports
-      txt.openImplicits = openImplicits
-      txt.prefix = prefix
-      txt.inConstructorSuffix = inConstructorSuffix
-      txt.returnsSeen = returnsSeen
-      txt.reportGeneralErrors = reportGeneralErrors
-      txt.checking = checking
-      txt.retyping = retyping
-      txt.savedTypeBounds = savedTypeBounds
-      txt
-    }
-    override def equals(that: Any): Boolean = that match {
-      case that: AnyRef if (this eq that) =>
-        true
-      case that if !inIDE =>
-        super.equals(that)
-      //case NoContext => false
-      case that: Context =>
-        if (that eq NoContext) return this eq NoContext
-        assert(that ne NoContext)
-        if (this eq NoContext) return false
-        assert(inIDE)
-        def eq[T](x : T, y : T) = x == y
-        val a0 = {
-          if ((tree ne null) && (tree ne EmptyTree)) tree.setType(null)
-          if ((tree eq null) || (that.tree eq null)) tree == that.tree else 
-            tree equalsStructure that.tree;
-        } 
-        val a1 = eq(owner, that.owner)
-        val a2 = eq(scope, that.scope)
-        def fix(txt0 : Context, txt1 : Context) = 
-          ((this eq txt0) && (that eq txt1)) || (txt0 eq txt1)
-        
-        val a3 = fix(outer, that.outer)
-        val a4 = fix(enclClass, that.enclClass)
-        val a5 = fix(enclMethod, that.enclMethod)
-        val a6 = eq(variance, that.variance)
-        val a7 = eq(_undetparams, that._undetparams)
-        val a8 = eq(depth, that.depth)
-        val a9 = eq(imports, that.imports)
-
-        val a10 = eq(openImplicits, that.openImplicits)
-        val a11 = eq(prefix, that.prefix)
-        val a12 = eq(inConstructorSuffix, that.inConstructorSuffix)
-        val a13 = eq(implicitsEnabled, that.implicitsEnabled)
-        val a14 = eq(checking, that.checking)
-        val a15 = eq(retyping, that.retyping)
-        val a16 = eq(savedTypeBounds, that.savedTypeBounds)
-        val a17 = eq(unit, that.unit)
-        val ret = a0 && a1 && a2 && a3 && a4 && a5 && a6 && a7 && a8 && a9 && a10 && a11 && a12 && a13 && a14 && a15 && a16 && a17
-        val a18 = {
-          if (implicitsRunId > that.implicitsRunId) {
-            that.implicitsRunId = NoRunId
-            that.implicitsCache = null
-          }
-          else if (that.implicitsRunId > implicitsRunId) {
-            implicitsRunId = NoRunId
-            implicitsCache = null
-          }
-          implicitsCache == that.implicitsCache
-        }
-        if (ret) {
-          if (!a18) {
-            //assert(this.implicitsCache == null || that.implicitsCache == null)
-          }
-        }
-        ret
-      case _ => false
-    }
-    
-
     def undetparams = _undetparams
     def undetparams_=(ps: List[Symbol]) = {
       //System.out.println("undetparams = " + ps);//debug
       _undetparams = ps
     }
 
+    def extractUndetparams() = {
+      val tparams = undetparams
+      undetparams = List()
+      tparams
+    }
+
     /**
      *  @param unit    ...
      *  @param tree    ...
@@ -222,15 +145,11 @@ trait Contexts { self: Analyzer =>
              scope: Scope, imports: List[ImportInfo]): Context = {
       val c = new Context
       c.unit = unit
-      c.tree = sanitize(tree)
+      c.tree = /*sanitize*/(tree) // used to be for IDE
       c.owner = owner
       c.scope = scope
       
-      c.outer = intern(this)
-      def internIf(txt : Context) = {
-        if (txt eq this) c.outer // already interned!
-        else txt
-      }
+      c.outer = this
       
       tree match {
         case Template(_, _, _) | PackageDef(_, _) =>
@@ -238,7 +157,7 @@ trait Contexts { self: Analyzer =>
           c.prefix = c.owner.thisType
           c.inConstructorSuffix = false
         case _ =>
-          c.enclClass = internIf(this.enclClass)
+          c.enclClass = this.enclClass
           c.prefix =
             if (c.owner != this.owner && c.owner.isTerm) NoPrefix
             else this.prefix
@@ -248,17 +167,19 @@ trait Contexts { self: Analyzer =>
         case DefDef(_, _, _, _, _, _) =>
           c.enclMethod = c
         case _ =>
-          c.enclMethod = internIf(this.enclMethod)
+          c.enclMethod = this.enclMethod
       }
       c.variance = this.variance
       c.depth = if (scope == this.scope) this.depth else this.depth + 1
       c.imports = imports
       c.reportAmbiguousErrors = this.reportAmbiguousErrors
       c.reportGeneralErrors = this.reportGeneralErrors
+      c.diagnostic = this.diagnostic
       c.implicitsEnabled = this.implicitsEnabled
       c.checking = this.checking
       c.retyping = this.retyping
       c.openImplicits = this.openImplicits
+      registerContext(c.asInstanceOf[analyzer.Context])
       c
     }
 
@@ -283,8 +204,8 @@ trait Contexts { self: Analyzer =>
       make(unit, tree, owner, scope, imports)
     }
 
-    def makeNewScope(tree: Tree, owner: Symbol)(implicit kind : ScopeKind): Context =
-      make(tree, owner, scopeFor(scope, tree, kind))
+    def makeNewScope(tree: Tree, owner: Symbol): Context =
+      make(tree, owner, new Scope(scope))
     // IDE stuff: distinguish between scopes created for typing and scopes created for naming. 
 
     def make(tree: Tree, owner: Symbol): Context =
@@ -293,8 +214,8 @@ trait Contexts { self: Analyzer =>
     def make(tree: Tree): Context =
       make(tree, owner)
 
-    def makeSilent(reportAmbiguousErrors: Boolean): Context = {
-      val c = make(tree)
+    def makeSilent(reportAmbiguousErrors: Boolean, newtree: Tree = tree): Context = {
+      val c = make(newtree)
       c.reportGeneralErrors = false
       c.reportAmbiguousErrors = reportAmbiguousErrors
       c
@@ -311,7 +232,8 @@ trait Contexts { self: Analyzer =>
       //todo: find out why we need next line
       while (baseContext.tree.isInstanceOf[Template])
         baseContext = baseContext.outer
-      val argContext = baseContext.makeNewScope(tree, owner)(Constructor0ScopeKind)
+      val argContext = baseContext.makeNewScope(tree, owner)
+      argContext.inSelfSuperCall = true
       argContext.reportGeneralErrors = this.reportGeneralErrors
       argContext.reportAmbiguousErrors = this.reportAmbiguousErrors
       def enterElems(c: Context) {
@@ -330,29 +252,29 @@ trait Contexts { self: Analyzer =>
       argContext
     }
 
-    //todo: remove
-    def makeConstructorSuffixContext = {
-      val c = make(tree)
-      c.inConstructorSuffix = true
-      c
-    }
+    private def diagString =
+      if (diagnostic.isEmpty) ""
+      else diagnostic.mkString("\n","\n", "")
 
-    def error(pos: Position, err: Error) {
-      val msg = err.getMessage()
-      if (reportGeneralErrors || inIDE)
-        unit.error(pos, if (checking) "**** ERROR DURING INTERNAL CHECKING ****\n" + msg else msg)
-      else
-        throw err
+    private def addDiagString(msg: String) = {
+      val ds = diagString
+      if (msg endsWith ds) msg else msg + ds
     }
 
-    def error(pos: Position, msg: String) {
-      if (reportGeneralErrors)
-        unit.error(pos, if (checking) "**** ERROR DURING INTERNAL CHECKING ****\n" + msg else msg)
-      else
-        throw new TypeError(pos, msg)
+    private def unitError(pos: Position, msg: String) = 
+      unit.error(pos, if (checking) "**** ERROR DURING INTERNAL CHECKING ****\n" + msg else msg)
+
+    def error(pos: Position, err: Throwable) =
+      if (reportGeneralErrors) unitError(pos, addDiagString(err.getMessage()))
+      else throw err
+
+    def error(pos: Position, msg: String) = {
+      val msg1 = addDiagString(msg)
+      if (reportGeneralErrors) unitError(pos, msg1)
+      else throw new TypeError(pos, msg1)
     }
 
-    def warning(pos:  Position, msg: String) {
+    def warning(pos:  Position, msg: String) = {
       if (reportGeneralErrors) unit.warning(pos, msg)
     }
  
@@ -395,7 +317,7 @@ trait Contexts { self: Analyzer =>
     override def toString(): String = {
       if (this == NoContext) "NoContext"
       else owner.toString() + " @ " + tree.getClass() +
-           " " + tree.toString() + ", scope = " + scope.hashCode() +
+           " " + tree.toString() + ", scope = " + scope.## +
            " " + scope.toList + "\n:: " + outer.toString()
     }
 
@@ -405,7 +327,7 @@ trait Contexts { self: Analyzer =>
       var c = this.enclClass
       while (c != NoContext && 
              !clazz.isNonBottomSubClass(c.owner) &&
-             !(c.owner.isModuleClass && clazz.isNonBottomSubClass(c.owner.linkedClassOfModule)))
+             !(c.owner.isModuleClass && clazz.isNonBottomSubClass(c.owner.companionClass)))
         c = c.outer.enclClass
       c
     }
@@ -428,20 +350,36 @@ trait Contexts { self: Analyzer =>
      *  @return            ...
      */
     def isAccessible(sym: Symbol, pre: Type, superAccess: Boolean): Boolean = {
+      @inline def accessWithinLinked(ab: Symbol) = {
+        val linked = ab.linkedClassOfClass
+        // don't have access if there is no linked class
+        // (before adding the `ne NoSymbol` check, this was a no-op when linked eq NoSymbol,
+        //  since `accessWithin(NoSymbol) == true` whatever the symbol)
+        (linked ne NoSymbol) && accessWithin(linked)
+      }
+
+      /** Are we inside definition of `ab'? */
+      def accessWithin(ab: Symbol) = {
+        // #3663: we must disregard package nesting if sym isJavaDefined
+        if(sym.isJavaDefined) {
+          // is `o` or one of its transitive owners equal to `ab`?
+          // stops at first package, since further owners can only be surrounding packages
+          @tailrec def abEnclosesStopAtPkg(o: Symbol): Boolean =
+            (o eq ab) || (!o.isPackageClass && (o ne NoSymbol) && abEnclosesStopAtPkg(o.owner))
+          abEnclosesStopAtPkg(owner)
+        } else (owner hasTransOwner ab)
+      }
 
-      /** Are we inside definition of `owner'? */
-      def accessWithin(owner: Symbol): Boolean = {
+/*
         var c = this
         while (c != NoContext && c.owner != owner) {
-          if (false && inIDE) // XXX: we didn't get to update these syms.... 
-            assert(c.owner.fullNameString != owner.fullNameString)
           if (c.outer eq null) assert(false, "accessWithin(" + owner + ") " + c);//debug
           if (c.outer.enclClass eq null) assert(false, "accessWithin(" + owner + ") " + c);//debug
           c = c.outer.enclClass
         }
         c != NoContext
       }
-
+*/
       /** Is `clazz' a subclass of an enclosing class? */
       def isSubClassOfEnclosing(clazz: Symbol): Boolean =
         enclosingSuperClassContext(clazz) != NoContext
@@ -453,17 +391,20 @@ trait Contexts { self: Analyzer =>
 
       (pre == NoPrefix) || {
         val ab = sym.accessBoundary(sym.owner)
-        ((ab.isTerm || ab == definitions.RootClass)
-         ||
-         (accessWithin(ab) || accessWithin(ab.linkedClassOfClass)) &&
-         (!sym.hasFlag(LOCAL) || 
-          (sym hasFlag PROTECTED) && isSubThisType(pre, sym.owner) ||
-          pre =:= sym.owner.thisType)
-         ||
-         (sym hasFlag PROTECTED) &&
-         (superAccess ||
-          (pre.widen.typeSymbol.isNonBottomSubClass(sym.owner) && 
-           (isSubClassOfEnclosing(pre.widen.typeSymbol) || phase.erasedTypes))))
+        (  (ab.isTerm || ab == definitions.RootClass)
+        || (accessWithin(ab) || accessWithinLinked(ab)) &&
+             (  !sym.hasFlag(LOCAL)
+             || sym.owner.isImplClass // allow private local accesses to impl classes
+             || (sym hasFlag PROTECTED) && isSubThisType(pre, sym.owner)
+             || pre =:= sym.owner.thisType
+             )
+        || (sym hasFlag PROTECTED) &&
+             (  superAccess
+             || sym.isConstructor
+             || (pre.widen.typeSymbol.isNonBottomSubClass(sym.owner) &&
+                  (isSubClassOfEnclosing(pre.widen.typeSymbol) || phase.erasedTypes))
+             )
+        )
         // note: phase.erasedTypes disables last test, because after addinterfaces
         // implementation classes are not in the superclass chain. If we enable the
         // test, bug780 fails.
@@ -498,98 +439,106 @@ trait Contexts { self: Analyzer =>
       implicitsCache = null
       if (outer != null && outer != this) outer.resetCache
     }
-    private def collectImplicits(syms: List[Symbol], pre: Type): List[ImplicitInfo] =
-      for (sym <- syms if sym.hasFlag(IMPLICIT) && isAccessible(sym, pre, false))
+
+    /** A symbol `sym` qualifies as an implicit if it has the IMPLICIT flag set,
+     *  it is accessible, and if it is imported there is not already a local symbol
+     *  with the same names. Local symbols override imported ones. This fixes #2866.
+     */
+    private def isQualifyingImplicit(sym: Symbol, pre: Type, imported: Boolean) =
+      sym.hasFlag(IMPLICIT) &&
+      isAccessible(sym, pre, false) && 
+      !(imported && {
+        val e = scope.lookupEntry(sym.name)
+        (e ne null) && (e.owner == scope)
+      })
+
+    private def collectImplicits(syms: List[Symbol], pre: Type, imported: Boolean = false): List[ImplicitInfo] =
+      for (sym <- syms if isQualifyingImplicit(sym, pre, imported))
       yield new ImplicitInfo(sym.name, pre, sym)
 
     private def collectImplicitImports(imp: ImportInfo): List[ImplicitInfo] = {
       val pre = imp.qual.tpe
-      def collect(sels: List[(Name, Name)]): List[ImplicitInfo] = sels match {
-        case List() => List()
-        case List((nme.WILDCARD, _)) => collectImplicits(pre.implicitMembers, pre)
-        case (from, to) :: sels1 => 
+      def collect(sels: List[ImportSelector]): List[ImplicitInfo] = sels match {
+        case List() => 
+          List()
+        case List(ImportSelector(nme.WILDCARD, _, _, _)) => 
+          collectImplicits(pre.implicitMembers, pre, imported = true)
+        case ImportSelector(from, _, to, _) :: sels1 => 
           var impls = collect(sels1) filter (info => info.name != from)
           if (to != nme.WILDCARD) {
-            val sym = imp.importedSymbol(to)
-            if (sym.hasFlag(IMPLICIT)) impls = new ImplicitInfo(to, pre, sym) :: impls
+            for (sym <- imp.importedSymbol(to).alternatives)
+              if (isQualifyingImplicit(sym, pre, imported = true))
+                impls = new ImplicitInfo(to, pre, sym) :: impls
           }
           impls
       }
-      if (settings.debug.value)
-        log("collect implicit imports " + imp + "=" + collect(imp.tree.selectors))//debug
+      //if (settings.debug.value) log("collect implicit imports " + imp + "=" + collect(imp.tree.selectors))//DEBUG
       collect(imp.tree.selectors)
     }
 
     def implicitss: List[List[ImplicitInfo]] = {
-      val nextOuter = 
-        if (owner.isConstructor) {
-          if (outer.tree.isInstanceOf[Template]) outer.outer.outer
-          else outer.outer
-        } else outer
-        // can we can do something smarter to bring back the implicit cache?
+      val nextOuter = if (owner.isConstructor) outer.outer.outer else outer
       if (implicitsRunId != currentRunId) {
         implicitsRunId = currentRunId
         implicitsCache = List()
         val newImplicits: List[ImplicitInfo] =
-          if (owner != nextOuter.owner && owner.isClass && !owner.isPackageClass) {
+          if (owner != nextOuter.owner && owner.isClass && !owner.isPackageClass && !inSelfSuperCall) {
             if (!owner.isInitialized) return nextOuter.implicitss
-            if (settings.debug.value)
-              log("collect member implicits " + owner + ", implicit members = " +
-                  owner.thisType.implicitMembers)//debug
+            // if (settings.debug.value) log("collect member implicits " + owner + ", implicit members = " + owner.thisType.implicitMembers)//DEBUG
             val savedEnclClass = enclClass
             this.enclClass = this
             val res = collectImplicits(owner.thisType.implicitMembers, owner.thisType)
             this.enclClass = savedEnclClass
             res
           } else if (scope != nextOuter.scope && !owner.isPackageClass) {
-            if (settings.debug.value)
-              log("collect local implicits " + scope.toList)//debug
+            if (settings.debug.value) log("collect local implicits " + scope.toList)//DEBUG
             collectImplicits(scope.toList, NoPrefix)
           } else if (imports != nextOuter.imports) {
             assert(imports.tail == nextOuter.imports)
             collectImplicitImports(imports.head)
+          } else if (owner.isPackageClass) { 
+ 	    // the corresponding package object may contain implicit members. 
+ 	    collectImplicits(owner.tpe.implicitMembers, owner.tpe)
           } else List()
         implicitsCache = if (newImplicits.isEmpty) nextOuter.implicitss
                          else newImplicits :: nextOuter.implicitss
       }
       implicitsCache
     }
-    override def hashCode = {
-      var hc = 0
-      implicit def b2i(b : Boolean) = if (b) 1 else 0
-      // assum enclClass/enclMethod/outer are all interned already.
-      hc += tree.hashCodeStructure
-      def f(txt : Context) = if (txt eq this) 0 else System.identityHashCode(txt)
-      hc += f(enclClass)
-      hc += f(enclMethod)
-      hc += f(outer)
-      hc += owner.hashCode
-      hc += scope.hashCode
-      hc += variance.hashCode
-      hc += _undetparams.hashCode
-      hc += depth
-      hc += imports.hashCode
-      hc += prefix.hashCode
-      hc += inConstructorSuffix
-      hc += checking
-      hc += retyping
-      hc += savedTypeBounds.hashCode
-      hc += (if (unit eq null) 0 else unit.hashCode)
-      hc
+
+    /**
+     * Find a symbol in this context or one of its outers.
+     *
+     * Used to find symbols are owned by methods (or fields), they can't be
+     * found in some scope.
+     *
+     * Examples: companion module of classes owned by a method, default getter
+     * methods of nested methods. See NamesDefaults.scala
+     */
+    def lookup(name: Name, expectedOwner: Symbol) = {
+      var res: Symbol = NoSymbol
+      var ctx = this
+      while(res == NoSymbol && ctx.outer != ctx) {
+        val s = ctx.scope.lookup(name)
+        if (s != NoSymbol && s.owner == expectedOwner)
+          res = s
+        else
+          ctx = ctx.outer
+      }
+      res
     }
-    
   }
   class ImportInfo(val tree: Import, val depth: Int) {
     /** The prefix expression */
     def qual: Tree = tree.symbol.info match {
       case ImportType(expr) => expr
-      case ErrorType => tree
+      case ErrorType => tree setType NoType // fix for #2870
       case _ => throw new FatalError("symbol " + tree.symbol + " has bad type: " + tree.symbol.info);//debug
     }
 
     /** Is name imported explicitly, not via wildcard? */
     def isExplicitImport(name: Name): Boolean =
-      tree.selectors exists (_._2 == name.toTermName)
+      tree.selectors exists (_.rename == name.toTermName)
 
     /** The symbol with name <code>name</code> imported from import clause
      *  <code>tree</code>.
@@ -599,52 +548,37 @@ trait Contexts { self: Analyzer =>
       var renamed = false
       var selectors = tree.selectors
       while (selectors != Nil && result == NoSymbol) {
-        if (selectors.head._1 != nme.WILDCARD)
-          notifyImport(name, qual.tpe, selectors.head._1, selectors.head._2)
+//        if (selectors.head.name != nme.WILDCARD) // used to be for IDE
+//          notifyImport(name, qual.tpe, selectors.head.name, selectors.head.rename)
 
-        if (selectors.head._2 == name.toTermName)
-          result = qual.tpe.member(
-            if (name.isTypeName) selectors.head._1.toTypeName else selectors.head._1)
-        else if (selectors.head._1 == name.toTermName)
+        if (selectors.head.rename == name.toTermName)
+          result = qual.tpe.nonLocalMember( // new to address #2733: consider only non-local members for imports
+            if (name.isTypeName) selectors.head.name.toTypeName else selectors.head.name)
+        else if (selectors.head.name == name.toTermName)
           renamed = true
-        else if (selectors.head._1 == nme.WILDCARD && !renamed)
-          result = qual.tpe.member(name)
+        else if (selectors.head.name == nme.WILDCARD && !renamed)
+          result = qual.tpe.nonLocalMember(name)
         selectors = selectors.tail
       }
       result
     }
 
-    override def toString() = tree.toString()
-    
-    override def hashCode = tree.hashCodeStructure + depth
-    override def equals(that : Any) = that match {
-      case that : ImportInfo =>
-        depth == that.depth && (tree equalsStructure that.tree)
-      case _ => false
-    }
-  }
+    def allImportedSymbols: List[Symbol] = 
+      qual.tpe.members flatMap (transformImport(tree.selectors, _))
 
-  class ImplicitInfo(val name: Name, val pre: Type, val sym: Symbol) {
-    private var tpeCache: Type = null
-    def tpe: Type = {
-      if (tpeCache eq null) tpeCache = pre.memberType(sym)
-      tpeCache
+    private def transformImport(selectors: List[ImportSelector], sym: Symbol): List[Symbol] = selectors match {
+      case List() => List()
+      case List(ImportSelector(nme.WILDCARD, _, _, _)) => List(sym)
+      case ImportSelector(from, _, to, _) :: _ if (from == sym.name) => 
+        if (to == nme.WILDCARD) List()
+        else { val sym1 = sym.cloneSymbol; sym1.name = to; List(sym1) }
+      case _ :: rest => transformImport(rest, sym)
     }
-    override def toString = "ImplicitInfo(" + name + "," + pre + "," + sym + ")"
-  }
 
-  val NoImplicitInfo = new ImplicitInfo(null, null, null)
+    override def toString() = tree.toString()
+  }
 
   case class ImportType(expr: Tree) extends Type {
-    override def equals(that : Any) = that match {
-    case ImportType(expr) =>
-      if (inIDE) this.expr equalsStructure expr
-      else this.expr == expr
-    case _ => false
-    }
-    override def hashCode = if (inIDE) expr.hashCodeStructure else expr.hashCode
     override def safeToString = "ImportType("+expr+")"
   }
-  protected def intern(txt : Context) = txt
-  
 }
diff --git a/src/compiler/scala/tools/nsc/typechecker/DeVirtualize.scala b/src/compiler/scala/tools/nsc/typechecker/DeVirtualize.scala
index 6c78355..ef93f51 100644
--- a/src/compiler/scala/tools/nsc/typechecker/DeVirtualize.scala
+++ b/src/compiler/scala/tools/nsc/typechecker/DeVirtualize.scala
@@ -1,10 +1,10 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: RefChecks.scala 13735 2008-01-18 17:18:58Z odersky $
 
-package scala.tools.nsc.typechecker
+package scala.tools.nsc
+package typechecker
 
 import symtab.Flags._
 import transform.{InfoTransform, TypingTransformers}
@@ -16,7 +16,6 @@ abstract class DeVirtualize extends InfoTransform with TypingTransformers {
   import global._
   import definitions._
   import typer.{typed, typedOperator, atOwner}
-  import posAssigner.atPos    
 
   /** the following two members override abstract members in Transform */
   val phaseName: String = "devirtualize"
@@ -86,7 +85,7 @@ abstract class DeVirtualize extends InfoTransform with TypingTransformers {
         def enter(sym: Symbol) = // at next phase because names of worker traits change
           atPhase(ownPhase.next) { decls.enter(sym) } 
         if (containsVirtuals(clazz)) {
-          decls = newScope
+          decls = new Scope
           for (m <- decls0.toList) {
             if (m.isVirtualClass) {
               m.setFlag(notDEFERRED | notFINAL | lateABSTRACT)
@@ -100,7 +99,7 @@ abstract class DeVirtualize extends InfoTransform with TypingTransformers {
         if (clazz.isVirtualClass) {
           println("virtual class: "+clazz+clazz.locationString)
           transformOwnerInfo(clazz) 
-          decls = newScope
+          decls = new Scope
           
           // add virtual fields for all primary constructor parameters
           for (row <- paramTypesAndIndices(clazz.primaryConstructor.tpe, 0))
@@ -137,7 +136,7 @@ abstract class DeVirtualize extends InfoTransform with TypingTransformers {
   protected def factoryName(clazz: Symbol) = 
     atPhase(ownPhase) { newTermName("new$"+clazz.name) }
 
-  /** Does `clazz' contaion virtual classes? */
+  /** Does `clazz' contain virtual classes? */
   protected def containsVirtuals(clazz: Symbol) = clazz.info.decls.toList exists (_.isVirtualClass)
 
   /** The inner classes that need factory methods in `clazz' 
@@ -177,7 +176,7 @@ abstract class DeVirtualize extends InfoTransform with TypingTransformers {
 
   /** The name of the field representing a constructor parameter of a virtual class */
   protected def paramFieldName(clazz: Symbol, index: Int) = atPhase(ownPhase) {
-    clazz.expandedName(newTermName("param$"+index))
+    nme.expandedName(newTermName("param$"+index), clazz)
   }
 
   /** The name of the field representing a constructor parameter of a virtual class */
@@ -242,7 +241,7 @@ abstract class DeVirtualize extends InfoTransform with TypingTransformers {
   protected def mkAbstractType(clazz: Symbol): Symbol = {
     val cabstype = clazz.owner.newAbstractType(clazz.pos, clazz.name)
       .setFlag(clazz.flags & absTypeFlagMask | SYNTHETIC)
-      .setAttributes(clazz.attributes)
+      .setAnnotations(clazz.annotations)
     atPhase(ownPhase.next) {
       cabstype setInfo new PolyTypeCompleter(cabstype, clazz) {
         def getInfo = {
@@ -252,7 +251,7 @@ abstract class DeVirtualize extends InfoTransform with TypingTransformers {
           val parents2 = addOverriddenVirtuals(clazz) map {
             c => typeRef(clazz.owner.thisType, c, typeParams map (_.tpe))
           }
-          mkTypeBounds(NothingClass.tpe, intersectionType(parents1 ::: parents2))
+          TypeBounds(NothingClass.tpe, intersectionType(parents1 ::: parents2))
         }
       }
     }
@@ -260,9 +259,9 @@ abstract class DeVirtualize extends InfoTransform with TypingTransformers {
 
   protected def paramTypesAndIndices(tpe: Type, start: Int): List[List[(Type, Int)]] = tpe match {
     case PolyType(_, restpe) => paramTypesAndIndices(restpe, start)
-    case MethodType(formals, restpe) =>
-      val end = start + formals.length
-      (formals zip List.range(start, end)) :: paramTypesAndIndices(restpe, end)
+    case MethodType(params, restpe) =>
+      val end = start + params.length
+      (tpe.paramTypes zip List.range(start, end)) :: paramTypesAndIndices(restpe, end)
     case _ =>
       List()
   }
@@ -292,12 +291,12 @@ abstract class DeVirtualize extends InfoTransform with TypingTransformers {
     val pos = if (clazz.owner == owner) clazz.pos else owner.pos
     val factory = owner.newMethod(pos, factoryName(clazz))
       .setFlag(clazz.flags & factoryFlagMask | SYNTHETIC)
-      .setAttributes(clazz.attributes)
+      .setAnnotations(clazz.annotations)
     factory setInfo new PolyTypeCompleter(factory, clazz) {
       private def copyType(tpe: Type): Type = tpe match {
         case MethodType(formals, restpe) => MethodType(formals, copyType(restpe))
         case PolyType(List(), restpe) => PolyType(List(), copyType(restpe))
-        case PolyType(_, _) => throw new Error("bad case: "+tpe)
+        case PolyType(_, _) => abort("bad case: "+tpe)
         case _ => owner.thisType.memberType(abstractType(clazz))
       }
       def getInfo = copyType(clazz.primaryConstructor.tpe)
@@ -305,9 +304,9 @@ abstract class DeVirtualize extends InfoTransform with TypingTransformers {
     factory
   }
 
-  def removeDuplicates(ts: List[Type]): List[Type] = ts match {
+  def distinct(ts: List[Type]): List[Type] = ts match {
     case List() => List()
-    case t :: ts1 => t :: removeDuplicates(ts1 filter (_.typeSymbol != t.typeSymbol))
+    case t :: ts1 => t :: distinct(ts1 filter (_.typeSymbol != t.typeSymbol))
   }
 
   /** The concrete class symbol VC$fix in the factory symbol (@see mkFactory)
@@ -317,7 +316,7 @@ abstract class DeVirtualize extends InfoTransform with TypingTransformers {
   protected def mkConcreteClass(clazz: Symbol, factory: Symbol) = {
     val cclazz = factory.newClass(clazz.pos, concreteClassName(clazz))
       .setFlag(FINAL | SYNTHETIC)
-      .setAttributes(clazz.attributes)
+      .setAnnotations(clazz.annotations)
       
     cclazz setInfo new LazyType {
       override def complete(sym: Symbol) {
@@ -333,9 +332,9 @@ abstract class DeVirtualize extends InfoTransform with TypingTransformers {
         }
         atPhase(ownPhase.next) {
           val parents2 = 
-            removeDuplicates(parents1.flatMap(addOverriddenVirtuals))
+            distinct(parents1.flatMap(addOverriddenVirtuals))
             .map(_.substSym(clazz.typeParams, factory.typeParams))
-          sym setInfo ClassInfoType(parents2, newScope, cclazz)
+          sym setInfo ClassInfoType(parents2, new Scope, cclazz)
         }
       }
     }
@@ -399,12 +398,14 @@ abstract class DeVirtualize extends InfoTransform with TypingTransformers {
               .setInfo(PolyType(List(), pt))
             cclazz.info.decls enter pfield
             atPos(factory.pos) {
-              DefDef(pfield, vparamss => Ident(fixParamName(i)))
+              DefDef(pfield, Ident(fixParamName(i)))
             }
           }
         }
       }
-      ClassDef(cclazz, Modifiers(0), vparamss, List(List()), pfields ::: overrideBridges)
+      atPos(clazz.pos) {
+        ClassDef(cclazz, Modifiers(0), vparamss, List(List()), pfields ::: overrideBridges, clazz.pos.focus)
+      }
     }
       
 
@@ -437,14 +438,14 @@ abstract class DeVirtualize extends InfoTransform with TypingTransformers {
       val abstpeSym = abstractType(clazz)
       localTyper.typed {
         atPos(factorySym.pos) {
-          DefDef(factorySym, vparamss => 
+          DefDef(factorySym,
             Block(
               List(cclazzDef), 
               TypeApply(
                 Select(
                   gen.mkForwarder(
                     Select(New(TypeTree(cclazzDef.symbol.tpe)), nme.CONSTRUCTOR),
-                    vparamss),
+                    factorySym.paramss),
                   Any_asInstanceOf),
              List(
                TypeTree(
@@ -464,7 +465,7 @@ abstract class DeVirtualize extends InfoTransform with TypingTransformers {
         .resetFlag(notOVERRIDE | notFINAL)
       cclazz.info.decls.enter(bridge)
       val superRef: Tree = Select(Super(cclazz, nme.EMPTY.toTypeName), meth)
-      DefDef(bridge, vparamss => gen.mkForwarder(superRef, vparamss))
+      DefDef(bridge, gen.mkForwarder(superRef, bridge.paramss))
     }
 
     /** Replace definitions of virtual classes by definitions of corresponding
@@ -527,13 +528,13 @@ abstract class DeVirtualize extends InfoTransform with TypingTransformers {
                   val pfield = paramField(sym.owner, paramFieldCount)
                   paramFieldCount += 1
                   pfield setPos pacc.pos
-                  paramFields += localTyper.typed(DefDef(pfield, vparamss => EmptyTree))
+                  paramFields += localTyper.typed(DefDef(pfield, EmptyTree))
                   val pfieldRef = localTyper.typed { 
                     atPos(pacc.pos) { 
                       Select(This(sym.owner), pfield) 
                     } 
                   }
-                  paramFieldAccessors += copy.ValDef(pacc, mods, name, tpt, pfieldRef)
+                  paramFieldAccessors += treeCopy.ValDef(pacc, mods, name, tpt, pfieldRef)
                 case _ =>
                   stat.symbol resetFlag PARAMACCESSOR // ??? can we do this                  
                   others += stat
@@ -541,11 +542,11 @@ abstract class DeVirtualize extends InfoTransform with TypingTransformers {
             else 
               (if (stat.symbol != null && (stat.symbol hasFlag PRESUPER)) presupers else others) += stat
           }
-          copy.Template(tree, parents, self, 
-                        paramFieldAccessors.toList ::: 
-                        presupers.toList ::: 
-                        paramFields.toList :::
-                        others.toList)
+          treeCopy.Template(tree, parents, self, 
+                            paramFieldAccessors.toList ::: 
+                            presupers.toList ::: 
+                            paramFields.toList :::
+                            others.toList)
         case _ =>
           tree setType atPhase(ownPhase)(devirtualizeMap(tree.tpe))
       }
diff --git a/src/compiler/scala/tools/nsc/typechecker/Duplicators.scala b/src/compiler/scala/tools/nsc/typechecker/Duplicators.scala
new file mode 100644
index 0000000..0b3a548
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/typechecker/Duplicators.scala
@@ -0,0 +1,293 @@
+package scala.tools.nsc
+package typechecker
+
+import scala.tools.nsc.symtab.Flags
+
+import scala.collection.{mutable, immutable}
+
+/** Duplicate trees and re-type check them, taking care to replace
+ *  and create fresh symbols for new local definitions.
+ */
+abstract class Duplicators extends Analyzer {
+  import global._
+
+  def retyped(context: Context, tree: Tree): Tree = {
+    resetClassOwners
+    (new BodyDuplicator(context)).typed(tree)
+  }
+
+  /** Retype the given tree in the given context. Use this method when retyping
+   *  a method in a different class. The typer will replace references to the this of
+   *  the old class with the new class, and map symbols through the given 'env'. The
+   *  environment is a map from type skolems to concrete types (see SpecializedTypes).
+   */
+  def retyped(context: Context, tree: Tree, oldThis: Symbol, newThis: Symbol, env: collection.Map[Symbol, Type]): Tree = {
+    if (oldThis ne newThis) {
+      oldClassOwner = oldThis
+      newClassOwner = newThis
+    } else resetClassOwners
+
+    envSubstitution = new SubstSkolemsTypeMap(env.keysIterator.toList, env.valuesIterator.toList)
+    log("retyped with env: " + env)
+    (new BodyDuplicator(context)).typed(tree)
+  }
+
+  def retypedMethod(context: Context, tree: Tree, oldThis: Symbol, newThis: Symbol): Tree =
+    (new BodyDuplicator(context)).retypedMethod(tree.asInstanceOf[DefDef], oldThis, newThis)
+
+  /** Return the special typer for duplicate method bodies. */
+  override def newTyper(context: Context): Typer = 
+    new BodyDuplicator(context)
+
+  private def resetClassOwners {
+    oldClassOwner = null
+    newClassOwner = null
+  }
+
+  private var oldClassOwner: Symbol = _
+  private var newClassOwner: Symbol = _
+  private var envSubstitution: SubstTypeMap = _
+
+  private class SubstSkolemsTypeMap(from: List[Symbol], to: List[Type]) extends SubstTypeMap(from, to) {
+    protected override def matches(sym1: Symbol, sym2: Symbol) = 
+      if (sym2.isTypeSkolem) sym2.deSkolemize eq sym1
+      else sym1 eq sym2
+  }
+
+  private val invalidSyms: mutable.Map[Symbol, Tree] = mutable.HashMap.empty[Symbol, Tree]
+  
+  /** A typer that creates new symbols for all definitions in the given tree
+   *  and updates references to them while re-typechecking. All types in the 
+   *  tree, except for TypeTrees, are erased prior to type checking. TypeTrees
+   *  are fixed by substituting invalid symbols for the new ones.
+   */
+  class BodyDuplicator(context: Context) extends Typer(context: Context) {
+
+    class FixInvalidSyms extends TypeMap {
+
+      def apply(tpe: Type): Type = {
+        mapOver(tpe)
+      }
+
+      override def mapOver(tpe: Type): Type = tpe match {
+        case TypeRef(NoPrefix, sym, args) if sym.isTypeParameterOrSkolem =>
+          val sym1 = context.scope.lookup(sym.name)
+//          assert(sym1 ne NoSymbol, tpe)
+          if ((sym1 ne NoSymbol) && (sym1 ne sym)) {
+            log("fixing " + sym + " -> " + sym1)
+            typeRef(NoPrefix, sym1, mapOverArgs(args, sym1.typeParams))
+          } else super.mapOver(tpe)
+
+        case TypeRef(pre, sym, args) =>
+          val newsym = updateSym(sym)
+          if (newsym ne sym) {
+            log("fixing " + sym + " -> " + newsym)
+            typeRef(mapOver(pre), newsym, mapOverArgs(args, newsym.typeParams))
+          } else 
+            super.mapOver(tpe)
+
+        case SingleType(pre, sym) =>
+          val sym1 = updateSym(sym)
+          if (sym1 ne sym) {
+            log("fixing " + sym + " -> " + sym1)
+            singleType(mapOver(pre), sym1)
+          } else
+            super.mapOver(tpe)
+
+        case ThisType(sym) =>
+          val sym1 = updateSym(sym)
+          if (sym1 ne sym) {
+            log("fixing " + sym + " -> " + sym1)
+            ThisType(sym1)
+          } else
+            super.mapOver(tpe)
+
+        
+        case _ =>
+          super.mapOver(tpe)
+      }
+    }
+    
+    /** Fix the given type by replacing invalid symbols with the new ones. */
+    def fixType(tpe: Type): Type = {
+      val tpe1 = envSubstitution(tpe)
+      val tpe2: Type = (new FixInvalidSyms)(tpe1)
+      val tpe3 = if (newClassOwner ne null) {
+        tpe2.asSeenFrom(newClassOwner.thisType, oldClassOwner)
+      } else tpe2
+      tpe3
+    }
+
+    /** Return the new symbol corresponding to `sym'. */
+    private def updateSym(sym: Symbol): Symbol =
+      if (invalidSyms.isDefinedAt(sym)) 
+        invalidSyms(sym).symbol
+      else
+        sym
+      
+    private def invalidate(tree: Tree) {
+      if (tree.isDef && tree.symbol != NoSymbol) {
+        log("invalid " + tree.symbol)
+        invalidSyms(tree.symbol) = tree
+
+        tree match { 
+          case ldef @ LabelDef(name, params, rhs) =>        
+            log("LabelDef " + name + " sym.info: " + ldef.symbol.info)
+            invalidSyms(ldef.symbol) = ldef
+          //          breakIf(true, this, ldef, context)
+            val newsym = ldef.symbol.cloneSymbol(context.owner)
+            newsym.setInfo(fixType(ldef.symbol.info))
+            ldef.symbol = newsym
+            log("newsym: " + newsym + " info: " + newsym.info)
+
+          case DefDef(_, name, tparams, vparamss, _, rhs) =>
+            // invalidate parameters
+            invalidate(tparams ::: vparamss.flatten)
+            tree.symbol = NoSymbol
+
+          case _ => 
+            tree.symbol = NoSymbol
+        }
+      }
+    }
+
+    private def invalidate(stats: List[Tree]) {
+      stats foreach invalidate
+    }
+      
+
+    def retypedMethod(ddef: DefDef, oldThis: Symbol, newThis: Symbol): Tree = {
+      oldClassOwner = oldThis
+      newClassOwner = newThis
+      invalidate(ddef.tparams)
+      for (vdef <- ddef.vparamss.flatten) {
+        invalidate(vdef)
+        vdef.tpe = null
+      }
+      ddef.symbol = NoSymbol
+      enterSym(context, ddef)
+      log("remapping this of " + oldClassOwner + " to " + newClassOwner)
+      typed(ddef)
+    }
+    
+    /** Special typer method for re-type checking trees. It expects a typed tree.
+     *  Returns a typed tree that has fresh symbols for all definitions in the original tree.
+     *
+     *  Each definition tree is visited and its symbol added to the invalidSyms map (except LabelDefs),
+     *  then cleared (forcing the namer to create fresh symbols).
+     *  All invalid symbols found in trees are cleared (except for LabelDefs), forcing the
+     *  typechecker to look for fresh ones in the context.
+     *
+     *  Type trees are typed by substituting old symbols for new ones (@see fixType).
+     *
+     *  LabelDefs are not typable from trees alone, unless they have the type ()Unit. Therefore,
+     *  their symbols are recreated ad-hoc and their types are fixed inline, instead of letting the
+     *  namer/typer handle them, or Idents that refer to them.
+     */
+    override def typed(tree: Tree, mode: Int, pt: Type): Tree = {
+      if (settings.debug.value) log("typing " + tree + ": " + tree.tpe)
+      if (tree.hasSymbol && tree.symbol != NoSymbol 
+          && !tree.symbol.isLabel  // labels cannot be retyped by the type checker as LabelDef has no ValDef/return type trees
+          && invalidSyms.isDefinedAt(tree.symbol)) {
+        if (settings.debug.value) log("removed symbol " + tree.symbol)
+        tree.symbol = NoSymbol
+      }
+
+      tree match {
+        case ttree @ TypeTree() =>
+          log("fixing tpe: " + tree.tpe + " with sym: " + tree.tpe.typeSymbol)
+          ttree.tpe = fixType(ttree.tpe)
+          ttree
+        case Block(stats, res) =>
+          log("invalidating block")
+          invalidate(stats)
+          invalidate(res)
+          tree.tpe = null
+          super.typed(tree, mode, pt)
+        
+        case ClassDef(_, _, _, tmpl @ Template(parents, _, stats)) =>
+//          log("invalidating classdef " + tree.tpe)
+          tmpl.symbol = tree.symbol.newLocalDummy(tree.pos)
+          invalidate(stats)
+          tree.tpe = null
+          super.typed(tree, mode, pt)
+
+        case ddef @ DefDef(_, _, _, _, tpt, rhs) =>
+          ddef.tpt.tpe = fixType(ddef.tpt.tpe)
+          ddef.tpe = null
+          super.typed(ddef, mode, pt)
+          
+        case vdef @ ValDef(_, _, tpt, rhs) =>
+//          log("vdef fixing tpe: " + tree.tpe + " with sym: " + tree.tpe.typeSymbol + " and " + invalidSyms)
+          vdef.tpt.tpe = fixType(vdef.tpt.tpe)
+          vdef.tpe = null
+          super.typed(vdef, mode, pt)
+
+        case ldef @ LabelDef(name, params, rhs) =>
+          ldef.tpe = null
+          val params1 = params map { p => Ident(updateSym(p.symbol)) }
+          super.typed(treeCopy.LabelDef(tree, name, params1, rhs), mode, pt)
+
+        case Bind(name, _) =>
+          invalidate(tree)
+          tree.tpe = null
+          super.typed(tree, mode, pt)
+
+        case Ident(_) if tree.symbol.isLabel =>
+          log("Ident to labeldef " + tree + " switched to ")
+          tree.symbol = updateSym(tree.symbol)
+          tree.tpe = null
+          super.typed(tree, mode, pt)
+
+        case Select(th @ This(_), sel) if (oldClassOwner ne null) && (th.symbol == oldClassOwner) =>
+          log("selection on this, no type ascription required")
+          // we use the symbol name instead of the tree name because the symbol may have been
+          // name mangled, rendering the tree name obsolete
+          super.typed(atPos(tree.pos)(Select(This(newClassOwner), tree.symbol.name)), mode, pt)
+
+        case This(_) if (oldClassOwner ne null) && (tree.symbol == oldClassOwner) =>
+//          val tree1 = Typed(This(newClassOwner), TypeTree(fixType(tree.tpe.widen)))
+          val tree1 = This(newClassOwner)
+          if (settings.debug.value) log("mapped " + tree + " to " + tree1)
+          super.typed(atPos(tree.pos)(tree1), mode, pt)
+
+        case This(_) =>
+          tree.symbol = updateSym(tree.symbol)
+          tree.tpe = null
+          super.typed(tree, mode, pt)
+
+        case Super(qual, mix) if (oldClassOwner ne null) && (tree.symbol == oldClassOwner) =>
+          val tree1 = Super(qual, mix)
+          log("changed " + tree + " to " + tree1)
+          super.typed(atPos(tree.pos)(tree1))
+
+        case Match(scrut, cases) =>
+          val scrut1 = typed(scrut, EXPRmode | BYVALmode, WildcardType)
+          val scrutTpe = scrut1.tpe.widen
+          val cases1 = if (scrutTpe.isFinalType) cases filter {
+            case CaseDef(Bind(_, pat @ Typed(_, tpt)), EmptyTree, body) =>
+              // the typed pattern is not incompatible with the scrutinee type
+              scrutTpe.matchesPattern(fixType(tpt.tpe))
+            case CaseDef(Typed(_, tpt), EmptyTree, body) =>
+              // the typed pattern is not incompatible with the scrutinee type
+              scrutTpe.matchesPattern(fixType(tpt.tpe))
+            case _ => true
+          } else cases
+
+          super.typed(atPos(tree.pos)(Match(scrut, cases1)), mode, pt)
+
+        case EmptyTree =>
+          // no need to do anything, in particular, don't set the type to null, EmptyTree.tpe_= asserts 
+          tree
+
+        case _ =>
+          if (tree.hasSymbol && tree.symbol != NoSymbol && (tree.symbol.owner == definitions.AnyClass)) {
+            tree.symbol = NoSymbol // maybe we can find a more specific member in a subclass of Any (see AnyVal members, like ==) 
+          }
+          tree.tpe = null
+          super.typed(tree, mode, pt)
+      }
+    }
+  }
+}
+
diff --git a/src/compiler/scala/tools/nsc/typechecker/EtaExpansion.scala b/src/compiler/scala/tools/nsc/typechecker/EtaExpansion.scala
index fb16e44..a87557f 100644
--- a/src/compiler/scala/tools/nsc/typechecker/EtaExpansion.scala
+++ b/src/compiler/scala/tools/nsc/typechecker/EtaExpansion.scala
@@ -1,10 +1,10 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: EtaExpansion.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.tools.nsc.typechecker
+package scala.tools.nsc
+package typechecker
 
 import scala.collection.mutable.ListBuffer
 import symtab.Flags._
@@ -17,15 +17,15 @@ import symtab.Flags._
 trait EtaExpansion { self: Analyzer =>
 
   import global._
-  import posAssigner.atPos
 
   object etaExpansion {
+    private def isMatch(vparam: ValDef, arg: Tree) = arg match {
+      case Ident(name)  => vparam.name == name
+      case _            => false
+    }
+      
     def unapply(tree: Tree): Option[(List[ValDef], Tree, List[Tree])] = tree match {
-      case Function(vparams, Apply(fn, args)) 
-      if (List.forall2(vparams, args) {
-        case (vparam, Ident(name)) => vparam.name == name
-        case _ => false
-      }) => 
+      case Function(vparams, Apply(fn, args)) if (vparams corresponds args)(isMatch) => // @PP: corresponds
         Some((vparams, fn, args))
       case _ =>
         None
@@ -49,22 +49,18 @@ trait EtaExpansion { self: Analyzer =>
    */
   def etaExpand(unit : CompilationUnit, tree: Tree): Tree = {
     val tpe = tree.tpe
-    val symbolHash = if (!inIDE) "" else Integer.toString(tree.symbol.hashCode, 10 + ('z' - 'a')) + "$"
+    val symbolHash = ""
     var cnt = 0 // for NoPosition
     def freshName(pos : util.Position, n : Int) = {
       cnt += 1
-      if (!inIDE) {
-        newTermName(unit.fresh.newName(pos, "eta$" + (cnt - 1) + "$"))
-      } else if (pos == util.NoPosition) {
-        // nothing we can do, hope for no conflict!
-        newTermName(("eta$" + symbolHash + (cnt - 1)))
-      } else 
-        newTermName(unit.fresh.newName(pos, "eta$" + symbolHash + (cnt - 1) + "$"))
-        // Martin to Sean: I removed the 
-        // else if (n == 0) branch and changed `n' in the line above to `(cnt - 1)'
-        // this was necessary because otherwise curried eta-expansions would get the same
-        // symbol. An example which failes test/files/run/Course-2002-02.scala
-        // todo: review and get rid of the `n' argument (which is unused right now).
+      newTermName(unit.fresh.newName(pos, "eta$" + (cnt - 1) + "$"))
+      // Note - the comment below made more sense before I ripped inIDE out -
+      // I leave it in to give context to the todo: at the bottom.
+      // Martin to Sean: I removed the 
+      // else if (n == 0) branch and changed `n' in the line above to `(cnt - 1)'
+      // this was necessary because otherwise curried eta-expansions would get the same
+      // symbol. An example which fails test/files/run/Course-2002-02.scala
+      // todo: review and get rid of the `n' argument (which is unused right now).
     }
     // { cnt = cnt + 1; newTermName("eta$" + cnt) }
     val defs = new ListBuffer[Tree]
@@ -80,19 +76,34 @@ trait EtaExpansion { self: Analyzer =>
         if (treeInfo.isPureExpr(tree)) tree
         else {
           val vname: Name = freshName(tree.pos, 0)
-          defs += atPos(tree.pos)(ValDef(Modifiers(SYNTHETIC), vname, TypeTree(), tree))
-          Ident(vname) setPos tree.pos
+          // Problem with ticket #2351 here 
+          defs += atPos(tree.pos) {
+            ValDef(Modifiers(SYNTHETIC), vname, TypeTree(), tree)
+          }
+          Ident(vname) setPos tree.pos.focus
         }
-      tree match {
+      val tree1 = tree match {
+        // a partial application using named arguments has the following form:
+        // { val qual$1 = qual
+        //   val x$1 = arg1
+        //   [...]
+        //   val x$n = argn
+        //   qual$1.fun(x$1, ..)..(.., x$n) }
+        // Eta-expansion has to be performed on `fun'
+        case Block(stats, fun) =>
+          defs ++= stats
+          liftoutPrefix(fun)
         case Apply(fn, args) =>
-          copy.Apply(tree, liftoutPrefix(fn), List.mapConserve(args)(liftout)) setType null
+          treeCopy.Apply(tree, liftoutPrefix(fn), args mapConserve (liftout)) setType null
         case TypeApply(fn, args) =>
-          copy.TypeApply(tree, liftoutPrefix(fn), args) setType null
+          treeCopy.TypeApply(tree, liftoutPrefix(fn), args) setType null
         case Select(qual, name) =>
-          copy.Select(tree, liftout(qual), name) setSymbol NoSymbol setType null
+          treeCopy.Select(tree, liftout(qual), name) setSymbol NoSymbol setType null
         case Ident(name) =>
           tree
       }
+      if (tree1 ne tree) tree1 setPos tree1.pos.makeTransparent
+      tree1 
     }
 
     /** Eta-expand lifted tree.
@@ -102,18 +113,13 @@ trait EtaExpansion { self: Analyzer =>
      *  @return     ...
      */
     def expand(tree: Tree, tpe: Type): Tree = tpe match {
-      case mt: ImplicitMethodType =>
-        tree
-      case MethodType(formals, restpe) =>
-        var cnt0 = 0
-        def cnt = {
-          cnt0 += 1
-          cnt0 - 1
-        } 
-        val params = formals map (formal =>
-          ValDef(Modifiers(SYNTHETIC | PARAM), freshName(tree.pos, cnt), TypeTree(formal), EmptyTree))
-        atPos(tree.pos)(Function(params, expand(Apply(tree, params map gen.paramToArg), restpe)))
-        //atPos(tree.pos)(Function(params, expand(Apply(tree, args), restpe)))
+      case mt @ MethodType(paramSyms, restpe) if !mt.isImplicit =>
+        val params = paramSyms map (sym =>
+          ValDef(Modifiers(SYNTHETIC | PARAM), 
+                 sym.name, TypeTree(sym.tpe) , EmptyTree))
+        atPos(tree.pos.makeTransparent) {
+          Function(params, expand(Apply(tree, params map gen.paramToArg), restpe))
+        }
       case _ =>
         tree
     }
diff --git a/src/compiler/scala/tools/nsc/typechecker/IdeSupport.scala b/src/compiler/scala/tools/nsc/typechecker/IdeSupport.scala
deleted file mode 100644
index 19f1645..0000000
--- a/src/compiler/scala/tools/nsc/typechecker/IdeSupport.scala
+++ /dev/null
@@ -1,375 +0,0 @@
-package scala.tools.nsc.typechecker;
-import scala.collection.jcl.WeakHashMap
-trait IdeSupport extends Analyzer {
-  val global : Global with symtab.IdeSupport
-  import global._ 
-
-  private class ContextInternMap extends WeakHashMap[Context,ref.WeakReference[Context]] {
-    var last : Context = _
-    override def default(txt : Context) : ref.WeakReference[Context] = {
-      if (txt eq NoContext) new ref.WeakReference(NoContext)
-      val txt0 = txt.intern0
-      last = txt0 // to prevent collection
-      val ret = new ref.WeakReference(txt0)
-      this(txt0) = ret
-      ret
-    }
-    def intern(txt : Context) = this(txt).get.get
-  }
-  private val internMap = new ContextInternMap
-  override def intern(txt : Context) = 
-    if (false) super.intern(txt)
-    else if (txt.outer eq txt) txt
-    else internMap.intern(txt)
-
-  override def newNamer(context : Context) : Namer = new Namer(context)
-  class Namer(context: Context) extends super.Namer(context) {
-    override protected def setInfo[Sym <: Symbol](sym : Sym)(tpe : LazyType) : Sym = {
-      assert(!sym.hasRawInfo || sym.rawInfo == NoType) // type information has already been reset.
-      if (currentClient.makeNoChanges) {
-        sym.setInfo(tpe)
-        try {
-          sym.info  // force completion.
-        } catch {
-          case e =>
-        }
-        return sym
-      }
-      object tpe0 extends LazyType with SimpleTypeProxy {
-        override def underlying = tpe
-        override def complete(sym0 : Symbol) : Unit = {
-          if (sym ne sym0) {
-            logError("DUPLICATE: " + sym.fullNameString + " "+sym.id + " vs. " + sym0.id, null)
-            toComplete -= sym0
-          }
-          toComplete -= sym
-          val pos = sym0.pos match {
-          case pos : TrackedPosition => pos
-          }
-          val oldType = oldTypeFor(sym0)
-          oldType match {
-            case PolyType(xxx,_) => 
-              val i = xxx.elements
-              var pause = false
-              while (i.hasNext) {
-                if (i.next.pos == util.NoPosition) pause = true
-              }
-              if (pause) {
-                assert(true)
-              }
-            case _=>
-          }
-          assert(sym0.rawInfo == this)
-          val hadTypeErrors = pos.owner != null && pos.owner.hasTypeErrors
-          if (pos.owner == null) underlying.complete(sym0) else pos.owner.activate(try {
-            underlying.complete(sym0)
-          } catch {
-          case te : TypeError => 
-            pos.owner.typeError(te.getMessage)
-            sym0.setInfo(ErrorType)
-          })
-          (oldType,sym0.info) match {
-            case (PolyType(xxx,_),PolyType(yyy,_)) if xxx != yyy =>
-              val oldc = xxx
-              val newc = yyy
-              Console.print("DIFF old=" + oldc.map(sym => sym0 + ":" + sym0.pos).mkString("",",",""))
-              Console.println(" new=" + newc.map(sym => sym0+ ":" + sym0.pos).mkString("",",",""))
-            case _ =>
-          }
-          
-          //if (!hadTypeErrors && pos.owner != null && pos.owner.hasTypeErrors) pos.owner.dirtyTyped
-          if (pos.owner != null && pos.owner.hasTypeErrors && (!sym0.rawInfo.isComplete || sym0.info == NoType || sym0.info == ErrorType)) {
-            // go back to original type.
-            val oldType = oldTypeFor(sym0)
-            if (oldType != NoType)
-              sym0.setInfo(oldType)
-          }
-        }
-      }
-      toComplete += sym
-      super.setInfo(sym)(tpe0)
-    }
-    override def enterSym(tree : Tree) : Context = tree match {
-    case tree : StubTree =>
-      if (tree.symbol == NoSymbol) // reset stub symbol on refresh.
-        tree.symbol = tree.underlying.updateNamer(this)
-      context
-    case tree => super.enterSym(tree)
-    }
-  }
-  override def newTyper(txt : Context) : Typer = new Typer(txt)
-  class Typer(context : Context) extends super.Typer(context) {
-    override def qualifyingClassContext(tree: Tree, qual: Name): Context = {
-      if (qual.isEmpty) super.qualifyingClassContext(tree, qual)
-      else {
-        var c = context.enclClass
-        val client = currentClient
-        while (c != NoContext && {
-          // register dependency. 
-          client.notify(qual, c.owner)
-          c.owner.owner.info.decls match {
-          case scope : HookedScope => scope.record(client, qual)
-          case _ =>
-          }
-          true
-        } && c.owner.name != qual) c = c.outer.enclClass
-        c
-      }
-    }
-    // no adapting.
-    override protected def adapt(tree: Tree, mode: Int, pt: Type): Tree = super.adapt(tree,mode,pt)
-    override def typed1(tree: Tree, mode: Int, pt: Type): Tree = tree match {
-    case tree : StubTree => 
-      if (tree.tpe == null) 
-        tree.tpe = tree.underlying.updateTyper(this, mode, pt)
-      tree
-    case tree => 
-      try {
-        super.typed1(tree, mode, pt)
-      } catch {
-        case e : TypeError => throw e
-        case e : Error => global.check(false, "tree: " + tree + " " + e); throw e
-      }
-    } 
-  }
-  private val toComplete = new scala.collection.jcl.LinkedHashSet[Symbol]
-  def finishTyping = while (!toComplete.isEmpty) {
-    toComplete.toList.foreach(sym => if (sym.pos match {
-    case pos : TrackedPosition if !pos.isValid => toComplete.remove(sym); false
-    case _ => true
-    }){
-      if (sym.info.isComplete) toComplete.remove(sym)
-      else {
-        sym.info
-        if (!sym.info.isComplete) {
-          Console.println("not-completing: " + sym)
-          toComplete remove sym
-        }
-      }
-    })
-  }
-
-  trait TrackedPosition extends global.TrackedPosition {
-    def owner : MemoizedTree
-    def isValid : Boolean
-  }
-  trait MemoizedTree {
-    def kind : TreeKind
-    def pos : TrackedPosition
-    def typeIsDirty : Boolean
-    def dirtyTyped : Unit
-    def useTrees : List[Tree]
-    def setUseTrees(uses : List[Tree]) : Unit
-    def lastTyped : List[Tree]
-    def activate(f : => Unit) : Unit
-    def typeError(msg : String) : Unit
-    def hasTypeErrors : Boolean
-    def shouldBeTyped : Boolean = true
-    // probably invalidate parent if its not being validated now
-    // most type changes detected via setType.
-    protected def typeChanged : Unit
-    protected def highlightChanged : Unit
-    def lastSymbol = if (lastTyped.isEmpty) NoSymbol else lastTyped.last.symbol
-    def lastType = if (lastTyped.isEmpty) null else lastTyped.last.tpe
-    protected var namerTxt : Context = NoContext
-    protected var typerTxt : Context = NoContext
-    protected var mode : Int = 0
-    protected var pt : Type = NoType
-
-    def doNamer = if (namerTxt ne NoContext) updateNamer(newNamer(namerTxt))
-    def updateNamer(namer : Namer) : Symbol = {
-      val makeNoChanges = currentClient.makeNoChanges
-      val namerTxt = intern(namer.context)
-      if (!makeNoChanges && (this.namerTxt ne namerTxt)) {
-        assert(namerTxt.scope ne EmptyScope)
-        assert(namerTxt.owner ne NoSymbol)
-        this.namerTxt = namerTxt
-        dirtyTyped
-      }
-      val lastSymbol = this.lastSymbol
-
-      def fakeUpdate(trees : List[Tree]) : Symbol = { trees.foreach{
-      case tree : DefTree if (tree.symbol != NoSymbol && tree.symbol != null) =>
-        // becareful, the symbol could have been rentered!
-        var e = namer.context.scope.lookupEntry(tree.symbol.name)
-        while (e != null && e.sym != tree.symbol) e = namer.context.scope.lookupNextEntry(e)
-        if (e == null) {
-          //Console.println("FK-ENTER: " + tree.symbol)
-          val sym = namer.enterInScope(tree.symbol)
-          if (sym != tree.symbol) {
-            Console.println("BAD: " + sym + " " + sym.id + " vs. " + tree.symbol.id)
-          }
-          import symtab.Flags._
-          val set = reuseMap.get(namer.context.scope.asInstanceOf[PersistentScope])
-          // could be getter or local, then we need to re-add getter/setter
-          if (sym.isGetter && set.isDefined) 
-            set.get.find(sym0 => sym0.name == nme.getterToSetter(sym.name) && sym0.isSetter) match {
-          case None => 
-          case Some(setter) =>
-            val setter0 = namer.enterInScope(setter)
-            assert(setter0 == setter)
-          } else if (sym.hasGetter && set.isDefined) 
-            set.get.find(sym0 => {
-              sym0.name == nme.getterName(sym.name) && 
-                sym0.isGetter
-            }) match {
-          case None =>
-          case Some(getter) =>
-            val getter0 = namer.enterInScope(getter)
-            assert(getter0 == getter)
-            if (set.isDefined) 
-              set.get.find(sym => sym.name == nme.getterToSetter(getter.name) && sym.isSetter) match {
-            case None => 
-            case Some(setter) =>
-              val setter0 = namer.enterInScope(setter)
-              assert(setter0 == setter)
-            }
-          } else if (sym.hasFlag(symtab.Flags.LAZY) && sym.lazyAccessor != NoSymbol) {
-              if (set.get.find(sym0 => sym0 == sym.lazyAccessor).isDefined) {
-                namer.enterInScope(sym.lazyAccessor)
-              }
-          }
-        } 
-      case _ =>
-      }; if (trees.isEmpty) NoSymbol else trees.last.symbol }
-      import symtab.Flags._
-      if (!typeIsDirty) lastTyped.foreach{
-      case tree :DefTree if tree.symbol != null && tree.symbol != NoSymbol && tree.symbol.isClass && tree.symbol.hasFlag(CASE) => 
-        var e = namer.context.scope.lookupEntry(tree.symbol.name.toTermName)
-        while (e != null && !e.sym.hasFlag(MODULE)) e = namer.context.scope.lookupNextEntry(e)
-        Console.println("CHECKING: " + e + " " + (if (e != null) caseClassOfModuleClass.contains(e.sym.moduleClass)))
-        if (e == null) dirtyTyped
-        // we don't clear caseClassOfModuleClass unless we have to.
-        else if (!caseClassOfModuleClass.contains(e.sym.moduleClass)) dirtyTyped
-      case tree : DefTree if tree.symbol != null && tree.symbol != NoSymbol =>
-      case _ =>
-      }
-      
-      if (makeNoChanges) {}
-      else if (!typeIsDirty && !lastTyped.isEmpty) 
-        return fakeUpdate(lastTyped)
-      else if (namerTxt != NoContext && shouldBeTyped) {} else return fakeUpdate(lastTyped)
-      val use = useTrees
-      if (makeNoChanges) {}
-      else if (use.isEmpty || use.last.symbol != NoSymbol) {
-        return fakeUpdate(use) // already named
-      }
-      
-      if (kind.isTop) namer.context.unit.source.file match {
-      case file : io.PlainFile => reloadSource(file)
-      case _ =>
-      }
-      // before we retype, unlink/recycle our previously defined symbols.
-      if (!makeNoChanges) lastTyped.foreach{tree => 
-        if (tree.symbol != NoSymbol && tree.symbol != null) (namer.context.scope,tree) match {
-        case (scope : PersistentScope,tree : DefTree) => if (!tree.symbol.isPackage) reuse(scope, tree.symbol) 
-        case _ => 
-        }
-      }
-      activate(try {
-        use.foreach{tree => 
-          namer.enterSym(tree)
-        }
-      } catch {
-        case te : TypeError => typeError(te.getMessage)
-      })
-      if (!makeNoChanges) use.foreach{tree=>
-        if (tree.symbol != null && 
-            tree.symbol.isClass && 
-            tree.symbol.hasFlag(symtab.Flags.CASE) && 
-            tree.symbol.owner != null &&   
-            tree.symbol.owner.rawInfo.isComplete) {
-          var e = tree.symbol.owner.info.decls.lookupEntry(tree.symbol.name.toTermName)
-          if (e != null) e.sym.pos match { // retype the object if its in the scope. 
-          case pos : TrackedPosition if pos.owner != null && pos.owner != MemoizedTree.this => 
-            pos.owner.dirtyTyped // hope this works!
-          case _ => 
-          }
-          ()
-        }
-      }
-      if (makeNoChanges) {}
-      else if (hasTypeErrors && lastSymbol != null && lastSymbol != NoSymbol && use.last.symbol != lastSymbol) {
-        if (use.last.symbol != null && use.last.symbol != NoSymbol) {
-          namer.context.scope unlink use.last.symbol
-        }
-        Console.println("ER-LINK: " + lastSymbol)
-        val sym = namer.enterInScope(lastSymbol)
-        assert(sym == lastSymbol)
-        use.last.symbol = lastSymbol
-      }
-      if (lastSymbol != NoSymbol && lastSymbol != use.last.symbol) {
-        assert(true)
-      }
-      use.last.symbol
-    }
-    def doTyper = try {
-      if (typerTxt ne NoContext) updateTyper(newTyper(typerTxt), mode, pt)
-    } catch {
-      case e => logError("doTyper crash", e)
-    }
-    def updateTyper(typer : Typer, mode : Int, pt : Type) : Type = {
-      val typerTxt = intern(typer.context)
-      val makeNoChanges = currentClient.makeNoChanges
-      if (!makeNoChanges && ((this.typerTxt ne typerTxt) || (this.pt != pt) || (this.mode != mode))) {
-        this.typerTxt = typerTxt
-        this.pt = pt
-        this.mode = mode
-        dirtyTyped
-      }
-      val lastType = this.lastType
-      if (makeNoChanges) {}
-      else if (typeIsDirty && shouldBeTyped && typerTxt != NoContext) {
-        
-      } else if (lastType == null) {
-        return NoType
-      } else return lastType
-      var use = useTrees
-      if (use.isEmpty) return lastType; 
-      if ((use.last.tpe != null)) return use.last.tpe
-      if (use.last.symbol == NoSymbol && namerTxt != NoContext)
-        updateNamer(newNamer(namerTxt))
-      if (makeNoChanges) {
-        assert(true)
-      }
-      activate(try {
-        setUseTrees{use = use.map{typer.typed(_,mode,pt)}; use}
-      } catch {
-        case te : TypeError => typeError(te.getMessage)
-      })
-      if (!makeNoChanges && hasTypeErrors && lastType != null) {
-        use.last.tpe = lastType
-      }
-      if (!makeNoChanges && !hasTypeErrors && use.last.tpe != null && lastType != null && 
-          !compareTypes(use.last.tpe, lastType,Nil)(_.info)) { 
-        // the type changed in a good way.
-        typeChanged
-      }
-      if (!makeNoChanges && (use.length != lastTyped.length || !use.zip(lastTyped).forall{
-        case (t0,t1) => t0.equalsStructure0(t1){
-        case (t0:StubTree,t1:StubTree) if t0.underlying == t0.underlying || true => true
-        case _ => false
-        }
-      })) {
-        highlightChanged
-      }
-      if (use.last.tpe == null) ErrorType else use.last.tpe
-    }
-  }
-  trait StubTree extends global.StubTree {
-    def underlying : MemoizedTree
-    override var symbol : Symbol = NoSymbol
-    override def duplicate : this.type = this //throw new Error("not supported") 
-    override def isType = underlying.kind.isType
-    override def isTerm = underlying.kind.isTerm
-    override def isDef = underlying.kind.isDef
-    override def hasSymbol = underlying.kind.hasSymbol
-    override def hashCode = underlying.hashCode
-    override def equals(that : Any) = that match {
-    case that : StubTree => that.underlying == underlying
-    case _ => false
-    }
-    override def toString = "st-" + underlying.toString
-    override def pos = util.NoPosition
-  }
-}
diff --git a/src/compiler/scala/tools/nsc/typechecker/Implicits.scala b/src/compiler/scala/tools/nsc/typechecker/Implicits.scala
new file mode 100644
index 0000000..2453a6a
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/typechecker/Implicits.scala
@@ -0,0 +1,980 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
+ * @author  Martin Odersky
+ */
+
+//todo: rewrite or disllow new T where T is a mixin (currently: <init> not a member of T)
+//todo: use inherited type info also for vars and values
+//todo: disallow C#D in superclass
+//todo: treat :::= correctly
+package scala.tools.nsc
+package typechecker
+
+import scala.collection.mutable.{LinkedHashMap, ListBuffer}
+import scala.tools.nsc.util.{HashSet, Set, SourceFile}
+import symtab.Flags._
+import util.Statistics._
+
+/** This trait provides methods to find various kinds of implicits.
+ *
+ *  @author  Martin Odersky
+ *  @version 1.0
+ */
+trait Implicits {
+self: Analyzer =>
+
+  import global._
+  import definitions._
+
+  def traceImplicits = printTypings
+  import global.typer.{printTyping, deindentTyping, indentTyping}
+
+  /** Search for an implicit value. See the comment on `result` at the end of class `ImplicitSearch`
+   *  for more info how the search is conducted. 
+   *  @param tree             The tree for which the implicit needs to be inserted.
+   *                          (the inference might instantiate some of the undetermined
+   *                          type parameters of that tree.
+   *  @param pt               The expected type of the implicit.
+   *  @param reportAmbiguous  Should ambiguous implicit errors be reported?
+   *                          False iff we search for a view to find out
+   *                          whether one type is coercible to another.
+   *  @param isView           We are looking for a view
+   *  @param context          The current context
+   *  @return                 A search result
+   */
+  def inferImplicit(tree: Tree, pt: Type, reportAmbiguous: Boolean, isView: Boolean, context: Context): SearchResult = {
+    printTyping("Beginning implicit search for "+ tree +" expecting "+ pt + (if(isView) " looking for a view" else ""))
+    indentTyping()
+    val rawTypeStart = startCounter(rawTypeImpl)
+    val findMemberStart = startCounter(findMemberImpl)
+    val subtypeStart = startCounter(subtypeImpl)
+    val start = startTimer(implicitNanos)
+    if (traceImplicits && !tree.isEmpty && !context.undetparams.isEmpty)
+      println("typing implicit with undetermined type params: "+context.undetparams+"\n"+tree)
+    val result = new ImplicitSearch(tree, pt, isView, context.makeImplicit(reportAmbiguous)).bestImplicit
+    context.undetparams = context.undetparams filterNot (result.subst.from contains _)
+    stopTimer(implicitNanos, start)
+    stopCounter(rawTypeImpl, rawTypeStart)
+    stopCounter(findMemberImpl, findMemberStart)
+    stopCounter(subtypeImpl, subtypeStart)
+    deindentTyping()
+    printTyping("Implicit search yielded: "+ result)
+    result
+  }
+
+  final val sizeLimit = 50000
+  val implicitsCache = new LinkedHashMap[Type, List[List[ImplicitInfo]]]
+
+  def resetImplicits() { implicitsCache.clear() }
+
+  /** If type `pt` an instance of Manifest or OptManifest, or an abstract type lower-bounded
+   *  by such an instance?
+   */
+  def isManifest(pt: Type): Boolean = pt.dealias match {
+    case TypeRef(_, PartialManifestClass, List(_)) | 
+         TypeRef(_, FullManifestClass, List(_)) |
+         TypeRef(_, OptManifestClass, List(_)) => true
+    case TypeRef(_, tsym, _) => tsym.isAbstractType && isManifest(pt.bounds.lo)
+    case _ => false
+  }
+
+  /** The result of an implicit search
+   *  @param  tree    The tree representing the implicit
+   *  @param  subst   A substituter that represents the undetermined type parameters
+   *                  that were instantiated by the winning implicit.
+   */
+  class SearchResult(val tree: Tree, val subst: TreeTypeSubstituter) {
+    override def toString = "SearchResult("+tree+", "+subst+")"
+  }
+
+  lazy val SearchFailure = new SearchResult(EmptyTree, EmptyTreeTypeSubstituter)
+
+  /** A class that records an available implicit
+   *  @param   name   The name of the implicit
+   *  @param   pre    The prefix type of the implicit
+   *  @param   sym    The symbol of the implicit
+   */
+  class ImplicitInfo(val name: Name, val pre: Type, val sym: Symbol) {
+    private var tpeCache: Type = null
+
+    /** Computes member type of implicit from prefix `pre` (cached). */
+    def tpe: Type = {
+      if (tpeCache eq null) tpeCache = pre.memberType(sym)
+      tpeCache
+    }
+
+    /** Does type `tp` contain an Error type as parameter or result?
+     */
+    private def containsError(tp: Type): Boolean = tp match {
+      case PolyType(tparams, restpe) => 
+        containsError(restpe)
+      case MethodType(params, restpe) => 
+        for (p <- params)
+          if (p.tpe.isError) return true
+        containsError(restpe)
+      case _ => 
+        tp.isError
+    }
+
+    def isCyclicOrErroneous = try {
+      containsError(tpe)
+    } catch {
+      case ex: CyclicReference =>
+        true
+    }
+
+    override def equals(other: Any) = other match {
+      case that: ImplicitInfo => 
+          this.name == that.name &&
+          this.pre =:= that.pre &&
+          this.sym == that.sym
+      case _ => false
+    }
+
+    override def hashCode = name.## + pre.## + sym.##
+
+    override def toString = "ImplicitInfo(" + name + "," + pre + "," + sym + ")"
+  }
+
+  /** A sentinel indicating no implicit was found */
+  val NoImplicitInfo = new ImplicitInfo(null, NoType, NoSymbol) {
+    // equals used to be implemented in ImplicitInfo with an `if(this eq NoImplicitInfo)` 
+    // overriding the equals here seems cleaner and benchmarks show no difference in performance 
+    override def equals(other: Any) = other match { case that: AnyRef => that eq this  case _ => false }
+    override def hashCode = 1
+  }
+
+  /** A constructor for types ?{ name: tp }, used in infer view to member
+   *  searches.
+   */
+  def memberWildcardType(name: Name, tp: Type) = {
+    val result = refinedType(List(WildcardType), NoSymbol)
+    var psym = if (name.isTypeName) result.typeSymbol.newAbstractType(NoPosition, name) 
+               else result.typeSymbol.newValue(NoPosition, name)
+    psym setInfo tp
+    result.decls enter psym
+    result
+  }
+
+  /** An extractor for types of the form ? { name: ? }
+   */
+  object HasMember {
+    def apply(name: Name): Type = memberWildcardType(name, WildcardType)
+    def unapply(pt: Type): Option[Name] = pt match {
+      case RefinedType(List(WildcardType), decls) =>
+        decls.toList match {
+          case List(sym) if (sym.tpe == WildcardType) => Some(sym.name)
+          case _ => None
+        }
+      case _ =>
+        None
+    }
+  }
+
+  /** An extractor for types of the form ? { name: (? >: argtpe <: Any*)restp }
+   */
+  object HasMethodMatching {
+    def apply(name: Name, argtpes: List[Type], restpe: Type): Type = {
+      def templateArgType(argtpe: Type) =
+        new BoundedWildcardType(TypeBounds(argtpe, AnyClass.tpe))
+      val dummyMethod = new TermSymbol(NoSymbol, NoPosition, "typer$dummy")
+      val mtpe = MethodType(dummyMethod.newSyntheticValueParams(argtpes map templateArgType), restpe)
+      memberWildcardType(name, mtpe)
+    }
+    def unapply(pt: Type): Option[(Name, List[Type], Type)] = pt match {
+      case RefinedType(List(WildcardType), decls) =>
+        decls.toList match {
+          case List(sym) =>
+            sym.tpe match {
+              case MethodType(params, restpe) 
+              if (params forall (_.tpe.isInstanceOf[BoundedWildcardType])) => 
+                Some((sym.name, params map (_.tpe.bounds.lo), restpe))
+              case _ => None
+            }
+          case _ => None
+        }
+      case _ => None
+    }
+  }
+
+  /** An extractor for unary function types arg => res
+   */
+  object Function1 {
+    def unapply(tp: Type) = tp match {
+      case TypeRef(_, sym, List(arg, res)) if (sym == FunctionClass(1)) => Some(arg, res)
+      case _ => None
+    }
+  }
+
+  /** A class that sets up an implicit search. For more info, see comments for `inferImplicit`.
+   *  @param tree             The tree for which the implicit needs to be inserted.
+   *  @param pt               The original expected type of the implicit.
+   *  @param isView           We are looking for a view
+   *  @param context0         The context used for the implicit search
+   */
+  class ImplicitSearch(tree: Tree, pt: Type, isView: Boolean, context0: Context) 
+    extends Typer(context0) {
+    printTyping("begin implicit search: "+(tree, pt, isView, context.outer.undetparams))
+//    assert(tree.isEmpty || tree.pos.isDefined, tree)
+
+    import infer._
+    /** Is implicit info `info1` better than implicit info `info2`?
+     */
+    def improves(info1: ImplicitInfo, info2: ImplicitInfo) = {
+      incCounter(improvesCount)
+      (info2 == NoImplicitInfo) ||
+      (info1 != NoImplicitInfo) &&
+      isStrictlyMoreSpecific(info1.tpe, info2.tpe, info1.sym, info2.sym)
+    }
+
+    /** Map all type params in given list to WildcardType
+     *  @param   tp  The type in which to do the mapping
+     *  @param   tparams  The list of type parameters to map
+     */
+    private def tparamsToWildcards(tp: Type, tparams: List[Symbol]) =
+      tp.instantiateTypeParams(tparams, tparams map (t => WildcardType))
+
+    /* Map a polytype to one in which all type parameters and argument-dependent types are replaced by wildcards.
+     * Consider `implicit def b(implicit x: A): x.T = error("")`. We need to approximate DebruijnIndex types 
+     * when checking whether `b` is a valid implicit, as we haven't even searched a value for the implicit arg `x`,
+     * so we have to approximate (otherwise it is excluded a priori).
+     */
+    private def depoly(tp: Type): Type = tp match {
+      case PolyType(tparams, restpe) => tparamsToWildcards(ApproximateDependentMap(restpe), tparams)
+      case _ => ApproximateDependentMap(tp)
+    }
+
+    /** Does type `dtor` dominate type `dted`?
+     *  This is the case if the stripped cores `dtor1` and `dted1` of both types are
+     *  the same wrt `=:=`, or if they overlap and the complexity of `dtor1` is higher
+     *  than the complexity of `dted1`.
+     *  The _stripped core_ of a type is the type where
+     *   - all refinements and annotations are dropped,
+     *   - all universal and existential quantification is eliminated
+     *     by replacing variables by their upper bounds,
+     *   - all remaining free type parameters in the type are replaced by WildcardType.
+     *  The _complexity_ of a stripped core type corresponds roughly to the number of
+     *  nodes in its ast, except that singleton types are widened before taking the complexity.
+     *  Two types overlap if they have the same type symbol, or
+     *  if one or both are intersection types with a pair of overlapiing parent types.
+     */
+    private def dominates(dtor: Type, dted: Type): Boolean = {
+      def core(tp: Type): Type = tp.normalize match {
+        case RefinedType(parents, defs) => intersectionType(parents map core, tp.typeSymbol.owner)
+        case AnnotatedType(annots, tp, selfsym) => core(tp)
+        case ExistentialType(tparams, result) => core(result).subst(tparams, tparams map (t => core(t.info.bounds.hi)))
+        case PolyType(tparams, result) => core(result).subst(tparams, tparams map (t => core(t.info.bounds.hi)))
+        case _ => tp
+      }
+      def stripped(tp: Type): Type = {
+        val tparams = freeTypeParametersNoSkolems.collect(tp)
+        tp.subst(tparams, tparams map (t => WildcardType))
+      }
+      def sum(xs: List[Int]) = (0 /: xs)(_ + _)
+      def complexity(tp: Type): Int = tp.normalize match {
+        case NoPrefix =>
+          0
+        case SingleType(pre, sym) => 
+          if (sym.isPackage) 0 else complexity(tp.widen)
+        case TypeRef(pre, sym, args) => 
+          complexity(pre) + sum(args map complexity) + 1
+        case RefinedType(parents, _) => 
+          sum(parents map complexity) + 1
+        case _ => 
+          1
+      }
+      def overlaps(tp1: Type, tp2: Type): Boolean = (tp1, tp2) match {
+        case (RefinedType(parents, _), _) => parents exists (overlaps(_, tp2))
+        case (_, RefinedType(parents, _)) => parents exists (overlaps(tp1, _))
+        case _ => tp1.typeSymbol == tp2.typeSymbol
+      }
+      val dtor1 = stripped(core(dtor))
+      val dted1 = stripped(core(dted))
+      overlaps(dtor1, dted1) && (dtor1 =:= dted1 || complexity(dtor1) > complexity(dted1))
+    }
+
+    incCounter(implicitSearchCount)
+
+    /** Issues an error signalling ambiguous implicits */
+    private def ambiguousImplicitError(info1: ImplicitInfo, info2: ImplicitInfo, 
+                               pre1: String, pre2: String, trailer: String) =
+      if (!info1.tpe.isErroneous && !info2.tpe.isErroneous) {
+        val coreMsg = 
+          pre1+" "+info1.sym+info1.sym.locationString+" of type "+info1.tpe+"\n "+
+          pre2+" "+info2.sym+info2.sym.locationString+" of type "+info2.tpe+"\n "+
+          trailer
+        error(tree.pos, 
+          if (isView) {
+            val found = pt.typeArgs(0)
+            val req = pt.typeArgs(1)
+            
+            /** A nice spot to explain some common situations a little
+             *  less confusingly.
+             */
+            def explanation = {
+              if ((found =:= AnyClass.tpe) && (AnyRefClass.tpe <:< req))
+                "Note: Any is not implicitly converted to AnyRef.  You can safely\n" +
+                "pattern match x: AnyRef or cast x.asInstanceOf[AnyRef] to do so."
+              else if ((found <:< AnyValClass.tpe) && (AnyRefClass.tpe <:< req))
+                "Note: primitive types are not implicitly converted to AnyRef.\n" +
+                "You can safely force boxing by casting x.asInstanceOf[AnyRef]."
+              else
+                "Note that implicit conversions are not applicable because they are ambiguous:\n "+
+                coreMsg+"are possible conversion functions from "+ found+" to "+req
+            }
+            
+            typeErrorMsg(found, req) + "\n" + explanation
+          }
+          else {
+            "ambiguous implicit values:\n "+coreMsg + "match expected type "+pt
+          })
+        }
+
+    /** The type parameters to instantiate */
+    val undetParams = if (isView) List() else context.outer.undetparams
+
+    /** Replace undetParams in type `tp` by Any/Nothing, according to variance */
+    def approximate(tp: Type) = 
+      tp.instantiateTypeParams(undetParams, undetParams map (_ => WildcardType))
+
+    val wildPt = approximate(pt)
+
+    /** Try to construct a typed tree from given implicit info with given
+     *  expected type.
+     *  Detect infinite search trees for implicits.
+     *
+     *  @param info    The given implicit info describing the implicit definition
+     *  @pre           <code>info.tpe</code> does not contain an error
+     */
+    private def typedImplicit(info: ImplicitInfo): SearchResult = 
+      (context.openImplicits find { case (tp, sym) => sym == tree.symbol && dominates(pt, tp)}) match {
+         case Some(pending) =>
+           // println("Pending implicit "+pending+" dominates "+pt+"/"+undetParams) //@MDEBUG
+           throw DivergentImplicit
+           SearchFailure 
+         case None =>
+           try {
+             context.openImplicits = (pt, tree.symbol) :: context.openImplicits
+             // println("  "*context.openImplicits.length+"typed implicit "+info+" for "+pt) //@MDEBUG
+             typedImplicit0(info)
+           } catch {
+             case DivergentImplicit => 
+               // println("DivergentImplicit for pt:"+ pt +", open implicits:"+context.openImplicits) //@MDEBUG
+               if (context.openImplicits.tail.isEmpty) {
+                 if (!(pt.isErroneous))
+                   context.unit.error(
+                     tree.pos, "diverging implicit expansion for type "+pt+"\nstarting with "+
+                     info.sym+info.sym.locationString)
+                 SearchFailure
+               } else {
+                 throw DivergentImplicit
+               }
+           } finally {
+             context.openImplicits = context.openImplicits.tail
+           }
+       }
+
+    private def typedImplicit0(info: ImplicitInfo): SearchResult = {
+
+      /** Todo reconcile with definition of stability given in Types.scala */
+      def isStable(tp: Type): Boolean = tp match {
+        case TypeRef(pre, sym, _) => 
+          sym.isPackageClass || 
+          sym.isModuleClass && isStable(pre) /*||
+          sym.isAliasType && isStable(tp.normalize)*/
+        case _ => tp.isStable
+      }
+
+      /** Does type `tp' match expected type `pt'
+       *  This is the case if either `pt' is a unary function type with a
+       *  HasMethodMatching type as result, and `tp' is a unary function
+       *  or method type whose result type has a method whose name and type
+       *  correspond to the HasMethodMatching type,
+       *  or otherwise if `tp' is compatible with `pt'.
+       *  This method is performance critical: 5-8% of typechecking time.
+       */
+      def matchesPt(tp: Type, pt: Type, undet: List[Symbol]) = {
+        val start = startTimer(matchesPtNanos)
+        val result = normSubType(tp, pt) || isView && {
+          pt match {
+            case Function1(arg, res) =>
+              matchesPtView(tp, arg, res, undet)
+            case _ =>
+              false
+          }
+        }
+        stopTimer(matchesPtNanos, start)
+        result
+      }
+
+      def matchesPtView(tp: Type, ptarg: Type, ptres: Type, undet: List[Symbol]): Boolean = tp match {
+        case mt @ MethodType(params, restpe) =>
+          if (mt.isImplicit) matchesPtView(restpe, ptarg, ptres, undet)
+          else params.length == 1 && matchesArgRes(params.head.tpe, restpe, ptarg, ptres, undet)
+        case ExistentialType(tparams, qtpe) =>
+          matchesPtView(normalize(qtpe), ptarg, ptres, undet)
+        case Function1(arg1, res1) =>
+          matchesArgRes(arg1, res1, ptarg, ptres, undet)
+        case _ => false
+      }
+
+      def matchesArgRes(tparg: Type, tpres: Type, ptarg: Type, ptres: Type, undet: List[Symbol]): Boolean = 
+        (ptarg weak_<:< tparg) && {
+          ptres match {
+            case HasMethodMatching(name, argtpes, restpe) =>
+              (tpres.member(name) filter (m => 
+                isApplicableSafe(undet, m.tpe, argtpes, restpe))) != NoSymbol
+            case _ =>
+              tpres <:< ptres
+          }
+        }
+
+      incCounter(plausiblyCompatibleImplicits)
+
+      printTyping("typed impl for "+wildPt+"? "+info.name +":"+ depoly(info.tpe)+ " orig info= "+ info.tpe +"/"+undetParams+"/"+isPlausiblyCompatible(info.tpe, wildPt)+"/"+matchesPt(depoly(info.tpe), wildPt, List())+"/"+info.pre+"/"+isStable(info.pre))
+      if (matchesPt(depoly(info.tpe), wildPt, List()) && isStable(info.pre)) {
+
+        incCounter(matchingImplicits)
+
+        val itree = atPos(tree.pos.focus) {
+          if (info.pre == NoPrefix) Ident(info.name) 
+          else Select(gen.mkAttributedQualifier(info.pre), info.name)
+        } 
+        printTyping("typedImplicit0 typing"+ itree +" with wildpt = "+ wildPt +" from implicit "+ info.name+":"+info.tpe)
+        def fail(reason: String): SearchResult = {
+          if (settings.XlogImplicits.value)
+            inform(itree+" is not a valid implicit value for "+pt+" because:\n"+reason)
+          SearchFailure
+        }
+        try {
+          val itree1 = 
+            if (isView)
+              typed1 (
+                atPos(itree.pos) (
+                  Apply(itree, List(Ident("<argument>").setType(approximate(pt.typeArgs.head))))), 
+                EXPRmode, approximate(pt.typeArgs.tail.head)
+              )
+            else
+              typed1(itree, EXPRmode, wildPt)
+
+          incCounter(typedImplicits)
+
+          printTyping("typed implicit "+itree1+":"+itree1.tpe+", pt = "+wildPt)
+          val itree2 = if (isView) (itree1: @unchecked) match { case Apply(fun, _) => fun }
+                       else adapt(itree1, EXPRmode, wildPt)
+          printTyping("adapted implicit "+itree1.symbol+":"+itree2.tpe+" to "+wildPt)
+          def hasMatchingSymbol(tree: Tree): Boolean = (tree.symbol == info.sym) || {
+            tree match {
+              case Apply(fun, _) => hasMatchingSymbol(fun)
+              case TypeApply(fun, _) => hasMatchingSymbol(fun)
+              case Select(pre, name) => name == nme.apply && pre.symbol == info.sym
+              case _ => false
+            }
+          }
+
+          if (itree2.tpe.isError) SearchFailure
+          else if (hasMatchingSymbol(itree1)) {
+            val tvars = undetParams map freshVar
+            if (matchesPt(itree2.tpe, pt.instantiateTypeParams(undetParams, tvars), undetParams)) {
+              printTyping("tvars = "+tvars+"/"+(tvars map (_.constr)))
+              val targs = solvedTypes(tvars, undetParams, undetParams map varianceInType(pt),
+                                      false, lubDepth(List(itree2.tpe, pt)))
+
+              // #2421: check that we correctly instantiated type parameters outside of the implicit tree:
+              checkBounds(itree2.pos, NoPrefix, NoSymbol, undetParams, targs, "inferred ")
+
+              // filter out failures from type inference, don't want to remove them from undetParams!
+              // we must be conservative in leaving type params in undetparams
+              val AdjustedTypeArgs(okParams, okArgs) = adjustTypeArgs(undetParams, targs)  // prototype == WildcardType: want to remove all inferred Nothing's
+              val subst = new TreeTypeSubstituter(okParams, okArgs)
+              subst traverse itree2 
+
+              // #2421b: since type inference (which may have been performed during implicit search)
+              // does not check whether inferred arguments meet the bounds of the corresponding parameter (see note in solvedTypes),
+              // must check again here:
+              // TODO: I would prefer to just call typed instead of duplicating the code here, but this is probably a hotspot (and you can't just call typed, need to force re-typecheck)
+              itree2 match {
+                case TypeApply(fun, args) => typedTypeApply(itree2, EXPRmode, fun, args)
+                case Apply(TypeApply(fun, args), _) => typedTypeApply(itree2, EXPRmode, fun, args) // t2421c
+                case _ =>
+              }
+
+              val result = new SearchResult(itree2, subst)
+              incCounter(foundImplicits)
+              if (traceImplicits) println("RESULT = "+result)
+              // println("RESULT = "+itree+"///"+itree1+"///"+itree2)//DEBUG
+              result
+            } else {
+              printTyping("incompatible: "+itree2.tpe+" does not match "+pt.instantiateTypeParams(undetParams, tvars))
+
+              SearchFailure
+            }
+          } else if (settings.XlogImplicits.value) 
+            fail("candidate implicit "+info.sym+info.sym.locationString+
+                 " is shadowed by other implicit: "+itree1.symbol+itree1.symbol.locationString)
+          else SearchFailure
+        } catch {
+          case ex: TypeError => fail(ex.getMessage())
+        }
+      } else {
+        SearchFailure
+      }
+    }
+
+    /** Should implicit definition symbol `sym' be considered for applicability testing?
+     *  This is the case if one of the following holds:
+     *   - the symbol's type is initialized
+     *   - the symbol comes from a classfile
+     *   - the symbol comes from a different sourcefile than the current one
+     *   - the symbol and the accessed symbol's definitions come before, and do not contain the closest enclosing definition, // see #3373
+     *   - the symbol's definition is a val, var, or def with an explicit result type
+     *  The aim of this method is to prevent premature cyclic reference errors
+     *  by computing the types of only those implicits for which one of these 
+     *  conditions is true.
+     */
+    def isValid(sym: Symbol) = {
+      def hasExplicitResultType(sym: Symbol) = {
+        def hasExplicitRT(tree: Tree) = tree match {
+          case ValDef(_, _, tpt, _) => !tpt.isEmpty
+          case DefDef(_, _, _, _, tpt, _) => !tpt.isEmpty
+          case _ => false
+        }
+        sym.rawInfo match {
+          case tc: TypeCompleter => hasExplicitRT(tc.tree)
+          case PolyType(_, tc: TypeCompleter) => hasExplicitRT(tc.tree)
+          case _ => true
+        }
+      }
+      def comesBefore(sym: Symbol, owner: Symbol) = {
+        val ownerPos = owner.pos.pointOrElse(Integer.MAX_VALUE)
+        sym.pos.pointOrElse(0) < ownerPos && (
+          if(sym isGetterOrSetter) {
+            val symAcc = sym.accessed // #3373
+            symAcc.pos.pointOrElse(0) < ownerPos &&
+            !(owner.ownerChain exists (o => (o eq sym) || (o eq symAcc))) // probably faster to iterate only once, don't feel like duplicating hasTransOwner for this case
+          } else !(owner hasTransOwner sym)) // faster than owner.ownerChain contains sym
+      }
+
+      sym.isInitialized ||
+      sym.sourceFile == null ||
+      (sym.sourceFile ne context.unit.source.file) || 
+      hasExplicitResultType(sym) ||
+      comesBefore(sym, context.owner)
+    }
+
+    /** Computes from a list of lists of implicit infos a map which takes
+     *  infos which are applicable for given expected type `pt` to their attributed trees.
+     *  Computes invalid implicits as a side effect (used for better error message).
+     *  @param iss            The given list of lists of implicit infos
+     *  @param isLocal        Is implicit definition visible without prefix?
+     *                        If this is the case then symbols in preceding lists shadow 
+     *                        symbols of the same name in succeeding lists.
+     */     
+    def applicableInfos(iss: List[List[ImplicitInfo]], 
+                        isLocal: Boolean, 
+                        invalidImplicits: ListBuffer[Symbol]): Map[ImplicitInfo, SearchResult] = {
+
+      val start = startCounter(subtypeAppInfos)
+
+      /** A set containing names that are shadowed by implicit infos */
+      lazy val shadowed = new HashSet[Name]("shadowed", 512)
+
+      // #3453
+      // in addition to the implicit symbols that may shadow the implicit with name `name`,
+      // this method tests whether there's a non-implicit symbol with name `name` in scope
+      // inspired by logic in typedIdent
+      def nonImplicitSynonymInScope(name: Name) = {
+        val defEntry = context.scope.lookupEntry(name)
+        (defEntry ne null) &&
+        reallyExists(defEntry.sym) &&
+        !defEntry.sym.isImplicit // the implicit ones are handled by the `shadowed` set above
+        // also, subsumes the test that defEntry.sym ne info.sym
+        // (the `info` that's in scope at the call to nonImplicitSynonymInScope in tryImplicit)
+      }
+
+      /** Is `sym' the standard conforms method in Predef?
+       *  Note: DON't replace this by sym == Predef_conforms, as Predef_conforms is a `def'
+       *  which does a member lookup (it can't be a lazy val because we might reload Predef
+       *  during resident compilations). 
+       */
+      def isConformsMethod(sym: Symbol) = 
+        sym.name == nme.conforms && sym.owner == PredefModule.moduleClass
+
+      /** Try implicit `info` to see whether it is applicable for expected type `pt`.
+       *  This is the case if all of the following holds:
+       *   - the info's type is not erroneous,
+       *   - the info is not shadowed by another info with the same name,
+       *   - we're not trying to infer a view that amounts to the identity function (specifically, Predef.identity or Predef.conforms)
+       *   - the result of typedImplicit is non-empty.
+       *   @return A search result with an attributed tree containing the implicit if succeeded,
+       *           SearchFailure if not.
+       *   @note Extreme hotspot!
+       */
+      def tryImplicit(info: ImplicitInfo): SearchResult = {
+        incCounter(triedImplicits)
+        if (info.isCyclicOrErroneous ||
+            (isLocal && (shadowed.contains(info.name) || nonImplicitSynonymInScope(info.name))) ||
+            (isView && isConformsMethod(info.sym)) ||
+            //@M this condition prevents no-op conversions, which are a problem (besides efficiency),
+            // one example is removeNames in NamesDefaults, which relies on the type checker failing in case of ambiguity between an assignment/named arg
+            !isPlausiblyCompatible(info.tpe, wildPt))
+           SearchFailure
+        else 
+          typedImplicit(info)
+      }
+
+      def addAppInfos(is: List[ImplicitInfo], m: Map[ImplicitInfo, SearchResult]): Map[ImplicitInfo, SearchResult] = {
+        var applicable = m
+        for (i <- is)
+          if (!isValid(i.sym)) invalidImplicits += i.sym
+          else {
+            val result = tryImplicit(i)
+            if (result != SearchFailure) applicable += (i -> result)
+          }
+        if (isLocal)
+          for (i <- is) shadowed addEntry i.name
+        applicable
+      }
+
+      // #3453 -- alternative fix, seems not to be faster than encoding the set as the boolean predicate nonImplicitSynonymInScope
+      // in addition to the *implicit* symbols that may shadow the implicit with name `name` (added to shadowed by addAppInfos)
+      // add names of non-implicit symbols that are in scope (accessible without prefix)
+      // for(sym <- context.scope; if !sym.isImplicit) shadowed addEntry sym.name
+
+      var applicable = Map[ImplicitInfo, SearchResult]()
+      for (is <- iss) applicable = addAppInfos(is, applicable)
+
+      stopCounter(subtypeAppInfos, start)
+      applicable
+    }
+
+    /** Search list of implicit info lists for one matching prototype
+     *  <code>pt</code>. If found return a search result with a tree from found implicit info
+     *  which is typed with expected type <code>pt</code>.
+     *  Otherwise return SearchFailure.
+     *
+     *  @param implicitInfoss The given list of lists of implicit infos
+     *  @param isLocal        Is implicit definition visible without prefix?
+     *                        If this is the case then symbols in preceding lists shadow 
+     *                        symbols of the same name in succeeding lists.
+     */
+    def searchImplicit(implicitInfoss: List[List[ImplicitInfo]], isLocal: Boolean): SearchResult = {
+
+      /** The implicits that are not valid because they come later in the source
+       *  and lack an explicit result type. Used for error diagnostics only.
+       */
+      val invalidImplicits = new ListBuffer[Symbol]
+
+      /** A map which takes applicable infos to their attributed trees. */
+      val applicable = applicableInfos(implicitInfoss, isLocal, invalidImplicits)
+
+      if (applicable.isEmpty && !invalidImplicits.isEmpty) {
+        setAddendum(tree.pos, () => 
+          "\n Note: implicit "+invalidImplicits.head+" is not applicable here"+
+          " because it comes after the application point and it lacks an explicit result type")
+      }
+
+      val start = startCounter(subtypeImprovCount)
+
+      /** A candidate for best applicable info wrt `improves` */
+      val best = (NoImplicitInfo /: applicable.keysIterator) (
+        (best, alt) => if (improves(alt, best)) alt else best)
+      if (best == NoImplicitInfo) SearchFailure
+      else {
+        /** The list of all applicable infos which are not improved upon by `best`. */
+        val competing = applicable.keySet dropWhile (alt => best == alt || improves(best, alt))
+        if (!competing.isEmpty) ambiguousImplicitError(best, competing.head, "both", "and", "") 
+
+        stopCounter(subtypeImprovCount, start)
+        applicable(best)
+      }
+    } // end searchImplicit
+    
+    /** The parts of a type is the smallest set of types that contains
+     *    - the type itself
+     *    - the parts of its immediate components (prefix and argument)
+     *    - the parts of its base types
+     *    - for alias types and abstract types, we take instead the parts
+     *    - of their upper bounds.
+     *  @return For those parts that refer to classes with companion objects that
+     *  can be accessed with unambiguous stable prefixes, the implicits infos
+     *  which are members of these companion objects.
+     */
+    private def companionImplicits(tp: Type): List[List[ImplicitInfo]] = {
+
+      val partMap = new LinkedHashMap[Symbol, Type]
+
+      /** Enter all parts of `tp` into `parts` set.
+       *  This method is performance critical: about 2-4% of all type checking is spent here
+       */
+      def getParts(tp: Type) {
+        tp match {
+          case TypeRef(pre, sym, args) =>
+            if (sym.isClass) {
+              if (!((sym.name == nme.REFINE_CLASS_NAME.toTypeName) ||
+                    (sym.name startsWith nme.ANON_CLASS_NAME) ||
+                    (sym.name == nme.ROOT.toTypeName)))
+                partMap get sym match {
+                  case Some(pre1) => 
+                    if (!(pre =:= pre1)) partMap(sym) = NoType // ambiguous prefix - ignore implicit members 
+                  case None =>
+                    if (pre.isStable) partMap(sym) = pre
+                    val bts = tp.baseTypeSeq
+                    var i = 1
+                    while (i < bts.length) {
+                      getParts(bts(i))
+                      i += 1
+                    }
+                    getParts(pre)
+                    args foreach getParts
+                }
+            } else if (sym.isAliasType) {
+              getParts(tp.normalize)
+            } else if (sym.isAbstractType) {
+              getParts(tp.bounds.hi)
+            }
+          case ThisType(_) =>
+            getParts(tp.widen)
+          case _: SingletonType =>
+            getParts(tp.widen)
+          case RefinedType(ps, _) =>
+            for (p <- ps) getParts(p)
+          case AnnotatedType(_, t, _) =>
+            getParts(t)
+          case ExistentialType(_, t) => 
+            getParts(t)
+          case PolyType(_, t) => 
+            getParts(t)
+          case _ =>
+        }
+      }
+
+      getParts(tp)
+      val buf = new ListBuffer[List[ImplicitInfo]]
+      for ((clazz, pre) <- partMap) {
+        if (pre != NoType) {
+          val companion = clazz.companionModule
+          companion.moduleClass match {
+            case mc: ModuleClassSymbol =>
+              buf += (mc.implicitMembers map (im => 
+                new ImplicitInfo(im.name, SingleType(pre, companion), im)))
+            case _ =>
+          }
+        }
+      }
+      //println("companion implicits of "+tp+" = "+buf.toList) // DEBUG
+      buf.toList
+    }
+          
+    /** The implicits made available by type `pt`.
+     *  These are all implicits found in companion objects of classes C
+     *  such that some part of `tp` has C as one of its superclasses.
+     */
+    private def implicitsOfExpectedType: List[List[ImplicitInfo]] = implicitsCache get pt match {
+      case Some(implicitInfoss) => 
+        incCounter(implicitCacheHits)
+        implicitInfoss
+      case None                 =>
+        incCounter(implicitCacheMisses)
+        val start = startTimer(subtypeETNanos)
+        val implicitInfoss = companionImplicits(pt)
+        stopTimer(subtypeETNanos, start)
+        implicitsCache(pt) = implicitInfoss
+        if (implicitsCache.size >= sizeLimit)
+          implicitsCache -= implicitsCache.keysIterator.next
+        implicitInfoss
+    }
+
+    /** Creates a tree that calls the relevant factory method in object
+      * reflect.Manifest for type 'tp'. An EmptyTree is returned if
+      * no manifest is found. todo: make this instantiate take type params as well?
+      */
+    private def manifestOfType(tp: Type, full: Boolean): SearchResult = {
+      
+      /** Creates a tree that calls the factory method called constructor in object reflect.Manifest */
+      def manifestFactoryCall(constructor: String, tparg: Type, args: Tree*): Tree =
+        if (args contains EmptyTree) EmptyTree
+        else typedPos(tree.pos.focus) {
+          Apply(
+            TypeApply(
+              Select(gen.mkAttributedRef(if (full) FullManifestModule else PartialManifestModule), constructor),
+              List(TypeTree(tparg))
+            ),
+            args.toList
+          )
+        }
+      
+      /** Creates a tree representing one of the singleton manifests.*/
+      def findSingletonManifest(name: String) = typedPos(tree.pos.focus) { 
+        Select(gen.mkAttributedRef(FullManifestModule), name)
+      }
+      
+      /** Re-wraps a type in a manifest before calling inferImplicit on the result */
+      def findManifest(tp: Type, manifestClass: Symbol = if (full) FullManifestClass else PartialManifestClass) =
+        inferImplicit(tree, appliedType(manifestClass.typeConstructor, List(tp)), true, false, context).tree
+
+      def findSubManifest(tp: Type) = findManifest(tp, if (full) FullManifestClass else OptManifestClass)
+      def mot(tp0: Type)(implicit from: List[Symbol] = List(), to: List[Type] = List()): SearchResult = {
+        implicit def wrapResult(tree: Tree): SearchResult = 
+          if (tree == EmptyTree) SearchFailure else new SearchResult(tree, new TreeTypeSubstituter(from, to))
+
+        val tp1 = tp0.normalize
+        tp1 match {
+          case ThisType(_) | SingleType(_, _) if !(tp1 exists {tp => tp.typeSymbol.isExistentiallyBound}) => // can't generate a reference to a value that's abstracted over by an existential
+            manifestFactoryCall("singleType", tp, gen.mkAttributedQualifier(tp1)) 
+          case ConstantType(value) =>
+            manifestOfType(tp1.deconst, full)
+          case TypeRef(pre, sym, args) =>
+            if (isValueClass(sym) || isPhantomClass(sym)) {
+              findSingletonManifest(sym.name.toString)
+            } else if (sym == ObjectClass || sym == AnyRefClass) {
+              findSingletonManifest("Object")
+            } else if (sym == RepeatedParamClass || sym == ByNameParamClass) {
+              EmptyTree
+            } else if (sym == ArrayClass && args.length == 1) {
+              manifestFactoryCall("arrayType", args.head, findManifest(args.head))
+            } else if (sym.isClass) {
+              val classarg0 = gen.mkClassOf(tp1) 
+              val classarg = tp match {
+                case ExistentialType(_, _) => 
+                  TypeApply(Select(classarg0, Any_asInstanceOf), 
+                            List(TypeTree(appliedType(ClassClass.typeConstructor, List(tp)))))
+                case _ => 
+                  classarg0
+              }
+              val suffix = classarg :: (args map findSubManifest)
+              manifestFactoryCall(
+                "classType", tp,
+                (if ((pre eq NoPrefix) || pre.typeSymbol.isStaticOwner) suffix
+                 else findSubManifest(pre) :: suffix): _*)
+            } else if (sym.isExistentiallyBound && full) {
+              manifestFactoryCall("wildcardType", tp,
+                                  findManifest(tp.bounds.lo), findManifest(tp.bounds.hi))
+            } else if(undetParams contains sym) { // looking for a manifest of a type parameter that hasn't been inferred by now, can't do much, but let's not fail
+              mot(NothingClass.tpe)(sym :: from, NothingClass.tpe :: to) // #3859: need to include the mapping from sym -> NothingClass.tpe in the SearchResult
+            } else {
+              EmptyTree  // a manifest should have been found by normal searchImplicit
+            }
+          case RefinedType(parents, decls) =>
+            // refinement is not generated yet
+            if (parents.length == 1) findManifest(parents.head)
+            else if (full) manifestFactoryCall("intersectionType", tp, parents map (findSubManifest(_)): _*)
+            else mot(erasure.erasure.intersectionDominator(parents))
+          case ExistentialType(tparams, result) =>
+            mot(tp1.skolemizeExistential)
+          case _ =>
+            EmptyTree
+        }
+      }
+
+      mot(tp)
+    }
+
+    def wrapResult(tree: Tree): SearchResult = 
+      if (tree == EmptyTree) SearchFailure else new SearchResult(tree, EmptyTreeTypeSubstituter)
+
+    /** The manifest corresponding to type `pt`, provided `pt` is an instance of Manifest.
+     */
+    private def implicitManifestOrOfExpectedType(pt: Type): SearchResult = pt.dealias match {
+      case TypeRef(_, FullManifestClass, List(arg)) => 
+        manifestOfType(arg, true)
+      case TypeRef(_, PartialManifestClass, List(arg)) => 
+        manifestOfType(arg, false)
+      case TypeRef(_, OptManifestClass, List(arg)) => 
+        val res = manifestOfType(arg, false)
+        if (res == SearchFailure) wrapResult(gen.mkAttributedRef(NoManifest)) else res
+      case TypeRef(_, tsym, _) if (tsym.isAbstractType) =>
+        implicitManifestOrOfExpectedType(pt.bounds.lo)
+      case _ =>
+        searchImplicit(implicitsOfExpectedType, false)
+    }
+            
+    /** The result of the implicit search:
+     *  First search implicits visible in current context.
+     *  If that fails, search implicits in expected type `pt`.
+     *  If that fails, and `pt` is an instance of Manifest, try to construct a manifest.
+     *  If all fails return SearchFailure
+     */
+    def bestImplicit: SearchResult = {
+      val failstart = startTimer(inscopeFailNanos)
+      val succstart = startTimer(inscopeSucceedNanos)
+      
+      var result = searchImplicit(context.implicitss, true)
+
+      if (result == SearchFailure) {
+        stopTimer(inscopeFailNanos, failstart)
+      } else {                                        
+        stopTimer(inscopeSucceedNanos, succstart)
+        incCounter(inscopeImplicitHits)
+      }
+      if (result == SearchFailure) {
+        val failstart = startTimer(oftypeFailNanos)
+        val succstart = startTimer(oftypeSucceedNanos)
+
+        result = implicitManifestOrOfExpectedType(pt)
+
+        if (result == SearchFailure) {
+          stopTimer(oftypeFailNanos, failstart)
+        } else {                                        
+          stopTimer(oftypeSucceedNanos, succstart)
+          incCounter(oftypeImplicitHits)
+        }
+      }
+
+      if (result == SearchFailure && settings.debug.value)
+        log("no implicits found for "+pt+" "+pt.typeSymbol.info.baseClasses+" "+implicitsOfExpectedType)
+
+      result
+    }
+
+    def allImplicits: List[SearchResult] = {
+      val invalidImplicits = new ListBuffer[Symbol]
+      def search(iss: List[List[ImplicitInfo]], isLocal: Boolean) = 
+        applicableInfos(iss, isLocal, invalidImplicits).values.toList
+      search(context.implicitss, true) ::: search(implicitsOfExpectedType, false)
+    }
+  }
+
+  object ImplicitNotFoundMsg {
+    def unapply(sym: Symbol): Option[(Message)] = sym.implicitNotFoundMsg map (m => (new Message(sym, m)))
+    // check the message's syntax: should be a string literal that may contain occurences of the string "${X}",
+    // where `X` refers to a type parameter of `sym`
+    def check(sym: Symbol): Option[String] =
+      sym.getAnnotation(ImplicitNotFoundClass).flatMap(_.stringArg(0) match {
+        case Some(m) => new Message(sym, m) validate
+        case None => Some("Missing argument `msg` on implicitNotFound annotation.")
+      })
+    
+
+    class Message(sym: Symbol, msg: String) {
+      // http://dcsobral.blogspot.com/2010/01/string-interpolation-in-scala-with.html
+      private def interpolate(text: String, vars: Map[String, String]) = { import scala.util.matching.Regex
+        """\$\{([^}]+)\}""".r.replaceAllIn(text, (_: Regex.Match) match { 
+          case Regex.Groups(v) => java.util.regex.Matcher.quoteReplacement(vars.getOrElse(v, "")) // #3915: need to quote replacement string since it may include $'s (such as the interpreter's $iw)
+        })}
+
+      private lazy val typeParamNames: List[String] = sym.typeParams.map(_.decodedName)
+
+      def format(paramName: Name, paramTp: Type): String = format(paramTp.typeArgs map (_.toString))
+      def format(typeArgs: List[String]): String = 
+        interpolate(msg, Map((typeParamNames zip typeArgs): _*)) // TODO: give access to the name and type of the implicit argument, etc?
+
+      def validate: Option[String] = {
+        import scala.util.matching.Regex; import collection.breakOut
+        // is there a shorter way to avoid the intermediate toList?
+        val refs = Set("""\$\{([^}]+)\}""".r.findAllIn(msg).matchData.map(_.group(1)).toList : _*)
+        val decls = Set(typeParamNames : _*)
+        (refs &~ decls) match {
+          case s if s isEmpty => None
+          case unboundNames =>
+            val singular = unboundNames.size == 1
+            Some("The type parameter"+( if(singular) " " else "s " )+ unboundNames.mkString(", ")  +
+                  " referenced in the message of the @implicitNotFound annotation "+( if(singular) "is" else "are" )+
+                  " not defined by "+ sym +".")
+        }
+      }
+    }
+  }
+
+  private val DivergentImplicit = new Exception()
+}
diff --git a/src/compiler/scala/tools/nsc/typechecker/Infer.scala b/src/compiler/scala/tools/nsc/typechecker/Infer.scala
index be5a754..7c37c05 100644
--- a/src/compiler/scala/tools/nsc/typechecker/Infer.scala
+++ b/src/compiler/scala/tools/nsc/typechecker/Infer.scala
@@ -1,12 +1,13 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: Infer.scala 16881 2009-01-09 16:28:11Z cunei $
 
-package scala.tools.nsc.typechecker
-import scala.tools.nsc.util.{Position, NoPosition}
+package scala.tools.nsc
+package typechecker
+
 import scala.collection.mutable.ListBuffer
+import scala.util.control.ControlThrowable
 import symtab.Flags._
 
 /** This trait ...
@@ -18,36 +19,31 @@ trait Infer {
   self: Analyzer =>
   import global._
   import definitions._
-  import posAssigner.atPos
-
-  // statistics
-  var normM = 0
-  var normP = 0
-  var normO = 0
 
-  private final val inferInfo = false
+  private final val inferInfo = false //@MDEBUG
 
 /* -- Type parameter inference utility functions --------------------------- */
 
   private def assertNonCyclic(tvar: TypeVar) =
     assert(tvar.constr.inst != tvar, tvar.origin)
 
-  def isVarArgs(formals: List[Type]) = 
-    !formals.isEmpty && (formals.last.typeSymbol == RepeatedParamClass)
+  def isVarArgs(params: List[Symbol]) = !params.isEmpty && isRepeatedParamType(params.last.tpe)
+  def isVarArgTpes(formals: List[Type]) = !formals.isEmpty && isRepeatedParamType(formals.last)
 
   /** The formal parameter types corresponding to <code>formals</code>.
-   *  If <code>formals</code> has a repeated last parameter, a list of 
+   *  If <code>formals</code> has a repeated last parameter, a list of
    *  (nargs - params.length + 1) copies of its type is returned.
+   *  By-name types are replaced with their underlying type.
    *
-   *  @param formals ...
-   *  @param nargs ...
+   *  @param removeByName allows keeping ByName parameters. Used in NamesDefaults.
+   *  @param removeRepeated allows keeping repeated parameter (if there's one argument). Used in NamesDefaults.
    */
-  def formalTypes(formals: List[Type], nargs: Int): List[Type] = {
-    val formals1 = formals map {
+  def formalTypes(formals: List[Type], nargs: Int, removeByName: Boolean = true, removeRepeated: Boolean = true): List[Type] = {
+    val formals1 = if (removeByName) formals mapConserve {
       case TypeRef(_, sym, List(arg)) if (sym == ByNameParamClass) => arg
       case formal => formal
-    }
-    if (isVarArgs(formals1)) {
+    } else formals
+    if (isVarArgTpes(formals1) && (removeRepeated || formals.length != nargs)) {
       val ft = formals1.last.normalize.typeArgs.head
       formals1.init ::: (for (i <- List.range(formals1.length - 1, nargs)) yield ft)
     } else formals1
@@ -59,22 +55,18 @@ trait Infer {
     else actuals
 
   def actualArgs(pos: Position, actuals: List[Tree], nformals: Int): List[Tree] =
-    if (nformals == 1 && actuals.length != 1 && !phase.erasedTypes) List(atPos(pos)(gen.mkTuple(actuals))) else actuals
+    if (nformals == 1 && actuals.length != 1 && actuals.length <= definitions.MaxTupleArity && !phase.erasedTypes)
+      List(atPos(pos)(gen.mkTuple(actuals))) else actuals
 
-  /** A fresh type varable with given type parameter as origin.
+  /** A fresh type variable with given type parameter as origin.
    *
    *  @param tparam ...
    *  @return       ...
    */
-  private def freshVar(tparam: Symbol): TypeVar =
-    new TypeVar(tparam.tpe, new TypeConstraint)  //@M TODO: might be affected by change to tpe in Symbol
-
-  //todo: remove comments around following privates; right now they cause an IllegalAccess
-  // error when built with scalac
-
-  /*private*/ class NoInstance(msg: String) extends RuntimeException(msg)
-
-  /*private*/ class DeferredNoInstance(getmsg: () => String) extends NoInstance("") {
+  def freshVar(tparam: Symbol): TypeVar = TypeVar(tparam) 
+  
+  private class NoInstance(msg: String) extends Throwable(msg) with ControlThrowable { }
+  private class DeferredNoInstance(getmsg: () => String) extends NoInstance("") {
     override def getMessage(): String = getmsg()
   }
 
@@ -88,7 +80,7 @@ trait Infer {
   object instantiate extends TypeMap {
     private var excludedVars = scala.collection.immutable.Set[TypeVar]()
     def apply(tp: Type): Type = tp match {
-      case WildcardType | NoType =>
+      case WildcardType | BoundedWildcardType(_) | NoType =>
         throw new NoInstance("undetermined type")
       case tv @ TypeVar(origin, constr) =>
         if (constr.inst == NoType) {
@@ -113,12 +105,12 @@ trait Infer {
    *  @return   ...
    */
   private[typechecker] def isFullyDefined(tp: Type): Boolean = tp match {
-    case WildcardType | NoType =>
+    case WildcardType | BoundedWildcardType(_) | NoType =>
       false
     case NoPrefix | ThisType(_) | ConstantType(_) => 
       true
     case TypeRef(pre, sym, args) =>
-      isFullyDefined(pre) && (args.isEmpty || (args forall isFullyDefined))
+      isFullyDefined(pre) && (args forall isFullyDefined)
     case SingleType(pre, sym) =>
       isFullyDefined(pre)
     case RefinedType(ts, decls) =>
@@ -142,50 +134,52 @@ trait Infer {
    *  @param upper      When <code>true</code> search for max solution else min.
    *  @throws NoInstance
    */
-  private def solvedTypes(tvars: List[TypeVar], tparams: List[Symbol],
-                          variances: List[Int], upper: Boolean, depth: Int): List[Type] = {
-    def boundsString(tvar: TypeVar) = 
-      "\n  "+
-      ((tvar.constr.lobounds map (_ + " <: " + tvar.origin.typeSymbol.name)) :::
-       (tvar.constr.hibounds map (tvar.origin.typeSymbol.name + " <: " + _)) mkString ", ")
+  def solvedTypes(tvars: List[TypeVar], tparams: List[Symbol],
+                  variances: List[Int], upper: Boolean, depth: Int): List[Type] = {
+//    def boundsString(tvar: TypeVar) = 
+//      "\n  "+
+//      ((tvar.constr.loBounds map (_ + " <: " + tvar.origin.typeSymbol.name)) :::
+//       (tvar.constr.hiBounds map (tvar.origin.typeSymbol.name + " <: " + _)) mkString ", ")
     if (!solve(tvars, tparams, variances, upper, depth)) {
 //    no panic, it's good enough to just guess a solution, we'll find out
 //    later whether it works.
+// @M danger, Will Robinson! this means that you should never trust inferred type arguments!
+// need to call checkBounds on the args/typars or type1 on the tree for the expression that results from type inference
+// see e.g., #2421: implicit search had been ignoring this caveat
 //      throw new DeferredNoInstance(() =>
 //        "no solution exists for constraints"+(tvars map boundsString))
     }
     for (tvar <- tvars) 
       if (tvar.constr.inst == tvar)
         if (tvar.origin.typeSymbol.info eq ErrorType) {
-          // this can happen if during solving a cyclic type paramater
+          // this can happen if during solving a cyclic type parameter
           // such as T <: T gets completed. See #360
           tvar.constr.inst = ErrorType
-        } else assert(false, tvar.origin)
+        } else assert(false, tvar.origin+" at "+tvar.origin.typeSymbol.owner)
     tvars map instantiate
   }
 
-  def skipImplicit(tp: Type) =
-    if (tp.isInstanceOf[ImplicitMethodType]) tp.resultType else tp
+  def skipImplicit(tp: Type) = tp match {
+    case mt: MethodType if mt.isImplicit  => mt.resultType
+    case _                                => tp
+  }
 
   /** Automatically perform the following conversions on expression types:
    *  A method type becomes the corresponding function type.
    *  A nullary method type becomes its result type.
    *  Implicit parameters are skipped.
-   *
-   *  @param tp ...
-   *  @return   ...
+   *  This method seems to be performance critical.
    */
-  def normalize(tp: Type): Type = skipImplicit(tp) match {
-    case MethodType(formals, restpe) if (!restpe.isDependent) =>
-      if (util.Statistics.enabled) normM += 1
-      functionType(formals, normalize(restpe))
-    case PolyType(List(), restpe) =>
-      if (util.Statistics.enabled) normP += 1
+  def normalize(tp: Type): Type = tp match {
+    case mt @ MethodType(params, restpe) if mt.isImplicit =>
+      normalize(restpe)
+    case mt @ MethodType(params, restpe) if !restpe.isDependent =>
+      functionType(params map (_.tpe), normalize(restpe))
+    case PolyType(List(), restpe) => // nullary method type
       normalize(restpe)
     case ExistentialType(tparams, qtpe) =>
       ExistentialType(tparams, normalize(qtpe))
     case tp1 =>
-      if (util.Statistics.enabled) normO += 1
       tp1 // @MAT aliases already handled by subtyping
   }
 
@@ -194,74 +188,19 @@ trait Infer {
 
   /** The context-dependent inferencer part */
   class Inferencer(context: Context) {
-
     /* -- Error Messages --------------------------------------------------- */
-
-    private var addendumPos: Position = NoPosition
-    private var addendum: () => String = _
-
-    def setAddendum(pos: Position, msg: () => String) = {
-      addendumPos = pos
-      addendum = msg
-    }
-
     def setError[T <: Tree](tree: T): T = {
+      def name        = newTermName("<error: " + tree.symbol + ">")
+      def errorClass  = if (context.reportGeneralErrors) context.owner.newErrorClass(name.toTypeName) else stdErrorClass
+      def errorValue  = if (context.reportGeneralErrors) context.owner.newErrorValue(name) else stdErrorValue
+      def errorSym    = if (tree.isType) errorClass else errorValue
+      
       if (tree.hasSymbol)
-        if (context.reportGeneralErrors) {
-          val name = newTermName("<error: " + tree.symbol + ">")
-          tree.setSymbol(
-            if (tree.isType) context.owner.newErrorClass(name.toTypeName)
-            else context.owner.newErrorValue(name))
-        } else {
-          tree.setSymbol(if (tree.isType) stdErrorClass else stdErrorValue)
-        }
-      tree.setType(ErrorType)
-    }
+        tree setSymbol errorSym
 
-    def decode(name: Name): String =
-      (if (name.isTypeName) "type " else "value ") + name.decode
-
-    def treeSymTypeMsg(tree: Tree): String =
-      if (tree.symbol eq null)
-        "expression of type " + tree.tpe
-      else if (tree.symbol.hasFlag(OVERLOADED))
-        "overloaded method " + tree.symbol + " with alternatives " + tree.tpe
-      else
-        tree.symbol.toString() +
-        (if (tree.symbol.isModule) ""
-         else if (tree.tpe.paramSectionCount > 0) ": "+tree.tpe 
-         else " of type "+tree.tpe) +
-        (if (tree.symbol.name == nme.apply) tree.symbol.locationString else "")
-
-    def applyErrorMsg(tree: Tree, msg: String, argtpes: List[Type], pt: Type) =
-      treeSymTypeMsg(tree) + msg + argtpes.mkString("(", ",", ")") +
-       (if (pt == WildcardType) "" else " with expected result type " + pt)
-
-    // todo: use also for other error messages
-    private def existentialContext(tp: Type) = tp.existentialSkolems match {
-      case List() => ""
-      case skolems => 
-        def disambiguate(ss: List[String]) = ss match {
-          case List() => ss
-          case s :: ss1 => s :: (ss1 map (s1 => if (s1 == s) "(some other)"+s1 else s1))
-        }
-      " where "+(disambiguate(skolems map (_.existentialToString)) mkString ", ")
+      tree setType ErrorType
     }
 
-    def foundReqMsg(found: Type, req: Type): String =
-      withDisambiguation(found, req) {
-        ";\n found   : " + found.toLongString + existentialContext(found) +
-         "\n required: " + req + existentialContext(req)
-      }
-
-    def typeErrorMsg(found: Type, req: Type) = {
-      //println(found.baseTypeSeq)
-      "type mismatch" + foundReqMsg(found, req) +
-      (if ((found.resultApprox ne found) && isWeaklyCompatible(found.resultApprox, req))
-        "\n possible cause: missing arguments for method or constructor"
-       else "")
-    }
-      
     def error(pos: Position, msg: String) {
       context.error(pos, msg)
     }
@@ -272,67 +211,36 @@ trait Infer {
     }
 
     def typeError(pos: Position, found: Type, req: Type) {
-      if (!found.isErroneous && !req.isErroneous) {
-        error(pos, 
-              typeErrorMsg(found, req)+
-              (if (pos != NoPosition && pos == addendumPos) addendum()
-               else ""))
-        if (settings.explaintypes.value) explainTypes(found, req)
+      if (!found.isErroneous && !req.isErroneous) {        
+        error(pos, withAddendum(pos)(typeErrorMsg(found, req)))
+        
+        if (settings.explaintypes.value)
+          explainTypes(found, req)
       }
     }
 
+    def typeErrorMsg(found: Type, req: Type) = {
+      def isPossiblyMissingArgs = (found.resultApprox ne found) && isWeaklyCompatible(found.resultApprox, req)
+      def missingArgsMsg = if (isPossiblyMissingArgs) "\n possible cause: missing arguments for method or constructor" else ""
+      
+      "type mismatch" + foundReqMsg(found, req) + missingArgsMsg
+    }
+
     def typeErrorTree(tree: Tree, found: Type, req: Type): Tree = {
       typeError(tree.pos, found, req)
       setError(tree)
     }
 
     def explainTypes(tp1: Type, tp2: Type) = 
-      withDisambiguation(tp1, tp2) { global.explainTypes(tp1, tp2) }
-
-    /** If types `tp1' `tp2' contain different type variables with same name 
-     *  differentiate the names by including owner information
-     */
-    private def withDisambiguation[T](tp1: Type, tp2: Type)(op: => T): T = {
-
-      def explainName(sym: Symbol) = { 
-        if (!sym.name.toString.endsWith(")") && !inIDE) {
-          sym.name = newTypeName(sym.name.toString+"(in "+sym.owner+")") 
-        }
-      }
-
-      val patches = new ListBuffer[(Symbol, Symbol, Name)]
-      for {
-        t1 @ TypeRef(_, sym1, _) <- tp1
-        t2 @ TypeRef(_, sym2, _) <- tp2
-        if sym1 != sym2 && t1.toString == t2.toString
-      } {
-        val name = sym1.name
-        explainName(sym1)
-        explainName(sym2)
-        if (sym1.owner == sym2.owner && !inIDE) sym2.name = newTypeName("(some other)"+sym2.name)
-        patches += ((sym1, sym2, name))
-      }
-
-      val result = op
-
-      for ((sym1, sym2, name) <- patches) {
-        sym1.name = name
-        sym2.name = name
-      }
-
-      result
-    }
+      withDisambiguation(tp1, tp2)(global.explainTypes(tp1, tp2))
 
     /* -- Tests & Checks---------------------------------------------------- */
 
     /** Check that <code>sym</code> is defined and accessible as a member of
      *  tree <code>site</code> with type <code>pre</code> in current context.
      *
-     *  @param tree ...
-     *  @param sym  ...
-     *  @param pre  ...
-     *  @param site ...
-     *  @return     ...
+     * Note: pre is not refchecked -- moreover, refchecking the resulting tree may not refcheck pre,
+     *       since pre may not occur in its type (callers should wrap the result in a TypeTreeWithDeferredRefCheck)
      */
     def checkAccessible(tree: Tree, sym: Symbol, pre: Type, site: Tree): Tree =
       if (sym.isError) {
@@ -348,6 +256,8 @@ trait Infer {
           context.unit.depends += sym.toplevelClass 
 
         val sym1 = sym filter (alt => context.isAccessible(alt, pre, site.isInstanceOf[Super]))
+        // Console.println("check acc " + (sym, sym1) + ":" + (sym.tpe, sym1.tpe) + " from " + pre);//DEBUG
+
         if (sym1 == NoSymbol) {
           if (settings.debug.value) {
             Console.println(context)
@@ -356,33 +266,16 @@ trait Infer {
           }
           accessError("")
         } else {
-          // Modify symbol's type so that raw types C
-          // are converted to existentials C[T] forSome { type T }.
-          // We can't do this on class loading because it would result
-          // in infinite cycles.
-          def cook(sym: Symbol) {
-            val tpe1 = rawToExistential(sym.tpe)
-            if (tpe1 ne sym.tpe) {
-              if (settings.debug.value) println("cooked: "+sym+":"+sym.tpe)
-              sym.setInfo(tpe1)
-            }
-          }
-          if (sym1.isTerm) { 
-            if (sym1 hasFlag JAVA) 
-              cook(sym1)
-            else if (sym1 hasFlag OVERLOADED)
-              for (sym2 <- sym1.alternatives)
-                if (sym2 hasFlag JAVA) 
-                  cook(sym2)
-          }
-          //Console.println("check acc " + sym1 + ":" + sym1.tpe + " from " + pre);//DEBUG
+          if(sym1.isTerm)
+            sym1.cookJavaRawInfo() // xform java rawtypes into existentials
+
           var owntype = try{ 
             pre.memberType(sym1)
           } catch {
             case ex: MalformedType =>
               if (settings.debug.value) ex.printStackTrace
               val sym2 = underlying(sym1)
-              val itype = withoutMalformedChecks(pre.memberType(sym2))
+              val itype = pre.memberType(sym2)
               accessError("\n because its instance type "+itype+
                           (if ("malformed type: "+itype.toString==ex.msg) " is malformed" 
                            else " contains a "+ex.msg))
@@ -397,34 +290,48 @@ trait Infer {
     def isPlausiblyCompatible(tp: Type, pt: Type): Boolean = tp match {
       case PolyType(_, restpe) =>
         isPlausiblyCompatible(restpe, pt)
-      case mt: ImplicitMethodType =>
-        isPlausiblyCompatible(mt.resultType, pt)
       case ExistentialType(tparams, qtpe) =>
         isPlausiblyCompatible(qtpe, pt)
-      case MethodType(formals, _) =>
-        pt.normalize match {
+      case mt @ MethodType(params, restpe) =>
+        if (mt.isImplicit) isPlausiblyCompatible(restpe, pt)
+        else pt match {
           case TypeRef(pre, sym, args) =>
-            !sym.isClass || {
+            if (sym.isAliasType) {
+              isPlausiblyCompatible(tp, pt.dealias)
+            } else if (sym.isAbstractType) {
+              isPlausiblyCompatible(tp, pt.bounds.lo)
+            } else {
               val l = args.length - 1
-              l == formals.length &&
-              sym == FunctionClass(l) &&
-              List.forall2(args, formals) (isPlausiblySubType) &&
-              isPlausiblySubType(tp.resultApprox, args.last)
+              l == params.length &&
+              sym == FunctionClass(l) && {
+                var curargs = args
+                var curparams = params
+                while (curparams.nonEmpty) {
+                  if (!isPlausiblySubType(curargs.head, curparams.head.tpe))
+                    return false
+                  curargs = curargs.tail
+                  curparams = curparams.tail
+                }
+                isPlausiblySubType(restpe, curargs.head)
+              }
             }
           case _ =>
-            true
+            false
         }
       case _ =>
-        true
+        isPlausiblySubType(tp, pt)
     }
         
-    private def isPlausiblySubType(tp1: Type, tp2: Type): Boolean = tp1.normalize match {
+    private def isPlausiblySubType(tp1: Type, tp2: Type): Boolean = tp1 match {
       case TypeRef(_, sym1, _) =>
-        !sym1.isClass || {
-          tp2.normalize match {
-            case TypeRef(_, sym2, _) => !sym2.isClass || (sym1 isSubClass sym2)
-            case _ => true
-          }
+        if (sym1.isAliasType) isPlausiblySubType(tp1.dealias, tp2)
+        else if (!sym1.isClass) true
+        else tp2 match {
+          case TypeRef(_, sym2, _) => 
+            if (sym2.isAliasType) isPlausiblySubType(tp1, tp2.dealias)
+            else !sym2.isClass || (sym1 isSubClass sym2) || isNumericSubClass(sym1, sym2)
+          case _ => 
+            true
         }
       case _ =>
         true
@@ -432,19 +339,98 @@ trait Infer {
 
     def isCompatible(tp: Type, pt: Type): Boolean = {
       val tp1 = normalize(tp)
-      (tp1 <:< pt) || isCoercible(tp, pt)
+      (tp1 weak_<:< pt) || isCoercible(tp1, pt)
+    }
+
+    final def normSubType(tp: Type, pt: Type): Boolean = tp match {
+      case mt @ MethodType(params, restpe) =>
+        if (mt.isImplicit) normSubType(restpe, pt)
+        else  pt match {
+          case TypeRef(pre, sym, args) =>
+            if (sym.isAliasType) {
+              normSubType(tp, pt.dealias)
+            } else if (sym.isAbstractType) {
+              normSubType(tp, pt.bounds.lo)
+            } else {
+              val l = args.length - 1
+              l == params.length &&
+              sym == FunctionClass(l) && {
+                var curargs = args
+                var curparams = params
+                while (curparams.nonEmpty) {
+                  if (!(curargs.head <:< curparams.head.tpe))
+                    return false
+                  curargs = curargs.tail
+                  curparams = curparams.tail
+                }
+                normSubType(restpe, curargs.head)
+              }
+            }
+          case _ =>
+            tp <:< pt
+        }
+      case PolyType(List(), restpe) => // nullary method type
+        normSubType(restpe, pt)
+      case ExistentialType(tparams, qtpe) =>
+        normalize(tp) <:< pt
+      case _ =>
+        tp <:< pt
+    }
+
+    def isCompatibleArg(tp: Type, pt: Type): Boolean = {
+      val tp1 = normalize(tp)
+      (tp1 weak_<:< pt) || isCoercible(tp1, pt)
     }
 
     def isWeaklyCompatible(tp: Type, pt: Type): Boolean =
-      pt.typeSymbol == UnitClass || isCompatible(tp, pt)
+      pt.typeSymbol == UnitClass || // can perform unit coercion
+      isCompatible(tp, pt) ||
+      tp.isInstanceOf[MethodType] && // can perform implicit () instantiation
+      tp.params.isEmpty && isCompatible(tp.resultType, pt)
+
+    /** Like weakly compatible but don't apply any implicit conversions yet.
+     *  Used when comparing the result type of a method with its prototype.
+     */
+    def isConservativelyCompatible(tp: Type, pt: Type): Boolean = {
+      val savedImplicitsEnabled = context.implicitsEnabled
+      context.implicitsEnabled = false
+      try {
+        isWeaklyCompatible(tp, pt)
+      } finally {
+        context.implicitsEnabled = savedImplicitsEnabled
+      }
+    }
 
     def isCoercible(tp: Type, pt: Type): Boolean = false
 
-    def isCompatible(tps: List[Type], pts: List[Type]): Boolean =
-      List.map2(tps, pts)((tp, pt) => isCompatible(tp, pt)) forall (x => x)
+    def isCompatibleArgs(tps: List[Type], pts: List[Type]) = 
+      (tps corresponds pts)(isCompatibleArg)  // @PP: corresponds
 
     /* -- Type instantiation------------------------------------------------ */
 
+    /** Replace any (possibly bounded) wildcard types in type `tp`
+     *  by existentially bound variables.
+     */
+    def makeFullyDefined(tp: Type): Type = {
+      val tparams = new ListBuffer[Symbol]
+      def addTypeParam(bounds: TypeBounds): Type = {
+        val tparam =  
+          context.owner.newAbstractType(context.tree.pos.focus, newTypeName("_"+tparams.size))
+            .setFlag(EXISTENTIAL)
+            .setInfo(bounds)
+        tparams += tparam
+        tparam.tpe
+      }
+      val tp1 = tp map { 
+        case WildcardType =>
+          addTypeParam(TypeBounds(NothingClass.tpe, AnyClass.tpe))
+        case BoundedWildcardType(bounds) =>
+          addTypeParam(bounds)
+        case t => t
+      }
+      existentialAbstraction(tparams.toList, tp1)
+    }
+
     /** Return inferred type arguments of polymorphic expression, given 
      *  its type parameters and result type and a prototype <code>pt</code>.
      *  If no minimal type variables exist that make the
@@ -455,19 +441,20 @@ trait Infer {
      *  @param pt      ...
      *  @return        ...
      */
-    private def exprTypeArgs(tparams: List[Symbol], restpe: Type, pt: Type): List[Type] = {
+    private def exprTypeArgs(tparams: List[Symbol], restpe: Type, pt: Type, checkCompat: (Type, Type) => Boolean = isCompatible): List[Type] = {
       val tvars = tparams map freshVar
-      if (isCompatible(restpe.instantiateTypeParams(tparams, tvars), pt)) {
+      if (checkCompat(restpe.instantiateTypeParams(tparams, tvars), pt)) {
         try {
           // If the restpe is an implicit method, and the expected type is fully defined
-          // optimze type varianbles wrt to the implicit formals only; ignore the result type.
+          // optimze type variables wrt to the implicit formals only; ignore the result type.
           // See test pos/jesper.scala 
           val varianceType = restpe match {
-            case mt: ImplicitMethodType if isFullyDefined(pt) =>
-              MethodType(mt.paramTypes, AnyClass.tpe)
+            case mt: MethodType if mt.isImplicit && isFullyDefined(pt) =>
+              MethodType(mt.params, AnyClass.tpe)
             case _ =>
               restpe
           }
+          //println("try to solve "+tvars+" "+tparams)
           solvedTypes(tvars, tparams, tparams map varianceInType(varianceType), 
                       false, lubDepth(List(restpe, pt)))
         } catch {
@@ -496,66 +483,140 @@ trait Infer {
       /** Map type variable to its instance, or, if `variance' is covariant/contravariant,
        *  to its upper/lower bound */
       def instantiateToBound(tvar: TypeVar, variance: Int): Type = try {
-        //Console.println("instantiate "+tvar+tvar.constr+" variance = "+variance);//DEBUG
-        if (tvar.constr.inst != NoType) {
-          instantiate(tvar.constr.inst)
-        } else if ((variance & COVARIANT) != 0 && !tvar.constr.hibounds.isEmpty) {
-          tvar setInst glb(tvar.constr.hibounds)
-          assertNonCyclic(tvar)//debug
-          instantiate(tvar.constr.inst)
-        } else if ((variance & CONTRAVARIANT) != 0 && !tvar.constr.lobounds.isEmpty) {
-          tvar setInst lub(tvar.constr.lobounds)
+        lazy val hiBounds = tvar.constr.hiBounds
+        lazy val loBounds = tvar.constr.loBounds
+        lazy val upper = glb(hiBounds)
+        lazy val lower = lub(loBounds)
+        def setInst(tp: Type): Type = {
+          tvar setInst tp
           assertNonCyclic(tvar)//debug
           instantiate(tvar.constr.inst)
-        } else if (!tvar.constr.hibounds.isEmpty && !tvar.constr.lobounds.isEmpty &&
-                   glb(tvar.constr.hibounds) <:< lub(tvar.constr.lobounds)) {
-          tvar setInst glb(tvar.constr.hibounds)
-          assertNonCyclic(tvar)//debug
+        }
+        //Console.println("instantiate "+tvar+tvar.constr+" variance = "+variance);//DEBUG
+        if (tvar.constr.inst != NoType) 
           instantiate(tvar.constr.inst)
-        } else {
+        else if ((variance & COVARIANT) != 0 && hiBounds.nonEmpty)
+          setInst(upper)
+        else if ((variance & CONTRAVARIANT) != 0 && loBounds.nonEmpty)
+          setInst(lower)
+        else if (hiBounds.nonEmpty && loBounds.nonEmpty && upper <:< lower)
+          setInst(upper)
+        else
           WildcardType
-        }
       } catch {
         case ex: NoInstance => WildcardType
       }
       val tvars = tparams map freshVar
-      if (isWeaklyCompatible(restpe.instantiateTypeParams(tparams, tvars), pt))
-        List.map2(tparams, tvars) ((tparam, tvar) =>
+      if (isConservativelyCompatible(restpe.instantiateTypeParams(tparams, tvars), pt))
+        (tparams, tvars).zipped map ((tparam, tvar) =>
           instantiateToBound(tvar, varianceInTypes(formals)(tparam)))
       else 
         tvars map (tvar => WildcardType)
     }
 
+    object AdjustedTypeArgs {
+      type Result = collection.mutable.LinkedHashMap[Symbol, Option[Type]]
+
+      def unapply(m: Result): Some[(List[Symbol], List[Type])] = Some(toLists(
+        m collect {case (p, Some(a)) => (p, a)} unzip  ))
+
+      object Undets {
+        def unapply(m: Result): Some[(List[Symbol], List[Type], List[Symbol])] = Some(toLists{
+          val (ok, nok) = m.map{case (p, a) => (p, a.getOrElse(null))}.partition(_._2 ne null)
+          val (okArgs, okTparams) = ok.unzip
+          (okArgs, okTparams, nok.keys)
+        })
+      }
+
+      object AllArgsAndUndets {
+        def unapply(m: Result): Some[(List[Symbol], List[Type], List[Type], List[Symbol])] = Some(toLists{
+          val (ok, nok) = m.map{case (p, a) => (p, a.getOrElse(null))}.partition(_._2 ne null)
+          val (okArgs, okTparams) = ok.unzip
+          (okArgs, okTparams, m.values.map(_.getOrElse(NothingClass.tpe)), nok.keys)
+        })
+      }
+
+      @inline private def toLists[A1, A2](pxs: (Iterable[A1], Iterable[A2])) = (pxs._1.toList, pxs._2.toList)
+      @inline private def toLists[A1, A2, A3](pxs: (Iterable[A1], Iterable[A2], Iterable[A3])) = (pxs._1.toList, pxs._2.toList, pxs._3.toList)
+      @inline private def toLists[A1, A2, A3, A4](pxs: (Iterable[A1], Iterable[A2], Iterable[A3], Iterable[A4])) = (pxs._1.toList, pxs._2.toList, pxs._3.toList, pxs._4.toList)
+    }
+
+    /** Retract arguments that were inferred to Nothing because inference failed. Correct types for repeated params.
+     *
+     * We detect Nothing-due-to-failure by only retracting a parameter if either:
+     *  - it occurs in an invariant/contravariant position in `restpe`
+     *  - `restpe == WildcardType`
+     *
+     * Retracted parameters are mapped to None. 
+     *  TODO: 
+     *    - make sure the performance hit of storing these in a map is acceptable (it's going to be a small map in 90% of the cases, I think)
+     *    - refactor further up the callstack so that we don't have to do this post-factum adjustment?
+     *
+     * Rewrite for repeated param types:  Map T* entries to Seq[T].
+     *  @return map from tparams to inferred arg, if inference was successful, tparams that map to None are considered left undetermined
+     *    type parameters that are inferred as `scala.Nothing' and that are not covariant in <code>restpe</code> are taken to be undetermined
+     */
+    def adjustTypeArgs(tparams: List[Symbol], targs: List[Type], restpe: Type = WildcardType): AdjustedTypeArgs.Result  = {
+      @inline def notCovariantIn(tparam: Symbol, restpe: Type) =
+        (varianceInType(restpe)(tparam) & COVARIANT) == 0  // tparam occurred non-covariantly (in invariant or contravariant position)
+
+      (tparams, targs).zipped.map{ (tparam, targ) =>
+        if (targ.typeSymbol == NothingClass && 
+            (restpe.isWildcard || notCovariantIn(tparam, restpe))) {
+          tparam -> None
+        } else {
+          tparam -> Some(
+            if      (targ.typeSymbol == RepeatedParamClass)     targ.baseType(SeqClass)
+            else if (targ.typeSymbol == JavaRepeatedParamClass) targ.baseType(ArrayClass)
+            else targ.widen
+          )
+        }
+      }(collection.breakOut)
+    }
+    
     /** Return inferred type arguments, given type parameters, formal parameters,
     *  argument types, result type and expected result type.
     *  If this is not possible, throw a <code>NoInstance</code> exception.
     *  Undetermined type arguments are represented by `definitions.NothingClass.tpe'.
     *  No check that inferred parameters conform to their bounds is made here.
     *
+    *  bq: was private, but need it for unapply checking
+    *
     *  @param   tparams         the type parameters of the method
     *  @param   formals         the value parameter types of the method
     *  @param   restp           the result type of the method
     *  @param   argtpes         the argument types of the application
     *  @param   pt              the expected return type of the application
-    *  @param   uninstantiated  a listbuffer receiving all uninstantiated type parameters
-    *                           (type parameters mapped by the constraint solver to `scala.All' 
-    *                           and not covariant in <code>restpe</code> are taken to be
-    *                           uninstantiated. Maps all those type arguments to their
-    *                           corresponding type parameters).
-    *  @return                  ...
+    *  @return  @see adjustTypeArgs
+
     *  @throws                  NoInstance
     */
-    // bq: was private, but need it for unapply checking
     def methTypeArgs(tparams: List[Symbol], formals: List[Type], restpe: Type, 
-                             argtpes: List[Type], pt: Type,
-                             uninstantiated: ListBuffer[Symbol]): List[Type] = {
+                     argtpes: List[Type], pt: Type): AdjustedTypeArgs.Result = {
       val tvars = tparams map freshVar
+      if (inferInfo) 
+        println("methTypeArgs tparams = "+tparams+
+                ", formals = "+formals+
+                ", restpe = "+restpe+
+                ", argtpes = "+argtpes+
+                ", pt = "+pt+
+                ", tvars = "+tvars+" "+(tvars map (_.constr)))
       if (formals.length != argtpes.length) {
         throw new NoInstance("parameter lists differ in length")
       }
+      
+      if (inferInfo) // @MDEBUG
+        println("methTypeArgs "+
+                "  tparams = "+tparams+"\n"+
+                "  formals = "+formals+"\n"+
+                "  restpe = "+restpe+"\n"+
+                "  restpe_inst = "+restpe.instantiateTypeParams(tparams, tvars)+"\n"+
+                "  argtpes = "+argtpes+"\n"+
+                "  pt = "+pt)
+      
       // check first whether type variables can be fully defined from
       // expected result type.
-      if (!isWeaklyCompatible(restpe.instantiateTypeParams(tparams, tvars), pt)) {
+      if (!isConservativelyCompatible(restpe.instantiateTypeParams(tparams, tvars), pt)) {
 //      just wait and instantiate from the arguments.
 //      that way, we can try to apply an implicit conversion afterwards. 
 //      This case could happen if restpe is not fully defined, so that
@@ -566,30 +627,24 @@ trait Infer {
       }
       for (tvar <- tvars)
         if (!isFullyDefined(tvar)) tvar.constr.inst = NoType
-
+ 
       // Then define remaining type variables from argument types.
-      List.map2(argtpes, formals) {(argtpe, formal) =>
-        if (!isCompatible(argtpe.deconst.instantiateTypeParams(tparams, tvars),
-                          formal.instantiateTypeParams(tparams, tvars))) {
+      (argtpes, formals).zipped map { (argtpe, formal) =>
+        //@M isCompatible has side-effect: isSubtype0 will register subtype checks in the tvar's bounds
+        if (!isCompatibleArg(argtpe.deconst.instantiateTypeParams(tparams, tvars), 
+                             formal.instantiateTypeParams(tparams, tvars))) {
           throw new DeferredNoInstance(() =>
             "argument expression's type is not compatible with formal parameter type" +
             foundReqMsg(argtpe.deconst.instantiateTypeParams(tparams, tvars), formal.instantiateTypeParams(tparams, tvars)))
         }
         ()
       }
+      if (inferInfo)
+        println("solve "+tvars+" "+(tvars map (_.constr)))
       val targs = solvedTypes(tvars, tparams, tparams map varianceInTypes(formals), 
                               false, lubDepth(formals) max lubDepth(argtpes))
-//      val res = 
-      List.map2(tparams, targs) {(tparam, targ) =>
-        if (targ.typeSymbol == NothingClass && (varianceInType(restpe)(tparam) & COVARIANT) == 0) {
-          uninstantiated += tparam
-          tparam.tpe  //@M TODO: might be affected by change to tpe in Symbol
-        } else if (targ.typeSymbol == RepeatedParamClass) {
-          targ.baseType(SeqClass)
-        } else {
-          targ.widen
-        }
-      }
+//      val res =
+      adjustTypeArgs(tparams, targs, restpe)
 //      println("meth type args "+", tparams = "+tparams+", formals = "+formals+", restpe = "+restpe+", argtpes = "+argtpes+", underlying = "+(argtpes map (_.widen))+", pt = "+pt+", uninstantiated = "+uninstantiated.toList+", result = "+res) //DEBUG
 //      res
     }
@@ -608,16 +663,72 @@ trait Infer {
       case OverloadedType(pre, alts) =>
         alts exists (alt => hasExactlyNumParams(pre.memberType(alt), n))
       case _ =>
-        formalTypes(tp.paramTypes, n).length == n
+        val len = tp.params.length
+        len == n || isVarArgs(tp.params) && len <= n + 1
     }
 
+    /**
+     * Verifies whether the named application is valid. The logic is very
+     * similar to the one in NamesDefaults.removeNames.
+     *
+     * @return a triple (argtpes1, argPos, namesOk) where
+     *  - argtpes1 the argument types in named application (assignments to
+     *    non-parameter names are treated as assignments, i.e. type Unit)
+     *  - argPos a Function1[Int, Int] mapping arguments from their current
+     *    to the corresponding position in params
+     *  - namesOK is false when there's an invalid use of named arguments
+     */
+    private def checkNames(argtpes: List[Type], params: List[Symbol]) = {
+      val argPos = (new Array[Int](argtpes.length)) map (x => -1)
+      var positionalAllowed = true
+      var namesOK = true
+      var index = 0
+      val argtpes1 = argtpes map {
+        case NamedType(name, tp) => // a named argument
+          var res = tp
+          val pos = params.indexWhere(p => p.name == name && !p.hasFlag(SYNTHETIC))
+          if (pos == -1) {
+            if (positionalAllowed) { // treat assignment as positional argument
+              argPos(index) = index
+              res = UnitClass.tpe
+            } else                   // unknown parameter name
+              namesOK = false
+          } else if (argPos.contains(pos)) { // parameter specified twice
+            namesOK = false
+          } else {
+            positionalAllowed = false
+            argPos(index) = pos
+          }
+          index += 1
+          res
+        case tp => // a positional argument
+          argPos(index) = index
+          if (!positionalAllowed)
+            namesOK = false // positional after named
+          index += 1
+          tp
+      }
+      (argtpes1, argPos, namesOK)
+    }
+
+    /** don't do a () to (()) conversion for methods whose second parameter
+     * is a varargs. This is a fairly kludgey way to address #3224. 
+     * We'll probably find a better way to do this by identifying
+     * tupled and n-ary methods, but thiws is something for a future major revision.
+     */
+    def isUnitForVarArgs(args: List[AnyRef], params: List[Symbol]): Boolean = 
+      args.length == 0 && params.length == 2 && isVarArgs(params)
+
     /** Is there an instantiation of free type variables <code>undetparams</code>
      *  such that function type <code>ftpe</code> is applicable to
      *  <code>argtpes</code> and its result conform to <code>pt</code>?
      *
      *  @param undetparams ...
-     *  @param ftpe        ...
-     *  @param argtpes     ...
+     *  @param ftpe        the type of the function (often a MethodType)
+     *  @param argtpes     the argument types; a NamedType(name, tp) for named
+     *    arguments. For each NamedType, if `name' does not exist in `ftpe', that
+     *    type is set to `Unit', i.e. the corresponding argument is treated as
+     *    an assignment expression (@see checkNames).
      *  @param pt          ...
      *  @return            ...
      */
@@ -628,24 +739,75 @@ trait Infer {
           alts exists (alt => isApplicable(undetparams, pre.memberType(alt), argtpes0, pt))
         case ExistentialType(tparams, qtpe) =>
           isApplicable(undetparams, qtpe, argtpes0, pt)
-        case MethodType(formals0, _) =>
+        case MethodType(params, _) =>
+          val formals0 = params map { param => 
+            param.tpe match {
+              case TypeRef(_, sym, List(tpe)) if sym isNonBottomSubClass CodeClass => tpe
+              case tpe => tpe
+            }
+          }
           val formals = formalTypes(formals0, argtpes0.length)
-          val argtpes = actualTypes(argtpes0, formals.length)
-          val restpe = ftpe.resultType(argtpes)
-          if (undetparams.isEmpty) {
-            (formals.length == argtpes.length &&
-             isCompatible(argtpes, formals) && 
-             isWeaklyCompatible(restpe, pt))
+
+          def tryTupleApply: Boolean = {
+            // if 1 formal, 1 argtpe (a tuple), otherwise unmodified argtpes0
+            val tupleArgTpes = actualTypes(argtpes0 map {
+                // no assignment is treated as named argument here
+              case NamedType(name, tp) => UnitClass.tpe
+              case tp => tp
+              }, formals.length)
+
+            argtpes0.length != tupleArgTpes.length && 
+            !isUnitForVarArgs(argtpes0, params) &&
+            isApplicable(undetparams, ftpe, tupleArgTpes, pt)
+          }
+          def typesCompatible(argtpes: List[Type]) = {
+            val restpe = ftpe.resultType(argtpes)
+            if (undetparams.isEmpty) {
+              isCompatibleArgs(argtpes, formals) && isWeaklyCompatible(restpe, pt)
+            } else {
+              try {
+                val AdjustedTypeArgs.Undets(okparams, okargs, leftUndet) = methTypeArgs(undetparams, formals, restpe, argtpes, pt)
+                // #2665: must use weak conformance, not regular one (follow the monomorphic case above)
+                (exprTypeArgs(leftUndet, restpe.instantiateTypeParams(okparams, okargs), pt, isWeaklyCompatible) ne null) && 
+                isWithinBounds(NoPrefix, NoSymbol, okparams, okargs)
+              } catch {
+                case ex: NoInstance => false
+              }
+            }
+          }
+
+          // very similar logic to doTypedApply in typechecker
+          if (argtpes0.length > formals.length) tryTupleApply
+          else if (argtpes0.length == formals.length) {
+            if (!argtpes0.exists(_.isInstanceOf[NamedType])) {
+              // fast track if no named arguments are used
+              typesCompatible(argtpes0)
+            } else {
+              // named arguments are used
+              val (argtpes1, argPos, namesOK) = checkNames(argtpes0, params)
+              if (!namesOK) false
+              // when using named application, the vararg param has to be specified exactly once
+              else if (!isIdentity(argPos) && (formals.length != params.length)) false
+              else {
+                // nb. arguments and names are OK, check if types are compatible
+                typesCompatible(reorderArgs(argtpes1, argPos))
+              }
+            }
           } else {
-            try {
-              val uninstantiated = new ListBuffer[Symbol]
-              val targs = methTypeArgs(undetparams, formals, restpe, argtpes, pt, uninstantiated)
-              (exprTypeArgs(uninstantiated.toList, restpe.instantiateTypeParams(undetparams, targs), pt) ne null) &&
-              isWithinBounds(NoPrefix, NoSymbol, undetparams, targs)
-            } catch {
-              case ex: NoInstance => false
+            // not enough arguments, check if applicable using defaults
+            val missing = missingParams[Type](argtpes0, params, {
+              case NamedType(name, _) => Some(name)
+              case _ => None
+            })._1
+            if (missing.exists(!_.hasFlag(DEFAULTPARAM))) tryTupleApply
+            else {
+              val argtpes1 = argtpes0 ::: missing.map {
+                p => NamedType(p.name, p.tpe) // add defaults as named arguments
+              }
+              isApplicable(undetparams, ftpe, argtpes1, pt)
             }
           }
+
         case PolyType(tparams, restpe) =>
           val tparams1 = cloneSymbols(tparams)
           isApplicable(tparams1 ::: undetparams, restpe.substSym(tparams, tparams1), argtpes0, pt)
@@ -655,14 +817,22 @@ trait Infer {
           false
       }
 
-    private[typechecker] def isApplicableSafe(undetparams: List[Symbol], ftpe: Type, argtpes0: List[Type], pt: Type): Boolean = {
+    /** Todo: Try to make isApplicable always safe (i.e. not cause TypeErrors).
+     */
+    private[typechecker] def isApplicableSafe(undetparams: List[Symbol], ftpe: Type,
+                                              argtpes0: List[Type], pt: Type): Boolean = {
       val reportAmbiguousErrors = context.reportAmbiguousErrors
       context.reportAmbiguousErrors = false
       try {
         isApplicable(undetparams, ftpe, argtpes0, pt)
       } catch {
         case ex: TypeError =>
-          false
+          try {
+            isApplicable(undetparams, ftpe, argtpes0, WildcardType)
+          } catch {
+            case ex: TypeError =>
+              false
+          }
       } finally {
         context.reportAmbiguousErrors = reportAmbiguousErrors
       }
@@ -676,36 +846,89 @@ trait Infer {
      *  @param ftpe2 ...
      *  @return      ...
      */
-    def isMoreSpecific(ftpe1: Type, ftpe2: Type): Boolean = ftpe1 match {
+    def isAsSpecific(ftpe1: Type, ftpe2: Type): Boolean = ftpe1 match {
       case OverloadedType(pre, alts) =>
-        alts exists (alt => isMoreSpecific(pre.memberType(alt), ftpe2))
+        alts exists (alt => isAsSpecific(pre.memberType(alt), ftpe2))
       case et: ExistentialType =>
-        et.withTypeVars(isStrictlyMoreSpecific(_, ftpe2))
-      case MethodType(formals @ (x :: xs), _) =>
-        isApplicable(List(), ftpe2, formals, WildcardType)
-      case PolyType(_, MethodType(formals @ (x :: xs), _)) =>
-        isApplicable(List(), ftpe2, formals, WildcardType)
+        isAsSpecific(ftpe1.skolemizeExistential, ftpe2)
+        //et.withTypeVars(isAsSpecific(_, ftpe2)) 
+      case mt: MethodType if mt.isImplicit =>
+        isAsSpecific(ftpe1.resultType, ftpe2)
+      case MethodType(params @ (x :: xs), _) =>
+        var argtpes = params map (_.tpe)
+        if (isVarArgs(params) && isVarArgs(ftpe2.params))
+          argtpes = argtpes map (argtpe => 
+            if (isRepeatedParamType(argtpe)) argtpe.typeArgs.head else argtpe)
+        isApplicable(List(), ftpe2, argtpes, WildcardType)
+      case PolyType(tparams, mt: MethodType) if mt.isImplicit =>
+        isAsSpecific(PolyType(tparams, mt.resultType), ftpe2)
+      case PolyType(_, MethodType(params @ (x :: xs), _)) =>
+        isApplicable(List(), ftpe2, params map (_.tpe), WildcardType)
       case ErrorType =>
         true
       case _ =>
         ftpe2 match {
           case OverloadedType(pre, alts) =>
-            alts forall (alt => isMoreSpecific(ftpe1, pre.memberType(alt)))
+            alts forall (alt => isAsSpecific(ftpe1, pre.memberType(alt)))
           case et: ExistentialType =>
-            et.withTypeVars(isStrictlyMoreSpecific(ftpe1, _))
-          case MethodType(_, _) | PolyType(_, MethodType(_, _)) =>
-            true
+            et.withTypeVars(isAsSpecific(ftpe1, _))
+          case mt: MethodType =>
+            !mt.isImplicit || isAsSpecific(ftpe1, mt.resultType)
+          case PolyType(tparams, mt: MethodType) =>
+            !mt.isImplicit || isAsSpecific(ftpe1, PolyType(tparams, mt.resultType))
           case _ =>
-            isMoreSpecificValueType(ftpe1, ftpe2, List(), List())
+            isAsSpecificValueType(ftpe1, ftpe2, List(), List())
         }
     }
 
+/*
     def isStrictlyMoreSpecific(ftpe1: Type, ftpe2: Type): Boolean =
-      ftpe1.isError || isMoreSpecific(ftpe1, ftpe2) && 
-      (!isMoreSpecific(ftpe2, ftpe1) || 
+      ftpe1.isError || isAsSpecific(ftpe1, ftpe2) && 
+      (!isAsSpecific(ftpe2, ftpe1) || 
        !ftpe1.isInstanceOf[OverloadedType] && ftpe2.isInstanceOf[OverloadedType] ||
        phase.erasedTypes && covariantReturnOverride(ftpe1, ftpe2))
+*/
+    /** Is sym1 (or its companion class in case it is a module) a subclass of
+     *  sym2 (or its companion class in case it is a module)?
+     */
+    def isProperSubClassOrObject(sym1: Symbol, sym2: Symbol): Boolean =
+      sym1 != sym2 && sym1 != NoSymbol && (sym1 isSubClass sym2) ||
+      sym1.isModuleClass && isProperSubClassOrObject(sym1.linkedClassOfClass, sym2) ||
+      sym2.isModuleClass && isProperSubClassOrObject(sym1, sym2.linkedClassOfClass)
 
+    /** is symbol `sym1` defined in a proper subclass of symbol `sym2`?
+     */
+    def isInProperSubClassOrObject(sym1: Symbol, sym2: Symbol) = 
+      sym2 == NoSymbol || isProperSubClassOrObject(sym1.owner, sym2.owner)
+
+    def isStrictlyMoreSpecific(ftpe1: Type, ftpe2: Type, sym1: Symbol, sym2: Symbol): Boolean = {
+      // ftpe1 / ftpe2 are OverloadedTypes (possibly with one single alternative) if they
+      // denote the type of an "apply" member method (see "followApply")
+      ftpe1.isError || {
+        val specificCount = (if (isAsSpecific(ftpe1, ftpe2)) 1 else 0) - 
+                            (if (isAsSpecific(ftpe2, ftpe1) &&
+                                 // todo: move to isAsSpecific test
+//                                 (!ftpe2.isInstanceOf[OverloadedType] || ftpe1.isInstanceOf[OverloadedType]) &&
+                                 (!phase.erasedTypes || covariantReturnOverride(ftpe1, ftpe2))) 1 else 0)
+        val subClassCount = (if (isInProperSubClassOrObject(sym1, sym2)) 1 else 0) -
+                            (if (isInProperSubClassOrObject(sym2, sym1)) 1 else 0)
+//        println("is more specific? "+sym1+":"+ftpe1+sym1.locationString+"/"+sym2+":"+ftpe2+sym2.locationString+":"+
+//                specificCount+"/"+subClassCount)
+        specificCount + subClassCount > 0
+      }
+    }
+/*
+      ftpe1.isError || {
+        if (isAsSpecific(ftpe1, ftpe2)) 
+          (!isAsSpecific(ftpe2, ftpe1) || 
+           isProperSubClassOrObject(sym1.owner, sym2.owner) ||
+           !ftpe1.isInstanceOf[OverloadedType] && ftpe2.isInstanceOf[OverloadedType] ||
+           phase.erasedTypes && covariantReturnOverride(ftpe1, ftpe2))
+        else
+          !isAsSpecific(ftpe2, ftpe1) && 
+          isProperSubClassOrObject(sym1.owner, sym2.owner)
+      }
+*/
     private def covariantReturnOverride(ftpe1: Type, ftpe2: Type): Boolean = (ftpe1, ftpe2) match {
       case (MethodType(_, rtpe1), MethodType(_, rtpe2)) =>
         rtpe1 <:< rtpe2 || rtpe2.typeSymbol == ObjectClass
@@ -713,11 +936,11 @@ trait Infer {
         false
     }
 
-    private def isMoreSpecificValueType(tpe1: Type, tpe2: Type, undef1: List[Symbol], undef2: List[Symbol]): Boolean = (tpe1, tpe2) match {
+    private def isAsSpecificValueType(tpe1: Type, tpe2: Type, undef1: List[Symbol], undef2: List[Symbol]): Boolean = (tpe1, tpe2) match {
       case (PolyType(tparams1, rtpe1), _) =>
-        isMoreSpecificValueType(rtpe1, tpe2, undef1 ::: tparams1, undef2)
+        isAsSpecificValueType(rtpe1, tpe2, undef1 ::: tparams1, undef2)
       case (_, PolyType(tparams2, rtpe2)) =>
-        isMoreSpecificValueType(tpe1, rtpe2, undef1, undef2 ::: tparams2)
+        isAsSpecificValueType(tpe1, rtpe2, undef1, undef2 ::: tparams2)
       case _ =>
         existentialAbstraction(undef1, tpe1) <:< existentialAbstraction(undef2, tpe2)
     }
@@ -742,7 +965,7 @@ trait Infer {
     def isStrictlyBetter(tpe1: Type, tpe2: Type) = {
       def isNullary(tpe: Type): Boolean = tpe match {
         case tp: RewrappingTypeProxy => isNullary(tp.underlying)
-        case _ => tpe.paramSectionCount == 0 || tpe.paramTypes.isEmpty
+        case _ => tpe.paramSectionCount == 0 || tpe.params.isEmpty
       }
       def isMethod(tpe: Type): Boolean = tpe match {
         case tp: RewrappingTypeProxy => isMethod(tp.underlying)
@@ -772,12 +995,12 @@ trait Infer {
       //@M TODO: errors for getters & setters are reported separately
       val kindErrors = checkKindBounds(tparams, targs, pre, owner)
            
-      if(!kindErrors.isEmpty)
+      if(!kindErrors.isEmpty) {
         error(pos, 
-          prefix + "the kinds of the type arguments " + targs.mkString("(", ",", ")") + 
+          prefix + "kinds of the type arguments " + targs.mkString("(", ",", ")") + 
           " do not conform to the expected kinds of the type parameters "+ tparams.mkString("(", ",", ")") + tparams.head.locationString+ "." +
           kindErrors.toList.mkString("\n", ", ", "")) 
-      else if (!isWithinBounds(pre, owner, tparams, targs)) { 
+      } else if (!isWithinBounds(pre, owner, tparams, targs)) { 
         if (!(targs exists (_.isErroneous)) && !(tparams exists (_.isErroneous))) {
           //val bounds = instantiatedBounds(pre, owner, tparams, targs)//DEBUG
           //println("bounds = "+bounds+", targs = "+targs+", targclasses = "+(targs map (_.getClass))+", parents = "+(targs map (_.parents)))
@@ -788,79 +1011,16 @@ trait Infer {
                 (tparams map (_.defString)).mkString("[", ",", "]"))
           if (settings.explaintypes.value) {
             val bounds = tparams map (tp => tp.info.instantiateTypeParams(tparams, targs).bounds)
-            List.map2(targs, bounds)((targ, bound) => explainTypes(bound.lo, targ))
-            List.map2(targs, bounds)((targ, bound) => explainTypes(targ, bound.hi))
+            (targs, bounds).zipped foreach ((targ, bound) => explainTypes(bound.lo, targ))
+            (targs, bounds).zipped foreach ((targ, bound) => explainTypes(targ, bound.hi))
             ()
           }
         }
       }
     }
     
-    /** Check whether <arg>sym1</arg>'s variance conforms to <arg>sym2</arg>'s variance
-     *
-     * If <arg>sym2</arg> is invariant, <arg>sym1</arg>'s variance is irrelevant. Otherwise they must be equal.
-     */
-    def variancesMatch(sym1: Symbol, sym2: Symbol): Boolean = (sym2.variance==0 || sym1.variance==sym2.variance)
-      
-    /** Check well-kindedness of type application (assumes arities are already checked) -- @M
-     * 
-     * This check is also performed when abstract type members become concrete (aka a "type alias") -- then tparams.length==1
-     * (checked one type member at a time -- in that case, prefix is the name of the type alias)
-     *
-     * Type application is just like value application: it's "contravariant" in the sense that 
-     * the type parameters of the supplied type arguments must conform to the type parameters of 
-     * the required type parameters:
-     *   - their bounds must be less strict
-     *   - variances must match (here, variances are absolute, the variance of a type parameter does not influence the variance of its higher-order parameters)     
-     *   - @M TODO: are these conditions correct,sufficient&necessary?
-     *
-     *  e.g. class Iterable[t, m[+x <: t]] --> the application Iterable[Int, List] is okay, since 
-     *       List's type parameter is also covariant and its bounds are weaker than <: Int
-     */
-    def checkKindBounds(tparams: List[Symbol], targs: List[Type], pre: Type, owner: Symbol): List[String] = {
-      def transform(tp: Type, clazz: Symbol): Type = tp.asSeenFrom(pre, clazz) // instantiate type params that come from outside the abstract type we're currently checking
-
-      // check that the type parameters <arg>hkargs</arg> to a higher-kinded type conform to the expected params <arg>hkparams</arg>
-      def checkKindBoundsHK(hkargs: List[Symbol], arg: Symbol, param: Symbol, paramowner: Symbol): (List[(Symbol, Symbol)], List[(Symbol, Symbol)], List[(Symbol, Symbol)]) = {
-// NOTE: sometimes hkargs != arg.typeParams, the symbol and the type may have very different type parameters
-        val hkparams = param.typeParams
-
-        if(hkargs.length != hkparams.length) {
-          if(arg == AnyClass || arg == NothingClass) (Nil, Nil, Nil) // Any and Nothing are kind-overloaded
-          else (List((arg, param)), Nil, Nil)
-        } else {
-          val _arityMismatches = new ListBuffer[(Symbol, Symbol)]
-          val _varianceMismatches = new ListBuffer[(Symbol, Symbol)]
-          val _stricterBounds = new ListBuffer[(Symbol, Symbol)] 
-          def varianceMismatch(a: Symbol, p: Symbol) { _varianceMismatches += (a, p) }
-          def stricterBound(a: Symbol, p: Symbol) { _stricterBounds += (a, p) }
-          def arityMismatches(as: Iterable[(Symbol, Symbol)]) { _arityMismatches ++= as }
-          def varianceMismatches(as: Iterable[(Symbol, Symbol)]) { _varianceMismatches ++= as }
-          def stricterBounds(as: Iterable[(Symbol, Symbol)]) { _stricterBounds ++= as }
-
-          for ((hkarg, hkparam) <- hkargs zip hkparams) { 
-            if (hkparam.typeParams.isEmpty) { // base-case: kind *
-              if (!variancesMatch(hkarg, hkparam))
-                varianceMismatch(hkarg, hkparam)                                         
-              
-              // instantiateTypeParams(tparams, targs) --> higher-order bounds may contain references to type arguments
-              // substSym(hkparams, hkargs) --> these types are going to be compared as types of kind * 
-              //    --> their arguments use different symbols, but are conceptually the same 
-              //        (could also replace the types by polytypes, but can't just strip the symbols, as ordering is lost then)
-              if (!(transform(hkparam.info.instantiateTypeParams(tparams, targs).bounds.substSym(hkparams, hkargs), paramowner) <:< transform(hkarg.info.bounds, owner)))
-                stricterBound(hkarg, hkparam)
-            } else {
-              val (am, vm, sb) = checkKindBoundsHK(hkarg.typeParams, hkarg, hkparam, paramowner)
-              arityMismatches(am)
-              varianceMismatches(vm)
-              stricterBounds(sb)
-            }
-          }      
-              
-          (_arityMismatches.toList, _varianceMismatches.toList, _stricterBounds.toList)
-        }    
-      }
 
+    def checkKindBounds(tparams: List[Symbol], targs: List[Type], pre: Type, owner: Symbol): List[String] = {
       // @M TODO this method is duplicated all over the place (varianceString)
       def varStr(s: Symbol): String =
         if (s.isCovariant) "covariant"
@@ -868,38 +1028,30 @@ trait Infer {
         else "invariant";                                                
 
       def qualify(a0: Symbol, b0: Symbol): String = if (a0.toString != b0.toString) "" else { 
-        assert(a0 ne b0)
-        assert(a0.owner ne b0.owner)
-        var a = a0; var b = b0
-        while (a.owner.name == b.owner.name) { a = a.owner; b = b.owner}
-        if (a.locationString ne "") " (" + a.locationString.trim + ")" else ""
-      }
-      
-      val errors = new ListBuffer[String]
-      (tparams zip targs).foreach{ case (tparam, targ) if(targ.isHigherKinded || !tparam.typeParams.isEmpty) => //println("check: "+(tparam, targ))
-        val (arityMismatches, varianceMismatches, stricterBounds) = 
-          checkKindBoundsHK(targ.typeParams, targ.typeSymbolDirect, tparam, tparam.owner) // NOTE: *not* targ.typeSymbol, which normalizes
-            // NOTE 2: must use the typeParams of the type targ, not the typeParams of the symbol of targ!!
-        
-        if (!(arityMismatches.isEmpty && varianceMismatches.isEmpty && stricterBounds.isEmpty)){
-          errors += (targ+"'s type parameters do not match "+tparam+"'s expected parameters: "+ 
-            (for ((a, p) <- arityMismatches)
-             yield a+qualify(a,p)+ " has "+reporter.countElementsAsString(a.typeParams.length, "type parameter")+", but "+
-              p+qualify(p,a)+" has "+reporter.countAsString(p.typeParams.length)).toList.mkString(", ") +
-            (for ((a, p) <- varianceMismatches)
-             yield a+qualify(a,p)+ " is "+varStr(a)+", but "+
-              p+qualify(p,a)+" is declared "+varStr(p)).toList.mkString(", ") +
-            (for ((a, p) <- stricterBounds)
-              yield a+qualify(a,p)+"'s bounds "+a.info+" are stricter than "+
-              p+qualify(p,a)+"'s declared bounds "+p.info).toList.mkString(", "))
+        if((a0 eq b0) || (a0.owner eq b0.owner)) "" 
+        else {
+          var a = a0; var b = b0
+          while (a.owner.name == b.owner.name) { a = a.owner; b = b.owner}
+          if (a.locationString ne "") " (" + a.locationString.trim + ")" else ""
         }
-       // case (tparam, targ) => println("no check: "+(tparam, targ, tparam.typeParams.isEmpty))                                                             
-       case _ =>
       }
-      
-      errors.toList
+
+      val errors = checkKindBounds0(tparams, targs, pre, owner, true)
+      val errorMessages = new ListBuffer[String]
+      errors foreach {case (targ, tparam, arityMismatches, varianceMismatches, stricterBounds) => errorMessages +=
+        (targ+"'s type parameters do not match "+tparam+"'s expected parameters: "+ 
+        (for ((a, p) <- arityMismatches)
+          yield a+qualify(a,p)+ " has "+reporter.countElementsAsString(a.typeParams.length, "type parameter")+", but "+
+            p+qualify(p,a)+" has "+reporter.countAsString(p.typeParams.length)).toList.mkString(", ") +
+        (for ((a, p) <- varianceMismatches)
+          yield a+qualify(a,p)+ " is "+varStr(a)+", but "+
+            p+qualify(p,a)+" is declared "+varStr(p)).toList.mkString(", ") +
+        (for ((a, p) <- stricterBounds)
+          yield a+qualify(a,p)+"'s bounds "+a.info+" are stricter than "+
+            p+qualify(p,a)+"'s declared bounds "+p.info).toList.mkString(", "))
+      }
+      errorMessages.toList
     }
-      
     /** Substitite free type variables `undetparams' of polymorphic argument
      *  expression `tree', given two prototypes `strictPt', and `lenientPt'.
      *  `strictPt' is the first attempt prototype where type parameters
@@ -922,21 +1074,40 @@ trait Infer {
       substExpr(tree, undetparams, targs, lenientPt)
     }
 
-    /** Substitute free type variables `undetparams; of polymorphic expression
-     *  <code>tree</code>, given prototype <code>pt</code>.
-     *
-     *  @param tree ...
-     *  @param undetparams ...
-     *  @param pt ...
+    /** Infer type arguments for `tparams` of polymorphic expression in `tree`, given prototype `pt`.
      */
-    def inferExprInstance(tree: Tree, undetparams: List[Symbol], pt: Type) {
+    def inferExprInstance(tree: Tree, tparams: List[Symbol], pt: Type, keepNothings: Boolean): List[Symbol] = {
       if (inferInfo)
         println("infer expr instance "+tree+":"+tree.tpe+"\n"+
-                "  undetparams = "+undetparams+"\n"+
+                "  tparams = "+tparams+"\n"+
                 "  pt = "+pt)
-      substExpr(tree, undetparams, exprTypeArgs(undetparams, tree.tpe, pt), pt)
+      substAdjustedArgs(tree, tparams, pt, exprTypeArgs(tparams, tree.tpe, pt), keepNothings)
+    }
+
+    /** Infer type arguments for `tparams` of polymorphic expression in `tree`, given prototype `pt`.
+     * Use specified type `treeTp` instead of `tree.tp`
+     */
+    def inferExprInstance(tree: Tree, tparams: List[Symbol], pt: Type, treeTp: Type, keepNothings: Boolean): List[Symbol] = {
       if (inferInfo)
-        println("inferred expr instance "+tree)
+        println("infer expr instance "+tree+":"+tree.tpe+"\n"+
+                "  tparams = "+tparams+"\n"+
+                "  pt = "+pt)
+      substAdjustedArgs(tree, tparams, pt, exprTypeArgs(tparams, treeTp, pt), keepNothings)
+    }
+
+    /** Substitute tparams to targs, after adjustment by adjustTypeArgs,
+     * return tparams that were not determined
+     */
+    def substAdjustedArgs(tree: Tree, tparams: List[Symbol], pt: Type, targs: List[Type], keepNothings: Boolean): List[Symbol] = {
+      if (keepNothings || (targs eq null)) { //@M: adjustTypeArgs fails if targs==null, neg/t0226
+        substExpr(tree, tparams, targs, pt)
+        List()
+      } else {
+        val AdjustedTypeArgs.Undets(okParams, okArgs, leftUndet) = adjustTypeArgs(tparams, targs)
+        if (inferInfo) println("inferred expr instance for "+ tree +" --> (okParams, okArgs, leftUndet)= "+(okParams, okArgs, leftUndet))
+        substExpr(tree, okParams, okArgs, pt)
+        leftUndet
+      }
     }
 
     /** Substitite free type variables `undetparams' of polymorphic argument
@@ -958,36 +1129,35 @@ trait Infer {
       }
     }
 
-    /** Substitite free type variables <code>undetparams</code> of application
+    /** Substitute free type variables <code>undetparams</code> of application
      *  <code>fn(args)</code>, given prototype <code>pt</code>.
      *
      *  @param fn          ...
      *  @param undetparams ...
      *  @param args        ...
      *  @param pt          ...
-     *  @return            Return the list of type parameters that remain uninstantiated.
+     *  @return            The type parameters that remain uninstantiated, 
+     *                     and that thus have not been substituted.
      */
     def inferMethodInstance(fn: Tree, undetparams: List[Symbol],
-                            args: List[Tree], pt: Type): List[Symbol] = fn.tpe match {
-      case MethodType(formals0, _) =>
+                            args: List[Tree], pt0: Type): List[Symbol] = fn.tpe match {
+      case MethodType(params0, _) =>
         if (inferInfo)
           println("infer method instance "+fn+"\n"+
                   "  undetparams = "+undetparams+"\n"+
                   "  args = "+args+"\n"+
-                  "  pt = "+pt)
+                  "  pt = "+pt0)
         try {
-          val formals = formalTypes(formals0, args.length)
+          val pt = if (pt0.typeSymbol == UnitClass) WildcardType else pt0
+          val formals = formalTypes(params0 map (_.tpe), args.length)
           val argtpes = actualTypes(args map (_.tpe.deconst), formals.length)
           val restpe = fn.tpe.resultType(argtpes)
-          val uninstantiated = new ListBuffer[Symbol]
-          val targs = methTypeArgs(undetparams, formals, restpe, argtpes, pt, uninstantiated)
-          checkBounds(fn.pos, NoPrefix, NoSymbol, undetparams, targs, "inferred ")
-          //Console.println("UNAPPLY subst type "+undetparams+" to "+targs+" in "+fn+" ( "+args+ ")")
-          val treeSubst = new TreeTypeSubstituter(undetparams, targs)
+          val AdjustedTypeArgs.AllArgsAndUndets(okparams, okargs, allargs, leftUndet) = methTypeArgs(undetparams, formals, restpe, argtpes, pt)
+          checkBounds(fn.pos, NoPrefix, NoSymbol, undetparams, allargs, "inferred ")
+          val treeSubst = new TreeTypeSubstituter(okparams, okargs)
           treeSubst.traverse(fn)
           treeSubst.traverseTrees(args)
-          //Console.println("UNAPPLY gives "+fn+" ( "+args+ "), argtpes = "+argtpes+", pt = "+pt)
-          uninstantiated.toList
+          leftUndet
         } catch {
           case ex: NoInstance =>
             errorTree(fn, 
@@ -1007,7 +1177,7 @@ trait Infer {
       case TypeRef(_, sym, _) if sym.isAliasType => 
         widen(tp.normalize)
       case rtp @ RefinedType(parents, decls) => 
-        copyRefinedType(rtp, List.mapConserve(parents)(widen), decls)
+        copyRefinedType(rtp, parents mapConserve (widen), decls)
       case AnnotatedType(_, underlying, _) =>
         widen(underlying)
       case _ =>
@@ -1066,7 +1236,7 @@ trait Infer {
             ptvars foreach instantiateTypeVar
           } else { if (settings.debug.value) Console.println("no instance: "); instError }
         } else { if (settings.debug.value) Console.println("not a subtype " + restpe.instantiateTypeParams(undetparams, tvars) + " of " + ptWithWildcards); instError }
-      } else { if (settings.debug.value) Console.println("not fuly defined: " + pt); instError }
+      } else { if (settings.debug.value) Console.println("not fully defined: " + pt); instError }
     }
 
     def instBounds(tvar: TypeVar): (Type, Type) = {
@@ -1074,24 +1244,21 @@ trait Infer {
       val instType = toOrigin(tvar.constr.inst)
       val (loBounds, hiBounds) =
         if (instType != NoType && isFullyDefined(instType)) (List(instType), List(instType))
-        else (tvar.constr.lobounds, tvar.constr.hibounds)
+        else (tvar.constr.loBounds, tvar.constr.hiBounds)
       val lo = lub(tparam.info.bounds.lo :: loBounds map toOrigin)
       val hi = glb(tparam.info.bounds.hi :: hiBounds map toOrigin)
       (lo, hi)
     }
 
     def isInstantiatable(tvars: List[TypeVar]) = {
-      def cloneTypeVar(tv: TypeVar) = {
-        val tv1 = TypeVar(tv.origin, new TypeConstraint(tv.constr.lobounds, tv.constr.hibounds))
-        tv1.constr.inst = tv.constr.inst
-        tv1
-      }
-      val tvars1 = tvars map cloneTypeVar
+      val tvars1 = tvars map (_.cloneInternal)
       // Note: right now it's not clear that solving is complete, or how it can be made complete!
       // So we should come back to this and investigate.
       solve(tvars1, tvars1 map (_.origin.typeSymbol), tvars1 map (x => COVARIANT), false)  
     }
 
+    // this is quite nasty: it destructively changes the info of the syms of e.g., method type params (see #3692, where the type param T's bounds were set to >: T <: T, so that parts looped)
+    // the changes are rolled back by restoreTypeBounds, but might be unintentially observed in the mean time
     def instantiateTypeVar(tvar: TypeVar) {
       val tparam = tvar.origin.typeSymbol
       if (false && 
@@ -1105,9 +1272,10 @@ trait Infer {
       } else {
         val (lo, hi) = instBounds(tvar)
         if (lo <:< hi) {
-          if (!((lo <:< tparam.info.bounds.lo) && (tparam.info.bounds.hi <:< hi))) {
+          if (!((lo <:< tparam.info.bounds.lo) && (tparam.info.bounds.hi <:< hi)) // bounds were improved
+             && tparam != lo.typeSymbolDirect && tparam != hi.typeSymbolDirect) { // don't create illegal cycles
             context.nextEnclosing(_.tree.isInstanceOf[CaseDef]).pushTypeBounds(tparam)
-            tparam setInfo mkTypeBounds(lo, hi)
+            tparam setInfo TypeBounds(lo, hi)
             if (settings.debug.value) log("new bounds of " + tparam + " = " + tparam.info)
           } else {
             if (settings.debug.value) log("redundant: "+tparam+" "+tparam.info+"/"+lo+" "+hi)
@@ -1119,8 +1287,8 @@ trait Infer {
     }
 
     def checkCheckable(pos: Position, tp: Type, kind: String) {
-      def patternWarning(tp: Type, prefix: String) = {
-        context.unit.uncheckedWarning(pos, prefix+tp+" in type"+kind+" is unchecked since it is eliminated by erasure")
+      def patternWarning(tp0: Type, prefix: String) = {
+        context.unit.uncheckedWarning(pos, prefix+tp0+" in type "+kind+tp+" is unchecked since it is eliminated by erasure")
       }
       def check(tp: Type, bound: List[Symbol]) {
         def isLocalBinding(sym: Symbol) =
@@ -1134,13 +1302,13 @@ trait Infer {
           case SingleType(pre, _) => 
             check(pre, bound)
           case TypeRef(pre, sym, args) => 
-            if (sym.isAbstractType) 
-              patternWarning(tp, "abstract type ")
-            else if (sym.isAliasType)
+            if (sym.isAbstractType) {
+              if (!isLocalBinding(sym)) patternWarning(tp, "abstract type ")
+            } else if (sym.isAliasType) {
               check(tp.normalize, bound)
-            else if (sym == NothingClass || sym == NullClass) 
-              error(pos, "this type cannot be used in a type pattern")
-            else
+            } else if (sym == NothingClass || sym == NullClass || sym == AnyValClass) {
+              error(pos, "type "+tp+" cannot be used in a type pattern or isInstanceOf test")
+            } else {
               for (arg <- args) {
                 if (sym == ArrayClass) check(arg, bound)
                 else arg match {
@@ -1150,6 +1318,7 @@ trait Infer {
                     patternWarning(arg, "non variable type-argument ")
                 }
               }
+            }
             check(pre, bound)
           case RefinedType(parents, decls) =>
             if (decls.isEmpty) for (p <- parents) check(p, bound)
@@ -1186,7 +1355,12 @@ trait Infer {
 
     def inferTypedPattern(pos: Position, pattp: Type, pt0: Type): Type = {
       val pt = widen(pt0)
-      checkCheckable(pos, pattp, " pattern")
+      
+      /** If we can absolutely rule out a match we can fail fast. */
+      if (pt.isFinalType && !(pt matchesPattern pattp))
+        error(pos, "scrutinee is incompatible with pattern type"+foundReqMsg(pattp, pt))
+      
+      checkCheckable(pos, pattp, "pattern ")
       if (!(pattp <:< pt)) {
         val tpparams = freeTypeParamsOfTerms.collect(pattp)
         if (settings.debug.value) log("free type params (1) = " + tpparams)
@@ -1198,11 +1372,10 @@ trait Infer {
           val ptparams = freeTypeParamsOfTerms.collect(pt)
           if (settings.debug.value) log("free type params (2) = " + ptparams)
           val ptvars = ptparams map freshVar
-          val pt1 = pt.instantiateTypeParams(ptparams, ptvars)
-          if (!(isPopulated(tp, pt1) && isInstantiatable(tvars ::: ptvars))) {
-            //println(tpparams)
-            //println(tvars map instBounds)
-            //println(ptvars map instBounds)
+          val pt1 = pt.instantiateTypeParams(ptparams, ptvars)  
+          // See ticket #2486 we have this example of code which would incorrectly
+          // fail without verifying that !(pattp matchesPattern pt)
+          if (!(isPopulated(tp, pt1) && isInstantiatable(tvars ::: ptvars)) && !(pattp matchesPattern pt)) {
             error(pos, "pattern type is incompatible with expected type"+foundReqMsg(pattp, pt))
             return pattp
           }
@@ -1271,23 +1444,25 @@ trait Infer {
     }
 
     def checkDead(tree: Tree): Tree = {
-      if (settings.Xwarndeadcode.value && tree.tpe != null && tree.tpe.typeSymbol == NothingClass)
+      if (settings.Ywarndeadcode.value && tree.tpe != null && tree.tpe.typeSymbol == NothingClass)
         context.warning (tree.pos, "dead code following this construct")
       tree
     }
 
     /* -- Overload Resolution ---------------------------------------------- */
 
+/*
     def checkNotShadowed(pos: Position, pre: Type, best: Symbol, eligible: List[Symbol]) =
       if (!phase.erasedTypes)
         for (alt <- eligible) {
-          if (alt.owner != best.owner && alt.owner.isSubClass(best.owner))
+          if (isProperSubClassOrObject(alt.owner, best.owner))
             error(pos,
                   "erroneous reference to overloaded definition,\n"+
                   "most specific definition is: "+best+best.locationString+" of type "+pre.memberType(best)+
                   ",\nyet alternative definition   "+alt+alt.locationString+" of type "+pre.memberType(alt)+
                   "\nis defined in a subclass")
         }
+*/
 
     /** Assign <code>tree</code> the symbol and type of the alternative which
      *  matches prototype <code>pt</code>, if it exists.
@@ -1297,6 +1472,8 @@ trait Infer {
     def inferExprAlternative(tree: Tree, pt: Type): Unit = tree.tpe match {
       case OverloadedType(pre, alts) => tryTwice {
         var alts1 = alts filter (alt => isWeaklyCompatible(pre.memberType(alt), pt))
+        //println("trying "+alts1+(alts1 map (_.tpe))+(alts1 map (_.locationString))+" for "+pt)
+        val applicable = alts1
         var secondTry = false
         if (alts1.isEmpty) { 
           alts1 = alts
@@ -1308,7 +1485,7 @@ trait Infer {
             val tp2 = pre.memberType(sym2)
             (tp2 == ErrorType ||
              !global.typer.infer.isWeaklyCompatible(tp2, pt) && global.typer.infer.isWeaklyCompatible(tp1, pt) ||
-             isStrictlyMoreSpecific(tp1, tp2)) }
+             isStrictlyMoreSpecific(tp1, tp2, sym1, sym2)) }
         val best = ((NoSymbol: Symbol) /: alts1) ((best, alt) =>
           if (improves(alt, best)) alt else best)
         val competing = alts1 dropWhile (alt => best == alt || improves(best, alt))
@@ -1333,9 +1510,9 @@ trait Infer {
             setError(tree)
           }
         } else {
-          val applicable = alts1 filter (alt => 
-            global.typer.infer.isWeaklyCompatible(pre.memberType(alt), pt))
-          checkNotShadowed(tree.pos, pre, best, applicable)
+//          val applicable = alts1 filter (alt => 
+//            global.typer.infer.isWeaklyCompatible(pre.memberType(alt), pt))
+//          checkNotShadowed(tree.pos, pre, best, applicable)
           tree.setSymbol(best).setType(pre.memberType(best))
         }
       }
@@ -1343,29 +1520,68 @@ trait Infer {
 
     /** Assign <code>tree</code> the type of an alternative which is applicable
      *  to <code>argtpes</code>, and whose result type is compatible with `pt'.
-     *  If several applicable alternatives exist, take the
-     *  most specialized one. 
+     *  If several applicable alternatives exist, drop the alternatives which use
+     *  default arguments, then select the most specialized one.
      *  If no applicable alternative exists, and pt != WildcardType, try again
      *  with pt = WildcardType.
      *  Otherwise, if there is no best alternative, error.
+     *
+     *  @param argtpes contains the argument types. If an argument is named, as
+     *    "a = 3", the corresponding type is `NamedType("a", Int)'. If the name
+     *    of some NamedType does not exist in an alternative's parameter names,
+     *    the type is replaces by `Unit', i.e. the argument is treated as an
+     *    assignment expression.
      */
-    def inferMethodAlternative(tree: Tree, undetparams: List[Symbol], argtpes: List[Type], pt: Type): Unit = tree.tpe match {
+    def inferMethodAlternative(tree: Tree, undetparams: List[Symbol],
+                               argtpes: List[Type], pt0: Type, varArgsOnly: Boolean = false): Unit = tree.tpe match {
       case OverloadedType(pre, alts) =>
+        val pt = if (pt0.typeSymbol == UnitClass) WildcardType else pt0
         tryTwice {
-          if (settings.debug.value) log("infer method alt " + tree.symbol + " with alternatives " + (alts map pre.memberType) + ", argtpes = " + argtpes + ", pt = " + pt)          
-          val applicable = alts filter (alt => isApplicable(undetparams, followApply(pre.memberType(alt)), argtpes, pt))
+          if (settings.debug.value)
+            log("infer method alt "+ tree.symbol +" with alternatives "+
+                (alts map pre.memberType) +", argtpes = "+ argtpes +", pt = "+ pt)
+
+          var allApplicable = alts filter (alt =>
+            isApplicable(undetparams, followApply(pre.memberType(alt)), argtpes, pt))
+
+          //log("applicable: "+ (allApplicable map pre.memberType))
+
+          if (varArgsOnly)
+            allApplicable = allApplicable filter (alt => isVarArgs(alt.tpe.params))
+
+          // if there are multiple, drop those that use a default
+          // (keep those that use vararg / tupling conversion)
+          val applicable =
+            if (allApplicable.length <= 1) allApplicable
+            else allApplicable filter (alt => {
+              val mtypes = followApply(alt.tpe) match {
+                case OverloadedType(_, alts) =>
+                  // for functional values, the `apply' method might be overloaded
+                  alts map (_.tpe)
+                case t => List(t)
+              }
+              mtypes.exists(t => t.params.length < argtpes.length || // tupling (*)
+                                 hasExactlyNumParams(t, argtpes.length)) // same nb or vararg
+              // (*) more arguments than parameters, but still applicable: tuplig conversion works.
+              //     todo: should not return "false" when paramTypes = (Unit) no argument is given
+              //     (tupling would work)
+            })
+
           def improves(sym1: Symbol, sym2: Symbol) =
+//            util.trace("improve "+sym1+sym1.locationString+" on "+sym2+sym2.locationString)(
             sym2 == NoSymbol || sym2.isError ||
-            isStrictlyMoreSpecific(followApply(pre.memberType(sym1)), followApply(pre.memberType(sym2)))
+            isStrictlyMoreSpecific(followApply(pre.memberType(sym1)),
+                                   followApply(pre.memberType(sym2)), sym1, sym2)
+
           val best = ((NoSymbol: Symbol) /: applicable) ((best, alt) =>
             if (improves(alt, best)) alt else best)
-          val competing = applicable dropWhile (alt => best == alt || improves(best, alt))
+          val competing = applicable.dropWhile(alt => best == alt || improves(best, alt))
           if (best == NoSymbol) {
             if (pt == WildcardType) {
               errorTree(tree, applyErrorMsg(tree, " cannot be applied to ", argtpes, pt))
             } else {
               inferMethodAlternative(tree, undetparams, argtpes, WildcardType)
-            }            
+            }
           } else if (!competing.isEmpty) {
             if (!(argtpes exists (_.isErroneous)) && !pt.isErroneous)
               context.ambiguousError(tree.pos, pre, best, competing.head,
@@ -1374,7 +1590,7 @@ trait Infer {
             setError(tree)
             ()
           } else {
-            checkNotShadowed(tree.pos, pre, best, applicable)
+//            checkNotShadowed(tree.pos, pre, best, applicable)
             tree.setSymbol(best).setType(pre.memberType(best))
           }
         }
@@ -1439,7 +1655,7 @@ trait Infer {
           if (sym.hasFlag(OVERLOADED)) {
             val tparams = new AsSeenFromMap(pre, sym.alternatives.head.owner).mapOver(
               sym.alternatives.head.typeParams)
-            val bounds = tparams map (_.tpe)  //@M TODO: might be affected by change to tpe in Symbol
+            val bounds = tparams map (_.tpeHK) // see e.g., #1236
             val tpe = 
               PolyType(tparams, 
                        OverloadedType(AntiPolyType(pre, bounds), sym.alternatives))
@@ -1454,3 +1670,4 @@ trait Infer {
     }
   }
 }
+
diff --git a/src/compiler/scala/tools/nsc/typechecker/Namers.scala b/src/compiler/scala/tools/nsc/typechecker/Namers.scala
index f70d6bd..930a675 100644
--- a/src/compiler/scala/tools/nsc/typechecker/Namers.scala
+++ b/src/compiler/scala/tools/nsc/typechecker/Namers.scala
@@ -1,13 +1,12 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: Namers.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.tools.nsc.typechecker
+package scala.tools.nsc
+package typechecker
 
 import scala.collection.mutable.HashMap
-import scala.tools.nsc.util.Position
 import symtab.Flags
 import symtab.Flags._
 
@@ -19,34 +18,49 @@ import symtab.Flags._
 trait Namers { self: Analyzer =>
   import global._
   import definitions._
-  import posAssigner.atPos
 
-  /** Convert to corresponding type parameters all skolems which satisfy one
-   *  of the following two conditions:
-   *  1. The skolem is a parameter of a class or alias type
-   *  2. The skolem is a method parameter which appears in parameter `tparams'
+  /** Convert to corresponding type parameters all skolems of method parameters
+   *  which appear in `tparams`.
    */
   class DeSkolemizeMap(tparams: List[Symbol]) extends TypeMap {
     def apply(tp: Type): Type = tp match {
       case TypeRef(pre, sym, args) 
       if (sym.isTypeSkolem && (tparams contains sym.deSkolemize)) =>
-        mapOver(rawTypeRef(NoPrefix, sym.deSkolemize, args))
+//        println("DESKOLEMIZING "+sym+" in "+sym.owner)
+        mapOver(TypeRef(NoPrefix, sym.deSkolemize, args))
+/*
       case PolyType(tparams1, restpe) =>
         new DeSkolemizeMap(tparams1 ::: tparams).mapOver(tp)
       case ClassInfoType(parents, decls, clazz) =>
-        val parents1 = List.mapConserve(parents)(this)
+        val parents1 = parents mapConserve (this)
         if (parents1 eq parents) tp else ClassInfoType(parents1, decls, clazz)
+*/
       case _ => 
         mapOver(tp)
     }
   }
+
   private class NormalNamer(context : Context) extends Namer(context)
   def newNamer(context : Context) : Namer = new NormalNamer(context)
 
+  // In the typeCompleter (templateSig) of a case class (resp it's module),
+  // synthetic `copy' (reps `apply', `unapply') methods are added. To compute
+  // their signatures, the corresponding ClassDef is needed.
+  // During naming, for each case class module symbol, the corresponding ClassDef
+  // is stored in this map.
   private[typechecker] val caseClassOfModuleClass = new HashMap[Symbol, ClassDef]
 
+  // Default getters of constructors are added to the companion object in the
+  // typeCompleter of the constructor (methodSig). To compute the signature,
+  // we need the ClassDef. To create and enter the symbols into the companion
+  // object, we need the templateNamer of that module class.
+  // This map is extended during naming of classes, the Namer is added in when
+  // it's available, i.e. in the type completer (templateSig) of the module class.
+  private[typechecker] val classAndNamerOfModule = new HashMap[Symbol, (ClassDef, Namer)]
+
   def resetNamer() {
     caseClassOfModuleClass.clear
+    classAndNamerOfModule.clear
   }
   
   abstract class Namer(val context: Context) {
@@ -55,13 +69,12 @@ trait Namers { self: Analyzer =>
 
     def setPrivateWithin[Sym <: Symbol](tree: Tree, sym: Sym, mods: Modifiers): Sym = {
       if (!mods.privateWithin.isEmpty) 
-        sym.privateWithin = typer.qualifyingClassContext(tree, mods.privateWithin).owner
+        sym.privateWithin = typer.qualifyingClass(tree, mods.privateWithin, true)
       sym
     }
 
-
     def inConstructorFlag: Long = 
-      if (context.owner.isConstructor && !context.inConstructorSuffix || context.owner.isEarly) INCONSTRUCTOR
+      if (context.owner.isConstructor && !context.inConstructorSuffix || context.owner.isEarlyInitialized) INCONSTRUCTOR
       else 0l
 
     def moduleClassFlags(moduleFlags: Long) = 
@@ -76,10 +89,10 @@ trait Namers { self: Analyzer =>
       if (sym.isModule && sym.moduleClass != NoSymbol)
         updatePosFlags(sym.moduleClass, pos, moduleClassFlags(flags))
       if (sym.owner.isPackageClass && 
-          (sym.linkedSym.rawInfo.isInstanceOf[loaders.SymbolLoader] ||
-           sym.linkedSym.rawInfo.isComplete && runId(sym.validTo) != currentRunId))
+          (sym.companionSymbol.rawInfo.isInstanceOf[loaders.SymbolLoader] ||
+           sym.companionSymbol.rawInfo.isComplete && runId(sym.validTo) != currentRunId))
         // pre-set linked symbol to NoType, in case it is not loaded together with this symbol.
-        sym.linkedSym.setInfo(NoType)
+        sym.companionSymbol.setInfo(NoType)
       sym
     }
 
@@ -92,7 +105,7 @@ trait Namers { self: Analyzer =>
     private var innerNamerCache: Namer = null
     protected def makeConstructorScope(classContext : Context) : Context = {
       val outerContext = classContext.outer.outer
-      outerContext.makeNewScope(outerContext.tree, outerContext.owner)(Constructor1ScopeKind)
+      outerContext.makeNewScope(outerContext.tree, outerContext.owner)
     }
 
     def namerOf(sym: Symbol): Namer = {
@@ -101,7 +114,7 @@ trait Namers { self: Analyzer =>
         if (innerNamerCache eq null)
           innerNamerCache =
             if (!isTemplateContext(context)) this
-            else newNamer(context.make(context.tree, context.owner, scopeFor(context.tree, InnerScopeKind)))
+            else newNamer(context.make(context.tree, context.owner, new Scope))
         innerNamerCache
       }
 
@@ -112,13 +125,14 @@ trait Namers { self: Analyzer =>
         unsafeTypeParams foreach(sym => paramContext.scope.enter(sym))
         newNamer(paramContext)
       }
-      if (sym.isTerm) {
-        if (sym.hasFlag(PARAM) && sym.owner.isPrimaryConstructor) 
-          primaryConstructorParamNamer
-        else if (sym.hasFlag(PARAMACCESSOR) && !inIDE)
-          primaryConstructorParamNamer
-        else innerNamer
-      } else innerNamer
+
+      def usePrimary = sym.isTerm && (
+        (sym hasFlag PARAMACCESSOR) ||
+        ((sym hasFlag PARAM) && sym.owner.isPrimaryConstructor)
+      )
+      
+      if (usePrimary) primaryConstructorParamNamer
+      else innerNamer
     }
 
     protected def conflict(newS : Symbol, oldS : Symbol) : Boolean = {
@@ -146,61 +160,43 @@ trait Namers { self: Analyzer =>
       else m.owner.isClass && context.scope == m.owner.info.decls
     }
 
+    /** Enter symbol into context's scope and return symbol itself */
     def enterInScope(sym: Symbol): Symbol = enterInScope(sym, context.scope)
 
+    /** Enter symbol into given scope and return symbol itself */
     def enterInScope(sym: Symbol, scope: Scope): Symbol = { 
       // allow for overloaded methods
       if (!(sym.isSourceMethod && sym.owner.isClass && !sym.owner.isPackageClass)) {
-        var prev = scope.lookupEntryWithContext(sym.name)(context.owner);
-        if ((prev ne null) && inIDE) {
-          var guess = prev
-          while ((guess ne null) && (guess.sym ne sym)) guess = scope.lookupNextEntry(guess)
-          if (guess != null) prev = guess
-          while (prev != null && (!prev.sym.hasRawInfo || !prev.sym.rawInfo.isComplete || 
-                 (prev.sym.sourceFile == null && sym.getClass == prev.sym.getClass))) {
-            if (!prev.sym.hasRawInfo ||  prev.sym.rawInfo.isComplete) {
-              Console.println("DITCHING: " + prev.sym)
-            }
-            scope unlink prev.sym
-            prev = scope.lookupNextEntry(prev)
-          } 
-          val sym0 = scope enter sym
-          if (sym0 ne sym) { 
-            Console.println("WEIRD: " + sym0 + " vs. " + sym + " " + sym0.id + " " + sym.id + " " + sym.sourceFile + " " + sym0.sourceFile)
-          }
-          if (prev != null && (sym0 ne prev.sym) && conflict(sym0,prev.sym)) {
-            doubleDefError(sym0.pos, prev.sym)
-          }
-          sym0
-        } else if ((prev ne null) && prev.owner == scope && conflict(sym, prev.sym)) {
+        var prev = scope.lookupEntry(sym.name)
+        if ((prev ne null) && prev.owner == scope && conflict(sym, prev.sym)) {
            doubleDefError(sym.pos, prev.sym)
-           sym setInfo ErrorType // don't do this in IDE for stability
+           sym setInfo ErrorType
            scope unlink prev.sym // let them co-exist...
            scope enter sym
         } else scope enter sym
       } else scope enter sym
     }
 
-    def enterPackageSymbol(pos: Position, name: Name): Symbol = {
-      val cscope = if (context.owner == EmptyPackageClass) RootClass.info.decls
-                   else context.scope
-      val p: Symbol = cscope.lookupWithContext(name)(context.owner)
-      if (p.isPackage && cscope == p.owner.info.decls) {
-        p
-      } else { 
-        val cowner = if (context.owner == EmptyPackageClass) RootClass else context.owner
-        val pkg = cowner.newPackage(pos, name)
-        // IDE: newScope should be ok because packages are never destroyed.
-        if (inIDE) assert(!pkg.moduleClass.hasRawInfo || !pkg.moduleClass.rawInfo.isComplete)
-        pkg.moduleClass.setInfo(new PackageClassInfoType(newScope, pkg.moduleClass, null))
+    def enterPackageSymbol(pos: Position, pid: RefTree, pkgOwner: Symbol): Symbol = {
+      val owner = pid match {
+        case Ident(name) => 
+          pkgOwner
+        case Select(qual: RefTree, name) => 
+          enterPackageSymbol(pos, qual, pkgOwner).moduleClass
+      }
+      var pkg = owner.info.decls.lookup(pid.name)
+      if (!pkg.isPackage || owner != pkg.owner) {
+        pkg = owner.newPackage(pos, pid.name)
+        pkg.moduleClass.setInfo(new PackageClassInfoType(new Scope, pkg.moduleClass))
         pkg.setInfo(pkg.moduleClass.tpe)
-        enterInScope(pkg, cscope)
+        enterInScope(pkg, owner.info.decls)
       }
+      pkg
     }
 
     def enterClassSymbol(tree : ClassDef): Symbol = {
-      var c: Symbol = context.scope.lookupWithContext(tree.name)(context.owner); 
-      if (!inIDE && c.isType && c.owner.isPackageClass && context.scope == c.owner.info.decls && !currentRun.compiles(c)) {
+      var c: Symbol = context.scope.lookup(tree.name)
+      if (c.isType && c.owner.isPackageClass && context.scope == c.owner.info.decls && currentRun.canRedefine(c)) {
         updatePosFlags(c, tree.pos, tree.mods.flags)
         setPrivateWithin(tree, c, tree.mods)
       } else {
@@ -217,9 +213,10 @@ trait Namers { self: Analyzer =>
         }
         clazz.sourceFile = file
         if (clazz.sourceFile ne null) {
-          assert(inIDE || !currentRun.compiles(clazz) || clazz.sourceFile == currentRun.symSource(c));
+          assert(currentRun.canRedefine(clazz) || clazz.sourceFile == currentRun.symSource(c));
           currentRun.symSource(c) = clazz.sourceFile
         }
+        registerTopLevelSym(clazz)
       }  
       assert(c.name.toString.indexOf('(') == -1)
       c
@@ -229,12 +226,15 @@ trait Namers { self: Analyzer =>
      *  or a class definition */
     def enterModuleSymbol(tree : ModuleDef): Symbol = {
       // .pos, mods.flags | MODULE | FINAL, name
-      var m: Symbol = context.scope.lookupWithContext(tree.name)(context.owner)
+      var m: Symbol = context.scope.lookup(tree.name)
       val moduleFlags = tree.mods.flags | MODULE | FINAL
       if (m.isModule && !m.isPackage && inCurrentScope(m) && 
-          ((!inIDE && !currentRun.compiles(m)) || (m hasFlag SYNTHETIC))) {
+          (currentRun.canRedefine(m) || (m hasFlag SYNTHETIC))) {
         updatePosFlags(m, tree.pos, moduleFlags)
         setPrivateWithin(tree, m, tree.mods)
+        if (m.moduleClass != NoSymbol)
+          setPrivateWithin(tree, m.moduleClass, tree.mods)
+          
         context.unit.synthetics -= m
       } else {        
         m = context.owner.newModule(tree.pos, tree.name)
@@ -245,9 +245,10 @@ trait Namers { self: Analyzer =>
         m.moduleClass.setFlag(moduleClassFlags(moduleFlags))
         setPrivateWithin(tree, m.moduleClass, tree.mods)
       }
-      if (m.owner.isPackageClass) {
+      if (m.owner.isPackageClass && !m.isPackage) {
         m.moduleClass.sourceFile = context.unit.source.file
         currentRun.symSource(m) = m.moduleClass.sourceFile
+        registerTopLevelSym(m)          
       }
       m
     }
@@ -271,8 +272,9 @@ trait Namers { self: Analyzer =>
       tskolems foreach (_.setInfo(ltp))
       tskolems
     }
+
     /** Replace type parameters with their TypeSkolems, which can later be deskolemized to the original type param 
-     * (a skolem is a representation of a bound variable when viewed outside its scope)
+     * (a skolem is a representation of a bound variable when viewed inside its scope)
      */
     def skolemize(tparams: List[TypeDef]) {
       val tskolems = newTypeSkolems(tparams map (_.symbol))
@@ -280,113 +282,158 @@ trait Namers { self: Analyzer =>
     }
 
     def applicableTypeParams(owner: Symbol): List[Symbol] =
-      if (inIDE && (owner eq NoSymbol)) List()
-      else if (owner.isTerm || owner.isPackageClass) List()
+      if (owner.isTerm || owner.isPackageClass) List()
       else applicableTypeParams(owner.owner) ::: owner.typeParams
 
-    def deSkolemize: TypeMap = new DeSkolemizeMap(applicableTypeParams(context.owner))
-    // should be special path for IDE but maybe not....
+    /** If no companion object for clazz exists yet, create one by applying `creator` to
+     *  class definition tree.
+     *  @return the companion object symbol.
+     */
+     def ensureCompanionObject(tree: ClassDef, creator: => Tree): Symbol = {
+       val m = companionModuleOf(tree.symbol, context)
+       // @luc: not sure why "currentRun.compiles(m)" is needed, things breaks
+       // otherwise. documentation welcome.
+       if (m != NoSymbol && currentRun.compiles(m)) m
+       else enterSyntheticSym(creator)
+     }
+
+    private def enterSymFinishWith(tree: Tree, tparams: List[TypeDef]) {
+      val sym = tree.symbol
+      if (settings.debug.value) log("entered " + sym + " in " + context.owner + ", scope-id = " + context.scope.## )
+      var ltype = namerOf(sym).typeCompleter(tree)
+      if (tparams nonEmpty) {
+        //@M! TypeDef's type params are handled differently
+        //@M e.g., in [A[x <: B], B], A and B are entered first as both are in scope in the definition of x 
+        //@M x is only in scope in `A[x <: B]'
+        if(!sym.isAbstractType) //@M TODO: change to isTypeMember ?
+          newNamer(context.makeNewScope(tree, sym)).enterSyms(tparams) 
+
+        ltype = new PolyTypeCompleter(tparams, ltype, tree, sym, context) //@M
+        if (sym.isTerm) skolemize(tparams)
+      }
+
+      if (sym.name == nme.copy || sym.name.startsWith(nme.copy + "$default$")) {
+        // it could be a compiler-generated copy method or one of its default getters
+        setInfo(sym)(mkTypeCompleter(tree)(copySym => {
+          def copyIsSynthetic() = sym.owner.info.member(nme.copy).hasFlag(SYNTHETIC)
+          if (sym.hasFlag(SYNTHETIC) && (!sym.hasFlag(DEFAULTPARAM) || copyIsSynthetic())) {
+            // the 'copy' method of case classes needs a special type completer to make bug0054.scala (and others)
+            // work. the copy method has to take exactly the same parameter types as the primary constructor.
+            val constrType = copySym.owner.primaryConstructor.tpe
+            val subst = new SubstSymMap(copySym.owner.typeParams, tparams map (_.symbol))
+            for ((params, cparams) <- tree.asInstanceOf[DefDef].vparamss.zip(constrType.paramss);
+                 (param, cparam) <- params.zip(cparams)) {
+              // need to clone the type cparam.tpe??? problem is: we don't have the new owner yet (the new param symbol)
+              param.tpt.setType(subst(cparam.tpe))
+            }
+          }
+          ltype.complete(sym)
+        }))
+      } else setInfo(sym)(ltype)
+    }
 
     def enterSym(tree: Tree): Context = {
+      def finishWith(tparams: List[TypeDef]) { enterSymFinishWith(tree, tparams) }
+      def finish = finishWith(Nil)
+      def sym = tree.symbol
+      if (sym != NoSymbol)
+        return this.context
       
-      def finishWith(tparams: List[TypeDef]) {
-        val sym = tree.symbol
-        if (settings.debug.value) log("entered " + sym + " in " + context.owner + ", scope-id = " + context.scope.hashCode());
-        var ltype = namerOf(sym).typeCompleter(tree)
-        if (!tparams.isEmpty) {
-          //@M! TypeDef's type params are handled differently
-          //@M e.g., in [A[x <: B], B], A and B are entered first as both are in scope in the definition of x 
-          //@M x is only in scope in `A[x <: B]'
-          if(!sym.isAbstractType) //@M TODO: change to isTypeMember ?
-            newNamer(context.makeNewScope(tree, sym)(FinishWithScopeKind)).enterSyms(tparams) 
-          ltype = new PolyTypeCompleter(tparams, ltype, tree, sym, context) //@M
-          if (sym.isTerm) skolemize(tparams)
-        } 
-        setInfo(sym)(ltype)
-      }
-      def finish = finishWith(List())
-
-      if (tree.symbol == NoSymbol) {
+      try { 
         val owner = context.owner
         tree match {
-          case PackageDef(name, stats) =>
-            tree.symbol = enterPackageSymbol(tree.pos, name)
-            val namer = newNamer(
-                context.make(tree, tree.symbol.moduleClass, tree.symbol.info.decls))
-            namer.enterSyms(stats)
+          case PackageDef(pid, stats) =>
+            tree.symbol = enterPackageSymbol(tree.pos, pid, 
+              if (context.owner == EmptyPackageClass) RootClass else context.owner)
+            val namer = newNamer(context.make(tree, sym.moduleClass, sym.info.decls))
+            namer enterSyms stats
+            
           case tree @ ClassDef(mods, name, tparams, impl) =>
             tree.symbol = enterClassSymbol(tree)
             finishWith(tparams)
-            if ((mods.flags & CASE) != 0) {
-              var m: Symbol = context.scope.lookupWithContext(tree.name.toTermName)(context.owner).filter(! _.isSourceMethod)
-              if (!(m.isModule && inCurrentScope(m) && (inIDE || currentRun.compiles(m)))) {
-                m = enterSyntheticSym(caseModuleDef(tree))
-              }
+            if (mods.isCase) {
+              if (treeInfo.firstConstructorArgs(impl.body).size > MaxFunctionArity)
+                context.error(tree.pos, "Implementation restriction: case classes cannot have more than " + MaxFunctionArity + " parameters.")
+              
+              val m = ensureCompanionObject(tree, caseModuleDef(tree))
               caseClassOfModuleClass(m.moduleClass) = tree
             }
+            val hasDefault = impl.body flatMap {
+              case DefDef(_, nme.CONSTRUCTOR, _, vparamss, _, _)  => vparamss.flatten
+              case _                                              => Nil
+            } exists (_.mods hasFlag DEFAULTPARAM)
+
+            if (hasDefault) {
+              val m = ensureCompanionObject(tree, companionModuleDef(tree))
+              classAndNamerOfModule(m) = (tree, null)
+            }
           case tree @ ModuleDef(mods, name, _) => 
             tree.symbol = enterModuleSymbol(tree)
-            tree.symbol.moduleClass.setInfo(namerOf(tree.symbol).moduleClassTypeCompleter((tree)))
+            sym.moduleClass setInfo namerOf(sym).moduleClassTypeCompleter(tree)
             finish
-            
-          case ValDef(mods, name, tp, rhs) =>
+          
+          case vd @ ValDef(mods, name, tp, rhs) =>
             if ((!context.owner.isClass ||
-                 (mods.flags & (PRIVATE | LOCAL)) == (PRIVATE | LOCAL) ||
+                 (mods.flags & (PRIVATE | LOCAL | CASEACCESSOR)) == (PRIVATE | LOCAL) ||
                  name.endsWith(nme.OUTER, nme.OUTER.length) ||
                  context.unit.isJava) && 
-                (mods.flags & LAZY) == 0) {
-              tree.symbol = enterInScope(owner.newValue(tree.pos, name)
-                .setFlag(mods.flags))
+                 !mods.isLazy) {
+              val vsym = owner.newValue(tree.pos, name).setFlag(mods.flags);
+              if(context.unit.isJava) setPrivateWithin(tree, vsym, mods) // #3663 -- for Scala fields we assume private[this]
+              tree.symbol = enterInScope(vsym)
               finish
             } else {
+              val mods1 =
+            	  if (mods.hasFlag(PRIVATE) && mods.hasFlag(LOCAL) && !mods.isLazy) {
+                    context.error(tree.pos, "private[this] not allowed for case class parameters")
+                    mods &~ LOCAL
+                  } else mods
               // add getter and possibly also setter
-              val accflags: Long = ACCESSOR |
-                (if ((mods.flags & MUTABLE) != 0) mods.flags & ~MUTABLE & ~PRESUPER 
-                 else mods.flags & ~PRESUPER | STABLE)
               if (nme.isSetterName(name))
                 context.error(tree.pos, "Names of vals or vars may not end in `_='")
-              var getter = owner.newMethod(tree.pos, name).setFlag(accflags)
-              setPrivateWithin(tree, getter, mods)
-              getter = enterInScope(getter).asInstanceOf[TermSymbol]
-              setInfo(getter)(namerOf(getter).getterTypeCompleter(tree))
-              if ((mods.flags & MUTABLE) != 0) {
-                var setter = owner.newMethod(tree.pos, nme.getterToSetter(name))
-                                .setFlag(accflags & ~STABLE & ~CASEACCESSOR)
-                setPrivateWithin(tree, setter, mods)
-                setter = enterInScope(setter).asInstanceOf[TermSymbol]
-                setInfo(setter)(namerOf(setter).setterTypeCompleter(tree))
+              // .isInstanceOf[..]: probably for (old) IDE hook. is this obsolete?
+              val getter = enterAccessorMethod(tree, name, getterFlags(mods1.flags), mods1)
+              setInfo(getter)(namerOf(getter).getterTypeCompleter(vd))
+              if (mods1.isVariable) {
+                val setter = enterAccessorMethod(tree, nme.getterToSetter(name), setterFlags(mods1.flags), mods1)
+                setInfo(setter)(namerOf(setter).setterTypeCompleter(vd))
               }
-              tree.symbol = 
-                if ((mods.flags & DEFERRED) == 0) { 
-                  var vsym = 
+              
+              tree.symbol =
+                if (mods1.isDeferred) {
+                  getter setPos tree.pos // unfocus getter position, because there won't be a separate value
+                } else {
+                  val vsym =
                     if (!context.owner.isClass) {
-                      assert((mods.flags & LAZY) != 0) // if not a field, it has to be a lazy val
-                      owner.newValue(tree.pos, name + "$lzy" ).setFlag(mods.flags | MUTABLE)
+                      assert(mods1.isLazy)   // if not a field, it has to be a lazy val
+                      owner.newValue(tree.pos, name + "$lzy" ).setFlag(mods1.flags | MUTABLE)
                     } else {
-                      owner.newValue(tree.pos, nme.getterToLocal(name))
-                        .setFlag(mods.flags & FieldFlags | PRIVATE | LOCAL | (if ((mods.flags & LAZY) != 0) MUTABLE else 0))
+                      val mFlag = if (mods1.isLazy) MUTABLE else 0
+                      val lFlag = if (mods.hasFlag(PRIVATE) && mods.hasFlag(LOCAL)) 0 else LOCAL
+                      val newflags = mods1.flags & FieldFlags | PRIVATE | lFlag | mFlag          
+                      owner.newValue(tree.pos, nme.getterToLocal(name)) setFlag newflags
                     }
-                  vsym = enterInScope(vsym).asInstanceOf[TermSymbol]
+                  enterInScope(vsym)
                   setInfo(vsym)(namerOf(vsym).typeCompleter(tree))
-                  if ((mods.flags & LAZY) != 0)
+                  if (mods1.isLazy)
                     vsym.setLazyAccessor(getter)
+
                   vsym
-                } else getter
+                }
+              addBeanGetterSetter(vd, getter)
             }
           case DefDef(mods, nme.CONSTRUCTOR, tparams, _, _, _) =>
-            var sym = owner.newConstructor(tree.pos).setFlag(mods.flags | owner.getFlag(ConstrFlags))
+            val sym = owner.newConstructor(tree.pos).setFlag(mods.flags | owner.getFlag(ConstrFlags))
             setPrivateWithin(tree, sym, mods)
             tree.symbol = enterInScope(sym)
             finishWith(tparams)
           case DefDef(mods, name, tparams, _, _, _) =>
-            var sym = (owner.newMethod(tree.pos, name)).setFlag(mods.flags)
-            setPrivateWithin(tree, sym, mods)
-            tree.symbol = enterInScope(sym) 
+            tree.symbol = enterNewMethod(tree, name, mods.flags, mods, tree.pos)
             finishWith(tparams)
           case TypeDef(mods, name, tparams, _) =>
             var flags: Long = mods.flags
-            if ((flags & PARAM) != 0) flags |= DEFERRED
-            var sym = new TypeSymbol(owner, tree.pos, name).setFlag(flags)
+            if ((flags & PARAM) != 0L) flags |= DEFERRED
+            val sym = new TypeSymbol(owner, tree.pos, name).setFlag(flags)
             setPrivateWithin(tree, sym, mods)
             tree.symbol = enterInScope(sym)
             finishWith(tparams) 
@@ -394,11 +441,17 @@ trait Namers { self: Analyzer =>
             enterSym(defn) 
           case imp @ Import(_, _) =>
             tree.symbol = NoSymbol.newImport(tree.pos)
-            setInfo(tree.symbol)(namerOf(tree.symbol).typeCompleter(tree))
+            setInfo(sym)(namerOf(sym).typeCompleter(tree))
             return (context.makeNewImport(imp))
           case _ =>
-        }
+        }        
       }
+      catch {
+        case ex: TypeError =>
+          //Console.println("caught " + ex + " in enterSym")//DEBUG
+          typer.reportTypeError(tree.pos, ex)
+          this.context
+      } 
       this.context
     }
 
@@ -408,15 +461,70 @@ trait Namers { self: Analyzer =>
       tree.symbol
     }
 
+    def enterNewMethod(tree: Tree, name: Name, flags: Long, mods: Modifiers, pos: Position): TermSymbol = {
+      val sym = context.owner.newMethod(pos, name).setFlag(flags)
+      setPrivateWithin(tree, sym, mods)
+      enterInScope(sym)
+      sym
+    }
+
+    def enterAccessorMethod(tree: Tree, name: Name, flags: Long, mods: Modifiers): TermSymbol = 
+      enterNewMethod(tree, name, flags, mods, tree.pos.focus)
+
+    private def addBeanGetterSetter(vd: ValDef, getter: Symbol) {
+      def isAnn(ann: Tree, demand: String) = ann match {
+        case Apply(Select(New(Ident(name)), _), _) =>
+          name.toString == demand
+        case Apply(Select(New(Select(pre, name)), _), _) =>
+          name.toString == demand
+        case _ => false
+      }
+      val ValDef(mods, name, tpt, _) = vd
+      val hasBP = mods.annotations.exists(isAnn(_, "BeanProperty"))
+      val hasBoolBP = mods.annotations.exists(isAnn(_, "BooleanBeanProperty"))
+      if ((hasBP || hasBoolBP) && !forMSIL) {
+        if (!name(0).isLetter)
+          context.error(vd.pos, "`BeanProperty' annotation can be applied "+
+                                "only to fields that start with a letter")
+        else if (mods.isPrivate)
+          // avoids name clashes with private fields in traits
+          context.error(vd.pos, "`BeanProperty' annotation can only be applied "+
+                                "to non-private fields")
+        else {
+          val flags = mods.flags & (DEFERRED | OVERRIDE | STATIC)
+          val beanName = name.toString.capitalize
+
+          val getterName = if (hasBoolBP) "is" + beanName
+                           else "get" + beanName
+          val getterMods = Modifiers(flags, mods.privateWithin, Nil, mods.positions)
+          val beanGetterDef = atPos(vd.pos.focus) {
+            DefDef(getterMods, getterName, Nil, List(Nil), tpt.duplicate,
+                   if (mods.isDeferred) EmptyTree
+                   else Select(This(getter.owner.name), name)) }
+          enterSyntheticSym(beanGetterDef)
+
+          if (mods hasFlag MUTABLE) {
+            // can't use "enterSyntheticSym", because the parameter type is not yet
+            // known. instead, uses the same machinery as for the non-bean setter:
+            // create and enter the symbol here, add the tree in Typer.addGettterSetter.
+            val setterName = "set" + beanName
+            val setter = enterAccessorMethod(vd, setterName, flags, mods)
+              .setPos(vd.pos.focus)
+            setInfo(setter)(namerOf(setter).setterTypeCompleter(vd))
+          }
+        }
+      }
+    }
+
 // --- Lazy Type Assignment --------------------------------------------------
 
     def typeCompleter(tree: Tree) = mkTypeCompleter(tree) { sym =>
-      if (settings.debug.value) log("defining " + sym + Flags.flagsToString(sym.flags));
+      if (settings.debug.value) log("defining " + sym + Flags.flagsToString(sym.flags)+sym.locationString)
       val tp = typeSig(tree)
       tp match {
         case TypeBounds(lo, hi) =>
           // check that lower bound is not an F-bound
-          for (val t <- lo) {
+          for (t <- lo) {
             t match {
               case TypeRef(_, sym, _) => sym.initialize
               case _ =>
@@ -437,25 +545,24 @@ trait Namers { self: Analyzer =>
       mkTypeCompleter(tree) { sym =>
         val moduleSymbol = tree.symbol
         assert(moduleSymbol.moduleClass == sym)
-        if (inIDE && moduleSymbol.rawInfo.isComplete) {
-          // reset!
-        }
         moduleSymbol.info // sets moduleClass info as a side effect.
         //assert(sym.rawInfo.isComplete)
       }
     }
 
-    def getterTypeCompleter(tree: Tree) = mkTypeCompleter(tree) { sym =>
+    def getterTypeCompleter(vd: ValDef) = mkTypeCompleter(vd) { sym =>
       if (settings.debug.value) log("defining " + sym)
-      sym.setInfo(PolyType(List(), typeSig(tree)))
+      val tp = typeSig(vd)
+      sym.setInfo(PolyType(List(), tp))
       if (settings.debug.value) log("defined " + sym)
       validate(sym)
     }
 
-    def setterTypeCompleter(tree: Tree) = mkTypeCompleter(tree) { sym =>
-      if (settings.debug.value) log("defining " + sym);
-      sym.setInfo(MethodType(List(typeSig(tree)), UnitClass.tpe))
-      if (settings.debug.value) log("defined " + sym);
+    def setterTypeCompleter(vd: ValDef) = mkTypeCompleter(vd) { sym =>
+      if (settings.debug.value) log("defining " + sym)
+      val param = sym.newSyntheticValueParam(typeSig(vd))
+      sym.setInfo(MethodType(List(param), UnitClass.tpe))
+      if (settings.debug.value) log("defined " + sym)
       validate(sym)
     }
 
@@ -491,20 +598,13 @@ trait Namers { self: Analyzer =>
       else tpe
     }
 
+    // sets each ValDef's symbol
     def enterValueParams(owner: Symbol, vparamss: List[List[ValDef]]): List[List[Symbol]] = {
       def enterValueParam(param: ValDef): Symbol = {
-        if (inIDE) param.symbol = {
-          var sym = owner.newValueParameter(param.pos, param.name).
-            setFlag(param.mods.flags & (BYNAMEPARAM | IMPLICIT))
-          setPrivateWithin(param, sym, param.mods)
-          sym = enterInScope(sym).asInstanceOf[TermSymbol]
-          if (!sym.hasRawInfo || sym.rawInfo.isComplete)
-            setInfo(sym)(typeCompleter(param))  
-          sym  
-        } else param.symbol = setInfo(
+        param.symbol = setInfo(
           enterInScope{
             val sym = owner.newValueParameter(param.pos, param.name).
-              setFlag(param.mods.flags & (BYNAMEPARAM | IMPLICIT))
+              setFlag(param.mods.flags & (BYNAMEPARAM | IMPLICIT | DEFAULTPARAM))
             setPrivateWithin(param, sym, param.mods)
           })(typeCompleter(param))
         param.symbol
@@ -530,7 +630,7 @@ trait Namers { self: Analyzer =>
           clazz.typeOfThis = selfTypeCompleter(self.tpt)
           self.symbol = clazz.thisSym.setPos(self.pos)
         } else {
-          self.tpt.tpe = NoType
+          self.tpt defineType NoType
           if (self.name != nme.WILDCARD) {
             clazz.typeOfThis = clazz.tpe
             self.symbol = clazz.thisSym
@@ -543,9 +643,46 @@ trait Namers { self: Analyzer =>
           self.symbol = context.scope enter self.symbol
         }
       }
+
+      /* experimental code for allowiong early types as type parameters
+      val earlyTypes = templ.body filter (treeInfo.isEarlyTypeDef)
+
+      val parentTyper = 
+        if (earlyTypes.isEmpty) typer
+        else {
+          val earlyContext = context.outer.makeNewScope(context.tree, context.outer.owner.newLocalDummy(templ.pos))
+          newNamer(earlyContext).enterSyms(earlyTypes)
+          newTyper(earlyContext).typedStats(earlyTypes, context.owner)
+
+          val parentContext = context.makeNewScope(context.tree, context.owner)
+          for (etdef <- earlyTypes) parentContext.scope enter etdef.symbol
+          newTyper(parentContext)
+        }
+      var parents = parentTyper.parentTypes(templ) map checkParent
+      if (!earlyTypes.isEmpty) {
+        val earlyMap = new EarlyMap(context.owner)
+        for (etdef <- earlyTypes) {
+          val esym = etdef.symbol
+          esym.owner = context.owner
+          esym.asInstanceOf[TypeSymbol].refreshType()
+          esym setInfo earlyMap(esym.info)
+        }
+      
+/*
+        println("earlies: "+(earlyTypes map (_.symbol)))
+        println("earlies: "+(earlyTypes map (_.symbol.tpe)))
+        println("earlies: "+(earlyTypes map (_.symbol.info)))
+        println("parents: "+parents)
+        println(templ)
+     
+*/
+	  
+      }
+*/
       var parents = typer.parentTypes(templ) map checkParent
       enterSelf(templ.self)
-      val decls = newClassScope(clazz)
+      val decls = new Scope
+//      for (etdef <- earlyTypes) decls enter etdef.symbol
       val templateNamer = newNamer(context.make(templ, clazz, decls))
         .enterSyms(templ.body)
 
@@ -556,7 +693,7 @@ trait Namers { self: Analyzer =>
           sym => TypeRef(clazz.owner.thisType, sym, clazz.typeParams map (_.tpe))))
       println("Parents of "+clazz+":"+parents)
 
-      // check that virtual classses are only defined as members of templates
+      // check that virtual classes are only defined as members of templates
       if (clazz.isVirtualClass && !clazz.owner.isClass)
         context.error(
           clazz.pos, 
@@ -579,133 +716,132 @@ trait Namers { self: Analyzer =>
 	  */
 
       // add apply and unapply methods to companion objects of case classes, 
-      // unless they exist already
-      Namers.this.caseClassOfModuleClass get clazz match {
-        case Some(cdef) =>
-          val go = if (inIDE) { // garbage collect in the presentaiton compiler.
-            assert(cdef.symbol != null && cdef.symbol != NoSymbol)
-            if (!cdef.symbol.isClass || !cdef.symbol.hasFlag(CASE) || cdef.symbol.rawInfo == NoType) false
-            else true
-          } else true
-          if (go)
+      // unless they exist already; here, "clazz" is the module class
+      if (clazz.isModuleClass) {
+        Namers.this.caseClassOfModuleClass get clazz match {
+          case Some(cdef) =>
             addApplyUnapply(cdef, templateNamer)
-          if (!go || !inIDE) caseClassOfModuleClass -= clazz
-          if (!go) {
-            val rem = clazz.linkedModuleOfClass
-            assert(rem != NoSymbol)
-          }
-        case None =>
+            caseClassOfModuleClass -= clazz
+          case None =>
+        }
+      }
+
+      // add the copy method to case classes; this needs to be done here, not in SyntheticMethods, because
+      // the namer phase must traverse this copy method to create default getters for its parameters.
+      // here, clazz is the ClassSymbol of the case class (not the module).
+      // @check: this seems to work only if the type completer of the class runs before the one of the
+      // module class: the one from the module class removes the entry form caseClassOfModuleClass (see above).
+      if (clazz.isClass && !clazz.hasFlag(MODULE)) {
+        Namers.this.caseClassOfModuleClass get companionModuleOf(clazz, context).moduleClass match {
+          case Some(cdef) =>
+            def hasCopy(decls: Scope) = {
+              decls.iterator exists (_.name == nme.copy)
+            }
+            if (!hasCopy(decls) &&
+                    !parents.exists(p => hasCopy(p.typeSymbol.info.decls)) &&
+                    !parents.flatMap(_.baseClasses).distinct.exists(bc => hasCopy(bc.info.decls)))
+              addCopyMethod(cdef, templateNamer)
+          case None =>
+        }
       }
-      ClassInfoType(parents, decls, clazz)    
+
+      // if default getters (for constructor defaults) need to be added to that module, here's the namer
+      // to use. clazz is the ModuleClass. sourceModule works also for classes defined in methods.
+      val module = clazz.sourceModule
+      if (classAndNamerOfModule contains module) {
+        val (cdef, _) = classAndNamerOfModule(module)
+        classAndNamerOfModule(module) = (cdef, templateNamer)
+      }
+
+      ClassInfoType(parents, decls, clazz)
     }
 
     private def classSig(tparams: List[TypeDef], impl: Template): Type = 
       polyType(typer.reenterTypeParams(tparams), templateSig(impl))
-    
-    private def methodSig(tparams: List[TypeDef], vparamss: List[List[ValDef]],
-                          tpt: Tree, rhs: Tree): Type = {
-      val meth = context.owner 
 
+    private def methodSig(mods: Modifiers, tparams: List[TypeDef],
+                          vparamss: List[List[ValDef]], tpt: Tree, rhs: Tree): Type = {
+      val meth = context.owner
+
+      // enters the skolemized version into scope, returns the deSkolemized symbols
       val tparamSyms = typer.reenterTypeParams(tparams)
-      var vparamSymss = 
-        if (inIDE && meth.isPrimaryConstructor) {
-          // @S: because they have already been entered this way....
+      // since the skolemized tparams are in scope, the TypeRefs in vparamSymss refer to skolemized tparams
+      var vparamSymss = enterValueParams(meth, vparamss)
+      // DEPMETTODO: do we need to skolemize value parameter symbols?
 
-          enterValueParams(meth.owner.owner, vparamss)
-        } else {
-          enterValueParams(meth, vparamss)
-        }
       if (tpt.isEmpty && meth.name == nme.CONSTRUCTOR) {
-        tpt.tpe = context.enclClass.owner.tpe
-        tpt setPos meth.pos
+        tpt defineType context.enclClass.owner.tpe
+        tpt setPos meth.pos.focus
       }
 
-      if (onlyPresentation && methodArgumentNames != null) 
-        methodArgumentNames(meth) = vparamss.map(_.map(_.symbol));
 
-      def convertToDeBruijn(vparams: List[Symbol], level: Int): TypeMap = new TypeMap {
-	def debruijnFor(param: Symbol) = 
-	  DeBruijnIndex(level, vparams indexOf param)
-        def apply(tp: Type) = {
-          tp match {
-            case SingleType(_, sym) =>
-              if (settings.Xexperimental.value && sym.owner == meth && (vparams contains sym)) {
-/*
-                if (sym hasFlag IMPLICIT) {
-                  context.error(sym.pos, "illegal type dependence on implicit parameter")
-                  ErrorType
-                } else 
-*/
-		debruijnFor(sym)
-              } else tp
-            case MethodType(formals, restpe) =>
-              val formals1 = List.mapConserve(formals)(this) 
-              val restpe1 = convertToDeBruijn(vparams, level + 1)(restpe)
-              if ((formals1 eq formals) && (restpe1 eq restpe)) tp
-              else copyMethodType(tp, formals1, restpe1)
-            case _ =>
-              mapOver(tp)
-          }
-        }
+      /** Called for all value parameter lists, right to left 
+       *  @param vparams the symbols of one parameter list
+       *  @param restpe  the result type (possibly a MethodType)
+       */
+      def makeMethodType(vparams: List[Symbol], restpe: Type) = {
+        // TODODEPMET: check that we actually don't need to do anything here
+        // new dependent method types: probably OK already, since 'enterValueParams' above
+        // enters them in scope, and all have a lazy type. so they may depend on other params. but: need to
+        // check that params only depend on ones in earlier sections, not the same. (done by checkDependencies,
+        // so re-use / adapt that)
+        val params = vparams map (vparam =>
+          if (meth hasFlag JAVA) vparam.setInfo(objToAny(vparam.tpe)) else vparam)
+         // TODODEPMET necessary?? new dependent types: replace symbols in restpe with the ones in vparams
+        if (meth hasFlag JAVA) JavaMethodType(params, restpe)
+        else MethodType(params, restpe)
+      }
 
-	object treeTrans extends TypeMapTransformer {
-	  override def transform(tree: Tree): Tree =
-	    tree match {
-	      case Ident(name) if (vparams contains tree.symbol) =>
-	        val dtpe = debruijnFor(tree.symbol)
-	        val dsym = 
-		    newLocalDummy(context.owner, tree.symbol.pos)
-		      .newValue(tree.symbol.pos, name)
-
-	        dsym.setFlag(PARAM)
-	        dsym.setInfo(dtpe)
-		Ident(name).setSymbol(dsym).copyAttrs(tree).setType(dtpe)
-	      case tree => super.transform(tree)
-	    }
-	}
-
-	override def mapOver(arg: Tree) = Some(treeTrans.transform(arg))
-      }
-
-      val checkDependencies: TypeTraverser = new TypeTraverser {
-        def traverse(tp: Type) = {
-          tp match {
-            case SingleType(_, sym) =>
-              if (sym.owner == meth && (vparamSymss exists (_ contains sym)))
-                context.error(
-                  sym.pos, 
-                  "illegal dependent method type"+
-                  (if (settings.Xexperimental.value) 
-                     ": parameter appears in the type of another parameter in the same section or an earlier one"
-                   else ""))
-            case _ =>
-              mapOver(tp)
+      def thisMethodType(restpe: Type) =  {
+        import scala.collection.mutable.ListBuffer
+        val okParams = ListBuffer[Symbol]()
+        // can we relax these restrictions? see test/files/pos/depmet_implicit_oopsla_session_2.scala and neg/depmet_try_implicit.scala for motivation
+        // should allow forward references since type selections on implicit args are like type parameters: 
+        // def foo[T](a: T, x: w.T2)(implicit w: ComputeT2[T])
+        // is more compact than: def foo[T, T2](a: T, x: T2)(implicit w: ComputeT2[T, T2])
+        // moreover, the latter is not an encoding of the former, which hides type inference of T2, so you can specify T while T2 is purely computed
+        val checkDependencies: TypeTraverser = new TypeTraverser {
+          def traverse(tp: Type) = {
+            tp match {
+              case SingleType(_, sym) =>
+                if (sym.owner == meth && sym.isValueParameter && !(okParams contains sym))
+                  context.error(
+                    sym.pos, 
+                    "illegal dependent method type"+
+                    (if (settings.YdepMethTpes.value) 
+                       ": parameter appears in the type of another parameter in the same section or an earlier one"
+                     else ""))
+              case _ =>
+                mapOver(tp)
+            }
+            this
           }
-          this
         }
-      }
-      
-      def makeMethodType(vparams: List[Symbol], restpe: Type) = {
-        val formals = vparams map (vparam => 
-          if (meth hasFlag JAVA) objToAny(vparam.tpe) else vparam.tpe)
-        val restpe1 = convertToDeBruijn(vparams, 1)(restpe)
-        if (!vparams.isEmpty && vparams.head.hasFlag(IMPLICIT)) 
-          ImplicitMethodType(formals, restpe1)
-        else if (meth hasFlag JAVA) JavaMethodType(formals, restpe1)
-        else MethodType(formals, restpe1)
-      }
+        for(vps <- vparamSymss) {
+          for(p <- vps) checkDependencies(p.info)
+          if(settings.YdepMethTpes.value) okParams ++= vps // can only refer to symbols in earlier parameter sections (if the extension is enabled)
+        }
+        checkDependencies(restpe) // DEPMETTODO: check not needed when they become on by default
 
-      def thisMethodType(restpe: Type) = 
         polyType(
-          tparamSyms, 
-          if (vparamSymss.isEmpty) PolyType(List(), restpe)
-          else checkDependencies((vparamSymss :\ restpe) (makeMethodType)))
+          tparamSyms, // deSkolemized symbols  -- TODO: check that their infos don't refer to method args?
+          if (vparamSymss.isEmpty) PolyType(List(), restpe) // nullary method type
+          // vparamss refer (if they do) to skolemized tparams
+          else (vparamSymss :\ restpe) (makeMethodType))
+      }
 
       var resultPt = if (tpt.isEmpty) WildcardType else typer.typedType(tpt).tpe
       val site = meth.owner.thisType
 
-      def overriddenSymbol = intersectionType(meth.owner.info.parents).member(meth.name).filter(sym =>
-          sym != NoSymbol && (site.memberType(sym) matches thisMethodType(resultPt)))
+      def overriddenSymbol = intersectionType(meth.owner.info.parents).member(meth.name).filter(sym => {
+        // luc: added .substSym from skolemized to deSkolemized
+        // site.memberType(sym): PolyType(tparams, MethodType(..., ...)) ==> all references to tparams are deSkolemized
+        // thisMethodType: tparams in PolyType are deSkolemized, the references in the MethodTypes are skolemized. ==> the two didn't match
+        // for instance, B.foo would not override A.foo, and the default on parameter b would not be inherited
+        //   class A { def foo[T](a: T)(b: T = a) = a }
+        //   class B extends A { override def foo[U](a: U)(b: U) = b }
+        sym != NoSymbol && (site.memberType(sym) matches thisMethodType(resultPt).substSym(tparams map (_.symbol), tparamSyms))
+      })
 
       // fill in result type and parameter types from overridden symbol if there is a unique one.
       if (meth.owner.isClass && (tpt.isEmpty || vparamss.exists(_.exists(_.tpt.isEmpty)))) {
@@ -714,20 +850,22 @@ trait Namers { self: Analyzer =>
           if (vparam.tpt.isEmpty) vparam.symbol setInfo WildcardType
         val overridden = overriddenSymbol
         if (overridden != NoSymbol && !(overridden hasFlag OVERLOADED)) {
+          overridden.cookJavaRawInfo() // #3404 xform java rawtypes into existentials
           resultPt = site.memberType(overridden) match {
             case PolyType(tparams, rt) => rt.substSym(tparams, tparamSyms)
             case mt => mt
           }
 
           for (vparams <- vparamss) {
-            var pfs = resultPt.paramTypes
+            var pps = resultPt.params
             for (vparam <- vparams) {
               if (vparam.tpt.isEmpty) {
-                vparam.tpt.tpe = pfs.head
-                vparam.tpt setPos vparam.pos
-                vparam.symbol setInfo pfs.head
+                val paramtpe = pps.head.tpe
+                vparam.symbol setInfo paramtpe
+                vparam.tpt defineType paramtpe
+                vparam.tpt setPos vparam.pos.focus
               }
-              pfs = pfs.tail
+              pps = pps.tail
             }
             resultPt = resultPt.resultType
           }
@@ -743,23 +881,153 @@ trait Namers { self: Analyzer =>
           }
         }
       } 
-      // Add a () parameter section if this overrides dome method with () parameters.
+      // Add a () parameter section if this overrides some method with () parameters.
       if (meth.owner.isClass && vparamss.isEmpty && overriddenSymbol.alternatives.exists(
         _.info.isInstanceOf[MethodType])) {
         vparamSymss = List(List())
       }
       for (vparams <- vparamss; vparam <- vparams if vparam.tpt.isEmpty) {
         context.error(vparam.pos, "missing parameter type")
-        vparam.tpt.tpe = ErrorType
+        vparam.tpt defineType ErrorType
       }
 
-      thisMethodType( 
-        if (tpt.isEmpty) {
-          val pt = resultPt.substSym(tparamSyms, tparams map (_.symbol)) 
-          tpt.tpe = widenIfNotFinal(meth, typer.computeType(rhs, pt), pt)
-          tpt setPos meth.pos
+      addDefaultGetters(meth, vparamss, tparams, overriddenSymbol)
+
+      thisMethodType({
+        val rt = if (tpt.isEmpty) {
+          // replace deSkolemized symbols with skolemized ones (for resultPt computed by looking at overridden symbol, right?)
+          val pt = resultPt.substSym(tparamSyms, tparams map (_.symbol))
+          // compute result type from rhs
+          tpt defineType widenIfNotFinal(meth, typer.computeType(rhs, pt), pt)
+          tpt setPos meth.pos.focus
           tpt.tpe
-        } else typer.typedType(tpt).tpe)
+        } else typer.typedType(tpt).tpe
+        // #2382: return type of default getters are always @uncheckedVariance
+        if (meth.hasFlag(DEFAULTPARAM))
+          rt.withAnnotation(AnnotationInfo(definitions.uncheckedVarianceClass.tpe, List(), List()))
+        else rt
+      })
+    }
+
+    /**
+     * For every default argument, insert a method computing that default
+     *
+     * Also adds the "override" and "defaultparam" (for inherited defaults) flags
+     * Typer is too late, if an inherited default is used before the method is
+     * typechecked, the corresponding param would not yet have the "defaultparam"
+     * flag.
+     */
+    private def addDefaultGetters(meth: Symbol, vparamss: List[List[ValDef]], tparams: List[TypeDef], overriddenSymbol: => Symbol) {
+      val isConstr = meth.isConstructor
+      val overridden = if (isConstr || !meth.owner.isClass) NoSymbol
+                       else overriddenSymbol
+      val overrides = overridden != NoSymbol && !(overridden hasFlag OVERLOADED)
+      // value parameters of the base class (whose defaults might be overridden)
+      var baseParamss = overridden.tpe.paramss
+        // match empty and missing parameter list
+        if (vparamss.isEmpty && baseParamss == List(Nil)) baseParamss = Nil
+        if (vparamss == List(Nil) && baseParamss.isEmpty) baseParamss = List(Nil)
+        assert(!overrides || vparamss.length == baseParamss.length, ""+ meth.fullName + ", "+ overridden.fullName)
+
+      // cache the namer used for entering the default getter symbols
+      var ownerNamer: Option[Namer] = None
+      var moduleNamer: Option[(ClassDef, Namer)] = None
+
+      var posCounter = 1
+
+      // for each value parameter, create the getter method if it has a default argument. previous
+      // denotes the parameter lists which are on the left side of the current one. these get added
+      // to the default getter. Example: "def foo(a: Int)(b: Int = a)" gives "foo$default$1(a: Int) = a"
+      (List[List[ValDef]]() /: (vparamss))((previous: List[List[ValDef]], vparams: List[ValDef]) => {
+        assert(!overrides || vparams.length == baseParamss.head.length, ""+ meth.fullName + ", "+ overridden.fullName)
+        var baseParams = if (overrides) baseParamss.head else Nil
+        for (vparam <- vparams) {
+          val sym = vparam.symbol
+          // true if the corresponding parameter of the base class has a default argument
+          val baseHasDefault = overrides && (baseParams.head hasFlag DEFAULTPARAM)
+          if (sym hasFlag DEFAULTPARAM) {
+            // generate a default getter for that argument
+            val oflag = if (baseHasDefault) OVERRIDE else 0
+            val name = (if (isConstr) "init" else meth.name) +"$default$"+ posCounter
+
+            // Create trees for the defaultGetter. Uses tools from Unapplies.scala
+            var deftParams = tparams map copyUntyped[TypeDef]
+            val defvParamss = previous map (_.map(p => {
+              // in the default getter, remove the default parameter
+              val p1 = atPos(p.pos.focus) { ValDef(p.mods &~ DEFAULTPARAM, p.name, p.tpt.duplicate, EmptyTree) }
+              UnTyper.traverse(p1)
+              p1
+            }))
+
+            val parentNamer = if (isConstr) {
+              val (cdef, nmr) = moduleNamer.getOrElse {
+                val module = companionModuleOf(meth.owner, context)
+                module.initialize // call type completer (typedTemplate), adds the
+                                  // module's templateNamer to classAndNamerOfModule
+                if (!classAndNamerOfModule.contains(module))
+                  return // fix #3649 (prevent crash in erroneous source code)
+                val (cdef, nmr) = classAndNamerOfModule(module)
+                moduleNamer = Some(cdef, nmr)
+                (cdef, nmr)
+              }
+              deftParams = cdef.tparams map copyUntypedInvariant
+              nmr
+            } else {
+              ownerNamer.getOrElse {
+                val ctx = context.nextEnclosing(c => c.scope.toList.contains(meth))
+                assert(ctx != NoContext)
+                val nmr = newNamer(ctx)
+                ownerNamer = Some(nmr)
+                nmr
+              }
+            }
+
+            // If the parameter type mentions any type parameter of the method, let the compiler infer the
+            // return type of the default getter => allow "def foo[T](x: T = 1)" to compile.
+            // This is better than always using Wildcard for inferring the result type, for example in
+            //    def f(i: Int, m: Int => Int = identity _) = m(i)
+            // if we use Wildcard as expected, we get "Nothing => Nothing", and the default is not usable.
+            val names = deftParams map { case TypeDef(_, name, _, _) => name }
+            object subst extends Transformer {
+              override def transform(tree: Tree): Tree = tree match {
+                case Ident(name) if (names contains name) =>
+                  TypeTree()
+                case _ =>
+                  super.transform(tree)
+              }
+              def apply(tree: Tree) = {
+                val r = transform(tree)
+                if (r.exists(_.isEmpty)) TypeTree()
+                else r
+              }
+            }
+
+            val defTpt = subst(copyUntyped(vparam.tpt match {
+              // default getter for by-name params
+              case AppliedTypeTree(_, List(arg)) if sym.hasFlag(BYNAMEPARAM) => arg
+              case t => t
+            }))
+            val defRhs = copyUntyped(vparam.rhs)
+
+            val defaultTree = atPos(vparam.pos.focus) {
+              DefDef(
+                Modifiers(meth.flags & (PRIVATE | PROTECTED | FINAL)) | SYNTHETIC | DEFAULTPARAM | oflag,
+                name, deftParams, defvParamss, defTpt, defRhs)
+            }
+            if (!isConstr)
+              meth.owner.resetFlag(INTERFACE) // there's a concrete member now
+            val default = parentNamer.enterSyntheticSym(defaultTree)
+          } else if (baseHasDefault) {
+            // the parameter does not have a default itself, but the corresponding parameter
+            // in the base class does.
+            sym.setFlag(DEFAULTPARAM)
+          }
+          posCounter += 1
+          if (overrides) baseParams = baseParams.tail
+        }
+        if (overrides) baseParamss = baseParamss.tail
+        previous ::: List(vparams)
+      })
     }
 
     //@M! an abstract type definition (abstract type member/type parameter) may take type parameters, which are in scope in its bounds
@@ -774,63 +1042,82 @@ trait Namers { self: Analyzer =>
           tp
       }
 
-      def verifyOverriding(other: Symbol): Boolean = {
-        if(other.unsafeTypeParams.length != tparamSyms.length) { 
-          context.error(tpsym.pos, 
-              "The kind of "+tpsym.keyString+" "+tpsym.varianceString + tpsym.nameString+
-              " does not conform to the expected kind of " + other.defString + other.locationString + ".")
-          false
-        } else true 
-      }
-      
-      // @M: make sure overriding in refinements respects rudimentary kinding
-      // have to do this early, as otherwise we might get crashes: (see neg/bug1275.scala)
-      //   suppose some parameterized type member is overridden by a type member w/o params, 
-      //   then appliedType will be called on a type that does not expect type args --> crash
-      if (tpsym.owner.isRefinementClass &&  // only needed in refinements
-          !tpsym.allOverriddenSymbols.forall{verifyOverriding(_)})
-	      ErrorType 
-      else polyType(tparamSyms, tp)   
+      // see neg/bug1275, #3419
+      // used to do a rudimentary kind check here to ensure overriding in refinements
+      // doesn't change a type member's arity (number of type parameters),
+      // e.g. trait T { type X[A] }; type S = T{type X}; val x: S
+      // X in x.X[A] will get rebound to the X in the refinement, which does not take any type parameters
+      // this mismatch does not crash the compiler (anymore), but leads to weird type errors,
+      // as x.X[A] will become NoType internally
+      // it's not obvious the errror refers to the X in the refinement and not the original X
+      // however, separate compilation requires the symbol info to be loaded to do this check,
+      // but loading the info will probably lead to spurious cyclic errors --> omit the check
+      polyType(tparamSyms, tp)
     }
 
-    /** Given a case class 
-     *
+    /** Given a case class
      *   case class C[Ts] (ps: Us)
-     *
      *  Add the following methods to toScope:
-     *
      *  1. if case class is not abstract, add
-     *
      *   <synthetic> <case> def apply[Ts](ps: Us): C[Ts] = new C[Ts](ps)
-     *
      *  2. add a method
-     *
      *   <synthetic> <case> def unapply[Ts](x: C[Ts]) = <ret-val>
-     * 
      *  where <ret-val> is the caseClassUnapplyReturnValue of class C (see UnApplies.scala)
+     *
+     * @param cdef is the class definition of the case class
+     * @param namer is the namer of the module class (the comp. obj)
      */
     def addApplyUnapply(cdef: ClassDef, namer: Namer) {
-      if (!(cdef.symbol hasFlag ABSTRACT))
-        namer.enterSyntheticSym(caseModuleApplyMeth(cdef))
+      if (!(cdef.symbol hasFlag ABSTRACT)) {
+        val applyMethod = caseModuleApplyMeth(cdef)
+        if (applyMethod.vparamss.size > 2)
+          context.error(cdef.symbol.pos, "case classes limited by implementation: maximum of 2 constructor parameter lists.")
+                  
+        namer.enterSyntheticSym(applyMethod)
+      }
       namer.enterSyntheticSym(caseModuleUnapplyMeth(cdef))
     }
 
+    def addCopyMethod(cdef: ClassDef, namer: Namer) {
+      caseClassCopyMeth(cdef) foreach (namer.enterSyntheticSym(_))
+    }
+
+
     def typeSig(tree: Tree): Type = {
-      val sym: Symbol = tree.symbol
-      tree match {
-        case defn: MemberDef => 
-          val ainfos = for {
-            annot <- defn.mods.annotations
-            val ainfo = typer.typedAnnotation(annot, tree.symbol)
-            if !ainfo.atp.isError && annot != null
-          } yield ainfo
-          if (!ainfos.isEmpty) {
-            val annotated = if (sym.isModule) sym.moduleClass else sym
-            annotated.attributes = ainfos
-          }
-        case _ =>
+
+      /** For definitions, transform Annotation trees to AnnotationInfos, assign
+       *  them to the sym's annotations. Type annotations: see Typer.typedAnnotated
+       *  We have to parse definition annotations here (not in the typer when traversing
+       *  the MemberDef tree): the typer looks at annotations of certain symbols; if
+       *  they were added only in typer, depending on the compilation order, they would
+       *  be visible or not
+       */
+      def annotate(annotated: Symbol) = {
+        // typeSig might be called multiple times, e.g. on a ValDef: val, getter, setter
+        // parse the annotations only once.
+        if (!annotated.isInitialized) tree match {
+          case defn: MemberDef =>
+            val ainfos = defn.mods.annotations filter { _ != null } map { ann =>
+              // need to be lazy, #1782
+              LazyAnnotationInfo(() => typer.typedAnnotation(ann))
+            }
+            if (!ainfos.isEmpty)
+              annotated.setAnnotations(ainfos)
+            if (annotated.isTypeSkolem) 
+              annotated.deSkolemize.setAnnotations(ainfos) 
+          case _ =>
+        }
       }
-      implicit val scopeKind = TypeSigScopeKind
+
+      val sym: Symbol = tree.symbol
+
+      // @Lukas: I am not sure this is the right way to do things.
+      // We used to only decorate the module class with annotations, which is
+      // clearly wrong. Now we decorate both the class and the object. 
+      // But maybe some annotations are only meant for one of these but not for the other?
+      annotate(sym)
+      if (sym.isModule) annotate(sym.moduleClass)
+
       val result = 
         try {
           tree match {
@@ -843,26 +1130,25 @@ trait Namers { self: Analyzer =>
               //clazz.typeOfThis = singleType(sym.owner.thisType, sym);
               clazz.tpe
 
-            case DefDef(_, _, tparams, vparamss, tpt, rhs) =>
-              //val result = 
-                newNamer(context.makeNewScope(tree, sym)).methodSig(tparams, vparamss, tpt, rhs)
+            case DefDef(mods, _, tparams, vparamss, tpt, rhs) =>
+              newNamer(context.makeNewScope(tree, sym)).methodSig(mods, tparams, vparamss, tpt, rhs)
 
-            case vdef @ ValDef(mods, _, tpt, rhs) =>
-              val typer1 = typer.constrTyperIf(sym.hasFlag(PARAM | PRESUPER) && sym.owner.isConstructor)
+            case vdef @ ValDef(mods, name, tpt, rhs) =>
+              val typer1 = typer.constrTyperIf(sym.hasFlag(PARAM | PRESUPER) && !mods.hasFlag(JAVA) && sym.owner.isConstructor)
               if (tpt.isEmpty) {
                 if (rhs.isEmpty) {
                   context.error(tpt.pos, "missing parameter type");
                   ErrorType
                 } else { 
-                  tpt.tpe = widenIfNotFinal(
+                  tpt defineType widenIfNotFinal(
                     sym, 
                     newTyper(typer1.context.make(vdef, sym)).computeType(rhs, WildcardType), 
                     WildcardType)
-                  tpt setPos vdef.pos
+                  tpt setPos vdef.pos.focus
                   tpt.tpe 
                 }
               } else typer1.typedType(tpt).tpe
-            
+
             case TypeDef(_, _, tparams, rhs) =>
               newNamer(context.makeNewScope(tree, sym)).typeDefSig(sym, tparams, rhs) //@M! 
               
@@ -870,17 +1156,17 @@ trait Namers { self: Analyzer =>
               val expr1 = typer.typedQualifier(expr)
               val base = expr1.tpe
               typer.checkStable(expr1)
-              if (expr1.symbol.isRootPackage) context.error(tree.pos, "_root_ cannot be imported")
+              if ((expr1.symbol ne null) && expr1.symbol.isRootPackage) context.error(tree.pos, "_root_ cannot be imported")
               def checkNotRedundant(pos: Position, from: Name, to: Name): Boolean = {
                 if (!tree.symbol.hasFlag(SYNTHETIC) &&
                     !((expr1.symbol ne null) && expr1.symbol.isInterpreterWrapper) &&
                     base.member(from) != NoSymbol) {
-                  val e = context.scope.lookupEntryWithContext(to)(context.owner)
+                  val e = context.scope.lookupEntry(to)
                   def warnRedundant(sym: Symbol) =
                     context.unit.warning(pos, "imported `"+to+
                                          "' is permanently hidden by definition of "+sym+
                                          sym.locationString)
-                  if ((e ne null) && e.owner == context.scope) {
+                  if ((e ne null) && e.owner == context.scope && e.sym.exists) {
                     warnRedundant(e.sym); return false
                   } else if (context eq context.enclClass) {
                     val defSym = context.prefix.member(to) filter (
@@ -890,21 +1176,38 @@ trait Namers { self: Analyzer =>
                 }
                 true
               }
-              def checkSelectors(selectors: List[(Name, Name)]): Unit = selectors match {
-                case (from, to) :: rest =>
+              
+              def isValidSelector(from: Name)(fun : => Unit) {
+                  if (base.nonLocalMember(from) == NoSymbol && 
+                      base.nonLocalMember(from.toTypeName) == NoSymbol) fun
+              }
+              
+              def checkSelectors(selectors: List[ImportSelector]): Unit = selectors match {
+                case ImportSelector(from, _, to, _) :: rest =>
                   if (from != nme.WILDCARD && base != ErrorType) {
-                    if (base.member(from) == NoSymbol && base.member(from.toTypeName) == NoSymbol)
-                      context.error(tree.pos, from.decode + " is not a member of " + expr);
+                    isValidSelector(from) {
+                      if (currentRun.compileSourceFor(expr, from))
+                        return typeSig(tree)
+                      // for Java code importing Scala objects
+                      if (from.endsWith(nme.DOLLARraw))
+                        isValidSelector(from.subName(0, from.length -1)) {
+                          context.error(tree.pos, from.decode + " is not a member of " + expr)
+                        }
+                      else
+                        context.error(tree.pos, from.decode + " is not a member of " + expr)
+                    }
+
                     if (checkNotRedundant(tree.pos, from, to))
                       checkNotRedundant(tree.pos, from.toTypeName, to.toTypeName)
                   }
-                  if (from != nme.WILDCARD && (rest.exists (sel => sel._1 == from)))
-                    context.error(tree.pos, from.decode + " is renamed twice");
-                  if ((to ne null) && to != nme.WILDCARD && (rest exists (sel => sel._2 == to)))
-                    context.error(tree.pos, to.decode + " appears twice as a target of a renaming");
+                  if (from != nme.WILDCARD && (rest.exists (sel => sel.name == from)))
+                    context.error(tree.pos, from.decode + " is renamed twice")
+                  if ((to ne null) && to != nme.WILDCARD && (rest exists (sel => sel.rename == to)))
+                    context.error(tree.pos, to.decode + " appears twice as a target of a renaming")
                   checkSelectors(rest)
                 case Nil => 
               }
+              
               checkSelectors(selectors)
               ImportType(expr1)
           }
@@ -914,7 +1217,26 @@ trait Namers { self: Analyzer =>
             typer.reportTypeError(tree.pos, ex)
             ErrorType
         }
-      deSkolemize(result)
+      result match {
+        case PolyType(tparams, restpe) 
+        if (!tparams.isEmpty && tparams.head.owner.isTerm ||
+            // Adriaan: The added condition below is quite a hack. It seems that HK type parameters is relying
+            // on a pass that forces all infos in the type to get everything right.
+            // The problem is that the same pass causes cyclic reference errors in
+            // test pos/cyclics.scala. It turned out that deSkolemize is run way more often than necessary,
+            // running it only when needed fixes the cyclic reference errors.
+            // But correcting deSkolemize broke HK types, because we don't do the traversal anymore.
+            // For the moment I made a special hack to do the traversal if we have HK type parameters.
+            // Maybe it's not a hack, then we need to document it better. But ideally, we should find
+            // a way to deal with HK types that's not dependent on accidental side
+            // effects like this.
+            tparams.exists(!_.typeParams.isEmpty)) =>
+          new DeSkolemizeMap(tparams) mapOver result
+        case _ => 
+//          println("not skolemizing "+result+" in "+context.owner)
+//          new DeSkolemizeMap(List()) mapOver result
+          result
+      }
     }
 
     /** Check that symbol's definition is well-formed. This means:
@@ -933,16 +1255,19 @@ trait Namers { self: Analyzer =>
             else 
               "illegal combination of modifiers: " + 
               Flags.flagsToString(flag1) + " and " + Flags.flagsToString(flag2) +
-              " for: " + sym + Flags.flagsToString(sym.rawflags));
+              " for: " + sym);
       }
+
       if (sym.hasFlag(IMPLICIT) && !sym.isTerm)
         context.error(sym.pos, "`implicit' modifier can be used only for values, variables and methods")
-      if (sym.hasFlag(IMPLICIT) && sym.owner.isPackageClass && !inIDE)
+      if (sym.hasFlag(IMPLICIT) && sym.owner.isPackageClass)
         context.error(sym.pos, "`implicit' modifier cannot be used for top-level objects")
+      if (sym.hasFlag(SEALED) && !sym.isClass)
+        context.error(sym.pos, "`sealed' modifier can be used only for classes")
       if (sym.hasFlag(ABSTRACT) && !sym.isClass)
         context.error(sym.pos, "`abstract' modifier can be used only for classes; " + 
           "\nit should be omitted for abstract members")
-      if (sym.hasFlag(OVERRIDE | ABSOVERRIDE) && sym.isClass)
+      if (sym.hasFlag(OVERRIDE | ABSOVERRIDE) && !sym.hasFlag(TRAIT) && sym.isClass)
         context.error(sym.pos, "`override' modifier not allowed for classes")
       if (sym.hasFlag(OVERRIDE | ABSOVERRIDE) && sym.isConstructor)
         context.error(sym.pos, "`override' modifier not allowed for constructors")
@@ -952,9 +1277,9 @@ trait Namers { self: Analyzer =>
         context.error(sym.pos, "`lazy' definitions may not be initialized early")
       if (sym.info.typeSymbol == FunctionClass(0) &&
           sym.isValueParameter && sym.owner.isClass && sym.owner.hasFlag(CASE))
-        context.error(sym.pos, "pass-by-name arguments not allowed for case class parameters");
+        context.error(sym.pos, "pass-by-name arguments not allowed for case class parameters")
       if (sym hasFlag DEFERRED) { // virtual classes count, too
-        if (sym.hasAttribute(definitions.NativeAttr))
+        if (sym.hasAnnotation(definitions.NativeAttr))
           sym.resetFlag(DEFERRED)
         else if (!sym.isValueParameter && !sym.isTypeParameterOrSkolem &&
           !context.tree.isInstanceOf[ExistentialTypeTree] &&
@@ -964,11 +1289,13 @@ trait Namers { self: Analyzer =>
             sym.resetFlag(DEFERRED)
         } 
       }
+
       checkNoConflict(DEFERRED, PRIVATE)
       checkNoConflict(FINAL, SEALED)
       checkNoConflict(PRIVATE, PROTECTED)
       checkNoConflict(PRIVATE, OVERRIDE)
-      //checkNoConflict(PRIVATE, FINAL) // can't do this because FINAL also means compile-time constant
+      /* checkNoConflict(PRIVATE, FINAL) // can't do this because FINAL also means compile-time constant */
+      checkNoConflict(ABSTRACT, FINAL)  // bug #1833
       checkNoConflict(DEFERRED, FINAL)
     }
   } 
@@ -989,7 +1316,7 @@ trait Namers { self: Analyzer =>
     override val tree = restp.tree
     override def complete(sym: Symbol) {
       if(ownerSym.isAbstractType) //@M an abstract type's type parameters are entered -- TODO: change to isTypeMember ?
-        newNamer(ctx.makeNewScope(owner, ownerSym)(PolyTypeCompleterScopeKind)).enterSyms(tparams) //@M
+        newNamer(ctx.makeNewScope(owner, ownerSym)).enterSyms(tparams) //@M
       restp.complete(sym)
     }
   }
@@ -1002,7 +1329,6 @@ trait Namers { self: Analyzer =>
     if (member hasFlag ACCESSOR) {
       if (member.isDeferred) {
         val getter = if (member.isSetter) member.getter(member.owner) else member
-        if (inIDE && getter == NoSymbol) return NoSymbol; 
         val result = getter.owner.newValue(getter.pos, getter.name) 
           .setInfo(getter.tpe.resultType)
           .setFlag(DEFERRED)
@@ -1011,6 +1337,25 @@ trait Namers { self: Analyzer =>
       } else member.accessed 
     } else member
 
+  /**
+   * Finds the companion module of a class symbol. Calling .companionModule
+   * does not work for classes defined inside methods.
+   */
+  def companionModuleOf(clazz: Symbol, context: Context) = {
+    var res = clazz.companionModule
+    if (res == NoSymbol)
+      res = context.lookup(clazz.name.toTermName, clazz.owner).suchThat(sym =>
+        sym.hasFlag(MODULE) && sym.isCoDefinedWith(clazz))
+    res
+  }
+
+  def companionClassOf(module: Symbol, context: Context) = {
+    var res = module.companionClass
+    if (res == NoSymbol)
+      res = context.lookup(module.name.toTypeName, module.owner).suchThat(_.isCoDefinedWith(module))
+    res
+  }
+
   /** An explanatory note to be added to error messages
    *  when there's a problem with abstract var defs */
   def varNotice(sym: Symbol): String = 
diff --git a/src/compiler/scala/tools/nsc/typechecker/NamesDefaults.scala b/src/compiler/scala/tools/nsc/typechecker/NamesDefaults.scala
new file mode 100644
index 0000000..0f3b48c
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/typechecker/NamesDefaults.scala
@@ -0,0 +1,504 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
+ * @author  Martin Odersky
+ */
+
+package scala.tools.nsc
+package typechecker
+
+import symtab.Flags._
+
+import scala.collection.mutable.ListBuffer
+
+/**
+ *  @author Lukas Rytz
+ *  @version 1.0
+ */
+trait NamesDefaults { self: Analyzer =>
+
+  import global._
+  import definitions._
+
+  case class NamedApplyInfo(qual: Option[Tree], targs: List[Tree],
+                            vargss: List[List[Tree]], blockTyper: Typer)
+  val noApplyInfo = NamedApplyInfo(None, Nil, Nil, null)
+
+  def nameOf(arg: Tree) = arg match {
+    case AssignOrNamedArg(Ident(name), rhs) => Some(name)
+    case _ => None
+  }
+  def isNamed(arg: Tree) = nameOf(arg).isDefined
+
+  
+  /** @param pos maps indicies from old to new */ 
+  def reorderArgs[T: ClassManifest](args: List[T], pos: Int => Int): List[T] = {
+    val res = new Array[T](args.length)
+    // (hopefully) faster than zipWithIndex
+    (0 /: args) { case (index, arg) => res(pos(index)) = arg; index + 1 }
+    res.toList
+  }
+  
+  /** @param pos maps indicies from new to old (!) */
+  def reorderArgsInv[T: ClassManifest](args: List[T], pos: Int => Int): List[T] = {
+    val argsArray = args.toArray
+    val res = new ListBuffer[T]
+    for (i <- 0 until argsArray.length)
+      res += argsArray(pos(i))
+    res.toList
+  }
+
+  /** returns `true' if every element is equal to its index */
+  def isIdentity(a: Array[Int]) = (0 until a.length).forall(i => a(i) == i)
+
+  /**
+   * Transform a function application into a Block, and assigns typer.context
+   * .namedApplyBlockInfo to the new block as side-effect. If tree has the form
+   *    Apply(fun, args)
+   * first the function "fun" (which might be an application itself!) is transformed into a
+   * block of the form
+   *   {
+   *     val qual$1 = qualifier_of_fun
+   *     val x$1 = arg_1_of_fun
+   *     ...
+   *     val x$n = arg_n_of_fun
+   *     qual$1.fun[targs](x$1, ...)...(..., x$n)
+   *   }
+   * then for each argument in args, a value is created and entered into the block. finally
+   * the application expression of the block is updated.
+   *   {
+   *     val qual$1 = ..
+   *     ...
+   *     val x$n = ...
+   *  >  val qual$n+1 = arg(1)
+   *  >  ...
+   *  >  val qual$n+m = arg(m)
+   *  >  qual$1.fun[targs](x$1, ...)...(..., x$n)(x$n+1, ..., x$n+m)
+   *   }
+   * 
+   * @param typer the typer calling this method; this method calls
+   *    typer.doTypedApply
+   * @param mode the mode to use for calling typer.doTypedApply
+   * @param pt the expected type for calling typer.doTypedApply
+   * 
+   * @param tree: the function application tree
+   * @argPos: a function mapping arguments from their current position to the
+   *   position specified by the method type. example:
+   *    def foo(a: Int, b: String)
+   *    foo(b = "1", a = 2)
+   *  calls
+   *    transformNamedApplication(Apply(foo, List("1", 2), { 0 => 1, 1 => 0 })
+   * 
+   *  @return the transformed application (a Block) together with the NamedApplyInfo.
+   *     if isNamedApplyBlock(tree), returns the existing context.namedApplyBlockInfo
+   */
+  def transformNamedApplication(typer: Typer, mode: Int, pt: Type)
+                               (tree: Tree, argPos: Int => Int): Tree = {
+    import typer._
+    import typer.infer._
+    val context = typer.context
+    import context.unit
+
+    /**
+     * Transform a function into a block, and passing context.namedApplyBlockInfo to
+     * the new block as side-effect.
+     *
+     * `baseFun' is typed, the resulting block must be typed as well.
+     *
+     * Fun is transformed in the following way:
+     *  - Ident(f)                                    ==>  Block(Nil, Ident(f))
+     *  - Select(qual, f) if (qual is stable)         ==>  Block(Nil, Select(qual, f))
+     *  - Select(qual, f) otherwise                   ==>  Block(ValDef(qual$1, qual), Select(qual$1, f))
+     *  - TypeApply(fun, targs)                       ==>  Block(Nil or qual$1, TypeApply(fun, targs))
+     *  - Select(New(TypeTree()), <init>)             ==>  Block(Nil, Select(New(TypeTree()), <init>))
+     *  - Select(New(Select(qual, typeName)), <init>) ==>  Block(Nil, Select(...))     NOTE: qual must be stable in a `new'
+     */
+    def baseFunBlock(baseFun: Tree): Tree = {
+      val isConstr = baseFun.symbol.isConstructor
+      val blockTyper = newTyper(context.makeNewScope(tree, context.owner))
+
+      // baseFun1: extract the function from a potential TypeApply
+      // funTargs: type arguments on baseFun, used to reconstruct TypeApply in blockWith(Out)Qualifier
+      // defaultTargs: type arguments to be used for calling defaultGetters. If the type arguments are given
+      //   in the source code, re-use them for default getter. Otherwise infer the default getter's t-args.
+      val (baseFun1, funTargs, defaultTargs) = baseFun match {
+        case TypeApply(fun, targs) =>
+          val targsInSource =
+            if (targs.forall(a => context.undetparams contains a.symbol)) Nil
+            else targs
+          (fun, targs, targsInSource)
+
+        case Select(New(tpt @ TypeTree()), _) if isConstr =>
+          val targsInSource = tpt.tpe match {
+            case TypeRef(pre, sym, args)
+            if (!args.forall(a => context.undetparams contains a.typeSymbol)) =>
+              args.map(TypeTree(_))
+            case _ =>
+              Nil
+          }
+          (baseFun, Nil, targsInSource)
+
+        case Select(TypeApply(New(TypeTree()), targs), _) if isConstr =>
+          val targsInSource =
+            if (targs.forall(a => context.undetparams contains a.symbol)) Nil
+            else targs
+          (baseFun, Nil, targsInSource)
+
+        case _ => (baseFun, Nil, Nil)
+      }
+
+      // never used for constructor calls, they always have a stable qualifier
+      def blockWithQualifier(qual: Tree, selected: Name) = {
+        val sym = blockTyper.context.owner.newValue(qual.pos, unit.fresh.newName(qual.pos, "qual$"))
+                            .setInfo(qual.tpe)
+        blockTyper.context.scope.enter(sym)
+        val vd = atPos(sym.pos)(ValDef(sym, qual).setType(NoType))
+
+        var baseFunTransformed = atPos(baseFun.pos.makeTransparent) {
+          // don't use treeCopy: it would assign opaque position.
+          val f = Select(gen.mkAttributedRef(sym), selected)
+                   .setType(baseFun1.tpe).setSymbol(baseFun1.symbol)
+          if (funTargs.isEmpty) f
+          else TypeApply(f, funTargs).setType(baseFun.tpe)
+        }
+
+        val b = Block(List(vd), baseFunTransformed)
+                  .setType(baseFunTransformed.tpe).setPos(baseFun.pos)
+
+        val defaultQual = Some(atPos(qual.pos.focus)(gen.mkAttributedRef(sym)))
+        context.namedApplyBlockInfo =
+          Some((b, NamedApplyInfo(defaultQual, defaultTargs, Nil, blockTyper)))
+        b
+      }
+
+      def blockWithoutQualifier(defaultQual: Option[Tree]) = {
+        val b = atPos(baseFun.pos)(Block(Nil, baseFun).setType(baseFun.tpe))
+        context.namedApplyBlockInfo =
+          Some((b, NamedApplyInfo(defaultQual, defaultTargs, Nil, blockTyper)))
+        b
+      }
+
+      def moduleQual(pos: Position, classType: Type) = {
+        // prefix does 'normalize', which fixes #3384
+        val pre = classType.prefix
+        if (pre == NoType) {
+          None
+        } else {
+          val module = companionModuleOf(baseFun.symbol.owner, context)
+          if (module == NoSymbol) None
+          else Some(atPos(pos.focus)(gen.mkAttributedRef(pre, module)))
+        }
+      }
+
+      baseFun1 match {
+        // constructor calls
+
+        case Select(New(tp @ TypeTree()), _) if isConstr =>
+          // 'moduleQual' fixes #3338. Same qualifier for selecting the companion object as for the class.
+          blockWithoutQualifier(moduleQual(tp.pos, tp.tpe))
+        case Select(TypeApply(New(tp @ TypeTree()), _), _) if isConstr =>
+          blockWithoutQualifier(moduleQual(tp.pos, tp.tpe))
+
+        case Select(New(tp @ Ident(_)), _) if isConstr =>
+          // 'moduleQual' fixes #3344
+          blockWithoutQualifier(moduleQual(tp.pos, tp.tpe))
+        case Select(TypeApply(New(tp @ Ident(_)), _), _) if isConstr =>
+          blockWithoutQualifier(moduleQual(tp.pos, tp.tpe))
+
+        case Select(New(tp @ Select(qual, _)), _) if isConstr =>
+          // in `new q.C()', q is always stable
+          assert(treeInfo.isPureExpr(qual), qual)
+          // 'moduleQual' fixes #2057
+          blockWithoutQualifier(moduleQual(tp.pos, tp.tpe))
+        case Select(TypeApply(New(tp @ Select(qual, _)), _), _) if isConstr =>
+          assert(treeInfo.isPureExpr(qual), qual)
+          blockWithoutQualifier(moduleQual(tp.pos, tp.tpe))
+
+        // super constructor calls
+        case Select(sp @ Super(_, _), _) if isConstr =>
+          // 'moduleQual' fixes #3207. selection of the companion module of the
+          // superclass needs to have the same prefix as the the superclass.
+          blockWithoutQualifier(moduleQual(baseFun.pos, sp.symbol.tpe.parents.head))
+
+        // self constructor calls (in secondary constructors)
+        case Select(tp, name) if isConstr =>
+          assert(treeInfo.isPureExpr(tp), tp)
+          blockWithoutQualifier(moduleQual(tp.pos, tp.tpe))
+
+        // other method calls
+
+        case Ident(_) =>
+          blockWithoutQualifier(None)
+
+        case Select(qual, name) =>
+          if (treeInfo.isPureExpr(qual))
+            blockWithoutQualifier(Some(qual.duplicate))
+          else
+            blockWithQualifier(qual, name)
+      }
+    }
+
+    /**
+     * For each argument (arg: T), create a local value
+     *  x$n: T = arg
+     *
+     * assumes "args" are typed. owner of the definitions in the block is the owner of
+     * the block (see typedBlock), but the symbols have to be entered into the block's scope.
+     *
+     * For by-name parameters, create a value
+     *  x$n: () => T = () => arg
+     */
+    def argValDefs(args: List[Tree], paramTypes: List[Type], blockTyper: Typer): List[ValDef] = {
+      val context = blockTyper.context
+      val symPs = (args, paramTypes).zipped map ((arg, tpe) => {
+        val byName = tpe.typeSymbol == ByNameParamClass
+        val (argTpe, repeated) =
+          if (tpe.typeSymbol == RepeatedParamClass) arg match {
+            case Typed(expr, tpt @ Ident(name)) if name == nme.WILDCARD_STAR.toTypeName =>
+              (expr.tpe, true)
+            case _ =>
+              (seqType(arg.tpe), true)
+          } else (arg.tpe, false)
+        val s = context.owner.newValue(arg.pos, unit.fresh.newName(arg.pos, "x$"))
+        val valType = if (byName) functionType(List(), argTpe)
+                      else if (repeated) argTpe
+                      else argTpe
+        s.setInfo(valType)
+        (context.scope.enter(s), byName, repeated)
+      })
+      (symPs, args).zipped map ((symP, arg) => {
+        val (sym, byName, repeated) = symP
+        // resetAttrs required for #2290. given a block { val x = 1; x }, when wrapping into a function
+        // () => { val x = 1; x }, the owner of symbol x must change (to the apply method of the function).
+        val body = if (byName) blockTyper.typed(Function(List(), resetLocalAttrs(arg)))
+                   else if (repeated) arg match {
+                     case Typed(expr, tpt @ Ident(name)) if name == nme.WILDCARD_STAR.toTypeName =>
+                       expr
+                     case _ =>
+                       val factory = Select(gen.mkAttributedRef(SeqModule), nme.apply)
+                       blockTyper.typed(Apply(factory, List(resetLocalAttrs(arg))))
+                   } else arg
+        atPos(body.pos)(ValDef(sym, body).setType(NoType))
+      })
+    }
+
+    // begin transform
+    if (isNamedApplyBlock(tree)) {
+      context.namedApplyBlockInfo.get._1
+    } else tree match {
+      // `fun' is typed. `namelessArgs' might be typed or not, if they are types are kept.
+      case Apply(fun, namelessArgs) =>
+        val transformedFun = transformNamedApplication(typer, mode, pt)(fun, x => x)
+        if (transformedFun.isErroneous) setError(tree)
+        else {
+          assert(isNamedApplyBlock(transformedFun), transformedFun)
+          val NamedApplyInfo(qual, targs, vargss, blockTyper) =
+            context.namedApplyBlockInfo.get._2
+          val existingBlock @ Block(stats, funOnly) = transformedFun
+
+          // type the application without names; put the arguments in definition-site order
+          val typedApp = doTypedApply(tree, funOnly, reorderArgs(namelessArgs, argPos), mode, pt)
+
+          if (typedApp.tpe.isError) setError(tree)
+          else typedApp match {
+            // Extract the typed arguments, restore the call-site evaluation order (using
+            // ValDef's in the block), change the arguments to these local values.
+            case Apply(expr, typedArgs) =>
+              // typedArgs: definition-site order
+              val formals = formalTypes(expr.tpe.paramTypes, typedArgs.length, false, false)
+              // valDefs: call-site order
+              val valDefs = argValDefs(reorderArgsInv(typedArgs, argPos),
+                                       reorderArgsInv(formals, argPos),
+                                       blockTyper)
+              // refArgs: definition-site order again
+              val refArgs = (reorderArgs(valDefs, argPos), formals).zipped map ((vDef, tpe) => {
+                val ref = gen.mkAttributedRef(vDef.symbol)
+                atPos(vDef.pos.focus) {
+                  // for by-name parameters, the local value is a nullary function returning the argument
+                  if (tpe.typeSymbol == ByNameParamClass) Apply(ref, List())
+                  else if (tpe.typeSymbol == RepeatedParamClass) Typed(ref, Ident(nme.WILDCARD_STAR.toTypeName))
+                  else ref
+                }
+              })
+              // cannot call blockTyper.typedBlock here, because the method expr might be partially applied only
+              val res = blockTyper.doTypedApply(tree, expr, refArgs, mode, pt)
+              res.setPos(res.pos.makeTransparent)
+              val block = Block(stats ::: valDefs, res).setType(res.tpe).setPos(tree.pos)
+              context.namedApplyBlockInfo =
+                Some((block, NamedApplyInfo(qual, targs, vargss ::: List(refArgs), blockTyper)))
+              block
+          }
+        }
+
+      case baseFun => // also treats "case TypeApply(fun, targs)" and "case Select(New(..), <init>)"
+        baseFunBlock(baseFun)
+
+    }
+  }
+
+  def missingParams[T](args: List[T], params: List[Symbol], argName: T => Option[Name] = nameOf _): (List[Symbol], Boolean) = {
+    val namedArgs = args.dropWhile(arg => {
+      val n = argName(arg)
+      n.isEmpty || params.forall(p => p.name != n.get)
+    })
+    val namedParams = params.drop(args.length - namedArgs.length)
+    // missing: keep those with a name which doesn't exist in namedArgs
+    val missingParams = namedParams.filter(p => namedArgs.forall(arg => {
+      val n = argName(arg)
+      n.isEmpty || n.get != p.name
+    }))
+    val allPositional = missingParams.length == namedParams.length
+    (missingParams, allPositional)
+  }
+
+  /**
+   * Extend the argument list `givenArgs' with default arguments. Defaults are added
+   * as named arguments calling the corresponding default getter.
+   *
+   * Example: given
+   *   def foo(x: Int = 2, y: String = "def")
+   *   foo(y = "lt")
+   * the argument list (y = "lt") is transformed to (y = "lt", x = foo$default$1())
+   */
+  def addDefaults(givenArgs: List[Tree], qual: Option[Tree], targs: List[Tree],
+                  previousArgss: List[List[Tree]], params: List[Symbol],
+                  pos: util.Position, context: Context): (List[Tree], List[Symbol]) = {
+    if (givenArgs.length < params.length) {
+      val (missing, positional) = missingParams(givenArgs, params)
+      if (missing forall (_.hasFlag(DEFAULTPARAM))) {
+        val defaultArgs = missing map (p => {
+          var default1 = qual match {
+            case Some(q) => gen.mkAttributedSelect(q.duplicate, defaultGetter(p, context))
+            case None =>    gen.mkAttributedRef(defaultGetter(p, context))
+          }
+          default1 = if (targs.isEmpty) default1
+                     else TypeApply(default1, targs.map(_.duplicate))
+          val default2 = (default1 /: previousArgss)((tree, args) =>
+            Apply(tree, args.map(_.duplicate)))
+          atPos(pos) {
+            if (positional) default2
+            else AssignOrNamedArg(Ident(p.name), default2)
+          }
+        })
+        (givenArgs ::: defaultArgs, Nil)
+      } else (givenArgs, missing filter (! _.hasFlag(DEFAULTPARAM)))
+    } else (givenArgs, Nil)
+  }
+
+  /**
+   * For a parameter with default argument, find the method symbol of
+   * the default getter.
+   */
+  def defaultGetter(param: Symbol, context: Context): Symbol = {
+    val i = param.owner.paramss.flatten.findIndexOf(p => p.name == param.name) + 1
+    if (i > 0) {
+      if (param.owner.isConstructor) {
+        val defGetterName = "init$default$"+ i
+        val mod = companionModuleOf(param.owner.owner, context)
+        mod.info.member(defGetterName)
+      } else {
+        val defGetterName = param.owner.name +"$default$"+ i
+        // isClass also works for methods in objects, owner is the ModuleClassSymbol
+        if (param.owner.owner.isClass) {
+          // .toInterface: otherwise we get the method symbol of the impl class
+          param.owner.owner.toInterface.info.member(defGetterName)
+        } else {
+          // the owner of the method is another method. find the default
+          // getter in the context.
+          context.lookup(defGetterName, param.owner.owner)
+        }
+      }
+    } else NoSymbol
+  }
+
+  /**
+   * Removes name assignments from args. Additionally, returns an array mapping
+   * argument indicies from call-site-order to definition-site-order.
+   *
+   * Verifies that names are not specified twice, positional args don't appear
+   * after named ones.
+   */
+  def removeNames(typer: Typer)(args: List[Tree], params: List[Symbol]): (List[Tree], Array[Int]) = {
+    import typer.infer.errorTree
+
+    // maps indicies from (order written by user) to (order of definition)
+    val argPos = (new Array[Int](args.length)) map (x => -1)
+    var positionalAllowed = true
+    val namelessArgs = for ((arg, index) <- (args.zipWithIndex)) yield arg match {
+      case a @ AssignOrNamedArg(Ident(name), rhs) =>
+        val pos = params.indexWhere(p => p.name == name && !p.hasFlag(SYNTHETIC))
+        if (pos == -1) {
+          if (positionalAllowed) {
+            argPos(index) = index
+            // prevent isNamed from being true when calling doTypedApply recursively,
+            // treat the arg as an assignment of type Unit
+            Assign(a.lhs, rhs).setPos(arg.pos)
+          } else {
+            errorTree(arg, "unknown parameter name: "+ name)
+          }
+        } else if (argPos contains pos) {
+          errorTree(arg, "parameter specified twice: "+ name)
+        } else {
+          // for named arguments, check whether the assignment expression would
+          // typecheck. if it does, report an ambiguous error.
+          val param = params(pos)
+          val paramtpe = params(pos).tpe.cloneInfo(param)
+          // replace type parameters by wildcard. in the below example we need to
+          // typecheck (x = 1) with wildcard (not T) so that it succeeds.
+          //   def f[T](x: T) = x
+          //   var x = 0
+          //   f(x = 1)   <<  "x = 1" typechecks with expected type WildcardType
+          val udp = typer.context.extractUndetparams()
+          val subst = new SubstTypeMap(udp, udp map (_ => WildcardType)) {
+            override def apply(tp: Type): Type = tp match {
+              case TypeRef(_, sym, List(arg)) if (sym == ByNameParamClass) => super.apply(arg)
+              case _ => super.apply(tp)
+            }
+          }
+          val reportAmbiguousErrors = typer.context.reportAmbiguousErrors
+          typer.context.reportAmbiguousErrors = false
+
+          val typedAssign = try {
+            typer.silent(_.typed(arg, subst(paramtpe)))
+          } catch {
+            // `silent` only catches and returns TypeErrors which are not CyclicReferences
+            // fix for #3685
+            case cr @ CyclicReference(sym, info) if (sym.name == param.name) =>
+              if (sym.isVariable || sym.isGetter && sym.accessed.isVariable) {
+                // named arg not allowed
+                typer.context.error(sym.pos, "variable definition needs type because the name is used as named argument the definition.")
+                typer.infer.setError(arg)
+              } else cr                                                            // named arg OK
+          }
+          val res = typedAssign match {
+            case _: TypeError =>
+              // if the named argument is on the original parameter
+              // position, positional after named is allowed.
+              if (index != pos)
+                positionalAllowed = false
+              argPos(index) = pos
+              rhs
+            case t: Tree =>
+              if (!t.isErroneous) {
+              // this throws an exception that's caught in `tryTypedApply` (as it uses `silent`)
+              // unfortunately, tryTypedApply recovers from the exception if you use errorTree(arg, ...) and conforms is allowed as a view (see tryImplicit in Implicits)
+              // because it tries to produce a new qualifier (if the old one was P, the new one will be conforms.apply(P)), and if that works, it pretends nothing happened
+              // so, to make sure tryTypedApply fails, would like to pass EmptyTree instead of arg, but can't do that because eventually setType(ErrorType) is called, and EmptyTree only accepts NoType as its tpe
+              // thus, we need to disable conforms as a view...
+                errorTree(arg, "reference to "+ name +" is ambiguous; it is both, a parameter\n"+
+                             "name of the method and the name of a variable currently in scope.")
+              } else t // error was reported above
+          }
+          typer.context.reportAmbiguousErrors = reportAmbiguousErrors
+          //@M note that we don't get here when an ambiguity was detected (during the computation of res),
+          // as errorTree throws an exception
+          typer.context.undetparams = udp
+          res
+        }
+      case _ =>
+        argPos(index) = index
+        if (positionalAllowed) arg
+        else errorTree(arg, "positional after named argument.")
+    }
+    (namelessArgs, argPos)
+  }
+}
diff --git a/src/compiler/scala/tools/nsc/typechecker/RefChecks.scala b/src/compiler/scala/tools/nsc/typechecker/RefChecks.scala
index 0db21ef..aca69e4 100644
--- a/src/compiler/scala/tools/nsc/typechecker/RefChecks.scala
+++ b/src/compiler/scala/tools/nsc/typechecker/RefChecks.scala
@@ -1,15 +1,15 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: RefChecks.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.tools.nsc.typechecker
+package scala.tools.nsc
+package typechecker
 
 import symtab.Flags._
 import collection.mutable.{HashSet, HashMap}
 import transform.InfoTransform
-import scala.tools.nsc.util.{Position, NoPosition}
+import scala.collection.mutable.ListBuffer
 
 /** <p>
  *    Post-attribution checking and transformation.
@@ -42,7 +42,6 @@ abstract class RefChecks extends InfoTransform {
   import global._
   import definitions._
   import typer.{typed, typedOperator, atOwner}
-  import posAssigner.atPos    
 
   /** the following two members override abstract members in Transform */
   val phaseName: String = "refchecks"
@@ -58,14 +57,112 @@ abstract class RefChecks extends InfoTransform {
       PolyType(List(), tp)
     } else tp
 
+  val toJavaRepeatedParam = new TypeMap {
+    def apply(tp: Type) = tp match {
+      case TypeRef(pre, RepeatedParamClass, args) =>
+        typeRef(pre, JavaRepeatedParamClass, args)
+      case _ =>
+        mapOver(tp)
+    }
+  }
+
+  val toScalaRepeatedParam = new TypeMap {
+    def apply(tp: Type): Type = tp match {
+      case tp @ TypeRef(pre, JavaRepeatedParamClass, args) =>
+        typeRef(pre, RepeatedParamClass, args)
+      case _ =>
+        mapOver(tp)
+    }
+  }
+
   class RefCheckTransformer(unit: CompilationUnit) extends Transformer { 
 
     var localTyper: analyzer.Typer = typer;
     var currentApplication: Tree = EmptyTree
     var inPattern: Boolean = false
+    var checkedCombinations = Set[List[Type]]()
+
+    // only one overloaded alternative is allowed to define default arguments
+    private def checkDefaultsInOverloaded(clazz: Symbol) {
+      def check(members: List[Symbol]): Unit = members match {
+        case x :: xs =>
+          if (x.paramss.exists(_.exists(p => p.hasFlag(DEFAULTPARAM))) && !nme.isProtectedAccessor(x.name)) {
+            val others = xs.filter(alt => {
+              alt.name == x.name &&
+              alt.paramss.exists(_.exists(_.hasFlag(DEFAULTPARAM))) &&
+              (!alt.isConstructor || alt.owner == x.owner) // constructors of different classes are allowed to have defaults
+            })
+            if (!others.isEmpty) {
+              val all = x :: others
+              val rest = if (all.exists(_.owner != clazz)) ".\nThe members with defaults are defined in "+
+                         all.map(_.owner).mkString("", " and ", ".") else "."
+              unit.error(clazz.pos, "in "+ clazz +", multiple overloaded alternatives of "+ x +
+                         " define default arguments"+ rest)
+              }
+          }
+          check(xs)
+        case _ => ()
+      }
+      check(clazz.info.members)
+    }
 
 // Override checking ------------------------------------------------------------
 
+    def hasRepeatedParam(tp: Type): Boolean = tp match {
+      case MethodType(formals, restpe) =>
+        formals.nonEmpty && formals.last.tpe.typeSymbol == RepeatedParamClass ||
+        hasRepeatedParam(restpe)
+      case PolyType(_, restpe) =>
+        hasRepeatedParam(restpe)
+      case _ =>
+        false
+    }
+
+    /** Add bridges for vararg methods that extend Java vararg methods
+     */
+    def addVarargBridges(clazz: Symbol): List[Tree] = {
+      val self = clazz.thisType
+
+      val bridges = new ListBuffer[Tree]
+
+      def varargBridge(member: Symbol, bridgetpe: Type): Tree = {
+        val bridge = member.cloneSymbolImpl(clazz)
+          .setPos(clazz.pos).setFlag(member.flags | VBRIDGE)
+        bridge.setInfo(bridgetpe.cloneInfo(bridge))
+        clazz.info.decls enter bridge
+        val List(params) = bridge.paramss
+        val TypeRef(_, JavaRepeatedParamClass, List(elemtp)) = params.last.tpe
+        val (initargs, List(lastarg0)) = (params map Ident) splitAt (params.length - 1)
+        val lastarg = gen.wildcardStar(gen.mkWrapArray(lastarg0, elemtp))
+        val body = Apply(Select(This(clazz), member), initargs ::: List(lastarg))
+        localTyper.typed {
+          /*util.trace("generating varargs bridge")*/(DefDef(bridge, body))
+        }
+      }
+
+      // For all concrete non-private members that have a (Scala) repeated parameter:
+      //   compute the corresponding method type `jtpe` with a Java repeated parameter
+      //   if a method with type `jtpe` exists and that method is not a varargs bridge
+      //   then create a varargs bridge of type `jtpe` that forwards to the
+      //   member method with the Scala vararg type.
+      for (member <- clazz.info.nonPrivateMembers) {
+        if (!(member hasFlag DEFERRED) && hasRepeatedParam(member.info)) {
+          val jtpe = toJavaRepeatedParam(self.memberType(member))
+          val inherited = clazz.info.nonPrivateMemberAdmitting(member.name, VBRIDGE) filter (
+            sym => (self.memberType(sym) matches jtpe) && !(sym hasFlag VBRIDGE)
+            // this is a bit tortuous: we look for non-private members or bridges
+            // if we find a bridge everything is OK. If we find another member,
+            // we need to create a bridge
+          )
+          if (inherited.exists) {
+            bridges += varargBridge(member, jtpe)
+          }
+        }
+      }
+
+      bridges.toList
+    }
+
     /** 1. Check all members of class `clazz' for overriding conditions.
      *  That is for overriding member M and overridden member O:
      *
@@ -90,7 +187,25 @@ abstract class RefChecks extends InfoTransform {
      *  4. Check that every member with an `override' modifier
      *     overrides some other member.
      */
-    private def checkAllOverrides(clazz: Symbol) {
+    private def checkAllOverrides(clazz: Symbol, typesOnly: Boolean = false) {
+
+      case class MixinOverrideError(member: Symbol, msg: String)
+
+      var mixinOverrideErrors = new ListBuffer[MixinOverrideError]()
+
+      def printMixinOverrideErrors() {
+        mixinOverrideErrors.toList match {
+          case List() => 
+          case List(MixinOverrideError(_, msg)) =>
+            unit.error(clazz.pos, msg)
+          case MixinOverrideError(member, msg) :: others =>
+            val others1 = others.map(_.member.name.decode).filter(member.name.decode != _).distinct
+            unit.error(
+              clazz.pos, 
+              msg+(if (others1.isEmpty) "" 
+                   else ";\n other members with override errors are: "+(others1 mkString ", ")))
+        }
+      }
 
       val self = clazz.thisType
  
@@ -126,46 +241,49 @@ abstract class RefChecks extends InfoTransform {
           tp1 <:< tp2
       }
 
-      /** Check that all conditions for overriding <code>other</code> by
-       *  <code>member</code> are met.
+      /** Check that all conditions for overriding `other` by `member`
+       *  of class `clazz` are met.
        */
       def checkOverride(clazz: Symbol, member: Symbol, other: Symbol) {
-        val pos = if (member.owner == clazz) member.pos else clazz.pos
+        def noErrorType = other.tpe != ErrorType && member.tpe != ErrorType
+        def isRootOrNone(sym: Symbol) = sym == RootClass || sym == NoSymbol
 
         def overrideError(msg: String) {
-          if (other.tpe != ErrorType && member.tpe != ErrorType)
-            unit.error(pos, "error overriding " + infoStringWithLocation(other) + 
-                       ";\n " + infoString(member) + " " + msg +
-                       (if ((other.owner isSubClass member.owner) && 
-                            other.isDeferred && !member.isDeferred) 
-                          ";\n (Note that "+infoStringWithLocation(other)+" is abstract,"+
-                          "\n  and is therefore overridden by concrete "+
-                          infoStringWithLocation(member)+")"
-                        else ""))
+          if (noErrorType) {
+            val fullmsg = 
+              "overriding "+infoStringWithLocation(other)+";\n "+
+              infoString(member)+" "+msg+
+              (if ((other.owner isSubClass member.owner) && other.isDeferred && !member.isDeferred) 
+                ";\n (Note that "+infoStringWithLocation(other)+" is abstract,"+
+               "\n  and is therefore overridden by concrete "+infoStringWithLocation(member)+")"
+               else "")
+            if (member.owner == clazz) unit.error(member.pos, fullmsg)
+            else mixinOverrideErrors += new MixinOverrideError(member, fullmsg)
+          }
         }
 
         def overrideTypeError() {
-          if (other.tpe != ErrorType && member.tpe != ErrorType) {
-            overrideError("has incompatible type "+analyzer.underlying(member).tpe.normalize)
+          if (noErrorType) {
+            overrideError("has incompatible type")
           }
         }
 
+        def accessFlagsToString(sym: Symbol) 
+          = flagsToString(sym getFlag (PRIVATE | PROTECTED), if (!sym.hasAccessBoundary) "" else sym.privateWithin.name.toString)
+
         def overrideAccessError() {
-          val pwString = if (other.privateWithin == NoSymbol) "" 
-                         else other.privateWithin.name.toString
-          val otherAccess = flagsToString(other getFlag (PRIVATE | PROTECTED), pwString)
-          overrideError("has weaker access privileges; it should be "+
-                        (if (otherAccess == "") "public" else "at least "+otherAccess))
+          val otherAccess = accessFlagsToString(other)
+          overrideError("has weaker access privileges; it should be "+ (if (otherAccess == "") "public" else "at least "+otherAccess))
         }
 
         //Console.println(infoString(member) + " overrides " + infoString(other) + " in " + clazz);//DEBUG
-        
+
         // return if we already checked this combination elsewhere
         if (member.owner != clazz) {
           if ((member.owner isSubClass other.owner) && (member.isDeferred || !other.isDeferred)) {
-                //Console.println(infoString(member) + " shadows1 " + infoString(other) " in " + clazz);//DEBUG
-                return; 
-              }
+            //Console.println(infoString(member) + " shadows1 " + infoString(other) " in " + clazz);//DEBUG
+            return; 
+          }
           if (clazz.info.parents exists (parent =>
             (parent.typeSymbol isSubClass other.owner) && (parent.typeSymbol isSubClass member.owner) &&
             (member.isDeferred || !other.isDeferred))) {
@@ -179,47 +297,78 @@ abstract class RefChecks extends InfoTransform {
             }
         }
 
-        if (member hasFlag PRIVATE) { // (1.1)
-          overrideError("has weaker access privileges; it should not be private")
-        }
-        val mb = member.accessBoundary(member.owner)
-        val ob = other.accessBoundary(member.owner)
-        if (mb != RootClass && mb != NoSymbol && // todo: change
-            (ob == RootClass || ob == NoSymbol || !ob.hasTransOwner(mb) ||
-             (other hasFlag PROTECTED) && !(member hasFlag PROTECTED))) {
-          overrideAccessError()
-        } else if (other hasFlag FINAL) { // (1.2)
-          overrideError("cannot override final member");
-        } else if (!other.isDeferred && !(member hasFlag (OVERRIDE | ABSOVERRIDE | SYNTHETIC))) { // (1.3), SYNTHETIC because of DEVIRTUALIZE
-          overrideError("needs `override' modifier");
-        } else if ((other hasFlag ABSOVERRIDE) && other.isIncompleteIn(clazz) && !(member hasFlag ABSOVERRIDE)) {
-          overrideError("needs `abstract override' modifiers")
-        } else if ((member hasFlag (OVERRIDE | ABSOVERRIDE)) && 
-                   (other hasFlag ACCESSOR) && other.accessed.isVariable && !other.accessed.hasFlag(LAZY)) {
-          overrideError("cannot override a mutable variable")
-        } else if (other.isStable && !member.isStable) { // (1.4)
-          overrideError("is not stable")
-        } else if (member.isValue && (member hasFlag LAZY) &&
-                   other.isValue && !other.isSourceMethod && !other.isDeferred && !(other hasFlag LAZY)) {
-          overrideError("cannot override a concrete non-lazy value")
-        } else if (other.isValue && (other hasFlag LAZY) && !other.isSourceMethod && !other.isDeferred &&
-                   member.isValue && !(member hasFlag LAZY)) {
-          overrideError("must be declared lazy to override a concrete lazy value")
-        } else {
+        /** Is the intersection between given two lists of overridden symbols empty?
+         */
+        def intersectionIsEmpty(syms1: List[Symbol], syms2: List[Symbol]) =
+          !(syms1 exists (syms2 contains))
+
+        if (typesOnly) checkOverrideTypes()
+        else {
+          // o: public | protected        | package-protected  (aka java's default access)
+          // ^-may be overridden by member with access privileges-v
+          // m: public | public/protected | public/protected/package-protected-in-same-package-as-o
+
+          if (member.isPrivate) // (1.1)
+            overrideError("has weaker access privileges; it should not be private")
+          
+          // todo: align accessibility implication checking with isAccessible in Contexts
+          val ob = other.accessBoundary(member.owner)
+          val mb = member.accessBoundary(member.owner)          
+          def isOverrideAccessOK = member.isPublic || {     // member is public, definitely same or relaxed access
+            (!other.isProtected || member.isProtected) &&   // if o is protected, so is m
+            (!isRootOrNone(ob) && ob.hasTransOwner(mb))     // m relaxes o's access boundary
+          }
+          if (!isOverrideAccessOK) {
+            overrideAccessError()
+          } else if (other.isClass || other.isModule) {
+            overrideError("cannot be used here - classes and objects cannot be overridden");
+          } else if (!other.isDeferred && (member.isClass || member.isModule)) {
+            overrideError("cannot be used here - classes and objects can only override abstract types");
+          } else if (other hasFlag FINAL) { // (1.2)
+            overrideError("cannot override final member");
+          } else if (!other.isDeferred && !(member hasFlag (OVERRIDE | ABSOVERRIDE | SYNTHETIC))) { // (1.3), SYNTHETIC because of DEVIRTUALIZE
+            overrideError("needs `override' modifier");
+          } else if ((other hasFlag ABSOVERRIDE) && other.isIncompleteIn(clazz) && !(member hasFlag ABSOVERRIDE)) {
+            overrideError("needs `abstract override' modifiers")
+          } else if ((member hasFlag (OVERRIDE | ABSOVERRIDE)) && 
+                     (other hasFlag ACCESSOR) && other.accessed.isVariable && !other.accessed.hasFlag(LAZY)) {
+            overrideError("cannot override a mutable variable")
+          } else if ((member hasFlag (OVERRIDE | ABSOVERRIDE)) && 
+                     !(member.owner.thisType.baseClasses exists (_ isSubClass other.owner)) && 
+                     !member.isDeferred && !other.isDeferred && 
+                     intersectionIsEmpty(member.allOverriddenSymbols, other.allOverriddenSymbols)) {
+            overrideError("cannot override a concrete member without a third member that's overridden by both "+
+                          "(this rule is designed to prevent ``accidental overrides'')")
+          } else if (other.isStable && !member.isStable) { // (1.4)
+            overrideError("needs to be a stable, immutable value")
+          } else if (member.isValue && (member hasFlag LAZY) &&
+                     other.isValue && !other.isSourceMethod && !other.isDeferred && !(other hasFlag LAZY)) {
+            overrideError("cannot override a concrete non-lazy value")
+          } else if (other.isValue && (other hasFlag LAZY) && !other.isSourceMethod && !other.isDeferred &&
+                     member.isValue && !(member hasFlag LAZY)) {
+            overrideError("must be declared lazy to override a concrete lazy value")
+          } else {
+            checkOverrideTypes()
+          }
+        }
+
+        def checkOverrideTypes() {
           if (other.isAliasType) {  
-            //if (!member.typeParams.isEmpty) // (1.5)  @MAT
+            //if (!member.typeParams.isEmpty) (1.5)  @MAT
             //  overrideError("may not be parameterized");
-            //if (!other.typeParams.isEmpty) // (1.5)   @MAT
+            //if (!other.typeParams.isEmpty)  (1.5)   @MAT
             //  overrideError("may not override parameterized type");
             // @M: substSym
+
             if (!(self.memberType(member).substSym(member.typeParams, other.typeParams) =:= self.memberType(other))) // (1.6)
               overrideTypeError();
           } else if (other.isAbstractType) {
             //if (!member.typeParams.isEmpty) // (1.7)  @MAT
             //  overrideError("may not be parameterized");
-            var memberTp = self.memberType(member)
+
+            val memberTp = self.memberType(member)
             val otherTp = self.memberInfo(other)
-            if (!(otherTp.bounds containsType memberTp)) { // (1.7.1) {
+            if (!(otherTp.bounds containsType memberTp)) { // (1.7.1)
               overrideTypeError(); // todo: do an explaintypes with bounds here
               explainTypes(_.bounds containsType _, otherTp, memberTp)
             }
@@ -238,63 +387,124 @@ abstract class RefChecks extends InfoTransform {
             // this overlaps somewhat with validateVariance
             if(member.isAliasType) {
               val kindErrors = typer.infer.checkKindBounds(List(member), List(memberTp.normalize), self, member.owner)
-           
+
               if(!kindErrors.isEmpty)
                 unit.error(member.pos, 
                   "The kind of the right-hand side "+memberTp.normalize+" of "+member.keyString+" "+
                   member.varianceString + member.nameString+ " does not conform to its expected kind."+
                   kindErrors.toList.mkString("\n", ", ", "")) 
+            } else if (member.isAbstractType) {
+              if (memberTp.isVolatile && !otherTp.bounds.hi.isVolatile)
+                overrideError("is a volatile type; cannot override a type with non-volatile upper bound")
             }
           } else if (other.isTerm) {
-            if (!overridesType(self.memberInfo(member), self.memberInfo(other))) { // 8
+            other.cookJavaRawInfo() // #2454
+            val memberTp = self.memberType(member)
+            val otherTp = self.memberType(other)
+            if (!overridesType(memberTp, otherTp)) { // 8
               overrideTypeError()
-              explainTypes(self.memberInfo(member), self.memberInfo(other))
+              explainTypes(memberTp, otherTp)
+            }
+
+            if (member.isStable && !otherTp.isVolatile) {
+	          if (memberTp.isVolatile)
+                overrideError("has a volatile type; cannot override a member with non-volatile type")
+              else memberTp.normalize.resultType match {
+                case rt: RefinedType if !(rt =:= otherTp) && !(checkedCombinations contains rt.parents) => 
+                  // might mask some inconsistencies -- check overrides 
+                  checkedCombinations += rt.parents
+                  val tsym = rt.typeSymbol;
+                  if (tsym.pos == NoPosition) tsym setPos member.pos
+                  checkAllOverrides(tsym, typesOnly = true)
+                case _ =>
+              }
             }
           }
         }
       }
-
+      
       val opc = new overridingPairs.Cursor(clazz)
       while (opc.hasNext) {
-        //Console.println("overrides " + opc.overriding/* + ":" + opc.overriding.tpe*/ + opc.overriding.locationString + " " + opc.overridden/* + ":" + opc.overridden.tpe*/ + opc.overridden.locationString + opc.overridden.hasFlag(DEFERRED));//DEBUG
+        //Console.println(opc.overriding/* + ":" + opc.overriding.tpe*/ + " in "+opc.overriding.fullName + " overrides " + opc.overridden/* + ":" + opc.overridden.tpe*/ + " in "+opc.overridden.fullName + "/"+ opc.overridden.hasFlag(DEFERRED));//debug
         if (!opc.overridden.isClass) checkOverride(clazz, opc.overriding, opc.overridden);
         
         opc.next
       }
-      // 2. Check that only abstract classes have deferred members
-      if (clazz.isClass && !clazz.isTrait) {
+      printMixinOverrideErrors() 
+
+      // Verifying a concrete class has nothing unimplemented.
+      if (clazz.isClass && !clazz.isTrait && !(clazz hasFlag ABSTRACT) && !typesOnly) {
+        val abstractErrors = new ListBuffer[String]
+        def abstractErrorMessage =
+          // a little formatting polish
+          if (abstractErrors.size <= 2) abstractErrors mkString " "
+          else abstractErrors.tail.mkString(abstractErrors.head + ":\n", "\n", "")
+         
         def abstractClassError(mustBeMixin: Boolean, msg: String) {
-          unit.error(clazz.pos,
-            (if (clazz.isAnonymousClass || clazz.isModuleClass) "object creation impossible"
-             else if (mustBeMixin) clazz.toString() + " needs to be a mixin"
-             else clazz.toString() + " needs to be abstract") + ", since " + msg);
-          clazz.setFlag(ABSTRACT)
-        }
-        // Find a concrete Java method that overrides `sym' under the erasure model.
-        // Bridge symbols qualify.
-        // Used as a fall back if no overriding symbol of a Java abstract method can be found
+          def prelude = (
+            if (clazz.isAnonymousClass || clazz.isModuleClass) "object creation impossible"
+            else if (mustBeMixin) clazz + " needs to be a mixin"
+            else clazz + " needs to be abstract"
+          ) + ", since"
+          
+          if (abstractErrors.isEmpty) abstractErrors ++= List(prelude, msg)
+          else abstractErrors += msg
+        }
+
         def javaErasedOverridingSym(sym: Symbol): Symbol = 
-          clazz.tpe.findMember(sym.name, PRIVATE, 0, false)(NoSymbol).filter(other =>
-            !other.isDeferred &&
-            (other hasFlag JAVA) && {
-              val tp1 = erasure.erasure(clazz.thisType.memberType(sym))
-              val tp2 = erasure.erasure(clazz.thisType.memberType(other))
+          clazz.tpe.nonPrivateMemberAdmitting(sym.name, BRIDGE).filter(other =>
+            !other.isDeferred && other.isJavaDefined && {
+              def uncurryAndErase(tp: Type) = erasure.erasure(uncurry.transformInfo(sym, tp)) // #3622: erasure operates on uncurried types -- note on passing sym in both cases: only sym.isType is relevant for uncurry.transformInfo
+              val tp1 = uncurryAndErase(clazz.thisType.memberType(sym))
+              val tp2 = uncurryAndErase(clazz.thisType.memberType(other))
               atPhase(currentRun.erasurePhase.next)(tp1 matches tp2)
             })
-        for (val member <- clazz.tpe.nonPrivateMembers)
-          if (member.isDeferred && !(clazz hasFlag ABSTRACT) &&
-              !isAbstractTypeWithoutFBound(member) &&
-              !((member hasFlag JAVA) && javaErasedOverridingSym(member) != NoSymbol)) {
-            abstractClassError(
-              false, infoString(member) + " is not defined" + analyzer.varNotice(member))
-          } else if ((member hasFlag ABSOVERRIDE) && member.isIncompleteIn(clazz)) {
-            val other = member.superSymbol(clazz);
-            abstractClassError(true,
-              infoString(member) + " is marked `abstract' and `override'" +
-              (if (other != NoSymbol) 
-                " and overrides incomplete superclass member " + infoString(other)
-               else ""))
+
+        def ignoreDeferred(member: Symbol) =
+          isAbstractTypeWithoutFBound(member) ||
+          (member.isJavaDefined && 
+           (currentRun.erasurePhase == NoPhase || // the test requires atPhase(erasurePhase.next) so shouldn't be done if the compiler has no erasure phase available
+            javaErasedOverridingSym(member) != NoSymbol))
+
+        // 2. Check that only abstract classes have deferred members
+        def checkNoAbstractMembers() = {
+          // Avoid spurious duplicates: first gather any missing members.
+          def memberList = clazz.tpe.nonPrivateMembersAdmitting(VBRIDGE)
+          val (missing, rest) = memberList partition (m => m.isDeferred && !ignoreDeferred(m))
+          // Group missing members by the underlying symbol.
+          val grouped = missing groupBy (analyzer underlying _ name)
+
+          for (member <- missing) {
+            def undefined(msg: String) = abstractClassError(false, infoString(member) + " is not defined" + msg)
+            val underlying = analyzer.underlying(member)
+          
+            // Give a specific error message for abstract vars based on why it fails:
+            // It could be unimplemented, have only one accessor, or be uninitialized.
+            if (underlying.isVariable) {
+              // If both getter and setter are missing, squelch the setter error.
+              val isMultiple = grouped(underlying.name).size > 1
+              // TODO: messages shouldn't be spread over two files, and varNotice is not a clear name
+              if (member.isSetter && isMultiple) ()
+              else undefined(
+                if (member.isSetter) "\n(Note that an abstract var requires a setter in addition to the getter)"
+                else if (member.isGetter && !isMultiple) "\n(Note that an abstract var requires a getter in addition to the setter)"
+                else analyzer.varNotice(member)
+              )
+            }
+            else undefined("")
           }
+        
+          // Check the remainder for invalid absoverride.
+          for (member <- rest ; if ((member hasFlag ABSOVERRIDE) && member.isIncompleteIn(clazz))) {
+            val other = member.superSymbol(clazz)
+            val explanation =
+              if (other != NoSymbol) " and overrides incomplete superclass member " + infoString(other)
+              else ", but no concrete implementation could be found in a base class"
+          
+            abstractClassError(true, infoString(member) + " is marked `abstract' and `override'" + explanation)
+          }
+        }
+
         // 3. Check that concrete classes do not have deferred definitions
         // that are not implemented in a subclass.
         // Note that this is not the same as (2); In a situation like
@@ -304,9 +514,9 @@ abstract class RefChecks extends InfoTransform {
         // 
         // (3) is violated but not (2).
         def checkNoAbstractDecls(bc: Symbol) {
-          for (val decl <- bc.info.decls.elements) {
-            if (decl.isDeferred && !isAbstractTypeWithoutFBound(decl)) { 
-              val impl = decl.matchingSymbol(clazz.thisType)
+          for (decl <- bc.info.decls.iterator) {
+            if (decl.isDeferred && !ignoreDeferred(decl)) { 
+              val impl = decl.matchingSymbol(clazz.thisType, admit = VBRIDGE)
               if (impl == NoSymbol || (decl.owner isSubClass impl.owner)) {
                 abstractClassError(false, "there is a deferred declaration of "+infoString(decl)+
                                    " which is not implemented in a subclass"+analyzer.varNotice(decl))
@@ -317,16 +527,63 @@ abstract class RefChecks extends InfoTransform {
           if (!parents.isEmpty && parents.head.typeSymbol.hasFlag(ABSTRACT)) 
             checkNoAbstractDecls(parents.head.typeSymbol)
         }
-        if (!(clazz hasFlag ABSTRACT)) checkNoAbstractDecls(clazz)
+        
+        checkNoAbstractMembers()
+        if (abstractErrors.isEmpty)
+          checkNoAbstractDecls(clazz)
+
+        if (abstractErrors.nonEmpty)
+          unit.error(clazz.pos, abstractErrorMessage)
+      }
+
+      /** Returns whether there is a symbol declared in class `inclazz`
+       *  (which must be different from `clazz`) whose name and type
+       *  seen as a member of `class.thisType` matches `member`'s.
+       */
+      def hasMatchingSym(inclazz: Symbol, member: Symbol): Boolean = {
+        val isVarargs = hasRepeatedParam(member.tpe)
+        lazy val varargsType = toJavaRepeatedParam(member.tpe)
+        
+        def isSignatureMatch(sym: Symbol) = !sym.isTerm || {
+          val symtpe            = clazz.thisType memberType sym
+          def matches(tp: Type) = tp matches symtpe
+          
+          matches(member.tpe) || (isVarargs && matches(varargsType))
+        }
+        /** The rules for accessing members which have an access boundary are more
+         *  restrictive in java than scala.  Since java has no concept of package nesting,
+         *  a member with "default" (package-level) access can only be accessed by members
+         *  in the exact same package.  Example:
+         *
+         *    package a.b;
+         *    public class JavaClass { void foo() { } }
+         *
+         *  The member foo() can be accessed only from members of package a.b, and not
+         *  nested packages like a.b.c.  In the analogous scala class:
+         *
+         *    package a.b
+         *    class ScalaClass { private[b] def foo() = () }
+         *
+         *  The member IS accessible to classes in package a.b.c.  The javaAccessCheck logic
+         *  is restricting the set of matching signatures according to the above semantics.
+         */
+        def javaAccessCheck(sym: Symbol) = (
+             !inclazz.isJavaDefined                             // not a java defined member
+          || !sym.hasAccessBoundary                             // no access boundary
+          || sym.isProtected                                    // marked protected in java, thus accessible to subclasses
+          || sym.privateWithin == member.enclosingPackageClass  // exact package match
+        )        
+        def classDecls   = inclazz.info.nonPrivateDecl(member.name)
+        def matchingSyms = classDecls filter (sym => isSignatureMatch(sym) && javaAccessCheck(sym))
+        
+        (inclazz != clazz) && (matchingSyms != NoSymbol)
       }
 
       // 4. Check that every defined member with an `override' modifier overrides some other member.
-      for (val member <- clazz.info.decls.toList)
+      for (member <- clazz.info.decls.toList)
         if ((member hasFlag (OVERRIDE | ABSOVERRIDE)) &&
-            (clazz.info.baseClasses.tail forall {
-               bc => member.matchingSymbol(bc, clazz.thisType) == NoSymbol
-            })) {
-          // for (val bc <- clazz.info.baseClasses.tail) Console.println("" + bc + " has " + bc.info.decl(member.name) + ":" + bc.info.decl(member.name).tpe);//DEBUG
+            !(clazz.thisType.baseClasses exists (hasMatchingSym(_, member)))) {
+          // for (bc <- clazz.info.baseClasses.tail) Console.println("" + bc + " has " + bc.info.decl(member.name) + ":" + bc.info.decl(member.name).tpe);//DEBUG
           unit.error(member.pos, member.toString() + " overrides nothing");
           member resetFlag OVERRIDE
         }
@@ -347,7 +604,7 @@ abstract class RefChecks extends InfoTransform {
 
       /** validate all base types of a class in reverse linear order. */
       def register(tp: Type) {
-//        if (clazz.fullNameString.endsWith("Collection.Projection"))
+//        if (clazz.fullName.endsWith("Collection.Projection"))
 //            println("validate base type "+tp)
         val baseClass = tp.typeSymbol
         if (baseClass.isClass) {
@@ -389,6 +646,7 @@ abstract class RefChecks extends InfoTransform {
 
     val varianceValidator = new Traverser {
 
+      /** Validate variance of info of symbol `base` */
       private def validateVariance(base: Symbol) {
 
         def varianceString(variance: Int): String =
@@ -396,25 +654,46 @@ abstract class RefChecks extends InfoTransform {
           else if (variance == -1) "contravariant"
           else "invariant";
 
+        /** The variance of a symbol occurrence of `tvar`
+         *  seen at the level of the definition of `base`.
+         *  The search proceeds from `base` to the owner of `tvar`.
+         *  Initially the state is covariant, but it might change along the search.
+         */
         def relativeVariance(tvar: Symbol): Int = {
           val clazz = tvar.owner
           var sym = base
           var state = CoVariance
           while (sym != clazz && state != AnyVariance) {
             //Console.println("flip: " + sym + " " + sym.isParameter());//DEBUG
+            // Flip occurrences of type parameters and parameters, unless
+            //  - it's a constructor, or case class factory or extractor
+            //  - it's a type parameter of tvar's owner.
             if ((sym hasFlag PARAM) && !sym.owner.isConstructor && !sym.owner.isCaseApplyOrUnapply &&
                 !(tvar.isTypeParameterOrSkolem && sym.isTypeParameterOrSkolem &&
                   tvar.owner == sym.owner)) state = -state;
             else if (!sym.owner.isClass || 
-                     ((sym.isPrivateLocal || sym.isProtectedLocal) && !(escapedPrivateLocals contains sym)))
+                     sym.isTerm && ((sym.isPrivateLocal || sym.isProtectedLocal) && !(escapedPrivateLocals contains sym))) {
+              // return AnyVariance if `sym` is local to a term
+              // or is private[this] or protected[this]
               state = AnyVariance
-            else if (sym.isAliasType) 
-              state = NoVariance
+            } else if (sym.isAliasType) {
+              // return AnyVariance if `sym` is an alias type
+              // that does not override anything. This is OK, because we always
+              // expand aliases for variance checking.
+              // However, if `sym` does override a type in a base class
+              // we have to assume NoVariance, as there might then be
+              // references to the type parameter that are not variance checked.
+              state = if (sym.allOverriddenSymbols.isEmpty) AnyVariance
+                      else NoVariance
+            }
             sym = sym.owner
           }
           state
         }
 
+        /** Validate that the type `tp` is variance-correct, assuming
+         *  the type occurs itself at variance position given by `variance`
+         */
         def validateVariance(tp: Type, variance: Int): Unit = tp match {
           case ErrorType => ;
           case WildcardType => ;
@@ -422,18 +701,25 @@ abstract class RefChecks extends InfoTransform {
           case NoPrefix => ;
           case ThisType(_) => ;
           case ConstantType(_) => ;
-          case DeBruijnIndex(_, _) => ;
+          // case DeBruijnIndex(_, _) => ;
           case SingleType(pre, sym) =>
             validateVariance(pre, variance)
           case TypeRef(pre, sym, args) =>
-            if (sym.variance != NoVariance) {
-              val v = relativeVariance(sym);
+//            println("validate "+sym+" at "+relativeVariance(sym))
+            if (sym.isAliasType/* && relativeVariance(sym) == AnyVariance*/)
+              validateVariance(tp.normalize, variance)
+            else if (sym.variance != NoVariance) {
+              val v = relativeVariance(sym)
               if (v != AnyVariance && sym.variance != v * variance) {
                 //Console.println("relativeVariance(" + base + "," + sym + ") = " + v);//DEBUG
+                def tpString(tp: Type) = tp match {
+                  case ClassInfoType(parents, _, clazz) => "supertype "+intersectionType(parents, clazz.owner)
+                  case _ => "type "+tp
+                }
                 unit.error(base.pos,
                            varianceString(sym.variance) + " " + sym + 
                            " occurs in " + varianceString(v * variance) + 
-                           " position in type " + base.info + " of " + base);
+                           " position in " + tpString(base.info) + " of " + base);
               }
             }
             validateVariance(pre, variance)
@@ -444,6 +730,8 @@ abstract class RefChecks extends InfoTransform {
             validateVariances(parents, variance)
           case RefinedType(parents, decls) =>
             validateVariances(parents, variance)
+            for (sym <- decls.toList)
+              validateVariance(sym.info, if (sym.isAliasType) NoVariance else variance)
           case TypeBounds(lo, hi) =>
             validateVariance(lo, -variance)
             validateVariance(hi, variance)
@@ -455,8 +743,9 @@ abstract class RefChecks extends InfoTransform {
           case ExistentialType(tparams, result) =>
             validateVariances(tparams map (_.info), variance)
             validateVariance(result, variance)
-          case AnnotatedType(attribs, tp, selfsym) =>
-            validateVariance(tp, variance)
+          case AnnotatedType(annots, tp, selfsym) =>
+            if (!(annots exists (_.atp.typeSymbol.isNonBottomSubClass(uncheckedVarianceClass))))
+              validateVariance(tp, variance)
         }
 
         def validateVariances(tps: List[Type], variance: Int) {
@@ -474,7 +763,8 @@ abstract class RefChecks extends InfoTransform {
 
       override def traverse(tree: Tree) {
         tree match {
-          case ClassDef(_, _, _, _) | TypeDef(_, _, _, _) =>
+          case ClassDef(_, _, _, _) | 
+               TypeDef(_, _, _, _) =>
             validateVariance(tree.symbol)
             super.traverse(tree)
           // ModuleDefs need not be considered because they have been eliminated already
@@ -493,8 +783,8 @@ abstract class RefChecks extends InfoTransform {
 // Forward reference checking ---------------------------------------------------
 
     class LevelInfo(val outer: LevelInfo) {
-      val scope: Scope = if (outer eq null) newScope else newScope(outer.scope)
-      var maxindex: Int = Math.MIN_INT
+      val scope: Scope = if (outer eq null) new Scope else new Scope(outer.scope)
+      var maxindex: Int = Int.MinValue
       var refpos: Position = _
       var refsym: Symbol = _
     }
@@ -512,13 +802,13 @@ abstract class RefChecks extends InfoTransform {
 
     private def enterSyms(stats: List[Tree]) {
       var index = -1
-      for (val stat <- stats) { 
+      for (stat <- stats) { 
         index = index + 1; 
         stat match {
           case ClassDef(_, _, _, _) | DefDef(_, _, _, _, _, _) | ModuleDef(_, _, _) | ValDef(_, _, _, _) =>
             assert(stat.symbol != NoSymbol, stat);//debug
             if (stat.symbol.isLocal) {
-              currentLevel.scope.enter(newScopeEntry(stat.symbol, currentLevel.scope));
+              currentLevel.scope.enter(stat.symbol)
               symIndex(stat.symbol) = index;
             }
           case _ =>
@@ -562,7 +852,7 @@ abstract class RefChecks extends InfoTransform {
                 sym = sym.info.bounds.hi.widen.typeSymbol
               sym
             }
-            val formal = underlyingClass(fn.tpe.paramTypes.head)
+            val formal = underlyingClass(fn.tpe.params.head.tpe)
             val actual = underlyingClass(args.head.tpe)
             val receiver = underlyingClass(qual.tpe)
             def nonSensibleWarning(what: String, alwaysEqual: Boolean) = 
@@ -572,6 +862,9 @@ abstract class RefChecks extends InfoTransform {
               nonSensibleWarning(pre+"values of types "+normalizeAll(qual.tpe.widen)+" and "+normalizeAll(args.head.tpe.widen),
                                  alwaysEqual) // @MAT normalize for consistency in error message, otherwise part is normalized due to use of `typeSymbol', but the rest isn't
             def hasObjectEquals = receiver.info.member(nme.equals_) == Object_equals
+            // see if it has any == methods beyond Any's and AnyRef's: ticket #2240
+            def hasOverloadedEqEq = receiver.info.member(nme.EQ).alternatives.length > 2
+            
             if (formal == UnitClass && actual == UnitClass)
               nonSensible("", true)
             else if ((receiver == BooleanClass || receiver == UnitClass) && 
@@ -579,7 +872,7 @@ abstract class RefChecks extends InfoTransform {
               nonSensible("", false)
             else if (isNumericValueClass(receiver) &&
                      !isNumericValueClass(actual) &&
-                     !(forMSIL || forCLDC|| (actual isSubClass BoxedNumberClass)) &&
+                     !(forMSIL || (actual isSubClass BoxedNumberClass)) &&
                      !(receiver isSubClass actual))
               nonSensible("", false)
             else if ((receiver hasFlag FINAL) && hasObjectEquals && !isValueClass(receiver) && 
@@ -587,7 +880,7 @@ abstract class RefChecks extends InfoTransform {
                      (name == nme.EQ || name == nme.LE))
               nonSensible("non-null ", false)
             else if ((isNew(qual) || isNew(args.head)) && hasObjectEquals &&
-                     (name == nme.EQ || name == nme.NE))
+                     (name == nme.EQ || name == nme.NE) && !hasOverloadedEqEq)
               nonSensibleWarning("a fresh object", false)
           case _ =>
         }
@@ -628,7 +921,7 @@ abstract class RefChecks extends InfoTransform {
         val cdef = ClassDef(mods | MODULE, name, List(), impl)
           .setPos(tree.pos) 
           .setSymbol(sym.moduleClass) 
-          .setType(NoType);
+          .setType(NoType)
         if (sym.isStatic) {
           if (!sym.allOverriddenSymbols.isEmpty) {
             val factory = sym.owner.newMethod(sym.pos, sym.name)
@@ -646,13 +939,7 @@ abstract class RefChecks extends InfoTransform {
             List(transform(cdef))
           }
         } else {
-          val vdef = 
-            localTyper.typed {
-              atPos(tree.pos) {
-                gen.mkModuleVarDef(sym)
-              }
-            }
-
+          val vdef = localTyper.typedPos(tree.pos) { gen.mkModuleVarDef(sym) }
           val ddef = 
             atPhase(phase.next) {
               localTyper.typed {
@@ -671,13 +958,13 @@ abstract class RefChecks extends InfoTransform {
         if (tree.symbol.hasFlag(LAZY)) {
           assert(tree.symbol.isTerm, tree.symbol)
           val vsym = tree.symbol
-          val hasUnitType = (tree.symbol.tpe.typeSymbol == definitions.UnitClass)
+          val hasUnitType = (tree.symbol.tpe.typeSymbol == UnitClass)
           val lazyDefSym = vsym.lazyAccessor
           assert(lazyDefSym != NoSymbol, vsym)
           val ownerTransformer = new ChangeOwnerTraverser(vsym, lazyDefSym)
           val lazyDef = atPos(tree.pos)(
-              DefDef(lazyDefSym, vparamss => ownerTransformer( 
-                if (tree.symbol.owner.isTrait // for traits, this is further tranformed in mixins
+              DefDef(lazyDefSym, ownerTransformer( 
+                if (tree.symbol.owner.isTrait // for traits, this is further transformed in mixins
                     || hasUnitType) rhs 
                 else Block(List(
                        Assign(gen.mkAttributedRef(vsym), rhs)),
@@ -701,204 +988,339 @@ abstract class RefChecks extends InfoTransform {
       case _ =>
         List(transform(tree))
     }
+    
+    /******** Begin transform inner function section ********/
 
-    override def transform(tree: Tree): Tree = try {
+    /** The private functions between here and 'transform' are conceptually
+     *  inner functions to that method, but have been moved outside of it to
+     *  ease the burden on the optimizer.
+     */
 
-      /* Check whether argument types conform to bounds of type parameters */
-      def checkBounds(pre: Type, owner: Symbol, tparams: List[Symbol], argtps: List[Type]): Unit = try {
-        typer.infer.checkBounds(tree.pos, pre, owner, tparams, argtps, "");
-      } catch {
+    /* Check whether argument types conform to bounds of type parameters */
+    private def checkBounds(pre: Type, owner: Symbol, tparams: List[Symbol], argtps: List[Type], pos: Position): Unit =
+      try typer.infer.checkBounds(pos, pre, owner, tparams, argtps, "")
+      catch {
         case ex: TypeError => 
-          unit.error(tree.pos, ex.getMessage());
+          unit.error(pos, ex.getMessage());
           if (settings.explaintypes.value) {
             val bounds = tparams map (tp => tp.info.instantiateTypeParams(tparams, argtps).bounds)
-            List.map2(argtps, bounds)((targ, bound) => explainTypes(bound.lo, targ))
-            List.map2(argtps, bounds)((targ, bound) => explainTypes(targ, bound.hi))
+            (argtps, bounds).zipped map ((targ, bound) => explainTypes(bound.lo, targ))
+            (argtps, bounds).zipped map ((targ, bound) => explainTypes(targ, bound.hi))
             ()
           }
       }
-
-      def isIrrefutable(pat: Tree, seltpe: Type): Boolean = {
-        val result = pat match {
-          case Apply(_, args) =>
-            val clazz = pat.tpe.typeSymbol;
-            clazz == seltpe.typeSymbol &&
-            clazz.isClass && (clazz hasFlag CASE) &&
-            List.forall2(
-              args,
-              clazz.primaryConstructor.tpe.asSeenFrom(seltpe, clazz).paramTypes)(isIrrefutable)
-          case Typed(pat, tpt) => 
-            seltpe <:< tpt.tpe
-          case Ident(nme.WILDCARD) =>
-            true
-          case Bind(_, pat) =>
-            isIrrefutable(pat, seltpe)
-          case _ =>
-            false
-        }
-        //Console.println("is irefutable? " + pat + ":" + pat.tpe + " against " + seltpe + ": " + result);//DEBUG
-        result
+    private def isIrrefutable(pat: Tree, seltpe: Type): Boolean = {
+      val result = pat match {
+        case Apply(_, args) =>
+          val clazz = pat.tpe.typeSymbol;
+          clazz == seltpe.typeSymbol &&
+          clazz.isClass && (clazz hasFlag CASE) &&
+          (args corresponds clazz.primaryConstructor.tpe.asSeenFrom(seltpe, clazz).paramTypes)(isIrrefutable) // @PP: corresponds
+        case Typed(pat, tpt) => 
+          seltpe <:< tpt.tpe
+        case Ident(nme.WILDCARD) =>
+          true
+        case Bind(_, pat) =>
+          isIrrefutable(pat, seltpe)
+        case _ =>
+          false
       }
-
-      /** If symbol is deprecated and is not contained in a deprecated definition,
-       *  issue a deprecated warning
-       */
-      def checkDeprecated(sym: Symbol, pos: Position) {
-        if (sym.isDeprecated && !currentOwner.ownerChain.exists(_.isDeprecated)) {
-          unit.deprecationWarning(pos, sym+sym.locationString+" is deprecated")
-        }
+      //Console.println("is irefutable? " + pat + ":" + pat.tpe + " against " + seltpe + ": " + result);//DEBUG
+      result
+    }
+    /** If symbol is deprecated and is not contained in a deprecated definition,
+     *  issue a deprecated warning
+     */
+    private def checkDeprecated(sym: Symbol, pos: Position) {
+      if (sym.isDeprecated && !currentOwner.ownerChain.exists(_.isDeprecated)) {
+        val dmsg = sym.deprecationMessage
+        val msg = sym.toString + sym.locationString +" is deprecated"+
+                  (if (dmsg.isDefined) ": "+ dmsg.get else "")
+        unit.deprecationWarning(pos, msg)
       }
+    }
+    /** Similar to deprecation: check if the symbol is marked with @migration
+     *  indicating it has changed semantics between versions.
+     */
+    private def checkMigration(sym: Symbol, pos: Position) = {
+      for (msg <- sym.migrationMessage)
+        unit.warning(pos, "%s%s has changed semantics:\n%s".format(sym, sym.locationString, msg))
+    }
+    
+    /** Check that a deprecated val or def does not override a
+      * concrete, non-deprecated method.  If it does, then
+      * deprecation is meaningless.
+      */
+    private def checkDeprecatedOvers(tree: Tree) {
+      val symbol = tree.symbol
+      if (symbol.isDeprecated) {
+        val concrOvers =
+          symbol.allOverriddenSymbols.filter(sym =>
+            !sym.isDeprecated && !sym.isDeferred)
+        if(!concrOvers.isEmpty)
+          unit.deprecationWarning(
+            tree.pos,
+            symbol.toString + " overrides concrete, non-deprecated symbol(s):" +
+            concrOvers.map(_.name.decode).mkString("    ", ", ", ""))
+      }
+    }
+    private def isRepeatedParamArg(tree: Tree) = currentApplication match {
+      case Apply(fn, args) =>
+        !args.isEmpty && (args.last eq tree) && 
+        fn.tpe.params.length == args.length && isRepeatedParamType(fn.tpe.params.last.tpe)
+      case _ =>
+        false
+    }
+    private def checkTypeRef(tp: Type, pos: Position) = tp match {
+      case TypeRef(pre, sym, args) =>
+        checkDeprecated(sym, pos)
+        if(sym.hasFlag(JAVA))
+          sym.typeParams foreach (_.cookJavaRawInfo())
+        if (!tp.isHigherKinded)
+          checkBounds(pre, sym.owner, sym.typeParams, args, pos)
+      case _ =>
+    }
 
-      /** Check that a deprecated val or def does not override a
-        * concrete, non-deprecated method.  If it does, then
-        * deprecation is meaningless.
-        */
-      def checkDeprecatedOvers() {
-        val symbol = tree.symbol
-        if (symbol.isDeprecated) {
-          val concrOvers =
-            symbol.allOverriddenSymbols.filter(sym =>
-              !sym.isDeprecated && !sym.isDeferred)
-          if(!concrOvers.isEmpty)
-            unit.deprecationWarning(
-              tree.pos,
-              symbol.toString + " overrides concrete, non-deprecated symbol(s):" +
-              concrOvers.map(_.fullNameString).mkString("    ", ", ", ""))
-        }
+    private def checkAnnotations(tpes: List[Type], pos: Position) = tpes foreach (tp => checkTypeRef(tp, pos))
+    private def doTypeTraversal(tree: Tree)(f: Type => Unit) = if (!inPattern) tree.tpe foreach f
+
+    private def applyRefchecksToAnnotations(tree: Tree): Unit = {
+      def applyChecks(annots: List[AnnotationInfo]) = {
+        checkAnnotations(annots map (_.atp), tree.pos)
+        transformTrees(annots flatMap (_.args))
       }
 
-      def isRepeatedParamArg(tree: Tree) = currentApplication match {
-        case Apply(fn, args) =>
-          !args.isEmpty && (args.last eq tree) && 
-          fn.tpe.paramTypes.length == args.length &&
-          fn.tpe.paramTypes.last.typeSymbol == RepeatedParamClass
+      tree match {
+        case m: MemberDef => 
+          val sym = m.symbol
+          applyChecks(sym.annotations)
+          // validate implicitNotFoundMessage
+          analyzer.ImplicitNotFoundMsg.check(sym) foreach { warn =>
+            unit.warning(tree.pos, "Invalid implicitNotFound message for %s%s:\n%s".format(sym, sym.locationString, warn))
+          }
+        case tpt at TypeTree() =>
+          if(tpt.original != null) {
+            tpt.original foreach {
+              case dc at TypeTreeWithDeferredRefCheck() => applyRefchecksToAnnotations(dc.check()) // #2416
+              case _ =>
+            }
+          }
+
+          doTypeTraversal(tree) {
+            case AnnotatedType(annots, _, _)  => applyChecks(annots)
+            case _ =>
+          }
         case _ =>
-          false
       }
+    }
+    
+    private def transformCaseApply(tree: Tree, ifNot: => Unit) = {
+      val sym = tree.symbol
+      
+      if (sym.isSourceMethod && sym.hasFlag(CASE) && sym.name == nme.apply)
+        toConstructor(tree.pos, tree.tpe)
+      else {
+        ifNot
+        tree
+      }
+    }
 
-      def isCaseApply(sym : Symbol) = sym.isSourceMethod && sym.hasFlag(CASE) && sym.name == nme.apply
+    private def transformApply(tree: Apply): Tree = tree match {
+      case Apply(
+        Select(qual, nme.filter), 
+        List(Function(
+          List(ValDef(_, pname, tpt, _)), 
+          Match(_, CaseDef(pat1, _, _) :: _))))
+        if ((pname startsWith nme.CHECK_IF_REFUTABLE_STRING) && 
+            isIrrefutable(pat1, tpt.tpe) && (qual.tpe <:< tree.tpe)) =>
+            
+          transform(qual)
+
+      case Apply(Select(New(tpt), name), args) 
+      if (tpt.tpe.typeSymbol == ArrayClass && args.length >= 2) =>
+        unit.deprecationWarning(tree.pos, 
+          "new Array(...) with multiple dimensions has been deprecated; use Array.ofDim(...) instead")
+        val manif = {
+          var etpe = tpt.tpe
+          for (_ <- args) { etpe = etpe.typeArgs.headOption.getOrElse(NoType) }
+          if (etpe == NoType) {
+            unit.error(tree.pos, "too many dimensions for array creation")
+            Literal(Constant(null))
+          } else {
+            localTyper.getManifestTree(tree.pos, etpe, false)
+          }
+        }
+        val newResult = localTyper.typedPos(tree.pos) {
+          new ApplyToImplicitArgs(Apply(Select(gen.mkAttributedRef(ArrayModule), nme.ofDim), args), List(manif))
+        }
+        currentApplication = tree
+        newResult
 
+      case Apply(fn, args) =>
+        checkSensible(tree.pos, fn, args)
+        currentApplication = tree
+        tree
+    }
+    private def transformSelect(tree: Select): Tree = {
+      val Select(qual, name) = tree
+      val sym = tree.symbol
+      
+      /** Note: if a symbol has both @deprecated and @migration annotations and both
+       *  warnings are enabled, only the first one checked here will be emitted.
+       *  I assume that's a consequence of some code trying to avoid noise by suppressing
+       *  warnings after the first, but I think it'd be better if we didn't have to
+       *  arbitrarily choose one as more important than the other.
+       */
+      checkDeprecated(sym, tree.pos)
+      if (settings.Xmigration28.value)
+        checkMigration(sym, tree.pos)        
+      
+      if (currentClass != sym.owner && (sym hasFlag LOCAL)) {
+        var o = currentClass
+        var hidden = false
+        while (!hidden && o != sym.owner && o != sym.owner.moduleClass && !o.isPackage) {
+          hidden = o.isTerm || o.isPrivateLocal
+          o = o.owner
+        }
+        if (!hidden) escapedPrivateLocals += sym
+      }
+      
+      def checkSuper(mix: Name) =
+        // term should have been eliminated by super accessors
+        assert(!(qual.symbol.isTrait && sym.isTerm && mix == nme.EMPTY.toTypeName))
+      
+      transformCaseApply(tree, 
+        qual match {
+          case Super(_, mix)  => checkSuper(mix)
+          case _              =>
+        }
+      )
+    }
+    private def transformIf(tree: If): Tree = {
+      val If(cond, thenpart, elsepart) = tree
+      def unitIfEmpty(t: Tree): Tree =
+        if (t == EmptyTree) Literal(()).setPos(tree.pos).setType(UnitClass.tpe) else t
+      
+      cond.tpe match {
+        case ConstantType(value) =>
+          val res = if (value.booleanValue) thenpart else elsepart
+          unitIfEmpty(res)
+        case _ => tree
+      }
+    }
+    
+    override def transform(tree: Tree): Tree = {
       val savedLocalTyper = localTyper
       val savedCurrentApplication = currentApplication
-      val sym = tree.symbol
-      var result = tree
-      tree match {
-        case DefDef(mods, name, tparams, vparams, tpt, EmptyTree) if tree.symbol.hasAttribute(definitions.NativeAttr) =>
-          tree.symbol.resetFlag(DEFERRED)
-          result = transform(copy.DefDef(tree, mods, name, tparams, vparams, tpt, 
-                typed(Apply(gen.mkAttributedRef(definitions.Predef_error), List(Literal("native method stub"))))))
+      try {
+        val sym = tree.symbol
 
-        case DefDef(_, _, _, _, _, _) =>
-          checkDeprecatedOvers()
+        // Apply RefChecks to annotations. Makes sure the annotations conform to
+        // type bounds (bug #935), issues deprecation warnings for symbols used
+        // inside annotations.
+        applyRefchecksToAnnotations(tree)
+        var result: Tree = tree match {
+          case DefDef(mods, name, tparams, vparams, tpt, EmptyTree) if tree.symbol.hasAnnotation(NativeAttr) =>
+            tree.symbol.resetFlag(DEFERRED)
+            transform(treeCopy.DefDef(tree, mods, name, tparams, vparams, tpt, 
+                  typed(Apply(gen.mkAttributedRef(Predef_error), List(Literal("native method stub"))))))
+
+          case ValDef(_, _, _, _) | DefDef(_, _, _, _, _, _) =>
+            checkDeprecatedOvers(tree)
+            tree
+
+          case Template(parents, self, body) =>
+            localTyper = localTyper.atOwner(tree, currentOwner)
+            validateBaseTypes(currentOwner)
+            checkDefaultsInOverloaded(currentOwner)
+            val bridges = addVarargBridges(currentOwner)
+            checkAllOverrides(currentOwner)
+
+            if (bridges.nonEmpty) treeCopy.Template(tree, parents, self, body ::: bridges)
+            else tree
+
+          case dc at TypeTreeWithDeferredRefCheck() => assert(false, "adapt should have turned dc: TypeTreeWithDeferredRefCheck into tpt: TypeTree, with tpt.original == dc"); dc
+          case tpt at TypeTree() =>
+            if(tpt.original != null) {
+              tpt.original foreach {
+                case dc at TypeTreeWithDeferredRefCheck() =>
+                  transform(dc.check()) // #2416 -- only call transform to do refchecks, but discard results
+                  // tpt has the right type if the deferred checks are ok
+                case _ =>
+              }
+            }
 
-        case ValDef(_, _, _, _) =>
-          checkDeprecatedOvers()
+            val existentialParams = new ListBuffer[Symbol]
+            doTypeTraversal(tree) { // check all bounds, except those that are
+                              // existential type parameters
+              case ExistentialType(tparams, tpe) => 
+                existentialParams ++= tparams
+              case t: TypeRef => 
+                val exparams = existentialParams.toList
+                val wildcards = exparams map (_ => WildcardType)
+                checkTypeRef(t.subst(exparams, wildcards), tree.pos)
+              case _ => 
+            }
+            tree
 
-        case Template(_, _, _) =>
-          localTyper = localTyper.atOwner(tree, currentOwner)
-          validateBaseTypes(currentOwner)
-          checkAllOverrides(currentOwner)
-        
-        case TypeTree() =>
-          if (!inPattern) {
-            new TypeTraverser {
-              def traverse(tp: Type) {
-                tp match {
-                  case TypeRef(pre, sym, args) => 
-                    checkDeprecated(sym, tree.pos)
-                    if (!tp.isHigherKinded) checkBounds(pre, sym.owner, sym.typeParams, args)
-                  case _ => 
-                }
-              }
-            } traverse tree.tpe
-          }
-        case TypeApply(fn, args) =>
-          checkBounds(NoPrefix, NoSymbol, fn.tpe.typeParams, args map (_.tpe)) 
-          if (isCaseApply(sym)) result = toConstructor(tree.pos, tree.tpe)
-
-        case Apply(
-          Select(qual, nme.filter), 
-          List(Function(
-            List(ValDef(_, pname, tpt, _)), 
-            Match(_, CaseDef(pat1, _, _) :: _))))
-          if ((pname startsWith nme.CHECK_IF_REFUTABLE_STRING) && 
-              isIrrefutable(pat1, tpt.tpe)) =>
-            result = qual
-
-        case Apply(fn, args) =>
-          checkSensible(tree.pos, fn, args)
-          currentApplication = tree
-
-        case If(cond, thenpart, elsepart) =>
-          cond.tpe match {
-            case ConstantType(value) => 
-              result = if (value.booleanValue) thenpart else elsepart;
-              if (result == EmptyTree) result = Literal(()).setPos(tree.pos).setType(UnitClass.tpe)
-            case _ => 
-          }
+          case TypeApply(fn, args) =>
+            checkBounds(NoPrefix, NoSymbol, fn.tpe.typeParams, args map (_.tpe), tree.pos)
+            transformCaseApply(tree, ())
+
+          case x @ Apply(_, _)  =>
+            transformApply(x)
+
+          case x @ If(_, _, _)  =>
+            transformIf(x)
 
-        case New(tpt) =>
-          enterReference(tree.pos, tpt.tpe.typeSymbol)
+          case New(tpt) =>
+            enterReference(tree.pos, tpt.tpe.typeSymbol)
+            tree
 
-        case Typed(expr, tpt @ Ident(name)) if (name == nme.WILDCARD_STAR.toTypeName) =>
-          if (!isRepeatedParamArg(tree))
+          case Typed(expr, tpt @ Ident(name)) if name == nme.WILDCARD_STAR.toTypeName && !isRepeatedParamArg(tree) =>
             unit.error(tree.pos, "no `: _*' annotation allowed here\n"+
               "(such annotations are only allowed in arguments to *-parameters)")
+            tree
 
-        case Ident(name) =>
-          if (isCaseApply(sym))
-            result = toConstructor(tree.pos, tree.tpe)
-          else if (name != nme.WILDCARD && name != nme.WILDCARD_STAR.toTypeName) {
-            assert(sym != NoSymbol, tree)//debug
-            enterReference(tree.pos, sym)
-          }
+          case Ident(name) =>
+            transformCaseApply(tree,
+              if (name != nme.WILDCARD && name != nme.WILDCARD_STAR.toTypeName) {
+                assert(sym != NoSymbol, tree) //debug
+                enterReference(tree.pos, sym)
+              }
+            )
 
-        case Select(qual, name) =>
-          checkDeprecated(sym, tree.pos)
-          if (currentClass != sym.owner && (sym hasFlag LOCAL)) {
-            var o = currentClass
-            var hidden = false
-            while (!hidden && o != sym.owner && o != sym.owner.moduleClass && !o.isPackage) {
-              hidden = o.isTerm || o.isPrivateLocal
-              o = o.owner
-            }
-            if (!hidden) escapedPrivateLocals += sym
-          }
-          if (isCaseApply(sym))
-            result = toConstructor(tree.pos, tree.tpe)
-          else qual match {
-            case Super(qualifier, mix) =>
-              val base = qual.symbol;
-              //Console.println("super: " + tree + " in " + base);//DEBUG
-              assert(!(base.isTrait && sym.isTerm && mix == nme.EMPTY.toTypeName)) // term should have been eliminated by super accessors
-            case _ =>
-          }
-        case _ =>
-      }
-      result = result match {
-        case CaseDef(pat, guard, body) =>
-          inPattern = true
-          val pat1 = transform(pat)
-          inPattern = false
-          copy.CaseDef(tree, pat1, transform(guard), transform(body))
-        case _ =>
-          super.transform(result)
-      }
-      result match {
-        case ClassDef(_, _, _, _) 
-           | TypeDef(_, _, _, _) =>
-          if (result.symbol.isLocal || result.symbol.owner.isPackageClass) 
-            varianceValidator.traverse(result)
-        case _ =>
-      }
-      localTyper = savedLocalTyper
-      currentApplication = savedCurrentApplication
-      result
-    } catch {
-      case ex: TypeError =>
-        if (settings.debug.value) ex.printStackTrace();
-        unit.error(tree.pos, ex.getMessage())
-        tree
+          case x @ Select(_, _) =>
+            transformSelect(x)
+
+          case _ => tree
+        }
+        result = result match {
+          case CaseDef(pat, guard, body) =>
+            inPattern = true
+            val pat1 = transform(pat)
+            inPattern = false
+            treeCopy.CaseDef(tree, pat1, transform(guard), transform(body))
+          case _ =>
+            super.transform(result)
+        }
+        result match {
+          case ClassDef(_, _, _, _) 
+             | TypeDef(_, _, _, _) =>
+            if (result.symbol.isLocal || result.symbol.owner.isPackageClass) 
+              varianceValidator.traverse(result)
+          case _ =>
+        }
+        result
+      } catch {
+        case ex: TypeError =>
+          if (settings.debug.value) ex.printStackTrace();
+          unit.error(tree.pos, ex.getMessage())
+          tree
+      } finally {
+        localTyper = savedLocalTyper
+        currentApplication = savedCurrentApplication
+      }        
     }
   }
 }
diff --git a/src/compiler/scala/tools/nsc/typechecker/SuperAccessors.scala b/src/compiler/scala/tools/nsc/typechecker/SuperAccessors.scala
index c7ddaac..616c3de 100644
--- a/src/compiler/scala/tools/nsc/typechecker/SuperAccessors.scala
+++ b/src/compiler/scala/tools/nsc/typechecker/SuperAccessors.scala
@@ -1,14 +1,13 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author Martin Odersky
  */
-// $Id: SuperAccessors.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.tools.nsc.typechecker
+package scala.tools.nsc
+package typechecker
 
 import scala.collection.mutable.ListBuffer
-import nsc.symtab.Flags._
-import scala.tools.nsc.util.{Position}
+import symtab.Flags._
 
 /** This phase adds super accessors for all super calls that
  *  either appear in a trait or have as a target a member of some outer class.
@@ -26,8 +25,7 @@ abstract class SuperAccessors extends transform.Transform with transform.TypingT
   // inherits abstract value `global' and class `Phase' from Transform
 
   import global._
-  import posAssigner.atPos
-  import typer.typed
+  import definitions.{ IntClass, UnitClass, ByNameParamClass, Any_asInstanceOf, Object_## }
 
   /** the following two members override abstract members in Transform */
   val phaseName: String = "superaccessors"
@@ -38,33 +36,28 @@ abstract class SuperAccessors extends transform.Transform with transform.TypingT
   class SuperAccTransformer(unit: CompilationUnit) extends TypingTransformer(unit) {
     private var validCurrentOwner = true
     private var accDefs: List[(Symbol, ListBuffer[Tree])] = List()
-    private val typer = analyzer.newTyper(analyzer.rootContext(unit))
-
+    
     private def accDefBuf(clazz: Symbol) = accDefs find (_._1 == clazz) match {
       case Some((_, buf)) => buf
       case None => throw new AssertionError("no acc def buf for "+clazz)
     }
-/*
-    private def transformArgs(args: List[Tree], formals: List[Type]) = {
-      if (!formals.isEmpty && formals.last.symbol == definitions.ByNameParamClass)
-        ((args take (formals.length - 1) map transform) :::
-         withInvalidOwner { args drop (formals.length - 1) map transform })
-      else
-        args map transform
-    }
-*/
-    private def transformArgs(args: List[Tree], formals: List[Type]) =
-      List.map2(args, formals){ (arg, formal) =>
-        if (formal.typeSymbol == definitions.ByNameParamClass) 
-          withInvalidOwner { checkPackedConforms(transform(arg), formal.typeArgs.head) }
+
+    private def transformArgs(args: List[Tree], params: List[Symbol]) =
+      ((args, params).zipped map { (arg, param) =>
+        if (param.tpe.typeSymbol == ByNameParamClass) 
+          withInvalidOwner { checkPackedConforms(transform(arg), param.tpe.typeArgs.head) }
         else transform(arg)
-      } :::
-      (args drop formals.length map transform)
+      }) :::
+      (args drop params.length map transform)
 
     private def checkPackedConforms(tree: Tree, pt: Type): Tree = {
       if (tree.tpe exists (_.typeSymbol.isExistentialSkolem)) {
-        val packed = typer.packedType(tree, NoSymbol)
-        if (!(packed <:< pt)) typer.infer.typeError(tree.pos, packed, pt)
+        val packed = localTyper.packedType(tree, NoSymbol)
+        if (!(packed <:< pt)) {
+          val errorContext = localTyper.context.make(localTyper.context.tree)
+          errorContext.reportGeneralErrors = true
+          analyzer.newTyper(errorContext).infer.typeError(tree.pos, packed, pt)
+        }
       }
       tree
     }
@@ -81,15 +74,21 @@ abstract class SuperAccessors extends transform.Transform with transform.TypingT
             other = linked.info.decl(sym.name.toTermName).filter(_.isModule)
           if (other != NoSymbol)
             unit.error(sym.pos, "name clash: "+sym.owner+" defines "+sym+
-                       "\nand its companion "+sym.owner.linkedModuleOfClass+" also defines "+
+                       "\nand its companion "+sym.owner.companionModule+" also defines "+
                        other)
         }
       }
 
-    private def transformSuperSelect(tree: Tree) = tree match {
-      case Select(sup @ Super(_, mix), name) =>
+    private def transformSuperSelect(tree: Tree): Tree = tree match {
+      // Intercept super.## and translate it to this.##
+      // which is fine since it's final.
+      case Select(sup @ Super(_, _), nme.HASHHASH)  =>
+        Select(gen.mkAttributedThis(sup.symbol), Object_##) setType IntClass.tpe
+        
+      case Select(sup @ Super(_, mix), name)  =>
         val sym = tree.symbol
         val clazz = sup.symbol
+
         if (sym.isDeferred) {
           val member = sym.overridingSymbol(clazz);
           if (mix != nme.EMPTY.toTypeName || member == NoSymbol || 
@@ -115,7 +114,7 @@ abstract class SuperAccessors extends transform.Transform with transform.TypingT
             superAcc.setInfo(superAccTpe.cloneInfo(superAcc))
             //println("creating super acc "+superAcc+":"+superAcc.tpe)//DEBUG
             clazz.info.decls enter superAcc;
-            accDefBuf(clazz) += typed(DefDef(superAcc, vparamss => EmptyTree))
+            accDefBuf(clazz) += typers(clazz).typed(DefDef(superAcc, EmptyTree))
           }
           atPos(sup.pos) {
             Select(gen.mkAttributedThis(clazz), superAcc) setType tree.tpe;
@@ -127,113 +126,121 @@ abstract class SuperAccessors extends transform.Transform with transform.TypingT
         assert(tree.tpe.isError, tree)
         tree
     }
- 
-    override def transform(tree: Tree): Tree = try { tree match {
-      case ClassDef(_, _, _, _) =>
-        checkCompanionNameClashes(tree.symbol)
-        val decls = tree.symbol.info.decls
-        for (val sym <- decls.toList) {
-          if (sym.privateWithin.isClass && !sym.privateWithin.isModuleClass &&
-              !sym.hasFlag(EXPANDEDNAME) && !sym.isConstructor) {
-            decls.unlink(sym)
-            sym.expandName(sym.privateWithin)
-            decls.enter(sym)
-          }
+
+    override def transform(tree: Tree): Tree = {
+      val sym = tree.symbol
+
+      def mayNeedProtectedAccessor(sel: Select, args: List[Tree], goToSuper: Boolean) =
+        if (needsProtectedAccessor(sym, tree.pos)) {
+          if (settings.debug.value)
+            log("Adding protected accessor for " + tree)
+
+          transform(makeAccessor(sel, args))
         }
-        super.transform(tree)
-      case ModuleDef(_, _, _) =>
-        checkCompanionNameClashes(tree.symbol)
-        super.transform(tree)
-      case Template(parents, self, body) =>
-	val ownAccDefs = new ListBuffer[Tree];
-	accDefs = (currentOwner, ownAccDefs) :: accDefs;
+        else if (goToSuper) super.transform(tree)
+        else tree
+      
+      try tree match {
+        case ClassDef(_, _, _, _) =>
+          checkCompanionNameClashes(sym)
+          val decls = sym.info.decls
+          for (s <- decls.toList) {
+            if (s.privateWithin.isClass && !s.privateWithin.isModuleClass &&
+                !s.hasFlag(EXPANDEDNAME) && !s.isConstructor) {
+              decls.unlink(s)
+              s.expandName(s.privateWithin)
+              decls.enter(s)
+            }
+          }
+          if (settings.verbose.value && onlyPresentation && !sym.isAnonymousClass) {
+            println("========== scaladoc of "+sym+" =============================")
+            println(toJavaDoc(expandedDocComment(sym)))
+            for (member <- sym.info.members) {
+              println(member+":"+sym.thisType.memberInfo(member)+"\n"+
+                      toJavaDoc(expandedDocComment(member, sym)))
+              for ((useCase, comment, pos) <- useCases(member, sym)) {
+                println("usecase "+useCase+":"+useCase.info)
+                println(toJavaDoc(comment))
+              }
+            }
+          }
+          super.transform(tree)
+        case ModuleDef(_, _, _) =>
+          checkCompanionNameClashes(sym)
+          super.transform(tree)
+        case Template(parents, self, body) =>
+          val ownAccDefs = new ListBuffer[Tree];
+          accDefs = (currentOwner, ownAccDefs) :: accDefs;
         
-        // ugly hack... normally, the following line should not be 
-        // necessary, the 'super' method taking care of that. but because
-        // that one is iterating through parents (and we dont want that here)
-        // we need to inline it.
-        curTree = tree
-        val body1 = atOwner(currentOwner) { transformTrees(body) }
-	accDefs = accDefs.tail;
-	copy.Template(tree, parents, self, ownAccDefs.toList ::: body1);
+          // ugly hack... normally, the following line should not be 
+          // necessary, the 'super' method taking care of that. but because
+          // that one is iterating through parents (and we dont want that here)
+          // we need to inline it.
+          curTree = tree
+          val body1 = atOwner(currentOwner) { transformTrees(body) }
+          accDefs = accDefs.tail;
+          treeCopy.Template(tree, parents, self, ownAccDefs.toList ::: body1);
 
-      case TypeApply(sel @ Select(This(_), name), args) =>
-        val sym = tree.symbol
-        if (needsProtectedAccessor(sym, tree.pos)) {
-          if (settings.debug.value) log("Adding protected accessor for " + tree);
-          transform(makeAccessor(sel.asInstanceOf[Select], args))
-        } else 
-          tree
+        case TypeApply(sel @ Select(This(_), name), args) =>
+          mayNeedProtectedAccessor(sel, args, false)
       
-      case Select(qual @ This(_), name) =>
-        val sym = tree.symbol
-         if ((sym hasFlag PARAMACCESSOR) && (sym.alias != NoSymbol)) {
-          val result = typed {
-            Select(
-              Super(qual.symbol, nme.EMPTY.toTypeName/*qual.symbol.info.parents.head.symbol.name*/) setPos qual.pos,
-              sym.alias) setPos tree.pos
+        case sel @ Select(qual @ This(_), name) =>
+           if ((sym hasFlag PARAMACCESSOR)
+               && (sym.alias != NoSymbol)) {
+            val result = localTyper.typed {
+                Select(
+                  Super(qual.symbol, nme.EMPTY.toTypeName/*qual.symbol.info.parents.head.symbol.name*/) setPos qual.pos,
+                  sym.alias) setPos tree.pos
+            }
+            if (settings.debug.value) 
+              Console.println("alias replacement: " + tree + " ==> " + result);//debug
+            localTyper.typed(gen.maybeMkAsInstanceOf(transformSuperSelect(result), sym.tpe, sym.alias.tpe, true))
           }
-          if (settings.debug.value) 
-            Console.println("alias replacement: " + tree + " ==> " + result);//debug
-          transformSuperSelect(result)
-        } else {
-          if (needsProtectedAccessor(sym, tree.pos)) {
-            if (settings.debug.value) log("Adding protected accessor for " + tree);
-            transform(makeAccessor(tree.asInstanceOf[Select], List(EmptyTree)))
-          } else 
-            tree
-        }
-      case Select(sup @ Super(_, mix), name) =>
-        val sym = tree.symbol
-        if (sym.isValue && !sym.isMethod || sym.hasFlag(ACCESSOR)) {
-          unit.error(tree.pos, "super may be not be used on "+
-                     (if (sym.hasFlag(ACCESSOR)) sym.accessed else sym))
-        }
-        transformSuperSelect(tree)
+          else mayNeedProtectedAccessor(sel, List(EmptyTree), false)
+
+        case Select(sup @ Super(_, mix), name) =>
+          if (sym.isValue && !sym.isMethod || sym.hasFlag(ACCESSOR)) {
+            unit.error(tree.pos, "super may be not be used on "+
+                       (if (sym.hasFlag(ACCESSOR)) sym.accessed else sym))
+          }
+          transformSuperSelect(tree)
       
-      case TypeApply(sel @ Select(qual, name), args) =>
-        val sym = tree.symbol
-        if (needsProtectedAccessor(sym, tree.pos)) {
-          if (settings.debug.value) log("Adding protected accessor for tree: " + tree);
-          transform(makeAccessor(sel.asInstanceOf[Select], args))
-        } else
-          super.transform(tree)
+        case TypeApply(sel @ Select(qual, name), args) =>
+          mayNeedProtectedAccessor(sel, args, true)
 
-      case Select(qual, name) =>
-        val sym = tree.symbol
-        if (needsProtectedAccessor(sym, tree.pos)) {
-          if (settings.debug.value) log("Adding protected accessor for tree: " + tree);
-          transform(makeAccessor(tree.asInstanceOf[Select], List(EmptyTree)))
-        } else
-          super.transform(tree)
-                
-      case Assign(lhs @ Select(qual, name), rhs) =>
-        if (lhs.symbol.isVariable && 
-            lhs.symbol.hasFlag(JAVA) &&
-            needsProtectedAccessor(lhs.symbol, tree.pos)) {
-          if (settings.debug.value) log("Adding protected setter for " + tree)
-          val setter = makeSetter(lhs);
-          if (settings.debug.value)
-            log("Replaced " + tree + " with " + setter);
-          transform(typed(Apply(setter, List(qual, rhs))))
-        } else
-          super.transform(tree)
+        case sel @ Select(qual, name) =>
+          mayNeedProtectedAccessor(sel, List(EmptyTree), true)
 
-      case Apply(fn, args) =>
-        assert(fn.tpe != null, tree) 
-        copy.Apply(tree, transform(fn), transformArgs(args, fn.tpe.paramTypes))
-      case Function(vparams, body) =>
-        withInvalidOwner {
-          copy.Function(tree, vparams, transform(body))
-        }
-      case _ =>
-        super.transform(tree)
-    }} catch {
-      case ex : AssertionError =>
-        if (tree.symbol != null && tree.symbol != NoSymbol) 
-          Console.println("TRANSFORM: " + tree.symbol.sourceFile)
-        Console.println("TREE: " + tree)
-        throw ex
+        case Assign(lhs @ Select(qual, name), rhs) =>
+          if (lhs.symbol.isVariable && 
+              lhs.symbol.hasFlag(JAVA) &&
+              needsProtectedAccessor(lhs.symbol, tree.pos)) {
+            if (settings.debug.value) log("Adding protected setter for " + tree)
+            val setter = makeSetter(lhs);
+            if (settings.debug.value)
+              log("Replaced " + tree + " with " + setter);
+            transform(localTyper.typed(Apply(setter, List(qual, rhs))))
+          } else
+            super.transform(tree)
+
+        case Apply(fn, args) =>
+          assert(fn.tpe != null, tree) 
+          treeCopy.Apply(tree, transform(fn), transformArgs(args, fn.tpe.params))
+        case Function(vparams, body) =>
+          withInvalidOwner {
+            treeCopy.Function(tree, vparams, transform(body))
+          }
+        case _ =>
+          super.transform(tree)
+      }
+      catch {
+        case ex : AssertionError =>
+          if (sym != null && sym != NoSymbol) 
+            Console.println("TRANSFORM: " + tree.symbol.sourceFile)
+            
+          Console.println("TREE: " + tree)
+          throw ex
+      }
     }
 
     override def atOwner[A](owner: Symbol)(trans: => A): A = {
@@ -261,37 +268,42 @@ abstract class SuperAccessors extends transform.Transform with transform.TypingT
       /** Return a list of list of types of all value parameter sections. */
       def allParamTypes(tpe: Type): List[List[Type]] = tpe match {
         case PolyType(_, restpe) => allParamTypes(restpe)
-        case MethodType(pts, res) => pts :: allParamTypes(res)
+        case MethodType(params, res) => params.map(_.tpe) :: allParamTypes(res)
         case _ => Nil
       }
-      
+
+
       assert(clazz != NoSymbol, sym)
       if (settings.debug.value)  log("Decided for host class: " + clazz)
-      
+
       val accName = nme.protName(sym.originalName)
       val hasArgs = sym.tpe.paramTypes != Nil
-      val memberType = sym.tpe // transform(sym.tpe)
+      val memberType = refchecks.toScalaRepeatedParam(sym.tpe) // fix for #2413
       
       // if the result type depends on the this type of an enclosing class, the accessor
       // has to take an object of exactly this type, otherwise it's more general
-      val objType = if (isThisType(memberType.finalResultType)) clazz.thisType else clazz.typeOfThis 
-      val accType = memberType match {
-        case PolyType(tparams, restpe) => 
-          PolyType(tparams, MethodType(List(objType), restpe.asSeenFrom(qual.tpe, sym.owner)))
+      val objType = if (isThisType(memberType.finalResultType)) clazz.thisType else clazz.typeOfThis
+      val accType = (protAcc: Symbol) => memberType match {
+        case PolyType(tparams, restpe) =>
+          // luc: question to author: should the tparams symbols not be cloned and get a new owner (protAcc)?
+          PolyType(tparams, MethodType(List(protAcc.newSyntheticValueParam(objType)),
+                                       restpe.cloneInfo(protAcc).asSeenFrom(qual.tpe, sym.owner)))
         case _ => 
-          MethodType(List(objType), memberType.asSeenFrom(qual.tpe, sym.owner))
+          MethodType(List(protAcc.newSyntheticValueParam(objType)),
+                     memberType.cloneInfo(protAcc).asSeenFrom(qual.tpe, sym.owner))
       }
       if (settings.debug.value) log("accType: " + accType)
         
-      var protAcc = clazz.info.decl(accName).suchThat(_.tpe == accType)
+      var protAcc = clazz.info.decl(accName).suchThat(s => s == NoSymbol || s.tpe =:= accType(s))
       if (protAcc == NoSymbol) { 
-        protAcc = clazz.newMethod(tree.pos, nme.protName(sym.originalName)).setInfo(accType)
+        protAcc = clazz.newMethod(tree.pos, nme.protName(sym.originalName))
+        protAcc.setInfo(accType(protAcc))
         clazz.info.decls.enter(protAcc);
-        val code = DefDef(protAcc, vparamss => {
-          val obj = vparamss.head.head // receiver
-          vparamss.tail.zip(allParamTypes(sym.tpe)).foldLeft(Select(Ident(obj), sym): Tree) (
+        val code = DefDef(protAcc, {
+          val obj = protAcc.paramss.head.head // receiver
+          protAcc.paramss.tail.zip(allParamTypes(sym.tpe)).foldLeft(Select(Ident(obj), sym): Tree) (
               (fun, pvparams) => {
-                Apply(fun, (List.map2(pvparams._1, pvparams._2) { (v, origTpe) => makeArg(v, obj, origTpe) } ))
+                Apply(fun, (pvparams._1, pvparams._2).zipped map (makeArg(_, obj, _)))
               })
         })
 
@@ -307,20 +319,22 @@ abstract class SuperAccessors extends transform.Transform with transform.TypingT
       }
       if (settings.debug.value)
         log("Replaced " + tree + " with " + res)
-      if (hasArgs) typer.typedOperator(res) else typer.typed(res)
+      if (hasArgs) localTyper.typedOperator(res) else localTyper.typed(res)
     }
     
     /** Adapt the given argument in call to protected member. 
-     *  Adaptation means adding a cast to a path-dependent type, for instance
+     *  Adaptation may add a cast to a path-dependent type, for instance
      *  
      *  def prot$m(obj: Outer)(x: Inner) = obj.m(x.asInstanceOf[obj.Inner]).
      *
      *  such a cast might be necessary when m expects an Outer.this.Inner (the 
      *  outer of 'obj' and 'x' have to be the same). This restriction can't be
      *  expressed in the type system (but is implicit when defining method m).
+     *
+     *  Also, it calls using repeated parameters are ascribed with ': _*'
      */
     private def makeArg(v: Symbol, obj: Symbol, expectedTpe: Type): Tree = {
-      val res = Ident(v)
+      var res: Tree = Ident(v)
       val sym = obj.tpe.typeSymbol
       var ownerClass: Symbol = NoSymbol
       
@@ -330,13 +344,15 @@ abstract class SuperAccessors extends transform.Transform with transform.TypingT
           if (sym.isSubClass(ownerClass)) true else false 
         case _ => false
       }
+      if (definitions.isRepeatedParamType(v.info)) {
+        res = gen.wildcardStar(res)
+        log("adapted to wildcard star: " + res)
+      }
       if (isDependentType) {
         val preciseTpe = expectedTpe.asSeenFrom(singleType(NoPrefix, obj), ownerClass) //typeRef(singleType(NoPrefix, obj), v.tpe.symbol, List())
-        TypeApply(Select(res, definitions.Any_asInstanceOf), 
+        TypeApply(Select(res, Any_asInstanceOf), 
                   List(TypeTree(preciseTpe)))
-      }
-      else
-        res              
+      } else res
     }
     
     /** For a path-dependent type, return the this type. */
@@ -359,10 +375,11 @@ abstract class SuperAccessors extends transform.Transform with transform.TypingT
       var protAcc = clazz.info.decl(accName)
       if (protAcc == NoSymbol) {
         protAcc = clazz.newMethod(field.pos, nme.protSetterName(field.originalName))
-                           .setInfo(MethodType(List(clazz.typeOfThis, field.tpe), definitions.UnitClass.tpe));
+        protAcc.setInfo(MethodType(protAcc.newSyntheticValueParams(List(clazz.typeOfThis, field.tpe)),
+                                   UnitClass.tpe))
         clazz.info.decls.enter(protAcc)
-        val code = DefDef(protAcc, vparamss => {
-          val obj :: value :: Nil = vparamss.head;
+        val code = DefDef(protAcc, {
+          val obj :: value :: Nil = protAcc.paramss.head;
           atPos(tree.pos) {
             Assign(
               Select(Ident(obj), field.name),
@@ -391,27 +408,39 @@ abstract class SuperAccessors extends transform.Transform with transform.TypingT
      * classes, this has to be signaled as error.
      */
     private def needsProtectedAccessor(sym: Symbol, pos: Position): Boolean = {
+      def errorRestriction(msg: String) {
+        unit.error(pos, "Implementation restriction: " + msg)
+      }
+
+      def accessibleThroughSubclassing: Boolean =
+        (validCurrentOwner
+            && currentOwner.enclClass.thisSym.isSubClass(sym.owner)
+            && !currentOwner.enclClass.isTrait)
+      
       val res = /* settings.debug.value && */
-      ((sym hasFlag PROTECTED) 
-       && (!validCurrentOwner || !(currentOwner.enclClass.thisSym isSubClass sym.owner))
-       && (enclPackage(sym.owner) != enclPackage(currentOwner))
-       && (enclPackage(sym.owner) == enclPackage(sym.accessBoundary(sym.owner))))
+      ((sym hasFlag PROTECTED)
+       && sym.hasFlag(JAVA)
+       && !sym.owner.isPackageClass
+       && !accessibleThroughSubclassing
+       && (sym.owner.enclosingPackageClass != currentOwner.enclosingPackageClass)
+       && (sym.owner.enclosingPackageClass == sym.accessBoundary(sym.owner).enclosingPackageClass))
 
       if (res) {
         val host = hostForAccessorOf(sym, currentOwner.enclClass)
-        if (host.thisSym != host) {
+        // bug #1393 - as things stand now the "host" could be a package.
+        if (host.isPackageClass) false
+        else if (host.thisSym != host) {
           if (host.thisSym.tpe.typeSymbol.hasFlag(JAVA))
-            unit.error(pos, "Implementation restriction: " + currentOwner.enclClass + " accesses protected "
-                            + sym + " from self type " + host.thisSym.tpe)
+            errorRestriction("%s accesses protected %s from self type %s.".format(currentOwner.enclClass, sym, host.thisSym.tpe))
           false
+        } else if (host.isTrait && sym.hasFlag(JAVA)) {
+            errorRestriction(("%s accesses protected %s inside a concrete trait method. " +
+                    "Add an accessor in a class extending %s to work around this bug.").format(currentOwner.enclClass, sym, sym.enclClass))
+            false
         } else res
       } else res
     }
       
-    /** Return the enclosing package of the given symbol. */
-    private def enclPackage(sym: Symbol): Symbol = 
-      if ((sym == NoSymbol) || sym.isPackageClass) sym else enclPackage(sym.owner)
-      
     /** Return the innermost enclosing class C of referencingClass for which either
      *  of the following holds: 
      *     - C is a subclass of sym.owner or 
@@ -420,11 +449,12 @@ abstract class SuperAccessors extends transform.Transform with transform.TypingT
     private def hostForAccessorOf(sym: Symbol, referencingClass: Symbol): Symbol = {
       if (referencingClass.isSubClass(sym.owner.enclClass)
           || referencingClass.thisSym.isSubClass(sym.owner.enclClass)
-          || enclPackage(referencingClass) == enclPackage(sym.owner)) {
+          || referencingClass.enclosingPackageClass == sym.owner.enclosingPackageClass) {
         assert(referencingClass.isClass)
         referencingClass
-      } else
+      } else if(referencingClass.owner.enclClass != NoSymbol)
         hostForAccessorOf(sym, referencingClass.owner.enclClass)
+      else referencingClass
     }
     
     /** Is 'tpe' the type of a member of an enclosing class? */
diff --git a/src/compiler/scala/tools/nsc/typechecker/SyntheticMethods.scala b/src/compiler/scala/tools/nsc/typechecker/SyntheticMethods.scala
index dccfceb..a47371c 100644
--- a/src/compiler/scala/tools/nsc/typechecker/SyntheticMethods.scala
+++ b/src/compiler/scala/tools/nsc/typechecker/SyntheticMethods.scala
@@ -1,11 +1,12 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author Martin Odersky
  */
-// $Id: SyntheticMethods.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.tools.nsc.typechecker
+package scala.tools.nsc
+package typechecker
 
+import symtab.Flags
 import symtab.Flags._
 import scala.collection.mutable.ListBuffer
 
@@ -26,323 +27,291 @@ import scala.collection.mutable.ListBuffer
  *    </li>
  *  </ul>
  */
-trait SyntheticMethods { self: Analyzer =>
+trait SyntheticMethods extends ast.TreeDSL {
+  self: Analyzer =>
+  
   import global._                  // the global environment
   import definitions._             // standard classes and methods
-  //import global.typer.{typed}      // methods to type trees
+
   // @S: type hack: by default, we are used from global.analyzer context
   // so this cast won't fail. If we aren't in global.analyzer, we have
   // to override this method anyways.
   protected def typer : Typer = global.typer.asInstanceOf[Typer]
 
-  /**
-   *  @param templ ...
-   *  @param clazz ...
-   *  @param unit  ...
-   *  @return      ...
+  /** Add the synthetic methods to case classes.  Note that a lot of the
+   *  complexity herein is a consequence of case classes inheriting from
+   *  case classes, which has been deprecated as of Sep 11 2009.  So when
+   *  the opportunity for removal arises, this can be simplified.
    */
-  def addSyntheticMethods(templ: Template, clazz: Symbol, context: Context): Template = try {
+  def addSyntheticMethods(templ: Template, clazz: Symbol, context: Context): Template = {
 
-    val localContext = if (reporter.hasErrors) context.makeSilent(false) else context
-    val localTyper = newTyper(localContext)
+    val localContext  = if (reporter.hasErrors) context makeSilent false else context
+    val localTyper    = newTyper(localContext)
 
-    def hasImplementation(name: Name): Boolean = if (inIDE) true else {
-      val sym = clazz.info.nonPrivateMember(name) 
+    def hasImplementation(name: Name): Boolean = {
+      val sym = clazz.info member name // member and not nonPrivateMember: bug #1385
       sym.isTerm && !(sym hasFlag DEFERRED)
     }
 
-    def hasOverridingImplementation(meth: Symbol): Boolean = if (inIDE) true else {
-      val sym = clazz.info.nonPrivateMember(meth.name)
+    def hasOverridingImplementation(meth: Symbol): Boolean = {
+      val sym = clazz.info nonPrivateMember meth.name
       sym.alternatives exists { sym =>
         sym != meth && !(sym hasFlag DEFERRED) && !(sym hasFlag (SYNTHETIC | SYNTHETICMETH)) && 
         (clazz.thisType.memberType(sym) matches clazz.thisType.memberType(meth))
       }
     }
 
-    def syntheticMethod(name: Name, flags: Int, tpe: Type) =
-      newSyntheticMethod(name, flags | OVERRIDE, tpe)
+    def syntheticMethod(name: Name, flags: Int, tpeCons: Symbol => Type) =
+      newSyntheticMethod(name, flags | OVERRIDE, tpeCons)
 
-    def newSyntheticMethod(name: Name, flags: Int, tpe: Type) = {
-      var method = clazz.newMethod(clazz.pos, name) 
-        .setFlag(flags | (if (inIDE) SYNTHETIC else SYNTHETICMETH))
-        .setInfo(tpe)
-      method = clazz.info.decls.enter(method).asInstanceOf[TermSymbol]
-      method
+    def newSyntheticMethod(name: Name, flags: Int, tpeCons: Symbol => Type) = {
+      val method = clazz.newMethod(clazz.pos.focus, name) setFlag (flags | SYNTHETICMETH)
+      method setInfo tpeCons(method)
+      clazz.info.decls.enter(method).asInstanceOf[TermSymbol]
     }
+    
+    def makeNoArgConstructor(res: Type) =
+      (sym: Symbol) => MethodType(Nil, res)
+    def makeTypeConstructor(args: List[Type], res: Type) =
+      (sym: Symbol) => MethodType(sym newSyntheticValueParams args, res)
+    
+    import CODE._
 
-    /*
-    def productSelectorMethod(n: int, accessor: Symbol): Tree = {
-      val method = syntheticMethod(newTermName("_"+n), FINAL, accessor.tpe) 
-      typed(DefDef(method, vparamss => gen.mkAttributedRef(accessor)))
-    }
-    */
-    def productPrefixMethod: Tree = {
-      val method = syntheticMethod(nme.productPrefix, 0, PolyType(List(), StringClass.tpe))
-      typer.typed(DefDef(method, vparamss => Literal(Constant(clazz.name.decode))))
+    def productPrefixMethod: Tree = typer.typed {
+      val method = syntheticMethod(nme.productPrefix, 0, sym => PolyType(Nil, StringClass.tpe))
+      DEF(method) === LIT(clazz.name.decode)
     }
 
-    def productArityMethod(nargs:Int ): Tree = {
-      val method = syntheticMethod(nme.productArity, 0, PolyType(List(), IntClass.tpe))
-      typer.typed(DefDef(method, vparamss => Literal(Constant(nargs))))
+    def productArityMethod(nargs: Int): Tree = {
+      val method = syntheticMethod(nme.productArity, 0, sym => PolyType(Nil, IntClass.tpe))
+      typer typed { DEF(method) === LIT(nargs) }
     }
 
-    def productElementMethod(accs: List[Symbol]): Tree = {
-      //val retTpe = lub(accs map (_.tpe.resultType))
-      val method = syntheticMethod(nme.productElement, 0, MethodType(List(IntClass.tpe), AnyClass.tpe/*retTpe*/))
-      typer.typed(DefDef(method, vparamss => Match(Ident(vparamss.head.head), {
-	(for ((sym,i) <- accs.zipWithIndex) yield {
-	  CaseDef(Literal(Constant(i)),EmptyTree, Ident(sym))
-	}):::List(CaseDef(Ident(nme.WILDCARD), EmptyTree, 
-		    Throw(New(TypeTree(IndexOutOfBoundsExceptionClass.tpe), List(List(
-		      Select(Ident(vparamss.head.head), nme.toString_)
-		    ))))))
-      })))
-    }
+    /** Common code for productElement and (currently disabled) productElementName
+     */
+    def perElementMethod(accs: List[Symbol], methodName: Name, resType: Type, caseFn: Symbol => Tree): Tree = {
+      val symToTpe  = makeTypeConstructor(List(IntClass.tpe), resType)
+      val method    = syntheticMethod(methodName, 0, symToTpe)
+      val arg       = method ARG 0
+      val default   = List(DEFAULT ==> THROW(IndexOutOfBoundsExceptionClass, arg))
+      val cases     =
+        for ((sym, i) <- accs.zipWithIndex) yield
+          CASE(LIT(i)) ==> caseFn(sym)
 
-    def moduleToStringMethod: Tree = {
-      val method = syntheticMethod(nme.toString_, FINAL, MethodType(List(), StringClass.tpe))
-      typer.typed(DefDef(method, vparamss => Literal(Constant(clazz.name.decode))))
+      typer typed {
+        DEF(method) === {
+          arg MATCH { cases ::: default : _* }
+        }
+      }
     }
+    def productElementMethod(accs: List[Symbol]): Tree =
+      perElementMethod(accs, nme.productElement, AnyClass.tpe, x => Ident(x))
+  
+    // def productElementNameMethod(accs: List[Symbol]): Tree =
+    //   perElementMethod(accs, nme.productElementName, StringClass.tpe, x => Literal(x.name.toString))
 
-    def tagMethod: Tree = {
-      val method = syntheticMethod(nme.tag, 0, MethodType(List(), IntClass.tpe))
-      typer.typed(DefDef(method, vparamss => Literal(Constant(clazz.tag))))
+    def moduleToStringMethod: Tree = {
+      val method = syntheticMethod(nme.toString_, FINAL, makeNoArgConstructor(StringClass.tpe))
+      typer typed { DEF(method) === LIT(clazz.name.decode) }
     }
 
-    def forwardingMethod(name: Name): Tree = {
-      val target = getMember(ScalaRunTimeModule, "_" + name)
-      val paramtypes =
-        if (target.tpe.paramTypes.isEmpty) List()
-        else target.tpe.paramTypes.tail
-      val method = syntheticMethod(
-        name, 0, MethodType(paramtypes, target.tpe.resultType))
-      typer.typed(DefDef(method, vparamss =>
-        Apply(gen.mkAttributedRef(target), This(clazz) :: (vparamss.head map Ident))))
+    def forwardingMethod(name: Name, targetName: Name): Tree = {
+      val target      = getMember(ScalaRunTimeModule, targetName)
+      val paramtypes  = target.tpe.paramTypes drop 1
+      val method      = syntheticMethod(
+        name, 0, makeTypeConstructor(paramtypes, target.tpe.resultType)
+      )
+        
+      typer typed {
+        DEF(method) === {
+          Apply(REF(target), This(clazz) :: (method ARGNAMES))
+        }
+      }
     }
+    
+    def hashCodeTarget: Name = nme.hashCode_
+      // if (settings.Yjenkins.value) "hashCodeJenkins" else nme.hashCode_
 
-    def equalsSym = 
-      syntheticMethod(nme.equals_, 0, MethodType(List(AnyClass.tpe), BooleanClass.tpe))
+    def equalsSym = syntheticMethod(
+      nme.equals_, 0, makeTypeConstructor(List(AnyClass.tpe), BooleanClass.tpe)
+    )
 
     /** The equality method for case modules:
      *   def equals(that: Any) = this eq that
      */
-    def equalsModuleMethod: Tree = {
+    def equalsModuleMethod: Tree = localTyper typed {
       val method = equalsSym
-      val methodDef = 
-        DefDef(method, vparamss =>
-          Apply(
-            Select(This(clazz), Object_eq), 
-            List(
-              TypeApply(
-                Select(
-                  Ident(vparamss.head.head),
-                  Any_asInstanceOf),
-                List(TypeTree(AnyRefClass.tpe))))))
-      localTyper.typed(methodDef)
+      val that = method ARG 0
+      
+      localTyper typed {
+        DEF(method) === { 
+          (This(clazz) DOT Object_eq)(that AS AnyRefClass.tpe)
+        }
+      }
+    }
+    
+    /** The canEqual method for case classes.  Note that if we spot
+     *  a user-supplied equals implementation, we simply return true
+     *  so as not to interfere.
+     */
+    def canEqualMethod: Tree = {
+      val method  = syntheticMethod(nme.canEqual_, 0, makeTypeConstructor(List(AnyClass.tpe), BooleanClass.tpe))
+      val that    = method ARG 0
+      
+      typer typed (DEF(method) === (that IS_OBJ clazz.tpe))
     }
 
-    /** The equality method for case classes:
+    /** The equality method for case classes.  The argument is an Any,
+     *  but because of boxing it will always be an Object, so a check
+     *  is neither necessary nor useful before the cast.
+     *
      *   def equals(that: Any) = 
-     *     that.isInstanceOf[AnyRef] &&
-     *     ((this eq that.asInstanceOf[AnyRef]) || 
+     *     (this eq that.asInstanceOf[AnyRef]) || 
      *     (that match {
-     *       case this.C(this.arg_1, ..., this.arg_n) => true
-     *       case _ => false
-     *     }))
+     *       case x @ this.C(this.arg_1, ..., this.arg_n) => x canEqual this  
+     *       case _                                       => false
+     *     })
      */
     def equalsClassMethod: Tree = {
       val method = equalsSym
-      val methodDef = 
-        DefDef(
-          method, 
-          { vparamss =>
-            val that = Ident(vparamss.head.head)
-            val constrParamTypes = clazz.primaryConstructor.tpe.paramTypes
-            val hasVarArgs = !constrParamTypes.isEmpty && constrParamTypes.last.typeSymbol == RepeatedParamClass
-            if (false && clazz.isStatic) {
-              // todo: elim
-              val target = getMember(ScalaRunTimeModule, if (hasVarArgs) nme._equalsWithVarArgs else nme._equals)
-              Apply(
-                Select(
-                  TypeApply(
-                    Select(that, Any_isInstanceOf),
-                    List(TypeTree(clazz.tpe))),
-                  Boolean_and),
-                List(
-                  Apply(gen.mkAttributedRef(target),
-                        This(clazz) :: (vparamss.head map Ident))))
-            } else {
-              val (pat, guard) = {
-                val guards = new ListBuffer[Tree]
-                val params = for ((acc, cpt) <- clazz.caseFieldAccessors zip constrParamTypes) yield { 
-                  val name = context.unit.fresh.newName(clazz.pos, acc.name+"$")
-                  val isVarArg = cpt.typeSymbol == RepeatedParamClass 
-                  guards += Apply(
-                    Select(
-                      Ident(name),
-                      if (isVarArg) nme.sameElements else nme.EQ),
-                    List(Ident(acc)))
-                  Bind(name, 
-                       if (isVarArg) Star(Ident(nme.WILDCARD))
-                       else Ident(nme.WILDCARD))
-                }
-                ( Apply(Ident(clazz.name.toTermName), params),
-                  if (guards.isEmpty) EmptyTree
-                  else guards reduceLeft { (g1: Tree, g2: Tree) =>
-                    Apply(Select(g1, nme.AMPAMP), List(g2))
-                  }
-                )
-              }
-              val isAnyRef = TypeApply(
-                    Select(that, Any_isInstanceOf),
-                    List(TypeTree(AnyRefClass.tpe)))
-              val cast = TypeApply(
-                    Select(that, Any_asInstanceOf),
-                    List(TypeTree(AnyRefClass.tpe)))
-              val eq_ = Apply(Select( This(clazz) , nme.eq), List(that setType AnyRefClass.tpe)) 
-              val match_ = Match(that, List(
-                    CaseDef(pat, guard, Literal(Constant(true))),
-                    CaseDef(Ident(nme.WILDCARD), EmptyTree, Literal(Constant(false)))))
-              Apply(
-                    Select(isAnyRef, Boolean_and),
-                    List(Apply(Select(eq_, Boolean_or),
-                    List(match_))))
-            }
-          }
-        )
-      localTyper.typed(methodDef)
+      val that = method ARG 0
+      val constrParamTypes = clazz.primaryConstructor.tpe.paramTypes
+      
+      // returns (Apply, Bind)
+      def makeTrees(acc: Symbol, cpt: Type): (Tree, Bind) = {
+        val varName     = context.unit.fresh.newName(clazz.pos.focus, acc.name + "$")
+        val isRepeated  = isRepeatedParamType(cpt)
+        val binding     = if (isRepeated) Star(WILD()) else WILD()
+        val eqMethod: Tree  =
+          if (isRepeated) gen.mkRuntimeCall(nme.sameElements, List(Ident(varName), Ident(acc)))
+          else (varName DOT nme.EQ)(Ident(acc))
+
+        (eqMethod, varName BIND binding)
+      }
+      
+      // Creates list of parameters and a guard for each
+      val (guards, params) = (clazz.caseFieldAccessors, constrParamTypes).zipped map makeTrees unzip
+
+      // Verify with canEqual method before returning true.
+      def canEqualCheck() = {
+        val that: Tree              = typer typed ((method ARG 0) AS clazz.tpe)
+        val canEqualOther: Symbol   = clazz.info nonPrivateMember nme.canEqual_
+        
+        (that DOT canEqualOther)(This(clazz))
+      }
+        
+      // Pattern is classname applied to parameters, and guards are all logical and-ed
+      val (guard, pat) = (AND(guards: _*), clazz.name.toTermName APPLY params)
+      
+      localTyper typed {
+        DEF(method) === {
+          (This(clazz) ANY_EQ that) OR (that MATCH(
+            (CASE(pat) IF guard)  ==> canEqualCheck()        ,
+            DEFAULT               ==> FALSE
+          ))
+        }
+      }
     }
 
-    def isSerializable(clazz: Symbol): Boolean =
-      !clazz.getAttributes(definitions.SerializableAttr).isEmpty
+    def hasSerializableAnnotation(clazz: Symbol) =
+      clazz hasAnnotation SerializableAttr
 
     def readResolveMethod: Tree = {
-      // !!! the synthetic method "readResolve" should be private,
-      // but then it is renamed !!!
-      val method = newSyntheticMethod(nme.readResolve, PROTECTED,
-                                      MethodType(List(), ObjectClass.tpe))
-      typer.typed(DefDef(method, vparamss => gen.mkAttributedRef(clazz.sourceModule)))
+      // !!! the synthetic method "readResolve" should be private, but then it is renamed !!!
+      val method = newSyntheticMethod(nme.readResolve, PROTECTED, makeNoArgConstructor(ObjectClass.tpe))
+      typer typed (DEF(method) === REF(clazz.sourceModule))
     }
 
     def newAccessorMethod(tree: Tree): Tree = tree match {
       case DefDef(_, _, _, _, _, rhs) =>
         var newAcc = tree.symbol.cloneSymbol
-        newAcc.name = context.unit.fresh.newName(tree.symbol.pos, tree.symbol.name + "$")
-        newAcc.setFlag(SYNTHETIC).resetFlag(ACCESSOR | PARAMACCESSOR | PRIVATE)
+        newAcc.name = context.unit.fresh.newName(tree.symbol.pos.focus, tree.symbol.name + "$")
+        newAcc setFlag SYNTHETIC resetFlag (ACCESSOR | PARAMACCESSOR | PRIVATE)
+        newAcc.privateWithin = NoSymbol
         newAcc = newAcc.owner.info.decls enter newAcc
-        val result = typer.typed(DefDef(newAcc, vparamss => rhs.duplicate))
+        val result = typer typed { DEF(newAcc) === rhs.duplicate }
         log("new accessor method " + result)
         result
     }
 
-    def beanSetterOrGetter(sym: Symbol): Symbol =
-      if (!sym.name(0).isLetter) {
-        context.unit.error(sym.pos, "attribute `BeanProperty' can be applied only to fields that start with a letter")
-        NoSymbol
-      } else {
-        var name0 = sym.name
-        if (sym.isSetter) name0 = nme.setterToGetter(name0)
-        val prefix = if (sym.isSetter) "set" else
-          if (sym.tpe.resultType == BooleanClass.tpe) "is" else "get"
-        val arity = if (sym.isSetter) 1 else 0
-        val name1 = prefix + name0(0).toUpperCase + name0.subName(1, name0.length)
-        val sym1 = clazz.info.decl(name1)
-        if (sym1 != NoSymbol && sym1.tpe.paramTypes.length == arity) {
-          context.unit.error(sym.pos, "a definition of `"+name1+"' already exists in " + clazz)
-          NoSymbol
-        } else {
-          clazz.newMethod(sym.pos, name1)
-            .setInfo(sym.info)
-            .setFlag(sym.getFlag(DEFERRED | OVERRIDE | STATIC))
-        }
-      }
-
     val ts = new ListBuffer[Tree]
 
-    def addBeanGetterMethod(sym: Symbol) = {
-      val getter = beanSetterOrGetter(sym)
-      if (getter != NoSymbol) {
-        clazz.info.decls.enter(getter)
-        ts += typer.typed(DefDef(
-          getter,
-          vparamss => if (sym hasFlag DEFERRED) EmptyTree else gen.mkAttributedRef(sym)))
-      }
-    }
-
-    def addBeanSetterMethod(sym: Symbol) = {
-      val setter = beanSetterOrGetter(sym)
-      if (setter != NoSymbol) {
-        clazz.info.decls.enter(setter)
-        ts += typer.typed(DefDef(
-          setter,
-          vparamss =>
-            if (sym hasFlag DEFERRED) EmptyTree 
-            else Apply(gen.mkAttributedRef(sym), List(Ident(vparamss.head.head)))))
-      }
-    }
-
-    def isPublic(sym: Symbol) = 
-      !sym.hasFlag(PRIVATE | PROTECTED) && sym.privateWithin == NoSymbol
-
-    if (!phase.erasedTypes) {
-      try {
-        if (clazz hasFlag CASE) {
-          val isTop = !(clazz.info.baseClasses.tail exists (_ hasFlag CASE))
-          // case classes are implicitly declared serializable
-          clazz.attributes = AnnotationInfo(SerializableAttr.tpe, List(), List()) :: clazz.attributes
+    if (!phase.erasedTypes) try {
+      if (clazz hasFlag Flags.CASE) {
+        val isTop = !(clazz.ancestors exists (_ hasFlag Flags.CASE))
+        // case classes are implicitly declared serializable
+        clazz addAnnotation AnnotationInfo(SerializableAttr.tpe, Nil, Nil)
 
-          if (isTop) {
-            for (stat <- templ.body) {
-              if (stat.isDef && stat.symbol.isMethod && stat.symbol.hasFlag(CASEACCESSOR) && !isPublic(stat.symbol)) {
-                ts += newAccessorMethod(stat)
-                stat.symbol.resetFlag(CASEACCESSOR)
-              }
-            }
-            if (!inIDE && !clazz.hasFlag(INTERFACE) && clazz.info.nonPrivateDecl(nme.tag) == NoSymbol) ts += tagMethod
+        if (isTop) {
+          // If this case class has fields with less than public visibility, their getter at this
+          // point also has those permissions.  In that case we create a new, public accessor method
+          // with a new name and remove the CASEACCESSOR flag from the existing getter.  This complicates
+          // the retrieval of the case field accessors (see def caseFieldAccessors in Symbols.)
+          def needsService(s: Symbol) = s.isMethod && (s hasFlag CASEACCESSOR) && !s.isPublic
+          for (stat <- templ.body ; if stat.isDef && needsService(stat.symbol)) {
+            ts += newAccessorMethod(stat)
+            stat.symbol resetFlag CASEACCESSOR
           }
-          if (clazz.isModuleClass) {
-            if (!hasOverridingImplementation(Object_toString)) ts += moduleToStringMethod
-            // if there's a synthetic method in a parent case class, override its equality
-            // with eq (see #883)
-            val otherEquals = clazz.info.nonPrivateMember(Object_equals.name) 
-            if (otherEquals.owner != clazz && (otherEquals hasFlag SYNTHETICMETH)) ts += equalsModuleMethod
-          } else {
-            if (!hasOverridingImplementation(Object_hashCode)) ts += forwardingMethod(nme.hashCode_)
-            if (!hasOverridingImplementation(Object_toString)) ts += forwardingMethod(nme.toString_)
-            if (!hasOverridingImplementation(Object_equals)) ts += equalsClassMethod
-          }
-
-          if (!hasOverridingImplementation(Product_productPrefix)) ts += productPrefixMethod
+        }
+        
+        // methods for case classes only
+        def classMethods = List(
+          Object_hashCode -> (() => forwardingMethod(nme.hashCode_, "_" + hashCodeTarget)),
+          Object_toString -> (() => forwardingMethod(nme.toString_, "_" + nme.toString_)),
+          Object_equals   -> (() => equalsClassMethod)
+        )
+        // methods for case objects only
+        def objectMethods = List(
+          Object_toString -> (() => moduleToStringMethod)
+        )
+        // methods for both classes and objects
+        def everywhereMethods = {
           val accessors = clazz.caseFieldAccessors
-          if (!hasOverridingImplementation(Product_productArity))
-            ts += productArityMethod(accessors.length)
-          if (!hasOverridingImplementation(Product_productElement))
-            ts += productElementMethod(accessors)
+          List(
+            Product_productPrefix   -> (() => productPrefixMethod),
+            Product_productArity    -> (() => productArityMethod(accessors.length)),
+            Product_productElement  -> (() => productElementMethod(accessors)),
+            // This is disabled pending a reimplementation which doesn't add any
+            // weight to case classes (i.e. inspects the bytecode.)
+            // Product_productElementName  -> (() => productElementNameMethod(accessors)),
+            Product_canEqual        -> (() => canEqualMethod)
+          )
         }
 
-        if (clazz.isModuleClass && isSerializable(clazz)) {
-          // If you serialize a singleton and then deserialize it twice,
-          // you will have two instances of your singleton, unless you implement
-          // the readResolve() method (see http://www.javaworld.com/javaworld/
-          // jw-04-2003/jw-0425-designpatterns_p.html)
-          if (!hasImplementation(nme.readResolve)) ts += readResolveMethod
+        if (clazz.isModuleClass) {
+          // if there's a synthetic method in a parent case class, override its equality
+          // with eq (see #883)
+          val otherEquals = clazz.info.nonPrivateMember(Object_equals.name) 
+          if (otherEquals.owner != clazz && (otherEquals hasFlag SYNTHETICMETH)) ts += equalsModuleMethod
         }
-        if (!forCLDC && !forMSIL)
-          for (sym <- clazz.info.decls.toList)
-            if (!sym.getAttributes(BeanPropertyAttr).isEmpty)
-              if (sym.isGetter)
-                addBeanGetterMethod(sym)
-              else if (sym.isSetter)
-                addBeanSetterMethod(sym)
-              else if (sym.isMethod || sym.isType)
-                context.unit.error(sym.pos, "attribute `BeanProperty' is not applicable to " + sym)
-      } catch {
-        case ex: TypeError =>
-          if (!reporter.hasErrors) throw ex
+
+        val methods = (if (clazz.isModuleClass) objectMethods else classMethods) ++ everywhereMethods
+        for ((m, impl) <- methods ; if !hasOverridingImplementation(m))
+          ts += impl()
+      }
+
+      if (clazz.isModuleClass) {
+        if (!hasSerializableAnnotation(clazz)) {
+          val comp = companionClassOf(clazz, context)
+          if (comp.hasFlag(Flags.CASE) || hasSerializableAnnotation(comp))
+            clazz addAnnotation AnnotationInfo(SerializableAttr.tpe, Nil, Nil)
+        }
+
+        /** If you serialize a singleton and then deserialize it twice,
+         *  you will have two instances of your singleton, unless you implement
+         *  the readResolve() method (see http://www.javaworld.com/javaworld/
+         *  jw-04-2003/jw-0425-designpatterns_p.html)
+         */
+        if (hasSerializableAnnotation(clazz) && !hasImplementation(nme.readResolve))
+          ts += readResolveMethod
       }
+    } catch {
+      case ex: TypeError =>
+        if (!reporter.hasErrors) throw ex
     }
+    
     val synthetics = ts.toList
-    copy.Template(
+    treeCopy.Template(
       templ, templ.parents, templ.self, if (synthetics.isEmpty) templ.body else templ.body ::: synthetics)
   }
 }
diff --git a/src/compiler/scala/tools/nsc/typechecker/TreeCheckers.scala b/src/compiler/scala/tools/nsc/typechecker/TreeCheckers.scala
index e3300a0..ad34b2b 100644
--- a/src/compiler/scala/tools/nsc/typechecker/TreeCheckers.scala
+++ b/src/compiler/scala/tools/nsc/typechecker/TreeCheckers.scala
@@ -1,13 +1,12 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: TreeCheckers.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.tools.nsc.typechecker
+package scala.tools.nsc
+package typechecker
 
 import scala.tools.nsc.symtab.Flags._
-import scala.tools.nsc.util.{Position, NoPosition}
 
 abstract class TreeCheckers extends Analyzer {
 
@@ -41,7 +40,6 @@ abstract class TreeCheckers extends Analyzer {
   override def newTyper(context: Context): Typer = new TreeChecker(context)
 
   class TreeChecker(context0: Context) extends Typer(context0) {
-
     import infer._
 
     override def typed(tree: Tree, mode: Int, pt: Type): Tree = {
@@ -49,104 +47,80 @@ abstract class TreeCheckers extends Analyzer {
         case EmptyTree | TypeTree() =>
           ;
         case _ =>
-          try {
-            if (!tpeOfTree.contains(tree)) {
-              tpeOfTree.update(tree, tree.tpe)
-              tree.tpe = null
-            }
-            val newtree = super.typed(tree, mode, pt);
-            if ((newtree ne tree) && !newtree.isInstanceOf[Literal])
-              error(tree.pos, "trees differ\n old: " + tree + " [" + tree.getClass() +
-                    "]\n new: " + newtree + " [" + newtree.getClass() + "]")
-          } catch {
-            case ex: Throwable =>
-              Console.println("exception while typing "+tree)
-              throw ex
+          if (!tpeOfTree.contains(tree)) {
+            tpeOfTree.update(tree, tree.tpe)
+            tree.tpe = null
           }
+          val newtree = super.typed(tree, mode, pt);
+          if ((newtree ne tree) && !newtree.isInstanceOf[Literal])
+            error(tree.pos, "trees differ\n old: " + tree + " [" + tree.getClass() +
+                  "]\n new: " + newtree + " [" + newtree.getClass() + "]")
       }
       tree
     }
 
     object precheck extends Traverser {
       override def traverse(tree: Tree) {
-        try {
-          tree match {
-            case DefDef(_, _, _, _, _, _) =>
-              if (tree.symbol.hasFlag(ACCESSOR) && 
-                  !tree.symbol.isDeferred &&
-                  !tree.symbol.tpe.resultType.isInstanceOf[ConstantType]) {
-                assert(tree.symbol.accessed != NoSymbol, tree.symbol)
-                assert(tree.symbol.accessed.getter(tree.symbol.owner) == tree.symbol ||
-                       tree.symbol.accessed.setter(tree.symbol.owner) == tree.symbol)
-              }
-            case ValDef(_, _, _, _) =>
-              if (tree.symbol.hasGetter) {
-                assert(tree.symbol.getter(tree.symbol.owner) != NoSymbol, tree.symbol)
-              }
-            case Apply(_, args) =>
-              assert(args forall (EmptyTree !=))
-            case Select(_, _) =>
-              assert(tree.symbol != NoSymbol, tree)
-            case This(_) =>
-              if (!(tree.symbol.isStatic && (tree.symbol hasFlag MODULE))) {
-                var o = currentOwner
-                while (o != tree.symbol) {
-                  o = o.owner
-                  if (o == NoSymbol) {
-                    error(tree.pos, "tree symbol "+tree.symbol+" does not point to enclosing class; tree = "+tree)
-                    return
-                  }
-                }
+        tree match {
+          case DefDef(_, _, _, _, _, _) =>
+            if (tree.symbol.hasFlag(ACCESSOR) && 
+                !tree.symbol.isDeferred &&
+                !tree.symbol.tpe.resultType.isInstanceOf[ConstantType]) {
+              assert(tree.symbol.accessed != NoSymbol, tree.symbol)
+              assert(tree.symbol.accessed.getter(tree.symbol.owner) == tree.symbol ||
+                     tree.symbol.accessed.setter(tree.symbol.owner) == tree.symbol)
+            }
+          case ValDef(_, _, _, _) =>
+            if (tree.symbol.hasGetter) {
+              assert(tree.symbol.getter(tree.symbol.owner) != NoSymbol, tree.symbol)
+            }
+          case Apply(_, args) =>
+            assert(args forall (EmptyTree !=))
+          case Select(_, _) =>
+            assert(tree.symbol != NoSymbol, tree)
+          case This(_) =>
+            if (!(tree.symbol.isStatic && (tree.symbol hasFlag MODULE))) {
+              if (currentOwner.ownerChain takeWhile (_ != tree.symbol) exists (_ == NoSymbol)) {
+                error(tree.pos, "tree symbol "+tree.symbol+" does not point to enclosing class; tree = "+tree)
+                return
               }
-            case _ =>
-          }
-          if (tree.pos == NoPosition && tree != EmptyTree) {
-            error(tree.pos, "tree without position: " + tree)
-          } else if ((tree.tpe eq null) && phase.id >= currentRun.typerPhase.id) {
-            error(tree.pos, "tree without type: " + tree)
-          } else if (tree.isDef && tree.symbol.owner != currentOwner) {
-            var owner = currentOwner
-            while (owner.isTerm && !owner.isMethod && tree.symbol.owner != owner)
-              owner = owner.owner;
-            if (tree.symbol.owner != owner) {
-              error(tree.pos, "" + tree.symbol + " has wrong owner: " + tree.symbol.owner +
-                    tree.symbol.owner.locationString + ", should be: " +
-                    currentOwner + currentOwner.locationString)
             }
-          } else {
-            super.traverse(tree)
+          case _ =>
+        }
+        if (tree.pos == NoPosition && tree != EmptyTree) {
+          error(tree.pos, "tree without position: " + tree)
+        } else if ((tree.tpe eq null) && phase.id >= currentRun.typerPhase.id) {
+          error(tree.pos, "tree without type: " + tree)
+        } else if (tree.isDef && tree.symbol.owner != currentOwner) {
+          var owner = currentOwner
+          while (owner.isTerm && !owner.isMethod && tree.symbol.owner != owner)
+            owner = owner.owner;
+          if (tree.symbol.owner != owner) {
+            error(tree.pos, "" + tree.symbol + " has wrong owner: " + tree.symbol.owner +
+                  tree.symbol.owner.locationString + ", should be: " +
+                  currentOwner + currentOwner.locationString)
           }
-        } catch {
-          case ex: Throwable =>
-            if (settings.debug.value)
-              Console.println("exception when traversing " + tree);
-            throw(ex)
+        } else {
+          super.traverse(tree)
         }
       }
     }
 
     object postcheck extends Traverser {
       override def traverse(tree: Tree) {
-        try {
-          tree match {
-            case EmptyTree | TypeTree() =>
-              ;
-            case _ =>
-              tpeOfTree.get(tree) match {
-                case Some(oldtpe) =>
-                  if (!(oldtpe =:= tree.tpe))
-                    error(tree.pos, "types differ\n old: " + oldtpe +
-                          "\n new: " + tree.tpe + "\n tree: " + tree)
-                  tree.tpe = oldtpe
-                  super.traverse(tree)
-                case None =>
-              }
-          }
-        } catch {
-          case ex: Throwable =>
-            if (settings.debug.value)
-              Console.println("exception when traversing " + tree);
-            throw(ex)
+        tree match {
+          case EmptyTree | TypeTree() =>
+            ;
+          case _ =>
+            tpeOfTree.get(tree) match {
+              case Some(oldtpe) =>
+                if (!(oldtpe =:= tree.tpe))
+                  error(tree.pos, "types differ\n old: " + oldtpe +
+                        "\n new: " + tree.tpe + "\n tree: " + tree)
+                tree.tpe = oldtpe
+                super.traverse(tree)
+              case None =>
+            }
         }
       }
     }
diff --git a/src/compiler/scala/tools/nsc/typechecker/TypeDiagnostics.scala b/src/compiler/scala/tools/nsc/typechecker/TypeDiagnostics.scala
new file mode 100644
index 0000000..3291ca4
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/typechecker/TypeDiagnostics.scala
@@ -0,0 +1,268 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
+ * @author  Paul Phillips
+ */
+
+package scala.tools.nsc
+package typechecker
+
+import scala.collection.mutable
+import scala.collection.mutable.ListBuffer
+import scala.util.control.ControlThrowable
+import scala.util.control.Exception.ultimately
+import symtab.Flags._
+import PartialFunction._
+
+/** An interface to enable higher configurability of diagnostic messages
+ *  regarding type errors.  This is barely a beginning as error messages are
+ *  distributed far and wide across the codebase.  The plan is to partition
+ *  error messages into some broad groups and provide some mechanism for
+ *  being more or less verbose on a selective basis.  Possible groups include
+ *  such examples as
+ * 
+ *    arity errors
+ *    kind errors
+ *    variance errors
+ *    ambiguity errors
+ *    volatility/stability errors
+ *    implementation restrictions
+ *
+ *  And more, and there is plenty of overlap, so it'll be a process.
+ *
+ *  @author Paul Phillips
+ *  @version 1.0
+ */
+trait TypeDiagnostics {
+  self: Analyzer =>
+
+  import global._
+  import definitions._
+  import global.typer.infer
+  
+  /** It can be quite difficult to know which of the many functions called "error"
+   *  is being called at any given point in the compiler.  To alleviate this I am
+   *  renaming such functions inside this trait based on where it originated.
+   */
+  def inferError(pos: Position, msg: String) = infer.error(pos, msg)
+  
+  /** The common situation of making sure nothing is erroneous could be
+   *  nicer if Symbols, Types, and Trees all implemented some common interface
+   *  in which isErroneous and similar would be placed.
+   */
+  def noErroneousTypes(tps: Type*)    = tps forall (x => !x.isErroneous)
+  def noErroneousSyms(syms: Symbol*)  = syms forall (x => !x.isErroneous)
+  def noErroneousTrees(trees: Tree*)  = trees forall (x => !x.isErroneous)
+  
+  /** A map of Positions to addendums - if an error involves a position in
+   *  the map, the addendum should also be printed.
+   */
+  private var addendums = mutable.Map[Position, () => String]()
+
+  def setAddendum(pos: Position, msg: () => String) =
+    if (pos != NoPosition)
+      addendums(pos) = msg
+
+  def withAddendum(pos: Position) = (_: String) + addendums.getOrElse(pos, () => "")()
+
+  def decodeWithNamespace(name: Name): String = {
+    val prefix = if (name.isTypeName) "type " else "value "
+    prefix + name.decode
+  }
+  
+  /** Does the positioned line assigned to t1 precede that of t2?
+   */
+  def linePrecedes(t1: Tree, t2: Tree) = t1.pos.isDefined && t1.pos.isDefined && t1.pos.line < t2.pos.line
+  
+  def notAMember(sel: Tree, qual: Tree, name: Name) = {
+    def decoded = decodeWithNamespace(name)
+    
+    def msg: String = name match {
+      case nme.CONSTRUCTOR    => qual.tpe.widen+" does not have a constructor"
+      case _                  =>
+        def memberOf = if (qual.tpe.typeSymbol.isTypeParameterOrSkolem) "type parameter " else ""
+        def possibleCause =
+          if (linePrecedes(qual, sel))
+            "\npossible cause: maybe a semicolon is missing before `"+decoded+"'?"
+          else
+            ""
+        
+        decoded+" is not a member of "+ memberOf + qual.tpe.widen + possibleCause
+    }
+    inferError(sel.pos, withAddendum(qual.pos)(msg))
+  }
+  
+  /** Only prints the parameter names if they're not synthetic,
+   *  since "x$1: Int" does not offer any more information than "Int".
+   */
+  private def methodTypeErrorString(tp: Type) = tp match {
+    case mt @ MethodType(params, resultType)  =>
+      def forString = 
+        if (params exists (_.isSynthetic)) params map (_.tpe)
+        else params map (_.defString)
+                  
+       forString.mkString("(", ",", ")") + resultType
+    case x                                    => x.toString
+  }
+
+  def alternatives(tree: Tree): List[Type] = tree.tpe match {
+    case OverloadedType(pre, alternatives)  => alternatives map pre.memberType
+    case _                                  => Nil
+  }
+  def alternativesString(tree: Tree) =
+    alternatives(tree) map (x => "  " + methodTypeErrorString(x)) mkString ("", " <and>\n", "\n")
+
+  def missingParameterTypeError(fun: Tree, vparam: ValDef) = {
+    val suffix = if (vparam.mods.isSynthetic) " for expanded function "+fun else ""
+    
+    inferError(vparam.pos, "missing parameter type" + suffix)
+    ErrorType
+  }
+  
+  def treeSymTypeMsg(tree: Tree): String = {
+    val sym               = tree.symbol
+    def hasParams         = tree.tpe.paramSectionCount > 0    
+    def preResultString   = if (hasParams) ": " else " of type "
+
+    def nullMessage       = "expression of type " + tree.tpe
+    def overloadedMessage = "overloaded method " + sym + " with alternatives:\n" + alternativesString(tree)
+    def moduleMessage     = "" + sym
+    def defaultMessage    = moduleMessage + preResultString + tree.tpe
+    def applyMessage      = defaultMessage + tree.symbol.locationString
+
+    if (sym == null) nullMessage
+    else if (sym.isOverloaded) overloadedMessage
+    else if (sym.isModule) moduleMessage
+    else if (sym.name == nme.apply) applyMessage
+    else defaultMessage
+  }
+  
+  def applyErrorMsg(tree: Tree, msg: String, argtpes: List[Type], pt: Type) = {
+    def asParams(xs: List[Any]) = xs.mkString("(", ", ", ")")
+
+    def resType   = if (pt isWildcard) "" else " with expected result type " + pt
+    def allTypes  = (alternatives(tree) flatMap (_.paramTypes)) ++ argtpes :+ pt
+
+    withDisambiguation(allTypes: _*) {
+      treeSymTypeMsg(tree) + msg + asParams(argtpes) + resType
+    }
+  }
+  
+  def disambiguate(ss: List[String]) = ss match {
+    case Nil      => Nil
+    case s :: ss  => s :: (ss map { case `s` => "(some other)"+s ; case x => x })
+  }
+  
+  // todo: use also for other error messages
+  def existentialContext(tp: Type) = tp.existentialSkolems match {
+    case Nil  => ""
+    case xs   => " where " + (disambiguate(xs map (_.existentialToString)) mkString ", ")
+  }
+  
+  def foundReqMsg(found: Type, req: Type): String =
+    withDisambiguation(found, req) {
+      ";\n found   : " + found.toLongString + existentialContext(found) +
+       "\n required: " + req + existentialContext(req)
+    }
+
+  /** If two given types contain different type variables with the same name
+   *  differentiate the names by including owner information.  Also, if the
+   *  type error is because of a conflict between two identically named
+   *  classes and one is in package scala, fully qualify the name so one
+   *  need not deduce why "java.util.Iterator" and "Iterator" don't match.
+   *  Another disambiguation performed is to address the confusion present
+   *  in the following snippet:
+   *    def f[Int](x: Int) = x + 5.
+   */
+  def withDisambiguation[T](types: Type*)(op: => T): T = {
+    object SymExtractor {
+      def unapply(x: Any) = x match {
+        case t @ TypeRef(_, sym, _)   => Some(t -> sym)
+        case t @ ConstantType(value)  => Some(t -> t.underlying.typeSymbol)
+        case _                        => None
+      }
+    }
+    val typerefs =
+      for (tp <- types.toList ; SymExtractor(t, sym) <- tp) yield
+        t -> sym
+    
+    val savedNames    = typerefs map { case (_, sym) => sym -> sym.name } toMap
+    def restoreNames  = savedNames foreach { case (sym, name) => sym.name = name }
+
+    def isAlreadyAltered(sym: Symbol) = sym.name != savedNames(sym)
+    
+    def modifyName(sym: Symbol)(f: String => String): Unit =
+      sym.name = newTypeName(f(sym.name.toString))
+
+    def scalaQualify(sym: Symbol) =
+      if (sym.owner.isScalaPackageClass)
+        modifyName(sym)("scala." + _)
+
+    def explainName(sym: Symbol) = {
+      scalaQualify(sym)
+      
+      if (!isAlreadyAltered(sym))
+        modifyName(sym)(_ + "(in " + sym.owner + ")")
+    }
+
+    ultimately(restoreNames) {
+      for ((t1, sym1) <- typerefs ; (t2, sym2) <- typerefs ; if sym1 != sym2 && (sym1 isLess sym2)) {
+                
+        if (t1.toString == t2.toString) {   // type variable collisions
+          List(sym1, sym2) foreach explainName
+          if (sym1.owner == sym2.owner)
+            sym2.name = newTypeName("(some other)"+sym2.name)
+        }
+        else if (sym1.name == sym2.name) {  // symbol name collisions
+          List(sym1, sym2) foreach { x =>
+            if (x.owner.isScalaPackageClass)
+              modifyName(x)("scala." + _)
+            else if (x.isTypeParameterOrSkolem)
+              explainName(x)
+          }
+        }
+      }
+      
+      // performing the actual operation
+      op
+    }
+  }
+  
+  trait TyperDiagnostics {
+    self: Typer =>
+
+    private def contextError(pos: Position, msg: String) = context.error(pos, msg)
+    private def contextError(pos: Position, err: Throwable) = context.error(pos, err)
+    
+    def symWasOverloaded(sym: Symbol) = sym.owner.isClass && sym.owner.info.member(sym.name).isOverloaded
+    def cyclicAdjective(sym: Symbol)  = if (symWasOverloaded(sym)) "overloaded" else "recursive"
+    
+    /** Returns Some(msg) if the given tree is untyped apparently due
+     *  to a cyclic reference, and None otherwise.
+     */
+    def cyclicReferenceMessage(sym: Symbol, tree: Tree) = condOpt(tree) {      
+      case ValDef(_, _, tpt, _) if tpt.tpe == null        => "recursive "+sym+" needs type"
+      case DefDef(_, _, _, _, tpt, _) if tpt.tpe == null  => List(cyclicAdjective(sym), sym, "needs result type") mkString " "
+    }
+  
+    /** Report a type error.
+     *
+     *  @param pos0   The position where to report the error
+     *  @param ex     The exception that caused the error
+     */
+    def reportTypeError(pos: Position, ex: TypeError) {
+      if (ex.pos == NoPosition) ex.pos = pos
+      if (!context.reportGeneralErrors) throw ex
+      if (settings.debug.value) ex.printStackTrace()
+
+      ex match {
+        case CyclicReference(sym, info: TypeCompleter) =>
+          contextError(ex.pos, cyclicReferenceMessage(sym, info.tree) getOrElse ex.getMessage())
+          
+          if (sym == ObjectClass) 
+            throw new FatalError("cannot redefine root "+sym)
+        case _ =>
+          contextError(ex.pos, ex)
+      }
+    }
+  }
+}
diff --git a/src/compiler/scala/tools/nsc/typechecker/Typers.scala b/src/compiler/scala/tools/nsc/typechecker/Typers.scala
index 272cec7..62374ed 100644
--- a/src/compiler/scala/tools/nsc/typechecker/Typers.scala
+++ b/src/compiler/scala/tools/nsc/typechecker/Typers.scala
@@ -1,22 +1,25 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: Typers.scala 16881 2009-01-09 16:28:11Z cunei $
 
 //todo: rewrite or disllow new T where T is a mixin (currently: <init> not a member of T)
 //todo: use inherited type info also for vars and values
 //todo: disallow C#D in superclass
 //todo: treat :::= correctly
-package scala.tools.nsc.typechecker
+package scala.tools.nsc
+package typechecker
 
 import scala.collection.mutable.{HashMap, ListBuffer}
-import scala.compat.Platform.currentTime
-import scala.tools.nsc.util.{HashSet, Position, Set, NoPosition, SourceFile}
+import scala.util.control.ControlThrowable
+import scala.tools.nsc.interactive.RangePositions
+import scala.tools.nsc.util.{Set, SourceFile, BatchSourceFile}
 import symtab.Flags._
-import util.HashSet
+
+import util.Statistics
+import util.Statistics._
  
-// Suggestion check whether we can do without priminng scopes with symbols of outer scopes,
+// Suggestion check whether we can do without priming scopes with symbols of outer scopes,
 // like the IDE does. 
 /** This trait provides methods to assign types to trees.
  *
@@ -26,23 +29,20 @@ import util.HashSet
 trait Typers { self: Analyzer =>
   import global._
   import definitions._
-  import posAssigner.atPos
-
-  private final val printTypings = false
-
-  var appcnt = 0
-  var idcnt = 0
-  var selcnt = 0
-  var implcnt = 0
-  var impltime = 0l
 
+  // namer calls typer.computeType(rhs) on DefDef / ValDef when tpt is empty. the result
+  // is cached here and re-used in typedDefDef / typedValDef
   private val transformed = new HashMap[Tree, Tree]
 
+  // currently not used at all (March 09)
   private val superDefs = new HashMap[Symbol, ListBuffer[Tree]]
 
+  final val shortenImports = false
+
   def resetTyper() {
     resetContexts
     resetNamer()
+    resetImplicits()
     transformed.clear
     superDefs.clear
   }
@@ -54,15 +54,24 @@ trait Typers { self: Analyzer =>
       super.traverse(tree)
     }
   } 
+/* needed for experimental version where eraly types can be type arguments
+  class EarlyMap(clazz: Symbol) extends TypeMap {
+    def apply(tp: Type): Type = tp match {
+      case TypeRef(NoPrefix, sym, List()) if (sym hasFlag PRESUPER) =>
+        TypeRef(ThisType(clazz), sym, List())
+      case _ =>
+        mapOver(tp)
+    }
+  }
+*/
   // IDE hooks
   def newTyper(context: Context): Typer = new NormalTyper(context)
   private class NormalTyper(context : Context) extends Typer(context)
   // hooks for auto completion
 
-  /** when in 1.4 mode the compiler accepts and ignores useless
-   *  type parameters of Java generics
-   */
-  def onePointFourMode = true // todo changeto: settings.target.value == "jvm-1.4"
+  // A transient flag to mark members of anonymous classes
+  // that are turned private by typedBlock
+  private final val SYNTHETIC_PRIVATE = TRANS_FLAG
 
   // Mode constants
 
@@ -114,11 +123,11 @@ trait Typers { self: Analyzer =>
    *  assignment.
    */
   val LHSmode       = 0x400
-
-  /** The mode <code>REGPATmode</code> is set when regular expression patterns
-   *  are allowed. 
+  
+  /** The mode <code>STARmode</code> is set when star patterns are allowed.
+   *  (This was formerly called REGPATmode.)
    */
-  val REGPATmode    = 0x1000
+  val STARmode      = 0x1000
 
   /** The mode <code>ALTmode</code> is set when we are under a pattern alternative */
   val ALTmode       = 0x2000
@@ -129,11 +138,14 @@ trait Typers { self: Analyzer =>
    */
   val HKmode        = 0x4000 // @M: could also use POLYmode | TAPPmode 
 
-  /** The mode <code>JAVACALLmode</code> is set when we are typing a call to a Java method
-   *  needed temporarily for vararg conversions
-   *  !!!VARARG-CONVERSION!!!
+  /** The mode <code>BYVALmode</code> is set when we are typing an expression
+   *  that occurs in a by-value position. An expression e1 is in by-value
+   *  position within expression e2 iff it will be reduced to a value at that
+   *  position during the evaluation of e2. Examples are by-value function
+   *  arguments or the conditional of an if-then-else clause.
+   *  This mode has been added to support continuations.
    */
-  val JAVACALLmode  = 0x8000
+  val BYVALmode     = 0x8000
 
   /** The mode <code>TYPEPATmode</code> is set when we are typing a type in a pattern
    */
@@ -141,37 +153,95 @@ trait Typers { self: Analyzer =>
 
   private val stickyModes: Int  = EXPRmode | PATTERNmode | TYPEmode | ALTmode
 
-  private def funMode(mode: Int) = mode & (stickyModes | SCCmode) | FUNmode | POLYmode
+  private def funMode(mode: Int) = mode & (stickyModes | SCCmode) | FUNmode | POLYmode | BYVALmode
 
   private def typeMode(mode: Int) = 
     if ((mode & (PATTERNmode | TYPEPATmode)) != 0) TYPEmode | TYPEPATmode
     else TYPEmode
 
-  private def argMode(fun: Tree, mode: Int) =
-    if (treeInfo.isSelfOrSuperConstrCall(fun)) mode | SCCmode 
-    else if (fun.symbol hasFlag JAVA) mode | JAVACALLmode // !!!VARARG-CONVERSION!!!
-    else mode 
-
-  private val DivergentImplicit = new Exception()
+  private def argMode(fun: Tree, mode: Int) = {
+    if (treeInfo.isSelfOrSuperConstrCall(fun)) mode | SCCmode
+    else mode
+  }
 
-  abstract class Typer(context0: Context) {
+  abstract class Typer(context0: Context) extends TyperDiagnostics {
     import context0.unit
 
     val infer = new Inferencer(context0) {
       override def isCoercible(tp: Type, pt: Type): Boolean =
         tp.isError || pt.isError ||
         context0.implicitsEnabled && // this condition prevents chains of views
-        inferView(NoPosition, tp, pt, false) != EmptyTree
+        inferView(EmptyTree, tp, pt, false) != EmptyTree
     }
 
-    /**
-     *  @param pos             ...
-     *  @param from            ...
-     *  @param to              ...
-     *  @param reportAmbiguous ...
-     *  @return                ...
+    /** Find implicit arguments and pass them to given tree.
+     */
+    def applyImplicitArgs(fun: Tree): Tree = fun.tpe match {
+      case MethodType(params, _) =>
+        val argResultsBuff = new ListBuffer[SearchResult]()
+        val argBuff = new ListBuffer[Tree]()
+
+        def mkPositionalArg(argTree: Tree, paramName: Name) = argTree
+        def mkNamedArg(argTree: Tree, paramName: Name) = atPos(argTree.pos)(new AssignOrNamedArg(Ident(paramName), (argTree)))
+        var mkArg: (Tree, Name) => Tree = mkPositionalArg
+
+        def errorMessage(paramName: Name, paramTp: Type) =
+          paramTp.typeSymbol match {
+            case ImplicitNotFoundMsg(msg) => msg.format(paramName, paramTp)
+            case _ =>
+              "could not find implicit value for "+
+                 (if (paramName startsWith nme.EVIDENCE_PARAM_PREFIX) "evidence parameter of type "
+                  else "parameter "+paramName+": ")+paramTp  
+          }
+
+        // DEPMETTODO: instantiate type vars that depend on earlier implicit args (see adapt (4.1))
+        //
+        // apply the substitutions (undet type param -> type) that were determined
+        // by implicit resolution of implicit arguments on the left of this argument
+        for(param <- params) {
+          var paramTp = param.tpe
+          for(ar <- argResultsBuff)
+            paramTp = paramTp.subst(ar.subst.from, ar.subst.to)
+
+          val res = inferImplicit(fun, paramTp, true, false, context)
+          argResultsBuff += res
+
+          if (res != SearchFailure) {
+            argBuff += mkArg(res.tree, param.name)
+          } else {
+            mkArg = mkNamedArg // don't pass the default argument (if any) here, but start emitting named arguments for the following args
+            if (!param.hasFlag(DEFAULTPARAM))
+              context.error(fun.pos, errorMessage(param.name, param.tpe))
+            /* else {
+             TODO: alternative (to expose implicit search failure more) --> 
+             resolve argument, do type inference, keep emitting positional args, infer type params based on default value for arg
+             for (ar <- argResultsBuff) ar.subst traverse defaultVal
+             val targs = exprTypeArgs(context.undetparams, defaultVal.tpe, paramTp)
+             substExpr(tree, tparams, targs, pt)
+            }*/
+          }
+        }
+
+        val args = argBuff.toList
+        for (ar <- argResultsBuff) {
+          ar.subst traverse fun
+          for (arg <- args) ar.subst traverse arg
+        }
+
+        new ApplyToImplicitArgs(fun, args) setPos fun.pos
+      case ErrorType =>
+        fun
+    }
+
+    /** Infer an implicit conversion (``view'') between two types.
+     *  @param tree             The tree which needs to be converted.
+     *  @param from             The source type of the conversion
+     *  @param to               The target type of the conversion
+     *  @param reportAmbiguous  Should ambiguous implicit errors be reported?
+     *                          False iff we search for a view to find out
+     *                          whether one type is coercible to another.
      */
-    private def inferView(pos: Position, from: Type, to: Type, reportAmbiguous: Boolean): Tree = {
+    def inferView(tree: Tree, from: Type, to: Type, reportAmbiguous: Boolean): Tree = {
       if (settings.debug.value) log("infer view from "+from+" to "+to)//debug
       if (phase.id > currentRun.typerPhase.id) EmptyTree
       else from match {
@@ -179,32 +249,17 @@ trait Typers { self: Analyzer =>
         case OverloadedType(_, _) => EmptyTree
         case PolyType(_, _) => EmptyTree
         case _ =>
-          val result = inferImplicit(pos, MethodType(List(from), to), reportAmbiguous)
+          def wrapImplicit(from: Type): Tree = {
+            val result = inferImplicit(tree, functionType(List(from), to), reportAmbiguous, true, context)
+            if (result.subst != EmptyTreeTypeSubstituter) result.subst traverse tree
+            result.tree
+          }
+          val result = wrapImplicit(from)
           if (result != EmptyTree) result
-          else inferImplicit(
-            pos,
-            MethodType(List(appliedType(ByNameParamClass.typeConstructor, List(from))), to),
-            reportAmbiguous)
+          else wrapImplicit(appliedType(ByNameParamClass.typeConstructor, List(from)))
       }
     }
 
-    /**
-     *  @param pos             ...
-     *  @param from            ...
-     *  @param name            ...
-     *  @param tp              ...
-     *  @param reportAmbiguous ...
-     *  @return                ...
-     */
-    private def inferView(pos: Position, from: Type, name: Name, tp: Type, reportAmbiguous: Boolean): Tree = {
-      val to = refinedType(List(WildcardType), NoSymbol)
-      var psym = (if (name.isTypeName) to.typeSymbol.newAbstractType(pos, name) 
-                  else to.typeSymbol.newValue(pos, name)) 
-      psym = to.decls enter psym
-      psym setInfo tp
-      inferView(pos, from, to, reportAmbiguous)
-    }
-
     import infer._
 
     private var namerCache: Namer = null
@@ -217,35 +272,6 @@ trait Typers { self: Analyzer =>
     private[typechecker] var context = context0
     def context1 = context
 
-    /** Report a type error.
-     *
-     *  @param pos0   The position where to report the error
-     *  @param ex     The exception that caused the error
-     */
-    def reportTypeError(pos0: Position, ex: TypeError) {
-      if (settings.debug.value) ex.printStackTrace()
-      val pos = if (ex.pos == NoPosition) pos0 else ex.pos
-      ex match {
-        case CyclicReference(sym, info: TypeCompleter) =>
-          val msg = 
-            info.tree match {
-              case ValDef(_, _, tpt, _) if (tpt.tpe eq null) =>
-                "recursive "+sym+" needs type"
-              case DefDef(_, _, _, _, tpt, _) if (tpt.tpe eq null) =>
-                (if (sym.owner.isClass && sym.owner.info.member(sym.name).hasFlag(OVERLOADED)) "overloaded "
-                 else "recursive ")+sym+" needs result type"
-              case _ =>
-                ex.getMessage()
-            }
-          if (context.retyping) context.error(pos, msg) 
-          else context.unit.error(pos, msg)
-          if (sym == ObjectClass) 
-            throw new FatalError("cannot redefine root "+sym)
-        case _ =>
-          context.error(pos, ex)
-      }
-    }
-
     /** Check that <code>tree</code> is a stable expression.
      *
      *  @param tree ...
@@ -262,7 +288,7 @@ trait Typers { self: Analyzer =>
             case t => t
           }
           "\n Note that "+tree.symbol+" is not stable because its type, "+tree.tpe+", is volatile."
-         } else ""))
+      } else ""))
 
     /** Would tree be a stable (i.e. a pure expression) if the type
      *  of its symbol was not volatile?
@@ -273,7 +299,7 @@ trait Typers { self: Analyzer =>
         val savedSTABLE = tree.symbol getFlag STABLE
         tree.symbol setInfo AnyRefClass.tpe
         tree.symbol setFlag STABLE
-       val result = treeInfo.isPureExpr(tree)
+        val result = treeInfo.isPureExpr(tree)
         tree.symbol setInfo savedTpe
         tree.symbol setFlag savedSTABLE
         result
@@ -281,9 +307,11 @@ trait Typers { self: Analyzer =>
     }
 
     /** Check that `tpt' refers to a non-refinement class type */
-    def checkClassType(tpt: Tree, existentialOK: Boolean) {
+    def checkClassType(tpt: Tree, existentialOK: Boolean, stablePrefix: Boolean) {
       def check(tpe: Type): Unit = tpe.normalize match {
-        case TypeRef(_, sym, _) if sym.isClass && !sym.isRefinementClass => ;
+        case TypeRef(pre, sym, _) if sym.isClass && !sym.isRefinementClass => 
+          if (stablePrefix && phase.id <= currentRun.typerPhase.id && !pre.isStable)
+            error(tpt.pos, "type "+pre+" is not a stable prefix")
         case ErrorType => ;
         case PolyType(_, restpe) => check(restpe)
         case ExistentialType(_, restpe) if existentialOK => check(restpe)
@@ -302,12 +330,12 @@ trait Typers { self: Analyzer =>
     def checkNonCyclic(pos: Position, tp: Type): Boolean = {
       def checkNotLocked(sym: Symbol): Boolean = {
         sym.initialize
-	sym.lockOK || {error(pos, "cyclic aliasing or subtyping involving "+sym); false}
+        sym.lockOK || {error(pos, "cyclic aliasing or subtyping involving "+sym); false}
       }
       tp match {
         case TypeRef(pre, sym, args) =>
           (checkNotLocked(sym)) && (
-            !sym.isTypeMember ||
+            !sym.isNonClassType ||
             checkNonCyclic(pos, appliedType(pre.memberInfo(sym), args), sym)   // @M! info for a type ref to a type parameter now returns a polytype
             // @M was: checkNonCyclic(pos, pre.memberInfo(sym).subst(sym.typeParams, args), sym)
           )
@@ -356,21 +384,19 @@ trait Typers { self: Analyzer =>
           /*
           if (formals.exists(_.typeSymbol == ByNameParamClass) && formals.length != 1)
             error(pos, "methods with `=>'-parameter can be converted to function values only if they take no other parameters")
-          if (formals exists (_.typeSymbol == RepeatedParamClass))
+          if (formals exists (isRepeatedParamType(_)))
             error(pos, "methods with `*'-parameters cannot be converted to function values");
           */
           if (restpe.isDependent)
-            error(pos, "method with dependent type "+tpe+" cannot be converted to function value");
+            error(pos, "method with dependent type "+tpe+" cannot be converted to function value")
           checkParamsConvertible(pos, restpe)
         case _ =>
       }
     }
-
-    def checkRegPatOK(pos: Position, mode: Int) = 
-      if ((mode & REGPATmode) == 0 && 
-          phase.id <= currentRun.typerPhase.id) // fixes t1059
-        error(pos, "no regular expression pattern allowed here\n"+
-              "(regular expression patterns are only allowed in arguments to *-parameters)")
+    
+    def checkStarPatOK(pos: Position, mode: Int) = 
+      if ((mode & STARmode) == 0 && phase.id <= currentRun.typerPhase.id)
+        error(pos, "star patterns must correspond with varargs parameters")
 
     /** Check that type of given tree does not contain local or private
      *  components.
@@ -407,20 +433,20 @@ trait Typers { self: Analyzer =>
         this.scope = scope
         hiddenSymbols = List()
         val tp1 = apply(tree.tpe)
-        if (hiddenSymbols.isEmpty || inIDE) tree setType tp1 // @S: because arguments of classes are owned by the classes' owner
+        if (hiddenSymbols.isEmpty) tree setType tp1
         else if (hiddenSymbols exists (_.isErroneous)) setError(tree)
         else if (isFullyDefined(pt)) tree setType pt //todo: eliminate
         else if (tp1.typeSymbol.isAnonymousClass) // todo: eliminate
           check(owner, scope, pt, tree setType tp1.typeSymbol.classBound)
         else if (owner == NoSymbol)
           tree setType packSymbols(hiddenSymbols.reverse, tp1)
-        else { // privates
+        else if (!phase.erasedTypes) { // privates
           val badSymbol = hiddenSymbols.head
           error(tree.pos,
                 (if (badSymbol hasFlag PRIVATE) "private " else "") + badSymbol +
                 " escapes its defining scope as part of type "+tree.tpe)
           setError(tree)
-        }
+        } else tree
       }
 
       def addHidden(sym: Symbol) =
@@ -428,7 +454,7 @@ trait Typers { self: Analyzer =>
 
       override def apply(t: Type): Type = {
         def checkNoEscape(sym: Symbol) {
-          if (sym.hasFlag(PRIVATE)) {
+          if (sym.hasFlag(PRIVATE) && !sym.hasFlag(SYNTHETIC_PRIVATE)) {
             var o = owner
             while (o != NoSymbol && o != sym.owner && 
                    !o.isLocal && !o.hasFlag(PRIVATE) &&
@@ -436,7 +462,7 @@ trait Typers { self: Analyzer =>
               o = o.owner
             if (o == sym.owner) addHidden(sym)
           } else if (sym.owner.isTerm && !sym.isTypeParameterOrSkolem) {
-            var e = scope.lookupEntryWithContext(sym.name)(context.owner)
+            var e = scope.lookupEntry(sym.name)
             var found = false
             while (!found && (e ne null) && e.owner == scope) {
               if (e.sym == sym) {
@@ -478,43 +504,60 @@ trait Typers { self: Analyzer =>
         tparam.symbol.deSkolemize 
       } 
 
-    /** The qualifying class of a this or super with prefix <code>qual</code>.
-     *
-     *  @param tree ...
-     *  @param qual ...
-     *  @return     ...
+    /** The qualifying class
+     *  of a this or super with prefix <code>qual</code>.
      */
-    def qualifyingClassContext(tree: Tree, qual: Name): Context = {
-      if (qual.isEmpty) {
-        if (context.enclClass.owner.isPackageClass) 
-          error(tree.pos, tree+" can be used only in a class, object, or template")
-        context.enclClass
-      } else {
-        var c = context.enclClass
-        while (c != NoContext && c.owner.name != qual) c = c.outer.enclClass
-        if (c == NoContext) error(tree.pos, qual+" is not an enclosing class")
-        c
+    def qualifyingClass(tree: Tree, qual: Name, packageOK: Boolean): Symbol =
+      context.enclClass.owner.ownerChain.find(o => qual.isEmpty || o.isClass && o.name == qual) match {
+        case Some(c) if packageOK || !c.isPackageClass =>
+          c
+        case _ => 
+          error(
+            tree.pos, 
+            if (qual.isEmpty) tree+" can be used only in a class, object, or template"
+            else qual+" is not an enclosing class")
+          NoSymbol
       }
-    }
 
     /** The typer for an expression, depending on where we are. If we are before a superclass 
      *  call, this is a typer over a constructor context; otherwise it is the current typer.
      */  
     def constrTyperIf(inConstr: Boolean): Typer =  
-      if (inConstr) newTyper(context.makeConstructorContext) else this
+      if (inConstr) {
+        assert(context.undetparams.isEmpty)
+        newTyper(context.makeConstructorContext)
+      } else this
 
     /** The typer for a label definition. If this is part of a template we
      *  first have to enter the label definition.
      */
     def labelTyper(ldef: LabelDef): Typer = 
       if (ldef.symbol == NoSymbol) { // labeldef is part of template
-        val typer1 = newTyper(context.makeNewScope(ldef, context.owner)(LabelScopeKind))
+        val typer1 = newTyper(context.makeNewScope(ldef, context.owner))
         typer1.enterLabelDef(ldef)
         typer1
       } else this
 
     final val xtypes = false
 
+    /** Is symbol defined and not stale?
+     */
+    def reallyExists(sym: Symbol) = {
+      if (isStale(sym)) sym.setInfo(NoType)
+      sym.exists
+    }
+
+    /** A symbol is stale if it is toplevel, to be loaded from a classfile, and
+     *  the classfile is produced from a sourcefile which is compiled in the current run.
+     */
+    def isStale(sym: Symbol): Boolean = {
+      sym.rawInfo.isInstanceOf[loaders.ClassfileLoader] && {
+        sym.rawInfo.load(sym)
+        (sym.sourceFile ne null) &&
+        (currentRun.compiledFiles contains sym.sourceFile.path)
+      }
+    }
+
     /** Does the context of tree <code>tree</code> require a stable type?
      */
     private def isStableContext(tree: Tree, mode: Int, pt: Type) =  
@@ -522,24 +565,84 @@ trait Typers { self: Analyzer =>
       (xtypes ||
       (pt.isStable ||
        (mode & QUALmode) != 0 && !tree.symbol.isConstant ||
-       pt.typeSymbol.isAbstractType && pt.bounds.lo.isStable && !(tree.tpe <:< pt)))
-
-    /** <p>
-     *    Post-process an identifier or selection node, performing the following:
-     *  </p>
-     *  <ol>
-     *  <!--(1)--><li>Check that non-function pattern expressions are stable</li>
-     *  <!--(2)--><li>Check that packages and static modules are not used as values</li>
-     *  <!--(3)--><li>Turn tree type into stable type if possible and required by context.</li>
+       pt.typeSymbol.isAbstractType && pt.bounds.lo.isStable && !(tree.tpe <:< pt)) ||
+       pt.typeSymbol.isRefinementClass && !(tree.tpe <:< pt))
+
+    /** Make symbol accessible. This means:
+     *  If symbol refers to package object, insert `.package` as second to last selector.
+     *  (exception for some symbols in scala package which are dealiased immediately)
+     *  Call checkAccessible, which sets tree's attributes.
+     *  Also note that checkAccessible looks up sym on pre without checking that pre is well-formed 
+     *  (illegal type applications in pre will be skipped -- that's why typedSelect wraps the resulting tree in a TreeWithDeferredChecks)
+     *  @return modified tree and new prefix type
+     */
+    private def makeAccessible(tree: Tree, sym: Symbol, pre: Type, site: Tree): (Tree, Type) =
+      if (isInPackageObject(sym, pre.typeSymbol)) {
+        if (pre.typeSymbol == ScalaPackageClass && sym.isTerm) {
+          // short cut some aliases. It seems that without that pattern matching
+          // fails to notice exhaustiveness and to generate good code when
+          // List extractors are mixed with :: patterns. See Test5 in lists.scala.
+          def dealias(sym: Symbol) =
+            ({ val t = gen.mkAttributedRef(sym) ; t.setPos(tree.pos) ; t }, sym.owner.thisType)
+          sym.name match {
+            case nme.List => return dealias(ListModule)
+            case nme.Seq => return dealias(SeqModule)
+            case nme.Nil => return dealias(NilModule)
+            case _ =>
+          }
+        }
+        val qual = typedQualifier { atPos(tree.pos.focusStart) {
+          tree match {
+            case Ident(_) => Ident(nme.PACKAGEkw)
+            case Select(qual, _) => Select(qual, nme.PACKAGEkw)
+            case SelectFromTypeTree(qual, _) => Select(qual, nme.PACKAGEkw)
+          }
+        }}
+        val tree1 = atPos(tree.pos) {
+          tree match {
+            case Ident(name) => Select(qual, name)
+            case Select(_, name) => Select(qual, name)
+            case SelectFromTypeTree(_, name) => SelectFromTypeTree(qual, name)
+          }
+        }
+        (checkAccessible(tree1, sym, qual.tpe, qual), qual.tpe)
+      } else {
+        (checkAccessible(tree, sym, pre, site), pre)
+      }
+
+    /** Is `sym` defined in package object of package `pkg`?
+     */
+    private def isInPackageObject(sym: Symbol, pkg: Symbol) = 
+      pkg.isPackageClass && {
+        sym.alternatives forall { sym =>
+          !sym.owner.isPackage && {
+            sym.owner.isPackageObjectClass && 
+            sym.owner.owner == pkg ||
+            pkg.isInitialized && {
+              // need to be careful here to not get a cyclic reference during bootstrap
+              val pkgobj = pkg.info.member(nme.PACKAGEkw)
+              pkgobj.isInitialized &&
+              (pkgobj.info.member(sym.name).alternatives contains sym)
+            }
+          }
+        }
+      }
+
+    /** Post-process an identifier or selection node, performing the following:
+     *  1. Check that non-function pattern expressions are stable
+     *  2. Check that packages and static modules are not used as values
+     *  3. Turn tree type into stable type if possible and required by context.
      *  </ol>
      */
     private def stabilize(tree: Tree, pre: Type, mode: Int, pt: Type): Tree = {
       if (tree.symbol.hasFlag(OVERLOADED) && (mode & FUNmode) == 0)
         inferExprAlternative(tree, pt)
       val sym = tree.symbol
+      
       if (tree.tpe.isError) tree
       else if ((mode & (PATTERNmode | FUNmode)) == PATTERNmode && tree.isTerm) { // (1)
-        checkStable(tree)
+        if (sym.isValue) checkStable(tree)
+        else errorTree(tree, sym+" is not a value")
       } else if ((mode & (EXPRmode | QUALmode)) == EXPRmode && !sym.isValue && !phase.erasedTypes) { // (2)
         errorTree(tree, sym+" is not a value")
       } else {
@@ -585,41 +688,76 @@ trait Typers { self: Analyzer =>
         case Select(qual, _) => qual.tpe
         case _ => NoPrefix
       }
-      if (tree.tpe.isInstanceOf[MethodType] && pre.isStable && sym.tpe.paramTypes.isEmpty &&
+      if (tree.tpe.isInstanceOf[MethodType] && pre.isStable && sym.tpe.params.isEmpty &&
           (isStableContext(tree, mode, pt) || sym.isModule))
         tree.setType(MethodType(List(), singleType(pre, sym)))
       else tree
     }
 
     /** The member with given name of given qualifier tree */
-    def member(qual: Tree, name: Name)(from : Symbol) = qual.tpe match {
+    def member(qual: Tree, name: Name) = qual.tpe match {
       case ThisType(clazz) if (context.enclClass.owner.hasTransOwner(clazz)) =>
         qual.tpe.member(name)
       case _  =>
         if (phase.next.erasedTypes) qual.tpe.member(name)
-        else qual.tpe.nonLocalMember(name)(from)
+        else qual.tpe.nonLocalMember(name)
     }      
 
-    def silent(op: Typer => Tree): AnyRef /* in fact, TypeError or Tree */ = try {
-      if (context.reportGeneralErrors) {
-        val context1 = context.makeSilent(context.reportAmbiguousErrors)
-        context1.undetparams = context.undetparams
-        context1.savedTypeBounds = context.savedTypeBounds
-        val typer1 = newTyper(context1)
-        val result = op(typer1)
-        context.undetparams = context1.undetparams
-        context.savedTypeBounds = context1.savedTypeBounds
-        result
-      } else {
-        op(this)
+    def silent[T](op: Typer => T,
+                  reportAmbiguousErrors: Boolean = context.reportAmbiguousErrors,
+                  newtree: Tree = context.tree): Any /* in fact, TypeError or T */ = { 
+      val rawTypeStart = startCounter(rawTypeFailed)
+      val findMemberStart = startCounter(findMemberFailed)
+      val subtypeStart = startCounter(subtypeFailed)
+      val failedSilentStart = startTimer(failedSilentNanos)
+      try {
+        if (context.reportGeneralErrors ||  
+            reportAmbiguousErrors != context.reportAmbiguousErrors || 
+            newtree != context.tree) { 
+          val context1 = context.makeSilent(reportAmbiguousErrors, newtree) 
+          context1.undetparams = context.undetparams
+          context1.savedTypeBounds = context.savedTypeBounds
+          context1.namedApplyBlockInfo = context.namedApplyBlockInfo
+          val typer1 = newTyper(context1)
+          val result = op(typer1)
+          context.undetparams = context1.undetparams
+          context.savedTypeBounds = context1.savedTypeBounds
+          context.namedApplyBlockInfo = context1.namedApplyBlockInfo
+          result
+        } else {
+          op(this)
+        }
+      } catch {
+        case ex: CyclicReference => throw ex
+        case ex: TypeError =>
+          stopCounter(rawTypeFailed, rawTypeStart)
+          stopCounter(findMemberFailed, findMemberStart)
+          stopCounter(subtypeFailed, subtypeStart)
+          stopTimer(failedSilentNanos, failedSilentStart)
+          ex
       }
-    } catch {
-      case ex: CyclicReference => throw ex
-      case ex: TypeError => ex
     }
 
+    /** Utility method: Try op1 on tree. If that gives an error try op2 instead.
+     */
+    def tryBoth(tree: Tree)(op1: (Typer, Tree) => Tree)(op2: (Typer, Tree) => Tree): Tree =
+      silent(op1(_, tree)) match {
+        case result1: Tree => 
+          result1
+        case ex1: TypeError =>
+          silent(op2(_, resetAllAttrs(tree))) match {
+            case result2: Tree =>
+//              println("snd succeeded: "+result2)
+              result2
+            case ex2: TypeError =>
+              reportTypeError(tree.pos, ex1)
+              setError(tree)
+          }
+      }
+
     /** Perform the following adaptations of expression, pattern or type `tree' wrt to 
      *  given mode `mode' and given prototype `pt':
+     *  (-1) For expressions with annotated types, let AnnotationCheckers decide what to do
      *  (0) Convert expressions with constant types to literals
      *  (1) Resolve overloading, unless mode contains FUNmode 
      *  (2) Apply parameterless functions
@@ -636,7 +774,7 @@ trait Typers { self: Analyzer =>
      *  (5) Convert constructors in a pattern as follows:
      *  (5.1) If constructor refers to a case class factory, set tree's type to the unique
      *        instance of its primary constructor that is a subtype of the expected type.
-     *  (5.2) If constructor refers to an exractor, convert to application of
+     *  (5.2) If constructor refers to an extractor, convert to application of
      *        unapply or unapplySeq method.
      *
      *  (6) Convert all other types to TypeTree nodes.
@@ -649,59 +787,97 @@ trait Typers { self: Analyzer =>
      *      is an integer fitting in the range of that type, convert it to that type. 
      *  (11) Widen numeric literals to their expected type, if necessary
      *  (12) When in mode EXPRmode, convert E to { E; () } if expected type is scala.Unit.
-     *  (13) When in mode EXPRmode, apply a view
+     *  (13) When in mode EXPRmode, apply AnnotationChecker conversion if expected type is annotated.
+     *  (14) When in mode EXPRmode, apply a view
      *  If all this fails, error
      */
-    protected def adapt(tree: Tree, mode: Int, pt: Type): Tree = tree.tpe match {
-      case ct @ ConstantType(value) if ((mode & (TYPEmode | FUNmode)) == 0 && (ct <:< pt) && !inIDE) => // (0)
-        copy.Literal(tree, value)
+    protected def adapt(tree: Tree, mode: Int, pt: Type, original: Tree = EmptyTree): Tree = tree.tpe match {
+      case atp @ AnnotatedType(_, _, _) if canAdaptAnnotations(tree, mode, pt) => // (-1)
+        adaptAnnotations(tree, mode, pt)
+      case ct @ ConstantType(value) if ((mode & (TYPEmode | FUNmode)) == 0 && (ct <:< pt) && !onlyPresentation) => // (0)
+        treeCopy.Literal(tree, value)
       case OverloadedType(pre, alts) if ((mode & FUNmode) == 0) => // (1)
         inferExprAlternative(tree, pt)
-        adapt(tree, mode, pt)
+        adapt(tree, mode, pt, original)
       case PolyType(List(), restpe) => // (2)
-        adapt(tree setType restpe, mode, pt)
+        adapt(tree setType restpe, mode, pt, original)
       case TypeRef(_, sym, List(arg))
       if ((mode & EXPRmode) != 0 && sym == ByNameParamClass) => // (2)
-        adapt(tree setType arg, mode, pt)
+        adapt(tree setType arg, mode, pt, original)
       case tr @ TypeRef(_, sym, _) 
       if sym.isAliasType && tr.normalize.isInstanceOf[ExistentialType] &&
         ((mode & (EXPRmode | LHSmode)) == EXPRmode) =>
-        adapt(tree setType tr.normalize.skolemizeExistential(context.owner, tree), mode, pt)
+        adapt(tree setType tr.normalize.skolemizeExistential(context.owner, tree), mode, pt, original)
       case et @ ExistentialType(_, _) if ((mode & (EXPRmode | LHSmode)) == EXPRmode) =>
-        adapt(tree setType et.skolemizeExistential(context.owner, tree), mode, pt)
-      case PolyType(tparams, restpe) if ((mode & (TAPPmode | PATTERNmode)) == 0) => // (3)
-        assert((mode & HKmode) == 0) //@M
+        adapt(tree setType et.skolemizeExistential(context.owner, tree), mode, pt, original)
+      case PolyType(tparams, restpe) if ((mode & (TAPPmode | PATTERNmode | HKmode)) == 0) => // (3)
+        // assert((mode & HKmode) == 0) //@M a PolyType in HKmode represents an anonymous type function,
+        // we're in HKmode since a higher-kinded type is expected --> hence, don't implicitly apply it to type params!
+        // ticket #2197 triggered turning the assert into a guard
+        // I guess this assert wasn't violated before because type aliases weren't expanded as eagerly
+        //  (the only way to get a PolyType for an anonymous type function is by normalisation, which applies eta-expansion)
+          // -- are we sure we want to expand aliases this early?
+          // -- what caused this change in behaviour??
         val tparams1 = cloneSymbols(tparams)
         val tree1 = if (tree.isType) tree 
                     else TypeApply(tree, tparams1 map (tparam => 
-                      TypeTree(tparam.tpe) setOriginal tree)) setPos tree.pos
+                      TypeTree(tparam.tpeHK) setPos tree.pos.focus)) setPos tree.pos //@M/tcpolyinfer: changed tparam.tpe to tparam.tpeHK
         context.undetparams = context.undetparams ::: tparams1
-        adapt(tree1 setType restpe.substSym(tparams, tparams1), mode, pt)
-      case mt: ImplicitMethodType if ((mode & (EXPRmode | FUNmode | LHSmode)) == EXPRmode) => // (4.1)
-        if (!context.undetparams.isEmpty & (mode & POLYmode) == 0) { // (9)
-          val tparams = context.undetparams
-          context.undetparams = List()
-          inferExprInstance(tree, tparams, pt)
-          adapt(tree, mode, pt)
-        } else {
-          val typer1 = constrTyperIf(treeInfo.isSelfOrSuperConstrCall(tree))
-          typer1.typed(typer1.applyImplicitArgs(tree), mode, pt)
+        adapt(tree1 setType restpe.substSym(tparams, tparams1), mode, pt, original)
+      case mt: MethodType if mt.isImplicit && ((mode & (EXPRmode | FUNmode | LHSmode)) == EXPRmode) => // (4.1)
+        if (context.undetparams nonEmpty) {  // (9) -- should revisit dropped condition `(mode & POLYmode) == 0`
+                                             // dropped so that type args of implicit method are inferred even if polymorphic expressions are allowed
+                                             // needed for implicits in 2.8 collection library -- maybe once #3346 is fixed, we can reinstate the condition?
+          context.undetparams =
+            inferExprInstance(tree, context.extractUndetparams(), pt,
+                    // approximate types that depend on arguments since dependency on implicit argument is like dependency on type parameter
+                    if(settings.YdepMethTpes.value) mt.approximate else mt,
+                    // if we are looking for a manifest, instantiate type to Nothing anyway,
+                    // as we would get ambiguity errors otherwise. Example
+                    // Looking for a manifest of Nil: This mas many potential types,
+                    // so we need to instantiate to minimal type List[Nothing].
+                    false) // false: retract Nothing's that indicate failure, ambiguities in manifests are dealt with in manifestOfType
         }
+
+        val typer1 = constrTyperIf(treeInfo.isSelfOrSuperConstrCall(tree))
+        if (original != EmptyTree && pt != WildcardType)
+          typer1.silent(tpr => tpr.typed(tpr.applyImplicitArgs(tree), mode, pt)) match {
+            case result: Tree => result
+            case ex: TypeError => 
+              if (settings.debug.value) log("fallback on implicits: "+tree+"/"+resetAllAttrs(original))
+              val tree1 = typed(resetAllAttrs(original), mode, WildcardType)
+              tree1.tpe = addAnnotations(tree1, tree1.tpe)
+              if (tree1.isEmpty) tree1 else adapt(tree1, mode, pt, EmptyTree)
+          }
+        else
+          typer1.typed(typer1.applyImplicitArgs(tree), mode, pt)
       case mt: MethodType
       if (((mode & (EXPRmode | FUNmode | LHSmode)) == EXPRmode) && 
           (context.undetparams.isEmpty || (mode & POLYmode) != 0)) =>
-        val meth = tree.symbol
-        if (!meth.isConstructor && 
-            //isCompatible(tparamsToWildcards(mt, context.undetparams), pt) &&
-            isFunctionType(pt))/* &&
-            (pt <:< functionType(mt.paramTypes map (t => WildcardType), WildcardType)))*/ { // (4.2)
+
+        val meth = tree match {
+          // a partial named application is a block (see comment in EtaExpansion)
+          case Block(_, tree1) => tree1.symbol
+          case _ => tree.symbol
+        }
+        if (!meth.isConstructor && isFunctionType(pt)) { // (4.2)
           if (settings.debug.value) log("eta-expanding "+tree+":"+tree.tpe+" to "+pt)
           checkParamsConvertible(tree.pos, tree.tpe)
-          val tree1 = etaExpand(context.unit, tree)
-//          println("eta "+tree+" ---> "+tree1+":"+tree1.tpe)
-          typed(tree1, mode, pt)
-        } else if (!meth.isConstructor && mt.paramTypes.isEmpty) { // (4.3)
-          adapt(typed(Apply(tree, List()) setPos tree.pos), mode, pt)
+          val tree0 = etaExpand(context.unit, tree)
+          // println("eta "+tree+" ---> "+tree0+":"+tree0.tpe+" undet: "+context.undetparams+ " mode: "+Integer.toHexString(mode))
+
+          if(meth.typeParams.nonEmpty) {
+            // #2624: need to infer type arguments for eta expansion of a polymorphic method
+            // context.undetparams contains clones of meth.typeParams (fresh ones were generated in etaExpand)
+            // need to run typer on tree0, since etaExpansion sets the tpe's of its subtrees to null
+            // can't type with the expected type, as we can't recreate the setup in (3) without calling typed
+            // (note that (3) does not call typed to do the polymorphic type instantiation --
+            //  it is called after the tree has been typed with a polymorphic expected result type)
+            instantiate(typed(tree0, mode, WildcardType), mode, pt)
+          } else
+            typed(tree0, mode, pt)
+        } else if (!meth.isConstructor && mt.params.isEmpty) { // (4.3)
+          adapt(typed(Apply(tree, List()) setPos tree.pos), mode, pt, original)
         } else if (context.implicitsEnabled) {
           errorTree(tree, "missing arguments for "+meth+meth.locationString+
                     (if (meth.isConstructor) ""
@@ -711,7 +887,7 @@ trait Typers { self: Analyzer =>
         }
       case _ =>
         def applyPossible = {
-          def applyMeth = member(adaptToName(tree, nme.apply), nme.apply)(context.owner)
+          def applyMeth = member(adaptToName(tree, nme.apply), nme.apply)
           if ((mode & TAPPmode) != 0)
             tree.tpe.typeParams.isEmpty && applyMeth.filter(! _.tpe.typeParams.isEmpty) != NoSymbol
           else 
@@ -724,7 +900,7 @@ trait Typers { self: Analyzer =>
                      !(tree.symbol.hasFlag(JAVA) && context.unit.isJava)) { // (7) 
             // @M When not typing a higher-kinded type ((mode & HKmode) == 0) 
             // or raw type (tree.symbol.hasFlag(JAVA) && context.unit.isJava), types must be of kind *, 
-            // and thus parameterised types must be applied to their type arguments
+            // and thus parameterized types must be applied to their type arguments
             // @M TODO: why do kind-* tree's have symbols, while higher-kinded ones don't?
             errorTree(tree, tree.symbol+" takes type parameters")
             tree setType tree.tpe
@@ -750,27 +926,20 @@ trait Typers { self: Analyzer =>
             case _ => TypeTree(tree.tpe) setOriginal(tree)
           }
         } else if ((mode & (PATTERNmode | FUNmode)) == (PATTERNmode | FUNmode)) { // (5)
-          val extractor = tree.symbol.filter(sym => unapplyMember(sym.tpe).exists)
+          val extractor = tree.symbol.filter(sym => reallyExists(unapplyMember(sym.tpe)))
           if (extractor != NoSymbol) {
             tree setSymbol extractor
             val unapply = unapplyMember(extractor.tpe)
-            val clazz = if (unapply.tpe.paramTypes.length == 1) unapply.tpe.paramTypes.head.typeSymbol 
-                        else NoSymbol
-            if ((unapply hasFlag CASE) && (clazz hasFlag CASE) && 
-                !(clazz.info.baseClasses.tail exists (_ hasFlag CASE))) {
-              if (!phase.erasedTypes) checkStable(tree) //todo: do we need to demand this?
+            val clazz = unapplyParameterType(unapply)
+
+            if ((unapply hasFlag CASE) && (clazz hasFlag CASE) && !(clazz.ancestors exists (_ hasFlag CASE))) {
+              if (!phase.erasedTypes) checkStable(tree) // todo: do we need to demand this?
               // convert synthetic unapply of case class to case class constructor
               val prefix = tree.tpe.prefix
               val tree1 = TypeTree(clazz.primaryConstructor.tpe.asSeenFrom(prefix, clazz.owner))
                   .setOriginal(tree)
-              try {
-                inferConstructorInstance(tree1, clazz.typeParams, pt)
-              } catch {
-                case tpe : TypeError => throw tpe
-                case t : Exception =>
-                  logError("CONTEXT: " + (tree.pos).dbgString, t)
-                  throw t
-              }
+              
+              inferConstructorInstance(tree1, clazz.typeParams, pt)
               tree1
             } else {
               tree
@@ -800,20 +969,7 @@ trait Typers { self: Analyzer =>
           assert((mode & HKmode) == 0) //@M
           instantiate(tree, mode, pt)
         } else if (tree.tpe <:< pt) {
-          def isStructuralType(tpe: Type): Boolean = tpe match {
-            case RefinedType(ps, decls) =>
-              decls.toList exists (x => x.isTerm && x.allOverriddenSymbols.isEmpty)
-            case _ =>
-              false
-          }
-          if (isStructuralType(pt) && tree.tpe.typeSymbol == ArrayClass) {
-            // all Arrays used as structural refinement typed values must be boxed
-            // this does not solve the case where the type to be adapted to comes
-            // from a type variable that was bound by a strctural but is instantiated
-            typed(Apply(Select(gen.mkAttributedRef(ScalaRunTimeModule), nme.forceBoxedArray), List(tree)))
-          }
-          else
-            tree
+          tree
         } else {
           if ((mode & PATTERNmode) != 0) {
             if ((tree.symbol ne null) && tree.symbol.isModule)
@@ -822,7 +978,7 @@ trait Typers { self: Analyzer =>
               return tree
           }
           val tree1 = constfold(tree, pt) // (10) (11)
-          if (tree1.tpe <:< pt) adapt(tree1, mode, pt)
+          if (tree1.tpe <:< pt) adapt(tree1, mode, pt, original)
           else {
             if ((mode & (EXPRmode | FUNmode)) == EXPRmode) {
               pt.normalize match {
@@ -831,15 +987,19 @@ trait Typers { self: Analyzer =>
                   // infinite expansion if pt is constant type ()
                   if (sym == UnitClass && tree.tpe <:< AnyClass.tpe) // (12)
                     return typed(atPos(tree.pos)(Block(List(tree), Literal(()))), mode, pt)
+                  else if (isNumericValueClass(sym) && isNumericSubType(tree.tpe, pt))
+                    return typed(atPos(tree.pos)(Select(tree, "to"+sym.name)), mode, pt)
+                case AnnotatedType(_, _, _) if canAdaptAnnotations(tree, mode, pt) => // (13)
+                    return typed(adaptAnnotations(tree, mode, pt), mode, pt)
                 case _ =>
               }
               if (!context.undetparams.isEmpty) {
                 return instantiate(tree, mode, pt)
               }
               if (context.implicitsEnabled && !tree.tpe.isError && !pt.isError) { 
-                // (13); the condition prevents chains of views 
+                // (14); the condition prevents chains of views 
                 if (settings.debug.value) log("inferring view from "+tree.tpe+" to "+pt)
-                val coercion = inferView(tree.pos, tree.tpe, pt, true)
+                val coercion = inferView(tree, tree.tpe, pt, true)
                 // convert forward views of delegate types into closures wrapped around
                 // the delegate's apply method (the "Invoke" method, which was translated into apply)
                 if (forMSIL && coercion != null && isCorrespondingDelegate(tree.tpe, pt)) {
@@ -851,7 +1011,7 @@ trait Typers { self: Analyzer =>
                 if (coercion != EmptyTree) {
                   if (settings.debug.value) log("inferred view from "+tree.tpe+" to "+pt+" = "+coercion+":"+coercion.tpe)
                   return newTyper(context.makeImplicit(context.reportAmbiguousErrors)).typed(
-                      Apply(coercion, List(tree)) setPos tree.pos, mode, pt)
+                    new ApplyImplicitView(coercion, List(tree)) setPos tree.pos, mode, pt)
                 }
               }
             }
@@ -871,34 +1031,67 @@ trait Typers { self: Analyzer =>
      *  @return     ...
      */
     def instantiate(tree: Tree, mode: Int, pt: Type): Tree = {
-      val tparams = context.undetparams
-      context.undetparams = List()
-      inferExprInstance(tree, tparams, pt)
+      inferExprInstance(tree, context.extractUndetparams(), pt, true)
       adapt(tree, mode, pt)
     }
 
-    /**
-     *  @param qual ...
-     *  @param name ...
-     *  @param tp   ...
-     *  @return     ...
-     */
-    def adaptToMember(qual: Tree, name: Name, tp: Type): Tree = {
-      val qtpe = qual.tpe.widen
+    def adaptToMember(qual: Tree, searchTemplate: Type): Tree = {
+      var qtpe = qual.tpe.widen
       if (qual.isTerm && 
           ((qual.symbol eq null) || !qual.symbol.isTerm || qual.symbol.isValue) &&
-          phase.id <= currentRun.typerPhase.id && !qtpe.isError && !tp.isError &&
-          qtpe.typeSymbol != NullClass && qtpe.typeSymbol != NothingClass && qtpe != WildcardType) {
-        val coercion = inferView(qual.pos, qtpe, name, tp, true)
-        if (coercion != EmptyTree) 
-          typedQualifier(atPos(qual.pos)(Apply(coercion, List(qual))))
-        else qual
-      } else qual
+          phase.id <= currentRun.typerPhase.id && !qtpe.isError &&
+          qtpe.typeSymbol != NullClass && qtpe.typeSymbol != NothingClass && qtpe != WildcardType && 
+          !qual.isInstanceOf[ApplyImplicitView] && // don't chain views
+          context.implicitsEnabled) { // don't try to adapt a top-level type that's the subject of an implicit search
+                                      // this happens because, if isView, typedImplicit tries to apply the "current" implicit value to 
+                                      // a value that needs to be coerced, so we check whether the implicit value has an `apply` method
+                                     // (if we allow this, we get divergence, e.g., starting at `conforms` during ant quick.bin) 
+                                     // note: implicit arguments are still inferred (this kind of "chaining" is allowed)
+        if (qtpe.normalize.isInstanceOf[ExistentialType]) {
+          qtpe = qtpe.normalize.skolemizeExistential(context.owner, qual) // open the existential
+          qual setType qtpe
+        }
+        val coercion = inferView(qual, qtpe, searchTemplate, true)
+        if (coercion != EmptyTree)
+          typedQualifier(atPos(qual.pos)(new ApplyImplicitView(coercion, List(qual))))
+        else
+          qual
+      } else {
+        qual
+      }
+    }
+
+    /** Try to apply an implicit conversion to `qual' to that it contains
+     *  a method `name` which can be applied to arguments `args' with expected type `pt'.
+     *  If `pt' is defined, there is a fallback to try again with pt = ?.
+     *  This helps avoiding propagating result information too far and solves
+     *  #1756.
+     *  If no conversion is found, return `qual' unchanged.
+     * 
+     */
+    def adaptToArguments(qual: Tree, name: Name, args: List[Tree], pt: Type): Tree = {
+      def doAdapt(restpe: Type) =
+        //util.trace("adaptToArgs "+qual+", name = "+name+", argtpes = "+(args map (_.tpe))+", pt = "+pt+" = ")
+        adaptToMember(qual, HasMethodMatching(name, args map (_.tpe), restpe))
+      if (pt != WildcardType) {
+        silent(_ => doAdapt(pt)) match {
+          case result: Tree if result != qual => 
+            result
+          case _ => 
+            if (settings.debug.value) log("fallback on implicits in adaptToArguments: "+qual+" . "+name)
+            doAdapt(WildcardType)
+        }
+      } else 
+        doAdapt(pt)
     }
 
+    /** Try to apply an implicit conversion to `qual' to that it contains a
+     *  member `name` of arbitrary type.
+     *  If no conversion is found, return `qual' unchanged.
+     */
     def adaptToName(qual: Tree, name: Name) =
-      if (member(qual, name)(context.owner) != NoSymbol) qual
-      else adaptToMember(qual, name, WildcardType)
+      if (member(qual, name) != NoSymbol) qual
+      else adaptToMember(qual, HasMember(name))
 
     private def typePrimaryConstrBody(clazz : Symbol, cbody: Tree, tparams: List[Symbol], enclTparams: List[Symbol], vparamss: List[List[ValDef]]): Tree = {
       // XXX: see about using the class's symbol....
@@ -906,6 +1099,20 @@ trait Typers { self: Analyzer =>
       namer.enterValueParams(context.owner, vparamss)
       typed(cbody)
     }
+    
+    private def validateNoCaseAncestor(clazz: Symbol) = {
+      // XXX I think this should issue a sharper warning of some kind like
+      // "change your code now!" as there are material bugs (which are very unlikely 
+      // to be fixed) associated with case class inheritance.
+      if (!phase.erasedTypes) {
+        for (ancestor <- clazz.ancestors find (_ hasFlag CASE))
+          unit.deprecationWarning(clazz.pos, ( 
+            "case class `%s' has case class ancestor `%s'.  This has been deprecated " +
+            "for unduly complicating both usage and implementation.  You should instead " + 
+            "use extractors for pattern matching on non-leaf nodes." ).format(clazz, ancestor)
+          )
+      }
+    }
 
     def parentTypes(templ: Template): List[Tree] = 
       if (templ.parents.isEmpty) List()
@@ -921,7 +1128,7 @@ trait Typers { self: Analyzer =>
           val supertpt1 = typedType(supertpt)
           if (!supertpt1.tpe.isError) {
             mixins = supertpt1 :: mixins
-            supertpt = TypeTree(supertpt1.tpe.parents.head) setOriginal supertpt /* setPos supertpt.pos */
+            supertpt = TypeTree(supertpt1.tpe.parents.head) setPos supertpt.pos.focus
           }
         }
 
@@ -936,11 +1143,11 @@ trait Typers { self: Analyzer =>
         // A method to replace a super reference by a New in a supercall
         def transformSuperCall(scall: Tree): Tree = (scall: @unchecked) match {
           case Apply(fn, args) =>
-            copy.Apply(scall, transformSuperCall(fn), args map (_.duplicate))
+            treeCopy.Apply(scall, transformSuperCall(fn), args map (_.duplicate))
           case Select(Super(_, _), nme.CONSTRUCTOR) =>
-            copy.Select(
+            treeCopy.Select(
               scall, 
-              New(TypeTree(supertpe) setOriginal supertpt) setType supertpe setPos supertpt.pos,
+              atPos(supertpt.pos.focus)(New(TypeTree(supertpe)) setType supertpe),
               nme.CONSTRUCTOR)
         }
 
@@ -951,16 +1158,16 @@ trait Typers { self: Analyzer =>
             val scall = if (cstats.isEmpty) EmptyTree else cstats.last
             val cbody1 = scall match {
               case Apply(_, _) =>
-                copy.Block(cbody, cstats1.init, 
+                treeCopy.Block(cbody, cstats1.init, 
                            if (supertparams.isEmpty) cunit.duplicate 
                            else transformSuperCall(scall))
               case _ =>
-                copy.Block(cbody, cstats1, cunit.duplicate)
+                treeCopy.Block(cbody, cstats1, cunit.duplicate)
             }
 
             val outercontext = context.outer 
             assert(clazz != NoSymbol)
-            val cscope = outercontext.makeNewScope(constr, outercontext.owner)(ParentTypesScopeKind(clazz))
+            val cscope = outercontext.makeNewScope(constr, outercontext.owner)
             val cbody2 = newTyper(cscope) // called both during completion AND typing.
                 .typePrimaryConstrBody(clazz,  
                   cbody1, supertparams, clazz.unsafeTypeParams, vparamss map (_.map(_.duplicate)))
@@ -970,20 +1177,28 @@ trait Typers { self: Analyzer =>
                 val sarg = treeInfo.firstArgument(scall)
                 if (sarg != EmptyTree && supertpe.typeSymbol != firstParent) 
                   error(sarg.pos, firstParent+" is a trait; does not take constructor arguments")
-                if (!supertparams.isEmpty) supertpt = TypeTree(cbody2.tpe) setPos supertpt.pos
+                if (!supertparams.isEmpty) supertpt = TypeTree(cbody2.tpe) setPos supertpt.pos.focus
               case _ =>
                 if (!supertparams.isEmpty) error(supertpt.pos, "missing type arguments")
             }
 
-            List.map2(cstats1, treeInfo.preSuperFields(templ.body)) {
+            (cstats1, treeInfo.preSuperFields(templ.body)).zipped map {
               (ldef, gdef) => gdef.tpt.tpe = ldef.symbol.tpe
             }
           case _ =>
             if (!supertparams.isEmpty) error(supertpt.pos, "missing type arguments")
         }
+/* experimental: early types as type arguments
+        val hasEarlyTypes = templ.body exists (treeInfo.isEarlyTypeDef)
+        val earlyMap = new EarlyMap(clazz)
+        List.mapConserve(supertpt :: mixins){ tpt => 
+          val tpt1 = checkNoEscaping.privates(clazz, tpt)
+          if (hasEarlyTypes) tpt1 else tpt1 setType earlyMap(tpt1.tpe)
+        }
+*/
 
         //Console.println("parents("+clazz") = "+supertpt :: mixins);//DEBUG
-        List.mapConserve(supertpt :: mixins)(tpt => checkNoEscaping.privates(clazz, tpt))
+        supertpt :: mixins mapConserve (tpt => checkNoEscaping.privates(clazz, tpt))
       } catch {
         case ex: TypeError =>
           templ.tpe = null
@@ -1010,16 +1225,16 @@ trait Typers { self: Analyzer =>
       def validateParentClass(parent: Tree, superclazz: Symbol) {
         if (!parent.tpe.isError) {
           val psym = parent.tpe.typeSymbol.initialize
-          checkClassType(parent, false)
+          checkClassType(parent, false, true)
           if (psym != superclazz) {
             if (psym.isTrait) {
               val ps = psym.info.parents
               if (!ps.isEmpty && !superclazz.isSubClass(ps.head.typeSymbol))
                 error(parent.pos, "illegal inheritance; super"+superclazz+
                       "\n is not a subclass of the super"+ps.head.typeSymbol+
-                      "\n of the mixin " + psym);
+                      "\n of the mixin " + psym)
             } else {
-              error(parent.pos, psym+" needs to be a trait be mixed in")
+              error(parent.pos, psym+" needs to be a trait to be mixed in")
             }
           } 
           if (psym hasFlag FINAL) {
@@ -1033,13 +1248,14 @@ trait Typers { self: Analyzer =>
           }
           if (!(selfType <:< parent.tpe.typeOfThis) && 
               !phase.erasedTypes &&     
-              !(context.owner hasFlag SYNTHETIC)) // don't do this check for synthetic concrete classes for virtuals (part of DEVIRTUALIZE)
+              !(context.owner hasFlag SYNTHETIC) && // don't do this check for synthetic concrete classes for virtuals (part of DEVIRTUALIZE)
+              !(settings.suppressVTWarn.value) &&
+              !selfType.isErroneous && !parent.tpe.isErroneous)
           { 
             //Console.println(context.owner);//DEBUG
             //Console.println(context.owner.unsafeTypeParams);//DEBUG
             //Console.println(List.fromArray(context.owner.info.closure));//DEBUG
-            // disable in IDE, don't know how else to avoid it on refresh
-            if (!inIDE) error(parent.pos, "illegal inheritance;\n self-type "+
+            error(parent.pos, "illegal inheritance;\n self-type "+
                   selfType+" does not conform to "+parent +
                   "'s selftype "+parent.tpe.typeOfThis)
             if (settings.explaintypes.value) explainTypes(selfType, parent.tpe.typeOfThis)
@@ -1051,6 +1267,14 @@ trait Typers { self: Analyzer =>
 
       if (!parents.isEmpty && !parents.head.tpe.isError)
         for (p <- parents) validateParentClass(p, parents.head.tpe.typeSymbol)
+
+/*
+      if (settings.Xshowcls.value != "" &&
+          settings.Xshowcls.value == context.owner.fullName)
+        println("INFO "+context.owner+
+                ", baseclasses = "+(context.owner.info.baseClasses map (_.fullName))+
+                ", lin = "+(context.owner.info.baseClasses map (context.owner.thisType.baseType)))
+*/ 
     }
 
     def checkFinitary(classinfo: ClassInfoType) {
@@ -1078,24 +1302,29 @@ trait Typers { self: Analyzer =>
      */
     def typedClassDef(cdef: ClassDef): Tree = {
 //      attributes(cdef)
-      val typedMods = typedModifiers(cdef.mods)
-      val clazz = cdef.symbol; 
-      if (inIDE && clazz == NoSymbol) {
-        throw new TypeError("type signature typing failed")
-      }
+      val clazz = cdef.symbol
+      val typedMods = removeAnnotations(cdef.mods)
       assert(clazz != NoSymbol)
       reenterTypeParams(cdef.tparams)
-      val tparams1 = List.mapConserve(cdef.tparams)(typedTypeDef)
-      val impl1 = newTyper(context.make(cdef.impl, clazz, scopeFor(cdef.impl, TypedDefScopeKind)))
+      val tparams1 = cdef.tparams mapConserve (typedTypeDef)
+      val impl1 = newTyper(context.make(cdef.impl, clazz, new Scope))
         .typedTemplate(cdef.impl, parentTypes(cdef.impl))
       val impl2 = addSyntheticMethods(impl1, clazz, context)
       if ((clazz != ClassfileAnnotationClass) &&
-	  (clazz isNonBottomSubClass ClassfileAnnotationClass))
-	unit.warning (cdef.pos,
+          (clazz isNonBottomSubClass ClassfileAnnotationClass))
+        unit.warning (cdef.pos,
           "implementation restriction: subclassing Classfile does not\n"+
           "make your annotation visible at runtime.  If that is what\n"+ 
-	  "you want, you must write the annotation class in Java.")
-      copy.ClassDef(cdef, typedMods, cdef.name, tparams1, impl2)
+          "you want, you must write the annotation class in Java.")
+      if (phase.id <= currentRun.typerPhase.id) {
+        for (ann <- clazz.getAnnotation(DeprecatedAttr)) {
+          val m = companionModuleOf(clazz, context)
+          if (m != NoSymbol) {
+            m.moduleClass.addAnnotation(AnnotationInfo(ann.atp, ann.args, List()))
+          }
+        }
+      }
+      treeCopy.ClassDef(cdef, typedMods, cdef.name, tparams1, impl2)
         .setType(NoType)
     }
  
@@ -1106,15 +1335,25 @@ trait Typers { self: Analyzer =>
     def typedModuleDef(mdef: ModuleDef): Tree = {
       //Console.println("sourcefile of " + mdef.symbol + "=" + mdef.symbol.sourceFile)
 //      attributes(mdef)
-      val typedMods = typedModifiers(mdef.mods)
+      // initialize all constructors of the linked class: the type completer (Namer.methodSig)
+      // might add default getters to this object. example: "object T; class T(x: Int = 1)"
+      val linkedClass = mdef.symbol.companionClass
+      if (linkedClass != NoSymbol)
+        for (c <- linkedClass.info.decl(nme.CONSTRUCTOR).alternatives)
+          c.initialize
       val clazz = mdef.symbol.moduleClass
-      if (inIDE && clazz == NoSymbol) throw new TypeError("bad signature")
+      val typedMods = removeAnnotations(mdef.mods)
       assert(clazz != NoSymbol)
-      val impl1 = newTyper(context.make(mdef.impl, clazz, scopeFor(mdef.impl, TypedDefScopeKind)))
+      val impl1 = newTyper(context.make(mdef.impl, clazz, new Scope))
         .typedTemplate(mdef.impl, parentTypes(mdef.impl))
       val impl2 = addSyntheticMethods(impl1, clazz, context)
 
-      copy.ModuleDef(mdef, typedMods, mdef.name, impl2) setType NoType
+      if (mdef.name == nme.PACKAGEkw) 
+        for (m <- mdef.symbol.info.members)
+          if (m.isClass && m.hasFlag(CASE))
+            context.error(if (m.pos.isDefined) m.pos else mdef.pos,
+                          "implementation restriction: "+mdef.symbol+" cannot contain case "+m)
+      treeCopy.ModuleDef(mdef, typedMods, mdef.name, impl2) setType NoType
     }
 
     /**
@@ -1123,50 +1362,93 @@ trait Typers { self: Analyzer =>
      */
     def addGetterSetter(stat: Tree): List[Tree] = stat match {
       case ValDef(mods, name, tpt, rhs) 
-        if (mods.flags & (PRIVATE | LOCAL)) != (PRIVATE | LOCAL)
-          && !stat.symbol.isModuleVar
-          && !stat.symbol.hasFlag(LAZY) =>
-        val vdef = copy.ValDef(stat, mods | PRIVATE | LOCAL, nme.getterToLocal(name), tpt, rhs)
-        val value = vdef.symbol
-        val getter = if ((mods hasFlag DEFERRED)) value else value.getter(value.owner)
-        // XXX:
-        if (inIDE && getter == NoSymbol) 
-          return Nil
+        // PRIVATE | LOCAL are fields generated for primary constructor arguments
+        if (mods.flags & (PRIVATE | LOCAL)) != (PRIVATE | LOCAL).toLong && !stat.symbol.isModuleVar =>
+
+        val isDeferred = mods hasFlag DEFERRED
+        val value = stat.symbol
+        val allAnnots = value.annotations
+        if (!isDeferred)
+          // keepClean: by default annotations go to the field, except if the field is
+          // generated for a class parameter (PARAMACCESSOR).
+          value.setAnnotations(memberAnnots(allAnnots, FieldTargetClass, keepClean = !mods.hasFlag(PARAMACCESSOR)))
+
+        val getter = if (isDeferred) value else value.getter(value.owner)
         assert(getter != NoSymbol, stat)
         if (getter hasFlag OVERLOADED)
           error(getter.pos, getter+" is defined twice")
-        val getterDef: DefDef = {
-          getter.attributes = value.initialize.attributes
-          val result = DefDef(getter, vparamss =>
-              if (mods hasFlag DEFERRED) EmptyTree 
-              else typed(
-                atPos(vdef.pos) { gen.mkCheckInit(Select(This(value.owner), value)) }, 
-                EXPRmode, value.tpe))
-          result.tpt.asInstanceOf[TypeTree] setOriginal tpt /* setPos tpt.pos */
-          checkNoEscaping.privates(getter, result.tpt)
-          copy.DefDef(result, result.mods withAnnotations mods.annotations, result.name,
-                      result.tparams, result.vparamss, result.tpt, result.rhs)
-          //todo: withAnnotations is probably unnecessary
-        }
-        def setterDef: DefDef = {
-          val setr = getter.setter(value.owner)
-          setr.attributes = value.attributes
-          val result = atPos(vdef.pos)(
-            DefDef(setr, vparamss =>
-              if ((mods hasFlag DEFERRED) || (setr hasFlag OVERLOADED)) 
-                EmptyTree
-              else 
-                typed(Assign(Select(This(value.owner), value),
-                             Ident(vparamss.head.head)))))
-          copy.DefDef(result, result.mods withAnnotations mods.annotations, result.name,
-                      result.tparams, result.vparamss, result.tpt, result.rhs)
-        }
-        val gs = if (mods hasFlag MUTABLE) List(getterDef, setterDef)
-                 else List(getterDef)
-        if (mods hasFlag DEFERRED) gs else vdef :: gs
+        getter.setAnnotations(memberAnnots(allAnnots, GetterTargetClass))
+
+        if (value.hasFlag(LAZY)) List(stat)
+        else {
+          val vdef = treeCopy.ValDef(stat, mods | PRIVATE | LOCAL, nme.getterToLocal(name), tpt, rhs)
+          val getterDef: DefDef = atPos(vdef.pos.focus) {
+            if (isDeferred) {
+              val r = DefDef(getter, EmptyTree)
+              r.tpt.asInstanceOf[TypeTree].setOriginal(tpt) // keep type tree of original abstract field
+              r
+            } else {
+              val rhs = gen.mkCheckInit(Select(This(value.owner), value))
+              val r = typed {
+                atPos(getter.pos.focus) {
+                  DefDef(getter, rhs)
+                }
+              }.asInstanceOf[DefDef]
+              r.tpt.setPos(tpt.pos.focus)
+              r
+            }
+          }
+          checkNoEscaping.privates(getter, getterDef.tpt)
+          def setterDef(setter: Symbol, isBean: Boolean = false): DefDef = {
+            setter.setAnnotations(memberAnnots(allAnnots, if (isBean) BeanSetterTargetClass else SetterTargetClass))
+            val result = typed {
+              atPos(vdef.pos.focus) {
+                DefDef(
+                  setter,
+                  if ((mods hasFlag DEFERRED) || (setter hasFlag OVERLOADED))
+                    EmptyTree
+                  else
+                    Assign(Select(This(value.owner), value),
+                           Ident(setter.paramss.head.head)))
+              }
+            }
+            result.asInstanceOf[DefDef]
+            // Martin: was 
+            // treeCopy.DefDef(result, result.mods, result.name, result.tparams,
+            //                result.vparamss, result.tpt, result.rhs)
+            // but that's redundant, no?
+          }
 
-      case DocDef(comment, defn) =>
-        addGetterSetter(defn) map (stat => DocDef(comment, stat))
+          val gs = new ListBuffer[DefDef]
+          gs.append(getterDef)
+          if (mods hasFlag MUTABLE) {
+            val setter = getter.setter(value.owner)
+            gs.append(setterDef(setter))
+          }
+          if (!forMSIL && (value.hasAnnotation(BeanPropertyAttr) ||
+              value.hasAnnotation(BooleanBeanPropertyAttr))) {
+            val nameSuffix = name.toString().capitalize
+            val beanGetterName =
+              (if (value.hasAnnotation(BooleanBeanPropertyAttr)) "is" else "get") +
+              nameSuffix
+            val beanGetter = value.owner.info.decl(beanGetterName)
+            if (beanGetter == NoSymbol) {
+              // the namer decides wether to generate these symbols or not. at that point, we don't
+              // have symbolic information yet, so we only look for annotations named "BeanProperty".
+              unit.error(stat.pos, "implementation limitation: the BeanProperty annotation cannot be used in a type alias or renamed import")
+            }
+            beanGetter.setAnnotations(memberAnnots(allAnnots, BeanGetterTargetClass))
+            if (mods.hasFlag(MUTABLE) && beanGetter != NoSymbol) {
+              val beanSetterName = "set" + nameSuffix
+              val beanSetter = value.owner.info.decl(beanSetterName)
+              // unlike for the beanGetter, the beanSetter body is generated here. see comment in Namers.
+              gs.append(setterDef(beanSetter, isBean = true))
+            }
+          }
+          if (mods hasFlag DEFERRED) gs.toList else vdef :: gs.toList
+        }
+      case dd @ DocDef(comment, defn) =>
+        addGetterSetter(defn) map (stat => DocDef(comment, stat) setPos dd.pos)
 
       case Annotated(annot, defn) =>
         addGetterSetter(defn) map (stat => Annotated(annot, stat))
@@ -1175,6 +1457,40 @@ trait Typers { self: Analyzer =>
         List(stat)
     }
 
+    /**
+     * The annotations amongst `annots` that should go on a member of class
+     * `memberClass` (field, getter, setter, beanGetter, beanSetter, param)
+     * If 'keepClean' is true, annotations without any meta-annotation are kept
+     */
+    protected def memberAnnots(annots: List[AnnotationInfo], memberClass: Symbol, keepClean: Boolean = false) = {
+
+      def hasMatching(metaAnnots: List[AnnotationInfo], orElse: => Boolean) = {
+        // either one of the meta-annotations matches the `memberClass`
+        metaAnnots.exists(_.atp.typeSymbol == memberClass) ||
+        // else, if there is no `target` meta-annotation at all, use the default case
+        (metaAnnots.forall(ann => {
+          val annClass = ann.atp.typeSymbol
+          annClass != FieldTargetClass && annClass != GetterTargetClass &&
+          annClass != SetterTargetClass && annClass != BeanGetterTargetClass &&
+          annClass != BeanSetterTargetClass && annClass != ParamTargetClass
+        }) && orElse)
+      }
+
+      // there was no meta-annotation on `ann`. Look if the class annotations of
+      // `ann` has a `target` annotation, otherwise put `ann` only on fields.
+      def noMetaAnnot(ann: AnnotationInfo) = {
+        hasMatching(ann.atp.typeSymbol.annotations, keepClean)
+      }
+
+      annots.filter(ann => ann.atp match {
+        // the annotation type has meta-annotations, e.g. @(foo @getter)
+        case AnnotatedType(metaAnnots, _, _) =>
+          hasMatching(metaAnnots, noMetaAnnot(ann))
+        // there are no meta-annotations, e.g. @foo
+        case _ => noMetaAnnot(ann)
+      })
+    }
+
     protected def enterSyms(txt: Context, trees: List[Tree]) = {
       var txt0 = txt
       for (tree <- trees) txt0 = enterSym(txt0, tree)
@@ -1194,14 +1510,23 @@ trait Typers { self: Analyzer =>
      */
     def typedTemplate(templ: Template, parents1: List[Tree]): Template = {
       val clazz = context.owner
+      // complete lazy annotations
+      val annots = clazz.annotations
       if (templ.symbol == NoSymbol)
-        templ setSymbol newLocalDummy(clazz, templ.pos)
+        templ setSymbol clazz.newLocalDummy(templ.pos)
       val self1 = templ.self match {
         case vd @ ValDef(mods, name, tpt, EmptyTree) =>
-          val tpt1 = checkNoEscaping.privates(clazz.thisSym, typedType(tpt))
-          copy.ValDef(vd, mods, name, tpt1, EmptyTree) setType NoType
+          val tpt1 = 
+            checkNoEscaping.privates(
+              clazz.thisSym, 
+              treeCopy.TypeTree(tpt) setType vd.symbol.tpe)
+          treeCopy.ValDef(vd, mods, name, tpt1, EmptyTree) setType NoType
       }
-      if (self1.name != nme.WILDCARD) context.scope enter self1.symbol
+// was: 
+//          val tpt1 = checkNoEscaping.privates(clazz.thisSym, typedType(tpt))
+//          treeCopy.ValDef(vd, mods, name, tpt1, EmptyTree) setType NoType
+// but this leads to cycles for existential self types ==> #2545
+    if (self1.name != nme.WILDCARD) context.scope enter self1.symbol
       val selfType =
         if (clazz.isAnonymousClass && !phase.erasedTypes) 
           intersectionType(clazz.info.parents, clazz.owner)
@@ -1210,6 +1535,9 @@ trait Typers { self: Analyzer =>
       assert(clazz.info.decls != EmptyScope)
       enterSyms(context.outer.make(templ, clazz, clazz.info.decls), templ.body)
       validateParentClasses(parents1, selfType)
+      if (clazz hasFlag CASE)
+        validateNoCaseAncestor(clazz)
+      
       if ((clazz isSubClass ClassfileAnnotationClass) && !clazz.owner.isPackageClass)
         unit.error(clazz.pos, "inner classes cannot be classfile annotations")
       if (!phase.erasedTypes && !clazz.info.resultType.isError) // @S: prevent crash for duplicated type members
@@ -1219,15 +1547,14 @@ trait Typers { self: Analyzer =>
           templ.body flatMap addGetterSetter
         else templ.body 
       val body1 = typedStats(body, templ.symbol)
-      copy.Template(templ, parents1, self1, body1) setType clazz.tpe
+      treeCopy.Template(templ, parents1, self1, body1) setType clazz.tpe
     }
 
-    /** Type check the annotations within a set of modifiers.  */
-    def typedModifiers(mods: Modifiers): Modifiers = {
-      val Modifiers(flags, privateWithin, annotations) = mods
-      val typedAnnots = annotations.map(typed(_).asInstanceOf[Annotation])
-      Modifiers(flags, privateWithin, typedAnnots)
-    }
+    /** Remove definition annotations from modifiers (they have been saved
+     *  into the symbol's ``annotations'' in the type completer / namer)
+     */
+    def removeAnnotations(mods: Modifiers): Modifiers =
+      Modifiers(mods.flags, mods.privateWithin, Nil, mods.positions)
 
     /**
      *  @param vdef ...
@@ -1237,23 +1564,46 @@ trait Typers { self: Analyzer =>
 //      attributes(vdef)
       val sym = vdef.symbol
       val typer1 = constrTyperIf(sym.hasFlag(PARAM) && sym.owner.isConstructor)
-      val typedMods = typedModifiers(vdef.mods)
+      val typedMods = removeAnnotations(vdef.mods)
+      
+      // complete lazy annotations
+      val annots = sym.annotations
 
-      var tpt1 = checkNoEscaping.privates(sym, typer1.typedType(
-        if (inIDE) vdef.tpt.duplicate // avoids wrong context sticking
-        else vdef.tpt))
+      var tpt1 = checkNoEscaping.privates(sym, typer1.typedType(vdef.tpt))
       checkNonCyclic(vdef, tpt1)
+      if (sym.hasAnnotation(definitions.VolatileAttr)) {
+        if (!sym.hasFlag(MUTABLE))
+          error(vdef.pos, "values cannot be volatile")
+        else if (sym.hasFlag(FINAL))
+          error(vdef.pos, "final vars cannot be volatile")
+      }
       val rhs1 =
         if (vdef.rhs.isEmpty) {
           if (sym.isVariable && sym.owner.isTerm && phase.id <= currentRun.typerPhase.id)
             error(vdef.pos, "local variables must be initialized")
           vdef.rhs
         } else {
-          //assert(vdef.rhs.tpe == null)
-          val rhs = if (inIDE && vdef.rhs.tpe != null) vdef.rhs.duplicate else vdef.rhs
-          newTyper(typer1.context.make(vdef, sym)).transformedOrTyped(rhs, tpt1.tpe)
+          val tpt2 = if (sym hasFlag DEFAULTPARAM) {
+            // When typechecking default parameter, replace all type parameters in the expected type by Wildcard.
+            // This allows defining "def foo[T](a: T = 1)"
+            val tparams =
+              if (sym.owner.isConstructor) sym.owner.owner.info.typeParams
+              else sym.owner.tpe.typeParams
+            val subst = new SubstTypeMap(tparams, tparams map (_ => WildcardType)) {
+              override def matches(sym: Symbol, sym1: Symbol) =
+                if (sym.isSkolem) matches(sym.deSkolemize, sym1)
+                else if (sym1.isSkolem) matches(sym, sym1.deSkolemize)
+                else super[SubstTypeMap].matches(sym, sym1) 
+            }
+            // allow defaults on by-name parameters
+            if (sym hasFlag BYNAMEPARAM)
+              if (tpt1.tpe.typeArgs.isEmpty) WildcardType // during erasure tpt1 is Function0
+              else subst(tpt1.tpe.typeArgs(0))
+            else subst(tpt1.tpe)
+          } else tpt1.tpe
+          newTyper(typer1.context.make(vdef, sym)).transformedOrTyped(vdef.rhs, EXPRmode | BYVALmode, tpt2)
         }
-      copy.ValDef(vdef, typedMods, vdef.name, tpt1, checkDead(rhs1)) setType NoType
+      treeCopy.ValDef(vdef, typedMods, vdef.name, tpt1, checkDead(rhs1)) setType NoType
     }
 
     /** Enter all aliases of local parameter accessors.
@@ -1263,18 +1613,15 @@ trait Typers { self: Analyzer =>
      *  @param rhs      ...
      */
     def computeParamAliases(clazz: Symbol, vparamss: List[List[ValDef]], rhs: Tree) {
-      if (settings.debug.value) log("computing param aliases for "+clazz+":"+clazz.primaryConstructor.tpe+":"+rhs);//debug
+      if (settings.debug.value) log("computing param aliases for "+clazz+":"+clazz.primaryConstructor.tpe+":"+rhs)//debug
       def decompose(call: Tree): (Tree, List[Tree]) = call match {
         case Apply(fn, args) =>
           val (superConstr, args1) = decompose(fn)
-          val formals = (if (fn.tpe == null && inIDE) ErrorType else fn.tpe).paramTypes
-          val args2 = if (formals.isEmpty || formals.last.typeSymbol != RepeatedParamClass) args
-                      else args.take(formals.length - 1) ::: List(EmptyTree)
-          if (args2.length != formals.length) {
-            if (!inIDE)          
-              assert(false, "mismatch " + clazz + " " + formals + " " + args2);//debug
-            else error(call.pos, "XXX: mismatch " + clazz + " " + formals + " " + args2)
-          } 
+          val params = fn.tpe.params
+          val args2 = if (params.isEmpty || !isRepeatedParamType(params.last.tpe)) args
+                      else args.take(params.length - 1) ::: List(EmptyTree)
+          if (args2.length != params.length)
+            assert(false, "mismatch " + clazz + " " + (params map (_.tpe)) + " " + args2)//debug 
           (superConstr, args1 ::: args2)
         case Block(stats, expr) if !stats.isEmpty =>
           decompose(stats.last)
@@ -1283,12 +1630,21 @@ trait Typers { self: Analyzer =>
       }
       val (superConstr, superArgs) = decompose(rhs)
       assert(superConstr.symbol ne null)//debug
+      
+      // an object cannot be allowed to pass a reference to itself to a superconstructor
+      // because of initialization issues; bug #473
+      for { 
+        arg <- superArgs
+        val sym = arg.symbol
+        if sym != null && sym.isModule && (sym.info.baseClasses contains clazz)
+      } error(rhs.pos, "super constructor cannot be passed a self reference unless parameter is declared by-name")
+      
       if (superConstr.symbol.isPrimaryConstructor) {
         val superClazz = superConstr.symbol.owner
         if (!superClazz.hasFlag(JAVA)) {
           val superParamAccessors = superClazz.constrParamAccessors
           if (superParamAccessors.length == superArgs.length) {
-            List.map2(superParamAccessors, superArgs) { (superAcc, superArg) =>
+            (superParamAccessors, superArgs).zipped map { (superAcc, superArg) =>
               superArg match {
                 case Ident(name) =>
                   if (vparamss.exists(_.exists(_.symbol == superArg.symbol))) {
@@ -1304,7 +1660,7 @@ trait Typers { self: Analyzer =>
                         ownAcc = ownAcc.accessed
                       if (!ownAcc.isVariable && !alias.accessed.isVariable) {
                         if (settings.debug.value)
-                          log("" + ownAcc + " has alias "+alias + alias.locationString);//debug
+                          log("" + ownAcc + " has alias "+alias + alias.locationString) //debug
                         ownAcc.asInstanceOf[TermSymbol].setAlias(alias)
                       }
                     }
@@ -1313,21 +1669,71 @@ trait Typers { self: Analyzer =>
               }
               ()
             }
-          } else if (inIDE) { // XXX: maybe add later
-            Console.println("" + superClazz + ":" +
-              superClazz.info.decls.toList.filter(_.hasFlag(PARAMACCESSOR)))
-            error(rhs.pos, "mismatch: " + superParamAccessors +
-              ";" + rhs + ";" + superClazz.info.decls)//debug
-            return                          
           }
         }
       }
     }
+      
+    /** Check if a method is defined in such a way that it can be called.
+      * A method cannot be called if it is a non-private member of a structural type
+      * and if its parameter's types are not one of
+      * - this.type
+      * - a type member of the structural type
+      * - an abstract type declared outside of the structural type. */
+    def checkMethodStructuralCompatible(meth: Symbol): Unit =
+      if (meth.owner.isStructuralRefinement && meth.allOverriddenSymbols.isEmpty && (!meth.hasFlag(PRIVATE) && meth.privateWithin == NoSymbol)) {
+        val tp: Type = meth.tpe match {
+          case mt: MethodType => mt
+          case pt: PolyType => pt.resultType
+          case _ => NoType
+        }
+        for (paramType <- tp.paramTypes)  {
+          if (paramType.typeSymbol.isAbstractType && !(paramType.typeSymbol.hasTransOwner(meth.owner)))
+            unit.error(meth.pos,"Parameter type in structural refinement may not refer to an abstract type defined outside that refinement")
+          else if (paramType.typeSymbol.isAbstractType && !(paramType.typeSymbol.hasTransOwner(meth)))
+            unit.error(meth.pos,"Parameter type in structural refinement may not refer to a type member of that refinement")
+          else if (paramType.isInstanceOf[ThisType] && paramType.typeSymbol == meth.owner)
+            unit.error(meth.pos,"Parameter type in structural refinement may not refer to the type of that refinement (self type)")
+        }
+      }
 
-    private def checkStructuralCondition(refinement: Symbol, vparam: ValDef) {
-      val tp = vparam.symbol.tpe
-      if (tp.typeSymbol.isAbstractType && !(tp.typeSymbol.hasTransOwner(refinement)))
-        error(vparam.tpt.pos,"Parameter type in structural refinement may not refer to abstract type defined outside that same refinement")
+    def typedUseCase(useCase: UseCase) {
+      def stringParser(str: String): syntaxAnalyzer.Parser = {
+        val file = new BatchSourceFile(context.unit.source.file, str) {
+          override def positionInUltimateSource(pos: Position) = {
+            pos.withSource(context.unit.source, useCase.pos.start)
+          }
+        }
+        val unit = new CompilationUnit(file)
+        new syntaxAnalyzer.UnitParser(unit)
+      }
+      val trees = stringParser(useCase.body+";").nonLocalDefOrDcl
+      val enclClass = context.enclClass.owner
+      def defineAlias(name: Name) =
+        if (context.scope.lookup(name) == NoSymbol) {
+          lookupVariable(name.toString.substring(1), enclClass) match {
+            case Some(repl) =>
+              silent(_.typedTypeConstructor(stringParser(repl).typ())) match {
+                case tpt: Tree =>
+                  val alias = enclClass.newAliasType(useCase.pos, name)
+                  val tparams = cloneSymbols(tpt.tpe.typeSymbol.typeParams, alias)
+                  alias setInfo polyType(tparams, appliedType(tpt.tpe, tparams map (_.tpe)))
+                  context.scope.enter(alias)
+                case _ =>
+              }
+            case _ =>
+          }
+        }
+      for (tree <- trees; t <- tree)
+        t match {
+          case Ident(name) if (name.length > 0 && name(0) == '$') => defineAlias(name)
+          case _ =>
+        }
+      useCase.aliases = context.scope.toList
+      namer.enterSyms(trees)
+      typedStats(trees, NoSymbol)
+      useCase.defined = context.scope.toList filterNot (useCase.aliases contains _)
+//      println("defined use cases: "+(useCase.defined map (sym => sym+":"+sym.tpe)))
     }
 
     /**
@@ -1336,18 +1742,32 @@ trait Typers { self: Analyzer =>
      */
     def typedDefDef(ddef: DefDef): DefDef = {
       val meth = ddef.symbol
-      if (inIDE && meth == NoSymbol) throw new TypeError("bad signature")
+   
       reenterTypeParams(ddef.tparams)
       reenterValueParams(ddef.vparamss)
-      val tparams1 = List.mapConserve(ddef.tparams)(typedTypeDef)
-      val vparamss1 = List.mapConserve(ddef.vparamss)(vparams1 =>
-        List.mapConserve(vparams1)(typedValDef))
-      for (vparams1 <- vparamss1; if !vparams1.isEmpty; vparam1 <- vparams1.init) {
-        if (vparam1.symbol.tpe.typeSymbol == RepeatedParamClass)
-          error(vparam1.pos, "*-parameter must come last")
+
+      // for `val` and `var` parameter, look at `target` meta-annotation
+      if (phase.id <= currentRun.typerPhase.id && meth.isPrimaryConstructor) {
+        for (vparams <- ddef.vparamss; vd <- vparams) {
+          if (vd hasFlag PARAMACCESSOR) {
+            val sym = vd.symbol
+            sym.setAnnotations(memberAnnots(sym.annotations, ParamTargetClass, keepClean = true))
+          }
+        }
       }
-      var tpt1 = checkNoEscaping.privates(meth, typedType(ddef.tpt))           
-      if (!settings.Xexperimental.value) {
+      
+      val tparams1 = ddef.tparams mapConserve typedTypeDef
+      val vparamss1 = ddef.vparamss mapConserve (_ mapConserve typedValDef)
+      
+      // complete lazy annotations
+      val annots = meth.annotations
+      
+      for (vparams1 <- vparamss1; vparam1 <- vparams1 dropRight 1)
+        if (isRepeatedParamType(vparam1.symbol.tpe))
+          error(vparam1.pos, "*-parameter must come last")
+
+      var tpt1 = checkNoEscaping.privates(meth, typedType(ddef.tpt))
+      if (!settings.YdepMethTpes.value) {
         for (vparams <- vparamss1; vparam <- vparams) {
           checkNoEscaping.locals(context.scope, WildcardType, vparam.tpt); ()
         }
@@ -1355,9 +1775,9 @@ trait Typers { self: Analyzer =>
       }
       checkNonCyclic(ddef, tpt1)
       ddef.tpt.setType(tpt1.tpe)
-      val typedMods = typedModifiers(ddef.mods)
+      val typedMods = removeAnnotations(ddef.mods)
       var rhs1 = 
-        if (ddef.name == nme.CONSTRUCTOR) {
+        if (ddef.name == nme.CONSTRUCTOR && !ddef.symbol.hasFlag(STATIC)) { // need this to make it possible to generate static ctors
           if (!meth.isPrimaryConstructor &&
               (!meth.owner.isClass ||
                meth.owner.isModuleClass ||
@@ -1366,34 +1786,56 @@ trait Typers { self: Analyzer =>
             error(ddef.pos, "constructor definition not allowed here")
           typed(ddef.rhs)
         } else {
-          if (inIDE && ddef.rhs == EmptyTree) EmptyTree
-          else transformedOrTyped(ddef.rhs, tpt1.tpe)
+          transformedOrTyped(ddef.rhs, EXPRmode, tpt1.tpe)
         }
+      
       if (meth.isPrimaryConstructor && meth.isClassConstructor && 
           phase.id <= currentRun.typerPhase.id && !reporter.hasErrors)
         computeParamAliases(meth.owner, vparamss1, rhs1)
       if (tpt1.tpe.typeSymbol != NothingClass && !context.returnsSeen) rhs1 = checkDead(rhs1)
-      
-      if (meth.owner.isRefinementClass && meth.allOverriddenSymbols.isEmpty)
-        for (vparams <- ddef.vparamss; vparam <- vparams) 
-          checkStructuralCondition(meth.owner, vparam)
 
-      copy.DefDef(ddef, typedMods, ddef.name, tparams1, vparamss1, tpt1, rhs1) setType NoType
+      if (phase.id <= currentRun.typerPhase.id && meth.owner.isClass &&
+          meth.paramss.exists(ps => ps.exists(_.hasFlag(DEFAULTPARAM)) && isRepeatedParamType(ps.last.tpe)))
+        error(meth.pos, "a parameter section with a `*'-parameter is not allowed to have default arguments")
+
+      checkMethodStructuralCompatible(meth)
+
+      treeCopy.DefDef(ddef, typedMods, ddef.name, tparams1, vparamss1, tpt1, rhs1) setType NoType
     }
 
     def typedTypeDef(tdef: TypeDef): TypeDef = {
-      reenterTypeParams(tdef.tparams) // @M!
-      val tparams1 = List.mapConserve(tdef.tparams)(typedTypeDef) // @M!
-      val typedMods = typedModifiers(tdef.mods)
+      def typeDefTyper = {
+        if(tdef.tparams isEmpty) Typer.this
+        else newTyper(context.makeNewScope(tdef, tdef.symbol))
+      }
+      typeDefTyper.typedTypeDef0(tdef)
+    }
+
+    // call typedTypeDef instead
+    // a TypeDef with type parameters must always be type checked in a new scope
+    private def typedTypeDef0(tdef: TypeDef): TypeDef = {
+      reenterTypeParams(tdef.tparams)
+      val tparams1 = tdef.tparams mapConserve {typedTypeDef(_)}
+      val typedMods = removeAnnotations(tdef.mods)
+      // complete lazy annotations
+      val annots = tdef.symbol.annotations
+
+      // @specialized should not be pickled when compiling with -no-specialize
+      if (settings.nospecialization.value && currentRun.compiles(tdef.symbol)) {
+        tdef.symbol.removeAnnotation(definitions.SpecializedClass)
+        tdef.symbol.deSkolemize.removeAnnotation(definitions.SpecializedClass)
+      }
+
       val rhs1 = checkNoEscaping.privates(tdef.symbol, typedType(tdef.rhs))
       checkNonCyclic(tdef.symbol)
-      rhs1.tpe match {
-        case TypeBounds(lo1, hi1) =>
-          if (!(lo1 <:< hi1))
-            error(tdef.pos, "lower bound "+lo1+" does not conform to upper bound "+hi1)
-        case _ =>
-      }
-      copy.TypeDef(tdef, typedMods, tdef.name, tparams1, rhs1) setType NoType
+      if (tdef.symbol.owner.isType) 
+        rhs1.tpe match {
+          case TypeBounds(lo1, hi1) =>
+            if (!(lo1 <:< hi1))
+              error(tdef.pos, "lower bound "+lo1+" does not conform to upper bound "+hi1)
+          case _ =>
+        }
+      treeCopy.TypeDef(tdef, typedMods, tdef.name, tparams1, rhs1) setType NoType
     }
 
     private def enterLabelDef(stat: Tree) {
@@ -1406,11 +1848,31 @@ trait Typers { self: Analyzer =>
       }
     }
 
+    private def isLoopHeaderLabel(name: Name): Boolean =
+      name.startsWith("while$") || name.startsWith("doWhile$")
+
     def typedLabelDef(ldef: LabelDef): LabelDef = {
-      val restpe = ldef.symbol.tpe.resultType
-      val rhs1 = typed(ldef.rhs, restpe)
-      ldef.params foreach (param => param.tpe = param.symbol.tpe)
-      copy.LabelDef(ldef, ldef.name, ldef.params, rhs1) setType restpe
+      if (!isLoopHeaderLabel(ldef.symbol.name) || phase.id > currentRun.typerPhase.id) {
+        val restpe = ldef.symbol.tpe.resultType
+        val rhs1 = typed(ldef.rhs, restpe)
+        ldef.params foreach (param => param.tpe = param.symbol.tpe)
+        treeCopy.LabelDef(ldef, ldef.name, ldef.params, rhs1) setType restpe
+      } else {
+        val initpe = ldef.symbol.tpe.resultType
+        val rhs1 = typed(ldef.rhs)
+        val restpe = rhs1.tpe
+        if (restpe == initpe) { // stable result, no need to check again
+          ldef.params foreach (param => param.tpe = param.symbol.tpe)
+          treeCopy.LabelDef(ldef, ldef.name, ldef.params, rhs1) setType restpe
+        } else {
+          context.scope.unlink(ldef.symbol)
+          val sym2 = namer.enterInScope(
+            context.owner.newLabel(ldef.pos, ldef.name) setInfo MethodType(List(), restpe))
+          val rhs2 = typed(resetAllAttrs(ldef.rhs), restpe)
+          ldef.params foreach (param => param.tpe = param.symbol.tpe)
+          treeCopy.LabelDef(ldef, ldef.name, ldef.params, rhs2) setSymbol sym2 setType restpe
+        }
+      }
     }
 
     protected def typedFunctionIDE(fun : Function, txt : Context) = {}
@@ -1422,21 +1884,78 @@ trait Typers { self: Analyzer =>
      *  @return      ...
      */
     def typedBlock(block: Block, mode: Int, pt: Type): Block = {
-      if (context.retyping) {
+      val syntheticPrivates = new ListBuffer[Symbol]
+      try {
+        namer.enterSyms(block.stats)
         for (stat <- block.stats) {
-          if (stat.isDef) context.scope.enter(stat.symbol)
+          if (onlyPresentation && stat.isDef) {
+            var e = context.scope.lookupEntry(stat.symbol.name)
+            while ((e ne null) && (e.sym ne stat.symbol)) e = e.tail
+            if (e eq null) context.scope.enter(stat.symbol)
+          }
+          enterLabelDef(stat)
         }
+
+        if (phaseId(currentPeriod) <= currentRun.typerPhase.id) {
+          // This is very tricky stuff, because we are navigating
+          // the Skylla and Charybdis of anonymous classes and what to return
+          // from them here. On the one hand, we cannot admit
+          // every non-private member of an anonymous class as a part of
+          // the structural type of the enclosing block. This runs afoul of
+          // the restriction that a structural type may not refer to an enclosing
+          // type parameter or abstract types (which in turn is necessitated
+          // by what can be done in Java reflection. On the other hand,
+          // making every term member private conflicts with private escape checking
+          // see ticket #3174 for an example.
+          // The cleanest way forward is if we would find a way to suppress
+          // structural type checking for these members and maybe defer 
+          // type errors to the places where members are called. But that would
+          // be a bug refactoring and also a  big departure from existing code.
+          // The probably safest fix for 2.8 is to keep members of an anonymous
+          // class that are not mentioned in a parent type private (as before)
+          // but to disable escape checking for code that's in the same anonymous class.
+          // That's what's done here. 
+          // We really should go back and think hard whether we find a better
+          // way to address the problem of escaping idents on the one hand and well-formed
+          // structural types on the other.
+          block match {
+            case block @ Block(List(classDef @ ClassDef(_, _, _, _)), newInst @ Apply(Select(New(_), _), _)) =>
+              // The block is an anonymous class definitions/instantiation pair
+              //   -> members that are hidden by the type of the block are made private
+              val visibleMembers = pt match {
+                case WildcardType => classDef.symbol.info.decls.toList
+                case BoundedWildcardType(TypeBounds(lo, hi)) => lo.members
+                case _ => pt.members
+              }
+              for (member <- classDef.symbol.info.decls.toList
+                   if member.isTerm && !member.isConstructor &&
+                      member.allOverriddenSymbols.isEmpty &&
+                      (!member.hasFlag(PRIVATE) && member.privateWithin == NoSymbol) &&
+                      !(visibleMembers exists { visible =>
+                        visible.name == member.name &&
+                        member.tpe <:< visible.tpe.substThis(visible.owner, ThisType(classDef.symbol))
+                      })
+              ) {
+                member.resetFlag(PROTECTED)
+                member.resetFlag(LOCAL)
+                member.setFlag(PRIVATE | SYNTHETIC_PRIVATE)
+                syntheticPrivates += member
+                member.privateWithin = NoSymbol
+              }
+            case _ =>
+          }
+        }
+        val stats1 = typedStats(block.stats, context.owner)
+        val expr1 = typed(block.expr, mode & ~(FUNmode | QUALmode), pt)
+        treeCopy.Block(block, stats1, expr1)
+          .setType(if (treeInfo.isPureExpr(block)) expr1.tpe else expr1.tpe.deconst)
+      } finally {
+        // enable escaping privates checking from the outside and recycle
+        // transient flag
+        for (sym <- syntheticPrivates) sym resetFlag SYNTHETIC_PRIVATE
       }
-      namer.enterSyms(block.stats)
-      block.stats foreach enterLabelDef
-      val stats1 = typedStats(block.stats, context.owner)
-      val expr1 = typed(block.expr, mode & ~(FUNmode | QUALmode), pt)
-      val block1 = copy.Block(block, stats1, expr1)
-        .setType(if (treeInfo.isPureExpr(block)) expr1.tpe else expr1.tpe.deconst)
-      //checkNoEscaping.locals(context.scope, pt, block1)
-      block1
     }
-
+ 
     /**
      *  @param cdef   ...
      *  @param pattpe ...
@@ -1444,6 +1963,10 @@ trait Typers { self: Analyzer =>
      *  @return       ...
      */
     def typedCase(cdef: CaseDef, pattpe: Type, pt: Type): CaseDef = {
+      // verify no _* except in last position      
+      for (Apply(_, xs) <- cdef.pat ; x <- xs dropRight 1 ; if treeInfo isStar x)
+        error(x.pos, "_* may only come last")
+        
       val pat1: Tree = typedPattern(cdef.pat, pattpe)
       val guard1: Tree = if (cdef.guard == EmptyTree) EmptyTree
                          else typed(cdef.guard, BooleanClass.tpe)
@@ -1460,13 +1983,13 @@ trait Typers { self: Analyzer =>
         }
       }
 //    body1 = checkNoEscaping.locals(context.scope, pt, body1)
-      copy.CaseDef(cdef, pat1, guard1, body1) setType body1.tpe
+      treeCopy.CaseDef(cdef, pat1, guard1, body1) setType body1.tpe
     }
 
     def typedCases(tree: Tree, cases: List[CaseDef], pattp0: Type, pt: Type): List[CaseDef] = {
       var pattp = pattp0
-      List.mapConserve(cases) ( cdef => 
-        newTyper(context.makeNewScope(cdef, context.owner)(TypedCasesScopeKind))
+      cases mapConserve (cdef => 
+        newTyper(context.makeNewScope(cdef, context.owner))
           .typedCase(cdef, pattp, pt))
 /* not yet!
         cdef.pat match {
@@ -1486,14 +2009,17 @@ trait Typers { self: Analyzer =>
      *  @return     ...
      */
     def typedFunction(fun: Function, mode: Int, pt: Type): Tree = {
-      val codeExpected = !forCLDC && !forMSIL && (pt.typeSymbol isNonBottomSubClass CodeClass)
+      val codeExpected = !forMSIL && (pt.typeSymbol isNonBottomSubClass CodeClass)
+      
+      if (fun.vparams.length > definitions.MaxFunctionArity)
+        return errorTree(fun, "implementation restricts functions to " + definitions.MaxFunctionArity + " parameters")
 
       def decompose(pt: Type): (Symbol, List[Type], Type) =
         if ((isFunctionType(pt)
              || 
              pt.typeSymbol == PartialFunctionClass && 
              fun.vparams.length == 1 && fun.body.isInstanceOf[Match]) 
-             && // see bug901 for a reason why next conditions are neeed
+             && // see bug901 for a reason why next conditions are needed
             (pt.normalize.typeArgs.length - 1 == fun.vparams.length 
              || 
              fun.vparams.exists(_.tpt.isEmpty)))
@@ -1506,7 +2032,7 @@ trait Typers { self: Analyzer =>
       if (fun.vparams.length != argpts.length)
         errorTree(fun, "wrong number of parameters; expected = " + argpts.length)
       else {
-        val vparamSyms = List.map2(fun.vparams, argpts) { (vparam, argpt) =>
+        val vparamSyms = (fun.vparams, argpts).zipped map { (vparam, argpt) =>
           if (vparam.tpt.isEmpty) {
             vparam.tpt.tpe = 
               if (isFullyDefined(argpt)) argpt
@@ -1532,13 +2058,14 @@ trait Typers { self: Analyzer =>
                    else ""))
                 ErrorType 
               }
+            if (!vparam.tpt.pos.isDefined) vparam.tpt setPos vparam.pos.focus
           }
           enterSym(context, vparam)
           if (context.retyping) context.scope enter vparam.symbol
           vparam.symbol
         }
 
-        val vparams = List.mapConserve(fun.vparams)(typedValDef)
+        val vparams = fun.vparams mapConserve (typedValDef)
 //        for (vparam <- vparams) {
 //          checkNoEscaping.locals(context.scope, WildcardType, vparam.tpt); ()
 //        }
@@ -1547,7 +2074,7 @@ trait Typers { self: Analyzer =>
         val restpe = packedType(body, fun.symbol).deconst
         val funtpe = typeRef(clazz.tpe.prefix, clazz, formals ::: List(restpe))
 //        body = checkNoEscaping.locals(context.scope, restpe, body)
-        val fun1 = copy.Function(fun, vparams, body).setType(funtpe)
+        val fun1 = treeCopy.Function(fun, vparams, body).setType(funtpe)
         if (codeExpected) {
           val liftPoint = Apply(Select(Ident(CodeModule), nme.lift_), List(fun1))
           typed(atPos(fun.pos)(liftPoint))
@@ -1555,54 +2082,58 @@ trait Typers { self: Analyzer =>
       }
     }
 
-    def typedRefinement(stats: List[Tree]): List[Tree] = {
+    def typedRefinement(stats: List[Tree]) {
       namer.enterSyms(stats)
-      val stats1 = typedStats(stats, NoSymbol)
-      for (stat <- stats1 if stat.isDef) {
-        val member = stat.symbol
-        if (!(context.owner.info.baseClasses.tail forall
-            (bc => member.matchingSymbol(bc, context.owner.thisType) == NoSymbol))) {
-          member setFlag OVERRIDE
+      // need to delay rest of typedRefinement to avoid cyclic reference errors
+      unit.toCheck += { () =>
+        val stats1 = typedStats(stats, NoSymbol)
+        for (stat <- stats1 if stat.isDef) {
+          val member = stat.symbol
+          if (!(context.owner.ancestors forall
+                (bc => member.matchingSymbol(bc, context.owner.thisType) == NoSymbol))) {
+                  member setFlag OVERRIDE
+                }
         }
       }
-      stats1
     }
 
     def typedImport(imp : Import) : Import = imp
 
     def typedStats(stats: List[Tree], exprOwner: Symbol): List[Tree] = {
-
       val inBlock = exprOwner == context.owner
-
+      def includesTargetPos(tree: Tree) = 
+        tree.pos.isRange && context.unit != null && (tree.pos includes context.unit.targetPos)
+      val localTarget = stats exists includesTargetPos
       def typedStat(stat: Tree): Tree = {
         if (context.owner.isRefinementClass && !treeInfo.isDeclaration(stat))
           errorTree(stat, "only declarations allowed here")
-        stat match {
-          case imp @ Import(_, _) =>
-            val imp0 = typedImport(imp)
-            if (imp0 ne null) {
-              context = context.makeNewImport(imp0)
-              imp0.symbol.initialize
-            }
-            if ((imp0 ne null) && inIDE) {
-              imp0.symbol.info match {
-              case ImportType(exr) => 
-                imp0.expr.tpe = exr.tpe
-              case _ =>
+        else 
+          stat match {
+            case imp @ Import(_, _) =>
+              val imp0 = typedImport(imp)
+              if (imp0 ne null) {
+                context = context.makeNewImport(imp0)
+                imp0.symbol.initialize
+                imp0
+              } else
+                EmptyTree
+            case _ =>
+              if (localTarget && !includesTargetPos(stat)) { 
+                // skip typechecking of statements in a sequence where some other statement includes
+                // the targetposition
+                stat
+              } else {
+                val localTyper = if (inBlock || (stat.isDef && !stat.isInstanceOf[LabelDef])) this
+                                 else newTyper(context.make(stat, exprOwner))
+                val result = checkDead(localTyper.typed(stat, EXPRmode | BYVALmode, WildcardType))
+                if (treeInfo.isSelfOrSuperConstrCall(result)) {
+                  context.inConstructorSuffix = true
+                  if (treeInfo.isSelfConstrCall(result) && result.symbol.pos.pointOrElse(0) >= exprOwner.enclMethod.pos.pointOrElse(0))
+                    error(stat.pos, "called constructor's definition must precede calling constructor's definition")
+                }
+                result
               }
-              imp0
-            } else EmptyTree
-          case _ =>
-            val localTyper = if (inBlock || (stat.isDef && !stat.isInstanceOf[LabelDef])) this
-                             else newTyper(context.make(stat, exprOwner))
-            val result = checkDead(localTyper.typed(stat))
-            if (treeInfo.isSelfOrSuperConstrCall(result)) {
-              context.inConstructorSuffix = true
-              if (!inIDE && treeInfo.isSelfConstrCall(result) && result.symbol.pos.offset.getOrElse(0) >= exprOwner.enclMethod.pos.offset.getOrElse(0))
-                error(stat.pos, "called constructor's definition must precede calling constructor's definition")
-            }
-            result
-        }
+          }
       }
 
       def accesses(accessor: Symbol, accessed: Symbol) = 
@@ -1611,36 +2142,58 @@ trait Typers { self: Analyzer =>
         !(accessed hasFlag ACCESSOR) && accessed.isPrivateLocal
 
       def checkNoDoubleDefsAndAddSynthetics(stats: List[Tree]): List[Tree] = {
-        val scope = if (inBlock) context.scope else context.owner.info.decls;
+        val scope = if (inBlock) context.scope else context.owner.info.decls
         val newStats = new ListBuffer[Tree]
-        var e = scope.elems;
-        while ((e ne null) && e.owner == scope) {
-
-          // check no double def
-          var e1 = scope.lookupNextEntry(e);
-          while ((e1 ne null) && e1.owner == scope) {
-            if (!accesses(e.sym, e1.sym) && !accesses(e1.sym, e.sym) && 
-                (e.sym.isType || inBlock || (e.sym.tpe matches e1.sym.tpe)))
-              if (!e.sym.isErroneous && !e1.sym.isErroneous && !inIDE)
-                error(e.sym.pos, e1.sym+" is defined twice"+
-                      {if(!settings.debug.value) "" else " in "+unit.toString})
-            e1 = scope.lookupNextEntry(e1);
-          }
+        var needsCheck = true
+        var moreToAdd = true
+        while (moreToAdd) {
+          val initSize = scope.size
+          var e = scope.elems
+          while ((e ne null) && e.owner == scope) {
+
+            // check no double def
+            if (needsCheck) {
+              var e1 = scope.lookupNextEntry(e)
+              while ((e1 ne null) && e1.owner == scope) {
+                if (!accesses(e.sym, e1.sym) && !accesses(e1.sym, e.sym) && 
+                    (e.sym.isType || inBlock || (e.sym.tpe matches e1.sym.tpe)))
+                  // default getters are defined twice when multiple overloads have defaults. an
+                  // error for this is issued in RefChecks.checkDefaultsInOverloaded
+                  if (!e.sym.isErroneous && !e1.sym.isErroneous && !e.sym.hasFlag(DEFAULTPARAM)) {
+                    error(e.sym.pos, e1.sym+" is defined twice"+
+                          {if(!settings.debug.value) "" else " in "+unit.toString})
+                    scope.unlink(e1) // need to unlink to avoid later problems with lub; see #2779
+                  }
+                e1 = scope.lookupNextEntry(e1)
+              }
+            }
 
           // add synthetics
           context.unit.synthetics get e.sym match {
             case Some(tree) =>
-              newStats += tree
+              newStats += typedStat(tree) // might add even more synthetics to the scope
               context.unit.synthetics -= e.sym
             case _ =>
           }
 
           e = e.next
         }
-        if (newStats.isEmpty) stats 
-        else stats ::: (newStats.toList map typedStat)
+        needsCheck = false
+        // the type completer of a synthetic might add more synthetics. example: if the
+        // factory method of a case class (i.e. the constructor) has a default.
+        moreToAdd = initSize != scope.size
+        }
+        if (newStats.isEmpty) stats
+        else {
+          val (defaultGetters, others) = newStats.toList.partition {
+            case DefDef(mods, _, _, _, _, _) => mods.hasFlag(DEFAULTPARAM)
+            case _ => false
+          }
+          // default getters first: see #2489
+          defaultGetters ::: stats ::: others
+        }
       }
-      val result = List.mapConserve(stats)(typedStat)
+      val result = stats mapConserve (typedStat)
       if (phase.erasedTypes) result
       else checkNoDoubleDefsAndAddSynthetics(result)
     }
@@ -1649,46 +2202,14 @@ trait Typers { self: Analyzer =>
       checkDead(constrTyperIf((mode & SCCmode) != 0).typed(arg, mode & stickyModes | newmode, pt))
 
     def typedArgs(args: List[Tree], mode: Int) =
-      List.mapConserve(args)(arg => typedArg(arg, mode, 0, WildcardType))
+      args mapConserve (arg => typedArg(arg, mode, 0, WildcardType))
 
     def typedArgs(args: List[Tree], mode: Int, originalFormals: List[Type], adaptedFormals: List[Type]) = {
-      if (isVarArgs(originalFormals)) {
-        val nonVarCount = originalFormals.length - 1
-        val prefix =
-          List.map2(args take nonVarCount, adaptedFormals take nonVarCount) ((arg, formal) =>
-            typedArg(arg, mode, 0, formal))
-
-        // if array is passed into java vararg and formal's element is not an array,
-        // convert it to vararg by adding : _*
-        // this is a gross hack to enable vararg transition; remove it as soon as possible.
-        // !!!VARARG-CONVERSION!!!
-        def hasArrayElement(tpe: Type) = 
-          tpe.typeArgs.length == 1 && tpe.typeArgs.head.typeSymbol == ArrayClass
-        var args0 = args 
-        if ((mode & JAVACALLmode) != 0 && 
-            (args.length == originalFormals.length) &&
-            !hasArrayElement(adaptedFormals(nonVarCount)) &&
-            !settings.XnoVarargsConversion.value) {
-              val lastarg = typedArg(args(nonVarCount), mode, REGPATmode, WildcardType)
-              if ((lastarg.tpe.typeSymbol == ArrayClass || lastarg.tpe.typeSymbol == NullClass) &&
-                  !treeInfo.isWildcardStarArg(lastarg)) {
-                if (lastarg.tpe.typeSymbol == ArrayClass)
-                  unit.warning(
-                    lastarg.pos,
-                    "I'm seeing an array passed into a Java vararg.\n"+
-                    "I assume that the elements of this array should be passed as individual arguments to the vararg.\n"+
-                    "Therefore I follow the array with a `: _*', to mark it as a vararg argument.\n"+
-                    "If that's not what you want, compile this file with option -Xno-varargs-conversion.")
-                args0 = args.init ::: List(gen.wildcardStar(args.last))
-              }
-            }
-        val suffix =
-          List.map2(args0 drop nonVarCount, adaptedFormals drop nonVarCount) ((arg, formal) =>
-            typedArg(arg, mode, REGPATmode, formal))
-        prefix ::: suffix
-      } else {
-        List.map2(args, adaptedFormals)((arg, formal) => typedArg(arg, mode, 0, formal))
-      }
+      var newmodes = originalFormals map ((tp: Type) => if (tp.typeSymbol != ByNameParamClass) BYVALmode else 0)
+      if (isVarArgTpes(originalFormals)) // TR check really necessary?
+        newmodes = newmodes.take(newmodes.length-1) ::: List.fill(args.length - originalFormals.length + 1)(STARmode | BYVALmode)
+      for (((arg, formal), m) <- ((args zip adaptedFormals) zip newmodes)) yield
+        typedArg(arg, mode, m, formal)
     }
 
     /** Does function need to be instantiated, because a missing parameter
@@ -1699,13 +2220,13 @@ trait Typers { self: Analyzer =>
         val losym = tparam.info.bounds.lo.typeSymbol
         losym != NothingClass && losym != NullClass
       }
-      List.exists2(formals, args) { 
+      (formals, args).zipped exists { 
         case (formal, Function(vparams, _)) =>
           (vparams exists (_.tpt.isEmpty)) &&
           vparams.length <= MaxFunctionArity &&
           (formal baseType FunctionClass(vparams.length) match {
             case TypeRef(_, _, formalargs) =>
-              List.exists2(formalargs, vparams) ((formalarg, vparam) =>
+              (formalargs, vparams).zipped.exists ((formalarg, vparam) =>
                 vparam.tpt.isEmpty && (tparams exists (formalarg contains))) &&
               (tparams forall isLowerBounded)
             case _ =>
@@ -1716,33 +2237,53 @@ trait Typers { self: Analyzer =>
       }
     }
 
-    /**
-     *  @param tree ...
-     *  @param fun0 ...
-     *  @param args ...
-     *  @param mode ...
-     *  @param pt   ...
-     *  @return     ...
+    /** Is `tree' a block created by a named application?
      */
+    def isNamedApplyBlock(tree: Tree) =
+      context.namedApplyBlockInfo exists (_._1 == tree)
+
+    def callToCompanionConstr(context: Context, calledFun: Symbol) = {
+      if (calledFun.isConstructor) {
+        val methCtx = context.enclMethod
+        if (methCtx != NoContext) {
+          val contextFun = methCtx.tree.symbol
+          contextFun.isPrimaryConstructor && contextFun.owner.isModuleClass &&
+          companionModuleOf(calledFun.owner, context).moduleClass == contextFun.owner
+        } else false
+      } else false
+    }
+
     def doTypedApply(tree: Tree, fun0: Tree, args: List[Tree], mode: Int, pt: Type): Tree = {
       var fun = fun0
       if (fun.hasSymbol && (fun.symbol hasFlag OVERLOADED)) {
-        // preadapt symbol to number and shape of arguments given
+        // remove alternatives with wrong number of parameters without looking at types.
+        // less expensive than including them in inferMethodAlternatvie (see below).
         def shapeType(arg: Tree): Type = arg match {
-          case Function(vparams, body) => 
+          case Function(vparams, body) =>
             functionType(vparams map (vparam => AnyClass.tpe), shapeType(body))
+          case AssignOrNamedArg(Ident(name), rhs) =>
+            NamedType(name, shapeType(rhs))
           case _ =>
             NothingClass.tpe
         }
         val argtypes = args map shapeType
         val pre = fun.symbol.tpe.prefix
-        var sym = fun.symbol filter { alt => 
+
+        var sym = fun.symbol filter { alt =>
+          // must use pt as expected type, not WildcardType (a tempting quick fix to #2665)
+          // now fixed by using isWeaklyCompatible in exprTypeArgs
+          // TODO: understand why exactly -- some types were not inferred anymore (`ant clean quick.bin` failed)
+          // (I had expected inferMethodAlternative to pick up the slack introduced by using WildcardType here)
           isApplicableSafe(context.undetparams, followApply(pre.memberType(alt)), argtypes, pt) 
         }
-        //println("narrowed to "+sym+":"+sym.info+"/"+argtypes)
         if (sym hasFlag OVERLOADED) {
-          // eliminate functions that would result from tupling transforms
-          val sym1 = sym filter (alt => hasExactlyNumParams(followApply(alt.tpe), argtypes.length))
+          val sym1 = sym filter (alt => {
+            // eliminate functions that would result from tupling transforms
+            // keeps alternatives with repeated params
+            hasExactlyNumParams(followApply(alt.tpe), argtypes.length) ||
+            // also keep alts which define at least one default
+            alt.tpe.paramss.exists(_.exists(_.hasFlag(DEFAULTPARAM)))
+          })
           if (sym1 != NoSymbol) sym = sym1
         }
         if (sym != NoSymbol)
@@ -1750,29 +2291,142 @@ trait Typers { self: Analyzer =>
       }
       fun.tpe match {
         case OverloadedType(pre, alts) =>
-          val undetparams = context.undetparams
-          context.undetparams = List()
-          val args1 = typedArgs(args, argMode(fun, mode))
+          val undetparams = context.extractUndetparams()
+
+          val argtpes = new ListBuffer[Type]
+          val amode = argMode(fun, mode)
+          val args1 = args map {
+            case arg @ AssignOrNamedArg(Ident(name), rhs) =>
+              // named args: only type the righthand sides ("unknown identifier" errors otherwise)
+              val rhs1 = typedArg(rhs, amode, BYVALmode, WildcardType)
+              argtpes += NamedType(name, rhs1.tpe.deconst)
+              // the assign is untyped; that's ok because we call doTypedApply
+              atPos(arg.pos) { new AssignOrNamedArg(arg.lhs , rhs1) }
+            case arg =>
+              val arg1 = typedArg(arg, amode, BYVALmode, WildcardType)
+              argtpes += arg1.tpe.deconst
+              arg1
+          }
           context.undetparams = undetparams
-          inferMethodAlternative(fun, context.undetparams, args1 map (_.tpe.deconst), pt)
+          inferMethodAlternative(fun, undetparams, argtpes.toList, pt, 
+                                 varArgsOnly = args.nonEmpty && treeInfo.isWildcardStarArg(args.last))
           doTypedApply(tree, adapt(fun, funMode(mode), WildcardType), args1, mode, pt)
-        case mt @ MethodType(formals0, _) =>
-          val formals = formalTypes(formals0, args.length)
-          var args1 = actualArgs(tree.pos, args, formals.length)
-          if (args1.length != args.length) {
-            silent(_.doTypedApply(tree, fun, args1, mode, pt)) match {
-              case t: Tree => t
-              case ex => errorTree(tree, "wrong number of arguments for "+treeSymTypeMsg(fun))
-            }
-          } else if (formals.length != args1.length) {
+
+        case mt @ MethodType(params, _) =>
+          val paramTypes = mt.paramTypes
+          // repeat vararg as often as needed, remove by-name
+          val formals = formalTypes(paramTypes, args.length)
+
+          /** Try packing all arguments into a Tuple and apply `fun'
+           *  to that. This is the last thing which is tried (after
+           *  default arguments)
+           */
+          def tryTupleApply: Option[Tree] = {
+            // if 1 formal, 1 arg (a tuple), otherwise unmodified args
+            val tupleArgs = actualArgs(tree.pos.makeTransparent, args, formals.length)
+
+            if (tupleArgs.length != args.length && !isUnitForVarArgs(args, params)) {
+              // expected one argument, but got 0 or >1 ==>  try applying to tuple
+              // the inner "doTypedApply" does "extractUndetparams" => restore when it fails
+              val savedUndetparams = context.undetparams
+              silent(_.doTypedApply(tree, fun, tupleArgs, mode, pt)) match {
+                case t: Tree => 
+//                  println("tuple conversion to "+t+" for "+mt)//DEBUG
+                  Some(t)
+                case ex =>
+                  context.undetparams = savedUndetparams
+                  None
+              }
+            } else None
+          }
+
+          /** Treats an application which uses named or default arguments.
+           *  Also works if names + a vararg used: when names are used, the vararg
+           *  parameter has to be specified exactly once. Note that combining varargs
+           *  and defaults is ruled out by typedDefDef.
+           */
+          def tryNamesDefaults: Tree = {
             if (mt.isErroneous) setError(tree)
-            else errorTree(tree, "wrong number of arguments for "+treeSymTypeMsg(fun))
+            else if ((mode & PATTERNmode) != 0)
+              // #2064
+              errorTree(tree, "wrong number of arguments for "+ treeSymTypeMsg(fun))
+            else if (args.length > formals.length) {
+              tryTupleApply.getOrElse {
+                errorTree(tree, "too many arguments for "+treeSymTypeMsg(fun))
+              }
+            } else if (args.length == formals.length) {
+              // we don't need defaults. names were used, so this application is transformed
+              // into a block (@see transformNamedApplication in NamesDefaults)
+              val (namelessArgs, argPos) = removeNames(Typer.this)(args, params)
+              if (namelessArgs exists (_.isErroneous)) {
+                setError(tree)
+              } else if (!isIdentity(argPos) && (formals.length != params.length))
+                // !isIdentity indicates that named arguments are used to re-order arguments
+                errorTree(tree, "when using named arguments, the vararg parameter "+
+                                "has to be specified exactly once")
+              else if (isIdentity(argPos) && !isNamedApplyBlock(fun)) {
+                // if there's no re-ordering, and fun is not transformed, no need to transform
+                // more than an optimization, e.g. important in "synchronized { x = update-x }"
+                doTypedApply(tree, fun, namelessArgs, mode, pt)
+              } else {
+                transformNamedApplication(Typer.this, mode, pt)(
+                                          treeCopy.Apply(tree, fun, namelessArgs), argPos)
+              }
+            } else {
+              // defaults are needed. they are added to the argument list in named style as
+              // calls to the default getters. Example:
+              //  foo[Int](a)()  ==>  foo[Int](a)(b = foo$qual.foo$default$2[Int](a))
+              val fun1 = transformNamedApplication(Typer.this, mode, pt)(fun, x => x)
+              if (fun1.isErroneous) setError(tree)
+              else {
+                assert(isNamedApplyBlock(fun1), fun1)
+                val NamedApplyInfo(qual, targs, previousArgss, _) = context.namedApplyBlockInfo.get._2
+                val blockIsEmpty = fun1 match {
+                  case Block(Nil, _) =>
+                    // if the block does not have any ValDef we can remove it. Note that the call to
+                    // "transformNamedApplication" is always needed in order to obtain targs/previousArgss
+                    context.namedApplyBlockInfo = None
+                    true
+                  case _ => false
+                }
+                val (allArgs, missing) = addDefaults(args, qual, targs, previousArgss, params, fun.pos.focus, context)
+                val funSym = fun1 match { case Block(_, expr) => expr.symbol }
+                if (allArgs.length != args.length && callToCompanionConstr(context, funSym)) {
+                  errorTree(tree, "module extending its companion class cannot use default constructor arguments")
+                } else if (allArgs.length == formals.length) {
+                  // useful when a default doesn't match parameter type, e.g. def f[T](x:T="a"); f[Int]()
+                  val note = "Error occurred in an application involving default arguments."
+                  if (!(context.diagnostic contains note)) context.diagnostic = note :: context.diagnostic
+                  doTypedApply(tree, if (blockIsEmpty) fun else fun1, allArgs, mode, pt)
+                } else {
+                  tryTupleApply.getOrElse {
+                    val suffix =
+                      if (missing.isEmpty) ""
+                      else {
+                        val missingStr = missing.take(3).map(_.name).mkString(", ") + (if (missing.length > 3) ", ..." else ".")
+                        val sOpt = if (missing.length > 1) "s" else ""
+                        ".\nUnspecified value parameter"+ sOpt +" "+ missingStr
+                      }
+                    errorTree(tree, "not enough arguments for "+treeSymTypeMsg(fun) + suffix)
+                  }
+                }
+              }
+            }
+          }
+
+          if (formals.length != args.length || // wrong nb of arguments
+              args.exists(isNamed(_)) ||       // uses a named argument
+              isNamedApplyBlock(fun)) {        // fun was transformed to a named apply block =>
+                                               // integrate this application into the block
+            tryNamesDefaults
           } else {
-            val tparams = context.undetparams
-            context.undetparams = List()
-            if (tparams.isEmpty) {
-              val args2 = typedArgs(args1, argMode(fun, mode), formals0, formals)
-              val restpe = mt.resultType(args2 map (_.tpe))
+            val tparams = context.extractUndetparams()
+            if (tparams.isEmpty) { // all type params are defined
+              val args1 = typedArgs(args, argMode(fun, mode), paramTypes, formals)
+              // instantiate dependent method types, must preserve singleton types where possible (stableTypeFor) -- example use case:
+              // val foo = "foo"; def precise(x: String)(y: x.type): x.type = {...}; val bar : foo.type = precise(foo)(foo)
+              // precise(foo) : foo.type => foo.type
+              val restpe = mt.resultType(args1 map (arg => gen.stableTypeFor(arg) getOrElse arg.tpe))
               def ifPatternSkipFormals(tp: Type) = tp match {
                 case MethodType(_, rtp) if ((mode & PATTERNmode) != 0) => rtp
                 case _ => tp
@@ -1792,43 +2446,60 @@ trait Typers { self: Analyzer =>
                        // the compiler thinks, the PLUS method takes only one argument,
                        // but he thinks it's an instance method -> still two ref's on the stack
                        //  -> translated by backend
-                       val rhs = copy.Apply(tree, f, args1)
+                       val rhs = treeCopy.Apply(tree, f, args)
                        return typed(Assign(qual, rhs))
                      }
                   case _ => ()
                 }
               }
 
-              if (!inIDE && fun.symbol == List_apply && args.isEmpty) {
+              if (fun.symbol == List_apply && args.isEmpty && !onlyPresentation) {
                 atPos(tree.pos) { gen.mkNil setType restpe }
-              } else
-                constfold(copy.Apply(tree, fun, args2).setType(ifPatternSkipFormals(restpe)))
-            } else if (needsInstantiation(tparams, formals, args1)) {
+              } else {
+                constfold(treeCopy.Apply(tree, fun, args1).setType(ifPatternSkipFormals(restpe)))
+              }
+              /* Would like to do the following instead, but curiously this fails; todo: investigate
+              if (fun.symbol.name == nme.apply && fun.symbol.owner == ListClass && args.isEmpty) {
+                atPos(tree.pos) { gen.mkNil setType restpe }
+              } else {
+                constfold(treeCopy.Apply(tree, fun, args1).setType(ifPatternSkipFormals(restpe)))
+              }
+              */
+
+            } else if (needsInstantiation(tparams, formals, args)) {
               //println("needs inst "+fun+" "+tparams+"/"+(tparams map (_.info)))
-              inferExprInstance(fun, tparams, WildcardType)
-              doTypedApply(tree, fun, args1, mode, pt)
+              inferExprInstance(fun, tparams, WildcardType, true)
+              doTypedApply(tree, fun, args, mode, pt)
             } else {
-              assert((mode & PATTERNmode) == 0); // this case cannot arise for patterns
+              assert((mode & PATTERNmode) == 0) // this case cannot arise for patterns
               val lenientTargs = protoTypeArgs(tparams, formals, mt.resultApprox, pt)
-              val strictTargs = List.map2(lenientTargs, tparams)((targ, tparam) =>
-                if (targ == WildcardType) tparam.tpe else targ)
-              def typedArgToPoly(arg: Tree, formal: Type): Tree = {
+              val strictTargs = (lenientTargs, tparams).zipped map ((targ, tparam) =>
+                if (targ == WildcardType) tparam.tpe else targ) //@M TODO: should probably be .tpeHK
+              var remainingParams = paramTypes
+              def typedArgToPoly(arg: Tree, formal: Type): Tree = { //TR TODO: cleanup
                 val lenientPt = formal.instantiateTypeParams(tparams, lenientTargs)
-                val arg1 = typedArg(arg, argMode(fun, mode), POLYmode, lenientPt)
-                val argtparams = context.undetparams
-                context.undetparams = List()
+                val newmode = 
+                  if (remainingParams.head.typeSymbol == ByNameParamClass) POLYmode
+                  else POLYmode | BYVALmode
+                if (remainingParams.tail.nonEmpty) remainingParams = remainingParams.tail
+                // println("typedArgToPoly(arg, formal): "+(arg, formal))
+                val arg1 = typedArg(arg, argMode(fun, mode), newmode, lenientPt)
+                val argtparams = context.extractUndetparams()
+                // println("typedArgToPoly(arg1, argtparams): "+(arg1, argtparams))
                 if (!argtparams.isEmpty) {
                   val strictPt = formal.instantiateTypeParams(tparams, strictTargs)
                   inferArgumentInstance(arg1, argtparams, strictPt, lenientPt)
                 }
                 arg1
               }
-              val args2 = List.map2(args1, formals)(typedArgToPoly)
-              if (args2 exists (_.tpe.isError)) setError(tree)
+              val args1 = (args, formals).zipped map typedArgToPoly
+              if (args1 exists (_.tpe.isError)) setError(tree)
               else {
-                if (settings.debug.value) log("infer method inst "+fun+", tparams = "+tparams+", args = "+args2.map(_.tpe)+", pt = "+pt+", lobounds = "+tparams.map(_.tpe.bounds.lo)+", parambounds = "+tparams.map(_.info));//debug
-                val undetparams = inferMethodInstance(fun, tparams, args2, pt)
-                val result = doTypedApply(tree, fun, args2, mode, pt)
+                if (settings.debug.value) log("infer method inst "+fun+", tparams = "+tparams+", args = "+args1.map(_.tpe)+", pt = "+pt+", lobounds = "+tparams.map(_.tpe.bounds.lo)+", parambounds = "+tparams.map(_.info)) //debug
+                // define the undetparams which have been fixed by this param list, replace the corresponding symbols in "fun"
+                // returns those undetparams which have not been instantiated.
+                val undetparams = inferMethodInstance(fun, tparams, args1, pt)
+                val result = doTypedApply(tree, fun, args1, mode, pt)
                 context.undetparams = undetparams
                 result
               }
@@ -1839,7 +2510,7 @@ trait Typers { self: Analyzer =>
           doTypedApply(tree, fun setType fun.tpe.widen, args, mode, pt)
         
         case ErrorType =>
-          setError(copy.Apply(tree, fun, args))
+          setError(treeCopy.Apply(tree, fun, args))
         /* --- begin unapply  --- */
 
         case otpe if (mode & PATTERNmode) != 0 && unapplyMember(otpe).exists =>
@@ -1858,8 +2529,8 @@ trait Typers { self: Analyzer =>
           if (!isApplicableSafe(List(), unappType, List(arg.tpe), WildcardType)) {
             //Console.println("UNAPP: need to typetest, arg.tpe = "+arg.tpe+", unappType = "+unappType)
             def freshArgType(tp: Type): (Type, List[Symbol]) = tp match {
-              case MethodType(formals, _) => 
-                (formals(0), List())
+              case MethodType(params, _) => 
+                (params(0).tpe, List())
               case PolyType(tparams, restype) => 
                 val tparams1 = cloneSymbols(tparams)
                 (freshArgType(restype)._1.substSym(tparams, tparams1), tparams1)
@@ -1867,11 +2538,19 @@ trait Typers { self: Analyzer =>
                 error(fun.pos, "cannot resolve overloaded unapply")
                 (ErrorType, List())
             }
-            val (unappFormal, freeVars) = freshArgType(unappType)
-            val context1 = context.makeNewScope(context.tree, context.owner)(FreshArgScopeKind)
-            freeVars foreach(sym => context1.scope.enter(sym))
+            val (unappFormal, freeVars) = freshArgType(unappType.skolemizeExistential(context.owner, tree))
+            val context1 = context.makeNewScope(context.tree, context.owner)
+            freeVars foreach context1.scope.enter
             val typer1 = newTyper(context1)
-            arg.tpe = typer1.infer.inferTypedPattern(tree.pos, unappFormal, arg.tpe)
+            val pattp = typer1.infer.inferTypedPattern(tree.pos, unappFormal, arg.tpe)
+            // turn any unresolved type variables in freevars into existential skolems
+            val skolems = freeVars map { fv =>
+              val skolem = new TypeSkolem(context1.owner, fun.pos, fv.name, fv)
+              skolem.setInfo(fv.info.cloneInfo(skolem))
+                .setFlag(fv.flags | EXISTENTIAL).resetFlag(PARAM)
+              skolem
+            }
+            arg.tpe = pattp.substSym(freeVars, skolems)
             //todo: replace arg with arg.asInstanceOf[inferTypedPattern(unappFormal, arg.tpe)] instead.
             argDummy.setInfo(arg.tpe) // bq: this line fixed #1281. w.r.t. comment ^^^, maybe good enough?
           }
@@ -1883,7 +2562,7 @@ trait Typers { self: Analyzer =>
               //Console.println(" contains?"+sym.tpe.decls.lookup(fun.symbol.name));
               if(sym != fun.symbol.owner && (sym.isPackageClass||sym.isModuleClass) /*(1)*/ ) { // (1) see 'files/pos/unapplyVal.scala'
                 if(fun.symbol.owner.isClass) {
-                  mkThisType(fun.symbol.owner)
+                  ThisType(fun.symbol.owner)
                 } else {
                 //Console.println("2 ThisType("+fun.symbol.owner+")")
                   NoPrefix                                                 // see 'files/run/unapplyComplex.scala'
@@ -1918,25 +2597,10 @@ trait Typers { self: Analyzer =>
             if (formals1.length == args.length) {
               val args1 = typedArgs(args, mode, formals0, formals1)
               if (!isFullyDefined(pt)) assert(false, tree+" ==> "+UnApply(fun1, args1)+", pt = "+pt)
-              // <pending-change>
-              //   this would be a better choice (from #1196), but fails due to (broken?) refinements
               val itype =  glb(List(pt, arg.tpe))
-              // </pending-change>
               // restore old type (arg is a dummy tree, just needs to pass typechecking)
               arg.tpe = oldArgType
-              UnApply(fun1, args1) setPos tree.pos setType itype //pt
-              //
-              // if you use the better itype, then the following happens.
-              // the required type looks wrong...
-              // 
-              ///files/pos/bug0646.scala                                [FAILED]
-              //
-              //failed with type mismatch;
-              // found   : scala.xml.NodeSeq{ ... }
-              // required: scala.xml.NodeSeq{ ... } with scala.xml.NodeSeq{ ... } with scala.xml.Node on: temp3._data().==("Blabla").&&({
-              //  exit(temp0);
-              //  true
-              //})
+              UnApply(fun1, args1) setPos tree.pos setType itype
             } else {
               errorTree(tree, "wrong number of arguments for "+treeSymTypeMsg(fun))
             }
@@ -1948,38 +2612,160 @@ trait Typers { self: Analyzer =>
       }
     }
 
-    def typedAnnotation(annot: Annotation, owner: Symbol): AnnotationInfo =
-      typedAnnotation(annot, owner, EXPRmode)
+    /**
+     * Convert an annotation constructor call into an AnnotationInfo.
+     *
+     * @param annClass the expected annotation class
+     */
+    def typedAnnotation(ann: Tree, mode: Int = EXPRmode, selfsym: Symbol = NoSymbol, annClass: Symbol = AnnotationClass, requireJava: Boolean = false): AnnotationInfo = {
+      lazy val annotationError = AnnotationInfo(ErrorType, Nil, Nil)
+      var hasError: Boolean = false
+      def error(pos: Position, msg: String) = {
+        context.error(pos, msg)
+        hasError = true
+        annotationError
+      }
 
-    def typedAnnotation(annot: Annotation, owner: Symbol, mode: Int): AnnotationInfo =
-      typedAnnotation(annot, owner, mode, NoSymbol)
+      /** Calling constfold right here is necessary because some trees (negated
+       *  floats and literals in particular) are not yet folded.
+       */
+      def tryConst(tr: Tree, pt: Type) = typed(constfold(tr), EXPRmode, pt) match {
+        // null cannot be used as constant value for classfile annotations
+        case l @ Literal(c) if !(l.isErroneous || c.value == null) =>
+          Some(LiteralAnnotArg(c))
+        case _ =>
+          error(tr.pos, "annotation argument needs to be a constant; found: "+tr)
+          None
+      }
 
-    def typedAnnotation(annot: Annotation, owner: Symbol, mode: Int, selfsym: Symbol): AnnotationInfo = {
-      var attrError: Boolean = false
-      def error(pos: Position, msg: String): Null = {
-        context.error(pos, msg)
-        attrError = true
-        null
+      /** Converts an untyped tree to a ClassfileAnnotArg. If the conversion fails,
+       *  an error message is reported and None is returned.
+       */
+      def tree2ConstArg(tree: Tree, pt: Type): Option[ClassfileAnnotArg] = tree match {
+        case Apply(Select(New(tpt), nme.CONSTRUCTOR), args) if (pt.typeSymbol == ArrayClass) =>
+          error(tree.pos, "Array constants have to be specified using the `Array(...)' factory method")
+          None
+
+        case ann @ Apply(Select(New(tpt), nme.CONSTRUCTOR), args) =>
+          val annInfo = typedAnnotation(ann, mode, NoSymbol, pt.typeSymbol, true)
+          if (annInfo.atp.isErroneous) {
+            // recursive typedAnnotation call already printed an error, so don't call "error"
+            hasError = true
+            None
+          } else Some(NestedAnnotArg(annInfo))
+
+        // use of Array.apply[T: ClassManifest](xs: T*): Array[T]
+        // and    Array.apply(x: Int, xs: Int*): Array[Int]       (and similar)
+        case Apply(fun, args) =>
+          val typedFun = typed(fun, funMode(mode), WildcardType)
+          if (typedFun.symbol.owner == ArrayModule.moduleClass && typedFun.symbol.name == nme.apply)
+            pt match {
+              case TypeRef(_, ArrayClass, targ :: _) =>
+                trees2ConstArg(args, targ)
+              case _ =>
+                // For classfile annotations, pt can only be T:
+                //   BT = Int, .., String, Class[_], JavaAnnotClass
+                //   T = BT | Array[BT]
+                // So an array literal as argument can only be valid if pt is Array[_]
+                error(tree.pos, "found array constant, expected argument of type "+ pt)
+                None
+            }
+          else
+            tryConst(tree, pt)
+
+        case Typed(t, _) => tree2ConstArg(t, pt)
+
+        case tree =>
+          tryConst(tree, pt)
+      }
+      def trees2ConstArg(trees: List[Tree], pt: Type): Option[ArrayAnnotArg] = {
+        val args = trees.map(tree2ConstArg(_, pt))
+        if (args.exists(_.isEmpty)) None
+        else Some(ArrayAnnotArg(args.map(_.get).toArray))
       }
-      def needConst(tr: Tree) {
-        error(tr.pos, "attribute argument needs to be a constant; found: "+tr)
+
+      // begin typedAnnotation
+      val (fun, argss) = {
+        def extract(fun: Tree, outerArgss: List[List[Tree]]):
+          (Tree, List[List[Tree]]) = fun match {
+            case Apply(f, args) =>
+              extract(f, args :: outerArgss)
+            case Select(New(tpt), nme.CONSTRUCTOR) =>
+              (fun, outerArgss)
+            case _ =>
+              error(fun.pos, "unexpected tree in annotation: "+ fun)
+              (setError(fun), outerArgss)
+          }
+        extract(ann, List())
       }
 
-      val typedConstr =
-        if (selfsym == NoSymbol) {
-          // why a new typer: definitions inside the annotation's constructor argument
-          // should not have the annotated's owner as owner.
-          val typer1 = newTyper(context.makeNewScope(annot.constr, owner)(TypedScopeKind))
-          typer1.typed(annot.constr, mode, AnnotationClass.tpe)
+      if (fun.isErroneous) annotationError
+      else {
+        val typedFun @ Select(New(tpt), _) = typed(fun, funMode(mode), WildcardType)
+        val annType = tpt.tpe
+
+        if (typedFun.isErroneous) annotationError
+        else if (annType.typeSymbol isNonBottomSubClass ClassfileAnnotationClass) {
+          // annotation to be saved as java classfile annotation
+          val isJava = typedFun.symbol.owner.hasFlag(JAVA)
+          if (!annType.typeSymbol.isNonBottomSubClass(annClass)) {
+            error(tpt.pos, "expected annotation of type "+ annClass.tpe +", found "+ annType)
+          } else if (argss.length > 1) {
+            error(ann.pos, "multiple argument lists on classfile annotation")
+          } else {
+            val args =
+              if (argss.head.length == 1 && !isNamed(argss.head.head))
+                List(new AssignOrNamedArg(Ident(nme.value), argss.head.head))
+              else argss.head
+            val annScope = annType.decls
+                .filter(sym => sym.isMethod && !sym.isConstructor && sym.hasFlag(JAVA))
+            val names = new collection.mutable.HashSet[Symbol]
+            names ++= (if (isJava) annScope.iterator
+                       else typedFun.tpe.params.iterator)
+            val nvPairs = args map {
+              case arg @ AssignOrNamedArg(Ident(name), rhs) =>
+                val sym = if (isJava) annScope.lookup(name)
+                          else typedFun.tpe.params.find(p => p.name == name).getOrElse(NoSymbol)
+                if (sym == NoSymbol) {
+                  error(arg.pos, "unknown annotation argument name: " + name)
+                  (nme.ERROR, None)
+                } else if (!names.contains(sym)) {
+                  error(arg.pos, "duplicate value for annotation argument " + name)
+                  (nme.ERROR, None)
+                } else {
+                  names -= sym
+                  if(isJava) sym.cookJavaRawInfo() // #3429
+                  val annArg = tree2ConstArg(rhs, sym.tpe.resultType)
+                  (sym.name, annArg)
+                }
+              case arg =>
+                error(arg.pos, "classfile annotation arguments have to be supplied as named arguments")
+                (nme.ERROR, None)
+            }
+
+            for (name <- names) {
+              if (!name.annotations.contains(AnnotationInfo(AnnotationDefaultAttr.tpe, List(), List())) &&
+                  !name.hasFlag(DEFAULTPARAM))
+                error(ann.pos, "annotation " + annType.typeSymbol.fullName + " is missing argument " + name.name)
+            }
+
+            if (hasError) annotationError
+            else AnnotationInfo(annType, List(), nvPairs map {p => (p._1, p._2.get)}).setPos(ann.pos)
+          }
+        } else if (requireJava) {
+          error(ann.pos, "nested classfile annotations must be defined in java; found: "+ annType)
         } else {
-          // Since a selfsym is supplied, the annotation should have
-          // an extra "self" identifier in scope for type checking.
-          // This is implemented by wrapping the rhs
-          // in a function like "self => rhs" during type checking,
-          // and then stripping the "self =>" and substituting
-          // in the supplied selfsym.
-          val funcparm = ValDef(NoMods, nme.self, TypeTree(selfsym.info), EmptyTree)
-          val func = Function(List(funcparm), annot.constr.duplicate)
+          val typedAnn = if (selfsym == NoSymbol) {
+            typed(ann, mode, annClass.tpe)
+          } else {
+            // Since a selfsym is supplied, the annotation should have
+            // an extra "self" identifier in scope for type checking.
+            // This is implemented by wrapping the rhs
+            // in a function like "self => rhs" during type checking,
+            // and then stripping the "self =>" and substituting
+            // in the supplied selfsym.
+            val funcparm = ValDef(NoMods, nme.self, TypeTree(selfsym.info), EmptyTree)
+            val func = Function(List(funcparm), ann.duplicate)
                                          // The .duplicate of annot.constr
                                          // deals with problems that
                                          // accur if this annotation is
@@ -1989,72 +2775,48 @@ trait Typers { self: Analyzer =>
                                          // ident's within annot.constr
                                          // will retain the old symbol
                                          // from the previous typing.
-          val fun1clazz = FunctionClass(1)
-          val funcType = typeRef(fun1clazz.tpe.prefix, 
-                                 fun1clazz, 
-                                 List(selfsym.info, AnnotationClass.tpe))
-
-          typed(func, mode, funcType) match {
-            case t @ Function(List(arg), rhs) => 
-              val subs =
-                new TreeSymSubstituter(List(arg.symbol),List(selfsym))
-              subs(rhs)
+            val fun1clazz = FunctionClass(1)
+            val funcType = typeRef(fun1clazz.tpe.prefix, 
+                                   fun1clazz, 
+                                   List(selfsym.info, annClass.tpe))
+
+            typed(func, mode, funcType) match {
+              case t @ Function(List(arg), rhs) => 
+                val subs =
+                  new TreeSymSubstituter(List(arg.symbol),List(selfsym))
+                subs(rhs)
+            }
           }
-        }
 
-      typedConstr match {
-        case t @ Apply(Select(New(tpt), nme.CONSTRUCTOR), args) =>
-          if ((t.tpe==null) || t.tpe.isErroneous) {
-            AnnotationInfo(ErrorType, List(), List())
-          }
-          else {
-            val annType = tpt.tpe
+          def annInfo(t: Tree): AnnotationInfo = t match {
+            case Apply(Select(New(tpt), nme.CONSTRUCTOR), args) =>
+              AnnotationInfo(annType, args, List()).setPos(t.pos)
 
-            val needsConstant =
-              (annType.typeSymbol isNonBottomSubClass ClassfileAnnotationClass)
+            case Block(stats, expr) =>
+              context.warning(t.pos, "Usage of named or default arguments transformed this annotation\n"+
+                                "constructor call into a block. The corresponding AnnotationInfo\n"+
+                                "will contain references to local values and default getters instead\n"+
+                                "of the actual argument trees")
+              annInfo(expr)
 
-            def annotArg(tree: Tree): AnnotationArgument = {
-              val arg = new AnnotationArgument(tree)
-              if(needsConstant && !arg.isConstant && !inIDE)
-                needConst(tree)
-              arg
-            }
-            val constrArgs = args map annotArg
+            case Apply(fun, args) =>
+              context.warning(t.pos, "Implementation limitation: multiple argument lists on annotations are\n"+
+                                     "currently not supported; ignoring arguments "+ args)
+              annInfo(fun)
 
-            val attrScope = annType.decls
-              .filter(sym => sym.isMethod && !sym.isConstructor && sym.hasFlag(JAVA))
-            val names = new collection.mutable.HashSet[Symbol]
-            names ++= attrScope.elements.filter(_.isMethod)
-            if (args.length == 1) {
-              names.retain(sym => sym.name != nme.value)
-            }
-            val nvPairs = annot.elements map {
-              case vd @ ValDef(_, name, _, rhs) => {
-                val sym = attrScope.lookupWithContext(name)(context.owner);
-                if (sym == NoSymbol) {
-                  error(vd.pos, "unknown attribute element name: " + name)
-                } else if (!names.contains(sym)) {
-                  error(vd.pos, "duplicate value for element " + name)
-                } else {
-                  names -= sym
-                  val annArg =
-                    annotArg(
-                      typed(rhs, EXPRmode, sym.tpe.resultType))
-                  (sym.name, annArg)
-                }
-              }
-            }
-            for (name <- names) {
-              if (!name.attributes.contains(AnnotationInfo(AnnotationDefaultAttr.tpe, List(), List()))) {
-                error(annot.constr.pos, "attribute " + annType.typeSymbol.fullNameString + " is missing element " + name.name)
-              }
-            }
-            if (annType.typeSymbol.hasFlag(JAVA) && settings.target.value == "jvm-1.4") {
-              context.warning (annot.constr.pos, "Java annotation will not be emitted in classfile unless you use the '-target:jvm-1.5' option")
-            }
-            if (attrError) AnnotationInfo(ErrorType, List(), List())
-            else AnnotationInfo(annType, constrArgs, nvPairs)
+            case _ =>
+              error(t.pos, "unexpected tree after typing annotation: "+ typedAnn)
           }
+
+          if (annType.typeSymbol == DeprecatedAttr &&
+              (argss.length == 0 || argss.head.length == 0))
+            unit.deprecationWarning(ann.pos,
+              "the `deprecated' annotation now takes a (message: String) as parameter\n"+
+              "indicating the reason for deprecation. That message is printed to the console and included in scaladoc.")
+
+          if ((typedAnn.tpe == null) || typedAnn.tpe.isErroneous) annotationError
+          else annInfo(typedAnn)
+        }
       }
     }
 
@@ -2082,7 +2844,7 @@ trait Typers { self: Analyzer =>
         val name = if (sym.isType) sym.name else newTypeName(sym.name+".type")
         val bound = sym.existentialBound
         val sowner = if (isRawParameter(sym)) context.owner else sym.owner
-        val quantified: Symbol = recycle(sowner.newAbstractType(sym.pos, name)) 
+        val quantified: Symbol = sowner.newAbstractType(sym.pos, name)
         trackSetInfo(quantified setFlag EXISTENTIAL)(bound.cloneInfo(quantified))
       }
       val typeParamTypes = typeParams map (_.tpe) // don't trackSetInfo here, since type already set!
@@ -2105,16 +2867,6 @@ trait Typers { self: Analyzer =>
         res
       }
 
-    class SymInstance(val sym: Symbol, val tp: Type) {
-      override def equals(other: Any): Boolean = other match {
-        case that: SymInstance =>
-          this.sym == that.sym && this.tp =:= that.tp
-        case _ =>
-          false
-      }
-      override def hashCode: Int = sym.hashCode * 41 + tp.hashCode
-    }
-
     /** convert skolems to existentials */
     def packedType(tree: Tree, owner: Symbol): Type = {
       def defines(tree: Tree, sym: Symbol) = 
@@ -2130,9 +2882,8 @@ trait Typers { self: Analyzer =>
         }
       var localSyms = collection.immutable.Set[Symbol]()
       var boundSyms = collection.immutable.Set[Symbol]()
-      var localInstances = collection.immutable.Map[SymInstance, Symbol]() 
       def isLocal(sym: Symbol): Boolean =
-        if (sym == NoSymbol) false
+        if (sym == NoSymbol || sym.isRefinementClass || sym.isLocalDummy) false
         else if (owner == NoSymbol) tree exists (defines(_, sym))
         else containsDef(owner, sym) || isRawParameter(sym)
       def containsLocal(tp: Type): Boolean = 
@@ -2151,93 +2902,49 @@ trait Typers { self: Analyzer =>
         }
       }
       // add all local symbols of `tp' to `localSyms'
-      // expanding higher-kinded types into individual copies for each instance.
+      // TODO: expand higher-kinded types into individual copies for each instance.
       def addLocals(tp: Type) {
+        val remainingSyms = new ListBuffer[Symbol]
         def addIfLocal(sym: Symbol, tp: Type) {
-          if (sym != NoSymbol && !sym.isRefinementClass && isLocal(sym) &&   
-              !(localSyms contains sym) && !(boundSyms contains sym) ) {
+          if (isLocal(sym) && !localSyms.contains(sym) && !boundSyms.contains(sym)) {
             if (sym.typeParams.isEmpty) {
               localSyms += sym
-              addLocals(sym.existentialBound)
-            } else if (tp.typeArgs.isEmpty) {
-              unit.error(tree.pos, 
-                "implementation restriction: can't existentially abstract over higher-kinded type" + tp)
+              remainingSyms += sym
             } else {
-              val inst = new SymInstance(sym, tp)
-              if (!(localInstances contains inst)) {
-                val bound = sym.existentialBound match {
-                  case PolyType(tparams, restpe) => 
-                    restpe.subst(tparams, tp.typeArgs)
-                  case t =>
-                    t
-                }
-                val local = trackSetInfo(recycle(sym.owner.newAbstractType(
-                  sym.pos, unit.fresh.newName(sym.pos, sym.name.toString))
-                    .setFlag(sym.flags)))(bound)
-                localInstances += (inst -> local)
-                addLocals(bound)
-              }
-            }
+              unit.error(tree.pos, 
+                "can't existentially abstract over parameterized type " + tp)
+            } 
           }
         }
+
         for (t <- tp) {
           t match {
             case ExistentialType(tparams, _) => 
               boundSyms ++= tparams
-	    case AnnotatedType(annots, _, _) =>
-	      for (annot <- annots; arg <- annot.args; t <- arg.intTree) {
-		t match {
-		  case Ident(_) =>
-		    // Check the symbol of an Ident, unless the
-		    // Ident's type is already over an existential.
-		    // (If the type is already over an existential,
+            case AnnotatedType(annots, _, _) =>
+              for (annot <- annots; arg <- annot.args) {
+                arg match {
+                  case Ident(_) =>
+                    // Check the symbol of an Ident, unless the
+                    // Ident's type is already over an existential.
+                    // (If the type is already over an existential,
                     // then remap the type, not the core symbol.)
-		    if (!t.tpe.typeSymbol.hasFlag(EXISTENTIAL))
-		      addIfLocal(t.symbol, t.tpe)
-		  case _ => ()
-		}
-	      }
+                    if (!arg.tpe.typeSymbol.hasFlag(EXISTENTIAL))
+                      addIfLocal(arg.symbol, arg.tpe)
+                  case _ => ()
+                }
+              }
             case _ =>
           }
           addIfLocal(t.termSymbol, t)
           addIfLocal(t.typeSymbol, t)
         }
-      }
-
-      object substLocals extends TypeMap {
-	    override val dropNonConstraintAnnotations = true
-
-        def apply(t: Type): Type = t match {
-          case TypeRef(_, sym, args) if (sym.isLocal && args.length > 0) =>
-            localInstances.get(new SymInstance(sym, t)) match {
-              case Some(local) => typeRef(NoPrefix, local, List())
-              case None => mapOver(t)
-            }
-          case _ => mapOver(t)
-        }
-
-	override def mapOver(arg: Tree, giveup: ()=>Nothing) = {
-	  object substLocalTrees extends TypeMapTransformer {
-	    override def transform(tr: Tree) = {
-              localInstances.get(new SymInstance(tr.symbol, tr.tpe)) match {
-		case Some(local) => 
-		  Ident(local.existentialToString)
-		    .setSymbol(tr.symbol).copyAttrs(tr).setType(
-		      typeRef(NoPrefix, local, List()))
-		
-		case None => super.transform(tr)
-	      }
-	    }
-	  }
-
-	  substLocalTrees.transform(arg)
-	}
+        for (sym <- remainingSyms) addLocals(sym.existentialBound)
       }
 
       val normalizedTpe = normalizeLocals(tree.tpe)
       addLocals(normalizedTpe)
-
-      packSymbols(localSyms.toList ::: localInstances.values.toList, substLocals(normalizedTpe))
+      packSymbols(localSyms.toList, normalizedTpe)
     }
 
     protected def typedExistentialTypeTree(tree: ExistentialTypeTree, mode: Int): Tree = {
@@ -2254,6 +2961,61 @@ trait Typers { self: Analyzer =>
       TypeTree(ExistentialType(typeParams, tpe)) setOriginal tree
     }
 
+    // lifted out of typed1 because it's needed in typedImplicit0
+    protected def typedTypeApply(tree: Tree, mode: Int, fun: Tree, args: List[Tree]): Tree = fun.tpe match {
+      case OverloadedType(pre, alts) =>
+        inferPolyAlternatives(fun, args map (_.tpe))
+        val tparams = fun.symbol.typeParams //@M TODO: fun.symbol.info.typeParams ? (as in typedAppliedTypeTree)
+        val args1 = if(args.length == tparams.length) {
+          //@M: in case TypeApply we can't check the kind-arities of the type arguments,
+          // as we don't know which alternative to choose... here we do
+          map2Conserve(args, tparams) { 
+            //@M! the polytype denotes the expected kind
+            (arg, tparam) => typedHigherKindedType(arg, mode, polyType(tparam.typeParams, AnyClass.tpe)) 
+          }          
+        } else // @M: there's probably something wrong when args.length != tparams.length... (triggered by bug #320)
+         // Martin, I'm using fake trees, because, if you use args or arg.map(typedType), 
+         // inferPolyAlternatives loops...  -- I have no idea why :-(
+         // ...actually this was looping anyway, see bug #278.
+          return errorTree(fun, "wrong number of type parameters for "+treeSymTypeMsg(fun))
+        
+        typedTypeApply(tree, mode, fun, args1)
+      case SingleType(_, _) =>
+        typedTypeApply(tree, mode, fun setType fun.tpe.widen, args)
+      case PolyType(tparams, restpe) if (tparams.length != 0) =>
+        if (tparams.length == args.length) {
+          val targs = args map (_.tpe)
+          checkBounds(tree.pos, NoPrefix, NoSymbol, tparams, targs, "")
+          if (fun.symbol == Predef_classOf) {
+            checkClassType(args.head, true, false) 
+            atPos(tree.pos) { gen.mkClassOf(targs.head) }
+          } else {
+            if (phase.id <= currentRun.typerPhase.id &&
+                fun.symbol == Any_isInstanceOf && !targs.isEmpty)
+              checkCheckable(tree.pos, targs.head, "")
+            val resultpe = restpe.instantiateTypeParams(tparams, targs)
+            //@M substitution in instantiateParams needs to be careful!
+            //@M example: class Foo[a] { def foo[m[x]]: m[a] = error("") } (new Foo[Int]).foo[List] : List[Int]
+            //@M    --> first, m[a] gets changed to m[Int], then m gets substituted for List, 
+            //          this must preserve m's type argument, so that we end up with List[Int], and not List[a]
+            //@M related bug: #1438 
+            //println("instantiating type params "+restpe+" "+tparams+" "+targs+" = "+resultpe)
+            treeCopy.TypeApply(tree, fun, args) setType resultpe
+          }
+        } else {
+          errorTree(tree, "wrong number of type parameters for "+treeSymTypeMsg(fun))
+        }
+      case ErrorType =>
+        setError(tree)
+      case _ =>
+        errorTree(tree, treeSymTypeMsg(fun)+" does not take type parameters.")
+    }
+
+    private[this] var typingIndent: String = ""
+    @inline final def deindentTyping() = if (printTypings) typingIndent = typingIndent.substring(0, typingIndent.length() - 2)
+    @inline final def indentTyping() = if (printTypings) typingIndent += "  "
+    @inline final def printTyping(s: => String) = if (printTypings) println(typingIndent+s)
+
     /**
      *  @param tree ...
      *  @param mode ...
@@ -2261,8 +3023,10 @@ trait Typers { self: Analyzer =>
      *  @return     ...
      */
     protected def typed1(tree: Tree, mode: Int, pt: Type): Tree = {
+      def isPatternMode = (mode & PATTERNmode) != 0
+      
       //Console.println("typed1("+tree.getClass()+","+Integer.toHexString(mode)+","+pt+")")
-      def ptOrLub(tps: List[Type]) = if (isFullyDefined(pt)) pt else lub(tps map (_.deconst))
+      def ptOrLub(tps: List[Type]) = if (isFullyDefined(pt)) (pt, false) else weakLub(tps map (_.deconst))
       
       //@M! get the type of the qualifier in a Select tree, otherwise: NoType
       def prefixType(fun: Tree): Type = fun match { 
@@ -2271,70 +3035,71 @@ trait Typers { self: Analyzer =>
         case _ => NoType
       }
       
-      def typedAnnotated(annot: Annotation, arg1: Tree): Tree = {
+      def typedAnnotated(ann: Tree, arg1: Tree): Tree = {
         /** mode for typing the annotation itself */
         val annotMode = mode & ~TYPEmode | EXPRmode
 
         if (arg1.isType) {
-          val selfsym =
-            if (!settings.selfInAnnots.value)
-              NoSymbol
-            else
-              arg1.tpe.selfsym match {
-                case NoSymbol =>
-                  /* Implementation limitation: Currently this
-                   * can cause cyclical reference errors even
-                   * when the self symbol is not referenced at all.
-                   * Surely at least some of these cases can be
-                   * fixed by proper use of LazyType's.  Lex tinkered
-                   * on this but did not succeed, so is leaving
-                   * it alone for now. Example code with the problem:
-                   *  class peer extends Annotation
-                   *  class NPE[T <: NPE[T] @peer]
-                   *
-                   * (Note: -Yself-in-annots must be on to see the problem)
-                   **/
-                  val sym = 
-                    newLocalDummy(context.owner, annot.pos)
-                      .newValue(annot.pos, nme.self)
-                  sym.setInfo(arg1.tpe.withoutAttributes)
-                  sym
-                case sym => sym
-              }
-
-          // use the annotation context's owner as parent for symbols defined
-          // inside a type annotation
-          val ainfo = typedAnnotation(annot, context.owner, annotMode, selfsym)
-          val atype0 = arg1.tpe.withAttribute(ainfo)
-          val atype =
-            if ((selfsym != NoSymbol) && (ainfo.refsSymbol(selfsym)))
-              atype0.withSelfsym(selfsym)
-            else
-              atype0 // do not record selfsym if
-                     // this annotation did not need it
+          // make sure the annotation is only typechecked once
+          if (ann.tpe == null) {
+            // an annotated type
+            val selfsym =
+              if (!settings.selfInAnnots.value)
+                NoSymbol
+              else
+                arg1.tpe.selfsym match {
+                  case NoSymbol =>
+                    /* Implementation limitation: Currently this
+                     * can cause cyclical reference errors even
+                     * when the self symbol is not referenced at all.
+                     * Surely at least some of these cases can be
+                     * fixed by proper use of LazyType's.  Lex tinkered
+                     * on this but did not succeed, so is leaving
+                     * it alone for now. Example code with the problem:
+                     *  class peer extends Annotation
+                     *  class NPE[T <: NPE[T] @peer]
+                     *
+                     * (Note: -Yself-in-annots must be on to see the problem)
+                     * */
+                    val sym = 
+                      context.owner.newLocalDummy(ann.pos)
+                        .newValue(ann.pos, nme.self)
+                    sym.setInfo(arg1.tpe.withoutAnnotations)
+                    sym
+                  case sym => sym
+                }
 
-          if (ainfo.isErroneous)
-            arg1  // simply drop erroneous annotations
-          else
-            TypeTree(atype) setOriginal tree
+            val ainfo = typedAnnotation(ann, annotMode, selfsym)
+            val atype0 = arg1.tpe.withAnnotation(ainfo)
+            val atype =
+              if ((selfsym != NoSymbol) && (ainfo.refsSymbol(selfsym)))
+                atype0.withSelfsym(selfsym)
+              else
+                atype0 // do not record selfsym if
+                       // this annotation did not need it
+
+            if (ainfo.isErroneous)
+              arg1  // simply drop erroneous annotations
+            else {
+              ann.tpe = atype
+              TypeTree(atype) setOriginal tree
+            }
+          } else {
+            // the annotation was typechecked before
+            TypeTree(ann.tpe) setOriginal tree
+          }
         } else {
-          def annotTypeTree(ainfo: AnnotationInfo): Tree = 
-            TypeTree(arg1.tpe.withAttribute(ainfo)) setOriginal tree
-
-          val annotInfo = typedAnnotation(annot, context.owner, annotMode)
-
-          arg1 match {
-            case _: DefTree => 
-              if (!annotInfo.atp.isError) {
-                val attributed =
-                  if (arg1.symbol.isModule) arg1.symbol.moduleClass else arg1.symbol
-                attributed.attributes = annotInfo :: attributed.attributes
-              }
-              arg1
-            case _ =>
-              val atpt = annotTypeTree(annotInfo)
-              Typed(arg1, atpt) setPos tree.pos setType atpt.tpe
+          // An annotated term, created with annotation ascription
+          //   term : @annot()
+          def annotTypeTree(ainfo: AnnotationInfo): Tree = //TR: function not used ??
+            TypeTree(arg1.tpe.withAnnotation(ainfo)) setOriginal tree
+
+          if (ann.tpe == null) {
+            val annotInfo = typedAnnotation(ann, annotMode)
+            ann.tpe = arg1.tpe.withAnnotation(annotInfo)
           }
+          val atype = ann.tpe
+          Typed(arg1, TypeTree(atype) setOriginal tree setPos tree.pos.focus) setPos tree.pos setType atype
         }
       }
 
@@ -2348,23 +3113,16 @@ trait Typers { self: Analyzer =>
                 context.owner.newAliasType(tree.pos, name) setInfo pt
               else 
                 context.owner.newAbstractType(tree.pos, name) setInfo
-                  mkTypeBounds(NothingClass.tpe, AnyClass.tpe)
+                  TypeBounds(NothingClass.tpe, AnyClass.tpe)
           val rawInfo = vble.rawInfo
           vble = if (vble.name == nme.WILDCARD.toTypeName) context.scope.enter(vble)
                  else namer.enterInScope(vble) 
-          trackSetInfo(vble)(rawInfo) // vble could have been recycled, detect changes in type       
+          trackSetInfo(vble)(rawInfo)
           tree setSymbol vble setType vble.tpe
         } else {
           if (vble == NoSymbol) 
             vble = context.owner.newValue(tree.pos, name)
           if (vble.name.toTermName != nme.WILDCARD) {
-/*
-          if (namesSomeIdent(vble.name))
-            context.warning(tree.pos,
-              "pattern variable"+vble.name+" shadows a value visible in the environment;\n"+
-              "use backquotes `"+vble.name+"` if you mean to match against that value;\n" +
-              "or rename the variable or use an explicit bind "+vble.name+"@_ to avoid this warning.")
-*/
             if ((mode & ALTmode) != 0)
               error(tree.pos, "illegal variable in pattern alternative")
             vble = namer.enterInScope(vble)
@@ -2373,62 +3131,66 @@ trait Typers { self: Analyzer =>
           trackSetInfo(vble)(
             if (treeInfo.isSequenceValued(body)) seqType(body1.tpe)
             else body1.tpe)
-          copy.Bind(tree, name, body1) setSymbol vble setType body1.tpe   // buraq, was: pt
+          treeCopy.Bind(tree, name, body1) setSymbol vble setType body1.tpe   // burak, was: pt
         }
       }
 
       def typedArrayValue(elemtpt: Tree, elems: List[Tree]) = {
         val elemtpt1 = typedType(elemtpt, mode)
-        val elems1 = List.mapConserve(elems)(elem => typed(elem, mode, elemtpt1.tpe))
-        copy.ArrayValue(tree, elemtpt1, elems1)
+        val elems1 = elems mapConserve (elem => typed(elem, mode, elemtpt1.tpe))
+        treeCopy.ArrayValue(tree, elemtpt1, elems1)
           .setType(
             (if (isFullyDefined(pt) && !phase.erasedTypes) pt
              else appliedType(ArrayClass.typeConstructor, List(elemtpt1.tpe))).notNull)
       }
 
       def typedAssign(lhs: Tree, rhs: Tree): Tree = {
-        def mayBeVarGetter(sym: Symbol) = sym.info match {
-          case PolyType(List(), _) => sym.owner.isClass && !sym.isStable
-          case _: ImplicitMethodType => sym.owner.isClass && !sym.isStable
-          case _ => false
-        }
-        val lhs1 = typed(lhs, EXPRmode | LHSmode, WildcardType)
-        val varsym = lhs1.symbol
-        if ((varsym ne null) && mayBeVarGetter(varsym))
+        val lhs1    = typed(lhs, EXPRmode | LHSmode, WildcardType)
+        val varsym  = lhs1.symbol
+        def failMsg =
+          if (varsym != null && varsym.isValue) "reassignment to val"
+          else "assignment to non variable"
+        
+        def fail = {    
+          if (!lhs1.tpe.isError)
+            error(tree.pos, failMsg)
+          
+          setError(tree)
+        }
+        if (varsym == null)
+          return fail
+        
+        if (treeInfo.mayBeVarGetter(varsym)) {
           lhs1 match {
             case Select(qual, name) =>
-              return typed(
-                Apply(
-                  Select(qual, nme.getterToSetter(name)) setPos lhs.pos,
-                  List(rhs)) setPos tree.pos, 
-                mode, pt)
-
+              val sel = Select(qual, nme.getterToSetter(name)) setPos lhs.pos
+              val app = Apply(sel, List(rhs)) setPos tree.pos              
+              return typed(app, mode, pt)
+          
             case _ =>
-
           }
-        if ((varsym ne null) && (varsym.isVariable || varsym.isValue && phase.erasedTypes)) {
-          val rhs1 = typed(rhs, lhs1.tpe)
-          copy.Assign(tree, lhs1, checkDead(rhs1)) setType UnitClass.tpe
-        } else {
-          if (!lhs1.tpe.isError) {
-            //println(lhs1+" = "+rhs)//DEBUG
-            error(tree.pos, 
-                  if ((varsym ne null) && varsym.isValue) "reassignment to val"
-                  else "assignment to non variable")
-          }
-          setError(tree)
         }
+        if (varsym.isVariable || varsym.isValue && phase.erasedTypes) {
+          val rhs1 = typed(rhs, EXPRmode | BYVALmode, lhs1.tpe)
+          treeCopy.Assign(tree, lhs1, checkDead(rhs1)) setType UnitClass.tpe
+        }
+        else fail
       }
 
       def typedIf(cond: Tree, thenp: Tree, elsep: Tree) = {
-        val cond1 = checkDead(typed(cond, BooleanClass.tpe))
-        if (elsep.isEmpty) {
+        val cond1 = checkDead(typed(cond, EXPRmode | BYVALmode, BooleanClass.tpe))
+        if (elsep.isEmpty) { // in the future, should be unnecessary
           val thenp1 = typed(thenp, UnitClass.tpe)
-          copy.If(tree, cond1, thenp1, elsep) setType UnitClass.tpe
-        } else {
-          val thenp1 = typed(thenp, pt)
-          val elsep1 = typed(elsep, pt)
-          copy.If(tree, cond1, thenp1, elsep1) setType ptOrLub(List(thenp1.tpe, elsep1.tpe))
+          treeCopy.If(tree, cond1, thenp1, elsep) setType thenp1.tpe
+        } else { 
+          var thenp1 = typed(thenp, pt)
+          var elsep1 = typed(elsep, pt)
+          val (owntype, needAdapt) = ptOrLub(List(thenp1.tpe, elsep1.tpe))
+          if (needAdapt) { //isNumericValueType(owntype)) {
+            thenp1 = adapt(thenp1, mode, owntype)
+            elsep1 = adapt(elsep1, mode, owntype)
+          }
+          treeCopy.If(tree, cond1, thenp1, elsep1) setType owntype
         }
       }
 
@@ -2442,54 +3204,56 @@ trait Typers { self: Analyzer =>
         } else {
           val DefDef(_, _, _, _, restpt, _) = enclMethod.tree
           var restpt0 = restpt
-          if (inIDE && (restpt0.tpe eq null)) {
-            restpt0 = typed(restpt0, TYPEmode, WildcardType)
-          }
           if (restpt0.tpe eq null) {
             errorTree(tree, "" + enclMethod.owner +
                       " has return statement; needs result type")
           } else {
             context.enclMethod.returnsSeen = true
-            val expr1: Tree = typed(expr, restpt0.tpe)
-            copy.Return(tree, checkDead(expr1)) setSymbol enclMethod.owner setType NothingClass.tpe
+            val expr1: Tree = typed(expr, EXPRmode | BYVALmode, restpt0.tpe)
+            treeCopy.Return(tree, checkDead(expr1)) setSymbol enclMethod.owner setType NothingClass.tpe
           }
         }
       }
 
       def typedNew(tpt: Tree) = {
-        var tpt1 = typedTypeConstructor(tpt)
-        checkClassType(tpt1, false)
-        if (tpt1.hasSymbol && !tpt1.symbol.typeParams.isEmpty) {
-          context.undetparams = cloneSymbols(tpt1.symbol.typeParams)
-          tpt1 = TypeTree()
-            .setOriginal(tpt1) /* .setPos(tpt1.pos) */
-            .setType(appliedType(tpt1.tpe, context.undetparams map (_.tpe)))
+        val tpt1 = {
+          val tpt0 = typedTypeConstructor(tpt)
+          checkClassType(tpt0, false, true)
+          if (tpt0.hasSymbol && !tpt0.symbol.typeParams.isEmpty) {
+            context.undetparams = cloneSymbols(tpt0.symbol.typeParams)
+            TypeTree().setOriginal(tpt0)
+                      .setType(appliedType(tpt0.tpe, context.undetparams map (_.tpe)))
+          } else tpt0
         }
+
         /** If current tree <tree> appears in <val x(: T)? = <tree>>
          *  return `tp with x.type' else return `tp'.
          */
-        def narrowRhs(tp: Type) = {
-          var sym = context.tree.symbol
-          if (sym != null && sym != NoSymbol && sym.owner.isClass && sym.getter(sym.owner) != NoSymbol) 
-            sym = sym.getter(sym.owner)
+        def narrowRhs(tp: Type) = { val sym = context.tree.symbol
           context.tree match {
-            case ValDef(mods, _, _, Apply(Select(`tree`, _), _)) if !(mods hasFlag MUTABLE) =>
-              val pre = if (sym.owner.isClass) sym.owner.thisType else NoPrefix
-              intersectionType(List(tp, singleType(pre, sym)))
-            case _ =>
-              tp
-          }
-        }
-        if (tpt1.tpe.typeSymbol.isAbstractType || (tpt1.tpe.typeSymbol hasFlag ABSTRACT))
-          error(tree.pos, tpt1.tpe.typeSymbol + " is abstract; cannot be instantiated")
-        else if (tpt1.tpe.typeSymbol.initialize.thisSym != tpt1.tpe.typeSymbol &&
-                 !(narrowRhs(tpt1.tpe) <:< tpt1.tpe.typeOfThis) && 
-                 !phase.erasedTypes) {
-          error(tree.pos, tpt1.tpe.typeSymbol + 
+            case ValDef(mods, _, _, Apply(Select(`tree`, _), _)) if !(mods hasFlag MUTABLE) && sym != null && sym != NoSymbol =>
+              val sym1 = if (sym.owner.isClass && sym.getter(sym.owner) != NoSymbol) sym.getter(sym.owner)
+                else if ((sym hasFlag LAZY) && sym.lazyAccessor != NoSymbol) sym.lazyAccessor
+                else sym
+              val pre = if (sym1.owner.isClass) sym1.owner.thisType else NoPrefix
+              intersectionType(List(tp, singleType(pre, sym1)))
+            case _ => tp
+          }}
+
+        val tp = tpt1.tpe
+        val sym = tp.typeSymbol
+        if (sym.isAbstractType || (sym hasFlag ABSTRACT))
+          error(tree.pos, sym + " is abstract; cannot be instantiated")
+        else if (!(  tp == sym.initialize.thisSym.tpe // when there's no explicit self type -- with (#3612) or without self variable
+                     // sym.thisSym.tpe == tp.typeOfThis (except for objects)
+                  || narrowRhs(tp) <:< tp.typeOfThis
+                  || phase.erasedTypes
+                  )) {
+          error(tree.pos, sym + 
                 " cannot be instantiated because it does not conform to its self-type "+
-                tpt1.tpe.typeOfThis)
+                tp.typeOfThis)
         }
-        copy.New(tree, tpt1).setType(tpt1.tpe)
+        treeCopy.New(tree, tpt1).setType(tp)
       }
 
       def typedEta(expr1: Tree): Tree = expr1.tpe match {
@@ -2511,7 +3275,7 @@ trait Typers { self: Analyzer =>
                                         pt != WildcardType && 
                                         pt != ErrorType && 
                                         isSubType(pt, DelegateClass.tpe)) =>
-              val scalaCaller = newScalaCaller(pt);
+              val scalaCaller = newScalaCaller(pt)
               addScalaCallerInfo(scalaCaller, expr1.symbol)
               val n: Name = scalaCaller.name
               val del = Ident(DelegateClass) setType DelegateClass.tpe
@@ -2519,7 +3283,7 @@ trait Typers { self: Analyzer =>
               //val f1 = TypeApply(f, List(Ident(pt.symbol) setType pt))
               val args: List[Tree] = if(expr1.symbol.isStatic) List(Literal(Constant(null)))
                                      else List(qual) // where the scala-method is located
-              val rhs = Apply(f, args);
+              val rhs = Apply(f, args)
               typed(rhs)
             case _ => 
               adapt(expr1, mode, functionType(formals map (t => WildcardType), WildcardType))
@@ -2530,54 +3294,6 @@ trait Typers { self: Analyzer =>
           errorTree(expr1, "_ must follow method; cannot follow " + expr1.tpe)
       }
 
-      def typedTypeApply(fun: Tree, args: List[Tree]): Tree = fun.tpe match {
-        case OverloadedType(pre, alts) =>
-          inferPolyAlternatives(fun, args map (_.tpe))
-          val tparams = fun.symbol.typeParams //@M TODO: fun.symbol.info.typeParams ? (as in typedAppliedTypeTree)
-          val args1 = if(args.length == tparams.length) {
-            //@M: in case TypeApply we can't check the kind-arities of the type arguments,
-            // as we don't know which alternative to choose... here we do
-            map2Conserve(args, tparams) { 
-              //@M! the polytype denotes the expected kind
-              (arg, tparam) => typedHigherKindedType(arg, mode, polyType(tparam.typeParams, AnyClass.tpe)) 
-            }          
-          } else // @M: there's probably something wrong when args.length != tparams.length... (triggered by bug #320)
-           // Martin, I'm using fake trees, because, if you use args or arg.map(typedType), 
-           // inferPolyAlternatives loops...  -- I have no idea why :-(
-            args.map(t => errorTree(tree, "wrong number of type parameters for "+treeSymTypeMsg(fun))) 
-          
-          typedTypeApply(fun, args1)
-        case SingleType(_, _) =>
-          typedTypeApply(fun setType fun.tpe.widen, args)
-        case PolyType(tparams, restpe) if (tparams.length != 0) =>
-          if (tparams.length == args.length) {
-            val targs = args map (_.tpe)
-            checkBounds(tree.pos, NoPrefix, NoSymbol, tparams, targs, "")
-            if (fun.symbol == Predef_classOf) {
-              checkClassType(args.head, true) 
-              atPos(tree.pos) { gen.mkClassOf(targs.head) }
-            } else {
-              if (phase.id <= currentRun.typerPhase.id &&
-                  fun.symbol == Any_isInstanceOf && !targs.isEmpty)
-                checkCheckable(tree.pos, targs.head, "")
-              val resultpe = restpe.instantiateTypeParams(tparams, targs)
-              //@M substitution in instantiateParams needs to be careful!
-              //@M example: class Foo[a] { def foo[m[x]]: m[a] = error("") } (new Foo[Int]).foo[List] : List[Int]
-              //@M    --> first, m[a] gets changed to m[Int], then m gets substituted for List, 
-              //          this must preserve m's type argument, so that we end up with List[Int], and not List[a]
-              //@M related bug: #1438 
-              //println("instantiating type params "+restpe+" "+tparams+" "+targs+" = "+resultpe)
-              copy.TypeApply(tree, fun, args) setType resultpe
-            }
-          } else {
-            errorTree(tree, "wrong number of type parameters for "+treeSymTypeMsg(fun))
-          }
-        case ErrorType =>
-          setError(tree)
-        case _ =>
-          errorTree(tree, treeSymTypeMsg(fun)+" does not take type parameters.")
-        }
-
       /**
        *  @param args ...
        *  @return     ...
@@ -2588,6 +3304,7 @@ trait Typers { self: Analyzer =>
         try {
           newTyper(c).typedArgs(args, mode)
         } catch {
+          case ex: CyclicReference => throw ex
           case ex: TypeError =>
             null
         }
@@ -2595,61 +3312,67 @@ trait Typers { self: Analyzer =>
 
       /** Try to apply function to arguments; if it does not work try to
        *  insert an implicit conversion.
-       *
-       *  @param fun  ...
-       *  @param args ...
-       *  @return     ...
        */
-      def tryTypedApply(fun: Tree, args: List[Tree]): Tree = 
+      def tryTypedApply(fun: Tree, args: List[Tree]): Tree = {
+        val start = startTimer(failedApplyNanos)
         silent(_.doTypedApply(tree, fun, args, mode, pt)) match {
-          case t: Tree => 
+          case t: Tree =>
             t
           case ex: TypeError =>
-            def errorInResult(tree: Tree): Boolean = tree.pos == ex.pos || {
-              tree match {
-                case Block(_, r) => errorInResult(r)
-                case Match(_, cases) => cases exists errorInResult
-                case CaseDef(_, _, r) => errorInResult(r)
-                case Annotated(_, r) => errorInResult(r)
-                case If(_, t, e) => errorInResult(t) || errorInResult(e)
-                case Try(b, catches, _) => errorInResult(b) || (catches exists errorInResult)
-                case Typed(r, Function(List(), EmptyTree)) => errorInResult(r)
-                case _ => false
-              }
-            }
-            if (errorInResult(fun) || (args exists errorInResult)) {
+            stopTimer(failedApplyNanos, start)
+            def treesInResult(tree: Tree): List[Tree] = tree :: (tree match {
+              case Block(_, r)                        => treesInResult(r)
+              case Match(_, cases)                    => cases
+              case CaseDef(_, _, r)                   => treesInResult(r)
+              case Annotated(_, r)                    => treesInResult(r)
+              case If(_, t, e)                        => treesInResult(t) ++ treesInResult(e)
+              case Try(b, catches, _)                 => treesInResult(b) ++ catches
+              case Typed(r, Function(Nil, EmptyTree)) => treesInResult(r)
+              case _                                  => Nil
+            })
+            def errorInResult(tree: Tree) = treesInResult(tree) exists (_.pos == ex.pos)
+            
+            if (fun :: tree :: args exists errorInResult) {
+              printTyping("second try for: "+fun+" and "+args)
               val Select(qual, name) = fun
               val args1 = tryTypedArgs(args, argMode(fun, mode), ex)
               val qual1 =
-                if ((args1 ne null) && !pt.isError) {
-                  def templateArgType(arg: Tree) =
-                    new BoundedWildcardType(mkTypeBounds(arg.tpe, AnyClass.tpe))
-                  adaptToMember(qual, name, MethodType(args1 map templateArgType, pt))
-                } else qual
+                if ((args1 ne null) && !pt.isError) adaptToArguments(qual, name, args1, pt) 
+                else qual
               if (qual1 ne qual) {
                 val tree1 = Apply(Select(qual1, name) setPos fun.pos, args1) setPos tree.pos
                 return typed1(tree1, mode | SNDTRYmode, pt)
               }
-            } 
+            } else printTyping("no second try for "+fun+" and "+args+" because error not in result:"+ex.pos+"!="+tree.pos)
+
             reportTypeError(tree.pos, ex)
             setError(tree)
         }
-
+      }
+    
       def typedApply(fun: Tree, args: List[Tree]) = {
         val stableApplication = (fun.symbol ne null) && fun.symbol.isMethod && fun.symbol.isStable
-        if (stableApplication && (mode & PATTERNmode) != 0) {
+        if (stableApplication && isPatternMode) {
           // treat stable function applications f() as expressions.
           typed1(tree, mode & ~PATTERNmode | EXPRmode, pt)
         } else {
-          val funpt = if ((mode & PATTERNmode) != 0) pt else WildcardType
-          silent(_.typed(fun, funMode(mode), funpt)) match {
+          val funpt = if (isPatternMode) pt else WildcardType
+          val appStart = startTimer(failedApplyNanos)
+          val opeqStart = startTimer(failedOpEqNanos)
+          silent(_.typed(fun, funMode(mode), funpt),  
+                 if ((mode & EXPRmode) != 0) false else context.reportAmbiguousErrors,  
+                 if ((mode & EXPRmode) != 0) tree else context.tree) match {
             case fun1: Tree =>
               val fun2 = if (stableApplication) stabilizeFun(fun1, mode, pt) else fun1
-              if (util.Statistics.enabled) appcnt += 1
+              incCounter(typedApplyCount)
+              def isImplicitMethod(tpe: Type) = tpe match {
+                case mt: MethodType => mt.isImplicit
+                case _ => false
+              }
               val res = 
                 if (phase.id <= currentRun.typerPhase.id &&
                     fun2.isInstanceOf[Select] && 
-                    !fun2.tpe.isInstanceOf[ImplicitMethodType] &&
+                    !isImplicitMethod(fun2.tpe) &&
                     ((fun2.symbol eq null) || !fun2.symbol.isConstructor) &&
                     (mode & (EXPRmode | SNDTRYmode)) == EXPRmode) {
                       tryTypedApply(fun2, args)
@@ -2661,63 +3384,87 @@ trait Typers { self: Analyzer =>
                 res.tpe = res.tpe.notNull
               }
               */
-              if (fun2.symbol == Array_apply) typed { atPos(tree.pos) { gen.mkCheckInit(res) } }
+              if (fun2.symbol == Array_apply) {
+                val checked = gen.mkCheckInit(res)
+                // this check is needed to avoid infinite recursion in Duplicators
+                // (calling typed1 more than once for the same tree)
+                if (checked ne res) typed { atPos(tree.pos)(checked) }
+                else res
+              } else res
+              /* Would like to do the following instead, but curiously this fails; todo: investigate
+              if (fun2.symbol.name == nme.apply && fun2.symbol.owner == ArrayClass) 
+                typed { atPos(tree.pos) { gen.mkCheckInit(res) } }
               else res
-                
+              */  
             case ex: TypeError =>
               fun match {
                 case Select(qual, name) 
-                if (mode & PATTERNmode) == 0 && nme.isOpAssignmentName(name.decode) =>
+                if !isPatternMode && nme.isOpAssignmentName(name.decode) =>
                   val qual1 = typedQualifier(qual)
                   if (treeInfo.isVariableOrGetter(qual1)) {
+                    stopTimer(failedOpEqNanos, opeqStart)
                     convertToAssignment(fun, qual1, name, args, ex) 
                   } else {
-		    if ((qual1.symbol ne null) && qual1.symbol.isValue) 
-		      error(tree.pos, "reassignment to val")
-		    else
+                    stopTimer(failedApplyNanos, appStart)
+                    if ((qual1.symbol ne null) && qual1.symbol.isValue) 
+                      error(tree.pos, "reassignment to val")
+                    else
                       reportTypeError(fun.pos, ex)
                     setError(tree)                           
                   }
                 case _ =>
+                  stopTimer(failedApplyNanos, appStart)
                   reportTypeError(fun.pos, ex)
                   setError(tree)                           
               }
           }
         }
       }
-
+    
       def convertToAssignment(fun: Tree, qual: Tree, name: Name, args: List[Tree], ex: TypeError): Tree = {
         val prefix = name.subName(0, name.length - nme.EQL.length)
         def mkAssign(vble: Tree): Tree = 
           Assign(
             vble,
-              Apply(Select(vble.duplicate, prefix) setPos fun.pos, args) setPos tree.pos
+            Apply(
+              Select(vble.duplicate, prefix) setPos fun.pos.focus, args) setPos tree.pos.makeTransparent
           ) setPos tree.pos
+        
+        def mkUpdate(table: Tree, indices: List[Tree]) = {
+          gen.evalOnceAll(table :: indices, context.owner, context.unit) { ts =>
+            val tab = ts.head
+            val is = ts.tail
+            Apply(
+               Select(tab(), nme.update) setPos table.pos,
+               ((is map (i => i())) ::: List(
+                 Apply(
+                   Select(
+                     Apply(
+                       Select(tab(), nme.apply) setPos table.pos,
+                       is map (i => i())) setPos qual.pos,
+                     prefix) setPos fun.pos, 
+                   args) setPos tree.pos)
+               )
+             ) setPos tree.pos
+           }
+        }
+      
         val tree1 = qual match {
+          case Ident(_) =>
+            mkAssign(qual)
+            
           case Select(qualqual, vname) =>
             gen.evalOnce(qualqual, context.owner, context.unit) { qq =>
-              mkAssign(Select(qq(), vname) setPos qual.pos)
+              val qq1 = qq()
+              mkAssign(Select(qq1, vname) setPos qual.pos)
             }
-          case Apply(Select(table, nme.apply), indices) =>
-            gen.evalOnceAll(table :: indices, context.owner, context.unit) { ts =>
-              val tab = ts.head
-              val is = ts.tail
-              Apply(
-                 Select(tab(), nme.update) setPos table.pos,
-                 ((is map (i => i())) ::: List(
-                   Apply(
-                     Select(
-                       Apply(
-                         Select(tab(), nme.apply) setPos table.pos,
-                         is map (i => i())) setPos qual.pos,
-                       prefix) setPos fun.pos, 
-                     args) setPos tree.pos)
-                 )
-               ) setPos tree.pos
-             }
-           case Ident(_) =>
-             mkAssign(qual)
-        }                
+          
+          case Apply(fn, indices) =>
+            treeInfo.methPart(fn) match {
+              case Select(table, nme.apply) => mkUpdate(table, indices)
+              case _                        => errorTree(qual, "Unexpected tree during assignment conversion.")
+            }
+        }
         typed1(tree1, mode, pt)
 /*
         if (settings.debug.value) log("retry assign: "+tree1)
@@ -2731,14 +3478,11 @@ trait Typers { self: Analyzer =>
 */
       }
 
+      def qualifyingClassSym(qual: Name): Symbol =
+        if (tree.symbol != NoSymbol) tree.symbol else qualifyingClass(tree, qual, false)
+
       def typedSuper(qual: Name, mix: Name) = {
-        val (clazz, selftype) =
-          if (tree.symbol != NoSymbol) {
-            (tree.symbol, tree.symbol.thisType)
-          } else {
-            val clazzContext = qualifyingClassContext(tree, qual)
-            (clazzContext.owner, clazzContext.prefix)
-          }
+        val clazz = qualifyingClassSym(qual)
         if (clazz == NoSymbol) setError(tree)
         else {
           def findMixinSuper(site: Type): Type = {
@@ -2769,26 +3513,19 @@ trait Typers { self: Analyzer =>
             } else {
               findMixinSuper(clazz.info)
             }
-          tree setSymbol clazz setType mkSuperType(selftype, owntype)
+          tree setSymbol clazz setType SuperType(clazz.thisType, owntype)
         }
       }
 
       def typedThis(qual: Name) = {
-        val (clazz, selftype) =
-          if (tree.symbol != NoSymbol) {
-            (tree.symbol, tree.symbol.thisType)
-          } else {
-            val clazzContext = qualifyingClassContext(tree, qual)
-            (clazzContext.owner, clazzContext.prefix)
-          }
+        val clazz = qualifyingClassSym(qual)
         if (clazz == NoSymbol) setError(tree)
         else {
-          tree setSymbol clazz setType selftype.underlying
-          if (isStableContext(tree, mode, pt)) tree setType selftype
+          tree setSymbol clazz setType clazz.thisType.underlying
+          if (isStableContext(tree, mode, pt)) tree setType clazz.thisType
           tree
         }
       }
-        
 
       /** Attribute a selection where <code>tree</code> is <code>qual.name</code>.
        *  <code>qual</code> is already attributed.
@@ -2813,63 +3550,88 @@ trait Typers { self: Analyzer =>
             }
             tree.symbol
           } else {
-            if (!inIDE) member(qual, name)(context.owner)
-            else verifyAndPrioritize(_ filter (alt => context.isAccessible(alt, qual.tpe, qual.isInstanceOf[Super])))(pt)(member(qual,name)(context.owner))
+            member(qual, name)
           }
         if (sym == NoSymbol && name != nme.CONSTRUCTOR && (mode & EXPRmode) != 0) {
-          val qual1 = adaptToName(qual, name)
-          if (qual1 ne qual) return typed(copy.Select(tree, qual1, name), mode, pt)
+          val qual1 = try {
+            adaptToName(qual, name)
+          } catch {
+            case ex: TypeError =>
+            // this happens if implicits are ambiguous; try again with more context info.
+            // println("last ditch effort: "+qual+" . "+name) // DEBUG
+            context.tree match {
+              case Apply(tree1, args) if tree1 eq tree => // try handling the arguments
+                // println("typing args: "+args) // DEBUG
+                silent(_.typedArgs(args, mode)) match {
+                  case args: List[_] =>
+                    adaptToArguments(qual, name, args.asInstanceOf[List[Tree]], WildcardType)
+                  case _ =>
+                    throw ex
+                }
+              case _ =>
+                // println("not in an apply: "+context.tree+"/"+tree) // DEBUG
+                throw ex
+            }
+          }
+          if (qual1 ne qual) return typed(treeCopy.Select(tree, qual1, name), mode, pt)
         }
-        if (!sym.exists) {
+        
+        if (!reallyExists(sym)) {
+          if (context.owner.toplevelClass.hasFlag(JAVA) && name.isTypeName) {
+            val tree1 = atPos(tree.pos) { gen.convertToSelectFromType(qual, name)  }
+            if (tree1 != EmptyTree) return typed1(tree1, mode, pt)
+          }
+            
           if (settings.debug.value) Console.err.println("qual = "+qual+":"+qual.tpe+"\nSymbol="+qual.tpe.termSymbol+"\nsymbol-info = "+qual.tpe.termSymbol.info+"\nscope-id = "+qual.tpe.termSymbol.info.decls.hashCode()+"\nmembers = "+qual.tpe.members+"\nname = "+name+"\nfound = "+sym+"\nowner = "+context.enclClass.owner)
-          if (!qual.tpe.widen.isErroneous) {
-            error(tree.pos,
-              if (name == nme.CONSTRUCTOR) 
-                qual.tpe.widen+" does not have a constructor"
-              else 
-                decode(name)+" is not a member of "+qual.tpe.widen +
-                (if (!inIDE && (context.unit ne null) && 
-                    ((for(a <- qual.pos.line; b <- tree.pos.line) yield a < b).getOrElse(false)))
-                  "\npossible cause: maybe a semicolon is missing before `"+decode(name)+"'?"
-                 else ""))
+          
+          def makeErrorTree = {
+            val tree1 = tree match {
+              case Select(_, _) => treeCopy.Select(tree, qual, name)
+              case SelectFromTypeTree(_, _) => treeCopy.SelectFromTypeTree(tree, qual, name)
+            }
+            setError(tree1)
           }
-          setError(tree)
+          
+          if (name == nme.ERROR && onlyPresentation)
+            return makeErrorTree
+            
+          if (!qual.tpe.widen.isErroneous)
+            notAMember(tree, qual, name)
+            
+          if (onlyPresentation) makeErrorTree else setError(tree) 
         } else {
           val tree1 = tree match {
-            case Select(_, _) => copy.Select(tree, qual, name)
-            case SelectFromTypeTree(_, _) => copy.SelectFromTypeTree(tree, qual, name)
+            case Select(_, _) => treeCopy.Select(tree, qual, name)
+            case SelectFromTypeTree(_, _) => treeCopy.SelectFromTypeTree(tree, qual, name)
           }
-          val result = stabilize(checkAccessible(tree1, sym, qual.tpe, qual), qual.tpe, mode, pt)
-          if (!global.phase.erasedTypes && settings.Xchecknull.value && 
-              !sym.isConstructor &&
-              !(qual.tpe <:< NotNullClass.tpe) && !qual.tpe.isNotNull)
+          val (tree2, pre2) = makeAccessible(tree1, sym, qual.tpe, qual)
+          val result = stabilize(tree2, pre2, mode, pt)
+
+          def isPotentialNullDeference() = {
+            phase.id <= currentRun.typerPhase.id &&
+            !sym.isConstructor &&
+            !(qual.tpe <:< NotNullClass.tpe) && !qual.tpe.isNotNull &&
+            !(List(Any_isInstanceOf, Any_asInstanceOf) contains result.symbol)  // null.is/as is not a dereference
+          }
+          // unit is null here sometimes; how are we to know when unit might be null? (See bug #2467.)
+          if (settings.Xchecknull.value && isPotentialNullDeference && unit != null)
             unit.warning(tree.pos, "potential null pointer dereference: "+tree)
-          result
-        }
-      }
 
-      /** does given name name an identifier visible at this point?
-       *
-       *  @param name the given name
-       *  @return     <code>true</code> if an identifier with the given name is visible.
-       */
-      def namesSomeIdent(name: Name): Boolean = {
-        var cx = context
-        while (cx != NoContext) {
-          val pre = cx.enclClass.prefix
-          val defEntry = cx.scope.lookupEntryWithContext(name)(context.owner)
-          if ((defEntry ne null) && defEntry.sym.exists) return true
-          cx = cx.enclClass
-          if ((pre.member(name) filter (
-            sym => sym.exists && context.isAccessible(sym, pre, false))) != NoSymbol) return true
-          cx = cx.outer
-        }
-        var imports = context.imports      // impSym != NoSymbol => it is imported from imports.head
-        while (!imports.isEmpty) {
-          if (imports.head.importedSymbol(name) != NoSymbol) return true
-          imports = imports.tail
+          result match {
+            // could checkAccessible (called by makeAccessible) potentially have skipped checking a type application in qual?
+            case SelectFromTypeTree(qual at TypeTree(), name) if qual.tpe.typeArgs nonEmpty => // TODO: somehow the new qual is not checked in refchecks
+              treeCopy.SelectFromTypeTree(
+                result,
+                (TypeTreeWithDeferredRefCheck(){ () => val tp = qual.tpe; val sym = tp.typeSymbolDirect
+                  // will execute during refchecks -- TODO: make private checkTypeRef in refchecks public and call that one?
+                  checkBounds(qual.pos, tp.prefix, sym.owner, sym.typeParams, tp.typeArgs, "")
+                  qual // you only get to see the wrapped tree after running this check :-p
+                }) setType qual.tpe,
+                name)
+            case _ =>
+              result
+          }
         }
-        false
       }
 
       /** Attribute an identifier consisting of a simple name or an outer reference.
@@ -2885,15 +3647,18 @@ trait Typers { self: Analyzer =>
 
         var defSym: Symbol = tree.symbol // the directly found symbol
         var pre: Type = NoPrefix         // the prefix type of defSym, if a class member
-        var qual: Tree = EmptyTree       // the qualififier tree if transformed tree is a select
+        var qual: Tree = EmptyTree       // the qualifier tree if transformed tree is a select
 
-        // if we are in a constructor of a pattern, ignore all definitions
+        // A symbol qualifies if it exists and is not stale. Stale symbols
+        // are made to disappear here. In addition,
+        // if we are in a constructor of a pattern, we ignore all definitions
         // which are methods (note: if we don't do that
         // case x :: xs in class List would return the :: method).
-        def qualifies(sym: Symbol): Boolean = 
-          sym.exists && 
+        def qualifies(sym: Symbol): Boolean = {
+          reallyExists(sym) &&
           ((mode & PATTERNmode | FUNmode) != (PATTERNmode | FUNmode) || !sym.isSourceMethod)
-           
+        }
+        
         if (defSym == NoSymbol) {
           var defEntry: ScopeEntry = null // the scope entry of defSym, if defined in a local scope
 
@@ -2905,25 +3670,13 @@ trait Typers { self: Analyzer =>
           }
           
           while (defSym == NoSymbol && cx != NoContext) {
+            currentRun.compileSourceFor(context.asInstanceOf[analyzer.Context], name)
             pre = cx.enclClass.prefix
-            defEntry = if (!inIDE) cx.scope.lookupEntryWithContext(name)(context.owner)
-                       else verifyAndPrioritize(sym => sym)(pt)(cx.scope.lookupEntryWithContext(name)(context.owner))
+            defEntry = cx.scope.lookupEntry(name)
             if ((defEntry ne null) && qualifies(defEntry.sym)) {
               defSym = defEntry.sym
-            } else if (inIDE) { // IDE: cannot rely on linked scopes.
-              if (cx.outer.owner eq cx.enclClass.owner) {
-                //cx = cx.outer
-                defSym = 
-                  verifyAndPrioritize{ // enables filtering of auto completion
-                  _ filter (sym => qualifies(sym) && context.isAccessible(sym, pre, false))
-                }(pt)(pre.member(name) filter (
-                    sym => qualifies(sym) && context.isAccessible(sym, pre, false)))
-              }
-              val oldScope = cx.scope
-              cx = cx.outer
-              while (cx.scope == oldScope && !(cx.outer.owner eq cx.enclClass.owner)) // can't skip          
-                cx = cx.outer
-            } else {
+            }
+            else {
               cx = cx.enclClass
               defSym = pre.member(name) filter (
                 sym => qualifies(sym) && context.isAccessible(sym, pre, false))
@@ -2933,9 +3686,9 @@ trait Typers { self: Analyzer =>
 
           val symDepth = if (defEntry eq null) cx.depth
                          else cx.depth - (cx.scope.nestingLevel - defEntry.owner.nestingLevel)
-          var impSym: Symbol = NoSymbol;      // the imported symbol
-          var imports = context.imports;      // impSym != NoSymbol => it is imported from imports.head
-          while (!impSym.exists && !imports.isEmpty && imports.head.depth > symDepth) {
+          var impSym: Symbol = NoSymbol      // the imported symbol
+          var imports = context.imports      // impSym != NoSymbol => it is imported from imports.head
+          while (!reallyExists(impSym) && !imports.isEmpty && imports.head.depth > symDepth) {
             impSym = imports.head.importedSymbol(name)
             if (!impSym.exists) imports = imports.tail
           }
@@ -2947,12 +3700,12 @@ trait Typers { self: Analyzer =>
 
           if (defSym.exists && impSym.exists) {
             // imported symbols take precedence over package-owned symbols in different
-            // compilation units. Defined symbols take precedence over errenous imports.
-            if (defSym.owner.isPackageClass && 
-                ((!inIDE && !currentRun.compiles(defSym)) ||
+            // compilation units. Defined symbols take precedence over erroneous imports.
+            if (defSym.definedInPackage && 
+                (!currentRun.compiles(defSym) ||
                  (context.unit ne null) && defSym.sourceFile != context.unit.source.file))
               defSym = NoSymbol
-            else if (impSym.isError)
+            else if (impSym.isError || impSym.name == nme.CONSTRUCTOR)
               impSym = NoSymbol
           }
           if (defSym.exists) {
@@ -2963,7 +3716,7 @@ trait Typers { self: Analyzer =>
             else if (!defSym.owner.isClass || defSym.owner.isPackageClass || defSym.isTypeParameterOrSkolem)
               pre = NoPrefix
             else
-              qual = atPos(tree.pos)(gen.mkAttributedQualifier(pre))
+              qual = atPos(tree.pos.focusStart)(gen.mkAttributedQualifier(pre))
           } else {
             if (impSym.exists) {
               var impSym1 = NoSymbol
@@ -2977,7 +3730,7 @@ trait Typers { self: Analyzer =>
                      (!imports.head.isExplicitImport(name) ||
                       imports1.head.depth == imports.head.depth)) {
                 var impSym1 = imports1.head.importedSymbol(name)
-                if (impSym1.exists) {
+                if (reallyExists(impSym1)) {
                   if (imports1.head.isExplicitImport(name)) {
                     if (imports.head.isExplicitImport(name) ||
                         imports1.head.depth != imports.head.depth) ambiguousImport()
@@ -2989,36 +3742,37 @@ trait Typers { self: Analyzer =>
                 imports1 = imports1.tail
               }
               defSym = impSym
-              qual = atPos(tree.pos)(resetPos(imports.head.qual.duplicate))
+              val qual0 = imports.head.qual
+              if (!(shortenImports && qual0.symbol.isPackage)) // optimization: don't write out package prefixes
+                qual = atPos(tree.pos.focusStart)(resetPos(qual0.duplicate))
               pre = qual.tpe
             } else {
               if (settings.debug.value) {
                 log(context.imports)//debug
               }
-              error(tree.pos, "not found: "+decode(name))
+              error(tree.pos, "not found: "+decodeWithNamespace(name))
               defSym = context.owner.newErrorSymbol(name)
             }
           }
         }
         if (defSym.owner.isPackageClass) pre = defSym.owner.thisType
         if (defSym.isThisSym) {
-          val tree1 = typed1(This(defSym.owner) setPos tree.pos, mode, pt)
-          if (inIDE) {
-            Ident(defSym.name) setType tree1.tpe setSymbol defSym setPos tree.pos
-          } else tree1
+          typed1(This(defSym.owner) setPos tree.pos, mode, pt)
         } else {
           val tree1 = if (qual == EmptyTree) tree
                       else atPos(tree.pos)(Select(qual, name))
                     // atPos necessary because qualifier might come from startContext
-          stabilize(checkAccessible(tree1, defSym, pre, qual), pre, mode, pt)
+          val (tree2, pre2) = makeAccessible(tree1, defSym, pre, qual)
+          // assert(pre.typeArgs isEmpty) // no need to add #2416-style check here, right?
+          stabilize(tree2, pre2, mode, pt)
         }
       }
 
       def typedCompoundTypeTree(templ: Template) = {
-        val parents1 = List.mapConserve(templ.parents)(typedType(_, mode))
+        val parents1 = templ.parents mapConserve (typedType(_, mode))
         if (parents1 exists (_.tpe.isError)) tree setType ErrorType
         else {
-          val decls = scopeFor(tree, CompoundTreeScopeKind)
+          val decls = new Scope
           //Console.println("Owner: " + context.enclClass.owner + " " + context.enclClass.owner.id)
           val self = refinedType(parents1 map (_.tpe), context.enclClass.owner, decls, templ.pos)
           newTyper(context.make(templ, self.typeSymbol, decls)).typedRefinement(templ.body)
@@ -3033,12 +3787,12 @@ trait Typers { self: Analyzer =>
         } else if (!tpt1.hasSymbol) {
           errorTree(tree, tpt1.tpe+" does not take type parameters")
         } else {
-          val tparams = tpt1.symbol.typeParams 
+          val tparams = tpt1.symbol.typeParams
           if (tparams.length == args.length) {
-          // @M: kind-arity checking is done here and in adapt, full kind-checking is in checkKindBounds (in Infer)
+            // @M: kind-arity checking is done here and in adapt, full kind-checking is in checkKindBounds (in Infer)
             val args1 = 
-              if(!tpt1.symbol.rawInfo.isComplete) 
-                List.mapConserve(args){(x: Tree) => typedHigherKindedType(x, mode)} 
+              if(!tpt1.symbol.rawInfo.isComplete)
+                args mapConserve (typedHigherKindedType(_, mode))
                 // if symbol hasn't been fully loaded, can't check kind-arity
               else map2Conserve(args, tparams) { 
                 (arg, tparam) => 
@@ -3046,11 +3800,8 @@ trait Typers { self: Analyzer =>
                   //@M! the polytype denotes the expected kind
               }
             val argtypes = args1 map (_.tpe)
-            val owntype = if (tpt1.symbol.isClass || tpt1.symbol.isTypeMember) 
-                             // @M! added the latter condition
-                             appliedType(tpt1.tpe, argtypes) 
-                          else tpt1.tpe.instantiateTypeParams(tparams, argtypes)
-            List.map2(args, tparams) { (arg, tparam) => arg match {
+
+            (args, tparams).zipped foreach { (arg, tparam) => arg match {
               // note: can't use args1 in selector, because Bind's got replaced 
               case Bind(_, _) => 
                 if (arg.symbol.isAbstractType)
@@ -3060,29 +3811,43 @@ trait Typers { self: Analyzer =>
                       glb(List(arg.symbol.info.bounds.hi, tparam.info.bounds.hi.subst(tparams, argtypes))))
               case _ =>
             }}
-            TypeTree(owntype) setOriginal(tree) // setPos tree.pos
+
+            val result = TypeTree(appliedType(tpt1.tpe, argtypes)) setOriginal(tree) // setPos tree.pos (done by setOriginal)
+            if(tpt1.tpe.isInstanceOf[PolyType]) // did the type application (performed by appliedType) involve an unchecked beta-reduction?
+              (TypeTreeWithDeferredRefCheck(){ () =>
+                // wrap the tree and include the bounds check -- refchecks will perform this check (that the beta reduction was indeed allowed) and unwrap
+                // we can't simply use original in refchecks because it does not contains types
+                // (and the only typed trees we have have been mangled so they're not quite the original tree anymore)
+                checkBounds(result.pos, tpt1.tpe.prefix, tpt1.symbol.owner, tpt1.symbol.typeParams, argtypes, "")
+                result // you only get to see the wrapped tree after running this check :-p
+              }).setType(result.tpe)
+            else result
           } else if (tparams.length == 0) {
-            if (onePointFourMode && (tpt1.symbol hasFlag JAVA)) tpt1
-            else errorTree(tree, tpt1.tpe+" does not take type parameters")
+            errorTree(tree, tpt1.tpe+" does not take type parameters")
           } else {
             //Console.println("\{tpt1}:\{tpt1.symbol}:\{tpt1.symbol.info}")
-            if (settings.debug.value) Console.println(tpt1+":"+tpt1.symbol+":"+tpt1.symbol.info);//debug
+            if (settings.debug.value) Console.println(tpt1+":"+tpt1.symbol+":"+tpt1.symbol.info)//debug
             errorTree(tree, "wrong number of type arguments for "+tpt1.tpe+", should be "+tparams.length)
           }
         }
       }
 
+      def adaptCase(cdef: CaseDef, tpe: Type): CaseDef = 
+        treeCopy.CaseDef(cdef, cdef.pat, cdef.guard, adapt(cdef.body, mode, tpe))
+
       // begin typed1
-      implicit val scopeKind = TypedScopeKind
       val sym: Symbol = tree.symbol
       if ((sym ne null) && (sym ne NoSymbol)) sym.initialize 
       //if (settings.debug.value && tree.isDef) log("typing definition of "+sym);//DEBUG
       tree match {
-        case PackageDef(name, stats) =>
-          assert(sym.moduleClass ne NoSymbol)
+        case PackageDef(pid, stats) =>
+          val pid1 = typedQualifier(pid).asInstanceOf[RefTree]
+          assert(sym.moduleClass ne NoSymbol, sym)
+          // complete lazy annotations
+          val annots = sym.annotations
           val stats1 = newTyper(context.make(tree, sym.moduleClass, sym.info.decls))
             .typedStats(stats, NoSymbol)
-          copy.PackageDef(tree, name, stats1) setType NoType
+          treeCopy.PackageDef(tree, pid1, stats1) setType NoType
 
         case tree @ ClassDef(_, _, _, _) =>
           newTyper(context.makeNewScope(tree, sym)).typedClassDef(tree)
@@ -3097,42 +3862,45 @@ trait Typers { self: Analyzer =>
           newTyper(context.makeNewScope(tree, sym)).typedDefDef(ddef)
 
         case tdef @ TypeDef(_, _, _, _) =>
-          newTyper(context.makeNewScope(tree, sym)).typedTypeDef(tdef)
+          typedTypeDef(tdef)
 
         case ldef @ LabelDef(_, _, _) =>
           labelTyper(ldef).typedLabelDef(ldef)
 
-        case DocDef(comment, defn) =>
-          val ret = typed(defn, mode, pt)
-          if ((comments ne null) && (defn.symbol ne null) && (defn.symbol ne NoSymbol)) comments(defn.symbol) = comment
-          ret
-
-	case Annotation(constr, elements) =>
-	  val typedConstr = typed(constr, mode, WildcardType)
-	  val typedElems = elements.map(typed(_, mode, WildcardType))
-          (copy.Annotation(tree, typedConstr, typedElems)
-	    setType typedConstr.tpe)
+        case ddef @ DocDef(comment, defn) =>
+          if (onlyPresentation && (sym ne null) && (sym ne NoSymbol)) {
+            docComments(sym) = comment
+            comment.defineVariables(sym)
+            val typer1 = newTyper(context.makeNewScope(tree, context.owner))
+            for (useCase <- comment.useCases) {
+              typer1.silent(_.typedUseCase(useCase)) match {
+                case ex: TypeError =>
+                  unit.warning(useCase.pos, ex.msg)
+                case _ =>
+              }
+              for (useCaseSym <- useCase.defined) {
+                if (sym.name != useCaseSym.name)
+                  unit.warning(useCase.pos, "@usecase " + useCaseSym.name.decode + " does not match commented symbol: " + sym.name.decode)
+              }
+            }
+          }
+          typed(defn, mode, pt)
 
-        case Annotated(annot, arg) =>
-          typedAnnotated(annot, typed(arg, mode, pt))
+        case Annotated(constr, arg) =>
+          typedAnnotated(constr, typed(arg, mode, pt))
 
         case tree @ Block(_, _) =>
-          newTyper(context.makeNewScope(tree, context.owner)(BlockScopeKind(context.depth)))
+          newTyper(context.makeNewScope(tree, context.owner))
             .typedBlock(tree, mode, pt)
 
-        case Sequence(elems) =>
-          checkRegPatOK(tree.pos, mode)
-          val elems1 = List.mapConserve(elems)(elem => typed(elem, mode, pt))
-          copy.Sequence(tree, elems1) setType pt
-
         case Alternative(alts) =>
-          val alts1 = List.mapConserve(alts)(alt => typed(alt, mode | ALTmode, pt))
-          copy.Alternative(tree, alts1) setType pt
+          val alts1 = alts mapConserve (alt => typed(alt, mode | ALTmode, pt))
+          treeCopy.Alternative(tree, alts1) setType pt
 
         case Star(elem) =>
-          checkRegPatOK(tree.pos, mode)
+          checkStarPatOK(tree.pos, mode)
           val elem1 = typed(elem, mode, pt)
-          copy.Star(tree, elem1) setType pt
+          treeCopy.Star(tree, elem1) setType pt
 
         case Bind(name, body) =>
           typedBind(name, body)
@@ -3140,21 +3908,24 @@ trait Typers { self: Analyzer =>
         case UnApply(fun, args) =>
           val fun1 = typed(fun)
           val tpes = formalTypes(unapplyTypeList(fun.symbol, fun1.tpe), args.length)
-          val args1 = List.map2(args, tpes)(typedPattern(_, _))
-          copy.UnApply(tree, fun1, args1) setType pt
+          val args1 = (args, tpes).zipped map (typedPattern(_, _))
+          treeCopy.UnApply(tree, fun1, args1) setType pt
 
         case ArrayValue(elemtpt, elems) =>
           typedArrayValue(elemtpt, elems)
 
         case tree @ Function(_, _) =>
           if (tree.symbol == NoSymbol)
-            tree.symbol = recycle(context.owner.newValue(tree.pos, nme.ANON_FUN_NAME)
-              .setFlag(SYNTHETIC).setInfo(NoType))
+            tree.symbol = context.owner.newValue(tree.pos, nme.ANON_FUN_NAME)
+              .setFlag(SYNTHETIC).setInfo(NoType)
           newTyper(context.makeNewScope(tree, tree.symbol)).typedFunction(tree, mode, pt)
 
         case Assign(lhs, rhs) =>
           typedAssign(lhs, rhs)
 
+        case AssignOrNamedArg(lhs, rhs) => // called by NamesDefaults in silent typecheck
+          typedAssign(lhs, rhs)
+
         case If(cond, thenp, elsep) =>
           typedIf(cond, thenp, elsep)
 
@@ -3162,32 +3933,42 @@ trait Typers { self: Analyzer =>
           if (selector == EmptyTree) {
             val arity = if (isFunctionType(pt)) pt.normalize.typeArgs.length - 1 else 1
             val params = for (i <- List.range(0, arity)) yield 
-              ValDef(Modifiers(PARAM | SYNTHETIC), 
-                  unit.fresh.newName(tree.pos, "x" + i + "$"), TypeTree(), EmptyTree)
+              atPos(tree.pos.focusStart) {
+                ValDef(Modifiers(PARAM | SYNTHETIC), 
+                       unit.fresh.newName(tree.pos, "x" + i + "$"), TypeTree(), EmptyTree)
+              }
             val ids = for (p <- params) yield Ident(p.name)
-            val selector1 = atPos(tree.pos) { if (arity == 1) ids.head else gen.mkTuple(ids) }
-            val body = copy.Match(tree, selector1, cases)
+            val selector1 = atPos(tree.pos.focusStart) { if (arity == 1) ids.head else gen.mkTuple(ids) }
+            val body = treeCopy.Match(tree, selector1, cases)
             typed1(atPos(tree.pos) { Function(params, body) }, mode, pt)
           } else {
-            val selector1 = checkDead(typed(selector))
-            val cases1 = typedCases(tree, cases, selector1.tpe.widen, pt)
-            copy.Match(tree, selector1, cases1) setType ptOrLub(cases1 map (_.tpe))
+            val selector1 = checkDead(typed(selector, EXPRmode | BYVALmode, WildcardType))
+            var cases1 = typedCases(tree, cases, selector1.tpe.widen, pt)
+            val (owntype, needAdapt) = ptOrLub(cases1 map (_.tpe))
+            if (needAdapt) {
+              cases1 = cases1 map (adaptCase(_, owntype))
+            }
+            treeCopy.Match(tree, selector1, cases1) setType owntype
           }
 
         case Return(expr) =>
           typedReturn(expr)
 
         case Try(block, catches, finalizer) =>
-          val block1 = typed(block, pt)
-          val catches1 = typedCases(tree, catches, ThrowableClass.tpe, pt)
+          var block1 = typed(block, pt)
+          var catches1 = typedCases(tree, catches, ThrowableClass.tpe, pt)
           val finalizer1 = if (finalizer.isEmpty) finalizer
                            else typed(finalizer, UnitClass.tpe)
-          copy.Try(tree, block1, catches1, finalizer1)
-            .setType(ptOrLub(block1.tpe :: (catches1 map (_.tpe))))
+          val (owntype, needAdapt) = ptOrLub(block1.tpe :: (catches1 map (_.tpe)))
+          if (needAdapt) {
+            block1 = adapt(block1, mode, owntype)
+            catches1 = catches1 map (adaptCase(_, owntype))
+          }
+          treeCopy.Try(tree, block1, catches1, finalizer1) setType owntype
 
         case Throw(expr) =>
-          val expr1 = typed(expr, ThrowableClass.tpe)
-          copy.Throw(tree, expr1) setType NothingClass.tpe
+          val expr1 = typed(expr, EXPRmode | BYVALmode, ThrowableClass.tpe)
+          treeCopy.Throw(tree, expr1) setType NothingClass.tpe
 
         case New(tpt: Tree) =>
           typedNew(tpt)
@@ -3197,10 +3978,21 @@ trait Typers { self: Analyzer =>
 
         case Typed(expr, tpt) =>
           if (treeInfo.isWildcardStarArg(tree)) {
-            val expr1 = typed(expr, mode & stickyModes, seqType(pt))
-            expr1.tpe.baseType(SeqClass) match {
+            val expr0 = typed(expr, mode & stickyModes, WildcardType)
+            def subArrayType(pt: Type) =
+              if (isValueClass(pt.typeSymbol) || !isFullyDefined(pt)) arrayType(pt)
+              else {
+                val tparam = context.owner freshExistential "" setInfo TypeBounds(NothingClass.tpe, pt)
+                ExistentialType(List(tparam), arrayType(tparam.tpe))
+              }
+            val (expr1, baseClass) = 
+              if (expr0.tpe.typeSymbol == ArrayClass)
+                (adapt(expr0, mode & stickyModes, subArrayType(pt)), ArrayClass)
+              else
+                (adapt(expr0, mode & stickyModes, seqType(pt)), SeqClass)
+            expr1.tpe.baseType(baseClass) match {
               case TypeRef(_, _, List(elemtp)) =>
-                copy.Typed(tree, expr1, tpt setType elemtp) setType elemtp
+                treeCopy.Typed(tree, expr1, tpt setType elemtp) setType elemtp
               case _ =>
                 setError(tree)
             }
@@ -3208,10 +4000,10 @@ trait Typers { self: Analyzer =>
             val tpt1 = typedType(tpt, mode)
             val expr1 = typed(expr, mode & stickyModes, tpt1.tpe.deconst)
             val owntype = 
-              if ((mode & PATTERNmode) != 0) inferTypedPattern(tpt1.pos, tpt1.tpe, pt) 
+              if (isPatternMode) inferTypedPattern(tpt1.pos, tpt1.tpe, pt) 
               else tpt1.tpe
             //Console.println(typed pattern: "+tree+":"+", tp = "+tpt1.tpe+", pt = "+pt+" ==> "+owntype)//DEBUG
-            copy.Typed(tree, expr1, tpt1) setType owntype
+            treeCopy.Typed(tree, expr1, tpt1) setType owntype
           }
 
         case TypeApply(fun, args) =>
@@ -3244,22 +4036,41 @@ trait Typers { self: Analyzer =>
                       // in the then-branch above. (see pos/tcpoly_overloaded.scala)
                       // this assert is too strict: be tolerant for errors like trait A { def foo[m[x], g]=error(""); def x[g] = foo[g/*ERR: missing argument type*/] }
                       //assert(fun1.symbol.info.isInstanceOf[OverloadedType] || fun1.symbol.isError) //, (fun1.symbol,fun1.symbol.info,fun1.symbol.info.getClass,args,tparams))
-                        List.mapConserve(args)(typedHigherKindedType(_, mode)) 
+                        args mapConserve (typedHigherKindedType(_, mode)) 
                       }
 
           //@M TODO: context.undetparams = undets_fun ?
-          typedTypeApply(fun1, args1)
+          typedTypeApply(tree, mode, fun1, args1)
 
         case Apply(Block(stats, expr), args) =>
           typed1(atPos(tree.pos)(Block(stats, Apply(expr, args))), mode, pt)
 
         case Apply(fun, args) =>
-          typedApply(fun, args)
+          typedApply(fun, args) match {
+            case Apply(Select(New(tpt), name), args) 
+            if (tpt.tpe != null &&
+                tpt.tpe.typeSymbol == ArrayClass && 
+                args.length == 1 && 
+                erasure.GenericArray.unapply(tpt.tpe).isDefined) => // !!! todo simplify by using extractor
+              // convert new Array[T](len) to evidence[ClassManifest[T]].newArray(len)
+              // convert new Array^N[T](len) for N > 1 to evidence[ClassManifest[T]].newArrayN(len)
+              val Some((level, manifType)) = erasure.GenericArray.unapply(tpt.tpe)
+              if (level > MaxArrayDims) 
+                error(tree.pos, "cannot create a generic multi-dimensional array of more than "+MaxArrayDims+" dimensions")
+              val newArrayApp = atPos(tree.pos) {
+                val manif = getManifestTree(tree.pos, manifType, false)
+                new ApplyToImplicitArgs(Select(manif, if (level == 1) "newArray" else "newArray"+level), args)
+              }
+              typed(newArrayApp, mode, pt)
+            case tree1 =>
+              tree1
+          }
 
         case ApplyDynamic(qual, args) =>
+          val reflectiveCalls = !(settings.refinementMethodDispatch.value == "invoke-dynamic") 
           val qual1 = typed(qual, AnyRefClass.tpe)
-          val args1 = List.mapConserve(args)(arg => typed(arg, AnyRefClass.tpe))
-          copy.ApplyDynamic(tree, qual1, args1) setType AnyRefClass.tpe
+          val args1 = args mapConserve (arg => if (reflectiveCalls) typed(arg, AnyRefClass.tpe) else typed(arg))
+          treeCopy.ApplyDynamic(tree, qual1, args1) setType (if (reflectiveCalls) AnyRefClass.tpe else tree.symbol.info.resultType)
 
         case Super(qual, mix) =>
           typedSuper(qual, mix)
@@ -3274,25 +4085,45 @@ trait Typers { self: Analyzer =>
           typedSelect(qual1, nme.CONSTRUCTOR)
 
         case Select(qual, name) =>
-          if (util.Statistics.enabled) selcnt += 1
+          incCounter(typedSelectCount)
           var qual1 = checkDead(typedQualifier(qual, mode))
           if (name.isTypeName) qual1 = checkStable(qual1)
-          val tree1 = typedSelect(qual1, name)
-          if (qual1.symbol == RootPackage) copy.Ident(tree1, name)
+
+          val tree1 = // temporarily use `filter' and an alternative for `withFilter'
+            if (name == nme.withFilter)
+              silent(_ => typedSelect(qual1, name)) match {
+                case result1: Tree => 
+                  result1
+                case ex1: TypeError =>
+                  silent(_ => typed1(Select(qual1, nme.filter) setPos tree.pos, mode, pt)) match {
+                    case result2: Tree =>
+                      unit.deprecationWarning(
+                        tree.pos, "`withFilter' method does not yet exist on "+qual1.tpe.widen+
+                        ", using `filter' method instead")
+                      result2
+                    case ex2: TypeError =>
+                      reportTypeError(tree.pos, ex1)
+                      setError(tree)
+                  }
+              }
+            else
+              typedSelect(qual1, name)
+
+          if (qual1.symbol == RootPackage) treeCopy.Ident(tree1, name)
           else tree1
 
         case Ident(name) =>
-          if (util.Statistics.enabled) idcnt += 1
+          incCounter(typedIdentCount)
           if ((name == nme.WILDCARD && (mode & (PATTERNmode | FUNmode)) == PATTERNmode) ||
               (name == nme.WILDCARD.toTypeName && (mode & TYPEmode) != 0))
-            tree setType pt
+            tree setType makeFullyDefined(pt)
           else 
             typedIdent(name)
           
         case Literal(value) =>
           tree setType (
             if (value.tag == UnitTag) UnitClass.tpe
-            else mkConstantType(value))
+            else ConstantType(value))
 
         case SingletonTypeTree(ref) =>
           val ref1 = checkStable(
@@ -3302,7 +4133,7 @@ trait Typers { self: Analyzer =>
         case SelectFromTypeTree(qual, selector) =>
           val qual1 = typedType(qual, mode)
           if (qual1.tpe.isVolatile) error(tree.pos, "illegal type selection from volatile type "+qual.tpe) 
-          typedSelect(typedType(qual, mode), selector)
+          typedSelect(qual1, selector)
 
         case CompoundTypeTree(templ) =>
           typedCompoundTypeTree(templ)
@@ -3313,19 +4144,25 @@ trait Typers { self: Analyzer =>
         case TypeBoundsTree(lo, hi) =>
           val lo1 = typedType(lo, mode)
           val hi1 = typedType(hi, mode)
-          copy.TypeBoundsTree(tree, lo1, hi1) setType mkTypeBounds(lo1.tpe, hi1.tpe)
+          treeCopy.TypeBoundsTree(tree, lo1, hi1) setType TypeBounds(lo1.tpe, hi1.tpe)
 
         case etpt @ ExistentialTypeTree(_, _) =>
           newTyper(context.makeNewScope(tree, context.owner)).typedExistentialTypeTree(etpt, mode)
 
-        case TypeTree() =>
-          // we should get here only when something before failed 
-          // and we try again (@see tryTypedApply). In that case we can assign 
-          // whatever type to tree; we just have to survive until a real error message is issued.
-          tree setType AnyClass.tpe
-        case EmptyTree if inIDE => EmptyTree // just tolerate it in the IDE.
+        case dc at TypeTreeWithDeferredRefCheck() => dc // TODO: should we re-type the wrapped tree? then we need to change TypeTreeWithDeferredRefCheck's representation to include the wrapped tree explicitly (instead of in its closure)
+        case tpt @ TypeTree() =>
+          if (tpt.original != null)
+            tree setType typedType(tpt.original, mode).tpe
+          else
+            // we should get here only when something before failed 
+            // and we try again (@see tryTypedApply). In that case we can assign 
+            // whatever type to tree; we just have to survive until a real error message is issued.
+            tree setType AnyClass.tpe
+        case Import(expr, selectors) =>
+          assert(onlyPresentation) // should not happen in normal circumstances.
+          tree setType tree.symbol.tpe
         case _ =>
-          throw new Error("unexpected tree: " + tree.getClass + "\n" + tree)//debug
+          abort("unexpected tree: " + tree.getClass + "\n" + tree)//debug
       }
     }
 
@@ -3335,50 +4172,70 @@ trait Typers { self: Analyzer =>
      *  @param pt   ...
      *  @return     ...
      */
-    def typed(tree: Tree, mode: Int, pt: Type): Tree =
+     def typed(tree: Tree, mode: Int, pt: Type): Tree = { indentTyping()
+      def dropExistential(tp: Type): Type = tp match {
+        case ExistentialType(tparams, tpe) => 
+          if (settings.debug.value) println("drop ex "+tree+" "+tp)
+          new SubstWildcardMap(tparams).apply(tp)
+        case TypeRef(_, sym, _) if sym.isAliasType =>
+          val tp0 = tp.normalize
+          val tp1 = dropExistential(tp0)
+          if (tp1 eq tp0) tp else tp1
+        case _ => tp
+      }
+
       try {
-        if (settings.debug.value)
-          assert(pt ne null, tree)//debug
+        if (Statistics.enabled) {
+          val t = currentTime()
+          if (pendingTreeTypes.nonEmpty) {
+            microsByType(pendingTreeTypes.head) += ((t - typerTime) / 1000).toInt
+          }
+          typerTime = t
+          pendingTreeTypes = tree.getClass :: pendingTreeTypes
+        }
         if (context.retyping &&
             (tree.tpe ne null) && (tree.tpe.isErroneous || !(tree.tpe <:< pt))) {
           tree.tpe = null
           if (tree.hasSymbol) tree.symbol = NoSymbol
         }
-        if (printTypings) println("typing "+tree+", "+context.undetparams+(mode & TYPEPATmode));//DEBUG
-        def dropExistential(tp: Type): Type = tp match {
-          case ExistentialType(tparams, tpe) => 
-            if (settings.debug.value) println("drop ex "+tree+" "+tp)
-            new SubstWildcardMap(tparams).apply(tp)
-          case TypeRef(_, sym, _) if sym.isAliasType =>
-            val tp0 = tp.normalize
-            val tp1 = dropExistential(tp0)
-            if (tp1 eq tp0) tp else tp1
-          case _ => tp
-        }
+        printTyping("typing "+tree+", pt = "+pt+", undetparams = "+context.undetparams+", implicits-enabled = "+context.implicitsEnabled+", silent = "+context.reportGeneralErrors) //DEBUG
+
         var tree1 = if (tree.tpe ne null) tree else typed1(tree, mode, dropExistential(pt))
-        if (printTypings) println("typed "+tree1+":"+tree1.tpe+", "+context.undetparams+", pt = "+pt);//DEBUG
+        printTyping("typed "+tree1+":"+tree1.tpe+(if (isSingleType(tree1.tpe)) " with underlying "+tree1.tpe.widen else "")+", undetparams = "+context.undetparams+", pt = "+pt) //DEBUG
        
         tree1.tpe = addAnnotations(tree1, tree1.tpe)
 
-        val result = if (tree1.isEmpty || (inIDE && tree1.tpe == null)) tree1 else adapt(tree1, mode, pt)
-        if (printTypings) println("adapted "+tree1+":"+tree1.tpe+" to "+pt+", "+context.undetparams);//DEBUG
+        val result = if (tree1.isEmpty) tree1 else adapt(tree1, mode, pt, tree)
+        printTyping("adapted "+tree1+":"+tree1.tpe.widen+" to "+pt+", "+context.undetparams) //DEBUG
+//      for (t <- tree1.tpe) assert(t != WildcardType)
 //      if ((mode & TYPEmode) != 0) println("type: "+tree1+" has type "+tree1.tpe)
+        if (phase.id <= currentRun.typerPhase.id) signalDone(context.asInstanceOf[analyzer.Context], tree, result)
         result
       } catch {
         case ex: TypeError =>
-          if (inIDE) throw ex
           tree.tpe = null
-          //Console.println("caught "+ex+" in typed");//DEBUG
+          printTyping("caught "+ex+" in typed: "+tree) //DEBUG
           reportTypeError(tree.pos, ex)
           setError(tree)
         case ex: Exception =>
-//          if (settings.debug.value) // @M causes cyclic reference error
-//            Console.println("exception when typing "+tree+", pt = "+pt)
+          if (settings.debug.value) // @M causes cyclic reference error
+            Console.println("exception when typing "+tree+", pt = "+pt)
           if ((context ne null) && (context.unit ne null) &&
               (context.unit.source ne null) && (tree ne null))
-            logError("AT: " + (tree.pos).dbgString, ex);
-          throw(ex)
+            logError("AT: " + (tree.pos).dbgString, ex)
+          throw ex
       }
+      finally {
+        deindentTyping()
+        if (Statistics.enabled) {
+          val t = currentTime()
+          microsByType(pendingTreeTypes.head) += ((t - typerTime) / 1000).toInt
+          visitsByType(pendingTreeTypes.head) += 1
+          typerTime = t
+          pendingTreeTypes = pendingTreeTypes.tail
+        }
+      }
+    }
 
     def atOwner(owner: Symbol): Typer =
       newTyper(context.make(context.tree, owner))
@@ -3396,6 +4253,8 @@ trait Typers { self: Analyzer =>
       ret
     }
 
+    def typedPos(pos: Position)(tree: Tree) = typed(atPos(pos)(tree))
+
     /** Types expression <code>tree</code> with given prototype <code>pt</code>.
      *
      *  @param tree ...
@@ -3407,22 +4266,32 @@ trait Typers { self: Analyzer =>
 
     /** Types qualifier <code>tree</code> of a select node.
      *  E.g. is tree occurs in a context like <code>tree.m</code>.
-     *
-     *  @param tree ...
-     *  @return     ...
+     */
+    def typedQualifier(tree: Tree, mode: Int, pt: Type): Tree =
+      typed(tree, EXPRmode | QUALmode | POLYmode | mode & TYPEPATmode, pt) // TR: don't set BYVALmode, since qualifier might end up as by-name param to an implicit
+
+    /** Types qualifier <code>tree</code> of a select node.
+     *  E.g. is tree occurs in a context like <code>tree.m</code>.
      */
     def typedQualifier(tree: Tree, mode: Int): Tree =
-      typed(tree, EXPRmode | QUALmode | POLYmode | mode & TYPEPATmode, WildcardType)
+      typedQualifier(tree, mode, WildcardType)
 
-    def typedQualifier(tree: Tree): Tree = typedQualifier(tree, NOmode)
+    def typedQualifier(tree: Tree): Tree = typedQualifier(tree, NOmode, WildcardType)
 
     /** Types function part of an application */
     def typedOperator(tree: Tree): Tree =
       typed(tree, EXPRmode | FUNmode | POLYmode | TAPPmode, WildcardType)
 
     /** Types a pattern with prototype <code>pt</code> */
-    def typedPattern(tree: Tree, pt: Type): Tree =
-      typed(tree, PATTERNmode, pt)
+    def typedPattern(tree: Tree, pt: Type): Tree = {
+      // We disable implicits because otherwise some constructs will
+      // type check which should not.  The pattern matcher does not
+      // perform implicit conversions in an attempt to consummate a match.
+      val savedImplicitsEnabled = context.implicitsEnabled
+      context.implicitsEnabled = false
+      try typed(tree, PATTERNmode, pt)
+      finally context.implicitsEnabled = savedImplicitsEnabled
+    }
 
     /** Types a (fully parameterized) type tree */
     def typedType(tree: Tree, mode: Int): Tree =
@@ -3444,11 +4313,26 @@ trait Typers { self: Analyzer =>
     /** Types a type constructor tree used in a new or supertype */
     def typedTypeConstructor(tree: Tree, mode: Int): Tree = {
       val result = typed(tree, typeMode(mode) | FUNmode, WildcardType)
-      val restpe = result.tpe.normalize
+
+      val restpe = result.tpe.normalize // normalize to get rid of type aliases for the following check (#1241)
       if (!phase.erasedTypes && restpe.isInstanceOf[TypeRef] && !restpe.prefix.isStable) {
         error(tree.pos, restpe.prefix+" is not a legal prefix for a constructor")
       }
-      result setType restpe // @M: normalization is done during erasure
+
+      //@M fix for #2208
+      // if there are no type arguments, normalization does not bypass any checks, so perform it to get rid of AnyRef
+      if(result.tpe.typeArgs.isEmpty) {
+        // minimal check: if(result.tpe.typeSymbolDirect eq AnyRefClass) {
+        // must expand the fake AnyRef type alias, because bootstrapping (init in Definitions) is not
+        // designed to deal with the cycles in the scala package (ScalaObject extends
+        // AnyRef, but the AnyRef type alias is entered after the scala package is
+        // loaded and completed, so that ScalaObject is unpickled while AnyRef is not
+        // yet defined )
+        result setType(restpe)
+      } else { // must not normalize: type application must be (bounds-)checked (during RefChecks), see #2208
+        // during uncurry (after refchecks), all types are normalized
+        result
+      }
     }
 
     def typedTypeConstructor(tree: Tree): Tree = typedTypeConstructor(tree, NOmode)
@@ -3459,401 +4343,32 @@ trait Typers { self: Analyzer =>
       packedType(tree1, context.owner)
     }
 
-    def transformedOrTyped(tree: Tree, pt: Type): Tree = transformed.get(tree) match {
+    def transformedOrTyped(tree: Tree, mode: Int, pt: Type): Tree = transformed.get(tree) match {
       case Some(tree1) => transformed -= tree; tree1
-      case None => typed(tree, pt)
+      case None => typed(tree, mode, pt)
+    }
+
+    def findManifest(tp: Type, full: Boolean) = atPhase(currentRun.typerPhase) {
+      inferImplicit(
+        EmptyTree, 
+        appliedType((if (full) FullManifestClass else PartialManifestClass).typeConstructor, List(tp)),
+        true, false, context)
     }
 
+    def getManifestTree(pos: Position, tp: Type, full: Boolean): Tree = {
+      val manifestOpt = findManifest(tp, full)
+      if (manifestOpt.tree.isEmpty) {
+        error(pos, "cannot find "+(if (full) "" else "class ")+"manifest for element type "+tp)
+        Literal(Constant(null))
+      } else {
+        manifestOpt.tree
+      }
+    }
 /*
     def convertToTypeTree(tree: Tree): Tree = tree match {
       case TypeTree() => tree
       case _ => TypeTree(tree.tpe)
     }
 */
-    /* -- Views --------------------------------------------------------------- */
-
-    private def tparamsToWildcards(tp: Type, tparams: List[Symbol]) =
-      tp.instantiateTypeParams(tparams, tparams map (t => WildcardType))
-
-    private def depoly(tp: Type): Type = tp match {
-      case PolyType(tparams, restpe) => tparamsToWildcards(restpe, tparams)
-      case _ => tp
-    }
-
-    private def containsError(tp: Type): Boolean = tp match {
-      case PolyType(tparams, restpe) => containsError(restpe)
-      case MethodType(formals, restpe) => (formals exists (_.isError)) || containsError(restpe)
-      case _ => tp.isError
-    }
-
-    private def dominates(dtor: Type, dted: Type): Boolean = {
-      def core(tp: Type): Type = tp.normalize match {
-        case RefinedType(parents, defs) => intersectionType(parents map core, tp.typeSymbol.owner)
-        case AnnotatedType(attribs, tp, selfsym) => core(tp)
-        case ExistentialType(tparams, result) => core(result).subst(tparams, tparams map (t => core(t.info.bounds.hi)))
-        case PolyType(tparams, result) => core(result).subst(tparams, tparams map (t => core(t.info.bounds.hi)))
-        case _ => tp
-      }
-      def stripped(tp: Type): Type = {
-        val tparams = freeTypeParametersNoSkolems.collect(tp)
-        tp.subst(tparams, tparams map (t => WildcardType))
-      }
-      def sum(xs: List[Int]) = (0 /: xs)(_ + _)
-      def complexity(tp: Type): Int = tp.normalize match {
-        case NoPrefix =>
-          0
-        case SingleType(pre, sym) => 
-          if (sym.isPackage) 0 else complexity(tp.widen)
-        case TypeRef(pre, sym, args) => 
-          complexity(pre) + sum(args map complexity) + 1
-        case RefinedType(parents, _) => 
-          sum(parents map complexity) + 1
-        case _ => 
-          1
-      }
-      def overlaps(tp1: Type, tp2: Type): Boolean = (tp1, tp2) match {
-        case (RefinedType(parents, _), _) => parents exists (overlaps(_, tp2))
-        case (_, RefinedType(parents, _)) => parents exists (overlaps(tp1, _))
-        case _ => tp1.typeSymbol == tp2.typeSymbol
-      }
-      val dtor1 = stripped(core(dtor))
-      val dted1 = stripped(core(dted))
-      overlaps(dtor1, dted1) && (dtor1 =:= dted1 || complexity(dtor1) > complexity(dted1))
-    }
-
-    /** Try to construct a typed tree from given implicit info with given
-     *  expected type.
-     *
-     *  @param pos     Position for error reporting
-     *  @param info    The given implicit info describing the implicit definition
-     *  @param pt0     The unnormalized expected type
-     *  @param pt      The normalized expected type
-     *  @param isLocal Is implicit definition visible without prefix?
-     *  @return        A typed tree if the implicit info can be made to conform
-     *                 to <code>pt</code>, EmptyTree otherwise.
-     *  @pre           <code>info.tpe</code> does not contain an error
-     */
-    private def typedImplicit(pos: Position, info: ImplicitInfo, pt0: Type, pt: Type, isLocal: Boolean): Tree =
-       context.openImplicits find (dominates(pt, _)) match {
-         case Some(pending) =>
-           throw DivergentImplicit
-           EmptyTree
-         case None =>
-           try {
-             context.openImplicits = pt :: context.openImplicits
-             typedImplicit0(pos, info, pt0, pt, isLocal)
-           } catch {
-             case DivergentImplicit => 
-               if (context.openImplicits.tail.isEmpty) {
-                 if (!(pt.isErroneous))
-                   context.unit.error(
-                     pos, "diverging implicit expansion for type "+pt+"\nstarting with "+
-                     info.sym+info.sym.locationString)
-                 EmptyTree
-               } else {
-                 throw DivergentImplicit
-               }
-           } finally {
-             context.openImplicits = context.openImplicits.tail
-           }
-       }
-
-    private def typedImplicit0(pos: Position, info: ImplicitInfo, pt0: Type, pt: Type, isLocal: Boolean): Tree = {
-      def isStable(tp: Type): Boolean = tp match {
-        case TypeRef(pre, sym, _) => sym.isPackageClass || sym.isModuleClass && isStable(pre)
-        case _ => tp.isStable
-      }
-      // println("typed impl for "+pt+"? "+info.name+":"+info.tpe+(isPlausiblyCompatible(info.tpe, pt))+isCompatible(depoly(info.tpe), pt)+isStable(info.pre))
-      if (isPlausiblyCompatible(info.tpe, pt) && isCompatible(depoly(info.tpe), pt) && isStable(info.pre)) {
-        val tree = atPos(pos) {
-          if (info.pre == NoPrefix/*isLocal*/) Ident(info.name)
-          else Select(gen.mkAttributedQualifier(info.pre), info.name)
-        }
-        // println("typed impl?? "+info.name+":"+info.tpe+" ==> "+tree+" with "+pt)
-        def fail(reason: String): Tree = {
-          if (settings.XlogImplicits.value)
-            inform(tree+" is not a valid implicit value for "+pt+" because:\n"+reason)
-          EmptyTree
-        }
-        try {
-          // if (!isLocal) tree setSymbol info.sym
-          val isView = pt0 match {
-            case MethodType(_, _) | PolyType(_, _) => true
-            case _ => false
-          }
-          val tree1 = 
-            if (isView) 
-              typed1(Apply(tree, List(Ident("<argument>") setType pt0.paramTypes.head)), EXPRmode, pt0.resultType)
-            else
-              typed1(tree, EXPRmode, pt)
-          //if (settings.debug.value) println("typed implicit "+tree1+":"+tree1.tpe+", pt = "+pt)
-          val tree2 = if (isView) (tree1: @unchecked) match { case Apply(fun, _) => fun }
-                      else adapt(tree1, EXPRmode, pt)
-          //if (settings.debug.value) println("adapted implicit "+tree1.symbol+":"+tree2.tpe+" to "+pt)("adapted implicit "+tree1.symbol+":"+tree2.tpe+" to "+pt)
-          def hasMatchingSymbol(tree: Tree): Boolean = (tree.symbol == info.sym) || {
-            tree match {
-              case Apply(fun, _) => hasMatchingSymbol(fun)
-              case TypeApply(fun, _) => hasMatchingSymbol(fun)
-              case Select(pre, name) => name == nme.apply && pre.symbol == info.sym
-              case _ => false
-            }
-          }
-          if (tree2.tpe.isError) EmptyTree
-          else if (hasMatchingSymbol(tree1)) tree2
-          else if (settings.XlogImplicits.value) 
-            fail("candidate implicit "+info.sym+info.sym.locationString+
-                 " is shadowed by other implicit: "+tree1.symbol+tree1.symbol.locationString)
-          else EmptyTree
-        } catch {
-          case ex: TypeError => fail(ex.getMessage())
-        }
-      } else EmptyTree
-    }
-
-    /** Infer implicit argument or view.
-     *
-     *  @param  pos             position for error reporting
-     *  @param  pt0             the expected type of the implicit
-     *  @param  isView          are we searching for a view? (this affects the error message)
-     *  @param  reportAmbiguous should ambiguous errors be reported?
-     *                          False iff we search for a view to find out
-     *                          whether one type is coercible to another
-     *  @return                 ...
-     *  @see                    <code>isCoercible</code>
-     */
-    private def inferImplicit(pos: Position, pt0: Type, reportAmbiguous: Boolean): Tree = {
-      val pt = normalize(pt0)
-      val isView = pt0.isInstanceOf[MethodType]
-
-      if (util.Statistics.enabled) implcnt += 1
-      val startTime = if (util.Statistics.enabled) currentTime else 0l
-
-      val tc = newTyper(context.makeImplicit(reportAmbiguous))
-
-      def ambiguousImplicitError(info1: ImplicitInfo, info2: ImplicitInfo, 
-                                 pre1: String, pre2: String, trailer: String) =
-        if (!info1.tpe.isErroneous && !info2.tpe.isErroneous) {
-          val coreMsg = 
-            pre1+" "+info1.sym+info1.sym.locationString+" of type "+info1.tpe+"\n "+
-            pre2+" "+info2.sym+info2.sym.locationString+" of type "+info2.tpe+"\n "+
-            trailer
-          error(pos, 
-            if (isView) {
-              val found = pt.typeArgs(0)
-              val req = pt.typeArgs(1)
-              typeErrorMsg(found, req)+
-              "\nNote that implicit conversions are not applicable because they are ambiguous:\n "+
-              coreMsg+"are possible conversion functions from "+ found+" to "+req
-            } else {
-              "ambiguous implicit values:\n "+coreMsg + "match expected type "+pt
-            })
-        }
-
-      /** Search list of implicit info lists for one matching prototype
-       *  <code>pt</code>. If found return a tree from found implicit info
-       *  which is typed with expected type <code>pt</code>.
-       *  Otherwise return EmptyTree
-       *
-       *  @param implicitInfoss The given list of lists of implicit infos
-       *  @param isLocal        Is implicit definition visible without prefix?
-       *                        If this is the case then symbols in preceding lists shadow 
-       *                        symbols of the same name in succeeding lists.
-       *  @return               ...
-       */
-      def searchImplicit(implicitInfoss: List[List[ImplicitInfo]], isLocal: Boolean): Tree = {
-        def isSubClassOrObject(sym1: Symbol, sym2: Symbol): Boolean =
-          sym1 != NoSymbol && (sym1 isSubClass sym2) ||
-          sym1.isModuleClass && isSubClassOrObject(sym1.linkedClassOfClass, sym2) ||
-          sym2.isModuleClass && isSubClassOrObject(sym1, sym2.linkedClassOfClass)
-        def improves(info1: ImplicitInfo, info2: ImplicitInfo) =
-          (info2 == NoImplicitInfo) ||
-          (info1 != NoImplicitInfo) &&
-          isStrictlyMoreSpecific(info1.tpe, info2.tpe)
-        val shadowed = new HashSet[Name](8)
-        def hasExplicitResultType(sym: Symbol) = {
-          def hasExplicitRT(tree: Tree) = tree match {
-            case ValDef(_, _, tpt, _) => !tpt.isEmpty
-            case DefDef(_, _, _, _, tpt, _) => !tpt.isEmpty
-            case _ => false
-          }
-          sym.rawInfo match {
-            case tc: TypeCompleter => hasExplicitRT(tc.tree)
-            case PolyType(_, tc: TypeCompleter) => hasExplicitRT(tc.tree)
-            case _ => true
-          }
-        }
-        def comesBefore(sym: Symbol, owner: Symbol) =
-          sym.pos.offset.getOrElse(0) < owner.pos.offset.getOrElse(Integer.MAX_VALUE) &&
-          !(owner.ownerChain contains sym)
-
-        /** Should implicit definition symbol `sym' be considered for applicability testing?
-         *  This is the case if one of the following holds:
-         *   - the symbol's type is initialized
-         *   - the symbol comes from a classfile
-         *   - the symbol comes from a different sourcefile than the current one
-         *   - the symbol's definition comes before, and does not contain the closest enclosing definition,
-         *   - the symbol's definition is a val, var, or def with an explicit result type
-         *  The aim of this method is to prevent premature cyclic reference errors
-         *  by computing the types of only those implicitis for which one of these 
-         *  conditions is true.
-         */
-        def isValid(sym: Symbol) = {
-          sym.isInitialized ||
-          sym.sourceFile == null ||
-          (sym.sourceFile ne context.unit.source.file) || 
-          hasExplicitResultType(sym) ||
-          comesBefore(sym, context.owner)
-        }
-        val lateImpls = new ListBuffer[Symbol]
-        def isApplicable(info: ImplicitInfo): Boolean =
-          !containsError(info.tpe) &&
-          !(isLocal && shadowed.contains(info.name)) &&
-          (!isView || info.sym != Predef_identity) &&
-          tc.typedImplicit(pos, info, pt0, pt, isLocal) != EmptyTree
-        def applicableInfos(is: List[ImplicitInfo]): List[ImplicitInfo] = {
-          val applicable = new ListBuffer[ImplicitInfo]
-          for (i <- is)
-            if (!isValid(i.sym)) lateImpls += i.sym
-            else if (isApplicable(i)) applicable += i
-          if (isLocal)
-            for (i <- is) shadowed addEntry i.name
-          applicable.toList
-        }
-        val applicable = implicitInfoss flatMap applicableInfos
-        if (applicable.isEmpty && !lateImpls.isEmpty) {
-          infer.setAddendum(pos, () =>
-            "\n Note: implicit "+lateImpls.first+" is not applicable here"+
-            "\n because it comes after the application point and it lacks an explicit result type")
-        }
-        val best = (NoImplicitInfo /: applicable) ((best, alt) => if (improves(alt, best)) alt else best)
-        if (best == NoImplicitInfo) EmptyTree
-        else {
-          val competing = applicable dropWhile (alt => best == alt || improves(best, alt))
-          if (!competing.isEmpty) ambiguousImplicitError(best, competing.head, "both", "and", "")
-          for (alt <- applicable)
-            if (alt.sym.owner != best.sym.owner && isSubClassOrObject(alt.sym.owner, best.sym.owner)) {
-              ambiguousImplicitError(best, alt, 
-                                     "most specific definition is:",
-                                     "yet alternative definition  ",
-                                     "is defined in a subclass.\n Both definitions ")
-            }
-          tc.typedImplicit(pos, best, pt0, pt, isLocal)
-        }
-      }
-
-      def implicitsOfType(tp: Type): List[List[ImplicitInfo]] = {
-        def getParts(tp: Type, s: collection.jcl.Set[Type]) {
-          tp match {
-            case TypeRef(pre, sym, args) if (!sym.isPackageClass) =>
-              for (bc <- sym.info.baseClasses)
-                if (sym.isClass) s add (tp.baseType(bc))
-              getParts(pre, s)
-              for (arg <- args) getParts(arg, s)
-            case ThisType(_) =>
-              getParts(tp.widen, s)
-            case _: SingletonType =>
-              getParts(tp.widen, s)
-            case RefinedType(ps, _) =>
-              for (p <- ps) getParts(p, s)
-            case AnnotatedType(_, t, _) =>
-	      getParts(t, s)
-            case _ =>
-          }
-        }
-        val tps = new collection.jcl.LinkedHashSet[Type]
-        getParts(tp, tps)
-        tps.elements.map(implicitsOfClass).toList
-      }
-
-      def implicitsOfClass(tp: Type): List[ImplicitInfo] = tp match {
-        case TypeRef(pre, clazz, _) =>
-          clazz.initialize.linkedClassOfClass.info.members.toList.filter(_.hasFlag(IMPLICIT)) map
-            (sym => new ImplicitInfo(sym.name, pre.memberType(clazz.linkedModuleOfClass), sym))
-        case _ =>
-          List()
-      }
-
-      def implicitManifest(pt: Type): Tree = {
-        // test below is designed so that ManifestClass need not be loaded
-        // (because it's not available everywhere)
-        if (pt.typeSymbol.fullNameString == "scala.reflect.Manifest")
-          pt match {
-            case TypeRef(_, ManifestClass, List(arg)) => manifestOfType(pos, arg)
-          }
-        else EmptyTree
-      }
-            
-      var tree = searchImplicit(context.implicitss, true)
-      if (tree == EmptyTree) tree = searchImplicit(implicitsOfType(pt), false)
-      if (tree == EmptyTree) tree = implicitManifest(pt)
-      if (util.Statistics.enabled)
-        impltime = impltime + currentTime - startTime
-      tree
-    }
-    
-    /** Creates a tree that calls the relevant factory method in object
-      * reflect.Manifest for type 'tp'. An EmptyTree is returned if  */
-    def manifestOfType(pos: Position, tp: Type): Tree = {
-      
-      /** Creates a tree that calls the factory method called constructor in object reflect.Manifest */
-      def manifestFactoryCall(constructor: String, args: Tree*): Tree =
-        if (args contains EmptyTree) EmptyTree
-        else 
-          typed(atPos(pos) {
-            Apply(
-              TypeApply(
-                Select(gen.mkAttributedRef(ManifestModule), constructor),
-                List(TypeTree(tp))
-              ),
-              args.toList
-            )
-          })
-      
-      /** Re-wraps a type in a manifest before calling inferImplicit on the result */
-      def findManifest(tp: Type): Tree = 
-        inferImplicit(pos, appliedType(ManifestClass.typeConstructor, List(tp)), true)
-        
-      tp.normalize match {
-        case ThisType(_) | SingleType(_, _) =>
-          manifestFactoryCall("singleType", gen.mkAttributedQualifier(tp)) 
-        case ConstantType(value) =>
-          findManifest(tp.deconst)
-        case TypeRef(pre, sym, args) =>
-          if (sym.isClass) {
-            val suffix = gen.mkClassOf(tp) :: (args map findManifest)
-            manifestFactoryCall(
-              "classType", 
-              (if ((pre eq NoPrefix) || pre.typeSymbol.isStaticOwner) suffix
-               else findManifest(pre) :: suffix): _*)
-          }
-          else if (sym.isTypeParameterOrSkolem) {
-            EmptyTree  // a manifest should have been found by normal searchImplicit
-          }
-          else {
-            manifestFactoryCall(
-              "abstractType", 
-              findManifest(pre) :: Literal(sym.name.toString) :: findManifest(tp.bounds.hi) :: (args map findManifest): _*)
-          }
-        case RefinedType(parents, decls) =>
-          // refinement is not generated yet
-          if (parents.length == 1) findManifest(parents.head)
-          else manifestFactoryCall("intersectionType", parents map findManifest: _*)
-        case _ =>
-          EmptyTree
-      }
-      
-    }
-
-    def applyImplicitArgs(tree: Tree): Tree = tree.tpe match {
-      case MethodType(formals, _) =>
-        def implicitArg(pt: Type) = {
-          val arg = inferImplicit(tree.pos, pt, true)
-          if (arg != EmptyTree) arg
-          else errorTree(tree, "no implicit argument matching parameter type "+pt+" was found.")
-        }
-        Apply(tree, formals map implicitArg) setPos tree.pos
-      case ErrorType =>
-        tree
-    }
   }
 }
diff --git a/src/compiler/scala/tools/nsc/typechecker/Unapplies.scala b/src/compiler/scala/tools/nsc/typechecker/Unapplies.scala
index 0ef0780..ef9a72d 100644
--- a/src/compiler/scala/tools/nsc/typechecker/Unapplies.scala
+++ b/src/compiler/scala/tools/nsc/typechecker/Unapplies.scala
@@ -1,10 +1,10 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: Unapplies.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.tools.nsc.typechecker
+package scala.tools.nsc
+package typechecker
 
 import symtab.Flags._
 
@@ -12,11 +12,17 @@ import symtab.Flags._
  *  @author  Martin Odersky
  *  @version 1.0
  */
-trait Unapplies { self: Analyzer =>
+trait Unapplies extends ast.TreeDSL
+{
+  self: Analyzer =>
 
   import global._
   import definitions._
-  import posAssigner.atPos
+  import CODE.{ CASE => _, _ }
+  
+  private def isVarargs(vd: ValDef) = treeInfo isRepeatedParamType vd.tpt
+  private def isByName(vd: ValDef)  = treeInfo isByNameParamType vd.tpt
+  private def toIdent(x: DefTree)   = Ident(x.name) setPos x.pos.focus
 
   /** returns type list for return type of the extraction */
   def unapplyTypeList(ufn: Symbol, ufntpe: Type) = {
@@ -25,7 +31,7 @@ trait Unapplies { self: Analyzer =>
     ufn.name match {
       case nme.unapply    => unapplyTypeListFromReturnType(ufntpe)
       case nme.unapplySeq => unapplyTypeListFromReturnTypeSeq(ufntpe)
-      case _ => throw new TypeError(ufn+" is not an unapply or unapplySeq")
+      case _              => throw new TypeError(ufn+" is not an unapply or unapplySeq")
     }
   }
   /** (the inverse of unapplyReturnTypeSeq)
@@ -34,20 +40,18 @@ trait Unapplies { self: Analyzer =>
    *   - returns T0...Tn if n>0 and T <: Product[T0...Tn]]
    *   - returns T otherwise
    */
-  def unapplyTypeListFromReturnType(tp1: Type): List[Type] =  { // rename: unapplyTypeListFromReturnType
-    val tp = unapplyUnwrap(tp1)
-    val B = BooleanClass
-    val O = OptionClass 
-    val S = SomeClass 
-    tp.typeSymbol match { // unapplySeqResultToMethodSig
-      case  B => Nil
-      case  O | S =>
+  def unapplyTypeListFromReturnType(tp1: Type): List[Type] = {
+    val tp = unapplyUnwrap(tp1)    
+    tp.typeSymbol match {                             // unapplySeqResultToMethodSig
+      case BooleanClass             => Nil
+      case OptionClass | SomeClass  =>
         val prod = tp.typeArgs.head
-        getProductArgs(prod)  match {
-          case Some(all @ (x1::x2::xs)) => all       // n >= 2
-          case _                        => prod::Nil // special n == 0 ||  n == 1 
+        getProductArgs(prod) match {
+          case Some(xs) if xs.size > 1  => xs         // n > 1
+          case _                        => List(prod) // special n == 0 ||  n == 1
         }
-      case _ => throw new TypeError("result type "+tp+" of unapply not in {boolean, Option[_], Some[_]}")
+      case _                        =>
+        throw new TypeError("result type "+tp+" of unapply not in {Boolean, Option[_], Some[_]}")
     }
   }
 
@@ -58,15 +62,16 @@ trait Unapplies { self: Analyzer =>
    */
   def unapplyTypeListFromReturnTypeSeq(tp1: Type): List[Type] = {
     val tp = unapplyUnwrap(tp1)
-    val   O = OptionClass; val S = SomeClass; tp.typeSymbol match { 
-    case  O                  | S =>
-      val ts = unapplyTypeListFromReturnType(tp1)
-      val last1 = ts.last.baseType(SeqClass) match {
-        case TypeRef(pre, seqClass, args) => typeRef(pre, RepeatedParamClass, args)
-        case _ => throw new TypeError("last not seq")
-      }
-      ts.init ::: List(last1)
-      case _ => throw new TypeError("result type "+tp+" of unapply not in {Option[_], Some[_]}")
+    tp.typeSymbol match {
+      case OptionClass | SomeClass  =>
+        val ts = unapplyTypeListFromReturnType(tp1)
+        val last1 = (ts.last baseType SeqClass) match {
+          case TypeRef(pre, seqClass, args) => typeRef(pre, RepeatedParamClass, args) // XXX seqClass or SeqClass?
+          case _                            => throw new TypeError("last not seq")
+        }
+        ts.init ::: List(last1)
+      case _                        =>
+        throw new TypeError("result type "+tp+" of unapply not in {Option[_], Some[_]}")
     }
   }
 
@@ -74,43 +79,42 @@ trait Unapplies { self: Analyzer =>
    *  for n == 0, boolean
    *  for n == 1, Some[T0]
    *  else Some[Product[Ti]]
-  def unapplyReturnType(elems: List[Type], useWildCards: Boolean) = 
-    if (elems.isEmpty)
-      BooleanClass.tpe
-    else if (elems.length == 1)
-      optionType(if(useWildCards) WildcardType else elems(0))
-    else 
-      productType({val es = elems; if(useWildCards) elems map { x => WildcardType} else elems})
    */
   def unapplyReturnTypeExpected(argsLength: Int) = argsLength match {
     case 0 => BooleanClass.tpe
     case 1 => optionType(WildcardType)
-    case n => optionType(productType(List.range(0,n).map (arg => WildcardType)))
+    case n => optionType(productType((List fill n)(WildcardType)))
   }
 
   /** returns unapply or unapplySeq if available */
-  def unapplyMember(tp: Type): Symbol = {
-    var unapp = tp.member(nme.unapply)
-    if (unapp == NoSymbol) unapp = tp.member(nme.unapplySeq)
-    unapp
+  def unapplyMember(tp: Type): Symbol = (tp member nme.unapply) match {
+    case NoSymbol => tp member nme.unapplySeq
+    case unapp    => unapp
+  }
+  /** returns unapply member's parameter type. */
+  def unapplyParameterType(extractor: Symbol) = {
+    val ps = extractor.tpe.params
+    if (ps.length == 1) ps.head.tpe.typeSymbol
+    else NoSymbol
   }
 
-  private def copyUntyped[T <: Tree](tree: T): T = {
-    val tree1 = tree.duplicate
-    UnTyper.traverse(tree1)
-    tree1
+  def copyUntyped[T <: Tree](tree: T): T =
+    returning[T](tree.duplicate)(UnTyper traverse _)
+
+  def copyUntypedInvariant(td: TypeDef): TypeDef = {
+    val copy = treeCopy.TypeDef(td, td.mods &~ (COVARIANT | CONTRAVARIANT), td.name, td.tparams, td.rhs)
+    
+    returning[TypeDef](copy.duplicate)(UnTyper traverse _)
   }
 
   private def classType(cdef: ClassDef, tparams: List[TypeDef]): Tree = {
-    val tycon = gen.mkAttributedRef(cdef.symbol)
-    if (tparams.isEmpty) tycon else AppliedTypeTree(tycon, tparams map (x => Ident(x.name)))
+    val tycon = REF(cdef.symbol)
+    if (tparams.isEmpty) tycon else AppliedTypeTree(tycon, tparams map toIdent)
   }
 
   private def constrParamss(cdef: ClassDef): List[List[ValDef]] = {
-    val constr = treeInfo.firstConstructor(cdef.impl.body)
-    (constr: @unchecked) match {
-      case DefDef(_, _, _, vparamss, _, _) => vparamss map (_ map copyUntyped[ValDef])
-    }
+    val DefDef(_, _, _, vparamss, _, _) = treeInfo firstConstructor cdef.impl.body
+    vparamss map (_ map copyUntyped[ValDef])
   }
 
   /** The return value of an unapply method of a case class C[Ts]
@@ -118,66 +122,87 @@ trait Unapplies { self: Analyzer =>
    *  @param caseclazz  The case class C[Ts]
    */
   private def caseClassUnapplyReturnValue(param: Name, caseclazz: Symbol) = {
-    def caseFieldAccessorValue(selector: Symbol) = Select(Ident(param), selector)
-    val accessors = caseclazz.caseFieldAccessors
-    if (accessors.isEmpty) Literal(true)
-    else 
-      Apply(
-        gen.scalaDot(nme.Some), 
-        List(
-          if (accessors.tail.isEmpty) caseFieldAccessorValue(accessors.head)
-          else Apply(
-            gen.scalaDot(newTermName("Tuple" + accessors.length)), 
-            accessors map caseFieldAccessorValue)))
+    def caseFieldAccessorValue(selector: Symbol): Tree = Ident(param) DOT selector
+    
+    caseclazz.caseFieldAccessors match {
+      case Nil      => TRUE
+      case xs       => SOME(xs map caseFieldAccessorValue: _*)
+    }
   }
 
   /** The module corresponding to a case class; without any member definitions
    */
-  def caseModuleDef(cdef: ClassDef): ModuleDef = atPos(cdef.pos) {
-    var parents = List(gen.scalaScalaObjectConstr)
-    if (!(cdef.mods hasFlag ABSTRACT) && cdef.tparams.isEmpty && constrParamss(cdef).length == 1)
-      parents = gen.scalaFunctionConstr(constrParamss(cdef).head map (_.tpt), 
-                                        Ident(cdef.name)) :: parents
+  def caseModuleDef(cdef: ClassDef): ModuleDef = {
+    // > MaxFunctionArity is caught in Namers, but for nice error reporting instead of
+    // an abrupt crash we trim the list here.
+    def primaries      = constrParamss(cdef).head take MaxFunctionArity map (_.tpt)
+    def inheritFromFun = !cdef.mods.isAbstract && cdef.tparams.isEmpty && constrParamss(cdef).length == 1
+    def createFun      = gen.scalaFunctionConstr(primaries, toIdent(cdef), abstractFun = true)
+    def parents        = if (inheritFromFun) List(createFun) else Nil
+        
+    companionModuleDef(cdef, parents)
+  }
+
+  def companionModuleDef(cdef: ClassDef, parents: List[Tree] = Nil): ModuleDef = atPos(cdef.pos.focus) {
+    val allParents = parents ::: List( gen.scalaScalaObjectConstr)
     ModuleDef(
       Modifiers(cdef.mods.flags & AccessFlags | SYNTHETIC, cdef.mods.privateWithin),
       cdef.name.toTermName,
-      Template(parents, emptyValDef, Modifiers(0), List(), List(List()), List()))
+      Template(allParents, emptyValDef, NoMods, Nil, List(Nil), Nil, cdef.impl.pos.focus))
   }
 
+  private val caseMods = Modifiers(SYNTHETIC | CASE)
+  
   /** The apply method corresponding to a case class
    */
   def caseModuleApplyMeth(cdef: ClassDef): DefDef = {
-    val tparams = cdef.tparams map copyUntyped[TypeDef]
-    val cparamss = constrParamss(cdef)
-    atPos(cdef.pos) {
-      DefDef(
-        Modifiers(SYNTHETIC | CASE), 
-        nme.apply, 
-        tparams, 
-        cparamss,
-        classType(cdef, tparams),
+    val tparams   = cdef.tparams map copyUntypedInvariant
+    val cparamss  = constrParamss(cdef)
+    atPos(cdef.pos.focus)(
+      DefDef(caseMods, nme.apply, tparams, cparamss, classType(cdef, tparams),
         New(classType(cdef, tparams), cparamss map (_ map gen.paramToArg)))
-    }
+    )
   }
 
   /** The unapply method corresponding to a case class
    */
   def caseModuleUnapplyMeth(cdef: ClassDef): DefDef = {
-    val tparams = cdef.tparams map copyUntyped[TypeDef]
-    val unapplyParamName = newTermName("x$0")
-    val hasVarArg = constrParamss(cdef) match {
-      case (cps @ (_ :: _)) :: _ => treeInfo.isRepeatedParamType(cps.last.tpt)
-      case _ => false
+    val tparams   = cdef.tparams map copyUntypedInvariant
+    val paramName = newTermName("x$0")
+    val method    = constrParamss(cdef) match {
+      case xs :: _ if !xs.isEmpty && isVarargs(xs.last) => nme.unapplySeq
+      case _                                            => nme.unapply
     }
-    atPos(cdef.pos) {
-      DefDef(
-        Modifiers(SYNTHETIC | CASE),
-        if (hasVarArg) nme.unapplySeq else nme.unapply,
-        tparams,
-        List(List(ValDef(Modifiers(PARAM | SYNTHETIC), unapplyParamName, 
-                         classType(cdef, tparams), EmptyTree))),
-        TypeTree(),
-        caseClassUnapplyReturnValue(unapplyParamName, cdef.symbol))
+    val cparams   = List(ValDef(Modifiers(PARAM | SYNTHETIC), paramName, classType(cdef, tparams), EmptyTree))
+    val ifNull    = if (constrParamss(cdef).head.size == 0) FALSE else REF(NoneModule)
+    val body      = nullSafe({ case Ident(x) => caseClassUnapplyReturnValue(x, cdef.symbol) }, ifNull)(Ident(paramName))
+
+    atPos(cdef.pos.focus)(
+      DefDef(caseMods, method, tparams, List(cparams), TypeTree(), body)
+    )
+  }
+
+  def caseClassCopyMeth(cdef: ClassDef): Option[DefDef] = {    
+    def isDisallowed(vd: ValDef) = isVarargs(vd) || isByName(vd)
+    val cparamss  = constrParamss(cdef)
+    val flat      = cparamss flatten
+    
+    if (flat.isEmpty || (cdef.symbol hasFlag ABSTRACT) || (flat exists isDisallowed)) None
+    else {
+      val tparams = cdef.tparams map copyUntypedInvariant
+      // the parameter types have to be exactly the same as the constructor's parameter types; so it's
+      // not good enough to just duplicated the (untyped) tpt tree; the parameter types are removed here
+      // and re-added in ``finishWith'' in the namer.
+      def paramWithDefault(vd: ValDef) =
+        treeCopy.ValDef(vd, vd.mods | DEFAULTPARAM, vd.name, atPos(vd.pos.focus)(TypeTree() setOriginal vd.tpt), toIdent(vd))
+      
+      val paramss   = cparamss map (_ map paramWithDefault)
+      val classTpe  = classType(cdef, tparams)
+      
+      Some(atPos(cdef.pos.focus)(
+        DefDef(Modifiers(SYNTHETIC), nme.copy, tparams, paramss, classTpe,
+          New(classTpe, paramss map (_ map toIdent)))
+      ))
     }
   }
 }
diff --git a/src/compiler/scala/tools/nsc/typechecker/Variances.scala b/src/compiler/scala/tools/nsc/typechecker/Variances.scala
index ff18f16..83b35cf 100644
--- a/src/compiler/scala/tools/nsc/typechecker/Variances.scala
+++ b/src/compiler/scala/tools/nsc/typechecker/Variances.scala
@@ -1,10 +1,10 @@
 /* NSC -- new scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: Variances.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.tools.nsc.typechecker
+package scala.tools.nsc
+package typechecker
 
 import symtab.Flags._
 
@@ -64,18 +64,16 @@ trait Variances {
     v
   }
 
-  /** Compute variance of type parameter `tparam' in all type annotations `attribs'. */
-  def varianceInAttribs(attribs: List[AnnotationInfo])(tparam: Symbol): Int = {
-    (VARIANCES /: attribs) ((v, attrib) => v & varianceInAttrib(attrib)(tparam))
+  /** Compute variance of type parameter `tparam' in all type annotations `annots'. */
+  def varianceInAttribs(annots: List[AnnotationInfo])(tparam: Symbol): Int = {
+    (VARIANCES /: annots) ((v, annot) => v & varianceInAttrib(annot)(tparam))
   }
 
-  /** Compute variance of type parameter `tparam' in type annotation `attrib'. */
-  def varianceInAttrib(attrib: AnnotationInfo)(tparam: Symbol): Int = {
-    varianceInType(attrib.atp)(tparam)
+  /** Compute variance of type parameter `tparam' in type annotation `annot'. */
+  def varianceInAttrib(annot: AnnotationInfo)(tparam: Symbol): Int = {
+    varianceInType(annot.atp)(tparam)
   }
 
-
-
   /** Compute variance of type parameter <code>tparam</code> in type <code>tp</code>. */
   def varianceInType(tp: Type)(tparam: Symbol): Int = tp match {
     case ErrorType | WildcardType | NoType | NoPrefix | ThisType(_) | ConstantType(_) =>
@@ -89,13 +87,13 @@ trait Variances {
       flip(varianceInType(lo)(tparam)) & varianceInType(hi)(tparam)
     case RefinedType(parents, defs) =>
       varianceInTypes(parents)(tparam) & varianceInSyms(defs.toList)(tparam)
-    case MethodType(formals, restpe) =>
-      flip(varianceInTypes(formals)(tparam)) & varianceInType(restpe)(tparam)
+    case MethodType(params, restpe) =>
+      flip(varianceInSyms(params)(tparam)) & varianceInType(restpe)(tparam)
     case PolyType(tparams, restpe) =>
       flip(varianceInSyms(tparams)(tparam)) & varianceInType(restpe)(tparam)
     case ExistentialType(tparams, restpe) =>
       varianceInSyms(tparams)(tparam) & varianceInType(restpe)(tparam)
-    case AnnotatedType(attribs, tp, _) =>
-      varianceInAttribs(attribs)(tparam) & varianceInType(tp)(tparam)
+    case AnnotatedType(annots, tp, _) =>
+      varianceInAttribs(annots)(tparam) & varianceInType(tp)(tparam)
   }
 }
diff --git a/src/compiler/scala/tools/nsc/util/ArgumentsExpander.scala b/src/compiler/scala/tools/nsc/util/ArgumentsExpander.scala
deleted file mode 100644
index 68aa347..0000000
--- a/src/compiler/scala/tools/nsc/util/ArgumentsExpander.scala
+++ /dev/null
@@ -1,42 +0,0 @@
-package scala.tools.nsc.util
-
-import java.io.{FileReader, BufferedReader, StreamTokenizer, FileNotFoundException}
-import scala.tools.nsc.io.AbstractFile
-import scala.collection.mutable.ListBuffer
-
-/**
- * Expands all arguments starting with @ to the contents of the
- * file named like each argument.
- */
-object ArgumentsExpander {
-
-  def expandArg(arg: String): List[String] =
-    expandFromFile(arg.substring(1))
-
-  /*
-   * Extracts all the arguments in a specified file.
-   * Throws FileNotFoundException if the file does not exist.
-   */
-  private def expandFromFile(fileName: String): List[String]  = {
-    val f = AbstractFile.getFile(fileName)
-    if (f eq null) throw new FileNotFoundException(
-      "argument file "+ fileName +" could not be found")
-
-    val in = new BufferedReader(new FileReader(f.file))
-
-    val tokenizer = new StreamTokenizer( in )
-    tokenizer.resetSyntax
-    tokenizer.wordChars(' ', 255)
-    tokenizer.whitespaceChars(0, ' ')
-    tokenizer.commentChar('#')
-    tokenizer.quoteChar('"')
-    tokenizer.quoteChar('\'')
-
-    val ts = new ListBuffer[String]
-    while (tokenizer.nextToken() != StreamTokenizer.TT_EOF) {
-      ts += tokenizer.sval
-    }
-    in.close()
-    ts.toList
-  }
-}
diff --git a/src/compiler/scala/tools/nsc/util/BitSet.scala b/src/compiler/scala/tools/nsc/util/BitSet.scala
new file mode 100644
index 0000000..09b32de
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/util/BitSet.scala
@@ -0,0 +1,156 @@
+package scala.tools.nsc
+package util
+
+import BitSet._
+
+abstract class BitSet {
+
+  protected def nwords: Int
+  protected def word(idx: Int): Long
+  protected def updateWord(idx: Int, w: Long): BitSet
+                         
+  def + (elem: Int): BitSet = {
+    require(elem >= 0)
+    if (contains(elem)) this 
+    else {
+      val idx = elem >> LogWL
+      updateWord(idx, word(idx) | (1L << elem))
+    }
+  }
+
+  def - (elem: Int): BitSet = {
+    require(elem >= 0)
+    if (contains(elem)) {
+      val idx = elem >> LogWL
+      updateWord(idx, word(idx) & ~(1L << elem))
+    } else this
+  }
+
+  def | (other: BitSet): BitSet = {
+    val len = this.nwords max other.nwords
+    val words = new Array[Long](len)
+    for (idx <- 0 until len)
+      words(idx) = this.word(idx) | other.word(idx)
+    fromArray(words)
+  }
+
+  def & (other: BitSet): BitSet = {
+    val len = this.nwords min other.nwords
+    val words = new Array[Long](len)
+    for (idx <- 0 until len)
+      words(idx) = this.word(idx) & other.word(idx)
+    fromArray(words)
+  }
+
+  def &~ (other: BitSet): BitSet = {
+    val len = this.nwords
+    val words = new Array[Long](len)
+    for (idx <- 0 until len)
+      words(idx) = this.word(idx) & ~other.word(idx)
+    fromArray(words)
+  }
+
+  def ^ (other: BitSet): BitSet = {
+    val len = this.nwords max other.nwords
+    val words = new Array[Long](len)
+    for (idx <- 0 until len)
+      words(idx) = this.word(idx) ^ other.word(idx)
+    fromArray(words)
+  }
+
+  def contains(elem: Int): Boolean =
+    0 <= elem && (word(elem >> LogWL) & (1L << elem)) != 0L
+
+  def subSet(other: BitSet): Boolean =
+    (0 until nwords) forall (idx => (this.word(idx) & ~ other.word(idx)) == 0L)
+
+  override def equals(other: Any) = other match {
+    case that: BitSet =>
+      (0 until (this.nwords max that.nwords)) forall (idx => this.word(idx) == that.word(idx))
+    case _ =>
+      false
+  }
+
+  override def hashCode: Int = {
+    var h = hashSeed
+    for (idx <- 0 until nwords) {
+      val w = word(idx)
+      h = (h * 41 + (w >>> 32).toInt) * 41 + w.toInt
+    }
+    h
+  }
+
+  def addString(sb: StringBuilder, start: String, sep: String, end: String) {
+    sb append start
+    var pre = ""
+    for (i <- 0 until nwords * WordLength)
+      if (contains(i)) {
+        sb append pre append i
+        pre = sep
+      }
+    sb append end
+  }
+
+  def mkString(start: String, sep: String, end: String) = {
+    val sb = new StringBuilder
+    addString(sb, start, sep, end)
+    sb.toString
+  }
+
+  override def toString = mkString("BitSet(", ", ", ")")
+}
+
+object BitSet {
+
+  private final val WordLength = 64
+  private final val LogWL = 6
+  private val hashSeed = "BitSet".hashCode
+
+  val empty: BitSet = new BitSet1(0L)
+
+  def apply(elems: Int*) = (empty /: elems) (_ + _)
+
+  def fromArray(elems: Array[Long]) = {
+    val len = elems.length
+    if (len == 0) empty
+    else if (len == 1) new BitSet1(elems(0))
+    else if (len == 2) new BitSet2(elems(0), elems(1))
+    else new BitSetN(elems)
+  }
+
+  private def updateArray(elems: Array[Long], idx: Int, w: Long): BitSet = {
+    var len = elems.length
+    while (len > 0 && (elems(len - 1) == 0L || w == 0L && idx == len - 1)) len -= 1
+    var newlen = len
+    if (idx >= newlen && w != 0L) newlen = idx + 1
+    val newelems = new Array[Long](newlen)
+    Array.copy(elems, 0, newelems, 0, len)
+    if (idx < newlen) newelems(idx) = w
+    else assert(w == 0L)
+    fromArray(newelems)
+  }
+
+  class BitSet1(val elems: Long) extends BitSet {
+    protected def nwords = 1
+    protected def word(idx: Int) = if (idx == 0) elems else 0L
+    protected def updateWord(idx: Int, w: Long): BitSet = 
+      if (idx == 0) new BitSet1(w)
+      else if (idx == 1) new BitSet2(elems, w)
+      else updateArray(Array(elems), idx, w)
+  }
+
+  class BitSet2(val elems0: Long, elems1: Long) extends BitSet {
+    protected def nwords = 2
+    protected def word(idx: Int) = if (idx == 0) elems0 else if (idx == 1) elems1 else 0L
+    protected def updateWord(idx: Int, w: Long): BitSet = 
+      if (idx == 0) new BitSet2(w, elems1)
+      else if (idx == 1) new BitSet2(elems0, w)
+      else updateArray(Array(elems0, elems1), idx, w)
+  }
+
+  class BitSetN(val elems: Array[Long]) extends BitSet {
+    protected def nwords = elems.length
+    protected def word(idx: Int) = if (idx < nwords) elems(idx) else 0L
+    protected def updateWord(idx: Int, w: Long): BitSet = updateArray(elems, idx, w)
+  }
+}
diff --git a/src/compiler/scala/tools/nsc/util/CharArrayReader.scala b/src/compiler/scala/tools/nsc/util/CharArrayReader.scala
index a6db570..3bbe6f8 100644
--- a/src/compiler/scala/tools/nsc/util/CharArrayReader.scala
+++ b/src/compiler/scala/tools/nsc/util/CharArrayReader.scala
@@ -1,134 +1,112 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: CharArrayReader.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.tools.nsc.util
+package scala.tools.nsc
+package util
 
-import scala.tools.nsc.util.SourceFile.{LF, FF, CR, SU}
+import Chars._
 
-class CharArrayReader(buf: RandomAccessSeq[Char], start: Int, /* startline: int, startcol: int, */
-                      decodeUni: Boolean, error: String => Unit) extends Iterator[Char] with Cloneable {
+abstract class CharArrayReader { self =>
 
-  def this(buf: RandomAccessSeq[Char], decodeUni: Boolean, error: String => Unit) =
-    this(buf, 0, /* 1, 1, */ decodeUni, error)
+  val buf: Array[Char]
 
-  /** produce a duplicate of this char array reader which starts reading
-    *  at current position, independent of what happens to original reader
-	*/
-  def dup: CharArrayReader = clone().asInstanceOf[CharArrayReader]
+  def decodeUni: Boolean = true
 
-  /** layout constant
-   */
-  val tabinc = 8
+  /** An error routine to call on bad unicode escapes \\uxxxx. */
+  protected def error(offset: Int, msg: String)
 
-  /** the line and column position of the current character
-  */
+  /** the last read character */
   var ch: Char = _
-  var bp = start
-  var oldBp = -1
-  var oldCh: Char = _
+
+  /** The offset one past the last read character */
+  var charOffset: Int = 0
+
+  /** The start offset of the current line */
+  var lineStartOffset: Int = 0
+
+  /** The start offset of the line before the current one */
+  var lastLineStartOffset: Int = 0
+
+  private var lastUnicodeOffset = -1
+
+  /** Is last character a unicode escape \\uxxxx? */
+  def isUnicodeEscape = charOffset == lastUnicodeOffset
   
-  //private var cline: Int = _
-  //private var ccol: Int = _
-  def cpos = bp
-  var isUnicode: Boolean = _
-  var lastLineStartPos: Int = 0
-  var lineStartPos: Int = 0
-  var lastBlankLinePos: Int = 0
-
-  private var onlyBlankChars = false
-  //private var nextline = startline
-  //private var nextcol = startcol
-
-  private def markNewLine() {
-    lastLineStartPos = lineStartPos
-    if (onlyBlankChars) lastBlankLinePos = lineStartPos
-    lineStartPos = bp
-    onlyBlankChars = true
-    //nextline += 1
-    //nextcol = 1
+  /** Advance one character; reducing CR;LF pairs to just LF */
+  final def nextChar() {
+    if (charOffset >= buf.length) {
+      ch = SU
+    } else {
+      val c = buf(charOffset)
+      ch = c
+      charOffset += 1
+      if (c == '\\') potentialUnicode()
+      else if (c < ' ') { skipCR(); potentialLineEnd() }
+    }
   }
 
-  def hasNext: Boolean = if (bp < buf.length) true 
-  else {
-    false
+  /** Advance one character, leaving CR;LF pairs intact */
+  final def nextRawChar() {
+    if (charOffset >= buf.length) {
+      ch = SU
+    } else {
+      val c = buf(charOffset)
+      ch = c
+      charOffset += 1
+      if (c == '\\') potentialUnicode()
+      else if (c < ' ') potentialLineEnd()
+    }
   }
 
-  def last: Char = if (bp > start + 2) buf(bp - 2) else ' ' // XML literals
-
-  def next: Char = {
-    //cline = nextline
-    //ccol = nextcol
-    val buf = this.buf.asInstanceOf[runtime.BoxedCharArray].value
-    if(!hasNext) {
-      ch = SU
-      return SU  // there is an endless stream of SU's at the end 
+  /** Interpret \\uxxxx escapes */
+  private def potentialUnicode() {
+    def evenSlashPrefix: Boolean = {
+      var p = charOffset - 2
+      while (p >= 0 && buf(p) == '\\') p -= 1
+      (charOffset - p) % 2 == 0
     }
-    oldBp = bp
-    oldCh = ch
-    ch = buf(bp)
-    isUnicode = false
-    bp = bp + 1
-    ch match {
-      case '\t' =>
-        // nextcol = ((nextcol - 1) / tabinc * tabinc) + tabinc + 1;
-      case CR =>
-        if (buf(bp) == LF) {
-          ch = LF
-          bp += 1
-        }
-        markNewLine()
-      case LF | FF =>
-        markNewLine()
-      case '\\' =>
-        def evenSlashPrefix: Boolean = {
-          var p = bp - 2
-          while (p >= 0 && buf(p) == '\\') p -= 1
-          (bp - p) % 2 == 0
-        }
-        def udigit: Int = {
-          val d = digit2int(buf(bp), 16)
-          if (d >= 0) { bp += 1; /* nextcol = nextcol + 1 */ }
-          else error("error in unicode escape");
-          d
-        }
-        // nextcol += 1
-        if (buf(bp) == 'u' && decodeUni && evenSlashPrefix) {
-          do {
-            bp += 1 //; nextcol += 1
-          } while (buf(bp) == 'u');
-          val code = udigit << 12 | udigit << 8 | udigit << 4 | udigit
-          ch = code.asInstanceOf[Char]
-          isUnicode = true
-        }
-      case _ =>
-        if (ch > ' ') onlyBlankChars = false
-        // nextcol += 1
+    def udigit: Int = {
+      val d = digit2int(buf(charOffset), 16)
+      if (d >= 0) charOffset += 1
+      else error(charOffset, "error in unicode escape")
+      d
+    }
+    if (charOffset < buf.length && buf(charOffset) == 'u' && decodeUni && evenSlashPrefix) {
+      do charOffset += 1
+      while (charOffset < buf.length && buf(charOffset) == 'u')
+      val code = udigit << 12 | udigit << 8 | udigit << 4 | udigit
+      lastUnicodeOffset = charOffset
+      ch = code.toChar
     }
-    ch
   }
 
-  def rewind {
-    if (oldBp == -1) throw new IllegalArgumentException
-    bp = oldBp
-    ch = oldCh
-    oldBp = -1
-    oldCh = 'x'
+  /** replace CR;LF by LF */
+  private def skipCR() {
+    if (ch == CR)
+      if (charOffset < buf.length && buf(charOffset) == LF) {
+        charOffset += 1
+        ch = LF
+      }
+  }    
+
+  /** Handle line ends */
+  private def potentialLineEnd() {
+    if (ch == LF || ch == FF) {
+      lastLineStartOffset = lineStartOffset
+      lineStartOffset = charOffset
+    }
   }
 
-  def copy: CharArrayReader =
-    new CharArrayReader(buf, bp, /* nextcol, nextline, */ decodeUni, error)
-
-  def digit2int(ch: Char, base: Int): Int = {
-    if ('0' <= ch && ch <= '9' && ch < '0' + base)
-      ch - '0'
-    else if ('A' <= ch && ch < 'A' + base - 10)
-      ch - 'A' + 10
-    else if ('a' <= ch && ch < 'a' + base - 10)
-      ch - 'a' + 10
-    else
-      -1
+  /** A new reader that takes off at the current character position */
+  def lookaheadReader = new CharArrayReader {
+    val buf = self.buf
+    charOffset = self.charOffset
+    ch = self.ch
+    override def decodeUni = self.decodeUni
+    def error(offset: Int, msg: String) = self.error(offset, msg)
+    /** A mystery why CharArrayReader.nextChar() returns Unit */
+    def getc() = { nextChar() ; ch }
   }
 }
diff --git a/src/compiler/scala/tools/nsc/util/Chars.scala b/src/compiler/scala/tools/nsc/util/Chars.scala
new file mode 100644
index 0000000..37d1d0d
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/util/Chars.scala
@@ -0,0 +1,85 @@
+/* NSC -- new Scala compiler
+ * Copyright 2006-2010 LAMP/EPFL
+ * @author  Martin Odersky
+ */
+
+package scala.tools.nsc
+package util
+
+import annotation.{ tailrec, switch }
+
+/** Contains constants and classifier methods for characters */
+object Chars {
+  // Be very careful touching these.
+  // Apparently trivial changes to the way you write these constants 
+  // will cause Scanners.scala to go from a nice efficient switch to 
+  // a ghastly nested if statement which will bring the type checker
+  // to its knees. See ticket #1456
+  // Martin: (this should be verified now that the pattern rules have been redesigned). 
+  final val LF = '\u000A'
+  final val FF = '\u000C'
+  final val CR = '\u000D'
+  final val SU = '\u001A'
+
+  /** Convert a character digit to an Int according to given base,
+   *  -1 if no success */
+  def digit2int(ch: Char, base: Int): Int = {
+    if ('0' <= ch && ch <= '9' && ch < '0' + base)
+      ch - '0'
+    else if ('A' <= ch && ch < 'A' + base - 10)
+      ch - 'A' + 10
+    else if ('a' <= ch && ch < 'a' + base - 10)
+      ch - 'a' + 10
+    else
+      -1
+  }
+  
+  /** Convert a character to a backslash-u escape */
+  def char2uescape(c: Char): String = {
+    var rest = c.toInt
+    val buf = new StringBuilder
+    for (i <- 1 to 4) {
+      buf ++= (rest % 16).toHexString
+      rest = rest / 16
+    }
+    "\\u" + buf.toString.reverse
+  }
+
+  /** Is character a line break? */
+  @inline def isLineBreakChar(c: Char) = (c: @switch) match {
+    case LF|FF|CR|SU  => true
+    case _            => false
+  }
+
+  /** Is character a whitespace character (but not a new line)? */
+  def isWhitespace(c: Char) = 
+    c == ' ' || c == '\t' || c == CR
+
+  /** Can character form part of a doc comment variable $xxx? */
+  def isVarPart(c: Char) = 
+    '0' <= c && c <= '9' || 'A' <= c && c <= 'Z' || 'a' <= c && c <= 'z'
+    
+  /** Can character start an alphanumeric Scala identifier? */
+  def isIdentifierStart(c: Char): Boolean =
+    (c == '_') || (c == '$') || Character.isUnicodeIdentifierStart(c)
+
+  /** Can character form part of an alphanumeric Scala identifier? */
+  def isIdentifierPart(c: Char) =
+    (c == '$') || Character.isUnicodeIdentifierPart(c)
+
+  /** Is character a math or other symbol in Unicode?  */
+  def isSpecial(c: Char) = {
+    val chtp = Character.getType(c)
+    chtp == Character.MATH_SYMBOL.toInt || chtp == Character.OTHER_SYMBOL.toInt
+  }
+
+  /** Can character form part of a Scala operator name? */
+  def isOperatorPart(c : Char) : Boolean = (c: @switch) match {
+    case '~' | '!' | '@' | '#' | '%' | 
+         '^' | '*' | '+' | '-' | '<' |
+         '>' | '?' | ':' | '=' | '&' | 
+         '|' | '/' | '\\' => true
+    case c => isSpecial(c)
+  }
+}
+
diff --git a/src/compiler/scala/tools/nsc/util/ClassPath.scala b/src/compiler/scala/tools/nsc/util/ClassPath.scala
index c43886d..7efb7c7 100644
--- a/src/compiler/scala/tools/nsc/util/ClassPath.scala
+++ b/src/compiler/scala/tools/nsc/util/ClassPath.scala
@@ -1,344 +1,425 @@
 /* NSC -- new Scala compiler
- * Copyright 2006-2009 LAMP/EPFL
+ * Copyright 2006-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
 
-// $Id: ClassPath.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.tools.nsc.util
+package scala.tools.nsc
+package util
 
-import java.io.File
+import java.io.{ File => JFile }
 import java.net.URL
-import java.util.StringTokenizer
 
-import scala.collection.mutable.ArrayBuffer
-import scala.tools.nsc.io.AbstractFile
+import scala.collection.mutable.{ListBuffer, ArrayBuffer, HashSet => MutHashSet}
+import io.{ File, Directory, Path, AbstractFile }
+import scala.tools.util.StringOps.splitWhere
+import Path.isJarOrZip
+import scala.tools.util.PathResolver
+import File.pathSeparator
 
 /** <p>
- *    This module provides star expansion of '-classpath' option arguments.
+ *    This module provides star expansion of '-classpath' option arguments, behaves the same as
+ *    java, see [http://java.sun.com/javase/6/docs/technotes/tools/windows/classpath.html]
  *  </p>
  *
  *  @author Stepan Koltsov
  */
 object ClassPath {
   /** Expand single path entry */
-  private def expandStar(pattern: String): List[String] = {
-    def nameMatchesStar(name: String) = name.toLowerCase().endsWith(".jar")
+  private def expandS(pattern: String): List[String] = {
+    val wildSuffix = File.separator + "*"
     
-    /** Get all jars in directory */
-    def lsJars(f: File) = {
-      val list = f.listFiles()
-      if (list eq null) Nil
-      else list.filter(f => f.isFile() && nameMatchesStar(f.getName())).map(_.getPath()).toList
-    }
+    /** Get all subdirectories, jars, zips out of a directory. */
+    def lsDir(dir: Directory, filt: String => Boolean = _ => true) =
+      dir.list filter (x => filt(x.name) && (x.isDirectory || isJarOrZip(x))) map (_.path) toList
+
+    def basedir(s: String) = 
+      if (s contains File.separator) s.substring(0, s.lastIndexOf(File.separator))
+      else "."
     
-    val suffix = File.separator + "*"
+    if (pattern == "*") lsDir(Directory("."))
+    else if (pattern endsWith wildSuffix) lsDir(Directory(pattern dropRight 2))
+    else if (pattern contains '*') {
+      val regexp = ("^%s$" format pattern.replaceAll("""\*""", """.*""")).r
+      lsDir(Directory(pattern).parent, regexp findFirstIn _ isDefined)
+    }
+    else List(pattern)
+  }
+
+  /** Return duplicated classpath entries as
+   *    (name, list of origins)
+   *  in the order they occur on the path.
+   */
+  def findDuplicates(cp: ClassPath[_]) = {
+    def toFullName(x: (String, _, cp.AnyClassRep)) = x._1 + "." + x._3.name
+    def toOriginString(x: ClassPath[_]) = x.origin getOrElse x.name
     
-    if (pattern == "*") lsJars(new File("."))
-    else if (pattern endsWith suffix) lsJars(new File(pattern.substring(0, pattern.length - suffix.length)))
-    else pattern :: Nil
+    /** Flatten everything into tuples, recombine grouped by name, filter down to 2+ entries. */
+    val flattened = (
+      for ((pkgName, pkg) <- cp.allPackagesWithNames ; clazz <- pkg.classes) yield
+        (pkgName, pkg, clazz)
+    )
+    val multipleAppearingEntries = flattened groupBy toFullName filter (_._2.size > 1)
+
+    /** Extract results. */
+    for (name <- flattened map toFullName distinct ; dups <- multipleAppearingEntries get name) yield
+      (name, dups map { case (_, cp, _) => toOriginString(cp) })
   }
+
+  /** Split classpath using platform-dependent path separator */
+  def split(path: String): List[String] = (path split pathSeparator).toList filterNot (_ == "") distinct
   
-  /** Split path using platform-dependent path separator */
-  def splitPath(path: String): List[String] = {
-    val strtok = new StringTokenizer(path, File.pathSeparator)
-    val buf = new collection.mutable.ListBuffer[String]
-    while (strtok.hasMoreTokens()) {
-      buf + strtok.nextToken()
-    }
-    buf.toList
+  /** Join classpath using platform-dependent path separator */
+  def join(paths: String*): String  = paths filterNot (_ == "") mkString pathSeparator
+  
+  /** Split the classpath, apply a transformation function, and reassemble it. */
+  def map(cp: String, f: String => String): String = join(split(cp) map f: _*)
+  
+  /** Split the classpath, filter according to predicate, and reassemble. */
+  def filter(cp: String, p: String => Boolean): String = join(split(cp) filter p: _*)
+  
+  /** Split the classpath and map them into Paths */
+  def toPaths(cp: String): List[Path] = split(cp) map (x => Path(x).toAbsolute)
+  
+  /** Join the paths as a classpath */
+  def fromPaths(paths: Path*): String = join(paths map (_.path): _*)
+
+  /** Split the classpath and map them into URLs */
+  def toURLs(cp: String): List[URL] = toPaths(cp) map (_.toURL)
+
+  /** Expand path and possibly expanding stars */
+  def expandPath(path: String, expandStar: Boolean = true): List[String] =
+    if (expandStar) split(path) flatMap expandS
+    else split(path)
+  
+  /** Expand dir out to contents, a la extdir */
+  def expandDir(extdir: String): List[String] = {
+    val dir = Option(AbstractFile getDirectory extdir) getOrElse (return Nil)
+    dir filter (_.isClassContainer) map (dir.sfile.get / _.name path) toList
   }
   
-  /** Expand path with expanding stars */
-  def expandPath(path: String): List[String] = splitPath(path).flatMap(expandStar(_))
+  /** A useful name filter. */
+  def isTraitImplementation(name: String) = name endsWith "$class.class"
+    
+  import java.net.MalformedURLException
+  def specToURL(spec: String): Option[URL] =
+    try Some(new URL(spec))
+    catch { case _: MalformedURLException => None }
   
-  def expandPath(path: String, expandStar: Boolean): List[String] =
-    if (expandStar) expandPath(path)
-    else splitPath(path)
+  /** A class modeling aspects of a ClassPath which should be
+   *  propagated to any classpaths it creates.
+   */
+  abstract class ClassPathContext[T] {
+    /** A filter which can be used to exclude entities from the classpath
+     *  based on their name.
+     */
+    def isValidName(name: String): Boolean = true
 
-}
+    /** From the representation to its identifier.
+     */
+    def toBinaryName(rep: T): String
+    
+    /** Create a new classpath based on the abstract file.
+     */
+    def newClassPath(file: AbstractFile): ClassPath[T]
+    
+    /** Creators for sub classpaths which preserve this context.
+     */
+    def sourcesInPath(path: String): List[ClassPath[T]] =
+      for (file <- expandPath(path, false) ; dir <- Option(AbstractFile getDirectory file)) yield
+        new SourcePath[T](dir, this)
+    
+    def contentsOfDirsInPath(path: String): List[ClassPath[T]] =
+      for (dir <- expandPath(path, false) ; name <- expandDir(dir) ; entry <- Option(AbstractFile getDirectory name)) yield
+        newClassPath(entry)
 
-/** <p>
- *    Richer classpath abstraction than files.
- *  </p>
- *  <p>
- *    Roughly based on Eclipse's classpath abstractions.
- *  </p>
- *
- *  @author Sean McDirmid
- */
-class ClassPath(onlyPresentation: Boolean) {
+    def classesAtAllURLS(path: String): List[ClassPath[T]] =
+      (path split " ").toList flatMap classesAtURL
 
-  def this() = this(false)
+    def classesAtURL(spec: String) =     
+      for (url <- specToURL(spec).toList ; location <- Option(AbstractFile getURL url)) yield
+        newClassPath(location)
 
-  class Source(val location: AbstractFile, val compile: Boolean) {
-    // assert(location           != null, "cannot find source location")
-    // assert(location.getFile() != null, "cannot find source location " + " " + location + " " + location.getClass())
-    override def toString(): String = "" + location + " " + compile
-  }
+    def classesInExpandedPath(path: String) = classesInPathImpl(path, true)
+    def classesInPath(path: String) = classesInPathImpl(path, false)
 
-  abstract class Entry(val location: AbstractFile) {
-    // assert(location           != null, "cannot find classpath location")
-    // assert(location.getFile() != null, "cannot find classpath location " + " " + location + " " + location.getClass())
-    def source: Source
-    override def toString() = 
-      (if (location == null) "<none>" else location.toString) + 
-        (if (source == null) "" else " source=" + source)
+    // Internal
+    private def classesInPathImpl(path: String, expand: Boolean) =
+      for (file <- expandPath(path, expand) ; dir <- Option(AbstractFile getDirectory file)) yield
+        newClassPath(dir)
   }
-
-  class Output(location0: AbstractFile, val sourceFile: AbstractFile) extends Entry(location0) {
-    def source = if (sourceFile ne null) new Source(sourceFile, true) else null
+  
+  class JavaContext extends ClassPathContext[AbstractFile] {
+    def toBinaryName(rep: AbstractFile) = {
+      assert(rep.name endsWith ".class", rep.name)
+      rep.name dropRight 6
+    }
+    def newClassPath(dir: AbstractFile) = new DirectoryClassPath(dir, this)
   }
-
-  class Library(location0: AbstractFile) extends Entry(location0) {
-    def doc: AbstractFile = null
-    def sourceFile: AbstractFile = null
-    def source = if (sourceFile eq null) null else new Source(sourceFile, false)
+  
+  object DefaultJavaContext extends JavaContext {
+    override def isValidName(name: String) = !isTraitImplementation(name)
   }
+  
+  /** From the source file to its identifier.
+   */
+  def toSourceName(f: AbstractFile): String = {
+    val nme = f.name
+    if (nme.endsWith(".scala"))
+      nme dropRight 6
+    else if (nme.endsWith(".java"))
+      nme dropRight 5
+    else
+      throw new FatalError("Unexpected source file ending: " + nme)
+  }
+}
+import ClassPath._
 
-  class Context(val entries: List[Entry]) {
-    def find(name: String, isDir: Boolean): Context = if (isPackage) {
-      def find0(entries: List[Entry]): Context = {
-        if (entries.isEmpty) new Context(Nil)
-        else {
-          val ret = find0(entries.tail)
-          val head = entries.head; 
-          val name0 = name + (if (!isDir) ".class" else "")
-          val clazz = if (head.location eq null) null
-                      else head.location.lookupPath(name0, isDir)
-
-          val source0 =
-            if (head.source eq null) null
-            else if ((clazz eq null) || isDir) {
-              val source1 = head.source.location.lookupPath(
-                name + (if (isDir) "" else ".scala"), isDir)
-              if ((source1 eq null) && !isDir && (clazz ne null)) head.source.location
-              else source1
-            }
-            else head.source.location
-
-          if ((clazz eq null) && (source0 eq null)) ret
-          else {
-            val entry = new Entry(clazz) {
-              override def source =
-                if (source0 eq null) null
-                else new Source(source0, head.source.compile)
-            }
-            try {
-              //Console.err.println("this=" + this + "\nclazz=" + clazz + "\nsource0=" + source0 + "\n")
-
-              if (!isDir) new Context(entry :: Nil)
-              else new Context(entry :: ret.entries)
-            } catch {
-              case e: Error =>
-              throw e
-            }
-          }
-        }
-      }
+/**
+ * Represents a package which contains classes and other packages
+ */
+abstract class ClassPath[T] {
+  type AnyClassRep = ClassPath[T]#ClassRep
 
-      val ret = find0(entries)
-      if (ret.entries.isEmpty) {
-        //Console.err.println("BAD_FILE: " + name + " in " + this)
-        null
-      } else ret
-    } else null
-
-    def isPackage: Boolean =
-      if (entries.isEmpty) false
-      else if (entries.head.location ne null) entries.head.location.isDirectory
-      else entries.head.source.location.isDirectory
-
-    def name =
-      if (entries.isEmpty) "<none>"
-      else {
-        val head = entries.head
-        val name = if (head.location ne null) head.location.name
-                   else head.source.location.name
-        if (isPackage) name
-        else name.substring(0, name.length() - (".class").length())
-      }
+  /**
+   * The short name of the package (without prefix)
+   */
+  def name: String
+  
+  /**
+   * A String representing the origin of this classpath element, if known.
+   * For example, the path of the directory or jar.
+   */
+  def origin: Option[String] = None
+  
+  /** A list of URLs representing this classpath.
+   */
+  def asURLs: List[URL]
+  
+  /** The whole classpath in the form of one String.
+   */
+  def asClasspathString: String
+
+  /** Info which should be propagated to any sub-classpaths.
+   */
+  def context: ClassPathContext[T]
+
+  /** Lists of entities.
+   */
+  def classes: List[AnyClassRep]
+  def packages: List[ClassPath[T]]
+  def sourcepaths: List[AbstractFile]
+  
+  /** Information which entails walking the tree.  This is probably only
+   *  necessary for tracking down problems - it's normally not used.
+   */
+  def allPackages: List[ClassPath[T]] = packages ::: (packages flatMap (_.allPackages))
+  def allPackageNames: List[String] = {
+    def subpackages(prefix: String, cp: ClassPath[T]): List[String] = (
+      (cp.packages map (prefix + _.name)) :::
+      (cp.packages flatMap (x => subpackages(prefix + x.name + ".", x)))
+    )
+    subpackages("", this)
+  }
+  def allPackagesWithNames: List[(String, ClassPath[T])] = {
+    val root = packages map (p => p.name -> p)
+    val subs =
+      for ((prefix, p) <- root ; (k, v) <- p.allPackagesWithNames) yield
+        (prefix + "." + k, v)
+    
+    root ::: subs
+  }
 
-    override def toString(): String = toString(entries)
-
-    def toString(entry: Entry): String =
-      ((if (entry.location eq null) "<none>"
-        else entry.location.toString()) +
-       (if (entry.source eq null) ""
-        else " with_source=" + entry.source.location.toString()))
-
-    def toString(entries0: List[Entry]): String =
-      if (entries0.isEmpty) ""
-      else toString(entries0.head) + ":::" + toString(entries0.tail)
-
-    def isSourceFile = {
-      def head = entries.head
-      def clazz = head.location
-      def source = if (head.source eq null) null else head.source.location
-      def isPredef = source.name.equals("Predef.scala") ||
-                     source.path.startsWith("scala/runtime")
-
-      if (entries.isEmpty || entries.isEmpty || (source eq null)) false
-      else if (!onlyPresentation && !head.source.compile) false
-      else if (source.isDirectory) false
-      else if (clazz eq null) true
-      else if (onlyPresentation && !isPredef) true
-      else if (source.lastModified > clazz.lastModified) true
-      else false
+  /**
+   * Represents classes which can be loaded with a ClassfileLoader/MSILTypeLoader
+   * and / or a SourcefileLoader.
+   */
+  case class ClassRep(binary: Option[T], source: Option[AbstractFile]) {
+    def name: String = binary match {
+      case Some(x)  => context.toBinaryName(x)
+      case _        =>
+        assert(source.isDefined)
+        toSourceName(source.get)
     }
-
-    def sourceFile = if ((entries.head.source ne null) && !entries.head.source.location.isDirectory)
-      entries.head.source.location else null
-
-    def classFile = if (!isSourceFile) entries.head.location else null
-
-    def sourcePath =
-      if (!isSourceFile && !entries.isEmpty && (entries.head.source ne null)) {
-        val ret = entries.head.source.location
-        if ((ret ne null) && !ret.isDirectory) {
-          Console.err.println("source path " + ret + " is not a directory")
-          null
-        } else ret
-      }
-      else null
-
-    def validPackage(name: String): Boolean =
-      ! (name.equals("META-INF") || name.startsWith("."))
   }
+  
+  /** Filters for assessing validity of various entities.
+   */
+  def validClassFile(name: String)  = (name endsWith ".class") && context.isValidName(name)
+  def validPackage(name: String)    = (name != "META-INF") && (name != "") && (name(0) != '.')
+  def validSourceFile(name: String) = validSourceExtensions exists (name endsWith _)
+  def validSourceExtensions         = List(".scala", ".java")
+
+  /**
+   * Find a ClassRep given a class name of the form "package.subpackage.ClassName".
+   * Does not support nested classes on .NET
+   */
+  def findClass(name: String): Option[AnyClassRep] =
+    splitWhere(name, _ == '.', true) match {
+      case Some((pkg, rest)) =>
+        val rep = packages find (_.name == pkg) flatMap (_ findClass rest)
+        rep map {
+          case x: ClassRep  => x
+          case x            => throw new FatalError("Unexpected ClassRep '%s' found searching for name '%s'".format(x, name))
+        }
+      case _ =>
+        classes find (_.name == name)
+    }
 
-  class Build {
-    val entries = new ArrayBuffer[Entry]
+  def findSourceFile(name: String): Option[AbstractFile] =
+    findClass(name) match {
+      case Some(ClassRep(Some(x: AbstractFile), _)) => Some(x)
+      case _                                        => None
+    }
 
-    def root = new Context(entries.toList)
+  def sortString = asURLs map (_.toString) sorted
+  override def equals(that: Any) = that match {
+    case x: ClassPath[_]  => this.sortString == x.sortString
+    case _                => false
+  }
+  override def hashCode = sortString.hashCode
+}
 
-    def this(classpath: String) {
-      this()
-      addFilesInPath(classpath)
-    }
+/**
+ * A Classpath containing source files
+ */
+class SourcePath[T](dir: AbstractFile, val context: ClassPathContext[T]) extends ClassPath[T] {  
+  def name = dir.name
+  override def origin = dir.underlyingSource map (_.path)
+  def asURLs = dir.sfile.toList map (_.toURL)
+  def asClasspathString = dir.path
+  val sourcepaths: List[AbstractFile] = List(dir)
+
+  lazy val classes: List[ClassRep] = dir collect {
+    case f if !f.isDirectory && validSourceFile(f.name) => ClassRep(None, Some(f))
+  } toList
+  
+  lazy val packages: List[SourcePath[T]] = dir collect {
+    case f if f.isDirectory && validPackage(f.name) => new SourcePath[T](f, context)
+  } toList
 
-    def this(source: String, output: String) {
-      this()
-      addDirsInPath(source, output)
-    }
 
-    def this(classpath: String, source: String, output: String,
-             boot: String, extdirs: String, codebase: String) {
-      this()
-      addFilesInPath(boot)
-      addArchivesInExtDirPath(extdirs)
-      addDirsInPath(source, output)
-      addFilesInPath(classpath)
-      addURLsInPath(codebase)
-    }
+  override def toString() = "sourcepath: "+ dir.toString()
+}
 
-    /**
-     *  Lookup the given path in this classpath. Returns null if not found.
-     *  Does not work with absolute paths (starting with '/').
-     * 
-     *  @param path  Path to look up (if isDir is false, '.class' is appended!).
-     *  @param isDir Whether to look for a directory or a file
-     *  @return      The abstract file or null if path was not found
-     */
-    def lookupPath(path: String, isDir: Boolean): AbstractFile = {
-      val ctx = root.find(path, isDir)
-      if (ctx eq null) null
-      else if (ctx.entries.isEmpty) null
-      else if (ctx.entries.head eq null) null
-      else ctx.entries.head.location
-    }
+/**
+ * A directory (or a .jar file) containing classfiles and packages
+ */
+class DirectoryClassPath(val dir: AbstractFile, val context: ClassPathContext[AbstractFile]) extends ClassPath[AbstractFile] {
+  def name = dir.name
+  override def origin = dir.underlyingSource map (_.path)
+  def asURLs = dir.sfile.toList map (_.toURL)
+  def asClasspathString = dir.path
+  val sourcepaths: List[AbstractFile] = Nil
+  
+  lazy val classes: List[ClassRep] = dir collect {
+    case f if !f.isDirectory && validClassFile(f.name) => ClassRep(Some(f), None)
+  } toList
+  
+  lazy val packages: List[DirectoryClassPath] = dir collect {
+    case f if f.isDirectory && validPackage(f.name) => new DirectoryClassPath(f, context)
+  } toList
+  
+  override def toString() = "directory classpath: "+ dir
+}
 
-    /**
-     *  @param classes where the class files come from and are written to
-     *  @param sources where the source files come from
-     */
-    def output(classes : String, sources : String) = {
-      assert(classes ne null)
-      assert(sources ne null)
-      val location = AbstractFile.getDirectory(classes)
-      val sources0 = AbstractFile.getDirectory(sources)
-      class Output0 extends Output(location, sources0) 
-      entries += new Output0()
-    }
-    /**
-     *  @param classes where the class files come from
-     *  @param sources optional source file attachment, otherwise null
-     */
-    def library(classes: String, sources: String) {
-      assert(classes ne null)
-      val location = AbstractFile.getDirectory(classes)
-      var sourceFile0 =
-        if (sources ne null) AbstractFile.getDirectory(sources)
-        else null
-      if (sourceFile0 ne null) {
-        val file00 = sourceFile0.lookupPath("src", true)
-        if ((file00 ne null) && file00.isDirectory) {
-          sourceFile0 = file00
-        }
-      }
-        
-      class Library0 extends Library(location) {
-        override def sourceFile = sourceFile0
+/**
+ * A classpath unifying multiple class- and sourcepath entries.
+ */
+class MergedClassPath[T](
+  val entries: List[ClassPath[T]],
+  val context: ClassPathContext[T])
+extends ClassPath[T] {
+  def name = entries.head.name
+  def asURLs = entries flatMap (_.asURLs)
+  lazy val sourcepaths: List[AbstractFile] = entries flatMap (_.sourcepaths)
+
+  override def origin = Some(entries map (x => x.origin getOrElse x.name) mkString ("Merged(", ", ", ")"))
+  override def asClasspathString: String = join(entries map (_.asClasspathString) : _*)
+
+  lazy val classes: List[AnyClassRep] = {
+    val cls = new ListBuffer[AnyClassRep]
+    for (e <- entries; c <- e.classes) {
+      val name = c.name
+      val idx = cls.indexWhere(_.name == name)
+      if (idx >= 0) {
+        val existing = cls(idx)
+        if (existing.binary.isEmpty && c.binary.isDefined)
+          cls(idx) = existing.copy(binary = c.binary)
+        if (existing.source.isEmpty && c.source.isDefined)
+          cls(idx) = existing.copy(source = c.source)
+      } else {
+        cls += c
       }
-      entries += new Library0()
     }
+    cls.toList
+  }
 
-    private def addFilesInPath(path: String) {
-      for (fileName <- ClassPath.expandPath(path)) {
-        val file = AbstractFile.getDirectory(fileName)
-        if (file ne null) entries += (new Library(file))
+  lazy val packages: List[ClassPath[T]] = {
+    val pkg = new ListBuffer[ClassPath[T]]
+    for (e <- entries; p <- e.packages) {
+      val name = p.name
+      val idx = pkg.indexWhere(_.name == name)
+      if (idx >= 0) {
+        pkg(idx) = addPackage(pkg(idx), p)
+      } else {
+        pkg += p
       }
     }
+    pkg.toList
+  }
 
-    private def addArchivesInExtDirPath(path: String) {
-      for (fileName <- ClassPath.expandPath(path)) {
-        val file = AbstractFile.getDirectory(fileName)
-        if (file ne null) {
-          for (file0 <- file) {
-            val name = file0.name
-            if (name.endsWith(".jar") || name.endsWith(".zip") || file0.isDirectory) {
-              val archive = AbstractFile.getDirectory(new File(file.file, name))
-              if (archive ne null) entries += (new Library(archive))
-            }
-          }
-        }
-      }
+  private def addPackage(to: ClassPath[T], pkg: ClassPath[T]) = {
+    val newEntries = to match {
+      case cp: MergedClassPath[_] => cp.entries :+ pkg
+      case _                      => List(to, pkg)
     }
+    new MergedClassPath[T](newEntries, context)
+  }
+  
+  override def allPackages: List[ClassPath[T]] = entries flatMap (_.allPackages)
+  override def allPackageNames = entries flatMap (_.allPackageNames)
+  override def allPackagesWithNames = entries flatMap (_.allPackagesWithNames)
 
-    private def addDirsInPath(source: String, output: String) {
-      val clazzes = AbstractFile.getDirectory(output)
-      if (clazzes eq null)
-        throw new FatalError("Output location \"" + output + "\" not found")
-      val strtok = new StringTokenizer(source, File.pathSeparator)
-      if (!strtok.hasMoreTokens()) {
-        val output0 = (new Output(clazzes, null))
-        entries += output0
-      }
-      else while (strtok.hasMoreTokens()) {
-        val sources = AbstractFile.getDirectory(strtok.nextToken())
-        val output0 = (new Output(clazzes, sources))
-        entries += output0
-      }    
-    }
+  def duplicatedClasses = {    
+    def toFullName(x: (String, _, AnyClassRep)) = x._1 + "." + x._3.name
+    
+    /** Flatten everything into tuples, recombine grouped by name, filter down to 2+ entries. */
+    val flattened = (
+      for ((pkgName, pkg) <- allPackagesWithNames ; clazz <- pkg.classes) yield
+        (pkgName, pkg, clazz)
+    )
+    val multipleAppearingEntries = flattened groupBy toFullName filter (_._2.size > 1)
+
+    /** Using original name list as reference point, return duplicated entries as
+     *    (name, list of origins)
+     *  in the order they occur on the path.
+     */
+    for (name <- flattened map toFullName distinct ; dups <- multipleAppearingEntries get name) yield
+      (name, dups map {
+        case (_, cp, _) if cp.origin.isDefined  => cp.origin.get
+        case (_, cp, _)                         => cp.asURLs.mkString
+      })
+  }
 
-    private val urlSeparator = " "
-    private def addURLsInPath(codebase: String) {
-      val strtok = new StringTokenizer(codebase, urlSeparator)
-      while (strtok.hasMoreTokens()) {
-        try {
-          val url = new URL(strtok.nextToken())
-          val archive = AbstractFile.getURL(url)
-          if (archive ne null) entries += (new Library(archive))
-        }
-        catch {
-          case e =>
-            Console.println("error in addURLsInPath: " + e.getMessage)//debug
-            throw e
-        }
-      }
+  def show {
+    println("ClassPath %s has %d entries and results in:\n".format(name, entries.size))
+    asClasspathString split ':' foreach (x => println("  " + x))
+  }
+  def showDuplicates =
+    ClassPath findDuplicates this foreach {
+      case (name, xs) => println(xs.mkString(name + ":\n  ", "\n  ", "\n"))
     }
+  
+  override def toString() = "merged classpath "+ entries.mkString("(", "\n", ")")
+}
 
-    override def toString() =
-      entries.toList.mkString("", File.pathSeparator, "")
-  } // class Build
-
+/**
+ * The classpath when compiling with target:jvm. Binary files (classfiles) are represented
+ * as AbstractFile. nsc.io.ZipArchive is used to view zip/jar archives as directories.
+ */
+class JavaClassPath(
+  containers: List[ClassPath[AbstractFile]],
+  context: JavaContext)
+extends MergedClassPath[AbstractFile](containers, context) {
 }
diff --git a/src/compiler/scala/tools/nsc/util/CommandLineParser.scala b/src/compiler/scala/tools/nsc/util/CommandLineParser.scala
new file mode 100644
index 0000000..63ac8d9
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/util/CommandLineParser.scala
@@ -0,0 +1,145 @@
+/* NEST (New Scala Test)
+ * Copyright 2007-2010 LAMP/EPFL
+ * @author Paul Phillips
+ */
+
+package scala.tools.nsc
+package util
+
+import scala.util.parsing.combinator._
+import scala.util.parsing.input.{ Reader }
+import scala.util.parsing.input.CharArrayReader.EofCh
+import scala.collection.mutable.ListBuffer
+
+/** A simple command line parser to replace the several different
+ *  simple ones spread around trunk.
+ * 
+ *  XXX Note this has been completely obsolesced by scala.tools.cmd.
+ *  I checked it back in as part of rolling partest back a month
+ *  rather than go down the rabbit hole of unravelling dependencies.
+ */
+
+trait ParserUtil extends Parsers {
+  class ParserPlus[+T](underlying: Parser[T]) {
+    def !~>[U](p: => Parser[U]): Parser[U] = (underlying ~! p) ^^ { case a~b  => b }
+    def <~![U](p: => Parser[U]): Parser[T] = (underlying ~! p) ^^ { case a~b  => a }
+  }
+  protected implicit def parser2parserPlus[T](p: Parser[T]): ParserPlus[T] = new ParserPlus(p)
+}
+
+case class CommandLine(
+  args: List[String],
+  unaryArguments: List[String],
+  binaryArguments: List[String]
+) {
+  def this(args: List[String]) = this(args, Nil, Nil)
+  def this(args: Array[String]) = this(args.toList, Nil, Nil)
+  def this(line: String) = this(CommandLineParser tokenize line, Nil, Nil)
+  
+  def withUnaryArgs(xs: List[String]) = copy(unaryArguments = xs)
+  def withBinaryArgs(xs: List[String]) = copy(binaryArguments = xs)
+  
+  def originalArgs = args
+  def assumeBinary = true
+  def enforceArity = true
+  def onlyKnownOptions = false
+  
+  val Terminator = "--"
+  val ValueForUnaryOption = "true"  // so if --opt is given, x(--opt) = true
+
+  def mapForUnary(opt: String) = Map(opt -> ValueForUnaryOption)
+  def errorFn(msg: String) = println(msg)
+  
+  /** argMap is option -> argument (or "" if it is a unary argument)
+   *  residualArgs are what is left after removing the options and their args.
+   */
+  lazy val (argMap, residualArgs) = {
+    val residualBuffer = new ListBuffer[String]
+    
+    def stripQuotes(s: String) = {
+      def isQuotedBy(c: Char) = s.length > 0 && s.head == c && s.last == c
+      if (List('"', '\'') exists isQuotedBy) s.tail.init else s
+    }
+    
+    def isValidOption(s: String) = !onlyKnownOptions || (unaryArguments contains s) || (binaryArguments contains s)
+    def isOption(s: String) = (s startsWith "-") && (isValidOption(s) || { unknownOption(s) ; false })
+    def isUnary(s: String) = isOption(s) && (unaryArguments contains s)
+    def isBinary(s: String) = isOption(s) && !isUnary(s) && (assumeBinary || (binaryArguments contains s))
+
+    def unknownOption(opt: String) =
+      errorFn("Option '%s' not recognized.".format(opt))
+    def missingArg(opt: String, what: String) =
+      errorFn("Option '%s' requires argument, found %s instead.".format(opt, what))
+    
+    def loop(args: List[String]): Map[String, String] = {
+      def residual(xs: List[String]) = { residualBuffer ++= xs ; Map[String, String]() }
+      if (args.isEmpty) return Map()
+      val hd :: rest = args
+      if (rest.isEmpty) {
+        if (isBinary(hd) && enforceArity)
+          missingArg(hd, "EOF")
+        
+        if (isOption(hd)) mapForUnary(hd) else residual(args)
+      }
+      else
+        if (hd == Terminator) residual(rest)
+      else {
+        val hd1 :: hd2 :: rest = args
+        
+        if (hd2 == Terminator) mapForUnary(hd1) ++ residual(rest)
+        else if (isUnary(hd1)) mapForUnary(hd1) ++ loop(hd2 :: rest)
+        else if (isBinary(hd1)) {
+          // Disabling this check so
+          //  --scalacopts "-verbose" works.  We can't tell if it's quoted,
+          // the shell does us in.
+          //
+          // if (isOption(hd2) && enforceArity)
+          //   missingArg(hd1, hd2)
+            
+          Map(hd1 -> hd2) ++ loop(rest)
+        }
+        else { residual(List(hd1)) ++ loop(hd2 :: rest) }
+      }
+    }
+    
+    (loop(args), residualBuffer map stripQuotes toList)
+  }
+  
+  def isSet(arg: String) = args contains arg
+  def get(arg: String) = argMap get arg
+  def getOrElse(arg: String, orElse: => String) = if (isSet(arg)) apply(arg) else orElse
+  def apply(arg: String) = argMap(arg)
+
+  override def toString() = "CommandLine(\n%s)\n" format (args map ("  " + _ + "\n") mkString)
+}
+
+object CommandLineParser extends RegexParsers with ParserUtil {
+  override def skipWhitespace = false
+  
+  def elemExcept(xs: Elem*): Parser[Elem] = elem("elemExcept", x => x != EofCh && !(xs contains x))
+  def elemOf(xs: Elem*): Parser[Elem]     = elem("elemOf", xs contains _)
+  def escaped(ch: Char): Parser[String] = "\\" + ch
+  def mkQuoted(ch: Char): Parser[String] = (
+      elem(ch) !~> rep(escaped(ch) | elemExcept(ch)) <~ ch ^^ (_.mkString)
+    | failure("Unmatched %s in input." format ch)
+  )
+  
+  /** Apparently windows can't deal with the quotes sticking around. */
+  lazy val squoted: Parser[String] = mkQuoted('\'')   // ^^ (x => "'%s'" format x)
+  lazy val dquoted: Parser[String] = mkQuoted('"')    // ^^ (x => "\"" + x + "\"")
+  lazy val token: Parser[String]   = """\S+""".r
+
+  lazy val argument: Parser[String] = squoted | dquoted | token
+  lazy val commandLine: Parser[List[String]] = phrase(repsep(argument, whiteSpace))
+  
+  class ParseException(msg: String) extends RuntimeException(msg)
+  
+  def tokenize(line: String): List[String] = tokenize(line, x => throw new ParseException(x))
+  def tokenize(line: String, errorFn: String => Unit): List[String] = {
+    parse(commandLine, line.trim) match {
+      case Success(args, _)     => args
+      case NoSuccess(msg, rest) => errorFn(msg) ; Nil
+    }
+  }
+  def apply(line: String) = new CommandLine(tokenize(line))
+}
diff --git a/src/compiler/scala/tools/nsc/util/DocStrings.scala b/src/compiler/scala/tools/nsc/util/DocStrings.scala
new file mode 100644
index 0000000..ce829fb
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/util/DocStrings.scala
@@ -0,0 +1,138 @@
+/* NSC -- new Scala compiler
+ * Copyright 2006-2010 LAMP/EPFL
+ * @author  Martin Odersky
+ */
+
+
+package scala.tools.nsc
+package util
+
+import Chars._
+import scala.collection.mutable.{HashMap, ListBuffer, StringBuilder}
+
+/** Utilitity methods for doc comment strings
+ */
+object DocStrings {
+
+  /** Returns index of string `str` following `start` skipping longest
+   *  sequence of whitespace characters characters (but no newlines)
+   */
+  def skipWhitespace(str: String, start: Int): Int =
+    if (start < str.length && isWhitespace(str charAt start)) skipWhitespace(str, start + 1)
+    else start
+
+  /** Returns index of string `str` following `start` skipping 
+   *  sequence of identifier characters.
+   */
+  def skipIdent(str: String, start: Int): Int =
+    if (start < str.length && isIdentifierPart(str charAt start)) skipIdent(str, start + 1)
+    else start
+
+  /** Returns index of string `str` after `start` skipping longest
+   *  sequence of space and tab characters, possibly also containing
+   *  a single `*' character or the `/``**` sequence.
+   *  @pre  start == str.length || str(start) == `\n'
+   */
+  def skipLineLead(str: String, start: Int): Int =
+    if (start == str.length) start
+    else {
+      val idx = skipWhitespace(str, start + 1)
+      if (idx < str.length && (str charAt idx) == '*') skipWhitespace(str, idx + 1)
+      else if (idx + 2 < str.length && (str charAt idx) == '/' && (str charAt (idx + 1)) == '*' && (str charAt (idx + 2)) == '*')
+        skipWhitespace(str, idx + 3)
+      else idx
+    }
+
+  /** Skips to next occurrence of `\n' or to the position after the `/``**` sequence following index `start`.
+   */
+  def skipToEol(str: String, start: Int): Int =
+    if (start + 2 < str.length && (str charAt start) == '/' && (str charAt (start + 1)) == '*' && (str charAt (start + 2)) == '*') start + 3
+    else if (start < str.length && (str charAt start) != '\n') skipToEol(str, start + 1)
+    else start
+
+  /** Returns first index following `start` and starting a line (i.e. after skipLineLead) or starting the comment
+   *  which satisfies predicate `p'.
+   */
+  def findNext(str: String, start: Int)(p: Int => Boolean): Int = {
+    val idx = skipLineLead(str, skipToEol(str, start))
+    if (idx < str.length && !p(idx)) findNext(str, idx)(p)
+    else idx
+  }
+
+  /** Return first index following `start` and starting a line (i.e. after skipLineLead)
+   *  which satisfies predicate `p'.
+   */
+  def findAll(str: String, start: Int)(p: Int => Boolean): List[Int] = {
+    val idx = findNext(str, start)(p)
+    if (idx == str.length) List()
+    else idx :: findAll(str, idx)(p)
+  }
+
+  /** Produces a string index, which is a list of ``sections'', i.e
+   *  pairs of start/end positions of all tagged sections in the string.
+   *  Every section starts with a `@' and extends to the next `@', or
+   *  to the end of the comment string, but excluding the final two
+   *  characters which terminate the comment.
+   */
+  def tagIndex(str: String, p: Int => Boolean = (idx => true)): List[(Int, Int)] =
+    findAll(str, 0) (idx => str(idx) == '@' && p(idx)) match {
+      case List() => List()
+      case idxs => idxs zip (idxs.tail ::: List(str.length - 2))
+    }
+
+  /** Does interval `iv` start with given `tag`?
+   */
+  def startsWithTag(str: String, section: (Int, Int), tag: String): Boolean = 
+    startsWithTag(str, section._1, tag)
+
+  def startsWithTag(str: String, start: Int, tag: String): Boolean =
+    str.startsWith(tag, start) && !isIdentifierPart(str charAt (start + tag.length))
+
+
+  /** The first start tag of a list of tag intervals,
+   *  or the end of the whole comment string - 2 if list is empty
+   */
+  def startTag(str: String, sections: List[(Int, Int)]) = sections match {
+    case List() => str.length - 2
+    case (start, _) :: _ => start
+  }
+
+  /** A map from parameter names to start/end indices describing all parameter
+   *  sections in `str` tagged with `tag`, where `sections` is the index of `str`.
+   */
+  def paramDocs(str: String, tag: String, sections: List[(Int, Int)]): Map[String, (Int, Int)] =
+    Map() ++ {
+      for (section <- sections if startsWithTag(str, section, tag)) yield {
+        val start = skipWhitespace(str, section._1 + tag.length)
+        str.substring(start, skipIdent(str, start)) -> section
+      }
+    }
+
+  /** Optionally start and end index of return section in `str`, or `None`
+   *  if `str` does not have a @return.
+   */
+  def returnDoc(str: String, sections: List[(Int, Int)]): Option[(Int, Int)] = 
+    sections find (startsWithTag(str, _, "@return"))
+    
+  /** Extracts variable name from a string, stripping any pair of surrounding braces */
+  def variableName(str: String): String = 
+    if (str.length >= 2 && (str charAt 0) == '{' && (str charAt (str.length - 1)) == '}')
+      str.substring(1, str.length - 1)
+    else
+      str
+
+  /** Returns index following variable, or start index if no variable was recognized
+   */
+  def skipVariable(str: String, start: Int): Int = {
+    var idx = start
+    if (idx < str.length && (str charAt idx) == '{') {
+      do idx += 1
+      while (idx < str.length && (str charAt idx) != '}')
+      if (idx < str.length) idx + 1 else start
+    } else {
+      while (idx < str.length && isVarPart(str charAt idx))
+        idx += 1
+      idx
+    }
+  }
+}
diff --git a/src/compiler/scala/tools/nsc/util/FreshNameCreator.scala b/src/compiler/scala/tools/nsc/util/FreshNameCreator.scala
index a35e274..714e731 100644
--- a/src/compiler/scala/tools/nsc/util/FreshNameCreator.scala
+++ b/src/compiler/scala/tools/nsc/util/FreshNameCreator.scala
@@ -1,44 +1,54 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: FreshNameCreator.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.tools.nsc.util
+package scala.tools.nsc
+package util
 
 import scala.collection.mutable.HashMap
 
 trait FreshNameCreator {
-  /** do not call before after type checking ends. Use newName(Position,String) instead. */
-  @deprecated def newName(prefix : String) : String
-  /** do not call before after type checking ends. Use newName(Position) instead. */
-  @deprecated def newName() : String
-  def newName(pos : util.Position, prefix : String) : String
-  def newName(pos : util.Position) : String
+
+  /** do not call before after type checking ends.
+   */
+  @deprecated("use newName(Position, String) instead")
+  def newName(prefix: String): String
+
+  /** do not call before after type checking ends.
+   */
+  @deprecated("use newName(Position) instead")
+  def newName(): String
+
+  def newName(pos: util.Position, prefix: String): String
+  def newName(pos: util.Position): String
 }
+
 object FreshNameCreator {
+
   class Default extends FreshNameCreator {
 
-  protected var counter = 0
-  protected val counters = new HashMap[String, Int]
+    protected var counter = 0
+    protected val counters = new HashMap[String, Int]
 
-  /**
-   * Create a fresh name with the given prefix. It is guaranteed
-   * that the returned name has never been returned by a previous
-   * call to this function (provided the prefix does not end in a digit).
-   */
-  def newName(prefix: String): String = {
-    val safePrefix = prefix.replace('<', '$').replace('>', '$')
-    val count = counters.getOrElse(safePrefix, 0) + 1
-    counters(safePrefix) = count
-    safePrefix + count
-  }
-  def newName(pos : util.Position, prefix : String) = newName(prefix)
-  def newName(pos : util.Position) = newName()
+    /**
+     * Create a fresh name with the given prefix. It is guaranteed
+     * that the returned name has never been returned by a previous
+     * call to this function (provided the prefix does not end in a digit).
+     */
+    def newName(prefix: String): String = {
+      val safePrefix = prefix.replace('<', '$').replace('>', '$')
+      val count = counters.getOrElse(safePrefix, 0) + 1
+      counters(safePrefix) = count
+      safePrefix + count
+    }
+    def newName(pos: util.Position, prefix: String) = newName(prefix)
+    def newName(pos: util.Position) = newName()
 
-  def newName(): String = {
-    counter = counter + 1
-    "$" + counter + "$"
+    def newName(): String = {
+      counter += 1
+      "$" + counter + "$"
+    }
   }
-}
+
 }
diff --git a/src/compiler/scala/tools/nsc/util/HashSet.scala b/src/compiler/scala/tools/nsc/util/HashSet.scala
index ffafb8d..2373097 100644
--- a/src/compiler/scala/tools/nsc/util/HashSet.scala
+++ b/src/compiler/scala/tools/nsc/util/HashSet.scala
@@ -1,25 +1,46 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: HashSet.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.tools.nsc.util
-
-class HashSet[T >: Null <: AnyRef](initialCapacity: Int) extends Set[T] {
+package scala.tools.nsc
+package util
 
+class HashSet[T >: Null <: AnyRef](val label: String, initialCapacity: Int) extends Set[T] {
+  def this(initialCapacity: Int) = this("No Label", initialCapacity)
+  def this(label: String) = this(label, 16)
   def this() = this(16)
 
-  private var capacity = initialCapacity
   private var used = 0
-  private var table = new Array[AnyRef](capacity)
+  private var table = new Array[AnyRef](initialCapacity)
+  // System.err.println("Created: " + this)
 
   def size: Int = used
+  def clear() {
+    used = 0
+    table = new Array[AnyRef](initialCapacity)
+  }
 
-  private def index(x: Int): Int = Math.abs(x % capacity)
+  private def index(x: Int): Int = math.abs(x % table.length)
+
+  def findEntryOrUpdate(x: T): T = {
+    var h = index(x.##)
+    var entry = table(h)
+    while (entry ne null) {
+      if (x == entry)
+        return entry.asInstanceOf[T]
+        
+      h = index(h + 1)
+      entry = table(h)
+    }
+    table(h) = x
+    used += 1
+    if (used > (table.length >> 2)) growTable()
+    x
+  }
 
   def findEntry(x: T): T = {
-    var h = index(x.hashCode())
+    var h = index(x.##)
     var entry = table(h)
     while ((entry ne null) && entry != x) {
       h = index(h + 1)
@@ -29,38 +50,53 @@ class HashSet[T >: Null <: AnyRef](initialCapacity: Int) extends Set[T] {
   }
 
   def addEntry(x: T) {
-    var h = index(x.hashCode())
+    var h = index(x.##)
     var entry = table(h)
     while (entry ne null) {
       if (entry == x) return
-      h = index((h + 1))
+      h = index(h + 1)
       entry = table(h)
     }
     table(h) = x
     used += 1
-    if (used >= (capacity >> 2)) growTable()
+    if (used > (table.length >> 2)) growTable()
   }
 
-  def elements = new Iterator[T] {
+  def iterator = new Iterator[T] {
     private var i = 0
     def hasNext: Boolean = {
-      while (i < capacity && (table(i) eq null)) i += 1
-      i < capacity
+      while (i < table.length && (table(i) eq null)) i += 1
+      i < table.length
     }
     def next: T =
       if (hasNext) { i += 1; table(i - 1).asInstanceOf[T] }
       else null
   }
+  
+  private def addOldEntry(x: T) {
+    var h = index(x.##)
+    var entry = table(h)
+    while (entry ne null) {
+      h = index(h + 1)
+      entry = table(h)
+    }
+    table(h) = x
+  }
 
   private def growTable() {
     val oldtable = table
-    capacity *= 2
-    table = new Array[AnyRef](capacity)
+    val growthFactor =
+      if (table.length <= initialCapacity) 8
+      else if (table.length <= (initialCapacity * 8)) 4
+      else 2
+      
+    table = new Array[AnyRef](table.length * growthFactor)
     var i = 0
     while (i < oldtable.length) {
       val entry = oldtable(i)
-      if (entry ne null) addEntry(entry.asInstanceOf[T])
+      if (entry ne null) addOldEntry(entry.asInstanceOf[T])
       i += 1
     }
   }
+  override def toString() = "HashSet %s(%d / %d)".format(label, used, table.length)
 }
diff --git a/src/compiler/scala/tools/nsc/util/InterruptReq.scala b/src/compiler/scala/tools/nsc/util/InterruptReq.scala
new file mode 100644
index 0000000..9ae4c50
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/util/InterruptReq.scala
@@ -0,0 +1,35 @@
+package scala.tools.nsc
+package util
+
+/** A class of work items to be used in interrupt requests.
+ */
+abstract class InterruptReq {
+  /** The result type of the operation
+   */
+  type R
+  
+  /** The operation to be performed */
+  protected val todo: () => R
+
+  /** The result provided */
+  private var result: Option[Either[R, Throwable]] = None
+
+  /** To be called from interrupted server to execute demanded task */
+  def execute(): Unit = synchronized {
+    try {
+      result = Some(Left(todo()))
+    } catch {
+      case t => result = Some(Right(t))
+    }
+    notify()
+  }
+
+  /** To be called from interrupting client to get result fo interrupt */
+  def getResult(): R = synchronized {
+    while (result.isEmpty) wait()
+    result.get match {
+      case Left(res) => res
+      case Right(t) => throw t
+    }
+  }
+}
diff --git a/src/compiler/scala/tools/nsc/util/JavaCharArrayReader.scala b/src/compiler/scala/tools/nsc/util/JavaCharArrayReader.scala
new file mode 100644
index 0000000..43b1229
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/util/JavaCharArrayReader.scala
@@ -0,0 +1,123 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
+ * @author  Martin Odersky
+ */
+
+package scala.tools.nsc
+package util
+
+import Chars._
+
+class JavaCharArrayReader(buf: IndexedSeq[Char], start: Int, /* startline: int, startcol: int, */
+                      decodeUni: Boolean, error: String => Unit) extends Iterator[Char] with Cloneable {
+
+  def this(buf: IndexedSeq[Char], decodeUni: Boolean, error: String => Unit) =
+    this(buf, 0, /* 1, 1, */ decodeUni, error)
+
+  /** produce a duplicate of this char array reader which starts reading
+    *  at current position, independent of what happens to original reader
+	*/
+  def dup: JavaCharArrayReader = clone().asInstanceOf[JavaCharArrayReader]
+
+  /** layout constant
+   */
+  val tabinc = 8
+
+  /** the line and column position of the current character
+  */
+  var ch: Char = _
+  var bp = start
+  var oldBp = -1
+  var oldCh: Char = _
+  
+  //private var cline: Int = _
+  //private var ccol: Int = _
+  def cpos = bp
+  var isUnicode: Boolean = _
+  var lastLineStartPos: Int = 0
+  var lineStartPos: Int = 0
+  var lastBlankLinePos: Int = 0
+
+  private var onlyBlankChars = false
+  //private var nextline = startline
+  //private var nextcol = startcol
+
+  private def markNewLine() {
+    lastLineStartPos = lineStartPos
+    if (onlyBlankChars) lastBlankLinePos = lineStartPos
+    lineStartPos = bp
+    onlyBlankChars = true
+    //nextline += 1
+    //nextcol = 1
+  }
+
+  def hasNext: Boolean = if (bp < buf.length) true 
+  else {
+    false
+  }
+
+  def last: Char = if (bp > start + 2) buf(bp - 2) else ' ' // XML literals
+
+  def next: Char = {
+    //cline = nextline
+    //ccol = nextcol
+    val buf = this.buf.asInstanceOf[collection.mutable.WrappedArray[Char]].array
+    if(!hasNext) {
+      ch = SU
+      return SU  // there is an endless stream of SU's at the end 
+    }
+    oldBp = bp
+    oldCh = ch
+    ch = buf(bp)
+    isUnicode = false
+    bp = bp + 1
+    ch match {
+      case '\t' =>
+        // nextcol = ((nextcol - 1) / tabinc * tabinc) + tabinc + 1;
+      case CR =>
+        if (bp < buf.size && buf(bp) == LF) {
+          ch = LF
+          bp += 1
+        }
+        markNewLine()
+      case LF | FF =>
+        markNewLine()
+      case '\\' =>
+        def evenSlashPrefix: Boolean = {
+          var p = bp - 2
+          while (p >= 0 && buf(p) == '\\') p -= 1
+          (bp - p) % 2 == 0
+        }
+        def udigit: Int = {
+          val d = digit2int(buf(bp), 16)
+          if (d >= 0) { bp += 1; /* nextcol = nextcol + 1 */ }
+          else error("error in unicode escape");
+          d
+        }
+        // nextcol += 1
+        if (buf(bp) == 'u' && decodeUni && evenSlashPrefix) {
+          do {
+            bp += 1 //; nextcol += 1
+          } while (buf(bp) == 'u');
+          val code = udigit << 12 | udigit << 8 | udigit << 4 | udigit
+          ch = code.asInstanceOf[Char]
+          isUnicode = true
+        }
+      case _ =>
+        if (ch > ' ') onlyBlankChars = false
+        // nextcol += 1
+    }
+    ch
+  }
+
+  def rewind {
+    if (oldBp == -1) throw new IllegalArgumentException
+    bp = oldBp
+    ch = oldCh
+    oldBp = -1
+    oldCh = 'x'
+  }
+
+  def copy: JavaCharArrayReader =
+    new JavaCharArrayReader(buf, bp, /* nextcol, nextline, */ decodeUni, error)
+}
diff --git a/src/compiler/scala/tools/nsc/util/MsilClassPath.scala b/src/compiler/scala/tools/nsc/util/MsilClassPath.scala
new file mode 100644
index 0000000..d4c100a
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/util/MsilClassPath.scala
@@ -0,0 +1,169 @@
+/* NSC -- new Scala compiler
+ * Copyright 2006-2010 LAMP/EPFL
+ * @author  Martin Odersky
+ */
+
+// $Id$
+
+package scala.tools.nsc
+package util
+
+import java.io.File
+import java.net.URL
+import java.util.StringTokenizer
+import scala.util.Sorting
+
+import scala.collection.mutable.{ ListBuffer, HashSet => MutHashSet }
+import scala.tools.nsc.io.AbstractFile
+
+import ch.epfl.lamp.compiler.msil.{ Type => MSILType, Assembly }
+import ClassPath.{ ClassPathContext, isTraitImplementation }
+
+/** Keeping the MSIL classpath code in its own file is important to make sure
+ *  we don't accidentally introduce a dependency on msil.jar in the jvm.
+ */
+
+object MsilClassPath {
+  def collectTypes(assemFile: AbstractFile) = {
+    var res: Array[MSILType] = MSILType.EmptyTypes
+    val assem = Assembly.LoadFrom(assemFile.path)
+    if (assem != null) {
+      // DeclaringType == null: true for non-inner classes
+      res = assem.GetTypes() filter (_.DeclaringType == null)
+      Sorting.stableSort(res, (t1: MSILType, t2: MSILType) => (t1.FullName compareTo t2.FullName) < 0)
+    }
+    res
+  }
+  
+  /** On the java side this logic is in PathResolver, but as I'm not really
+   *  up to folding MSIL into that, I am encapsulating it here.
+   */
+  def fromSettings(settings: Settings): MsilClassPath = {
+    val context =
+      if (settings.inline.value) new MsilContext
+      else new MsilContext { override def isValidName(name: String) = !isTraitImplementation(name) }
+    
+    import settings._
+    new MsilClassPath(assemextdirs.value, assemrefs.value, sourcepath.value, context)
+  }  
+  
+  class MsilContext extends ClassPathContext[MSILType] {
+    def toBinaryName(rep: MSILType) = rep.Name
+    def newClassPath(assemFile: AbstractFile) = new AssemblyClassPath(MsilClassPath collectTypes assemFile, "", this)
+  }
+  
+  private def assembleEntries(ext: String, user: String, source: String, context: MsilContext): List[ClassPath[MSILType]] = {
+    import ClassPath._
+    val etr = new ListBuffer[ClassPath[MSILType]]
+    val names = new MutHashSet[String]
+
+    // 1. Assemblies from -Xassem-extdirs
+    for (dirName <- expandPath(ext, expandStar = false)) {
+      val dir = AbstractFile.getDirectory(dirName)
+      if (dir ne null) {
+        for (file <- dir) {
+          val name = file.name.toLowerCase
+          if (name.endsWith(".dll") || name.endsWith(".exe")) {
+            names += name
+            etr += context.newClassPath(file)
+          }
+        }
+      }
+    }
+
+    // 2. Assemblies from -Xassem-path
+    for (fileName <- expandPath(user, expandStar = false)) {
+      val file = AbstractFile.getFile(fileName)
+      if (file ne null) {
+        val name = file.name.toLowerCase
+        if (name.endsWith(".dll") || name.endsWith(".exe")) {
+          names += name
+          etr += context.newClassPath(file)
+        }
+      }
+    }
+
+    def check(n: String) {
+      if (!names.contains(n))
+      throw new AssertionError("Cannot find assembly "+ n +
+         ". Use -Xassem-extdirs or -Xassem-path to specify its location")
+    }
+    check("mscorlib.dll")
+    check("scalaruntime.dll")
+
+    // 3. Source path
+    for (dirName <- expandPath(source, expandStar = false)) {
+      val file = AbstractFile.getDirectory(dirName)
+      if (file ne null) etr += new SourcePath[MSILType](file, context)
+    }
+
+    etr.toList
+  }
+}
+import MsilClassPath._
+
+/**
+ * A assembly file (dll / exe) containing classes and namespaces
+ */
+class AssemblyClassPath(types: Array[MSILType], namespace: String, val context: MsilContext) extends ClassPath[MSILType] {
+  def name = {
+    val i = namespace.lastIndexOf('.')
+    if (i < 0) namespace
+    else namespace drop (i + 1)
+  }
+  def asURLs = List(new java.net.URL(name))
+  def asClasspathString = error("Unknown")  // I don't know what if anything makes sense here?
+
+  private lazy val first: Int = {
+    var m = 0
+    var n = types.length - 1
+    while (m < n) {
+      val l = (m + n) / 2
+      val res = types(l).FullName.compareTo(namespace)
+      if (res < 0) m = l + 1
+      else n = l
+    }
+    if (types(m).FullName.startsWith(namespace)) m else types.length
+  }
+
+  lazy val classes = {
+    val cls = new ListBuffer[ClassRep]
+    var i = first
+    while (i < types.length && types(i).Namespace.startsWith(namespace)) {
+      // CLRTypes used to exclude java.lang.Object and java.lang.String (no idea why..)
+      if (types(i).Namespace == namespace)
+        cls += ClassRep(Some(types(i)), None)
+      i += 1
+    }
+    cls.toList
+  }
+
+  lazy val packages = {
+    val nsSet = new MutHashSet[String]
+    var i = first
+    while (i < types.length && types(i).Namespace.startsWith(namespace)) {
+      val subns = types(i).Namespace
+      if (subns.length > namespace.length) {
+        // example: namespace = "System", subns = "System.Reflection.Emit"
+        //   => find second "." and "System.Reflection" to nsSet.
+        val end = subns.indexOf('.', namespace.length + 1)
+        nsSet += (if (end < 0) subns
+                  else subns.substring(0, end))
+      }
+      i += 1
+    }
+    for (ns <- nsSet.toList)
+      yield new AssemblyClassPath(types, ns, context)
+  }
+
+  val sourcepaths: List[AbstractFile] = Nil
+  
+  override def toString() = "assembly classpath "+ namespace
+}
+
+/**
+ * The classpath when compiling with target:msil. Binary files are represented as
+ * MSILType values.
+ */
+class MsilClassPath(ext: String, user: String, source: String, context: MsilContext)
+extends MergedClassPath[MSILType](MsilClassPath.assembleEntries(ext, user, source, context), context) { }
\ No newline at end of file
diff --git a/src/compiler/scala/tools/nsc/util/NameTransformer.scala b/src/compiler/scala/tools/nsc/util/NameTransformer.scala
deleted file mode 100644
index 9f73fc8..0000000
--- a/src/compiler/scala/tools/nsc/util/NameTransformer.scala
+++ /dev/null
@@ -1,148 +0,0 @@
-/* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
- * @author  Martin Odersky
- */
-// $Id: NameTransformer.scala 17013 2009-02-02 11:59:53Z washburn $
-
-package scala.tools.nsc.util
-
-object NameTransformer {
-  private val nops = 128
-  private val ncodes = 26 * 26
-
-  private class OpCodes(val op: Char, val code: String, val next: OpCodes)
-
-  private val op2code = new Array[String](nops)
-  private val code2op = new Array[OpCodes](ncodes)
-
-  private def enterOp(op: Char, code: String) = {
-    op2code(op) = code
-    val c = (code.charAt(1) - 'a') * 26 + code.charAt(2) - 'a'
-    code2op(c) = new OpCodes(op, code, code2op(c))
-  }
-
-  /* Note: decoding assumes opcodes are only ever lowercase. */
-  enterOp('~', "$tilde")
-  enterOp('=', "$eq")
-  enterOp('<', "$less")
-  enterOp('>', "$greater")
-  enterOp('!', "$bang")
-  enterOp('#', "$hash")
-  enterOp('%', "$percent")
-  enterOp('^', "$up")
-  enterOp('&', "$amp")
-  enterOp('|', "$bar")
-  enterOp('*', "$times")
-  enterOp('/', "$div")
-  enterOp('+', "$plus")
-  enterOp('-', "$minus")
-  enterOp(':', "$colon")
-  enterOp('\\', "$bslash")
-  enterOp('?', "$qmark")
-  enterOp('@', "$at")
-
-  /** Replace operator symbols by corresponding "<code>$op_name</code>".
-   *
-   *  @param name ...
-   *  @return     ...
-   */
-  def encode(name: String): String = {
-    var buf: StringBuilder = null
-    val len = name.length()
-    var i = 0
-    while (i < len) {
-      val c = name charAt i
-      if (c < nops && (op2code(c) ne null)) {
-        if (buf eq null) {
-          buf = new StringBuilder()
-          buf.append(name.substring(0, i))
-        }
-        buf.append(op2code(c))
-      /* Handle glyphs that are not valid Java/JVM identifiers */
-      } else if (!Character.isJavaIdentifierPart(c)) {
-	if (buf eq null) {
-	  buf = new StringBuilder()
-	  buf.append(name.substring(0, i))
-	}
-        /* Annoying hack to format a hexadeciaml number with leading
-           zeros -- there does not appear to be any function pre-Java
-           1.5 to do this. */ 
-	buf.append("$u" + Integer.toHexString(c + 0x10000).substring(1).toUpperCase)
-      } else if (buf ne null) {
-        buf.append(c)
-      }
-      i += 1
-    }
-    if (buf eq null) name else buf.toString()
-  }
-
-  /** Replace <code>$op_name</code> by corresponding operator symbol.
-   *
-   *  @param name0 ...
-   *  @return      ...
-   */
-  def decode(name0: String): String = {
-    //System.out.println("decode: " + name);//DEBUG
-    val name = if (name0.endsWith("<init>")) name0.substring(0, name0.length() - ("<init>").length()) + "this"
-               else name0;
-    var buf: StringBuilder = null
-    val len = name.length()
-    var i = 0
-    while (i < len) {
-      var ops: OpCodes = null
-      var unicode = false
-      val c = name charAt i
-      if (c == '$' && i + 2 < len) {
-        val ch1 = name.charAt(i+1)
-        if ('a' <= ch1 && ch1 <= 'z') {
-          val ch2 = name.charAt(i+2)
-          if ('a' <= ch2 && ch2 <= 'z') {
-            ops = code2op((ch1 - 'a') * 26 + ch2 - 'a')
-            while ((ops ne null) && !name.startsWith(ops.code, i)) ops = ops.next
-            if (ops ne null) {
-              if (buf eq null) {
-                buf = new StringBuilder()
-                buf.append(name.substring(0, i))
-              }
-              buf.append(ops.op)
-              i += ops.code.length()
-            }
-            /* Handle the decoding of Unicode glyphs that are 
-             * not valid Java/JVM identifiers */
-          } else if ((len - i) >= 6 && // Check that there are enough characters left
-	             ch1 == 'u' && 
-                     ((Character.isDigit(ch2)) || 
-		     ('A' <= ch2 && ch2 <= 'F'))) {
-            /* Skip past "$u", next four should be hexadecimal */
-            val hex = name.substring(i+2, i+6)
-            try {
-              val str = Integer.parseInt(hex, 16).toChar
-              if (buf eq null) {
-                buf = new StringBuilder()
-                buf.append(name.substring(0, i))
-              }
-              buf.append(str)
-              /* 2 for "$u", 4 for hexadecimal number */
-              i += 6
-              unicode = true
-            } catch {
-              case _:NumberFormatException =>
-                /* <code>hex</code> did not decode to a hexadecimal number, so
-                 * do nothing. */
-            }
-                       }
-        }
-      }
-      /* If we didn't see an opcode or encoded Unicode glyph, and the
-        buffer is non-empty, write the current character and advance
-         one */ 
-      if ((ops eq null) && !unicode) { 
-	if (buf ne null)
-          buf.append(c) 
-	i += 1 
-      } 
-    }
-    //System.out.println("= " + (if (buf == null) name else buf.toString()));//DEBUG
-    if (buf eq null) name else buf.toString()
-  }
-}
diff --git a/src/compiler/scala/tools/nsc/util/NewCharArrayReader.scala b/src/compiler/scala/tools/nsc/util/NewCharArrayReader.scala
deleted file mode 100644
index a6079d3..0000000
--- a/src/compiler/scala/tools/nsc/util/NewCharArrayReader.scala
+++ /dev/null
@@ -1,74 +0,0 @@
-/* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
- * @author  Martin Odersky
- */
-// $Id: NewCharArrayReader.scala 16894 2009-01-13 13:09:41Z cunei $
-
-package scala.tools.nsc.util
-
-import scala.tools.nsc.util.SourceFile.{LF, FF, CR, SU}
-
-class NewCharArrayReader(val buf: RandomAccessSeq[Char], // should not change 
-                       decodeUni: Boolean, error: (Int,String) => Unit) extends Iterator[Char] {
-  private var idx : Int = 0
-  private var isUnicode0 = false
-  def isUnicode = isUnicode0
-  
-  private val bufLength = buf.length
-  def seek(offset : Int) = {
-    assert(offset <= bufLength)
-    idx = offset
-  }
-  def offset = idx
-  def withOffset = new Iterator[(Int,Char)] {
-    def hasNext = NewCharArrayReader.this.hasNext
-    def next = (offset, NewCharArrayReader.this.next)
-  }
-  override def hasNext = { // could be padded
-    if (idx == bufLength - 1) buf(idx) != SU
-    else idx < bufLength
-  }
-  override def next : Char = {
-    isUnicode0 = false
-    if (!hasNext) return SU
-    var ch = buf(idx)
-    idx = idx + 1
-    ch match {
-    case CR if buf.safeIs(idx + 1, LF) => 
-      idx += 1; ch = LF
-    case LF | FF => 
-    case '\\' => 
-      def evenSlashPrefix: Boolean = {
-        var p = idx - 2
-        while (p >= 0 && buf(p) == '\\') p = p - 1;
-        (idx - p) % 2 == 0
-      }
-      def udigit: Int = {
-        val d = digit2int(buf(idx), 16)
-        if (d >= 0) { idx = idx + 1 }
-        else if (error != null) error(idx, "error in unicode escape");
-        d
-      }
-      if (idx < bufLength && buf(idx) == 'u' && decodeUni && evenSlashPrefix) {
-        do {
-          idx = idx + 1; // nextcol = nextcol + 1;
-        } while (idx < bufLength && buf(idx) == 'u');
-        val code = udigit << 12 | udigit << 8 | udigit << 4 | udigit
-        isUnicode0 = true
-        ch = code.asInstanceOf[Char]
-      }
-    case _ => 
-    }
-    ch
-  }
-  def digit2int(ch: Char, base: Int): Int = {
-    if ('0' <= ch && ch <= '9' && ch < '0' + base)
-      ch - '0'
-    else if ('A' <= ch && ch < 'A' + base - 10)
-      ch - 'A' + 10
-    else if ('a' <= ch && ch < 'a' + base - 10)
-      ch - 'a' + 10
-    else
-      -1
-  }
-}
diff --git a/src/compiler/scala/tools/nsc/util/Position.scala b/src/compiler/scala/tools/nsc/util/Position.scala
index e8cc425..393ce68 100644
--- a/src/compiler/scala/tools/nsc/util/Position.scala
+++ b/src/compiler/scala/tools/nsc/util/Position.scala
@@ -1,50 +1,183 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
+ *
  */
-// $Id: Position.scala 16881 2009-01-09 16:28:11Z cunei $
 
-package scala.tools.nsc.util
+package scala.tools.nsc
+package util
 
 object Position {
-  // a static field
-  private val tabInc = 8
+  val tabInc = 8
 }
-
+/** The Position class and its subclasses represent positions of ASTs and symbols.
+ *  Except for NoPosition and FakePos, every position refers to a SourceFile
+ *  and to an offset in the sourcefile (its `point'). For batch compilation,
+ *  that's all. For interactive IDE's there are also RangePositions
+ *  and TransparentPositions. A RangePosition indicates a start and an end
+ *  in addition to its point. TransparentPositions are a subclass of RangePositions.
+ *  Range positions that are not transparent are called opaque.
+ *  Trees with RangePositions need to satisfy the following invariants.
+ *
+ *  INV1: A tree with an offset position never contains a child
+ *        with a range position
+ *  INV2: If the child of a tree with a range position also has a range position,
+ *        then the child's range is contained in the parent's range.
+ *  INV3: Opaque range positions of children of the same node are non-overlapping
+ *        (this means their overlap is at most a single point).
+ *
+ *  The following tests are useful on positions:
+ *
+ *  pos.isDefined     true if position is not a NoPosition nor a FakePosition
+ *  pos.isRange       true if position is a range
+ *  pos.isOpaqueRange true if position is an opaque range
+ *
+ *  The following accessor methods are provided:
+ *
+ *  pos.source        The source file of the position, which must be defined
+ *  pos.point         The offset of the position's point, which must be defined
+ *  pos.start         The start of the position, which must be a range
+ *  pos.end           The end of the position, which must be a range
+ *
+ *  There are also convenience methods, such as
+ *
+ *  pos.startOrPoint
+ *  pos.endOrPoint
+ *  pos.pointOrElse(default)
+ *
+ *  These are less strict about the kind of position on which they can be applied.
+ *
+ *  The following conversion methods are often used:
+ *
+ *  pos.focus           converts a range position to an offset position, keeping its point;
+ *                      returns all other positions unchanged.
+ *  pos.makeTransparent converts an opaque range position into a transparent one.
+ *                      returns all other positions unchanged.
+ */
 trait Position {
-  import Position.tabInc
-  def offset: Option[Int] = None
-  def source: Option[SourceFile] = None
-
-  def line: Option[Int] = 
-    if (offset.isEmpty || source.isEmpty) None
-    else Some(source.get.offsetToLine(offset.get) + 1)
-
-  def column: Option[Int] =
-    if (offset.isEmpty || source.isEmpty)
-      None
-    else {
-      var column = 1
-      // find beginning offset for line
-      val line = source.get.offsetToLine(offset.get)
-      var coffset = source.get.lineToOffset(line)
-      var continue = true
-      while (continue) {
-        if (coffset == offset.getOrElse(-1)) continue = false
-        else if (source.get.asInstanceOf[BatchSourceFile].content(coffset) == '\t') 
-          column = ((column - 1) / tabInc * tabInc) + tabInc + 1
-        else column += 1
-        coffset += 1
-      }
-      Some(column)
-    }
 
-  def lineContent: String = {
-    val line = this.line
-    if (!line.isEmpty) source.get.lineToString(line.get - 1)
+  /** An optional value containing the source file referred to by this position, or
+   *  None if not defined.
+   */
+  def source: SourceFile = throw new UnsupportedOperationException("Position.source")
+
+  /** Is this position neither a NoPosition nor a FakePosition?
+   *  If isDefined is true, offset and source are both defined.
+   */
+  def isDefined: Boolean = false
+
+  /** Is this position a transparent position? */
+  def isTransparent: Boolean = false
+
+  /** Is this position a range position? */
+  def isRange: Boolean = false
+  
+  /** Is this position a non-transparent range position? */
+  def isOpaqueRange: Boolean = false
+
+  /** if opaque range, make this position transparent */
+  def makeTransparent: Position = this
+  
+  /** The start of the position's range, error if not a range position */
+  def start: Int = throw new UnsupportedOperationException("Position.start")
+
+  /** The start of the position's range, or point if not a range position */
+  def startOrPoint: Int = point
+
+  /**  The point (where the ^ is) of the position */
+  def point: Int = throw new UnsupportedOperationException("Position.point")
+
+  /**  The point (where the ^ is) of the position, or else `default' if undefined */
+  def pointOrElse(default: Int): Int = default
+
+  /** The end of the position's range, error if not a range position */
+  def end: Int = throw new UnsupportedOperationException("Position.end")
+
+  /** The end of the position's range, or point if not a range position */
+  def endOrPoint: Int = point
+
+  @deprecated("use point instead")
+  def offset: Option[Int] = if (isDefined) Some(point) else None
+
+  /** The same position with a different start value (if a range) */
+  def withStart(off: Int) = this
+
+  /** The same position with a different end value (if a range) */
+  def withEnd(off: Int) = this
+
+  /** The same position with a different point value (if a range or offset) */
+  def withPoint(off: Int) = this
+
+  /** The same position with a different source value, and its values shifted by given offset */
+  def withSource(source: SourceFile, shift: Int) = this
+
+  /** If this is a range, the union with the other range, with the point of this position.
+   *  Otherwise, this position
+   */
+  def union(pos: Position) = this
+
+  /** If this is a range position, the offset position of its start.
+   *  Otherwise the position itself
+   */
+  def focusStart = this
+  
+  /** If this is a range position, the offset position of its point.
+   *  Otherwise the position itself
+   */
+  def focus = this
+  
+  /** If this is a range position, the offset position of its end.
+   *  Otherwise the position itself
+   */
+  def focusEnd = this
+  
+  /** Does this position include the given position `pos`.
+   *  This holds this is a range position and its range [start..end] 
+   *  is the same or covers the range of the given position.
+   */
+  def includes(pos: Position) = false
+
+  /** Does this position properly include the given position `pos` ("properly" meaning their
+   *  ranges are not the same)?
+   */
+  def properlyIncludes(pos: Position) = 
+    includes(pos) && (start < pos.startOrPoint || pos.endOrPoint < end)
+  
+  /** Does this position precede that position?
+   *  This holds if both positions are defined and the end point of this position
+   *  is not larger than the start point of the given position.
+   */
+  def precedes(pos: Position) = 
+    isDefined && pos.isDefined && endOrPoint <= pos.startOrPoint
+
+  /** Does this position properly precede the given position `pos` ("properly" meaning their ranges
+   *  do not share a common point).
+   */
+  def properlyPrecedes(pos: Position) =
+    isDefined && pos.isDefined && endOrPoint < pos.startOrPoint
+
+  /** Does this position overlap with that position?
+   *  This holds if both positions are ranges and there is an interval of
+   *  non-zero length that is shared by both position ranges.
+   */
+  def overlaps(pos: Position) = 
+    isRange && pos.isRange && 
+    ((pos.start < end && start < pos.end) || (start < pos.end && pos.start < end))
+  
+  /** Does this position cover the same range as that position?
+   *  Holds only if both position are ranges
+   */
+  def sameRange(pos: Position) = 
+    isRange && pos.isRange && start == pos.start && end == pos.end
+
+  def line: Int = throw new UnsupportedOperationException("Position.line")
+
+  def column: Int = throw new UnsupportedOperationException("Position.column")
+
+  def lineContent: String =
+    if (isDefined) source.lineToString(line - 1)
     else "NO_LINE"
-  }
-   
+
   /** Map this position to a position in an original source
    * file.  If the SourceFile is a normal SourceFile, simply
    * return this.
@@ -52,48 +185,89 @@ trait Position {
   def inUltimateSource(source : SourceFile) = 
     if (source == null) this else source.positionInUltimateSource(this)
   
-  def dbgString = {
-    (if (source.isEmpty) "" else "source-" + source.get.path) +
-      (if (line.isEmpty) "" else "line-" + line.get) +
-        (if (offset.isEmpty) "" 
-         else if (offset.get >= source.get.length) "out-of-bounds-" + offset.get 
-         else {
-           val ret = "offset=" + offset.get;
-           var add = "";
-           /*
-           while (offset.get + add.length < source.get.length &&
-                  add.length < 10) add = add + source.get.content(offset.get + add.length());
-           */
-           ret + " c[0..9]=\"" + add + "\"";
-         })
-  }
-  
+  def dbgString = toString
+
+  def show: String = "["+toString+"]"
 }
 
-case object NoPosition extends Position
-case class FakePos(msg: String) extends Position {
-  override def toString=msg
+case object NoPosition extends Position {
+  override def dbgString = toString
 }
 
-case class LinePosition(source0: SourceFile, line0: Int) extends Position {
-  assert(line0 >= 1)
-  override def offset = None
-  override def column = None
-  override def line = Some(line0)
-  override def source = Some(source0)
+case class FakePos(msg: String) extends Position {
+  override def toString = msg
 }
 
-case class OffsetPosition(source0: SourceFile, offset0: Int) extends Position {
-  override def source = Some(source0)
-  override def offset = Some(offset0)
+class OffsetPosition(override val source: SourceFile, override val point: Int) extends Position {
+  override def isDefined = true
+  override def pointOrElse(default: Int): Int = point
+  override def withPoint(off: Int) = new OffsetPosition(source, off)
+  override def withSource(source: SourceFile, shift: Int) = new OffsetPosition(source, point + shift)
+
+  override def line: Int = source.offsetToLine(point) + 1
+  
+  override def column: Int = {
+    var idx = source.lineToOffset(source.offsetToLine(point))
+    var col = 0
+    while (idx != point) {
+      col += (if (source.content(idx) == '\t') Position.tabInc - col % Position.tabInc else 1)
+      idx += 1
+    }
+    col + 1
+  }
+
+  override def union(pos: Position) = 
+    if (pos.isRange) pos else this
+
   override def equals(that : Any) = that match {
-  case that : OffsetPosition => offset0 == that.offset0 && source0.file == that.source0.file 
-  case that => false
+    case that : OffsetPosition => point == that.point && source.file == that.source.file 
+    case that => false
+  }
+  override def hashCode = point * 37 + source.file.hashCode
+
+  override def toString = {
+    val pointmsg = if (point > source.length) "out-of-bounds-" else "offset="
+    "source-%s,line-%s,%s%s".format(source.path, line, pointmsg, point)
   }
-  override def hashCode = offset0 + source0.file.hashCode
+  override def show = "["+point+"]"
 }
 
 /** new for position ranges */
-class RangePosition(source0: SourceFile, offset0: Int, start: Int, end: Int) 
-extends OffsetPosition(source0, offset0)
+class RangePosition(source: SourceFile, override val start: Int, point: Int, override val end: Int) 
+extends OffsetPosition(source, point) {
+  if (start > end) assert(false, "bad position: "+show)
+  override def isRange: Boolean = true
+  override def isOpaqueRange: Boolean = true
+  override def startOrPoint: Int = start
+  override def endOrPoint: Int = end
+  override def withStart(off: Int) = new RangePosition(source, off, point, end)
+  override def withEnd(off: Int) = new RangePosition(source, start, point, off)
+  override def withPoint(off: Int) = new RangePosition(source, start, off, end)
+  override def withSource(source: SourceFile, shift: Int) = new RangePosition(source, start + shift, point + shift, end + shift)
+  override def focusStart = new OffsetPosition(source, start)
+  override def focus = {
+    if (focusCache eq NoPosition) focusCache = new OffsetPosition(source, point)
+    focusCache
+  }
+  override def focusEnd = new OffsetPosition(source, end)
+  override def makeTransparent = new TransparentPosition(source, start, point, end)
+  override def includes(pos: Position) = pos.isDefined && start <= pos.startOrPoint && pos.endOrPoint <= end
+  override def union(pos: Position) = 
+    if (pos.isRange) new RangePosition(source, start min pos.start, point, end max pos.end) else this
+  override def toString = "RangePosition("+source+", "+start+", "+point+", "+end+")"
+  override def show = "["+start+":"+end+"]"
+  private var focusCache: Position = NoPosition
+}
+
+class TransparentPosition(source: SourceFile, start: Int, point: Int, end: Int) extends RangePosition(source, start, point, end) {
+  override def isOpaqueRange: Boolean = false
+  override def isTransparent = true
+  override def makeTransparent = this
+  override def show = "<"+start+":"+end+">"
+}
+
+
+
+  
+
   
diff --git a/src/compiler/scala/tools/nsc/util/RegexCache.scala b/src/compiler/scala/tools/nsc/util/RegexCache.scala
index a14c3f7..e9dc990 100644
--- a/src/compiler/scala/tools/nsc/util/RegexCache.scala
+++ b/src/compiler/scala/tools/nsc/util/RegexCache.scala
@@ -1,10 +1,10 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Lex Spoon
  */
-// $Id: RegexCache.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.tools.nsc.util
+package scala.tools.nsc
+package util
 import java.util.regex.Pattern
 import scala.collection.mutable
 
diff --git a/src/compiler/scala/tools/nsc/util/ScalaClassLoader.scala b/src/compiler/scala/tools/nsc/util/ScalaClassLoader.scala
new file mode 100644
index 0000000..66d92b6
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/util/ScalaClassLoader.scala
@@ -0,0 +1,131 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
+ * @author  Paul Phillips
+ */
+
+package scala.tools.nsc
+package util
+
+import java.lang.{ ClassLoader => JavaClassLoader }
+import java.lang.reflect.{ Constructor, Modifier, Method }
+import java.net.URL
+import ScalaClassLoader._
+import scala.util.control.Exception.{ catching }
+
+trait ScalaClassLoader extends JavaClassLoader {  
+  /** Override to see classloader activity traced */
+  protected def trace: Boolean = false
+  
+  /** Executing an action with this classloader as context classloader */
+  def asContext[T](action: => T): T = {
+    val oldLoader = getContextLoader
+    try {
+      setContextLoader(this)
+      action
+    }
+    finally setContextLoader(oldLoader)
+  }
+  def setAsContext() { setContextLoader(this) }
+  
+  /** Load and link a class with this classloader */  
+  def tryToLoadClass[T <: AnyRef](path: String): Option[Class[T]] = tryClass(path, false)
+  /** Load, link and initialize a class with this classloader */
+  def tryToInitializeClass[T <: AnyRef](path: String): Option[Class[T]] = tryClass(path, true)
+  
+  private def tryBody[T <: AnyRef](body: => Any): Option[T] =
+    catching(classOf[ClassNotFoundException], classOf[SecurityException]) opt body.asInstanceOf[T]
+  
+  private def tryClass[T <: AnyRef](path: String, initialize: Boolean): Option[Class[T]] =
+    catching(classOf[ClassNotFoundException], classOf[SecurityException]) opt 
+      Class.forName(path, initialize, this).asInstanceOf[Class[T]]
+
+  /** Create an instance of a class with this classloader */
+  def create(path: String): AnyRef = {
+    tryToInitializeClass(path) match {
+      case Some(clazz)    => clazz.newInstance()
+      case None           => null
+    }
+  }
+  
+  override def findClass(name: String) = {
+    val result = super.findClass(name)
+    if (trace) println("findClass(%s) = %s".format(name, result))
+    result
+  }
+  
+  override def loadClass(name: String, resolve: Boolean) = {
+    val result = super.loadClass(name, resolve)
+    if (trace) println("loadClass(%s, %s) = %s".format(name, resolve, result))
+    result
+  }
+
+  /** The actual bytes for a class file, or an empty array if it can't be found. */
+  def findBytesForClassName(s: String): Array[Byte] = {
+    val name = s.replaceAll("""\.""", "/") + ".class"
+    val url = this.getResource(name)
+
+    if (url == null) Array()
+    else new io.Streamable.Bytes { def inputStream() = url.openStream } . toByteArray()
+  }
+  
+  /** Run the main method of a class to be loaded by this classloader */
+  def run(objectName: String, arguments: Seq[String]) {
+    val clsToRun = tryToInitializeClass(objectName) getOrElse ( 
+      throw new ClassNotFoundException(objectName)
+    )
+      
+    val method = clsToRun.getMethod("main", classOf[Array[String]])
+    if (!Modifier.isStatic(method.getModifiers))
+      throw new NoSuchMethodException(objectName + ".main is not static")
+
+    asContext(method.invoke(null, Array(arguments.toArray: AnyRef): _*))  // !!! : AnyRef shouldn't be necessary
+  }
+}
+
+object ScalaClassLoader {
+  class URLClassLoader(urls: Seq[URL], parent: JavaClassLoader) 
+      extends java.net.URLClassLoader(urls.toArray, parent) 
+      with ScalaClassLoader {
+
+    private var classloaderURLs = urls.toList
+    
+    /** Override to widen to public */
+    override def addURL(url: URL) = {
+      classloaderURLs +:= url
+      super.addURL(url)
+    }
+    
+    override def toString = urls.mkString("URLClassLoader(\n  ", "\n  ", "\n)\n")
+  }
+  
+  def setContextLoader(cl: JavaClassLoader) = Thread.currentThread.setContextClassLoader(cl)
+  def getContextLoader() = Thread.currentThread.getContextClassLoader()
+  def getSystemLoader(): ScalaClassLoader = new JavaClassLoader(JavaClassLoader.getSystemClassLoader()) with ScalaClassLoader
+  def defaultParentClassLoader() = findExtClassLoader()
+  
+  def fromURLs(urls: Seq[URL], parent: ClassLoader = defaultParentClassLoader()): URLClassLoader =
+    new URLClassLoader(urls.toList, parent)
+  
+  /** True if supplied class exists in supplied path */
+  def classExists(urls: Seq[URL], name: String): Boolean =
+    (fromURLs(urls) tryToLoadClass name).isDefined  
+  
+  // we cannot use the app classloader here or we get what looks to
+  // be classloader deadlock, but if we pass null we bypass the extension
+  // classloader and our extensions, so we search the hierarchy to find
+  // the classloader whose parent is null.  Resolves bug #857.
+  def findExtClassLoader(): JavaClassLoader = {
+    def search(cl: JavaClassLoader): JavaClassLoader = {
+      if (cl == null) null
+      else if (cl.getParent == null) cl
+      else search(cl.getParent)
+    }
+    
+    search(getContextLoader())
+  }
+
+  /** Finding what jar a clazz or instance came from */
+  def origin(x: Any): Option[URL] = originOfClass(x.asInstanceOf[AnyRef].getClass)  
+  def originOfClass(x: Class[_]): Option[URL] =
+    Option(x.getProtectionDomain.getCodeSource) flatMap (x => Option(x.getLocation))
+}
diff --git a/src/compiler/scala/tools/nsc/util/Set.scala b/src/compiler/scala/tools/nsc/util/Set.scala
index 094a30c..337893c 100644
--- a/src/compiler/scala/tools/nsc/util/Set.scala
+++ b/src/compiler/scala/tools/nsc/util/Set.scala
@@ -1,10 +1,10 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: Set.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.tools.nsc.util
+package scala.tools.nsc
+package util
 
 /** A common class for lightweight sets.
  */
@@ -14,11 +14,13 @@ abstract class Set[T <: AnyRef] {
 
   def addEntry(x: T): Unit
 
-  def elements: Iterator[T]
+  def iterator: Iterator[T]	
+  
+  @deprecated("use `iterator' instead") def elements = iterator
 
   def contains(x: T): Boolean =
     findEntry(x) ne null
 
-  def toList = elements.toList
+  def toList = iterator.toList
 
 }
diff --git a/src/compiler/scala/tools/nsc/util/ShowPickled.scala b/src/compiler/scala/tools/nsc/util/ShowPickled.scala
index dcced93..19f8bc0 100644
--- a/src/compiler/scala/tools/nsc/util/ShowPickled.scala
+++ b/src/compiler/scala/tools/nsc/util/ShowPickled.scala
@@ -1,23 +1,59 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id: ShowPickled.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.tools.nsc.util
+package scala.tools
+package nsc
+package util
 
 import java.io.{File, FileInputStream, PrintStream, IOException}
-import java.lang.Integer.toHexString
+import java.lang.Long.toHexString
 import java.lang.Float.intBitsToFloat
 import java.lang.Double.longBitsToDouble
 
-import symtab.{Flags, Names}
-import symtab.classfile.{PickleBuffer, PickleFormat}
+import cmd.program.Simple
+import symtab.{ Flags, Names }
+import scala.reflect.generic.{ PickleBuffer, PickleFormat }
+import interpreter.ByteCode.scalaSigBytesForPath
 
 object ShowPickled extends Names {
-
   import PickleFormat._
 
+  case class PickleBufferEntry(num: Int, startIndex: Int, tag: Int, bytes: Array[Byte]) {
+    def isName = tag == TERMname || tag == TYPEname
+    def hasName = tag match {
+      case TYPEsym | ALIASsym | CLASSsym | MODULEsym | VALsym | EXTref | EXTMODCLASSref => true
+      case _                                                                            => false
+    }
+    def readName = 
+      if (isName) new String(bytes, "UTF-8")
+      else error("%s is no name" format tagName)
+    def nameIndex =
+      if (hasName) readNat(bytes, 0)
+      else error("%s has no name" format tagName)
+      
+    def tagName = tag2string(tag)
+    override def toString = "%d,%d: %s".format(num, startIndex, tagName)
+  }
+  
+  case class PickleBufferEntryList(entries: IndexedSeq[PickleBufferEntry]) {
+    def nameAt(idx: Int) = {
+      val entry = entries(idx)
+      if (entry.isName) entry.readName
+      else if (entry.hasName) entries(entry.nameIndex).readName
+      else "?"
+    }
+  }
+  
+  def makeEntryList(buf: PickleBuffer, index: Array[Int]) = {
+    val entries = buf.toIndexedSeq.zipWithIndex map {
+      case ((tag, data), num) => PickleBufferEntry(num, index(num), tag, data)
+    }
+
+    PickleBufferEntryList(entries)
+  }  
+
   def tag2string(tag: Int): String = tag match {
     case TERMname       => "TERMname"
     case TYPEname       => "TYPEname"
@@ -40,6 +76,8 @@ object ShowPickled extends Names {
     case CLASSINFOtpe   => "CLASSINFOtpe"
     case METHODtpe      => "METHODtpe"
     case POLYtpe        => "POLYtpe"
+    case IMPLICITMETHODtpe => "IMPLICITMETHODtpe"
+    case SUPERtpe       => "SUPERtpe"    
     case LITERALunit    => "LITERALunit"
     case LITERALboolean => "LITERALboolean"
     case LITERALbyte    => "LITERALbyte"
@@ -52,52 +90,110 @@ object ShowPickled extends Names {
     case LITERALstring  => "LITERALstring"
     case LITERALnull    => "LITERALnull"
     case LITERALclass   => "LITERALclass"
-    case ATTRIBUTE      => "ATTRIBUTE"
+    case LITERALenum    => "LITERALenum"
+    case SYMANNOT       => "SYMANNOT"
     case CHILDREN       => "CHILDREN"
-    case PosTYPEsym     => "PosTYPEsym"
-    case PosALIASsym    => "PosALIASsym"
-    case PosCLASSsym    => "PosCLASSsym"
-    case PosMODULEsym   => "PosMODULEsym"
-    case PosVALsym      => "PosVALsym"
+    case ANNOTATEDtpe   => "ANNOTATEDtpe"
+    case ANNOTINFO      => "ANNOTINFO"
+    case ANNOTARGARRAY  => "ANNOTARGARRAY"
+    // case DEBRUIJNINDEXtpe => "DEBRUIJNINDEXtpe"
+    case EXISTENTIALtpe => "EXISTENTIALtpe"
+    case TREE           => "TREE"
+    case MODIFIERS      => "MODIFIERS"
+        
     case _ => "***BAD TAG***(" + tag + ")"
   }
+  
+  /** Extremely regrettably, essentially copied from PickleBuffer.
+   */
+  def readNat(data: Array[Byte], index: Int): Int = {
+    var idx = index
+    var result = 0L
+    var b = 0L
+    do {
+      b = data(idx)
+      idx += 1
+      result = (result << 7) + (b & 0x7f)
+    } while((b & 0x80) != 0L)
+
+    result.toInt
+  }
 
-  def printFile(buf: PickleBuffer, out: PrintStream) {
+  def printFile(buf: PickleBuffer, out: PrintStream): Unit = printFile(buf, out, false)
+  def printFile(buf: PickleBuffer, out: PrintStream, bare: Boolean) {
     out.println("Version " + buf.readNat() + "." + buf.readNat())
     val index = buf.createIndex
+    val entryList = makeEntryList(buf, index)
+    buf.readIndex = 0
+    
+    /** A print wrapper which discards everything if bare is true.
+     */
+    def p(s: String) = if (!bare) out print s
 
     def printNameRef() {
-      val x = buf.readNat()
-      val savedIndex = buf.readIndex
-      buf.readIndex = index(x)
-      val tag = buf.readByte()
-      val len = buf.readNat()
-      out.print(" " + x + "(" + newTermName(buf.bytes, buf.readIndex, len) + ")")
-      buf.readIndex = savedIndex
+      val idx = buf.readNat()
+      val name = entryList nameAt idx
+      val toPrint = if (bare) " " + name else " %s(%s)".format(idx, name)
+      
+      out print toPrint
     }
 
-    def printNat() = out.print(" " + buf.readNat())
+    def printNat() = p(" " + buf.readNat())
+    def printReadNat(x: Int) = p(" " + x)
+      
     def printSymbolRef() = printNat()
     def printTypeRef() = printNat()
     def printConstantRef() = printNat()
+    def printAnnotInfoRef() = printNat()
+    def printConstAnnotArgRef() = printNat()
+    def printAnnotArgRef() = printNat()
 
-    def printSymInfo() {
+    def printSymInfo(end: Int) {
       printNameRef()
       printSymbolRef()
-      val flags = buf.readNat()
-      out.print(" " + toHexString(flags) +
-                "[" + Flags.flagsToString(flags) + "] ")
-      printTypeRef()
+      val pflags = buf.readLongNat()
+      def printFlags(privateWithin: Option[Int]) = {
+        val accessBoundary = (
+          for (idx <- privateWithin) yield {
+            val s = entryList nameAt idx
+            if (bare) s else idx + "(" + s + ")"
+          }
+        )
+        val flagString = {
+          val arg1 = Flags.pickledToRawFlags(pflags)
+          accessBoundary match {
+            case Some(pw) => Flags.flagsToString(arg1, pw)
+            case _        => Flags.flagsToString(arg1)
+          }
+        }
+
+        out.print(" %s[%s]".format(toHexString(pflags), flagString))
+      }
+
+      /** Might be info or privateWithin */  
+      val x = buf.readNat()
+      if (buf.readIndex == end) {
+        printFlags(None)
+        printReadNat(x)
+      }
+      else {
+        printFlags(Some(x))
+        printTypeRef()
+      }
     }
 
+    /** Note: the entries which require some semantic analysis to be correctly
+     *  interpreted are for the most part going to tell you the wrong thing.
+     *  It's not so easy to duplicate the logic applied in the UnPickler.
+     */
     def printEntry(i: Int) {
       buf.readIndex = index(i)
-      out.print(i + "," + buf.readIndex + ": ")
+      p(i + "," + buf.readIndex + ": ")
       val tag = buf.readByte()
       out.print(tag2string(tag))
       val len = buf.readNat()
       val end = len + buf.readIndex
-      out.print(" " + len + ":")
+      p(" " + len + ":")
       tag match {
         case TERMname =>
           out.print(" ")
@@ -108,11 +204,7 @@ object ShowPickled extends Names {
           out.print(newTypeName(buf.bytes, buf.readIndex, len))
           buf.readIndex = end
         case TYPEsym | ALIASsym | CLASSsym | MODULEsym | VALsym =>
-          printSymInfo()
-          if (tag == CLASSsym && (buf.readIndex < end)) printTypeRef()
-        case PosTYPEsym | PosALIASsym | PosCLASSsym | PosMODULEsym | PosVALsym =>
-          printNat() 
-          printSymInfo()
+          printSymInfo(end)
           if (tag == CLASSsym && (buf.readIndex < end)) printTypeRef()
         case EXTref | EXTMODCLASSref =>
           printNameRef()
@@ -131,58 +223,90 @@ object ShowPickled extends Names {
           printSymbolRef(); buf.until(end, printTypeRef)
         case CLASSINFOtpe =>
           printSymbolRef(); buf.until(end, printTypeRef)
-        case METHODtpe =>
+        case METHODtpe | IMPLICITMETHODtpe =>
           printTypeRef(); buf.until(end, printTypeRef)
         case POLYtpe =>
           printTypeRef(); buf.until(end, printSymbolRef)
         case LITERALboolean =>
-          out.print(if (buf.readLong(len) == 0) " false" else " true")
+          out.print(if (buf.readLong(len) == 0L) " false" else " true")
         case LITERALbyte    =>
-          out.print(" " + buf.readLong(len).asInstanceOf[Byte])
+          out.print(" " + buf.readLong(len).toByte)
         case LITERALshort   =>
-          out.print(" " + buf.readLong(len).asInstanceOf[Short])
+          out.print(" " + buf.readLong(len).toShort)
         case LITERALchar    =>
-          out.print(" " + buf.readLong(len).asInstanceOf[Char])
+          out.print(" " + buf.readLong(len).toChar)
         case LITERALint     =>
-          out.print(" " + buf.readLong(len).asInstanceOf[Int])
+          out.print(" " + buf.readLong(len).toInt)
         case LITERALlong    =>
           out.print(" " + buf.readLong(len))
         case LITERALfloat   =>
-          out.print(" " + intBitsToFloat(buf.readLong(len).asInstanceOf[Int]))
+          out.print(" " + intBitsToFloat(buf.readLong(len).toInt))
         case LITERALdouble  =>
           out.print(" " + longBitsToDouble(buf.readLong(len)))
         case LITERALstring  =>
           printNameRef()
+        case LITERALenum    =>
+          printSymbolRef()
         case LITERALnull    =>
           out.print(" <null>")
         case LITERALclass   =>
           printTypeRef()
-        case ATTRIBUTE      =>
-          printSymbolRef(); printTypeRef(); buf.until(end, printConstantRef)
         case CHILDREN       =>
           printSymbolRef(); buf.until(end, printSymbolRef)
+        case SYMANNOT       =>
+          printSymbolRef(); printTypeRef(); buf.until(end, printAnnotArgRef)
+        case ANNOTATEDtpe   =>
+          printTypeRef(); buf.until(end, printAnnotInfoRef);
+        case ANNOTINFO      =>
+          printTypeRef(); buf.until(end, printAnnotArgRef)
+        case ANNOTARGARRAY  =>
+          buf.until(end, printConstAnnotArgRef)
+        case EXISTENTIALtpe =>
+          printTypeRef(); buf.until(end, printSymbolRef)
+          
         case _ =>
       }
       out.println()
-      if (buf.readIndex != end)
-        out.println("BAD ENTRY END: , computed = " + end +
-                    ", factual = " + buf.readIndex)
+      if (buf.readIndex != end) {
+        out.println("BAD ENTRY END: computed = %d, actual = %d, bytes = %s".format(
+          end, buf.readIndex, buf.bytes.slice(index(i), (end max buf.readIndex)).mkString(", ")
+        ))
+      }
     }
 
     for (i <- 0 until index.length) printEntry(i)
   }
+  
+  def fromFile(path: String) = fromBytes(io.File(path).toByteArray)
+  def fromName(name: String) = fromBytes(scalaSigBytesForPath(name) getOrElse Array())
+  def fromBytes(data: => Array[Byte]): Option[PickleBuffer] =
+    try Some(new PickleBuffer(data, 0, data.length))
+    catch { case _: Exception => None }
+  
+  def show(what: String, pickle: PickleBuffer, bare: Boolean) = {
+    Console.println(what + ": ")
+    printFile(pickle, Console.out, bare)
+  }
+
+  private lazy val ShowPickledSpec =
+    Simple(
+      Simple.scalaProgramInfo("showPickled", "Usage: showPickled [--bare] <classname>"),
+      List("--bare" -> "suppress numbers in output"),
+      Nil,
+      null
+    )
 
+  /** Option --bare suppresses numbers so the output can be diffed.
+   */
   def main(args: Array[String]) {
-    val file = new File(args(0))
-    try {
-      val stream = new FileInputStream(file)
-      val data = new Array[Byte](stream.available())
-      stream.read(data)
-      val pickle = new PickleBuffer(data, 0, data.length)
-      printFile(pickle, Console.out)
-    } catch {
-      case ex: IOException =>
-        Console.println("cannot read " + file + ": " + ex.getMessage())
+    val runner = ShowPickledSpec instance args
+    import runner._    
+    
+    residualArgs foreach { arg =>
+      (fromFile(arg) orElse fromName(arg)) match {
+        case Some(pb) => show(arg, pb, parsed isSet "--bare")
+        case _        => Console.println("Cannot read " + arg)
+      }
     }
   }
 }
diff --git a/src/compiler/scala/tools/nsc/util/SourceFile.scala b/src/compiler/scala/tools/nsc/util/SourceFile.scala
index a921adc..f863e57 100644
--- a/src/compiler/scala/tools/nsc/util/SourceFile.scala
+++ b/src/compiler/scala/tools/nsc/util/SourceFile.scala
@@ -1,35 +1,25 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
 
-// $Id: SourceFile.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.tools.nsc.util
-import scala.tools.nsc.io.{AbstractFile, VirtualFile}
+package scala.tools.nsc
+package util
 
-object SourceFile {
-  // Be very careful touching these.
-  // Apparently trivial changes to the way you write these constants 
-  // will cause Scanners.scala to go from a nice efficient switch to 
-  // a ghastly nested if statement which will bring the type checker
-  // to its knees. See ticket #1456
-  final val LF = '\u000A'
-  final val FF = '\u000C'
-  final val CR = '\u000D'
-  final val SU = '\u001A'
+import io.{ AbstractFile, VirtualFile }
+import scala.collection.mutable.ArrayBuffer
+import annotation.tailrec
+import java.util.regex.Pattern
+import java.io.IOException
+import Chars._
 
-  def isLineBreak(c: Int) = c match {
-  case LF|FF|CR|SU => true
-  case _ => false
-  }
-}
 /** abstract base class of a source file used in the compiler */
 abstract class SourceFile {
-  import SourceFile._
-  def content : RandomAccessSeq[Char] // normalized, must end in SU
+  def content : Array[Char]         // normalized, must end in SU
   def file    : AbstractFile
   def isLineBreak(idx : Int) : Boolean
+  def isSelfContained: Boolean
   def length : Int
   def position(offset: Int) : Position = {
     assert(offset < length)
@@ -46,196 +36,110 @@ abstract class SourceFile {
   def dbg(offset: Int) = (new OffsetPosition(this, offset)).dbgString
   def path = file.path
 
-  def beginsWith(offset: Int, text: String): Boolean
-  def skipWhitespace(offset: Int): Int
-  def lineToString(index: Int): String
-  
-  def identifier(pos : Position, compiler  : scala.tools.nsc.Global) : Option[String] = None
-  
-}
-/** a file whose contents do not change over time */
-class BatchSourceFile(val file : AbstractFile, _content : Array[Char]) extends SourceFile {
-  import SourceFile._
-  def this(_file: AbstractFile) = this(_file, _file.toCharArray)
-  def this(sourceName: String, content: Array[Char]) =
-    this(new VirtualFile(sourceName), content)
-  override def equals(that : Any) = that match {
-    case that : BatchSourceFile => file == that.file
-    case _ => false
-  }
-  override def hashCode = file.hashCode
-    
-  val content = _content // don't sweat it...
-  override val length = content.length
+  def beginsWith(offset: Int, text: String): Boolean =
+    (content drop offset) startsWith text
 
-  override def identifier(pos : Position, compiler : scala.tools.nsc.Global) = pos match {
-    case OffsetPosition(source,offset) if source == this && offset != -1 =>  
-      import java.lang.Character
-      var i = offset + 1
-      while (i < content.length && 
-             (compiler.syntaxAnalyzer.isOperatorPart(content(i)) ||
-              compiler.syntaxAnalyzer.isIdentifierPart(content(i)))) i = i + 1
+  def lineToString(index: Int): String =
+    content drop lineToOffset(index) takeWhile (c => !isLineBreakChar(c.toChar)) mkString
     
-      assert(i > offset)
-      if (i <= content.length && offset >= 0)
-        Some(new String(content, offset, i - offset))
-      else None
-  case _ => super.identifier(pos, compiler)
-  }
+  @tailrec
+  final def skipWhitespace(offset: Int): Int =  
+    if (content(offset).isWhitespace) skipWhitespace(offset + 1) else offset
   
-  def isLineBreak(idx: Int) =
-    if (idx >= content.length) false
-    else if (!SourceFile.isLineBreak(content(idx))) false
-    else if (content(idx) == CR && content(idx + 1) == LF) false
-    else true
-  
-  def beginsWith(offset: Int, text: String): Boolean = {
-    var idx = 0
-    while (idx < text.length()) {
-      if (offset + idx >= content.length) return false
-      if (content(offset + idx) != text.charAt(idx)) return false
-      idx += 1
-    }
-    return true
-  }
-  def skipWhitespace(offset: Int): Int =
-    if (content(offset).isWhitespace) skipWhitespace(offset + 1)
-    else offset
+  def identifier(pos: Position, compiler: Global): Option[String] = None  
+}
 
-  def lineToString(index: Int): String = {
-    var offset = lineToOffset(index)
-    val buf = new StringBuilder()
-    while (!isLineBreak(offset) && offset < content.length) {
-      buf.append(content(offset))
-      offset += 1
+object ScriptSourceFile {
+  /** Length of the script header from the given content, if there is one.
+   *  The header begins with "#!" or "::#!" and ends with a line starting
+   *  with "!#" or "::!#".
+   */
+  def headerLength(cs: Array[Char]): Int = {
+    val headerPattern = Pattern.compile("""^(::)?!#.*(\r|\n|\r\n)""", Pattern.MULTILINE)
+    val headerStarts  = List("#!", "::#!")
+    
+    if (headerStarts exists (cs startsWith _)) {
+      val matcher = headerPattern matcher cs.mkString
+      if (matcher.find) matcher.end
+      else throw new IOException("script file does not close its header with !# or ::!#")
     }
-    buf.toString()
+    else 0
   }
-  object line {
-    var index  = 0
-    var offset = 0
-
-    def find(toFind: Int, isIndex: Boolean): Int = {
-      if (toFind == 0) return 0
-      if (!isIndex && (toFind > content.length)) {
-        throw new Error(toFind + " not valid offset in " +
-                        file.name + ":" + content.length)
-      }
-
-      def get(isIndex : Boolean) = if (isIndex) index else offset
-
-      val isBackward = toFind <= get(isIndex)
-      val increment = if (isBackward) -1 else + 1
-      val oneIfBackward = if (isBackward) +1 else 0
-
-      while (true) {
-        if (!isIndex && offset == toFind) return index;
-        if (isBackward && offset <= 0)
-          throw new Error(offset + " " + index + " " + toFind + " " + isIndex);
-        offset = offset + increment
-        if (!isBackward) assert(offset <= content.length);
-
-        if (isLineBreak(offset + (if (isBackward) 0 else -1))) {
-          index = index + increment
-          if (isIndex && index + oneIfBackward == toFind) 
-            return offset + oneIfBackward;
-        }
-      }
-      throw new Error()
-    }
+  def stripHeader(cs: Array[Char]): Array[Char] = cs drop headerLength(cs)
+  
+  def apply(file: AbstractFile, content: Array[Char]) = {
+    val underlying = new BatchSourceFile(file, content)
+    val headerLen = headerLength(content)
+    val stripped = new ScriptSourceFile(underlying, content drop headerLen, headerLen)
+    
+    stripped
   }
-  def offsetToLine(offset: Int): Int = line.find(offset, false)
-  def lineToOffset(index : Int): Int = line.find(index , true)
 }
+import ScriptSourceFile._
 
+class ScriptSourceFile(underlying: BatchSourceFile, content: Array[Char], override val start: Int) extends BatchSourceFile(underlying.file, content) {  
+  override def isSelfContained = false
 
+  override def positionInUltimateSource(pos: Position) =
+    if (!pos.isDefined) super.positionInUltimateSource(pos)
+    else new OffsetPosition(underlying, pos.point + start)
+}
 
-/** A source file composed of multiple other source files.
- *
- *  @version 1.0
- */
-class CompoundSourceFile(
-    name: String,
-    components: List[BatchSourceFile],
-    contents: Array[Char])
-extends BatchSourceFile(name, contents)
-{
-  /** The usual constructor.  Specify a name for the compound file and
-   *  a list of component sources.
-   */
-  def this(name: String, components: BatchSourceFile*) = {
-    this(
-      name,
-      components.toList,
-      Array.concat(components.toList.map(comp => 
-        CompoundSourceFile.stripSU(comp.content).toArray):_*))
+/** a file whose contents do not change over time */
+class BatchSourceFile(val file : AbstractFile, val content: Array[Char]) extends SourceFile {
+  
+  def this(_file: AbstractFile)                 = this(_file, _file.toCharArray)
+  def this(sourceName: String, cs: Seq[Char])   = this(new VirtualFile(sourceName), cs.toArray)
+  def this(file: AbstractFile, cs: Seq[Char])   = this(file, cs.toArray)
+    
+  override def equals(that : Any) = that match {
+    case that : BatchSourceFile => file.path == that.file.path && start == that.start
+    case _ => false
   }
-
-  /** Create an instance with the specified components and a generic name. */
-  def this(components: BatchSourceFile*) =
-    this("(virtual file)", components.toList:_*)
-
-  override def positionInUltimateSource(position: Position) = {
-    if (position.offset.isEmpty) super.positionInUltimateSource(position)
-    else {
-      println("!!!")
-      var off = position.offset.get
-      var compsLeft = components
-      while (compsLeft.head.content.length-1 <= off && !compsLeft.tail.isEmpty) {
-        println("discarding "+compsLeft.head)
-        off = off - compsLeft.head.content.length + 1
-        compsLeft = compsLeft.tail
-      }
-      compsLeft.head.positionInUltimateSource(new OffsetPosition(this, off))
+  override def hashCode = file.path.## + start.##
+  val length = content.length
+  def start = 0
+  def isSelfContained = true
+
+  override def identifier(pos: Position, compiler: Global) = 
+    if (pos.isDefined && pos.source == this && pos.point != -1) {
+      def isOK(c: Char) = isIdentifierPart(c) || isOperatorPart(c)
+      Some(new String(content drop pos.point takeWhile isOK))
+    } else {
+      super.identifier(pos, compiler)
+    }
+  
+  def isLineBreak(idx: Int) =
+    if (idx >= length) false else {
+      val ch = content(idx)
+      // don't identify the CR in CR LF as a line break, since LF will do.
+      if (ch == CR) (idx + 1 == length) || (content(idx + 1) != LF)
+      else isLineBreakChar(ch)
     }
-  }
-}
-
-object CompoundSourceFile {
-  private[util] def stripSU(chars: Array[Char]) =
-    if (chars.length > 0 && chars.last == SourceFile.SU)
-      chars.slice(0, chars.length-1)
-    else
-      chars
-}
 
+  def calculateLineIndices(cs: Array[Char]) = {
+    val buf = new ArrayBuffer[Int]
+    buf += 0
+    for (i <- 0 until cs.length) if (isLineBreak(i)) buf += i + 1
+    buf += cs.length // sentinel, so that findLine below works smoother
+    buf.toArray
+  }  
+  private lazy val lineIndices: Array[Int] = calculateLineIndices(content)  
 
-/** One portion of an underlying file.  The fragment includes
-  * the indeces from the specified start (inclusively) to stop
-  * (not inclusively).
-  */
-class SourceFileFragment(
-    name: String,
-    underlyingFile: BatchSourceFile,
-    start: Int,
-    stop: Int,
-    contents: Array[Char])
-extends BatchSourceFile(name, contents) {
-  def this(name: String, underlyingFile: BatchSourceFile, start: Int, stop: Int) =
-    this(
-      name,
-      underlyingFile,
-      start,
-      stop,
-      { assert(start >= 0)
-        assert(start <= stop)
-        assert(start <= underlyingFile.length)
-        assert(stop <= underlyingFile.length)
-        underlyingFile.content.slice(start, stop).toArray })
+  def lineToOffset(index : Int): Int = lineIndices(index)
 
-  def this(underlyingFile: BatchSourceFile, start: Int, stop: Int) =
-    this(
-      "(fragment of " + underlyingFile.file.name + ")",
-      underlyingFile,
-      start,
-      stop)
+  private var lastLine = 0
 
-  override def positionInUltimateSource(position: Position) = {
-    if (position.offset.isEmpty)
-      super.positionInUltimateSource(position)
-    else {
-      super.positionInUltimateSource(
-      new OffsetPosition(this, position.offset.get))
-    }
+  /** Convert offset to line in this source file
+   *  Lines are numbered from 0
+   */
+  def offsetToLine(offset: Int): Int = {
+    val lines = lineIndices
+    def findLine(lo: Int, hi: Int, mid: Int): Int =
+      if (offset < lines(mid)) findLine(lo, mid - 1, (lo + mid - 1) / 2)
+      else if (offset >= lines(mid + 1)) findLine(mid + 1, hi, (mid + 1 + hi) / 2)
+      else mid
+    lastLine = findLine(0, lines.length, lastLine)
+    lastLine
   }
 }
diff --git a/src/compiler/scala/tools/nsc/util/Statistics.scala b/src/compiler/scala/tools/nsc/util/Statistics.scala
index eaabfc4..604ca4c 100644
--- a/src/compiler/scala/tools/nsc/util/Statistics.scala
+++ b/src/compiler/scala/tools/nsc/util/Statistics.scala
@@ -1,45 +1,279 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
 
-// $Id: Statistics.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.tools.nsc.util
+package scala.tools.nsc
+package util
 
 object Statistics {
-  final val enabled = false
+
+  private var _enabled = false
+
+  def enabled = _enabled
+  def enabled_=(cond: Boolean) = {
+    if (cond && !_enabled) {
+      val test = new Timer()
+      val start = System.nanoTime()
+      var total = 0L
+      for (i <- 1 to 10000) {
+        val time = System.nanoTime()
+        total += System.nanoTime() - time
+      }
+      val total2 = System.nanoTime() - start
+      println("Enabling statistics, measuring overhead = "+
+              total/10000.0+"ns to "+total2/10000.0+"ns per timer")
+      _enabled = true 
+    }
+  }
+
+  var phasesShown = List("parser", "typer", "erasure", "cleanup")
+
+  def currentTime() = 
+    if (_enabled) System.nanoTime() else 0L
+
+  private def showPercent(x: Double, base: Double) = 
+    if (base == 0) "" else " ("+"%2.1f".format(x / base * 100)+"%)"
+
+  def incCounter(c: Counter) {
+    if (_enabled) c.value += 1
+  }
+
+  def incCounter(c: Counter, delta: Int) {
+    if (_enabled) c.value += delta
+  }
+
+  def startCounter(sc: SubCounter): IntPair =
+    if (_enabled) sc.start() else null
+
+  def stopCounter(sc: SubCounter, start: IntPair) {
+    if (_enabled) sc.stop(start)
+  }
+
+  def startTimer(tm: Timer): LongPair = 
+    if (_enabled) tm.start() else null
+
+  def stopTimer(tm: Timer, start: LongPair) {
+    if (_enabled) tm.stop(start)
+  }
+
+  case class IntPair(x: Int, y: Int)
+  case class LongPair(x: Long, y: Long)
+
+  class Counter {
+    var value: Int = 0
+    override def toString = value.toString
+  }
+
+  class SubCounter(c: Counter) {
+    var value: Int = 0
+    def start(): IntPair =
+      if (_enabled) IntPair(value, c.value) else null
+    def stop(prev: IntPair) {
+      if (_enabled) {
+        val IntPair(value0, cvalue0) = prev
+        value = value0 + c.value - cvalue0
+      }
+    }
+    override def toString = 
+      value+showPercent(value, c.value)
+  }
+
+  class Timer {
+    var nanos: Long = 0
+    var timings = 0
+    def start(): LongPair = 
+      if (_enabled) {
+        timings += 1
+        LongPair(nanos, System.nanoTime()) 
+      } else null
+    def stop(prev: LongPair) {
+      if (_enabled) {
+        val LongPair(nanos0, start) = prev
+        nanos = nanos0 + System.nanoTime() - start
+        timings += 1
+      }
+    }
+    override def toString = (timings/2)+" spans, "+nanos.toString+"ns"
+  }
+
+  class ClassCounts extends scala.collection.mutable.HashMap[Class[_], Int] {
+    override def default(key: Class[_]) = 0
+  }
+
+  var nodeByType = new ClassCounts
+
+  var microsByType = new ClassCounts
+  var visitsByType = new ClassCounts
+  var pendingTreeTypes: List[Class[_]] = List() 
+  var typerTime: Long = 0L
+
+  val singletonBaseTypeSeqCount = new Counter
+  val compoundBaseTypeSeqCount = new Counter
+  val typerefBaseTypeSeqCount = new Counter
+  val findMemberCount = new Counter
+  val noMemberCount = new Counter
+  val multMemberCount = new Counter
+  val findMemberNanos = new Timer
+  val asSeenFromCount = new Counter
+  val asSeenFromNanos = new Timer
+  val subtypeCount = new Counter
+  val subtypeNanos = new Timer
+  val sametypeCount = new Counter
+  val rawTypeCount = new Counter
+  val rawTypeFailed = new SubCounter(rawTypeCount)
+  val findMemberFailed = new SubCounter(findMemberCount)
+  val subtypeFailed = new SubCounter(subtypeCount)
+  val rawTypeImpl = new SubCounter(rawTypeCount)
+  val findMemberImpl = new SubCounter(findMemberCount)
+  val subtypeImpl = new SubCounter(subtypeCount)
+  val baseTypeSeqCount = new Counter
+  val baseTypeSeqLenTotal = new Counter
+  val typeSymbolCount = new Counter
+  val classSymbolCount = new Counter
+  val typedApplyCount = new Counter
+  val typedIdentCount = new Counter
+  val typedSelectCount = new Counter
+  val typerNanos = new Timer
+  val classReadNanos = new Timer
+
+  val failedApplyNanos = new Timer
+  val failedOpEqNanos = new Timer
+  val failedSilentNanos = new Timer
+
+  val implicitSearchCount = new Counter
+  val implicitNanos = new Timer
+  val oftypeImplicitHits = new Counter
+  val inscopeImplicitHits = new Counter
+
+  val triedImplicits = new Counter
+  val plausiblyCompatibleImplicits = new Counter
+  val matchingImplicits = new Counter
+  val typedImplicits = new Counter
+  val foundImplicits = new Counter
+
+  val inscopeSucceedNanos = new Timer
+  val inscopeFailNanos = new Timer
+  val oftypeSucceedNanos = new Timer
+  val oftypeFailNanos = new Timer
+  val implicitCacheHits = new Counter
+  val implicitCacheMisses = new Counter
+  val improvesCount = new Counter
+  val subtypeAppInfos = new SubCounter(subtypeCount)
+  val subtypeImprovCount = new SubCounter(subtypeCount)
+  val subtypeETNanos = new Timer
+  val matchesPtNanos = new Timer
+  val ctr1 = new Counter
+  val ctr2 = new Counter
+  val ctr3 = new Counter
+  val ctr4 = new Counter
+  val counter1: SubCounter = new SubCounter(subtypeCount)
+  val counter2: SubCounter = new SubCounter(subtypeCount)
+  val timer1: Timer = new Timer
+  val timer2: Timer = new Timer
 }
 
 abstract class Statistics {
 
+  import Statistics._
+
   val global: Global
   import global._
 
-  def print(phase: Phase) = {
+  def countNodes(tree: Tree, counts: ClassCounts) {
+    for (t <- tree) counts(t.getClass) += 1
+    counts
+  }
+
+  def showRelative(base: Long)(value: Long) = 
+    value+showPercent(value, base)
+
+  def showRelTyper(timer: Timer) = 
+    timer+showPercent(timer.nanos, typerNanos.nanos)
+
+  def showCounts(counts: ClassCounts) = 
+    counts.toSeq.sortWith(_._2 > _._2).map { 
+      case (cls, cnt) => 
+        cls.toString.substring(cls.toString.lastIndexOf("$") + 1)+": "+cnt
+    }
+
+  def print(phase: Phase) = if (phasesShown contains phase.name) {
     inform("*** Cumulative statistics at phase " + phase)
-    inform("#tree nodes  : " + nodeCount)
-    inform("#identifiers : " + analyzer.idcnt)
-    inform("#selections  : " + analyzer.selcnt)
-    inform("#applications: " + analyzer.appcnt)
-    inform("#implicits   : " + analyzer.implcnt)
-    inform("ms implicits : " + analyzer.impltime)
-    inform("#uniquetypes : " + uniqueTypeCount)
-    inform("#symbols     : " + symbolCount)
-    inform("#type symbols: " + typeSymbolCount)
-    inform("#class symbols: " + classSymbolCount)
-    inform("#singleton closures: " + singletonBaseTypeSeqCount)
-    inform("#compound closures : " + compoundBaseTypeSeqCount)
-    inform("#typeref closures  : " + typerefBaseTypeSeqCount)
-    inform("#findMember     : " + findMemberCount)
-    inform("#notfound member: " + noMemberCount)
-    inform("#mulitple member: " + multMemberCount)
-    inform("time findMember: " + findMemberMillis)
-    inform("#norm meth : " + analyzer.normM)
-    inform("#norm poly : " + analyzer.normP)
-    inform("#norm other: " + analyzer.normO)
-    inform("#subtype  : " + subtypeCount)
-    inform("ms subtype: " + subtypeMillis)
-    inform("ms type-flow-analysis: " + analysis.timer.millis)
+    inform("#created tree nodes  : " + nodeCount)
+    inform("#created tree nodes by type: "+showCounts(nodeByType))
+    if (phase.name != "parser") {
+      val counts = new ClassCounts
+      for (u <- currentRun.units; t <- u.body) counts(t.getClass) += 1
+      inform("#retained nodes          : " + counts.values.sum)
+      inform("#retained nodes by type  : " + showCounts(counts))
+      inform("#typechecked identifiers : " + typedIdentCount)
+      inform("#typechecked selections  : " + typedSelectCount)
+      inform("#typechecked applications: " + typedApplyCount)
+      inform("#raw type creations      : " + rawTypeCount)
+      inform("  of which in failed     : " + rawTypeFailed)
+      inform("  of which in implicits  : " + rawTypeImpl)
+      inform("#unique types            : " + uniqueTypeCount)
+      inform("#symbols                 : " + symbolCount)
+      inform("  of which type symbols  : " + typeSymbolCount)
+      inform("  of which class symbols : " + classSymbolCount)
+      inform("#base type seqs          : " + baseTypeSeqCount)
+      inform("avg base type seq length : " + baseTypeSeqLenTotal.value.toFloat / baseTypeSeqCount.value)
+      inform("#singleton base type seqs: " + singletonBaseTypeSeqCount)
+      inform("#compound base type seqs : " + compoundBaseTypeSeqCount)
+      inform("#typeref base type seqs  : " + typerefBaseTypeSeqCount)
+      inform("#findMember ops          : " + findMemberCount)
+      inform("  of which in failed     : " + findMemberFailed)
+      inform("  of which in implicits  : " + findMemberImpl)
+      inform("#notfound member         : " + noMemberCount)
+      inform("#multiple member         : " + multMemberCount)
+      inform("#asSeenFrom ops          : " + asSeenFromCount)
+      inform("#subtype                 : " + subtypeCount)
+      inform("  of which in failed     : " + subtypeFailed)
+      inform("  of which in implicits  : " + subtypeImpl)
+      inform("  of which in app impl   : " + subtypeAppInfos) 
+      inform("  of which in improv     : " + subtypeImprovCount) 
+      inform("#sametype                : " + sametypeCount)
+      inform("ms type-flow-analysis: " + analysis.timer.millis) 
+
+      if (phase.name == "typer") {
+        inform("time spent typechecking  : "+showRelTyper(typerNanos))
+        inform("time classfilereading    : "+showRelTyper(classReadNanos))
+        inform("time spent in implicits  : "+showRelTyper(implicitNanos))
+        inform("    successful in scope  : "+showRelTyper(inscopeSucceedNanos))
+        inform("        failed in scope  : "+showRelTyper(inscopeFailNanos))
+        inform("     successful of type  : "+showRelTyper(oftypeSucceedNanos))
+        inform("         failed of type  : "+showRelTyper(oftypeFailNanos))
+        inform("       assembling parts  : "+showRelTyper(subtypeETNanos))
+        inform("              matchesPT  : "+showRelTyper(matchesPtNanos))
+        inform("implicit cache hits      : "+showRelative(implicitCacheHits.value + implicitCacheMisses.value)(implicitCacheHits.value))
+        inform("time spent in failed     : "+showRelTyper(failedSilentNanos))     
+        inform("       failed apply      : "+showRelTyper(failedApplyNanos))
+        inform("       failed op=        : "+showRelTyper(failedOpEqNanos))     
+        inform("micros by tree node      : "+showCounts(microsByType))
+        inform("#visits by tree node     : "+showCounts(visitsByType))
+        val average = new ClassCounts
+        for (c <- microsByType.keysIterator) average(c) = microsByType(c)/visitsByType(c)
+        inform("avg micros by tree node  : "+showCounts(average))
+        inform("time spent in <:<        : "+showRelTyper(subtypeNanos))
+        inform("time spent in findmember : "+showRelTyper(findMemberNanos))
+        inform("time spent in asSeenFrom : "+showRelTyper(asSeenFromNanos))
+        inform("#implicit searches       : " + implicitSearchCount)
+        inform("#tried, plausible, matching, typed, found implicits: "+triedImplicits+", "+plausiblyCompatibleImplicits+", "+matchingImplicits+", "+typedImplicits+", "+foundImplicits)
+        inform("#implicit improves tests : " + improvesCount)
+        inform("#implicit inscope hits   : " + inscopeImplicitHits)
+        inform("#implicit oftype hits    : " + oftypeImplicitHits)
+      }
+
+      if (ctr1 != null)     inform("#ctr1                    : " + ctr1)
+      if (ctr2 != null)     inform("#ctr2                    : " + ctr2)
+      if (ctr3 != null)     inform("#ctr3                    : " + ctr3)
+      if (ctr4 != null)     inform("#ctr4                    : " + ctr4)
+      if (counter1 != null) inform("#counter1                : " + counter1)
+      if (counter2 != null) inform("#counter2                : " + counter2)
+      if (timer1   != null) inform("#timer1                  : " + timer1)
+      if (timer2   != null) inform("#timer2                  : " + timer2)
+      //for (t <- uniques.iterator) println("unique: "+t)
+    }
   }
 }
diff --git a/src/compiler/scala/tools/nsc/util/TreeSet.scala b/src/compiler/scala/tools/nsc/util/TreeSet.scala
index 40e8890..de9b3cb 100644
--- a/src/compiler/scala/tools/nsc/util/TreeSet.scala
+++ b/src/compiler/scala/tools/nsc/util/TreeSet.scala
@@ -1,10 +1,10 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author  Martin Odersky
  */
-// $Id$
 
-package scala.tools.nsc.util
+package scala.tools.nsc
+package util
 
 /** Sets implemented as binary trees.
  *
@@ -40,14 +40,12 @@ class TreeSet[T >: Null <: AnyRef](less: (T, T) => Boolean) extends Set[T] {
     tree = add(tree)
   }
 
-  def elements = {
-    def elems(t: Tree): Iterator[T] = {
-      var it = Iterator.single(t.elem)
-      if (t.l ne null) it = elems(t.l) append it
-      if (t.r ne null) it = it append elems(t.r)
-      it
+  def iterator = {
+    def elems(t: Tree): Iterator[T] = {      
+      if (t eq null) Iterator.empty
+      else elems(t.l) ++ (Iterator single t.elem) ++ elems(t.r)
     }
-    if (tree eq null) Iterator.empty else elems(tree)
+    elems(tree)
   }
 
   override def toString(): String = {
diff --git a/src/compiler/scala/tools/nsc/util/WorkScheduler.scala b/src/compiler/scala/tools/nsc/util/WorkScheduler.scala
new file mode 100644
index 0000000..6241371
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/util/WorkScheduler.scala
@@ -0,0 +1,79 @@
+package scala.tools.nsc
+package util
+
+import scala.collection.mutable.Queue
+
+class WorkScheduler {
+
+  type Action = () => Unit
+
+  private var todo = new Queue[Action]
+  private var throwables = new Queue[Throwable]
+  private var interruptReqs = new Queue[InterruptReq]
+
+  /** Called from server: block until one of todo list, throwables or interruptReqs is nonempty */
+  def waitForMoreWork() = synchronized {
+    while (todo.isEmpty && throwables.isEmpty && interruptReqs.isEmpty) { wait() } 
+  }
+
+  /** called from Server: test whether one of todo list, throwables, or InterruptReqs is nonempty */
+  def moreWork(): Boolean = synchronized {
+    todo.nonEmpty || throwables.nonEmpty || interruptReqs.nonEmpty
+  }
+
+  /** Called from server: get first action in todo list, and pop it off */
+  def nextWorkItem(): Option[Action] = synchronized {
+    if (todo.isEmpty) None else Some(todo.dequeue()) 
+  }
+
+  /** Called from server: return optional exception posted by client
+   *  Reset to no exception.
+   */
+  def pollThrowable(): Option[Throwable] = synchronized {
+    if (throwables.isEmpty) 
+      None
+    else {
+      val result = Some(throwables.dequeue())
+      if (!throwables.isEmpty)
+        postWorkItem { () => }
+      result
+    }
+  }
+
+  def pollInterrupt(): Option[InterruptReq] = synchronized {
+    if (interruptReqs.isEmpty) None else Some(interruptReqs.dequeue())
+  }
+
+  /** Called from client: have interrupt executed by server and return result */
+  def doQuickly[A](op: () => A): A = {
+    val ir = new InterruptReq {
+      type R = A
+      val todo = op
+    }
+    synchronized {
+      interruptReqs enqueue ir
+      notify()
+    }
+    ir.getResult()
+  }
+
+  /** Called from client: have action executed by server */
+  def postWorkItem(action: Action) = synchronized {
+    todo enqueue action
+    notify()
+  }
+  
+  /** Called from client: cancel all queued actions */
+  def cancelQueued() = synchronized {
+    todo.clear()
+  }
+
+  /** Called from client:
+   *  Require an exception to be thrown on next poll.
+   */
+  def raise(exc: Throwable) = synchronized {
+    throwables enqueue exc
+    postWorkItem { () => }
+  }
+}
+
diff --git a/src/compiler/scala/tools/nsc/util/package.scala b/src/compiler/scala/tools/nsc/util/package.scala
new file mode 100644
index 0000000..c99b2fd
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/util/package.scala
@@ -0,0 +1,29 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
+ * @author Paul Phillips
+ */
+ 
+package scala.tools.nsc
+
+import java.io.{ OutputStream, PrintStream, ByteArrayOutputStream, PrintWriter, StringWriter }
+
+package object util {  
+  /** Apply a function and return the passed value */
+  def returning[T](x: T)(f: T => Unit): T = { f(x) ; x }
+
+  /** Generate a string using a routine that wants to write on a stream. */
+  def stringFromWriter(writer: PrintWriter => Unit): String = {
+    val stringWriter = new StringWriter()
+    val stream = new NewLinePrintWriter(stringWriter)
+    writer(stream)
+    stream.close()
+    stringWriter.toString
+  }
+  def stringFromStream(stream: OutputStream => Unit): String = {
+    val bs = new ByteArrayOutputStream()
+    val ps = new PrintStream(bs)
+    stream(ps)
+    ps.close()
+    bs.toString()
+  }
+}
diff --git a/src/compiler/scala/tools/nsc/util/trace.scala b/src/compiler/scala/tools/nsc/util/trace.scala
new file mode 100644
index 0000000..97b3123
--- /dev/null
+++ b/src/compiler/scala/tools/nsc/util/trace.scala
@@ -0,0 +1,13 @@
+package scala.tools.nsc
+package util
+
+object trace {
+  def apply[T](msg: String)(value: T): T = {
+    println(msg+value)
+    value
+  }
+  def withFun[T, U](msg: String)(value: T)(fun: T => U): T = {
+    println(msg+fun(value))
+    value
+  }
+}
diff --git a/src/compiler/scala/tools/util/AbstractTimer.scala b/src/compiler/scala/tools/util/AbstractTimer.scala
index 3234a6f..b0ea663 100644
--- a/src/compiler/scala/tools/util/AbstractTimer.scala
+++ b/src/compiler/scala/tools/util/AbstractTimer.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: AbstractTimer.scala 16894 2009-01-13 13:09:41Z cunei $
 
 package scala.tools.util
 
@@ -36,7 +35,7 @@ abstract class AbstractTimer {
 
   /** Starts a new timer. */
   def start() {
-    starts += currentTime
+    starts push currentTime
   }
 
   /** Ends the current timer. */
diff --git a/src/compiler/scala/tools/util/ClassPathSettings.scala b/src/compiler/scala/tools/util/ClassPathSettings.scala
new file mode 100644
index 0000000..74b7409
--- /dev/null
+++ b/src/compiler/scala/tools/util/ClassPathSettings.scala
@@ -0,0 +1,32 @@
+/* NSC -- new Scala compiler
+ * Copyright 2006-2010 LAMP/EPFL
+ * @author  Paul Phillips
+ */
+
+package scala.tools
+package util
+
+trait ClassPathSettings {
+  def javabootclasspath: String   // -javabootclasspath
+  def javaextdirs: String         // -javaextdirs
+  def bootclasspath: String       // -bootclasspath
+  def extdirs: String             // -extdirs
+  def classpath: String           // -classpath
+  def sourcepath: String          // -sourcepath
+}
+
+// val debugLogger = {
+//   val f = File("/tmp/path-resolve-log.txt")
+//   if (f.exists) f.truncate()
+//   else f.createFile()
+//   
+//   val res = f.bufferedWriter()
+//   res write ("Started debug log: %s\n".format(new java.util.Date))
+//   res
+// }
+// def log(msg: Any) = {
+//   Console println msg
+//   debugLogger.write(msg.toString + "\n")
+//   debugLogger flush
+// }
+
diff --git a/src/compiler/scala/tools/util/PathResolver.scala b/src/compiler/scala/tools/util/PathResolver.scala
new file mode 100644
index 0000000..bf4fd81
--- /dev/null
+++ b/src/compiler/scala/tools/util/PathResolver.scala
@@ -0,0 +1,253 @@
+/* NSC -- new Scala compiler
+ * Copyright 2006-2010 LAMP/EPFL
+ * @author  Paul Phillips
+ */
+
+package scala.tools
+package util
+
+import java.net.{ URL, MalformedURLException }
+import scala.util.Properties._
+import nsc.{ Settings, GenericRunnerSettings }
+import nsc.util.{ ClassPath, JavaClassPath, ScalaClassLoader }
+import nsc.io.{ File, Directory, Path }
+import ClassPath.{ JavaContext, DefaultJavaContext, join, split }
+import PartialFunction.condOpt
+
+// Loosely based on the draft specification at:
+// https://lampsvn.epfl.ch/trac/scala/wiki/Classpath
+
+object PathResolver {
+  def firstNonEmpty(xs: String*)            = xs find (_ != "") getOrElse ""
+  
+  private def fileOpt(f: Path): Option[String]      = f ifFile (_.path)
+  private def dirOpt(d: Path): Option[String]       = d ifDirectory (_.path)
+  private def expandToPath(p: Path)                 = join(ClassPath.expandPath(p.path, true): _*)
+  private def expandToContents(p: Path)             = join(ClassPath.expandDir(p.path): _*)
+
+  /** Map all classpath elements to absolute paths and reconstruct the classpath.
+    */
+  def makeAbsolute(cp: String) = ClassPath.map(cp, x => Path(x).toAbsolute.path)
+
+  /** pretty print class path */
+  def ppcp(s: String) = split(s) match {
+    case Nil      => ""
+    case Seq(x)   => x
+    case xs       => xs map ("\n" + _) mkString
+  }
+  
+  /** Values found solely by inspecting environment or property variables.
+   */
+  object Environment {
+    private def searchForBootClasspath = {
+      import scala.collection.JavaConversions._
+      System.getProperties find (_._1 endsWith ".boot.class.path") map (_._2) getOrElse ""
+    }
+    private def searchForScalaHome = {
+      for (url <- ScalaClassLoader originOfClass classOf[ScalaObject] ; if url.getProtocol == "file") yield
+        File(url.getFile).parent.path
+    } getOrElse ""
+
+    /** Environment variables which java pays attention to so it
+     *  seems we do as well.
+     */
+    def classPathEnv        =  envOrElse("CLASSPATH", "")
+    def sourcePathEnv       =  envOrElse("SOURCEPATH", "")
+    
+    def javaBootClassPath   = propOrElse("sun.boot.class.path", searchForBootClasspath)
+    def javaExtDirs         = propOrEmpty("java.ext.dirs")
+    def scalaHome           = propOrEmpty("scala.home")
+    def scalaExtDirs        = propOrEmpty("scala.ext.dirs")
+
+    /** The java classpath and whether to use it. */
+    def javaUserClassPath   = propOrElse("java.class.path", "")
+    def useJavaClassPath    = propOrFalse("scala.usejavacp")
+    
+    override def toString = """
+      |object Environment {
+      |  scalaHome          = %s (useJavaClassPath = %s)
+      |  javaBootClassPath  = <%d chars>
+      |  javaExtDirs        = %s
+      |  javaUserClassPath  = %s
+      |  scalaExtDirs       = %s
+      |}""".trim.stripMargin.format(
+        scalaHome, useJavaClassPath,
+        javaBootClassPath.length,
+        ppcp(javaExtDirs),
+        ppcp(javaUserClassPath),
+        ppcp(scalaExtDirs)
+      )
+  }
+  
+  /** Default values based on those in Environment as interpreted according
+   *  to the path resolution specification.
+   */
+  object Defaults {    
+    /* Against my better judgment, giving in to martin here and allowing
+     * CLASSPATH as the default if no -cp is given.  Only if there is no
+     * command line option or environment variable is "." used.
+     */
+    def scalaUserClassPath  = firstNonEmpty(Environment.classPathEnv, ".")
+    def scalaSourcePath     = Environment.sourcePathEnv
+
+    def javaBootClassPath = Environment.javaBootClassPath
+    def javaUserClassPath = Environment.javaUserClassPath
+    def javaExtDirs       = Environment.javaExtDirs
+    def useJavaClassPath  = Environment.useJavaClassPath
+
+    def scalaHome         = Environment.scalaHome
+    def scalaHomeDir      = Directory(scalaHome)
+    def scalaHomeExists   = scalaHomeDir.isDirectory
+    def scalaLibDir       = Directory(scalaHomeDir / "lib")
+    def scalaClassesDir   = Directory(scalaHomeDir / "classes")
+    
+    def scalaLibAsJar     = File(scalaLibDir / "scala-library.jar")
+    def scalaLibAsDir     = Directory(scalaClassesDir / "library")
+    
+    def scalaLibDirFound: Option[Directory] =
+      if (scalaLibAsJar.isFile) Some(scalaLibDir)
+      else if (scalaLibAsDir.isDirectory) Some(scalaClassesDir)
+      else None
+    
+    def scalaLibFound =
+      if (scalaLibAsJar.isFile) scalaLibAsJar.path
+      else if (scalaLibAsDir.isDirectory) scalaLibAsDir.path
+      else ""
+    
+    def scalaBootClassPath  = scalaLibDirFound match {
+      case Some(dir) if scalaHomeExists => join(ClassPath expandDir dir.path: _*)
+      case _                            => ""
+    }
+
+    def scalaExtDirs = Environment.scalaExtDirs
+
+    def scalaPluginPath = (scalaHomeDir / "misc" / "scala-devel" / "plugins").path
+
+    override def toString = """
+      |object Defaults {
+      |  scalaHome            = %s
+      |  javaBootClassPath    = %s
+      |  scalaLibDirFound     = %s
+      |  scalaLibFound        = %s
+      |  scalaBootClassPath   = %s
+      |  scalaPluginPath      = %s
+      |}""".trim.stripMargin.format(
+        scalaHome,
+        ppcp(javaBootClassPath),
+        scalaLibDirFound, scalaLibFound,
+        ppcp(scalaBootClassPath), ppcp(scalaPluginPath)
+      )
+  }
+
+  def fromPathString(path: String, context: JavaContext = DefaultJavaContext): JavaClassPath = {
+    val s = new Settings()
+    s.classpath.value = path
+    new PathResolver(s, context) result
+  }
+  
+  /** With no arguments, show the interesting values in Environment and Defaults.
+   *  If there are arguments, show those in Calculated as if those options had been
+   *  given to a scala runner.
+   */
+  def main(args: Array[String]): Unit = {
+    if (args.isEmpty) {
+      println(Environment)
+      println(Defaults)
+    }
+    else {
+      val settings = new Settings()
+      val rest = settings.processArguments(args.toList, false)._2
+      val pr = new PathResolver(settings)
+      println(" COMMAND: 'scala %s'".format(args.mkString(" ")))
+      println("RESIDUAL: 'scala %s'\n".format(rest.mkString(" ")))
+      pr.result.show
+    }
+  }
+}
+import PathResolver.{ Defaults, Environment, firstNonEmpty, ppcp }
+
+class PathResolver(settings: Settings, context: JavaContext) {
+  def this(settings: Settings) = this(settings, if (settings.inline.value) new JavaContext else DefaultJavaContext)
+  
+  private def cmdLineOrElse(name: String, alt: String) = {
+    (commandLineFor(name) match {
+      case Some("") => None
+      case x        => x
+    }) getOrElse alt
+  }
+
+  private def commandLineFor(s: String): Option[String] = condOpt(s) {
+    case "javabootclasspath"  => settings.javabootclasspath.value
+    case "javaextdirs"        => settings.javaextdirs.value
+    case "bootclasspath"      => settings.bootclasspath.value
+    case "extdirs"            => settings.extdirs.value
+    case "classpath" | "cp"   => settings.classpath.value
+    case "sourcepath"         => settings.sourcepath.value
+  }
+  
+  /** Calculated values based on any given command line options, falling back on
+   *  those in Defaults.
+   */
+  object Calculated {
+    def scalaHome           = Defaults.scalaHome    
+    def useJavaClassPath    = settings.usejavacp.value || Defaults.useJavaClassPath
+    def javaBootClassPath   = cmdLineOrElse("javabootclasspath", Defaults.javaBootClassPath)
+    def javaExtDirs         = cmdLineOrElse("javaextdirs", Defaults.javaExtDirs)
+    def javaUserClassPath   = if (useJavaClassPath) Defaults.javaUserClassPath else ""
+    def scalaBootClassPath  = cmdLineOrElse("bootclasspath", Defaults.scalaBootClassPath)
+    def scalaExtDirs        = cmdLineOrElse("extdirs", Defaults.scalaExtDirs)
+    def userClassPath       = cmdLineOrElse("classpath", Defaults.scalaUserClassPath)
+    def sourcePath          = cmdLineOrElse("sourcepath", Defaults.scalaSourcePath)
+    
+    import context._
+
+    // Assemble the elements!
+    def basis = List(
+      classesInPath(javaBootClassPath),             // 1. The Java bootstrap class path.
+      contentsOfDirsInPath(javaExtDirs),            // 2. The Java extension class path.
+      classesInExpandedPath(javaUserClassPath),     // 3. The Java application class path.
+      classesInPath(scalaBootClassPath),            // 4. The Scala boot class path.
+      contentsOfDirsInPath(scalaExtDirs),           // 5. The Scala extension class path.
+      classesInExpandedPath(userClassPath),         // 6. The Scala application class path.
+      sourcesInPath(sourcePath)                     // 7. The Scala source path.
+    )
+    
+    lazy val containers = basis.flatten.distinct
+
+    override def toString = """
+      |object Calculated {
+      |  scalaHome            = %s
+      |  javaBootClassPath    = %s
+      |  javaExtDirs          = %s
+      |  javaUserClassPath    = %s
+      |    useJavaClassPath   = %s
+      |  scalaBootClassPath   = %s
+      |  scalaExtDirs         = %s
+      |  userClassPath        = %s
+      |  sourcePath           = %s
+      |}""".trim.stripMargin.format(
+        scalaHome,
+        ppcp(javaBootClassPath), ppcp(javaExtDirs), ppcp(javaUserClassPath),
+        useJavaClassPath,
+        ppcp(scalaBootClassPath), ppcp(scalaExtDirs), ppcp(userClassPath),
+        ppcp(sourcePath)
+      )
+  }
+  
+  def containers = Calculated.containers
+
+  lazy val result = {
+    val cp = new JavaClassPath(containers, context)
+    if (settings.Ylogcp.value) {
+      Console.println("Classpath built from " + settings.toConciseString)
+      Console.println("Defaults: " + PathResolver.Defaults)
+      
+      val xs = (Calculated.basis drop 2).flatten.distinct
+      println("After java boot/extdirs classpath has %d entries:" format xs.size)
+      xs foreach (x => println("  " + x))
+    }
+    cp
+  }
+    
+  def asURLs = result.asURLs
+}
diff --git a/src/compiler/scala/tools/util/SocketConnection.scala b/src/compiler/scala/tools/util/SocketConnection.scala
index 72a2629..040f2b2 100644
--- a/src/compiler/scala/tools/util/SocketConnection.scala
+++ b/src/compiler/scala/tools/util/SocketConnection.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: SocketConnection.scala 16894 2009-01-13 13:09:41Z cunei $
 
 package scala.tools.util
 
diff --git a/src/compiler/scala/tools/util/SocketServer.scala b/src/compiler/scala/tools/util/SocketServer.scala
index 7634744..5fb35ec 100644
--- a/src/compiler/scala/tools/util/SocketServer.scala
+++ b/src/compiler/scala/tools/util/SocketServer.scala
@@ -1,21 +1,30 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: SocketServer.scala 16894 2009-01-13 13:09:41Z cunei $
 
 package scala.tools.util
 
-import java.lang.System
-import java.io.PrintWriter
-import java.io.BufferedOutputStream
-import java.io.{BufferedReader, InputStreamReader}
-import java.io.IOException
-import java.net.{ServerSocket, SocketException, SocketTimeoutException}
+import java.io.{ PrintWriter, BufferedOutputStream, BufferedReader, InputStreamReader, IOException }
+import java.net.{ Socket, ServerSocket, SocketException, SocketTimeoutException }
+
+object SocketServer
+{
+  // After 30 idle minutes, politely exit.
+  // Should the port file disappear, and the clients
+  // therefore unable to contact this server instance,
+  // the process will just eventually terminate by itself.
+  val IdleTimeout = 1800000
+  val BufferSize  = 10240
+  
+  def bufferedReader(s: Socket) = new BufferedReader(new InputStreamReader(s.getInputStream()))
+  def bufferedOutput(s: Socket) = new BufferedOutputStream(s.getOutputStream, BufferSize)
+}
+import SocketServer._
 
 /** The abstract class <code>SocketServer</code> implements the server
  *  communication for the fast Scala compiler.
@@ -23,8 +32,8 @@ import java.net.{ServerSocket, SocketException, SocketTimeoutException}
  *  @author  Martin Odersky
  *  @version 1.0
  */
-abstract class SocketServer {
-
+abstract class SocketServer
+{
   def shutDown: Boolean
   def session()
 
@@ -45,49 +54,44 @@ abstract class SocketServer {
   // some cleanup, if any
   def timeout() {}
   
-  val serverSocket = try {
-    new ServerSocket(0)
-  } catch {
-    case e: IOException =>
-      fatal("Could not listen on any port; exiting.")
-  }
+  val serverSocket =
+    try new ServerSocket(0)
+    catch { case e: IOException => fatal("Could not listen on any port; exiting.") }
+    
   val port: Int = serverSocket.getLocalPort()
+  
+  // @todo: this is going to be a prime candidate for ARM
+  def doSession(clientSocket: Socket) = {
+    out = new PrintWriter(clientSocket.getOutputStream(), true)
+    in = bufferedReader(clientSocket)
+    val bufout = bufferedOutput(clientSocket)
+    
+    scala.Console.withOut(bufout) { session() }
+    
+    bufout.close()
+    out.close()
+    in.close()
+  }
 
   def run() {
-    try {
-      // After 30 idle minutes, politely exit.
-      // Should the port file disappear, and the clients
-      // therefore unable to contact this server instance,
-      // the process will just eventually terminate by itself.
-      serverSocket.setSoTimeout(1800000)
-    } catch {
-      case e: SocketException =>
-        fatal("Could not set timeout on port: " + port + "; exiting.")
+    def fail(s: String) = fatal(s format port)
+    
+    try serverSocket setSoTimeout IdleTimeout catch {
+      case e: SocketException => fail("Could not set timeout on port: %d; exiting.")
     }
+    
     try {
       while (!shutDown) {
-        val clientSocket = try {
-          serverSocket.accept()
-        } catch {
-          case e: IOException =>
-            fatal("Accept on port " + port + " failed; exiting.")
-        }
-        
-        out = new PrintWriter(clientSocket.getOutputStream(), true)
-        in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()))
-        val bufout = new BufferedOutputStream(clientSocket.getOutputStream, 10240)
-        
-        scala.Console.withOut(bufout) {
-          session()
-        }
-        bufout.close()
-        out.close()
-        in.close()
+        val clientSocket = try serverSocket.accept() catch {
+          case e: IOException => fail("Accept on port %d failed; exiting.")
+        }        
+        doSession(clientSocket)
         clientSocket.close()
       }
-    } catch {
+    }
+    catch {
       case e: SocketTimeoutException =>
-        warn("Timeout elapsed with no requests from clients on port " + port + "; exiting")
+        warn("Timeout elapsed with no requests from clients on port %d; exiting" format port)
         timeout()
     }
     serverSocket.close()
diff --git a/src/compiler/scala/tools/util/StringOps.scala b/src/compiler/scala/tools/util/StringOps.scala
index 28a74ed..04a6dee 100644
--- a/src/compiler/scala/tools/util/StringOps.scala
+++ b/src/compiler/scala/tools/util/StringOps.scala
@@ -1,23 +1,22 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: StringOps.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.tools.util
+package scala.tools
+package util
 
-/** This objects provides methods to extract elements from
- *  a string according to some defined character separator.
+/** This object provides utility methods to extract elements
+ *  from Strings.
  *
  *  @author Martin Odersky
  *  @version 1.0
  */
 object StringOps {
-
   def decompose(str: String, sep: Char): List[String] = {
     def ws(start: Int): List[String] =
       if (start == str.length) List()
@@ -31,4 +30,19 @@ object StringOps {
   }
 
   def words(str: String): List[String] = decompose(str, ' ')
+  
+  def stripPrefixOpt(str: String, prefix: String): Option[String] = 
+    if (str startsWith prefix) Some(str drop prefix.length)
+    else None
+    
+  def stripSuffixOpt(str: String, suffix: String): Option[String] =
+    if (str endsWith suffix) Some(str dropRight suffix.length)
+    else None
+  
+  def splitWhere(str: String, f: Char => Boolean, doDropIndex: Boolean = false): Option[(String, String)] =
+    splitAt(str, str indexWhere f, doDropIndex)
+
+  def splitAt(str: String, idx: Int, doDropIndex: Boolean = false): Option[(String, String)] =
+    if (idx == -1) None
+    else Some(str take idx, str drop (if (doDropIndex) idx + 1 else idx))
 }
diff --git a/src/compiler/scala/tools/util/UTF8Codec.scala b/src/compiler/scala/tools/util/UTF8Codec.scala
deleted file mode 100644
index 0349eff..0000000
--- a/src/compiler/scala/tools/util/UTF8Codec.scala
+++ /dev/null
@@ -1,82 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: UTF8Codec.scala 16894 2009-01-13 13:09:41Z cunei $
-
-package scala.tools.util
-
-/** This object provides methods for encoding/decoding UTF-8 characters.
- *
- *  @author Martin Odersky
- *  @version 1.0
- */
-object UTF8Codec {
-
-  def encode(src: Array[Char], from: Int, dst: Array[Byte], to: Int, len: Int): Int = {
-    var i = from
-    var j = to
-    val end = from + len
-    while (i < end) {
-      val ch = src(i)
-      i += 1
-      if (ch < 128) {
-        dst(j) = ch.toByte
-        j += 1
-      }
-      else if (ch <= 0x3FF) {
-        dst(j)   = (0xC0 | (ch >> 6)).toByte
-        dst(j+1) = (0x80 | (ch & 0x3F)).toByte
-        j += 2
-      } else {
-        dst(j)   = (0xE0 | (ch >> 12)).toByte
-        dst(j+1) = (0x80 | ((ch >> 6) & 0x3F)).toByte
-        dst(j+2) = (0x80 | (ch & 0x3F)).toByte
-        j += 3
-      }
-    }
-    j
-  }
-
-  def encode(s: String, dst: Array[Byte], to: Int): Int =
-    encode(s.toCharArray(), 0, dst, to, s.length())
-
-  def encode(s: String): Array[Byte] = {
-    val dst = new Array[Byte](s.length() * 3)
-    val len = encode(s, dst, 0)
-    dst.subArray(0, len)
-  }
-
-  def decode(src: Array[Byte], from: Int,
-             dst: Array[Char], to: Int, len: Int): Int =
-  {
-    var i = from
-    var j = to
-    val end = from + len
-    while (i < end) {
-      var b = src(i) & 0xFF
-      i += 1
-      if (b >= 0xE0) {
-        b = ((b & 0x0F) << 12) | (src(i) & 0x3F) << 6
-        b = b | (src(i+1) & 0x3F)
-        i += 2
-      } else if (b >= 0xC0) {
-        b = ((b & 0x1F) << 6) | (src(i) & 0x3F)
-        i += 1
-      }
-      dst(j) = b.toChar
-      j += 1
-    }
-    j
-  }
-
-  def decode(src: Array[Byte], from: Int, len: Int): String = {
-    val cs = new Array[Char](len)
-    new String(cs, 0, decode(src, 0, cs, 0, len))
-  }
-
-}
diff --git a/src/compiler/scala/tools/util/Which.scala b/src/compiler/scala/tools/util/Which.scala
new file mode 100644
index 0000000..7231019
--- /dev/null
+++ b/src/compiler/scala/tools/util/Which.scala
@@ -0,0 +1,39 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
+ * @author  Paul Phillips
+ */
+
+package scala.tools
+package util
+
+import scala.tools.nsc._
+
+/** A tool for identifying which classfile is being used.
+ *  under the given conditions.
+ */
+object Which
+{
+  def main(args: Array[String]): Unit = {
+    val settings = new Settings()
+    val names = settings.processArguments(args.toList, true)._2
+    val global = new Global(settings)
+    val cp = global.classPath
+
+    import cp._
+    
+    for (name <- names) {
+      def fail = println("Could not find: %s".format(name))
+      (cp findClass name) match {
+        case Some(classRep) => classRep.binary match {
+          case Some(f)  => println("%s is %s".format(name, f))
+          case _        => fail
+        }
+        case _ => fail
+      }
+    }
+  }
+}
+
+
+
+
diff --git a/src/continuations/library/scala/util/continuations/ControlContext.scala b/src/continuations/library/scala/util/continuations/ControlContext.scala
new file mode 100644
index 0000000..83d5985
--- /dev/null
+++ b/src/continuations/library/scala/util/continuations/ControlContext.scala
@@ -0,0 +1,161 @@
+// $Id$
+
+package scala.util.continuations
+
+
+class cpsParam[-B,+C] extends StaticAnnotation with TypeConstraint
+
+private class cpsSym[B] extends Annotation // implementation detail
+
+private class cpsSynth extends Annotation // implementation detail
+
+private class cpsPlus extends StaticAnnotation with TypeConstraint // implementation detail
+private class cpsMinus extends Annotation // implementation detail
+
+
+
+ at serializable final class ControlContext[+A,-B,+C](val fun: (A => B, Exception => B) => C, val x: A) {
+  
+  /*  
+    final def map[A1](f: A => A1): ControlContext[A1,B,C] = {
+      new ControlContext((k:(A1 => B)) => fun((x:A) => k(f(x))), null.asInstanceOf[A1])
+    }
+  
+    final def flatMap[A1,B1<:B](f: (A => ControlContext[A1,B1,B])): ControlContext[A1,B1,C] = {
+      new ControlContext((k:(A1 => B1)) => fun((x:A) => f(x).fun(k)))
+    }
+  */
+
+
+  @noinline final def map[A1](f: A => A1): ControlContext[A1,B,C] = {
+    if (fun eq null)
+      try {
+        new ControlContext(null, f(x)) // TODO: only alloc if f(x) != x
+      } catch {
+        case ex: Exception => 
+          new ControlContext((k: A1 => B, thr: Exception => B) => thr(ex).asInstanceOf[C], null.asInstanceOf[A1])
+      }
+    else
+      new ControlContext({ (k: A1 => B, thr: Exception => B) =>
+        fun( { (x:A) =>
+          var done = false
+          try {
+            val res = f(x)
+            done = true
+            k(res)
+          } catch {
+            case ex: Exception if !done =>
+              thr(ex)
+          }
+        }, thr)
+      }, null.asInstanceOf[A1])
+  }
+  
+
+  // it would be nice if @inline would turn the trivial path into a tail call.
+  // unfortunately it doesn't, so we do it ourselves in SelectiveCPSTransform
+  
+  @noinline final def flatMap[A1,B1,C1<:B](f: (A => ControlContext[A1,B1,C1])): ControlContext[A1,B1,C] = {
+    if (fun eq null)
+      try {
+        f(x).asInstanceOf[ControlContext[A1,B1,C]]
+      } catch {
+        case ex: Exception => 
+          new ControlContext((k: A1 => B1, thr: Exception => B1) => thr(ex).asInstanceOf[C], null.asInstanceOf[A1])
+      }
+    else
+      new ControlContext({ (k: A1 => B1, thr: Exception => B1) =>
+        fun( { (x:A) =>
+          var done = false
+          try {
+            val ctxR = f(x)
+            done = true
+            val res: C1 = ctxR.foreachFull(k, thr) // => B1
+            res
+          } catch {
+            case ex: Exception if !done =>
+              thr(ex).asInstanceOf[B] // => B NOTE: in general this is unsafe! 
+          }                           // However, the plugin will not generate offending code
+        }, thr.asInstanceOf[Exception=>B]) // => B
+      }, null.asInstanceOf[A1])
+  }
+
+  final def foreach(f: A => B) = foreachFull(f, throw _)
+  
+  def foreachFull(f: A => B, g: Exception => B): C = {
+    if (fun eq null)
+      f(x).asInstanceOf[C]
+    else
+      fun(f, g)
+  }
+  
+
+  final def isTrivial = fun eq null
+  final def getTrivialValue = x.asInstanceOf[A]
+
+  // need filter or other functions?
+
+  final def flatMapCatch[A1>:A,B1<:B,C1>:C<:B1](pf: PartialFunction[Exception, ControlContext[A1,B1,C1]]): ControlContext[A1,B1,C1] = {
+    if (fun eq null)
+      this
+    else {
+      val fun1 = (ret1: A1 => B1, thr1: Exception => B1) => {
+        val thr: Exception => B1 = { t: Exception =>
+          var captureExceptions = true
+          try {
+            if (pf.isDefinedAt(t)) {
+              val cc1 = pf(t)
+              captureExceptions = false
+              cc1.foreachFull(ret1, thr1) // Throw => B
+            } else {
+              captureExceptions = false
+              thr1(t) // Throw => B1
+            }
+          } catch {
+            case t1: Exception if captureExceptions => thr1(t1) // => E2
+          }
+        }
+        fun(ret1, thr)// fun(ret1, thr)  // => B
+      }
+      new ControlContext(fun1, null.asInstanceOf[A1])
+    }
+  }
+
+  final def mapFinally(f: () => Unit): ControlContext[A,B,C] = {
+    if (fun eq null) {
+      try {
+        f()
+        this
+      } catch {
+        case ex: Exception => 
+          new ControlContext((k: A => B, thr: Exception => B) => thr(ex).asInstanceOf[C], null.asInstanceOf[A])
+      }
+    } else {
+      val fun1 = (ret1: A => B, thr1: Exception => B) => {
+        val ret: A => B = { x: A =>
+          var captureExceptions = true
+          try {
+            f()
+            captureExceptions = false
+            ret1(x)
+          } catch {
+            case t1: Exception if captureExceptions => thr1(t1)
+          }
+        }
+        val thr: Exception => B = { t: Exception =>
+          var captureExceptions = true
+          try {
+            f()
+            captureExceptions = false
+            thr1(t)
+          } catch {
+            case t1: Exception if captureExceptions => thr1(t1)
+          }
+        }
+        fun(ret, thr1)
+      }
+      new ControlContext(fun1, null.asInstanceOf[A])
+    }
+  }
+  
+}
diff --git a/src/continuations/library/scala/util/continuations/package.scala b/src/continuations/library/scala/util/continuations/package.scala
new file mode 100644
index 0000000..1f87274
--- /dev/null
+++ b/src/continuations/library/scala/util/continuations/package.scala
@@ -0,0 +1,65 @@
+// $Id$
+
+
+// TODO: scaladoc
+
+package scala.util
+
+package object continuations {
+
+  type cps[A] = cpsParam[A,A]
+  
+  type suspendable = cps[Unit]
+  
+
+  def shift[A,B,C](fun: (A => B) => C): A @cpsParam[B,C] = {
+    throw new NoSuchMethodException("this code has to be compiled with the Scala continuations plugin enabled")
+  }
+
+  def reset[A,C](ctx: =>(A @cpsParam[A,C])): C = {
+    val ctxR = reify[A,A,C](ctx)
+    if (ctxR.isTrivial)
+      ctxR.getTrivialValue.asInstanceOf[C]
+    else
+      ctxR.foreach((x:A) => x)
+  }
+
+  def reset0[A](ctx: =>(A @cpsParam[A,A])): A = reset(ctx)
+
+  def run[A](ctx: =>(Any @cpsParam[Unit,A])): A = {
+    val ctxR = reify[Any,Unit,A](ctx)
+    if (ctxR.isTrivial)
+      ctxR.getTrivialValue.asInstanceOf[A]
+    else
+      ctxR.foreach((x:Any) => ())
+  }
+
+  
+  // methods below are primarily implementation details and are not
+  // needed frequently in client code
+
+  def shiftUnit0[A,B](x: A): A @cpsParam[B,B] = {
+    shiftUnit[A,B,B](x)
+  }
+
+  def shiftUnit[A,B,C>:B](x: A): A @cpsParam[B,C] = {
+    throw new NoSuchMethodException("this code has to be compiled with the Scala continuations plugin enabled")
+  }
+
+  def reify[A,B,C](ctx: =>(A @cpsParam[B,C])): ControlContext[A,B,C] = {
+    throw new NoSuchMethodException("this code has to be compiled with the Scala continuations plugin enabled")
+  }  
+
+  def shiftUnitR[A,B](x: A): ControlContext[A,B,B] = {
+    new ControlContext(null, x)
+  }
+
+  def shiftR[A,B,C](fun: (A => B) => C): ControlContext[A,B,C] = {
+    new ControlContext((f:A=>B,g:Exception=>B) => fun(f), null.asInstanceOf[A])
+  }
+
+  def reifyR[A,B,C](ctx: => ControlContext[A,B,C]): ControlContext[A,B,C] = {
+    ctx
+  }
+
+}
diff --git a/src/continuations/plugin/scala/tools/selectivecps/CPSAnnotationChecker.scala b/src/continuations/plugin/scala/tools/selectivecps/CPSAnnotationChecker.scala
new file mode 100644
index 0000000..021c694
--- /dev/null
+++ b/src/continuations/plugin/scala/tools/selectivecps/CPSAnnotationChecker.scala
@@ -0,0 +1,462 @@
+// $Id$
+
+package scala.tools.selectivecps
+
+import scala.tools.nsc.Global
+
+import scala.collection.mutable.{Map, HashMap}
+
+import java.io.{StringWriter, PrintWriter}
+
+abstract class CPSAnnotationChecker extends CPSUtils {
+  val global: Global
+  import global._
+  import definitions._
+
+  //override val verbose = true
+
+  /** 
+   *  Checks whether @cps annotations conform
+   */
+  object checker extends AnnotationChecker {
+
+    /** Check annotations to decide whether tpe1 <:< tpe2 */
+    def annotationsConform(tpe1: Type, tpe2: Type): Boolean = {
+      if (!cpsEnabled) return true
+
+      vprintln("check annotations: " + tpe1 + " <:< " + tpe2)
+
+      // Nothing is least element, but Any is not the greatest
+      if (tpe1.typeSymbol eq NothingClass)
+        return true
+      
+      val annots1 = filterAttribs(tpe1,MarkerCPSTypes)
+      val annots2 = filterAttribs(tpe2,MarkerCPSTypes)
+      
+      // @plus and @minus should only occur at the left, and never together
+      // TODO: insert check
+      val adaptPlusAnnots1 = filterAttribs(tpe1,MarkerCPSAdaptPlus)
+      val adaptMinusAnnots1 = filterAttribs(tpe1,MarkerCPSAdaptMinus)
+      
+      // @minus @cps is the same as no annotations
+      if (!adaptMinusAnnots1.isEmpty)
+        return annots2.isEmpty
+
+      // to handle answer type modification, we must make @plus <:< @cps
+      if (!adaptPlusAnnots1.isEmpty && annots1.isEmpty)
+        return true
+
+      // @plus @cps will fall through and compare the @cps type args
+
+      // @cps parameters must match exactly
+      if ((annots1 corresponds annots2) { _.atp <:< _.atp })
+        return true
+
+      false
+    }
+    
+
+    /** Refine the computed least upper bound of a list of types. 
+     *  All this should do is add annotations. */
+    override def annotationsLub(tpe: Type, ts: List[Type]): Type = {
+      if (!cpsEnabled) return tpe
+      
+      val annots1 = filterAttribs(tpe, MarkerCPSTypes)
+      val annots2 = ts flatMap (filterAttribs(_, MarkerCPSTypes))
+      
+      if (annots2.nonEmpty) {
+        val cpsLub = AnnotationInfo(global.lub(annots1:::annots2 map (_.atp)), Nil, Nil)
+        val tpe1 = if (annots1.nonEmpty) removeAttribs(tpe, MarkerCPSTypes) else tpe
+        tpe1.withAnnotation(cpsLub)
+      } else tpe
+    }
+
+    /** Refine the bounds on type parameters to the given type arguments. */
+    override def adaptBoundsToAnnotations(bounds: List[TypeBounds], tparams: List[Symbol], targs: List[Type]): List[TypeBounds] = {
+      if (!cpsEnabled) return bounds
+
+      val anyAtCPS = AnnotationInfo(appliedType(MarkerCPSTypes.tpe, List(NothingClass.tpe, AnyClass.tpe)), Nil, Nil)
+      if (isFunctionType(tparams.head.owner.tpe) || tparams.head.owner == PartialFunctionClass) {
+        vprintln("function bound: " + tparams.head.owner.tpe + "/"+bounds+"/"+targs)
+        if (targs.last.hasAnnotation(MarkerCPSTypes))
+          bounds.reverse match {
+            case res::b if !res.hi.hasAnnotation(MarkerCPSTypes) => 
+              (TypeBounds(res.lo, res.hi.withAnnotation(anyAtCPS))::b).reverse
+            case _ => bounds
+          }
+        else
+          bounds
+      } else if (tparams.head.owner == ByNameParamClass) {
+        vprintln("byname bound: " + tparams.head.owner.tpe + "/"+bounds+"/"+targs)
+        if (targs.head.hasAnnotation(MarkerCPSTypes) && !bounds.head.hi.hasAnnotation(MarkerCPSTypes))
+          TypeBounds(bounds.head.lo, bounds.head.hi.withAnnotation(anyAtCPS))::Nil
+        else bounds
+      } else
+        bounds
+    }
+
+
+    override def canAdaptAnnotations(tree: Tree, mode: Int, pt: Type): Boolean = {
+      if (!cpsEnabled) return false
+      vprintln("can adapt annotations? " + tree + " / " + tree.tpe + " / " + Integer.toHexString(mode) + " / " + pt)
+
+      val annots1 = filterAttribs(tree.tpe,MarkerCPSTypes)
+      val annots2 = filterAttribs(pt,MarkerCPSTypes)
+      
+      if ((mode & global.analyzer.PATTERNmode) != 0) {
+        //println("can adapt pattern annotations? " + tree + " / " + tree.tpe + " / " + Integer.toHexString(mode) + " / " + pt)
+        if (!annots1.isEmpty) {
+          return true
+        }
+      }
+
+/*
+      // not precise enough -- still relying on addAnnotations to remove things from ValDef symbols
+      if ((mode & global.analyzer.TYPEmode) != 0 && (mode & global.analyzer.BYVALmode) != 0) {
+        if (!annots1.isEmpty) {
+          return true
+        }
+      }
+*/
+
+/*
+      this interferes with overloading resolution
+      if ((mode & global.analyzer.BYVALmode) != 0 && tree.tpe <:< pt) {
+        vprintln("already compatible, can't adapt further")
+        return false
+      }
+*/
+      if ((mode & global.analyzer.EXPRmode) != 0) {
+        if ((annots1 corresponds annots2) { case (a1,a2) => a1.atp <:< a2.atp }) {
+          vprintln("already same, can't adapt further")
+          return false
+        }
+
+        if (annots1.isEmpty && !annots2.isEmpty && ((mode & global.analyzer.BYVALmode) == 0)) {
+          //println("can adapt annotations? " + tree + " / " + tree.tpe + " / " + Integer.toHexString(mode) + " / " + pt)
+          val adapt = AnnotationInfo(MarkerCPSAdaptPlus.tpe, Nil, Nil)
+          if (!tree.tpe.annotations.contains(adapt)) {
+  //          val base = tree.tpe <:< removeAllCPSAnnotations(pt)
+  //          val known = global.analyzer.isFullyDefined(pt)
+  //          println(same + "/" + base + "/" + known)
+            //val same = annots2 forall { case AnnotationInfo(atp: TypeRef, _, _) => atp.typeArgs(0) =:= atp.typeArgs(1) }
+            // TBD: use same or not?
+            //if (same) {
+              vprintln("yes we can!! (unit)")
+              return true
+            //}
+          }
+        } else if (!annots1.isEmpty && ((mode & global.analyzer.BYVALmode) != 0)) {
+          if (!tree.tpe.hasAnnotation(MarkerCPSAdaptMinus)) {
+            vprintln("yes we can!! (byval)")
+            return true
+          }
+        }
+      }
+      false
+    }
+    
+    
+    override def adaptAnnotations(tree: Tree, mode: Int, pt: Type): Tree = {
+      if (!cpsEnabled) return tree
+      
+      vprintln("adapt annotations " + tree + " / " + tree.tpe + " / " + Integer.toHexString(mode) + " / " + pt)
+
+      val annots1 = filterAttribs(tree.tpe,MarkerCPSTypes)
+      val annots2 = filterAttribs(pt,MarkerCPSTypes)
+
+      if ((mode & global.analyzer.PATTERNmode) != 0) {
+        if (!annots1.isEmpty) {
+          return tree.setType(removeAllCPSAnnotations(tree.tpe))
+        }
+      }
+
+/*
+      // doesn't work correctly -- still relying on addAnnotations to remove things from ValDef symbols
+      if ((mode & global.analyzer.TYPEmode) != 0 && (mode & global.analyzer.BYVALmode) != 0) {
+        if (!annots1.isEmpty) {
+          println("removing annotation from " + tree + "/" + tree.tpe)
+          val s = tree.setType(removeAllCPSAnnotations(tree.tpe))
+          println(s)
+          s
+        }
+      }
+*/
+      
+      if ((mode & global.analyzer.EXPRmode) != 0) {
+        if (annots1.isEmpty && !annots2.isEmpty && ((mode & global.analyzer.BYVALmode) == 0)) { // shiftUnit
+          // add a marker annotation that will make tree.tpe behave as pt, subtyping wise
+          // tree will look like having any possible annotation
+          //println("adapt annotations " + tree + " / " + tree.tpe + " / " + Integer.toHexString(mode) + " / " + pt)
+        
+          val adapt = AnnotationInfo(MarkerCPSAdaptPlus.tpe, Nil, Nil)
+          //val same = annots2 forall { case AnnotationInfo(atp: TypeRef, _, _) => atp.typeArgs(0) =:= atp.typeArgs(1) }
+          // TBD: use same or not? see infer0.scala/infer1.scala
+
+          // CAVEAT:
+          //  for monomorphic answer types we want to have @plus @cps (for better checking)
+          //  for answer type modification we want to have only @plus (because actual answer type may differ from pt)
+      
+          //val known = global.analyzer.isFullyDefined(pt)
+
+          if (/*same &&*/ !tree.tpe.annotations.contains(adapt)) {
+            //if (known)
+              return tree.setType(tree.tpe.withAnnotations(adapt::annots2)) // needed for #1807
+            //else
+            //  return tree.setType(tree.tpe.withAnnotations(adapt::Nil))
+          }
+          tree
+        } else if (!annots1.isEmpty && ((mode & global.analyzer.BYVALmode) != 0)) { // dropping annotation
+          // add a marker annotation that will make tree.tpe behave as pt, subtyping wise
+          // tree will look like having no annotation
+          if (!tree.tpe.hasAnnotation(MarkerCPSAdaptMinus)) {
+            val adapt = AnnotationInfo(MarkerCPSAdaptMinus.tpe, Nil, Nil)
+            return tree.setType(tree.tpe.withAnnotations(adapt::Nil))
+          }
+        }
+      }
+      tree
+    }
+
+
+    def updateAttributesFromChildren(tpe: Type, childAnnots: List[AnnotationInfo], byName: List[Tree]): Type = {
+      tpe match {
+        // Would need to push annots into each alternative of overloaded type
+        // But we can't, since alternatives aren't types but symbols, which we
+        // can't change (we'd be affecting symbols globally)
+        /*
+        case OverloadedType(pre, alts) =>
+          OverloadedType(pre, alts.map((sym: Symbol) => updateAttributes(pre.memberType(sym), annots)))
+        */
+        case _ =>
+          assert(childAnnots forall (_.atp.typeSymbol == MarkerCPSTypes), childAnnots)
+          /*
+            [] + [] = []
+            plus + [] = plus
+            cps + [] = cps
+            plus cps + [] = plus cps
+            minus cps + [] = minus cp
+            synth cps + [] = synth cps // <- synth on left - does it happen?
+
+            [] + cps = cps
+            plus + cps = synth cps
+            cps + cps = cps! <- lin
+            plus cps + cps = synth cps! <- unify
+            minus cps + cps = minus cps! <- lin
+            synth cps + cps = synth cps! <- unify
+          */
+          
+          val plus = tpe.hasAnnotation(MarkerCPSAdaptPlus) || (tpe.hasAnnotation(MarkerCPSTypes) && 
+                        byName.nonEmpty && byName.forall(_.tpe.hasAnnotation(MarkerCPSAdaptPlus)))
+          
+          // move @plus annotations outward from by-name children
+          if (childAnnots.isEmpty) {
+            if (plus) { // @plus or @plus @cps
+              for (t <- byName) {
+                //println("removeAnnotation " + t + " / " + t.tpe)
+                t.setType(removeAttribs(t.tpe, MarkerCPSAdaptPlus, MarkerCPSTypes))
+              }
+              return tpe.withAnnotation(AnnotationInfo(MarkerCPSAdaptPlus.tpe, Nil, Nil))
+            } else
+              return tpe
+          }
+
+          val annots1 = filterAttribs(tpe, MarkerCPSTypes)
+
+          if (annots1.isEmpty) { // nothing or @plus
+            val synth = MarkerCPSSynth.tpe
+            val annots2 = List(linearize(childAnnots))
+            removeAttribs(tpe,MarkerCPSAdaptPlus).withAnnotations(AnnotationInfo(synth, Nil, Nil)::annots2)
+          } else {
+            val annot1 = single(annots1)
+            if (plus) { // @plus @cps
+              val synth = AnnotationInfo(MarkerCPSSynth.tpe, Nil, Nil)
+              val annot2 = linearize(childAnnots)
+              if (!(annot2.atp <:< annot1.atp))
+                throw new TypeError(annot2 + " is not a subtype of " + annot1)
+              val res = removeAttribs(tpe, MarkerCPSAdaptPlus, MarkerCPSTypes).withAnnotations(List(synth, annot2))
+              for (t <- byName) {
+                //println("removeAnnotation " + t + " / " + t.tpe)
+                t.setType(removeAttribs(t.tpe, MarkerCPSAdaptPlus, MarkerCPSTypes))
+              }
+              res
+            } else if (tpe.hasAnnotation(MarkerCPSSynth)) { // @synth @cps
+              val annot2 = linearize(childAnnots)
+              if (!(annot2.atp <:< annot1.atp))
+                throw new TypeError(annot2 + " is not a subtype of " + annot1)
+              removeAttribs(tpe, MarkerCPSTypes).withAnnotation(annot2)
+            } else { // @cps
+              removeAttribs(tpe, MarkerCPSTypes).withAnnotation(linearize(childAnnots:::annots1))
+            }
+          }
+      }
+    }
+
+
+
+
+
+    def transArgList(fun: Tree, args: List[Tree]): List[List[Tree]] = {
+      val formals = fun.tpe.paramTypes
+      val overshoot = args.length - formals.length
+    
+      for ((a,tp) <- args.zip(formals ::: List.fill(overshoot)(NoType))) yield {
+        tp match {
+          case TypeRef(_, sym, List(elemtp)) if sym == ByNameParamClass =>
+            Nil // TODO: check conformance??
+          case _ =>
+            List(a)
+        }
+      }
+    }
+
+
+    def transStms(stms: List[Tree]): List[Tree] = stms match {
+      case ValDef(mods, name, tpt, rhs)::xs =>
+        rhs::transStms(xs)
+      case Assign(lhs, rhs)::xs =>
+        rhs::transStms(xs)
+      case x::xs =>
+        x::transStms(xs)
+      case Nil =>
+        Nil
+    }
+    
+    def single(xs: List[AnnotationInfo]) = xs match {
+      case List(x) => x
+      case _ =>
+        global.error("not a single cps annotation: " + xs)// FIXME: error message
+        xs(0)
+    }
+
+    def transChildrenInOrder(tree: Tree, tpe: Type, childTrees: List[Tree], byName: List[Tree]) = {
+      val children = childTrees.flatMap { t =>
+        if (t.tpe eq null) Nil else {
+          val types = filterAttribs(t.tpe, MarkerCPSTypes)
+          // TODO: check that it has been adapted and if so correctly
+          if (types.isEmpty) Nil else List(single(types))
+        }
+      }
+                            
+      val newtpe = updateAttributesFromChildren(tpe, children, byName)
+    
+      if (!newtpe.annotations.isEmpty)
+        vprintln("[checker] inferred " + tree + " / " + tpe + " ===> "+ newtpe)
+      
+      newtpe
+    }
+
+    /** Modify the type that has thus far been inferred
+     *  for a tree.  All this should do is add annotations. */
+
+    override def addAnnotations(tree: Tree, tpe: Type): Type = {
+      if (!cpsEnabled) { 
+        if (tpe.annotations.nonEmpty && tpe.hasAnnotation(MarkerCPSTypes))
+          global.reporter.error(tree.pos, "this code must be compiled with the Scala continuations plugin enabled")
+        return tpe 
+      } 
+
+//      if (tree.tpe.hasAnnotation(MarkerCPSAdaptPlus))
+//        println("addAnnotation " + tree + "/" + tpe)
+
+      tree match {
+
+        case Apply(fun @ Select(qual, name), args) if (fun.tpe ne null) && !fun.tpe.isErroneous =>
+
+          // HACK: With overloaded methods, fun will never get annotated. This is because
+          // the 'overloaded' type gets annotated, but not the alternatives (among which
+          // fun's type is chosen)
+
+          vprintln("[checker] checking select apply " + tree + "/" + tpe)
+          
+          transChildrenInOrder(tree, tpe, qual::(transArgList(fun, args).flatten), Nil)
+
+        case TypeApply(fun @ Select(qual, name), args) if (fun.tpe ne null) && !fun.tpe.isErroneous =>
+          vprintln("[checker] checking select apply " + tree + "/" + tpe)
+
+          transChildrenInOrder(tree, tpe, List(qual, fun), Nil)
+
+        case Apply(fun, args) if (fun.tpe ne null) && !fun.tpe.isErroneous =>
+
+          vprintln("[checker] checking unknown apply " + tree + "/" + tpe)
+          
+          transChildrenInOrder(tree, tpe, fun::(transArgList(fun, args).flatten), Nil)
+
+        case TypeApply(fun, args) =>
+
+          vprintln("[checker] checking type apply " + tree + "/" + tpe)
+
+          transChildrenInOrder(tree, tpe, List(fun), Nil)
+
+        case Select(qual, name) =>
+
+          vprintln("[checker] checking select " + tree + "/" + tpe)
+
+          // straightforward way is problematic (see select.scala and Test2.scala)
+          // transChildrenInOrder(tree, tpe, List(qual), Nil)
+
+          // the problem is that qual may be of type OverloadedType (or MethodType) and
+          // we cannot safely annotate these. so we just ignore these cases and
+          // clean up later in the Apply/TypeApply trees.
+          
+          if (qual.tpe.hasAnnotation(MarkerCPSTypes)) {
+            // however there is one special case:
+            // if it's a method without parameters, just apply it. normally done in adapt, but
+            // we have to do it here so we don't lose the cps information (wouldn't trigger our
+            // adapt and there is no Apply/TypeApply created)
+            tpe match {
+              case PolyType(List(), restpe) =>
+                //println("yep: " + restpe + "," + restpe.getClass)
+                transChildrenInOrder(tree, restpe, List(qual), Nil)
+              case _ : PolyType => tpe
+              case _ : MethodType => tpe
+              case _ : OverloadedType => tpe
+              case _ =>
+                transChildrenInOrder(tree, tpe, List(qual), Nil)
+            }
+          } else
+            tpe
+
+        case If(cond, thenp, elsep) =>
+          transChildrenInOrder(tree, tpe, List(cond), List(thenp, elsep))
+
+        case Match(select, cases) =>
+          // TODO: can there be cases that are not CaseDefs?? check collect vs map!
+          transChildrenInOrder(tree, tpe, List(select), cases:::(cases collect { case CaseDef(_, _, body) => body }))
+
+        case Try(block, catches, finalizer) =>
+          val tpe1 = transChildrenInOrder(tree, tpe, Nil, block::catches:::(catches collect { case CaseDef(_, _, body) => body }))
+
+          val annots = filterAttribs(tpe1, MarkerCPSTypes)
+          if (annots.nonEmpty) {
+            val ann = single(annots)
+            val atp0::atp1::Nil = ann.atp.normalize.typeArgs
+            if (!(atp0 =:= atp1))
+              throw new TypeError("only simple cps types allowed in try/catch blocks (found: " + tpe1 + ")")
+            if (!finalizer.isEmpty) // no finalizers allowed. see explanation in SelectiveCPSTransform
+              reporter.error(tree.pos, "try/catch blocks that use continuations cannot have finalizers")
+          }
+          tpe1
+
+        case Block(stms, expr) =>
+          // if any stm has annotation, so does block
+          transChildrenInOrder(tree, tpe, transStms(stms), List(expr))
+
+        case ValDef(mods, name, tpt, rhs) =>
+          vprintln("[checker] checking valdef " + name + "/"+tpe+"/"+tpt+"/"+tree.symbol.tpe)
+          // ValDef symbols must *not* have annotations!
+          if (hasAnswerTypeAnn(tree.symbol.info)) { // is it okay to modify sym here?
+            vprintln("removing annotation from sym " + tree.symbol + "/" + tree.symbol.tpe + "/" + tpt)
+            tpt.setType(removeAllCPSAnnotations(tpt.tpe))
+            tree.symbol.setInfo(removeAllCPSAnnotations(tree.symbol.info))
+          }
+          tpe
+
+        case _ =>
+          tpe
+      }
+
+          
+    }
+  }
+}
diff --git a/src/continuations/plugin/scala/tools/selectivecps/CPSUtils.scala b/src/continuations/plugin/scala/tools/selectivecps/CPSUtils.scala
new file mode 100644
index 0000000..a3bbd1c
--- /dev/null
+++ b/src/continuations/plugin/scala/tools/selectivecps/CPSUtils.scala
@@ -0,0 +1,131 @@
+// $Id$
+
+package scala.tools.selectivecps
+
+import scala.tools.nsc.Global
+
+trait CPSUtils {
+  val global: Global
+  import global._
+  import definitions._
+
+  var cpsEnabled = false
+  val verbose: Boolean = System.getProperty("cpsVerbose", "false") == "true"
+  @inline final def vprintln(x: =>Any): Unit = if (verbose) println(x)
+
+
+  lazy val MarkerCPSSym = definitions.getClass("scala.util.continuations.cpsSym")
+  lazy val MarkerCPSTypes = definitions.getClass("scala.util.continuations.cpsParam")
+  lazy val MarkerCPSSynth = definitions.getClass("scala.util.continuations.cpsSynth")
+
+  lazy val MarkerCPSAdaptPlus = definitions.getClass("scala.util.continuations.cpsPlus")
+  lazy val MarkerCPSAdaptMinus = definitions.getClass("scala.util.continuations.cpsMinus")
+
+
+  lazy val Context = definitions.getClass("scala.util.continuations.ControlContext")
+
+  lazy val ModCPS = definitions.getModule("scala.util.continuations")
+  lazy val MethShiftUnit = definitions.getMember(ModCPS, "shiftUnit")
+  lazy val MethShiftUnitR = definitions.getMember(ModCPS, "shiftUnitR")
+  lazy val MethShift = definitions.getMember(ModCPS, "shift")
+  lazy val MethShiftR = definitions.getMember(ModCPS, "shiftR")
+  lazy val MethReify = definitions.getMember(ModCPS, "reify")
+  lazy val MethReifyR = definitions.getMember(ModCPS, "reifyR")
+
+
+  lazy val allCPSAnnotations = List(MarkerCPSSym, MarkerCPSTypes, MarkerCPSSynth,
+    MarkerCPSAdaptPlus, MarkerCPSAdaptMinus)
+
+  // annotation checker
+  
+  def filterAttribs(tpe:Type, cls:Symbol) = 
+    tpe.annotations.filter(_.atp.typeSymbol == cls)
+
+  def removeAttribs(tpe:Type, cls:Symbol*) =
+    tpe.withoutAnnotations.withAnnotations(tpe.annotations.filterNot(cls contains _.atp.typeSymbol))
+
+  def removeAllCPSAnnotations(tpe: Type) = removeAttribs(tpe, allCPSAnnotations:_*)
+
+  def linearize(ann: List[AnnotationInfo]): AnnotationInfo = {
+    ann.reduceLeft { (a, b) =>
+      val atp0::atp1::Nil = a.atp.normalize.typeArgs
+      val btp0::btp1::Nil = b.atp.normalize.typeArgs
+      val (u0,v0) = (atp0, atp1)
+      val (u1,v1) = (btp0, btp1)
+/*
+      val (u0,v0) = (a.atp.typeArgs(0), a.atp.typeArgs(1))
+      val (u1,v1) = (b.atp.typeArgs(0), b.atp.typeArgs(1))
+      vprintln("check lin " + a + " andThen " + b)
+*/
+      vprintln("check lin " + a + " andThen " + b)
+      if (!(v1 <:< u0))
+        throw new TypeError("illegal answer type modification: " + a + " andThen " + b)
+      // TODO: improve error message (but it is not very common)
+      AnnotationInfo(appliedType(MarkerCPSTypes.tpe, List(u1,v0)),Nil,Nil)
+    }
+  }
+
+  // anf transform
+
+  def getExternalAnswerTypeAnn(tp: Type) = {
+    tp.annotations.find(a => a.atp.typeSymbol == MarkerCPSTypes) match {
+      case Some(AnnotationInfo(atp, _, _)) => 
+        val atp0::atp1::Nil = atp.normalize.typeArgs
+        Some((atp0, atp1))
+      case None => 
+        if (tp.hasAnnotation(MarkerCPSAdaptPlus))
+          global.warning("trying to instantiate type " + tp + " to unknown cps type")
+        None
+    }
+  }
+
+  def getAnswerTypeAnn(tp: Type) = {
+    tp.annotations.find(a => a.atp.typeSymbol == MarkerCPSTypes) match {
+      case Some(AnnotationInfo(atp, _, _)) => 
+        if (!tp.hasAnnotation(MarkerCPSAdaptPlus)) {//&& !tp.hasAnnotation(MarkerCPSAdaptMinus))
+          val atp0::atp1::Nil = atp.normalize.typeArgs
+          Some((atp0, atp1))
+        } else
+          None
+      case None => None
+    }
+  }
+
+  def hasAnswerTypeAnn(tp: Type) = {
+    tp.hasAnnotation(MarkerCPSTypes) && !tp.hasAnnotation(MarkerCPSAdaptPlus) /*&&
+      !tp.hasAnnotation(MarkerCPSAdaptMinus)*/
+  }
+
+  def hasSynthAnn(tp: Type) = {
+    tp.annotations.exists(a => a.atp.typeSymbol == MarkerCPSSynth)
+  }
+
+  def updateSynthFlag(tree: Tree) = { // remove annotations if *we* added them (@synth present)
+    if (hasSynthAnn(tree.tpe)) {
+      log("removing annotation from " + tree)
+      tree.setType(removeAllCPSAnnotations(tree.tpe))
+    } else
+      tree
+  }
+
+  type CPSInfo = Option[(Type,Type)]
+
+  def linearize(a: CPSInfo, b: CPSInfo)(implicit unit: CompilationUnit, pos: Position): CPSInfo = {
+    (a,b) match {
+      case (Some((u0,v0)), Some((u1,v1))) =>
+        vprintln("check lin " + a + " andThen " + b)
+        if (!(v1 <:< u0)) {
+          unit.error(pos,"cannot change answer type in composition of cps expressions " +
+          "from " + u1 + " to " + v0 + " because " + v1 + " is not a subtype of " + u0 + ".")
+          throw new Exception("check lin " + a + " andThen " + b)
+        }
+        Some((u1,v0))
+      case (Some(_), _) => a
+      case (_, Some(_)) => b
+      case _ => None
+    }
+  }
+  
+  // cps transform
+
+}
\ No newline at end of file
diff --git a/src/continuations/plugin/scala/tools/selectivecps/SelectiveANFTransform.scala b/src/continuations/plugin/scala/tools/selectivecps/SelectiveANFTransform.scala
new file mode 100644
index 0000000..ca69c64
--- /dev/null
+++ b/src/continuations/plugin/scala/tools/selectivecps/SelectiveANFTransform.scala
@@ -0,0 +1,414 @@
+// $Id$
+
+package scala.tools.selectivecps
+
+import scala.tools.nsc._
+import scala.tools.nsc.transform._
+import scala.tools.nsc.symtab._
+import scala.tools.nsc.plugins._
+
+import scala.tools.nsc.ast._
+
+/** 
+ * In methods marked @cps, explicitly name results of calls to other @cps methods
+ */
+abstract class SelectiveANFTransform extends PluginComponent with Transform with
+  TypingTransformers with CPSUtils {
+  // inherits abstract value `global' and class `Phase' from Transform
+
+  import global._                  // the global environment
+  import definitions._             // standard classes and methods
+  import typer.atOwner             // methods to type trees
+
+  /** the following two members override abstract members in Transform */
+  val phaseName: String = "selectiveanf"
+
+  protected def newTransformer(unit: CompilationUnit): Transformer =
+    new ANFTransformer(unit)
+
+
+  class ANFTransformer(unit: CompilationUnit) extends TypingTransformer(unit) {
+
+    implicit val _unit = unit // allow code in CPSUtils.scala to report errors
+    var cpsAllowed: Boolean = false // detect cps code in places we do not handle (yet)
+
+    override def transform(tree: Tree): Tree = {
+      if (!cpsEnabled) return tree
+
+      tree match {
+
+        // Maybe we should further generalize the transform and move it over 
+        // to the regular Transformer facility. But then, actual and required cps
+        // state would need more complicated (stateful!) tracking. 
+        
+        // Making the default case use transExpr(tree, None, None) instead of
+        // calling super.transform() would be a start, but at the moment,
+        // this would cause infinite recursion. But we could remove the
+        // ValDef case here.
+        
+        case dd @ DefDef(mods, name, tparams, vparamss, tpt, rhs) =>
+          log("transforming " + dd.symbol)
+
+          atOwner(dd.symbol) {
+            val rhs1 = transExpr(rhs, None, getExternalAnswerTypeAnn(tpt.tpe))
+      
+            log("result "+rhs1)
+            log("result is of type "+rhs1.tpe)
+
+            treeCopy.DefDef(dd, mods, name, transformTypeDefs(tparams), transformValDefss(vparamss),
+                        transform(tpt), rhs1)
+          }
+
+        case ff @ Function(vparams, body) =>
+          log("transforming anon function " + ff.symbol)
+
+          atOwner(ff.symbol) {
+
+            //val body1 = transExpr(body, None, getExternalAnswerTypeAnn(body.tpe))
+
+            // need to special case partial functions: if expected type is @cps
+            // but all cases are pure, then we would transform
+            // { x => x match { case A => ... }} to
+            // { x => shiftUnit(x match { case A => ... })}
+            // which Uncurry cannot handle (see function6.scala)
+            
+            val ext = getExternalAnswerTypeAnn(body.tpe)
+            
+            val body1 = body match {
+              case Match(selector, cases) if (ext.isDefined && getAnswerTypeAnn(body.tpe).isEmpty) =>
+                val cases1 = for {
+                  cd @ CaseDef(pat, guard, caseBody) <- cases
+                  val caseBody1 = transExpr(body, None, ext)
+                } yield {
+                  treeCopy.CaseDef(cd, transform(pat), transform(guard), caseBody1)
+                }
+                treeCopy.Match(tree, transform(selector), cases1)
+
+              case _ =>
+                transExpr(body, None, ext)
+            }
+            
+            log("result "+body1)
+            log("result is of type "+body1.tpe)
+
+            treeCopy.Function(ff, transformValDefs(vparams), body1)
+          }
+
+        case vd @ ValDef(mods, name, tpt, rhs) => // object-level valdefs
+          log("transforming valdef " + vd.symbol)
+
+          atOwner(vd.symbol) {
+
+            assert(getExternalAnswerTypeAnn(tpt.tpe) == None)
+
+            val rhs1 = transExpr(rhs, None, None)
+
+            treeCopy.ValDef(vd, mods, name, transform(tpt), rhs1)
+          }
+
+        case TypeTree() =>
+          // circumvent cpsAllowed here
+          super.transform(tree)
+        
+        case Apply(_,_) =>
+          // this allows reset { ... } in object constructors
+          // it's kind of a hack to put it here (see note above)
+          transExpr(tree, None, None)
+        
+        case _ => 
+          
+          if (hasAnswerTypeAnn(tree.tpe)) {
+            if (!cpsAllowed)
+              unit.error(tree.pos, "cps code not allowed here / " + tree.getClass + " / " + tree)
+
+            log(tree)
+          }
+
+          cpsAllowed = false
+          super.transform(tree)            
+      }
+    }
+
+
+    def transExpr(tree: Tree, cpsA: CPSInfo, cpsR: CPSInfo): Tree = {
+      transTailValue(tree, cpsA, cpsR) match {
+        case (Nil, b) => b
+        case (a, b) =>
+          treeCopy.Block(tree, a,b)
+      }
+    }
+
+
+    def transArgList(fun: Tree, args: List[Tree], cpsA: CPSInfo): (List[List[Tree]], List[Tree], CPSInfo) = {
+      val formals = fun.tpe.paramTypes
+      val overshoot = args.length - formals.length
+      
+      var spc: CPSInfo = cpsA
+      
+      val (stm,expr) = (for ((a,tp) <- args.zip(formals ::: List.fill(overshoot)(NoType))) yield {
+        tp match {
+          case TypeRef(_, sym, List(elemtp)) if sym == ByNameParamClass =>
+            (Nil, transExpr(a, None, getAnswerTypeAnn(elemtp)))
+          case _ =>
+            val (valStm, valExpr, valSpc) = transInlineValue(a, spc)
+            spc = valSpc
+            (valStm, valExpr)
+        }
+      }).unzip
+      
+      (stm,expr,spc)
+    }
+
+
+    def transValue(tree: Tree, cpsA: CPSInfo, cpsR: CPSInfo): (List[Tree], Tree, CPSInfo) = {
+      // return value: (stms, expr, spc), where spc is CPSInfo after stms but *before* expr
+      implicit val pos = tree.pos
+      tree match {
+        case Block(stms, expr) => 
+          val (cpsA2, cpsR2) = (cpsA, linearize(cpsA, getAnswerTypeAnn(tree.tpe))) // tbd
+//          val (cpsA2, cpsR2) = (None, getAnswerTypeAnn(tree.tpe))
+          val (a, b) = transBlock(stms, expr, cpsA2, cpsR2)
+          
+          val tree1 = (treeCopy.Block(tree, a, b)) // no updateSynthFlag here!!!
+
+          (Nil, tree1, cpsA)
+
+        case If(cond, thenp, elsep) =>
+          
+          val (condStats, condVal, spc) = transInlineValue(cond, cpsA)
+
+          val (cpsA2, cpsR2) = (spc, linearize(spc, getAnswerTypeAnn(tree.tpe)))
+//          val (cpsA2, cpsR2) = (None, getAnswerTypeAnn(tree.tpe))
+          val thenVal = transExpr(thenp, cpsA2, cpsR2)
+          val elseVal = transExpr(elsep, cpsA2, cpsR2)
+          
+          // check that then and else parts agree (not necessary any more, but left as sanity check)
+          if (cpsR.isDefined) {
+            if (elsep == EmptyTree)
+              unit.error(tree.pos, "always need else part in cps code")
+          }
+          if (hasAnswerTypeAnn(thenVal.tpe) != hasAnswerTypeAnn(elseVal.tpe)) {
+            unit.error(tree.pos, "then and else parts must both be cps code or neither of them")
+          }
+
+          (condStats, updateSynthFlag(treeCopy.If(tree, condVal, thenVal, elseVal)), spc)
+
+        case Match(selector, cases) =>
+        
+          val (selStats, selVal, spc) = transInlineValue(selector, cpsA)
+          val (cpsA2, cpsR2) = (spc, linearize(spc, getAnswerTypeAnn(tree.tpe)))
+//          val (cpsA2, cpsR2) = (None, getAnswerTypeAnn(tree.tpe))
+
+          val caseVals = for {
+            cd @ CaseDef(pat, guard, body) <- cases
+            val bodyVal = transExpr(body, cpsA2, cpsR2)
+          } yield {
+            treeCopy.CaseDef(cd, transform(pat), transform(guard), bodyVal)
+          }
+          
+          (selStats, updateSynthFlag(treeCopy.Match(tree, selVal, caseVals)), spc)
+
+
+        case ldef @ LabelDef(name, params, rhs) =>
+          if (hasAnswerTypeAnn(tree.tpe)) {
+            val sym = currentOwner.newMethod(tree.pos, name)//unit.fresh.newName(tree.pos, "myloopvar")
+                        .setInfo(ldef.symbol.info)
+                        .setFlag(Flags.SYNTHETIC)
+          
+            val rhs1 = new TreeSymSubstituter(List(ldef.symbol), List(sym)).transform(rhs)
+            val rhsVal = transExpr(rhs1, None, getAnswerTypeAnn(tree.tpe))
+
+            val stm1 = localTyper.typed(DefDef(sym, rhsVal))
+            val expr = localTyper.typed(Apply(Ident(sym), List()))
+
+            (List(stm1), expr, cpsA)
+          } else {
+            val rhsVal = transExpr(rhs, None, None)
+            (Nil, updateSynthFlag(treeCopy.LabelDef(tree, name, params, rhsVal)), cpsA)
+          }
+          
+
+        case Try(block, catches, finalizer) =>
+          val blockVal = transExpr(block, cpsA, cpsR)
+        
+          val catchVals = for {
+            cd @ CaseDef(pat, guard, body) <- catches
+            val bodyVal = transExpr(body, cpsA, cpsR)
+          } yield {
+            treeCopy.CaseDef(cd, transform(pat), transform(guard), bodyVal)
+          }
+
+          val finallyVal = transExpr(finalizer, None, None) // for now, no cps in finally
+
+          (Nil, updateSynthFlag(treeCopy.Try(tree, blockVal, catchVals, finallyVal)), cpsA)
+
+        case Assign(lhs, rhs) =>
+          // allow cps code in rhs only
+          val (stms, expr, spc) = transInlineValue(rhs, cpsA)
+          (stms, updateSynthFlag(treeCopy.Assign(tree, transform(lhs), expr)), spc)
+          
+        case Return(expr0) =>
+          val (stms, expr, spc) = transInlineValue(expr0, cpsA)
+          (stms, updateSynthFlag(treeCopy.Return(tree, expr)), spc)
+
+        case Throw(expr0) =>
+          val (stms, expr, spc) = transInlineValue(expr0, cpsA)
+          (stms, updateSynthFlag(treeCopy.Throw(tree, expr)), spc)
+
+        case Typed(expr0, tpt) =>
+          // TODO: should x: A @cps[B,C] have a special meaning?
+          // type casts used in different ways (see match2.scala, #3199)
+          val (stms, expr, spc) = transInlineValue(expr0, cpsA)
+          val tpt1 = if (treeInfo.isWildcardStarArg(tree)) tpt else
+            treeCopy.TypeTree(tpt).setType(removeAllCPSAnnotations(tpt.tpe))
+//        (stms, updateSynthFlag(treeCopy.Typed(tree, expr, tpt1)), spc)
+          (stms, treeCopy.Typed(tree, expr, tpt1).setType(removeAllCPSAnnotations(tree.tpe)), spc)
+          
+        case TypeApply(fun, args) =>
+          val (stms, expr, spc) = transInlineValue(fun, cpsA)
+          (stms, updateSynthFlag(treeCopy.TypeApply(tree, expr, args)), spc)
+
+        case Select(qual, name) =>
+          val (stms, expr, spc) = transInlineValue(qual, cpsA)
+          (stms, updateSynthFlag(treeCopy.Select(tree, expr, name)), spc)
+
+        case Apply(fun, args) =>
+          val (funStm, funExpr, funSpc) = transInlineValue(fun, cpsA)
+          val (argStm, argExpr, argSpc) = transArgList(fun, args, funSpc)
+
+          (funStm ::: (argStm.flatten), updateSynthFlag(treeCopy.Apply(tree, funExpr, argExpr)),
+            argSpc)
+
+        case _ =>
+          cpsAllowed = true
+          (Nil, transform(tree), cpsA)
+      }
+    }
+    
+    def transTailValue(tree: Tree, cpsA: CPSInfo, cpsR: CPSInfo): (List[Tree], Tree) = {
+      
+      val (stms, expr, spc) = transValue(tree, cpsA, cpsR)
+
+      val bot = linearize(spc, getAnswerTypeAnn(expr.tpe))(unit, tree.pos)
+
+      val plainTpe = removeAllCPSAnnotations(expr.tpe)
+
+      if (cpsR.isDefined && !bot.isDefined) {
+        
+        if (!expr.isEmpty && (expr.tpe.typeSymbol ne NothingClass)) {
+          // must convert!
+          log("cps type conversion (has: " + cpsA + "/" + spc + "/" + expr.tpe  + ")")
+          log("cps type conversion (expected: " + cpsR.get + "): " + expr)
+          
+          if (!expr.tpe.hasAnnotation(MarkerCPSAdaptPlus))
+            unit.warning(tree.pos, "expression " + tree + " is cps-transformed unexpectedly")
+          
+          try {
+            val Some((a, b)) = cpsR
+
+            val res = localTyper.typed(atPos(tree.pos) {
+                    Apply(TypeApply(gen.mkAttributedRef(MethShiftUnit), 
+                      List(TypeTree(plainTpe), TypeTree(a), TypeTree(b))), 
+                       List(expr))
+            })
+            return (stms, res)
+
+          } catch {
+            case ex:TypeError =>
+              unit.error(ex.pos, "cannot cps-transform expression " + tree + ": " + ex.msg)
+          }
+        }
+
+      } else if (!cpsR.isDefined && bot.isDefined) {
+        // error!
+        log("cps type error: " + expr)
+        //println("cps type error: " + expr + "/" + expr.tpe + "/" + getAnswerTypeAnn(expr.tpe))
+
+        println(cpsR + "/" + spc + "/" + bot)
+
+        unit.error(tree.pos, "found cps expression in non-cps position")
+      } else {
+        // all is well
+
+        if (expr.tpe.hasAnnotation(MarkerCPSAdaptPlus)) {
+          unit.warning(tree.pos, "expression " + expr + " of type " + expr.tpe + " is not expected to have a cps type")
+          expr.setType(removeAllCPSAnnotations(expr.tpe))
+        }
+
+        // TODO: sanity check that types agree
+      }
+
+      (stms, expr)
+    }
+    
+    def transInlineValue(tree: Tree, cpsA: CPSInfo): (List[Tree], Tree, CPSInfo) = {
+
+      val (stms, expr, spc) = transValue(tree, cpsA, None) // never required to be cps
+
+      getAnswerTypeAnn(expr.tpe) match {
+        case spcVal @ Some(_) =>
+
+          val valueTpe = removeAllCPSAnnotations(expr.tpe)
+
+          val sym = currentOwner.newValue(tree.pos, unit.fresh.newName(tree.pos, "tmp"))
+                      .setInfo(valueTpe)
+                      .setFlag(Flags.SYNTHETIC)
+                      .setAnnotations(List(AnnotationInfo(MarkerCPSSym.tpe, Nil, Nil)))
+
+          (stms ::: List(ValDef(sym, expr) setType(NoType)),
+             Ident(sym) setType(valueTpe) setPos(tree.pos), linearize(spc, spcVal)(unit, tree.pos))
+
+        case _ =>
+          (stms, expr, spc)
+      }
+
+    }
+
+
+
+    def transInlineStm(stm: Tree, cpsA: CPSInfo):  (List[Tree], CPSInfo) = {
+      stm match {
+
+        // TODO: what about DefDefs?
+        // TODO: relation to top-level val def?
+        // TODO: what about lazy vals?
+
+        case tree @ ValDef(mods, name, tpt, rhs) =>
+          val (stms, anfRhs, spc) = atOwner(tree.symbol) { transValue(rhs, cpsA, None) }
+        
+          val tv = new ChangeOwnerTraverser(tree.symbol, currentOwner)
+          stms.foreach(tv.traverse(_))
+
+          // TODO: symbol might already have annotation. Should check conformance
+          // TODO: better yet: do without annotations on symbols
+          
+          val spcVal = getAnswerTypeAnn(anfRhs.tpe)
+          if (spcVal.isDefined) {
+              tree.symbol.setAnnotations(List(AnnotationInfo(MarkerCPSSym.tpe, Nil, Nil)))
+          }
+          
+          (stms:::List(treeCopy.ValDef(tree, mods, name, tpt, anfRhs)), linearize(spc, spcVal)(unit, tree.pos))
+
+        case _ =>
+          val (headStms, headExpr, headSpc) = transInlineValue(stm, cpsA)
+          val valSpc = getAnswerTypeAnn(headExpr.tpe)
+          (headStms:::List(headExpr), linearize(headSpc, valSpc)(unit, stm.pos))
+      }
+    }
+
+    def transBlock(stms: List[Tree], expr: Tree, cpsA: CPSInfo, cpsR: CPSInfo): (List[Tree], Tree) = {
+      stms match {
+        case Nil =>
+          transTailValue(expr, cpsA, cpsR)
+
+        case stm::rest =>
+          var (rest2, expr2) = (rest, expr)
+          val (headStms, headSpc) = transInlineStm(stm, cpsA)
+          val (restStms, restExpr) = transBlock(rest2, expr2, headSpc, cpsR)
+          (headStms:::restStms, restExpr)
+       }
+    }
+
+
+  }
+}
diff --git a/src/continuations/plugin/scala/tools/selectivecps/SelectiveCPSPlugin.scala b/src/continuations/plugin/scala/tools/selectivecps/SelectiveCPSPlugin.scala
new file mode 100644
index 0000000..e1834bb
--- /dev/null
+++ b/src/continuations/plugin/scala/tools/selectivecps/SelectiveCPSPlugin.scala
@@ -0,0 +1,60 @@
+// $Id$
+
+package scala.tools.selectivecps
+
+import scala.tools.nsc
+import scala.tools.nsc.typechecker._
+import nsc.Global
+import nsc.Phase
+import nsc.plugins.Plugin
+import nsc.plugins.PluginComponent
+
+class SelectiveCPSPlugin(val global: Global) extends Plugin {
+  import global._
+
+  val name = "continuations"
+  val description = "applies selective cps conversion"
+  
+  val anfPhase = new SelectiveANFTransform() { 
+    val global = SelectiveCPSPlugin.this.global
+    val runsAfter = List("pickler") 
+  }
+  
+  val cpsPhase = new SelectiveCPSTransform() { 
+    val global = SelectiveCPSPlugin.this.global
+    val runsAfter = List("selectiveanf")
+  }
+  
+  
+  val components = List[PluginComponent](anfPhase, cpsPhase)
+
+  val checker = new CPSAnnotationChecker {
+    val global: SelectiveCPSPlugin.this.global.type = SelectiveCPSPlugin.this.global
+  }
+  global.addAnnotationChecker(checker.checker)
+
+  global.log("instantiated cps plugin: " + this)
+
+  def setEnabled(flag: Boolean) = {
+    checker.cpsEnabled = flag
+    anfPhase.cpsEnabled = flag
+    cpsPhase.cpsEnabled = flag
+  }
+
+  // TODO: require -enabled command-line flag
+  
+  override def processOptions(options: List[String], error: String => Unit) = {
+    var enabled = false
+    for (option <- options) {
+      if (option == "enable") {
+        enabled = true
+      } else {
+        error("Option not understood: "+option)
+      }
+    }
+    setEnabled(enabled)
+  }
+
+  override val optionsHelp: Option[String] =
+    Some("  -P:continuations:enable        Enable continuations")
+}
diff --git a/src/continuations/plugin/scala/tools/selectivecps/SelectiveCPSTransform.scala b/src/continuations/plugin/scala/tools/selectivecps/SelectiveCPSTransform.scala
new file mode 100644
index 0000000..6143e46
--- /dev/null
+++ b/src/continuations/plugin/scala/tools/selectivecps/SelectiveCPSTransform.scala
@@ -0,0 +1,384 @@
+// $Id$
+
+package scala.tools.selectivecps
+
+import scala.collection._
+
+import scala.tools.nsc._
+import scala.tools.nsc.transform._
+import scala.tools.nsc.plugins._
+
+import scala.tools.nsc.ast.TreeBrowsers
+import scala.tools.nsc.ast._
+
+/** 
+ * In methods marked @cps, CPS-transform assignments introduced by ANF-transform phase.
+ */
+abstract class SelectiveCPSTransform extends PluginComponent with 
+  InfoTransform with TypingTransformers with CPSUtils {
+  // inherits abstract value `global' and class `Phase' from Transform
+
+  import global._                  // the global environment
+  import definitions._             // standard classes and methods
+  import typer.atOwner             // methods to type trees
+
+  /** the following two members override abstract members in Transform */
+  val phaseName: String = "selectivecps"
+
+  protected def newTransformer(unit: CompilationUnit): Transformer =
+    new CPSTransformer(unit)
+
+  /** This class does not change linearization */
+  override def changesBaseClasses = false
+
+  /** - return symbol's transformed type, 
+   */
+  def transformInfo(sym: Symbol, tp: Type): Type = {
+    if (!cpsEnabled) return tp
+
+    val newtp = transformCPSType(tp)
+
+    if (newtp != tp)
+      log("transformInfo changed type for " + sym + " to " + newtp);
+
+    if (sym == MethReifyR)
+      log("transformInfo (not)changed type for " + sym + " to " + newtp);
+
+    newtp
+  }
+
+  def transformCPSType(tp: Type): Type = {  // TODO: use a TypeMap? need to handle more cases?
+    tp match {
+      case PolyType(params,res) => PolyType(params, transformCPSType(res))
+      case MethodType(params,res) =>
+        MethodType(params, transformCPSType(res))
+      case TypeRef(pre, sym, args) => TypeRef(pre, sym, args.map(transformCPSType(_)))
+      case _ =>
+        getExternalAnswerTypeAnn(tp) match {
+          case Some((res, outer)) =>
+            appliedType(Context.tpe, List(removeAllCPSAnnotations(tp), res, outer))
+          case _ =>
+            removeAllCPSAnnotations(tp)
+        }
+    }
+  }
+
+
+  class CPSTransformer(unit: CompilationUnit) extends TypingTransformer(unit) {
+
+    override def transform(tree: Tree): Tree = {
+      if (!cpsEnabled) return tree
+      postTransform(mainTransform(tree))
+    }
+
+    def postTransform(tree: Tree): Tree = {
+      tree.setType(transformCPSType(tree.tpe))
+    }
+
+
+    def mainTransform(tree: Tree): Tree = {
+      tree match {
+
+        // TODO: can we generalize this?
+        
+        case Apply(TypeApply(fun, targs), args)
+        if (fun.symbol == MethShift) =>
+          log("found shift: " + tree)
+          atPos(tree.pos) {
+            val funR = gen.mkAttributedRef(MethShiftR) // TODO: correct?
+            //gen.mkAttributedSelect(gen.mkAttributedSelect(gen.mkAttributedSelect(gen.mkAttributedIdent(ScalaPackage),
+            //ScalaPackage.tpe.member("util")), ScalaPackage.tpe.member("util").tpe.member("continuations")), MethShiftR)
+            //gen.mkAttributedRef(ModCPS.tpe,  MethShiftR) // TODO: correct?
+            log(funR.tpe)
+            Apply(
+                TypeApply(funR, targs).setType(appliedType(funR.tpe, targs.map((t:Tree) => t.tpe))),
+                args.map(transform(_))
+            ).setType(transformCPSType(tree.tpe))
+          }
+        
+        case Apply(TypeApply(fun, targs), args)
+        if (fun.symbol == MethShiftUnit) =>
+          log("found shiftUnit: " + tree)
+          atPos(tree.pos) {
+            val funR = gen.mkAttributedRef(MethShiftUnitR) // TODO: correct?
+            log(funR.tpe)
+            Apply(
+                TypeApply(funR, List(targs(0), targs(1))).setType(appliedType(funR.tpe, 
+                    List(targs(0).tpe, targs(1).tpe))),
+                args.map(transform(_))
+            ).setType(appliedType(Context.tpe, List(targs(0).tpe,targs(1).tpe,targs(1).tpe)))
+          }
+
+        case Apply(TypeApply(fun, targs), args)
+        if (fun.symbol == MethReify) =>
+          log("found reify: " + tree)
+          atPos(tree.pos) {
+            val funR = gen.mkAttributedRef(MethReifyR) // TODO: correct?
+            log(funR.tpe)
+            Apply(
+                TypeApply(funR, targs).setType(appliedType(funR.tpe, targs.map((t:Tree) => t.tpe))),
+                args.map(transform(_))
+            ).setType(transformCPSType(tree.tpe))
+          }
+
+      case Try(block, catches, finalizer) =>
+        // currently duplicates the catch block into a partial function.
+        // this is kinda risky, but we don't expect there will be lots
+        // of try/catches inside catch blocks (exp. blowup unlikely).
+
+        // CAVEAT: finalizers are surprisingly tricky!
+        // the problem is that they cannot easily be removed
+        // from the regular control path and hence will
+        // also be invoked after creating the Context object.
+        
+        /*
+        object Test {
+          def foo1 = {
+            throw new Exception("in sub")
+            shift((k:Int=>Int) => k(1))
+            10
+          }
+          def foo2 = {
+            shift((k:Int=>Int) => k(2))
+            20
+          }
+          def foo3 = {
+            shift((k:Int=>Int) => k(3))
+            throw new Exception("in sub")
+            30
+          }
+          def foo4 = {
+            shift((k:Int=>Int) => 4)
+            throw new Exception("in sub")
+            40
+          }
+          def bar(x: Int) = try {
+            if (x == 1)
+              foo1
+            else if (x == 2)
+              foo2
+            else if (x == 3)
+              foo3
+            else //if (x == 4)
+              foo4
+          } catch {
+            case _ =>
+              println("exception")
+              0
+          } finally {
+            println("done")
+          }
+        }
+        
+        reset(Test.bar(1)) // should print: exception,done,0
+        reset(Test.bar(2)) // should print: done,20 <-- but prints: done,done,20
+        reset(Test.bar(3)) // should print: exception,done,0 <-- but prints: done,exception,done,0
+        reset(Test.bar(4)) // should print: 4 <-- but prints: done,4
+        */
+
+        val block1 = transform(block)
+        val catches1 = transformCaseDefs(catches)
+        val finalizer1 = transform(finalizer)
+
+        if (hasAnswerTypeAnn(tree.tpe)) {
+          //vprintln("CPS Transform: " + tree + "/" + tree.tpe + "/" + block1.tpe)
+
+          val (stms, expr1) = block1 match {
+            case Block(stms, expr) => (stms, expr)
+            case expr => (Nil, expr)
+          }
+
+          val targettp = transformCPSType(tree.tpe)
+          
+//          val expr2 = if (catches.nonEmpty) {
+            val pos = catches.head.pos
+            val argSym = currentOwner.newValueParameter(pos, "$ex").setInfo(ThrowableClass.tpe)
+            val rhs = Match(Ident(argSym), catches1)
+            val fun = Function(List(ValDef(argSym)), rhs)
+            val funSym = currentOwner.newValueParameter(pos, "$catches").setInfo(appliedType(PartialFunctionClass.tpe, List(ThrowableClass.tpe, targettp)))
+            val funDef = localTyper.typed(atPos(pos) { ValDef(funSym, fun) })
+            val expr2 = localTyper.typed(atPos(pos) { Apply(Select(expr1, expr1.tpe.member("flatMapCatch")), List(Ident(funSym))) })
+
+            argSym.owner = fun.symbol
+            val chown = new ChangeOwnerTraverser(currentOwner, fun.symbol)
+            chown.traverse(rhs)
+            
+            val exSym = currentOwner.newValueParameter(pos, "$ex").setInfo(ThrowableClass.tpe)
+            val catch2 = { localTyper.typedCases(tree, List(
+              CaseDef(Bind(exSym, Typed(Ident("_"), TypeTree(ThrowableClass.tpe))), 
+                Apply(Select(Ident(funSym), "isDefinedAt"), List(Ident(exSym))), 
+                Apply(Ident(funSym), List(Ident(exSym))))
+            ), ThrowableClass.tpe, targettp) }
+
+            //typedCases(tree, catches, ThrowableClass.tpe, pt)
+
+            localTyper.typed(Block(List(funDef), treeCopy.Try(tree, treeCopy.Block(block1, stms, expr2), catch2, finalizer1)))
+
+
+/*
+          disabled for now - see notes above
+          
+          val expr3 = if (!finalizer.isEmpty) {
+            val pos = finalizer.pos
+            val finalizer2 = duplicateTree(finalizer1)
+            val fun = Function(List(), finalizer2)
+            val expr3 = localTyper.typed(atPos(pos) { Apply(Select(expr2, expr2.tpe.member("mapFinally")), List(fun)) })
+
+            val chown = new ChangeOwnerTraverser(currentOwner, fun.symbol)
+            chown.traverse(finalizer2)
+
+            expr3
+          } else
+            expr2
+*/
+        } else {
+          treeCopy.Try(tree, block1, catches1, finalizer1)
+        }
+
+      case Block(stms, expr) => 
+        
+          val (stms1, expr1) = transBlock(stms, expr)
+          treeCopy.Block(tree, stms1, expr1)
+
+        case _ => 
+          super.transform(tree)
+      }
+    }
+
+
+
+    def transBlock(stms: List[Tree], expr: Tree): (List[Tree], Tree) = {
+
+      stms match {
+        case Nil =>
+          (Nil, transform(expr))
+
+        case stm::rest =>
+
+          stm match {
+            case vd @ ValDef(mods, name, tpt, rhs)
+            if (vd.symbol.hasAnnotation(MarkerCPSSym)) =>
+
+              log("found marked ValDef "+name+" of type " + vd.symbol.tpe)
+
+              val tpe = vd.symbol.tpe
+              val rhs1 = atOwner(vd.symbol) { transform(rhs) }
+
+              new ChangeOwnerTraverser(vd.symbol, currentOwner).traverse(rhs1) // TODO: don't traverse twice
+              
+              log("valdef symbol " + vd.symbol + " has type " + tpe)
+              log("right hand side " + rhs1 + " has type " + rhs1.tpe)
+
+              log("currentOwner: " + currentOwner)
+              log("currentMethod: " + currentMethod)
+
+              val (bodyStms, bodyExpr) = transBlock(rest, expr)
+              // FIXME: result will later be traversed again by TreeSymSubstituter and
+              // ChangeOwnerTraverser => exp. running time.
+              // Should be changed to fuse traversals into one.
+              
+              val specialCaseTrivial = bodyExpr match {
+                case Apply(fun, args) =>
+                  // for now, look for explicit tail calls only.
+                  // are there other cases that could profit from specializing on
+                  // trivial contexts as well?
+                  (bodyExpr.tpe.typeSymbol == Context) && (currentMethod == fun.symbol)
+                case _ => false
+              }
+              
+              def applyTrivial(ctxValSym: Symbol, body: Tree) = {
+                
+                val body1 = (new TreeSymSubstituter(List(vd.symbol), List(ctxValSym)))(body)
+                
+                val body2 = localTyper.typed(atPos(vd.symbol.pos) { body1 })
+                
+                // in theory it would be nicer to look for an @cps annotation instead
+                // of testing for Context
+                if ((body2.tpe == null) || !(body2.tpe.typeSymbol == Context)) {
+                  //println(body2 + "/" + body2.tpe)
+                  unit.error(rhs.pos, "cannot compute type for CPS-transformed function result")
+                }
+                body2
+              }
+              
+              def applyCombinatorFun(ctxR: Tree, body: Tree) = {
+                val arg = currentOwner.newValueParameter(ctxR.pos, name).setInfo(tpe)
+                val body1 = (new TreeSymSubstituter(List(vd.symbol), List(arg)))(body)
+                val fun = localTyper.typed(atPos(vd.symbol.pos) { Function(List(ValDef(arg)), body1) }) // types body as well
+                arg.owner = fun.symbol
+                new ChangeOwnerTraverser(currentOwner, fun.symbol).traverse(body1)
+                
+                // see note about multiple traversals above
+
+                log("fun.symbol: "+fun.symbol)
+                log("fun.symbol.owner: "+fun.symbol.owner)
+                log("arg.owner: "+arg.owner)
+              
+                log("fun.tpe:"+fun.tpe)
+                log("return type of fun:"+body1.tpe)
+              
+                var methodName = "map"
+              
+                if (body1.tpe != null) {
+                  if (body1.tpe.typeSymbol == Context)
+                    methodName = "flatMap"
+                }
+                else
+                  unit.error(rhs.pos, "cannot compute type for CPS-transformed function result")
+              
+                log("will use method:"+methodName)
+
+                localTyper.typed(atPos(vd.symbol.pos) {
+                  Apply(Select(ctxR, ctxR.tpe.member(methodName)), List(fun))
+                })
+              }
+              
+              def mkBlock(stms: List[Tree], expr: Tree) = if (stms.nonEmpty) Block(stms, expr) else expr
+              
+              try { 
+                if (specialCaseTrivial) {
+                  log("will optimize possible tail call: " + bodyExpr)
+                  
+                  // FIXME: flatMap impl has become more complicated due to
+                  // exceptions. do we need to put a try/catch in the then part??
+                  
+                  // val ctx = <rhs>
+                  // if (ctx.isTrivial)
+                  //   val <lhs> = ctx.getTrivialValue; ...    <--- TODO: try/catch ??? don't bother for the moment...
+                  // else
+                  //   ctx.flatMap { <lhs> => ... }
+                  val ctxSym = currentOwner.newValue(vd.symbol.name + "$shift").setInfo(rhs1.tpe)
+                  val ctxDef = localTyper.typed(ValDef(ctxSym, rhs1))
+                  def ctxRef = localTyper.typed(Ident(ctxSym))
+                  val argSym = currentOwner.newValue(vd.symbol.name).setInfo(tpe)
+                  val argDef = localTyper.typed(ValDef(argSym, Select(ctxRef, ctxRef.tpe.member("getTrivialValue"))))
+                  val switchExpr = localTyper.typed(atPos(vd.symbol.pos) {
+                    val body2 = duplicateTree(mkBlock(bodyStms, bodyExpr)) // dup before typing!
+                    If(Select(ctxRef, ctxSym.tpe.member("isTrivial")),
+                      applyTrivial(argSym, mkBlock(argDef::bodyStms, bodyExpr)),
+                      applyCombinatorFun(ctxRef, body2))
+                  })
+                  (List(ctxDef), switchExpr)
+                } else {
+                  // ctx.flatMap { <lhs> => ... }
+                  //     or
+                  // ctx.map { <lhs> => ... }
+                  (Nil, applyCombinatorFun(rhs1, mkBlock(bodyStms, bodyExpr)))
+                }
+              } catch {
+                case ex:TypeError =>
+                  unit.error(ex.pos, ex.msg)
+                  (bodyStms, bodyExpr)
+              }
+              
+            case _ => 
+                val stm1 = transform(stm)
+                val (a, b) = transBlock(rest, expr)
+                (stm1::a, b)
+            }
+      }
+    }
+
+
+  }
+}
diff --git a/src/continuations/plugin/scalac-plugin.xml b/src/continuations/plugin/scalac-plugin.xml
new file mode 100644
index 0000000..04d4265
--- /dev/null
+++ b/src/continuations/plugin/scalac-plugin.xml
@@ -0,0 +1,5 @@
+<!-- $Id$ -->
+<plugin>
+  <name>continuations</name>
+  <classname>scala.tools.selectivecps.SelectiveCPSPlugin</classname>
+</plugin>
diff --git a/src/dbc/scala/dbc/DataType.scala b/src/dbc/scala/dbc/DataType.scala
index da07438..0455b62 100644
--- a/src/dbc/scala/dbc/DataType.scala
+++ b/src/dbc/scala/dbc/DataType.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: DataType.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala.dbc;
diff --git a/src/dbc/scala/dbc/Database.scala b/src/dbc/scala/dbc/Database.scala
index ad4175a..91e126f 100644
--- a/src/dbc/scala/dbc/Database.scala
+++ b/src/dbc/scala/dbc/Database.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id:Database.scala 6853 2006-03-20 16:58:47 +0100 (Mon, 20 Mar 2006) dubochet $
 
 
 package scala.dbc
@@ -77,7 +76,7 @@ case class Database(dbms: Vendor) {
       connection.close()
     } else {
       lock.acquire
-      usedConnections = usedConnections.remove(e => (e.equals(connection)));
+      usedConnections = usedConnections.filterNot(e => (e.equals(connection)));
       if (availableConnections.length < vendor.retainedConnections)
         availableConnections = connection :: availableConnections
       else
diff --git a/src/dbc/scala/dbc/Syntax.scala b/src/dbc/scala/dbc/Syntax.scala
index 6df2496..2e4df15 100644
--- a/src/dbc/scala/dbc/Syntax.scala
+++ b/src/dbc/scala/dbc/Syntax.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Syntax.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala.dbc;
diff --git a/src/dbc/scala/dbc/Utilities.scala b/src/dbc/scala/dbc/Utilities.scala
index f1e7cf2..9f16f89 100644
--- a/src/dbc/scala/dbc/Utilities.scala
+++ b/src/dbc/scala/dbc/Utilities.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Utilities.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala.dbc;
diff --git a/src/dbc/scala/dbc/Value.scala b/src/dbc/scala/dbc/Value.scala
index 3dc2fad..548192f 100644
--- a/src/dbc/scala/dbc/Value.scala
+++ b/src/dbc/scala/dbc/Value.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Value.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala.dbc;
diff --git a/src/dbc/scala/dbc/Vendor.scala b/src/dbc/scala/dbc/Vendor.scala
index 79cab2d..82d94eb 100644
--- a/src/dbc/scala/dbc/Vendor.scala
+++ b/src/dbc/scala/dbc/Vendor.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Vendor.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala.dbc;
diff --git a/src/dbc/scala/dbc/datatype/ApproximateNumeric.scala b/src/dbc/scala/dbc/datatype/ApproximateNumeric.scala
index 352ee9b..bbc77fc 100644
--- a/src/dbc/scala/dbc/datatype/ApproximateNumeric.scala
+++ b/src/dbc/scala/dbc/datatype/ApproximateNumeric.scala
@@ -1,15 +1,15 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: ApproximateNumeric.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.dbc.datatype;
+package scala.dbc
+package datatype;
 
 
 /** A type category for all SQL types that store varying-precision
diff --git a/src/dbc/scala/dbc/datatype/Boolean.scala b/src/dbc/scala/dbc/datatype/Boolean.scala
index eea2717..7cebcfd 100644
--- a/src/dbc/scala/dbc/datatype/Boolean.scala
+++ b/src/dbc/scala/dbc/datatype/Boolean.scala
@@ -1,15 +1,15 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id:Boolean.scala 6853 2006-03-20 16:58:47 +0100 (Mon, 20 Mar 2006) dubochet $
 
 
-package scala.dbc.datatype;
+package scala.dbc
+package datatype;
 
 
 /** The SQL type for a truth value. */
diff --git a/src/dbc/scala/dbc/datatype/Character.scala b/src/dbc/scala/dbc/datatype/Character.scala
index ac7b060..a66bebf 100644
--- a/src/dbc/scala/dbc/datatype/Character.scala
+++ b/src/dbc/scala/dbc/datatype/Character.scala
@@ -1,15 +1,15 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Character.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.dbc.datatype;
+package scala.dbc
+package datatype;
 
 
 /** A SQL type for a string of characters of arbitrary length with
diff --git a/src/dbc/scala/dbc/datatype/CharacterLargeObject.scala b/src/dbc/scala/dbc/datatype/CharacterLargeObject.scala
index cb63baa..82b30a5 100644
--- a/src/dbc/scala/dbc/datatype/CharacterLargeObject.scala
+++ b/src/dbc/scala/dbc/datatype/CharacterLargeObject.scala
@@ -1,15 +1,15 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id:CharacterLargeObject.scala 6853 2006-03-20 16:58:47 +0100 (Mon, 20 Mar 2006) dubochet $
 
 
-package scala.dbc.datatype;
+package scala.dbc
+package datatype;
 
 
 /** A SQL type for an unbounded length string of characters with arbitrary
diff --git a/src/dbc/scala/dbc/datatype/CharacterString.scala b/src/dbc/scala/dbc/datatype/CharacterString.scala
index d379a3f..d1b2710 100644
--- a/src/dbc/scala/dbc/datatype/CharacterString.scala
+++ b/src/dbc/scala/dbc/datatype/CharacterString.scala
@@ -1,15 +1,15 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id:CharacterString.scala 6853 2006-03-20 16:58:47 +0100 (Mon, 20 Mar 2006) dubochet $
 
 
-package scala.dbc.datatype;
+package scala.dbc
+package datatype;
 
 
 /** A type category for all SQL types that store strings of characters. */
diff --git a/src/dbc/scala/dbc/datatype/CharacterVarying.scala b/src/dbc/scala/dbc/datatype/CharacterVarying.scala
index 252795e..11b5de1 100644
--- a/src/dbc/scala/dbc/datatype/CharacterVarying.scala
+++ b/src/dbc/scala/dbc/datatype/CharacterVarying.scala
@@ -1,15 +1,15 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: CharacterVarying.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.dbc.datatype;
+package scala.dbc
+package datatype;
 
 
 /** A SQL type for a varying length string of characters with arbitrary
diff --git a/src/dbc/scala/dbc/datatype/ExactNumeric.scala b/src/dbc/scala/dbc/datatype/ExactNumeric.scala
index 8770083..d0d28cc 100644
--- a/src/dbc/scala/dbc/datatype/ExactNumeric.scala
+++ b/src/dbc/scala/dbc/datatype/ExactNumeric.scala
@@ -1,15 +1,15 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: ExactNumeric.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.dbc.datatype;
+package scala.dbc
+package datatype;
 
 
 /** A type category for all SQL types that store constant-precision
diff --git a/src/dbc/scala/dbc/datatype/Factory.scala b/src/dbc/scala/dbc/datatype/Factory.scala
index d77cb6a..e35d1af 100644
--- a/src/dbc/scala/dbc/datatype/Factory.scala
+++ b/src/dbc/scala/dbc/datatype/Factory.scala
@@ -1,15 +1,15 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id:Factory.scala 6853 2006-03-20 16:58:47 +0100 (Mon, 20 Mar 2006) dubochet $
 
 
-package scala.dbc.datatype;
+package scala.dbc
+package datatype;
 
 
 import java.sql.Types._;
@@ -21,7 +21,7 @@ object Factory {
   final val java_lang_Integer_SIZE = 32;
   final val java_lang_Long_SIZE    = 64;
 
-  /** Returns a mullable property formated as a boolean option */
+  /** Returns a nullable property formatted as a boolean option */
   def isNullable (metadata:java.sql.ResultSetMetaData, index:Int): Option[scala.Boolean] =
     metadata.isNullable(index) match {
       case java.sql.ResultSetMetaData.columnNoNulls => Some(false);
diff --git a/src/dbc/scala/dbc/datatype/Numeric.scala b/src/dbc/scala/dbc/datatype/Numeric.scala
index 65135aa..4c39869 100644
--- a/src/dbc/scala/dbc/datatype/Numeric.scala
+++ b/src/dbc/scala/dbc/datatype/Numeric.scala
@@ -1,15 +1,15 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Numeric.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.dbc.datatype;
+package scala.dbc
+package datatype;
 
 
 /** A type category for all SQL types that store numbers. */
diff --git a/src/dbc/scala/dbc/datatype/String.scala b/src/dbc/scala/dbc/datatype/String.scala
index b38d122..99c60e4 100644
--- a/src/dbc/scala/dbc/datatype/String.scala
+++ b/src/dbc/scala/dbc/datatype/String.scala
@@ -1,15 +1,15 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: String.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.dbc.datatype;
+package scala.dbc
+package datatype;
 
 
 /** A type category for all SQL types that store strings of elements.
diff --git a/src/dbc/scala/dbc/datatype/Unknown.scala b/src/dbc/scala/dbc/datatype/Unknown.scala
index 9d8444d..fddc30a 100644
--- a/src/dbc/scala/dbc/datatype/Unknown.scala
+++ b/src/dbc/scala/dbc/datatype/Unknown.scala
@@ -1,15 +1,15 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Unknown.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.dbc.datatype;
+package scala.dbc
+package datatype;
 
 
 /** The SQL type for a truth value. */
diff --git a/src/dbc/scala/dbc/exception/IncompatibleSchema.scala b/src/dbc/scala/dbc/exception/IncompatibleSchema.scala
index 02f4990..883a236 100644
--- a/src/dbc/scala/dbc/exception/IncompatibleSchema.scala
+++ b/src/dbc/scala/dbc/exception/IncompatibleSchema.scala
@@ -1,15 +1,15 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id:IncompatibleSchema.scala 6853 2006-03-20 16:58:47 +0100 (Mon, 20 Mar 2006) dubochet $
 
 
-package scala.dbc.exception;
+package scala.dbc
+package exception
 
 
 /** A type category for all SQL types that store constant-precision numbers. */
diff --git a/src/dbc/scala/dbc/exception/UnsupportedFeature.scala b/src/dbc/scala/dbc/exception/UnsupportedFeature.scala
index fd4a756..3e3d2f6 100644
--- a/src/dbc/scala/dbc/exception/UnsupportedFeature.scala
+++ b/src/dbc/scala/dbc/exception/UnsupportedFeature.scala
@@ -1,15 +1,15 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: UnsupportedFeature.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.dbc.exception;
+package scala.dbc
+package exception
 
 
 /** A type category for all SQL types that store constant-precision numbers. */
diff --git a/src/dbc/scala/dbc/result/Field.scala b/src/dbc/scala/dbc/result/Field.scala
index 0a2c794..b01dd5d 100644
--- a/src/dbc/scala/dbc/result/Field.scala
+++ b/src/dbc/scala/dbc/result/Field.scala
@@ -1,15 +1,15 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id:Field.scala 6853 2006-03-20 16:58:47 +0100 (Mon, 20 Mar 2006) dubochet $
 
 
-package scala.dbc.result
+package scala.dbc
+package result
 
 
 import scala.dbc.datatype._
diff --git a/src/dbc/scala/dbc/result/FieldMetadata.scala b/src/dbc/scala/dbc/result/FieldMetadata.scala
index a461e16..8314eaa 100644
--- a/src/dbc/scala/dbc/result/FieldMetadata.scala
+++ b/src/dbc/scala/dbc/result/FieldMetadata.scala
@@ -1,15 +1,15 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id:FieldMetadata.scala 6853 2006-03-20 16:58:47 +0100 (Mon, 20 Mar 2006) dubochet $
 
 
-package scala.dbc.result
+package scala.dbc
+package result
 
 
 /** The class <code>FieldMetadata</cocde> provides informations attached to
diff --git a/src/dbc/scala/dbc/result/Relation.scala b/src/dbc/scala/dbc/result/Relation.scala
index e797f2c..a54b415 100644
--- a/src/dbc/scala/dbc/result/Relation.scala
+++ b/src/dbc/scala/dbc/result/Relation.scala
@@ -1,15 +1,15 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id:Relation.scala 6853 2006-03-20 16:58:47 +0100 (Mon, 20 Mar 2006) dubochet $
 
 
-package scala.dbc.result
+package scala.dbc
+package result
 
 
 /** An ISO-9075:2003 (SQL) table. This is equivalent to a relation in the
@@ -39,8 +39,13 @@ abstract class Relation extends AnyRef with Iterable[Tuple] {
   
   /** Metadata about the field at the given index. If there is no such
    * field <code>None</code> is returned instead. */
-  def metadataFor (index:Int): Option[FieldMetadata] =
-    try {Some(metadata(index))} catch {case e => None}
+  def metadataFor (index:Int): Option[FieldMetadata] = {
+    val meta = metadata
+    if (meta.length > index)
+      Some(meta(index))
+    else
+      None
+  }
   
   /** Metadata about the field with the given column name. If there is no
    * such field, <code>None</code> is returned instead. */
@@ -51,12 +56,13 @@ abstract class Relation extends AnyRef with Iterable[Tuple] {
    * <h3>Caution</h3> A Relation only has one single iterator, due to limitations
    * in DBMS. This means that if this method is called multiple times, all returned
    * iterators will share the same state. */
-  def elements: Iterator[Tuple] = new Iterator[Tuple] {
+  def iterator: Iterator[Tuple] = new Iterator[Tuple] {
     protected val result: java.sql.ResultSet = Relation.this.sqlResult
-    def hasNext: Boolean = !(result.isLast())
+    def hasNext: Boolean = resultNext
+    private var resultNext = result.next()
     def next: Tuple = {
-      if (result.next()) {
-        new Tuple {
+      if (resultNext) {
+        val newTuple = new Tuple {
           val me = this
           val originatingRelation = Relation.this
           val fields: List[Field] = for (fieldMetadata <- metadata) yield
@@ -66,7 +72,11 @@ abstract class Relation extends AnyRef with Iterable[Tuple] {
               val originatingTuple = me
             }
         }
-      } else error("next on empty iterator")
+        resultNext = result.next()
+        newTuple
+      }
+      else error("next on empty iterator")
     }
-  }
+  }	
+
 }
diff --git a/src/dbc/scala/dbc/result/Status.scala b/src/dbc/scala/dbc/result/Status.scala
index a52a7cb..5fe2c61 100644
--- a/src/dbc/scala/dbc/result/Status.scala
+++ b/src/dbc/scala/dbc/result/Status.scala
@@ -1,15 +1,15 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id:Status.scala 6853 2006-03-20 16:58:47 +0100 (Mon, 20 Mar 2006) dubochet $
 
 
-package scala.dbc.result;
+package scala.dbc
+package result;
 
 
 import scala.dbc.datatype._;
diff --git a/src/dbc/scala/dbc/result/Tuple.scala b/src/dbc/scala/dbc/result/Tuple.scala
index 0736205..6a918cc 100644
--- a/src/dbc/scala/dbc/result/Tuple.scala
+++ b/src/dbc/scala/dbc/result/Tuple.scala
@@ -1,15 +1,15 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id:Tuple.scala 6853 2006-03-20 16:58:47 +0100 (Mon, 20 Mar 2006) dubochet $
 
 
-package scala.dbc.result;
+package scala.dbc
+package result;
 
 
 /** An ISO-9075:2003 (SQL) table row. This is equivalent to a tuple in the relational model. */
diff --git a/src/dbc/scala/dbc/statement/AccessMode.scala b/src/dbc/scala/dbc/statement/AccessMode.scala
index 6315150..d5304c4 100644
--- a/src/dbc/scala/dbc/statement/AccessMode.scala
+++ b/src/dbc/scala/dbc/statement/AccessMode.scala
@@ -1,15 +1,15 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id:AccessMode.scala 6853 2006-03-20 16:58:47 +0100 (Mon, 20 Mar 2006) dubochet $
 
 
-package scala.dbc.statement
+package scala.dbc
+package statement
 
 
 abstract class AccessMode {
diff --git a/src/dbc/scala/dbc/statement/DerivedColumn.scala b/src/dbc/scala/dbc/statement/DerivedColumn.scala
index 0d1efe7..7ebfe61 100644
--- a/src/dbc/scala/dbc/statement/DerivedColumn.scala
+++ b/src/dbc/scala/dbc/statement/DerivedColumn.scala
@@ -1,15 +1,15 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: DerivedColumn.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.dbc.statement
+package scala.dbc
+package statement
 
 
 abstract class DerivedColumn {
diff --git a/src/dbc/scala/dbc/statement/Expression.scala b/src/dbc/scala/dbc/statement/Expression.scala
index f73ee1f..35511d6 100644
--- a/src/dbc/scala/dbc/statement/Expression.scala
+++ b/src/dbc/scala/dbc/statement/Expression.scala
@@ -1,15 +1,15 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Expression.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.dbc.statement
+package scala.dbc
+package statement
 
 
 /** An expression that calculates some value from fields. */
diff --git a/src/dbc/scala/dbc/statement/Insert.scala b/src/dbc/scala/dbc/statement/Insert.scala
index ef8cd6a..ec4850b 100644
--- a/src/dbc/scala/dbc/statement/Insert.scala
+++ b/src/dbc/scala/dbc/statement/Insert.scala
@@ -1,15 +1,15 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id:Insert.scala 6853 2006-03-20 16:58:47 +0100 (Mon, 20 Mar 2006) dubochet $
 
 
-package scala.dbc.statement
+package scala.dbc
+package statement
 
 
 import scala.dbc.statement.expression._
diff --git a/src/dbc/scala/dbc/statement/InsertionData.scala b/src/dbc/scala/dbc/statement/InsertionData.scala
index 5755b31..e0f9083 100644
--- a/src/dbc/scala/dbc/statement/InsertionData.scala
+++ b/src/dbc/scala/dbc/statement/InsertionData.scala
@@ -1,15 +1,15 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id:InsertionData.scala 6853 2006-03-20 16:58:47 +0100 (Mon, 20 Mar 2006) dubochet $
 
 
-package scala.dbc.statement
+package scala.dbc
+package statement
 
 
 import scala.dbc.statement.expression._
diff --git a/src/dbc/scala/dbc/statement/IsolationLevel.scala b/src/dbc/scala/dbc/statement/IsolationLevel.scala
index 40b1a5d..444c03a 100644
--- a/src/dbc/scala/dbc/statement/IsolationLevel.scala
+++ b/src/dbc/scala/dbc/statement/IsolationLevel.scala
@@ -1,15 +1,15 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id:IsolationLevel.scala 6853 2006-03-20 16:58:47 +0100 (Mon, 20 Mar 2006) dubochet $
 
 
-package scala.dbc.statement
+package scala.dbc
+package statement
 
 
 abstract class IsolationLevel {
diff --git a/src/dbc/scala/dbc/statement/JoinType.scala b/src/dbc/scala/dbc/statement/JoinType.scala
index 16903a8..4a9af82 100644
--- a/src/dbc/scala/dbc/statement/JoinType.scala
+++ b/src/dbc/scala/dbc/statement/JoinType.scala
@@ -1,15 +1,15 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: JoinType.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.dbc.statement
+package scala.dbc
+package statement
 
 
 /** A join behaviour in a <code>Jointure</code>. */
diff --git a/src/dbc/scala/dbc/statement/Jointure.scala b/src/dbc/scala/dbc/statement/Jointure.scala
index 5ee43f6..74bc60c 100644
--- a/src/dbc/scala/dbc/statement/Jointure.scala
+++ b/src/dbc/scala/dbc/statement/Jointure.scala
@@ -1,15 +1,15 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id:Jointure.scala 6853 2006-03-20 16:58:47 +0100 (Mon, 20 Mar 2006) dubochet $
 
 
-package scala.dbc.statement
+package scala.dbc
+package statement
 
 
 /** A jointure between two relations. */
diff --git a/src/dbc/scala/dbc/statement/Relation.scala b/src/dbc/scala/dbc/statement/Relation.scala
index f262570..65d468a 100644
--- a/src/dbc/scala/dbc/statement/Relation.scala
+++ b/src/dbc/scala/dbc/statement/Relation.scala
@@ -1,15 +1,15 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id:Relation.scala 6853 2006-03-20 16:58:47 +0100 (Mon, 20 Mar 2006) dubochet $
 
 
-package scala.dbc.statement;
+package scala.dbc
+package statement;
 
 
 /** A statement that returns a relation. */
diff --git a/src/dbc/scala/dbc/statement/Select.scala b/src/dbc/scala/dbc/statement/Select.scala
index 38d65ff..c0cf185 100644
--- a/src/dbc/scala/dbc/statement/Select.scala
+++ b/src/dbc/scala/dbc/statement/Select.scala
@@ -1,15 +1,15 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id:Select.scala 6853 2006-03-20 16:58:47 +0100 (Mon, 20 Mar 2006) dubochet $
 
 
-package scala.dbc.statement
+package scala.dbc
+package statement
 
 
 /** A statement that when executed on a database will return a relation.
diff --git a/src/dbc/scala/dbc/statement/SetClause.scala b/src/dbc/scala/dbc/statement/SetClause.scala
index 16c6656..177c869 100644
--- a/src/dbc/scala/dbc/statement/SetClause.scala
+++ b/src/dbc/scala/dbc/statement/SetClause.scala
@@ -1,15 +1,15 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id:SetClause.scala 6853 2006-03-20 16:58:47 +0100 (Mon, 20 Mar 2006) dubochet $
 
 
-package scala.dbc.statement
+package scala.dbc
+package statement
 
 
 import scala.dbc.statement.expression._
diff --git a/src/dbc/scala/dbc/statement/SetQuantifier.scala b/src/dbc/scala/dbc/statement/SetQuantifier.scala
index 4febee6..1f224ea 100644
--- a/src/dbc/scala/dbc/statement/SetQuantifier.scala
+++ b/src/dbc/scala/dbc/statement/SetQuantifier.scala
@@ -1,15 +1,15 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id:SetQuantifier.scala 6853 2006-03-20 16:58:47 +0100 (Mon, 20 Mar 2006) dubochet $
 
 
-package scala.dbc.statement
+package scala.dbc
+package statement
 
 
 /** A set quantifier that defines the collection type of a relation. */
diff --git a/src/dbc/scala/dbc/statement/Statement.scala b/src/dbc/scala/dbc/statement/Statement.scala
index e396a02..a8d52ba 100644
--- a/src/dbc/scala/dbc/statement/Statement.scala
+++ b/src/dbc/scala/dbc/statement/Statement.scala
@@ -1,15 +1,15 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id:Statement.scala 6853 2006-03-20 16:58:47 +0100 (Mon, 20 Mar 2006) dubochet $
 
 
-package scala.dbc.statement
+package scala.dbc
+package statement
 
 
 /** An ISO-9075:2003 (SQL) statement. */
diff --git a/src/dbc/scala/dbc/statement/Status.scala b/src/dbc/scala/dbc/statement/Status.scala
index d8a8451..bea3a26 100644
--- a/src/dbc/scala/dbc/statement/Status.scala
+++ b/src/dbc/scala/dbc/statement/Status.scala
@@ -1,15 +1,15 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id:Status.scala 6853 2006-03-20 16:58:47 +0100 (Mon, 20 Mar 2006) dubochet $
 
 
-package scala.dbc.statement
+package scala.dbc
+package statement
 
 import scala.dbc.Database
 import scala.dbc.result
diff --git a/src/dbc/scala/dbc/statement/Table.scala b/src/dbc/scala/dbc/statement/Table.scala
index 050faa8..f7aae81 100644
--- a/src/dbc/scala/dbc/statement/Table.scala
+++ b/src/dbc/scala/dbc/statement/Table.scala
@@ -1,15 +1,15 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id:Table.scala 6853 2006-03-20 16:58:47 +0100 (Mon, 20 Mar 2006) dubochet $
 
 
-package scala.dbc.statement
+package scala.dbc
+package statement
 
 
 /** A reference to a table in the database.
diff --git a/src/dbc/scala/dbc/statement/Transaction.scala b/src/dbc/scala/dbc/statement/Transaction.scala
index 5c9e419..9ffc0e1 100644
--- a/src/dbc/scala/dbc/statement/Transaction.scala
+++ b/src/dbc/scala/dbc/statement/Transaction.scala
@@ -1,15 +1,15 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id:Transaction.scala 6853 2006-03-20 16:58:47 +0100 (Mon, 20 Mar 2006) dubochet $
 
 
-package scala.dbc.statement;
+package scala.dbc
+package statement;
 
 
 /** A statement that changes the status of the database. */
diff --git a/src/dbc/scala/dbc/statement/Update.scala b/src/dbc/scala/dbc/statement/Update.scala
index 86d21ad..d782342 100644
--- a/src/dbc/scala/dbc/statement/Update.scala
+++ b/src/dbc/scala/dbc/statement/Update.scala
@@ -1,15 +1,15 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id:Update.scala 6853 2006-03-20 16:58:47 +0100 (Mon, 20 Mar 2006) dubochet $
 
 
-package scala.dbc.statement;
+package scala.dbc
+package statement;
 
 
 import scala.dbc.statement.expression._;
diff --git a/src/dbc/scala/dbc/statement/expression/Aggregate.scala b/src/dbc/scala/dbc/statement/expression/Aggregate.scala
index e5d2bda..e5adf1b 100644
--- a/src/dbc/scala/dbc/statement/expression/Aggregate.scala
+++ b/src/dbc/scala/dbc/statement/expression/Aggregate.scala
@@ -1,15 +1,16 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Aggregate.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.dbc.statement.expression;
+package scala.dbc
+package statement
+package expression
 
 
 abstract class Aggregate extends Expression {
diff --git a/src/dbc/scala/dbc/statement/expression/BinaryOperator.scala b/src/dbc/scala/dbc/statement/expression/BinaryOperator.scala
index 285b558..390c95a 100644
--- a/src/dbc/scala/dbc/statement/expression/BinaryOperator.scala
+++ b/src/dbc/scala/dbc/statement/expression/BinaryOperator.scala
@@ -1,15 +1,16 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: BinaryOperator.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.dbc.statement.expression;
+package scala.dbc
+package statement
+package expression;
 
 
 abstract class BinaryOperator extends Expression {
diff --git a/src/dbc/scala/dbc/statement/expression/Constant.scala b/src/dbc/scala/dbc/statement/expression/Constant.scala
index 0e94367..da5989a 100644
--- a/src/dbc/scala/dbc/statement/expression/Constant.scala
+++ b/src/dbc/scala/dbc/statement/expression/Constant.scala
@@ -1,15 +1,16 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id:Constant.scala 6853 2006-03-20 16:58:47 +0100 (Mon, 20 Mar 2006) dubochet $
 
 
-package scala.dbc.statement.expression;
+package scala.dbc
+package statement
+package expression;
 
 
 abstract class Constant extends Expression {
diff --git a/src/dbc/scala/dbc/statement/expression/Default.scala b/src/dbc/scala/dbc/statement/expression/Default.scala
index 7e64c19..9317f43 100644
--- a/src/dbc/scala/dbc/statement/expression/Default.scala
+++ b/src/dbc/scala/dbc/statement/expression/Default.scala
@@ -1,15 +1,16 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id:Default.scala 6853 2006-03-20 16:58:47 +0100 (Mon, 20 Mar 2006) dubochet $
 
 
-package scala.dbc.statement.expression;
+package scala.dbc
+package statement
+package expression;
 
 
 case object Default extends Expression {
diff --git a/src/dbc/scala/dbc/statement/expression/Field.scala b/src/dbc/scala/dbc/statement/expression/Field.scala
index 80e451d..f1822f0 100644
--- a/src/dbc/scala/dbc/statement/expression/Field.scala
+++ b/src/dbc/scala/dbc/statement/expression/Field.scala
@@ -1,15 +1,16 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Field.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.dbc.statement.expression;
+package scala.dbc
+package statement
+package expression;
 
 
 abstract class Field extends Expression {
diff --git a/src/dbc/scala/dbc/statement/expression/FunctionCall.scala b/src/dbc/scala/dbc/statement/expression/FunctionCall.scala
index 03d9811..51e9c29 100644
--- a/src/dbc/scala/dbc/statement/expression/FunctionCall.scala
+++ b/src/dbc/scala/dbc/statement/expression/FunctionCall.scala
@@ -1,15 +1,16 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id:FunctionCall.scala 6853 2006-03-20 16:58:47 +0100 (Mon, 20 Mar 2006) dubochet $
 
 
-package scala.dbc.statement.expression;
+package scala.dbc
+package statement
+package expression;
 
 
 case class FunctionCall (
diff --git a/src/dbc/scala/dbc/statement/expression/Select.scala b/src/dbc/scala/dbc/statement/expression/Select.scala
index dd3d7b6..814f413 100644
--- a/src/dbc/scala/dbc/statement/expression/Select.scala
+++ b/src/dbc/scala/dbc/statement/expression/Select.scala
@@ -1,15 +1,16 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Select.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.dbc.statement.expression;
+package scala.dbc
+package statement
+package expression;
 
 
 abstract class Select extends Expression {
diff --git a/src/dbc/scala/dbc/statement/expression/SetFunction.scala b/src/dbc/scala/dbc/statement/expression/SetFunction.scala
index 424f659..36061b0 100644
--- a/src/dbc/scala/dbc/statement/expression/SetFunction.scala
+++ b/src/dbc/scala/dbc/statement/expression/SetFunction.scala
@@ -1,15 +1,16 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id:SetFunction.scala 6853 2006-03-20 16:58:47 +0100 (Mon, 20 Mar 2006) dubochet $
 
 
-package scala.dbc.statement.expression;
+package scala.dbc
+package statement
+package expression;
 
 
 abstract class SetFunction {
diff --git a/src/dbc/scala/dbc/statement/expression/TypeCast.scala b/src/dbc/scala/dbc/statement/expression/TypeCast.scala
index 2d28dd5..8477b16 100644
--- a/src/dbc/scala/dbc/statement/expression/TypeCast.scala
+++ b/src/dbc/scala/dbc/statement/expression/TypeCast.scala
@@ -1,15 +1,16 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id:TypeCast.scala 6853 2006-03-20 16:58:47 +0100 (Mon, 20 Mar 2006) dubochet $
 
 
-package scala.dbc.statement.expression;
+package scala.dbc
+package statement
+package expression;
 
 
 case class TypeCast (
diff --git a/src/dbc/scala/dbc/statement/expression/UnaryOperator.scala b/src/dbc/scala/dbc/statement/expression/UnaryOperator.scala
index 188ef9b..2b6bb14 100644
--- a/src/dbc/scala/dbc/statement/expression/UnaryOperator.scala
+++ b/src/dbc/scala/dbc/statement/expression/UnaryOperator.scala
@@ -1,15 +1,16 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: UnaryOperator.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.dbc.statement.expression;
+package scala.dbc
+package statement
+package expression;
 
 
 abstract class UnaryOperator extends Expression {
diff --git a/src/dbc/scala/dbc/syntax/DataTypeUtil.scala b/src/dbc/scala/dbc/syntax/DataTypeUtil.scala
index a48e111..f3e38dd 100644
--- a/src/dbc/scala/dbc/syntax/DataTypeUtil.scala
+++ b/src/dbc/scala/dbc/syntax/DataTypeUtil.scala
@@ -1,15 +1,15 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id:DataTypeUtil.scala 6853 2006-03-20 16:58:47 +0100 (Mon, 20 Mar 2006) dubochet $
 
 
-package scala.dbc.syntax;
+package scala.dbc
+package syntax;
 
 
 import java.math.BigDecimal;
diff --git a/src/dbc/scala/dbc/syntax/Database.scala b/src/dbc/scala/dbc/syntax/Database.scala
index a145128..2950fa3 100644
--- a/src/dbc/scala/dbc/syntax/Database.scala
+++ b/src/dbc/scala/dbc/syntax/Database.scala
@@ -1,15 +1,15 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id:Database.scala 6853 2006-03-20 16:58:47 +0100 (Mon, 20 Mar 2006) dubochet $
 
 
-package scala.dbc.syntax;
+package scala.dbc
+package syntax;
 
 
 import java.net.URI;
diff --git a/src/dbc/scala/dbc/syntax/Statement.scala b/src/dbc/scala/dbc/syntax/Statement.scala
index 1cdf6bb..89b8eef 100644
--- a/src/dbc/scala/dbc/syntax/Statement.scala
+++ b/src/dbc/scala/dbc/syntax/Statement.scala
@@ -1,15 +1,15 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id:Statement.scala 6853 2006-03-20 16:58:47 +0100 (Mon, 20 Mar 2006) dubochet $
 
 
-package scala.dbc.syntax;
+package scala.dbc
+package syntax;
 
 
 import java.math.BigDecimal;
diff --git a/src/dbc/scala/dbc/syntax/StatementExpression.scala b/src/dbc/scala/dbc/syntax/StatementExpression.scala
index cca6d9b..c2fa682 100644
--- a/src/dbc/scala/dbc/syntax/StatementExpression.scala
+++ b/src/dbc/scala/dbc/syntax/StatementExpression.scala
@@ -1,15 +1,15 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id:StatementExpression.scala 6853 2006-03-20 16:58:47 +0100 (Mon, 20 Mar 2006) dubochet $
 
 
-package scala.dbc.syntax;
+package scala.dbc
+package syntax;
 
 
 import java.math.BigDecimal;
diff --git a/src/dbc/scala/dbc/value/ApproximateNumeric.scala b/src/dbc/scala/dbc/value/ApproximateNumeric.scala
index 49a580f..852c815 100644
--- a/src/dbc/scala/dbc/value/ApproximateNumeric.scala
+++ b/src/dbc/scala/dbc/value/ApproximateNumeric.scala
@@ -1,15 +1,15 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: ApproximateNumeric.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.dbc.value;
+package scala.dbc
+package value;
 
 
 abstract class ApproximateNumeric [Type] extends Value {
diff --git a/src/dbc/scala/dbc/value/Boolean.scala b/src/dbc/scala/dbc/value/Boolean.scala
index 2507167..b5d7ab6 100644
--- a/src/dbc/scala/dbc/value/Boolean.scala
+++ b/src/dbc/scala/dbc/value/Boolean.scala
@@ -1,15 +1,15 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id:Boolean.scala 6853 2006-03-20 16:58:47 +0100 (Mon, 20 Mar 2006) dubochet $
 
 
-package scala.dbc.value;
+package scala.dbc
+package value;
 
 
 abstract class Boolean extends Value {
diff --git a/src/dbc/scala/dbc/value/Character.scala b/src/dbc/scala/dbc/value/Character.scala
index 8484ad7..79bda1f 100644
--- a/src/dbc/scala/dbc/value/Character.scala
+++ b/src/dbc/scala/dbc/value/Character.scala
@@ -1,15 +1,15 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id:Character.scala 6853 2006-03-20 16:58:47 +0100 (Mon, 20 Mar 2006) dubochet $
 
 
-package scala.dbc.value;
+package scala.dbc
+package value;
 
 
 /** A SQL-99 value of type character string. */
diff --git a/src/dbc/scala/dbc/value/CharacterLargeObject.scala b/src/dbc/scala/dbc/value/CharacterLargeObject.scala
index 13121eb..f47b6dd 100644
--- a/src/dbc/scala/dbc/value/CharacterLargeObject.scala
+++ b/src/dbc/scala/dbc/value/CharacterLargeObject.scala
@@ -1,15 +1,15 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id:CharacterLargeObject.scala 6853 2006-03-20 16:58:47 +0100 (Mon, 20 Mar 2006) dubochet $
 
 
-package scala.dbc.value;
+package scala.dbc
+package value;
 
 
 /** A SQL-99 value of type character large object. */
diff --git a/src/dbc/scala/dbc/value/CharacterVarying.scala b/src/dbc/scala/dbc/value/CharacterVarying.scala
index 4964866..2c5fc02 100644
--- a/src/dbc/scala/dbc/value/CharacterVarying.scala
+++ b/src/dbc/scala/dbc/value/CharacterVarying.scala
@@ -1,15 +1,15 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id:CharacterVarying.scala 6853 2006-03-20 16:58:47 +0100 (Mon, 20 Mar 2006) dubochet $
 
 
-package scala.dbc.value;
+package scala.dbc
+package value;
 
 
 /** A SQL-99 value of type character varying string. */
diff --git a/src/dbc/scala/dbc/value/Conversion.scala b/src/dbc/scala/dbc/value/Conversion.scala
index 100e1c2..04ed12e 100644
--- a/src/dbc/scala/dbc/value/Conversion.scala
+++ b/src/dbc/scala/dbc/value/Conversion.scala
@@ -1,15 +1,15 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Conversion.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.dbc.value;
+package scala.dbc
+package value;
 
 
 import java.math._;
diff --git a/src/dbc/scala/dbc/value/ExactNumeric.scala b/src/dbc/scala/dbc/value/ExactNumeric.scala
index f1d2214..9fe9f47 100644
--- a/src/dbc/scala/dbc/value/ExactNumeric.scala
+++ b/src/dbc/scala/dbc/value/ExactNumeric.scala
@@ -1,15 +1,15 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id:ExactNumeric.scala 6853 2006-03-20 16:58:47 +0100 (Mon, 20 Mar 2006) dubochet $
 
 
-package scala.dbc.value;
+package scala.dbc
+package value;
 
 
 import java.math.BigInteger;
diff --git a/src/dbc/scala/dbc/value/Factory.scala b/src/dbc/scala/dbc/value/Factory.scala
index e5037bf..142f843 100644
--- a/src/dbc/scala/dbc/value/Factory.scala
+++ b/src/dbc/scala/dbc/value/Factory.scala
@@ -1,15 +1,15 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id:Factory.scala 6853 2006-03-20 16:58:47 +0100 (Mon, 20 Mar 2006) dubochet $
 
 
-package scala.dbc.value;
+package scala.dbc
+package value;
 
 
 import java.math.BigInteger;
diff --git a/src/dbc/scala/dbc/value/Unknown.scala b/src/dbc/scala/dbc/value/Unknown.scala
index efcf98c..c4e9339 100644
--- a/src/dbc/scala/dbc/value/Unknown.scala
+++ b/src/dbc/scala/dbc/value/Unknown.scala
@@ -1,15 +1,15 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id:Unknown.scala 6853 2006-03-20 16:58:47 +0100 (Mon, 20 Mar 2006) dubochet $
 
 
-package scala.dbc.value;
+package scala.dbc
+package value;
 
 
 abstract class Unknown extends Value {
diff --git a/src/dbc/scala/dbc/vendor/PostgreSQL.scala b/src/dbc/scala/dbc/vendor/PostgreSQL.scala
index 1dc76f0..35e0f8f 100644
--- a/src/dbc/scala/dbc/vendor/PostgreSQL.scala
+++ b/src/dbc/scala/dbc/vendor/PostgreSQL.scala
@@ -1,15 +1,15 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id:PostgreSQL.scala 6853 2006-03-20 16:58:47 +0100 (Mon, 20 Mar 2006) dubochet $
 
 
-package scala.dbc.vendor;
+package scala.dbc
+package vendor;
 
 
 import compat.Platform
diff --git a/src/dotnet-library/README b/src/dotnet-library/README
deleted file mode 100644
index a85976c..0000000
--- a/src/dotnet-library/README
+++ /dev/null
@@ -1,78 +0,0 @@
-INFO: The dotnet-library tree has been synchronized with
-revision 15115 of src/library on $Date: 2008-05-21 14:33:42 +0200 (Wed, 21 May 2008) $.
-
-IMPORTANT:
-Never, never, never, ever add/remove/edit files in the dotnet-library
-tree by hand. If you need to change sth use the opportunity to merge
-the changes that have occured since the last merge. Any manual intervention
-makes the merging harder and is to be considerd rude and counterproductive.
-
-HOW TO MERGE:
-You can obtain the revision number of the last merge from the commit history
-of the tree. Or from the second line of this document. But you should
-always check to see if it is consistent with svn log messages.
-
-
-lamppc26:trunk luc$ svn log -r 15115 
-------------------------------------------------------------------------
-r15115 | rytz | 2008-05-20 16:57:39 +0200 (Tue, 20 May 2008) | 1 line
-
-Synced src/dotnet-library with rev 15086 of src/library
-------------------------------------------------------------------------
-
-
-Unless you have a specific revision in mind you can check the lates revision
-of the src/library tree with
-
-koko:~/scala>svn info src/library/
-Path: src/library
-URL: https://lampsvn.epfl.ch/svn-repos/scala/scala/trunk/src/library
-Repository Root: https://lampsvn.epfl.ch/svn-repos/scala
-Repository UUID: 5e8d7ff9-d8ef-0310-90f0-a4852d11357a
-Revision: 12880
-Node Kind: directory
-Schedule: normal
-Last Changed Author: mihaylov
-Last Changed Rev: 12880
-Last Changed Date: 2007-09-17 12:56:57 +0200 (Mon, 17 Sep 2007)
-
-
-From this we could figure out that we need to merge the changes that happened
-between revisions 12365 and 12880 of the src/library tree:
-
-koko:~/scala/src/dotnet-library>svn merge \
-https://lampsvn.epfl.ch/svn-repos/scala/scala/trunk/src/library@12365 \
-https://lampsvn.epfl.ch/svn-repos/scala/scala/trunk/src/library@12880 ./
-
-
-(note the ./ at the end of the line specifying the working copy)
-
-You'll get many "Skipped missing target: ..." messages because this tree
-only contains files that are different for MSIL. Hopefully, changes in those
-files do not introduce anything platform-specific because they will be copied
-from the src/library tree. If there are platform-specific changes, the
-offending file has to be added to the dotnet-library tree and modified to
-compile for .NET.
-
-When you have sorted out the conflicts (by means of manual editing and
-'svn resolved'), at the top project directory run
-
-ant msil
-
-to check, at the bare minimum, whether the MSIL subset of the library compiles.
-If this is fine, you can commit your changes but make sure that in the commit
-message you
-
- INCLUDE THE REVISION NUMBER WITH WHICH YOU HAVE MERGED!!!!
-
-This is very important because subversion will not keep it for you. And this
-number is absilutely necessary for the next merge. Also, you should update
-the revision number in this document for consistency.
-
-koko:~/scala/src/dotnet-library>svn ci -m "Synced src/dotnet-library with rev 12880 of src/library"
-Adding         dotnet-library/README
-Sending        dotnet-library/scala/Predef.scala
-Sending        dotnet-library/scala/Random.scala
-Sending        dotnet-library/scala/runtime/RichString.scala
-Transmitting file data ....
-Committed revision 12881.
diff --git a/src/dotnet-library/scala/Application.scala b/src/dotnet-library/scala/Application.scala
deleted file mode 100644
index 7b11e94..0000000
--- a/src/dotnet-library/scala/Application.scala
+++ /dev/null
@@ -1,61 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: Application.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala
-
-//import java.lang.System.getProperty
-//import scala.compat.Platform.currentTime
-
-/** <p>
- *    The <code>Application</code> class can be used to quickly turn objects
- *    into executable programs. Here is an example:
- *  </p><pre>
- *  object Main with Application {
- *    Console.println("Hello World!");
- *  }
- *  </pre>
- *  <p>
- *    Here, object <code>Main</code> inherits the <code>main</code> method
- *    of <code>Application</code>. The body of the <code>Main</code> object
- *    defines the main program. This technique does not work if the main
- *    program depends on command-line arguments (which are not accessible
- *    with the technique presented here).
- *  </p>
- *  <p>
- *    It is possible to time the execution of objects that inherit from class
- *    <code>Application</code> by setting the global <code>scala.time</code>
- *    property. Here is an example for benchmarking object <code>Main</code>:
- *  </p><pre>
- *  java -Dscala.time Main
- *  </pre>
- *
- *  @author  Matthias Zenger
- *  @version 1.0, 10/09/2003
- */
-
-trait Application {
-
-    /** The time when execution of this program started.
-     */
-//    val executionStart: Long = currentTime
-
-  /** The default main method.
-   *
-   *  @param args the arguments passed to the main method
-   */
-  def main(args: Array[String]) = {
-//     if (getProperty("scala.time") ne null) {
-//       val total = currentTime - executionStart
-//       Console.println("[total " + total + "ms]")
-//     }
-  }
-
-}
diff --git a/src/dotnet-library/scala/BigDecimal.scala b/src/dotnet-library/scala/BigDecimal.scala
deleted file mode 100644
index dffcaf8..0000000
--- a/src/dotnet-library/scala/BigDecimal.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* BigDecimal.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/BigInt.scala b/src/dotnet-library/scala/BigInt.scala
deleted file mode 100644
index 192d2ad..0000000
--- a/src/dotnet-library/scala/BigInt.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* BigInt does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/Console.scala b/src/dotnet-library/scala/Console.scala
deleted file mode 100644
index b327b86..0000000
--- a/src/dotnet-library/scala/Console.scala
+++ /dev/null
@@ -1,308 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: Console.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala
-
-
-import System.IO.{TextReader,TextWriter}
-
-import scala.util.DynamicVariable
-import Predef._
-
-
-/** The <code>Console</code> object implements functionality for
- *  printing Scala values on the terminal. There are also functions
- *  for reading specific values. <code>Console</code> also defines
- *  constants for marking up text on ANSI terminals.
- *
- *  @author  Matthias Zenger
- *  @version 1.0, 03/09/2003
- */
-object Console {
-
-  // ANSI colors foreground
-  final val BLACK      = "\033[30m"
-  final val RED        = "\033[31m"
-  final val GREEN      = "\033[32m"
-  final val YELLOW     = "\033[33m"
-  final val BLUE       = "\033[34m"
-  final val MAGENTA    = "\033[35m"
-  final val CYAN       = "\033[36m"
-  final val WHITE      = "\033[37m"
-
-  // ANSI colors background
-  final val BLACK_B    = "\033[40m"
-  final val RED_B      = "\033[41m"
-  final val GREEN_B    = "\033[42m"
-  final val YELLOW_B   = "\033[43m"
-  final val BLUE_B     = "\033[44m"
-  final val MAGENTA_B  = "\033[45m"
-  final val CYAN_B     = "\033[46m"
-  final val WHITE_B    = "\033[47m"
-
-  // ANSI styles
-  final val RESET      = "\033[0m"
-  final val BOLD       = "\033[1m"
-  final val UNDERLINED = "\033[4m"
-  final val BLINK      = "\033[5m"
-  final val REVERSED   = "\033[7m"
-  final val INVISIBLE  = "\033[8m"
-
-  private val outVar = new DynamicVariable[TextWriter](System.Console.Out)
-  private val inVar  = new DynamicVariable[TextReader](System.Console.In)
-
-  def out = outVar.value
-  def in = inVar.value
-
-  /** Set the default output stream.
-   *
-   *  @param out the new output stream.
-   */
-  def setOut(out: TextWriter) { outVar.value = out }
-
-  /** Set the default output stream for the duration
-   *  of execution of one thunk.
-   *
-   *  @param out the new output stream.
-   *  @param thunk the code to execute with
-   *               the new output stream active
-   */
-  def withOut[T](out: TextWriter)(thunk: =>T): T =
-    outVar.withValue(out)(thunk)
-
-
-  /** Set the default input stream.
-   *
-   *  @param reader specifies the new input stream.
-   */
-  def setIn(reader: TextReader): Unit = {
-    inVar.value = reader
-  }
-
-  /** Set the default input stream for the duration
-   *  of execution of one thunk.
-   *
-   *  @param in the new input stream.
-   *  @param thunk the code to execute with
-   *               the new input stream active
-   */
-  def withIn[T](reader: TextReader)(thunk: =>T): T =
-    inVar.withValue(reader)(thunk)
-
-  /** Print an object on the terminal.
-   *
-   *  @param obj the object to print.
-   */
-  def print(obj: Any): Unit =
-    out.Write(if (null == obj) "null" else obj.toString())
-
-  /** Flush the output stream. This function is required when partial
-   *  output (i.e. output not terminated by a new line character) has
-   *  to be made visible on the terminal.
-   */
-  def flush() { out.Flush() }
-
-  /** Print a new line character on the terminal.
-   */
-  def println(): Unit = out.WriteLine()
-
-  /** Print out an object followed by a new line character.
-   *
-   *  @param x the object to print.
-   */
-  def println(x: Any): Unit = out.WriteLine(x)
-
-  /** <p>
-   *    Prints its arguments as a formatted string, based on a string
-   *    pattern (in a fashion similar to printf in C).
-   *  </p>
-   *  <p>
-   *    The interpretation of the formatting patterns is described in
-   *    <a href="" target="contentFrame" class="java/util/Formatter">
-   *    <code>java.util.Formatter</code></a>.
-   *  </p>
-   *
-   *  @param text the pattern for formatting the arguments.
-   *  @param args the arguments used to instantiating the pattern.
-   *  @throws java.lang.IllegalArgumentException
-   */
-  def printf(text: String, args: Any*) { format(text, args: _*) }
-
-  /**
-   *  @see <a href="#printf(java.lang.String,scala.Any*)"
-   *       target="contentFrame">Console.printf</a>.
-   */
-  def format(text: String, args: Any*): Unit =
-    if (text eq null) out.Write("null")
-    else out.Write(text, args.toArray)
-
-  /** Read a full line from the terminal.  Throws System.IO.EndOfStreamException if the end of the 
-   * input stream has been reached.
-   *
-   * @return the string read from the terminal.
-   * @throws System.IO.EndOfStreamException
-   */
-  def readLine(): String = {
-	val s = in.ReadLine()
-	if (s == null) throw new System.IO.EndOfStreamException("Console has reached end of input") else s
-  }
-
-  /** Print a formatted text and read a full line from the terminal.  
-   * Returns null if the end of the input stream has been reached.
-   *
-   *  @param text the format of the text to print out.
-   *  @param args the parameters used to instantiate the format.
-   *  @return the string read from the terminal.
-   */
-  def readLine(text: String, args: Any*): String = {
-    format(text, args: _*)
-    readLine()
-  }
-
-
-  /** Read a boolean value from the terminal.
-   *
-   *  @return the boolean value read from the terminal.
-   */
-  def readBoolean(): Boolean = readLine().toLowerCase() match {
-    case "true" => true
-    case "t" => true
-    case "yes" => true
-    case "y" => true
-    case _ => false
-  }
-
-  /** Read a byte value from the terminal.
-   */
-  def readByte(): Byte = readLine().toByte
-
-  /** Read a short value from the terminal.
-   */
-  def readShort(): Short = readLine().toShort
-
-  /** Read a char value from the terminal.
-   */
-  def readChar(): Char = readLine() charAt 0
-
-  /** Read an int value from the terminal.
-   */
-  def readInt(): Int = readLine().toInt
-
-  /** Read an int value from the terminal.
-   */
-  def readLong(): Long = readLine().toLong
-
-  /** Read a float value from the terminal.
-   */
-  def readFloat(): Float = readLine().toFloat
-
-  /** Read a double value from the terminal.
-   */
-  def readDouble(): Double = readLine().toDouble
-
-//   /** Read in some structured input, specified by a format specifier.
-//    *  See class <code>java.text.MessageFormat</code> for details of
-//    *  the format specification.
-//    *
-//    *  @param format the format of the input.
-//    *  @return a list of all extracted values.
-//    */
-//   def readf(format: String): List[Any] =
-//     textComponents(new MessageFormat(format).parse(readLine()))
-
-//   /** Read in some structured input, specified by a format specifier.
-//    *  Opposed to <code>readf</code>, this function only returns the
-//    *  first value extracted from the input according to the format
-//    *  specification.
-//    *
-//    *  @param format ...
-//    *  @return ...
-//    */
-//   def readf1(format: String): Any = readf(format).head
-
-//   /** Read in some structured input, specified by a format specifier.
-//    *  Opposed to <code>readf</code>, this function only returns the
-//    *  first two values extracted from the input according to the format
-//    *  specification.
-//    *
-//    *  @param format ...
-//    *  @return ...
-//    */
-//   def readf2(format: String): (Any, Any) = {
-//     val res = readf(format)
-//     (res.head, res.tail.head)
-//   }
-
-//   /** Read in some structured input, specified by a format specifier.
-//    *  Opposed to <code>readf</code>, this function only returns the
-//    *  first three values extracted from the input according to the format
-//    *  specification.
-//    *
-//    *  @param format ...
-//    *  @return ...
-//    */
-//   def readf3(format: String): (Any, Any, Any) = {
-//     val res = readf(format)
-//     (res.head, res.tail.head, res.tail.tail.head)
-//   }
-
-//   private def textComponents(a: Array[AnyRef]): List[Any] = {
-//     var i: Int = a.length - 1
-//     var res: List[Any] = Nil
-//     while (i >= 0) {
-//       res = (a(i) match {
-//         case x: java.lang.Boolean => x.booleanValue()
-//         case x: java.lang.Byte => x.byteValue()
-//         case x: java.lang.Short => x.shortValue()
-//         case x: java.lang.Character => x.charValue()
-//         case x: java.lang.Integer => x.intValue()
-//         case x: java.lang.Long => x.longValue()
-//         case x: java.lang.Float => x.floatValue()
-//         case x: java.lang.Double => x.doubleValue()
-//         case x => x
-//       }) :: res;
-//       i = i - 1
-//     }
-//     res
-//   }
-
-//  private def textParams(s: Seq[Any]): Array[AnyRef] = {
-//    val res = new Array[AnyRef](s.length)
-//    var i: Int = 0
-//    val iter = s.elements
-//    while (iter.hasNext) {
-//      res(i) = iter.next match {
-//        case x: Boolean => java.lang.Boolean.valueOf(x)
-//        /** Should use java.lang.Byte.valueOf(Byte), but only available
-//         * in Java 1.5 and above. */
-//        case x: Byte    => new java.lang.Byte(x)
-//        /** Should use java.lang.Short.valueOf(Short), but only available
-//         * in Java 1.5 and above. */
-//        case x: Short   => new java.lang.Short(x)
-//        /** Should use java.lang.Character.valueOf(Char), but only available
-//         * in Java 1.5 and above. */
-//        case x: Char    => new java.lang.Character(x)
-//        /** Should use java.lang.Integer.valueOf(Int), but only available
-//         * in Java 1.5 and above. */
-//        case x: Int     => new java.lang.Integer(x)
-//        /** Should use java.lang.Long.valueOf(Long), but only available
-//         * in Java 1.5 and above. */
-//        case x: Long    => new java.lang.Long(x)
-//        case x: Float   => new java.lang.Float(x)
-//        case x: Double  => new java.lang.Double(x)
-//        case x: Unit    => "()"
-//        case x: AnyRef  => x
-//      }
-//      i += 1
-//    }
-//    res
-//  }
-}
diff --git a/src/dotnet-library/scala/List.scala b/src/dotnet-library/scala/List.scala
deleted file mode 100644
index 33e7e63..0000000
--- a/src/dotnet-library/scala/List.scala
+++ /dev/null
@@ -1,1362 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: List.scala 16881 2009-01-09 16:28:11Z cunei $
-
-
-package scala
-
-import scala.collection.mutable.ListBuffer
-import Predef._
-
-/** This object provides methods for creating specialized lists, and for
- *  transforming special kinds of lists (e.g. lists of lists).
- *
- *  @author  Martin Odersky and others
- *  @version 1.0, 15/07/2003
- */
-object List {
-
-  /** Create a list with given elements.
-   *
-   *  @param xs the elements to put in the list
-   *  @return the list containing elements xs.
-   */
-  def apply[A](xs: A*): List[A] = xs.toList
-
-  /** for unapply matching
-   */
-  def unapplySeq[A](x: List[A]): Some[List[A]] = Some(x)
-
-  /** Create a sorted list of all integers in a range.
-   *
-   *  @param from the start value of the list
-   *  @param end the end value of the list
-   *  @return the sorted list of all integers in range [from;end).
-   */
-  def range(start: Int, end: Int): List[Int] =
-    range(start, end, 1)
-
-  /** Create a list with element values
-   * <code>v<sub>n+1</sub> = v<sub>n</sub> + step</code>
-   * where <code>v<sub>0</sub> = start</code>
-   * and elements are in the range between <code>start</code> (inclusive)
-   * and <code>end</code> (exclusive)
-   *
-   *  @param start the start value of the list
-   *  @param end  the end value of the list
-   *  @param step the increment value of the list
-   *  @return     the sorted list of all integers in range [start;end).
-   */
-  def range(start: Int, end: Int, step: Int): List[Int] = {
-    val b = new ListBuffer[Int]
-    var i = start
-    while ((step <= 0 || i < end) && (step >= 0 || i > end)) {
-      b += i
-      i += step
-    }
-    b.toList
-  }
-
-  /** Create a sorted list with element values
-   * <code>v<sub>n+1</sub> = step(v<sub>n</sub>)</code>
-   * where <code>v<sub>0</sub> = start</code>
-   * and elements are in the range between <code>start</code> (inclusive)
-   * and <code>end</code> (exclusive)
-   *
-   *  @param start the start value of the list
-   *  @param end  the end value of the list
-   *  @param step the increment function of the list, must be monotonically increasing or decreasing
-   *  @return     the sorted list of all integers in range [start;end).
-   */
-  def range(start: Int, end: Int, step: Int => Int): List[Int] = {
-    val up = step(start) > start
-    val down = step(start) < start
-    val b = new ListBuffer[Int]
-    var i = start
-    while ((!up || i < end) && (!down || i > end)) {
-      b += i
-      i += step(i)
-    }
-    b.toList
-  }
-
-  /** Create a list containing several copies of an element.
-   *
-   *  @param n    the length of the resulting list
-   *  @param elem the element composing the resulting list
-   *  @return     a list composed of n elements all equal to elem
-   */
-  def make[A](n: Int, elem: A): List[A] = {
-    val b = new ListBuffer[A]
-    var i = 0
-    while (i < n) {
-      b += elem
-      i += 1
-    }
-    b.toList
-  }
-
-  /** Create a list by applying a function to successive integers.
-   *
-   *  @param n     the length of the resulting list
-   *  @param maker the procedure which, given an integer <code>n</code>,
-   *               returns the nth element of the resulting list, where
-   *               <code>n</code> is in interval <code>[0;n)</code>.
-   *  @return      the list obtained by applying the maker function to
-   *               successive integers from 0 to n (exclusive).
-   */
-  def tabulate[A](n: Int, maker: Int => A): List[A] = {
-    val b = new ListBuffer[A]
-    var i = 0
-    while (i < n) {
-      b += maker(i)
-      i += 1
-    }
-    b.toList
-  }
-
-  /** Concatenate all the elements of a given list of lists.
-   *
-   *  @param xss the list of lists that are to be concatenated
-   *  @return    the concatenation of all the lists
-   */
-  def flatten[A](xss: List[List[A]]): List[A] = concat(xss: _*)
-
-  /** Concatenate all the argument lists into a single list.
-   *
-   *  @param xss the lists that are to be concatenated
-   *  @return the concatenation of all the lists
-   */
-  def concat[A](xss: List[A]*): List[A] = { 
-    val b = new ListBuffer[A] 
-    for (xs <- xss) {
-      var xc = xs
-      while (!xc.isEmpty) {
-        b += xc.head
-        xc = xc.tail
-      }
-    }
-    b.toList
-  }
-
-  /** Transforms a list of pairs into a pair of lists.
-   *
-   *  @param xs the list of pairs to unzip
-   *  @return a pair of lists.
-   */
-  def unzip[A,B](xs: List[(A,B)]): (List[A], List[B]) = {
-    val b1 = new ListBuffer[A]
-    val b2 = new ListBuffer[B]
-    var xc = xs
-    while (!xc.isEmpty) {
-      b1 += xc.head._1
-      b2 += xc.head._2
-      xc = xc.tail
-    }
-    (b1.toList, b2.toList)
-  }
-
-  /** Transforms an iterable of pairs into a pair of lists.
-   *
-   *  @param xs the iterable of pairs to unzip
-   *  @return a pair of lists.
-   */
-  def unzip[A,B](xs: Iterable[(A,B)]): (List[A], List[B]) = 
-      xs.foldRight[(List[A], List[B])]((Nil, Nil)) {
-        case ((x, y), (xs, ys)) => (x :: xs, y :: ys)
-      }
-
-  /** 
-   * Returns the <code>Left</code> values in the given <code>Iterable</code> of <code>Either</code>s.
-   */ 
-  def lefts[A, B](es: Iterable[Either[A, B]]) = 
-    es.foldRight[List[A]](Nil)((e, as) => e match {
-      case Left(a) => a :: as
-      case Right(_) => as
-    })     
- 
-  /** 
-   * Returns the <code>Right</code> values in the given<code>Iterable</code> of  <code>Either</code>s.
-   */      
-  def rights[A, B](es: Iterable[Either[A, B]]) = 
-    es.foldRight[List[B]](Nil)((e, bs) => e match {
-      case Left(_) => bs
-      case Right(b) => b :: bs
-    })
-
-  /** Transforms an Iterable of Eithers into a pair of lists.
-   *
-   *  @param xs the iterable of Eithers to separate
-   *  @return a pair of lists.
-   */
-  def separate[A,B](es: Iterable[Either[A,B]]): (List[A], List[B]) =
-      es.foldRight[(List[A], List[B])]((Nil, Nil)) {
-      case (Left(a), (lefts, rights)) => (a :: lefts, rights)
-      case (Right(b), (lefts, rights)) => (lefts, b :: rights)
-    }
-
-  /** Converts an iterator to a list.
-   *
-   *  @param it the iterator to convert
-   *  @return   a list that contains the elements returned by successive
-   *            calls to <code>it.next</code>
-   */
-  def fromIterator[A](it: Iterator[A]): List[A] = it.toList
-
-  /** Converts an array into a list.
-   *
-   *  @param arr the array to convert
-   *  @return    a list that contains the same elements than <code>arr</code>
-   *             in the same order
-   */
-  def fromArray[A](arr: Array[A]): List[A] = fromArray(arr, 0, arr.length)
-
-  /** Converts a range of an array into a list.
-   *
-   *  @param arr   the array to convert
-   *  @param start the first index to consider
-   *  @param len   the lenght of the range to convert
-   *  @return      a list that contains the same elements than <code>arr</code>
-   *               in the same order
-   */
-  def fromArray[A](arr: Array[A], start: Int, len: Int): List[A] = {
-    var res: List[A] = Nil
-    var i = start + len
-    while (i > start) {
-      i -= 1
-      res = arr(i) :: res
-    }
-    res
-  }
-
-  /** Parses a string which contains substrings separated by a
-   *  separator character and returns a list of all substrings.
-   *
-   *  @param str       the string to parse
-   *  @param separator the separator character
-   *  @return          the list of substrings
-   */
-  def fromString(str: String, separator: Char): List[String] = {
-    var words: List[String] = Nil
-    var pos = str.length()
-    while (pos > 0) {
-      val pos1 = str.lastIndexOf(separator, pos - 1)
-      if (pos1 + 1 < pos)
-        words = str.substring(pos1 + 1, pos) :: words
-      pos = pos1
-    }
-    words
-  }
-
-  /** Returns the given string as a list of characters.
-   *
-   *  @param str the string to convert.
-   *  @return    the string as a list of characters.
-   *  @deprecated use <code>str.toList</code> instead
-   */
-  @deprecated def fromString(str: String): List[Char] =
-    str.toList
-
-  /** Returns the given list of characters as a string.
-   *
-   *  @param xs the list to convert.
-   *  @return   the list in form of a string.
-   */
-  def toString(xs: List[Char]): String = {
-    val sb = new StringBuilder()
-    var xc = xs
-    while (!xc.isEmpty) {
-      sb.append(xc.head)
-      xc = xc.tail
-    }
-    sb.toString()
-  }
-
-  /** Like xs map f, but returns <code>xs</code> unchanged if function
-   *  <code>f</code> maps all elements to themselves.
-   *
-   *  @param xs ...
-   *  @param f  ...
-   *  @return   ...
-   */
-  def mapConserve[A <: AnyRef](xs: List[A])(f: A => A): List[A] = {
-    def loop(ys: List[A]): List[A] =
-      if (ys.isEmpty) xs
-      else {
-        val head0 = ys.head
-        val head1 = f(head0)
-        if (head1 eq head0) {
-          loop(ys.tail)
-        } else {
-          val ys1 = head1 :: mapConserve(ys.tail)(f)
-          if (xs eq ys) ys1
-          else {
-            val b = new ListBuffer[A]
-            var xc = xs
-            while (xc ne ys) {
-              b += xc.head
-              xc = xc.tail
-            }
-            b.prependToList(ys1)
-          }
-        }
-      }
-    loop(xs)
-  }
-
-  /** Returns the list resulting from applying the given function <code>f</code>
-   *  to corresponding elements of the argument lists.
-   *
-   *  @param f function to apply to each pair of elements.
-   *  @return <code>[f(a0,b0), ..., f(an,bn)]</code> if the lists are 
-   *          <code>[a0, ..., ak]</code>, <code>[b0, ..., bl]</code> and
-   *          <code>n = min(k,l)</code>
-   */
-  def map2[A,B,C](xs: List[A], ys: List[B])(f: (A, B) => C): List[C] = {
-    val b = new ListBuffer[C]
-    var xc = xs
-    var yc = ys
-    while (!xc.isEmpty && !yc.isEmpty) {
-      b += f(xc.head, yc.head)
-      xc = xc.tail
-      yc = yc.tail
-    }
-    b.toList
-  }
-
-  /** Returns the list resulting from applying the given function
-   *  <code>f</code> to corresponding elements of the argument lists.
-   *
-   *  @param f function to apply to each pair of elements.
-   *  @return  <code>[f(a<sub>0</sub>,b<sub>0</sub>,c<sub>0</sub>),
-   *           ..., f(a<sub>n</sub>,b<sub>n</sub>,c<sub>n</sub>)]</code>
-   *           if the lists are <code>[a<sub>0</sub>, ..., a<sub>k</sub>]</code>,
-   *           <code>[b<sub>0</sub>, ..., b<sub>l</sub>]</code>,
-   *           <code>[c<sub>0</sub>, ..., c<sub>m</sub>]</code> and
-   *           <code>n = min(k,l,m)</code>
-   */
-  def map3[A,B,C,D](xs: List[A], ys: List[B], zs: List[C])(f: (A, B, C) => D): List[D] = {
-    val b = new ListBuffer[D]
-    var xc = xs
-    var yc = ys
-    var zc = zs
-    while (!xc.isEmpty && !yc.isEmpty && !zc.isEmpty) {
-      b += f(xc.head, yc.head, zc.head)
-      xc = xc.tail
-      yc = yc.tail
-      zc = zc.tail
-    }
-    b.toList
-  }
-
-  /** Tests whether the given predicate <code>p</code> holds 
-   *  for all corresponding elements of the argument lists.
-   *
-   *  @param p function to apply to each pair of elements.
-   *  @return  <code>(p(a<sub>0</sub>,b<sub>0</sub>) &&
-   *           ... && p(a<sub>n</sub>,b<sub>n</sub>))]</code>
-   *           if the lists are <code>[a<sub>0</sub>, ..., a<sub>k</sub>]</code>;
-   *           <code>[b<sub>0</sub>, ..., b<sub>l</sub>]</code>
-   *           and <code>n = min(k,l)</code>
-   */
-  def forall2[A,B](xs: List[A], ys: List[B])(f: (A, B) => Boolean): Boolean = {
-    var xc = xs
-    var yc = ys
-    while (!xc.isEmpty && !yc.isEmpty) {
-      if (!f(xc.head, yc.head)) return false
-      xc = xc.tail
-      yc = yc.tail
-    }
-    true
-  }
-
-  /** Tests whether the given predicate <code>p</code> holds
-   *  for some corresponding elements of the argument lists.
-   *
-   *  @param p function to apply to each pair of elements.
-   *  @return  <code>n != 0 && (p(a<sub>0</sub>,b<sub>0</sub>) ||
-   *           ... || p(a<sub>n</sub>,b<sub>n</sub>))]</code> if the lists are
-   *           <code>[a<sub>0</sub>, ..., a<sub>k</sub>]</code>,
-   *           <code>[b<sub>0</sub>, ..., b<sub>l</sub>]</code> and
-   *           <code>n = min(k,l)</code>
-   */
-  def exists2[A,B](xs: List[A], ys: List[B])(f: (A, B) => Boolean): Boolean = {
-    var xc = xs
-    var yc = ys
-    while (!xc.isEmpty && !yc.isEmpty) {
-      if (f(xc.head, yc.head)) return true
-      xc = xc.tail
-      yc = yc.tail
-    }
-    false
-  }
-
-  /** Transposes a list of lists.
-   *  pre: All element lists have the same length.
-   *
-   *  @param xss the list of lists
-   *  @return    the transposed list of lists
-   */
-  def transpose[A](xss: List[List[A]]): List[List[A]] = {
-    val buf = new ListBuffer[List[A]]
-    var yss = xss
-    while (!yss.head.isEmpty) {
-      buf += (yss map (_.head))
-      yss = (yss map (_.tail))
-    }
-    buf.toList
-  }
-
-  /** Lists with ordered elements are ordered
-  implicit def list2ordered[a <% Ordered[a]](x: List[a]): Ordered[List[a]] = new Ordered[List[a]] {
-    def compare [b >: List[a] <% Ordered[b]](y: b): Int = y match {
-      case y1: List[a] => compareLists(x, y1);
-      case _ => -(y compare x)
-    }
-    private def compareLists(xs: List[a], ys: List[a]): Int = {
-      if (xs.isEmpty && ys.isEmpty) 0
-      else if (xs.isEmpty) -1
-      else if (ys.isEmpty) 1
-      else {
-        val s = xs.head compare ys.head;
-        if (s != 0) s
-        else compareLists(xs.tail, ys.tail)
-      }
-    }
-  }
-   */
-}
-
-/** A class representing an ordered collection of elements of type
- *  <code>a</code>. This class comes with two implementing case
- *  classes <code>scala.Nil</code> and <code>scala.::</code> that
- *  implement the abstract members <code>isEmpty</code>,
- *  <code>head</code> and <code>tail</code>.
- *
- *  @author  Martin Odersky and others
- *  @version 1.0, 16/07/2003
- */
-sealed abstract class List[+A] extends Seq[A] {
-
-  /** Returns true if the list does not contain any elements.
-   *  @return <code>true</code>, iff the list is empty.
-   */
-  override def isEmpty: Boolean
-
-  /** Returns this first element of the list.
-   *
-   *  @return the first element of this list.
-   *  @throws Predef.NoSuchElementException if the list is empty.
-   */
-  def head: A
-
-  /** returns length - l, without calling length
-   */
-  override def lengthCompare(l: Int) = {
-    if (isEmpty) 0 - l
-    else if (l <= 0) 1
-    else tail.lengthCompare(l - 1)
-  }
-
-  /** Returns this list without its first element.
-   *
-   *  @return this list without its first element.
-   *  @throws Predef.NoSuchElementException if the list is empty.
-   */
-  def tail: List[A]
-
-  /** <p>
-   *    Add an element <code>x</code> at the beginning of this list.
-   *  </p>
-   *
-   *  @param x the element to prepend.
-   *  @return  the list with <code>x</code> added at the beginning.
-   *  @ex <code>1 :: List(2, 3) = List(2, 3).::(1) = List(1, 2, 3)</code>
-   */
-  def ::[B >: A] (x: B): List[B] =
-    new scala.::(x, this)
-
-  /** <p>
-   *    Add an element <code>x</code> at the end of this list.
-   *  </p>
-   *
-   *  @deprecated Replace uses of <code>l + e</code> with <code>l ::: List(e)</code>.
-   * 
-   *  @param x the element to append.
-   *  @return  the list with <code>x</code> added at the end.
-   */
-  @deprecated def +[B >: A](x: B): List[B] =
-    if (isEmpty) List(x)
-    else {
-      val buf = new ListBuffer[B]
-      this copyToBuffer buf
-      buf += x
-      buf.toList
-    }
-
-  /** <p>
-   *    Returns a list resulting from the concatenation of the given
-   *    list <code>prefix</code> and this list. 
-   *  </p>
-   *
-   *  @param prefix the list to concatenate at the beginning of this list.
-   *  @return the concatenation of the two lists.
-   *  @ex <code>List(1, 2) ::: List(3, 4) = List(3, 4).:::(List(1, 2)) = List(1, 2, 3, 4)</code>
-   */
-  def :::[B >: A](prefix: List[B]): List[B] =
-    if (isEmpty) prefix
-    else {
-      val b = new ListBuffer[B]
-      var those = prefix
-      while (!those.isEmpty) {
-        b += those.head
-        those = those.tail
-      }
-      b.prependToList(this)
-    }
-
-  /** Appends two list objects.
-   */
-  override def ++[B >: A](that: Iterable[B]): List[B] = {
-    val buf = new ListBuffer[B]
-    this copyToBuffer buf
-    that copyToBuffer buf
-    buf.toList
-  }
-
-  /** Reverse the given prefix and append the current list to that.
-   *  This function is equivalent to an application of <code>reverse</code>
-   *  on the prefix followed by a call to <code>:::</code>, but more
-   *  efficient (and tail recursive).
-   *
-   *  @param prefix the prefix to reverse and then prepend
-   *  @return       the concatenation of the reversed prefix and the current list.
-   */
-  def reverse_:::[B >: A](prefix: List[B]): List[B] = {
-    var these: List[B] = this
-    var pres = prefix
-    while (!pres.isEmpty) {
-      these = pres.head :: these
-      pres = pres.tail
-    }
-    these
-  }
-
-  /** Returns the number of elements in the list.
-   *
-   *  @return the number of elements in the list.
-   */
-  def length: Int = {
-    var these = this
-    var len = 0
-    while (!these.isEmpty) {
-      len += 1
-      these = these.tail
-    }
-    len
-  }
-
-  /** Creates a list with all indices in the list. This is
-   *  equivalent to a call to <code>List.range(0, xs.length)</code>.
-   *
-   *  @return a list of all indices in the list.
-   */
-  def indices: List[Int] = {
-    val b = new ListBuffer[Int]
-    var i = 0
-    var these = this
-    while (!these.isEmpty) {
-      b += i
-      i += 1
-      these = these.tail
-    }
-    b.toList
-  }
- 
-  /** Returns the elements in the list as an iterator
-   *
-   *  @return an iterator on the list elements.
-   */
-  override def elements: Iterator[A] = new Iterator[A] {
-    var these = List.this
-    def hasNext: Boolean = !these.isEmpty
-    def next: A =
-      if (!hasNext)
-        throw new NoSuchElementException("next on empty Iterator")
-      else {
-        val result = these.head; these = these.tail; result
-      }
-    override def toList: List[A] = these
-  }
-
-  /** Overrides the method in Iterable for efficiency.
-   *
-   *  @return  the list itself
-   */
-  override def toList: List[A] = this
-
-  /** Returns the list without its last element.
-   *
-   *  @return the list without its last element.
-   *  @throws Predef.UnsupportedOperationException if the list is empty.
-   */
-  def init: List[A] =
-    if (isEmpty) throw new UnsupportedOperationException("Nil.init")
-    else {
-      val b = new ListBuffer[A]
-      var elem = head
-      var next = tail
-      while (!next.isEmpty) {
-        b += elem
-        elem = next.head
-        next = next.tail
-      }
-      b.toList
-    }
-
-  /** Returns the last element of this list.
-   *
-   *  @return the last element of the list.
-   *  @throws Predef.NoSuchElementException if the list is empty.
-   */
-  override def last: A =
-    if (isEmpty) throw new Predef.NoSuchElementException("Nil.last")
-    else {
-      var cur = this
-      var next = this.tail
-      while (!next.isEmpty) {
-        cur = next
-        next = next.tail
-      }
-      cur.head
-    }
-
-  /** Returns the <code>n</code> first elements of this list, or else the whole 
-   *  list, if it has less than <code>n</code> elements.
-   *
-   *  @param n the number of elements to take.
-   *  @return the <code>n</code> first elements of this list.
-   */
-  override def take(n: Int): List[A] = {
-    val b = new ListBuffer[A]
-    var i = 0
-    var these = this
-    while (!these.isEmpty && i < n) {
-      i += 1
-      b += these.head
-      these = these.tail
-    }
-    if (these.isEmpty) this
-    else b.toList
-  }
-
-  /** Returns the list with elements belonging to the given index range.
-   *
-   *  @param start the start position of the list slice.
-   *  @param end   the end position (exclusive) of the list slice.
-   *  @return the list with elements belonging to the given index range.
-   */
-  override def slice(start: Int, end: Int): List[A] = {
-    val s = start max 0
-    val e = end min this.length
-    drop(s) take (e - s)
-  }
-
-  /** Returns the list without its <code>n</code> first elements.
-   *  If this list has less than <code>n</code> elements, the empty list is returned.
-   *
-   *  @param n the number of elements to drop.
-   *  @return the list without its <code>n</code> first elements.
-   */
-  override def drop(n: Int): List[A] = {
-    var these = this
-    var count = n
-    while (!these.isEmpty && count > 0) {
-      these = these.tail
-      count -= 1
-    }
-    these
-  }
-
-  /** Returns the rightmost <code>n</code> elements from this list.
-   *
-   *  @param n the number of elements to take
-   *  @return the suffix of length <code>n</code> of the list
-   */
-  def takeRight(n: Int): List[A] = {
-    def loop(lead: List[A], lag: List[A]): List[A] = lead match {
-      case Nil => lag
-      case _ :: tail => loop(tail, lag.tail)
-    }
-    loop(drop(n), this)
-  }
-
-  /** Returns the list wihout its rightmost <code>n</code> elements.
-   *
-   *  @param n the number of elements to take
-   *  @return the suffix of length <code>n</code> of the list
-   */
-  def dropRight(n: Int): List[A] = {
-    def loop(lead: List[A], lag: List[A]): List[A] = lead match {
-      case Nil => Nil
-      case _ :: tail => lag.head :: loop(tail, lag.tail)
-    }
-    loop(drop(n), this)
-  }
-
-  /** Split the list at a given point and return the two parts thus
-   *  created.
-   *
-   *  @param n the position at which to split
-   *  @return  a pair of lists composed of the first <code>n</code>
-   *           elements, and the other elements.
-   */
-  def splitAt(n: Int): (List[A], List[A]) = {
-    val b = new ListBuffer[A]
-    var i = 0
-    var these = this
-    while (!these.isEmpty && i < n) {
-      i += 1
-      b += these.head
-      these = these.tail
-    }
-    (b.toList, these)
-  }
-
-  /** Returns the longest prefix of this list whose elements satisfy
-   *  the predicate <code>p</code>.
-   *
-   *  @param p the test predicate.
-   *  @return  the longest prefix of this list whose elements satisfy
-   *           the predicate <code>p</code>.
-   */
-  override def takeWhile(p: A => Boolean): List[A] = {
-    val b = new ListBuffer[A]
-    var these = this
-    while (!these.isEmpty && p(these.head)) {
-      b += these.head
-      these = these.tail
-    }
-    b.toList
-  }
-
-  /** Returns the longest suffix of this list whose first element
-   *  does not satisfy the predicate <code>p</code>.
-   *
-   *  @param p the test predicate.
-   *  @return  the longest suffix of the list whose first element
-   *           does not satisfy the predicate <code>p</code>.
-   */
-  override def dropWhile(p: A => Boolean): List[A] =
-    if (isEmpty || !p(head)) this
-    else tail dropWhile p
-
-  /** Returns the longest prefix of the list whose elements all satisfy
-   *  the given predicate, and the rest of the list.
-   *
-   *  @param p the test predicate
-   *  @return  a pair consisting of the longest prefix of the list whose
-   *           elements all satisfy <code>p</code>, and the rest of the list.
-   */
-  def span(p: A => Boolean): (List[A], List[A]) = {
-    val b = new ListBuffer[A]
-    var these = this
-    while (!these.isEmpty && p(these.head)) {
-      b += these.head
-      these = these.tail
-    }
-    (b.toList, these)
-  }
-
-  /** Like <code>span</code> but with the predicate inverted.
-   */
-  def break(p: A => Boolean): (List[A], List[A]) = span { x => !p(x) }
-
-  /** Returns the <code>n</code>-th element of this list. The first element
-   *  (head of the list) is at position 0.
-   *
-   *  @param n index of the element to return
-   *  @return  the element at position <code>n</code> in this list.
-   *  @throws Predef.NoSuchElementException if the list is too short.
-   */
-  def apply(n: Int): A = drop(n).head
-
-  /** Returns the list resulting from applying the given function <code>f</code> to each
-   *  element of this list.
-   *
-   *  @param f function to apply to each element.
-   *  @return <code>[f(a0), ..., f(an)]</code> if this list is <code>[a0, ..., an]</code>.
-   */
-  final override def map[B](f: A => B): List[B] = {
-    val b = new ListBuffer[B]
-    var these = this
-    while (!these.isEmpty) {
-      b += f(these.head)
-      these = these.tail
-    }
-    b.toList
-  }
-
-  /** Apply a function to all the elements of the list, and return the
-   *  reversed list of results. This is equivalent to a call to <code>map</code>
-   *  followed by a call to <code>reverse</code>, but more efficient.
-   *
-   *  @param f the function to apply to each elements.
-   *  @return  the reversed list of results.
-   */
-  def reverseMap[B](f: A => B): List[B] = {
-    def loop(l: List[A], res: List[B]): List[B] = l match {
-      case Nil => res
-      case head :: tail => loop(tail, f(head) :: res)
-    }
-    loop(this, Nil)
-  }
-
-  /** Apply the given function <code>f</code> to each element of this list
-   *  (while respecting the order of the elements).
-   *
-   *  @param f the treatment to apply to each element.
-   */
-  final override def foreach(f: A => Unit) {
-    var these = this
-    while (!these.isEmpty) {
-      f(these.head)
-      these = these.tail
-    }
-  }
-
-  /** Returns all the elements of this list that satisfy the
-   *  predicate <code>p</code>. The order of the elements is preserved.
-   *  It is guarenteed that the receiver list itself is returned iff all its
-   *  elements satisfy the predicate `p'. Hence the following equality is valid:
-   *
-   *  (xs filter p) eq xs  ==  xs forall p
-   *
-   *  @param p the predicate used to filter the list.
-   *  @return the elements of this list satisfying <code>p</code>.
-   */
-  final override def filter(p: A => Boolean): List[A] = {
-    // return same list if all elements satisfy p
-    var these = this
-    while (!these.isEmpty && p(these.head)) {
-      these = these.tail
-    }
-    if (these.isEmpty) this
-    else {
-      val b = new ListBuffer[A]
-      var these1 = this
-      while (these1 ne these) {
-        b += these1.head
-        these1 = these1.tail
-      }
-
-      these = these.tail // prevent the second evaluation of the predicate
-                         // on the element on which it first failed
-      while (!these.isEmpty) {
-        if (p(these.head)) b += these.head
-        these = these.tail
-      }
-      b.toList
-    }
-  }
-
-//  final def filterMap[B](f: PartialFunction[A, B]): List[B] = 
-//    this filter f.isDefinedAt map f
-
-  /** Removes all elements of the list which satisfy the predicate
-   *  <code>p</code>. This is like <code>filter</code> with the
-   *  predicate inversed.
-   *
-   *  @param p the predicate to use to test elements
-   *  @return  the list without all elements which satisfy <code>p</code>
-   */
-  def remove(p: A => Boolean): List[A] = filter (x => !p(x))
-
-  /** Partition the list in two sub-lists according to a predicate.
-   *
-   *  @param p the predicate on which to partition
-   *  @return  a pair of lists: the list of all elements which satisfy
-   *           <code>p</code> and the list of all elements which do not.
-   *           The relative order of the elements in the sub-lists is the
-   *           same as in the original list.
-   */
-  override def partition(p: A => Boolean): (List[A], List[A]) = {
-    val btrue = new ListBuffer[A]
-    val bfalse = new ListBuffer[A]
-    var these = this
-    while (!these.isEmpty) {
-      (if (p(these.head)) btrue else bfalse) += these.head
-      these = these.tail
-    }
-    (btrue.toList, bfalse.toList)
-  }
-
-  /** <p>
-   *    Sort the list according to the comparison function
-   *    <code><(e1: a, e2: a) => Boolean</code>,
-   *    which should be true iff <code>e1</code> is smaller than
-   *    <code>e2</code>. 
-   *  </p>
-   *
-   *  @param lt the comparison function
-   *  @return   a list sorted according to the comparison function
-   *            <code><(e1: a, e2: a) => Boolean</code>.
-   *  @ex <pre>
-   *    List("Steve", "Tom", "John", "Bob")
-   *      .sort((e1, e2) => (e1 compareTo e2) < 0) =
-   *    List("Bob", "John", "Steve", "Tom")</pre>
-   */
-  def sort(lt : (A,A) => Boolean): List[A] = {
-    /** Merge two already-sorted lists */
-    def merge(l1: List[A], l2: List[A]): List[A] = {
-      val res = new ListBuffer[A]
-      var left1 = l1
-      var left2 = l2
-
-      while (!left1.isEmpty && !left2.isEmpty) {
-	if(lt(left1.head, left2.head)) {
-	  res += left1.head
-	  left1 = left1.tail
-	} else {
-	  res += left2.head
-	  left2 = left2.tail
-	}
-      }
-
-      res ++= left1
-      res ++= left2
-
-      res.toList
-    }
-
-    /** Split a list into two lists of about the same size */
-    def split(lst: List[A]) = {
-      val res1 = new ListBuffer[A]
-      val res2 = new ListBuffer[A]
-      var left = lst
-
-      while (!left.isEmpty) {
-	res1 += left.head
-	left = left.tail
-	if (!left.isEmpty) {
-	  res2 += left.head
-	  left = left.tail
-	}
-      }
-
-      (res1.toList, res2.toList)
-    }
-
-
-    /** Merge-sort the specified list */
-    def ms(lst: List[A]): List[A] =
-      lst match {
-	case Nil => lst
-	case x :: Nil => lst
-	case x :: y :: Nil =>
-	  if (lt(x,y))
-	    lst
-	  else
-	    y :: x :: Nil
-
-	case lst =>
-          val (l1, l2) = split(lst)
-          val l1s = ms(l1)
-          val l2s = ms(l2)
-          merge(l1s, l2s)
-      }
-
-    ms(this)
-  }
-
-
-  /** Count the number of elements in the list which satisfy a predicate.
-   *
-   *  @param p the predicate for which to count
-   *  @return  the number of elements satisfying the predicate <code>p</code>.
-   */
-  def count(p: A => Boolean): Int = {
-    var cnt = 0
-    var these = this
-    while (!these.isEmpty) {
-      if (p(these.head)) cnt += 1
-      these = these.tail
-    }
-    cnt
-  }
-
-  /** Tests if the predicate <code>p</code> is satisfied by all elements
-   *  in this list.
-   *
-   *  @param p the test predicate.
-   *  @return  <code>true</code> iff all elements of this list satisfy the
-   *           predicate <code>p</code>.
-   */
-  override def forall(p: A => Boolean): Boolean = {
-    var these = this
-    while (!these.isEmpty) {
-      if (!p(these.head)) return false
-      these = these.tail
-    }
-    true
-  }
-
-  /** Tests the existence in this list of an element that satisfies the
-   *  predicate <code>p</code>.
-   *
-   *  @param p the test predicate.
-   *  @return  <code>true</code> iff there exists an element in this list that
-   *           satisfies the predicate <code>p</code>.
-   */
-  override def exists(p: A => Boolean): Boolean = {
-    var these = this
-    while (!these.isEmpty) {
-      if (p(these.head)) return true
-      these = these.tail
-    }
-    false
-  }
-
-  /** Find and return the first element of the list satisfying a
-   *  predicate, if any.
-   *
-   *  @param p the predicate
-   *  @return the first element in the list satisfying <code>p</code>,
-   *  or <code>None</code> if none exists.
-   */
-  override def find(p: A => Boolean): Option[A] = {
-    var these = this
-    while (!these.isEmpty) {
-      if (p(these.head)) return Some(these.head)
-      these = these.tail
-    }
-    None
-  }
-
-  /** Combines the elements of this list together using the binary
-   *  function <code>f</code>, from left to right, and starting with
-   *  the value <code>z</code>.
-   *
-   *  @return <code>f(... (f(f(z, a<sub>0</sub>), a<sub>1</sub>) ...),
-   *          a<sub>n</sub>)</code> if the list is
-   *          <code>[a<sub>0</sub>, a<sub>1</sub>, ..., a<sub>n</sub>]</code>.
-   */
-  override def foldLeft[B](z: B)(f: (B, A) => B): B = {
-    var acc = z
-    var these = this
-    while (!these.isEmpty) {
-      acc = f(acc, these.head)
-      these = these.tail
-    }
-    acc
-  }
-
-  /** Combines the elements of this list together using the binary
-   *  function <code>f</code>, from right to left, and starting with
-   *  the value <code>z</code>.
-   *
-   *  @return <code>f(a<sub>0</sub>, f(a<sub>1</sub>, f(..., f(a<sub>n</sub>, z)...)))</code>
-   *          if the list is <code>[a<sub>0</sub>, a1, ..., a<sub>n</sub>]</code>.
-   */
-  override def foldRight[B](z: B)(f: (A, B) => B): B = this match {
-    case Nil => z
-    case x :: xs => f(x, xs.foldRight(z)(f))
-  }
-
-  /** Combines the elements of this list together using the binary
-   *  operator <code>op</code>, from left to right
-   *  @param op  The operator to apply
-   *  @return <code>op(... op(a<sub>0</sub>,a<sub>1</sub>), ..., a<sub>n</sub>)</code> 
-      if the list has elements
-   *          <code>a<sub>0</sub>, a<sub>1</sub>, ..., a<sub>n</sub></code>.
-   *  @throws Predef.UnsupportedOperationException if the list is empty.
-   */
-  override def reduceLeft[B >: A](f: (B, A) => B): B = this match {
-    case Nil => throw new UnsupportedOperationException("Nil.reduceLeft")
-    case x :: Nil => x
-    case x0 :: x1 :: xs => 
-      var acc : B = f(x0, x1)
-      var these : List[A] = xs
-      while (!these.isEmpty) {
-        acc = f(acc, these.head)
-        these = these.tail
-      }
-      acc
-  }
-
-  /** Combines the elements of this list together using the binary
-   *  operator <code>op</code>, from right to left
-   *  @param op  The operator to apply
-   *
-   *  @return <code>a<sub>0</sub> op (... op (a<sub>n-1</sub> op a<sub>n</sub>)...)</code>
-   *          if the list has elements <code>a<sub>0</sub>, a<sub>1</sub>, ...,
-   *          a<sub>n</sub></code>.
-   *
-   *  @throws Predef.UnsupportedOperationException if the list is empty.
-   */
-  override def reduceRight[B >: A](f: (A, B) => B): B = this match {
-    case Nil => throw new UnsupportedOperationException("Nil.reduceRight")
-    case x :: Nil => x
-    case x :: xs => f(x, xs reduceRight f)
-  }
-
-  /** Applies the given function <code>f</code> to each element of
-   *  this list, then concatenates the results.
-   *
-   *  @param f the function to apply on each element.
-   *  @return  <code>f(a<sub>0</sub>) ::: ... ::: f(a<sub>n</sub>)</code> if
-   *           this list is <code>[a<sub>0</sub>, ..., a<sub>n</sub>]</code>.
-   */
-  final override def flatMap[B](f: A => Iterable[B]): List[B] = {
-    val b = new ListBuffer[B]
-    var these = this
-    while (!these.isEmpty) {
-      var those = f(these.head).elements
-      while (those.hasNext) {
-        b += those.next
-      }
-      these = these.tail
-    }
-    b.toList
-  }
-
-  /** A list consisting of all elements of this list in reverse order.
-   */
-  override def reverse: List[A] = {
-    var result: List[A] = Nil
-    var these = this
-    while (!these.isEmpty) {
-      result = these.head :: result
-      these = these.tail
-    }
-    result
-  }
-
-  /** Returns a list formed from this list and the specified list
-   *  <code>that</code> by associating each element of the former with
-   *  the element at the same position in the latter.
-   *  If one of the two lists is longer than the other, its remaining elements are ignored.
-   *
-   *  @return     <code>List((a<sub>0</sub>,b<sub>0</sub>), ...,
-   *              (a<sub>min(m,n)</sub>,b<sub>min(m,n)</sub>))</code> when
-   *              <code>List(a<sub>0</sub>, ..., a<sub>m</sub>)
-   *              zip List(b<sub>0</sub>, ..., b<sub>n</sub>)</code> is invoked.
-   */
-  def zip[B](that: List[B]): List[(A, B)] = {
-    val b = new ListBuffer[(A, B)]
-    var these = this
-    var those = that
-    while (!these.isEmpty && !those.isEmpty) {
-      b += (these.head, those.head)
-      these = these.tail
-      those = those.tail
-    }
-    b.toList
-  }
-
-  /** Returns a list that pairs each element of this list
-   *  with its index, counting from 0.
-   *
-   *  @return      the list <code>List((a<sub>0</sub>,0), (a<sub>1</sub>,1), ...)</code>
-   *               where <code>a<sub>i</sub></code> are the elements of this list.
-   */
-  def zipWithIndex: List[(A, Int)] = {
-    val b = new ListBuffer[(A, Int)]
-    var these = this
-    var idx = 0
-
-    while(!these.isEmpty) {
-      b += (these.head, idx)
-      these = these.tail
-      idx += 1
-    }
-
-    b.toList
-  }
-
-  /** Returns a list formed from this list and the specified list
-   *  <code>that</code> by associating each element of the former with
-   *  the element at the same position in the latter.
-   *
-   *  @param that     list <code>that</code> may have a different length
-   *                  as the self list.
-   *  @param thisElem element <code>thisElem</code> is used to fill up the
-   *                  resulting list if the self list is shorter than
-   *                  <code>that</code>
-   *  @param thatElem element <code>thatElem</code> is used to fill up the
-   *                  resulting list if <code>that</code> is shorter than
-   *                  the self list
-   *  @return         <code>List((a<sub>0</sub>,b<sub>0</sub>), ...,
-   *                  (a<sub>n</sub>,b<sub>n</sub>), (elem,b<sub>n+1</sub>),
-   *                  ..., {elem,b<sub>m</sub>})</code>
-   *                  when <code>[a<sub>0</sub>, ..., a<sub>n</sub>] zip
-   *                  [b<sub>0</sub>, ..., b<sub>m</sub>]</code> is
-   *                  invoked where <code>m > n</code>.
-   */
-  def zipAll[B, C >: A, D >: B](that: List[B], thisElem: C, thatElem: D): List[(C, D)] = {
-    val b = new ListBuffer[(C, D)]
-    var these = this
-    var those = that
-    while (!these.isEmpty && !those.isEmpty) {
-      b += (these.head, those.head)
-      these = these.tail
-      those = those.tail
-    }
-    while (!these.isEmpty) {
-      b += (these.head, thatElem)
-      these = these.tail
-    }
-    while (!those.isEmpty) {
-      b += (thisElem, those.head)
-      those = those.tail
-    }
-    b.toList
-  }
-
-  /** Computes the union of this list and the given list
-   *  <code>that</code>.
-   *
-   *  @param that the list of elements to add to the list.
-   *  @return     a list without doubles containing the elements of this
-   *              list and those of the given list <code>that</code>.
-   */
-  def union[B >: A](that: List[B]): List[B] = {
-    val b = new ListBuffer[B]
-    var these = this
-    while (!these.isEmpty) {
-      if (!that.contains(these.head)) b += these.head
-      these = these.tail
-    }
-    b.prependToList(that)
-  }
-
-  /** Computes the difference between this list and the given list
-   *  <code>that</code>.
-   *
-   *  @param that the list of elements to remove from this list.
-   *  @return     this list without the elements of the given list
-   *              <code>that</code>.
-   *  @deprecated use <code>--</code> instead
-   */
-  @deprecated
-  def diff[B >: A](that: List[B]): List[B] = this -- that
-
-  /** Computes the difference between this list and the given list
-   *  <code>that</code>.
-   *
-   *  @param that the list of elements to remove from this list.
-   *  @return     this list without the elements of the given list
-   *              <code>that</code>.
-   */
-  def -- [B >: A](that: List[B]): List[B] = {
-    val b = new ListBuffer[B]
-    var these = this
-    while (!these.isEmpty) {
-      if (!that.contains(these.head)) b += these.head
-      these = these.tail
-    }
-    b.toList
-  }
-
-  /** Computes the difference between this list and the given object
-   *  <code>x</code>.
-   *
-   *  @param x    the object to remove from this list.
-   *  @return     this list without the elements of the given object
-   *              <code>x</code>.
-   */
-  def - [B >: A](x: B): List[B] =
-    this -- List(x)
-
-  /** Concatenate the elements of this list. The elements of this list
-   *  should be a <code>Iterables</code>.
-   *
-   *  Note: The compiler might not be able to infer the type parameter.
-   *
-   *  @param f    An implicit conversion to an <code>Iterable</code> instance.
-   *  @return     The concatenation of all elements of iterables in this list.
-   */
-  def flatten[B](implicit f : A => Iterable[B]) : List[B] = {
-    val buf = new ListBuffer[B]
-    foreach(f(_).foreach(buf += _))
-    buf.toList
-  }
-
-  /** Computes the intersection between this list and the given list
-   *  <code>that</code>.
-   *
-   *  @param that the list to intersect.
-   *  @return     the list of elements contained both in this list and
-   *              in the given list <code>that</code>.
-   */
-  def intersect[B >: A](that: List[B]): List[B] = filter(x => that contains x)
-
-  /** Removes redundant elements from the list. Uses the method <code>==</code>
-   *  to decide if two elements are identical.
-   *
-   *  @return the list without doubles.
-   */
-  def removeDuplicates: List[A] = {
-    val b = new ListBuffer[A]
-    var these = this
-    while (!these.isEmpty) {
-      if (!these.tail.contains(these.head)) b += these.head
-      these = these.tail
-    }
-    b.toList
-  }
-   
-  override protected def stringPrefix = "List"
-  override def projection = toStream
-  override def toStream : Stream[A] = new Stream.Definite[A] {
-    override def force : List[A] = List.this
-    override def isEmpty = List.this.isEmpty
-    override def head = List.this.head
-    override def tail = List.this.tail.toStream
-    protected def addDefinedElems(buf: StringBuilder, prefix: String): StringBuilder = if (!isEmpty) {
-      var prefix0 = prefix
-      var buf1 = buf.append(prefix0).append(head)
-      prefix0 = ", "
-      var tail0 = tail
-      while (!tail0.isEmpty) {
-        buf1 = buf.append(prefix0).append(tail0.head)
-        tail0 = tail0.tail
-      }
-      buf1
-    } else buf
-  }
-
-}
-
-/** The empty list.
- *
- *  @author  Martin Odersky
- *  @version 1.0, 15/07/2003
- */
- at SerialVersionUID(0 - 8256821097970055419L)
-case object Nil extends List[Nothing] {
-  override def isEmpty = true
-  def head: Nothing =
-    throw new NoSuchElementException("head of empty list")
-  def tail: List[Nothing] =
-    throw new NoSuchElementException("tail of empty list")
-}
-
-/** A non empty list characterized by a head and a tail.
- *
- *  @author  Martin Odersky
- *  @version 1.0, 15/07/2003
- */
- at SerialVersionUID(0L - 8476791151983527571L)
-final case class ::[B](private var hd: B, private[scala] var tl: List[B]) extends List[B] {
-  def head : B = hd
-  def tail : List[B] = tl
-  override def isEmpty: Boolean = false
-}
-
diff --git a/src/dotnet-library/scala/Math.scala b/src/dotnet-library/scala/Math.scala
deleted file mode 100644
index e79fdb3..0000000
--- a/src/dotnet-library/scala/Math.scala
+++ /dev/null
@@ -1,147 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: Math.scala 16881 2009-01-09 16:28:11Z cunei $
-
-
-package scala
-
-/** The object <code>Math</code> contains methods for performing basic numeric
- *  operations such as the elementary exponential, logarithm, square root, and
- *  trigonometric functions.
- */
-object Math {
-
-  /** The smallest possible value for <a href="Byte.html" target="_self">scala.Byte</a>. */
-  val MIN_BYTE   = System.Byte.MinValue
-  /** The greatest possible value for <a href="Byte.html" target="_self">scala.Byte</a>. */
-  val MAX_BYTE   = System.Byte.MaxValue
-
-  /** The smallest possible value for <a href="Short.html" target="_self">scala.Short</a>. */
-  val MIN_SHORT  = System.Int16.MinValue
-  /** The greatest possible value for <a href="Short.html" target="_self">scala.Short</a>. */
-  val MAX_SHORT  = System.Int16.MaxValue
-
-  /** The smallest possible value for <a href="Char.html" target="_self">scala.Char</a>. */
-  val MIN_CHAR   = System.Char.MinValue
-  /** The greatest possible value for <a href="Char.html" target="_self">scala.Char</a>. */
-  val MAX_CHAR   = System.Char.MaxValue
-
-  /** The smallest possible value for <a href="Int.html" target="_self">scala.Int</a>. */
-  val MIN_INT    = System.Int32.MinValue
-  /** The greatest possible value for <a href="Int.html" target="_self">scala.Int</a>. */
-  val MAX_INT    = System.Int32.MaxValue
-
-  /** The smallest possible value for <a href="Long.html" target="_self">scala.Long</a>. */
-  val MIN_LONG   = System.Int64.MinValue
-  /** The greatest possible value for <a href="Long.html" target="_self">scala.Long</a>. */
-  val MAX_LONG   = System.Int64.MaxValue
-
-  /** The smallest possible value for <a href="Float.html" target="_self">scala.Float</a>. */
-  val MIN_FLOAT  = System.Single.MinValue
-  /** The smallest difference between two values of <a href="Float.html" target="_self">scala.Float</a>. */
-  val EPS_FLOAT  = System.Single.Epsilon
-  /** The greatest possible value for <a href="Float.html" target="_self">scala.Float</a>. */
-  val MAX_FLOAT  = System.Single.MinValue
-  /** A value of type <a href="Float.html" target="_self">scala.Float</a> that represents no number. */
-  //val NaN_FLOAT  = System.Single.NaN
-  /** Negative infinity of type <a href="Float.html" target="_self">scala.Float</a>. */
-  //val NEG_INF_FLOAT = System.Double.NegativeInfinity
-  /** Positive infinity of type <a href="Float.html" target="_self">scala.Float</a>. */
-  //val POS_INF_FLOAT = System.Double.PositiveInfinity
-
-  /** The smallest possible value for <a href="Double.html" target="_self">scala.Double</a>. */
-  val MIN_DOUBLE = System.Double.MinValue
-  /** The smallest difference between two values of <a href="Double.html" target="_self">scala.Double</a>. */
-  val EPS_DOUBLE = System.Double.Epsilon
-  /** The greatest possible value for <a href="Double.html" target="_self">scala.Double</a>. */
-  val MAX_DOUBLE = System.Double.MaxValue
-  /** A value of type <a href="Double.html" target="_self">scala.Double</a> that represents no number. */
-  //val NaN_DOUBLE = System.Double.NaN
-  /** Negative infinity of type <a href="Double.html" target="_self">scala.Double</a>. */
-  //val NEG_INF_DOUBLE = System.Double.NegativeInfinity
-  /** Positive infinity of type <a href="Double.html" target="_self">scala.Double</a>. */
-  //val POS_INF_DOUBLE = System.Double.PositiveInfinity
-
-  /** The <code>double</code> value that is closer than any other to
-   *  <code>e</code>, the base of the natural logarithms.
-   */
-
-  val E = System.Math.E
-  val Pi = System.Math.PI
-
-  //def random: Double = System.Math.random()
-
-  def sin(x: Double): Double = System.Math.Sin(x)
-  def cos(x: Double): Double = System.Math.Cos(x)
-  def tan(x: Double): Double = System.Math.Tan(x)
-  def asin(x: Double): Double = System.Math.Asin(x)
-  def acos(x: Double): Double = System.Math.Acos(x)
-  def atan(x: Double): Double = System.Math.Atan(x)
-
-  def toRadians(x: Double): Double = x * Pi / 180.0
-
-  def toDegrees(x: Double): Double = x * 180.0 / Pi
-
-  def exp(x: Double): Double = System.Math.Exp(x)
-  def log(x: Double): Double = System.Math.Log(x)
-  def sqrt(x: Double): Double = System.Math.Sqrt(x)
-  def sqrt(x: Int): Int = System.Math.Sqrt(x.toDouble).toInt
-  def IEEEremainder(x: Double, y: Double): Double = System.Math.IEEERemainder(x, y)
-
-  def ceil(x: Double): Double = System.Math.Ceiling(x)
-  def floor(x: Double): Double = System.Math.Floor(x)
-
-  //def rint(x: Double): Double = System.Math.rint(x)
-  def atan2(y: Double, x: Double): Double = System.Math.Atan2(y, x)
-  def pow(x: Double, y: Double): Double = System.Math.Pow(x, y)
-  def round(x: Float): Int = System.Math.Round(x).toInt
-  def round(x: Double): Long = System.Math.Round(x).toLong
-
-  def abs(x: Int): Int = System.Math.Abs(x)
-  def abs(x: Long): Long = System.Math.Abs(x)
-  def abs(x: Float): Float = System.Math.Abs(x)
-  def abs(x: Double): Double = System.Math.Abs(x)
-
-  def max(x: Int, y: Int): Int = System.Math.Max(x, y)
-  def max(x: Long, y: Long): Long = System.Math.Max(x, y)
-  def max(x: Float, y: Float): Float = System.Math.Max(x, y)
-  def max(x: Double, y: Double): Double = System.Math.Max(x, y)
-
-  def min(x: Int, y: Int): Int = System.Math.Min(x, y)
-  def min(x: Long, y: Long): Long  = System.Math.Min(x, y)
-  def min(x: Float, y: Float): Float  = System.Math.Min(x, y)
-  def min(x: Double, y: Double): Double = System.Math.Min(x, y)
-
-  def signum(x: Double): Double = x match { case 0 => 0
-                                            case y if y < 0 => -1.0
-                                            case y if y > 0 => 1.0 }
-  def signum(x: Float): Float = x match { case 0f => 0f
-                                          case y if y < 0f => -1.0f
-                                          case y if y > 0f => 1.0f }
-  def signum(x: Long): Long = x match { case 0l => 0l
-                                        case y if y < 0l => -1l
-                                        case y if y > 0l => 1l }
-  def signum(x: Int): Int = x match { case 0 => 0
-                                      case y if y < 0 => -1
-                                      case y if y > 0 => 1}
-
-  // from Java 1.5
-//   def log10(x: Double): Double = java.lang.Math.log10(x)
-//   def cbrt(x: Double): Double = java.lang.Math.cbrt(x)
-
-//   def ulp(x: Double): Double = java.lang.Math.ulp(x)
-//   def ulp(x: Float): Float = java.lang.Math.ulp(x)
-//   def sinh(x: Double): Double = java.lang.Math.sinh(x)
-//   def cosh(x: Double): Double = java.lang.Math.cosh(x)
-//   def tanh(x: Double):Double = java.lang.Math.tanh(x)
-//   def hypot(x: Double, y: Double): Double = java.lang.Math.hypot(x, y)
-//   def expm1(x: Double): Double = java.lang.Math.expm1(x)
-//   def log1p(x: Double): Double = java.lang.Math.log1p(x)
-
-}
diff --git a/src/dotnet-library/scala/Predef.scala b/src/dotnet-library/scala/Predef.scala
deleted file mode 100644
index 5989445..0000000
--- a/src/dotnet-library/scala/Predef.scala
+++ /dev/null
@@ -1,328 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: Predef.scala 16881 2009-01-09 16:28:11Z cunei $
-
-
-package scala
-
-
-/** The <code>Predef</code> object provides definitions that are
- *  accessible in all Scala compilation units without explicit
- *  qualification.
- */
-object Predef {
-
-  // classOf dummy ------------------------------------------------------
-
-  /** Return the runtime representation of a class type. */
-  def classOf[T]: Class[T] = null
-
-  // aliases ------------------------------------------------------------
-
-  @deprecated type byte    = scala.Byte
-  @deprecated type short   = scala.Short
-  @deprecated type char    = scala.Char
-  @deprecated type int     = scala.Int
-  @deprecated type long    = scala.Long
-  @deprecated type float   = scala.Float
-  @deprecated type double  = scala.Double
-  @deprecated type boolean = scala.Boolean
-  @deprecated type unit    = scala.Unit
-
-  type String        = System.String
-  type Class[T]      = System.Type
-  type Runnable      = scala.runtime.Runnable
-
-  type Throwable = System.Exception
-  type Exception = System.Exception
-  type Error     = System.Exception
-
-  type RuntimeException = System.Exception
-  type NullPointerException = System.NullReferenceException
-  type ClassCastException = System.InvalidCastException
-  type IndexOutOfBoundsException = System.IndexOutOfRangeException
-  type ArrayIndexOutOfBoundsException = System.IndexOutOfRangeException
-  type StringIndexOutOfBoundsException = System.IndexOutOfRangeException
-  type UnsupportedOperationException = System.InvalidOperationException
-  type IllegalArgumentException = System.ArgumentException
-  type NoSuchElementException = System.InvalidOperationException
-  //type NumberFormatException = java.lang.NumberFormatException
-
-  // miscelleaneous -----------------------------------------------------
-  
-  //val $scope = scala.xml.TopScope
-
-  type Function[-A, +B] = Function1[A, B]
-
-  type Map[A, B] = collection.immutable.Map[A, B]
-  type Set[A] = collection.immutable.Set[A]
-
-  val Map = collection.immutable.Map
-  val Set = collection.immutable.Set
-
-  // errors and asserts -------------------------------------------------
-
-  def error(message: String): Nothing = throw new RuntimeException(message)
-
-  def exit(): Nothing = exit(0)
-
-  def exit(status: Int): Nothing = {
-    System.Environment.Exit(status)
-    throw new Throwable()
-  }
-
-  def assert(assertion: Boolean) {
-    if (!assertion)
-      throw new Error("assertion failed")
-  }
-
-  def assert(assertion: Boolean, message: Any) {
-    if (!assertion)
-      throw new Error("assertion failed: " + message)
-  }
-
-  def assume(assumption: Boolean) {
-    if (!assumption)
-      throw new IllegalArgumentException("assumption failed")
-  }
-
-  def assume(assumption: Boolean, message: Any) {
-    if (!assumption)
-      throw new System.Security.SecurityException("assumption failed: "+ message)
-  }
-
-  def require(requirement: Boolean) {
-    if (!requirement)
-      throw new IllegalArgumentException("requirement failed")
-  }
-
-  def require(requirement: Boolean, message: Any) {
-    if (!requirement)
-      throw new IllegalArgumentException("requirement failed: "+ message)
-  }
-
-  // tupling ------------------------------------------------------------
-
-  type Pair[+A, +B] = Tuple2[A, B]
-  object Pair {
-    def apply[A, B](x: A, y: B) = Tuple2(x, y)
-    def unapply[A, B](x: Tuple2[A, B]): Option[Tuple2[A, B]] = Some(x)
-  }
-
-  type Triple[+A, +B, +C] = Tuple3[A, B, C]
-  object Triple {
-    def apply[A, B, C](x: A, y: B, z: C) = Tuple3(x, y, z)
-    def unapply[A, B, C](x: Tuple3[A, B, C]): Option[Tuple3[A, B, C]] = Some(x)
-  }
-
-  class Ensuring[A](x: A) {
-    def ensuring(cond: Boolean): A = { assert(cond); x }
-    def ensuring(cond: Boolean, msg: Any): A = { assert(cond, msg); x }
-    def ensuring(cond: A => Boolean): A = { assert(cond(x)); x }
-    def ensuring(cond: A => Boolean, msg: Any): A = { assert(cond(x), msg); x }
-  }
-  implicit def any2Ensuring[A](x: A): Ensuring[A] = new Ensuring(x)
-
-  class ArrowAssoc[A](x: A) {
-    def -> [B](y: B): Tuple2[A, B] = Tuple2(x, y)
-  }
-  implicit def any2ArrowAssoc[A](x: A): ArrowAssoc[A] = new ArrowAssoc(x)
-
-  def Tuple[A1](x1: A1) = Tuple1(x1)
-  def Tuple[A1, A2](x1: A1, x2: A2) = Tuple2(x1, x2)
-  def Tuple[A1, A2, A3](x1: A1, x2: A2, x3: A3) = Tuple3(x1, x2, x3)
-  def Tuple[A1, A2, A3, A4](x1: A1, x2: A2, x3: A3, x4: A4) = Tuple4(x1, x2, x3, x4)
-  def Tuple[A1, A2, A3, A4, A5](x1: A1, x2: A2, x3: A3, x4: A4, x5: A5) = Tuple5(x1, x2, x3, x4, x5)
-  def Tuple[A1, A2, A3, A4, A5, A6](x1: A1, x2: A2, x3: A3, x4: A4, x5: A5, x6: A6) = Tuple6(x1, x2, x3, x4, x5, x6)
-  def Tuple[A1, A2, A3, A4, A5, A6, A7](x1: A1, x2: A2, x3: A3, x4: A4, x5: A5, x6: A6, x7: A7) = Tuple7(x1, x2, x3, x4, x5, x6, x7)
-  def Tuple[A1, A2, A3, A4, A5, A6, A7, A8](x1: A1, x2: A2, x3: A3, x4: A4, x5: A5, x6: A6, x7: A7, x8: A8) = Tuple8(x1, x2, x3, x4, x5, x6, x7, x8)
-  def Tuple[A1, A2, A3, A4, A5, A6, A7, A8, A9](x1: A1, x2: A2, x3: A3, x4: A4, x5: A5, x6: A6, x7: A7, x8: A8, x9: A9) = Tuple9(x1, x2, x3, x4, x5, x6, x7, x8, x9)
-
-  // printing and reading -----------------------------------------------
-
-  def print(x: Any) = Console.print(x)
-  def println() = Console.println()
-  def println(x: Any) = Console.println(x)
-  //def printf(text: String, xs: Any*) = Console.printf(text, xs: _*)
-  //def format(text: String, xs: Any*) = Console.format(text, xs)
-
-  def readLine(): String = Console.readLine()
-  def readLine(text: String, args: Any*) = Console.readLine(text, args)
-  def readBoolean() = Console.readBoolean()
-  def readByte() = Console.readByte()
-  def readShort() = Console.readShort()
-  def readChar() = Console.readChar()
-  def readInt() = Console.readInt()
-  def readLong() = Console.readLong()
-  def readFloat() = Console.readFloat()
-  def readDouble() = Console.readDouble()
-  //def readf(format: String) = Console.readf(format)
-  //def readf1(format: String) = Console.readf1(format)
-  //def readf2(format: String) = Console.readf2(format)
-  //def readf3(format: String) = Console.readf3(format)
-
-  // views --------------------------------------------------------------
-
-  implicit def identity[A](x: A): A = x
-
-  implicit def byteWrapper(x: Byte)     = new runtime.RichByte(x)
-  implicit def shortWrapper(x: Short)   = new runtime.RichShort(x)
-  implicit def intWrapper(x: Int)       = new runtime.RichInt(x)
-  implicit def charWrapper(c: Char)     = new runtime.RichChar(c)
-  implicit def longWrapper(x: Long)     = new runtime.RichLong(x)
-  implicit def floatWrapper(x: Float)   = new runtime.RichFloat(x)
-  implicit def doubleWrapper(x: Double) = new runtime.RichDouble(x)
-
-  implicit def booleanWrapper(x: Boolean)  = new runtime.RichBoolean(x)
-
-  implicit def stringWrapper(x: String) = new runtime.RichString(x)
-  //implicit def stringBuilderWrapper(x : StringBuilder): runtime.RichStringBuilder = new runtime.RichStringBuilder(x)
-
-  implicit def any2stringadd(x: Any) = new runtime.StringAdd(x)
-
-  implicit def exceptionWrapper(exc: Throwable) = new runtime.RichException(exc)
-
-  final class GetClassWrapper(obj: AnyRef) {
-    def getClass(): runtime.RichClass = classWrapper(obj.GetType())
-  }
-  implicit def getClassWrapper(obj: AnyRef) = new GetClassWrapper(obj)
-  implicit def classWrapper(clazz: Class[_]): runtime.RichClass =
-    new runtime.RichClass(clazz)
-
-  implicit def unit2ordered(x: Unit): Ordered[Unit] = new Ordered[Unit] with Proxy {
-    def self: Any = x
-    def compare(y: Unit): Int = 0
-  }
-
-  implicit def iterable2ordered[A <% Ordered[A]](xs: Iterable[A]): Ordered[Iterable[A]] =
-    new Ordered[Iterable[A]] with Proxy {
-      val self = xs
-      def compare(that: Iterable[A]): Int = {
-        var res = 0
-        val these = xs.elements
-        val those = that.elements
-        while (res == 0 && these.hasNext)
-          res = if (those.hasNext) these.next compare those.next else 1
-        if (res == 0) {
-          if (those.hasNext) -1 else 0
-        } else 
-          res
-      }
-    }
-
-  implicit def tuple22ordered[A1 <% Ordered[A1], A2 <% Ordered[A2]](x: Tuple2[A1, A2]): Ordered[Tuple2[A1, A2]] = 
-    new Ordered[Tuple2[A1, A2]] with Proxy {
-      val self = x
-      def compare(y: Tuple2[A1, A2]): Int = {
-        val res = x._1 compare y._1
-        if (res == 0) x._2 compare y._2
-        else res
-      }
-    }
-
-  implicit def tuple32ordered[A1 <% Ordered[A1], A2 <% Ordered[A2], A3 <% Ordered[A3]](x: Tuple3[A1, A2, A3]): Ordered[Tuple3[A1, A2, A3]] = 
-    new Ordered[Tuple3[A1, A2, A3]] with Proxy {
-      val self = x
-      def compare(y: Tuple3[A1, A2, A3]): Int = {
-        val res = x._1 compare y._1
-        if (res == 0) Tuple2(x._2, x._3) compare Tuple2(y._2, y._3)
-        else res
-      }
-    }
-
-  implicit def tuple42ordered[A1 <% Ordered[A1], A2 <% Ordered[A2], A3 <% Ordered[A3], A4 <% Ordered[A4]](x: Tuple4[A1, A2, A3, A4]): Ordered[Tuple4[A1, A2, A3, A4]] = 
-    new Ordered[Tuple4[A1, A2, A3, A4]] with Proxy {
-      val self = x
-      def compare(y: Tuple4[A1, A2, A3, A4]): Int = {
-        val res = x._1 compare y._1
-        if (res == 0) Tuple3(x._2, x._3, x._4) compare Tuple3(y._2, y._3, y._4)
-        else res
-      }
-    }
-
-  implicit def tuple52ordered[A1 <% Ordered[A1], A2 <% Ordered[A2], A3 <% Ordered[A3], A4 <% Ordered[A4], A5 <% Ordered[A5]](x: Tuple5[A1, A2, A3, A4, A5]): Ordered[Tuple5[A1, A2, A3, A4, A5]] = 
-    new Ordered[Tuple5[A1, A2, A3, A4, A5]] with Proxy {
-      val self = x
-      def compare(y: Tuple5[A1, A2, A3, A4, A5]): Int = {
-        val res = x._1 compare y._1
-        if (res == 0) Tuple4(x._2, x._3, x._4, x._5) compare Tuple4(y._2, y._3, y._4, y._5)
-        else res
-      }
-    }
-
-  implicit def tuple62ordered[A1 <% Ordered[A1], A2 <% Ordered[A2], A3 <% Ordered[A3], A4 <% Ordered[A4], A5 <% Ordered[A5], A6 <% Ordered[A6]](x: Tuple6[A1, A2, A3, A4, A5, A6]): Ordered[Tuple6[A1, A2, A3, A4, A5, A6]] = 
-    new Ordered[Tuple6[A1, A2, A3, A4, A5, A6]] with Proxy {
-      val self = x
-      def compare(y: Tuple6[A1, A2, A3, A4, A5, A6]): Int = {
-        val res = x._1 compare y._1
-        if (res == 0) Tuple5(x._2, x._3, x._4, x._5, x._6) compare Tuple5(y._2, y._3, y._4, y._5, y._6)
-        else res
-      }
-    }
-
-  implicit def tuple72ordered[A1 <% Ordered[A1], A2 <% Ordered[A2], A3 <% Ordered[A3], A4 <% Ordered[A4], A5 <% Ordered[A5], A6 <% Ordered[A6], A7 <% Ordered[A7]](x: Tuple7[A1, A2, A3, A4, A5, A6, A7]): Ordered[Tuple7[A1, A2, A3, A4, A5, A6, A7]] = 
-    new Ordered[Tuple7[A1, A2, A3, A4, A5, A6, A7]] with Proxy {
-      val self = x
-      def compare(y: Tuple7[A1, A2, A3, A4, A5, A6, A7]): Int = {
-        val res = x._1 compare y._1
-        if (res == 0) Tuple6(x._2, x._3, x._4, x._5, x._6, x._7) compare Tuple6(y._2, y._3, y._4, y._5, y._6, y._7)
-        else res
-      }
-    }
-
-  implicit def tuple82ordered[A1 <% Ordered[A1], A2 <% Ordered[A2], A3 <% Ordered[A3], A4 <% Ordered[A4], A5 <% Ordered[A5], A6 <% Ordered[A6], A7 <% Ordered[A7], A8 <% Ordered[A8]](x: Tuple8[A1, A2, A3, A4, A5, A6, A7, A8]): Ordered[Tuple8[A1, A2, A3, A4, A5, A6, A7, A8]] = 
-    new Ordered[Tuple8[A1, A2, A3, A4, A5, A6, A7, A8]] with Proxy {
-      val self = x
-      def compare(y: Tuple8[A1, A2, A3, A4, A5, A6, A7, A8]): Int = {
-        val res = x._1 compare y._1
-        if (res == 0) Tuple7(x._2, x._3, x._4, x._5, x._6, x._7, x._8) compare Tuple7(y._2, y._3, y._4, y._5, y._6, y._7, y._8)
-        else res
-      }
-    }
-
-  implicit def tuple92ordered[A1 <% Ordered[A1], A2 <% Ordered[A2], A3 <% Ordered[A3], A4 <% Ordered[A4], A5 <% Ordered[A5], A6 <% Ordered[A6], A7 <% Ordered[A7], A8 <% Ordered[A8], A9 <% Ordered[A9]](x: Tuple9[A1, A2, A3, A4, A5, A6, A7, A8, A9]): Ordered[Tuple9[A1, A2, A3, A4, A5, A6, A7, A8, A9]] = 
-    new Ordered[Tuple9[A1, A2, A3, A4, A5, A6, A7, A8, A9]] with Proxy {
-      val self = x
-      def compare(y: Tuple9[A1, A2, A3, A4, A5, A6, A7, A8, A9]): Int = {
-        val res = x._1 compare y._1
-        if (res == 0) Tuple8(x._2, x._3, x._4, x._5, x._6, x._7, x._8, x._9) compare Tuple8(y._2, y._3, y._4, y._5, y._6, y._7, y._8, y._9)
-        else res
-      }
-    }
-
-  implicit def byte2short(x: Byte): Short = x.toShort
-  implicit def byte2int(x: Byte): Int = x.toInt
-  implicit def byte2long(x: Byte): Long = x.toLong
-  implicit def byte2float(x: Byte): Float = x.toFloat
-  implicit def byte2double(x: Byte): Double = x.toDouble
-
-  implicit def short2int(x: Short): Int = x.toInt
-  implicit def short2long(x: Short): Long = x.toLong
-  implicit def short2float(x: Short): Float = x.toFloat
-  implicit def short2double(x: Short): Double = x.toDouble
-
-  implicit def char2int(x: Char): Int = x.toInt
-  implicit def char2long(x: Char): Long = x.toLong
-  implicit def char2float(x: Char): Float = x.toFloat
-  implicit def char2double(x: Char): Double = x.toDouble
-
-  implicit def int2long(x: Int): Long = x.toLong
-  implicit def int2float(x: Int): Float = x.toFloat
-  implicit def int2double(x: Int): Double = x.toDouble
-
-  implicit def long2float(x: Long): Float = x.toFloat
-  implicit def long2double(x: Long): Double = x.toDouble
-
-  implicit def float2double(x: Float): Double = x.toDouble
-
-  implicit def forceArrayProjection[A](x : Array.Projection[A]) : Array[A] = x.force
-
-  def currentThread = System.Threading.Thread.CurrentThread
-
-}
diff --git a/src/dotnet-library/scala/Random.scala b/src/dotnet-library/scala/Random.scala
deleted file mode 100644
index aa8e017..0000000
--- a/src/dotnet-library/scala/Random.scala
+++ /dev/null
@@ -1,77 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: Random.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala
-
-/**
- *  @author Stephane Micheloud
- *
- *  Use class <code>scala.util.Random</code> instead.
- */
- at deprecated
-class Random(self0: System.Random) {
-  private var rnd = self0 // see setSeed(seed)
-  def self = rnd
-
-  /** Creates a new random number generator using a single long seed. */
-  def this(seed: Long) = this(new System.Random(seed.toInt))
-
-  /** Creates a new random number generator using a single integer seed. */
-  def this(seed: Int) = this(new System.Random(seed))
-
-  /** Creates a new random number generator. */
-  def this() = this(new System.Random(System.Environment.TickCount))
-
-  /** Returns the next pseudorandom, uniformly distributed boolean value
-   *  from this random number generator's sequence.
-   */
-  def nextBoolean(): Boolean = (nextInt() & 0x1) == 1
-
-  /** Generates random bytes and places them into a user-supplied byte
-   *  array.
-   */
-  def nextBytes(bytes: Array[Byte]) { rnd.NextBytes(bytes) }
-
-  /** Returns the next pseudorandom, uniformly distributed double value
-   *  between 0.0 and 1.0 from this random number generator's sequence.
-   */
-  def nextDouble(): Double = rnd.NextDouble()
-
-  /** Returns the next pseudorandom, uniformly distributed float value
-   *  between 0.0 and 1.0 from this random number generator's sequence.
-   */
-  def nextFloat(): Float = nextDouble().toFloat
-
-  /** Returns the next pseudorandom, Gaussian ("normally") distributed
-   *  double value with mean 0.0 and standard deviation 1.0 from this
-   *  random number generator's sequence.
-   */
-  //def nextGaussian(): Double
-
-  /** Returns the next pseudorandom, uniformly distributed int value
-   *  from this random number generator's sequence.
-   */
-  def nextInt(): Int = rnd.Next()
-
-  /** Returns a pseudorandom, uniformly distributed int value between 0
-   *  (inclusive) and the specified value (exclusive), drawn from this
-   *  random number generator's sequence.
-   */
-  def nextInt(n: Int): Int = rnd.Next(0, n)
-
-  /** Returns the next pseudorandom, uniformly distributed long value
-   *  from this random number generator's sequence.
-   */
-  def nextLong(): Long = nextInt().toLong // 2x nextInt() ?!
-
-  def setSeed(seed: Long) { rnd = new System.Random(seed.toInt) }
-
-}
diff --git a/src/dotnet-library/scala/StringBuilder.scala b/src/dotnet-library/scala/StringBuilder.scala
deleted file mode 100644
index 29a2360..0000000
--- a/src/dotnet-library/scala/StringBuilder.scala
+++ /dev/null
@@ -1,913 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: StringBuilder.scala 16881 2009-01-09 16:28:11Z cunei $
-
-
-package scala
-
-import Predef._
-
-/** <p>
- *    A mutable sequence of characters.  This class provides an API compatible
- *    with <code>java.lang.StringBuilder</code>, but with no guarantee of
- *    synchronization.
- *  </p>
- *
- *  @author Stephane Micheloud
- *  @version 1.0
- */
-final class StringBuilder(initCapacity: Int, private val initValue: String)
-extends (Int => Char) with Proxy {
-  if (initCapacity < 0) throw new IllegalArgumentException
-  if (initValue eq null) throw new NullPointerException
-
-  /** The value is used for character storage. */
-  private var value = new Array[Char](initCapacity + initValue.length)
-
-  /** The count is the number of characters used. */
-  private var count: Int = 0
-
-  /** Constructs a string builder with no characters in it and an 
-   *  initial capacity of 16 characters.
-   */
-  def this() = this(16, "")
-
-  /** Constructs a string builder with no characters in it and an 
-   *  initial capacity specified by the <code>capacity</code> argument. 
-   *
-   *  @param  capacity  the initial capacity.
-   *  @throws NegativeArraySizeException  if the <code>capacity</code>
-   *                    argument is less than <code>0</code>.
-   */
-  def this(capacity: Int) = this(capacity, "")
-
-  def this(str: String) = this(16, str)
-
-  append(initValue)
-
-  def self = this
-
-  def toArray: Array[Char] = value
-
-  def length: Int = count
-
-  def length_=(n: Int) { setLength(n) }
-
-  /** Sets the length of the character sequence.
-   *
-   *  @param  newLength  the new length
-   *  @throws IndexOutOfBoundsException  if the <code>n</code> argument is negative.
-   */
-  def setLength(n: Int) {
-    if (n < 0)
-      throw new StringIndexOutOfBoundsException//(n)
-    if (n > value.length) expandCapacity(n)
-    if (count < n)
-      while (count < n) {
-        value(count) = '\0'; count += 1
-      }
-    else
-      count = n
-  }
-
-  /** Returns the current capacity. The capacity is the amount of storage 
-   *  available for newly inserted characters, beyond which an allocation 
-   *  will occur.
-   *
-   *  @return  the current capacity
-   */
-  def capacity: Int = value.length
-
-  /** Same as <code>ensureCapacity</code>. */
-  def capacity_=(n: Int) { ensureCapacity(n) }
-
-  /** <p>
-   *    Ensures that the capacity is at least equal to the specified minimum.
-   *    If the current capacity is less than the argument, then a new internal
-   *    array is allocated with greater capacity. The new capacity is the larger of: 
-   *  </p>
-   *  <ul>
-   *    <li>The <code>n</code> argument. 
-   *    <li>Twice the old capacity, plus <code>2</code>. 
-   *  </ul>
-   *  <p>
-   *    If the <code>n</code> argument is non-positive, this
-   *    method takes no action and simply returns.
-   *  </p>
-   *
-   *  @param n the minimum desired capacity.
-   */
-  def ensureCapacity(n: Int) {
-    if (n > value.length) expandCapacity(n)
-  }
-
-  private def expandCapacity(n: Int) {
-    val newCapacity = (value.length + 1) * 2
-    value = StringBuilder.copyOf(
-      value,
-      if (newCapacity < 0) Math.MAX_INT else if (n > newCapacity) n else newCapacity
-    )
-  }
-
-  /** <p>
-   *    Returns the <code>Char</code> value in this sequence at the specified index.
-   *    The first <code>Char</code> value is at index <code>0</code>, the next at index
-   *    <code>1</code>, and so on, as in array indexing.
-   *  </p>
-   *  <p>
-   *    The index argument must be greater than or equal to
-   *    <code>0</code>, and less than the length of this sequence.
-   *  </p>
-   *
-   *  @param  index   the index of the desired <code>Char</code> value.
-   *  @return         the <code>Char</code> value at the specified index.
-   *  @throws IndexOutOfBoundsException  if <code>index</code> is 
-   *                  negative or greater than or equal to <code>length()</code>.
-   */
-  def charAt(index: Int): Char = {
-    if (index < 0 || index >= count)
-      throw new StringIndexOutOfBoundsException//(index)
-    value(index)
-  }
-
-  /** Same as <code>charAt</code>. */
-  def apply(i: Int): Char = charAt(i)
-
-  /** <p>
-   *    Removes the <code>Char</code> at the specified position in this
-   *    sequence. This sequence is shortened by one <code>Char</code>.
-   *  </p>
-   *
-   *  @param  index  Index of <code>Char</code> to remove
-   *  @return        This object.
-   *  @throws StringIndexOutOfBoundsException  if the <code>index</code>
-   *	             is negative or greater than or equal to <code>length()</code>.
-   */
-  def deleteCharAt(index: Int): StringBuilder = {
-    if (index < 0 || index >= count)
-      throw new StringIndexOutOfBoundsException//(index)
-    compat.Platform.arraycopy(value, index + 1, value, index, count - index - 1)
-    count -= 1
-    this
-  }
-
-  /** <p>
-   *    The character at the specified index is set to <code>ch</code>. This 
-   *    sequence is altered to represent a new character sequence that is 
-   *    identical to the old character sequence, except that it contains the 
-   *    character <code>ch</code> at position <code>index</code>. 
-   *  </p>
-   *  <p>
-   *    The index argument must be greater than or equal to 
-   *    <code>0</code>, and less than the length of this sequence. 
-   *  </p>
-   *
-   *  @param  index   the index of the character to modify.
-   *  @param  ch      the new character.
-   *  @throws IndexOutOfBoundsException  if <code>index</code> is 
-   *                  negative or greater than or equal to <code>length()</code>.
-   */
-  def setCharAt(index: Int, ch: Char) {
-    if (index < 0 || index >= count)
-      throw new StringIndexOutOfBoundsException//(index)
-    value(index) = ch
-  }
-
-  /** Same as <code>setCharAt</code>. */
-  def update(i: Int, c: Char) { setCharAt(i, c) }
-
-  /** Returns a new <code>String</code> that contains a subsequence of
-   *  characters currently contained in this character sequence. The 
-   *  substring begins at the specified index and extends to the end of
-   *  this sequence.
-   * 
-   *  @param  start  The beginning index, inclusive.
-   *  @return        The new string.
-   *  @throws StringIndexOutOfBoundsException  if <code>start</code> is
-   *                 less than zero, or greater than the length of this object.
-   */
-  def substring(start: Int): String = substring(start, count)
-
-  /** Returns a new <code>String</code> that contains a subsequence of
-   *  characters currently contained in this sequence. The 
-   *  substring begins at the specified <code>start</code> and 
-   *  extends to the character at index <code>end - 1</code>.
-   *
-   *  @param  start  The beginning index, inclusive.
-   *  @param  end    The ending index, exclusive.
-   *  @return The new string.
-   *  @throws StringIndexOutOfBoundsException  if <code>start</code>
-   *                 or <code>end</code> are negative or greater than
-   *		     <code>length()</code>, or <code>start</code> is
-   *		     greater than <code>end</code>.
-   */
-  def substring(start: Int, end: Int): String = {
-    if (start < 0)
-      throw new StringIndexOutOfBoundsException//(start)
-    if (end > count)
-      throw new StringIndexOutOfBoundsException//(end)
-    if (start > end)
-      throw new StringIndexOutOfBoundsException//(end - start)
-    new String(value, start, end - start)
-  }
-
-  /** <p>
-   *    Appends the string representation of the <code>Any</code> 
-   *    argument.
-   *  </p>
-   *  <p>
-   *    The argument is converted to a string as if by the method 
-   *    <code>System.Convert.ToString</code>, and the characters of
-   *    that string are then appended to this sequence.
-   *  </p>
-   *
-   *  @param  x   an <code>Any</code> object.
-   *  @return     a reference to this object.
-   */
-  def append(x: Any): StringBuilder =
-    append(System.Convert.ToString(x))
-
-  /** Appends the specified string to this character sequence.
-   *
-   *  @param  s   a string.
-   *  @return     a reference to this object.
-   */
-  def append(s: String): StringBuilder = {
-    val str = if (s == null) "null" else s
-    val len = str.length
-    if (len > 0) {
-      val newCount = count + len
-      if (newCount > value.length) expandCapacity(newCount)
-      compat.Platform.arraycopy(str.ToCharArray, 0, value, count, len)
-      count = newCount
-    }
-    this
-  }
-
-  /** Appends the specified string builder to this sequence.
-   *
-   *  @param sb
-   *  @return 
-   */
-  def append(sb: StringBuilder): StringBuilder =
-    if (sb == null)
-      append("null")
-    else {
-      val len = sb.length
-      val newCount = count + len
-      if (newCount > value.length) expandCapacity(newCount)
-      compat.Platform.arraycopy(sb.toArray, 0, value, count, len)
-      count = newCount
-      this
-    }
-
-  /** <p>
-   *    Appends the string representation of the <code>Char</code> sequence 
-   *    argument to this sequence.
-   *  </p>
-   *  <p>
-   *    The characters of the sequence argument are appended, in order,
-   *    to the contents of this sequence. The length of this sequence
-   *    increases by the length of the argument.
-   *  </p>
-   *
-   *  @param  x  the characters to be appended.
-   *  @return    a reference to this object.
-   */
-  def append(x: Seq[Char]): StringBuilder =
-    append(x.toArray, 0, x.length)
-
-  /** <p>
-   *    Appends the string representation of the <code>Char</code> array 
-   *    argument to this sequence.
-   *  </p>
-   *  <p>
-   *    The characters of the array argument are appended, in order, to 
-   *    the contents of this sequence. The length of this sequence
-   *    increases by the length of the argument.
-   *  </p>
-   *
-   *  @param  x  the characters to be appended.
-   *  @return    a reference to this object.
-   */
-  def append(x: Array[Char]): StringBuilder =
-    append(x, 0, x.length)
-
-  /** <p>
-   *    Appends the string representation of a subarray of the
-   *    <code>char</code> array argument to this sequence.
-   *  </p>
-   *  <p>
-   *    Characters of the <code>Char</code> array <code>x</code>, starting at
-   *    index <code>offset</code>, are appended, in order, to the contents
-   *    of this sequence. The length of this sequence increases
-   *    by the value of <code>len</code>.
-   *  </p>
-   *
-   *  @param  x      the characters to be appended.
-   *  @param  offset the index of the first <code>Char</code> to append.
-   *  @param  len    the number of <code>Char</code>s to append.
-   *  @return        a reference to this object.
-   */
-  def append(x: Array[Char], offset: Int, len: Int): StringBuilder = {
-    val newCount = count + len
-    if (newCount > value.length) expandCapacity(newCount)
-    compat.Platform.arraycopy(x, offset, value, count, len)
-    count = newCount
-    this
-  }
-
-  /** <p>
-   *    Appends the string representation of the <code>Boolean</code> 
-   *    argument to the sequence.
-   *  </p>
-   *  <p>
-   *    The argument is converted to a string as if by the method 
-   *    <code>System.Convert.ToString</code>, and the characters of 
-   *    that string are then appended to this sequence. 
-   *  </p>
-   *
-   *   @param  x  a <code>Boolean</code>.
-   *   @return    a reference to this object.
-   */
-  def append(x: Boolean): StringBuilder = {
-    if (x) {
-      val newCount = count + 4
-      if (newCount > value.length) expandCapacity(newCount)
-      value(count) = 't'; count += 1
-      value(count) = 'r'; count += 1
-      value(count) = 'u'; count += 1
-      value(count) = 'e'; count += 1
-    } else {
-      val newCount = count + 5
-      if (newCount > value.length) expandCapacity(newCount)
-      value(count) = 'f'; count += 1
-      value(count) = 'a'; count += 1
-      value(count) = 'l'; count += 1
-      value(count) = 's'; count += 1
-      value(count) = 'e'; count += 1
-    }
-    this
-  }
-
-  def append(x: Char): StringBuilder = {
-    val newCount = count + 1
-    if (newCount > value.length) expandCapacity(newCount)
-    value(count) = x; count += 1
-    this
-  }
-
-  def append(x: Short): StringBuilder =
-    append(System.Convert.ToString(x))
-
-  def append(x: Int): StringBuilder =
-    append(System.Convert.ToString(x))
-
-  def append(x: Long): StringBuilder =
-    append(System.Convert.ToString(x))
-
-  def append(x: Float): StringBuilder =
-    append(System.Convert.ToString(x))
-
-  def append(x: Double): StringBuilder = 
-    append(System.Convert.ToString(x))
-
-  /** Removes the characters in a substring of this sequence.
-   *  The substring begins at the specified <code>start</code> and extends to
-   *  the character at index <code>end - 1</code> or to the end of the
-   *  sequence if no such character exists. If
-   *  <code>start</code> is equal to <code>end</code>, no changes are made.
-   *
-   *  @param  start  The beginning index, inclusive.
-   *  @param  end    The ending index, exclusive.
-   *  @return        This object.
-   *  @throws StringIndexOutOfBoundsException  if <code>start</code>
-   *                 is negative, greater than <code>length()</code>, or
-   *		     greater than <code>end</code>.
-   */
-  def delete(start: Int, end: Int): StringBuilder = {
-    if (start < 0 || start > end)
-      throw new StringIndexOutOfBoundsException//(start)
-    val end0 = if (end > count) count else end
-    val len = end0 - start
-    if (len > 0) {
-      compat.Platform.arraycopy(value, start + len, value, start, count - end0)
-      count -= len
-    }
-    this
-  }
-
-  /** Replaces the characters in a substring of this sequence
-   *  with characters in the specified <code>String</code>. The substring
-   *  begins at the specified <code>start</code> and extends to the character
-   *  at index <code>end - 1</code> or to the end of the sequence if no such
-   *  character exists. First the characters in the substring are removed and
-   *  then the specified <code>String</code> is inserted at <code>start</code>.
-   * 
-   *  @param  start  The beginning index, inclusive.
-   *  @param  end    The ending index, exclusive.
-   *  @param  str    String that will replace previous contents.
-   *  @return        This object.
-   *  @throws StringIndexOutOfBoundsException  if <code>start</code>
-   *                 is negative, greater than <code>length()</code>, or
-   *		     greater than <code>end</code>.
-   */
-  def replace(start: Int, end: Int, str: String) {
-    if (start < 0 || start > count || start > end)
-      throw new StringIndexOutOfBoundsException//(start)
-
-    val end0 = if (end > count) count else end
-    val len = str.length()
-    val newCount = count + len - (end0 - start)
-    if (newCount > value.length) expandCapacity(newCount)
-
-    compat.Platform.arraycopy(value, end, value, start + len, count - end)
-    compat.Platform.arraycopy(str.ToCharArray, 0, value, start, len)
-    count = newCount
-    this
-  }
-
-  /** Inserts the string representation of a subarray of the <code>str</code>
-   *  array argument into this sequence. The subarray begins at the specified
-   *  <code>offset</code> and extends <code>len</code> <code>char</code>s.
-   *  The characters of the subarray are inserted into this sequence at
-   *  the position indicated by <code>index</code>. The length of this
-   *  sequence increases by <code>len</code> <code>Char</code>s.
-   *
-   * @param  index   position at which to insert subarray.
-   * @param  str     a <code>Char</code> array.
-   * @param  offset  the index of the first <code>char</code> in subarray to
-   *                 be inserted.
-   * @param  len     the number of <code>Char</code>s in the subarray to
-   *                 be inserted.
-   * @return         This object
-   * @throws StringIndexOutOfBoundsException  if <code>index</code>
-   *                 is negative or greater than <code>length()</code>, or
-   *                 <code>offset</code> or <code>len</code> are negative, or
-   *                 <code>(offset+len)</code> is greater than
-   *                 <code>str.length</code>.
-   */
-  def insert(index: Int, str: Array[Char], offset: Int, len: Int): StringBuilder = {
-    if (index < 0 || index > count)
-      throw new StringIndexOutOfBoundsException//(index)
-    if (offset < 0 || len < 0 || offset > str.length - len)
-      throw new StringIndexOutOfBoundsException/*(
-                "offset " + offset + ", len " + len +
-                ", str.length " + str.length)*/
-    val newCount = count + len
-    if (newCount > value.length) expandCapacity(newCount)
-    compat.Platform.arraycopy(value, index, value, index + len, count - index)
-    compat.Platform.arraycopy(str, offset, value, index, len)
-    count = newCount
-    this
-  }
-
-  /** <p>
-   *    Inserts the string representation of the <code>Any</code> 
-   *    argument into this character sequence.
-   *  </p>
-   *  <p>
-   *    The second argument is converted to a string as if by the method 
-   *    <code>System.Convert.ToString</code>, and the characters of that 
-   *    string are then inserted into this sequence at the indicated 
-   *    offset. 
-   *  </p>
-   *  <p>
-   *    The offset argument must be greater than or equal to 
-   *    <code>0</code>, and less than or equal to the length of this 
-   *    sequence.
-   *  </p>
-   *
-   *  @param  offset  the offset.
-   *  @param  x       an <code>Any</code> value.
-   *  @return         a reference to this object.
-   *  @throws StringIndexOutOfBoundsException  if the offset is invalid.
-   */
-  def insert(at: Int, x: Any): StringBuilder =
-    insert(at, System.Convert.ToString(x))
-
-  /** Inserts the string into this character sequence.
-   *
-   *  @param  at  the offset position.
-   *  @param  x   a string.
-   *  @return     a reference to this object.
-   *  @throws StringIndexOutOfBoundsException  if the offset is invalid.
-   */
-  def insert(at: Int, x: String): StringBuilder = {
-    if (at < 0 || at > count)
-      throw new StringIndexOutOfBoundsException//(at)
-    val str = if (x == null) "null" else x
-    val len = str.length
-    val newCount = count + len
-    if (newCount > value.length) expandCapacity(newCount)
-    compat.Platform.arraycopy(value, at, value, at + len, count - at)
-    compat.Platform.arraycopy(str.ToCharArray, 0, value, at, len)
-    count = newCount
-    this
-  }
-
-  /** Inserts the string representation of the <code>Char</code> sequence 
-   *  argument into this sequence.
-   *
-   *  @param  at  the offset position.
-   *  @param  x   a character sequence.
-   *  @return     a reference to this object.
-   *  @throws StringIndexOutOfBoundsException  if the offset is invalid.
-   */
-  def insert(at: Int, x: Seq[Char]): StringBuilder =
-    insert(at, x.toArray)
-
-  /** Inserts the string representation of the <code>Char</code> array 
-   *  argument into this sequence.
-   *
-   *  @param  at  the offset position.
-   *  @param  x   a character array.
-   *  @return     a reference to this object.
-   *  @throws StringIndexOutOfBoundsException  if the offset is invalid.
-   */
-  def insert(at: Int, x: Array[Char]): StringBuilder = {
-    if (at < 0 || at > count)
-      throw new StringIndexOutOfBoundsException//(at)
-    val len = x.length
-    val newCount = count + len
-    if (newCount > value.length) expandCapacity(newCount)
-    compat.Platform.arraycopy(value, at, value, at + len, count - at)
-    compat.Platform.arraycopy(x, 0, value, at, len)
-    count = newCount
-    this
-  }
-
-  /** <p>
-   *    Inserts the string representation of the <code>Boolean</code> argument
-   *    into this sequence.
-   *  </p>
-   *  <p>
-   *    The offset argument must be greater than or equal to 0, and less than
-   *    or equal to the length of this sequence.
-   *  </p>
-   *
-   *  @param  at  the offset position.
-   *  @param  x   a <code>Boolean</code> value.
-   *  @return     a reference to this object.
-   */
-  def insert(at: Int, x: Boolean): StringBuilder =
-    insert(at, System.Convert.ToString(x))
-
-
-  /** <p>
-   *    Inserts the string representation of the <code>Char</code> argument
-   *    into this sequence.
-   *  </p>
-   *  <p>
-   *    The offset argument must be greater than or equal to 0, and less than
-   *    or equal to the length of this sequence.
-   *  </p>
-   *
-   *  @param  at  the offset position.
-   *  @param  x   a <code>Char</code> value.
-   *  @return     a reference to this object.
-   */
-  def insert(at: Int, x: Char): StringBuilder = {
-    if (at < 0 || at > count)
-      throw new StringIndexOutOfBoundsException//(at)
-    val newCount = count + 1
-    if (newCount > value.length) expandCapacity(newCount)
-    compat.Platform.arraycopy(value, at, value, at + 1, count - at)
-    value(at) = x
-    count = newCount
-    this
-  }
-
-  /** <p>
-   *    Inserts the string representation of the <code>Short</code> argument
-   *    into this sequence.
-   *  </p>
-   *  <p>
-   *    The offset argument must be greater than or equal to 0, and less than
-   *    or equal to the length of this sequence.
-   *  </p>
-   *
-   *  @param  at  the offset position.
-   *  @param  x   a <code>Short</code> value.
-   *  @return     a reference to this object.
-   */
-  def insert(at: Int, x: Short): StringBuilder =
-    insert(at, System.Convert.ToString(x))
-
-  /** <p>
-   *    Inserts the string representation of the <code>Int</code> argument
-   *    into this sequence.
-   *  </p>
-   *  <p>
-   *    The offset argument must be greater than or equal to 0, and less than
-   *    or equal to the length of this sequence.
-   *  </p>
-   *
-   *  @param  at  the offset position.
-   *  @param  x   a <code>Int</code> value.
-   *  @return     a reference to this object.
-   */
-  def insert(at: Int, x: Int): StringBuilder =
-    insert(at, System.Convert.ToString(x))
-
-  /** <p>
-   *    Inserts the string representation of the <code>Long</code> argument
-   *    into this sequence.
-   *  </p>
-   *  <p>
-   *    The offset argument must be greater than or equal to 0, and less than
-   *    or equal to the length of this sequence.
-   *  </p>
-   *
-   *  @param  at  the offset position.
-   *  @param  x   a <code>Long</code> value.
-   *  @return     a reference to this object.
-   */
-  def insert(at: Int, x: Long): StringBuilder =
-    insert(at, System.Convert.ToString(x))
-
-  /** <p>
-   *    Inserts the string representation of the <code>Float</code> argument
-   *    into this sequence.
-   *  </p>
-   *  <p>
-   *    The offset argument must be greater than or equal to 0, and less than
-   *    or equal to the length of this sequence.
-   *  </p>
-   *
-   *  @param  at  the offset position.
-   *  @param  x   a <code>Float</code> value.
-   *  @return     a reference to this object.
-   */
-  def insert(at: Int, x: Float): StringBuilder =
-    insert(at, System.Convert.ToString(x))
-
-  /** <p>
-   *    Inserts the string representation of the <code>Double</code> argument
-   *    into this sequence.
-   *  </p>
-   *  <p>
-   *    The offset argument must be greater than or equal to 0, and less than
-   *    or equal to the length of this sequence.
-   *  </p>
-   *
-   *  @param  at  the offset position.
-   *  @param  x   a <code>Double</code> value.
-   *  @return     a reference to this object.
-   */
-  def insert(at: Int, x: Double): StringBuilder =
-    insert(at, System.Convert.ToString(x))
-
-  /** <p>
-   *    Returns the index within this string of the first occurrence of the
-   *    specified substring. The integer returned is the smallest value 
-   *    <i>k</i> such that:
-   *  </p>
-   *  <blockquote><pre>
-   *  this.toString().startsWith(str, <i>k</i>)</pre>
-   *  </blockquote>
-   *  <p>
-   *    is <code>true</code>.
-   *  </p>
-   *
-   *  @param  str  any string.
-   *  @return      if the string argument occurs as a substring within this
-   *               object, then the index of the first character of the first
-   *               such substring is returned; if it does not occur as a
-   *               substring, <code>-1</code> is returned.
-   *  @throws NullPointerException if <code>str</code> is <code>null</code>.
-   */
-  def indexOf(str: String): Int = indexOf(str, 0)
-
-  /** <p>
-   *    Returns the index within this string of the first occurrence of the
-   *    specified substring, starting at the specified index. The integer
-   *    returned is the smallest value <code>k</code> for which:
-   *  </p><pre>
-   *    k >= Math.min(fromIndex, str.length()) &&
-   *                   this.toString().startsWith(str, k)</pre>
-   *  <p>
-   *    If no such value of <code>k</code> exists, then <code>-1</code>
-   *    is returned.
-   *  </p>
-   *
-   *  @param str        the substring for which to search.
-   *  @param fromIndex  the index from which to start the search.
-   *  @return           the index within this string of the first occurrence
-   *                    of the specified substring, starting at the specified index.
-   */
-  def indexOf(str: String, fromIndex: Int): Int =
-    StringBuilder.indexOf(value, 0, count, str.ToCharArray, 0, str.length(), fromIndex)
-
-  /** <p>
-   *    Returns the index within this string of the rightmost occurrence
-   *    of the specified substring.  The rightmost empty string "" is
-   *    considered to occur at the index value <code>this.length()</code>. 
-   *    The returned index is the largest value <i>k</i> such that 
-   *  </p>
-   *  <blockquote><pre>
-   *  this.toString().startsWith(str, k)</pre>
-   *  </blockquote>
-   *  <p>
-   *    is true.
-   *  </p>
-   *
-   * @param  str  the substring to search for.
-   * @return      if the string argument occurs one or more times as a substring
-   *              within this object, then the index of the first character of
-   *              the last such substring is returned. If it does not occur as
-   *              a substring, <code>-1</code> is returned.
-   * @throws NullPointerException  if <code>str</code> is <code>null</code>.
-   */
-  def lastIndexOf(str: String): Int = lastIndexOf(str, count)
-
-  /** <p>
-   *    Returns the index within this string of the last occurrence of the
-   *    specified substring. The integer returned is the largest value
-   *    <code>k</code> such that:
-   *  </p><pre>
-   *    k <= Math.min(fromIndex, str.length()) &&
-   *                   this.toString().startsWith(str, k)</pre>
-   *  <p>
-   *    If no such value of <code>k</code> exists, then <code>-1</code>
-   *    is returned.
-   *  </p>
-   *
-   *  @param  str        the substring to search for.
-   *  @param  fromIndex  the index to start the search from.
-   *  @return            the index within this sequence of the last occurrence
-   *                     of the specified substring.
-   */
-  def lastIndexOf(str: String, fromIndex: Int): Int =
-    StringBuilder.lastIndexOf(value, 0, count, str.ToCharArray, 0, str.length(), fromIndex)
-
-  /** <p>
-   *    Causes this character sequence to be replaced by the reverse of the
-   *    sequence. If there are any surrogate pairs included in the sequence,
-   *    these are treated as single characters for the reverse operation.
-   *    Thus, the order of the high-low surrogates is never reversed.
-   *  </p>
-   *  <p>
-   *    Let <i>n</i> be the character length of this character sequence
-   *    (not the length in <code>Char</code> values) just prior to
-   *    execution of the <code>reverse</code> method. Then the
-   *    character at index <i>k</i> in the new character sequence is
-   *    equal to the character at index <i>n-k-1</i> in the old
-   *    character sequence.
-   *  </p>
-   *
-   *  @return  a reference to this object.
-   */
-  def reverse(): StringBuilder = {
-    var hasSurrogate = false
-    val n = count - 1
-    var j = (n-1) >> 1
-    while (j >= 0) {
-      val temp = value(j)
-      val temp2 = value(n - j)
-      if (!hasSurrogate)
-        hasSurrogate =
-          (temp >= StringBuilder.MIN_SURROGATE && temp <= StringBuilder.MAX_SURROGATE) ||
-       	  (temp2 >= StringBuilder.MIN_SURROGATE && temp2 <= StringBuilder.MAX_SURROGATE)
-      value(j) = temp2
-      value(n - j) = temp
-      j -= 1
-    }
-    if (hasSurrogate) {
-      // Reverse back all valid surrogate pairs
-      var i = 0
-      while (i < count - 1) {
-        val c2 = value(i)
-	if (StringBuilder.isLowSurrogate(c2)) {
-          val c1 = value(i + 1)
-          if (StringBuilder.isHighSurrogate(c1)) {
-            value(i) = c1; i += 1
-            value(i) = c2
-          }
-        }
-        i += 1
-      }
-    }
-    this
-  }
-
-  /** Returns a string representing the data in this sequence.
-   *  A new <code>String</code> object is allocated and initialized to 
-   *  contain the character sequence currently represented by this 
-   *  object. This <code>String</code> is then returned. Subsequent 
-   *  changes to this sequence do not affect the contents of the 
-   *  <code>String</code>.
-   *
-   *  @return  a string representation of this sequence of characters.
-   */
-  override def toString(): String = new String(value, 0, count)
-
-}
-
-
-object StringBuilder {
-
-  private val MIN_HIGH_SURROGATE = '\uD800'
-  private val MAX_HIGH_SURROGATE = '\uDBFF'
-
-  private val MIN_LOW_SURROGATE = '\uDC00'
-  private val MAX_LOW_SURROGATE = '\uDFFF'
-
-  // constants <code>java.langCharacter.MIN-/MAX_SURROGATE</code> exist since 1.5
-  private val MIN_SURROGATE = MIN_HIGH_SURROGATE
-  private val MAX_SURROGATE = MAX_LOW_SURROGATE
-
-  // methods <code>java.langCharacter.isLow-/isHighSurrogate</code> exist since 1.5
-  private def isLowSurrogate(ch: Char): Boolean =
-    MIN_LOW_SURROGATE <= ch && ch <= MAX_LOW_SURROGATE
-
-  private def isHighSurrogate(ch: Char): Boolean =
-    MIN_HIGH_SURROGATE <= ch && ch <= MAX_HIGH_SURROGATE
-
-  // method <code>java.util.Arrays.copyOf</code> exists since 1.6
-  private def copyOf(src: Array[Char], newLength: Int): Array[Char] = {
-    val dest = new Array[Char](newLength)
-    compat.Platform.arraycopy(src, 0, dest, 0, Math.min(src.length, newLength))
-    dest
-  }
-
-  private def indexOf(source: Array[Char], sourceOffset: Int, sourceCount: Int,
-                      target: Array[Char], targetOffset: Int, targetCount: Int,
-                      fromIndex: Int): Int =
-    if (fromIndex >= sourceCount)
-      if (targetCount == 0) sourceCount else -1
-    else {
-      val inx = if (fromIndex < 0) 0 else fromIndex
-      if (targetCount == 0)
-        inx
-      else {
-        val first  = target(targetOffset)
-        val max = sourceOffset + (sourceCount - targetCount)
-
-        var i = sourceOffset + inx
-        while (i <= max) {
-          /* Look for first character. */
-          if (source(i) != first) {
-            i += 1
-            while (i <= max && source(i) != first) i += 1
-          }
-          /* Found first character, now look at the rest of v2 */
-          if (i <= max) {
-            var j = i + 1
-            val end = j + targetCount - 1
-            var k = targetOffset + 1
-            while (j < end && source(j) == target(k)) {
-              j += 1
-              k += 1
-            }
-            if (j == end) {
-              /* Found whole string. */
-              return i - sourceOffset
-            }
-          } // if
-          i += 1
-        } // while
-        -1
-      }
-    }
-
-  private def lastIndexOf(source: Array[Char], sourceOffset: Int, sourceCount: Int,
-                          target: Array[Char], targetOffset: Int, targetCount: Int,
-                          fromIndex: Int): Int = {
-    val rightIndex = sourceCount - targetCount
-    if (fromIndex < 0) return -1
-    val inx = if (fromIndex > rightIndex) rightIndex else fromIndex
-    // Empty string always matches
-    if (targetCount == 0) return inx
-
-    val strLastIndex = targetOffset + targetCount - 1
-    val strLastChar = target(strLastIndex)
-    val min = sourceOffset + targetCount - 1
-    var i = min + fromIndex
-
-    while (true) {
-      while (i >= min && source(i) != strLastChar) i -= 1
-      if (i < min) return -1
-      var j = i - 1
-      val start = j - (targetCount - 1)
-      var k = strLastIndex - 1
-      var outerWhile = false
-      while (j > start && !outerWhile) {
-        if (source(j) != target(k)) {
-          j -= 1
-          k -= 1
-          i -= 1
-          outerWhile = true
-        }
-      }
-      if (!outerWhile) return start - sourceOffset + 1
-    }
-    -1
-  }
-}
diff --git a/src/dotnet-library/scala/Symbol.scala b/src/dotnet-library/scala/Symbol.scala
deleted file mode 100644
index 3bbc70b..0000000
--- a/src/dotnet-library/scala/Symbol.scala
+++ /dev/null
@@ -1,49 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: Symbol.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala
-
-
-/** <p>
- *    Instances of <code>Symbol</code> can be created easily with
- *    Scala's built-in quote mechanism.
- *  </p>
- *  <p>
- *    For instance, the <a href="http://scala-lang.org/" target="_top">Scala</a>
- *    term <code>'mysym</code> will invoke the constructor of the
- *    <code>Symbol</code> class in the following way:
- *    <code>new Symbol("mysym")</code>.
- *  </p>
- *  
- *  @author  Martin Odersky
- *  @version 1.7, 08/12/2003
- */
-final case class Symbol(name: String) {
-
-  /** Converts this symbol to a string.
-   */
-  override def toString(): String = {
-    "'" + name
-  }
-
-  /** <p>
-   *    Makes this symbol into a unique reference.
-   *  </p>
-   *  <p>
-   *    If two interened symbols are equal (i.e. they have the same name)
-   *    then they must be identical (wrt reference equality).
-   *  </p>
-   *
-   *  @return the unique reference to this symbol.
-   */
-  def intern: Symbol = this
-
-}
diff --git a/src/dotnet-library/scala/collection/immutable/PagedSeq.scala b/src/dotnet-library/scala/collection/immutable/PagedSeq.scala
deleted file mode 100644
index afa2ef2..0000000
--- a/src/dotnet-library/scala/collection/immutable/PagedSeq.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* PagedSeq does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/collection/jcl/ArrayList.scala b/src/dotnet-library/scala/collection/jcl/ArrayList.scala
deleted file mode 100644
index b708c82..0000000
--- a/src/dotnet-library/scala/collection/jcl/ArrayList.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* ArrayList does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/collection/jcl/Buffer.scala b/src/dotnet-library/scala/collection/jcl/Buffer.scala
deleted file mode 100644
index e90266c..0000000
--- a/src/dotnet-library/scala/collection/jcl/Buffer.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* Buffer does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/collection/jcl/BufferIterator.scala b/src/dotnet-library/scala/collection/jcl/BufferIterator.scala
deleted file mode 100644
index 4807032..0000000
--- a/src/dotnet-library/scala/collection/jcl/BufferIterator.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* BufferIterator does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/collection/jcl/BufferWrapper.scala b/src/dotnet-library/scala/collection/jcl/BufferWrapper.scala
deleted file mode 100644
index ba77694..0000000
--- a/src/dotnet-library/scala/collection/jcl/BufferWrapper.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* BufferWrapper does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/collection/jcl/Collection.scala b/src/dotnet-library/scala/collection/jcl/Collection.scala
deleted file mode 100644
index 6972e14..0000000
--- a/src/dotnet-library/scala/collection/jcl/Collection.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* Collection does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/collection/jcl/CollectionWrapper.scala b/src/dotnet-library/scala/collection/jcl/CollectionWrapper.scala
deleted file mode 100644
index 7006b11..0000000
--- a/src/dotnet-library/scala/collection/jcl/CollectionWrapper.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* CollectionWrapper does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/collection/jcl/Conversions.scala b/src/dotnet-library/scala/collection/jcl/Conversions.scala
deleted file mode 100644
index 97c99f6..0000000
--- a/src/dotnet-library/scala/collection/jcl/Conversions.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* Conversions does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/collection/jcl/HashMap.scala b/src/dotnet-library/scala/collection/jcl/HashMap.scala
deleted file mode 100644
index e62738f..0000000
--- a/src/dotnet-library/scala/collection/jcl/HashMap.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* HashMap does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/collection/jcl/HashSet.scala b/src/dotnet-library/scala/collection/jcl/HashSet.scala
deleted file mode 100644
index c2599b2..0000000
--- a/src/dotnet-library/scala/collection/jcl/HashSet.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* HashSet does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/collection/jcl/Hashtable.scala b/src/dotnet-library/scala/collection/jcl/Hashtable.scala
deleted file mode 100644
index cf07705..0000000
--- a/src/dotnet-library/scala/collection/jcl/Hashtable.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* Hashtable does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/collection/jcl/IdentityHashMap.scala b/src/dotnet-library/scala/collection/jcl/IdentityHashMap.scala
deleted file mode 100644
index e121285..0000000
--- a/src/dotnet-library/scala/collection/jcl/IdentityHashMap.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* IdentityHashMap does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/collection/jcl/IterableWrapper.scala b/src/dotnet-library/scala/collection/jcl/IterableWrapper.scala
deleted file mode 100644
index 076d707..0000000
--- a/src/dotnet-library/scala/collection/jcl/IterableWrapper.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* IterableWrapper does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/collection/jcl/LinkedHashMap.scala b/src/dotnet-library/scala/collection/jcl/LinkedHashMap.scala
deleted file mode 100644
index 77de6a4..0000000
--- a/src/dotnet-library/scala/collection/jcl/LinkedHashMap.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* LinkedHashMap does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/collection/jcl/LinkedHashSet.scala b/src/dotnet-library/scala/collection/jcl/LinkedHashSet.scala
deleted file mode 100644
index 3de125b..0000000
--- a/src/dotnet-library/scala/collection/jcl/LinkedHashSet.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* LinkedHashSet does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/collection/jcl/LinkedList.scala b/src/dotnet-library/scala/collection/jcl/LinkedList.scala
deleted file mode 100644
index e512dd4..0000000
--- a/src/dotnet-library/scala/collection/jcl/LinkedList.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* LinkedList does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/collection/jcl/Map.scala b/src/dotnet-library/scala/collection/jcl/Map.scala
deleted file mode 100644
index aed3a99..0000000
--- a/src/dotnet-library/scala/collection/jcl/Map.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* Map does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/collection/jcl/MapWrapper.scala b/src/dotnet-library/scala/collection/jcl/MapWrapper.scala
deleted file mode 100644
index 77d4700..0000000
--- a/src/dotnet-library/scala/collection/jcl/MapWrapper.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* MapWrapper does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/collection/jcl/MutableIterable.scala b/src/dotnet-library/scala/collection/jcl/MutableIterable.scala
deleted file mode 100644
index 87b2d9f..0000000
--- a/src/dotnet-library/scala/collection/jcl/MutableIterable.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* MutableIterable does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/collection/jcl/MutableIterator.scala b/src/dotnet-library/scala/collection/jcl/MutableIterator.scala
deleted file mode 100644
index 1ada29b..0000000
--- a/src/dotnet-library/scala/collection/jcl/MutableIterator.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* MutableIterator does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/collection/jcl/MutableSeq.scala b/src/dotnet-library/scala/collection/jcl/MutableSeq.scala
deleted file mode 100644
index 60132e8..0000000
--- a/src/dotnet-library/scala/collection/jcl/MutableSeq.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* MutableSeq does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/collection/jcl/Ranged.scala b/src/dotnet-library/scala/collection/jcl/Ranged.scala
deleted file mode 100644
index 5394b8b..0000000
--- a/src/dotnet-library/scala/collection/jcl/Ranged.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* Ranged does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/collection/jcl/SeqIterator.scala b/src/dotnet-library/scala/collection/jcl/SeqIterator.scala
deleted file mode 100644
index 1d952ba..0000000
--- a/src/dotnet-library/scala/collection/jcl/SeqIterator.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* SeqIterator does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/collection/jcl/Set.scala b/src/dotnet-library/scala/collection/jcl/Set.scala
deleted file mode 100644
index 5c5bae7..0000000
--- a/src/dotnet-library/scala/collection/jcl/Set.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* Set does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/collection/jcl/SetWrapper.scala b/src/dotnet-library/scala/collection/jcl/SetWrapper.scala
deleted file mode 100644
index 448b137..0000000
--- a/src/dotnet-library/scala/collection/jcl/SetWrapper.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* SetWrapper does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/collection/jcl/Sorted.scala b/src/dotnet-library/scala/collection/jcl/Sorted.scala
deleted file mode 100644
index 7fcfe8a..0000000
--- a/src/dotnet-library/scala/collection/jcl/Sorted.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* Sorted does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/collection/jcl/SortedMap.scala b/src/dotnet-library/scala/collection/jcl/SortedMap.scala
deleted file mode 100644
index dbbc103..0000000
--- a/src/dotnet-library/scala/collection/jcl/SortedMap.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* SortedMap does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/collection/jcl/SortedMapWrapper.scala b/src/dotnet-library/scala/collection/jcl/SortedMapWrapper.scala
deleted file mode 100644
index dbf001f..0000000
--- a/src/dotnet-library/scala/collection/jcl/SortedMapWrapper.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* SortedMapWrapper does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/collection/jcl/SortedSet.scala b/src/dotnet-library/scala/collection/jcl/SortedSet.scala
deleted file mode 100644
index 6b7351b..0000000
--- a/src/dotnet-library/scala/collection/jcl/SortedSet.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* SortedSet does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/collection/jcl/SortedSetWrapper.scala b/src/dotnet-library/scala/collection/jcl/SortedSetWrapper.scala
deleted file mode 100644
index e2667de..0000000
--- a/src/dotnet-library/scala/collection/jcl/SortedSetWrapper.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* SortedSetWrapper does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/collection/jcl/Tests.scala b/src/dotnet-library/scala/collection/jcl/Tests.scala
deleted file mode 100644
index 3939b18..0000000
--- a/src/dotnet-library/scala/collection/jcl/Tests.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* Tests does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/collection/jcl/TreeMap.scala b/src/dotnet-library/scala/collection/jcl/TreeMap.scala
deleted file mode 100644
index 3c6efab..0000000
--- a/src/dotnet-library/scala/collection/jcl/TreeMap.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* TreeMap does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/collection/jcl/TreeSet.scala b/src/dotnet-library/scala/collection/jcl/TreeSet.scala
deleted file mode 100644
index 9a32c52..0000000
--- a/src/dotnet-library/scala/collection/jcl/TreeSet.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* TreeSet does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/collection/jcl/WeakHashMap.scala b/src/dotnet-library/scala/collection/jcl/WeakHashMap.scala
deleted file mode 100644
index dbe2039..0000000
--- a/src/dotnet-library/scala/collection/jcl/WeakHashMap.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* WeakHashMap does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/collection/mutable/JavaMapAdaptor.scala b/src/dotnet-library/scala/collection/mutable/JavaMapAdaptor.scala
deleted file mode 100644
index fec4858..0000000
--- a/src/dotnet-library/scala/collection/mutable/JavaMapAdaptor.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* JavaMapAdaptor does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/collection/mutable/JavaSetAdaptor.scala b/src/dotnet-library/scala/collection/mutable/JavaSetAdaptor.scala
deleted file mode 100644
index 36ba221..0000000
--- a/src/dotnet-library/scala/collection/mutable/JavaSetAdaptor.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* JavaSetAdaptor does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/collection/mutable/OpenHashMap.scala b/src/dotnet-library/scala/collection/mutable/OpenHashMap.scala
deleted file mode 100644
index df3bcad..0000000
--- a/src/dotnet-library/scala/collection/mutable/OpenHashMap.scala
+++ /dev/null
@@ -1,4 +0,0 @@
-/** OpenHashMap.scala currently doesn't work on .NET because of a bug.
- *  Remove this file once the ticket is closed.
- *  http://lampsvn.epfl.ch/trac/scala/ticket/1218
- */
diff --git a/src/dotnet-library/scala/compat/Platform.scala b/src/dotnet-library/scala/compat/Platform.scala
deleted file mode 100644
index 3774835..0000000
--- a/src/dotnet-library/scala/compat/Platform.scala
+++ /dev/null
@@ -1,63 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: Platform.scala 16881 2009-01-09 16:28:11Z cunei $
-
-
-package scala.compat
-
-
-import Predef._
-
-object Platform {
-
-  type StackOverflowError = System.StackOverflowException
-  type ConcurrentModificationException = System.Exception
-
-  /**
-   *  @param src     ..
-   *  @param srcPos  ..
-   *  @param dest    ..
-   *  @param destPos ..
-   *  @param length  ..
-   */
-  def arraycopy(src: AnyRef, srcPos: Int, dest: AnyRef, destPos: Int, length: Int) {
-    if (!src.isInstanceOf[System.Array]) throw new Exception("src for arraycopy is not an Array; use scala.Array.copy for boxed arrays");
-    if (!dest.isInstanceOf[System.Array]) throw new Exception("dest for arraycopy is not an Array; use scala.Array.copy for boxed arrays");
-    System.Array.Copy(src.asInstanceOf[System.Array], srcPos, dest.asInstanceOf[System.Array], destPos, length)
-  }
-
-  /** Create array of the same type as arrayInstance with the given
-   *  length.
-   *
-   *  @param elemClass ..
-   *  @param length    ..
-   *  @return          ..
-   */
-  def createArray(elemClass: Class[_], length: Int): AnyRef =
-    System.Array.CreateInstance(elemClass, length)
-
-  def arrayclear(arr: Array[Int]) {
-    System.Array.Clear(arr.asInstanceOf[System.Array], 0, arr.length)
-  }
-
-  def getClassForName(name: String): Class[_] = System.Type.GetType(name)
-
-  val EOL = System.Environment.NewLine
-
-  def currentTime: Long = 0L
-/* // compiler crash :-(
-  private lazy val baseTicks = (new System.DateTime(1970, 1, 1, 0, 0, 0)).Ticks
-  def currentTime: Long = {
-    val nowTicks = System.DateTime.UtcNow.Ticks
-    (nowTicks - baseTicks) / 10000
-  }
-*/
-  def collectGarbage { System.GC.Collect() }
-
-}
diff --git a/src/dotnet-library/scala/concurrent/jolib.scala b/src/dotnet-library/scala/concurrent/jolib.scala
deleted file mode 100644
index 73cb5bf..0000000
--- a/src/dotnet-library/scala/concurrent/jolib.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* jolib does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/concurrent/ops.scala b/src/dotnet-library/scala/concurrent/ops.scala
deleted file mode 100644
index 7251a6a..0000000
--- a/src/dotnet-library/scala/concurrent/ops.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* ops does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/concurrent/pilib.scala b/src/dotnet-library/scala/concurrent/pilib.scala
deleted file mode 100644
index 249110e..0000000
--- a/src/dotnet-library/scala/concurrent/pilib.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* pilib does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/io/BufferedSource.scala b/src/dotnet-library/scala/io/BufferedSource.scala
deleted file mode 100644
index 93f7c77..0000000
--- a/src/dotnet-library/scala/io/BufferedSource.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* BufferedSource.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/io/BytePickle.scala b/src/dotnet-library/scala/io/BytePickle.scala
deleted file mode 100644
index f394307..0000000
--- a/src/dotnet-library/scala/io/BytePickle.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* BytePickle.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/io/Position.scala b/src/dotnet-library/scala/io/Position.scala
deleted file mode 100644
index 353cb08..0000000
--- a/src/dotnet-library/scala/io/Position.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* Position.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/io/Source.scala b/src/dotnet-library/scala/io/Source.scala
deleted file mode 100644
index 8730782..0000000
--- a/src/dotnet-library/scala/io/Source.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* Source.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/io/UTF8Codec.scala b/src/dotnet-library/scala/io/UTF8Codec.scala
deleted file mode 100644
index ce953d0..0000000
--- a/src/dotnet-library/scala/io/UTF8Codec.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* UTF8Codec.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/mobile/Code.scala b/src/dotnet-library/scala/mobile/Code.scala
deleted file mode 100644
index 51c9974..0000000
--- a/src/dotnet-library/scala/mobile/Code.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* Code.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/mobile/Location.scala b/src/dotnet-library/scala/mobile/Location.scala
deleted file mode 100644
index 1e55c24..0000000
--- a/src/dotnet-library/scala/mobile/Location.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* Location.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/ref/PhantomReference.scala b/src/dotnet-library/scala/ref/PhantomReference.scala
deleted file mode 100644
index d2bc86f..0000000
--- a/src/dotnet-library/scala/ref/PhantomReference.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* PhantomReference does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/ref/ReferenceQueue.scala b/src/dotnet-library/scala/ref/ReferenceQueue.scala
deleted file mode 100644
index cc95c40..0000000
--- a/src/dotnet-library/scala/ref/ReferenceQueue.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* ReferenceQueue does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/ref/ReferenceWrapper.scala b/src/dotnet-library/scala/ref/ReferenceWrapper.scala
deleted file mode 100644
index 3a95443..0000000
--- a/src/dotnet-library/scala/ref/ReferenceWrapper.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* ReferenceWrapper does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/ref/SoftReference.scala b/src/dotnet-library/scala/ref/SoftReference.scala
deleted file mode 100644
index decd2c9..0000000
--- a/src/dotnet-library/scala/ref/SoftReference.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* SoftReference does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/ref/WeakReference.scala b/src/dotnet-library/scala/ref/WeakReference.scala
deleted file mode 100644
index 322d270..0000000
--- a/src/dotnet-library/scala/ref/WeakReference.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* WeakReference does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/reflect/Manifest.scala b/src/dotnet-library/scala/reflect/Manifest.scala
deleted file mode 100644
index 8e48dae..0000000
--- a/src/dotnet-library/scala/reflect/Manifest.scala
+++ /dev/null
@@ -1,143 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2007-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: Manifest.scala 16881 2009-01-09 16:28:11Z cunei $
-
-
-package scala.reflect
-
-/** <p>
-  *   A <code>Manifest[T]</code> is an opaque descriptor for type <code>T</code>.
-  *   Currently, its only use is to give access to the erasure of the type as a
-  *   <code>Class</code> instance.
-  * </p>
-  * <p>
-  *   <b>BE AWARE</b>: The different type-relation operators are all forwarded 
-  *   to the erased type as an approximation of the final semantics where
-  *   these operators should be on the unerased type.
-  * </p>
-  */
-trait Manifest[T] {
-
-  /** A class representing the type U to which T would be erased. Note
-    * that there is no subtyping relationship between T and U. */
-  def erasure: Predef.Class[U] forSome { type U }
-
-  /** Tests whether the type represented by this manifest is a subtype of
-    * the type represented by `that' manifest. BE AWARE: the current
-    * implementation is an approximation, as the test is done on the
-    * erasure of the type. */
-  def <:<(that: Manifest[_]): Boolean = {
-    def subtype(sub: Predef.Class[_], sup: Predef.Class[_]): Boolean = {
-      val subSuperClass = sub.BaseType
-      val subSuperInterfaces = sub.GetInterfaces.toList
-      val subSuper =
-        (if (subSuperClass == null) Nil else List(subSuperClass)) ::: subSuperInterfaces
-      (subSuper contains sup) || (subSuper exists (subtype(_, sup)))
-    }
-    this.erasure == that.erasure || subtype(this.erasure, that.erasure)
-  }
-  
-  /** Tests whether the type represented by this manifest is a supertype 
-    * of the type represented by `that' manifest. BE AWARE: the current
-    * implementation is an approximation, as the test is done on the
-    * erasure of the type. */
-  def >:>(that: Manifest[_]): Boolean =
-    that <:< this
-    
-  /** Tests whether the type represented by this manifest is equal to the
-    * type represented by `that' manifest. BE AWARE: the current
-    * implementation is an approximation, as the test is done on the
-    * erasure of the type. */
-  override def equals(that: Any): Boolean = that match {
-    case m:Manifest[_] => this.erasure == m.erasure
-    case _ => false
-  }
-    
-}
-
-/** <p>
-  *   This object is used by the compiler and <b>should not be used in client
-  *   code</b>. The object <code>Manifest</code> defines factory methods for
-  *   manifests.
-  * </p>
-  * <p>
-  *   <b>BE AWARE</b>: The factory for refinement types is missing and
-  *   will be implemented in a later version of this class.
-  * </p>
-  */
-object Manifest {
-
-  /** Manifest for the singleton type `value.type'. */
-  def singleType[T](value: Any): Manifest[T] =
-    new Manifest[T] {
-      lazy val erasure =
-        value match {
-          case anyRefValue: AnyRef => anyRefValue.GetType
-          case anyValue => error("There is no singleton type for AnyVal values")
-        }
-      override lazy val toString = value.toString + ".type"
-    }
-
-  /** Manifest for the class type `clazz', where `clazz' is
-    * a top-level or static class. */
-  def classType[T](clazz: Predef.Class[T]): Manifest[T] =
-    new Manifest[T] {
-      val erasure = clazz
-      override lazy val toString = erasure.getName
-    }
-
-  /** Manifest for the class type `clazz[args]', where `clazz' is
-    * a top-level or static class. */
-  def classType[T](clazz: Predef.Class[_], args: Manifest[_]*): Manifest[T] =
-    new Manifest[T] {
-      val erasure = clazz
-      val typeArguments: Seq[Manifest[_]] = args
-      override lazy val toString = erasure.getName + typeArguments.mkString("[", ", ", "]")
-    }
-
-  /** Manifest for the class type `prefix # clazz'. */
-  def classType[T](prefix: Manifest[_], clazz: Predef.Class[_]): Manifest[T] =
-    new Manifest[T] {
-      val erasure = clazz
-      override lazy val toString = prefix.toString + "#" + clazz.getName
-    }
-
-  /** Manifest for the class type `prefix # clazz[args]'. */
-  def classType[T](prefix: Manifest[_], clazz: Predef.Class[_], args: Manifest[_]*): Manifest[T] =
-    new Manifest[T] {
-      val erasure = clazz
-      val typeArguments: Seq[Manifest[_]] = args
-      override lazy val toString = prefix.toString + "#" + clazz.getName + typeArguments.mkString("[", ", ", "]")
-    }
-
-  /** Manifest for the abstract type `prefix # name'. `upperBound' is not
-    * strictly necessary as it could be obtained by reflection. It was
-    * added so that erasure can be calculated without reflection. */
-  def abstractType[T](prefix: Manifest[_], name: String, upperBound: Manifest[_]): Manifest[T] =
-    new Manifest[T] {
-      lazy val erasure = upperBound.erasure
-      override lazy val toString = prefix.toString + "#" + name
-    }
-
-  /** Manifest for the abstract type `prefix # name[args]'. */
-  def abstractType[T](prefix: Manifest[_], name: String, upperBound: Manifest[_], args: Manifest[_]*): Manifest[T] =
-    new Manifest[T] {
-      lazy val erasure = upperBound.erasure
-      val typeArguments: Seq[Manifest[_]] = args
-      override lazy val toString = prefix.toString + "#" + name + typeArguments.mkString("[", ", ", "]")
-    }
-
-  /** Manifest for the intersection type `parents_0 with ... with parents_n'. */
-  def intersectionType[T](parents: Manifest[_]*): Manifest[T] =
-    new Manifest[T] {
-      lazy val erasure = parents.first.erasure
-      override lazy val toString = parents.mkString(" with ")
-    }
-  
-}
diff --git a/src/dotnet-library/scala/reflect/ScalaBeanInfo.scala b/src/dotnet-library/scala/reflect/ScalaBeanInfo.scala
deleted file mode 100644
index 5d4ffb4..0000000
--- a/src/dotnet-library/scala/reflect/ScalaBeanInfo.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* ScalaBeanInfo does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/runtime/BooleanRef.cs b/src/dotnet-library/scala/runtime/BooleanRef.cs
deleted file mode 100644
index da24329..0000000
--- a/src/dotnet-library/scala/runtime/BooleanRef.cs
+++ /dev/null
@@ -1,22 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: BooleanRef.cs 16894 2009-01-13 13:09:41Z cunei $
-
-namespace scala.runtime {
-
-  using System;
-
-  [Serializable]
-  public class BooleanRef {
-    public bool elem;
-    public BooleanRef(bool elem) { this.elem = elem; }
-    override public string ToString() { return elem.ToString(); }
-  }
-
-}
diff --git a/src/dotnet-library/scala/runtime/BoxedUnit.cs b/src/dotnet-library/scala/runtime/BoxedUnit.cs
deleted file mode 100644
index a06a5b8..0000000
--- a/src/dotnet-library/scala/runtime/BoxedUnit.cs
+++ /dev/null
@@ -1,36 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: BoxedUnit.cs 16894 2009-01-13 13:09:41Z cunei $
-
-
-namespace scala.runtime {
-
-  using System;
-
-  [Serializable]
-  public sealed class BoxedUnit {
-
-    public static readonly BoxedUnit UNIT = new BoxedUnit();
-
-    private BoxedUnit() { }
-
-    override public bool Equals(object other) {
-      return this == other;
-    }
-
-    override public int GetHashCode() {
-      return 0;
-    }
-
-    override public string ToString() {
-      return "()";
-    }
-  }
-
-}
diff --git a/src/dotnet-library/scala/runtime/ByteRef.cs b/src/dotnet-library/scala/runtime/ByteRef.cs
deleted file mode 100644
index e86ab2d..0000000
--- a/src/dotnet-library/scala/runtime/ByteRef.cs
+++ /dev/null
@@ -1,22 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: ByteRef.cs 16894 2009-01-13 13:09:41Z cunei $
-
-namespace scala.runtime {
-
-  using System;
-
-  [Serializable]
-  public class ByteRef {
-    public byte elem;
-    public ByteRef(byte elem) { this.elem = elem; }
-    override public string ToString() { return elem.ToString(); }
-  }
-
-}
diff --git a/src/dotnet-library/scala/runtime/CharRef.cs b/src/dotnet-library/scala/runtime/CharRef.cs
deleted file mode 100644
index 6c961c4..0000000
--- a/src/dotnet-library/scala/runtime/CharRef.cs
+++ /dev/null
@@ -1,22 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: CharRef.cs 16894 2009-01-13 13:09:41Z cunei $
-
-namespace scala.runtime {
-
-  using System;
-
-  [Serializable]
-  public class CharRef {
-    public char elem;
-    public CharRef(char elem) { this.elem = elem; }
-    override public string ToString() { return elem.ToString(); }
-  }
-
-}
diff --git a/src/dotnet-library/scala/runtime/Comparator.cs b/src/dotnet-library/scala/runtime/Comparator.cs
deleted file mode 100644
index 4b7f49b..0000000
--- a/src/dotnet-library/scala/runtime/Comparator.cs
+++ /dev/null
@@ -1,51 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: Comparator.cs 16894 2009-01-13 13:09:41Z cunei $
-
-namespace scala.runtime {
-
-  using System;
-
-  public class Comparator {
-    public static bool equals(object a, object b) {
-      if (a == null)
-        return b == null;
-      if (a.Equals(b))
-        return true;
-      if (a == b)
-        return true;
-      IConvertible aa = a as IConvertible;
-      IConvertible bb = b as IConvertible;
-      
-      // We must check if a and b are realy convertible to numbers, because 
-      // String is also an implementation of IConvertible...
-      // So we can avoid having "12" == 12 returning true !!
-      if((a is Decimal || a is Double || a is Single || a is Byte 
-          || a is SByte || a is Int16 || a is UInt16 || a is Int32 
-          || a is UInt32 || a is Int64 || a is UInt64) 
-          && (b is Decimal || b is Double || b is Single || b is Byte 
-          || b is SByte || b is Int16 || b is UInt16 || b is Int32 
-          || b is UInt32 || b is Int64 || b is UInt64)){
-        if (aa != null && bb != null) {
-         if (a is Decimal || b is Decimal)
-           return aa.ToDecimal(null) == bb.ToDecimal(null);
-         if (a is Double || b is Double)
-            return aa.ToDouble(null) == bb.ToDouble(null);
-          if (a is Single || b is Single)
-            return aa.ToSingle(null) == bb.ToSingle(null);
-          if (a is Int64 || b is Int64)
-            return aa.ToInt64(null) == bb.ToInt64(null);
-          return aa.ToInt32(null) == bb.ToInt32(null);
-        }
-      }
-      return false;
-    }
-  }
-
-}
diff --git a/src/dotnet-library/scala/runtime/DoubleRef.cs b/src/dotnet-library/scala/runtime/DoubleRef.cs
deleted file mode 100644
index 739d06c..0000000
--- a/src/dotnet-library/scala/runtime/DoubleRef.cs
+++ /dev/null
@@ -1,22 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: DoubleRef.cs 16894 2009-01-13 13:09:41Z cunei $
-
-namespace scala.runtime {
-
-  using System;
-
-  [Serializable]
-  public class DoubleRef {
-    public double elem;
-    public DoubleRef(double elem) { this.elem = elem; }
-    override public string ToString() { return elem.ToString(); }
-  }
-
-}
diff --git a/src/dotnet-library/scala/runtime/ExceptionHandling.cs b/src/dotnet-library/scala/runtime/ExceptionHandling.cs
deleted file mode 100644
index bdb7ba8..0000000
--- a/src/dotnet-library/scala/runtime/ExceptionHandling.cs
+++ /dev/null
@@ -1,27 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: ExceptionHandling.cs 16894 2009-01-13 13:09:41Z cunei $
-
-namespace scala.runtime {
-
-  using System;
-
-  public abstract class ExceptionHandling {
-
-    public static Exception tryCatch(Runnable runnable) {
-      try {
-        runnable.run();
-        return null;
-      } catch (Exception exception) {
-        return exception;
-      }
-    }
-  }
-
-}
diff --git a/src/dotnet-library/scala/runtime/FloatRef.cs b/src/dotnet-library/scala/runtime/FloatRef.cs
deleted file mode 100644
index 1e3da13..0000000
--- a/src/dotnet-library/scala/runtime/FloatRef.cs
+++ /dev/null
@@ -1,22 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: FloatRef.cs 16894 2009-01-13 13:09:41Z cunei $
-
-namespace scala.runtime {
-
-  using System;
-
-  [Serializable]
-  public class FloatRef {
-    public float elem;
-    public FloatRef(float elem) { this.elem = elem; }
-    override public string ToString() { return elem.ToString(); }
-  }
-
-}
diff --git a/src/dotnet-library/scala/runtime/IntRef.cs b/src/dotnet-library/scala/runtime/IntRef.cs
deleted file mode 100644
index e4a2d01..0000000
--- a/src/dotnet-library/scala/runtime/IntRef.cs
+++ /dev/null
@@ -1,22 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: IntRef.cs 16894 2009-01-13 13:09:41Z cunei $
-
-namespace scala.runtime {
-
-  using System;
-
-  [Serializable]
-  public class IntRef {
-    public int elem;
-    public IntRef(int elem) { this.elem = elem; }
-    override public string ToString() { return elem.ToString(); }
-  }
-
-}
diff --git a/src/dotnet-library/scala/runtime/LongRef.cs b/src/dotnet-library/scala/runtime/LongRef.cs
deleted file mode 100644
index 9b87b44..0000000
--- a/src/dotnet-library/scala/runtime/LongRef.cs
+++ /dev/null
@@ -1,22 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: LongRef.cs 16894 2009-01-13 13:09:41Z cunei $
-
-namespace scala.runtime {
-
-  using System;
-
-  [Serializable]
-  public class LongRef {
-    public long elem;
-    public LongRef(long elem) { this.elem = elem; }
-    override public string ToString() { return elem.ToString(); }
-  }
-
-}
diff --git a/src/dotnet-library/scala/runtime/NonLocalReturnException.scala b/src/dotnet-library/scala/runtime/NonLocalReturnException.scala
deleted file mode 100644
index 1ee4db6..0000000
--- a/src/dotnet-library/scala/runtime/NonLocalReturnException.scala
+++ /dev/null
@@ -1,17 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: NonLocalReturnException.scala 15604 2008-07-24 09:56:59Z phaller $
-
-
-package scala.runtime
-
-
-import Predef.RuntimeException
-
-class NonLocalReturnException[T](val key: AnyRef, val value: T) extends RuntimeException
diff --git a/src/dotnet-library/scala/runtime/ObjectRef.cs b/src/dotnet-library/scala/runtime/ObjectRef.cs
deleted file mode 100644
index f0569c5..0000000
--- a/src/dotnet-library/scala/runtime/ObjectRef.cs
+++ /dev/null
@@ -1,22 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: ObjectRef.cs 16894 2009-01-13 13:09:41Z cunei $
-
-namespace scala.runtime {
-
-  using System;
-
-  [Serializable]
-  public class ObjectRef {
-    public Object elem;
-    public ObjectRef(Object elem) { this.elem = elem; }
-    override public string ToString() { return "" + elem; }
-  }
-
-}
diff --git a/src/dotnet-library/scala/runtime/RichChar.scala b/src/dotnet-library/scala/runtime/RichChar.scala
deleted file mode 100644
index 574c774..0000000
--- a/src/dotnet-library/scala/runtime/RichChar.scala
+++ /dev/null
@@ -1,70 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: RichChar.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala.runtime
-
-
-import Predef.NoSuchElementException
-
-/** <p>
- *    For example, in the following code
- *  </p>
- *  <pre>
- *    <b>object</b> test <b>extends</b> Application {
- *      Console.println(<chr>'\40'</chr>.isWhitespace)
- *      Console.println('\011'.isWhitespace)
- *      Console.println('1'.asDigit == 1)
- *      Console.println('A'.asDigit == 10)
- *    }</pre>
- *  <p>
- *    the implicit conversions are performed using the predefined view
- *    <a href="../Predef$object.html#charWrapper(scala.Char)"
- *    target="contentFrame"><code>Predef.charWrapper</code></a>.
- *  </p>
- */
-final class RichChar(x: Char) extends Proxy with Ordered[Char] {
-
-  // Proxy.self
-  def self: Any = x
-
-  // Ordered[Char].compare
-  def compare (y: Char): Int = if (x < y) -1 else if (x > y) 1 else 0
-
-  def asDigit: Int = System.Char.GetNumericValue(x).toInt
-
-  def isControl: Boolean = System.Char.IsControl(x)
-  def isDigit: Boolean = System.Char.IsDigit(x)
-  def isLetter: Boolean = System.Char.IsLetter(x)
-  def isLetterOrDigit: Boolean = System.Char.IsLetterOrDigit(x)
-  def isLowerCase: Boolean = System.Char.IsLower(x)
-  def isUpperCase: Boolean = System.Char.IsUpper(x)
-  def isWhitespace: Boolean = System.Char.IsWhiteSpace(x)
-
-  def toLowerCase: Char = System.Char.ToLower(x)
-  def toUpperCase: Char = System.Char.ToUpper(x)
-
-  /** Create an Iterator[Char] over the characters from 'x' to 'y' - 1
-   */
-  def until(limit: Char): Iterator[Char] = new Iterator[Char] {
-    private var ch = x
-    def hasNext: Boolean = ch < limit
-    def next: Char =
-      if (hasNext) { val j = ch; ch = (ch + 1).toChar; j }
-      else throw new NoSuchElementException("next on empty iterator")
-  }
-
-  //def until(y: Char): Iterator[Char] = to(y)
-
-  /** Create an Iterator[Char] over the characters from 'x' to 'y'
-   */
-  def to(y: Char): Iterator[Char] = until((y + 1).toChar)
-
-}
diff --git a/src/dotnet-library/scala/runtime/RichClass.scala b/src/dotnet-library/scala/runtime/RichClass.scala
deleted file mode 100644
index d5cb210..0000000
--- a/src/dotnet-library/scala/runtime/RichClass.scala
+++ /dev/null
@@ -1,25 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: RichClass.scala 16881 2009-01-09 16:28:11Z cunei $
-
-
-package scala.runtime
-
-import Predef.Class
-
-final class RichClass(val self: Class[_]) extends Proxy {
-
-  def isPrimitive(): Boolean = self.IsPrimitive
-  def isArray(): Boolean = self.IsArray
-
-  def getClass(): RichClass = this
-  def getName(): String = self.Name
-  def getComponentType(): Class[_] = self.GetElementType
-
-}
diff --git a/src/dotnet-library/scala/runtime/RichDouble.scala b/src/dotnet-library/scala/runtime/RichDouble.scala
deleted file mode 100644
index d99f9c7..0000000
--- a/src/dotnet-library/scala/runtime/RichDouble.scala
+++ /dev/null
@@ -1,52 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: RichDouble.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala.runtime
-
-
-final class RichDouble(x: Double) extends Proxy with Ordered[Double] {
-
-  // Proxy.self
-  def self: Any = x
-
-  // Ordered[Double].compare
-  def compare(y: Double): Int = if (x < y) -1 else if (x > y) 1 else 0
-
-  def min(y: Double): Double = Math.min(x, y)
-  def max(y: Double): Double = Math.max(x, y)
-  def abs: Double = Math.abs(x)
-
-  def round: Long = Math.round(x)
-  def ceil: Double = Math.ceil(x)
-  def floor: Double = Math.floor(x)
-
-  /** Converts an angle measured in degrees to an approximately equivalent
-   *  angle measured in radians.
-   *
-   *  @param  x an angle, in degrees
-   *  @return the measurement of the angle <code>x</code> in radians.
-   */
-  def toRadians: Double = Math.toRadians(x)
-
-  /** Converts an angle measured in radians to an approximately equivalent
-   *  angle measured in degrees.
-   *
-   *  @param  x angle, in radians
-   *  @return the measurement of the angle <code>x</code> in degrees.
-   */
-  def toDegrees: Double = Math.toDegrees(x)
-
-  def isNaN: Boolean = System.Double.IsNaN(x)
-  def isInfinity: Boolean = System.Double.IsInfinity(x)
-  def isPosInfinity: Boolean = System.Double.IsPositiveInfinity(x)
-  def isNegInfinity: Boolean = System.Double.IsNegativeInfinity(x)
-
-}
diff --git a/src/dotnet-library/scala/runtime/RichException.scala b/src/dotnet-library/scala/runtime/RichException.scala
deleted file mode 100644
index 4394e4d..0000000
--- a/src/dotnet-library/scala/runtime/RichException.scala
+++ /dev/null
@@ -1,21 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: RichException.scala 16881 2009-01-09 16:28:11Z cunei $
-
-
-package scala.runtime
-
-
-final class RichException(exc: System.Exception) {
-
-  def printStackTrace() = System.Console.WriteLine(exc.StackTrace)
-  def getMessage() = exc.Message
-  def getStackTraceString: String = exc.StackTrace
-
-}
diff --git a/src/dotnet-library/scala/runtime/RichFloat.scala b/src/dotnet-library/scala/runtime/RichFloat.scala
deleted file mode 100644
index 6058fd5..0000000
--- a/src/dotnet-library/scala/runtime/RichFloat.scala
+++ /dev/null
@@ -1,54 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: RichFloat.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala.runtime
-
-
-import Predef._
-
-final class RichFloat(x: Float) extends Proxy with Ordered[Float] {
-
-  // Proxy.self
-  def self: Any = x
-
-  // Ordered[Float].compare
-  def compare (y: Float): Int = if (x < y) -1 else if (x > y) 1 else 0
-
-  def min(y: Float) = Math.min(x, y)
-  def max(y: Float) = Math.max(x, y)
-  def abs: Float = Math.abs(x)
-
-  def round: Int = Math.round(x)
-  def ceil: Float = Math.ceil(x).toFloat
-  def floor: Float = Math.floor(x).toFloat
-
-  /** Converts an angle measured in degrees to an approximately equivalent
-   *  angle measured in radians.
-   *
-   *  @param  x an angle, in degrees
-   *  @return the measurement of the angle <code>x</code> in radians.
-   */
-  def toRadians: Float = Math.toRadians(x).toFloat
-
-  /** Converts an angle measured in radians to an approximately equivalent
-   *  angle measured in degrees.
-   *
-   *  @param  x angle, in radians
-   *  @return the measurement of the angle <code>x</code> in degrees.
-   */
-  def toDegrees: Float = Math.toDegrees(x).toFloat
-
-  def isNaN: Boolean = System.Single.IsNaN(x)
-  def isInfinity: Boolean = System.Single.IsInfinity(x)
-  def isPosInfinity: Boolean = System.Single.IsPositiveInfinity(x)
-  def isNegInfinity: Boolean = System.Single.IsNegativeInfinity(x)
-
-}
diff --git a/src/dotnet-library/scala/runtime/RichInt.scala b/src/dotnet-library/scala/runtime/RichInt.scala
deleted file mode 100644
index a517e5a..0000000
--- a/src/dotnet-library/scala/runtime/RichInt.scala
+++ /dev/null
@@ -1,39 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: RichInt.scala 16881 2009-01-09 16:28:11Z cunei $
-
-
-package scala.runtime
-
-
-final class RichInt(start: Int) extends Proxy with Ordered[Int] {
-
-  // Proxy
-  def self: Any = start
-
-  // Ordered[Int]
-  def compare(that: Int): Int = if (start < that) -1 else if (start > that) 1 else 0
-
-  /** See <code>Iterator.range</code>. */
-  def until(end: Int): Range = new Range(start, end, 1)
-
-  /** See <code>Iterator.range</code>. */
-  def until(end: Int, step: Int): Range = new Range(start, end, step)
-
-  /** like <code>until</code>, but includes the last index */
-  def to(end: Int) = new Range.Inclusive(start, end, 1)
-
-  def min(that: Int): Int = if (start < that) start else that
-  def max(that: Int): Int = if (start > that) start else that
-  def abs: Int = if (start < 0) -start else start
-
-  def toBinaryString: String = System.Convert.ToString(start, 2)
-  def toHexString: String = System.Convert.ToString(start, 16)
-  def toOctalString: String = System.Convert.ToString(start, 8)
-}
diff --git a/src/dotnet-library/scala/runtime/RichLong.scala b/src/dotnet-library/scala/runtime/RichLong.scala
deleted file mode 100644
index 8b9f7df..0000000
--- a/src/dotnet-library/scala/runtime/RichLong.scala
+++ /dev/null
@@ -1,30 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: RichLong.scala 16881 2009-01-09 16:28:11Z cunei $
-
-
-package scala.runtime
-
-
-final class RichLong(x: Long) extends Proxy with Ordered[Long] {
-
-  // Proxy.self
-  def self: Any = x
-
-  // Ordered[Long].compare
-  def compare(y: Long): Int = if (x < y) -1 else if (x > y) 1 else 0
-
-  def min(y: Long): Long = if (x < y) x else y
-  def max(y: Long): Long = if (x > y) x else y
-  def abs: Long = if (x < 0) -x else x
-
-  def toBinaryString: String = System.Convert.ToString(x, 2)
-  def toHexString: String = System.Convert.ToString(x, 16)
-  def toOctalString: String = System.Convert.ToString(x, 8)
-}
diff --git a/src/dotnet-library/scala/runtime/RichString.scala b/src/dotnet-library/scala/runtime/RichString.scala
deleted file mode 100644
index 17c0d8a..0000000
--- a/src/dotnet-library/scala/runtime/RichString.scala
+++ /dev/null
@@ -1,219 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: RichString.scala 16881 2009-01-09 16:28:11Z cunei $
-
-
-package scala.runtime
-
-import Predef._
-
-final class RichString(val self: String) extends Proxy with RandomAccessSeq[Char] with Ordered[String] {
-  import RichString._  
-  override def apply(n: Int) = self charAt n
-  override def length = self.length
-  override def toString = self
-  override def mkString = self
-
-  override def slice(from: Int, until: Int): RichString = {
-    val len = self.length
-    new RichString(
-      if (from >= until || from >= len)
-        ""
-      else {
-        val from0 = if (from < 0) 0 else from
-        val until0 = if (until > len) len else until
-        self.substring(from0, until0)
-      }
-    )
-  }
-
-  //override def ++ [B >: A](that: Iterable[B]): Seq[B] = {
-  override def ++[B >: Char](that: Iterable[B]): RandomAccessSeq[B] = that match {
-    case that: RichString => new RichString(self + that.self) 
-    case that => super.++(that)
-  }
-  
-  override def take(until: Int): RichString = slice(0, until)
-
-  override def drop(from: Int): RichString = slice(from, self.length)
-
-  override def startsWith[B](that: Seq[B]) = that match {
-    case that: RichString => self startsWith that.self
-    case that => super.startsWith(that)
-  }
-
-  override def endsWith[B](that: Seq[B]) = that match {
-    case that: RichString => self endsWith that.self
-    case that => super.endsWith(that)
-  }
-
-  override def indexOf[B](that: Seq[B]) = that match {
-    case that: RichString => self indexOf that.self
-    case that => super.indexOf(that)
-  }
-
-  override def containsSlice[B](that: Seq[B]) = that match {
-    case that: RichString => self contains that.self
-    case that => super.containsSlice(that)
-  }
-
-  override def reverse: RichString = {
-    val buf = new StringBuilder
-    var i = self.length - 1
-    while (i >= 0) {
-      buf append (self charAt i)
-      i -= 1
-    }
-    new RichString(buf.toString)
-  }
-  
-  /** return n times the current string 
-   */
-  def * (n: Int): String = {
-    val buf = new StringBuilder
-    for (i <- 0 until n) buf append self
-    buf.toString
-  }
-
-  override def compare(other: String) = self compareTo other
-
-  private def isLineBreak(c: Char) = c == LF || c == FF
-
-  /** <p>
-   *    Strip trailing line end character from this string if it has one.
-   *    A line end character is one of
-   *  </p>
-   *  <ul style="list-style-type: none;">
-   *    <li>LF - line feed   (0x0A hex)</li>
-   *    <li>FF - form feed   (0x0C hex)</li>
-   *  </ul>
-   *  <p>
-   *    If a line feed character LF is preceded by a carriage return CR
-   *    (0x0D hex), the CR character is also stripped (Windows convention).
-   *  </p>
-   */
-  def stripLineEnd: String = {
-    val len = self.length
-    if (len == 0) self
-    else {
-      val last = apply(len - 1)
-      if (isLineBreak(last))
-        self.substring(0, if (last == LF && len >= 2 && apply(len - 2) == CR) len - 2 else len - 1)
-      else 
-        self
-    }
-  }
-
-  /** <p>
-   *    Return all lines in this string in an iterator, including trailing
-   *    line end characters.
-   *  </p>
-   *  <p>
-   *    The number of strings returned is one greater than the number of line
-   *    end characters in this string. For an empty string, a single empty
-   *    line is returned. A line end character is one of
-   *  </p>
-   *  <ul style="list-style-type: none;">
-   *    <li>LF - line feed   (0x0A hex)</li>
-   *    <li>FF - form feed   (0x0C hex)</li>
-   *  </ul>
-   */
-  def linesWithSeparators = new Iterator[String] {
-    val len = self.length
-    var index = 0
-    def hasNext: Boolean = index < len
-    def next(): String = {
-      if (index >= len) throw new NoSuchElementException("next on empty iterator")
-      val start = index
-      while (index < len && !isLineBreak(apply(index))) index += 1
-      index += 1
-      self.substring(start, index min len)
-    }
-  }
-
-  /** Return all lines in this string in an iterator, excluding trailing line
-   *  end characters, i.e. apply <code>.stripLineEnd</code> to all lines
-   *  returned by <code>linesWithSeparators</code>.
-   */
-  def lines: Iterator[String] = 
-    linesWithSeparators map (line => new RichString(line).stripLineEnd)
-
-  /** Returns this string with first character converted to upper case */
-  def capitalize: String =
-    if (self == null) null
-    else if (self.length == 0) ""
-    else {
-      val chars = self.toCharArray
-      chars(0) = chars(0).toUpperCase
-      new String(chars)
-    }
-
-  /** <p>
-   *    For every line in this string:
-   *  </p>
-   *  <blockquote>
-   *     Strip a leading prefix consisting of blanks or control characters
-   *     followed by <code>marginChar</code> from the line.
-   *  </blockquote>
-   */
-  def stripMargin(marginChar: Char): String = {
-    val buf = new StringBuilder
-    for (line <- linesWithSeparators) {
-      val len = line.length
-      var index = 0
-      while (index < len && line.charAt(index) <= ' ') index += 1
-      buf append
-        (if (index < len && line.charAt(index) == marginChar) line.substring(index + 1) else line)
-    }
-    buf.toString
-  }
-
-  /** <p>
-   *    For every line in this string:
-   *  </p>
-   *  <blockquote>
-   *     Strip a leading prefix consisting of blanks or control characters
-   *     followed by <code>|</code> from the line.
-   *  </blockquote>
-   */
-  def stripMargin: String = stripMargin('|')
-
-  def split(separator: Char): Array[String] = self.Split(Array(separator))
-
-  def split(separators: Array[Char]): Array[String] = self.Split(separators)
-
-  def toBoolean: Boolean = System.Boolean.Parse(self)
-  def toByte: Byte       = System.Byte.Parse(self)
-  def toShort: Short     = System.Int16.Parse(self)
-  def toInt: Int         = System.Int32.Parse(self)
-  def toLong: Long       = System.Int64.Parse(self)
-  def toFloat: Float     = System.Single.Parse(self)
-  def toDouble: Double   = System.Double.Parse(self)
-
-  def toArray: Array[Char] = {
-	self.ToCharArray()
-  }
-}
-
-object RichString {
-  // just statics for rich string.
-  private final val LF: Char = 0x0A
-  private final val FF: Char = 0x0C
-  private final val CR: Char = 0x0D
-  private final val SU: Char = 0x1A
-
-  private def parseBoolean(s: String): Boolean =
-    if (s != null) s.toLowerCase match {
-      case "true" => true
-      case "false" => false
-      case _ => throw new System.FormatException("For input string: \""+s+"\"")
-    }
-    else
-      throw new System.FormatException("For input string: \"null\"")
-}
diff --git a/src/dotnet-library/scala/runtime/RichStringBuilder.scala b/src/dotnet-library/scala/runtime/RichStringBuilder.scala
deleted file mode 100644
index 67c1c79..0000000
--- a/src/dotnet-library/scala/runtime/RichStringBuilder.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* RichStringBuilder does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/runtime/Runnable.cs b/src/dotnet-library/scala/runtime/Runnable.cs
deleted file mode 100644
index a32134f..0000000
--- a/src/dotnet-library/scala/runtime/Runnable.cs
+++ /dev/null
@@ -1,17 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: Runnable.cs 16894 2009-01-13 13:09:41Z cunei $
-
-namespace scala.runtime {
-
-  public interface Runnable {
-    void run();
-  }
-
-}
diff --git a/src/dotnet-library/scala/runtime/ShortRef.cs b/src/dotnet-library/scala/runtime/ShortRef.cs
deleted file mode 100644
index 525953f..0000000
--- a/src/dotnet-library/scala/runtime/ShortRef.cs
+++ /dev/null
@@ -1,22 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: ShortRef.cs 16894 2009-01-13 13:09:41Z cunei $
-
-namespace scala.runtime {
-
-  using System;
-
-  [Serializable]
-  public class ShortRef {
-    public short elem;
-    public ShortRef(short elem) { this.elem = elem; }
-    override public string ToString() { return elem.ToString(); }
-  }
-
-}
diff --git a/src/dotnet-library/scala/runtime/StringAdd.scala b/src/dotnet-library/scala/runtime/StringAdd.scala
deleted file mode 100644
index 40a8db2..0000000
--- a/src/dotnet-library/scala/runtime/StringAdd.scala
+++ /dev/null
@@ -1,28 +0,0 @@
-/*                                                                      *\
-**     ________ ___   __   ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ |_|                                         **
-**                                                                      **
-\*                                                                      */
-
-// $Id: StringAdd.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala.runtime
-
-
-import Predef._
-
-final class StringAdd(self: Any) {
-
-  def +(other: String) = self.toString + other
-
-  /** Formats string according to given <code>format</code> string.
-   *  Format strings are as for <code>String.format</code> (@see
-   *  http://msdn2.microsoft.com/en-us/library/system.string.format(VS.71).aspx
-   *  and http://www.codeproject.com/books/0735616485.asp).
-   */
-  def formatted(format: String): String = 
-    String.Format(format, Array(self.asInstanceOf[Object]))
-}
diff --git a/src/dotnet-library/scala/runtime/SymtabAttribute.cs b/src/dotnet-library/scala/runtime/SymtabAttribute.cs
deleted file mode 100644
index 388c74d..0000000
--- a/src/dotnet-library/scala/runtime/SymtabAttribute.cs
+++ /dev/null
@@ -1,22 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: SymtabAttribute.cs 16894 2009-01-13 13:09:41Z cunei $
-
-namespace scala.runtime {
-
-  using System;
-
-  public class SymtabAttribute : Attribute {
-    public byte[] symtab;
-
-    public SymtabAttribute(byte[] symtab) { this.symtab = symtab; }
-    public SymtabAttribute() {}
-  }
-
-}
diff --git a/src/dotnet-library/scala/testing/Benchmark.scala b/src/dotnet-library/scala/testing/Benchmark.scala
deleted file mode 100644
index 1e5cd8c..0000000
--- a/src/dotnet-library/scala/testing/Benchmark.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* Benchmark does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/testing/SUnit.scala b/src/dotnet-library/scala/testing/SUnit.scala
deleted file mode 100644
index 0c657b9..0000000
--- a/src/dotnet-library/scala/testing/SUnit.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* SUnit does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/testing/Show.scala b/src/dotnet-library/scala/testing/Show.scala
deleted file mode 100644
index 06adc0b..0000000
--- a/src/dotnet-library/scala/testing/Show.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* scala.testing.Show does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/text/Document.scala b/src/dotnet-library/scala/text/Document.scala
deleted file mode 100644
index e7b3049..0000000
--- a/src/dotnet-library/scala/text/Document.scala
+++ /dev/null
@@ -1,122 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: Document.scala 11950 2007-06-08 12:08:26Z michelou $
-
-
-package scala.text
-
-
-import System.IO.TextWriter
-
-case object DocNil extends Document
-case object DocBreak extends Document
-case class DocText(txt: String) extends Document
-case class DocGroup(doc: Document) extends Document
-case class DocNest(indent: Int, doc: Document) extends Document
-case class DocCons(hd: Document, tl: Document) extends Document
-
-/**
- * A basic pretty-printing library, based on Lindig's strict version
- * of Wadler's adaptation of Hughes' pretty-printer.
- *
- * @author Michel Schinz
- * @version 1.0
- */
-abstract class Document {
-  def ::(hd: Document): Document = DocCons(hd, this)
-  def ::(hd: String): Document = DocCons(DocText(hd), this)
-  def :/:(hd: Document): Document = hd :: DocBreak :: this
-  def :/:(hd: String): Document = hd :: DocBreak :: this
-
-  /**
-   * Format this document on <code>writer</code> and try to set line
-   * breaks so that the result fits in <code>width</code> columns.
-   *
-   * @param width  ...
-   * @param writer ...
-   */
-  def format(width: Int, writer: TextWriter) {
-    type FmtState = (Int, Boolean, Document)
-
-    def fits(w: Int, state: List[FmtState]): Boolean = state match {
-      case _ if w < 0 =>
-        false
-      case List() =>
-        true
-      case (_, _, DocNil) :: z =>
-        fits(w, z)
-      case (i, b, DocCons(h, t)) :: z =>
-        fits(w, (i,b,h) :: (i,b,t) :: z)
-      case (_, _, DocText(t)) :: z =>
-        fits(w - t.length(), z)
-      case (i, b, DocNest(ii, d)) :: z =>
-        fits(w, (i + ii, b, d) :: z)
-      case (_, false, DocBreak) :: z =>
-        fits(w - 1, z)
-      case (_, true, DocBreak) :: z =>
-        true
-      case (i, _, DocGroup(d)) :: z =>
-        fits(w, (i, false, d) :: z)
-    }
-
-    def spaces(n: Int) {
-      var rem = n
-      while (rem >= 16) { writer Write "                "; rem -= 16 }
-      if (rem >= 8)     { writer Write "        "; rem -= 8 }
-      if (rem >= 4)     { writer Write "    "; rem -= 4 }
-      if (rem >= 2)     { writer Write "  "; rem -= 2}
-      if (rem == 1)     { writer Write " " }
-    }
-
-    def fmt(k: Int, state: List[FmtState]): Unit = state match {
-      case List() => ()
-      case (_, _, DocNil) :: z =>
-        fmt(k, z)
-      case (i, b, DocCons(h, t)) :: z =>
-        fmt(k, (i, b, h) :: (i, b, t) :: z)
-      case (i, _, DocText(t)) :: z =>
-        writer Write t
-        fmt(k + t.length(), z)
-      case (i, b, DocNest(ii, d)) :: z =>
-        fmt(k, (i + ii, b, d) :: z)
-      case (i, true, DocBreak) :: z =>
-        writer Write "\n"
-        spaces(i);
-        fmt(i, z)
-      case (i, false, DocBreak) :: z =>
-        writer Write " "
-        fmt(k + 1, z)
-      case (i, b, DocGroup(d)) :: z =>
-        val fitsFlat = fits(width - k, (i, false, d) :: z)
-        fmt(k, (i, !fitsFlat, d) :: z)
-    }
-
-    fmt(0, (0, false, DocGroup(this)) :: Nil)
-  }
-}
-
-object Document {
-  /** The empty document */
-  def empty = DocNil
-
-  /** A break, which will either be turned into a space or a line break */
-  def break = DocBreak
-
-  /** A document consisting of some text literal */
-  def text(s: String): Document = DocText(s)
-
-  /**
-   * A group, whose components will either be printed with all breaks
-   * rendered as spaces, or with all breaks rendered as line breaks.
-   */
-  def group(d: Document): Document = DocGroup(d)
-
-  /** A nested document, which will be indented as specified. */
-  def nest(i: Int, d: Document): Document = DocNest(i, d)
-}
diff --git a/src/dotnet-library/scala/util/DynamicVariable.scala b/src/dotnet-library/scala/util/DynamicVariable.scala
deleted file mode 100644
index bf80e8d..0000000
--- a/src/dotnet-library/scala/util/DynamicVariable.scala
+++ /dev/null
@@ -1,83 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: DynamicVariable.scala 16881 2009-01-09 16:28:11Z cunei $
-
-
-package scala.util
-
-
-import Predef._
-import System.Threading.Thread
-import System.LocalDataStoreSlot
-
-/** <p>
- *    DynamicVariables provide a binding mechanism where the current
- *    value is found through <em>dynamic scope</em>, but where
- *    access to the variable itself is resolved through <em>static
- *    scope</em>.
- *  </p>
- *  <p>
- *    The current value can be retrieved with the
- *    <code>value</code> method.  New values should be
- *    pushed using the <code>withValue</code> method.
- *    Values pushed via <code>withValue</code> only
- *    stay valid while the <code>withValue</code>'s
- *    <em>second</em> argument, a parameterless closure,
- *    executes.  When the second argument finishes,
- *    the variable reverts to the previous value.
- *  </p>
- *  <p>
- *    Usage of <code>withValue</code> looks like this:
- *  </p>
- *  <blockquote><pre>
- *  someDynamicVariable.withValue(newValue) {
- *    // ... code called in here that calls value ...
- *    // ... will be given back the newValue ...
- *  }
- *  </pre></blockquote>
- *  <p>
- *    Each thread gets its own stack of bindings.  When a 
- *    new thread is created, the fluid gets a copy of
- *    the stack of bindings from the parent thread, and 
- *    from then on the bindings for the new thread
- *    are independent of those for the original thread.
- *  </p>
- *
- *  @author  Lex Spoon
- *  @version 1.1, 2007-5-21
- */
-class DynamicVariable[T](init: T) {
-  private val slot: LocalDataStoreSlot = Thread.AllocateDataSlot()
-  value = init
-
-  /** Retrieve the current value */
-  def value: T = Thread.GetData(slot).asInstanceOf[T]
-
-  /** Set the value of the fluid while executing the specified
-    * thunk.
-    *
-    * @param newval The value to which to set the fluid
-    * @param thunk The code to evaluate under the new setting
-    */
-  def withValue[S](newval: T)(thunk: =>S): S = {
-    val oldval = value
-    value = newval
-
-    try { thunk } finally {
-      value = oldval
-    }
-  }
-
-  /** Change the currently bound value, discarding the old value.
-    * Usually withValue() gives better semantics.
-    */
-  def value_=(newval: T) = { Thread.SetData(slot, newval.asInstanceOf[AnyRef]) }
-
-  override def toString: String = "DynamicVariable(" + value  +")"
-}
diff --git a/src/dotnet-library/scala/util/Marshal.scala b/src/dotnet-library/scala/util/Marshal.scala
deleted file mode 100644
index 4817f34..0000000
--- a/src/dotnet-library/scala/util/Marshal.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* Marshal does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/util/Properties.scala b/src/dotnet-library/scala/util/Properties.scala
deleted file mode 100644
index efa7824..0000000
--- a/src/dotnet-library/scala/util/Properties.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* Properties does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/util/Random.scala b/src/dotnet-library/scala/util/Random.scala
deleted file mode 100644
index 3235464..0000000
--- a/src/dotnet-library/scala/util/Random.scala
+++ /dev/null
@@ -1,74 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: Random.scala 14498 2008-04-04 12:12:27Z washburn $
-
-
-package scala.util
-
-/**
- *  @author Stephane Micheloud
- */
-class Random(self0: System.Random) {
-  private var rnd = self0 // see setSeed(seed)
-  def self = rnd
-
-  /** Creates a new random number generator using a single long seed. */
-  def this(seed: Long) = this(new System.Random(seed.toInt))
-
-  /** Creates a new random number generator using a single integer seed. */
-  def this(seed: Int) = this(new System.Random(seed))
-
-  /** Creates a new random number generator. */
-  def this() = this(new System.Random(System.Environment.TickCount))
-
-  /** Returns the next pseudorandom, uniformly distributed boolean value
-   *  from this random number generator's sequence.
-   */
-  def nextBoolean(): Boolean = (nextInt() & 0x1) == 1
-
-  /** Generates random bytes and places them into a user-supplied byte
-   *  array.
-   */
-  def nextBytes(bytes: Array[Byte]) { rnd.NextBytes(bytes) }
-
-  /** Returns the next pseudorandom, uniformly distributed double value
-   *  between 0.0 and 1.0 from this random number generator's sequence.
-   */
-  def nextDouble(): Double = rnd.NextDouble()
-
-  /** Returns the next pseudorandom, uniformly distributed float value
-   *  between 0.0 and 1.0 from this random number generator's sequence.
-   */
-  def nextFloat(): Float = nextDouble().toFloat
-
-  /** Returns the next pseudorandom, Gaussian ("normally") distributed
-   *  double value with mean 0.0 and standard deviation 1.0 from this
-   *  random number generator's sequence.
-   */
-  //def nextGaussian(): Double
-
-  /** Returns the next pseudorandom, uniformly distributed int value
-   *  from this random number generator's sequence.
-   */
-  def nextInt(): Int = rnd.Next()
-
-  /** Returns a pseudorandom, uniformly distributed int value between 0
-   *  (inclusive) and the specified value (exclusive), drawn from this
-   *  random number generator's sequence.
-   */
-  def nextInt(n: Int): Int = rnd.Next(0, n)
-
-  /** Returns the next pseudorandom, uniformly distributed long value
-   *  from this random number generator's sequence.
-   */
-  def nextLong(): Long = nextInt().toLong // 2x nextInt() ?!
-
-  def setSeed(seed: Long) { rnd = new System.Random(seed.toInt) }
-
-}
diff --git a/src/dotnet-library/scala/util/automata/BaseBerrySethi.scala b/src/dotnet-library/scala/util/automata/BaseBerrySethi.scala
deleted file mode 100644
index 092475a..0000000
--- a/src/dotnet-library/scala/util/automata/BaseBerrySethi.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* BaseBerrySethi.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/util/automata/DetWordAutom.scala b/src/dotnet-library/scala/util/automata/DetWordAutom.scala
deleted file mode 100644
index 7ce9f50..0000000
--- a/src/dotnet-library/scala/util/automata/DetWordAutom.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* DetWordAutom.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/util/automata/Inclusion.scala b/src/dotnet-library/scala/util/automata/Inclusion.scala
deleted file mode 100644
index da47d6d..0000000
--- a/src/dotnet-library/scala/util/automata/Inclusion.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* Inclusion.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/util/automata/NondetWordAutom.scala b/src/dotnet-library/scala/util/automata/NondetWordAutom.scala
deleted file mode 100644
index 65235bd..0000000
--- a/src/dotnet-library/scala/util/automata/NondetWordAutom.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* NondetWordAutom.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/util/automata/SubsetConstruction.scala b/src/dotnet-library/scala/util/automata/SubsetConstruction.scala
deleted file mode 100644
index 1f3124e..0000000
--- a/src/dotnet-library/scala/util/automata/SubsetConstruction.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* SubsetConstruction.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/util/automata/WordBerrySethi.scala b/src/dotnet-library/scala/util/automata/WordBerrySethi.scala
deleted file mode 100644
index fe13e35..0000000
--- a/src/dotnet-library/scala/util/automata/WordBerrySethi.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* WordBerrySethi.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/util/grammar/HedgeRHS.scala b/src/dotnet-library/scala/util/grammar/HedgeRHS.scala
deleted file mode 100644
index df362c4..0000000
--- a/src/dotnet-library/scala/util/grammar/HedgeRHS.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* HedgeRHS.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/util/grammar/TreeRHS.scala b/src/dotnet-library/scala/util/grammar/TreeRHS.scala
deleted file mode 100644
index e26c41a..0000000
--- a/src/dotnet-library/scala/util/grammar/TreeRHS.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* TreeRHS.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/util/logging/ConsoleLogger.scala b/src/dotnet-library/scala/util/logging/ConsoleLogger.scala
deleted file mode 100644
index d746e41..0000000
--- a/src/dotnet-library/scala/util/logging/ConsoleLogger.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* ConsoleLogger.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/util/logging/Logged.scala b/src/dotnet-library/scala/util/logging/Logged.scala
deleted file mode 100644
index 2b27dfc..0000000
--- a/src/dotnet-library/scala/util/logging/Logged.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* Logged.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/util/matching/BitField.scala b/src/dotnet-library/scala/util/matching/BitField.scala
deleted file mode 100644
index c7dc224..0000000
--- a/src/dotnet-library/scala/util/matching/BitField.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* BitField does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/util/matching/FixedBitField.scala b/src/dotnet-library/scala/util/matching/FixedBitField.scala
deleted file mode 100644
index 2968768..0000000
--- a/src/dotnet-library/scala/util/matching/FixedBitField.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* FixedBitField does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/util/matching/MatchableBigInt.scala b/src/dotnet-library/scala/util/matching/MatchableBigInt.scala
deleted file mode 100644
index d862c47..0000000
--- a/src/dotnet-library/scala/util/matching/MatchableBigInt.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* MatchableBigInt does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/util/matching/Regex.scala b/src/dotnet-library/scala/util/matching/Regex.scala
deleted file mode 100644
index f7932da..0000000
--- a/src/dotnet-library/scala/util/matching/Regex.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* Regex does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/util/parsing/CharInputStreamIterator.scala b/src/dotnet-library/scala/util/parsing/CharInputStreamIterator.scala
deleted file mode 100644
index 5d22aa4..0000000
--- a/src/dotnet-library/scala/util/parsing/CharInputStreamIterator.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* CharInputStreamIterator does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/util/parsing/Parsers.scala b/src/dotnet-library/scala/util/parsing/Parsers.scala
deleted file mode 100644
index e71232e..0000000
--- a/src/dotnet-library/scala/util/parsing/Parsers.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* Parsers.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/util/parsing/SimpleTokenizer.scala b/src/dotnet-library/scala/util/parsing/SimpleTokenizer.scala
deleted file mode 100644
index c26c826..0000000
--- a/src/dotnet-library/scala/util/parsing/SimpleTokenizer.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* SimpleTokenizer.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/util/parsing/ast/AbstractSyntax.scala b/src/dotnet-library/scala/util/parsing/ast/AbstractSyntax.scala
deleted file mode 100644
index f0f5d9a..0000000
--- a/src/dotnet-library/scala/util/parsing/ast/AbstractSyntax.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* AbstractSyntax.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/util/parsing/ast/Binders.scala b/src/dotnet-library/scala/util/parsing/ast/Binders.scala
deleted file mode 100644
index a6abe60..0000000
--- a/src/dotnet-library/scala/util/parsing/ast/Binders.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* Binders does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/util/parsing/combinator/ImplicitConversions.scala b/src/dotnet-library/scala/util/parsing/combinator/ImplicitConversions.scala
deleted file mode 100644
index eaf080a..0000000
--- a/src/dotnet-library/scala/util/parsing/combinator/ImplicitConversions.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* ImplicitConversions.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/util/parsing/combinator/JavaTokenParsers.scala b/src/dotnet-library/scala/util/parsing/combinator/JavaTokenParsers.scala
deleted file mode 100644
index 9cee82a..0000000
--- a/src/dotnet-library/scala/util/parsing/combinator/JavaTokenParsers.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* JavaTokenParsers does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/util/parsing/combinator/Parsers.scala b/src/dotnet-library/scala/util/parsing/combinator/Parsers.scala
deleted file mode 100644
index 55bc2af..0000000
--- a/src/dotnet-library/scala/util/parsing/combinator/Parsers.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* Parsers does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/util/parsing/combinator/RegexParsers.scala b/src/dotnet-library/scala/util/parsing/combinator/RegexParsers.scala
deleted file mode 100644
index ffdd88f..0000000
--- a/src/dotnet-library/scala/util/parsing/combinator/RegexParsers.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* RegexParsers does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/util/parsing/combinator/lexical/Lexical.scala b/src/dotnet-library/scala/util/parsing/combinator/lexical/Lexical.scala
deleted file mode 100644
index 12a1b6d..0000000
--- a/src/dotnet-library/scala/util/parsing/combinator/lexical/Lexical.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* Lexical.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/util/parsing/combinator/lexical/Scanners.scala b/src/dotnet-library/scala/util/parsing/combinator/lexical/Scanners.scala
deleted file mode 100644
index e94f892..0000000
--- a/src/dotnet-library/scala/util/parsing/combinator/lexical/Scanners.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* Scanners does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/util/parsing/combinator/lexical/StdLexical.scala b/src/dotnet-library/scala/util/parsing/combinator/lexical/StdLexical.scala
deleted file mode 100644
index a1f7dfb..0000000
--- a/src/dotnet-library/scala/util/parsing/combinator/lexical/StdLexical.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* StdLexical does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/util/parsing/combinator/syntactical/StandardTokenParsers.scala b/src/dotnet-library/scala/util/parsing/combinator/syntactical/StandardTokenParsers.scala
deleted file mode 100644
index ee9ba79..0000000
--- a/src/dotnet-library/scala/util/parsing/combinator/syntactical/StandardTokenParsers.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* StandardTokenParsers.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/util/parsing/combinator/syntactical/StdTokenParsers.scala b/src/dotnet-library/scala/util/parsing/combinator/syntactical/StdTokenParsers.scala
deleted file mode 100644
index c56a747..0000000
--- a/src/dotnet-library/scala/util/parsing/combinator/syntactical/StdTokenParsers.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* StdTokenParsers.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/util/parsing/combinator/syntactical/TokenParsers.scala b/src/dotnet-library/scala/util/parsing/combinator/syntactical/TokenParsers.scala
deleted file mode 100644
index 1e58018..0000000
--- a/src/dotnet-library/scala/util/parsing/combinator/syntactical/TokenParsers.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* TokenParsers.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/util/parsing/combinator/testing/RegexTest.scala b/src/dotnet-library/scala/util/parsing/combinator/testing/RegexTest.scala
deleted file mode 100644
index bf6b23b..0000000
--- a/src/dotnet-library/scala/util/parsing/combinator/testing/RegexTest.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* RegexTest does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/util/parsing/combinator/testing/Tester.scala b/src/dotnet-library/scala/util/parsing/combinator/testing/Tester.scala
deleted file mode 100644
index e6b5eee..0000000
--- a/src/dotnet-library/scala/util/parsing/combinator/testing/Tester.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* Tester does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/util/parsing/combinatorold/$tilde.scala b/src/dotnet-library/scala/util/parsing/combinatorold/$tilde.scala
deleted file mode 100644
index f875fca..0000000
--- a/src/dotnet-library/scala/util/parsing/combinatorold/$tilde.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* $tilde.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/util/parsing/combinatorold/ImplicitConversions.scala b/src/dotnet-library/scala/util/parsing/combinatorold/ImplicitConversions.scala
deleted file mode 100644
index eaf080a..0000000
--- a/src/dotnet-library/scala/util/parsing/combinatorold/ImplicitConversions.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* ImplicitConversions.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/util/parsing/combinatorold/Parsers.scala b/src/dotnet-library/scala/util/parsing/combinatorold/Parsers.scala
deleted file mode 100644
index e71232e..0000000
--- a/src/dotnet-library/scala/util/parsing/combinatorold/Parsers.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* Parsers.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/util/parsing/combinatorold/lexical/Lexical.scala b/src/dotnet-library/scala/util/parsing/combinatorold/lexical/Lexical.scala
deleted file mode 100644
index 12a1b6d..0000000
--- a/src/dotnet-library/scala/util/parsing/combinatorold/lexical/Lexical.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* Lexical.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/util/parsing/combinatorold/lexical/Scanners.scala b/src/dotnet-library/scala/util/parsing/combinatorold/lexical/Scanners.scala
deleted file mode 100644
index 793b829..0000000
--- a/src/dotnet-library/scala/util/parsing/combinatorold/lexical/Scanners.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* Scanners.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/util/parsing/combinatorold/lexical/StdLexical.scala b/src/dotnet-library/scala/util/parsing/combinatorold/lexical/StdLexical.scala
deleted file mode 100644
index 52ad544..0000000
--- a/src/dotnet-library/scala/util/parsing/combinatorold/lexical/StdLexical.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* StdLexical.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/util/parsing/combinatorold/syntactical/BindingParsers.scala b/src/dotnet-library/scala/util/parsing/combinatorold/syntactical/BindingParsers.scala
deleted file mode 100644
index 880810e..0000000
--- a/src/dotnet-library/scala/util/parsing/combinatorold/syntactical/BindingParsers.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* BindingParsers.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/util/parsing/combinatorold/syntactical/StdTokenParsers.scala b/src/dotnet-library/scala/util/parsing/combinatorold/syntactical/StdTokenParsers.scala
deleted file mode 100644
index c56a747..0000000
--- a/src/dotnet-library/scala/util/parsing/combinatorold/syntactical/StdTokenParsers.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* StdTokenParsers.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/util/parsing/combinatorold/syntactical/TokenParsers.scala b/src/dotnet-library/scala/util/parsing/combinatorold/syntactical/TokenParsers.scala
deleted file mode 100644
index 1e58018..0000000
--- a/src/dotnet-library/scala/util/parsing/combinatorold/syntactical/TokenParsers.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* TokenParsers.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/util/parsing/combinatorold/testing/Tester.scala b/src/dotnet-library/scala/util/parsing/combinatorold/testing/Tester.scala
deleted file mode 100644
index fff3782..0000000
--- a/src/dotnet-library/scala/util/parsing/combinatorold/testing/Tester.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* Tester.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/util/parsing/input/CharArrayPosition.scala b/src/dotnet-library/scala/util/parsing/input/CharArrayPosition.scala
deleted file mode 100644
index 6668f89..0000000
--- a/src/dotnet-library/scala/util/parsing/input/CharArrayPosition.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* CharArrayPosition.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/util/parsing/input/CharArrayReader.scala b/src/dotnet-library/scala/util/parsing/input/CharArrayReader.scala
deleted file mode 100644
index b481a7d..0000000
--- a/src/dotnet-library/scala/util/parsing/input/CharArrayReader.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* CharArrayReader.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/util/parsing/input/CharSequenceReader.scala b/src/dotnet-library/scala/util/parsing/input/CharSequenceReader.scala
deleted file mode 100644
index 93d732a..0000000
--- a/src/dotnet-library/scala/util/parsing/input/CharSequenceReader.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* CharSequenceReader.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/util/parsing/input/NoPosition.scala b/src/dotnet-library/scala/util/parsing/input/NoPosition.scala
deleted file mode 100644
index a5d2bbe..0000000
--- a/src/dotnet-library/scala/util/parsing/input/NoPosition.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* NoPosition.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/util/parsing/input/OffsetPosition.scala b/src/dotnet-library/scala/util/parsing/input/OffsetPosition.scala
deleted file mode 100644
index 70705db..0000000
--- a/src/dotnet-library/scala/util/parsing/input/OffsetPosition.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* OffsetPosition.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/util/parsing/input/PagedSeqReader.scala b/src/dotnet-library/scala/util/parsing/input/PagedSeqReader.scala
deleted file mode 100644
index d45f112..0000000
--- a/src/dotnet-library/scala/util/parsing/input/PagedSeqReader.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* PagedSeqReader.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/util/parsing/input/Position.scala b/src/dotnet-library/scala/util/parsing/input/Position.scala
deleted file mode 100644
index 6fd5272..0000000
--- a/src/dotnet-library/scala/util/parsing/input/Position.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* Position does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/util/parsing/input/Positional.scala b/src/dotnet-library/scala/util/parsing/input/Positional.scala
deleted file mode 100644
index bc9b502..0000000
--- a/src/dotnet-library/scala/util/parsing/input/Positional.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* Positional does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/util/parsing/input/Reader.scala b/src/dotnet-library/scala/util/parsing/input/Reader.scala
deleted file mode 100644
index d757031..0000000
--- a/src/dotnet-library/scala/util/parsing/input/Reader.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* Reader does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/util/parsing/input/StreamReader.scala b/src/dotnet-library/scala/util/parsing/input/StreamReader.scala
deleted file mode 100644
index 856b42e..0000000
--- a/src/dotnet-library/scala/util/parsing/input/StreamReader.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* StreamReader.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/util/parsing/json/JSON.scala b/src/dotnet-library/scala/util/parsing/json/JSON.scala
deleted file mode 100644
index 74c1685..0000000
--- a/src/dotnet-library/scala/util/parsing/json/JSON.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* JSON.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/util/parsing/json/Lexer.scala b/src/dotnet-library/scala/util/parsing/json/Lexer.scala
deleted file mode 100644
index 0e73053..0000000
--- a/src/dotnet-library/scala/util/parsing/json/Lexer.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* Lexer.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/util/parsing/json/Parser.scala b/src/dotnet-library/scala/util/parsing/json/Parser.scala
deleted file mode 100644
index 4d132ba..0000000
--- a/src/dotnet-library/scala/util/parsing/json/Parser.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* Parser.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/util/parsing/syntax/StdTokens.scala b/src/dotnet-library/scala/util/parsing/syntax/StdTokens.scala
deleted file mode 100644
index 52ce547..0000000
--- a/src/dotnet-library/scala/util/parsing/syntax/StdTokens.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* StdTokens.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/util/parsing/syntax/Tokens.scala b/src/dotnet-library/scala/util/parsing/syntax/Tokens.scala
deleted file mode 100644
index 8cc8924..0000000
--- a/src/dotnet-library/scala/util/parsing/syntax/Tokens.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* Tokens.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/util/regexp/Base.scala b/src/dotnet-library/scala/util/regexp/Base.scala
deleted file mode 100644
index 83ca478..0000000
--- a/src/dotnet-library/scala/util/regexp/Base.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* Base.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/util/regexp/PointedHedgeExp.scala b/src/dotnet-library/scala/util/regexp/PointedHedgeExp.scala
deleted file mode 100644
index bd514f5..0000000
--- a/src/dotnet-library/scala/util/regexp/PointedHedgeExp.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* PointedHedgeExp.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/util/regexp/SyntaxError.scala b/src/dotnet-library/scala/util/regexp/SyntaxError.scala
deleted file mode 100644
index ef09c8b..0000000
--- a/src/dotnet-library/scala/util/regexp/SyntaxError.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* SyntaxError.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/util/regexp/WordExp.scala b/src/dotnet-library/scala/util/regexp/WordExp.scala
deleted file mode 100644
index 91c2948..0000000
--- a/src/dotnet-library/scala/util/regexp/WordExp.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* WordExp.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/xml/Atom.scala b/src/dotnet-library/scala/xml/Atom.scala
deleted file mode 100644
index cb97d64..0000000
--- a/src/dotnet-library/scala/xml/Atom.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* Atom.scala does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/xml/Comment.scala b/src/dotnet-library/scala/xml/Comment.scala
deleted file mode 100644
index 3fe49c7..0000000
--- a/src/dotnet-library/scala/xml/Comment.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* Comment.scala does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/xml/Document.scala b/src/dotnet-library/scala/xml/Document.scala
deleted file mode 100644
index 9a3e441..0000000
--- a/src/dotnet-library/scala/xml/Document.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* Document.scala does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/xml/Elem.scala b/src/dotnet-library/scala/xml/Elem.scala
deleted file mode 100644
index 6f51090..0000000
--- a/src/dotnet-library/scala/xml/Elem.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* Elem.scala does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/xml/EntityRef.scala b/src/dotnet-library/scala/xml/EntityRef.scala
deleted file mode 100644
index e179fb9..0000000
--- a/src/dotnet-library/scala/xml/EntityRef.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* EntityRef.scala does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/xml/Group.scala b/src/dotnet-library/scala/xml/Group.scala
deleted file mode 100644
index 3a71374..0000000
--- a/src/dotnet-library/scala/xml/Group.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* Group.scala does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/xml/HasKeyValue.scala b/src/dotnet-library/scala/xml/HasKeyValue.scala
deleted file mode 100644
index 31b53bf..0000000
--- a/src/dotnet-library/scala/xml/HasKeyValue.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* HasKeyValue.scala does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/xml/MalformedAttributeException.scala b/src/dotnet-library/scala/xml/MalformedAttributeException.scala
deleted file mode 100644
index 4fea099..0000000
--- a/src/dotnet-library/scala/xml/MalformedAttributeException.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* MalformedAttributeException.scala does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/xml/MetaData.scala b/src/dotnet-library/scala/xml/MetaData.scala
deleted file mode 100644
index 16ba9b0..0000000
--- a/src/dotnet-library/scala/xml/MetaData.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* MetaData.scala does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/xml/NamespaceBinding.scala b/src/dotnet-library/scala/xml/NamespaceBinding.scala
deleted file mode 100644
index 6fa1309..0000000
--- a/src/dotnet-library/scala/xml/NamespaceBinding.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* NamespaceBinding.scala does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/xml/Node.scala b/src/dotnet-library/scala/xml/Node.scala
deleted file mode 100644
index a4fda43..0000000
--- a/src/dotnet-library/scala/xml/Node.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* Node.scala does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/xml/NodeBuffer.scala b/src/dotnet-library/scala/xml/NodeBuffer.scala
deleted file mode 100644
index 37bed04..0000000
--- a/src/dotnet-library/scala/xml/NodeBuffer.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* NodeBuffer.scala does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/xml/NodeSeq.scala b/src/dotnet-library/scala/xml/NodeSeq.scala
deleted file mode 100644
index b7a6371..0000000
--- a/src/dotnet-library/scala/xml/NodeSeq.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* NodeSeq.scala does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/xml/NodeTraverser.scala b/src/dotnet-library/scala/xml/NodeTraverser.scala
deleted file mode 100644
index 87aca3a..0000000
--- a/src/dotnet-library/scala/xml/NodeTraverser.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* NodeTraverser.scala does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/xml/Null.scala b/src/dotnet-library/scala/xml/Null.scala
deleted file mode 100644
index 42f17ee..0000000
--- a/src/dotnet-library/scala/xml/Null.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* Null.scala does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/xml/PCData.scala b/src/dotnet-library/scala/xml/PCData.scala
deleted file mode 100644
index 185b016..0000000
--- a/src/dotnet-library/scala/xml/PCData.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* PCData.scala does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/xml/Parsing.scala b/src/dotnet-library/scala/xml/Parsing.scala
deleted file mode 100644
index 510a535..0000000
--- a/src/dotnet-library/scala/xml/Parsing.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* Parsing.scala does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/xml/PrefixedAttribute.scala b/src/dotnet-library/scala/xml/PrefixedAttribute.scala
deleted file mode 100644
index a01eee7..0000000
--- a/src/dotnet-library/scala/xml/PrefixedAttribute.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* PrefixedAttribute.scala does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/xml/PrettyPrinter.scala b/src/dotnet-library/scala/xml/PrettyPrinter.scala
deleted file mode 100644
index c45630b..0000000
--- a/src/dotnet-library/scala/xml/PrettyPrinter.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* PrettyPrinter.scala does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/xml/ProcInstr.scala b/src/dotnet-library/scala/xml/ProcInstr.scala
deleted file mode 100644
index c3f6874..0000000
--- a/src/dotnet-library/scala/xml/ProcInstr.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* ProcInstr.scala does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/xml/QNode.scala b/src/dotnet-library/scala/xml/QNode.scala
deleted file mode 100644
index 29f0274..0000000
--- a/src/dotnet-library/scala/xml/QNode.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* QNode.scala does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/xml/SpecialNode.scala b/src/dotnet-library/scala/xml/SpecialNode.scala
deleted file mode 100644
index 857a02f..0000000
--- a/src/dotnet-library/scala/xml/SpecialNode.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* SpecialNode.scala does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/xml/Text.scala b/src/dotnet-library/scala/xml/Text.scala
deleted file mode 100644
index 9b23f64..0000000
--- a/src/dotnet-library/scala/xml/Text.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* Text.scala does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/xml/TextBuffer.scala b/src/dotnet-library/scala/xml/TextBuffer.scala
deleted file mode 100644
index 3a97bc1..0000000
--- a/src/dotnet-library/scala/xml/TextBuffer.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* TextBuffer.scala does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/xml/TopScope.scala b/src/dotnet-library/scala/xml/TopScope.scala
deleted file mode 100644
index bcc4491..0000000
--- a/src/dotnet-library/scala/xml/TopScope.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* TopScope.scala does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/xml/TypeSymbol.scala b/src/dotnet-library/scala/xml/TypeSymbol.scala
deleted file mode 100644
index d300f74..0000000
--- a/src/dotnet-library/scala/xml/TypeSymbol.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* TypeSymbol.scala does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/xml/Unparsed.scala b/src/dotnet-library/scala/xml/Unparsed.scala
deleted file mode 100644
index 2a0d68b..0000000
--- a/src/dotnet-library/scala/xml/Unparsed.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* Unparsed.scala does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/xml/UnprefixedAttribute.scala b/src/dotnet-library/scala/xml/UnprefixedAttribute.scala
deleted file mode 100644
index bb959f7..0000000
--- a/src/dotnet-library/scala/xml/UnprefixedAttribute.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* UnprefixedAttribute.scala does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/xml/Utility.scala b/src/dotnet-library/scala/xml/Utility.scala
deleted file mode 100644
index 874a96b..0000000
--- a/src/dotnet-library/scala/xml/Utility.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* Utility.scala does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/xml/XML.scala b/src/dotnet-library/scala/xml/XML.scala
deleted file mode 100644
index 4333bf1..0000000
--- a/src/dotnet-library/scala/xml/XML.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* XML.scala does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/xml/Xhtml.scala b/src/dotnet-library/scala/xml/Xhtml.scala
deleted file mode 100644
index d55d9b4..0000000
--- a/src/dotnet-library/scala/xml/Xhtml.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* Xhtml.scala does not exist for the dotnet target */
diff --git a/src/dotnet-library/scala/xml/dtd/ContentModel.scala b/src/dotnet-library/scala/xml/dtd/ContentModel.scala
deleted file mode 100644
index cd14638..0000000
--- a/src/dotnet-library/scala/xml/dtd/ContentModel.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* ContentModel.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/xml/dtd/ContentModelParser.scala b/src/dotnet-library/scala/xml/dtd/ContentModelParser.scala
deleted file mode 100644
index ac73be0..0000000
--- a/src/dotnet-library/scala/xml/dtd/ContentModelParser.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* ContentModelParser.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/xml/dtd/DTD.scala b/src/dotnet-library/scala/xml/dtd/DTD.scala
deleted file mode 100644
index 529c8df..0000000
--- a/src/dotnet-library/scala/xml/dtd/DTD.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* DTD.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/xml/dtd/Decl.scala b/src/dotnet-library/scala/xml/dtd/Decl.scala
deleted file mode 100644
index a412a09..0000000
--- a/src/dotnet-library/scala/xml/dtd/Decl.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* Decl.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/xml/dtd/DocType.scala b/src/dotnet-library/scala/xml/dtd/DocType.scala
deleted file mode 100644
index 13c54e3..0000000
--- a/src/dotnet-library/scala/xml/dtd/DocType.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* DocType.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/xml/dtd/DtdTypeSymbol.scala b/src/dotnet-library/scala/xml/dtd/DtdTypeSymbol.scala
deleted file mode 100644
index afcfeb5..0000000
--- a/src/dotnet-library/scala/xml/dtd/DtdTypeSymbol.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* DtdTypeSymbol.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/xml/dtd/ElementValidator.scala b/src/dotnet-library/scala/xml/dtd/ElementValidator.scala
deleted file mode 100644
index 0f3141e..0000000
--- a/src/dotnet-library/scala/xml/dtd/ElementValidator.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* ElementValidator.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/xml/dtd/ExternalID.scala b/src/dotnet-library/scala/xml/dtd/ExternalID.scala
deleted file mode 100644
index c508524..0000000
--- a/src/dotnet-library/scala/xml/dtd/ExternalID.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* ExternalID.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/xml/dtd/Scanner.scala b/src/dotnet-library/scala/xml/dtd/Scanner.scala
deleted file mode 100644
index 882a99c..0000000
--- a/src/dotnet-library/scala/xml/dtd/Scanner.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* Scanner.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/xml/dtd/Tokens.scala b/src/dotnet-library/scala/xml/dtd/Tokens.scala
deleted file mode 100644
index 8cc8924..0000000
--- a/src/dotnet-library/scala/xml/dtd/Tokens.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* Tokens.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/xml/dtd/ValidationException.scala b/src/dotnet-library/scala/xml/dtd/ValidationException.scala
deleted file mode 100644
index 18ccbd4..0000000
--- a/src/dotnet-library/scala/xml/dtd/ValidationException.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* ValidationException.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/xml/factory/Binder.scala b/src/dotnet-library/scala/xml/factory/Binder.scala
deleted file mode 100644
index d491f8e..0000000
--- a/src/dotnet-library/scala/xml/factory/Binder.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* Binder.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/xml/factory/LoggedNodeFactory.scala b/src/dotnet-library/scala/xml/factory/LoggedNodeFactory.scala
deleted file mode 100644
index 176e4bc..0000000
--- a/src/dotnet-library/scala/xml/factory/LoggedNodeFactory.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* LoggedNodeFactory.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/xml/factory/NodeFactory.scala b/src/dotnet-library/scala/xml/factory/NodeFactory.scala
deleted file mode 100644
index e4137d6..0000000
--- a/src/dotnet-library/scala/xml/factory/NodeFactory.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* NodeFactory.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/xml/include/CircularIncludeException.scala b/src/dotnet-library/scala/xml/include/CircularIncludeException.scala
deleted file mode 100644
index 12da87f..0000000
--- a/src/dotnet-library/scala/xml/include/CircularIncludeException.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* CircularIncludeException.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/xml/include/UnavailableResourceException.scala b/src/dotnet-library/scala/xml/include/UnavailableResourceException.scala
deleted file mode 100644
index 17b2069..0000000
--- a/src/dotnet-library/scala/xml/include/UnavailableResourceException.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* UnavailableResourceException.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/xml/include/XIncludeException.scala b/src/dotnet-library/scala/xml/include/XIncludeException.scala
deleted file mode 100644
index 1e384e1..0000000
--- a/src/dotnet-library/scala/xml/include/XIncludeException.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* XIncludeException.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/xml/include/sax/EncodingHeuristics.scala b/src/dotnet-library/scala/xml/include/sax/EncodingHeuristics.scala
deleted file mode 100644
index a6b4854..0000000
--- a/src/dotnet-library/scala/xml/include/sax/EncodingHeuristics.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* EncodingHeuristics.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/xml/include/sax/Main.scala b/src/dotnet-library/scala/xml/include/sax/Main.scala
deleted file mode 100644
index 63433c7..0000000
--- a/src/dotnet-library/scala/xml/include/sax/Main.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* Main.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/xml/include/sax/XIncludeFilter.scala b/src/dotnet-library/scala/xml/include/sax/XIncludeFilter.scala
deleted file mode 100644
index 9ec2db6..0000000
--- a/src/dotnet-library/scala/xml/include/sax/XIncludeFilter.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* XIncludeFilter.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/xml/include/sax/XIncluder.scala b/src/dotnet-library/scala/xml/include/sax/XIncluder.scala
deleted file mode 100644
index 46bfd47..0000000
--- a/src/dotnet-library/scala/xml/include/sax/XIncluder.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* XIncluder.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/xml/parsing/ConstructingHandler.scala b/src/dotnet-library/scala/xml/parsing/ConstructingHandler.scala
deleted file mode 100644
index a2f0c8a..0000000
--- a/src/dotnet-library/scala/xml/parsing/ConstructingHandler.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* ConstructingHandler.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/xml/parsing/ConstructingParser.scala b/src/dotnet-library/scala/xml/parsing/ConstructingParser.scala
deleted file mode 100644
index c3c0647..0000000
--- a/src/dotnet-library/scala/xml/parsing/ConstructingParser.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* ConstructingParser.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/xml/parsing/DefaultMarkupHandler.scala b/src/dotnet-library/scala/xml/parsing/DefaultMarkupHandler.scala
deleted file mode 100644
index 07b6169..0000000
--- a/src/dotnet-library/scala/xml/parsing/DefaultMarkupHandler.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* DefaultMarkupHandler.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/xml/parsing/ExternalSources.scala b/src/dotnet-library/scala/xml/parsing/ExternalSources.scala
deleted file mode 100644
index 53d7b01..0000000
--- a/src/dotnet-library/scala/xml/parsing/ExternalSources.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* ExternalSources.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/xml/parsing/FactoryAdapter.scala b/src/dotnet-library/scala/xml/parsing/FactoryAdapter.scala
deleted file mode 100644
index 93ee1d9..0000000
--- a/src/dotnet-library/scala/xml/parsing/FactoryAdapter.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* FactoryAdapter.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/xml/parsing/FatalError.scala b/src/dotnet-library/scala/xml/parsing/FatalError.scala
deleted file mode 100644
index 16127b6..0000000
--- a/src/dotnet-library/scala/xml/parsing/FatalError.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* FatalError.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/xml/parsing/MarkupHandler.scala b/src/dotnet-library/scala/xml/parsing/MarkupHandler.scala
deleted file mode 100644
index fa2eb18..0000000
--- a/src/dotnet-library/scala/xml/parsing/MarkupHandler.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* MarkupHandler.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/xml/parsing/MarkupParser.scala b/src/dotnet-library/scala/xml/parsing/MarkupParser.scala
deleted file mode 100644
index 8de8e9b..0000000
--- a/src/dotnet-library/scala/xml/parsing/MarkupParser.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* MarkupParser.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/xml/parsing/NoBindingFactoryAdapter.scala b/src/dotnet-library/scala/xml/parsing/NoBindingFactoryAdapter.scala
deleted file mode 100644
index 238d436..0000000
--- a/src/dotnet-library/scala/xml/parsing/NoBindingFactoryAdapter.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* NoBindingFactoryAdapter.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/xml/parsing/TokenTests.scala b/src/dotnet-library/scala/xml/parsing/TokenTests.scala
deleted file mode 100644
index 86c64c5..0000000
--- a/src/dotnet-library/scala/xml/parsing/TokenTests.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* TokenTests.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/xml/parsing/ValidatingMarkupHandler.scala b/src/dotnet-library/scala/xml/parsing/ValidatingMarkupHandler.scala
deleted file mode 100644
index b41e349..0000000
--- a/src/dotnet-library/scala/xml/parsing/ValidatingMarkupHandler.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* ValidatingMarkupHandler.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/xml/parsing/XhtmlEntities.scala b/src/dotnet-library/scala/xml/parsing/XhtmlEntities.scala
deleted file mode 100644
index b2c05fb..0000000
--- a/src/dotnet-library/scala/xml/parsing/XhtmlEntities.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* XhtmlEntities.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/xml/parsing/XhtmlParser.scala b/src/dotnet-library/scala/xml/parsing/XhtmlParser.scala
deleted file mode 100644
index 2386bd9..0000000
--- a/src/dotnet-library/scala/xml/parsing/XhtmlParser.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* XhtmlParser.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/xml/path/Expression.scala b/src/dotnet-library/scala/xml/path/Expression.scala
deleted file mode 100644
index 0ea3b48..0000000
--- a/src/dotnet-library/scala/xml/path/Expression.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* Expression.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/xml/persistent/CachedFileStorage.scala b/src/dotnet-library/scala/xml/persistent/CachedFileStorage.scala
deleted file mode 100644
index 2845a22..0000000
--- a/src/dotnet-library/scala/xml/persistent/CachedFileStorage.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* CachedFileStorage.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/xml/persistent/Index.scala b/src/dotnet-library/scala/xml/persistent/Index.scala
deleted file mode 100644
index 239f21f..0000000
--- a/src/dotnet-library/scala/xml/persistent/Index.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* Index.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/xml/persistent/IndexedStorage.scala b/src/dotnet-library/scala/xml/persistent/IndexedStorage.scala
deleted file mode 100644
index 63158b4..0000000
--- a/src/dotnet-library/scala/xml/persistent/IndexedStorage.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* IndexedStorage.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/xml/persistent/SetStorage.scala b/src/dotnet-library/scala/xml/persistent/SetStorage.scala
deleted file mode 100644
index 6722499..0000000
--- a/src/dotnet-library/scala/xml/persistent/SetStorage.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* SetStorage.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/xml/pull/XMLEvent.scala b/src/dotnet-library/scala/xml/pull/XMLEvent.scala
deleted file mode 100644
index 554105f..0000000
--- a/src/dotnet-library/scala/xml/pull/XMLEvent.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* XMLEvent.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/xml/pull/XMLEventReader.scala b/src/dotnet-library/scala/xml/pull/XMLEventReader.scala
deleted file mode 100644
index db11fde..0000000
--- a/src/dotnet-library/scala/xml/pull/XMLEventReader.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* XMLEventReader.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/xml/transform/BasicTransformer.scala b/src/dotnet-library/scala/xml/transform/BasicTransformer.scala
deleted file mode 100644
index 4a7f5c3..0000000
--- a/src/dotnet-library/scala/xml/transform/BasicTransformer.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* BasicTransformer.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/xml/transform/RewriteRule.scala b/src/dotnet-library/scala/xml/transform/RewriteRule.scala
deleted file mode 100644
index f7ff367..0000000
--- a/src/dotnet-library/scala/xml/transform/RewriteRule.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* RewriteRule.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/dotnet-library/scala/xml/transform/RuleTransformer.scala b/src/dotnet-library/scala/xml/transform/RuleTransformer.scala
deleted file mode 100644
index 3fcd455..0000000
--- a/src/dotnet-library/scala/xml/transform/RuleTransformer.scala
+++ /dev/null
@@ -1 +0,0 @@
-/* RuleTransformer.scala does not exist for the dotnet target */
\ No newline at end of file
diff --git a/src/fjbg/ch/epfl/lamp/fjbg/FJBGContext.java b/src/fjbg/ch/epfl/lamp/fjbg/FJBGContext.java
new file mode 100644
index 0000000..569a9ac
--- /dev/null
+++ b/src/fjbg/ch/epfl/lamp/fjbg/FJBGContext.java
@@ -0,0 +1,169 @@
+
+package ch.epfl.lamp.fjbg;
+
+import java.io.DataInputStream;
+import java.io.IOException;
+
+/**
+ * Context in which FJBG executes. Used both as a factory for most
+ * FJBG classes and as a repository for other factories.
+ *
+ * @author Michel Schinz
+ * @version 1.0
+ */
+
+public class FJBGContext {
+    /** Class file major version */
+    final int MAJOR_VERSION;
+
+    /** Class file minor version */
+    final int MINOR_VERSION;
+
+    public FJBGContext() {
+        this(45, 3);
+    }
+
+    public FJBGContext(int major, int minor) {
+        MAJOR_VERSION = major;
+        MINOR_VERSION = minor;
+    }
+
+    // Factory methods
+    //////////////////////////////////////////////////////////////////////
+
+    public JClass JClass(int accessFlags,
+                         String name,
+                         String superclassName,
+                         String[] interfaceNames,
+                         String sourceFileName) {
+        return new JClass(this,
+                          accessFlags,
+                          name,
+                          superclassName,
+                          interfaceNames,
+                          sourceFileName);
+    }
+
+    public JClass JClass(DataInputStream stream)
+        throws IOException {
+        return new JClass(this, stream);
+    }
+
+    public JConstantPool JConstantPool() {
+        return new JConstantPool(this);
+    }
+
+    public JConstantPool JConstantPool(DataInputStream stream)
+        throws IOException {
+        return new JConstantPool(this, stream);
+    }
+
+    public JField JField(JClass owner,
+			 int accessFlags,
+			 String name,
+			 JType type) {
+        return new JField(this,
+                          owner,
+			  accessFlags,
+			  name,
+			  type);
+    }
+
+    public JField JField(JClass owner, DataInputStream stream)
+        throws IOException {
+        return new JField(this, owner, stream);
+    }
+
+    public JMethod JMethod(JClass owner,
+                           int accessFlags,
+                           String name,
+                           JType returnType,
+                           JType[] argTypes,
+                           String[] argNames) {
+        return new JMethod(this,
+                           owner,
+                           accessFlags,
+                           name,
+                           returnType,
+                           argTypes,
+                           argNames);
+    }
+
+    public JMethod JMethod(JClass owner,
+                           int accessFlags,
+                           String name,
+                           JMethodType type,
+                           String[] argNames) {
+        return JMethod(owner,
+                       accessFlags,
+                       name,
+                       type.getReturnType(),
+                       type.getArgumentTypes(),
+                       argNames);
+    }
+
+    public JMethod JMethod(JClass owner, DataInputStream stream)
+        throws IOException {
+        return new JMethod(this, owner, stream);
+    }
+
+    public JLocalVariable JLocalVariable(JMethod owner,
+                                         JType type,
+                                         String name,
+                                         int index) {
+        return new JLocalVariable(this, owner, type, name, index);
+    }
+
+    public JCode JCode(JClass clazz, JMethod owner) {
+        return new JExtendedCode(this, clazz, owner);
+    }
+
+    public JCode JCode(JClass clazz, JMethod owner, DataInputStream stream)
+        throws IOException {
+        return new JCode(this, clazz, owner, stream);
+    }
+
+    public JAttributeFactory JAttributeFactory() {
+        return new JAttributeFactory(this);
+    }
+
+    // Attributes
+    public JCodeAttribute JCodeAttribute(JClass clazz, JMethod owner) {
+        return new JCodeAttribute(this, clazz, owner);
+    }
+
+    public JLineNumberTableAttribute JLineNumberTableAttribute(JClass clazz,
+                                                               JCode owner) {
+        return new JLineNumberTableAttribute(this, clazz, owner);
+    }
+
+    public JOtherAttribute JOtherAttribute(JClass clazz,
+                                           Object owner,
+                                           String name,
+                                           byte[] contents,
+                                           int length) {
+        return new JOtherAttribute(this, clazz, owner, name, contents, length);
+    }
+
+    public JOtherAttribute JOtherAttribute(JClass clazz,
+                                           Object owner,
+                                           String name,
+                                           byte[] contents) {
+        return JOtherAttribute(clazz, owner, name, contents, contents.length);
+    }
+
+    public JSourceFileAttribute JSourceFileAttribute(JClass clazz,
+                                                     String sourceFileName) {
+        return new JSourceFileAttribute(this, clazz, sourceFileName);
+    }
+
+    /// Repository
+    //////////////////////////////////////////////////////////////////////
+
+    protected JAttributeFactory jAttributeFactory = null;
+    public JAttributeFactory getJAttributeFactory() {
+        if (jAttributeFactory == null)
+            jAttributeFactory = JAttributeFactory();
+        return jAttributeFactory;
+    }
+}
diff --git a/src/fjbg/ch/epfl/lamp/fjbg/JAccessFlags.java b/src/fjbg/ch/epfl/lamp/fjbg/JAccessFlags.java
new file mode 100644
index 0000000..78fbcf1
--- /dev/null
+++ b/src/fjbg/ch/epfl/lamp/fjbg/JAccessFlags.java
@@ -0,0 +1,31 @@
+
+package ch.epfl.lamp.fjbg;
+
+/**
+ * Definition of access flags for fields, methods and classes.
+ *
+ * @author Michel Schinz
+ * @version 1.0
+ */
+
+public interface JAccessFlags {
+    public static int ACC_PUBLIC    = 0x0001;
+    public static int ACC_PRIVATE   = 0x0002;
+    public static int ACC_PROTECTED = 0x0004;
+    public static int ACC_STATIC    = 0x0008;
+    public static int ACC_FINAL     = 0x0010;
+    public static int ACC_SUPER     = 0x0020;
+    public static int ACC_VOLATILE  = 0x0040;
+    public static int ACC_TRANSIENT = 0x0080;
+    public static int ACC_NATIVE    = 0x0100;
+    public static int ACC_INTERFACE = 0x0200;
+    public static int ACC_ABSTRACT  = 0x0400;
+    public static int ACC_STRICT    = 0x0800;
+    public static int ACC_SYNTHETIC = 0x1000;
+    public static int ACC_ANNOTATION= 0x2000;
+    public static int ACC_ENUM      = 0x4000;
+    
+    // 1.5 specifics
+    public static int ACC_BRIDGE    = 0x0040;
+    public static int ACC_VARARGS   = 0x0080;    
+}
diff --git a/src/fjbg/ch/epfl/lamp/fjbg/JArrayType.java b/src/fjbg/ch/epfl/lamp/fjbg/JArrayType.java
new file mode 100644
index 0000000..53aeee3
--- /dev/null
+++ b/src/fjbg/ch/epfl/lamp/fjbg/JArrayType.java
@@ -0,0 +1,58 @@
+
+package ch.epfl.lamp.fjbg;
+
+/**
+ * Types for Java arrays.
+ *
+ * @author Michel Schinz
+ * @version 1.0
+ */
+
+public class JArrayType extends JReferenceType {
+    protected final JType elementType;
+    protected String signature = null;
+
+    public JArrayType(JType elementType) {
+        this.elementType = elementType;
+    }
+
+    public int getSize() { return 1; }
+
+    public String getSignature() {
+        if (signature == null)
+            signature = "[" + elementType.getSignature();
+        return signature;
+    }
+
+    public String getDescriptor() {
+        return getSignature();
+    }
+
+    public int getTag() { return T_ARRAY; }
+
+    public JType getElementType() { return elementType; }
+
+    public String toString() {
+        return elementType.toString() + "[]";
+    }
+
+    public boolean isArrayType() { return true; }
+
+    public boolean isCompatibleWith(JType other) {
+        if (other instanceof JObjectType)
+            return (JObjectType)other == JObjectType.JAVA_LANG_OBJECT;
+        else if (other instanceof JArrayType)
+            return elementType.isCompatibleWith(((JArrayType)other).elementType);
+        else return other == JType.REFERENCE;
+    }
+
+    public static JArrayType BOOLEAN   = new JArrayType(JType.BOOLEAN);
+    public static JArrayType BYTE      = new JArrayType(JType.BYTE);
+    public static JArrayType CHAR      = new JArrayType(JType.CHAR);
+    public static JArrayType SHORT     = new JArrayType(JType.SHORT);
+    public static JArrayType INT       = new JArrayType(JType.INT);
+    public static JArrayType FLOAT     = new JArrayType(JType.FLOAT);
+    public static JArrayType LONG      = new JArrayType(JType.LONG);
+    public static JArrayType DOUBLE    = new JArrayType(JType.DOUBLE);
+    public static JArrayType REFERENCE = new JArrayType(JType.REFERENCE);
+}
diff --git a/src/fjbg/ch/epfl/lamp/fjbg/JAttribute.java b/src/fjbg/ch/epfl/lamp/fjbg/JAttribute.java
new file mode 100644
index 0000000..caaff77
--- /dev/null
+++ b/src/fjbg/ch/epfl/lamp/fjbg/JAttribute.java
@@ -0,0 +1,74 @@
+
+package ch.epfl.lamp.fjbg;
+
+import java.io.*;
+import java.util.*;
+
+/**
+ * Abstract superclass for attributes which can be attached to various
+ * parts of a class file.
+ *
+ * @author Michel Schinz
+ * @version 1.0
+ */
+
+public abstract class JAttribute {
+    protected final int nameIdx;
+
+    static public void writeTo(List/*<JAttribute>*/ attrs, DataOutputStream stream)
+        throws IOException {
+        stream.writeShort(attrs.size());
+        Iterator attrsIt = attrs.iterator();
+        while (attrsIt.hasNext()) {
+            JAttribute attr = (JAttribute)attrsIt.next();
+            attr.writeTo(stream);
+        }
+    }
+
+    static public List/*<JAttribute>*/ readFrom(FJBGContext context,
+                                                JClass clazz,
+                                                Object owner,
+                                                DataInputStream stream)
+        throws IOException {
+        JAttributeFactory factory = context.getJAttributeFactory();
+        int count = stream.readShort();
+        ArrayList list = new ArrayList(count);
+        for (int i = 0; i < count; ++i)
+            list.add(factory.newInstance(clazz, owner, stream));
+        return list;
+    }
+
+    public JAttribute(FJBGContext context, JClass clazz) {
+        this.nameIdx = clazz.getConstantPool().addUtf8(getName());
+    }
+
+    public JAttribute(FJBGContext context, JClass clazz, String name) {
+        this.nameIdx = clazz.getConstantPool().addUtf8(name);
+    }
+
+    abstract public String getName();
+
+    /**
+     * Write the attribute to a stream.
+     */
+    public void writeTo(DataOutputStream stream) throws IOException {
+        int contentsSize = getSize();
+
+        stream.writeShort(nameIdx);
+        stream.writeInt(contentsSize);
+        int streamSizeBefore = stream.size();
+        writeContentsTo(stream);
+        int streamSizeDiff = stream.size() - streamSizeBefore;
+
+        assert contentsSize == streamSizeDiff
+            : "invalid size for attribute " + getName()
+            + " given: " + contentsSize
+            + " actual: " + streamSizeDiff;
+    }
+
+    // Note: it is not legal to add data to the constant pool during
+    // the execution of any of the following two methods.
+    protected abstract int getSize();
+    protected abstract void writeContentsTo(DataOutputStream stream)
+        throws IOException;
+}
diff --git a/src/fjbg/ch/epfl/lamp/fjbg/JAttributeFactory.java b/src/fjbg/ch/epfl/lamp/fjbg/JAttributeFactory.java
new file mode 100644
index 0000000..92333dc
--- /dev/null
+++ b/src/fjbg/ch/epfl/lamp/fjbg/JAttributeFactory.java
@@ -0,0 +1,90 @@
+
+package ch.epfl.lamp.fjbg;
+
+import java.io.*;
+import java.util.*;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.InvocationTargetException;
+
+/**
+ * Extensible factory to build subclasses of JAttribute based on an
+ * attribute name.
+ *
+ * @author Michel Schinz
+ * @version 1.0
+ */
+
+public class JAttributeFactory {
+    protected FJBGContext context;
+    protected HashMap/*<String, Constructor>*/ constructors = new HashMap();
+
+    protected final static Class[] CONSTRUCTOR_ARGS = new Class[] {
+        FJBGContext.class,
+        JClass.class,
+        Object.class,
+        String.class,
+        int.class,
+        DataInputStream.class
+    };
+
+    protected final static Constructor defaultDefaultConstructor;
+    static {
+        try {
+            defaultDefaultConstructor =
+                 JOtherAttribute.class.getConstructor(CONSTRUCTOR_ARGS);
+        } catch (NoSuchMethodException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    protected final Constructor defaultConstructor;
+
+    public JAttributeFactory(FJBGContext context,
+                             Constructor defaultConstructor) {
+        this.context = context;
+        this.defaultConstructor = defaultConstructor;
+        registerClass("Code", JCodeAttribute.class);
+        registerClass("LineNumberTable", JLineNumberTableAttribute.class);
+        registerClass("SourceFile", JSourceFileAttribute.class);
+    }
+
+    public JAttributeFactory(FJBGContext context) {
+        this(context, defaultDefaultConstructor);
+    }
+
+    public void registerClass(String attributeName,
+                              Class clazz) {
+        if (! JAttribute.class.isAssignableFrom(clazz))
+            throw new IllegalArgumentException("Not a subclass of JAttribute: "
+                                               + clazz);
+
+        try {
+            Constructor constr = clazz.getConstructor(CONSTRUCTOR_ARGS);
+            constructors.put(attributeName, constr);
+        } catch (NoSuchMethodException e) {
+            throw new IllegalArgumentException("No appropriate constructor for "
+                                               + clazz);
+        }
+    }
+
+    public JAttribute newInstance(JClass clazz,
+                                  Object owner,
+                                  DataInputStream stream)
+        throws IOException {
+        String name = clazz.getConstantPool().lookupUtf8(stream.readShort());
+        Integer size = new Integer(stream.readInt());
+        Constructor constr = (Constructor)constructors.get(name);
+        if (constr == null) constr = defaultConstructor;
+
+        Object[] args = new Object[] { context, clazz, owner, name, size, stream };
+        try {
+            return (JAttribute)constr.newInstance(args);
+        } catch (InstantiationException e) {
+            throw new RuntimeException(e);
+        } catch (IllegalAccessException e) {
+            throw new RuntimeException(e);
+        } catch (InvocationTargetException e) {
+            throw new RuntimeException(e);
+        }
+    }
+}
diff --git a/src/fjbg/ch/epfl/lamp/fjbg/JBootstrapInvokeDynamic.java b/src/fjbg/ch/epfl/lamp/fjbg/JBootstrapInvokeDynamic.java
new file mode 100644
index 0000000..1907d33
--- /dev/null
+++ b/src/fjbg/ch/epfl/lamp/fjbg/JBootstrapInvokeDynamic.java
@@ -0,0 +1,35 @@
+package ch.epfl.lamp.fjbg;
+
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.util.Iterator;
+
+/**
+ * BootstrapInvokeDynamic entry, as described by JSR 292 (invoke dynamic)
+ * 
+ * @author Iulian Dragos
+ *
+ */
+public class JBootstrapInvokeDynamic extends JAttribute {
+	/** Constant pool of the current classfile. */
+	private JConstantPool pool;
+	
+	private int classIndex = -1;
+	
+    public JBootstrapInvokeDynamic(FJBGContext context,
+            JClass clazz, String className) {
+    	super(context, clazz);
+    	this.pool = clazz.pool;
+    	this.classIndex = pool.addClass(className);
+    }
+	
+    public String getName() { return "BootstrapInvokeDynamic"; }
+
+	protected int getSize() {
+		return 2;
+	}
+
+	protected void writeContentsTo(DataOutputStream stream) throws IOException {
+		stream.writeShort(classIndex);
+	}
+}
diff --git a/src/fjbg/ch/epfl/lamp/fjbg/JClass.java b/src/fjbg/ch/epfl/lamp/fjbg/JClass.java
new file mode 100644
index 0000000..5f9f483
--- /dev/null
+++ b/src/fjbg/ch/epfl/lamp/fjbg/JClass.java
@@ -0,0 +1,319 @@
+
+package ch.epfl.lamp.fjbg;
+
+import java.util.*;
+import java.io.*;
+
+/**
+ * Representation of a Java class.
+ *
+ * @author Michel Schinz
+ * @version 1.0
+ */
+public class JClass extends JMember {
+
+    /** Magic number for Java class files. */
+    public final static int MAGIC_NUMBER = 0xCAFEBABE;
+
+    protected final JAttributeFactory attributeFactory;
+
+    protected final String superclassName;
+    protected final String[] interfaceNames;
+    protected final String sourceFileName;
+    protected final JConstantPool pool;
+    
+    protected JBootstrapInvokeDynamic bootstrapClassAttr = null;
+
+    public final static String[] NO_INTERFACES = new String[0];
+
+    protected final LinkedList/*<JMethod>*/ methods = new LinkedList();
+    protected final LinkedList/*<JField>*/ fields = new LinkedList();
+
+    protected JInnerClassesAttribute innerClasses;
+    
+    protected int major;
+    protected int minor;
+
+    /**
+     * Creates a new class with its access flags, name, superclass name,
+     * interfaces names and source file name initialized to a given value.
+     * The constructor also initializes the pool and adds a sourceFileName
+     * attribute to the class.
+     * @param accessFlags the int representing the access flags of the class.
+     * @param name the string representing the name of the class.
+     * @param superclassName the string representing the name of the class'
+     * superclass.
+     * @param interfaceNames the list of strings representing the names of the
+     * interfaces implemented by the class.
+     * @param sourceFileName name of the file from which the class was compiled.
+     */
+    protected JClass(FJBGContext context,
+                     int accessFlags,
+                     String name,
+                     String superclassName,
+                     String[] interfaceNames,
+                     String sourceFileName) {
+        super(context, accessFlags, name);
+        this.attributeFactory = context.getJAttributeFactory();
+
+        this.major = context.MAJOR_VERSION;
+        this.minor = context.MINOR_VERSION;
+
+        this.superclassName = superclassName;
+        this.interfaceNames = interfaceNames;
+        this.sourceFileName = sourceFileName;
+        this.pool = context.JConstantPool();
+        if (sourceFileName != null)
+            addAttribute(context.JSourceFileAttribute(this, sourceFileName));
+    }
+
+    protected JClass(FJBGContext context, DataInputStream stream)
+        throws IOException {
+        super(context);
+        this.attributeFactory = context.getJAttributeFactory();
+
+        int magic = stream.readInt();
+        if (magic != MAGIC_NUMBER)
+            throw new IllegalArgumentException("invalid magic number: "+magic);
+
+        minor = stream.readShort();
+        major = stream.readShort();
+        pool = context.JConstantPool(stream);
+        accessFlags = stream.readShort();
+
+	// This class, super class and interfaces
+        name = pool.lookupClass(stream.readShort());
+        superclassName = pool.lookupClass(stream.readShort());
+        interfaceNames = new String[stream.readShort()];
+        for (int i = 0; i < interfaceNames.length; ++i)
+            interfaceNames[i] = pool.lookupClass(stream.readShort());
+
+        // Fields, methods and attributes
+        int fieldsCount = stream.readShort();
+        for (int i = 0; i < fieldsCount; ++i)
+            addField(context.JField(this, stream));
+
+        int methodsCount = stream.readShort();
+        for (int i = 0; i < methodsCount; ++i)
+            addMethod(context.JMethod(this, stream));
+
+        int attributesCount = stream.readShort();
+        for (int i = 0; i < attributesCount; ++i)
+            addAttribute(attributeFactory.newInstance(this, this, stream));
+
+        sourceFileName = null;
+    }
+
+    /**
+     * Gets the name of the class' superclass.
+     * @return The string representing the name of the class' superclass.
+     */
+    public String getSuperclassName() { return superclassName; }
+
+    /**
+     * Gets the names of the interfaces implemented by the class.
+     * @return The array containing the string representations of the
+     * names of the interfaces implemented by the class.
+     */
+    public String[] getInterfaceNames() { return interfaceNames; }
+
+    /**
+     * Gets the type of the objects that are instances of the class.
+     * @return The type of the instances of the class.
+     */
+    public JType getType() { return new JObjectType(name); }
+
+    public JClass getJClass() { return this; }
+
+    /**
+     * Gets the version number of the class.
+     * @param major The int representing the major part of the version number
+     * of the class.
+     * @param minor The int representing the minor part of the version number
+     * of the class.
+     */
+    public void setVersion(int major, int minor) {
+        assert !frozen;
+	this.major = major;
+	this.minor = minor;
+    }
+
+    /**
+     * Gets the major part of the number describing the version of the class.
+     * @return The int representing the major part of the version number of
+     * the class.
+     */
+    public int getMajorVersion() { return major; }
+
+    /**
+     * Gets the minor part of the number describing the version of the class.
+     * @return The int representing the minor part of the version number of
+     * the class.
+     */
+    public int getMinorVersion() { return minor; }
+
+    /**
+     * Gets the constant pool of the class.
+     * @return The constant pool of the class.
+     */
+    public JConstantPool getConstantPool() { return pool; }
+
+    public JInnerClassesAttribute getInnerClasses() {
+    	if (innerClasses == null) {
+    		innerClasses = new JInnerClassesAttribute(context, this);
+    		addAttribute(innerClasses);
+    	}
+    	return innerClasses;
+    }
+    
+    /**
+     * Decides if the class is an interface.
+     * @return The boolean representing if the class is an interface or not.
+     */
+    public boolean isInterface() {
+	return (accessFlags & JAccessFlags.ACC_INTERFACE) != 0;
+    }
+
+    public void addField(JField field) {
+        assert !frozen;
+	fields.add(field);
+    }
+
+    /**
+     * Create and add a new field to the class.
+     */
+    public JField addNewField(int accessFlags, String name, JType type) {
+        assert !frozen;
+        JField f = context.JField(this, accessFlags, name, type);
+        addField(f);
+        return f;
+    }
+
+    protected void addMethod(JMethod method) {
+        assert !frozen;
+	methods.add(method);
+    }
+
+    /**
+     * Create and add a new method to the class.
+     */
+    public JMethod addNewMethod(int accessFlags,
+                                String name,
+                                JType returnType,
+                                JType[] argTypes,
+                                String[] argNames) {
+        assert !frozen;
+        JMethod m = context.JMethod(this,
+                                    accessFlags,
+                                    name,
+                                    returnType,
+                                    argTypes,
+                                    argNames);
+        addMethod(m);
+        return m;
+    }
+
+    /**
+     * Remove a previously-added method. This makes no attempt at
+     * minimising the constant pool by removing all constants which
+     * were used only by this method.
+     */
+    public void removeMethod(JMethod m) {
+        assert !frozen;
+        methods.remove(m);
+    }
+
+    public JMethod[] getMethods() {
+        return (JMethod[])methods.toArray(new JMethod[methods.size()]);
+    }
+
+    /**
+     * Freeze the contents of this class so that it can be written to
+     * a file.
+     */
+    public void freeze() {
+        assert !frozen;
+        frozen = true;
+    }
+
+    /**
+     * Writes the contents of the class to a file referenced by its name.
+     * @param fileName The name of the file in which the class must be written.
+     */
+    public void writeTo(String fileName) throws IOException {
+        writeTo(new File(fileName));
+    }
+
+    /**
+     * Writes the contents of the class to a file.
+     * @param file The file in which the class must be written.
+     */
+    public void writeTo(File file) throws IOException {
+        File parent = file.getParentFile();
+        if (parent != null && !parent.isDirectory())
+            if (!parent.mkdirs())
+                throw new IOException("cannot create directory " + parent);
+
+	FileOutputStream fStream = new FileOutputStream(file);
+        BufferedOutputStream bStream = new BufferedOutputStream(fStream);
+	DataOutputStream dStream = new DataOutputStream(bStream);
+	writeTo(dStream);
+	dStream.close();
+        bStream.close();
+	fStream.close();
+    }
+
+    public void setBootstrapClass(String bootstrapClass) {
+    	assert bootstrapClassAttr == null;
+    	bootstrapClassAttr = new JBootstrapInvokeDynamic(context, this, bootstrapClass);
+    	addAttribute(bootstrapClassAttr);
+    }
+    
+    /**
+     * Writes the contents of the class to a data stream.
+     * @param stream The data stream in which the class must be written.
+     */
+    public void writeTo(DataOutputStream stream) throws IOException {
+        if (!frozen) freeze();
+
+	int thisClassIdx = pool.addClass(name);
+	int superClassIdx = pool.addClass(superclassName);
+	int[] interfacesIdx = new int[interfaceNames.length];
+
+	for (int i = 0; i < interfaceNames.length; ++i)
+	    interfacesIdx[i] = pool.addClass(interfaceNames[i]);
+
+        pool.freeze();
+
+	// Magic number.
+	stream.writeInt(MAGIC_NUMBER);
+	// Version
+	stream.writeShort(minor);
+	stream.writeShort(major);
+	// Constant pool
+	pool.writeTo(stream);
+	// Access flags
+	stream.writeShort(accessFlags);
+
+	// This class, super class and interfaces
+	stream.writeShort(thisClassIdx);
+	stream.writeShort(superClassIdx);
+	stream.writeShort(interfacesIdx.length);
+	for (int i = 0; i < interfacesIdx.length; ++i)
+	    stream.writeShort(interfacesIdx[i]);
+
+	// Fields and methods
+	stream.writeShort(fields.size());
+        Iterator fieldsIt = fields.iterator();
+        while (fieldsIt.hasNext())
+            ((JField)fieldsIt.next()).writeTo(stream);
+
+	stream.writeShort(methods.size());
+        Iterator methodsIt = methods.iterator();
+        while (methodsIt.hasNext())
+            ((JMethod)methodsIt.next()).writeTo(stream);
+
+	// Attributes
+        JAttribute.writeTo(attributes, stream);
+    }
+}
diff --git a/src/fjbg/ch/epfl/lamp/fjbg/JCode.java b/src/fjbg/ch/epfl/lamp/fjbg/JCode.java
new file mode 100644
index 0000000..6cc441c
--- /dev/null
+++ b/src/fjbg/ch/epfl/lamp/fjbg/JCode.java
@@ -0,0 +1,1130 @@
+
+package ch.epfl.lamp.fjbg;
+
+import java.util.*;
+import java.io.*;
+
+import ch.epfl.lamp.util.*;
+
+/**
+ * List of instructions, to which Java byte-code instructions can be
+ * added.
+ *
+ * @author Michel Schinz, Thomas Friedli
+ * @version 1.0
+ */
+
+public class JCode {
+    protected boolean frozen = false;
+
+    protected final FJBGContext context;
+    protected final JMethod owner;
+
+    protected final ByteArray codeArray;
+
+    protected final LinkedList/*<ExceptionHandler>*/ exceptionHandlers =
+        new LinkedList();
+
+    protected final JConstantPool pool;
+
+    protected final ArrayList/*<OffsetToPatch>*/ offsetToPatch =
+        new ArrayList();
+
+    protected static int UNKNOWN_STACK_SIZE = Integer.MIN_VALUE;
+    protected int maxStackSize = UNKNOWN_STACK_SIZE;
+    protected int[] stackProduction = null;
+    protected int[] stackSizes;
+
+    protected JCode(FJBGContext context, JClass clazz, JMethod owner) {
+        this.context = context;
+        this.pool = clazz.getConstantPool();
+        this.owner = owner;
+        this.codeArray = new ByteArray();
+    }
+
+    protected JCode(FJBGContext context,
+                    JClass clazz,
+                    JMethod owner,
+                    DataInputStream stream)
+        throws IOException {
+        this.context = context;
+        this.pool = clazz.getConstantPool();
+        this.owner = owner;
+        int size = stream.readInt();
+        this.codeArray = new ByteArray(stream, size);
+    }
+
+    /**
+     * Gets the program counter, which is defined as the address of the
+     * next instruction.
+     * @return The int representing the value of the program counter
+     */
+    public int getPC() {
+        return codeArray.getSize();
+    }
+
+    /**
+     * Gets the size of the code
+     * @return The number of bytes of the code
+     */
+    public int getSize() {
+        return codeArray.getSize();
+    }
+
+    /**
+     * Gets the method to which the code belongs
+     * @return The method to which the code belongs
+     */
+    public JMethod getOwner() {
+        return owner;
+    }
+
+    // Stack size
+    public int getMaxStackSize() {
+        if (maxStackSize == UNKNOWN_STACK_SIZE)
+            maxStackSize = computeMaxStackSize();
+        return maxStackSize;
+    }
+
+    // Freezing
+    //////////////////////////////////////////////////////////////////////
+
+    public void freeze() throws OffsetTooBigException {
+        assert !frozen;
+        patchAllOffset();
+        codeArray.freeze();
+        frozen = true;
+    }
+
+    // Attributes
+    //////////////////////////////////////////////////////////////////////
+
+    protected final LinkedList/*<JAttribute>*/ attributes = new LinkedList();
+
+    public void addAttribute(JAttribute attr) {
+        attributes.add(attr);
+    }
+
+    public List/*<JAttribute>*/ getAttributes() {
+        return attributes;
+    }
+
+    // Emitting code
+    //////////////////////////////////////////////////////////////////////
+
+    public void emit(JOpcode opcode) {
+        setStackProduction(getPC(), opcode);
+        codeArray.addU1(opcode.code);
+    }
+
+    public void emitNOP() { emit(JOpcode.NOP); }
+
+    // Constant loading.
+    public void emitACONST_NULL() { emit(JOpcode.ACONST_NULL); }
+    public void emitICONST_M1() { emit(JOpcode.ICONST_M1); }
+    public void emitICONST_0() { emit(JOpcode.ICONST_0); }
+    public void emitICONST_1() { emit(JOpcode.ICONST_1); }
+    public void emitICONST_2() { emit(JOpcode.ICONST_2); }
+    public void emitICONST_3() { emit(JOpcode.ICONST_3); }
+    public void emitICONST_4() { emit(JOpcode.ICONST_4); }
+    public void emitICONST_5() { emit(JOpcode.ICONST_5); }
+    public void emitLCONST_0() { emit(JOpcode.LCONST_0); }
+    public void emitLCONST_1() { emit(JOpcode.LCONST_1); }
+    public void emitFCONST_0() { emit(JOpcode.FCONST_0); }
+    public void emitFCONST_1() { emit(JOpcode.FCONST_1); }
+    public void emitFCONST_2() { emit(JOpcode.FCONST_2); }
+    public void emitDCONST_0() { emit(JOpcode.DCONST_0); }
+    public void emitDCONST_1() { emit(JOpcode.DCONST_1); }
+
+    public void emitBIPUSH(int b) { emitU1(JOpcode.BIPUSH, b); }
+    public void emitSIPUSH(int s) { emitU2(JOpcode.SIPUSH, s); }
+    public void emitLDC(int value) {
+        emitU1(JOpcode.LDC, pool.addInteger(value));
+    }
+    public void emitLDC(float value) {
+        emitU1(JOpcode.LDC, pool.addFloat(value));
+    }
+    public void emitLDC(String value) {
+        emitU1(JOpcode.LDC, pool.addString(value));
+    }
+    public void emitLDC_W(int value) {
+        emitU1(JOpcode.LDC_W, pool.addInteger(value));
+    }
+    public void emitLDC_W(float value) {
+        emitU1(JOpcode.LDC_W, pool.addFloat(value));
+    }
+    public void emitLDC_W(String value) {
+        emitU1(JOpcode.LDC_W, pool.addString(value));
+    }
+    public void emitLDC2_W(long value) {
+        emitU2(JOpcode.LDC2_W, pool.addLong(value));
+    }
+    public void emitLDC2_W(double value) {
+        emitU2(JOpcode.LDC2_W, pool.addDouble(value));
+    }
+
+    // Loading variables.
+    public void emitILOAD(int index) { emitU1(JOpcode.ILOAD, index); }
+    public void emitLLOAD(int index) { emitU1(JOpcode.LLOAD, index); }
+    public void emitFLOAD(int index) { emitU1(JOpcode.FLOAD, index); }
+    public void emitDLOAD(int index) { emitU1(JOpcode.DLOAD, index); }
+    public void emitALOAD(int index) { emitU1(JOpcode.ALOAD, index); }
+
+    public void emitILOAD_0() { emit(JOpcode.ILOAD_0); }
+    public void emitILOAD_1() { emit(JOpcode.ILOAD_1); }
+    public void emitILOAD_2() { emit(JOpcode.ILOAD_2); }
+    public void emitILOAD_3() { emit(JOpcode.ILOAD_3); }
+    public void emitLLOAD_0() { emit(JOpcode.LLOAD_0); }
+    public void emitLLOAD_1() { emit(JOpcode.LLOAD_1); }
+    public void emitLLOAD_2() { emit(JOpcode.LLOAD_2); }
+    public void emitLLOAD_3() { emit(JOpcode.LLOAD_3); }
+    public void emitFLOAD_0() { emit(JOpcode.FLOAD_0); }
+    public void emitFLOAD_1() { emit(JOpcode.FLOAD_1); }
+    public void emitFLOAD_2() { emit(JOpcode.FLOAD_2); }
+    public void emitFLOAD_3() { emit(JOpcode.FLOAD_3); }
+    public void emitDLOAD_0() { emit(JOpcode.DLOAD_0); }
+    public void emitDLOAD_1() { emit(JOpcode.DLOAD_1); }
+    public void emitDLOAD_2() { emit(JOpcode.DLOAD_2); }
+    public void emitDLOAD_3() { emit(JOpcode.DLOAD_3); }
+    public void emitALOAD_0() { emit(JOpcode.ALOAD_0); }
+    public void emitALOAD_1() { emit(JOpcode.ALOAD_1); }
+    public void emitALOAD_2() { emit(JOpcode.ALOAD_2); }
+    public void emitALOAD_3() { emit(JOpcode.ALOAD_3); }
+
+    public void emitIALOAD() { emit(JOpcode.IALOAD); }
+    public void emitLALOAD() { emit(JOpcode.LALOAD); }
+    public void emitFALOAD() { emit(JOpcode.FALOAD); }
+    public void emitDALOAD() { emit(JOpcode.DALOAD); }
+    public void emitAALOAD() { emit(JOpcode.AALOAD); }
+    public void emitBALOAD() { emit(JOpcode.BALOAD); }
+    public void emitCALOAD() { emit(JOpcode.CALOAD); }
+    public void emitSALOAD() { emit(JOpcode.SALOAD); }
+
+    // Storing variables.
+    public void emitISTORE(int index) { emitU1(JOpcode.ISTORE, index); }
+    public void emitLSTORE(int index) { emitU1(JOpcode.LSTORE, index); }
+    public void emitFSTORE(int index) { emitU1(JOpcode.FSTORE, index); }
+    public void emitDSTORE(int index) { emitU1(JOpcode.DSTORE, index); }
+    public void emitASTORE(int index) { emitU1(JOpcode.ASTORE, index); }
+
+    public void emitISTORE_0() { emit(JOpcode.ISTORE_0); }
+    public void emitISTORE_1() { emit(JOpcode.ISTORE_1); }
+    public void emitISTORE_2() { emit(JOpcode.ISTORE_2); }
+    public void emitISTORE_3() { emit(JOpcode.ISTORE_3); }
+    public void emitLSTORE_0() { emit(JOpcode.LSTORE_0); }
+    public void emitLSTORE_1() { emit(JOpcode.LSTORE_1); }
+    public void emitLSTORE_2() { emit(JOpcode.LSTORE_2); }
+    public void emitLSTORE_3() { emit(JOpcode.LSTORE_3); }
+    public void emitFSTORE_0() { emit(JOpcode.FSTORE_0); }
+    public void emitFSTORE_1() { emit(JOpcode.FSTORE_1); }
+    public void emitFSTORE_2() { emit(JOpcode.FSTORE_2); }
+    public void emitFSTORE_3() { emit(JOpcode.FSTORE_3); }
+    public void emitDSTORE_0() { emit(JOpcode.DSTORE_0); }
+    public void emitDSTORE_1() { emit(JOpcode.DSTORE_1); }
+    public void emitDSTORE_2() { emit(JOpcode.DSTORE_2); }
+    public void emitDSTORE_3() { emit(JOpcode.DSTORE_3); }
+    public void emitASTORE_0() { emit(JOpcode.ASTORE_0); }
+    public void emitASTORE_1() { emit(JOpcode.ASTORE_1); }
+    public void emitASTORE_2() { emit(JOpcode.ASTORE_2); }
+    public void emitASTORE_3() { emit(JOpcode.ASTORE_3); }
+
+    public void emitIASTORE() { emit(JOpcode.IASTORE); }
+    public void emitLASTORE() { emit(JOpcode.LASTORE); }
+    public void emitFASTORE() { emit(JOpcode.FASTORE); }
+    public void emitDASTORE() { emit(JOpcode.DASTORE); }
+    public void emitAASTORE() { emit(JOpcode.AASTORE); }
+    public void emitBASTORE() { emit(JOpcode.BASTORE); }
+    public void emitCASTORE() { emit(JOpcode.CASTORE); }
+    public void emitSASTORE() { emit(JOpcode.SASTORE); }
+
+    // Stack manipulation.
+    public void emitPOP() { emit(JOpcode.POP); }
+    public void emitPOP2() { emit(JOpcode.POP2); }
+    public void emitDUP() { emit(JOpcode.DUP); }
+    public void emitDUP_X1() { emit(JOpcode.DUP_X1); }
+    public void emitDUP_X2() { emit(JOpcode.DUP_X2); }
+    public void emitDUP2() { emit(JOpcode.DUP2); }
+    public void emitDUP2_X1() { emit(JOpcode.DUP2_X1); }
+    public void emitDUP2_X2() { emit(JOpcode.DUP2_X2); }
+    public void emitSWAP() { emit(JOpcode.SWAP); }
+
+    // Artithmetic and logic operations.
+    public void emitIADD() { emit(JOpcode.IADD); }
+    public void emitLADD() { emit(JOpcode.LADD); }
+    public void emitFADD() { emit(JOpcode.FADD); }
+    public void emitDADD() { emit(JOpcode.DADD); }
+
+    public void emitISUB() { emit(JOpcode.ISUB); }
+    public void emitLSUB() { emit(JOpcode.LSUB); }
+    public void emitFSUB() { emit(JOpcode.FSUB); }
+    public void emitDSUB() { emit(JOpcode.DSUB); }
+
+    public void emitIMUL() { emit(JOpcode.IMUL); }
+    public void emitLMUL() { emit(JOpcode.LMUL); }
+    public void emitFMUL() { emit(JOpcode.FMUL); }
+    public void emitDMUL() { emit(JOpcode.DMUL); }
+
+    public void emitIDIV() { emit(JOpcode.IDIV); }
+    public void emitLDIV() { emit(JOpcode.LDIV); }
+    public void emitFDIV() { emit(JOpcode.FDIV); }
+    public void emitDDIV() { emit(JOpcode.DDIV); }
+
+    public void emitIREM() { emit(JOpcode.IREM); }
+    public void emitLREM() { emit(JOpcode.LREM); }
+    public void emitFREM() { emit(JOpcode.FREM); }
+    public void emitDREM() { emit(JOpcode.DREM); }
+
+    public void emitINEG() { emit(JOpcode.INEG); }
+    public void emitLNEG() { emit(JOpcode.LNEG); }
+    public void emitFNEG() { emit(JOpcode.FNEG); }
+    public void emitDNEG() { emit(JOpcode.DNEG); }
+
+    public void emitISHL() { emit(JOpcode.ISHL); }
+    public void emitLSHL() { emit(JOpcode.LSHL); }
+
+    public void emitISHR() { emit(JOpcode.ISHR); }
+    public void emitLSHR() { emit(JOpcode.LSHR); }
+
+    public void emitIUSHR() { emit(JOpcode.IUSHR); }
+    public void emitLUSHR() { emit(JOpcode.LUSHR); }
+
+    public void emitIAND() { emit(JOpcode.IAND); }
+    public void emitLAND() { emit(JOpcode.LAND); }
+
+    public void emitIOR() { emit(JOpcode.IOR); }
+    public void emitLOR() { emit(JOpcode.LOR); }
+
+    public void emitIXOR() { emit(JOpcode.IXOR); }
+    public void emitLXOR() { emit(JOpcode.LXOR); }
+
+    public void emitIINC(int index, int increment) {
+        emitU1U1(JOpcode.IINC, index, increment);
+    }
+
+    // (Numeric) type conversions.
+    public void emitI2L() { emit(JOpcode.I2L); }
+    public void emitI2F() { emit(JOpcode.I2F); }
+    public void emitI2D() { emit(JOpcode.I2D); }
+    public void emitL2I() { emit(JOpcode.L2I); }
+    public void emitL2F() { emit(JOpcode.L2F); }
+    public void emitL2D() { emit(JOpcode.L2D); }
+    public void emitF2I() { emit(JOpcode.F2I); }
+    public void emitF2L() { emit(JOpcode.F2L); }
+    public void emitF2D() { emit(JOpcode.F2D); }
+    public void emitD2I() { emit(JOpcode.D2I); }
+    public void emitD2L() { emit(JOpcode.D2L); }
+    public void emitD2F() { emit(JOpcode.D2F); }
+    public void emitI2B() { emit(JOpcode.I2B); }
+    public void emitI2C() { emit(JOpcode.I2C); }
+    public void emitI2S() { emit(JOpcode.I2S); }
+
+    // Comparisons and tests.
+    public void emitLCMP() { emit(JOpcode.LCMP); }
+    public void emitFCMPL() { emit(JOpcode.FCMPL); }
+    public void emitFCMPG() { emit(JOpcode.FCMPG); }
+    public void emitDCMPL() { emit(JOpcode.DCMPL); }
+    public void emitDCMPG() { emit(JOpcode.DCMPG); }
+
+    protected void emitGenericIF(JOpcode opcode, Label label)
+        throws OffsetTooBigException {
+        emitU2(opcode, label.getOffset16(getPC() + 1, getPC()));
+    }
+
+    public void emitIFEQ(Label label) throws OffsetTooBigException {
+        emitGenericIF(JOpcode.IFEQ, label);
+    }
+    public void emitIFEQ(int targetPC) throws OffsetTooBigException {
+        emitU2(JOpcode.IFEQ, targetPC - getPC());
+    }
+    public void emitIFEQ() {
+        emitU2(JOpcode.IFEQ, 0);
+    }
+
+    public void emitIFNE(Label label) throws OffsetTooBigException {
+        emitGenericIF(JOpcode.IFNE, label);
+    }
+    public void emitIFNE(int targetPC) throws OffsetTooBigException {
+        emitU2(JOpcode.IFNE, targetPC - getPC());
+    }
+    public void emitIFNE() {
+        emitU2(JOpcode.IFNE, 0);
+    }
+
+    public void emitIFLT(Label label) throws OffsetTooBigException {
+        emitGenericIF(JOpcode.IFLT, label);
+    }
+    public void emitIFLT(int targetPC) throws OffsetTooBigException {
+        emitU2(JOpcode.IFLT, targetPC - getPC());
+    }
+    public void emitIFLT() {
+        emitU2(JOpcode.IFLT, 0);
+    }
+
+    public void emitIFGE(Label label) throws OffsetTooBigException {
+        emitGenericIF(JOpcode.IFGE, label);
+    }
+    public void emitIFGE(int targetPC) throws OffsetTooBigException {
+        emitU2(JOpcode.IFGE, targetPC - getPC());
+    }
+    public void emitIFGE() {
+        emitU2(JOpcode.IFGE, 0);
+    }
+
+    public void emitIFGT(Label label) throws OffsetTooBigException {
+        emitGenericIF(JOpcode.IFGT, label);
+    }
+    public void emitIFGT(int targetPC) throws OffsetTooBigException {
+        emitU2(JOpcode.IFGT, targetPC - getPC());
+    }
+    public void emitIFGT() {
+        emitU2(JOpcode.IFGT, 0);
+    }
+
+    public void emitIFLE(Label label) throws OffsetTooBigException {
+        emitGenericIF(JOpcode.IFLE, label);
+    }
+    public void emitIFLE(int targetPC) throws OffsetTooBigException {
+        emitU2(JOpcode.IFLE, targetPC - getPC());
+    }
+    public void emitIFLE() {
+        emitU2(JOpcode.IFLE, 0);
+    }
+
+    public void emitIF_ICMPEQ(Label label) throws OffsetTooBigException {
+        emitGenericIF(JOpcode.IF_ICMPEQ, label);
+    }
+    public void emitIF_ICMPEQ(int targetPC) throws OffsetTooBigException {
+        emitU2(JOpcode.IF_ICMPEQ, targetPC - getPC());
+    }
+    public void emitIF_ICMPEQ() {
+        emitU2(JOpcode.IF_ICMPEQ, 0);
+    }
+
+    public void emitIF_ICMPNE(Label label) throws OffsetTooBigException {
+        emitGenericIF(JOpcode.IF_ICMPNE, label);
+    }
+    public void emitIF_ICMPNE(int targetPC) throws OffsetTooBigException {
+        emitU2(JOpcode.IF_ICMPNE, targetPC - getPC());
+    }
+    public void emitIF_ICMPNE() {
+        emitU2(JOpcode.IF_ICMPNE, 0);
+    }
+
+    public void emitIF_ICMPLT(Label label) throws OffsetTooBigException {
+        emitGenericIF(JOpcode.IF_ICMPLT, label);
+    }
+    public void emitIF_ICMPLT(int targetPC) throws OffsetTooBigException {
+        emitU2(JOpcode.IF_ICMPLT, targetPC - getPC());
+    }
+    public void emitIF_ICMPLT() {
+        emitU2(JOpcode.IF_ICMPLT, 0);
+    }
+
+    public void emitIF_ICMPGE(Label label) throws OffsetTooBigException {
+        emitGenericIF(JOpcode.IF_ICMPGE, label);
+    }
+    public void emitIF_ICMPGE(int targetPC) throws OffsetTooBigException {
+        emitU2(JOpcode.IF_ICMPGE, targetPC - getPC());
+    }
+    public void emitIF_ICMPGE() {
+        emitU2(JOpcode.IF_ICMPGE, 0);
+    }
+
+    public void emitIF_ICMPGT(Label label) throws OffsetTooBigException {
+        emitGenericIF(JOpcode.IF_ICMPGT, label);
+    }
+    public void emitIF_ICMPGT(int targetPC) throws OffsetTooBigException {
+        emitU2(JOpcode.IF_ICMPGT, targetPC - getPC());
+    }
+    public void emitIF_ICMPGT() {
+        emitU2(JOpcode.IF_ICMPGT, 0);
+    }
+
+    public void emitIF_ICMPLE(Label label) throws OffsetTooBigException {
+        emitGenericIF(JOpcode.IF_ICMPLE, label);
+    }
+    public void emitIF_ICMPLE(int targetPC) throws OffsetTooBigException {
+        emitU2(JOpcode.IF_ICMPLE, targetPC - getPC());
+    }
+    public void emitIF_ICMPLE() {
+        emitU2(JOpcode.IF_ICMPLE, 0);
+    }
+
+    public void emitIF_ACMPEQ(Label label) throws OffsetTooBigException {
+        emitGenericIF(JOpcode.IF_ACMPEQ, label);
+    }
+    public void emitIF_ACMPEQ(int targetPC) throws OffsetTooBigException {
+        emitU2(JOpcode.IF_ACMPEQ, targetPC - getPC());
+    }
+    public void emitIF_ACMPEQ() {
+        emitU2(JOpcode.IF_ACMPEQ, 0);
+    }
+
+    public void emitIF_ACMPNE(Label label) throws OffsetTooBigException {
+        emitGenericIF(JOpcode.IF_ACMPNE, label);
+    }
+    public void emitIF_ACMPNE(int targetPC) throws OffsetTooBigException {
+        emitU2(JOpcode.IF_ACMPNE, targetPC - getPC());
+    }
+    public void emitIF_ACMPNE() {
+        emitU2(JOpcode.IF_ACMPNE, 0);
+    }
+
+    public void emitIFNULL(Label label) throws OffsetTooBigException {
+        emitGenericIF(JOpcode.IFNULL, label);
+    }
+    public void emitIFNULL(int targetPC) throws OffsetTooBigException {
+        emitU2(JOpcode.IFNULL, targetPC - getPC());
+    }
+    public void emitIFNULL() {
+        emitU2(JOpcode.IFNULL, 0);
+    }
+
+    public void emitIFNONNULL(Label label) throws OffsetTooBigException {
+        emitGenericIF(JOpcode.IFNONNULL, label);
+    }
+    public void emitIFNONNULL(int targetPC) throws OffsetTooBigException {
+        emitU2(JOpcode.IFNONNULL, targetPC - getPC());
+    }
+    public void emitIFNONNULL() {
+        emitU2(JOpcode.IFNONNULL, 0);
+    }
+
+    public void emitGOTO(Label label) throws OffsetTooBigException {
+        emitU2(JOpcode.GOTO, label.getOffset16(getPC() + 1, getPC()));
+    }
+    public void emitGOTO(int targetPC) throws OffsetTooBigException {
+        int offset = targetPC - getPC();
+        checkOffset16(offset);
+        emitU2(JOpcode.GOTO, offset);
+    }
+    public void emitGOTO() {
+        emitU2(JOpcode.GOTO, 0);
+    }
+
+    public void emitGOTO_W(Label label) {
+        emitU4(JOpcode.GOTO_W, label.getOffset32(getPC() + 1, getPC()));
+    }
+    public void emitGOTO_W(int targetPC) {
+        emitU4(JOpcode.GOTO_W, targetPC - getPC());
+    }
+    public void emitGOTO_W() {
+        emitU4(JOpcode.GOTO_W, 0);
+    }
+
+    public void emitJSR(Label label) throws OffsetTooBigException {
+        emitU2(JOpcode.JSR, label.getOffset16(getPC() + 1, getPC()));
+    }
+    public void emitJSR(int targetPC) {
+	emitU2(JOpcode.JSR, targetPC - getPC());
+    }
+    public void emitJSR() {
+	emitU2(JOpcode.JSR, 0);
+    }
+
+    public void emitJSR_W(Label label) {
+        emitU4(JOpcode.JSR_W, label.getOffset32(getPC() + 1, getPC()));
+    }
+    public void emitJSR_W(int targetPC) {
+	emitU4(JOpcode.JSR_W, targetPC - getPC());
+    }
+    public void emitJSR_W() {
+	emitU4(JOpcode.JSR_W, 0);
+    }
+
+    /*
+    public void emitRET(Label label) throws OffsetTooBigException {
+        emitU2(JOpcode.RET, label.getOffset16(getPC() + 1, getPC()));
+    }
+    public void emitRET(int targetPC) {
+	emitU1(JOpcode.RET, targetPC);
+    }
+    public void emitRET() {
+	emitU1(JOpcode.RET, 0);
+    }
+    */
+
+    public void emitRET(int index) {
+        emitU1(JOpcode.RET, index);
+    }
+
+    public void emitRET(JLocalVariable var) {
+        emitRET(var.getIndex());
+    }
+
+    public void emitTABLESWITCH(int[] keys,
+				Label[] branches,
+				Label defaultBranch) {
+	assert keys.length == branches.length;
+
+        int low = keys[0], high = keys[keys.length - 1];
+	int instrPC = getPC();
+
+	setStackProduction(instrPC, JOpcode.TABLESWITCH);
+	codeArray.addU1(JOpcode.cTABLESWITCH);
+	while (getPC() % 4 != 0) codeArray.addU1(0);
+
+        codeArray.addU4(defaultBranch.getOffset32(getPC(), instrPC));
+        codeArray.addU4(low);
+        codeArray.addU4(high);
+	for (int i = 0; i < branches.length; i++) {
+            assert keys[i] == low + i;
+            codeArray.addU4(branches[i].getOffset32(getPC(), instrPC));
+	}
+    }
+
+    public void emitLOOKUPSWITCH(int[] keys,
+				 Label[] branches,
+				 Label defaultBranch) {
+	assert keys.length == branches.length;
+
+	int instrPC = getPC();
+	setStackProduction(getPC(), JOpcode.LOOKUPSWITCH);
+	codeArray.addU1(JOpcode.cLOOKUPSWITCH);
+	while (getPC() % 4 != 0) codeArray.addU1(0);
+
+        codeArray.addU4(defaultBranch.getOffset32(getPC(), instrPC));
+	codeArray.addU4(branches.length);
+	for (int i = 0; i < branches.length; i++) {
+	    codeArray.addU4(keys[i]);
+            codeArray.addU4(branches[i].getOffset32(getPC(), instrPC));
+	}
+    }
+
+    public void emitIRETURN() { emit(JOpcode.IRETURN); }
+    public void emitLRETURN() { emit(JOpcode.LRETURN); }
+    public void emitFRETURN() { emit(JOpcode.FRETURN); }
+    public void emitDRETURN() { emit(JOpcode.DRETURN); }
+    public void emitARETURN() { emit(JOpcode.ARETURN); }
+    public void emitRETURN() { emit(JOpcode.RETURN); }
+
+    // Field access
+    public void emitGETSTATIC(String className, String name, JType type) {
+        setStackProduction(getPC(), type.getSize());
+        int index = pool.addFieldRef(className, name, type.getSignature());
+        emitU2(JOpcode.GETSTATIC, index);
+    }
+    public void emitPUTSTATIC(String className, String name, JType type) {
+        setStackProduction(getPC(), -type.getSize());
+        int index = pool.addFieldRef(className, name, type.getSignature());
+        emitU2(JOpcode.PUTSTATIC, index);
+    }
+    public void emitGETFIELD(String className, String name, JType type) {
+        setStackProduction(getPC(), type.getSize() - 1);
+        int index = pool.addFieldRef(className, name, type.getSignature());
+        emitU2(JOpcode.GETFIELD, index);
+    }
+    public void emitPUTFIELD(String className, String name, JType type) {
+        setStackProduction(getPC(), -(type.getSize() + 1));
+        int index = pool.addFieldRef(className, name, type.getSignature());
+        emitU2(JOpcode.PUTFIELD, index);
+    }
+
+    // Method invocation
+    public void emitINVOKEVIRTUAL(String className,
+                                  String name,
+                                  JMethodType type) {
+        setStackProduction(getPC(), type.getProducedStack() - 1);
+        int index =
+            pool.addClassMethodRef(className, name, type.getSignature());
+        emitU2(JOpcode.INVOKEVIRTUAL, index);
+    }
+    public void emitINVOKESPECIAL(String className,
+                                  String name,
+                                  JMethodType type) {
+        setStackProduction(getPC(), type.getProducedStack() - 1);
+        int index =
+            pool.addClassMethodRef(className, name, type.getSignature());
+        emitU2(JOpcode.INVOKESPECIAL, index);
+    }
+    public void emitINVOKESTATIC(String className,
+                                 String name,
+                                 JMethodType type) {
+        setStackProduction(getPC(), type.getProducedStack());
+        int index =
+            pool.addClassMethodRef(className, name, type.getSignature());
+        emitU2(JOpcode.INVOKESTATIC, index);
+    }
+    public void emitINVOKEINTERFACE(String className,
+                                    String name,
+                                    JMethodType type) {
+        setStackProduction(getPC(), type.getProducedStack() - 1);
+        int index =
+            pool.addInterfaceMethodRef(className, name, type.getSignature());
+        emitU2U1U1(JOpcode.INVOKEINTERFACE, index, type.getArgsSize() + 1, 0);
+    }
+
+    // Object creation
+    public void emitNEW(String className) {
+        emitU2(JOpcode.NEW, pool.addClass(className));
+    }
+    public void emitNEWARRAY(JType elemType) {
+        emitU1(JOpcode.NEWARRAY, elemType.getTag());
+    }
+    public void emitANEWARRAY(JReferenceType elemType) {
+        emitU2(JOpcode.ANEWARRAY, pool.addDescriptor(elemType));
+    }
+    public void emitMULTIANEWARRAY(JReferenceType elemType, int dimensions) {
+        setStackProduction(getPC(), -dimensions + 1);
+        emitU2U1(JOpcode.MULTIANEWARRAY,
+                 pool.addDescriptor(elemType),
+                 dimensions);
+    }
+    public void emitARRAYLENGTH() { emit(JOpcode.ARRAYLENGTH); }
+
+    // Exception throwing
+    public void emitATHROW() { emit(JOpcode.ATHROW); }
+
+    // Dynamic typing
+    public void emitCHECKCAST(JReferenceType type) {
+        emitU2(JOpcode.CHECKCAST, pool.addDescriptor(type));
+    }
+    public void emitINSTANCEOF(JReferenceType type) {
+        emitU2(JOpcode.INSTANCEOF, pool.addDescriptor(type));
+    }
+
+    // Monitors
+    public void emitMONITORENTER() { emit(JOpcode.MONITORENTER); }
+    public void emitMONITOREXIT() { emit(JOpcode.MONITOREXIT); }
+
+    // Wide variants
+    // FIXME setStackProd. will here raise an exception
+    public void emitWIDE(JOpcode opcode, int index) {
+        assert (opcode.code == JOpcode.cILOAD)
+            || (opcode.code == JOpcode.cLLOAD)
+            || (opcode.code == JOpcode.cFLOAD)
+            || (opcode.code == JOpcode.cDLOAD)
+            || (opcode.code == JOpcode.cALOAD)
+            || (opcode.code == JOpcode.cISTORE)
+            || (opcode.code == JOpcode.cLSTORE)
+            || (opcode.code == JOpcode.cFSTORE)
+            || (opcode.code == JOpcode.cDSTORE)
+            || (opcode.code == JOpcode.cASTORE)
+	    || (opcode.code == JOpcode.cRET)
+            : "invalide opcode for WIDE: " + opcode;
+
+	setStackProduction(getPC(), opcode);
+	codeArray.addU1(JOpcode.WIDE.code);
+        codeArray.addU1(opcode.code);
+	codeArray.addU2(index);
+    }
+    public void emitWIDE(JOpcode opcode, int index, int constant) {
+	assert opcode.code == JOpcode.cIINC
+            : "invalid opcode for WIDE: " + opcode;
+
+	setStackProduction(getPC(), opcode);
+	codeArray.addU1(JOpcode.cWIDE);
+        codeArray.addU1(opcode.code);
+	codeArray.addU2(index);
+	codeArray.addU2(constant);
+    }
+
+    protected void emitU1(JOpcode opcode, int i1) {
+        setStackProduction(getPC(), opcode);
+        codeArray.addU1(opcode.code);
+	codeArray.addU1(i1);
+    }
+
+    protected void emitU1U1(JOpcode opcode, int i1, int i2) {
+        setStackProduction(getPC(), opcode);
+        codeArray.addU1(opcode.code);
+	codeArray.addU1(i1);
+	codeArray.addU1(i2);
+    }
+
+    protected void emitU2(JOpcode opcode, int i1) {
+        setStackProduction(getPC(), opcode);
+        codeArray.addU1(opcode.code);
+	codeArray.addU2(i1);
+    }
+
+    protected void emitU2U1(JOpcode opcode, int i1, int i2) {
+        setStackProduction(getPC(), opcode);
+        codeArray.addU1(opcode.code);
+	codeArray.addU2(i1);
+	codeArray.addU1(i2);
+    }
+
+    protected void emitU2U1U1(JOpcode opcode, int i1, int i2, int i3) {
+        setStackProduction(getPC(), opcode);
+        codeArray.addU1(opcode.code);
+	codeArray.addU2(i1);
+	codeArray.addU1(i2);
+	codeArray.addU1(i3);
+    }
+
+    protected void emitU4(JOpcode opcode, int i1) {
+        setStackProduction(getPC(), opcode);
+        codeArray.addU1(opcode.code);
+	codeArray.addU4(i1);
+    }
+
+    protected int getU1(int sourcePos) {
+        return codeArray.getU1(sourcePos);
+    }
+
+    protected int getU2(int sourcePos) {
+        return codeArray.getU2(sourcePos);
+    }
+
+    protected int getU4(int sourcePos) {
+        return codeArray.getU4(sourcePos);
+    }
+
+    protected int getS1(int sourcePos) {
+        return codeArray.getS1(sourcePos);
+    }
+
+    protected int getS2(int sourcePos) {
+        return codeArray.getS2(sourcePos);
+    }
+
+    protected int getS4(int sourcePos) {
+        return codeArray.getS4(sourcePos);
+    }
+
+    // Stack size computation
+    //////////////////////////////////////////////////////////////////////
+
+    protected int getStackProduction(int pc) {
+        if (stackProduction == null || pc >= stackProduction.length)
+            return UNKNOWN_STACK_SIZE;
+        else
+            return stackProduction[pc];
+    }
+
+    protected void setStackProduction(int pc, int production) {
+        if (stackProduction == null) {
+            stackProduction = new int[256];
+            Arrays.fill(stackProduction, UNKNOWN_STACK_SIZE);
+        } else {
+        	while (pc >= stackProduction.length) {
+	            int[] newStackProduction = new int[stackProduction.length * 2];
+	            System.arraycopy(stackProduction, 0,
+	                             newStackProduction, 0,
+	                             stackProduction.length);
+	            Arrays.fill(newStackProduction,
+	                        stackProduction.length,
+	                        newStackProduction.length,
+	                        UNKNOWN_STACK_SIZE);
+	            stackProduction = newStackProduction;
+	        }
+        }
+    	stackProduction[pc] = production;
+    }
+
+    protected void setStackProduction(int pc, JOpcode opcode) {
+        // TODO we should instead check whether the opcode has known
+        // stack consumption/production.
+        if (getStackProduction(pc) == UNKNOWN_STACK_SIZE) 
+//        		&& opcode.hasKnownProducedDataSize()
+//        		&& opcode.hasKnownConsumedDataSize())
+            setStackProduction(pc,
+                               opcode.getProducedDataSize()
+                               - opcode.getConsumedDataSize());
+    }
+
+    protected int computeMaxStackSize() {
+        if (stackSizes == null) {
+            stackSizes = new int[getSize()];
+            Arrays.fill(stackSizes, UNKNOWN_STACK_SIZE);
+            stackSizes[0] = 0;
+        }
+        int size = computeMaxStackSize(0, 0, 0);
+        
+        // compute stack sizes for exception handlers too
+        ExceptionHandler exh = null;
+        for (Iterator it = exceptionHandlers.iterator();
+             it.hasNext();) {
+            exh = (ExceptionHandler)it.next();
+            int exhSize = computeMaxStackSize(exh.getHandlerPC(), 1, 1);
+            if (size < exhSize)
+                size = exhSize;
+        }
+
+        return size;
+    }
+
+    protected int computeMaxStackSize(int pc, int stackSize, int maxStackSize) {
+        JCodeIterator iterator = new JCodeIterator(this, pc);
+        for (;;) {
+            int successors = iterator.getSuccessorCount();
+            if (successors == 0)
+                return maxStackSize;
+            else {
+                assert stackProduction[iterator.getPC()] != UNKNOWN_STACK_SIZE
+                    : "unknown stack production, pc=" + iterator.getPC()
+                    + " in method " + owner.getName();
+                stackSize += stackProduction[iterator.getPC()];
+                if (stackSize > maxStackSize)
+                    maxStackSize = stackSize;
+                int nextPC = -1;
+                for (int i = 0; i < successors; ++i) {
+                    int succPC = iterator.getSuccessorPC(i);
+                    assert succPC >= 0 && succPC < stackSizes.length
+                        : iterator.getPC() + ": invalid pc: " + succPC
+                        + " op: " + iterator.getOpcode();
+                    if (stackSizes[succPC] == UNKNOWN_STACK_SIZE) {
+                        stackSizes[succPC] = stackSize;
+                        if (nextPC == -1)
+                            nextPC = succPC;
+                        else
+                            maxStackSize = computeMaxStackSize(succPC,
+                                                               stackSize,
+                                                               maxStackSize);
+                    }
+                }
+                if (nextPC == -1)
+                    return maxStackSize;
+                else
+                    iterator.moveTo(nextPC);
+            }
+        }
+    }
+
+    // Labels
+    //////////////////////////////////////////////////////////////////////
+
+    public static class OffsetTooBigException extends Exception {
+        public OffsetTooBigException() { super(); }
+        public OffsetTooBigException(String message) { super(message); }
+    }
+
+    protected void checkOffset16(int offset) throws OffsetTooBigException {
+        if (offset < Short.MIN_VALUE || offset > Short.MAX_VALUE)
+            throw new OffsetTooBigException("offset too big to fit"
+                                            + " in 16 bits: " + offset);
+    }
+
+    public class Label {
+        protected boolean anchored = false;
+        protected int targetPC = 0;
+
+        public void anchorToNext() {
+            assert !anchored;
+            this.targetPC = getPC();
+            anchored = true;
+        }
+
+        public int getAnchor() {
+            assert anchored;
+            return targetPC;
+        }
+
+        protected int getOffset16(int pc, int instrPC)
+            throws OffsetTooBigException {
+            if (anchored) {
+                int offset = targetPC - instrPC;
+                checkOffset16(offset);
+                return offset;
+            } else {
+                recordOffsetToPatch(pc, 16, instrPC, this);
+                return 0;
+            }
+        }
+
+        protected int getOffset32(int pc, int instrPC) {
+            if (anchored)
+                return targetPC - instrPC;
+            else {
+                recordOffsetToPatch(pc, 32, instrPC, this);
+                return 0;
+            }
+        }
+    }
+
+    public Label newLabel() {
+        return new Label();
+    }
+
+    public Label[] newLabels(int count) {
+        Label[] labels = new Label[count];
+        for (int i = 0; i < labels.length; ++i)
+            labels[i] = newLabel();
+        return labels;
+    }
+
+    protected static class OffsetToPatch {
+        public final int pc;
+        public final int size;
+        public final int instrPC;
+        public final Label label;
+
+        public OffsetToPatch(int pc, int size, int instrPC, Label label) {
+            this.pc = pc;
+            this.size = size;
+            this.instrPC = instrPC;
+            this.label = label;
+        }
+    }
+
+    protected void recordOffsetToPatch(int offsetPC,
+                                       int size,
+                                       int instrPC,
+                                       Label label) {
+        offsetToPatch.add(new OffsetToPatch(offsetPC, size, instrPC, label));
+    }
+
+    protected void patchAllOffset() throws OffsetTooBigException {
+        Iterator offsetIt = offsetToPatch.iterator();
+        while (offsetIt.hasNext()) {
+            OffsetToPatch offset = (OffsetToPatch)offsetIt.next();
+            int offsetValue = offset.label.getAnchor() - offset.instrPC;
+            if (offset.size == 16) {
+                checkOffset16(offsetValue);
+                codeArray.putU2(offset.pc, offsetValue);
+            } else
+                codeArray.putU4(offset.pc, offsetValue);
+        }
+    }
+
+    // Exception handling
+    //////////////////////////////////////////////////////////////////////
+
+    public class ExceptionHandler {
+        protected int startPC, endPC, handlerPC;
+        protected final String catchType;
+        protected final int catchTypeIndex;
+
+        public void setStartPC(int pc) {
+            this.startPC = pc;
+        }
+        
+        public int getStartPC() {
+            return this.startPC;
+        }
+
+        public void setEndPC(int pc) {
+            this.endPC = pc;
+        }
+        
+        public int getEndPC() {
+            return this.endPC;
+        }
+
+        public void setHandlerPC(int pc) {
+            this.handlerPC = pc;
+        }
+        
+        public int getHandlerPC() {
+            return this.handlerPC;
+        }
+
+        public ExceptionHandler(String catchType) {
+            this(0, 0, 0, catchType);
+        }
+
+        public ExceptionHandler(int startPC,
+                                   int endPC,
+                                   int handlerPC,
+                                   String catchType) {
+            this.startPC = startPC;
+            this.endPC = endPC;
+            this.handlerPC = handlerPC;
+            this.catchType = catchType;
+            this.catchTypeIndex = (catchType == null
+                                   ? 0
+                                   : pool.addClass(catchType));
+        }
+
+        public ExceptionHandler(DataInputStream stream) throws IOException {
+            this.startPC = stream.readShort();
+            this.endPC = stream.readShort();
+            this.handlerPC = stream.readShort();
+            this.catchTypeIndex = stream.readShort();
+            this.catchType = (catchTypeIndex == 0
+                              ? null
+                              : pool.lookupClass(catchTypeIndex));
+        }
+
+        public void writeTo(DataOutputStream stream) throws IOException {
+            stream.writeShort(startPC);
+            stream.writeShort(endPC);
+            stream.writeShort(handlerPC);
+            stream.writeShort(catchTypeIndex);
+        }
+    }
+
+    public void addExceptionHandler(ExceptionHandler handler) {
+        assert !frozen;
+        exceptionHandlers.add(handler);
+    }
+
+    public void addExceptionHandler(int startPC,
+                                    int endPC,
+                                    int handlerPC,
+                                    String catchType) {
+        addExceptionHandler(new ExceptionHandler(startPC,
+                                                 endPC,
+                                                 handlerPC,
+                                                 catchType));
+    }
+
+    public void addFinallyHandler(int startPC, int endPC, int handlerPC) {
+        assert !frozen;
+        addExceptionHandler(startPC, endPC, handlerPC, null);
+    }
+
+    public List/*<JExceptionHandler>*/ getExceptionHandlers() {
+        return exceptionHandlers;
+    }
+
+    // Line numbers
+    //////////////////////////////////////////////////////////////////////
+
+    protected int[] lineNumbers = null;
+    protected void ensureLineNumberCapacity(int endPC) {
+        assert !frozen;
+        if (lineNumbers == null) {
+            lineNumbers = new int[endPC];
+            addAttribute(context.JLineNumberTableAttribute(owner.getOwner(),
+                                                           this));
+        } else if (lineNumbers.length < endPC) {
+            int[] newLN = new int[Math.max(endPC, lineNumbers.length * 2)];
+            System.arraycopy(lineNumbers, 0, newLN, 0, lineNumbers.length);
+            lineNumbers = newLN;
+        }
+    }
+
+    /**
+     * Set all line numbers in the interval [startPC, endPC) to
+     * line, overwriting existing line numbers.
+     */
+    public void setLineNumber(int startPC, int endPC, int line) {
+        ensureLineNumberCapacity(endPC);
+        Arrays.fill(lineNumbers, startPC, endPC, line);
+    }
+
+    public void setLineNumber(int instrPC, int line) {
+        setLineNumber(instrPC, instrPC + 1, line);
+    }
+
+    /** Sets all non-filled line numbers in the interval [startPC, endPC)
+     *  to 'line'.
+     */
+    public void completeLineNumber(int startPC, int endPC, int line) {
+        ensureLineNumberCapacity(endPC);
+        for (int pc = startPC; pc < endPC; ++pc)
+            if (lineNumbers[pc] == 0) lineNumbers[pc] = line;
+    }
+
+    public int[] getLineNumbers() {
+        assert frozen;
+        if (lineNumbers == null) return new int[0];
+        else if (lineNumbers.length == getPC()) return lineNumbers;
+        else {
+            int[] trimmedLN = new int[getPC()];
+            System.arraycopy(lineNumbers, 0,
+                             trimmedLN, 0,
+                             Math.min(lineNumbers.length, trimmedLN.length));
+            return trimmedLN;
+        }
+    }
+
+    // Output
+    public void writeTo(DataOutputStream stream) throws IOException {
+        assert frozen;
+        stream.writeInt(getSize());
+	codeArray.writeTo(stream);
+    }
+}
diff --git a/src/fjbg/ch/epfl/lamp/fjbg/JCodeAttribute.java b/src/fjbg/ch/epfl/lamp/fjbg/JCodeAttribute.java
new file mode 100644
index 0000000..44a3d55
--- /dev/null
+++ b/src/fjbg/ch/epfl/lamp/fjbg/JCodeAttribute.java
@@ -0,0 +1,88 @@
+
+package ch.epfl.lamp.fjbg;
+
+import java.util.*;
+import java.io.*;
+
+/**
+ * Code attribute, containing code of methods.
+ *
+ * @author Michel Schinz
+ * @version 1.0
+ */
+
+public class JCodeAttribute extends JAttribute {
+    protected final JCode code;
+
+    public JCodeAttribute(FJBGContext context, JClass clazz, JMethod owner) {
+        super(context, clazz);
+        this.code = owner.getCode();
+
+        assert clazz == owner.getOwner();
+    }
+
+    public JCodeAttribute(FJBGContext context,
+                          JClass clazz,
+                          Object owner,
+                          String name,
+                          int size,
+                          DataInputStream stream)
+        throws IOException {
+        super(context, clazz);
+
+        stream.readShort();     // skip max stack size
+        stream.readShort();     // skip max locals
+
+        this.code = context.JCode(clazz, (JMethod)owner, stream);
+
+        int handlersCount = stream.readShort();
+        for (int i = 0; i < handlersCount; ++i)
+            code.addExceptionHandler(code.new ExceptionHandler(stream));
+
+        List/*<JAttribute>*/ attributes =
+            JAttribute.readFrom(context, clazz, owner, stream);
+        Iterator attrIt = attributes.iterator();
+        while (attrIt.hasNext())
+            code.addAttribute((JAttribute)attrIt.next());
+
+        assert name.equals(getName());
+    }
+
+    public String getName() { return "Code"; }
+
+    protected int getSize() {
+        int handlersNum = code.getExceptionHandlers().size();
+
+        int attrsSize = 0;
+        Iterator attrsIt = code.getAttributes().iterator();
+        while (attrsIt.hasNext()) {
+            JAttribute attr = (JAttribute)attrsIt.next();
+            attrsSize += attr.getSize() + 6;
+        }
+
+        return 2                // max stack
+            + 2                 // max locals
+            + 4                 // code size
+            + code.getSize()    // code
+            + 2                 // exception table size
+            + 8 * handlersNum   // exception table
+            + 2                 // attributes count
+            + attrsSize;        // attributes
+    }
+
+    protected void writeContentsTo(DataOutputStream stream) throws IOException {
+        List/*<JExceptionHandler>*/ handlers = code.getExceptionHandlers();
+
+        stream.writeShort(code.getMaxStackSize());
+        stream.writeShort(code.getOwner().getMaxLocals());
+
+        code.writeTo(stream);
+
+        stream.writeShort(handlers.size());
+        Iterator handlerIt = handlers.iterator();
+        while (handlerIt.hasNext())
+            ((JCode.ExceptionHandler)handlerIt.next()).writeTo(stream);
+
+        JAttribute.writeTo(code.getAttributes(), stream);
+    }
+}
diff --git a/src/fjbg/ch/epfl/lamp/fjbg/JCodeIterator.java b/src/fjbg/ch/epfl/lamp/fjbg/JCodeIterator.java
new file mode 100644
index 0000000..34b38c8
--- /dev/null
+++ b/src/fjbg/ch/epfl/lamp/fjbg/JCodeIterator.java
@@ -0,0 +1,373 @@
+
+package ch.epfl.lamp.fjbg;
+
+import ch.epfl.lamp.util.ByteArray;
+
+/**
+ * Iterator used to examine the contents of an instruction list.
+ *
+ * @version 1.0
+ * @author Michel Schinz, Thomas Friedli
+ */
+
+public class JCodeIterator {
+    protected final JCode code;
+    protected final JConstantPool pool;
+    protected final ByteArray codeArray;
+
+    protected int pc;
+    protected JOpcode opcode;
+
+    /**
+     * Creates a new code iterator with its instruction list
+     * and its pc initialized to a given value.
+     */
+    public JCodeIterator(JCode code, int pc) {
+        this.code = code;
+        this.pool = code.getOwner().getOwner().getConstantPool();
+        this.codeArray = code.codeArray;
+        this.pc = pc;
+        setOpcode();
+    }
+
+    public JCodeIterator(JCode code) {
+        this(code, 0);
+    }
+
+    /**
+     * Get the current program counter.
+     * @return The current program counter.
+     */
+    public int getPC() { return pc; }
+
+    /**
+     * Searches the type of the instruction positionned at the
+     * current address and updates the current instruction.
+     */
+    protected void setOpcode() {
+        // TODO : check if the current pc is the beginning
+        //        of an instruction
+        opcode = isValid() ? JOpcode.OPCODES[codeArray.getU1(pc)] : null;
+    }
+
+    /**
+     * Returns the opcode of the current instruction.
+     * @return The opcode of the current instruction.
+     */
+    public JOpcode getOpcode() {
+        return opcode;
+    }
+
+    /**
+     * Updates the program counter to an given value.
+     * @param pc The new value of the program counter.
+     */
+    public void moveTo(int pc) {
+        this.pc = pc;
+        setOpcode();
+    }
+
+    /**
+     * Check the validity of the iterator.
+     * @return true iff the iterator points to a valid address.
+     */
+    public boolean isValid() {
+        return pc < codeArray.getSize();
+    }
+
+    /**
+     * Updates the current instruction with the next one in the
+     * sense of their position in the code.
+     */
+    public void moveToNext() {
+        moveTo(pc + getInstructionSize());
+    }
+
+    /**
+     * Updates the current instruction with a specific successor
+     * of it.
+     * @param succ The index of the wanted successor in the list of
+     * the successors of the current instruction.
+     */
+    public void moveToSuccessor(int succ) {
+        moveTo(getSuccessorPC(succ));
+    }
+
+    /**
+     * Updates the current instruction with the one positionned
+     * at a given index relatively to the actual program counter
+     * @param offset The relative position of the instruction
+     * compared with the position of the current one
+     */
+    public void moveRelatively(int offset) {
+        moveTo(pc + offset);
+    }
+
+    /**
+     * Returns the size in bytes of the current instruction.
+     * @return The size in bytes of the current instruction.
+     */
+    public int getInstructionSize() {
+        if (opcode.size != JOpcode.UNKNOWN) {
+            return opcode.size;
+        } else if (opcode == JOpcode.TABLESWITCH) {
+            int lowOffset = 1 + pad4(pc + 1) + 4;
+            int low = codeArray.getS4(pc + lowOffset);
+            int high = codeArray.getS4(pc + lowOffset + 4);
+            return lowOffset + 8 + 4 * (high - low + 1);
+        } else if (opcode == JOpcode.LOOKUPSWITCH) {
+            int npairsOffset = 1 + pad4(pc + 1) + 4;
+            int npairs = codeArray.getS4(pc + npairsOffset);
+            return npairsOffset + 4 + 8 * npairs;
+        } else if (opcode == JOpcode.WIDE) {
+            if (codeArray.getU1(pc + 1) == JOpcode.cIINC)
+                return 6;
+            else
+                return 4;
+        } else
+            throw new Error("Unknown size for instruction " + opcode);
+    }
+
+    /**
+     * Returns the number of successors of the current instruction.
+     * @return The number of successors of the current instruction.
+     */
+    public int getSuccessorCount() {
+        if (opcode.successorCount != JOpcode.UNKNOWN) {
+            return opcode.successorCount;
+        } else if (opcode == JOpcode.TABLESWITCH) {
+            int lowPos = pc + 1 + pad4(pc + 1) + 4;
+            return 1                           // default case
+                + codeArray.getS4(lowPos + 4)  // value of HIGH field
+                - codeArray.getS4(lowPos) + 1; // value of LOW field
+        } else if (opcode == JOpcode.LOOKUPSWITCH) {
+            int npairsPos = pc + 1 + pad4(pc + 1) + 4;
+            return 1 + codeArray.getS4(npairsPos);
+        } else
+            throw new Error("Unknown successors for instruction " + opcode);
+    }
+
+    /**
+     * Returns the address of the successor of the current instruction
+     * given its index in the list of successors of the current
+     * instruction.
+     * @param index The index of the wanted successor in the list of
+     * the successors of the current instruction.
+     * @return The address of the specific successor.
+     */
+    public int getSuccessorPC(int index) {
+        assert (index >= 0) && (index < getSuccessorCount()) : index;
+
+        switch (opcode.jumpKind) {
+        case JOpcode.JMP_NEXT:
+            return pc + getInstructionSize();
+        case JOpcode.JMP_ALWAYS_S2_OFFSET:
+            return pc + codeArray.getS2(pc + 1);
+        case JOpcode.JMP_ALWAYS_S4_OFFSET:
+            return pc + codeArray.getS4(pc + 1);
+        case JOpcode.JMP_MAYBE_S2_OFFSET:
+            if (index == 0)
+                return pc + getInstructionSize();
+            else
+                return pc + codeArray.getS2(pc + 1);
+        case JOpcode.JMP_TABLE: {
+            int defaultPos = pc + 1 + pad4(pc + 1);
+            if (index == 0)
+                return pc + codeArray.getS4(defaultPos);
+            else
+                return pc + codeArray.getS4(defaultPos + 3*4 + 4 * (index - 1));
+        }
+        case JOpcode.JMP_LOOKUP: {
+            int defaultPos = pc + 1 + pad4(pc + 1);
+            if (index == 0)
+                return pc + codeArray.getS4(defaultPos);
+            else
+                return pc + codeArray.getS4(defaultPos + 2*4 + 4 + 8 * (index - 1));
+        }
+        default:
+            throw new Error();
+        }
+    }
+
+    /**
+     * Returns the total size of data words put on the stack by the current
+     * instruction.
+     * @return The total size of data words put on the stack by the current
+     * instruction.
+     */
+    public int getProducedDataSize() {
+        if (opcode.getProducedDataTypes() == JOpcode.UNKNOWN_TYPE) {
+            switch (opcode.code) {
+            case JOpcode.cLDC: case JOpcode.cLDC_W: case JOpcode.cBALOAD:
+                return 1;
+            case JOpcode.cLDC2_W: case JOpcode.cDUP: case JOpcode.cSWAP:
+                return 2;
+            case JOpcode.cDUP_X1:
+                return 3;
+            case JOpcode.cDUP_X2: case JOpcode.cDUP2:
+                return 4;
+            case JOpcode.cDUP2_X1:
+                return 5;
+            case JOpcode.cDUP2_X2:
+                return 6;
+            case JOpcode.cGETSTATIC: case JOpcode.cGETFIELD: {
+                JConstantPool.FieldOrMethodRefEntry entry =
+                    (JConstantPool.FieldOrMethodRefEntry)
+                    pool.lookupEntry(codeArray.getU2(pc + 1));
+                return JType.parseSignature(entry.getSignature()).getSize();
+            }
+            case JOpcode.cWIDE : {
+                int op = codeArray.getU1(pc + 1);
+                if (op >= JOpcode.cILOAD && op <= JOpcode.cALOAD) {
+                    JOpcode opcode2 = JOpcode.OPCODES[op];
+                    return JType.getTotalSize(opcode2.getProducedDataTypes());
+                } else if (op >= JOpcode.cISTORE && op <= JOpcode.cASTORE)
+                    return 0;
+                else return 0; // (IINC)
+            }
+            default :
+                throw new Error(opcode.toString());
+            }
+        } else
+            return JType.getTotalSize(opcode.getProducedDataTypes());
+    }
+
+    /**
+     * Returns the total size of data words taken from the stack by the current
+     * instruction.
+     * @return The total size of data words taken from the stack by the current
+     * instruction.
+     */
+    public int getConsumedDataSize() {
+        if (opcode.getConsumedDataTypes() != JOpcode.UNKNOWN_TYPE)
+            return JType.getTotalSize(opcode.getConsumedDataTypes());
+        else {
+            switch (opcode.code) {
+            case JOpcode.cPOP: case JOpcode.cDUP:
+                return 1;
+            case JOpcode.cPOP2: case JOpcode.cSWAP:
+            case JOpcode.cDUP_X1: case JOpcode.cDUP2:
+                return 2;
+            case JOpcode.cDUP_X2: case JOpcode.cDUP2_X1:
+                return 3;
+            case JOpcode.cDUP2_X2:
+                return 4;
+            case JOpcode.cPUTSTATIC: case JOpcode.cPUTFIELD: {
+                JConstantPool.FieldOrMethodRefEntry entry =
+                    (JConstantPool.FieldOrMethodRefEntry)
+                    pool.lookupEntry(codeArray.getU2(pc + 1));
+                return JType.parseSignature(entry.getSignature()).getSize();
+            }
+            case JOpcode.cINVOKEVIRTUAL: case JOpcode.cINVOKESPECIAL:
+            case JOpcode.cINVOKESTATIC:  case JOpcode.cINVOKEINTERFACE : {
+                JConstantPool.FieldOrMethodRefEntry entry =
+                    (JConstantPool.FieldOrMethodRefEntry)
+                    pool.lookupEntry(codeArray.getU2(pc + 1));
+                JMethodType tp = (JMethodType)
+                    JType.parseSignature(entry.getSignature());
+                return tp.getArgsSize()
+                    + (opcode == JOpcode.INVOKESTATIC ? 0 : 1);
+            }
+            case JOpcode.cWIDE : {
+                int op = codeArray.getU1(pc + 1);
+                if (op >= JOpcode.cILOAD && op <= JOpcode.cALOAD)
+                    return 0;
+                else if (op >= JOpcode.cISTORE && op <= JOpcode.cASTORE) {
+                    JOpcode opcode2 = JOpcode.OPCODES[op];
+                    return JType.getTotalSize(opcode2.getConsumedDataTypes());
+                } else
+                    return 0; // (IINC)
+            }
+            case JOpcode.cMULTIANEWARRAY :
+                return codeArray.getU1(pc + 3);
+            default:
+                throw new Error(opcode.toString());
+            }
+        }
+    }
+
+    /**
+     * Returns the number of data types put on the stack by the current
+     * instruction.
+     * @return The number of data types put on the stack by the current
+     * instruction.
+     */
+    public int getProducedDataTypesNumber() {
+        if (opcode.getProducedDataTypes() != JOpcode.UNKNOWN_TYPE)
+            return opcode.getProducedDataTypes().length;
+        else {
+            switch (opcode.code) {
+            case JOpcode.cLDC: case JOpcode.cLDC_W: case JOpcode.cLDC2_W:
+            case JOpcode.cBALOAD: case JOpcode.cGETSTATIC:
+            case JOpcode.cGETFIELD:
+                return 1;
+            case JOpcode.cDUP: case JOpcode.cSWAP:
+                return 2;
+            case JOpcode.cDUP_X1:
+                return 3;
+            case JOpcode.cWIDE: {
+                int op = codeArray.getU1(pc + 1);
+                if (op >= JOpcode.cILOAD && op <= JOpcode.cALOAD)
+                    return 1;
+                else if (op >= JOpcode.cISTORE && op <= JOpcode.cASTORE)
+                    return 0;
+                else
+                    return 0; // (IINC)
+            }
+            default:
+                throw new Error("JOpcode implementation error");
+            }
+        }
+    }
+
+    /**
+     * Returns the number of data types taken from the stack by the current
+     * instruction.
+     * @return The number of data types taken from the stack by the current
+     * instruction.
+     */
+//     public int getConsumedDataTypesNumber() {
+//         if (opcode.getConsumedDataTypes() == JOpcode.UNKNOWN_TYPE) {
+//             switch (opcode.code) {
+//             case 87 : return 1; // POP
+//             case 88 : return 2; // POP2
+//             case 89 : return 1; // DUP
+//             case 90 : return 2; // DUP_X1
+//             case 91 : // DUP_X2
+//             case 92 : // DUP2
+//             case 93 : // DUP2_X1
+//             case 94 : // DUP2_X2
+//                 throw new UnsupportedOperationException("Opcode " + opcode.name
+//                                                         + " has a stack-dependant"
+//                                                         + " data types consumption");
+//             case 95 : return 2; // SWAP
+//             case 179 : return 1; // PUTSTATIC
+//             case 181 : return 1; // PUTFIELD
+//             case 182 : // INVOKEVIRTUAL
+//             case 183 : // INVOKESPECIAL
+//             case 185 : // INVOKEINTERFACE
+//                 s = epool.getClassMethodRef(codeArray.getU2(pc + 1)).split(" ")[3];
+//                 return ((JMethodType)JType.parseSignature(s)).argTypes.length + 1;
+//             case 184 : // INVOKESTATIC
+//                 s = epool.getClassMethodRef(codeArray.getU2(pc + 1)).split(" ")[3];
+//                 return ((JMethodType)JType.parseSignature(s)).argTypes.length;
+//             case 196 : // WIDE
+//                 int op = codeArray.getU1(pc + 1);
+//                 if (op >= 21 && op <= 25) return 0; // (xLOAD)
+//                 else if (op >= 54 && op <= 58) // (xSTORE)
+//                     return JOpcode.OPCODES[op].getConsumedDataTypes().length;
+//                 else return 0; // (IINC)
+//             case 197 : return codeArray.getU1(pc + 3); // MULTIANEWARRAY
+//             default : throw new Error("JOpcode implementation error");
+//             }
+//         } else return opcode.getConsumedDataTypes().length;
+//     }
+
+
+    // Return the number between 0 and 3 which, if added to the given
+    // value, would yield a multiple of 4.
+    protected int[] padding = { 0, 3, 2, 1 };
+    protected int pad4(int value) {
+        return padding[value % 4];
+    }
+}
diff --git a/src/fjbg/ch/epfl/lamp/fjbg/JConstantPool.java b/src/fjbg/ch/epfl/lamp/fjbg/JConstantPool.java
new file mode 100644
index 0000000..0df4498
--- /dev/null
+++ b/src/fjbg/ch/epfl/lamp/fjbg/JConstantPool.java
@@ -0,0 +1,638 @@
+
+package ch.epfl.lamp.fjbg;
+
+import java.util.*;
+import java.io.*;
+
+/**
+ * Constant pool, holding constants for a Java class file.
+ *
+ * @author Michel Schinz
+ * @version 2.0
+ */
+
+public class JConstantPool {
+    protected boolean frozen = false;
+
+    protected HashMap/*<Entry,Integer>*/ entryToIndex = new HashMap();
+    protected Entry[] indexToEntry;
+    protected int currIndex;
+
+    public static final short CONSTANT_Utf8               = 1;
+    public static final short CONSTANT_Integer            = 3;
+    public static final short CONSTANT_Float              = 4;
+    public static final short CONSTANT_Long               = 5;
+    public static final short CONSTANT_Double             = 6;
+    public static final short CONSTANT_Class              = 7;
+    public static final short CONSTANT_String             = 8;
+    public static final short CONSTANT_Fieldref           = 9;
+    public static final short CONSTANT_Methodref          = 10;
+    public static final short CONSTANT_InterfaceMethodref = 11;
+    public static final short CONSTANT_NameAndType        = 12;
+
+    protected JConstantPool(FJBGContext context) {
+        indexToEntry = new Entry[8];
+        currIndex = 1;
+    }
+
+    protected JConstantPool(FJBGContext context, DataInputStream stream)
+        throws IOException {
+        int count = stream.readShort();
+        indexToEntry = new EntryIndex[count];
+
+        currIndex = 1;
+        while (currIndex < count) {
+            EntryIndex e;
+            int tag = stream.readByte();
+
+            switch (tag) {
+            case CONSTANT_Utf8:
+                e = new Utf8Entry(stream);
+                break;
+            case CONSTANT_Integer:
+                e = new IntegerEntry(stream);
+                break;
+            case CONSTANT_Float:
+                e = new FloatEntry(stream);
+                break;
+            case CONSTANT_Long:
+                e = new LongEntry(stream);
+                break;
+            case CONSTANT_Double:
+                e = new DoubleEntry(stream);
+                break;
+            case CONSTANT_Class:
+                e = new DescriptorEntryIndex(stream);
+                break;
+            case CONSTANT_String:
+                e = new StringEntryIndex(stream);
+                break;
+            case CONSTANT_Fieldref:
+            case CONSTANT_Methodref:
+            case CONSTANT_InterfaceMethodref:
+                e = new FieldOrMethodRefEntryIndex(tag, stream);
+                break;
+            case CONSTANT_NameAndType:
+                e = new NameAndTypeEntryIndex(stream);
+                break;
+            default:
+                throw new IllegalArgumentException("unknown entry in pool: " + tag);
+            }
+            indexToEntry[currIndex] = e;
+            currIndex += e.getSize();
+        }
+    }
+
+    public void freeze() { frozen = true; }
+
+    /**
+     * Returns a string representing the type of an entry
+     * knowing its tag
+     * @param tag The tag representing the type of the
+     * constant pool entry
+     */
+    public String getEntryType(int tag) {
+        switch (tag) {
+        case 4 : return "Utf8";
+        case 5 : return "Integer";
+        case 6 : return "Float";
+        case 7 : return "Long";
+        case 8 : return "Double";
+        case 9 : return "Class";
+        case 10 : return "String";
+        case 11 : return "Fieldref";
+        case 12 : return "Methodref";
+        case 13 : return "InterfaceMethodref";
+        case 14 : return "NameAndType";
+        default : throw new Error("invalid constant pool tag : " + tag);
+        }
+    }
+
+    public int addClass(String className) {
+        return addDescriptor(className.replace('.', '/'));
+    }
+
+    public String lookupClass(int index) {
+        DescriptorEntry entry = (DescriptorEntry)lookupEntry(index);
+        return entry.getValue().replace('/', '.');
+    }
+
+    public int addDescriptor(JReferenceType type) {
+        return addDescriptor(type.getDescriptor());
+    }
+
+    protected int addDescriptor(String name) {
+        return addEntry(new DescriptorEntryValue(name));
+    }
+
+    public int addClassMethodRef(String className,
+                                 String methodName,
+                                 String signature) {
+        return addMethodRef(true, className, methodName, signature);
+    }
+
+    public int addInterfaceMethodRef(String className,
+                                     String methodName,
+                                     String signature) {
+        return addMethodRef(false, className, methodName, signature);
+    }
+
+    public int addMethodRef(boolean isClass,
+			    String className,
+			    String methodName,
+			    String signature) {
+        return addEntry(new FieldOrMethodRefEntryValue(isClass
+                                                       ? CONSTANT_Methodref
+                                                       : CONSTANT_InterfaceMethodref,
+                                                       className,
+                                                       methodName,
+                                                       signature));
+    }
+
+    public int addFieldRef(String className,
+                           String fieldName,
+                           String signature) {
+        return addEntry(new FieldOrMethodRefEntryValue(CONSTANT_Fieldref,
+                                                       className,
+                                                       fieldName,
+                                                       signature));
+    }
+
+    public int addInteger(int value) {
+        return addEntry(new IntegerEntry(value));
+    }
+
+    public int addFloat(float value) {
+        return addEntry(new FloatEntry(value));
+    }
+
+    public int addLong(long value) {
+        return addEntry(new LongEntry(value));
+    }
+
+    public int addDouble(double value) {
+        return addEntry(new DoubleEntry(value));
+    }
+
+    public int addString(String value) {
+        return addEntry(new StringEntryValue(value));
+    }
+
+    public int addNameAndType(String name, String descriptor) {
+        return addEntry(new NameAndTypeEntryValue(name, descriptor));
+    }
+
+    public int addUtf8(String value) {
+        return addEntry(new Utf8Entry(value));
+    }
+
+    public int addUtf8(byte[] value) {
+        return addEntry(new Utf8Entry(value));
+    }
+
+    public String lookupUtf8(int index) {
+        Utf8Entry entry = (Utf8Entry)lookupEntry(index);
+        return entry.getValue();
+    }
+
+    protected int addEntry(EntryValue e) {
+        assert !frozen;
+
+        Integer idx = (Integer)entryToIndex.get(e);
+        if (idx != null)
+            return idx.intValue();
+
+        e.addChildren();
+
+        int index = currIndex;
+        currIndex += e.getSize();
+
+        entryToIndex.put(e, new Integer(index));
+        if (index >= indexToEntry.length) {
+            Entry[] newI2E = new Entry[indexToEntry.length * 2];
+            System.arraycopy(indexToEntry, 0, newI2E, 0, indexToEntry.length);
+            indexToEntry = newI2E;
+        }
+        indexToEntry[index] = e;
+        return index;
+    }
+
+    public Entry lookupEntry(int index) {
+        assert index > 0 && index < currIndex
+            : "invalid index: " + index;
+        assert indexToEntry[index] != null
+            : "invalid index (null contents): " + index;
+        return indexToEntry[index];
+    }
+
+    public void writeTo(DataOutputStream stream) throws IOException {
+        if (! frozen) freeze();
+
+	stream.writeShort(currIndex);
+        for (int i = 0; i < currIndex; ++i) {
+            Entry entry = indexToEntry[i];
+            if (entry != null) {
+                stream.writeByte(entry.getTag());
+                entry.writeContentsTo(stream);
+            }
+        }
+    }
+
+    /// Classes for the various kinds of entries
+    //////////////////////////////////////////////////////////////////////
+
+    public interface Entry {
+        public int getTag();
+
+        int getSize();
+        void writeContentsTo(DataOutputStream stream) throws IOException;
+    }
+
+    protected interface EntryValue extends Entry {
+        abstract void addChildren();
+    }
+
+    protected interface EntryIndex extends Entry {
+        abstract void fetchChildren();
+    }
+
+    abstract protected class ChildlessEntry implements EntryValue, EntryIndex {
+        public void addChildren() {}
+        public void fetchChildren() {}
+    }
+
+    public class IntegerEntry extends ChildlessEntry implements Entry {
+        private final int value;
+        public IntegerEntry(int value) { this.value = value; }
+        public IntegerEntry(DataInputStream stream) throws IOException {
+            this(stream.readInt());
+        }
+
+        public int hashCode() { return value; }
+        public boolean equals(Object o) {
+            return o instanceof IntegerEntry && ((IntegerEntry)o).value == value;
+        }
+
+        public int getTag() { return CONSTANT_Integer; }
+        public int getValue() { return value; }
+
+        public int getSize() { return 1; }
+        public void writeContentsTo(DataOutputStream stream) throws IOException {
+            stream.writeInt(value);
+        }
+    }
+
+    public class FloatEntry extends ChildlessEntry implements Entry {
+        private final float value;
+        public FloatEntry(float value) { this.value = value; }
+        public FloatEntry(DataInputStream stream) throws IOException {
+            this(stream.readFloat());
+        }
+
+        public int hashCode() { return (int)value; }
+        public boolean equals(Object o) {
+            return o instanceof FloatEntry && ((FloatEntry)o).value == value;
+        }
+
+        public int getTag() { return CONSTANT_Float; }
+        public float getValue() { return value; }
+
+        public int getSize() { return 1; }
+        public void writeContentsTo(DataOutputStream stream) throws IOException {
+            stream.writeFloat(value);
+        }
+    }
+
+    public class LongEntry extends ChildlessEntry implements Entry {
+        private final long value;
+        public LongEntry(long value) { this.value = value; }
+        public LongEntry(DataInputStream stream) throws IOException {
+            this(stream.readLong());
+        }
+
+        public int hashCode() { return (int)value; }
+        public boolean equals(Object o) {
+            return o instanceof LongEntry && ((LongEntry)o).value == value;
+        }
+
+        public int getTag() { return CONSTANT_Long; }
+        public long getValue() { return value; }
+
+        public int getSize() { return 2; }
+        public void writeContentsTo(DataOutputStream stream) throws IOException {
+            stream.writeLong(value);
+        }
+    }
+
+    public class DoubleEntry extends ChildlessEntry implements Entry {
+        private final double value;
+        public DoubleEntry(double value) { this.value = value; }
+        public DoubleEntry(DataInputStream stream) throws IOException {
+            this(stream.readDouble());
+        }
+
+        public int hashCode() { return (int)value; }
+        public boolean equals(Object o) {
+            return o instanceof DoubleEntry && ((DoubleEntry)o).value == value;
+        }
+
+        public int getTag() { return CONSTANT_Double; }
+        public double getValue() { return value; }
+
+        public int getSize() { return 2; }
+        public void writeContentsTo(DataOutputStream stream) throws IOException {
+            stream.writeDouble(value);
+        }
+    }
+
+    public class Utf8Entry extends ChildlessEntry implements Entry {
+        private final String value;
+        private final byte[] bytes;
+        public Utf8Entry(String value) {
+            this.value = value.intern();
+            this.bytes = null;
+        }
+        public Utf8Entry(DataInputStream stream) throws IOException {
+            this(stream.readUTF());
+        }
+        public Utf8Entry(byte[] bytes) {
+            this.bytes = bytes;
+            this.value = null;
+        }
+
+        public int hashCode() {
+            if (bytes != null) return bytes.hashCode();
+            return value.hashCode();
+        }
+        public boolean equals(Object o) {
+            boolean isEqual = o instanceof Utf8Entry;
+            if (bytes != null) {
+                isEqual = isEqual && ((Utf8Entry)o).bytes == bytes;
+            }
+            else {
+                isEqual = isEqual && ((Utf8Entry)o).value == value;
+            }
+            return isEqual;
+        }
+
+        public int getTag() { return CONSTANT_Utf8; }
+        public String getValue() { return value; }
+        public byte[] getBytes() { return bytes; }
+
+        public int getSize() { return 1; }
+        public void writeContentsTo(DataOutputStream stream) throws IOException {
+            if (bytes != null) {
+                if (bytes.length > 65535) {
+                    throw new IOException("String literal of length " + bytes.length + " does not fit in Classfile");
+                }
+                stream.writeShort(bytes.length);
+                stream.write(bytes);
+            }
+            else
+                stream.writeUTF(value);
+        }
+    }
+
+    abstract public class StringEntry implements Entry {
+        protected String value;
+        protected int valueIndex;
+
+        public int hashCode() {
+            assert value != null;
+            return value.hashCode();
+        }
+        public boolean equals(Object o) {
+            return o instanceof StringEntry && ((StringEntry)o).value == value;
+        }
+
+        public int getTag() { return CONSTANT_String; }
+        public String getValue() { return value; }
+
+        public int getSize() { return 1; }
+        public void writeContentsTo(DataOutputStream stream) throws IOException {
+            stream.writeShort(valueIndex);
+        }
+    }
+
+    public class StringEntryValue extends StringEntry implements EntryValue {
+        public StringEntryValue(String value) {
+            this.value = value.intern();
+        }
+        public void addChildren() {
+            valueIndex = addUtf8(value);
+        }
+    }
+
+    public class StringEntryIndex extends StringEntry implements EntryIndex {
+        public StringEntryIndex(int valueIndex) {
+            this.valueIndex = valueIndex;
+        }
+        public StringEntryIndex(DataInputStream stream) throws IOException {
+            this(stream.readShort());
+        }
+        public String getValue() {
+            if (value == null) fetchChildren();
+            return super.getValue();
+        }
+        public void fetchChildren() {
+            value = lookupUtf8(valueIndex);
+        }
+    }
+
+    abstract public class DescriptorEntry implements Entry {
+        protected String name;
+        protected int nameIndex;
+
+        public int hashCode() {
+            assert name != null;
+            return name.hashCode();
+        }
+        public boolean equals(Object o) {
+            return o instanceof DescriptorEntry && ((DescriptorEntry)o).name == name;
+        }
+
+        public int getTag() { return CONSTANT_Class; }
+        public String getValue() { return name; }
+
+        public int getSize() { return 1; }
+        public void writeContentsTo(DataOutputStream stream) throws IOException {
+            stream.writeShort(nameIndex);
+        }
+    }
+
+    protected class DescriptorEntryValue
+        extends DescriptorEntry
+        implements EntryValue {
+        public DescriptorEntryValue(String name) { this.name = name.intern(); }
+        public void addChildren() {
+            nameIndex = addUtf8(name);
+        }
+    }
+
+    protected class DescriptorEntryIndex
+        extends DescriptorEntry
+        implements EntryIndex {
+        public DescriptorEntryIndex(int nameIndex) { this.nameIndex = nameIndex; }
+        public DescriptorEntryIndex(DataInputStream stream) throws IOException {
+            this(stream.readShort());
+        }
+        public String getValue() {
+            if (name == null) fetchChildren();
+            return super.getValue();
+        }
+        public void fetchChildren() {
+            name = lookupUtf8(nameIndex);
+        }
+    }
+
+    abstract public class FieldOrMethodRefEntry implements Entry {
+        private final int tag;
+        protected String className, thingName, signature;
+        protected int classIndex, nameAndTypeIndex;
+
+        public FieldOrMethodRefEntry(int tag) {
+            assert tag == CONSTANT_Fieldref
+                || tag == CONSTANT_Methodref
+                || tag == CONSTANT_InterfaceMethodref;
+
+            this.tag = tag;
+        }
+
+        public int hashCode() {
+            return tag
+                + className.hashCode()
+                + thingName.hashCode()
+                + signature.hashCode();
+        }
+        public boolean equals(Object o) {
+            return o instanceof FieldOrMethodRefEntry
+                && ((FieldOrMethodRefEntry)o).tag == tag
+                && ((FieldOrMethodRefEntry)o).className == className
+                && ((FieldOrMethodRefEntry)o).thingName == thingName
+                && ((FieldOrMethodRefEntry)o).signature == signature;
+        }
+
+        public int getTag() { return tag; }
+        public String getClassName() { return className; }
+        public String getFieldOrMethodName() { return thingName; }
+        public String getSignature() { return signature; }
+
+        public int getSize() { return 1; }
+        public void writeContentsTo(DataOutputStream stream) throws IOException {
+            stream.writeShort(classIndex);
+            stream.writeShort(nameAndTypeIndex);
+        }
+    }
+
+    protected class FieldOrMethodRefEntryValue
+        extends FieldOrMethodRefEntry
+        implements EntryValue {
+        public FieldOrMethodRefEntryValue(int tag,
+                                          String className,
+                                          String thingName,
+                                          String signature) {
+            super(tag);
+            this.className = className.intern();
+            this.thingName = thingName.intern();
+            this.signature = signature.intern();
+        }
+
+        public void addChildren() {
+            classIndex = addClass(className);
+            nameAndTypeIndex = addNameAndType(thingName, signature);
+        }
+    }
+
+    protected class FieldOrMethodRefEntryIndex
+        extends FieldOrMethodRefEntry
+        implements EntryIndex {
+        public FieldOrMethodRefEntryIndex(int tag,
+                                          int classIndex,
+                                          int nameAndTypeIndex) {
+            super(tag);
+            this.classIndex = classIndex;
+            this.nameAndTypeIndex = nameAndTypeIndex;
+        }
+        public FieldOrMethodRefEntryIndex(int tag, DataInputStream stream)
+            throws IOException {
+            this(tag, stream.readShort(), stream.readShort());
+        }
+        public String getClassName() {
+            if (className == null) fetchChildren();
+            return super.getClassName();
+        }
+        public String getFieldOrMethodName() {
+            if (thingName == null) fetchChildren();
+            return super.getFieldOrMethodName();
+        }
+        public String getSignature() {
+            if (signature == null) fetchChildren();
+            return super.getSignature();
+        }
+        public void fetchChildren() {
+            className = lookupClass(classIndex);
+            NameAndTypeEntry nat = (NameAndTypeEntry)lookupEntry(nameAndTypeIndex);
+            thingName = nat.getName();
+            signature = nat.getDescriptor();
+        }
+    }
+
+    abstract public class NameAndTypeEntry implements Entry {
+        protected String name, descriptor;
+        protected int nameIndex, descriptorIndex;
+
+        public int hashCode() { return name.hashCode() + descriptor.hashCode(); }
+        public boolean equals(Object o) {
+            return o instanceof NameAndTypeEntry
+                && ((NameAndTypeEntry)o).name == name
+                && ((NameAndTypeEntry)o).descriptor == descriptor;
+        }
+
+        public int getTag() { return CONSTANT_NameAndType; }
+        public String getName() { return name; }
+        public String getDescriptor() { return descriptor; }
+
+        public int getSize() { return 1; }
+        public void writeContentsTo(DataOutputStream stream) throws IOException {
+            stream.writeShort(nameIndex);
+            stream.writeShort(descriptorIndex);
+        }
+    }
+
+    protected class NameAndTypeEntryValue
+        extends NameAndTypeEntry
+        implements EntryValue {
+        public NameAndTypeEntryValue(String name, String descriptor) {
+            this.name = name.intern();
+            this.descriptor = descriptor.intern();
+        }
+        public void addChildren() {
+            nameIndex = addUtf8(name);
+            descriptorIndex = addUtf8(descriptor);
+        }
+    }
+
+    protected class NameAndTypeEntryIndex
+        extends NameAndTypeEntry
+        implements EntryIndex {
+        public NameAndTypeEntryIndex(int nameIndex, int descriptorIndex) {
+            this.nameIndex = nameIndex;
+            this.descriptorIndex = descriptorIndex;
+        }
+        public NameAndTypeEntryIndex(DataInputStream stream) throws IOException {
+            this(stream.readShort(), stream.readShort());
+        }
+        public String getName() {
+            if (name == null) fetchChildren();
+            return super.getName();
+        }
+        public String getDescriptor() {
+            if (descriptor == null) fetchChildren();
+            return super.getDescriptor();
+        }
+        public void fetchChildren() {
+            name = lookupUtf8(nameIndex);
+            descriptor = lookupUtf8(descriptorIndex);
+        }
+    }
+}
diff --git a/src/fjbg/ch/epfl/lamp/fjbg/JExtendedCode.java b/src/fjbg/ch/epfl/lamp/fjbg/JExtendedCode.java
new file mode 100644
index 0000000..523f960
--- /dev/null
+++ b/src/fjbg/ch/epfl/lamp/fjbg/JExtendedCode.java
@@ -0,0 +1,613 @@
+
+package ch.epfl.lamp.fjbg;
+
+/**
+ * Extended list of instructions, providing pseudo-instructions which
+ * are easier to use than the standard ones.
+ *
+ * @author Michel Schinz, Thomas Friedli
+ * @version 1.0
+ */
+
+public class JExtendedCode extends JCode {
+    public final static int COND_EQ = 0;
+    public final static int COND_NE = 1;
+    public final static int COND_LT = 2;
+    public final static int COND_GE = 3;
+    public final static int COND_GT = 4;
+    public final static int COND_LE = 5;
+
+    private final JOpcode[] forbidden = new JOpcode[0];
+    private final JOpcode[] nothingToDo = new JOpcode[0];
+
+    private final JOpcode[][][] typeConversions = {
+        {
+            /* T_BOOLEAN -> T_BOOLEAN */ nothingToDo,
+            /* T_BOOLEAN -> T_CHAR */    forbidden,
+            /* T_BOOLEAN -> T_FLOAT */   forbidden,
+            /* T_BOOLEAN -> T_DOUBLE */  forbidden,
+            /* T_BOOLEAN -> T_BYTE */    forbidden,
+            /* T_BOOLEAN -> T_SHORT */   forbidden,
+            /* T_BOOLEAN -> T_INT */     forbidden,
+            /* T_BOOLEAN -> T_LONG */    forbidden
+        },
+        {
+            /* T_CHAR -> T_BOOLEAN */ forbidden,
+            /* T_CHAR -> T_CHAR */    nothingToDo,
+            /* T_CHAR -> T_FLOAT */   {JOpcode.I2F},
+            /* T_CHAR -> T_DOUBLE */  {JOpcode.I2D},
+            /* T_CHAR -> T_BYTE */    {JOpcode.I2B},
+            /* T_CHAR -> T_SHORT */   {JOpcode.I2S},
+            /* T_CHAR -> T_INT */     nothingToDo,
+            /* T_CHAR -> T_LONG */    {JOpcode.I2L}
+        },
+        {
+            /* T_FLOAT -> T_BOOLEAN */ forbidden,
+            /* T_FLOAT -> T_CHAR */    {JOpcode.F2I, JOpcode.I2C},
+            /* T_FLOAT -> T_FLOAT */   nothingToDo,
+            /* T_FLOAT -> T_DOUBLE */  {JOpcode.F2D},
+            /* T_FLOAT -> T_BYTE */    {JOpcode.F2I, JOpcode.I2B},
+            /* T_FLOAT -> T_SHORT */   {JOpcode.F2I, JOpcode.I2S},
+            /* T_FLOAT -> T_INT */     {JOpcode.F2I},
+            /* T_FLOAT -> T_LONG */    {JOpcode.F2L}
+        },
+        {
+            /* T_DOUBLE -> T_BOOLEAN */ forbidden,
+            /* T_DOUBLE -> T_CHAR */    {JOpcode.D2I, JOpcode.I2C},
+            /* T_DOUBLE -> T_FLOAT */   {JOpcode.D2F},
+            /* T_DOUBLE -> T_DOUBLE */  nothingToDo,
+            /* T_DOUBLE -> T_BYTE */    {JOpcode.D2I, JOpcode.I2B},
+            /* T_DOUBLE -> T_SHORT */   {JOpcode.D2I, JOpcode.I2S},
+            /* T_DOUBLE -> T_INT */     {JOpcode.D2I},
+            /* T_DOUBLE -> T_LONG */    {JOpcode.D2L}
+        },
+        {
+            /* T_BYTE -> T_BOOLEAN */ forbidden,
+            /* T_BYTE -> T_CHAR */    {JOpcode.I2C},
+            /* T_BYTE -> T_FLOAT */   {JOpcode.I2F},
+            /* T_BYTE -> T_DOUBLE */  {JOpcode.I2D},
+            /* T_BYTE -> T_BYTE */    nothingToDo,
+            /* T_BYTE -> T_SHORT */   nothingToDo,
+            /* T_BYTE -> T_INT */     nothingToDo,
+            /* T_BYTE -> T_LONG */    {JOpcode.I2L}
+        },
+        {
+            /* T_SHORT -> T_BOOLEAN */ forbidden,
+            /* T_SHORT -> T_CHAR */    {JOpcode.I2C},
+            /* T_SHORT -> T_FLOAT */   {JOpcode.I2F},
+            /* T_SHORT -> T_DOUBLE */  {JOpcode.I2D},
+            /* T_SHORT -> T_BYTE */    {JOpcode.I2B},
+            /* T_SHORT -> T_SHORT */   nothingToDo,
+            /* T_SHORT -> T_INT */     nothingToDo,
+            /* T_SHORT -> T_LONG */    {JOpcode.I2L}
+        },
+        {
+            /* T_INT -> T_BOOLEAN */ forbidden,
+            /* T_INT -> T_CHAR */    {JOpcode.I2C},
+            /* T_INT -> T_FLOAT */   {JOpcode.I2F},
+            /* T_INT -> T_DOUBLE */  {JOpcode.I2D},
+            /* T_INT -> T_BYTE */    {JOpcode.I2B},
+            /* T_INT -> T_SHORT */   {JOpcode.I2S},
+            /* T_INT -> T_INT */     nothingToDo,
+            /* T_INT -> T_LONG */    {JOpcode.I2L}
+        },
+        {
+            /* T_LONG -> T_BOOLEAN */ forbidden,
+            /* T_LONG -> T_CHAR */    {JOpcode.L2I, JOpcode.I2C},
+            /* T_LONG -> T_FLOAT */   {JOpcode.L2F},
+            /* T_LONG -> T_DOUBLE */  {JOpcode.L2D},
+            /* T_LONG -> T_BYTE */    {JOpcode.L2I, JOpcode.I2B},
+            /* T_LONG -> T_SHORT */   {JOpcode.L2I, JOpcode.I2S},
+            /* T_LONG -> T_INT */     {JOpcode.L2I},
+            /* T_LONG -> T_LONG */    nothingToDo
+        }
+    };
+
+    public JExtendedCode(FJBGContext context,
+                         JClass clazz,
+                         JMethod owner) {
+        super(context, clazz, owner);
+    }
+
+    public void emitPUSH(boolean value) { emitPUSH(value ? 1 : 0); }
+    public void emitPUSH(Boolean value) { emitPUSH(value.booleanValue()); }
+
+    public void emitPUSH(byte value) { emitBIPUSH(value); }
+    public void emitPUSH(Byte value) { emitPUSH(value.byteValue()); }
+
+    public void emitPUSH(short value) { emitSIPUSH(value); }
+    public void emitPUSH(Short value) { emitPUSH(value.shortValue()); }
+
+    // TODO check that we do the right thing here
+    public void emitPUSH(char value) { emitPUSH((int)value); }
+    public void emitPUSH(Character value) { emitPUSH(value.charValue()); }
+
+    public void emitPUSH(int value) {
+        switch (value) {
+        case -1: emitICONST_M1(); break;
+        case 0: emitICONST_0(); break;
+        case 1: emitICONST_1(); break;
+        case 2: emitICONST_2(); break;
+        case 3: emitICONST_3(); break;
+        case 4: emitICONST_4(); break;
+        case 5: emitICONST_5(); break;
+        default: emitPUSH_index(pool.addInteger(value)); break;
+        }
+    }
+    public void emitPUSH(Integer value) { emitPUSH(value.intValue()); }
+
+    public void emitPUSH(long value) {
+        if (value == 0L)
+            emitLCONST_0();
+        else if (value == 1L)
+            emitLCONST_1();
+        else
+            emitLDC2_W(value);
+    }
+    public void emitPUSH(Long value) { emitPUSH(value.longValue()); }
+
+    public void emitPUSH(float value) {
+        if (value == 0.0F)
+            emitFCONST_0();
+        else if (value == 1.0F)
+            emitFCONST_1();
+        else if (value == 2.0F)
+            emitFCONST_2();
+        else
+            emitPUSH_index(pool.addFloat(value));
+    }
+    public void emitPUSH(Float value) { emitPUSH(value.floatValue()); }
+
+    public void emitPUSH(double value) {
+        if (value == 0.0)
+            emitDCONST_0();
+        else if (value == 1.0)
+            emitDCONST_1();
+        else
+            emitLDC2_W(value);
+    }
+    public void emitPUSH(Double value) { emitPUSH(value.doubleValue()); }
+
+    public void emitPUSH(String s) {
+        emitPUSH_index(pool.addString(s));
+    }
+
+    /** Pushes a class literal on the stack */
+    public void emitPUSH(JReferenceType type) {
+        assert owner.owner.major >= 49;
+        emitPUSH_index(pool.addClass(type.getDescriptor()));
+    }
+
+    protected void emitPUSH_index(int index) {
+        if (index <= 0xFF)
+            emitU1(JOpcode.LDC, index);
+        else
+            emitU2(JOpcode.LDC_W, index);
+    }
+
+    public void emitLOAD(int index, JType type) {
+        JOpcode opcode;
+
+        switch (type.getTag()) {
+        case JType.T_BOOLEAN: case JType.T_BYTE: case JType.T_CHAR:
+        case JType.T_SHORT: case JType.T_INT:
+            switch (index) {
+            case 0: emitILOAD_0(); return;
+            case 1: emitILOAD_1(); return;
+            case 2: emitILOAD_2(); return;
+            case 3: emitILOAD_3(); return;
+            default: opcode = JOpcode.ILOAD;
+            } break;
+        case JType.T_FLOAT:
+            switch (index) {
+            case 0: emitFLOAD_0(); return;
+            case 1: emitFLOAD_1(); return;
+            case 2: emitFLOAD_2(); return;
+            case 3: emitFLOAD_3(); return;
+            default: opcode = JOpcode.FLOAD;
+            } break;
+        case JType.T_LONG:
+            switch (index) {
+            case 0: emitLLOAD_0(); return;
+            case 1: emitLLOAD_1(); return;
+            case 2: emitLLOAD_2(); return;
+            case 3: emitLLOAD_3(); return;
+            default: opcode = JOpcode.LLOAD;
+            } break;
+        case JType.T_DOUBLE:
+            switch (index) {
+            case 0: emitDLOAD_0(); return;
+            case 1: emitDLOAD_1(); return;
+            case 2: emitDLOAD_2(); return;
+            case 3: emitDLOAD_3(); return;
+            default: opcode = JOpcode.DLOAD;
+            } break;
+        case JType.T_ARRAY: case JType.T_OBJECT:
+            switch (index) {
+            case 0: emitALOAD_0(); return;
+            case 1: emitALOAD_1(); return;
+            case 2: emitALOAD_2(); return;
+            case 3: emitALOAD_3(); return;
+            default: opcode = JOpcode.ALOAD;
+            } break;
+        default:
+            throw new IllegalArgumentException("invalid type for load "+type);
+        }
+
+        if (index > 0xFF)
+            emitWIDE(opcode, index);
+        else
+            emitU1(opcode, index);
+    }
+    public void emitLOAD(JLocalVariable var) {
+        emitLOAD(var.index, var.type);
+    }
+
+    public void emitSTORE(int index, JType type) {
+        JOpcode opcode;
+
+        switch (type.getTag()) {
+        case JType.T_BOOLEAN: case JType.T_BYTE: case JType.T_CHAR:
+        case JType.T_SHORT: case JType.T_INT:
+            switch (index) {
+            case 0: emitISTORE_0(); return;
+            case 1: emitISTORE_1(); return;
+            case 2: emitISTORE_2(); return;
+            case 3: emitISTORE_3(); return;
+            default: opcode = JOpcode.ISTORE;
+            } break;
+        case JType.T_FLOAT:
+            switch (index) {
+            case 0: emitFSTORE_0(); return;
+            case 1: emitFSTORE_1(); return;
+            case 2: emitFSTORE_2(); return;
+            case 3: emitFSTORE_3(); return;
+            default: opcode = JOpcode.FSTORE;
+            } break;
+        case JType.T_LONG:
+            switch (index) {
+            case 0: emitLSTORE_0(); return;
+            case 1: emitLSTORE_1(); return;
+            case 2: emitLSTORE_2(); return;
+            case 3: emitLSTORE_3(); return;
+            default: opcode = JOpcode.LSTORE;
+            } break;
+        case JType.T_DOUBLE:
+            switch (index) {
+            case 0: emitDSTORE_0(); return;
+            case 1: emitDSTORE_1(); return;
+            case 2: emitDSTORE_2(); return;
+            case 3: emitDSTORE_3(); return;
+            default: opcode = JOpcode.DSTORE;
+            } break;
+        case JType.T_ARRAY: case JType.T_OBJECT: case JType.T_ADDRESS:
+            switch (index) {
+            case 0: emitASTORE_0(); return;
+            case 1: emitASTORE_1(); return;
+            case 2: emitASTORE_2(); return;
+            case 3: emitASTORE_3(); return;
+            default: opcode = JOpcode.ASTORE;
+            } break;
+        default:
+            throw new IllegalArgumentException("invalid type for store "+type);
+        }
+
+        if (index > 0xFF)
+            emitWIDE(opcode, index);
+        else
+            emitU1(opcode, index);
+    }
+    public void emitSTORE(JLocalVariable var) {
+        emitSTORE(var.index, var.type);
+    }
+
+    public void emitALOAD(JType type) {
+        switch (type.getTag()) {
+        case JType.T_BOOLEAN:
+        case JType.T_BYTE:
+            emitBALOAD();
+            break;
+        case JType.T_CHAR:
+            emitCALOAD();
+            break;
+        case JType.T_SHORT:
+            emitSALOAD();
+            break;
+        case JType.T_INT:
+            emitIALOAD();
+            break;
+        case JType.T_FLOAT:
+            emitFALOAD();
+            break;
+        case JType.T_LONG:
+            emitLALOAD();
+            break;
+        case JType.T_DOUBLE:
+            emitDALOAD();
+            break;
+        case JType.T_ARRAY:
+        case JType.T_OBJECT:
+            emitAALOAD();
+            break;
+        default:
+            throw new IllegalArgumentException("invalid type for aload " + type);
+        }
+    }
+
+    public void emitASTORE(JType type) {
+        switch (type.getTag()) {
+        case JType.T_BOOLEAN:
+        case JType.T_BYTE:
+            emitBASTORE();
+            break;
+        case JType.T_CHAR:
+            emitCASTORE();
+            break;
+        case JType.T_SHORT:
+            emitSASTORE();
+            break;
+        case JType.T_INT:
+            emitIASTORE();
+            break;
+        case JType.T_FLOAT:
+            emitFASTORE();
+            break;
+        case JType.T_LONG:
+            emitLASTORE();
+            break;
+        case JType.T_DOUBLE:
+            emitDASTORE();
+            break;
+        case JType.T_ARRAY:
+        case JType.T_OBJECT:
+            emitAASTORE();
+            break;
+        default:
+            throw new IllegalArgumentException("invalid type for astore " + type);
+        }
+    }
+
+    public void emitRETURN(JType type) {
+        if (type.isValueType()) {
+            switch (type.getTag()) {
+            case JType.T_BOOLEAN:
+            case JType.T_BYTE:
+            case JType.T_CHAR:
+            case JType.T_SHORT:
+            case JType.T_INT:
+                emitIRETURN();
+                break;
+            case JType.T_FLOAT:
+                emitFRETURN();
+                break;
+            case JType.T_LONG:
+                emitLRETURN();
+                break;
+            case JType.T_DOUBLE:
+                emitDRETURN();
+                break;
+            }
+        } else if (type.isArrayType() || type.isObjectType())
+            emitARETURN();
+        else if (type == JType.VOID)
+            emitRETURN();
+        else
+            throw new IllegalArgumentException("invalid type for RETURN " + type);
+    }
+
+    public void emitADD(JType type) {
+        switch (type.getTag()) {
+        case JType.T_BOOLEAN: case JType.T_BYTE: case JType.T_CHAR:
+        case JType.T_SHORT: case JType.T_INT:
+            emitIADD(); break;
+        case JType.T_FLOAT:
+            emitFADD(); break;
+        case JType.T_LONG:
+            emitLADD(); break;
+        case JType.T_DOUBLE:
+            emitDADD(); break;
+        }
+    }
+
+    /**
+     * Emits a basic type conversion instruction choosen according to the
+     * types given in parameter.
+     *
+     * @param fromType The type of the value to be cast into another type.
+     * @param toType The type the value will be cast into.
+     */
+    public void emitT2T(JType fromType, JType toType) {
+        assert fromType.getTag() >= JType.T_BOOLEAN
+            && fromType.getTag() <= JType.T_LONG
+            && toType.getTag() >= JType.T_BOOLEAN
+            && toType.getTag() <= JType.T_LONG;
+
+        JOpcode[] conv = typeConversions[fromType.getTag() - 4][toType.getTag() - 4];
+        if (conv == forbidden) {
+            throw new Error("inconvertible types : " + fromType.toString()
+                            + " -> " + toType.toString());
+        } else if (conv != nothingToDo) {
+            for (int i = 0; i < conv.length; i++) {
+                emit(conv[i]);
+            }
+        }
+    }
+
+    public void emitIF(int cond, Label label) throws OffsetTooBigException {
+        assert cond >= COND_EQ && cond <= COND_LE;
+        emitU2(JOpcode.OPCODES[153 + cond], label.getOffset16(getPC() + 1, getPC()));
+    }
+    public void emitIF(int cond, int targetPC) throws OffsetTooBigException {
+        int offset = targetPC - getPC();
+        emitU2(JOpcode.OPCODES[153 + cond], offset);
+    }
+    public void emitIF(int cond) throws OffsetTooBigException {
+        emitIF(cond, 0);
+    }
+
+    public void emitIF_ICMP(int cond, Label label) throws OffsetTooBigException {
+        assert cond >= COND_EQ && cond <= COND_LE;
+        emitU2(JOpcode.OPCODES[159 + cond], label.getOffset16(getPC() + 1, getPC()));
+    }
+    public void emitIF_ICMP(int cond, int targetPC) throws OffsetTooBigException {
+        int offset = targetPC - getPC();
+        emitU2(JOpcode.OPCODES[159 + cond], offset);
+    }
+    public void emitIF_ICMP(int cond) throws OffsetTooBigException {
+        emitIF_ICMP(cond, 0);
+    }
+
+    public void emitIF_ACMP(int cond, Label label) throws OffsetTooBigException {
+        assert cond == COND_EQ || cond == COND_NE;
+        emitU2(JOpcode.OPCODES[165 + cond], label.getOffset16(getPC() + 1, getPC()));
+    }
+    public void emitIF_ACMP(int cond, int targetPC) throws OffsetTooBigException {
+        int offset = targetPC - getPC();
+        emitU2(JOpcode.OPCODES[165 + cond], offset);
+    }
+    public void emitIF_ACMP(int cond) throws OffsetTooBigException {
+        emitIF_ACMP(cond, 0);
+    }
+
+    public void emitGOTO_maybe_W(Label label, boolean defaultToWide) {
+        if (label.anchored)
+            emitGOTO_maybe_W(label.targetPC);
+        else {
+            if (defaultToWide)
+                emitGOTO_W(label);
+            else {
+                try {
+                    emitGOTO(label);
+                } catch (OffsetTooBigException e) {
+                    throw new Error(e);
+                }
+            }
+        }
+    }
+
+    public void emitGOTO_maybe_W(int targetPC) {
+        int offset = targetPC - (getPC() + 1);
+        if (offset < Short.MIN_VALUE || offset > Short.MAX_VALUE)
+            emitGOTO_W(targetPC);
+        else {
+            try {
+                emitGOTO(targetPC);
+            } catch (OffsetTooBigException e) {
+                throw new Error(e);
+            }
+        }
+    }
+
+    /**
+     * Emits a switch instruction choosen according to the caracteristics
+     * of the given list of keys and a default maxRate.
+     *
+     * @param keySets The array of all keys that must be compared to the
+     *        value on stack.
+     * @param branches The labels representing the jump addresses linked
+     *        with the corresponding keys.
+     * @param defaultBranch The label representing the default branch
+     *        address.
+     */
+    public void emitSWITCH(int[][] keySets,
+                           Label[] branches,
+                           Label defaultBranch,
+                           double minDensity) {
+        assert keySets.length == branches.length;
+
+        int flatSize = 0;
+        for (int i = 0; i < keySets.length; ++i)
+            flatSize += keySets[i].length;
+
+        int[] flatKeys = new int[flatSize];
+        Label[] flatBranches = new Label[flatSize];
+        int flatI = 0;
+        for (int i = 0; i < keySets.length; ++i) {
+            Label branch = branches[i];
+            int[] keys = keySets[i];
+            for (int j = 0; j < keys.length; ++j) {
+                flatKeys[flatI] = keys[j];
+                flatBranches[flatI] = branch;
+            }
+            ++flatI;
+        }
+        assert flatI == flatSize;
+        emitSWITCH(flatKeys, flatBranches, defaultBranch, minDensity);
+    }
+
+    /**
+     * Emits a switch instruction choosen according to the caracteristics
+     * of the given list of keys and a given maxRate.
+     *
+     * @param keys The array of all keys that must be compared to the
+     *        value on stack.
+     * @param branches The labels representing the jump addresses linked
+     *        with the corresponding keys.
+     * @param defaultBranch The label representing the default branch
+     *        address.
+     * @param minDensity The minimum density to use for TABLESWITCH.
+     */
+    public void emitSWITCH(int[] keys,
+                           Label[] branches,
+                           Label defaultBranch,
+                           double minDensity) {
+        assert keys.length == branches.length;
+
+        // sorting the tables
+        // FIXME use quicksort
+        for (int i = 1; i < keys.length; i++) {
+            for (int j = 1; j <= keys.length - i; j++) {
+                if (keys[j] < keys[j - 1]) {
+                    int tmp = keys[j];
+                    keys[j] = keys[j - 1];
+                    keys[j - 1] = tmp;
+
+                    Label tmp_l = branches[j];
+                    branches[j] = branches[j - 1];
+                    branches[j - 1] = tmp_l;
+                }
+            }
+        }
+
+        int keyMin = keys[0], keyMax = keys[keys.length - 1];
+        int keyRange = keyMax - keyMin + 1;
+        if ((double)keys.length / (double)keyRange >= minDensity) {
+            // Keys are dense enough, use a table in which holes are
+            // filled with defaultBranch.
+            int[] newKeys = new int[keyRange];
+            Label[] newBranches = new Label[keyRange];
+            int oldPos = 0;
+            for (int i = 0; i < keyRange; ++i) {
+                int key = keyMin + i;
+                newKeys[i] = key;
+                if (keys[oldPos] == key) {
+                    newBranches[i] = branches[oldPos];
+                    ++oldPos;
+                } else
+                    newBranches[i] = defaultBranch;
+            }
+            assert oldPos == keys.length;
+            emitTABLESWITCH(newKeys, newBranches, defaultBranch);
+        } else
+            emitLOOKUPSWITCH(keys, branches, defaultBranch);
+    }
+
+    /**
+     * Emits a method invocation instruction choosen according to
+     * the caracteristics of the given method.
+     *
+     * @param method The method to be invoked.
+     */
+    public void emitINVOKE(JMethod method) {
+        String mName = method.getName();
+        String cName = method.getOwner().getName();
+        JMethodType mType = (JMethodType)method.getType();
+        if (method.isStatic())
+            emitINVOKESTATIC(cName, mName, mType);
+        else if (method.getOwner().isInterface())
+            emitINVOKEINTERFACE(cName, mName, mType);
+        else
+            emitINVOKEVIRTUAL(cName, mName, mType);
+    }
+
+}
diff --git a/src/fjbg/ch/epfl/lamp/fjbg/JField.java b/src/fjbg/ch/epfl/lamp/fjbg/JField.java
new file mode 100644
index 0000000..2c1e306
--- /dev/null
+++ b/src/fjbg/ch/epfl/lamp/fjbg/JField.java
@@ -0,0 +1,29 @@
+
+package ch.epfl.lamp.fjbg;
+
+import java.io.DataInputStream;
+import java.io.IOException;
+
+/**
+ * Java class field.
+ *
+ * @author Michel Schinz
+ * @version 1.0
+ */
+
+public class JField extends JFieldOrMethod {
+    protected JField(FJBGContext context,
+                     JClass owner,
+                     int accessFlags,
+                     String name,
+                     JType type) {
+        super(context, owner, accessFlags, name, type);
+    }
+
+    protected JField(FJBGContext context,
+                     JClass owner,
+                     DataInputStream stream)
+        throws IOException {
+        super(context, owner, stream);
+    }
+}
diff --git a/src/fjbg/ch/epfl/lamp/fjbg/JFieldOrMethod.java b/src/fjbg/ch/epfl/lamp/fjbg/JFieldOrMethod.java
new file mode 100644
index 0000000..fec7310
--- /dev/null
+++ b/src/fjbg/ch/epfl/lamp/fjbg/JFieldOrMethod.java
@@ -0,0 +1,121 @@
+
+package ch.epfl.lamp.fjbg;
+
+import java.io.*;
+
+/**
+ * Abstract superclass for a Java field or method.
+ *
+ * @author Michel Schinz
+ * @version 1.0
+ */
+
+abstract public class JFieldOrMethod extends JMember {
+
+    protected final JClass owner;
+    protected final JType type;
+
+    protected final int nameIndex, signatureIndex;
+
+    protected JFieldOrMethod(FJBGContext context,
+                             JClass owner,
+                             int accessFlags,
+                             String name,
+                             JType type) {
+        super(context, accessFlags, name);
+        this.owner = owner;
+        this.type = type;
+
+        JConstantPool pool = owner.getConstantPool();
+        nameIndex = pool.addUtf8(name);
+        signatureIndex = pool.addUtf8(type.getSignature());
+    }
+
+    protected JFieldOrMethod(FJBGContext context,
+                             JClass owner,
+                             DataInputStream stream)
+        throws IOException {
+        super(context);
+        this.owner = owner;
+        this.accessFlags = stream.readShort();
+        this.nameIndex = stream.readShort();
+        this.name = owner.pool.lookupUtf8(nameIndex);
+        this.signatureIndex = stream.readShort();
+        this.type = JType.parseSignature(owner.pool.lookupUtf8(signatureIndex));
+        this.attributes.addAll(JAttribute.readFrom(context, owner, this, stream));
+    }
+
+    public void freeze() throws JCode.OffsetTooBigException {
+        assert !frozen;
+        frozen = true;
+    }
+
+    public JClass getOwner() { return owner; }
+
+    public JType getType() { return type; }
+
+    public JClass getJClass() { return owner; }
+
+    public boolean isPublic() {
+        return (accessFlags & JAccessFlags.ACC_PUBLIC) != 0;
+    }
+
+    public boolean isPrivate() {
+        return (accessFlags & JAccessFlags.ACC_PRIVATE) != 0;
+    }
+
+    public boolean isProtected() {
+        return (accessFlags & JAccessFlags.ACC_PROTECTED) != 0;
+    }
+
+    public boolean isStatic() {
+        return (accessFlags & JAccessFlags.ACC_STATIC) != 0;
+    }
+
+    public boolean isFinal() {
+        return (accessFlags & JAccessFlags.ACC_FINAL) != 0;
+    }
+
+    public boolean isSuper() {
+        return (accessFlags & JAccessFlags.ACC_SUPER) != 0;
+    }
+
+    public boolean isVolatile() {
+        return (accessFlags & JAccessFlags.ACC_VOLATILE) != 0;
+    }
+
+    public boolean isTransient() {
+        return (accessFlags & JAccessFlags.ACC_TRANSIENT) != 0;
+    }
+
+    public boolean isNative() {
+        return (accessFlags & JAccessFlags.ACC_NATIVE) != 0;
+    }
+
+    public boolean isInterface() {
+        return (accessFlags & JAccessFlags.ACC_INTERFACE) != 0;
+    }
+
+    public boolean isAbstract() {
+        return (accessFlags & JAccessFlags.ACC_ABSTRACT) != 0;
+    }
+
+    public boolean isStrict() {
+        return (accessFlags & JAccessFlags.ACC_STRICT) != 0;
+    }
+
+    public void writeTo(DataOutputStream stream) throws IOException {
+        if (! frozen) {
+            try {
+                freeze();
+            }
+            catch (JCode.OffsetTooBigException e) {
+                throw new Error(e);
+            }
+        }
+        stream.writeShort(accessFlags);
+        stream.writeShort(nameIndex);
+        stream.writeShort(signatureIndex);
+        JAttribute.writeTo(getAttributes(), stream);
+    }
+}
diff --git a/src/fjbg/ch/epfl/lamp/fjbg/JInnerClassesAttribute.java b/src/fjbg/ch/epfl/lamp/fjbg/JInnerClassesAttribute.java
new file mode 100644
index 0000000..614dc1c
--- /dev/null
+++ b/src/fjbg/ch/epfl/lamp/fjbg/JInnerClassesAttribute.java
@@ -0,0 +1,89 @@
+package ch.epfl.lamp.fjbg;
+
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.util.*;
+
+/**
+ * InnerClasses attribute. See section 4.7.5 of the JVM
+ * Specification.
+ * 
+ * @author Iulian Dragos
+ */
+public class JInnerClassesAttribute extends JAttribute {
+	/** InnerClass entries */
+	private Map/*<InnerClassEntry>*/ entries = new LinkedHashMap();
+	
+	/** Constant pool of the current classfile. */
+	private JConstantPool pool;
+	
+    public JInnerClassesAttribute(FJBGContext context,
+            JClass clazz) {
+    	super(context, clazz);
+    	this.pool = clazz.pool;
+    }
+
+    public void addEntry(String inner, String outer, String name, int flags) {
+    	Entry e = new Entry(inner, outer, name, flags);
+    	if (entries.containsKey(inner)) {
+    		Entry other = (Entry) entries.get(inner);
+    		assert other.outerInfo == e.outerInfo && other.originalName == e.originalName && other.innerFlags == e.innerFlags
+    			: inner + "already declared as " + other;
+    	} else
+    		entries.put(inner, e);
+    }
+    
+    public String getName() { return "InnerClasses"; }
+
+	protected int getSize() {
+		return 2 + entries.size() * 8;
+	}
+
+	protected void writeContentsTo(DataOutputStream stream) throws IOException {
+		stream.writeShort(entries.size());
+		for (Iterator it = entries.values().iterator(); it.hasNext(); ) {
+			Entry e = (Entry)it.next();
+			stream.writeShort(e.innerInfo);
+			stream.writeShort(e.outerInfo);
+			stream.writeShort(e.originalName);
+			stream.writeShort(e.innerFlags);
+		}
+	}
+
+	/** An entry in the InnerClasses attribute, as defined by the JVM Spec. */
+	private class Entry {
+		/** CONSTANT_Class_info index in the pool for the inner class (mangled). */
+		int innerInfo;
+		
+		/** CONSTANT_Class_info index in the pool for the outer class (mangled). */
+		int outerInfo;
+		
+		/** CONSTANT_Utf8_info index in the pool for the original name of the inner class. */
+		int originalName;
+		
+		/** Short int for modifier flags. */
+		int innerFlags;
+		
+		public Entry(int iI, int oI, int oN, int f) {
+			this.innerInfo = iI;
+			this.outerInfo = oI;
+			this.originalName = oN;
+			this.innerFlags = f;
+		}
+		
+		public Entry(String innerClass, String outerClass, String name, int flags) {
+			this(pool.addClass(innerClass),pool.addClass(outerClass), pool.addUtf8(name), flags);
+		}
+		
+		/** Two entries are equal if they refer to the same inner class.
+		 *  innerInfo represents a unique name (mangled). 
+		 */
+		public boolean equals(Object other) {
+			if (other instanceof Entry) {
+				Entry otherEntry = (Entry) other;
+				return otherEntry.innerInfo == this.innerInfo;
+			}
+			return false;
+		}
+	}
+}
diff --git a/src/fjbg/ch/epfl/lamp/fjbg/JLabel.java b/src/fjbg/ch/epfl/lamp/fjbg/JLabel.java
new file mode 100644
index 0000000..39d7147
--- /dev/null
+++ b/src/fjbg/ch/epfl/lamp/fjbg/JLabel.java
@@ -0,0 +1,26 @@
+
+package ch.epfl.lamp.fjbg;
+
+/**
+ * Labels which can be attached to instructions.
+ *
+ * @version 1.0
+ * @author Michel Schinz
+ */
+
+public class JLabel {
+    public final static int UNDEFINED_ANCHOR = -1;
+    protected int anchor = UNDEFINED_ANCHOR;
+
+    public boolean isAnchored() { return anchor != UNDEFINED_ANCHOR; }
+
+    public int getAnchor() {
+	assert isAnchored();
+        return anchor;
+    }
+
+    public void setAnchor(int anchor) {
+	assert !isAnchored();
+        this.anchor = anchor;
+    }
+}
diff --git a/src/fjbg/ch/epfl/lamp/fjbg/JLineNumberTableAttribute.java b/src/fjbg/ch/epfl/lamp/fjbg/JLineNumberTableAttribute.java
new file mode 100644
index 0000000..1403c34
--- /dev/null
+++ b/src/fjbg/ch/epfl/lamp/fjbg/JLineNumberTableAttribute.java
@@ -0,0 +1,98 @@
+
+package ch.epfl.lamp.fjbg;
+
+import java.io.DataOutputStream;
+import java.io.DataInputStream;
+import java.io.IOException;
+
+/**
+ * Attribute storing correspondance between instructions and source
+ * line numbers.
+ *
+ * @version 1.0
+ * @author Michel Schinz
+ */
+
+public class JLineNumberTableAttribute extends JAttribute {
+    protected final JCode code;
+
+    public JLineNumberTableAttribute(FJBGContext context,
+                                     JClass clazz,
+                                     JCode owner) {
+        super(context, clazz);
+        this.code = owner;
+
+        assert owner.getOwner().getOwner() == clazz;
+    }
+
+    public JLineNumberTableAttribute(FJBGContext context,
+                                     JClass clazz,
+                                     Object owner,
+                                     String name,
+                                     int size,
+                                     DataInputStream stream)
+        throws IOException {
+        super(context, clazz);
+        code = (JCode)owner;
+
+        int[] mapping = new int[code.getSize()];
+
+        int count = stream.readShort();
+        for (int i = 0; i < count; ++i) {
+            int startPC = stream.readShort();
+            int lineNum = stream.readShort();
+            mapping[startPC] = lineNum;
+        }
+
+        int lineNum = 0;
+        for (int pc = 0; pc < mapping.length; ++pc) {
+            if (mapping[pc] != 0) lineNum = mapping[pc];
+            if (lineNum != 0) code.setLineNumber(pc, lineNum);
+        }
+
+        assert name.equals(getName());
+    }
+
+    public String getName() { return "LineNumberTable"; }
+
+    protected int[] encoding;
+    protected int[] encode() {
+        if (encoding == null) {
+            int[] lineNumbers = code.getLineNumbers();
+            int[] preEncoding = new int[lineNumbers.length * 2];
+            int prevLineNum = 0;
+
+            int i = 0;
+            for (int pc = 0; pc < lineNumbers.length; ++pc) {
+                int lineNum = lineNumbers[pc];
+                if (lineNum != 0 & lineNum != prevLineNum) {
+                    preEncoding[i++] = pc;
+                    preEncoding[i++] = lineNum;
+                    prevLineNum = lineNum;
+                }
+            }
+            if (i == preEncoding.length)
+                encoding = preEncoding;
+            else {
+                encoding = new int[i];
+                System.arraycopy(preEncoding, 0, encoding, 0, i);
+            }
+        }
+        return encoding;
+    }
+
+    protected int getSize() {
+        int[] encoding = encode();
+        return 2 + encoding.length * 2;
+    }
+
+    protected void writeContentsTo(DataOutputStream stream) throws IOException {
+        int[] encoding = encode();
+        int entries = encoding.length / 2;
+        stream.writeShort(entries);
+        for (int i = 0; i < entries; ++i) {
+            stream.writeShort(encoding[i * 2]);
+            stream.writeShort(encoding[i * 2 + 1]);
+        }
+    }
+}
diff --git a/src/fjbg/ch/epfl/lamp/fjbg/JLocalVariable.java b/src/fjbg/ch/epfl/lamp/fjbg/JLocalVariable.java
new file mode 100644
index 0000000..9cbc8bb
--- /dev/null
+++ b/src/fjbg/ch/epfl/lamp/fjbg/JLocalVariable.java
@@ -0,0 +1,34 @@
+
+package ch.epfl.lamp.fjbg;
+
+/**
+ * Representation of a local variable or method argument.
+ *
+ * @version 1.0
+ * @author Michel Schinz
+ */
+
+public class JLocalVariable {
+    protected final JMethod owner;
+    protected final JType type;
+    protected final String name;
+    protected final int index;
+
+    protected JLocalVariable(FJBGContext context,
+                             JMethod owner,
+                             JType type,
+                             String name,
+                             int index) {
+        this.owner = owner;
+	this.type = type;
+        this.name = name;
+        this.index = index;
+
+        assert index < 0xFFFF : "index too big for local variable: " + index;
+    }
+
+    public JMethod getOwner() { return owner; }
+    public int getIndex() { return index; }
+    public String getName() { return name; }
+    public JType getType() { return type; }
+}
diff --git a/src/fjbg/ch/epfl/lamp/fjbg/JMember.java b/src/fjbg/ch/epfl/lamp/fjbg/JMember.java
new file mode 100644
index 0000000..8d082fb
--- /dev/null
+++ b/src/fjbg/ch/epfl/lamp/fjbg/JMember.java
@@ -0,0 +1,98 @@
+
+package ch.epfl.lamp.fjbg;
+
+import java.util.List;
+import java.util.LinkedList;
+import java.util.Iterator;
+
+/**
+ * Abstract superclass for a Java class, field or method.
+ *
+ * @author Nikolay Mihaylov
+ * @version 1.0
+ */
+
+abstract public class JMember {
+
+    protected boolean frozen = false;
+
+    protected final FJBGContext context;
+
+    protected String name;
+
+    protected int accessFlags;
+
+    protected final List/*<JAttribute>*/ attributes = new LinkedList();
+
+    protected JMember(FJBGContext context) { this.context = context; }
+
+    protected JMember(FJBGContext context, int accessFlags, String name) {
+        this(context);
+        this.name = name;
+        this.accessFlags = accessFlags;
+    }
+
+    /**
+     * Gets the access flags of the class.
+     * @return The int representing the access flags of the class.
+     */
+    public int getAccessFlags() { return accessFlags; }
+
+    /**
+     * Gets the name of the member.
+     * @return The string representing the name of the member.
+     */
+    public String getName() { return name; }
+
+    /**
+     * Gets the type of the objects that are instances of the class.
+     * @return The type of the instances of the class.
+     */
+    public abstract JType getType();
+
+    /**
+     * Gets the class corresponding to/owning this member
+     * @return The class owning this member or the class itself.
+     */
+    public abstract JClass getJClass();
+
+    /**
+     * Gets the constant pool of the class.
+     * @return The constant pool of the class.
+     */
+    public JConstantPool getConstantPool() { return getJClass().getConstantPool(); }
+
+    public FJBGContext getContext() { return context; }
+
+    /**
+     * Adds an attribute to the class.
+     * @param attr The attribute to be added.
+     */
+    public void addAttribute(JAttribute attr) {
+        assert !frozen;
+        attributes.add(attr);
+    }
+
+    /**
+     * Gets the list of all attributes of the class.
+     * @return The list of the attributes of the class representation.
+     */
+    public List/*<JAttribute>*/ getAttributes() {
+        return attributes;
+    }
+
+    /**
+     * Get the attribute with the given name, or null if it doesn't
+     * exist.
+     */
+    public JAttribute getAttribute(String name) {
+        Iterator attrIt = getAttributes().iterator();
+        while (attrIt.hasNext()) {
+            JAttribute attr = (JAttribute)attrIt.next();
+            if (attr.getName().equals(name))
+                return attr;
+        }
+        return null;
+    }
+
+}
diff --git a/src/fjbg/ch/epfl/lamp/fjbg/JMethod.java b/src/fjbg/ch/epfl/lamp/fjbg/JMethod.java
new file mode 100644
index 0000000..804b431
--- /dev/null
+++ b/src/fjbg/ch/epfl/lamp/fjbg/JMethod.java
@@ -0,0 +1,132 @@
+
+package ch.epfl.lamp.fjbg;
+
+import java.util.LinkedList;
+import java.util.Iterator;
+import java.io.DataInputStream;
+import java.io.IOException;
+
+/**
+ * Representation of a Java method.
+ *
+ * @version 1.0
+ * @author Michel Schinz
+ */
+
+public class JMethod extends JFieldOrMethod {
+    public final static String CLASS_CONSTRUCTOR_NAME = "<clinit>";
+    public final static String INSTANCE_CONSTRUCTOR_NAME = "<init>";
+
+    protected final JCode code;
+    protected final String[] argNames;
+
+    protected final LinkedList/*<JLocalVariable>*/ localVariables =
+        new LinkedList();
+    protected int localVariableIndex = 0;
+
+    protected JMethod(FJBGContext context,
+                      JClass owner,
+                      int accessFlags,
+                      String name,
+                      JType returnType,
+                      JType[] argTypes,
+                      String[] argNames) {
+        super(context,
+              owner,
+              accessFlags,
+              name,
+              new JMethodType(returnType, argTypes));
+        this.argNames = argNames;
+
+        assert argTypes.length == argNames.length;
+
+        if (isAbstract() || isNative()) {
+            code = null;
+        } else {
+            JConstantPool pool = owner.getConstantPool();
+            code = context.JCode(owner, this);
+            addAttribute(context.JCodeAttribute(owner, this));
+
+            if (!isStatic())
+                addNewLocalVariable(owner.getType(), "this");
+
+            for (int i = 0; i < argTypes.length; ++i)
+                addNewLocalVariable(argTypes[i], argNames[i]);
+        }
+    }
+
+    protected JMethod(FJBGContext context,
+                      JClass owner,
+                      DataInputStream stream)
+        throws IOException {
+        super(context, owner, stream);
+
+        // Fetch code from the attributes.
+        setCode: {
+            Iterator attrIt = attributes.iterator();
+            while (attrIt.hasNext()) {
+                Object attr = attrIt.next();
+                if (attr instanceof JCodeAttribute) {
+                    code = ((JCodeAttribute)attr).code;
+                    break setCode;
+                }
+            }
+            code = null;
+        }
+        argNames = null;        // TODO get from attribute
+    }
+
+    public void freeze() throws JCode.OffsetTooBigException {
+        if (code != null) code.freeze();
+        super.freeze();
+    }
+
+    public JType getReturnType() {
+        return ((JMethodType)type).getReturnType();
+    }
+
+    public JType[] getArgumentTypes() {
+        return ((JMethodType)type).getArgumentTypes();
+    }
+
+    public String[] getArgumentNames() {
+        return argNames;
+    }
+
+    public JCode getCode() {
+        assert !isAbstract();
+        return code;
+    }
+
+    public JCodeIterator codeIterator() {
+        return new JCodeIterator(code);
+    }
+
+    // Local variables
+    // FIXME : find a better management method for local variables
+    public JLocalVariable addNewLocalVariable(JType type, String name) {
+        assert !frozen;
+        JLocalVariable var =
+            context.JLocalVariable(this, type, name, localVariableIndex);
+        localVariableIndex += type.getSize();
+        localVariables.add(var);
+        return var;
+    }
+
+    public JLocalVariable getLocalVariable(int index) {
+        for (int i = 0; i < localVariables.size(); i++) {
+            if (((JLocalVariable)localVariables.get(i)).index == index)
+                return (JLocalVariable)localVariables.get(i);
+        }
+        return null;
+    }
+
+    public JLocalVariable[] getLocalVariables() {
+        return (JLocalVariable[])localVariables
+            .toArray(new JLocalVariable[localVariables.size()]);
+    }
+
+    public int getMaxLocals() {
+        return localVariableIndex;
+    }
+}
diff --git a/src/fjbg/ch/epfl/lamp/fjbg/JMethodType.java b/src/fjbg/ch/epfl/lamp/fjbg/JMethodType.java
new file mode 100644
index 0000000..ec44967
--- /dev/null
+++ b/src/fjbg/ch/epfl/lamp/fjbg/JMethodType.java
@@ -0,0 +1,71 @@
+
+package ch.epfl.lamp.fjbg;
+
+/**
+ * Type for Java methods. These types do not really exist in Java, but
+ * are provided here because they are useful in several places.
+ *
+ * @version 1.0
+ * @author Michel Schinz
+ */
+
+public class JMethodType extends JType {
+    protected final JType returnType;
+    protected final JType[] argTypes;
+    protected String signature = null;
+
+    public final static JMethodType ARGLESS_VOID_FUNCTION =
+        new JMethodType(JType.VOID, JType.EMPTY_ARRAY);
+
+    public JMethodType(JType returnType, JType[] argTypes) {
+        this.returnType = returnType;
+        this.argTypes = argTypes;
+    }
+
+    public JType getReturnType() { return returnType; }
+    public JType[] getArgumentTypes() { return argTypes; }
+
+    public int getSize() {
+        throw new UnsupportedOperationException();
+    }
+
+    public String getSignature() {
+        if (signature == null) {
+            StringBuffer buf = new StringBuffer();
+            buf.append('(');
+            for (int i = 0; i < argTypes.length; ++i)
+                buf.append(argTypes[i].getSignature());
+            buf.append(')');
+            buf.append(returnType.getSignature());
+            signature = buf.toString();
+        }
+        return signature;
+    }
+
+    public int getTag() { return T_UNKNOWN; }
+
+    public String toString() {
+        StringBuffer buf = new StringBuffer();
+        buf.append('(');
+        for (int i = 0; i < argTypes.length; ++i)
+            buf.append(argTypes[i].toString());
+        buf.append(')');
+        buf.append(returnType.toString());
+        return buf.toString();
+    }
+
+    public int getArgsSize() {
+        int size = 0;
+        for (int i = 0; i < argTypes.length; ++i)
+            size += argTypes[i].getSize();
+        return size;
+    }
+
+    public int getProducedStack() {
+        return returnType.getSize() - getArgsSize();
+    }
+
+    public boolean isCompatibleWith(JType other) {
+        return false;
+    }
+}
diff --git a/src/fjbg/ch/epfl/lamp/fjbg/JObjectType.java b/src/fjbg/ch/epfl/lamp/fjbg/JObjectType.java
new file mode 100644
index 0000000..b4edb86
--- /dev/null
+++ b/src/fjbg/ch/epfl/lamp/fjbg/JObjectType.java
@@ -0,0 +1,52 @@
+
+package ch.epfl.lamp.fjbg;
+
+/**
+ * Types for Java objects.
+ *
+ * @version 1.0
+ * @author Michel Schinz
+ */
+
+public class JObjectType extends JReferenceType {
+    protected final String name;
+    protected String signature = null;
+
+    public final static JObjectType JAVA_LANG_OBJECT =
+        new JObjectType("java.lang.Object");
+    public final static JObjectType JAVA_LANG_STRING =
+        new JObjectType("java.lang.String");
+    public final static JObjectType CLONEABLE =
+        new JObjectType("Cloneable");
+    public final static JObjectType JAVA_IO_SERIALIZABLE =
+        new JObjectType("java.io.Serializable");
+
+    public JObjectType(String name) {
+        this.name = name;
+    }
+
+    public int getSize() { return 1; }
+
+    public String getName() { return name; }
+
+    public String getSignature() {
+        if (signature == null)
+            signature = "L" + name.replace('.','/') + ";";
+        return signature;
+    }
+
+    public String getDescriptor() {
+        return name.replace('.','/');
+    }
+
+    public int getTag() { return T_OBJECT; }
+
+    public String toString() { return name; }
+
+    public boolean isObjectType() { return true; }
+
+    public boolean isCompatibleWith(JType other) {
+        return other instanceof JObjectType
+            || other == JType.REFERENCE;
+    }
+}
diff --git a/src/fjbg/ch/epfl/lamp/fjbg/JOpcode.java b/src/fjbg/ch/epfl/lamp/fjbg/JOpcode.java
new file mode 100644
index 0000000..f7ee688
--- /dev/null
+++ b/src/fjbg/ch/epfl/lamp/fjbg/JOpcode.java
@@ -0,0 +1,1263 @@
+
+package ch.epfl.lamp.fjbg;
+
+/**
+ * Definition of opcodes for the JVM.
+ *
+ * @author Michel Schinz, Thomas Friedli
+ * @version 1.0
+ */
+
+public class JOpcode {
+    public final String name;
+    public final int code;
+
+    // The following attributes can be (statically) unknown for some
+    // instructions, and are therefore not public. To know their value,
+    // functions have to be used (see JCodeIterator).
+    protected final int size;
+    protected final JType[] producedDataTypes;
+    protected final JType[] consumedDataTypes;
+    protected final int jumpKind;
+    protected final int successorCount;
+
+    protected final static int UNKNOWN = Integer.MIN_VALUE;
+
+    protected final static int JMP_NONE             = 0;
+    protected final static int JMP_NEXT             = 1;
+    protected final static int JMP_ALWAYS_S2_OFFSET = 2;
+    protected final static int JMP_ALWAYS_S4_OFFSET = 3;
+    protected final static int JMP_MAYBE_S2_OFFSET  = 4;
+    protected final static int JMP_TABLE            = 5;
+    protected final static int JMP_LOOKUP           = 6;
+
+    protected final static JType[] NO_DATA = new JType[0];
+
+    protected final static JType[] INT_TYPE =
+        new JType[] { JType.INT };
+    protected final static JType[] FLOAT_TYPE =
+        new JType[] { JType.FLOAT };
+    protected final static JType[] LONG_TYPE =
+        new JType[] { JType.LONG };
+    protected final static JType[] DOUBLE_TYPE =
+        new JType[] { JType.DOUBLE };
+    protected final static JType[] OBJECT_REF_TYPE =
+        new JType[] { JObjectType.JAVA_LANG_OBJECT };
+    protected final static JType[] ARRAY_REF_TYPE =
+        new JType[] { new JArrayType(JType.VOID) };
+    protected final static JType[] REFERENCE_TYPE =
+        new JType[] { JType.REFERENCE };
+    protected final static JType[] ADDRESS_TYPE =
+        new JType[] { JType.ADDRESS };
+    protected final static JType[] UNKNOWN_TYPE =
+        new JType[] { JType.UNKNOWN };
+
+    /// Instruction codes
+    public final static int cNOP             = 0;
+    public final static int cACONST_NULL     = 1;
+    public final static int cICONST_M1       = 2;
+    public final static int cICONST_0        = 3;
+    public final static int cICONST_1        = 4;
+    public final static int cICONST_2        = 5;
+    public final static int cICONST_3        = 6;
+    public final static int cICONST_4        = 7;
+    public final static int cICONST_5        = 8;
+    public final static int cLCONST_0        = 9;
+    public final static int cLCONST_1        = 10;
+    public final static int cFCONST_0        = 11;
+    public final static int cFCONST_1        = 12;
+    public final static int cFCONST_2        = 13;
+    public final static int cDCONST_0        = 14;
+    public final static int cDCONST_1        = 15;
+    public final static int cBIPUSH          = 16;
+    public final static int cSIPUSH          = 17;
+    public final static int cLDC             = 18;
+    public final static int cLDC_W           = 19;
+    public final static int cLDC2_W          = 20;
+    public final static int cILOAD           = 21;
+    public final static int cLLOAD           = 22;
+    public final static int cFLOAD           = 23;
+    public final static int cDLOAD           = 24;
+    public final static int cALOAD           = 25;
+    public final static int cILOAD_0         = 26;
+    public final static int cILOAD_1         = 27;
+    public final static int cILOAD_2         = 28;
+    public final static int cILOAD_3         = 29;
+    public final static int cLLOAD_0         = 30;
+    public final static int cLLOAD_1         = 31;
+    public final static int cLLOAD_2         = 32;
+    public final static int cLLOAD_3         = 33;
+    public final static int cFLOAD_0         = 34;
+    public final static int cFLOAD_1         = 35;
+    public final static int cFLOAD_2         = 36;
+    public final static int cFLOAD_3         = 37;
+    public final static int cDLOAD_0         = 38;
+    public final static int cDLOAD_1         = 39;
+    public final static int cDLOAD_2         = 40;
+    public final static int cDLOAD_3         = 41;
+    public final static int cALOAD_0         = 42;
+    public final static int cALOAD_1         = 43;
+    public final static int cALOAD_2         = 44;
+    public final static int cALOAD_3         = 45;
+    public final static int cIALOAD          = 46;
+    public final static int cLALOAD          = 47;
+    public final static int cFALOAD          = 48;
+    public final static int cDALOAD          = 49;
+    public final static int cAALOAD          = 50;
+    public final static int cBALOAD          = 51;
+    public final static int cCALOAD          = 52;
+    public final static int cSALOAD          = 53;
+    public final static int cISTORE          = 54;
+    public final static int cLSTORE          = 55;
+    public final static int cFSTORE          = 56;
+    public final static int cDSTORE          = 57;
+    public final static int cASTORE          = 58;
+    public final static int cISTORE_0        = 59;
+    public final static int cISTORE_1        = 60;
+    public final static int cISTORE_2        = 61;
+    public final static int cISTORE_3        = 62;
+    public final static int cLSTORE_0        = 63;
+    public final static int cLSTORE_1        = 64;
+    public final static int cLSTORE_2        = 65;
+    public final static int cLSTORE_3        = 66;
+    public final static int cFSTORE_0        = 67;
+    public final static int cFSTORE_1        = 68;
+    public final static int cFSTORE_2        = 69;
+    public final static int cFSTORE_3        = 70;
+    public final static int cDSTORE_0        = 71;
+    public final static int cDSTORE_1        = 72;
+    public final static int cDSTORE_2        = 73;
+    public final static int cDSTORE_3        = 74;
+    public final static int cASTORE_0        = 75;
+    public final static int cASTORE_1        = 76;
+    public final static int cASTORE_2        = 77;
+    public final static int cASTORE_3        = 78;
+    public final static int cIASTORE         = 79;
+    public final static int cLASTORE         = 80;
+    public final static int cFASTORE         = 81;
+    public final static int cDASTORE         = 82;
+    public final static int cAASTORE         = 83;
+    public final static int cBASTORE         = 84;
+    public final static int cCASTORE         = 85;
+    public final static int cSASTORE         = 86;
+    public final static int cPOP             = 87;
+    public final static int cPOP2            = 88;
+    public final static int cDUP             = 89;
+    public final static int cDUP_X1          = 90;
+    public final static int cDUP_X2          = 91;
+    public final static int cDUP2            = 92;
+    public final static int cDUP2_X1         = 93;
+    public final static int cDUP2_X2         = 94;
+    public final static int cSWAP            = 95;
+    public final static int cIADD            = 96;
+    public final static int cLADD            = 97;
+    public final static int cFADD            = 98;
+    public final static int cDADD            = 99;
+    public final static int cISUB            = 100;
+    public final static int cLSUB            = 101;
+    public final static int cFSUB            = 102;
+    public final static int cDSUB            = 103;
+    public final static int cIMUL            = 104;
+    public final static int cLMUL            = 105;
+    public final static int cFMUL            = 106;
+    public final static int cDMUL            = 107;
+    public final static int cIDIV            = 108;
+    public final static int cLDIV            = 109;
+    public final static int cFDIV            = 110;
+    public final static int cDDIV            = 111;
+    public final static int cIREM            = 112;
+    public final static int cLREM            = 113;
+    public final static int cFREM            = 114;
+    public final static int cDREM            = 115;
+    public final static int cINEG            = 116;
+    public final static int cLNEG            = 117;
+    public final static int cFNEG            = 118;
+    public final static int cDNEG            = 119;
+    public final static int cISHL            = 120;
+    public final static int cLSHL            = 121;
+    public final static int cISHR            = 122;
+    public final static int cLSHR            = 123;
+    public final static int cIUSHR           = 124;
+    public final static int cLUSHR           = 125;
+    public final static int cIAND            = 126;
+    public final static int cLAND            = 127;
+    public final static int cIOR             = 128;
+    public final static int cLOR             = 129;
+    public final static int cIXOR            = 130;
+    public final static int cLXOR            = 131;
+    public final static int cIINC            = 132;
+    public final static int cI2L             = 133;
+    public final static int cI2F             = 134;
+    public final static int cI2D             = 135;
+    public final static int cL2I             = 136;
+    public final static int cL2F             = 137;
+    public final static int cL2D             = 138;
+    public final static int cF2I             = 139;
+    public final static int cF2L             = 140;
+    public final static int cF2D             = 141;
+    public final static int cD2I             = 142;
+    public final static int cD2L             = 143;
+    public final static int cD2F             = 144;
+    public final static int cI2B             = 145;
+    public final static int cI2C             = 146;
+    public final static int cI2S             = 147;
+    public final static int cLCMP            = 148;
+    public final static int cFCMPL           = 149;
+    public final static int cFCMPG           = 150;
+    public final static int cDCMPL           = 151;
+    public final static int cDCMPG           = 152;
+    public final static int cIFEQ            = 153;
+    public final static int cIFNE            = 154;
+    public final static int cIFLT            = 155;
+    public final static int cIFGE            = 156;
+    public final static int cIFGT            = 157;
+    public final static int cIFLE            = 158;
+    public final static int cIF_ICMPEQ       = 159;
+    public final static int cIF_ICMPNE       = 160;
+    public final static int cIF_ICMPLT       = 161;
+    public final static int cIF_ICMPGE       = 162;
+    public final static int cIF_ICMPGT       = 163;
+    public final static int cIF_ICMPLE       = 164;
+    public final static int cIF_ACMPEQ       = 165;
+    public final static int cIF_ACMPNE       = 166;
+    public final static int cGOTO            = 167;
+    public final static int cJSR             = 168;
+    public final static int cRET             = 169;
+    public final static int cTABLESWITCH     = 170;
+    public final static int cLOOKUPSWITCH    = 171;
+    public final static int cIRETURN         = 172;
+    public final static int cLRETURN         = 173;
+    public final static int cFRETURN         = 174;
+    public final static int cDRETURN         = 175;
+    public final static int cARETURN         = 176;
+    public final static int cRETURN          = 177;
+    public final static int cGETSTATIC       = 178;
+    public final static int cPUTSTATIC       = 179;
+    public final static int cGETFIELD        = 180;
+    public final static int cPUTFIELD        = 181;
+    public final static int cINVOKEVIRTUAL   = 182;
+    public final static int cINVOKESPECIAL   = 183;
+    public final static int cINVOKESTATIC    = 184;
+    public final static int cINVOKEINTERFACE = 185;
+    public final static int cNEW             = 187;
+    public final static int cNEWARRAY        = 188;
+    public final static int cANEWARRAY       = 189;
+    public final static int cARRAYLENGTH     = 190;
+    public final static int cATHROW          = 191;
+    public final static int cCHECKCAST       = 192;
+    public final static int cINSTANCEOF      = 193;
+    public final static int cMONITORENTER    = 194;
+    public final static int cMONITOREXIT     = 195;
+    public final static int cWIDE            = 196;
+    public final static int cMULTIANEWARRAY  = 197;
+    public final static int cIFNULL          = 198;
+    public final static int cIFNONNULL       = 199;
+    public final static int cGOTO_W          = 200;
+    public final static int cJSR_W           = 201;
+
+    // Objects representing instructions
+    public final static JOpcode NOP =
+        new JOpcode("NOP", cNOP, 1, NO_DATA, NO_DATA, JMP_NEXT);
+    public final static JOpcode ACONST_NULL = new JOpcode("ACONST_NULL",
+                                                          cACONST_NULL,
+                                                          1,
+                                                          REFERENCE_TYPE,
+                                                          NO_DATA,
+                                                          JMP_NEXT);
+    public final static JOpcode ICONST_M1 =
+        new JOpcode("ICONST_M1", cICONST_M1, 1, INT_TYPE, NO_DATA, JMP_NEXT);
+    public final static JOpcode ICONST_0 =
+        new JOpcode("ICONST_0", cICONST_0, 1, INT_TYPE, NO_DATA, JMP_NEXT);
+    public final static JOpcode ICONST_1 =
+        new JOpcode("ICONST_1", cICONST_1, 1, INT_TYPE, NO_DATA, JMP_NEXT);
+    public final static JOpcode ICONST_2 =
+        new JOpcode("ICONST_2", cICONST_2, 1, INT_TYPE, NO_DATA, JMP_NEXT);
+    public final static JOpcode ICONST_3 =
+        new JOpcode("ICONST_3", cICONST_3, 1, INT_TYPE, NO_DATA, JMP_NEXT);
+    public final static JOpcode ICONST_4 =
+        new JOpcode("ICONST_4", cICONST_4, 1, INT_TYPE, NO_DATA, JMP_NEXT);
+    public final static JOpcode ICONST_5 =
+        new JOpcode("ICONST_5", cICONST_5, 1, INT_TYPE, NO_DATA, JMP_NEXT);
+    public final static JOpcode LCONST_0 =
+        new JOpcode("LCONST_0", cLCONST_0, 1, LONG_TYPE, NO_DATA, JMP_NEXT);
+    public final static JOpcode LCONST_1 =
+        new JOpcode("LCONST_1", cLCONST_1, 1, LONG_TYPE, NO_DATA, JMP_NEXT);
+    public final static JOpcode FCONST_0 =
+        new JOpcode("FCONST_0", cFCONST_0, 1, FLOAT_TYPE, NO_DATA, JMP_NEXT);
+    public final static JOpcode FCONST_1 =
+        new JOpcode("FCONST_1", cFCONST_1, 1, FLOAT_TYPE, NO_DATA, JMP_NEXT);
+    public final static JOpcode FCONST_2 =
+        new JOpcode("FCONST_2", cFCONST_2, 1, FLOAT_TYPE, NO_DATA, JMP_NEXT);
+    public final static JOpcode DCONST_0 =
+        new JOpcode("DCONST_0", cDCONST_0, 1, DOUBLE_TYPE, NO_DATA, JMP_NEXT);
+    public final static JOpcode DCONST_1 =
+        new JOpcode("DCONST_1", cDCONST_1, 1, DOUBLE_TYPE, NO_DATA, JMP_NEXT);
+    public final static JOpcode BIPUSH =
+        new JOpcode("BIPUSH", cBIPUSH, 2, INT_TYPE, NO_DATA, JMP_NEXT);
+    public final static JOpcode SIPUSH =
+        new JOpcode("SIPUSH", cSIPUSH, 3, INT_TYPE, NO_DATA, JMP_NEXT);
+    public final static JOpcode LDC =
+        new JOpcode("LDC", cLDC, 2, UNKNOWN_TYPE, NO_DATA, JMP_NEXT);
+    public final static JOpcode LDC_W =
+        new JOpcode("LDC_W", cLDC_W, 3, UNKNOWN_TYPE, NO_DATA, JMP_NEXT);
+    public final static JOpcode LDC2_W =
+        new JOpcode("LDC2_W", cLDC2_W, 3, UNKNOWN_TYPE, NO_DATA, JMP_NEXT);
+    public final static JOpcode ILOAD =
+        new JOpcode("ILOAD", cILOAD, 2, INT_TYPE, NO_DATA, JMP_NEXT);
+    public final static JOpcode LLOAD =
+        new JOpcode("LLOAD", cLLOAD, 2, LONG_TYPE, NO_DATA, JMP_NEXT);
+    public final static JOpcode FLOAD =
+        new JOpcode("FLOAD", cFLOAD, 2, FLOAT_TYPE, NO_DATA, JMP_NEXT);
+    public final static JOpcode DLOAD =
+        new JOpcode("DLOAD", cDLOAD, 2, DOUBLE_TYPE, NO_DATA, JMP_NEXT);
+    public final static JOpcode ALOAD =
+        new JOpcode("ALOAD", cALOAD, 2, REFERENCE_TYPE, NO_DATA, JMP_NEXT);
+    public final static JOpcode ILOAD_0 =
+        new JOpcode("ILOAD_0", cILOAD_0, 1, INT_TYPE, NO_DATA, JMP_NEXT);
+    public final static JOpcode ILOAD_1 =
+        new JOpcode("ILOAD_1", cILOAD_1, 1, INT_TYPE, NO_DATA, JMP_NEXT);
+    public final static JOpcode ILOAD_2 =
+        new JOpcode("ILOAD_2", cILOAD_2, 1, INT_TYPE, NO_DATA, JMP_NEXT);
+    public final static JOpcode ILOAD_3 =
+        new JOpcode("ILOAD_3", cILOAD_3, 1, INT_TYPE, NO_DATA, JMP_NEXT);
+    public final static JOpcode LLOAD_0 =
+        new JOpcode("LLOAD_0", cLLOAD_0, 1, LONG_TYPE, NO_DATA, JMP_NEXT);
+    public final static JOpcode LLOAD_1 =
+        new JOpcode("LLOAD_1", cLLOAD_1, 1, LONG_TYPE, NO_DATA, JMP_NEXT);
+    public final static JOpcode LLOAD_2 =
+        new JOpcode("LLOAD_2", cLLOAD_2, 1, LONG_TYPE, NO_DATA, JMP_NEXT);
+    public final static JOpcode LLOAD_3 =
+        new JOpcode("LLOAD_3", cLLOAD_3, 1, LONG_TYPE, NO_DATA, JMP_NEXT);
+    public final static JOpcode FLOAD_0 =
+        new JOpcode("FLOAD_0", cFLOAD_0, 1, FLOAT_TYPE, NO_DATA, JMP_NEXT);
+    public final static JOpcode FLOAD_1 =
+        new JOpcode("FLOAD_1", cFLOAD_1, 1, FLOAT_TYPE, NO_DATA, JMP_NEXT);
+    public final static JOpcode FLOAD_2 =
+        new JOpcode("FLOAD_2", cFLOAD_2, 1, FLOAT_TYPE, NO_DATA, JMP_NEXT);
+    public final static JOpcode FLOAD_3 =
+        new JOpcode("FLOAD_3", cFLOAD_3, 1, FLOAT_TYPE, NO_DATA, JMP_NEXT);
+    public final static JOpcode DLOAD_0 =
+        new JOpcode("DLOAD_0", cDLOAD_0, 1, DOUBLE_TYPE, NO_DATA, JMP_NEXT);
+    public final static JOpcode DLOAD_1 =
+        new JOpcode("DLOAD_1", cDLOAD_1, 1, DOUBLE_TYPE, NO_DATA, JMP_NEXT);
+    public final static JOpcode DLOAD_2 =
+        new JOpcode("DLOAD_2", cDLOAD_2, 1, DOUBLE_TYPE, NO_DATA, JMP_NEXT);
+    public final static JOpcode DLOAD_3 =
+        new JOpcode("DLOAD_3", cDLOAD_3, 1, DOUBLE_TYPE, NO_DATA, JMP_NEXT);
+    public final static JOpcode ALOAD_0 =
+        new JOpcode("ALOAD_0", cALOAD_0, 1, REFERENCE_TYPE, NO_DATA, JMP_NEXT);
+    public final static JOpcode ALOAD_1 =
+        new JOpcode("ALOAD_1", cALOAD_1, 1, REFERENCE_TYPE, NO_DATA, JMP_NEXT);
+    public final static JOpcode ALOAD_2 =
+        new JOpcode("ALOAD_2", cALOAD_2, 1, REFERENCE_TYPE, NO_DATA, JMP_NEXT);
+    public final static JOpcode ALOAD_3 =
+        new JOpcode("ALOAD_3", cALOAD_3, 1, REFERENCE_TYPE, NO_DATA, JMP_NEXT);
+    public final static JOpcode IALOAD =
+        new JOpcode("IALOAD",
+                    cIALOAD,
+                    1,
+                    INT_TYPE,
+                    new JType[] {JType.INT, JArrayType.INT},
+                    JMP_NEXT);
+    public final static JOpcode LALOAD =
+        new JOpcode("LALOAD",
+                    cLALOAD,
+                    1,
+                    LONG_TYPE,
+                    new JType[] {JType.INT, JArrayType.LONG},
+                    JMP_NEXT);
+    public final static JOpcode FALOAD =
+        new JOpcode("FALOAD",
+                    cFALOAD,
+                    1,
+                    FLOAT_TYPE,
+                    new JType[] {JType.INT, JArrayType.FLOAT},
+                    JMP_NEXT);
+    public final static JOpcode DALOAD =
+        new JOpcode("DALOAD",
+                    cDALOAD,
+                    1,
+                    DOUBLE_TYPE,
+                    new JType[] {JType.INT, JArrayType.DOUBLE},
+                    JMP_NEXT);
+    public final static JOpcode AALOAD =
+        new JOpcode("AALOAD",
+                    cAALOAD,
+                    1,
+                    REFERENCE_TYPE,
+                    new JType[] {JType.INT, JArrayType.REFERENCE},
+                    JMP_NEXT);
+    public final static JOpcode BALOAD =
+        new JOpcode("BALOAD",
+                    cBALOAD,
+                    1,
+                    INT_TYPE,
+                    new JType[] {JType.INT, new JArrayType(JType.UNKNOWN)},
+                    JMP_NEXT);
+    public final static JOpcode CALOAD =
+        new JOpcode("CALOAD",
+                    cCALOAD,
+                    1,
+                    INT_TYPE,
+                    new JType[] {JType.INT, JArrayType.CHAR},
+                    JMP_NEXT);
+    public final static JOpcode SALOAD =
+        new JOpcode("SALOAD",
+                    cSALOAD,
+                    1,
+                    INT_TYPE,
+                    new JType[] {JType.INT, JArrayType.SHORT},
+                    JMP_NEXT);
+    public final static JOpcode ISTORE =
+        new JOpcode("ISTORE", cISTORE, 2, NO_DATA, INT_TYPE, JMP_NEXT);
+    public final static JOpcode LSTORE =
+        new JOpcode("LSTORE", cLSTORE, 2, NO_DATA, LONG_TYPE, JMP_NEXT);
+    public final static JOpcode FSTORE =
+        new JOpcode("FSTORE", cFSTORE, 2, NO_DATA, FLOAT_TYPE, JMP_NEXT);
+    public final static JOpcode DSTORE =
+        new JOpcode("DSTORE", cDSTORE, 2, NO_DATA, DOUBLE_TYPE, JMP_NEXT);
+    public final static JOpcode ASTORE =
+        new JOpcode("ASTORE", cASTORE, 2, NO_DATA, REFERENCE_TYPE, JMP_NEXT);
+    public final static JOpcode ISTORE_0 =
+        new JOpcode("ISTORE_0", cISTORE_0, 1, NO_DATA, INT_TYPE, JMP_NEXT);
+    public final static JOpcode ISTORE_1 =
+        new JOpcode("ISTORE_1", cISTORE_1, 1, NO_DATA, INT_TYPE, JMP_NEXT);
+    public final static JOpcode ISTORE_2 =
+        new JOpcode("ISTORE_2", cISTORE_2, 1, NO_DATA, INT_TYPE, JMP_NEXT);
+    public final static JOpcode ISTORE_3 =
+        new JOpcode("ISTORE_3", cISTORE_3, 1, NO_DATA, INT_TYPE, JMP_NEXT);
+    public final static JOpcode LSTORE_0 =
+        new JOpcode("LSTORE_0", cLSTORE_0, 1, NO_DATA, LONG_TYPE, JMP_NEXT);
+    public final static JOpcode LSTORE_1 =
+        new JOpcode("LSTORE_1", cLSTORE_1, 1, NO_DATA, LONG_TYPE, JMP_NEXT);
+    public final static JOpcode LSTORE_2 =
+        new JOpcode("LSTORE_2", cLSTORE_2, 1, NO_DATA, LONG_TYPE, JMP_NEXT);
+    public final static JOpcode LSTORE_3 =
+        new JOpcode("LSTORE_3", cLSTORE_3, 1, NO_DATA, LONG_TYPE, JMP_NEXT);
+    public final static JOpcode FSTORE_0 =
+        new JOpcode("FSTORE_0", cFSTORE_0, 1, NO_DATA, FLOAT_TYPE, JMP_NEXT);
+    public final static JOpcode FSTORE_1 =
+        new JOpcode("FSTORE_1", cFSTORE_1, 1, NO_DATA, FLOAT_TYPE, JMP_NEXT);
+    public final static JOpcode FSTORE_2 =
+        new JOpcode("FSTORE_2", cFSTORE_2, 1, NO_DATA, FLOAT_TYPE, JMP_NEXT);
+    public final static JOpcode FSTORE_3 =
+        new JOpcode("FSTORE_3", cFSTORE_3, 1, NO_DATA, FLOAT_TYPE, JMP_NEXT);
+    public final static JOpcode DSTORE_0 =
+        new JOpcode("DSTORE_0", cDSTORE_0, 1, NO_DATA, DOUBLE_TYPE, JMP_NEXT);
+    public final static JOpcode DSTORE_1 =
+        new JOpcode("DSTORE_1", cDSTORE_1, 1, NO_DATA, DOUBLE_TYPE, JMP_NEXT);
+    public final static JOpcode DSTORE_2 =
+        new JOpcode("DSTORE_2", cDSTORE_2, 1, NO_DATA, DOUBLE_TYPE, JMP_NEXT);
+    public final static JOpcode DSTORE_3 =
+        new JOpcode("DSTORE_3", cDSTORE_3, 1, NO_DATA, DOUBLE_TYPE, JMP_NEXT);
+    public final static JOpcode ASTORE_0 = new JOpcode("ASTORE_0",
+                                                       cASTORE_0,
+                                                       1,
+                                                       NO_DATA,
+                                                       REFERENCE_TYPE,
+                                                       JMP_NEXT);
+    public final static JOpcode ASTORE_1 = new JOpcode("ASTORE_1",
+                                                       cASTORE_1,
+                                                       1,
+                                                       NO_DATA,
+                                                       REFERENCE_TYPE,
+                                                       JMP_NEXT);
+    public final static JOpcode ASTORE_2 = new JOpcode("ASTORE_2",
+                                                       cASTORE_2,
+                                                       1,
+                                                       NO_DATA,
+                                                       REFERENCE_TYPE,
+                                                       JMP_NEXT);
+    public final static JOpcode ASTORE_3 = new JOpcode("ASTORE_3",
+                                                       cASTORE_3,
+                                                       1,
+                                                       NO_DATA,
+                                                       REFERENCE_TYPE,
+                                                       JMP_NEXT);
+    public final static JOpcode IASTORE =
+        new JOpcode("IASTORE",
+                    cIASTORE,
+                    1,
+                    NO_DATA,
+                    new JType[] { JType.INT,
+                                  JType.INT,
+                                  JArrayType.INT},
+                    JMP_NEXT);
+    public final static JOpcode LASTORE =
+        new JOpcode("LASTORE",
+                    cLASTORE,
+                    1,
+                    NO_DATA,
+                    new JType[] { JType.LONG,
+                                  JType.INT,
+                                  JArrayType.LONG},
+                    JMP_NEXT);
+    public final static JOpcode FASTORE =
+        new JOpcode("FASTORE",
+                    cFASTORE,
+                    1,
+                    NO_DATA,
+                    new JType[] { JType.FLOAT,
+                                  JType.INT,
+                                  JArrayType.FLOAT},
+                    JMP_NEXT);
+    public final static JOpcode DASTORE =
+        new JOpcode("DASTORE",
+                    cDASTORE,
+                    1,
+                    NO_DATA,
+                    new JType[] { JType.DOUBLE,
+                                  JType.INT,
+                                  JArrayType.DOUBLE},
+                    JMP_NEXT);
+    public final static JOpcode AASTORE =
+        new JOpcode("AASTORE",
+                    cAASTORE,
+                    1,
+                    NO_DATA,
+                    new JType[] { JType.REFERENCE,
+                                  JType.INT,
+                                  JArrayType.REFERENCE},
+                    JMP_NEXT);
+    public final static JOpcode BASTORE =
+        new JOpcode("BASTORE",
+                    cBASTORE,
+                    1,
+                    NO_DATA,
+                    new JType[] { JType.INT,
+                                  JType.INT,
+                                  new JArrayType(JType.UNKNOWN)},
+                    JMP_NEXT);
+    public final static JOpcode CASTORE =
+        new JOpcode("CASTORE",
+                    cCASTORE,
+                    1,
+                    NO_DATA,
+                    new JType[] { JType.INT,
+                                  JType.INT,
+                                  JArrayType.CHAR},
+                    JMP_NEXT);
+    public final static JOpcode SASTORE =
+        new JOpcode("SASTORE",
+                    cSASTORE,
+                    1,
+                    NO_DATA,
+                    new JType[] { JType.INT,
+                                  JType.INT,
+                                  JArrayType.SHORT},
+                    JMP_NEXT);
+    public final static JOpcode POP =
+        new JOpcode("POP", cPOP, 1, NO_DATA, UNKNOWN_TYPE, JMP_NEXT);
+    public final static JOpcode POP2 =
+        new JOpcode("POP2", cPOP2, 1, NO_DATA, UNKNOWN_TYPE, JMP_NEXT);
+    public final static JOpcode DUP =
+        new JOpcode("DUP", cDUP, 1, UNKNOWN_TYPE, UNKNOWN_TYPE, JMP_NEXT);
+    public final static JOpcode DUP_X1 = new JOpcode("DUP_X1",
+                                                     cDUP_X1,
+                                                     1,
+                                                     UNKNOWN_TYPE,
+                                                     UNKNOWN_TYPE,
+                                                     JMP_NEXT);
+    public final static JOpcode DUP_X2 = new JOpcode("DUP_X2",
+                                                     cDUP_X2,
+                                                     1,
+                                                     UNKNOWN_TYPE,
+                                                     UNKNOWN_TYPE,
+                                                     JMP_NEXT);
+    public final static JOpcode DUP2 =
+        new JOpcode("DUP2", cDUP2, 1, UNKNOWN_TYPE, UNKNOWN_TYPE, JMP_NEXT);
+    public final static JOpcode DUP2_X1 = new JOpcode("DUP2_X1",
+                                                      cDUP2_X1,
+                                                      1,
+                                                      UNKNOWN_TYPE,
+                                                      UNKNOWN_TYPE,
+                                                      JMP_NEXT);
+    public final static JOpcode DUP2_X2 = new JOpcode("DUP2_X2",
+                                                      cDUP2_X2,
+                                                      1,
+                                                      UNKNOWN_TYPE,
+                                                      UNKNOWN_TYPE,
+                                                      JMP_NEXT);
+    public final static JOpcode SWAP =
+        new JOpcode("SWAP", cSWAP, 1, UNKNOWN_TYPE, UNKNOWN_TYPE, JMP_NEXT);
+    public final static JOpcode IADD =
+        new JOpcode("IADD",
+                    cIADD,
+                    1,
+                    INT_TYPE,
+                    new JType[] { JType.INT, JType.INT },
+                    JMP_NEXT);
+    public final static JOpcode LADD =
+        new JOpcode("LADD",
+                    cLADD,
+                    1,
+                    LONG_TYPE,
+                    new JType[] { JType.LONG, JType.LONG },
+                    JMP_NEXT);
+    public final static JOpcode FADD =
+        new JOpcode("FADD",
+                    cFADD,
+                    1,
+                    FLOAT_TYPE,
+                    new JType[] { JType.FLOAT, JType.FLOAT },
+                    JMP_NEXT);
+    public final static JOpcode DADD =
+        new JOpcode("DADD",
+                    cDADD,
+                    1,
+                    DOUBLE_TYPE,
+                    new JType[] { JType.DOUBLE, JType.DOUBLE },
+                    JMP_NEXT);
+    public final static JOpcode ISUB =
+        new JOpcode("ISUB",
+                    cISUB,
+                    1,
+                    INT_TYPE,
+                    new JType[] {JType.INT, JType.INT },
+                    JMP_NEXT);
+    public final static JOpcode LSUB =
+        new JOpcode("LSUB",
+                    cLSUB,
+                    1,
+                    LONG_TYPE,
+                    new JType[] { JType.LONG, JType.LONG },
+                    JMP_NEXT);
+    public final static JOpcode FSUB =
+        new JOpcode("FSUB",
+                    cFSUB,
+                    1,
+                    FLOAT_TYPE,
+                    new JType[] { JType.FLOAT, JType.FLOAT },
+                    JMP_NEXT);
+    public final static JOpcode DSUB =
+        new JOpcode("DSUB",
+                    cDSUB,
+                    1,
+                    DOUBLE_TYPE,
+                    new JType[] { JType.DOUBLE, JType.DOUBLE },
+                    JMP_NEXT);
+    public final static JOpcode IMUL =
+        new JOpcode("IMUL",
+                    cIMUL,
+                    1,
+                    INT_TYPE,
+                    new JType[] {JType.INT, JType.INT },
+                    JMP_NEXT);
+    public final static JOpcode LMUL =
+        new JOpcode("LMUL",
+                    cLMUL,
+                    1,
+                    LONG_TYPE,
+                    new JType[] { JType.LONG, JType.LONG },
+                    JMP_NEXT);
+    public final static JOpcode FMUL =
+        new JOpcode("FMUL",
+                    cFMUL,
+                    1,
+                    FLOAT_TYPE,
+                    new JType[] { JType.FLOAT, JType.FLOAT },
+                    JMP_NEXT);
+    public final static JOpcode DMUL =
+        new JOpcode("DMUL",
+                    cDMUL,
+                    1,
+                    DOUBLE_TYPE,
+                    new JType[] { JType.DOUBLE, JType.DOUBLE },
+                    JMP_NEXT);
+    public final static JOpcode IDIV =
+        new JOpcode("IDIV",
+                    cIDIV,
+                    1,
+                    INT_TYPE,
+                    new JType[] {JType.INT, JType.INT },
+                    JMP_NEXT);
+    public final static JOpcode LDIV =
+        new JOpcode("LDIV",
+                    cLDIV,
+                    1,
+                    LONG_TYPE,
+                    new JType[] { JType.LONG, JType.LONG },
+                    JMP_NEXT);
+    public final static JOpcode FDIV =
+        new JOpcode("FDIV",
+                    cFDIV,
+                    1,
+                    FLOAT_TYPE,
+                    new JType[] { JType.FLOAT, JType.FLOAT },
+                    JMP_NEXT);
+    public final static JOpcode DDIV =
+        new JOpcode("DDIV",
+                    cDDIV,
+                    1,
+                    DOUBLE_TYPE,
+                    new JType[] { JType.DOUBLE, JType.DOUBLE },
+                    JMP_NEXT);
+    public final static JOpcode IREM =
+        new JOpcode("IREM",
+                    cIREM,
+                    1,
+                    INT_TYPE,
+                    new JType[] {JType.INT, JType.INT },
+                    JMP_NEXT);
+    public final static JOpcode LREM =
+        new JOpcode("LREM",
+                    cLREM,
+                    1,
+                    LONG_TYPE,
+                    new JType[] { JType.LONG, JType.LONG },
+                    JMP_NEXT);
+    public final static JOpcode FREM =
+        new JOpcode("FREM",
+                    cFREM,
+                    1,
+                    FLOAT_TYPE,
+                    new JType[] { JType.FLOAT, JType.FLOAT },
+                    JMP_NEXT);
+    public final static JOpcode DREM =
+        new JOpcode("DREM",
+                    cDREM,
+                    1,
+                    DOUBLE_TYPE,
+                    new JType[] { JType.DOUBLE, JType.DOUBLE },
+                    JMP_NEXT);
+    public final static JOpcode INEG =
+        new JOpcode("INEG", cINEG, 1, INT_TYPE, INT_TYPE, JMP_NEXT);
+    public final static JOpcode LNEG =
+        new JOpcode("LNEG", cLNEG, 1, LONG_TYPE, LONG_TYPE, JMP_NEXT);
+    public final static JOpcode FNEG =
+        new JOpcode("FNEG", cFNEG, 1, FLOAT_TYPE, FLOAT_TYPE, JMP_NEXT);
+    public final static JOpcode DNEG =
+        new JOpcode("DNEG", cDNEG, 1, DOUBLE_TYPE, DOUBLE_TYPE, JMP_NEXT);
+    public final static JOpcode ISHL =
+        new JOpcode("ISHL", cISHL,
+                    1,
+                    INT_TYPE,
+                    new JType[] { JType.INT, JType.INT },
+                    JMP_NEXT);
+    public final static JOpcode LSHL =
+        new JOpcode("LSHL",
+                    cLSHL,
+                    1,
+                    LONG_TYPE,
+                    new JType [] { JType.INT, JType.LONG },
+                    JMP_NEXT);
+    public final static JOpcode ISHR =
+        new JOpcode("ISHR",
+                    cISHR,
+                    1,
+                    INT_TYPE,
+                    new JType[] { JType.INT, JType.INT },
+                    JMP_NEXT);
+    public final static JOpcode LSHR =
+        new JOpcode("LSHR",
+                    cLSHR,
+                    1,
+                    LONG_TYPE,
+                    new JType[] { JType.INT, JType.LONG },
+                    JMP_NEXT);
+    public final static JOpcode IUSHR =
+        new JOpcode("IUSHR",
+                    cIUSHR,
+                    1,
+                    INT_TYPE,
+                    new JType[] { JType.INT, JType.INT },
+                    JMP_NEXT);
+    public final static JOpcode LUSHR =
+        new JOpcode("LUSHR",
+                    cLUSHR,
+                    1,
+                    LONG_TYPE,
+                    new JType[] { JType.INT, JType.LONG },
+                    JMP_NEXT);
+    public final static JOpcode IAND =
+        new JOpcode("IAND",
+                    cIAND,
+                    1,
+                    INT_TYPE,
+                    new JType[] { JType.INT, JType.INT },
+                    JMP_NEXT);
+    public final static JOpcode LAND =
+        new JOpcode("LAND",
+                    cLAND,
+                    1,
+                    LONG_TYPE,
+                    new JType[] { JType.LONG, JType.LONG },
+                    JMP_NEXT);
+    public final static JOpcode IOR =
+        new JOpcode("IOR",
+                    cIOR,
+                    1,
+                    INT_TYPE,
+                    new JType[] { JType.INT, JType.INT },
+                    JMP_NEXT);
+    public final static JOpcode LOR =
+        new JOpcode("LOR",
+                    cLOR,
+                    1,
+                    LONG_TYPE,
+                    new JType[] { JType.LONG, JType.LONG },
+                    JMP_NEXT);
+    public final static JOpcode IXOR =
+        new JOpcode("IXOR",
+                    cIXOR,
+                    1,
+                    INT_TYPE,
+                    new JType[] { JType.INT, JType.INT },
+                    JMP_NEXT);
+    public final static JOpcode LXOR =
+        new JOpcode("LXOR",
+                    cLXOR,
+                    1,
+                    LONG_TYPE,
+                    new JType[] { JType.LONG, JType.LONG },
+                    JMP_NEXT);
+    public final static JOpcode IINC =
+        new JOpcode("IINC", cIINC, 3, NO_DATA, NO_DATA, JMP_NEXT);
+    public final static JOpcode I2L =
+        new JOpcode("I2L", cI2L, 1, LONG_TYPE, INT_TYPE, JMP_NEXT);
+    public final static JOpcode I2F =
+        new JOpcode("I2F", cI2F, 1, FLOAT_TYPE, INT_TYPE, JMP_NEXT);
+    public final static JOpcode I2D =
+        new JOpcode("I2D", cI2D, 1, DOUBLE_TYPE, INT_TYPE, JMP_NEXT);
+    public final static JOpcode L2I =
+        new JOpcode("L2I", cL2I, 1, INT_TYPE, LONG_TYPE, JMP_NEXT);
+    public final static JOpcode L2F =
+        new JOpcode("L2F", cL2F, 1, FLOAT_TYPE, LONG_TYPE, JMP_NEXT);
+    public final static JOpcode L2D =
+        new JOpcode("L2D", cL2D, 1, DOUBLE_TYPE, LONG_TYPE, JMP_NEXT);
+    public final static JOpcode F2I =
+        new JOpcode("F2I", cF2I, 1, INT_TYPE, FLOAT_TYPE, JMP_NEXT);
+    public final static JOpcode F2L =
+        new JOpcode("F2L", cF2L, 1, LONG_TYPE, FLOAT_TYPE, JMP_NEXT);
+    public final static JOpcode F2D =
+        new JOpcode("F2D", cF2D, 1, DOUBLE_TYPE, FLOAT_TYPE, JMP_NEXT);
+    public final static JOpcode D2I =
+        new JOpcode("D2I", cD2I, 1, INT_TYPE, DOUBLE_TYPE, JMP_NEXT);
+    public final static JOpcode D2L =
+        new JOpcode("D2L", cD2L, 1, LONG_TYPE, DOUBLE_TYPE, JMP_NEXT);
+    public final static JOpcode D2F =
+        new JOpcode("D2F", cD2F, 1, FLOAT_TYPE, DOUBLE_TYPE, JMP_NEXT);
+    public final static JOpcode I2B =
+        new JOpcode("I2B", cI2B, 1, INT_TYPE, INT_TYPE, JMP_NEXT);
+    public final static JOpcode I2C =
+        new JOpcode("I2C", cI2C, 1, INT_TYPE, INT_TYPE, JMP_NEXT);
+    public final static JOpcode I2S =
+        new JOpcode("I2S", cI2S, 1, INT_TYPE, INT_TYPE, JMP_NEXT);
+    public final static JOpcode LCMP =
+        new JOpcode("LCMP",
+                    cLCMP,
+                    1,
+                    INT_TYPE,
+                    new JType[] { JType.LONG, JType.LONG },
+                    JMP_NEXT);
+    public final static JOpcode FCMPL =
+        new JOpcode("FCMPL",
+                    cFCMPL,
+                    1,
+                    INT_TYPE,
+                    new JType[] { JType.FLOAT, JType.FLOAT },
+                    JMP_NEXT);
+    public final static JOpcode FCMPG =
+        new JOpcode("FCMPG",
+                    cFCMPG,
+                    1,
+                    INT_TYPE,
+                    new JType[] { JType.FLOAT, JType.FLOAT },
+                    JMP_NEXT);
+    public final static JOpcode DCMPL =
+        new JOpcode("DCMPL",
+                    cDCMPL,
+                    1,
+                    INT_TYPE,
+                    new JType[] { JType.LONG, JType.LONG },
+                    JMP_NEXT);
+    public final static JOpcode DCMPG =
+        new JOpcode("DCMPG",
+                    cDCMPG,
+                    1,
+                    INT_TYPE,
+                    new JType[] { JType.DOUBLE, JType.DOUBLE },
+                    JMP_NEXT);
+    public final static JOpcode IFEQ =
+        new JOpcode("IFEQ", cIFEQ, 3, NO_DATA, INT_TYPE, JMP_MAYBE_S2_OFFSET);
+    public final static JOpcode IFNE =
+        new JOpcode("IFNE", cIFNE, 3, NO_DATA, INT_TYPE, JMP_MAYBE_S2_OFFSET);
+    public final static JOpcode IFLT =
+        new JOpcode("IFLT", cIFLT, 3, NO_DATA, INT_TYPE, JMP_MAYBE_S2_OFFSET);
+    public final static JOpcode IFGE =
+        new JOpcode("IFGE", cIFGE, 3, NO_DATA, INT_TYPE, JMP_MAYBE_S2_OFFSET);
+    public final static JOpcode IFGT =
+        new JOpcode("IFGT", cIFGT, 3, NO_DATA, INT_TYPE, JMP_MAYBE_S2_OFFSET);
+    public final static JOpcode IFLE =
+        new JOpcode("IFLE", cIFLE, 3, NO_DATA, INT_TYPE, JMP_MAYBE_S2_OFFSET);
+    public final static JOpcode IF_ICMPEQ =
+        new JOpcode("IF_ICMPEQ",
+                    cIF_ICMPEQ,
+                    3,
+                    NO_DATA,
+                    new JType[] { JType.INT, JType.INT },
+                    JMP_MAYBE_S2_OFFSET);
+    public final static JOpcode IF_ICMPNE =
+        new JOpcode("IF_ICMPNE",
+                    cIF_ICMPNE,
+                    3,
+                    NO_DATA,
+                    new JType[] { JType.INT, JType.INT },
+                    JMP_MAYBE_S2_OFFSET);
+    public final static JOpcode IF_ICMPLT =
+        new JOpcode("IF_ICMPLT",
+                    cIF_ICMPLT,
+                    3,
+                    NO_DATA,
+                    new JType[] { JType.INT, JType.INT },
+                    JMP_MAYBE_S2_OFFSET);
+    public final static JOpcode IF_ICMPGE =
+        new JOpcode("IF_ICMPGE",
+                    cIF_ICMPGE,
+                    3,
+                    NO_DATA,
+                    new JType[] { JType.INT, JType.INT },
+                    JMP_MAYBE_S2_OFFSET);
+    public final static JOpcode IF_ICMPGT =
+        new JOpcode("IF_ICMPGT",
+                    cIF_ICMPGT,
+                    3,
+                    NO_DATA,
+                    new JType[] { JType.INT, JType.INT },
+                    JMP_MAYBE_S2_OFFSET);
+    public final static JOpcode IF_ICMPLE =
+        new JOpcode("IF_ICMPLE",
+                    cIF_ICMPLE,
+                    3,
+                    NO_DATA,
+                    new JType[] { JType.INT, JType.INT },
+                    JMP_MAYBE_S2_OFFSET);
+    public final static JOpcode IF_ACMPEQ =
+        new JOpcode("IF_ACMPEQ",
+                    cIF_ACMPEQ,
+                    3,
+                    NO_DATA,
+                    new JType[] { JType.REFERENCE, JType.REFERENCE },
+                    JMP_MAYBE_S2_OFFSET);
+    public final static JOpcode IF_ACMPNE =
+        new JOpcode("IF_ACMPNE",
+                    cIF_ACMPNE,
+                    3,
+                    NO_DATA,
+                    new JType[] { JType.REFERENCE, JType.REFERENCE },
+                    JMP_MAYBE_S2_OFFSET);
+    public final static JOpcode GOTO =
+        new JOpcode("GOTO", cGOTO, 3, NO_DATA, NO_DATA, JMP_ALWAYS_S2_OFFSET);
+    public final static JOpcode JSR =
+        new JOpcode("JSR", cJSR, 3, ADDRESS_TYPE, NO_DATA, JMP_ALWAYS_S2_OFFSET);
+    public final static JOpcode RET =
+        new JOpcode("RET", cRET, 2, NO_DATA, NO_DATA, JMP_NONE);
+    public final static JOpcode TABLESWITCH = new JOpcode("TABLESWITCH",
+                                                          cTABLESWITCH,
+                                                          UNKNOWN,
+                                                          NO_DATA,
+                                                          INT_TYPE,
+                                                          JMP_TABLE);
+    public final static JOpcode LOOKUPSWITCH = new JOpcode("LOOKUPSWITCH",
+                                                           cLOOKUPSWITCH,
+                                                           UNKNOWN,
+                                                           NO_DATA,
+                                                           INT_TYPE,
+                                                           JMP_LOOKUP);
+    public final static JOpcode IRETURN =
+        new JOpcode("IRETURN", cIRETURN, 1, NO_DATA, INT_TYPE, JMP_NONE);
+    public final static JOpcode LRETURN =
+        new JOpcode("LRETURN", cLRETURN, 1, NO_DATA, LONG_TYPE, JMP_NONE);
+    public final static JOpcode FRETURN =
+        new JOpcode("FRETURN", cFRETURN, 1, NO_DATA, FLOAT_TYPE, JMP_NONE);
+    public final static JOpcode DRETURN =
+        new JOpcode("DRETURN", cDRETURN, 1, NO_DATA, DOUBLE_TYPE, JMP_NONE);
+    public final static JOpcode ARETURN = new JOpcode("ARETURN",
+                                                      cARETURN,
+                                                      1,
+                                                      NO_DATA,
+                                                      OBJECT_REF_TYPE,
+                                                      JMP_NONE);
+    public final static JOpcode RETURN =
+        new JOpcode("RETURN", cRETURN, 1, NO_DATA, NO_DATA, JMP_NONE);
+    public final static JOpcode GETSTATIC = new JOpcode("GETSTATIC",
+                                                        cGETSTATIC,
+                                                        3,
+                                                        UNKNOWN_TYPE,
+                                                        NO_DATA,
+                                                        JMP_NEXT);
+    public final static JOpcode PUTSTATIC = new JOpcode("PUTSTATIC",
+                                                        cPUTSTATIC,
+                                                        3,
+                                                        NO_DATA,
+                                                        UNKNOWN_TYPE,
+                                                        JMP_NEXT);
+    public final static JOpcode GETFIELD = new JOpcode("GETFIELD",
+                                                       cGETFIELD,
+                                                       3,
+                                                       UNKNOWN_TYPE,
+                                                       OBJECT_REF_TYPE,
+                                                       JMP_NEXT);
+    public final static JOpcode PUTFIELD =
+        new JOpcode("PUTFIELD", cPUTFIELD, 3, NO_DATA, UNKNOWN_TYPE, JMP_NEXT);
+    public final static JOpcode INVOKEVIRTUAL = new JOpcode("INVOKEVIRTUAL",
+                                                            cINVOKEVIRTUAL,
+                                                            3,
+                                                            NO_DATA,
+                                                            UNKNOWN_TYPE,
+                                                            JMP_NEXT);
+    public final static JOpcode INVOKESPECIAL = new JOpcode("INVOKESPECIAL",
+                                                            cINVOKESPECIAL,
+                                                            3,
+                                                            NO_DATA,
+                                                            UNKNOWN_TYPE,
+                                                            JMP_NEXT);
+    public final static JOpcode INVOKESTATIC = new JOpcode("INVOKESTATIC",
+                                                           cINVOKESTATIC,
+                                                           3,
+                                                           NO_DATA,
+                                                           UNKNOWN_TYPE,
+                                                           JMP_NEXT);
+    public final static JOpcode INVOKEINTERFACE =
+        new JOpcode("INVOKEINTERFACE",
+                    cINVOKEINTERFACE,
+                    5,
+                    NO_DATA,
+                    UNKNOWN_TYPE,
+                    JMP_NEXT);
+    public final static JOpcode NEW =
+        new JOpcode("NEW", cNEW, 3, OBJECT_REF_TYPE, NO_DATA, JMP_NEXT);
+    public final static JOpcode NEWARRAY =
+        new JOpcode("NEWARRAY",
+                    cNEWARRAY,
+                    2,
+                    ARRAY_REF_TYPE,
+                    INT_TYPE,
+                    JMP_NEXT);
+    public final static JOpcode ANEWARRAY =
+        new JOpcode("ANEWARRAY",
+                    cANEWARRAY,
+                    3,
+                    ARRAY_REF_TYPE,
+                    INT_TYPE,
+                    JMP_NEXT);
+    public final static JOpcode ARRAYLENGTH = new JOpcode("ARRAYLENGTH",
+                                                          cARRAYLENGTH,
+                                                          1,
+                                                          INT_TYPE,
+                                                          ARRAY_REF_TYPE,
+                                                          JMP_NEXT);
+    public final static JOpcode ATHROW = new JOpcode("ATHROW",
+                                                     cATHROW,
+                                                     1,
+                                                     OBJECT_REF_TYPE,
+                                                     OBJECT_REF_TYPE,
+                                                     JMP_NONE);
+    public final static JOpcode CHECKCAST = new JOpcode("CHECKCAST",
+                                                        cCHECKCAST,
+                                                        3,
+                                                        OBJECT_REF_TYPE,
+                                                        OBJECT_REF_TYPE,
+                                                        JMP_NEXT);
+    public final static JOpcode INSTANCEOF = new JOpcode("INSTANCEOF",
+                                                         cINSTANCEOF,
+                                                         3,
+                                                         INT_TYPE,
+                                                         OBJECT_REF_TYPE,
+                                                         JMP_NEXT);
+    public final static JOpcode MONITORENTER = new JOpcode("MONITORENTER",
+                                                           cMONITORENTER,
+                                                           1,
+                                                           NO_DATA,
+                                                           OBJECT_REF_TYPE,
+                                                           JMP_NEXT);
+    public final static JOpcode MONITOREXIT = new JOpcode("MONITOREXIT",
+                                                          cMONITOREXIT,
+                                                          1,
+                                                          NO_DATA,
+                                                          OBJECT_REF_TYPE,
+                                                          JMP_NEXT);
+    public final static JOpcode WIDE = new JOpcode("WIDE",
+                                                   cWIDE,
+                                                   UNKNOWN,
+                                                   UNKNOWN_TYPE,
+                                                   UNKNOWN_TYPE,
+                                                   JMP_NEXT);
+    public final static JOpcode MULTIANEWARRAY = new JOpcode("MULTIANEWARRAY",
+                                                             cMULTIANEWARRAY,
+                                                             4,
+                                                             ARRAY_REF_TYPE,
+                                                             UNKNOWN_TYPE,
+                                                             JMP_NEXT);
+    public final static JOpcode IFNULL = new JOpcode("IFNULL",
+                                                     cIFNULL,
+                                                     3,
+                                                     NO_DATA,
+                                                     REFERENCE_TYPE,
+                                                     JMP_MAYBE_S2_OFFSET);
+    public final static JOpcode IFNONNULL = new JOpcode("IFNONNULL",
+                                                        cIFNONNULL,
+                                                        3,
+                                                        NO_DATA,
+                                                        REFERENCE_TYPE,
+                                                        JMP_MAYBE_S2_OFFSET);
+    public final static JOpcode GOTO_W = new JOpcode("GOTO_W",
+                                                     cGOTO_W,
+                                                     5,
+                                                     NO_DATA,
+                                                     NO_DATA,
+                                                     JMP_ALWAYS_S4_OFFSET);
+    public final static JOpcode JSR_W =
+        new JOpcode("JSR_W", cJSR_W, 5, ADDRESS_TYPE, NO_DATA, JMP_NEXT);
+
+    public final static JOpcode[] OPCODES = {
+        NOP, ACONST_NULL, ICONST_M1, ICONST_0, ICONST_1,
+        ICONST_2, ICONST_3, ICONST_4, ICONST_5, LCONST_0,
+        LCONST_1, FCONST_0, FCONST_1, FCONST_2, DCONST_0,
+        DCONST_1, BIPUSH, SIPUSH, LDC, LDC_W,
+        LDC2_W, ILOAD, LLOAD, FLOAD, DLOAD,
+        ALOAD, ILOAD_0, ILOAD_1, ILOAD_2, ILOAD_3,
+        LLOAD_0, LLOAD_1, LLOAD_2, LLOAD_3, FLOAD_0,
+        FLOAD_1, FLOAD_2, FLOAD_3, DLOAD_0, DLOAD_1,
+        DLOAD_2, DLOAD_3, ALOAD_0, ALOAD_1, ALOAD_2,
+        ALOAD_3, IALOAD, LALOAD, FALOAD, DALOAD,
+        AALOAD, BALOAD, CALOAD, SALOAD, ISTORE,
+        LSTORE, FSTORE, DSTORE, ASTORE, ISTORE_0,
+        ISTORE_1, ISTORE_2, ISTORE_3, LSTORE_0, LSTORE_1,
+        LSTORE_2, LSTORE_3, FSTORE_0, FSTORE_1, FSTORE_2,
+        FSTORE_3, DSTORE_0, DSTORE_1, DSTORE_2, DSTORE_3,
+        ASTORE_0, ASTORE_1, ASTORE_2, ASTORE_3, IASTORE,
+        LASTORE, FASTORE, DASTORE, AASTORE, BASTORE,
+        CASTORE, SASTORE, POP, POP2, DUP,
+        DUP_X1, DUP_X2, DUP2, DUP2_X1, DUP2_X2,
+        SWAP, IADD, LADD, FADD, DADD,
+        ISUB, LSUB, FSUB, DSUB, IMUL,
+        LMUL, FMUL, DMUL, IDIV, LDIV,
+        FDIV, DDIV, IREM, LREM, FREM,
+        DREM, INEG, LNEG, FNEG, DNEG,
+        ISHL, LSHL, ISHR, LSHR, IUSHR,
+        LUSHR, IAND, LAND, IOR, LOR,
+        IXOR, LXOR, IINC, I2L, I2F,
+        I2D, L2I, L2F, L2D, F2I,
+        F2L, F2D, D2I, D2L, D2F,
+        I2B, I2C, I2S, LCMP, FCMPL,
+        FCMPG, DCMPL, DCMPG, IFEQ, IFNE,
+        IFLT, IFGE, IFGT, IFLE, IF_ICMPEQ,
+        IF_ICMPNE, IF_ICMPLT, IF_ICMPGE, IF_ICMPGT, IF_ICMPLE,
+        IF_ACMPEQ, IF_ACMPNE, GOTO, JSR, RET,
+        TABLESWITCH, LOOKUPSWITCH, IRETURN, LRETURN, FRETURN,
+        DRETURN, ARETURN, RETURN, GETSTATIC, PUTSTATIC,
+        GETFIELD, PUTFIELD, INVOKEVIRTUAL, INVOKESPECIAL, INVOKESTATIC,
+        INVOKEINTERFACE, null, NEW, NEWARRAY, ANEWARRAY,
+        ARRAYLENGTH, ATHROW, CHECKCAST, INSTANCEOF, MONITORENTER,
+        MONITOREXIT, WIDE, MULTIANEWARRAY, IFNULL, IFNONNULL,
+        GOTO_W, JSR_W
+    };
+
+    protected JOpcode(String name,
+                      int code,
+                      int size,
+                      JType[] producedDataTypes,
+                      JType[] consumedDataTypes,
+                      int jumpKind) {
+        this.name = name;
+        this.code = code;
+        this.size = size;
+        this.producedDataTypes = producedDataTypes;
+        this.consumedDataTypes = consumedDataTypes;
+        this.jumpKind = jumpKind;
+        switch (jumpKind) {
+        case JMP_NONE: successorCount = 0; break;
+        case JMP_NEXT: successorCount = 1; break;
+        case JMP_ALWAYS_S2_OFFSET: successorCount = 1; break;
+        case JMP_ALWAYS_S4_OFFSET: successorCount = 1; break;
+        case JMP_MAYBE_S2_OFFSET: successorCount = 2; break;
+        case JMP_TABLE: successorCount = UNKNOWN; break;
+        case JMP_LOOKUP: successorCount = UNKNOWN; break;
+        default: successorCount = UNKNOWN; break;
+        }
+    }
+
+    public String toString() { return name; }
+    protected int getSize() { return size; }
+    protected JType[] getProducedDataTypes() { return producedDataTypes; }
+    protected JType[] getConsumedDataTypes() { return consumedDataTypes; }
+
+    protected int getProducedDataSize() {
+        if (producedDataTypes != UNKNOWN_TYPE)
+            return JType.getTotalSize(producedDataTypes);
+        else {
+            switch (code) {
+            case cLDC: case cLDC_W: case cBALOAD:
+                return 1;
+            case cLDC2_W: case cDUP: case cSWAP:
+                return 2;
+            case cDUP_X1:
+                return 3;
+            case cDUP_X2: case cDUP2:
+                return 4;
+            case cDUP2_X1:
+                return 5;
+            case cDUP2_X2:
+                return 6;
+            default:
+                throw new Error(this.toString());
+            }
+        }
+    }
+
+    protected int getConsumedDataSize() {
+        if (consumedDataTypes != UNKNOWN_TYPE)
+            return JType.getTotalSize(consumedDataTypes);
+        else {
+            switch (code) {
+            case cPOP: case cDUP:
+                return 1;
+            case cPOP2: case cDUP_X1: case cDUP2: case cSWAP:
+                return 2;
+            case cDUP_X2: case cDUP2_X1:
+                return 3;
+            case cDUP2_X2:
+                return 4;
+            default:
+                throw new Error(this.toString());
+            }
+        }
+    }
+
+    protected int getProducedDataTypesNumber() {
+        if (producedDataTypes != UNKNOWN_TYPE)
+            return producedDataTypes.length;
+        else {
+            switch (code) {
+            case cLDC: case cLDC_W: case cLDC2_W: case cBALOAD:
+            case cGETSTATIC: case cGETFIELD:
+                return 1;
+            case cDUP: case cSWAP:
+                return 2;
+            case cDUP_X2: case cDUP2: case cDUP2_X1: case cDUP2_X2:
+                return 2;
+            case cDUP_X1:
+                return 3;
+            default:
+                throw new Error(this.toString());
+            }
+        }
+    }
+
+    protected int getConsumedDataTypesNumber() {
+        if (consumedDataTypes != UNKNOWN_TYPE)
+            return consumedDataTypes.length;
+        else {
+            switch (code) {
+            case cPOP: case cDUP: case cPUTSTATIC:
+                return 1;
+            case cPUTFIELD: case cDUP_X1: case cDUP_X2:
+            case cDUP2: case cDUP2_X1: case cPOP2: case cSWAP:
+                return 2;
+            default:
+                throw new Error(this.toString());
+            }
+        }
+    }
+}
diff --git a/src/fjbg/ch/epfl/lamp/fjbg/JOtherAttribute.java b/src/fjbg/ch/epfl/lamp/fjbg/JOtherAttribute.java
new file mode 100644
index 0000000..7a64f91
--- /dev/null
+++ b/src/fjbg/ch/epfl/lamp/fjbg/JOtherAttribute.java
@@ -0,0 +1,53 @@
+
+package ch.epfl.lamp.fjbg;
+
+import java.io.*;
+
+/**
+ * Attributes which are unknown to the JVM (or at least to this
+ * library).
+ *
+ * @author Michel Schinz
+ * @version 1.0
+ */
+
+public class JOtherAttribute extends JAttribute {
+    protected final String name;
+    protected final byte[] contents;
+    protected final int length;
+
+    public JOtherAttribute(FJBGContext context,
+                           JClass clazz,
+                           Object owner,
+                           String name,
+                           byte[] contents,
+                           int length) {
+        super(context, clazz, name);
+        this.name = name;
+        this.contents = contents;
+        this.length = length;
+    }
+
+    public JOtherAttribute(FJBGContext context,
+                           JClass clazz,
+                           Object owner,
+                           String name,
+                           int size,
+                           DataInputStream stream)
+        throws IOException {
+        super(context, clazz, name);
+        this.name = name;
+        this.contents = new byte[size];
+        this.length = size;
+
+        stream.read(contents, 0, length);
+    }
+
+    public String getName() { return name; }
+
+    protected int getSize() { return length; }
+
+    protected void writeContentsTo(DataOutputStream stream) throws IOException {
+        stream.write(contents, 0, length);
+    }
+}
diff --git a/src/fjbg/ch/epfl/lamp/fjbg/JReferenceType.java b/src/fjbg/ch/epfl/lamp/fjbg/JReferenceType.java
new file mode 100644
index 0000000..0ed6ef4
--- /dev/null
+++ b/src/fjbg/ch/epfl/lamp/fjbg/JReferenceType.java
@@ -0,0 +1,15 @@
+
+package ch.epfl.lamp.fjbg;
+
+/**
+ * Types for Java references, i.e. arrays and objects.
+ *
+ * @version 1.0
+ * @author Michel Schinz
+ */
+
+abstract public class JReferenceType extends JType {
+    public boolean isReferenceType() { return true; }
+
+    abstract public String getDescriptor();
+}
diff --git a/src/fjbg/ch/epfl/lamp/fjbg/JSourceFileAttribute.java b/src/fjbg/ch/epfl/lamp/fjbg/JSourceFileAttribute.java
new file mode 100644
index 0000000..e447872
--- /dev/null
+++ b/src/fjbg/ch/epfl/lamp/fjbg/JSourceFileAttribute.java
@@ -0,0 +1,52 @@
+
+package ch.epfl.lamp.fjbg;
+
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.IOException;
+
+/**
+ * Sourcefile attribute, which can be attached to class files to
+ * associate them with their source file.
+ *
+ * @version 1.0
+ * @author Michel Schinz
+ */
+
+public class JSourceFileAttribute extends JAttribute {
+    protected final String sourceFileName;
+    protected final int sourceFileIndex;
+
+    public JSourceFileAttribute(FJBGContext context,
+                                JClass clazz,
+                                String sourceFileName) {
+        super(context, clazz);
+        this.sourceFileName = sourceFileName;
+        this.sourceFileIndex = clazz.getConstantPool().addUtf8(sourceFileName);
+    }
+
+    public JSourceFileAttribute(FJBGContext context,
+                                JClass clazz,
+                                Object owner,
+                                String name,
+                                int size,
+                                DataInputStream stream)
+        throws IOException {
+        super(context, clazz);
+        stream.readInt();       // ignore size
+        this.sourceFileIndex = stream.readShort();
+        this.sourceFileName = clazz.getConstantPool().lookupUtf8(sourceFileIndex);
+
+        assert name.equals(getName());
+    }
+
+    public String getName() { return "SourceFile"; }
+
+    protected int getSize() {
+        return 2;
+    }
+
+    protected void writeContentsTo(DataOutputStream stream) throws IOException {
+        stream.writeShort(sourceFileIndex);
+    }
+}
diff --git a/src/fjbg/ch/epfl/lamp/fjbg/JType.java b/src/fjbg/ch/epfl/lamp/fjbg/JType.java
new file mode 100644
index 0000000..b926a59
--- /dev/null
+++ b/src/fjbg/ch/epfl/lamp/fjbg/JType.java
@@ -0,0 +1,288 @@
+
+package ch.epfl.lamp.fjbg;
+
+import java.util.*;
+import java.io.StringReader;
+import java.io.IOException;
+
+/**
+ * Representation of Java types.
+ *
+ * @version 1.0
+ * @author Michel Schinz
+ */
+
+abstract public class JType {
+    abstract public int getSize();
+    abstract public String getSignature();
+    abstract public int getTag();
+    abstract public String toString();
+    abstract public boolean isCompatibleWith(JType other);
+
+    public boolean isValueType() { return false; }
+    public boolean isObjectType() { return false; }
+    public boolean isArrayType() { return false; }
+    public boolean isReferenceType() { return false; }
+
+    // Tags for types. Taken from BCEL.
+    public static final int T_BOOLEAN = 4;
+    public static final int T_CHAR    = 5;
+    public static final int T_FLOAT   = 6;
+    public static final int T_DOUBLE  = 7;
+    public static final int T_BYTE    = 8;
+    public static final int T_SHORT   = 9;
+    public static final int T_INT     = 10;
+    public static final int T_LONG    = 11;
+    public static final int T_VOID    = 12; // Non-standard
+    public static final int T_ARRAY   = 13;
+    public static final int T_OBJECT  = 14;
+    public static final int T_UNKNOWN = 15;
+    public static final int T_ADDRESS = 16;
+
+    public static final int T_REFERENCE = 17; // type compatible with references
+
+    public static final JType[] EMPTY_ARRAY = new JType[0];
+
+    protected static JType parseSig(StringReader s) throws IOException {
+        int nextChar = s.read();
+        if (nextChar == -1) throw new IllegalArgumentException();
+
+        switch ((char)nextChar) {
+        case 'V' : return VOID;
+        case 'Z' : return BOOLEAN;
+        case 'B' : return BYTE;
+        case 'C' : return CHAR;
+        case 'S' : return SHORT;
+        case 'I' : return INT;
+        case 'F' : return FLOAT;
+        case 'J' : return LONG;
+        case 'D' : return DOUBLE;
+        case 'L': {
+            StringBuffer className = new StringBuffer();
+            for (;;) {
+                nextChar = s.read();
+                if (nextChar == -1 || nextChar == ';') break;
+                className.append(nextChar == '/' ? ':' : ((char)nextChar));
+            }
+            if (nextChar != ';') throw new IllegalArgumentException();
+            return new JObjectType(className.toString());
+        }
+        case '[': {
+            JType elemType = parseSig(s);
+            return new JArrayType(elemType);
+        }
+        case '(': {
+            ArrayList argTps = new ArrayList();
+            for (;;) {
+                s.mark(1);
+                nextChar = s.read();
+                if (nextChar == -1 || nextChar == ')') break;
+                s.reset();
+                argTps.add(parseSig(s));
+            }
+            if (nextChar != ')') throw new IllegalArgumentException("a");
+            JType[] argTpsA = (JType[])argTps.toArray(new JType[argTps.size()]);
+            JType returnType = parseSig(s);
+            return new JMethodType(returnType, argTpsA);
+        }
+        default:
+            throw new IllegalArgumentException();
+        }
+    }
+
+    public static JType parseSignature(String signature) {
+        try {
+            StringReader sigReader = new StringReader(signature);
+            JType parsed = parseSig(sigReader);
+            if (sigReader.read() != -1)
+                throw new IllegalArgumentException();
+            return parsed;
+        } catch (IllegalArgumentException e) {
+            throw new IllegalArgumentException("invalid signature " + signature);
+        } catch (IOException e) {
+            throw new Error(e);
+        }
+    }
+
+    public static int getTotalSize(JType[] types) {
+        int size = 0;
+        for (int i = 0; i < types.length; ++i)
+            size += types[i].getSize();
+        return size;
+    }
+
+    protected JType() {}
+
+    public static JType VOID = new JType() {
+            public int getSize() { return 0; }
+            public String getSignature() { return "V"; }
+            public int getTag() { return T_VOID; }
+            public String toString() { return "void"; }
+            public boolean isCompatibleWith(JType other) {
+                throw new UnsupportedOperationException("type VOID is no real "
+                                                        + "data type therefore "
+                                                        + "cannot be assigned to "
+                                                        + other.toString());
+            }
+        };
+
+    public static JType BOOLEAN = new JType() {
+            public int getSize() { return 1; }
+            public String getSignature() { return "Z"; }
+            public int getTag() { return T_BOOLEAN; }
+            public String toString() { return "boolean"; }
+            public boolean isValueType() { return true; }
+            public boolean isCompatibleWith(JType other) {
+                return other == BOOLEAN
+                    || other == INT
+                    || other == BYTE
+                    || other == CHAR
+                    || other == SHORT;
+            }
+        };
+
+    public static JType BYTE = new JType() {
+            public int getSize() { return 1; }
+            public String getSignature() { return "B"; }
+            public int getTag() { return T_BYTE; }
+            public String toString() { return "byte"; }
+            public boolean isValueType() { return true; }
+            public boolean isCompatibleWith(JType other) {
+                return other == BOOLEAN
+                    || other == INT
+                    || other == BYTE
+                    || other == CHAR
+                    || other == SHORT;
+            }
+        };
+
+    public static JType CHAR = new JType() {
+            public int getSize() { return 1; }
+            public String getSignature() { return "C"; }
+            public int getTag() { return T_CHAR; }
+            public String toString() { return "char"; }
+            public boolean isValueType() { return true; }
+            public boolean isCompatibleWith(JType other) {
+                return other == BOOLEAN
+                    || other == INT
+                    || other == BYTE
+                    || other == CHAR
+                    || other == SHORT;
+            }
+        };
+
+    public static JType SHORT = new JType() {
+            public int getSize() { return 1; }
+            public String getSignature() { return "S"; }
+            public int getTag() { return T_SHORT; }
+            public String toString() { return "short"; }
+            public boolean isValueType() { return true; }
+            public boolean isCompatibleWith(JType other) {
+                return other == BOOLEAN
+                    || other == INT
+                    || other == BYTE
+                    || other == CHAR
+                    || other == SHORT;
+            }
+        };
+
+    public static JType INT = new JType() {
+            public int getSize() { return 1; }
+            public String getSignature() { return "I"; }
+            public int getTag() { return T_INT; }
+            public String toString() { return "int"; }
+            public boolean isValueType() { return true; }
+            public boolean isCompatibleWith(JType other) {
+                return other == BOOLEAN
+                    || other == INT
+                    || other == BYTE
+                    || other == CHAR
+                    || other == SHORT;
+            }
+        };
+
+    public static JType FLOAT = new JType() {
+            public int getSize() { return 1; }
+            public String getSignature() { return "F"; }
+            public int getTag() { return T_FLOAT; }
+            public String toString() { return "float"; }
+            public boolean isValueType() { return true; }
+            public boolean isCompatibleWith(JType other) {
+                return other == FLOAT;
+            }
+        };
+
+    public static JType LONG = new JType() {
+            public int getSize() { return 2; }
+            public String getSignature() { return "J"; }
+            public int getTag() { return T_LONG; }
+            public String toString() { return "long"; }
+            public boolean isValueType() { return true; }
+            public boolean isCompatibleWith(JType other) {
+                return other == LONG;
+            }
+        };
+
+    public static JType DOUBLE = new JType() {
+            public int getSize() { return 2; }
+            public String getSignature() { return "D"; }
+            public int getTag() { return T_DOUBLE; }
+            public String toString() { return "double"; }
+            public boolean isValueType() { return true; }
+            public boolean isCompatibleWith(JType other) {
+                return other == DOUBLE;
+            }
+        };
+
+    public static JType REFERENCE = new JType() {
+            public int getSize() { return 1; }
+            public String getSignature() {
+                throw new UnsupportedOperationException("type REFERENCE is no real "
+                                                        + "data type and therefore "
+                                                        + "has no signature");
+            }
+            public int getTag() { return T_REFERENCE; }
+            public String toString() { return "<reference>"; }
+            public boolean isCompatibleWith(JType other) {
+                throw new UnsupportedOperationException("type REFERENCE is no real "
+                                                        + "data type and therefore "
+                                                        + "cannot be assigned to "
+                                                        + other.toString());
+            }
+        };
+
+    public static JType ADDRESS = new JType() {
+            public int getSize() { return 1; }
+            public String getSignature() {
+                throw new UnsupportedOperationException("type ADDRESS is no usable "
+                                                        + "data type and therefore "
+                                                        + "has no signature");
+            }
+            public int getTag() { return T_ADDRESS; }
+            public String toString() { return "<address>"; }
+            public boolean isCompatibleWith(JType other) {
+                return other == ADDRESS;
+            }
+        };
+
+    public static JType UNKNOWN = new JType() {
+            public int getSize() {
+                throw new UnsupportedOperationException("type UNKNOWN is no real "
+                                                        + "data type and therefore "
+                                                        + "has no size");
+            }
+            public String getSignature() {
+                throw new UnsupportedOperationException("type UNKNOWN is no real "
+                                                        + "data type and therefore "
+                                                        + "has no signature");
+            }
+            public int getTag() { return T_UNKNOWN; }
+            public String toString() { return "<unknown>"; }
+            public boolean isCompatibleWith(JType other) {
+                throw new UnsupportedOperationException("type UNKNOWN is no real "
+                                                        + "data type and therefore "
+                                                        + "cannot be assigned to "
+                                                        + other.toString());
+            }
+        };
+}
diff --git a/src/fjbg/ch/epfl/lamp/util/ByteArray.java b/src/fjbg/ch/epfl/lamp/util/ByteArray.java
new file mode 100644
index 0000000..d6b7048
--- /dev/null
+++ b/src/fjbg/ch/epfl/lamp/util/ByteArray.java
@@ -0,0 +1,139 @@
+
+package ch.epfl.lamp.util;
+
+import java.io.*;
+
+/**
+ * Array of bytes.
+ *
+ * @author Michel Schinz
+ * @version 1.0
+ */
+
+public class ByteArray {
+    protected final static int BYTE_BLOCK_BITS = 8;
+    protected final static int BYTE_BLOCK_SIZE = 1 << BYTE_BLOCK_BITS;
+    protected final static int BYTE_BLOCK_MASK = BYTE_BLOCK_SIZE - 1;
+
+    protected byte[][] data = new byte[][] { new byte[BYTE_BLOCK_SIZE] };
+    protected int pos = 0;	// The next free position.
+
+    protected boolean frozen = false;
+
+    public ByteArray() { }
+
+    public ByteArray(InputStream stream, int size) throws IOException {
+    	size = pos;
+        for (int block = 0; size > 0; ++block) {
+            int sizeToRead = Math.min(BYTE_BLOCK_SIZE, size);
+            stream.read(data[block], 0, sizeToRead);
+
+            size -= sizeToRead;
+            if (size > 0) addNewBlock();
+        }
+    }
+
+    public void freeze() { frozen = true; }
+
+    public int nextBytePosition() {
+        return pos;
+    }
+
+    public int getSize() {
+	return pos;
+    }
+
+    protected void addNewBlock() {
+        int nextBlockPos = pos >>> BYTE_BLOCK_BITS;
+        if (nextBlockPos == data.length) {
+            byte[][] newData = new byte[data.length * 2][];
+            System.arraycopy(data, 0, newData, 0, data.length);
+            data = newData;
+        }
+        assert data[nextBlockPos] == null : pos + " " + nextBlockPos;
+        data[nextBlockPos] = new byte[BYTE_BLOCK_SIZE];
+    }
+
+    protected void addByte(int b) {
+        assert !frozen;
+
+        if ((pos & BYTE_BLOCK_MASK) == 0 && pos > 0)
+            addNewBlock();
+        int currPos = pos++;
+        data[currPos >>> BYTE_BLOCK_BITS][currPos & BYTE_BLOCK_MASK] = (byte)b;
+    }
+
+    public void addU1(int i) {
+	assert i <= 0xFF : i;
+	addByte(i);
+    }
+
+    public void addU2(int i) {
+	assert i <= 0xFFFF : i;
+
+	addByte(i >>> 8);
+	addByte(i & 0xFF);
+    }
+
+    public void addU4(int i) {
+	addByte(i >>> 24);
+	addByte((i >>> 16) & 0xFF);
+	addByte((i >>>  8) & 0xFF);
+	addByte(i & 0xFF);
+    }
+
+    public void putByte(int targetPos, int b) {
+        assert !frozen;
+	assert targetPos < pos : targetPos + " >= " + pos;
+
+	data[targetPos >>> BYTE_BLOCK_BITS][targetPos & BYTE_BLOCK_MASK] = (byte)b;
+    }
+
+    public void putU2(int targetPos, int i) {
+	assert i < 0xFFFF : i;
+	putByte(targetPos, i >>> 8);
+	putByte(targetPos + 1, i & 0xFF);
+    }
+
+    public void putU4(int targetPos, int i) {
+	putByte(targetPos, i >>> 24);
+	putByte(targetPos + 1, (i >>> 16) & 0xFF);
+	putByte(targetPos + 2, (i >>>  8) & 0xFF);
+	putByte(targetPos + 3, i & 0xFF);
+    }
+
+    public int getU1(int sourcePos) {
+        assert sourcePos < pos : sourcePos + " >= " + pos;
+        return data[sourcePos >>> BYTE_BLOCK_BITS][sourcePos & BYTE_BLOCK_MASK] & 0xFF;
+    }
+
+    public int getU2(int sourcePos) {
+        return (getU1(sourcePos) << 8) | getU1(sourcePos + 1);
+    }
+
+    public int getU4(int sourcePos) {
+        return (getU2(sourcePos) << 16) | getU2(sourcePos + 2);
+    }
+
+    public int getS1(int sourcePos) {
+        assert sourcePos < pos : sourcePos + " >= " + pos;
+        return data[sourcePos >>> BYTE_BLOCK_BITS][sourcePos & BYTE_BLOCK_MASK];
+    }
+
+    public int getS2(int sourcePos) {
+        return (getS1(sourcePos) << 8) | getU1(sourcePos + 1);
+    }
+
+    public int getS4(int sourcePos) {
+        return (getS2(sourcePos) << 16) | getU2(sourcePos + 2);
+    }
+
+    public void writeTo(OutputStream stream) throws IOException {
+        if (!frozen) freeze();
+
+	for (int i = 0; i < data.length && data[i] != null; ++i) {
+	    int len = Math.min(BYTE_BLOCK_SIZE, pos - (i << BYTE_BLOCK_BITS));
+	    stream.write(data[i], 0, len);
+	}
+    }
+}
diff --git a/src/forkjoin/scala/concurrent/forkjoin/ForkJoinPool.java b/src/forkjoin/scala/concurrent/forkjoin/ForkJoinPool.java
new file mode 100644
index 0000000..c55beee
--- /dev/null
+++ b/src/forkjoin/scala/concurrent/forkjoin/ForkJoinPool.java
@@ -0,0 +1,1870 @@
+/*
+ * Written by Doug Lea with assistance from members of JCP JSR-166
+ * Expert Group and released to the public domain, as explained at
+ * http://creativecommons.org/licenses/publicdomain
+ */
+
+package scala.concurrent.forkjoin;
+import java.util.*;
+import java.util.concurrent.*;
+import java.util.concurrent.locks.*;
+import java.util.concurrent.atomic.*;
+import sun.misc.Unsafe;
+import java.lang.reflect.*;
+
+/**
+ * An {@link ExecutorService} for running {@link ForkJoinTask}s.  A
+ * ForkJoinPool provides the entry point for submissions from
+ * non-ForkJoinTasks, as well as management and monitoring operations.
+ * Normally a single ForkJoinPool is used for a large number of
+ * submitted tasks. Otherwise, use would not usually outweigh the
+ * construction and bookkeeping overhead of creating a large set of
+ * threads.
+ *
+ * <p>ForkJoinPools differ from other kinds of Executors mainly in
+ * that they provide <em>work-stealing</em>: all threads in the pool
+ * attempt to find and execute subtasks created by other active tasks
+ * (eventually blocking if none exist). This makes them efficient when
+ * most tasks spawn other subtasks (as do most ForkJoinTasks), as well
+ * as the mixed execution of some plain Runnable- or Callable- based
+ * activities along with ForkJoinTasks. When setting
+ * <tt>setAsyncMode</tt>, a ForkJoinPools may also be appropriate for
+ * use with fine-grained tasks that are never joined. Otherwise, other
+ * ExecutorService implementations are typically more appropriate
+ * choices.
+ *
+ * <p>A ForkJoinPool may be constructed with a given parallelism level
+ * (target pool size), which it attempts to maintain by dynamically
+ * adding, suspending, or resuming threads, even if some tasks are
+ * waiting to join others. However, no such adjustments are performed
+ * in the face of blocked IO or other unmanaged synchronization. The
+ * nested <code>ManagedBlocker</code> interface enables extension of
+ * the kinds of synchronization accommodated.  The target parallelism
+ * level may also be changed dynamically (<code>setParallelism</code>)
+ * and thread construction can be limited using methods
+ * <code>setMaximumPoolSize</code> and/or
+ * <code>setMaintainsParallelism</code>.
+ *
+ * <p>In addition to execution and lifecycle control methods, this
+ * class provides status check methods (for example
+ * <code>getStealCount</code>) that are intended to aid in developing,
+ * tuning, and monitoring fork/join applications. Also, method
+ * <code>toString</code> returns indications of pool state in a
+ * convenient form for informal monitoring.
+ *
+ * <p><b>Implementation notes</b>: This implementation restricts the
+ * maximum number of running threads to 32767. Attempts to create
+ * pools with greater than the maximum result in
+ * IllegalArgumentExceptions.
+ */
+public class ForkJoinPool /*extends AbstractExecutorService*/ {
+
+    /*
+     * See the extended comments interspersed below for design,
+     * rationale, and walkthroughs.
+     */
+
+    /** Mask for packing and unpacking shorts */
+    private static final int  shortMask = 0xffff;
+
+    /** Max pool size -- must be a power of two minus 1 */
+    private static final int MAX_THREADS =  0x7FFF;
+
+    // placeholder for java.util.concurrent.RunnableFuture
+    interface RunnableFuture<T> extends Runnable {
+    }
+
+    /**
+     * Factory for creating new ForkJoinWorkerThreads.  A
+     * ForkJoinWorkerThreadFactory must be defined and used for
+     * ForkJoinWorkerThread subclasses that extend base functionality
+     * or initialize threads with different contexts.
+     */
+    public static interface ForkJoinWorkerThreadFactory {
+        /**
+         * Returns a new worker thread operating in the given pool.
+         *
+         * @param pool the pool this thread works in
+         * @throws NullPointerException if pool is null;
+         */
+        public ForkJoinWorkerThread newThread(ForkJoinPool pool);
+    }
+
+    /**
+     * Default ForkJoinWorkerThreadFactory implementation, creates a
+     * new ForkJoinWorkerThread.
+     */
+    static class  DefaultForkJoinWorkerThreadFactory
+        implements ForkJoinWorkerThreadFactory {
+        public ForkJoinWorkerThread newThread(ForkJoinPool pool) {
+            try {
+                return new ForkJoinWorkerThread(pool);
+            } catch (OutOfMemoryError oom)  {
+                return null;
+            }
+        }
+    }
+
+    /**
+     * Creates a new ForkJoinWorkerThread. This factory is used unless
+     * overridden in ForkJoinPool constructors.
+     */
+    public static final ForkJoinWorkerThreadFactory
+        defaultForkJoinWorkerThreadFactory =
+        new DefaultForkJoinWorkerThreadFactory();
+
+    /**
+     * Permission required for callers of methods that may start or
+     * kill threads.
+     */
+    private static final RuntimePermission modifyThreadPermission =
+        new RuntimePermission("modifyThread");
+
+    /**
+     * If there is a security manager, makes sure caller has
+     * permission to modify threads.
+     */
+    private static void checkPermission() {
+        SecurityManager security = System.getSecurityManager();
+        if (security != null)
+            security.checkPermission(modifyThreadPermission);
+    }
+
+    /**
+     * Generator for assigning sequence numbers as pool names.
+     */
+    private static final AtomicInteger poolNumberGenerator =
+        new AtomicInteger();
+
+    /**
+     * Array holding all worker threads in the pool. Initialized upon
+     * first use. Array size must be a power of two.  Updates and
+     * replacements are protected by workerLock, but it is always kept
+     * in a consistent enough state to be randomly accessed without
+     * locking by workers performing work-stealing.
+     */
+    public volatile ForkJoinWorkerThread[] workers;
+
+    /**
+     * Lock protecting access to workers.
+     */
+    private final ReentrantLock workerLock;
+
+    /**
+     * Condition for awaitTermination.
+     */
+    private final Condition termination;
+
+    /**
+     * The uncaught exception handler used when any worker
+     * abrupty terminates
+     */
+    private Thread.UncaughtExceptionHandler ueh;
+
+    /**
+     * Creation factory for worker threads.
+     */
+    private final ForkJoinWorkerThreadFactory factory;
+
+    /**
+     * Head of stack of threads that were created to maintain
+     * parallelism when other threads blocked, but have since
+     * suspended when the parallelism level rose.
+     */
+    private volatile WaitQueueNode spareStack;
+
+    /**
+     * Sum of per-thread steal counts, updated only when threads are
+     * idle or terminating.
+     */
+    private final AtomicLong stealCount;
+
+    /**
+     * Queue for external submissions.
+     */
+    private final LinkedTransferQueue<ForkJoinTask<?>> submissionQueue;
+
+    /**
+     * Head of Treiber stack for barrier sync. See below for explanation
+     */
+    private volatile WaitQueueNode syncStack;
+
+    /**
+     * The count for event barrier
+     */
+    private volatile long eventCount;
+
+    /**
+     * Pool number, just for assigning useful names to worker threads
+     */
+    private final int poolNumber;
+
+    /**
+     * The maximum allowed pool size
+     */
+    private volatile int maxPoolSize;
+
+    /**
+     * The desired parallelism level, updated only under workerLock.
+     */
+    private volatile int parallelism;
+
+    /**
+     * True if use local fifo, not default lifo, for local polling
+     */
+    private volatile boolean locallyFifo;
+
+    /**
+     * Holds number of total (i.e., created and not yet terminated)
+     * and running (i.e., not blocked on joins or other managed sync)
+     * threads, packed into one int to ensure consistent snapshot when
+     * making decisions about creating and suspending spare
+     * threads. Updated only by CAS.  Note: CASes in
+     * updateRunningCount and preJoin running active count is in low
+     * word, so need to be modified if this changes
+     */
+    private volatile int workerCounts;
+
+    private static int totalCountOf(int s)           { return s >>> 16;  }
+    private static int runningCountOf(int s)         { return s & shortMask; }
+    private static int workerCountsFor(int t, int r) { return (t << 16) + r; }
+
+    /**
+     * Add delta (which may be negative) to running count.  This must
+     * be called before (with negative arg) and after (with positive)
+     * any managed synchronization (i.e., mainly, joins)
+     * @param delta the number to add
+     */
+    final void updateRunningCount(int delta) {
+        int s;
+        do;while (!casWorkerCounts(s = workerCounts, s + delta));
+    }
+
+    /**
+     * Add delta (which may be negative) to both total and running
+     * count.  This must be called upon creation and termination of
+     * worker threads.
+     * @param delta the number to add
+     */
+    private void updateWorkerCount(int delta) {
+        int d = delta + (delta << 16); // add to both lo and hi parts
+        int s;
+        do;while (!casWorkerCounts(s = workerCounts, s + d));
+    }
+
+    /**
+     * Lifecycle control. High word contains runState, low word
+     * contains the number of workers that are (probably) executing
+     * tasks. This value is atomically incremented before a worker
+     * gets a task to run, and decremented when worker has no tasks
+     * and cannot find any. These two fields are bundled together to
+     * support correct termination triggering.  Note: activeCount
+     * CAS'es cheat by assuming active count is in low word, so need
+     * to be modified if this changes
+     */
+    private volatile int runControl;
+
+    // RunState values. Order among values matters
+    private static final int RUNNING     = 0;
+    private static final int SHUTDOWN    = 1;
+    private static final int TERMINATING = 2;
+    private static final int TERMINATED  = 3;
+
+    private static int runStateOf(int c)             { return c >>> 16; }
+    private static int activeCountOf(int c)          { return c & shortMask; }
+    private static int runControlFor(int r, int a)   { return (r << 16) + a; }
+
+    /**
+     * Try incrementing active count; fail on contention. Called by
+     * workers before/during executing tasks.
+     * @return true on success;
+     */
+    final boolean tryIncrementActiveCount() {
+        int c = runControl;
+        return casRunControl(c, c+1);
+    }
+
+    /**
+     * Try decrementing active count; fail on contention.
+     * Possibly trigger termination on success
+     * Called by workers when they can't find tasks.
+     * @return true on success
+     */
+    final boolean tryDecrementActiveCount() {
+        int c = runControl;
+        int nextc = c - 1;
+        if (!casRunControl(c, nextc))
+            return false;
+        if (canTerminateOnShutdown(nextc))
+            terminateOnShutdown();
+        return true;
+    }
+
+    /**
+     * Return true if argument represents zero active count and
+     * nonzero runstate, which is the triggering condition for
+     * terminating on shutdown.
+     */
+    private static boolean canTerminateOnShutdown(int c) {
+        return ((c & -c) >>> 16) != 0; // i.e. least bit is nonzero runState bit
+    }
+
+    /**
+     * Transition run state to at least the given state. Return true
+     * if not already at least given state.
+     */
+    private boolean transitionRunStateTo(int state) {
+        for (;;) {
+            int c = runControl;
+            if (runStateOf(c) >= state)
+                return false;
+            if (casRunControl(c, runControlFor(state, activeCountOf(c))))
+                return true;
+        }
+    }
+
+    /**
+     * Controls whether to add spares to maintain parallelism
+     */
+    private volatile boolean maintainsParallelism;
+
+    // Constructors
+
+    /**
+     * Creates a ForkJoinPool with a pool size equal to the number of
+     * processors available on the system and using the default
+     * ForkJoinWorkerThreadFactory,
+     * @throws SecurityException if a security manager exists and
+     *         the caller is not permitted to modify threads
+     *         because it does not hold {@link
+     *         java.lang.RuntimePermission}<code>("modifyThread")</code>,
+     */
+    public ForkJoinPool() {
+        this(Runtime.getRuntime().availableProcessors(),
+             defaultForkJoinWorkerThreadFactory);
+    }
+
+    /**
+     * Creates a ForkJoinPool with the indicated parellelism level
+     * threads, and using the default ForkJoinWorkerThreadFactory,
+     * @param parallelism the number of worker threads
+     * @throws IllegalArgumentException if parallelism less than or
+     * equal to zero
+     * @throws SecurityException if a security manager exists and
+     *         the caller is not permitted to modify threads
+     *         because it does not hold {@link
+     *         java.lang.RuntimePermission}<code>("modifyThread")</code>,
+     */
+    public ForkJoinPool(int parallelism) {
+        this(parallelism, defaultForkJoinWorkerThreadFactory);
+    }
+
+    /**
+     * Creates a ForkJoinPool with parallelism equal to the number of
+     * processors available on the system and using the given
+     * ForkJoinWorkerThreadFactory,
+     * @param factory the factory for creating new threads
+     * @throws NullPointerException if factory is null
+     * @throws SecurityException if a security manager exists and
+     *         the caller is not permitted to modify threads
+     *         because it does not hold {@link
+     *         java.lang.RuntimePermission}<code>("modifyThread")</code>,
+     */
+    public ForkJoinPool(ForkJoinWorkerThreadFactory factory) {
+        this(Runtime.getRuntime().availableProcessors(), factory);
+    }
+
+    /**
+     * Creates a ForkJoinPool with the given parallelism and factory.
+     *
+     * @param parallelism the targeted number of worker threads
+     * @param factory the factory for creating new threads
+     * @throws IllegalArgumentException if parallelism less than or
+     * equal to zero, or greater than implementation limit.
+     * @throws NullPointerException if factory is null
+     * @throws SecurityException if a security manager exists and
+     *         the caller is not permitted to modify threads
+     *         because it does not hold {@link
+     *         java.lang.RuntimePermission}<code>("modifyThread")</code>,
+     */
+    public ForkJoinPool(int parallelism, ForkJoinWorkerThreadFactory factory) {
+        if (parallelism <= 0 || parallelism > MAX_THREADS)
+            throw new IllegalArgumentException();
+        if (factory == null)
+            throw new NullPointerException();
+        checkPermission();
+        this.factory = factory;
+        this.parallelism = parallelism;
+        this.maxPoolSize = MAX_THREADS;
+        this.maintainsParallelism = true;
+        this.poolNumber = poolNumberGenerator.incrementAndGet();
+        this.workerLock = new ReentrantLock();
+        this.termination = workerLock.newCondition();
+        this.stealCount = new AtomicLong();
+        this.submissionQueue = new LinkedTransferQueue<ForkJoinTask<?>>();
+        // worker array and workers are lazily constructed
+    }
+
+    /**
+     * Create new worker using factory.
+     * @param index the index to assign worker
+     * @return new worker, or null of factory failed
+     */
+    private ForkJoinWorkerThread createWorker(int index) {
+        Thread.UncaughtExceptionHandler h = ueh;
+        ForkJoinWorkerThread w = factory.newThread(this);
+        if (w != null) {
+            w.poolIndex = index;
+            w.setDaemon(true);
+            w.setAsyncMode(locallyFifo);
+            w.setName("ForkJoinPool-" + poolNumber + "-worker-" + index);
+            if (h != null)
+                w.setUncaughtExceptionHandler(h);
+        }
+        return w;
+    }
+
+    /**
+     * Return a good size for worker array given pool size.
+     * Currently requires size to be a power of two.
+     */
+    private static int arraySizeFor(int ps) {
+        return ps <= 1? 1 : (1 << (32 - Integer.numberOfLeadingZeros(ps-1)));
+    }
+
+    public static ForkJoinWorkerThread[] copyOfWorkers(ForkJoinWorkerThread[] original, int newLength) {
+        ForkJoinWorkerThread[] copy = new ForkJoinWorkerThread[newLength];
+        System.arraycopy(original, 0, copy, 0, Math.min(newLength, original.length));
+        return copy;
+    }
+
+    /**
+     * Create or resize array if necessary to hold newLength.
+     * Call only under exlusion or lock
+     * @return the array
+     */
+    private ForkJoinWorkerThread[] ensureWorkerArrayCapacity(int newLength) {
+        ForkJoinWorkerThread[] ws = workers;
+        if (ws == null)
+            return workers = new ForkJoinWorkerThread[arraySizeFor(newLength)];
+        else if (newLength > ws.length)
+            return workers = copyOfWorkers(ws, arraySizeFor(newLength));
+        else
+            return ws;
+    }
+
+    /**
+     * Try to shrink workers into smaller array after one or more terminate
+     */
+    private void tryShrinkWorkerArray() {
+        ForkJoinWorkerThread[] ws = workers;
+        if (ws != null) {
+            int len = ws.length;
+            int last = len - 1;
+            while (last >= 0 && ws[last] == null)
+                --last;
+            int newLength = arraySizeFor(last+1);
+            if (newLength < len)
+                workers = copyOfWorkers(ws, newLength);
+        }
+    }
+
+    /**
+     * Initialize workers if necessary
+     */
+    final void ensureWorkerInitialization() {
+        ForkJoinWorkerThread[] ws = workers;
+        if (ws == null) {
+            final ReentrantLock lock = this.workerLock;
+            lock.lock();
+            try {
+                ws = workers;
+                if (ws == null) {
+                    int ps = parallelism;
+                    ws = ensureWorkerArrayCapacity(ps);
+                    for (int i = 0; i < ps; ++i) {
+                        ForkJoinWorkerThread w = createWorker(i);
+                        if (w != null) {
+                            ws[i] = w;
+                            w.start();
+                            updateWorkerCount(1);
+                        }
+                    }
+                }
+            } finally {
+                lock.unlock();
+            }
+        }
+    }
+
+    /**
+     * Worker creation and startup for threads added via setParallelism.
+     */
+    private void createAndStartAddedWorkers() {
+        resumeAllSpares();  // Allow spares to convert to nonspare
+        int ps = parallelism;
+        ForkJoinWorkerThread[] ws = ensureWorkerArrayCapacity(ps);
+        int len = ws.length;
+        // Sweep through slots, to keep lowest indices most populated
+        int k = 0;
+        while (k < len) {
+            if (ws[k] != null) {
+                ++k;
+                continue;
+            }
+            int s = workerCounts;
+            int tc = totalCountOf(s);
+            int rc = runningCountOf(s);
+            if (rc >= ps || tc >= ps)
+                break;
+            if (casWorkerCounts (s, workerCountsFor(tc+1, rc+1))) {
+                ForkJoinWorkerThread w = createWorker(k);
+                if (w != null) {
+                    ws[k++] = w;
+                    w.start();
+                }
+                else {
+                    updateWorkerCount(-1); // back out on failed creation
+                    break;
+                }
+            }
+        }
+    }
+
+    // Execution methods
+
+    /**
+     * Common code for execute, invoke and submit
+     */
+    private <T> void doSubmit(ForkJoinTask<T> task) {
+        if (isShutdown())
+            throw new RejectedExecutionException();
+        if (workers == null)
+            ensureWorkerInitialization();
+        submissionQueue.offer(task);
+        signalIdleWorkers();
+    }
+
+    /**
+     * Performs the given task; returning its result upon completion
+     * @param task the task
+     * @return the task's result
+     * @throws NullPointerException if task is null
+     * @throws RejectedExecutionException if pool is shut down
+     */
+    public <T> T invoke(ForkJoinTask<T> task) {
+        doSubmit(task);
+        return task.join();
+    }
+
+    /**
+     * Arranges for (asynchronous) execution of the given task.
+     * @param task the task
+     * @throws NullPointerException if task is null
+     * @throws RejectedExecutionException if pool is shut down
+     */
+    public <T> void execute(ForkJoinTask<T> task) {
+        doSubmit(task);
+    }
+
+    // AbstractExecutorService methods
+
+    public void execute(Runnable task) {
+        doSubmit(new AdaptedRunnable<Void>(task, null));
+    }
+
+    public <T> ForkJoinTask<T> submit(Callable<T> task) {
+        ForkJoinTask<T> job = new AdaptedCallable<T>(task);
+        doSubmit(job);
+        return job;
+    }
+
+    public <T> ForkJoinTask<T> submit(Runnable task, T result) {
+        ForkJoinTask<T> job = new AdaptedRunnable<T>(task, result);
+        doSubmit(job);
+        return job;
+    }
+
+    public ForkJoinTask<?> submit(Runnable task) {
+        ForkJoinTask<Void> job = new AdaptedRunnable<Void>(task, null);
+        doSubmit(job);
+        return job;
+    }
+
+    /**
+     * Adaptor for Runnables. This implements RunnableFuture
+     * to be compliant with AbstractExecutorService constraints
+     */
+    static final class AdaptedRunnable<T> extends ForkJoinTask<T>
+        implements RunnableFuture<T> {
+        final Runnable runnable;
+        final T resultOnCompletion;
+        T result;
+        AdaptedRunnable(Runnable runnable, T result) {
+            if (runnable == null) throw new NullPointerException();
+            this.runnable = runnable;
+            this.resultOnCompletion = result;
+        }
+        public T getRawResult() { return result; }
+        public void setRawResult(T v) { result = v; }
+        public boolean exec() {
+            runnable.run();
+            result = resultOnCompletion;
+            return true;
+        }
+        public void run() { invoke(); }
+    }
+
+    /**
+     * Adaptor for Callables
+     */
+    static final class AdaptedCallable<T> extends ForkJoinTask<T>
+        implements RunnableFuture<T> {
+        final Callable<T> callable;
+        T result;
+        AdaptedCallable(Callable<T> callable) {
+            if (callable == null) throw new NullPointerException();
+            this.callable = callable;
+        }
+        public T getRawResult() { return result; }
+        public void setRawResult(T v) { result = v; }
+        public boolean exec() {
+            try {
+                result = callable.call();
+                return true;
+            } catch (Error err) {
+                throw err;
+            } catch (RuntimeException rex) {
+                throw rex;
+            } catch (Exception ex) {
+                throw new RuntimeException(ex);
+            }
+        }
+        public void run() { invoke(); }
+    }
+
+    public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) {
+        ArrayList<ForkJoinTask<T>> ts =
+            new ArrayList<ForkJoinTask<T>>(tasks.size());
+        for (Callable<T> c : tasks)
+            ts.add(new AdaptedCallable<T>(c));
+        invoke(new InvokeAll<T>(ts));
+        return (List<Future<T>>)(List)ts;
+    }
+
+    static final class InvokeAll<T> extends RecursiveAction {
+        final ArrayList<ForkJoinTask<T>> tasks;
+        InvokeAll(ArrayList<ForkJoinTask<T>> tasks) { this.tasks = tasks; }
+        public void compute() {
+            try { invokeAll(tasks); } catch(Exception ignore) {}
+        }
+    }
+
+    // Configuration and status settings and queries
+
+    /**
+     * Returns the factory used for constructing new workers
+     *
+     * @return the factory used for constructing new workers
+     */
+    public ForkJoinWorkerThreadFactory getFactory() {
+        return factory;
+    }
+
+    /**
+     * Returns the handler for internal worker threads that terminate
+     * due to unrecoverable errors encountered while executing tasks.
+     * @return the handler, or null if none
+     */
+    public Thread.UncaughtExceptionHandler getUncaughtExceptionHandler() {
+        Thread.UncaughtExceptionHandler h;
+        final ReentrantLock lock = this.workerLock;
+        lock.lock();
+        try {
+            h = ueh;
+        } finally {
+            lock.unlock();
+        }
+        return h;
+    }
+
+    /**
+     * Sets the handler for internal worker threads that terminate due
+     * to unrecoverable errors encountered while executing tasks.
+     * Unless set, the current default or ThreadGroup handler is used
+     * as handler.
+     *
+     * @param h the new handler
+     * @return the old handler, or null if none
+     * @throws SecurityException if a security manager exists and
+     *         the caller is not permitted to modify threads
+     *         because it does not hold {@link
+     *         java.lang.RuntimePermission}<code>("modifyThread")</code>,
+     */
+    public Thread.UncaughtExceptionHandler
+        setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler h) {
+        checkPermission();
+        Thread.UncaughtExceptionHandler old = null;
+        final ReentrantLock lock = this.workerLock;
+        lock.lock();
+        try {
+            old = ueh;
+            ueh = h;
+            ForkJoinWorkerThread[] ws = workers;
+            if (ws != null) {
+                for (int i = 0; i < ws.length; ++i) {
+                    ForkJoinWorkerThread w = ws[i];
+                    if (w != null)
+                        w.setUncaughtExceptionHandler(h);
+                }
+            }
+        } finally {
+            lock.unlock();
+        }
+        return old;
+    }
+
+
+    /**
+     * Sets the target paralleism level of this pool.
+     * @param parallelism the target parallelism
+     * @throws IllegalArgumentException if parallelism less than or
+     * equal to zero or greater than maximum size bounds.
+     * @throws SecurityException if a security manager exists and
+     *         the caller is not permitted to modify threads
+     *         because it does not hold {@link
+     *         java.lang.RuntimePermission}<code>("modifyThread")</code>,
+     */
+    public void setParallelism(int parallelism) {
+        checkPermission();
+        if (parallelism <= 0 || parallelism > maxPoolSize)
+            throw new IllegalArgumentException();
+        final ReentrantLock lock = this.workerLock;
+        lock.lock();
+        try {
+            if (!isTerminating()) {
+                int p = this.parallelism;
+                this.parallelism = parallelism;
+                if (parallelism > p)
+                    createAndStartAddedWorkers();
+                else
+                    trimSpares();
+            }
+        } finally {
+            lock.unlock();
+        }
+        signalIdleWorkers();
+    }
+
+    /**
+     * Returns the targeted number of worker threads in this pool.
+     *
+     * @return the targeted number of worker threads in this pool
+     */
+    public int getParallelism() {
+        return parallelism;
+    }
+
+    /**
+     * Returns the number of worker threads that have started but not
+     * yet terminated.  This result returned by this method may differ
+     * from <code>getParallelism</code> when threads are created to
+     * maintain parallelism when others are cooperatively blocked.
+     *
+     * @return the number of worker threads
+     */
+    public int getPoolSize() {
+        return totalCountOf(workerCounts);
+    }
+
+    /**
+     * Returns the maximum number of threads allowed to exist in the
+     * pool, even if there are insufficient unblocked running threads.
+     * @return the maximum
+     */
+    public int getMaximumPoolSize() {
+        return maxPoolSize;
+    }
+
+    /**
+     * Sets the maximum number of threads allowed to exist in the
+     * pool, even if there are insufficient unblocked running threads.
+     * Setting this value has no effect on current pool size. It
+     * controls construction of new threads.
+     * @throws IllegalArgumentException if negative or greater then
+     * internal implementation limit.
+     */
+    public void setMaximumPoolSize(int newMax) {
+        if (newMax < 0 || newMax > MAX_THREADS)
+            throw new IllegalArgumentException();
+        maxPoolSize = newMax;
+    }
+
+
+    /**
+     * Returns true if this pool dynamically maintains its target
+     * parallelism level. If false, new threads are added only to
+     * avoid possible starvation.
+     * This setting is by default true;
+     * @return true if maintains parallelism
+     */
+    public boolean getMaintainsParallelism() {
+        return maintainsParallelism;
+    }
+
+    /**
+     * Sets whether this pool dynamically maintains its target
+     * parallelism level. If false, new threads are added only to
+     * avoid possible starvation.
+     * @param enable true to maintains parallelism
+     */
+    public void setMaintainsParallelism(boolean enable) {
+        maintainsParallelism = enable;
+    }
+
+    /**
+     * Establishes local first-in-first-out scheduling mode for forked
+     * tasks that are never joined. This mode may be more appropriate
+     * than default locally stack-based mode in applications in which
+     * worker threads only process asynchronous tasks.  This method is
+     * designed to be invoked only when pool is quiescent, and
+     * typically only before any tasks are submitted. The effects of
+     * invocations at ather times may be unpredictable.
+     *
+     * @param async if true, use locally FIFO scheduling
+     * @return the previous mode.
+     */
+    public boolean setAsyncMode(boolean async) {
+        boolean oldMode = locallyFifo;
+        locallyFifo = async;
+        ForkJoinWorkerThread[] ws = workers;
+        if (ws != null) {
+            for (int i = 0; i < ws.length; ++i) {
+                ForkJoinWorkerThread t = ws[i];
+                if (t != null)
+                    t.setAsyncMode(async);
+            }
+        }
+        return oldMode;
+    }
+
+    /**
+     * Returns true if this pool uses local first-in-first-out
+     * scheduling mode for forked tasks that are never joined. 
+     *
+     * @return true if this pool uses async mode.
+     */
+    public boolean getAsyncMode() {
+        return locallyFifo;
+    }
+
+    /**
+     * Returns an estimate of the number of worker threads that are
+     * not blocked waiting to join tasks or for other managed
+     * synchronization.
+     *
+     * @return the number of worker threads
+     */
+    public int getRunningThreadCount() {
+        return runningCountOf(workerCounts);
+    }
+
+    /**
+     * Returns an estimate of the number of threads that are currently
+     * stealing or executing tasks. This method may overestimate the
+     * number of active threads.
+     * @return the number of active threads.
+     */
+    public int getActiveThreadCount() {
+        return activeCountOf(runControl);
+    }
+
+    /**
+     * Returns an estimate of the number of threads that are currently
+     * idle waiting for tasks. This method may underestimate the
+     * number of idle threads.
+     * @return the number of idle threads.
+     */
+    final int getIdleThreadCount() {
+        int c = runningCountOf(workerCounts) - activeCountOf(runControl);
+        return (c <= 0)? 0 : c;
+    }
+
+    /**
+     * Returns true if all worker threads are currently idle. An idle
+     * worker is one that cannot obtain a task to execute because none
+     * are available to steal from other threads, and there are no
+     * pending submissions to the pool. This method is conservative:
+     * It might not return true immediately upon idleness of all
+     * threads, but will eventually become true if threads remain
+     * inactive.
+     * @return true if all threads are currently idle
+     */
+    public boolean isQuiescent() {
+        return activeCountOf(runControl) == 0;
+    }
+
+    /**
+     * Returns an estimate of the total number of tasks stolen from
+     * one thread's work queue by another. The reported value
+     * underestimates the actual total number of steals when the pool
+     * is not quiescent. This value may be useful for monitoring and
+     * tuning fork/join programs: In general, steal counts should be
+     * high enough to keep threads busy, but low enough to avoid
+     * overhead and contention across threads.
+     * @return the number of steals.
+     */
+    public long getStealCount() {
+        return stealCount.get();
+    }
+
+    /**
+     * Accumulate steal count from a worker. Call only
+     * when worker known to be idle.
+     */
+    private void updateStealCount(ForkJoinWorkerThread w) {
+        int sc = w.getAndClearStealCount();
+        if (sc != 0)
+            stealCount.addAndGet(sc);
+    }
+
+    /**
+     * Returns an estimate of the total number of tasks currently held
+     * in queues by worker threads (but not including tasks submitted
+     * to the pool that have not begun executing). This value is only
+     * an approximation, obtained by iterating across all threads in
+     * the pool. This method may be useful for tuning task
+     * granularities.
+     * @return the number of queued tasks.
+     */
+    public long getQueuedTaskCount() {
+        long count = 0;
+        ForkJoinWorkerThread[] ws = workers;
+        if (ws != null) {
+            for (int i = 0; i < ws.length; ++i) {
+                ForkJoinWorkerThread t = ws[i];
+                if (t != null)
+                    count += t.getQueueSize();
+            }
+        }
+        return count;
+    }
+
+    /**
+     * Returns an estimate of the number tasks submitted to this pool
+     * that have not yet begun executing. This method takes time
+     * proportional to the number of submissions.
+     * @return the number of queued submissions.
+     */
+    public int getQueuedSubmissionCount() {
+        return submissionQueue.size();
+    }
+
+    /**
+     * Returns true if there are any tasks submitted to this pool
+     * that have not yet begun executing.
+     * @return <code>true</code> if there are any queued submissions.
+     */
+    public boolean hasQueuedSubmissions() {
+        return !submissionQueue.isEmpty();
+    }
+
+    /**
+     * Removes and returns the next unexecuted submission if one is
+     * available.  This method may be useful in extensions to this
+     * class that re-assign work in systems with multiple pools.
+     * @return the next submission, or null if none
+     */
+    protected ForkJoinTask<?> pollSubmission() {
+        return submissionQueue.poll();
+    }
+
+    /**
+     * Removes all available unexecuted submitted and forked tasks
+     * from scheduling queues and adds them to the given collection,
+     * without altering their execution status. These may include
+     * artifically generated or wrapped tasks. This method id designed
+     * to be invoked only when the pool is known to be
+     * quiescent. Invocations at other times may not remove all
+     * tasks. A failure encountered while attempting to add elements
+     * to collection <tt>c</tt> may result in elements being in
+     * neither, either or both collections when the associated
+     * exception is thrown.  The behavior of this operation is
+     * undefined if the specified collection is modified while the
+     * operation is in progress.
+     * @param c the collection to transfer elements into
+     * @return the number of elements transferred
+     */
+    protected int drainTasksTo(Collection<ForkJoinTask<?>> c) {
+        int n = submissionQueue.drainTo(c);
+        ForkJoinWorkerThread[] ws = workers;
+        if (ws != null) {
+            for (int i = 0; i < ws.length; ++i) {
+                ForkJoinWorkerThread w = ws[i];
+                if (w != null)
+                    n += w.drainTasksTo(c);
+            }
+        }
+        return n;
+    }
+
+    /**
+     * Returns a string identifying this pool, as well as its state,
+     * including indications of run state, parallelism level, and
+     * worker and task counts.
+     *
+     * @return a string identifying this pool, as well as its state
+     */
+    public String toString() {
+        int ps = parallelism;
+        int wc = workerCounts;
+        int rc = runControl;
+        long st = getStealCount();
+        long qt = getQueuedTaskCount();
+        long qs = getQueuedSubmissionCount();
+        return super.toString() +
+            "[" + runStateToString(runStateOf(rc)) +
+            ", parallelism = " + ps +
+            ", size = " + totalCountOf(wc) +
+            ", active = " + activeCountOf(rc) +
+            ", running = " + runningCountOf(wc) +
+            ", steals = " + st +
+            ", tasks = " + qt +
+            ", submissions = " + qs +
+            "]";
+    }
+
+    private static String runStateToString(int rs) {
+        switch(rs) {
+        case RUNNING: return "Running";
+        case SHUTDOWN: return "Shutting down";
+        case TERMINATING: return "Terminating";
+        case TERMINATED: return "Terminated";
+        default: throw new Error("Unknown run state");
+        }
+    }
+
+    // lifecycle control
+
+    /**
+     * Initiates an orderly shutdown in which previously submitted
+     * tasks are executed, but no new tasks will be accepted.
+     * Invocation has no additional effect if already shut down.
+     * Tasks that are in the process of being submitted concurrently
+     * during the course of this method may or may not be rejected.
+     * @throws SecurityException if a security manager exists and
+     *         the caller is not permitted to modify threads
+     *         because it does not hold {@link
+     *         java.lang.RuntimePermission}<code>("modifyThread")</code>,
+     */
+    public void shutdown() {
+        checkPermission();
+        transitionRunStateTo(SHUTDOWN);
+        if (canTerminateOnShutdown(runControl))
+            terminateOnShutdown();
+    }
+
+    /**
+     * Attempts to stop all actively executing tasks, and cancels all
+     * waiting tasks.  Tasks that are in the process of being
+     * submitted or executed concurrently during the course of this
+     * method may or may not be rejected. Unlike some other executors,
+     * this method cancels rather than collects non-executed tasks
+     * upon termination, so always returns an empty list. However, you
+     * can use method <code>drainTasksTo</code> before invoking this
+     * method to transfer unexecuted tasks to another collection.
+     * @return an empty list
+     * @throws SecurityException if a security manager exists and
+     *         the caller is not permitted to modify threads
+     *         because it does not hold {@link
+     *         java.lang.RuntimePermission}<code>("modifyThread")</code>,
+     */
+    public List<Runnable> shutdownNow() {
+        checkPermission();
+        terminate();
+        return Collections.emptyList();
+    }
+
+    /**
+     * Returns <code>true</code> if all tasks have completed following shut down.
+     *
+     * @return <code>true</code> if all tasks have completed following shut down
+     */
+    public boolean isTerminated() {
+        return runStateOf(runControl) == TERMINATED;
+    }
+
+    /**
+     * Returns <code>true</code> if the process of termination has
+     * commenced but possibly not yet completed.
+     *
+     * @return <code>true</code> if terminating
+     */
+    public boolean isTerminating() {
+        return runStateOf(runControl) >= TERMINATING;
+    }
+
+    /**
+     * Returns <code>true</code> if this pool has been shut down.
+     *
+     * @return <code>true</code> if this pool has been shut down
+     */
+    public boolean isShutdown() {
+        return runStateOf(runControl) >= SHUTDOWN;
+    }
+
+    /**
+     * Blocks until all tasks have completed execution after a shutdown
+     * request, or the timeout occurs, or the current thread is
+     * interrupted, whichever happens first.
+     *
+     * @param timeout the maximum time to wait
+     * @param unit the time unit of the timeout argument
+     * @return <code>true</code> if this executor terminated and
+     *         <code>false</code> if the timeout elapsed before termination
+     * @throws InterruptedException if interrupted while waiting
+     */
+    public boolean awaitTermination(long timeout, TimeUnit unit)
+        throws InterruptedException {
+        long nanos = unit.toNanos(timeout);
+        final ReentrantLock lock = this.workerLock;
+        lock.lock();
+        try {
+            for (;;) {
+                if (isTerminated())
+                    return true;
+                if (nanos <= 0)
+                    return false;
+                nanos = termination.awaitNanos(nanos);
+            }
+        } finally {
+            lock.unlock();
+        }
+    }
+
+    // Shutdown and termination support
+
+    /**
+     * Callback from terminating worker. Null out the corresponding
+     * workers slot, and if terminating, try to terminate, else try to
+     * shrink workers array.
+     * @param w the worker
+     */
+    final void workerTerminated(ForkJoinWorkerThread w) {
+        updateStealCount(w);
+        updateWorkerCount(-1);
+        final ReentrantLock lock = this.workerLock;
+        lock.lock();
+        try {
+            ForkJoinWorkerThread[] ws = workers;
+            if (ws != null) {
+                int idx = w.poolIndex;
+                if (idx >= 0 && idx < ws.length && ws[idx] == w)
+                    ws[idx] = null;
+                if (totalCountOf(workerCounts) == 0) {
+                    terminate(); // no-op if already terminating
+                    transitionRunStateTo(TERMINATED);
+                    termination.signalAll();
+                }
+                else if (!isTerminating()) {
+                    tryShrinkWorkerArray();
+                    tryResumeSpare(true); // allow replacement
+                }
+            }
+        } finally {
+            lock.unlock();
+        }
+        signalIdleWorkers();
+    }
+
+    /**
+     * Initiate termination.
+     */
+    private void terminate() {
+        if (transitionRunStateTo(TERMINATING)) {
+            stopAllWorkers();
+            resumeAllSpares();
+            signalIdleWorkers();
+            cancelQueuedSubmissions();
+            cancelQueuedWorkerTasks();
+            interruptUnterminatedWorkers();
+            signalIdleWorkers(); // resignal after interrupt
+        }
+    }
+
+    /**
+     * Possibly terminate when on shutdown state
+     */
+    private void terminateOnShutdown() {
+        if (!hasQueuedSubmissions() && canTerminateOnShutdown(runControl))
+            terminate();
+    }
+
+    /**
+     * Clear out and cancel submissions
+     */
+    private void cancelQueuedSubmissions() {
+        ForkJoinTask<?> task;
+        while ((task = pollSubmission()) != null)
+            task.cancel(false);
+    }
+
+    /**
+     * Clean out worker queues.
+     */
+    private void cancelQueuedWorkerTasks() {
+        final ReentrantLock lock = this.workerLock;
+        lock.lock();
+        try {
+            ForkJoinWorkerThread[] ws = workers;
+            if (ws != null) {
+                for (int i = 0; i < ws.length; ++i) {
+                    ForkJoinWorkerThread t = ws[i];
+                    if (t != null)
+                        t.cancelTasks();
+                }
+            }
+        } finally {
+            lock.unlock();
+        }
+    }
+
+    /**
+     * Set each worker's status to terminating. Requires lock to avoid
+     * conflicts with add/remove
+     */
+    private void stopAllWorkers() {
+        final ReentrantLock lock = this.workerLock;
+        lock.lock();
+        try {
+            ForkJoinWorkerThread[] ws = workers;
+            if (ws != null) {
+                for (int i = 0; i < ws.length; ++i) {
+                    ForkJoinWorkerThread t = ws[i];
+                    if (t != null)
+                        t.shutdownNow();
+                }
+            }
+        } finally {
+            lock.unlock();
+        }
+    }
+
+    /**
+     * Interrupt all unterminated workers.  This is not required for
+     * sake of internal control, but may help unstick user code during
+     * shutdown.
+     */
+    private void interruptUnterminatedWorkers() {
+        final ReentrantLock lock = this.workerLock;
+        lock.lock();
+        try {
+            ForkJoinWorkerThread[] ws = workers;
+            if (ws != null) {
+                for (int i = 0; i < ws.length; ++i) {
+                    ForkJoinWorkerThread t = ws[i];
+                    if (t != null && !t.isTerminated()) {
+                        try {
+                            t.interrupt();
+                        } catch (SecurityException ignore) {
+                        }
+                    }
+                }
+            }
+        } finally {
+            lock.unlock();
+        }
+    }
+
+
+    /*
+     * Nodes for event barrier to manage idle threads.  Queue nodes
+     * are basic Treiber stack nodes, also used for spare stack.
+     *
+     * The event barrier has an event count and a wait queue (actually
+     * a Treiber stack).  Workers are enabled to look for work when
+     * the eventCount is incremented. If they fail to find work, they
+     * may wait for next count. Upon release, threads help others wake
+     * up.
+     *
+     * Synchronization events occur only in enough contexts to
+     * maintain overall liveness:
+     *
+     *   - Submission of a new task to the pool
+     *   - Resizes or other changes to the workers array
+     *   - pool termination
+     *   - A worker pushing a task on an empty queue
+     *
+     * The case of pushing a task occurs often enough, and is heavy
+     * enough compared to simple stack pushes, to require special
+     * handling: Method signalWork returns without advancing count if
+     * the queue appears to be empty.  This would ordinarily result in
+     * races causing some queued waiters not to be woken up. To avoid
+     * this, the first worker enqueued in method sync (see
+     * syncIsReleasable) rescans for tasks after being enqueued, and
+     * helps signal if any are found. This works well because the
+     * worker has nothing better to do, and so might as well help
+     * alleviate the overhead and contention on the threads actually
+     * doing work.  Also, since event counts increments on task
+     * availability exist to maintain liveness (rather than to force
+     * refreshes etc), it is OK for callers to exit early if
+     * contending with another signaller.
+     */
+    static final class WaitQueueNode {
+        WaitQueueNode next; // only written before enqueued
+        volatile ForkJoinWorkerThread thread; // nulled to cancel wait
+        final long count; // unused for spare stack
+
+        WaitQueueNode(long c, ForkJoinWorkerThread w) {
+            count = c;
+            thread = w;
+        }
+
+        /**
+         * Wake up waiter, returning false if known to already
+         */
+        boolean signal() {
+            ForkJoinWorkerThread t = thread;
+            if (t == null)
+                return false;
+            thread = null;
+            LockSupport.unpark(t);
+            return true;
+        }
+
+        /**
+         * Await release on sync
+         */
+        void awaitSyncRelease(ForkJoinPool p) {
+            while (thread != null && !p.syncIsReleasable(this))
+                LockSupport.park(this);
+        }
+
+        /**
+         * Await resumption as spare
+         */
+        void awaitSpareRelease() {
+            while (thread != null) {
+                if (!Thread.interrupted())
+                    LockSupport.park(this);
+            }
+        }
+    }
+
+    /**
+     * Ensures that no thread is waiting for count to advance from the
+     * current value of eventCount read on entry to this method, by
+     * releasing waiting threads if necessary.
+     * @return the count
+     */
+    final long ensureSync() {
+        long c = eventCount;
+        WaitQueueNode q;
+        while ((q = syncStack) != null && q.count < c) {
+            if (casBarrierStack(q, null)) {
+                do {
+                    q.signal();
+                } while ((q = q.next) != null);
+                break;
+            }
+        }
+        return c;
+    }
+
+    /**
+     * Increments event count and releases waiting threads.
+     */
+    private void signalIdleWorkers() {
+        long c;
+        do;while (!casEventCount(c = eventCount, c+1));
+        ensureSync();
+    }
+
+    /**
+     * Signal threads waiting to poll a task. Because method sync
+     * rechecks availability, it is OK to only proceed if queue
+     * appears to be non-empty, and OK to skip under contention to
+     * increment count (since some other thread succeeded).
+     */
+    final void signalWork() {
+        long c;
+        WaitQueueNode q;
+        if (syncStack != null &&
+            casEventCount(c = eventCount, c+1) &&
+            (((q = syncStack) != null && q.count <= c) &&
+             (!casBarrierStack(q, q.next) || !q.signal())))
+            ensureSync();
+    }
+
+    /**
+     * Waits until event count advances from last value held by
+     * caller, or if excess threads, caller is resumed as spare, or
+     * caller or pool is terminating. Updates caller's event on exit.
+     * @param w the calling worker thread
+     */
+    final void sync(ForkJoinWorkerThread w) {
+        updateStealCount(w); // Transfer w's count while it is idle
+
+        while (!w.isShutdown() && !isTerminating() && !suspendIfSpare(w)) {
+            long prev = w.lastEventCount;
+            WaitQueueNode node = null;
+            WaitQueueNode h;
+            while (eventCount == prev &&
+                   ((h = syncStack) == null || h.count == prev)) {
+                if (node == null)
+                    node = new WaitQueueNode(prev, w);
+                if (casBarrierStack(node.next = h, node)) {
+                    node.awaitSyncRelease(this);
+                    break;
+                }
+            }
+            long ec = ensureSync();
+            if (ec != prev) {
+                w.lastEventCount = ec;
+                break;
+            }
+        }
+    }
+
+    /**
+     * Returns true if worker waiting on sync can proceed:
+     *  - on signal (thread == null)
+     *  - on event count advance (winning race to notify vs signaller)
+     *  - on Interrupt
+     *  - if the first queued node, we find work available
+     * If node was not signalled and event count not advanced on exit,
+     * then we also help advance event count.
+     * @return true if node can be released
+     */
+    final boolean syncIsReleasable(WaitQueueNode node) {
+        long prev = node.count;
+        if (!Thread.interrupted() && node.thread != null &&
+            (node.next != null ||
+             !ForkJoinWorkerThread.hasQueuedTasks(workers)) &&
+            eventCount == prev)
+            return false;
+        if (node.thread != null) {
+            node.thread = null;
+            long ec = eventCount;
+            if (prev <= ec) // help signal
+                casEventCount(ec, ec+1);
+        }
+        return true;
+    }
+
+    /**
+     * Returns true if a new sync event occurred since last call to
+     * sync or this method, if so, updating caller's count.
+     */
+    final boolean hasNewSyncEvent(ForkJoinWorkerThread w) {
+        long lc = w.lastEventCount;
+        long ec = ensureSync();
+        if (ec == lc)
+            return false;
+        w.lastEventCount = ec;
+        return true;
+    }
+
+    //  Parallelism maintenance
+
+    /**
+     * Decrement running count; if too low, add spare.
+     *
+     * Conceptually, all we need to do here is add or resume a
+     * spare thread when one is about to block (and remove or
+     * suspend it later when unblocked -- see suspendIfSpare).
+     * However, implementing this idea requires coping with
+     * several problems: We have imperfect information about the
+     * states of threads. Some count updates can and usually do
+     * lag run state changes, despite arrangements to keep them
+     * accurate (for example, when possible, updating counts
+     * before signalling or resuming), especially when running on
+     * dynamic JVMs that don't optimize the infrequent paths that
+     * update counts. Generating too many threads can make these
+     * problems become worse, because excess threads are more
+     * likely to be context-switched with others, slowing them all
+     * down, especially if there is no work available, so all are
+     * busy scanning or idling.  Also, excess spare threads can
+     * only be suspended or removed when they are idle, not
+     * immediately when they aren't needed. So adding threads will
+     * raise parallelism level for longer than necessary.  Also,
+     * FJ applications often enounter highly transient peaks when
+     * many threads are blocked joining, but for less time than it
+     * takes to create or resume spares.
+     *
+     * @param joinMe if non-null, return early if done
+     * @param maintainParallelism if true, try to stay within
+     * target counts, else create only to avoid starvation
+     * @return true if joinMe known to be done
+     */
+    final boolean preJoin(ForkJoinTask<?> joinMe, boolean maintainParallelism) {
+        maintainParallelism &= maintainsParallelism; // overrride
+        boolean dec = false;  // true when running count decremented
+        while (spareStack == null || !tryResumeSpare(dec)) {
+            int counts = workerCounts;
+            if (dec || (dec = casWorkerCounts(counts, --counts))) { // CAS cheat
+                if (!needSpare(counts, maintainParallelism))
+                    break;
+                if (joinMe.status < 0)
+                    return true;
+                if (tryAddSpare(counts))
+                    break;
+            }
+        }
+        return false;
+    }
+
+    /**
+     * Same idea as preJoin
+     */
+    final boolean preBlock(ManagedBlocker blocker, boolean maintainParallelism){
+        maintainParallelism &= maintainsParallelism;
+        boolean dec = false;
+        while (spareStack == null || !tryResumeSpare(dec)) {
+            int counts = workerCounts;
+            if (dec || (dec = casWorkerCounts(counts, --counts))) {
+                if (!needSpare(counts, maintainParallelism))
+                    break;
+                if (blocker.isReleasable())
+                    return true;
+                if (tryAddSpare(counts))
+                    break;
+            }
+        }
+        return false;
+    }
+
+    /**
+     * Returns true if a spare thread appears to be needed.  If
+     * maintaining parallelism, returns true when the deficit in
+     * running threads is more than the surplus of total threads, and
+     * there is apparently some work to do.  This self-limiting rule
+     * means that the more threads that have already been added, the
+     * less parallelism we will tolerate before adding another.
+     * @param counts current worker counts
+     * @param maintainParallelism try to maintain parallelism
+     */
+    private boolean needSpare(int counts, boolean maintainParallelism) {
+        int ps = parallelism;
+        int rc = runningCountOf(counts);
+        int tc = totalCountOf(counts);
+        int runningDeficit = ps - rc;
+        int totalSurplus = tc - ps;
+        return (tc < maxPoolSize &&
+                (rc == 0 || totalSurplus < 0 ||
+                 (maintainParallelism &&
+                  runningDeficit > totalSurplus &&
+                  ForkJoinWorkerThread.hasQueuedTasks(workers))));
+    }
+
+    /**
+     * Add a spare worker if lock available and no more than the
+     * expected numbers of threads exist
+     * @return true if successful
+     */
+    private boolean tryAddSpare(int expectedCounts) {
+        final ReentrantLock lock = this.workerLock;
+        int expectedRunning = runningCountOf(expectedCounts);
+        int expectedTotal = totalCountOf(expectedCounts);
+        boolean success = false;
+        boolean locked = false;
+        // confirm counts while locking; CAS after obtaining lock
+        try {
+            for (;;) {
+                int s = workerCounts;
+                int tc = totalCountOf(s);
+                int rc = runningCountOf(s);
+                if (rc > expectedRunning || tc > expectedTotal)
+                    break;
+                if (!locked && !(locked = lock.tryLock()))
+                    break;
+                if (casWorkerCounts(s, workerCountsFor(tc+1, rc+1))) {
+                    createAndStartSpare(tc);
+                    success = true;
+                    break;
+                }
+            }
+        } finally {
+            if (locked)
+                lock.unlock();
+        }
+        return success;
+    }
+
+    /**
+     * Add the kth spare worker. On entry, pool coounts are already
+     * adjusted to reflect addition.
+     */
+    private void createAndStartSpare(int k) {
+        ForkJoinWorkerThread w = null;
+        ForkJoinWorkerThread[] ws = ensureWorkerArrayCapacity(k + 1);
+        int len = ws.length;
+        // Probably, we can place at slot k. If not, find empty slot
+        if (k < len && ws[k] != null) {
+            for (k = 0; k < len && ws[k] != null; ++k)
+                ;
+        }
+        if (k < len && !isTerminating() && (w = createWorker(k)) != null) {
+            ws[k] = w;
+            w.start();
+        }
+        else
+            updateWorkerCount(-1); // adjust on failure
+        signalIdleWorkers();
+    }
+
+    /**
+     * Suspend calling thread w if there are excess threads.  Called
+     * only from sync.  Spares are enqueued in a Treiber stack
+     * using the same WaitQueueNodes as barriers.  They are resumed
+     * mainly in preJoin, but are also woken on pool events that
+     * require all threads to check run state.
+     * @param w the caller
+     */
+    private boolean suspendIfSpare(ForkJoinWorkerThread w) {
+        WaitQueueNode node = null;
+        int s;
+        while (parallelism < runningCountOf(s = workerCounts)) {
+            if (node == null)
+                node = new WaitQueueNode(0, w);
+            if (casWorkerCounts(s, s-1)) { // representation-dependent
+                // push onto stack
+                do;while (!casSpareStack(node.next = spareStack, node));
+                // block until released by resumeSpare
+                node.awaitSpareRelease();
+                return true;
+            }
+        }
+        return false;
+    }
+
+    /**
+     * Try to pop and resume a spare thread.
+     * @param updateCount if true, increment running count on success
+     * @return true if successful
+     */
+    private boolean tryResumeSpare(boolean updateCount) {
+        WaitQueueNode q;
+        while ((q = spareStack) != null) {
+            if (casSpareStack(q, q.next)) {
+                if (updateCount)
+                    updateRunningCount(1);
+                q.signal();
+                return true;
+            }
+        }
+        return false;
+    }
+
+    /**
+     * Pop and resume all spare threads. Same idea as ensureSync.
+     * @return true if any spares released
+     */
+    private boolean resumeAllSpares() {
+        WaitQueueNode q;
+        while ( (q = spareStack) != null) {
+            if (casSpareStack(q, null)) {
+                do {
+                    updateRunningCount(1);
+                    q.signal();
+                } while ((q = q.next) != null);
+                return true;
+            }
+        }
+        return false;
+    }
+
+    /**
+     * Pop and shutdown excessive spare threads. Call only while
+     * holding lock. This is not guaranteed to eliminate all excess
+     * threads, only those suspended as spares, which are the ones
+     * unlikely to be needed in the future.
+     */
+    private void trimSpares() {
+        int surplus = totalCountOf(workerCounts) - parallelism;
+        WaitQueueNode q;
+        while (surplus > 0 && (q = spareStack) != null) {
+            if (casSpareStack(q, null)) {
+                do {
+                    updateRunningCount(1);
+                    ForkJoinWorkerThread w = q.thread;
+                    if (w != null && surplus > 0 &&
+                        runningCountOf(workerCounts) > 0 && w.shutdown())
+                        --surplus;
+                    q.signal();
+                } while ((q = q.next) != null);
+            }
+        }
+    }
+
+    /**
+     * Interface for extending managed parallelism for tasks running
+     * in ForkJoinPools. A ManagedBlocker provides two methods.
+     * Method <code>isReleasable</code> must return true if blocking is not
+     * necessary. Method <code>block</code> blocks the current thread
+     * if necessary (perhaps internally invoking isReleasable before
+     * actually blocking.).
+     * <p>For example, here is a ManagedBlocker based on a
+     * ReentrantLock:
+     * <pre>
+     *   class ManagedLocker implements ManagedBlocker {
+     *     final ReentrantLock lock;
+     *     boolean hasLock = false;
+     *     ManagedLocker(ReentrantLock lock) { this.lock = lock; }
+     *     public boolean block() {
+     *        if (!hasLock)
+     *           lock.lock();
+     *        return true;
+     *     }
+     *     public boolean isReleasable() {
+     *        return hasLock || (hasLock = lock.tryLock());
+     *     }
+     *   }
+     * </pre>
+     */
+    public static interface ManagedBlocker {
+        /**
+         * Possibly blocks the current thread, for example waiting for
+         * a lock or condition.
+         * @return true if no additional blocking is necessary (i.e.,
+         * if isReleasable would return true).
+         * @throws InterruptedException if interrupted while waiting
+         * (the method is not required to do so, but is allowe to).
+         */
+        boolean block() throws InterruptedException;
+
+        /**
+         * Returns true if blocking is unnecessary.
+         */
+        boolean isReleasable();
+    }
+
+    /**
+     * Blocks in accord with the given blocker.  If the current thread
+     * is a ForkJoinWorkerThread, this method possibly arranges for a
+     * spare thread to be activated if necessary to ensure parallelism
+     * while the current thread is blocked.  If
+     * <code>maintainParallelism</code> is true and the pool supports
+     * it ({@link #getMaintainsParallelism}), this method attempts to
+     * maintain the pool's nominal parallelism. Otherwise if activates
+     * a thread only if necessary to avoid complete starvation. This
+     * option may be preferable when blockages use timeouts, or are
+     * almost always brief.
+     *
+     * <p> If the caller is not a ForkJoinTask, this method is behaviorally
+     * equivalent to
+     * <pre>
+     *   while (!blocker.isReleasable())
+     *      if (blocker.block())
+     *         return;
+     * </pre>
+     * If the caller is a ForkJoinTask, then the pool may first
+     * be expanded to ensure parallelism, and later adjusted.
+     *
+     * @param blocker the blocker
+     * @param maintainParallelism if true and supported by this pool,
+     * attempt to maintain the pool's nominal parallelism; otherwise
+     * activate a thread only if necessary to avoid complete
+     * starvation.
+     * @throws InterruptedException if blocker.block did so.
+     */
+    public static void managedBlock(ManagedBlocker blocker,
+                                    boolean maintainParallelism)
+        throws InterruptedException {
+        Thread t = Thread.currentThread();
+        ForkJoinPool pool = (t instanceof ForkJoinWorkerThread?
+                             ((ForkJoinWorkerThread)t).pool : null);
+        if (!blocker.isReleasable()) {
+            try {
+                if (pool == null ||
+                    !pool.preBlock(blocker, maintainParallelism))
+                    awaitBlocker(blocker);
+            } finally {
+                if (pool != null)
+                    pool.updateRunningCount(1);
+            }
+        }
+    }
+
+    private static void awaitBlocker(ManagedBlocker blocker)
+        throws InterruptedException {
+        do;while (!blocker.isReleasable() && !blocker.block());
+    }
+
+    // AbstractExecutorService overrides
+
+    protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
+        return new AdaptedRunnable(runnable, value);
+    }
+
+    protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
+        return new AdaptedCallable(callable);
+    }
+
+
+    // Temporary Unsafe mechanics for preliminary release
+    private static Unsafe getUnsafe() throws Throwable {
+        try {
+            return Unsafe.getUnsafe();
+        } catch (SecurityException se) {
+            try {
+                return java.security.AccessController.doPrivileged
+                    (new java.security.PrivilegedExceptionAction<Unsafe>() {
+                        public Unsafe run() throws Exception {
+                            return getUnsafePrivileged();
+                        }});
+            } catch (java.security.PrivilegedActionException e) {
+                throw e.getCause();
+            }
+        }
+    }
+
+    private static Unsafe getUnsafePrivileged()
+            throws NoSuchFieldException, IllegalAccessException {
+        Field f = Unsafe.class.getDeclaredField("theUnsafe");
+        f.setAccessible(true);
+        return (Unsafe) f.get(null);
+    }
+
+    private static long fieldOffset(String fieldName)
+            throws NoSuchFieldException {
+        return _unsafe.objectFieldOffset
+            (ForkJoinPool.class.getDeclaredField(fieldName));
+    }
+
+    static final Unsafe _unsafe;
+    static final long eventCountOffset;
+    static final long workerCountsOffset;
+    static final long runControlOffset;
+    static final long syncStackOffset;
+    static final long spareStackOffset;
+
+    static {
+        try {
+            _unsafe = getUnsafe();
+            eventCountOffset = fieldOffset("eventCount");
+            workerCountsOffset = fieldOffset("workerCounts");
+            runControlOffset = fieldOffset("runControl");
+            syncStackOffset = fieldOffset("syncStack");
+            spareStackOffset = fieldOffset("spareStack");
+        } catch (Throwable e) {
+            throw new RuntimeException("Could not initialize intrinsics", e);
+        }
+    }
+
+    private boolean casEventCount(long cmp, long val) {
+        return _unsafe.compareAndSwapLong(this, eventCountOffset, cmp, val);
+    }
+    private boolean casWorkerCounts(int cmp, int val) {
+        return _unsafe.compareAndSwapInt(this, workerCountsOffset, cmp, val);
+    }
+    private boolean casRunControl(int cmp, int val) {
+        return _unsafe.compareAndSwapInt(this, runControlOffset, cmp, val);
+    }
+    private boolean casSpareStack(WaitQueueNode cmp, WaitQueueNode val) {
+        return _unsafe.compareAndSwapObject(this, spareStackOffset, cmp, val);
+    }
+    private boolean casBarrierStack(WaitQueueNode cmp, WaitQueueNode val) {
+        return _unsafe.compareAndSwapObject(this, syncStackOffset, cmp, val);
+    }
+}
diff --git a/src/forkjoin/scala/concurrent/forkjoin/ForkJoinTask.java b/src/forkjoin/scala/concurrent/forkjoin/ForkJoinTask.java
new file mode 100644
index 0000000..039580a
--- /dev/null
+++ b/src/forkjoin/scala/concurrent/forkjoin/ForkJoinTask.java
@@ -0,0 +1,1063 @@
+/*
+ * Written by Doug Lea with assistance from members of JCP JSR-166
+ * Expert Group and released to the public domain, as explained at
+ * http://creativecommons.org/licenses/publicdomain
+ */
+
+package scala.concurrent.forkjoin;
+import java.io.Serializable;
+import java.util.*;
+import java.util.concurrent.*;
+import java.util.concurrent.atomic.*;
+import sun.misc.Unsafe;
+import java.lang.reflect.*;
+
+/**
+ * Abstract base class for tasks that run within a {@link
+ * ForkJoinPool}.  A ForkJoinTask is a thread-like entity that is much
+ * lighter weight than a normal thread.  Huge numbers of tasks and
+ * subtasks may be hosted by a small number of actual threads in a
+ * ForkJoinPool, at the price of some usage limitations.
+ *
+ * <p> A "main" ForkJoinTask begins execution when submitted to a
+ * {@link ForkJoinPool}. Once started, it will usually in turn start
+ * other subtasks.  As indicated by the name of this class, many
+ * programs using ForkJoinTasks employ only methods <code>fork</code>
+ * and <code>join</code>, or derivatives such as
+ * <code>invokeAll</code>.  However, this class also provides a number
+ * of other methods that can come into play in advanced usages, as
+ * well as extension mechanics that allow support of new forms of
+ * fork/join processing.
+ *
+ * <p>A ForkJoinTask is a lightweight form of {@link Future}.  The
+ * efficiency of ForkJoinTasks stems from a set of restrictions (that
+ * are only partially statically enforceable) reflecting their
+ * intended use as computational tasks calculating pure functions or
+ * operating on purely isolated objects.  The primary coordination
+ * mechanisms are {@link #fork}, that arranges asynchronous execution,
+ * and {@link #join}, that doesn't proceed until the task's result has
+ * been computed.  Computations should avoid <code>synchronized</code>
+ * methods or blocks, and should minimize other blocking
+ * synchronization apart from joining other tasks or using
+ * synchronizers such as Phasers that are advertised to cooperate with
+ * fork/join scheduling. Tasks should also not perform blocking IO,
+ * and should ideally access variables that are completely independent
+ * of those accessed by other running tasks. Minor breaches of these
+ * restrictions, for example using shared output streams, may be
+ * tolerable in practice, but frequent use may result in poor
+ * performance, and the potential to indefinitely stall if the number
+ * of threads not waiting for IO or other external synchronization
+ * becomes exhausted. This usage restriction is in part enforced by
+ * not permitting checked exceptions such as <code>IOExceptions</code>
+ * to be thrown. However, computations may still encounter unchecked
+ * exceptions, that are rethrown to callers attempting join
+ * them. These exceptions may additionally include
+ * RejectedExecutionExceptions stemming from internal resource
+ * exhaustion such as failure to allocate internal task queues.
+ *
+ * <p>The primary method for awaiting completion and extracting
+ * results of a task is {@link #join}, but there are several variants:
+ * The {@link Future#get} methods support interruptible and/or timed
+ * waits for completion and report results using <code>Future</code>
+ * conventions. Method {@link #helpJoin} enables callers to actively
+ * execute other tasks while awaiting joins, which is sometimes more
+ * efficient but only applies when all subtasks are known to be
+ * strictly tree-structured. Method {@link #invoke} is semantically
+ * equivalent to <code>fork(); join()</code> but always attempts to
+ * begin execution in the current thread. The "<em>quiet</em>" forms
+ * of these methods do not extract results or report exceptions. These
+ * may be useful when a set of tasks are being executed, and you need
+ * to delay processing of results or exceptions until all complete.
+ * Method <code>invokeAll</code> (available in multiple versions)
+ * performs the most common form of parallel invocation: forking a set
+ * of tasks and joining them all.
+ *
+ * <p> The ForkJoinTask class is not usually directly subclassed.
+ * Instead, you subclass one of the abstract classes that support a
+ * particular style of fork/join processing.  Normally, a concrete
+ * ForkJoinTask subclass declares fields comprising its parameters,
+ * established in a constructor, and then defines a <code>compute</code>
+ * method that somehow uses the control methods supplied by this base
+ * class. While these methods have <code>public</code> access (to allow
+ * instances of different task subclasses to call each others
+ * methods), some of them may only be called from within other
+ * ForkJoinTasks. Attempts to invoke them in other contexts result in
+ * exceptions or errors possibly including ClassCastException.
+ *
+ * <p>Most base support methods are <code>final</code> because their
+ * implementations are intrinsically tied to the underlying
+ * lightweight task scheduling framework, and so cannot be overridden.
+ * Developers creating new basic styles of fork/join processing should
+ * minimally implement <code>protected</code> methods
+ * <code>exec</code>, <code>setRawResult</code>, and
+ * <code>getRawResult</code>, while also introducing an abstract
+ * computational method that can be implemented in its subclasses,
+ * possibly relying on other <code>protected</code> methods provided
+ * by this class.
+ *
+ * <p>ForkJoinTasks should perform relatively small amounts of
+ * computations, othewise splitting into smaller tasks. As a very
+ * rough rule of thumb, a task should perform more than 100 and less
+ * than 10000 basic computational steps. If tasks are too big, then
+ * parellelism cannot improve throughput. If too small, then memory
+ * and internal task maintenance overhead may overwhelm processing.
+ *
+ * <p>ForkJoinTasks are <code>Serializable</code>, which enables them
+ * to be used in extensions such as remote execution frameworks. It is
+ * in general sensible to serialize tasks only before or after, but
+ * not during execution. Serialization is not relied on during
+ * execution itself.
+ */
+public abstract class ForkJoinTask<V> implements Future<V>, Serializable {
+
+    /**
+     * Run control status bits packed into a single int to minimize
+     * footprint and to ensure atomicity (via CAS).  Status is
+     * initially zero, and takes on nonnegative values until
+     * completed, upon which status holds COMPLETED. CANCELLED, or
+     * EXCEPTIONAL, which use the top 3 bits.  Tasks undergoing
+     * blocking waits by other threads have SIGNAL_MASK bits set --
+     * bit 15 for external (nonFJ) waits, and the rest a count of
+     * waiting FJ threads.  (This representation relies on
+     * ForkJoinPool max thread limits). Completion of a stolen task
+     * with SIGNAL_MASK bits set awakens waiter via notifyAll. Even
+     * though suboptimal for some purposes, we use basic builtin
+     * wait/notify to take advantage of "monitor inflation" in JVMs
+     * that we would otherwise need to emulate to avoid adding further
+     * per-task bookkeeping overhead. Note that bits 16-28 are
+     * currently unused. Also value 0x80000000 is available as spare
+     * completion value.
+     */
+    volatile int status; // accessed directy by pool and workers
+
+    static final int COMPLETION_MASK      = 0xe0000000;
+    static final int NORMAL               = 0xe0000000; // == mask
+    static final int CANCELLED            = 0xc0000000;
+    static final int EXCEPTIONAL          = 0xa0000000;
+    static final int SIGNAL_MASK          = 0x0000ffff;
+    static final int INTERNAL_SIGNAL_MASK = 0x00007fff;
+    static final int EXTERNAL_SIGNAL      = 0x00008000; // top bit of low word
+
+    /**
+     * Table of exceptions thrown by tasks, to enable reporting by
+     * callers. Because exceptions are rare, we don't directly keep
+     * them with task objects, but instead us a weak ref table.  Note
+     * that cancellation exceptions don't appear in the table, but are
+     * instead recorded as status values.
+     * Todo: Use ConcurrentReferenceHashMap
+     */
+    static final Map<ForkJoinTask<?>, Throwable> exceptionMap =
+        Collections.synchronizedMap
+        (new WeakHashMap<ForkJoinTask<?>, Throwable>());
+
+    // within-package utilities
+
+    /**
+     * Get current worker thread, or null if not a worker thread
+     */
+    static ForkJoinWorkerThread getWorker() {
+        Thread t = Thread.currentThread();
+        return ((t instanceof ForkJoinWorkerThread)?
+                (ForkJoinWorkerThread)t : null);
+    }
+
+    final boolean casStatus(int cmp, int val) {
+        return _unsafe.compareAndSwapInt(this, statusOffset, cmp, val);
+    }
+
+    /**
+     * Workaround for not being able to rethrow unchecked exceptions.
+     */
+    static void rethrowException(Throwable ex) {
+        if (ex != null)
+            _unsafe.throwException(ex);
+    }
+
+    // Setting completion status
+
+    /**
+     * Mark completion and wake up threads waiting to join this task.
+     * @param completion one of NORMAL, CANCELLED, EXCEPTIONAL
+     */
+    final void setCompletion(int completion) {
+        ForkJoinPool pool = getPool();
+        if (pool != null) {
+            int s; // Clear signal bits while setting completion status
+            do;while ((s = status) >= 0 && !casStatus(s, completion));
+
+            if ((s & SIGNAL_MASK) != 0) {
+                if ((s &= INTERNAL_SIGNAL_MASK) != 0)
+                    pool.updateRunningCount(s);
+                synchronized(this) { notifyAll(); }
+            }
+        }
+        else
+            externallySetCompletion(completion);
+    }
+
+    /**
+     * Version of setCompletion for non-FJ threads.  Leaves signal
+     * bits for unblocked threads to adjust, and always notifies.
+     */
+    private void externallySetCompletion(int completion) {
+        int s;
+        do;while ((s = status) >= 0 &&
+                  !casStatus(s, (s & SIGNAL_MASK) | completion));
+        synchronized(this) { notifyAll(); }
+    }
+
+    /**
+     * Sets status to indicate normal completion
+     */
+    final void setNormalCompletion() {
+        // Try typical fast case -- single CAS, no signal, not already done.
+        // Manually expand casStatus to improve chances of inlining it
+        if (!_unsafe.compareAndSwapInt(this, statusOffset, 0, NORMAL))
+            setCompletion(NORMAL);
+    }
+
+    // internal waiting and notification
+
+    /**
+     * Performs the actual monitor wait for awaitDone
+     */
+    private void doAwaitDone() {
+        // Minimize lock bias and in/de-flation effects by maximizing
+        // chances of waiting inside sync
+        try {
+            while (status >= 0)
+                synchronized(this) { if (status >= 0) wait(); }
+        } catch (InterruptedException ie) {
+            onInterruptedWait();
+        }
+    }
+
+    /**
+     * Performs the actual monitor wait for awaitDone
+     */
+    private void doAwaitDone(long startTime, long nanos) {
+        synchronized(this) {
+            try {
+                while (status >= 0) {
+                    long nt = nanos - System.nanoTime() - startTime;
+                    if (nt <= 0)
+                        break;
+                    wait(nt / 1000000, (int)(nt % 1000000));
+                }
+            } catch (InterruptedException ie) {
+                onInterruptedWait();
+            }
+        }
+    }
+
+    // Awaiting completion
+
+    /**
+     * Sets status to indicate there is joiner, then waits for join,
+     * surrounded with pool notifications.
+     * @return status upon exit
+     */
+    private int awaitDone(ForkJoinWorkerThread w, boolean maintainParallelism) {
+        ForkJoinPool pool = w == null? null : w.pool;
+        int s;
+        while ((s = status) >= 0) {
+            if (casStatus(s, pool == null? s|EXTERNAL_SIGNAL : s+1)) {
+                if (pool == null || !pool.preJoin(this, maintainParallelism))
+                    doAwaitDone();
+                if (((s = status) & INTERNAL_SIGNAL_MASK) != 0)
+                    adjustPoolCountsOnUnblock(pool);
+                break;
+            }
+        }
+        return s;
+    }
+
+    /**
+     * Timed version of awaitDone
+     * @return status upon exit
+     */
+    private int awaitDone(ForkJoinWorkerThread w, long nanos) {
+        ForkJoinPool pool = w == null? null : w.pool;
+        int s;
+        while ((s = status) >= 0) {
+            if (casStatus(s, pool == null? s|EXTERNAL_SIGNAL : s+1)) {
+                long startTime = System.nanoTime();
+                if (pool == null || !pool.preJoin(this, false))
+                    doAwaitDone(startTime, nanos);
+                if ((s = status) >= 0) {
+                    adjustPoolCountsOnCancelledWait(pool);
+                    s = status;
+                }
+                if (s < 0 && (s & INTERNAL_SIGNAL_MASK) != 0)
+                    adjustPoolCountsOnUnblock(pool);
+                break;
+            }
+        }
+        return s;
+    }
+
+    /**
+     * Notify pool that thread is unblocked. Called by signalled
+     * threads when woken by non-FJ threads (which is atypical).
+     */
+    private void adjustPoolCountsOnUnblock(ForkJoinPool pool) {
+        int s;
+        do;while ((s = status) < 0 && !casStatus(s, s & COMPLETION_MASK));
+        if (pool != null && (s &= INTERNAL_SIGNAL_MASK) != 0)
+            pool.updateRunningCount(s);
+    }
+
+    /**
+     * Notify pool to adjust counts on cancelled or timed out wait
+     */
+    private void adjustPoolCountsOnCancelledWait(ForkJoinPool pool) {
+        if (pool != null) {
+            int s;
+            while ((s = status) >= 0 && (s & INTERNAL_SIGNAL_MASK) != 0) {
+                if (casStatus(s, s - 1)) {
+                    pool.updateRunningCount(1);
+                    break;
+                }
+            }
+        }
+    }
+
+    /**
+     * Handle interruptions during waits.
+     */
+    private void onInterruptedWait() {
+        ForkJoinWorkerThread w = getWorker();
+        if (w == null)
+            Thread.currentThread().interrupt(); // re-interrupt
+        else if (w.isTerminating())
+            cancelIgnoringExceptions();
+        // else if FJworker, ignore interrupt
+    }
+
+    // Recording and reporting exceptions
+
+    private void setDoneExceptionally(Throwable rex) {
+        exceptionMap.put(this, rex);
+        setCompletion(EXCEPTIONAL);
+    }
+
+    /**
+     * Throws the exception associated with status s;
+     * @throws the exception
+     */
+    private void reportException(int s) {
+        if ((s &= COMPLETION_MASK) < NORMAL) {
+            if (s == CANCELLED)
+                throw new CancellationException();
+            else
+                rethrowException(exceptionMap.get(this));
+        }
+    }
+
+    /**
+     * Returns result or throws exception using j.u.c.Future conventions
+     * Only call when isDone known to be true.
+     */
+    private V reportFutureResult()
+        throws ExecutionException, InterruptedException {
+        int s = status & COMPLETION_MASK;
+        if (s < NORMAL) {
+            Throwable ex;
+            if (s == CANCELLED)
+                throw new CancellationException();
+            if (s == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null)
+                throw new ExecutionException(ex);
+            if (Thread.interrupted())
+                throw new InterruptedException();
+        }
+        return getRawResult();
+    }
+
+    /**
+     * Returns result or throws exception using j.u.c.Future conventions
+     * with timeouts
+     */
+    private V reportTimedFutureResult()
+        throws InterruptedException, ExecutionException, TimeoutException {
+        Throwable ex;
+        int s = status & COMPLETION_MASK;
+        if (s == NORMAL)
+            return getRawResult();
+        if (s == CANCELLED)
+            throw new CancellationException();
+        if (s == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null)
+            throw new ExecutionException(ex);
+        if (Thread.interrupted())
+            throw new InterruptedException();
+        throw new TimeoutException();
+    }
+
+    // internal execution methods
+
+    /**
+     * Calls exec, recording completion, and rethrowing exception if
+     * encountered. Caller should normally check status before calling
+     * @return true if completed normally
+     */
+    private boolean tryExec() {
+        try { // try block must contain only call to exec
+            if (!exec())
+                return false;
+        } catch (Throwable rex) {
+            setDoneExceptionally(rex);
+            rethrowException(rex);
+            return false; // not reached
+        }
+        setNormalCompletion();
+        return true;
+    }
+
+    /**
+     * Main execution method used by worker threads. Invokes
+     * base computation unless already complete
+     */
+    final void quietlyExec() {
+        if (status >= 0) {
+            try {
+                if (!exec())
+                    return;
+            } catch(Throwable rex) {
+                setDoneExceptionally(rex);
+                return;
+            }
+            setNormalCompletion();
+        }
+    }
+
+    /**
+     * Calls exec, recording but not rethrowing exception
+     * Caller should normally check status before calling
+     * @return true if completed normally
+     */
+    private boolean tryQuietlyInvoke() {
+        try {
+            if (!exec())
+                return false;
+        } catch (Throwable rex) {
+            setDoneExceptionally(rex);
+            return false;
+        }
+        setNormalCompletion();
+        return true;
+    }
+
+    /**
+     * Cancel, ignoring any exceptions it throws
+     */
+    final void cancelIgnoringExceptions() {
+        try {
+            cancel(false);
+        } catch(Throwable ignore) {
+        }
+    }
+
+    /**
+     * Main implementation of helpJoin
+     */
+    private int busyJoin(ForkJoinWorkerThread w) {
+        int s;
+        ForkJoinTask<?> t;
+        while ((s = status) >= 0 && (t = w.scanWhileJoining(this)) != null)
+            t.quietlyExec();
+        return (s >= 0)? awaitDone(w, false) : s; // block if no work
+    }
+
+    // public methods
+
+    /**
+     * Arranges to asynchronously execute this task.  While it is not
+     * necessarily enforced, it is a usage error to fork a task more
+     * than once unless it has completed and been reinitialized.  This
+     * method may be invoked only from within ForkJoinTask
+     * computations. Attempts to invoke in other contexts result in
+     * exceptions or errors possibly including ClassCastException.
+     */
+    public final void fork() {
+        ((ForkJoinWorkerThread)(Thread.currentThread())).pushTask(this);
+    }
+
+    /**
+     * Returns the result of the computation when it is ready.
+     * This method differs from <code>get</code> in that abnormal
+     * completion results in RuntimeExceptions or Errors, not
+     * ExecutionExceptions.
+     *
+     * @return the computed result
+     */
+    public final V join() {
+        ForkJoinWorkerThread w = getWorker();
+        if (w == null || status < 0 || !w.unpushTask(this) || !tryExec())
+            reportException(awaitDone(w, true));
+        return getRawResult();
+    }
+
+    /**
+     * Commences performing this task, awaits its completion if
+     * necessary, and return its result.
+     * @throws Throwable (a RuntimeException, Error, or unchecked
+     * exception) if the underlying computation did so.
+     * @return the computed result
+     */
+    public final V invoke() {
+        if (status >= 0 && tryExec())
+            return getRawResult();
+        else
+            return join();
+    }
+
+    /**
+     * Forks both tasks, returning when <code>isDone</code> holds for
+     * both of them or an exception is encountered. This method may be
+     * invoked only from within ForkJoinTask computations. Attempts to
+     * invoke in other contexts result in exceptions or errors
+     * possibly including ClassCastException.
+     * @param t1 one task
+     * @param t2 the other task
+     * @throws NullPointerException if t1 or t2 are null
+     * @throws RuntimeException or Error if either task did so.
+     */
+    public static void invokeAll(ForkJoinTask<?>t1, ForkJoinTask<?> t2) {
+        t2.fork();
+        t1.invoke();
+        t2.join();
+    }
+
+    /**
+     * Forks the given tasks, returning when <code>isDone</code> holds
+     * for all of them. If any task encounters an exception, others
+     * may be cancelled.  This method may be invoked only from within
+     * ForkJoinTask computations. Attempts to invoke in other contexts
+     * result in exceptions or errors possibly including ClassCastException.
+     * @param tasks the array of tasks
+     * @throws NullPointerException if tasks or any element are null.
+     * @throws RuntimeException or Error if any task did so.
+     */
+    public static void invokeAll(ForkJoinTask<?>... tasks) {
+        Throwable ex = null;
+        int last = tasks.length - 1;
+        for (int i = last; i >= 0; --i) {
+            ForkJoinTask<?> t = tasks[i];
+            if (t == null) {
+                if (ex == null)
+                    ex = new NullPointerException();
+            }
+            else if (i != 0)
+                t.fork();
+            else {
+                t.quietlyInvoke();
+                if (ex == null)
+                    ex = t.getException();
+            }
+        }
+        for (int i = 1; i <= last; ++i) {
+            ForkJoinTask<?> t = tasks[i];
+            if (t != null) {
+                if (ex != null)
+                    t.cancel(false);
+                else {
+                    t.quietlyJoin();
+                    if (ex == null)
+                        ex = t.getException();
+                }
+            }
+        }
+        if (ex != null)
+            rethrowException(ex);
+    }
+
+    /**
+     * Forks all tasks in the collection, returning when
+     * <code>isDone</code> holds for all of them. If any task
+     * encounters an exception, others may be cancelled.  This method
+     * may be invoked only from within ForkJoinTask
+     * computations. Attempts to invoke in other contexts resul!t in
+     * exceptions or errors possibly including ClassCastException.
+     * @param tasks the collection of tasks
+     * @throws NullPointerException if tasks or any element are null.
+     * @throws RuntimeException or Error if any task did so.
+     */
+    public static void invokeAll(Collection<? extends ForkJoinTask<?>> tasks) {
+        if (!(tasks instanceof List)) {
+            invokeAll(tasks.toArray(new ForkJoinTask[tasks.size()]));
+            return;
+        }
+        List<? extends ForkJoinTask<?>> ts =
+            (List<? extends ForkJoinTask<?>>)tasks;
+        Throwable ex = null;
+        int last = ts.size() - 1;
+        for (int i = last; i >= 0; --i) {
+            ForkJoinTask<?> t = ts.get(i);
+            if (t == null) {
+                if (ex == null)
+                    ex = new NullPointerException();
+            }
+            else if (i != 0)
+                t.fork();
+            else {
+                t.quietlyInvoke();
+                if (ex == null)
+                    ex = t.getException();
+            }
+        }
+        for (int i = 1; i <= last; ++i) {
+            ForkJoinTask<?> t = ts.get(i);
+            if (t != null) {
+                if (ex != null)
+                    t.cancel(false);
+                else {
+                    t.quietlyJoin();
+                    if (ex == null)
+                        ex = t.getException();
+                }
+            }
+        }
+        if (ex != null)
+            rethrowException(ex);
+    }
+
+    /**
+     * Returns true if the computation performed by this task has
+     * completed (or has been cancelled).
+     * @return true if this computation has completed
+     */
+    public final boolean isDone() {
+        return status < 0;
+    }
+
+    /**
+     * Returns true if this task was cancelled.
+     * @return true if this task was cancelled
+     */
+    public final boolean isCancelled() {
+        return (status & COMPLETION_MASK) == CANCELLED;
+    }
+
+    /**
+     * Asserts that the results of this task's computation will not be
+     * used. If a cancellation occurs before atempting to execute this
+     * task, then execution will be suppressed, <code>isCancelled</code>
+     * will report true, and <code>join</code> will result in a
+     * <code>CancellationException</code> being thrown. Otherwise, when
+     * cancellation races with completion, there are no guarantees
+     * about whether <code>isCancelled</code> will report true, whether
+     * <code>join</code> will return normally or via an exception, or
+     * whether these behaviors will remain consistent upon repeated
+     * invocation.
+     *
+     * <p>This method may be overridden in subclasses, but if so, must
+     * still ensure that these minimal properties hold. In particular,
+     * the cancel method itself must not throw exceptions.
+     *
+     * <p> This method is designed to be invoked by <em>other</em>
+     * tasks. To terminate the current task, you can just return or
+     * throw an unchecked exception from its computation method, or
+     * invoke <code>completeExceptionally</code>.
+     *
+     * @param mayInterruptIfRunning this value is ignored in the
+     * default implementation because tasks are not in general
+     * cancelled via interruption.
+     *
+     * @return true if this task is now cancelled
+     */
+    public boolean cancel(boolean mayInterruptIfRunning) {
+        setCompletion(CANCELLED);
+        return (status & COMPLETION_MASK) == CANCELLED;
+    }
+
+    /**
+     * Returns true if this task threw an exception or was cancelled
+     * @return true if this task threw an exception or was cancelled
+     */
+    public final boolean isCompletedAbnormally() {
+        return (status & COMPLETION_MASK) < NORMAL;
+    }
+
+    /**
+     * Returns the exception thrown by the base computation, or a
+     * CancellationException if cancelled, or null if none or if the
+     * method has not yet completed.
+     * @return the exception, or null if none
+     */
+    public final Throwable getException() {
+        int s = status & COMPLETION_MASK;
+        if (s >= NORMAL)
+            return null;
+        if (s == CANCELLED)
+            return new CancellationException();
+        return exceptionMap.get(this);
+    }
+
+    /**
+     * Completes this task abnormally, and if not already aborted or
+     * cancelled, causes it to throw the given exception upon
+     * <code>join</code> and related operations. This method may be used
+     * to induce exceptions in asynchronous tasks, or to force
+     * completion of tasks that would not otherwise complete.  Its use
+     * in other situations is likely to be wrong.  This method is
+     * overridable, but overridden versions must invoke <code>super</code>
+     * implementation to maintain guarantees.
+     *
+     * @param ex the exception to throw. If this exception is
+     * not a RuntimeException or Error, the actual exception thrown
+     * will be a RuntimeException with cause ex.
+     */
+    public void completeExceptionally(Throwable ex) {
+        setDoneExceptionally((ex instanceof RuntimeException) ||
+                             (ex instanceof Error)? ex :
+                             new RuntimeException(ex));
+    }
+
+    /**
+     * Completes this task, and if not already aborted or cancelled,
+     * returning a <code>null</code> result upon <code>join</code> and related
+     * operations. This method may be used to provide results for
+     * asynchronous tasks, or to provide alternative handling for
+     * tasks that would not otherwise complete normally. Its use in
+     * other situations is likely to be wrong. This method is
+     * overridable, but overridden versions must invoke <code>super</code>
+     * implementation to maintain guarantees.
+     *
+     * @param value the result value for this task.
+     */
+    public void complete(V value) {
+        try {
+            setRawResult(value);
+        } catch(Throwable rex) {
+            setDoneExceptionally(rex);
+            return;
+        }
+        setNormalCompletion();
+    }
+
+    public final V get() throws InterruptedException, ExecutionException {
+        ForkJoinWorkerThread w = getWorker();
+        if (w == null || status < 0 || !w.unpushTask(this) || !tryQuietlyInvoke())
+            awaitDone(w, true);
+        return reportFutureResult();
+    }
+
+    public final V get(long timeout, TimeUnit unit)
+        throws InterruptedException, ExecutionException, TimeoutException {
+        ForkJoinWorkerThread w = getWorker();
+        if (w == null || status < 0 || !w.unpushTask(this) || !tryQuietlyInvoke())
+            awaitDone(w, unit.toNanos(timeout));
+        return reportTimedFutureResult();
+    }
+
+    /**
+     * Possibly executes other tasks until this task is ready, then
+     * returns the result of the computation.  This method may be more
+     * efficient than <code>join</code>, but is only applicable when
+     * there are no potemtial dependencies between continuation of the
+     * current task and that of any other task that might be executed
+     * while helping. (This usually holds for pure divide-and-conquer
+     * tasks). This method may be invoked only from within
+     * ForkJoinTask computations. Attempts to invoke in other contexts
+     * resul!t in exceptions or errors possibly including ClassCastException.
+     * @return the computed result
+     */
+    public final V helpJoin() {
+        ForkJoinWorkerThread w = (ForkJoinWorkerThread)(Thread.currentThread());
+        if (status < 0 || !w.unpushTask(this) || !tryExec())
+            reportException(busyJoin(w));
+        return getRawResult();
+    }
+
+    /**
+     * Possibly executes other tasks until this task is ready.  This
+     * method may be invoked only from within ForkJoinTask
+     * computations. Attempts to invoke in other contexts resul!t in
+     * exceptions or errors possibly including ClassCastException.
+     */
+    public final void quietlyHelpJoin() {
+        if (status >= 0) {
+            ForkJoinWorkerThread w =
+                (ForkJoinWorkerThread)(Thread.currentThread());
+            if (!w.unpushTask(this) || !tryQuietlyInvoke())
+                busyJoin(w);
+        }
+    }
+
+    /**
+     * Joins this task, without returning its result or throwing an
+     * exception. This method may be useful when processing
+     * collections of tasks when some have been cancelled or otherwise
+     * known to have aborted.
+     */
+    public final void quietlyJoin() {
+        if (status >= 0) {
+            ForkJoinWorkerThread w = getWorker();
+            if (w == null || !w.unpushTask(this) || !tryQuietlyInvoke())
+                awaitDone(w, true);
+        }
+    }
+
+    /**
+     * Commences performing this task and awaits its completion if
+     * necessary, without returning its result or throwing an
+     * exception. This method may be useful when processing
+     * collections of tasks when some have been cancelled or otherwise
+     * known to have aborted.
+     */
+    public final void quietlyInvoke() {
+        if (status >= 0 && !tryQuietlyInvoke())
+            quietlyJoin();
+    }
+
+    /**
+     * Possibly executes tasks until the pool hosting the current task
+     * {@link ForkJoinPool#isQuiescent}. This method may be of use in
+     * designs in which many tasks are forked, but none are explicitly
+     * joined, instead executing them until all are processed.
+     */
+    public static void helpQuiesce() {
+        ((ForkJoinWorkerThread)(Thread.currentThread())).
+            helpQuiescePool();
+    }
+
+    /**
+     * Resets the internal bookkeeping state of this task, allowing a
+     * subsequent <code>fork</code>. This method allows repeated reuse of
+     * this task, but only if reuse occurs when this task has either
+     * never been forked, or has been forked, then completed and all
+     * outstanding joins of this task have also completed. Effects
+     * under any other usage conditions are not guaranteed, and are
+     * almost surely wrong. This method may be useful when executing
+     * pre-constructed trees of subtasks in loops.
+     */
+    public void reinitialize() {
+        if ((status & COMPLETION_MASK) == EXCEPTIONAL)
+            exceptionMap.remove(this);
+        status = 0;
+    }
+
+    /**
+     * Returns the pool hosting the current task execution, or null
+     * if this task is executing outside of any pool.
+     * @return the pool, or null if none.
+     */
+    public static ForkJoinPool getPool() {
+        Thread t = Thread.currentThread();
+        return ((t instanceof ForkJoinWorkerThread)?
+                ((ForkJoinWorkerThread)t).pool : null);
+    }
+
+    /**
+     * Tries to unschedule this task for execution. This method will
+     * typically succeed if this task is the most recently forked task
+     * by the current thread, and has not commenced executing in
+     * another thread.  This method may be useful when arranging
+     * alternative local processing of tasks that could have been, but
+     * were not, stolen. This method may be invoked only from within
+     * ForkJoinTask computations. Attempts to invoke in other contexts
+     * result in exceptions or errors possibly including ClassCastException.
+     * @return true if unforked
+     */
+    public boolean tryUnfork() {
+        return ((ForkJoinWorkerThread)(Thread.currentThread())).unpushTask(this);
+    }
+
+    /**
+     * Returns an estimate of the number of tasks that have been
+     * forked by the current worker thread but not yet executed. This
+     * value may be useful for heuristic decisions about whether to
+     * fork other tasks.
+     * @return the number of tasks
+     */
+    public static int getQueuedTaskCount() {
+        return ((ForkJoinWorkerThread)(Thread.currentThread())).
+            getQueueSize();
+    }
+
+    /**
+     * Returns a estimate of how many more locally queued tasks are
+     * held by the current worker thread than there are other worker
+     * threads that might steal them.  This value may be useful for
+     * heuristic decisions about whether to fork other tasks. In many
+     * usages of ForkJoinTasks, at steady state, each worker should
+     * aim to maintain a small constant surplus (for example, 3) of
+     * tasks, and to process computations locally if this threshold is
+     * exceeded.
+     * @return the surplus number of tasks, which may be negative
+     */
+    public static int getSurplusQueuedTaskCount() {
+        return ((ForkJoinWorkerThread)(Thread.currentThread()))
+            .getEstimatedSurplusTaskCount();
+    }
+
+    // Extension methods
+
+    /**
+     * Returns the result that would be returned by <code>join</code>,
+     * even if this task completed abnormally, or null if this task is
+     * not known to have been completed.  This method is designed to
+     * aid debugging, as well as to support extensions. Its use in any
+     * other context is discouraged.
+     *
+     * @return the result, or null if not completed.
+     */
+    public abstract V getRawResult();
+
+    /**
+     * Forces the given value to be returned as a result.  This method
+     * is designed to support extensions, and should not in general be
+     * called otherwise.
+     *
+     * @param value the value
+     */
+    protected abstract void setRawResult(V value);
+
+    /**
+     * Immediately performs the base action of this task.  This method
+     * is designed to support extensions, and should not in general be
+     * called otherwise. The return value controls whether this task
+     * is considered to be done normally. It may return false in
+     * asynchronous actions that require explicit invocations of
+     * <code>complete</code> to become joinable. It may throw exceptions
+     * to indicate abnormal exit.
+     * @return true if completed normally
+     * @throws Error or RuntimeException if encountered during computation
+     */
+    protected abstract boolean exec();
+
+    /**
+     * Returns, but does not unschedule or execute, the task queued by
+     * the current thread but not yet executed, if one is
+     * available. There is no guarantee that this task will actually
+     * be polled or executed next.  This method is designed primarily
+     * to support extensions, and is unlikely to be useful otherwise.
+     * This method may be invoked only from within ForkJoinTask
+     * computations. Attempts to invoke in other contexts result in
+     * exceptions or errors possibly including ClassCastException.
+     *
+     * @return the next task, or null if none are available
+     */
+    protected static ForkJoinTask<?> peekNextLocalTask() {
+        return ((ForkJoinWorkerThread)(Thread.currentThread())).peekTask();
+    }
+
+    /**
+     * Unschedules and returns, without executing, the next task
+     * queued by the current thread but not yet executed.  This method
+     * is designed primarily to support extensions, and is unlikely to
+     * be useful otherwise.  This method may be invoked only from
+     * within ForkJoinTask computations. Attempts to invoke in other
+     * contexts result in exceptions or errors possibly including
+     * ClassCastException.
+     *
+     * @return the next task, or null if none are available
+     */
+    protected static ForkJoinTask<?> pollNextLocalTask() {
+        return ((ForkJoinWorkerThread)(Thread.currentThread())).pollLocalTask();
+    }
+    
+    /**
+     * Unschedules and returns, without executing, the next task
+     * queued by the current thread but not yet executed, if one is
+     * available, or if not available, a task that was forked by some
+     * other thread, if available. Availability may be transient, so a
+     * <code>null</code> result does not necessarily imply quiecence
+     * of the pool this task is operating in.  This method is designed
+     * primarily to support extensions, and is unlikely to be useful
+     * otherwise.  This method may be invoked only from within
+     * ForkJoinTask computations. Attempts to invoke in other contexts
+     * result in exceptions or errors possibly including
+     * ClassCastException.
+     *
+     * @return a task, or null if none are available
+     */
+    protected static ForkJoinTask<?> pollTask() {
+        return ((ForkJoinWorkerThread)(Thread.currentThread())).
+            pollTask();
+    }
+
+    // Serialization support
+
+    private static final long serialVersionUID = -7721805057305804111L;
+
+    /**
+     * Save the state to a stream.
+     *
+     * @serialData the current run status and the exception thrown
+     * during execution, or null if none.
+     * @param s the stream
+     */
+    private void writeObject(java.io.ObjectOutputStream s)
+        throws java.io.IOException {
+        s.defaultWriteObject();
+        s.writeObject(getException());
+    }
+
+    /**
+     * Reconstitute the instance from a stream.
+     * @param s the stream
+     */
+    private void readObject(java.io.ObjectInputStream s)
+        throws java.io.IOException, ClassNotFoundException {
+        s.defaultReadObject();
+        status &= ~INTERNAL_SIGNAL_MASK; // clear internal signal counts
+        status |= EXTERNAL_SIGNAL; // conservatively set external signal
+        Object ex = s.readObject();
+        if (ex != null)
+            setDoneExceptionally((Throwable)ex);
+    }
+
+    // Temporary Unsafe mechanics for preliminary release
+    private static Unsafe getUnsafe() throws Throwable {
+        try {
+            return Unsafe.getUnsafe();
+        } catch (SecurityException se) {
+            try {
+                return java.security.AccessController.doPrivileged
+                    (new java.security.PrivilegedExceptionAction<Unsafe>() {
+                        public Unsafe run() throws Exception {
+                            return getUnsafePrivileged();
+                        }});
+            } catch (java.security.PrivilegedActionException e) {
+                throw e.getCause();
+            }
+        }
+    }
+
+    private static Unsafe getUnsafePrivileged()
+            throws NoSuchFieldException, IllegalAccessException {
+        Field f = Unsafe.class.getDeclaredField("theUnsafe");
+        f.setAccessible(true);
+        return (Unsafe) f.get(null);
+    }
+
+    private static long fieldOffset(String fieldName, Unsafe unsafe)
+            throws NoSuchFieldException {
+        // do not use _unsafe to avoid NPE
+        return unsafe.objectFieldOffset
+            (ForkJoinTask.class.getDeclaredField(fieldName));
+    }
+
+    static final Unsafe _unsafe;
+    static final long statusOffset;
+
+    static {
+        Unsafe tmpUnsafe = null;
+        long tmpStatusOffset = 0;
+        try {
+            tmpUnsafe = getUnsafe();
+            tmpStatusOffset = fieldOffset("status", tmpUnsafe);
+        } catch (Throwable e) {
+            // Ignore the failure to load sun.misc.Unsafe on Android so
+            // that platform can use the actor library without the
+            // fork/join scheduler.
+            String vmVendor = System.getProperty("java.vm.vendor");
+            if (!vmVendor.contains("Android")) {
+	        throw new RuntimeException("Could not initialize intrinsics", e);
+            }
+        }
+        _unsafe = tmpUnsafe;
+	statusOffset = tmpStatusOffset;
+    }
+
+}
diff --git a/src/forkjoin/scala/concurrent/forkjoin/ForkJoinWorkerThread.java b/src/forkjoin/scala/concurrent/forkjoin/ForkJoinWorkerThread.java
new file mode 100644
index 0000000..2432b28
--- /dev/null
+++ b/src/forkjoin/scala/concurrent/forkjoin/ForkJoinWorkerThread.java
@@ -0,0 +1,773 @@
+/*
+ * Written by Doug Lea with assistance from members of JCP JSR-166
+ * Expert Group and released to the public domain, as explained at
+ * http://creativecommons.org/licenses/publicdomain
+ */
+
+package scala.concurrent.forkjoin;
+import java.util.*;
+import java.util.concurrent.*;
+import java.util.concurrent.atomic.*;
+import java.util.concurrent.locks.*;
+import sun.misc.Unsafe;
+import java.lang.reflect.*;
+
+/**
+ * A thread managed by a {@link ForkJoinPool}.  This class is
+ * subclassable solely for the sake of adding functionality -- there
+ * are no overridable methods dealing with scheduling or
+ * execution. However, you can override initialization and termination
+ * methods surrounding the main task processing loop.  If you do
+ * create such a subclass, you will also need to supply a custom
+ * ForkJoinWorkerThreadFactory to use it in a ForkJoinPool.
+ *
+ */
+public class ForkJoinWorkerThread extends Thread {
+    /*
+     * Algorithm overview:
+     *
+     * 1. Work-Stealing: Work-stealing queues are special forms of
+     * Deques that support only three of the four possible
+     * end-operations -- push, pop, and deq (aka steal), and only do
+     * so under the constraints that push and pop are called only from
+     * the owning thread, while deq may be called from other threads.
+     * (If you are unfamiliar with them, you probably want to read
+     * Herlihy and Shavit's book "The Art of Multiprocessor
+     * programming", chapter 16 describing these in more detail before
+     * proceeding.)  The main work-stealing queue design is roughly
+     * similar to "Dynamic Circular Work-Stealing Deque" by David
+     * Chase and Yossi Lev, SPAA 2005
+     * (http://research.sun.com/scalable/pubs/index.html).  The main
+     * difference ultimately stems from gc requirements that we null
+     * out taken slots as soon as we can, to maintain as small a
+     * footprint as possible even in programs generating huge numbers
+     * of tasks. To accomplish this, we shift the CAS arbitrating pop
+     * vs deq (steal) from being on the indices ("base" and "sp") to
+     * the slots themselves (mainly via method "casSlotNull()"). So,
+     * both a successful pop and deq mainly entail CAS'ing a nonnull
+     * slot to null.  Because we rely on CASes of references, we do
+     * not need tag bits on base or sp.  They are simple ints as used
+     * in any circular array-based queue (see for example ArrayDeque).
+     * Updates to the indices must still be ordered in a way that
+     * guarantees that (sp - base) > 0 means the queue is empty, but
+     * otherwise may err on the side of possibly making the queue
+     * appear nonempty when a push, pop, or deq have not fully
+     * committed. Note that this means that the deq operation,
+     * considered individually, is not wait-free. One thief cannot
+     * successfully continue until another in-progress one (or, if
+     * previously empty, a push) completes.  However, in the
+     * aggregate, we ensure at least probablistic non-blockingness. If
+     * an attempted steal fails, a thief always chooses a different
+     * random victim target to try next. So, in order for one thief to
+     * progress, it suffices for any in-progress deq or new push on
+     * any empty queue to complete. One reason this works well here is
+     * that apparently-nonempty often means soon-to-be-stealable,
+     * which gives threads a chance to activate if necessary before
+     * stealing (see below).
+     *
+     * Efficient implementation of this approach currently relies on
+     * an uncomfortable amount of "Unsafe" mechanics. To maintain
+     * correct orderings, reads and writes of variable base require
+     * volatile ordering.  Variable sp does not require volatile write
+     * but needs cheaper store-ordering on writes.  Because they are
+     * protected by volatile base reads, reads of the queue array and
+     * its slots do not need volatile load semantics, but writes (in
+     * push) require store order and CASes (in pop and deq) require
+     * (volatile) CAS semantics. Since these combinations aren't
+     * supported using ordinary volatiles, the only way to accomplish
+     * these effciently is to use direct Unsafe calls. (Using external
+     * AtomicIntegers and AtomicReferenceArrays for the indices and
+     * array is significantly slower because of memory locality and
+     * indirection effects.) Further, performance on most platforms is
+     * very sensitive to placement and sizing of the (resizable) queue
+     * array.  Even though these queues don't usually become all that
+     * big, the initial size must be large enough to counteract cache
+     * contention effects across multiple queues (especially in the
+     * presence of GC cardmarking). Also, to improve thread-locality,
+     * queues are currently initialized immediately after the thread
+     * gets the initial signal to start processing tasks.  However,
+     * all queue-related methods except pushTask are written in a way
+     * that allows them to instead be lazily allocated and/or disposed
+     * of when empty. All together, these low-level implementation
+     * choices produce as much as a factor of 4 performance
+     * improvement compared to naive implementations, and enable the
+     * processing of billions of tasks per second, sometimes at the
+     * expense of ugliness.
+     *
+     * 2. Run control: The primary run control is based on a global
+     * counter (activeCount) held by the pool. It uses an algorithm
+     * similar to that in Herlihy and Shavit section 17.6 to cause
+     * threads to eventually block when all threads declare they are
+     * inactive. (See variable "scans".)  For this to work, threads
+     * must be declared active when executing tasks, and before
+     * stealing a task. They must be inactive before blocking on the
+     * Pool Barrier (awaiting a new submission or other Pool
+     * event). In between, there is some free play which we take
+     * advantage of to avoid contention and rapid flickering of the
+     * global activeCount: If inactive, we activate only if a victim
+     * queue appears to be nonempty (see above).  Similarly, a thread
+     * tries to inactivate only after a full scan of other threads.
+     * The net effect is that contention on activeCount is rarely a
+     * measurable performance issue. (There are also a few other cases
+     * where we scan for work rather than retry/block upon
+     * contention.)
+     *
+     * 3. Selection control. We maintain policy of always choosing to
+     * run local tasks rather than stealing, and always trying to
+     * steal tasks before trying to run a new submission. All steals
+     * are currently performed in randomly-chosen deq-order. It may be
+     * worthwhile to bias these with locality / anti-locality
+     * information, but doing this well probably requires more
+     * lower-level information from JVMs than currently provided.
+     */
+
+    /**
+     * Capacity of work-stealing queue array upon initialization.
+     * Must be a power of two. Initial size must be at least 2, but is
+     * padded to minimize cache effects.
+     */
+    private static final int INITIAL_QUEUE_CAPACITY = 1 << 13;
+
+    /**
+     * Maximum work-stealing queue array size.  Must be less than or
+     * equal to 1 << 28 to ensure lack of index wraparound. (This
+     * is less than usual bounds, because we need leftshift by 3
+     * to be in int range).
+     */
+    private static final int MAXIMUM_QUEUE_CAPACITY = 1 << 28;
+
+    /**
+     * The pool this thread works in. Accessed directly by ForkJoinTask
+     */
+    final ForkJoinPool pool;
+
+    /**
+     * The work-stealing queue array. Size must be a power of two.
+     * Initialized when thread starts, to improve memory locality.
+     */
+    private ForkJoinTask<?>[] queue;
+
+    /**
+     * Index (mod queue.length) of next queue slot to push to or pop
+     * from. It is written only by owner thread, via ordered store.
+     * Both sp and base are allowed to wrap around on overflow, but
+     * (sp - base) still estimates size.
+     */
+    private volatile int sp;
+
+    /**
+     * Index (mod queue.length) of least valid queue slot, which is
+     * always the next position to steal from if nonempty.
+     */
+    private volatile int base;
+
+    /**
+     * Activity status. When true, this worker is considered active.
+     * Must be false upon construction. It must be true when executing
+     * tasks, and BEFORE stealing a task. It must be false before
+     * calling pool.sync
+     */
+    private boolean active;
+
+    /**
+     * Run state of this worker. Supports simple versions of the usual
+     * shutdown/shutdownNow control.
+     */
+    private volatile int runState;
+
+    /**
+     * Seed for random number generator for choosing steal victims.
+     * Uses Marsaglia xorshift. Must be nonzero upon initialization.
+     */
+    private int seed;
+
+    /**
+     * Number of steals, transferred to pool when idle
+     */
+    private int stealCount;
+
+    /**
+     * Index of this worker in pool array. Set once by pool before
+     * running, and accessed directly by pool during cleanup etc
+     */
+    int poolIndex;
+
+    /**
+     * The last barrier event waited for. Accessed in pool callback
+     * methods, but only by current thread.
+     */
+    long lastEventCount;
+
+    /**
+     * True if use local fifo, not default lifo, for local polling
+     */
+    private boolean locallyFifo;
+
+    /**
+     * Creates a ForkJoinWorkerThread operating in the given pool.
+     * @param pool the pool this thread works in
+     * @throws NullPointerException if pool is null
+     */
+    protected ForkJoinWorkerThread(ForkJoinPool pool) {
+        if (pool == null) throw new NullPointerException();
+        this.pool = pool;
+        // Note: poolIndex is set by pool during construction
+        // Remaining initialization is deferred to onStart
+    }
+
+    // Public access methods
+
+    /**
+     * Returns the pool hosting this thread
+     * @return the pool
+     */
+    public ForkJoinPool getPool() {
+        return pool;
+    }
+
+    /**
+     * Returns the index number of this thread in its pool.  The
+     * returned value ranges from zero to the maximum number of
+     * threads (minus one) that have ever been created in the pool.
+     * This method may be useful for applications that track status or
+     * collect results per-worker rather than per-task.
+     * @return the index number.
+     */
+    public int getPoolIndex() {
+        return poolIndex;
+    }
+
+    /**
+     * Establishes local first-in-first-out scheduling mode for forked
+     * tasks that are never joined. 
+     * @param async if true, use locally FIFO scheduling
+     */
+    void setAsyncMode(boolean async) {
+        locallyFifo = async;
+    }
+
+    // Runstate management
+
+    // Runstate values. Order matters
+    private static final int RUNNING     = 0;
+    private static final int SHUTDOWN    = 1;
+    private static final int TERMINATING = 2;
+    private static final int TERMINATED  = 3;
+
+    final boolean isShutdown()    { return runState >= SHUTDOWN;  }
+    final boolean isTerminating() { return runState >= TERMINATING;  }
+    final boolean isTerminated()  { return runState == TERMINATED; }
+    final boolean shutdown()      { return transitionRunStateTo(SHUTDOWN); }
+    final boolean shutdownNow()   { return transitionRunStateTo(TERMINATING); }
+
+    /**
+     * Transition to at least the given state. Return true if not
+     * already at least given state.
+     */
+    private boolean transitionRunStateTo(int state) {
+        for (;;) {
+            int s = runState;
+            if (s >= state)
+                return false;
+            if (_unsafe.compareAndSwapInt(this, runStateOffset, s, state))
+                return true;
+        }
+    }
+
+    /**
+     * Try to set status to active; fail on contention
+     */
+    private boolean tryActivate() {
+        if (!active) {
+            if (!pool.tryIncrementActiveCount())
+                return false;
+            active = true;
+        }
+        return true;
+    }
+
+    /**
+     * Try to set status to active; fail on contention
+     */
+    private boolean tryInactivate() {
+        if (active) {
+            if (!pool.tryDecrementActiveCount())
+                return false;
+            active = false;
+        }
+        return true;
+    }
+
+    /**
+     * Computes next value for random victim probe. Scans don't
+     * require a very high quality generator, but also not a crummy
+     * one. Marsaglia xor-shift is cheap and works well.
+     */
+    private static int xorShift(int r) {
+        r ^= r << 1;
+        r ^= r >>> 3;
+        r ^= r << 10;
+        return r;
+    }
+
+    // Lifecycle methods
+
+    /**
+     * This method is required to be public, but should never be
+     * called explicitly. It performs the main run loop to execute
+     * ForkJoinTasks.
+     */
+    public void run() {
+        Throwable exception = null;
+        try {
+            onStart();
+            pool.sync(this); // await first pool event
+            mainLoop();
+        } catch (Throwable ex) {
+            exception = ex;
+        } finally {
+            onTermination(exception);
+        }
+    }
+
+    /**
+     * Execute tasks until shut down.
+     */
+    private void mainLoop() {
+        while (!isShutdown()) {
+            ForkJoinTask<?> t = pollTask();
+            if (t != null || (t = pollSubmission()) != null)
+                t.quietlyExec();
+            else if (tryInactivate())
+                pool.sync(this);
+        }
+    }
+
+    /**
+     * Initializes internal state after construction but before
+     * processing any tasks. If you override this method, you must
+     * invoke super.onStart() at the beginning of the method.
+     * Initialization requires care: Most fields must have legal
+     * default values, to ensure that attempted accesses from other
+     * threads work correctly even before this thread starts
+     * processing tasks.
+     */
+    protected void onStart() {
+        // Allocate while starting to improve chances of thread-local
+        // isolation
+        queue = new ForkJoinTask<?>[INITIAL_QUEUE_CAPACITY];
+        // Initial value of seed need not be especially random but
+        // should differ across workers and must be nonzero
+        int p = poolIndex + 1;
+        seed = p + (p << 8) + (p << 16) + (p << 24); // spread bits
+    }
+
+    /**
+     * Perform cleanup associated with termination of this worker
+     * thread.  If you override this method, you must invoke
+     * super.onTermination at the end of the overridden method.
+     *
+     * @param exception the exception causing this thread to abort due
+     * to an unrecoverable error, or null if completed normally.
+     */
+    protected void onTermination(Throwable exception) {
+        // Execute remaining local tasks unless aborting or terminating
+        while (exception == null &&  !pool.isTerminating() && base != sp) {
+            try {
+                ForkJoinTask<?> t = popTask();
+                if (t != null)
+                    t.quietlyExec();
+            } catch(Throwable ex) {
+                exception = ex;
+            }
+        }
+        // Cancel other tasks, transition status, notify pool, and
+        // propagate exception to uncaught exception handler
+        try {
+            do;while (!tryInactivate()); // ensure inactive
+            cancelTasks();
+            runState = TERMINATED;
+            pool.workerTerminated(this);
+        } catch (Throwable ex) {        // Shouldn't ever happen
+            if (exception == null)      // but if so, at least rethrown
+                exception = ex;
+        } finally {
+            if (exception != null)
+                ForkJoinTask.rethrowException(exception);
+        }
+    }
+
+    // Intrinsics-based support for queue operations.
+
+    /**
+     * Add in store-order the given task at given slot of q to
+     * null. Caller must ensure q is nonnull and index is in range.
+     */
+    private static void setSlot(ForkJoinTask<?>[] q, int i,
+                                ForkJoinTask<?> t){
+        _unsafe.putOrderedObject(q, (i << qShift) + qBase, t);
+    }
+
+    /**
+     * CAS given slot of q to null. Caller must ensure q is nonnull
+     * and index is in range.
+     */
+    private static boolean casSlotNull(ForkJoinTask<?>[] q, int i,
+                                       ForkJoinTask<?> t) {
+        return _unsafe.compareAndSwapObject(q, (i << qShift) + qBase, t, null);
+    }
+
+    /**
+     * Sets sp in store-order.
+     */
+    private void storeSp(int s) {
+        _unsafe.putOrderedInt(this, spOffset, s);
+    }
+
+    // Main queue methods
+
+    /**
+     * Pushes a task. Called only by current thread.
+     * @param t the task. Caller must ensure nonnull
+     */
+    final void pushTask(ForkJoinTask<?> t) {
+        ForkJoinTask<?>[] q = queue;
+        int mask = q.length - 1;
+        int s = sp;
+        setSlot(q, s & mask, t);
+        storeSp(++s);
+        if ((s -= base) == 1)
+            pool.signalWork();
+        else if (s >= mask)
+            growQueue();
+    }
+
+    /**
+     * Tries to take a task from the base of the queue, failing if
+     * either empty or contended.
+     * @return a task, or null if none or contended.
+     */
+    final ForkJoinTask<?> deqTask() {
+        ForkJoinTask<?> t;
+        ForkJoinTask<?>[] q;
+        int i;
+        int b;
+        if (sp != (b = base) &&
+            (q = queue) != null && // must read q after b
+            (t = q[i = (q.length - 1) & b]) != null &&
+            casSlotNull(q, i, t)) {
+            base = b + 1;
+            return t;
+        }
+        return null;
+    }
+
+    /**
+     * Returns a popped task, or null if empty. Ensures active status
+     * if nonnull. Called only by current thread.
+     */
+    final ForkJoinTask<?> popTask() {
+        int s = sp;
+        while (s != base) {
+            if (tryActivate()) {
+                ForkJoinTask<?>[] q = queue;
+                int mask = q.length - 1;
+                int i = (s - 1) & mask;
+                ForkJoinTask<?> t = q[i];
+                if (t == null || !casSlotNull(q, i, t))
+                    break;
+                storeSp(s - 1);
+                return t;
+            }
+        }
+        return null;
+    }
+
+    /**
+     * Specialized version of popTask to pop only if
+     * topmost element is the given task. Called only
+     * by current thread while active.
+     * @param t the task. Caller must ensure nonnull
+     */
+    final boolean unpushTask(ForkJoinTask<?> t) {
+        ForkJoinTask<?>[] q = queue;
+        int mask = q.length - 1;
+        int s = sp - 1;
+        if (casSlotNull(q, s & mask, t)) {
+            storeSp(s);
+            return true;
+        }
+        return false;
+    }
+
+    /**
+     * Returns next task.
+     */
+    final ForkJoinTask<?> peekTask() {
+        ForkJoinTask<?>[] q = queue;
+        if (q == null)
+            return null;
+        int mask = q.length - 1;
+        int i = locallyFifo? base : (sp - 1);
+        return q[i & mask];
+    }
+
+    /**
+     * Doubles queue array size. Transfers elements by emulating
+     * steals (deqs) from old array and placing, oldest first, into
+     * new array.
+     */
+    private void growQueue() {
+        ForkJoinTask<?>[] oldQ = queue;
+        int oldSize = oldQ.length;
+        int newSize = oldSize << 1;
+        if (newSize > MAXIMUM_QUEUE_CAPACITY)
+            throw new RejectedExecutionException("Queue capacity exceeded");
+        ForkJoinTask<?>[] newQ = queue = new ForkJoinTask<?>[newSize];
+
+        int b = base;
+        int bf = b + oldSize;
+        int oldMask = oldSize - 1;
+        int newMask = newSize - 1;
+        do {
+            int oldIndex = b & oldMask;
+            ForkJoinTask<?> t = oldQ[oldIndex];
+            if (t != null && !casSlotNull(oldQ, oldIndex, t))
+                t = null;
+            setSlot(newQ, b & newMask, t);
+        } while (++b != bf);
+        pool.signalWork();
+    }
+
+    /**
+     * Tries to steal a task from another worker. Starts at a random
+     * index of workers array, and probes workers until finding one
+     * with non-empty queue or finding that all are empty.  It
+     * randomly selects the first n probes. If these are empty, it
+     * resorts to a full circular traversal, which is necessary to
+     * accurately set active status by caller. Also restarts if pool
+     * events occurred since last scan, which forces refresh of
+     * workers array, in case barrier was associated with resize.
+     *
+     * This method must be both fast and quiet -- usually avoiding
+     * memory accesses that could disrupt cache sharing etc other than
+     * those needed to check for and take tasks. This accounts for,
+     * among other things, updating random seed in place without
+     * storing it until exit.
+     *
+     * @return a task, or null if none found
+     */
+    private ForkJoinTask<?> scan() {
+        ForkJoinTask<?> t = null;
+        int r = seed;                    // extract once to keep scan quiet
+        ForkJoinWorkerThread[] ws;       // refreshed on outer loop
+        int mask;                        // must be power 2 minus 1 and > 0
+        outer:do {
+            if ((ws = pool.workers) != null && (mask = ws.length - 1) > 0) {
+                int idx = r;
+                int probes = ~mask;      // use random index while negative
+                for (;;) {
+                    r = xorShift(r);     // update random seed
+                    ForkJoinWorkerThread v = ws[mask & idx];
+                    if (v == null || v.sp == v.base) {
+                        if (probes <= mask)
+                            idx = (probes++ < 0)? r : (idx + 1);
+                        else
+                            break;
+                    }
+                    else if (!tryActivate() || (t = v.deqTask()) == null)
+                        continue outer;  // restart on contention
+                    else
+                        break outer;
+                }
+            }
+        } while (pool.hasNewSyncEvent(this)); // retry on pool events
+        seed = r;
+        return t;
+    }
+
+    /**
+     * gets and removes a local or stolen a task
+     * @return a task, if available
+     */
+    final ForkJoinTask<?> pollTask() {
+        ForkJoinTask<?> t = locallyFifo? deqTask() : popTask();
+        if (t == null && (t = scan()) != null)
+            ++stealCount;
+        return t;
+    }
+
+    /**
+     * gets a local task
+     * @return a task, if available
+     */
+    final ForkJoinTask<?> pollLocalTask() {
+        return locallyFifo? deqTask() : popTask();
+    }
+
+    /**
+     * Returns a pool submission, if one exists, activating first.
+     * @return a submission, if available
+     */
+    private ForkJoinTask<?> pollSubmission() {
+        ForkJoinPool p = pool;
+        while (p.hasQueuedSubmissions()) {
+            ForkJoinTask<?> t;
+            if (tryActivate() && (t = p.pollSubmission()) != null)
+                return t;
+        }
+        return null;
+    }
+
+    // Methods accessed only by Pool
+
+    /**
+     * Removes and cancels all tasks in queue.  Can be called from any
+     * thread.
+     */
+    final void cancelTasks() {
+        ForkJoinTask<?> t;
+        while (base != sp && (t = deqTask()) != null)
+            t.cancelIgnoringExceptions();
+    }
+
+    /**
+     * Drains tasks to given collection c
+     * @return the number of tasks drained
+     */
+    final int drainTasksTo(Collection<ForkJoinTask<?>> c) {
+        int n = 0;
+        ForkJoinTask<?> t;
+        while (base != sp && (t = deqTask()) != null) {
+            c.add(t);
+            ++n;
+        }
+        return n;
+    }
+
+    /**
+     * Get and clear steal count for accumulation by pool.  Called
+     * only when known to be idle (in pool.sync and termination).
+     */
+    final int getAndClearStealCount() {
+        int sc = stealCount;
+        stealCount = 0;
+        return sc;
+    }
+
+    /**
+     * Returns true if at least one worker in the given array appears
+     * to have at least one queued task.
+     * @param ws array of workers
+     */
+    static boolean hasQueuedTasks(ForkJoinWorkerThread[] ws) {
+        if (ws != null) {
+            int len = ws.length;
+            for (int j = 0; j < 2; ++j) { // need two passes for clean sweep
+                for (int i = 0; i < len; ++i) {
+                    ForkJoinWorkerThread w = ws[i];
+                    if (w != null && w.sp != w.base)
+                        return true;
+                }
+            }
+        }
+        return false;
+    }
+
+    // Support methods for ForkJoinTask
+
+    /**
+     * Returns an estimate of the number of tasks in the queue.
+     */
+    final int getQueueSize() {
+        int n = sp - base;
+        return n < 0? 0 : n; // suppress momentarily negative values
+    }
+
+    /**
+     * Returns an estimate of the number of tasks, offset by a
+     * function of number of idle workers.
+     */
+    final int getEstimatedSurplusTaskCount() {
+        // The halving approximates weighting idle vs non-idle workers
+        return (sp - base) - (pool.getIdleThreadCount() >>> 1);
+    }
+
+    /**
+     * Scan, returning early if joinMe done
+     */
+    final ForkJoinTask<?> scanWhileJoining(ForkJoinTask<?> joinMe) {
+        ForkJoinTask<?> t = pollTask();
+        if (t != null && joinMe.status < 0 && sp == base) {
+            pushTask(t); // unsteal if done and this task would be stealable
+            t = null;
+        }
+        return t;
+    }
+
+    /**
+     * Runs tasks until pool isQuiescent
+     */
+    final void helpQuiescePool() {
+        for (;;) {
+            ForkJoinTask<?> t = pollTask();
+            if (t != null)
+                t.quietlyExec();
+            else if (tryInactivate() && pool.isQuiescent())
+                break;
+        }
+        do;while (!tryActivate()); // re-activate on exit
+    }
+
+    // Temporary Unsafe mechanics for preliminary release
+    private static Unsafe getUnsafe() throws Throwable {
+        try {
+            return Unsafe.getUnsafe();
+        } catch (SecurityException se) {
+            try {
+                return java.security.AccessController.doPrivileged
+                    (new java.security.PrivilegedExceptionAction<Unsafe>() {
+                        public Unsafe run() throws Exception {
+                            return getUnsafePrivileged();
+                        }});
+            } catch (java.security.PrivilegedActionException e) {
+                throw e.getCause();
+            }
+        }
+    }
+
+    private static Unsafe getUnsafePrivileged()
+            throws NoSuchFieldException, IllegalAccessException {
+        Field f = Unsafe.class.getDeclaredField("theUnsafe");
+        f.setAccessible(true);
+        return (Unsafe) f.get(null);
+    }
+
+    private static long fieldOffset(String fieldName)
+            throws NoSuchFieldException {
+        return _unsafe.objectFieldOffset
+            (ForkJoinWorkerThread.class.getDeclaredField(fieldName));
+    }
+
+    static final Unsafe _unsafe;
+    static final long baseOffset;
+    static final long spOffset;
+    static final long runStateOffset;
+    static final long qBase;
+    static final int qShift;
+    static {
+        try {
+            _unsafe = getUnsafe();
+            baseOffset = fieldOffset("base");
+            spOffset = fieldOffset("sp");
+            runStateOffset = fieldOffset("runState");
+            qBase = _unsafe.arrayBaseOffset(ForkJoinTask[].class);
+            int s = _unsafe.arrayIndexScale(ForkJoinTask[].class);
+            if ((s & (s-1)) != 0)
+                throw new Error("data type scale not a power of two");
+            qShift = 31 - Integer.numberOfLeadingZeros(s);
+        } catch (Throwable e) {
+            throw new RuntimeException("Could not initialize intrinsics", e);
+        }
+    }
+}
diff --git a/src/forkjoin/scala/concurrent/forkjoin/LinkedTransferQueue.java b/src/forkjoin/scala/concurrent/forkjoin/LinkedTransferQueue.java
new file mode 100644
index 0000000..3b46c17
--- /dev/null
+++ b/src/forkjoin/scala/concurrent/forkjoin/LinkedTransferQueue.java
@@ -0,0 +1,840 @@
+/*
+ * Written by Doug Lea with assistance from members of JCP JSR-166
+ * Expert Group and released to the public domain, as explained at
+ * http://creativecommons.org/licenses/publicdomain
+ */
+
+package scala.concurrent.forkjoin;
+import java.util.concurrent.*;
+import java.util.concurrent.locks.*;
+import java.util.concurrent.atomic.*;
+import java.util.*;
+import java.io.*;
+import sun.misc.Unsafe;
+import java.lang.reflect.*;
+
+/**
+ * An unbounded {@linkplain TransferQueue} based on linked nodes.
+ * This queue orders elements FIFO (first-in-first-out) with respect
+ * to any given producer.  The <em>head</em> of the queue is that
+ * element that has been on the queue the longest time for some
+ * producer.  The <em>tail</em> of the queue is that element that has
+ * been on the queue the shortest time for some producer.
+ *
+ * <p>Beware that, unlike in most collections, the {@code size}
+ * method is <em>NOT</em> a constant-time operation. Because of the
+ * asynchronous nature of these queues, determining the current number
+ * of elements requires a traversal of the elements.
+ *
+ * <p>This class and its iterator implement all of the
+ * <em>optional</em> methods of the {@link Collection} and {@link
+ * Iterator} interfaces.
+ *
+ * <p>Memory consistency effects: As with other concurrent
+ * collections, actions in a thread prior to placing an object into a
+ * {@code LinkedTransferQueue}
+ * <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a>
+ * actions subsequent to the access or removal of that element from
+ * the {@code LinkedTransferQueue} in another thread.
+ *
+ * <p>This class is a member of the
+ * <a href="{@docRoot}/../technotes/guides/collections/index.html">
+ * Java Collections Framework</a>.
+ *
+ * @since 1.7
+ * @author Doug Lea
+ * @param <E> the type of elements held in this collection
+ *
+ */
+public class LinkedTransferQueue<E> extends AbstractQueue<E>
+    implements TransferQueue<E>, java.io.Serializable {
+    private static final long serialVersionUID = -3223113410248163686L;
+
+    /*
+     * This class extends the approach used in FIFO-mode
+     * SynchronousQueues. See the internal documentation, as well as
+     * the PPoPP 2006 paper "Scalable Synchronous Queues" by Scherer,
+     * Lea & Scott
+     * (http://www.cs.rice.edu/~wns1/papers/2006-PPoPP-SQ.pdf)
+     *
+     * The main extension is to provide different Wait modes for the
+     * main "xfer" method that puts or takes items.  These don't
+     * impact the basic dual-queue logic, but instead control whether
+     * or how threads block upon insertion of request or data nodes
+     * into the dual queue. It also uses slightly different
+     * conventions for tracking whether nodes are off-list or
+     * cancelled.
+     */
+
+    // Wait modes for xfer method
+    static final int NOWAIT  = 0;
+    static final int TIMEOUT = 1;
+    static final int WAIT    = 2;
+
+    /** The number of CPUs, for spin control */
+    static final int NCPUS = Runtime.getRuntime().availableProcessors();
+
+    /**
+     * The number of times to spin before blocking in timed waits.
+     * The value is empirically derived -- it works well across a
+     * variety of processors and OSes. Empirically, the best value
+     * seems not to vary with number of CPUs (beyond 2) so is just
+     * a constant.
+     */
+    static final int maxTimedSpins = (NCPUS < 2)? 0 : 32;
+
+    /**
+     * The number of times to spin before blocking in untimed waits.
+     * This is greater than timed value because untimed waits spin
+     * faster since they don't need to check times on each spin.
+     */
+    static final int maxUntimedSpins = maxTimedSpins * 16;
+
+    /**
+     * The number of nanoseconds for which it is faster to spin
+     * rather than to use timed park. A rough estimate suffices.
+     */
+    static final long spinForTimeoutThreshold = 1000L;
+
+    /**
+     * Node class for LinkedTransferQueue. Opportunistically
+     * subclasses from AtomicReference to represent item. Uses Object,
+     * not E, to allow setting item to "this" after use, to avoid
+     * garbage retention. Similarly, setting the next field to this is
+     * used as sentinel that node is off list.
+     */
+    static final class QNode extends AtomicReference<Object> {
+        volatile QNode next;
+        volatile Thread waiter;       // to control park/unpark
+        final boolean isData;
+        QNode(Object item, boolean isData) {
+            super(item);
+            this.isData = isData;
+        }
+
+        static final AtomicReferenceFieldUpdater<QNode, QNode>
+            nextUpdater = AtomicReferenceFieldUpdater.newUpdater
+            (QNode.class, QNode.class, "next");
+
+        final boolean casNext(QNode cmp, QNode val) {
+            return nextUpdater.compareAndSet(this, cmp, val);
+        }
+
+        final void clearNext() {
+            nextUpdater.lazySet(this, this);
+        }
+
+    }
+
+    /**
+     * Padded version of AtomicReference used for head, tail and
+     * cleanMe, to alleviate contention across threads CASing one vs
+     * the other.
+     */
+    static final class PaddedAtomicReference<T> extends AtomicReference<T> {
+        // enough padding for 64bytes with 4byte refs
+        Object p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, pa, pb, pc, pd, pe;
+        PaddedAtomicReference(T r) { super(r); }
+    }
+
+
+    /** head of the queue */
+    private transient final PaddedAtomicReference<QNode> head;
+    /** tail of the queue */
+    private transient final PaddedAtomicReference<QNode> tail;
+
+    /**
+     * Reference to a cancelled node that might not yet have been
+     * unlinked from queue because it was the last inserted node
+     * when it cancelled.
+     */
+    private transient final PaddedAtomicReference<QNode> cleanMe;
+
+    /**
+     * Tries to cas nh as new head; if successful, unlink
+     * old head's next node to avoid garbage retention.
+     */
+    private boolean advanceHead(QNode h, QNode nh) {
+        if (h == head.get() && head.compareAndSet(h, nh)) {
+            h.clearNext(); // forget old next
+            return true;
+        }
+        return false;
+    }
+
+    /**
+     * Puts or takes an item. Used for most queue operations (except
+     * poll() and tryTransfer()). See the similar code in
+     * SynchronousQueue for detailed explanation.
+     *
+     * @param e the item or if null, signifies that this is a take
+     * @param mode the wait mode: NOWAIT, TIMEOUT, WAIT
+     * @param nanos timeout in nanosecs, used only if mode is TIMEOUT
+     * @return an item, or null on failure
+     */
+    private Object xfer(Object e, int mode, long nanos) {
+        boolean isData = (e != null);
+        QNode s = null;
+        final PaddedAtomicReference<QNode> head = this.head;
+        final PaddedAtomicReference<QNode> tail = this.tail;
+
+        for (;;) {
+            QNode t = tail.get();
+            QNode h = head.get();
+
+            if (t != null && (t == h || t.isData == isData)) {
+                if (s == null)
+                    s = new QNode(e, isData);
+                QNode last = t.next;
+                if (last != null) {
+                    if (t == tail.get())
+                        tail.compareAndSet(t, last);
+                }
+                else if (t.casNext(null, s)) {
+                    tail.compareAndSet(t, s);
+                    return awaitFulfill(t, s, e, mode, nanos);
+                }
+            }
+
+            else if (h != null) {
+                QNode first = h.next;
+                if (t == tail.get() && first != null &&
+                    advanceHead(h, first)) {
+                    Object x = first.get();
+                    if (x != first && first.compareAndSet(x, e)) {
+                        LockSupport.unpark(first.waiter);
+                        return isData? e : x;
+                    }
+                }
+            }
+        }
+    }
+
+
+    /**
+     * Version of xfer for poll() and tryTransfer, which
+     * simplifies control paths both here and in xfer.
+     */
+    private Object fulfill(Object e) {
+        boolean isData = (e != null);
+        final PaddedAtomicReference<QNode> head = this.head;
+        final PaddedAtomicReference<QNode> tail = this.tail;
+
+        for (;;) {
+            QNode t = tail.get();
+            QNode h = head.get();
+
+            if (t != null && (t == h || t.isData == isData)) {
+                QNode last = t.next;
+                if (t == tail.get()) {
+                    if (last != null)
+                        tail.compareAndSet(t, last);
+                    else
+                        return null;
+                }
+            }
+            else if (h != null) {
+                QNode first = h.next;
+                if (t == tail.get() &&
+                    first != null &&
+                    advanceHead(h, first)) {
+                    Object x = first.get();
+                    if (x != first && first.compareAndSet(x, e)) {
+                        LockSupport.unpark(first.waiter);
+                        return isData? e : x;
+                    }
+                }
+            }
+        }
+    }
+
+    /**
+     * Spins/blocks until node s is fulfilled or caller gives up,
+     * depending on wait mode.
+     *
+     * @param pred the predecessor of waiting node
+     * @param s the waiting node
+     * @param e the comparison value for checking match
+     * @param mode mode
+     * @param nanos timeout value
+     * @return matched item, or s if cancelled
+     */
+    private Object awaitFulfill(QNode pred, QNode s, Object e,
+                                int mode, long nanos) {
+        if (mode == NOWAIT)
+            return null;
+
+        long lastTime = (mode == TIMEOUT)? System.nanoTime() : 0;
+        Thread w = Thread.currentThread();
+        int spins = -1; // set to desired spin count below
+        for (;;) {
+            if (w.isInterrupted())
+                s.compareAndSet(e, s);
+            Object x = s.get();
+            if (x != e) {                 // Node was matched or cancelled
+                advanceHead(pred, s);     // unlink if head
+                if (x == s) {             // was cancelled
+                    clean(pred, s);
+                    return null;
+                }
+                else if (x != null) {
+                    s.set(s);             // avoid garbage retention
+                    return x;
+                }
+                else
+                    return e;
+            }
+            if (mode == TIMEOUT) {
+                long now = System.nanoTime();
+                nanos -= now - lastTime;
+                lastTime = now;
+                if (nanos <= 0) {
+                    s.compareAndSet(e, s); // try to cancel
+                    continue;
+                }
+            }
+            if (spins < 0) {
+                QNode h = head.get(); // only spin if at head
+                spins = ((h != null && h.next == s) ?
+                         (mode == TIMEOUT?
+                          maxTimedSpins : maxUntimedSpins) : 0);
+            }
+            if (spins > 0)
+                --spins;
+            else if (s.waiter == null)
+                s.waiter = w;
+            else if (mode != TIMEOUT) {
+                LockSupport.park(this);
+                s.waiter = null;
+                spins = -1;
+            }
+            else if (nanos > spinForTimeoutThreshold) {
+                LockSupport.parkNanos(this, nanos);
+                s.waiter = null;
+                spins = -1;
+            }
+        }
+    }
+
+    /**
+     * Returns validated tail for use in cleaning methods.
+     */
+    private QNode getValidatedTail() {
+        for (;;) {
+            QNode h = head.get();
+            QNode first = h.next;
+            if (first != null && first.next == first) { // help advance
+                advanceHead(h, first);
+                continue;
+            }
+            QNode t = tail.get();
+            QNode last = t.next;
+            if (t == tail.get()) {
+                if (last != null)
+                    tail.compareAndSet(t, last); // help advance
+                else
+                    return t;
+            }
+        }
+    }
+
+    /**
+     * Gets rid of cancelled node s with original predecessor pred.
+     *
+     * @param pred predecessor of cancelled node
+     * @param s the cancelled node
+     */
+    private void clean(QNode pred, QNode s) {
+        Thread w = s.waiter;
+        if (w != null) {             // Wake up thread
+            s.waiter = null;
+            if (w != Thread.currentThread())
+                LockSupport.unpark(w);
+        }
+
+        if (pred == null)
+            return;
+
+        /*
+         * At any given time, exactly one node on list cannot be
+         * deleted -- the last inserted node. To accommodate this, if
+         * we cannot delete s, we save its predecessor as "cleanMe",
+         * processing the previously saved version first. At least one
+         * of node s or the node previously saved can always be
+         * processed, so this always terminates.
+         */
+        while (pred.next == s) {
+            QNode oldpred = reclean();  // First, help get rid of cleanMe
+            QNode t = getValidatedTail();
+            if (s != t) {               // If not tail, try to unsplice
+                QNode sn = s.next;      // s.next == s means s already off list
+                if (sn == s || pred.casNext(s, sn))
+                    break;
+            }
+            else if (oldpred == pred || // Already saved
+                     (oldpred == null && cleanMe.compareAndSet(null, pred)))
+                break;                  // Postpone cleaning
+        }
+    }
+
+    /**
+     * Tries to unsplice the cancelled node held in cleanMe that was
+     * previously uncleanable because it was at tail.
+     *
+     * @return current cleanMe node (or null)
+     */
+    private QNode reclean() {
+        /*
+         * cleanMe is, or at one time was, predecessor of cancelled
+         * node s that was the tail so could not be unspliced.  If s
+         * is no longer the tail, try to unsplice if necessary and
+         * make cleanMe slot available.  This differs from similar
+         * code in clean() because we must check that pred still
+         * points to a cancelled node that must be unspliced -- if
+         * not, we can (must) clear cleanMe without unsplicing.
+         * This can loop only due to contention on casNext or
+         * clearing cleanMe.
+         */
+        QNode pred;
+        while ((pred = cleanMe.get()) != null) {
+            QNode t = getValidatedTail();
+            QNode s = pred.next;
+            if (s != t) {
+                QNode sn;
+                if (s == null || s == pred || s.get() != s ||
+                    (sn = s.next) == s || pred.casNext(s, sn))
+                    cleanMe.compareAndSet(pred, null);
+            }
+            else // s is still tail; cannot clean
+                break;
+        }
+        return pred;
+    }
+
+    /**
+     * Creates an initially empty {@code LinkedTransferQueue}.
+     */
+    public LinkedTransferQueue() {
+        QNode dummy = new QNode(null, false);
+        head = new PaddedAtomicReference<QNode>(dummy);
+        tail = new PaddedAtomicReference<QNode>(dummy);
+        cleanMe = new PaddedAtomicReference<QNode>(null);
+    }
+
+    /**
+     * Creates a {@code LinkedTransferQueue}
+     * initially containing the elements of the given collection,
+     * added in traversal order of the collection's iterator.
+     *
+     * @param c the collection of elements to initially contain
+     * @throws NullPointerException if the specified collection or any
+     *         of its elements are null
+     */
+    public LinkedTransferQueue(Collection<? extends E> c) {
+        this();
+        addAll(c);
+    }
+
+    public void put(E e) throws InterruptedException {
+        if (e == null) throw new NullPointerException();
+        if (Thread.interrupted()) throw new InterruptedException();
+        xfer(e, NOWAIT, 0);
+    }
+
+    public boolean offer(E e, long timeout, TimeUnit unit)
+        throws InterruptedException {
+        if (e == null) throw new NullPointerException();
+        if (Thread.interrupted()) throw new InterruptedException();
+        xfer(e, NOWAIT, 0);
+        return true;
+    }
+
+    public boolean offer(E e) {
+        if (e == null) throw new NullPointerException();
+        xfer(e, NOWAIT, 0);
+        return true;
+    }
+
+    public boolean add(E e) {
+        if (e == null) throw new NullPointerException();
+        xfer(e, NOWAIT, 0);
+        return true;
+    }
+
+    public void transfer(E e) throws InterruptedException {
+        if (e == null) throw new NullPointerException();
+        if (xfer(e, WAIT, 0) == null) {
+            Thread.interrupted();
+            throw new InterruptedException();
+        }
+    }
+
+    public boolean tryTransfer(E e, long timeout, TimeUnit unit)
+        throws InterruptedException {
+        if (e == null) throw new NullPointerException();
+        if (xfer(e, TIMEOUT, unit.toNanos(timeout)) != null)
+            return true;
+        if (!Thread.interrupted())
+            return false;
+        throw new InterruptedException();
+    }
+
+    public boolean tryTransfer(E e) {
+        if (e == null) throw new NullPointerException();
+        return fulfill(e) != null;
+    }
+
+    public E take() throws InterruptedException {
+        Object e = xfer(null, WAIT, 0);
+        if (e != null)
+            return (E)e;
+        Thread.interrupted();
+        throw new InterruptedException();
+    }
+
+    public E poll(long timeout, TimeUnit unit) throws InterruptedException {
+        Object e = xfer(null, TIMEOUT, unit.toNanos(timeout));
+        if (e != null || !Thread.interrupted())
+            return (E)e;
+        throw new InterruptedException();
+    }
+
+    public E poll() {
+        return (E)fulfill(null);
+    }
+
+    public int drainTo(Collection<? super E> c) {
+        if (c == null)
+            throw new NullPointerException();
+        if (c == this)
+            throw new IllegalArgumentException();
+        int n = 0;
+        E e;
+        while ( (e = poll()) != null) {
+            c.add(e);
+            ++n;
+        }
+        return n;
+    }
+
+    public int drainTo(Collection<? super E> c, int maxElements) {
+        if (c == null)
+            throw new NullPointerException();
+        if (c == this)
+            throw new IllegalArgumentException();
+        int n = 0;
+        E e;
+        while (n < maxElements && (e = poll()) != null) {
+            c.add(e);
+            ++n;
+        }
+        return n;
+    }
+
+    // Traversal-based methods
+
+    /**
+     * Returns head after performing any outstanding helping steps.
+     */
+    private QNode traversalHead() {
+        for (;;) {
+            QNode t = tail.get();
+            QNode h = head.get();
+            if (h != null && t != null) {
+                QNode last = t.next;
+                QNode first = h.next;
+                if (t == tail.get()) {
+                    if (last != null)
+                        tail.compareAndSet(t, last);
+                    else if (first != null) {
+                        Object x = first.get();
+                        if (x == first)
+                            advanceHead(h, first);
+                        else
+                            return h;
+                    }
+                    else
+                        return h;
+                }
+            }
+            reclean();
+        }
+    }
+
+
+    public Iterator<E> iterator() {
+        return new Itr();
+    }
+
+    /**
+     * Iterators. Basic strategy is to traverse list, treating
+     * non-data (i.e., request) nodes as terminating list.
+     * Once a valid data node is found, the item is cached
+     * so that the next call to next() will return it even
+     * if subsequently removed.
+     */
+    class Itr implements Iterator<E> {
+        QNode next;        // node to return next
+        QNode pnext;       // predecessor of next
+        QNode snext;       // successor of next
+        QNode curr;        // last returned node, for remove()
+        QNode pcurr;       // predecessor of curr, for remove()
+        E nextItem;        // Cache of next item, once commited to in next
+
+        Itr() {
+            findNext();
+        }
+
+        /**
+         * Ensures next points to next valid node, or null if none.
+         */
+        void findNext() {
+            for (;;) {
+                QNode pred = pnext;
+                QNode q = next;
+                if (pred == null || pred == q) {
+                    pred = traversalHead();
+                    q = pred.next;
+                }
+                if (q == null || !q.isData) {
+                    next = null;
+                    return;
+                }
+                Object x = q.get();
+                QNode s = q.next;
+                if (x != null && q != x && q != s) {
+                    nextItem = (E)x;
+                    snext = s;
+                    pnext = pred;
+                    next = q;
+                    return;
+                }
+                pnext = q;
+                next = s;
+            }
+        }
+
+        public boolean hasNext() {
+            return next != null;
+        }
+
+        public E next() {
+            if (next == null) throw new NoSuchElementException();
+            pcurr = pnext;
+            curr = next;
+            pnext = next;
+            next = snext;
+            E x = nextItem;
+            findNext();
+            return x;
+        }
+
+        public void remove() {
+            QNode p = curr;
+            if (p == null)
+                throw new IllegalStateException();
+            Object x = p.get();
+            if (x != null && x != p && p.compareAndSet(x, p))
+                clean(pcurr, p);
+        }
+    }
+
+    public E peek() {
+        for (;;) {
+            QNode h = traversalHead();
+            QNode p = h.next;
+            if (p == null)
+                return null;
+            Object x = p.get();
+            if (p != x) {
+                if (!p.isData)
+                    return null;
+                if (x != null)
+                    return (E)x;
+            }
+        }
+    }
+
+    public boolean isEmpty() {
+        for (;;) {
+            QNode h = traversalHead();
+            QNode p = h.next;
+            if (p == null)
+                return true;
+            Object x = p.get();
+            if (p != x) {
+                if (!p.isData)
+                    return true;
+                if (x != null)
+                    return false;
+            }
+        }
+    }
+
+    public boolean hasWaitingConsumer() {
+        for (;;) {
+            QNode h = traversalHead();
+            QNode p = h.next;
+            if (p == null)
+                return false;
+            Object x = p.get();
+            if (p != x)
+                return !p.isData;
+        }
+    }
+
+    /**
+     * Returns the number of elements in this queue.  If this queue
+     * contains more than {@code Integer.MAX_VALUE} elements, returns
+     * {@code Integer.MAX_VALUE}.
+     *
+     * <p>Beware that, unlike in most collections, this method is
+     * <em>NOT</em> a constant-time operation. Because of the
+     * asynchronous nature of these queues, determining the current
+     * number of elements requires an O(n) traversal.
+     *
+     * @return the number of elements in this queue
+     */
+    public int size() {
+        int count = 0;
+        QNode h = traversalHead();
+        for (QNode p = h.next; p != null && p.isData; p = p.next) {
+            Object x = p.get();
+            if (x != null && x != p) {
+                if (++count == Integer.MAX_VALUE) // saturated
+                    break;
+            }
+        }
+        return count;
+    }
+
+    public int getWaitingConsumerCount() {
+        int count = 0;
+        QNode h = traversalHead();
+        for (QNode p = h.next; p != null && !p.isData; p = p.next) {
+            if (p.get() == null) {
+                if (++count == Integer.MAX_VALUE)
+                    break;
+            }
+        }
+        return count;
+    }
+
+    public int remainingCapacity() {
+        return Integer.MAX_VALUE;
+    }
+
+    public boolean remove(Object o) {
+        if (o == null)
+            return false;
+        for (;;) {
+            QNode pred = traversalHead();
+            for (;;) {
+                QNode q = pred.next;
+                if (q == null || !q.isData)
+                    return false;
+                if (q == pred) // restart
+                    break;
+                Object x = q.get();
+                if (x != null && x != q && o.equals(x) &&
+                    q.compareAndSet(x, q)) {
+                    clean(pred, q);
+                    return true;
+                }
+                pred = q;
+            }
+        }
+    }
+
+    /**
+     * Save the state to a stream (that is, serialize it).
+     *
+     * @serialData All of the elements (each an {@code E}) in
+     * the proper order, followed by a null
+     * @param s the stream
+     */
+    private void writeObject(java.io.ObjectOutputStream s)
+        throws java.io.IOException {
+        s.defaultWriteObject();
+        for (E e : this)
+            s.writeObject(e);
+        // Use trailing null as sentinel
+        s.writeObject(null);
+    }
+
+    /**
+     * Reconstitute the Queue instance from a stream (that is,
+     * deserialize it).
+     * @param s the stream
+     */
+    private void readObject(java.io.ObjectInputStream s)
+        throws java.io.IOException, ClassNotFoundException {
+        s.defaultReadObject();
+        resetHeadAndTail();
+        for (;;) {
+            E item = (E)s.readObject();
+            if (item == null)
+                break;
+            else
+                offer(item);
+        }
+    }
+
+
+    // Support for resetting head/tail while deserializing
+    private void resetHeadAndTail() {
+        QNode dummy = new QNode(null, false);
+        _unsafe.putObjectVolatile(this, headOffset,
+                                  new PaddedAtomicReference<QNode>(dummy));
+        _unsafe.putObjectVolatile(this, tailOffset,
+                                  new PaddedAtomicReference<QNode>(dummy));
+        _unsafe.putObjectVolatile(this, cleanMeOffset,
+                                  new PaddedAtomicReference<QNode>(null));
+    }
+
+    // Temporary Unsafe mechanics for preliminary release
+    private static Unsafe getUnsafe() throws Throwable {
+        try {
+            return Unsafe.getUnsafe();
+        } catch (SecurityException se) {
+            try {
+                return java.security.AccessController.doPrivileged
+                    (new java.security.PrivilegedExceptionAction<Unsafe>() {
+                        public Unsafe run() throws Exception {
+                            return getUnsafePrivileged();
+                        }});
+            } catch (java.security.PrivilegedActionException e) {
+                throw e.getCause();
+            }
+        }
+    }
+
+    private static Unsafe getUnsafePrivileged()
+            throws NoSuchFieldException, IllegalAccessException {
+        Field f = Unsafe.class.getDeclaredField("theUnsafe");
+        f.setAccessible(true);
+        return (Unsafe) f.get(null);
+    }
+
+    private static long fieldOffset(String fieldName)
+            throws NoSuchFieldException {
+        return _unsafe.objectFieldOffset
+            (LinkedTransferQueue.class.getDeclaredField(fieldName));
+    }
+
+    private static final Unsafe _unsafe;
+    private static final long headOffset;
+    private static final long tailOffset;
+    private static final long cleanMeOffset;
+    static {
+        try {
+            _unsafe = getUnsafe();
+            headOffset = fieldOffset("head");
+            tailOffset = fieldOffset("tail");
+            cleanMeOffset = fieldOffset("cleanMe");
+        } catch (Throwable e) {
+            throw new RuntimeException("Could not initialize intrinsics", e);
+        }
+    }
+
+}
diff --git a/src/forkjoin/scala/concurrent/forkjoin/RecursiveAction.java b/src/forkjoin/scala/concurrent/forkjoin/RecursiveAction.java
new file mode 100644
index 0000000..3b54de8
--- /dev/null
+++ b/src/forkjoin/scala/concurrent/forkjoin/RecursiveAction.java
@@ -0,0 +1,151 @@
+/*
+ * Written by Doug Lea with assistance from members of JCP JSR-166
+ * Expert Group and released to the public domain, as explained at
+ * http://creativecommons.org/licenses/publicdomain
+ */
+
+package scala.concurrent.forkjoin;
+
+/**
+ * Recursive resultless ForkJoinTasks. This class establishes
+ * conventions to parameterize resultless actions as <tt>Void</tt>
+ * ForkJoinTasks. Because <tt>null</tt> is the only valid value of
+ * <tt>Void</tt>, methods such as join always return <tt>null</tt>
+ * upon completion.
+ * 
+ * <p><b>Sample Usages.</b> Here is a sketch of a ForkJoin sort that
+ * sorts a given <tt>long[]</tt> array:
+ *
+ * <pre>
+ * class SortTask extends RecursiveAction {
+ *   final long[] array; final int lo; final int hi;
+ *   SortTask(long[] array, int lo, int hi) {
+ *     this.array = array; this.lo = lo; this.hi = hi;
+ *   }
+ *   protected void compute() {
+ *     if (hi - lo < THRESHOLD)
+ *       sequentiallySort(array, lo, hi);
+ *     else {
+ *       int mid = (lo + hi) >>> 1;
+ *       invokeAll(new SortTask(array, lo, mid),
+ *                 new SortTask(array, mid, hi));
+ *       merge(array, lo, hi);
+ *     }
+ *   }
+ * }
+ * </pre>
+ *
+ * You could then sort anArray by creating <tt>new SortTask(anArray, 0,
+ * anArray.length-1) </tt> and invoking it in a ForkJoinPool.
+ * As a more concrete simple example, the following task increments
+ * each element of an array:
+ * <pre>
+ * class IncrementTask extends RecursiveAction {
+ *   final long[] array; final int lo; final int hi;
+ *   IncrementTask(long[] array, int lo, int hi) {
+ *     this.array = array; this.lo = lo; this.hi = hi;
+ *   }
+ *   protected void compute() {
+ *     if (hi - lo < THRESHOLD) {
+ *       for (int i = lo; i < hi; ++i)
+ *         array[i]++;
+ *     }
+ *     else {
+ *       int mid = (lo + hi) >>> 1;
+ *       invokeAll(new IncrementTask(array, lo, mid),
+ *                 new IncrementTask(array, mid, hi));
+ *     }
+ *   }
+ * }
+ * </pre>
+ *
+ *
+ * <p>The following example illustrates some refinements and idioms
+ * that may lead to better performance: RecursiveActions need not be
+ * fully recursive, so long as they maintain the basic
+ * divide-and-conquer approach. Here is a class that sums the squares
+ * of each element of a double array, by subdividing out only the
+ * right-hand-sides of repeated divisions by two, and keeping track of
+ * them with a chain of <tt>next</tt> references. It uses a dynamic
+ * threshold based on method <tt>surplus</tt>, but counterbalances
+ * potential excess partitioning by directly performing leaf actions
+ * on unstolen tasks rather than further subdividing.
+ *
+ * <pre>
+ * double sumOfSquares(ForkJoinPool pool, double[] array) {
+ *   int n = array.length;
+ *   int seqSize = 1 + n / (8 * pool.getParallelism());
+ *   Applyer a = new Applyer(array, 0, n, seqSize, null);
+ *   pool.invoke(a);
+ *   return a.result;
+ * }
+ *
+ * class Applyer extends RecursiveAction {
+ *   final double[] array;
+ *   final int lo, hi, seqSize;
+ *   double result;
+ *   Applyer next; // keeps track of right-hand-side tasks
+ *   Applyer(double[] array, int lo, int hi, int seqSize, Applyer next) {
+ *     this.array = array; this.lo = lo; this.hi = hi;
+ *     this.seqSize = seqSize; this.next = next;
+ *   }
+ *
+ *   double atLeaf(int l, int r) {
+ *     double sum = 0;
+ *     for (int i = l; i < h; ++i) // perform leftmost base step
+ *       sum += array[i] * array[i];
+ *     return sum;
+ *   }
+ *
+ *   protected void compute() {
+ *     int l = lo;
+ *     int h = hi;
+ *     Applyer right = null;
+ *     while (h - l > 1 &&
+ *        ForkJoinWorkerThread.getEstimatedSurplusTaskCount() <= 3) {
+ *        int mid = (l + h) >>> 1;
+ *        right = new Applyer(array, mid, h, seqSize, right);
+ *        right.fork();
+ *        h = mid;
+ *     }
+ *     double sum = atLeaf(l, h);
+ *     while (right != null) {
+ *        if (right.tryUnfork()) // directly calculate if not stolen
+ *          sum += right.atLeaf(right.lo, right.hi);
+ *       else {
+ *          right.helpJoin();
+ *          sum += right.result;
+ *        }
+ *        right = right.next;
+ *      }
+ *     result = sum;
+ *   }
+ * }
+ * </pre>
+ */
+public abstract class RecursiveAction extends ForkJoinTask<Void> {
+
+    /**
+     * The main computation performed by this task. 
+     */
+    protected abstract void compute();
+
+    /**
+     * Always returns null
+     */
+    public final Void getRawResult() { return null; }
+
+    /**
+     * Requires null completion value.
+     */
+    protected final void setRawResult(Void mustBeNull) { }
+
+    /**
+     * Implements execution conventions for RecursiveActions
+     */
+    protected final boolean exec() {
+        compute();
+        return true;
+    }
+
+}
diff --git a/src/forkjoin/scala/concurrent/forkjoin/RecursiveTask.java b/src/forkjoin/scala/concurrent/forkjoin/RecursiveTask.java
new file mode 100644
index 0000000..c884271
--- /dev/null
+++ b/src/forkjoin/scala/concurrent/forkjoin/RecursiveTask.java
@@ -0,0 +1,71 @@
+/*
+ * Written by Doug Lea with assistance from members of JCP JSR-166
+ * Expert Group and released to the public domain, as explained at
+ * http://creativecommons.org/licenses/publicdomain
+ */
+
+package scala.concurrent.forkjoin;
+
+/**
+ * Recursive result-bearing ForkJoinTasks.
+ * <p> For a classic example, here is a task computing Fibonacci numbers:
+ *
+ * <pre>
+ * class Fibonacci extends RecursiveTask<Integer> {
+ *   final int n;
+ *   Fibonnaci(int n) { this.n = n; }
+ *   Integer compute() {
+ *     if (n <= 1)
+ *        return n;
+ *     Fibonacci f1 = new Fibonacci(n - 1);
+ *     f1.fork();
+ *     Fibonacci f2 = new Fibonacci(n - 2);
+ *     return f2.compute() + f1.join();
+ *   }
+ * }
+ * </pre>
+ *
+ * However, besides being a dumb way to compute Fibonacci functions
+ * (there is a simple fast linear algorithm that you'd use in
+ * practice), this is likely to perform poorly because the smallest
+ * subtasks are too small to be worthwhile splitting up. Instead, as
+ * is the case for nearly all fork/join applications, you'd pick some
+ * minimum granularity size (for example 10 here) for which you always
+ * sequentially solve rather than subdividing.  
+ *
+ */
+public abstract class RecursiveTask<V> extends ForkJoinTask<V> {
+
+    /**
+     * Empty constructor for use by subclasses.
+     */
+    protected RecursiveTask() {
+    }
+
+    /**
+     * The result returned by compute method.
+     */
+    V result;
+
+    /**
+     * The main computation performed by this task. 
+     */
+    protected abstract V compute();
+
+    public final V getRawResult() {
+        return result;
+    }
+
+    protected final void setRawResult(V value) {
+        result = value;
+    }
+
+    /**
+     * Implements execution conventions for RecursiveTask
+     */
+    protected final boolean exec() {
+        result = compute();
+        return true;
+    }
+
+}
diff --git a/src/forkjoin/scala/concurrent/forkjoin/ThreadLocalRandom.java b/src/forkjoin/scala/concurrent/forkjoin/ThreadLocalRandom.java
new file mode 100644
index 0000000..34e2e37
--- /dev/null
+++ b/src/forkjoin/scala/concurrent/forkjoin/ThreadLocalRandom.java
@@ -0,0 +1,186 @@
+/*
+ * Written by Doug Lea with assistance from members of JCP JSR-166
+ * Expert Group and released to the public domain, as explained at
+ * http://creativecommons.org/licenses/publicdomain
+ */
+
+package scala.concurrent.forkjoin;
+import java.util.*;
+
+/**
+ * A random number generator with the same properties as class {@link
+ * Random} but isolated to the current Thread.  Like the global
+ * generator used by the {@link java.lang.Math} class, a
+ * ThreadLocalRandom is initialized with an internally generated seed
+ * that may not otherwise be modified. When applicable, use of
+ * ThreadLocalRandom rather than shared Random objects in concurrent
+ * programs will typically encounter much less overhead and
+ * contention.  ThreadLocalRandoms are particularly appropriate when
+ * multiple tasks (for example, each a {@link ForkJoinTask}), use
+ * random numbers in parallel in thread pools.
+ *
+ * <p>Usages of this class should typically be of the form:
+ * <code>ThreadLocalRandom.current().nextX(...)</code> (where
+ * <code>X</code> is <code>Int</code>, <code>Long</code>, etc).
+ * When all usages are of this form, it is never possible to
+ * accidently share ThreadLocalRandoms across multiple threads.
+ *
+ * <p>This class also provides additional commonly used bounded random
+ * generation methods.
+ */
+public class ThreadLocalRandom extends Random {
+    // same constants as Random, but must be redeclared because private
+    private final static long multiplier = 0x5DEECE66DL;
+    private final static long addend = 0xBL;
+    private final static long mask = (1L << 48) - 1;
+
+    /**
+     * The random seed. We can't use super.seed
+     */
+    private long rnd;
+
+    /**
+     * Initialization flag to permit the first and only allowed call
+     * to setSeed (inside Random constructor) to succeed.  We can't
+     * allow others since it would cause setting seed in one part of a
+     * program to unintentionally impact other usages by the thread.
+     */
+    boolean initialized;
+
+    // Padding to help avoid memory contention among seed updates in
+    // different TLRs in the common case that they are located near
+    // each other.
+    private long pad0, pad1, pad2, pad3, pad4, pad5, pad6, pad7;
+
+    /**
+     * The actual ThreadLocal
+     */
+    private static final ThreadLocal<ThreadLocalRandom> localRandom =
+        new ThreadLocal<ThreadLocalRandom>() {
+            protected ThreadLocalRandom initialValue() {
+                return new ThreadLocalRandom();
+            }
+    };
+
+
+    /**
+     * Constructor called only by localRandom.initialValue.
+     * We rely on the fact that the superclass no-arg constructor
+     * invokes setSeed exactly once to initialize.
+     */
+    ThreadLocalRandom() {
+        super();
+    }
+
+    /**
+     * Returns the current Thread's ThreadLocalRandom
+     * @return the current Thread's ThreadLocalRandom
+     */
+    public static ThreadLocalRandom current() {
+        return localRandom.get();
+    }
+
+    /**
+     * Throws UnsupportedOperationException. Setting seeds in this
+     * generator is unsupported.
+     * @throws UnsupportedOperationException always
+     */
+    public void setSeed(long seed) {
+        if (initialized)
+            throw new UnsupportedOperationException();
+        initialized = true;
+        rnd = (seed ^ multiplier) & mask;
+    }
+
+    protected int next(int bits) {
+        return (int)((rnd = (rnd * multiplier + addend) & mask) >>> (48-bits));
+    }
+
+    /**
+     * Returns a pseudorandom, uniformly distributed value between the
+     * given least value (inclusive) and bound (exclusive).
+     * @param least the least value returned
+     * @param bound the upper bound (exclusive)
+     * @throws IllegalArgumentException if least greater than or equal
+     * to bound
+     * @return the next value
+     */
+    public int nextInt(int least, int bound) {
+        if (least >= bound)
+            throw new IllegalArgumentException();
+        return nextInt(bound - least) + least;
+    }
+
+    /**
+     * Returns a pseudorandom, uniformly distributed value
+     * between 0 (inclusive) and the specified value (exclusive)
+     * @param n the bound on the random number to be returned.  Must be
+     *        positive.
+     * @return the next value
+     * @throws IllegalArgumentException if n is not positive
+     */
+    public long nextLong(long n) {
+        if (n <= 0)
+            throw new IllegalArgumentException("n must be positive");
+        // Divide n by two until small enough for nextInt. On each
+        // iteration (at most 31 of them but usually much less),
+        // randomly choose both whether to include high bit in result
+        // (offset) and whether to continue with the lower vs upper
+        // half (which makes a difference only if odd).
+        long offset = 0;
+        while (n >= Integer.MAX_VALUE) {
+            int bits = next(2);
+            long half = n >>> 1;
+            long nextn = ((bits & 2) == 0)? half : n - half;
+            if ((bits & 1) == 0)
+                offset += n - nextn;
+            n = nextn;
+        }
+        return offset + nextInt((int)n);
+    }
+
+    /**
+     * Returns a pseudorandom, uniformly distributed value between the
+     * given least value (inclusive) and bound (exclusive).
+     * @param least the least value returned
+     * @param bound the upper bound (exclusive)
+     * @return the next value
+     * @throws IllegalArgumentException if least greater than or equal
+     * to bound
+     */
+    public long nextLong(long least, long bound) {
+        if (least >= bound)
+            throw new IllegalArgumentException();
+        return nextLong(bound - least) + least;
+    }
+
+    /**
+     * Returns a pseudorandom, uniformly distributed {@code double} value
+     * between 0 (inclusive) and the specified value (exclusive)
+     * @param n the bound on the random number to be returned.  Must be
+     *        positive.
+     * @return the next value
+     * @throws IllegalArgumentException if n is not positive
+     */
+    public double nextDouble(double n) {
+        if (n <= 0)
+            throw new IllegalArgumentException("n must be positive");
+        return nextDouble() * n;
+    }
+
+    /**
+     * Returns a pseudorandom, uniformly distributed value between the
+     * given least value (inclusive) and bound (exclusive).
+     * @param least the least value returned
+     * @param bound the upper bound (exclusive)
+     * @return the next value
+     * @throws IllegalArgumentException if least greater than or equal
+     * to bound
+     */
+    public double nextDouble(double least, double bound) {
+        if (least >= bound)
+            throw new IllegalArgumentException();
+        return nextDouble() * (bound - least) + least;
+    }
+
+}
diff --git a/src/forkjoin/scala/concurrent/forkjoin/TransferQueue.java b/src/forkjoin/scala/concurrent/forkjoin/TransferQueue.java
new file mode 100644
index 0000000..9c7b228
--- /dev/null
+++ b/src/forkjoin/scala/concurrent/forkjoin/TransferQueue.java
@@ -0,0 +1,118 @@
+/*
+ * Written by Doug Lea with assistance from members of JCP JSR-166
+ * Expert Group and released to the public domain, as explained at
+ * http://creativecommons.org/licenses/publicdomain
+ */
+
+package scala.concurrent.forkjoin;
+import java.util.concurrent.*;
+
+/**
+ * A {@link BlockingQueue} in which producers may wait for consumers
+ * to receive elements.  A {@code TransferQueue} may be useful for
+ * example in message passing applications in which producers
+ * sometimes (using method {@code transfer}) await receipt of
+ * elements by consumers invoking {@code take} or {@code poll},
+ * while at other times enqueue elements (via method {@code put})
+ * without waiting for receipt. Non-blocking and time-out versions of
+ * {@code tryTransfer} are also available.  A TransferQueue may also
+ * be queried via {@code hasWaitingConsumer} whether there are any
+ * threads waiting for items, which is a converse analogy to a
+ * {@code peek} operation.
+ *
+ * <p>Like any {@code BlockingQueue}, a {@code TransferQueue} may be
+ * capacity bounded. If so, an attempted {@code transfer} operation
+ * may initially block waiting for available space, and/or
+ * subsequently block waiting for reception by a consumer.  Note that
+ * in a queue with zero capacity, such as {@link SynchronousQueue},
+ * {@code put} and {@code transfer} are effectively synonymous.
+ *
+ * <p>This interface is a member of the
+ * <a href="{@docRoot}/../technotes/guides/collections/index.html">
+ * Java Collections Framework</a>.
+ *
+ * @since 1.7
+ * @author Doug Lea
+ * @param <E> the type of elements held in this collection
+ */
+public interface TransferQueue<E> extends BlockingQueue<E> {
+    /**
+     * Transfers the specified element if there exists a consumer
+     * already waiting to receive it, otherwise returning {@code false}
+     * without enqueuing the element.
+     *
+     * @param e the element to transfer
+     * @return {@code true} if the element was transferred, else
+     *         {@code false}
+     * @throws ClassCastException if the class of the specified element
+     *         prevents it from being added to this queue
+     * @throws NullPointerException if the specified element is null
+     * @throws IllegalArgumentException if some property of the specified
+     *         element prevents it from being added to this queue
+     */
+    boolean tryTransfer(E e);
+
+    /**
+     * Inserts the specified element into this queue, waiting if
+     * necessary for space to become available and the element to be
+     * dequeued by a consumer invoking {@code take} or {@code poll}.
+     *
+     * @param e the element to transfer
+     * @throws InterruptedException if interrupted while waiting,
+     *         in which case the element is not enqueued.
+     * @throws ClassCastException if the class of the specified element
+     *         prevents it from being added to this queue
+     * @throws NullPointerException if the specified element is null
+     * @throws IllegalArgumentException if some property of the specified
+     *         element prevents it from being added to this queue
+     */
+    void transfer(E e) throws InterruptedException;
+
+    /**
+     * Inserts the specified element into this queue, waiting up to
+     * the specified wait time if necessary for space to become
+     * available and the element to be dequeued by a consumer invoking
+     * {@code take} or {@code poll}.
+     *
+     * @param e the element to transfer
+     * @param timeout how long to wait before giving up, in units of
+     *        {@code unit}
+     * @param unit a {@code TimeUnit} determining how to interpret the
+     *        {@code timeout} parameter
+     * @return {@code true} if successful, or {@code false} if
+     *         the specified waiting time elapses before completion,
+     *         in which case the element is not enqueued.
+     * @throws InterruptedException if interrupted while waiting,
+     *         in which case the element is not enqueued.
+     * @throws ClassCastException if the class of the specified element
+     *         prevents it from being added to this queue
+     * @throws NullPointerException if the specified element is null
+     * @throws IllegalArgumentException if some property of the specified
+     *         element prevents it from being added to this queue
+     */
+    boolean tryTransfer(E e, long timeout, TimeUnit unit)
+        throws InterruptedException;
+
+    /**
+     * Returns {@code true} if there is at least one consumer waiting
+     * to dequeue an element via {@code take} or {@code poll}.
+     * The return value represents a momentary state of affairs.
+     *
+     * @return {@code true} if there is at least one waiting consumer
+     */
+    boolean hasWaitingConsumer();
+
+    /**
+     * Returns an estimate of the number of consumers waiting to
+     * dequeue elements via {@code take} or {@code poll}. The return
+     * value is an approximation of a momentary state of affairs, that
+     * may be inaccurate if consumers have completed or given up
+     * waiting. The value may be useful for monitoring and heuristics,
+     * but not for synchronization control. Implementations of this
+     * method are likely to be noticeably slower than those for
+     * {@link #hasWaitingConsumer}.
+     *
+     * @return the number of consumers waiting to dequeue elements
+     */
+    int getWaitingConsumerCount();
+}
diff --git a/src/forkjoin/scala/concurrent/forkjoin/package-info.java b/src/forkjoin/scala/concurrent/forkjoin/package-info.java
new file mode 100644
index 0000000..b8fa0fa
--- /dev/null
+++ b/src/forkjoin/scala/concurrent/forkjoin/package-info.java
@@ -0,0 +1,29 @@
+/*
+ * Written by Doug Lea with assistance from members of JCP JSR-166
+ * Expert Group and released to the public domain, as explained at
+ * http://creativecommons.org/licenses/publicdomain
+ */
+
+
+/**
+ * Preview versions of classes targeted for Java 7.  Includes a
+ * fine-grained parallel computation framework: ForkJoinTasks and
+ * their related support classes provide a very efficient basis for
+ * obtaining platform-independent parallel speed-ups of
+ * computation-intensive operations.  They are not a full substitute
+ * for the kinds of arbitrary processing supported by Executors or
+ * Threads. However, when applicable, they typically provide
+ * significantly greater performance on multiprocessor platforms.
+ *
+ * <p> Candidates for fork/join processing mainly include those that
+ * can be expressed using parallel divide-and-conquer techniques: To
+ * solve a problem, break it in two (or more) parts, and then solve
+ * those parts in parallel, continuing on in this way until the
+ * problem is too small to be broken up, so is solved directly.  The
+ * underlying <em>work-stealing</em> framework makes subtasks
+ * available to other threads (normally one per CPU), that help
+ * complete the tasks.  In general, the most efficient ForkJoinTasks
+ * are those that directly implement this algorithmic design pattern.
+ *
+ */
+package scala.concurrent.forkjoin;
diff --git a/src/intellij/actors.iml.SAMPLE b/src/intellij/actors.iml.SAMPLE
new file mode 100644
index 0000000..ace6ec7
--- /dev/null
+++ b/src/intellij/actors.iml.SAMPLE
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<module relativePaths="true" type="JAVA_MODULE" version="4">
+  <component name="FacetManager">
+    <facet type="Scala" name="Scala">
+      <configuration />
+    </facet>
+  </component>
+  <component name="NewModuleRootManager" inherit-compiler-output="true">
+    <exclude-output />
+    <content url="file://$MODULE_DIR$/../actors">
+      <sourceFolder url="file://$MODULE_DIR$/../actors" isTestSource="false" />
+    </content>
+    <orderEntry type="inheritedJdk" />
+    <orderEntry type="sourceFolder" forTests="false" />
+    <orderEntry type="module" module-name="compiler" />
+    <orderEntry type="module" module-name="library" />
+    <orderEntry type="library" name="Project ant library" level="project" />
+    <orderEntry type="library" name="Project Scala SDK" level="project" />
+  </component>
+</module>
+
diff --git a/src/intellij/compiler.iml.SAMPLE b/src/intellij/compiler.iml.SAMPLE
new file mode 100644
index 0000000..cc0b64e
--- /dev/null
+++ b/src/intellij/compiler.iml.SAMPLE
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<module relativePaths="true" type="JAVA_MODULE" version="4">
+  <component name="FacetManager">
+    <facet type="Scala" name="Scala">
+      <configuration>
+        <option name="takeFromSettings" value="true" />
+        <option name="myScalaCompilerJarPath" value="build/locker/classes/compiler lib/fjbg.jar lib/msil.jar" />
+        <option name="myScalaSdkJarPath" value="build/locker/classes/library" />
+      </configuration>
+    </facet>
+  </component>
+  <component name="NewModuleRootManager" inherit-compiler-output="false">
+    <output url="file://$MODULE_DIR$/../../build/quick/classes/compiler" />
+    <output-test url="file://$MODULE_DIR$/../../out/test/compiler" />
+    <exclude-output />
+    <content url="file://$MODULE_DIR$/../compiler">
+      <sourceFolder url="file://$MODULE_DIR$/../compiler" isTestSource="false" />
+    </content>
+    <orderEntry type="inheritedJdk" />
+    <orderEntry type="sourceFolder" forTests="false" />
+    <orderEntry type="library" name="Project ant library" level="project" />
+    <orderEntry type="library" name="Project Scala SDK" level="project" />
+    <orderEntry type="library" name="ant" level="project" />
+    <orderEntry type="library" name="locker" level="project" />
+  </component>
+</module>
+
diff --git a/src/intellij/dbc.iml.SAMPLE b/src/intellij/dbc.iml.SAMPLE
new file mode 100644
index 0000000..d82bda7
--- /dev/null
+++ b/src/intellij/dbc.iml.SAMPLE
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<module relativePaths="true" type="JAVA_MODULE" version="4">
+  <component name="FacetManager">
+    <facet type="Scala" name="Scala">
+      <configuration />
+    </facet>
+  </component>
+  <component name="NewModuleRootManager" inherit-compiler-output="true">
+    <exclude-output />
+    <content url="file://$MODULE_DIR$/../dbc">
+      <sourceFolder url="file://$MODULE_DIR$/../dbc" isTestSource="false" />
+    </content>
+    <orderEntry type="inheritedJdk" />
+    <orderEntry type="sourceFolder" forTests="false" />
+    <orderEntry type="module" module-name="compiler" />
+    <orderEntry type="module" module-name="library" />
+    <orderEntry type="module" module-name="actors" />
+    <orderEntry type="library" name="Project ant library" level="project" />
+    <orderEntry type="library" name="Project Scala SDK" level="project" />
+  </component>
+</module>
+
diff --git a/src/intellij/library.iml.SAMPLE b/src/intellij/library.iml.SAMPLE
new file mode 100644
index 0000000..a871963
--- /dev/null
+++ b/src/intellij/library.iml.SAMPLE
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<module relativePaths="true" type="JAVA_MODULE" version="4">
+  <component name="FacetManager">
+    <facet type="Scala" name="Scala">
+      <configuration />
+    </facet>
+  </component>
+  <component name="NewModuleRootManager" inherit-compiler-output="true">
+    <exclude-output />
+    <content url="file://$MODULE_DIR$/../../META-INF" />
+    <content url="file://$MODULE_DIR$/../../bin" />
+    <content url="file://$MODULE_DIR$/../../lib" />
+    <content url="file://$MODULE_DIR$/../library">
+      <sourceFolder url="file://$MODULE_DIR$/../library" isTestSource="false" />
+    </content>
+    <orderEntry type="inheritedJdk" />
+    <orderEntry type="sourceFolder" forTests="false" />
+    <orderEntry type="library" name="Project ant library" level="project" />
+    <orderEntry type="library" name="Project Scala SDK" level="project" />
+    <orderEntry type="library" name="ant" level="application" />
+  </component>
+</module>
+
diff --git a/src/intellij/manual.iml.SAMPLE b/src/intellij/manual.iml.SAMPLE
new file mode 100644
index 0000000..bbdcfbe
--- /dev/null
+++ b/src/intellij/manual.iml.SAMPLE
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<module relativePaths="true" type="JAVA_MODULE" version="4">
+  <component name="FacetManager">
+    <facet type="Scala" name="Scala">
+      <configuration />
+    </facet>
+  </component>
+  <component name="NewModuleRootManager" inherit-compiler-output="true">
+    <exclude-output />
+    <content url="file://$MODULE_DIR$/../manual">
+      <sourceFolder url="file://$MODULE_DIR$/../manual" isTestSource="false" />
+    </content>
+    <orderEntry type="inheritedJdk" />
+    <orderEntry type="sourceFolder" forTests="false" />
+    <orderEntry type="module" module-name="actors" />
+    <orderEntry type="module" module-name="compiler" />
+    <orderEntry type="module" module-name="dbc" />
+    <orderEntry type="module" module-name="library" />
+    <orderEntry type="module" module-name="partest" />
+    <orderEntry type="module" module-name="scalap" />
+    <orderEntry type="module" module-name="swing" />
+    <orderEntry type="library" name="Project ant library" level="project" />
+    <orderEntry type="library" name="Project Scala SDK" level="project" />
+    <orderEntry type="library" name="ant" level="application" />
+  </component>
+</module>
+
diff --git a/src/intellij/partest.iml.SAMPLE b/src/intellij/partest.iml.SAMPLE
new file mode 100644
index 0000000..3df457a
--- /dev/null
+++ b/src/intellij/partest.iml.SAMPLE
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<module relativePaths="true" type="JAVA_MODULE" version="4">
+  <component name="FacetManager">
+    <facet type="Scala" name="Scala">
+      <configuration />
+    </facet>
+  </component>
+  <component name="NewModuleRootManager" inherit-compiler-output="true">
+    <exclude-output />
+    <content url="file://$MODULE_DIR$/../partest">
+      <sourceFolder url="file://$MODULE_DIR$/../partest" isTestSource="false" />
+    </content>
+    <content url="file://$MODULE_DIR$/../../test" />
+    <orderEntry type="inheritedJdk" />
+    <orderEntry type="sourceFolder" forTests="false" />
+    <orderEntry type="module" module-name="actors" />
+    <orderEntry type="module" module-name="compiler" />
+    <orderEntry type="module" module-name="dbc" />
+    <orderEntry type="module" module-name="library" />
+    <orderEntry type="module" module-name="manual" />
+    <orderEntry type="module" module-name="scalap" />
+    <orderEntry type="module" module-name="swing" />
+    <orderEntry type="library" name="Project ant library" level="project" />
+    <orderEntry type="library" name="Project Scala SDK" level="project" />
+    <orderEntry type="library" name="ant" level="application" />
+  </component>
+</module>
+
diff --git a/src/intellij/scala-lang.ipr.SAMPLE b/src/intellij/scala-lang.ipr.SAMPLE
new file mode 100644
index 0000000..2506c74
--- /dev/null
+++ b/src/intellij/scala-lang.ipr.SAMPLE
@@ -0,0 +1,1446 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+  <component name="AntConfiguration">
+    <defaultAnt bundledAnt="true" />
+    <buildFile url="file://$PROJECT_DIR$/../../build.xml">
+      <additionalClassPath />
+      <antReference projectDefault="true" />
+      <customJdkName value="" />
+      <maximumHeapSize value="128" />
+      <maximumStackSize value="32" />
+      <properties />
+    </buildFile>
+  </component>
+  <component name="BuildJarProjectSettings">
+    <option name="BUILD_JARS_ON_MAKE" value="false" />
+  </component>
+  <component name="CodeStyleSettingsManager">
+    <option name="PER_PROJECT_SETTINGS">
+      <value>
+        <ADDITIONAL_INDENT_OPTIONS fileType="java">
+          <option name="INDENT_SIZE" value="4" />
+          <option name="CONTINUATION_INDENT_SIZE" value="8" />
+          <option name="TAB_SIZE" value="4" />
+          <option name="USE_TAB_CHARACTER" value="false" />
+          <option name="SMART_TABS" value="false" />
+          <option name="LABEL_INDENT_SIZE" value="0" />
+          <option name="LABEL_INDENT_ABSOLUTE" value="false" />
+        </ADDITIONAL_INDENT_OPTIONS>
+        <ADDITIONAL_INDENT_OPTIONS fileType="jsp">
+          <option name="INDENT_SIZE" value="4" />
+          <option name="CONTINUATION_INDENT_SIZE" value="8" />
+          <option name="TAB_SIZE" value="4" />
+          <option name="USE_TAB_CHARACTER" value="false" />
+          <option name="SMART_TABS" value="false" />
+          <option name="LABEL_INDENT_SIZE" value="0" />
+          <option name="LABEL_INDENT_ABSOLUTE" value="false" />
+        </ADDITIONAL_INDENT_OPTIONS>
+        <ADDITIONAL_INDENT_OPTIONS fileType="xml">
+          <option name="INDENT_SIZE" value="4" />
+          <option name="CONTINUATION_INDENT_SIZE" value="8" />
+          <option name="TAB_SIZE" value="4" />
+          <option name="USE_TAB_CHARACTER" value="false" />
+          <option name="SMART_TABS" value="false" />
+          <option name="LABEL_INDENT_SIZE" value="0" />
+          <option name="LABEL_INDENT_ABSOLUTE" value="false" />
+        </ADDITIONAL_INDENT_OPTIONS>
+      </value>
+    </option>
+  </component>
+  <component name="CompilerAPISettings">
+    <option name="DEBUGGING_INFO" value="true" />
+    <option name="GENERATE_NO_WARNINGS" value="false" />
+    <option name="DEPRECATION" value="true" />
+    <option name="ADDITIONAL_OPTIONS_STRING" value="" />
+    <option name="MAXIMUM_HEAP_SIZE" value="128" />
+  </component>
+  <component name="CompilerConfiguration">
+    <option name="DEFAULT_COMPILER" value="Javac" />
+    <resourceExtensions>
+      <entry name=".+\.(properties|xml|html|dtd|tld)" />
+      <entry name=".+\.(gif|png|jpeg|jpg)" />
+    </resourceExtensions>
+    <wildcardResourcePatterns>
+      <entry name="?*.properties" />
+      <entry name="?*.xml" />
+      <entry name="?*.gif" />
+      <entry name="?*.png" />
+      <entry name="?*.jpeg" />
+      <entry name="?*.jpg" />
+      <entry name="?*.html" />
+      <entry name="?*.dtd" />
+      <entry name="?*.tld" />
+      <entry name="?*.ftl" />
+    </wildcardResourcePatterns>
+    <annotationProcessing enabled="false" useClasspath="true" />
+  </component>
+  <component name="CopyrightManager" default="">
+    <module2copyright />
+  </component>
+  <component name="DependencyValidationManager">
+    <option name="SKIP_IMPORT_STATEMENTS" value="false" />
+  </component>
+  <component name="EclipseCompilerSettings">
+    <option name="DEBUGGING_INFO" value="true" />
+    <option name="GENERATE_NO_WARNINGS" value="true" />
+    <option name="DEPRECATION" value="false" />
+    <option name="ADDITIONAL_OPTIONS_STRING" value="" />
+    <option name="MAXIMUM_HEAP_SIZE" value="128" />
+  </component>
+  <component name="EclipseEmbeddedCompilerSettings">
+    <option name="DEBUGGING_INFO" value="true" />
+    <option name="GENERATE_NO_WARNINGS" value="true" />
+    <option name="DEPRECATION" value="false" />
+    <option name="ADDITIONAL_OPTIONS_STRING" value="" />
+    <option name="MAXIMUM_HEAP_SIZE" value="128" />
+  </component>
+  <component name="Encoding" useUTFGuessing="true" native2AsciiForPropertiesFiles="false" />
+  <component name="FacetAutodetectingManager">
+    <autodetection-disabled>
+      <facet-type id="Scala">
+        <modules>
+          <module name="files">
+            <files>
+              <file url="file://$PROJECT_DIR$/../../test/files/android/HelloAndroid.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/ant/fsc.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/ant/scalac.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/ant/scaladoc.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/cldc/randoms.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/cli/test1/Main.check.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/cli/test1/Main.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/cli/test2/Main.check.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/cli/test2/Main.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/cli/test3/Main.check.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/cli/test3/Main.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/jvm/JavaInteraction.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/jvm/bigints.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/jvm/bug560bis.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/jvm/inner.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/jvm/manifests.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/jvm/methvsfield.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/jvm/natives.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/jvm/nest.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/jvm/protectedacc.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/jvm/serialization.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/jvm/t0632.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/jvm/t1116.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/jvm/t1143-2/t1143-2.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/jvm/t1143.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/jvm/typerep.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/jvm/unittest_io.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/jvm/unittest_xml.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/jvm/xml01.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/jvm/xml02.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/jvm/xml03syntax.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/jvm/xml04embed.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/jvm/xmlattr.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/jvm/xmlmore.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/jvm/xmlpull.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/jvm/xmlstuff.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/jvm5/annotations.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/jvm5/bug676.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/jvm5/bug680.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/jvm5/console.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/jvm5/genericNest.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/jvm5/interpreter.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/jvm5/outerEnum.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/jvm5/stringbuilder.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/jvm5/sync-var.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/jvm5/t0014.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/jvm5/t1461.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/jvm5/t1464/MyTrait.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/jvm5/throws-annot.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/jvm5/typerep.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/abstract.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/accesses.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/annot-nonconst.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/badtok-1.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/badtok-2.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/badtok-3.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug1010.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug1011.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug1017.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug1041.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug1106.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug1112.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug112706A.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug1181.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug1183.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug1224.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug1241.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug1275.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug1392.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug1523.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug1623.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug1838.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug200.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug276.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug278.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug284.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug343.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug391.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug409.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug412.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug414.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug418.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug421.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug452.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug473.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug500.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug501.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug510.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug512.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug515.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug520.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug521.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug545.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug550.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug555.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug556.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug558.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug562.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug563.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug565.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug576.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug585.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug588.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug591.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug593.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug608.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug630.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug631.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug633.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug639.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug649.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug650.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug663.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug664.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug667.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug668.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug677.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug691.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug692.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug693.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug696.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug700.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug708.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug712.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug715.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug729.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug752.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug765.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug766.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug779.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug783.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug798.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug800.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug835.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug836.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug845.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug846.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug856.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug875.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug876.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug877.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug882.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug900.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug908.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug909.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug910.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug935.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug944.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug960.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug961.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug987.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/bug997.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/checksensible.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/constrs.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/cyclics.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/divergent-implicit.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/faculty.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/forward.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/gadts1.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/higherkind_novalue.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/imp2.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/implicits.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/lazy-override.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/lazyvals.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/lubs.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/mixins.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/multi-array.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/nopredefs.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/null-unsoundness.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/overload.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/parstar.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/patmatexhaust.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/patternalts.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/plugin-after-terminal/src/ThePlugin.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/plugin-after-terminal/testsource.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/plugin-before-parser/src/ThePlugin.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/plugin-before-parser/testsource.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/plugin-cyclic-dependency/src/ThePlugin.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/plugin-cyclic-dependency/testsource.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/plugin-multiple-rafter/src/ThePlugin.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/plugin-multiple-rafter/testsource.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/plugin-rafter-before-1/src/ThePlugin.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/plugin-rafter-before-1/testsource.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/plugin-rightafter-terminal/src/ThePlugin.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/plugin-rightafter-terminal/testsource.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/sabin2.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/saito.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/sensitive.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/structural.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/switch.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/t0003.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/t0015.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/t0117.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/t0152.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/t0204.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/t0207.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/t0209.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/t0214.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/t0218.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/t0226.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/t0259.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/t0345.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/t0351.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/t0503.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/t0528neg.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/t0590.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/t0606.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/t0673/Test.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/t0699/A.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/t0699/B.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/t0764.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/t0842.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/t0899.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/t0903.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/t1009.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/t1033.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/t1049.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/t1163.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/t1168.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/t1215.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/t1371.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/t1659.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/tailrec.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/tcpoly_bounds.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/tcpoly_override.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/tcpoly_typealias.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/tcpoly_variance.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/tcpoly_variance_enforce.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/typeerror.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/unreachablechar.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/variances.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/viewtest.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/volatile-intersection.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/volatile.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/wellkinded_app.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/wellkinded_app2.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/wellkinded_bounds.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/wellkinded_wrongarity.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/wellkinded_wrongarity2.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/xmlcorner.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/xmltruncated1.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/xmltruncated2.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/xmltruncated3.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/xmltruncated4.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/xmltruncated5.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/neg/xmltruncated6.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/A.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/List1.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/MailBox.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/NoCyclicReference.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/S1.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/S3.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/S5.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/S8.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/Transactions.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/X.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/Z.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/abstract.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/aliases.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/annot-inner.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/annotations.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/arrays2.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/attributes.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bounds.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug0002.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug0017.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug0020.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug0029.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug0030.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug0031.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug0032.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug0036.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug0039.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug0049.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug0053.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug0054.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug0061.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug0064.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug0066.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug0068.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug0069.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug0076.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug0081.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug0082.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug0085.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug0091.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug0093.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug0123.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug0204.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug0304.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug0325.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug0422.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug0599.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug0646.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug1000.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug1001.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug1006.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug1014.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug1034.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug1049.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug1050.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug1056.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug1070.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug1075.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug1085.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug1087.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug1090.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug1107.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug1119.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug1123.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug112606A.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug1136.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug115.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug116.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug1168.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug1185.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug119.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug1203.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug121.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug1210.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug1210a.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug122.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug1237.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug124.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug1241.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug1279a.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug1292.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug1385.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug151.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug1565.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug159.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug160.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug175.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug177.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug183.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug1858.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug201.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug210.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug211.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug229.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug245.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug247.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug262.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug267.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug284.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug287.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug289.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug295.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug296.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug304.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug318.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug319.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug342.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug344.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug348plus.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug359.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug360.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug361.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug372.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug374.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug389.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug397.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug402.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug404.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug415.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug419.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug422.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug430-feb09.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug430.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug432.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug439.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug443.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug460.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug514.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug516.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug522.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug530.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug531.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug532.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug533.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug566.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug577.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug592.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug595.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug596.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug599.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug602.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug604.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug607.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug611.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug613.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug615.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug616.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug628.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug640.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug651.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug661.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug675.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug684.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug690.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug694.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug697.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug698.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug703.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug704.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug711.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug720.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug756.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug757.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug757a.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug758.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug759.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug762.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug767.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug780.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug788.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug789.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug796.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug802.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug803.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug805.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug807.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug812.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug839.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug851.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug873.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug880.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug892.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug911.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug927.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/bug946.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/builders.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/caseaccs.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/cfcrash.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/channels.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/cls.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/cls1.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/clsrefine.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/code.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/collections.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/comp-rec-test.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/compile.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/compile1.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/compound.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/constfold.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/contrib467.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/contrib701.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/cyclics.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/escapes2.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/eta.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/exceptions.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/functions.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/gadt-gilles.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/gadts2.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/gosh.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/gui.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/homonym.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/imp2.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/imports.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/infer.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/infer2.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/inferbroadtype.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/init.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/itay.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/jesper.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/kinzer.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/ksbug1.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/lambda.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/lambdalift.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/lambdalift1.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/largecasetest.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/listpattern.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/localmodules.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/looping-jsig.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/manifest1.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/matchStarlift.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/matthias1.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/matthias3.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/matthias4.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/matthias5.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/maxim1.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/michel1.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/michel2.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/michel3.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/michel4.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/michel5.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/michel6.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/mixins.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/modules.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/modules1.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/moduletrans.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/needstypeearly.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/nested.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/nested2.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/null.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/nullary.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/nullary_poly.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/override.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/partialfun.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/pat_gilles.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/pat_iuli.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/patterns.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/patterns1.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/patterns1213.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/patterns2.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/patterns3.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/philippe1.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/philippe2.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/philippe3.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/philippe4.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/pmbug.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/proj-rec-test.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/propagate.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/protected-t1010.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/rebind.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/return_thistype.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/scoping1.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/scoping2.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/scoping3.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/seqtest2.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/simplelists.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/stable.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/strings.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/sudoku.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/t0055.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/t0154.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/t0165.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/t0227.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/t0231.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/t0273.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/t0288/Foo.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/t0301.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/t0438.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/t0453.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/t0504.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/t0586.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/t0591.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/t0651.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/t0654.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/t0674.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/t0710.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/t0770.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/t0774/deathname.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/t0774/unrelated.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/t0786.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/t0851.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/t0872.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/t0904.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/t0905.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/t0999.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/t1001.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/t1027.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/t1049.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/t1059.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/t1087.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/t1107/O.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/t1107/T.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/t1131.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/t1146.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/t1147.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/t1159.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/t1164.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/t1280.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/t1380/hallo.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/t1391.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/t1409/ConcreteImpl.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/t1438.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/t1439.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/t1480.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/t1648.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/t1675.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/t1761.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/t1789.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/t1840/S.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/tcpoly_boundedmonad.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/tcpoly_bounds1.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/tcpoly_checkkinds_mix.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/tcpoly_gm.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/tcpoly_higherorder_bound_method.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/tcpoly_late_method_params.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/tcpoly_method.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/tcpoly_overloaded.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/tcpoly_param_scoping.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/tcpoly_poly.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/tcpoly_return_overriding.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/tcpoly_seq.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/tcpoly_seq_typealias.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/tcpoly_subst.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/tcpoly_typeapp.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/tcpoly_typesub.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/tcpoly_variance.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/tcpoly_wildcards.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/ted.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/test1.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/test2.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/test4.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/test4a.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/test4refine.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/test5.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/test5refine.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/testcast.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/thistype.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/thistypes.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/ticket0137.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/tinondefcons.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/traits.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/tryexpr.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/typealias_dubious.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/typealiases.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/typerep-stephane.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/typerep.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/typesafecons.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/unapply.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/unapplyComplex.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/unapplyContexts2.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/unapplyGeneric.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/unapplyNeedsMemberType.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/unapplySeq.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/unapplyVal.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/unicode-decode.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/valdefs.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/variances.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/viewtest1.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos/viewtest2.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos5/chang/Test.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos5/ilya/S.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos5/ilya2/A.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos5/signatures/sig.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos5/t0695/Test.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos5/t1101/S.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos5/t1102/S.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos5/t1150/S.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos5/t1152/S.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos5/t1176/S.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos5/t1196/S.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos5/t1197/S.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos5/t1203/S.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos5/t1230/S.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos5/t1231/S.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos5/t1232/S.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos5/t1263/test.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/pos5/t1711/Seq.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/res/bug597/Main.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/res/bug597/Test.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/res/bug687/QueryA.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/res/bug687/QueryB.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/res/bug722/IfElse.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/res/bug722/Parser.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/res/bug722/ScanBased.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/res/bug735/ScalaExpressions.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/res/bug735/ScalaTyper.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/res/bug743/BracesXXX.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/res/bug743/ParserXXX.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/res/bug785/ScalaNewTyper.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/res/bug785/ScalaTrees.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/res/bug831/NewScalaParserXXX.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/res/bug831/NewScalaTestXXX.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/Course-2002-01.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/Course-2002-02.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/Course-2002-03.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/Course-2002-04.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/Course-2002-05.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/Course-2002-06.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/Course-2002-07.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/Course-2002-08.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/Course-2002-09.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/Course-2002-10.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/Course-2002-13.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/NestedClasses.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/absoverride.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/amp.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/arrays.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/arybufgrow.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/bitsets.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/boolexprs.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/boolord.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/bridges.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/bug0325.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/bug1074.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/bug1192.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/bug1220.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/bug216.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/bug405.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/bug428.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/bug429.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/bug594.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/bug601.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/bug603.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/bug627.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/bug629.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/bug657.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/bug744.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/bug889.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/bug920.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/bug949.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/bug978.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/bugs.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/byname.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/caseclasses.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/checked.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/classof.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/collection-stacks.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/collections.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/colltest.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/complicatedmatch.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/constrained-types.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/constructors.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/contrib674.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/ctor-order.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/deeps.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/docgenerator.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/enums.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/exceptions-2.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/exceptions.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/existentials.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/exoticnames.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/fors.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/forvaleq.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/gadts.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/impconvtimes.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/implicits.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/imports.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/infiniteloop.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/infix.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/intmap.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/iq.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/issue192.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/iterables.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/iterators.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/json.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/jtptest.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/lazy-exprs.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/lazy-locals.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/lazy-override.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/lazy-traits.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/lisp.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/lists.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/literals.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/map_test.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/matcharraytail.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/matchbytes.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/matchemptyarray.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/matchintasany.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/matchonstream.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/misc.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/missingparams.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/mixins.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/multi-array.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/overloads.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/patmatnew.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/promotion.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/randomAccessSeq-apply.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/range.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/retclosure.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/retsynch.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/richs.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/runtime-richChar.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/runtime.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/slices.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/sort.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/streams.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/structural.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/syncchannel.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/t0005.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/t0017.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/t0042.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/t0091.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/t0412.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/t0421.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/t0485.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/t0486.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/t0508.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/t0528.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/t0607.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/t0631.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/t0663.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/t0668.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/t0677.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/t0700.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/t0807.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/t0883.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/t0911.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/t0936.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/t1323.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/t1368.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/t1423.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/t1500.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/t1501.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/t1505.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/t1524.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/t1535.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/t1618.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/t1620.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/t1718.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/t1747.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/t1829.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/tailcalls.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/tcpoly_monads.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/tcpoly_overriding.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/tcpoly_parseridioms.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/try-2.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/try.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/tuples.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/typealias_overriding.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/unapply.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/unapplyArray.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/unboxingBug.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/unittest_collection.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/unittest_io.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/verify-ctor.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/run/withIndex.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/scalacheck/list.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/script/fact.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/script/second.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/script/t1015.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/script/t1017.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/script/utf8.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/shootout/ackermann.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/shootout/ary.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/shootout/binarytrees.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/shootout/binarytrees.scala-2.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/shootout/binarytrees.scala-3.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/shootout/chameneos.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/shootout/except.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/shootout/fannkuch.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/shootout/fannkuch.scala-2.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/shootout/fibo.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/shootout/harmonic.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/shootout/hash.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/shootout/hash2.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/shootout/hello.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/shootout/knucleotide.scala-2.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/shootout/knucleotide.scala-3.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/shootout/lists.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/shootout/message.scala-2.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/shootout/nbody.scala-2.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/shootout/nestedloop.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/shootout/nsieve.scala-2.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/shootout/nsieve.scala-3.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/shootout/nsievebits.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/shootout/nsievebits.scala-2.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/shootout/nsievebits.scala-3.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/shootout/objinst.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/shootout/partialsums.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/shootout/partialsums.scala-2.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/shootout/recursive.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/shootout/regexdna.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/shootout/spectralnorm.scala-2.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/shootout/strcat.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/shootout/sumcol.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/shootout/sumcol.scala-2.scala" />
+              <file url="file://$PROJECT_DIR$/../../test/files/shootout/takfp.scala" />
+            </files>
+          </module>
+          <module name="library">
+            <files>
+              <file url="file://$PROJECT_DIR$/../android-library/scala/ScalaObject.scala" />
+              <file url="file://$PROJECT_DIR$/../android-library/scala/reflect/ScalaBeanInfo.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/Application.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/BigDecimal.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/BigInt.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/Console.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/Math.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/Numeric.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/Ordering.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/Predef.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/Range.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/Symbol.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/collection/JavaConversions.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/collection/immutable/List.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/collection/immutable/PagedSeq.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/collection/mutable/OpenHashMap.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/collection/mutable/StringBuilder.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/collection/mutable/WeakHashMap.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/compat/Platform.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/concurrent/DelayedLazyVal.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/concurrent/jolib.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/concurrent/ops.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/concurrent/pilib.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/io/BufferedSource.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/io/BytePickle.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/io/Codec.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/io/File.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/io/Position.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/io/Source.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/io/UTF8Codec.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/mobile/Code.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/mobile/Location.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/net/Utility.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/ref/PhantomReference.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/ref/ReferenceQueue.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/ref/ReferenceWrapper.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/ref/SoftReference.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/ref/WeakReference.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/reflect/Invocation.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/reflect/Manifest.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/reflect/ScalaBeanInfo.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/runtime/MethodCache.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/runtime/NonLocalReturnControl.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/runtime/RichChar.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/runtime/RichClass.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/runtime/RichDouble.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/runtime/RichException.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/runtime/RichFloat.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/runtime/RichInt.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/runtime/RichLong.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/runtime/RichString.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/runtime/StringAdd.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/testing/Benchmark.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/testing/SUnit.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/testing/Show.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/text/Document.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/util/ClassLoader.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/util/DynamicVariable.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/util/Marshal.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/util/NameTransformer.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/util/Properties.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/util/Random.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/util/automata/BaseBerrySethi.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/util/automata/DetWordAutom.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/util/automata/Inclusion.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/util/automata/NondetWordAutom.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/util/automata/SubsetConstruction.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/util/automata/WordBerrySethi.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/util/control/Exception.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/util/grammar/HedgeRHS.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/util/grammar/TreeRHS.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/util/logging/ConsoleLogger.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/util/logging/Logged.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/util/matching/Regex.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/util/parsing/ast/AbstractSyntax.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/util/parsing/ast/Binders.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/util/parsing/combinator/ImplicitConversions.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/util/parsing/combinator/JavaTokenParsers.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/util/parsing/combinator/PackratParsers.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/util/parsing/combinator/Parsers.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/util/parsing/combinator/RegexParsers.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/util/parsing/combinator/lexical/Lexical.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/util/parsing/combinator/lexical/Scanners.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/util/parsing/combinator/lexical/StdLexical.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/util/parsing/combinator/syntactical/StandardTokenParsers.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/util/parsing/combinator/syntactical/StdTokenParsers.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/util/parsing/combinator/syntactical/TokenParsers.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/util/parsing/combinator/testing/RegexTest.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/util/parsing/combinator/testing/Tester.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/util/parsing/combinatorold/$tilde.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/util/parsing/combinatorold/ImplicitConversions.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/util/parsing/combinatorold/Parsers.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/util/parsing/combinatorold/lexical/Lexical.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/util/parsing/combinatorold/lexical/Scanners.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/util/parsing/combinatorold/lexical/StdLexical.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/util/parsing/combinatorold/syntactical/BindingParsers.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/util/parsing/combinatorold/syntactical/StdTokenParsers.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/util/parsing/combinatorold/syntactical/TokenParsers.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/util/parsing/combinatorold/testing/Tester.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/util/parsing/input/CharArrayPosition.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/util/parsing/input/CharArrayReader.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/util/parsing/input/CharSequenceReader.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/util/parsing/input/NoPosition.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/util/parsing/input/OffsetPosition.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/util/parsing/input/PagedSeqReader.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/util/parsing/input/Position.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/util/parsing/input/Positional.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/util/parsing/input/Reader.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/util/parsing/input/StreamReader.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/util/parsing/json/JSON.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/util/parsing/json/Lexer.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/util/parsing/json/Parser.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/util/parsing/syntax/StdTokens.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/util/parsing/syntax/Tokens.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/util/regexp/Base.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/util/regexp/PointedHedgeExp.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/util/regexp/SyntaxError.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/util/regexp/WordExp.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/Atom.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/Attribute.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/Comment.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/Document.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/Elem.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/EntityRef.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/Group.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/HasKeyValue.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/MalformedAttributeException.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/MetaData.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/NamespaceBinding.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/Node.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/NodeBuffer.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/NodeSeq.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/NodeTraverser.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/Null.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/PCData.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/Parsing.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/PrefixedAttribute.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/PrettyPrinter.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/ProcInstr.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/QNode.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/SpecialNode.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/Text.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/TextBuffer.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/TopScope.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/TypeSymbol.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/Unparsed.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/UnprefixedAttribute.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/Utility.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/XML.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/Xhtml.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/dtd/ContentModel.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/dtd/ContentModelParser.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/dtd/DTD.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/dtd/Decl.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/dtd/DocType.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/dtd/DtdTypeSymbol.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/dtd/ElementValidator.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/dtd/ExternalID.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/dtd/Scanner.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/dtd/Tokens.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/dtd/ValidationException.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/factory/Binder.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/factory/LoggedNodeFactory.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/factory/NodeFactory.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/factory/XMLLoader.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/include/CircularIncludeException.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/include/UnavailableResourceException.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/include/XIncludeException.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/include/sax/EncodingHeuristics.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/include/sax/Main.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/include/sax/XIncludeFilter.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/include/sax/XIncluder.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/parsing/ConstructingHandler.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/parsing/ConstructingParser.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/parsing/DefaultMarkupHandler.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/parsing/ExternalSources.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/parsing/FactoryAdapter.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/parsing/FatalError.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/parsing/MarkupHandler.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/parsing/MarkupParser.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/parsing/NoBindingFactoryAdapter.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/parsing/TokenTests.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/parsing/ValidatingMarkupHandler.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/parsing/XhtmlEntities.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/parsing/XhtmlParser.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/path/Expression.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/persistent/CachedFileStorage.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/persistent/Index.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/persistent/IndexedStorage.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/persistent/SetStorage.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/pull/XMLEvent.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/pull/XMLEventReader.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/transform/BasicTransformer.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/transform/RewriteRule.scala" />
+              <file url="file://$PROJECT_DIR$/../dotnet-library/scala/xml/transform/RuleTransformer.scala" />
+              <file url="file://$PROJECT_DIR$/../scalap/scala/tools/scalap/scalax/rules/scalasig/ScalaSigPrinter.scala" />
+            </files>
+          </module>
+        </modules>
+      </facet-type>
+    </autodetection-disabled>
+  </component>
+  <component name="IdProvider" IDEtalkID="522B472C2EA573563CC2BA93160270BE" />
+  <component name="InspectionProjectProfileManager">
+    <list size="5">
+      <item index="0" class="java.lang.String" itemvalue="TYPO" />
+      <item index="1" class="java.lang.String" itemvalue="SERVER PROBLEM" />
+      <item index="2" class="java.lang.String" itemvalue="INFO" />
+      <item index="3" class="java.lang.String" itemvalue="WARNING" />
+      <item index="4" class="java.lang.String" itemvalue="ERROR" />
+    </list>
+  </component>
+  <component name="JavacSettings">
+    <option name="DEBUGGING_INFO" value="true" />
+    <option name="GENERATE_NO_WARNINGS" value="false" />
+    <option name="DEPRECATION" value="true" />
+    <option name="ADDITIONAL_OPTIONS_STRING" value="" />
+    <option name="MAXIMUM_HEAP_SIZE" value="128" />
+  </component>
+  <component name="JavadocGenerationManager">
+    <option name="OUTPUT_DIRECTORY" />
+    <option name="OPTION_SCOPE" value="protected" />
+    <option name="OPTION_HIERARCHY" value="true" />
+    <option name="OPTION_NAVIGATOR" value="true" />
+    <option name="OPTION_INDEX" value="true" />
+    <option name="OPTION_SEPARATE_INDEX" value="true" />
+    <option name="OPTION_DOCUMENT_TAG_USE" value="false" />
+    <option name="OPTION_DOCUMENT_TAG_AUTHOR" value="false" />
+    <option name="OPTION_DOCUMENT_TAG_VERSION" value="false" />
+    <option name="OPTION_DOCUMENT_TAG_DEPRECATED" value="true" />
+    <option name="OPTION_DEPRECATED_LIST" value="true" />
+    <option name="OTHER_OPTIONS" value="" />
+    <option name="HEAP_SIZE" />
+    <option name="LOCALE" />
+    <option name="OPEN_IN_BROWSER" value="true" />
+  </component>
+  <component name="JikesSettings">
+    <option name="JIKES_PATH" value="" />
+    <option name="DEBUGGING_INFO" value="true" />
+    <option name="DEPRECATION" value="true" />
+    <option name="GENERATE_NO_WARNINGS" value="false" />
+    <option name="IS_EMACS_ERRORS_MODE" value="true" />
+    <option name="ADDITIONAL_OPTIONS_STRING" value="" />
+  </component>
+  <component name="Palette2">
+    <group name="Swing">
+      <item class="com.intellij.uiDesigner.HSpacer" tooltip-text="Horizontal Spacer" icon="/com/intellij/uiDesigner/icons/hspacer.png" removable="false" auto-create-binding="false" can-attach-label="false">
+        <default-constraints vsize-policy="1" hsize-policy="6" anchor="0" fill="1" />
+      </item>
+      <item class="com.intellij.uiDesigner.VSpacer" tooltip-text="Vertical Spacer" icon="/com/intellij/uiDesigner/icons/vspacer.png" removable="false" auto-create-binding="false" can-attach-label="false">
+        <default-constraints vsize-policy="6" hsize-policy="1" anchor="0" fill="2" />
+      </item>
+      <item class="javax.swing.JPanel" icon="/com/intellij/uiDesigner/icons/panel.png" removable="false" auto-create-binding="false" can-attach-label="false">
+        <default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3" />
+      </item>
+      <item class="javax.swing.JScrollPane" icon="/com/intellij/uiDesigner/icons/scrollPane.png" removable="false" auto-create-binding="false" can-attach-label="true">
+        <default-constraints vsize-policy="7" hsize-policy="7" anchor="0" fill="3" />
+      </item>
+      <item class="javax.swing.JButton" icon="/com/intellij/uiDesigner/icons/button.png" removable="false" auto-create-binding="true" can-attach-label="false">
+        <default-constraints vsize-policy="0" hsize-policy="3" anchor="0" fill="1" />
+        <initial-values>
+          <property name="text" value="Button" />
+        </initial-values>
+      </item>
+      <item class="javax.swing.JRadioButton" icon="/com/intellij/uiDesigner/icons/radioButton.png" removable="false" auto-create-binding="true" can-attach-label="false">
+        <default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
+        <initial-values>
+          <property name="text" value="RadioButton" />
+        </initial-values>
+      </item>
+      <item class="javax.swing.JCheckBox" icon="/com/intellij/uiDesigner/icons/checkBox.png" removable="false" auto-create-binding="true" can-attach-label="false">
+        <default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
+        <initial-values>
+          <property name="text" value="CheckBox" />
+        </initial-values>
+      </item>
+      <item class="javax.swing.JLabel" icon="/com/intellij/uiDesigner/icons/label.png" removable="false" auto-create-binding="false" can-attach-label="false">
+        <default-constraints vsize-policy="0" hsize-policy="0" anchor="8" fill="0" />
+        <initial-values>
+          <property name="text" value="Label" />
+        </initial-values>
+      </item>
+      <item class="javax.swing.JTextField" icon="/com/intellij/uiDesigner/icons/textField.png" removable="false" auto-create-binding="true" can-attach-label="true">
+        <default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
+          <preferred-size width="150" height="-1" />
+        </default-constraints>
+      </item>
+      <item class="javax.swing.JPasswordField" icon="/com/intellij/uiDesigner/icons/passwordField.png" removable="false" auto-create-binding="true" can-attach-label="true">
+        <default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
+          <preferred-size width="150" height="-1" />
+        </default-constraints>
+      </item>
+      <item class="javax.swing.JFormattedTextField" icon="/com/intellij/uiDesigner/icons/formattedTextField.png" removable="false" auto-create-binding="true" can-attach-label="true">
+        <default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
+          <preferred-size width="150" height="-1" />
+        </default-constraints>
+      </item>
+      <item class="javax.swing.JTextArea" icon="/com/intellij/uiDesigner/icons/textArea.png" removable="false" auto-create-binding="true" can-attach-label="true">
+        <default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
+          <preferred-size width="150" height="50" />
+        </default-constraints>
+      </item>
+      <item class="javax.swing.JTextPane" icon="/com/intellij/uiDesigner/icons/textPane.png" removable="false" auto-create-binding="true" can-attach-label="true">
+        <default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
+          <preferred-size width="150" height="50" />
+        </default-constraints>
+      </item>
+      <item class="javax.swing.JEditorPane" icon="/com/intellij/uiDesigner/icons/editorPane.png" removable="false" auto-create-binding="true" can-attach-label="true">
+        <default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
+          <preferred-size width="150" height="50" />
+        </default-constraints>
+      </item>
+      <item class="javax.swing.JComboBox" icon="/com/intellij/uiDesigner/icons/comboBox.png" removable="false" auto-create-binding="true" can-attach-label="true">
+        <default-constraints vsize-policy="0" hsize-policy="2" anchor="8" fill="1" />
+      </item>
+      <item class="javax.swing.JTable" icon="/com/intellij/uiDesigner/icons/table.png" removable="false" auto-create-binding="true" can-attach-label="false">
+        <default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
+          <preferred-size width="150" height="50" />
+        </default-constraints>
+      </item>
+      <item class="javax.swing.JList" icon="/com/intellij/uiDesigner/icons/list.png" removable="false" auto-create-binding="true" can-attach-label="false">
+        <default-constraints vsize-policy="6" hsize-policy="2" anchor="0" fill="3">
+          <preferred-size width="150" height="50" />
+        </default-constraints>
+      </item>
+      <item class="javax.swing.JTree" icon="/com/intellij/uiDesigner/icons/tree.png" removable="false" auto-create-binding="true" can-attach-label="false">
+        <default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
+          <preferred-size width="150" height="50" />
+        </default-constraints>
+      </item>
+      <item class="javax.swing.JTabbedPane" icon="/com/intellij/uiDesigner/icons/tabbedPane.png" removable="false" auto-create-binding="true" can-attach-label="false">
+        <default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
+          <preferred-size width="200" height="200" />
+        </default-constraints>
+      </item>
+      <item class="javax.swing.JSplitPane" icon="/com/intellij/uiDesigner/icons/splitPane.png" removable="false" auto-create-binding="false" can-attach-label="false">
+        <default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
+          <preferred-size width="200" height="200" />
+        </default-constraints>
+      </item>
+      <item class="javax.swing.JSpinner" icon="/com/intellij/uiDesigner/icons/spinner.png" removable="false" auto-create-binding="true" can-attach-label="true">
+        <default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
+      </item>
+      <item class="javax.swing.JSlider" icon="/com/intellij/uiDesigner/icons/slider.png" removable="false" auto-create-binding="true" can-attach-label="false">
+        <default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
+      </item>
+      <item class="javax.swing.JSeparator" icon="/com/intellij/uiDesigner/icons/separator.png" removable="false" auto-create-binding="false" can-attach-label="false">
+        <default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3" />
+      </item>
+      <item class="javax.swing.JProgressBar" icon="/com/intellij/uiDesigner/icons/progressbar.png" removable="false" auto-create-binding="true" can-attach-label="false">
+        <default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1" />
+      </item>
+      <item class="javax.swing.JToolBar" icon="/com/intellij/uiDesigner/icons/toolbar.png" removable="false" auto-create-binding="false" can-attach-label="false">
+        <default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1">
+          <preferred-size width="-1" height="20" />
+        </default-constraints>
+      </item>
+      <item class="javax.swing.JToolBar$Separator" icon="/com/intellij/uiDesigner/icons/toolbarSeparator.png" removable="false" auto-create-binding="false" can-attach-label="false">
+        <default-constraints vsize-policy="0" hsize-policy="0" anchor="0" fill="1" />
+      </item>
+      <item class="javax.swing.JScrollBar" icon="/com/intellij/uiDesigner/icons/scrollbar.png" removable="false" auto-create-binding="true" can-attach-label="false">
+        <default-constraints vsize-policy="6" hsize-policy="0" anchor="0" fill="2" />
+      </item>
+    </group>
+  </component>
+  <component name="ProjectDetails">
+    <option name="projectName" value="scala-lang" />
+  </component>
+  <component name="ProjectDictionaryState">
+    <dictionary name="dragos" />
+    <dictionary name="odersky" />
+  </component>
+  <component name="ProjectKey">
+    <option name="state" value="https://lampsvn.epfl.ch/svn-repos/scala/scala/trunk/scala-lang.ipr" />
+  </component>
+  <component name="ProjectModuleManager">
+    <modules>
+      <module fileurl="file://$PROJECT_DIR$/actors.iml" filepath="$PROJECT_DIR$/actors.iml" />
+      <module fileurl="file://$PROJECT_DIR$/compiler.iml" filepath="$PROJECT_DIR$/compiler.iml" />
+      <module fileurl="file://$PROJECT_DIR$/dbc.iml" filepath="$PROJECT_DIR$/dbc.iml" />
+      <module fileurl="file://$PROJECT_DIR$/library.iml" filepath="$PROJECT_DIR$/library.iml" />
+      <module fileurl="file://$PROJECT_DIR$/manual.iml" filepath="$PROJECT_DIR$/manual.iml" />
+      <module fileurl="file://$PROJECT_DIR$/partest.iml" filepath="$PROJECT_DIR$/partest.iml" />
+      <module fileurl="file://$PROJECT_DIR$/scalap.iml" filepath="$PROJECT_DIR$/scalap.iml" />
+      <module fileurl="file://$PROJECT_DIR$/swing.iml" filepath="$PROJECT_DIR$/swing.iml" />
+    </modules>
+  </component>
+  <component name="ProjectRootManager" version="2" languageLevel="JDK_1_5" assert-keyword="true" jdk-15="true" project-jdk-name="1.6" project-jdk-type="JavaSDK">
+    <output url="file://$PROJECT_DIR$/../../out" />
+  </component>
+  <component name="ResourceManagerContainer">
+    <option name="myResourceBundles">
+      <value>
+        <list size="0" />
+      </value>
+    </option>
+  </component>
+  <component name="RmicSettings">
+    <option name="IS_EANABLED" value="false" />
+    <option name="DEBUGGING_INFO" value="true" />
+    <option name="GENERATE_NO_WARNINGS" value="false" />
+    <option name="GENERATE_IIOP_STUBS" value="false" />
+    <option name="ADDITIONAL_OPTIONS_STRING" value="" />
+  </component>
+  <component name="ScalaSettings">
+    <option name="MAXIMUM_HEAP_SIZE" value="1024" />
+    <option name="DEPRECATION" value="false" />
+    <option name="UNCHECKED" value="false" />
+  </component>
+  <component name="SvnBranchConfigurationManager">
+    <option name="myConfigurationMap">
+      <map>
+        <entry key="$PROJECT_DIR$/../..">
+          <value>
+            <SvnBranchConfiguration>
+              <option name="branchMap">
+                <map>
+                  <entry key="https://lampsvn.epfl.ch/svn-repos/scala/scala/branches">
+                    <value>
+                      <list />
+                    </value>
+                  </entry>
+                  <entry key="https://lampsvn.epfl.ch/svn-repos/scala/scala/tags">
+                    <value>
+                      <list />
+                    </value>
+                  </entry>
+                </map>
+              </option>
+              <option name="branchUrls">
+                <list>
+                  <option value="https://lampsvn.epfl.ch/svn-repos/scala/scala/branches" />
+                  <option value="https://lampsvn.epfl.ch/svn-repos/scala/scala/tags" />
+                </list>
+              </option>
+              <option name="trunkUrl" value="https://lampsvn.epfl.ch/svn-repos/scala/scala/trunk" />
+            </SvnBranchConfiguration>
+          </value>
+        </entry>
+      </map>
+    </option>
+    <option name="myVersion" value="124" />
+    <option name="mySupportsUserInfoFilter" value="true" />
+  </component>
+  <component name="VcsDirectoryMappings">
+    <mapping directory="" vcs="svn" />
+  </component>
+  <component name="WebServicesPlugin" addRequiredLibraries="true" />
+  <component name="libraryTable">
+    <library name="Project ant library">
+      <CLASSES>
+        <root url="jar://$PROJECT_DIR$/../../lib/ant/ant-contrib.jar!/" />
+        <root url="jar://$PROJECT_DIR$/../../lib/ant/vizant.jar!/" />
+        <root url="jar://$PROJECT_DIR$/../../lib/ant/maven-ant-tasks-2.0.9.jar!/" />
+        <root url="jar://$PROJECT_DIR$/../../lib/ant/ant-dotnet-1.0.jar!/" />
+      </CLASSES>
+      <JAVADOC />
+      <SOURCES />
+    </library>
+    <library name="Project Scala SDK">
+      <CLASSES>
+        <root url="jar://$PROJECT_DIR$/../../lib/jline.jar!/" />
+        <root url="jar://$PROJECT_DIR$/../../lib/fjbg.jar!/" />
+        <root url="jar://$PROJECT_DIR$/../../lib/ScalaCheck.jar!/" />
+        <root url="jar://$PROJECT_DIR$/../../lib/msil.jar!/" />
+      </CLASSES>
+      <JAVADOC />
+      <SOURCES />
+    </library>
+    <library name="ant">
+      <CLASSES>
+        <root url="jar:///../share/ant/lib/ant.jar!/" />
+      </CLASSES>
+      <JAVADOC />
+      <SOURCES />
+    </library>
+    <library name="locker">
+      <CLASSES>
+        <root url="file://$PROJECT_DIR$/../../build/locker/classes/library" />
+        <root url="file://$PROJECT_DIR$/../../build/locker/classes/compiler" />
+      </CLASSES>
+      <JAVADOC />
+      <SOURCES />
+    </library>
+  </component>
+</project>
+
diff --git a/src/intellij/scalap.iml.SAMPLE b/src/intellij/scalap.iml.SAMPLE
new file mode 100644
index 0000000..48f98a0
--- /dev/null
+++ b/src/intellij/scalap.iml.SAMPLE
@@ -0,0 +1,19 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<module relativePaths="true" type="JAVA_MODULE" version="4">
+  <component name="FacetManager">
+    <facet type="Scala" name="Scala">
+      <configuration />
+    </facet>
+  </component>
+  <component name="NewModuleRootManager" inherit-compiler-output="true">
+    <exclude-output />
+    <content url="file://$MODULE_DIR$/../scalap">
+      <sourceFolder url="file://$MODULE_DIR$/../scalap" isTestSource="false" />
+    </content>
+    <orderEntry type="inheritedJdk" />
+    <orderEntry type="sourceFolder" forTests="false" />
+    <orderEntry type="module" module-name="compiler" />
+    <orderEntry type="module" module-name="library" />
+  </component>
+</module>
+
diff --git a/src/intellij/swing.iml.SAMPLE b/src/intellij/swing.iml.SAMPLE
new file mode 100644
index 0000000..c623fe0
--- /dev/null
+++ b/src/intellij/swing.iml.SAMPLE
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<module relativePaths="true" type="JAVA_MODULE" version="4">
+  <component name="FacetManager">
+    <facet type="Scala" name="Scala">
+      <configuration />
+    </facet>
+  </component>
+  <component name="NewModuleRootManager" inherit-compiler-output="true">
+    <exclude-output />
+    <content url="file://$MODULE_DIR$/../swing">
+      <sourceFolder url="file://$MODULE_DIR$/../swing" isTestSource="false" />
+    </content>
+    <orderEntry type="inheritedJdk" />
+    <orderEntry type="sourceFolder" forTests="false" />
+    <orderEntry type="module" module-name="actors" />
+    <orderEntry type="module" module-name="compiler" />
+    <orderEntry type="module" module-name="library" />
+    <orderEntry type="library" name="Project ant library" level="project" />
+    <orderEntry type="library" name="Project Scala SDK" level="project" />
+  </component>
+</module>
+
diff --git a/src/jline/LICENSE.txt b/src/jline/LICENSE.txt
new file mode 100644
index 0000000..1cdc44c
--- /dev/null
+++ b/src/jline/LICENSE.txt
@@ -0,0 +1,33 @@
+Copyright (c) 2002-2006, Marc Prud'hommeaux <mwp1 at cornell.edu>
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or
+without modification, are permitted provided that the following
+conditions are met:
+
+Redistributions of source code must retain the above copyright
+notice, this list of conditions and the following disclaimer.
+
+Redistributions in binary form must reproduce the above copyright
+notice, this list of conditions and the following disclaimer
+in the documentation and/or other materials provided with
+the distribution.
+
+Neither the name of JLine nor the names of its contributors
+may be used to endorse or promote products derived from this
+software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
+BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
+EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
+OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
+AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
+IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+OF THE POSSIBILITY OF SUCH DAMAGE.
+
diff --git a/src/jline/pom.xml b/src/jline/pom.xml
new file mode 100644
index 0000000..ac0e188
--- /dev/null
+++ b/src/jline/pom.xml
@@ -0,0 +1,224 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+To build, you need to have Maven 2 installed.
+
+To compile, run:
+
+    mvn compile
+
+To run tests, run:
+
+    mvn test
+
+To run one particular test, e.g. TestSomeTest, run:
+
+    mvn test -Dtest=TestSomeTest
+
+To build the jars, run:
+
+    mvn package
+
+To create and upload a release, run:
+
+    mvn deploy
+
+To build the site and upload it, run:
+
+    mvn site:deploy
+
+To perform a complete release, run:
+
+    mvn clean compile package site assembly:assembly deploy site:deploy
+
+To actually upload the artifact to sourceforge, it must be manually ftp'd:
+
+    lftp ftp://upload.sourceforge.net/incoming/ -e "put `ls target/jline-*.zip`"
+
+To make a bundle and request that ibilio upload it, do:
+
+    mvn source:jar javadoc:jar repository:bundle-create
+
+    scp target/jline-*-bundle.jar shell.sourceforge.net:/home/groups/j/jl/jline/htdocs
+
+    Make a request like at http://jira.codehaus.org/browse/MAVENUPLOAD-1003
+
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
+    http://maven.apache.org/maven-v4_0_0.xsd">
+
+<properties>
+  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+</properties>
+  <modelVersion>4.0.0</modelVersion>
+  <groupId>jline</groupId>
+  <artifactId>jline</artifactId>
+  <packaging>jar</packaging>
+  <name>JLine</name>
+  <version>0.9.95-SNAPSHOT</version>
+  <description>JLine is a java library for reading and editing user input in console applications. It features tab-completion, command history, password masking, customizable keybindings, and pass-through handlers to use to chain to other console applications.</description>
+  <url>http://jline.sourceforge.net</url>
+  <issueManagement>
+    <system>sourceforge</system>
+    <url>http://sourceforge.net/tracker/?group_id=64033&atid=506056</url>
+  </issueManagement>
+  <inceptionYear>2002</inceptionYear>
+  <mailingLists>
+    <mailingList>
+      <name>JLine users</name>
+      <subscribe>https://lists.sourceforge.net/lists/listinfo/jline-users</subscribe>
+      <post>jline-users at lists.sourceforge.net</post>
+      <archive>http://sourceforge.net/mailarchive/forum.php?forum=jline-users</archive>
+    </mailingList>
+  </mailingLists>
+
+  <developers>
+    <developer>
+      <id>mprudhom</id>
+      <name>Marc Prud'hommeaux</name>
+      <email>mwp1 at cornell.edu</email>
+    </developer>
+  </developers>
+  <licenses>
+    <license>
+      <name>BSD</name>
+      <url>LICENSE.txt</url>
+    </license>
+  </licenses>
+  <scm>
+    <connection>scm:cvs:pserver:anonymous at jline.cvs.sourceforge.net:/cvsroot/jline:jline</connection>
+    <developerConnection>scm:cvs:ext:${maven.username}@jline.cvs.sourceforge.net:/cvsroot/jline:jline</developerConnection>
+    <url>http://jline.cvs.sourceforge.net/jline</url>
+  </scm>
+  <dependencies>
+    <dependency>
+      <groupId>junit</groupId>
+      <artifactId>junit</artifactId>
+      <version>3.8.1</version>
+      <scope>test</scope>
+    </dependency>
+  </dependencies>
+
+  <build>
+    <plugins>
+      <!--
+      <plugin>
+        <groupId>org.codehaus.mojo</groupId>
+        <artifactId>jalopy-maven-plugin</artifactId>
+        <version>1.0-SNAPSHOT</version>
+        <configuration>
+          <fileFormat>UNIX</fileFormat>
+          <convention>codestyle.xml</convention>
+        </configuration>
+        <executions>
+          <execution>
+            <goals>
+              <goal>format</goal>
+            </goals>
+          </execution>
+        </executions>
+      </plugin>
+      -->
+      <plugin>
+        <groupId>org.apache.maven.plugins</groupId>
+        <artifactId>maven-surefire-plugin</artifactId>
+        <configuration>
+          <!-- <testFailureIgnore>true</testFailureIgnore> -->
+          <useFile>false</useFile>
+          <trimStackTrace>false</trimStackTrace>
+        </configuration>
+      </plugin>
+      <plugin>
+        <groupId>org.apache.maven.plugins</groupId>
+        <artifactId>maven-compiler-plugin</artifactId>
+        <configuration>
+          <source>1.5</source>
+          <target>1.5</target>
+          <showWarnings>true</showWarnings>
+          <compilerArgument>-Xlint:unchecked</compilerArgument>
+        </configuration>
+      </plugin>
+      <plugin>
+        <groupId>org.apache.maven.plugins</groupId>
+        <artifactId>maven-site-plugin</artifactId>
+        <configuration>
+          <stagingDirectory>../site-staging</stagingDirectory>
+        </configuration>
+      </plugin>
+      <plugin>
+        <groupId>org.apache.maven.plugins</groupId>
+        <artifactId>maven-assembly-plugin</artifactId>
+        <configuration>
+          <descriptors>
+            <descriptor>src/assembly/assembly.xml</descriptor>
+          </descriptors>
+        </configuration>
+      </plugin>
+    </plugins>
+  </build>
+
+  <reporting>
+    <plugins>
+      <plugin>
+        <groupId>org.codehaus.mojo</groupId>
+        <artifactId>jxr-maven-plugin</artifactId>
+        <configuration>
+          <aggregate>true</aggregate>
+        </configuration>
+      </plugin>
+      <plugin>
+        <groupId>org.apache.maven.plugins</groupId>
+        <artifactId>maven-javadoc-plugin</artifactId>
+        <configuration>
+          <aggregate>true</aggregate>
+          <linksource>true</linksource>
+          <links>
+            <link>http://java.sun.com/j2se/1.5.0/docs/api</link>
+          </links>
+        </configuration>
+      </plugin>
+      <plugin>
+        <groupId>org.apache.maven.plugins</groupId>
+        <artifactId>maven-pmd-plugin</artifactId>
+      </plugin>
+      <plugin>
+        <groupId>org.apache.maven.plugins</groupId>
+        <artifactId>maven-project-info-reports-plugin</artifactId>
+        <reportSets>
+          <reportSet>
+            <reports>
+              <!-- <report>dependencies</report> -->
+              <!-- <report>cim</report> -->
+              <!-- <report>cobertura</report> -->
+              <report>project-team</report>
+              <report>mailing-list</report>
+              <report>issue-tracking</report>
+              <report>license</report>
+              <report>scm</report>
+            </reports>
+          </reportSet>
+        </reportSets>
+      </plugin>
+      <plugin>
+        <groupId>org.codehaus.mojo</groupId>
+        <artifactId>surefire-report-maven-plugin</artifactId>
+      </plugin>
+    </plugins>
+  </reporting>
+  <distributionManagement>
+    <repository>
+      <id>jline</id>
+      <url>scp://shell.sourceforge.net/home/groups/j/jl/jline/htdocs/m2repo</url>
+    </repository>
+    <snapshotRepository>
+      <id>jline</id>
+      <url>scp://shell.sourceforge.net/home/groups/j/jl/jline/htdocs/m2snapshot</url>
+    </snapshotRepository>
+    <site>
+      <id>jline</id>
+      <name>jline</name>
+      <url>scpexe://shell.sourceforge.net/home/groups/j/jl/jline/htdocs/</url>
+    </site>
+  </distributionManagement>
+</project>
diff --git a/src/jline/src/assembly/assembly.xml b/src/jline/src/assembly/assembly.xml
new file mode 100644
index 0000000..216c697
--- /dev/null
+++ b/src/jline/src/assembly/assembly.xml
@@ -0,0 +1,55 @@
+<assembly>
+    <id></id>
+    <formats>
+        <format>zip</format>
+    </formats>
+    <includeBaseDirectory>true</includeBaseDirectory>
+    <fileSets>
+        <fileSet>
+            <includes>
+                <include>README*</include>
+                <include>LICENSE*</include>
+                <include>NOTICE*</include>
+            </includes>
+        </fileSet>
+        <fileSet>
+          <directory>target</directory>
+          <outputDirectory></outputDirectory>
+          <includes>
+            <include>*.jar</include>
+          </includes>
+        </fileSet>
+        <fileSet>
+            <directory>licenses</directory>
+            <outputDirectory>/lib</outputDirectory>
+            <includes>
+                <include>*</include>
+            </includes>
+        </fileSet>
+        <fileSet>
+            <directory>src/test/java/jline/example</directory>
+            <outputDirectory>/examples/jline/example</outputDirectory>
+        </fileSet>
+        <fileSet>
+            <directory>src/test/resources/jline/example</directory>
+            <outputDirectory>/examples/jline/example</outputDirectory>
+        </fileSet>
+        <fileSet>
+            <directory>target/site/apidocs</directory>
+            <outputDirectory>/apidocs</outputDirectory>
+        </fileSet>
+
+        <!-- also include sources -->
+        <fileSet>
+          <directory>src</directory>
+          <outputDirectory>/src/src</outputDirectory>
+        </fileSet>
+        <fileSet>
+          <directory></directory>
+          <outputDirectory>/src</outputDirectory>
+          <includes>
+            <include>pom.xml</include>
+          </includes>
+        </fileSet>
+    </fileSets>
+</assembly>
diff --git a/src/jline/src/main/java/jline/ANSIBuffer.java b/src/jline/src/main/java/jline/ANSIBuffer.java
new file mode 100644
index 0000000..c2e3318
--- /dev/null
+++ b/src/jline/src/main/java/jline/ANSIBuffer.java
@@ -0,0 +1,405 @@
+/*
+ * Copyright (c) 2002-2007, Marc Prud'hommeaux. All rights reserved.
+ *
+ * This software is distributable under the BSD license. See the terms of the
+ * BSD license in the documentation provided with this software.
+ */
+package jline;
+
+import java.io.*;
+
+/**
+ *  A buffer that can contain ANSI text.
+ *
+ *  @author  <a href="mailto:mwp1 at cornell.edu">Marc Prud'hommeaux</a>
+ */
+public class ANSIBuffer {
+    private boolean ansiEnabled = true;
+    private final StringBuffer ansiBuffer = new StringBuffer();
+    private final StringBuffer plainBuffer = new StringBuffer();
+
+    public ANSIBuffer() {
+    }
+
+    public ANSIBuffer(final String str) {
+        append(str);
+    }
+
+    public void setAnsiEnabled(final boolean ansi) {
+        this.ansiEnabled = ansi;
+    }
+
+    public boolean getAnsiEnabled() {
+        return this.ansiEnabled;
+    }
+
+    public String getAnsiBuffer() {
+        return ansiBuffer.toString();
+    }
+
+    public String getPlainBuffer() {
+        return plainBuffer.toString();
+    }
+
+    public String toString(final boolean ansi) {
+        return ansi ? getAnsiBuffer() : getPlainBuffer();
+    }
+
+    public String toString() {
+        return toString(ansiEnabled);
+    }
+
+    public ANSIBuffer append(final String str) {
+        ansiBuffer.append(str);
+        plainBuffer.append(str);
+
+        return this;
+    }
+
+    public ANSIBuffer attrib(final String str, final int code) {
+        ansiBuffer.append(ANSICodes.attrib(code)).append(str)
+                  .append(ANSICodes.attrib(ANSICodes.OFF));
+        plainBuffer.append(str);
+
+        return this;
+    }
+
+    public ANSIBuffer red(final String str) {
+        return attrib(str, ANSICodes.FG_RED);
+    }
+
+    public ANSIBuffer blue(final String str) {
+        return attrib(str, ANSICodes.FG_BLUE);
+    }
+
+    public ANSIBuffer green(final String str) {
+        return attrib(str, ANSICodes.FG_GREEN);
+    }
+
+    public ANSIBuffer black(final String str) {
+        return attrib(str, ANSICodes.FG_BLACK);
+    }
+
+    public ANSIBuffer yellow(final String str) {
+        return attrib(str, ANSICodes.FG_YELLOW);
+    }
+
+    public ANSIBuffer magenta(final String str) {
+        return attrib(str, ANSICodes.FG_MAGENTA);
+    }
+
+    public ANSIBuffer cyan(final String str) {
+        return attrib(str, ANSICodes.FG_CYAN);
+    }
+
+    public ANSIBuffer bold(final String str) {
+        return attrib(str, ANSICodes.BOLD);
+    }
+
+    public ANSIBuffer underscore(final String str) {
+        return attrib(str, ANSICodes.UNDERSCORE);
+    }
+
+    public ANSIBuffer blink(final String str) {
+        return attrib(str, ANSICodes.BLINK);
+    }
+
+    public ANSIBuffer reverse(final String str) {
+        return attrib(str, ANSICodes.REVERSE);
+    }
+
+    public static class ANSICodes {
+        static final int OFF = 0;
+        static final int BOLD = 1;
+        static final int UNDERSCORE = 4;
+        static final int BLINK = 5;
+        static final int REVERSE = 7;
+        static final int CONCEALED = 8;
+        static final int FG_BLACK = 30;
+        static final int FG_RED = 31;
+        static final int FG_GREEN = 32;
+        static final int FG_YELLOW = 33;
+        static final int FG_BLUE = 34;
+        static final int FG_MAGENTA = 35;
+        static final int FG_CYAN = 36;
+        static final int FG_WHITE = 37;
+        static final char ESC = 27;
+
+        /**
+         *  Constructor is private since this is a utility class.
+         */
+        private ANSICodes() {
+        }
+
+        /**
+          * Sets the screen mode. The mode will be one of the following values:
+          * <pre>
+          * mode     description
+          * ----------------------------------------
+          *   0      40 x 148 x 25 monochrome (text)
+          *   1      40 x 148 x 25 color (text)
+          *   2      80 x 148 x 25 monochrome (text)
+          *   3      80 x 148 x 25 color (text)
+          *   4      320 x 148 x 200 4-color (graphics)
+          *   5      320 x 148 x 200 monochrome (graphics)
+          *   6      640 x 148 x 200 monochrome (graphics)
+          *   7      Enables line wrapping
+          *  13      320 x 148 x 200 color (graphics)
+          *  14      640 x 148 x 200 color (16-color graphics)
+          *  15      640 x 148 x 350 monochrome (2-color graphics)
+          *  16      640 x 148 x 350 color (16-color graphics)
+          *  17      640 x 148 x 480 monochrome (2-color graphics)
+          *  18      640 x 148 x 480 color (16-color graphics)
+          *  19      320 x 148 x 200 color (256-color graphics)
+          * </pre>
+          */
+        public static String setmode(final int mode) {
+            return ESC + "[=" + mode + "h";
+        }
+
+        /**
+          * Same as setmode () except for mode = 7, which disables line
+          * wrapping (useful for writing the right-most column without
+          * scrolling to the next line).
+          */
+        public static String resetmode(final int mode) {
+            return ESC + "[=" + mode + "l";
+        }
+
+        /**
+          * Clears the screen and moves the cursor to the home postition.
+          */
+        public static String clrscr() {
+            return ESC + "[2J";
+        }
+
+        /**
+          * Removes all characters from the current cursor position until
+          * the end of the line.
+          */
+        public static String clreol() {
+            return ESC + "[K";
+        }
+
+        /**
+          * Moves the cursor n positions to the left. If n is greater or
+          * equal to the current cursor column, the cursor is moved to the
+          * first column.
+          */
+        public static String left(final int n) {
+            return ESC + "[" + n + "D";
+        }
+
+        /**
+          * Moves the cursor n positions to the right. If n plus the current
+          * cursor column is greater than the rightmost column, the cursor
+          * is moved to the rightmost column.
+          */
+        public static String right(final int n) {
+            return ESC + "[" + n + "C";
+        }
+
+        /**
+          * Moves the cursor n rows up without changing the current column.
+          * If n is greater than or equal to the current row, the cursor is
+          * placed in the first row.
+          */
+        public static String up(final int n) {
+            return ESC + "[" + n + "A";
+        }
+
+        /**
+          * Moves the cursor n rows down. If n plus the current row is greater
+          * than the bottom row, the cursor is moved to the bottom row.
+          */
+        public static String down(final int n) {
+            return ESC + "[" + n + "B";
+        }
+
+        /*
+          * Moves the cursor to the given row and column. (1,1) represents
+          * the upper left corner. The lower right corner of a usual DOS
+          * screen is (25, 80).
+          */
+        public static String gotoxy(final int row, final int column) {
+            return ESC + "[" + row + ";" + column + "H";
+        }
+
+        /**
+          * Saves the current cursor position.
+          */
+        public static String save() {
+            return ESC + "[s";
+        }
+
+        /**
+          * Restores the saved cursor position.
+          */
+        public static String restore() {
+            return ESC + "[u";
+        }
+
+        /**
+          * Sets the character attribute. It will be
+         * one of the following character attributes:
+          *
+          * <pre>
+          * Text attributes
+          *    0    All attributes off
+          *    1    Bold on
+          *    4    Underscore (on monochrome display adapter only)
+          *    5    Blink on
+          *    7    Reverse video on
+          *    8    Concealed on
+          *
+          *   Foreground colors
+          *    30    Black
+          *    31    Red
+          *    32    Green
+          *    33    Yellow
+          *    34    Blue
+          *    35    Magenta
+          *    36    Cyan
+          *    37    White
+          *
+          *   Background colors
+          *    40    Black
+          *    41    Red
+          *    42    Green
+          *    43    Yellow
+          *    44    Blue
+          *    45    Magenta
+          *    46    Cyan
+          *    47    White
+          * </pre>
+          *
+          * The attributes remain in effect until the next attribute command
+          * is sent.
+          */
+        public static String attrib(final int attr) {
+            return ESC + "[" + attr + "m";
+        }
+
+        /**
+          * Sets the key with the given code to the given value. code must be
+          * derived from the following table, value must
+         * be any semicolon-separated
+          * combination of String (enclosed in double quotes) and numeric values.
+          * For example, to set F1 to the String "Hello F1", followed by a CRLF
+          * sequence, one can use: ANSI.setkey ("0;59", "\"Hello F1\";13;10").
+          * Heres's the table of key values:
+          * <pre>
+          * Key                       Code      SHIFT+code  CTRL+code  ALT+code
+          * ---------------------------------------------------------------
+          * F1                        0;59      0;84        0;94       0;104
+          * F2                        0;60      0;85        0;95       0;105
+          * F3                        0;61      0;86        0;96       0;106
+          * F4                        0;62      0;87        0;97       0;107
+          * F5                        0;63      0;88        0;98       0;108
+          * F6                        0;64      0;89        0;99       0;109
+          * F7                        0;65      0;90        0;100      0;110
+          * F8                        0;66      0;91        0;101      0;111
+          * F9                        0;67      0;92        0;102      0;112
+          * F10                       0;68      0;93        0;103      0;113
+          * F11                       0;133     0;135       0;137      0;139
+          * F12                       0;134     0;136       0;138      0;140
+          * HOME (num keypad)         0;71      55          0;119      --
+          * UP ARROW (num keypad)     0;72      56          (0;141)    --
+          * PAGE UP (num keypad)      0;73      57          0;132      --
+          * LEFT ARROW (num keypad)   0;75      52          0;115      --
+          * RIGHT ARROW (num keypad)  0;77      54          0;116      --
+          * END (num keypad)          0;79      49          0;117      --
+          * DOWN ARROW (num keypad)   0;80      50          (0;145)    --
+          * PAGE DOWN (num keypad)    0;81      51          0;118      --
+          * INSERT (num keypad)       0;82      48          (0;146)    --
+          * DELETE  (num keypad)      0;83      46          (0;147)    --
+          * HOME                      (224;71)  (224;71)    (224;119)  (224;151)
+          * UP ARROW                  (224;72)  (224;72)    (224;141)  (224;152)
+          * PAGE UP                   (224;73)  (224;73)    (224;132)  (224;153)
+          * LEFT ARROW                (224;75)  (224;75)    (224;115)  (224;155)
+          * RIGHT ARROW               (224;77)  (224;77)    (224;116)  (224;157)
+          * END                       (224;79)  (224;79)    (224;117)  (224;159)
+          * DOWN ARROW                (224;80)  (224;80)    (224;145)  (224;154)
+          * PAGE DOWN                 (224;81)  (224;81)    (224;118)  (224;161)
+          * INSERT                    (224;82)  (224;82)    (224;146)  (224;162)
+          * DELETE                    (224;83)  (224;83)    (224;147)  (224;163)
+          * PRINT SCREEN              --        --          0;114      --
+          * PAUSE/BREAK               --        --          0;0        --
+          * BACKSPACE                 8         8           127        (0)
+          * ENTER                     13        --          10         (0
+          * TAB                       9         0;15        (0;148)    (0;165)
+          * NULL                      0;3       --          --         --
+          * A                         97        65          1          0;30
+          * B                         98        66          2          0;48
+          * C                         99        66          3          0;46
+          * D                         100       68          4          0;32
+          * E                         101       69          5          0;18
+          * F                         102       70          6          0;33
+          * G                         103       71          7          0;34
+          * H                         104       72          8          0;35
+          * I                         105       73          9          0;23
+          * J                         106       74          10         0;36
+          * K                         107       75          11         0;37
+          * L                         108       76          12         0;38
+          * M                         109       77          13         0;50
+          * N                         110       78          14         0;49
+          * O                         111       79          15         0;24
+          * P                         112       80          16         0;25
+          * Q                         113       81          17         0;16
+          * R                         114       82          18         0;19
+          * S                         115       83          19         0;31
+          * T                         116       84          20         0;20
+          * U                         117       85          21         0;22
+          * V                         118       86          22         0;47
+          * W                         119       87          23         0;17
+          * X                         120       88          24         0;45
+          * Y                         121       89          25         0;21
+          * Z                         122       90          26         0;44
+          * 1                         49        33          --         0;120
+          * 2                         50        64          0          0;121
+          * 3                         51        35          --         0;122
+          * 4                         52        36          --         0;123
+          * 5                         53        37          --         0;124
+          * 6                         54        94          30         0;125
+          * 7                         55        38          --         0;126
+          * 8                         56        42          --         0;126
+          * 9                         57        40          --         0;127
+          * 0                         48        41          --         0;129
+          * -                         45        95          31         0;130
+          * =                         61        43          ---        0;131
+          * [                         91        123         27         0;26
+          * ]                         93        125         29         0;27
+          *                           92        124         28         0;43
+          * ;                         59        58          --         0;39
+          * '                         39        34          --         0;40
+          * ,                         44        60          --         0;51
+          * .                         46        62          --         0;52
+          * /                         47        63          --         0;53
+          * `                         96        126         --         (0;41)
+          * ENTER (keypad)            13        --          10         (0;166)
+          * / (keypad)                47        47          (0;142)    (0;74)
+          * * (keypad)                42        (0;144)     (0;78)     --
+          * - (keypad)                45        45          (0;149)    (0;164)
+          * + (keypad)                43        43          (0;150)    (0;55)
+          * 5 (keypad)                (0;76)    53          (0;143)    --
+          */
+        public static String setkey(final String code, final String value) {
+            return ESC + "[" + code + ";" + value + "p";
+        }
+    }
+
+    public static void main(final String[] args) throws Exception {
+        // sequence, one can use: ANSI.setkey ("0;59", "\"Hello F1\";13;10").
+        BufferedReader reader =
+            new BufferedReader(new InputStreamReader(System.in));
+        System.out.print(ANSICodes.setkey("97", "97;98;99;13")
+                         + ANSICodes.attrib(ANSICodes.OFF));
+        System.out.flush();
+
+        String line;
+
+        while ((line = reader.readLine()) != null) {
+            System.out.println("GOT: " + line);
+        }
+    }
+}
diff --git a/src/jline/src/main/java/jline/ArgumentCompletor.java b/src/jline/src/main/java/jline/ArgumentCompletor.java
new file mode 100644
index 0000000..2cd572c
--- /dev/null
+++ b/src/jline/src/main/java/jline/ArgumentCompletor.java
@@ -0,0 +1,439 @@
+/*
+ * Copyright (c) 2002-2007, Marc Prud'hommeaux. All rights reserved.
+ *
+ * This software is distributable under the BSD license. See the terms of the
+ * BSD license in the documentation provided with this software.
+ */
+package jline;
+
+import java.util.*;
+
+/**
+ *  A {@link Completor} implementation that invokes a child completor
+ *  using the appropriate <i>separator</i> argument. This
+ *  can be used instead of the individual completors having to
+ *  know about argument parsing semantics.
+ *  <p>
+ *  <strong>Example 1</strong>: Any argument of the command line can
+ *  use file completion.
+ *  <p>
+ *  <pre>
+ *        consoleReader.addCompletor (new ArgumentCompletor (
+ *                new {@link FileNameCompletor} ()))
+ *  </pre>
+ *  <p>
+ *  <strong>Example 2</strong>: The first argument of the command line
+ *  can be completed with any of "foo", "bar", or "baz", and remaining
+ *  arguments can be completed with a file name.
+ *  <p>
+ *  <pre>
+ *        consoleReader.addCompletor (new ArgumentCompletor (
+ *                new {@link SimpleCompletor} (new String [] { "foo", "bar", "baz"})));
+ *        consoleReader.addCompletor (new ArgumentCompletor (
+ *                new {@link FileNameCompletor} ()));
+ *  </pre>
+ *
+ *  <p>
+ *        When the argument index is past the last embedded completors, the last
+ *        completors is always used. To disable this behavior, have the last
+ *        completor be a {@link NullCompletor}. For example:
+ *        </p>
+ *
+ *        <pre>
+ *        consoleReader.addCompletor (new ArgumentCompletor (
+ *                new {@link SimpleCompletor} (new String [] { "foo", "bar", "baz"}),
+ *                new {@link SimpleCompletor} (new String [] { "xxx", "yyy", "xxx"}),
+ *                new {@link NullCompletor}
+ *                ));
+ *        </pre>
+ *  <p>
+ *  TODO: handle argument quoting and escape characters
+ *  </p>
+ *
+ *  @author  <a href="mailto:mwp1 at cornell.edu">Marc Prud'hommeaux</a>
+ */
+public class ArgumentCompletor implements Completor {
+    final Completor[] completors;
+    final ArgumentDelimiter delim;
+    boolean strict = true;
+
+    /**
+     *  Constuctor: create a new completor with the default
+     *  argument separator of " ".
+     *
+     *  @param  completor  the embedded completor
+     */
+    public ArgumentCompletor(final Completor completor) {
+        this(new Completor[] {
+                 completor
+             });
+    }
+
+    /**
+     *  Constuctor: create a new completor with the default
+     *  argument separator of " ".
+     *
+     *  @param  completors  the List of completors to use
+     */
+    public ArgumentCompletor(final List<Completor> completors) {
+        this((Completor[]) completors.toArray(new Completor[completors.size()]));
+    }
+
+    /**
+     *  Constuctor: create a new completor with the default
+     *  argument separator of " ".
+     *
+     *  @param  completors  the embedded argument completors
+     */
+    public ArgumentCompletor(final Completor[] completors) {
+        this(completors, new WhitespaceArgumentDelimiter());
+    }
+
+    /**
+     *  Constuctor: create a new completor with the specified
+     *  argument delimiter.
+     *
+     *  @param  completor the embedded completor
+     *  @param  delim     the delimiter for parsing arguments
+     */
+    public ArgumentCompletor(final Completor completor,
+                             final ArgumentDelimiter delim) {
+        this(new Completor[] {
+                 completor
+             }, delim);
+    }
+
+    /**
+     *  Constuctor: create a new completor with the specified
+     *  argument delimiter.
+     *
+     *  @param  completors the embedded completors
+     *  @param  delim      the delimiter for parsing arguments
+     */
+    public ArgumentCompletor(final Completor[] completors,
+                             final ArgumentDelimiter delim) {
+        this.completors = completors;
+        this.delim = delim;
+    }
+
+    /**
+     *  If true, a completion at argument index N will only succeed
+     *  if all the completions from 0-(N-1) also succeed.
+     */
+    public void setStrict(final boolean strict) {
+        this.strict = strict;
+    }
+
+    /**
+     *  Returns whether a completion at argument index N will succees
+     *  if all the completions from arguments 0-(N-1) also succeed.
+     */
+    public boolean getStrict() {
+        return this.strict;
+    }
+
+    public int complete(final String buffer, final int cursor,
+                        final List<String> candidates) {
+        ArgumentList list = delim.delimit(buffer, cursor);
+        int argpos = list.getArgumentPosition();
+        int argIndex = list.getCursorArgumentIndex();
+
+        if (argIndex < 0) {
+            return -1;
+        }
+
+        final Completor comp;
+
+        // if we are beyond the end of the completors, just use the last one
+        if (argIndex >= completors.length) {
+            comp = completors[completors.length - 1];
+        } else {
+            comp = completors[argIndex];
+        }
+
+        // ensure that all the previous completors are successful before
+        // allowing this completor to pass (only if strict is true).
+        for (int i = 0; getStrict() && (i < argIndex); i++) {
+            Completor sub =
+                completors[(i >= completors.length) ? (completors.length - 1) : i];
+            String[] args = list.getArguments();
+            String arg = ((args == null) || (i >= args.length)) ? "" : args[i];
+
+            List<String> subCandidates = new LinkedList<String>();
+
+            if (sub.complete(arg, arg.length(), subCandidates) == -1) {
+                return -1;
+            }
+
+            if (subCandidates.size() == 0) {
+                return -1;
+            }
+        }
+
+        int ret = comp.complete(list.getCursorArgument(), argpos, candidates);
+
+        if (ret == -1) {
+            return -1;
+        }
+
+        int pos = ret + (list.getBufferPosition() - argpos);
+
+        /**
+         *  Special case: when completing in the middle of a line, and the
+         *  area under the cursor is a delimiter, then trim any delimiters
+         *  from the candidates, since we do not need to have an extra
+         *  delimiter.
+         *
+         *  E.g., if we have a completion for "foo", and we
+         *  enter "f bar" into the buffer, and move to after the "f"
+         *  and hit TAB, we want "foo bar" instead of "foo  bar".
+         */
+        if ((cursor != buffer.length()) && delim.isDelimiter(buffer, cursor)) {
+            for (int i = 0; i < candidates.size(); i++) {
+                String val = candidates.get(i).toString();
+
+                while ((val.length() > 0)
+                    && delim.isDelimiter(val, val.length() - 1)) {
+                    val = val.substring(0, val.length() - 1);
+                }
+
+                candidates.set(i, val);
+            }
+        }
+
+        ConsoleReader.debug("Completing " + buffer + "(pos=" + cursor + ") "
+            + "with: " + candidates + ": offset=" + pos);
+
+        return pos;
+    }
+
+    /**
+     *  The {@link ArgumentCompletor.ArgumentDelimiter} allows custom
+     *  breaking up of a {@link String} into individual arguments in
+     *  order to dispatch the arguments to the nested {@link Completor}.
+     *
+     *  @author  <a href="mailto:mwp1 at cornell.edu">Marc Prud'hommeaux</a>
+     */
+    public static interface ArgumentDelimiter {
+        /**
+         *  Break the specified buffer into individual tokens
+         *  that can be completed on their own.
+         *
+         *  @param  buffer           the buffer to split
+         *  @param  argumentPosition the current position of the
+         *                           cursor in the buffer
+         *  @return                  the tokens
+         */
+        ArgumentList delimit(String buffer, int argumentPosition);
+
+        /**
+         *  Returns true if the specified character is a whitespace
+         *  parameter.
+         *
+         *  @param  buffer the complete command buffer
+         *  @param  pos    the index of the character in the buffer
+         *  @return        true if the character should be a delimiter
+         */
+        boolean isDelimiter(String buffer, int pos);
+    }
+
+    /**
+     *  Abstract implementation of a delimiter that uses the
+     *  {@link #isDelimiter} method to determine if a particular
+     *  character should be used as a delimiter.
+     *
+     *  @author  <a href="mailto:mwp1 at cornell.edu">Marc Prud'hommeaux</a>
+     */
+    public abstract static class AbstractArgumentDelimiter
+        implements ArgumentDelimiter {
+        private char[] quoteChars = new char[] { '\'', '"' };
+        private char[] escapeChars = new char[] { '\\' };
+
+        public void setQuoteChars(final char[] quoteChars) {
+            this.quoteChars = quoteChars;
+        }
+
+        public char[] getQuoteChars() {
+            return this.quoteChars;
+        }
+
+        public void setEscapeChars(final char[] escapeChars) {
+            this.escapeChars = escapeChars;
+        }
+
+        public char[] getEscapeChars() {
+            return this.escapeChars;
+        }
+
+        public ArgumentList delimit(final String buffer, final int cursor) {
+            List<String> args = new LinkedList<String>();
+            StringBuffer arg = new StringBuffer();
+            int argpos = -1;
+            int bindex = -1;
+
+            for (int i = 0; (buffer != null) && (i <= buffer.length()); i++) {
+                // once we reach the cursor, set the
+                // position of the selected index
+                if (i == cursor) {
+                    bindex = args.size();
+                    // the position in the current argument is just the
+                    // length of the current argument
+                    argpos = arg.length();
+                }
+
+                if ((i == buffer.length()) || isDelimiter(buffer, i)) {
+                    if (arg.length() > 0) {
+                        args.add(arg.toString());
+                        arg.setLength(0); // reset the arg
+                    }
+                } else {
+                    arg.append(buffer.charAt(i));
+                }
+            }
+
+            return new ArgumentList((String[]) args.
+                toArray(new String[args.size()]), bindex, argpos, cursor);
+        }
+
+        /**
+         *  Returns true if the specified character is a whitespace
+         *  parameter. Check to ensure that the character is not
+         *  escaped by any of
+         *  {@link #getQuoteChars}, and is not escaped by ant of the
+         *  {@link #getEscapeChars}, and returns true from
+         *  {@link #isDelimiterChar}.
+         *
+         *  @param  buffer the complete command buffer
+         *  @param  pos    the index of the character in the buffer
+         *  @return        true if the character should be a delimiter
+         */
+        public boolean isDelimiter(final String buffer, final int pos) {
+            if (isQuoted(buffer, pos)) {
+                return false;
+            }
+
+            if (isEscaped(buffer, pos)) {
+                return false;
+            }
+
+            return isDelimiterChar(buffer, pos);
+        }
+
+        public boolean isQuoted(final String buffer, final int pos) {
+            return false;
+        }
+
+        public boolean isEscaped(final String buffer, final int pos) {
+            if (pos <= 0) {
+                return false;
+            }
+
+            for (int i = 0; (escapeChars != null) && (i < escapeChars.length);
+                     i++) {
+                if (buffer.charAt(pos) == escapeChars[i]) {
+                    return !isEscaped(buffer, pos - 1); // escape escape
+                }
+            }
+
+            return false;
+        }
+
+        /**
+         *  Returns true if the character at the specified position
+         *  if a delimiter. This method will only be called if the
+         *  character is not enclosed in any of the
+         *  {@link #getQuoteChars}, and is not escaped by ant of the
+         *  {@link #getEscapeChars}. To perform escaping manually,
+         *  override {@link #isDelimiter} instead.
+         */
+        public abstract boolean isDelimiterChar(String buffer, int pos);
+    }
+
+    /**
+     *  {@link ArgumentCompletor.ArgumentDelimiter}
+     *  implementation that counts all
+     *  whitespace (as reported by {@link Character#isWhitespace})
+     *  as being a delimiter.
+     *
+     *  @author  <a href="mailto:mwp1 at cornell.edu">Marc Prud'hommeaux</a>
+     */
+    public static class WhitespaceArgumentDelimiter
+        extends AbstractArgumentDelimiter {
+        /**
+         *  The character is a delimiter if it is whitespace, and the
+         *  preceeding character is not an escape character.
+         */
+        public boolean isDelimiterChar(String buffer, int pos) {
+            return Character.isWhitespace(buffer.charAt(pos));
+        }
+    }
+
+    /**
+     *  The result of a delimited buffer.
+     *
+     *  @author  <a href="mailto:mwp1 at cornell.edu">Marc Prud'hommeaux</a>
+     */
+    public static class ArgumentList {
+        private String[] arguments;
+        private int cursorArgumentIndex;
+        private int argumentPosition;
+        private int bufferPosition;
+
+        /**
+         *  @param  arguments           the array of tokens
+         *  @param  cursorArgumentIndex the token index of the cursor
+         *  @param  argumentPosition    the position of the cursor in the
+         *                              current token
+         *  @param  bufferPosition      the position of the cursor in
+         *                              the whole buffer
+         */
+        public ArgumentList(String[] arguments, int cursorArgumentIndex,
+            int argumentPosition, int bufferPosition) {
+            this.arguments = arguments;
+            this.cursorArgumentIndex = cursorArgumentIndex;
+            this.argumentPosition = argumentPosition;
+            this.bufferPosition = bufferPosition;
+        }
+
+        public void setCursorArgumentIndex(int cursorArgumentIndex) {
+            this.cursorArgumentIndex = cursorArgumentIndex;
+        }
+
+        public int getCursorArgumentIndex() {
+            return this.cursorArgumentIndex;
+        }
+
+        public String getCursorArgument() {
+            if ((cursorArgumentIndex < 0)
+                || (cursorArgumentIndex >= arguments.length)) {
+                return null;
+            }
+
+            return arguments[cursorArgumentIndex];
+        }
+
+        public void setArgumentPosition(int argumentPosition) {
+            this.argumentPosition = argumentPosition;
+        }
+
+        public int getArgumentPosition() {
+            return this.argumentPosition;
+        }
+
+        public void setArguments(String[] arguments) {
+            this.arguments = arguments;
+        }
+
+        public String[] getArguments() {
+            return this.arguments;
+        }
+
+        public void setBufferPosition(int bufferPosition) {
+            this.bufferPosition = bufferPosition;
+        }
+
+        public int getBufferPosition() {
+            return this.bufferPosition;
+        }
+    }
+}
diff --git a/src/jline/src/main/java/jline/CandidateCycleCompletionHandler.java b/src/jline/src/main/java/jline/CandidateCycleCompletionHandler.java
new file mode 100644
index 0000000..a0bf208
--- /dev/null
+++ b/src/jline/src/main/java/jline/CandidateCycleCompletionHandler.java
@@ -0,0 +1,28 @@
+/*
+ * Copyright (c) 2002-2007, Marc Prud'hommeaux. All rights reserved.
+ *
+ * This software is distributable under the BSD license. See the terms of the
+ * BSD license in the documentation provided with this software.
+ */
+package jline;
+
+import java.io.*;
+import java.util.*;
+
+/**
+ *  <p>
+ *  A {@link CompletionHandler} that deals with multiple distinct completions
+ *  by cycling through each one every time tab is pressed. This
+ *  mimics the behavior of the
+ *  <a href="http://packages.qa.debian.org/e/editline.html">editline</a>
+ *  library.
+ *  </p>
+ *  <p><strong>This class is currently a stub; it does nothing</strong></p>
+ *  @author  <a href="mailto:mwp1 at cornell.edu">Marc Prud'hommeaux</a>
+ */
+public class CandidateCycleCompletionHandler implements CompletionHandler {
+    public boolean complete(final ConsoleReader reader, final List candidates,
+                            final int position) throws IOException {
+        throw new IllegalStateException("CandidateCycleCompletionHandler unimplemented");
+    }
+}
diff --git a/src/jline/src/main/java/jline/CandidateListCompletionHandler.java b/src/jline/src/main/java/jline/CandidateListCompletionHandler.java
new file mode 100644
index 0000000..17f03d5
--- /dev/null
+++ b/src/jline/src/main/java/jline/CandidateListCompletionHandler.java
@@ -0,0 +1,189 @@
+/*
+ * Copyright (c) 2002-2007, Marc Prud'hommeaux. All rights reserved.
+ *
+ * This software is distributable under the BSD license. See the terms of the
+ * BSD license in the documentation provided with this software.
+ */
+package jline;
+
+import java.io.*;
+import java.text.MessageFormat;
+import java.util.*;
+
+/**
+ *  <p>
+ *  A {@link CompletionHandler} that deals with multiple distinct completions
+ *  by outputting the complete list of possibilities to the console. This
+ *  mimics the behavior of the
+ *  <a href="http://www.gnu.org/directory/readline.html">readline</a>
+ *  library.
+ *  </p>
+ *
+ *  <strong>TODO:</strong>
+ *  <ul>
+ *        <li>handle quotes and escaped quotes</li>
+ *        <li>enable automatic escaping of whitespace</li>
+ *  </ul>
+ *
+ *  @author  <a href="mailto:mwp1 at cornell.edu">Marc Prud'hommeaux</a>
+ */
+public class CandidateListCompletionHandler implements CompletionHandler {
+    private static ResourceBundle loc = ResourceBundle.
+        getBundle(CandidateListCompletionHandler.class.getName());
+
+    private boolean eagerNewlines = true;
+
+    public void setAlwaysIncludeNewline(boolean eagerNewlines) {
+        this.eagerNewlines = eagerNewlines;
+    }
+
+    public boolean complete(final ConsoleReader reader, final List<String> candidates,
+                            final int pos) throws IOException {
+        CursorBuffer buf = reader.getCursorBuffer();
+
+        // if there is only one completion, then fill in the buffer
+        if (candidates.size() == 1) {
+            String value = candidates.get(0).toString();
+
+            // fail if the only candidate is the same as the current buffer
+            if (value.equals(buf.toString())) {
+                return false;
+            }
+
+            setBuffer(reader, value, pos);
+
+            return true;
+        } else if (candidates.size() > 1) {
+            String value = getUnambiguousCompletions(candidates);
+            String bufString = buf.toString();
+            setBuffer(reader, value, pos);
+        }
+
+        if (eagerNewlines)
+            reader.printNewline();
+        printCandidates(reader, candidates, eagerNewlines);
+
+        // redraw the current console buffer
+        reader.drawLine();
+
+        return true;
+    }
+
+    public static void setBuffer(ConsoleReader reader, String value, int offset)
+                           throws IOException {
+        while ((reader.getCursorBuffer().cursor > offset)
+                   && reader.backspace()) {
+            ;
+        }
+
+        reader.putString(value);
+        reader.setCursorPosition(offset + value.length());
+    }
+
+    /**
+     *  Print out the candidates. If the size of the candidates
+     *  is greated than the {@link getAutoprintThreshhold},
+     *  they prompt with aq warning.
+     *
+     *  @param  candidates  the list of candidates to print
+     */
+    public static final void printCandidates(ConsoleReader reader,
+                                             Collection<String> candidates, boolean eagerNewlines)
+                                throws IOException {
+        Set<String> distinct = new HashSet<String>(candidates);
+
+        if (distinct.size() > reader.getAutoprintThreshhold()) {
+            if (!eagerNewlines)
+                reader.printNewline();
+            reader.printString(MessageFormat.format
+                (loc.getString("display-candidates"), new Object[] {
+                    new Integer(candidates .size())
+                    }) + " ");
+
+            reader.flushConsole();
+
+            int c;
+
+            String noOpt = loc.getString("display-candidates-no");
+            String yesOpt = loc.getString("display-candidates-yes");
+
+            while ((c = reader.readCharacter(new char[] {
+                yesOpt.charAt(0), noOpt.charAt(0) })) != -1) {
+                if (noOpt.startsWith
+                    (new String(new char[] { (char) c }))) {
+                    reader.printNewline();
+                    return;
+                } else if (yesOpt.startsWith
+                    (new String(new char[] { (char) c }))) {
+                    break;
+                } else {
+                    reader.beep();
+                }
+            }
+        }
+
+        // copy the values and make them distinct, without otherwise
+        // affecting the ordering. Only do it if the sizes differ.
+        if (distinct.size() != candidates.size()) {
+            Collection<String> copy = new ArrayList<String>();
+
+            for (Iterator<String> i = candidates.iterator(); i.hasNext();) {
+                String next = i.next();
+
+                if (!(copy.contains(next))) {
+                    copy.add(next);
+                }
+            }
+
+            candidates = copy;
+        }
+
+        reader.printNewline();
+        reader.printColumns(candidates);
+    }
+
+    /**
+     *  Returns a root that matches all the {@link String} elements
+     *  of the specified {@link List}, or null if there are
+     *  no commalities. For example, if the list contains
+     *  <i>foobar</i>, <i>foobaz</i>, <i>foobuz</i>, the
+     *  method will return <i>foob</i>.
+     */
+    private final String getUnambiguousCompletions(final List<String> candidates) {
+        if ((candidates == null) || (candidates.size() == 0)) {
+            return null;
+        }
+
+        // convert to an array for speed
+        String[] strings =
+            (String[]) candidates.toArray(new String[candidates.size()]);
+
+        String first = strings[0];
+        StringBuffer candidate = new StringBuffer();
+
+        for (int i = 0; i < first.length(); i++) {
+            if (startsWith(first.substring(0, i + 1), strings)) {
+                candidate.append(first.charAt(i));
+            } else {
+                break;
+            }
+        }
+
+        return candidate.toString();
+    }
+
+    /**
+     *  @return  true is all the elements of <i>candidates</i>
+     *                          start with <i>starts</i>
+     */
+    private final boolean startsWith(final String starts,
+                                     final String[] candidates) {
+        for (int i = 0; i < candidates.length; i++) {
+            if (!candidates[i].startsWith(starts)) {
+                return false;
+            }
+        }
+
+        return true;
+    }
+}
diff --git a/src/jline/src/main/java/jline/ClassNameCompletor.java b/src/jline/src/main/java/jline/ClassNameCompletor.java
new file mode 100644
index 0000000..5c3ca87
--- /dev/null
+++ b/src/jline/src/main/java/jline/ClassNameCompletor.java
@@ -0,0 +1,146 @@
+/*
+ * Copyright (c) 2002-2007, Marc Prud'hommeaux. All rights reserved.
+ *
+ * This software is distributable under the BSD license. See the terms of the
+ * BSD license in the documentation provided with this software.
+ */
+package jline;
+
+import java.io.*;
+import java.net.*;
+import java.util.*;
+import java.util.jar.JarEntry;
+import java.util.jar.JarFile;
+
+/**
+ *  A Completor implementation that completes java class names. By default,
+ *  it scans the java class path to locate all the classes.
+ *
+ *  @author  <a href="mailto:mwp1 at cornell.edu">Marc Prud'hommeaux</a>
+ */
+public class ClassNameCompletor extends SimpleCompletor {
+
+    /**
+     *  Complete candidates using all the classes available in the
+     *  java <em>CLASSPATH</em>.
+     */
+    public ClassNameCompletor() throws IOException {
+        this(null);
+    }
+
+    public ClassNameCompletor(final SimpleCompletorFilter filter)
+        throws IOException {
+        super(getClassNames(), filter);
+        setDelimiter(".");
+    }
+
+    public static String[] getClassNames() throws IOException {
+        Set<URL> urls = new HashSet<URL>();
+
+        for (ClassLoader loader = ClassNameCompletor.class
+            .getClassLoader(); loader != null;
+                 loader = loader.getParent()) {
+            if (!(loader instanceof URLClassLoader)) {
+                continue;
+            }
+
+            urls.addAll(Arrays.asList(((URLClassLoader) loader).getURLs()));
+        }
+
+        // Now add the URL that holds java.lang.String. This is because
+        // some JVMs do not report the core classes jar in the list of
+        // class loaders.
+        Class[] systemClasses = new Class[] {
+            String.class, javax.swing.JFrame.class
+            };
+
+        for (int i = 0; i < systemClasses.length; i++) {
+            URL classURL = systemClasses[i].getResource("/"
+                + systemClasses[i].getName() .replace('.', '/') + ".class");
+
+            if (classURL != null) {
+                URLConnection uc = (URLConnection) classURL.openConnection();
+
+                if (uc instanceof JarURLConnection) {
+                    urls.add(((JarURLConnection) uc).getJarFileURL());
+                }
+            }
+        }
+
+        Set<String> classes = new HashSet<String>();
+
+        for (Iterator i = urls.iterator(); i.hasNext();) {
+            URL url = (URL) i.next();
+            File file = new File(url.getFile());
+
+            if (file.isDirectory()) {
+                Set<String> files = getClassFiles(file.getAbsolutePath(),
+                    new HashSet<String>(), file, new int[] { 200 });
+                classes.addAll(files);
+
+                continue;
+            }
+
+            if ((file == null) || !file.isFile()) // TODO: handle directories
+             {
+                continue;
+            }
+
+            JarFile jf = new JarFile(file);
+
+            for (Enumeration e = jf.entries(); e.hasMoreElements();) {
+                JarEntry entry = (JarEntry) e.nextElement();
+
+                if (entry == null) {
+                    continue;
+                }
+
+                String name = entry.getName();
+
+                if (!name.endsWith(".class")) // only use class files
+                 {
+                    continue;
+                }
+
+                classes.add(name);
+            }
+        }
+
+        // now filter classes by changing "/" to "." and trimming the
+        // trailing ".class"
+        Set<String> classNames = new TreeSet<String>();
+
+        for (Iterator<String> i = classes.iterator(); i.hasNext();) {
+            String name = (String) i.next();
+            classNames.add(name.replace('/', '.').
+                substring(0, name.length() - 6));
+        }
+
+        return (String[]) classNames.toArray(new String[classNames.size()]);
+    }
+
+    private static Set<String> getClassFiles(String root, Set<String> holder, File directory,
+        int[] maxDirectories) {
+        // we have passed the maximum number of directories to scan
+        if (maxDirectories[0]-- < 0) {
+            return holder;
+        }
+
+        File[] files = directory.listFiles();
+
+        for (int i = 0; (files != null) && (i < files.length); i++) {
+            String name = files[i].getAbsolutePath();
+
+            if (!(name.startsWith(root))) {
+                continue;
+            } else if (files[i].isDirectory()) {
+                getClassFiles(root, holder, files[i], maxDirectories);
+            } else if (files[i].getName().endsWith(".class")) {
+                holder.add(files[i].getAbsolutePath().
+                    substring(root.length() + 1));
+            }
+        }
+
+        return holder;
+    }
+}
diff --git a/src/jline/src/main/java/jline/CompletionHandler.java b/src/jline/src/main/java/jline/CompletionHandler.java
new file mode 100644
index 0000000..5dffdcb
--- /dev/null
+++ b/src/jline/src/main/java/jline/CompletionHandler.java
@@ -0,0 +1,20 @@
+/*
+ * Copyright (c) 2002-2007, Marc Prud'hommeaux. All rights reserved.
+ *
+ * This software is distributable under the BSD license. See the terms of the
+ * BSD license in the documentation provided with this software.
+ */
+package jline;
+
+import java.io.*;
+import java.util.*;
+
+/**
+ *  Handler for dealing with candidates for tab-completion.
+ *
+ *  @author  <a href="mailto:mwp1 at cornell.edu">Marc Prud'hommeaux</a>
+ */
+public interface CompletionHandler {
+    boolean complete(ConsoleReader reader, List<String> candidates, int position)
+              throws IOException;
+}
diff --git a/src/jline/src/main/java/jline/Completor.java b/src/jline/src/main/java/jline/Completor.java
new file mode 100644
index 0000000..ed1238a
--- /dev/null
+++ b/src/jline/src/main/java/jline/Completor.java
@@ -0,0 +1,32 @@
+/*
+ * Copyright (c) 2002-2007, Marc Prud'hommeaux. All rights reserved.
+ *
+ * This software is distributable under the BSD license. See the terms of the
+ * BSD license in the documentation provided with this software.
+ */
+package jline;
+
+import java.util.*;
+
+/**
+ *  A Completor is the mechanism by which tab-completion candidates
+ *  will be resolved.
+ *
+ *  @author  <a href="mailto:mwp1 at cornell.edu">Marc Prud'hommeaux</a>
+ */
+public interface Completor {
+    /**
+     *  Populates <i>candidates</i> with a list of possible
+     *  completions for the <i>buffer</i>. The <i>candidates</i>
+     *  list will not be sorted before being displayed to the
+     *  user: thus, the complete method should sort the
+     *  {@link List} before returning.
+     *
+     *
+     *  @param  buffer     the buffer
+     *  @param  candidates the {@link List} of candidates to populate
+     *  @return            the index of the <i>buffer</i> for which
+     *                     the completion will be relative
+     */
+    int complete(String buffer, int cursor, List<String> candidates);
+}
diff --git a/src/jline/src/main/java/jline/ConsoleOperations.java b/src/jline/src/main/java/jline/ConsoleOperations.java
new file mode 100644
index 0000000..585ed40
--- /dev/null
+++ b/src/jline/src/main/java/jline/ConsoleOperations.java
@@ -0,0 +1,276 @@
+/*
+ * Copyright (c) 2002-2007, Marc Prud'hommeaux. All rights reserved.
+ *
+ * This software is distributable under the BSD license. See the terms of the
+ * BSD license in the documentation provided with this software.
+ */
+package jline;
+
+import java.awt.event.KeyEvent;
+
+/**
+ *  Symbolic constants for Console operations and virtual key bindings.
+ *  @see KeyEvent
+ *
+ *  @author  <a href="mailto:mwp1 at cornell.edu">Marc Prud'hommeaux</a>
+ */
+public interface ConsoleOperations {
+    final String CR = System.getProperty("line.separator");
+    final char BACKSPACE = '\b';
+    final char RESET_LINE = '\r';
+    final char KEYBOARD_BELL = '\07';
+    final char CTRL_A = 1;
+    final char CTRL_B = 2;
+    final char CTRL_C = 3;
+    final char CTRL_D = 4;
+    final char CTRL_E = 5;
+    final char CTRL_F = 6;
+    final static char CTRL_K = 11;
+    final static char CTRL_L = 12;
+    final char CTRL_N = 14;
+    final char CTRL_P = 16;
+    final static char CTRL_OB = 27;
+    final static char DELETE = 127;
+    final static char CTRL_QM = 127;
+
+
+    /**
+     *        Logical constants for key operations.
+     */
+
+    /**
+     *  Unknown operation.
+     */
+    final short UNKNOWN = -99;
+
+    /**
+     *  Operation that moves to the beginning of the buffer.
+     */
+    final short MOVE_TO_BEG = -1;
+
+    /**
+     *  Operation that moves to the end of the buffer.
+     */
+    final short MOVE_TO_END = -3;
+
+    /**
+     *  Operation that moved to the previous character in the buffer.
+     */
+    final short PREV_CHAR = -4;
+
+    /**
+     *  Operation that issues a newline.
+     */
+    final short NEWLINE = -6;
+
+    /**
+     *  Operation that deletes the buffer from the current character to the end.
+     */
+    final short KILL_LINE = -7;
+
+    /**
+     *  Operation that clears the screen.
+     */
+    final short CLEAR_SCREEN = -8;
+
+    /**
+     *  Operation that sets the buffer to the next history item.
+     */
+    final short NEXT_HISTORY = -9;
+
+    /**
+     *  Operation that sets the buffer to the previous history item.
+     */
+    final short PREV_HISTORY = -11;
+
+    /**
+     *  Operation that redisplays the current buffer.
+     */
+    final short REDISPLAY = -13;
+
+    /**
+     *  Operation that deletes the buffer from the cursor to the beginning.
+     */
+    final short KILL_LINE_PREV = -15;
+
+    /**
+     *  Operation that deletes the previous word in the buffer.
+     */
+    final short DELETE_PREV_WORD = -16;
+
+    /**
+     *  Operation that moves to the next character in the buffer.
+     */
+    final short NEXT_CHAR = -19;
+
+    /**
+     *  Operation that moves to the previous character in the buffer.
+     */
+    final short REPEAT_PREV_CHAR = -20;
+
+    /**
+     *  Operation that searches backwards in the command history.
+     */
+    final short SEARCH_PREV = -21;
+
+    /**
+     *  Operation that repeats the character.
+     */
+    final short REPEAT_NEXT_CHAR = -24;
+
+    /**
+     *  Operation that searches forward in the command history.
+     */
+    final short SEARCH_NEXT = -25;
+
+    /**
+     *  Operation that moved to the previous whitespace.
+     */
+    final short PREV_SPACE_WORD = -27;
+
+    /**
+     *  Operation that moved to the end of the current word.
+     */
+    final short TO_END_WORD = -29;
+
+    /**
+     *  Operation that
+     */
+    final short REPEAT_SEARCH_PREV = -34;
+
+    /**
+     *  Operation that
+     */
+    final short PASTE_PREV = -36;
+
+    /**
+     *  Operation that
+     */
+    final short REPLACE_MODE = -37;
+
+    /**
+     *  Operation that
+     */
+    final short SUBSTITUTE_LINE = -38;
+
+    /**
+     *  Operation that
+     */
+    final short TO_PREV_CHAR = -39;
+
+    /**
+     *  Operation that
+     */
+    final short NEXT_SPACE_WORD = -40;
+
+    /**
+     *  Operation that
+     */
+    final short DELETE_PREV_CHAR = -41;
+
+    /**
+     *  Operation that
+     */
+    final short ADD = -42;
+
+    /**
+     *  Operation that
+     */
+    final short PREV_WORD = -43;
+
+    /**
+     *  Operation that
+     */
+    final short CHANGE_META = -44;
+
+    /**
+     *  Operation that
+     */
+    final short DELETE_META = -45;
+
+    /**
+     *  Operation that
+     */
+    final short END_WORD = -46;
+
+    /**
+     *  Operation that toggles insert/overtype
+     */
+    final short INSERT = -48;
+
+    /**
+     *  Operation that
+     */
+    final short REPEAT_SEARCH_NEXT = -49;
+
+    /**
+     *  Operation that
+     */
+    final short PASTE_NEXT = -50;
+
+    /**
+     *  Operation that
+     */
+    final short REPLACE_CHAR = -51;
+
+    /**
+     *  Operation that
+     */
+    final short SUBSTITUTE_CHAR = -52;
+
+    /**
+     *  Operation that
+     */
+    final short TO_NEXT_CHAR = -53;
+
+    /**
+     *  Operation that undoes the previous operation.
+     */
+    final short UNDO = -54;
+
+    /**
+     *  Operation that moved to the next word.
+     */
+    final short NEXT_WORD = -55;
+
+    /**
+     *  Operation that deletes the previous character.
+     */
+    final short DELETE_NEXT_CHAR = -56;
+
+    /**
+     *  Operation that toggles between uppercase and lowercase.
+     */
+    final short CHANGE_CASE = -57;
+
+    /**
+     *  Operation that performs completion operation on the current word.
+     */
+    final short COMPLETE = -58;
+
+    /**
+     *  Operation that exits the command prompt.
+     */
+    final short EXIT = -59;
+
+    /**
+     *  Operation that pastes the contents of the clipboard into the line
+     */
+    final short PASTE = -60;
+
+    /**
+     * Operation that moves the current History to the beginning.
+     */
+    final static short START_OF_HISTORY = -61;
+
+    /**
+     * Operation that moves the current History to the end.
+     */
+    final static short END_OF_HISTORY = -62;
+
+    /**
+     * Operation that clears whatever text is on the current line.
+     */
+    final static short CLEAR_LINE = -63;
+
+}
diff --git a/src/jline/src/main/java/jline/ConsoleReader.java b/src/jline/src/main/java/jline/ConsoleReader.java
new file mode 100644
index 0000000..e1706d1
--- /dev/null
+++ b/src/jline/src/main/java/jline/ConsoleReader.java
@@ -0,0 +1,1625 @@
+/*
+ * Copyright (c) 2002-2007, Marc Prud'hommeaux. All rights reserved.
+ *
+ * This software is distributable under the BSD license. See the terms of the
+ * BSD license in the documentation provided with this software.
+ */
+package jline;
+
+import java.awt.*;
+import java.awt.datatransfer.*;
+import java.awt.event.ActionListener;
+
+import java.io.*;
+import java.util.*;
+import java.util.List;
+
+/**
+ * A reader for console applications. It supports custom tab-completion,
+ * saveable command history, and command line editing. On some platforms,
+ * platform-specific commands will need to be issued before the reader will
+ * function properly. See {@link Terminal#initializeTerminal} for convenience
+ * methods for issuing platform-specific setup commands.
+ *
+ * @author <a href="mailto:mwp1 at cornell.edu">Marc Prud'hommeaux</a>
+ */
+public class ConsoleReader implements ConsoleOperations {
+
+    final static int TAB_WIDTH = 4;
+
+    String prompt;
+
+    private boolean useHistory = true;
+
+    private boolean usePagination = false;
+
+    public static final String CR = System.getProperty("line.separator");
+
+    private static ResourceBundle loc = ResourceBundle
+            .getBundle(CandidateListCompletionHandler.class.getName());
+
+    /**
+     * Map that contains the operation name to keymay operation mapping.
+     */
+    public static SortedMap<String, Short> KEYMAP_NAMES;
+
+    static {
+        Map<String, Short> names = new TreeMap<String, Short>();
+
+        names.put("MOVE_TO_BEG", new Short(MOVE_TO_BEG));
+        names.put("MOVE_TO_END", new Short(MOVE_TO_END));
+        names.put("PREV_CHAR", new Short(PREV_CHAR));
+        names.put("NEWLINE", new Short(NEWLINE));
+        names.put("KILL_LINE", new Short(KILL_LINE));
+        names.put("PASTE", new Short(PASTE));
+        names.put("CLEAR_SCREEN", new Short(CLEAR_SCREEN));
+        names.put("NEXT_HISTORY", new Short(NEXT_HISTORY));
+        names.put("PREV_HISTORY", new Short(PREV_HISTORY));
+        names.put("START_OF_HISTORY", new Short(START_OF_HISTORY));
+        names.put("END_OF_HISTORY", new Short(END_OF_HISTORY));
+        names.put("REDISPLAY", new Short(REDISPLAY));
+        names.put("KILL_LINE_PREV", new Short(KILL_LINE_PREV));
+        names.put("DELETE_PREV_WORD", new Short(DELETE_PREV_WORD));
+        names.put("NEXT_CHAR", new Short(NEXT_CHAR));
+        names.put("REPEAT_PREV_CHAR", new Short(REPEAT_PREV_CHAR));
+        names.put("SEARCH_PREV", new Short(SEARCH_PREV));
+        names.put("REPEAT_NEXT_CHAR", new Short(REPEAT_NEXT_CHAR));
+        names.put("SEARCH_NEXT", new Short(SEARCH_NEXT));
+        names.put("PREV_SPACE_WORD", new Short(PREV_SPACE_WORD));
+        names.put("TO_END_WORD", new Short(TO_END_WORD));
+        names.put("REPEAT_SEARCH_PREV", new Short(REPEAT_SEARCH_PREV));
+        names.put("PASTE_PREV", new Short(PASTE_PREV));
+        names.put("REPLACE_MODE", new Short(REPLACE_MODE));
+        names.put("SUBSTITUTE_LINE", new Short(SUBSTITUTE_LINE));
+        names.put("TO_PREV_CHAR", new Short(TO_PREV_CHAR));
+        names.put("NEXT_SPACE_WORD", new Short(NEXT_SPACE_WORD));
+        names.put("DELETE_PREV_CHAR", new Short(DELETE_PREV_CHAR));
+        names.put("ADD", new Short(ADD));
+        names.put("PREV_WORD", new Short(PREV_WORD));
+        names.put("CHANGE_META", new Short(CHANGE_META));
+        names.put("DELETE_META", new Short(DELETE_META));
+        names.put("END_WORD", new Short(END_WORD));
+        names.put("NEXT_CHAR", new Short(NEXT_CHAR));
+        names.put("INSERT", new Short(INSERT));
+        names.put("REPEAT_SEARCH_NEXT", new Short(REPEAT_SEARCH_NEXT));
+        names.put("PASTE_NEXT", new Short(PASTE_NEXT));
+        names.put("REPLACE_CHAR", new Short(REPLACE_CHAR));
+        names.put("SUBSTITUTE_CHAR", new Short(SUBSTITUTE_CHAR));
+        names.put("TO_NEXT_CHAR", new Short(TO_NEXT_CHAR));
+        names.put("UNDO", new Short(UNDO));
+        names.put("NEXT_WORD", new Short(NEXT_WORD));
+        names.put("DELETE_NEXT_CHAR", new Short(DELETE_NEXT_CHAR));
+        names.put("CHANGE_CASE", new Short(CHANGE_CASE));
+        names.put("COMPLETE", new Short(COMPLETE));
+        names.put("EXIT", new Short(EXIT));
+        names.put("CLEAR_LINE", new Short(CLEAR_LINE));
+
+        KEYMAP_NAMES = new TreeMap<String, Short>(Collections.unmodifiableMap(names));
+    }
+
+    /**
+     * The map for logical operations.
+     */
+    private final short[] keybindings;
+
+    /**
+     * If true, issue an audible keyboard bell when appropriate.
+     */
+    private boolean bellEnabled = true;
+
+    /**
+     * The current character mask.
+     */
+    private Character mask = null;
+
+    /**
+     * The null mask.
+     */
+    private static final Character NULL_MASK = new Character((char) 0);
+
+    /**
+     * The number of tab-completion candidates above which a warning will be
+     * prompted before showing all the candidates.
+     */
+    private int autoprintThreshhold = Integer.getInteger(
+            "jline.completion.threshold", 100).intValue(); // same default as
+
+    // bash
+
+    /**
+     * The Terminal to use.
+     */
+    private final Terminal terminal;
+
+    private CompletionHandler completionHandler = new CandidateListCompletionHandler();
+
+    InputStream in;
+
+    final Writer out;
+
+    final CursorBuffer buf = new CursorBuffer();
+
+    static PrintWriter debugger;
+
+    History history = new History();
+
+    final List<Completor> completors = new LinkedList<Completor>();
+
+    private Character echoCharacter = null;
+
+    private Map<Character, ActionListener> triggeredActions = new HashMap<Character, ActionListener>();
+
+
+	/**
+	 * Adding a triggered Action allows to give another curse of action
+	 * if a character passed the preprocessing.
+	 * 
+	 * Say you want to close the application if the user enter q.
+	 * addTriggerAction('q', new ActionListener(){ System.exit(0); });
+	 * would do the trick.
+	 * 
+	 * @param c
+	 * @param listener
+	 */
+	public void addTriggeredAction(char c, ActionListener listener){
+		triggeredActions.put(new Character(c), listener);
+	}
+	
+    /**
+     * Create a new reader using {@link FileDescriptor#in} for input and
+     * {@link System#out} for output. {@link FileDescriptor#in} is used because
+     * it has a better chance of being unbuffered.
+     */
+    public ConsoleReader() throws IOException {	
+        this(new FileInputStream(FileDescriptor.in), 
+        		new PrintWriter(
+        				new OutputStreamWriter(System.out,
+        						System.getProperty("jline.WindowsTerminal.output.encoding",System.getProperty("file.encoding")))));
+    }
+
+    /**
+     * Create a new reader using the specified {@link InputStream} for input and
+     * the specific writer for output, using the default keybindings resource.
+     */
+    public ConsoleReader(final InputStream in, final Writer out)
+            throws IOException {
+        this(in, out, null);
+    }
+
+    public ConsoleReader(final InputStream in, final Writer out,
+            final InputStream bindings) throws IOException {
+        this(in, out, bindings, Terminal.getTerminal());
+    }
+
+    /**
+     * Create a new reader.
+     *
+     * @param in
+     *            the input
+     * @param out
+     *            the output
+     * @param bindings
+     *            the key bindings to use
+     * @param term
+     *            the terminal to use
+     */
+    public ConsoleReader(InputStream in, Writer out, InputStream bindings,
+            Terminal term) throws IOException {
+        this.terminal = term;
+        setInput(in);
+        this.out = out;
+        if (bindings == null) {
+            try {
+                String defaultBindingFile =
+                        new File(System.getProperty("user.home"),
+                                 ".jlinebindings.properties").getAbsolutePath();
+                String bindingFile = System.getProperty("jline.keybindings", defaultBindingFile);
+
+                if (new File(bindingFile).isFile()) {
+                    bindings = new FileInputStream(new File(bindingFile));
+                } 
+            } catch (Exception e) {
+                // swallow exceptions with option debugging
+                if (debugger != null) {
+                    e.printStackTrace(debugger);
+                }
+            }
+        }
+
+        if (bindings == null) {
+            bindings = terminal.getDefaultBindings();
+        }
+
+        this.keybindings = new short[Character.MAX_VALUE * 2];
+
+        Arrays.fill(this.keybindings, UNKNOWN);
+
+        /**
+         * Loads the key bindings. Bindings file is in the format:
+         *
+         * keycode: operation name
+         */
+        if (bindings != null) {
+            Properties p = new Properties();
+            p.load(bindings);
+            bindings.close();
+
+            for (Iterator i = p.keySet().iterator(); i.hasNext();) {
+                String val = (String) i.next();
+
+                try {
+                    Short code = new Short(val);
+                    String op = (String) p.getProperty(val);
+
+                    Short opval = (Short) KEYMAP_NAMES.get(op);
+
+                    if (opval != null) {
+                        keybindings[code.shortValue()] = opval.shortValue();
+                    }
+                } catch (NumberFormatException nfe) {
+                    consumeException(nfe);
+                }
+            }
+
+            // hardwired arrow key bindings
+            // keybindings[VK_UP] = PREV_HISTORY;
+            // keybindings[VK_DOWN] = NEXT_HISTORY;
+            // keybindings[VK_LEFT] = PREV_CHAR;
+            // keybindings[VK_RIGHT] = NEXT_CHAR;
+        }
+    }
+
+    public Terminal getTerminal() {
+        return this.terminal;
+    }
+
+    /**
+     * Set the stream for debugging. Development use only.
+     */
+    public void setDebug(final PrintWriter debugger) {
+        ConsoleReader.debugger = debugger;
+    }
+
+    /**
+     * Set the stream to be used for console input.
+     */
+    public void setInput(final InputStream in) {
+        this.in = in;
+    }
+
+    /**
+     * Returns the stream used for console input.
+     */
+    public InputStream getInput() {
+        return this.in;
+    }
+
+    /**
+     * Read the next line and return the contents of the buffer.
+     */
+    public String readLine() throws IOException {
+        return readLine((String) null);
+    }
+
+    /**
+     * Read the next line with the specified character mask. If null, then
+     * characters will be echoed. If 0, then no characters will be echoed.
+     */
+    public String readLine(final Character mask) throws IOException {
+        return readLine(null, mask);
+    }
+
+    /**
+     * @param bellEnabled
+     *            if true, enable audible keyboard bells if an alert is
+     *            required.
+     */
+    public void setBellEnabled(final boolean bellEnabled) {
+        this.bellEnabled = bellEnabled;
+    }
+
+    /**
+     * @return true is audible keyboard bell is enabled.
+     */
+    public boolean getBellEnabled() {
+        return this.bellEnabled;
+    }
+
+    /**
+     * Query the terminal to find the current width;
+     *
+     * @see Terminal#getTerminalWidth
+     * @return the width of the current terminal.
+     */
+    public int getTermwidth() {
+        return Terminal.setupTerminal().getTerminalWidth();
+    }
+
+    /**
+     * Query the terminal to find the current width;
+     *
+     * @see Terminal#getTerminalHeight
+     *
+     * @return the height of the current terminal.
+     */
+    public int getTermheight() {
+        return Terminal.setupTerminal().getTerminalHeight();
+    }
+
+    /**
+     * @param autoprintThreshhold
+     *            the number of candidates to print without issuing a warning.
+     */
+    public void setAutoprintThreshhold(final int autoprintThreshhold) {
+        this.autoprintThreshhold = autoprintThreshhold;
+    }
+
+    /**
+     * @return the number of candidates to print without issing a warning.
+     */
+    public int getAutoprintThreshhold() {
+        return this.autoprintThreshhold;
+    }
+
+    int getKeyForAction(short logicalAction) {
+        for (int i = 0; i < keybindings.length; i++) {
+            if (keybindings[i] == logicalAction) {
+                return i;
+            }
+        }
+
+        return -1;
+    }
+
+    /**
+     * Clear the echoed characters for the specified character code.
+     */
+    int clearEcho(int c) throws IOException {
+        // if the terminal is not echoing, then just return...
+        if (!terminal.getEcho()) {
+            return 0;
+        }
+
+        // otherwise, clear
+        int num = countEchoCharacters((char) c);
+        back(num);
+        drawBuffer(num);
+
+        return num;
+    }
+
+    int countEchoCharacters(char c) {
+        // tabs as special: we need to determine the number of spaces
+        // to cancel based on what out current cursor position is
+        if (c == 9) {
+            int tabstop = 8; // will this ever be different?
+            int position = getCursorPosition();
+
+            return tabstop - (position % tabstop);
+        }
+
+        return getPrintableCharacters(c).length();
+    }
+
+    /**
+     * Return the number of characters that will be printed when the specified
+     * character is echoed to the screen. Adapted from cat by Torbjorn Granlund,
+     * as repeated in stty by David MacKenzie.
+     */
+    StringBuffer getPrintableCharacters(char ch) {
+        StringBuffer sbuff = new StringBuffer();
+
+        if (ch >= 32) {
+            if (ch < 127) {
+                sbuff.append(ch);
+            } else if (ch == 127) {
+                sbuff.append('^');
+                sbuff.append('?');
+            } else {
+                sbuff.append('M');
+                sbuff.append('-');
+
+                if (ch >= (128 + 32)) {
+                    if (ch < (128 + 127)) {
+                        sbuff.append((char) (ch - 128));
+                    } else {
+                        sbuff.append('^');
+                        sbuff.append('?');
+                    }
+                } else {
+                    sbuff.append('^');
+                    sbuff.append((char) (ch - 128 + 64));
+                }
+            }
+        } else {
+            sbuff.append('^');
+            sbuff.append((char) (ch + 64));
+        }
+
+        return sbuff;
+    }
+
+    int getCursorPosition() {
+        // FIXME: does not handle anything but a line with a prompt
+        // absolute position
+        return ((prompt == null) ? 0 : prompt.length()) + buf.cursor;
+    }
+
+    public String readLine(final String prompt) throws IOException {
+        return readLine(prompt, null);
+    }
+
+    /**
+     * The default prompt that will be issued.
+     */
+    public void setDefaultPrompt(String prompt) {
+        this.prompt = prompt;
+    }
+
+    /**
+     * The default prompt that will be issued.
+     */
+    public String getDefaultPrompt() {
+        return prompt;
+    }
+
+    /**
+     * Read a line from the <i>in</i> {@link InputStream}, and return the line
+     * (without any trailing newlines).
+     *
+     * @param prompt
+     *            the prompt to issue to the console, may be null.
+     * @return a line that is read from the terminal, or null if there was null
+     *         input (e.g., <i>CTRL-D</i> was pressed).
+     */
+    public String readLine(final String prompt, final Character mask)
+            throws IOException {
+        this.mask = mask;
+        if (prompt != null)
+            this.prompt = prompt;
+
+        try {
+            terminal.beforeReadLine(this, this.prompt, mask);
+
+            if ((this.prompt != null) && (this.prompt.length() > 0)) {
+                out.write(this.prompt);
+                out.flush();
+            }
+
+            // if the terminal is unsupported, just use plain-java reading
+            if (!terminal.isSupported()) {
+                return readLine(in);
+            }
+
+            while (true) {
+                int[] next = readBinding();
+
+                if (next == null) {
+                    return null;
+                }
+
+                int c = next[0];
+                int code = next[1];
+
+                if (c == -1) {
+                    return null;
+                }
+
+                boolean success = true;
+
+                switch (code) {
+                case EXIT: // ctrl-d
+
+                    if (buf.buffer.length() == 0) {
+                        return null;
+                    }
+		    break;
+
+                case COMPLETE: // tab
+                    success = complete();
+                    break;
+
+                case MOVE_TO_BEG:
+                    success = setCursorPosition(0);
+                    break;
+
+                case KILL_LINE: // CTRL-K
+                    success = killLine();
+                    break;
+
+                case CLEAR_SCREEN: // CTRL-L
+                    success = clearScreen();
+                    break;
+
+                case KILL_LINE_PREV: // CTRL-U
+                    success = resetLine();
+                    break;
+
+                case NEWLINE: // enter
+                    moveToEnd();
+                    printNewline(); // output newline
+                    return finishBuffer();
+
+                case DELETE_PREV_CHAR: // backspace
+                    success = backspace();
+                    break;
+
+                case DELETE_NEXT_CHAR: // delete
+                    success = deleteCurrentCharacter();
+                    break;
+
+                case MOVE_TO_END:
+                    success = moveToEnd();
+                    break;
+
+                case PREV_CHAR:
+                    success = moveCursor(-1) != 0;
+                    break;
+
+                case NEXT_CHAR:
+                    success = moveCursor(1) != 0;
+                    break;
+
+                case NEXT_HISTORY:
+                    success = moveHistory(true);
+                    break;
+
+                case PREV_HISTORY:
+                    success = moveHistory(false);
+                    break;
+
+                case REDISPLAY:
+                    break;
+
+                case PASTE:
+                    success = paste();
+                    break;
+
+                case DELETE_PREV_WORD:
+                    success = deletePreviousWord();
+                    break;
+
+                case PREV_WORD:
+                    success = previousWord();
+                    break;
+
+                case NEXT_WORD:
+                    success = nextWord();
+                    break;
+
+                case START_OF_HISTORY:
+                    success = history.moveToFirstEntry();
+                    if (success)
+                        setBuffer(history.current());
+                    break;
+
+                case END_OF_HISTORY:
+                    success = history.moveToLastEntry();
+                    if (success)
+                        setBuffer(history.current());
+                    break;
+
+                case CLEAR_LINE:
+                    moveInternal(-(buf.buffer.length()));
+                    killLine();
+                    break;
+
+                case INSERT:
+                    buf.setOvertyping(!buf.isOvertyping());
+                    break;
+
+                case UNKNOWN:
+                default:
+                    if (c != 0) { // ignore null chars
+                    	ActionListener action = (ActionListener) triggeredActions.get(new Character((char)c));
+                    	if (action != null)
+                    		action.actionPerformed(null);
+                    	else
+                    		putChar(c, true);
+                    } else
+                        success = false;
+                }
+
+                if (!(success)) {
+                    beep();
+                }
+
+                flushConsole();
+            }
+        } finally {
+            terminal.afterReadLine(this, this.prompt, mask);
+        }
+    }
+
+    private String readLine(InputStream in) throws IOException {
+        StringBuffer buf = new StringBuffer();
+
+        while (true) {
+            int i = in.read();
+
+            if ((i == -1) || (i == '\n') || (i == '\r')) {
+                return buf.toString();
+            }
+
+            buf.append((char) i);
+        }
+
+        // return new BufferedReader (new InputStreamReader (in)).readLine ();
+    }
+
+    /**
+     * Reads the console input and returns an array of the form [raw, key
+     * binding].
+     */
+    private int[] readBinding() throws IOException {
+        int c = readVirtualKey();
+
+        if (c == -1) {
+            return null;
+        }
+
+        // extract the appropriate key binding
+        short code = keybindings[c];
+
+        if (debugger != null) {
+            debug("    translated: " + (int) c + ": " + code);
+        }
+
+        return new int[] { c, code };
+    }
+
+    /**
+     * Move up or down the history tree.
+     */
+    private final boolean moveHistory(final boolean next) throws IOException {
+        if (next && !history.next()) {
+            return false;
+        } else if (!next && !history.previous()) {
+            return false;
+        }
+
+        setBuffer(history.current());
+
+        return true;
+    }
+
+    /**
+     * Paste the contents of the clipboard into the console buffer
+     *
+     * @return true if clipboard contents pasted
+     */
+    public boolean paste() throws IOException {
+        Clipboard clipboard;
+        try { // May throw ugly exception on system without X
+            clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
+        } catch (Exception e) {
+            return false;
+        }
+
+        if (clipboard == null) {
+            return false;
+        }
+
+        Transferable transferable = clipboard.getContents(null);
+
+        if (transferable == null) {
+            return false;
+        }
+
+        try {
+            Object content = transferable
+                    .getTransferData(DataFlavor.plainTextFlavor);
+
+            /*
+             * This fix was suggested in bug #1060649 at
+             * http://sourceforge.net/tracker/index.php?func=detail&aid=1060649&group_id=64033&atid=506056
+             * to get around the deprecated DataFlavor.plainTextFlavor, but it
+             * raises a UnsupportedFlavorException on Mac OS X
+             */
+            if (content == null) {
+                try {
+                    content = new DataFlavor().getReaderForText(transferable);
+                } catch (Exception e) {
+                }
+            }
+
+            if (content == null) {
+                return false;
+            }
+
+            String value;
+
+            if (content instanceof Reader) {
+                // TODO: we might want instead connect to the input stream
+                // so we can interpret individual lines
+                value = "";
+
+                String line = null;
+
+                for (BufferedReader read = new BufferedReader((Reader) content); (line = read
+                        .readLine()) != null;) {
+                    if (value.length() > 0) {
+                        value += "\n";
+                    }
+
+                    value += line;
+                }
+            } else {
+                value = content.toString();
+            }
+
+            if (value == null) {
+                return true;
+            }
+
+            putString(value);
+
+            return true;
+        } catch (UnsupportedFlavorException ufe) {
+            if (debugger != null)
+                debug(ufe + "");
+
+            return false;
+        }
+    }
+
+    /**
+     * Kill the buffer ahead of the current cursor position.
+     *
+     * @return true if successful
+     */
+    public boolean killLine() throws IOException {
+        int cp = buf.cursor;
+        int len = buf.buffer.length();
+
+        if (cp >= len) {
+            return false;
+        }
+
+        int num = buf.buffer.length() - cp;
+        clearAhead(num);
+
+        for (int i = 0; i < num; i++) {
+            buf.buffer.deleteCharAt(len - i - 1);
+        }
+
+        return true;
+    }
+
+    /**
+     * Clear the screen by issuing the ANSI "clear screen" code.
+     */
+    public boolean clearScreen() throws IOException {
+        if (!terminal.isANSISupported()) {
+            return false;
+        }
+
+        // send the ANSI code to clear the screen
+        printString(((char) 27) + "[2J");
+        flushConsole();
+
+        // then send the ANSI code to go to position 1,1
+        printString(((char) 27) + "[1;1H");
+        flushConsole();
+
+        redrawLine();
+
+        return true;
+    }
+
+    /**
+     * Use the completors to modify the buffer with the appropriate completions.
+     *
+     * @return true if successful
+     */
+    private final boolean complete() throws IOException {
+        // debug ("tab for (" + buf + ")");
+        if (completors.size() == 0) {
+            return false;
+        }
+
+        List<String> candidates = new LinkedList<String>();
+        String bufstr = buf.buffer.toString();
+        int cursor = buf.cursor;
+
+        int position = -1;
+
+        for (Iterator i = completors.iterator(); i.hasNext();) {
+            Completor comp = (Completor) i.next();
+
+            if ((position = comp.complete(bufstr, cursor, candidates)) != -1) {
+                break;
+            }
+        }
+
+        // no candidates? Fail.
+        if (candidates.size() == 0) {
+            return false;
+        }
+
+        return completionHandler.complete(this, candidates, position);
+    }
+
+    public CursorBuffer getCursorBuffer() {
+        return buf;
+    }
+
+    /**
+     * Output the specified {@link Collection} in proper columns.
+     *
+     * @param stuff
+     *            the stuff to print
+     */
+    public void printColumns(final Collection stuff) throws IOException {
+        if ((stuff == null) || (stuff.size() == 0)) {
+            return;
+        }
+
+        int width = getTermwidth();
+        int maxwidth = 0;
+
+        for (Iterator i = stuff.iterator(); i.hasNext(); maxwidth = Math.max(
+                maxwidth, i.next().toString().length())) {
+            ;
+        }
+
+        StringBuffer line = new StringBuffer();
+
+        int showLines;
+
+        if (usePagination)
+            showLines = getTermheight() - 1; // page limit
+        else
+            showLines = Integer.MAX_VALUE;
+
+        for (Iterator i = stuff.iterator(); i.hasNext();) {
+            String cur = (String) i.next();
+
+            if ((line.length() + maxwidth) > width) {
+                printString(line.toString().trim());
+                printNewline();
+                line.setLength(0);
+                if (--showLines == 0) { // Overflow
+                    printString(loc.getString("display-more"));
+                    flushConsole();
+                    int c = readVirtualKey();
+                    if (c == '\r' || c == '\n')
+                        showLines = 1; // one step forward
+                    else if (c != 'q')
+                        showLines = getTermheight() - 1; // page forward
+
+                    back(loc.getString("display-more").length());
+                    if (c == 'q')
+                        break; // cancel
+                }
+            }
+
+            pad(cur, maxwidth + 3, line);
+        }
+
+        if (line.length() > 0) {
+            printString(line.toString().trim());
+            printNewline();
+            line.setLength(0);
+        }
+    }
+
+    /**
+     * Append <i>toPad</i> to the specified <i>appendTo</i>, as well as (<i>toPad.length () -
+     * len</i>) spaces.
+     *
+     * @param toPad
+     *            the {@link String} to pad
+     * @param len
+     *            the target length
+     * @param appendTo
+     *            the {@link StringBuffer} to which to append the padded
+     *            {@link String}.
+     */
+    private final void pad(final String toPad, final int len,
+            final StringBuffer appendTo) {
+        appendTo.append(toPad);
+
+        for (int i = 0; i < (len - toPad.length()); i++, appendTo.append(' ')) {
+            ;
+        }
+    }
+
+    /**
+     * Add the specified {@link Completor} to the list of handlers for
+     * tab-completion.
+     *
+     * @param completor
+     *            the {@link Completor} to add
+     * @return true if it was successfully added
+     */
+    public boolean addCompletor(final Completor completor) {
+        return completors.add(completor);
+    }
+
+    /**
+     * Remove the specified {@link Completor} from the list of handlers for
+     * tab-completion.
+     *
+     * @param completor
+     *            the {@link Completor} to remove
+     * @return true if it was successfully removed
+     */
+    public boolean removeCompletor(final Completor completor) {
+        return completors.remove(completor);
+    }
+
+    /**
+     * Returns an unmodifiable list of all the completors.
+     */
+    public Collection<Completor> getCompletors() {
+        return Collections.unmodifiableList(completors);
+    }
+
+    /**
+     * Erase the current line.
+     *
+     * @return false if we failed (e.g., the buffer was empty)
+     */
+    final boolean resetLine() throws IOException {
+        if (buf.cursor == 0) {
+            return false;
+        }
+
+        backspaceAll();
+
+        return true;
+    }
+
+    /**
+     * Move the cursor position to the specified absolute index.
+     */
+    public final boolean setCursorPosition(final int position)
+            throws IOException {
+        return moveCursor(position - buf.cursor) != 0;
+    }
+
+    /**
+     * Set the current buffer's content to the specified {@link String}. The
+     * visual console will be modified to show the current buffer.
+     *
+     * @param buffer
+     *            the new contents of the buffer.
+     */
+    private final void setBuffer(final String buffer) throws IOException {
+        // don't bother modifying it if it is unchanged
+        if (buffer.equals(buf.buffer.toString())) {
+            return;
+        }
+
+        // obtain the difference between the current buffer and the new one
+        int sameIndex = 0;
+
+        for (int i = 0, l1 = buffer.length(), l2 = buf.buffer.length(); (i < l1)
+                && (i < l2); i++) {
+            if (buffer.charAt(i) == buf.buffer.charAt(i)) {
+                sameIndex++;
+            } else {
+                break;
+            }
+        }
+
+        int diff = buf.buffer.length() - sameIndex;
+
+        backspace(diff); // go back for the differences
+        killLine(); // clear to the end of the line
+        buf.buffer.setLength(sameIndex); // the new length
+        putString(buffer.substring(sameIndex)); // append the differences
+    }
+
+    /**
+     * Clear the line and redraw it.
+     */
+    public final void redrawLine() throws IOException {
+        printCharacter(RESET_LINE);
+        flushConsole();
+        drawLine();
+    }
+
+    /**
+     * Output put the prompt + the current buffer
+     */
+    public final void drawLine() throws IOException {
+        if (prompt != null) {
+            printString(prompt);
+        }
+
+        printString(buf.buffer.toString());
+
+        if (buf.length() != buf.cursor) // not at end of line
+            back(buf.length() - buf.cursor); // sync
+    }
+
+    /**
+     * Output a platform-dependant newline.
+     */
+    public final void printNewline() throws IOException {
+        printString(CR);
+        flushConsole();
+    }
+
+    /**
+     * Clear the buffer and add its contents to the history.
+     *
+     * @return the former contents of the buffer.
+     */
+    final String finishBuffer() {
+        String str = buf.buffer.toString();
+
+        // we only add it to the history if the buffer is not empty
+        // and if mask is null, since having a mask typically means
+        // the string was a password. We clear the mask after this call
+        if (str.length() > 0) {
+            if (mask == null && useHistory) {
+                history.addToHistory(str);
+            } else {
+                mask = null;
+            }
+        }
+
+        history.moveToEnd();
+
+        buf.buffer.setLength(0);
+        buf.cursor = 0;
+
+        return str;
+    }
+
+    /**
+     * Write out the specified string to the buffer and the output stream.
+     */
+    public final void putString(final String str) throws IOException {
+        buf.write(str);
+        printString(str);
+        drawBuffer();
+    }
+
+    /**
+     * Output the specified string to the output stream (but not the buffer).
+     */
+    public final void printString(final String str) throws IOException {
+        printCharacters(str.toCharArray());
+    }
+
+    /**
+     * Output the specified character, both to the buffer and the output stream.
+     */
+    private final void putChar(final int c, final boolean print)
+            throws IOException {
+        buf.write((char) c);
+
+        if (print) {
+            // no masking...
+            if (mask == null) {
+                printCharacter(c);
+            }
+            // null mask: don't print anything...
+            else if (mask.charValue() == 0) {
+                ;
+            }
+            // otherwise print the mask...
+            else {
+                printCharacter(mask.charValue());
+            }
+
+            drawBuffer();
+        }
+    }
+
+    /**
+     * Redraw the rest of the buffer from the cursor onwards. This is necessary
+     * for inserting text into the buffer.
+     *
+     * @param clear
+     *            the number of characters to clear after the end of the buffer
+     */
+    private final void drawBuffer(final int clear) throws IOException {
+        // debug ("drawBuffer: " + clear);
+        char[] chars = buf.buffer.substring(buf.cursor).toCharArray();
+        if (mask != null)
+            Arrays.fill(chars, mask.charValue());
+
+        printCharacters(chars);
+
+        clearAhead(clear);
+        back(chars.length);
+        flushConsole();
+    }
+
+    /**
+     * Redraw the rest of the buffer from the cursor onwards. This is necessary
+     * for inserting text into the buffer.
+     */
+    private final void drawBuffer() throws IOException {
+        drawBuffer(0);
+    }
+
+    /**
+     * Clear ahead the specified number of characters without moving the cursor.
+     */
+    private final void clearAhead(final int num) throws IOException {
+        if (num == 0) {
+            return;
+        }
+
+        // debug ("clearAhead: " + num);
+
+        // print blank extra characters
+        printCharacters(' ', num);
+
+        // we need to flush here so a "clever" console
+        // doesn't just ignore the redundancy of a space followed by
+        // a backspace.
+        flushConsole();
+
+        // reset the visual cursor
+        back(num);
+
+        flushConsole();
+    }
+
+    /**
+     * Move the visual cursor backwards without modifying the buffer cursor.
+     */
+    private final void back(final int num) throws IOException {
+        printCharacters(BACKSPACE, num);
+        flushConsole();
+    }
+
+    /**
+     * Issue an audible keyboard bell, if {@link #getBellEnabled} return true.
+     */
+    public final void beep() throws IOException {
+        if (!(getBellEnabled())) {
+            return;
+        }
+
+        printCharacter(KEYBOARD_BELL);
+        // need to flush so the console actually beeps
+        flushConsole();
+    }
+
+    /**
+     * Output the specified character to the output stream without manipulating
+     * the current buffer.
+     */
+    private final void printCharacter(final int c) throws IOException {
+        if (c == '\t') {
+            char cbuf[] = new char[TAB_WIDTH];
+            Arrays.fill(cbuf, ' ');
+            out.write(cbuf);
+            return;
+        }
+	    
+        out.write(c);
+    }
+
+    /**
+     * Output the specified characters to the output stream without manipulating
+     * the current buffer.
+     */
+    private final void printCharacters(final char[] c) throws IOException {
+        int len = 0;
+        for (int i = 0; i < c.length; i++)
+            if (c[i] == '\t')
+                len += TAB_WIDTH;
+            else
+                len++;
+
+        char cbuf[];        
+        if (len == c.length)
+            cbuf = c;
+        else {
+            cbuf = new char[len];
+            int pos = 0;
+            for (int i = 0; i < c.length; i++){
+                if (c[i] == '\t') {
+                    Arrays.fill(cbuf, pos, pos + TAB_WIDTH, ' ');
+                    pos += TAB_WIDTH;
+	        } else {
+                    cbuf[pos] = c[i];
+                    pos++;
+                }
+	    }
+        }
+            
+        out.write(cbuf);
+    }
+
+    private final void printCharacters(final char c, final int num)
+            throws IOException {
+        if (num == 1) {
+            printCharacter(c);
+        } else {
+            char[] chars = new char[num];
+            Arrays.fill(chars, c);
+            printCharacters(chars);
+        }
+    }
+
+    /**
+     * Flush the console output stream. This is important for printout out
+     * single characters (like a backspace or keyboard) that we want the console
+     * to handle immedately.
+     */
+    public final void flushConsole() throws IOException {
+        out.flush();
+    }
+
+    private final int backspaceAll() throws IOException {
+        return backspace(Integer.MAX_VALUE);
+    }
+
+    /**
+     * Issue <em>num</em> backspaces.
+     *
+     * @return the number of characters backed up
+     */
+    private final int backspace(final int num) throws IOException {
+        if (buf.cursor == 0) {
+            return 0;
+        }
+
+        int count = 0;
+
+        count = moveCursor(-1 * num) * -1;
+        // debug ("Deleting from " + buf.cursor + " for " + count);
+        buf.buffer.delete(buf.cursor, buf.cursor + count);
+        drawBuffer(count);
+
+        return count;
+    }
+
+    /**
+     * Issue a backspace.
+     *
+     * @return true if successful
+     */
+    public final boolean backspace() throws IOException {
+        return backspace(1) == 1;
+    }
+
+    private final boolean moveToEnd() throws IOException {
+        if (moveCursor(1) == 0) {
+            return false;
+        }
+
+        while (moveCursor(1) != 0) {
+            ;
+        }
+
+        return true;
+    }
+
+    /**
+     * Delete the character at the current position and redraw the remainder of
+     * the buffer.
+     */
+    private final boolean deleteCurrentCharacter() throws IOException {
+        boolean success = buf.buffer.length() > 0;
+        if (!success) {
+            return false;
+        }
+
+        if (buf.cursor == buf.buffer.length()) {
+            return false;
+        }
+
+        buf.buffer.deleteCharAt(buf.cursor);
+        drawBuffer(1);
+        return true;
+    }
+
+    private final boolean previousWord() throws IOException {
+        while (isDelimiter(buf.current()) && (moveCursor(-1) != 0)) {
+            ;
+        }
+
+        while (!isDelimiter(buf.current()) && (moveCursor(-1) != 0)) {
+            ;
+        }
+
+        return true;
+    }
+
+    private final boolean nextWord() throws IOException {
+        while (isDelimiter(buf.current()) && (moveCursor(1) != 0)) {
+            ;
+        }
+
+        while (!isDelimiter(buf.current()) && (moveCursor(1) != 0)) {
+            ;
+        }
+
+        return true;
+    }
+
+    private final boolean deletePreviousWord() throws IOException {
+        while (isDelimiter(buf.current()) && backspace()) {
+            ;
+        }
+
+        while (!isDelimiter(buf.current()) && backspace()) {
+            ;
+        }
+
+        return true;
+    }
+
+    /**
+     * Move the cursor <i>where</i> characters.
+     *
+     * @param where
+     *            if less than 0, move abs(<i>where</i>) to the left,
+     *            otherwise move <i>where</i> to the right.
+     *
+     * @return the number of spaces we moved
+     */
+    public final int moveCursor(final int num) throws IOException {
+        int where = num;
+
+        if ((buf.cursor == 0) && (where < 0)) {
+            return 0;
+        }
+
+        if ((buf.cursor == buf.buffer.length()) && (where > 0)) {
+            return 0;
+        }
+
+        if ((buf.cursor + where) < 0) {
+            where = -buf.cursor;
+        } else if ((buf.cursor + where) > buf.buffer.length()) {
+            where = buf.buffer.length() - buf.cursor;
+        }
+
+        moveInternal(where);
+
+        return where;
+    }
+
+    /**
+     * debug.
+     *
+     * @param str
+     *            the message to issue.
+     */
+    public static void debug(final String str) {
+        if (debugger != null) {
+            debugger.println(str);
+            debugger.flush();
+        }
+    }
+
+    /**
+     * Move the cursor <i>where</i> characters, withough checking the current
+     * buffer.
+     *
+     * @see #where
+     *
+     * @param where
+     *            the number of characters to move to the right or left.
+     */
+    private final void moveInternal(final int where) throws IOException {
+        // debug ("move cursor " + where + " ("
+        // + buf.cursor + " => " + (buf.cursor + where) + ")");
+        buf.cursor += where;
+
+        char c;
+
+        if (where < 0) {
+	    int len = 0;
+            for (int i = buf.cursor; i < buf.cursor - where; i++){
+                if (buf.getBuffer().charAt(i) == '\t')
+                    len += TAB_WIDTH;
+                else
+                    len++;
+	    }
+
+	    char cbuf[] = new char[len];
+	    Arrays.fill(cbuf, BACKSPACE);
+	    out.write(cbuf);
+		
+	    return;
+        } else if (buf.cursor == 0) {
+            return;
+        } else if (mask != null) {
+            c = mask.charValue();
+        } else {
+            printCharacters(buf.buffer.substring(buf.cursor - where, buf.cursor).toCharArray());
+            return;
+        }
+
+        // null character mask: don't output anything
+        if (NULL_MASK.equals(mask)) {
+            return;
+        }
+
+        printCharacters(c, Math.abs(where));
+    }
+
+    /**
+     * Read a character from the console.
+     *
+     * @return the character, or -1 if an EOF is received.
+     */
+    public final int readVirtualKey() throws IOException {
+        int c = terminal.readVirtualKey(in);
+
+        if (debugger != null) {
+            debug("keystroke: " + c + "");
+        }
+
+        // clear any echo characters
+        clearEcho(c);
+
+        return c;
+    }
+
+    public final int readCharacter(final char[] allowed) throws IOException {
+        // if we restrict to a limited set and the current character
+        // is not in the set, then try again.
+        char c;
+
+        Arrays.sort(allowed); // always need to sort before binarySearch
+
+        while (Arrays.binarySearch(allowed, c = (char) readVirtualKey()) < 0)
+            ;
+
+        return c;
+    }
+
+   
+    /**
+     *  Issue <em>num</em> deletes.
+     *
+     *  @return  the number of characters backed up
+     */
+    private final int delete (final int num)
+    throws IOException
+    {
+    	/* Commented out beacuse of DWA-2949:
+           if (buf.cursor == 0)
+                       return 0;*/
+
+        buf.buffer.delete (buf.cursor, buf.cursor + 1);
+        drawBuffer (1);
+
+        return 1;
+    }
+
+    public final boolean replace(int num, String replacement) {
+        buf.buffer.replace(buf.cursor - num, buf.cursor, replacement);
+        try {
+            moveCursor(-num);
+            drawBuffer(Math.max(0, num - replacement.length()));
+            moveCursor(replacement.length());
+        } catch (IOException e) {
+            e.printStackTrace();
+            return false;
+        }
+        return true;
+    }
+
+    /**
+     *  Issue a delete.
+     *
+     *  @return  true if successful
+     */
+    public final boolean delete ()
+    throws IOException
+    {
+        return delete (1) == 1;
+    }
+
+
+    public void setHistory(final History history) {
+        this.history = history;
+    }
+
+    public History getHistory() {
+        return this.history;
+    }
+
+    public void setCompletionHandler(final CompletionHandler completionHandler) {
+        this.completionHandler = completionHandler;
+    }
+
+    public CompletionHandler getCompletionHandler() {
+        return this.completionHandler;
+    }
+
+    /**
+     * <p>
+     * Set the echo character. For example, to have "*" entered when a password
+     * is typed:
+     * </p>
+     *
+     * <pre>
+     * myConsoleReader.setEchoCharacter(new Character('*'));
+     * </pre>
+     *
+     * <p>
+     * Setting the character to
+     *
+     * <pre>
+     * null
+     * </pre>
+     *
+     * will restore normal character echoing. Setting the character to
+     *
+     * <pre>
+     * new Character(0)
+     * </pre>
+     *
+     * will cause nothing to be echoed.
+     * </p>
+     *
+     * @param echoCharacter
+     *            the character to echo to the console in place of the typed
+     *            character.
+     */
+    public void setEchoCharacter(final Character echoCharacter) {
+        this.echoCharacter = echoCharacter;
+    }
+
+    /**
+     * Returns the echo character.
+     */
+    public Character getEchoCharacter() {
+        return this.echoCharacter;
+    }
+
+    /**
+     * No-op for exceptions we want to silently consume.
+     */
+    private void consumeException(final Throwable e) {
+    }
+
+    /**
+     * Checks to see if the specified character is a delimiter. We consider a
+     * character a delimiter if it is anything but a letter or digit.
+     *
+     * @param c
+     *            the character to test
+     * @return true if it is a delimiter
+     */
+    private boolean isDelimiter(char c) {
+        return !Character.isLetterOrDigit(c);
+    }
+
+    /**
+     * Whether or not to add new commands to the history buffer.
+     */
+    public void setUseHistory(boolean useHistory) {
+        this.useHistory = useHistory;
+    }
+
+    /**
+     * Whether or not to add new commands to the history buffer.
+     */
+    public boolean getUseHistory() {
+        return useHistory;
+    }
+
+    /**
+     * Whether to use pagination when the number of rows of candidates exceeds
+     * the height of the temrinal.
+     */
+    public void setUsePagination(boolean usePagination) {
+        this.usePagination = usePagination;
+    }
+
+    /**
+     * Whether to use pagination when the number of rows of candidates exceeds
+     * the height of the temrinal.
+     */
+    public boolean getUsePagination() {
+        return this.usePagination;
+    }
+
+}
diff --git a/src/jline/src/main/java/jline/ConsoleReaderInputStream.java b/src/jline/src/main/java/jline/ConsoleReaderInputStream.java
new file mode 100644
index 0000000..d2a14d8
--- /dev/null
+++ b/src/jline/src/main/java/jline/ConsoleReaderInputStream.java
@@ -0,0 +1,108 @@
+/*
+ * Copyright (c) 2002-2007, Marc Prud'hommeaux. All rights reserved.
+ *
+ * This software is distributable under the BSD license. See the terms of the
+ * BSD license in the documentation provided with this software.
+ */
+package jline;
+
+import java.io.*;
+import java.util.*;
+
+/**
+ *  An {@link InputStream} implementation that wraps a {@link ConsoleReader}.
+ *  It is useful for setting up the {@link System#in} for a generic
+ *  console.
+ *  @author  <a href="mailto:mwp1 at cornell.edu">Marc Prud'hommeaux</a>
+ */
+public class ConsoleReaderInputStream extends SequenceInputStream {
+    private static InputStream systemIn = System.in;
+
+    public static void setIn() throws IOException {
+        setIn(new ConsoleReader());
+    }
+
+    public static void setIn(final ConsoleReader reader) {
+        System.setIn(new ConsoleReaderInputStream(reader));
+    }
+
+    /**
+     *  Restore the original {@link System#in} input stream.
+     */
+    public static void restoreIn() {
+        System.setIn(systemIn);
+    }
+
+    public ConsoleReaderInputStream(final ConsoleReader reader) {
+        super(new ConsoleEnumeration(reader));
+    }
+
+    private static class ConsoleEnumeration implements Enumeration<InputStream> {
+        private final ConsoleReader reader;
+        private ConsoleLineInputStream next = null;
+        private ConsoleLineInputStream prev = null;
+
+        public ConsoleEnumeration(final ConsoleReader reader) {
+            this.reader = reader;
+        }
+
+        public InputStream nextElement() {
+            if (next != null) {
+                InputStream n = next;
+                prev = next;
+                next = null;
+
+                return n;
+            }
+
+            return new ConsoleLineInputStream(reader);
+        }
+
+        public boolean hasMoreElements() {
+            // the last line was null
+            if ((prev != null) && (prev.wasNull == true)) {
+                return false;
+            }
+
+            if (next == null) {
+                next = (ConsoleLineInputStream) nextElement();
+            }
+
+            return next != null;
+        }
+    }
+
+    private static class ConsoleLineInputStream extends InputStream {
+        private final ConsoleReader reader;
+        private String line = null;
+        private int index = 0;
+        private boolean eol = false;
+        protected boolean wasNull = false;
+
+        public ConsoleLineInputStream(final ConsoleReader reader) {
+            this.reader = reader;
+        }
+
+        public int read() throws IOException {
+            if (eol) {
+                return -1;
+            }
+
+            if (line == null) {
+                line = reader.readLine();
+            }
+
+            if (line == null) {
+                wasNull = true;
+                return -1;
+            }
+
+            if (index >= line.length()) {
+                eol = true;
+                return '\n'; // lines are ended with a newline
+            }
+
+            return line.charAt(index++);
+        }
+    }
+}
diff --git a/src/jline/src/main/java/jline/ConsoleRunner.java b/src/jline/src/main/java/jline/ConsoleRunner.java
new file mode 100644
index 0000000..dac4b7c
--- /dev/null
+++ b/src/jline/src/main/java/jline/ConsoleRunner.java
@@ -0,0 +1,86 @@
+/*
+ * Copyright (c) 2002-2007, Marc Prud'hommeaux. All rights reserved.
+ *
+ * This software is distributable under the BSD license. See the terms of the
+ * BSD license in the documentation provided with this software.
+ */
+package jline;
+
+import java.io.*;
+import java.util.*;
+
+/**
+ *  <p>
+ *  A pass-through application that sets the system input stream to a
+ *  {@link ConsoleReader} and invokes the specified main method.
+ *  </p>
+ *  @author  <a href="mailto:mwp1 at cornell.edu">Marc Prud'hommeaux</a>
+ */
+public class ConsoleRunner {
+    public static final String property = "jline.history";
+
+    public static void main(final String[] args) throws Exception {
+        String historyFileName = null;
+
+        List<String> argList = new ArrayList<String>(Arrays.asList(args));
+
+        if (argList.size() == 0) {
+            usage();
+
+            return;
+        }
+
+        historyFileName = System.getProperty(ConsoleRunner.property, null);
+
+        // invoke the main() method
+        String mainClass = (String) argList.remove(0);
+
+        // setup the inpout stream
+        ConsoleReader reader = new ConsoleReader();
+
+        if (historyFileName != null) {
+            reader.setHistory(new History (new File
+                (System.getProperty("user.home"),
+                    ".jline-" + mainClass
+                        + "." + historyFileName + ".history")));
+        } else {
+            reader.setHistory(new History(new File
+                (System.getProperty("user.home"),
+                    ".jline-" + mainClass + ".history")));
+        }
+
+        String completors = System.getProperty
+            (ConsoleRunner.class.getName() + ".completors", "");
+        List<Completor> completorList = new ArrayList<Completor>();
+
+        for (StringTokenizer tok = new StringTokenizer(completors, ",");
+            tok.hasMoreTokens();) {
+            completorList.add
+                ((Completor) Class.forName(tok.nextToken()).newInstance());
+        }
+
+        if (completorList.size() > 0) {
+            reader.addCompletor(new ArgumentCompletor(completorList));
+        }
+
+        ConsoleReaderInputStream.setIn(reader);
+
+        try {
+            Class.forName(mainClass).
+                getMethod("main", new Class[] { String[].class }).
+                invoke(null, new Object[] { argList.toArray(new String[0]) });
+        } finally {
+            // just in case this main method is called from another program
+            ConsoleReaderInputStream.restoreIn();
+        }
+    }
+
+    private static void usage() {
+        System.out.println("Usage: \n   java " + "[-Djline.history='name'] "
+            + ConsoleRunner.class.getName()
+            + " <target class name> [args]"
+            + "\n\nThe -Djline.history option will avoid history"
+            + "\nmangling when running ConsoleRunner on the same application."
+            + "\n\nargs will be passed directly to the target class name.");
+    }
+}
diff --git a/src/jline/src/main/java/jline/CursorBuffer.java b/src/jline/src/main/java/jline/CursorBuffer.java
new file mode 100644
index 0000000..120d705
--- /dev/null
+++ b/src/jline/src/main/java/jline/CursorBuffer.java
@@ -0,0 +1,104 @@
+/*
+ * Copyright (c) 2002-2007, Marc Prud'hommeaux. All rights reserved.
+ *
+ * This software is distributable under the BSD license. See the terms of the
+ * BSD license in the documentation provided with this software.
+ */
+package jline;
+
+/**
+ * A CursorBuffer is a holder for a {@link StringBuffer} that also contains the
+ * current cursor position.
+ *
+ * @author <a href="mailto:mwp1 at cornell.edu">Marc Prud'hommeaux</a>
+ */
+public class CursorBuffer {
+    public int cursor = 0;
+
+    StringBuffer buffer = new StringBuffer();
+
+    private boolean overtyping = false;
+
+    public int length() {
+        return buffer.length();
+    }
+
+    public char current() {
+        if (cursor <= 0) {
+            return 0;
+        }
+
+        return buffer.charAt(cursor - 1);
+    }
+
+    public boolean clearBuffer() {
+        if (buffer.length() == 0) {
+            return false;
+        }
+
+        buffer.delete(0, buffer.length());
+        cursor = 0;
+        return true;
+    }
+
+    /**
+     * Write the specific character into the buffer, setting the cursor position
+     * ahead one. The text may overwrite or insert based on the current setting
+     * of isOvertyping().
+     *
+     * @param c
+     *            the character to insert
+     */
+    public void write(final char c) {
+        buffer.insert(cursor++, c);
+        if (isOvertyping() && cursor < buffer.length()) {
+            buffer.deleteCharAt(cursor);
+        }
+    }
+
+    /**
+     * Insert the specified {@link String} into the buffer, setting the cursor
+     * to the end of the insertion point.
+     *
+     * @param str
+     *            the String to insert. Must not be null.
+     */
+    public void write(final String str) {
+        if (buffer.length() == 0) {
+            buffer.append(str);
+        } else {
+            buffer.insert(cursor, str);
+        }
+
+        cursor += str.length();
+
+        if (isOvertyping() && cursor < buffer.length()) {
+            buffer.delete(cursor, (cursor + str.length()));
+        }
+    }
+
+    public String toString() {
+        return buffer.toString();
+    }
+
+    public boolean isOvertyping() {
+        return overtyping;
+    }
+
+    public void setOvertyping(boolean b) {
+        overtyping = b;
+    }
+
+	public StringBuffer getBuffer() {
+		return buffer;
+	}
+
+	public void setBuffer(StringBuffer buffer) {
+		buffer.setLength(0);
+		buffer.append(this.buffer.toString());
+		
+		this.buffer = buffer;
+	}
+    
+    
+}
diff --git a/src/jline/src/main/java/jline/FileNameCompletor.java b/src/jline/src/main/java/jline/FileNameCompletor.java
new file mode 100644
index 0000000..d1d6373
--- /dev/null
+++ b/src/jline/src/main/java/jline/FileNameCompletor.java
@@ -0,0 +1,133 @@
+/*
+ * Copyright (c) 2002-2007, Marc Prud'hommeaux. All rights reserved.
+ *
+ * This software is distributable under the BSD license. See the terms of the
+ * BSD license in the documentation provided with this software.
+ */
+package jline;
+
+import java.io.*;
+import java.util.*;
+
+/**
+ *  A file name completor takes the buffer and issues a list of
+ *  potential completions.
+ *
+ *  <p>
+ *  This completor tries to behave as similar as possible to
+ *  <i>bash</i>'s file name completion (using GNU readline)
+ *  with the following exceptions:
+ *
+ *  <ul>
+ *  <li>Candidates that are directories will end with "/"</li>
+ *  <li>Wildcard regular expressions are not evaluated or replaced</li>
+ *  <li>The "~" character can be used to represent the user's home,
+ *  but it cannot complete to other users' homes, since java does
+ *  not provide any way of determining that easily</li>
+ *  </ul>
+ *
+ *  <p>TODO</p>
+ *  <ul>
+ *  <li>Handle files with spaces in them</li>
+ *  <li>Have an option for file type color highlighting</li>
+ *  </ul>
+ *
+ *  @author  <a href="mailto:mwp1 at cornell.edu">Marc Prud'hommeaux</a>
+ */
+public class FileNameCompletor implements Completor {
+    public int complete(final String buf, final int cursor,
+                        final List<String> candidates) {
+        String buffer = (buf == null) ? "" : buf;
+
+        String translated = buffer;
+
+        // special character: ~ maps to the user's home directory
+        if (translated.startsWith("~" + File.separator)) {
+            translated = System.getProperty("user.home")
+                         + translated.substring(1);
+        } else if (translated.startsWith("~")) {
+            translated = new File(System.getProperty("user.home")).getParentFile()
+                                                                  .getAbsolutePath();
+        } else if (!(translated.startsWith(File.separator))) {
+            translated = new File("").getAbsolutePath() + File.separator
+                         + translated;
+        }
+
+        File f = new File(translated);
+
+        final File dir;
+
+        if (translated.endsWith(File.separator)) {
+            dir = f;
+        } else {
+            dir = f.getParentFile();
+        }
+
+        final File[] entries = (dir == null) ? new File[0] : dir.listFiles();
+
+        try {
+            return matchFiles(buffer, translated, entries, candidates);
+        } finally {
+            // we want to output a sorted list of files
+            sortFileNames(candidates);
+        }
+    }
+
+    protected void sortFileNames(final List<String> fileNames) {
+        Collections.sort(fileNames);
+    }
+
+    /**
+     *  Match the specified <i>buffer</i> to the array of <i>entries</i>
+     *  and enter the matches into the list of <i>candidates</i>. This method
+     *  can be overridden in a subclass that wants to do more
+     *  sophisticated file name completion.
+     *
+     *  @param        buffer                the untranslated buffer
+     *  @param        translated        the buffer with common characters replaced
+     *  @param        entries                the list of files to match
+     *  @param        candidates        the list of candidates to populate
+     *
+     *  @return  the offset of the match
+     */
+    public int matchFiles(String buffer, String translated, File[] entries,
+                          List<String> candidates) {
+        if (entries == null) {
+            return -1;
+        }
+
+        int matches = 0;
+
+        // first pass: just count the matches
+        for (int i = 0; i < entries.length; i++) {
+            if (entries[i].getAbsolutePath().startsWith(translated)) {
+                matches++;
+            }
+        }
+
+        // green - executable
+        // blue - directory
+        // red - compressed
+        // cyan - symlink
+        for (int i = 0; i < entries.length; i++) {
+            if (entries[i].getAbsolutePath().startsWith(translated)) {
+                String name =
+                    entries[i].getName()
+                    + (((matches == 1) && entries[i].isDirectory())
+                       ? File.separator : " ");
+
+                /*
+                if (entries [i].isDirectory ())
+                {
+                        name = new ANSIBuffer ().blue (name).toString ();
+                }
+                */
+                candidates.add(name);
+            }
+        }
+
+        final int index = buffer.lastIndexOf(File.separator);
+
+        return index + File.separator.length();
+    }
+}
diff --git a/src/jline/src/main/java/jline/History.java b/src/jline/src/main/java/jline/History.java
new file mode 100644
index 0000000..9e96f69
--- /dev/null
+++ b/src/jline/src/main/java/jline/History.java
@@ -0,0 +1,255 @@
+/*
+ * Copyright (c) 2002-2007, Marc Prud'hommeaux. All rights reserved.
+ *
+ * This software is distributable under the BSD license. See the terms of the
+ * BSD license in the documentation provided with this software.
+ */
+package jline;
+
+import java.io.*;
+import java.util.*;
+
+/**
+ * A command history buffer.
+ *
+ * @author <a href="mailto:mwp1 at cornell.edu">Marc Prud'hommeaux</a>
+ */
+public class History {
+    private List<String> history = new ArrayList<String>();
+
+    private PrintWriter output = null;
+
+    private int maxSize = 500;
+
+    private int currentIndex = 0;
+
+    /**
+     * Construstor: initialize a blank history.
+     */
+    public History() {
+    }
+
+    /**
+     * Construstor: initialize History object the the specified {@link File} for
+     * storage.
+     */
+    public History(final File historyFile) throws IOException {
+        setHistoryFile(historyFile);
+    }
+
+    public void setHistoryFile(final File historyFile) throws IOException {
+        if (historyFile.isFile()) {
+            load(new FileInputStream(historyFile));
+        }
+
+        setOutput(new PrintWriter(new FileWriter(historyFile), true));
+        flushBuffer();
+    }
+
+    /**
+     * Load the history buffer from the specified InputStream.
+     */
+    public void load(final InputStream in) throws IOException {
+        load(new InputStreamReader(in));
+    }
+
+    /**
+     * Load the history buffer from the specified Reader.
+     */
+    public void load(final Reader reader) throws IOException {
+        BufferedReader breader = new BufferedReader(reader);
+        List<String> lines = new ArrayList<String>();
+        String line;
+
+        while ((line = breader.readLine()) != null) {
+            lines.add(line);
+        }
+
+        for (Iterator i = lines.iterator(); i.hasNext();) {
+            addToHistory((String) i.next());
+        }
+    }
+
+    public int size() {
+        return history.size();
+    }
+
+    /**
+     * Clear the history buffer
+     */
+    public void clear() {
+        history.clear();
+        currentIndex = 0;
+    }
+
+    /**
+     * Add the specified buffer to the end of the history. The pointer is set to
+     * the end of the history buffer.
+     */
+    public void addToHistory(final String buffer) {
+        // don't append duplicates to the end of the buffer
+        if ((history.size() != 0)
+                && buffer.equals(history.get(history.size() - 1))) {
+            return;
+        }
+
+        history.add(buffer);
+
+        while (history.size() > getMaxSize()) {
+            history.remove(0);
+        }
+
+        currentIndex = history.size();
+
+        if (getOutput() != null) {
+            getOutput().println(buffer);
+            getOutput().flush();
+        }
+    }
+
+    /**
+     * Flush the entire history buffer to the output PrintWriter.
+     */
+    public void flushBuffer() throws IOException {
+        if (getOutput() != null) {
+            for (Iterator i = history.iterator(); i.hasNext(); getOutput()
+                    .println((String) i.next())) {
+                ;
+            }
+
+            getOutput().flush();
+        }
+    }
+
+    /**
+     * This moves the history to the last entry. This entry is one position
+     * before the moveToEnd() position.
+     *
+     * @return Returns false if there were no history entries or the history
+     *         index was already at the last entry.
+     */
+    public boolean moveToLastEntry() {
+        int lastEntry = history.size() - 1;
+        if (lastEntry >= 0 && lastEntry != currentIndex) {
+            currentIndex = history.size() - 1;
+            return true;
+        }
+
+        return false;
+    }
+
+    /**
+     * Move to the end of the history buffer. This will be a blank entry, after
+     * all of the other entries.
+     */
+    public void moveToEnd() {
+        currentIndex = history.size();
+    }
+
+    /**
+     * Set the maximum size that the history buffer will store.
+     */
+    public void setMaxSize(final int maxSize) {
+        this.maxSize = maxSize;
+    }
+
+    /**
+     * Get the maximum size that the history buffer will store.
+     */
+    public int getMaxSize() {
+        return this.maxSize;
+    }
+
+    /**
+     * The output to which all history elements will be written (or null of
+     * history is not saved to a buffer).
+     */
+    public void setOutput(final PrintWriter output) {
+        this.output = output;
+    }
+
+    /**
+     * Returns the PrintWriter that is used to store history elements.
+     */
+    public PrintWriter getOutput() {
+        return this.output;
+    }
+
+    /**
+     * Returns the current history index.
+     */
+    public int getCurrentIndex() {
+        return this.currentIndex;
+    }
+
+    /**
+     * Return the content of the current buffer.
+     */
+    public String current() {
+        if (currentIndex >= history.size()) {
+            return "";
+        }
+
+        return (String) history.get(currentIndex);
+    }
+
+    /**
+     * Move the pointer to the previous element in the buffer.
+     *
+     * @return true if we successfully went to the previous element
+     */
+    public boolean previous() {
+        if (currentIndex <= 0) {
+            return false;
+        }
+
+        currentIndex--;
+
+        return true;
+    }
+
+    /**
+     * Move the pointer to the next element in the buffer.
+     *
+     * @return true if we successfully went to the next element
+     */
+    public boolean next() {
+        if (currentIndex >= history.size()) {
+            return false;
+        }
+
+        currentIndex++;
+
+        return true;
+    }
+
+    /**
+     * Returns an immutable list of the history buffer.
+     */
+    public List<String> getHistoryList() {
+        return Collections.unmodifiableList(history);
+    }
+
+    /**
+     * Returns the standard {@link AbstractCollection#toString} representation
+     * of the history list.
+     */
+    public String toString() {
+        return history.toString();
+    }
+
+    /**
+     * Moves the history index to the first entry.
+     *
+     * @return Return false if there are no entries in the history or if the
+     *         history is already at the beginning.
+     */
+    public boolean moveToFirstEntry() {
+        if (history.size() > 0 && currentIndex != 0) {
+            currentIndex = 0;
+            return true;
+        }
+
+        return false;
+    }
+}
diff --git a/src/jline/src/main/java/jline/MultiCompletor.java b/src/jline/src/main/java/jline/MultiCompletor.java
new file mode 100644
index 0000000..2d43a20
--- /dev/null
+++ b/src/jline/src/main/java/jline/MultiCompletor.java
@@ -0,0 +1,83 @@
+/*
+ * Copyright (c) 2002-2007, Marc Prud'hommeaux. All rights reserved.
+ *
+ * This software is distributable under the BSD license. See the terms of the
+ * BSD license in the documentation provided with this software.
+ */
+package jline;
+
+import java.util.*;
+
+/**
+ *  <p>
+ *  A completor that contains multiple embedded completors. This differs
+ *  from the {@link ArgumentCompletor}, in that the nested completors
+ *  are dispatched individually, rather than delimited by arguments.
+ *  </p>
+ *
+ *  @author  <a href="mailto:mwp1 at cornell.edu">Marc Prud'hommeaux</a>
+ */
+public class MultiCompletor implements Completor {
+    Completor[] completors = new Completor[0];
+
+    /**
+     *  Construct a MultiCompletor with no embedded completors.
+     */
+    public MultiCompletor() {
+        this(new Completor[0]);
+    }
+
+    /**
+     *  Construct a MultiCompletor with the specified list of
+     *  {@link Completor} instances.
+     */
+    public MultiCompletor(final List<Completor> completors) {
+        this((Completor[]) completors.toArray(new Completor[completors.size()]));
+    }
+
+    /**
+     *  Construct a MultiCompletor with the specified
+     *  {@link Completor} instances.
+     */
+    public MultiCompletor(final Completor[] completors) {
+        this.completors = completors;
+    }
+
+    public int complete(final String buffer, final int pos, final List<String> cand) {
+        int[] positions = new int[completors.length];
+        List<List<String>> copies = new ArrayList<List<String>>();
+        for (int i = 0; i < completors.length; i++) {
+            copies.add(null);
+        }
+
+        for (int i = 0; i < completors.length; i++) {
+            // clone and save the candidate list
+            copies.set(i, new LinkedList<String>(cand));
+            positions[i] = completors[i].complete(buffer, pos, copies.get(i));
+        }
+
+        int maxposition = -1;
+
+        for (int i = 0; i < positions.length; i++) {
+            maxposition = Math.max(maxposition, positions[i]);
+        }
+
+        // now we have the max cursor value: build up all the
+        // candidate lists that have the same cursor value
+        for (int i = 0; i < copies.size(); i++) {
+            if (positions[i] == maxposition) {
+                cand.addAll(copies.get(i));
+            }
+        }
+
+        return maxposition;
+    }
+
+    public void setCompletors(final Completor[] completors) {
+        this.completors = completors;
+    }
+
+    public Completor[] getCompletors() {
+        return this.completors;
+    }
+}
diff --git a/src/jline/src/main/java/jline/NullCompletor.java b/src/jline/src/main/java/jline/NullCompletor.java
new file mode 100644
index 0000000..aa6cdf7
--- /dev/null
+++ b/src/jline/src/main/java/jline/NullCompletor.java
@@ -0,0 +1,27 @@
+/*
+ * Copyright (c) 2002-2007, Marc Prud'hommeaux. All rights reserved.
+ *
+ * This software is distributable under the BSD license. See the terms of the
+ * BSD license in the documentation provided with this software.
+ */
+package jline;
+
+import java.util.*;
+
+/**
+ *  <p>
+ *  A completor that does nothing. Useful as the last item in an
+ *  {@link ArgumentCompletor}.
+ *  </p>
+ *
+ *  @author  <a href="mailto:mwp1 at cornell.edu">Marc Prud'hommeaux</a>
+ */
+public class NullCompletor implements Completor {
+    /**
+     *  Returns -1 always, indicating that the the buffer is never
+     *  handled.
+     */
+    public int complete(final String buffer, int cursor, List candidates) {
+        return -1;
+    }
+}
diff --git a/src/jline/src/main/java/jline/SimpleCompletor.java b/src/jline/src/main/java/jline/SimpleCompletor.java
new file mode 100644
index 0000000..3581277
--- /dev/null
+++ b/src/jline/src/main/java/jline/SimpleCompletor.java
@@ -0,0 +1,194 @@
+/*
+ * Copyright (c) 2002-2007, Marc Prud'hommeaux. All rights reserved.
+ *
+ * This software is distributable under the BSD license. See the terms of the
+ * BSD license in the documentation provided with this software.
+ */
+package jline;
+
+import java.io.*;
+import java.util.*;
+
+/**
+ *  <p>
+ *  A simple {@link Completor} implementation that handles a pre-defined
+ *  list of completion words.
+ *  </p>
+ *
+ *  <p>
+ *  Example usage:
+ *  </p>
+ *  <pre>
+ *  myConsoleReader.addCompletor (new SimpleCompletor (new String [] { "now", "yesterday", "tomorrow" }));
+ *  </pre>
+ *
+ *  @author  <a href="mailto:mwp1 at cornell.edu">Marc Prud'hommeaux</a>
+ */
+public class SimpleCompletor implements Completor, Cloneable {
+    /**
+     *  The list of candidates that will be completed.
+     */
+    SortedSet<String> candidates;
+
+    /**
+     *  A delimiter to use to qualify completions.
+     */
+    String delimiter;
+    final SimpleCompletorFilter filter;
+
+    /**
+     *  Create a new SimpleCompletor with a single possible completion
+     *  values.
+     */
+    public SimpleCompletor(final String candidateString) {
+        this(new String[] {
+                 candidateString
+             });
+    }
+
+    /**
+     *  Create a new SimpleCompletor with a list of possible completion
+     *  values.
+     */
+    public SimpleCompletor(final String[] candidateStrings) {
+        this(candidateStrings, null);
+    }
+
+    public SimpleCompletor(final String[] strings,
+                           final SimpleCompletorFilter filter) {
+        this.filter = filter;
+        setCandidateStrings(strings);
+    }
+
+    /**
+     *  Complete candidates using the contents of the specified Reader.
+     */
+    public SimpleCompletor(final Reader reader) throws IOException {
+        this(getStrings(reader));
+    }
+
+    /**
+     *  Complete candidates using the whitespearated values in
+     *  read from the specified Reader.
+     */
+    public SimpleCompletor(final InputStream in) throws IOException {
+        this(getStrings(new InputStreamReader(in)));
+    }
+
+    private static String[] getStrings(final Reader in)
+                                throws IOException {
+        final Reader reader =
+            (in instanceof BufferedReader) ? in : new BufferedReader(in);
+
+        List<String> words = new LinkedList<String>();
+        String line;
+
+        while ((line = ((BufferedReader) reader).readLine()) != null) {
+            for (StringTokenizer tok = new StringTokenizer(line);
+                     tok.hasMoreTokens(); words.add(tok.nextToken())) {
+                ;
+            }
+        }
+
+        return (String[]) words.toArray(new String[words.size()]);
+    }
+
+    public int complete(final String buffer, final int cursor, final List<String> clist) {
+        String start = (buffer == null) ? "" : buffer;
+
+        SortedSet<String> matches = candidates.tailSet(start);
+
+        for (Iterator i = matches.iterator(); i.hasNext();) {
+            String can = (String) i.next();
+
+            if (!(can.startsWith(start))) {
+                break;
+            }
+
+            if (delimiter != null) {
+                int index = can.indexOf(delimiter, cursor);
+
+                if (index != -1) {
+                    can = can.substring(0, index + 1);
+                }
+            }
+
+            clist.add(can);
+        }
+
+        if (clist.size() == 1) {
+            clist.set(0, ((String) clist.get(0)) + " ");
+        }
+
+        // the index of the completion is always from the beginning of
+        // the buffer.
+        return (clist.size() == 0) ? (-1) : 0;
+    }
+
+    public void setDelimiter(final String delimiter) {
+        this.delimiter = delimiter;
+    }
+
+    public String getDelimiter() {
+        return this.delimiter;
+    }
+
+    public void setCandidates(final SortedSet<String> candidates) {
+        if (filter != null) {
+            TreeSet<String> filtered = new TreeSet<String>();
+
+            for (Iterator i = candidates.iterator(); i.hasNext();) {
+                String element = (String) i.next();
+                element = filter.filter(element);
+
+                if (element != null) {
+                    filtered.add(element);
+                }
+            }
+
+            this.candidates = filtered;
+        } else {
+            this.candidates = candidates;
+        }
+    }
+
+    public SortedSet getCandidates() {
+        return Collections.unmodifiableSortedSet(this.candidates);
+    }
+
+    public void setCandidateStrings(final String[] strings) {
+        setCandidates(new TreeSet<String>(Arrays.asList(strings)));
+    }
+
+    public void addCandidateString(final String candidateString) {
+        final String string =
+            (filter == null) ? candidateString : filter.filter(candidateString);
+
+        if (string != null) {
+            candidates.add(string);
+        }
+    }
+
+    public Object clone() throws CloneNotSupportedException {
+        return super.clone();
+    }
+
+    /**
+     *  Filter for elements in the completor.
+     *
+     *  @author  <a href="mailto:mwp1 at cornell.edu">Marc Prud'hommeaux</a>
+     */
+    public static interface SimpleCompletorFilter {
+        /**
+         *  Filter the specified String. To not filter it, return the
+         *  same String as the parameter. To exclude it, return null.
+         */
+        public String filter(String element);
+    }
+
+    public static class NoOpFilter implements SimpleCompletorFilter {
+        public String filter(final String element) {
+            return element;
+        }
+    }
+}
diff --git a/src/jline/src/main/java/jline/Terminal.java b/src/jline/src/main/java/jline/Terminal.java
new file mode 100644
index 0000000..9f268b3
--- /dev/null
+++ b/src/jline/src/main/java/jline/Terminal.java
@@ -0,0 +1,180 @@
+/*
+ * Copyright (c) 2002-2007, Marc Prud'hommeaux. All rights reserved.
+ *
+ * This software is distributable under the BSD license. See the terms of the
+ * BSD license in the documentation provided with this software.
+ */
+package jline;
+
+import java.io.*;
+
+/**
+ *  Representation of the input terminal for a platform. Handles
+ *  any initialization that the platform may need to perform
+ *  in order to allow the {@link ConsoleReader} to correctly handle
+ *  input.
+ *
+ *  @author  <a href="mailto:mwp1 at cornell.edu">Marc Prud'hommeaux</a>
+ */
+public abstract class Terminal implements ConsoleOperations {
+    private static Terminal term;
+
+    /**
+     *  @see #setupTerminal
+     */
+    public static Terminal getTerminal() {
+        return setupTerminal();
+    }
+
+    /** 
+     *  Reset the current terminal to null. 
+     */
+    public static void resetTerminal() {
+        term = null;
+    }
+
+    /**
+     *  <p>Configure and return the {@link Terminal} instance for the
+     *  current platform. This will initialize any system settings
+     *  that are required for the console to be able to handle
+     *  input correctly, such as setting tabtop, buffered input, and
+     *  character echo.</p>
+     *
+     *  <p>This class will use the Terminal implementation specified in the
+     *  <em>jline.terminal</em> system property, or, if it is unset, by
+     *  detecting the operating system from the <em>os.name</em>
+     *  system property and instantiating either the
+     *  {@link WindowsTerminalTest} or {@link UnixTerminal}.
+     *
+     *  @see #initializeTerminal
+     */
+    public static synchronized Terminal setupTerminal() {
+        if (term != null) {
+            return term;
+        }
+
+        final Terminal t;
+
+        String os = System.getProperty("os.name").toLowerCase();
+        String termProp = System.getProperty("jline.terminal");
+
+        if ((termProp != null) && (termProp.length() > 0)) {
+            try {
+                t = (Terminal) Class.forName(termProp).newInstance();
+            } catch (Exception e) {
+                throw (IllegalArgumentException) new IllegalArgumentException(e
+                    .toString()).fillInStackTrace();
+            }
+        } else if (os.indexOf("windows") != -1) {
+            t = new WindowsTerminal();
+        } else {
+            t = new UnixTerminal();
+        }
+
+        try {
+            t.initializeTerminal();
+        } catch (Exception e) {
+            e.printStackTrace();
+
+            return term = new UnsupportedTerminal();
+        }
+
+        return term = t;
+    }
+
+    /**
+     *  Returns true if the current console supports ANSI
+     *  codes.
+     */
+    public boolean isANSISupported() {
+        return true;
+    }
+
+    /**
+     *  Read a single character from the input stream. This might
+     *  enable a terminal implementation to better handle nuances of
+     *  the console.
+     */
+    public int readCharacter(final InputStream in) throws IOException {
+        return in.read();
+    }
+
+    /**
+     *  Reads a virtual key from the console. Typically, this will
+     *  just be the raw character that was entered, but in some cases,
+     *  multiple input keys will need to be translated into a single
+     *  virtual key.
+     *
+     *  @param  in  the InputStream to read from
+     *  @return  the virtual key (e.g., {@link ConsoleOperations#VK_UP})
+     */
+    public int readVirtualKey(InputStream in) throws IOException {
+        return readCharacter(in);
+    }
+
+    /**
+     *  Initialize any system settings
+     *  that are required for the console to be able to handle
+     *  input correctly, such as setting tabtop, buffered input, and
+     *  character echo.
+     */
+    public abstract void initializeTerminal() throws Exception;
+
+    /**
+     *  Returns the current width of the terminal (in characters)
+     */
+    public abstract int getTerminalWidth();
+
+    /**
+     *  Returns the current height of the terminal (in lines)
+     */
+    public abstract int getTerminalHeight();
+
+    /**
+     *  Returns true if this terminal is capable of initializing the
+     *  terminal to use jline.
+     */
+    public abstract boolean isSupported();
+
+    /**
+     *  Returns true if the terminal will echo all characters type.
+     */
+    public abstract boolean getEcho();
+
+    /**
+     *  Invokes before the console reads a line with the prompt and mask.
+     */
+    public void beforeReadLine(ConsoleReader reader, String prompt,
+                               Character mask) {
+    }
+
+    /**
+     *  Invokes after the console reads a line with the prompt and mask.
+     */
+    public void afterReadLine(ConsoleReader reader, String prompt,
+                              Character mask) {
+    }
+
+    /**
+     *  Returns false if character echoing is disabled.
+     */
+    public abstract boolean isEchoEnabled();
+
+
+    /**
+     *  Enable character echoing. This can be used to re-enable character
+     *  if the ConsoleReader is no longer being used.
+     */
+    public abstract void enableEcho();
+
+
+    /**
+     *  Disable character echoing. This can be used to manually re-enable
+     *  character if the ConsoleReader has been disabled.
+     */
+    public abstract void disableEcho();
+
+    public InputStream getDefaultBindings() {
+        return Terminal.class.getResourceAsStream("keybindings.properties");
+    }
+}
diff --git a/src/jline/src/main/java/jline/UnixTerminal.java b/src/jline/src/main/java/jline/UnixTerminal.java
new file mode 100644
index 0000000..a80aec5
--- /dev/null
+++ b/src/jline/src/main/java/jline/UnixTerminal.java
@@ -0,0 +1,431 @@
+/*
+ * Copyright (c) 2002-2007, Marc Prud'hommeaux. All rights reserved.
+ *
+ * This software is distributable under the BSD license. See the terms of the
+ * BSD license in the documentation provided with this software.
+ */
+package jline;
+
+import java.io.*;
+import java.util.*;
+
+/**
+ *  <p>
+ *  Terminal that is used for unix platforms. Terminal initialization
+ *  is handled by issuing the <em>stty</em> command against the
+ *  <em>/dev/tty</em> file to disable character echoing and enable
+ *  character input. All known unix systems (including
+ *  Linux and Macintosh OS X) support the <em>stty</em>), so this
+ *  implementation should work for an reasonable POSIX system.
+ *        </p>
+ *
+ *  @author  <a href="mailto:mwp1 at cornell.edu">Marc Prud'hommeaux</a>
+ *  @author  Updates <a href="mailto:dwkemp at gmail.com">Dale Kemp</a> 2005-12-03
+ */
+public class UnixTerminal extends Terminal {
+    public static final short ARROW_START = 27;
+    public static final short ARROW_PREFIX = 91;
+    public static final short ARROW_LEFT = 68;
+    public static final short ARROW_RIGHT = 67;
+    public static final short ARROW_UP = 65;
+    public static final short ARROW_DOWN = 66;
+    public static final short O_PREFIX = 79;
+    public static final short HOME_CODE = 72;
+    public static final short END_CODE = 70;
+
+    public static final short DEL_THIRD = 51;
+    public static final short DEL_SECOND = 126;
+
+    private boolean echoEnabled;
+    private String ttyConfig;
+    private boolean backspaceDeleteSwitched = false;
+    private static String sttyCommand =
+        System.getProperty("jline.sttyCommand", "stty");
+
+    
+    String encoding = System.getProperty("jline.UnixTerminal.input.encoding", "UTF-8");
+    ReplayPrefixOneCharInputStream replayStream = new ReplayPrefixOneCharInputStream(encoding);
+    InputStreamReader replayReader;
+
+    public UnixTerminal() {
+        try {
+            replayReader = new InputStreamReader(replayStream, encoding);
+        } catch (Exception e) {
+            throw new RuntimeException(e);
+        }
+    }
+   
+    protected void checkBackspace(){
+        String[] ttyConfigSplit = ttyConfig.split(":|=");
+        String eof;
+
+        if ("gfmt1".equals(ttyConfigSplit[0]) && ttyConfigSplit.length > 20) {
+            // BSD style -g
+            eof = ttyConfigSplit[20];
+        } else if (ttyConfigSplit.length > 6 && ttyConfigSplit[6] != null) {
+            eof = ttyConfigSplit[6];
+        } else {
+            return;
+        }
+	
+        backspaceDeleteSwitched = eof.equals("7f");
+    }
+    
+    /**
+     *  Remove line-buffered input by invoking "stty -icanon min 1"
+     *  against the current terminal.
+     */
+    public void initializeTerminal() throws IOException, InterruptedException {
+        // save the initial tty configuration
+        ttyConfig = stty("-g");
+
+        // sanity check
+        if ((ttyConfig.length() == 0)
+                || ((ttyConfig.indexOf("=") == -1)
+                       && (ttyConfig.indexOf(":") == -1))) {
+            throw new IOException("Unrecognized stty code: " + ttyConfig);
+        }
+
+        checkBackspace();
+
+        // set the console to be character-buffered instead of line-buffered
+        stty("-icanon min 1");
+
+        // disable character echoing
+        stty("-echo");
+        echoEnabled = false;
+
+        // at exit, restore the original tty configuration (for JDK 1.3+)
+        try {
+            Runtime.getRuntime().addShutdownHook(new Thread() {
+                    public void start() {
+                        try {
+                            restoreTerminal();
+                        } catch (Exception e) {
+                            consumeException(e);
+                        }
+                    }
+                });
+        } catch (AbstractMethodError ame) {
+            // JDK 1.3+ only method. Bummer.
+            consumeException(ame);
+        }
+    }
+
+    /** 
+     * Restore the original terminal configuration, which can be used when
+     * shutting down the console reader. The ConsoleReader cannot be
+     * used after calling this method.
+     */
+    public void restoreTerminal() throws Exception {
+        if (ttyConfig != null) {
+            stty(ttyConfig);
+            ttyConfig = null;
+        }
+        resetTerminal();
+    }
+
+    
+    
+    public int readVirtualKey(InputStream in) throws IOException {
+        int c = readCharacter(in);
+
+        if (backspaceDeleteSwitched)
+            if (c == DELETE)
+                c = '\b';
+            else if (c == '\b')
+                c = DELETE;
+
+        // in Unix terminals, arrow keys are represented by
+        // a sequence of 3 characters. E.g., the up arrow
+        // key yields 27, 91, 68
+        if (c == ARROW_START) {
+		//also the escape key is 27
+		//thats why we read until we
+		//have something different than 27
+		//this is a bugfix, because otherwise
+		//pressing escape and than an arrow key
+		//was an undefined state
+		while (c == ARROW_START)
+            		c = readCharacter(in);
+            if (c == ARROW_PREFIX || c == O_PREFIX) {
+                c = readCharacter(in);
+                if (c == ARROW_UP) {
+                    return CTRL_P;
+                } else if (c == ARROW_DOWN) {
+                    return CTRL_N;
+                } else if (c == ARROW_LEFT) {
+                    return CTRL_B;
+                } else if (c == ARROW_RIGHT) {
+                    return CTRL_F;
+                } else if (c == HOME_CODE) {
+                    return CTRL_A;
+                } else if (c == END_CODE) {
+                    return CTRL_E;
+                } else if (c == DEL_THIRD) {
+                    c = readCharacter(in); // read 4th
+                    return DELETE;
+                }
+            } 
+        } 
+        // handle unicode characters, thanks for a patch from amyi at inf.ed.ac.uk
+        if (c > 128) {
+          // handle unicode characters longer than 2 bytes,
+          // thanks to Marc.Herbert at continuent.com
+            replayStream.setInput(c, in);
+//            replayReader = new InputStreamReader(replayStream, encoding);
+            c = replayReader.read();
+            
+        }
+
+        return c;
+    }
+
+    /**
+     *  No-op for exceptions we want to silently consume.
+     */
+    private void consumeException(Throwable e) {
+    }
+
+    public boolean isSupported() {
+        return true;
+    }
+
+    public boolean getEcho() {
+        return false;
+    }
+
+    /**
+     *  Returns the value of "stty size" width param.
+     *
+     *  <strong>Note</strong>: this method caches the value from the
+     *  first time it is called in order to increase speed, which means
+     *  that changing to size of the terminal will not be reflected
+     *  in the console.
+     */
+    public int getTerminalWidth() {
+        int val = -1;
+
+        try {
+            val = getTerminalProperty("columns");
+        } catch (Exception e) {
+        }
+
+        if (val == -1) {
+            val = 80;
+        }
+
+        return val;
+    }
+
+    /**
+     *  Returns the value of "stty size" height param.
+     *
+     *  <strong>Note</strong>: this method caches the value from the
+     *  first time it is called in order to increase speed, which means
+     *  that changing to size of the terminal will not be reflected
+     *  in the console.
+     */
+    public int getTerminalHeight() {
+        int val = -1;
+
+        try {
+            val = getTerminalProperty("rows");
+        } catch (Exception e) {
+        }
+
+        if (val == -1) {
+            val = 24;
+        }
+
+        return val;
+    }
+
+    private static int getTerminalProperty(String prop)
+                                    throws IOException, InterruptedException {
+        // need to be able handle both output formats:
+        // speed 9600 baud; 24 rows; 140 columns;
+        // and:
+        // speed 38400 baud; rows = 49; columns = 111; ypixels = 0; xpixels = 0;
+        String props = stty("-a");
+
+        for (StringTokenizer tok = new StringTokenizer(props, ";\n");
+                 tok.hasMoreTokens();) {
+            String str = tok.nextToken().trim();
+
+            if (str.startsWith(prop)) {
+                int index = str.lastIndexOf(" ");
+
+                return Integer.parseInt(str.substring(index).trim());
+            } else if (str.endsWith(prop)) {
+                int index = str.indexOf(" ");
+
+                return Integer.parseInt(str.substring(0, index).trim());
+            }
+        }
+
+        return -1;
+    }
+
+    /**
+     *  Execute the stty command with the specified arguments
+     *  against the current active terminal.
+     */
+    private static String stty(final String args)
+                        throws IOException, InterruptedException {
+        return exec("stty " + args + " < /dev/tty").trim();
+    }
+
+    /**
+     *  Execute the specified command and return the output
+     *  (both stdout and stderr).
+     */
+    private static String exec(final String cmd)
+                        throws IOException, InterruptedException {
+        return exec(new String[] {
+                        "sh",
+                        "-c",
+                        cmd
+                    });
+    }
+
+    /**
+     *  Execute the specified command and return the output
+     *  (both stdout and stderr).
+     */
+    private static String exec(final String[] cmd)
+                        throws IOException, InterruptedException {
+        ByteArrayOutputStream bout = new ByteArrayOutputStream();
+
+        Process p = Runtime.getRuntime().exec(cmd);
+        int c;
+        InputStream in;
+
+        in = p.getInputStream();
+
+        while ((c = in.read()) != -1) {
+            bout.write(c);
+        }
+
+        in = p.getErrorStream();
+
+        while ((c = in.read()) != -1) {
+            bout.write(c);
+        }
+
+        p.waitFor();
+
+        String result = new String(bout.toByteArray());
+
+        return result;
+    }
+
+    /**
+     *  The command to use to set the terminal options. Defaults
+     *  to "stty", or the value of the system property "jline.sttyCommand".
+     */
+    public static void setSttyCommand(String cmd) {
+        sttyCommand = cmd;
+    }
+
+    /**
+     *  The command to use to set the terminal options. Defaults
+     *  to "stty", or the value of the system property "jline.sttyCommand".
+     */
+    public static String getSttyCommand() {
+        return sttyCommand;
+    }
+
+    public synchronized boolean isEchoEnabled() {
+        return echoEnabled;
+    }
+
+
+    public synchronized void enableEcho() {
+    	try {
+			stty("echo");
+            echoEnabled = true;
+		} catch (Exception e) {
+			consumeException(e);
+		}
+    }
+
+    public synchronized void disableEcho() {
+    	try {
+			stty("-echo");
+            echoEnabled = false;
+		} catch (Exception e) {
+			consumeException(e);
+		}
+    }
+
+    /**
+     * This is awkward and inefficient, but probably the minimal way to add
+     * UTF-8 support to JLine
+     *
+     * @author <a href="mailto:Marc.Herbert at continuent.com">Marc Herbert</a>
+     */
+    static class ReplayPrefixOneCharInputStream extends InputStream {
+        byte firstByte;
+        int byteLength;
+        InputStream wrappedStream;
+        int byteRead;
+
+        final String encoding;
+        
+        public ReplayPrefixOneCharInputStream(String encoding) {
+            this.encoding = encoding;
+        }
+        
+        public void setInput(int recorded, InputStream wrapped) throws IOException {
+            this.byteRead = 0;
+            this.firstByte = (byte) recorded;
+            this.wrappedStream = wrapped;
+
+            byteLength = 1;
+            if (encoding.equalsIgnoreCase("UTF-8"))
+                setInputUTF8(recorded, wrapped);
+            else if (encoding.equalsIgnoreCase("UTF-16"))
+                byteLength = 2;
+            else if (encoding.equalsIgnoreCase("UTF-32"))
+                byteLength = 4;
+        }
+            
+            
+        public void setInputUTF8(int recorded, InputStream wrapped) throws IOException {
+            // 110yyyyy 10zzzzzz
+            if ((firstByte & (byte) 0xE0) == (byte) 0xC0)
+                this.byteLength = 2;
+            // 1110xxxx 10yyyyyy 10zzzzzz
+            else if ((firstByte & (byte) 0xF0) == (byte) 0xE0)
+                this.byteLength = 3;
+            // 11110www 10xxxxxx 10yyyyyy 10zzzzzz
+            else if ((firstByte & (byte) 0xF8) == (byte) 0xF0)
+                this.byteLength = 4;
+            else
+                throw new IOException("invalid UTF-8 first byte: " + firstByte);
+        }
+
+        public int read() throws IOException {
+            if (available() == 0)
+                return -1;
+
+            byteRead++;
+
+            if (byteRead == 1)
+                return firstByte;
+
+            return wrappedStream.read();
+        }
+
+        /**
+        * InputStreamReader is greedy and will try to read bytes in advance. We
+        * do NOT want this to happen since we use a temporary/"losing bytes"
+        * InputStreamReader above, that's why we hide the real
+        * wrappedStream.available() here.
+        */
+        public int available() {
+            return byteLength - byteRead;
+        }
+    }
+}
diff --git a/src/jline/src/main/java/jline/UnsupportedTerminal.java b/src/jline/src/main/java/jline/UnsupportedTerminal.java
new file mode 100644
index 0000000..2d87a18
--- /dev/null
+++ b/src/jline/src/main/java/jline/UnsupportedTerminal.java
@@ -0,0 +1,98 @@
+/*
+ * Copyright (c) 2002-2007, Marc Prud'hommeaux. All rights reserved.
+ *
+ * This software is distributable under the BSD license. See the terms of the
+ * BSD license in the documentation provided with this software.
+ */
+package jline;
+
+import java.io.IOException;
+
+/**
+ *  A no-op unsupported terminal.
+ *
+ *  @author  <a href="mailto:mwp1 at cornell.edu">Marc Prud'hommeaux</a>
+ */
+public class UnsupportedTerminal extends Terminal {
+    private Thread maskThread = null;
+
+    public void initializeTerminal() {
+        // nothing we need to do (or can do) for windows.
+    }
+
+    public boolean getEcho() {
+        return true;
+    }
+
+
+    public boolean isEchoEnabled() {
+        return true;
+    }
+
+
+    public void enableEcho() {
+    }
+
+
+    public void disableEcho() {
+    }
+
+
+    /**
+     *  Always returng 80, since we can't access this info on Windows.
+     */
+    public int getTerminalWidth() {
+        return 80;
+    }
+
+    /**
+     *  Always returng 24, since we can't access this info on Windows.
+     */
+    public int getTerminalHeight() {
+        return 80;
+    }
+
+    public boolean isSupported() {
+        return false;
+    }
+
+    public void beforeReadLine(final ConsoleReader reader, final String prompt,
+       final Character mask) {
+        if ((mask != null) && (maskThread == null)) {
+            final String fullPrompt = "\r" + prompt
+                + "                 "
+                + "                 "
+                + "                 "
+                + "\r" + prompt;
+
+            maskThread = new Thread("JLine Mask Thread") {
+                public void run() {
+                    while (!interrupted()) {
+                        try {
+                            reader.out.write(fullPrompt);
+                            reader.out.flush();
+                            sleep(3);
+                        } catch (IOException ioe) {
+                            return;
+                        } catch (InterruptedException ie) {
+                            return;
+                        }
+                    }
+                }
+            };
+
+            maskThread.setPriority(Thread.MAX_PRIORITY);
+            maskThread.setDaemon(true);
+            maskThread.start();
+        }
+    }
+
+    public void afterReadLine(final ConsoleReader reader, final String prompt,
+        final Character mask) {
+        if ((maskThread != null) && maskThread.isAlive()) {
+            maskThread.interrupt();
+        }
+
+        maskThread = null;
+    }
+}
diff --git a/src/jline/src/main/java/jline/WindowsTerminal.java b/src/jline/src/main/java/jline/WindowsTerminal.java
new file mode 100644
index 0000000..6f30afb
--- /dev/null
+++ b/src/jline/src/main/java/jline/WindowsTerminal.java
@@ -0,0 +1,513 @@
+/*
+ * Copyright (c) 2002-2007, Marc Prud'hommeaux. All rights reserved.
+ *
+ * This software is distributable under the BSD license. See the terms of the
+ * BSD license in the documentation provided with this software.
+ */
+package jline;
+
+import java.io.*;
+
+import jline.UnixTerminal.ReplayPrefixOneCharInputStream;
+
+/**
+ * <p>
+ * Terminal implementation for Microsoft Windows. Terminal initialization in
+ * {@link #initializeTerminal} is accomplished by extracting the
+ * <em>jline_<i>version</i>.dll</em>, saving it to the system temporary
+ * directoy (determined by the setting of the <em>java.io.tmpdir</em> System
+ * property), loading the library, and then calling the Win32 APIs <a
+ * href="http://msdn.microsoft.com/library/default.asp?
+ * url=/library/en-us/dllproc/base/setconsolemode.asp">SetConsoleMode</a> and
+ * <a href="http://msdn.microsoft.com/library/default.asp?
+ * url=/library/en-us/dllproc/base/getconsolemode.asp">GetConsoleMode</a> to
+ * disable character echoing.
+ * </p>
+ *
+ * <p>
+ * By default, the {@link #readCharacter} method will attempt to test to see if
+ * the specified {@link InputStream} is {@link System#in} or a wrapper around
+ * {@link FileDescriptor#in}, and if so, will bypass the character reading to
+ * directly invoke the readc() method in the JNI library. This is so the class
+ * can read special keys (like arrow keys) which are otherwise inaccessible via
+ * the {@link System#in} stream. Using JNI reading can be bypassed by setting
+ * the <code>jline.WindowsTerminal.disableDirectConsole</code> system property
+ * to <code>true</code>.
+ * </p>
+ *
+ * @author <a href="mailto:mwp1 at cornell.edu">Marc Prud'hommeaux</a>
+ */
+public class WindowsTerminal extends Terminal {
+    // constants copied from wincon.h
+
+    /**
+     * The ReadFile or ReadConsole function returns only when a carriage return
+     * character is read. If this mode is disable, the functions return when one
+     * or more characters are available.
+     */
+    private static final int ENABLE_LINE_INPUT = 2;
+
+    /**
+     * Characters read by the ReadFile or ReadConsole function are written to
+     * the active screen buffer as they are read. This mode can be used only if
+     * the ENABLE_LINE_INPUT mode is also enabled.
+     */
+    private static final int ENABLE_ECHO_INPUT = 4;
+
+    /**
+     * CTRL+C is processed by the system and is not placed in the input buffer.
+     * If the input buffer is being read by ReadFile or ReadConsole, other
+     * control keys are processed by the system and are not returned in the
+     * ReadFile or ReadConsole buffer. If the ENABLE_LINE_INPUT mode is also
+     * enabled, backspace, carriage return, and linefeed characters are handled
+     * by the system.
+     */
+    private static final int ENABLE_PROCESSED_INPUT = 1;
+
+    /**
+     * User interactions that change the size of the console screen buffer are
+     * reported in the console's input buffee. Information about these events
+     * can be read from the input buffer by applications using
+     * theReadConsoleInput function, but not by those using ReadFile
+     * orReadConsole.
+     */
+    private static final int ENABLE_WINDOW_INPUT = 8;
+
+    /**
+     * If the mouse pointer is within the borders of the console window and the
+     * window has the keyboard focus, mouse events generated by mouse movement
+     * and button presses are placed in the input buffer. These events are
+     * discarded by ReadFile or ReadConsole, even when this mode is enabled.
+     */
+    private static final int ENABLE_MOUSE_INPUT = 16;
+
+    /**
+     * When enabled, text entered in a console window will be inserted at the
+     * current cursor location and all text following that location will not be
+     * overwritten. When disabled, all following text will be overwritten. An OR
+     * operation must be performed with this flag and the ENABLE_EXTENDED_FLAGS
+     * flag to enable this functionality.
+     */
+    private static final int ENABLE_PROCESSED_OUTPUT = 1;
+
+    /**
+     * This flag enables the user to use the mouse to select and edit text. To
+     * enable this option, use the OR to combine this flag with
+     * ENABLE_EXTENDED_FLAGS.
+     */
+    private static final int ENABLE_WRAP_AT_EOL_OUTPUT = 2;
+
+    /**
+     * On windows terminals, this character indicates that a 'special' key has
+     * been pressed. This means that a key such as an arrow key, or delete, or
+     * home, etc. will be indicated by the next character.
+     */
+    public static final int SPECIAL_KEY_INDICATOR = 224;
+
+    /**
+     * On windows terminals, this character indicates that a special key on the
+     * number pad has been pressed.
+     */
+    public static final int NUMPAD_KEY_INDICATOR = 0;
+
+    /**
+     * When following the SPECIAL_KEY_INDICATOR or NUMPAD_KEY_INDICATOR,
+     * this character indicates an left arrow key press.
+     */
+    public static final int LEFT_ARROW_KEY = 75;
+
+    /**
+     * When following the SPECIAL_KEY_INDICATOR or NUMPAD_KEY_INDICATOR
+     * this character indicates an
+     * right arrow key press.
+     */
+    public static final int RIGHT_ARROW_KEY = 77;
+
+    /**
+     * When following the SPECIAL_KEY_INDICATOR or NUMPAD_KEY_INDICATOR
+     * this character indicates an up
+     * arrow key press.
+     */
+    public static final int UP_ARROW_KEY = 72;
+
+    /**
+     * When following the SPECIAL_KEY_INDICATOR or NUMPAD_KEY_INDICATOR
+     * this character indicates an
+     * down arrow key press.
+     */
+    public static final int DOWN_ARROW_KEY = 80;
+
+    /**
+     * When following the SPECIAL_KEY_INDICATOR or NUMPAD_KEY_INDICATOR
+     * this character indicates that
+     * the delete key was pressed.
+     */
+    public static final int DELETE_KEY = 83;
+
+    /**
+     * When following the SPECIAL_KEY_INDICATOR or NUMPAD_KEY_INDICATOR
+     * this character indicates that
+     * the home key was pressed.
+     */
+    public static final int HOME_KEY = 71;
+
+    /**
+     * When following the SPECIAL_KEY_INDICATOR or NUMPAD_KEY_INDICATOR
+     * this character indicates that
+     * the end key was pressed.
+     */
+    public static final char END_KEY = 79;
+
+    /**
+     * When following the SPECIAL_KEY_INDICATOR or NUMPAD_KEY_INDICATOR
+     * this character indicates that
+     * the page up key was pressed.
+     */
+    public static final char PAGE_UP_KEY = 73;
+
+    /**
+     * When following the SPECIAL_KEY_INDICATOR or NUMPAD_KEY_INDICATOR
+     * this character indicates that
+     * the page down key was pressed.
+     */
+    public static final char PAGE_DOWN_KEY = 81;
+
+    /**
+     * When following the SPECIAL_KEY_INDICATOR or NUMPAD_KEY_INDICATOR
+     * this character indicates that
+     * the insert key was pressed.
+     */
+    public static final char INSERT_KEY = 82;
+
+    /**
+     * When following the SPECIAL_KEY_INDICATOR or NUMPAD_KEY_INDICATOR,
+     * this character indicates that the escape key was pressed.
+     */
+    public static final char ESCAPE_KEY = 0;
+
+    private Boolean directConsole;
+
+    private boolean echoEnabled;
+    
+    String encoding = System.getProperty("jline.WindowsTerminal.input.encoding", System.getProperty("file.encoding"));
+    ReplayPrefixOneCharInputStream replayStream = new ReplayPrefixOneCharInputStream(encoding);
+    InputStreamReader replayReader;
+    
+    public WindowsTerminal() {
+        String dir = System.getProperty("jline.WindowsTerminal.directConsole");
+
+        if ("true".equals(dir)) {
+            directConsole = Boolean.TRUE;
+        } else if ("false".equals(dir)) {
+            directConsole = Boolean.FALSE;
+        }
+        
+        try {
+            replayReader = new InputStreamReader(replayStream, encoding);
+        } catch (Exception e) {
+            throw new RuntimeException(e);
+        }
+        
+    }
+
+    private native int getConsoleMode();
+
+    private native void setConsoleMode(final int mode);
+
+    private native int readByte();
+
+    private native int getWindowsTerminalWidth();
+
+    private native int getWindowsTerminalHeight();
+
+    public int readCharacter(final InputStream in) throws IOException {
+        // if we can detect that we are directly wrapping the system
+        // input, then bypass the input stream and read directly (which
+        // allows us to access otherwise unreadable strokes, such as
+        // the arrow keys)
+        if (directConsole == Boolean.FALSE) {
+            return super.readCharacter(in);
+        } else if ((directConsole == Boolean.TRUE)
+            || ((in == System.in) || (in instanceof FileInputStream
+                && (((FileInputStream) in).getFD() == FileDescriptor.in)))) {
+            return readByte();
+        } else {
+            return super.readCharacter(in);
+        }
+    }
+
+    public void initializeTerminal() throws Exception {
+        loadLibrary("jline");
+
+        final int originalMode = getConsoleMode();
+
+        setConsoleMode(originalMode & ~ENABLE_ECHO_INPUT);
+
+        // set the console to raw mode
+        int newMode = originalMode
+            & ~(ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT
+                | ENABLE_PROCESSED_INPUT | ENABLE_WINDOW_INPUT);
+        echoEnabled = false;
+        setConsoleMode(newMode);
+
+        // at exit, restore the original tty configuration (for JDK 1.3+)
+        try {
+            Runtime.getRuntime().addShutdownHook(new Thread() {
+                public void start() {
+                    // restore the old console mode
+                    setConsoleMode(originalMode);
+                }
+            });
+        } catch (AbstractMethodError ame) {
+            // JDK 1.3+ only method. Bummer.
+            consumeException(ame);
+        }
+    }
+
+    private void loadLibrary(final String name) throws IOException {
+        // store the DLL in the temporary directory for the System
+        String version = getClass().getPackage().getImplementationVersion();
+
+        if (version == null) {
+            version = "";
+        }
+
+        version = version.replace('.', '_');
+
+        File f = new File(System.getProperty("java.io.tmpdir"), name + "_"
+                + version + ".dll");
+        boolean exists = f.isFile(); // check if it already exists
+
+        // extract the embedded jline.dll file from the jar and save
+        // it to the current directory
+        int bits = 32;
+
+        // check for 64-bit systems and use to appropriate DLL
+        if (System.getProperty("os.arch").indexOf("64") != -1)
+            bits = 64;
+
+        InputStream in = new BufferedInputStream(getClass()
+            .getResourceAsStream(name + bits + ".dll"));
+
+        try {
+            OutputStream fout = new BufferedOutputStream(
+                    new FileOutputStream(f));
+            byte[] bytes = new byte[1024 * 10];
+
+            for (int n = 0; n != -1; n = in.read(bytes)) {
+                fout.write(bytes, 0, n);
+            }
+
+            fout.close();
+        } catch (IOException ioe) {
+            // We might get an IOException trying to overwrite an existing
+            // jline.dll file if there is another process using the DLL.
+            // If this happens, ignore errors.
+            if (!exists) {
+                throw ioe;
+            }
+        }
+
+        // try to clean up the DLL after the JVM exits
+        f.deleteOnExit();
+
+        // now actually load the DLL
+        System.load(f.getAbsolutePath());
+    }
+
+    public int readVirtualKey(InputStream in) throws IOException {
+        int indicator = readCharacter(in);
+
+        // in Windows terminals, arrow keys are represented by
+        // a sequence of 2 characters. E.g., the up arrow
+        // key yields 224, 72
+        if (indicator == SPECIAL_KEY_INDICATOR
+                || indicator == NUMPAD_KEY_INDICATOR) {
+            int key = readCharacter(in);
+
+            switch (key) {
+            case UP_ARROW_KEY:
+                return CTRL_P; // translate UP -> CTRL-P
+            case LEFT_ARROW_KEY:
+                return CTRL_B; // translate LEFT -> CTRL-B
+            case RIGHT_ARROW_KEY:
+                return CTRL_F; // translate RIGHT -> CTRL-F
+            case DOWN_ARROW_KEY:
+                return CTRL_N; // translate DOWN -> CTRL-N
+            case DELETE_KEY:
+                return CTRL_QM; // translate DELETE -> CTRL-?
+            case HOME_KEY:
+                return CTRL_A;
+            case END_KEY:
+                return CTRL_E;
+            case PAGE_UP_KEY:
+                return CTRL_K;
+            case PAGE_DOWN_KEY:
+                return CTRL_L;
+            case ESCAPE_KEY:
+                return CTRL_OB; // translate ESCAPE -> CTRL-[
+            case INSERT_KEY:
+                return CTRL_C;
+            default:
+                return 0;
+            }
+        } else if (indicator > 128) {
+            	// handle unicode characters longer than 2 bytes,
+            	// thanks to Marc.Herbert at continuent.com
+                replayStream.setInput(indicator, in);
+                // replayReader = new InputStreamReader(replayStream, encoding);
+                indicator = replayReader.read();
+                
+        }
+        
+        return indicator;
+        
+	}
+
+    public boolean isSupported() {
+        return true;
+    }
+
+    /**
+     * Windows doesn't support ANSI codes by default; disable them.
+     */
+    public boolean isANSISupported() {
+        return false;
+    }
+
+    public boolean getEcho() {
+        return false;
+    }
+
+    /**
+     * Unsupported; return the default.
+     *
+     * @see Terminal#getTerminalWidth
+     */
+    public int getTerminalWidth() {
+        return getWindowsTerminalWidth();
+    }
+
+    /**
+     * Unsupported; return the default.
+     *
+     * @see Terminal#getTerminalHeight
+     */
+    public int getTerminalHeight() {
+        return getWindowsTerminalHeight();
+    }
+
+    /**
+     * No-op for exceptions we want to silently consume.
+     */
+    private void consumeException(final Throwable e) {
+    }
+
+    /**
+     * Whether or not to allow the use of the JNI console interaction.
+     */
+    public void setDirectConsole(Boolean directConsole) {
+        this.directConsole = directConsole;
+    }
+
+    /**
+     * Whether or not to allow the use of the JNI console interaction.
+     */
+    public Boolean getDirectConsole() {
+        return this.directConsole;
+    }
+
+    public synchronized boolean isEchoEnabled() {
+        return echoEnabled;
+    }
+
+    public synchronized void enableEcho() {
+        // Must set these four modes at the same time to make it work fine.
+        setConsoleMode(getConsoleMode() | ENABLE_ECHO_INPUT | ENABLE_LINE_INPUT
+            | ENABLE_PROCESSED_INPUT | ENABLE_WINDOW_INPUT);
+        echoEnabled = true;
+    }
+
+    public synchronized void disableEcho() {
+        // Must set these four modes at the same time to make it work fine.
+        setConsoleMode(getConsoleMode()
+            & ~(ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT
+                | ENABLE_PROCESSED_INPUT | ENABLE_WINDOW_INPUT));
+        echoEnabled = true;
+    }
+
+    public InputStream getDefaultBindings() {
+        return getClass().getResourceAsStream("windowsbindings.properties");
+    }
+    
+    /**
+     * This is awkward and inefficient, but probably the minimal way to add
+     * UTF-8 support to JLine
+     *
+     * @author <a href="mailto:Marc.Herbert at continuent.com">Marc Herbert</a>
+     */
+    static class ReplayPrefixOneCharInputStream extends InputStream {
+        byte firstByte;
+        int byteLength;
+        InputStream wrappedStream;
+        int byteRead;
+
+        final String encoding;
+        
+        public ReplayPrefixOneCharInputStream(String encoding) {
+            this.encoding = encoding;
+        }
+        
+        public void setInput(int recorded, InputStream wrapped) throws IOException {
+            this.byteRead = 0;
+            this.firstByte = (byte) recorded;
+            this.wrappedStream = wrapped;
+
+            byteLength = 1;
+            if (encoding.equalsIgnoreCase("UTF-8"))
+                setInputUTF8(recorded, wrapped);
+            else if (encoding.equalsIgnoreCase("UTF-16"))
+                byteLength = 2;
+            else if (encoding.equalsIgnoreCase("UTF-32"))
+                byteLength = 4;
+        }
+            
+            
+        public void setInputUTF8(int recorded, InputStream wrapped) throws IOException {
+            // 110yyyyy 10zzzzzz
+            if ((firstByte & (byte) 0xE0) == (byte) 0xC0)
+                this.byteLength = 2;
+            // 1110xxxx 10yyyyyy 10zzzzzz
+            else if ((firstByte & (byte) 0xF0) == (byte) 0xE0)
+                this.byteLength = 3;
+            // 11110www 10xxxxxx 10yyyyyy 10zzzzzz
+            else if ((firstByte & (byte) 0xF8) == (byte) 0xF0)
+                this.byteLength = 4;
+            else
+                throw new IOException("invalid UTF-8 first byte: " + firstByte);
+        }
+
+        public int read() throws IOException {
+            if (available() == 0)
+                return -1;
+
+            byteRead++;
+
+            if (byteRead == 1)
+                return firstByte;
+
+            return wrappedStream.read();
+        }
+
+        /**
+        * InputStreamReader is greedy and will try to read bytes in advance. We
+        * do NOT want this to happen since we use a temporary/"losing bytes"
+        * InputStreamReader above, that's why we hide the real
+        * wrappedStream.available() here.
+        */
+        public int available() {
+            return byteLength - byteRead;
+        }
+    }
+    
+}
diff --git a/src/jline/src/main/java/jline/package.html b/src/jline/src/main/java/jline/package.html
new file mode 100644
index 0000000..c807431
--- /dev/null
+++ b/src/jline/src/main/java/jline/package.html
@@ -0,0 +1,9 @@
+<body>
+<p>
+The core JLine API. The central class is
+<a href="ConsoleReader">jline.ConsoleReader</a>}, which
+is a reader for obtaining input from an arbitrary
+InputStream (usually <em>System.in</em>).
+</p>
+</body>
+
diff --git a/src/jline/src/main/native/Makefile b/src/jline/src/main/native/Makefile
new file mode 100644
index 0000000..c620814
--- /dev/null
+++ b/src/jline/src/main/native/Makefile
@@ -0,0 +1,8 @@
+
+
+#export PATH=${PATH}:/usr/lib/gcc-lib/i686-pc-cygwin/3.3.3
+JDK='/C/Program Files/Java/jdk1.5.0/'
+
+native:
+	#gcc -I'C:/Program Files/Java/'*'/include/' -I'C:/Program Files/Java/'*'/include//win32/' -mno-cygwin -Wl,--add-stdcall-alias -shared -o jline.dll jline_WindowsTerminal.c
+	gcc -L /usr/lib/mingw/ -I${JDK}/include -I${JDK}/include/win32 -mwindows -mno-cygwin -Wl,--add-stdcall-alias -shared -o jline.dll jline_WindowsTerminal.c
diff --git a/src/jline/src/main/native/jline_WindowsTerminal.c b/src/jline/src/main/native/jline_WindowsTerminal.c
new file mode 100644
index 0000000..f020cae
--- /dev/null
+++ b/src/jline/src/main/native/jline_WindowsTerminal.c
@@ -0,0 +1,57 @@
+#include "jline_WindowsTerminal.h"
+#include <windows.h>
+
+JNIEXPORT jint JNICALL Java_jline_WindowsTerminal_getConsoleMode
+  (JNIEnv *env, jobject ob)
+{
+	DWORD mode;
+	HANDLE hConsole = GetStdHandle (STD_INPUT_HANDLE);
+
+	if (hConsole == INVALID_HANDLE_VALUE)
+		return -1;
+
+	if (!GetConsoleMode (hConsole, &mode))
+		return -1;
+
+	// CloseHandle (hConsole);
+
+	// printf ("JNI get mode=%d\n", mode);
+	return mode;
+}
+
+JNIEXPORT void JNICALL Java_jline_WindowsTerminal_setConsoleMode
+  (JNIEnv *env, jobject ob, jint mode)
+{
+	DWORD m = (DWORD)mode;
+	HANDLE hConsole = GetStdHandle (STD_INPUT_HANDLE);
+
+	if (hConsole == INVALID_HANDLE_VALUE)
+		return;
+
+	// printf ("JNI set mode=%d\n", m);
+	SetConsoleMode (hConsole, m);
+	// CloseHandle (hConsole);
+}
+
+JNIEXPORT jint JNICALL Java_jline_WindowsTerminal_readByte (JNIEnv * env, jclass class)
+{
+	return getch ();
+}
+
+JNIEXPORT jint JNICALL Java_jline_WindowsTerminal_getWindowsTerminalWidth (JNIEnv * env, jclass class)
+{
+	HANDLE inputHandle = GetStdHandle (STD_INPUT_HANDLE);
+	HANDLE outputHandle = GetStdHandle (STD_OUTPUT_HANDLE);
+	PCONSOLE_SCREEN_BUFFER_INFO info =  malloc (sizeof (CONSOLE_SCREEN_BUFFER_INFO));
+	GetConsoleScreenBufferInfo (outputHandle, info);
+	return info->srWindow.Right - info->srWindow.Left+1;
+}
+
+JNIEXPORT jint JNICALL Java_jline_WindowsTerminal_getWindowsTerminalHeight (JNIEnv * env, jclass class)
+{
+	HANDLE inputHandle = GetStdHandle (STD_INPUT_HANDLE);
+	HANDLE outputHandle = GetStdHandle (STD_OUTPUT_HANDLE);
+	PCONSOLE_SCREEN_BUFFER_INFO info =  malloc (sizeof (CONSOLE_SCREEN_BUFFER_INFO));
+	GetConsoleScreenBufferInfo (outputHandle, info);
+	return info->srWindow.Bottom - info->srWindow.Top+1;
+}
diff --git a/src/jline/src/main/native/jline_WindowsTerminal.h b/src/jline/src/main/native/jline_WindowsTerminal.h
new file mode 100644
index 0000000..5078b93
--- /dev/null
+++ b/src/jline/src/main/native/jline_WindowsTerminal.h
@@ -0,0 +1,68 @@
+/* DO NOT EDIT THIS FILE - it is machine generated */
+#include <jni.h>
+/* Header for class jline_WindowsTerminal */
+
+#ifndef _Included_jline_WindowsTerminal
+#define _Included_jline_WindowsTerminal
+#ifdef __cplusplus
+extern "C" {
+#endif
+/* Inaccessible static: term */
+#undef jline_WindowsTerminal_ENABLE_LINE_INPUT
+#define jline_WindowsTerminal_ENABLE_LINE_INPUT 2L
+#undef jline_WindowsTerminal_ENABLE_ECHO_INPUT
+#define jline_WindowsTerminal_ENABLE_ECHO_INPUT 4L
+#undef jline_WindowsTerminal_ENABLE_PROCESSED_INPUT
+#define jline_WindowsTerminal_ENABLE_PROCESSED_INPUT 1L
+#undef jline_WindowsTerminal_ENABLE_WINDOW_INPUT
+#define jline_WindowsTerminal_ENABLE_WINDOW_INPUT 8L
+#undef jline_WindowsTerminal_ENABLE_MOUSE_INPUT
+#define jline_WindowsTerminal_ENABLE_MOUSE_INPUT 16L
+#undef jline_WindowsTerminal_ENABLE_PROCESSED_OUTPUT
+#define jline_WindowsTerminal_ENABLE_PROCESSED_OUTPUT 1L
+#undef jline_WindowsTerminal_ENABLE_WRAP_AT_EOL_OUTPUT
+#define jline_WindowsTerminal_ENABLE_WRAP_AT_EOL_OUTPUT 2L
+/*
+ * Class:     jline_WindowsTerminal
+ * Method:    getConsoleMode
+ * Signature: ()I
+ */
+JNIEXPORT jint JNICALL Java_jline_WindowsTerminal_getConsoleMode
+  (JNIEnv *, jobject);
+
+/*
+ * Class:     jline_WindowsTerminal
+ * Method:    setConsoleMode
+ * Signature: (I)V
+ */
+JNIEXPORT void JNICALL Java_jline_WindowsTerminal_setConsoleMode
+  (JNIEnv *, jobject, jint);
+
+/*
+ * Class:     jline_WindowsTerminal
+ * Method:    readByte
+ * Signature: ()I
+ */
+JNIEXPORT jint JNICALL Java_jline_WindowsTerminal_readByte
+  (JNIEnv *, jobject);
+
+/*
+ * Class:     jline_WindowsTerminal
+ * Method:    getWindowsTerminalWidth
+ * Signature: ()I
+ */
+JNIEXPORT jint JNICALL Java_jline_WindowsTerminal_getWindowsTerminalWidth
+  (JNIEnv *, jobject);
+
+/*
+ * Class:     jline_WindowsTerminal
+ * Method:    getWindowsTerminalHeight
+ * Signature: ()I
+ */
+JNIEXPORT jint JNICALL Java_jline_WindowsTerminal_getWindowsTerminalHeight
+  (JNIEnv *, jobject);
+
+#ifdef __cplusplus
+}
+#endif
+#endif
diff --git a/src/jline/src/main/resources/jline/CandidateListCompletionHandler.properties b/src/jline/src/main/resources/jline/CandidateListCompletionHandler.properties
new file mode 100644
index 0000000..18ee221
--- /dev/null
+++ b/src/jline/src/main/resources/jline/CandidateListCompletionHandler.properties
@@ -0,0 +1,5 @@
+display-candidates: Display all {0} possibilities? (y or n)
+display-candidates-yes: y
+display-candidates-no: n
+display-more: --More--
+
diff --git a/src/jline/src/main/resources/jline/jline32.dll b/src/jline/src/main/resources/jline/jline32.dll
new file mode 100644
index 0000000..a0d3b11
Binary files /dev/null and b/src/jline/src/main/resources/jline/jline32.dll differ
diff --git a/src/jline/src/main/resources/jline/jline64.dll b/src/jline/src/main/resources/jline/jline64.dll
new file mode 100644
index 0000000..922d6b0
Binary files /dev/null and b/src/jline/src/main/resources/jline/jline64.dll differ
diff --git a/src/jline/src/main/resources/jline/keybindings.properties b/src/jline/src/main/resources/jline/keybindings.properties
new file mode 100644
index 0000000..6f13615
--- /dev/null
+++ b/src/jline/src/main/resources/jline/keybindings.properties
@@ -0,0 +1,62 @@
+# Keybinding mapping for JLine. The format is:
+#    [key code]: [logical operation]
+
+# CTRL-B: move to the previous character
+2: PREV_CHAR
+
+# CTRL-G: move to the previous word
+7: PREV_WORD
+
+# CTRL-F: move to the next character
+6: NEXT_CHAR
+
+# CTRL-A: move to the beginning of the line
+1: MOVE_TO_BEG
+
+# CTRL-D: close out the input stream
+4: EXIT
+
+# CTRL-E: move the cursor to the end of the line
+5: MOVE_TO_END
+
+# BACKSPACE, CTRL-H: delete the previous character
+# 8 is the ASCII code for backspace and therefor
+# deleting the previous character
+8: DELETE_PREV_CHAR
+
+# TAB, CTRL-I: signal that console completion should be attempted
+9: COMPLETE
+
+# CTRL-J, CTRL-M: newline
+10: NEWLINE
+
+# CTRL-K: erase the current line
+11: KILL_LINE
+
+# ENTER: newline
+13: NEWLINE
+
+# CTRL-L: clear screen
+12: CLEAR_SCREEN
+
+# CTRL-N: scroll to the next element in the history buffer
+14: NEXT_HISTORY
+
+# CTRL-P: scroll to the previous element in the history buffer
+16: PREV_HISTORY
+
+# CTRL-R: redraw the current line
+18: REDISPLAY
+
+# CTRL-U: delete all the characters before the cursor position
+21: KILL_LINE_PREV
+
+# CTRL-V: paste the contents of the clipboard (useful for Windows terminal)
+22: PASTE
+
+# CTRL-W: delete the word directly before the cursor
+23: DELETE_PREV_WORD
+
+# DELETE, CTRL-?: delete the previous character
+# 127 is the ASCII code for delete
+127: DELETE_PREV_CHAR
diff --git a/src/jline/src/main/resources/jline/windowsbindings.properties b/src/jline/src/main/resources/jline/windowsbindings.properties
new file mode 100644
index 0000000..51ba491
--- /dev/null
+++ b/src/jline/src/main/resources/jline/windowsbindings.properties
@@ -0,0 +1,65 @@
+# Keybinding mapping for JLine. The format is:
+#    [key code]: [logical operation]
+
+# CTRL-B: move to the previous character
+2: PREV_CHAR
+
+# CTRL-C: toggle overtype mode (frankly, I wasn't sure where to bind this)
+3: INSERT
+
+# CTRL-G: move to the previous word
+7: PREV_WORD
+
+# CTRL-F: move to the next character
+6: NEXT_CHAR
+
+# CTRL-A: move to the beginning of the line
+1: MOVE_TO_BEG
+
+# CTRL-D: close out the input stream
+4: EXIT
+
+# CTRL-E: move the cursor to the end of the line
+5: MOVE_TO_END
+
+# CTRL-H: delete the previous character
+8: DELETE_PREV_CHAR
+
+# TAB, CTRL-I: signal that console completion should be attempted
+9: COMPLETE
+
+# CTRL-J, CTRL-M: newline
+10: NEWLINE
+
+# CTRL-K: Vertical tab - on windows we'll move to the start of the history
+11: START_OF_HISTORY
+
+# ENTER: newline
+13: NEWLINE
+
+# CTRL-L: Form feed - on windows, we'll move to the end of the history
+12: END_OF_HISTORY
+
+# CTRL-N: scroll to the next element in the history buffer
+14: NEXT_HISTORY
+
+# CTRL-P: scroll to the previous element in the history buffer
+16: PREV_HISTORY
+
+# CTRL-R: redraw the current line
+18: REDISPLAY
+
+# CTRL-U: delete all the characters before the cursor position
+21: KILL_LINE_PREV
+
+# CTRL-V: paste the contents of the clipboard (useful for Windows terminal)
+22: PASTE
+
+# CTRL-W: delete the word directly before the cursor
+23: DELETE_PREV_WORD
+
+# CTRL-[: escape - clear the current line.
+27: CLEAR_LINE
+
+# CTRL-?: delete the previous character
+127: DELETE_NEXT_CHAR
diff --git a/src/jline/src/site/apt/building.apt b/src/jline/src/site/apt/building.apt
new file mode 100644
index 0000000..a091378
--- /dev/null
+++ b/src/jline/src/site/apt/building.apt
@@ -0,0 +1,39 @@
+ ------
+ jline
+ ------
+
+Building JLine
+
+ Building JLine requires an installation of {{{http://maven.apache.org/}Maven 2}}.
+
+ Source code is included in the JLine distribution, or can be checked out from CVS as described {{{source-repository.html}here}}.
+
+Maven Repository
+
+ If you are using Maven 2, you can add JLine as an automatic dependency by adding the following to your project's pom.xml file:
+
++--------------------------------+                        
+
+    <repositories>
+        ...
+        <repository>
+            <id>jline</id>
+            <name>JLine Project Repository</name>
+            <url>http://jline.sourceforge.net/m2repo</url>
+        </repository>
+    </repositories>
+    <dependencies>
+        ...
+        <dependency>
+            <groupId>jline</groupId>
+            <artifactId>jline</artifactId>
+            <version>0.9.9</version>
+        </dependency>
+    </dependencies>
+
++--------------------------------+                        
+
+
+
+
+
diff --git a/src/jline/src/site/apt/downloads.apt b/src/jline/src/site/apt/downloads.apt
new file mode 100644
index 0000000..de90db9
--- /dev/null
+++ b/src/jline/src/site/apt/downloads.apt
@@ -0,0 +1,39 @@
+ ------
+ jline
+ ------
+
+Download JLine
+
+ JLine packages can be downloaded from:
+
+ {{{http://sourceforge.net/project/showfiles.php?group_id=64033}http://sourceforge.net/project/showfiles.php?group_id=64033}}
+
+
+Maven Repository
+
+ If you are using Maven 2, you can add JLine as an automatic dependency by adding the following to your project's pom.xml file:
+
++--------------------------------+                        
+
+    <repositories>
+        ...
+        <repository>
+            <id>jline</id>
+            <name>JLine Project Repository</name>
+            <url>http://jline.sourceforge.net/m2repo</url>
+        </repository>
+    </repositories>
+    <dependencies>
+        ...
+        <dependency>
+            <groupId>jline</groupId>
+            <artifactId>jline</artifactId>
+            <version>0.9.9</version>
+        </dependency>
+    </dependencies>
+
++--------------------------------+                        
+
+
+
+
diff --git a/src/jline/src/site/docbook/index.xml b/src/jline/src/site/docbook/index.xml
new file mode 100644
index 0000000..c68b42f
--- /dev/null
+++ b/src/jline/src/site/docbook/index.xml
@@ -0,0 +1,492 @@
+<!DOCTYPE book
+  PUBLIC "-//OASIS//DTD DocBook XML V4.1.2//EN"
+  "http://www.docbook.org/xml/4.1.2/docbookx.dtd">
+
+<book>
+	<bookinfo>
+		<title>
+			JLine
+		</title>
+		<copyright>
+	   		<year>2002, 2003,  2004, 2005, 2006, 2007</year>
+			<holder>Marc Prud'hommeaux</holder>
+		</copyright>
+	</bookinfo>
+	<part id="manual">
+		<title>JLine Manual</title>
+
+		<chapter id="introduction">
+			<title>Introduction</title>
+			<para>
+			JLine is a Java library for handling console input.
+			It is similar in functionality to BSD editline and GNU
+			readline. People familiar with the readline/editline
+			capabilities for modern shells (such as bash and tcsh) will
+			find most of the command editing features of JLine to
+			be familiar.
+			</para>
+		</chapter>
+
+		<chapter id="license">
+			<title>License and Terms of Use</title>
+			<para>
+				JLine is distributed under the BSD license, meaning that
+				you are completely free to redistribute, modify, or sell it
+				with almost no restrictins.
+				For more information on the BSD license, see
+				<ulink url="http://www.opensource.org/licenses/bsd-license.php"
+				>http://www.opensource.org/licenses/bsd-license.php</ulink>.
+			</para>
+			<para>
+				For information on obtaining the software under another
+				license, contact the copyright holder:
+				<ulink url="mailto:mwp1 at cornell.edu">mwp1 at cornell.edu</ulink>.
+			</para>
+		</chapter>
+
+		<chapter id="obtaining">
+			<title>Obtaining JLine</title>
+			<para>
+				JLine is hosted on SourceForge, and is located at
+				<ulink url="http://jline.sf.net">http://jline.sf.net</ulink>.
+				The latest release can be downloaded from 
+				<ulink url=
+				"http://sourceforge.net/project/showfiles.php?group_id=64033">http://sourceforge.net/project/showfiles.php?group_id=64033</ulink>.
+				API documentation can be found in the
+                <ulink url="apidocs">apidocs/</ulink> directory.
+			</para>
+		</chapter>
+
+		<chapter id="installation">
+			<title>Installation</title>
+			<para>
+				JLine has no library dependencies, aside from a JVM
+				of version 1.2 or higher. To install JLine, download the
+				<filename>jline.jar</filename> file, and either place it in
+				the system-wide java extensions directory, or
+				manually add it to your
+				<computeroutput>CLASSPATH</computeroutput>.
+				The extensions directory is dependent on your operating
+				system. Some few examples are:
+				<itemizedlist>
+					<listitem><para>
+					Macintosh OS X:
+					<filename>/Library/Java/Extensions</filename> or
+					<filename>/System/Library/Java/Extensions</filename>
+					</para></listitem>
+					<listitem><para>
+					Microsoft Windows:
+					<filename>JAVAHOME\jre\lib\ext</filename>
+					(example: 
+					<filename>C:\j2sdk1.4.1_03\jre\lib\ext</filename>)
+					</para></listitem>
+					<listitem><para>
+					UNIX Systems:
+					<filename>JAVAHOME/jre/lib/ext</filename>
+					(example: 
+					<filename>/usr/local/java/jre/lib/ext</filename>)
+					</para></listitem>
+				</itemizedlist>
+			</para>
+			<para>
+				JLine is not 100% pure Java. On Windows, it relies on a
+				<filename>.dll</filename> file to initialize the terminal
+				to be able to accept unbuffered input. However,
+				no installation is necessary for this: when initialized,
+				JLine will dynamically extract the DLL to a temporary
+				directory and load it. For more details, see the
+				documentation for the <classname>jline.WindowsTerminal</classname> class.
+			</para>
+			<para>
+				On UNIX systems (including Macintosh OS X), JLine will
+				execute the <filename>stty</filename> command to initialize
+				the terminal to allow unbuffered input. For more details,
+				see the documentation for the <classname>jline.UnixTerminal</classname> class.
+			</para>
+			<para>
+				For both Windows and UNIX systems, JLine will fail to
+				initialize if it is run inside a strict security manager
+				that does not allow the loading of libraries, writing
+				to the file system, or executing external programs. However,
+				for most console applications, this is usually not the case.
+			</para>
+		</chapter>
+		<chapter id="supported_platforms">
+			<title>Supported Platforms</title>
+			<para>
+				JLine should work on any Windows system, or any
+				minimally compliant POSIX system (includling Linux and
+				Macintosh OS X).
+			</para>
+			<para>
+				The platforms on which JLine has been confirmed to work are:
+				<itemizedlist>
+					<listitem><para>
+						Microsoft Windows XP
+					</para></listitem>
+					<listitem><para>
+						RedHat Linux 9.0
+					</para></listitem>
+					<listitem><para>
+						Debian Linux 3.0
+					</para></listitem>
+					<listitem><para>
+						Macintosh OS X 10.3
+					</para></listitem>
+				</itemizedlist>
+			</para>
+			<para>
+				Please report successes or failures to the author:
+				<ulink url="mailto:mwp1 at cornell.edu">mwp1 at cornell.edu</ulink>.
+			</para>
+		</chapter>
+		<chapter id="features">
+			<title>Features</title>
+			<section id="features_history">
+				<title>Command History</title>
+				<para>
+				</para>
+			</section>
+			<section id="features_completion">
+				<title>Tab completion</title>
+				<para>
+				</para>
+			</section>
+			<section id="features_line_editing">
+				<title>Line editing</title>
+				<para>
+				</para>
+			</section>
+			<section id="features_keybindings">
+				<title>Custom Keybindings</title>
+				<para>
+				You can create your own keybindings by creating a
+				<filename>HOME/.jlinebindings.properties"</filename>
+				file. You can override the location of this file with
+				the "<computeroutput>jline.keybindings</computeroutput>"
+				system property.
+				</para>
+                <!--
+				<para>
+				The default keybindings are as follows:
+					<programlisting>
+					</programlisting>
+				</para>
+                -->
+			</section>
+			<section id="features_masking">
+				<title>Character masking</title>
+				<para>
+				</para>
+			</section>
+		</chapter>
+		<chapter id="api">
+			<title>API</title>
+			<para>
+				This section discusses some common usages of the JLine API.
+				For in-depth usage of the JLine API, see the
+				<ulink url="apidocs">apidocs</ulink>.
+			</para>
+			<section id="reading_password">
+				<title>Reading a password from the console</title>
+				<para>
+					A common task that console applications need to do is
+					read in a password. While it is standard for software
+					to not echo password strings as they are typed,
+					the Java core APIs surprisingly do not provide any
+					means to do this.
+				</para>
+				<para>
+					JLine can read a password with the following code:
+					<programlisting>
+String password = new <classname>jline.ConsoleReader</classname>().readLine(new Character('*'));
+					</programlisting>
+					This will replace every character types on the console
+					with a star character.
+				</para>
+				<para>
+					Alternately, you can have it not echo password
+					character at all:
+					<programlisting>
+String password = new <classname>jline.ConsoleReader</classname>().readLine(new Character(0));
+					</programlisting>
+				</para>
+				<para>
+					The <filename>jline-demo.jar</filename> file contains
+					a sample application that reads the password. To run
+					the sample, execute:
+					<programlisting>
+java -cp jline-demo.jar jline.example.PasswordReader "*"
+					</programlisting>
+				</para>
+			</section>
+		</chapter>
+		<chapter id="faq">
+			<title>Frequently Asked Questions</title>
+			<section id="faq_unsupported_platform"><title>
+				Can I disable JLine if it isn't working on my platform?
+				</title>
+				<para>
+				You can disable JLine by setting the System property
+				"<computeroutput>jline.terminal</computeroutput>"
+				to
+				"<classname>jline.UnsupportedTerminal</classname>". For example:
+				<programlisting>
+java -Djline.terminal=jline.UnsupportedTerminal jline.example.Example simple
+				</programlisting>
+				</para>
+			</section>
+			<section id="faq_custom_keybindings"><title>
+				How do I customize the key bindings?
+				</title>
+				<para>
+				You can create your own keybindings by creating a
+				<filename>HOME/.jlinebindings.properties"</filename>
+				file. You can override the location of this file with
+				the "<computeroutput>jline.keybindings</computeroutput>"
+				system property. To examine the format to use, see the
+				<filename>src/jline/keybindings.properties</filename>
+				file in the source distribution.
+				</para>
+			</section>
+			<section id="faq_jline_as_default"><title>
+				Can I use JLine as the default console input stream for
+				all applications?
+				</title>
+				<para>
+				No, but you can use the <classname>jline.ConsoleRunner</classname> application
+				to set up the system input stream and continue on
+				the launch another program. For example, to use JLine
+				as the input handler for the popular 
+				<ulink url="http://www.beanshell.org">BeanShell</ulink>
+				console application, you can run:
+				<programlisting>
+java <classname>jline.ConsoleRunner</classname> <ulink url="http://www.beanshell.org/manual/standalonemode.html">bsh.Interpreter</ulink>
+				</programlisting>
+				</para>
+			</section>
+			<section id="faq_jline_beanshell"><title>
+				Can I use JLine as the input handler for <ulink url="http://www.beanshell.org">BeanShell</ulink>?
+				</title>
+				<para>
+				Yes. Try running:
+				<programlisting>
+java <classname>jline.ConsoleRunner</classname> <ulink url="http://www.beanshell.org/manual/standalonemode.html">bsh.Interpreter</ulink>
+				</programlisting>
+				</para>
+			</section>
+			<section id="faq_jline_jdb"><title>
+				Can I use JLine as the input handler for <ulink url="http://java.sun.com/j2se/1.3/docs/tooldocs/solaris/jdb.html">jdb</ulink> (the java debugger)?
+				</title>
+				<para>
+				Yes. Try running:
+				<programlisting>
+java <classname>jline.ConsoleRunner</classname> com.sun.tools.example.debug.tty.TTY <emphasis>args</emphasis>
+				</programlisting>
+				</para>
+			</section>
+			<section id="faq_pure_java"><title>
+				Is JLine <trademark>100% pure Java</trademark>?
+				</title>
+				<para>
+				No: JLine uses a couple small native methods in the Windows
+				platform. On Unix, it is technically pure java, but relies
+				on the execution of external (non-java) programs. See the
+				<link linkend="installation">installation section</link>
+				for more details.
+				</para>
+			</section>
+			<section id="faq_password"><title>
+				How do I make it so password characters are no echoed
+				to the screen?
+				</title>
+				<para>
+				See <link linkend="reading_password"/>.
+				</para>
+			</section>
+			<section id="faq_cursrs"><title>
+				Is JLine a full-featured curses implementation?
+				</title>
+				<para>
+				No: JLine has no ability to position the cursor on the
+				console. It might someday evolve into a plausible
+				Java curses implementation.
+				</para>
+			</section>
+		</chapter>
+	</part>
+
+	<appendix id="known_bugs">
+		<title>Known Bugs</title>	
+		<itemizedlist>
+			<listitem><para>
+			Clearing the screen (CTRL-L) doesn't currently work on Windows.
+			</para></listitem>
+		</itemizedlist>
+	</appendix>
+
+	<appendix id="contributors">
+		<title>Contributors</title>	
+        <para>
+        The following people have contributed to improving JLine over the
+        years:
+        </para>
+		<itemizedlist>
+			<listitem><para>
+            Marc Prud'hommeaux
+			</para></listitem>
+			<listitem><para>
+            Damian Steer
+			</para></listitem>
+			<listitem><para>
+            Dale Kemp
+			</para></listitem>
+			<listitem><para>
+            Jun Liu
+			</para></listitem>
+			<listitem><para>
+            malcolm at epcc.ed.ac.uk
+			</para></listitem>
+			<listitem><para>
+            Simon Patarin
+			</para></listitem>
+			<listitem><para>
+            Amy Isard
+			</para></listitem>
+			<listitem><para>
+            Ryan Bell
+			</para></listitem>
+			<listitem><para>
+            Marc Herbert
+			</para></listitem>
+			<listitem><para>
+            Christian Salm
+			</para></listitem>
+		</itemizedlist>
+	</appendix>
+
+	<appendix id="todo">
+		<title>Future enhancements</title>	
+		<itemizedlist>
+			<listitem><para>
+				Add localization for all strings.
+			</para></listitem>
+			<listitem><para>
+				Create a BNFCompletor that can handle any BNF.
+			</para></listitem>
+		</itemizedlist>
+	</appendix>
+
+	<appendix id="changelog">
+		<title>Change Log</title>
+		<itemizedlist>
+			<title>0.9.93 2007-11-13</title>
+			<listitem><para>
+                Fixed backspace handling on Unix/OS X.
+			</para></listitem>
+		</itemizedlist>
+		<itemizedlist>
+			<title>0.9.92 2007-10-30</title>
+			<listitem><para>
+                JLine now works with 64-bit Windows systems.
+			</para></listitem>
+		</itemizedlist>
+		<itemizedlist>
+			<title>0.9.91 2007-03-11</title>
+			<listitem><para>
+                Added ConsoleReader.setUsePagination() method which allows
+                configuration of pagination when the number of rows of
+                candidates exceeds the height of the detected terminal, thanks
+                to a patch by Damian Steer.
+			</para></listitem>
+			<listitem><para>
+                Better support for UTF-8 inputs (issue #1623521).
+			</para></listitem>
+			<listitem><para>
+                Improved list of supported keys on Windows (issue #1649790).
+			</para></listitem>
+		</itemizedlist>
+		<itemizedlist>
+			<title>0.9.5 2006-03-08</title>
+			<listitem><para>
+				Fixed problem with "stty" on Solaris, which doesn't
+				understand "stty size" to query the terminal size. It now
+				uses "stty -a", which supposedly outputs a POSIX standard 
+				format.
+			</para></listitem>
+			<listitem><para>
+				Support HOME and END keys, thanks to a patch by
+				Dale Kemp.
+			</para></listitem>
+		</itemizedlist>
+		<itemizedlist>
+			<title>0.9.1 2005-01-29</title>
+			<listitem><para>
+				Fixed problem with the 0.9.0 distribution that
+				failed to include the Windows jline.dll in the jline.jar,
+				rendering it inoperable on Windows.
+			</para></listitem>
+			<listitem><para>
+				Implemented proper interception or arrow keys on Windows,
+				meaning that history can now be navigated with the UP
+				and DOWN keys, and line editing can take place with
+				the LEFT and RIGHT arrow keys.
+			</para></listitem>
+		</itemizedlist>
+		<itemizedlist>
+			<title>0.9.0 2005-01-23</title>
+			<listitem><para>
+				Changed license from GPL to BSD.
+			</para></listitem>
+			<listitem><para>
+				Made "CTRL-L" map to clearing the screen.
+			</para></listitem>
+		</itemizedlist>
+		<itemizedlist>
+			<title>0.8.1 2003-11-18</title>
+			<listitem><para>
+				Fixed accidental dependency on JVM 1.4.
+			</para></listitem>
+		</itemizedlist>
+		<itemizedlist>
+			<title>0.8.0 2003-11-17</title>
+			<listitem><para>
+				Windows support using a native .dll
+			</para></listitem>
+			<listitem><para>
+				A new ClassNameCompletor
+			</para></listitem>
+			<listitem><para>
+				Many doc improvements
+			</para></listitem>
+		</itemizedlist>
+		<itemizedlist>
+			<title>0.6.0 2003-07-08</title>
+			<listitem><para>
+				Many bugfixes
+			</para></listitem>
+			<listitem><para>
+				Better release system
+			</para></listitem>
+			<listitem><para>
+				Automatically set terminal property by
+				issuing stty on UNIX systems
+			</para></listitem>
+			<listitem><para>
+				Additional tab-completion handlers
+			</para></listitem>
+			<listitem><para>
+				Tested on Debian Linux and Mac OS 10.2
+			</para></listitem>
+			<listitem><para>
+				Example includes dictionary, filename, and simple completion
+			</para></listitem>
+		</itemizedlist>
+		<itemizedlist>
+			<title>0.3.0 2002-10-05</title>
+			<listitem><para>
+				Initial release
+			</para></listitem>
+		</itemizedlist>
+	</appendix>
+</book>
diff --git a/src/jline/src/site/fml/faq.fml b/src/jline/src/site/fml/faq.fml
new file mode 100644
index 0000000..b9902b0
--- /dev/null
+++ b/src/jline/src/site/fml/faq.fml
@@ -0,0 +1,26 @@
+ <?xml version="1.0"?>
+<faqs title="JLine FAQ">
+  <part id="general">
+    <faq>
+      <question>How does JLine work?</question>
+      <answer>
+        <p>
+        On Windows, JLine uses a native .dll (which it automatically
+        extracts from the jline jar and loads at runtime) to access
+        native console features. On UNIX systems, JLine will perform
+        the necessary terminal setup by launching the "stty" command. 
+        </p>
+      </answer>
+    </faq>
+    <faq>
+      <question>What platforms has JLine been tested on?</question>
+      <answer>
+        <p>
+        Various flavors of Windows (95, 98, NT, XP, 2000), Mac OS X,
+        and multiple UNIX systems (Linux, Solaris, HPUX). 
+        </p>
+      </answer>
+    </faq>
+
+  </part>
+</faqs> 
diff --git a/src/jline/src/site/resources/css/site.css b/src/jline/src/site/resources/css/site.css
new file mode 100644
index 0000000..5d71608
--- /dev/null
+++ b/src/jline/src/site/resources/css/site.css
@@ -0,0 +1,311 @@
+
+body {
+    min-width: 600px;
+    width: 600px;
+    width: auto !important;
+    background-color: #fff;
+    font-family: Verdana, sans;
+}
+
+body,div,span,td,p,h2,h3,h4,h5,h6,a,ul,li {
+    font-family: Verdana, sans;
+    font-size: 11px;
+    color: #5A5A5A;
+    font-style: normal;
+}
+
+a,a:hover,a:visited,a:active {
+    color: #5A5A5A;
+    /* text-decoration: underline; */
+}
+
+/* main layout */
+#banner {
+    color: #FFA500;
+    border: none;
+    margin: 0 0 0 0;
+    background-color: #fff;
+    background-image: url(../images/header.jpg);
+    background-position: right;
+    background-repeat: no-repeat;
+    height: 100px;
+}
+
+#bannerLeft img{
+    margin: 10px 0 0 10px;
+}
+
+#leftColumn {
+    background-color: transparent;
+    position: absolute;
+    top: 140px;
+    left: 20px;
+    width: 180px;
+    margin: 0px;
+    padding: 0px;
+    border: none;
+}
+
+#bodyColumn {
+    margin: 0 0 20px 220px;
+    background-color: #fff;
+    padding: 30px;
+    position: relative;
+    background-image: url(../images/dotted.png);
+    background-repeat: repeat-y;
+}
+
+#footer div.xright {
+    color: #fff;
+    margin-right: 10px;
+}
+
+/* end main layout */
+.deprecated {
+    text-decoration: line-through;
+}
+
+.comment {
+    color: green;
+}
+
+.source pre {
+    font-family: "Andale Mono", monospace;
+    font-size: 11px;
+    background-color: #ddd;
+    width: 100%;
+    color: #5A5A5A;
+    border-width: 0px;
+    padding-top: 6px;
+    padding-left: 3px;
+}
+
+#breadcrumbs {
+    background-color: #FE1100;
+    border: none;
+    height: 15px;
+}
+
+/*
+    workaround for bug in the Doxia docbook renderer that opens
+    anchors (e.g. <a name="index">), but doesn't ever close them
+*/
+#section a,a:hover,a:visited,a:active {
+    text-decoration: none;
+}
+
+
+#breadcrumbs a {
+    color: #fff;
+    margin-left: 20px;
+    text-decoration: none;
+}
+
+h1 {
+    border: none;
+    padding-left: 0;
+    font-weight: bold;
+    text-transform: capitalize;
+    background-color: #7FAABB !important;
+    color: #FFFFFF !important;
+    font-size: 19px !important;
+}
+
+h2 {
+    border: none;
+    padding-left: 0;
+    font-size: 13px;
+    font-weight: bold;
+    text-transform: capitalize;
+    background-color: #7FAABB !important;
+    color: #FFFFFF !important;
+    font-size: 17px !important;
+}
+
+h3 {
+    border: none;
+    font-weight: bolder;
+    padding-left: 0;
+    background-color: #8BBBD1 !important;
+    color: #FFFFFF !important;
+}
+
+#navcolumn {
+    padding: 0;
+    overflow: hidden;
+}
+
+#navcolumn ul {
+    margin: 0px 0 3px 0;
+    background-repeat: repeat-x;
+}
+
+#navcolumn h5 {
+    border: none;
+    background-image: url(../images/dotted.png);
+    background-repeat: repeat-x;
+    padding: 4px 0 3px 20px;
+    font-size: 11px !important;
+    margin-top: -1px;
+}
+
+#navcolumn ul {
+    margin-bottom: 8px;
+}
+
+#navcolumn li {
+    margin: 0px 0 0px 3px;
+    padding: 2px;
+    list-style-position: outside;
+    font-size: 7.5pt !important;
+    padding-left: 16px;
+    padding-left /**/: 2px !important;
+    /* warning, don't reformat, there should be no comment between padding-left and comment, to fix IE5 issues */
+}
+
+#menuDownloadable_docs li {
+    background-image: url(../images/ico_file_pdf.png);
+    padding-top: 3px;
+    padding-bottom: 1px;
+}
+
+#navcolumn strong {
+    color: #000000;
+    font-weight: bold;
+}
+
+#navcolumn strong a {
+    color: #000000;
+    font-weight: bold;
+}
+
+#navcolumn a {
+    padding-left: 14px;
+    text-decoration: underline;
+    padding-bottom: 2px;
+    color: #5a5a5a;
+}
+
+#navcolumn a img {
+    margin-top: 0;
+}
+
+#navcolumn a#poweredBy img {
+    margin: 0 0 15px 20px;
+    width: 90px;
+    height: 30px;
+}
+
+#navcolumn #lastPublished {
+    color: #999;
+    margin: 0 0 0 20px;
+}
+
+#navcolumn a:hover {
+    color: Olive;
+    padding-left: 14px;
+    text-decoration: underline;
+    padding-bottom: 2px;
+}
+
+#breadcrumbs div.xright,#breadcrumbs div.xleft {
+    color: #fff;
+    display: inline;
+    font-size: 7pt !important;
+}
+
+#banner a#projectLogo img {
+    float: left;
+    background-color: #fff !important;
+    margin: 20px 0 0 20px !important;
+}
+
+#navcolumn li {
+    color: #000000;
+}
+
+#navcolumn strong {
+    color: #000000;
+    font-weight: bold;
+    margin-left: 15px;
+}
+
+div.source {
+    background-color: #ddd;
+}
+
+div.source pre,code,td.code {
+    font-size: 8pt !important;
+    font-family: monospace;
+    margin: 0;
+}
+
+td.code {
+    font-size: 10pt !important;
+    font-family: monospace;
+}
+
+div#legend {
+    display: none;
+}
+
+table td.source {
+    border: none !important;
+}
+
+table td,table th {
+    font-size: 8pt !important;
+    font-family: verdana;
+}
+
+table th {
+    font-weight: bold;
+}
+
+.collapsed {
+    background-image: url(../images/collapsed.png) !important;
+}
+
+li.expanded {
+    background-image: url(../images/expanded.png) !important;
+}
+
+/*
+li.expanded ul {
+    margin-top: 5px !important;
+}
+*/
+
+a.externalLink,a.newWindow {
+    padding-right: 9px !important;
+    background-image: none !important; /*ie5*/
+}
+
+a.externalLink /* */ {
+    background-image: url(../images/external.png) !important;
+}
+
+a.newWindow /* */ {
+    background-image: url(../images/newwindow.png) !important;
+}
+
+table {
+    width: 68%; /* fix for ie 5.x */
+}
+
+i {
+    content: "\"/*"
+}
+
+table {
+    width: 100%;
+}
+/* remove banner: comment the following lines for the full layout */ /*
+#banner, #breadcrumbs {
+    display: none !important;
+}
+#leftColumn {
+    position: relative;
+    top: 0;
+}
+*/
diff --git a/src/jline/src/site/resources/images/collapsed.png b/src/jline/src/site/resources/images/collapsed.png
new file mode 100644
index 0000000..a02c1e6
Binary files /dev/null and b/src/jline/src/site/resources/images/collapsed.png differ
diff --git a/src/jline/src/site/resources/images/dotted.png b/src/jline/src/site/resources/images/dotted.png
new file mode 100644
index 0000000..8a4d443
Binary files /dev/null and b/src/jline/src/site/resources/images/dotted.png differ
diff --git a/src/jline/src/site/resources/images/expanded.png b/src/jline/src/site/resources/images/expanded.png
new file mode 100644
index 0000000..8a19dbf
Binary files /dev/null and b/src/jline/src/site/resources/images/expanded.png differ
diff --git a/src/jline/src/site/resources/images/external.png b/src/jline/src/site/resources/images/external.png
new file mode 100644
index 0000000..19f2895
Binary files /dev/null and b/src/jline/src/site/resources/images/external.png differ
diff --git a/src/jline/src/site/resources/images/ico_file_pdf.png b/src/jline/src/site/resources/images/ico_file_pdf.png
new file mode 100644
index 0000000..9ceb00f
Binary files /dev/null and b/src/jline/src/site/resources/images/ico_file_pdf.png differ
diff --git a/src/jline/src/site/resources/images/logo.jpg b/src/jline/src/site/resources/images/logo.jpg
new file mode 100644
index 0000000..1f1da5c
Binary files /dev/null and b/src/jline/src/site/resources/images/logo.jpg differ
diff --git a/src/jline/src/site/resources/images/newwindow.png b/src/jline/src/site/resources/images/newwindow.png
new file mode 100644
index 0000000..1374c22
Binary files /dev/null and b/src/jline/src/site/resources/images/newwindow.png differ
diff --git a/src/jline/src/site/site.xml b/src/jline/src/site/site.xml
new file mode 100644
index 0000000..274ec83
--- /dev/null
+++ b/src/jline/src/site/site.xml
@@ -0,0 +1,40 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<project name="JLine">
+    <bannerLeft>
+        <name>JLine</name>
+        <src>images/logo.jpg</src>
+        <href>http://jline.sourceforge.net/</href>
+    </bannerLeft>     
+    <bannerRight>
+        <name>SourceForge</name>
+        <src>http://sourceforge.net/sflogo.php?group_id=64033</src>
+        <href>http://sourceforge.net/</href>
+    </bannerRight>     
+    <body>
+        <menu name="JLine">
+            <item name="Manual" href="index.html"/>
+            <item name="FAQs" href="faq.html"/>
+            <item name="Download" href="downloads.html"/>
+            <item name="Building" href="building.html"/>
+        </menu>
+
+        <menu name="Community">
+            <item name="Forums"
+                href="http://sourceforge.net/forum/?group_id=64033"/>
+            <item name="Issue Tracker"
+                href="http://sourceforge.net/tracker/?group_id=64033"/>
+            <item name="News"
+                href="http://sourceforge.net/news/?group_id=64033"/>
+        </menu>
+
+        <menu name="Project">
+            <item name="Javadocs"
+                href="apidocs/index.html"/>
+            <item name="Browse Source Code"
+                href="http://jline.cvs.sourceforge.net/jline/"/>
+        </menu>
+
+        ${reports}
+
+    </body>
+</project>
diff --git a/src/jline/src/test/java/jline/ConsoleReaderTest.java b/src/jline/src/test/java/jline/ConsoleReaderTest.java
new file mode 100644
index 0000000..4a25783
--- /dev/null
+++ b/src/jline/src/test/java/jline/ConsoleReaderTest.java
@@ -0,0 +1,162 @@
+package jline;
+
+import java.io.ByteArrayInputStream;
+import java.io.InputStream;
+import java.io.StringWriter;
+import java.io.Writer;
+
+import junit.framework.TestCase;
+
+public class ConsoleReaderTest extends TestCase {
+
+    public ConsoleReaderTest(String name) {
+        super(name);
+    }
+
+    protected void setUp() throws Exception {
+        System.setProperty("jline.WindowsTerminal.directConsole", "false");
+    }
+
+    public void testDeleteAndBackspaceKeymappings() throws Exception {
+        // test only works on Windows
+        if (!(Terminal.getTerminal() instanceof WindowsTerminal))
+            return;
+
+        ConsoleReader consoleReader = new ConsoleReader();
+        assertNotNull(consoleReader);
+        assertEquals(127, consoleReader
+                .getKeyForAction(ConsoleReader.DELETE_NEXT_CHAR));
+        assertEquals(8, consoleReader
+                .getKeyForAction(ConsoleReader.DELETE_PREV_CHAR));
+    }
+
+    public void testReadline() throws Exception {
+        ConsoleReader consoleReader = createConsole("Sample String\r\n"
+                .getBytes());
+        assertNotNull(consoleReader);
+        String line = consoleReader.readLine();
+        assertEquals("Sample String", line);
+
+    }
+
+    public void testDeleteOnWindowsTerminal() throws Exception {
+        // test only works on Windows
+        if (!(Terminal.getTerminal() instanceof WindowsTerminal))
+            return;
+
+        char[] characters = new char[] { 'S', 's',
+                WindowsTerminal.SPECIAL_KEY_INDICATOR,
+                WindowsTerminal.LEFT_ARROW_KEY,
+                WindowsTerminal.SPECIAL_KEY_INDICATOR,
+                WindowsTerminal.DELETE_KEY, '\r', 'n' };
+        assertWindowsKeyBehavior("S", characters);
+    }
+
+    public void testNumpadDeleteOnWindowsTerminal() throws Exception {
+        // test only works on Windows
+        if (!(Terminal.getTerminal() instanceof WindowsTerminal))
+            return;
+
+        char[] characters = new char[] { 'S', 's',
+                WindowsTerminal.NUMPAD_KEY_INDICATOR,
+                WindowsTerminal.LEFT_ARROW_KEY,
+                WindowsTerminal.NUMPAD_KEY_INDICATOR,
+                WindowsTerminal.DELETE_KEY, '\r', 'n' };
+        assertWindowsKeyBehavior("S", characters);
+    }
+
+    public void testHomeKeyOnWindowsTerminal() throws Exception {
+        // test only works on Windows
+        if (!(Terminal.getTerminal() instanceof WindowsTerminal))
+            return;
+
+        char[] characters = new char[] { 'S', 's',
+                WindowsTerminal.SPECIAL_KEY_INDICATOR,
+                WindowsTerminal.HOME_KEY, 'x', '\r', '\n' };
+        assertWindowsKeyBehavior("xSs", characters);
+
+    }
+
+    public void testEndKeyOnWindowsTerminal() throws Exception {
+        // test only works on Windows
+        if (!(Terminal.getTerminal() instanceof WindowsTerminal))
+            return;
+
+        char[] characters = new char[] { 'S', 's',
+                WindowsTerminal.SPECIAL_KEY_INDICATOR,
+                WindowsTerminal.HOME_KEY, 'x',
+                WindowsTerminal.SPECIAL_KEY_INDICATOR, WindowsTerminal.END_KEY,
+                'j', '\r', '\n' };
+        assertWindowsKeyBehavior("xSsj", characters);
+    }
+
+    public void testPageUpOnWindowsTerminal() throws Exception {
+        // test only works on Windows
+        if (!(Terminal.getTerminal() instanceof WindowsTerminal))
+            return;
+
+        char[] characters = new char[] { WindowsTerminal.SPECIAL_KEY_INDICATOR,
+                WindowsTerminal.PAGE_UP_KEY, '\r', '\n' };
+        assertWindowsKeyBehavior("dir", characters);
+    }
+
+    public void testPageDownOnWindowsTerminal() throws Exception {
+        // test only works on Windows
+        if (!(Terminal.getTerminal() instanceof WindowsTerminal))
+            return;
+
+        char[] characters = new char[] { WindowsTerminal.SPECIAL_KEY_INDICATOR,
+                WindowsTerminal.PAGE_DOWN_KEY, '\r', '\n' };
+        assertWindowsKeyBehavior("mkdir monkey", characters);
+    }
+
+    public void testEscapeOnWindowsTerminal() throws Exception {
+        // test only works on Windows
+        if (!(Terminal.getTerminal() instanceof WindowsTerminal))
+            return;
+
+        char[] characters = new char[] { 's', 's', 's',
+                WindowsTerminal.SPECIAL_KEY_INDICATOR,
+                WindowsTerminal.ESCAPE_KEY, '\r', '\n' };
+        assertWindowsKeyBehavior("", characters);
+    }
+
+    public void testInsertOnWindowsTerminal() throws Exception {
+        // test only works on Windows
+        if (!(Terminal.getTerminal() instanceof WindowsTerminal))
+            return;
+
+        char[] characters = new char[] { 'o', 'p', 's',
+                WindowsTerminal.SPECIAL_KEY_INDICATOR,
+                WindowsTerminal.HOME_KEY,
+                WindowsTerminal.SPECIAL_KEY_INDICATOR,
+                WindowsTerminal.INSERT_KEY, 'o', 'o', 'p', 's', '\r', '\n' };
+        assertWindowsKeyBehavior("oops", characters);
+    }
+
+    private void assertWindowsKeyBehavior(String expected, char[] input)
+            throws Exception {
+        StringBuffer buffer = new StringBuffer();
+        buffer.append(input);
+        ConsoleReader reader = createConsole(buffer.toString().getBytes());
+        assertNotNull(reader);
+        String line = reader.readLine();
+        assertEquals(expected, line);
+    }
+
+    private ConsoleReader createConsole(byte[] bytes) throws Exception {
+        InputStream in = new ByteArrayInputStream(bytes);
+        Writer writer = new StringWriter();
+        ConsoleReader reader = new ConsoleReader(in, writer);
+        reader.setHistory(createSeededHistory());
+        return reader;
+    }
+
+    private History createSeededHistory() {
+        History history = new History();
+        history.addToHistory("dir");
+        history.addToHistory("cd c:\\");
+        history.addToHistory("mkdir monkey");
+        return history;
+    }
+}
diff --git a/src/jline/src/test/java/jline/JLineTestCase.java b/src/jline/src/test/java/jline/JLineTestCase.java
new file mode 100644
index 0000000..92e09d4
--- /dev/null
+++ b/src/jline/src/test/java/jline/JLineTestCase.java
@@ -0,0 +1,140 @@
+/*
+ * Copyright (c) 2002-2007, Marc Prud'hommeaux. All rights reserved.
+ *
+ * This software is distributable under the BSD license. See the terms of the
+ * BSD license in the documentation provided with this software.
+ */
+package jline;
+
+import junit.framework.*;
+
+import java.io.*;
+
+public abstract class JLineTestCase extends TestCase {
+    ConsoleReader console;
+
+    public JLineTestCase(String test) {
+        super(test);
+    }
+
+    public void setUp() throws Exception {
+        super.setUp();
+        console = new ConsoleReader(null, new PrintWriter(
+                new OutputStreamWriter(new ByteArrayOutputStream())), null,
+                new UnixTerminal());
+    }
+
+    public void assertBuffer(String expected, Buffer buffer) throws IOException {
+        assertBuffer(expected, buffer, true);
+    }
+
+    public void assertBuffer(String expected, Buffer buffer, boolean clear)
+            throws IOException {
+        // clear current buffer, if any
+        if (clear) {
+            console.finishBuffer();
+            console.getHistory().clear();
+        }
+
+        console.setInput(new ByteArrayInputStream(buffer.getBytes()));
+
+        // run it through the reader
+        while (console.readLine((String) null) != null) {
+            ;
+        }
+
+        assertEquals(expected, console.getCursorBuffer().toString());
+    }
+
+    private int getKeyForAction(short logicalAction) {
+        int action = console.getKeyForAction(logicalAction);
+
+        if (action == -1) {
+            fail("Keystroke for logical action " + logicalAction
+                    + " was not bound in the console");
+        }
+
+        return action;
+    }
+
+    /**
+     * TODO: Fix this so tests don't break on windows machines.
+     *
+     * @author Ryan
+     *
+     */
+    class Buffer {
+        private final ByteArrayOutputStream bout = new ByteArrayOutputStream();
+
+        public Buffer() {
+        }
+
+        public Buffer(String str) {
+            append(str);
+        }
+
+        public byte[] getBytes() {
+            return bout.toByteArray();
+        }
+
+        public Buffer op(short operation) {
+            return append(getKeyForAction(operation));
+        }
+
+        public Buffer ctrlA() {
+            return append(getKeyForAction(ConsoleReader.MOVE_TO_BEG));
+        }
+
+        public Buffer ctrlU() {
+            return append(getKeyForAction(ConsoleReader.KILL_LINE_PREV));
+        }
+
+        public Buffer tab() {
+            return append(getKeyForAction(ConsoleReader.COMPLETE));
+        }
+
+        public Buffer back() {
+            return append(getKeyForAction(ConsoleReader.DELETE_PREV_CHAR));
+        }
+
+        public Buffer left() {
+            return append(UnixTerminal.ARROW_START).append(
+                    UnixTerminal.ARROW_PREFIX).append(UnixTerminal.ARROW_LEFT);
+        }
+
+        public Buffer right() {
+            return append(UnixTerminal.ARROW_START).append(
+                    UnixTerminal.ARROW_PREFIX).append(UnixTerminal.ARROW_RIGHT);
+        }
+
+        public Buffer up() {
+            return append(UnixTerminal.ARROW_START).append(
+                    UnixTerminal.ARROW_PREFIX).append(UnixTerminal.ARROW_UP);
+        }
+
+        public Buffer down() {
+            return append(UnixTerminal.ARROW_START).append(
+                    UnixTerminal.ARROW_PREFIX).append(UnixTerminal.ARROW_DOWN);
+        }
+
+        public Buffer append(String str) {
+            byte[] bytes = str.getBytes();
+
+            for (int i = 0; i < bytes.length; i++) {
+                append(bytes[i]);
+            }
+
+            return this;
+        }
+
+        public Buffer append(int i) {
+            return append((byte) i);
+        }
+
+        public Buffer append(byte b) {
+            bout.write(b);
+
+            return this;
+        }
+    }
+}
diff --git a/src/jline/src/test/java/jline/TestCompletion.java b/src/jline/src/test/java/jline/TestCompletion.java
new file mode 100644
index 0000000..a481e26
--- /dev/null
+++ b/src/jline/src/test/java/jline/TestCompletion.java
@@ -0,0 +1,71 @@
+/*
+ * Copyright (c) 2002-2007, Marc Prud'hommeaux. All rights reserved.
+ *
+ * This software is distributable under the BSD license. See the terms of the
+ * BSD license in the documentation provided with this software.
+ */
+package jline;
+
+import java.util.*;
+
+/**
+ *  Tests command history.
+ *
+ *  @author  <a href="mailto:mwp1 at cornell.edu">Marc Prud'hommeaux</a>
+ */
+public class TestCompletion extends JLineTestCase {
+    public TestCompletion(String test) {
+        super(test);
+    }
+
+    public void testSimpleCompletor() throws Exception {
+        // clear any current completors
+        for (Iterator i = console.getCompletors().iterator(); i.hasNext();
+                 console.removeCompletor((Completor) i.next())) {
+            ;
+        }
+
+        console.addCompletor
+            (new SimpleCompletor(new String[] { "foo", "bar", "baz" }));
+
+        assertBuffer("foo ", new Buffer("f").op(ConsoleReader.COMPLETE));
+        // single tab completes to unabbiguous "ba"
+        assertBuffer("ba", new Buffer("b").op(ConsoleReader.COMPLETE));
+        assertBuffer("ba", new Buffer("ba").op(ConsoleReader.COMPLETE));
+        assertBuffer("baz ", new Buffer("baz").op(ConsoleReader.COMPLETE));
+    }
+
+    public void testArgumentCompletor() throws Exception {
+        // clear any current completors
+        for (Iterator i = console.getCompletors().iterator(); i.hasNext();
+                 console.removeCompletor((Completor) i.next())) {
+            ;
+        }
+
+        console.addCompletor(new ArgumentCompletor
+            (new SimpleCompletor(new String[] { "foo", "bar", "baz" })));
+
+        assertBuffer("foo foo ", new Buffer("foo f").
+            op(ConsoleReader.COMPLETE));
+        assertBuffer("foo ba", new Buffer("foo b").
+            op(ConsoleReader.COMPLETE));
+        assertBuffer("foo ba", new Buffer("foo ba").
+            op(ConsoleReader.COMPLETE));
+        assertBuffer("foo baz ", new Buffer("foo baz").
+            op(ConsoleReader.COMPLETE));
+
+        // test completion in the mid range
+        assertBuffer("foo baz",
+            new Buffer("f baz").left().left().left().left().
+                op(ConsoleReader.COMPLETE));
+        assertBuffer("ba foo",
+            new Buffer("b foo").left().left().left().left().
+                op(ConsoleReader.COMPLETE));
+        assertBuffer("foo ba baz",
+            new Buffer("foo b baz").left().left().left().left().
+                op(ConsoleReader.COMPLETE));
+        assertBuffer("foo foo baz",
+            new Buffer("foo f baz").left().left().left().left().
+                op(ConsoleReader.COMPLETE));
+    }
+}
diff --git a/src/jline/src/test/java/jline/TestEditLine.java b/src/jline/src/test/java/jline/TestEditLine.java
new file mode 100644
index 0000000..88b4524
--- /dev/null
+++ b/src/jline/src/test/java/jline/TestEditLine.java
@@ -0,0 +1,160 @@
+/*
+ * Copyright (c) 2002-2007, Marc Prud'hommeaux. All rights reserved.
+ *
+ * This software is distributable under the BSD license. See the terms of the
+ * BSD license in the documentation provided with this software.
+ */
+package jline;
+
+
+/**
+ *  Tests various features of editing lines.
+ *
+ *  @author  <a href="mailto:mwp1 at cornell.edu">Marc Prud'hommeaux</a>
+ */
+public class TestEditLine extends JLineTestCase {
+    public TestEditLine(String test) {
+        super(test);
+    }
+
+    public void testDeletePreviousWord() throws Exception {
+        Buffer b = new Buffer("This is a test");
+
+        assertBuffer("This is a ", b = b.op(ConsoleReader.DELETE_PREV_WORD));
+        assertBuffer("This is ", b = b.op(ConsoleReader.DELETE_PREV_WORD));
+        assertBuffer("This ", b = b.op(ConsoleReader.DELETE_PREV_WORD));
+        assertBuffer("", b = b.op(ConsoleReader.DELETE_PREV_WORD));
+        assertBuffer("", b = b.op(ConsoleReader.DELETE_PREV_WORD));
+        assertBuffer("", b = b.op(ConsoleReader.DELETE_PREV_WORD));
+    }
+
+    public void testMoveToEnd() throws Exception {
+        Buffer b = new Buffer("This is a test");
+
+        assertBuffer("This is a XtestX",
+                     new Buffer("This is a test").op(ConsoleReader.PREV_WORD)
+                                                 .append('X')
+                                                 .op(ConsoleReader.MOVE_TO_END)
+                                                 .append('X'));
+
+        assertBuffer("This is Xa testX",
+                     new Buffer("This is a test").op(ConsoleReader.PREV_WORD)
+                                                 .op(ConsoleReader.PREV_WORD)
+                                                 .append('X')
+                                                 .op(ConsoleReader.MOVE_TO_END)
+                                                 .append('X'));
+
+        assertBuffer("This Xis a testX",
+                     new Buffer("This is a test").op(ConsoleReader.PREV_WORD)
+                                                 .op(ConsoleReader.PREV_WORD)
+                                                 .op(ConsoleReader.PREV_WORD)
+                                                 .append('X')
+                                                 .op(ConsoleReader.MOVE_TO_END)
+                                                 .append('X'));
+    }
+
+    public void testPreviousWord() throws Exception {
+        assertBuffer("This is a Xtest",
+                     new Buffer("This is a test").op(ConsoleReader.PREV_WORD)
+                                                 .append('X'));
+        assertBuffer("This is Xa test",
+                     new Buffer("This is a test").op(ConsoleReader.PREV_WORD)
+                                                 .op(ConsoleReader.PREV_WORD)
+                                                 .append('X'));
+        assertBuffer("This Xis a test",
+                     new Buffer("This is a test").op(ConsoleReader.PREV_WORD)
+                                                 .op(ConsoleReader.PREV_WORD)
+                                                 .op(ConsoleReader.PREV_WORD)
+                                                 .append('X'));
+        assertBuffer("XThis is a test",
+                     new Buffer("This is a test").op(ConsoleReader.PREV_WORD)
+                                                 .op(ConsoleReader.PREV_WORD)
+                                                 .op(ConsoleReader.PREV_WORD)
+                                                 .op(ConsoleReader.PREV_WORD)
+                                                 .append('X'));
+        assertBuffer("XThis is a test",
+                     new Buffer("This is a test").op(ConsoleReader.PREV_WORD)
+                                                 .op(ConsoleReader.PREV_WORD)
+                                                 .op(ConsoleReader.PREV_WORD)
+                                                 .op(ConsoleReader.PREV_WORD)
+                                                 .op(ConsoleReader.PREV_WORD)
+                                                 .append('X'));
+        assertBuffer("XThis is a test",
+                     new Buffer("This is a test").op(ConsoleReader.PREV_WORD)
+                                                 .op(ConsoleReader.PREV_WORD)
+                                                 .op(ConsoleReader.PREV_WORD)
+                                                 .op(ConsoleReader.PREV_WORD)
+                                                 .op(ConsoleReader.PREV_WORD)
+                                                 .op(ConsoleReader.PREV_WORD)
+                                                 .append('X'));
+    }
+
+    public void testLineStart() throws Exception {
+        assertBuffer("XThis is a test",
+                     new Buffer("This is a test").ctrlA().append('X'));
+        assertBuffer("TXhis is a test",
+                     new Buffer("This is a test").ctrlA().right().append('X'));
+    }
+
+    public void testClearLine() throws Exception {
+        assertBuffer("", new Buffer("This is a test").ctrlU());
+        assertBuffer("t", new Buffer("This is a test").left().ctrlU());
+        assertBuffer("st", new Buffer("This is a test").left().left().ctrlU());
+    }
+
+    public void testRight() throws Exception {
+        Buffer b = new Buffer("This is a test");
+        b = b.left().right().back();
+        assertBuffer("This is a tes", b);
+        b = b.left().left().left().right().left().back();
+        assertBuffer("This is ates", b);
+        b.append('X');
+        assertBuffer("This is aXtes", b);
+    }
+
+    public void testLeft() throws Exception {
+        Buffer b = new Buffer("This is a test");
+        b = b.left().left().left();
+        assertBuffer("This is a est", b = b.back());
+        assertBuffer("This is aest", b = b.back());
+        assertBuffer("This is est", b = b.back());
+        assertBuffer("This isest", b = b.back());
+        assertBuffer("This iest", b = b.back());
+        assertBuffer("This est", b = b.back());
+        assertBuffer("Thisest", b = b.back());
+        assertBuffer("Thiest", b = b.back());
+        assertBuffer("Thest", b = b.back());
+        assertBuffer("Test", b = b.back());
+        assertBuffer("est", b = b.back());
+        assertBuffer("est", b = b.back());
+        assertBuffer("est", b = b.back());
+        assertBuffer("est", b = b.back());
+        assertBuffer("est", b = b.back());
+    }
+
+    public void testBackspace() throws Exception {
+        Buffer b = new Buffer("This is a test");
+        assertBuffer("This is a tes", b = b.back());
+        assertBuffer("This is a te", b = b.back());
+        assertBuffer("This is a t", b = b.back());
+        assertBuffer("This is a ", b = b.back());
+        assertBuffer("This is a", b = b.back());
+        assertBuffer("This is ", b = b.back());
+        assertBuffer("This is", b = b.back());
+        assertBuffer("This i", b = b.back());
+        assertBuffer("This ", b = b.back());
+        assertBuffer("This", b = b.back());
+        assertBuffer("Thi", b = b.back());
+        assertBuffer("Th", b = b.back());
+        assertBuffer("T", b = b.back());
+        assertBuffer("", b = b.back());
+        assertBuffer("", b = b.back());
+        assertBuffer("", b = b.back());
+        assertBuffer("", b = b.back());
+        assertBuffer("", b = b.back());
+    }
+
+    public void testBuffer() throws Exception {
+        assertBuffer("This is a test", new Buffer("This is a test"));
+    }
+}
diff --git a/src/jline/src/test/java/jline/TestHistory.java b/src/jline/src/test/java/jline/TestHistory.java
new file mode 100644
index 0000000..a39afa5
--- /dev/null
+++ b/src/jline/src/test/java/jline/TestHistory.java
@@ -0,0 +1,76 @@
+/*
+ * Copyright (c) 2002-2007, Marc Prud'hommeaux. All rights reserved.
+ *
+ * This software is distributable under the BSD license. See the terms of the
+ * BSD license in the documentation provided with this software.
+ */
+package jline;
+
+
+/**
+ *  Tests command history.
+ *
+ *  @author  <a href="mailto:mwp1 at cornell.edu">Marc Prud'hommeaux</a>
+ */
+public class TestHistory extends JLineTestCase {
+    public TestHistory(String test) {
+        super(test);
+    }
+
+    public void testSingleHistory() throws Exception {
+        Buffer b = new Buffer().
+            append("test line 1").op(ConsoleReader.NEWLINE).
+            append("test line 2").op(ConsoleReader.NEWLINE).
+            append("test line 3").op(ConsoleReader.NEWLINE).
+            append("test line 4").op(ConsoleReader.NEWLINE).
+            append("test line 5").op(ConsoleReader.NEWLINE).
+            append("");
+
+        assertBuffer("", b);
+
+        assertBuffer("test line 5", b = b.op(ConsoleReader.PREV_HISTORY));
+        assertBuffer("test line 4", b = b.op(ConsoleReader.PREV_HISTORY));
+        assertBuffer("test line 5", b = b.op(ConsoleReader.NEXT_HISTORY));
+        assertBuffer("test line 4", b = b.op(ConsoleReader.PREV_HISTORY));
+        assertBuffer("test line 3", b = b.op(ConsoleReader.PREV_HISTORY));
+        assertBuffer("test line 2", b = b.op(ConsoleReader.PREV_HISTORY));
+        assertBuffer("test line 1", b = b.op(ConsoleReader.PREV_HISTORY));
+
+        // beginning of history
+        assertBuffer("test line 1", b = b.op(ConsoleReader.PREV_HISTORY));
+        assertBuffer("test line 1", b = b.op(ConsoleReader.PREV_HISTORY));
+        assertBuffer("test line 1", b = b.op(ConsoleReader.PREV_HISTORY));
+        assertBuffer("test line 1", b = b.op(ConsoleReader.PREV_HISTORY));
+
+        assertBuffer("test line 2", b = b.op(ConsoleReader.NEXT_HISTORY));
+        assertBuffer("test line 3", b = b.op(ConsoleReader.NEXT_HISTORY));
+        assertBuffer("test line 4", b = b.op(ConsoleReader.NEXT_HISTORY));
+        assertBuffer("test line 5", b = b.op(ConsoleReader.NEXT_HISTORY));
+
+        // end of history
+        assertBuffer("", b = b.op(ConsoleReader.NEXT_HISTORY));
+        assertBuffer("", b = b.op(ConsoleReader.NEXT_HISTORY));
+        assertBuffer("", b = b.op(ConsoleReader.NEXT_HISTORY));
+
+        assertBuffer("test line 5", b = b.op(ConsoleReader.PREV_HISTORY));
+        assertBuffer("test line 4", b = b.op(ConsoleReader.PREV_HISTORY));
+        b = b.op(ConsoleReader.MOVE_TO_BEG).append("XXX")
+             .op(ConsoleReader.NEWLINE);
+        assertBuffer("XXXtest line 4", b = b.op(ConsoleReader.PREV_HISTORY));
+        assertBuffer("test line 5", b = b.op(ConsoleReader.PREV_HISTORY));
+        assertBuffer("test line 4", b = b.op(ConsoleReader.PREV_HISTORY));
+        assertBuffer("test line 5", b = b.op(ConsoleReader.NEXT_HISTORY));
+        assertBuffer("XXXtest line 4", b = b.op(ConsoleReader.NEXT_HISTORY));
+        assertBuffer("", b = b.op(ConsoleReader.NEXT_HISTORY));
+
+        assertBuffer("XXXtest line 4", b = b.op(ConsoleReader.PREV_HISTORY));
+        assertBuffer("XXXtest line 4", b = b.op(ConsoleReader.NEWLINE).
+            op(ConsoleReader.PREV_HISTORY));
+        assertBuffer("XXXtest line 4", b = b.op(ConsoleReader.NEWLINE).
+            op(ConsoleReader.PREV_HISTORY));
+        assertBuffer("XXXtest line 4", b = b.op(ConsoleReader.NEWLINE).
+            op(ConsoleReader.PREV_HISTORY));
+        assertBuffer("XXXtest line 4", b = b.op(ConsoleReader.NEWLINE).
+            op(ConsoleReader.PREV_HISTORY));
+    }
+}
diff --git a/src/jline/src/test/java/jline/example/Example.java b/src/jline/src/test/java/jline/example/Example.java
new file mode 100644
index 0000000..80a8d99
--- /dev/null
+++ b/src/jline/src/test/java/jline/example/Example.java
@@ -0,0 +1,97 @@
+/*
+ * Copyright (c) 2002-2006, Marc Prud'hommeaux. All rights reserved.
+ *
+ * This software is distributable under the BSD license. See the terms of the
+ * BSD license in the documentation provided with this software.
+ */
+package jline.example;
+
+import jline.*;
+
+import java.io.*;
+import java.util.*;
+import java.util.zip.*;
+
+public class Example {
+    public static void usage() {
+        System.out.println("Usage: java " + Example.class.getName()
+                + " [none/simple/files/dictionary [trigger mask]]");
+        System.out.println("  none - no completors");
+        System.out.println("  simple - a simple completor that comples "
+                + "\"foo\", \"bar\", and \"baz\"");
+        System.out
+                .println("  files - a completor that comples " + "file names");
+        System.out.println("  dictionary - a completor that comples "
+                + "english dictionary words");
+        System.out.println("  classes - a completor that comples "
+                + "java class names");
+        System.out
+                .println("  trigger - a special word which causes it to assume "
+                        + "the next line is a password");
+        System.out.println("  mask - is the character to print in place of "
+                + "the actual password character");
+        System.out.println("\n  E.g - java Example simple su '*'\n"
+                + "will use the simple compleator with 'su' triggering\n"
+                + "the use of '*' as a password mask.");
+    }
+
+    public static void main(String[] args) throws IOException {
+        Character mask = null;
+        String trigger = null;
+
+        ConsoleReader reader = new ConsoleReader();
+        reader.setBellEnabled(false);
+        reader.setDebug(new PrintWriter(new FileWriter("writer.debug", true)));
+
+        if ((args == null) || (args.length == 0)) {
+            usage();
+
+            return;
+        }
+
+        List<Completor> completors = new LinkedList<Completor>();
+
+        if (args.length > 0) {
+            if (args[0].equals("none")) {
+            } else if (args[0].equals("files")) {
+                completors.add(new FileNameCompletor());
+            } else if (args[0].equals("classes")) {
+                completors.add(new ClassNameCompletor());
+            } else if (args[0].equals("dictionary")) {
+                completors.add(new SimpleCompletor(new GZIPInputStream(
+                        Example.class.getResourceAsStream("english.gz"))));
+            } else if (args[0].equals("simple")) {
+                completors.add(new SimpleCompletor(new String[] { "foo", "bar",
+                        "baz" }));
+            } else {
+                usage();
+
+                return;
+            }
+        }
+
+        if (args.length == 3) {
+            mask = new Character(args[2].charAt(0));
+            trigger = args[1];
+        }
+
+        reader.addCompletor(new ArgumentCompletor(completors));
+
+        String line;
+        PrintWriter out = new PrintWriter(System.out);
+
+        while ((line = reader.readLine("prompt> ")) != null) {
+            out.println("======>\"" + line + "\"");
+            out.flush();
+
+            // If we input the special word then we will mask
+            // the next line.
+            if ((trigger != null) && (line.compareTo(trigger) == 0)) {
+                line = reader.readLine("password> ", mask);
+            }
+            if (line.equalsIgnoreCase("quit") || line.equalsIgnoreCase("exit")) {
+                break;
+            }
+        }
+    }
+}
diff --git a/src/jline/src/test/java/jline/example/PasswordReader.java b/src/jline/src/test/java/jline/example/PasswordReader.java
new file mode 100644
index 0000000..1331855
--- /dev/null
+++ b/src/jline/src/test/java/jline/example/PasswordReader.java
@@ -0,0 +1,32 @@
+/*
+ * Copyright (c) 2002-2007, Marc Prud'hommeaux. All rights reserved.
+ *
+ * This software is distributable under the BSD license. See the terms of the
+ * BSD license in the documentation provided with this software.
+ */
+package jline.example;
+
+import jline.*;
+
+import java.io.*;
+
+public class PasswordReader {
+    public static void usage() {
+        System.out.println("Usage: java "
+            + PasswordReader.class.getName() + " [mask]");
+    }
+
+    public static void main(String[] args) throws IOException {
+        ConsoleReader reader = new ConsoleReader();
+
+        Character mask = (args.length == 0)
+            ? new Character((char) 0)
+            : new Character(args[0].charAt(0));
+
+        String line = null;
+        do {
+            line = reader.readLine("enter password> ", mask);
+            System.out.println("Got password: " + line);
+        } while(line != null && line.length() > 0);
+    }
+}
diff --git a/src/jline/src/test/resources/jline/example/english.gz b/src/jline/src/test/resources/jline/example/english.gz
new file mode 100644
index 0000000..f0a85c0
Binary files /dev/null and b/src/jline/src/test/resources/jline/example/english.gz differ
diff --git a/src/jvm14-actors/scala/actors/Actor.scala b/src/jvm14-actors/scala/actors/Actor.scala
deleted file mode 100644
index 06c9579..0000000
--- a/src/jvm14-actors/scala/actors/Actor.scala
+++ /dev/null
@@ -1,970 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2005-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: Actor.scala 16759 2008-12-15 10:19:01Z phaller $
-
-package scala.actors
-
-import scala.collection.mutable.{HashSet, Queue}
-import scala.compat.Platform
-
-import java.util.{Timer, TimerTask}
-
-/**
- * The <code>Actor</code> object provides functions for the definition of
- * actors, as well as actor operations, such as
- * <code>receive</code>, <code>react</code>, <code>reply</code>,
- * etc.
- *
- * @version 0.9.18
- * @author Philipp Haller
- */
-object Actor {
-
-  private[actors] val tl = new ThreadLocal[Actor]
-
-  private[actors] var timer = new Timer
-
-  /**
-   * Returns the currently executing actor. Should be used instead
-   * of <code>this</code> in all blocks of code executed by
-   * actors.
-   *
-   * @return returns the currently executing actor.
-   */
-  def self: Actor = {
-    var a = tl.get.asInstanceOf[Actor]
-    if (null eq a) {
-      a = new ActorProxy(currentThread)
-      tl.set(a)
-    }
-    a
-  }
-
-  /**
-   * Resets an actor proxy associated with the current thread.
-   * It replaces the implicit <code>ActorProxy</code> instance
-   * of the current thread (if any) with a new instance.
-   *
-   * This permits to re-use the current thread as an actor
-   * even if its <code>ActorProxy</code> has died for some reason.
-   */
-  def resetProxy {
-    val a = tl.get.asInstanceOf[Actor]
-    if ((null ne a) && a.isInstanceOf[ActorProxy])
-      tl.set(new ActorProxy(currentThread))
-  }
-
-  /**
-   * Removes any reference to an <code>Actor</code> instance
-   * currently stored in thread-local storage.
-   *
-   * This allows to release references from threads that are
-   * potentially long-running or being re-used (e.g. inside
-   * a thread pool). Permanent references in thread-local storage
-   * are a potential memory leak.
-   */
-  def clearSelf {
-    tl.set(null)
-  }
-
-  /**
-   * <p>This is a factory method for creating actors.</p>
-   *
-   * <p>The following example demonstrates its usage:</p>
-   *
-   * <pre>
-   * import scala.actors.Actor._
-   * ...
-   * val a = actor {
-   *   ...
-   * }
-   * </pre>
-   *
-   * @param  body  the code block to be executed by the newly created actor
-   * @return       the newly created actor. Note that it is automatically started.
-   */
-  def actor(body: => Unit): Actor = {
-    val actor = new Actor {
-      def act() = body
-    }
-    actor.start()
-    actor
-  }
-
-  /**
-   * <p>
-   * This is a factory method for creating actors whose
-   * body is defined using a <code>Responder</code>.
-   * </p>
-   *
-   * <p>The following example demonstrates its usage:</p>
-   *
-   * <pre>
-   * import scala.actors.Actor._
-   * import Responder.exec
-   * ...
-   * val a = reactor {
-   *   for {
-   *     res <- b !! MyRequest;
-   *     if exec(println("result: "+res))
-   *   } yield {}
-   * }
-   * </pre>
-   *
-   * @param  body  the <code>Responder</code> to be executed by the newly created actor
-   * @return       the newly created actor. Note that it is automatically started.
-   */
-  def reactor(body: => Responder[Unit]): Actor = {
-    val a = new Actor {
-      def act() {
-        Responder.run(body)
-      }
-    }
-    a.start()
-    a
-  }
-
-  /**
-   * Receives the next message from the mailbox of the current actor
-   * <code>self</code>.
-   */
-  def ? : Any = self.?
-
-  /**
-   * Receives a message from the mailbox of
-   * <code>self</code>. Blocks if no message matching any of the
-   * cases of <code>f</code> can be received.
-   *
-   * @param  f a partial function specifying patterns and actions
-   * @return   the result of processing the received message
-   */
-  def receive[A](f: PartialFunction[Any, A]): A =
-    self.receive(f)
-
-  /**
-   * Receives a message from the mailbox of
-   * <code>self</code>. Blocks at most <code>msec</code>
-   * milliseconds if no message matching any of the cases of
-   * <code>f</code> can be received. If no message could be
-   * received the <code>TIMEOUT</code> action is executed if
-   * specified.
-   *
-   * @param  msec the time span before timeout
-   * @param  f    a partial function specifying patterns and actions
-   * @return      the result of processing the received message
-   */
-  def receiveWithin[R](msec: Long)(f: PartialFunction[Any, R]): R =
-    self.receiveWithin(msec)(f)
-
-  /**
-   * Lightweight variant of <code>receive</code>.
-   *
-   * Actions in <code>f</code> have to contain the rest of the
-   * computation of <code>self</code>, as this method will never
-   * return.
-   *
-   * @param  f a partial function specifying patterns and actions
-   * @return   this function never returns
-   */
-  def react(f: PartialFunction[Any, Unit]): Nothing =
-    self.react(f)
-
-  /**
-   * Lightweight variant of <code>receiveWithin</code>.
-   *
-   * Actions in <code>f</code> have to contain the rest of the
-   * computation of <code>self</code>, as this method will never
-   * return.
-   *
-   * @param  msec the time span before timeout
-   * @param  f    a partial function specifying patterns and actions
-   * @return      this function never returns
-   */
-  def reactWithin(msec: Long)(f: PartialFunction[Any, Unit]): Nothing =
-    self.reactWithin(msec)(f)
-
-  def eventloop(f: PartialFunction[Any, Unit]): Nothing =
-    self.react(new RecursiveProxyHandler(self, f))
-
-  private class RecursiveProxyHandler(a: Actor, f: PartialFunction[Any, Unit])
-          extends PartialFunction[Any, Unit] {
-    def isDefinedAt(m: Any): Boolean =
-      true // events are immediately removed from the mailbox
-    def apply(m: Any) {
-      if (f.isDefinedAt(m)) f(m)
-      self.react(this)
-    }
-  }
-
-  /**
-   * Returns the actor which sent the last received message.
-   */
-  def sender: OutputChannel[Any] = self.sender
-
-  /**
-   * Send <code>msg</code> to the actor waiting in a call to
-   * <code>!?</code>.
-   */
-  def reply(msg: Any): Unit = self.reply(msg)
-
-  /**
-   * Send <code>()</code> to the actor waiting in a call to
-   * <code>!?</code>.
-   */
-  def reply(): Unit = self.reply(())
-
-  /**
-   * Returns the number of messages in <code>self</code>'s mailbox
-   *
-   * @return the number of messages in <code>self</code>'s mailbox
-   */
-  def mailboxSize: Int = self.mailboxSize
-
-  /**
-   * <p>
-   * Converts a synchronous event-based operation into
-   * an asynchronous <code>Responder</code>.
-   * </p>
-   *
-   * <p>The following example demonstrates its usage:</p>
-   * 
-   * <pre>
-   * val adder = reactor {
-   *   for {
-   *     _ <- respondOn(react) { case Add(a, b) => reply(a+b) }
-   *   } yield {}
-   * }
-   * </pre>
-   */
-  def respondOn[A, B](fun: PartialFunction[A, Unit] => Nothing):
-    PartialFunction[A, B] => Responder[B] =
-      (caseBlock: PartialFunction[A, B]) => new Responder[B] {
-        def respond(k: B => Unit) = fun(caseBlock andThen k)
-      }
-
-  private[actors] trait Body[a] {
-    def andThen[b](other: => b): Unit
-  }
-
-  implicit def mkBody[a](body: => a) = new Body[a] {
-    def andThen[b](other: => b): Unit = self.seq(body, other)
-  }
-
-  /**
-   * Causes <code>self</code> to repeatedly execute
-   * <code>body</code>.
-   *
-   * @param body the code block to be executed
-   */
-  def loop(body: => Unit): Unit = body andThen loop(body)
-
-  /**
-   * Causes <code>self</code> to repeatedly execute
-   * <code>body</code> while the condition
-   * <code>cond</code> is <code>true</code>.
-   *
-   * @param cond the condition to test
-   * @param body the code block to be executed
-   */
-  def loopWhile(cond: => Boolean)(body: => Unit): Unit =
-    if (cond) { body andThen loopWhile(cond)(body) }
-    else continue
-
-  /**
-   * Links <code>self</code> to actor <code>to</code>.
-   *
-   * @param  to the actor to link to
-   * @return 
-   */
-  def link(to: AbstractActor): AbstractActor = self.link(to)
-
-  /**
-   * Links <code>self</code> to actor defined by <code>body</code>.
-   *
-   * @param body ...
-   * @return     ...
-   */
-  def link(body: => Unit): Actor = self.link(body)
-
-  /**
-   * Unlinks <code>self</code> from actor <code>from</code>.
-   *
-   * @param from the actor to unlink from
-   */
-  def unlink(from: Actor): Unit = self.unlink(from)
-
-  /**
-   * <p>
-   *   Terminates execution of <code>self</code> with the following
-   *   effect on linked actors:
-   * </p>
-   * <p>
-   *   For each linked actor <code>a</code> with
-   *   <code>trapExit</code> set to <code>true</code>, send message
-   *   <code>Exit(self, reason)</code> to <code>a</code>.
-   * </p>
-   * <p>
-   *   For each linked actor <code>a</code> with
-   *   <code>trapExit</code> set to <code>false</code> (default),
-   *   call <code>a.exit(reason)</code> if
-   *   <code>reason != 'normal</code>.
-   * </p>
-   */
-  def exit(reason: AnyRef): Nothing = self.exit(reason)
-
-  /**
-   * <p>
-   *   Terminates execution of <code>self</code> with the following
-   *   effect on linked actors:
-   * </p>
-   * <p>
-   *   For each linked actor <code>a</code> with
-   *   <code>trapExit</code> set to <code>true</code>, send message
-   *   <code>Exit(self, 'normal)</code> to <code>a</code>.
-   * </p>
-   */
-  def exit(): Nothing = self.exit()
-
-  def continue: Unit = throw new KillActorException
-}
-
-/**
- * <p>
- *   This class provides an implementation of event-based actors.
- *   The main ideas of our approach are explained in the two papers
- * </p>
- * <ul>
- *   <li>
- *     <a href="http://lampwww.epfl.ch/~odersky/papers/jmlc06.pdf">
- *     <span style="font-weight:bold; white-space:nowrap;">Event-Based
- *     Programming without Inversion of Control</span></a>,<br/>
- *     Philipp Haller and Martin Odersky, <i>Proc. JMLC 2006</i>, and
- *   </li>
- *   <li>
- *     <a href="http://lamp.epfl.ch/~phaller/doc/haller07coord.pdf">
- *     <span style="font-weight:bold; white-space:nowrap;">Actors that
- *     Unify Threads and Events</span></a>,<br/>
- *     Philipp Haller and Martin Odersky, <i>Proc. COORDINATION 2007</i>.
- *   </li>
- * </ul>
- *
- * @version 0.9.18
- * @author Philipp Haller
- */
- at serializable
-trait Actor extends AbstractActor {
-
-  private var received: Option[Any] = None
-
-  private val waitingForNone = (m: Any) => false
-  private var waitingFor: Any => Boolean = waitingForNone
-  private var isSuspended = false
-
-  protected val mailbox = new MessageQueue
-  private var sessions: List[OutputChannel[Any]] = Nil
-
-  protected def scheduler: IScheduler =
-    Scheduler
-
-  /**
-   * Returns the number of messages in this actor's mailbox
-   *
-   * @return the number of messages in this actor's mailbox
-   */
-  def mailboxSize: Int = synchronized {
-    mailbox.size
-  }
-
-  /**
-   * Sends <code>msg</code> to this actor (asynchronous) supplying
-   * explicit reply destination.
-   *
-   * @param  msg      the message to send
-   * @param  replyTo  the reply destination
-   */
-  def send(msg: Any, replyTo: OutputChannel[Any]) = synchronized {
-    tick()
-    if (waitingFor(msg)) {
-      received = Some(msg)
-
-      if (isSuspended)
-        sessions = replyTo :: sessions
-      else
-        sessions = List(replyTo)
-
-      waitingFor = waitingForNone
-
-      if (!onTimeout.isEmpty) {
-        onTimeout.get.cancel()
-        onTimeout = None
-      }
-
-      if (isSuspended)
-        resumeActor()
-      else // assert continuation != null
-        scheduler.execute(new Reaction(this, continuation, msg))
-    } else {
-      mailbox.append(msg, replyTo)
-    }
-  }
-
-  /**
-   * Receives a message from this actor's mailbox.
-   *
-   * @param  f    a partial function with message patterns and actions
-   * @return      result of processing the received value
-   */
-  def receive[R](f: PartialFunction[Any, R]): R = {
-    assert(Actor.self == this, "receive from channel belonging to other actor")
-    if (shouldExit) exit() // links
-    this.synchronized {
-      tick()
-      val qel = mailbox.extractFirst((m: Any) => f.isDefinedAt(m))
-      if (null eq qel) {
-        waitingFor = f.isDefinedAt
-        isSuspended = true
-        suspendActor()
-      } else {
-        received = Some(qel.msg)
-        sessions = qel.session :: sessions
-      }
-      waitingFor = waitingForNone
-      isSuspended = false
-    }
-    val result = f(received.get)
-    sessions = sessions.tail
-    result
-  }
-
-  /**
-   * Receives a message from this actor's mailbox within a certain
-   * time span.
-   *
-   * @param  msec the time span before timeout
-   * @param  f    a partial function with message patterns and actions
-   * @return      result of processing the received value
-   */
-  def receiveWithin[R](msec: Long)(f: PartialFunction[Any, R]): R = {
-    assert(Actor.self == this, "receive from channel belonging to other actor")
-    if (shouldExit) exit() // links
-    this.synchronized {
-      tick()
-      // first, remove spurious TIMEOUT message from mailbox if any
-      val spurious = mailbox.extractFirst((m: Any) => m == TIMEOUT)
-
-      val qel = mailbox.extractFirst((m: Any) => f.isDefinedAt(m))
-      if (null eq qel) {
-        if (msec == 0) {
-          if (f.isDefinedAt(TIMEOUT))
-            return f(TIMEOUT)
-          else
-            error("unhandled timeout")
-        }
-        else {
-          waitingFor = f.isDefinedAt
-          isSuspended = true
-          received = None
-          suspendActorFor(msec)
-          if (received.isEmpty) {
-            if (f.isDefinedAt(TIMEOUT)) {
-              waitingFor = waitingForNone
-              isSuspended = false
-              val result = f(TIMEOUT)
-              return result
-            }
-            else
-              error("unhandled timeout")
-          }
-        }
-      } else {
-        received = Some(qel.msg)
-        sessions = qel.session :: sessions
-      }
-      waitingFor = waitingForNone
-      isSuspended = false
-    }
-    val result = f(received.get)
-    sessions = sessions.tail
-    result
-  }
-
-  /**
-   * Receives a message from this actor's mailbox.
-   * <p>
-   * This method never returns. Therefore, the rest of the computation
-   * has to be contained in the actions of the partial function.
-   *
-   * @param  f    a partial function with message patterns and actions
-   */
-  def react(f: PartialFunction[Any, Unit]): Nothing = {
-    assert(Actor.self == this, "react on channel belonging to other actor")
-    if (shouldExit) exit() // links
-    this.synchronized {
-      tick()
-      val qel = mailbox.extractFirst((m: Any) => f.isDefinedAt(m))
-      if (null eq qel) {
-        waitingFor = f.isDefinedAt
-        continuation = f
-        isDetached = true
-      } else {
-        sessions = List(qel.session)
-        scheduleActor(f, qel.msg)
-      }
-      throw new SuspendActorException
-    }
-  }
-
-  /**
-   * Receives a message from this actor's mailbox within a certain
-   * time span.
-   * <p>
-   * This method never returns. Therefore, the rest of the computation
-   * has to be contained in the actions of the partial function.
-   *
-   * @param  msec the time span before timeout
-   * @param  f    a partial function with message patterns and actions
-   */
-  def reactWithin(msec: Long)(f: PartialFunction[Any, Unit]): Nothing = {
-    assert(Actor.self == this, "react on channel belonging to other actor")
-    if (shouldExit) exit() // links
-    this.synchronized {
-      tick()
-      // first, remove spurious TIMEOUT message from mailbox if any
-      val spurious = mailbox.extractFirst((m: Any) => m == TIMEOUT)
-
-      val qel = mailbox.extractFirst((m: Any) => f.isDefinedAt(m))
-      if (null eq qel) {
-        if (msec == 0) {
-          if (f.isDefinedAt(TIMEOUT)) {
-            sessions = List(Actor.self)
-            scheduleActor(f, TIMEOUT)
-          }
-          else
-            error("unhandled timeout")
-        }
-        else {
-          waitingFor = f.isDefinedAt
-
-          val thisActor = this
-          onTimeout = Some(new TimerTask {
-            def run() { thisActor ! TIMEOUT }
-          })
-          Actor.timer.schedule(onTimeout.get, msec)
-
-          continuation = f
-          isDetached = true
-        }
-      } else {
-        sessions = List(qel.session)
-        scheduleActor(f, qel.msg)
-      }
-      throw new SuspendActorException
-    }
-  }
-
-  /**
-   * The behavior of an actor is specified by implementing this
-   * abstract method. Note that the preferred way to create actors
-   * is through the <code>actor</code> method
-   * defined in object <code>Actor</code>.
-   */
-  def act(): Unit
-
-  /**
-   * Sends <code>msg</code> to this actor (asynchronous).
-   */
-  def !(msg: Any) {
-    send(msg, Actor.self)
-  }
-
-  /**
-   * Forwards <code>msg</code> to this actor (asynchronous).
-   */
-  def forward(msg: Any) {
-    send(msg, Actor.sender)
-  }
-
-  /**
-   * Sends <code>msg</code> to this actor and awaits reply
-   * (synchronous).
-   *
-   * @param  msg the message to be sent
-   * @return     the reply
-   */
-  def !?(msg: Any): Any = {
-    val replyCh = Actor.self.freshReplyChannel
-    send(msg, replyCh)
-    replyCh.receive {
-      case x => x
-    }
-  }
-
-  /**
-   * Sends <code>msg</code> to this actor and awaits reply
-   * (synchronous) within <code>msec</code> milliseconds.
-   *
-   * @param  msec the time span before timeout
-   * @param  msg  the message to be sent
-   * @return      <code>None</code> in case of timeout, otherwise
-   *              <code>Some(x)</code> where <code>x</code> is the reply
-   */
-  def !?(msec: Long, msg: Any): Option[Any] = {
-    val replyCh = Actor.self.freshReplyChannel
-    send(msg, replyCh)
-    replyCh.receiveWithin(msec) {
-      case TIMEOUT => None
-      case x => Some(x)
-    }
-  }
-
-  /**
-   * Sends <code>msg</code> to this actor and immediately
-   * returns a future representing the reply value.
-   */
-  def !!(msg: Any): Future[Any] = {
-    val ftch = new Channel[Any](Actor.self)
-    send(msg, ftch)
-    new Future[Any](ftch) {
-      def apply() =
-        if (isSet) value.get
-        else ch.receive {
-          case any => value = Some(any); any
-        }
-      def respond(k: Any => Unit): Unit =
- 	if (isSet) k(value.get)
- 	else ch.react {
- 	  case any => value = Some(any); k(any)
- 	}
-      def isSet = value match {
-        case None => ch.receiveWithin(0) {
-          case TIMEOUT => false
-          case any => value = Some(any); true
-        }
-        case Some(_) => true
-      }
-    }
-  }
-
-  /**
-   * Sends <code>msg</code> to this actor and immediately
-   * returns a future representing the reply value.
-   * The reply is post-processed using the partial function
-   * <code>f</code>. This also allows to recover a more
-   * precise type for the reply value.
-   */
-  def !![A](msg: Any, f: PartialFunction[Any, A]): Future[A] = {
-    val ftch = new Channel[Any](Actor.self)
-    send(msg, ftch)
-    new Future[A](ftch) {
-      def apply() =
-        if (isSet) value.get.asInstanceOf[A]
-        else ch.receive {
-          case any => value = Some(f(any)); value.get.asInstanceOf[A]
-        }
-      def respond(k: A => Unit): Unit =
- 	if (isSet) k(value.get.asInstanceOf[A])
- 	else ch.react {
- 	  case any => value = Some(f(any)); k(value.get.asInstanceOf[A])
- 	}
-      def isSet = value match {
-        case None => ch.receiveWithin(0) {
-          case TIMEOUT => false
-          case any => value = Some(f(any)); true
-        }
-        case Some(_) => true
-      }
-    }
-  }
-
-  /**
-   * Replies with <code>msg</code> to the sender.
-   */
-  def reply(msg: Any) {
-    sender ! msg
-  }
-
-  private var rc: Channel[Any] = null
-  private[actors] def replyChannel = rc
-  private[actors] def freshReplyChannel: Channel[Any] =
-    { rc = new Channel[Any](this); rc }
-
-  /**
-   * Receives the next message from this actor's mailbox.
-   */
-  def ? : Any = receive {
-    case x => x
-  }
-
-  def sender: OutputChannel[Any] = sessions.head
-
-  def receiver: Actor = this
-
-  private var continuation: PartialFunction[Any, Unit] = null
-  private var onTimeout: Option[TimerTask] = None
-  // accessed in Reaction
-  private[actors] var isDetached = false
-  private var isWaiting = false
-
-  // guarded by lock of this
-  protected def scheduleActor(f: PartialFunction[Any, Unit], msg: Any) =
-    if ((f eq null) && (continuation eq null)) {
-      // do nothing (timeout is handled instead)
-    }
-    else {
-      val task = new Reaction(this,
-                              if (f eq null) continuation else f,
-                              msg)
-      scheduler execute task
-    }
-
-  private def tick(): Unit =
-    scheduler tick this
-
-  private[actors] var kill: () => Unit = () => {}
-
-  private def suspendActor() {
-    isWaiting = true
-    while (isWaiting) {
-      try {
-        wait()
-      } catch {
-        case _: InterruptedException =>
-      }
-    }
-    // links: check if we should exit
-    if (shouldExit) exit()
-  }
-
-  private def suspendActorFor(msec: Long) {
-    val ts = Platform.currentTime
-    var waittime = msec
-    var fromExc = false
-    isWaiting = true
-    while (isWaiting) {
-      try {
-        fromExc = false
-        wait(waittime)
-      } catch {
-        case _: InterruptedException => {
-          fromExc = true
-          val now = Platform.currentTime
-          val waited = now-ts
-          waittime = msec-waited
-          if (waittime < 0) { isWaiting = false }
-        }
-      }
-      if (!fromExc) { isWaiting = false }
-    }
-    // links: check if we should exit
-    if (shouldExit) exit()
-  }
-
-  private def resumeActor() {
-    isWaiting = false
-    notify()
-  }
-
-  /**
-   * Starts this actor.
-   */
-  def start(): Actor = synchronized {
-    // Reset various flags.
-    //
-    // Note that we do *not* reset `trapExit`. The reason is that
-    // users should be able to set the field in the constructor
-    // and before `act` is called.
-
-    exitReason = 'normal
-    exiting = false
-    shouldExit = false
-
-    scheduler execute {
-      ActorGC.newActor(Actor.this)
-      (new Reaction(Actor.this)).run()
-    }
-
-    this
-  }
-
-  private def seq[a, b](first: => a, next: => b): Unit = {
-    val s = Actor.self
-    val killNext = s.kill
-    s.kill = () => {
-      s.kill = killNext
-
-      // to avoid stack overflow:
-      // instead of directly executing `next`,
-      // schedule as continuation
-      scheduleActor({ case _ => next }, 1)
-      throw new SuspendActorException
-    }
-    first
-    throw new KillActorException
-  }
-
-  private[actors] var links: List[AbstractActor] = Nil
-
-  /**
-   * Links <code>self</code> to actor <code>to</code>.
-   *
-   * @param to ...
-   * @return   ...
-   */
-  def link(to: AbstractActor): AbstractActor = {
-    assert(Actor.self == this, "link called on actor different from self")
-    synchronized {
-      links = to :: links
-    }
-    to.linkTo(this)
-    to
-  }
-
-  /**
-   * Links <code>self</code> to actor defined by <code>body</code>.
-   */
-  def link(body: => Unit): Actor = {
-    val actor = new Actor {
-      def act() = body
-    }
-    link(actor)
-    actor.start()
-    actor
-  }
-
-  private[actors] def linkTo(to: AbstractActor) = synchronized {
-    links = to :: links
-  }
-
-  /**
-   * Unlinks <code>self</code> from actor <code>from</code>.
-   */
-  def unlink(from: AbstractActor) {
-    assert(Actor.self == this, "unlink called on actor different from self")
-    synchronized {
-      links = links.remove(from.==)
-    }
-    from.unlinkFrom(this)
-  }
-
-  private[actors] def unlinkFrom(from: AbstractActor) = synchronized {
-    links = links.remove(from.==)
-  }
-
-  var trapExit = false
-  private[actors] var exitReason: AnyRef = 'normal
-  private[actors] var shouldExit = false
-
-  /**
-   * <p>
-   *   Terminates execution of <code>self</code> with the following
-   *   effect on linked actors:
-   * </p>
-   * <p>
-   *   For each linked actor <code>a</code> with
-   *   <code>trapExit</code> set to <code>true</code>, send message
-   *   <code>Exit(self, reason)</code> to <code>a</code>.
-   * </p>
-   * <p>
-   *   For each linked actor <code>a</code> with
-   *   <code>trapExit</code> set to <code>false</code> (default),
-   *   call <code>a.exit(reason)</code> if
-   *   <code>reason != 'normal</code>.
-   * </p>
-   */
-  def exit(reason: AnyRef): Nothing = {
-    exitReason = reason
-    exit()
-  }
-
-  /**
-   * Terminates with exit reason <code>'normal</code>.
-   */
-  def exit(): Nothing = {
-    // links
-    if (!links.isEmpty)
-      exitLinked()
-    throw new ExitActorException
-  }
-
-  // Assume !links.isEmpty
-  private[actors] def exitLinked() {
-    exiting = true
-    // remove this from links
-    val mylinks = links.remove(this.==)
-    // exit linked processes
-    mylinks.foreach((linked: AbstractActor) => {
-      unlink(linked)
-      if (!linked.exiting)
-        linked.exit(this, exitReason)
-    })
-  }
-
-  // Assume !links.isEmpty
-  private[actors] def exitLinked(reason: AnyRef) {
-    exitReason = reason
-    exitLinked()
-  }
-
-  // Assume !this.exiting
-  private[actors] def exit(from: AbstractActor, reason: AnyRef) {
-    if (trapExit) {
-      this ! Exit(from, reason)
-    }
-    else if (reason != 'normal)
-      this.synchronized {
-        shouldExit = true
-        exitReason = reason
-        if (isSuspended)
-          resumeActor()
-        else if (isDetached)
-          scheduleActor(null, null)
-      }
-  }
-
-}
-
-
-/** <p>
- *    This object is used as the timeout pattern in
- *    <a href="Actor.html#receiveWithin(Long)" target="contentFrame">
- *    <code>receiveWithin</code></a> and
- *    <a href="Actor.html#reactWithin(Long)" target="contentFrame">
- *    <code>reactWithin</code></a>.
- *  </p>
- *  <p>
- *    The following example demonstrates its usage:
- *  </p><pre>
- *    receiveWithin(500) {
- *      <b>case</b> (x, y) <b>=></b> ...
- *      <b>case</b> TIMEOUT <b>=></b> ...
- *    }</pre>
- *
- *  @version 0.9.8
- *  @author Philipp Haller
- */
-case object TIMEOUT
-
-
-case class Exit(from: AbstractActor, reason: AnyRef)
-
-/** <p>
- *    This class is used to manage control flow of actor
- *    executions.
- *  </p>
- *
- * @version 0.9.8
- * @author Philipp Haller
- */
-private[actors] class SuspendActorException extends Throwable {
-  /*
-   * For efficiency reasons we do not fill in
-   * the execution stack trace.
-   */
-  override def fillInStackTrace(): Throwable = this
-}
diff --git a/src/jvm14-actors/scala/actors/FJTaskScheduler2.scala b/src/jvm14-actors/scala/actors/FJTaskScheduler2.scala
deleted file mode 100644
index 95007b5..0000000
--- a/src/jvm14-actors/scala/actors/FJTaskScheduler2.scala
+++ /dev/null
@@ -1,179 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2005-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: FJTaskScheduler2.scala 16171 2008-09-29 09:28:09Z phaller $
-
-package scala.actors
-
-import compat.Platform
-
-import java.lang.{Runnable, Thread, InterruptedException, System, Runtime}
-
-import scala.collection.Set
-import scala.collection.mutable.{ArrayBuffer, Buffer, HashMap, Queue, Stack, HashSet}
-
-/**
- * FJTaskScheduler2
- *
- * @version 0.9.19
- * @author Philipp Haller
- */
-class FJTaskScheduler2 extends Thread with IScheduler {
-  // as long as this thread runs, JVM should not exit
-  setDaemon(false)
-
-  var printStats = false
-
-  val rt = Runtime.getRuntime()
-  val minNumThreads = 4
-
-  val coreProp = try {
-    System.getProperty("actors.corePoolSize")
-  } catch {
-    case ace: java.security.AccessControlException =>
-      null
-  }
-  val maxProp =
-    try {
-      System.getProperty("actors.maxPoolSize")
-    } catch {
-      case ace: java.security.AccessControlException =>
-        null
-    }
-
-  val initCoreSize =
-    if (null ne coreProp) Integer.parseInt(coreProp)
-    else {
-      val numCores = rt.availableProcessors()
-      if (2 * numCores > minNumThreads)
-        2 * numCores
-      else
-        minNumThreads
-    }
-
-  val maxSize =
-    if (null ne maxProp) Integer.parseInt(maxProp)
-    else 256
-
-  private var coreSize = initCoreSize
-
-  private val executor =
-    new FJTaskRunnerGroup(coreSize)
-
-  @volatile private var terminating = false
-  private var suspending = false
-
-  private var lastActivity = Platform.currentTime
-
-  private var submittedTasks = 0
-
-  def printActorDump {}
-
-  private val TICK_FREQ = 50
-  private val CHECK_FREQ = 100
-
-  def onLockup(handler: () => Unit) =
-    lockupHandler = handler
-
-  def onLockup(millis: Int)(handler: () => Unit) = {
-    //LOCKUP_CHECK_FREQ = millis / CHECK_FREQ
-    lockupHandler = handler
-  }
-
-  private var lockupHandler: () => Unit = null
-
-  override def run() {
-    try {
-      while (!terminating) {
-        this.synchronized {
-          try {
-            wait(CHECK_FREQ)
-          } catch {
-            case _: InterruptedException =>
-              if (terminating) throw new QuitException
-          }
-
-          if (!suspending) {
-
-            // check if we need more threads
-            if (Platform.currentTime - lastActivity >= TICK_FREQ
-                && coreSize < maxSize
-                && executor.checkPoolSize()) {
-                  //Debug.info(this+": increasing thread pool size")
-                  coreSize += 1
-                  lastActivity = Platform.currentTime
-                }
-            else {
-              if (ActorGC.allTerminated) {
-                // if all worker threads idle terminate
-                if (executor.getActiveCount() == 0) {
-                  Debug.info(this+": initiating shutdown...")
-
-                  // Note that we don't have to shutdown
-                  // the FJTaskRunnerGroup since there is
-                  // no separate thread associated with it,
-                  // and FJTaskRunner threads have daemon status.
-
-                  // terminate timer thread
-                  Actor.timer.cancel()
-                  terminating = true
-                  throw new QuitException
-                }
-              }
-            }
-          }
-        } // sync
-
-      } // while (!terminating)
-    } catch {
-      case _: QuitException =>
-        // allow thread to exit
-        if (printStats) executor.stats()
-    }
-  }
-
-  /**
-   *  @param  task the task to be executed
-   */
-  def execute(task: Runnable): Unit =
-    executor execute task
-
-  def execute(fun: => Unit): Unit =
-    executor.execute(new Runnable {
-      def run() { fun }
-    })
-
-  private var tickCnt = 0
-
-  /**
-   *  @param  a the actor
-   */
-  def tick(a: Actor) = synchronized {
-    if (tickCnt == 100) {
-      tickCnt = 0
-      lastActivity = Platform.currentTime
-    } else
-      tickCnt += 1
-  }
-
-  /** Shuts down all idle worker threads.
-   */
-  def shutdown(): Unit = synchronized {
-    terminating = true
-    // terminate timer thread
-    Actor.timer.cancel()
-  }
-
-  def snapshot(): LinkedQueue = {
-    suspending = true
-    executor.snapshot()
-  }
-
-  private[actors] override def isActive =
-    !terminating
-}
diff --git a/src/jvm14-library/scala/BigDecimal.scala b/src/jvm14-library/scala/BigDecimal.scala
deleted file mode 100644
index b620a43..0000000
--- a/src/jvm14-library/scala/BigDecimal.scala
+++ /dev/null
@@ -1,269 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2007-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: BigDecimal.scala 15937 2008-08-26 13:48:19Z michelou $
-
-package scala
-
-import java.math.{BigDecimal => BigDec}
-
-/** 
- *  @author  Stephane Micheloud
- *  @version 1.0
- */
-object BigDecimal {
-
-  @serializable
-  object RoundingMode extends Enumeration {
-    type RoundingMode = Value
-    val ROUND_UP, ROUND_DOWN, ROUND_CEILING, ROUND_FLOOR, ROUND_HALF_UP,
-        ROUND_HALF_DOWN, ROUND_HALF_EVEN, ROUND_UNNECESSARY = Value
-  }
-
-  private val minCached = -512
-  private val maxCached = 512
-  private lazy val cache = new Array[BigDecimal](maxCached - minCached + 1)
-
-  /** Constructs a <code>BigDecimal</code> whose value is equal to that of the
-   *  specified <code>Integer</code> value.
-   *
-   *  @param i the specified integer value
-   *  @return  the constructed <code>BigDecimal</code>
-   */
-  def apply(i: Int): BigDecimal =
-    if (minCached <= i && i <= maxCached) {
-      val offset = i - minCached
-      var n = cache(offset)
-      if (n eq null) { n = new BigDecimal(BigDec.valueOf(i)); cache(offset) = n }
-      n
-    } else new BigDecimal(BigDec.valueOf(i))
-
-  /** Constructs a <code>BigDecimal</code> whose value is equal to that of the
-   *  specified long value.
-   *
-   *  @param l the specified long value
-   *  @return  the constructed <code>BigDecimal</code>
-   */
-  def apply(l: Long): BigDecimal =
-    if (minCached <= l && l <= maxCached) apply(l.toInt)
-    else new BigDecimal(BigDec.valueOf(l))
-
-  /** Constructs a <code>BigDecimal</code> whose value is equal to that of the
-   *  specified double value.
-   *
-   *  @param d the specified <code>Double</code> value
-   *  @return  the constructed <code>BigDecimal</code>
-   */
-  def apply(d: Double): BigDecimal =
-    new BigDecimal(new BigDec(d))
-
-  /** Translates a character array representation of a <code>BigDecimal</code>
-   *  into a <code>BigDecimal</code>.
-   */
-  def apply(x: Array[Char]): BigDecimal = 
-    new BigDecimal(new BigDec(x.toString))
-
-  /** Translates the decimal String representation of a <code>BigDecimal</code>
-   *  into a <code>BigDecimal</code>.
-   */
-  def apply(x: String): BigDecimal = 
-    new BigDecimal(new BigDec(x))
-
-  /** Constructs a <code>BigDecimal</code> whose value is equal to that of the
-   *  specified <code>BigInt</code> value.
-   *
-   *  @param x the specified <code>BigInt</code> value
-   *  @return  the constructed <code>BigDecimal</code>
-   */
-  def apply(x: BigInt): BigDecimal =
-    new BigDecimal(new BigDec(x.bigInteger))
-
-  /** Implicit conversion from <code>Int</code> to <code>BigDecimal</code>. */
-  implicit def int2bigDecimal(i: Int): BigDecimal = apply(i)
-
-  /** Implicit conversion from <code>Long</code> to <code>BigDecimal</code>. */
-  implicit def long2bigDecimal(l: Long): BigDecimal = apply(l)
-
-  /** Implicit conversion from <code>Double</code> to <code>BigDecimal</code>. */
-  implicit def double2bigDecimal(d: Double): BigDecimal = apply(d)
-
-  /** Implicit conversion from BigDecimal to <code>Ordered</code>. */
-  implicit def bigDecimal2ordered(x: BigDecimal): Ordered[BigDecimal] =
-    new Ordered[BigDecimal] with Proxy {
-      def self: Any = x
-      def compare(y: BigDecimal): Int = x.bigDecimal.compareTo(y.bigDecimal)
-    }
-}
-
-/** 
- *  @author  Stephane Micheloud
- *  @version 1.0
- */
- at serializable
-class BigDecimal(val bigDecimal: BigDec) extends java.lang.Number {
-  import BigDecimal.RoundingMode._
-
-  /** Returns the hash code for this BigDecimal. */
-  override def hashCode(): Int = this.bigDecimal.hashCode()
-
-  /** Compares this BigDecimal with the specified value for equality.
-   */
-  override def equals(that: Any): Boolean = that match {
-    case that: BigDecimal => this equals that
-    case that: java.lang.Double => this.bigDecimal.doubleValue == that.doubleValue
-    case that: java.lang.Float  => this.bigDecimal.floatValue == that.floatValue
-    case that: java.lang.Number => this equals BigDecimal(that.longValue)
-    case that: java.lang.Character => this equals BigDecimal(that.charValue.asInstanceOf[Int])
-    case _ => false
-  }
-
-  /** Compares this BigDecimal with the specified BigDecimal for equality.
-   */
-  def equals (that: BigDecimal): Boolean =
-    this.bigDecimal.compareTo(that.bigDecimal) == 0
-
-  /** Compares this BigDecimal with the specified BigDecimal
-   */
-  def compare (that: BigDecimal): Int = this.bigDecimal.compareTo(that.bigDecimal)
-
-  /** Less-than-or-equals comparison of BigDecimals
-   */
-  def <= (that: BigDecimal): Boolean = this.bigDecimal.compareTo(that.bigDecimal) <= 0
-
-  /** Greater-than-or-equals comparison of BigDecimals
-   */
-  def >= (that: BigDecimal): Boolean = this.bigDecimal.compareTo(that.bigDecimal) >= 0
-
-  /** Less-than of BigDecimals
-   */
-  def <  (that: BigDecimal): Boolean = this.bigDecimal.compareTo(that.bigDecimal) <  0
-
-  /** Greater-than comparison of BigDecimals
-   */
-  def >  (that: BigDecimal): Boolean = this.bigDecimal.compareTo(that.bigDecimal) > 0
-
-  /** Addition of BigDecimals
-   */
-  def +  (that: BigDecimal): BigDecimal =
-    new BigDecimal(this.bigDecimal.add(that.bigDecimal))
-
-  /** Subtraction of BigDecimals
-   */
-  def -  (that: BigDecimal): BigDecimal =
-    new BigDecimal(this.bigDecimal.subtract(that.bigDecimal))
-
-  /** Multiplication of BigDecimals
-   */
-  def *  (that: BigDecimal): BigDecimal =
-    new BigDecimal(this.bigDecimal.multiply(that.bigDecimal))
-
-  /** Division of BigDecimals. Default rounding mode is <code>ROUND_HALF_UP</code>
-   *  (same value as <code>MathContext.DEFAULT_ROUNDINGMODE</code> (private)
-   *  in Java 1.5 or newer).
-   */
-  def /  (that: BigDecimal): BigDecimal =
-    new BigDecimal(this.bigDecimal.divide(that.bigDecimal, BigDec.ROUND_HALF_UP))
-
-  /** Returns the minimum of this and that
-   */
-  def min (that: BigDecimal): BigDecimal =
-    new BigDecimal(this.bigDecimal.min(that.bigDecimal))
-
-  /** Returns the maximum of this and that
-   */
-  def max (that: BigDecimal): BigDecimal =
-    new BigDecimal(this.bigDecimal.max(that.bigDecimal))
-
-  /** Returns a BigDecimal whose value is the negation of this BigDecimal
-   */
-  def unary_- : BigDecimal = new BigDecimal(this.bigDecimal.negate())
-  
-  /** Returns the absolute value of this BigDecimal
-   */
-  def abs: BigDecimal = new BigDecimal(this.bigDecimal.abs())
-
-  /** Returns the sign of this BigDecimal, i.e. 
-   *   -1 if it is less than 0, 
-   *   +1 if it is greater than 0
-   *   0  if it is equal to 0
-   */
-  def signum: Int = this.bigDecimal.signum()
-
-  /** Returns the scale of this <code>BigDecimal</code>.
-   */
-  def scale: Int = this.bigDecimal.scale()
-
-  /** Returns a <code>BigDecimal</code> whose scale is the specified value, and whose value is
-   *  numerically equal to this BigDecimal's.
-   */
-  def setScale(scale: Int): BigDecimal =
-    new BigDecimal(this.bigDecimal setScale scale)
-
-  def setScale(scale: Int, mode: RoundingMode): BigDecimal =
-    new BigDecimal(this.bigDecimal.setScale(scale, mode.id))
-
-  /** Converts this BigDecimal to a <tt>byte</tt>. 
-   *  If the BigDecimal is too big to fit in a byte, only the low-order 8 bits are returned. 
-   *  Note that this conversion can lose information about the overall magnitude of the 
-   *  BigDecimal value as well as return a result with the opposite sign.
-   */
-  override def byteValue   = intValue.toByte
-
-  /** Converts this BigDecimal to a <tt>short</tt>. 
-   *  If the BigDecimal is too big to fit in a byte, only the low-order 16 bits are returned. 
-   *  Note that this conversion can lose information about the overall magnitude of the 
-   *  BigDecimal value as well as return a result with the opposite sign.
-   */
-  override def shortValue  = intValue.toShort
-
-  /** Converts this BigDecimal to a <tt>char</tt>. 
-   *  If the BigDecimal is too big to fit in a char, only the low-order 16 bits are returned. 
-   *  Note that this conversion can lose information about the overall magnitude of the 
-   *  BigDecimal value and that it always returns a positive result.
-   */
-  def charValue   = intValue.toChar
-
-  /** Converts this BigDecimal to an <tt>int</tt>. 
-   *  If the BigDecimal is too big to fit in a char, only the low-order 32 bits
-   *  are returned. Note that this conversion can lose information about the
-   *  overall magnitude of the BigDecimal value as well as return a result with
-   *  the opposite sign.
-   */
-  def intValue    = this.bigDecimal.intValue
-
-  /** Converts this BigDecimal to a <tt>Long</tt>.
-   *  If the BigDecimal is too big to fit in a char, only the low-order 64 bits
-   *  are returned. Note that this conversion can lose information about the
-   *  overall magnitude of the BigDecimal value as well as return a result with
-   *  the opposite sign.
-   */
-  def longValue   = this.bigDecimal.longValue
-
-  /** Converts this BigDecimal to a <tt>float</tt>.
-   *  if this BigDecimal has too great a magnitude to represent as a float,
-   *  it will be converted to <code>Float.NEGATIVE_INFINITY</code> or
-   *  <code>Float.POSITIVE_INFINITY</code> as appropriate.
-   */
-  def floatValue  = this.bigDecimal.floatValue
-
-  /** Converts this BigDecimal to a <tt>Double</tt>. 
-   *  if this BigDecimal has too great a magnitude to represent as a float, 
-   *  it will be converted to <code>Float.NEGATIVE_INFINITY</code> or
-   *  <code>Float.POSITIVE_INFINITY</code> as appropriate. 
-   */
-  def doubleValue = this.bigDecimal.doubleValue
-
-  /** Converts this <code>BigDecimal</code> to a BigInteger.
-   */
-  def toBigInt(): BigInt = new BigInt(this.bigDecimal.toBigInteger())
-
-  /** Returns the decimal String representation of this BigDecimal.
-   */
-  override def toString(): String = this.bigDecimal.toString()
-
-}
diff --git a/src/jvm14-library/scala/runtime/RichString.scala b/src/jvm14-library/scala/runtime/RichString.scala
deleted file mode 100644
index 263f26f..0000000
--- a/src/jvm14-library/scala/runtime/RichString.scala
+++ /dev/null
@@ -1,266 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: RichString.scala 16881 2009-01-09 16:28:11Z cunei $
-
-
-package scala.runtime
-
-import Predef._
-import scala.util.matching.Regex
-
-final class RichString(val self: String) extends Proxy with RandomAccessSeq[Char] with Ordered[String] {
-  import RichString._  
-  override def apply(n: Int) = self charAt n
-  override def length = self.length
-  override def toString = self
-  override def mkString = self
-
-  override def slice(from: Int, until: Int): RichString = {
-    val len = self.length
-    new RichString(
-      if (from >= until || from >= len)
-        ""
-      else {
-        val from0 = if (from < 0) 0 else from
-        val until0 = if (until > len) len else until
-        self.substring(from0, until0)
-      }
-    )
-  }
-
-  //override def ++ [B >: A](that: Iterable[B]): Seq[B] = {
-  override def ++[B >: Char](that: Iterable[B]): RandomAccessSeq[B] = that match {
-    case that: RichString => new RichString(self + that.self) 
-    case that => super.++(that)
-  }
-  
-  override def take(until: Int): RichString = slice(0, until)
-
-  override def drop(from: Int): RichString = slice(from, self.length)
-
-  override def startsWith[B](that: Seq[B]) = that match {
-    case that: RichString => self startsWith that.self
-    case that => super.startsWith(that)
-  }
-
-  override def endsWith[B](that: Seq[B]) = that match {
-    case that: RichString => self endsWith that.self
-    case that => super.endsWith(that)
-  }
-
-  override def indexOf[B](that: Seq[B]) = that match {
-    case that: RichString => self indexOf that.self
-    case that => super.indexOf(that)
-  }
-
-  override def containsSlice[B](that: Seq[B]) = that match {
-    case that: RichString => self contains that.self
-    case that => super.containsSlice(that)
-  }
- 
-  def contains(arg: String) : Boolean = {
-    self.matches(""".*\Q"""+arg+"""\E.*""")
-  }
-
-  override def reverse: RichString = {
-    val buf = new StringBuilder
-    var i = self.length - 1
-    while (i >= 0) {
-      buf append (self charAt i)
-      i -= 1
-    }
-    new RichString(buf.toString)
-  }
-  
-  /** return n times the current string 
-   */
-  def * (n: Int): String = {
-    val buf = new StringBuilder
-    for (i <- 0 until n) buf append self
-    buf.toString
-  }
-
-  override def compare(other: String) = self compareTo other
-
-  private def isLineBreak(c: Char) = c == LF || c == FF
-
-  /** <p>
-   *    Strip trailing line end character from this string if it has one.
-   *    A line end character is one of
-   *  </p>
-   *  <ul style="list-style-type: none;">
-   *    <li>LF - line feed   (0x0A hex)</li>
-   *    <li>FF - form feed   (0x0C hex)</li>
-   *  </ul>
-   *  <p>
-   *    If a line feed character LF is preceded by a carriage return CR
-   *    (0x0D hex), the CR character is also stripped (Windows convention).
-   *  </p>
-   */
-  def stripLineEnd: String = {
-    val len = self.length
-    if (len == 0) self
-    else {
-      val last = apply(len - 1)
-      if (isLineBreak(last))
-        self.substring(0, if (last == LF && len >= 2 && apply(len - 2) == CR) len - 2 else len - 1)
-      else 
-        self
-    }
-  }
-
-  /** <p>
-   *    Return all lines in this string in an iterator, including trailing
-   *    line end characters.
-   *  </p>
-   *  <p>
-   *    The number of strings returned is one greater than the number of line
-   *    end characters in this string. For an empty string, a single empty
-   *    line is returned. A line end character is one of
-   *  </p>
-   *  <ul style="list-style-type: none;">
-   *    <li>LF - line feed   (0x0A hex)</li>
-   *    <li>FF - form feed   (0x0C hex)</li>
-   *  </ul>
-   */
-  def linesWithSeparators = new Iterator[String] {
-    val len = self.length
-    var index = 0
-    def hasNext: Boolean = index < len
-    def next(): String = {
-      if (index >= len) throw new NoSuchElementException("next on empty iterator")
-      val start = index
-      while (index < len && !isLineBreak(apply(index))) index += 1
-      index += 1
-      self.substring(start, index min len)
-    }
-  }
-
-  /** Return all lines in this string in an iterator, excluding trailing line
-   *  end characters, i.e. apply <code>.stripLineEnd</code> to all lines
-   *  returned by <code>linesWithSeparators</code>.
-   */
-  def lines: Iterator[String] = 
-    linesWithSeparators map (line => new RichString(line).stripLineEnd)
-
-  /** Returns this string with first character converted to upper case */
-  def capitalize: String =
-    if (self == null) null
-    else if (self.length == 0) ""
-    else {
-      val chars = self.toCharArray
-      chars(0) = chars(0).toUpperCase
-      new String(chars)
-    }
-
-  /** <p>
-   *    For every line in this string:
-   *  </p>
-   *  <blockquote>
-   *     Strip a leading prefix consisting of blanks or control characters
-   *     followed by <code>marginChar</code> from the line.
-   *  </blockquote>
-   */
-  def stripMargin(marginChar: Char): String = {
-    val buf = new StringBuilder
-    for (line <- linesWithSeparators) {
-      val len = line.length
-      var index = 0
-      while (index < len && line.charAt(index) <= ' ') index += 1
-      buf append
-        (if (index < len && line.charAt(index) == marginChar) line.substring(index + 1) else line)
-    }
-    buf.toString
-  }
-
-  /** <p>
-   *    For every line in this string:
-   *  </p>
-   *  <blockquote>
-   *     Strip a leading prefix consisting of blanks or control characters
-   *     followed by <code>|</code> from the line.
-   *  </blockquote>
-   */
-  def stripMargin: String = stripMargin('|')
-
-  // NB. "\\Q" + '\\' + "\\E" works on Java 1.5 and newer, but not on Java 1.4
-  private def escape(ch: Char): String = ch match {
-    case '\\' => "\\\\"
-    case _ => "\\Q"+ch+"\\E"
-  }
-
-  @throws(classOf[java.util.regex.PatternSyntaxException])
-  def split(separator: Char): Array[String] = self.split(escape(separator))
-
-  @throws(classOf[java.util.regex.PatternSyntaxException])
-  def split(separators: Array[Char]): Array[String] = {
-    val re = separators.foldLeft("[")(_+escape(_)) + "]"
-    self.split(re)
-  }
-
-  /** You can follow a string with `.r', turning
-   *  it into a Regex. E.g.
-   *
-   *  """A\w*""".r   is the regular expression for identifiers starting with `A'.
-   */
-  def r: Regex = new Regex(self)
-  
-  def toBoolean: Boolean = parseBoolean(self)
-  def toByte: Byte       = java.lang.Byte.parseByte(self)
-  def toShort: Short     = java.lang.Short.parseShort(self)
-  def toInt: Int         = java.lang.Integer.parseInt(self)
-  def toLong: Long       = java.lang.Long.parseLong(self)
-  def toFloat: Float     = java.lang.Float.parseFloat(self)
-  def toDouble: Double   = java.lang.Double.parseDouble(self)
-
-  def toArray: Array[Char] = {
-    val result = new Array[Char](length)
-    self.getChars(0, length, result, 0)
-    result
-  }
-
-
-  /** <p>
-   *  Uses the underlying string as a pattern (in a fashion similar to
-   *  printf in C), and uses the supplied arguments to fill in the
-   *  holes.  Only works on Java 1.5 or higher!
-   *  </p>
-   *  <p>
-   *    The interpretation of the formatting patterns is described in
-   *    <a href="" target="contentFrame" class="java/util/Formatter">
-   *    <code>java.util.Formatter</code></a>.
-   *  </p>
-   *
-   *  @param args the arguments used to instantiating the pattern.
-   *  @throws java.lang.IllegalArgumentException
-   */
-  def format(args : Any*) : String = {
-    val m =  classOf[String].getDeclaredMethod("format", classOf[String], classOf[Array[Object]])
-    m.invoke(null, self, 
-	     args.asInstanceOf[scala.runtime.BoxedObjectArray].
-             unbox(args.getClass).asInstanceOf[Array[Object]]).asInstanceOf[String]
-  }
-}
-
-object RichString {
-  // just statics for rich string.
-  private final val LF: Char = 0x0A
-  private final val FF: Char = 0x0C
-  private final val CR: Char = 0x0D
-  private final val SU: Char = 0x1A
-
-  private def parseBoolean(s: String): Boolean =
-    if (s != null) s.toLowerCase match {
-      case "true" => true
-      case "false" => false
-      case _ => throw new NumberFormatException("For input string: \""+s+"\"")
-    }
-    else
-      throw new NumberFormatException("For input string: \"null\"")
-}
diff --git a/src/jvm14-library/scala/util/parsing/json/JSON.scala b/src/jvm14-library/scala/util/parsing/json/JSON.scala
deleted file mode 100644
index bf05cc2..0000000
--- a/src/jvm14-library/scala/util/parsing/json/JSON.scala
+++ /dev/null
@@ -1,95 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: JSON.scala 15746 2008-08-11 17:33:54Z dchenbecker $
-
-
-package scala.util.parsing.json
-
-/** 
- * This object provides a simple interface to the JSON parser class. The default conversion
- * for numerics is into a double. If you wish to override this behavior at the global level,
- * you can set the globalNumberParser property to your own (String => Any) function. If you only
- * want to override at the per-thread level then you can set the perThreadNumberParser property to your
- * function. For example:
- * 
- * <pre>
- * val myConversionFunc = {input : String => BigDecimal(input)}
- * 
- * // Global override
- * JSON.globalNumberParser = myConversionFunc
- * 
- * // Per-thread override
- * JSON.perThreadNumberParser = myConversionFunc
- * </pre>
- *
- *  @author Derek Chen-Becker <"java"+ at +"chen-becker"+"."+"org">
- */
-object JSON extends Parser {
-
-  /**
-   * Parse the given JSON string and return a list of elements. If the
-   * string is a JSON object it will be a list of pairs. If it's a JSON 
-   * array it will be be a list of individual elements.
-   *
-   * @param input the given JSON string.
-   * @return      an optional list of of elements. 
-   */
-  def parse(input: String): Option[List[Any]] =
-    phrase(root)(new lexical.Scanner(input)) match {
-      case Success(result, _) => Some(result)
-      case _ => None
-    }
-  
-  /**
-   * Parse the given JSON string and return either a <code>List[Any]</code>
-   * if the JSON string specifies an <code>Array</code>, or a
-   * <code>Map[String,Any]</code> if the JSON string specifies an object.
-   *
-   * @param input the given JSON string.
-   * @return      an optional list or map.
-   */
-  def parseFull(input: String): Option[Any] =
-    parse(input) match {
-      case Some(data) => Some(resolveType(data))
-      case None => None
-    }
-
-  /**
-   * A utility method to resolve a parsed JSON list into objects or 
-   * arrays. See the parse method for details.
-   */
-  def resolveType(input: List[_]): Any = {
-    var objMap = Map[String, Any]()
-    
-    if (input.forall { 
-      case (key: String, value: List[_]) =>
-        objMap += (key -> resolveType(value))
-        true
-      case (key : String, value : Any) =>
-        objMap += (key -> value)
-        true
-      case _ => false
-    }) objMap
-    else
-      input
-  }
-  
-  /**
-   * The global (VM) default function for converting a string to a numeric value. 
-   */
-  def globalNumberParser_=(f: NumericParser) { defaultNumberParser = f }
-  def globalNumberParser : NumericParser = defaultNumberParser
-  
-  /**
-   * Defines the function used to convert a numeric string literal into a numeric format on a per-thread
-   * basis. Use globalNumberParser for a global override
-   */
-   def perThreadNumberParser_=(f : NumericParser) { numberParser.set(f) }
-   def perThreadNumberParser : NumericParser = numberParser.get().asInstanceOf[NumericParser] // cast for jvm 1.4
-}
diff --git a/src/jvm14-library/scala/util/parsing/json/Parser.scala b/src/jvm14-library/scala/util/parsing/json/Parser.scala
deleted file mode 100644
index efad030..0000000
--- a/src/jvm14-library/scala/util/parsing/json/Parser.scala
+++ /dev/null
@@ -1,50 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: Parser.scala 15746 2008-08-11 17:33:54Z dchenbecker $
-
-
-package scala.util.parsing.json
-
-import scala.util.parsing.combinator._
-import scala.util.parsing.combinator.syntactical._
-import scala.util.parsing.combinator.lexical._
-
-/**
- *  @author Derek Chen-Becker <"java"+ at +"chen-becker"+"."+"org">
- */
-class Parser extends StdTokenParsers with ImplicitConversions {
-  // Fill in abstract defs
-  type Tokens = Lexer
-  val lexical = new Tokens
-
-  // Configure lexical parsing
-  lexical.reserved ++= List("true", "false", "null")
-  lexical.delimiters ++= List("{", "}", "[", "]", ":", ",")
-
-  /** Type signature for functions that can parse numeric literals */
-  type NumericParser = String => Any
-  
-  // Global default number parsing function
-  protected var defaultNumberParser : NumericParser = {_.toDouble}
-  
-  // Per-thread default number parsing function
-  protected val numberParser = new ThreadLocal[NumericParser]() {
-    override def initialValue() = defaultNumberParser
-  }
-  
-  // Define the grammar
-  def root       = jsonObj | jsonArray
-  def jsonObj    = "{" ~> repsep(objEntry, ",") <~ "}"
-  def jsonArray  = "[" ~> repsep(value, ",") <~ "]"
-  def objEntry   = stringVal ~ (":" ~> value) ^^ { case x ~ y => (x, y) }
-  def value: Parser[Any] = (jsonObj | jsonArray | number | "true" ^^^ true | "false" ^^^ false | "null" ^^^ null | stringVal)
-  def stringVal  = accept("string", { case lexical.StringLit(n) => n} )
-  def number     = accept("number", { case lexical.NumericLit(n) => numberParser.get.asInstanceOf[NumericParser].apply(n)} ) // cast for jvm 1.4
-}
-
diff --git a/src/library/scala/Annotation.scala b/src/library/scala/Annotation.scala
index 697f6b9..8c75e15 100644
--- a/src/library/scala/Annotation.scala
+++ b/src/library/scala/Annotation.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2006-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Annotation.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala
@@ -22,5 +21,6 @@ package scala
  *
  *  @author  Martin Odersky
  *  @version 1.1, 2/02/2007
+ *  @since 2.4
  */
 abstract class Annotation {}
diff --git a/src/library/scala/Application.scala b/src/library/scala/Application.scala
index 2ef58bd..d75f235 100644
--- a/src/library/scala/Application.scala
+++ b/src/library/scala/Application.scala
@@ -1,22 +1,21 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Application.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala
 
-import java.lang.System.getProperty
 import scala.compat.Platform.currentTime
 
 /** <p>
  *    The <code>Application</code> trait can be used to quickly turn objects
- *    into executable programs, but is <em>not recommended</em>.  Here is an example:
+ *    into executable programs, but is <em>not recommended</em>.
+ *    Here is an example:
  *  </p><pre>
  *  <b>object</b> Main <b>extends</b> Application {
  *    Console.println("Hello World!")
@@ -36,26 +35,37 @@ import scala.compat.Platform.currentTime
  *  </p><pre>
  *  java -Dscala.time Main
  *  </pre>
- *  <p>In practice the <code>Application</code> trait has a number of serious
- *  pitfalls:
+ *  <p>
+ *    In practice the <code>Application</code> trait has a number of serious
+ *    pitfalls:
+ *  </p>
  *  <ul>
- *    <li>As described above, there is no way to obtain the 
- *    command-line arguments because all code in body of an <code>object</code>
- *    extending <code>Application</code> is run as part of the static initialization
- *    which occurs before <code>Application</code>'s <code>main</code> method 
- *    even begins execution.</li>  
  *    <li> Threaded code that references the object will block until static 
  *    initialization is complete.  However, because the entire execution of an 
  *    <code>object</code> extending <code>Application</code> takes place during
  *    static initialization, concurrent code will <em>always</em> deadlock if 
  *    it must synchronize with the enclosing object.</li>
+ *    <li>As described above, there is no way to obtain the 
+ *    command-line arguments because all code in body of an <code>object</code>
+ *    extending <code>Application</code> is run as part of the static initialization
+ *    which occurs before <code>Application</code>'s <code>main</code> method 
+ *    even begins execution.</li>  
  *    <li>Static initializers are run only once during program execution, and 
  *    JVM authors usually assume their execution to be relatively short.  
  *    Therefore, certain JVM configurations may become confused, or simply fail to
  *    optimize or JIT the code in the body of an <code>object</code> extending 
  *    <code>Application</code>.  This can lead to a significant 
  *    performance degradation.</li>
- *  </p>
+ *  </ul>
+ *
+ *  Instead, it is recommended to define a <code>main</code> method explicitly:
+ *  <pre>
+ *  <b>object</b> Main {
+ *    <b>def</b> main(args: Array[String]) {
+ *      //..
+ *    }
+ *  }
+ *  </pre>
  *
  *  @author  Matthias Zenger
  *  @version 1.0, 10/09/2003
@@ -63,16 +73,16 @@ import scala.compat.Platform.currentTime
 
 trait Application {
 
-  /** The time when execution of this program started.
-   */
+  /** The time when the execution of this program started, in milliseconds since 1
+    * January 1970 UTC. */
   val executionStart: Long = currentTime
 
   /** The default main method.
    *
    *  @param args the arguments passed to the main method
    */
-  def main(args: Array[String]) = {
-    if (getProperty("scala.time") ne null) {
+  def main(args: Array[String]) {
+    if (util.Properties.propIsSet("scala.time")) {
       val total = currentTime - executionStart
       Console.println("[total " + total + "ms]")
     }
diff --git a/src/library/scala/Array.scala b/src/library/scala/Array.scala
index 39f7432..061009f 100644
--- a/src/library/scala/Array.scala
+++ b/src/library/scala/Array.scala
@@ -1,214 +1,431 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Array.scala 16881 2009-01-09 16:28:11Z cunei $
 
 
 package scala
 
-
-import Predef._
+import scala.collection.generic._
+import scala.collection.mutable.{ArrayBuilder, ArraySeq}
 import compat.Platform.arraycopy
+import scala.reflect.ClassManifest
+import scala.runtime.ScalaRunTime.{array_apply, array_update}
 
-/** This object contains utility methods operating on arrays.
+/** Contains a fallback builder for arrays when the element type
+ *  does not have a class manifest. In that case a generic array is built.
+ */
+class FallbackArrayBuilding {
+
+  /** A builder factory that generates a generic array.
+   *  Called instead of Array.newBuilder if the element type of an array
+   *  does not have a class manifest. Note that fallbackBuilder factory
+   *  needs an implicit parameter (otherwise it would not be dominated in implicit search
+   *  by Array.canBuildFrom). We make sure that that implicit search is always
+   *  successfull. 
+   */
+  implicit def fallbackCanBuildFrom[T](implicit m: DummyImplicit): CanBuildFrom[Array[_], T, ArraySeq[T]] = 
+    new CanBuildFrom[Array[_], T, ArraySeq[T]] { 
+      def apply(from: Array[_]) = ArraySeq.newBuilder[T]
+      def apply() = ArraySeq.newBuilder[T]
+    }
+}
+
+/** Utility methods for operating on arrays.
  *
  *  @author Martin Odersky
  *  @version 1.0
  */
-object Array {
-
-  /** Copy one array to another.
-   *  Equivalent to
-   *    <code>System.arraycopy(src, srcPos, dest, destPos, length)</code>,
-   *  except that this works also for polymorphic and boxed arrays.
-   *
-   *  @param src     ...
-   *  @param srcPos  ...
-   *  @param dest    ...
-   *  @param destPos ...
-   *  @param length  ...
-   */
-  def copy(src: AnyRef, srcPos: Int, dest: AnyRef, destPos: Int, length: Int) {
-    src match {
-      case xs: runtime.BoxedArray =>
-        xs.copyTo(srcPos, dest, destPos, length)
-      case _ =>
-        dest match {
-          case xs: runtime.BoxedArray =>
-            xs.copyFrom(src, srcPos, destPos, length)
-          case _ =>
-            def fillDest[T](da: Array[T], sa: Int=>T) {
-              var d = destPos
-              for (s <- srcPos to srcPos+length-1) {
-                da(d) = sa(s); d += 1
-              }
-            }
-            if (dest.isInstanceOf[Array[Any]]) {
-              def fill(sa: Int=>Any) = fillDest(dest.asInstanceOf[Array[Any]], sa)
-              src match {
-                case sa:Array[Int]     => fill(s=>Int.box(sa(s)))
-                case sa:Array[Long]    => fill(s=>Long.box(sa(s)))
-                case sa:Array[Char]    => fill(s=>Char.box(sa(s)))
-                case sa:Array[Boolean] => fill(s=>Boolean.box(sa(s)))
-                case sa:Array[Byte]    => fill(s=>Byte.box(sa(s)))
-                case sa:Array[Short]   => fill(s=>Short.box(sa(s)))
-                case sa:Array[Double]  => fill(s=>Double.box(sa(s)))
-                case sa:Array[Float]   => fill(s=>Float.box(sa(s)))
-                case _ => arraycopy(src, srcPos, dest, destPos, length)
-              }
-            } else if (dest.isInstanceOf[Array[AnyVal]]) {
-              def fill(sa: Int=>AnyVal) = fillDest(dest.asInstanceOf[Array[AnyVal]], sa)
-              src match {
-                case sa:Array[Int]     => fill(sa(_))
-                case sa:Array[Long]    => fill(sa(_))
-                case sa:Array[Char]    => fill(sa(_))
-                case sa:Array[Boolean] => fill(sa(_))
-                case sa:Array[Byte]    => fill(sa(_))
-                case sa:Array[Short]   => fill(sa(_))
-                case sa:Array[Double]  => fill(sa(_))
-                case sa:Array[Float]   => fill(sa(_))
-                case _ => arraycopy(src, srcPos, dest, destPos, length)
-              }
-            } else
-              arraycopy(src, srcPos, dest, destPos, length)
-        }
+object Array extends FallbackArrayBuilding {
+  implicit def canBuildFrom[T](implicit m: ClassManifest[T]): CanBuildFrom[Array[_], T, Array[T]] = 
+    new CanBuildFrom[Array[_], T, Array[T]] { 
+      def apply(from: Array[_]) = ArrayBuilder.make[T]()(m) 
+      def apply() = ArrayBuilder.make[T]()(m) 
     }
-  }
 
-  /** Concatenate all argument sequences into a single array.
-   *
-   *  @param xs the given argument sequences
-   *  @return   the array created from the concatenated arguments
+  /**
+   * Returns a new [[scala.collection.mutable.ArrayBuilder]].
    */
-  def concat[T](xs: Seq[T]*): Array[T] = {
-    var len = 0
-    for (x <- xs) len += x.length
-    val result = new Array[T](len)
-    var start = 0
-    for (x <- xs) {
-      copy(x.toArray, 0, result, start, x.length)
-      start += x.length
-    }
-    result
+  def newBuilder[T](implicit m: ClassManifest[T]): ArrayBuilder[T] = ArrayBuilder.make[T]()(m)
+
+  private def slowcopy(src : AnyRef, 
+                       srcPos : Int, 
+                       dest : AnyRef, 
+                       destPos : Int, 
+                       length : Int) {
+    var i = srcPos
+    var j = destPos
+    val srcUntil = srcPos + length
+    while (i < srcUntil) {
+      array_update(dest, j, array_apply(src, i))
+      i += 1
+      j += 1
+    }  
   }
 
-  /** Create a an array containing of successive integers.
+  /** Copy one array to another.
+   *  Equivalent to Java's
+   *    `System.arraycopy(src, srcPos, dest, destPos, length)`,
+   *  except that this also works for polymorphic and boxed arrays.
    *
-   *  @param from the value of the first element of the array
-   *  @param end  the value of the last element fo the array plus 1
-   *  @return the sorted array of all integers in range [from;end).
+   *  Note that the passed-in `dest` array will be modified by this call.
+   *
+   *  @param src the source array.
+   *  @param srcPos  starting position in the source array.
+   *  @param dest destination array.
+   *  @param destPos starting position in the destination array.
+   *  @param length the number of array elements to be copied.
+   *
+   *  @see `java.lang.System#arraycopy`
    */
-  def range(start: Int, end: Int): Array[Int] = {
-    val result = new Array[Int](end - start)
-    for (i <- start until end) result(i - start) = i
-    result
+  def copy(src: AnyRef, srcPos: Int, dest: AnyRef, destPos: Int, length: Int) {
+    val srcClass = src.getClass
+    if (srcClass.isArray && dest.getClass.isAssignableFrom(srcClass))
+      arraycopy(src, srcPos, dest, destPos, length)
+    else
+      slowcopy(src, srcPos, dest, destPos, length)
   }
 
-  /** Create an array with given elements.
+  /** Returns an array of length 0 */
+  def empty[T: ClassManifest]: Array[T] = new Array[T](0)
+ 
+  /** Creates an array with given elements.
    *
    *  @param xs the elements to put in the array
-   *  @return the array containing elements xs.
+   *  @return an array containing all elements from xs.
    */
-  def apply[A <: AnyRef](xs: A*): Array[A] = {
-    val array = new Array[A](xs.length)
+  def apply[T: ClassManifest](xs: T*): Array[T] = {
+    val array = new Array[T](xs.length)
     var i = 0
-    for (x <- xs.elements) { array(i) = x; i += 1 }
+    for (x <- xs.iterator) { array(i) = x; i += 1 }
+    array
+  }
+            
+  /** Creates an array of `Boolean` objects */
+  def apply(x: Boolean, xs: Boolean*): Array[Boolean] = {
+    val array = new Array[Boolean](xs.length + 1)
+    array(0) = x
+    var i = 1
+    for (x <- xs.iterator) { array(i) = x; i += 1 }
     array
   }
 
-
-/* The following metod clashes with the previous one, and has therefore been
- * removed. Note that this is a choice between efficiency and generality.
- * The previous factory method is more efficient than the one that has been
- * commented out. Since it is anyway possible to create a polymorphic array
- * using
- *        new Array[T]
- * it was preferred to restrict the definition of the factory method.
-
-   def Array[A](xs: A*): Array[A] = {
-    val array = new Array[A](xs.length)
-    var i = 0
-    for (x <- xs.elements) { array(i) = x; i += 1 }
+  /** Creates an array of `Byte` objects */
+  def apply(x: Byte, xs: Byte*): Array[Byte] = {
+    val array = new Array[Byte](xs.length + 1)
+    array(0) = x
+    var i = 1
+    for (x <- xs.iterator) { array(i) = x; i += 1 }
     array
   }
-*/
 
-  def apply(xs: Boolean*): Array[Boolean] = {
-    val array = new Array[Boolean](xs.length)
-    var i = 0
-    for (x <- xs.elements) { array(i) = x; i += 1 }
+  /** Creates an array of `Short` objects */
+  def apply(x: Short, xs: Short*): Array[Short] = {
+    val array = new Array[Short](xs.length + 1)
+    array(0) = x
+    var i = 1
+    for (x <- xs.iterator) { array(i) = x; i += 1 }
     array
   }
 
-  def apply(xs: Byte*): Array[Byte] = {
-    val array = new Array[Byte](xs.length)
-    var i = 0
-    for (x <- xs.elements) { array(i) = x; i += 1 }
+  /** Creates an array of `Char` objects */
+  def apply(x: Char, xs: Char*): Array[Char] = {
+    val array = new Array[Char](xs.length + 1)
+    array(0) = x
+    var i = 1
+    for (x <- xs.iterator) { array(i) = x; i += 1 }
     array
   }
 
-  def apply(xs: Short*): Array[Short] = {
-    val array = new Array[Short](xs.length)
-    var i = 0
-    for (x <- xs.elements) { array(i) = x; i += 1 }
+  /** Creates an array of `Int` objects */
+  def apply(x: Int, xs: Int*): Array[Int] = {
+    val array = new Array[Int](xs.length + 1)
+    array(0) = x
+    var i = 1
+    for (x <- xs.iterator) { array(i) = x; i += 1 }
     array
   }
 
-  def apply(xs: Char*): Array[Char] = {
-    val array = new Array[Char](xs.length)
-    var i = 0
-    for (x <- xs.elements) { array(i) = x; i += 1 }
+  /** Creates an array of `Long` objects */
+  def apply(x: Long, xs: Long*): Array[Long] = {
+    val array = new Array[Long](xs.length + 1)
+    array(0) = x
+    var i = 1
+    for (x <- xs.iterator) { array(i) = x; i += 1 }
     array
   }
 
-  def apply(xs: Int*): Array[Int] = {
-    val array = new Array[Int](xs.length)
-    var i = 0
-    for (x <- xs.elements) { array(i) = x; i += 1 }
+  /** Creates an array of `Float` objects */
+  def apply(x: Float, xs: Float*): Array[Float] = {
+    val array = new Array[Float](xs.length + 1)
+    array(0) = x
+    var i = 1
+    for (x <- xs.iterator) { array(i) = x; i += 1 }
     array
   }
 
-  def apply(xs: Long*): Array[Long] = {
-    val array = new Array[Long](xs.length)
-    var i = 0
-    for (x <- xs.elements) { array(i) = x; i += 1 }
+  /** Creates an array of `Double` objects */
+  def apply(x: Double, xs: Double*): Array[Double] = {
+    val array = new Array[Double](xs.length + 1)
+    array(0) = x
+    var i = 1
+    for (x <- xs.iterator) { array(i) = x; i += 1 }
     array
   }
 
-  def apply(xs: Float*): Array[Float] = {
-    val array = new Array[Float](xs.length)
-    var i = 0
-    for (x <- xs.elements) { array(i) = x; i += 1 }
+  /** Creates an array of `Unit` objects */
+  def apply(x: Unit, xs: Unit*): Array[Unit] = {
+    val array = new Array[Unit](xs.length + 1)
+    array(0) = x
+    var i = 1
+    for (x <- xs.iterator) { array(i) = x; i += 1 }
     array
   }
 
-  def apply(xs: Double*): Array[Double] = {
-    val array = new Array[Double](xs.length)
+  /** Creates array with given dimensions */
+  def ofDim[T: ClassManifest](n1: Int): Array[T] = 
+    new Array[T](n1)
+  /** Creates a 2-dimensional array */
+  def ofDim[T: ClassManifest](n1: Int, n2: Int): Array[Array[T]] = {
+    val arr: Array[Array[T]] = (new Array[Array[T]](n1): Array[Array[T]])
+    for (i <- 0 until n1) arr(i) = new Array[T](n2)
+    arr
+    // tabulate(n1)(_ => ofDim[T](n2))
+  }
+  /** Creates a 3-dimensional array */
+  def ofDim[T: ClassManifest](n1: Int, n2: Int, n3: Int): Array[Array[Array[T]]] = 
+    tabulate(n1)(_ => ofDim[T](n2, n3))
+  /** Creates a 4-dimensional array */
+  def ofDim[T: ClassManifest](n1: Int, n2: Int, n3: Int, n4: Int): Array[Array[Array[Array[T]]]] = 
+    tabulate(n1)(_ => ofDim[T](n2, n3, n4))
+  /** Creates a 5-dimensional array */
+  def ofDim[T: ClassManifest](n1: Int, n2: Int, n3: Int, n4: Int, n5: Int): Array[Array[Array[Array[Array[T]]]]] = 
+    tabulate(n1)(_ => ofDim[T](n2, n3, n4, n5))
+
+  /** Concatenates all arrays into a single array.
+   *
+   *  @param xss the given arrays
+   *  @return   the array created from concatenating `xss`
+   */
+  def concat[T: ClassManifest](xss: Array[T]*): Array[T] = {
+    val b = newBuilder[T]
+    b.sizeHint(xss.map(_.size).sum)
+    for (xs <- xss) b ++= xs
+    b.result
+  }
+
+  /** Returns an array that contains the results of some element computation a number
+   *  of times.
+   *
+   *  Note that this means that `elem` is computed a total of n times:
+   *  {{{
+   * scala> Array.fill(3){ java.lang.Math.random } 
+   * res3: Array[Double] = Array(0.365461167592537, 1.550395944913685E-4, 0.7907242137333306)
+   *  }}}
+   *
+   *  @param   n  the number of elements desired
+   *  @param   elem the element computation
+   *  @return an Array of size n, where each element contains the result of computing
+   *  `elem`.
+   */
+  def fill[T: ClassManifest](n: Int)(elem: => T): Array[T] = {
+    val b = newBuilder[T]
+    b.sizeHint(n)
     var i = 0
-    for (x <- xs.elements) { array(i) = x; i += 1 }
-    array
+    while (i < n) {
+      b += elem
+      i += 1
+    }
+    b.result
   }
 
-  def apply(xs: Unit*): Array[Unit] = {
-    val array = new Array[Unit](xs.length)
+  /** Returns a two-dimensional array that contains the results of some element
+   *  computation a number of times.
+   *
+   *  @param   n1  the number of elements in the 1st dimension
+   *  @param   n2  the number of elements in the 2nd dimension
+   *  @param   elem the element computation
+   */
+  def fill[T: ClassManifest](n1: Int, n2: Int)(elem: => T): Array[Array[T]] = 
+    tabulate(n1)(_ => fill(n2)(elem))
+
+  /** Returns a three-dimensional array that contains the results of some element
+   *  computation a number of times.
+   *
+   *  @param   n1  the number of elements in the 1st dimension
+   *  @param   n2  the number of elements in the 2nd dimension
+   *  @param   n3  the number of elements in the 3nd dimension
+   *  @param   elem the element computation
+   */
+  def fill[T: ClassManifest](n1: Int, n2: Int, n3: Int)(elem: => T): Array[Array[Array[T]]] = 
+    tabulate(n1)(_ => fill(n2, n3)(elem))
+
+  /** Returns a four-dimensional array that contains the results of some element
+   *  computation a number of times.
+   *
+   *  @param   n1  the number of elements in the 1st dimension
+   *  @param   n2  the number of elements in the 2nd dimension
+   *  @param   n3  the number of elements in the 3nd dimension
+   *  @param   n4  the number of elements in the 4th dimension
+   *  @param   elem the element computation
+   */
+  def fill[T: ClassManifest](n1: Int, n2: Int, n3: Int, n4: Int)(elem: => T): Array[Array[Array[Array[T]]]] = 
+    tabulate(n1)(_ => fill(n2, n3, n4)(elem))
+
+  /** Returns a five-dimensional array that contains the results of some element
+   *  computation a number of times.
+   *
+   *  @param   n1  the number of elements in the 1st dimension
+   *  @param   n2  the number of elements in the 2nd dimension
+   *  @param   n3  the number of elements in the 3nd dimension
+   *  @param   n4  the number of elements in the 4th dimension
+   *  @param   n5  the number of elements in the 5th dimension
+   *  @param   elem the element computation
+   */
+  def fill[T: ClassManifest](n1: Int, n2: Int, n3: Int, n4: Int, n5: Int)(elem: => T): Array[Array[Array[Array[Array[T]]]]] = 
+    tabulate(n1)(_ => fill(n2, n3, n4, n5)(elem))
+
+  /** Returns an array containing values of a given function over a range of integer
+   *  values starting from 0.
+   *
+   *  @param  n   The number of elements in the array
+   *  @param  f   The function computing element values
+   *  @return A traversable consisting of elements `f(0),f(1), ..., f(n - 1)`
+   */	
+  def tabulate[T: ClassManifest](n: Int)(f: Int => T): Array[T] = {
+    val b = newBuilder[T]
+    b.sizeHint(n)
     var i = 0
-    for (x <- xs.elements) { array(i) = x; i += 1 }
-    array
+    while (i < n) {
+      b += f(i)
+      i += 1
+    }
+    b.result
   }
 
-  /** Create an array containing several copies of an element.
+  /** Returns a two-dimensional array containing values of a given function over
+   *  ranges of integer values starting from 0.
+   *
+   *  @param   n1  the number of elements in the 1st dimension
+   *  @param   n2  the number of elements in the 2nd dimension
+   *  @param   f   The function computing element values
+   */	
+  def tabulate[T: ClassManifest](n1: Int, n2: Int)(f: (Int, Int) => T): Array[Array[T]] = 
+    tabulate(n1)(i1 => tabulate(n2)(f(i1, _)))
+
+  /** Returns a three-dimensional array containing values of a given function over
+   *  ranges of integer values starting from 0.
+   *
+   *  @param   n1  the number of elements in the 1st dimension
+   *  @param   n2  the number of elements in the 2nd dimension
+   *  @param   n3  the number of elements in the 3nd dimension
+   *  @param   f   The function computing element values
+   */	
+  def tabulate[T: ClassManifest](n1: Int, n2: Int, n3: Int)(f: (Int, Int, Int) => T): Array[Array[Array[T]]] = 
+    tabulate(n1)(i1 => tabulate(n2, n3)(f(i1, _, _)))
+
+  /** Returns a four-dimensional array containing values of a given function over
+   *  ranges of integer values starting from 0.
+   *
+   *  @param   n1  the number of elements in the 1st dimension
+   *  @param   n2  the number of elements in the 2nd dimension
+   *  @param   n3  the number of elements in the 3nd dimension
+   *  @param   n4  the number of elements in the 4th dimension
+   *  @param   f   The function computing element values
+   */	
+  def tabulate[T: ClassManifest](n1: Int, n2: Int, n3: Int, n4: Int)(f: (Int, Int, Int, Int) => T): Array[Array[Array[Array[T]]]] = 
+    tabulate(n1)(i1 => tabulate(n2, n3, n4)(f(i1, _, _, _)))
+
+  /** Returns a five-dimensional array containing values of a given function over
+   *  ranges of integer values starting from 0.
+   *
+   *  @param   n1  the number of elements in the 1st dimension
+   *  @param   n2  the number of elements in the 2nd dimension
+   *  @param   n3  the number of elements in the 3nd dimension
+   *  @param   n4  the number of elements in the 4th dimension
+   *  @param   n5  the number of elements in the 5th dimension
+   *  @param   f   The function computing element values
+   */	
+  def tabulate[T: ClassManifest](n1: Int, n2: Int, n3: Int, n4: Int, n5: Int)(f: (Int, Int, Int, Int, Int) => T): Array[Array[Array[Array[Array[T]]]]] = 
+    tabulate(n1)(i1 => tabulate(n2, n3, n4, n5)(f(i1, _, _, _, _)))
+
+  /** Returns an array containing a sequence of increasing integers in a range.
+   *
+   *  @param from the start value of the array
+   *  @param end the end value of the array, exclusive (in other words, this is the first value '''not''' returned)
+   *  @return  the array with values in range `start, start + 1, ..., end - 1`
+   *  up to, but excluding, `end`.
+   */
+  def range(start: Int, end: Int): Array[Int] = range(start, end, 1)
+
+  /** Returns an array containing equally spaced values in some integer interval.
+   *
+   *  @param start the start value of the array
+   *  @param end   the end value of the array, exclusive (in other words, this is the first value '''not''' returned)
+   *  @param step  the increment value of the array (may not be zero)
+   *  @return      the array with values in `start, start + step, ...` up to, but excluding `end`
+   */
+  def range(start: Int, end: Int, step: Int): Array[Int] = {
+    if (step == 0) throw new IllegalArgumentException("zero step")
+    val b = newBuilder[Int]
+    b.sizeHint(Range.count(start, end, step, false))
+
+    var i = start
+    while (if (step < 0) end < i else i < end) {
+      b += i
+      i += step
+    }
+    b.result
+  }
+
+  /** Returns an array containing repeated applications of a function to a start value.
+   *
+   *  @param start the start value of the array
+   *  @param len   the number of elements returned by the array
+   *  @param f     the function that is repeatedly applied
+   *  @return      the array returning `len` values in the sequence `start, f(start), f(f(start)), ...`
+   */
+  def iterate[T: ClassManifest](start: T, len: Int)(f: T => T): Array[T] = {
+    val b = newBuilder[T]
+    
+    if (len > 0) {
+      b.sizeHint(len)
+      var acc = start
+      var i = 1
+      b += acc
+      
+      while (i < len) {
+        acc = f(acc)
+        i += 1
+        b += acc
+      }
+    }
+    b.result
+  }
+
+  /** Called in a pattern match like `{ case Array(x,y,z) => println('3 elements')}`.
+   *
+   *  @param x the selector value
+   *  @return  sequence wrapped in a [[scala.Some]], if x is a Seq, otherwise `None`
+   */
+  def unapplySeq[T](x: Array[T]): Option[IndexedSeq[T]] = 
+    if (x == null) None else Some(x.toIndexedSeq) 
+    // !!! the null check should to be necessary, but without it 2241 fails. Seems to be a bug
+    // in pattern matcher.
+
+  /** Creates an array containing several copies of an element.
    *
    *  @param n    the length of the resulting array
    *  @param elem the element composing the resulting array
    *  @return     an array composed of n elements all equal to elem
    */
-  def make[A](n: Int, elem: A): Array[A] = {
-    val a = new Array[A](n)
+  @deprecated("use `Array.fill' instead")
+  def make[T: ClassManifest](n: Int, elem: T): Array[T] = {
+    val a = new Array[T](n)
     var i = 0
     while (i < n) {
       a(i) = elem
@@ -217,11 +434,12 @@ object Array {
     a
   }
 
-  /** Create an array containing the values of a given function <code>f</code> 
-   *  over given range <code>[0..n)</code>
+  /** Creates an array containing the values of a given function `f` 
+   *  over given range `[0..n)`
    */
-  def fromFunction[A](f: Int => A)(n: Int): Array[A] = {
-    val a = new Array[A](n)
+  @deprecated("use `Array.tabulate' instead")
+  def fromFunction[T: ClassManifest](f: Int => T)(n: Int): Array[T] = {
+    val a = new Array[T](n)
     var i = 0
     while (i < n) {
       a(i) = f(i)
@@ -230,138 +448,94 @@ object Array {
     a
   }
   
-  /** Create an array containing the values of a given function <code>f</code> 
-   *  over given range <code>[0..n1, 0..n2)</code>
+  /** Creates an array containing the values of a given function `f` 
+   *  over given range `[0..n1, 0..n2)`
    */
-  def fromFunction[A](f: (Int, Int) => A)(n1: Int, n2: Int): Array[Array[A]] =
+  @deprecated("use `Array.tabulate' instead")
+  def fromFunction[T: ClassManifest](f: (Int, Int) => T)(n1: Int, n2: Int): Array[Array[T]] =
     fromFunction(i => fromFunction(f(i, _))(n2))(n1)
   
-  /** Create an array containing the values of a given function <code>f</code> 
-   *  over given range <code>[0..n1, 0..n2, 0..n3)</code>
+  /** Creates an array containing the values of a given function `f` 
+   *  over given range `[0..n1, 0..n2, 0..n3)`
    */
-  def fromFunction[A](f: (Int, Int, Int) => A)(n1: Int, n2: Int, n3: Int): Array[Array[Array[A]]] = 
+  @deprecated("use `Array.tabulate' instead")
+  def fromFunction[T: ClassManifest](f: (Int, Int, Int) => T)(n1: Int, n2: Int, n3: Int): Array[Array[Array[T]]] = 
     fromFunction(i => fromFunction(f(i, _, _))(n2, n3))(n1)
 
-  /** Create an array containing the values of a given function <code>f</code> 
-   *  over given range <code>[0..n1, 0..n2, 0..n3, 0..n4)</code>
+  /** Creates an array containing the values of a given function `f` 
+   *  over given range `[0..n1, 0..n2, 0..n3, 0..n4)`
    */
-  def fromFunction[A](f: (Int, Int, Int, Int) => A)(n1: Int, n2: Int, n3: Int, n4: Int): Array[Array[Array[Array[A]]]] = 
+  @deprecated("use `Array.tabulate' instead")
+  def fromFunction[T: ClassManifest](f: (Int, Int, Int, Int) => T)(n1: Int, n2: Int, n3: Int, n4: Int): Array[Array[Array[Array[T]]]] = 
     fromFunction(i => fromFunction(f(i, _, _, _))(n2, n3, n4))(n1)
 
-  /** Create an array containing the values of a given function <code>f</code> 
-   *  over given range <code>[0..n1, 0..n2, 0..n3, 0..n4, 0..n5)</code>
+  /** Creates an array containing the values of a given function `f` 
+   *  over given range `[0..n1, 0..n2, 0..n3, 0..n4, 0..n5)`
    */
-  def fromFunction[A](f: (Int, Int, Int, Int, Int) => A)(n1: Int, n2: Int, n3: Int, n4: Int, n5: Int): Array[Array[Array[Array[Array[A]]]]] = 
+  @deprecated("use `Array.tabulate' instead")
+  def fromFunction[T: ClassManifest](f: (Int, Int, Int, Int, Int) => T)(n1: Int, n2: Int, n3: Int, n4: Int, n5: Int): Array[Array[Array[Array[Array[T]]]]] = 
     fromFunction(i => fromFunction(f(i, _, _, _, _))(n2, n3, n4, n5))(n1)
-
- /** This method is called as a result of a pattern match { case Array(...) => } or val Array(...) = ....
-   *
-   *  @param x the selector value
-   *  @return  array wrapped in an option
-   */
-   def unapplySeq[A](x: Array[A]): Option[Seq[A]] = Some(x)
-    
-   trait ArrayLike[A] extends RandomAccessSeq.Mutable[A] {
-     def force : Array[A]
-   }
-
-   trait Projection[A] extends RandomAccessSeq.MutableProjection[A] with ArrayLike[A] {
-     protected def newArray[B >: A](length : Int, elements : Iterator[A]) : Array[B]
-     override def toArray[B >: A] = (newArray(length, elements))//:Any).asInstanceOf[Array[B]]
-     override def force : Array[A] = toArray
-     override def drop( from: Int) = slice(from, length)
-     override def take(until: Int) = slice(0, until)
-     override def dropWhile(p: A => Boolean) = {
-       val c = length + 1
-       drop((findIndexOf(!p(_)) + c) % c)
-     }
-     override def takeWhile(p: A => Boolean) = {
-       val c = length + 1
-       take((findIndexOf(!p(_)) + c) % c)
-     }
-     override def slice(from0: Int, until0: Int): Projection[A] = new RandomAccessSeq.MutableSlice[A] with Projection[A] {
-       override def from = from0
-       override def until = until0
-       override def underlying = Projection.this
-       override protected def newArray[B >: A](length: Int, elements: Iterator[A]) =
-         underlying.newArray(length, elements)
-       override def slice(from0: Int, until0: Int) =
-         Projection.this.slice(from + from0, from + until0)
-     }
-     
-     
-     override def reverse : Projection[A] = new Projection[A] {
-       override protected def newArray[B >: A](length : Int, elements : Iterator[A]) =
-         Projection.this.newArray(length, elements)
-       def update(idx : Int, what : A) : Unit = Projection.this.update(length - idx - 1, what)
-       def length = Projection.this.length
-       def apply(idx : Int) = Projection.this.apply(length - idx - 1)
-       override def stringPrefix = Projection.this.stringPrefix + "R"
-     }
-   }
-   trait Array0[A] extends RandomAccessSeq.Mutable[A] with ArrayLike[A] {
-     override def projection : Projection[A] = throw new Error
-     override def slice(from : Int, until : Int) : Projection[A] = projection.slice(from, until)
-     override def take(until : Int) : Projection[A] = projection.take(until)
-     override def drop(from : Int) : Projection[A] = projection.drop(from)
-     override def dropWhile(p: A => Boolean) = projection.dropWhile(p)
-     override def takeWhile(p: A => Boolean) = projection.takeWhile(p)
-     override def reverse = projection.reverse
-     override def force = asInstanceOf[Array[A]]
-   }
 }
 
-/** This class represents polymorphic arrays. <code>Array[T]</code> is Scala's representation
- *  for Java's <code>T[]</code>.
+/** Represents polymorphic arrays. `Array[T]` is Scala's representation
+ *  for Java's `T[]`.
  *
  *  @author Martin Odersky
  *  @version 1.0
  */
-final class Array[A](_length: Int) extends Array.Array0[A] {
+final class Array[T](_length: Int) {
 
    /** Multidimensional array creation */
+   @deprecated("use `Array.ofDim' instead")
    def this(dim1: Int, dim2: Int) = {
      this(dim1)
      throw new Error()
    }
 
    /** Multidimensional array creation */
+   @deprecated("use `Array.ofDim' instead")
    def this(dim1: Int, dim2: Int, dim3: Int) = {
      this(dim1)
      throw new Error()
    }
 
    /** Multidimensional array creation */
+   @deprecated("use `Array.ofDim' instead")
    def this(dim1: Int, dim2: Int, dim3: Int, dim4: Int) = {
      this(dim1)
      throw new Error()
    }
 
    /** Multidimensional array creation */
+   @deprecated("use `Array.ofDim' instead")
    def this(dim1: Int, dim2: Int, dim3: Int, dim4: Int, dim5: Int) = {
      this(dim1);
      throw new Error()
    }
 
    /** Multidimensional array creation */
+   @deprecated("use `Array.ofDim' instead")
    def this(dim1: Int, dim2: Int, dim3: Int, dim4: Int, dim5: Int, dim6: Int) = {
      this(dim1)
      throw new Error()
    }
 
    /** Multidimensional array creation */
+   @deprecated("use `Array.ofDim' instead")
    def this(dim1: Int, dim2: Int, dim3: Int, dim4: Int, dim5: Int, dim6: Int, dim7: Int) = {
      this(dim1)
      throw new Error()
    }
 
    /** Multidimensional array creation */
+   @deprecated("use `Array.ofDim' instead")
    def this(dim1: Int, dim2: Int, dim3: Int, dim4: Int, dim5: Int, dim6: Int, dim7: Int, dim8: Int) = {
      this(dim1)
      throw new Error()
    }
 
    /** Multidimensional array creation */
+   @deprecated("use `Array.ofDim' instead")
    def this(dim1: Int, dim2: Int, dim3: Int, dim4: Int, dim5: Int, dim6: Int, dim7: Int, dim8: Int, dim9: Int) = {
      this(dim1)
      throw new Error()
@@ -372,151 +546,44 @@ final class Array[A](_length: Int) extends Array.Array0[A] {
 
   /** The element at given index. 
    *  <p>
-   *    Indices start a <code>0</code>; <code>xs.apply(0)</code> is the first 
-   *    element of array <code>xs</code>.
+   *    Indices start a `0`; `xs.apply(0)` is the first 
+   *    element of array `xs`.
    *  </p>
    *  <p>
-   *    Note the indexing syntax <code>xs(i)</code> is a shorthand for
-   *    <code>xs.apply(i)</code>.
+   *    Note the indexing syntax `xs(i)` is a shorthand for
+   *    `xs.apply(i)`.
    *  </p>
    *
    *  @param i   the index
-   *  @throws ArrayIndexOutOfBoundsException if <code>i < 0</code> or
-   *          <code>length <= i</code>
+   *  @throws ArrayIndexOutOfBoundsException if `i < 0` or
+   *          `length <= i`
    */
-  def apply(i: Int): A = throw new Error()
+  def apply(i: Int): T = throw new Error()
 
   /** <p>
    *    Update the element at given index. 
    *  </p>
    *  <p>
-   *    Indices start a <code>0</code>; <code>xs.apply(0)</code> is the first 
-   *    element of array <code>xs</code>.
+   *    Indices start a `0`; `xs.apply(0)` is the first 
+   *    element of array `xs`.
    *  </p>
    *  <p>
-   *    Note the indexing syntax <code>xs(i) = x</code> is a shorthand 
-   *    for <code>xs.update(i, x)</code>.
+   *    Note the indexing syntax `xs(i) = x` is a shorthand 
+   *    for `xs.update(i, x)`.
    *  </p>
    *
    *  @param i   the index
-   *  @param x   the value to be written at index <code>i</code>
-   *  @throws ArrayIndexOutOfBoundsException if <code>i < 0</code> or
-   *          <code>length <= i</code>
-   */
-  override def update(i: Int, x: A) { throw new Error() }
-
-  /** An iterator returning the elements of this array, starting from 0.
-   */
-  override def elements: Iterator[A] = throw new Error()
-
-  /** @deprecated  use <code>slice(from,end).force</code> instead */
-  def subArray(from: Int, end: Int): Array[A] = throw new Error()
-
-  /** Returns an array consisting of all elements of this array that satisfy the
-   *  predicate <code>p</code>. The order of the elements is preserved.
-   *
-   *  @param p the predicate used to filter the array.
-   *  @return the elements of this array satisfying <code>p</code>.
-   */
-  override def filter(p: A => Boolean): Array[A] = throw new Error()
-
-  /** Returns an array consisting of all elements of this array followed
-   *  by all elements of the argument iterable.
+   *  @param x   the value to be written at index `i`
+   *  @throws ArrayIndexOutOfBoundsException if `i < 0` or
+   *          `length <= i`
    */
-  override def ++[B >: A](that: Iterable[B]): Array[B] = throw new Error()
-
-  /** Returns the array resulting from applying the given function <code>f</code> to each
-   *  element of this array.
-   *
-   *  @param f function to apply to each element.
-   *  @return <code>[f(a0), ..., f(an)]</code> if this array is <code>[a0, ..., an]</code>.
-   */
-  override def map[B](f: A => B): Array[B] = throw new Error()
-
-  /** Applies the given function <code>f</code> to each element of
-   *  this array, then concatenates the results.
-   *
-   *  @param f the function to apply on each element.
-   *  @return  <code>f(a<sub>0</sub>) ::: ... ::: f(a<sub>n</sub>)</code> if
-   *           this array is <code>[a<sub>0</sub>, ..., a<sub>n</sub>]</code>.
-   */
-  override def flatMap[B](f: A => Iterable[B]): Array[B] = throw new Error()
-
-  /** Returns an array formed from this array and the specified array
-   *  <code>that</code> by associating each element of the former with
-   *  the element at the same position in the latter.
-   *  If one of the two arrays is longer than the other, its remaining elements are ignored.
-   *
-   *  @return     <code>Array({a<sub>0</sub>,b<sub>0</sub>}, ...,
-   *              {a<sub>min(m,n)</sub>,b<sub>min(m,n)</sub>})</code> when
-   *              <code>Array(a<sub>0</sub>, ..., a<sub>m</sub>)
-   *              zip Array(b<sub>0</sub>, ..., b<sub>n</sub>)</code> is invoked.
-   */
-  def zip[B](that: Array[B]): Array[(A, B)] = throw new Error()
-
-  /** Returns an array that pairs each element of this array
-   *  with its index, counting from 0.
-   *
-   *  @return      the array <code>Array({a<sub>0</sub>,0}, {a<sub>1</sub>,1},...)</code>
-   *               where <code>a<sub>i</sub></code> are the elements of this stream.
-   */
-  def zipWithIndex: Array[(A, Int)] = throw new Error()
-
-  /** Returns an array that contains all indices of this array */
-  def indices: Array[Int] = throw new Error()
-
-  /**
-   *  @return a deep string representation of this array.
-   */
-  def deepToString(): String = throw new Error()
-
-  /** <p>
-   *    Returns a string representation of this array object. The resulting string
-   *    begins with the string <code>start</code> and is finished by the string
-   *    <code>end</code>. Inside, the string representations of elements (w.r.t.
-   *    the method <code>deepToString()</code>) are separated by the string
-   *    <code>sep</code>. For example:
-   *  </p>
-   *  <p>
-   *    <code>Array(Array(1, 2), Array(3)).deepMkString("[", "; ", "]") = "[[1; 2]; [3]]"</code>
-   *  </p>
-   *
-   *  @param start starting string.
-   *  @param sep separator string.
-   *  @param end ending string.
-   *  @return a string representation of this array object.
-   */
-  def deepMkString(start: String, sep: String, end: String): String =
-    throw new Error()
-
-  /** Returns a string representation of this array object. The string
-   *  representations of elements (w.r.t. the method <code>deepToString()</code>)
-   *  are separated by the string <code>sep</code>.
-   *
-   *  @param sep separator string.
-   *  @return a string representation of this array object.
-   */
-  def deepMkString(sep: String): String = throw new Error()
-
+  def update(i: Int, x: T) { throw new Error() }
+  
   /** <p>
-   *    Returns <code>true</code> if the two specified arrays are
-   *    <em>deeply equal</em> to one another.
-   *  </p>
-   *  <p>
-   *    Two array references are considered deeply equal if both are null,
-   *    or if they refer to arrays that contain the same number of elements
-   *    and all corresponding pairs of elements in the two arrays are deeply
-   *    equal.
-   *  </p>
-   *  <p>
-   *    See also method <code>deepEquals</code> in the Java class
-   *    <a href="http://java.sun.com/javase/6/docs/api/java/util/Arrays.html"
-   *    target="_top">java.utils.Arrays</a>
+   *    Clone the Array.
    *  </p>
    *
-   *  @param that the second
-   *  @return     <code>true</code> iff both arrays are deeply equal.
+   *  @return A clone of the Array.
    */
-  def deepEquals(that: Any): Boolean = throw new Error()
-
+  override def clone: Array[T] = throw new Error()
 }
diff --git a/src/library/scala/Attribute.scala b/src/library/scala/Attribute.scala
deleted file mode 100644
index 9b1a84b..0000000
--- a/src/library/scala/Attribute.scala
+++ /dev/null
@@ -1,22 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: Attribute.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala
-
-/** <p>
- *  </p>
- *
- *  @deprecated  use Annotation instead
- *  @author  Martin Odersky
- *  @version 1.1, 2/02/2007
- */
- at deprecated
-abstract class Attribute {}
diff --git a/src/library/scala/BigDecimal.scala b/src/library/scala/BigDecimal.scala
deleted file mode 100644
index 3fdd25a..0000000
--- a/src/library/scala/BigDecimal.scala
+++ /dev/null
@@ -1,267 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2007-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: BigDecimal.scala 16881 2009-01-09 16:28:11Z cunei $
-
-package scala
-
-import java.math.{BigDecimal => BigDec}
-
-/** 
- *  @author  Stephane Micheloud
- *  @version 1.0
- */
-object BigDecimal {
-
-  @serializable
-  object RoundingMode extends Enumeration {
-    type RoundingMode = Value
-    val ROUND_UP, ROUND_DOWN, ROUND_CEILING, ROUND_FLOOR, ROUND_HALF_UP,
-        ROUND_HALF_DOWN, ROUND_HALF_EVEN, ROUND_UNNECESSARY = Value
-  }
-
-  private val minCached = -512
-  private val maxCached = 512
-  private lazy val cache = new Array[BigDecimal](maxCached - minCached + 1)
-
-  /** Constructs a <code>BigDecimal</code> whose value is equal to that of the
-   *  specified <code>Integer</code> value.
-   *
-   *  @param i the specified integer value
-   *  @return  the constructed <code>BigDecimal</code>
-   */
-  def apply(i: Int): BigDecimal =
-    if (minCached <= i && i <= maxCached) {
-      val offset = i - minCached
-      var n = cache(offset)
-      if (n eq null) { n = new BigDecimal(BigDec.valueOf(i)); cache(offset) = n }
-      n
-    } else new BigDecimal(BigDec.valueOf(i))
-
-  /** Constructs a <code>BigDecimal</code> whose value is equal to that of the
-   *  specified long value.
-   *
-   *  @param l the specified long value
-   *  @return  the constructed <code>BigDecimal</code>
-   */
-  def apply(l: Long): BigDecimal =
-    if (minCached <= l && l <= maxCached) apply(l.toInt)
-    else new BigDecimal(BigDec.valueOf(l))
-
-  /** Constructs a <code>BigDecimal</code> whose value is equal to that of the
-   *  specified double value.
-   *
-   *  @param d the specified <code>Double</code> value
-   *  @return  the constructed <code>BigDecimal</code>
-   */
-  def apply(d: Double): BigDecimal =
-    new BigDecimal(new BigDec(d))
-
-  /** Translates a character array representation of a <code>BigDecimal</code>
-   *  into a <code>BigDecimal</code>.
-   */
-  def apply(x: Array[Char]): BigDecimal = 
-    new BigDecimal(new BigDec(x.toString))
-
-  /** Translates the decimal String representation of a <code>BigDecimal</code>
-   *  into a <code>BigDecimal</code>.
-   */
-  def apply(x: String): BigDecimal = 
-    new BigDecimal(new BigDec(x))
-
-  /** Constructs a <code>BigDecimal</code> whose value is equal to that of the
-   *  specified <code>BigInt</code> value.
-   *
-   *  @param x the specified <code>BigInt</code> value
-   *  @return  the constructed <code>BigDecimal</code>
-   */
-  def apply(x: BigInt): BigDecimal =
-    new BigDecimal(new BigDec(x.bigInteger))
-
-  /** Implicit conversion from <code>Int</code> to <code>BigDecimal</code>. */
-  implicit def int2bigDecimal(i: Int): BigDecimal = apply(i)
-
-  /** Implicit conversion from <code>Long</code> to <code>BigDecimal</code>. */
-  implicit def long2bigDecimal(l: Long): BigDecimal = apply(l)
-
-  /** Implicit conversion from <code>Double</code> to <code>BigDecimal</code>. */
-  implicit def double2bigDecimal(d: Double): BigDecimal = apply(d)
-
-  /** Implicit conversion from BigDecimal to <code>Ordered</code>. */
-  implicit def bigDecimal2ordered(x: BigDecimal): Ordered[BigDecimal] =
-    new Ordered[BigDecimal] with Proxy {
-      def self: Any = x
-      def compare(y: BigDecimal): Int = x.bigDecimal.compareTo(y.bigDecimal)
-    }
-}
-
-/** 
- *  @author  Stephane Micheloud
- *  @version 1.0
- */
- at serializable
-class BigDecimal(val bigDecimal: BigDec) extends java.lang.Number {
-  import BigDecimal.RoundingMode._
-
-  /** Returns the hash code for this BigDecimal. */
-  override def hashCode(): Int = this.bigDecimal.hashCode()
-
-  /** Compares this BigDecimal with the specified value for equality.
-   */
-  override def equals(that: Any): Boolean = that match {
-    case that: BigDecimal => this equals that
-    case that: java.lang.Double => this.bigDecimal.doubleValue == that.doubleValue
-    case that: java.lang.Float  => this.bigDecimal.floatValue == that.floatValue
-    case that: java.lang.Number => this equals BigDecimal(that.longValue)
-    case that: java.lang.Character => this equals BigDecimal(that.charValue.asInstanceOf[Int])
-    case _ => false
-  }
-
-  /** Compares this BigDecimal with the specified BigDecimal for equality.
-   */
-  def equals (that: BigDecimal): Boolean =
-    this.bigDecimal.compareTo(that.bigDecimal) == 0
-
-  /** Compares this BigDecimal with the specified BigDecimal
-   */
-  def compare (that: BigDecimal): Int = this.bigDecimal.compareTo(that.bigDecimal)
-
-  /** Less-than-or-equals comparison of BigDecimals
-   */
-  def <= (that: BigDecimal): Boolean = this.bigDecimal.compareTo(that.bigDecimal) <= 0
-
-  /** Greater-than-or-equals comparison of BigDecimals
-   */
-  def >= (that: BigDecimal): Boolean = this.bigDecimal.compareTo(that.bigDecimal) >= 0
-
-  /** Less-than of BigDecimals
-   */
-  def <  (that: BigDecimal): Boolean = this.bigDecimal.compareTo(that.bigDecimal) <  0
-
-  /** Greater-than comparison of BigDecimals
-   */
-  def >  (that: BigDecimal): Boolean = this.bigDecimal.compareTo(that.bigDecimal) > 0
-
-  /** Addition of BigDecimals
-   */
-  def +  (that: BigDecimal): BigDecimal =
-    new BigDecimal(this.bigDecimal.add(that.bigDecimal))
-
-  /** Subtraction of BigDecimals
-   */
-  def -  (that: BigDecimal): BigDecimal =
-    new BigDecimal(this.bigDecimal.subtract(that.bigDecimal))
-
-  /** Multiplication of BigDecimals
-   */
-  def *  (that: BigDecimal): BigDecimal =
-    new BigDecimal(this.bigDecimal.multiply(that.bigDecimal))
-
-  /** Division of BigDecimals
-   */
-  def /  (that: BigDecimal): BigDecimal =
-    new BigDecimal(this.bigDecimal.divide(that.bigDecimal))
-
-  /** Returns the minimum of this and that
-   */
-  def min (that: BigDecimal): BigDecimal =
-    new BigDecimal(this.bigDecimal.min(that.bigDecimal))
-
-  /** Returns the maximum of this and that
-   */
-  def max (that: BigDecimal): BigDecimal =
-    new BigDecimal(this.bigDecimal.max(that.bigDecimal))
-
-  /** Returns a BigDecimal whose value is the negation of this BigDecimal
-   */
-  def unary_- : BigDecimal = new BigDecimal(this.bigDecimal.negate())
-  
-  /** Returns the absolute value of this BigDecimal
-   */
-  def abs: BigDecimal = new BigDecimal(this.bigDecimal.abs())
-
-  /** Returns the sign of this BigDecimal, i.e. 
-   *   -1 if it is less than 0, 
-   *   +1 if it is greater than 0
-   *   0  if it is equal to 0
-   */
-  def signum: Int = this.bigDecimal.signum()
-
-  /** Returns the scale of this <code>BigDecimal</code>.
-   */
-  def scale: Int = this.bigDecimal.scale()
-
-  /** Returns a <code>BigDecimal</code> whose scale is the specified value, and whose value is
-   *  numerically equal to this BigDecimal's.
-   */
-  def setScale(scale: Int): BigDecimal =
-    new BigDecimal(this.bigDecimal setScale scale)
-
-  def setScale(scale: Int, mode: RoundingMode): BigDecimal =
-    new BigDecimal(this.bigDecimal.setScale(scale, mode.id))
-
-  /** Converts this BigDecimal to a <tt>byte</tt>. 
-   *  If the BigDecimal is too big to fit in a byte, only the low-order 8 bits are returned. 
-   *  Note that this conversion can lose information about the overall magnitude of the 
-   *  BigDecimal value as well as return a result with the opposite sign.
-   */
-  override def byteValue   = intValue.toByte
-
-  /** Converts this BigDecimal to a <tt>short</tt>. 
-   *  If the BigDecimal is too big to fit in a byte, only the low-order 16 bits are returned. 
-   *  Note that this conversion can lose information about the overall magnitude of the 
-   *  BigDecimal value as well as return a result with the opposite sign.
-   */
-  override def shortValue  = intValue.toShort
-
-  /** Converts this BigDecimal to a <tt>char</tt>. 
-   *  If the BigDecimal is too big to fit in a char, only the low-order 16 bits are returned. 
-   *  Note that this conversion can lose information about the overall magnitude of the 
-   *  BigDecimal value and that it always returns a positive result.
-   */
-  def charValue   = intValue.toChar
-
-  /** Converts this BigDecimal to an <tt>int</tt>. 
-   *  If the BigDecimal is too big to fit in a char, only the low-order 32 bits
-   *  are returned. Note that this conversion can lose information about the
-   *  overall magnitude of the BigDecimal value as well as return a result with
-   *  the opposite sign.
-   */
-  def intValue    = this.bigDecimal.intValue
-
-  /** Converts this BigDecimal to a <tt>Long</tt>.
-   *  If the BigDecimal is too big to fit in a char, only the low-order 64 bits
-   *  are returned. Note that this conversion can lose information about the
-   *  overall magnitude of the BigDecimal value as well as return a result with
-   *  the opposite sign.
-   */
-  def longValue   = this.bigDecimal.longValue
-
-  /** Converts this BigDecimal to a <tt>float</tt>.
-   *  if this BigDecimal has too great a magnitude to represent as a float,
-   *  it will be converted to <code>Float.NEGATIVE_INFINITY</code> or
-   *  <code>Float.POSITIVE_INFINITY</code> as appropriate.
-   */
-  def floatValue  = this.bigDecimal.floatValue
-
-  /** Converts this BigDecimal to a <tt>Double</tt>. 
-   *  if this BigDecimal has too great a magnitude to represent as a float, 
-   *  it will be converted to <code>Float.NEGATIVE_INFINITY</code> or
-   *  <code>Float.POSITIVE_INFINITY</code> as appropriate. 
-   */
-  def doubleValue = this.bigDecimal.doubleValue
-
-  /** Converts this <code>BigDecimal</code> to a BigInteger.
-   */
-  def toBigInt(): BigInt = new BigInt(this.bigDecimal.toBigInteger())
-
-  /** Returns the decimal String representation of this BigDecimal.
-   */
-  override def toString(): String = this.bigDecimal.toString()
-
-}
diff --git a/src/library/scala/BigInt.scala b/src/library/scala/BigInt.scala
deleted file mode 100644
index 6938554..0000000
--- a/src/library/scala/BigInt.scala
+++ /dev/null
@@ -1,366 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: BigInt.scala 16881 2009-01-09 16:28:11Z cunei $
-
-
-package scala
-
-import java.math.BigInteger
-
-/** 
- *  @author  Martin Odersky
- *  @version 1.0, 15/07/2003
- */
-object BigInt {
-
-  private val minCached = -1024
-  private val maxCached = 1024
-  private val cache = new Array[BigInt](maxCached - minCached + 1)
-
-  /** Constructs a <code>BigInt</code> whose value is equal to that of the
-   *  specified integer value.
-   *
-   *  @param i the specified integer value
-   *  @return  the constructed <code>BigInt</code>
-   */
-  def apply(i: Int): BigInt =
-    if (minCached <= i && i <= maxCached) {
-      val offset = i - minCached
-      var n = cache(offset)
-      if (n eq null) { n = new BigInt(BigInteger.valueOf(i)); cache(offset) = n }
-      n
-    } else new BigInt(BigInteger.valueOf(i))
-
-  /** Constructs a <code>BigInt</code> whose value is equal to that of the
-   *  specified long value.
-   *
-   *  @param l the specified long value
-   *  @return  the constructed <code>BigInt</code>
-   */
-  def apply(l: Long): BigInt =
-    if (minCached <= l && l <= maxCached) apply(l.toInt)
-    else new BigInt(BigInteger.valueOf(l))
-
-  /** Translates a byte array containing the two's-complement binary 
-   *  representation of a BigInt into a BigInt.
-   */
-  def apply(x: Array[Byte]): BigInt = 
-    new BigInt(new BigInteger(x))
-
-  /** Translates the sign-magnitude representation of a BigInt into a BigInt.
-   */
-  def apply(signum: Int, magnitude: Array[Byte]): BigInt =
-    new BigInt(new BigInteger(signum, magnitude))
-  
-  /** Constructs a randomly generated positive BigInt that is probably prime, 
-   *  with the specified bitLength.
-   */
-  def apply(bitlength: Int, certaInty: Int, rnd: scala.util.Random): BigInt =
-    new BigInt(new BigInteger(bitlength, certaInty, rnd.self))
-
-  /** Constructs a randomly generated BigInt, uniformly distributed over the
-   *  range 0 to (2 ^ numBits - 1), inclusive.
-   *
-   *  @param numbits ...
-   *  @param rnd     ...
-   *  @return        ...
-   */
-  def apply(numbits: Int, rnd: scala.util.Random): BigInt =
-    new BigInt(new BigInteger(numbits, rnd.self))
-
-  /** Translates the decimal String representation of a BigInt into a BigInt.
-   */
-  def apply(x: String): BigInt = 
-    new BigInt(new BigInteger(x))
-
-  /** Translates the string representation of a BigInt in the
-   *  specified <code>radix</code> into a BigInt.
-   *
-   *  @param x     ...
-   *  @param radix ...
-   *  @return      ...
-   */
-  def apply(x: String, radix: Int): BigInt =
-    new BigInt(new BigInteger(x, radix))
-
-  /** Returns a positive BigInt that is probably prime, with the specified bitLength.
-   */
-  def probablePrime(bitLength: Int, rnd: scala.util.Random): BigInt =
-    new BigInt(BigInteger.probablePrime(bitLength, rnd.self))
-
-  /** Implicit conversion from <code>int</code> to <code>BigInt</code>.
-   */
-  implicit def int2bigInt(i: Int): BigInt = apply(i)
-
-  /** Implicit copnversion from long to BigInt
-   */
-  implicit def long2bigInt(l: Long): BigInt = apply(l)
-
-  /** Implicit conversion from BigInt to <code>Ordered</code>.
-   */
-  implicit def bigInt2ordered(x: BigInt): Ordered[BigInt] = new Ordered[BigInt] with Proxy {
-    def self: Any = x;
-    def compare (y: BigInt): Int = x.bigInteger.compareTo(y.bigInteger)
-  }
-}
-
-/** 
- *  @author  Martin Odersky
- *  @version 1.0, 15/07/2003
- */
- at serializable
-class BigInt(val bigInteger: BigInteger) extends java.lang.Number {
-
-  /** Returns the hash code for this BigInt. */
-  override def hashCode(): Int = this.bigInteger.hashCode()
-
-  /** Compares this BigInt with the specified value for equality.
-   */
-  override def equals (that: Any): Boolean = that match {
-    case that: BigInt => this equals that
-    case that: java.lang.Double => this.bigInteger.doubleValue == that.doubleValue
-    case that: java.lang.Float  => this.bigInteger.floatValue == that.floatValue
-    case that: java.lang.Number => this equals BigInt(that.longValue)
-    case that: java.lang.Character => this equals BigInt(that.charValue.asInstanceOf[Int])
-    case _ => false
-  }
-
-  /** Compares this BigInt with the specified BigInt for equality.
-   */
-  def equals (that: BigInt): Boolean =
-    this.bigInteger.compareTo(that.bigInteger) == 0
-
-  /** Compares this BigInt with the specified BigInt
-   */
-  def compare (that: BigInt): Int = this.bigInteger.compareTo(that.bigInteger)
-
-  /** Less-than-or-equals comparison of BigInts
-   */
-  def <= (that: BigInt): Boolean = this.bigInteger.compareTo(that.bigInteger) <= 0
-
-  /** Greater-than-or-equals comparison of BigInts
-   */
-  def >= (that: BigInt): Boolean = this.bigInteger.compareTo(that.bigInteger) >= 0
-
-  /** Less-than of BigInts
-   */
-  def <  (that: BigInt): Boolean = this.bigInteger.compareTo(that.bigInteger) <  0
-
-  /** Greater-than comparison of BigInts
-   */
-  def >  (that: BigInt): Boolean = this.bigInteger.compareTo(that.bigInteger) > 0
-
-  /** Addition of BigInts
-   */
-  def +  (that: BigInt): BigInt = new BigInt(this.bigInteger.add(that.bigInteger))
-
-  /** Subtraction of BigInts
-   */
-  def -  (that: BigInt): BigInt = new BigInt(this.bigInteger.subtract(that.bigInteger))
-
-  /** Multiplication of BigInts
-   */
-  def *  (that: BigInt): BigInt = new BigInt(this.bigInteger.multiply(that.bigInteger))
-
-  /** Division of BigInts
-   */
-  def /  (that: BigInt): BigInt = new BigInt(this.bigInteger.divide(that.bigInteger))
-
-  /** Remainder of BigInts
-   */
-  def %  (that: BigInt): BigInt = new BigInt(this.bigInteger.remainder(that.bigInteger))
-
-  /** Returns a pair of two BigInts containing (this / that) and (this % that).
-   */
-  def /% (that: BigInt): (BigInt, BigInt) = {
-    val dr = this.bigInteger.divideAndRemainder(that.bigInteger)
-    (new BigInt(dr(0)), new BigInt(dr(1)))
-  }
-
-  /** Leftshift of BigInt
-   */
-  def << (n: Int): BigInt = new BigInt(this.bigInteger.shiftLeft(n))
-
-  /** (Signed) rightshift of BigInt
-   */
-  def >> (n: Int): BigInt = new BigInt(this.bigInteger.shiftRight(n))
-
-  /** Bitwise and of BigInts
-   */
-  def &  (that: BigInt): BigInt = new BigInt(this.bigInteger.and(that.bigInteger))
-
-  /** Bitwise or of BigInts
-   */
-  def |  (that: BigInt): BigInt = new BigInt(this.bigInteger.or (that.bigInteger))
-
-  /** Bitwise exclusive-or of BigInts
-   */
-  def ^  (that: BigInt): BigInt = new BigInt(this.bigInteger.xor(that.bigInteger))
-
-  /** Bitwise and-not of BigInts. Returns a BigInt whose value is (this & ~that).
-   */
-  def &~ (that: BigInt): BigInt = new BigInt(this.bigInteger.andNot(that.bigInteger))
-
-  /** Returns the greatest common divisor of abs(this) and abs(that)
-   */
-  def gcd (that: BigInt): BigInt = new BigInt(this.bigInteger.gcd(that.bigInteger))
-
-  /** Returns a BigInt whose value is (this mod m).
-   *  This method differs from `%' in that it always returns a non-negative BigInt.
-   */
-  def mod (that: BigInt): BigInt = new BigInt(this.bigInteger.mod(that.bigInteger))
-
-  /** Returns the minimum of this and that
-   */
-  def min (that: BigInt): BigInt = new BigInt(this.bigInteger.min(that.bigInteger))
-
-  /** Returns the maximum of this and that
-   */
-  def max (that: BigInt): BigInt = new BigInt(this.bigInteger.max(that.bigInteger))
-  
-  /** Returns a BigInt whose value is (<tt>this</tt> raised to the power of <tt>exp</tt>).
-   */
-  def pow (exp: Int): BigInt = new BigInt(this.bigInteger.pow(exp))
-
-  /** Returns a BigInt whose value is
-   *  (<tt>this</tt> raised to the power of <tt>exp</tt> modulo <tt>m</tt>).
-   */
-  def modPow (exp: BigInt, m: BigInt): BigInt =
-    new BigInt(this.bigInteger.modPow(exp.bigInteger, m.bigInteger))
-
-  /** Returns a BigInt whose value is (the inverse of <tt>this</tt> modulo <tt>m</tt>).
-   */
-  def modInverse (m: BigInt): BigInt = new BigInt(this.bigInteger.modInverse(m.bigInteger))
-
-  /** Returns a BigInt whose value is the negation of this BigInt
-   */
-  def unary_- : BigInt   = new BigInt(this.bigInteger.negate())
-  
-  /** Returns the absolute value of this BigInt
-   */
-  def abs: BigInt = new BigInt(this.bigInteger.abs())
-
-  /** Returns the sign of this BigInt, i.e. 
-   *   -1 if it is less than 0, 
-   *   +1 if it is greater than 0
-   *   0  if it is equal to 0
-   */
-  def signum: Int = this.bigInteger.signum()
-
-  /** Returns the bitwise complement of this BigNum
-   */
-  def ~ : BigInt   = new BigInt(this.bigInteger.not())
-
-  /** Returns true if and only if the designated bit is set.
-   */
-  def testBit (n: Int): Boolean = this.bigInteger.testBit(n)
-
-  /** Returns a BigInt whose value is equivalent to this BigInt with the designated bit set.
-   */
-  def setBit  (n: Int): BigInt  = new BigInt(this.bigInteger.setBit(n))
-
-  /** Returns a BigInt whose value is equivalent to this BigInt with the designated bit cleared.
-   */
-  def clearBit(n: Int): BigInt  = new BigInt(this.bigInteger.clearBit(n))
-
-  /** Returns a BigInt whose value is equivalent to this BigInt with the designated bit flipped.
-   */
-  def flipBit (n: Int): BigInt  = new BigInt(this.bigInteger.flipBit(n))
-
-  /** Returns the index of the rightmost (lowest-order) one bit in this BigInt
-   * (the number of zero bits to the right of the rightmost one bit).
-   */
-  def lowestSetBit: Int         = this.bigInteger.getLowestSetBit()
-
-  /** Returns the number of bits in the minimal two's-complement representation of this BigInt, 
-   *  excluding a sign bit.
-   */
-  def bitLength: Int            = this.bigInteger.bitLength()
-  
-  /** Returns the number of bits in the two's complement representation of this BigInt 
-   *  that differ from its sign bit.
-   */
-  def bitCount: Int             = this.bigInteger.bitCount()
-
-  /** Returns true if this BigInt is probably prime, false if it's definitely composite.
-   *  @param certainty  a measure of the uncertainty that the caller is willing to tolerate: 
-   *                    if the call returns true the probability that this BigInt is prime 
-   *                    exceeds (1 - 1/2 ^ certainty). 
-   *                    The execution time of this method is proportional to the value of 
-   *                    this parameter.
-   */
-  def isProbablePrime(certainty: Int) = this.bigInteger.isProbablePrime(certainty)
-  
-  /** Converts this BigInt to a <tt>byte</tt>. 
-   *  If the BigInt is too big to fit in a byte, only the low-order 8 bits are returned. 
-   *  Note that this conversion can lose information about the overall magnitude of the 
-   *  BigInt value as well as return a result with the opposite sign.
-   */
-  override def byteValue   = intValue.toByte
-
-  /** Converts this BigInt to a <tt>short</tt>. 
-   *  If the BigInt is too big to fit in a byte, only the low-order 16 bits are returned. 
-   *  Note that this conversion can lose information about the overall magnitude of the 
-   *  BigInt value as well as return a result with the opposite sign.
-   */
-  override def shortValue  = intValue.toShort
-
-  /** Converts this BigInt to a <tt>char</tt>. 
-   *  If the BigInt is too big to fit in a char, only the low-order 16 bits are returned. 
-   *  Note that this conversion can lose information about the overall magnitude of the 
-   *  BigInt value and that it always returns a positive result.
-   */
-  def charValue   = intValue.toChar
-
-  /** Converts this BigInt to an <tt>int</tt>. 
-   *  If the BigInt is too big to fit in a char, only the low-order 32 bits
-   *  are returned. Note that this conversion can lose information about the
-   *  overall magnitude of the BigInt value as well as return a result with
-   *  the opposite sign.
-   */
-  def intValue    = this.bigInteger.intValue
-
-  /** Converts this BigInt to a <tt>long</tt>.
-   *  If the BigInt is too big to fit in a char, only the low-order 64 bits
-   *  are returned. Note that this conversion can lose information about the
-   *  overall magnitude of the BigInt value as well as return a result with
-   *  the opposite sign.
-   */
-  def longValue   = this.bigInteger.longValue
-
-  /** Converts this BigInt to a <tt>float</tt>.
-   *  if this BigInt has too great a magnitude to represent as a float,
-   *  it will be converted to <code>Float.NEGATIVE_INFINITY</code> or
-   *  <code>Float.POSITIVE_INFINITY</code> as appropriate.
-   */
-  def floatValue  = this.bigInteger.floatValue
-
-  /** Converts this BigInt to a <tt>double</tt>. 
-   *  if this BigInt has too great a magnitude to represent as a float, 
-   *  it will be converted to <code>Float.NEGATIVE_INFINITY</code> or
-   *  <code>Float.POSITIVE_INFINITY</code> as appropriate. 
-   */
-  def doubleValue = this.bigInteger.doubleValue
-
-  /** Returns the decimal String representation of this BigInt.
-   */
-  override def toString(): String = this.bigInteger.toString()
-
-  /** Returns the String representation in the specified radix of this BigInt.
-   */
-  def toString(radix: Int): String = this.bigInteger.toString(radix)
-
-  /** Returns a byte array containing the two's-complement representation of
-   *  this BigInt. The byte array will be in big-endian byte-order: the most
-   *  significant byte is in the zeroth element. The array will contain the
-   *  minimum number of bytes required to represent this BigInt, including at
-   *  least one sign bit.
-   */
-  def toByteArray: Array[Byte] = this.bigInteger.toByteArray()
-}
diff --git a/src/library/scala/BufferedIterator.scala b/src/library/scala/BufferedIterator.scala
deleted file mode 100644
index 9d6c239..0000000
--- a/src/library/scala/BufferedIterator.scala
+++ /dev/null
@@ -1,194 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: BufferedIterator.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala
-
-
-import Predef._
-
-/** Buffered iterators are iterators which allow to inspect the next
- *  element without discarding it.
- *
- *  @author  Martin Odersky
- *  @author  SeanMcDirmid
- *  @version 2.0, 16/04/2007
- */
-trait BufferedIterator[+A] extends Iterator[A] {
-  /** Checks what the next available element is.
-    *
-    *  @return the current element
-    */
-  def head : A 
-  def headOpt = if (!hasNext) None else Some(head)
-  override def buffered: this.type = this
-  /** iterates over and applies <code>f</code> to the next element
-   *  if this iterator has a next element that <code>f</code> is defined for. 
-   */
-  def readIf[T](f : PartialFunction[A,T]) : Option[T] = 
-    if (hasNext && f.isDefinedAt(head)) 
-      Some(f(next))
-    else None
-   
-  /** iterates over elements as long as <code>f</code> is true
-   *  for each element, returns whether anything was read
-   */
-  def readWhile(f : A => Boolean) : Boolean = {
-    var read = false
-    while (hasNext && f(head)) {
-      next
-      read = true
-    }
-    read
-  }
-  def advanced : BufferedIterator.Advanced[A] = new BufferedIterator.Default[A] {
-    protected def fill(sz : Int) : Seq[A] = if (BufferedIterator.this.hasNext) (BufferedIterator.this.next) :: Nil else Nil
-  }
-}
-
-object BufferedIterator {
-  import collection.mutable.{Buffer, ListBuffer}
-
-  trait Advanced[+A] extends BufferedIterator[A] {
-    /** returns the first <code>sz</code> elements that will be iterated by this iterator, 
-     *  or fewer if the iterator has less elements left to iterate over 
-     */
-    def peekList(sz : Int) : Seq[A]
-    
-    /** Checks what the next available element is.
-     *
-     *  @return the current element
-     */
-    def head: A = peek(0)
-    
-    /** return the <code>n</code>th element that will be iterated by this iterator */
-    def peek(n : Int) : A = {
-      val lst = peekList(n + 1);
-      if (n == 0) {
-        return if (lst.isEmpty) defaultPeek
-               else lst(0)
-      }
-      
-      val i = lst.elements
-      var m = 0
-      while (m < n && i.hasNext) {
-        i.next; m += 1
-      }
-      if (!i.hasNext) defaultPeek
-      else i.next
-    }
-    /** element returned when no element left to iterate over; 
-     *  throws <code>NoSuchElementException</code> by default 
-     */
-    protected def defaultPeek : A = throw new Predef.NoSuchElementException
-
-    /** true if elements of <code>seq</code> will be iterated over next in this iterator
-     */ 
-    def startsWith(seq : Seq[Any]) : Boolean = {
-      var sz = seq.length
-      val j = peekList(sz).elements
-      val i = seq.elements
-      while (i.hasNext && j.hasNext) 
-        if (i.next != j.next) return false
-      return !i.hasNext
-    }
-    def readIfStartsWith(seq : Seq[Any]) : Boolean = {
-      if (startsWith(seq)) {
-        var i = 0
-        while (i < seq.length) {
-          next; i = i + 1
-        }
-        true
-      } else false
-    }
-    override def counted : CountedIterator[A] with Advanced[A] = new CountedIterator[A] with Advanced[A] {
-      private var cnt = -1
-      def count = cnt
-      override def hasNext: Boolean = Advanced.this.hasNext
-      override def next: A = { cnt += 1; Advanced.this.next }
-      override def peekList(sz : Int) : Seq[A] = Advanced.this.peekList(sz)
-      override protected def defaultPeek : A = Advanced.this.defaultPeek
-      override def counted : this.type = this
-    }
-    override def hasNext = !peekList(1).isEmpty
-    override def toString = {
-      val list = peekList(0)
-      if (!list.isEmpty) "peek " + list else "***"
-    }
-      
-    override def advanced : this.type = this
-  }
-  
-  trait PutBack[+A] extends Advanced[A] {
-    protected[this] def putBack(a : A) : Unit
-    override def counted : CountedIterator[A] with PutBack[A] = new CountedIterator[A] with PutBack[A] {
-      private var cnt = -1
-      def count = cnt
-      override protected def defaultPeek : A = PutBack.this.defaultPeek
-      override def next: A = { cnt += 1; PutBack.this.next }
-      override def hasNext: Boolean = PutBack.this.hasNext
-      override def peekList(sz : Int) : Seq[A] = PutBack.this.peekList(sz)
-      override protected[this] def putBack(a : A) : Unit = {
-        if (cnt <= 0) throw new IllegalArgumentException
-        PutBack.this.putBack(a)
-        cnt = cnt - 1
-      }
-      override def counted : this.type = this
-    }
-    protected[this] def flushFrom[B <% Seq[A]](i : Default[B]) = 
-      i.forget.reverse.foreach(_.reverse.foreach(putBack))
-  }
-  
-  
-  abstract class Default[+A] extends PutBack[A] {
-    import scala.collection.mutable.ListBuffer
-    private[this] val lookahead = new ListBuffer[A]  // = Nil
-    override protected[this] def putBack(a : A) : Unit = a +: lookahead
-    override protected def defaultPeek : A = throw new Predef.NoSuchElementException
-    override def hasNext = !lookahead.isEmpty || super.hasNext
-
-    /** used to fill lookahead buffer. <code>sz</code> can be used by implementations as a heauristic to determine how many elements are desired */
-    protected def fill(sz : Int) : Seq[A]
-    
-    private[BufferedIterator] def forget : List[A] = {
-      val ret = lookahead.toList
-      lookahead.clear
-      ret
-    }
-      
-    override def peekList(sz : Int) : Seq[A] = {
-      if (sz == 0) return lookahead.readOnly
-      else if (sz == 1) {
-        if (!lookahead.isEmpty) return lookahead.readOnly
-        fill(sz) match {
-        case Seq.singleton(x) => lookahead += x
-        case next => lookahead ++= next
-        }
-        return lookahead.readOnly
-      }
-      var sz0 = lookahead.length
-      while (sz0 < sz) {
-        val next = fill(sz - sz0)
-        if (next.isEmpty) return lookahead.readOnly
-        sz0 += next.length
-        lookahead ++= next
-      }
-      lookahead.readOnly
-    }
-    override def next : A = {
-      val lst = peekList(1)
-      if (lst.isEmpty) throw new Predef.NoSuchElementException
-      lookahead.remove(0)
-      lst(0)
-    }
-  }
-}
-
-
diff --git a/src/library/scala/ByNameFunction.scala b/src/library/scala/ByNameFunction.scala
deleted file mode 100644
index a5d0dee..0000000
--- a/src/library/scala/ByNameFunction.scala
+++ /dev/null
@@ -1,26 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: ByNameFunction.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala
-
-/** A partial function of type <code>PartialFunction[A, B]</code> is a
- *  unary function where the domain does not include all values of type
- *  <code>A</code>. The function <code>isDefinedAt</code> allows to
- *  test dynamically, if a value is in the domain of the function.
- *
- *  @author  Martin Odersky
- *  @version 1.0, 16/07/2003
- */
-trait ByNameFunction[-A, +B] extends AnyRef {
-  def apply(x: => A): B
-  override def toString() = "<function>"
-}
-
diff --git a/src/library/scala/Cell.scala b/src/library/scala/Cell.scala
index 6a343fe..0e054d5 100644
--- a/src/library/scala/Cell.scala
+++ b/src/library/scala/Cell.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Cell.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala
diff --git a/src/library/scala/ClassfileAnnotation.scala b/src/library/scala/ClassfileAnnotation.scala
index 609c794..b762d71 100644
--- a/src/library/scala/ClassfileAnnotation.scala
+++ b/src/library/scala/ClassfileAnnotation.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2006-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: ClassfileAnnotation.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala
@@ -19,5 +18,6 @@ package scala
  *
  *  @author  Martin Odersky
  *  @version 1.1, 2/02/2007
+ *  @since 2.4
  */
-trait ClassfileAnnotation extends Annotation
+trait ClassfileAnnotation extends StaticAnnotation
diff --git a/src/library/scala/ClassfileAttribute.scala b/src/library/scala/ClassfileAttribute.scala
deleted file mode 100644
index 725e851..0000000
--- a/src/library/scala/ClassfileAttribute.scala
+++ /dev/null
@@ -1,26 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: ClassfileAttribute.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala
-
-/** <p>
- *    A base class for classfile attributes. These are stored as
- *    <a href="http://java.sun.com/j2se/1.5.0/docs/guide/language/annotations.html"
- *    target="_top">Java annotations</a> in classfiles.
- *  </p>
- *
- *  @deprecated  use <a href="ClassfileAnnotation.html"
- *               target="contentFrame">ClassfileAnnotation</a> instead
- *  @author  Martin Odersky
- *  @version 1.1, 2/02/2007
- */
- at deprecated
-trait ClassfileAttribute extends Attribute {}
diff --git a/src/library/scala/Collection.scala b/src/library/scala/Collection.scala
deleted file mode 100644
index 4db4f60..0000000
--- a/src/library/scala/Collection.scala
+++ /dev/null
@@ -1,47 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: Collection.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala
-
-
-import Predef._
-
-/** Variant of <code>Iterable</code> used to describe
- *  collections with a finite number of elements. 
- *  Basically, this trait just adds size and toString to Iterable,
- *  as most of the methods in Iterable already assume finite-ness.
- *
- *  @author Sean McDirmid
- */
-trait Collection[+A] extends Iterable[A] {
-  /** Returns the number of elements in this collection.
-    *
-    *  @return number of collection elements.
-    */
-  def size : Int
-  /** Converts this iterable to a fresh Array with elements.
-    */
-  def toArray[B >: A]: Array[B] = toList.toArray
-
-  override def toString = mkString(stringPrefix + "(", ", ", ")")
-
-  /** Defines the prefix of this object's <code>toString</code> representation.
-   */
-  protected def stringPrefix : String = {
-    var string = this.getClass.getName
-    val idx1 = string.lastIndexOf('.' : Int)
-    if (idx1 != -1) string = string.substring(idx1 + 1)
-    val idx2 = string.indexOf('$')
-    if (idx2 != -1) string = string.substring(0, idx2)
-    string
-  }
-}
-
diff --git a/src/library/scala/CollectionProxy.scala b/src/library/scala/CollectionProxy.scala
deleted file mode 100644
index 130f9e4..0000000
--- a/src/library/scala/CollectionProxy.scala
+++ /dev/null
@@ -1,55 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: CollectionProxy.scala 16881 2009-01-09 16:28:11Z cunei $
-
-
-package scala
-
-import scala.collection.mutable.Buffer
-
-
-/** This class implements a proxy for iterable objects. It forwards
- *  all calls to a different iterable object.
- *
- *  @author  Matthias Zenger
- *  @author  Martin Odersky
- *  @version 2.0, 31/12/2006
- */
-trait CollectionProxy[+A] extends Collection[A] with IterableProxy[A] {
-
-  def self: Collection[A]
-  override def size = self.size                       
-  override def toArray[B >: A] : Array[B] = self.toArray
-/*
-  override def elements: Iterator[A] = self.elements
-  override def map[B](f: A => B): Collection[B] = self map f
-  override def flatMap[B](f: A => Collection[B]): Collection[B] = self flatMap f
-  override def filter(p: A => Boolean): Collection[A] = self filter p
-  override def takeWhile(p: A => Boolean): Collection[A] = self takeWhile p 
-  override def dropWhile(p: A => Boolean): Collection[A] = self dropWhile p
-  override def drop(n: Int): Collection[A] = self drop n
-  override def foreach(f: A => Unit): Unit = self foreach f
-  override def forall(p: A => Boolean): Boolean = self forall p
-  override def exists(p: A => Boolean): Boolean = self exists p
-  override def find(p: A => Boolean): Option[A] = self find p
-  override def findIndexOf(p: A => Boolean): Int = self findIndexOf p
-  override def indexOf[B >: A](elem: B): Int = self indexOf elem
-  override def foldLeft[B](z: B)(op: (B, A) => B): B = (self foldLeft z)(op)
-  override def foldRight[B](z: B)(op: (A, B) => B): B = (self foldRight z)(op)
-  override def /:[B](z: B)(op: (B, A) => B): B = (z /: self)(op)
-  override def :\[B](z: B)(op: (A, B) => B): B = (self :\ z)(op)
-  override def reduceLeft[B >: A](op: (B, B) => B): B = self reduceLeft op
-  override def reduceRight[B >: A](op: (B, B) => B): B = self reduceRight op
-  override def sameElements[B >: A](that: Iterable[B]): Boolean = self sameElements that
-  override def copyToBuffer[B >: A](dest: Buffer[B]): Unit = self copyToBuffer dest
-  override def toList: List[A] = self.toList
-  override def mkString(start: String, sep: String, end: String): String = self.mkString(start, sep, end)
-  override def addString(buf: StringBuilder, start: String, sep: String, end: String): StringBuilder = self.addString(buf, start, sep, end)
-  */
-}
diff --git a/src/library/scala/Console.scala b/src/library/scala/Console.scala
index 4449dbe..f4dc2e5 100644
--- a/src/library/scala/Console.scala
+++ b/src/library/scala/Console.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Console.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala
@@ -14,9 +13,7 @@ package scala
 import java.io.{BufferedReader, InputStream, InputStreamReader, 
                 IOException, OutputStream, PrintStream, Reader}
 import java.text.MessageFormat
-
 import scala.util.DynamicVariable
-import Predef._
 
 
 /** The <code>Console</code> object implements functionality for
@@ -58,14 +55,14 @@ object Console {
   final val INVISIBLE  = "\033[8m"
 
   private val outVar = new DynamicVariable[PrintStream](java.lang.System.out)
+  private val errVar = new DynamicVariable[PrintStream](java.lang.System.err)
   private val inVar = new DynamicVariable[BufferedReader](
     new BufferedReader(new InputStreamReader(java.lang.System.in)))
 
   def out = outVar.value
+  def err = errVar.value
   def in = inVar.value
 
-  val err = java.lang.System.err
-
   /** Set the default output stream.
    *
    *  @param out the new output stream.
@@ -85,7 +82,7 @@ object Console {
 
   /** Set the default output stream.
    *
-   *  @param@ out the new output stream.
+   *  @param out the new output stream.
    */
   def setOut(out: OutputStream): Unit =
     setOut(new PrintStream(out))
@@ -102,11 +99,47 @@ object Console {
     withOut(new PrintStream(out))(thunk)
 
 
+  /** Set the default error stream.
+   *
+   *  @param err the new error stream.
+   */
+  def setErr(err: PrintStream) { errVar.value = err }
+
+  /** Set the default error stream for the duration
+   *  of execution of one thunk.
+   *
+   *  @param err the new error stream.
+   *  @param thunk the code to execute with
+   *               the new error stream active
+   *  @return ...
+   */
+  def withErr[T](err: PrintStream)(thunk: =>T): T =
+    errVar.withValue(err)(thunk)
+
+  /** Set the default error stream.
+   *
+   *  @param err the new error stream.
+   */
+  def setErr(err: OutputStream): Unit =
+    setErr(new PrintStream(err))
+
+  /** Set the default error stream for the duration
+   *  of execution of one thunk.
+   *
+   *  @param err the new error stream.
+   *  @param thunk the code to execute with
+   *               the new error stream active
+   *  @return ...
+   */
+  def withErr[T](err: OutputStream)(thunk: =>T): T =
+    withErr(new PrintStream(err))(thunk)
+
+
   /** Set the default input stream.
    *
    *  @param reader specifies the new input stream.
    */
-  def setIn(reader: Reader): Unit = {
+  def setIn(reader: Reader) {
     inVar.value = new BufferedReader(reader)
   }
 
@@ -117,16 +150,17 @@ object Console {
    *  @param thunk the code to execute with
    *               the new input stream active
    */
-    def withIn[T](reader: Reader)(thunk: =>T): T =
-      inVar.withValue(new BufferedReader(reader))(thunk)
+  def withIn[T](reader: Reader)(thunk: =>T): T =
+    inVar.withValue(new BufferedReader(reader))(thunk)
 
 
   /** Set the default input stream.
    *
    *  @param in the new input stream.     
    */
-  def setIn(in: InputStream): Unit =
+  def setIn(in: InputStream) {
     setIn(new InputStreamReader(in))
+  }
 
   /** Set the default input stream for the duration
    *  of execution of one thunk.
@@ -142,8 +176,9 @@ object Console {
    *
    *  @param obj the object to print.
    */
-  def print(obj: Any): Unit =
+  def print(obj: Any) {
     out.print(if (null == obj) "null" else obj.toString())
+  }
 
   /** Flush the output stream. This function is required when partial
    *  output (i.e. output not terminated by a new line character) has
@@ -153,13 +188,13 @@ object Console {
 
   /** Print a new line character on the terminal.
    */
-  def println(): Unit = out.println()
+  def println() { out.println() }
 
   /** Print out an object followed by a new line character.
    *
    *  @param x the object to print.
    */
-  def println(x: Any): Unit = out.println(x)
+  def println(x: Any) { out.println(x) }
 
   /** <p>
    *    Prints its arguments as a formatted string, based on a string
@@ -177,16 +212,6 @@ object Console {
    */
   def printf(text: String, args: Any*) { out.print(text format (args : _*)) }
 
-  /**
-   *  @see <a href="#printf(java.lang.String,scala.Any*)"
-   *       target="contentFrame">Console.printf</a>.
-   *  @deprecated For console output, use <code>Console.printf</code>.  For <code>String</code> formatting, 
-   *              <code>RichString</code>'s <code>format</code> method.
-   */
-  @deprecated def format(text: String, args: Any*) {
-      if (text eq null) out.printf("null") else (out.print(text format (args : _*)))
-  }
-
   /** Read a full line from the terminal.  Returns <code>null</code> if the end of the 
    * input stream has been reached.
    *
@@ -202,7 +227,7 @@ object Console {
    *  @return the string read from the terminal.
    */
   def readLine(text: String, args: Any*): String = {
-    format(text, args: _*)
+    printf(text, args: _*)
     readLine()
   }
 
@@ -214,17 +239,17 @@ object Console {
    *  @throws java.io.EOFException
    */
   def readBoolean(): Boolean = {
-       val s = readLine()
-       if (s == null) 
-	 throw new java.io.EOFException("Console has reached end of input")
-       else
-	 s.toLowerCase() match {
-           case "true" => true
-	   case "t" => true
-	   case "yes" => true
-	   case "y" => true
-	   case _ => false
-	 }
+    val s = readLine()
+    if (s == null) 
+      throw new java.io.EOFException("Console has reached end of input")
+    else
+      s.toLowerCase() match {
+        case "true" => true
+        case "t" => true
+        case "yes" => true
+        case "y" => true
+        case _ => false
+      }
   }
 
   /** Read a byte value from the terminal.
@@ -398,36 +423,4 @@ object Console {
     }
     res
   }
-
-  private def textParams(s: Seq[Any]): Array[AnyRef] = {
-    val res = new Array[AnyRef](s.length)
-    var i: Int = 0
-    val iter = s.elements
-    while (iter.hasNext) {
-      res(i) = iter.next match {
-        case x: Boolean => java.lang.Boolean.valueOf(x)
-        /** Should use java.lang.Byte.valueOf(Byte), but only available
-         * in Java 1.5 and above. */
-        case x: Byte    => new java.lang.Byte(x)
-        /** Should use java.lang.Short.valueOf(Short), but only available
-         * in Java 1.5 and above. */
-        case x: Short   => new java.lang.Short(x)
-        /** Should use java.lang.Character.valueOf(Char), but only available
-         * in Java 1.5 and above. */
-        case x: Char    => new java.lang.Character(x)
-        /** Should use java.lang.Integer.valueOf(Int), but only available
-         * in Java 1.5 and above. */
-        case x: Int     => new java.lang.Integer(x)
-        /** Should use java.lang.Long.valueOf(Long), but only available
-         * in Java 1.5 and above. */
-        case x: Long    => new java.lang.Long(x)
-        case x: Float   => new java.lang.Float(x)
-        case x: Double  => new java.lang.Double(x)
-        case x: Unit    => "()"
-        case x: AnyRef  => x
-      }
-      i += 1
-    }
-    res
-  }
 }
diff --git a/src/library/scala/CountedIterator.scala b/src/library/scala/CountedIterator.scala
index 8489a6e..31364be 100644
--- a/src/library/scala/CountedIterator.scala
+++ b/src/library/scala/CountedIterator.scala
@@ -1,31 +1,24 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: CountedIterator.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala
 
 /** Counted iterators keep track of the number of elements seen so far
  *
- *  @author  Martin Odersky
- *  @version 1.0, 16/07/2003
+ *  @since 2.0
  */
+ at deprecated("use iterator.zipWithIndex instead")
 trait CountedIterator[+A] extends Iterator[A] {
   /** counts the elements in this iterator; counts start at 0
    */
   def count: Int
   
   override def counted : this.type = this
-  override def buffered: BufferedIterator[A] with CountedIterator[A] = new BufferedIterator.Default[A] with CountedIterator[A] {
-    protected def fill(sz : Int) = if (CountedIterator.this.hasNext) (CountedIterator.this.next) :: Nil else Nil
-    override def count = CountedIterator.this.count - peekList(0).length
-    override def counted : this.type = this
-    override def buffered : this.type = this
-  }
 }
diff --git a/src/library/scala/Either.scala b/src/library/scala/Either.scala
index 8184fc9..312aeb3 100644
--- a/src/library/scala/Either.scala
+++ b/src/library/scala/Either.scala
@@ -1,16 +1,27 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
 package scala
 
-/**
- * <p>
- * The <code>Either</code> type represents a value of one of two possible types (a disjoint union).
- * The data constructors; <code>Left</code> and <code>Right</code> represent the two possible 
- * values. The <code>Either</code> type is often used as an alternative to 
- * <code>scala.Option</code> where <code>Left</code> represents failure (by convention) and
- * <code>Right</code> is akin to <code>Some</code>.
- * </p>
+/** <p>
+ *   The <code>Either</code> type represents a value of one of two possible
+ *   types (a disjoint union). The data constructors <code>Left</code> and
+ *   <code>Right</code> represent the two possible values.
+ *   The <code>Either</code> type is often used as an alternative to 
+ *   <code>scala.Option</code> where <code>Left</code> represents failure
+ *   (by convention) and <code>Right</code> is akin to <code>Some</code>.
+ *  </p>
  *
- * @author <a href="mailto:research at workingmouse.com">Tony Morris</a>, Workingmouse
- * @version 1.0, 11/10/2008
+ *  @author <a href="mailto:research at workingmouse.com">Tony Morris</a>, Workingmouse
+ *  @version 1.0, 11/10/2008
+ *  @since 2.7
  */
 sealed abstract class Either[+A, +B] {
   /**
@@ -38,33 +49,66 @@ sealed abstract class Either[+A, +B] {
     case Left(a) => Right(a)
     case Right(b) => Left(b)
   }
-   
+  
+  /**
+   * Joins an <code>Either</code> through <code>Right</code>.
+   */
+  def joinRight[A1 >: A, B1 >: B, C](implicit ev: B1 <:< Either[A1, C]): Either[A1, C] = this match {
+    case Left(a)  => Left(a)
+    case Right(b) => b
+  }
+  
+  /**
+   * Joins an <code>Either</code> through <code>Left</code>.
+   */
+  def joinLeft[A1 >: A, B1 >: B, C](implicit ev: A1 <:< Either[C, B1]): Either[C, B1] = this match {
+    case Left(a)  => a
+    case Right(b) => Right(b)
+  }
+
   /**
    * Returns <code>true</code> if this is a <code>Left</code>, <code>false</code> otherwise.
    */
-  def isLeft = false  // Default here, overriden in Left
+  def isLeft: Boolean
   
   /**
    * Returns <code>true</code> if this is a <code>Right</code>, <code>false</code> otherwise.
    */
-  def isRight = false // Default here, overriden in Right.
+  def isRight: Boolean
 }
+
 /**
  * The left side of the disjoint union, as opposed to the <code>Right</code> side.
  *
  * @author <a href="mailto:research at workingmouse.com">Tony Morris</a>, Workingmouse
  * @version 1.0, 11/10/2008
  */
-final case class Left[+A, +B](a: A) extends Either[A, B] { override def isLeft = true }
+final case class Left[+A, +B](a: A) extends Either[A, B] { 
+  def isLeft = true
+  def isRight = false
+}
+
 /**
  * The right side of the disjoint union, as opposed to the <code>Left</code> side.
  *
  * @author <a href="mailto:research at workingmouse.com">Tony Morris</a>, Workingmouse
  * @version 1.0, 11/10/2008 
  */ 
-final case class Right[+A, +B](b: B) extends Either[A, B] { override def isRight = true }
+final case class Right[+A, +B](b: B) extends Either[A, B] {
+  def isLeft = false
+  def isRight = true
+}
 
 object Either {
+  class MergeableEither[A](x: Either[A, A]) {
+    def merge: A = x match {
+      case Left(a)  => a
+      case Right(a) => a
+    }
+  }
+  
+  implicit def either2mergeable[A](x: Either[A, A]): MergeableEither[A] = new MergeableEither(x)
+
   /**
    * Projects an <code>Either</code> into a <code>Left</code>.
    *
@@ -88,7 +132,7 @@ object Either {
      *
      * @param e The side-effect to execute.
      */
-    def foreach(f: A => Unit) = e match {
+    def foreach[U](f: A => U) = e match {
       case Left(a) => f(a)
       case Right(_) => {}
     }
@@ -152,7 +196,7 @@ object Either {
      * <code>Seq</code> if this is a <code>Right</code>.
      */
     def toSeq = e match {
-      case Left(a) => Seq.singleton(a)
+      case Left(a) => Seq(a)
       case Right(_) => Seq.empty
     }
 
@@ -189,7 +233,7 @@ object Either {
      *
      * @param e The side-effect to execute.
      */
-    def foreach(f: B => Unit) = e match {
+    def foreach[U](f: B => U) = e match {
       case Left(_) => {}
       case Right(b) => f(b)
     }
@@ -239,27 +283,25 @@ object Either {
       case Right(b) => Right(f(b))
     }
 
-    /**
-     * Returns <code>None</code> if this is a <code>Left</code> or if the given predicate
-     * <code>p</code> does not hold for the right value, otherwise, returns a <code>Right</code>.
+    /** Returns <code>None</code> if this is a <code>Left</code> or if the
+     *  given predicate <code>p</code> does not hold for the right value,
+     *  otherwise, returns a <code>Right</code>.
      */
     def filter[X](p: B => Boolean): Option[Either[X, B]] = e match {
       case Left(_) => None
       case Right(b) => if(p(b)) Some(Right(b)) else None
     }
 
-    /**
-     * Returns a <code>Seq</code> containing the <code>Right</code> value if it exists or an empty
-     * <code>Seq</code> if this is a <code>Left</code>.
+    /** Returns a <code>Seq</code> containing the <code>Right</code> value if
+     *  it exists or an empty <code>Seq</code> if this is a <code>Left</code>.
      */
     def toSeq = e match {
       case Left(_) => Seq.empty
-      case Right(b) => Seq.singleton(b)
+      case Right(b) => Seq(b)
     }
 
-    /**
-     * Returns a <code>Some</code> containing the <code>Right</code> value if it exists or a
-     * <code>None</code> if this is a <code>Left</code>.
+    /** Returns a <code>Some</code> containing the <code>Right</code> value
+     *  if it exists or a <code>None</code> if this is a <code>Left</code>.
      */
     def toOption = e match {
       case Left(_) => None
@@ -267,31 +309,27 @@ object Either {
     }
   }
 
-  /**
-   * Joins an <code>Either</code> through <code>Left</code>.
-   */
+  @deprecated("use `x.joinLeft'")
   def joinLeft[A, B](es: Either[Either[A, B], B]) =
     es.left.flatMap(x => x)
 
-  /**
-   * Joins an <code>Either</code> through <code>Right</code>.
-   */
+  @deprecated("use `x.joinRight'")
   def joinRight[A, B](es: Either[A, Either[A, B]]) =
     es.right.flatMap(x => x)
-
+    
   /**
    * Takes an <code>Either</code> to its contained value within <code>Left</code> or 
    * <code>Right</code>.
    */
+  @deprecated("use `x.merge'")
   def merge[T](e: Either[T, T]) = e match {
     case Left(t) => t
     case Right(t) => t
   }
    
-  /**
-   * If the condition satisfies, return the given A in <code>Left</code>, otherwise, return the 
-   * given B in <code>Right</code>.
+  /** If the condition satisfies, return the given A in <code>Left</code>,
+   *  otherwise, return the given B in <code>Right</code>.
    */
-  def cond[A, B](test: Boolean, right: => B, left: => A) = 
-    if(test) Right(right) else Left(left)
+  def cond[A, B](test: Boolean, right: => B, left: => A): Either[A, B] = 
+    if (test) Right(right) else Left(left)
 }
diff --git a/src/library/scala/Enumeration.scala b/src/library/scala/Enumeration.scala
index 949f10d..b3b26c7 100644
--- a/src/library/scala/Enumeration.scala
+++ b/src/library/scala/Enumeration.scala
@@ -1,18 +1,17 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Enumeration.scala 16881 2009-01-09 16:28:11Z cunei $
-
-
 package scala
 
-
-import scala.collection.mutable.{Map, HashMap}
+import scala.collection.SetLike
+import scala.collection.{ mutable, immutable, generic }
+import java.lang.reflect.{ Modifier, Method => JMethod, Field => JField }
+import java.util.NoSuchElementException
 
 /** <p>
  *    Defines a finite set of values specific to the enumeration. Typically
@@ -42,7 +41,7 @@ import scala.collection.mutable.{Map, HashMap}
  *
  *    <b>def</b> isWorkingDay(d: WeekDay) = ! (d == Sat || d == Sun)
  * 
- *    WeekDay filter isWorkingDay foreach println
+ *    WeekDay.values filter isWorkingDay foreach println
  *  }</pre>
  *
  *  @param initial The initial value from which to count the integers that
@@ -55,99 +54,81 @@ import scala.collection.mutable.{Map, HashMap}
 @serializable
 @SerialVersionUID(8476000850333817230L)
 abstract class Enumeration(initial: Int, names: String*) {
+  thisenum =>
     
   def this() = this(0, null)
-    
   def this(names: String*) = this(0, names: _*)
+
+  /* Note that `readResolve` cannot be private, since otherwise
+     the JVM does not invoke it when deserializing subclasses. */
+  protected def readResolve(): AnyRef = thisenum.getClass.getField("MODULE$").get()
+
+  /** The name of this enumeration.  
+   */
+  override def toString = (getClass.getName stripSuffix "$" split '.' last) split '$' last
   
-  /** The name of this enumeration.  */
-  def name = {
-    val cname = this.getClass().getName()
-    if (cname endsWith "$")
-      cname.substring(0, cname.length() - 1)
-    else if (cname endsWith "$class")
-      cname.substring(0, cname.length() - 6)
-    else
-      cname
-  }
-  
-  /** The mapping from the integer used to identifying values to the actual
+  /** The mapping from the integer used to identify values to the actual
     * values. */
-  private val values: Map[Int, Value] = new HashMap
-  
+  private val vmap: mutable.Map[Int, Value] = new mutable.HashMap
+
   /** The cache listing all values of this enumeration. */
-  @transient private var vcache: List[Value] = null
-  
-  private def updateCache: List[Value] =
-    if (vcache eq null) {
-      vcache = values.values.toList.sort(_.id < _.id);
-      vcache
-    } else
-      vcache;
-  
+  @transient private var vset: ValueSet = null
+  @transient private var vsetDefined = false
+
+  /** The mapping from the integer used to identify values to their
+    * names. */
+  private val nmap: mutable.Map[Int, String] = new mutable.HashMap
+
+  /** The values of this enumeration as a set.
+   */
+  def values: ValueSet = {
+    if (!vsetDefined) {
+      vset = new ValueSet(immutable.BitSet.empty ++ (vmap.values map (_.id)))
+      vsetDefined = true
+    }
+    vset
+  }
+
   /** The integer to use to identify the next created value. */
   protected var nextId = initial
   
   /** The string to use to name the next created value. */
-  protected var nextName = names.elements
-  
+  protected var nextName = names.iterator
+  private def nextNameOrElse(orElse: => String) =
+    if (nextName.hasNext) nextName.next else orElse
+
   /** The highest integer amongst those used to identify values in this
     * enumeration. */
   private var topId = initial
-  
+
   /** The highest integer amongst those used to identify values in this
     * enumeration. */
   final def maxId = topId
-  
-  /** The value in this enumeration identified by integer <code>x</code>. */
-  final def apply(x: Int): Value = values(x)
-    
-  /** A new iterator over all values of this enumeration. */
-  final def elements: Iterator[Value] = updateCache.elements
-  
-  /** Apply a function f to all values of this enumeration. */
-  def foreach(f: Value => Unit): Unit = elements foreach f
-  
-  /** Apply a predicate p to all values of this enumeration and return
-    * true, iff the predicate yields true for all values. */ 
-  def forall(p: Value => Boolean): Boolean = elements forall p
-  
-  /** Apply a predicate p to all values of this enumeration and return
-    * true, iff there is at least one value for which p yields true. */
-  def exists(p: Value => Boolean): Boolean = elements exists p
-  
-  /** Returns an iterator resulting from applying the given function f to each
-    * value of this enumeration. */
-  def map[B](f: Value => B): Iterator[B] = elements map f
-  
-  /** Applies the given function f to each value of this enumeration, then
-    * concatenates the results. */
-  def flatMap[B](f: Value => Iterator[B]): Iterator[B] = elements flatMap f
-    
-  /** Returns all values of this enumeration that satisfy the predicate p.
-    * The order of values is preserved. */
-  def filter(p: Value => Boolean): Iterator[Value] = elements filter p
-    
-  override def toString(): String = updateCache.mkString("{", ", ", "}")
+
+  /** The value of this enumeration with given id `x`
+   */
+  final def apply(x: Int): Value = vmap(x)
 
   /** Returns a Value from this Enumeration whose name matches 
    * the argument <var>s</var>.
-   * You must pass a String* set of names to the constructor,
-   * or initialize each Enumeration with Value(String),
-   * for valueOf to work.
-   * @param s an enumeration name
-   * @return <tt>Some(Value)</tt> if an enumeration's name matches <var>s</var>, 
-   * else <tt>None</tt>
+   *
+   * You can pass a String* set of names to the constructor, or
+   * initialize each Enumeration with Value(String). Otherwise, the
+   * names are determined automatically through reflection.
+   *
+   * Note the change here wrt 2.7 is intentional. You should know whether
+   * a name is in an Enumeration beforehand. If not, just use find on
+   * values.
+   *
+   * @param  s an Enumeration name
+   * @return   the Value of this Enumeration if its name matches <var>s</var>
+   * @throws   java.util.NoSuchElementException if no Value with a matching
+   *           name is in this Enumeration
    */
-  def valueOf(s:String) = {
-    var v: Option[Value] = None
-    for( e <- elements ) if (s == e.toString()) v = Some(e)
-    v
-  }
+  final def withName(s: String): Value = values.find(_.toString == s).get
 
   /** Creates a fresh value, part of this enumeration. */
-  protected final def Value: Value =
-    new Val(nextId, if (nextName.hasNext) nextName.next else null)
+  protected final def Value: Value = Value(nextId)      
   
   /** Creates a fresh value, part of this enumeration, identified by the integer
    *  <code>i</code>.
@@ -156,14 +137,13 @@ abstract class Enumeration(initial: Int, names: String*) {
    *           unique amongst all values of the enumeration.
    *  @return  ..
    */
-  protected final def Value(i: Int): Value =
-    new Val(i, if (nextName.hasNext) nextName.next else null)
+  protected final def Value(i: Int): Value = Value(i, nextNameOrElse(null))
   
   /** Creates a fresh value, part of this enumeration, called <code>name</code>.
    *
    *  @param name A human-readable name for that value.
    */
-  protected final def Value(name: String): Value = new Val(nextId, name)
+  protected final def Value(name: String): Value = Value(nextId, name)
   
   /** Creates a fresh value, part of this enumeration, called <code>name</code>
    *  and identified by the integer <code>i</code>.
@@ -174,30 +154,58 @@ abstract class Enumeration(initial: Int, names: String*) {
    * @return     ..
    */
   protected final def Value(i: Int, name: String): Value = new Val(i, name)
-  
+
+  private def populateNameMap() {
+    // The list of possible Value methods: 0-args which return a conforming type
+    val methods = getClass.getMethods filter (m => m.getParameterTypes.isEmpty && classOf[Value].isAssignableFrom(m.getReturnType))
+    
+    methods foreach { m =>
+      val name = m.getName
+      // invoke method to obtain actual `Value` instance
+      val value = m.invoke(this).asInstanceOf[Value]
+      // verify that outer points to the correct Enumeration: ticket #3616.
+      if (value.outerEnum eq thisenum) {
+        val id = Int.unbox(classOf[Val] getMethod "id" invoke value)
+        nmap += ((id, name))
+      }
+    }
+  }
+
+  /* Obtains the name for the value with id `i`. If no name is cached
+   * in `nmap`, it populates `nmap` using reflection.
+   */
+  private def nameOf(i: Int): String = synchronized {
+    nmap.getOrElse(i, { populateNameMap() ; nmap(i) })
+  }
+
   /** The type of the enumerated values. */
   @serializable
   @SerialVersionUID(7091335633555234129L)
   abstract class Value extends Ordered[Value] {
     /** the id and bit location of this enumeration value */
     def id: Int
+    /** a marker so we can tell whose values belong to whom come reflective-naming time */
+    private[Enumeration] val outerEnum = thisenum
+
     override def compare(that: Value): Int = this.id - that.id
-    override def equals(other: Any): Boolean = 
-      other match {
-        case that: Value => compare(that) == 0
-        case _ => false
-      } 
-    override def hashCode: Int = id.hashCode
+    override def equals(other: Any) = other match {
+      case that: Enumeration#Value  => (outerEnum eq that.outerEnum) && (id == that.id)
+      case _                        => false
+    }
+    override def hashCode: Int = id.##
+
     /** this enumeration value as an <code>Int</code> bit mask.
      *  @throws IllegalArgumentException if <code>id</code> is greater than 31
      */
+    @deprecated("mask32 will be removed")
     def mask32: Int = {
       if (id >= 32) throw new IllegalArgumentException
       1  << id
     }
-    /** this enumeration value as an <code>Long</code> bit mask. 
+    /** this enumeration value as a <code>Long</code> bit mask. 
      *  @throws IllegalArgumentException if <code>id</code> is greater than 63
      */
+    @deprecated("mask64 will be removed")
     def mask64: Long = {
       if (id >= 64) throw new IllegalArgumentException
       1L << id
@@ -206,179 +214,107 @@ abstract class Enumeration(initial: Int, names: String*) {
   
   /** A class implementing the <a href="Enumeration.Value.html"
    *  target="contentFrame"><code>Value</code></a> type. This class can be
-   *  overriden to change the enumeration's naming and integer identification
+   *  overridden to change the enumeration's naming and integer identification
    *  behaviour.
    */
   @serializable
   @SerialVersionUID(0 - 3501153230598116017L)
   protected class Val(i: Int, name: String) extends Value {
-    def this(i: Int) =
-      this(i, if (nextName.hasNext) nextName.next else i.toString())
-    def this(name: String) = this(nextId, name)
-    def this() =
-      this(nextId, if (nextName.hasNext) nextName.next else nextId.toString())
-    assert(!values.isDefinedAt(i))
-    values(i) = this
+    def this(i: Int)        = this(i, nextNameOrElse(i.toString))
+    def this(name: String)  = this(nextId, name)
+    def this()              = this(nextId)
+
+    assert(!vmap.isDefinedAt(i), "Duplicate id: " + i)
+    vmap(i) = this
+    vsetDefined = false
     nextId = i + 1
     if (nextId > topId) topId = nextId
     def id = i
     override def toString() =
-      if (name eq null) Enumeration.this.name + "(" + i + ")"
-      else name
-    private def readResolve(): AnyRef =
-      if (values ne null) values(i)
-      else this
-  }
-  
-  /** A set that efficiently stores enumeration values as bits.
-   *
-   *  @author Sean McDirmid
-   *
-   *  @ex 
-   * 
-   *  <pre>
-   *  <b>object</b> flags <b>extends</b> Enumeration {
-   *    <b>val</b> Public = Value(5, "public");
-   *    <b>val</b> Private = Value(4, "private");
-   *    <b>val</b> Protected = Value(6, "protected");
-   *    <b>val</b> Final = Value(7, "final");
-   *  }
-   *
-   *  <b>class</b> Entity {
-   *    <b>var</b> flags0 : Int = ...;
-   *    <b>def</b> flags = flags.Set32(flags0);
-   *  } 
-   *
-   *  <b>val</b> e : Entity = ...;
-   *
-   *  <b>if</b> (e.flags.contains(flags.Private))
-   *    e.flags0 = (e.flags | flags.Final).underlying; 
-   *  </pre>
-   */
-  abstract class SetXX extends collection.immutable.Set[Value] {
-
-    /** either Int or Long */
-    type Underlying <: AnyVal
-    type TSet <: SetXX 
-
-    /** The integer that bit-encodes a set of enumeration values. 
-     */
-    val underlying: Underlying
-
-    /** returns the underlying integer representation of this set as a long. */
-    protected def underlyingAsLong: Long
-
-    /** Equivalent to <code>++</code> for bit sets. Returns a set 
-     *  that has all values in <code>this</code> and <code>set</code>.
-     */
-    def |(set: TSet): TSet
+      if (name != null) name
+      else try thisenum.nameOf(i)
+      catch { case _: NoSuchElementException => "<Invalid enum: no field for #" + i + ">" }
 
-    /** Equivalent to <code>+</code> for bit sets. Returns a set 
-     *  that has all values in <code>this</code> with the addition of <code>value</code>.
-     */
-    def |(value: Value): TSet
-
-    /** Equivalent to <code>**</code> for bit sets.
-     *  Returns a bit set that has all values that are both in <code>this</code> and <code>set</code>.
-     */
-    def &(set: TSet): TSet
-
-    /** Equivalent to <code>-</code> for bit sets. 
-     *  Returns a bit set that has all values in <code>this</code> except for <code>value</code>.
-     */
-    def &~(value: Value): TSet
-    def -(value: Value): TSet = this &~ value
-    def +(value: Value): TSet = this | value
-    def ++(set: TSet): TSet = this | set
-    def **(set: TSet): TSet = this & set
-    def size = {
-      var x = underlyingAsLong
-      var sz = 0
-      while (x != 0) {
-        if ((x & 1) != 0) sz += 1
-        x = x >> 1
-      }
-      sz
+    protected def readResolve(): AnyRef = {
+      val enum = thisenum.readResolve().asInstanceOf[Enumeration]
+      if (enum.vmap == null) this
+      else enum.vmap(i)
     }
-    override def stringPrefix = Enumeration.this.name;
-    def elements = new Iterator[Value] {
-      var bit = 0
-      var underlying = underlyingAsLong
-      def hasNext = underlying != 0
-      private def shift = {
-        underlying = underlying >> 1
-        bit += 1
-      }
-      def next = {
-        if (underlying == 0) throw new NoSuchElementException
-        while ((underlying & 1) == 0) shift
-        val ret = values(bit)
-        shift
-        ret
-      }
-    }
-    def empty[B]: scala.collection.immutable.Set[B] = new scala.collection.immutable.HashSet[B];
   }
 
-  /** An enumeration bit set that can handle enumeration values with ids up
-   *  to 31 in an <code>Int</code>.
+  /** A class for sets of values
+   *  Iterating through this set will yield values in increasing order of their ids.
+   *  @param   ids   The set of ids of values, organized as a BitSet. 
    */
-  class Set32(val underlying: Int) extends SetXX {
-    def this() = this(0)
-    type Underlying = Int
-    type TSet = Set32
-    def underlyingAsLong = {
-      if (underlying >= 0) underlying.toLong
-      else {
-        val underlying0 = (~(1 << 31)) & underlying
-        assert(underlying0 >= 0)
-        underlying0.toLong | (1L << 31)
-      }
-    }
-    def contains(value: Value) = (underlying & value.mask32) != 0
-    def |(set: Set32) = new Set32(underlying | set.underlying)
-    def |(value: Value) = new Set32(underlying | value.mask32)
-    def &~(value: Value) = new Set32(underlying & (~value.mask32))
-    def &(set: Set32) = new Set32(underlying & set.underlying)
+  class ValueSet private[Enumeration] (val ids: immutable.BitSet) extends Set[Value] with SetLike[Value, ValueSet] {
+    override def empty = ValueSet.empty
+    def contains(v: Value) = ids contains (v.id)
+    def + (value: Value) = new ValueSet(ids + value.id)
+    def - (value: Value) = new ValueSet(ids - value.id)
+    def iterator = ids.iterator map thisenum.apply
+    override def stringPrefix = thisenum + ".ValueSet"
   }
 
-  /** create an empty 32 bit enumeration set */
-  def Set32 = new Set32
-
-  /** create a bit enumeration set according ot underlying */
-  def Set32(underlying: Int) = new Set32(underlying)
+  /** A factory object for value sets */
+  object ValueSet {
+    import mutable.{ Builder, AddingBuilder }
+    import generic.CanBuildFrom
 
-  /** An enumeration bit set that can handle enumeration values with ids up
-   *  to 63 in a <code>Long</code>.
-   */
-  class Set64(val underlying: Long) extends SetXX {
-    def this() = this(0)
-    type Underlying = Long
-    type TSet = Set64
-    def underlyingAsLong = underlying
-    def contains(value: Value) = (underlying & value.mask64) != 0
-    def |(set: Set64) = new Set64(underlying | set.underlying)
-    def |(value: Value) = new Set64(underlying | value.mask64)
-    def &~(value: Value) = new Set64(underlying & (~value.mask64))
-    def &(set: Set64) = new Set64(underlying & set.underlying)
+    /** The empty value set */
+    val empty = new ValueSet(immutable.BitSet.empty)
+    /** A value set consisting of given elements */ 
+    def apply(elems: Value*): ValueSet = empty ++ elems
+    /** A builder object for value sets */
+    def newBuilder: Builder[Value, ValueSet] = new AddingBuilder(empty)
+    /** The implicit builder for value sets */
+    implicit def canBuildFrom: CanBuildFrom[ValueSet, Value, ValueSet] = 
+      new CanBuildFrom[ValueSet, Value, ValueSet] { 
+        def apply(from: ValueSet) = newBuilder 
+        def apply() = newBuilder 
+      }
   }
+  
+  /** The name of this enumeration. */
+  @deprecated("use toString instead") def name = toString
 
-  /** create an empty 64 bit enumeration set */
-  def Set64 = new Set64
-
-  /** create a bit enumeration set according ot underlying */
-  def Set64(underlying: Long) = new Set64(underlying)
+  @deprecated("use withName instead")
+  def valueOf(s: String) = values.find(_.toString == s)
 
-  /** used to reverse engineer bit locations from pre-defined bit masks */
-  def maskToBit(n: Long) = {
-    assert(n != 0)
-    var bit = 0
-    var m = n
-    while ((m & 1) != 1) {
-      m = m >> 1
-      bit += 1
-    }
-    assert(m == 1)
-    bit
-  }
+  /** A new iterator over all values of this enumeration. */
+  @deprecated("use values.iterator instead")
+  final def iterator: Iterator[Value] = values.iterator
+  
+  /** Apply a function f to all values of this enumeration. */
+  @deprecated("use values.foreach instead")
+  def foreach(f: Value => Unit): Unit = this.iterator foreach f
+  
+  /** Apply a predicate p to all values of this enumeration and return
+    * true, iff the predicate yields true for all values. 
+   */
+  @deprecated("use values.forall instead")
+  def forall(p: Value => Boolean): Boolean = this.iterator forall p
+  
+  /** Apply a predicate p to all values of this enumeration and return
+    * true, iff there is at least one value for which p yields true.
+    */
+  @deprecated("use values.exists instead")
+  def exists(p: Value => Boolean): Boolean = this.iterator exists p
+  
+  /** Returns an iterator resulting from applying the given function f to each
+    * value of this enumeration.
+    */
+  @deprecated("use values.map instead")
+  def map[B](f: Value => B): Iterator[B] = this.iterator map f
+  
+  /** Applies the given function f to each value of this enumeration, then
+    * concatenates the results. 
+    */
+  @deprecated("use values.flatMap instead")
+  def flatMap[B](f: Value => Iterator[B]): Iterator[B] = this.iterator flatMap f
+    
+  /** Returns all values of this enumeration that satisfy the predicate p.
+    * The order of values is preserved. 
+    */
+  @deprecated("use values.filter instead")
+  def filter(p: Value => Boolean): Iterator[Value] = this.iterator filter p
 }
diff --git a/src/library/scala/Equals.scala b/src/library/scala/Equals.scala
new file mode 100644
index 0000000..2bb2c56
--- /dev/null
+++ b/src/library/scala/Equals.scala
@@ -0,0 +1,27 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala
+
+/** An interface containing operations for equality.
+ *  The only method not already present in class `AnyRef` is `canEqual`.
+ */
+trait Equals {
+
+  /** A method that should be called from every well-designed equals method
+   *  that is open to be overridden in a subclass. See Programming in Scala,
+   *  Chapter 28 for discussion and design.
+   */
+  def canEqual(that: Any): Boolean
+
+  /** The equality method defined in `AnyRef`.
+   */
+  def equals(that: Any): Boolean
+}
diff --git a/src/library/scala/Equiv.scala b/src/library/scala/Equiv.scala
deleted file mode 100644
index 9ae9a2d..0000000
--- a/src/library/scala/Equiv.scala
+++ /dev/null
@@ -1,41 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: Equiv.scala 16881 2009-01-09 16:28:11Z cunei $
-
-package scala
-
-/** A trait for representing equivalence relations.  It is important to 
- * distinguish between a type that can be compared for equality or 
- * equivalence and a representation of equivalence on some type.  This 
- * trait is for representing the latter.  
- *
- * An <a href="http://en.wikipedia.org/wiki/Equivalence_relation">equivalence 
- * relation</a> is a binary relation on a type.  This relation is exposed as
- * the <code>equiv</code> method of the <code>Equiv</code> trait.  This
- * relation must be:
- * <ul>
- * <li>reflexive: <code>equiv(x, x) == true</code>, for any <code>x</code> of 
- * type <code>T</code>.</li>
- * <li>symmetric: <code>equiv(x, y) == equiv(y, x)</code>, for any <code>x</code> 
- * and <code>y</code> of type <code>T</code>.</li>
- * <li>transitive: if <code>equiv(x, y) == true</code> and <code>equiv(y, z) == true</code> 
- * then <code>equiv(x, z) == true</code>, for any <code>x</code>, <code>y</code>,
- * and <code>z</code> of type <code>T</code>.</li>
- * </ul>
- *
- * @author  Geoffrey Washburn
- * @version 1.0, 2008-04-03
- */
-
-trait Equiv[T] {
-  /** Returns <code>true</code> iff <code>x</code> is equivalent to
-   *  <code>y</code>.  
-   */
-  def equiv(x: T, y: T): Boolean 
-}
diff --git a/src/library/scala/Function.scala b/src/library/scala/Function.scala
index 6746fe8..06df1a5 100644
--- a/src/library/scala/Function.scala
+++ b/src/library/scala/Function.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Function.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala
@@ -16,8 +15,8 @@ package scala
  *  @author  Martin Odersky
  *  @version 1.0, 29/11/2006
  */
-object Function {
-
+object Function
+{
   /** Given a sequence of functions <code>f<sub>1</sub></code>, ...,
    *  <code>f<sub>n</sub></code>, return the function <code>f<sub>1</sub>
    *  andThen ... andThen f<sub>n</sub></code>.
@@ -36,6 +35,7 @@ object Function {
    *  @param f  ...
    *  @return   ...
    */
+  @deprecated("Use `f.curried` instead")
   def curried[a1, a2, b](f: (a1, a2) => b): a1 => a2 => b = {
     x1 => x2 => f(x1, x2)
   }
@@ -45,18 +45,21 @@ object Function {
    *  @param f  ...
    *  @return   ...
    */
+  @deprecated("Use `f.curried` instead")
   def curried[a1, a2, a3, b](f: (a1, a2, a3) => b): a1 => a2 => a3 => b = {
     x1 => x2 => x3 => f(x1, x2, x3)
   }
 
   /** Currying for functions of arity 4.
    */
+  @deprecated("Use `f.curried` instead")
   def curried[a1, a2, a3, a4, b](f: (a1, a2, a3, a4) => b): a1 => a2 => a3 => a4 => b = {
     x1 => x2 => x3 => x4 => f(x1, x2, x3, x4)
   }
 
   /** Currying for functions of arity 5.
    */
+  @deprecated("Use `f.curried` instead")
   def curried[a1, a2, a3, a4, a5, b](f: (a1, a2, a3, a4, a5) => b): a1 => a2 => a3 => a4 => a5 => b = {
     x1 => x2 => x3 => x4 => x5 => f(x1, x2, x3, x4, x5)
   }
@@ -89,9 +92,13 @@ object Function {
   /** Tupling for functions of arity 2. This transforms a function
    *  of arity 2 into a unary function that takes a pair of arguments.
    *
+   *  @note  These functions are slotted for deprecation, but it is on
+   *  hold pending superior type inference for tupling anonymous functions.
+   *
    *  @param f  ...
    *  @return   ...
    */
+  // @deprecated("Use `f.tupled` instead")
   def tupled[a1, a2, b](f: (a1, a2) => b): Tuple2[a1, a2] => b = {
     case Tuple2(x1, x2) => f(x1, x2)
   }
@@ -99,6 +106,7 @@ object Function {
   /** Tupling for functions of arity 3. This transforms a function
    *  of arity 3 into a unary function that takes a triple of arguments.
    */
+  // @deprecated("Use `f.tupled` instead") 
   def tupled[a1, a2, a3, b](f: (a1, a2, a3) => b): Tuple3[a1, a2, a3] => b = {
     case Tuple3(x1, x2, x3) => f(x1, x2, x3)
   }
@@ -106,6 +114,7 @@ object Function {
   /** Tupling for functions of arity 4. This transforms a function
    *  of arity 4 into a unary function that takes a 4-tuple of arguments.
    */
+  // @deprecated("Use `f.tupled` instead") 
   def tupled[a1, a2, a3, a4, b](f: (a1, a2, a3, a4) => b): Tuple4[a1, a2, a3, a4] => b = {
     case Tuple4(x1, x2, x3, x4) => f(x1, x2, x3, x4)
   }
@@ -113,6 +122,7 @@ object Function {
   /** Tupling for functions of arity 5. This transforms a function
    *  of arity 5 into a unary function that takes a 5-tuple of arguments.
    */
+  // @deprecated("Use `f.tupled` instead") 
   def tupled[a1, a2, a3, a4, a5, b](f: (a1, a2, a3, a4, a5) => b): Tuple5[a1, a2, a3, a4, a5] => b = {
     case Tuple5(x1, x2, x3, x4, x5) => f(x1, x2, x3, x4, x5)
   }
diff --git a/src/library/scala/Function0.scala b/src/library/scala/Function0.scala
index 1421d68..7eda37d 100644
--- a/src/library/scala/Function0.scala
+++ b/src/library/scala/Function0.scala
@@ -1,24 +1,24 @@
-
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Function0.scala 16881 2009-01-09 16:28:11Z cunei $
 
-// generated by genprod on Wed Apr 23 10:06:16 CEST 2008 (with fancy comment) (with extra methods)
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010 (with fancy comment) 
 
 package scala
 
 
+
+
 /** <p>
  *    Function with 0 parameters.
  *  </p>
  *  <p>
-      In the following example the definition of
+ * In the following example the definition of
  *    <code>currentSeconds</code> is a shorthand for the anonymous class
  *    definition <code>anonfun0</code>:
  *  </p>
@@ -35,9 +35,8 @@ package scala
  *    println(anonfun0())
  *  }</pre>
  */
-trait Function0[+R] extends AnyRef { self =>
+trait Function0[@specialized +R] extends AnyRef { self =>
   def apply(): R
-  override def toString() = "<function>"
+  override def toString() = "<function0>"
   
-
 }
diff --git a/src/library/scala/Function1.scala b/src/library/scala/Function1.scala
index e5eae60..6187eb4 100644
--- a/src/library/scala/Function1.scala
+++ b/src/library/scala/Function1.scala
@@ -1,26 +1,26 @@
-
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Function1.scala 16881 2009-01-09 16:28:11Z cunei $
 
-// generated by genprod on Wed Apr 23 10:06:16 CEST 2008 (with fancy comment) (with extra methods)
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010 (with fancy comment) (with extra methods)
 
 package scala
 
 
+
+
 /** <p>
- *    Function with 1 parameters.
+ *    Function with 1 parameter.
  *  </p>
  *  <p>
-      In the following example the definition of
- *    <code>succ</code> is a shorthand for the anonymous class definition
- *    <code>anonfun1</code>:
+ * In the following example the definition of
+ *    <code>succ</code> is a shorthand for the anonymous class
+ *    definition <code>anonfun1</code>:
  *  </p>
  *  <pre>
  *  <b>object</b> Main <b>extends</b> Application {
@@ -35,14 +35,14 @@ package scala
  *    println(anonfun1(0))
  *  }</pre>
  */
-trait Function1[-T1, +R] extends AnyRef { self =>
+trait Function1[@specialized(scala.Int, scala.Long, scala.Float, scala.Double) -T1, @specialized(scala.Unit, scala.Boolean, scala.Int, scala.Float, scala.Long, scala.Double) +R] extends AnyRef { self =>
   def apply(v1:T1): R
-  override def toString() = "<function>"
+  override def toString() = "<function1>"
   
   /** (f compose g)(x) ==  f(g(x))
    */
   def compose[A](g: A => T1): A => R = { x => apply(g(x)) }
-  
+
   /** (f andThen g)(x) ==  g(f(x))
    */
   def andThen[A](g: R => A): T1 => A = { x => g(apply(x)) }
diff --git a/src/library/scala/Function10.scala b/src/library/scala/Function10.scala
index 966485c..d7780ce 100644
--- a/src/library/scala/Function10.scala
+++ b/src/library/scala/Function10.scala
@@ -1,31 +1,40 @@
-
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Function10.scala 16881 2009-01-09 16:28:11Z cunei $
 
-// generated by genprod on Wed Apr 23 10:06:16 CEST 2008  (with extra methods)
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  (with extra methods)
 
 package scala
 
 
+
+
 /** <p>
  *    Function with 10 parameters.
  *  </p>
  *  
  */
 trait Function10[-T1, -T2, -T3, -T4, -T5, -T6, -T7, -T8, -T9, -T10, +R] extends AnyRef { self =>
-  def apply(v1:T1, v2:T2, v3:T3, v4:T4, v5:T5, v6:T6, v7:T7, v8:T8, v9:T9, v10:T10): R
-  override def toString() = "<function>"
+  def apply(v1:T1,v2:T2,v3:T3,v4:T4,v5:T5,v6:T6,v7:T7,v8:T8,v9:T9,v10:T10): R
+  override def toString() = "<function10>"
   
-  /** f(x1,x2,x3,x4,x5,x6,x7,x8,x9,x10)  == (f.curry)(x1)(x2)(x3)(x4)(x5)(x6)(x7)(x8)(x9)(x10)
+  /** f(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10)  == (f.curried)(x1)(x2)(x3)(x4)(x5)(x6)(x7)(x8)(x9)(x10)
    */
-  def curry: T1 => T2 => T3 => T4 => T5 => T6 => T7 => T8 => T9 => T10 => R = { 
-      (x1: T1) => ((x2: T2, x3: T3, x4: T4, x5: T5, x6: T6, x7: T7, x8: T8, x9: T9, x10: T10) => self.apply(x1,x2,x3,x4,x5,x6,x7,x8,x9,x10)).curry
+  def curried: T1 => T2 => T3 => T4 => T5 => T6 => T7 => T8 => T9 => T10 => R = {
+    (x1: T1) => ((x2: T2, x3: T3, x4: T4, x5: T5, x6: T6, x7: T7, x8: T8, x9: T9, x10: T10) => self.apply(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10)).curried
   }
+  @deprecated("Use 'curried' instead")
+  def curry = curried
+
+  /* f(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10) == (f.tupled)(Tuple10(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10))
+   */
+  def tupled: Tuple10[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10] => R = {
+    case Tuple10(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10) => apply(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10)
+  }
+
 }
diff --git a/src/library/scala/Function11.scala b/src/library/scala/Function11.scala
index b3c8bb8..39af61d 100644
--- a/src/library/scala/Function11.scala
+++ b/src/library/scala/Function11.scala
@@ -1,31 +1,40 @@
-
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Function11.scala 16881 2009-01-09 16:28:11Z cunei $
 
-// generated by genprod on Wed Apr 23 10:06:16 CEST 2008  (with extra methods)
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  (with extra methods)
 
 package scala
 
 
+
+
 /** <p>
  *    Function with 11 parameters.
  *  </p>
  *  
  */
 trait Function11[-T1, -T2, -T3, -T4, -T5, -T6, -T7, -T8, -T9, -T10, -T11, +R] extends AnyRef { self =>
-  def apply(v1:T1, v2:T2, v3:T3, v4:T4, v5:T5, v6:T6, v7:T7, v8:T8, v9:T9, v10:T10, v11:T11): R
-  override def toString() = "<function>"
+  def apply(v1:T1,v2:T2,v3:T3,v4:T4,v5:T5,v6:T6,v7:T7,v8:T8,v9:T9,v10:T10,v11:T11): R
+  override def toString() = "<function11>"
   
-  /** f(x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11)  == (f.curry)(x1)(x2)(x3)(x4)(x5)(x6)(x7)(x8)(x9)(x10)(x11)
+  /** f(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11)  == (f.curried)(x1)(x2)(x3)(x4)(x5)(x6)(x7)(x8)(x9)(x10)(x11)
    */
-  def curry: T1 => T2 => T3 => T4 => T5 => T6 => T7 => T8 => T9 => T10 => T11 => R = { 
-      (x1: T1) => ((x2: T2, x3: T3, x4: T4, x5: T5, x6: T6, x7: T7, x8: T8, x9: T9, x10: T10, x11: T11) => self.apply(x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11)).curry
+  def curried: T1 => T2 => T3 => T4 => T5 => T6 => T7 => T8 => T9 => T10 => T11 => R = {
+    (x1: T1) => ((x2: T2, x3: T3, x4: T4, x5: T5, x6: T6, x7: T7, x8: T8, x9: T9, x10: T10, x11: T11) => self.apply(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11)).curried
   }
+  @deprecated("Use 'curried' instead")
+  def curry = curried
+
+  /* f(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11) == (f.tupled)(Tuple11(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11))
+   */
+  def tupled: Tuple11[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11] => R = {
+    case Tuple11(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11) => apply(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11)
+  }
+
 }
diff --git a/src/library/scala/Function12.scala b/src/library/scala/Function12.scala
index e3a442f..68f199b 100644
--- a/src/library/scala/Function12.scala
+++ b/src/library/scala/Function12.scala
@@ -1,31 +1,40 @@
-
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Function12.scala 16881 2009-01-09 16:28:11Z cunei $
 
-// generated by genprod on Wed Apr 23 10:06:16 CEST 2008  (with extra methods)
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  (with extra methods)
 
 package scala
 
 
+
+
 /** <p>
  *    Function with 12 parameters.
  *  </p>
  *  
  */
 trait Function12[-T1, -T2, -T3, -T4, -T5, -T6, -T7, -T8, -T9, -T10, -T11, -T12, +R] extends AnyRef { self =>
-  def apply(v1:T1, v2:T2, v3:T3, v4:T4, v5:T5, v6:T6, v7:T7, v8:T8, v9:T9, v10:T10, v11:T11, v12:T12): R
-  override def toString() = "<function>"
+  def apply(v1:T1,v2:T2,v3:T3,v4:T4,v5:T5,v6:T6,v7:T7,v8:T8,v9:T9,v10:T10,v11:T11,v12:T12): R
+  override def toString() = "<function12>"
   
-  /** f(x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12)  == (f.curry)(x1)(x2)(x3)(x4)(x5)(x6)(x7)(x8)(x9)(x10)(x11)(x12)
+  /** f(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12)  == (f.curried)(x1)(x2)(x3)(x4)(x5)(x6)(x7)(x8)(x9)(x10)(x11)(x12)
    */
-  def curry: T1 => T2 => T3 => T4 => T5 => T6 => T7 => T8 => T9 => T10 => T11 => T12 => R = { 
-      (x1: T1) => ((x2: T2, x3: T3, x4: T4, x5: T5, x6: T6, x7: T7, x8: T8, x9: T9, x10: T10, x11: T11, x12: T12) => self.apply(x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12)).curry
+  def curried: T1 => T2 => T3 => T4 => T5 => T6 => T7 => T8 => T9 => T10 => T11 => T12 => R = {
+    (x1: T1) => ((x2: T2, x3: T3, x4: T4, x5: T5, x6: T6, x7: T7, x8: T8, x9: T9, x10: T10, x11: T11, x12: T12) => self.apply(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12)).curried
   }
+  @deprecated("Use 'curried' instead")
+  def curry = curried
+
+  /* f(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12) == (f.tupled)(Tuple12(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12))
+   */
+  def tupled: Tuple12[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12] => R = {
+    case Tuple12(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12) => apply(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12)
+  }
+
 }
diff --git a/src/library/scala/Function13.scala b/src/library/scala/Function13.scala
index 2f187c0..d7ee6ba 100644
--- a/src/library/scala/Function13.scala
+++ b/src/library/scala/Function13.scala
@@ -1,31 +1,40 @@
-
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Function13.scala 16881 2009-01-09 16:28:11Z cunei $
 
-// generated by genprod on Wed Apr 23 10:06:16 CEST 2008  (with extra methods)
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  (with extra methods)
 
 package scala
 
 
+
+
 /** <p>
  *    Function with 13 parameters.
  *  </p>
  *  
  */
 trait Function13[-T1, -T2, -T3, -T4, -T5, -T6, -T7, -T8, -T9, -T10, -T11, -T12, -T13, +R] extends AnyRef { self =>
-  def apply(v1:T1, v2:T2, v3:T3, v4:T4, v5:T5, v6:T6, v7:T7, v8:T8, v9:T9, v10:T10, v11:T11, v12:T12, v13:T13): R
-  override def toString() = "<function>"
+  def apply(v1:T1,v2:T2,v3:T3,v4:T4,v5:T5,v6:T6,v7:T7,v8:T8,v9:T9,v10:T10,v11:T11,v12:T12,v13:T13): R
+  override def toString() = "<function13>"
   
-  /** f(x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12,x13)  == (f.curry)(x1)(x2)(x3)(x4)(x5)(x6)(x7)(x8)(x9)(x10)(x11)(x12)(x13)
+  /** f(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13)  == (f.curried)(x1)(x2)(x3)(x4)(x5)(x6)(x7)(x8)(x9)(x10)(x11)(x12)(x13)
    */
-  def curry: T1 => T2 => T3 => T4 => T5 => T6 => T7 => T8 => T9 => T10 => T11 => T12 => T13 => R = { 
-      (x1: T1) => ((x2: T2, x3: T3, x4: T4, x5: T5, x6: T6, x7: T7, x8: T8, x9: T9, x10: T10, x11: T11, x12: T12, x13: T13) => self.apply(x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12,x13)).curry
+  def curried: T1 => T2 => T3 => T4 => T5 => T6 => T7 => T8 => T9 => T10 => T11 => T12 => T13 => R = {
+    (x1: T1) => ((x2: T2, x3: T3, x4: T4, x5: T5, x6: T6, x7: T7, x8: T8, x9: T9, x10: T10, x11: T11, x12: T12, x13: T13) => self.apply(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13)).curried
   }
+  @deprecated("Use 'curried' instead")
+  def curry = curried
+
+  /* f(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13) == (f.tupled)(Tuple13(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13))
+   */
+  def tupled: Tuple13[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13] => R = {
+    case Tuple13(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13) => apply(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13)
+  }
+
 }
diff --git a/src/library/scala/Function14.scala b/src/library/scala/Function14.scala
index e8429a7..0421449 100644
--- a/src/library/scala/Function14.scala
+++ b/src/library/scala/Function14.scala
@@ -1,31 +1,40 @@
-
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Function14.scala 16881 2009-01-09 16:28:11Z cunei $
 
-// generated by genprod on Wed Apr 23 10:06:16 CEST 2008  (with extra methods)
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  (with extra methods)
 
 package scala
 
 
+
+
 /** <p>
  *    Function with 14 parameters.
  *  </p>
  *  
  */
 trait Function14[-T1, -T2, -T3, -T4, -T5, -T6, -T7, -T8, -T9, -T10, -T11, -T12, -T13, -T14, +R] extends AnyRef { self =>
-  def apply(v1:T1, v2:T2, v3:T3, v4:T4, v5:T5, v6:T6, v7:T7, v8:T8, v9:T9, v10:T10, v11:T11, v12:T12, v13:T13, v14:T14): R
-  override def toString() = "<function>"
+  def apply(v1:T1,v2:T2,v3:T3,v4:T4,v5:T5,v6:T6,v7:T7,v8:T8,v9:T9,v10:T10,v11:T11,v12:T12,v13:T13,v14:T14): R
+  override def toString() = "<function14>"
   
-  /** f(x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12,x13,x14)  == (f.curry)(x1)(x2)(x3)(x4)(x5)(x6)(x7)(x8)(x9)(x10)(x11)(x12)(x13)(x14)
+  /** f(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14)  == (f.curried)(x1)(x2)(x3)(x4)(x5)(x6)(x7)(x8)(x9)(x10)(x11)(x12)(x13)(x14)
    */
-  def curry: T1 => T2 => T3 => T4 => T5 => T6 => T7 => T8 => T9 => T10 => T11 => T12 => T13 => T14 => R = { 
-      (x1: T1) => ((x2: T2, x3: T3, x4: T4, x5: T5, x6: T6, x7: T7, x8: T8, x9: T9, x10: T10, x11: T11, x12: T12, x13: T13, x14: T14) => self.apply(x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12,x13,x14)).curry
+  def curried: T1 => T2 => T3 => T4 => T5 => T6 => T7 => T8 => T9 => T10 => T11 => T12 => T13 => T14 => R = {
+    (x1: T1) => ((x2: T2, x3: T3, x4: T4, x5: T5, x6: T6, x7: T7, x8: T8, x9: T9, x10: T10, x11: T11, x12: T12, x13: T13, x14: T14) => self.apply(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14)).curried
   }
+  @deprecated("Use 'curried' instead")
+  def curry = curried
+
+  /* f(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14) == (f.tupled)(Tuple14(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14))
+   */
+  def tupled: Tuple14[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14] => R = {
+    case Tuple14(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14) => apply(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14)
+  }
+
 }
diff --git a/src/library/scala/Function15.scala b/src/library/scala/Function15.scala
index 71402b8..8958025 100644
--- a/src/library/scala/Function15.scala
+++ b/src/library/scala/Function15.scala
@@ -1,31 +1,40 @@
-
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Function15.scala 16881 2009-01-09 16:28:11Z cunei $
 
-// generated by genprod on Wed Apr 23 10:06:16 CEST 2008  (with extra methods)
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  (with extra methods)
 
 package scala
 
 
+
+
 /** <p>
  *    Function with 15 parameters.
  *  </p>
  *  
  */
 trait Function15[-T1, -T2, -T3, -T4, -T5, -T6, -T7, -T8, -T9, -T10, -T11, -T12, -T13, -T14, -T15, +R] extends AnyRef { self =>
-  def apply(v1:T1, v2:T2, v3:T3, v4:T4, v5:T5, v6:T6, v7:T7, v8:T8, v9:T9, v10:T10, v11:T11, v12:T12, v13:T13, v14:T14, v15:T15): R
-  override def toString() = "<function>"
+  def apply(v1:T1,v2:T2,v3:T3,v4:T4,v5:T5,v6:T6,v7:T7,v8:T8,v9:T9,v10:T10,v11:T11,v12:T12,v13:T13,v14:T14,v15:T15): R
+  override def toString() = "<function15>"
   
-  /** f(x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12,x13,x14,x15)  == (f.curry)(x1)(x2)(x3)(x4)(x5)(x6)(x7)(x8)(x9)(x10)(x11)(x12)(x13)(x14)(x15)
+  /** f(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15)  == (f.curried)(x1)(x2)(x3)(x4)(x5)(x6)(x7)(x8)(x9)(x10)(x11)(x12)(x13)(x14)(x15)
    */
-  def curry: T1 => T2 => T3 => T4 => T5 => T6 => T7 => T8 => T9 => T10 => T11 => T12 => T13 => T14 => T15 => R = { 
-      (x1: T1) => ((x2: T2, x3: T3, x4: T4, x5: T5, x6: T6, x7: T7, x8: T8, x9: T9, x10: T10, x11: T11, x12: T12, x13: T13, x14: T14, x15: T15) => self.apply(x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12,x13,x14,x15)).curry
+  def curried: T1 => T2 => T3 => T4 => T5 => T6 => T7 => T8 => T9 => T10 => T11 => T12 => T13 => T14 => T15 => R = {
+    (x1: T1) => ((x2: T2, x3: T3, x4: T4, x5: T5, x6: T6, x7: T7, x8: T8, x9: T9, x10: T10, x11: T11, x12: T12, x13: T13, x14: T14, x15: T15) => self.apply(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15)).curried
   }
+  @deprecated("Use 'curried' instead")
+  def curry = curried
+
+  /* f(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15) == (f.tupled)(Tuple15(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15))
+   */
+  def tupled: Tuple15[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15] => R = {
+    case Tuple15(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15) => apply(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15)
+  }
+
 }
diff --git a/src/library/scala/Function16.scala b/src/library/scala/Function16.scala
index c5e3a0b..a0b5e41 100644
--- a/src/library/scala/Function16.scala
+++ b/src/library/scala/Function16.scala
@@ -1,31 +1,40 @@
-
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Function16.scala 16881 2009-01-09 16:28:11Z cunei $
 
-// generated by genprod on Wed Apr 23 10:06:16 CEST 2008  (with extra methods)
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  (with extra methods)
 
 package scala
 
 
+
+
 /** <p>
  *    Function with 16 parameters.
  *  </p>
  *  
  */
 trait Function16[-T1, -T2, -T3, -T4, -T5, -T6, -T7, -T8, -T9, -T10, -T11, -T12, -T13, -T14, -T15, -T16, +R] extends AnyRef { self =>
-  def apply(v1:T1, v2:T2, v3:T3, v4:T4, v5:T5, v6:T6, v7:T7, v8:T8, v9:T9, v10:T10, v11:T11, v12:T12, v13:T13, v14:T14, v15:T15, v16:T16): R
-  override def toString() = "<function>"
+  def apply(v1:T1,v2:T2,v3:T3,v4:T4,v5:T5,v6:T6,v7:T7,v8:T8,v9:T9,v10:T10,v11:T11,v12:T12,v13:T13,v14:T14,v15:T15,v16:T16): R
+  override def toString() = "<function16>"
   
-  /** f(x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12,x13,x14,x15,x16)  == (f.curry)(x1)(x2)(x3)(x4)(x5)(x6)(x7)(x8)(x9)(x10)(x11)(x12)(x13)(x14)(x15)(x16)
+  /** f(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16)  == (f.curried)(x1)(x2)(x3)(x4)(x5)(x6)(x7)(x8)(x9)(x10)(x11)(x12)(x13)(x14)(x15)(x16)
    */
-  def curry: T1 => T2 => T3 => T4 => T5 => T6 => T7 => T8 => T9 => T10 => T11 => T12 => T13 => T14 => T15 => T16 => R = { 
-      (x1: T1) => ((x2: T2, x3: T3, x4: T4, x5: T5, x6: T6, x7: T7, x8: T8, x9: T9, x10: T10, x11: T11, x12: T12, x13: T13, x14: T14, x15: T15, x16: T16) => self.apply(x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12,x13,x14,x15,x16)).curry
+  def curried: T1 => T2 => T3 => T4 => T5 => T6 => T7 => T8 => T9 => T10 => T11 => T12 => T13 => T14 => T15 => T16 => R = {
+    (x1: T1) => ((x2: T2, x3: T3, x4: T4, x5: T5, x6: T6, x7: T7, x8: T8, x9: T9, x10: T10, x11: T11, x12: T12, x13: T13, x14: T14, x15: T15, x16: T16) => self.apply(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16)).curried
   }
+  @deprecated("Use 'curried' instead")
+  def curry = curried
+
+  /* f(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16) == (f.tupled)(Tuple16(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16))
+   */
+  def tupled: Tuple16[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16] => R = {
+    case Tuple16(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16) => apply(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16)
+  }
+
 }
diff --git a/src/library/scala/Function17.scala b/src/library/scala/Function17.scala
index 932d0e9..bc708fd 100644
--- a/src/library/scala/Function17.scala
+++ b/src/library/scala/Function17.scala
@@ -1,31 +1,40 @@
-
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Function17.scala 16881 2009-01-09 16:28:11Z cunei $
 
-// generated by genprod on Wed Apr 23 10:06:16 CEST 2008  (with extra methods)
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  (with extra methods)
 
 package scala
 
 
+
+
 /** <p>
  *    Function with 17 parameters.
  *  </p>
  *  
  */
 trait Function17[-T1, -T2, -T3, -T4, -T5, -T6, -T7, -T8, -T9, -T10, -T11, -T12, -T13, -T14, -T15, -T16, -T17, +R] extends AnyRef { self =>
-  def apply(v1:T1, v2:T2, v3:T3, v4:T4, v5:T5, v6:T6, v7:T7, v8:T8, v9:T9, v10:T10, v11:T11, v12:T12, v13:T13, v14:T14, v15:T15, v16:T16, v17:T17): R
-  override def toString() = "<function>"
+  def apply(v1:T1,v2:T2,v3:T3,v4:T4,v5:T5,v6:T6,v7:T7,v8:T8,v9:T9,v10:T10,v11:T11,v12:T12,v13:T13,v14:T14,v15:T15,v16:T16,v17:T17): R
+  override def toString() = "<function17>"
   
-  /** f(x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12,x13,x14,x15,x16,x17)  == (f.curry)(x1)(x2)(x3)(x4)(x5)(x6)(x7)(x8)(x9)(x10)(x11)(x12)(x13)(x14)(x15)(x16)(x17)
+  /** f(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17)  == (f.curried)(x1)(x2)(x3)(x4)(x5)(x6)(x7)(x8)(x9)(x10)(x11)(x12)(x13)(x14)(x15)(x16)(x17)
    */
-  def curry: T1 => T2 => T3 => T4 => T5 => T6 => T7 => T8 => T9 => T10 => T11 => T12 => T13 => T14 => T15 => T16 => T17 => R = { 
-      (x1: T1) => ((x2: T2, x3: T3, x4: T4, x5: T5, x6: T6, x7: T7, x8: T8, x9: T9, x10: T10, x11: T11, x12: T12, x13: T13, x14: T14, x15: T15, x16: T16, x17: T17) => self.apply(x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12,x13,x14,x15,x16,x17)).curry
+  def curried: T1 => T2 => T3 => T4 => T5 => T6 => T7 => T8 => T9 => T10 => T11 => T12 => T13 => T14 => T15 => T16 => T17 => R = {
+    (x1: T1) => ((x2: T2, x3: T3, x4: T4, x5: T5, x6: T6, x7: T7, x8: T8, x9: T9, x10: T10, x11: T11, x12: T12, x13: T13, x14: T14, x15: T15, x16: T16, x17: T17) => self.apply(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17)).curried
   }
+  @deprecated("Use 'curried' instead")
+  def curry = curried
+
+  /* f(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17) == (f.tupled)(Tuple17(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17))
+   */
+  def tupled: Tuple17[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17] => R = {
+    case Tuple17(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17) => apply(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17)
+  }
+
 }
diff --git a/src/library/scala/Function18.scala b/src/library/scala/Function18.scala
index 28de0d9..c7b8ac6 100644
--- a/src/library/scala/Function18.scala
+++ b/src/library/scala/Function18.scala
@@ -1,31 +1,40 @@
-
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Function18.scala 16881 2009-01-09 16:28:11Z cunei $
 
-// generated by genprod on Wed Apr 23 10:06:16 CEST 2008  (with extra methods)
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  (with extra methods)
 
 package scala
 
 
+
+
 /** <p>
  *    Function with 18 parameters.
  *  </p>
  *  
  */
 trait Function18[-T1, -T2, -T3, -T4, -T5, -T6, -T7, -T8, -T9, -T10, -T11, -T12, -T13, -T14, -T15, -T16, -T17, -T18, +R] extends AnyRef { self =>
-  def apply(v1:T1, v2:T2, v3:T3, v4:T4, v5:T5, v6:T6, v7:T7, v8:T8, v9:T9, v10:T10, v11:T11, v12:T12, v13:T13, v14:T14, v15:T15, v16:T16, v17:T17, v18:T18): R
-  override def toString() = "<function>"
+  def apply(v1:T1,v2:T2,v3:T3,v4:T4,v5:T5,v6:T6,v7:T7,v8:T8,v9:T9,v10:T10,v11:T11,v12:T12,v13:T13,v14:T14,v15:T15,v16:T16,v17:T17,v18:T18): R
+  override def toString() = "<function18>"
   
-  /** f(x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12,x13,x14,x15,x16,x17,x18)  == (f.curry)(x1)(x2)(x3)(x4)(x5)(x6)(x7)(x8)(x9)(x10)(x11)(x12)(x13)(x14)(x15)(x16)(x17)(x18)
+  /** f(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17, x18)  == (f.curried)(x1)(x2)(x3)(x4)(x5)(x6)(x7)(x8)(x9)(x10)(x11)(x12)(x13)(x14)(x15)(x16)(x17)(x18)
    */
-  def curry: T1 => T2 => T3 => T4 => T5 => T6 => T7 => T8 => T9 => T10 => T11 => T12 => T13 => T14 => T15 => T16 => T17 => T18 => R = { 
-      (x1: T1) => ((x2: T2, x3: T3, x4: T4, x5: T5, x6: T6, x7: T7, x8: T8, x9: T9, x10: T10, x11: T11, x12: T12, x13: T13, x14: T14, x15: T15, x16: T16, x17: T17, x18: T18) => self.apply(x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12,x13,x14,x15,x16,x17,x18)).curry
+  def curried: T1 => T2 => T3 => T4 => T5 => T6 => T7 => T8 => T9 => T10 => T11 => T12 => T13 => T14 => T15 => T16 => T17 => T18 => R = {
+    (x1: T1) => ((x2: T2, x3: T3, x4: T4, x5: T5, x6: T6, x7: T7, x8: T8, x9: T9, x10: T10, x11: T11, x12: T12, x13: T13, x14: T14, x15: T15, x16: T16, x17: T17, x18: T18) => self.apply(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17, x18)).curried
   }
+  @deprecated("Use 'curried' instead")
+  def curry = curried
+
+  /* f(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17, x18) == (f.tupled)(Tuple18(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17, x18))
+   */
+  def tupled: Tuple18[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18] => R = {
+    case Tuple18(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17, x18) => apply(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17, x18)
+  }
+
 }
diff --git a/src/library/scala/Function19.scala b/src/library/scala/Function19.scala
index 51888e4..0bdf209 100644
--- a/src/library/scala/Function19.scala
+++ b/src/library/scala/Function19.scala
@@ -1,31 +1,40 @@
-
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Function19.scala 16881 2009-01-09 16:28:11Z cunei $
 
-// generated by genprod on Wed Apr 23 10:06:16 CEST 2008  (with extra methods)
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  (with extra methods)
 
 package scala
 
 
+
+
 /** <p>
  *    Function with 19 parameters.
  *  </p>
  *  
  */
 trait Function19[-T1, -T2, -T3, -T4, -T5, -T6, -T7, -T8, -T9, -T10, -T11, -T12, -T13, -T14, -T15, -T16, -T17, -T18, -T19, +R] extends AnyRef { self =>
-  def apply(v1:T1, v2:T2, v3:T3, v4:T4, v5:T5, v6:T6, v7:T7, v8:T8, v9:T9, v10:T10, v11:T11, v12:T12, v13:T13, v14:T14, v15:T15, v16:T16, v17:T17, v18:T18, v19:T19): R
-  override def toString() = "<function>"
+  def apply(v1:T1,v2:T2,v3:T3,v4:T4,v5:T5,v6:T6,v7:T7,v8:T8,v9:T9,v10:T10,v11:T11,v12:T12,v13:T13,v14:T14,v15:T15,v16:T16,v17:T17,v18:T18,v19:T19): R
+  override def toString() = "<function19>"
   
-  /** f(x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12,x13,x14,x15,x16,x17,x18,x19)  == (f.curry)(x1)(x2)(x3)(x4)(x5)(x6)(x7)(x8)(x9)(x10)(x11)(x12)(x13)(x14)(x15)(x16)(x17)(x18)(x19)
+  /** f(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17, x18, x19)  == (f.curried)(x1)(x2)(x3)(x4)(x5)(x6)(x7)(x8)(x9)(x10)(x11)(x12)(x13)(x14)(x15)(x16)(x17)(x18)(x19)
    */
-  def curry: T1 => T2 => T3 => T4 => T5 => T6 => T7 => T8 => T9 => T10 => T11 => T12 => T13 => T14 => T15 => T16 => T17 => T18 => T19 => R = { 
-      (x1: T1) => ((x2: T2, x3: T3, x4: T4, x5: T5, x6: T6, x7: T7, x8: T8, x9: T9, x10: T10, x11: T11, x12: T12, x13: T13, x14: T14, x15: T15, x16: T16, x17: T17, x18: T18, x19: T19) => self.apply(x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12,x13,x14,x15,x16,x17,x18,x19)).curry
+  def curried: T1 => T2 => T3 => T4 => T5 => T6 => T7 => T8 => T9 => T10 => T11 => T12 => T13 => T14 => T15 => T16 => T17 => T18 => T19 => R = {
+    (x1: T1) => ((x2: T2, x3: T3, x4: T4, x5: T5, x6: T6, x7: T7, x8: T8, x9: T9, x10: T10, x11: T11, x12: T12, x13: T13, x14: T14, x15: T15, x16: T16, x17: T17, x18: T18, x19: T19) => self.apply(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17, x18, x19)).curried
   }
+  @deprecated("Use 'curried' instead")
+  def curry = curried
+
+  /* f(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17, x18, x19) == (f.tupled)(Tuple19(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17, x18, x19))
+   */
+  def tupled: Tuple19[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19] => R = {
+    case Tuple19(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17, x18, x19) => apply(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17, x18, x19)
+  }
+
 }
diff --git a/src/library/scala/Function2.scala b/src/library/scala/Function2.scala
index 7429b93..fd2c4cd 100644
--- a/src/library/scala/Function2.scala
+++ b/src/library/scala/Function2.scala
@@ -1,26 +1,26 @@
-
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Function2.scala 16881 2009-01-09 16:28:11Z cunei $
 
-// generated by genprod on Wed Apr 23 10:06:16 CEST 2008 (with fancy comment) (with extra methods)
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010 (with fancy comment) (with extra methods)
 
 package scala
 
 
+
+
 /** <p>
  *    Function with 2 parameters.
  *  </p>
  *  <p>
-      In the following example the definition of
- *    <code>max</code> is a shorthand for the anonymous class definition
- *    <code>anonfun2</code>:
+ * In the following example the definition of
+ *    <code>max</code> is a shorthand for the anonymous class
+ *    definition <code>anonfun2</code>:
  *  </p>
  *  <pre>
  *  <b>object</b> Main <b>extends</b> Application {
@@ -35,13 +35,22 @@ package scala
  *    println(anonfun2(0, 1))
  *  }</pre>
  */
-trait Function2[-T1, -T2, +R] extends AnyRef { self =>
-  def apply(v1:T1, v2:T2): R
-  override def toString() = "<function>"
+trait Function2[@specialized(scala.Int, scala.Long, scala.Double) -T1, @specialized(scala.Int, scala.Long, scala.Double) -T2, @specialized(scala.Unit, scala.Boolean, scala.Int, scala.Float, scala.Long, scala.Double) +R] extends AnyRef { self =>
+  def apply(v1:T1,v2:T2): R
+  override def toString() = "<function2>"
   
-  /** f(x1,x2)  == (f.curry)(x1)(x2)
+  /** f(x1, x2)  == (f.curried)(x1)(x2)
    */
-  def curry: T1 => T2 => R = { 
-      (x1: T1) => (x2: T2) => apply(x1,x2)
+  def curried: T1 => T2 => R = {
+    (x1: T1) => (x2: T2) => apply(x1, x2)
   }
+  @deprecated("Use 'curried' instead")
+  def curry = curried
+
+  /* f(x1, x2) == (f.tupled)(Tuple2(x1, x2))
+   */
+  def tupled: Tuple2[T1, T2] => R = {
+    case Tuple2(x1, x2) => apply(x1, x2)
+  }
+
 }
diff --git a/src/library/scala/Function20.scala b/src/library/scala/Function20.scala
index cfe0617..29436fe 100644
--- a/src/library/scala/Function20.scala
+++ b/src/library/scala/Function20.scala
@@ -1,31 +1,40 @@
-
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Function20.scala 16881 2009-01-09 16:28:11Z cunei $
 
-// generated by genprod on Wed Apr 23 10:06:16 CEST 2008  (with extra methods)
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  (with extra methods)
 
 package scala
 
 
+
+
 /** <p>
  *    Function with 20 parameters.
  *  </p>
  *  
  */
 trait Function20[-T1, -T2, -T3, -T4, -T5, -T6, -T7, -T8, -T9, -T10, -T11, -T12, -T13, -T14, -T15, -T16, -T17, -T18, -T19, -T20, +R] extends AnyRef { self =>
-  def apply(v1:T1, v2:T2, v3:T3, v4:T4, v5:T5, v6:T6, v7:T7, v8:T8, v9:T9, v10:T10, v11:T11, v12:T12, v13:T13, v14:T14, v15:T15, v16:T16, v17:T17, v18:T18, v19:T19, v20:T20): R
-  override def toString() = "<function>"
+  def apply(v1:T1,v2:T2,v3:T3,v4:T4,v5:T5,v6:T6,v7:T7,v8:T8,v9:T9,v10:T10,v11:T11,v12:T12,v13:T13,v14:T14,v15:T15,v16:T16,v17:T17,v18:T18,v19:T19,v20:T20): R
+  override def toString() = "<function20>"
   
-  /** f(x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12,x13,x14,x15,x16,x17,x18,x19,x20)  == (f.curry)(x1)(x2)(x3)(x4)(x5)(x6)(x7)(x8)(x9)(x10)(x11)(x12)(x13)(x14)(x15)(x16)(x17)(x18)(x19)(x20)
+  /** f(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17, x18, x19, x20)  == (f.curried)(x1)(x2)(x3)(x4)(x5)(x6)(x7)(x8)(x9)(x10)(x11)(x12)(x13)(x14)(x15)(x16)(x17)(x18)(x19)(x20)
    */
-  def curry: T1 => T2 => T3 => T4 => T5 => T6 => T7 => T8 => T9 => T10 => T11 => T12 => T13 => T14 => T15 => T16 => T17 => T18 => T19 => T20 => R = { 
-      (x1: T1) => ((x2: T2, x3: T3, x4: T4, x5: T5, x6: T6, x7: T7, x8: T8, x9: T9, x10: T10, x11: T11, x12: T12, x13: T13, x14: T14, x15: T15, x16: T16, x17: T17, x18: T18, x19: T19, x20: T20) => self.apply(x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12,x13,x14,x15,x16,x17,x18,x19,x20)).curry
+  def curried: T1 => T2 => T3 => T4 => T5 => T6 => T7 => T8 => T9 => T10 => T11 => T12 => T13 => T14 => T15 => T16 => T17 => T18 => T19 => T20 => R = {
+    (x1: T1) => ((x2: T2, x3: T3, x4: T4, x5: T5, x6: T6, x7: T7, x8: T8, x9: T9, x10: T10, x11: T11, x12: T12, x13: T13, x14: T14, x15: T15, x16: T16, x17: T17, x18: T18, x19: T19, x20: T20) => self.apply(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17, x18, x19, x20)).curried
   }
+  @deprecated("Use 'curried' instead")
+  def curry = curried
+
+  /* f(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17, x18, x19, x20) == (f.tupled)(Tuple20(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17, x18, x19, x20))
+   */
+  def tupled: Tuple20[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20] => R = {
+    case Tuple20(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17, x18, x19, x20) => apply(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17, x18, x19, x20)
+  }
+
 }
diff --git a/src/library/scala/Function21.scala b/src/library/scala/Function21.scala
index dfdede4..76ad32a 100644
--- a/src/library/scala/Function21.scala
+++ b/src/library/scala/Function21.scala
@@ -1,31 +1,40 @@
-
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Function21.scala 16881 2009-01-09 16:28:11Z cunei $
 
-// generated by genprod on Wed Apr 23 10:06:16 CEST 2008  (with extra methods)
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  (with extra methods)
 
 package scala
 
 
+
+
 /** <p>
  *    Function with 21 parameters.
  *  </p>
  *  
  */
 trait Function21[-T1, -T2, -T3, -T4, -T5, -T6, -T7, -T8, -T9, -T10, -T11, -T12, -T13, -T14, -T15, -T16, -T17, -T18, -T19, -T20, -T21, +R] extends AnyRef { self =>
-  def apply(v1:T1, v2:T2, v3:T3, v4:T4, v5:T5, v6:T6, v7:T7, v8:T8, v9:T9, v10:T10, v11:T11, v12:T12, v13:T13, v14:T14, v15:T15, v16:T16, v17:T17, v18:T18, v19:T19, v20:T20, v21:T21): R
-  override def toString() = "<function>"
+  def apply(v1:T1,v2:T2,v3:T3,v4:T4,v5:T5,v6:T6,v7:T7,v8:T8,v9:T9,v10:T10,v11:T11,v12:T12,v13:T13,v14:T14,v15:T15,v16:T16,v17:T17,v18:T18,v19:T19,v20:T20,v21:T21): R
+  override def toString() = "<function21>"
   
-  /** f(x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12,x13,x14,x15,x16,x17,x18,x19,x20,x21)  == (f.curry)(x1)(x2)(x3)(x4)(x5)(x6)(x7)(x8)(x9)(x10)(x11)(x12)(x13)(x14)(x15)(x16)(x17)(x18)(x19)(x20)(x21)
+  /** f(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17, x18, x19, x20, x21)  == (f.curried)(x1)(x2)(x3)(x4)(x5)(x6)(x7)(x8)(x9)(x10)(x11)(x12)(x13)(x14)(x15)(x16)(x17)(x18)(x19)(x20)(x21)
    */
-  def curry: T1 => T2 => T3 => T4 => T5 => T6 => T7 => T8 => T9 => T10 => T11 => T12 => T13 => T14 => T15 => T16 => T17 => T18 => T19 => T20 => T21 => R = { 
-      (x1: T1) => ((x2: T2, x3: T3, x4: T4, x5: T5, x6: T6, x7: T7, x8: T8, x9: T9, x10: T10, x11: T11, x12: T12, x13: T13, x14: T14, x15: T15, x16: T16, x17: T17, x18: T18, x19: T19, x20: T20, x21: T21) => self.apply(x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12,x13,x14,x15,x16,x17,x18,x19,x20,x21)).curry
+  def curried: T1 => T2 => T3 => T4 => T5 => T6 => T7 => T8 => T9 => T10 => T11 => T12 => T13 => T14 => T15 => T16 => T17 => T18 => T19 => T20 => T21 => R = {
+    (x1: T1) => ((x2: T2, x3: T3, x4: T4, x5: T5, x6: T6, x7: T7, x8: T8, x9: T9, x10: T10, x11: T11, x12: T12, x13: T13, x14: T14, x15: T15, x16: T16, x17: T17, x18: T18, x19: T19, x20: T20, x21: T21) => self.apply(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17, x18, x19, x20, x21)).curried
   }
+  @deprecated("Use 'curried' instead")
+  def curry = curried
+
+  /* f(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17, x18, x19, x20, x21) == (f.tupled)(Tuple21(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17, x18, x19, x20, x21))
+   */
+  def tupled: Tuple21[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21] => R = {
+    case Tuple21(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17, x18, x19, x20, x21) => apply(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17, x18, x19, x20, x21)
+  }
+
 }
diff --git a/src/library/scala/Function22.scala b/src/library/scala/Function22.scala
index 8251a2c..f4ec23e 100644
--- a/src/library/scala/Function22.scala
+++ b/src/library/scala/Function22.scala
@@ -1,31 +1,40 @@
-
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Function22.scala 16881 2009-01-09 16:28:11Z cunei $
 
-// generated by genprod on Wed Apr 23 10:06:16 CEST 2008  (with extra methods)
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  (with extra methods)
 
 package scala
 
 
+
+
 /** <p>
  *    Function with 22 parameters.
  *  </p>
  *  
  */
 trait Function22[-T1, -T2, -T3, -T4, -T5, -T6, -T7, -T8, -T9, -T10, -T11, -T12, -T13, -T14, -T15, -T16, -T17, -T18, -T19, -T20, -T21, -T22, +R] extends AnyRef { self =>
-  def apply(v1:T1, v2:T2, v3:T3, v4:T4, v5:T5, v6:T6, v7:T7, v8:T8, v9:T9, v10:T10, v11:T11, v12:T12, v13:T13, v14:T14, v15:T15, v16:T16, v17:T17, v18:T18, v19:T19, v20:T20, v21:T21, v22:T22): R
-  override def toString() = "<function>"
+  def apply(v1:T1,v2:T2,v3:T3,v4:T4,v5:T5,v6:T6,v7:T7,v8:T8,v9:T9,v10:T10,v11:T11,v12:T12,v13:T13,v14:T14,v15:T15,v16:T16,v17:T17,v18:T18,v19:T19,v20:T20,v21:T21,v22:T22): R
+  override def toString() = "<function22>"
   
-  /** f(x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12,x13,x14,x15,x16,x17,x18,x19,x20,x21,x22)  == (f.curry)(x1)(x2)(x3)(x4)(x5)(x6)(x7)(x8)(x9)(x10)(x11)(x12)(x13)(x14)(x15)(x16)(x17)(x18)(x19)(x20)(x21)(x22)
+  /** f(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17, x18, x19, x20, x21, x22)  == (f.curried)(x1)(x2)(x3)(x4)(x5)(x6)(x7)(x8)(x9)(x10)(x11)(x12)(x13)(x14)(x15)(x16)(x17)(x18)(x19)(x20)(x21)(x22)
    */
-  def curry: T1 => T2 => T3 => T4 => T5 => T6 => T7 => T8 => T9 => T10 => T11 => T12 => T13 => T14 => T15 => T16 => T17 => T18 => T19 => T20 => T21 => T22 => R = { 
-      (x1: T1) => ((x2: T2, x3: T3, x4: T4, x5: T5, x6: T6, x7: T7, x8: T8, x9: T9, x10: T10, x11: T11, x12: T12, x13: T13, x14: T14, x15: T15, x16: T16, x17: T17, x18: T18, x19: T19, x20: T20, x21: T21, x22: T22) => self.apply(x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12,x13,x14,x15,x16,x17,x18,x19,x20,x21,x22)).curry
+  def curried: T1 => T2 => T3 => T4 => T5 => T6 => T7 => T8 => T9 => T10 => T11 => T12 => T13 => T14 => T15 => T16 => T17 => T18 => T19 => T20 => T21 => T22 => R = {
+    (x1: T1) => ((x2: T2, x3: T3, x4: T4, x5: T5, x6: T6, x7: T7, x8: T8, x9: T9, x10: T10, x11: T11, x12: T12, x13: T13, x14: T14, x15: T15, x16: T16, x17: T17, x18: T18, x19: T19, x20: T20, x21: T21, x22: T22) => self.apply(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17, x18, x19, x20, x21, x22)).curried
   }
+  @deprecated("Use 'curried' instead")
+  def curry = curried
+
+  /* f(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17, x18, x19, x20, x21, x22) == (f.tupled)(Tuple22(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17, x18, x19, x20, x21, x22))
+   */
+  def tupled: Tuple22[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22] => R = {
+    case Tuple22(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17, x18, x19, x20, x21, x22) => apply(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17, x18, x19, x20, x21, x22)
+  }
+
 }
diff --git a/src/library/scala/Function3.scala b/src/library/scala/Function3.scala
index c4ee007..4cdd245 100644
--- a/src/library/scala/Function3.scala
+++ b/src/library/scala/Function3.scala
@@ -1,31 +1,40 @@
-
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Function3.scala 16881 2009-01-09 16:28:11Z cunei $
 
-// generated by genprod on Wed Apr 23 10:06:16 CEST 2008  (with extra methods)
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  (with extra methods)
 
 package scala
 
 
+
+
 /** <p>
  *    Function with 3 parameters.
  *  </p>
  *  
  */
 trait Function3[-T1, -T2, -T3, +R] extends AnyRef { self =>
-  def apply(v1:T1, v2:T2, v3:T3): R
-  override def toString() = "<function>"
+  def apply(v1:T1,v2:T2,v3:T3): R
+  override def toString() = "<function3>"
   
-  /** f(x1,x2,x3)  == (f.curry)(x1)(x2)(x3)
+  /** f(x1, x2, x3)  == (f.curried)(x1)(x2)(x3)
    */
-  def curry: T1 => T2 => T3 => R = { 
-      (x1: T1) => (x2: T2) => (x3: T3) => apply(x1,x2,x3)
+  def curried: T1 => T2 => T3 => R = {
+    (x1: T1) => (x2: T2) => (x3: T3) => apply(x1, x2, x3)
   }
+  @deprecated("Use 'curried' instead")
+  def curry = curried
+
+  /* f(x1, x2, x3) == (f.tupled)(Tuple3(x1, x2, x3))
+   */
+  def tupled: Tuple3[T1, T2, T3] => R = {
+    case Tuple3(x1, x2, x3) => apply(x1, x2, x3)
+  }
+
 }
diff --git a/src/library/scala/Function4.scala b/src/library/scala/Function4.scala
index 305ef50..c13c82a 100644
--- a/src/library/scala/Function4.scala
+++ b/src/library/scala/Function4.scala
@@ -1,31 +1,40 @@
-
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Function4.scala 16881 2009-01-09 16:28:11Z cunei $
 
-// generated by genprod on Wed Apr 23 10:06:16 CEST 2008  (with extra methods)
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  (with extra methods)
 
 package scala
 
 
+
+
 /** <p>
  *    Function with 4 parameters.
  *  </p>
  *  
  */
 trait Function4[-T1, -T2, -T3, -T4, +R] extends AnyRef { self =>
-  def apply(v1:T1, v2:T2, v3:T3, v4:T4): R
-  override def toString() = "<function>"
+  def apply(v1:T1,v2:T2,v3:T3,v4:T4): R
+  override def toString() = "<function4>"
   
-  /** f(x1,x2,x3,x4)  == (f.curry)(x1)(x2)(x3)(x4)
+  /** f(x1, x2, x3, x4)  == (f.curried)(x1)(x2)(x3)(x4)
    */
-  def curry: T1 => T2 => T3 => T4 => R = { 
-      (x1: T1) => (x2: T2) => (x3: T3) => (x4: T4) => apply(x1,x2,x3,x4)
+  def curried: T1 => T2 => T3 => T4 => R = {
+    (x1: T1) => (x2: T2) => (x3: T3) => (x4: T4) => apply(x1, x2, x3, x4)
   }
+  @deprecated("Use 'curried' instead")
+  def curry = curried
+
+  /* f(x1, x2, x3, x4) == (f.tupled)(Tuple4(x1, x2, x3, x4))
+   */
+  def tupled: Tuple4[T1, T2, T3, T4] => R = {
+    case Tuple4(x1, x2, x3, x4) => apply(x1, x2, x3, x4)
+  }
+
 }
diff --git a/src/library/scala/Function5.scala b/src/library/scala/Function5.scala
index 848bfcc..6f23814 100644
--- a/src/library/scala/Function5.scala
+++ b/src/library/scala/Function5.scala
@@ -1,31 +1,40 @@
-
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Function5.scala 16881 2009-01-09 16:28:11Z cunei $
 
-// generated by genprod on Wed Apr 23 10:06:16 CEST 2008  (with extra methods)
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  (with extra methods)
 
 package scala
 
 
+
+
 /** <p>
  *    Function with 5 parameters.
  *  </p>
  *  
  */
 trait Function5[-T1, -T2, -T3, -T4, -T5, +R] extends AnyRef { self =>
-  def apply(v1:T1, v2:T2, v3:T3, v4:T4, v5:T5): R
-  override def toString() = "<function>"
+  def apply(v1:T1,v2:T2,v3:T3,v4:T4,v5:T5): R
+  override def toString() = "<function5>"
   
-  /** f(x1,x2,x3,x4,x5)  == (f.curry)(x1)(x2)(x3)(x4)(x5)
+  /** f(x1, x2, x3, x4, x5)  == (f.curried)(x1)(x2)(x3)(x4)(x5)
    */
-  def curry: T1 => T2 => T3 => T4 => T5 => R = { 
-      (x1: T1) => ((x2: T2, x3: T3, x4: T4, x5: T5) => self.apply(x1,x2,x3,x4,x5)).curry
+  def curried: T1 => T2 => T3 => T4 => T5 => R = {
+    (x1: T1) => ((x2: T2, x3: T3, x4: T4, x5: T5) => self.apply(x1, x2, x3, x4, x5)).curried
   }
+  @deprecated("Use 'curried' instead")
+  def curry = curried
+
+  /* f(x1, x2, x3, x4, x5) == (f.tupled)(Tuple5(x1, x2, x3, x4, x5))
+   */
+  def tupled: Tuple5[T1, T2, T3, T4, T5] => R = {
+    case Tuple5(x1, x2, x3, x4, x5) => apply(x1, x2, x3, x4, x5)
+  }
+
 }
diff --git a/src/library/scala/Function6.scala b/src/library/scala/Function6.scala
index 909432e..a7f0065 100644
--- a/src/library/scala/Function6.scala
+++ b/src/library/scala/Function6.scala
@@ -1,31 +1,40 @@
-
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Function6.scala 16881 2009-01-09 16:28:11Z cunei $
 
-// generated by genprod on Wed Apr 23 10:06:16 CEST 2008  (with extra methods)
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  (with extra methods)
 
 package scala
 
 
+
+
 /** <p>
  *    Function with 6 parameters.
  *  </p>
  *  
  */
 trait Function6[-T1, -T2, -T3, -T4, -T5, -T6, +R] extends AnyRef { self =>
-  def apply(v1:T1, v2:T2, v3:T3, v4:T4, v5:T5, v6:T6): R
-  override def toString() = "<function>"
+  def apply(v1:T1,v2:T2,v3:T3,v4:T4,v5:T5,v6:T6): R
+  override def toString() = "<function6>"
   
-  /** f(x1,x2,x3,x4,x5,x6)  == (f.curry)(x1)(x2)(x3)(x4)(x5)(x6)
+  /** f(x1, x2, x3, x4, x5, x6)  == (f.curried)(x1)(x2)(x3)(x4)(x5)(x6)
    */
-  def curry: T1 => T2 => T3 => T4 => T5 => T6 => R = { 
-      (x1: T1) => ((x2: T2, x3: T3, x4: T4, x5: T5, x6: T6) => self.apply(x1,x2,x3,x4,x5,x6)).curry
+  def curried: T1 => T2 => T3 => T4 => T5 => T6 => R = {
+    (x1: T1) => ((x2: T2, x3: T3, x4: T4, x5: T5, x6: T6) => self.apply(x1, x2, x3, x4, x5, x6)).curried
   }
+  @deprecated("Use 'curried' instead")
+  def curry = curried
+
+  /* f(x1, x2, x3, x4, x5, x6) == (f.tupled)(Tuple6(x1, x2, x3, x4, x5, x6))
+   */
+  def tupled: Tuple6[T1, T2, T3, T4, T5, T6] => R = {
+    case Tuple6(x1, x2, x3, x4, x5, x6) => apply(x1, x2, x3, x4, x5, x6)
+  }
+
 }
diff --git a/src/library/scala/Function7.scala b/src/library/scala/Function7.scala
index 7d9ad0e..e59c63b 100644
--- a/src/library/scala/Function7.scala
+++ b/src/library/scala/Function7.scala
@@ -1,31 +1,40 @@
-
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Function7.scala 16881 2009-01-09 16:28:11Z cunei $
 
-// generated by genprod on Wed Apr 23 10:06:16 CEST 2008  (with extra methods)
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  (with extra methods)
 
 package scala
 
 
+
+
 /** <p>
  *    Function with 7 parameters.
  *  </p>
  *  
  */
 trait Function7[-T1, -T2, -T3, -T4, -T5, -T6, -T7, +R] extends AnyRef { self =>
-  def apply(v1:T1, v2:T2, v3:T3, v4:T4, v5:T5, v6:T6, v7:T7): R
-  override def toString() = "<function>"
+  def apply(v1:T1,v2:T2,v3:T3,v4:T4,v5:T5,v6:T6,v7:T7): R
+  override def toString() = "<function7>"
   
-  /** f(x1,x2,x3,x4,x5,x6,x7)  == (f.curry)(x1)(x2)(x3)(x4)(x5)(x6)(x7)
+  /** f(x1, x2, x3, x4, x5, x6, x7)  == (f.curried)(x1)(x2)(x3)(x4)(x5)(x6)(x7)
    */
-  def curry: T1 => T2 => T3 => T4 => T5 => T6 => T7 => R = { 
-      (x1: T1) => ((x2: T2, x3: T3, x4: T4, x5: T5, x6: T6, x7: T7) => self.apply(x1,x2,x3,x4,x5,x6,x7)).curry
+  def curried: T1 => T2 => T3 => T4 => T5 => T6 => T7 => R = {
+    (x1: T1) => ((x2: T2, x3: T3, x4: T4, x5: T5, x6: T6, x7: T7) => self.apply(x1, x2, x3, x4, x5, x6, x7)).curried
   }
+  @deprecated("Use 'curried' instead")
+  def curry = curried
+
+  /* f(x1, x2, x3, x4, x5, x6, x7) == (f.tupled)(Tuple7(x1, x2, x3, x4, x5, x6, x7))
+   */
+  def tupled: Tuple7[T1, T2, T3, T4, T5, T6, T7] => R = {
+    case Tuple7(x1, x2, x3, x4, x5, x6, x7) => apply(x1, x2, x3, x4, x5, x6, x7)
+  }
+
 }
diff --git a/src/library/scala/Function8.scala b/src/library/scala/Function8.scala
index cda98ba..1585198 100644
--- a/src/library/scala/Function8.scala
+++ b/src/library/scala/Function8.scala
@@ -1,31 +1,40 @@
-
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Function8.scala 16881 2009-01-09 16:28:11Z cunei $
 
-// generated by genprod on Wed Apr 23 10:06:16 CEST 2008  (with extra methods)
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  (with extra methods)
 
 package scala
 
 
+
+
 /** <p>
  *    Function with 8 parameters.
  *  </p>
  *  
  */
 trait Function8[-T1, -T2, -T3, -T4, -T5, -T6, -T7, -T8, +R] extends AnyRef { self =>
-  def apply(v1:T1, v2:T2, v3:T3, v4:T4, v5:T5, v6:T6, v7:T7, v8:T8): R
-  override def toString() = "<function>"
+  def apply(v1:T1,v2:T2,v3:T3,v4:T4,v5:T5,v6:T6,v7:T7,v8:T8): R
+  override def toString() = "<function8>"
   
-  /** f(x1,x2,x3,x4,x5,x6,x7,x8)  == (f.curry)(x1)(x2)(x3)(x4)(x5)(x6)(x7)(x8)
+  /** f(x1, x2, x3, x4, x5, x6, x7, x8)  == (f.curried)(x1)(x2)(x3)(x4)(x5)(x6)(x7)(x8)
    */
-  def curry: T1 => T2 => T3 => T4 => T5 => T6 => T7 => T8 => R = { 
-      (x1: T1) => ((x2: T2, x3: T3, x4: T4, x5: T5, x6: T6, x7: T7, x8: T8) => self.apply(x1,x2,x3,x4,x5,x6,x7,x8)).curry
+  def curried: T1 => T2 => T3 => T4 => T5 => T6 => T7 => T8 => R = {
+    (x1: T1) => ((x2: T2, x3: T3, x4: T4, x5: T5, x6: T6, x7: T7, x8: T8) => self.apply(x1, x2, x3, x4, x5, x6, x7, x8)).curried
   }
+  @deprecated("Use 'curried' instead")
+  def curry = curried
+
+  /* f(x1, x2, x3, x4, x5, x6, x7, x8) == (f.tupled)(Tuple8(x1, x2, x3, x4, x5, x6, x7, x8))
+   */
+  def tupled: Tuple8[T1, T2, T3, T4, T5, T6, T7, T8] => R = {
+    case Tuple8(x1, x2, x3, x4, x5, x6, x7, x8) => apply(x1, x2, x3, x4, x5, x6, x7, x8)
+  }
+
 }
diff --git a/src/library/scala/Function9.scala b/src/library/scala/Function9.scala
index 5bb4acf..408f1fb 100644
--- a/src/library/scala/Function9.scala
+++ b/src/library/scala/Function9.scala
@@ -1,31 +1,40 @@
-
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Function9.scala 16881 2009-01-09 16:28:11Z cunei $
 
-// generated by genprod on Wed Apr 23 10:06:16 CEST 2008  (with extra methods)
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  (with extra methods)
 
 package scala
 
 
+
+
 /** <p>
  *    Function with 9 parameters.
  *  </p>
  *  
  */
 trait Function9[-T1, -T2, -T3, -T4, -T5, -T6, -T7, -T8, -T9, +R] extends AnyRef { self =>
-  def apply(v1:T1, v2:T2, v3:T3, v4:T4, v5:T5, v6:T6, v7:T7, v8:T8, v9:T9): R
-  override def toString() = "<function>"
+  def apply(v1:T1,v2:T2,v3:T3,v4:T4,v5:T5,v6:T6,v7:T7,v8:T8,v9:T9): R
+  override def toString() = "<function9>"
   
-  /** f(x1,x2,x3,x4,x5,x6,x7,x8,x9)  == (f.curry)(x1)(x2)(x3)(x4)(x5)(x6)(x7)(x8)(x9)
+  /** f(x1, x2, x3, x4, x5, x6, x7, x8, x9)  == (f.curried)(x1)(x2)(x3)(x4)(x5)(x6)(x7)(x8)(x9)
    */
-  def curry: T1 => T2 => T3 => T4 => T5 => T6 => T7 => T8 => T9 => R = { 
-      (x1: T1) => ((x2: T2, x3: T3, x4: T4, x5: T5, x6: T6, x7: T7, x8: T8, x9: T9) => self.apply(x1,x2,x3,x4,x5,x6,x7,x8,x9)).curry
+  def curried: T1 => T2 => T3 => T4 => T5 => T6 => T7 => T8 => T9 => R = {
+    (x1: T1) => ((x2: T2, x3: T3, x4: T4, x5: T5, x6: T6, x7: T7, x8: T8, x9: T9) => self.apply(x1, x2, x3, x4, x5, x6, x7, x8, x9)).curried
   }
+  @deprecated("Use 'curried' instead")
+  def curry = curried
+
+  /* f(x1, x2, x3, x4, x5, x6, x7, x8, x9) == (f.tupled)(Tuple9(x1, x2, x3, x4, x5, x6, x7, x8, x9))
+   */
+  def tupled: Tuple9[T1, T2, T3, T4, T5, T6, T7, T8, T9] => R = {
+    case Tuple9(x1, x2, x3, x4, x5, x6, x7, x8, x9) => apply(x1, x2, x3, x4, x5, x6, x7, x8, x9)
+  }
+
 }
diff --git a/src/library/scala/Immutable.scala b/src/library/scala/Immutable.scala
new file mode 100644
index 0000000..56511df
--- /dev/null
+++ b/src/library/scala/Immutable.scala
@@ -0,0 +1,18 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala
+
+/** A marker trait for all immutable datastructures such as immutable
+ *  collections.
+ *
+ *  @since 2.8
+ */
+trait Immutable
diff --git a/src/library/scala/Iterable.scala b/src/library/scala/Iterable.scala
deleted file mode 100644
index 98a3df4..0000000
--- a/src/library/scala/Iterable.scala
+++ /dev/null
@@ -1,516 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: Iterable.scala 16881 2009-01-09 16:28:11Z cunei $
-
-
-package scala
-
-
-import Predef._
-import collection.mutable.{Buffer,ArrayBuffer}
-
-/** Various utilities for instances of <a href="Iterable.html">Iterable</a>.
- *
- *  @author  Matthias Zenger
- *  @version 1.1, 04/02/2004
- */
-object Iterable {
-/*
-  implicit def view[A <% Ordered[A]](x: Iterable[A]): Ordered[Iterable[A]] =
-    new Ordered[Iterable[A]] {
-      def compare[B >: Iterable[A] <% Ordered[B]](that: B): Int = that match {
-        case y: Iterable[A] =>
-          val xs = x.elements
-          val ys = y.elements
-          var res = 0
-          while (xs.hasNext && ys.hasNext && (res == 0)) {
-            res = xs.next compare ys.next
-          }
-          if (xs.hasNext) 1
-          else if (ys.hasNext) -1
-          else res
-        case _ =>
-          -(that compare x)
-      }
-    }
-*/
-  /** The minimum element of a non-empty sequence of ordered elements */
-  def min[A <% Ordered[A]](seq: Iterable[A]): A = {
-    val xs = seq.elements
-    if (!xs.hasNext) throw new IllegalArgumentException("min(<empty>)")
-    var min = xs.next
-    while (xs.hasNext) {
-      val x = xs.next
-      if (x < min) min = x
-    }
-    min
-  }
-
-  /** The maximum element of a non-empty sequence of ordered elements */
-  def max[A <% Ordered[A]](seq: Iterable[A]): A = {
-    val xs = seq.elements
-    if (!xs.hasNext) throw new IllegalArgumentException("max(<empty>)")
-    var max = xs.next
-    while (xs.hasNext) {
-      val x = xs.next
-      if (max < x) max = x
-    }
-    max
-  }
-
-  /** The empty iterable object */
-  val empty = new Iterable[Nothing] {
-    def elements = Iterator.empty
-  }
-  /** A non-strict projection of an iterable. 
-   * @author Sean McDirmid
-   */
-  trait Projection[+A] extends Iterable[A] {
-    override def projection = this
-    /** convert to a copied strict collection */
-    def force : Iterable[A] = toList
-    
-    /** non-strict */
-    override def filter(p : A => Boolean) : Projection[A] = new Projection[A] {
-      def elements = Projection.this.elements.filter(p)
-    }
-    /** non-strict */
-    override def map[B](f: A => B) : Projection[B] = new Projection[B] {
-      def elements = Projection.this.elements.map(f)
-    }
-    /** non-strict */
-    override def flatMap[B](f: A => Iterable[B]) : Projection[B] = new Projection[B] {
-      def elements = Projection.this.elements.flatMap(a => f(a).elements)
-    }  
-    /** non-strict */
-    override def takeWhile(p: A => Boolean): Projection[A] = new Projection[A] {
-      def elements = Projection.this.elements.takeWhile(p)
-    }
-    /** The projection resulting from the concatenation of this projection with the <code>rest</code> projection.
-     *  @param rest   The projection that gets appended to this projection
-     */
-    def append[B >: A](rest : => Iterable[B]): Projection[B] = new Projection[B] {
-      def elements = Projection.this.elements ++ rest.elements
-    }
-  }
-}
-
-
-/** Collection classes mixing in this class provide a method
- *  <code>elements</code> which returns an iterator over all the
- *  elements contained in the collection.
- *
- *  @note If a collection has a known <code>size</code>, it should also sub-type <code>Collection</code>. 
- *        Only potentially unbounded collections should directly sub-class <code>Iterable</code>. 
- *  @author  Matthias Zenger
- *  @version 1.1, 04/02/2004
- */
-trait Iterable[+A] {
-
-  /** Creates a new iterator over all elements contained in this
-   *  object.
-   *  
-   *  @return the new iterator
-   */
-  def elements: Iterator[A]
-
-  /** Appends two iterable objects.
-   *
-   *  @return the new iterable object
-   *  @deprecated  use <code>++</code> instead
-   *  @note Will not terminate for infinite-sized collections.
-   */
-  @deprecated
-  def concat[B >: A](that: Iterable[B]): Collection[B] =
-    this ++ that
-
-  /** Appends two iterable objects.
-   *
-   *  @return the new iterable object
-   *  @note Will not terminate for infinite-sized collections.
-   */
-  def ++ [B >: A](that: Iterable[B]): Collection[B] = {
-    val buf = new ArrayBuffer[B]
-    this copyToBuffer buf
-    that copyToBuffer buf
-    buf
-  }
-
-  /** Returns the iterable resulting from applying the given function
-   *  <code>f</code> to each element of this iterable.
-   *
-   *  @note Will not terminate for infinite-sized collections.
-   *  @param f function to apply to each element.
-   *  @return <code>f(a<sub>0</sub>), ..., f(a<sub>n</sub>)</code>
-   *          if this iterable is <code>a<sub>0</sub>, ..., an</code>.
-   */
-  def map[B](f: A => B): Iterable[B] = {
-    val buf = new ArrayBuffer[B]
-    val elems = elements
-    while (elems.hasNext) buf += f(elems.next)
-    buf
-  }
-
-  /** Applies the given function <code>f</code> to each element of
-   *  this iterable, then concatenates the results.
-   *
-   *  @note Will not terminate for infinite-sized collections.
-   *  @param f the function to apply on each element.
-   *  @return  <code>f(a<sub>0</sub>) ::: ... ::: f(a<sub>n</sub>)</code> if
-   *           this iterable is <code>a<sub>0</sub>, ..., a<sub>n</sub></code>.
-   */
-  def flatMap[B](f: A => Iterable[B]): Iterable[B] = {
-    val buf = new ArrayBuffer[B]
-    val elems = elements
-    while (elems.hasNext) f(elems.next) copyToBuffer buf
-    buf
-  }
-
-  /** Returns all the elements of this iterable that satisfy the
-   *  predicate <code>p</code>. The order of the elements is preserved.
-   *
-   *  @note Will not terminate for infinite-sized collections.
-   *  @param p the predicate used to filter the list.
-   *  @return the elements of this list satisfying <code>p</code>.
-   */
-  def filter(p: A => Boolean): Iterable[A] = {
-    val buf = new ArrayBuffer[A]
-    val elems = elements
-    while (elems.hasNext) { val x = elems.next; if (p(x)) buf += x }
-    buf
-  }
-
-  /** Partitions this iterable in two iterables according to a predicate.
-   *
-   *  @param p the predicate on which to partition
-   *  @return  a pair of iterables: the iterable that satisfy the predicate
-   *           <code>p</code> and the iterable that do not.
-   *           The relative order of the elements in the resulting iterables
-   *           is the same as in the original iterable.
-   */
-  def partition(p: A => Boolean): (Iterable[A], Iterable[A]) = {
-    val matched = new ArrayBuffer[A]
-    val failed = new ArrayBuffer[A]
-    val elems = elements
-    while (elems.hasNext) { val x = elems.next; if (p(x)) matched += x else failed += x }
-    (matched, failed)
-  }
-
-  /** Returns the longest prefix of this iterable whose elements satisfy
-   *  the predicate <code>p</code>.
-   *
-   *  @note May not terminate for infinite-sized collections.
-   *  @param p the test predicate.
-   *  @return  the longest prefix of this iterable whose elements satisfy
-   *           the predicate <code>p</code>.
-   */
-  def takeWhile(p: A => Boolean): Iterable[A] = 
-    (new ArrayBuffer[A] ++ elements.takeWhile(p))
-
-  /** Returns the longest suffix of this iterable whose first element
-   *  does not satisfy the predicate <code>p</code>.
-   *
-   *  @note May not terminate for infinite-sized collections.
-   *  @param p the test predicate.
-   *  @return  the longest suffix of the iterable whose first element
-   *           does not satisfy the predicate <code>p</code>.
-   */
-  def dropWhile(p: A => Boolean): Collection[A] = 
-    (new ArrayBuffer[A] ++ elements.dropWhile(p))
-
-  /** Returns an iterable consisting only over the first <code>n</code>
-   *  elements of this iterable, or else the whole iterable, if it has less
-   *  than <code>n</code> elements.
-   *
-   *  @deprecated API does not make sense for non-ordered collections
-   *  @param n the number of elements to take
-   *  @return  the new iterable
-   */
-  @deprecated def take(n: Int): Collection[A] = 
-    (new ArrayBuffer[A] ++ elements.take(n))
-
-  /** Returns this iterable without its <code>n</code> first elements
-   *  If this iterable has less than <code>n</code> elements, the empty
-   *  iterable is returned.
-   *
-   *  @note Will not terminate for infinite-sized collections.
-   *  @deprecated API does not make sense for non-ordered collections
-   *  @param n the number of elements to drop
-   *  @return  the new iterable
-   */
-  @deprecated def drop(n: Int): Collection[A] =
-    (new ArrayBuffer[A] ++ elements.drop(n))
-
-  /** Apply a function <code>f</code> to all elements of this
-   *  iterable object.
-   *
-   *  @note Will not terminate for infinite-sized collections.
-   *  @param  f   a function that is applied to every element.
-   */
-  def foreach(f: A => Unit): Unit = elements.foreach(f)
-
-  /** Apply a predicate <code>p</code> to all elements of this
-   *  iterable object and return true, iff the predicate yields
-   *  true for all elements.
-   *
-   *  @note May not terminate for infinite-sized collections.
-   *  @param   p     the predicate
-   *  @return true, iff the predicate yields true for all elements.
-   */
-  def forall(p: A => Boolean): Boolean = elements.forall(p)
-
-  /** Apply a predicate <code>p</code> to all elements of this
-   *  iterable object and return true, iff there is at least one
-   *  element for which <code>p</code> yields true.
-   *
-   *  @note May not terminate for infinite-sized collections.
-   *  @param   p     the predicate
-   *  @return true, iff the predicate yields true for at least one element.
-   */
-  def exists(p: A => Boolean): Boolean = elements.exists(p)
-
-  /** Find and return the first element of the iterable object satisfying a
-   *  predicate, if any.
-   *
-   *  @note may not terminate for infinite-sized collections.
-   *  @param p the predicate
-   *  @return the first element in the iterable object satisfying <code>p</code>,
-   *  or <code>None</code> if none exists.
-   */
-  def find(p: A => Boolean): Option[A] = elements.find(p)
-
-  /** Returns index of the first element satisying a predicate, or -1.
-   *
-   *  @note may not terminate for infinite-sized collections.
-   *  @param  p the predicate
-   *  @return   the index of the first element satisfying <code>p</code>,
-   *            or -1 if such an element does not exist
-   *  @deprecated  Method is pushed to <code>Seq</code>, will be removed from <code>Iterable</code>.
-   */
-  @deprecated def findIndexOf(p: A => Boolean): Int =
-    elements.findIndexOf(p)
-
-  /** Returns the index of the first occurence of the specified
-   *  object in this iterable object.
-   *
-   *  @note may not terminate for infinite-sized collections.
-   *  @param  elem  element to search for.
-   *  @return the index in this sequence of the first occurence of the
-   *          specified element, or -1 if the sequence does not contain
-   *          this element.
-   *  @deprecated  Method is pushed to <code>Seq</code>, will be removed from <code>Iterable</code>.
-   */
-  @deprecated def indexOf[B >: A](elem: B): Int =
-    elements.indexOf(elem)
-
-  /** Combines the elements of this iterable object together using the binary
-   *  function <code>f</code>, from left to right, and starting with
-   *  the value <code>z</code>.
-   *
-   *  @note Will not terminate for infinite-sized collections.
-   *  @return <code>f(... (f(f(z, a<sub>0</sub>), a<sub>1</sub>) ...),
-   *          a<sub>n</sub>)</code> if the list is
-   *          <code>[a<sub>0</sub>, a<sub>1</sub>, ..., a<sub>n</sub>]</code>.
-   */
-  def foldLeft[B](z: B)(op: (B, A) => B): B = elements.foldLeft(z)(op)
-
-  /** Combines the elements of this list together using the binary
-   *  function <code>f</code>, from right to left, and starting with
-   *  the value <code>z</code>.
-   *
-   *  @note Will not terminate for infinite-sized collections.
-   *  @return <code>f(a<sub>0</sub>, f(a<sub>1</sub>, f(..., f(a<sub>n</sub>, z)...)))</code>
-   *          if the list is <code>[a<sub>0</sub>, a1, ..., a<sub>n</sub>]</code>.
-   */
-  def foldRight[B](z: B)(op: (A, B) => B): B = elements.foldRight(z)(op)
-
-  /** Similar to <code>foldLeft</code> but can be used as
-   *  an operator with the order of list and zero arguments reversed.
-   *  That is, <code>z /: xs</code> is the same as <code>xs foldLeft z</code>
-   *  @note Will not terminate for infinite-sized collections.
-   */
-  def /:[B](z: B)(op: (B, A) => B): B = foldLeft(z)(op)
-
-  /** An alias for <code>foldRight</code>.
-   *  That is, <code>xs :\ z</code> is the same as <code>xs foldRight z</code>
-   *  @note Will not terminate for infinite-sized collections.
-   */
-  def :\[B](z: B)(op: (A, B) => B): B = foldRight(z)(op)
-
-  /** Combines the elements of this iterable object together using the binary
-   *  operator <code>op</code>, from left to right
-   *  @note Will not terminate for infinite-sized collections.
-   *  @param op  The operator to apply
-   *  @return <code>op(... op(a<sub>0</sub>,a<sub>1</sub>), ..., a<sub>n</sub>)</code> 
-      if the iterable object has elements
-   *          <code>a<sub>0</sub>, a<sub>1</sub>, ..., a<sub>n</sub></code>.
-   *  @throws Predef.UnsupportedOperationException if the iterable object is empty.
-   */
-  def reduceLeft[B >: A](op: (B, A) => B): B = elements.reduceLeft(op)
-
-/** Combines the elements of this iterable object together using the binary
-   *  operator <code>op</code>, from right to left
-   *  @note Will not terminate for infinite-sized collections.
-   *  @param op  The operator to apply
-   *
-   *  @return <code>a<sub>0</sub> op (... op (a<sub>n-1</sub> op a<sub>n</sub>)...)</code>
-   *          if the iterable object has elements <code>a<sub>0</sub>, a<sub>1</sub>, ...,
-   *          a<sub>n</sub></code>.
-   *
-   *  @throws Predef.UnsupportedOperationException if the iterator is empty.
-   */
-  def reduceRight[B >: A](op: (A, B) => B): B = elements.reduceRight(op)
-
-  /** Copy all elements to a given buffer 
-   *  @note Will not terminate for infinite-sized collections.
-   *  @param  dest   The buffer to which elements are copied
-   *  @note Will not terminate if not finite.
-   */
-  def copyToBuffer[B >: A](dest: Buffer[B]): Unit = elements copyToBuffer dest
-  
-  /** Checks if the other iterable object contains the same elements.
-   *
-   *  @note will not terminate for infinite-sized collections.
-   *  @param that  the other iterable object
-   *  @return true, iff both iterable objects contain the same elements.
-   */
-  def sameElements[B >: A](that: Iterable[B]): Boolean = {
-    val ita = this.elements
-    val itb = that.elements
-    var res = true
-    while (res && ita.hasNext && itb.hasNext) {
-      res = (ita.next == itb.next)
-    }
-    !ita.hasNext && !itb.hasNext && res
-  }
-
-  /**
-   *  Returns a list containing all of the elements in this iterable object.
-   *  @note Will not terminate for infinite-sized collections.
-   */
-  def toList: List[A] = elements.toList
-  
-  /**
-   *  Returns a sequence containing all of the elements in this iterable object.
-   *  @note Will not terminate for infinite-sized collections.
-   */
-  def toSeq: Seq[A] = toList 
-
-  /**
-   *  Returns a stream containing all of the elements in this iterable object.
-   *  @note consider using <code>projection</code> for lazy behavior.
-   */
-  def toStream: Stream[A] = Stream.fromIterator(elements)
-
-  /** Returns a string representation of this iterable object. The resulting string
-   *  begins with the string <code>start</code> and is finished by the string
-   *  <code>end</code>. Inside, the string representations of elements (w.r.t.
-   *  the method <code>toString()</code>) are separated by the string
-   *  <code>sep</code>.
-   *
-   *  @ex  <code>List(1, 2, 3).mkString("(", "; ", ")") = "(1; 2; 3)"</code>
-   *  @note Will not terminate for infinite-sized collections.
-   *  @param start starting string.
-   *  @param sep separator string.
-   *  @param end ending string.
-   *  @return a string representation of this iterable object.
-   */
-  def mkString(start: String, sep: String, end: String): String = {
-    val buf = new StringBuilder()
-    addString(buf, start, sep, end).toString
-  }
-  
-  /** Returns a string representation of this iterable object. The string
-   *  representations of elements (w.r.t. the method <code>toString()</code>)
-   *  are separated by the string <code>sep</code>.
-   *
-   *  @note Will not terminate for infinite-sized collections.
-   *  @param sep separator string.
-   *  @return a string representation of this iterable object.
-   */
-  def mkString(sep: String): String = this.mkString("", sep, "")
-
-  /** Converts a collection into a flat <code>String</code> by each element's toString method. 
-   *  @note Will not terminate for infinite-sized collections.
-   */
-  def mkString = {
-    val buf = new StringBuilder
-    foreach(buf append _.toString)
-    buf.toString
-  }
-   
-  /** Write all elements of this string into given string builder.
-   *
-   *  @note Will not terminate for infinite-sized collections.
-   *  @param buf the StringBuilder to which elements are appended
-   *  @param start starting string.
-   *  @param sep separator string.
-   *  @param end ending string.
-   *  @return the <code>buf</code> StringBuilder object
-   */
-  def addString(buf: StringBuilder, start: String, sep: String, end: String): StringBuilder = {
-    buf.append(start)
-    val elems = elements
-    if (elems.hasNext) buf.append(elems.next)
-    while (elems.hasNext) {
-      buf.append(sep); buf.append(elems.next)
-    }
-    buf.append(end)
-  }
-
-  /** Write all elements of this string into given string builder.
-   *
-   *  @note Will not terminate for infinite-sized collections.
-   *  @param buf the StringBuilder to which elements are appended
-   *  @param sep separator string.
-   *  @return the <code>buf</code> StringBuilder object
-   */
-  def addString(buf: StringBuilder, sep: String): StringBuilder = addString(buf, "", sep, "")
-
-  /** Write all elements of this string into given string builder, with no separator string
-   *  between elements.
-   *  @note Will not terminate for infinite-sized collections.
-   *  @param buf the StringBuilder to which elements are appended
-   *  @return the <code>buf</code> StringBuilder object
-   */
-  def addString(buf: StringBuilder): StringBuilder = addString(buf, "", "", "")
-
-   
-  /** Fills the given array <code>xs</code> with the elements of
-   *  this sequence starting at position <code>start</code>.
-   *
-   *  @note Will not terminate for infinite-sized collections.
-   *  @param  xs the array to fill.
-   *  @param  start starting index.
-   *  @pre    the array must be large enough to hold all elements.
-   */
-  def copyToArray[B >: A](xs: Array[B], start: Int): Unit = 
-    elements.copyToArray(xs, start)
-
-  
-  /** Is this collection empty? */
-  def isEmpty = !elements.hasNext
-
-  /** 
-   * returns a projection that can be used to call non-strict <code>filter</code>,
-   * <code>map</code>, and <code>flatMap</code> methods that build projections
-   * of the collection.
-   */
-  def projection : Iterable.Projection[A] = new Iterable.Projection[A] {
-    def elements = Iterable.this.elements
-    override def force = Iterable.this
-  }
-  
-  /** returns true iff this collection has a bound size. 
-   *  Many APIs in this trait will not work on collections of 
-   *  unbound sizes. 
-   */
-  def hasDefiniteSize = true
-  
-}
diff --git a/src/library/scala/IterableProxy.scala b/src/library/scala/IterableProxy.scala
deleted file mode 100644
index 6a0cab9..0000000
--- a/src/library/scala/IterableProxy.scala
+++ /dev/null
@@ -1,79 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: IterableProxy.scala 16881 2009-01-09 16:28:11Z cunei $
-
-
-package scala
-
-import scala.collection.mutable.Buffer
-
-
-/** This class implements a proxy for iterable objects. It forwards
- *  all calls to a different iterable object.
- *
- *  @author  Matthias Zenger
- *  @author  Martin Odersky
- *  @version 2.0, 31/12/2006
- */
-trait IterableProxy[+A] extends Iterable[A] with Proxy {
-
-  override def self: Iterable[A]
-  
-  override def elements = self.elements
-  @deprecated
-  override def concat [B >: A](that: Iterable[B]) = self concat that
-  override def ++[B >: A](that: Iterable[B]) = self ++ that
-  override def map[B](f: A => B) = self map f
-  override def flatMap[B](f: A => Iterable[B]) = self flatMap f
-  override def filter(p: A => Boolean) = self filter p
-  override def partition(p: A => Boolean) = self partition p
-  override def takeWhile(p: A => Boolean) = self takeWhile p 
-  override def dropWhile(p: A => Boolean) = self dropWhile p
-  @deprecated override def take(n: Int) = self take n
-  @deprecated override def drop(n: Int) = self drop n
-  override def foreach(f: A => Unit) = self foreach f
-  override def forall(p: A => Boolean) = self forall p
-  override def exists(p: A => Boolean) = self exists p
-  override def find(p: A => Boolean) = self find p
-  @deprecated override def findIndexOf(p: A => Boolean) = self findIndexOf p
-  @deprecated override def indexOf[B >: A](elem: B): Int = self indexOf elem
-  override def foldLeft[B](z: B)(op: (B, A) => B) = (self foldLeft z)(op)
-  override def foldRight[B](z: B)(op: (A, B) => B) = (self foldRight z)(op)
-  override def /:[B](z: B)(op: (B, A) => B) = (z /: self)(op)
-  override def :\[B](z: B)(op: (A, B) => B) = (self :\ z)(op)
-  override def reduceLeft[B >: A](op: (B, A) => B) = self reduceLeft op
-  override def reduceRight[B >: A](op: (A, B) => B) = self reduceRight op
-  override def copyToBuffer[B >: A](dest: Buffer[B]) = self copyToBuffer dest
-  override def sameElements[B >: A](that: Iterable[B]) = self sameElements that
-  
-  override def toList = self.toList
-  override def toSeq = self.toSeq
-  override def toStream = self.toStream
-  
-  override def mkString(start: String, sep: String, end: String) = self.mkString(start, sep, end)
-  override def mkString(sep: String) = self.mkString(sep)
-  override def mkString = self.mkString
-  
-  override def addString(buf: StringBuilder, start: String, sep: String, end: String) =
-    self.addString(buf, start, sep, end)
-  
-  override def addString(buf: StringBuilder, sep: String) =
-    self.addString(buf, sep)
-  
-  override def addString(buf: StringBuilder) =
-    self.addString(buf)
-  
-  override def copyToArray[B >: A](xs: Array[B], start: Int) = self.copyToArray(xs, start)
-  
-  override def isEmpty = self.isEmpty
-  
-  override def projection = self.projection
-  
-  override def hasDefiniteSize = self.hasDefiniteSize
-}
diff --git a/src/library/scala/Iterator.scala b/src/library/scala/Iterator.scala
deleted file mode 100644
index e8d05d2..0000000
--- a/src/library/scala/Iterator.scala
+++ /dev/null
@@ -1,765 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: Iterator.scala 16881 2009-01-09 16:28:11Z cunei $
-
-
-package scala
-
-
-import Predef._
-import collection.mutable.{Buffer, ListBuffer, ArrayBuffer}
-
-/** The <code>Iterator</code> object provides various functions for
- *  creating specialized iterators.
- *
- *  @author  Martin Odersky
- *  @author  Matthias Zenger
- *  @version 1.2, 10/02/2007
- */
-object Iterator {
-
-  val empty = new Iterator[Nothing] {
-    def hasNext: Boolean = false
-    def next(): Nothing = throw new NoSuchElementException("next on empty iterator")
-  }
-
-  /**
-   *  @param x the element
-   *  @return  the iterator with one single element
-   */
-  def single[a](x: a) = new Iterator[a] {
-    private var hasnext = true
-    def hasNext: Boolean = hasnext
-    def next(): a =
-      if (hasnext) { hasnext = false; x }
-      else throw new NoSuchElementException("next on empty iterator")
-  }
-
-  def fromValues[a](xs: a*) = xs.elements
-
-  /**
-   *  @param xs the array of elements
-   *  @see also: RandomAccessSeq.elements and slice
-   */
-  def fromArray[a](xs: Array[a]): Iterator[a] =
-    fromArray(xs, 0, xs.length)
-
-  /**
-   *  @param xs     the array of elements
-   *  @param start  the start index
-   *  @param length  the length
-   *  @see also: RandomAccessSeq.elements and slice
-   */
-  @throws(classOf[NoSuchElementException])
-  def fromArray[a](xs: Array[a], start: Int, length: Int): Iterator[a] =
-    new BufferedIterator.Advanced[a] {
-      private var i = start
-      val end = if (start + length < xs.length) start + length else xs.length
-      override def hasNext: Boolean = i < end
-      def next(): a =
-        if (hasNext) { val x = xs(i) ; i += 1 ; x }
-        else throw new NoSuchElementException("next on empty iterator")
-        
-      override protected def defaultPeek : a = throw new NoSuchElementException("no lookahead")
-      override def peekList(sz: Int): Seq[a] = 
-        xs.slice(i, if (i + sz > xs.length) xs.length else i + sz)
-  }
-
-  /**
-   *  @param str the given string
-   *  @return    the iterator on <code>str</code>
-   *  @deprecated replaced by <code>str.elements</code>
-   */
-  @deprecated def fromString(str: String): Iterator[Char] =
-    new BufferedIterator.Advanced[Char] {
-      private var i = 0
-      private val len = str.length()
-      override def hasNext = i < len
-      def next = { val c = str charAt i; i += 1; c }
-      
-      override protected def defaultPeek : Char = throw new NoSuchElementException
-      override def peekList(sz: Int): Seq[Char] =
-        str.substring(i, if (i + sz > str.length) str.length else i + sz)
-    }
-
-  /**
-   *  @param n the product arity
-   *  @return  the iterator on <code>Product<n></code>.
-   */
-  def fromProduct(n: Product): Iterator[Any] = new Iterator[Any] {
-    private var c: Int = 0
-    private val cmax = n.productArity
-    def hasNext = c < cmax
-    def next() = { val a = n productElement c; c += 1; a }
-  }
-
-  /**
-   * @deprecated use <code>fromProduct</code> instead.
-   */
-  @deprecated
-  def fromCaseClass(n: Product) = fromProduct(n)
-
-  /** Create an iterator with elements
-   *  <code>e<sub>n+1</sub> = e<sub>n</sub> + 1</code>
-   *  where <code>e<sub>0</sub> = start</code>
-   *  and <code>e<sub>i</sub> < end</code>. However, 
-   *  if <code>start ≥ end</code>, then it will return an empty range.
-   *
-   *  @param start the start value of the iterator
-   *  @param end   the end value of the iterator
-   *  @return      the iterator with values in range <code>[start;end)</code>.
-   */
-  def range(start: Int, end: Int): Iterator[Int] = range(start, end, 1)
-
-  /** Create an iterator with elements
-   *  <code>e<sub>n+1</sub> = e<sub>n</sub> + step</code>
-   *  where <code>e<sub>0</sub> = start</code>
-   *  and elements are in the range between <code>start</code> (inclusive)
-   *  and <code>end</code> (exclusive)
-   *
-   *  @param start the start value of the iterator
-   *  @param end   the end value of the iterator
-   *  @param step  the increment value of the iterator (must be positive or negative)
-   *  @return      the iterator with values in range <code>[start;end)</code>.
-   */
-  @throws(classOf[NoSuchElementException])
-  def range(start: Int, end: Int, step: Int) = new Iterator[Int] {
-    private var i = start
-    def hasNext: Boolean = (step <= 0 || i < end) && (step >= 0 || i > end)
-    def next(): Int =
-      if (hasNext) { val j = i; i += step; j }
-      else throw new NoSuchElementException("next on empty iterator")
-  }
-
-  /** Create an iterator with elements
-   *  <code>e<sub>n+1</sub> = step(e<sub>n</sub>)</code>
-   *  where <code>e<sub>0</sub> = start</code>
-   *  and elements are in the range between <code>start</code> (inclusive)
-   *  and <code>end</code> (exclusive)
-   *
-   *  @param start the start value of the iterator
-   *  @param end   the end value of the iterator
-   *  @param step  the increment function of the iterator, must be monotonically increasing or decreasing
-   *  @return      the iterator with values in range <code>[start;end)</code>.
-   */
-  @throws(classOf[NoSuchElementException])
-  def range(start: Int, end: Int, step: Int => Int) = new Iterator[Int] {
-    private val up = step(start) > start
-    private val down = step(start) < start
-    private var i = start
-    def hasNext: Boolean = (!up || i < end) && (!down || i > end)
-    def next(): Int =
-      if (hasNext) { val j = i; i = step(i); j }
-      else throw new NoSuchElementException("next on empty iterator")
-  }
-
-  /** Create an iterator with elements
-   *  <code>e<sub>n+1</sub> = e<sub>n</sub> + 1</code>
-   *  where <code>e<sub>0</sub> = start</code>.
-   *
-   *  @param start the start value of the iterator
-   *  @return      the iterator starting at value <code>start</code>.
-   */
-  def from(start: Int): Iterator[Int] = from(start, 1)
-
-  /** Create an iterator with elements
-   * <code>e<sub>n+1</sub> = e<sub>n</sub> + step</code>
-   *  where <code>e<sub>0</sub> = start</code>.
-   *
-   *  @param start the start value of the iterator
-   *  @param step  the increment value of the iterator
-   *  @return      the iterator starting at value <code>start</code>.
-   */
-  def from(start: Int, step: Int): Iterator[Int] = from(start, {x:Int => x + step})
-
-  /** Create an iterator with elements
-   *  <code>e<sub>n+1</sub> = step(e<sub>n</sub>)</code>
-   *  where <code>e<sub>0</sub> = start</code>.
-   *
-   *  @param start the start value of the iterator
-   *  @param step  the increment function of the iterator
-   *  @return      the iterator starting at value <code>start</code>.
-   */
-  def from(start: Int, step: Int => Int): Iterator[Int] = new Iterator[Int] {
-    private var i = start
-    override def hasNext: Boolean = true
-    def next(): Int = { val j = i; i = step(i); j }
-  }
-
-  /** Create an iterator that is the concantenation of all iterators
-   *  returned by a given iterator of iterators.
-   *   @param its   The iterator which returns on each call to next
-   *                a new iterator whose elements are to be concatenated to the result.
-   */
-  def flatten[T](its: Iterator[Iterator[T]]): Iterator[T] = new Iterator[T] {
-    private var it = its.next
-    def hasNext: Boolean = {
-      while (!it.hasNext && its.hasNext) it = its.next
-      it.hasNext
-    }
-    def next(): T = 
-      if (hasNext) it.next
-      else empty.next()
-  }
-}
-
-/** Iterators are data structures that allow to iterate over a sequence
- *  of elements. They have a <code>hasNext</code> method for checking
- *  if there is a next element available, and a <code>next</code> method
- *  which returns the next element and discards it from the iterator.
- *
- *  @author  Martin Odersky, Matthias Zenger
- *  @version 1.2, 15/03/2004
- */
-trait Iterator[+A] {
-
-  /** Does this iterator provide another element?
-   */
-  def hasNext: Boolean
-
-  /** Returns the next element.
-   */
-  def next(): A
-  
-
-  /** Returns a new iterator that iterates only over the first <code>n</code>
-   *  elements.
-   *
-   *  @param n the number of elements to take
-   *  @return  the new iterator
-   */
-  @throws(classOf[NoSuchElementException])
-  def take(n: Int): Iterator[A] = new Iterator[A] {
-    var remaining = n
-    def hasNext = remaining > 0 && Iterator.this.hasNext
-    def next(): A =
-      if (hasNext) { remaining -= 1; Iterator.this.next }
-      else throw new NoSuchElementException("next on empty iterator")
-  }
-
-  /** Removes the first <code>n</code> elements from this iterator.
-   *
-   *  @param n the number of elements to drop
-   *  @return  the new iterator
-   */
-  def drop(n: Int): Iterator[A] =
-    if (n > 0 && hasNext) { next; drop(n - 1) } else this
-
-  /** A sub-iterator of <code>until - from elements 
-   *  starting at index <code>from</code>
-   *
-   *  @param from   The index of the first element of the slice
-   *  @param until    The index of the element following the slice
-   */
-  def slice(from: Int, until: Int): Iterator[A] = drop(from).take(until - from)
-
-  /** Returns a new iterator that maps all elements of this iterator
-   *  to new elements using function <code>f</code>.
-   */
-  def map[B](f: A => B): Iterator[B] = new Iterator[B] {
-    def hasNext = Iterator.this.hasNext
-    def next() = f(Iterator.this.next)
-  }
-
-  /** Returns a new iterator that first yields the elements of this
-   *  iterator followed by the elements provided by iterator <code>that</code>.
-   *  @deprecated  use <code>++</code>
-   */
-  def append[B >: A](that: Iterator[B]) = new Iterator[B] {
-    def hasNext = Iterator.this.hasNext || that.hasNext
-    def next() = if (Iterator.this.hasNext) Iterator.this.next else that.next
-  }
-
-  /** Returns a new iterator that first yields the elements of this
-   *  iterator followed by the elements provided by iterator <code>that</code>.
-   */
-  def ++[B >: A](that: => Iterator[B]) = new Iterator[B] {
-    // optimize a little bit to prevent n log n behavior.
-    var what : Iterator[B] = Iterator.this 
-    def hasNext = if (what.hasNext) true
-                  else if (what eq Iterator.this) {
-                    what = that
-                    what.hasNext
-                  } else false
-                  
-    def next = { hasNext; what.next }
-  }
-
-  /** Applies the given function <code>f</code> to each element of
-   *  this iterator, then concatenates the results.
-   *
-   *  @param f the function to apply on each element.
-   *  @return  an iterator over <code>f(a<sub>0</sub>), ... ,
-   *           f(a<sub>n</sub>)</code> if this iterator yields the
-   *           elements <code>a<sub>0</sub>, ..., a<sub>n</sub></code>.
-   */
-  @throws(classOf[NoSuchElementException])
-  def flatMap[B](f: A => Iterator[B]): Iterator[B] = new Iterator[B] {
-    private var cur: Iterator[B] = Iterator.empty
-    def hasNext: Boolean =
-      if (cur.hasNext) true
-      else if (Iterator.this.hasNext) {
-        cur = f(Iterator.this.next)
-        hasNext
-      } else false
-    def next(): B = 
-      if (cur.hasNext) cur.next
-      else if (Iterator.this.hasNext) {
-        cur = f(Iterator.this.next)
-        next
-      } else throw new NoSuchElementException("next on empty iterator")
-  }
-
-  protected class PredicatedIterator(p : A => Boolean) extends BufferedIterator.Default[A] {
-    protected def doEnd : Boolean = false
-    protected override def fill(sz: Int): Seq[A] = {
-      while (true) {
-        if (!Iterator.this.hasNext) return Nil
-        val ret = Iterator.this.next
-        if (p(ret)) return ret :: Nil
-        if (doEnd) return Nil
-      }
-      throw new Error
-    }
-  }
-  protected class TakeWhileIterator(p : A => Boolean) extends PredicatedIterator(p) {
-    private var ended = false
-    override protected def doEnd = {
-      ended = true; true
-    }
-    override protected def fill(sz : Int) : Seq[A] = 
-      if (ended) Nil else super.fill(sz)
-  }
-  
-
-  /** Returns an iterator over all the elements of this iterator that
-   *  satisfy the predicate <code>p</code>. The order of the elements
-   *  is preserved.
-   *
-   *  @param p the predicate used to filter the iterator.
-   *  @return  the elements of this iterator satisfying <code>p</code>.
-   */
-  def filter(p: A => Boolean): Iterator[A] = new PredicatedIterator(p)
-
-  /** Returns an iterator over the longest prefix of this iterator such that
-   *  all elements of the result satisfy the predicate <code>p</code>. 
-   *  The order of the elements is preserved.
-   *
-   *  The behavior of <code>this</code> iterator is undefined after this method invocation.
-   *
-   *  @param p the predicate used to filter the iterator.
-   *  @return  the longest prefix of this iterator satisfying <code>p</code>.
-   */
-  def takeWhile(p: A => Boolean): Iterator[A] = new TakeWhileIterator(p)
-
-  /** Skips longest sequence of elements of this iterator which satisfy given 
-   *  predicate <code>p</code>, and returns an iterator of the remaining elements.
-   *
-   *  The behavior of <code>this</code> iterator is undefined after this method invocation.
-   *
-   *  @param p the predicate used to skip elements.
-   *  @return  an iterator consisting of the remaining elements
-   */
-  def dropWhile(p: A => Boolean): Iterator[A] =
-    if (hasNext) {
-      val x = next
-      if (p(x)) dropWhile(p)
-      else Iterator.single(x) append this
-    } else this
-
-  /** Return an iterator formed from this iterator and the specified iterator
-   *  <code>that</code> by associating each element of the former with
-   *  the element at the same position in the latter.
-   *  If one of the two iterators is longer than the other, its remaining elements are ignored.
-   *
-   *  @return     an iterator yielding <code>{a<sub>0</sub>,b<sub>0</sub>},
-   *              {a<sub>1</sub>,b<sub>1</sub>}, ...</code> where
-   *              <code>a<sub>i</sub></code> are the elements from this iterator
-   *              and <code>b<sub>i</sub></code> are the elements from iterator
-   *              <code>that</code>.
-   */
-  def zip[B](that: Iterator[B]) = new Iterator[(A, B)] {
-    def hasNext = Iterator.this.hasNext && that.hasNext
-    def next = (Iterator.this.next, that.next)
-  }
-
-  /** Return an iterator that pairs each element of this iterator
-   *  with its index, counting from 0.
-   *
-   *  @return      an iterator yielding <code>{a<sub>0</sub>,0},
-   *               {a<sub>1</sub>,1}...</code> where <code>a<sub>i</sub></code>
-   *               are the elements from this iterator.
-   */
-  def zipWithIndex = new Iterator[(A, Int)] {
-    var idx = 0
-    def hasNext = Iterator.this.hasNext
-    def next = {
-      val ret = (Iterator.this.next, idx)
-      idx += 1
-      ret
-    }
-  }
-
-  /** Apply a function <code>f</code> to all elements of this
-   *  iterable object.
-   *
-   *  @param  f   a function that is applied to every element.
-   */
-  def foreach(f: A => Unit) { while (hasNext) f(next) }
-
-  /** Apply a predicate <code>p</code> to all elements of this
-   *  iterable object and return <code>true</code> iff the predicate yields
-   *  <code>true</code> for all elements.
-   *
-   *  @param p the predicate
-   *  @return  <code>true</code> iff the predicate yields <code>true</code>
-   *           for all elements.
-   */
-  def forall(p: A => Boolean): Boolean = {
-    var res = true
-    while (res && hasNext) res = p(next)
-    res
-  }
-
-  /** Apply a predicate <code>p</code> to all elements of this
-   *  iterable object and return true, iff there is at least one
-   *  element for which <code>p</code> yields <code>true</code>.
-   *
-   *  @param p the predicate
-   *  @return  <code>true</code> iff the predicate yields <code>true</code>
-   *           for at least one element.
-   */
-  def exists(p: A => Boolean): Boolean = {
-    var res = false
-    while (!res && hasNext) res = p(next)
-    res
-  }
-
-  /** Tests if the given value <code>elem</code> is a member of this iterator.
-   *
-   *  @param elem element whose membership has to be tested.
-   *  @return     <code>true</code> iff there is an element of this iterator which
-   *              is equal (w.r.t. <code>==</code>) to <code>elem</code>.
-   */
-  def contains(elem: Any): Boolean = exists { _ == elem }
-
-  /** Find and return the first element of the iterable object satisfying a
-   *  predicate, if any.
-   *
-   *  @param p the predicate
-   *  @return  the first element in the iterable object satisfying
-   *           <code>p</code>, or <code>None</code> if none exists.
-   */
-  def find(p: A => Boolean): Option[A] = {
-    var res: Option[A] = None
-    while (res.isEmpty && hasNext) {
-      val e = next
-      if (p(e)) res = Some(e)
-    }
-    res
-  }
-  
-  /** Returns index of the first element satisying a predicate, or -1.
-   *
-   *  @note may not terminate for infinite-sized collections.
-   *  @param  p the predicate
-   *  @return   the index of the first element satisfying <code>p</code>,
-   *           or -1 if such an element does not exist
-   */
-  def findIndexOf(p: A => Boolean): Int = {
-    var i = 0
-    var found = false
-    while (!found && hasNext) {
-      if (p(next)) {
-        found = true
-      } else {
-        i += 1
-      }
-    }
-    if (found) i else -1
-  }
-  
-  /** Returns the index of the first occurence of the specified
-   *  object in this iterable object.
-   *
-   *  @note may not terminate for infinite-sized collections.
-   *  @param  elem  element to search for.
-   *  @return the index in this sequence of the first occurence of the
-   *          specified element, or -1 if the sequence does not contain
-   *          this element.
-   */
-  def indexOf[B >: A](elem: B): Int = {
-    var i = 0
-    var found = false
-    while (!found && hasNext) {
-      if (next == elem) {
-        found = true
-      } else {
-        i += 1
-      }
-    }
-    if (found) i else -1
-  }
-
-  /** Combines the elements of this iterator together using the binary
-   *  operator <code>op</code>, from left to right, and starting with
-   *  the value <code>z</code>.
-   *
-   *  @return <code>op(... (op(op(z,a<sub>0</sub>),a<sub>1</sub>) ...),
-   *          a<sub>n</sub>)</code> if the iterator yields elements
-   *          <code>a<sub>0</sub>, a<sub>1</sub>, ..., a<sub>n</sub></code>.
-   */
-  def foldLeft[B](z: B)(op: (B, A) => B): B = {
-    var acc = z
-    while (hasNext) acc = op(acc, next)
-    acc
-  }
-
-  /** Combines the elements of this iterator together using the binary
-   *  operator <code>op</code>, from right to left, and starting with
-   *  the value <code>z</code>.
-   *
-   *  @return <code>a<sub>0</sub> op (... op (a<sub>n</sub> op z)...)</code>
-   *          if the iterator yields elements <code>a<sub>0</sub>, a<sub>1</sub>, ...,
-   *          a<sub>n</sub></code>.
-   */
-  def foldRight[B](z: B)(op: (A, B) => B): B = {
-    def fold(z: B): B = if (hasNext) op(next, fold(z)) else z
-    fold(z)
-  }
-
-  /** Similar to <code>foldLeft</code> but can be used as
-   *  an operator with the order of iterator and zero arguments reversed.
-   *  That is, <code>z /: xs</code> is the same as <code>xs foldLeft z</code>.
-   *
-   *  @param z the left argument of the first application of <code>op</code>
-   *           (evaluation occurs from left to right).
-   *  @param op the applied operator.
-   *  @return  the result value
-   *  @see     <code><a href="#foldLeft">foldLeft</a></code>.
-   */
-  def /:[B](z: B)(op: (B, A) => B): B = foldLeft(z)(op)
-
-  /** An alias for <code>foldRight</code>.
-   *  That is, <code>xs :\ z</code> is the same as <code>xs foldRight z</code>.
-   *
-   *  @param z the right argument of the first application of <code>op</code>
-   *           (evaluation occurs from right to left).
-   *  @param op the applied operator.
-   *  @return  the result value.
-   *  @see     <code><a href="#foldRight">foldRight</a></code>.
-   */
-  def :\[B](z: B)(op: (A, B) => B): B = foldRight(z)(op)
-
-  /** Combines the elements of this iterator together using the binary
-   *  operator <code>op</code>, from left to right
-   *  @param op  The operator to apply
-   *  @return <code>op(... op(a<sub>0</sub>,a<sub>1</sub>), ..., a<sub>n</sub>)</code> 
-      if the iterator yields elements
-   *          <code>a<sub>0</sub>, a<sub>1</sub>, ..., a<sub>n</sub></code>.
-   *  @throws Predef.UnsupportedOperationException if the iterator is empty.
-   */
-  @throws(classOf[UnsupportedOperationException])
-  def reduceLeft[B >: A](op: (B, A) => B): B = {
-    if (hasNext) foldLeft[B](next)(op)
-    else throw new UnsupportedOperationException("empty.reduceLeft")
-  }
-
-  /** Combines the elements of this iterator together using the binary
-   *  operator <code>op</code>, from right to left
-   *  @param op  The operator to apply
-   *
-   *  @return <code>a<sub>0</sub> op (... op (a<sub>n-1</sub> op a<sub>n</sub>)...)</code>
-   *          if the iterator yields elements <code>a<sub>0</sub>, a<sub>1</sub>, ...,
-   *          a<sub>n</sub></code>.
-
-   *  @throws Predef.UnsupportedOperationException if the iterator is empty.
-   */
-  @throws(classOf[UnsupportedOperationException])
-  def reduceRight[B >: A](op: (A, B) => B): B = {
-    if (!hasNext) throw new UnsupportedOperationException("empty.reduceRight")
-    val x = next
-    if (hasNext) op(x, reduceRight(op))
-    else x
-  }
-
-  /** Returns a buffered iterator from this iterator.
-   */
-  def buffered: BufferedIterator[A] = new BufferedIterator.Default[A] {
-    protected def fill(sz : Int) = if (Iterator.this.hasNext) (Iterator.this.next) :: Nil else Nil
-  }
-
-  /** Returns a counted iterator from this iterator.
-   */
-  def counted = new CountedIterator[A] {
-    private var cnt = -1
-    def count = cnt
-    def hasNext: Boolean = Iterator.this.hasNext
-    def next(): A = { cnt += 1; Iterator.this.next }
-  }
-
-  /** Creates two new iterators that both iterate over the same elements
-   *  than this iterator (in the same order).
-   *
-   *  @return a pair of iterators
-   */
-  def duplicate: (Iterator[A], Iterator[A]) = {
-    var xs: List[A] = Nil
-    var ahead: Iterator[A] = null
-    class Partner extends Iterator[A] {
-      var ys: List[A] = Nil
-      def hasNext: Boolean = Iterator.this.synchronized (
-        ((this == ahead) && Iterator.this.hasNext) ||
-        ((this != ahead) && (!xs.isEmpty || !ys.isEmpty || Iterator.this.hasNext))
-      )
-      def next(): A = Iterator.this.synchronized {
-        if (this == ahead) {
-          val e = Iterator.this.next
-          xs = e :: xs; e
-        } else {
-          if (ys.isEmpty) {
-            ys = xs.reverse
-            xs = Nil
-          }
-          ys match {
-            case Nil =>
-              val e = Iterator.this.next
-              ahead = this
-              xs = e :: xs; e
-            case z :: zs =>
-              ys = zs; z
-          }
-        }
-      }
-    }
-    ahead = new Partner
-    (ahead, new Partner)
-  }
-
-  /** Fills the given array <code>xs</code> with the elements of
-   *  this sequence starting at position <code>start</code>.
-   *
-   *  @param  xs    the array to fill.
-   *  @param  start the starting index.
-   *  @pre          the array must be large enough to hold all elements.
-   */
-  def copyToArray[B >: A](xs: Array[B], start: Int) {
-    var i = start
-    while (hasNext) {
-      xs(i) = next
-      i += 1
-    }
-  }
-  /** Fills the given array <code>xs</code> with the elements of
-   *  this sequence starting at position <code>start</code>.  Like <code>copyToArray</code>, 
-   *  but designed to accomodate IO stream operations. 
-   *
-   *  @param  xs    the array to fill.
-   *  @param  start the starting index.
-   *  @param  sz    the maximum number of elements to be read.
-   *  @pre          the array must be large enough to hold <code>sz</code> elements.
-   */
-  def readInto[B >: A](xs: Array[B], start: Int, sz: Int) {
-    var i = start
-    while (hasNext && i - start < sz) {
-      xs(i) = next
-      i += 1
-    }
-  }
-  def readInto[B >: A](xs: Array[B], start: Int) {
-    readInto(xs, start, xs.length - start)
-  }
-  def readInto[B >: A](xs: Array[B]) {
-    readInto(xs, 0, xs.length)
-  }
-
-  /** Copy all elements to a buffer 
-   *  @param   The buffer to which elements are copied
-   *  @return  The buffer to which elements are copied
-   */
-  def copyToBuffer[B >: A](dest: Buffer[B]) {
-    while (hasNext) dest += next
-  }
-
-  /** Transform this iterator into a list of all elements.
-   *
-   *  @return  a list which enumerates all elements of this iterator.
-   */
-  def toList: List[A] = {
-    val res = new ListBuffer[A]
-    while (hasNext) res += next
-    res.toList
-  }
-  
-  /** Collect elements into a seq.
-   *
-   * @return  a seq which enumerates all elements of this iterator.
-   */
-  def collect: Seq[A] = {
-    val buffer = new ArrayBuffer[A]
-    this copyToBuffer buffer
-    buffer.readOnly
-  }
-
-  /** Returns a string representation of the elements in this iterator. The resulting string
-   *  begins with the string <code>start</code> and is finished by the string
-   *  <code>end</code>. Inside, the string representations of elements (w.r.t.
-   *  the method <code>toString()</code>) are separated by the string
-   *  <code>sep</code>.
-   *  <p/>
-   *  Ex: <br/>
-   *  <code>List(1, 2, 3).mkString("(", "; ", ")") = "(1; 2; 3)"</code>
-   *
-   *  @param start starting string.
-   *  @param sep separator string.
-   *  @param end ending string.
-   *  @return a string representation of this iterable object.
-   */
-  def mkString(start: String, sep: String, end: String): String = {
-    val buf = new StringBuilder
-    addString(buf, start, sep, end).toString
-  }
-
-  /** Returns a string representation of this iterable object. The string
-   *  representations of elements (w.r.t. the method <code>toString()</code>)
-   *  are separated by the string <code>sep</code>.
-   *
-   *  @param sep separator string.
-   *  @return a string representation of this iterable object.
-   */
-  def mkString(sep: String): String = this.mkString("", sep, "")
-
-  /** Returns a string representation of this iterable object. The string
-   *  representations of elements (w.r.t. the method <code>toString()</code>)
-   *  are separated by a comma.
-   *
-   *  @return a string representation of this iterable object.
-   */
-  def mkString: String =
-    mkString("")
-
-  /** Write all elements of this string into given string builder.
-   *
-   *  @param buf   ...
-   *  @param start the starting string
-   *  @param sep   the separator string
-   *  @param end   the ending string
-   *  @return      ...
-   */
-  def addString(buf: StringBuilder, start: String, sep: String, end: String): StringBuilder = {
-    buf.append(start)
-    val elems = this
-    if (elems.hasNext) buf.append(elems.next)
-    while (elems.hasNext) {
-      buf.append(sep); buf.append(elems.next)
-    }
-    buf.append(end)
-  }
-  override def toString = (if (hasNext) "non-empty" else "empty")+" iterator"
-}
diff --git a/src/library/scala/List.scala b/src/library/scala/List.scala
deleted file mode 100644
index a68990e..0000000
--- a/src/library/scala/List.scala
+++ /dev/null
@@ -1,1407 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: List.scala 17137 2009-02-17 20:09:49Z rytz $
-
-
-package scala
-
-import scala.collection.mutable.ListBuffer
-import Predef._
-
-/** This object provides methods for creating specialized lists, and for
- *  transforming special kinds of lists (e.g. lists of lists).
- *
- *  @author  Martin Odersky and others
- *  @version 1.0, 15/07/2003
- */
-object List {
-
-  /** Create a list with given elements.
-   *
-   *  @param xs the elements to put in the list
-   *  @return the list containing elements xs.
-   */
-  def apply[A](xs: A*): List[A] = xs.toList
-
-  /** for unapply matching
-   */
-  def unapplySeq[A](x: List[A]): Some[List[A]] = Some(x)
-
-  /** Create a sorted list of all integers in a range.
-   *
-   *  @param from the start value of the list
-   *  @param end the end value of the list
-   *  @return the sorted list of all integers in range [from;end).
-   */
-  def range(start: Int, end: Int): List[Int] =
-    range(start, end, 1)
-
-  /** Create a list with element values
-   * <code>v<sub>n+1</sub> = v<sub>n</sub> + step</code>
-   * where <code>v<sub>0</sub> = start</code>
-   * and elements are in the range between <code>start</code> (inclusive)
-   * and <code>end</code> (exclusive)
-   *
-   *  @param start the start value of the list
-   *  @param end  the end value of the list
-   *  @param step the increment value of the list
-   *  @return     the sorted list of all integers in range [start;end).
-   */
-  def range(start: Int, end: Int, step: Int): List[Int] = {
-    if (step == 0)
-      throw new IllegalArgumentException("step is zero")
-    val b = new ListBuffer[Int]
-    var i = start
-    while ((step <= 0 || i < end) && (step >= 0 || i > end)) {
-      b += i
-      i += step
-    }
-    b.toList
-  }
-
-  /** Create a sorted list with element values
-   * <code>v<sub>n+1</sub> = step(v<sub>n</sub>)</code>
-   * where <code>v<sub>0</sub> = start</code>
-   * and elements are in the range between <code>start</code> (inclusive)
-   * and <code>end</code> (exclusive)
-   *
-   *  @param start the start value of the list
-   *  @param end  the end value of the list
-   *  @param step the increment function of the list, which given <code>v<sub>n</sub></code>,
-   *              computes <code>v<sub>n+1</sub></code>. Must be monotonically increasing
-   *              or decreasing.
-   *  @return     the sorted list of all integers in range [start;end).
-   */
-  def range(start: Int, end: Int, step: Int => Int): List[Int] = {
-    val up = step(start) > start
-    val down = step(start) < start
-    val b = new ListBuffer[Int]
-    var i = start
-    while ((!up || i < end) && (!down || i > end)) {
-      b += i
-      val next = step(i)
-      if (i == next)
-        throw new IllegalArgumentException("the step function did not make any progress on "+ i)
-      i = next
-    }
-    b.toList
-  }
-
-  /** Create a list containing several copies of an element.
-   *
-   *  @param n    the length of the resulting list
-   *  @param elem the element composing the resulting list
-   *  @return     a list composed of n elements all equal to elem
-   */
-  def make[A](n: Int, elem: A): List[A] = {
-    val b = new ListBuffer[A]
-    var i = 0
-    while (i < n) {
-      b += elem
-      i += 1
-    }
-    b.toList
-  }
-
-  /** Create a list by applying a function to successive integers.
-   *
-   *  @param n     the length of the resulting list
-   *  @param maker the procedure which, given an integer <code>n</code>,
-   *               returns the nth element of the resulting list, where
-   *               <code>n</code> is in interval <code>[0;n)</code>.
-   *  @return      the list obtained by applying the maker function to
-   *               successive integers from 0 to n (exclusive).
-   */
-  def tabulate[A](n: Int, maker: Int => A): List[A] = {
-    val b = new ListBuffer[A]
-    var i = 0
-    while (i < n) {
-      b += maker(i)
-      i += 1
-    }
-    b.toList
-  }
-
-  /** Concatenate all the elements of a given list of lists.
-   *
-   *  @param xss the list of lists that are to be concatenated
-   *  @return    the concatenation of all the lists
-   */
-  def flatten[A](xss: List[List[A]]): List[A] = concat(xss: _*)
-
-  /** Concatenate all the argument lists into a single list.
-   *
-   *  @param xss the lists that are to be concatenated
-   *  @return the concatenation of all the lists
-   */
-  def concat[A](xss: List[A]*): List[A] = { 
-    val b = new ListBuffer[A] 
-    for (xs <- xss) {
-      var xc = xs
-      while (!xc.isEmpty) {
-        b += xc.head
-        xc = xc.tail
-      }
-    }
-    b.toList
-  }
-
-  /** Transforms a list of pairs into a pair of lists.
-   *
-   *  @param xs the list of pairs to unzip
-   *  @return a pair of lists.
-   */
-  def unzip[A,B](xs: List[(A,B)]): (List[A], List[B]) = {
-    val b1 = new ListBuffer[A]
-    val b2 = new ListBuffer[B]
-    var xc = xs
-    while (!xc.isEmpty) {
-      b1 += xc.head._1
-      b2 += xc.head._2
-      xc = xc.tail
-    }
-    (b1.toList, b2.toList)
-  }
-
-  /** Transforms an iterable of pairs into a pair of lists.
-   *
-   *  @param xs the iterable of pairs to unzip
-   *  @return a pair of lists.
-   */
-  def unzip[A,B](xs: Iterable[(A,B)]): (List[A], List[B]) = 
-      xs.foldRight[(List[A], List[B])]((Nil, Nil)) {
-        case ((x, y), (xs, ys)) => (x :: xs, y :: ys)
-      }
-
-  /** 
-   * Returns the <code>Left</code> values in the given <code>Iterable</code> of <code>Either</code>s.
-   */ 
-  def lefts[A, B](es: Iterable[Either[A, B]]) = 
-    es.foldRight[List[A]](Nil)((e, as) => e match {
-      case Left(a) => a :: as
-      case Right(_) => as
-    })     
- 
-  /** 
-   * Returns the <code>Right</code> values in the given<code>Iterable</code> of  <code>Either</code>s.
-   */      
-  def rights[A, B](es: Iterable[Either[A, B]]) = 
-    es.foldRight[List[B]](Nil)((e, bs) => e match {
-      case Left(_) => bs
-      case Right(b) => b :: bs
-    })
-
-  /** Transforms an Iterable of Eithers into a pair of lists.
-   *
-   *  @param xs the iterable of Eithers to separate
-   *  @return a pair of lists.
-   */
-  def separate[A,B](es: Iterable[Either[A,B]]): (List[A], List[B]) =
-      es.foldRight[(List[A], List[B])]((Nil, Nil)) {
-      case (Left(a), (lefts, rights)) => (a :: lefts, rights)
-      case (Right(b), (lefts, rights)) => (lefts, b :: rights)
-    }
-
-  /** Converts an iterator to a list.
-   *
-   *  @param it the iterator to convert
-   *  @return   a list that contains the elements returned by successive
-   *            calls to <code>it.next</code>
-   */
-  def fromIterator[A](it: Iterator[A]): List[A] = it.toList
-
-  /** Converts an array into a list.
-   *
-   *  @param arr the array to convert
-   *  @return    a list that contains the same elements than <code>arr</code>
-   *             in the same order
-   */
-  def fromArray[A](arr: Array[A]): List[A] = fromArray(arr, 0, arr.length)
-
-  /** Converts a range of an array into a list.
-   *
-   *  @param arr   the array to convert
-   *  @param start the first index to consider
-   *  @param len   the lenght of the range to convert
-   *  @return      a list that contains the same elements than <code>arr</code>
-   *               in the same order
-   */
-  def fromArray[A](arr: Array[A], start: Int, len: Int): List[A] = {
-    var res: List[A] = Nil
-    var i = start + len
-    while (i > start) {
-      i -= 1
-      res = arr(i) :: res
-    }
-    res
-  }
-
-  /** Parses a string which contains substrings separated by a
-   *  separator character and returns a list of all substrings.
-   *
-   *  @param str       the string to parse
-   *  @param separator the separator character
-   *  @return          the list of substrings
-   */
-  def fromString(str: String, separator: Char): List[String] = {
-    var words: List[String] = Nil
-    var pos = str.length()
-    while (pos > 0) {
-      val pos1 = str.lastIndexOf(separator, pos - 1)
-      if (pos1 + 1 < pos)
-        words = str.substring(pos1 + 1, pos) :: words
-      pos = pos1
-    }
-    words
-  }
-
-  /** Returns the given string as a list of characters.
-   *
-   *  @param str the string to convert.
-   *  @return    the string as a list of characters.
-   *  @deprecated use <code>str.toList</code> instead
-   */
-  @deprecated def fromString(str: String): List[Char] =
-    str.toList
-
-  /** Returns the given list of characters as a string.
-   *
-   *  @param xs the list to convert.
-   *  @return   the list in form of a string.
-   */
-  def toString(xs: List[Char]): String = {
-    val sb = new StringBuilder()
-    var xc = xs
-    while (!xc.isEmpty) {
-      sb.append(xc.head)
-      xc = xc.tail
-    }
-    sb.toString()
-  }
-
-  /** Like xs map f, but returns <code>xs</code> unchanged if function
-   *  <code>f</code> maps all elements to themselves.
-   *
-   *  @param xs ...
-   *  @param f  ...
-   *  @return   ...
-   */
-  def mapConserve[A <: AnyRef](xs: List[A])(f: A => A): List[A] = {
-    def loop(ys: List[A]): List[A] =
-      if (ys.isEmpty) xs
-      else {
-        val head0 = ys.head
-        val head1 = f(head0)
-        if (head1 eq head0) {
-          loop(ys.tail)
-        } else {
-          val ys1 = head1 :: mapConserve(ys.tail)(f)
-          if (xs eq ys) ys1
-          else {
-            val b = new ListBuffer[A]
-            var xc = xs
-            while (xc ne ys) {
-              b += xc.head
-              xc = xc.tail
-            }
-            b.prependToList(ys1)
-          }
-        }
-      }
-    loop(xs)
-  }
-
-  /** Returns the list resulting from applying the given function <code>f</code>
-   *  to corresponding elements of the argument lists.
-   *
-   *  @param f function to apply to each pair of elements.
-   *  @return <code>[f(a0,b0), ..., f(an,bn)]</code> if the lists are 
-   *          <code>[a0, ..., ak]</code>, <code>[b0, ..., bl]</code> and
-   *          <code>n = min(k,l)</code>
-   */
-  def map2[A,B,C](xs: List[A], ys: List[B])(f: (A, B) => C): List[C] = {
-    val b = new ListBuffer[C]
-    var xc = xs
-    var yc = ys
-    while (!xc.isEmpty && !yc.isEmpty) {
-      b += f(xc.head, yc.head)
-      xc = xc.tail
-      yc = yc.tail
-    }
-    b.toList
-  }
-
-  /** Returns the list resulting from applying the given function
-   *  <code>f</code> to corresponding elements of the argument lists.
-   *
-   *  @param f function to apply to each pair of elements.
-   *  @return  <code>[f(a<sub>0</sub>,b<sub>0</sub>,c<sub>0</sub>),
-   *           ..., f(a<sub>n</sub>,b<sub>n</sub>,c<sub>n</sub>)]</code>
-   *           if the lists are <code>[a<sub>0</sub>, ..., a<sub>k</sub>]</code>,
-   *           <code>[b<sub>0</sub>, ..., b<sub>l</sub>]</code>,
-   *           <code>[c<sub>0</sub>, ..., c<sub>m</sub>]</code> and
-   *           <code>n = min(k,l,m)</code>
-   */
-  def map3[A,B,C,D](xs: List[A], ys: List[B], zs: List[C])(f: (A, B, C) => D): List[D] = {
-    val b = new ListBuffer[D]
-    var xc = xs
-    var yc = ys
-    var zc = zs
-    while (!xc.isEmpty && !yc.isEmpty && !zc.isEmpty) {
-      b += f(xc.head, yc.head, zc.head)
-      xc = xc.tail
-      yc = yc.tail
-      zc = zc.tail
-    }
-    b.toList
-  }
-
-  /** Tests whether the given predicate <code>p</code> holds 
-   *  for all corresponding elements of the argument lists.
-   *
-   *  @param p function to apply to each pair of elements.
-   *  @return  <code>(p(a<sub>0</sub>,b<sub>0</sub>) &&
-   *           ... && p(a<sub>n</sub>,b<sub>n</sub>))]</code>
-   *           if the lists are <code>[a<sub>0</sub>, ..., a<sub>k</sub>]</code>;
-   *           <code>[b<sub>0</sub>, ..., b<sub>l</sub>]</code>
-   *           and <code>n = min(k,l)</code>
-   */
-  def forall2[A,B](xs: List[A], ys: List[B])(f: (A, B) => Boolean): Boolean = {
-    var xc = xs
-    var yc = ys
-    while (!xc.isEmpty && !yc.isEmpty) {
-      if (!f(xc.head, yc.head)) return false
-      xc = xc.tail
-      yc = yc.tail
-    }
-    true
-  }
-
-  /** Tests whether the given predicate <code>p</code> holds
-   *  for some corresponding elements of the argument lists.
-   *
-   *  @param p function to apply to each pair of elements.
-   *  @return  <code>n != 0 && (p(a<sub>0</sub>,b<sub>0</sub>) ||
-   *           ... || p(a<sub>n</sub>,b<sub>n</sub>))]</code> if the lists are
-   *           <code>[a<sub>0</sub>, ..., a<sub>k</sub>]</code>,
-   *           <code>[b<sub>0</sub>, ..., b<sub>l</sub>]</code> and
-   *           <code>n = min(k,l)</code>
-   */
-  def exists2[A,B](xs: List[A], ys: List[B])(f: (A, B) => Boolean): Boolean = {
-    var xc = xs
-    var yc = ys
-    while (!xc.isEmpty && !yc.isEmpty) {
-      if (f(xc.head, yc.head)) return true
-      xc = xc.tail
-      yc = yc.tail
-    }
-    false
-  }
-
-  /** Transposes a list of lists.
-   *  pre: All element lists have the same length.
-   *
-   *  @param xss the list of lists
-   *  @return    the transposed list of lists
-   */
-  def transpose[A](xss: List[List[A]]): List[List[A]] = {
-    val buf = new ListBuffer[List[A]]
-    var yss = xss
-    while (!yss.head.isEmpty) {
-      buf += (yss map (_.head))
-      yss = (yss map (_.tail))
-    }
-    buf.toList
-  }
-
-  /** Lists with ordered elements are ordered
-  implicit def list2ordered[a <% Ordered[a]](x: List[a]): Ordered[List[a]] = new Ordered[List[a]] {
-    def compare [b >: List[a] <% Ordered[b]](y: b): Int = y match {
-      case y1: List[a] => compareLists(x, y1);
-      case _ => -(y compare x)
-    }
-    private def compareLists(xs: List[a], ys: List[a]): Int = {
-      if (xs.isEmpty && ys.isEmpty) 0
-      else if (xs.isEmpty) -1
-      else if (ys.isEmpty) 1
-      else {
-        val s = xs.head compare ys.head;
-        if (s != 0) s
-        else compareLists(xs.tail, ys.tail)
-      }
-    }
-  }
-   */
-}
-
-/** A class representing an ordered collection of elements of type
- *  <code>a</code>. This class comes with two implementing case
- *  classes <code>scala.Nil</code> and <code>scala.::</code> that
- *  implement the abstract members <code>isEmpty</code>,
- *  <code>head</code> and <code>tail</code>.
- *
- *  @author  Martin Odersky and others
- *  @version 1.0, 16/07/2003
- */
-sealed abstract class List[+A] extends Seq[A] with Product {
-
-  /** Returns true if the list does not contain any elements.
-   *  @return <code>true</code>, iff the list is empty.
-   */
-  override def isEmpty: Boolean
-
-  /** Returns this first element of the list.
-   *
-   *  @return the first element of this list.
-   *  @throws Predef.NoSuchElementException if the list is empty.
-   */
-  def head: A
-
-  /** Result of comparing <code>length</code> with operand <code>l</code>.
-   *  returns <code>x</code> where
-   *  <code>x < 0</code>    iff    <code>this.length < l</code>
-   *  <code>x == 0</code>   iff    <code>this.length == l</code>
-   *  <code>x > 0</code>    iff    <code>this.length > that</code>.
-   *
-   *  This method is used by matching streams against right-ignoring (...,_*) patterns.
-   *  
-   *  This method does not call <code>List.length</code>, it works for <code>O(l)</code>,
-   *  not for <code>O(length)</code>.
-   */
-  override def lengthCompare(l: Int) = {
-    if (isEmpty) 0 - l
-    else if (l <= 0) 1
-    else tail.lengthCompare(l - 1)
-  }
-
-  /** Returns this list without its first element.
-   *
-   *  @return this list without its first element.
-   *  @throws Predef.NoSuchElementException if the list is empty.
-   */
-  def tail: List[A]
-
-  /** <p>
-   *    Add an element <code>x</code> at the beginning of this list.
-   *  </p>
-   *
-   *  @param x the element to prepend.
-   *  @return  the list with <code>x</code> added at the beginning.
-   *  @ex <code>1 :: List(2, 3) = List(2, 3).::(1) = List(1, 2, 3)</code>
-   */
-  def ::[B >: A] (x: B): List[B] =
-    new scala.::(x, this)
-
-  /** <p>
-   *    Add an element <code>x</code> at the end of this list.
-   *  </p>
-   *
-   *  @deprecated Replace uses of <code>l + e</code> with <code>l ::: List(e)</code>.
-   * 
-   *  @param x the element to append.
-   *  @return  the list with <code>x</code> added at the end.
-   */
-  @deprecated def +[B >: A](x: B): List[B] =
-    if (isEmpty) List(x)
-    else {
-      val buf = new ListBuffer[B]
-      this copyToBuffer buf
-      buf += x
-      buf.toList
-    }
-
-  /** <p>
-   *    Returns a list resulting from the concatenation of the given
-   *    list <code>prefix</code> and this list. 
-   *  </p>
-   *
-   *  @param prefix the list to concatenate at the beginning of this list.
-   *  @return the concatenation of the two lists.
-   *  @ex <code>List(1, 2) ::: List(3, 4) = List(3, 4).:::(List(1, 2)) = List(1, 2, 3, 4)</code>
-   */
-  def :::[B >: A](prefix: List[B]): List[B] =
-    if (isEmpty) prefix
-    else {
-      val b = new ListBuffer[B]
-      var those = prefix
-      while (!those.isEmpty) {
-        b += those.head
-        those = those.tail
-      }
-      b.prependToList(this)
-    }
-
-  /** Appends two list objects.
-   */
-  override def ++[B >: A](that: Iterable[B]): List[B] =
-    this ::: that.toList
-
-  /** Reverse the given prefix and append the current list to that.
-   *  This function is equivalent to an application of <code>reverse</code>
-   *  on the prefix followed by a call to <code>:::</code>, but more
-   *  efficient (and tail recursive).
-   *
-   *  @param prefix the prefix to reverse and then prepend
-   *  @return       the concatenation of the reversed prefix and the current list.
-   */
-  def reverse_:::[B >: A](prefix: List[B]): List[B] = {
-    var these: List[B] = this
-    var pres = prefix
-    while (!pres.isEmpty) {
-      these = pres.head :: these
-      pres = pres.tail
-    }
-    these
-  }
-
-  /** Returns the number of elements in the list.
-   *
-   *  @return the number of elements in the list.
-   */
-  def length: Int = {
-    var these = this
-    var len = 0
-    while (!these.isEmpty) {
-      len += 1
-      these = these.tail
-    }
-    len
-  }
-
-  /** Creates a list with all indices in the list. This is
-   *  equivalent to a call to <code>List.range(0, xs.length)</code>.
-   *
-   *  @return a list of all indices in the list.
-   */
-  def indices: List[Int] = {
-    val b = new ListBuffer[Int]
-    var i = 0
-    var these = this
-    while (!these.isEmpty) {
-      b += i
-      i += 1
-      these = these.tail
-    }
-    b.toList
-  }
- 
-  /** Returns the elements in the list as an iterator
-   *
-   *  @return an iterator on the list elements.
-   */
-  override def elements: Iterator[A] = new Iterator[A] {
-    var these = List.this
-    def hasNext: Boolean = !these.isEmpty
-    def next: A =
-      if (!hasNext)
-        throw new NoSuchElementException("next on empty Iterator")
-      else {
-        val result = these.head; these = these.tail; result
-      }
-    override def toList: List[A] = these
-  }
-
-  /** Overrides the method in Iterable for efficiency.
-   *
-   *  @return  the list itself
-   */
-  override def toList: List[A] = this
-
-  /** Returns the list without its last element.
-   *
-   *  @return the list without its last element.
-   *  @throws Predef.UnsupportedOperationException if the list is empty.
-   */
-  def init: List[A] =
-    if (isEmpty) throw new UnsupportedOperationException("Nil.init")
-    else {
-      val b = new ListBuffer[A]
-      var elem = head
-      var next = tail
-      while (!next.isEmpty) {
-        b += elem
-        elem = next.head
-        next = next.tail
-      }
-      b.toList
-    }
-
-  /** Returns the last element of this list.
-   *
-   *  @return the last element of the list.
-   *  @throws Predef.NoSuchElementException if the list is empty.
-   */
-  override def last: A =
-    if (isEmpty) throw new Predef.NoSuchElementException("Nil.last")
-    else {
-      var cur = this
-      var next = this.tail
-      while (!next.isEmpty) {
-        cur = next
-        next = next.tail
-      }
-      cur.head
-    }
-
-  /** Returns the <code>n</code> first elements of this list, or else the whole 
-   *  list, if it has less than <code>n</code> elements.
-   *
-   *  @param n the number of elements to take.
-   *  @return the <code>n</code> first elements of this list.
-   */
-  override def take(n: Int): List[A] = {
-    val b = new ListBuffer[A]
-    var i = 0
-    var these = this
-    while (!these.isEmpty && i < n) {
-      i += 1
-      b += these.head
-      these = these.tail
-    }
-    if (these.isEmpty) this
-    else b.toList
-  }
-
-  /** Returns the list with elements belonging to the given index range.
-   *
-   *  @param start the start position of the list slice.
-   *  @param end   the end position (exclusive) of the list slice.
-   *  @return the list with elements belonging to the given index range.
-   */
-  override def slice(start: Int, end: Int): List[A] = {
-    val s = start max 0
-    val e = end min this.length
-    drop(s) take (e - s)
-  }
-
-  /** Returns the list without its <code>n</code> first elements.
-   *  If this list has less than <code>n</code> elements, the empty list is returned.
-   *
-   *  @param n the number of elements to drop.
-   *  @return the list without its <code>n</code> first elements.
-   */
-  override def drop(n: Int): List[A] = {
-    var these = this
-    var count = n
-    while (!these.isEmpty && count > 0) {
-      these = these.tail
-      count -= 1
-    }
-    these
-  }
-
-  /** Returns the rightmost <code>n</code> elements from this list.
-   *
-   *  @param n the number of elements to take
-   *  @return the suffix of length <code>n</code> of the list
-   */
-  def takeRight(n: Int): List[A] = {
-    def loop(lead: List[A], lag: List[A]): List[A] = lead match {
-      case Nil => lag
-      case _ :: tail => loop(tail, lag.tail)
-    }
-    loop(drop(n), this)
-  }
-
-  /** Returns the list wihout its rightmost <code>n</code> elements.
-   *
-   *  @param n the number of elements to take
-   *  @return the list without its rightmost <code>n</code> elements
-   */
-  def dropRight(n: Int): List[A] = {
-    def loop(lead: List[A], lag: List[A]): List[A] = lead match {
-      case Nil => Nil
-      case _ :: tail => lag.head :: loop(tail, lag.tail)
-    }
-    loop(drop(n), this)
-  }
-
-  /** Split the list at a given point and return the two parts thus
-   *  created.
-   *
-   *  @param n the position at which to split
-   *  @return  a pair of lists composed of the first <code>n</code>
-   *           elements, and the other elements.
-   */
-  def splitAt(n: Int): (List[A], List[A]) = {
-    val b = new ListBuffer[A]
-    var i = 0
-    var these = this
-    while (!these.isEmpty && i < n) {
-      i += 1
-      b += these.head
-      these = these.tail
-    }
-    (b.toList, these)
-  }
-
-  /** Returns the longest prefix of this list whose elements satisfy
-   *  the predicate <code>p</code>.
-   *
-   *  @param p the test predicate.
-   *  @return  the longest prefix of this list whose elements satisfy
-   *           the predicate <code>p</code>.
-   */
-  override def takeWhile(p: A => Boolean): List[A] = {
-    val b = new ListBuffer[A]
-    var these = this
-    while (!these.isEmpty && p(these.head)) {
-      b += these.head
-      these = these.tail
-    }
-    b.toList
-  }
-
-  /** Returns the longest suffix of this list whose first element
-   *  does not satisfy the predicate <code>p</code>.
-   *
-   *  @param p the test predicate.
-   *  @return  the longest suffix of the list whose first element
-   *           does not satisfy the predicate <code>p</code>.
-   */
-  override def dropWhile(p: A => Boolean): List[A] =
-    if (isEmpty || !p(head)) this
-    else tail dropWhile p
-
-  /** Returns the longest prefix of the list whose elements all satisfy
-   *  the given predicate, and the rest of the list.
-   *
-   *  @param p the test predicate
-   *  @return  a pair consisting of the longest prefix of the list whose
-   *           elements all satisfy <code>p</code>, and the rest of the list.
-   */
-  def span(p: A => Boolean): (List[A], List[A]) = {
-    val b = new ListBuffer[A]
-    var these = this
-    while (!these.isEmpty && p(these.head)) {
-      b += these.head
-      these = these.tail
-    }
-    (b.toList, these)
-  }
-
-  /** Like <code>span</code> but with the predicate inverted.
-   */
-  def break(p: A => Boolean): (List[A], List[A]) = span { x => !p(x) }
-
-  /** Returns the <code>n</code>-th element of this list. The first element
-   *  (head of the list) is at position 0.
-   *
-   *  @param n index of the element to return
-   *  @return  the element at position <code>n</code> in this list.
-   *  @throws Predef.NoSuchElementException if the list is too short.
-   */
-  def apply(n: Int): A = drop(n).head
-
-  /** Returns the list resulting from applying the given function <code>f</code> to each
-   *  element of this list.
-   *
-   *  @param f function to apply to each element.
-   *  @return <code>[f(a0), ..., f(an)]</code> if this list is <code>[a0, ..., an]</code>.
-   */
-  final override def map[B](f: A => B): List[B] = {
-    val b = new ListBuffer[B]
-    var these = this
-    while (!these.isEmpty) {
-      b += f(these.head)
-      these = these.tail
-    }
-    b.toList
-  }
-
-  /** Apply a function to all the elements of the list, and return the
-   *  reversed list of results. This is equivalent to a call to <code>map</code>
-   *  followed by a call to <code>reverse</code>, but more efficient.
-   *
-   *  @param f the function to apply to each elements.
-   *  @return  the reversed list of results.
-   */
-  def reverseMap[B](f: A => B): List[B] = {
-    def loop(l: List[A], res: List[B]): List[B] = l match {
-      case Nil => res
-      case head :: tail => loop(tail, f(head) :: res)
-    }
-    loop(this, Nil)
-  }
-
-  /** Apply the given function <code>f</code> to each element of this list
-   *  (while respecting the order of the elements).
-   *
-   *  @param f the treatment to apply to each element.
-   */
-  final override def foreach(f: A => Unit) {
-    var these = this
-    while (!these.isEmpty) {
-      f(these.head)
-      these = these.tail
-    }
-  }
-
-  /** Returns all the elements of this list that satisfy the
-   *  predicate <code>p</code>. The order of the elements is preserved.
-   *  It is guarenteed that the receiver list itself is returned iff all its
-   *  elements satisfy the predicate `p'. Hence the following equality is valid:
-   *
-   *  (xs filter p) eq xs  ==  xs forall p
-   *
-   *  @param p the predicate used to filter the list.
-   *  @return the elements of this list satisfying <code>p</code>.
-   */
-  final override def filter(p: A => Boolean): List[A] = {
-    // return same list if all elements satisfy p
-    var these = this
-    while (!these.isEmpty && p(these.head)) {
-      these = these.tail
-    }
-    if (these.isEmpty) this
-    else {
-      val b = new ListBuffer[A]
-      var these1 = this
-      while (these1 ne these) {
-        b += these1.head
-        these1 = these1.tail
-      }
-
-      these = these.tail // prevent the second evaluation of the predicate
-                         // on the element on which it first failed
-      while (!these.isEmpty) {
-        if (p(these.head)) b += these.head
-        these = these.tail
-      }
-      b.toList
-    }
-  }
-
-//  final def filterMap[B](f: PartialFunction[A, B]): List[B] = 
-//    this filter f.isDefinedAt map f
-
-  /** Removes all elements of the list which satisfy the predicate
-   *  <code>p</code>. This is like <code>filter</code> with the
-   *  predicate inversed.
-   *
-   *  @param p the predicate to use to test elements
-   *  @return  the list without all elements which satisfy <code>p</code>
-   */
-  def remove(p: A => Boolean): List[A] = filter (x => !p(x))
-
-  /** Partition the list in two sub-lists according to a predicate.
-   *
-   *  @param p the predicate on which to partition
-   *  @return  a pair of lists: the list of all elements which satisfy
-   *           <code>p</code> and the list of all elements which do not.
-   *           The relative order of the elements in the sub-lists is the
-   *           same as in the original list.
-   */
-  override def partition(p: A => Boolean): (List[A], List[A]) = {
-    val btrue = new ListBuffer[A]
-    val bfalse = new ListBuffer[A]
-    var these = this
-    while (!these.isEmpty) {
-      (if (p(these.head)) btrue else bfalse) += these.head
-      these = these.tail
-    }
-    (btrue.toList, bfalse.toList)
-  }
-
-  /** <p>
-   *    Sort the list according to the comparison function
-   *    <code><(e1: a, e2: a) => Boolean</code>,
-   *    which should be true iff <code>e1</code> is smaller than
-   *    <code>e2</code>. 
-   *  </p>
-   *
-   *  @param lt the comparison function
-   *  @return   a list sorted according to the comparison function
-   *            <code><(e1: a, e2: a) => Boolean</code>.
-   *  @ex <pre>
-   *    List("Steve", "Tom", "John", "Bob")
-   *      .sort((e1, e2) => (e1 compareTo e2) < 0) =
-   *    List("Bob", "John", "Steve", "Tom")</pre>
-   */
-  def sort(lt : (A,A) => Boolean): List[A] = {
-    /** Merge two already-sorted lists */
-    def merge(l1: List[A], l2: List[A]): List[A] = {
-      val res = new ListBuffer[A]
-      var left1 = l1
-      var left2 = l2
-
-      while (!left1.isEmpty && !left2.isEmpty) {
-	if(lt(left1.head, left2.head)) {
-	  res += left1.head
-	  left1 = left1.tail
-	} else {
-	  res += left2.head
-	  left2 = left2.tail
-	}
-      }
-
-      res ++= left1
-      res ++= left2
-
-      res.toList
-    }
-
-    /** Split a list into two lists of about the same size */
-    def split(lst: List[A]) = {
-      val res1 = new ListBuffer[A]
-      val res2 = new ListBuffer[A]
-      var left = lst
-
-      while (!left.isEmpty) {
-	res1 += left.head
-	left = left.tail
-	if (!left.isEmpty) {
-	  res2 += left.head
-	  left = left.tail
-	}
-      }
-
-      (res1.toList, res2.toList)
-    }
-
-
-    /** Merge-sort the specified list */
-    def ms(lst: List[A]): List[A] =
-      lst match {
-	case Nil => lst
-	case x :: Nil => lst
-	case x :: y :: Nil =>
-	  if (lt(x,y))
-	    lst
-	  else
-	    y :: x :: Nil
-
-	case lst =>
-          val (l1, l2) = split(lst)
-          val l1s = ms(l1)
-          val l2s = ms(l2)
-          merge(l1s, l2s)
-      }
-
-    ms(this)
-  }
-
-
-  /** Count the number of elements in the list which satisfy a predicate.
-   *
-   *  @param p the predicate for which to count
-   *  @return  the number of elements satisfying the predicate <code>p</code>.
-   */
-  def count(p: A => Boolean): Int = {
-    var cnt = 0
-    var these = this
-    while (!these.isEmpty) {
-      if (p(these.head)) cnt += 1
-      these = these.tail
-    }
-    cnt
-  }
-
-  /** Tests if the predicate <code>p</code> is satisfied by all elements
-   *  in this list.
-   *
-   *  @param p the test predicate.
-   *  @return  <code>true</code> iff all elements of this list satisfy the
-   *           predicate <code>p</code>.
-   */
-  override def forall(p: A => Boolean): Boolean = {
-    var these = this
-    while (!these.isEmpty) {
-      if (!p(these.head)) return false
-      these = these.tail
-    }
-    true
-  }
-
-  /** Tests the existence in this list of an element that satisfies the
-   *  predicate <code>p</code>.
-   *
-   *  @param p the test predicate.
-   *  @return  <code>true</code> iff there exists an element in this list that
-   *           satisfies the predicate <code>p</code>.
-   */
-  override def exists(p: A => Boolean): Boolean = {
-    var these = this
-    while (!these.isEmpty) {
-      if (p(these.head)) return true
-      these = these.tail
-    }
-    false
-  }
-
-  /** Find and return the first element of the list satisfying a
-   *  predicate, if any.
-   *
-   *  @param p the predicate
-   *  @return the first element in the list satisfying <code>p</code>,
-   *  or <code>None</code> if none exists.
-   */
-  override def find(p: A => Boolean): Option[A] = {
-    var these = this
-    while (!these.isEmpty) {
-      if (p(these.head)) return Some(these.head)
-      these = these.tail
-    }
-    None
-  }
-
-  /** Combines the elements of this list together using the binary
-   *  function <code>f</code>, from left to right, and starting with
-   *  the value <code>z</code>.
-   *
-   *  @return <code>f(... (f(f(z, a<sub>0</sub>), a<sub>1</sub>) ...),
-   *          a<sub>n</sub>)</code> if the list is
-   *          <code>[a<sub>0</sub>, a<sub>1</sub>, ..., a<sub>n</sub>]</code>.
-   */
-  override def foldLeft[B](z: B)(f: (B, A) => B): B = {
-    var acc = z
-    var these = this
-    while (!these.isEmpty) {
-      acc = f(acc, these.head)
-      these = these.tail
-    }
-    acc
-  }
-
-  /** Combines the elements of this list together using the binary
-   *  function <code>f</code>, from right to left, and starting with
-   *  the value <code>z</code>.
-   *
-   *  @return <code>f(a<sub>0</sub>, f(a<sub>1</sub>, f(..., f(a<sub>n</sub>, z)...)))</code>
-   *          if the list is <code>[a<sub>0</sub>, a1, ..., a<sub>n</sub>]</code>.
-   */
-  override def foldRight[B](z: B)(f: (A, B) => B): B = this match {
-    case Nil => z
-    case x :: xs => f(x, xs.foldRight(z)(f))
-  }
-
-  /** Combines the elements of this list together using the binary
-   *  operator <code>op</code>, from left to right
-   *  @param op  The operator to apply
-   *  @return <code>op(... op(a<sub>0</sub>,a<sub>1</sub>), ..., a<sub>n</sub>)</code> 
-      if the list has elements
-   *          <code>a<sub>0</sub>, a<sub>1</sub>, ..., a<sub>n</sub></code>.
-   *  @throws Predef.UnsupportedOperationException if the list is empty.
-   */
-  override def reduceLeft[B >: A](f: (B, A) => B): B = this match {
-    case Nil => throw new UnsupportedOperationException("Nil.reduceLeft")
-    case x :: Nil => x
-    case x0 :: x1 :: xs => 
-      var acc : B = f(x0, x1)
-      var these : List[A] = xs
-      while (!these.isEmpty) {
-        acc = f(acc, these.head)
-        these = these.tail
-      }
-      acc
-  }
-
-  /** Combines the elements of this list together using the binary
-   *  operator <code>op</code>, from right to left
-   *  @param op  The operator to apply
-   *
-   *  @return <code>a<sub>0</sub> op (... op (a<sub>n-1</sub> op a<sub>n</sub>)...)</code>
-   *          if the list has elements <code>a<sub>0</sub>, a<sub>1</sub>, ...,
-   *          a<sub>n</sub></code>.
-   *
-   *  @throws Predef.UnsupportedOperationException if the list is empty.
-   */
-  override def reduceRight[B >: A](f: (A, B) => B): B = this match {
-    case Nil => throw new UnsupportedOperationException("Nil.reduceRight")
-    case x :: Nil => x
-    case x :: xs => f(x, xs reduceRight f)
-  }
-
-  /** Applies the given function <code>f</code> to each element of
-   *  this list, then concatenates the results.
-   *
-   *  @param f the function to apply on each element.
-   *  @return  <code>f(a<sub>0</sub>) ::: ... ::: f(a<sub>n</sub>)</code> if
-   *           this list is <code>[a<sub>0</sub>, ..., a<sub>n</sub>]</code>.
-   */
-  final override def flatMap[B](f: A => Iterable[B]): List[B] = {
-    val b = new ListBuffer[B]
-    var these = this
-    while (!these.isEmpty) {
-      var those = f(these.head).elements
-      while (those.hasNext) {
-        b += those.next
-      }
-      these = these.tail
-    }
-    b.toList
-  }
-
-  /** A list consisting of all elements of this list in reverse order.
-   */
-  override def reverse: List[A] = {
-    var result: List[A] = Nil
-    var these = this
-    while (!these.isEmpty) {
-      result = these.head :: result
-      these = these.tail
-    }
-    result
-  }
-
-  /** Returns a list formed from this list and the specified list
-   *  <code>that</code> by associating each element of the former with
-   *  the element at the same position in the latter.
-   *  If one of the two lists is longer than the other, its remaining elements are ignored.
-   *
-   *  @return     <code>List((a<sub>0</sub>,b<sub>0</sub>), ...,
-   *              (a<sub>min(m,n)</sub>,b<sub>min(m,n)</sub>))</code> when
-   *              <code>List(a<sub>0</sub>, ..., a<sub>m</sub>)
-   *              zip List(b<sub>0</sub>, ..., b<sub>n</sub>)</code> is invoked.
-   */
-  def zip[B](that: List[B]): List[(A, B)] = {
-    val b = new ListBuffer[(A, B)]
-    var these = this
-    var those = that
-    while (!these.isEmpty && !those.isEmpty) {
-      b += ((these.head, those.head))
-      these = these.tail
-      those = those.tail
-    }
-    b.toList
-  }
-
-  /** Returns a list that pairs each element of this list
-   *  with its index, counting from 0.
-   *
-   *  @return      the list <code>List((a<sub>0</sub>,0), (a<sub>1</sub>,1), ...)</code>
-   *               where <code>a<sub>i</sub></code> are the elements of this list.
-   */
-  def zipWithIndex: List[(A, Int)] = {
-    val b = new ListBuffer[(A, Int)]
-    var these = this
-    var idx = 0
-
-    while(!these.isEmpty) {
-      b += ((these.head, idx))
-      these = these.tail
-      idx += 1
-    }
-
-    b.toList
-  }
-
-  /** Returns a list formed from this list and the specified list
-   *  <code>that</code> by associating each element of the former with
-   *  the element at the same position in the latter.
-   *
-   *  @param that     list <code>that</code> may have a different length
-   *                  as the self list.
-   *  @param thisElem element <code>thisElem</code> is used to fill up the
-   *                  resulting list if the self list is shorter than
-   *                  <code>that</code>
-   *  @param thatElem element <code>thatElem</code> is used to fill up the
-   *                  resulting list if <code>that</code> is shorter than
-   *                  the self list
-   *  @return         <code>List((a<sub>0</sub>,b<sub>0</sub>), ...,
-   *                  (a<sub>n</sub>,b<sub>n</sub>), (elem,b<sub>n+1</sub>),
-   *                  ..., {elem,b<sub>m</sub>})</code>
-   *                  when <code>[a<sub>0</sub>, ..., a<sub>n</sub>] zip
-   *                  [b<sub>0</sub>, ..., b<sub>m</sub>]</code> is
-   *                  invoked where <code>m > n</code>.
-   */
-  def zipAll[B, C >: A, D >: B](that: List[B], thisElem: C, thatElem: D): List[(C, D)] = {
-    val b = new ListBuffer[(C, D)]
-    var these = this
-    var those = that
-    while (!these.isEmpty && !those.isEmpty) {
-      b += ((these.head, those.head))
-      these = these.tail
-      those = those.tail
-    }
-    while (!these.isEmpty) {
-      b += ((these.head, thatElem))
-      these = these.tail
-    }
-    while (!those.isEmpty) {
-      b += ((thisElem, those.head))
-      those = those.tail
-    }
-    b.toList
-  }
-
-  /** Computes the union of this list and the given list
-   *  <code>that</code>.
-   *
-   *  @param that the list of elements to add to the list.
-   *  @return     a list without doubles containing the elements of this
-   *              list and those of the given list <code>that</code>.
-   */
-  def union[B >: A](that: List[B]): List[B] = {
-    val b = new ListBuffer[B]
-    var these = this
-    while (!these.isEmpty) {
-      if (!that.contains(these.head)) b += these.head
-      these = these.tail
-    }
-    b.prependToList(that)
-  }
-
-  /** Computes the difference between this list and the given list
-   *  <code>that</code>.
-   *
-   *  @param that the list of elements to remove from this list.
-   *  @return     this list without the elements of the given list
-   *              <code>that</code>.
-   *  @deprecated use <code>--</code> instead
-   */
-  @deprecated
-  def diff[B >: A](that: List[B]): List[B] = this -- that
-
-  /** Computes the difference between this list and the given list
-   *  <code>that</code>.
-   *
-   *  @param that the list of elements to remove from this list.
-   *  @return     this list without the elements of the given list
-   *              <code>that</code>.
-   */
-  def -- [B >: A](that: List[B]): List[B] = {
-    val b = new ListBuffer[B]
-    var these = this
-    while (!these.isEmpty) {
-      if (!that.contains(these.head)) b += these.head
-      these = these.tail
-    }
-    b.toList
-  }
-
-  /** Computes the difference between this list and the given object
-   *  <code>x</code>.
-   *
-   *  @param x    the object to remove from this list.
-   *  @return     this list without the elements of the given object
-   *              <code>x</code>.
-   */
-  def - [B >: A](x: B): List[B] = {
-    val b = new ListBuffer[B]
-    var these = this
-    while (!these.isEmpty) {
-      if (these.head != x) b += these.head
-      these = these.tail
-    }
-    b.toList
-  }
-
-  /** Concatenate the elements of this list. The elements of this list
-   *  should be a <code>Iterables</code>.
-   *
-   *  Note: The compiler might not be able to infer the type parameter.
-   *
-   *  @param f    An implicit conversion to an <code>Iterable</code> instance.
-   *  @return     The concatenation of all elements of iterables in this list.
-   */
-  def flatten[B](implicit f : A => Iterable[B]) : List[B] = {
-    val buf = new ListBuffer[B]
-    foreach(f(_).foreach(buf += _))
-    buf.toList
-  }
-
-  /** Computes the intersection between this list and the given list
-   *  <code>that</code>.
-   *
-   *  @param that the list to intersect.
-   *  @return     the list of elements contained both in this list and
-   *              in the given list <code>that</code>.
-   */
-  def intersect[B >: A](that: List[B]): List[B] = filter(x => that contains x)
-
-  /** Removes redundant elements from the list. Uses the method <code>==</code>
-   *  to decide if two elements are identical.
-   *
-   *  @return the list without doubles.
-   */
-  def removeDuplicates: List[A] = {
-    val b = new ListBuffer[A]
-    var these = this
-    while (!these.isEmpty) {
-      if (!these.tail.contains(these.head)) b += these.head
-      these = these.tail
-    }
-    b.toList
-  }
-   
-  override protected def stringPrefix = "List"
-  override def projection = toStream
-  override def toStream : Stream[A] = new Stream.Definite[A] {
-    override def force : List[A] = List.this
-    override def isEmpty = List.this.isEmpty
-    override def head = List.this.head
-    override def tail = List.this.tail.toStream
-    protected def addDefinedElems(buf: StringBuilder, prefix: String): StringBuilder = if (!isEmpty) {
-      var prefix0 = prefix
-      var buf1 = buf.append(prefix0).append(head)
-      prefix0 = ", "
-      var tail0 = tail
-      while (!tail0.isEmpty) {
-        buf1 = buf.append(prefix0).append(tail0.head)
-        tail0 = tail0.tail
-      }
-      buf1
-    } else buf
-  }
-
-}
-
-/** The empty list.
- *
- *  @author  Martin Odersky
- *  @version 1.0, 15/07/2003
- */
- at SerialVersionUID(0 - 8256821097970055419L)
-case object Nil extends List[Nothing] {
-  override def isEmpty = true
-  def head: Nothing =
-    throw new NoSuchElementException("head of empty list")
-  def tail: List[Nothing] =
-    throw new NoSuchElementException("tail of empty list")
-}
-
-/** A non empty list characterized by a head and a tail.
- *
- *  @author  Martin Odersky
- *  @version 1.0, 15/07/2003
- */
- at SerialVersionUID(0L - 8476791151983527571L)
-final case class ::[B](private var hd: B, private[scala] var tl: List[B]) extends List[B] {
-  def head : B = hd
-  def tail : List[B] = tl
-  override def isEmpty: Boolean = false
-
-  import java.io._
-
-  private def writeObject(out: ObjectOutputStream) {
-    var xs: List[B] = this
-    while (!xs.isEmpty) { out.writeObject(xs.head); xs = xs.tail }
-    out.writeObject(ListSerializeEnd)
-  }
-
-  private def readObject(in: ObjectInputStream) {
-    hd = in.readObject.asInstanceOf[B]
-    assert(hd != ListSerializeEnd)
-    var current: ::[B] = this
-    while (true) in.readObject match {
-      case ListSerializeEnd =>
-        current.tl = Nil
-        return
-      case a : Any =>
-        val list : ::[B] = new ::(a.asInstanceOf[B], Nil)
-        current.tl = list
-        current = list
-    }
-  }
-}
-
-/** Only used for list serialization */
- at SerialVersionUID(0L - 8476791151975527571L)
-private[scala] case object ListSerializeEnd
diff --git a/src/library/scala/LowPriorityImplicits.scala b/src/library/scala/LowPriorityImplicits.scala
new file mode 100644
index 0000000..af8227d
--- /dev/null
+++ b/src/library/scala/LowPriorityImplicits.scala
@@ -0,0 +1,60 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+package scala
+
+import collection.mutable._
+import collection.immutable.WrappedString
+import collection.generic.CanBuildFrom
+
+/** The `LowPriorityImplicits` class provides implicit values that
+ *  are valid in all Scala compilation units without explicit qualification,
+ *  but that are partially overridden by higher-priority conversions in object
+ *  `Predef`.
+ *
+ *  @author  Martin Odersky
+ *  @since 2.8
+ */
+class LowPriorityImplicits {
+
+  implicit def genericWrapArray[T](xs: Array[T]): WrappedArray[T] = 
+    if (xs ne null) WrappedArray.make(xs) else null
+
+  implicit def wrapRefArray[T <: AnyRef](xs: Array[T]): WrappedArray[T] = if (xs ne null) new WrappedArray.ofRef[T](xs) else null
+  implicit def wrapIntArray(xs: Array[Int]): WrappedArray[Int] = if (xs ne null) new WrappedArray.ofInt(xs) else null
+  implicit def wrapDoubleArray(xs: Array[Double]): WrappedArray[Double] = if (xs ne null) new WrappedArray.ofDouble(xs) else null
+  implicit def wrapLongArray(xs: Array[Long]): WrappedArray[Long] = if (xs ne null) new WrappedArray.ofLong(xs) else null
+  implicit def wrapFloatArray(xs: Array[Float]): WrappedArray[Float] = if (xs ne null) new WrappedArray.ofFloat(xs) else null
+  implicit def wrapCharArray(xs: Array[Char]): WrappedArray[Char] = if (xs ne null) new WrappedArray.ofChar(xs) else null
+  implicit def wrapByteArray(xs: Array[Byte]): WrappedArray[Byte] = if (xs ne null) new WrappedArray.ofByte(xs) else null
+  implicit def wrapShortArray(xs: Array[Short]): WrappedArray[Short] = if (xs ne null) new WrappedArray.ofShort(xs) else null
+  implicit def wrapBooleanArray(xs: Array[Boolean]): WrappedArray[Boolean] = if (xs ne null) new WrappedArray.ofBoolean(xs) else null
+  implicit def wrapUnitArray(xs: Array[Unit]): WrappedArray[Unit] = if (xs ne null) new WrappedArray.ofUnit(xs) else null
+
+  implicit def wrapString(s: String): WrappedString = if (s ne null) new WrappedString(s) else null
+  implicit def unwrapString(ws: WrappedString): String = if (ws ne null) ws.self else null
+
+  implicit def fallbackStringCanBuildFrom[T]: CanBuildFrom[String, T, collection.immutable.IndexedSeq[T]] = 
+    new CanBuildFrom[String, T, collection.immutable.IndexedSeq[T]] { 
+      def apply(from: String) = scala.collection.immutable.IndexedSeq.newBuilder[T]
+      def apply() = scala.collection.immutable.IndexedSeq.newBuilder[T]
+    }
+
+  /** Can go away after next newstarr */
+  /** Caution - not yet.  pos/t1459, pos/t2569, jvm/t1342 all fail without the next line. */
+  def wrapArray[T <: AnyRef](xs: Array[T]): WrappedArray[T] = new WrappedArray.ofRef[T](xs)
+  def wrapArray(xs: Array[Int]): WrappedArray[Int] = new WrappedArray.ofInt(xs)
+  def wrapArray(xs: Array[Double]): WrappedArray[Double] = new WrappedArray.ofDouble(xs)
+  def wrapArray(xs: Array[Long]): WrappedArray[Long] = new WrappedArray.ofLong(xs)
+  def wrapArray(xs: Array[Float]): WrappedArray[Float] = new WrappedArray.ofFloat(xs)
+  def wrapArray(xs: Array[Char]): WrappedArray[Char] = new WrappedArray.ofChar(xs)
+  def wrapArray(xs: Array[Byte]): WrappedArray[Byte] = new WrappedArray.ofByte(xs)
+  def wrapArray(xs: Array[Short]): WrappedArray[Short] = new WrappedArray.ofShort(xs)
+  def wrapArray(xs: Array[Boolean]): WrappedArray[Boolean] = new WrappedArray.ofBoolean(xs)
+  def wrapArray(xs: Array[Unit]): WrappedArray[Unit] = new WrappedArray.ofUnit(xs)
+}
diff --git a/src/library/scala/MatchError.scala b/src/library/scala/MatchError.scala
index c3c5329..bdd1915 100644
--- a/src/library/scala/MatchError.scala
+++ b/src/library/scala/MatchError.scala
@@ -1,18 +1,15 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: MatchError.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala
 
-import Predef._
-
 /** This class implements errors which are thrown whenever an
  *  object doesn't match any pattern of a pattern matching
  *  expression.
@@ -20,6 +17,7 @@ import Predef._
  *  @author  Matthias Zenger
  *  @author  Martin Odersky
  *  @version 1.1, 05/03/2004
+ *  @since   2.0
  */
 final class MatchError(msg: String) extends RuntimeException(msg) {
   def this(obj: Any) =
diff --git a/src/library/scala/Math.scala b/src/library/scala/Math.scala
index 8ffdc53..69a3985 100644
--- a/src/library/scala/Math.scala
+++ b/src/library/scala/Math.scala
@@ -1,13 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Math.scala 16881 2009-01-09 16:28:11Z cunei $
-
 
 package scala
 
@@ -15,190 +13,83 @@ package scala
  *  operations such as the elementary exponential, logarithm, square root, and
  *  trigonometric functions.
  */
-object Math {
+ at deprecated("use scala.math package instead")
+object Math extends MathCommon {
+  @deprecated("Use scala.Byte.MinValue instead")
+  val MIN_BYTE = java.lang.Byte.MIN_VALUE
+
+  @deprecated("Use scala.Byte.MaxValue instead")
+  val MAX_BYTE = java.lang.Byte.MAX_VALUE
+
+  @deprecated("Use scala.Short.MinValue instead")
+  val MIN_SHORT = java.lang.Short.MIN_VALUE
+
+  @deprecated("Use scala.Short.MaxValue instead")
+  val MAX_SHORT = java.lang.Short.MAX_VALUE
 
-  /** The smallest possible value for <a href="Byte.html" target="_self">scala.Byte</a>. */
-  val MIN_BYTE   = java.lang.Byte.MIN_VALUE
-  /** The greatest possible value for <a href="Byte.html" target="_self">scala.Byte</a>. */
-  val MAX_BYTE   = java.lang.Byte.MAX_VALUE
+  @deprecated("Use scala.Char.MinValue instead")
+  val MIN_CHAR = java.lang.Character.MIN_VALUE
 
-  /** The smallest possible value for <a href="Short.html" target="_self">scala.Short</a>. */
-  val MIN_SHORT  = java.lang.Short.MIN_VALUE
-  /** The greatest possible value for <a href="Short.html" target="_self">scala.Short</a>. */
-  val MAX_SHORT  = java.lang.Short.MAX_VALUE
+  @deprecated("Use scala.Char.MaxValue instead")
+  val MAX_CHAR = java.lang.Character.MAX_VALUE
 
-  /** The smallest possible value for <a href="Char.html" target="_self">scala.Char</a>. */
-  val MIN_CHAR   = java.lang.Character.MIN_VALUE
-  /** The greatest possible value for <a href="Char.html" target="_self">scala.Char</a>. */
-  val MAX_CHAR   = java.lang.Character.MAX_VALUE
+  @deprecated("Use scala.Int.MinValue instead")
+  val MIN_INT = java.lang.Integer.MIN_VALUE
 
-  /** The smallest possible value for <a href="Int.html" target="_self">scala.Int</a>. */
-  val MIN_INT    = java.lang.Integer.MIN_VALUE
-  /** The greatest possible value for <a href="Int.html" target="_self">scala.Int</a>. */
-  val MAX_INT    = java.lang.Integer.MAX_VALUE
+  @deprecated("Use scala.Int.MaxValue instead")
+  val MAX_INT = java.lang.Integer.MAX_VALUE
 
-  /** The smallest possible value for <a href="Long.html" target="_self">scala.Long</a>. */
-  val MIN_LONG   = java.lang.Long.MIN_VALUE
-  /** The greatest possible value for <a href="Long.html" target="_self">scala.Long</a>. */
-  val MAX_LONG   = java.lang.Long.MAX_VALUE
+  @deprecated("Use scala.Long.MinValue instead")
+  val MIN_LONG = java.lang.Long.MIN_VALUE
+
+  @deprecated("Use scala.Long.MaxValue instead")
+  val MAX_LONG = java.lang.Long.MAX_VALUE
 
   /** The smallest possible value for <a href="Float.html" target="_self">scala.Float</a>. */
+  @deprecated("Use scala.Float.MinValue instead")
   val MIN_FLOAT  = -java.lang.Float.MAX_VALUE
+
   /** The smallest difference between two values of <a href="Float.html" target="_self">scala.Float</a>. */
+  @deprecated("Use scala.Float.Epsilon instead")
   val EPS_FLOAT  = java.lang.Float.MIN_VALUE
+
   /** The greatest possible value for <a href="Float.html" target="_self">scala.Float</a>. */
+  @deprecated("Use scala.Float.MaxValue instead")
   val MAX_FLOAT  = java.lang.Float.MAX_VALUE
+
   /** A value of type <a href="Float.html" target="_self">scala.Float</a> that represents no number. */
+  @deprecated("Use scala.Float.NaN instead")
   val NaN_FLOAT  = java.lang.Float.NaN
+
   /** Negative infinity of type <a href="Float.html" target="_self">scala.Float</a>. */
+  @deprecated("Use scala.Float.NegativeInfinity instead")
   val NEG_INF_FLOAT = java.lang.Float.NEGATIVE_INFINITY
+
   /** Positive infinity of type <a href="Float.html" target="_self">scala.Float</a>. */
+  @deprecated("Use scala.Float.PositiveInfinity instead")
   val POS_INF_FLOAT = java.lang.Float.POSITIVE_INFINITY
 
   /** The smallest possible value for <a href="Double.html" target="_self">scala.Double</a>. */
+  @deprecated("Use scala.Double.MinValue instead")
   val MIN_DOUBLE = -java.lang.Double.MAX_VALUE
+
   /** The smallest difference between two values of <a href="Double.html" target="_self">scala.Double</a>. */
+  @deprecated("Use scala.Double.Epsilon instead")
   val EPS_DOUBLE = java.lang.Double.MIN_VALUE
+
   /** The greatest possible value for <a href="Double.html" target="_self">scala.Double</a>. */
+  @deprecated("Use scala.Double.MaxValue instead")
   val MAX_DOUBLE = java.lang.Double.MAX_VALUE
+
   /** A value of type <a href="Double.html" target="_self">scala.Double</a> that represents no number. */
+  @deprecated("Use scala.Double.NaN instead")
   val NaN_DOUBLE = java.lang.Double.NaN
+
   /** Negative infinity of type <a href="Double.html" target="_self">scala.Double</a>. */
+  @deprecated("Use scala.Double.NegativeInfinity instead")
   val NEG_INF_DOUBLE = java.lang.Double.NEGATIVE_INFINITY
+
   /** Positive infinity of type <a href="Double.html" target="_self">scala.Double</a>. */
+  @deprecated("Use scala.Double.PositiveInfinity instead")
   val POS_INF_DOUBLE = java.lang.Double.POSITIVE_INFINITY
-
-  /** The <code>double</code> value that is closer than any other to
-   *  <code>e</code>, the base of the natural logarithms.
-   */
-  val E = java.lang.Math.E
-
-  /** The <code>double</code> value that is closer than any other to
-   *  <code>pi</code>, the ratio of the circumference of a circle to its
-   *  diameter.
-   */
-  val Pi = java.lang.Math.PI
-
-  /** Returns a <code>double</code> value with a positive sign, greater than
-   *  or equal to <code>0.0</code> and less than <code>1.0</code>.
-   */
-  def random: Double = java.lang.Math.random()
-
-  def sin(x: Double): Double = java.lang.Math.sin(x)
-  def cos(x: Double): Double = java.lang.Math.cos(x)
-  def tan(x: Double): Double = java.lang.Math.tan(x)
-  def asin(x: Double): Double = java.lang.Math.asin(x)
-  def acos(x: Double): Double = java.lang.Math.acos(x)
-  def atan(x: Double): Double = java.lang.Math.atan(x)
-
-  /** Converts an angle measured in degrees to an approximately equivalent
-   *  angle measured in radians.
-   *
-   *  @param  x an angle, in degrees
-   *  @return the measurement of the angle <code>x</code> in radians.
-   */
-  def toRadians(x: Double): Double = java.lang.Math.toRadians(x)
-
-  /** Converts an angle measured in radians to an approximately equivalent
-   *  angle measured in degrees.
-   *
-   *  @param  x angle, in radians
-   *  @return the measurement of the angle <code>x</code> in degrees.
-   */
-  def toDegrees(x: Double): Double = java.lang.Math.toDegrees(x)
-
-  /** Returns Euler's number <code>e</code> raised to the power of a
-   *  <code>double</code> value.
-   *
-   *  @param  x the exponent to raise <code>e</code> to.
-   *  @return the value <code>e<sup>a</sup></code>, where <code>e</code>
-   *          is the base of the natural logarithms.
-   */
-  def exp(x: Double): Double = java.lang.Math.exp(x)
-  def log(x: Double): Double = java.lang.Math.log(x)
-  def sqrt(x: Double): Double = java.lang.Math.sqrt(x)
-  def sqrt(x: Int): Int = java.lang.Math.sqrt(x.toDouble).toInt
-  def IEEEremainder(x: Double, y: Double): Double = java.lang.Math.IEEEremainder(x, y)
-
-  def ceil(x: Double): Double = java.lang.Math.ceil(x)
-  def floor(x: Double): Double = java.lang.Math.floor(x)
-
-  /** Returns the <code>double</code> value that is closest in value to the
-   *  argument and is equal to a mathematical integer.
-   *
-   *  @param  x a <code>double</code> value
-   *  @return the closest floating-point value to a that is equal to a
-   *          mathematical integer.
-   */
-  def rint(x: Double): Double = java.lang.Math.rint(x)
-
-  /** Converts rectangular coordinates <code>(x, y)</code> to polar
-   *  <code>(r, theta)</code>.
-   *
-   *  @param  x the ordinate coordinate
-   *  @param  y the abscissa coordinate
-   *  @return the <em>theta</em> component of the point <code>(r, theta)</code>
-   *          in polar coordinates that corresponds to the point
-   *          <code>(x, y)</code> in Cartesian coordinates.
-   */
-  def atan2(y: Double, x: Double): Double = java.lang.Math.atan2(y, x)
-
-  /** Returns the value of the first argument raised to the power of the
-   *  second argument.
-   *
-   *  @param x the base.
-   *  @param y the exponent.
-   *  @return the value <code>x<sup>y</sup></code>.
-   */
-  def pow(x: Double, y: Double): Double = java.lang.Math.pow(x, y)
-
-  /** Returns the closest <code>long</code> to the argument.
-   *
-   *  @param  x a floating-point value to be rounded to a <code>long</code>.
-   *  @return the value of the argument rounded to the nearest
-   *          <code>long</code> value.
-   */
-  def round(x: Float): Int = java.lang.Math.round(x)
-  def round(x: Double): Long = java.lang.Math.round(x)
-  def abs(x: Int): Int = java.lang.Math.abs(x)
-  def abs(x: Long): Long = java.lang.Math.abs(x)
-  def abs(x: Float): Float = java.lang.Math.abs(x)
-  def abs(x: Double): Double = java.lang.Math.abs(x)
-
-  def max(x: Int, y: Int): Int = java.lang.Math.max(x, y)
-  def max(x: Long, y: Long): Long = java.lang.Math.max(x, y)
-  def max(x: Float, y: Float): Float = java.lang.Math.max(x, y)
-  def max(x: Double, y: Double): Double = java.lang.Math.max(x, y)
-
-  def min(x: Int, y: Int): Int = java.lang.Math.min(x, y)
-  def min(x: Long, y: Long): Long  = java.lang.Math.min(x, y)
-  def min(x: Float, y: Float): Float  = java.lang.Math.min(x, y)
-  def min(x: Double, y: Double): Double = java.lang.Math.min(x, y)
-
-  def signum(x: Double): Double = x match { case 0 => 0
-                                            case y if y < 0 => -1.0
-                                            case y if y > 0 => 1.0 }
-  def signum(x: Float): Float = x match { case 0f => 0f
-                                          case y if y < 0f => -1.0f
-                                          case y if y > 0f => 1.0f }
-  def signum(x: Long): Long = x match { case 0l => 0l
-                                        case y if y < 0l => -1l
-                                        case y if y > 0l => 1l }
-  def signum(x: Int): Int = x match { case 0 => 0
-                                      case y if y < 0 => -1
-                                      case y if y > 0 => 1}
-
-  // from Java 1.5
-//   def log10(x: Double): Double = java.lang.Math.log10(x)
-//   def cbrt(x: Double): Double = java.lang.Math.cbrt(x)
-
-//   def ulp(x: Double): Double = java.lang.Math.ulp(x)
-//   def ulp(x: Float): Float = java.lang.Math.ulp(x)
-//   def sinh(x: Double): Double = java.lang.Math.sinh(x)
-//   def cosh(x: Double): Double = java.lang.Math.cosh(x)
-//   def tanh(x: Double):Double = java.lang.Math.tanh(x)
-//   def hypot(x: Double, y: Double): Double = java.lang.Math.hypot(x, y)
-//   def expm1(x: Double): Double = java.lang.Math.expm1(x)
-//   def log1p(x: Double): Double = java.lang.Math.log1p(x)
-
-}
+}
\ No newline at end of file
diff --git a/src/library/scala/MathCommon.scala b/src/library/scala/MathCommon.scala
new file mode 100644
index 0000000..11edf50
--- /dev/null
+++ b/src/library/scala/MathCommon.scala
@@ -0,0 +1,143 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+package scala
+
+/** Common code between the deprecated scala.Math object and
+ *  the scala.math package object.
+ */
+private[scala] class MathCommon {
+  /** The <code>double</code> value that is closer than any other to
+   *  <code>e</code>, the base of the natural logarithms.
+   */
+  val E = java.lang.Math.E
+
+  /** The <code>double</code> value that is closer than any other to
+   *  <code>pi</code>, the ratio of the circumference of a circle to its
+   *  diameter.
+   */
+  val Pi = java.lang.Math.PI
+
+  /** Returns a <code>double</code> value with a positive sign, greater than
+   *  or equal to <code>0.0</code> and less than <code>1.0</code>.
+   */
+  def random: Double = java.lang.Math.random()
+
+  def sin(x: Double): Double = java.lang.Math.sin(x)
+  def cos(x: Double): Double = java.lang.Math.cos(x)
+  def tan(x: Double): Double = java.lang.Math.tan(x)
+  def asin(x: Double): Double = java.lang.Math.asin(x)
+  def acos(x: Double): Double = java.lang.Math.acos(x)
+  def atan(x: Double): Double = java.lang.Math.atan(x)
+
+  /** Converts an angle measured in degrees to an approximately equivalent
+   *  angle measured in radians.
+   *
+   *  @param  x an angle, in degrees
+   *  @return the measurement of the angle <code>x</code> in radians.
+   */
+  def toRadians(x: Double): Double = java.lang.Math.toRadians(x)
+
+  /** Converts an angle measured in radians to an approximately equivalent
+   *  angle measured in degrees.
+   *
+   *  @param  x angle, in radians
+   *  @return the measurement of the angle <code>x</code> in degrees.
+   */
+  def toDegrees(x: Double): Double = java.lang.Math.toDegrees(x)
+
+  /** Returns Euler's number <code>e</code> raised to the power of a
+   *  <code>double</code> value.
+   *
+   *  @param  x the exponent to raise <code>e</code> to.
+   *  @return the value <code>e<sup>a</sup></code>, where <code>e</code>
+   *          is the base of the natural logarithms.
+   */
+  def exp(x: Double): Double = java.lang.Math.exp(x)
+  def log(x: Double): Double = java.lang.Math.log(x)
+  def sqrt(x: Double): Double = java.lang.Math.sqrt(x)
+  def IEEEremainder(x: Double, y: Double): Double = java.lang.Math.IEEEremainder(x, y)
+
+  def ceil(x: Double): Double = java.lang.Math.ceil(x)
+  def floor(x: Double): Double = java.lang.Math.floor(x)
+
+  /** Returns the <code>double</code> value that is closest in value to the
+   *  argument and is equal to a mathematical integer.
+   *
+   *  @param  x a <code>double</code> value
+   *  @return the closest floating-point value to a that is equal to a
+   *          mathematical integer.
+   */
+  def rint(x: Double): Double = java.lang.Math.rint(x)
+
+  /** Converts rectangular coordinates <code>(x, y)</code> to polar
+   *  <code>(r, theta)</code>.
+   *
+   *  @param  x the ordinate coordinate
+   *  @param  y the abscissa coordinate
+   *  @return the <em>theta</em> component of the point <code>(r, theta)</code>
+   *          in polar coordinates that corresponds to the point
+   *          <code>(x, y)</code> in Cartesian coordinates.
+   */
+  def atan2(y: Double, x: Double): Double = java.lang.Math.atan2(y, x)
+
+  /** Returns the value of the first argument raised to the power of the
+   *  second argument.
+   *
+   *  @param x the base.
+   *  @param y the exponent.
+   *  @return the value <code>x<sup>y</sup></code>.
+   */
+  def pow(x: Double, y: Double): Double = java.lang.Math.pow(x, y)
+
+  /** Returns the closest <code>long</code> to the argument.
+   *
+   *  @param  x a floating-point value to be rounded to a <code>long</code>.
+   *  @return the value of the argument rounded to the nearest
+   *          <code>long</code> value.
+   */
+  def round(x: Float): Int = java.lang.Math.round(x)
+  def round(x: Double): Long = java.lang.Math.round(x)
+  def abs(x: Int): Int = java.lang.Math.abs(x)
+  def abs(x: Long): Long = java.lang.Math.abs(x)
+  def abs(x: Float): Float = java.lang.Math.abs(x)
+  def abs(x: Double): Double = java.lang.Math.abs(x)
+
+  def max(x: Int, y: Int): Int = java.lang.Math.max(x, y)
+  def max(x: Long, y: Long): Long = java.lang.Math.max(x, y)
+  def max(x: Float, y: Float): Float = java.lang.Math.max(x, y)
+  def max(x: Double, y: Double): Double = java.lang.Math.max(x, y)
+
+  def min(x: Int, y: Int): Int = java.lang.Math.min(x, y)
+  def min(x: Long, y: Long): Long  = java.lang.Math.min(x, y)
+  def min(x: Float, y: Float): Float  = java.lang.Math.min(x, y)
+  def min(x: Double, y: Double): Double = java.lang.Math.min(x, y)
+
+  def signum(x: Double): Double =
+    if (x == 0d) 0d
+    else if (x < 0) -1.0
+    else if (x > 0) 1.0
+    else x    // NaN
+
+  def signum(x: Float): Float = 
+    if (x == 0f) 0f
+    else if (x < 0) -1.0f
+    else if (x > 0) 1.0f
+    else x    // NaN
+
+  def signum(x: Long): Long = 
+    if (x == 0l) 0l
+    else if (x < 0) -1l
+    else 1l
+
+  def signum(x: Int): Int = 
+    if (x == 0) 0
+    else if (x < 0) -1
+    else 1
+}
diff --git a/src/library/scala/Mutable.scala b/src/library/scala/Mutable.scala
new file mode 100644
index 0000000..f484c0a
--- /dev/null
+++ b/src/library/scala/Mutable.scala
@@ -0,0 +1,18 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala
+
+/**
+ * A marker trait for mutable datatructures such as mutable collections
+ *
+ * @since 2.8
+ */
+trait Mutable 
diff --git a/src/library/scala/NotDefinedError.scala b/src/library/scala/NotDefinedError.scala
index 3236b72..3694f28 100644
--- a/src/library/scala/NotDefinedError.scala
+++ b/src/library/scala/NotDefinedError.scala
@@ -1,17 +1,17 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: NotDefinedError.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala
 
-
-import Predef._
-
+/**
+ * @since 2.0
+ */
+ at deprecated("Use a custom Error class instead")
 final class NotDefinedError(msg: String) extends Error("not defined: " + msg)
diff --git a/src/library/scala/NotNull.scala b/src/library/scala/NotNull.scala
index 316b87e..8e4a29f 100644
--- a/src/library/scala/NotNull.scala
+++ b/src/library/scala/NotNull.scala
@@ -1,12 +1,17 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
+
+
+
 package scala
 
-/** A marker trait for things that are not allowed to be null
+/**
+ * A marker trait for things that are not allowed to be null
+ * @since 2.5
  */
 trait NotNull {}
diff --git a/src/library/scala/Option.scala b/src/library/scala/Option.scala
index fc18cae..5112db0 100644
--- a/src/library/scala/Option.scala
+++ b/src/library/scala/Option.scala
@@ -1,135 +1,247 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Option.scala 16881 2009-01-09 16:28:11Z cunei $
-
-
 package scala
 
-
-import Predef._
-
 object Option {
   /** An implicit conversion that converts an option to an iterable value
    */
   implicit def option2Iterable[A](xo: Option[A]): Iterable[A] = xo.toList
+
+  /** An Option factory which creates Some(x) if the argument is not null,
+   *  and None if it is null.
+   *
+   *  @param  x the value
+   *  @return   Some(value) if value != null, None if value == null
+   */
+  def apply[A](x: A): Option[A] = if (x == null) None else Some(x)
+
+  /** An Option factory which returns $none in a manner consistent with
+   *  the collections hierarchy.
+   */
+  def empty[A] : Option[A] = None
 }
 
-/** This class represents optional values. Instances of <code>Option</code>
- *  are either instances of case class <code>Some</code> or it is case
- *  object <code>None</code>.
+/** Represents optional values. Instances of `Option`
+ *  are either an instance of $some or the object $none.
+ *
+ *  The most idiomatic way to use an $option instance
+ *  is to treat it as a collection or monad and
+ *  use `map`,`flatMap`, `filter`,
+ *  or `foreach`:
+ *
+ *  {{{
+ *  val name:Option[String] = request.getParameter("name")
+ *  val upper = name map { _.trim } filter { _.length != 0 } map { _.toUpperCase }
+ *  println(upper.getOrElse(""))
+ *  }}}
+ *
+ *  Note that this is equivalent to {{{
+ *  val upper = for {
+ *    name <- request.getParameter("name")
+ *    trimmed <- Some(name.trim)
+ *    upper <- Some(trimmed.toUpperCase) if trimmed.length != 0
+ *  } yield upper
+ *  println(upper.getOrElse(""))
+ *  }}}
+ *
+ *  Because of how for comprehension works, if $none is returned
+ *  from `request.getParameter`, the entire expression results in
+ *  $none
+ *
+ *  This allows for sophisticated chaining of $option values without
+ *  having to check for the existence of a value.
+ *
+ *  A less-idiomatic way to use $option values is via pattern matching: {{{
+ *  val nameMaybe = request.getParameter("name")
+ *  nameMaybe match {
+ *    case Some(name) => {
+ *      println(name.trim.toUppercase)
+ *    }
+ *    case None => {
+ *      println("No name value")
+ *    }
+ *  }
+ *  }}}
  *
  *  @author  Martin Odersky
  *  @author  Matthias Zenger
  *  @version 1.1, 16/01/2007
+ *  @define none `None`
+ *  @define some [[scala.Some]]
+ *  @define option [[scala.Option]]
+ *  @define p `p`
+ *  @define f `f`
  */
 sealed abstract class Option[+A] extends Product {
+  self =>
 
-  /** True if the option is the <code>None</code> value, false otherwise.
+  /** Returns true if the option is $none, false otherwise.
    */
   def isEmpty: Boolean
 
-  /** True if the option is a <code>Some</code>(...) false otherwise.
+  /** Returns true if the option is an instance of $some, false otherwise.
    */
   def isDefined: Boolean = !isEmpty
 
-  /** get the value of this option.
-   *  @requires that the option is nonEmpty.
+  /** Returns the option's value.
+   *  @note The option must be nonEmpty.
    *  @throws Predef.NoSuchElementException if the option is empty.
    */
   def get: A
 
-  /** @deprecated; use <code>getOrElse</code> instead
-   */
-  @deprecated
-  def get[B >: A](default: B): B = this match {
-    case None => default
-    case Some(x) => x
-  }
-
-  /** If the option is nonempty return its value,
-   *  otherwise return the result of evaluating a default expression.
+  /** Returns the option's value if the option is nonempty, otherwise
+   * return the result of evaluating `default`.
    *
    *  @param default  the default expression.
    */
   def getOrElse[B >: A](default: => B): B = 
     if (isEmpty) default else this.get
 
-  /** If the option is nonempty, return a function applied to its value,
-   *  wrapped in a Some i.e. <code>Some(f(this.get))</code>.
-   *  Otherwise return <code>None</code>.
+  /** Returns the option's value if it is nonempty,
+   * or `null` if it is empty.
+   * Although the use of null is discouraged, code written to use 
+   * $option must often interface with code that expects and returns nulls.
+   * @example {{{
+   * val initalText: Option[String] = getInitialText
+   * val textField = new JComponent(initalText.orNull,20)
+   * }}}
+   */
+  def orNull[A1 >: A](implicit ev: Null <:< A1): A1 = this getOrElse null
+
+  /** Returns a $some containing the result of applying $f to this $option's
+   * value if this $option is nonempty.
+   * Otherwise return $none.
+   *
+   *  @note This is similar to `flatMap` except here,
+   *  $f does not need to wrap its result in an $option.
    *
    *  @param  f   the function to apply
+   *  @see flatMap
+   *  @see foreach
    */
   def map[B](f: A => B): Option[B] = 
     if (isEmpty) None else Some(f(this.get))
 
-  /** If the option is nonempty, return a function applied to its value.
-   *  Otherwise return None.
+  /** Returns the result of applying $f to this $option's value if
+   * this $option is nonempty.
+   * Returns $none if this $option is empty.
+   * Slightly different from `map` in that $f is expected to
+   * return an $option (which could be $none).
+   *
    *  @param  f   the function to apply
+   *  @see map
+   *  @see foreach
    */
   def flatMap[B](f: A => Option[B]): Option[B] = 
     if (isEmpty) None else f(this.get)
 
-  /** If the option is nonempty and the given predicate <code>p</code>
-   *  yields <code>false</code> on its value, return <code>None</code>.
-   *  Otherwise return the option value itself.
+  /** Returns this $option if it is nonempty '''and''' applying the predicate $p to
+   * this $option's value returns true. Otherwise, return $none.
    *
    *  @param  p   the predicate used for testing.
    */
   def filter(p: A => Boolean): Option[A] = 
     if (isEmpty || p(this.get)) this else None
 
-  /** Apply the given procedure <code>f</code> to the option's value,
-   *  if it is nonempty. Do nothing if it is empty.
+  /** Necessary to keep $option from being implicitly converted to
+   *  [[scala.collection.Iterable]] in `for` comprehensions.
+   */
+  def withFilter(p: A => Boolean): WithFilter = new WithFilter(p)
+
+  /** We need a whole WithFilter class to honor the "doesn't create a new
+   *  collection" contract even though it seems unlikely to matter much in a
+   *  collection with max size 1.
+   */
+  class WithFilter(p: A => Boolean) {
+    def map[B](f: A => B): Option[B] = self filter p map f
+    def flatMap[B](f: A => Option[B]): Option[B] = self filter p flatMap f
+    def foreach[U](f: A => U): Unit = self filter p foreach f
+    def withFilter(q: A => Boolean): WithFilter = new WithFilter(x => p(x) && q(x))
+  }
+
+  /** Returns true if this option is nonempty '''and''' the predicate
+   * $p returns true when applied to this $option's value.
+   * Otherwise, returns false.
+   *
+   *  @param  p   the predicate to test
+   */
+  def exists(p: A => Boolean): Boolean =
+    !isEmpty && p(this.get)
+
+  /** Apply the given procedure $f to the option's value,
+   *  if it is nonempty. Otherwise, do nothing.
    *
    *  @param  f   the procedure to apply.
+   *  @see map
+   *  @see flatMap
    */
-  def foreach(f: A => Unit) {
+  def foreach[U](f: A => U) {
     if (!isEmpty) f(this.get)
   }
 
-  /** If the option is nonempty return it,
-   *  otherwise return the result of evaluating an alternative expression.
-   *  @param alternative  the alternative expression.
+  /** Returns a $some containing the result of
+   * applying `pf` to this $option's contained
+   * value, '''if''' this option is
+   * nonempty '''and''' `pf` is defined for that value.
+   * Returns $none otherwise.
+   *
+   *  @param  pf   the partial function.
+   *  @return the result of applying `pf` to this $option's
+   *  value (if possible), or $none.
+   */
+  def collect[B](pf: PartialFunction[A, B]): Option[B] =
+    if (!isEmpty && pf.isDefinedAt(this.get)) Some(pf(this.get)) else None  
+
+  /** Returns this $option if it is nonempty,
+   *  otherwise return the result of evaluating `alternative`.
+   *  @param alternative the alternative expression.
    */
   def orElse[B >: A](alternative: => Option[B]): Option[B] = 
     if (isEmpty) alternative else this
 
-  /** An singleton iterator returning the option's value if it is nonempty
-   *  or the empty iterator if the option is empty.
+  /** Returns a singleton iterator returning the $option's value
+   * if it is nonempty, or an empty iterator if the option is empty.
    */
-  def elements: Iterator[A] = 
-    if (isEmpty) Iterator.empty else Iterator.fromValues(this.get)
+  def iterator: Iterator[A] = 
+    if (isEmpty) Iterator.empty else Iterator.single(this.get)
 
-  /** A singleton list containing the option's value if it is nonempty
-   *  or the empty list if the option is empty.
+  /** Returns a singleton list containing the $option's value
+   * if it is nonempty, or the empty list if the $option is empty.
    */
   def toList: List[A] = 
     if (isEmpty) List() else List(this.get)
 
-  /** An <code>Either</code> that is a <code>Left</code> with the given argument
-   * <code>left</code> if this is empty, or a <code>Right</code> if this is nonempty with the
-   * option's value.
+  /** Returns a [[scala.Left]] containing the given
+   * argument `left` if this $option is empty, or
+   * a [[scala.Right]] containing this $option's value if
+   * this is nonempty.
+   *
+   * @param left the expression to evaluate and return if this is empty
+   * @see toLeft
    */
   def toRight[X](left: => X) =
     if (isEmpty) Left(left) else Right(this.get)
 
-  /** An <code>Either</code> that is a <code>Right</code> with the given argument
-   * <code>right</code> if this is empty, or a <code>Left</code> if this is nonempty with the
-   * option's value.
+  /** Returns a [[scala.Right]] containing the given
+   * argument `right` if this is empty, or
+   * a [[scala.Left]] containing this $option's value
+   * if this $option is nonempty.
+   *
+   * @param right the expression to evaluate and return if this is empty
+   * @see toRight
    */
   def toLeft[X](right: => X) =
     if (isEmpty) Right(right) else Left(this.get)
 }
 
-/** Class <code>Some[A]</code> represents existing values of type
- *  <code>A</code>.
+/** Class `Some[A]` represents existing values of type
+ *  `A`.
  *
  *  @author  Martin Odersky
  *  @version 1.0, 16/07/2003
diff --git a/src/library/scala/Ordered.scala b/src/library/scala/Ordered.scala
deleted file mode 100644
index 85727c8..0000000
--- a/src/library/scala/Ordered.scala
+++ /dev/null
@@ -1,53 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: Ordered.scala 16881 2009-01-09 16:28:11Z cunei $
-
-
-package scala
-
-/** A trait for totally ordered data.
- *
- * Note that since version 2006-07-24 this trait is no longer covariant in a.
- *
- * It is important that the equals method for an instance of 
- * Ordered[A] be consistent with the compare method.  However, 
- * due to limitations inherent in the type erasure semantics, 
- * there is no reasonable way to provide a default implementation
- * of equality for instances of Ordered[A].  Therefore, if you need
- * to be able to use equality on an instance of Ordered[A] you must 
- * provide it yourself either when inheiriting or instantiating. 
- *
- * It is important that the hashCode method for an instance of 
- * Ordered[A] be consistent with the compare method. However, 
- * it is not possible to provide a sensible default implementation.
- * Therefore, if you need to be able compute the hash of an 
- * instance of Ordered[A] you must provide it yourself either when 
- * inheiriting or instantiating. 
- *
- *  @author  Martin Odersky
- *  @version 1.1, 2006-07-24 
- */
-trait Ordered[A] {
-
-  /** Result of comparing <code>this</code> with operand <code>that</code>.
-   *  returns <code>x</code> where
-   *  <code>x < 0</code>    iff    <code>this < that</code>
-   *  <code>x == 0</code>   iff    <code>this == that</code>
-   *  <code>x > 0</code>    iff    <code>this > that</code>
-   */
-  def compare(that: A): Int
-
-  def <  (that: A): Boolean = (this compare that) <  0
-  def >  (that: A): Boolean = (this compare that) >  0
-  def <= (that: A): Boolean = (this compare that) <= 0
-  def >= (that: A): Boolean = (this compare that) >= 0
-  def compareTo(that: A): Int = compare(that)
-
-
-}
diff --git a/src/library/scala/Ordering.scala b/src/library/scala/Ordering.scala
deleted file mode 100644
index a9342b6..0000000
--- a/src/library/scala/Ordering.scala
+++ /dev/null
@@ -1,74 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: Ordering.scala 16881 2009-01-09 16:28:11Z cunei $
-
-package scala
-
-/** A trait for representing total orderings.  It is important to 
- * distinguish between a type that has a total order and a representation 
- * of total  ordering on some type.  This trait is for representing the 
- * latter.  
- *
- * A <a href="http://en.wikipedia.org/wiki/Total_order">total ordering</a> 
- * is a binary relation on a type <code>T</code> that is also an equivalence relation
- * and partial ordering on values of type <code>T</code>.  This relation is exposed as
- * the <code>compare</code> method of the <code>Ordering</code> trait.   
- * This relation must be:
- * <ul>
- * <li>reflexive: <code>compare(x, x) == 0</code>, for any <code>x</code> of 
- * type <code>T</code>.</li>
- * <li>symmetry: <code>compare(x, y) == z</code> and <code>compare(y, x) == w</code>
- * then <code>Math.signum(z) == -Math.signum(w)</code>, for any <code>x</code> and <code>y</code> of 
- * type <code>T</code> and <code>z</code> and <code>w</code> of type <code>Int</code>.</li>
- * <li>transitive: if <code>compare(x, y) == z</code> and <code>compare(y, w) == v</code> 
- * and <code>Math.signum(z) >= 0</code> and <code>Math.signum(v) >= 0</code> then
- * <code>compare(x, w) == u</code> and <code>Math.signum(z + v) == Math.signum(u)</code>,
- * for any <code>x</code>, <code>y</code>,
- * and <code>w</code> of type <code>T</code> and <code>z</code>, <code>v</code>, and <code>u</code>
- * of type <code>Int</code>.</li>
- * </ul>
- *
- * @author Geoffrey Washburn
- * @version 0.9.5, 2008-04-15
- */
-
-trait Ordering[T] extends PartialOrdering[T] { 
- /** Returns a negative integer iff <code>x</code> comes before 
-   * <code>y</code> in the ordering, returns 0 iff <code>x</code> 
-   * is the same in the ordering as <code>y</code>, and returns a 
-   * positive number iff <code>x</code> comes after
-   * <code>y</code> in the ordering.
-   */
-  def compare(x: T, y: T): Int
-
- /** Returns <code>true</code> iff <code>x</code> comes before 
-   *  <code>y</code> in the ordering.
-   */
-  override def lteq(x: T, y: T): Boolean = compare(x, y) <= 0
-
-  /** Returns <code>true</code> iff <code>y</code> comes before
-   *  <code>x</code> in the ordering. 
-   */
-  override def gteq(x: T, y: T): Boolean = compare(x, y) >= 0
-
-  /** Returns <code>true</code> iff <code>x</code> comes before 
-   *  <code>y</code> in the ordering and is not the same as <code>y</code>.
-   */
-  override def lt(x: T, y: T): Boolean = compare(x, y) < 0
-
-  /** Returns <code>true</code> iff <code>y</code> comes before 
-   *  <code>x</code> in the ordering and is not the same as <code>x</code>.
-   */
-  override def gt(x: T, y: T): Boolean = compare(x, y) > 0
-
-  /** Returns <code>true</code> iff <code>x</code> is equivalent to
-   *  <code>y</code> in the ordering. 
-   */
-  override def equiv(x: T, y: T): Boolean = compare(x, y) == 0
-}
diff --git a/src/library/scala/PartialFunction.scala b/src/library/scala/PartialFunction.scala
index 013894d..22de6a6 100644
--- a/src/library/scala/PartialFunction.scala
+++ b/src/library/scala/PartialFunction.scala
@@ -1,34 +1,42 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: PartialFunction.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala
 
-
-/** A partial function of type <code>PartialFunction[A, B]</code> is a
- *  unary function where the domain does not include all values of type
- *  <code>A</code>. The function <code>isDefinedAt</code> allows to
- *  test dynamically, if a value is in the domain of the function.
+/** A partial function of type `PartialFunction[A, B]` is a
+ *  unary function where the domain does not necessarily include all values of type
+ *  `A`. The function `isDefinedAt` allows to
+ *  test dynamically if a value is in the domain of the function.
  *
  *  @author  Martin Odersky
  *  @version 1.0, 16/07/2003
  */
-trait PartialFunction[-A, +B] extends AnyRef with (A => B) {
+trait PartialFunction[-A, +B] extends (A => B) {
 
-  /** Checks if a value is contained in the functions domain.
+  /** Checks if a value is contained in the function's domain.
    *
    *  @param  x   the value to test
-   *  @return true, iff <code>x</code> is in the domain of this function.
+   *  @return `true`, iff `x` is in the domain of this function, `false` otherwise.
    */
   def isDefinedAt(x: A): Boolean
 
+  /** Composes this partial function with a fallback partial function which gets applied where this partial function
+   *  is not defined.
+   *
+   *  @param   that    the fallback function
+   *  @tparam  A1      the argument type of the fallback function
+   *  @tparam  B1      the result type of the fallback function
+   *  @return  a partial function which has as domain the union of the domains
+   *           of this partial function and `that`. The resulting partial function
+   *           takes `x` to `this(x)` where `this` is defined, and to `that(x)` where it is not.
+   */
   def orElse[A1 <: A, B1 >: B](that: PartialFunction[A1, B1]) : PartialFunction[A1, B1] = 
     new PartialFunction[A1, B1] {
     def isDefinedAt(x: A1): Boolean = 
@@ -38,9 +46,63 @@ trait PartialFunction[-A, +B] extends AnyRef with (A => B) {
       else that.apply(x)
   }
 
+  /**  Composes this partial function with a transformation function that gets applied
+   *   to results of this partial function.
+   *   @param  k  the transformation function
+   *   @tparam C  the result type of the transformation function.
+   *   @return a partial function with the same domain as this partial function, which maps
+   *           arguments `x` to `k(this(x))`.
+   */
   override def andThen[C](k: B => C) : PartialFunction[A, C] = new PartialFunction[A, C] {
     def isDefinedAt(x: A): Boolean = PartialFunction.this.isDefinedAt(x)
     def apply(x: A): C = k(PartialFunction.this.apply(x))
   }
+
+  /** Turns this partial function into an plain function returning an `Option` result.
+   *  @return  a function that takes an argument `x` to `Some(this(x))` if `this`
+   *           is defined for `x`, and to `None` otherwise.
+   */
+  def lift: A => Option[B] = { x => if (isDefinedAt(x)) Some(this(x)) else None }
 }
 
+/** A few handy operations which leverage the extra bit of information
+ *  available in partial functions.  Examples:
+ * 
+ * <pre>
+ *  import PartialFunction._
+ *
+ *  def strangeConditional(other: Any): Boolean = cond(other) {
+ *    case x: String if x == "abc" || x == "def"  => true
+ *    case x: Int => true
+ *  }
+ *  def onlyInt(v: Any): Option[Int] = condOpt(v) { case x: Int => x }
+ * </pre>
+ * 
+ *  @author  Paul Phillips
+ *  @since   2.8
+ */
+object PartialFunction
+{
+  /** Creates a Boolean test based on a value and a partial function.
+   *  It behaves like a 'match' statement with an implied 'case _ => false'
+   *  following the supplied cases.
+   *
+   *  @param  x   the value to test
+   *  @param  pf  the partial function
+   *  @return true, iff `x` is in the domain of `pf` and `pf(x) == true`.
+   */
+  def cond[T](x: T)(pf: PartialFunction[T, Boolean]): Boolean =
+    (pf isDefinedAt x) && pf(x)
+  
+  /** Transforms a PartialFunction[T, U] `pf' into Function1[T, Option[U]] `f'
+   *  whose result is Some(x) if the argument is in pf's domain and None otherwise,
+   *  and applies it to the value `x'.  In effect, it is a 'match' statement
+   *  which wraps all case results in Some(_) and adds 'case _ => None' to the end.
+   *
+   *  @param  x     the value to test
+   *  @param  pf    the PartialFunction[T, U]
+   *  @return `Some(pf(x))` if `pf isDefinedAt x`, `None` otherwise.
+   */
+  def condOpt[T,U](x: T)(pf: PartialFunction[T, U]): Option[U] =
+    if (pf isDefinedAt x) Some(pf(x)) else None
+}
diff --git a/src/library/scala/PartialOrdering.scala b/src/library/scala/PartialOrdering.scala
deleted file mode 100644
index 45ee61a..0000000
--- a/src/library/scala/PartialOrdering.scala
+++ /dev/null
@@ -1,62 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: PartialOrdering.scala 16881 2009-01-09 16:28:11Z cunei $
-
-package scala
-
-/** A trait for representing partial orderings.  It is important to 
- * distinguish between a type that has a partial order and a representation 
- * of partial ordering on some type.  This trait is for representing the latter.  
- * 
- * A <a href="http://en.wikipedia.org/wiki/Partial_order">partial ordering</a> 
- * is a binary relation on a type <code>T</code> that is also an equivalence 
- * relation on values of type <code>T</code>.  This relation is exposed as
- * the <code>lteq</code> method of the <code>PartialOrdering</code> trait.  
- * This relation must be:
- * <ul>
- * <li>reflexive: <code>lteq(x, x) == true</code>, for any <code>x</code> of 
- * type <code>T</code>.</li>
- * <li>anti-symmetric: <code>lteq(x, y) == true</code> and <code>lteq(y, x) == true</code>
- * then <code>equiv(x, y)</code>, for any <code>x</code> and <code>y</code> of 
- * type <code>T</code>.</li>
- * <li>transitive: if <code>lteq(x, y) == true</code> and <code>lteq(y, z) == true</code> 
- * then <code>lteq(x, z) == true</code>,  for any <code>x</code>, <code>y</code>,
- * and <code>z</code> of type <code>T</code>.</li>
- * </ul>
- *
- *  @author  Geoffrey Washburn
- *  @version 1.0, 2008-04-0-3
- */
-
-trait PartialOrdering[T] extends Equiv[T] {
-  /** Returns <code>true</code> iff <code>x</code> comes before 
-   *  <code>y</code> in the ordering.
-   */
-  def lteq(x: T, y: T): Boolean
-
-  /** Returns <code>true</code> iff <code>y</code> comes before
-   *  <code>x</code> in the ordering. 
-   */
-  def gteq(x: T, y: T): Boolean = lteq(y, x)
-
-  /** Returns <code>true</code> iff <code>x</code> comes before 
-   *  <code>y</code> in the ordering and is not the same as <code>y</code>.
-   */
-  def lt(x: T, y: T): Boolean = lteq(x, y) && !equiv(x, y)
-
-  /** Returns <code>true</code> iff <code>y</code> comes before 
-   *  <code>x</code> in the ordering and is not the same as <code>x</code>.
-   */
-  def gt(x: T, y: T): Boolean = gteq(x, y) && !equiv(x, y)
-
-  /** Returns <code>true</code> iff <code>x</code> is equivalent to
-   *  <code>y</code> in the ordering. 
-   */
-  def equiv(x: T, y: T): Boolean = lteq(x,y) && lteq(y,x)
-}
diff --git a/src/library/scala/PartiallyOrdered.scala b/src/library/scala/PartiallyOrdered.scala
deleted file mode 100644
index 9ab64f8..0000000
--- a/src/library/scala/PartiallyOrdered.scala
+++ /dev/null
@@ -1,50 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: PartiallyOrdered.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala
-
-/** A class for partially ordered data.
- *
- *  @author  Martin Odersky
- *  @version 1.0, 23/04/2004
- */
-trait PartiallyOrdered[+A] {
-
-  /** Result of comparing <code>this</code> with operand <code>that</code>.
-   *  Returns <code>None</code> if operands are not comparable.
-   *  If operands are comparable, returns <code>Some(x)</code> where
-   *  <code>x < 0</code>    iff    <code>this < that</code>
-   *  <code>x == 0</code>   iff    <code>this == that</code>
-   *  <code>x > 0</code>    iff    <code>this > that</code>
-   */
-  def tryCompareTo [B >: A <% PartiallyOrdered[B]](that: B): Option[Int]
-
-  def <  [B >: A <% PartiallyOrdered[B]](that: B): Boolean =
-    (this tryCompareTo that) match {
-      case Some(x) if x < 0 => true
-      case _ => false
-    }
-  def >  [B >: A <% PartiallyOrdered[B]](that: B): Boolean =
-    (this tryCompareTo that) match {
-      case Some(x) if x > 0 => true
-      case _ => false
-    }
-  def <= [B >: A <% PartiallyOrdered[B]](that: B): Boolean =
-    (this tryCompareTo that) match {
-      case Some(x) if x <= 0 => true
-      case _ => false
-    }
-  def >= [B >: A <% PartiallyOrdered[B]](that: B): Boolean =
-    (this tryCompareTo that) match {
-      case Some(x) if x >= 0 => true
-      case _ => false
-    }
-}
diff --git a/src/library/scala/Predef.scala b/src/library/scala/Predef.scala
index 8af2c07..90da3d3 100644
--- a/src/library/scala/Predef.scala
+++ b/src/library/scala/Predef.scala
@@ -1,76 +1,58 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Predef.scala 16881 2009-01-09 16:28:11Z cunei $
 
 
 package scala
 
+import collection.immutable.StringOps
+import collection.mutable.ArrayOps
+import collection.generic.CanBuildFrom
+import annotation.elidable
+import annotation.elidable.ASSERTION
 
 /** The <code>Predef</code> object provides definitions that are
  *  accessible in all Scala compilation units without explicit
  *  qualification.
  */
-object Predef {
-
-  // classOf dummy ------------------------------------------------------
-
-  /** Return the runtime representation of a class type. */
+object Predef extends LowPriorityImplicits {
+  /** Return the runtime representation of a class type.  This is a stub method.
+   *  The actual implementation is filled in by the compiler.
+   */
   def classOf[T]: Class[T] = null
 
-  // aliases ------------------------------------------------------------
-
-  @deprecated type byte    = scala.Byte
-  @deprecated type short   = scala.Short
-  @deprecated type char    = scala.Char
-  @deprecated type int     = scala.Int
-  @deprecated type long    = scala.Long
-  @deprecated type float   = scala.Float
-  @deprecated type double  = scala.Double
-  @deprecated type boolean = scala.Boolean
-  @deprecated type unit    = scala.Unit
-
-  /** @deprecated use <code>java.lang.Integer</code> instead */
-  @deprecated type Integer = java.lang.Integer
-  /** @deprecated use <code>java.lang.Character</code> instead */
-  @deprecated type Character = java.lang.Character
-
   type String        = java.lang.String
   type Class[T]      = java.lang.Class[T]
-  type Runnable      = java.lang.Runnable
-
-  type Throwable = java.lang.Throwable
-  type Exception = java.lang.Exception
-  type Error     = java.lang.Error
-
-  type RuntimeException                = java.lang.RuntimeException
-  type NullPointerException            = java.lang.NullPointerException
-  type ClassCastException              = java.lang.ClassCastException
-  type IndexOutOfBoundsException       = java.lang.IndexOutOfBoundsException
-  type ArrayIndexOutOfBoundsException  = java.lang.ArrayIndexOutOfBoundsException
-  type StringIndexOutOfBoundsException = java.lang.StringIndexOutOfBoundsException
-  type UnsupportedOperationException   = java.lang.UnsupportedOperationException
-  type IllegalArgumentException        = java.lang.IllegalArgumentException
-  type NoSuchElementException          = java.util.NoSuchElementException
-  type NumberFormatException           = java.lang.NumberFormatException
 
   // miscelleaneous -----------------------------------------------------
-  
-  val $scope = scala.xml.TopScope
+  scala.`package`                         // to force scala package object to be seen.
+  scala.collection.immutable.List         // to force Nil, :: to be seen.
 
   type Function[-A, +B] = Function1[A, B]
-
+    
   type Map[A, +B] = collection.immutable.Map[A, B]
   type Set[A] = collection.immutable.Set[A]
-
   val Map = collection.immutable.Map
   val Set = collection.immutable.Set
 
+  type Manifest[T] = scala.reflect.Manifest[T]
+  type ClassManifest[T] = scala.reflect.ClassManifest[T]
+  def implicitly[T](implicit e: T) = e
+  def manifest[T](implicit m: Manifest[T]) = m
+  def classManifest[T](implicit m: ClassManifest[T]) = m
+
+  // @see `conforms` for the implicit version
+  def identity[A](x: A): A = x 
+
+  def currentThread = java.lang.Thread.currentThread()
+
+  @inline def locally[T](x: T): T = x
+
   // errors and asserts -------------------------------------------------
 
   def error(message: String): Nothing = throw new RuntimeException(message)
@@ -82,35 +64,94 @@ object Predef {
     throw new Throwable()
   }
 
+  /** Tests an expression, throwing an AssertionError if false.
+   *  Calls to this method will not be generated if -Xelide-below
+   *  is at least ASSERTION.
+   *
+   *  @see elidable
+   *  @param p   the expression to test
+   */
+  @elidable(ASSERTION)
   def assert(assertion: Boolean) {
     if (!assertion)
       throw new java.lang.AssertionError("assertion failed")
   }
 
-  def assert(assertion: Boolean, message: Any) {
+  /** Tests an expression, throwing an AssertionError if false.
+   *  Calls to this method will not be generated if -Xelide-below
+   *  is at least ASSERTION.
+   *
+   *  @see elidable
+   *  @param p   the expression to test
+   *  @param msg a String to include in the failure message
+   */
+  @elidable(ASSERTION)
+  def assert(assertion: Boolean, message: => Any) {
     if (!assertion)
       throw new java.lang.AssertionError("assertion failed: "+ message)
   }
 
+  /** Tests an expression, throwing an AssertionError if false.
+   *  This method differs from assert only in the intent expressed:
+   *  assert contains a predicate which needs to be proven, while
+   *  assume contains an axiom for a static checker.  Calls to this method
+   *  will not be generated if -Xelide-below is at least ASSERTION.
+   *
+   *  @see elidable
+   *  @param p   the expression to test
+   */
+  @elidable(ASSERTION)
   def assume(assumption: Boolean) {
     if (!assumption)
       throw new java.lang.AssertionError("assumption failed")
   }
 
-  def assume(assumption: Boolean, message: Any) {
+  /** Tests an expression, throwing an AssertionError if false.
+   *  This method differs from assert only in the intent expressed:
+   *  assert contains a predicate which needs to be proven, while
+   *  assume contains an axiom for a static checker.  Calls to this method
+   *  will not be generated if -Xelide-below is at least ASSERTION.
+   *
+   *  @see elidable
+   *  @param p   the expression to test
+   *  @param msg a String to include in the failure message
+   */
+  @elidable(ASSERTION)
+  def assume(assumption: Boolean, message: => Any) {
     if (!assumption)
       throw new java.lang.AssertionError("assumption failed: "+ message)
   }
 
+  /** Tests an expression, throwing an IllegalArgumentException if false.
+   *  This method is similar to assert, but blames the caller of the method
+   *  for violating the condition.
+   *
+   *  @param p   the expression to test
+   */
   def require(requirement: Boolean) {
     if (!requirement)
       throw new IllegalArgumentException("requirement failed")
   }
 
-  def require(requirement: Boolean, message: Any) {
+  /** Tests an expression, throwing an IllegalArgumentException if false.
+   *  This method is similar to assert, but blames the caller of the method
+   *  for violating the condition.
+   *
+   *  @param p   the expression to test
+   *  @param msg a String to include in the failure message
+   */
+  def require(requirement: Boolean, message: => Any) {
     if (!requirement)
       throw new IllegalArgumentException("requirement failed: "+ message)
   }
+  
+  final class Ensuring[A](val x: A) {
+    def ensuring(cond: Boolean): A = { assert(cond); x }
+    def ensuring(cond: Boolean, msg: Any): A = { assert(cond, msg); x }
+    def ensuring(cond: A => Boolean): A = { assert(cond(x)); x }
+    def ensuring(cond: A => Boolean, msg: Any): A = { assert(cond(x), msg); x }
+  }
+  implicit def any2Ensuring[A](x: A): Ensuring[A] = new Ensuring(x)
 
   // tupling ------------------------------------------------------------
 
@@ -126,37 +167,19 @@ object Predef {
     def unapply[A, B, C](x: Tuple3[A, B, C]): Option[Tuple3[A, B, C]] = Some(x)
   }
 
-  class Ensuring[A](x: A) {
-    def ensuring(cond: Boolean): A = { assert(cond); x }
-    def ensuring(cond: Boolean, msg: Any): A = { assert(cond, msg); x }
-    def ensuring(cond: A => Boolean): A = { assert(cond(x)); x }
-    def ensuring(cond: A => Boolean, msg: Any): A = { assert(cond(x), msg); x }
-  }
-  implicit def any2Ensuring[A](x: A): Ensuring[A] = new Ensuring(x)
-
-  class ArrowAssoc[A](x: A) {
-    def -> [B](y: B): Tuple2[A, B] = Tuple2(x, y)
+  final class ArrowAssoc[A](val x: A) {
+    @inline def -> [B](y: B): Tuple2[A, B] = Tuple2(x, y)
     def →[B](y: B): Tuple2[A, B] = ->(y)
   }
   implicit def any2ArrowAssoc[A](x: A): ArrowAssoc[A] = new ArrowAssoc(x)
 
-  def Tuple[A1](x1: A1) = Tuple1(x1)
-  def Tuple[A1, A2](x1: A1, x2: A2) = Tuple2(x1, x2)
-  def Tuple[A1, A2, A3](x1: A1, x2: A2, x3: A3) = Tuple3(x1, x2, x3)
-  def Tuple[A1, A2, A3, A4](x1: A1, x2: A2, x3: A3, x4: A4) = Tuple4(x1, x2, x3, x4)
-  def Tuple[A1, A2, A3, A4, A5](x1: A1, x2: A2, x3: A3, x4: A4, x5: A5) = Tuple5(x1, x2, x3, x4, x5)
-  def Tuple[A1, A2, A3, A4, A5, A6](x1: A1, x2: A2, x3: A3, x4: A4, x5: A5, x6: A6) = Tuple6(x1, x2, x3, x4, x5, x6)
-  def Tuple[A1, A2, A3, A4, A5, A6, A7](x1: A1, x2: A2, x3: A3, x4: A4, x5: A5, x6: A6, x7: A7) = Tuple7(x1, x2, x3, x4, x5, x6, x7)
-  def Tuple[A1, A2, A3, A4, A5, A6, A7, A8](x1: A1, x2: A2, x3: A3, x4: A4, x5: A5, x6: A6, x7: A7, x8: A8) = Tuple8(x1, x2, x3, x4, x5, x6, x7, x8)
-  def Tuple[A1, A2, A3, A4, A5, A6, A7, A8, A9](x1: A1, x2: A2, x3: A3, x4: A4, x5: A5, x6: A6, x7: A7, x8: A8, x9: A9) = Tuple9(x1, x2, x3, x4, x5, x6, x7, x8, x9)
-
   // printing and reading -----------------------------------------------
 
   def print(x: Any) = Console.print(x)
   def println() = Console.println()
   def println(x: Any) = Console.println(x)
-  def printf(text: String, xs: Any*) = Console.printf(text, xs: _*)
-  def format(text: String, xs: Any*) = Console.format(text, xs: _*)
+  def printf(text: String, xs: Any*) = Console.print(format(text, xs: _*))
+  def format(text: String, xs: Any*) = augmentString(text).format(xs: _*)
 
   def readLine(): String = Console.readLine()
   def readLine(text: String, args: Any*) = Console.readLine(text, args)
@@ -175,125 +198,43 @@ object Predef {
   
   // views --------------------------------------------------------------
 
-  implicit def identity[A](x: A): A = x
-
   implicit def byteWrapper(x: Byte)     = new runtime.RichByte(x)
   implicit def shortWrapper(x: Short)   = new runtime.RichShort(x)
   implicit def intWrapper(x: Int)       = new runtime.RichInt(x)
   implicit def charWrapper(c: Char)     = new runtime.RichChar(c)
   implicit def longWrapper(x: Long)     = new runtime.RichLong(x)
   implicit def floatWrapper(x: Float)   = new runtime.RichFloat(x)
-  implicit def doubleWrapper(x: Double) = new runtime.RichDouble(x)
-
-  implicit def booleanWrapper(x: Boolean)  = new runtime.RichBoolean(x)
-
-  implicit def stringWrapper(x: String) = new runtime.RichString(x)
-  implicit def stringBuilderWrapper(x : StringBuilder): runtime.RichStringBuilder = new runtime.RichStringBuilder(x)
-
-  implicit def any2stringadd(x: Any) = new runtime.StringAdd(x)
+  implicit def doubleWrapper(x: Double) = new runtime.RichDouble(x)  
+  implicit def booleanWrapper(x: Boolean) = new runtime.RichBoolean(x)
 
   implicit def exceptionWrapper(exc: Throwable) = new runtime.RichException(exc)
 
-  implicit def unit2ordered(x: Unit): Ordered[Unit] = new Ordered[Unit] with Proxy {
-    def self: Any = x
-    def compare(y: Unit): Int = 0
+  implicit def genericArrayOps[T](xs: Array[T]): ArrayOps[T] = (xs: AnyRef) match { // !!! drop the AnyRef and get unreachable code errors!
+    case x: Array[AnyRef] => refArrayOps[AnyRef](x).asInstanceOf[ArrayOps[T]]
+    case x: Array[Int] => intArrayOps(x).asInstanceOf[ArrayOps[T]]
+    case x: Array[Double] => doubleArrayOps(x).asInstanceOf[ArrayOps[T]]
+    case x: Array[Long] => longArrayOps(x).asInstanceOf[ArrayOps[T]]
+    case x: Array[Float] => floatArrayOps(x).asInstanceOf[ArrayOps[T]]
+    case x: Array[Char] => charArrayOps(x).asInstanceOf[ArrayOps[T]]
+    case x: Array[Byte] => byteArrayOps(x).asInstanceOf[ArrayOps[T]] 
+    case x: Array[Short] => shortArrayOps(x).asInstanceOf[ArrayOps[T]]
+    case x: Array[Boolean] => booleanArrayOps(x).asInstanceOf[ArrayOps[T]]
+    case x: Array[Unit] => unitArrayOps(x).asInstanceOf[ArrayOps[T]]
+    case null => null
   }
-
-  implicit def iterable2ordered[A <% Ordered[A]](xs: Iterable[A]): Ordered[Iterable[A]] =
-    new Ordered[Iterable[A]] with Proxy {
-      val self = xs
-      def compare(that: Iterable[A]): Int = {
-        var res = 0
-        val these = xs.elements
-        val those = that.elements
-        while (res == 0 && these.hasNext)
-          res = if (those.hasNext) these.next compare those.next else 1
-        if (res == 0) {
-          if (those.hasNext) -1 else 0
-        } else 
-          res
-      }
-    }
-
-  implicit def tuple22ordered[A1 <% Ordered[A1], A2 <% Ordered[A2]](x: Tuple2[A1, A2]): Ordered[Tuple2[A1, A2]] = 
-    new Ordered[Tuple2[A1, A2]] with Proxy {
-      val self = x
-      def compare(y: Tuple2[A1, A2]): Int = {
-        val res = x._1 compare y._1
-        if (res == 0) x._2 compare y._2
-        else res
-      }
-    }
-
-  implicit def tuple32ordered[A1 <% Ordered[A1], A2 <% Ordered[A2], A3 <% Ordered[A3]](x: Tuple3[A1, A2, A3]): Ordered[Tuple3[A1, A2, A3]] = 
-    new Ordered[Tuple3[A1, A2, A3]] with Proxy {
-      val self = x
-      def compare(y: Tuple3[A1, A2, A3]): Int = {
-        val res = x._1 compare y._1
-        if (res == 0) Tuple2(x._2, x._3) compare Tuple2(y._2, y._3)
-        else res
-      }
-    }
-
-  implicit def tuple42ordered[A1 <% Ordered[A1], A2 <% Ordered[A2], A3 <% Ordered[A3], A4 <% Ordered[A4]](x: Tuple4[A1, A2, A3, A4]): Ordered[Tuple4[A1, A2, A3, A4]] = 
-    new Ordered[Tuple4[A1, A2, A3, A4]] with Proxy {
-      val self = x
-      def compare(y: Tuple4[A1, A2, A3, A4]): Int = {
-        val res = x._1 compare y._1
-        if (res == 0) Tuple3(x._2, x._3, x._4) compare Tuple3(y._2, y._3, y._4)
-        else res
-      }
-    }
-
-  implicit def tuple52ordered[A1 <% Ordered[A1], A2 <% Ordered[A2], A3 <% Ordered[A3], A4 <% Ordered[A4], A5 <% Ordered[A5]](x: Tuple5[A1, A2, A3, A4, A5]): Ordered[Tuple5[A1, A2, A3, A4, A5]] = 
-    new Ordered[Tuple5[A1, A2, A3, A4, A5]] with Proxy {
-      val self = x
-      def compare(y: Tuple5[A1, A2, A3, A4, A5]): Int = {
-        val res = x._1 compare y._1
-        if (res == 0) Tuple4(x._2, x._3, x._4, x._5) compare Tuple4(y._2, y._3, y._4, y._5)
-        else res
-      }
-    }
-
-  implicit def tuple62ordered[A1 <% Ordered[A1], A2 <% Ordered[A2], A3 <% Ordered[A3], A4 <% Ordered[A4], A5 <% Ordered[A5], A6 <% Ordered[A6]](x: Tuple6[A1, A2, A3, A4, A5, A6]): Ordered[Tuple6[A1, A2, A3, A4, A5, A6]] = 
-    new Ordered[Tuple6[A1, A2, A3, A4, A5, A6]] with Proxy {
-      val self = x
-      def compare(y: Tuple6[A1, A2, A3, A4, A5, A6]): Int = {
-        val res = x._1 compare y._1
-        if (res == 0) Tuple5(x._2, x._3, x._4, x._5, x._6) compare Tuple5(y._2, y._3, y._4, y._5, y._6)
-        else res
-      }
-    }
-
-  implicit def tuple72ordered[A1 <% Ordered[A1], A2 <% Ordered[A2], A3 <% Ordered[A3], A4 <% Ordered[A4], A5 <% Ordered[A5], A6 <% Ordered[A6], A7 <% Ordered[A7]](x: Tuple7[A1, A2, A3, A4, A5, A6, A7]): Ordered[Tuple7[A1, A2, A3, A4, A5, A6, A7]] = 
-    new Ordered[Tuple7[A1, A2, A3, A4, A5, A6, A7]] with Proxy {
-      val self = x
-      def compare(y: Tuple7[A1, A2, A3, A4, A5, A6, A7]): Int = {
-        val res = x._1 compare y._1
-        if (res == 0) Tuple6(x._2, x._3, x._4, x._5, x._6, x._7) compare Tuple6(y._2, y._3, y._4, y._5, y._6, y._7)
-        else res
-      }
-    }
-
-  implicit def tuple82ordered[A1 <% Ordered[A1], A2 <% Ordered[A2], A3 <% Ordered[A3], A4 <% Ordered[A4], A5 <% Ordered[A5], A6 <% Ordered[A6], A7 <% Ordered[A7], A8 <% Ordered[A8]](x: Tuple8[A1, A2, A3, A4, A5, A6, A7, A8]): Ordered[Tuple8[A1, A2, A3, A4, A5, A6, A7, A8]] = 
-    new Ordered[Tuple8[A1, A2, A3, A4, A5, A6, A7, A8]] with Proxy {
-      val self = x
-      def compare(y: Tuple8[A1, A2, A3, A4, A5, A6, A7, A8]): Int = {
-        val res = x._1 compare y._1
-        if (res == 0) Tuple7(x._2, x._3, x._4, x._5, x._6, x._7, x._8) compare Tuple7(y._2, y._3, y._4, y._5, y._6, y._7, y._8)
-        else res
-      }
-    }
-
-  implicit def tuple92ordered[A1 <% Ordered[A1], A2 <% Ordered[A2], A3 <% Ordered[A3], A4 <% Ordered[A4], A5 <% Ordered[A5], A6 <% Ordered[A6], A7 <% Ordered[A7], A8 <% Ordered[A8], A9 <% Ordered[A9]](x: Tuple9[A1, A2, A3, A4, A5, A6, A7, A8, A9]): Ordered[Tuple9[A1, A2, A3, A4, A5, A6, A7, A8, A9]] = 
-    new Ordered[Tuple9[A1, A2, A3, A4, A5, A6, A7, A8, A9]] with Proxy {
-      val self = x
-      def compare(y: Tuple9[A1, A2, A3, A4, A5, A6, A7, A8, A9]): Int = {
-        val res = x._1 compare y._1
-        if (res == 0) Tuple8(x._2, x._3, x._4, x._5, x._6, x._7, x._8, x._9) compare Tuple8(y._2, y._3, y._4, y._5, y._6, y._7, y._8, y._9)
-        else res
-      }
-    }
+  
+  implicit def refArrayOps[T <: AnyRef](xs: Array[T]): ArrayOps[T] = new ArrayOps.ofRef[T](xs)
+  implicit def intArrayOps(xs: Array[Int]): ArrayOps[Int] = new ArrayOps.ofInt(xs)
+  implicit def doubleArrayOps(xs: Array[Double]): ArrayOps[Double] = new ArrayOps.ofDouble(xs)
+  implicit def longArrayOps(xs: Array[Long]): ArrayOps[Long] = new ArrayOps.ofLong(xs)
+  implicit def floatArrayOps(xs: Array[Float]): ArrayOps[Float] = new ArrayOps.ofFloat(xs)
+  implicit def charArrayOps(xs: Array[Char]): ArrayOps[Char] = new ArrayOps.ofChar(xs)
+  implicit def byteArrayOps(xs: Array[Byte]): ArrayOps[Byte] = new ArrayOps.ofByte(xs)
+  implicit def shortArrayOps(xs: Array[Short]): ArrayOps[Short] = new ArrayOps.ofShort(xs)
+  implicit def booleanArrayOps(xs: Array[Boolean]): ArrayOps[Boolean] = new ArrayOps.ofBoolean(xs)
+  implicit def unitArrayOps(xs: Array[Unit]): ArrayOps[Unit] = new ArrayOps.ofUnit(xs)
+
+  // Primitive Widenings --------------------------------------------------------------
 
   implicit def byte2short(x: Byte): Short = x.toShort
   implicit def byte2int(x: Byte): Int = x.toInt
@@ -319,38 +260,75 @@ object Predef {
   implicit def long2double(x: Long): Double = x.toDouble
 
   implicit def float2double(x: Float): Double = x.toDouble
+  
+  // "Autoboxing" --------------------------------------------------------------  
 
-  /** Should use java.lang.Byte.valueOf(Byte), but only available
-   * in Java 1.5 and above. */
-  implicit def byte2Byte(x: Byte) = new java.lang.Byte(x)
-  /** Should use java.lang.Short.valueOf(Short), but only available
-   * in Java 1.5 and above. */
-  implicit def short2Short(x: Short) = new java.lang.Short(x)
-  /** Should use java.lang.Character.valueOf(Char), but only available
-   * in Java 1.5 and above. */
-  implicit def char2Character(x: Char) = new java.lang.Character(x)
-  /** Should use java.lang.Integer.valueOf(Int), but only available
-   * in Java 1.5 and above. */
-  implicit def int2Integer(x: Int) = new java.lang.Integer(x)
-  /** Should use java.lang.Long.valueOf(Long), but only available
-   * in Java 1.5 and above. */
-  implicit def long2Long(x: Long) = new java.lang.Long(x)
-  implicit def float2Float(x: Float) = new java.lang.Float(x)
-  implicit def double2Double(x: Double) = new java.lang.Double(x)
-  implicit def boolean2Boolean(x: Boolean) = java.lang.Boolean.valueOf(x)
-
-  /** any array projection can be automatically converted into an array */
-  implicit def forceArrayProjection[A](x: Array.Projection[A]): Array[A] = x.force
-  /** any random access character seq (including rich string can be converted into a string */
-  implicit def forceRandomAccessCharSeq(x: runtime.RichString): String = x.mkString
-  implicit def lazyStreamToConsable[A](xs: => Stream[A]) = new runtime.StreamCons(xs)
-
-  implicit def seqToCharSequence(xs: RandomAccessSeq[Char]): CharSequence = new CharSequence {
+  implicit def byte2Byte(x: Byte)           = java.lang.Byte.valueOf(x)
+  implicit def short2Short(x: Short)        = java.lang.Short.valueOf(x)
+  implicit def char2Character(x: Char)      = java.lang.Character.valueOf(x)
+  implicit def int2Integer(x: Int)          = java.lang.Integer.valueOf(x)
+  implicit def long2Long(x: Long)           = java.lang.Long.valueOf(x)
+  implicit def float2Float(x: Float)        = java.lang.Float.valueOf(x)
+  implicit def double2Double(x: Double)     = java.lang.Double.valueOf(x)
+  implicit def boolean2Boolean(x: Boolean)  = java.lang.Boolean.valueOf(x)
+
+  // Strings and CharSequences --------------------------------------------------------------
+
+  implicit def any2stringadd(x: Any) = new runtime.StringAdd(x)
+  implicit def augmentString(x: String): StringOps = new StringOps(x)
+  implicit def unaugmentString(x: StringOps): String = x.repr
+
+  implicit def stringCanBuildFrom: CanBuildFrom[String, Char, String] = 
+    new CanBuildFrom[String, Char, String] { 
+      def apply(from: String) = new scala.collection.mutable.StringBuilder 
+      def apply() = new scala.collection.mutable.StringBuilder 
+    }
+
+  implicit def seqToCharSequence(xs: collection.IndexedSeq[Char]): CharSequence = new CharSequence {
     def length: Int = xs.length
     def charAt(index: Int): Char = xs(index)
     def subSequence(start: Int, end: Int): CharSequence = seqToCharSequence(xs.slice(start, end))
     override def toString: String = xs.mkString("")
   }
 
-  def currentThread = java.lang.Thread.currentThread()
+  implicit def arrayToCharSequence(xs: Array[Char]): CharSequence = new CharSequence {
+    def length: Int = xs.length
+    def charAt(index: Int): Char = xs(index)
+    def subSequence(start: Int, end: Int): CharSequence = arrayToCharSequence(xs.slice(start, end))
+    override def toString: String = xs.mkString("")
+  }
+  
+  // Type Constraints --------------------------------------------------------------
+
+  // used, for example, in the encoding of generalized constraints
+  // we need a new type constructor `<:<` and evidence `conforms`, as 
+  // reusing `Function2` and `identity` leads to ambiguities (any2stringadd is inferred)
+  // to constrain any abstract type T that's in scope in a method's argument list (not just the method's own type parameters)
+  // simply add an implicit argument of type `T <:< U`, where U is the required upper bound (for lower-bounds, use: `U <: T`)
+  // in part contributed by Jason Zaugg
+  sealed abstract class <:<[-From, +To] extends (From => To)
+  implicit def conforms[A]: A <:< A = new (A <:< A) {def apply(x: A) = x} // not in the <:< companion object because it is also intended to subsume identity (which is no longer implicit)
+ 
+  sealed abstract class =:=[From, To] extends (From => To)
+  object =:= {
+    implicit def tpEquals[A]: A =:= A = new (A =:= A) {def apply(x: A) = x}
+  }
+ 
+  sealed abstract class <%<[-From, +To] extends (From => To)
+  object <%< {
+    implicit def conformsOrViewsAs[A <% B, B]: A <%< B = new (A <%< B) {def apply(x: A) = x}
+  }
+ 
+  /** A type for which there is always an implicit value.
+   *  @see fallbackCanBuildFrom in Array.scala
+   */
+  class DummyImplicit
+  
+  object DummyImplicit {
+  
+    /** An implicit value yielding a DummyImplicit.
+     *   @see fallbackCanBuildFrom in Array.scala
+     */
+    implicit def dummyImplicit: DummyImplicit = new DummyImplicit
+  }
 }
diff --git a/src/library/scala/Product.scala b/src/library/scala/Product.scala
index 5c88531..65e5da4 100644
--- a/src/library/scala/Product.scala
+++ b/src/library/scala/Product.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Product.scala 16881 2009-01-09 16:28:11Z cunei $
 
 
 package scala
@@ -16,10 +15,11 @@ package scala
  *
  *  @author  Burak Emir
  *  @version 1.0
+ *  @since   2.3
  */
-trait Product extends AnyRef {
+trait Product extends Equals {
 
-  /** for a product <code>A(x_1,...,x_k)</code>, returns <code>x_(n+1)</code>
+  /** For a product <code>A(x_1,...,x_k)</code>, returns <code>x_(n+1)</code>
    *  for <code>0 <= n < k</code>
    *
    *  @param  n the index of the element to return
@@ -32,11 +32,21 @@ trait Product extends AnyRef {
    */
   def productArity: Int
 
+  /** An iterator that returns all fields of this product */
+  def productIterator: Iterator[Any] = new Iterator[Any] {
+    private var c: Int = 0
+    private val cmax = productArity
+    def hasNext = c < cmax
+    def next() = { val result = productElement(c); c += 1; result }
+  }
+  
+  @deprecated("use productIterator instead")
+  def productElements: Iterator[Any] = productIterator
+
   /** 
    *  By default the empty string. Implementations may override this
    *  method in order to prepend a string prefix to the result of the 
    *  toString methods. 
    */
   def productPrefix = ""
-
 }
diff --git a/src/library/scala/Product1.scala b/src/library/scala/Product1.scala
index 8c232d2..8bd823e 100644
--- a/src/library/scala/Product1.scala
+++ b/src/library/scala/Product1.scala
@@ -1,30 +1,28 @@
-
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Product1.scala 16881 2009-01-09 16:28:11Z cunei $
 
-// generated by genprod on Wed Apr 23 10:06:16 CEST 2008  
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  
 
 package scala
 
-import Predef._
+
 
 object Product1 {
   def unapply[T1](x: Product1[T1]): Option[Product1[T1]] = 
     Some(x)
 }
 
-/** Product1 is a cartesian product of 1 components 
+/** Product1 is a cartesian product of 1 component.
  *  
+ *  @since 2.3
  */
-trait Product1[+T1] extends Product {
-
+trait Product1[@specialized(Int, Long, Double) +T1] extends Product {
   /**
    *  The arity of this product.
    *  @return 1
@@ -40,15 +38,14 @@ trait Product1[+T1] extends Product {
    *  @throws  IndexOutOfBoundsException
    */
   @throws(classOf[IndexOutOfBoundsException])
-  override def productElement(n: Int) = n match {
+  override def productElement(n: Int) = n match { 
     case 0 => _1
     case _ => throw new IndexOutOfBoundsException(n.toString())
-  }
+ }  
 
   /** projection of this product */
   def _1: T1
 
 
 
-  
 }
diff --git a/src/library/scala/Product10.scala b/src/library/scala/Product10.scala
index b598bda..a4faad6 100644
--- a/src/library/scala/Product10.scala
+++ b/src/library/scala/Product10.scala
@@ -1,30 +1,28 @@
-
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Product10.scala 16881 2009-01-09 16:28:11Z cunei $
 
-// generated by genprod on Wed Apr 23 10:06:16 CEST 2008  
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  
 
 package scala
 
-import Predef._
+
 
 object Product10 {
   def unapply[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10](x: Product10[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]): Option[Product10[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]] = 
     Some(x)
 }
 
-/** Product10 is a cartesian product of 10 components 
+/** Product10 is a cartesian product of 10 components.
  *  
+ *  @since 2.3
  */
 trait Product10[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10] extends Product {
-
   /**
    *  The arity of this product.
    *  @return 10
@@ -40,7 +38,7 @@ trait Product10[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10] extends Produ
    *  @throws  IndexOutOfBoundsException
    */
   @throws(classOf[IndexOutOfBoundsException])
-  override def productElement(n: Int) = n match {
+  override def productElement(n: Int) = n match { 
     case 0 => _1
     case 1 => _2
     case 2 => _3
@@ -52,39 +50,38 @@ trait Product10[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10] extends Produ
     case 8 => _9
     case 9 => _10
     case _ => throw new IndexOutOfBoundsException(n.toString())
-  }
+ }  
 
   /** projection of this product */
   def _1: T1
 
-/** projection of this product */
+  /** projection of this product */
   def _2: T2
 
-/** projection of this product */
+  /** projection of this product */
   def _3: T3
 
-/** projection of this product */
+  /** projection of this product */
   def _4: T4
 
-/** projection of this product */
+  /** projection of this product */
   def _5: T5
 
-/** projection of this product */
+  /** projection of this product */
   def _6: T6
 
-/** projection of this product */
+  /** projection of this product */
   def _7: T7
 
-/** projection of this product */
+  /** projection of this product */
   def _8: T8
 
-/** projection of this product */
+  /** projection of this product */
   def _9: T9
 
-/** projection of this product */
+  /** projection of this product */
   def _10: T10
 
 
 
-  
 }
diff --git a/src/library/scala/Product11.scala b/src/library/scala/Product11.scala
index f95ff75..75299c9 100644
--- a/src/library/scala/Product11.scala
+++ b/src/library/scala/Product11.scala
@@ -1,30 +1,28 @@
-
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Product11.scala 16881 2009-01-09 16:28:11Z cunei $
 
-// generated by genprod on Wed Apr 23 10:06:16 CEST 2008  
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  
 
 package scala
 
-import Predef._
+
 
 object Product11 {
   def unapply[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11](x: Product11[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11]): Option[Product11[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11]] = 
     Some(x)
 }
 
-/** Product11 is a cartesian product of 11 components 
+/** Product11 is a cartesian product of 11 components.
  *  
+ *  @since 2.3
  */
 trait Product11[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11] extends Product {
-
   /**
    *  The arity of this product.
    *  @return 11
@@ -40,7 +38,7 @@ trait Product11[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11] extends
    *  @throws  IndexOutOfBoundsException
    */
   @throws(classOf[IndexOutOfBoundsException])
-  override def productElement(n: Int) = n match {
+  override def productElement(n: Int) = n match { 
     case 0 => _1
     case 1 => _2
     case 2 => _3
@@ -53,42 +51,41 @@ trait Product11[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11] extends
     case 9 => _10
     case 10 => _11
     case _ => throw new IndexOutOfBoundsException(n.toString())
-  }
+ }  
 
   /** projection of this product */
   def _1: T1
 
-/** projection of this product */
+  /** projection of this product */
   def _2: T2
 
-/** projection of this product */
+  /** projection of this product */
   def _3: T3
 
-/** projection of this product */
+  /** projection of this product */
   def _4: T4
 
-/** projection of this product */
+  /** projection of this product */
   def _5: T5
 
-/** projection of this product */
+  /** projection of this product */
   def _6: T6
 
-/** projection of this product */
+  /** projection of this product */
   def _7: T7
 
-/** projection of this product */
+  /** projection of this product */
   def _8: T8
 
-/** projection of this product */
+  /** projection of this product */
   def _9: T9
 
-/** projection of this product */
+  /** projection of this product */
   def _10: T10
 
-/** projection of this product */
+  /** projection of this product */
   def _11: T11
 
 
 
-  
 }
diff --git a/src/library/scala/Product12.scala b/src/library/scala/Product12.scala
index 2092f9e..958764c 100644
--- a/src/library/scala/Product12.scala
+++ b/src/library/scala/Product12.scala
@@ -1,30 +1,28 @@
-
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Product12.scala 16881 2009-01-09 16:28:11Z cunei $
 
-// generated by genprod on Wed Apr 23 10:06:16 CEST 2008  
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  
 
 package scala
 
-import Predef._
+
 
 object Product12 {
   def unapply[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12](x: Product12[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12]): Option[Product12[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12]] = 
     Some(x)
 }
 
-/** Product12 is a cartesian product of 12 components 
+/** Product12 is a cartesian product of 12 components.
  *  
+ *  @since 2.3
  */
 trait Product12[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12] extends Product {
-
   /**
    *  The arity of this product.
    *  @return 12
@@ -40,7 +38,7 @@ trait Product12[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12] e
    *  @throws  IndexOutOfBoundsException
    */
   @throws(classOf[IndexOutOfBoundsException])
-  override def productElement(n: Int) = n match {
+  override def productElement(n: Int) = n match { 
     case 0 => _1
     case 1 => _2
     case 2 => _3
@@ -54,45 +52,44 @@ trait Product12[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12] e
     case 10 => _11
     case 11 => _12
     case _ => throw new IndexOutOfBoundsException(n.toString())
-  }
+ }  
 
   /** projection of this product */
   def _1: T1
 
-/** projection of this product */
+  /** projection of this product */
   def _2: T2
 
-/** projection of this product */
+  /** projection of this product */
   def _3: T3
 
-/** projection of this product */
+  /** projection of this product */
   def _4: T4
 
-/** projection of this product */
+  /** projection of this product */
   def _5: T5
 
-/** projection of this product */
+  /** projection of this product */
   def _6: T6
 
-/** projection of this product */
+  /** projection of this product */
   def _7: T7
 
-/** projection of this product */
+  /** projection of this product */
   def _8: T8
 
-/** projection of this product */
+  /** projection of this product */
   def _9: T9
 
-/** projection of this product */
+  /** projection of this product */
   def _10: T10
 
-/** projection of this product */
+  /** projection of this product */
   def _11: T11
 
-/** projection of this product */
+  /** projection of this product */
   def _12: T12
 
 
 
-  
 }
diff --git a/src/library/scala/Product13.scala b/src/library/scala/Product13.scala
index 91bc539..7cbafa5 100644
--- a/src/library/scala/Product13.scala
+++ b/src/library/scala/Product13.scala
@@ -1,30 +1,28 @@
-
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Product13.scala 16881 2009-01-09 16:28:11Z cunei $
 
-// generated by genprod on Wed Apr 23 10:06:16 CEST 2008  
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  
 
 package scala
 
-import Predef._
+
 
 object Product13 {
   def unapply[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13](x: Product13[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13]): Option[Product13[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13]] = 
     Some(x)
 }
 
-/** Product13 is a cartesian product of 13 components 
+/** Product13 is a cartesian product of 13 components.
  *  
+ *  @since 2.3
  */
 trait Product13[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +T13] extends Product {
-
   /**
    *  The arity of this product.
    *  @return 13
@@ -40,7 +38,7 @@ trait Product13[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +
    *  @throws  IndexOutOfBoundsException
    */
   @throws(classOf[IndexOutOfBoundsException])
-  override def productElement(n: Int) = n match {
+  override def productElement(n: Int) = n match { 
     case 0 => _1
     case 1 => _2
     case 2 => _3
@@ -55,48 +53,47 @@ trait Product13[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +
     case 11 => _12
     case 12 => _13
     case _ => throw new IndexOutOfBoundsException(n.toString())
-  }
+ }  
 
   /** projection of this product */
   def _1: T1
 
-/** projection of this product */
+  /** projection of this product */
   def _2: T2
 
-/** projection of this product */
+  /** projection of this product */
   def _3: T3
 
-/** projection of this product */
+  /** projection of this product */
   def _4: T4
 
-/** projection of this product */
+  /** projection of this product */
   def _5: T5
 
-/** projection of this product */
+  /** projection of this product */
   def _6: T6
 
-/** projection of this product */
+  /** projection of this product */
   def _7: T7
 
-/** projection of this product */
+  /** projection of this product */
   def _8: T8
 
-/** projection of this product */
+  /** projection of this product */
   def _9: T9
 
-/** projection of this product */
+  /** projection of this product */
   def _10: T10
 
-/** projection of this product */
+  /** projection of this product */
   def _11: T11
 
-/** projection of this product */
+  /** projection of this product */
   def _12: T12
 
-/** projection of this product */
+  /** projection of this product */
   def _13: T13
 
 
 
-  
 }
diff --git a/src/library/scala/Product14.scala b/src/library/scala/Product14.scala
index 3175ac6..5afe324 100644
--- a/src/library/scala/Product14.scala
+++ b/src/library/scala/Product14.scala
@@ -1,30 +1,28 @@
-
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Product14.scala 16881 2009-01-09 16:28:11Z cunei $
 
-// generated by genprod on Wed Apr 23 10:06:16 CEST 2008  
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  
 
 package scala
 
-import Predef._
+
 
 object Product14 {
   def unapply[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14](x: Product14[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14]): Option[Product14[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14]] = 
     Some(x)
 }
 
-/** Product14 is a cartesian product of 14 components 
+/** Product14 is a cartesian product of 14 components.
  *  
+ *  @since 2.3
  */
 trait Product14[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +T13, +T14] extends Product {
-
   /**
    *  The arity of this product.
    *  @return 14
@@ -40,7 +38,7 @@ trait Product14[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +
    *  @throws  IndexOutOfBoundsException
    */
   @throws(classOf[IndexOutOfBoundsException])
-  override def productElement(n: Int) = n match {
+  override def productElement(n: Int) = n match { 
     case 0 => _1
     case 1 => _2
     case 2 => _3
@@ -56,51 +54,50 @@ trait Product14[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +
     case 12 => _13
     case 13 => _14
     case _ => throw new IndexOutOfBoundsException(n.toString())
-  }
+ }  
 
   /** projection of this product */
   def _1: T1
 
-/** projection of this product */
+  /** projection of this product */
   def _2: T2
 
-/** projection of this product */
+  /** projection of this product */
   def _3: T3
 
-/** projection of this product */
+  /** projection of this product */
   def _4: T4
 
-/** projection of this product */
+  /** projection of this product */
   def _5: T5
 
-/** projection of this product */
+  /** projection of this product */
   def _6: T6
 
-/** projection of this product */
+  /** projection of this product */
   def _7: T7
 
-/** projection of this product */
+  /** projection of this product */
   def _8: T8
 
-/** projection of this product */
+  /** projection of this product */
   def _9: T9
 
-/** projection of this product */
+  /** projection of this product */
   def _10: T10
 
-/** projection of this product */
+  /** projection of this product */
   def _11: T11
 
-/** projection of this product */
+  /** projection of this product */
   def _12: T12
 
-/** projection of this product */
+  /** projection of this product */
   def _13: T13
 
-/** projection of this product */
+  /** projection of this product */
   def _14: T14
 
 
 
-  
 }
diff --git a/src/library/scala/Product15.scala b/src/library/scala/Product15.scala
index 58b3c9c..a3f986b 100644
--- a/src/library/scala/Product15.scala
+++ b/src/library/scala/Product15.scala
@@ -1,30 +1,28 @@
-
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Product15.scala 16881 2009-01-09 16:28:11Z cunei $
 
-// generated by genprod on Wed Apr 23 10:06:16 CEST 2008  
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  
 
 package scala
 
-import Predef._
+
 
 object Product15 {
   def unapply[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15](x: Product15[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15]): Option[Product15[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15]] = 
     Some(x)
 }
 
-/** Product15 is a cartesian product of 15 components 
+/** Product15 is a cartesian product of 15 components.
  *  
+ *  @since 2.3
  */
 trait Product15[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +T13, +T14, +T15] extends Product {
-
   /**
    *  The arity of this product.
    *  @return 15
@@ -40,7 +38,7 @@ trait Product15[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +
    *  @throws  IndexOutOfBoundsException
    */
   @throws(classOf[IndexOutOfBoundsException])
-  override def productElement(n: Int) = n match {
+  override def productElement(n: Int) = n match { 
     case 0 => _1
     case 1 => _2
     case 2 => _3
@@ -57,54 +55,53 @@ trait Product15[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +
     case 13 => _14
     case 14 => _15
     case _ => throw new IndexOutOfBoundsException(n.toString())
-  }
+ }  
 
   /** projection of this product */
   def _1: T1
 
-/** projection of this product */
+  /** projection of this product */
   def _2: T2
 
-/** projection of this product */
+  /** projection of this product */
   def _3: T3
 
-/** projection of this product */
+  /** projection of this product */
   def _4: T4
 
-/** projection of this product */
+  /** projection of this product */
   def _5: T5
 
-/** projection of this product */
+  /** projection of this product */
   def _6: T6
 
-/** projection of this product */
+  /** projection of this product */
   def _7: T7
 
-/** projection of this product */
+  /** projection of this product */
   def _8: T8
 
-/** projection of this product */
+  /** projection of this product */
   def _9: T9
 
-/** projection of this product */
+  /** projection of this product */
   def _10: T10
 
-/** projection of this product */
+  /** projection of this product */
   def _11: T11
 
-/** projection of this product */
+  /** projection of this product */
   def _12: T12
 
-/** projection of this product */
+  /** projection of this product */
   def _13: T13
 
-/** projection of this product */
+  /** projection of this product */
   def _14: T14
 
-/** projection of this product */
+  /** projection of this product */
   def _15: T15
 
 
 
-  
 }
diff --git a/src/library/scala/Product16.scala b/src/library/scala/Product16.scala
index 91b1589..f2eb843 100644
--- a/src/library/scala/Product16.scala
+++ b/src/library/scala/Product16.scala
@@ -1,30 +1,28 @@
-
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Product16.scala 16881 2009-01-09 16:28:11Z cunei $
 
-// generated by genprod on Wed Apr 23 10:06:16 CEST 2008  
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  
 
 package scala
 
-import Predef._
+
 
 object Product16 {
   def unapply[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16](x: Product16[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16]): Option[Product16[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16]] = 
     Some(x)
 }
 
-/** Product16 is a cartesian product of 16 components 
+/** Product16 is a cartesian product of 16 components.
  *  
+ *  @since 2.3
  */
 trait Product16[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +T13, +T14, +T15, +T16] extends Product {
-
   /**
    *  The arity of this product.
    *  @return 16
@@ -40,7 +38,7 @@ trait Product16[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +
    *  @throws  IndexOutOfBoundsException
    */
   @throws(classOf[IndexOutOfBoundsException])
-  override def productElement(n: Int) = n match {
+  override def productElement(n: Int) = n match { 
     case 0 => _1
     case 1 => _2
     case 2 => _3
@@ -58,57 +56,56 @@ trait Product16[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +
     case 14 => _15
     case 15 => _16
     case _ => throw new IndexOutOfBoundsException(n.toString())
-  }
+ }  
 
   /** projection of this product */
   def _1: T1
 
-/** projection of this product */
+  /** projection of this product */
   def _2: T2
 
-/** projection of this product */
+  /** projection of this product */
   def _3: T3
 
-/** projection of this product */
+  /** projection of this product */
   def _4: T4
 
-/** projection of this product */
+  /** projection of this product */
   def _5: T5
 
-/** projection of this product */
+  /** projection of this product */
   def _6: T6
 
-/** projection of this product */
+  /** projection of this product */
   def _7: T7
 
-/** projection of this product */
+  /** projection of this product */
   def _8: T8
 
-/** projection of this product */
+  /** projection of this product */
   def _9: T9
 
-/** projection of this product */
+  /** projection of this product */
   def _10: T10
 
-/** projection of this product */
+  /** projection of this product */
   def _11: T11
 
-/** projection of this product */
+  /** projection of this product */
   def _12: T12
 
-/** projection of this product */
+  /** projection of this product */
   def _13: T13
 
-/** projection of this product */
+  /** projection of this product */
   def _14: T14
 
-/** projection of this product */
+  /** projection of this product */
   def _15: T15
 
-/** projection of this product */
+  /** projection of this product */
   def _16: T16
 
 
 
-  
 }
diff --git a/src/library/scala/Product17.scala b/src/library/scala/Product17.scala
index ec6b1db..2ba037e 100644
--- a/src/library/scala/Product17.scala
+++ b/src/library/scala/Product17.scala
@@ -1,30 +1,28 @@
-
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Product17.scala 16881 2009-01-09 16:28:11Z cunei $
 
-// generated by genprod on Wed Apr 23 10:06:16 CEST 2008  
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  
 
 package scala
 
-import Predef._
+
 
 object Product17 {
   def unapply[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17](x: Product17[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17]): Option[Product17[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17]] = 
     Some(x)
 }
 
-/** Product17 is a cartesian product of 17 components 
+/** Product17 is a cartesian product of 17 components.
  *  
+ *  @since 2.3
  */
 trait Product17[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +T13, +T14, +T15, +T16, +T17] extends Product {
-
   /**
    *  The arity of this product.
    *  @return 17
@@ -40,7 +38,7 @@ trait Product17[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +
    *  @throws  IndexOutOfBoundsException
    */
   @throws(classOf[IndexOutOfBoundsException])
-  override def productElement(n: Int) = n match {
+  override def productElement(n: Int) = n match { 
     case 0 => _1
     case 1 => _2
     case 2 => _3
@@ -59,60 +57,59 @@ trait Product17[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +
     case 15 => _16
     case 16 => _17
     case _ => throw new IndexOutOfBoundsException(n.toString())
-  }
+ }  
 
   /** projection of this product */
   def _1: T1
 
-/** projection of this product */
+  /** projection of this product */
   def _2: T2
 
-/** projection of this product */
+  /** projection of this product */
   def _3: T3
 
-/** projection of this product */
+  /** projection of this product */
   def _4: T4
 
-/** projection of this product */
+  /** projection of this product */
   def _5: T5
 
-/** projection of this product */
+  /** projection of this product */
   def _6: T6
 
-/** projection of this product */
+  /** projection of this product */
   def _7: T7
 
-/** projection of this product */
+  /** projection of this product */
   def _8: T8
 
-/** projection of this product */
+  /** projection of this product */
   def _9: T9
 
-/** projection of this product */
+  /** projection of this product */
   def _10: T10
 
-/** projection of this product */
+  /** projection of this product */
   def _11: T11
 
-/** projection of this product */
+  /** projection of this product */
   def _12: T12
 
-/** projection of this product */
+  /** projection of this product */
   def _13: T13
 
-/** projection of this product */
+  /** projection of this product */
   def _14: T14
 
-/** projection of this product */
+  /** projection of this product */
   def _15: T15
 
-/** projection of this product */
+  /** projection of this product */
   def _16: T16
 
-/** projection of this product */
+  /** projection of this product */
   def _17: T17
 
 
 
-  
 }
diff --git a/src/library/scala/Product18.scala b/src/library/scala/Product18.scala
index 879b30f..5282a3f 100644
--- a/src/library/scala/Product18.scala
+++ b/src/library/scala/Product18.scala
@@ -1,30 +1,28 @@
-
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Product18.scala 16881 2009-01-09 16:28:11Z cunei $
 
-// generated by genprod on Wed Apr 23 10:06:16 CEST 2008  
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  
 
 package scala
 
-import Predef._
+
 
 object Product18 {
   def unapply[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18](x: Product18[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18]): Option[Product18[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18]] = 
     Some(x)
 }
 
-/** Product18 is a cartesian product of 18 components 
+/** Product18 is a cartesian product of 18 components.
  *  
+ *  @since 2.3
  */
 trait Product18[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +T13, +T14, +T15, +T16, +T17, +T18] extends Product {
-
   /**
    *  The arity of this product.
    *  @return 18
@@ -40,7 +38,7 @@ trait Product18[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +
    *  @throws  IndexOutOfBoundsException
    */
   @throws(classOf[IndexOutOfBoundsException])
-  override def productElement(n: Int) = n match {
+  override def productElement(n: Int) = n match { 
     case 0 => _1
     case 1 => _2
     case 2 => _3
@@ -60,63 +58,62 @@ trait Product18[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +
     case 16 => _17
     case 17 => _18
     case _ => throw new IndexOutOfBoundsException(n.toString())
-  }
+ }  
 
   /** projection of this product */
   def _1: T1
 
-/** projection of this product */
+  /** projection of this product */
   def _2: T2
 
-/** projection of this product */
+  /** projection of this product */
   def _3: T3
 
-/** projection of this product */
+  /** projection of this product */
   def _4: T4
 
-/** projection of this product */
+  /** projection of this product */
   def _5: T5
 
-/** projection of this product */
+  /** projection of this product */
   def _6: T6
 
-/** projection of this product */
+  /** projection of this product */
   def _7: T7
 
-/** projection of this product */
+  /** projection of this product */
   def _8: T8
 
-/** projection of this product */
+  /** projection of this product */
   def _9: T9
 
-/** projection of this product */
+  /** projection of this product */
   def _10: T10
 
-/** projection of this product */
+  /** projection of this product */
   def _11: T11
 
-/** projection of this product */
+  /** projection of this product */
   def _12: T12
 
-/** projection of this product */
+  /** projection of this product */
   def _13: T13
 
-/** projection of this product */
+  /** projection of this product */
   def _14: T14
 
-/** projection of this product */
+  /** projection of this product */
   def _15: T15
 
-/** projection of this product */
+  /** projection of this product */
   def _16: T16
 
-/** projection of this product */
+  /** projection of this product */
   def _17: T17
 
-/** projection of this product */
+  /** projection of this product */
   def _18: T18
 
 
 
-  
 }
diff --git a/src/library/scala/Product19.scala b/src/library/scala/Product19.scala
index 83e321e..f0df79a 100644
--- a/src/library/scala/Product19.scala
+++ b/src/library/scala/Product19.scala
@@ -1,30 +1,28 @@
-
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Product19.scala 16881 2009-01-09 16:28:11Z cunei $
 
-// generated by genprod on Wed Apr 23 10:06:16 CEST 2008  
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  
 
 package scala
 
-import Predef._
+
 
 object Product19 {
   def unapply[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19](x: Product19[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19]): Option[Product19[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19]] = 
     Some(x)
 }
 
-/** Product19 is a cartesian product of 19 components 
+/** Product19 is a cartesian product of 19 components.
  *  
+ *  @since 2.3
  */
 trait Product19[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +T13, +T14, +T15, +T16, +T17, +T18, +T19] extends Product {
-
   /**
    *  The arity of this product.
    *  @return 19
@@ -40,7 +38,7 @@ trait Product19[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +
    *  @throws  IndexOutOfBoundsException
    */
   @throws(classOf[IndexOutOfBoundsException])
-  override def productElement(n: Int) = n match {
+  override def productElement(n: Int) = n match { 
     case 0 => _1
     case 1 => _2
     case 2 => _3
@@ -61,66 +59,65 @@ trait Product19[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +
     case 17 => _18
     case 18 => _19
     case _ => throw new IndexOutOfBoundsException(n.toString())
-  }
+ }  
 
   /** projection of this product */
   def _1: T1
 
-/** projection of this product */
+  /** projection of this product */
   def _2: T2
 
-/** projection of this product */
+  /** projection of this product */
   def _3: T3
 
-/** projection of this product */
+  /** projection of this product */
   def _4: T4
 
-/** projection of this product */
+  /** projection of this product */
   def _5: T5
 
-/** projection of this product */
+  /** projection of this product */
   def _6: T6
 
-/** projection of this product */
+  /** projection of this product */
   def _7: T7
 
-/** projection of this product */
+  /** projection of this product */
   def _8: T8
 
-/** projection of this product */
+  /** projection of this product */
   def _9: T9
 
-/** projection of this product */
+  /** projection of this product */
   def _10: T10
 
-/** projection of this product */
+  /** projection of this product */
   def _11: T11
 
-/** projection of this product */
+  /** projection of this product */
   def _12: T12
 
-/** projection of this product */
+  /** projection of this product */
   def _13: T13
 
-/** projection of this product */
+  /** projection of this product */
   def _14: T14
 
-/** projection of this product */
+  /** projection of this product */
   def _15: T15
 
-/** projection of this product */
+  /** projection of this product */
   def _16: T16
 
-/** projection of this product */
+  /** projection of this product */
   def _17: T17
 
-/** projection of this product */
+  /** projection of this product */
   def _18: T18
 
-/** projection of this product */
+  /** projection of this product */
   def _19: T19
 
 
 
-  
 }
diff --git a/src/library/scala/Product2.scala b/src/library/scala/Product2.scala
index dc35f5f..3d449f0 100644
--- a/src/library/scala/Product2.scala
+++ b/src/library/scala/Product2.scala
@@ -1,30 +1,28 @@
-
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Product2.scala 16881 2009-01-09 16:28:11Z cunei $
 
-// generated by genprod on Wed Apr 23 10:06:16 CEST 2008  
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  
 
 package scala
 
-import Predef._
+
 
 object Product2 {
   def unapply[T1, T2](x: Product2[T1, T2]): Option[Product2[T1, T2]] = 
     Some(x)
 }
 
-/** Product2 is a cartesian product of 2 components 
+/** Product2 is a cartesian product of 2 components.
  *  
+ *  @since 2.3
  */
-trait Product2[+T1, +T2] extends Product {
-
+trait Product2[@specialized(Int, Long, Double) +T1, @specialized(Int, Long, Double) +T2] extends Product {
   /**
    *  The arity of this product.
    *  @return 2
@@ -40,19 +38,18 @@ trait Product2[+T1, +T2] extends Product {
    *  @throws  IndexOutOfBoundsException
    */
   @throws(classOf[IndexOutOfBoundsException])
-  override def productElement(n: Int) = n match {
+  override def productElement(n: Int) = n match { 
     case 0 => _1
     case 1 => _2
     case _ => throw new IndexOutOfBoundsException(n.toString())
-  }
+ }  
 
   /** projection of this product */
   def _1: T1
 
-/** projection of this product */
+  /** projection of this product */
   def _2: T2
 
 
 
-  
 }
diff --git a/src/library/scala/Product20.scala b/src/library/scala/Product20.scala
index cb4518e..3bd399b 100644
--- a/src/library/scala/Product20.scala
+++ b/src/library/scala/Product20.scala
@@ -1,30 +1,28 @@
-
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Product20.scala 16881 2009-01-09 16:28:11Z cunei $
 
-// generated by genprod on Wed Apr 23 10:06:16 CEST 2008  
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  
 
 package scala
 
-import Predef._
+
 
 object Product20 {
   def unapply[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20](x: Product20[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20]): Option[Product20[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20]] = 
     Some(x)
 }
 
-/** Product20 is a cartesian product of 20 components 
+/** Product20 is a cartesian product of 20 components.
  *  
+ *  @since 2.3
  */
 trait Product20[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +T13, +T14, +T15, +T16, +T17, +T18, +T19, +T20] extends Product {
-
   /**
    *  The arity of this product.
    *  @return 20
@@ -40,7 +38,7 @@ trait Product20[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +
    *  @throws  IndexOutOfBoundsException
    */
   @throws(classOf[IndexOutOfBoundsException])
-  override def productElement(n: Int) = n match {
+  override def productElement(n: Int) = n match { 
     case 0 => _1
     case 1 => _2
     case 2 => _3
@@ -62,69 +60,68 @@ trait Product20[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +
     case 18 => _19
     case 19 => _20
     case _ => throw new IndexOutOfBoundsException(n.toString())
-  }
+ }  
 
   /** projection of this product */
   def _1: T1
 
-/** projection of this product */
+  /** projection of this product */
   def _2: T2
 
-/** projection of this product */
+  /** projection of this product */
   def _3: T3
 
-/** projection of this product */
+  /** projection of this product */
   def _4: T4
 
-/** projection of this product */
+  /** projection of this product */
   def _5: T5
 
-/** projection of this product */
+  /** projection of this product */
   def _6: T6
 
-/** projection of this product */
+  /** projection of this product */
   def _7: T7
 
-/** projection of this product */
+  /** projection of this product */
   def _8: T8
 
-/** projection of this product */
+  /** projection of this product */
   def _9: T9
 
-/** projection of this product */
+  /** projection of this product */
   def _10: T10
 
-/** projection of this product */
+  /** projection of this product */
   def _11: T11
 
-/** projection of this product */
+  /** projection of this product */
   def _12: T12
 
-/** projection of this product */
+  /** projection of this product */
   def _13: T13
 
-/** projection of this product */
+  /** projection of this product */
   def _14: T14
 
-/** projection of this product */
+  /** projection of this product */
   def _15: T15
 
-/** projection of this product */
+  /** projection of this product */
   def _16: T16
 
-/** projection of this product */
+  /** projection of this product */
   def _17: T17
 
-/** projection of this product */
+  /** projection of this product */
   def _18: T18
 
-/** projection of this product */
+  /** projection of this product */
   def _19: T19
 
-/** projection of this product */
+  /** projection of this product */
   def _20: T20
 
 
 
-  
 }
diff --git a/src/library/scala/Product21.scala b/src/library/scala/Product21.scala
index 19bcf45..45aeed8 100644
--- a/src/library/scala/Product21.scala
+++ b/src/library/scala/Product21.scala
@@ -1,30 +1,28 @@
-
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Product21.scala 16881 2009-01-09 16:28:11Z cunei $
 
-// generated by genprod on Wed Apr 23 10:06:16 CEST 2008  
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  
 
 package scala
 
-import Predef._
+
 
 object Product21 {
   def unapply[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21](x: Product21[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21]): Option[Product21[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21]] = 
     Some(x)
 }
 
-/** Product21 is a cartesian product of 21 components 
+/** Product21 is a cartesian product of 21 components.
  *  
+ *  @since 2.3
  */
 trait Product21[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +T13, +T14, +T15, +T16, +T17, +T18, +T19, +T20, +T21] extends Product {
-
   /**
    *  The arity of this product.
    *  @return 21
@@ -40,7 +38,7 @@ trait Product21[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +
    *  @throws  IndexOutOfBoundsException
    */
   @throws(classOf[IndexOutOfBoundsException])
-  override def productElement(n: Int) = n match {
+  override def productElement(n: Int) = n match { 
     case 0 => _1
     case 1 => _2
     case 2 => _3
@@ -63,72 +61,71 @@ trait Product21[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +
     case 19 => _20
     case 20 => _21
     case _ => throw new IndexOutOfBoundsException(n.toString())
-  }
+ }  
 
   /** projection of this product */
   def _1: T1
 
-/** projection of this product */
+  /** projection of this product */
   def _2: T2
 
-/** projection of this product */
+  /** projection of this product */
   def _3: T3
 
-/** projection of this product */
+  /** projection of this product */
   def _4: T4
 
-/** projection of this product */
+  /** projection of this product */
   def _5: T5
 
-/** projection of this product */
+  /** projection of this product */
   def _6: T6
 
-/** projection of this product */
+  /** projection of this product */
   def _7: T7
 
-/** projection of this product */
+  /** projection of this product */
   def _8: T8
 
-/** projection of this product */
+  /** projection of this product */
   def _9: T9
 
-/** projection of this product */
+  /** projection of this product */
   def _10: T10
 
-/** projection of this product */
+  /** projection of this product */
   def _11: T11
 
-/** projection of this product */
+  /** projection of this product */
   def _12: T12
 
-/** projection of this product */
+  /** projection of this product */
   def _13: T13
 
-/** projection of this product */
+  /** projection of this product */
   def _14: T14
 
-/** projection of this product */
+  /** projection of this product */
   def _15: T15
 
-/** projection of this product */
+  /** projection of this product */
   def _16: T16
 
-/** projection of this product */
+  /** projection of this product */
   def _17: T17
 
-/** projection of this product */
+  /** projection of this product */
   def _18: T18
 
-/** projection of this product */
+  /** projection of this product */
   def _19: T19
 
-/** projection of this product */
+  /** projection of this product */
   def _20: T20
 
-/** projection of this product */
+  /** projection of this product */
   def _21: T21
 
 
 
-  
 }
diff --git a/src/library/scala/Product22.scala b/src/library/scala/Product22.scala
index 2bb0cb7..8d09306 100644
--- a/src/library/scala/Product22.scala
+++ b/src/library/scala/Product22.scala
@@ -1,30 +1,28 @@
-
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Product22.scala 16881 2009-01-09 16:28:11Z cunei $
 
-// generated by genprod on Wed Apr 23 10:06:16 CEST 2008  
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  
 
 package scala
 
-import Predef._
+
 
 object Product22 {
   def unapply[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22](x: Product22[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22]): Option[Product22[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22]] = 
     Some(x)
 }
 
-/** Product22 is a cartesian product of 22 components 
+/** Product22 is a cartesian product of 22 components.
  *  
+ *  @since 2.3
  */
 trait Product22[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +T13, +T14, +T15, +T16, +T17, +T18, +T19, +T20, +T21, +T22] extends Product {
-
   /**
    *  The arity of this product.
    *  @return 22
@@ -40,7 +38,7 @@ trait Product22[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +
    *  @throws  IndexOutOfBoundsException
    */
   @throws(classOf[IndexOutOfBoundsException])
-  override def productElement(n: Int) = n match {
+  override def productElement(n: Int) = n match { 
     case 0 => _1
     case 1 => _2
     case 2 => _3
@@ -64,75 +62,74 @@ trait Product22[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +
     case 20 => _21
     case 21 => _22
     case _ => throw new IndexOutOfBoundsException(n.toString())
-  }
+ }  
 
   /** projection of this product */
   def _1: T1
 
-/** projection of this product */
+  /** projection of this product */
   def _2: T2
 
-/** projection of this product */
+  /** projection of this product */
   def _3: T3
 
-/** projection of this product */
+  /** projection of this product */
   def _4: T4
 
-/** projection of this product */
+  /** projection of this product */
   def _5: T5
 
-/** projection of this product */
+  /** projection of this product */
   def _6: T6
 
-/** projection of this product */
+  /** projection of this product */
   def _7: T7
 
-/** projection of this product */
+  /** projection of this product */
   def _8: T8
 
-/** projection of this product */
+  /** projection of this product */
   def _9: T9
 
-/** projection of this product */
+  /** projection of this product */
   def _10: T10
 
-/** projection of this product */
+  /** projection of this product */
   def _11: T11
 
-/** projection of this product */
+  /** projection of this product */
   def _12: T12
 
-/** projection of this product */
+  /** projection of this product */
   def _13: T13
 
-/** projection of this product */
+  /** projection of this product */
   def _14: T14
 
-/** projection of this product */
+  /** projection of this product */
   def _15: T15
 
-/** projection of this product */
+  /** projection of this product */
   def _16: T16
 
-/** projection of this product */
+  /** projection of this product */
   def _17: T17
 
-/** projection of this product */
+  /** projection of this product */
   def _18: T18
 
-/** projection of this product */
+  /** projection of this product */
   def _19: T19
 
-/** projection of this product */
+  /** projection of this product */
   def _20: T20
 
-/** projection of this product */
+  /** projection of this product */
   def _21: T21
 
-/** projection of this product */
+  /** projection of this product */
   def _22: T22
 
 
 
-  
 }
diff --git a/src/library/scala/Product3.scala b/src/library/scala/Product3.scala
index 74a20a9..32e9686 100644
--- a/src/library/scala/Product3.scala
+++ b/src/library/scala/Product3.scala
@@ -1,30 +1,28 @@
-
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Product3.scala 16881 2009-01-09 16:28:11Z cunei $
 
-// generated by genprod on Wed Apr 23 10:06:16 CEST 2008  
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  
 
 package scala
 
-import Predef._
+
 
 object Product3 {
   def unapply[T1, T2, T3](x: Product3[T1, T2, T3]): Option[Product3[T1, T2, T3]] = 
     Some(x)
 }
 
-/** Product3 is a cartesian product of 3 components 
+/** Product3 is a cartesian product of 3 components.
  *  
+ *  @since 2.3
  */
 trait Product3[+T1, +T2, +T3] extends Product {
-
   /**
    *  The arity of this product.
    *  @return 3
@@ -40,23 +38,22 @@ trait Product3[+T1, +T2, +T3] extends Product {
    *  @throws  IndexOutOfBoundsException
    */
   @throws(classOf[IndexOutOfBoundsException])
-  override def productElement(n: Int) = n match {
+  override def productElement(n: Int) = n match { 
     case 0 => _1
     case 1 => _2
     case 2 => _3
     case _ => throw new IndexOutOfBoundsException(n.toString())
-  }
+ }  
 
   /** projection of this product */
   def _1: T1
 
-/** projection of this product */
+  /** projection of this product */
   def _2: T2
 
-/** projection of this product */
+  /** projection of this product */
   def _3: T3
 
 
 
-  
 }
diff --git a/src/library/scala/Product4.scala b/src/library/scala/Product4.scala
index cc03d03..c34298c 100644
--- a/src/library/scala/Product4.scala
+++ b/src/library/scala/Product4.scala
@@ -1,30 +1,28 @@
-
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Product4.scala 16881 2009-01-09 16:28:11Z cunei $
 
-// generated by genprod on Wed Apr 23 10:06:16 CEST 2008  
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  
 
 package scala
 
-import Predef._
+
 
 object Product4 {
   def unapply[T1, T2, T3, T4](x: Product4[T1, T2, T3, T4]): Option[Product4[T1, T2, T3, T4]] = 
     Some(x)
 }
 
-/** Product4 is a cartesian product of 4 components 
+/** Product4 is a cartesian product of 4 components.
  *  
+ *  @since 2.3
  */
 trait Product4[+T1, +T2, +T3, +T4] extends Product {
-
   /**
    *  The arity of this product.
    *  @return 4
@@ -40,27 +38,26 @@ trait Product4[+T1, +T2, +T3, +T4] extends Product {
    *  @throws  IndexOutOfBoundsException
    */
   @throws(classOf[IndexOutOfBoundsException])
-  override def productElement(n: Int) = n match {
+  override def productElement(n: Int) = n match { 
     case 0 => _1
     case 1 => _2
     case 2 => _3
     case 3 => _4
     case _ => throw new IndexOutOfBoundsException(n.toString())
-  }
+ }  
 
   /** projection of this product */
   def _1: T1
 
-/** projection of this product */
+  /** projection of this product */
   def _2: T2
 
-/** projection of this product */
+  /** projection of this product */
   def _3: T3
 
-/** projection of this product */
+  /** projection of this product */
   def _4: T4
 
 
 
-  
 }
diff --git a/src/library/scala/Product5.scala b/src/library/scala/Product5.scala
index 5562032..719b2f7 100644
--- a/src/library/scala/Product5.scala
+++ b/src/library/scala/Product5.scala
@@ -1,30 +1,28 @@
-
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Product5.scala 16881 2009-01-09 16:28:11Z cunei $
 
-// generated by genprod on Wed Apr 23 10:06:16 CEST 2008  
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  
 
 package scala
 
-import Predef._
+
 
 object Product5 {
   def unapply[T1, T2, T3, T4, T5](x: Product5[T1, T2, T3, T4, T5]): Option[Product5[T1, T2, T3, T4, T5]] = 
     Some(x)
 }
 
-/** Product5 is a cartesian product of 5 components 
+/** Product5 is a cartesian product of 5 components.
  *  
+ *  @since 2.3
  */
 trait Product5[+T1, +T2, +T3, +T4, +T5] extends Product {
-
   /**
    *  The arity of this product.
    *  @return 5
@@ -40,31 +38,30 @@ trait Product5[+T1, +T2, +T3, +T4, +T5] extends Product {
    *  @throws  IndexOutOfBoundsException
    */
   @throws(classOf[IndexOutOfBoundsException])
-  override def productElement(n: Int) = n match {
+  override def productElement(n: Int) = n match { 
     case 0 => _1
     case 1 => _2
     case 2 => _3
     case 3 => _4
     case 4 => _5
     case _ => throw new IndexOutOfBoundsException(n.toString())
-  }
+ }  
 
   /** projection of this product */
   def _1: T1
 
-/** projection of this product */
+  /** projection of this product */
   def _2: T2
 
-/** projection of this product */
+  /** projection of this product */
   def _3: T3
 
-/** projection of this product */
+  /** projection of this product */
   def _4: T4
 
-/** projection of this product */
+  /** projection of this product */
   def _5: T5
 
 
 
-  
 }
diff --git a/src/library/scala/Product6.scala b/src/library/scala/Product6.scala
index fec2311..e3c0b60 100644
--- a/src/library/scala/Product6.scala
+++ b/src/library/scala/Product6.scala
@@ -1,30 +1,28 @@
-
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Product6.scala 16881 2009-01-09 16:28:11Z cunei $
 
-// generated by genprod on Wed Apr 23 10:06:16 CEST 2008  
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  
 
 package scala
 
-import Predef._
+
 
 object Product6 {
   def unapply[T1, T2, T3, T4, T5, T6](x: Product6[T1, T2, T3, T4, T5, T6]): Option[Product6[T1, T2, T3, T4, T5, T6]] = 
     Some(x)
 }
 
-/** Product6 is a cartesian product of 6 components 
+/** Product6 is a cartesian product of 6 components.
  *  
+ *  @since 2.3
  */
 trait Product6[+T1, +T2, +T3, +T4, +T5, +T6] extends Product {
-
   /**
    *  The arity of this product.
    *  @return 6
@@ -40,7 +38,7 @@ trait Product6[+T1, +T2, +T3, +T4, +T5, +T6] extends Product {
    *  @throws  IndexOutOfBoundsException
    */
   @throws(classOf[IndexOutOfBoundsException])
-  override def productElement(n: Int) = n match {
+  override def productElement(n: Int) = n match { 
     case 0 => _1
     case 1 => _2
     case 2 => _3
@@ -48,27 +46,26 @@ trait Product6[+T1, +T2, +T3, +T4, +T5, +T6] extends Product {
     case 4 => _5
     case 5 => _6
     case _ => throw new IndexOutOfBoundsException(n.toString())
-  }
+ }  
 
   /** projection of this product */
   def _1: T1
 
-/** projection of this product */
+  /** projection of this product */
   def _2: T2
 
-/** projection of this product */
+  /** projection of this product */
   def _3: T3
 
-/** projection of this product */
+  /** projection of this product */
   def _4: T4
 
-/** projection of this product */
+  /** projection of this product */
   def _5: T5
 
-/** projection of this product */
+  /** projection of this product */
   def _6: T6
 
 
 
-  
 }
diff --git a/src/library/scala/Product7.scala b/src/library/scala/Product7.scala
index 814c127..bae771d 100644
--- a/src/library/scala/Product7.scala
+++ b/src/library/scala/Product7.scala
@@ -1,30 +1,28 @@
-
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Product7.scala 16881 2009-01-09 16:28:11Z cunei $
 
-// generated by genprod on Wed Apr 23 10:06:16 CEST 2008  
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  
 
 package scala
 
-import Predef._
+
 
 object Product7 {
   def unapply[T1, T2, T3, T4, T5, T6, T7](x: Product7[T1, T2, T3, T4, T5, T6, T7]): Option[Product7[T1, T2, T3, T4, T5, T6, T7]] = 
     Some(x)
 }
 
-/** Product7 is a cartesian product of 7 components 
+/** Product7 is a cartesian product of 7 components.
  *  
+ *  @since 2.3
  */
 trait Product7[+T1, +T2, +T3, +T4, +T5, +T6, +T7] extends Product {
-
   /**
    *  The arity of this product.
    *  @return 7
@@ -40,7 +38,7 @@ trait Product7[+T1, +T2, +T3, +T4, +T5, +T6, +T7] extends Product {
    *  @throws  IndexOutOfBoundsException
    */
   @throws(classOf[IndexOutOfBoundsException])
-  override def productElement(n: Int) = n match {
+  override def productElement(n: Int) = n match { 
     case 0 => _1
     case 1 => _2
     case 2 => _3
@@ -49,30 +47,29 @@ trait Product7[+T1, +T2, +T3, +T4, +T5, +T6, +T7] extends Product {
     case 5 => _6
     case 6 => _7
     case _ => throw new IndexOutOfBoundsException(n.toString())
-  }
+ }  
 
   /** projection of this product */
   def _1: T1
 
-/** projection of this product */
+  /** projection of this product */
   def _2: T2
 
-/** projection of this product */
+  /** projection of this product */
   def _3: T3
 
-/** projection of this product */
+  /** projection of this product */
   def _4: T4
 
-/** projection of this product */
+  /** projection of this product */
   def _5: T5
 
-/** projection of this product */
+  /** projection of this product */
   def _6: T6
 
-/** projection of this product */
+  /** projection of this product */
   def _7: T7
 
 
 
-  
 }
diff --git a/src/library/scala/Product8.scala b/src/library/scala/Product8.scala
index 3525dd1..5c8ea0c 100644
--- a/src/library/scala/Product8.scala
+++ b/src/library/scala/Product8.scala
@@ -1,30 +1,28 @@
-
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Product8.scala 16881 2009-01-09 16:28:11Z cunei $
 
-// generated by genprod on Wed Apr 23 10:06:16 CEST 2008  
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  
 
 package scala
 
-import Predef._
+
 
 object Product8 {
   def unapply[T1, T2, T3, T4, T5, T6, T7, T8](x: Product8[T1, T2, T3, T4, T5, T6, T7, T8]): Option[Product8[T1, T2, T3, T4, T5, T6, T7, T8]] = 
     Some(x)
 }
 
-/** Product8 is a cartesian product of 8 components 
+/** Product8 is a cartesian product of 8 components.
  *  
+ *  @since 2.3
  */
 trait Product8[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8] extends Product {
-
   /**
    *  The arity of this product.
    *  @return 8
@@ -40,7 +38,7 @@ trait Product8[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8] extends Product {
    *  @throws  IndexOutOfBoundsException
    */
   @throws(classOf[IndexOutOfBoundsException])
-  override def productElement(n: Int) = n match {
+  override def productElement(n: Int) = n match { 
     case 0 => _1
     case 1 => _2
     case 2 => _3
@@ -50,33 +48,32 @@ trait Product8[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8] extends Product {
     case 6 => _7
     case 7 => _8
     case _ => throw new IndexOutOfBoundsException(n.toString())
-  }
+ }  
 
   /** projection of this product */
   def _1: T1
 
-/** projection of this product */
+  /** projection of this product */
   def _2: T2
 
-/** projection of this product */
+  /** projection of this product */
   def _3: T3
 
-/** projection of this product */
+  /** projection of this product */
   def _4: T4
 
-/** projection of this product */
+  /** projection of this product */
   def _5: T5
 
-/** projection of this product */
+  /** projection of this product */
   def _6: T6
 
-/** projection of this product */
+  /** projection of this product */
   def _7: T7
 
-/** projection of this product */
+  /** projection of this product */
   def _8: T8
 
 
 
-  
 }
diff --git a/src/library/scala/Product9.scala b/src/library/scala/Product9.scala
index 6c2166f..2c49656 100644
--- a/src/library/scala/Product9.scala
+++ b/src/library/scala/Product9.scala
@@ -1,30 +1,28 @@
-
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Product9.scala 16881 2009-01-09 16:28:11Z cunei $
 
-// generated by genprod on Wed Apr 23 10:06:16 CEST 2008  
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  
 
 package scala
 
-import Predef._
+
 
 object Product9 {
   def unapply[T1, T2, T3, T4, T5, T6, T7, T8, T9](x: Product9[T1, T2, T3, T4, T5, T6, T7, T8, T9]): Option[Product9[T1, T2, T3, T4, T5, T6, T7, T8, T9]] = 
     Some(x)
 }
 
-/** Product9 is a cartesian product of 9 components 
+/** Product9 is a cartesian product of 9 components.
  *  
+ *  @since 2.3
  */
 trait Product9[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9] extends Product {
-
   /**
    *  The arity of this product.
    *  @return 9
@@ -40,7 +38,7 @@ trait Product9[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9] extends Product {
    *  @throws  IndexOutOfBoundsException
    */
   @throws(classOf[IndexOutOfBoundsException])
-  override def productElement(n: Int) = n match {
+  override def productElement(n: Int) = n match { 
     case 0 => _1
     case 1 => _2
     case 2 => _3
@@ -51,36 +49,35 @@ trait Product9[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9] extends Product {
     case 7 => _8
     case 8 => _9
     case _ => throw new IndexOutOfBoundsException(n.toString())
-  }
+ }  
 
   /** projection of this product */
   def _1: T1
 
-/** projection of this product */
+  /** projection of this product */
   def _2: T2
 
-/** projection of this product */
+  /** projection of this product */
   def _3: T3
 
-/** projection of this product */
+  /** projection of this product */
   def _4: T4
 
-/** projection of this product */
+  /** projection of this product */
   def _5: T5
 
-/** projection of this product */
+  /** projection of this product */
   def _6: T6
 
-/** projection of this product */
+  /** projection of this product */
   def _7: T7
 
-/** projection of this product */
+  /** projection of this product */
   def _8: T8
 
-/** projection of this product */
+  /** projection of this product */
   def _9: T9
 
 
 
-  
 }
diff --git a/src/library/scala/Proxy.scala b/src/library/scala/Proxy.scala
index ffa9a93..9d275e8 100644
--- a/src/library/scala/Proxy.scala
+++ b/src/library/scala/Proxy.scala
@@ -1,19 +1,16 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://www.scala-lang.org/           **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Proxy.scala 16881 2009-01-09 16:28:11Z cunei $
 
 
 package scala
 
 
-import Predef._
-
 /** This class implements a simple proxy that forwards all calls to
  *  methods of class <code>Any</code> to another object <code>self</code>.
  *  Please note that only those methods can be forwarded that are
@@ -24,10 +21,9 @@ import Predef._
  */
 trait Proxy {
   def self: Any
-  override def hashCode: Int = self.hashCode
-  override def equals(that: Any): Boolean = that match {
-    case that: Proxy => self equals that.self
-    case that        => false
-  }
+  override def hashCode: Int = self.##
+  override def equals(that: Any): Boolean = 
+    if(that == null) false 
+    else that equals self
   override def toString: String = self.toString
 }
diff --git a/src/library/scala/Random.scala b/src/library/scala/Random.scala
deleted file mode 100644
index 87d0254..0000000
--- a/src/library/scala/Random.scala
+++ /dev/null
@@ -1,75 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: Random.scala 16881 2009-01-09 16:28:11Z cunei $
-
-
-package scala
-
-/**
- *  @author Stephane Micheloud
- *
- *  @deprecated Use class <code>scala.util.Random</code> instead.
- */
- at deprecated
-class Random(val self: java.util.Random) {
-
-  /** Creates a new random number generator using a single long seed. */
-  def this(seed: Long) = this(new java.util.Random(seed))
-
-  /** Creates a new random number generator using a single integer seed. */
-  def this(seed: Int) = this(seed.toLong)
-
-  /** Creates a new random number generator. */
-  def this() = this(compat.Platform.currentTime)
-
-  /** Returns the next pseudorandom, uniformly distributed boolean value
-   *  from this random number generator's sequence.
-   */
-  def nextBoolean(): Boolean = self.nextBoolean()
-
-  /** Generates random bytes and places them into a user-supplied byte
-   *  array.
-   */
-  def nextBytes(bytes: Array[Byte]) { self.nextBytes(bytes) }
-
-  /** Returns the next pseudorandom, uniformly distributed double value
-   *  between 0.0 and 1.0 from this random number generator's sequence.
-   */
-  def nextDouble(): Double = self.nextDouble()
-
-  /** Returns the next pseudorandom, uniformly distributed float value
-   *  between 0.0 and 1.0 from this random number generator's sequence.
-   */
-  def nextFloat(): Float = self.nextFloat()
-
-  /** Returns the next pseudorandom, Gaussian ("normally") distributed
-   *  double value with mean 0.0 and standard deviation 1.0 from this
-   *  random number generator's sequence.
-   */
-  //def nextGaussian(): Double = self.nextGaussian()
-
-  /** Returns the next pseudorandom, uniformly distributed int value
-   *  from this random number generator's sequence.
-   */
-  def nextInt(): Int = self.nextInt()
-
-  /** Returns a pseudorandom, uniformly distributed int value between 0
-   *  (inclusive) and the specified value (exclusive), drawn from this
-   *  random number generator's sequence.
-   */
-  def nextInt(n: Int): Int = self.nextInt(n)
-
-  /** Returns the next pseudorandom, uniformly distributed long value
-   *  from this random number generator's sequence.
-   */
-  def nextLong(): Long = self.nextLong()
-
-  def setSeed(seed: Long) { self.setSeed(seed) }
- 
-}
diff --git a/src/library/scala/RandomAccessSeq.scala b/src/library/scala/RandomAccessSeq.scala
deleted file mode 100644
index 1791b0b..0000000
--- a/src/library/scala/RandomAccessSeq.scala
+++ /dev/null
@@ -1,245 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: RandomAccessSeq.scala 16881 2009-01-09 16:28:11Z cunei $
-
-package scala
-
-import collection.mutable.ArrayBuffer
-
-object RandomAccessSeq {
-  
-  /** Create read only sequence of specified elements */
-  def apply[A](xs: A*): RandomAccessSeq[A] =
-    if (xs.isEmpty) empty
-    else {
-      val buffer = new ArrayBuffer[A]
-      xs copyToBuffer buffer
-      buffer.readOnly
-    }
-  
-  /** The empty sequence */
-  val empty : RandomAccessSeq[Nothing] = new RandomAccessSeq.Projection[Nothing] {
-    def length = 0
-    def apply(i: Int): Nothing = throw new NoSuchElementException("empty sequence")
-    override def elements = Iterator.empty
-    override def projection = this
-    override def force = this
-  }
-
-  trait Projection[+A] extends Seq.Projection[A] with RandomAccessSeq[A] {
-    override def projection = this
-    override def force : RandomAccessSeq[A] = toArray
-    protected class MapProjection[B](f : A => B) extends super.MapProjection(f) with Projection[B]
-    override def map[B](f: A => B) : Projection[B] = new MapProjection[B](f)
-    override def append[B >: A](that: => Iterable[B]): Projection[B] = {
-      val that0 : Seq[B] = that match {
-      case that : Seq.Projection[b] => that
-      case that : Seq[b] => that
-      case that => that.toList
-      }
-      new Projection[B] {
-        def length = Projection.this.length + that0.length
-        def apply(idx : Int) = 
-          if (idx < Projection.this.length) Projection.this(idx)
-          else that0(idx - Projection.this.length)
-      }        
-    }
-  }
-  private[scala] trait Slice[+A] extends Projection[A] {
-    protected def from  : Int
-    protected def until : Int
-    protected def underlying : RandomAccessSeq[A]
-    def length = {
-      val length0 = underlying.length
-      if (from >= until || from >= length0) 0
-      else (if (until >= length0) length0 else until) - (if (from < 0) 0 else from)
-    }
-    def apply(idx : Int) = if (idx < 0 || idx >= length) throw new Predef.IndexOutOfBoundsException
-                           else underlying.apply((if (from < 0) 0 else from) + idx)
-    override def slice(from0 : Int, until0 : Int) = {
-      val from = if (this.from < 0) 0 else this.from
-      underlying.slice(from + from0, from + until0)  
-    }
-  }
-  private[scala] trait Patch[+A] extends Projection[A] {
-    protected def original : RandomAccessSeq[A]
-    protected def patch : RandomAccessSeq[A]
-    protected def from : Int
-    protected def replaced : Int
-    def length = original.length + patch.length - replaced
-    def apply(idx : Int) = 
-      if (idx < from) original.apply(idx)
-      else if (idx < from + patch.length) patch.apply(idx - from)
-      else original.apply(idx - patch.length + replaced)
-    override def stringPrefix = "patch"
-  }
-  
-  /** A random access sequence that supports update (e.g., an array) */
-  trait Mutable[A] extends RandomAccessSeq[A] {
-    /** <p>
-     *    Update the element at given index. 
-     *  </p>
-     *  <p>
-     *    Indices start a <code>0</code>; <code>xs.apply(0)</code> is the first 
-     *    element of mutable sequence <code>xs</code>.
-     *  </p>
-     *  <p>
-     *    Note the indexing syntax <code>xs(i) = x</code> is a shorthand 
-     *    for <code>xs.update(i, x)</code>.
-     *  </p>
-     *
-     *  @param i   the index
-     *  @param x   the value to be written at index <code>i</code>
-     *  @throws ArrayIndexOutOfBoundsException if <code>i < 0</code> or
-     *          <code>length <= i</code>
-     */
-    def update(idx : Int, what : A) : Unit
-    override def projection : MutableProjection[A] = new MutableProjection[A] {
-      override def force : Mutable[A] = Mutable.this
-      def update(idx : Int, what : A) : Unit = Mutable.this.update(idx, what)
-      def length = Mutable.this.length
-      def apply(idx : Int) = Mutable.this.apply(idx)
-    }
-    def readOnly : RandomAccessSeq[A] = new RandomAccessSeq[A] {
-      def length = Mutable.this.length
-      def apply(idx : Int) = Mutable.this.apply(idx)
-      override def stringPrefix = Mutable.this.stringPrefix + "RO"
-    }
-    override def drop( from: Int): MutableProjection[A] = slice(from, length)
-    override def take(until: Int): MutableProjection[A] = slice(0, until)
-    override def slice(from0: Int, until0: Int) : MutableProjection[A] = new MutableSlice[A] {
-      def from = from0
-      def until = until0
-      def underlying = Mutable.this
-    }
-    override def reverse : MutableProjection[A] = new MutableProjection[A] {
-      def update(idx: Int, what: A) { Mutable.this.update(length - idx - 1, what) }
-      def length = Mutable.this.length
-      def apply(idx: Int) = Mutable.this.apply(length - idx - 1)
-      override def stringPrefix = Mutable.this.stringPrefix + "R"
-      override def reverse: MutableProjection[A] = Mutable.this.projection
-    }
-  }
-  trait MutableProjection[A] extends Projection[A] with Mutable[A] {
-    override def force : Mutable[A] = toArray
-    override def projection : MutableProjection[A] = this
-  }
-  private[scala] trait MutableSlice[A] extends MutableProjection[A] with Slice[A] {
-    protected def underlying : Mutable[A]
-    override def slice(from0 : Int, until0 : Int) = {
-      val from = (if (this.from < 0) 0 else this.from)
-      underlying.slice(from + from0, from + until0)  
-    }
-    override def update(idx : Int, what : A) : Unit = {
-      val from = (if (this.from < 0) 0 else this.from)
-      if (idx < 0 || idx >= length) throw new Predef.IndexOutOfBoundsException
-      else underlying.update(from + idx, what)
-    }
-  }
-}
-
-/** Sequences that support O(1) element access and O(1) length computation.
- *  @author Sean McDirmid
- */
-trait RandomAccessSeq[+A] extends Seq[A] {
-  override def projection : RandomAccessSeq.Projection[A] = new RandomAccessSeq.Projection[A] {
-    def length = RandomAccessSeq.this.length
-    def apply(idx : Int) = RandomAccessSeq.this.apply(idx)
-    override def elements = RandomAccessSeq.this.elements
-    override def stringPrefix = RandomAccessSeq.this.stringPrefix + "P"
-  }
-  override def elements : Iterator[A] = new BufferedIterator.Advanced[A] {
-    var idx = 0
-    override def peekList(sz : Int) = new RandomAccessSeq[A] {
-      override def length = RandomAccessSeq.this.length - idx
-      override def apply(jdx : Int) = RandomAccessSeq.this.apply(jdx + idx)
-    }
-    override def hasNext = idx < RandomAccessSeq.this.length
-    def next = {
-      if (!hasNext) throw new Predef.NoSuchElementException
-      val ret = RandomAccessSeq.this.apply(idx)
-      idx += 1
-      ret
-    }
-  }
-  override def drop( from: Int): RandomAccessSeq[A] = slice(from, length)
-  override def take(until: Int): RandomAccessSeq[A] = slice(0, until)
-  override def slice(from0 : Int, until0 : Int) : RandomAccessSeq[A] = new RandomAccessSeq.Slice[A] {
-    def from = from0
-    def until = until0
-    def underlying = RandomAccessSeq.this
-  }
-  override def reverse : Seq[A] = new RandomAccessSeq.Projection[A] {
-    def length = RandomAccessSeq.this.length
-    def apply(idx : Int) = RandomAccessSeq.this.apply(length - idx - 1)
-    override def stringPrefix = RandomAccessSeq.this.stringPrefix + "R"
-    override def reverse : RandomAccessSeq.Projection[A] = RandomAccessSeq.this.projection
-  }
-  
-  /** Partitions this random access sequence in two random access
-   *  sequences according to a predicate.
-   *
-   *  @param p the predicate on which to partition
-   *  @return  a pair of random access sequences: the sequence of all elements
-   *           that satisfy the predicate <code>p</code> and the sequence of
-   *           all elements that do not.
-   *           The relative order of the elements in the resulting sequences
-   *           is the same as in the original sequence.
-   */
-  override def partition(p: A => Boolean): (RandomAccessSeq[A], RandomAccessSeq[A]) = {
-    val matched = new ArrayBuffer[A]
-    val failed = new ArrayBuffer[A]
-    val elems = elements
-    while (elems.hasNext) { val x = elems.next; if (p(x)) matched += x else failed += x }
-    (matched, failed)
-  }
-  
-  /** insert segment <code>patch</code> into this sequence at <code>from</code>  
-   *  replacing  <code>replaced</code> elements. The result is a projection.
-   */
-  def patch[B >: A](from0: Int, patch0: RandomAccessSeq[B], replaced0: Int): RandomAccessSeq.Projection[B] = new RandomAccessSeq.Patch[B] {
-    override def original = RandomAccessSeq.this
-    override def from = from0
-    override def patch = patch0
-    override def replaced = replaced0
-    override def stringPrefix = RandomAccessSeq.this.stringPrefix + "P"
-  }
-  
-  override def ++[B >: A](that: Iterable[B]): RandomAccessSeq[B] = that match {
-    case that: RandomAccessSeq[b] => 
-      val ret = new Array[B](length + that.length)
-      copyToArray(ret, 0)
-      (that : RandomAccessSeq[B]).copyToArray(ret, length)
-      ret
-    case that => 
-      val buf = new scala.collection.mutable.ArrayBuffer[B]
-      this copyToBuffer buf
-      that copyToBuffer buf
-      buf.readOnly
-  }
-  
-  override def toStream : Stream[A] = new Stream.Definite[A] {
-    override def isEmpty = RandomAccessSeq.this.isEmpty
-    override def head = RandomAccessSeq.this.apply(0)
-    override def tail = RandomAccessSeq.this.drop(1).toStream
-    protected def addDefinedElems(buf: StringBuilder, prefix: String): StringBuilder = {
-      var prefix0 = prefix
-      var buf0 = buf
-      elements.foreach{e =>
-        buf0 = buf0.append(prefix0).append(e)
-        prefix0 = ", "
-      }
-      buf0
-    }
-  }
-  
-  /** will return false if index is out of bounds */
-  final def safeIs(idx : Int, a : Any) = if (idx >= 0 && idx < length) this(idx) == a else false
-  
-}
diff --git a/src/library/scala/RandomAccessSeqProxy.scala b/src/library/scala/RandomAccessSeqProxy.scala
deleted file mode 100644
index 5c6d18c..0000000
--- a/src/library/scala/RandomAccessSeqProxy.scala
+++ /dev/null
@@ -1,37 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: RandomAccessSeqProxy.scala 16881 2009-01-09 16:28:11Z cunei $
-
-
-package scala
-
-/** This class implements a proxy for random access sequences. It forwards
- *  all calls to a different sequence object.
- *
- *  @author  Stepan Koltsov
- *  @version 1.0, 27/06/2008
- */
-trait RandomAccessSeqProxy[+A] extends RandomAccessSeq[A] with SeqProxy[A] {
-  override def self: RandomAccessSeq[A]
-  
-  override def projection = self.projection
-  
-  override def drop(from: Int): RandomAccessSeq[A] = self.drop(from)
-  override def take(until: Int): RandomAccessSeq[A] = self.take(until)
-  override def slice(from: Int, until: Int) : RandomAccessSeq[A] = self.slice(from, until)
-  override def reverse = self.reverse
-  override def partition(p: A => Boolean): (RandomAccessSeq[A], RandomAccessSeq[A]) =
-    self.partition(p)
-  override def patch[B >: A](from0: Int, patch0: RandomAccessSeq[B], replaced0: Int) =
-    self.patch(from0, patch0, replaced0)
-  override def ++[B >: A](that: Iterable[B]): RandomAccessSeq[B] = self ++ that
-  override def toStream: Stream[A] = self.toStream
-}
-
-// vim: set ts=2 sw=2 et:
diff --git a/src/library/scala/Range.scala b/src/library/scala/Range.scala
deleted file mode 100644
index b929125..0000000
--- a/src/library/scala/Range.scala
+++ /dev/null
@@ -1,109 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: Range.scala 16881 2009-01-09 16:28:11Z cunei $
-
-
-package scala
-
-import Predef._
-
-/** <p>
- *    The <code>Range</code> class represents integer values in range
- *    <code>[start;end)</code> with non-zero step value <code>step</code>.
- *    Sort of acts like a sequence also (supports length and contains).
- *    For example:
- *  </p><pre>
- *     <b>val</b> r1 = 0 until 10
- *     <b>val</b> r2 = r1.start until r1.end by r1.step + 1
- *     println(r2.length) // = 5
- *  </pre>
- *
- *  @author  Stephane Micheloud
- *  @version 1.0, 01/05/2007
- */
-class Range(val start: Int, val end: Int, val step: Int) extends RandomAccessSeq.Projection[Int] {
-  if (step == 0) throw new Predef.IllegalArgumentException
-
-  /** Create a new range with the start and end values of this range and
-   *  a new <code>step</code>.
-   */
-  def by(step: Int): Range = new Range(start, end, step)
-
-  override def foreach(f: Int => Unit) {
-    if (step > 0) {
-      var i = this.start
-      val until = if (inInterval(end)) end + 1 else end
-
-      while (i < until) {
-        f(i)
-        i += step
-      }
-    } else {
-      var i = this.start
-      val until = if (inInterval(end)) end - 1 else end
-
-      while (i > until) {
-        f(i)
-        i += step
-      }
-    }
-  }
-
-  lazy val length: Int = {
-    if (start < end && this.step < 0) 0
-    else if (start > end && this.step > 0) 0
-    else {
-      val base = if (start < end) end - start
-                 else start - end
-      assert(base >= 0)
-      val step = if (this.step < 0) -this.step else this.step
-      assert(step >= 0)
-      base / step + last(base, step)
-    }
-  }
-
-  protected def last(base: Int, step: Int): Int =
-    if (base % step != 0) 1 else 0
-
-  def apply(idx: Int): Int = {
-    if (idx < 0 || idx >= length) throw new Predef.IndexOutOfBoundsException
-    start + (step * idx)
-  }
-
-  /** a <code>Seq.contains</code>, not a <code>Iterator.contains</code>! */
-  def contains(x: Int): Boolean = {
-    inInterval(x) && (((x - start) % step) == 0)
-  }
-
-  /** Is the argument inside the interval defined by `start' and `end'? 
-   *  Returns true if `x' is inside [start, end).
-   */
-  protected def inInterval(x: Int): Boolean =
-    if (step > 0) 
-      (x >= start && x < end) 
-    else 
-      (x <= start && x > end)
-
-  def inclusive = new Range.Inclusive(start,end,step)
-}
-
-object Range {
-  class Inclusive(start: Int, end: Int, step: Int) extends Range(start, end, step) {
-    override def apply(idx: Int): Int = super.apply(idx)
-    override protected def last(base: Int, step: Int): Int = 1
-    override def by(step: Int): Range = new Inclusive(start, end, step)
-
-    /** Returns true if x is inside the interval [start, end]. */ 
-    override protected def inInterval(x: Int) =
-      if (step > 0) 
-        (x >= start && x <= end) 
-      else 
-        (x <= start && x >= end)
-  }
-}
diff --git a/src/library/scala/Responder.scala b/src/library/scala/Responder.scala
index 7d994de..5d2f27c 100644
--- a/src/library/scala/Responder.scala
+++ b/src/library/scala/Responder.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2005-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2005-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Responder.scala 16894 2009-01-13 13:09:41Z cunei $
 
 package scala
 
@@ -17,6 +16,7 @@ package scala
  *  @version 1.0
  *
  *  @see class Responder
+ *  @since 2.1
  */
 object Responder {
 
@@ -64,7 +64,9 @@ object Responder {
  *  @author Martin Odersky
  *  @author Burak Emir
  *  @version 1.0
+ *  @since 2.1
  */
+ at serializable
 abstract class Responder[+A] {
 
   def respond(k: A => Unit): Unit
@@ -88,5 +90,7 @@ abstract class Responder[+A] {
       Responder.this.respond(x => if (p(x)) k(x) else ())
     }
   }
+
+  override def toString = "Responder"
 }
 
diff --git a/src/library/scala/ScalaObject.scala b/src/library/scala/ScalaObject.scala
index 399f81f..fe67787 100644
--- a/src/library/scala/ScalaObject.scala
+++ b/src/library/scala/ScalaObject.scala
@@ -1,24 +1,13 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: ScalaObject.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala
 
-import Predef._
-
-trait ScalaObject extends AnyRef {
-
-  /** This method is needed for optimizing pattern matching expressions
-   *  which match on constructors of case classes.
-   */
-  @remote
-  def $tag(): Int = 0
-
-}
+trait ScalaObject extends java.lang.Object
diff --git a/src/library/scala/Seq.scala b/src/library/scala/Seq.scala
deleted file mode 100644
index 9cc9980..0000000
--- a/src/library/scala/Seq.scala
+++ /dev/null
@@ -1,511 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: Seq.scala 17137 2009-02-17 20:09:49Z rytz $
-
-
-package scala
-
-import Predef._
-import collection.mutable.ArrayBuffer
-
-object Seq {
-
-  /** The empty sequence */
-  val empty : Seq[Nothing] = RandomAccessSeq.empty
-
-  /** This method is called in a pattern match { case Seq(...) => }.
-   *
-   *  @param x the selector value
-   *  @return  sequence wrapped in an option, if this is a Seq, otherwise none
-   */
-  def unapplySeq[A](x: Seq[A]): Some[Seq[A]] = Some(x)
-  
-  /** Create read only sequence of specified elements */
-  def apply[A](xs: A*): Seq[A] = RandomAccessSeq(xs: _*)
-  
-  case class singleton[A](value: A) extends RandomAccessSeq[A] {
-    override def length = 1
-    override def isDefinedAt(idx: Int): Boolean = idx == 0
-    override def apply(idx: Int) = idx match {
-      case 0 => value
-      case _ => throw new Predef.IndexOutOfBoundsException
-    }
-  }
-
-  /** Builds a singleton sequence.
-   *
-   * @deprecated use <code>singleton</code> instead.
-   */
-  @deprecated def single[A](x: A) = singleton(x)
-
-  trait Projection[+A] extends Seq[A] with Iterable.Projection[A]  {
-    override def projection = this
-    override def force : Seq[A] = toList
-
-    override def map[B](f: A => B) : Projection[B] = new MapProjection(f)
-    protected class MapProjection[B](f : A => B) extends Projection[B] {
-      def length = Projection.this.length
-      def elements = Projection.this.elements.map(f)
-      def apply(idx : Int) = f(Projection.this.apply(idx))
-      override def stringPrefix = Projection.this.stringPrefix + "M"
-    }
-    override def flatMap[B](f: A => Iterable[B]): Projection[B] = new Projection[B] {
-      override def stringPrefix = Projection.this.stringPrefix + "G"
-      def elements = Projection.this.elements.flatMap(a => f(a).elements)
-      def length = {
-        var sz = 0
-        Projection.this.foreach(a => sz = sz + f(a).asInstanceOf[Collection[B]].size)
-        sz
-      }
-      def apply(idx : Int) : B = {
-        var jdx = 0
-        Projection.this.foreach(a => {
-          val i = f(a)
-          val length = i.asInstanceOf[Collection[B]].size
-          if (idx < jdx + length) {
-            val j = i.elements
-            while (jdx < idx) {
-              j.next; jdx += 1
-            }
-            return j.next
-          } else jdx += length
-        })
-        throw new IndexOutOfBoundsException
-      }
-    }
-    override def append[B >: A](that: => Iterable[B]): Projection[B] = that match {
-      case that: Seq[b] => new Projection[B] {
-          def length = Projection.this.length + that.length
-          def elements : Iterator[B] = Projection.this.elements ++ (that.elements:Iterator[B])
-          def apply(idx : Int) = 
-            if (idx < Projection.this.length) Projection.this(idx)
-            else that(idx - Projection.this.length)
-        }
-      case that =>
-        (this ++ that).projection // sucks but no other option.
-    }
-
-    protected abstract class ComputeSize[B] extends Projection[B] {
-      def apply(idx: Int): B = {
-        var sz = 0
-        val i = elements
-        while (i.hasNext) {
-          val ret = i.next
-          if (sz == idx) return ret
-          sz += 1
-        }
-        throw new Predef.IndexOutOfBoundsException
-      }
-      override def length: Int = {
-        val i = elements
-        var sz = 0
-        while (i.hasNext) {
-          sz += 1
-          i.next
-        }
-        sz
-      }
-    }
-    override def takeWhile(p: A => Boolean): Projection[A] = new ComputeSize[A] {
-      override def stringPrefix = Projection.this.stringPrefix + "TW"
-      override def elements = Projection.this.elements.takeWhile(p)
-    }
-    override def filter(p : A => Boolean) : Projection[A] = new ComputeSize[A] {
-      override def stringPrefix = Projection.this.stringPrefix + "F"
-      override def elements = Projection.this.elements.filter(p)
-    }
-  }
-}
-
-
-/** Class <code>Seq[A]</code> represents finite sequences of elements
- *  of type <code>A</code>.
- *
- *  @author  Martin Odersky
- *  @author  Matthias Zenger
- *  @version 1.0, 16/07/2003
- */
-trait Seq[+A] extends AnyRef with PartialFunction[Int, A] with Collection[A] {
-
-  /** Returns the length of the sequence.
-   *
-   *  @return the sequence length.
-   */
-  def length: Int
-
-  /** Result of comparing <code>length</code> with operand <code>l</code>.
-   *  returns <code>x</code> where
-   *  <code>x < 0</code>    iff    <code>this.length < l</code>
-   *  <code>x == 0</code>   iff    <code>this.length == l</code>
-   *  <code>x > 0</code>    iff    <code>this.length > that</code>.
-   *
-   *  This method is used by matching streams against right-ignoring (...,_*) patterns.
-   *  Lazy sequences should override this method if length forces evaluation of the stream. 
-   */
-  def lengthCompare(l: Int): Int = length - l
-
-  /** should always be <code>length</code> */
-  def size = length
-
-  /** Returns true if length == 0
-   */
-  override def isEmpty: Boolean = { length == 0 }
-
-  /** Appends two iterable objects.
-   *
-   *  @return     the new iterable object
-   *  @deprecated use <code>++</code> instead
-   */
-  @deprecated
-  override def concat [B >: A](that: Iterable[B]): Seq[B] = {
-    val buf = new ArrayBuffer[B]
-    this copyToBuffer buf
-    that copyToBuffer buf
-    buf.readOnly
-  }
-   
-  /** Returns the last element of this list.
-   *
-   *  @return the last element of the list.
-   *  @throws Predef.NoSuchElementException if the list is empty.
-   */
-  def last: A = length match {
-    case 0 => throw new Predef.NoSuchElementException
-    case n => this(n - 1)
-  }
-
-  /** Returns as an option the last element of this list or
-   *  <code>None</code> if list is empty.
-   *
-   *  @return the last element as an option.
-   */
-  def lastOption: Option[A] = length match {
-    case 0 => None
-    case n => Some(this(n-1))
-  }
-
-  /** Returns the first element of this list.
-   *
-   *  @return the first element of the list.
-   *  @throws Predef.UnsupportedOperationException if the list is empty.
-   */
-  def first: A =
-    if (isEmpty) throw new Predef.NoSuchElementException
-    else this(0)
-
-  /** Returns as an option the first element of this list or
-   *  <code>None</code> if list is empty.
-   *
-   *  @return the first element as an option.
-   */
-  def firstOption: Option[A] = if (isEmpty) None else Some(apply(0))
-
-  @deprecated
-  def headOption: Option[A] = firstOption
-
-  /** Appends two iterable objects.
-   */
-  override def ++ [B >: A](that: Iterable[B]): Seq[B] = {
-    val buf = new ArrayBuffer[B]
-    this copyToBuffer buf
-    that copyToBuffer buf
-    buf.readOnly
-  }
-
-  /** Is this partial function defined for the index <code>x</code>?
-   *
-   *  @param x ..
-   *  @return  <code>true</code>, iff <code>x</code> is a legal sequence index.
-   */
-  def isDefinedAt(x: Int): Boolean = (x >= 0) && (x < length)
-
-  /** Returns the index of the last occurence of the specified element
-   *  in this sequence, or -1 if the sequence does not contain this element.
-   *
-   *  @param  elem   element to search for.
-   *  @return the index in this sequence of the last occurence of the
-   *          specified element, or -1 if the sequence does not contain
-   *          this element.
-   */
-  def lastIndexOf[B >: A](elem: B): Int = {
-    var i = length
-    var found = false
-    while (!found && (i > 0)) {
-      i -= 1
-      if (this(i) == elem) found = true
-    }
-    if (found) i else -1
-  }
-    
-  /** Returns index of the first element satisying a predicate, or -1.
-   *
-   *  @note may not terminate for infinite-sized collections.
-   *  @param  p the predicate
-   *  @return   the index of the first element satisfying <code>p</code>,
-   *            or -1 if such an element does not exist
-   */
-  override def findIndexOf(p: A => Boolean): Int =
-    elements.findIndexOf(p)
-  
-  /** Returns the index of the first occurence of the specified
-   *  object in this iterable object.
-   *
-   *  @note may not terminate for infinite-sized collections.
-   *  @param  elem  element to search for.
-   *  @return the index in this sequence of the first occurence of the
-   *          specified element, or -1 if the sequence does not contain
-   *          this element.
-   */
-  override def indexOf[B >: A](elem: B): Int =
-    elements.indexOf(elem)
-        
-  /** Returns the sequence resulting from applying the given function
-   *  <code>f</code> to each element of this sequence.
-   *
-   *  @param f function to apply to each element.
-   *  @return  <code>f(a<sub>0</sub>), ..., f(a<sub>n</sub>)</code> if this
-   *           sequence is <code>a<sub>0</sub>, ..., a<sub>n</sub></code>.
-   */
-  override def map[B](f: A => B): Seq[B] = {
-    // todo: malformed scala signature suing build when replaced by
-    // super.map(f).asInstanceOf[Seq[B2]]
-    val buf = new ArrayBuffer[B]
-    val elems = elements
-    while (elems.hasNext) buf += f(elems.next)
-    buf.readOnly
-  }
-
-  /** Applies the given function <code>f</code> to each element of
-   *  this sequence, then concatenates the results.
-   *
-   *  @param f the function to apply on each element.
-   *  @return  <code>f(a<sub>0</sub>) ::: ... ::: f(a<sub>n</sub>)</code> if
-   *           this sequence is <code>a<sub>0</sub>, ..., a<sub>n</sub></code>.
-   */
-  override def flatMap[B](f: A => Iterable[B]): Seq[B] = {
-    val buf = new ArrayBuffer[B]
-    val elems = elements
-    while (elems.hasNext) f(elems.next) copyToBuffer buf
-    buf.readOnly
-  }
-
-  /** Returns all the elements of this sequence that satisfy the
-   *  predicate <code>p</code>. The order of the elements is preserved.
-   *
-   *  @param p the predicate used to filter the list.
-   *  @return the elements of this list satisfying <code>p</code>.
-   */
-  override def filter(p: A => Boolean): Seq[A] = super.filter(p).asInstanceOf[Seq[A]]
-
-  /** Returns a sequence consisting only over the first <code>n</code>
-   *  elements of this sequence, or else the whole sequence, if it has less
-   *  than <code>n</code> elements. (non-strict)
-   *
-   *  @param n the number of elements to take
-   *  @return a possibly projected sequence
-   */
-  override def take(n: Int): Seq[A] = {
-    var m = 0
-    val result = new scala.collection.mutable.ListBuffer[A]
-    val i = elements
-    while (m < n && i.hasNext) {
-      result += i.next; m += 1
-    }
-    result.toList
-  }
-    
-
-  /** Returns this sequence without its <code>n</code> first elements
-   *  If this sequence has less than <code>n</code> elements, the empty
-   *  sequence is returned. (non-strict)
-   *
-   *  @param n the number of elements to drop
-   *  @return  the new sequence 
-   */
-  override def drop(n: Int): Seq[A] = {
-    import scala.collection.mutable.ListBuffer
-    var m = 0
-    val result = new ListBuffer[A]
-    val i = elements
-    while (m < n && i.hasNext) {
-      i.next; m += 1
-    }
-    while (i.hasNext) result += i.next
-    result.toList
-  }
-
-   /** A sub-sequence starting at index <code>from</code> 
-    *  and ending (non-inclusive) at index <code>until</code> (non-strict)
-    *
-    *  @param from   The index of the first element of the slice
-    *  @param until    The index of the element following the slice
-    *  @throws IndexOutOfBoundsException if <code>from < 0</code>
-    *          or <code>length < from + len<code>
-    */
-  def slice(from: Int, until: Int): Seq[A] = drop(from).take(until - from)
-
-   /** A sub-sequence starting at index <code>from</code> 
-    *  and extending up to the length of the current sequence (non-strict)
-    *
-    *  @param from   The index of the first element of the slice
-    *  @throws IndexOutOfBoundsException if <code>from < 0</code>
-    *  @deprecated Use <code>drop(n: Int): Seq[A]</code> instead.
-    */
- @deprecated def slice(from: Int): Seq[A] = slice(from, length)
-
-  /** Returns the longest prefix of this sequence whose elements satisfy
-   *  the predicate <code>p</code>.
-   *
-   *  @param p the test predicate.
-   *  @return  the longest prefix of this sequence whose elements satisfy
-   *           the predicate <code>p</code>.
-   */
-  override def takeWhile(p: A => Boolean): Seq[A] = super.takeWhile(p).asInstanceOf[Seq[A]]
-
-  /** Returns the longest suffix of this sequence whose first element
-   *  does not satisfy the predicate <code>p</code>.
-   *
-   *  @param p the test predicate.
-   *  @return  the longest suffix of the sequence whose first element
-   *           does not satisfy the predicate <code>p</code>.
-   */
-  override def dropWhile(p: A => Boolean): Seq[A] = super.dropWhile(p).asInstanceOf[Seq[A]]
-
-  /** A sequence consisting of all elements of this sequence in reverse order.
-   */
-  def reverse: Seq[A] = {
-    var result: List[A] = Nil
-    val elems = elements
-    while (elems.hasNext) result = elems.next :: result
-    result
-  }
-
-  /** Tests if the given value <code>elem</code> is a member of this 
-   *  sequence.
-   *
-   *  @param elem element whose membership has to be tested.
-   *  @return     <code>true</code> iff there is an element of this sequence
-   *              which is equal (w.r.t. <code>==</code>) to <code>elem</code>.
-   */
-  def contains(elem: Any): Boolean = exists (_ == elem)
-
-  /** Returns a subsequence starting from index <code>from</code>
-   *  consisting of <code>len</code> elements.
-   *
-   *  @deprecated use <code>slice</code> instead
-   */
-  @deprecated
-  def subseq(from: Int, end: Int): Seq[A] = slice(from, end - from)
-
-  /** Converts this sequence to a fresh Array with <code>length</code> elements.
-   */
-  override def toArray[B >: A]: Array[B] = {
-    val result = new Array[B](length)
-    copyToArray(result, 0)
-    result
-  }
-  
-  /**
-   *  Overridden for efficiency.
-   *
-   *  @return  the sequence itself
-   */
-  override def toSeq: Seq[A] = this
-
-  override def projection: Seq.Projection[A] = new Seq.Projection[A] {
-    override def force: Seq[A] = Seq.this
-    def elements = Seq.this.elements
-    def length = Seq.this.length
-    def apply(idx : Int) = (Seq.this.apply(idx))
-    override def stringPrefix = Seq.this.stringPrefix + "P"
-  }
-
-  def equalsWith[B](that: Seq[B])(f: (A,B) => Boolean): Boolean = {
-    if (size != that.size) return false
-    val i = elements
-    val j = that.elements
-    while (i.hasNext) if (!f(i.next, j.next)) return false
-    true
-  }
-
-  /**
-   * Checks whether the argument sequence is contained at the 
-   * specified index within the receiver object. 
-   * 
-   * If the both the receiver object, <code>this</code> and 
-   * the argument, <code>that</code> are infinite sequences 
-   * this method may not terminate.
-   *
-   * @return true if <code>that</code> is contained in 
-   * <code>this</code>, at the specified index, otherwise false 
-   *
-   * @see String.startsWith
-   */
-  def startsWith[B](that: Seq[B], offset: Int): Boolean = {  
-    val i = elements.drop(offset)
-    val j = that.elements
-    var result = true
-    while (j.hasNext && i.hasNext && result) 
-      result = i.next == j.next
-    result && !j.hasNext
-  }
-
-  /**
-   * Check whether the receiver object starts with the argument sequence.
-   *
-   * @return true if <code>that</code> is a prefix of <code>this</code>,
-   * otherwise false 
-   *
-   * @see Seq.startsWith
-   */
-  def startsWith[B](that: Seq[B]): Boolean = startsWith(that, 0)
-
-
-  /** @return true if this sequence end with that sequence 
-   *  @see String.endsWith 
-   */
-  def endsWith[B](that: Seq[B]): Boolean =
-    drop(length - that.length).sameElements(that)
-
-  /**
-   * Searches for the argument sequence in the receiver object, returning 
-   * the smallest index where a match occurs.
-   * 
-   * If the receiver object, <code>this</code>, is an infinite sequence 
-   * this method will not terminate if there is no match.  Similarly, if 
-   * the both the receiver object and the argument, <code>that</code> are 
-   * infinite sequences this method will not terminate.
-   *
-   * Because both the receiver object and the argument can both potentially 
-   * be an infinite sequences, we do not attempt to use an optimized 
-   * searching algorithm.  Therefore, the running time will be proportional
-   * to the length of the receiver object and the argument.  Subclasses and 
-   * traits can potentially provide an optimized implementation.
-   *
-   * @return -1 if <code>that</code> not contained in <code>this</code>, 
-   * otherwise the smallest index where <code>that</code> is found.
-   *
-   * @see String.indexOf
-   */
-  def indexOf[B >: A](that: Seq[B]): Int = {
-    val e = this.elements
-    // Offset into e
-    var i = 0
-    if (that.isEmpty) return 0
-    while (e.hasNext) {
-      if (this.startsWith(that, i)) return i
-      e.next; i += 1
-    }
-    -1
-  }
-
-  /** Is <code>that</code> a slice in this? 
-   */
-  def containsSlice[B](that: Seq[B]): Boolean = indexOf(that) != -1 
-}
diff --git a/src/library/scala/SeqProxy.scala b/src/library/scala/SeqProxy.scala
deleted file mode 100644
index 5462e46..0000000
--- a/src/library/scala/SeqProxy.scala
+++ /dev/null
@@ -1,85 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: SeqProxy.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala
-
-
-/** This class implements a proxy for sequences. It forwards
- *  all calls to a different sequence object.
- *
- *  @author  Martin Odersky
- *  @author  Matthias Zenger
- *  @version 2.0, 31/12/2006
- */
-trait SeqProxy[+A] extends Seq[A] with CollectionProxy[A] {
-
-  override def self: Seq[A]
-  
-  // PartialFunction delegates
-
-  override def apply(i: Int): A = self(i)
-  
-  // Seq delegates
-  // Seq methods could be printed by  cat Seq.scala | sed -n '/trait Seq/,$ p' | egrep '^  (override )?def'
-  
-  override def length: Int = self.length
-  override def lengthCompare(l: Int) = self lengthCompare l
-  override def size = self.size
-  override def isEmpty = self.isEmpty
-  @deprecated
-  override def concat [B >: A](that: Iterable[B]): Seq[B] = self concat that
-  override def last = self.last
-  override def lastOption = self.lastOption
-  override def first = self.first
-  override def firstOption = self.firstOption
-  override def headOption = self.headOption
-  
-  override def ++ [B >: A](that: Iterable[B]) = self ++ that
-  override def isDefinedAt(x: Int): Boolean = self isDefinedAt x
-  
-  override def lastIndexOf[B >: A](elem: B): Int = self lastIndexOf elem
-  override def findIndexOf(p: A => Boolean): Int = self findIndexOf p
-  
-  override def indexOf[B >: A](elem: B): Int = self indexOf elem
-  
-  override def map[B](f: A => B): Seq[B] = self map f
-  override def flatMap[B](f: A => Iterable[B]) = self flatMap f
-  override def filter(p: A => Boolean): Seq[A] = self filter p
-  override def take(n: Int): Seq[A] = self take n
-  override def drop(n: Int): Seq[A] = self drop n
-  
-  override def slice(from: Int, len: Int): Seq[A] = self.slice(from, len)
-  override def slice(from: Int) = self slice from
-  
-  override def takeWhile(p: A => Boolean): Seq[A] = self takeWhile p
-  override def dropWhile(p: A => Boolean): Seq[A] = self dropWhile p
-  
-  override def reverse: Seq[A] = self.reverse
-  
-  override def contains(elem: Any): Boolean = self contains elem
-  
-  override def subseq(from: Int, end: Int) = self.subseq(from, end)
-  
-  override def toArray[B >: A]: Array[B] = self.toArray
-  
-  override def toSeq = self.toSeq
-  
-  override def projection = self.projection
-  
-  override def equalsWith[B](that: Seq[B])(f: (A, B) => Boolean): Boolean = self.equalsWith(that)(f)
-  
-  override def startsWith[B](that: Seq[B]) = self startsWith that
-  override def endsWith[B](that: Seq[B]) = self endsWith that
-  
-  override def indexOf[B >: A](that: Seq[B]) = self indexOf that
-  
-  override def containsSlice[B](that: Seq[B]) = self containsSlice that
-}
diff --git a/src/library/scala/SerialVersionUID.scala b/src/library/scala/SerialVersionUID.scala
index 5e7a7fc..0a2e29c 100644
--- a/src/library/scala/SerialVersionUID.scala
+++ b/src/library/scala/SerialVersionUID.scala
@@ -1,19 +1,18 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 */
 
-// $Id: SerialVersionUID.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala
 
 
 /**
- * Annotation for specifying the static SerialVersionUID field
- * of a serializable class
+ * Annotation for specifying the <code>static SerialVersionUID</code> field
+ * of a serializable class.
  */
 class SerialVersionUID(uid: Long) extends StaticAnnotation
diff --git a/src/library/scala/StaticAnnotation.scala b/src/library/scala/StaticAnnotation.scala
index e0367da..a1c3828 100644
--- a/src/library/scala/StaticAnnotation.scala
+++ b/src/library/scala/StaticAnnotation.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2006-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: StaticAnnotation.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala
@@ -18,5 +17,6 @@ package scala
  *
  *  @author  Martin Odersky
  *  @version 1.1, 2/02/2007
+ *  @since   2.4
  */
 trait StaticAnnotation extends Annotation {}
diff --git a/src/library/scala/StaticAttribute.scala b/src/library/scala/StaticAttribute.scala
deleted file mode 100644
index 5cba839..0000000
--- a/src/library/scala/StaticAttribute.scala
+++ /dev/null
@@ -1,25 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: StaticAttribute.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala
-
-/** <p>
- *    A base class for static attributes. These are available
- *    to the Scala type checker, even across different compilation units.
- *  </p>
- *
- *  @deprecated  use <a href="StaticAnnotation.html"
- *               target="contentFrame">StaticAnnotation</a> instead
- *  @author  Martin Odersky
- *  @version 1.1, 2/02/2007
- */
- at deprecated
-trait StaticAttribute extends Attribute {}
diff --git a/src/library/scala/Stream.scala b/src/library/scala/Stream.scala
deleted file mode 100644
index b59cea5..0000000
--- a/src/library/scala/Stream.scala
+++ /dev/null
@@ -1,518 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: Stream.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala
-
-import Predef._
-
-/**
- * The object <code>Stream</code> provides helper functions
- * to manipulate streams.
- *
- * @author Martin Odersky, Matthias Zenger
- * @version 1.1 08/08/03
- */
-object Stream {
-
-  def apply[A](xs: A*) = (xs :\ (empty: Stream[A]))(cons(_, _))
-    
-  def unapplySeq[A](xs: Stream[A]): Option[Seq[A]] = Some(xs)
-
-  object lazy_:: {
-    def unapply[A](xs: Stream[A]): Option[(A, Stream[A])] = 
-      if (xs.isEmpty) None
-      else Some(xs.head, xs.tail)
-  }
-
-   /** a stream with a definite size */
-  trait Definite[+A] extends Stream[A] with Function0[Stream[A]] {
-     override def hasDefiniteSize = true
-     override def apply = this
-
-    /** Converts stream to string. Redefined here as
-     *  super[Stream].toString does not pass because of an implementation
-     *  restriction (super[C] cannot be called when C is a class).
-     */
-    override def toString =
-      "Stream(" + addDefinedElems(new StringBuilder(), "") + ")"
-   }
-   
-  /** The empty stream */
-  val empty: Stream[Nothing] = new Definite[Nothing] {
-    override def isEmpty = true
-    def head: Nothing = throw new NoSuchElementException("head of empty stream")
-    def tail: Stream[Nothing] = throw new UnsupportedOperationException("tail of empty stream")
-    protected def addDefinedElems(buf: StringBuilder, prefix: String): StringBuilder = buf
-  }
-
-  object cons {
-
-    /** A stream consisting of a given first element and remaining elements 
-     *  @param hd   The first element of the result stream
-     *  @param tl   The remaining elements of the result stream
-     */
-    def apply[A](hd: A, tl: => Stream[A]) = new Stream[A] {
-      override def hasDefiniteSize = if (tlDefined) tlVal.hasDefiniteSize else super.hasDefiniteSize
-      override def isEmpty = false
-      def head = hd
-      private var tlVal: Stream[A] = _
-      private def tlDefined = tlVal ne null
-      def tail: Stream[A] = {
-        if (!tlDefined) { tlVal = tl }
-        tlVal 
-      }
-      protected def addDefinedElems(buf: StringBuilder, prefix: String): StringBuilder = {
-        val buf1 = buf.append(prefix).append(hd)
-        if (tlDefined) tlVal.addDefinedElems(buf1, ", ") else buf1 append ", ?"
-      }
-    }
-
-    def unapply[A](str: Stream[A]): Option[(A, Stream[A])] =
-      if(str.isEmpty)
-        None
-      else
-        Some((str.head, str.tail))
-  }
-
-  /** A stream containing all elements of a given iterator, in the order they are produced.
-   *  @param it   The iterator producing the stream's elements
-   */
-  def fromIterator[A](it: Iterator[A]): Stream[A] =
-    if (it.hasNext) cons(it.next, fromIterator(it)) else empty
-
-  /** The concatenation of a sequence of streams 
-   */
-  def concat[A](xs: Iterable[Stream[A]]): Stream[A] = concat(xs.elements)
-
-  /** The concatenation of all given streams 
-   */
-  def concat[A](s1: Stream[A], s2: Stream[A], ss: Stream[A]*): Stream[A] =
-    s1 append s2 append concat(ss.elements)
-
-  /** The concatenation of all streams returned by an iterator
-   */
-  def concat[A](xs: Iterator[Stream[A]]): Stream[A] =
-    if (xs.hasNext) xs.next append concat(xs)
-    else empty
-
-  /**
-   * Create a stream with element values
-   * <code>v<sub>n+1</sub> = v<sub>n</sub> + 1</code>
-   * where <code>v<sub>0</sub> = start</code>
-   * and <code>v<sub>i</sub> < end</code>.
-   *
-   * @param start the start value of the stream
-   * @param end the end value of the stream
-   * @return the stream starting at value <code>start</code>.
-   */
-  def range(start: Int, end: Int): Stream[Int] = 
-    range(start, end, 1)
-
-  /**
-   * Create a stream with element values
-   * <code>v<sub>n+1</sub> = v<sub>n</sub> + step</code>
-   * where <code>v<sub>0</sub> = start</code>
-   * and elements are in the range between <code>start</code> (inclusive)
-   * and <code>end</code> (exclusive)
-   *
-   * @param start the start value of the stream
-   * @param end the end value of the stream
-   * @param step the increment value of the stream
-   * @return the stream starting at value <code>start</code>.
-   */
-  final def range(start: Int, end: Int, step: Int): Stream[Int] = {
-    if ((step <= 0 || start < end) && (step >= 0 || start > end)) 
-      cons(start, range(start + step, end, step))
-    else 
-      empty
-  }
-
-  /**
-   * Create a stream with element values
-   * <code>v<sub>n+1</sub> = step(v<sub>n</sub>)</code>
-   * where <code>v<sub>0</sub> = start</code>
-   * and elements are in the range between <code>start</code> (inclusive)
-   * and <code>end</code> (exclusive)
-   *
-   * @param start the start value of the stream
-   * @param end the end value of the stream
-   * @param step the increment function of the stream, must be monotonically increasing or decreasing
-   * @return the stream starting at value <code>start</code>.
-   */
-  def range(start: Int, end: Int, step: Int => Int): Stream[Int] = {
-    val up = step(start) > start
-    val down = step(start) < start
-    def loop(lo: Int): Stream[Int] =
-      if ((!up || lo < end) && (!down || lo > end)) cons(lo, loop(step(lo)))
-      else empty
-    loop(start)
-  }
-   
-  /**
-   * Create an infinite stream starting at <code>start</code>
-   * and incrementing by step <code>step</code>
-   *
-   * @param start the start value of the stream
-   * @param step the increment value of the stream
-   * @return the stream starting at value <code>start</code>.
-   */
-  def from(start: Int, step: Int): Stream[Int] =
-    cons(start, from(start+step, step))
-
-  /**
-   * Create an infinite stream starting at <code>start</code>
-   * and incrementing by 1.
-   *
-   * @param start the start value of the stream
-   * @return the stream starting at value <code>start</code>.
-   */
-  def from(start: Int): Stream[Int] = from(start, 1)
-
-  /**
-   * Create an infinite stream containing the given element.
-   *
-   * @param elem the element composing the resulting stream
-   * @return the stream containing an inifinite number of elem
-   */
-  def const[A](elem: A): Stream[A] = cons(elem, const(elem))
-
-  /** Create a stream containing several copies of an element.
-   *
-   *  @param n    the length of the resulting stream
-   *  @param elem the element composing the resulting stream
-   *  @return     the stream composed of n elements all equal to elem
-   */
-  def make[A](n: Int, elem: A): Stream[A] = 
-    Stream.const(elem) take n
-}
-
-/**
- * <p>The class <code>Stream</code> implements lazy lists where elements
- * are only evaluated when they are needed. Here is an example:</p>
- * <pre>
- * <b>object</b> Main <b>extends</b> Application {
- *
- *   <b>def</b> from(n: Int): Stream[Int] =
- *     Stream.cons(n, from(n + 1))
- *
- *   <b>def</b> sieve(s: Stream[Int]): Stream[Int] =
- *     Stream.cons(s.head, sieve(s.tail filter { _ % s.head != 0 }))
- *
- *   <b>def</b> primes = sieve(from(2))
- *
- *   primes take 10 print
- * }
- * </pre>
- *
- * @author Martin Odersky, Matthias Zenger
- * @version 1.1 08/08/03
- */
-abstract class Stream[+A] extends Seq.Projection[A] {
-
-  /** is this stream empty? */
-  override def isEmpty: Boolean
-
-  override def force : List[A] = toList
-  
-  /** The first element of this stream 
-   *  @throws Predef.NoSuchElementException if the stream is empty.
-   */
-  def head: A
-
-  /** A stream consisting of the remaining elements of this stream after the first one.
-   *  @throws Predef.UnsupportedOperationException if the stream is empty.
-   */
-  def tail: Stream[A]
-
-  /** The length of this stream */
-  override def length: Int = {
-    var len = 0
-    var here = this
-    while (!here.isEmpty) {
-      len += 1
-      here = here.tail
-    }
-    len
-  }
-
-  /** Result of comparing <code>length</code> with operand <code>l</code>.
-   *  returns <code>x</code> where
-   *  <code>x < 0</code>    iff    <code>this.length < l</code>
-   *  <code>x == 0</code>   iff    <code>this.length == l</code>
-   *  <code>x > 0</code>    iff    <code>this.length > that</code>.
-   *
-   *  This method is used by matching streams against right-ignoring (...,_*) patterns.
-   *
-   *  This method does not call <code>Stream.length</code>, it works for <code>O(l)</code>,
-   *  not for <code>O(length)</code> and does not force full Stream evaluation.
-   */
-  final override def lengthCompare(l: Int) = {
-    if (isEmpty) 0 - l
-    else if (l <= 0) 1
-    else tail.lengthCompare(l - 1)
-  }
-
-  override def hasDefiniteSize = false
-  
-  
-  /** The stream resulting from the concatenation of this stream with the argument stream.
-   *  @param rest   The stream that gets appended to this stream
-   */
-  override def append[B >: A](rest: => Iterable[B]): Stream[B] =
-    if (isEmpty) rest.toStream else Stream.cons(head, tail append rest)
-    
-
-  /** An iterator returning the elements of this stream one by one.
-   */
-  override def elements: Iterator[A] = new Iterator[A] {
-    var current = Stream.this
-    def hasNext: Boolean = !current.isEmpty
-    def next: A = { val result = current.head; current = current.tail; result }
-  }
-
-  /** The stream without its last element.
-   *  @throws Predef.UnsupportedOperationException if the stream is empty.
-   */
-  def init: Stream[A] =
-    if (isEmpty) throw new UnsupportedOperationException("Stream.empty.init")
-    else if (tail.isEmpty) Stream.empty
-    else Stream.cons(head, tail.init)
-
-  /** Returns the last element of this stream.
-   *
-   *  @return the last element of the stream.
-   *  @throws Predef.NoSuchElementException if the stream is empty.
-   */
-  override final def last: A =
-    if (isEmpty) throw new NoSuchElementException("Stream.empty.last")
-    else 
-      if (tail.isEmpty) head else tail.last
-
-  /** Returns the <code>n</code>-th element of this stream. The first element
-   *  (head of the stream) is at position 0.
-   *
-   *  @param n index of the element to return
-   *  @return  the element at position <code>n</code> in this stream.
-   *  @throws Predef.NoSuchElementException if the stream is too short.
-   */
-  override def apply(n: Int): A = drop(n).head
-
-  /** Returns the <code>n</code> first elements of this stream, or else the whole 
-   *  stream, if it has less than <code>n</code> elements.
-   *
-   *  @param n the number of elements to take.
-   *  @return the <code>n</code> first elements of this stream.
-   */
-  override def take(n: Int): Stream[A] =
-    if (isEmpty || n <= 0) Stream.empty
-    else Stream.cons(head, if (n == 1) Stream.empty else (tail.take(n-1)))
-
-  /** Returns the stream without its <code>n</code> first elements.
-   *  If the stream has less than <code>n</code> elements, the empty stream is returned.
-   *
-   *  @param n the number of elements to drop.
-   *  @return the stream without its <code>n</code> first elements.
-   */
-  override final def drop(n: Int): Stream[A] = {
-    if (isEmpty || n <= 0) this
-    else tail.drop(n - 1)
-  }
-   
-
-  /** Returns the longest prefix of this stream whose elements satisfy
-   *  the predicate <code>p</code>.
-   *
-   *  @param p the test predicate.
-   *  @return  the longest prefix of this stream whose elements satisfy
-   *           the predicate <code>p</code>.
-   */
-  override def takeWhile(p: A => Boolean): Stream[A] =
-    if (isEmpty || !p(head)) Stream.empty
-    else Stream.cons(head, tail takeWhile p)
-
-  /** Returns the longest suffix of this stream whose first element
-   *  does not satisfy the predicate <code>p</code>.
-   *
-   *  @param p the test predicate.
-   *  @return  the longest suffix of the stream whose first element
-   *           does not satisfy the predicate <code>p</code>.
-   */
-  override final def dropWhile(p: A => Boolean): Stream[A] = {
-    if (isEmpty || !p(head)) this
-    else tail.dropWhile(p)
-  }
-
-  /** Returns the stream resulting from applying the given function <code>f</code> to each
-   *  element of this stream.
-   *
-   *  @param f function to apply to each element.
-   *  @return <code>[f(a0), ..., f(an)]</code> if this stream is <code>[a0, ..., an]</code>.
-   */
-  override def map[B](f: A => B): Stream[B] =
-    if (isEmpty) Stream.empty
-    else Stream.cons(f(head), tail map f)
-
-  /** Apply the given function <code>f</code> to each element of this stream
-   *  (while respecting the order of the elements).
-   *
-   *  @param f the treatment to apply to each element.
-   */
-  override final def foreach(f: A => Unit) {
-    if (isEmpty) {}
-    else { f(head); tail.foreach(f) }
-  }
-
-  /** Returns all the elements of this stream that satisfy the
-   *  predicate <code>p</code>. The order of the elements is preserved.
-   *
-   *  @param p the predicate used to filter the stream.
-   *  @return the elements of this stream satisfying <code>p</code>.
-   */
-  override final def filter(p: A => Boolean): Stream[A] = {
-    if (isEmpty) this
-    else if (p(head)) Stream.cons(head, tail.filter(p))
-    else tail.filter(p)
-  }
-
-  /** Tests if the predicate <code>p</code> is satisfied by all elements
-   *  in this stream.
-   *
-   *  @param p the test predicate.
-   *  @return  <code>true</code> iff all elements of this stream satisfy the
-   *           predicate <code>p</code>.
-   */
-  override final def forall(p: A => Boolean): Boolean = {
-    if (isEmpty) true
-    else if (p(head)) tail.forall(p)
-    else false
-  }
-
-  /** Tests the existence in this stream of an element that satisfies the
-   *  predicate <code>p</code>.
-   *
-   *  @param p the test predicate.
-   *  @return  <code>true</code> iff there exists an element in this stream that
-   *           satisfies the predicate <code>p</code>.
-   */
-  override final def exists(p: A => Boolean): Boolean = {
-    if (isEmpty) false
-    else if (p(head)) true
-    else tail.exists(p)
-  }
-
-  /** Combines the elements of this stream together using the binary
-   *  function <code>f</code>, from left to right, and starting with
-   *  the value <code>z</code>.
-   *
-   *  @return <code>f(... (f(f(z, a<sub>0</sub>), a<sub>1</sub>) ...),
-   *          a<sub>n</sub>)</code> if the stream is
-   *          <code>[a<sub>0</sub>, a<sub>1</sub>, ..., a<sub>n</sub>]</code>.
-   */
-  override final def foldLeft[B](z: B)(f: (B, A) => B): B = {
-    if (isEmpty) z
-    else tail.foldLeft(f(z, head))(f)
-  }
-
-  /** Combines the elements of this stream together using the binary
-   *  function <code>f</code>, from rigth to left, and starting with
-   *  the value <code>z</code>.
-   *
-   *  @return <code>f(a<sub>0</sub>, f(a<sub>1</sub>, f(..., f(a<sub>n</sub>, z)...)))</code>
-   *          if the stream is <code>[a<sub>0</sub>, a1, ..., a<sub>n</sub>]</code>.
-   */
-  override def foldRight[B](z: B)(f: (A, B) => B): B =
-    if (isEmpty) z
-    else f(head, tail.foldRight(z)(f))
-
-  /** Applies the given function <code>f</code> to each element of
-   *  this stream, then concatenates the results.
-   *
-   *  @param f the function to apply on each element.
-   *  @return  <code>f(a<sub>0</sub>) ::: ... ::: f(a<sub>n</sub>)</code> if
-   *           this stream is <code>[a<sub>0</sub>, ..., a<sub>n</sub>]</code>.
-   */
-  override def flatMap[B](f: A => Iterable[B]): Stream[B] = {
-    // drops A's for which f yields an empty Iterable[B]
-    def loop(s: Stream[A]): Stream[B] = {
-      if (s.isEmpty)
-        Stream.empty
-      else {
-        val i = f(s.head)
-        if (i isEmpty)
-          loop(s.tail)
-        else
-          i.toStream append loop(s.tail)
-      }
-    }
-
-    loop(this)
-  }
-
-  override def toStream = this
-
-  /** A stream consisting of all elements of this stream in reverse order.
-   */
-  override def reverse: Stream[A] =
-    foldLeft(Stream.empty: Stream[A])((xs, x) => Stream.cons(x, xs))
-
-  /** Fills the given array <code>xs</code> with the elements of
-   *  this stream starting at position <code>start</code>.
-   *
-   *  @param  xs the array to fill.
-   *  @param  start starting index.
-   *  @pre    the array must be large enough to hold all elements.
-   */
-  override final def copyToArray[B >: A](xs: Array[B], start: Int) {
-    if (!isEmpty) { xs(start) = head; tail.copyToArray(xs, start + 1) }
-  }
-
-  /** Returns a stream formed from this stream and the specified stream
-   *  <code>that</code> by associating each element of the former with
-   *  the element at the same position in the latter.
-   *  If one of the two streams is longer than the other, its remaining elements are ignored.
-   *
-   *  @return     <code>Stream({a<sub>0</sub>,b<sub>0</sub>}, ...,
-   *              {a<sub>min(m,n)</sub>,b<sub>min(m,n)</sub>)}</code> when
-   *              <code>Stream(a<sub>0</sub>, ..., a<sub>m</sub>)
-   *              zip Stream(b<sub>0</sub>, ..., b<sub>n</sub>)</code> is invoked.
-   */
-  def zip[B](that: Stream[B]): Stream[(A, B)] =
-    if (this.isEmpty || that.isEmpty) Stream.empty
-    else Stream.cons((this.head, that.head), this.tail zip that.tail)
-
-  
-  /** Returns a stream that pairs each element of this stream
-   *  with its index, counting from 0.
-   *
-   *  @return      the stream <code>Stream({a<sub>0</sub>,0}, {a<sub>0</sub>,1},...)</code>
-   *               where <code>a<sub>i</sub></code> are the elements of this stream.
-   */
-  def zipWithIndex: Stream[(A, Int)] =
-    zip(Stream.from(0))
-
-  /** Prints elements of this stream one by one, separated by commas */
-  def print { print(", ") }
-
-  /** Prints elements of this stream one by one, separated by <code>sep</code>
-   *  @param sep   The separator string printed between consecutive elements. 
-   */
-  def print(sep: String) {
-    if (isEmpty) Console.println("Stream.empty")
-    else { Console.print(head); Console.print(sep); tail.print(sep) }
-  }
-
-  /** Converts stream to string */
-  override def toString =
-    "Stream(" + addDefinedElems(new StringBuilder(), "") + ")"
-
-  /** Write all elements of this string into given string builder */
-  protected def addDefinedElems(buf: StringBuilder, prefix: String): StringBuilder
-}
diff --git a/src/library/scala/StringBuilder.scala b/src/library/scala/StringBuilder.scala
deleted file mode 100644
index dba194e..0000000
--- a/src/library/scala/StringBuilder.scala
+++ /dev/null
@@ -1,952 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: StringBuilder.scala 16881 2009-01-09 16:28:11Z cunei $
-
-
-package scala
-
-import Predef._
-
-/** <p>
- *    A mutable sequence of characters.  This class provides an API compatible
- *    with <a class="java/lang/StringBuilder" href="" target="_top">
- *    <code>java.lang.StringBuilder</code></a>.
- *  </p>
- *
- *  @author Stephane Micheloud
- *  @version 1.0
- */
- at serializable
- at SerialVersionUID(0 - 8525408645367278351L)
-final class StringBuilder(initCapacity: Int, private val initValue: String)
-      extends (Int => Char) {
-  if (initCapacity < 0) throw new IllegalArgumentException
-  if (initValue eq null) throw new NullPointerException
-
-  /** The value is used for character storage. */
-  private var value = new Array[Char](initCapacity + initValue.length)
-
-  /** The count is the number of characters used. */
-  private var count: Int = 0
-
-  /** Constructs a string builder with no characters in it and an 
-   *  initial capacity of 16 characters.
-   */
-  def this() = this(16, "")
-
-  /** Constructs a string builder with no characters in it and an 
-   *  initial capacity specified by the <code>capacity</code> argument. 
-   *
-   *  @param  capacity  the initial capacity.
-   *  @throws NegativeArraySizeException  if the <code>capacity</code>
-   *                    argument is less than <code>0</code>.
-   */
-  def this(capacity: Int) = this(capacity, "")
-
-  def this(str: String) = this(16, str)
-
-  append(initValue)
-
-  def toArray: Array[Char] = value
-
-  def length: Int = count
-
-  def length_=(n: Int) { setLength(n) }
-
-  /** Sets the length of the character sequence.
-   *
-   *  @param  newLength  the new length
-   *  @throws IndexOutOfBoundsException  if the <code>n</code> argument is negative.
-   */
-  def setLength(n: Int) {
-    if (n < 0)
-      throw new StringIndexOutOfBoundsException(n)
-    if (n > value.length) expandCapacity(n)
-    if (count < n)
-      while (count < n) {
-        value(count) = '\0'; count += 1
-      }
-    else
-      count = n
-  }
-
-  /** Returns the current capacity. The capacity is the amount of storage 
-   *  available for newly inserted characters, beyond which an allocation 
-   *  will occur.
-   *
-   *  @return  the current capacity
-   */
-  def capacity: Int = value.length
-
-  /** Same as <code>ensureCapacity</code>. */
-  def capacity_=(n: Int) { ensureCapacity(n) }
-
-  /** <p>
-   *    Ensures that the capacity is at least equal to the specified minimum.
-   *    If the current capacity is less than the argument, then a new internal
-   *    array is allocated with greater capacity. The new capacity is the larger of: 
-   *  </p>
-   *  <ul>
-   *    <li>The <code>n</code> argument. 
-   *    <li>Twice the old capacity, plus <code>2</code>. 
-   *  </ul>
-   *  <p>
-   *    If the <code>n</code> argument is non-positive, this
-   *    method takes no action and simply returns.
-   *  </p>
-   *
-   *  @param n the minimum desired capacity.
-   */
-  def ensureCapacity(n: Int) {
-    if (n > value.length) expandCapacity(n)
-  }
-
-  private def expandCapacity(n: Int) {
-    val newCapacity = (value.length + 1) * 2
-    value = StringBuilder.copyOf(
-      value,
-      if (newCapacity < 0) Math.MAX_INT else if (n > newCapacity) n else newCapacity
-    )
-  }
-
-  /** <p>
-   *    Returns the <code>Char</code> value in this sequence at the specified index.
-   *    The first <code>Char</code> value is at index <code>0</code>, the next at index
-   *    <code>1</code>, and so on, as in array indexing.
-   *  </p>
-   *  <p>
-   *    The index argument must be greater than or equal to
-   *    <code>0</code>, and less than the length of this sequence.
-   *  </p>
-   *
-   *  @param  index   the index of the desired <code>Char</code> value.
-   *  @return         the <code>Char</code> value at the specified index.
-   *  @throws IndexOutOfBoundsException  if <code>index</code> is 
-   *                  negative or greater than or equal to <code>length()</code>.
-   */
-  def charAt(index: Int): Char = {
-    if (index < 0 || index >= count)
-      throw new StringIndexOutOfBoundsException(index)
-    value(index)
-  }
-
-  /** Same as <code>charAt</code>. */
-  def apply(i: Int): Char = charAt(i)
-
-  /** <p>
-   *    Removes the <code>Char</code> at the specified position in this
-   *    sequence. This sequence is shortened by one <code>Char</code>.
-   *  </p>
-   *
-   *  @param  index  Index of <code>Char</code> to remove
-   *  @return        This object.
-   *  @throws StringIndexOutOfBoundsException  if the <code>index</code>
-   *	             is negative or greater than or equal to <code>length()</code>.
-   */
-  def deleteCharAt(index: Int): StringBuilder = {
-    if (index < 0 || index >= count)
-      throw new StringIndexOutOfBoundsException(index)
-    compat.Platform.arraycopy(value, index + 1, value, index, count - index - 1)
-    count -= 1
-    this
-  }
-
-  /** <p>
-   *    The character at the specified index is set to <code>ch</code>. This 
-   *    sequence is altered to represent a new character sequence that is 
-   *    identical to the old character sequence, except that it contains the 
-   *    character <code>ch</code> at position <code>index</code>. 
-   *  </p>
-   *  <p>
-   *    The index argument must be greater than or equal to 
-   *    <code>0</code>, and less than the length of this sequence. 
-   *  </p>
-   *
-   *  @param  index   the index of the character to modify.
-   *  @param  ch      the new character.
-   *  @throws IndexOutOfBoundsException  if <code>index</code> is 
-   *                  negative or greater than or equal to <code>length()</code>.
-   */
-  def setCharAt(index: Int, ch: Char) {
-    if (index < 0 || index >= count)
-      throw new StringIndexOutOfBoundsException(index)
-    value(index) = ch
-  }
-
-  /** Same as <code>setCharAt</code>. */
-  def update(i: Int, c: Char) { setCharAt(i, c) }
-
-  /** Returns a new <code>String</code> that contains a subsequence of
-   *  characters currently contained in this character sequence. The 
-   *  substring begins at the specified index and extends to the end of
-   *  this sequence.
-   * 
-   *  @param  start  The beginning index, inclusive.
-   *  @return        The new string.
-   *  @throws StringIndexOutOfBoundsException  if <code>start</code> is
-   *                 less than zero, or greater than the length of this object.
-   */
-  def substring(start: Int): String = substring(start, count)
-
-  /** Returns a new <code>String</code> that contains a subsequence of
-   *  characters currently contained in this sequence. The 
-   *  substring begins at the specified <code>start</code> and 
-   *  extends to the character at index <code>end - 1</code>.
-   *
-   *  @param  start  The beginning index, inclusive.
-   *  @param  end    The ending index, exclusive.
-   *  @return The new string.
-   *  @throws StringIndexOutOfBoundsException  if <code>start</code>
-   *                 or <code>end</code> are negative or greater than
-   *		     <code>length()</code>, or <code>start</code> is
-   *		     greater than <code>end</code>.
-   */
-  def substring(start: Int, end: Int): String = {
-    if (start < 0)
-      throw new StringIndexOutOfBoundsException(start)
-    if (end > count)
-      throw new StringIndexOutOfBoundsException(end)
-    if (start > end)
-      throw new StringIndexOutOfBoundsException(end - start)
-    new String(value, start, end - start)
-  }
-
-  /** <p>
-   *    Appends the string representation of the <code>Any</code> 
-   *    argument.
-   *  </p>
-   *  <p>
-   *    The argument is converted to a string as if by the method 
-   *    <code>String.valueOf</code>, and the characters of that 
-   *    string are then appended to this sequence.
-   *  </p>
-   *
-   *  @param  x   an <code>Any</code> object.
-   *  @return     a reference to this object.
-   */
-  def append(x: Any): StringBuilder =
-    append(String.valueOf(x))
-
-  /** Appends the specified string to this character sequence.
-   *
-   *  @param  s   a string.
-   *  @return     a reference to this object.
-   */
-  def append(s: String): StringBuilder = {
-    val str = if (s == null) "null" else s
-    val len = str.length
-    if (len > 0) {
-      val newCount = count + len
-      if (newCount > value.length) expandCapacity(newCount)
-      str.getChars(0, len, value, count)
-      count = newCount
-    }
-    this
-  }
-
-  /** Appends the specified string builder to this sequence.
-   *
-   *  @param sb
-   *  @return 
-   */
-  def append(sb: StringBuilder): StringBuilder =
-    if (sb == null)
-      append("null")
-    else {
-      val len = sb.length
-      val newCount = count + len
-      if (newCount > value.length) expandCapacity(newCount)
-      compat.Platform.arraycopy(sb.toArray, 0, value, count, len)
-      count = newCount
-      this
-    }
-
-  /** <p>
-   *    Appends the string representation of the <code>Char</code> sequence 
-   *    argument to this sequence.
-   *  </p>
-   *  <p>
-   *    The characters of the sequence argument are appended, in order,
-   *    to the contents of this sequence. The length of this sequence
-   *    increases by the length of the argument.
-   *  </p>
-   *
-   *  @param  x  the characters to be appended.
-   *  @return    a reference to this object.
-   */
-  def append(x: Seq[Char]): StringBuilder =
-    append(x.toArray, 0, x.length)
-
-  /** <p>
-   *    Appends the string representation of the <code>Char</code> array 
-   *    argument to this sequence.
-   *  </p>
-   *  <p>
-   *    The characters of the array argument are appended, in order, to 
-   *    the contents of this sequence. The length of this sequence
-   *    increases by the length of the argument.
-   *  </p>
-   *
-   *  @param  x  the characters to be appended.
-   *  @return    a reference to this object.
-   */
-  def append(x: Array[Char]): StringBuilder =
-    append(x, 0, x.length)
-
-  /** <p>
-   *    Appends the string representation of a subarray of the
-   *    <code>char</code> array argument to this sequence.
-   *  </p>
-   *  <p>
-   *    Characters of the <code>Char</code> array <code>x</code>, starting at
-   *    index <code>offset</code>, are appended, in order, to the contents
-   *    of this sequence. The length of this sequence increases
-   *    by the value of <code>len</code>.
-   *  </p>
-   *
-   *  @param  x      the characters to be appended.
-   *  @param  offset the index of the first <code>Char</code> to append.
-   *  @param  len    the number of <code>Char</code>s to append.
-   *  @return        a reference to this object.
-   */
-  def append(x: Array[Char], offset: Int, len: Int): StringBuilder = {
-    val newCount = count + len
-    if (newCount > value.length) expandCapacity(newCount)
-    compat.Platform.arraycopy(x, offset, value, count, len)
-    count = newCount
-    this
-  }
-
-  /** <p>
-   *    Appends the string representation of the <code>Boolean</code> 
-   *    argument to the sequence.
-   *  </p>
-   *  <p>
-   *    The argument is converted to a string as if by the method 
-   *    <code>String.valueOf</code>, and the characters of that 
-   *   string are then appended to this sequence. 
-   *  </p>
-   *
-   *   @param  x  a <code>Boolean</code>.
-   *   @return    a reference to this object.
-   */
-  def append(x: Boolean): StringBuilder = {
-    if (x) {
-      val newCount = count + 4
-      if (newCount > value.length) expandCapacity(newCount)
-      value(count) = 't'; count += 1
-      value(count) = 'r'; count += 1
-      value(count) = 'u'; count += 1
-      value(count) = 'e'; count += 1
-    } else {
-      val newCount = count + 5
-      if (newCount > value.length) expandCapacity(newCount)
-      value(count) = 'f'; count += 1
-      value(count) = 'a'; count += 1
-      value(count) = 'l'; count += 1
-      value(count) = 's'; count += 1
-      value(count) = 'e'; count += 1
-    }
-    this
-  }
-
-  def append(x: Byte): StringBuilder =
-    append(String.valueOf(x))
-
-  def append(x: Char): StringBuilder = {
-    val newCount = count + 1
-    if (newCount > value.length) expandCapacity(newCount)
-    value(count) = x; count += 1
-    this
-  }
-
-  def append(x: Short): StringBuilder =
-    append(String.valueOf(x))
-
-  def append(x: Int): StringBuilder =
-    append(String.valueOf(x))
-
-  def append(x: Long): StringBuilder =
-    append(String.valueOf(x))
-
-  def append(x: Float): StringBuilder =
-    append(String.valueOf(x))
-
-  def append(x: Double): StringBuilder = 
-    append(String.valueOf(x))
-
-  /** Removes the characters in a substring of this sequence.
-   *  The substring begins at the specified <code>start</code> and extends to
-   *  the character at index <code>end - 1</code> or to the end of the
-   *  sequence if no such character exists. If
-   *  <code>start</code> is equal to <code>end</code>, no changes are made.
-   *
-   *  @param  start  The beginning index, inclusive.
-   *  @param  end    The ending index, exclusive.
-   *  @return        This object.
-   *  @throws StringIndexOutOfBoundsException  if <code>start</code>
-   *                 is negative, greater than <code>length()</code>, or
-   *		     greater than <code>end</code>.
-   */
-  def delete(start: Int, end: Int): StringBuilder = {
-    if (start < 0 || start > end)
-      throw new StringIndexOutOfBoundsException(start)
-    val end0 = if (end > count) count else end
-    val len = end0 - start
-    if (len > 0) {
-      compat.Platform.arraycopy(value, start + len, value, start, count - end0)
-      count -= len
-    }
-    this
-  }
-
-  /** Replaces the characters in a substring of this sequence
-   *  with characters in the specified <code>String</code>. The substring
-   *  begins at the specified <code>start</code> and extends to the character
-   *  at index <code>end - 1</code> or to the end of the sequence if no such
-   *  character exists. First the characters in the substring are removed and
-   *  then the specified <code>String</code> is inserted at <code>start</code>.
-   * 
-   *  @param  start  The beginning index, inclusive.
-   *  @param  end    The ending index, exclusive.
-   *  @param  str    String that will replace previous contents.
-   *  @return        This object.
-   *  @throws StringIndexOutOfBoundsException  if <code>start</code>
-   *                 is negative, greater than <code>length()</code>, or
-   *		     greater than <code>end</code>.
-   */
-  def replace(start: Int, end: Int, str: String) {
-    if (start < 0 || start > count || start > end)
-      throw new StringIndexOutOfBoundsException(start)
-
-    val end0 = if (end > count) count else end
-    val len = str.length()
-    val newCount = count + len - (end0 - start)
-    if (newCount > value.length) expandCapacity(newCount)
-
-    compat.Platform.arraycopy(value, end, value, start + len, count - end)
-    str.getChars(0, len, value, start)  
-    count = newCount
-    this
-  }
-
-  /** Inserts the string representation of a subarray of the <code>str</code>
-   *  array argument into this sequence. The subarray begins at the specified
-   *  <code>offset</code> and extends <code>len</code> <code>char</code>s.
-   *  The characters of the subarray are inserted into this sequence at
-   *  the position indicated by <code>index</code>. The length of this
-   *  sequence increases by <code>len</code> <code>Char</code>s.
-   *
-   * @param  index   position at which to insert subarray.
-   * @param  str     a <code>Char</code> array.
-   * @param  offset  the index of the first <code>char</code> in subarray to
-   *                 be inserted.
-   * @param  len     the number of <code>Char</code>s in the subarray to
-   *                 be inserted.
-   * @return         This object
-   * @throws StringIndexOutOfBoundsException  if <code>index</code>
-   *                 is negative or greater than <code>length()</code>, or
-   *                 <code>offset</code> or <code>len</code> are negative, or
-   *                 <code>(offset+len)</code> is greater than
-   *                 <code>str.length</code>.
-   */
-  def insert(index: Int, str: Array[Char], offset: Int, len: Int): StringBuilder = {
-    if (index < 0 || index > count)
-      throw new StringIndexOutOfBoundsException(index)
-    if (offset < 0 || len < 0 || offset > str.length - len)
-      throw new StringIndexOutOfBoundsException(
-                "offset " + offset + ", len " + len +
-                ", str.length " + str.length)
-    val newCount = count + len
-    if (newCount > value.length) expandCapacity(newCount)
-    compat.Platform.arraycopy(value, index, value, index + len, count - index)
-    compat.Platform.arraycopy(str, offset, value, index, len)
-    count = newCount
-    this
-  }
-
-  /** <p>
-   *    Inserts the string representation of the <code>Any</code> 
-   *    argument into this character sequence.
-   *  </p>
-   *  <p>
-   *    The second argument is converted to a string as if by the method 
-   *    <code>String.valueOf</code>, and the characters of that 
-   *    string are then inserted into this sequence at the indicated 
-   *    offset. 
-   *  </p>
-   *  <p>
-   *    The offset argument must be greater than or equal to 
-   *    <code>0</code>, and less than or equal to the length of this 
-   *    sequence.
-   *  </p>
-   *
-   *  @param  offset  the offset.
-   *  @param  x       an <code>Any</code> value.
-   *  @return         a reference to this object.
-   *  @throws StringIndexOutOfBoundsException  if the offset is invalid.
-   */
-  def insert(at: Int, x: Any): StringBuilder =
-    insert(at, String.valueOf(x))
-
-  /** Inserts the string into this character sequence.
-   *
-   *  @param  at  the offset position.
-   *  @param  x   a string.
-   *  @return     a reference to this object.
-   *  @throws StringIndexOutOfBoundsException  if the offset is invalid.
-   */
-  def insert(at: Int, x: String): StringBuilder = {
-    if (at < 0 || at > count)
-      throw new StringIndexOutOfBoundsException(at)
-    val str = if (x == null) "null" else x
-    val len = str.length
-    val newCount = count + len
-    if (newCount > value.length) expandCapacity(newCount)
-    compat.Platform.arraycopy(value, at, value, at + len, count - at)
-    str.getChars(0, len, value, at)
-    count = newCount
-    this
-  }
-
-  /** Inserts the string representation of the <code>Char</code> sequence 
-   *  argument into this sequence.
-   *
-   *  @param  at  the offset position.
-   *  @param  x   a character sequence.
-   *  @return     a reference to this object.
-   *  @throws StringIndexOutOfBoundsException  if the offset is invalid.
-   */
-  def insert(at: Int, x: Seq[Char]): StringBuilder =
-    insert(at, x.toArray)
-
-  /** Inserts the string representation of the <code>Char</code> array 
-   *  argument into this sequence.
-   *
-   *  @param  at  the offset position.
-   *  @param  x   a character array.
-   *  @return     a reference to this object.
-   *  @throws StringIndexOutOfBoundsException  if the offset is invalid.
-   */
-  def insert(at: Int, x: Array[Char]): StringBuilder = {
-    if (at < 0 || at > count)
-      throw new StringIndexOutOfBoundsException(at)
-    val len = x.length
-    val newCount = count + len
-    if (newCount > value.length) expandCapacity(newCount)
-    compat.Platform.arraycopy(value, at, value, at + len, count - at)
-    compat.Platform.arraycopy(x, 0, value, at, len)
-    count = newCount
-    this
-  }
-
-  /** <p>
-   *    Inserts the string representation of the <code>Boolean</code> argument
-   *    into this sequence.
-   *  </p>
-   *  <p>
-   *    The offset argument must be greater than or equal to 0, and less than
-   *    or equal to the length of this sequence.
-   *  </p>
-   *
-   *  @param  at  the offset position.
-   *  @param  x   a <code>Boolean</code> value.
-   *  @return     a reference to this object.
-   */
-  def insert(at: Int, x: Boolean): StringBuilder =
-    insert(at, String.valueOf(x))
-
-  /** <p>
-   *    Inserts the string representation of the <code>Byte</code> argument
-   *    into this sequence.
-   *  </p>
-   *  <p>
-   *    The offset argument must be greater than or equal to 0, and less than
-   *    or equal to the length of this sequence.
-   *  </p>
-   *
-   *  @param  at  the offset position.
-   *  @param  x   a <code>Byte</code> value.
-   *  @return     a reference to this object.
-   */
-  def insert(at: Int, x: Byte): StringBuilder =
-    insert(at, String.valueOf(x))
-
-  /** <p>
-   *    Inserts the string representation of the <code>Char</code> argument
-   *    into this sequence.
-   *  </p>
-   *  <p>
-   *    The offset argument must be greater than or equal to 0, and less than
-   *    or equal to the length of this sequence.
-   *  </p>
-   *
-   *  @param  at  the offset position.
-   *  @param  x   a <code>Char</code> value.
-   *  @return     a reference to this object.
-   */
-  def insert(at: Int, x: Char): StringBuilder = {
-    if (at < 0 || at > count)
-      throw new StringIndexOutOfBoundsException(at)
-    val newCount = count + 1
-    if (newCount > value.length) expandCapacity(newCount)
-    compat.Platform.arraycopy(value, at, value, at + 1, count - at)
-    value(at) = x
-    count = newCount
-    this
-  }
-
-  /** <p>
-   *    Inserts the string representation of the <code>Short</code> argument
-   *    into this sequence.
-   *  </p>
-   *  <p>
-   *    The offset argument must be greater than or equal to 0, and less than
-   *    or equal to the length of this sequence.
-   *  </p>
-   *
-   *  @param  at  the offset position.
-   *  @param  x   a <code>Short</code> value.
-   *  @return     a reference to this object.
-   */
-  def insert(at: Int, x: Short): StringBuilder =
-    insert(at, String.valueOf(x))
-
-  /** <p>
-   *    Inserts the string representation of the <code>Int</code> argument
-   *    into this sequence.
-   *  </p>
-   *  <p>
-   *    The offset argument must be greater than or equal to 0, and less than
-   *    or equal to the length of this sequence.
-   *  </p>
-   *
-   *  @param  at  the offset position.
-   *  @param  x   a <code>Int</code> value.
-   *  @return     a reference to this object.
-   */
-  def insert(at: Int, x: Int): StringBuilder =
-    insert(at, String.valueOf(x))
-
-  /** <p>
-   *    Inserts the string representation of the <code>Long</code> argument
-   *    into this sequence.
-   *  </p>
-   *  <p>
-   *    The offset argument must be greater than or equal to 0, and less than
-   *    or equal to the length of this sequence.
-   *  </p>
-   *
-   *  @param  at  the offset position.
-   *  @param  x   a <code>Long</code> value.
-   *  @return     a reference to this object.
-   */
-  def insert(at: Int, x: Long): StringBuilder =
-    insert(at, String.valueOf(x))
-
-  /** <p>
-   *    Inserts the string representation of the <code>Float</code> argument
-   *    into this sequence.
-   *  </p>
-   *  <p>
-   *    The offset argument must be greater than or equal to 0, and less than
-   *    or equal to the length of this sequence.
-   *  </p>
-   *
-   *  @param  at  the offset position.
-   *  @param  x   a <code>Float</code> value.
-   *  @return     a reference to this object.
-   */
-  def insert(at: Int, x: Float): StringBuilder =
-    insert(at, String.valueOf(x))
-
-  /** <p>
-   *    Inserts the string representation of the <code>Double</code> argument
-   *    into this sequence.
-   *  </p>
-   *  <p>
-   *    The offset argument must be greater than or equal to 0, and less than
-   *    or equal to the length of this sequence.
-   *  </p>
-   *
-   *  @param  at  the offset position.
-   *  @param  x   a <code>Double</code> value.
-   *  @return     a reference to this object.
-   */
-  def insert(at: Int, x: Double): StringBuilder =
-    insert(at, String.valueOf(x))
-
-  /** <p>
-   *    Returns the index within this string of the first occurrence of the
-   *    specified substring. The integer returned is the smallest value 
-   *    <i>k</i> such that:
-   *  </p>
-   *  <blockquote><pre>
-   *  this.toString().startsWith(str, <i>k</i>)</pre>
-   *  </blockquote>
-   *  <p>
-   *    is <code>true</code>.
-   *  </p>
-   *
-   *  @param  str  any string.
-   *  @return      if the string argument occurs as a substring within this
-   *               object, then the index of the first character of the first
-   *               such substring is returned; if it does not occur as a
-   *               substring, <code>-1</code> is returned.
-   *  @throws NullPointerException if <code>str</code> is <code>null</code>.
-   */
-  def indexOf(str: String): Int = indexOf(str, 0)
-
-  /** <p>
-   *    Returns the index within this string of the first occurrence of the
-   *    specified substring, starting at the specified index. The integer
-   *    returned is the smallest value <code>k</code> for which:
-   *  </p><pre>
-   *    k >= Math.min(fromIndex, str.length()) &&
-   *                   this.toString().startsWith(str, k)</pre>
-   *  <p>
-   *    If no such value of <code>k</code> exists, then <code>-1</code>
-   *    is returned.
-   *  </p>
-   *
-   *  @param str        the substring for which to search.
-   *  @param fromIndex  the index from which to start the search.
-   *  @return           the index within this string of the first occurrence
-   *                    of the specified substring, starting at the specified index.
-   */
-  def indexOf(str: String, fromIndex: Int): Int =
-    StringBuilder.indexOf(value, 0, count, str.toCharArray, 0, str.length(), fromIndex)
-
-  /** <p>
-   *    Returns the index within this string of the rightmost occurrence
-   *    of the specified substring.  The rightmost empty string "" is
-   *    considered to occur at the index value <code>this.length()</code>. 
-   *    The returned index is the largest value <i>k</i> such that 
-   *  </p>
-   *  <blockquote><pre>
-   *  this.toString().startsWith(str, k)</pre>
-   *  </blockquote>
-   *  <p>
-   *    is true.
-   *  </p>
-   *
-   * @param  str  the substring to search for.
-   * @return      if the string argument occurs one or more times as a substring
-   *              within this object, then the index of the first character of
-   *              the last such substring is returned. If it does not occur as
-   *              a substring, <code>-1</code> is returned.
-   * @throws NullPointerException  if <code>str</code> is <code>null</code>.
-   */
-  def lastIndexOf(str: String): Int = lastIndexOf(str, count)
-
-  /** <p>
-   *    Returns the index within this string of the last occurrence of the
-   *    specified substring. The integer returned is the largest value
-   *    <code>k</code> such that:
-   *  </p><pre>
-   *    k <= Math.min(fromIndex, str.length()) &&
-   *                   this.toString().startsWith(str, k)</pre>
-   *  <p>
-   *    If no such value of <code>k</code> exists, then <code>-1</code>
-   *    is returned.
-   *  </p>
-   *
-   *  @param  str        the substring to search for.
-   *  @param  fromIndex  the index to start the search from.
-   *  @return            the index within this sequence of the last occurrence
-   *                     of the specified substring.
-   */
-  def lastIndexOf(str: String, fromIndex: Int): Int =
-    StringBuilder.lastIndexOf(value, 0, count, str.toCharArray, 0, str.length(), fromIndex)
-
-  /** <p>
-   *    Causes this character sequence to be replaced by the reverse of the
-   *    sequence. If there are any surrogate pairs included in the sequence,
-   *    these are treated as single characters for the reverse operation.
-   *    Thus, the order of the high-low surrogates is never reversed.
-   *  </p>
-   *  <p>
-   *    Let <i>n</i> be the character length of this character sequence
-   *    (not the length in <code>Char</code> values) just prior to
-   *    execution of the <code>reverse</code> method. Then the
-   *    character at index <i>k</i> in the new character sequence is
-   *    equal to the character at index <i>n-k-1</i> in the old
-   *    character sequence.
-   *  </p>
-   *
-   *  @return  a reference to this object.
-   */
-  def reverse(): StringBuilder = {
-    var hasSurrogate = false
-    val n = count - 1
-    var j = (n-1) >> 1
-    while (j >= 0) {
-      val temp = value(j)
-      val temp2 = value(n - j)
-      if (!hasSurrogate)
-        hasSurrogate =
-          (temp >= StringBuilder.MIN_SURROGATE && temp <= StringBuilder.MAX_SURROGATE) ||
-       	  (temp2 >= StringBuilder.MIN_SURROGATE && temp2 <= StringBuilder.MAX_SURROGATE)
-      value(j) = temp2
-      value(n - j) = temp
-      j -= 1
-    }
-    if (hasSurrogate) {
-      // Reverse back all valid surrogate pairs
-      var i = 0
-      while (i < count - 1) {
-        val c2 = value(i)
-	if (StringBuilder.isLowSurrogate(c2)) {
-          val c1 = value(i + 1)
-          if (StringBuilder.isHighSurrogate(c1)) {
-            value(i) = c1; i += 1
-            value(i) = c2
-          }
-        }
-        i += 1
-      }
-    }
-    this
-  }
-
-  /** Returns a string representing the data in this sequence.
-   *  A new <code>String</code> object is allocated and initialized to 
-   *  contain the character sequence currently represented by this 
-   *  object. This <code>String</code> is then returned. Subsequent 
-   *  changes to this sequence do not affect the contents of the 
-   *  <code>String</code>.
-   *
-   *  @return  a string representation of this sequence of characters.
-   */
-  override def toString(): String = new String(value, 0, count)
-
-  @throws(classOf[java.io.IOException])
-  private def writeObject(s: java.io.ObjectOutputStream) {
-    s.defaultWriteObject()
-    s.writeInt(count)
-    s.writeObject(value)
-  }
-
-  @throws(classOf[java.io.IOException])
-  private def readObject(s: java.io.ObjectInputStream ) {
-    s.defaultReadObject()
-    count = s.readInt()
-    value = s.readObject().asInstanceOf[Array[Char]]
-  }
-
-}
-
-
-object StringBuilder {
-
-  private val MIN_HIGH_SURROGATE = '\uD800'
-  private val MAX_HIGH_SURROGATE = '\uDBFF'
-
-  private val MIN_LOW_SURROGATE = '\uDC00'
-  private val MAX_LOW_SURROGATE = '\uDFFF'
-
-  // constants <code>java.langCharacter.MIN-/MAX_SURROGATE</code> exist since 1.5
-  private val MIN_SURROGATE = MIN_HIGH_SURROGATE
-  private val MAX_SURROGATE = MAX_LOW_SURROGATE
-
-  // methods <code>java.langCharacter.isLow-/isHighSurrogate</code> exist since 1.5
-  private def isLowSurrogate(ch: Char): Boolean =
-    MIN_LOW_SURROGATE <= ch && ch <= MAX_LOW_SURROGATE
-
-  private def isHighSurrogate(ch: Char): Boolean =
-    MIN_HIGH_SURROGATE <= ch && ch <= MAX_HIGH_SURROGATE
-
-  // method <code>java.util.Arrays.copyOf</code> exists since 1.6
-  private def copyOf(src: Array[Char], newLength: Int): Array[Char] = {
-    val dest = new Array[Char](newLength)
-    compat.Platform.arraycopy(src, 0, dest, 0, Math.min(src.length, newLength))
-    dest
-  }
-
-  private def indexOf(source: Array[Char], sourceOffset: Int, sourceCount: Int,
-                      target: Array[Char], targetOffset: Int, targetCount: Int,
-                      fromIndex: Int): Int =
-    if (fromIndex >= sourceCount)
-      if (targetCount == 0) sourceCount else -1
-    else {
-      val inx = if (fromIndex < 0) 0 else fromIndex
-      if (targetCount == 0)
-        inx
-      else {
-        val first  = target(targetOffset)
-        val max = sourceOffset + (sourceCount - targetCount)
-
-        var i = sourceOffset + inx
-        while (i <= max) {
-          /* Look for first character. */
-          if (source(i) != first) {
-            i += 1
-            while (i <= max && source(i) != first) i += 1
-          }
-          /* Found first character, now look at the rest of v2 */
-          if (i <= max) {
-            var j = i + 1
-            val end = j + targetCount - 1
-            var k = targetOffset + 1
-            while (j < end && source(j) == target(k)) {
-              j += 1
-              k += 1
-            }
-            if (j == end) {
-              /* Found whole string. */
-              return i - sourceOffset
-            }
-          } // if
-          i += 1
-        } // while
-        -1
-      }
-    }
-
-  private def lastIndexOf(source: Array[Char], sourceOffset: Int, sourceCount: Int,
-                          target: Array[Char], targetOffset: Int, targetCount: Int,
-                          fromIndex: Int): Int = {
-    val rightIndex = sourceCount - targetCount
-    if (fromIndex < 0) return -1
-    val inx = if (fromIndex > rightIndex) rightIndex else fromIndex
-    // Empty string always matches
-    if (targetCount == 0) return inx
-
-    val strLastIndex = targetOffset + targetCount - 1
-    val strLastChar = target(strLastIndex)
-    val min = sourceOffset + targetCount - 1
-    var i = min + fromIndex
-
-    while (true) {
-      while (i >= min && source(i) != strLastChar) i -= 1
-      if (i < min) return -1
-      var j = i - 1
-      val start = j - (targetCount - 1)
-      var k = strLastIndex - 1
-      var outerWhile = false
-      while (j > start && !outerWhile) {
-        if (source(j) != target(k)) {
-          j -= 1
-          k -= 1
-          i -= 1
-          outerWhile = true
-        }
-      }
-      if (!outerWhile) return start - sourceOffset + 1
-    }
-    -1
-  }
-
-  implicit def toCharSequence(sb: StringBuilder): java.lang.CharSequence = new java.lang.CharSequence {
-    def length: Int = sb.length
-    def charAt(index: Int): Char = sb.charAt(index)
-    def subSequence(start: Int, end: Int): java.lang.CharSequence = sb.substring(start, end)
-    override def toString: String = sb.toString
-  }
-}
diff --git a/src/library/scala/Symbol.scala b/src/library/scala/Symbol.scala
index 0ab75f3..0dcc838 100644
--- a/src/library/scala/Symbol.scala
+++ b/src/library/scala/Symbol.scala
@@ -1,20 +1,15 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Symbol.scala 16881 2009-01-09 16:28:11Z cunei $
 
 
 package scala
 
-import scala.collection.jcl
-
-private[scala] object internedSymbols extends jcl.WeakHashMap[String, ref.WeakReference[Symbol]]
-
 /** <p>
  *    This class provides a simple way to get unique objects for
  *    equal strings. Since symbols are interned, they can be compared using
@@ -34,7 +29,6 @@ private[scala] object internedSymbols extends jcl.WeakHashMap[String, ref.WeakRe
  */
 @serializable
 final class Symbol private (val name: String) {
-
   /** Converts this symbol to a string.
    */
   override def toString(): String = "'" + name
@@ -43,27 +37,55 @@ final class Symbol private (val name: String) {
   private def readResolve(): Any = Symbol.apply(name)
 }
 
-object Symbol {
+object Symbol extends UniquenessCache[String, Symbol]
+{
+  protected def valueFromKey(name: String): Symbol = new Symbol(name)
+  protected def keyFromValue(sym: Symbol): Option[String] = Some(sym.name)
+}
 
-  /** <p>
-   *    Makes this symbol into a unique reference.
-   *  </p>
-   *  <p>
-   *    If two interened symbols are equal (i.e. they have the same name)
-   *    then they must be identical (wrt reference equality).
-   *  </p>
-   *
-   *  @return the unique reference to this string.
-   */
-  def apply(name: String): Symbol = internedSymbols.synchronized {
-    internedSymbols.get(name).flatMap(_.get) match {
-    case Some(sym) => sym 
-    case _ =>
-      val sym = new Symbol(name)
-      internedSymbols(name) = new ref.WeakReference(sym)
-      sym
+/** This is private so it won't appear in the library API, but
+  * abstracted to offer some hope of reusability.  */
+private[scala] abstract class UniquenessCache[K, V >: Null]
+{
+  import java.lang.ref.WeakReference
+  import java.util.WeakHashMap
+  import java.util.concurrent.locks.ReentrantReadWriteLock
+  
+  private val rwl = new ReentrantReadWriteLock()
+  private val rlock = rwl.readLock
+  private val wlock = rwl.writeLock
+  private val map = new WeakHashMap[K, WeakReference[V]]
+  
+  protected def valueFromKey(k: K): V
+  protected def keyFromValue(v: V): Option[K]
+  
+  def apply(name: K): V = {
+    def cached(): V = {
+      rlock.lock
+      try {
+        val reference = map get name
+        if (reference == null) null
+        else reference.get  // will be null if we were gc-ed
+      }
+      finally rlock.unlock
+    }
+    def updateCache(): V = {
+      wlock.lock
+      try {
+        val res = cached()
+        if (res != null) res
+        else {        
+          val sym = valueFromKey(name)
+          map.put(name, new WeakReference(sym))
+          sym
+        }
+      }
+      finally wlock.unlock
     }
+    
+    val res = cached()
+    if (res == null) updateCache()
+    else res
   }
-
-  def unapply(other: Symbol): Option[String] = Some(other.name)
+  def unapply(other: V): Option[K] = keyFromValue(other)
 }
diff --git a/src/library/scala/Tuple1.scala b/src/library/scala/Tuple1.scala
index 22afc34..9b981dc 100644
--- a/src/library/scala/Tuple1.scala
+++ b/src/library/scala/Tuple1.scala
@@ -1,28 +1,25 @@
-
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Tuple1.scala 16881 2009-01-09 16:28:11Z cunei $
 
-// generated by genprod on Wed Apr 23 10:06:16 CEST 2008  
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  
 
 package scala
 
+
+
+
 /** Tuple1 is the canonical representation of a @see Product1 
  *  
  */
-case class Tuple1[+T1](_1:T1) 
-  extends Product1[T1]  {
-
-   override def toString() = {
-     val sb = new StringBuilder
-     sb.append('(').append(_1).append(",)")
-     sb.toString
-   }
+case class Tuple1[@specialized(Int, Long, Double) +T1](_1:T1)
+  extends Product1[T1]
+{  
+  override def toString() = "(" + _1 + ")"  
   
 }
diff --git a/src/library/scala/Tuple10.scala b/src/library/scala/Tuple10.scala
index 7ac041d..0a1b0eb 100644
--- a/src/library/scala/Tuple10.scala
+++ b/src/library/scala/Tuple10.scala
@@ -1,28 +1,25 @@
-
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Tuple10.scala 16881 2009-01-09 16:28:11Z cunei $
 
-// generated by genprod on Wed Apr 23 10:06:16 CEST 2008  
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  
 
 package scala
 
+
+
+
 /** Tuple10 is the canonical representation of a @see Product10 
  *  
  */
-case class Tuple10[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10](_1:T1, _2:T2, _3:T3, _4:T4, _5:T5, _6:T6, _7:T7, _8:T8, _9:T9, _10:T10) 
-  extends Product10[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]  {
-
-   override def toString() = {
-     val sb = new StringBuilder
-     sb.append('(').append(_1).append(',').append(_2).append(',').append(_3).append(',').append(_4).append(',').append(_5).append(',').append(_6).append(',').append(_7).append(',').append(_8).append(',').append(_9).append(',').append(_10).append(')')
-     sb.toString
-   }
+case class Tuple10[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10](_1:T1,_2:T2,_3:T3,_4:T4,_5:T5,_6:T6,_7:T7,_8:T8,_9:T9,_10:T10)
+  extends Product10[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]
+{  
+  override def toString() = "(" + _1 + "," + _2 + "," + _3 + "," + _4 + "," + _5 + "," + _6 + "," + _7 + "," + _8 + "," + _9 + "," + _10 + ")"  
   
 }
diff --git a/src/library/scala/Tuple11.scala b/src/library/scala/Tuple11.scala
index 2dc5362..2628818 100644
--- a/src/library/scala/Tuple11.scala
+++ b/src/library/scala/Tuple11.scala
@@ -1,28 +1,25 @@
-
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Tuple11.scala 16881 2009-01-09 16:28:11Z cunei $
 
-// generated by genprod on Wed Apr 23 10:06:16 CEST 2008  
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  
 
 package scala
 
+
+
+
 /** Tuple11 is the canonical representation of a @see Product11 
  *  
  */
-case class Tuple11[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11](_1:T1, _2:T2, _3:T3, _4:T4, _5:T5, _6:T6, _7:T7, _8:T8, _9:T9, _10:T10, _11:T11) 
-  extends Product11[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11]  {
-
-   override def toString() = {
-     val sb = new StringBuilder
-     sb.append('(').append(_1).append(',').append(_2).append(',').append(_3).append(',').append(_4).append(',').append(_5).append(',').append(_6).append(',').append(_7).append(',').append(_8).append(',').append(_9).append(',').append(_10).append(',').append(_11).append(')')
-     sb.toString
-   }
+case class Tuple11[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11](_1:T1,_2:T2,_3:T3,_4:T4,_5:T5,_6:T6,_7:T7,_8:T8,_9:T9,_10:T10,_11:T11)
+  extends Product11[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11]
+{  
+  override def toString() = "(" + _1 + "," + _2 + "," + _3 + "," + _4 + "," + _5 + "," + _6 + "," + _7 + "," + _8 + "," + _9 + "," + _10 + "," + _11 + ")"  
   
 }
diff --git a/src/library/scala/Tuple12.scala b/src/library/scala/Tuple12.scala
index d84b5e5..874cf79 100644
--- a/src/library/scala/Tuple12.scala
+++ b/src/library/scala/Tuple12.scala
@@ -1,28 +1,26 @@
-
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Tuple12.scala 16881 2009-01-09 16:28:11Z cunei $
 
-// generated by genprod on Wed Apr 23 10:06:16 CEST 2008  
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  
 
 package scala
 
+
+
+
 /** Tuple12 is the canonical representation of a @see Product12 
  *  
  */
-case class Tuple12[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12](_1:T1, _2:T2, _3:T3, _4:T4, _5:T5, _6:T6, _7:T7, _8:T8, _9:T9, _10:T10, _11:T11, _12:T12) 
-  extends Product12[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12]  {
-
-   override def toString() = {
-     val sb = new StringBuilder
-     sb.append('(').append(_1).append(',').append(_2).append(',').append(_3).append(',').append(_4).append(',').append(_5).append(',').append(_6).append(',').append(_7).append(',').append(_8).append(',').append(_9).append(',').append(_10).append(',').append(_11).append(',').append(_12).append(')')
-     sb.toString
-   }
+case class Tuple12[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12](_1:T1,_2:T2,_3:T3,_4:T4,_5:T5,_6:T6,_7:T7,_8:T8,_9:T9,_10:T10,_11:T11,_12:T12)
+  extends Product12[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12]
+{  
+  override def toString() = "(" + _1 + "," + _2 + "," + _3 + "," + _4 + "," + _5 + "," + _6 +
+    "," + _7 + "," + _8 + "," + _9 + "," + _10 + "," + _11 + "," + _12 + ")"  
   
 }
diff --git a/src/library/scala/Tuple13.scala b/src/library/scala/Tuple13.scala
index 53be587..24ddf7c 100644
--- a/src/library/scala/Tuple13.scala
+++ b/src/library/scala/Tuple13.scala
@@ -1,28 +1,26 @@
-
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Tuple13.scala 16881 2009-01-09 16:28:11Z cunei $
 
-// generated by genprod on Wed Apr 23 10:06:16 CEST 2008  
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  
 
 package scala
 
+
+
+
 /** Tuple13 is the canonical representation of a @see Product13 
  *  
  */
-case class Tuple13[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +T13](_1:T1, _2:T2, _3:T3, _4:T4, _5:T5, _6:T6, _7:T7, _8:T8, _9:T9, _10:T10, _11:T11, _12:T12, _13:T13) 
-  extends Product13[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13]  {
-
-   override def toString() = {
-     val sb = new StringBuilder
-     sb.append('(').append(_1).append(',').append(_2).append(',').append(_3).append(',').append(_4).append(',').append(_5).append(',').append(_6).append(',').append(_7).append(',').append(_8).append(',').append(_9).append(',').append(_10).append(',').append(_11).append(',').append(_12).append(',').append(_13).append(')')
-     sb.toString
-   }
+case class Tuple13[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +T13](_1:T1,_2:T2,_3:T3,_4:T4,_5:T5,_6:T6,_7:T7,_8:T8,_9:T9,_10:T10,_11:T11,_12:T12,_13:T13)
+  extends Product13[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13]
+{  
+  override def toString() = "(" + _1 + "," + _2 + "," + _3 + "," + _4 + "," + _5 + "," + _6 +
+    "," + _7 + "," + _8 + "," + _9 + "," + _10 + "," + _11 + "," + _12 + "," + _13 + ")"  
   
 }
diff --git a/src/library/scala/Tuple14.scala b/src/library/scala/Tuple14.scala
index b5fca57..8a29e40 100644
--- a/src/library/scala/Tuple14.scala
+++ b/src/library/scala/Tuple14.scala
@@ -1,28 +1,26 @@
-
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Tuple14.scala 16881 2009-01-09 16:28:11Z cunei $
 
-// generated by genprod on Wed Apr 23 10:06:16 CEST 2008  
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  
 
 package scala
 
+
+
+
 /** Tuple14 is the canonical representation of a @see Product14 
  *  
  */
-case class Tuple14[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +T13, +T14](_1:T1, _2:T2, _3:T3, _4:T4, _5:T5, _6:T6, _7:T7, _8:T8, _9:T9, _10:T10, _11:T11, _12:T12, _13:T13, _14:T14) 
-  extends Product14[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14]  {
-
-   override def toString() = {
-     val sb = new StringBuilder
-     sb.append('(').append(_1).append(',').append(_2).append(',').append(_3).append(',').append(_4).append(',').append(_5).append(',').append(_6).append(',').append(_7).append(',').append(_8).append(',').append(_9).append(',').append(_10).append(',').append(_11).append(',').append(_12).append(',').append(_13).append(',').append(_14).append(')')
-     sb.toString
-   }
+case class Tuple14[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +T13, +T14](_1:T1,_2:T2,_3:T3,_4:T4,_5:T5,_6:T6,_7:T7,_8:T8,_9:T9,_10:T10,_11:T11,_12:T12,_13:T13,_14:T14)
+  extends Product14[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14]
+{  
+  override def toString() = "(" + _1 + "," + _2 + "," + _3 + "," + _4 + "," + _5 + "," + _6 + "," + _7 +
+    "," + _8 + "," + _9 + "," + _10 + "," + _11 + "," + _12 + "," + _13 + "," + _14 + ")"  
   
 }
diff --git a/src/library/scala/Tuple15.scala b/src/library/scala/Tuple15.scala
index 3386631..e587fd5 100644
--- a/src/library/scala/Tuple15.scala
+++ b/src/library/scala/Tuple15.scala
@@ -1,28 +1,26 @@
-
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Tuple15.scala 16881 2009-01-09 16:28:11Z cunei $
 
-// generated by genprod on Wed Apr 23 10:06:16 CEST 2008  
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  
 
 package scala
 
+
+
+
 /** Tuple15 is the canonical representation of a @see Product15 
  *  
  */
-case class Tuple15[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +T13, +T14, +T15](_1:T1, _2:T2, _3:T3, _4:T4, _5:T5, _6:T6, _7:T7, _8:T8, _9:T9, _10:T10, _11:T11, _12:T12, _13:T13, _14:T14, _15:T15) 
-  extends Product15[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15]  {
-
-   override def toString() = {
-     val sb = new StringBuilder
-     sb.append('(').append(_1).append(',').append(_2).append(',').append(_3).append(',').append(_4).append(',').append(_5).append(',').append(_6).append(',').append(_7).append(',').append(_8).append(',').append(_9).append(',').append(_10).append(',').append(_11).append(',').append(_12).append(',').append(_13).append(',').append(_14).append(',').append(_15).append(')')
-     sb.toString
-   }
+case class Tuple15[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +T13, +T14, +T15](_1:T1,_2:T2,_3:T3,_4:T4,_5:T5,_6:T6,_7:T7,_8:T8,_9:T9,_10:T10,_11:T11,_12:T12,_13:T13,_14:T14,_15:T15)
+  extends Product15[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15]
+{  
+  override def toString() = "(" + _1 + "," + _2 + "," + _3 + "," + _4 + "," + _5 + "," + _6 + "," + _7 +
+    "," + _8 + "," + _9 + "," + _10 + "," + _11 + "," + _12 + "," + _13 + "," + _14 + "," + _15 + ")"  
   
 }
diff --git a/src/library/scala/Tuple16.scala b/src/library/scala/Tuple16.scala
index 174aa62..f48b420 100644
--- a/src/library/scala/Tuple16.scala
+++ b/src/library/scala/Tuple16.scala
@@ -1,28 +1,26 @@
-
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Tuple16.scala 16881 2009-01-09 16:28:11Z cunei $
 
-// generated by genprod on Wed Apr 23 10:06:16 CEST 2008  
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  
 
 package scala
 
+
+
+
 /** Tuple16 is the canonical representation of a @see Product16 
  *  
  */
-case class Tuple16[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +T13, +T14, +T15, +T16](_1:T1, _2:T2, _3:T3, _4:T4, _5:T5, _6:T6, _7:T7, _8:T8, _9:T9, _10:T10, _11:T11, _12:T12, _13:T13, _14:T14, _15:T15, _16:T16) 
-  extends Product16[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16]  {
-
-   override def toString() = {
-     val sb = new StringBuilder
-     sb.append('(').append(_1).append(',').append(_2).append(',').append(_3).append(',').append(_4).append(',').append(_5).append(',').append(_6).append(',').append(_7).append(',').append(_8).append(',').append(_9).append(',').append(_10).append(',').append(_11).append(',').append(_12).append(',').append(_13).append(',').append(_14).append(',').append(_15).append(',').append(_16).append(')')
-     sb.toString
-   }
+case class Tuple16[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +T13, +T14, +T15, +T16](_1:T1,_2:T2,_3:T3,_4:T4,_5:T5,_6:T6,_7:T7,_8:T8,_9:T9,_10:T10,_11:T11,_12:T12,_13:T13,_14:T14,_15:T15,_16:T16)
+  extends Product16[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16]
+{  
+  override def toString() = "(" + _1 + "," + _2 + "," + _3 + "," + _4 + "," + _5 + "," + _6 + "," + _7 + "," + _8 +
+    "," + _9 + "," + _10 + "," + _11 + "," + _12 + "," + _13 + "," + _14 + "," + _15 + "," + _16 + ")"  
   
 }
diff --git a/src/library/scala/Tuple17.scala b/src/library/scala/Tuple17.scala
index 084f1c7..c55d0e2 100644
--- a/src/library/scala/Tuple17.scala
+++ b/src/library/scala/Tuple17.scala
@@ -1,28 +1,26 @@
-
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Tuple17.scala 16881 2009-01-09 16:28:11Z cunei $
 
-// generated by genprod on Wed Apr 23 10:06:16 CEST 2008  
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  
 
 package scala
 
+
+
+
 /** Tuple17 is the canonical representation of a @see Product17 
  *  
  */
-case class Tuple17[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +T13, +T14, +T15, +T16, +T17](_1:T1, _2:T2, _3:T3, _4:T4, _5:T5, _6:T6, _7:T7, _8:T8, _9:T9, _10:T10, _11:T11, _12:T12, _13:T13, _14:T14, _15:T15, _16:T16, _17:T17) 
-  extends Product17[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17]  {
-
-   override def toString() = {
-     val sb = new StringBuilder
-     sb.append('(').append(_1).append(',').append(_2).append(',').append(_3).append(',').append(_4).append(',').append(_5).append(',').append(_6).append(',').append(_7).append(',').append(_8).append(',').append(_9).append(',').append(_10).append(',').append(_11).append(',').append(_12).append(',').append(_13).append(',').append(_14).append(',').append(_15).append(',').append(_16).append(',').append(_17).append(')')
-     sb.toString
-   }
+case class Tuple17[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +T13, +T14, +T15, +T16, +T17](_1:T1,_2:T2,_3:T3,_4:T4,_5:T5,_6:T6,_7:T7,_8:T8,_9:T9,_10:T10,_11:T11,_12:T12,_13:T13,_14:T14,_15:T15,_16:T16,_17:T17)
+  extends Product17[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17]
+{  
+  override def toString() = "(" + _1 + "," + _2 + "," + _3 + "," + _4 + "," + _5 + "," + _6 + "," + _7 + "," + _8 +
+    "," + _9 + "," + _10 + "," + _11 + "," + _12 + "," + _13 + "," + _14 + "," + _15 + "," + _16 + "," + _17 + ")"  
   
 }
diff --git a/src/library/scala/Tuple18.scala b/src/library/scala/Tuple18.scala
index 236446f..71e2df3 100644
--- a/src/library/scala/Tuple18.scala
+++ b/src/library/scala/Tuple18.scala
@@ -1,28 +1,26 @@
-
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Tuple18.scala 16881 2009-01-09 16:28:11Z cunei $
 
-// generated by genprod on Wed Apr 23 10:06:16 CEST 2008  
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  
 
 package scala
 
+
+
+
 /** Tuple18 is the canonical representation of a @see Product18 
  *  
  */
-case class Tuple18[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +T13, +T14, +T15, +T16, +T17, +T18](_1:T1, _2:T2, _3:T3, _4:T4, _5:T5, _6:T6, _7:T7, _8:T8, _9:T9, _10:T10, _11:T11, _12:T12, _13:T13, _14:T14, _15:T15, _16:T16, _17:T17, _18:T18) 
-  extends Product18[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18]  {
-
-   override def toString() = {
-     val sb = new StringBuilder
-     sb.append('(').append(_1).append(',').append(_2).append(',').append(_3).append(',').append(_4).append(',').append(_5).append(',').append(_6).append(',').append(_7).append(',').append(_8).append(',').append(_9).append(',').append(_10).append(',').append(_11).append(',').append(_12).append(',').append(_13).append(',').append(_14).append(',').append(_15).append(',').append(_16).append(',').append(_17).append(',').append(_18).append(')')
-     sb.toString
-   }
+case class Tuple18[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +T13, +T14, +T15, +T16, +T17, +T18](_1:T1,_2:T2,_3:T3,_4:T4,_5:T5,_6:T6,_7:T7,_8:T8,_9:T9,_10:T10,_11:T11,_12:T12,_13:T13,_14:T14,_15:T15,_16:T16,_17:T17,_18:T18)
+  extends Product18[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18]
+{  
+  override def toString() = "(" + _1 + "," + _2 + "," + _3 + "," + _4 + "," + _5 + "," + _6 + "," + _7 + "," + _8 + "," + _9 +
+    "," + _10 + "," + _11 + "," + _12 + "," + _13 + "," + _14 + "," + _15 + "," + _16 + "," + _17 + "," + _18 + ")"  
   
 }
diff --git a/src/library/scala/Tuple19.scala b/src/library/scala/Tuple19.scala
index f8cfb17..a0b7671 100644
--- a/src/library/scala/Tuple19.scala
+++ b/src/library/scala/Tuple19.scala
@@ -1,28 +1,26 @@
-
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Tuple19.scala 16881 2009-01-09 16:28:11Z cunei $
 
-// generated by genprod on Wed Apr 23 10:06:16 CEST 2008  
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  
 
 package scala
 
+
+
+
 /** Tuple19 is the canonical representation of a @see Product19 
  *  
  */
-case class Tuple19[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +T13, +T14, +T15, +T16, +T17, +T18, +T19](_1:T1, _2:T2, _3:T3, _4:T4, _5:T5, _6:T6, _7:T7, _8:T8, _9:T9, _10:T10, _11:T11, _12:T12, _13:T13, _14:T14, _15:T15, _16:T16, _17:T17, _18:T18, _19:T19) 
-  extends Product19[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19]  {
-
-   override def toString() = {
-     val sb = new StringBuilder
-     sb.append('(').append(_1).append(',').append(_2).append(',').append(_3).append(',').append(_4).append(',').append(_5).append(',').append(_6).append(',').append(_7).append(',').append(_8).append(',').append(_9).append(',').append(_10).append(',').append(_11).append(',').append(_12).append(',').append(_13).append(',').append(_14).append(',').append(_15).append(',').append(_16).append(',').append(_17).append(',').append(_18).append(',').append(_19).append(')')
-     sb.toString
-   }
+case class Tuple19[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +T13, +T14, +T15, +T16, +T17, +T18, +T19](_1:T1,_2:T2,_3:T3,_4:T4,_5:T5,_6:T6,_7:T7,_8:T8,_9:T9,_10:T10,_11:T11,_12:T12,_13:T13,_14:T14,_15:T15,_16:T16,_17:T17,_18:T18,_19:T19)
+  extends Product19[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19]
+{  
+  override def toString() = "(" + _1 + "," + _2 + "," + _3 + "," + _4 + "," + _5 + "," + _6 + "," + _7 + "," + _8 + "," + _9 +
+    "," + _10 + "," + _11 + "," + _12 + "," + _13 + "," + _14 + "," + _15 + "," + _16 + "," + _17 + "," + _18 + "," + _19 + ")"  
   
 }
diff --git a/src/library/scala/Tuple2.scala b/src/library/scala/Tuple2.scala
index 84aaf9e..644c9f5 100644
--- a/src/library/scala/Tuple2.scala
+++ b/src/library/scala/Tuple2.scala
@@ -1,31 +1,126 @@
-
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Tuple2.scala 16881 2009-01-09 16:28:11Z cunei $
 
-// generated by genprod on Wed Apr 23 10:06:16 CEST 2008  (with extra methods)
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  (with extra methods)
 
 package scala
 
+import scala.collection.{TraversableLike, IterableLike, IndexedSeqLike}
+import scala.collection.generic.CanBuildFrom
+
+
+
+
 /** Tuple2 is the canonical representation of a @see Product2 
  *  
  */
-case class Tuple2[+T1, +T2](_1:T1, _2:T2) 
-  extends Product2[T1, T2]  {
-
-   override def toString() = {
-     val sb = new StringBuilder
-     sb.append('(').append(_1).append(',').append(_2).append(')')
-     sb.toString
-   }
+case class Tuple2[@specialized(Int, Long, Double) +T1, @specialized(Int, Long, Double) +T2](_1:T1,_2:T2)
+  extends Product2[T1, T2]
+{  
+  override def toString() = "(" + _1 + "," + _2 + ")"  
   
   /** Swap the elements of the tuple */
   def swap: Tuple2[T2,T1] = Tuple2(_2, _1)
 
+  def zip[Repr1, El1, El2, To](implicit w1:   T1 => TraversableLike[El1, Repr1],
+                                        w2:   T2 => Iterable[El2],
+                                        cbf1: CanBuildFrom[Repr1, (El1, El2), To]): To = {
+    val coll1: TraversableLike[El1, Repr1] = _1
+    val coll2: Iterable[El2] = _2
+    val b1 = cbf1(coll1.repr)
+    val elems2 = coll2.iterator
+
+    for(el1 <- coll1)
+      if(elems2.hasNext)
+        b1 += ((el1, elems2.next))
+
+    b1.result
+  }
+
+  /** Wraps a tuple in a `Zipped`, which supports 2-ary generalisations of map, flatMap, filter,...
+   *
+   * @see Zipped
+   * $willNotTerminateInf
+   */
+  def zipped[Repr1, El1, Repr2, El2](implicit w1: T1 => TraversableLike[El1, Repr1], w2: T2 => IterableLike[El2, Repr2]): Zipped[Repr1, El1, Repr2, El2]
+    = new Zipped[Repr1, El1, Repr2, El2](_1, _2)
+
+  class Zipped[+Repr1, +El1, +Repr2, +El2](coll1: TraversableLike[El1, Repr1], coll2: IterableLike[El2, Repr2]) { // coll2: IterableLike for filter
+    def map[B, To](f: (El1, El2) => B)(implicit cbf: CanBuildFrom[Repr1, B, To]): To = {
+      val b = cbf(coll1.repr)
+      b.sizeHint(coll1)
+      val elems2 = coll2.iterator
+      for(el1 <- coll1)
+       if(elems2.hasNext)
+         b += f(el1, elems2.next)
+
+      b.result
+    }
+
+    def flatMap[B, To](f: (El1, El2) => Traversable[B])(implicit cbf: CanBuildFrom[Repr1, B, To]): To = {
+      val b = cbf(coll1.repr)
+      val elems2 = coll2.iterator
+
+      for(el1 <- coll1)
+       if(elems2.hasNext)
+         b ++= f(el1, elems2.next)
+
+      b.result
+    }
+
+    def filter[To1, To2](f: (El1, El2) => Boolean)(implicit cbf1: CanBuildFrom[Repr1, El1, To1], cbf2: CanBuildFrom[Repr2, El2, To2]): (To1, To2) = {
+      val b1 = cbf1(coll1.repr)
+      val b2 = cbf2(coll2.repr)
+      val elems2 = coll2.iterator
+
+      for(el1 <- coll1) {
+        if(elems2.hasNext) {
+          val el2 = elems2.next
+          if(f(el1, el2)) {
+            b1 += el1
+            b2 += el2
+          }
+        }
+      }
+
+      (b1.result, b2.result)
+    }
+
+    def exists(f: (El1, El2) => Boolean): Boolean = {
+      var acc = false
+      val elems2 = coll2.iterator
+
+      for(el1 <- coll1)
+       if(!acc && elems2.hasNext)
+         acc = f(el1, elems2.next)
+
+      acc
+    }
+
+    def forall(f: (El1, El2) => Boolean): Boolean = {
+      var acc = true
+      val elems2 = coll2.iterator
+
+      for(el1 <- coll1)
+       if(acc && elems2.hasNext)
+         acc = f(el1, elems2.next)
+
+      acc
+    }
+
+    def foreach[U](f: (El1, El2) => U): Unit = {
+      val elems2 = coll2.iterator
+
+      for(el1 <- coll1)
+       if(elems2.hasNext)
+         f(el1, elems2.next)
+    }
+  }
+
 }
diff --git a/src/library/scala/Tuple20.scala b/src/library/scala/Tuple20.scala
index 2654739..763b28f 100644
--- a/src/library/scala/Tuple20.scala
+++ b/src/library/scala/Tuple20.scala
@@ -1,28 +1,26 @@
-
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Tuple20.scala 16881 2009-01-09 16:28:11Z cunei $
 
-// generated by genprod on Wed Apr 23 10:06:16 CEST 2008  
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  
 
 package scala
 
+
+
+
 /** Tuple20 is the canonical representation of a @see Product20 
  *  
  */
-case class Tuple20[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +T13, +T14, +T15, +T16, +T17, +T18, +T19, +T20](_1:T1, _2:T2, _3:T3, _4:T4, _5:T5, _6:T6, _7:T7, _8:T8, _9:T9, _10:T10, _11:T11, _12:T12, _13:T13, _14:T14, _15:T15, _16:T16, _17:T17, _18:T18, _19:T19, _20:T20) 
-  extends Product20[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20]  {
-
-   override def toString() = {
-     val sb = new StringBuilder
-     sb.append('(').append(_1).append(',').append(_2).append(',').append(_3).append(',').append(_4).append(',').append(_5).append(',').append(_6).append(',').append(_7).append(',').append(_8).append(',').append(_9).append(',').append(_10).append(',').append(_11).append(',').append(_12).append(',').append(_13).append(',').append(_14).append(',').append(_15).append(',').append(_16).append(',').append(_17).append(',').append(_18).append(',').append(_19).append(',').append(_20).append(')')
-     sb.toString
-   }
+case class Tuple20[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +T13, +T14, +T15, +T16, +T17, +T18, +T19, +T20](_1:T1,_2:T2,_3:T3,_4:T4,_5:T5,_6:T6,_7:T7,_8:T8,_9:T9,_10:T10,_11:T11,_12:T12,_13:T13,_14:T14,_15:T15,_16:T16,_17:T17,_18:T18,_19:T19,_20:T20)
+  extends Product20[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20]
+{  
+  override def toString() = "(" + _1 + "," + _2 + "," + _3 + "," + _4 + "," + _5 + "," + _6 + "," + _7 + "," + _8 + "," + _9 + "," + _10 +
+    "," + _11 + "," + _12 + "," + _13 + "," + _14 + "," + _15 + "," + _16 + "," + _17 + "," + _18 + "," + _19 + "," + _20 + ")"  
   
 }
diff --git a/src/library/scala/Tuple21.scala b/src/library/scala/Tuple21.scala
index 809b114..e5b7ea9 100644
--- a/src/library/scala/Tuple21.scala
+++ b/src/library/scala/Tuple21.scala
@@ -1,28 +1,26 @@
-
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Tuple21.scala 16881 2009-01-09 16:28:11Z cunei $
 
-// generated by genprod on Wed Apr 23 10:06:16 CEST 2008  
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  
 
 package scala
 
+
+
+
 /** Tuple21 is the canonical representation of a @see Product21 
  *  
  */
-case class Tuple21[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +T13, +T14, +T15, +T16, +T17, +T18, +T19, +T20, +T21](_1:T1, _2:T2, _3:T3, _4:T4, _5:T5, _6:T6, _7:T7, _8:T8, _9:T9, _10:T10, _11:T11, _12:T12, _13:T13, _14:T14, _15:T15, _16:T16, _17:T17, _18:T18, _19:T19, _20:T20, _21:T21) 
-  extends Product21[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21]  {
-
-   override def toString() = {
-     val sb = new StringBuilder
-     sb.append('(').append(_1).append(',').append(_2).append(',').append(_3).append(',').append(_4).append(',').append(_5).append(',').append(_6).append(',').append(_7).append(',').append(_8).append(',').append(_9).append(',').append(_10).append(',').append(_11).append(',').append(_12).append(',').append(_13).append(',').append(_14).append(',').append(_15).append(',').append(_16).append(',').append(_17).append(',').append(_18).append(',').append(_19).append(',').append(_20).append(',').a [...]
-     sb.toString
-   }
+case class Tuple21[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +T13, +T14, +T15, +T16, +T17, +T18, +T19, +T20, +T21](_1:T1,_2:T2,_3:T3,_4:T4,_5:T5,_6:T6,_7:T7,_8:T8,_9:T9,_10:T10,_11:T11,_12:T12,_13:T13,_14:T14,_15:T15,_16:T16,_17:T17,_18:T18,_19:T19,_20:T20,_21:T21)
+  extends Product21[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21]
+{  
+  override def toString() = "(" + _1 + "," + _2 + "," + _3 + "," + _4 + "," + _5 + "," + _6 + "," + _7 + "," + _8 + "," + _9 + "," + _10 +
+    "," + _11 + "," + _12 + "," + _13 + "," + _14 + "," + _15 + "," + _16 + "," + _17 + "," + _18 + "," + _19 + "," + _20 + "," + _21 + ")"  
   
 }
diff --git a/src/library/scala/Tuple22.scala b/src/library/scala/Tuple22.scala
index de08e9b..56eb478 100644
--- a/src/library/scala/Tuple22.scala
+++ b/src/library/scala/Tuple22.scala
@@ -1,28 +1,26 @@
-
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Tuple22.scala 16881 2009-01-09 16:28:11Z cunei $
 
-// generated by genprod on Wed Apr 23 10:06:16 CEST 2008  
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  
 
 package scala
 
+
+
+
 /** Tuple22 is the canonical representation of a @see Product22 
  *  
  */
-case class Tuple22[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +T13, +T14, +T15, +T16, +T17, +T18, +T19, +T20, +T21, +T22](_1:T1, _2:T2, _3:T3, _4:T4, _5:T5, _6:T6, _7:T7, _8:T8, _9:T9, _10:T10, _11:T11, _12:T12, _13:T13, _14:T14, _15:T15, _16:T16, _17:T17, _18:T18, _19:T19, _20:T20, _21:T21, _22:T22) 
-  extends Product22[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22]  {
-
-   override def toString() = {
-     val sb = new StringBuilder
-     sb.append('(').append(_1).append(',').append(_2).append(',').append(_3).append(',').append(_4).append(',').append(_5).append(',').append(_6).append(',').append(_7).append(',').append(_8).append(',').append(_9).append(',').append(_10).append(',').append(_11).append(',').append(_12).append(',').append(_13).append(',').append(_14).append(',').append(_15).append(',').append(_16).append(',').append(_17).append(',').append(_18).append(',').append(_19).append(',').append(_20).append(',').a [...]
-     sb.toString
-   }
+case class Tuple22[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +T13, +T14, +T15, +T16, +T17, +T18, +T19, +T20, +T21, +T22](_1:T1,_2:T2,_3:T3,_4:T4,_5:T5,_6:T6,_7:T7,_8:T8,_9:T9,_10:T10,_11:T11,_12:T12,_13:T13,_14:T14,_15:T15,_16:T16,_17:T17,_18:T18,_19:T19,_20:T20,_21:T21,_22:T22)
+  extends Product22[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22]
+{  
+  override def toString() = "(" + _1 + "," + _2 + "," + _3 + "," + _4 + "," + _5 + "," + _6 + "," + _7 + "," + _8 + "," + _9 + "," + _10 + "," + _11 +
+    "," + _12 + "," + _13 + "," + _14 + "," + _15 + "," + _16 + "," + _17 + "," + _18 + "," + _19 + "," + _20 + "," + _21 + "," + _22 + ")"  
   
 }
diff --git a/src/library/scala/Tuple3.scala b/src/library/scala/Tuple3.scala
index fe5ae5c..0562258 100644
--- a/src/library/scala/Tuple3.scala
+++ b/src/library/scala/Tuple3.scala
@@ -1,28 +1,142 @@
-
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Tuple3.scala 16881 2009-01-09 16:28:11Z cunei $
 
-// generated by genprod on Wed Apr 23 10:06:16 CEST 2008  
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  (with extra methods)
 
 package scala
 
+import scala.collection.{TraversableLike, IterableLike}
+import scala.collection.generic.CanBuildFrom
+
+
+
+
 /** Tuple3 is the canonical representation of a @see Product3 
  *  
  */
-case class Tuple3[+T1, +T2, +T3](_1:T1, _2:T2, _3:T3) 
-  extends Product3[T1, T2, T3]  {
-
-   override def toString() = {
-     val sb = new StringBuilder
-     sb.append('(').append(_1).append(',').append(_2).append(',').append(_3).append(')')
-     sb.toString
-   }
+case class Tuple3[+T1, +T2, +T3](_1:T1,_2:T2,_3:T3)
+  extends Product3[T1, T2, T3]
+{  
+  override def toString() = "(" + _1 + "," + _2 + "," + _3 + ")"  
   
+  def zip[Repr1, El1, El2, El3, To](implicit w1:   T1 => TraversableLike[El1, Repr1],
+                                             w2:   T2 => Iterable[El2],
+                                             w3:   T3 => Iterable[El3],
+                                             cbf1: CanBuildFrom[Repr1, (El1, El2, El3), To]): To = {
+    val coll1: TraversableLike[El1, Repr1] = _1
+    val coll2: Iterable[El2] = _2
+    val coll3: Iterable[El3] = _3
+    val b1 = cbf1(coll1.repr)
+    val elems2 = coll2.iterator
+    val elems3 = coll3.iterator
+
+    for(el1 <- coll1)
+      if(elems2.hasNext && elems3.hasNext)
+        b1 += ((el1, elems2.next, elems3.next))
+
+    b1.result
+  }
+
+  /** Wraps a tuple in a `Zipped`, which supports 3-ary generalisations of map, flatMap, filter,...
+   *
+   * @see Zipped
+   * $willNotTerminateInf
+   */
+  def zipped[Repr1, El1, Repr2, El2, Repr3, El3](implicit w1: T1 => TraversableLike[El1, Repr1],
+                                                          w2: T2 => IterableLike[El2, Repr2],
+                                                          w3: T3 => IterableLike[El3, Repr3]): Zipped[Repr1, El1, Repr2, El2, Repr3, El3]
+    = new Zipped[Repr1, El1, Repr2, El2, Repr3, El3](_1, _2, _3)
+
+  class Zipped[+Repr1, +El1, +Repr2, +El2, +Repr3, +El3](coll1: TraversableLike[El1, Repr1],
+                                                         coll2: IterableLike[El2, Repr2],
+                                                         coll3: IterableLike[El3, Repr3]) {
+    def map[B, To](f: (El1, El2, El3) => B)(implicit cbf: CanBuildFrom[Repr1, B, To]): To = {
+     val b = cbf(coll1.repr)
+     val elems2 = coll2.iterator
+     val elems3 = coll3.iterator
+
+     for(el1 <- coll1)
+       if(elems2.hasNext && elems3.hasNext)
+         b += f(el1, elems2.next, elems3.next)
+
+     b.result
+    }
+
+    def flatMap[B, To](f: (El1, El2, El3) => Traversable[B])(implicit cbf: CanBuildFrom[Repr1, B, To]): To = {
+      val b = cbf(coll1.repr)
+      val elems2 = coll2.iterator
+      val elems3 = coll3.iterator
+
+      for(el1 <- coll1)
+       if(elems2.hasNext && elems3.hasNext)
+         b ++= f(el1, elems2.next, elems3.next)
+
+      b.result
+    }
+
+    def filter[To1, To2, To3](f: (El1, El2, El3) => Boolean)(
+                 implicit cbf1: CanBuildFrom[Repr1, El1, To1],
+                          cbf2: CanBuildFrom[Repr2, El2, To2],
+                          cbf3: CanBuildFrom[Repr3, El3, To3]): (To1, To2, To3) = {
+      val b1 = cbf1(coll1.repr)
+      val b2 = cbf2(coll2.repr)
+      val b3 = cbf3(coll3.repr)
+      val elems2 = coll2.iterator
+      val elems3 = coll3.iterator
+
+      for(el1 <- coll1) {
+        if(elems2.hasNext && elems3.hasNext) {
+          val el2 = elems2.next
+          val el3 = elems3.next
+          if(f(el1, el2, el3)) {
+            b1 += el1
+            b2 += el2
+            b3 += el3
+          }
+        }
+      }
+
+      (b1.result, b2.result, b3.result)
+    }
+
+    def exists(f: (El1, El2, El3) => Boolean): Boolean = {
+      var acc = false
+      val elems2 = coll2.iterator
+      val elems3 = coll3.iterator
+
+      for(el1 <- coll1)
+       if(!acc && elems2.hasNext && elems3.hasNext)
+         acc = f(el1, elems2.next, elems3.next)
+
+      acc
+    }
+
+    def forall(f: (El1, El2, El3) => Boolean): Boolean = {
+      var acc = true
+      val elems2 = coll2.iterator
+      val elems3 = coll3.iterator
+
+      for(el1 <- coll1)
+       if(acc && elems2.hasNext && elems3.hasNext)
+         acc = f(el1, elems2.next, elems3.next)
+
+      acc
+    }
+
+    def foreach[U](f: (El1, El2, El3) => U): Unit = {
+      val elems2 = coll2.iterator
+      val elems3 = coll3.iterator
+
+      for(el1 <- coll1)
+       if(elems2.hasNext && elems3.hasNext)
+         f(el1, elems2.next, elems3.next)
+    }
+  }
+
 }
diff --git a/src/library/scala/Tuple4.scala b/src/library/scala/Tuple4.scala
index effa44f..cb5ed36 100644
--- a/src/library/scala/Tuple4.scala
+++ b/src/library/scala/Tuple4.scala
@@ -1,28 +1,25 @@
-
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Tuple4.scala 16881 2009-01-09 16:28:11Z cunei $
 
-// generated by genprod on Wed Apr 23 10:06:16 CEST 2008  
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  
 
 package scala
 
+
+
+
 /** Tuple4 is the canonical representation of a @see Product4 
  *  
  */
-case class Tuple4[+T1, +T2, +T3, +T4](_1:T1, _2:T2, _3:T3, _4:T4) 
-  extends Product4[T1, T2, T3, T4]  {
-
-   override def toString() = {
-     val sb = new StringBuilder
-     sb.append('(').append(_1).append(',').append(_2).append(',').append(_3).append(',').append(_4).append(')')
-     sb.toString
-   }
+case class Tuple4[+T1, +T2, +T3, +T4](_1:T1,_2:T2,_3:T3,_4:T4)
+  extends Product4[T1, T2, T3, T4]
+{  
+  override def toString() = "(" + _1 + "," + _2 + "," + _3 + "," + _4 + ")"  
   
 }
diff --git a/src/library/scala/Tuple5.scala b/src/library/scala/Tuple5.scala
index 8149f23..698d4bb 100644
--- a/src/library/scala/Tuple5.scala
+++ b/src/library/scala/Tuple5.scala
@@ -1,28 +1,25 @@
-
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Tuple5.scala 16881 2009-01-09 16:28:11Z cunei $
 
-// generated by genprod on Wed Apr 23 10:06:16 CEST 2008  
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  
 
 package scala
 
+
+
+
 /** Tuple5 is the canonical representation of a @see Product5 
  *  
  */
-case class Tuple5[+T1, +T2, +T3, +T4, +T5](_1:T1, _2:T2, _3:T3, _4:T4, _5:T5) 
-  extends Product5[T1, T2, T3, T4, T5]  {
-
-   override def toString() = {
-     val sb = new StringBuilder
-     sb.append('(').append(_1).append(',').append(_2).append(',').append(_3).append(',').append(_4).append(',').append(_5).append(')')
-     sb.toString
-   }
+case class Tuple5[+T1, +T2, +T3, +T4, +T5](_1:T1,_2:T2,_3:T3,_4:T4,_5:T5)
+  extends Product5[T1, T2, T3, T4, T5]
+{  
+  override def toString() = "(" + _1 + "," + _2 + "," + _3 + "," + _4 + "," + _5 + ")"  
   
 }
diff --git a/src/library/scala/Tuple6.scala b/src/library/scala/Tuple6.scala
index 1e3e3f5..4b0e48c 100644
--- a/src/library/scala/Tuple6.scala
+++ b/src/library/scala/Tuple6.scala
@@ -1,28 +1,25 @@
-
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Tuple6.scala 16881 2009-01-09 16:28:11Z cunei $
 
-// generated by genprod on Wed Apr 23 10:06:16 CEST 2008  
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  
 
 package scala
 
+
+
+
 /** Tuple6 is the canonical representation of a @see Product6 
  *  
  */
-case class Tuple6[+T1, +T2, +T3, +T4, +T5, +T6](_1:T1, _2:T2, _3:T3, _4:T4, _5:T5, _6:T6) 
-  extends Product6[T1, T2, T3, T4, T5, T6]  {
-
-   override def toString() = {
-     val sb = new StringBuilder
-     sb.append('(').append(_1).append(',').append(_2).append(',').append(_3).append(',').append(_4).append(',').append(_5).append(',').append(_6).append(')')
-     sb.toString
-   }
+case class Tuple6[+T1, +T2, +T3, +T4, +T5, +T6](_1:T1,_2:T2,_3:T3,_4:T4,_5:T5,_6:T6)
+  extends Product6[T1, T2, T3, T4, T5, T6]
+{  
+  override def toString() = "(" + _1 + "," + _2 + "," + _3 + "," + _4 + "," + _5 + "," + _6 + ")"  
   
 }
diff --git a/src/library/scala/Tuple7.scala b/src/library/scala/Tuple7.scala
index 61896c0..4b28665 100644
--- a/src/library/scala/Tuple7.scala
+++ b/src/library/scala/Tuple7.scala
@@ -1,28 +1,25 @@
-
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Tuple7.scala 16881 2009-01-09 16:28:11Z cunei $
 
-// generated by genprod on Wed Apr 23 10:06:16 CEST 2008  
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  
 
 package scala
 
+
+
+
 /** Tuple7 is the canonical representation of a @see Product7 
  *  
  */
-case class Tuple7[+T1, +T2, +T3, +T4, +T5, +T6, +T7](_1:T1, _2:T2, _3:T3, _4:T4, _5:T5, _6:T6, _7:T7) 
-  extends Product7[T1, T2, T3, T4, T5, T6, T7]  {
-
-   override def toString() = {
-     val sb = new StringBuilder
-     sb.append('(').append(_1).append(',').append(_2).append(',').append(_3).append(',').append(_4).append(',').append(_5).append(',').append(_6).append(',').append(_7).append(')')
-     sb.toString
-   }
+case class Tuple7[+T1, +T2, +T3, +T4, +T5, +T6, +T7](_1:T1,_2:T2,_3:T3,_4:T4,_5:T5,_6:T6,_7:T7)
+  extends Product7[T1, T2, T3, T4, T5, T6, T7]
+{  
+  override def toString() = "(" + _1 + "," + _2 + "," + _3 + "," + _4 + "," + _5 + "," + _6 + "," + _7 + ")"  
   
 }
diff --git a/src/library/scala/Tuple8.scala b/src/library/scala/Tuple8.scala
index 556b4cd..8310102 100644
--- a/src/library/scala/Tuple8.scala
+++ b/src/library/scala/Tuple8.scala
@@ -1,28 +1,25 @@
-
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Tuple8.scala 16881 2009-01-09 16:28:11Z cunei $
 
-// generated by genprod on Wed Apr 23 10:06:16 CEST 2008  
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  
 
 package scala
 
+
+
+
 /** Tuple8 is the canonical representation of a @see Product8 
  *  
  */
-case class Tuple8[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8](_1:T1, _2:T2, _3:T3, _4:T4, _5:T5, _6:T6, _7:T7, _8:T8) 
-  extends Product8[T1, T2, T3, T4, T5, T6, T7, T8]  {
-
-   override def toString() = {
-     val sb = new StringBuilder
-     sb.append('(').append(_1).append(',').append(_2).append(',').append(_3).append(',').append(_4).append(',').append(_5).append(',').append(_6).append(',').append(_7).append(',').append(_8).append(')')
-     sb.toString
-   }
+case class Tuple8[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8](_1:T1,_2:T2,_3:T3,_4:T4,_5:T5,_6:T6,_7:T7,_8:T8)
+  extends Product8[T1, T2, T3, T4, T5, T6, T7, T8]
+{  
+  override def toString() = "(" + _1 + "," + _2 + "," + _3 + "," + _4 + "," + _5 + "," + _6 + "," + _7 + "," + _8 + ")"  
   
 }
diff --git a/src/library/scala/Tuple9.scala b/src/library/scala/Tuple9.scala
index 19a9070..3e89f3d 100644
--- a/src/library/scala/Tuple9.scala
+++ b/src/library/scala/Tuple9.scala
@@ -1,28 +1,25 @@
-
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Tuple9.scala 16881 2009-01-09 16:28:11Z cunei $
 
-// generated by genprod on Wed Apr 23 10:06:16 CEST 2008  
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  
 
 package scala
 
+
+
+
 /** Tuple9 is the canonical representation of a @see Product9 
  *  
  */
-case class Tuple9[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9](_1:T1, _2:T2, _3:T3, _4:T4, _5:T5, _6:T6, _7:T7, _8:T8, _9:T9) 
-  extends Product9[T1, T2, T3, T4, T5, T6, T7, T8, T9]  {
-
-   override def toString() = {
-     val sb = new StringBuilder
-     sb.append('(').append(_1).append(',').append(_2).append(',').append(_3).append(',').append(_4).append(',').append(_5).append(',').append(_6).append(',').append(_7).append(',').append(_8).append(',').append(_9).append(')')
-     sb.toString
-   }
+case class Tuple9[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9](_1:T1,_2:T2,_3:T3,_4:T4,_5:T5,_6:T6,_7:T7,_8:T8,_9:T9)
+  extends Product9[T1, T2, T3, T4, T5, T6, T7, T8, T9]
+{  
+  override def toString() = "(" + _1 + "," + _2 + "," + _3 + "," + _4 + "," + _5 + "," + _6 + "," + _7 + "," + _8 + "," + _9 + ")"  
   
 }
diff --git a/src/library/scala/TypeConstraint.scala b/src/library/scala/TypeConstraint.scala
index 2f5aa43..1cb7e55 100644
--- a/src/library/scala/TypeConstraint.scala
+++ b/src/library/scala/TypeConstraint.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2006-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: TypeConstraint.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala
@@ -26,5 +25,6 @@ package scala
  *
  *  @author  Lex Spoon
  *  @version 1.1, 2007-11-5
+ *  @since   2.6
  */
 trait TypeConstraint extends Annotation
diff --git a/src/library/scala/UninitializedError.scala b/src/library/scala/UninitializedError.scala
index 22e2028..f130c7c 100644
--- a/src/library/scala/UninitializedError.scala
+++ b/src/library/scala/UninitializedError.scala
@@ -1,20 +1,18 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: UninitializedError.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala
 
-import Predef._
-
 /** This class represents uninitialized variable/value errors.
  *
  *  @author  Martin Odersky
+ *  @since   2.5
  */
 final class UninitializedError extends RuntimeException("uninitialized value")
diff --git a/src/library/scala/UninitializedFieldError.scala b/src/library/scala/UninitializedFieldError.scala
index 7e4508e..9bc3c50 100644
--- a/src/library/scala/UninitializedFieldError.scala
+++ b/src/library/scala/UninitializedFieldError.scala
@@ -1,26 +1,25 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: $
 
 
 package scala
 
-import Predef._
-
 /** This class implements errors which are thrown whenever a
  *  field is used before it has been initialized. 
  *
  *  Such runtime checks are not emitted by default. See the
  *  compiler documentation for knowing how to turn them on.
  *
- *  Note: This check requires the new initialization order,
- *    planned for 2.8.0 and available under -Xexperimental.
+ *  Note: This check requires the initialization order
+ *  first implemented in scala 2.8.
+ *
+ *  @since 2.7
  */
 final case class UninitializedFieldError(msg: String) 
            extends RuntimeException(msg) {
diff --git a/src/library/scala/annotation/elidable.scala b/src/library/scala/annotation/elidable.scala
new file mode 100644
index 0000000..61c360c
--- /dev/null
+++ b/src/library/scala/annotation/elidable.scala
@@ -0,0 +1,68 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+package scala.annotation
+
+import java.util.logging.Level
+ 
+/** An annotation for methods for which invocations might
+ *  be removed in the generated code.
+ * 
+ *  Behavior is influenced by passing -Xelide-below <arg>
+ *  to scalac.  Methods marked elidable will be omitted from
+ *  generated code if the priority given the annotation is lower
+ *  than to the command line argument.  Examples:
+ *  {{{
+ *  import annotation.elidable._
+ * 
+ *    @elidable(WARNING) def foo = log("foo")
+ *    @elidable(FINE) def bar = log("bar")
+ *
+ *  scalac -Xelide-below=1000
+ *  }}}
+ *  @since 2.8
+ */
+final class elidable(final val level: Int) extends StaticAnnotation {}
+
+/** This useless appearing code was necessary to allow people to use
+ *  named constants for the elidable annotation.  This is what it takes
+ *  to convince the compiler to fold the constants: otherwise when it's
+ *  time to check an elision level it's staring at a tree like
+ *    (Select(Level, Select(FINEST, Apply(intValue, Nil))))
+ *  instead of the number 300.
+ *
+ *  @since 2.8
+ */
+object elidable {
+  final val ALL = Int.MinValue  // Level.ALL.intValue()
+  final val FINEST = 300        // Level.FINEST.intValue()
+  final val FINER = 400         // Level.FINER.intValue()
+  final val FINE = 500          // Level.FINE.intValue()
+  final val CONFIG = 700        // Level.CONFIG.intValue()
+  final val INFO = 800          // Level.INFO.intValue()
+  final val WARNING = 900       // Level.WARNING.intValue()
+  final val SEVERE = 1000       // Level.SEVERE.intValue()
+  final val OFF = Int.MaxValue  // Level.OFF.intValue()
+  
+  // and since we had to do that anyway, we can add a few of our own
+  final val ASSERTION = 2000    // we should make this more granular
+  
+  // for command line parsing so we can use names or ints
+  val byName: Map[String, Int] = Map(
+    "ALL" -> ALL,
+    "FINEST" -> FINEST,
+    "FINER" -> FINER,
+    "FINE" -> FINE,
+    "CONFIG" -> CONFIG,
+    "INFO" -> INFO,
+    "WARNING" -> WARNING,
+    "SEVERE" -> SEVERE,
+    "OFF" -> OFF,
+    "ASSERTION" -> ASSERTION
+  )
+}
diff --git a/src/library/scala/annotation/implicitNotFound.scala b/src/library/scala/annotation/implicitNotFound.scala
new file mode 100644
index 0000000..393b05e
--- /dev/null
+++ b/src/library/scala/annotation/implicitNotFound.scala
@@ -0,0 +1,18 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+package scala.annotation
+ 
+/**
+ * An annotation that specifies the error message that is emitted when the compiler
+ * cannot find an implicit value of the annotated type.
+ *
+ * @author Adriaan Moors
+ * @since 2.8.1
+ */
+final class implicitNotFound(msg: String) extends StaticAnnotation {}
\ No newline at end of file
diff --git a/src/library/scala/annotation/migration.scala b/src/library/scala/annotation/migration.scala
new file mode 100644
index 0000000..4a06ef7
--- /dev/null
+++ b/src/library/scala/annotation/migration.scala
@@ -0,0 +1,28 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+package scala.annotation
+ 
+/**
+ * An annotation that marks a member as having changed semantics
+ * between versions.  This is intended for methods which for one
+ * reason or another retain the same name and type signature,
+ * but some aspect of their behavior is different.  An illustrative
+ * examples is Stack.iterator, which reversed from LIFO to FIFO
+ * order between scala 2.7 and 2.8.
+ *
+ * The version numbers are to mark the scala major/minor release
+ * version where the change took place.
+ *
+ * @since 2.8
+ */
+private[scala] final class migration(
+  majorVersion: Int,
+  minorVersion: Int,
+  message: String)
+extends StaticAnnotation {}
diff --git a/src/library/scala/annotation/switch.scala b/src/library/scala/annotation/switch.scala
new file mode 100644
index 0000000..f9fbba1
--- /dev/null
+++ b/src/library/scala/annotation/switch.scala
@@ -0,0 +1,38 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+package scala.annotation
+ 
+/** <p>
+ *    An annotation to be applied to a match expression.  If present,
+ *    the compiler will verify that the match has been compiled to a
+ *    <a href="http://java.sun.com/docs/books/jvms/second_edition/html/Instructions2.doc14.html"
+ *    target="_top"><code>tableswitch</code></a> or
+ *    <a href="http://java.sun.com/docs/books/jvms/second_edition/html/Instructions2.doc8.html#lookupswitch"
+ *    target="_top"><code>lookupswitch</code></a>, and issue an error if it
+ *    instead compiles into a series of conditional expressions.<br/>
+ *    Example:
+ *  </p>
+ *  <pre>
+ *    <b>def</b> fetchToken() {
+ *      (ch: @switch) <b>match</b> {
+ *        <b>case</b> ' ' | '\t' | CR | LF | FF <b>=></b>
+ *          nextChar()
+ *          fetchToken()
+ *        <b>case</b> 'A' /*..'Z'*/ | '$' | '_' | 'a' /*..'z'*/ <b>=></b>
+ *          putChar(ch)
+ *          nextChar()
+ *          getIdentRest()
+ *        <b>case</b> ',' <b>=></b>
+ *          nextChar(); token = COMMA
+ *        // more cases
+ *      }
+ *    }</pre>
+ *
+ *  @since 2.8
+ */
+final class switch extends StaticAnnotation
diff --git a/src/library/scala/annotation/tailrec.scala b/src/library/scala/annotation/tailrec.scala
new file mode 100644
index 0000000..24e0a88
--- /dev/null
+++ b/src/library/scala/annotation/tailrec.scala
@@ -0,0 +1,18 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+package scala.annotation
+ 
+/** <p>
+ *    A method annotation which verifies that the method will be compiled
+ *    with tail call optimization.  If it is present, the compiler will
+ *    issue an error if the method cannot be optimized into a loop.
+ *  </p>
+ *
+ *  @since 2.8
+ */
+final class tailrec extends StaticAnnotation
diff --git a/src/library/scala/annotation/target/beanGetter.scala b/src/library/scala/annotation/target/beanGetter.scala
new file mode 100644
index 0000000..e815e69
--- /dev/null
+++ b/src/library/scala/annotation/target/beanGetter.scala
@@ -0,0 +1,51 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+package scala.annotation.target
+
+/**
+ * For every field of a class, the Scala compiler generates up to four
+ * synthetic accessors: getter, setter, bean getter and bean setter.
+ * The meta-annotations in package {{{scala.annotation.target}}} are
+ * used to control to which of the above members the annotations on
+ * the field are copied. By default, field annotations are only added
+ * to the actual field, but not to any of the accessors. By annotating
+ * the annotation type or the annotation class with one or several of
+ * the meta-annotations this behavior can be changed.
+ *
+ * In the following example, the annotation {{{@Id}}} will be added
+ * only to the bean getter {{{getX}}}. In order to annotate the field
+ * as well, the meta-annotation {{{@field}}} would need to be added.
+ *
+ * {{{
+ * import javax.persistence.Id
+ * class A {
+ *   @(Id @beanGetter) @BeanProperty val x = 0
+ * }
+ * }}}
+ *
+ * The syntax can be improved using a type alias:
+ *
+ * {{{
+ * object ScalaJPA {
+ *   type Id = javax.persistence.Id @beanGetter
+ * }
+ * import ScalaJPA.Id
+ * class A {
+ *   @Id @BeanProperty val x = 0
+ * }
+ * }}}
+ *
+ * For annotations defined in Scala, a default target can be specified
+ * in the annotation class itself, for example
+ *
+ * {{{
+ * @getter
+ * class myAnnotation extends Annotation
+ * }}}
+ */
+final class beanGetter extends StaticAnnotation
diff --git a/src/library/scala/annotation/target/beanSetter.scala b/src/library/scala/annotation/target/beanSetter.scala
new file mode 100644
index 0000000..d719969
--- /dev/null
+++ b/src/library/scala/annotation/target/beanSetter.scala
@@ -0,0 +1,51 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+package scala.annotation.target
+
+/**
+ * For every field of a class, the Scala compiler generates up to four
+ * synthetic accessors: getter, setter, bean getter and bean setter.
+ * The meta-annotations in package {{{scala.annotation.target}}} are
+ * used to control to which of the above members the annotations on
+ * the field are copied. By default, field annotations are only added
+ * to the actual field, but not to any of the accessors. By annotating
+ * the annotation type or the annotation class with one or several of
+ * the meta-annotations this behavior can be changed.
+ *
+ * In the following example, the annotation {{{@Id}}} will be added
+ * only to the bean getter {{{getX}}}. In order to annotate the field
+ * as well, the meta-annotation {{{@field}}} would need to be added.
+ *
+ * {{{
+ * import javax.persistence.Id
+ * class A {
+ *   @(Id @beanGetter) @BeanProperty val x = 0
+ * }
+ * }}}
+ *
+ * The syntax can be improved using a type alias:
+ *
+ * {{{
+ * object ScalaJPA {
+ *   type Id = javax.persistence.Id @beanGetter
+ * }
+ * import ScalaJPA.Id
+ * class A {
+ *   @Id @BeanProperty val x = 0
+ * }
+ * }}}
+ *
+ * For annotations defined in Scala, a default target can be specified
+ * in the annotation class itself, for example
+ *
+ * {{{
+ * @getter
+ * class myAnnotation extends Annotation
+ * }}}
+ */
+final class beanSetter extends StaticAnnotation
diff --git a/src/library/scala/annotation/target/field.scala b/src/library/scala/annotation/target/field.scala
new file mode 100644
index 0000000..94e82bc
--- /dev/null
+++ b/src/library/scala/annotation/target/field.scala
@@ -0,0 +1,51 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+package scala.annotation.target
+
+/**
+ * For every field of a class, the Scala compiler generates up to four
+ * synthetic accessors: getter, setter, bean getter and bean setter.
+ * The meta-annotations in package {{{scala.annotation.target}}} are
+ * used to control to which of the above members the annotations on
+ * the field are copied. By default, field annotations are only added
+ * to the actual field, but not to any of the accessors. By annotating
+ * the annotation type or the annotation class with one or several of
+ * the meta-annotations this behavior can be changed.
+ *
+ * In the following example, the annotation {{{@Id}}} will be added
+ * only to the bean getter {{{getX}}}. In order to annotate the field
+ * as well, the meta-annotation {{{@field}}} would need to be added.
+ *
+ * {{{
+ * import javax.persistence.Id
+ * class A {
+ *   @(Id @beanGetter) @BeanProperty val x = 0
+ * }
+ * }}}
+ *
+ * The syntax can be improved using a type alias:
+ *
+ * {{{
+ * object ScalaJPA {
+ *   type Id = javax.persistence.Id @beanGetter
+ * }
+ * import ScalaJPA.Id
+ * class A {
+ *   @Id @BeanProperty val x = 0
+ * }
+ * }}}
+ *
+ * For annotations defined in Scala, a default target can be specified
+ * in the annotation class itself, for example
+ *
+ * {{{
+ * @getter
+ * class myAnnotation extends Annotation
+ * }}}
+ */
+final class field extends StaticAnnotation
diff --git a/src/library/scala/annotation/target/getter.scala b/src/library/scala/annotation/target/getter.scala
new file mode 100644
index 0000000..2d5e856
--- /dev/null
+++ b/src/library/scala/annotation/target/getter.scala
@@ -0,0 +1,51 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+package scala.annotation.target
+
+/**
+ * For every field of a class, the Scala compiler generates up to four
+ * synthetic accessors: getter, setter, bean getter and bean setter.
+ * The meta-annotations in package {{{scala.annotation.target}}} are
+ * used to control to which of the above members the annotations on
+ * the field are copied. By default, field annotations are only added
+ * to the actual field, but not to any of the accessors. By annotating
+ * the annotation type or the annotation class with one or several of
+ * the meta-annotations this behavior can be changed.
+ *
+ * In the following example, the annotation {{{@Id}}} will be added
+ * only to the bean getter {{{getX}}}. In order to annotate the field
+ * as well, the meta-annotation {{{@field}}} would need to be added.
+ *
+ * {{{
+ * import javax.persistence.Id
+ * class A {
+ *   @(Id @beanGetter) @BeanProperty val x = 0
+ * }
+ * }}}
+ *
+ * The syntax can be improved using a type alias:
+ *
+ * {{{
+ * object ScalaJPA {
+ *   type Id = javax.persistence.Id @beanGetter
+ * }
+ * import ScalaJPA.Id
+ * class A {
+ *   @Id @BeanProperty val x = 0
+ * }
+ * }}}
+ *
+ * For annotations defined in Scala, a default target can be specified
+ * in the annotation class itself, for example
+ *
+ * {{{
+ * @getter
+ * class myAnnotation extends Annotation
+ * }}}
+ */
+final class getter extends StaticAnnotation
diff --git a/src/library/scala/annotation/target/param.scala b/src/library/scala/annotation/target/param.scala
new file mode 100644
index 0000000..317080f
--- /dev/null
+++ b/src/library/scala/annotation/target/param.scala
@@ -0,0 +1,51 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+package scala.annotation.target
+
+/**
+ * For every field of a class, the Scala compiler generates up to four
+ * synthetic accessors: getter, setter, bean getter and bean setter.
+ * The meta-annotations in package {{{scala.annotation.target}}} are
+ * used to control to which of the above members the annotations on
+ * the field are copied. By default, field annotations are only added
+ * to the actual field, but not to any of the accessors. By annotating
+ * the annotation type or the annotation class with one or several of
+ * the meta-annotations this behavior can be changed.
+ *
+ * In the following example, the annotation {{{@Id}}} will be added
+ * only to the bean getter {{{getX}}}. In order to annotate the field
+ * as well, the meta-annotation {{{@field}}} would need to be added.
+ *
+ * {{{
+ * import javax.persistence.Id
+ * class A {
+ *   @(Id @beanGetter) @BeanProperty val x = 0
+ * }
+ * }}}
+ *
+ * The syntax can be improved using a type alias:
+ *
+ * {{{
+ * object ScalaJPA {
+ *   type Id = javax.persistence.Id @beanGetter
+ * }
+ * import ScalaJPA.Id
+ * class A {
+ *   @Id @BeanProperty val x = 0
+ * }
+ * }}}
+ *
+ * For annotations defined in Scala, a default target can be specified
+ * in the annotation class itself, for example
+ *
+ * {{{
+ * @getter
+ * class myAnnotation extends Annotation
+ * }}}
+ */
+final class param extends StaticAnnotation
diff --git a/src/library/scala/annotation/target/setter.scala b/src/library/scala/annotation/target/setter.scala
new file mode 100644
index 0000000..4e0758b
--- /dev/null
+++ b/src/library/scala/annotation/target/setter.scala
@@ -0,0 +1,51 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+package scala.annotation.target
+
+/**
+ * For every field of a class, the Scala compiler generates up to four
+ * synthetic accessors: getter, setter, bean getter and bean setter.
+ * The meta-annotations in package {{{scala.annotation.target}}} are
+ * used to control to which of the above members the annotations on
+ * the field are copied. By default, field annotations are only added
+ * to the actual field, but not to any of the accessors. By annotating
+ * the annotation type or the annotation class with one or several of
+ * the meta-annotations this behavior can be changed.
+ *
+ * In the following example, the annotation {{{@Id}}} will be added
+ * only to the bean getter {{{getX}}}. In order to annotate the field
+ * as well, the meta-annotation {{{@field}}} would need to be added.
+ *
+ * {{{
+ * import javax.persistence.Id
+ * class A {
+ *   @(Id @beanGetter) @BeanProperty val x = 0
+ * }
+ * }}}
+ *
+ * The syntax can be improved using a type alias:
+ *
+ * {{{
+ * object ScalaJPA {
+ *   type Id = javax.persistence.Id @beanGetter
+ * }
+ * import ScalaJPA.Id
+ * class A {
+ *   @Id @BeanProperty val x = 0
+ * }
+ * }}}
+ *
+ * For annotations defined in Scala, a default target can be specified
+ * in the annotation class itself, for example
+ *
+ * {{{
+ * @getter
+ * class myAnnotation extends Annotation
+ * }}}
+ */
+final class setter extends StaticAnnotation
diff --git a/src/library/scala/annotation/unchecked/uncheckedStable.scala b/src/library/scala/annotation/unchecked/uncheckedStable.scala
index 1d1e99a..8cfa608 100644
--- a/src/library/scala/annotation/unchecked/uncheckedStable.scala
+++ b/src/library/scala/annotation/unchecked/uncheckedStable.scala
@@ -1,6 +1,6 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
@@ -9,5 +9,7 @@ package scala.annotation.unchecked
 
 /** An annotation for values that are assumed to be stable even though their
  *  types are volatile.  
+ *
+ *  @since 2.7
  */
 final class uncheckedStable extends StaticAnnotation {}
diff --git a/src/library/scala/annotation/unchecked/uncheckedVariance.scala b/src/library/scala/annotation/unchecked/uncheckedVariance.scala
index 1aa0eea..e8b2673 100644
--- a/src/library/scala/annotation/unchecked/uncheckedVariance.scala
+++ b/src/library/scala/annotation/unchecked/uncheckedVariance.scala
@@ -1,6 +1,6 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
@@ -9,5 +9,7 @@ package scala.annotation.unchecked
 
 /** An annotation for type arguments for which one wants to suppress variance checking
  *  types are volatile.  
+ *
+ *  @since 2.7
  */
 final class uncheckedVariance extends StaticAnnotation {}
diff --git a/src/library/scala/cloneable.scala b/src/library/scala/cloneable.scala
index de9d323..9becd3f 100644
--- a/src/library/scala/cloneable.scala
+++ b/src/library/scala/cloneable.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: cloneable.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala
diff --git a/src/library/scala/collection/BitSet.scala b/src/library/scala/collection/BitSet.scala
index b758de4..3a37603 100644
--- a/src/library/scala/collection/BitSet.scala
+++ b/src/library/scala/collection/BitSet.scala
@@ -1,157 +1,34 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: BitSet.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala.collection
 
-/** <p>
- *    The class <code>BitSet</code> provides the interface for a space-efficient
- *    implementation of dense integer sets represented as bits in array of
- *    integers. Bit indices are between <code>0..(capacity-1)</code> inclusive.
- *  </p>
- *
- *  @author  Burak Emir, Stephane Micheloud, Nikolay Mihaylov
- *  @author  Martin Odersky
- *  @version 2.0  01/01/2007
- */
-
-abstract class BitSet extends Set[Int] {
-
-  import compat.Platform.arraycopy
-
-  /** number of bits in this bitset */
-  def size: Int
-
-  /**
-   *  @param i ...
-   *  @return <code>true</code> if bit <code>i</code> is set.
-   */
-  def contains(i: Int): Boolean = {
-    (i < capacity) && {
-      val j = offset(i)
-      (0 <= j) && (j < arr.length) &&
-      ((arr(j) & mask(i)) != 0)
-    }
-  }
-
-  def capacity: Int
-
-  protected def arr: Array[Int]
-
-  /** returns an iterator over the truth values of all bits */
-   final def elements: Iterator[Int] = new Iterator[Int] {
-     var i = 0
-     def findNext: Unit = {
-       while (!BitSet.this.contains(i) && (i < capacity))
-         i = i + 1
-     }
-     findNext
-     def hasNext: Boolean = i < capacity
-     def next(): Int = { val j = i; i = i + 1; findNext; j }
-   }
-
-
-  /**
-   * @return a copy of the array underlying this bitset
-   */
-     /*
-  def toArray: Array[Int] = {
-    val length = memsize(capacity)
-    val newarr = new Array[Int](length)
-    if (arr.length > 0)
-      arraycopy(this.arr, 0, newarr, 0, length)
-    newarr
-  }*/
-
-  /** Checks if two bitsets are structurally identical.
-   *  Uses accelerated (32 x faster) check if the other set is a BitSet
-   *
-   *  @param other ...
-   *  @return      <code>true</code>, iff both bitsets contain the same
-   *               elements.
-   */
-  override def equals(other: Any): Boolean = other match {
-    case that: BitSet =>
-      (size == that.size) && {
-        var len = memsize(Math.min(this.capacity, that.capacity))
-        var i = 0
-        while (i < len && arr(i) == that.arr(i)) i = i + 1
-        i == len
-      }
-    case _ =>
-      super.equals(other)
-  }
+import generic._
 
-  override def hashCode(): Int = {
-    val len = memsize(this.capacity)
-    var h = 0
-    var i = 0
-    while (i < len) { h = h * 41 + arr(i); i = i + 1 }
-    h
-  }
-
-  /** Checks if this set is a subset of set <code>that</code>.
-   *  Uses accelerated (32 x faster) check if the other set is a BitSet
-   *
-   *  @param other another set.
-   *  @return      <code>true</code>, iff the other set is a superset of
-   *               this set.
-   */
-  override def subsetOf(other: Set[Int]): Boolean = other match {
-    case that: BitSet =>
-      val thisLen = memsize(this.capacity)
-      val thatLen = memsize(that.capacity)
-      val minLen = Math.min(thisLen, thatLen)
-      var i = 0
-      while (i < minLen && that.arr(i) == (that.arr(i) | arr(i))) i = i + 1
-      while (i < thisLen && arr(i) == 0) i = i + 1
-      i == thisLen
-    case _ =>
-      super.subsetOf(other)
-  }
-
-  /**
-   *  @param n the number of bits to be stored.
-   *  @return  the number of <code>Int</code> cells needed to store
-   *           <code>n</code> bits.
-   */
-  protected final def memsize(n: Int): Int = offset(n + 31)
-
-  /** 
-   *  @param n ...
-   *  @return  the number of bits represented by <code>n</code> words.
-   */
-  protected final def nbits(n: Int): Int = n << 5
-
-  /**
-   *  @param n ...
-   *  @return the position in the array where the bit resides.
-   */
-  protected final def offset(n: Int): Int = n >>> 5
-
-  /**
-   *  @param n ...
-   *  @return a mask with 1 at the position of the bit.
-   */
-  protected final def mask(n: Int): Int = 1 << (n & 0x1F)
-
-  /**
-   * @return a copy of the array underlying this bitset
-   */
-  def underlying : Array[Int] = {
-     val length = memsize(capacity)
-     val newarr = new Array[Int](length)
-     if (arr.length > 0)
-       arraycopy(this.arr, 0, newarr, 0, length)
-     newarr
-   }
+/** A common base class for mutable and immutable bitsets.
+ *  $bitsetinfo
+ */
+trait BitSet extends Set[Int] 
+                with BitSetLike[BitSet] {
+  override def empty: BitSet = BitSet.empty
+}
 
-  protected override def stringPrefix = "Set"
+/** $factoryInfo
+ *  @define coll bitset
+ *  @define Coll BitSet
+ */
+object BitSet extends BitSetFactory[BitSet] {
+  val empty: BitSet = immutable.BitSet.empty  
+  def newBuilder = immutable.BitSet.newBuilder
+  
+  /** $canBuildFromInfo */
+  implicit def canBuildFrom: CanBuildFrom[BitSet, Int, BitSet] = bitsetCanBuildFrom
 }
+
diff --git a/src/library/scala/collection/BitSetLike.scala b/src/library/scala/collection/BitSetLike.scala
new file mode 100644
index 0000000..98940ee
--- /dev/null
+++ b/src/library/scala/collection/BitSetLike.scala
@@ -0,0 +1,194 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+
+import BitSetLike._
+import generic._
+import mutable.StringBuilder
+
+/** A template trait for bitsets.
+ *  $bitsetinfo
+ *
+ * This trait provides most of the operations of a `BitSet` independently of its representation.
+ * It is inherited by all concrete implementations of bitsets.
+ *
+ *  @tparam  This the type of the bitset itself.
+ *
+ *  @define bitsetinfo
+ *  Bitsets are sets of non-negative integers which are represented as
+ *  variable-size arrays of bits packed into 64-bit words. The memory footprint of a bitset is
+ *  determined by the largest number stored in it.
+ *  @author  Martin Odersky
+ *  @version 2.8
+ *  @since 2.8
+ *  @define coll bitset
+ *  @define Coll BitSet
+ */
+trait BitSetLike[+This <: BitSetLike[This] with Set[Int]] extends SetLike[Int, This] { self =>
+
+  def empty: This
+ 
+  /** The number of words (each with 64 bits) making up the set */
+  protected def nwords: Int
+
+  /** The words at index `idx', or 0L if outside the range of the set
+   *  '''Note:''' requires `idx >= 0`
+   */
+  protected def word(idx: Int): Long
+
+  /** Creates a new set of this kind from an array of longs
+   */
+  protected def fromArray(elems: Array[Long]): This
+
+  override def size: Int = {
+    var s = 0
+    var i = nwords
+    while (i > 0) {
+      i -= 1
+      s += popCount(word(i))
+    }
+    s
+  }
+
+  def iterator = new Iterator[Int] {
+    private var current = 0
+    private val end = nwords * WordLength
+    def hasNext: Boolean = {
+      while (current < end && !self.contains(current)) current += 1
+      current < end
+    }
+    def next(): Int = 
+      if (hasNext) { val r = current; current += 1; r } 
+      else Iterator.empty.next
+  }
+
+  override def foreach[B](f: Int => B) {
+    for (i <- 0 until nwords) {
+      val w = word(i)
+      for (j <- i * WordLength until (i + 1) * WordLength) {
+        if ((w & (1L << j)) != 0L) f(j)
+      }
+    }
+  }
+
+  /** Computes the union between this bitset and another bitset by performing
+   *  a bitwise "or".
+   *
+   *  @param   other  the bitset to form the union with.
+   *  @return  a new bitset consisting of all bits that are in this
+   *           bitset or in the given bitset `other`. 
+   */
+  def | (other: BitSet): This = {
+    val len = this.nwords max other.nwords
+    val words = new Array[Long](len)
+    for (idx <- 0 until len)
+      words(idx) = this.word(idx) | other.word(idx)
+    fromArray(words)
+  }
+
+  /** Computes the intersection between this bitset and another bitset by performing 
+   *  a bitwise "and".
+   *  @param   that  the bitset to intersect with.
+   *  @return  a new bitset consisting of all elements that are both in this
+   *  bitset and in the given bitset `other`. 
+   */
+  def & (other: BitSet): This = {
+    val len = this.nwords min other.nwords
+    val words = new Array[Long](len)
+    for (idx <- 0 until len)
+      words(idx) = this.word(idx) & other.word(idx)
+    fromArray(words)
+  }
+
+  /** Computes the difference of this bitset and another bitset by performing 
+   *  a bitwise "and-not".
+   * 
+   *  @param that the set of bits to exclude.
+   *  @return     a bitset containing those bits of this
+   *              bitset that are not also contained in the given bitset `other`.
+   */
+  def &~ (other: BitSet): This = {
+    val len = this.nwords
+    val words = new Array[Long](len)
+    for (idx <- 0 until len)
+      words(idx) = this.word(idx) & ~other.word(idx)
+    fromArray(words)
+  }
+
+  /** Computes the symmetric difference of this bitset and another bitset by performing 
+   *  a bitwise "exclusive-or".
+   * 
+   *  @param that the other bitset to take part in the symmetric difference. 
+   *  @return     a bitset containing those bits of this
+   *              bitset or the other bitset that are not contained in both bitsets.
+   */
+  def ^ (other: BitSet): This = {
+    val len = this.nwords max other.nwords
+    val words = new Array[Long](len)
+    for (idx <- 0 until len)
+      words(idx) = this.word(idx) ^ other.word(idx)
+    fromArray(words)
+  }
+
+  def contains(elem: Int): Boolean =
+    0 <= elem && (word(elem >> LogWL) & (1L << elem)) != 0L
+
+  /** Tests whether this bitset is a subset of another bitset.
+   *
+   *  @param that  the bitset to test.
+   *  @return     `true` if this bitset is a subset of `other`, i.e. if
+   *              every bit of this set is also an element in `other`.
+   */
+  def subsetOf(other: BitSet): Boolean =
+    (0 until nwords) forall (idx => (this.word(idx) & ~ other.word(idx)) == 0L)
+
+  override def addString(sb: StringBuilder, start: String, sep: String, end: String) = {
+    sb append start
+    var pre = ""
+    for (i <- 0 until nwords * WordLength)
+      if (contains(i)) {
+        sb append pre append i
+        pre = sep
+      }
+    sb append end
+  }
+
+  override def stringPrefix = "BitSet"                                                                                      
+}
+
+/** Companion object for BitSets. Contains private data only */
+object BitSetLike {
+  private[collection] val LogWL = 6
+  private val WordLength = 64
+
+  private[collection] def updateArray(elems: Array[Long], idx: Int, w: Long): Array[Long] = {
+    var len = elems.length
+    while (len > 0 && (elems(len - 1) == 0L || w == 0L && idx == len - 1)) len -= 1
+    var newlen = len
+    if (idx >= newlen && w != 0L) newlen = idx + 1
+    val newelems = new Array[Long](newlen)
+    Array.copy(elems, 0, newelems, 0, len)
+    if (idx < newlen) newelems(idx) = w
+    else assert(w == 0L)
+    newelems
+  }
+
+  private val pc1: Array[Int] = {
+    def countBits(x: Int): Int = if (x == 0) 0 else x % 2 + countBits(x >>> 1)
+    Array.tabulate(256)(countBits _)
+  }
+
+  private def popCount(w: Long): Int = {
+    def pc2(w: Int) = if (w == 0) 0 else pc1(w & 0xff) + pc1(w >>> 8)
+    def pc4(w: Int) = if (w == 0) 0 else pc2(w & 0xffff) + pc2(w >>> 16)
+    if (w == 0L) 0 else pc4(w.toInt) + pc4((w >>> 32).toInt)
+  }
+}
diff --git a/src/library/scala/collection/BufferedIterator.scala b/src/library/scala/collection/BufferedIterator.scala
new file mode 100644
index 0000000..ab56d93
--- /dev/null
+++ b/src/library/scala/collection/BufferedIterator.scala
@@ -0,0 +1,27 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+
+/** Buffered iterators are iterators which provide a method <code>head</code>
+ *  that inspects the next element without discarding it.
+ *
+ *  @author  Martin Odersky
+ *  @version 2.8
+ *  @since   2.8
+ */
+trait BufferedIterator[+A] extends Iterator[A] {
+
+  /** Returns next element of iterator without advancing beyond it.
+   */
+  def head: A
+
+  override def buffered: this.type = this
+}
diff --git a/src/library/scala/collection/DefaultMap.scala b/src/library/scala/collection/DefaultMap.scala
new file mode 100644
index 0000000..046e96d
--- /dev/null
+++ b/src/library/scala/collection/DefaultMap.scala
@@ -0,0 +1,51 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+
+import generic._
+
+/** <p>
+ *    A default map which implements the <code>+</code> and <code>-</code>
+ *    methods of maps.<br/>
+ *    Instances that inherit from <code>DefaultMap[A, B]</code> still have to
+ *    define:
+ *  </p><pre>
+ *    <b>def</b> get(key: A): Option[B]
+ *    <b>def</b> iterator: Iterator[(A, B)]</pre>
+ *  <p>
+ *    It refers back to the original map.
+ *  </p>
+ *  <p>
+ *    It might also be advisable to override <code>foreach</code> or
+ *    <code>size</code> if efficient implementations can be found.
+ *  </p>
+ *
+ *  @since 2.8
+ */
+trait DefaultMap[A, +B] extends Map[A, B] { self =>
+
+  /** A default implementation which creates a new immutable map.
+   */
+  override def +[B1 >: B](kv: (A, B1)): Map[A, B1] = {
+    val b = Map.newBuilder[A, B1]
+    b ++= this
+    b += ((kv._1, kv._2))
+    b.result
+  }
+
+  /** A default implementation which creates a new immutable map.
+   */
+  override def - (key: A): Map[A, B] = {
+    val b = newBuilder
+    b ++= this filter (key !=)
+    b.result
+  }
+}
diff --git a/src/library/scala/collection/IndexedSeq.scala b/src/library/scala/collection/IndexedSeq.scala
new file mode 100644
index 0000000..2d9f41d
--- /dev/null
+++ b/src/library/scala/collection/IndexedSeq.scala
@@ -0,0 +1,34 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2006-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+
+import generic._
+import mutable.Builder
+
+/** A base trait for indexed sequences.
+ *  $indexedSeqInfo
+ */
+trait IndexedSeq[+A] extends Seq[A] 
+                    with GenericTraversableTemplate[A, IndexedSeq]
+                    with IndexedSeqLike[A, IndexedSeq[A]] {
+  override def companion: GenericCompanion[IndexedSeq] = IndexedSeq
+}
+
+/** $factoryInfo
+ *  The current default implementation of a $Coll is a `Vector`.
+ *  @define coll indexed sequence
+ *  @define Coll IndexedSeq
+ */
+object IndexedSeq extends SeqFactory[IndexedSeq] {
+  implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, IndexedSeq[A]] = new GenericCanBuildFrom[A]
+  def newBuilder[A]: Builder[A, IndexedSeq[A]] = immutable.IndexedSeq.newBuilder[A]
+}
+
diff --git a/src/library/scala/collection/IndexedSeqLike.scala b/src/library/scala/collection/IndexedSeqLike.scala
new file mode 100644
index 0000000..ac2d98d
--- /dev/null
+++ b/src/library/scala/collection/IndexedSeqLike.scala
@@ -0,0 +1,97 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2006-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+
+import generic._
+import mutable.ArrayBuffer
+import scala.annotation.tailrec
+
+/** A template trait for indexed sequences of type `IndexedSeq[A]`.
+ *
+ *  $indexedSeqInfo
+ *
+ *  This trait just implements `iterator` in terms of `apply` and `length`.
+ *  However, see `IndexedSeqOptimized` for an implementation trait that overrides operations
+ *  to make them run faster under the assumption of fast random access with `apply`. 
+ *
+ *  @define  Coll  IndexedSeq
+ *  @define indexedSeqInfo
+ *  Indexed sequences support constant-time or near constant-time element
+ *  access and length computation. They are defined in terms of abstract methods
+ *  `apply` for indexing and `length`.
+ * 
+ *  Indexed sequences do not add any new methods wrt `Seq`, but promise
+ *  efficient implementations of random access patterns.
+ * 
+ *  @tparam A    the element type of the $coll
+ *  @tparam Repr the type of the actual $coll containing the elements.
+ *  @author Martin Odersky
+ *  @version 2.8
+ *  @since   2.8
+ *  @define willNotTerminateInf
+ *  @define mayNotTerminateInf
+ */
+trait IndexedSeqLike[+A, +Repr] extends SeqLike[A, Repr] { self =>
+
+  override protected[this] def thisCollection: IndexedSeq[A] = this.asInstanceOf[IndexedSeq[A]]
+  override protected[this] def toCollection(repr: Repr): IndexedSeq[A] = repr.asInstanceOf[IndexedSeq[A]]
+
+  /** The class of the iterator returned by the `iterator` method.
+   *  multiple `take`, `drop`, and `slice` operations on this iterator are bunched
+   *  together for better efficiency.
+   */
+  @serializable @SerialVersionUID(1756321872811029277L)
+  protected class Elements(start: Int, end: Int) extends BufferedIterator[A] {
+    private var i = start
+
+    def hasNext: Boolean = i < end
+
+    def next: A = 
+      if (i < end) {
+        val x = self(i)
+        i += 1
+        x
+      } else Iterator.empty.next
+
+    def head = 
+      if (i < end) self(i) else Iterator.empty.next
+
+    /** $super
+     *  '''Note:''' `drop` is overridden to enable fast searching in the middle of indexed sequences.
+     */
+    override def drop(n: Int): Iterator[A] =
+      if (n > 0) new Elements(i + n, end) else this
+
+    /** $super
+     *  '''Note:''' `take` is overridden to be symmetric to `drop`.
+     */
+    override def take(n: Int): Iterator[A] =
+      if (n <= 0) Iterator.empty.buffered
+      else if (i + n < end) new Elements(i, i + n) 
+      else this
+  }
+
+  override /*IterableLike*/
+  def iterator: Iterator[A] = new Elements(0, length)
+/*
+  override /*SeqLike*/
+  def view = new IndexedSeqView[A, Repr] {
+    protected lazy val underlying = self.repr
+    override def iterator = self.iterator
+    override def length = self.length
+    override def apply(idx: Int) = self.apply(idx)
+  }
+
+  override /*SeqLike*/
+  def view(from: Int, until: Int) = view.slice(from, until)
+*/
+}
+
diff --git a/src/library/scala/collection/IndexedSeqOptimized.scala b/src/library/scala/collection/IndexedSeqOptimized.scala
new file mode 100644
index 0000000..9a68fa4
--- /dev/null
+++ b/src/library/scala/collection/IndexedSeqOptimized.scala
@@ -0,0 +1,287 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2006-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+
+import generic._
+import mutable.ArrayBuffer
+import scala.annotation.tailrec
+
+/** A template trait for indexed sequences of type `IndexedSeq[A]` which optimizes
+ *  the implementation of several methods under the assumption of fast random access.
+ *
+ *  $indexedSeqInfo
+ * 
+ *  @define willNotTerminateInf
+ *  @define mayNotTerminateInf
+ */
+trait IndexedSeqOptimized[+A, +Repr] extends IndexedSeqLike[A, Repr] { self =>
+
+  override /*IterableLike*/
+  def isEmpty: Boolean = { length == 0 }
+
+  override /*IterableLike*/
+  def foreach[U](f: A =>  U): Unit = {
+    var i = 0
+    val len = length
+    while (i < len) { f(this(i)); i += 1 }
+  }
+
+  override /*IterableLike*/ 
+  def forall(p: A => Boolean): Boolean = prefixLength(p(_)) == length
+
+  override /*IterableLike*/  
+  def exists(p: A => Boolean): Boolean = prefixLength(!p(_)) != length
+
+  override /*IterableLike*/
+  def find(p: A => Boolean): Option[A] = {
+    val i = prefixLength(!p(_))
+    if (i < length) Some(this(i)) else None
+  }
+/*
+  override /*IterableLike*/
+  def mapFind[B](f: A => Option[B]): Option[B] = {
+    var i = 0
+    var res: Option[B] = None
+    val len = length
+    while (res.isEmpty && i < len) {
+      res = f(this(i))
+      i += 1
+    }
+    res
+  }
+*/
+  @tailrec
+  private def foldl[B](start: Int, end: Int, z: B, op: (B, A) => B): B =
+    if (start == end) z
+    else foldl(start + 1, end, op(z, this(start)), op)
+
+  @tailrec
+  private def foldr[B](start: Int, end: Int, z: B, op: (A, B) => B): B =
+    if (start == end) z
+    else foldr(start, end - 1, op(this(end - 1), z), op)
+
+  override /*TraversableLike*/
+  def foldLeft[B](z: B)(op: (B, A) => B): B = 
+    foldl(0, length, z, op)
+
+  override /*IterableLike*/
+  def foldRight[B](z: B)(op: (A, B) => B): B = 
+    foldr(0, length, z, op)
+
+  override /*TraversableLike*/
+  def reduceLeft[B >: A](op: (B, A) => B): B = 
+    if (length > 0) foldl(1, length, this(0), op) else super.reduceLeft(op)
+
+  override /*IterableLike*/
+  def reduceRight[B >: A](op: (A, B) => B): B = 
+    if (length > 0) foldr(0, length - 1, this(length - 1), op) else super.reduceRight(op)
+  
+  override /*IterableLike*/
+  def zip[A1 >: A, B, That](that: Iterable[B])(implicit bf: CanBuildFrom[Repr, (A1, B), That]): That = that match {
+    case that: IndexedSeq[_] =>
+      val b = bf(repr)
+      var i = 0
+      val len = this.length min that.length
+      b.sizeHint(len)
+      while (i < len) {
+        b += ((this(i), that(i).asInstanceOf[B]))
+        i += 1
+      }
+      b.result
+    case _ =>
+      super.zip[A1, B, That](that)(bf)
+  }
+
+  override /*IterableLike*/
+  def zipWithIndex[A1 >: A, That](implicit bf: CanBuildFrom[Repr, (A1, Int), That]): That = {
+    val b = bf(repr)
+    val len = length
+    b.sizeHint(len)
+    var i = 0
+    while (i < len) {
+      b += ((this(i), i))
+      i += 1
+    }
+    b.result
+  }
+  
+  override /*IterableLike*/
+  def slice(from: Int, until: Int): Repr = {
+    var i = from max 0
+    val end = until min length
+    val b = newBuilder
+    b.sizeHint(end - i)
+    while (i < end) {
+      b += this(i)
+      i += 1
+    }
+    b.result
+  }
+
+  override /*IterableLike*/
+  def head: A = if (isEmpty) super.head else this(0)
+
+  override /*TraversableLike*/
+  def tail: Repr = if (isEmpty) super.tail else slice(1, length)
+
+  override /*TraversableLike*/
+  def last: A = if (length > 0) this(length - 1) else super.last
+
+  override /*IterableLike*/
+  def init: Repr = if (length > 0) slice(0, length - 1) else super.init
+
+  override /*TraversableLike*/
+  def take(n: Int): Repr = slice(0, n)
+
+  override /*TraversableLike*/
+  def drop(n: Int): Repr = slice(n, length)
+
+  override /*IterableLike*/
+  def takeRight(n: Int): Repr = slice(length - n, length)
+
+  override /*IterableLike*/
+  def dropRight(n: Int): Repr = slice(0, length - n)
+
+  override /*TraversableLike*/
+  def splitAt(n: Int): (Repr, Repr) = (take(n), drop(n))
+
+  override /*IterableLike*/
+  def takeWhile(p: A => Boolean): Repr = take(prefixLength(p))
+
+  override /*TraversableLike*/
+  def dropWhile(p: A => Boolean): Repr = drop(prefixLength(p))
+
+  override /*TraversableLike*/
+  def span(p: A => Boolean): (Repr, Repr) = splitAt(prefixLength(p))
+
+  override /*IterableLike*/
+  def sameElements[B >: A](that: Iterable[B]): Boolean = that match {
+    case that: IndexedSeq[_] =>
+      val len = length
+      len == that.length && {
+        var i = 0
+        while (i < len && this(i) == that(i)) i += 1
+        i == len
+      }
+    case _ =>
+      super.sameElements(that)
+  }        
+  
+  override /*IterableLike*/
+  def copyToArray[B >: A](xs: Array[B], start: Int, len: Int) {
+    var i = 0
+    var j = start
+    val end = length min len min (xs.length - start)
+    while (i < end) {
+      xs(j) = this(i)
+      i += 1
+      j += 1
+    }
+  }
+
+
+  // Overridden methods from Seq
+  
+  override /*SeqLike*/
+  def lengthCompare(len: Int): Int = length - len
+  
+  override /*SeqLike*/
+  def segmentLength(p: A => Boolean, from: Int): Int = {
+    val start = from
+    val len = length
+    var i = start
+    while (i < len && p(this(i))) i += 1
+    i - start
+  }
+
+  private def negLength(n: Int) = if (n == length) -1 else n
+
+  override /*SeqLike*/
+  def indexWhere(p: A => Boolean, from: Int): Int = {
+    val start = from max 0
+    negLength(start + segmentLength(!p(_), start))
+  }	
+
+  override /*SeqLike*/
+  def lastIndexWhere(p: A => Boolean, end: Int): Int = {
+    var i = end
+    while (i >= 0 && !p(this(i))) i -= 1
+    i
+  }
+
+  override /*SeqLike*/
+  def reverse: Repr = {
+    val b = newBuilder
+    b.sizeHint(length)
+    var i = length
+    while (0 < i) {
+      i -= 1
+      b += this(i)
+    }
+    b.result
+  }
+
+  override /*SeqLike*/
+  def reverseIterator: Iterator[A] = new Iterator[A] {
+    private var i = self.length
+    def hasNext: Boolean = 0 < i
+    def next: A = 
+      if (0 < i) {
+        i -= 1
+        self(i)
+      } else Iterator.empty.next
+  }
+
+  override /*SeqLike*/
+  def startsWith[B](that: Seq[B], offset: Int): Boolean = that match {
+    case that: IndexedSeq[_] =>
+      var i = offset
+      var j = 0
+      val thisLen = length
+      val thatLen = that.length
+      while (i < thisLen && j < thatLen && this(i) == that(j)) {
+        i += 1
+        j += 1
+      }
+      j == thatLen
+    case _ =>
+      var i = offset
+      val thisLen = length
+      val thatElems = that.iterator
+      while (i < thisLen && thatElems.hasNext) {
+        if (this(i) != thatElems.next())
+          return false
+        
+        i += 1
+      }
+      !thatElems.hasNext
+  }
+
+  override /*SeqLike*/
+  def endsWith[B](that: Seq[B]): Boolean = that match {
+    case that: IndexedSeq[_] =>
+      var i = length - 1
+      var j = that.length - 1
+      
+      (j <= i) && {
+        while (j >= 0) {
+          if (this(i) != that(j))
+            return false
+          i -= 1
+          j -= 1
+        }
+        true
+      }
+    case _ =>
+      super.endsWith(that)
+  }
+}
+
diff --git a/src/library/scala/collection/Iterable.scala b/src/library/scala/collection/Iterable.scala
new file mode 100644
index 0000000..2c29d07
--- /dev/null
+++ b/src/library/scala/collection/Iterable.scala
@@ -0,0 +1,59 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+
+import generic._
+import scala.util.control.Breaks._
+import mutable.Builder
+
+/** A base trait for iterable collections.
+ *  $iterableInfo
+ */
+trait Iterable[+A] extends Traversable[A] 
+                      with GenericTraversableTemplate[A, Iterable]
+                      with IterableLike[A, Iterable[A]] {
+   override def companion: GenericCompanion[Iterable] = Iterable
+ 
+  /* The following methods are inherited from trait IterableLike
+   *
+  override def iterator: Iterator[A]
+  override def takeRight(n: Int): Iterable[A]
+  override def dropRight(n: Int): Iterable[A]
+  override def sameElements[B >: A](that: Iterable[B]): Boolean
+  override def view
+  override def view(from: Int, until: Int)
+  */
+
+}
+                                         
+/** $factoryInfo
+ *  The current default implementation of a $Coll is a `Vector`.
+ *  @define coll iterable collection
+ *  @define Coll Iterable
+ */
+object Iterable extends TraversableFactory[Iterable] {
+  
+  /** $genericCanBuildFromInfo */
+  implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, Iterable[A]] = new GenericCanBuildFrom[A]
+
+  def newBuilder[A]: Builder[A, Iterable[A]] = immutable.Iterable.newBuilder[A]
+  
+  /** The minimum element of a non-empty sequence of ordered elements */
+  @deprecated("use <seq>.min instead, where <seq> is the sequence for which you want to compute the minimum")
+  def min[A](seq: Iterable[A])(implicit ord: Ordering[A]): A = seq.min
+
+  /** The maximum element of a non-empty sequence of ordered elements */
+  @deprecated("use <seq>.max instead, where <seq> is the sequence for which you want to compute the maximum")
+  def max[A](seq: Iterable[A])(implicit ord: Ordering[A]): A = seq.max
+
+  @deprecated("use View instead")
+  type Projection[A] = IterableView[A, Coll]
+}
diff --git a/src/library/scala/collection/IterableLike.scala b/src/library/scala/collection/IterableLike.scala
new file mode 100644
index 0000000..65228fc
--- /dev/null
+++ b/src/library/scala/collection/IterableLike.scala
@@ -0,0 +1,394 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+package scala.collection
+import generic._
+import immutable.{List, Stream}
+import annotation.unchecked.uncheckedVariance
+
+/** A template trait for iterable collections of type `Iterable[A]`.
+ *  $iterableInfo
+ *  @define iterableInfo
+ *    This is a base trait for all $mutability Scala collections that define an `iterator`
+ *    method to step through one-by-one the collection's elements.
+ *    Implementations of this trait need to provide a concrete method with
+ *    signature:
+ *    {{{
+ *       def iterator: Iterator[A]
+ *    }}}
+ *    They also need to provide a method `newBuilder`
+ *    which creates a builder for collections of the same kind.
+ *
+ *    This trait implements `Iterable`'s `foreach`
+ *    method by stepping through all elements using `iterator`.
+ *    Subclasses should re-implement `foreach` with something more efficient,
+ *    if possible.
+
+ *    This trait adds methods `iterator`, `sameElements`,
+ *    `takeRight`, `dropRight` to the methods inherited
+ *    from trait <a href="../Traversable.html" target="ContentFrame">
+ *    `Traversable`</a>.
+
+ *    Note: This trait replaces every method that uses `break` in
+ *    `TraversableLike` by an iterator version.
+ *
+ *  @author Martin Odersky
+ *  @version 2.8
+ *  @since   2.8
+ *  @tparam A    the element type of the collection
+ *  @tparam Repr the type of the actual collection containing the elements.
+ *
+ *  @define Coll Iterable
+ *  @define coll iterable collection
+ *  @define zipthatinfo the class of the returned collection. Where possible, `That` is 
+ *    the same class as the current collection class `Repr`, but this
+ *    depends on the element type `(A1, B)` being admissible for that class,
+ *    which means that an implicit instance of type `CanBuildFrom[Repr, (A1, B), That]`.
+ *    is found.
+ *  @define zipbfinfo  an implicit value of class `CanBuildFrom` which determines the
+ *    result class `That` from the current representation type `Repr`
+ *    and the new element type `(A1, B)`. 
+ */
+trait IterableLike[+A, +Repr] extends Equals with TraversableLike[A, Repr] { 
+self =>
+
+  override protected[this] def thisCollection: Iterable[A] = this.asInstanceOf[Iterable[A]]
+  override protected[this] def toCollection(repr: Repr): Iterable[A] = repr.asInstanceOf[Iterable[A]]
+
+  /** Creates a new iterator over all elements contained in this
+   *  iterable object.
+   *  
+   *  @return the new iterator
+   */
+  def iterator: Iterator[A]
+  
+  /** Applies a function `f` to all elements of this $coll.
+   *  
+   *    Note: this method underlies the implementation of most other bulk operations.
+   *    Subclasses should re-implement this method if a more efficient implementation exists.
+   *  
+   *  @usecase def foreach(f: A => Unit): Unit
+   */
+  def foreach[U](f: A => U): Unit = 
+    iterator.foreach(f)
+
+  override /*TraversableLike*/ def forall(p: A => Boolean): Boolean = 
+    iterator.forall(p)
+  override /*TraversableLike*/ def exists(p: A => Boolean): Boolean = 
+    iterator.exists(p)
+  override /*TraversableLike*/ def find(p: A => Boolean): Option[A] = 
+    iterator.find(p)
+/*
+  override /*TraversableLike*/ def mapFind[B](f: A => Option[B]): Option[B] = 
+    iterator.mapFind(f)
+*/
+  override /*TraversableLike*/ def isEmpty: Boolean = 
+    !iterator.hasNext
+  override /*TraversableLike*/ def foldRight[B](z: B)(op: (A, B) => B): B =
+    iterator.foldRight(z)(op)
+  override /*TraversableLike*/ def reduceRight[B >: A](op: (A, B) => B): B = 
+    iterator.reduceRight(op)
+  override /*TraversableLike*/ def toIterable: Iterable[A] = 
+    thisCollection
+
+  override /*TraversableLike*/ def head: A =
+    if (isEmpty) throw new NoSuchElementException
+    else iterator.next
+
+  override /*TraversableLike*/ def take(n: Int): Repr = {
+    val b = newBuilder
+    b.sizeHintBounded(n, this)
+    var i = 0
+    val it = iterator
+    while (i < n && it.hasNext) {
+      b += it.next
+      i += 1
+    }
+    b.result
+  }
+  
+  override /*TraversableLike*/ def slice(from: Int, until: Int): Repr = {
+    val b = newBuilder
+    b.sizeHintBounded(until - from, this)
+    var i = from
+    val it = iterator drop from
+    while (i < until && it.hasNext) {
+      b += it.next
+      i += 1
+    }
+    b.result
+  }
+
+  override /*TraversableLike*/ def takeWhile(p: A => Boolean): Repr = {
+    val b = newBuilder
+    val it = iterator
+    while (it.hasNext) {
+      val x = it.next
+      if (!p(x)) return b.result
+      b += x
+    }
+    b.result
+  }
+  
+  /** Partitions elements in fixed size ${coll}s.
+   *  @see Iterator#grouped   
+   *
+   *  @param size the number of elements per group
+   *  @return An iterator producing ${coll}s of size `size`, except the
+   *          last will be truncated if the elements don't divide evenly.
+   */
+  def grouped(size: Int): Iterator[Repr] =
+    for (xs <- iterator grouped size) yield {
+      val b = newBuilder
+      b ++= xs
+      b.result
+    }
+  
+  /** Groups elements in fixed size blocks by passing a "sliding window"
+   *  over them (as opposed to partitioning them, as is done in grouped.)
+   *  @see Iterator#sliding   
+   *
+   *  @param size the number of elements per group
+   *  @param step the distance between the first elements of successive
+   *         groups (defaults to 1)
+   *  @return An iterator producing ${coll}s of size `size`, except the
+   *          last and the only element will be truncated if there are
+   *          fewer elements than size.
+   */
+  def sliding[B >: A](size: Int): Iterator[Repr] = sliding(size, 1)
+  def sliding[B >: A](size: Int, step: Int): Iterator[Repr] =
+    for (xs <- iterator.sliding(size, step)) yield {
+      val b = newBuilder
+      b ++= xs
+      b.result
+    }
+
+  /** Selects last ''n'' elements.
+   *  $orderDependent
+   *
+   *  @param n the number of elements to take
+   *  @return a $coll consisting only of the last `n` elements of this $coll, or else the
+   *          whole $coll, if it has less than `n` elements.
+   */
+  def takeRight(n: Int): Repr = {
+    val b = newBuilder
+    b.sizeHintBounded(n, this)
+    val lead = this.iterator drop n
+    var go = false
+    for (x <- this) {
+      if (lead.hasNext) lead.next
+      else go = true
+      if (go) b += x
+    }
+    b.result
+  }
+
+  /** Selects all elements except last ''n'' ones. 
+   *  $orderDependent
+   *  
+   *  @param  n    The number of elements to take
+   *  @return a $coll consisting of all elements of this $coll except the first `n` ones, or else the
+   *          empty $coll, if this $coll has less than `n` elements.
+   */
+  def dropRight(n: Int): Repr = {
+    val b = newBuilder
+    if (n >= 0) b.sizeHint(this, -n)
+    val lead = iterator drop n
+    val it = iterator
+    while (lead.hasNext) {
+      b += it.next
+      lead.next
+    }
+    b.result
+  }
+
+  override /*TraversableLike*/ def copyToArray[B >: A](xs: Array[B], start: Int, len: Int) {
+    var i = start
+    val end = (start + len) min xs.length
+    val it = iterator
+    while (i < end && it.hasNext) {
+      xs(i) = it.next
+      i += 1
+    }
+  }
+
+  /** Returns a $coll formed from this $coll and another iterable collection
+   *  by combining corresponding elements in pairs.
+   *  If one of the two collections is longer than the other, its remaining elements are ignored.
+   * 
+   *  $orderDependent
+   *  
+   *  @param   that  The iterable providing the second half of each result pair
+   *  @tparam  A1    the type of the first half of the returned pairs (this is always a supertype
+   *                 of the collection's element type `A`).
+   *  @tparam  B     the type of the second half of the returned pairs
+   *  @tparam  That  $zipthatinfo
+   *  @param   bf    $zipbfinfo
+   *  @return        a new collection of type `That` containing pairs consisting of
+   *                 corresponding elements of this $coll and `that`. The length
+   *                 of the returned collection is the minimum of the lengths of this $coll and `that`.
+   *
+   *  @usecase def zip[B](that: Iterable[B]): $Coll[(A, B)]
+   *
+   *  @param   that  The iterable providing the second half of each result pair
+   *  @tparam  B     the type of the second half of the returned pairs
+   *  @return        a new $coll containing pairs consisting of
+   *                 corresponding elements of this $coll and `that`. The length
+   *                 of the returned collection is the minimum of the lengths of this $coll and `that`.
+   */
+  def zip[A1 >: A, B, That](that: Iterable[B])(implicit bf: CanBuildFrom[Repr, (A1, B), That]): That = {
+    val b = bf(repr)
+    val these = this.iterator
+    val those = that.iterator
+    while (these.hasNext && those.hasNext)
+      b += ((these.next, those.next))
+    b.result
+  }
+
+  /** Returns a $coll formed from this $coll and another iterable collection
+   *  by combining corresponding elements in pairs.
+   *  If one of the two collections is shorter than the other,
+   *  placeholder elements are used to extend the shorter collection to the length of the longer.
+   * 
+   *  $orderDependent
+   *
+   *  @param that     the iterable providing the second half of each result pair
+   *  @param thisElem the element to be used to fill up the result if this $coll is shorter than `that`.
+   *  @param thatElem the element to be used to fill up the result if `that` is shorter than this $coll.
+   *  @return        a new collection of type `That` containing pairs consisting of
+   *                 corresponding elements of this $coll and `that`. The length
+   *                 of the returned collection is the maximum of the lengths of this $coll and `that`.
+   *                 If this $coll is shorter than `that`, `thisElem` values are used to pad the result.
+   *                 If `that` is shorter than this $coll, `thatElem` values are used to pad the result.
+   * 
+   *  @usecase def zipAll[B](that: Iterable[B], thisElem: A, thatElem: B): $Coll[(A, B)]
+   *
+   *  @param   that  The iterable providing the second half of each result pair
+   *  @param thisElem the element to be used to fill up the result if this $coll is shorter than `that`.
+   *  @param thatElem the element to be used to fill up the result if `that` is shorter than this $coll.
+   *  @tparam  B     the type of the second half of the returned pairs
+   *  @return        a new $coll containing pairs consisting of
+   *                 corresponding elements of this $coll and `that`. The length
+   *                 of the returned collection is the maximum of the lengths of this $coll and `that`.
+   *                 If this $coll is shorter than `that`, `thisElem` values are used to pad the result.
+   *                 If `that` is shorter than this $coll, `thatElem` values are used to pad the result.
+   */
+  def zipAll[B, A1 >: A, That](that: Iterable[B], thisElem: A1, thatElem: B)(implicit bf: CanBuildFrom[Repr, (A1, B), That]): That = {  
+    val b = bf(repr)
+    val these = this.iterator
+    val those = that.iterator
+    while (these.hasNext && those.hasNext)
+      b += ((these.next, those.next))
+    while (these.hasNext)
+      b += ((these.next, thatElem))
+    while (those.hasNext)
+      b += ((thisElem, those.next))
+    b.result
+  }
+
+  /** Zips this $coll with its indices.
+   *
+   *  $orderDependent
+   * 
+   *  @tparam  A1    the type of the first half of the returned pairs (this is always a supertype
+   *                 of the collection's element type `A`).
+   *  @tparam  That  the class of the returned collection. Where possible, `That` is 
+   *    the same class as the current collection class `Repr`, but this
+   *    depends on the element type `(A1, Int)` being admissible for that class,
+   *    which means that an implicit instance of type `CanBuildFrom[Repr, (A1, Int), That]`.
+   *    is found.
+   *  @tparam  bf    an implicit value of class `CanBuildFrom` which determines the
+   *    result class `That` from the current representation type `Repr`
+   *    and the new element type `(A1, Int)`.
+   *  @return        A new collection of type `That` containing pairs consisting of all elements of this
+   *                 $coll paired with their index. Indices start at `0`.
+   *
+   *  @usecase def zipWithIndex: $Coll[(A, Int)]
+   *
+   *  @return        A new $coll containing pairs consisting of all elements of this
+   *                 $coll paired with their index. Indices start at `0`.
+   *  @example
+   *    `List("a", "b", "c").zipWithIndex = List(("a", 0), ("b", 1), ("c", 2))`
+   *  
+   */
+  def zipWithIndex[A1 >: A, That](implicit bf: CanBuildFrom[Repr, (A1, Int), That]): That = {
+    val b = bf(repr)
+    var i = 0
+    for (x <- this) {
+      b += ((x, i))
+      i +=1 
+    }
+    b.result
+  }
+
+  /** Checks if the other iterable collection contains the same elements in the same order as this $coll.
+   *
+   *  $orderDependent
+   *  $willNotTerminateInf
+   *
+   *  @param that  the collection to compare with.
+   *  @tparam B    the type of the elements of collection `that`. 
+   *  @return `true`, if both collections contain the same elements in the same order, `false` otherwise.
+   *
+   *  @usecase  def sameElements(that: Iterable[A]): Boolean
+   * 
+   *  @param that  the collection to compare with.
+   *  @return `true`, if both collections contain the same elements in the same order, `false` otherwise.
+   */
+  def sameElements[B >: A](that: Iterable[B]): Boolean = {
+    val these = this.iterator
+    val those = that.iterator
+    while (these.hasNext && those.hasNext)
+      if (these.next != those.next)
+        return false
+
+    !these.hasNext && !those.hasNext
+  }                                                                                         
+
+  override /*TraversableLike*/ def toStream: Stream[A] = iterator.toStream
+  
+  /** Converts this $coll to a sequence.
+   *
+   *  $willNotTerminateInf
+   *  @return a sequence containing all the elements of this $coll.
+   */
+  override /*TraversableOnce*/ def toSeq: Seq[A] = toList
+  
+  /** Method called from equality methods, so that user-defined subclasses can 
+   *  refuse to be equal to other collections of the same kind.
+   *  @param   that   The object with which this $coll should be compared
+   *  @return  `true`, if this $coll can possibly equal `that`, `false` otherwise. The test
+   *           takes into consideration only the run-time types of objects but ignores their elements.
+   */
+  override /*TraversableLike*/ def canEqual(that: Any) = true
+
+  override /*TraversableLike*/ def view = new IterableView[A, Repr] {
+    protected lazy val underlying = self.repr
+    override def iterator = self.iterator
+  }
+
+  override /*TraversableLike*/ def view(from: Int, until: Int) = view.slice(from, until)
+  
+  @deprecated("use `iterator' instead")
+  def elements = iterator
+
+  @deprecated("use `head' instead") def first: A = head
+
+  /** `None` if iterable is empty.
+   */
+  @deprecated("use `headOption' instead") def firstOption: Option[A] = headOption
+
+  /** 
+   * returns a projection that can be used to call non-strict `filter`,
+   * `map`, and `flatMap` methods that build projections
+   * of the collection.
+   */
+  @deprecated("use `view' instead")
+  def projection = view
+}
diff --git a/src/library/scala/collection/IterableProxy.scala b/src/library/scala/collection/IterableProxy.scala
new file mode 100644
index 0000000..bf18b62
--- /dev/null
+++ b/src/library/scala/collection/IterableProxy.scala
@@ -0,0 +1,24 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+
+import generic._
+
+/** <p>
+ *    This trait implements a proxy for iterable objects. It forwards
+ *    all calls to a different iterable object.
+ *  </p>
+ *
+ *  @author  Martin Odersky
+ *  @version 2.8
+ *  @since   2.8
+ */
+trait IterableProxy[+A] extends Iterable[A] with IterableProxyLike[A, Iterable[A]] 
diff --git a/src/library/scala/collection/IterableProxyLike.scala b/src/library/scala/collection/IterableProxyLike.scala
new file mode 100644
index 0000000..80e0b8e
--- /dev/null
+++ b/src/library/scala/collection/IterableProxyLike.scala
@@ -0,0 +1,40 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+
+import generic._
+import mutable.Buffer
+
+// Methods could be printed by  cat IterableLike.scala | egrep '^  (override )?def'
+
+/** This trait implements a proxy for Iterable objects. It forwards
+ *  all calls to a different Iterable object.
+ *
+ *  @author  Martin Odersky
+ *  @version 2.8
+ *  @since   2.8
+ */
+trait IterableProxyLike[+A, +Repr <: IterableLike[A, Repr] with Iterable[A]]
+    extends IterableLike[A, Repr]
+    with TraversableProxyLike[A, Repr] {  
+  override def iterator: Iterator[A] = self.iterator
+  override def grouped(size: Int): Iterator[Repr] = self.grouped(size)
+  override def sliding[B >: A](size: Int): Iterator[Repr] = self.sliding(size)
+  override def sliding[B >: A](size: Int, step: Int): Iterator[Repr] = self.sliding(size, step)
+  override def takeRight(n: Int): Repr = self.takeRight(n)
+  override def dropRight(n: Int): Repr = self.dropRight(n)
+  override def zip[A1 >: A, B, That](that: Iterable[B])(implicit bf: CanBuildFrom[Repr, (A1, B), That]): That = self.zip[A1, B, That](that)(bf)
+  override def zipAll[B, A1 >: A, That](that: Iterable[B], thisElem: A1, thatElem: B)(implicit bf: CanBuildFrom[Repr, (A1, B), That]): That = self.zipAll(that, thisElem, thatElem)(bf)
+  override def zipWithIndex[A1 >: A, That](implicit bf: CanBuildFrom[Repr, (A1, Int), That]): That = self.zipWithIndex(bf)
+  override def sameElements[B >: A](that: Iterable[B]): Boolean = self.sameElements(that)
+  override def view = self.view
+  override def view(from: Int, until: Int) = self.view(from, until)
+}
diff --git a/src/library/scala/collection/IterableView.scala b/src/library/scala/collection/IterableView.scala
new file mode 100644
index 0000000..326dfc7
--- /dev/null
+++ b/src/library/scala/collection/IterableView.scala
@@ -0,0 +1,31 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+
+import generic._
+import TraversableView.NoBuilder
+
+/** A base trait for non-strict views of `Iterable`s.
+ *  $iterableViewInfo
+ */
+trait IterableView[+A, +Coll] extends IterableViewLike[A, Coll, IterableView[A, Coll]]
+
+/** An object containing the necessary implicit definitions to make
+ *  `IterableView`s work. Its definitions are generally not accessed directly by clients.
+ */
+object IterableView {
+  type Coll = TraversableView[_, C] forSome {type C <: Traversable[_]}
+  implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, IterableView[A, Iterable[_]]] = 
+    new CanBuildFrom[Coll, A, IterableView[A, Iterable[_]]] { 
+      def apply(from: Coll) = new NoBuilder 
+      def apply() = new NoBuilder 
+    }
+}
diff --git a/src/library/scala/collection/IterableViewLike.scala b/src/library/scala/collection/IterableViewLike.scala
new file mode 100644
index 0000000..cccbbe8
--- /dev/null
+++ b/src/library/scala/collection/IterableViewLike.scala
@@ -0,0 +1,126 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+
+import generic._
+import collection.immutable.Stream
+import TraversableView.NoBuilder
+
+/** A template trait for non-strict views of iterable collections.
+ *  $iterableViewInfo
+ *
+ *  @define iterableViewInfo
+ *  $viewInfo
+ *  All views for iterable collections are defined by re-interpreting the `iterator` method.
+ * 
+ *  @author Martin Odersky
+ *  @version 2.8
+ *  @since   2.8
+ *  @tparam A    the element type of the view
+ *  @tparam Coll the type of the underlying collection containing the elements.
+ *  @tparam This the type of the view itself
+ */
+trait IterableViewLike[+A, 
+                       +Coll,
+                       +This <: IterableView[A, Coll] with IterableViewLike[A, Coll, This]] 
+extends Iterable[A] with IterableLike[A, This] with TraversableView[A, Coll] with TraversableViewLike[A, Coll, This]  
+{ self =>
+
+  trait Transformed[+B] extends IterableView[B, Coll] with super.Transformed[B]
+
+  trait Forced[B] extends Transformed[B] with super.Forced[B] {
+    override def iterator = forced.iterator
+  }
+
+  trait Sliced extends Transformed[A] with super.Sliced {
+    override def iterator = self.iterator slice (from, until)
+  }
+
+  trait Mapped[B] extends Transformed[B] with super.Mapped[B] {
+    override def iterator = self.iterator map mapping
+  }
+
+  trait FlatMapped[B] extends Transformed[B] with super.FlatMapped[B] {
+    override def iterator = self.iterator flatMap (mapping(_).toIterable.iterator)
+  }
+    
+  trait Appended[B >: A] extends Transformed[B] with super.Appended[B] {
+    override def iterator = self.iterator ++ rest.toIterable.iterator
+  }
+
+  trait Filtered extends Transformed[A] with super.Filtered {
+    override def iterator = self.iterator filter pred
+  }
+    
+  trait TakenWhile extends Transformed[A] with super.TakenWhile {
+    override def iterator = self.iterator takeWhile pred
+  }
+
+  trait DroppedWhile extends Transformed[A] with super.DroppedWhile {
+    override def iterator = self.iterator dropWhile pred
+  }
+
+  trait Zipped[B] extends Transformed[(A, B)] {
+    protected[this] val other: Iterable[B]
+    override def iterator: Iterator[(A, B)] = self.iterator zip other.iterator
+    override def stringPrefix = self.stringPrefix+"Z"
+  }
+  
+  trait ZippedAll[A1 >: A, B] extends Transformed[(A1, B)] {
+    protected[this] val other: Iterable[B]
+    protected[this] val thisElem: A1
+    protected[this] val thatElem: B
+    override def iterator: Iterator[(A1, B)] = 
+      self.iterator.zipAll(other.iterator, thisElem, thatElem)
+  }
+  
+  override def zip[A1 >: A, B, That](that: Iterable[B])(implicit bf: CanBuildFrom[This, (A1, B), That]): That = {
+    newZipped(that).asInstanceOf[That]
+// was:    val b = bf(repr)
+//    if (b.isInstanceOf[NoBuilder[_]]) newZipped(that).asInstanceOf[That]
+//    else super.zip[A1, B, That](that)(bf)    
+  }
+
+  override def zipWithIndex[A1 >: A, That](implicit bf: CanBuildFrom[This, (A1, Int), That]): That =
+    zip[A1, Int, That](Stream from 0)(bf)
+
+  override def zipAll[B, A1 >: A, That](that: Iterable[B], thisElem: A1, thatElem: B)(implicit bf: CanBuildFrom[This, (A1, B), That]): That =
+    newZippedAll(that, thisElem, thatElem).asInstanceOf[That]
+
+  protected def newZipped[B](that: Iterable[B]): Transformed[(A, B)] = new Zipped[B] {
+    val other = that
+  }
+  protected def newZippedAll[A1 >: A, B](that: Iterable[B], _thisElem: A1, _thatElem: B): Transformed[(A1, B)] = new ZippedAll[A1, B] {
+    val other: Iterable[B] = that
+    val thisElem = _thisElem
+    val thatElem = _thatElem
+  }
+   
+  /** Boilerplate method, to override in each subclass
+   *  This method could be eliminated if Scala had virtual classes
+   */
+  protected override def newForced[B](xs: => Seq[B]): Transformed[B] = new Forced[B] { val forced = xs }
+  protected override def newAppended[B >: A](that: Traversable[B]): Transformed[B] = new Appended[B] { val rest = that }
+  protected override def newMapped[B](f: A => B): Transformed[B] = new Mapped[B] { val mapping = f }
+  protected override def newFlatMapped[B](f: A => Traversable[B]): Transformed[B] = new FlatMapped[B] { val mapping = f }
+  protected override def newFiltered(p: A => Boolean): Transformed[A] = new Filtered { val pred = p }
+  protected override def newSliced(_from: Int, _until: Int): Transformed[A] = new Sliced { val from = _from; val until = _until }
+  protected override def newDroppedWhile(p: A => Boolean): Transformed[A] = new DroppedWhile { val pred = p }
+  protected override def newTakenWhile(p: A => Boolean): Transformed[A] = new TakenWhile { val pred = p }
+
+  override def grouped(size: Int): Iterator[This] = 
+    self.iterator.grouped(size).map(xs => newForced(xs).asInstanceOf[This])
+
+  override def sliding[B >: A](size: Int, step: Int): Iterator[This] =
+    self.iterator.sliding(size).map(xs => newForced(xs).asInstanceOf[This])
+
+  override def stringPrefix = "IterableView"
+}
diff --git a/src/library/scala/collection/Iterator.scala b/src/library/scala/collection/Iterator.scala
new file mode 100644
index 0000000..1b205f5
--- /dev/null
+++ b/src/library/scala/collection/Iterator.scala
@@ -0,0 +1,1066 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+
+import mutable.ArrayBuffer
+import annotation.{ tailrec, migration }
+
+/** The `Iterator` object provides various functions for
+ *  creating specialized iterators.
+ *
+ *  @author  Martin Odersky
+ *  @author  Matthias Zenger
+ *  @version 2.8
+ *  @since   2.8
+ */
+object Iterator {
+
+  /** The iterator which produces no values */
+  val empty = new Iterator[Nothing] {
+    def hasNext: Boolean = false
+    def next(): Nothing = throw new NoSuchElementException("next on empty iterator")
+  }
+
+  /** Creates an iterator which produces a single element.
+   *  '''Note:''' Equivalent, but more efficient than Iterator(elem)
+   *  @param elem the element
+   *  @return An iterator which produces `elem` on the first call to `next`,
+   *          and which has no further elements.
+   */
+  def single[A](elem: A) = new Iterator[A] {
+    private var hasnext = true
+    def hasNext: Boolean = hasnext
+    def next(): A =
+      if (hasnext) { hasnext = false; elem }
+      else empty.next()
+  }
+
+  /** Creates an iterator with given elements
+   *  @param elems  The elements returned one-by-one from the iterator
+   *  @return An iterator which produces the given elements on the
+   *          first calls to `next`, and which has no further elements.
+   */
+  def apply[A](elems: A*): Iterator[A] = elems.iterator
+
+  /** Creates iterator that produces the results of some element computation
+   *  a number of times.
+   *  @param   n  the number of elements returned by the iterator.
+   *  @param   elem the element computation
+   *  @return  An iterator that produces the results of `n` evaluations of `elem`.
+   */
+  def fill[A](len: Int)(elem: => A) = new Iterator[A] {
+    private var i = 0
+    def hasNext: Boolean = i < len
+    def next(): A =
+      if (hasNext) { i += 1; elem }
+      else empty.next()
+  }
+
+  /** Creates an iterator producing the values of a given function over a range of integer values starting from 0.
+   *  @param  n   The number of elements returned by the iterator
+   *  @param  f   The function computing element values
+   *  @return An iterator that produces the values `f(0), ..., f(n -1)`.
+   */	
+  def tabulate[A](end: Int)(f: Int => A) = new Iterator[A] {
+    private var i = 0
+    def hasNext: Boolean = i < end
+    def next(): A =
+      if (hasNext) { val result = f(i); i += 1; result }
+      else empty.next()
+  }    
+
+  /** Creates nn iterator returning successive values in some integer interval.
+   *  
+   *  @param start the start value of the iterator
+   *  @param end   the end value of the iterator (the first value NOT returned)
+   *  @return      the iterator producing values `start, start + 1, ..., end - 1`
+   */
+  def range(start: Int, end: Int): Iterator[Int] = range(start, end, 1)
+
+  /** An iterator producing equally spaced values in some integer interval.
+   *
+   *  @param start the start value of the iterator
+   *  @param end   the end value of the iterator (the first value NOT returned)
+   *  @param step  the increment value of the iterator (must be positive or negative)
+   *  @return      the iterator producing values `start, start + step, ...` up to, but excluding `end`
+   */
+  def range(start: Int, end: Int, step: Int) = new Iterator[Int] {
+    if (step == 0) throw new IllegalArgumentException("zero step")
+    private var i = start
+    def hasNext: Boolean = (step <= 0 || i < end) && (step >= 0 || i > end)
+    def next(): Int =
+      if (hasNext) { val result = i; i += step; result }
+      else empty.next()
+  }
+
+  /** Creates an infinite iterator that repeatedly applies a given function to the previous result.
+   *
+   *  @param start the start value of the iterator
+   *  @param f     the function that's repeatedly applied
+   *  @return      the iterator producing the infinite sequence of values `start, f(start), f(f(start)), ...`
+   */
+  def iterate[T](start: T)(f: T => T): Iterator[T] = new Iterator[T] {
+    private[this] var first = true
+    private[this] var acc = start
+    def hasNext: Boolean = true
+    def next(): T = {
+      if (first) first = false
+      else acc = f(acc)
+      
+      acc
+    }
+  }
+
+  /** Creates an infinite-length iterator which returns successive values from some start value.
+
+   *  @param start the start value of the iterator
+   *  @return      the iterator producing the infinite sequence of values `start, start + 1, start + 2, ...`
+   */
+  def from(start: Int): Iterator[Int] = from(start, 1)
+
+  /** Creates an infinite-length iterator returning values equally spaced apart.
+   *
+   *  @param start the start value of the iterator
+   *  @param step  the increment between successive values
+   *  @return      the iterator producing the infinite sequence of values `start, start + 1 * step, start + 2 * step, ...`
+   */
+  def from(start: Int, step: Int): Iterator[Int] = new Iterator[Int] {
+    private var i = start
+    def hasNext: Boolean = true
+    def next(): Int = { val result = i; i += step; result }
+  }
+
+  /** Creates an infinite-length iterator returning the results of evaluating
+   *  an expression. The expression is recomputed for every element.
+   *
+   *  @param elem the element computation.
+   *  @return the iterator containing an infinite number of results of evaluating `elem`.
+   */
+  def continually[A](elem: => A): Iterator[A] = new Iterator[A] {
+    def hasNext = true
+    def next = elem
+  }
+  
+  /** With the advent of TraversableOnce, it can be useful to have a builder
+   *  for Iterators so they can be treated uniformly along with the collections.
+   *  See scala.util.Random.shuffle for an example.
+   */
+  class IteratorCanBuildFrom[A] extends generic.CanBuildFrom[Iterator[A], A, Iterator[A]] {
+    def newIterator = new ArrayBuffer[A] mapResult (_.iterator)
+    
+    /** Creates a new builder on request of a collection.
+     *  @param from  the collection requesting the builder to be created.
+     *  @return the result of invoking the `genericBuilder` method on `from`.
+     */
+    def apply(from: Iterator[A]) = newIterator
+    
+    /** Creates a new builder from scratch
+     *  @return the result of invoking the `newBuilder` method of this factory.
+     */
+    def apply() = newIterator
+  }
+  
+  implicit def iteratorCanBuildFrom[T]: IteratorCanBuildFrom[T] = new IteratorCanBuildFrom[T]  
+
+  /** A wrapper class for the `flatten` method that is added to
+   *  class `Iterator` with implicit conversion
+   *  @see iteratorIteratorWrapper.
+   */
+  class IteratorIteratorOps[A](its: Iterator[Iterator[A]]) {
+    /** If `its` is an iterator of iterators, `its.flatten` gives the iterator
+     *  that is the concatenation of all iterators in `its`.
+     */
+    def flatten: Iterator[A] = new Iterator[A] {
+      private var it: Iterator[A] = empty
+      def hasNext: Boolean = it.hasNext || its.hasNext && { it = its.next(); hasNext }
+      def next(): A = if (hasNext) it.next() else empty.next()
+    }
+  }
+
+  /** An implicit conversion which adds the `flatten` method to class `Iterator` */
+  implicit def iteratorIteratorWrapper[A](its: Iterator[Iterator[A]]): IteratorIteratorOps[A] = 
+    new IteratorIteratorOps[A](its)
+
+  @deprecated("use `xs.iterator' or `Iterator(xs)' instead")
+  def fromValues[a](xs: a*) = xs.iterator
+
+  /** @param xs the array of elements
+   *  @see also: IndexedSeq.iterator and slice
+   */
+  @deprecated("use `xs.iterator' instead")
+  def fromArray[a](xs: Array[a]): Iterator[a] =
+    fromArray(xs, 0, xs.length)
+
+  /**
+   *  @param xs     the array of elements
+   *  @param start  the start index
+   *  @param length  the length
+   *  @see also: IndexedSeq.iterator and slice
+   */
+  @deprecated("use `xs.slice(start, start + length).iterator' instead")
+  def fromArray[a](xs: Array[a], start: Int, length: Int): Iterator[a] =
+    xs.slice(start, start + length).iterator
+
+  /**
+   *  @param n the product arity
+   *  @return  the iterator on `Product<n>`.
+   */
+  @deprecated("use product.productIterator instead")
+  def fromProduct(n: Product): Iterator[Any] = new Iterator[Any] {
+    private var c: Int = 0
+    private val cmax = n.productArity
+    def hasNext = c < cmax
+    def next() = { val a = n productElement c; c += 1; a }
+  }
+
+  /** Create an iterator with elements
+   *  `e<sub>n+1</sub> = step(e<sub>n</sub>)`
+   *  where `e<sub>0</sub> = start`
+   *  and elements are in the range between `start` (inclusive)
+   *  and `end` (exclusive)
+   *
+   *  @param start the start value of the iterator
+   *  @param end   the end value of the iterator
+   *  @param step  the increment function of the iterator, must be monotonically increasing or decreasing
+   *  @return      the iterator with values in range `[start;end)`.
+   */
+  @deprecated("use Iterator.iterate(start, end - start)(step) instead")
+  def range(start: Int, end: Int, step: Int => Int) = new Iterator[Int] {
+    private val up = step(start) > start
+    private val down = step(start) < start
+    private var i = start
+    def hasNext: Boolean = (!up || i < end) && (!down || i > end)
+    def next(): Int =
+      if (hasNext) { val j = i; i = step(i); j }
+      else empty.next()
+  }
+
+  /** Create an iterator with elements
+   *  `e<sub>n+1</sub> = step(e<sub>n</sub>)`
+   *  where `e<sub>0</sub> = start`.
+   *
+   *  @param start the start value of the iterator
+   *  @param step  the increment function of the iterator
+   *  @return      the iterator starting at value `start`.
+   */
+  @deprecated("use iterate(start)(step) instead")
+  def from(start: Int, step: Int => Int): Iterator[Int] = new Iterator[Int] {
+    private var i = start
+    override def hasNext: Boolean = true
+    def next(): Int = { val j = i; i = step(i); j }
+  }
+
+  /** Create an iterator that is the concatenation of all iterators
+   *  returned by a given iterator of iterators.
+   *   @param its   The iterator which returns on each call to next
+   *                a new iterator whose elements are to be concatenated to the result.
+   */
+  @deprecated("use its.flatten instead")
+  def flatten[T](its: Iterator[Iterator[T]]): Iterator[T] = new Iterator[T] {
+    private var cur = its.next
+    def hasNext: Boolean = {
+      while (!cur.hasNext && its.hasNext) cur = its.next
+      cur.hasNext
+    }
+    def next(): T = 
+      (if (hasNext) cur else empty).next()
+  }
+}
+
+import Iterator.empty
+
+/** Iterators are data structures that allow to iterate over a sequence
+ *  of elements. They have a `hasNext` method for checking
+ *  if there is a next element available, and a `next` method
+ *  which returns the next element and discards it from the iterator.
+ *
+ *  @author  Martin Odersky, Matthias Zenger
+ *  @version 2.8
+ *  @since   1
+ *  @define willNotTerminateInf
+ *  Note: will not terminate for infinite iterators.
+ *  @define mayNotTerminateInf
+ *  Note: may not terminate for infinite iterators.
+ */
+trait Iterator[+A] extends TraversableOnce[A] {
+  self =>
+
+  /** Tests whether this iterator can provide another element.
+   *  @return  `true` if a subsequent call to `next` will yield an element,
+   *           `false` otherwise.
+   */
+  def hasNext: Boolean
+
+  /** Produces the next element of this iterator.
+   *  @return  the next element of this iterator, if `hasNext` is `true`,
+   *           undefined behavior otherwise.
+   */
+  def next(): A
+  
+  /** Tests whether this iterator is empty.
+   *  @return   `true` if hasNext is false, `false` otherwise.
+   */
+  def isEmpty: Boolean = !hasNext
+  
+  /** Tests whether this Iterator can be repeatedly traversed.
+   *  @return   `false`
+   */
+  def isTraversableAgain = false
+  
+  /** Tests whether this Iterator has a known size.
+   *
+   *  @return   `true` for empty Iterators, `false` otherwise.
+   */
+  def hasDefiniteSize = isEmpty
+  
+  /** Selects first ''n'' values of this iterator.
+   *  @param  n    the number of values to take
+   *  @return an iterator producing only of the first `n` values of this iterator, or else the
+   *          whole iterator, if it produces less than `n` values.
+   */
+  def take(n: Int): Iterator[A] = new Iterator[A] {
+    private var remaining = n
+    def hasNext = remaining > 0 && self.hasNext
+    def next(): A =
+      if (hasNext) { remaining -= 1; self.next() }
+      else empty.next()
+  }
+
+  /** Advances this iterator past the first ''n'' elements,
+   *  or the length of the iterator, whichever is smaller.
+   *
+   *  @param n the number of elements to drop
+   *  @return  an iterator which produces all values of the current iterator, except
+   *           it omits the first `n` values.
+   */
+  def drop(n: Int): Iterator[A] = {
+    @tailrec
+    def loop(left: Int): Iterator[A] =
+      if (left > 0 && hasNext) { next; loop(left - 1) }
+      else this
+    
+    loop(n)
+  }
+
+  /** Creates an iterator returning an interval of the values produced by this iterator.
+   *  @param from   the index of the first element in this iterator which forms part of the slice.
+   *  @param until  the index of the first element following the slice.
+   *  @return an iterator which advances this iterator past the first `from` elements using `drop`,
+   *  and then takes `until - from` elements, using `take`.
+   */
+  def slice(from: Int, until: Int): Iterator[A] = drop(from).take(until - from)
+
+  /** Creates a new iterator that maps all produced values of this iterator
+   *  to new values using a transformation function.
+   *  @param f  the transformation function
+   *  @return a new iterator which transforms every value produced by this
+   *          iterator by applying the function `f` to it.
+   */
+  def map[B](f: A => B): Iterator[B] = new Iterator[B] {
+    def hasNext = self.hasNext
+    def next() = f(self.next())
+  }
+
+  /** Concatenates this iterator with another.
+   *  @param   that   the other iterator
+   *  @return  a new iterator that first yields the values produced by this
+   *  iterator followed by the values produced by iterator `that`.
+   *  @usecase def ++(that: => Iterator[A]): Iterator[A]
+   */
+  def ++[B >: A](that: => Iterator[B]): Iterator[B] = new Iterator[B] {
+    // optimize a little bit to prevent n log n behavior.
+    private var cur : Iterator[B] = self
+    // since that is by-name, make sure it's only referenced once - 
+    // if "val it = that" is inside the block, then hasNext on an empty
+    // iterator will continually reevaluate it.  (ticket #3269)
+    lazy val it = that
+    // the eq check is to avoid an infinite loop on "x ++ x"
+    def hasNext = cur.hasNext || ((cur eq self) && {
+      it.hasNext && {
+        cur = it
+        true
+      }
+    })
+    def next() = { hasNext; cur.next() }
+  }
+
+  /** Creates a new iterator by applying a function to all values produced by this iterator
+   *  and concatenating the results. 
+   *
+   *  @param f the function to apply on each element.
+   *  @return   the iterator resulting from applying the given iterator-valued function
+   *                `f` to each value produced by this iterator and concatenating the results.
+   */
+  def flatMap[B](f: A => Iterator[B]): Iterator[B] = new Iterator[B] {
+    private var cur: Iterator[B] = empty
+    def hasNext: Boolean = 
+      cur.hasNext || self.hasNext && { cur = f(self.next); hasNext }
+    def next(): B = (if (hasNext) cur else empty).next() 
+  }
+
+  /** Returns an iterator over all the elements of this iterator that
+   *  satisfy the predicate `p`. The order of the elements
+   *  is preserved.
+   *
+   *  @param p the predicate used to test values.
+   *  @return  an iterator which produces those values of this iterator which satisfy the predicate `p`.
+   */
+  def filter(p: A => Boolean): Iterator[A] = new Iterator[A] {
+    private var hd: A = _
+    private var hdDefined: Boolean = false
+    
+    def hasNext: Boolean = hdDefined || {
+      do {
+        if (!self.hasNext) return false
+        hd = self.next()
+      } while (!p(hd))
+      hdDefined = true
+      true
+    }
+    
+    def next() = if (hasNext) { hdDefined = false; hd } else empty.next()
+  }
+
+  /** Creates an iterator over all the elements of this iterator that
+   *  satisfy the predicate `p`. The order of the elements
+   *  is preserved.
+   *
+   *  '''Note:''' `withFilter` is the same as `filter` on iterators. It exists so that
+   *  for-expressions with filters work over iterators. 
+   *
+   *  @param p the predicate used to test values.
+   *  @return  an iterator which produces those values of this iterator which satisfy the predicate `p`.
+   */                   
+  def withFilter(p: A => Boolean): Iterator[A] = filter(p)
+    
+  /** Creates an iterator over all the elements of this iterator which
+   *  do not satisfy a predicate p.
+   *
+   *  @param p the predicate used to test values.
+   *  @return  an iterator which produces those values of this iterator which do not satisfy the predicate `p`.
+   */
+  def filterNot(p: A => Boolean): Iterator[A] = filter(!p(_))
+  
+ /** Creates an iterator by transforming values
+  *  produced by this iterator with a partial function, dropping those
+  *  values for which the partial function is not defined.
+  *  @param pf the partial function which filters and maps the iterator.
+  *  @return a new iterator which yields each value `x` produced by this iterator for
+  *          which `pf` is defined the image `pf(x)`.
+  */
+  @migration(2, 8,
+    "This collect implementation bears no relationship to the one before 2.8.\n"+
+    "The previous behavior can be reproduced with toSeq."
+  )
+  def collect[B](pf: PartialFunction[A, B]): Iterator[B] = {
+    val self = buffered
+    new Iterator[B] {
+      private def skip() = while (self.hasNext && !pf.isDefinedAt(self.head)) self.next()
+      def hasNext = { skip(); self.hasNext }
+      def next() = { skip(); pf(self.next()) }
+    }
+  }
+
+  /** Takes longest prefix of values produced by this iterator that satisfy a predicate.
+   *  @param   p  The predicate used to test elements.
+   *  @return  An iterator returning the values produced by this iterator, until
+   *           this iterator produces a value that does not satisfy
+   *           the predicate `p`.
+   */
+  def takeWhile(p: A => Boolean): Iterator[A] = new Iterator[A] {
+    private var hd: A = _
+    private var hdDefined: Boolean = false
+    private var tail: Iterator[A] = self
+  
+    def hasNext = hdDefined || tail.hasNext && {
+      hd = tail.next()
+      if (p(hd)) hdDefined = true 
+      else tail = Iterator.empty
+      hdDefined
+    }
+    def next() = if (hasNext) { hdDefined = false; hd } else empty.next()
+  }
+
+  /** Partitions this iterator in two iterators according to a predicate.
+   *
+   *  @param p the predicate on which to partition
+   *  @return  a pair of iterators: the iterator that satisfies the predicate
+   *           `p` and the iterator that does not.
+   *           The relative order of the elements in the resulting iterators
+   *           is the same as in the original iterator.
+   */
+  def partition(p: A => Boolean): (Iterator[A], Iterator[A]) = {
+    val self = buffered
+    class PartitionIterator(p: A => Boolean) extends Iterator[A] {
+      var other: PartitionIterator = _
+      val lookahead = new scala.collection.mutable.Queue[A]
+      def skip() = 
+        while (self.hasNext && !p(self.head)) {
+          other.lookahead += self.next
+        }
+      def hasNext = !lookahead.isEmpty || { skip(); self.hasNext }
+      def next() = if (!lookahead.isEmpty) lookahead.dequeue() 
+                   else { skip(); self.next() }
+    }
+    val l = new PartitionIterator(p)
+    val r = new PartitionIterator(!p(_))
+    l.other = r
+    r.other = l
+    (l, r)
+  }
+
+  /** Skips longest sequence of elements of this iterator which satisfy given 
+   *  predicate `p`, and returns an iterator of the remaining elements.
+   *
+   *  @param p the predicate used to skip elements.
+   *  @return  an iterator consisting of the remaining elements
+   */
+  def dropWhile(p: A => Boolean): Iterator[A] = {
+    val self = buffered
+    new Iterator[A] {
+      var dropped = false
+      private def skip() =
+        if (!dropped) {
+          while (self.hasNext && p(self.head)) self.next()
+          dropped = true
+        }
+      def hasNext = { skip(); self.hasNext }
+      def next() = { skip(); self.next() }
+    }
+  }
+
+  /** Creates an iterator formed from this iterator and another iterator
+   *  by combining corresponding values in pairs.
+   *  If one of the two iterators is longer than the other, its remaining
+   *  elements are ignored.
+   *  @param   that  The iterator providing the second half of each result pair
+   *  @return        a new iterator containing pairs consisting of
+   *                 corresponding elements of this iterator and `that`. The number
+   *                 of elements returned by the new iterator is the
+   *                 minimum of the number of elements returned by this
+   *                 iterator and `that`.
+   */	
+  def zip[B](that: Iterator[B]) = new Iterator[(A, B)] {
+    def hasNext = self.hasNext && that.hasNext
+    def next = (self.next, that.next)
+  }
+
+  /** Appends an element value to this iterator until a given target length is reached.
+   *  @param   len   the target length
+   *  @param   elem  the padding value 
+   *  @return a new iterator consisting of producing all values of this iterator,
+   *          followed by the minimal number of occurrences of `elem` so 
+   *          that the number of produced values is at least `len`. 
+   *  @usecase def padTo(len: Int, elem: A): Iterator[A]
+   */
+  def padTo[A1 >: A](len: Int, elem: A1) = new Iterator[A1] {
+    private var count = 0
+    def hasNext = self.hasNext || count < len 
+    def next = {
+      count += 1
+      if (self.hasNext) self.next
+      else if (count <= len) elem
+      else empty.next
+    }
+  }
+
+  /** Creates an iterator that pairs each element produced by this iterator
+   *  with its index, counting from 0.
+   */
+  def zipWithIndex = new Iterator[(A, Int)] {
+    var idx = 0
+    def hasNext = self.hasNext
+    def next = {
+      val ret = (self.next, idx)
+      idx += 1
+      ret
+    }
+  }
+
+  /** Creates an iterator formed from this iterator and another iterator
+   *  by combining corresponding elements in pairs.
+   *  If one of the two iterators is shorter than the other,
+   *  placeholder elements are used to extend the shorter iterator to the length of the longer.
+   *
+   *  @param that     iterator `that` may have a different length
+   *                  as the self iterator.
+   *  @param thisElem element `thisElem` is used to fill up the
+   *                  resulting iterator if the self iterator is shorter than
+   *                  `that`
+   *  @param thatElem element `thatElem` is used to fill up the
+   *                  resulting iterator if `that` is shorter than
+   *                  the self iterator
+   *  @return         a new iterator containing pairs consisting of
+   *                  corresponding values of this iterator and `that`. The length
+   *                  of the returned iterator is the maximum of the lengths of this iterator and `that`.
+   *                  If this iterator is shorter than `that`, `thisElem` values are used to pad the result.
+   *                  If `that` is shorter than this iterator, `thatElem` values are used to pad the result.
+   *  @usecase def zipAll[B](that: Iterator[B], thisElem: A, thatElem: B): Iterator[(A, B)]
+   */
+  def zipAll[B, A1 >: A, B1 >: B](that: Iterator[B], thisElem: A1, thatElem: B1) = new Iterator[(A1, B1)] {  
+    def hasNext = self.hasNext || that.hasNext
+    def next(): (A1, B1) = 
+      if (self.hasNext) {
+        if (that.hasNext) (self.next(), that.next())
+        else (self.next(), thatElem)
+      } else {
+        if (that.hasNext) (thisElem, that.next())
+        else empty.next()
+      }
+  }
+
+  /** Applies a function `f` to all values produced by this iterator.
+   *  
+   *  @param  f   the function that is applied for its side-effect to every element.
+   *              The result of function `f` is discarded.
+   *              
+   *  @tparam  U  the type parameter describing the result of function `f`. 
+   *              This result will always be ignored. Typically `U` is `Unit`,
+   *              but this is not necessary.
+   *
+   *  @usecase def foreach(f: A => Unit): Unit
+   */
+  def foreach[U](f: A =>  U) { while (hasNext) f(next()) }
+
+  /** Tests whether a predicate holds for all values produced by this iterator.
+   *  $mayNotTerminateInf
+   *
+   *  @param   p     the predicate used to test elements.
+   *  @return        `true` if the given predicate `p` holds for all values
+   *                 produced by this iterator, otherwise `false`.
+   */
+  def forall(p: A => Boolean): Boolean = {
+    var res = true
+    while (res && hasNext) res = p(next())
+    res
+  }
+
+  /** Tests whether a predicate holds for some of the values produced by this iterator.
+   *  $mayNotTerminateInf
+   *
+   *  @param   p     the predicate used to test elements.
+   *  @return        `true` if the given predicate `p` holds for some of the values
+   *                 produced by this iterator, otherwise `false`.
+   */
+  def exists(p: A => Boolean): Boolean = {
+    var res = false
+    while (!res && hasNext) res = p(next())
+    res
+  }
+
+  /** Tests whether this iterator contains a given value as an element.
+   *  $mayNotTerminateInf
+   *
+   *  @param elem  the element to test.
+   *  @return     `true` if this iterator produces some value that is
+   *               is equal (wrt `==`) to `elem`, `false` otherwise.
+   */
+  def contains(elem: Any): Boolean = exists(_ == elem)
+
+  /** Finds the first value produced by the iterator satisfying a
+   *  predicate, if any.
+   *  $mayNotTerminateInf
+   *
+   *  @param p the predicate used to test values.
+   *  @return  an option value containing the first value produced by the iterator that satisfies
+   *           predicate `p`, or `None` if none exists.
+   */
+  def find(p: A => Boolean): Option[A] = {
+    var res: Option[A] = None
+    while (res.isEmpty && hasNext) {
+      val e = next()
+      if (p(e)) res = Some(e)
+    }
+    res
+  }
+  
+  /** Applies option-valued function to successive elements of this iterator
+   *  until a defined value is found.
+   *
+   *  @param f    the function to be applied to successive elements.
+   *  @return     an option value containing the first defined result of
+   *              `f`, or `None` if `f` returns `None` for all all elements.
+  def mapFind[B](f: A => Option[B]): Option[B] = {
+    var res: Option[B] = None
+    while (res.isEmpty && hasNext) {
+      res = f(next())
+    }
+    res
+  }
+   */
+
+  /** Returns the index of the first produced value satisfying a predicate, or -1.
+   *  $mayNotTerminateInf
+   *  @param  p the predicate to test values
+   *  @return   the index of the first produced value satisfying `p`,
+   *           or -1 if such an element does not exist until the end of the iterator is reached.
+   */
+  def indexWhere(p: A => Boolean): Int = {
+    var i = 0
+    var found = false
+    while (!found && hasNext) {
+      if (p(next())) {
+        found = true
+      } else {
+        i += 1
+      }
+    }
+    if (found) i else -1
+  }
+  
+  /** Returns the index of the first occurrence of the specified
+   *  object in this iterable object.
+   *  $mayNotTerminateInf
+   *
+   *  @param  elem  element to search for.
+   *  @return the index of the first occurrence of `elem` in the values produced by this iterator,
+   *          or -1 if such an element does not exist until the end of the iterator is reached.
+   */
+  def indexOf[B >: A](elem: B): Int = {
+    var i = 0
+    var found = false
+    while (!found && hasNext) {
+      if (next() == elem) {
+        found = true
+      } else {
+        i += 1
+      }
+    }
+    if (found) i else -1
+  }
+  
+  /** Creates a buffered iterator from this iterator.
+   *  @see BufferedIterator
+   *  @return  a buffered iterator producing the same values as this iterator.
+   */
+  def buffered = new BufferedIterator[A] {
+    private var hd: A = _
+    private var hdDefined: Boolean = false
+
+    def head: A = {
+      if (!hdDefined) { 
+        hd = next()
+        hdDefined = true
+      }
+      hd
+    }
+
+    def hasNext = 
+      hdDefined || self.hasNext
+
+    def next = 
+      if (hdDefined) {
+        hdDefined = false
+        hd
+      } else self.next
+  }
+  
+  /** A flexible iterator for transforming an `Iterator[A]` into an
+   *  Iterator[Seq[A]], with configurable sequence size, step, and
+   *  strategy for dealing with elements which don't fit evenly.
+   * 
+   *  Typical uses can be achieved via methods `grouped' and `sliding'.
+   */
+  class GroupedIterator[B >: A](self: Iterator[A], size: Int, step: Int) extends Iterator[Seq[B]] {
+    require(size >= 1 && step >= 1)
+
+    private[this] var buffer: ArrayBuffer[B] = ArrayBuffer()  // the buffer    
+    private[this] var filled = false                          // whether the buffer is "hot"
+    private[this] var _partial = true                         // whether we deliver short sequences
+    private[this] var pad: Option[() => B] = None             // what to pad short sequences with
+    
+    /** Public functions which can be used to configure the iterator before use. */
+    def withPadding(x: => B): this.type = {
+      pad = Some(() => x)
+      this
+    }
+    def withPartial(x: Boolean): this.type = {
+      _partial = x
+      if (_partial == true) // reset pad since otherwise it will take precedence
+        pad = None
+
+      this
+    }
+
+    /** For reasons which remain to be determined, calling
+     *  self.take(n).toSeq cause an infinite loop, so we have
+     *  a slight variation on take for local usage.
+     */
+    private def takeDestructively(size: Int): Seq[A] = {
+      val buf = new ArrayBuffer[A]
+      var i = 0
+      while (self.hasNext && i < size) {
+        buf += self.next
+        i += 1
+      }
+      buf
+    }
+    
+    private def padding(x: Int) = List.fill(x)(pad.get())
+    private def gap = (step - size) max 0
+    
+    private def go(count: Int) = {
+      val prevSize = buffer.size
+      def isFirst = prevSize == 0
+      // If there is padding defined we insert it immediately
+      // so the rest of the code can be oblivious
+      val xs: Seq[B] = {
+        val res = takeDestructively(count)
+        // extra checks so we don't calculate length unless there's reason
+        if (pad.isDefined && !self.hasNext) {
+          val shortBy = count - res.length
+          if (shortBy > 0) res ++ padding(shortBy) else res
+        }
+        else res
+      }
+      lazy val len = xs.length
+      lazy val incomplete = len < count
+      
+      // if 0 elements are requested, or if the number of newly obtained
+      // elements is less than the gap between sequences, we are done.
+      def deliver(howMany: Int) = {
+        (howMany > 0 && (isFirst || len > gap)) && {
+          if (!isFirst)
+            buffer trimStart (step min prevSize)
+          
+          val available =
+            if (isFirst) len
+            else howMany min (len - gap)
+          
+          buffer ++= (xs takeRight available)
+          filled = true
+          true
+        }
+      }
+      
+      if (xs.isEmpty) false                         // self ran out of elements
+      else if (_partial) deliver(len min size)      // if _partial is true, we deliver regardless
+      else if (incomplete) false                    // !_partial && incomplete means no more seqs
+      else if (isFirst) deliver(len)                // first element
+      else deliver(step min size)                   // the typical case
+    }
+    
+    // fill() returns false if no more sequences can be produced
+    private def fill(): Boolean = {
+      if (!self.hasNext) false
+      // the first time we grab size, but after that we grab step
+      else if (buffer.isEmpty) go(size)
+      else go(step)
+    }
+      
+    def hasNext = filled || fill()
+    def next = {
+      if (!filled)
+        fill()
+      
+      if (!filled)
+        throw new NoSuchElementException("next on empty iterator")
+      filled = false
+      buffer.toList
+    }      
+  }
+
+  /** Returns an iterator which groups this iterator into fixed size 
+   *  blocks.  Example usages:
+   *
+   *  <pre>
+   *    // Returns List(List(1, 2, 3), List(4, 5, 6), List(7)))
+   *    (1 to 7).iterator grouped 3 toList
+   *    // Returns List(List(1, 2, 3), List(4, 5, 6))
+   *    (1 to 7).iterator grouped 3 withPartial false toList
+   *    // Returns List(List(1, 2, 3), List(4, 5, 6), List(7, 20, 25)
+   *    // Illustrating that withPadding's argument is by-name.
+   *    val it2 = Iterator.iterate(20)(_ + 5)
+   *    (1 to 7).iterator grouped 3 withPadding it2.next toList
+   *  </pre>
+   */
+  def grouped[B >: A](size: Int): GroupedIterator[B] =
+    new GroupedIterator[B](self, size, size)
+
+  /** Returns an iterator which presents a "sliding window" view of
+   *  another iterator.  The first argument is the window size, and
+   *  the second is how far to advance the window on each iteration;
+   *  defaults to 1.  Example usages:
+   * 
+   *  <pre>
+   *    // Returns List(List(1, 2, 3), List(2, 3, 4), List(3, 4, 5))
+   *    (1 to 5).iterator.sliding(3).toList
+   *    // Returns List(List(1, 2, 3, 4), List(4, 5))
+   *    (1 to 5).iterator.sliding(4, 3).toList
+   *    // Returns List(List(1, 2, 3, 4))
+   *    (1 to 5).iterator.sliding(4, 3).withPartial(false).toList
+   *    // Returns List(List(1, 2, 3, 4), List(4, 5, 20, 25))
+   *    // Illustrating that withPadding's argument is by-name.
+   *    val it2 = Iterator.iterate(20)(_ + 5)
+   *    (1 to 5).iterator.sliding(4, 3).withPadding(it2.next).toList
+   *  </pre>
+   */
+  def sliding[B >: A](size: Int, step: Int = 1): GroupedIterator[B] =
+    new GroupedIterator[B](self, size, step)
+
+  /** Returns the number of elements in this iterator.
+   *  $willNotTerminateInf
+   * 
+   *  Note: The iterator is at its end after this method returns.
+   */
+  def length: Int = this.size
+
+  /** Creates two new iterators that both iterate over the same elements
+   *  as this iterator (in the same order).  The duplicate iterators are
+   *  considered equal if they are positioned at the same element.
+   *
+   *  @return a pair of iterators
+   */
+  def duplicate: (Iterator[A], Iterator[A]) = {
+    val gap = new scala.collection.mutable.Queue[A]
+    var ahead: Iterator[A] = null
+    class Partner extends Iterator[A] {
+      def hasNext: Boolean = self.synchronized {
+        (this ne ahead) && !gap.isEmpty || self.hasNext
+      }	
+      def next(): A = self.synchronized {
+        if (gap.isEmpty) ahead = this
+        if (this eq ahead) {
+          val e = self.next()
+          gap enqueue e
+          e
+        } else gap.dequeue
+      }
+      // to verify partnerhood we use reference equality on gap because
+      // type testing does not discriminate based on origin.
+      private def compareGap(queue: scala.collection.mutable.Queue[A]) = gap eq queue
+      override def hashCode = gap.hashCode
+      override def equals(other: Any) = other match {
+        case x: Partner   => x.compareGap(gap) && gap.isEmpty
+        case _            => super.equals(other)
+      }
+    }
+    (new Partner, new Partner)
+  }
+
+  /** Returns this iterator with patched values.
+   *  @param from     The start index from which to patch
+   *  @param ps       The iterator of patch values
+   *  @param replaced The number of values in the original iterator that are replaced by the patch.
+   */
+  def patch[B >: A](from: Int, patchElems: Iterator[B], replaced: Int) = new Iterator[B] {
+    private var origElems = self
+    private var i = 0
+    def hasNext: Boolean = 
+      if (i < from) origElems.hasNext 
+      else patchElems.hasNext || origElems.hasNext
+    def next(): B = {
+      val result: B = 
+        if (i < from || !patchElems.hasNext) origElems.next()
+        else patchElems.next()
+      i += 1
+      if (i == from) origElems = origElems drop replaced
+      result
+    }
+  }
+  
+  /** Copies selected values produced by this iterator to an array.
+   *  Fills the given array `xs` with at most `len` values produced by this 
+   *  iterator, after skipping `start` values.
+   *  Copying will stop once either the end of the current iterator is reached,
+   *  or the end of the array is reached, or `len` elements have been copied.
+   *
+   *  $willNotTerminateInf
+   * 
+   *  @param  xs     the array to fill.
+   *  @param  start  the starting index.
+   *  @param  len    the maximal number of elements to copy.
+   *  @tparam B      the type of the elements of the array. 
+   * 
+   *
+   *  @usecase def copyToArray(xs: Array[A], start: Int, len: Int): Unit
+   */
+  def copyToArray[B >: A](xs: Array[B], start: Int, len: Int): Unit = {
+    var i = start
+    val end = start + len min xs.length
+    while (hasNext && i < end) {
+      xs(i) = next()
+      i += 1
+    }
+  }
+  
+  /** Tests if another iterator produces the same values as this one.
+   *  $willNotTerminateInf
+   *  @param that  the other iterator
+   *  @return `true`, if both iterators produce the same elements in the same order, `false` otherwise.
+   */
+  def sameElements(that: Iterator[_]): Boolean = {    
+    while (hasNext && that.hasNext)
+      if (next != that.next)
+        return false
+    
+    !hasNext && !that.hasNext
+  }
+
+  def toTraversable: Traversable[A] = toStream  
+  def toIterator: Iterator[A] = self
+  def toStream: Stream[A] =
+    if (self.hasNext) Stream.cons(self.next, self.toStream)
+    else Stream.empty[A]
+
+  /** Converts this iterator to a string.  
+   *  @return `"empty iterator"` or `"non-empty iterator"`, depending on whether or not the iterator is empty.
+   */
+  override def toString = (if (hasNext) "non-empty" else "empty")+" iterator"
+
+  /** Returns a new iterator that first yields the elements of this
+   *  iterator followed by the elements provided by iterator `that`.
+   */
+  @deprecated("use `++`")
+  def append[B >: A](that: Iterator[B]) = self ++ that
+
+  /** Returns index of the first element satisfying a predicate, or -1. */
+  @deprecated("use `indexWhere` instead")
+  def findIndexOf(p: A => Boolean): Int = indexWhere(p)
+
+  /** Returns a counted iterator from this iterator.
+   */
+  @deprecated("use zipWithIndex in Iterator")
+  def counted = new CountedIterator[A] {
+    private var cnt = 0
+    def count = cnt
+    def hasNext: Boolean = self.hasNext
+    def next(): A = { cnt += 1; self.next }
+  }
+  
+  /** Fills the given array `xs` with the elements of
+   *  this sequence starting at position `start`.  Like `copyToArray`, 
+   *  but designed to accomodate IO stream operations. 
+   *
+   *  '''Note:'''   the array must be large enough to hold `sz` elements.
+   *  @param  xs    the array to fill.
+   *  @param  start the starting index.
+   *  @param  sz    the maximum number of elements to be read.
+   */
+  @deprecated("use copyToArray instead")
+  def readInto[B >: A](xs: Array[B], start: Int, sz: Int) {
+    var i = start
+    while (hasNext && i - start < sz) {
+      xs(i) = next
+      i += 1
+    }
+  }
+
+  @deprecated("use copyToArray instead")
+  def readInto[B >: A](xs: Array[B], start: Int) {
+    readInto(xs, start, xs.length - start)
+  }
+
+  @deprecated("use copyToArray instead")
+  def readInto[B >: A](xs: Array[B]) {
+    readInto(xs, 0, xs.length)
+  }
+}
diff --git a/src/library/scala/collection/JavaConversions.scala b/src/library/scala/collection/JavaConversions.scala
new file mode 100644
index 0000000..1e930c9
--- /dev/null
+++ b/src/library/scala/collection/JavaConversions.scala
@@ -0,0 +1,927 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2006-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://www.scala-lang.org/           **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+
+/** <p>
+ *    A collection of implicit conversions supporting interoperability between
+ *    Scala and Java collections.
+ *  </p>
+ *  <p>
+ *    The following conversions are supported:
+ *  </p>
+ *  <ul>
+ *    <li><code>scala.collection.Iterable</code> <=> <code>java.lang.Iterable</code></li>
+ *    <li><code>scala.collection.Iterable</code> <=> <code>java.util.Collection</code></li>
+ *    <li><code>scala.collection.Iterator</code> <=> <code>java.util.{ Iterator, Enumeration }</code></li>
+ *    <li><code>scala.collection.mutable.Buffer</code> <=> <code>java.util.List</code></li>
+ *    <li><code>scala.collection.mutable.Set</code> <=> <code>java.util.Set</code></li>
+ *    <li><code>scala.collection.mutable.Map</code> <=> <code>java.util.{ Map, Dictionary }</code></li>
+ *    <li><code>scala.collection.mutable.ConcurrentMap</code> <=> <code>java.util.concurrent.ConcurrentMap</code></li>
+ *  </ul>
+ *  <p>
+ *    In all cases, converting from a source type to a target type and back
+ *    again will return the original source object, eg.
+ *  </p>
+ *  <pre>
+ *    <b>import</b> scala.collection.JavaConversions._
+ * 
+ *    <b>val</b> sl = <b>new</b> scala.collection.mutable.ListBuffer[Int]
+ *    <b>val</b> jl : java.util.List[Int] = sl
+ *    <b>val</b> sl2 : scala.collection.mutable.Buffer[Int] = jl
+ *    assert(sl eq sl2)g</pre>
+ *  <p>
+ *  In addition, the following one way conversions are provided:
+ *  </p>
+ *  <ul>
+ *    <li><code>scala.collection.Seq => <code>java.util.List }</code></li>
+ *    <li><code>scala.collection.mutable.Seq => <code>java.util.List</code></li>
+ *    <li><code>scala.collection.Set</code> => <code>java.util.Set</code></li>
+ *    <li><code>scala.collection.Map</code> => <code>java.util.Map</code></li>
+ *  </ul>
+ * 
+ *  @author Miles Sabin
+ *  @author Martin Odersky
+ *  @since  2.8
+ */
+object JavaConversions {
+  import java.{ lang => jl, util => ju }
+  import java.util.{ concurrent => juc }
+
+  // Scala => Java
+
+  /**
+   * Implicitly converts a Scala <code>Iterator</code> to a Java <code>Iterator</code>.
+   * The returned Java <code>Iterator</code> is backed by the provided Scala
+   * <code>Iterator</code> and any side-effects of using it via the Java interface will
+   * be visible via the Scala interface and vice versa.
+   * <p>
+   * If the Scala <code>Iterator</code> was previously obtained from an implicit or
+   * explicit call of <code>asIterator(java.util.Iterator)</code> then the original
+   * Java <code>Iterator</code> will be returned.
+   * 
+   * @param i The <code>Iterator</code> to be converted.
+   * @return A Java <code>Iterator</code> view of the argument.
+   */
+  implicit def asJavaIterator[A](i : Iterator[A]): ju.Iterator[A] = i match {
+    case JIteratorWrapper(wrapped) => wrapped
+    case _ => IteratorWrapper(i)
+  }
+
+  @deprecated("use asJavaIterator instead") 
+  def asIterator[A](i : Iterator[A]): ju.Iterator[A] = asJavaIterator[A](i)
+
+  /**
+   * Implicitly converts a Scala <code>Iterator</code> to a Java <code>Enumeration</code>.
+   * The returned Java <code>Enumeration</code> is backed by the provided Scala
+   * <code>Iterator</code> and any side-effects of using it via the Java interface will
+   * be visible via the Scala interface and vice versa.
+   * <p>
+   * If the Scala <code>Iterator</code> was previously obtained from an implicit or
+   * explicit call of <code>asIterator(java.util.Enumeration)</code> then the
+   * original Java <code>Enumeration</code> will be returned.
+   * 
+   * @param i The <code>Iterator</code> to be converted.
+   * @return A Java <code>Enumeration</code> view of the argument.
+   */
+  implicit def asJavaEnumeration[A](i : Iterator[A]): ju.Enumeration[A] = i match {
+    case JEnumerationWrapper(wrapped) => wrapped
+    case _ => IteratorWrapper(i)
+  }
+
+  @deprecated("use asJavaEnmeration instead") 
+  def asEnumeration[A](i : Iterator[A]): ju.Enumeration[A] = asJavaEnumeration[A](i)
+
+  /**
+   * Implicitly converts a Scala <code>Iterable</code> to a Java <code>Iterable</code>.
+   * The returned Java <code>Iterable</code> is backed by the provided Scala
+   * <code>Iterable</code> and any side-effects of using it via the Java interface will
+   * be visible via the Scala interface and vice versa.
+   * <p>
+   * If the Scala <code>Iterable</code> was previously obtained from an implicit or
+   * explicit call of <code>asIterable(java.lang.Iterable)</code> then the original
+   * Java <code>Iterable</code> will be returned.
+   * 
+   * @param i The <code>Iterable</code> to be converted.
+   * @return A Java <code>Iterable</code> view of the argument.
+   */
+  implicit def asJavaIterable[A](i : Iterable[A]): jl.Iterable[A] = i match {
+    case JIterableWrapper(wrapped) => wrapped
+    case _ => IterableWrapper(i)
+  }
+
+  @deprecated("use asJavaIterable instead") 
+  def asIterable[A](i : Iterable[A]): jl.Iterable[A] = asJavaIterable[A](i)
+
+  /**
+   * Implicitly converts a Scala <code>Iterable</code> to an immutable Java
+   * <code>Collection</code>.
+   * <p>
+   * If the Scala <code>Iterable</code> was previously obtained from an implicit or
+   * explicit call of <code>asSizedIterable(java.util.Collection)</code> then the original
+   * Java <code>Collection</code> will be returned.
+   * 
+   * @param i The <code>SizedIterable</code> to be converted.
+   * @return A Java <code>Collection</code> view of the argument.
+   */
+  implicit def asJavaCollection[A](i : Iterable[A]): ju.Collection[A] = i match {
+    case JCollectionWrapper(wrapped) => wrapped
+    case _ => new IterableWrapper(i)
+  }
+  
+  @deprecated("use asJavaCollection instead") 
+  def asCollection[A](i : Iterable[A]): ju.Collection[A] = asJavaCollection[A](i)
+
+  /**
+   * Implicitly converts a Scala mutable <code>Buffer</code> to a Java <code>List</code>.
+   * The returned Java <code>List</code> is backed by the provided Scala
+   * <code>Buffer</code> and any side-effects of using it via the Java interface will
+   * be visible via the Scala interface and vice versa.
+   * <p>
+   * If the Scala <code>Buffer</code> was previously obtained from an implicit or
+   * explicit call of <code>asBuffer(java.util.List)</code> then the original
+   * Java <code>List</code> will be returned.
+   * 
+   * @param b The <code>Buffer</code> to be converted.
+   * @return A Java <code>List</code> view of the argument.
+   */
+  implicit def asJavaList[A](b : mutable.Buffer[A]): ju.List[A] = b match {
+    case JListWrapper(wrapped) => wrapped
+    case _ => new MutableBufferWrapper(b)
+  }
+
+  @deprecated("use asJavaList instead") 
+  def asList[A](b : mutable.Buffer[A]): ju.List[A] = asJavaList[A](b)
+
+  /**
+   * Implicitly converts a Scala mutable <code>Seq</code> to a Java <code>List</code>.
+   * The returned Java <code>List</code> is backed by the provided Scala
+   * <code>Seq</code> and any side-effects of using it via the Java interface will
+   * be visible via the Scala interface and vice versa.
+   * <p>
+   * If the Scala <code>Seq</code> was previously obtained from an implicit or
+   * explicit call of <code>asSeq(java.util.List)</code> then the original
+   * Java <code>List</code> will be returned.
+   * 
+   * @param b The <code>Seq</code> to be converted.
+   * @return A Java <code>List</code> view of the argument.
+   */
+  implicit def asJavaList[A](b : mutable.Seq[A]): ju.List[A] = b match {
+    case JListWrapper(wrapped) => wrapped
+    case _ => new MutableSeqWrapper(b)
+  }
+
+  @deprecated("use asJavaList instead") 
+  def asList[A](b : mutable.Seq[A]): ju.List[A] = asJavaList[A](b)
+
+  /**
+   * Implicitly converts a Scala <code>Seq</code> to a Java <code>List</code>.
+   * The returned Java <code>List</code> is backed by the provided Scala
+   * <code>Seq</code> and any side-effects of using it via the Java interface will
+   * be visible via the Scala interface and vice versa.
+   * <p>
+   * If the Scala <code>Seq</code> was previously obtained from an implicit or
+   * explicit call of <code>asSeq(java.util.List)</code> then the original
+   * Java <code>List</code> will be returned.
+   * 
+   * @param b The <code>Seq</code> to be converted.
+   * @return A Java <code>List</code> view of the argument.
+   */
+  implicit def asJavaList[A](b : Seq[A]): ju.List[A] = b match {
+    case JListWrapper(wrapped) => wrapped
+    case _ => new SeqWrapper(b)
+  }
+
+  @deprecated("use asJavaList instead") 
+  def asList[A](b : Seq[A]): ju.List[A] = asJavaList[A](b)
+
+  /**
+   * Implicitly converts a Scala mutable <code>Set</code> to a Java <code>Set</code>.
+   * The returned Java <code>Set</code> is backed by the provided Scala
+   * <code>Set</code> and any side-effects of using it via the Java interface will
+   * be visible via the Scala interface and vice versa.
+   * <p>
+   * If the Scala <code>Set</code> was previously obtained from an implicit or
+   * explicit call of <code>asSet(java.util.Set)</code> then the original
+   * Java <code>Set</code> will be returned.
+   * 
+   * @param s The <code>Set</code> to be converted.
+   * @return A Java <code>Set</code> view of the argument.
+   */
+  implicit def asJavaSet[A](s : mutable.Set[A]): ju.Set[A] = s match {
+    case JSetWrapper(wrapped) => wrapped
+    case _ => new MutableSetWrapper(s)
+  }
+
+  @deprecated("use asJavaSet instead") 
+  def asSet[A](s : mutable.Set[A]): ju.Set[A] = asJavaSet[A](s)
+
+  /**
+   * Implicitly converts a Scala <code>Set</code> to a Java <code>Set</code>.
+   * The returned Java <code>Set</code> is backed by the provided Scala
+   * <code>Set</code> and any side-effects of using it via the Java interface will
+   * be visible via the Scala interface and vice versa.
+   * <p>
+   * If the Scala <code>Set</code> was previously obtained from an implicit or
+   * explicit call of <code>asSet(java.util.Set)</code> then the original
+   * Java <code>Set</code> will be returned.
+   * 
+   * @param s The <code>Set</code> to be converted.
+   * @return A Java <code>Set</code> view of the argument.
+   */
+  implicit def asJavaSet[A](s: Set[A]): ju.Set[A] = s match {
+    case JSetWrapper(wrapped) => wrapped
+    case _ => new SetWrapper(s)
+  }
+
+  @deprecated("use asJavaSet instead") 
+  def asSet[A](s : Set[A]): ju.Set[A] = asJavaSet[A](s)
+
+  /**
+   * Implicitly converts a Scala mutable <code>Map</code> to a Java <code>Map</code>.
+   * The returned Java <code>Map</code> is backed by the provided Scala
+   * <code>Map</code> and any side-effects of using it via the Java interface will
+   * be visible via the Scala interface and vice versa.
+   * <p>
+   * If the Scala <code>Map</code> was previously obtained from an implicit or
+   * explicit call of <code>asMap(java.util.Map)</code> then the original
+   * Java <code>Map</code> will be returned.
+   * 
+   * @param m The <code>Map</code> to be converted.
+   * @return A Java <code>Map</code> view of the argument.
+   */
+  implicit def asJavaMap[A, B](m : mutable.Map[A, B]): ju.Map[A, B] = m match {
+    //case JConcurrentMapWrapper(wrapped) => wrapped
+    case JMapWrapper(wrapped) => wrapped
+    case _ => new MutableMapWrapper(m)
+  }
+
+  @deprecated("use asJavaMap instead") 
+  def asMap[A, B](m : mutable.Map[A, B]): ju.Map[A, B] = asJavaMap[A, B](m)
+
+  /**
+   * Implicitly converts a Scala mutable <code>Map</code> to a Java <code>Dictionary</code>.
+   * The returned Java <code>Dictionary</code> is backed by the provided Scala
+   * <code>Dictionary</code> and any side-effects of using it via the Java interface will
+   * be visible via the Scala interface and vice versa.
+   * <p>
+   * If the Scala <code>Dictionary</code> was previously obtained from an implicit or
+   * explicit call of <code>asMap(java.util.Dictionary)</code> then the original
+   * Java <code>Dictionary</code> will be returned.
+   * 
+   * @param m The <code>Map</code> to be converted.
+   * @return A Java <code>Dictionary</code> view of the argument.
+   */
+  implicit def asJavaDictionary[A, B](m : mutable.Map[A, B]): ju.Dictionary[A, B] = m match {
+    //case JConcurrentMapWrapper(wrapped) => wrapped
+    case JDictionaryWrapper(wrapped) => wrapped
+    case _ => new DictionaryWrapper(m)
+  }
+
+  @deprecated("use asJavaDictionary instead") 
+  def asDictionary[A, B](m : mutable.Map[A, B]): ju.Dictionary[A, B] = asJavaDictionary[A, B](m)
+
+  /**
+   * Implicitly converts a Scala <code>Map</code> to a Java <code>Map</code>.
+   * The returned Java <code>Map</code> is backed by the provided Scala
+   * <code>Map</code> and any side-effects of using it via the Java interface will
+   * be visible via the Scala interface and vice versa.
+   * <p>
+   * If the Scala <code>Map</code> was previously obtained from an implicit or
+   * explicit call of <code>asMap(java.util.Map)</code> then the original
+   * Java <code>Map</code> will be returned.
+   * 
+   * @param m The <code>Map</code> to be converted.
+   * @return A Java <code>Map</code> view of the argument.
+   */
+  implicit def asJavaMap[A, B](m : Map[A, B]): ju.Map[A, B] = m match {
+    //case JConcurrentMapWrapper(wrapped) => wrapped
+    case JMapWrapper(wrapped) => wrapped
+    case _ => new MapWrapper(m)
+  }
+  
+  @deprecated("use asJavaMap instead") 
+  def asMap[A, B](m : Map[A, B]): ju.Map[A, B] = asJavaMap[A, B](m)
+
+  /**
+   * Implicitly converts a Scala mutable `ConcurrentMap` to a Java `ConcurrentMap`.
+   * The returned Java `ConcurrentMap` is backed by the provided Scala `ConcurrentMap`
+   * and any side-effects of using it via the Java interface will be visible
+   * via the Scala interface and vice versa.
+   * <p>
+   * If the Scala <code>ConcurrentMap</code> was previously obtained from an implicit or
+   * explicit call of <code>asConcurrentMap(java.util.concurrect.ConcurrentMap)</code> then the original
+   * Java <code>ConcurrentMap</code> will be returned.
+   * 
+   * @param m The <code>ConcurrentMap</code> to be converted.
+   * @return A Java <code>ConcurrentMap</code> view of the argument.
+   */
+  implicit def asJavaConcurrentMap[A, B](m: mutable.ConcurrentMap[A, B]): juc.ConcurrentMap[A, B] = m match {
+    case JConcurrentMapWrapper(wrapped) => wrapped
+    case _ => new ConcurrentMapWrapper(m)
+  }
+
+  @deprecated("use asJavaConcurrentMap instead") 
+  def asConcurrentMap[A, B](m: mutable.ConcurrentMap[A, B]): juc.ConcurrentMap[A, B] = asJavaConcurrentMap[A, B](m)
+
+  // Java => Scala
+  
+  /**
+   * Implicitly converts a Java <code>Iterator</code> to a Scala <code>Iterator</code>.
+   * The returned Scala <code>Iterator</code> is backed by the provided Java
+   * <code>Iterator</code> and any side-effects of using it via the Scala interface will
+   * be visible via the Java interface and vice versa.
+   * <p>
+   * If the Java <code>Iterator</code> was previously obtained from an implicit or
+   * explicit call of <code>asIterator(scala.collection.Iterator)</code> then the original
+   * Scala <code>Iterator</code> will be returned.
+   * 
+   * @param i The <code>Iterator</code> to be converted.
+   * @return A Scala <code>Iterator</code> view of the argument.
+   */
+  implicit def asScalaIterator[A](i : ju.Iterator[A]): Iterator[A] = i match {
+    case IteratorWrapper(wrapped) => wrapped
+    case _ => JIteratorWrapper(i)
+  }
+
+  @deprecated("use asScalaIterator instead") 
+  def asIterator[A](i : ju.Iterator[A]): Iterator[A] = asScalaIterator[A](i)
+  
+  /**
+   * Implicitly converts a Java <code>Enumeration</code> to a Scala <code>Iterator</code>.
+   * The returned Scala <code>Iterator</code> is backed by the provided Java
+   * <code>Enumeration</code> and any side-effects of using it via the Scala interface will
+   * be visible via the Java interface and vice versa.
+   * <p>
+   * If the Java <code>Enumeration</code> was previously obtained from an implicit or
+   * explicit call of <code>asEnumeration(scala.collection.Iterator)</code> then the
+   * original Scala <code>Iterator</code> will be returned.
+   * 
+   * @param i The <code>Enumeration</code> to be converted.
+   * @return A Scala <code>Iterator</code> view of the argument.
+   */
+  implicit def enumerationAsScalaIterator[A](i : ju.Enumeration[A]): Iterator[A] = i match {
+    case IteratorWrapper(wrapped) => wrapped
+    case _ => JEnumerationWrapper(i)
+  }
+  
+  @deprecated("use enumerationAsScalaIterator instead") 
+  def asIterator[A](i : ju.Enumeration[A]): Iterator[A] = enumerationAsScalaIterator[A](i)
+
+  /**
+   * Implicitly converts a Java <code>Iterable</code> to a Scala <code>Iterable</code>.
+   * The returned Scala <code>Iterable</code> is backed by the provided Java
+   * <code>Iterable</code> and any side-effects of using it via the Scala interface will
+   * be visible via the Java interface and vice versa.
+   * <p>
+   * If the Java <code>Iterable</code> was previously obtained from an implicit or
+   * explicit call of <code>asIterable(scala.collection.Iterable)</code> then the original
+   * Scala <code>Iterable</code> will be returned.
+   * 
+   * @param i The <code>Iterable</code> to be converted.
+   * @return A Scala <code>Iterable</code> view of the argument.
+   */
+  implicit def asScalaIterable[A](i : jl.Iterable[A]): Iterable[A] = i match {
+    case IterableWrapper(wrapped) => wrapped
+    case _ => JIterableWrapper(i)
+  }
+  
+  @deprecated("use asScalaIterable instead") 
+  def asIterable[A](i : jl.Iterable[A]): Iterable[A] = asScalaIterable[A](i)
+
+  /**
+   * Implicitly converts a Java <code>Collection</code> to an Scala <code>Iterable</code>.
+   * <p>
+   * If the Java <code>Collection</code> was previously obtained from an implicit or
+   * explicit call of <code>asCollection(scala.collection.SizedIterable)</code> then
+   * the original Scala <code>SizedIterable</code> will be returned.
+   * 
+   * @param i The <code>Collection</code> to be converted.
+   * @return A Scala <code>SizedIterable</code> view of the argument.
+   */
+  implicit def asScalaIterable[A](i : ju.Collection[A]): Iterable[A] = i match {
+    case IterableWrapper(wrapped) => wrapped
+    case _ => JCollectionWrapper(i)
+  }
+  
+  @deprecated("use asScalaIterable instead") 
+  def asIterable[A](i : ju.Collection[A]): Iterable[A] = asScalaIterable[A](i)
+
+  /**
+   * Implicitly converts a Java <code>List</code> to a Scala mutable <code>Buffer</code>.
+   * The returned Scala <code>Buffer</code> is backed by the provided Java
+   * <code>List</code> and any side-effects of using it via the Scala interface will
+   * be visible via the Java interface and vice versa.
+   * <p>
+   * If the Java <code>List</code> was previously obtained from an implicit or
+   * explicit call of <code>asList(scala.collection.mutable.Buffer)</code> then the original
+   * Scala <code>Buffer</code> will be returned.
+   * 
+   * @param l The <code>List</code> to be converted.
+   * @return A Scala mutable <code>Buffer</code> view of the argument.
+   */
+  implicit def asScalaBuffer[A](l : ju.List[A]): mutable.Buffer[A] = l match {
+    case MutableBufferWrapper(wrapped) => wrapped
+    case _ =>new JListWrapper(l)
+  }
+
+  @deprecated("use asScalaBuffer instead") 
+  def asBuffer[A](l : ju.List[A]): mutable.Buffer[A] = asScalaBuffer[A](l)
+
+  /**
+   * Implicitly converts a Java <code>Set</code> to a Scala mutable <code>Set</code>.
+   * The returned Scala <code>Set</code> is backed by the provided Java
+   * <code>Set</code> and any side-effects of using it via the Scala interface will
+   * be visible via the Java interface and vice versa.
+   * <p>
+   * If the Java <code>Set</code> was previously obtained from an implicit or
+   * explicit call of <code>asSet(scala.collection.mutable.Set)</code> then the original
+   * ScalaThe reported problems have to do with dependent method types, which is currently an experimental feature in Scala and is still under development. We emphasize that these problems are related to type-inference and, as stated in the paper, it is possible to run and type-check the programs with additional annotations. <code>Set</code> will be returned.
+   * 
+   * @param s The <code>Set</code> to be converted.
+   * @return A Scala mutable <code>Set</code> view of the argument.
+   */
+  implicit def asScalaSet[A](s : ju.Set[A]): mutable.Set[A] = s match {
+    case MutableSetWrapper(wrapped) => wrapped
+    case _ =>new JSetWrapper(s)
+  }
+  
+  @deprecated("use asScalaSet instead") 
+  def asSet[A](s : ju.Set[A]): mutable.Set[A] = asScalaSet[A](s)
+
+  /**
+   * Implicitly converts a Java <code>Map</code> to a Scala mutable <code>Map</code>.
+   * The returned Scala <code>Map</code> is backed by the provided Java
+   * <code>Map</code> and any side-effects of using it via the Scala interface will
+   * be visible via the Java interface and vice versa.
+   * <p>
+   * If the Java <code>Map</code> was previously obtained from an implicit or
+   * explicit call of <code>asMap(scala.collection.mutable.Map)</code> then the original
+   * Scala <code>Map</code> will be returned.
+   * 
+   * @param m The <code>Map</code> to be converted.
+   * @return A Scala mutable <code>Map</code> view of the argument.
+   */
+  implicit def asScalaMap[A, B](m : ju.Map[A, B]): mutable.Map[A, B] = m match {
+    //case ConcurrentMapWrapper(wrapped) => wrapped
+    case MutableMapWrapper(wrapped) => wrapped
+    case _ => new JMapWrapper(m)
+  }
+  
+  @deprecated("use asScalaMap instead") 
+  def asMap[A, B](m : ju.Map[A, B]): mutable.Map[A, B] = asScalaMap[A, B](m)
+
+  /**
+   * Implicitly converts a Java <code>ConcurrentMap</code> to a Scala mutable <code>ConcurrentMap</code>.
+   * The returned Scala <code>ConcurrentMap</code> is backed by the provided Java
+   * <code>ConcurrentMap</code> and any side-effects of using it via the Scala interface will
+   * be visible via the Java interface and vice versa.
+   * <p>
+   * If the Java <code>ConcurrentMap</code> was previously obtained from an implicit or
+   * explicit call of <code>asConcurrentMap(scala.collection.mutable.ConcurrentMap)</code> then the original
+   * Scala <code>ConcurrentMap</code> will be returned.
+   * 
+   * @param m The <code>ConcurrentMap</code> to be converted.
+   * @return A Scala mutable <code>ConcurrrentMap</code> view of the argument.
+   */
+  implicit def asScalaConcurrentMap[A, B](m: juc.ConcurrentMap[A, B]): mutable.ConcurrentMap[A, B] = m match {
+    case cmw: ConcurrentMapWrapper[a, b] => cmw.underlying
+    case _ => new JConcurrentMapWrapper(m)
+  }
+  
+  @deprecated("use asScalaConcurrentMap instead") 
+  def asConcurrentMap[A, B](m: juc.ConcurrentMap[A, B]): mutable.ConcurrentMap[A, B] = asScalaConcurrentMap[A, B](m)
+
+  /**
+   * Implicitly converts a Java <code>Dictionary</code> to a Scala mutable <code>Map[String, String]</code>.
+   * The returned Scala <code>Map[String, String]</code> is backed by the provided Java
+   * <code>Dictionary</code> and any side-effects of using it via the Scala interface will
+   * be visible via the Java interface and vice versa.
+   * 
+   * @param m The <code>Dictionary</code> to be converted.
+   * @return A Scala mutable <code>Map[String, String]</code> view of the argument.
+   */
+  implicit def dictionaryAsScalaMap[A, B](p: ju.Dictionary[A, B]): mutable.Map[A, B] = p match {
+    case DictionaryWrapper(wrapped) => wrapped
+    case _ => new JDictionaryWrapper(p)
+  }
+
+  @deprecated("use dictionaryAsScalaMap instead") 
+  def asMap[A, B](p: ju.Dictionary[A, B]): mutable.Map[A, B] = dictionaryAsScalaMap[A, B](p)
+
+  /**
+   * Implicitly converts a Java <code>Properties</code> to a Scala mutable <code>Map[String, String]</code>.
+   * The returned Scala <code>Map[String, String]</code> is backed by the provided Java
+   * <code>Properties</code> and any side-effects of using it via the Scala interface will
+   * be visible via the Java interface and vice versa.
+   * 
+   * @param m The <code>Properties</code> to be converted.
+   * @return A Scala mutable <code>Map[String, String]</code> view of the argument.
+   */
+  implicit def asScalaMap(p: ju.Properties): mutable.Map[String, String] = p match {
+    case _ => new JPropertiesWrapper(p)
+  }
+
+  @deprecated("use asScalaMap instead") 
+  def asMap(p: ju.Properties): mutable.Map[String, String] = asScalaMap(p)
+
+  // Private implementations (shared by JavaConverters) ...
+
+  case class IteratorWrapper[A](underlying : Iterator[A]) extends ju.Iterator[A] with ju.Enumeration[A] {
+    def hasNext = underlying.hasNext
+    def next = underlying.next
+    def hasMoreElements = underlying.hasNext
+    def nextElement = underlying.next
+    def remove = throw new UnsupportedOperationException
+  }
+
+  class ToIteratorWrapper[A](underlying : Iterator[A]) {
+    def asJava = new IteratorWrapper(underlying)
+  }
+
+  case class JIteratorWrapper[A](underlying : ju.Iterator[A]) extends Iterator[A] {
+    def hasNext = underlying.hasNext
+    def next = underlying.next
+  }
+
+  case class JEnumerationWrapper[A](underlying : ju.Enumeration[A]) extends Iterator[A] {
+    def hasNext = underlying.hasMoreElements
+    def next = underlying.nextElement
+  }
+
+  case class IterableWrapper[A](underlying : Iterable[A]) extends ju.AbstractCollection[A] {
+    def iterator = underlying.iterator
+    def size = underlying.size
+    override def isEmpty = underlying.isEmpty
+  }
+
+  case class JIterableWrapper[A](underlying : jl.Iterable[A]) extends Iterable[A] {
+    def iterator = underlying.iterator
+    def newBuilder[B] = new mutable.ArrayBuffer[B]
+  }
+
+  case class JCollectionWrapper[A](underlying : ju.Collection[A]) extends Iterable[A] {
+    def iterator = underlying.iterator
+    override def size = underlying.size
+    override def isEmpty = underlying.isEmpty
+    def newBuilder[B] = new mutable.ArrayBuffer[B]
+  }
+  
+  case class SeqWrapper[A](underlying : Seq[A]) extends ju.AbstractList[A] {
+    def size = underlying.length
+    def get(i : Int) = underlying(i)
+  }
+  
+  case class MutableSeqWrapper[A](underlying : mutable.Seq[A]) extends ju.AbstractList[A] {
+    def size = underlying.length
+    def get(i : Int) = underlying(i)
+    override def set(i : Int, elem: A) = { val p = underlying(i) ; underlying(i) = elem ; p }
+  }
+  
+  case class MutableBufferWrapper[A](underlying : mutable.Buffer[A]) extends ju.AbstractList[A] {
+    def size = underlying.length
+    def get(i : Int) = underlying(i)
+    override def set(i : Int, elem: A) = { val p = underlying(i) ; underlying(i) = elem ; p }
+    override def add(elem : A) = { underlying.append(elem) ; true }
+    override def remove(i : Int) = underlying.remove(i)
+  }
+  
+  case class JListWrapper[A](val underlying : ju.List[A]) extends mutable.Buffer[A] {
+    def length = underlying.size
+    override def isEmpty = underlying.isEmpty
+    override def iterator : Iterator[A] = underlying.iterator
+    def apply(i : Int) = underlying.get(i)
+    def update(i : Int, elem : A) = underlying.set(i, elem)
+    def +=:(elem : A) = { underlying.subList(0, 0).add(elem) ; this } 
+    def +=(elem : A): this.type = { underlying.add(elem); this }
+    def insertAll(i : Int, elems : Traversable[A]) = { val ins = underlying.subList(0, i) ;  elems.foreach(ins.add(_)) }
+    def remove(i : Int) = underlying.remove(i)
+    def clear = underlying.clear
+    def result = this
+  }
+  
+  class SetWrapper[A](underlying: Set[A]) extends ju.AbstractSet[A] {
+    self =>
+    def size = underlying.size
+    def iterator = new ju.Iterator[A] {
+      val ui = underlying.iterator
+      var prev : Option[A] = None
+      def hasNext = ui.hasNext
+      def next = { val e = ui.next ; prev = Some(e) ; e }
+      def remove = prev match {
+        case Some(e) => 
+          underlying match {
+            case ms: mutable.Set[a] => 
+              ms.remove(e.asInstanceOf[a])
+              prev = None
+            case _ =>
+              throw new UnsupportedOperationException("remove")
+          }
+        case _ => throw new IllegalStateException("next must be called at least once before remove")
+      }
+    }
+  }
+
+  case class MutableSetWrapper[A](underlying : mutable.Set[A]) extends SetWrapper[A](underlying) {
+    override def add(elem: A) = { val sz = underlying.size ; underlying += elem ; sz < underlying.size }
+    override def remove(elem : AnyRef) = try {
+      underlying.remove(elem.asInstanceOf[A])
+    } catch {
+      case ex: ClassCastException => false
+    }
+    override def clear() = underlying.clear()
+  }
+  
+  case class JSetWrapper[A](underlying : ju.Set[A]) extends mutable.Set[A] with mutable.SetLike[A, JSetWrapper[A]] {
+    override def size = underlying.size
+
+    def iterator = underlying.iterator
+  
+    def contains(elem: A): Boolean = underlying.contains(elem)
+  
+    def +=(elem: A): this.type = { underlying.add(elem); this }
+    def -=(elem: A): this.type = { underlying.remove(elem); this }
+
+    override def add(elem: A): Boolean = underlying.add(elem)
+    override def remove(elem: A): Boolean = underlying.remove(elem)
+    override def clear() = underlying.clear()
+
+    override def empty = JSetWrapper(new ju.HashSet[A])
+  }
+
+  class MapWrapper[A, B](underlying: Map[A, B]) extends ju.AbstractMap[A, B] { self =>
+    override def size = underlying.size
+
+    override def get(key: AnyRef): B = try {
+      underlying get key.asInstanceOf[A] match {
+        case None => null.asInstanceOf[B]
+        case Some(v) => v
+      }
+    } catch {
+      case ex: ClassCastException => null.asInstanceOf[B]
+    }
+
+    override def entrySet: ju.Set[ju.Map.Entry[A, B]] = new ju.AbstractSet[ju.Map.Entry[A, B]] {
+      def size = self.size
+
+      def iterator = new ju.Iterator[ju.Map.Entry[A, B]] {
+        val ui = underlying.iterator
+        var prev : Option[A] = None
+        
+        def hasNext = ui.hasNext
+      
+        def next = {
+          val (k, v) = ui.next
+          prev = Some(k)
+          new ju.Map.Entry[A, B] {
+            def getKey = k
+            def getValue = v
+            def setValue(v1 : B) = self.put(k, v1)
+            override def equals(other : Any) = other match {
+              case e : ju.Map.Entry[_, _] => k == e.getKey && v == e.getValue
+              case _ => false
+            }
+          }
+        }
+        
+        def remove = prev match {
+          case Some(k) => 
+            underlying match {
+              case mm: mutable.Map[a, _] =>
+                val v = mm.remove(k.asInstanceOf[a])
+                prev = None
+                v
+              case _ =>
+                throw new UnsupportedOperationException("remove")
+            }
+          case _ => 
+            throw new IllegalStateException("next must be called at least once before remove")
+        }
+      }
+    }
+  }
+
+  case class MutableMapWrapper[A, B](underlying: mutable.Map[A, B])
+  extends MapWrapper[A, B](underlying) {
+    override def put(k : A, v : B) = underlying.put(k, v) match {
+      case Some(v1) => v1
+      case None => null.asInstanceOf[B]
+    }
+    
+    override def remove(k : AnyRef): B = try {
+      underlying.remove(k.asInstanceOf[A]) match {
+        case None => null.asInstanceOf[B]
+        case Some(v) => v
+      }
+    } catch {
+      case ex: ClassCastException => null.asInstanceOf[B]
+    }
+
+    override def clear() = underlying.clear()
+  }
+  
+  trait JMapWrapperLike[A, B, +Repr <: mutable.MapLike[A, B, Repr] with mutable.Map[A, B]]
+  extends mutable.Map[A, B] with mutable.MapLike[A, B, Repr] {
+    def underlying: ju.Map[A, B]
+    
+    override def size = underlying.size
+    
+    def get(k : A) = {
+      val v = underlying.get(k)
+      if (v != null)
+        Some(v)
+      else if(underlying.containsKey(k))
+        Some(null.asInstanceOf[B])
+      else
+        None
+    }
+
+    def +=(kv: (A, B)): this.type = { underlying.put(kv._1, kv._2); this }
+    def -=(key: A): this.type = { underlying.remove(key); this }
+
+    override def put(k : A, v : B): Option[B] = {
+      val r = underlying.put(k, v)
+      if (r != null) Some(r) else None
+    }
+    
+    override def update(k : A, v : B) { underlying.put(k, v) }
+    
+    override def remove(k : A): Option[B] = { 
+      val r = underlying.remove(k)
+      if (r != null) Some(r) else None
+    }
+
+    def iterator = new Iterator[(A, B)] {
+      val ui = underlying.entrySet.iterator
+      def hasNext = ui.hasNext
+      def next = { val e = ui.next ; (e.getKey, e.getValue) }
+    }
+    
+    override def clear() = underlying.clear()
+    
+    override def empty: Repr = null.asInstanceOf[Repr]
+  }
+  
+  case class JMapWrapper[A, B](val underlying : ju.Map[A, B])
+  extends JMapWrapperLike[A, B, JMapWrapper[A, B]] {
+    override def empty = JMapWrapper(new ju.HashMap[A, B])
+  }
+  
+  class ConcurrentMapWrapper[A, B](override val underlying: mutable.ConcurrentMap[A, B])
+  extends MutableMapWrapper[A, B](underlying) with juc.ConcurrentMap[A, B] {
+    
+    def putIfAbsent(k: A, v: B) = underlying.putIfAbsent(k, v) match {
+      case Some(v) => v
+      case None => null.asInstanceOf[B]
+    }
+    
+    def remove(k: AnyRef, v: AnyRef) = try {
+      underlying.remove(k.asInstanceOf[A], v.asInstanceOf[B])
+    } catch {
+      case ex: ClassCastException =>
+        false
+    }
+    
+    def replace(k: A, v: B): B = underlying.replace(k, v) match {
+      case Some(v) => v
+      case None => null.asInstanceOf[B]
+    }
+    
+    def replace(k: A, oldval: B, newval: B) = underlying.replace(k, oldval, newval)
+  }
+  
+  case class JConcurrentMapWrapper[A, B](val underlying: juc.ConcurrentMap[A, B])
+  extends JMapWrapperLike[A, B, JConcurrentMapWrapper[A, B]] with mutable.ConcurrentMap[A, B] {
+    override def get(k: A) = {
+      val v = underlying.get(k)
+      if (v != null) Some(v)
+      else None
+    }
+    
+    override def empty = new JConcurrentMapWrapper(new juc.ConcurrentHashMap[A, B])
+    
+    def putIfAbsent(k: A, v: B): Option[B] = {
+      val r = underlying.putIfAbsent(k, v)
+      if (r != null) Some(r) else None
+    }
+    
+    def remove(k: A, v: B): Boolean = underlying.remove(k, v)
+    
+    def replace(k: A, v: B): Option[B] = {
+      val prev = underlying.replace(k, v)
+      if (prev != null) Some(prev) else None
+    }
+    
+    def replace(k: A, oldvalue: B, newvalue: B): Boolean = underlying.replace(k, oldvalue, newvalue)
+  }
+  
+  case class DictionaryWrapper[A, B](underlying: mutable.Map[A, B])
+  extends ju.Dictionary[A, B] {
+    def size: Int = underlying.size
+    def isEmpty: Boolean = underlying.isEmpty
+    def keys: ju.Enumeration[A] = asJavaEnumeration(underlying.keysIterator)
+    def elements: ju.Enumeration[B] = asJavaEnumeration(underlying.valuesIterator)
+    def get(key: AnyRef) = try {
+      underlying.get(key.asInstanceOf[A]) match {
+        case None => null.asInstanceOf[B]
+        case Some(v) => v
+      }
+    } catch {
+      case ex: ClassCastException => null.asInstanceOf[B]
+    }
+    def put(key: A, value: B): B = underlying.put(key, value) match {
+      case Some(v) => v
+      case None => null.asInstanceOf[B]
+    }
+    override def remove(key: AnyRef) = try {
+      underlying.remove(key.asInstanceOf[A]) match {
+        case None => null.asInstanceOf[B]
+        case Some(v) => v
+      }
+    } catch {
+      case ex: ClassCastException => null.asInstanceOf[B]
+    }
+  }
+
+  case class JDictionaryWrapper[A, B](underlying: ju.Dictionary[A, B])
+  extends mutable.Map[A, B] {
+
+    override def size: Int = underlying.size
+
+    def get(k : A) = {
+      val v = underlying.get(k)
+      if (v != null) Some(v) else None
+    }
+
+    def +=(kv: (A, B)): this.type = { underlying.put(kv._1, kv._2); this }
+    def -=(key: A): this.type = { underlying.remove(key); this }
+
+    override def put(k : A, v : B): Option[B] = {
+      val r = underlying.put(k, v)
+      if (r != null) Some(r) else None
+    }
+    
+    override def update(k : A, v : B) { underlying.put(k, v) }
+    
+    override def remove(k : A): Option[B] = { 
+      val r = underlying.remove(k)
+      if (r != null) Some(r) else None
+    }
+
+    def iterator = enumerationAsScalaIterator(underlying.keys) map (k => (k, underlying get k))
+    
+    override def clear() = underlying.clear()
+  }
+
+  case class JPropertiesWrapper(underlying: ju.Properties)
+  extends mutable.Map[String, String] with mutable.MapLike[String, String, JPropertiesWrapper] {
+    override def size = underlying.size
+    
+    def get(k : String) = {
+      val v = underlying.get(k)
+      if (v != null)
+        Some(v.asInstanceOf[String])
+      else
+        None
+    }
+
+    def +=(kv: (String, String)): this.type = { underlying.put(kv._1, kv._2); this }
+    def -=(key: String): this.type = { underlying.remove(key); this }
+
+    override def put(k : String, v : String): Option[String] = {
+      val r = underlying.put(k, v)
+      if (r != null) Some(r.asInstanceOf[String]) else None
+    }
+    
+    override def update(k : String, v : String) { underlying.put(k, v) }
+    
+    override def remove(k : String): Option[String] = { 
+      val r = underlying.remove(k)
+      if (r != null) Some(r.asInstanceOf[String]) else None
+    }
+
+    def iterator = new Iterator[(String, String)] {
+      val ui = underlying.entrySet.iterator
+      def hasNext = ui.hasNext
+      def next = { val e = ui.next ; (e.getKey.asInstanceOf[String], e.getValue.asInstanceOf[String]) }
+    }
+    
+    override def clear() = underlying.clear()
+    
+    override def empty = JPropertiesWrapper(new ju.Properties)
+    
+    def getProperty(key: String) = underlying.getProperty(key)
+    
+    def getProperty(key: String, defaultValue: String) = underlying.getProperty(key, defaultValue)
+    
+    def setProperty(key: String, value: String) = underlying.setProperty(key, value)
+  }
+}
+
diff --git a/src/library/scala/collection/JavaConverters.scala b/src/library/scala/collection/JavaConverters.scala
new file mode 100644
index 0000000..6875502
--- /dev/null
+++ b/src/library/scala/collection/JavaConverters.scala
@@ -0,0 +1,456 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2006-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://www.scala-lang.org/           **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+
+/** <p>
+ *    A collection of decorators that allow to convert between
+ *    Scala and Java collections using `asScala` and `asJava` methods.
+ *  </p>
+ *  <p>
+ *    The following conversions are supported via `asJava`, `asScala`
+ *  </p>
+ *  <ul>
+ *    <li><code>scala.collection.Iterable</code> <=> <code>java.lang.Iterable</code></li>
+ *    <li><code>scala.collection.Iterator</code> <=> <code>java.util.Iterator</code></li>
+ *    <li><code>scala.collection.mutable.Buffer</code> <=> <code>java.util.List</code></li>
+ *    <li><code>scala.collection.mutable.Set</code> <=> <code>java.util.Set</code></li>
+ *    <li><code>scala.collection.mutable.Map</code> <=> <code>java.util.Map</code></li>
+ *    <li><code>scala.collection.mutable.ConcurrentMap</code> <=> <code>java.util.concurrent.ConcurrentMap</code></li>
+ *  </ul>
+ *  <p>
+ *    In all cases, converting from a source type to a target type and back
+ *    again will return the original source object, e.g.
+ *  </p>
+ *  <pre>
+ *    <b>import</b> scala.collection.JavaConverters._
+ * 
+ *    <b>val</b> sl = <b>new</b> scala.collection.mutable.ListBuffer[Int]
+ *    <b>val</b> jl : java.util.List[Int] = sl.asJava
+ *    <b>val</b> sl2 : scala.collection.mutable.Buffer[Int] = jl.asScala
+ *    assert(sl eq sl2)g</pre>
+ *  <p>
+ *  <p>
+ *    The following conversions also are supported, but the
+ *    direction Scala to Java is done my a more specifically named method:
+ *    `asJavaCollection`, `asJavaEnumeration`, `asJavaDictionary`.
+ *  </p>
+ *  <ul>
+ *    <li><code>scala.collection.Iterable</code> <=> <code>java.util.Collection</code></li>
+ *    <li><code>scala.collection.Iterator</code> <=> <code>java.util.Enumeration</code></li>
+ *    <li><code>scala.collection.mutable.Map</code> <=> <code>java.util.Dictionary</code></li>
+ *  </ul>
+ *  In addition, the following one way conversions are provided via `asJava`:
+ *  </p>
+ *  <ul>
+ *    <li><code>scala.collection.Seq => <code>java.util.List }</code></li>
+ *    <li><code>scala.collection.mutable.Seq => <code>java.util.List</code></li>
+ *    <li><code>scala.collection.Set</code> => <code>java.util.Set</code></li>
+ *    <li><code>scala.collection.Map</code> => <code>java.util.Map</code></li>
+ *  </ul>
+ * 
+ *  @author Martin Odersky
+ *  @since  2.8.1
+ */
+object JavaConverters {
+  import java.{ lang => jl, util => ju }
+  import java.util.{ concurrent => juc }
+  import JavaConversions._
+
+  // Conversion decorator classes
+  
+  /** Generic class containing the `asJava` converter method */
+  class AsJava[C](op: => C) {
+    /** Converts a Scala collection to the corresponding Java collection */
+    def asJava: C = op
+  }
+
+  /** Generic class containing the `asScala` converter method */
+  class AsScala[C](op: => C) {
+    /** Converts a Java collection to the corresponding Scala collection */
+    def asScala: C = op
+  }
+
+  /** Generic class containing the `asJavaCollection` converter method */
+  class AsJavaCollection[A](i: Iterable[A]) {
+    /** Converts a Scala `Iterable` to a Java `Collection` */
+    def asJavaCollection: ju.Collection[A] = JavaConversions.asJavaCollection(i)
+  }
+
+  /** Generic class containing the `asJavaEnumeration` converter method */
+  class AsJavaEnumeration[A](i: Iterator[A]) {
+    /** Converts a Scala `Iterator` to a Java `Enumeration` */
+    def asJavaEnumeration: ju.Enumeration[A] = JavaConversions.asJavaEnumeration(i)
+  }
+
+  /** Generic class containing the `asJavaDictionary` converter method */
+  class AsJavaDictionary[A, B](m : mutable.Map[A, B]) {
+    /** Converts a Scala `Map` to a Java `Dictionary` */
+    def asJavaDictionary: ju.Dictionary[A, B] = JavaConversions.asJavaDictionary(m)
+  }
+    
+  // Scala => Java
+  
+  /**
+   * Adds an `asJava` method that implicitly converts a Scala <code>Iterator</code> to a Java <code>Iterator</code>.
+   * The returned Java <code>Iterator</code> is backed by the provided Scala
+   * <code>Iterator</code> and any side-effects of using it via the Java interface will
+   * be visible via the Scala interface and vice versa.
+   * <p>
+   * If the Scala <code>Iterator</code> was previously obtained from an implicit or
+   * explicit call of <code>asIterator(java.util.Iterator)</code> then the original
+   * Java <code>Iterator</code> will be returned by the `asJava` method.
+   * 
+   * @param i The <code>Iterator</code> to be converted.
+   * @return An object with an `asJava` method that returns a Java <code>Iterator</code> view of the argument. 
+   */
+  implicit def asJavaIteratorConverter[A](i : Iterator[A]): AsJava[ju.Iterator[A]] = 
+    new AsJava(asJavaIterator(i))
+
+  /**
+   * Adds an `asJavaEnumeration` method that implicitly converts a Scala <code>Iterator</code> to a Java <code>Enumeration</code>.
+   * The returned Java <code>Enumeration</code> is backed by the provided Scala
+   * <code>Iterator</code> and any side-effects of using it via the Java interface will
+   * be visible via the Scala interface and vice versa.
+   * <p>
+   * If the Scala <code>Iterator</code> was previously obtained from an implicit or
+   * explicit call of <code>asIterator(java.util.Enumeration)</code> then the
+   * original Java <code>Enumeration</code> will be returned.
+   * 
+   * @param i The <code>Iterator</code> to be converted.
+   * @return An object with an `asJavaEnumeration` method that returns a Java <code>Enumeration</code> view of the argument.
+   */
+  implicit def asJavaEnumerationConverter[A](i : Iterator[A]): AsJavaEnumeration[A] = 
+    new AsJavaEnumeration(i)
+
+  /**
+   * Adds an `asJava` method that implicitly converts a Scala <code>Iterable</code> to a Java <code>Iterable</code>.
+   * The returned Java <code>Iterable</code> is backed by the provided Scala
+   * <code>Iterable</code> and any side-effects of using it via the Java interface will
+   * be visible via the Scala interface and vice versa.
+   * <p>
+   * If the Scala <code>Iterable</code> was previously obtained from an implicit or
+   * explicit call of <code>asIterable(java.lang.Iterable)</code> then the original
+   * Java <code>Iterable</code> will be returned.
+   * 
+   * @param i The <code>Iterable</code> to be converted.
+   * @return An object with an `asJavaCollection` method that returns a Java <code>Iterable</code> view of the argument.
+   */
+  implicit def asJavaIterableConverter[A](i : Iterable[A]): AsJava[jl.Iterable[A]] = 
+    new AsJava(asJavaIterable(i))
+
+  /**
+   * Adds an `asJavaCollection` method that implicitly converts a Scala <code>Iterable</code> to an immutable Java
+   * <code>Collection</code>.
+   * <p>
+   * If the Scala <code>Iterable</code> was previously obtained from an implicit or
+   * explicit call of <code>asSizedIterable(java.util.Collection)</code> then the original
+   * Java <code>Collection</code> will be returned.
+   * 
+   * @param i The <code>SizedIterable</code> to be converted.
+   * @return An object with an `asJava` method that returns a Java <code>Collection</code> view of the argument.
+   */
+  implicit def asJavaCollectionConverter[A](i : Iterable[A]): AsJavaCollection[A] = 
+    new AsJavaCollection(i)
+
+  /**
+   * Adds an `asJava` method that implicitly converts a Scala mutable <code>Buffer</code> to a Java <code>List</code>.
+   * The returned Java <code>List</code> is backed by the provided Scala
+   * <code>Buffer</code> and any side-effects of using it via the Java interface will
+   * be visible via the Scala interface and vice versa.
+   * <p>
+   * If the Scala <code>Buffer</code> was previously obtained from an implicit or
+   * explicit call of <code>asBuffer(java.util.List)</code> then the original
+   * Java <code>List</code> will be returned.
+   * 
+   * @param b The <code>Buffer</code> to be converted.
+   * @return An object with an `asJava` method that returns a Java <code>List</code> view of the argument.
+   */
+  implicit def asJavaListConverter[A](b : mutable.Buffer[A]): AsJava[ju.List[A]] = 
+    new AsJava(asJavaList(b))
+    
+  /**
+   * Adds an `asJava` method that implicitly converts a Scala mutable <code>Seq</code> to a Java <code>List</code>.
+   * The returned Java <code>List</code> is backed by the provided Scala
+   * <code>Seq</code> and any side-effects of using it via the Java interface will
+   * be visible via the Scala interface and vice versa.
+   * <p>
+   * If the Scala <code>Seq</code> was previously obtained from an implicit or
+   * explicit call of <code>asSeq(java.util.List)</code> then the original
+   * Java <code>List</code> will be returned.
+   * 
+   * @param b The <code>Seq</code> to be converted.
+   * @return An object with an `asJava` method that returns a Java <code>List</code> view of the argument.
+   */
+  implicit def asJavaListConverter[A](b : mutable.Seq[A]): AsJava[ju.List[A]] = 
+    new AsJava(asJavaList(b))
+    
+  /**
+   * Adds an `asJava` method that implicitly converts a Scala <code>Seq</code> to a Java <code>List</code>.
+   * The returned Java <code>List</code> is backed by the provided Scala
+   * <code>Seq</code> and any side-effects of using it via the Java interface will
+   * be visible via the Scala interface and vice versa.
+   * <p>
+   * If the Scala <code>Seq</code> was previously obtained from an implicit or
+   * explicit call of <code>asSeq(java.util.List)</code> then the original
+   * Java <code>List</code> will be returned.
+   * 
+   * @param b The <code>Seq</code> to be converted.
+   * @return An object with an `asJava` method that returns a Java <code>List</code> view of the argument.
+   */
+  implicit def asJavaListConverter[A](b : Seq[A]): AsJava[ju.List[A]] = 
+    new AsJava(asJavaList(b))
+    
+  /**
+   * Adds an `asJava` method that implicitly converts a Scala mutable <code>Set</code> to a Java <code>Set</code>.
+   * The returned Java <code>Set</code> is backed by the provided Scala
+   * <code>Set</code> and any side-effects of using it via the Java interface will
+   * be visible via the Scala interface and vice versa.
+   * <p>
+   * If the Scala <code>Set</code> was previously obtained from an implicit or
+   * explicit call of <code>asSet(java.util.Set)</code> then the original
+   * Java <code>Set</code> will be returned.
+   * 
+   * @param s The <code>Set</code> to be converted.
+   * @return An object with an `asJava` method that returns a Java <code>Set</code> view of the argument.
+   */
+  implicit def asJavaSetConverter[A](s : mutable.Set[A]): AsJava[ju.Set[A]] = 
+    new AsJava(asJavaSet(s))
+
+  /**
+   * Adds an `asJava` method that implicitly converts a Scala <code>Set</code> to a Java <code>Set</code>.
+   * The returned Java <code>Set</code> is backed by the provided Scala
+   * <code>Set</code> and any side-effects of using it via the Java interface will
+   * be visible via the Scala interface and vice versa.
+   * <p>
+   * If the Scala <code>Set</code> was previously obtained from an implicit or
+   * explicit call of <code>asSet(java.util.Set)</code> then the original
+   * Java <code>Set</code> will be returned.
+   * 
+   * @param s The <code>Set</code> to be converted.
+   * @return An object with an `asJava` method that returns a Java <code>Set</code> view of the argument.
+   */
+  implicit def asJavaSetConverter[A](s : Set[A]): AsJava[ju.Set[A]] = 
+    new AsJava(asJavaSet(s))
+
+  /**
+   * Adds an `asJava` method that implicitly converts a Scala mutable <code>Map</code> to a Java <code>Map</code>.
+   * The returned Java <code>Map</code> is backed by the provided Scala
+   * <code>Map</code> and any side-effects of using it via the Java interface will
+   * be visible via the Scala interface and vice versa.
+   * <p>
+   * If the Scala <code>Map</code> was previously obtained from an implicit or
+   * explicit call of <code>asMap(java.util.Map)</code> then the original
+   * Java <code>Map</code> will be returned.
+   * 
+   * @param m The <code>Map</code> to be converted.
+   * @return An object with an `asJava` method that returns a Java <code>Map</code> view of the argument.
+   */
+  implicit def asJavaMapConverter[A, B](m : mutable.Map[A, B]): AsJava[ju.Map[A, B]] = 
+    new AsJava(asJavaMap(m))
+
+  /**
+   * Adds an `asJavaDictionary` method that implicitly converts a Scala mutable <code>Map</code> to a Java <code>Dictionary</code>.
+   * The returned Java <code>Dictionary</code> is backed by the provided Scala
+   * <code>Dictionary</code> and any side-effects of using it via the Java interface will
+   * be visible via the Scala interface and vice versa.
+   * <p>
+   * If the Scala <code>Dictionary</code> was previously obtained from an implicit or
+   * explicit call of <code>asMap(java.util.Dictionary)</code> then the original
+   * Java <code>Dictionary</code> will be returned.
+   * 
+   * @param m The <code>Map</code> to be converted.
+   * @return An object with an `asJavaDictionary` method that returns a Java <code>Dictionary</code> view of the argument.
+   */
+  implicit def asJavaDictionaryConverter[A, B](m : mutable.Map[A, B]): AsJavaDictionary[A, B] = 
+    new AsJavaDictionary(m)
+
+  /**
+   * Adds an `asJava` method that implicitly converts a Scala <code>Map</code> to a Java <code>Map</code>.
+   * The returned Java <code>Map</code> is backed by the provided Scala
+   * <code>Map</code> and any side-effects of using it via the Java interface will
+   * be visible via the Scala interface and vice versa.
+   * <p>
+   * If the Scala <code>Map</code> was previously obtained from an implicit or
+   * explicit call of <code>asMap(java.util.Map)</code> then the original
+   * Java <code>Map</code> will be returned.
+   * 
+   * @param m The <code>Map</code> to be converted.
+   * @return An object with an `asJava` method that returns a Java <code>Map</code> view of the argument.
+   */
+  implicit def asJavaMapConverter[A, B](m : Map[A, B]): AsJava[ju.Map[A, B]] = 
+    new AsJava(asJavaMap(m))
+
+  /**
+   * Adds an `asJava` method that implicitly converts a Scala mutable `ConcurrentMap` to a Java `ConcurrentMap`.
+   * The returned Java `ConcurrentMap` is backed by the provided Scala `ConcurrentMap`
+   * and any side-effects of using it via the Java interface will be visible
+   * via the Scala interface and vice versa.
+   * <p>
+   * If the Scala <code>ConcurrentMap</code> was previously obtained from an implicit or
+   * explicit call of <code>asConcurrentMap(java.util.concurrect.ConcurrentMap)</code> then the original
+   * Java <code>ConcurrentMap</code> will be returned.
+   * 
+   * @param m The <code>ConcurrentMap</code> to be converted.
+   * @return An object with an `asJava` method that returns a Java <code>ConcurrentMap</code> view of the argument.
+   */
+  implicit def asJavaConcurrentMapConverter[A, B](m: mutable.ConcurrentMap[A, B]): AsJava[juc.ConcurrentMap[A, B]] = 
+    new AsJava(asJavaConcurrentMap(m))
+
+  /**
+   * Adds an `asScala` method that implicitly converts a Java <code>Iterator</code> to a Scala <code>Iterator</code>.
+   * The returned Scala <code>Iterator</code> is backed by the provided Java
+   * <code>Iterator</code> and any side-effects of using it via the Scala interface will
+   * be visible via the Java interface and vice versa.
+   * <p>
+   * If the Java <code>Iterator</code> was previously obtained from an implicit or
+   * explicit call of <code>asIterator(scala.collection.Iterator)</code> then the original
+   * Scala <code>Iterator</code> will be returned.
+   * 
+   * @param i The <code>Iterator</code> to be converted.
+   * @return An object with an `asScala` method that returns a Scala <code>Iterator</code> view of the argument.
+   */
+  implicit def asScalaIteratorConverter[A](i : ju.Iterator[A]): AsScala[Iterator[A]] = 
+    new AsScala(asScalaIterator(i))
+
+  /**
+   * Adds an `asScala` method that implicitly converts a Java <code>Enumeration</code> to a Scala <code>Iterator</code>.
+   * The returned Scala <code>Iterator</code> is backed by the provided Java
+   * <code>Enumeration</code> and any side-effects of using it via the Scala interface will
+   * be visible via the Java interface and vice versa.
+   * <p>
+   * If the Java <code>Enumeration</code> was previously obtained from an implicit or
+   * explicit call of <code>asEnumeration(scala.collection.Iterator)</code> then the
+   * original Scala <code>Iterator</code> will be returned.
+   * 
+   * @param i The <code>Enumeration</code> to be converted.
+   * @return An object with an `asScala` method that returns a Scala <code>Iterator</code> view of the argument.
+   */
+  implicit def enumerationAsScalaIteratorConverter[A](i : ju.Enumeration[A]): AsScala[Iterator[A]] = 
+    new AsScala(enumerationAsScalaIterator(i))
+
+  /**
+   * Adds an `asScala` method that implicitly converts a Java <code>Iterable</code> to a Scala <code>Iterable</code>.
+   * The returned Scala <code>Iterable</code> is backed by the provided Java
+   * <code>Iterable</code> and any side-effects of using it via the Scala interface will
+   * be visible via the Java interface and vice versa.
+   * <p>
+   * If the Java <code>Iterable</code> was previously obtained from an implicit or
+   * explicit call of <code>asIterable(scala.collection.Iterable)</code> then the original
+   * Scala <code>Iterable</code> will be returned.
+   * 
+   * @param i The <code>Iterable</code> to be converted.
+   * @return An object with an `asScala` method that returns a Scala <code>Iterable</code> view of the argument.
+   */
+  implicit def asScalaIterableConverter[A](i : jl.Iterable[A]): AsScala[Iterable[A]] = 
+    new AsScala(asScalaIterable(i))
+
+  /**
+   * Adds an `asScala` method that implicitly converts a Java <code>Collection</code> to an Scala <code>Iterable</code>.
+   * <p>
+   * If the Java <code>Collection</code> was previously obtained from an implicit or
+   * explicit call of <code>asCollection(scala.collection.SizedIterable)</code> then
+   * the original Scala <code>SizedIterable</code> will be returned.
+   * 
+   * @param i The <code>Collection</code> to be converted.
+   * @return An object with an `asScala` method that returns a Scala <code>SizedIterable</code> view of the argument.
+   */
+  implicit def asScalaIterableConverter[A](i : ju.Collection[A]): AsScala[Iterable[A]] = 
+    new AsScala(asScalaIterable(i))
+
+  /**
+   * Adds an `asScala` method that implicitly converts a Java <code>List</code> to a Scala mutable <code>Buffer</code>.
+   * The returned Scala <code>Buffer</code> is backed by the provided Java
+   * <code>List</code> and any side-effects of using it via the Scala interface will
+   * be visible via the Java interface and vice versa.
+   * <p>
+   * If the Java <code>List</code> was previously obtained from an implicit or
+   * explicit call of <code>asList(scala.collection.mutable.Buffer)</code> then the original
+   * Scala <code>Buffer</code> will be returned.
+   * 
+   * @param l The <code>List</code> to be converted.
+   * @return An object with an `asScala` method that returns a Scala mutable <code>Buffer</code> view of the argument.
+   */
+  implicit def asScalaBufferConverter[A](l : ju.List[A]): AsScala[mutable.Buffer[A]] = 
+    new AsScala(asScalaBuffer(l))
+
+  /**
+   * Adds an `asScala` method that implicitly converts a Java <code>Set</code> to a Scala mutable <code>Set</code>.
+   * The returned Scala <code>Set</code> is backed by the provided Java
+   * <code>Set</code> and any side-effects of using it via the Scala interface will
+   * be visible via the Java interface and vice versa.
+   * <p>
+   * If the Java <code>Set</code> was previously obtained from an implicit or
+   * explicit call of <code>asSet(scala.collection.mutable.Set)</code> then the original
+   * ScalaThe reported problems have to do with dependent method types, which is currently an experimental feature in Scala and is still under development. We emphasize that these problems are related to type-inference and, as stated in the paper, it is possible to run and type-check the programs with additional annotations. <code>Set</code> will be returned.
+   * 
+   * @param s The <code>Set</code> to be converted.
+   * @return An object with an `asScala` method that returns a Scala mutable <code>Set</code> view of the argument.
+   */
+  implicit def asScalaSetConverter[A](s : ju.Set[A]): AsScala[mutable.Set[A]] = 
+    new AsScala(asScalaSet(s))
+
+  /**
+   * Adds an `asScala` method that implicitly converts a Java <code>Map</code> to a Scala mutable <code>Map</code>.
+   * The returned Scala <code>Map</code> is backed by the provided Java
+   * <code>Map</code> and any side-effects of using it via the Scala interface will
+   * be visible via the Java interface and vice versa.
+   * <p>
+   * If the Java <code>Map</code> was previously obtained from an implicit or
+   * explicit call of <code>asMap(scala.collection.mutable.Map)</code> then the original
+   * Scala <code>Map</code> will be returned.
+   * 
+   * @param m The <code>Map</code> to be converted.
+   * @return An object with an `asScala` method that returns a Scala mutable <code>Map</code> view of the argument.
+   */
+  implicit def asScalaMapConverter[A, B](m : ju.Map[A, B]): AsScala[mutable.Map[A, B]] = 
+    new AsScala(asScalaMap(m))
+
+  /**
+   * Adds an `asScala` method that implicitly converts a Java <code>ConcurrentMap</code> to a Scala mutable <code>ConcurrentMap</code>.
+   * The returned Scala <code>ConcurrentMap</code> is backed by the provided Java
+   * <code>ConcurrentMap</code> and any side-effects of using it via the Scala interface will
+   * be visible via the Java interface and vice versa.
+   * <p>
+   * If the Java <code>ConcurrentMap</code> was previously obtained from an implicit or
+   * explicit call of <code>asConcurrentMap(scala.collection.mutable.ConcurrentMap)</code> then the original
+   * Scala <code>ConcurrentMap</code> will be returned.
+   * 
+   * @param m The <code>ConcurrentMap</code> to be converted.
+   * @return An object with an `asScala` method that returns a Scala mutable <code>ConcurrrentMap</code> view of the argument.
+   */
+  implicit def asScalaConcurrentMapConverter[A, B](m: juc.ConcurrentMap[A, B]): AsScala[mutable.ConcurrentMap[A, B]] = 
+    new AsScala(asScalaConcurrentMap(m))
+
+  /**
+   * Adds an `asScala` method that implicitly converts a Java <code>Dictionary</code> to a Scala mutable <code>Map[String, String]</code>.
+   * The returned Scala <code>Map[String, String]</code> is backed by the provided Java
+   * <code>Dictionary</code> and any side-effects of using it via the Scala interface will
+   * be visible via the Java interface and vice versa.
+   * 
+   * @param m The <code>Dictionary</code> to be converted.
+   * @return An object with an `asScala` method that returns a Scala mutable <code>Map[String, String]</code> view of the argument.
+   */
+  implicit def dictionaryAsScalaMapConverter[A, B](p: ju.Dictionary[A, B]): AsScala[mutable.Map[A, B]] =
+    new AsScala(dictionaryAsScalaMap(p))
+      
+  /**
+   * Adds an `asScala` method that implicitly converts a Java <code>Properties</code> to a Scala mutable <code>Map[String, String]</code>.
+   * The returned Scala <code>Map[String, String]</code> is backed by the provided Java
+   * <code>Properties</code> and any side-effects of using it via the Scala interface will
+   * be visible via the Java interface and vice versa.
+   * 
+   * @param m The <code>Properties</code> to be converted.
+   * @return An object with an `asScala` method that returns a Scala mutable <code>Map[String, String]</code> view of the argument.
+   */
+  implicit def asScalaMapConverter(p: ju.Properties): AsScala[mutable.Map[String, String]] = 
+    new AsScala(asScalaMap(p))
+    
+}
diff --git a/src/library/scala/collection/LinearSeq.scala b/src/library/scala/collection/LinearSeq.scala
new file mode 100644
index 0000000..4872927
--- /dev/null
+++ b/src/library/scala/collection/LinearSeq.scala
@@ -0,0 +1,33 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+
+import generic._
+import mutable.Builder
+
+/** A base trait for linear sequences.
+ *  $linearSeqInfo
+ */
+trait LinearSeq[+A] extends Seq[A] 
+                            with GenericTraversableTemplate[A, LinearSeq]
+                            with LinearSeqLike[A, LinearSeq[A]] {
+  override def companion: GenericCompanion[LinearSeq] = LinearSeq
+}
+
+/** $factoryInfo
+ *  The current default implementation of a $Coll is a `Vector`.
+ *  @define coll linear sequence
+ *  @define Coll LinearSeq
+ */
+object LinearSeq extends SeqFactory[LinearSeq] {
+  implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, LinearSeq[A]] = new GenericCanBuildFrom[A]
+  def newBuilder[A]: Builder[A, LinearSeq[A]] = immutable.LinearSeq.newBuilder[A]
+}
diff --git a/src/library/scala/collection/LinearSeqLike.scala b/src/library/scala/collection/LinearSeqLike.scala
new file mode 100644
index 0000000..dce1db9
--- /dev/null
+++ b/src/library/scala/collection/LinearSeqLike.scala
@@ -0,0 +1,61 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+import generic._
+
+import mutable.ListBuffer
+import immutable.List
+import scala.util.control.Breaks._
+
+/** A template trait for linear sequences of type `LinearSeq[A]`.
+ *
+ *  $linearSeqInfo
+ * 
+ *  This trait just implements `iterator`
+ *  in terms of `isEmpty, ``head`, and `tail`.
+ *  However, see `LinearSeqOptimized` for an implementation trait that overrides operations
+ *  to make them run faster under the assumption of fast linear access with `head` and `tail`. 
+ *
+ *  @define  linearSeqInfo
+ *  Linear sequences are defined in terms of three abstract methods, which are assumed
+ *  to have efficient implementations. These are:
+ *  {{{
+ *     def isEmpty: Boolean
+ *     def head: A
+ *     def tail: Repr
+ *  }}}
+ *  Here, `A` is the type of the sequence elements and `Repr` is the type of the sequence itself.
+ *
+ *  Linear sequences do not add any new methods to `Seq`, but promise efficient implementations
+ *  of linear access patterns.
+ *  @author  Martin Odersky
+ *  @version 2.8
+ *  @since   2.8
+ *
+ *  @tparam A    the element type of the $coll
+ *  @tparam Repr the type of the actual $coll containing the elements.
+ */
+trait LinearSeqLike[+A, +Repr <: LinearSeqLike[A, Repr]] extends SeqLike[A, Repr] { self: Repr =>
+
+  override protected[this] def thisCollection: LinearSeq[A] = this.asInstanceOf[LinearSeq[A]]
+  override protected[this] def toCollection(repr: Repr): LinearSeq[A] = repr.asInstanceOf[LinearSeq[A]]
+
+  override /*IterableLike*/ 
+  def iterator: Iterator[A] = new Iterator[A] {
+    var these = self
+    def hasNext: Boolean = !these.isEmpty
+    def next: A = 
+      if (hasNext) {
+        val result = these.head; these = these.tail; result
+      } else Iterator.empty.next
+    override def toList: List[A] = these.toList
+  }
+}
diff --git a/src/library/scala/collection/LinearSeqOptimized.scala b/src/library/scala/collection/LinearSeqOptimized.scala
new file mode 100644
index 0000000..0415ce1
--- /dev/null
+++ b/src/library/scala/collection/LinearSeqOptimized.scala
@@ -0,0 +1,294 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+import generic._
+
+import mutable.ListBuffer
+import immutable.List
+import scala.util.control.Breaks._
+
+/** A template trait for linear sequences of type `LinearSeq[A]`  which optimizes
+ *  the implementation of several methods under the assumption of fast linear access.
+ *
+ *  $linearSeqInfo
+ */
+trait LinearSeqOptimized[+A, +Repr <: LinearSeqOptimized[A, Repr]] extends LinearSeqLike[A, Repr] { self: Repr =>
+
+  def isEmpty: Boolean
+
+  def head: A
+
+  def tail: Repr
+
+  /** The length of the $coll.
+   * 
+   *  $willNotTerminateInf
+   *
+   *  Note: the execution of `length` may take time proportial to the length of the sequence.
+   */
+  def length: Int = {
+    var these = self
+    var len = 0
+    while (!these.isEmpty) {
+      len += 1
+      these = these.tail
+    }
+    len
+  }
+
+  /** Selects an element by its index in the $coll.
+   *  Note: the execution of `apply` may take time proportial to the index value.
+   *  @throws `IndexOutOfBoundsException` if `idx` does not satisfy `0 <= idx < length`.
+   */
+  def apply(n: Int): A = {
+    val rest = drop(n)
+    if (n < 0 || rest.isEmpty) throw new IndexOutOfBoundsException
+    rest.head
+  }
+
+  override /*IterableLike*/ 
+  def foreach[B](f: A => B) {
+    var these = this
+    while (!these.isEmpty) {
+      f(these.head)
+      these = these.tail
+    }
+  }
+
+                                                                                   
+  override /*IterableLike*/ 
+  def forall(p: A => Boolean): Boolean = {
+    var these = this
+    while (!these.isEmpty) {
+      if (!p(these.head)) return false
+      these = these.tail
+    }
+    true
+  }
+
+  override /*IterableLike*/ 
+  def exists(p: A => Boolean): Boolean = {
+    var these = this
+    while (!these.isEmpty) {
+      if (p(these.head)) return true
+      these = these.tail
+    }
+    false
+  }
+
+  override /*TraversableLike*/ 
+  def count(p: A => Boolean): Int = {
+    var these = this
+    var cnt = 0
+    while (!these.isEmpty) {
+      if (p(these.head)) cnt += 1
+      these = these.tail
+    }
+    cnt
+  }
+
+  override /*IterableLike*/ 
+  def find(p: A => Boolean): Option[A] = {
+    var these = this
+    while (!these.isEmpty) {
+      if (p(these.head)) return Some(these.head)
+      these = these.tail
+    }
+    None
+  }
+/*
+  override def mapFind[B](f: A => Option[B]): Option[B] = {
+    var res: Option[B] = None
+    var these = this
+    while (res.isEmpty && !these.isEmpty) {
+      res = f(these.head)
+      these = these.tail
+    }
+    res
+  }
+*/
+  override /*TraversableLike*/ 
+  def foldLeft[B](z: B)(f: (B, A) => B): B = {
+    var acc = z
+    var these = this
+    while (!these.isEmpty) {
+      acc = f(acc, these.head)
+      these = these.tail
+    }
+    acc
+  }
+
+  override /*IterableLike*/ 
+  def foldRight[B](z: B)(f: (A, B) => B): B = 
+    if (this.isEmpty) z
+    else f(head, tail.foldRight(z)(f))
+
+  override /*TraversableLike*/ 
+  def reduceLeft[B >: A](f: (B, A) => B): B = 
+    if (isEmpty) throw new UnsupportedOperationException("empty.reduceLeft")
+    else tail.foldLeft[B](head)(f)
+
+  override /*IterableLike*/ 
+  def reduceRight[B >: A](op: (A, B) => B): B = 
+    if (isEmpty) throw new UnsupportedOperationException("Nil.reduceRight")
+    else if (tail.isEmpty) head
+    else op(head, tail.reduceRight(op))
+  
+  override /*TraversableLike*/ 
+  def last: A = {
+    if (isEmpty) throw new NoSuchElementException
+    var these = this
+    var nx = these.tail
+    while (!nx.isEmpty) {
+      these = nx
+      nx = nx.tail
+    }
+    these.head
+  }
+  
+  override /*IterableLike*/ 
+  def take(n: Int): Repr = {
+    val b = newBuilder
+    var i = 0
+    var these = repr
+    while (!these.isEmpty && i < n) {
+      i += 1
+      b += these.head
+      these = these.tail
+    }
+    b.result
+  }
+  
+  override /*TraversableLike*/ 
+  def drop(n: Int): Repr = {
+    var these: Repr = repr
+    var count = n
+    while (!these.isEmpty && count > 0) {
+      these = these.tail
+      count -= 1
+    }
+    these
+  }
+
+  override /*IterableLike*/ 
+  def dropRight(n: Int): Repr = {
+    val b = newBuilder
+    var these = this
+    var lead = this drop n
+    while (!lead.isEmpty) {
+      b += these.head
+      these = these.tail
+      lead = lead.tail
+    }
+    b.result
+  }
+
+  override /*IterableLike*/ 
+  def slice(from: Int, until: Int): Repr = {
+    val b = newBuilder 
+    var i = from
+    var these = this drop from
+    while (i < until && !these.isEmpty) {
+      b += these.head
+      these = these.tail
+      i += 1
+    }
+    b.result
+  }
+
+  override /*IterableLike*/ 
+  def takeWhile(p: A => Boolean): Repr = {
+    val b = newBuilder
+    var these = this
+    while (!these.isEmpty && p(these.head)) {
+      b += these.head
+      these = these.tail
+    }
+    b.result
+  }
+
+  override /*TraversableLike*/ 
+  def span(p: A => Boolean): (Repr, Repr) = {
+    var these: Repr = repr
+    val b = newBuilder
+    while (!these.isEmpty && p(these.head)) {
+      b += these.head
+      these = these.tail
+    }
+    (b.result, these)
+  }  
+
+  override /*IterableLike*/ 
+  def sameElements[B >: A](that: Iterable[B]): Boolean = that match {
+    case that1: LinearSeq[_] =>
+      var these = this
+      var those = that1
+      while (!these.isEmpty && !those.isEmpty && these.head == those.head) {
+        these = these.tail
+        those = those.tail
+      }
+      these.isEmpty && those.isEmpty
+    case _ =>
+      super.sameElements(that)
+  }
+  
+  override /*SeqLike*/
+  def lengthCompare(len: Int): Int =  {
+    var i = 0
+    var these = self
+    while (!these.isEmpty && i <= len) {
+      i += 1
+      these = these.tail
+    }
+    i - len
+  }
+
+  override /*SeqLike*/
+  def isDefinedAt(x: Int): Boolean = x >= 0 && lengthCompare(x) > 0
+
+  override /*SeqLike*/
+  def segmentLength(p: A => Boolean, from: Int): Int = {
+    var i = 0
+    var these = this drop from
+    while (!these.isEmpty && p(these.head)) {
+      i += 1
+      these = these.tail
+    }
+    i
+  }
+
+  override /*SeqLike*/
+  def indexWhere(p: A => Boolean, from: Int): Int = {
+    var i = from
+    var these = this drop from
+    while (these.nonEmpty) {
+      if (p(these.head))
+        return i
+      
+      i += 1
+      these = these.tail
+    }
+    -1
+  }
+
+  override /*SeqLike*/
+  def lastIndexWhere(p: A => Boolean, end: Int): Int = {
+    var i = 0
+    var these = this
+    var last = -1
+    while (!these.isEmpty && i <= end) {
+      if (p(these.head)) last = i
+      these = these.tail
+      i += 1
+    }
+    last
+  }
+}
diff --git a/src/library/scala/collection/Map.scala b/src/library/scala/collection/Map.scala
index 9cd301b..8ebabf5 100644
--- a/src/library/scala/collection/Map.scala
+++ b/src/library/scala/collection/Map.scala
@@ -1,198 +1,44 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Map.scala 16881 2009-01-09 16:28:11Z cunei $
 
 
 package scala.collection
 
-import Predef._
-
-object Map {
-  trait Projection[A, +B] extends Iterable.Projection[(A, B)] with Map[A, B]
+import generic._
+
+/** 
+ *  A map from keys of type `A` to values of type `B`.
+ *  
+ *  $mapnote
+ *  
+ *  '''Note:''' If you do not have specific implementations for `add` and `-` in mind,
+ *        you might consider inheriting from `DefaultMap` instead.
+ *  
+ *  '''Note:''' If your additions and mutations return the same kind of map as the map
+ *        you are defining, you should inherit from `MapLike` as well.
+ *  
+ *  @tparam A     the type of the keys in this map.
+ *  @tparam B     the type of the values associated with keys.
+ *  
+ *  @since 1
+ */
+trait Map[A, +B] extends Iterable[(A, B)] with MapLike[A, B, Map[A, B]] {
+  def empty: Map[A, B] = Map.empty
 }
 
-
-/** <p>
-*     A map is a collection that maps each key to one or zero values.
- *  </p>
- *  <p>
- *    This trait provides a limited interface, only allowing reading of elements.
- *    There are two extensions of this trait, in packages
- *    <code><a href="mutable$content.html" target="contentFrame">
- *    scala.collection.mutable</a></code>
- *    and <code><a href="immutable$content.html" target="contentFrame">
- *    scala.collection.immutable</a></code>, which provide functionality for
- *    adding new key/value mappings to a map. The trait in the first package is
- *    for maps that are modified destructively, whereas the trait in
- *    the second package is for immutable maps which create a new map
- *    when something is added or removed from them.
- *  </p>
- *
- *  @author  Matthias Zenger
- *  @author  Martin Odersky
- *  @version 1.2, 31/12/2006
+/** $factoryInfo
+ *  @define Coll Map
+ *  @define coll map
  */
-trait Map[A, +B] extends PartialFunction[A, B] with Collection[(A, B)] {
-
-  /** Compute the number of key-to-value mappings.
-   *
-   *  @return the number of mappings
-   */
-  def size: Int
-
-  /** Check if this map maps <code>key</code> to a value and return the
-   *  value if it exists.
-   *
-   *  @param  key the key of the mapping of interest
-   *  @return     the value of the mapping, if it exists
-   */
-  def get(key: A): Option[B]
-    
-  /** Check if this map maps <code>key</code> to a value.
-    *  Return that value if it exists, otherwise return <code>default</code>.
-    */
-  def getOrElse[B2 >: B](key: A, default: => B2): B2 =
-    get(key) match {
-      case Some(v) => v
-      case None => default 
-    }
-
-  /** Is this an empty map?
-   *
-   *  @return <code>true</code> iff the map is empty.
-   */
-  override def isEmpty: Boolean = size == 0
-
-  /** Retrieve the value which is associated with the given key. This
-   *  method throws an exception if there is no mapping from the given
-   *  key to a value.
-   *
-   *  @param  key the key
-   *  @return     the value associated with the given key.
-   */
-  def apply(key: A): B = get(key) match {
-    case None => default(key)
-    case Some(value) => value
-  }
-
-  /** Is the given key mapped to a value by this map?
-   *
-   *  @param key the key
-   *  @return    <code>true</code> iff there is a mapping for key in this map
-   */
-  def contains(key: A): Boolean = get(key) match {
-    case None => false
-    case Some(_) => true
-  }
-
-  /** Does this map contain a mapping from the given key to a value?
-   *
-   *  @param key the key
-   *  @return    <code>true</code> iff there is a mapping for key in this map
-   */
-  def isDefinedAt(key: A) = contains(key)
-
-  /** Creates an iterator for all keys.
-   *
-   *  @return an iterator over all keys.
-   */
-  def keys: Iterator[A] = new Iterator[A] {
-    val iter = Map.this.elements
-    def hasNext = iter.hasNext
-    def next = iter.next._1
-  }
-
-  /** @return the keys of this map as a set. 
-   */
-  def keySet: Set[A] = new Set[A] {
-    def size = Map.this.size
-    def contains(key : A) = Map.this.contains(key)
-    def elements = Map.this.elements.map(_._1)
-  }
-
-  /** Creates an iterator for a contained values.
-   *
-   *  @return an iterator over all values.
-   */
-  def values: Iterator[B] = new Iterator[B] {
-    val iter = Map.this.elements
-    def hasNext = iter.hasNext
-    def next = iter.next._2
-  }
-
-  /** Compares two maps structurally; i.e. checks if all mappings
-   *  contained in this map are also contained in the other map,
-   *  and vice versa.
-   *
-   *  @param that the other map
-   *  @return     <code>true</code> iff both maps contain exactly the
-   *              same mappings.
-   */
-  override def equals(that: Any): Boolean = that match {
-    case other: Map[a, b] =>
-      this.size == other.size && this.elements.forall {
-        case (key, value) => other.get(key.asInstanceOf[a]) match {
-          case None => false
-          case Some(otherval) => value == otherval
-        }
-      }
-    case _ => false
-  }
-
-  /** A hash method compatible with <code>equals</code> 
-   */
-  override def hashCode() =
-    (0 /: elements) ((hash, kv) => hash + kv.hashCode)
-
-
-  /** Creates a string representation for this map.
-   *
-   *  @return    a string showing all mappings
-   */
-  override def toString() =
-    elements.toList.map(kv => kv._1 + " -> " + kv._2).mkString(stringPrefix + "(", ", ", ")")
-    
-  /** The default value for the map, returned when a key is not found
-   *  The method implemented here yields an error,
-   *  but it might be overridden in subclasses.
-   *
-   *  @param key the given key value
-   *  @throws Predef.NoSuchElementException
-   */
-  def default(key: A): B =
-    throw new NoSuchElementException("key not found: " + key)
-    
-  override def projection: Map.Projection[A,B] = new Map.Projection[A, B] {
-    override def elements = Map.this.elements
-    override def size = Map.this.size
-    override def get(key: A): Option[B] = Map.this.get(key)
-  }
-  /** non-strict filter based on keys only */
-  def filterKeys(p: A => Boolean): Map.Projection[A, B] = new Map.Projection[A, B] {
-    def elements = Map.this.elements.filter(x => p(x._1))
-    def size = {
-      var sz = 0
-      Map.this.foreach(x => if (p(x._1)) sz = sz + 1)
-      sz
-    }
-    override def contains(key: A) = Map.this.contains(key) && p(key)
-    override def get(key: A) = if (!p(key)) None else Map.this.get(key)
-  }
-  /** non-strict map elements using existing key set */
-  def mapElements[C](f: B => C) : Map.Projection[A,C] = new Map.Projection[A,C] {
-    def elements = Map.this.elements.map(e => (e._1, f(e._2)))
-    def size = Map.this.size
-    override def contains(key: A) = Map.this.contains(key)
-    override def get(key: A) = Map.this.get(key).map(f)
-  }
-
-  /** Defines the prefix of this object's <code>toString</code> representation.
-   */
-  override protected def stringPrefix: String = "Map"
+object Map extends MapFactory[Map] {
+  def empty[A, B]: immutable.Map[A, B] = immutable.Map.empty
+  
+  /** $mapCanBuildFromInfo */
+  implicit def canBuildFrom[A, B]: CanBuildFrom[Coll, (A, B), Map[A, B]] = new MapCanBuildFrom[A, B]
 }
diff --git a/src/library/scala/collection/MapLike.scala b/src/library/scala/collection/MapLike.scala
new file mode 100644
index 0000000..4a54f64
--- /dev/null
+++ b/src/library/scala/collection/MapLike.scala
@@ -0,0 +1,361 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+package scala.collection
+
+import generic._
+import mutable.{Builder, StringBuilder, MapBuilder}
+import annotation.migration
+import PartialFunction._
+
+/** A template trait for maps, which associate keys with values.
+ *
+ *  $mapNote 
+ *  $mapTags
+ *  @since 2.8
+ *
+ *  @define mapNote
+ *    '''Implementation note:'''
+ *    This trait provides most of the operations of a `Map` independently of its representation.
+ *    It is typically inherited by concrete implementations of maps.
+ *
+ *    To implement a concrete map, you need to provide implementations of the
+ *    following methods:
+ *    {{{
+ *       def get(key: A): Option[B]
+ *       def iterator: Iterator[(A, B)]
+ *       def + [B1 >: B](kv: (A, B1)): This
+ *       def -(key: A): This
+ *    }}}
+ *    If you wish that methods like `take`, `drop`, `filter` also return the same kind of map
+ *    you should also override:
+ *    {{{
+ *       def empty: This
+ *    }}}
+ *    It is also good idea to override methods `foreach` and
+ *    `size` for efficiency.
+ * 
+ *  @define mapTags
+ *  @tparam A    the type of the keys.
+ *  @tparam B    the type of associated values.
+ *  @tparam This the type of the map itself.
+ *
+ *  @author  Martin Odersky
+ *  @version 2.8
+ * 
+ *  @define coll map
+ *  @define Coll Map
+ *  @define willNotTerminateInf
+ *  @define mayNotTerminateInf
+ */
+trait MapLike[A, +B, +This <: MapLike[A, B, This] with Map[A, B]]
+  extends PartialFunction[A, B] 
+     with IterableLike[(A, B), This] 
+     with Subtractable[A, This] { 
+self =>
+  // note: can't inherit Addable because of variance problems: Map
+  // is covariant in its value type B, but Addable is nonvariant.
+
+  /** The empty map of the same type as this map
+   *   @return   an empty map of type `This`.
+   */
+  def empty: This
+       
+  /** A common implementation of `newBuilder` for all maps in terms of `empty`.
+   *  Overridden for mutable maps in `mutable.MapLike`.
+   */
+  override protected[this] def newBuilder: Builder[(A, B), This] = new MapBuilder[A, B, This](empty)
+
+  /** Optionally returns the value associated with a key.
+   *
+   *  @param  key    the key value
+   *  @return an option value containing the value associated with `key` in this map,
+   *          or `None` if none exists.
+   */
+  def get(key: A): Option[B]
+
+  /** Creates a new iterator over all key/value pairs of this map
+   *  
+   *  @return the new iterator
+   */
+  def iterator: Iterator[(A, B)]
+     
+  /** Adds a key/value pair to this map, returning a new map. 
+   *  @param    kv the key/value pair
+   *  @tparam   B1 the type of the value in the key/value pair. 
+   *  @return   a new map with the new binding added to this map
+   *  @usecase  def + (kv: (A, B)): Map[A, B]
+   */
+  def + [B1 >: B] (kv: (A, B1)): Map[A, B1]
+
+  /** Removes a key from this map, returning a new map.
+   *  @param    key the key to be removed
+   *  @return   a new map without a binding for `key`
+   *  @usecase  def - (key: A): Map[A, B]
+   */
+  def - (key: A): This
+
+  /** Tests whether the map is empty.
+   *
+   *  @return `true` if the map does not contain any key/value binding, `false` otherwise.
+   */
+  override def isEmpty: Boolean = size == 0
+
+  /**  Returns the value associated with a key, or a default value if the key is not contained in the map. 
+   *   @param   key      the key.
+   *   @param   default  a computation that yields a default value in case no binding for `key` is
+   *                     found in the map.
+   *   @tparam  B1       the result type of the default computation. 
+   *   @return  the value associated with `key` if it exists,
+   *            otherwise the result of the `default` computation.
+   *   @usecase def getOrElse(key: A, default: => B): B
+   */
+  def getOrElse[B1 >: B](key: A, default: => B1): B1 = get(key) match {
+    case Some(v) => v
+    case None => default 
+  }
+
+  /** Retrieves the value which is associated with the given key. This
+   *  method invokes the `default` method of the map if there is no mapping
+   *  from the given key to a value. Unless overridden, the `default` method throws a
+   *  `NoSuchElementException`.
+   *
+   *  @param  key the key
+   *  @return     the value associated with the given key, or the result of the
+   *              map's `default` method, if none exists.
+   */
+  def apply(key: A): B = get(key) match {
+    case None => default(key)
+    case Some(value) => value
+  }
+
+  /** Tests whether this map contains a binding for a key.
+   *
+   *  @param key the key
+   *  @return    `true` if there is a binding for `key` in this map, `false` otherwise.
+   */
+  def contains(key: A): Boolean = get(key) match {
+    case None => false
+    case Some(_) => true
+  }
+
+  /** Tests whether this map contains a binding for a key. This method,
+   *  which implements an abstract method of trait `PartialFunction`,
+   *  is equivalent to `contains`.
+   *
+   *  @param key the key
+   *  @return    `true` if there is a binding for `key` in this map, `false` otherwise.
+   */
+  def isDefinedAt(key: A) = contains(key)
+
+  /** Collects all keys of this map in a set.
+   * @return  a set containing all keys of this map.
+   */
+  def keySet: Set[A] = new DefaultKeySet
+
+  /** The implementation class of the set returned by `keySet`.
+   */
+  protected class DefaultKeySet extends Set[A] {
+    def contains(key : A) = self.contains(key)
+    def iterator = keysIterator
+    def + (elem: A): Set[A] = (Set[A]() ++ this + elem).asInstanceOf[Set[A]] // !!! concrete overrides abstract problem
+    def - (elem: A): Set[A] = (Set[A]() ++ this - elem).asInstanceOf[Set[A]] // !!! concrete overrides abstract problem
+    override def size = self.size
+    override def foreach[C](f: A => C) = for ((k, v) <- self) f(k)
+  }
+
+  /** Creates an iterator for all keys.
+   *
+   *  @return an iterator over all keys.
+   */
+  def keysIterator: Iterator[A] = new Iterator[A] {
+    val iter = self.iterator
+    def hasNext = iter.hasNext
+    def next = iter.next._1
+  }
+
+  /** Creates an iterator for all keys.
+   *
+   *  @return an iterator over all keys.
+   */
+  @migration(2, 8, "As of 2.8, keys returns Iterable[A] rather than Iterator[A].")
+  def keys: Iterable[A] = keySet
+
+  /** Collects all values of this map in an iterable collection. 
+   * @return the values of this map as an iterable.
+   */
+  @migration(2, 8, "As of 2.8, values returns Iterable[B] rather than Iterator[B].")
+  def values: Iterable[B] = new DefaultValuesIterable
+
+  /** The implementation class of the iterable returned by `values`.
+   */
+  protected class DefaultValuesIterable extends Iterable[B] {
+    def iterator = valuesIterator
+    override def size = self.size
+    override def foreach[C](f: B => C) = for ((k, v) <- self) f(v)
+  }
+
+  /** Creates an iterator for all values in this map.
+   *
+   *  @return an iterator over all values that are associated with some key in this map.
+   */
+  def valuesIterator: Iterator[B] = new Iterator[B] {
+    val iter = self.iterator
+    def hasNext = iter.hasNext
+    def next = iter.next._2
+  }
+
+  /** Defines the default value computation for the map,
+   *  returned when a key is not found
+   *  The method implemented here throws an exception,
+   *  but it might be overridden in subclasses.
+   *
+   *  @param key the given key value for which a binding is missing.
+   *  @throws `NoSuchElementException`
+   */
+  def default(key: A): B =
+    throw new NoSuchElementException("key not found: " + key)
+    
+  /** Filters this map by retaining only keys satisfying a predicate.
+   *  @param  p   the predicate used to test keys
+   *  @return an immutable map consisting only of those key value pairs of this map where the key satisfies
+   *          the predicate `p`. The resulting map wraps the original map without copying any elements.
+   */
+  def filterKeys(p: A => Boolean): Map[A, B] = new DefaultMap[A, B] {
+    override def foreach[C](f: ((A, B)) => C): Unit = for (kv <- self) if (p(kv._1)) f(kv)
+    def iterator = self.iterator.filter(kv => p(kv._1))
+    override def contains(key: A) = self.contains(key) && p(key)
+    def get(key: A) = if (!p(key)) None else self.get(key)
+  }    
+
+  /** Transforms this map by applying a function to every retrieved value.
+   *  @param  f   the function used to transform values of this map.
+   *  @return a map view which maps every key of this map
+   *          to `f(this(key))`. The resulting map wraps the original map without copying any elements.
+   */
+  def mapValues[C](f: B => C): Map[A, C] = new DefaultMap[A, C] {
+    override def foreach[D](g: ((A, C)) => D): Unit = for ((k, v) <- self) g((k, f(v)))
+    def iterator = for ((k, v) <- self.iterator) yield (k, f(v))
+    override def size = self.size
+    override def contains(key: A) = self.contains(key)
+    def get(key: A) = self.get(key).map(f)
+  }
+
+  @deprecated("use `mapValues' instead") def mapElements[C](f: B => C) = mapValues(f)
+
+  // The following 5 operations (updated, two times +, two times ++) should really be
+  // generic, returning This[B]. We need better covariance support to express that though.
+  // So right now we do the brute force approach of code duplication.
+
+  /** Creates a new map obtained by updating this map with a given key/value pair. 
+   *  @param    key the key
+   *  @param    value the value
+   *  @tparam   B1 the type of the added value
+   *  @return   A new map with the new key/value mapping added to this map.
+   *  @usecase  def updated(key: A, value: B): Map[A, B]
+   */
+  def updated [B1 >: B](key: A, value: B1): Map[A, B1] = this + ((key, value))
+
+  /** Adds key/value pairs to this map, returning a new map.
+   *
+   *  This method takes two or more key/value pairs. Another overloaded
+   *  variant of this method handles the case where a single key/value pair is
+   *  added.
+   *  @param    kv1 the first key/value pair
+   *  @param    kv2 the second key/value pair
+   *  @param    kvs the remaining key/value pairs
+   *  @tparam   B1  the type of the added values
+   *  @return   a new map with the given bindings added to this map
+   *  @usecase  def + (kvs: (A, B)*): Map[A, B]
+   *  @param    the key/value pairs
+   */
+  def + [B1 >: B] (kv1: (A, B1), kv2: (A, B1), kvs: (A, B1) *): Map[A, B1] =
+    this + kv1 + kv2 ++ kvs
+
+  /** Adds all key/value pairs in a traversable collection to this map, returning a new map.
+   *
+   *  @param    kvs the collection containing the added key/value pairs
+   *  @tparam   B1  the type of the added values
+   *  @return   a new map with the given bindings added to this map
+   *  @usecase  def ++ (xs: Traversable[(A, B)]): Map[A, B]
+   */
+  def ++[B1 >: B](xs: TraversableOnce[(A, B1)]): Map[A, B1] = 
+    ((repr: Map[A, B1]) /: xs) (_ + _)
+
+  /** Returns a new map with all key/value pairs for which the predicate
+   *  `p` returns `true`.
+   *
+   *  '''Note:'''    This method works by successively removing elements fro which the
+   *           predicate is false from this set.
+   *           If removal is slow, or you expect that most elements of the set
+   *           will be removed, you might consider using `filter`
+   *           with a negated predicate instead. 
+   *  @param p    A predicate over key-value pairs
+   *  @return     A new map containing elements not satisfying the predicate.
+   */
+  override def filterNot(p: ((A, B)) => Boolean): This = {
+    var res: This = repr
+    for (kv <- this)
+      if (p(kv)) res = (res - kv._1).asInstanceOf[This] // !!! concrete overrides abstract problem
+    res
+  }
+
+  /** Appends all bindings of this map to a string builder using start, end, and separator strings.
+   *  The written text begins with the string `start` and ends with the string
+   *  `end`. Inside, the string representations of all bindings of this map
+   *  in the form of `key -> value` are separated by the string `sep`.
+   *   
+   *  @param b     the builder to which strings are appended.
+   *  @param start the starting string.
+   *  @param sep   the separator string.
+   *  @param end   the ending string.
+   *  @return      the string builder `b` to which elements were appended.
+   */
+  override def addString(b: StringBuilder, start: String, sep: String, end: String): StringBuilder =
+    this.iterator.map { case (k, v) => k+" -> "+v }.addString(b, start, sep, end)
+
+  /** Defines the prefix of this object's `toString` representation.
+   *  @return  a string representation which starts the result of `toString` applied to this $coll.
+   *           Unless overridden in subclasses, the string prefix of every map is `"Map"`.
+   */
+  override def stringPrefix: String = "Map"
+
+  override /*PartialFunction*/
+  def toString = super[IterableLike].toString
+  
+  override def hashCode() = this map (_.##) sum
+  
+  /** Compares two maps structurally; i.e. checks if all mappings
+   *  contained in this map are also contained in the other map,
+   *  and vice versa.
+   *
+   *  @param that the other map
+   *  @return     `true` if both maps contain exactly the
+   *              same mappings, `false` otherwise.
+   */
+  override def equals(that: Any): Boolean = that match {
+    case that: Map[b, _] => 
+      (this eq that) ||
+      (that canEqual this) &&
+      (this.size == that.size) && {
+      try {
+        this forall { 
+          case (k, v) => that.get(k.asInstanceOf[b]) match {
+            case Some(`v`) => true
+            case _ => false
+          }
+        }
+      } catch { 
+        case ex: ClassCastException => 
+          println("class cast "); false 
+      }}
+    case _ =>
+      false
+  }
+}
diff --git a/src/library/scala/collection/MapProxy.scala b/src/library/scala/collection/MapProxy.scala
index 70bbfc5..1cc7d81 100644
--- a/src/library/scala/collection/MapProxy.scala
+++ b/src/library/scala/collection/MapProxy.scala
@@ -1,17 +1,15 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: MapProxy.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala.collection
 
-
 /** This is a simple wrapper class for <a href="Map.html"
  *  target="contentFrame"><code>scala.collection.Map</code></a>.
  *  It is most useful for assembling customized map abstractions
@@ -19,27 +17,6 @@ package scala.collection
  *
  *  @author  Matthias Zenger
  *  @version 1.0, 21/07/2003
+ *  @since   1
  */
-trait MapProxy[A, +B] extends Map[A, B] with CollectionProxy[(A, B)] {
-
-  override def self: Map[A, B]
-
-  override def size = self.size
-  override def get(key: A) = self.get(key)
-  override def getOrElse[B2 >: B](key: A, default: => B2) = self.getOrElse(key, default)
-  
-  override def isEmpty = self.isEmpty
-  override def apply(key: A) = self.apply(key)
-  override def contains(key: A) = self.contains(key)
-  override def isDefinedAt(key: A) = self.isDefinedAt(key)
-  override def keys = self.keys
-  override def keySet = self.keySet
-  override def values = self.values
-  override def equals(that: Any) = self equals that
-  override def hashCode() = self.hashCode()
-  override def toString() = self.toString()
-  override def default(key: A) = self.default(key)
-  override def projection = self.projection
-  override def filterKeys(p: A => Boolean) = self filterKeys p
-  override def mapElements[C](f: B => C) = self mapElements f
-}
+trait MapProxy[A, +B] extends Map[A, B] with MapProxyLike[A, B, Map[A, B]]
diff --git a/src/library/scala/collection/MapProxyLike.scala b/src/library/scala/collection/MapProxyLike.scala
new file mode 100644
index 0000000..f2f5727
--- /dev/null
+++ b/src/library/scala/collection/MapProxyLike.scala
@@ -0,0 +1,50 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+package scala.collection
+
+import generic._
+
+// Methods could be printed by  cat MapLike.scala | egrep '^  (override )?def'
+
+/** This trait implements a proxy for Map objects. It forwards
+ *  all calls to a different Map object.
+ *
+ *  @author  Martin Odersky
+ *  @version 2.8
+ *  @since   2.8
+ */
+trait MapProxyLike[A, +B, +This <: MapLike[A, B, This] with Map[A, B]]
+      extends MapLike[A, B, This]
+      with IterableProxyLike[(A, B), This]
+{  
+  override def get(key: A): Option[B] = self.get(key)
+  override def iterator: Iterator[(A, B)] = self.iterator
+  override def + [B1 >: B] (kv: (A, B1)): Map[A, B1] = self.+(kv)
+  override def - (key: A): This = self.-(key)
+  override def isEmpty: Boolean = self.isEmpty
+  override def getOrElse[B1 >: B](key: A, default: => B1): B1 = self.getOrElse(key, default)
+  override def apply(key: A): B = self.apply(key)
+  override def contains(key: A): Boolean = self.contains(key)
+  override def isDefinedAt(key: A) = self.isDefinedAt(key)
+  override def keySet: Set[A] = self.keySet
+  override def keysIterator: Iterator[A] = self.keysIterator
+  override def keys: Iterable[A] = self.keys
+  override def values: Iterable[B] = self.values
+  override def valuesIterator: Iterator[B] = self.valuesIterator
+  override def default(key: A): B = self.default(key)
+  override def filterKeys(p: A => Boolean) = self.filterKeys(p)
+  override def mapValues[C](f: B => C) = self.mapValues(f) 
+  override def updated [B1 >: B](key: A, value: B1): Map[A, B1] = self.updated(key, value)
+  override def + [B1 >: B] (kv1: (A, B1), kv2: (A, B1), kvs: (A, B1) *): Map[A, B1] = self.+(kv1, kv2, kvs: _*)
+  override def ++[B1 >: B](xs: TraversableOnce[(A, B1)]): Map[A, B1] =  self.++(xs)
+  override def filterNot(p: ((A, B)) => Boolean) = self filterNot p
+  
+  override def addString(b: StringBuilder, start: String, sep: String, end: String): StringBuilder =
+    self.addString(b, start, sep, end)
+}
diff --git a/src/library/scala/collection/Ranged.scala b/src/library/scala/collection/Ranged.scala
deleted file mode 100644
index 6ca5993..0000000
--- a/src/library/scala/collection/Ranged.scala
+++ /dev/null
@@ -1,61 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: Ranged.scala 16894 2009-01-13 13:09:41Z cunei $
-
-package scala.collection
-
-/** Any collection (including maps) whose keys (or elements) are ordered.
- *
- *  @author Sean McDirmid
- */
-trait Ranged[K, +A] extends Iterable[A] {
-  //protected type SortedSelf <: Ranged[K,A];
-
-  /** Returns the first key of the collection. */
-  def firstKey: K
-
-  /** Returns the last key of the collection. */
-  def lastKey: K
-
-  /** Comparison function that orders keys. */
-  def compare(k0: K, k1: K): Int
- 
-  /** Creates a ranged projection of this collection. Any mutations in the
-   *  ranged projection will update this collection and vice versa.  Note: keys
-   *  are not garuanteed to be consistent between this collection and the projection.
-   *  This is the case for buffers where indexing is relative to the projection. 
-   *
-   *  @param from  The lower-bound (inclusive) of the ranged projection.
-   *               <code>None</code> if there is no lower bound.
-   *  @param until The upper-bound (exclusive) of the ranged projection.
-   *               <code>None</code> if there is no upper bound.
-   */
-  def rangeImpl(from: Option[K], until: Option[K]): Ranged[K, A]
-
-  /** Creates a ranged projection of this collection with no upper-bound.
-   *
-   *  @param from The lower-bound (inclusive) of the ranged projection.
-   */
-  def from(from: K) = rangeImpl(Some(from), None)
-
-  /** Creates a ranged projection of this collection with no lower-bound.
-   *
-   *  @param until The upper-bound (exclusive) of the ranged projection.
-   */
-  def until(until: K) = rangeImpl(None, Some(until))
-  
-  /** Creates a ranged projection of this collection with both a lower-bound
-   *  and an upper-bound.
-   *
-   *  @param from  The upper-bound (exclusive) of the ranged projection.
-   *  @param until ...
-   *  @return      ...
-   */
-  def range(from: K, until: K) = rangeImpl(Some(from), Some(until))
-}
diff --git a/src/library/scala/collection/RollbackIterator.scala b/src/library/scala/collection/RollbackIterator.scala
deleted file mode 100644
index 6456712..0000000
--- a/src/library/scala/collection/RollbackIterator.scala
+++ /dev/null
@@ -1,87 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2007-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: RollbackIterator.scala 16881 2009-01-09 16:28:11Z cunei $
-
-package scala.collection
-
-import scala.collection.mutable.{ArrayBuffer}
-
-/** Rollback iterators are buffered iterators which allow for unbounded rollbacks
- *
- *  @author  Sean McDirmid
- */
-class RollbackIterator[+A](underlying: Iterator[A]) extends BufferedIterator.Default[A] {
-  private[this] var rollback: ArrayBuffer[A] = null
-  protected def fill(sz: Int): Seq[A] =
-    if (underlying.hasNext) underlying.next :: Nil else Nil
-
-  override def next: A = {
-    val ret = super.next
-    if (rollback != null) rollback += ret
-    ret
-  }
-
-  private def initRollback =
-    if (rollback == null) {
-      rollback = new ArrayBuffer[A]
-      None
-    }
-    else Some(rollback.length)
-
-  /** will rollback all elements iterated during 
-   *  <code>f</code>'s execution if <code>f</code> return false 
-   */
-  def tryRead[T](f: => Option[T]): Option[T] = {
-    val oldLength = initRollback
-    var g : Option[T] = None
-    try {
-      g = f
-    } finally {
-      if (g.isEmpty) {
-        //putBack(rollback(0))
-        val sz = oldLength.getOrElse(0)
-        val i = rollback.drop(sz).reverse.elements
-        while (i.hasNext) putBack(i.next)
-        if (oldLength.isEmpty) rollback = null          
-        else rollback.reduceToSize(sz)
-      }
-    }
-    if (!g.isEmpty && oldLength.isEmpty) 
-      rollback = null
-    g
-
-  }
-  /** remembers elements iterated over during <code>g</code>'s execution
-   *  and provides these elements to the result of <code>g</code>'s execution
-   */
-  def remember[T](g: => (Seq[A] => T)): T = {
-    val oldLength = initRollback
-    var in: Seq[A] = Nil
-    val f = try {
-      g
-    } finally {
-      in = rollback.drop(oldLength.getOrElse(0))
-      if (oldLength.isEmpty) rollback = null
-    }
-    f(in)
-  }
-
-  /** returns true if any elements are iterated over during <code>f</code>'s execution 
-   */
-  def read(f: => Unit): Boolean = remember[Boolean] {
-    f; seq => !seq.isEmpty
-  }
-
-  /** if elements of <code>seq</code> will be iterated over next in this iterator,
-   *  returns true and iterates over these elements
-   */
-  override def readIfStartsWith(seq : Seq[Any]) : Boolean = 
-    !tryRead{if (seq.forall(a => hasNext && next == a)) Some(()) else None}.isEmpty
-
-}
diff --git a/src/library/scala/collection/Seq.scala b/src/library/scala/collection/Seq.scala
new file mode 100644
index 0000000..fa05778
--- /dev/null
+++ b/src/library/scala/collection/Seq.scala
@@ -0,0 +1,46 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+
+import generic._
+import mutable.Builder
+
+/** A base trait for sequences.
+ *  $seqInfo
+ */
+trait Seq[+A] extends PartialFunction[Int, A] 
+                      with Iterable[A] 
+                      with GenericTraversableTemplate[A, Seq]
+                      with SeqLike[A, Seq[A]] {
+  override def companion: GenericCompanion[Seq] = Seq
+}
+
+/** $factoryInfo
+ *  The current default implementation of a $Coll is a `Vector`.
+ *  @define coll sequence
+ *  @define Coll Seq
+ */
+object Seq extends SeqFactory[Seq] {
+
+  private[collection] val hashSeed = "Seq".hashCode
+   
+  /** $genericCanBuildFromInfo */
+  implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, Seq[A]] = new GenericCanBuildFrom[A]
+
+  def newBuilder[A]: Builder[A, Seq[A]] = immutable.Seq.newBuilder[A]
+  
+  @deprecated("use View instead")
+  type Projection[A] = SeqView[A, Coll] 
+  
+  @deprecated("use Seq(value) instead")
+  def singleton[A](value: A) = Seq(value) 
+}
+
diff --git a/src/library/scala/collection/SeqLike.scala b/src/library/scala/collection/SeqLike.scala
new file mode 100644
index 0000000..144b1ac
--- /dev/null
+++ b/src/library/scala/collection/SeqLike.scala
@@ -0,0 +1,897 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+
+import mutable.{ListBuffer, HashMap, ArraySeq}
+import immutable.{List, Range}
+import generic._
+
+/** The companion object for trait `SeqLike`.
+ */
+object SeqLike {
+
+  /**  A KMP implementation, based on the undoubtedly reliable wikipedia entry.
+   *
+   *  @author paulp
+   *  @since  2.8
+   */
+  private def KMP[B](S: Seq[B], W: Seq[B]): Option[Int] = {
+    // trivial cases
+    if (W.isEmpty) return Some(0)
+    else if (W drop 1 isEmpty) return (S indexOf W(0)) match {
+      case -1 => None
+      case x  => Some(x)
+    }
+    
+    val T: Array[Int] = {
+      val arr = new Array[Int](W.length)
+      var pos = 2
+      var cnd = 0
+      arr(0) = -1
+      arr(1) = 0
+      while (pos < W.length) {
+        if (W(pos - 1) == W(cnd)) {
+          arr(pos) = cnd + 1
+          pos += 1
+          cnd += 1
+        }
+        else if (cnd > 0) {
+          cnd = arr(cnd)
+        }
+        else {
+          arr(pos) = 0
+          pos += 1
+        }
+      }
+      arr
+    }
+    
+    var m, i = 0
+    def mi = m + i
+    
+    while (mi < S.length) {
+      if (W(i) == S(mi)) {
+        i += 1
+        if (i == W.length)
+          return Some(m)
+      }
+      else {
+        m = mi - T(i)
+        if (i > 0)
+          i = T(i)
+      }
+    }
+    None
+  }
+
+  /** Finds a particular index at which one sequence occurs in another sequence.
+   *  Both the source sequence and the target sequence are expressed in terms
+   *  other sequences S' and T' with offset and length parameters.  This
+   *  function is designed to wrap the KMP machinery in a sufficiently general
+   *  way that all library sequence searches can use it.  It is unlikely you
+   *  have cause to call it directly: prefer functions such as StringBuilder#indexOf
+   *  and Seq#lastIndexOf.
+   *   
+   *  @param  source        the sequence to search in
+   *  @param  sourceOffset  the starting offset in source
+   *  @param  sourceCount   the length beyond sourceOffset to search
+   *  @param  target        the sequence being searched for
+   *  @param  targetOffset  the starting offset in target
+   *  @param  targetCount   the length beyond targetOffset which makes up the target string
+   *  @param  fromIndex     the smallest index at which the target sequence may start
+   *
+   *  @return the applicable index in source where target exists, or -1 if not found
+   */
+  def indexOf[B](
+    source: Seq[B], sourceOffset: Int, sourceCount: Int,
+    target: Seq[B], targetOffset: Int, targetCount: Int,
+    fromIndex: Int): Int =
+      KMP(source.slice(sourceOffset, sourceCount) drop fromIndex, target.slice(targetOffset, targetCount)) match {
+        case None    => -1
+        case Some(x) => x + fromIndex
+      }
+
+  /** Finds a particular index at which one sequence occurs in another sequence.
+   *  Like indexOf, but finds the latest occurrence rather than earliest.
+   *  
+   *  @see  SeqLike#indexOf
+   */
+  def lastIndexOf[B](
+    source: Seq[B], sourceOffset: Int, sourceCount: Int,
+    target: Seq[B], targetOffset: Int, targetCount: Int,
+    fromIndex: Int): Int = {
+      val src = (source.slice(sourceOffset, sourceCount) take fromIndex).reverse
+      val tgt = target.slice(targetOffset, targetCount).reverse
+
+      KMP(src, tgt) match {
+        case None    => -1
+        case Some(x) => (src.length - tgt.length - x) + sourceOffset
+      }
+    }
+}
+
+/** A template trait for sequences of type `Seq[A]`
+ *  $seqInfo
+ *
+ *  @define seqInfo
+ *  Sequences are special cases of iterable collections of class `Iterable`.
+ *  Unlike iterables, sequences always have a defined order of elements.
+ *  Sequences provide a method `apply` for indexing. Indices range from `0` up the the `length` of
+ *  a sequence. Sequences support a number to find occurrences of elements or subsequences, including
+ *  `segmentLength`, `prefixLength`, `indexWhere`, `indexOf`, `lastIndexWhere`, `lastIndexOf`,
+ *  `startsWith`, `endsWith`, `indexOfSlice`.
+ *
+ *  Another way to see a sequence is as a `PartialFunction` from `Int` values
+ *  to the element type of the sequence. The `isDefinedAt` method of a sequence
+ *  returns `true` for the interval from `0` until `length`.
+ *
+ *  Sequences can be accessed in reverse order of their elements, using methods
+ *  `reverse` and `reverseIterator`.
+ *
+ *  Sequences have two principal subtraits, `IndexedSeq` and `LinearSeq`, which give different guarantees for performance.
+ *  An `IndexedSeq` provides fast random-access of elements and a fast `length` operation.
+ *  A `LinearSeq` provides fast access only to the first element via `head`, but also
+ *  has a fast `tail` operation. 
+ *
+ *  @tparam A    the element type of the collection
+ *  @tparam Repr the type of the actual collection containing the elements.
+ *
+ *  @author  Martin Odersky
+ *  @author  Matthias Zenger
+ *  @version 1.0, 16/07/2003
+ *  @since   2.8
+ * 
+ *  @define Coll Seq
+ *  @define coll sequence
+ *  @define thatinfo the class of the returned collection. Where possible, `That` is 
+ *    the same class as the current collection class `Repr`, but this
+ *    depends on the element type `B` being admissible for that class,
+ *    which means that an implicit instance of type `CanBuildFrom[Repr, B, That]`
+ *    is found.
+ *  @define bfinfo an implicit value of class `CanBuildFrom` which determines the
+ *    result class `That` from the current representation type `Repr`
+ *    and the new element type `B`. 
+ *  @define orderDependent
+ *  @define orderDependentFold
+ *  @define mayNotTerminateInf
+ *
+ *    Note: may not terminate for infinite-sized collections.
+ *  @define willNotTerminateInf
+ *
+ *    Note: will not terminate for infinite-sized collections.
+ */
+trait SeqLike[+A, +Repr] extends IterableLike[A, Repr] { self =>
+
+  override protected[this] def thisCollection: Seq[A] = this.asInstanceOf[Seq[A]]
+  override protected[this] def toCollection(repr: Repr): Seq[A] = repr.asInstanceOf[Seq[A]]
+
+  /** The length of the $coll.
+   * 
+   *  $willNotTerminateInf
+   *
+   *  Note: `xs.length` and `xs.size` yield the same result.
+   * 
+   *  @return     the number of elements in this $coll.
+   */
+  def length: Int
+
+  /** Selects an element by its index in the $coll.
+   *
+   *  @param  idx  The index to select.
+   *  @return the element of this $coll at index `idx`, where `0` indicates the first element.
+   *  @throws `IndexOutOfBoundsException` if `idx` does not satisfy `0 <= idx < length`.
+   */
+  def apply(idx: Int): A
+
+  /** Compares the length of this $coll to a test value.
+   *
+   *   @param   len   the test value that gets compared with the length.
+   *   @return  A value `x` where
+   *   {{{
+   *        x <  0       if this.length <  len
+   *        x == 0       if this.length == len
+   *        x >  0       if this.length >  len
+   *   }}}
+   *  The method as implemented here does not call `length` directly; its running time
+   *  is `O(length min len)` instead of `O(length)`. The method should be overwritten
+   *  if computing `length` is cheap.
+   */
+  def lengthCompare(len: Int): Int = {
+    var i = 0
+    val it = iterator
+    while (it.hasNext && i <= len) {
+      it.next()
+      i += 1
+    }
+    i - len
+  }
+
+  /** The size of this $coll, equivalent to `length`.
+   * 
+   *  $willNotTerminateInf
+   */
+  override def size = length
+
+  /** Tests whether this $coll contains given index.
+   *
+   *  The implementations of methods `apply` and `isDefinedAt` turn a `Seq[A]` into
+   *  a `PartialFunction[Int, A]`.
+   *
+   * @param    idx     the index to test
+   * @return   `true` if this $coll contains an element at position `idx`, `false` otherwise.
+   */
+  def isDefinedAt(idx: Int): Boolean = (idx >= 0) && (idx < length)
+
+  /** Computes length of longest segment whose elements all satisfy some predicate.
+   * 
+   *  $mayNotTerminateInf
+   *
+   *  @param   p     the predicate used to test elements.
+   *  @param   from  the index where the search starts.
+   *  @return  the length of the longest segment of this $coll starting from index `from`
+   *           such that every element of the segment satisfies the predicate `p`.
+   */
+  def segmentLength(p: A => Boolean, from: Int): Int = {
+    var i = 0
+    var it = iterator.drop(from)
+    while (it.hasNext && p(it.next()))
+      i += 1
+    i
+  }
+
+  /** Returns the length of the longest prefix whose elements all satisfy some predicate. 
+   * 
+   *  $mayNotTerminateInf
+   *
+   *  @param   p     the predicate used to test elements.
+   *  @return  the length of the longest prefix of this $coll
+   *           such that every element of the segment satisfies the predicate `p`.
+   */
+  def prefixLength(p: A => Boolean) = segmentLength(p, 0)
+
+  /** Finds index of first element satisfying some predicate.
+   * 
+   *  $mayNotTerminateInf
+   *
+   *  @param   p     the predicate used to test elements.
+   *  @return  the index of the first element of this $coll that satisfies the predicate `p`,
+   *           or `-1`, if none exists.
+   */
+  def indexWhere(p: A => Boolean): Int = indexWhere(p, 0)
+
+  /** Finds index of the first element satisfying some predicate after or at some start index.
+   * 
+   *  $mayNotTerminateInf
+   *
+   *  @param   p     the predicate used to test elements.
+   *  @param   from   the start index
+   *  @return  the index `>= from` of the first element of this $coll that satisfies the predicate `p`,
+   *           or `-1`, if none exists.
+   */
+  def indexWhere(p: A => Boolean, from: Int): Int = {
+    var i = from
+    var it = iterator.drop(from)
+    while (it.hasNext) {
+      if (p(it.next())) return i
+      else i += 1
+    }
+
+    -1
+  }
+
+  /** Returns index of the first element satisfying a predicate, or `-1`.
+   */
+  def findIndexOf(p: A => Boolean): Int = indexWhere(p)
+
+  /** Finds index of first occurrence of some value in this $coll.
+   * 
+   *  $mayNotTerminateInf
+   *
+   *  @param   elem   the element value to search for.
+   *  @tparam  B      the type of the element `elem`. 
+   *  @return  the index of the first element of this $coll that is equal (wrt `==`)
+   *           to `elem`, or `-1`, if none exists.
+   *
+   *  @usecase def indexOf(elem: A): Int
+   */
+  def indexOf[B >: A](elem: B): Int = indexOf(elem, 0)
+
+  /** Finds index of first occurrence of some value in this $coll after or at some start index.
+   * 
+   *  $mayNotTerminateInf
+   *
+   *  @param   elem   the element value to search for.
+   *  @tparam  B      the type of the element `elem`. 
+   *  @param   from   the start index
+   *  @return  the index `>= from` of the first element of this $coll that is equal (wrt `==`)
+   *           to `elem`, or `-1`, if none exists.
+   *
+   *  @usecase def indexOf(elem: A, from: Int): Int
+   */
+  def indexOf[B >: A](elem: B, from: Int): Int = indexWhere(elem ==, from)
+
+  /** Finds index of last occurrence of some value in this $coll.
+   * 
+   *  $willNotTerminateInf
+   *
+   *  @param   elem   the element value to search for.
+   *  @tparam  B      the type of the element `elem`. 
+   *  @return  the index of the last element of this $coll that is equal (wrt `==`)
+   *           to `elem`, or `-1`, if none exists.
+   *
+   *  @usecase def lastIndexOf(elem: A): Int
+   */
+  def lastIndexOf[B >: A](elem: B): Int = lastIndexWhere(elem ==)
+
+  /** Finds index of last occurrence of some value in this $coll before or at a given end index.
+   * 
+   *  @param   elem   the element value to search for.
+   *  @param   end    the end index.
+   *  @tparam  B      the type of the element `elem`. 
+   *  @return  the index `<= end` of the last element of this $coll that is equal (wrt `==`)
+   *           to `elem`, or `-1`, if none exists.
+   *
+   *  @usecase def lastIndexOf(elem: A, end: Int): Int
+   */
+  def lastIndexOf[B >: A](elem: B, end: Int): Int = lastIndexWhere(elem ==, end)
+
+  /** Finds index of last element satisfying some predicate.
+   * 
+   *  $willNotTerminateInf
+   *
+   *  @param   p     the predicate used to test elements.
+   *  @return  the index of the last element of this $coll that satisfies the predicate `p`,
+   *           or `-1`, if none exists.
+   */
+  def lastIndexWhere(p: A => Boolean): Int = lastIndexWhere(p, length - 1)
+
+  /** Finds index of last element satisfying some predicate before or at given end index.
+   * 
+   *  @param   p     the predicate used to test elements.
+   *  @return  the index `<= end` of the last element of this $coll that satisfies the predicate `p`,
+   *           or `-1`, if none exists.
+   */
+  def lastIndexWhere(p: A => Boolean, end: Int): Int = {
+    var i = length - 1
+    val it = reverseIterator
+    while (it.hasNext && { val elem = it.next; (i > end || !p(elem)) }) i -= 1
+    i
+  }
+
+  /** Returns new $coll wih elements in reversed order.
+   * 
+   *  $willNotTerminateInf
+   * 
+   *  @return A new $coll with all elements of this $coll in reversed order.
+   */
+  def reverse: Repr = {
+    var xs: List[A] = List()
+    for (x <- this) 
+      xs = x :: xs
+    val b = newBuilder
+    b.sizeHint(this)
+    for (x <- xs)
+      b += x
+    b.result
+  }
+  
+  /**
+   *  Builds a new collection by applying a function to all elements of this $coll and
+   *  collecting the results in reversed order.
+   * 
+   *  $willNotTerminateInf
+   *
+   *  Note: `xs.reverseMap(f)` is the same as `xs.reverse.map(f)` but might be more efficient.
+   * 
+   *  @param f      the function to apply to each element.
+   *  @tparam B     the element type of the returned collection.
+   *  @tparam That  $thatinfo
+   *  @param bf     $bfinfo
+   *  @return       a new collection of type `That` resulting from applying the given function
+   *                `f` to each element of this $coll and collecting the results in reversed order.
+   *
+   *  @usecase def reverseMap[B](f: A => B): $Coll[B] 
+   *  
+   *  Note: `xs.reverseMap(f)` is the same as `xs.reverse.map(f)` but might be more efficient.
+   *  @return       a new $coll resulting from applying the given function
+   *                `f` to each element of this $coll and collecting the results in reversed order.
+   */
+  def reverseMap[B, That](f: A => B)(implicit bf: CanBuildFrom[Repr, B, That]): That = {
+    var xs: List[A] = List()
+    for (x <- this) 
+      xs = x :: xs
+    val b = bf(repr)
+    for (x <- xs)
+      b += f(x)
+
+    b.result
+  }
+
+  /** An iterator yielding elements in reversed order.
+   *
+   *   $willNotTerminateInf
+   *
+   * Note: `xs.reverseIterator` is the same as `xs.reverse.iterator` but might be more efficient.
+   *
+   *  @return  an iterator yielding the elements of this $coll in reversed order
+   */
+  def reverseIterator: Iterator[A] = toCollection(reverse).iterator
+
+  @deprecated("use `reverseIterator' instead")
+  def reversedElements = reverseIterator
+
+  /** Tests whether this $coll contains the given sequence at a given index. 
+   * 
+   * If the both the receiver object, <code>this</code> and 
+   * the argument, <code>that</code> are infinite sequences 
+   * this method may not terminate.
+   * 
+   * @param  that    the sequence to test
+   * @param  offset  the index where the sequence is searched.
+   * @return `true` if the sequence `that` is contained in this $coll at index `offset`,
+   *         otherwise `false`. 
+   */
+  def startsWith[B](that: Seq[B], offset: Int): Boolean = {  
+    val i = this.iterator drop offset
+    val j = that.iterator
+    while (j.hasNext && i.hasNext)
+      if (i.next != j.next)
+        return false
+
+    !j.hasNext
+  }
+
+  /** Tests whether this $coll starts with the given sequence.
+   *
+   * @param  that    the sequence to test
+   * @return `true` if this collection has `that` as a prefix, `false` otherwise.
+   */
+  def startsWith[B](that: Seq[B]): Boolean = startsWith(that, 0)
+
+  /** Tests whether this $coll ends with the given sequence.
+   *  $willNotTerminateInf
+   *  @param  that    the sequence to test
+   *  @return `true` if this $coll has `that` as a suffix, `false` otherwise.
+   */
+  def endsWith[B](that: Seq[B]): Boolean = {
+    val i = this.iterator.drop(length - that.length)
+    val j = that.iterator
+    while (i.hasNext && j.hasNext)
+      if (i.next != j.next)
+        return false
+    
+    !j.hasNext
+  }
+
+  /** Finds first index where this $coll contains a given sequence as a slice.
+   *  $mayNotTerminateInf
+   *  @param  that    the sequence to test
+   *  @return  the first index such that the elements of this $coll starting at this index
+   *           match the elements of sequence `that`, or `-1` of no such subsequence exists. 
+   */
+  def indexOfSlice[B >: A](that: Seq[B]): Int = indexOfSlice(that, 0)
+  
+  /** Finds first index after or at a start index where this $coll contains a given sequence as a slice.
+   *  $mayNotTerminateInf
+   *  @param  that    the sequence to test
+   *  @param  from    the start index  
+   *  @return  the first index `>= from` such that the elements of this $coll starting at this index
+   *           match the elements of sequence `that`, or `-1` of no such subsequence exists. 
+   */
+  def indexOfSlice[B >: A](that: Seq[B], from: Int): Int = 
+    if (this.hasDefiniteSize && that.hasDefiniteSize)
+      SeqLike.indexOf(thisCollection, 0, length, that, 0, that.length, from)
+    else {
+      var i = from
+      var s: Seq[A] = thisCollection drop i
+      while (!s.isEmpty) {
+        if (s startsWith that)
+          return i
+        
+        i += 1
+        s = s.tail
+      }
+      -1
+    }
+      
+  /** Finds last index where this $coll contains a given sequence as a slice.
+   *  $willNotTerminateInf
+   *  @param  that    the sequence to test
+   *  @return  the last index such that the elements of this $coll starting a this index
+   *           match the elements of sequence `that`, or `-1` of no such subsequence exists. 
+   */
+  def lastIndexOfSlice[B >: A](that: Seq[B]): Int = lastIndexOfSlice(that, length)
+
+  /** Finds last index before or at a given end index where this $coll contains a given sequence as a slice.
+   *  @param  that    the sequence to test
+   *  @param  end     the end index
+   *  @return  the last index `<= end` such that the elements of this $coll starting at this index
+   *           match the elements of sequence `that`, or `-1` of no such subsequence exists. 
+   */
+  def lastIndexOfSlice[B >: A](that: Seq[B], end: Int): Int = 
+    SeqLike.lastIndexOf(thisCollection, 0, length, that, 0, that.length, end)
+
+  /** Tests whether this $coll contains a given sequence as a slice.
+   *  $mayNotTerminateInf
+   *  @param  that    the sequence to test
+   *  @return  `true` if this $coll contains a slice with the same elements
+   *           as `that`, otherwise `false`.
+   */
+  def containsSlice[B](that: Seq[B]): Boolean = indexOfSlice(that) != -1 
+
+  /** Tests whether this $coll contains a given value as an element.
+   *  $mayNotTerminateInf
+   *
+   *  @param elem  the element to test.
+   *  @return     `true` if this $coll has an element that is
+   *               is equal (wrt `==`) to `elem`, `false` otherwise.
+   */
+  def contains(elem: Any): Boolean = exists (_ == elem)
+
+  /** Produces a new sequence which contains all elements of this $coll and also all elements of
+   *  a given sequence. `xs union ys`  is equivalent to `xs ++ ys`.
+   *  $willNotTerminateInf
+   *
+   *  Another way to express this
+   *  is that `xs union ys` computes the order-presevring multi-set union of `xs` and `ys`.
+   *  `union` is hence a counter-part of `diff` and `intersect` which also work on multi-sets.
+   *
+   *  $willNotTerminateInf
+   *
+   *  @param that   the sequence to add.
+   *  @tparam B     the element type of the returned $coll.
+   *  @tparam That  $thatinfo
+   *  @param bf     $bfinfo
+   *  @return       a new collection of type `That` which contains all elements of this $coll
+   *                followed by all elements of `that`.
+   *  @usecase def union(that: Seq[A]): $Coll[A]
+   *  @return       a new $coll which contains all elements of this $coll
+   *                followed by all elements of `that`.
+   */
+  def union[B >: A, That](that: Seq[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = 
+    this ++ that
+
+  /** Computes the multiset difference between this $coll and another sequence.
+   *  $willNotTerminateInf
+   *
+   *  @param that   the sequence of elements to remove 
+   *  @tparam B     the element type of the returned $coll.
+   *  @tparam That  $thatinfo
+   *  @param bf     $bfinfo
+   *  @return       a new collection of type `That` which contains all elements of this $coll
+   *                except some of occurrences of elements that also appear in `that`.
+   *                If an element value `x` appears
+   *                ''n'' times in `that`, then the first ''n'' occurrences of `x` will not form
+   *                part of the result, but any following occurrences will.
+   *  @usecase def diff(that: Seq[A]): $Coll[A]
+   *  @return       a new $coll which contains all elements of this $coll
+   *                except some of occurrences of elements that also appear in `that`.
+   *                If an element value `x` appears
+   *                ''n'' times in `that`, then the first ''n'' occurrences of `x` will not form
+   *                part of the result, but any following occurrences will.
+   */
+  def diff[B >: A](that: Seq[B]): Repr = {
+    val occ = occCounts(that)
+    val b = newBuilder
+    for (x <- this)
+      if (occ(x) == 0) b += x
+      else occ(x) -= 1 
+    b.result
+  }
+
+  /** Computes the multiset intersection between this $coll and another sequence.
+   *  $mayNotTerminateInf
+   *
+   *  @param that   the sequence of elements to intersect with.
+   *  @tparam B     the element type of the returned $coll.
+   *  @tparam That  $thatinfo
+   *  @param bf     $bfinfo
+   *  @return       a new collection of type `That` which contains all elements of this $coll
+   *                which also appear in `that`.
+   *                If an element value `x` appears
+   *                ''n'' times in `that`, then the first ''n'' occurrences of `x` will be retained
+   *                in the result, but any following occurrences will be omitted.
+   *  @usecase def intersect(that: Seq[A]): $Coll[A]
+   *  @return       a new $coll which contains all elements of this $coll
+   *                which also appear in `that`.
+   *                If an element value `x` appears
+   *                ''n'' times in `that`, then the first ''n'' occurrences of `x` will be retained
+   *                in the result, but any following occurrences will be omitted.
+   */
+  def intersect[B >: A](that: Seq[B]): Repr = {
+    val occ = occCounts(that)
+    val b = newBuilder
+    for (x <- this)
+      if (occ(x) > 0) {
+        b += x
+        occ(x) -= 1
+      }
+    b.result
+  }
+
+  private def occCounts[B](seq: Seq[B]): mutable.Map[B, Int] = {
+    val occ = new mutable.HashMap[B, Int] { override def default(k: B) = 0 }
+    for (y <- seq) occ(y) += 1
+    occ
+  }
+
+  /** Builds a new $coll from this $coll without any duplicate elements.
+   *  $willNotTerminateInf
+   *
+   *  @return  A new $coll which contains the first occurrence of every element of this $coll.
+   */
+  def distinct: Repr = {
+    val b = newBuilder
+    var seen = Set[A]() //TR: should use mutable.HashSet?
+    for (x <- this) {
+      if (!(seen contains x)) {
+        b += x
+        seen = (seen + x)
+      }
+    }
+    b.result
+  }
+
+  /** Produces a new $coll where a slice of elements in this $coll is replaced by another sequence.
+   *
+   *  @param  from     the index of the first replaced element
+   *  @param  patch    the replacement sequence
+   *  @param  replaced the number of elements to drop in the original $coll
+   *  @tparam B        the element type of the returned $coll.
+   *  @tparam That     $thatinfo
+   *  @param bf        $bfinfo
+   *  @return          a new $coll consisting of all elements of this $coll 
+   *                   except that `replaced` elements starting from `from` are replaced
+   *                   by `patch`.
+   *  @usecase def patch(from: Int, that: Seq[A], replaced: Int): $Coll[A]
+   *  @return          a new $coll consisting of all elements of this $coll 
+   *                   except that `replaced` elements starting from `from` are replaced
+   *                   by `patch`.
+   */
+  def patch[B >: A, That](from: Int, patch: Seq[B], replaced: Int)(implicit bf: CanBuildFrom[Repr, B, That]): That = {
+    val b = bf(repr)
+    val (prefix, rest) = this.splitAt(from)
+    b ++= toCollection(prefix)
+    b ++= patch
+    b ++= toCollection(rest).view drop replaced
+    b.result
+  }
+
+  /** A copy of this $coll with one single replaced element.
+   *  @param  index  the position of the replacement
+   *  @param  elem   the replacing element
+   *  @tparam B        the element type of the returned $coll.
+   *  @tparam That     $thatinfo
+   *  @param bf        $bfinfo
+   *  @return a new $coll` which is a copy of this $coll with the element at position `index` replaced by `elem`.
+   *  @usecase def updated(index: Int, elem: A): $Coll[A]
+   *  @return a copy of this $coll with the element at position `index` replaced by `elem`.
+   */
+  def updated[B >: A, That](index: Int, elem: B)(implicit bf: CanBuildFrom[Repr, B, That]): That = {
+    val b = bf(repr)
+    val (prefix, rest) = this.splitAt(index)
+    b ++= toCollection(prefix)
+    b += elem
+    b ++= toCollection(rest).view.tail
+    b.result
+  }
+
+  /** Prepends an element to this $coll
+   *  @param  elem   the prepended element
+   *  @tparam B      the element type of the returned $coll.
+   *  @tparam That   $thatinfo
+   *  @param bf      $bfinfo
+   *  @return a new collection of type `That` consisting of `elem` followed
+   *          by all elements of this $coll.
+   *  @usecase def +:(elem: A): $Coll[A]
+   *  @return a new $coll consisting of `elem` followed
+   *          by all elements of this $coll.
+   */
+  def +:[B >: A, That](elem: B)(implicit bf: CanBuildFrom[Repr, B, That]): That = {
+    val b = bf(repr)
+    b += elem
+    b ++= thisCollection
+    b.result
+  }
+
+  /** Appends an element to this $coll
+   *  $willNotTerminateInf
+   *  @param  elem   the appended element
+   *  @tparam B      the element type of the returned $coll.
+   *  @tparam That   $thatinfo
+   *  @param bf      $bfinfo
+   *  @return a new collection of type `That` consisting of
+   *          all elements of this $coll followed by `elem`.
+   *  @usecase def :+(elem: A): $Coll[A]
+   *  @return a new $coll consisting of
+   *          all elements of this $coll followed by `elem`.
+   */
+  def :+[B >: A, That](elem: B)(implicit bf: CanBuildFrom[Repr, B, That]): That = {
+    val b = bf(repr)
+    b ++= thisCollection
+    b += elem
+    b.result
+  }
+
+  /** Appends an element value to this $coll until a given target length is reached.
+   *  @param   len   the target length
+   *  @param   elem  the padding value 
+   *  @tparam B      the element type of the returned $coll.
+   *  @tparam That   $thatinfo
+   *  @param bf      $bfinfo
+   *  @return a new collection of type `That` consisting of
+   *          all elements of this $coll followed by the minimal number of occurrences of `elem` so 
+   *          that the resulting collection has a length of at least `len`. 
+   *  @usecase def padTo(len: Int, elem: A): $Coll[A]
+   *  @return a new $coll consisting of
+   *          all elements of this $coll followed by the minimal number of occurrences of `elem` so 
+   *          that the resulting $coll has a length of at least `len`. 
+   */
+  def padTo[B >: A, That](len: Int, elem: B)(implicit bf: CanBuildFrom[Repr, B, That]): That = {
+    val b = bf(repr)
+    b.sizeHint(length max len)
+    var diff = len - length
+    b ++= thisCollection
+    while (diff > 0) {
+      b += elem
+      diff -= 1 
+    }
+    b.result
+  }
+
+  /** Tests whether every element of this $coll relates to the
+   *  corresponding element of another sequence by satisfying a test predicate.
+   *
+   *  @param   that  the other sequence
+   *  @param   p     the test predicate, which relates elements from both sequences
+   *  @tparam  B     the type of the elements of `that`
+   *  @return  `true` if both sequences have the same length and
+   *                  `p(x, y)` is `true` for all corresponding elements `x` of this $coll
+   *                  and `y` of `that`, otherwise `false`.
+   */
+  def corresponds[B](that: Seq[B])(p: (A,B) => Boolean): Boolean = {
+    val i = this.iterator
+    val j = that.iterator
+    while (i.hasNext && j.hasNext)
+      if (!p(i.next, j.next))
+        return false
+    
+    !i.hasNext && !j.hasNext
+  }
+
+  /** Sorts this $coll according to a comparison function.
+   *  $willNotTerminateInf
+   * 
+   *  The sort is stable. That is, elements that are equal wrt `lt` appear in the
+   *  same order in the sorted sequence as in the original.
+   *
+   *  @param  lt  the comparison function which tests whether
+   *              its first argument precedes its second argument in
+   *              the desired ordering.
+   *  @return     a $coll consisting of the elements of this $coll
+   *              sorted according to the comparison function `lt`.
+   *  @example {{{
+   *    List("Steve", "Tom", "John", "Bob").sortWith(_.compareTo(_) < 0) = 
+   *    List("Bob", "John", "Steve", "Tom")
+   *  }}}
+   */
+  def sortWith(lt: (A, A) => Boolean): Repr = sorted(Ordering fromLessThan lt)
+  
+  /** Sorts this $Coll according to the Ordering which results from transforming
+   *  an implicitly given Ordering with a transformation function.
+   *  @see scala.math.Ordering
+   *  $willNotTerminateInf
+   *  @param   f the transformation function mapping elements
+   *           to some other domain `B`.
+   *  @param   ord the ordering assumed on domain `B`.
+   *  @tparam  B the target type of the transformation `f`, and the type where
+   *           the ordering `ord` is defined.
+   *  @return  a $coll consisting of the elements of this $coll
+   *           sorted according to the ordering where `x < y` if
+   *           `ord.lt(f(x), f(y))`.
+   *
+   *  @example {{{
+   *    val words = "The quick brown fox jumped over the lazy dog".split(' ')
+   *    // this works because scala.Ordering will implicitly provide an Ordering[Tuple2[Int, Char]]
+   *    words.sortBy(x => (x.length, x.head))
+   *    res0: Array[String] = Array(The, dog, fox, the, lazy, over, brown, quick, jumped)
+   *  }}}
+   */  
+  def sortBy[B](f: A => B)(implicit ord: Ordering[B]): Repr = sorted(ord on f)
+
+  /** Sorts this $coll according to an Ordering.
+   * 
+   *  The sort is stable. That is, elements that are equal wrt `lt` appear in the
+   *  same order in the sorted sequence as in the original.
+   *
+   *  @see scala.math.Ordering
+   * 
+   *  @param  ord the ordering to be used to compare elements.
+   *  @return     a $coll consisting of the elements of this $coll
+   *              sorted according to the ordering `ord`.
+   */
+  def sorted[B >: A](implicit ord: Ordering[B]): Repr = {
+    val arr = new ArraySeq[A](this.length)
+    var i = 0
+    for (x <- this) {
+      arr(i) = x
+      i += 1
+    }
+    java.util.Arrays.sort(arr.array, ord.asInstanceOf[Ordering[Object]])
+    val b = newBuilder
+    b.sizeHint(this)
+    for (x <- arr) b += x
+    b.result
+  }
+
+  /** Converts this $coll to a sequence.
+   *  $willNotTerminateInf
+   *
+   *  Overridden for efficiency.
+   */
+  override def toSeq: Seq[A] = thisCollection
+
+  /** Produces the range of all indices of this sequence.
+   *
+   *  @return  a `Range` value from `0` to one less than the length of this $coll.
+   */
+  def indices: Range = 0 until length
+
+  override def view = new SeqView[A, Repr] {
+    protected lazy val underlying = self.repr
+    override def iterator = self.iterator
+    override def length = self.length
+    override def apply(idx: Int) = self.apply(idx)
+  }
+
+  override def view(from: Int, until: Int) = view.slice(from, until)
+
+  /** Hashcodes for $Coll produce a value from the hashcodes of all the
+   *  elements of the $coll.
+   */
+  override def hashCode() = (Seq.hashSeed /: this)(_ * 41 + _.##)
+
+  override def equals(that: Any): Boolean = that match {
+    case that: Seq[_] => (that canEqual this) && (this sameElements that)
+    case _            => false
+  }
+
+  /* Need to override string, so that it's not the Function1's string that gets mixed in.
+   */
+  override def toString = super[IterableLike].toString
+
+  /** Returns index of the last element satisfying a predicate, or -1.
+   */
+  @deprecated("use `lastIndexWhere` instead")
+  def findLastIndexOf(p: A => Boolean): Int = lastIndexWhere(p)
+
+  /** Tests whether every element of this $coll relates to the
+   *  corresponding element of another sequence by satisfying a test predicate.
+   *
+   *  @param   that  the other sequence
+   *  @param   p     the test predicate, which relates elements from both sequences
+   *  @tparam  B     the type of the elements of `that`
+   *  @return  `true` if both sequences have the same length and
+   *                  `p(x, y)` is `true` for all corresponding elements `x` of this $coll
+   *                  and `y` of `that`, otherwise `false`.
+   */
+  @deprecated("use `corresponds` instead")
+  def equalsWith[B](that: Seq[B])(f: (A,B) => Boolean): Boolean = corresponds(that)(f)
+
+ /** 
+   * returns a projection that can be used to call non-strict <code>filter</code>,
+   * <code>map</code>, and <code>flatMap</code> methods that build projections
+   * of the collection.
+   */
+  @deprecated("use `view' instead")
+  override def projection = view
+}
+
diff --git a/src/library/scala/collection/SeqProxy.scala b/src/library/scala/collection/SeqProxy.scala
new file mode 100644
index 0000000..605994c
--- /dev/null
+++ b/src/library/scala/collection/SeqProxy.scala
@@ -0,0 +1,20 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+
+/** This trait implements a proxy for sequence objects. It forwards
+ *  all calls to a different sequence object.
+ *
+ *  @author  Martin Odersky
+ *  @version 2.8
+ *  @since   2.8
+ */
+trait SeqProxy[+A] extends Seq[A] with SeqProxyLike[A, Seq[A]] 
diff --git a/src/library/scala/collection/SeqProxyLike.scala b/src/library/scala/collection/SeqProxyLike.scala
new file mode 100644
index 0000000..18ff553
--- /dev/null
+++ b/src/library/scala/collection/SeqProxyLike.scala
@@ -0,0 +1,73 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+
+import generic._
+
+// Methods could be printed by  cat SeqLike.scala | egrep '^  (override )?def'
+
+
+/** This trait implements a proxy for sequences. It forwards
+ *  all calls to a different sequence.
+ *
+ *  @author  Martin Odersky
+ *  @version 2.8
+ *  @since   2.8
+ */
+trait SeqProxyLike[+A, +Repr <: SeqLike[A, Repr] with Seq[A]] extends SeqLike[A, Repr] with IterableProxyLike[A, Repr] { 
+  override def size = self.size
+  override def toSeq: Seq[A] = self.toSeq
+  override def length: Int = self.length
+  override def apply(idx: Int): A = self.apply(idx)
+  override def lengthCompare(len: Int): Int = self.lengthCompare(len)
+  override def isDefinedAt(x: Int): Boolean = self.isDefinedAt(x)
+  override def segmentLength(p: A => Boolean, from: Int): Int = self.segmentLength(p, from)
+  override def prefixLength(p: A => Boolean) = self.prefixLength(p)
+  override def indexWhere(p: A => Boolean): Int = self.indexWhere(p)
+  override def indexWhere(p: A => Boolean, from: Int): Int = self.indexWhere(p, from)
+  override def findIndexOf(p: A => Boolean): Int = self.indexWhere(p)
+  override def indexOf[B >: A](elem: B): Int = self.indexOf(elem)
+  override def indexOf[B >: A](elem: B, from: Int): Int = self.indexOf(elem, from)
+  override def lastIndexOf[B >: A](elem: B): Int = self.lastIndexOf(elem)
+  override def lastIndexOf[B >: A](elem: B, end: Int): Int = self.lastIndexWhere(elem ==, end)
+  override def lastIndexWhere(p: A => Boolean): Int = self.lastIndexWhere(p, length - 1)
+  override def lastIndexWhere(p: A => Boolean, end: Int): Int = self.lastIndexWhere(p)
+  override def reverse: Repr = self.reverse
+  override def reverseMap[B, That](f: A => B)(implicit bf: CanBuildFrom[Repr, B, That]): That = self.reverseMap(f)(bf)
+  override def reverseIterator: Iterator[A] = self.reverseIterator
+  override def startsWith[B](that: Seq[B], offset: Int): Boolean = self.startsWith(that, offset)
+  override def startsWith[B](that: Seq[B]): Boolean = self.startsWith(that)
+  override def endsWith[B](that: Seq[B]): Boolean = self.endsWith(that)
+  override def indexOfSlice[B >: A](that: Seq[B]): Int = self.indexOfSlice(that)
+  override def indexOfSlice[B >: A](that: Seq[B], from: Int): Int = self.indexOfSlice(that)
+  override def lastIndexOfSlice[B >: A](that: Seq[B]): Int = self.lastIndexOfSlice(that)
+  override def lastIndexOfSlice[B >: A](that: Seq[B], end: Int): Int = self.lastIndexOfSlice(that, end)
+  override def containsSlice[B](that: Seq[B]): Boolean = self.indexOfSlice(that) != -1
+  override def contains(elem: Any): Boolean = self.contains(elem)
+  override def union[B >: A, That](that: Seq[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = self.union(that)(bf)
+  override def diff[B >: A](that: Seq[B]): Repr = self.diff(that)
+  override def intersect[B >: A](that: Seq[B]): Repr = self.intersect(that)
+  override def distinct: Repr = self.distinct
+  override def patch[B >: A, That](from: Int, patch: Seq[B], replaced: Int)(implicit bf: CanBuildFrom[Repr, B, That]): That = self.patch(from, patch, replaced)(bf)
+  override def updated[B >: A, That](index: Int, elem: B)(implicit bf: CanBuildFrom[Repr, B, That]): That = self.updated(index, elem)(bf)
+  override def +:[B >: A, That](elem: B)(implicit bf: CanBuildFrom[Repr, B, That]): That = self.+:(elem)(bf)
+  override def :+[B >: A, That](elem: B)(implicit bf: CanBuildFrom[Repr, B, That]): That = self.:+(elem)(bf)
+  override def padTo[B >: A, That](len: Int, elem: B)(implicit bf: CanBuildFrom[Repr, B, That]): That = self.padTo(len, elem)(bf)
+  override def corresponds[B](that: Seq[B])(p: (A,B) => Boolean): Boolean = self.corresponds(that)(p)
+  override def sortWith(lt: (A, A) => Boolean): Repr = self.sortWith(lt)
+  override def sortBy[B](f: A => B)(implicit ord: Ordering[B]): Repr = self.sortBy(f)(ord)
+  override def sorted[B >: A](implicit ord: Ordering[B]): Repr = self.sorted(ord)
+  override def indices: Range = self.indices
+  override def view = self.view
+  override def view(from: Int, until: Int) = self.view(from, until)
+}
+
+
diff --git a/src/library/scala/collection/SeqView.scala b/src/library/scala/collection/SeqView.scala
new file mode 100644
index 0000000..a1901e5
--- /dev/null
+++ b/src/library/scala/collection/SeqView.scala
@@ -0,0 +1,32 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+
+import generic._
+import TraversableView.NoBuilder
+
+/** A base trait for non-strict views of sequences.
+ *  $seqViewInfo
+ */
+trait SeqView[+A, +Coll] extends SeqViewLike[A, Coll, SeqView[A, Coll]] 
+
+/** An object containing the necessary implicit definitions to make
+ *  `SeqView`s work. Its definitions are generally not accessed directly by clients.
+ */
+object SeqView {
+  type Coll = TraversableView[_, C] forSome {type C <: Traversable[_]}
+  implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, SeqView[A, Seq[_]]] = 
+    new CanBuildFrom[Coll, A, SeqView[A, Seq[_]]] { 
+      def apply(from: Coll) = new NoBuilder 
+      def apply() = new NoBuilder 
+    }
+}
+
diff --git a/src/library/scala/collection/SeqViewLike.scala b/src/library/scala/collection/SeqViewLike.scala
new file mode 100644
index 0000000..9745a21
--- /dev/null
+++ b/src/library/scala/collection/SeqViewLike.scala
@@ -0,0 +1,228 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+
+import generic._
+import Seq.fill
+import TraversableView.NoBuilder
+
+/** A template trait for non-strict views of sequences.
+ *  $seqViewInfo
+ * 
+ *  @define seqViewInfo
+ *  $viewInfo
+ *  All views for sequences are defined by re-interpreting the `length` and `apply` methods.
+ * 
+ *  @author Martin Odersky
+ *  @version 2.8
+ *  @since   2.8
+ *  @tparam A    the element type of the view
+ *  @tparam Coll the type of the underlying collection containing the elements.
+ *  @tparam This the type of the view itself
+ */
+trait SeqViewLike[+A, 
+                  +Coll,
+                  +This <: SeqView[A, Coll] with SeqViewLike[A, Coll, This]] 
+  extends Seq[A] with SeqLike[A, This] with IterableView[A, Coll] with IterableViewLike[A, Coll, This] 
+{ self =>
+
+  trait Transformed[+B] extends SeqView[B, Coll] with super.Transformed[B] {
+    override def length: Int
+    override def apply(idx: Int): B
+  }
+
+  trait Forced[B] extends Transformed[B] with super.Forced[B] {
+    override def length = forced.length
+    override def apply(idx: Int) = forced.apply(idx)
+  }
+
+  trait Sliced extends Transformed[A] with super.Sliced {
+    override def length = ((until min self.length) - from) max 0
+    override def apply(idx: Int): A =
+      if (idx + from < until) self.apply(idx + from)
+      else throw new IndexOutOfBoundsException(idx.toString)
+  }
+
+  trait Mapped[B] extends Transformed[B] with super.Mapped[B] {
+    override def length = self.length
+    override def apply(idx: Int): B = mapping(self apply idx)
+  }
+
+  trait FlatMapped[B] extends Transformed[B] with super.FlatMapped[B] {
+    protected[this] lazy val index = {
+      val index = new Array[Int](self.length + 1)
+      index(0) = 0
+      for (i <- 0 until self.length) 
+        index(i + 1) = index(i) + mapping(self(i)).size
+      index
+    }      
+    protected[this] def findRow(idx: Int, lo: Int, hi: Int): Int = {
+      val mid = (lo + hi) / 2
+      if (idx < index(mid)) findRow(idx, lo, mid - 1)
+      else if (idx >= index(mid + 1)) findRow(idx, mid + 1, hi)
+      else mid
+    }
+    override def length = index(self.length)
+    override def apply(idx: Int) = {
+      val row = findRow(idx, 0, self.length - 1)
+      mapping(self(row)).toSeq(idx - index(row))
+    }
+  }
+    
+  trait Appended[B >: A] extends Transformed[B] with super.Appended[B] {
+    protected[this] lazy val restSeq = rest.toSeq
+    override def length = self.length + restSeq.length
+    override def apply(idx: Int) = 
+      if (idx < self.length) self(idx) else restSeq(idx - self.length)
+  }
+
+  trait Filtered extends Transformed[A] with super.Filtered {
+    protected[this] lazy val index = {
+      var len = 0
+      val arr = new Array[Int](self.length)
+      for (i <- 0 until self.length) 
+        if (pred(self(i))) { 
+          arr(len) = i
+          len += 1
+        }
+      arr take len
+    }
+    override def length = index.length
+    override def apply(idx: Int) = self(index(idx))
+  }
+    
+  trait TakenWhile extends Transformed[A] with super.TakenWhile {
+    protected[this] lazy val len = self prefixLength pred
+    override def length = len
+    override def apply(idx: Int) =
+      if (idx < len) self(idx)
+      else throw new IndexOutOfBoundsException(idx.toString)
+  }
+
+  trait DroppedWhile extends Transformed[A] with super.DroppedWhile {
+    protected[this] lazy val start = self prefixLength pred
+    override def length = self.length - start
+    override def apply(idx: Int) =
+      if (idx >= 0) self(idx + start)
+      else throw new IndexOutOfBoundsException(idx.toString)
+  }
+
+  trait Zipped[B] extends Transformed[(A, B)] with super.Zipped[B] {
+    protected[this] lazy val thatSeq = other.toSeq
+    /* Have to be careful here - other may be an infinite sequence. */
+    override def length = if ((thatSeq lengthCompare self.length) <= 0) thatSeq.length else self.length
+    override def apply(idx: Int) = (self.apply(idx), thatSeq.apply(idx))
+  }
+  
+  trait ZippedAll[A1 >: A, B] extends Transformed[(A1, B)] with super.ZippedAll[A1, B] {
+    protected[this] lazy val thatSeq = other.toSeq
+    override def length: Int = self.length max thatSeq.length
+    override def apply(idx: Int) = 
+      (if (idx < self.length) self.apply(idx) else thisElem,
+       if (idx < thatSeq.length) thatSeq.apply(idx) else thatElem)
+  }
+  
+  trait Reversed extends Transformed[A] {
+    override def iterator: Iterator[A] = createReversedIterator
+    override def length: Int = self.length
+    override def apply(idx: Int): A = self.apply(length - 1 - idx)
+    override def stringPrefix = self.stringPrefix+"R"
+    
+    private def createReversedIterator = {
+      var lst = List[A]()
+      for (elem <- self) lst ::= elem
+      lst.iterator
+    }
+  }
+
+  trait Patched[B >: A] extends Transformed[B] {
+    protected[this] val from: Int
+    protected[this] val patch: Seq[B]
+    protected[this] val replaced: Int
+    private lazy val plen = patch.length
+    override def iterator: Iterator[B] = self.iterator patch (from, patch.iterator, replaced)
+    override def length: Int = self.length + plen - replaced
+    override def apply(idx: Int): B = 
+      if (idx < from) self.apply(idx)
+      else if (idx < from + plen) patch.apply(idx - from)
+      else self.apply(idx - plen + replaced)
+    override def stringPrefix = self.stringPrefix+"P"
+  }
+
+  trait Prepended[B >: A] extends Transformed[B] {
+    protected[this] val fst: B
+    override def iterator: Iterator[B] = Iterator.single(fst) ++ self.iterator
+    override def length: Int = 1 + self.length
+    override def apply(idx: Int): B = 
+      if (idx == 0) fst
+      else self.apply(idx - 1)
+    override def stringPrefix = self.stringPrefix+"A"
+  }
+
+  /** Boilerplate method, to override in each subclass
+   *  This method could be eliminated if Scala had virtual classes
+   */
+  protected override def newForced[B](xs: => Seq[B]): Transformed[B] = new Forced[B] { val forced = xs }
+  protected override def newAppended[B >: A](that: Traversable[B]): Transformed[B] = new Appended[B] { val rest = that }
+  protected override def newMapped[B](f: A => B): Transformed[B] = new Mapped[B] { val mapping = f }
+  protected override def newFlatMapped[B](f: A => Traversable[B]): Transformed[B] = new FlatMapped[B] { val mapping = f }
+  protected override def newFiltered(p: A => Boolean): Transformed[A] = new Filtered { val pred = p }
+  protected override def newSliced(_from: Int, _until: Int): Transformed[A] = new Sliced { val from = _from; val until = _until }
+  protected override def newDroppedWhile(p: A => Boolean): Transformed[A] = new DroppedWhile { val pred = p }
+  protected override def newTakenWhile(p: A => Boolean): Transformed[A] = new TakenWhile { val pred = p }
+  protected override def newZipped[B](that: Iterable[B]): Transformed[(A, B)] = new Zipped[B] { val other = that }
+  protected override def newZippedAll[A1 >: A, B](that: Iterable[B], _thisElem: A1, _thatElem: B): Transformed[(A1, B)] = new ZippedAll[A1, B] { val other = that; val thisElem = _thisElem; val thatElem = _thatElem }
+  protected def newReversed: Transformed[A] = new Reversed { }
+  protected def newPatched[B >: A](_from: Int, _patch: Seq[B], _replaced: Int): Transformed[B] = new Patched[B] { val from = _from; val patch = _patch; val replaced = _replaced }
+  protected def newPrepended[B >: A](elem: B): Transformed[B] = new Prepended[B] { protected[this] val fst = elem }
+
+  override def reverse: This = newReversed.asInstanceOf[This]
+
+  override def patch[B >: A, That](from: Int, patch: Seq[B], replaced: Int)(implicit bf: CanBuildFrom[This, B, That]): That = {
+    newPatched(from, patch, replaced).asInstanceOf[That]
+// was:    val b = bf(repr)
+//    if (b.isInstanceOf[NoBuilder[_]]) newPatched(from, patch, replaced).asInstanceOf[That]
+//    else super.patch[B, That](from, patch, replaced)(bf) 
+  }
+
+  override def padTo[B >: A, That](len: Int, elem: B)(implicit bf: CanBuildFrom[This, B, That]): That =
+    patch(length, fill(len - length)(elem), 0)
+    
+  override def reverseMap[B, That](f: A => B)(implicit bf: CanBuildFrom[This, B, That]): That =
+    reverse.map(f)
+
+  override def updated[B >: A, That](index: Int, elem: B)(implicit bf: CanBuildFrom[This, B, That]): That = {
+    require(0 <= index && index < length)
+    patch(index, List(elem), 1)(bf)
+  }
+
+  override def +:[B >: A, That](elem: B)(implicit bf: CanBuildFrom[This, B, That]): That = 
+    newPrepended(elem).asInstanceOf[That]
+    
+  override def :+[B >: A, That](elem: B)(implicit bf: CanBuildFrom[This, B, That]): That = 
+    ++(Iterator.single(elem))(bf)
+
+  override def union[B >: A, That](that: Seq[B])(implicit bf: CanBuildFrom[This, B, That]): That = 
+    newForced(thisSeq union that).asInstanceOf[That]
+
+  override def diff[B >: A](that: Seq[B]): This = 
+    newForced(thisSeq diff that).asInstanceOf[This]
+
+  override def intersect[B >: A](that: Seq[B]): This = 
+    newForced(thisSeq intersect that).asInstanceOf[This]
+
+  override def sorted[B >: A](implicit ord: Ordering[B]): This =
+    newForced(thisSeq sorted ord).asInstanceOf[This]
+
+  override def stringPrefix = "SeqView"
+}
+
+
diff --git a/src/library/scala/collection/Set.scala b/src/library/scala/collection/Set.scala
index 8fdd964..298feb9 100644
--- a/src/library/scala/collection/Set.scala
+++ b/src/library/scala/collection/Set.scala
@@ -1,131 +1,42 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Set.scala 16894 2009-01-13 13:09:41Z cunei $
-
 
 package scala.collection
 
+import generic._
 
-/** <p>
- *    A set is a collection that includes at most one of any object.
- *  </p>
- *  <p>
- *    This trait provides a limited interface, only allowing reading of elements.
- *    There are two extensions of this trait, in packages
- *    <code><a href="mutable$content.html" target="contentFrame">
- *    scala.collection.mutable</a></code>
- *    and <code><a href="immutable$content.html" target="contentFrame">
- *    scala.collection.immutable</a></code>, which provide functionality for
- *    adding and removing objects from the set. The trait in the first package is
- *    for sets that are modified destructively, whereas the trait in
- *    the second package is for immutable sets which create a new set
- *    when something is added or removed to them.
+/** A base trait for all sets, mutable as well as immutable.
  *
- *  @author  Matthias Zenger
- *  @author  Martin Odersky
- *  @version 2.0, 01/01/2007
+ * $setNote
+ * $setNote2
+ * $setTags 
+ * @since 1.0
+ * @author Matthias Zenger
+ * @define setNote2
+ * '''Implementation note:''' If your additions and mutations return the same kind of set as the set
+ *       you are defining, you should inherit from `SetLike` as well.
  */
-trait Set[A] extends (A => Boolean) with Collection[A] {
-
-  /** Returns the number of elements in this set.
-   *
-   *  @return number of set elements.
-   */
-  def size: Int
-
-  /** Checks if this set contains element <code>elem</code>.
-   *
-   *  @param elem the element to check for membership.
-   *  @return     <code>true</code> iff <code>elem</code> is contained in
-   *              this set.
-   */
-  def contains(elem: A): Boolean
-
-  /** This method allows sets to be interpreted as predicates.
-   *  It returns <code>true</code>, iff this set contains element
-   *  <code>elem</code>.
-   *
-   *  @param elem the element to check for membership.
-   *  @return     <code>true</code> iff <code>elem</code> is contained in
-   *              this set.
-   */
-  def apply(elem: A): Boolean = contains(elem)
-
-  /** Checks if this set is empty.
-   *
-   *  @return <code>true</code> iff there is no element in the set.
-   */
-  override def isEmpty: Boolean = size == 0
-
-  /** Checks if this set is a subset of set <code>that</code>.
-   *
-   *  @param that another set.
-   *  @return     <code>true</code> iff the other set is a superset of
-   *              this set.
-   *  todo: rename to isSubsetOf  
-   */
-  def subsetOf(that: Set[A]): Boolean = forall(that.contains)
-  
-  @deprecated def *(that : Set[A]) : Set[A] = this ** that
-  
-  /** Intersect. It computes an intersection with set <code>that</code>.
-   *  It removes all the elements that are not present in <code>that</code>.
-   *
-   *  @param that the set to intersect with
-   */
-  def **(that : Set[A]) : Set[A] = {
-     val min = Math.min(size, that.size)
-     val buf = new Array[A](min)
-     var count = 0
-     val i = elements
-     while (i.hasNext) {
-       val a = i.next
-       if (that.contains(a)) {
-         buf(count) = a
-         count += 1
-       } 
-     }
-     if (count == size) this
-     else if (count == that.size) that
-     else {
-       import scala.collection.mutable.HashSet
-       val ret = new HashSet[A]
-       ret ++= buf.projection.take(count)
-       ret
-     }
-  }
-  /** Compares this set with another object and returns true, iff the
-   *  other object is also a set which contains the same elements as
-   *  this set.
-   *
-   *  @param that the other object
-   *  @note not necessarily run-time type safe.
-   *  @return     <code>true</code> iff this set and the other set
-   *              contain the same elements.
-   */
-  override def equals(that: Any): Boolean = that match {
-    case other: Set[_] =>
-      this.size == other.size && subsetOf(other.asInstanceOf[Set[A]])
-    case _ =>
-      false
-  }
-
-  override def hashCode() =
-    (0 /: this)((hash, e) => hash + e.hashCode())
-
-  override def toArray[B >: A]: Array[B] = {
-    val result = new Array[B](size)
-    copyToArray(result, 0)
-    result
-  }
+trait Set[A] extends (A => Boolean) 
+                with Iterable[A] 
+                with GenericSetTemplate[A, Set]
+                with SetLike[A, Set[A]] {
+  override def companion: GenericCompanion[Set] = Set
+}
 
-  /** Defines the prefix of this object's <code>toString</code> representation.
-   */
-  override protected def stringPrefix : String = "Set"
+/** $factoryInfo
+ *  The current default implementation of a $Coll is one of `EmptySet`, `Set1`, `Set2`, `Set3`, `Set4` in
+ *  class `immutable.Set` for sets of sizes up to 4, and a `immutable.HashSet` for sets of larger sizes.
+ *  @define coll set
+ *  @define Coll Set
+ */
+object Set extends SetFactory[Set] {
+  def newBuilder[A] = immutable.Set.newBuilder[A]
+  override def empty[A]: Set[A] = immutable.Set.empty[A]
+  implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, Set[A]] = setCanBuildFrom[A]
 }
diff --git a/src/library/scala/collection/SetLike.scala b/src/library/scala/collection/SetLike.scala
new file mode 100644
index 0000000..bc40e84
--- /dev/null
+++ b/src/library/scala/collection/SetLike.scala
@@ -0,0 +1,210 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+package scala.collection
+
+import generic._
+import mutable.{Builder, AddingBuilder}
+import PartialFunction._
+
+/** A template trait for sets.
+ *
+ *  $setNote
+ *  $setTags
+ *  @since 2.8
+ *
+ *  @define setNote
+ *
+ *  A set is a collection that contains no duplicate elements.
+ *  
+ *    '''Implementation note:'''
+ *    This trait provides most of the operations of a `Set` independently of its representation.
+ *    It is typically inherited by concrete implementations of sets.
+ *
+ *    To implement a concrete set, you need to provide implementations of the
+ *    following methods:
+ *    {{{
+ *       def contains(key: A): Boolean
+ *       def iterator: Iterator[A]
+ *       def +(elem: A): This
+ *       def -(elem: A): This
+ *    }}}
+ *    If you wish that methods like `take`, `drop`,
+ *    `filter` return the same kind of set, you should also override:
+ *    {{{
+ *       def empty: This
+ *    }}}
+ *    It is also good idea to override methods `foreach` and
+ *    `size` for efficiency.
+ * 
+ * @define setTags
+ *  @tparam A    the type of the elements of the set
+ *  @tparam This the type of the set itself.
+ *
+ *  @author  Martin Odersky
+ *  @version 2.8
+ * 
+ *  @define coll set
+ *  @define Coll Set
+ *  @define willNotTerminateInf
+ *  @define mayNotTerminateInf
+ */
+trait SetLike[A, +This <: SetLike[A, This] with Set[A]] 
+extends IterableLike[A, This] 
+   with Addable[A, This] 
+   with Subtractable[A, This] { 
+self =>
+
+  /** The empty set of the same type as this set
+   * @return  an empty set of type `This`.
+   */
+  def empty: This
+
+  /** A common implementation of `newBuilder` for all sets in terms
+   *  of `empty`. Overridden for mutable sets in
+   *  <a href="mutable/SetLike.html" target="ContentFrame">
+   *  `mutable.SetLike`</a>.
+   */
+  override protected[this] def newBuilder: Builder[A, This] = new AddingBuilder[A, This](empty)
+
+  /** Tests if some element is contained in this set.
+   *
+   *  @param elem the element to test for membership.
+   *  @return     `true` if `elem` is contained in this set, `false` otherwise.
+   */
+  def contains(elem: A): Boolean
+
+  /** Creates a new set with an additional element, unless the element is
+   *  already present.
+   *
+   *  @param elem the element to be added
+   *  @return a new set that contains all elements of this set and that also
+   *          contains `elem`.
+   */
+  def + (elem: A): This
+
+  /** Creates a new set with a given element removed from this set.
+   *
+   *  @param elem the element to be removed
+   *  @return a new set that contains all elements of this set but that does not
+   *          contain `elem`.
+   */
+  def - (elem: A): This
+
+  /** Tests if this set is empty.
+   *
+   *  @return `true` if there is no element in the set, `false` otherwise.
+   */
+  override def isEmpty: Boolean = size == 0
+
+  /** Tests if some element is contained in this set.
+   *
+   *  This method is equivalent to `contains`. It allows sets to be interpreted as predicates.
+   *  @param elem the element to test for membership.
+   *  @return  `true` if `elem` is contained in this set, `false` otherwise.
+   */
+  def apply(elem: A): Boolean = contains(elem)
+
+  /** Computes the intersection between this set and another set.
+   *
+   *  @param   that  the set to intersect with.
+   *  @return  a new set consisting of all elements that are both in this
+   *  set and in the given set `that`. 
+   */
+  def intersect(that: Set[A]): This = filter(that.contains)
+
+  /** Computes the intersection between this set and another set.
+   *
+   *  '''Note:'''  Same as `intersect`.
+   *  @param   that  the set to intersect with.
+   *  @return  a new set consisting of all elements that are both in this
+   *  set and in the given set `that`. 
+   */
+  def &(that: Set[A]): This = intersect(that)
+
+ /**  This method is an alias for `intersect`. 
+   *  It computes an intersection with set `that`.
+   *  It removes all the elements that are not present in `that`.
+   *
+   *  @param that the set to intersect with
+   */
+  @deprecated("use & instead") def ** (that: Set[A]): This = intersect(that)
+  
+  /** Computes the union between of set and another set.
+   *
+   *  @param   that  the set to form the union with.
+   *  @return  a new set consisting of all elements that are in this
+   *  set or in the given set `that`. 
+   */
+  def union(that: Set[A]): This = this.++(that)
+
+  /** Computes the union between this set and another set.
+   *
+   *  '''Note:'''  Same as `union`.
+   *  @param   that  the set to form the union with.
+   *  @return  a new set consisting of all elements that are in this
+   *  set or in the given set `that`. 
+   */
+  def | (that: Set[A]): This = union(that)
+
+  /** Computes the difference of this set and another set.
+   *
+   *  @param that the set of elements to exclude.
+   *  @return     a set containing those elements of this
+   *              set that are not also contained in the given set `that`.
+   */
+  def diff(that: Set[A]): This = --(that)
+
+  /** The difference of this set and another set.
+   *
+   *  '''Note:'''  Same as `diff`.
+   *  @param that the set of elements to exclude.
+   *  @return     a set containing those elements of this
+   *              set that are not also contained in the given set `that`.
+   */
+  def &~(that: Set[A]): This = diff(that)
+
+  /** Tests whether this set is a subset of another set.
+   *
+   *  @param that  the set to test.
+   *  @return     `true` if this set is a subset of `that`, i.e. if
+   *              every element of this set is also an element of `that`.
+   */
+  def subsetOf(that: Set[A]): Boolean = forall(that.contains)
+
+  /** Defines the prefix of this object's `toString` representation.
+   *  @return  a string representation which starts the result of `toString` applied to this set.
+   *           Unless overridden this is simply `"Set"`.
+   */
+  override def stringPrefix: String = "Set"
+
+  override def toString = super[IterableLike].toString
+  override def hashCode() = this map (_.hashCode) sum
+  
+  /** Compares this set with another object for equality.
+   *
+   *  '''Note:''' This operation contains an unchecked cast: if `that`
+   *        is a set, it will assume with an unchecked cast
+   *        that it has the same element type as this set.
+   *        Any subsequent ClassCastException is treated as a `false` result.
+   *  @param that the other object
+   *  @return     `true` if `that` is a set which contains the same elements
+   *              as this set.
+   */
+  override def equals(that: Any): Boolean = that match {
+    case that: Set[_] =>
+      (this eq that) ||
+      (that canEqual this) &&
+      (this.size == that.size) &&
+      (try this subsetOf that.asInstanceOf[Set[A]]
+       catch { case ex: ClassCastException => false })
+    case _ =>
+      false
+  }
+}
diff --git a/src/library/scala/collection/SetProxy.scala b/src/library/scala/collection/SetProxy.scala
index 7c46228..03ea4fb 100644
--- a/src/library/scala/collection/SetProxy.scala
+++ b/src/library/scala/collection/SetProxy.scala
@@ -1,17 +1,15 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: SetProxy.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala.collection
 
-
 /** This is a simple wrapper class for <a href="Set.html"
  *  target="contentFrame"><code>scala.collection.Set</code></a>.
  *  It is most useful for assembling customized set abstractions
@@ -21,10 +19,5 @@ package scala.collection
  *  @author  Martin Odersky
  *  @version 2.0, 01/01/2007
  */
-trait SetProxy[A] extends Set[A] with IterableProxy[A] {
-  def self: Set[A]
-  def size: Int = self.size
-  override def isEmpty: Boolean = self.isEmpty
-  def contains(elem: A): Boolean = self.contains(elem)
-  override def subsetOf(that: Set[A]): Boolean = self.subsetOf(that)
-}
+
+trait SetProxy[A] extends Set[A] with SetProxyLike[A, Set[A]]
diff --git a/src/library/scala/collection/SetProxyLike.scala b/src/library/scala/collection/SetProxyLike.scala
new file mode 100644
index 0000000..cd79a0e
--- /dev/null
+++ b/src/library/scala/collection/SetProxyLike.scala
@@ -0,0 +1,38 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+package scala.collection
+
+import generic._
+
+// Methods could be printed by  cat SetLike.scala | egrep '^  (override )?def'
+
+/** This trait implements a proxy for sets. It forwards
+ *  all calls to a different set.
+ *
+ *  @author  Martin Odersky
+ *  @version 2.8
+ */
+trait SetProxyLike[A, +This <: SetLike[A, This] with Set[A]] extends SetLike[A, This] with IterableProxyLike[A, This]
+{ 
+  def empty: This
+  // def empty: This
+  override def contains(elem: A): Boolean = self.contains(elem)
+  override def + (elem: A) = self.+(elem)
+  override def - (elem: A) = self.-(elem)
+  override def isEmpty: Boolean = self.isEmpty
+  override def apply(elem: A): Boolean = self.apply(elem)
+  override def intersect(that: Set[A]) = self.intersect(that)
+  override def &(that: Set[A]): This = self.&(that)
+  override def union(that: Set[A]): This = self.union(that)
+  override def | (that: Set[A]): This = self.|(that)
+  override def diff(that: Set[A]): This = self.diff(that)
+  override def &~(that: Set[A]): This = self.&~(that)
+  override def subsetOf(that: Set[A]): Boolean = self.subsetOf(that)
+}
diff --git a/src/library/scala/collection/Sorted.scala b/src/library/scala/collection/Sorted.scala
deleted file mode 100644
index 39b9bce..0000000
--- a/src/library/scala/collection/Sorted.scala
+++ /dev/null
@@ -1,70 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: Sorted.scala 16881 2009-01-09 16:28:11Z cunei $
-
-package scala.collection
-
-/** Any collection (including maps) whose keys (or elements) are ordered.
- *
- *  @author Sean McDirmid
- */
-trait Sorted[K,+A] extends Ranged[K,A] {
-
-  /** return as a projection the set of keys in this collection */
-  def keySet: SortedSet[K]
-  
-  /** Creates a ranged projection of this collection. Any mutations in the
-   *  ranged projection will update this collection and vice versa.  Keys
-   *  are garuanteed to be consistent between the collection and its projection.
-   *
-   *  @param from  The lower-bound (inclusive) of the ranged projection.
-   *               <code>None</code> if there is no lower bound.
-   *  @param until The upper-bound (exclusive) of the ranged projection.
-   *               <code>None</code> if there is no upper bound.
-   */
-  override def rangeImpl(from: Option[K], until: Option[K]): Sorted[K,A]
-
-  override def from(from: K) = rangeImpl(Some(from), None)
-
-  override def until(until: K) = rangeImpl(None, Some(until))
-
-  override def range(from: K, until: K) = rangeImpl(Some(from),Some(until))
-  
-  /** Create a range projection of this collection with no lower-bound.
-   *  @param to The upper-bound (inclusive) of the ranged projection.
-   */
-  def to(to: K): Sorted[K,A] = {
-    // tough!
-    val i = keySet.from(to).elements;
-    if (!i.hasNext) return this;
-    val next = i.next;
-    if (next == to) {
-      if (!i.hasNext) return this;
-      else return until(i.next);
-    } else return until(next);
-  }
-
-  protected def hasAll(j: Iterator[K]): Boolean = {
-    val i = keySet.elements;
-    if (!i.hasNext) return !j.hasNext;
-    var in = i.next;
-    while (j.hasNext) {
-      val jn = j.next;
-      while ({
-        val n = compare(jn, in);
-        if (n == 0) false;
-        else if (n < 0) return false;
-        else if (!i.hasNext) return false;
-        else true;
-      }) in = i.next;
-    }
-    true
-  }      
-
-}
diff --git a/src/library/scala/collection/SortedMap.scala b/src/library/scala/collection/SortedMap.scala
index 465aa5e..4e3236e 100644
--- a/src/library/scala/collection/SortedMap.scala
+++ b/src/library/scala/collection/SortedMap.scala
@@ -1,44 +1,39 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
+**    / __/ __// _ | / /  / _ |    (c) 2006-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: SortedMap.scala 16894 2009-01-13 13:09:41Z cunei $
+package scala.collection
 
-package scala.collection;
+import generic._
+import mutable.Builder
 
 /** A map whose keys are sorted.
  *
  *  @author Sean McDirmid
+ *  @author Martin Odersky
+ *  @version 2.8
+ *  @since   2.4
  */
-trait SortedMap[K,+E] extends Map[K,E] with Sorted[K,Tuple2[K,E]] {
-  override def firstKey : K = elements.next._1;
-  override def lastKey : K = {
-    val i = elements;
-    var last : K = i.next._1;
-    while (i.hasNext) last = i.next._1;
-    last;
-  }
-  
-  // XXX: implement default version
-  override def rangeImpl(from : Option[K], until : Option[K]) : SortedMap[K,E];
-  override def from(from: K) = rangeImpl(Some(from), None);
-  override def until(until: K) = rangeImpl(None, Some(until));
-  override def range(from: K, until: K) = rangeImpl(Some(from),Some(until));
-  
-  protected class DefaultKeySet extends SortedSet[K] {
-    def size = SortedMap.this.size
-    def contains(key : K) = SortedMap.this.contains(key)
-    def elements = SortedMap.this.elements.map(_._1)
-    def compare(k0 : K, k1 : K) = SortedMap.this.compare(k0, k1);
-    override def rangeImpl(from : Option[K], until : Option[K]) : SortedSet[K] = {
-      val map = SortedMap.this.rangeImpl(from,until);
-      new map.DefaultKeySet;
-    }
-  }
-  // XXX: implement default version
-  override def keySet : SortedSet[K] = new DefaultKeySet;
+trait SortedMap[A, +B] extends Map[A, B] with SortedMapLike[A, B, SortedMap[A, B]] {
+  /** Needs to be overridden in subclasses. */
+  override def empty: SortedMap[A, B] = SortedMap.empty[A, B]
+
+  override protected[this] def newBuilder: Builder[(A, B), SortedMap[A, B]] = 
+    immutable.SortedMap.newBuilder[A, B]
+}
+
+/**
+ * @since 2.8
+ */
+object SortedMap extends SortedMapFactory[SortedMap] {
+  def empty[A, B](implicit ord: Ordering[A]): immutable.SortedMap[A, B] = immutable.SortedMap.empty[A, B](ord)
+
+  implicit def canBuildFrom[A, B](implicit ord: Ordering[A]): CanBuildFrom[Coll, (A, B), SortedMap[A, B]] = new SortedMapCanBuildFrom[A, B]
 }
+
+
+
diff --git a/src/library/scala/collection/SortedMapLike.scala b/src/library/scala/collection/SortedMapLike.scala
new file mode 100644
index 0000000..0d85c1c
--- /dev/null
+++ b/src/library/scala/collection/SortedMapLike.scala
@@ -0,0 +1,75 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2006-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+
+import generic._
+
+/** A template for maps whose keys are sorted.
+ *  To create a concrete sorted map, you need to implement the rangeImpl method,
+ *  in addition to those of `MapLike`.
+ *
+ *  @author Sean McDirmid
+ *  @author Martin Odersky
+ *  @version 2.8
+ *  @since   2.8
+ */
+trait SortedMapLike[A, +B, +This <: SortedMapLike[A, B, This] with SortedMap[A, B]] extends Sorted[A, This] with MapLike[A, B, This] { 
+self =>
+
+  def firstKey : A = head._1
+  def lastKey : A = last._1
+
+  implicit def ordering: Ordering[A]
+
+  // XXX: implement default version
+  def rangeImpl(from : Option[A], until : Option[A]) : This
+
+  override def keySet : SortedSet[A] = new DefaultKeySortedSet
+
+  protected class DefaultKeySortedSet extends super.DefaultKeySet with SortedSet[A] {
+    implicit def ordering = self.ordering
+    override def + (elem: A): SortedSet[A] = (SortedSet[A]() ++ this + elem)
+    override def - (elem: A): SortedSet[A] = (SortedSet[A]() ++ this - elem)
+    override def rangeImpl(from : Option[A], until : Option[A]) : SortedSet[A] = {
+      val map = self.rangeImpl(from, until)
+      new map.DefaultKeySortedSet
+    }
+  }
+
+  /** Add a key/value pair to this map. 
+   *  @param    key the key
+   *  @param    value the value
+   *  @return   A new map with the new binding added to this map
+   */
+  override def updated[B1 >: B](key: A, value: B1): SortedMap[A, B1] = this+((key, value))
+
+  /** Add a key/value pair to this map. 
+   *  @param    kv the key/value pair
+   *  @return   A new map with the new binding added to this map
+   */
+  def + [B1 >: B] (kv: (A, B1)): SortedMap[A, B1]
+
+  // todo: Add generic +,-, and so on.
+
+  /** Adds two or more elements to this collection and returns
+   *  either the collection itself (if it is mutable), or a new collection
+   *  with the added elements.
+   *
+   *  @param elem1 the first element to add.
+   *  @param elem2 the second element to add.
+   *  @param elems the remaining elements to add.
+   */
+  override def + [B1 >: B] (elem1: (A, B1), elem2: (A, B1), elems: (A, B1) *): SortedMap[A, B1] = {
+    var m = this + elem1 + elem2;
+    for (e <- elems) m = m + e
+    m
+  }
+}
diff --git a/src/library/scala/collection/SortedSet.scala b/src/library/scala/collection/SortedSet.scala
index 6c6ee21..2d59d12 100644
--- a/src/library/scala/collection/SortedSet.scala
+++ b/src/library/scala/collection/SortedSet.scala
@@ -1,48 +1,34 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2006-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: SortedSet.scala 16894 2009-01-13 13:09:41Z cunei $
 
 package scala.collection
+import generic._
 
-/** Analogous to a Java sorted set.
+/** A sorted set.
  *
  *  @author Sean McDirmid
+ *  @author Martin Odersky
+ *  @version 2.8
+ *  @since   2.4
  */
-trait SortedSet[A] extends Set[A] with Sorted[A, A] {
-
-  override def keySet = this
-
-  override def firstKey: A = {
-    val i = elements
-    if (i.hasNext) i.next
-    else throw new NoSuchElementException
-  }
-
-  override def lastKey: A = {
-    var last: A = null.asInstanceOf[A]
-    val i = elements
-    while (i.hasNext) last = i.next;
-    if (last == null) throw new NoSuchElementException
-    else last
-  }
-
-  override def rangeImpl(from: Option[A], until: Option[A]): SortedSet[A]
-
-  override def from(from: A) = rangeImpl(Some(from), None)
+trait SortedSet[A] extends Set[A] with SortedSetLike[A, SortedSet[A]] {
+  /** Needs to be overridden in subclasses. */
+  override def empty: SortedSet[A] = SortedSet.empty[A]
+}
 
-  override def until(until: A) = rangeImpl(None, Some(until))
+/**
+ * @since 2.8
+ */
+object SortedSet extends SortedSetFactory[SortedSet] {
+  def empty[A](implicit ord: Ordering[A]): immutable.SortedSet[A] = immutable.SortedSet.empty[A](ord)
+  implicit def canBuildFrom[A](implicit ord: Ordering[A]): CanBuildFrom[Coll, A, SortedSet[A]] = new SortedSetCanBuildFrom[A]
+}
 
-  override def range(from: A, until: A) = rangeImpl(Some(from),Some(until))
 
-  override def subsetOf(that: Set[A]): Boolean = that match {
-    case that: SortedSet[_] => that.hasAll(elements)
-    case that => super.subsetOf(that)
-  }
 
-}
diff --git a/src/library/scala/collection/SortedSetLike.scala b/src/library/scala/collection/SortedSetLike.scala
new file mode 100644
index 0000000..4dfeffb
--- /dev/null
+++ b/src/library/scala/collection/SortedSetLike.scala
@@ -0,0 +1,43 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2006-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+package scala.collection
+import generic._
+
+/** A template for sets which are sorted.
+ *
+ *  @author Sean McDirmid
+ *  @author Martin Odersky
+ *  @version 2.8
+ *  @since   2.8
+ */
+trait SortedSetLike[A, +This <: SortedSet[A] with SortedSetLike[A, This]] extends Sorted[A, This] with SetLike[A, This] {
+self =>
+
+  implicit def ordering: Ordering[A]
+
+  override def keySet = repr
+
+  override def firstKey: A = head
+  override def lastKey: A = last
+
+  def rangeImpl(from: Option[A], until: Option[A]): This
+
+  override def from(from: A): This = rangeImpl(Some(from), None)
+  override def until(until: A): This = rangeImpl(None, Some(until))
+  override def range(from: A, until: A): This = rangeImpl(Some(from), Some(until))
+
+  override def subsetOf(that: Set[A]): Boolean = that match {
+    // TODO: It may actually be pretty rare that the guard here ever 
+    // passes. Is this really worth keeping? If it is, we should add
+    // more sensible implementations of == to Ordering. 
+    case that: SortedSet[_] if that.ordering == ordering => that.hasAll(this.iterator)
+    case that => super.subsetOf(that)
+  }
+}
diff --git a/src/library/scala/collection/Traversable.scala b/src/library/scala/collection/Traversable.scala
new file mode 100644
index 0000000..8126905
--- /dev/null
+++ b/src/library/scala/collection/Traversable.scala
@@ -0,0 +1,97 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+
+import generic._
+import mutable.{Builder, Buffer, ArrayBuffer, ListBuffer}
+import scala.util.control.Breaks
+
+/** A trait for traversable collections.
+ *  $traversableInfo
+ */
+trait Traversable[+A] extends TraversableLike[A, Traversable[A]] 
+                         with GenericTraversableTemplate[A, Traversable] {
+  def companion: GenericCompanion[Traversable] = Traversable
+
+  /* The following methods are inherited from TraversableLike
+   * 
+  override def isEmpty: Boolean
+  override def size: Int
+  override def hasDefiniteSize
+  override def ++[B >: A, That](xs: TraversableOnce[B])(implicit bf: CanBuildFrom[Traversable[A], B, That]): That
+  override def map[B, That](f: A => B)(implicit bf: CanBuildFrom[Traversable[A], B, That]): That
+  override def flatMap[B, That](f: A => Traversable[B])(implicit bf: CanBuildFrom[Traversable[A], B, That]): That
+  override def filter(p: A => Boolean): Traversable[A]
+  override def remove(p: A => Boolean): Traversable[A]
+  override def partition(p: A => Boolean): (Traversable[A], Traversable[A])
+  override def groupBy[K](f: A => K): Map[K, Traversable[A]]
+  override def foreach[U](f: A =>  U): Unit
+  override def forall(p: A => Boolean): Boolean
+  override def exists(p: A => Boolean): Boolean
+  override def count(p: A => Boolean): Int
+  override def find(p: A => Boolean): Option[A]
+  override def foldLeft[B](z: B)(op: (B, A) => B): B
+  override def /: [B](z: B)(op: (B, A) => B): B
+  override def foldRight[B](z: B)(op: (A, B) => B): B
+  override def :\ [B](z: B)(op: (A, B) => B): B
+  override def reduceLeft[B >: A](op: (B, A) => B): B
+  override def reduceLeftOption[B >: A](op: (B, A) => B): Option[B]
+  override def reduceRight[B >: A](op: (A, B) => B): B
+  override def reduceRightOption[B >: A](op: (A, B) => B): Option[B]
+  override def head: A
+  override def headOption: Option[A]
+  override def tail: Traversable[A]
+  override def last: A
+  override def lastOption: Option[A]
+  override def init: Traversable[A]
+  override def take(n: Int): Traversable[A]
+  override def drop(n: Int): Traversable[A]
+  override def slice(from: Int, until: Int): Traversable[A]
+  override def takeWhile(p: A => Boolean): Traversable[A]
+  override def dropWhile(p: A => Boolean): Traversable[A]
+  override def span(p: A => Boolean): (Traversable[A], Traversable[A])
+  override def splitAt(n: Int): (Traversable[A], Traversable[A])
+  override def copyToBuffer[B >: A](dest: Buffer[B])
+  override def copyToArray[B >: A](xs: Array[B], start: Int, len: Int)
+  override def copyToArray[B >: A](xs: Array[B], start: Int)
+  override def toArray[B >: A : ClassManifest]: Array[B]
+  override def toList: List[A]
+  override def toIterable: Iterable[A]
+  override def toSeq: Seq[A]
+  override def toStream: Stream[A]
+  override def sortWith(lt : (A,A) => Boolean): Traversable[A]
+  override def mkString(start: String, sep: String, end: String): String
+  override def mkString(sep: String): String
+  override def mkString: String
+  override def addString(b: StringBuilder, start: String, sep: String, end: String): StringBuilder
+  override def addString(b: StringBuilder, sep: String): StringBuilder
+  override def addString(b: StringBuilder): StringBuilder
+  override def toString
+  override def stringPrefix : String
+  override def view
+  override def view(from: Int, until: Int): TraversableView[A, Traversable[A]]
+  */
+}
+
+/** $factoryInfo
+ *  The current default implementation of a $Coll is a `Vector`.
+ */
+object Traversable extends TraversableFactory[Traversable] { self =>
+
+  /** Provides break functionality separate from client code */
+  private[collection] val breaks: Breaks = new Breaks
+  
+  /** $genericCanBuildFromInfo */
+  implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, Traversable[A]] = new GenericCanBuildFrom[A]
+
+  def newBuilder[A]: Builder[A, Traversable[A]] = immutable.Traversable.newBuilder[A]
+}
+
diff --git a/src/library/scala/collection/TraversableLike.scala b/src/library/scala/collection/TraversableLike.scala
new file mode 100644
index 0000000..bf6af3b
--- /dev/null
+++ b/src/library/scala/collection/TraversableLike.scala
@@ -0,0 +1,839 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+import generic._
+
+import scala.reflect.ClassManifest
+import mutable.{Builder, StringBuilder, Buffer, ArrayBuffer, ListBuffer}
+import immutable.{List, Stream, Nil, ::}
+
+/** A template trait for traversable collections of type `Traversable[A]`.
+ *  $traversableInfo
+ *  @define mutability
+ *  @define traversableInfo
+ *  This is a base trait of all kinds of $mutability Scala collections. It implements
+ *  the behavior common to all collections, in terms of a method
+ *  `foreach` with signature:
+ * {{{
+ *     def foreach[U](f: Elem => U): Unit
+ * }}}
+ *  Collection classes mixing in this trait provide a concrete 
+ *  `foreach` method which traverses all the
+ *  elements contained in the collection, applying a given function to each.
+ *  They also need to provide a method `newBuilder`
+ *  which creates a builder for collections of the same kind.
+ *  
+ *  A traversable class might or might not have two properties: strictness
+ *  and orderedness. Neither is represented as a type.
+ *  
+ *  The instances of a strict collection class have all their elements
+ *  computed before they can be used as values. By contrast, instances of
+ *  a non-strict collection class may defer computation of some of their
+ *  elements until after the instance is available as a value.
+ *  A typical example of a non-strict collection class is a
+ *  <a href="../immutable/Stream.html" target="ContentFrame">
+ *  `scala.collection.immutable.Stream`</a>.
+ *  A more general class of examples are `TraversableViews`.
+ *  
+ *  If a collection is an instance of an ordered collection class, traversing
+ *  its elements with `foreach` will always visit elements in the
+ *  same order, even for different runs of the program. If the class is not
+ *  ordered, `foreach` can visit elements in different orders for
+ *  different runs (but it will keep the same order in the same run).'
+ * 
+ *  A typical example of a collection class which is not ordered is a
+ *  `HashMap` of objects. The traversal order for hash maps will
+ *  depend on the hash codes of its elements, and these hash codes might
+ *  differ from one run to the next. By contrast, a `LinkedHashMap`
+ *  is ordered because it's `foreach` method visits elements in the
+ *  order they were inserted into the `HashMap`.
+ *
+ *  @author Martin Odersky
+ *  @version 2.8
+ *  @since   2.8
+ *  @tparam A    the element type of the collection
+ *  @tparam Repr the type of the actual collection containing the elements.
+ *
+ *  @define Coll Traversable
+ *  @define coll traversable collection
+ *  @define thatinfo the class of the returned collection. Where possible, `That` is 
+ *    the same class as the current collection class `Repr`, but this
+ *    depends on the element type `B` being admissible for that class,
+ *    which means that an implicit instance of type `CanBuildFrom[Repr, B, That]`
+ *    is found.
+ *  @define bfinfo an implicit value of class `CanBuildFrom` which determines the
+ *    result class `That` from the current representation type `Repr` and
+ *    and the new element type `B`. 
+ *  @define orderDependent
+ * 
+ *    Note: might return different results for different runs, unless the underlying collection type is ordered.
+ *  @define orderDependentFold
+ * 
+ *    Note: might return different results for different runs, unless the underlying collection type is ordered.
+ *    or the operator is associative and commutative.
+ *  @define mayNotTerminateInf
+ *
+ *    Note: may not terminate for infinite-sized collections.
+ *  @define willNotTerminateInf
+ *
+ *    Note: will not terminate for infinite-sized collections.
+ */
+trait TraversableLike[+A, +Repr] extends HasNewBuilder[A, Repr] 
+                                    with FilterMonadic[A, Repr]
+                                    with TraversableOnce[A] { 
+  self =>
+
+  import Traversable.breaks._
+
+  /** The type implementing this traversable */
+  protected type Self = Repr
+
+  /** The collection of type $coll underlying this `TraversableLike` object.
+   *  By default this is implemented as the `TraversableLike` object itself, but this can be overridden.
+   */
+  def repr: Repr = this.asInstanceOf[Repr]
+
+  /** The underlying collection seen as an instance of `$Coll`.
+   *  By default this is implemented as the current collection object itself,
+   *  but this can be overridden.
+   */
+  protected[this] def thisCollection: Traversable[A] = this.asInstanceOf[Traversable[A]]
+
+  /** A conversion from collections of type `Repr` to `$Coll` objects.
+   *  By default this is implemented as just a cast, but this can be overridden.
+   */
+  protected[this] def toCollection(repr: Repr): Traversable[A] = repr.asInstanceOf[Traversable[A]]
+
+  /** Creates a new builder for this collection type.
+   */
+  protected[this] def newBuilder: Builder[A, Repr]
+
+  /** Applies a function `f` to all elements of this $coll.
+   *  
+   *    Note: this method underlies the implementation of most other bulk operations.
+   *    It's important to implement this method in an efficient way.
+   *  
+   *
+   *  @param  f   the function that is applied for its side-effect to every element.
+   *              The result of function `f` is discarded.
+   *              
+   *  @tparam  U  the type parameter describing the result of function `f`. 
+   *              This result will always be ignored. Typically `U` is `Unit`,
+   *              but this is not necessary.
+   *
+   *  @usecase def foreach(f: A => Unit): Unit
+   */
+  def foreach[U](f: A => U): Unit
+
+  /** Tests whether this $coll is empty.
+   *
+   *  @return    `true` if the $coll contain no elements, `false` otherwise.
+   */
+  def isEmpty: Boolean = {
+    var result = true
+    breakable {
+      for (x <- this) {
+        result = false
+        break
+      }
+    }
+    result
+  }
+  
+  /** Tests whether this $coll can be repeatedly traversed.
+   *  @return   `true`
+   */
+  final def isTraversableAgain = true
+
+  /** Tests whether this $coll is known to have a finite size.
+   *  All strict collections are known to have finite size. For a non-strict collection
+   *  such as `Stream`, the predicate returns `true` if all elements have been computed.
+   *  It returns `false` if the stream is not yet evaluated to the end.
+   *
+   *  Note: many collection methods will not work on collections of infinite sizes. 
+   *
+   *  @return  `true` if this collection is known to have finite size, `false` otherwise.
+   */
+  def hasDefiniteSize = true
+
+  /** Concatenates this $coll with the elements of a traversable collection.
+   * 
+   *  @param that   the traversable to append.
+   *  @tparam B     the element type of the returned collection. 
+   *  @tparam That  $thatinfo
+   *  @param bf     $bfinfo
+   *  @return       a new collection of type `That` which contains all elements of this $coll
+   *                followed by all elements of `that`.
+   * 
+   *  @usecase def ++(that: TraversableOnce[A]): $Coll[A]
+   *  
+   *  @return       a new $coll which contains all elements of this $coll
+   *                followed by all elements of `that`.
+   */
+  def ++[B >: A, That](that: TraversableOnce[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = {
+    val b = bf(repr)
+    if (that.isInstanceOf[IndexedSeqLike[_, _]]) b.sizeHint(this, that.size)
+    b ++= thisCollection
+    b ++= that
+    b.result
+  }
+
+  /** Builds a new collection by applying a function to all elements of this $coll.
+   *
+   *  @param f      the function to apply to each element.
+   *  @tparam B     the element type of the returned collection.
+   *  @tparam That  $thatinfo
+   *  @param bf     $bfinfo
+   *  @return       a new collection of type `That` resulting from applying the given function
+   *                `f` to each element of this $coll and collecting the results.
+   *
+   *  @usecase def map[B](f: A => B): $Coll[B] 
+   *  
+   *  @return       a new $coll resulting from applying the given function
+   *                `f` to each element of this $coll and collecting the results.
+   */
+  def map[B, That](f: A => B)(implicit bf: CanBuildFrom[Repr, B, That]): That = {
+    val b = bf(repr)
+    b.sizeHint(this) 
+    for (x <- this) b += f(x)
+    b.result
+  }
+
+  /** Builds a new collection by applying a function to all elements of this $coll
+   *  and concatenating the results. 
+   *
+   *  @param f      the function to apply to each element.
+   *  @tparam B     the element type of the returned collection.
+   *  @tparam That  $thatinfo
+   *  @param bf     $bfinfo
+   *  @return       a new collection of type `That` resulting from applying the given collection-valued function
+   *                `f` to each element of this $coll and concatenating the results.
+   *
+   *  @usecase def flatMap[B](f: A => Traversable[B]): $Coll[B]
+   * 
+   *  @return       a new $coll resulting from applying the given collection-valued function
+   *                `f` to each element of this $coll and concatenating the results.
+   */
+  def flatMap[B, That](f: A => Traversable[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = {
+    val b = bf(repr)
+    for (x <- this) b ++= f(x)
+    b.result
+  }
+  
+  /** Selects all elements of this $coll which satisfy a predicate.
+   *
+   *  @param p     the predicate used to test elements.
+   *  @return      a new $coll consisting of all elements of this $coll that satisfy the given
+   *               predicate `p`. The order of the elements is preserved.
+   */
+  def filter(p: A => Boolean): Repr = {
+    val b = newBuilder
+    for (x <- this) 
+      if (p(x)) b += x
+    b.result
+  }
+  
+  /** Selects all elements of this $coll which do not satisfy a predicate.
+   *
+   *  @param p     the predicate used to test elements.
+   *  @return      a new $coll consisting of all elements of this $coll that do not satisfy the given
+   *               predicate `p`. The order of the elements is preserved.
+   */
+  def filterNot(p: A => Boolean): Repr = filter(!p(_))
+
+  /** Builds a new collection by applying a partial function to all elements of this $coll
+   *  on which the function is defined.
+   *
+   *  @param pf     the partial function which filters and maps the $coll.
+   *  @tparam B     the element type of the returned collection.
+   *  @tparam That  $thatinfo
+   *  @param bf     $bfinfo
+   *  @return       a new collection of type `That` resulting from applying the partial function
+   *                `pf` to each element on which it is defined and collecting the results.
+   *                The order of the elements is preserved.
+   *
+   *  @usecase def collect[B](pf: PartialFunction[A, B]): $Coll[B]
+   *  
+   *  @return       a new $coll resulting from applying the given partial function
+   *                `pf` to each element on which it is defined and collecting the results.
+   *                The order of the elements is preserved.
+   */
+  def collect[B, That](pf: PartialFunction[A, B])(implicit bf: CanBuildFrom[Repr, B, That]): That = {
+    val b = bf(repr)
+    for (x <- this) if (pf.isDefinedAt(x)) b += pf(x)
+    b.result
+  }
+
+  /** Builds a new collection by applying an option-valued function to all elements of this $coll
+   *  on which the function is defined.
+   *
+   *  @param f      the option-valued function which filters and maps the $coll.
+   *  @tparam B     the element type of the returned collection.
+   *  @tparam That  $thatinfo
+   *  @param bf     $bfinfo
+   *  @return       a new collection of type `That` resulting from applying the option-valued function
+   *                `f` to each element and collecting all defined results.
+   *                The order of the elements is preserved.
+   *
+   *  @usecase def filterMap[B](f: A => Option[B]): $Coll[B]
+   *  
+   *  @param pf     the partial function which filters and maps the $coll.
+   *  @return       a new $coll resulting from applying the given option-valued function
+   *                `f` to each element and collecting all defined results.
+   *                The order of the elements is preserved.
+  def filterMap[B, That](f: A => Option[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = {
+    val b = bf(repr)
+    for (x <- this) 
+      f(x) match {
+        case Some(y) => b += y
+        case _ =>
+      }
+    b.result
+  }
+   */
+
+  /** Partitions this $coll in two ${coll}s according to a predicate.
+   *
+   *  @param p the predicate on which to partition.
+   *  @return  a pair of ${coll}s: the first $coll consists of all elements that 
+   *           satisfy the predicate `p` and the second $coll consists of all elements
+   *           that don't. The relative order of the elements in the resulting ${coll}s
+   *           is the same as in the original $coll.
+   */
+  def partition(p: A => Boolean): (Repr, Repr) = {
+    val l, r = newBuilder
+    for (x <- this) (if (p(x)) l else r) += x
+    (l.result, r.result)
+  }
+
+  /** Partitions this $coll into a map of ${coll}s according to some discriminator function.
+   *
+   *  Note: this method is not re-implemented by views. This means
+   *        when applied to a view it will always force the view and
+   *        return a new $coll.
+   * 
+   *  @param f     the discriminator function.
+   *  @tparam K    the type of keys returned by the discriminator function.
+   *  @return      A map from keys to ${coll}s such that the following invariant holds:
+   *               {{{
+   *                 (xs partition f)(k) = xs filter (x => f(x) == k)
+   *               }}}
+   *               That is, every key `k` is bound to a $coll of those elements `x`
+   *               for which `f(x)` equals `k`.
+   * 
+   */
+  def groupBy[K](f: A => K): immutable.Map[K, Repr] = {
+    val m = mutable.Map.empty[K, Builder[A, Repr]]
+    for (elem <- this) {
+      val key = f(elem)
+      val bldr = m.getOrElseUpdate(key, newBuilder)
+      bldr += elem
+    }
+    val b = immutable.Map.newBuilder[K, Repr]
+    for ((k, v) <- m)
+      b += ((k, v.result))
+    
+    b.result
+  }
+
+  /** Tests whether a predicate holds for all elements of this $coll.
+   *
+   *  $mayNotTerminateInf
+   *
+   *  @param   p     the predicate used to test elements.
+   *  @return        `true` if the given predicate `p` holds for all elements
+   *                 of this $coll, otherwise `false`.
+   */
+  def forall(p: A => Boolean): Boolean = {
+    var result = true
+    breakable {
+      for (x <- this)
+        if (!p(x)) { result = false; break }
+    }
+    result
+  }
+
+  /** Tests whether a predicate holds for some of the elements of this $coll.
+   *
+   *  $mayNotTerminateInf
+   *
+   *  @param   p     the predicate used to test elements.
+   *  @return        `true` if the given predicate `p` holds for some of the elements
+   *                 of this $coll, otherwise `false`.
+   */
+  def exists(p: A => Boolean): Boolean = {
+    var result = false
+    breakable {
+      for (x <- this)
+        if (p(x)) { result = true; break }
+    }
+    result
+  }
+
+  /** Finds the first element of the $coll satisfying a predicate, if any.
+   * 
+   *  $mayNotTerminateInf
+   *  $orderDependent
+   *
+   *  @param p    the predicate used to test elements.
+   *  @return     an option value containing the first element in the $coll
+   *              that satisfies `p`, or `None` if none exists.
+   */
+  def find(p: A => Boolean): Option[A] = {
+    var result: Option[A] = None
+    breakable {
+      for (x <- this)
+        if (p(x)) { result = Some(x); break }
+    }
+    result
+  }
+  
+  /** Applies option-valued function to successive elements of this $coll
+   *  until a defined value is found.
+   * 
+   *  $mayNotTerminateInf
+   *  $orderDependent
+   *
+   *  @param f    the function to be applied to successive elements.
+   *  @return     an option value containing the first defined result of
+   *              `f`, or `None` if `f` returns `None` for all all elements.
+  def mapFind[B](f: A => Option[B]): Option[B] = {
+    var result: Option[B] = None
+    breakable {
+      for (x <- this)
+        f(x) match {
+          case s @ Some(_) => result = s; break
+          case _ =>
+        }
+    }
+    result
+  }
+   */
+  
+  /**
+   * Produces a collection containing cummulative results of applying the operator going left to right.
+   * $willNotTerminateInf
+   * $orderDependent
+   * 
+   * @tparam B      the type of the elements in the resulting collection
+   * @tparam That   the actual type of the resulting collection
+   * @param z       the initial value
+   * @param op      the binary operator applied to the intermediate result and the element
+   * @param bf      $bfinfo
+   * @return        collection with intermediate results
+   */
+  def scanLeft[B, That](z: B)(op: (B, A) => B)(implicit bf: CanBuildFrom[Repr, B, That]): That = {
+    val b = bf(repr)
+    b.sizeHint(this, 1)
+    var acc = z
+    b += acc
+    for (x <- this) { acc = op(acc, x); b += acc }
+    b.result
+  }
+  
+  /**
+   * Produces a collection containing cummulative results of applying the operator going right to left.
+   * $willNotTerminateInf
+   * $orderDependent
+   * 
+   * @tparam B      the type of the elements in the resulting collection
+   * @tparam That   the actual type of the resulting collection
+   * @param z       the initial value
+   * @param op      the binary operator applied to the intermediate result and the element
+   * @param bf      $bfinfo
+   * @return        collection with intermediate results
+   */
+  def scanRight[B, That](z: B)(op: (A, B) => B)(implicit bf: CanBuildFrom[Repr, B, That]): That = {
+    val b = bf(repr)
+    b.sizeHint(this, 1)
+    var acc = z
+    b += acc
+    for (x <- reversed) { acc = op(x, acc); b += acc }
+    b.result
+  }
+
+  /** Selects the first element of this $coll.
+   *  $orderDependent
+   *  @return  the first element of this $coll.
+   *  @throws `NoSuchElementException` if the $coll is empty.
+   */
+  def head: A = {
+    var result: () => A = () => throw new NoSuchElementException
+    breakable {
+      for (x <- this) {
+        result = () => x
+        break
+      }
+    }
+    result()
+  }
+
+  /** Optionally selects the first element.
+   *  $orderDependent
+   *  @return  the first element of this $coll if it is nonempty, `None` if it is empty.
+   */
+  def headOption: Option[A] = if (isEmpty) None else Some(head)
+
+  /** Selects all elements except the first.
+   *  $orderDependent
+   *  @return  a $coll consisting of all elements of this $coll
+   *           except the first one.
+   *  @throws `UnsupportedOperationException` if the $coll is empty.
+   */ 
+  def tail: Repr = {
+    if (isEmpty) throw new UnsupportedOperationException("empty.tail")
+    drop(1)
+  }
+
+  /** Selects the last element.
+    * $orderDependent
+    * @return The last element of this $coll.
+    * @throws NoSuchElementException If the $coll is empty. */
+  def last: A = {
+    var lst = head
+    for (x <- this)
+      lst = x
+    lst
+  }
+
+  /** Optionally selects the last element.
+   *  $orderDependent
+   *  @return  the last element of this $coll$ if it is nonempty, `None` if it is empty.
+   */
+  def lastOption: Option[A] = if (isEmpty) None else Some(last)
+
+  /** Selects all elements except the last.
+   *  $orderDependent
+   *  @return  a $coll consisting of all elements of this $coll
+   *           except the last one.
+   *  @throws `UnsupportedOperationException` if the $coll is empty.
+   */
+  def init: Repr = {
+    if (isEmpty) throw new UnsupportedOperationException("empty.init")
+    var lst = head
+    var follow = false
+    val b = newBuilder
+    b.sizeHint(this, -1)
+    for (x <- this) {
+      if (follow) b += lst
+      else follow = true
+      lst = x
+    }
+    b.result
+  }
+
+  /** Selects first ''n'' elements.
+   *  $orderDependent
+   *  @param  n    Tt number of elements to take from this $coll.
+   *  @return a $coll consisting only of the first `n` elements of this $coll, or else the
+   *          whole $coll, if it has less than `n` elements.
+   */
+  def take(n: Int): Repr = {
+    val b = newBuilder
+    b.sizeHintBounded(n, this)
+    var i = 0
+    breakable {
+      for (x <- this) {
+        if (i >= n) break
+        b += x
+        i += 1
+      }
+    } 
+    b.result
+  }
+
+  /** Selects all elements except first ''n'' ones. 
+   *  $orderDependent
+   *  @param  n    the number of elements to drop from this $coll.
+   *  @return a $coll consisting of all elements of this $coll except the first `n` ones, or else the
+   *          empty $coll, if this $coll has less than `n` elements.
+   */
+  def drop(n: Int): Repr = {
+    val b = newBuilder
+    if (n >= 0) b.sizeHint(this, -n)
+    var i = 0
+    for (x <- this) {
+      if (i >= n) b += x
+      i += 1
+    }
+    b.result
+  }
+
+  /** Selects an interval of elements.
+   *
+   *  Note: `c.slice(from, to)`  is equivalent to (but possibly more efficient than)
+   *  `c.drop(from).take(to - from)`
+   *  $orderDependent
+   *
+   *  @param from   the index of the first returned element in this $coll.
+   *  @param until  the index one past the last returned element in this $coll.
+   *  @return  a $coll containing the elements starting at index `from`
+   *           and extending up to (but not including) index `until` of this $coll.
+   */
+  def slice(from: Int, until: Int): Repr = {
+    val b = newBuilder
+    b.sizeHintBounded(until - from, this)
+    var i = 0
+    breakable {
+      for (x <- this) {
+        if (i >= from) b += x
+        i += 1
+        if (i == until) break
+      }
+    } 
+    b.result
+  }
+
+  /** Takes longest prefix of elements that satisfy a predicate.
+   *  $orderDependent
+   *  @param   p  The predicate used to test elements.
+   *  @return  the longest prefix of this $coll whose elements all satisfy
+   *           the predicate `p`.
+   */
+  def takeWhile(p: A => Boolean): Repr = {
+    val b = newBuilder
+    breakable {
+      for (x <- this) {
+        if (!p(x)) break
+        b += x
+      }
+    }
+    b.result
+  }
+
+  /** Drops longest prefix of elements that satisfy a predicate.
+   *  $orderDependent
+   *  @param   p  The predicate used to test elements.
+   *  @return  the longest suffix of this $coll whose first element
+   *           does not satisfy the predicate `p`.
+   */
+  def dropWhile(p: A => Boolean): Repr = {
+    val b = newBuilder
+    var go = false
+    for (x <- this) {
+      if (!p(x)) go = true
+      if (go) b += x
+    }
+    b.result
+  }
+
+  /** Splits this $coll into a prefix/suffix pair according to a predicate.
+   *
+   *  Note: `c span p`  is equivalent to (but possibly more efficient than)
+   *  `(c takeWhile p, c dropWhile p)`, provided the evaluation of the predicate `p`
+   *  does not cause any side-effects.
+   *  $orderDependent
+   * 
+   *  @param p the test predicate
+   *  @return  a pair consisting of the longest prefix of this $coll whose
+   *           elements all satisfy `p`, and the rest of this $coll.
+   */
+  def span(p: A => Boolean): (Repr, Repr) = {
+    val l, r = newBuilder
+    var toLeft = true
+    for (x <- this) {
+      toLeft = toLeft && p(x)
+      (if (toLeft) l else r) += x
+    }
+    (l.result, r.result)
+  }
+
+  /** Splits this $coll into two at a given position.
+   *  Note: `c splitAt n` is equivalent to (but possibly more efficient than)
+   *         `(c take n, c drop n)`.
+   *  $orderDependent
+   * 
+   *  @param n the position at which to split.
+   *  @return  a pair of ${coll}s consisting of the first `n`
+   *           elements of this $coll, and the other elements.
+   */
+  def splitAt(n: Int): (Repr, Repr) = {
+    val l, r = newBuilder
+    l.sizeHintBounded(n, this)
+    if (n >= 0) r.sizeHint(this, -n)
+    var i = 0
+    for (x <- this) {
+      (if (i < n) l else r) += x
+      i += 1
+    }
+    (l.result, r.result)
+  }
+
+  /** Copies elements of this $coll to an array.
+   *  Fills the given array `xs` with at most `len` elements of
+   *  this $coll, starting at position `start`.
+   *  Copying will stop once either the end of the current $coll is reached,
+   *  or the end of the array is reached, or `len` elements have been copied.
+   *
+   *  $willNotTerminateInf
+   * 
+   *  @param  xs     the array to fill.
+   *  @param  start  the starting index.
+   *  @param  len    the maximal number of elements to copy.
+   *  @tparam B      the type of the elements of the array. 
+   * 
+   *
+   *  @usecase def copyToArray(xs: Array[A], start: Int, len: Int): Unit
+   */
+  def copyToArray[B >: A](xs: Array[B], start: Int, len: Int) {
+    var i = start
+    val end = (start + len) min xs.length
+    breakable {
+      for (x <- this) {
+        if (i >= end) break
+        xs(i) = x
+        i += 1
+      }
+    }
+  }
+
+  def toTraversable: Traversable[A] = thisCollection
+  def toIterator: Iterator[A] = toStream.iterator
+  def toStream: Stream[A] = toBuffer.toStream
+
+  /** Converts this $coll to a string.
+   *  @return   a string representation of this collection. By default this
+   *            string consists of the `stringPrefix` of this $coll,
+   *            followed by all elements separated by commas and enclosed in parentheses.
+   */
+  override def toString = mkString(stringPrefix + "(", ", ", ")")
+
+  /** Defines the prefix of this object's `toString` representation.
+   *  @return  a string representation which starts the result of `toString` applied to this $coll.
+   *           By default the string prefix is the simple name of the collection class $coll.
+   */
+  def stringPrefix : String = {
+    var string = repr.asInstanceOf[AnyRef].getClass.getName
+    val idx1 = string.lastIndexOf('.' : Int)
+    if (idx1 != -1) string = string.substring(idx1 + 1)
+    val idx2 = string.indexOf('$')
+    if (idx2 != -1) string = string.substring(0, idx2)
+    string
+  }
+
+  /** Creates a non-strict view of this $coll.
+   * 
+   *  @return a non-strict view of this $coll.
+   */
+  def view = new TraversableView[A, Repr] {
+    protected lazy val underlying = self.repr
+    override def foreach[U](f: A => U) = self foreach f
+  }
+
+  /** Creates a non-strict view of a slice of this $coll.
+   *
+   *  Note: the difference between `view` and `slice` is that `view` produces
+   *        a view of the current $coll, whereas `slice` produces a new $coll.
+   * 
+   *  Note: `view(from, to)` is equivalent to `view.slice(from, to)`
+   *  $orderDependent
+   * 
+   *  @param from   the index of the first element of the view
+   *  @param until  the index of the element following the view
+   *  @return a non-strict view of a slice of this $coll, starting at index `from`
+   *  and extending up to (but not including) index `until`.
+   */
+  def view(from: Int, until: Int): TraversableView[A, Repr] = view.slice(from, until)
+
+  /** Creates a non-strict filter of this $coll.
+   *
+   *  Note: the difference between `c filter p` and `c withFilter p` is that
+   *        the former creates a new collection, whereas the latter only restricts
+   *        the domain of subsequent `map`, `flatMap`, `foreach`, and `withFilter` operations.
+   *  $orderDependent
+   * 
+   *  @param p   the predicate used to test elements.
+   *  @return    an object of class `WithFilter`, which supports
+   *             `map`, `flatMap`, `foreach`, and `withFilter` operations.
+   *             All these operations apply to those elements of this $coll which
+   *             satisfy the predicate `p`.
+   */
+  def withFilter(p: A => Boolean): FilterMonadic[A, Repr] = new WithFilter(p)
+
+  /** A class supporting filtered operations. Instances of this class are returned by
+   *  method `withFilter`.
+   */
+  class WithFilter(p: A => Boolean) extends FilterMonadic[A, Repr] {
+
+    /** Builds a new collection by applying a function to all elements of the
+     *  outer $coll containing this `WithFilter` instance that satisfy predicate `p`.
+     *
+     *  @param f      the function to apply to each element.
+     *  @tparam B     the element type of the returned collection.
+     *  @tparam That  $thatinfo
+     *  @param bf     $bfinfo
+     *  @return       a new collection of type `That` resulting from applying the given function
+     *                `f` to each element of the outer $coll that satisfies predicate `p`
+     *                and collecting the results.
+     *
+     *  @usecase def map[B](f: A => B): $Coll[B] 
+     *  
+     *  @return       a new $coll resulting from applying the given function
+     *                `f` to each element of the outer $coll that satisfies predicate `p`
+     *                and collecting the results.
+     */
+    def map[B, That](f: A => B)(implicit bf: CanBuildFrom[Repr, B, That]): That = {
+      val b = bf(repr)
+      for (x <- self) 
+        if (p(x)) b += f(x)
+      b.result
+    }
+
+    /** Builds a new collection by applying a function to all elements of the
+     *  outer $coll containing this `WithFilter` instance that satisfy predicate `p` and concatenating the results. 
+     *
+     *  @param f      the function to apply to each element.
+     *  @tparam B     the element type of the returned collection.
+     *  @tparam That  $thatinfo
+     *  @param bf     $bfinfo
+     *  @return       a new collection of type `That` resulting from applying the given collection-valued function
+     *                `f` to each element of the outer $coll that satisfies predicate `p` and concatenating the results.
+     *
+     *  @usecase def flatMap[B](f: A => Traversable[B]): $Coll[B]
+     * 
+     *  @return       a new $coll resulting from applying the given collection-valued function
+     *                `f` to each element of the outer $coll that satisfies predicate `p` and concatenating the results.
+     */
+    def flatMap[B, That](f: A => Traversable[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = {
+      val b = bf(repr)
+      for (x <- self) 
+        if (p(x)) b ++= f(x)
+      b.result
+    }
+
+    /** Applies a function `f` to all elements of the outer $coll containing this `WithFilter` instance
+     *  that satisfy predicate `p`.
+     *
+     *  @param  f   the function that is applied for its side-effect to every element.
+     *              The result of function `f` is discarded.
+     *              
+     *  @tparam  U  the type parameter describing the result of function `f`. 
+     *              This result will always be ignored. Typically `U` is `Unit`,
+     *              but this is not necessary.
+     *
+     *  @usecase def foreach(f: A => Unit): Unit
+     */   
+    def foreach[U](f: A => U): Unit = 
+      for (x <- self) 
+        if (p(x)) f(x)
+
+    /** Further refines the filter for this $coll.
+     *
+     *  @param q   the predicate used to test elements.
+     *  @return    an object of class `WithFilter`, which supports
+     *             `map`, `flatMap`, `foreach`, and `withFilter` operations.
+     *             All these operations apply to those elements of this $coll which
+     *             satisfy the predicate `q` in addition to the predicate `p`.
+     */
+    def withFilter(q: A => Boolean): WithFilter = 
+      new WithFilter(x => p(x) && q(x))
+  }
+}
diff --git a/src/library/scala/collection/TraversableOnce.scala b/src/library/scala/collection/TraversableOnce.scala
new file mode 100644
index 0000000..44476ee
--- /dev/null
+++ b/src/library/scala/collection/TraversableOnce.scala
@@ -0,0 +1,538 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+package scala.collection
+
+import mutable.{ Buffer, ListBuffer, ArrayBuffer }
+
+/** A template trait for collections which can be traversed either once only
+ *  or one or more times.
+ *  $traversableonceinfo
+ * 
+ *  @tparam A    the element type of the collection
+ *
+ *  @define traversableonceinfo
+ *  This trait is composed of those methods which can be implemented
+ *  solely in terms of foreach and which do not need access to a Builder.
+ *  It represents the implementations common to Iterators and
+ *  Traversables, such as folds, conversions, and other operations which
+ *  traverse some or all of the elements and return a derived value.
+ *
+ *  @author Martin Odersky
+ *  @author Paul Phillips
+ *  @version 2.8
+ *  @since   2.8
+ *
+ *  @define coll traversable or iterator
+ *  @define orderDependentFold
+ * 
+ *    Note: might return different results for different runs, unless the underlying collection type is ordered
+ *    or the operator is associative and commutative.
+ *  @define willNotTerminateInf
+ *
+ *    Note: will not terminate for infinite-sized collections.
+ */
+trait TraversableOnce[+A] {
+  self =>
+
+  /** Self-documenting abstract methods. */
+  def foreach[U](f: A => U): Unit
+  def isEmpty: Boolean
+  def hasDefiniteSize: Boolean
+  
+  /** Tests whether this $coll can be repeatedly traversed.  Always
+   *  true for Traversables and false for Iterators unless overridden.
+   *
+   *  @return   `true` if it is repeatedly traversable, `false` otherwise.
+   */
+  def isTraversableAgain: Boolean
+  
+  /** Returns an Iterator over the elements in this $coll.  Will return
+   *  the same Iterator if this instance is already an Iterator.
+   *  $willNotTerminateInf
+   *  @return an Iterator containing all elements of this $coll.
+   */	
+  def toIterator: Iterator[A]
+  
+  /** Converts this $coll to an unspecified Traversable.  Will return
+   *  the same collection if this instance is already Traversable.
+   *  $willNotTerminateInf
+   *  @return a Traversable containing all elements of this $coll.
+   */	
+  def toTraversable: Traversable[A]
+
+  /** Converts this $coll to a stream.
+   *  $willNotTerminateInf
+   *  @return a stream containing all elements of this $coll.
+   */	
+  def toStream: Stream[A]
+
+  /** Presently these are abstract because the Traversable versions use
+   *  breakable/break, and I wasn't sure enough of how that's supposed to
+   *  function to consolidate them with the Iterator versions.
+   */
+  def forall(p: A => Boolean): Boolean
+  def exists(p: A => Boolean): Boolean
+  def find(p: A => Boolean): Option[A]
+  def copyToArray[B >: A](xs: Array[B], start: Int, len: Int): Unit
+  // def mapFind[B](f: A => Option[B]): Option[B]
+  
+  // for internal use
+  protected[this] def reversed = {
+    var elems: List[A] = Nil
+    self foreach (elems ::= _)
+    elems
+  }
+
+  /** The size of this $coll.
+   *
+   *  $willNotTerminateInf
+   *
+   *  @return    the number of elements in this $coll.
+   */
+  def size: Int = {
+    var result = 0	
+    for (x <- self) result += 1
+    result
+  }
+  
+  /** Tests whether the $coll is not empty.
+   * 
+   *  @return    `true` if the $coll contains at least one element, `false` otherwise.
+   */
+  def nonEmpty: Boolean = !isEmpty
+  
+  /** Counts the number of elements in the $coll which satisfy a predicate.
+   *
+   *  @param p     the predicate  used to test elements.
+   *  @return      the number of elements satisfying the predicate `p`.
+   */
+  def count(p: A => Boolean): Int = {
+    var cnt = 0
+    for (x <- this)
+      if (p(x)) cnt += 1
+
+    cnt
+  }
+  
+  /** Applies a binary operator to a start value and all elements of this $coll, going left to right.
+   *
+   *  Note: `/:` is alternate syntax for `foldLeft`; `z /: xs` is the same as `xs foldLeft z`.
+   *  $willNotTerminateInf
+   *  $orderDependentFold
+   *
+   *  @param   z    the start value.
+   *  @param   op   the binary operator.
+   *  @tparam  B    the result type of the binary operator.
+   *  @return  the result of inserting `op` between consecutive elements of this $coll,
+   *           going left to right with the start value `z` on the left:
+   *           {{{
+   *             op(...op(op(z, x,,1,,), x,,2,,), ..., x,,n,,)
+   *           }}}
+   *           where `x,,1,,, ..., x,,n,,` are the elements of this $coll.
+   */
+  def /:[B](z: B)(op: (B, A) => B): B = foldLeft(z)(op)
+  
+  /** Applies a binary operator to all elements of this $coll and a start value, going right to left.
+   *
+   *  Note: `:\` is alternate syntax for `foldRight`; `xs :\ z` is the same as `xs foldRight z`.
+   *  $willNotTerminateInf
+   *  $orderDependentFold
+   * 
+   *  @param   z    the start value
+   *  @param   op   the binary operator
+   *  @tparam  B    the result type of the binary operator.
+   *  @return  the result of inserting `op` between consecutive elements of this $coll,
+   *           going right to left with the start value `z` on the right:
+   *           {{{
+   *             op(x,,1,,, op(x,,2,,, ... op(x,,n,,, z)...))
+   *           }}}
+   *           where `x,,1,,, ..., x,,n,,` are the elements of this $coll.
+   */
+  def :\[B](z: B)(op: (A, B) => B): B = foldRight(z)(op)
+  
+  /** Applies a binary operator to a start value and all elements of this $coll, going left to right.
+   * 
+   *  $willNotTerminateInf
+   *  $orderDependentFold
+   *
+   *  @param   z    the start value.
+   *  @param   op   the binary operator.
+   *  @tparam  B    the result type of the binary operator.
+   *  @return  the result of inserting `op` between consecutive elements of this $coll,
+   *           going left to right with the start value `z` on the left:
+   *           {{{
+   *             op(...op(z, x,,1,,), x,,2,,, ..., x,,n,,)
+   *           }}}
+   *           where `x,,1,,, ..., x,,n,,` are the elements of this $coll.
+   */
+  def foldLeft[B](z: B)(op: (B, A) => B): B = {
+    var result = z
+    this foreach (x => result = op(result, x))
+    result
+  }
+  
+  /** Applies a binary operator to all elements of this $coll and a start value, going right to left.
+   * 
+   *  $willNotTerminateInf
+   *  $orderDependentFold
+   *  @param   z    the start value.
+   *  @param   op   the binary operator.
+   *  @tparam  B    the result type of the binary operator.
+   *  @return  the result of inserting `op` between consecutive elements of this $coll,
+   *           going right to left with the start value `z` on the right:
+   *           {{{
+   *             op(x,,1,,, op(x,,2,,, ... op(x,,n,,, z)...))
+   *           }}}
+   *           where `x,,1,,, ..., x,,n,,` are the elements of this $coll.
+   */
+  def foldRight[B](z: B)(op: (A, B) => B): B =
+    reversed.foldLeft(z)((x, y) => op(y, x))
+  
+  /** Applies a binary operator to all elements of this $coll, going left to right.
+   *  $willNotTerminateInf
+   *  $orderDependentFold
+   *
+   *  @param  op    the binary operator.
+   *  @tparam  B    the result type of the binary operator.
+   *  @return  the result of inserting `op` between consecutive elements of this $coll,
+   *           going left to right:
+   *           {{{
+   *             op(...(op(x,,1,,, x,,2,,), ... ) , x,,n,,)
+   *           }}}
+   *           where `x,,1,,, ..., x,,n,,` are the elements of this $coll.
+   *  @throws `UnsupportedOperationException` if this $coll is empty.
+   */
+  def reduceLeft[B >: A](op: (B, A) => B): B = {
+    if (isEmpty)
+      throw new UnsupportedOperationException("empty.reduceLeft")
+    
+    var first = true
+    var acc: B = 0.asInstanceOf[B]
+
+    for (x <- self) {
+      if (first) {
+        acc = x
+        first = false
+      }
+      else acc = op(acc, x)
+    }
+    acc
+  }
+
+  /** Applies a binary operator to all elements of this $coll, going right to left.
+   *  $willNotTerminateInf
+   *  $orderDependentFold
+   * 
+   *  @param  op    the binary operator.
+   *  @tparam  B    the result type of the binary operator.
+   *  @return  the result of inserting `op` between consecutive elements of this $coll,
+   *           going right to left:
+   *           {{{
+   *             op(x,,1,,, op(x,,2,,, ..., op(x,,n-1,,, x,,n,,)...))
+   *           }}}
+   *           where `x,,1,,, ..., x,,n,,` are the elements of this $coll.
+   *  @throws `UnsupportedOperationException` if this $coll is empty.
+   */
+  def reduceRight[B >: A](op: (A, B) => B): B = {
+    if (isEmpty)
+      throw new UnsupportedOperationException("empty.reduceRight")
+    
+    reversed.reduceLeft[B]((x, y) => op(y, x))
+  }
+  
+  /** Optionally applies a binary operator to all elements of this $coll, going left to right.
+   *  $willNotTerminateInf
+   *  $orderDependentFold
+   *  
+   *  @param  op    the binary operator.
+   *  @tparam  B    the result type of the binary operator.
+   *  @return  an option value containing the result of `reduceLeft(op)` is this $coll is nonempty,
+   *           `None` otherwise.
+   */
+  def reduceLeftOption[B >: A](op: (B, A) => B): Option[B] =
+    if (isEmpty) None else Some(reduceLeft(op))
+
+  /** Optionally applies a binary operator to all elements of this $coll, going right to left.
+   *  $willNotTerminateInf
+   *  $orderDependentFold
+   * 
+   *  @param  op    the binary operator.
+   *  @tparam  B    the result type of the binary operator.
+   *  @return  an option value containing the result of `reduceRight(op)` is this $coll is nonempty,
+   *           `None` otherwise.
+   */
+  def reduceRightOption[B >: A](op: (A, B) => B): Option[B] =
+    if (isEmpty) None else Some(reduceRight(op))
+  
+  /** Sums up the elements of this collection.
+   * 
+   *   @param   num  an implicit parameter defining a set of numeric operations
+   *                 which includes the `+` operator to be used in forming the sum.
+   *   @tparam  B    the result type of the `+` operator.  
+   *   @return       the sum of all elements of this $coll with respect to the `+` operator in `num`.
+   *
+   *   @usecase def sum: A
+   * 
+   *   @return       the sum of all elements in this $coll of numbers of type `Int`.
+   *   Instead of `Int`, any other type `T` with an implicit `Numeric[T]` implementation 
+   *   can be used as element type of the $coll and as result type of `sum`. 
+   *   Examples of such types are: `Long`, `Float`, `Double`, `BigInt`.
+   * 
+   */
+  def sum[B >: A](implicit num: Numeric[B]): B = foldLeft(num.zero)(num.plus)
+  
+  /** Multiplies up the elements of this collection.
+   * 
+   *   @param   num  an implicit parameter defining a set of numeric operations
+   *                 which includes the `*` operator to be used in forming the product.
+   *   @tparam  B    the result type of the `*` operator.  
+   *   @return       the product of all elements of this $coll with respect to the `*` operator in `num`.
+   *
+   *   @usecase def product: A
+   * 
+   *   @return       the product of all elements in this $coll of numbers of type `Int`.
+   *   Instead of `Int`, any other type `T` with an implicit `Numeric[T]` implementation 
+   *   can be used as element type of the $coll and as result type of `product`. 
+   *   Examples of such types are: `Long`, `Float`, `Double`, `BigInt`.
+   */
+  def product[B >: A](implicit num: Numeric[B]): B = foldLeft(num.one)(num.times)
+
+  /** Finds the smallest element.
+   *
+   *  @param    cmp   An ordering to be used for comparing elements.
+   *  @tparam   B     The type over which the ordering is defined.   
+   *  @return   the smallest element of this $coll with respect to the ordering `cmp`.
+   *
+   *  @usecase def min: A
+   *  @return   the smallest element of this $coll  
+   */
+  def min[B >: A](implicit cmp: Ordering[B]): A = {
+    if (isEmpty)
+      throw new UnsupportedOperationException("empty.min")
+    
+    reduceLeft((x, y) => if (cmp.lteq(x, y)) x else y)
+  }
+
+  /** Finds the largest element.
+   *
+   *  @param    cmp   An ordering to be used for comparing elements.
+   *  @tparam   B     The type over which the ordering is defined.   
+   *  @return   the largest element of this $coll with respect to the ordering `cmp`.
+   *
+   *  @usecase def max: A
+   *  @return   the largest element of this $coll. 
+   */
+  def max[B >: A](implicit cmp: Ordering[B]): A = {
+    if (isEmpty)
+      throw new UnsupportedOperationException("empty.max")
+    
+    reduceLeft((x, y) => if (cmp.gteq(x, y)) x else y)
+  }
+
+  /** Copies all elements of this $coll to a buffer.
+   *  $willNotTerminateInf
+   *  @param  dest   The buffer to which elements are copied.
+   */
+  def copyToBuffer[B >: A](dest: Buffer[B]): Unit = dest ++= self
+  
+  /** Copies values of this $coll to an array.
+   *  Fills the given array `xs` with values of this $coll, after skipping `start` values.
+   *  Copying will stop once either the end of the current $coll is reached,
+   *  or the end of the array is reached.
+   *
+   *  $willNotTerminateInf
+   * 
+   *  @param  xs     the array to fill.
+   *  @param  start  the starting index.
+   *  @tparam B      the type of the elements of the array. 
+   *
+   *  @usecase def copyToArray(xs: Array[A], start: Int): Unit
+   */
+  def copyToArray[B >: A](xs: Array[B], start: Int): Unit = 
+    copyToArray(xs, start, xs.length - start)
+
+  /** Copies values of this $coll to an array.
+   *  Fills the given array `xs` with values of this $coll.
+   *  Copying will stop once either the end of the current $coll is reached,
+   *  or the end of the array is reached.
+   *
+   *  $willNotTerminateInf
+   * 
+   *  @param  xs     the array to fill.
+   *  @tparam B      the type of the elements of the array. 
+   * 
+   *  @usecase def copyToArray(xs: Array[A]): Unit
+   */
+  def copyToArray[B >: A](xs: Array[B]): Unit =
+    copyToArray(xs, 0, xs.length)
+  
+  /** Converts this $coll to an array.
+   *  $willNotTerminateInf
+   * 
+   *  @tparam B    the type of the elements of the array. A `ClassManifest` for this type must
+   *               be available.
+   *  @return  an array containing all elements of this $coll.
+   *
+   *  @usecase def toArray: Array[A]
+   *  @return  an array containing all elements of this $coll.
+   *           A `ClassManifest` must be available for the element type of this $coll.
+   */
+  def toArray[B >: A : ClassManifest]: Array[B] = {
+    if (isTraversableAgain) {
+      val result = new Array[B](size)
+      copyToArray(result, 0)
+      result
+    }
+    else toBuffer.toArray
+  }
+  
+  /** Converts this $coll to a list.
+   *  $willNotTerminateInf
+   *  @return a list containing all elements of this $coll.
+   */
+  def toList: List[A] = new ListBuffer[A] ++= self toList
+
+  /** Converts this $coll to an iterable collection.  Note that
+   *  the choice of target `Iterable` is lazy in this default implementation
+   *  as this `TraversableOnce` may be lazy and unevaluated (i.e. it may
+   *  be an iterator which is only traversable once).
+   *
+   *  $willNotTerminateInf 
+   *  @return an `Iterable` containing all elements of this $coll.
+   */	
+  def toIterable: Iterable[A] = toStream
+ 
+  /** Converts this $coll to a sequence. As with `toIterable`, it's lazy
+   *  in this default implementation, as this `TraversableOnce` may be
+   *  lazy and unevaluated.
+   *  
+   *  $willNotTerminateInf
+   *  @return a sequence containing all elements of this $coll.
+   */	
+  def toSeq: Seq[A] = toStream
+ 
+  /** Converts this $coll to an indexed sequence.
+   *  $willNotTerminateInf
+   *  @return an indexed sequence containing all elements of this $coll.
+   */	
+  def toIndexedSeq[B >: A]: immutable.IndexedSeq[B] = immutable.IndexedSeq() ++ self
+  
+  /** Converts this $coll to a mutable buffer.
+   *  $willNotTerminateInf
+   *  @return a buffer containing all elements of this $coll.
+   */	
+  def toBuffer[B >: A]: mutable.Buffer[B] = new ArrayBuffer[B] ++= self
+  
+  /** Converts this $coll to a set.
+   *  $willNotTerminateInf
+   *  @return      a set containing all elements of this $coll.
+   */
+  def toSet[B >: A]: immutable.Set[B] = immutable.Set() ++ self
+
+  /** Converts this $coll to a map.  This method is unavailable unless
+   *  the elements are members of Tuple2, each ((K, V)) becoming a key-value
+   *  pair in the map.  Duplicate keys will be overwritten by later keys:
+   *  if this is an unordered collection, which key is in the resulting map
+   *  is undefined.
+   *  $willNotTerminateInf
+   *  @return      a map containing all elements of this $coll.
+   *  @usecase   def toMap: Map[K, V]
+   *  @return      a map of type `immutable.Map[K, V]`
+   *               containing all key/value pairs of type `(K, V)` of this $coll.
+   */
+  def toMap[T, U](implicit ev: A <:< (T, U)): immutable.Map[T, U] = {
+    val b = immutable.Map.newBuilder[T, U]
+    for (x <- self)
+      b += x
+      
+    b.result
+  }  
+  
+  /** Displays all elements of this $coll in a string using start, end, and separator strings.
+   *
+   *  @param start the starting string.
+   *  @param sep   the separator string.
+   *  @param end   the ending string.
+   *  @return      a string representation of this $coll. The resulting string
+   *               begins with the string `start` and ends with the string
+   *               `end`. Inside, the string representations (w.r.t. the method `toString`)
+   *               of all elements of this $coll are separated by the string `sep`.
+   *
+   *  @example  `List(1, 2, 3).mkString("(", "; ", ")") = "(1; 2; 3)"`
+   */
+  def mkString(start: String, sep: String, end: String): String =
+    addString(new StringBuilder(), start, sep, end).toString
+
+  /** Displays all elements of this $coll in a string using a separator string.
+   *
+   *  @param sep   the separator string.
+   *  @return      a string representation of this $coll. In the resulting string
+   *               the string representations (w.r.t. the method `toString`)
+   *               of all elements of this $coll are separated by the string `sep`.
+   *
+   *  @example  `List(1, 2, 3).mkString("|") = "1|2|3"`
+   */
+  def mkString(sep: String): String = mkString("", sep, "")
+
+  /** Displays all elements of this $coll in a string.
+   *  @return a string representation of this $coll. In the resulting string
+   *          the string representations (w.r.t. the method `toString`)
+   *          of all elements of this $coll follow each other without any separator string.
+   */
+  def mkString: String = mkString("")
+
+  /** Appends all elements of this $coll to a string builder using start, end, and separator strings.
+   *  The written text begins with the string `start` and ends with the string
+   *  `end`. Inside, the string representations (w.r.t. the method `toString`)
+   *  of all elements of this $coll are separated by the string `sep`.
+   *
+   *  @param  b    the string builder to which elements are appended.
+   *  @param start the starting string.
+   *  @param sep   the separator string.
+   *  @param end   the ending string.
+   *  @return      the string builder `b` to which elements were appended.
+   */
+  def addString(b: StringBuilder, start: String, sep: String, end: String): StringBuilder = {
+    var first = true
+
+    b append start    
+    for (x <- self) {
+      if (first) {
+        b append x
+        first = false
+      }
+      else {
+        b append sep
+        b append x
+      }
+    }
+    b append end
+
+    b
+  }
+
+  /** Appends all elements of this $coll to a string builder using a separator string.
+   *  The written text consists of the string representations (w.r.t. the method `toString`)
+   *  of all elements of this $coll, separated by the string `sep`.
+   *
+   *  @param  b    the string builder to which elements are appended.
+   *  @param sep   the separator string.
+   *  @return      the string builder `b` to which elements were appended.
+   */
+  def addString(b: StringBuilder, sep: String): StringBuilder = addString(b, "", sep, "")
+
+  /** Appends all elements of this $coll to a string builder.
+   *  The written text consists of the string representations (w.r.t. the method `toString`)
+   *  of all elements of this $coll without any separator string.
+   *
+   *  @param  b    the string builder to which elements are appended.
+   *  @return      the string builder `b` to which elements were appended.
+   */
+  def addString(b: StringBuilder): StringBuilder = addString(b, "")
+}
diff --git a/src/library/scala/collection/TraversableProxy.scala b/src/library/scala/collection/TraversableProxy.scala
new file mode 100644
index 0000000..4a26c88
--- /dev/null
+++ b/src/library/scala/collection/TraversableProxy.scala
@@ -0,0 +1,23 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+
+// Methods could be printed by  cat TraverableLike.scala | egrep '^  (override )?def'
+
+
+/** This trait implements a proxy for traversable objects. It forwards
+ *  all calls to a different traversable object
+ *
+ *  @author  Martin Odersky
+ *  @version 2.8
+ *  @since   2.8
+ */
+trait TraversableProxy[+A] extends Traversable[A] with TraversableProxyLike[A, Traversable[A]]
diff --git a/src/library/scala/collection/TraversableProxyLike.scala b/src/library/scala/collection/TraversableProxyLike.scala
new file mode 100644
index 0000000..e705198
--- /dev/null
+++ b/src/library/scala/collection/TraversableProxyLike.scala
@@ -0,0 +1,98 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+
+import generic._
+import mutable.{Buffer, StringBuilder}
+
+// Methods could be printed by  cat TraversableLike.scala | egrep '^  (override )?def'
+
+/** This trait implements a proxy for Traversable objects. It forwards
+ *  all calls to a different Traversable object.
+ *
+ *  @author  Martin Odersky
+ *  @version 2.8
+ *  @since   2.8
+ */
+trait TraversableProxyLike[+A, +Repr <: TraversableLike[A, Repr] with Traversable[A]] extends TraversableLike[A, Repr] with Proxy {
+  def self: Repr
+
+  override def foreach[B](f: A => B): Unit = self.foreach(f)
+  override def isEmpty: Boolean = self.isEmpty
+  override def nonEmpty: Boolean = self.nonEmpty
+  override def size: Int = self.size
+  override def hasDefiniteSize = self.hasDefiniteSize
+  override def ++[B >: A, That](xs: TraversableOnce[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = self.++(xs)(bf)
+  override def map[B, That](f: A => B)(implicit bf: CanBuildFrom[Repr, B, That]): That = self.map(f)(bf)
+  override def flatMap[B, That](f: A => Traversable[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = self.flatMap(f)(bf)
+  override def filter(p: A => Boolean): Repr = self.filter(p)
+  override def filterNot(p: A => Boolean): Repr = self.filterNot(p)
+  override def collect[B, That](pf: PartialFunction[A, B])(implicit bf: CanBuildFrom[Repr, B, That]): That = self.collect(pf)(bf)
+  override def partition(p: A => Boolean): (Repr, Repr) = self.partition(p)
+  override def groupBy[K](f: A => K): immutable.Map[K, Repr] = self.groupBy(f)
+  override def forall(p: A => Boolean): Boolean = self.forall(p)
+  override def exists(p: A => Boolean): Boolean = self.exists(p)
+  override def count(p: A => Boolean): Int = self.count(p)
+  override def find(p: A => Boolean): Option[A] = self.find(p)
+  override def foldLeft[B](z: B)(op: (B, A) => B): B = self.foldLeft(z)(op)
+  override def /: [B](z: B)(op: (B, A) => B): B = self./:(z)(op)
+  override def foldRight[B](z: B)(op: (A, B) => B): B = self.foldRight(z)(op)
+  override def :\ [B](z: B)(op: (A, B) => B): B = self.:\(z)(op)
+  override def reduceLeft[B >: A](op: (B, A) => B): B = self.reduceLeft(op)
+  override def reduceLeftOption[B >: A](op: (B, A) => B): Option[B] = self.reduceLeftOption(op)
+  override def reduceRight[B >: A](op: (A, B) => B): B = self.reduceRight(op)
+  override def reduceRightOption[B >: A](op: (A, B) => B): Option[B] = self.reduceRightOption(op)
+  override def scanLeft[B, That](z: B)(op: (B, A) => B)(implicit bf: CanBuildFrom[Repr, B, That]): That = self.scanLeft(z)(op)(bf)
+  override def scanRight[B, That](z: B)(op: (A, B) => B)(implicit bf: CanBuildFrom[Repr, B, That]): That = self.scanRight(z)(op)(bf)
+  override def sum[B >: A](implicit num: Numeric[B]): B = self.sum(num)
+  override def product[B >: A](implicit num: Numeric[B]): B = self.product(num)
+  override def min[B >: A](implicit cmp: Ordering[B]): A = self.min(cmp)
+  override def max[B >: A](implicit cmp: Ordering[B]): A = self.max(cmp)
+  override def head: A = self.head
+  override def headOption: Option[A] = self.headOption
+  override def tail: Repr = self.tail
+  override def last: A = self.last
+  override def lastOption: Option[A] = self.lastOption
+  override def init: Repr = self.init
+  override def take(n: Int): Repr = self.take(n)
+  override def drop(n: Int): Repr = self.drop(n)
+  override def slice(from: Int, until: Int): Repr = self.slice(from, until)
+  override def takeWhile(p: A => Boolean): Repr = self.takeWhile(p)
+  override def dropWhile(p: A => Boolean): Repr = self.dropWhile(p)
+  override def span(p: A => Boolean): (Repr, Repr) = self.span(p)
+  override def splitAt(n: Int): (Repr, Repr) = self.splitAt(n)
+  override def copyToBuffer[B >: A](dest: Buffer[B]) = self.copyToBuffer(dest)
+  override def copyToArray[B >: A](xs: Array[B], start: Int, len: Int) = self.copyToArray(xs, start, len)
+  override def copyToArray[B >: A](xs: Array[B], start: Int) = self.copyToArray(xs, start)
+  override def copyToArray[B >: A](xs: Array[B]) = self.copyToArray(xs)
+  override def toArray[B >: A: ClassManifest]: Array[B] = self.toArray
+  override def toList: List[A] = self.toList
+  override def toIterable: Iterable[A] = self.toIterable
+  override def toSeq: Seq[A] = self.toSeq
+  override def toIndexedSeq[B >: A] = self.toIndexedSeq
+  override def toBuffer[B >: A] = self.toBuffer
+  override def toStream: Stream[A] = self.toStream
+  override def toSet[B >: A]: immutable.Set[B] = self.toSet  
+  override def toMap[T, U](implicit ev: A <:< (T, U)): immutable.Map[T, U] = self.toMap(ev)
+  override def toTraversable: Traversable[A] = self.toTraversable
+  override def toIterator: Iterator[A] = self.toIterator
+  override def mkString(start: String, sep: String, end: String): String = self.mkString(start, sep, end)
+  override def mkString(sep: String): String = self.mkString(sep)
+  override def mkString: String = self.mkString
+  override def addString(b: StringBuilder, start: String, sep: String, end: String): StringBuilder = self.addString(b, start, sep, end)
+  override def addString(b: StringBuilder, sep: String): StringBuilder = self.addString(b, sep)
+  override def addString(b: StringBuilder): StringBuilder = self.addString(b)
+  override def stringPrefix : String = self.stringPrefix
+  override def view = self.view
+  override def view(from: Int, until: Int): TraversableView[A, Repr] = self.view(from, until)
+  // This appears difficult to override due to the type of WithFilter.
+  // override def withFilter(p: A => Boolean): WithFilter = self.withFilter(p)
+}
diff --git a/src/library/scala/collection/TraversableView.scala b/src/library/scala/collection/TraversableView.scala
new file mode 100644
index 0000000..dab197e
--- /dev/null
+++ b/src/library/scala/collection/TraversableView.scala
@@ -0,0 +1,39 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+
+import generic._
+import mutable.Builder
+import TraversableView.NoBuilder
+
+/** A base trait for non-strict views of traversable collections.
+ *  $traversableViewInfo
+ */
+trait TraversableView[+A, +Coll] extends TraversableViewLike[A, Coll, TraversableView[A, Coll]]
+
+/** An object containing the necessary implicit definitions to make
+ *  `TraversableView`s work. Its definitions are generally not accessed directly by clients.
+ */
+object TraversableView {
+  class NoBuilder[A] extends Builder[A, Nothing] {
+    def +=(elem: A): this.type = this
+    def iterator: Iterator[A] = Iterator.empty
+    @deprecated("use `iterator' instead") def elements = iterator
+    def result() = throw new UnsupportedOperationException("TraversableView.Builder.result")
+    def clear() {}
+  }
+  type Coll = TraversableView[_, C] forSome {type C <: Traversable[_]}
+  implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, TraversableView[A, Traversable[_]]] = 
+    new CanBuildFrom[Coll, A, TraversableView[A, Traversable[_]]] { 
+      def apply(from: Coll) = new NoBuilder 
+      def apply() = new NoBuilder 
+    }
+}
diff --git a/src/library/scala/collection/TraversableViewLike.scala b/src/library/scala/collection/TraversableViewLike.scala
new file mode 100644
index 0000000..51c6b4a
--- /dev/null
+++ b/src/library/scala/collection/TraversableViewLike.scala
@@ -0,0 +1,225 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+
+import generic._
+import mutable.{Builder, ArrayBuffer}
+import TraversableView.NoBuilder
+
+/** A template trait for non-strict views of traversable collections.
+ *  $traversableviewinfo
+ *
+ *  Implementation note: Methods such as `map` or `flatMap` on this view will not invoke the implicitly passed
+ *  `Builder` factory, but will return a new view directly, to preserve by-name behavior.
+ *  The new view is then cast to the factory's result type. This means that every `CanBuildFrom`
+ *  that takes a `View` as its `From` type parameter must yield the same view (or a generic
+ *  superclass of it) as its result parameter. If that assumption is broken, cast errors might result.
+ *
+ * @define viewinfo
+ *  A view is a lazy version of some collection. Collection transformers such as 
+ *  `map` or `filter` or `++` do not traverse any elements when applied on a view.
+ *  Instead they create a new view which simply records that fact that the operation
+ *  needs to be applied. The collection elements are accessed, and the view operations are applied,
+ *  when a non-view result is needed, or when the `force` method is called on a view.
+ * @define traversableviewinfo
+ *  $viewinfo
+ *
+ *  All views for traversable collections are defined by creating a new `foreach` method.
+
+ *  @author Martin Odersky
+ *  @version 2.8
+ *  @since   2.8
+ *  @tparam A    the element type of the view
+ *  @tparam Coll the type of the underlying collection containing the elements.
+ *  @tparam This the type of the view itself
+ */
+trait TraversableViewLike[+A, 
+                          +Coll, 
+                          +This <: TraversableView[A, Coll] with TraversableViewLike[A, Coll, This]]
+  extends Traversable[A] with TraversableLike[A, This] { 
+self =>
+
+  override protected[this] def newBuilder: Builder[A, This] =    
+    throw new UnsupportedOperationException(this+".newBuilder")
+
+  protected def underlying: Coll
+
+  def force[B >: A, That](implicit bf: CanBuildFrom[Coll, B, That]) = {
+    val b = bf(underlying)
+    b ++= this
+    b.result()
+  }
+
+  /** The implementation base trait of this view.
+   *  This trait and all its subtraits has to be re-implemented for each
+   *  ViewLike class. 
+   */
+  trait Transformed[+B] extends TraversableView[B, Coll] {
+    lazy val underlying = self.underlying
+    override def toString = stringPrefix+"(...)"
+  }
+
+  /** A fall back which forces everything into a vector and then applies an operation
+   *  on it. Used for those operations which do not naturally lend themselves to a view
+   */
+  trait Forced[B] extends Transformed[B] {
+    protected[this] def forced: Seq[B]
+    private[this] lazy val forcedCache = forced
+    override def foreach[U](f: B => U) = forcedCache.foreach(f)
+    override def stringPrefix = self.stringPrefix+"C"
+  }
+
+  /** pre: from >= 0  
+   */
+  trait Sliced extends Transformed[A] {
+    protected[this] val from: Int
+    protected[this] val until: Int
+    override def foreach[U](f: A => U) {
+      var index = 0
+      for (x <- self) {
+        if (from <= index) {
+          if (until <= index) return
+          f(x)
+        }
+        index += 1
+      }
+    }
+    override def stringPrefix = self.stringPrefix+"S"
+    override def slice(from1: Int, until1: Int): This =
+      newSliced(from1 max 0, until1 max 0).asInstanceOf[This]
+  }
+
+  trait Mapped[B] extends Transformed[B] {
+    protected[this] val mapping: A => B
+    override def foreach[U](f: B => U) {
+      for (x <- self)
+        f(mapping(x))
+    }
+    override def stringPrefix = self.stringPrefix+"M"
+  }
+
+  trait FlatMapped[B] extends Transformed[B] {
+    protected[this] val mapping: A => Traversable[B]
+    override def foreach[U](f: B => U) {
+      for (x <- self)
+        for (y <- mapping(x))
+          f(y)
+    }
+    override def stringPrefix = self.stringPrefix+"N"
+  }
+
+  trait Appended[B >: A] extends Transformed[B] {
+    protected[this] val rest: Traversable[B]
+    override def foreach[U](f: B => U) {
+      for (x <- self) f(x)
+      for (x <- rest) f(x)
+    }
+    override def stringPrefix = self.stringPrefix+"A"
+  }    
+
+  trait Filtered extends Transformed[A] {
+    protected[this] val pred: A => Boolean 
+    override def foreach[U](f: A => U) {
+      for (x <- self)
+        if (pred(x)) f(x)
+    }
+    override def stringPrefix = self.stringPrefix+"F"
+  }
+
+  trait TakenWhile extends Transformed[A] {
+    protected[this] val pred: A => Boolean 
+    override def foreach[U](f: A => U) {
+      for (x <- self) {
+        if (!pred(x)) return
+        f(x)
+      }
+    }
+    override def stringPrefix = self.stringPrefix+"T"
+  }
+
+  trait DroppedWhile extends Transformed[A] {
+    protected[this] val pred: A => Boolean 
+    override def foreach[U](f: A => U) {
+      var go = false
+      for (x <- self) {
+        if (!go && !pred(x)) go = true
+        if (go) f(x)
+      }
+    }
+    override def stringPrefix = self.stringPrefix+"D"
+  }
+
+  /** Boilerplate method, to override in each subclass
+   *  This method could be eliminated if Scala had virtual classes
+   */
+  protected def newForced[B](xs: => Seq[B]): Transformed[B] = new Forced[B] { val forced = xs }
+  protected def newAppended[B >: A](that: Traversable[B]): Transformed[B] = new Appended[B] { val rest = that }
+  protected def newMapped[B](f: A => B): Transformed[B] = new Mapped[B] { val mapping = f }
+  protected def newFlatMapped[B](f: A => Traversable[B]): Transformed[B] = new FlatMapped[B] { val mapping = f }
+  protected def newFiltered(p: A => Boolean): Transformed[A] = new Filtered { val pred = p }
+  protected def newSliced(_from: Int, _until: Int): Transformed[A] = new Sliced { val from = _from; val until = _until }
+  protected def newDroppedWhile(p: A => Boolean): Transformed[A] = new DroppedWhile { val pred = p }
+  protected def newTakenWhile(p: A => Boolean): Transformed[A] = new TakenWhile { val pred = p }
+  
+  override def ++[B >: A, That](xs: TraversableOnce[B])(implicit bf: CanBuildFrom[This, B, That]): That = {
+    newAppended(xs.toTraversable).asInstanceOf[That]
+// was:    if (bf.isInstanceOf[ByPassCanBuildFrom]) newAppended(that).asInstanceOf[That]
+//         else super.++[B, That](that)(bf) 
+  }
+
+  override def map[B, That](f: A => B)(implicit bf: CanBuildFrom[This, B, That]): That = {
+    newMapped(f).asInstanceOf[That]
+//    val b = bf(repr)
+//          if (b.isInstanceOf[NoBuilder[_]]) newMapped(f).asInstanceOf[That]
+//    else super.map[B, That](f)(bf) 
+  }
+
+  override def collect[B, That](pf: PartialFunction[A, B])(implicit bf: CanBuildFrom[This, B, That]): That =
+    filter(pf.isDefinedAt).map(pf)(bf)
+
+  override def flatMap[B, That](f: A => Traversable[B])(implicit bf: CanBuildFrom[This, B, That]): That = {
+    newFlatMapped(f).asInstanceOf[That]
+// was:    val b = bf(repr)
+//     if (b.isInstanceOf[NoBuilder[_]]) newFlatMapped(f).asInstanceOf[That]
+//    else super.flatMap[B, That](f)(bf)
+  }
+
+  protected[this] def thisSeq: Seq[A] = {
+    val buf = new ArrayBuffer[A]
+    self foreach (buf +=)
+    buf.result
+  }
+
+  override def filter(p: A => Boolean): This = newFiltered(p).asInstanceOf[This]
+  override def withFilter(p: A => Boolean): This = newFiltered(p).asInstanceOf[This]
+  override def partition(p: A => Boolean): (This, This) = (filter(p), filter(!p(_)))
+  override def init: This = newSliced(0, size - 1).asInstanceOf[This]
+  override def drop(n: Int): This = newSliced(n max 0, Int.MaxValue).asInstanceOf[This]
+  override def take(n: Int): This = newSliced(0, n).asInstanceOf[This]
+  override def slice(from: Int, until: Int): This = newSliced(from max 0, until).asInstanceOf[This]
+  override def dropWhile(p: A => Boolean): This = newDroppedWhile(p).asInstanceOf[This]
+  override def takeWhile(p: A => Boolean): This = newTakenWhile(p).asInstanceOf[This]
+  override def span(p: A => Boolean): (This, This) = (takeWhile(p), dropWhile(p))
+  override def splitAt(n: Int): (This, This) = (take(n), drop(n))
+
+  override def scanLeft[B, That](z: B)(op: (B, A) => B)(implicit bf: CanBuildFrom[This, B, That]): That =
+    newForced(thisSeq.scanLeft(z)(op)).asInstanceOf[That]
+
+  override def scanRight[B, That](z: B)(op: (A, B) => B)(implicit bf: CanBuildFrom[This, B, That]): That =
+    newForced(thisSeq.scanRight(z)(op)).asInstanceOf[That]
+
+  override def groupBy[K](f: A => K): immutable.Map[K, This] =
+    thisSeq.groupBy(f).mapValues(xs => newForced(xs).asInstanceOf[This])
+  
+  override def stringPrefix = "TraversableView"
+}
+
+
diff --git a/src/library/scala/collection/generic/Addable.scala b/src/library/scala/collection/generic/Addable.scala
new file mode 100644
index 0000000..f284b24
--- /dev/null
+++ b/src/library/scala/collection/generic/Addable.scala
@@ -0,0 +1,55 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+package scala.collection
+package generic
+
+/** This trait represents collection-like objects that can be added to
+ *  using a '+' operator. It defines variants of `+` and `++`
+ *  as convenience methods in terms of single-element addition `+`.
+ *  @tparam   A    the type of the elements of the $coll
+ *  @tparam   Repr the type of the $coll itself
+ *  @author   Martin Odersky
+ *  @version 2.8
+ *  @since   2.8
+ *  @define  $coll collection
+ *  @define  $Coll Addable
+ */
+trait Addable[A, +Repr <: Addable[A, Repr]] { self => 
+
+  /** The representation object of type `Repr` which contains the collection's elements
+   */
+  protected def repr: Repr
+
+  /** Creates a new $coll with an additional element, unless the element is already present.
+   *  @param elem the element to add
+   *  @return a fresh collection with `elem` added.
+   */
+  def +(elem: A): Repr
+
+  /** Creates a new $coll with additional elements. 
+   *
+   *  This method takes two or more elements to be added. Another overloaded
+   *  variant of this method handles the case where a single element is
+   *  added.
+   *  @param elem1 the first element to add.
+   *  @param elem2 the second element to add.
+   *  @param elems the remaining elements to add.
+   *  @return   a new $coll with the given elements added.
+   */
+  def + (elem1: A, elem2: A, elems: A*): Repr =
+    this + elem1 + elem2 ++ elems
+
+  /** Creates a new $coll by adding all elements contained in another collection to this $coll.
+   *
+   *  @param elems     the collection containing the added elements.
+   *  @return a new $coll with the given elements added.
+   */
+  def ++ (xs: TraversableOnce[A]): Repr = (repr /: xs) (_ + _)
+}
diff --git a/src/library/scala/collection/generic/BitSetFactory.scala b/src/library/scala/collection/generic/BitSetFactory.scala
new file mode 100644
index 0000000..375f534
--- /dev/null
+++ b/src/library/scala/collection/generic/BitSetFactory.scala
@@ -0,0 +1,38 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+package generic
+
+import scala.collection._
+import mutable.Builder
+
+/** @define coll collection
+ *  @define Coll Traversable
+ *  @define factoryInfo
+ *    This object provides a set of operations to create `$Coll` values.
+ *    @author Martin Odersky
+ *    @version 2.8
+ *  @define canBuildFromInfo
+ *    The standard `CanBuildFrom` instance for $Coll objects.
+ *    @see CanBuildFrom
+ *  @define bitsetCanBuildFrom
+ *    The standard `CanBuildFrom` instance for bitsets.
+ */
+trait BitSetFactory[Coll <: BitSet with BitSetLike[Coll]] { 
+  def empty: Coll
+  def newBuilder: Builder[Int, Coll]
+  def apply(elems: Int*): Coll = (empty /: elems) (_ + _)
+  def bitsetCanBuildFrom = new CanBuildFrom[Coll, Int, Coll] {
+    def apply(from: Coll) = newBuilder
+    def apply() = newBuilder
+  }
+}
+
diff --git a/src/library/scala/collection/generic/CanBuildFrom.scala b/src/library/scala/collection/generic/CanBuildFrom.scala
new file mode 100644
index 0000000..ce18f96
--- /dev/null
+++ b/src/library/scala/collection/generic/CanBuildFrom.scala
@@ -0,0 +1,46 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+package scala.collection
+package generic
+
+import mutable.Builder
+import scala.annotation.implicitNotFound
+
+/** A base trait for builder factories.      
+ *
+ *  @tparam From  the type of the underlying collection that requests
+ *                a builder to be created.
+ *  @tparam Elem  the element type of the collection to be created.
+ *  @tparam To    the type of the collection to be created.
+ *
+ *  @see Builder 
+ *  @author Martin Odersky
+ *  @author Adriaan Moors
+ *  @since 2.8
+ */
+ at implicitNotFound(msg = "Cannot construct a collection of type ${To} with elements of type ${Elem} based on a collection of type ${To}.")
+trait CanBuildFrom[-From, -Elem, +To] {
+
+  /** Creates a new builder on request of a collection.
+   *  @param from  the collection requesting the builder to be created.
+   *  @return a builder for collections of type `To` with element type `Elem`.
+   *          The collections framework usually arranges things so
+   *          that the created builder will build the same kind of collection
+   *          as `from`.
+   */
+  def apply(from: From): Builder[Elem, To]
+
+  /** Creates a new builder from scratch.
+   *
+   *  @return a builder for collections of type `To` with element type `Elem`.
+   *  @see scala.collection.breakOut
+   */
+  def apply(): Builder[Elem, To]
+}
diff --git a/src/library/scala/collection/generic/FilterMonadic.scala b/src/library/scala/collection/generic/FilterMonadic.scala
new file mode 100644
index 0000000..a4a796e
--- /dev/null
+++ b/src/library/scala/collection/generic/FilterMonadic.scala
@@ -0,0 +1,11 @@
+package scala.collection.generic
+
+/** A template trait that contains just the `map`, `flatMap`, `foreach` and `withFilter` methods
+ *  of trait `TraversableLike`.
+ */
+trait FilterMonadic[+A, +Repr] {
+  def map[B, That](f: A => B)(implicit bf: CanBuildFrom[Repr, B, That]): That
+  def flatMap[B, That](f: A => Traversable[B])(implicit bf: CanBuildFrom[Repr, B, That]): That
+  def foreach[U](f: A => U): Unit
+  def withFilter(p: A => Boolean): FilterMonadic[A, Repr]
+}
diff --git a/src/library/scala/collection/generic/GenericCompanion.scala b/src/library/scala/collection/generic/GenericCompanion.scala
new file mode 100644
index 0000000..5266538
--- /dev/null
+++ b/src/library/scala/collection/generic/GenericCompanion.scala
@@ -0,0 +1,50 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+package generic
+
+import mutable.Builder
+
+/** A template class for companion objects of ``regular'' collection classes
+ *  represent an unconstrained higher-kinded type. Typically
+ *  such classes inherit from trait `GenericTraversableTemplate`.
+ *  @tparam  CC   The type constructor representing the collection class.
+ *  @see GenericTraversableTemplate
+ *  @author Martin Odersky
+ *  @since 2.8
+ *  @define coll  collection
+ *  @define Coll  CC
+ */
+abstract class GenericCompanion[+CC[X] <: Traversable[X]] { 
+  /** The underlying collection type with unknown element type */
+  type Coll = CC[_]  
+
+  /** The default builder for `$Coll` objects.
+   *  @tparam A      the type of the ${coll}'s elements
+   */
+  def newBuilder[A]: Builder[A, CC[A]]
+
+  /** An empty collection of type `$Coll[A]`
+   *  @tparam A      the type of the ${coll}'s elements
+   */
+  def empty[A]: CC[A] = newBuilder[A].result
+ 
+  /** Creates a $coll with the specified elements.
+   *  @tparam A      the type of the ${coll}'s elements
+   *  @param elems  the elements of the created $coll
+   *  @return a new $coll with elements `elems`
+   */
+  def apply[A](elems: A*): CC[A] = {
+    val b = newBuilder[A]
+    b ++= elems
+    b.result
+  }	
+}
diff --git a/src/library/scala/collection/generic/GenericSetTemplate.scala b/src/library/scala/collection/generic/GenericSetTemplate.scala
new file mode 100644
index 0000000..937179b
--- /dev/null
+++ b/src/library/scala/collection/generic/GenericSetTemplate.scala
@@ -0,0 +1,20 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+package generic
+
+/**
+ * @since 2.8
+ */
+trait GenericSetTemplate[A, +CC[X] <: Set[X]] extends GenericTraversableTemplate[A, CC] { 
+  def empty: CC[A] = companion.empty[A]
+}
+
diff --git a/src/library/scala/collection/generic/GenericTraversableTemplate.scala b/src/library/scala/collection/generic/GenericTraversableTemplate.scala
new file mode 100644
index 0000000..1c5b78a
--- /dev/null
+++ b/src/library/scala/collection/generic/GenericTraversableTemplate.scala
@@ -0,0 +1,124 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+package generic
+
+import mutable.Builder
+import annotation.unchecked.uncheckedVariance
+
+/** A template class for companion objects of ``regular'' collection classes
+ *  that represent an unconstrained higher-kinded type.
+ *  @tparam  A    The type of the collection elements.
+ *  @tparam  CC   The type constructor representing the collection class.
+ *  @author Martin Odersky
+ *  @since 2.8
+ *  @define coll  collection
+ *  @define Coll  CC
+ */
+trait GenericTraversableTemplate[+A, +CC[X] <: Traversable[X]] extends HasNewBuilder[A, CC[A] @uncheckedVariance] { 
+
+  /** Applies a function `f` to all elements of this $coll.
+   *
+   *  @param  f   the function that is applied for its side-effect to every element.
+   *              The result of function `f` is discarded.
+   *              
+   *  @tparam  U  the type parameter describing the result of function `f`. 
+   *              This result will always be ignored. Typically `U` is `Unit`,
+   *              but this is not necessary.
+   *
+   *  @usecase def foreach(f: A => Unit): Unit
+   */
+  def foreach[U](f: A => U): Unit
+
+  /** Selects the first element of this $coll.
+   *  @return  the first element of this $coll.
+   *  @throws `NoSuchElementException` if the $coll is empty.
+   */
+  def head: A
+
+  /** Tests whether this $coll is empty.
+   *
+   *  @return    `true` if the $coll contain no elements, `false` otherwise.
+   */
+  def isEmpty: Boolean
+
+  /** The factory companion object that builds instances of class $Coll.
+   *  (or its `Iterable` superclass where class $Coll is not a `Seq`.) 
+   */
+  def companion: GenericCompanion[CC]
+
+  /** The builder that builds instances of type $Coll[A]
+   */
+  protected[this] def newBuilder: Builder[A, CC[A]] = companion.newBuilder[A]
+
+  /** The generic builder that builds instances of $Coll
+   *  at arbitrary element types.
+   */
+  def genericBuilder[B]: Builder[B, CC[B]] = companion.newBuilder[B]
+
+  /** Converts this $coll of pairs into two collections of the first and second
+   *  halfs of each pair.
+   *  @param A1 the type of the first half of the element pairs
+   *  @param A2 the type of the second half of the element pairs
+   *  @param asPair an implicit conversion which asserts that the element type of this
+   *          $coll is a pair.
+   *  @return a pair ${coll}s, containing the first, respectively second half
+   *          of each element pair of this $coll.
+   */
+  def unzip[A1, A2](implicit asPair: A => /*<:<!!!*/ (A1, A2)): (CC[A1], CC[A2]) = {
+    val b1 = genericBuilder[A1]
+    val b2 = genericBuilder[A2]
+    for (xy <- this) {
+      val (x, y) = asPair(xy)
+      b1 += x
+      b2 += y
+    }
+    (b1.result, b2.result)
+  }
+
+  /** Converts this $coll of traversable collections into
+   *  a $coll in which all element collections are concatenated.
+   *  @tparam B the type of the elements of each traversable collection. 
+   *  @param asTraversable an implicit conversion which asserts that the element type of this
+   *         $coll is a `Traversable`.
+   *  @return a new $coll resulting from concatenating all element ${coll}s.
+   *  @usecase def flatten[B]: $Coll[B]
+   */
+  def flatten[B](implicit asTraversable: A => /*<:<!!!*/ Traversable[B]): CC[B] = {
+    val b = genericBuilder[B]
+    for (xs <- this)
+      b ++= asTraversable(xs)
+    b.result
+  }
+
+  /** Transposes this $coll of traversable collections into
+   *  a $coll of ${coll}s.
+   *  @tparam B the type of the elements of each traversable collection.
+   *  @param  asTraversable an implicit conversion which asserts that the element type of this
+   *          $coll is a `Traversable`.
+   *  @return a two-dimensional $coll of ${coll}s which has as ''n''th row
+   *          the ''n''th column of this $coll. 
+   */
+  def transpose[B](implicit asTraversable: A => /*<:<!!!*/ Traversable[B]): CC[CC[B] @uncheckedVariance] = {
+    val bs: IndexedSeq[Builder[B, CC[B]]] = IndexedSeq.fill(asTraversable(head).size)(genericBuilder[B])
+    for (xs <- this) {
+      var i = 0
+      for (x <- asTraversable(xs)) {
+        bs(i) += x
+        i += 1
+      }
+    }
+    val bb = genericBuilder[CC[B]]
+    for (b <- bs) bb += b.result
+    bb.result
+  }
+}
+
diff --git a/src/library/scala/collection/generic/Growable.scala b/src/library/scala/collection/generic/Growable.scala
new file mode 100644
index 0000000..7aaabf7
--- /dev/null
+++ b/src/library/scala/collection/generic/Growable.scala
@@ -0,0 +1,54 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+package scala.collection
+package generic 
+
+/** This trait forms part of collections that can be augmented
+ *  using a `+=` operator and that can be cleared of all elements using
+ *  a `clear` method.
+ *        
+ *  @author   Martin Odersky
+ *  @version 2.8
+ *  @since   2.8
+ *  @define coll growable collection
+ *  @define Coll Growable
+ *  @define add  add
+ *  @define Add  add
+ */
+trait Growable[-A] { 
+
+  /** ${Add}s a single element to this $coll.
+   *
+   *  @param elem  the element to $add.
+   *  @return the $coll itself
+   */
+  def +=(elem: A): this.type
+
+  /** ${Add}s two or more elements to this $coll.
+   *
+   *  @param elem1 the first element to $add.
+   *  @param elem2 the second element to $add.
+   *  @param elems the remaining elements to $add.
+   *  @return the $coll itself
+   */
+  def +=(elem1: A, elem2: A, elems: A*): this.type = this += elem1 += elem2 ++= elems
+
+  /** ${Add}s all elements produced by a TraversableOnce to this $coll.
+   *
+   *  @param iter  the TraversableOnce producing the elements to $add.
+   *  @return  the $coll itself. 
+   */
+  def ++=(xs: TraversableOnce[A]): this.type = { xs foreach += ; this } 
+
+  /** Clears the $coll's contents. After this operation, the
+   *  $coll is empty.
+   */
+  def clear()
+}
diff --git a/src/library/scala/collection/generic/HasNewBuilder.scala b/src/library/scala/collection/generic/HasNewBuilder.scala
new file mode 100644
index 0000000..e36813e
--- /dev/null
+++ b/src/library/scala/collection/generic/HasNewBuilder.scala
@@ -0,0 +1,16 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+package scala.collection
+package generic
+
+import mutable.Builder
+
+trait HasNewBuilder[+A, +Repr] {
+  /** The builder that builds instances of Repr */
+  protected[this] def newBuilder: Builder[A, Repr]
+}
diff --git a/src/library/scala/collection/generic/ImmutableMapFactory.scala b/src/library/scala/collection/generic/ImmutableMapFactory.scala
new file mode 100644
index 0000000..55568d9
--- /dev/null
+++ b/src/library/scala/collection/generic/ImmutableMapFactory.scala
@@ -0,0 +1,18 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+package scala.collection
+package generic
+
+/** A template for companion objects of `immutable.Map` and subclasses thereof.
+ *    @author Martin Odersky
+ *    @version 2.8
+ *    @since 2.8
+ */
+abstract class ImmutableMapFactory[CC[A, +B] <: immutable.Map[A, B] with immutable.MapLike[A, B, CC[A, B]]] extends MapFactory[CC] 
diff --git a/src/library/scala/collection/generic/ImmutableSetFactory.scala b/src/library/scala/collection/generic/ImmutableSetFactory.scala
new file mode 100644
index 0000000..5ee18a7
--- /dev/null
+++ b/src/library/scala/collection/generic/ImmutableSetFactory.scala
@@ -0,0 +1,18 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+package scala.collection
+package generic
+
+import mutable.{ Builder, AddingBuilder }
+
+abstract class ImmutableSetFactory[CC[X] <: immutable.Set[X] with SetLike[X, CC[X]]]
+  extends SetFactory[CC] {
+    
+  def newBuilder[A]: Builder[A, CC[A]] = new AddingBuilder[A, CC[A]](empty[A])
+}
diff --git a/src/library/scala/collection/generic/ImmutableSortedMapFactory.scala b/src/library/scala/collection/generic/ImmutableSortedMapFactory.scala
new file mode 100644
index 0000000..149a9c3
--- /dev/null
+++ b/src/library/scala/collection/generic/ImmutableSortedMapFactory.scala
@@ -0,0 +1,26 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+package generic
+
+/** A template for companion objects of `SortedMap` and subclasses thereof.
+ *
+ *  @since 2.8
+ *  @define Coll SortedMap
+ *  @define coll sorted map
+ *  @define factoryInfo
+ *    This object provides a set of operations needed to create sorted maps of type `$Coll`.
+ *    @author Martin Odersky
+ *    @version 2.8
+ *  @define sortedMapCanBuildFromInfo
+ *    The standard `CanBuildFrom` instance for sorted maps
+ */
+abstract class ImmutableSortedMapFactory[CC[A, B] <: immutable.SortedMap[A, B] with SortedMapLike[A, B, CC[A, B]]] extends SortedMapFactory[CC] 
diff --git a/src/library/scala/collection/generic/ImmutableSortedSetFactory.scala b/src/library/scala/collection/generic/ImmutableSortedSetFactory.scala
new file mode 100644
index 0000000..20ca840
--- /dev/null
+++ b/src/library/scala/collection/generic/ImmutableSortedSetFactory.scala
@@ -0,0 +1,26 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+package generic
+
+/** A template for companion objects of `SortedSet` and subclasses thereof.
+ *  
+ *  @since 2.8
+ *  @define Coll immutable.SortedSet
+ *  @define coll immutable sorted 
+ *  @define factoryInfo
+ *    This object provides a set of operations needed to create sorted sets of type `$Coll`.
+ *    @author Martin Odersky
+ *    @version 2.8
+ *  @define sortedSetCanBuildFromInfo
+ *    The standard `CanBuildFrom` instance for sorted sets
+ */
+abstract class ImmutableSortedSetFactory[CC[A] <: immutable.SortedSet[A] with SortedSetLike[A, CC[A]]] extends SortedSetFactory[CC]
\ No newline at end of file
diff --git a/src/library/scala/collection/generic/IterableForwarder.scala b/src/library/scala/collection/generic/IterableForwarder.scala
new file mode 100644
index 0000000..3313d90
--- /dev/null
+++ b/src/library/scala/collection/generic/IterableForwarder.scala
@@ -0,0 +1,45 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection.generic
+import scala.collection._
+
+import collection.mutable.Buffer
+
+/** <p>
+ *    This trait implements a forwarder for iterable objects. It forwards
+ *    all calls to a different iterable object, except for
+ *  </p>
+ *  <ul>
+ *    <li><code>toString</code>, <code>hashCode</code>, <code>equals</code>,
+ *      <code>stringPrefix</code></li>
+ *    <li><code>newBuilder</code>, <code>view</code></li>
+ *    <li>all calls creating a new iterable object of the same kind</li>
+ *  </ul>
+ *  <p>
+ *    The above methods are forwarded by subclass <a href="../IterableProxy.html"
+ *    target="ContentFrame"><code>IterableProxy</code></a>.
+ *  </p>
+ *
+ *  @author  Martin Odersky
+ *  @version 2.8
+ *  @since   2.8
+ */
+trait IterableForwarder[+A] extends Iterable[A] with TraversableForwarder[A] {
+
+  /** The iterable object to which calls are forwarded */
+  protected def underlying: Iterable[A]
+  
+  // Iterable delegates
+  // Iterable methods could be printed by  cat IterableLike.scala | sed -n '/trait Iterable/,$ p' | egrep '^  (override )?def'
+  
+  override def iterator: Iterator[A] = underlying.iterator
+  override def sameElements[B >: A](that: Iterable[B]): Boolean = underlying.sameElements(that)
+}
diff --git a/src/library/scala/collection/generic/MapFactory.scala b/src/library/scala/collection/generic/MapFactory.scala
new file mode 100644
index 0000000..916024e
--- /dev/null
+++ b/src/library/scala/collection/generic/MapFactory.scala
@@ -0,0 +1,62 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+package generic
+
+import mutable.{Builder, MapBuilder}
+
+/** A template for companion objects of `Map` and subclasses thereof.
+ *
+ *  @define coll map
+ *  @define Coll Map
+ *  @define factoryInfo
+ *    This object provides a set of operations needed to create `$Coll` values.
+ *    @author Martin Odersky
+ *    @version 2.8
+ *    @since 2.8
+ *  @define canBuildFromInfo
+ *    The standard `CanBuildFrom` instance for `$Coll` objects.
+ *    @see CanBuildFrom
+ *  @define mapCanBuildFromInfo
+ *    The standard `CanBuildFrom` instance for `$Coll` objects.
+ *    The created value is an instance of class `MapCanBuildFrom`.
+ *    @see CanBuildFrom
+ *    @see GenericCanBuildFrom
+ */
+abstract class MapFactory[CC[A, B] <: Map[A, B] with MapLike[A, B, CC[A, B]]] {
+
+  /** The type constructor of the collection that can be built by this factory */
+  type Coll = CC[_, _]
+
+  /** An empty $Coll */
+  def empty[A, B]: CC[A, B]
+
+  /** A collection of type $Coll that contains given key/value bindings.
+   *  @param elems   the key/value pairs that make up the $coll
+   *  @tparam A      the type of the keys
+   *  @tparam B      the type of the associated values
+   *  @return        a new $coll consisting key/value pairs given by `elems`.
+   */
+  def apply[A, B](elems: (A, B)*): CC[A, B] = (newBuilder[A, B] ++= elems).result
+
+  /** The default builder for $Coll objects.
+   *  @tparam A      the type of the keys
+   *  @tparam B      the type of the associated values
+   */
+  def newBuilder[A, B]: Builder[(A, B), CC[A, B]] = new MapBuilder[A, B, CC[A, B]](empty[A, B])
+
+  /** The standard `CanBuildFrom` class for maps.
+   */
+  class MapCanBuildFrom[A, B] extends CanBuildFrom[Coll, (A, B), CC[A, B]] {
+    def apply(from: Coll) = newBuilder[A, B]
+    def apply() = newBuilder
+  }
+}
diff --git a/src/library/scala/collection/generic/MutableMapFactory.scala b/src/library/scala/collection/generic/MutableMapFactory.scala
new file mode 100644
index 0000000..26b1fae
--- /dev/null
+++ b/src/library/scala/collection/generic/MutableMapFactory.scala
@@ -0,0 +1,29 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+package generic
+
+import mutable.Builder
+
+/** A template for companion objects of `mutable.Map` and subclasses thereof.
+ *    @author Martin Odersky
+ *    @version 2.8
+ *    @since 2.8
+ */
+abstract class MutableMapFactory[CC[A, B] <: mutable.Map[A, B] with mutable.MapLike[A, B, CC[A, B]]] 
+  extends MapFactory[CC] {
+
+  /** The default builder for $Coll objects.
+   *  @tparam A      the type of the keys
+   *  @tparam B      the type of the associated values
+   */
+  override def newBuilder[A, B]: Builder[(A, B), CC[A, B]] = empty[A, B]
+}
diff --git a/src/library/scala/collection/generic/MutableSetFactory.scala b/src/library/scala/collection/generic/MutableSetFactory.scala
new file mode 100644
index 0000000..eca1e9b
--- /dev/null
+++ b/src/library/scala/collection/generic/MutableSetFactory.scala
@@ -0,0 +1,18 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+package scala.collection
+package generic
+
+import mutable.{ Builder, GrowingBuilder }
+
+abstract class MutableSetFactory[CC[X] <: mutable.Set[X] with mutable.SetLike[X, CC[X]]]
+  extends SetFactory[CC] {
+    
+  def newBuilder[A]: Builder[A, CC[A]] = new GrowingBuilder[A, CC[A]](empty[A])
+}
diff --git a/src/library/scala/collection/generic/SeqFactory.scala b/src/library/scala/collection/generic/SeqFactory.scala
new file mode 100644
index 0000000..1671695
--- /dev/null
+++ b/src/library/scala/collection/generic/SeqFactory.scala
@@ -0,0 +1,26 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+package generic
+
+/** A template for companion objects of Seq and subclasses thereof.
+ *
+ *  @since 2.8
+ */
+abstract class SeqFactory[CC[X] <: Seq[X] with GenericTraversableTemplate[X, CC]] extends TraversableFactory[CC] {
+  
+  /** This method is called in a pattern match { case Seq(...) => }.
+   *
+   *  @param x the selector value
+   *  @return  sequence wrapped in an option, if this is a Seq, otherwise none
+   */
+  def unapplySeq[A](x: CC[A]): Some[CC[A]] = Some(x)
+}
diff --git a/src/library/scala/collection/generic/SeqForwarder.scala b/src/library/scala/collection/generic/SeqForwarder.scala
new file mode 100644
index 0000000..eec126c
--- /dev/null
+++ b/src/library/scala/collection/generic/SeqForwarder.scala
@@ -0,0 +1,59 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection.generic
+import scala.collection._
+import scala.collection.immutable.Range
+
+/** This class implements a forwarder for sequences. It forwards
+ *  all calls to a different sequence object except for
+ *
+ *    - toString, hashCode, equals, stringPrefix
+ *    - newBuilder, view, toSeq
+ *    - all calls creating a new sequence of the same kind
+ *
+ *  The above methods are forwarded by subclass SeqProxy
+ *
+ *  @author  Martin Odersky
+ *  @version 2.8
+ *  @since   2.8
+ */
+trait SeqForwarder[+A] extends Seq[A] with IterableForwarder[A] {
+
+  protected override def underlying: Seq[A] 
+  
+  override def length: Int = underlying.length
+  override def apply(idx: Int): A = underlying.apply(idx)
+  override def lengthCompare(len: Int): Int = underlying.lengthCompare(len)
+  override def isDefinedAt(x: Int): Boolean = underlying.isDefinedAt(x)
+  override def segmentLength(p: A => Boolean, from: Int): Int = underlying.segmentLength(p, from)
+  override def prefixLength(p: A => Boolean) = underlying.prefixLength(p)
+  override def indexWhere(p: A => Boolean): Int = underlying.indexWhere(p)
+  override def indexWhere(p: A => Boolean, from: Int): Int = underlying.indexWhere(p, from)
+  override def findIndexOf(p: A => Boolean): Int = underlying.indexWhere(p)
+  override def indexOf[B >: A](elem: B): Int = underlying.indexOf(elem)
+  override def indexOf[B >: A](elem: B, from: Int): Int = underlying.indexOf(elem, from)
+  override def lastIndexOf[B >: A](elem: B): Int = underlying.lastIndexOf(elem)
+  override def lastIndexOf[B >: A](elem: B, end: Int): Int = underlying.lastIndexOf(elem, end)
+  override def lastIndexWhere(p: A => Boolean): Int = underlying.lastIndexWhere(p)
+  override def lastIndexWhere(p: A => Boolean, end: Int): Int = underlying.lastIndexWhere(p, end)
+  override def reverseIterator: Iterator[A] = underlying.reverseIterator
+  override def startsWith[B](that: Seq[B], offset: Int): Boolean = underlying.startsWith(that, offset)
+  override def startsWith[B](that: Seq[B]): Boolean = underlying.startsWith(that)
+  override def endsWith[B](that: Seq[B]): Boolean = underlying.endsWith(that)
+  override def indexOfSlice[B >: A](that: Seq[B]): Int = underlying.indexOfSlice(that)
+  override def indexOfSlice[B >: A](that: Seq[B], from: Int): Int = underlying.indexOfSlice(that, from)
+  override def lastIndexOfSlice[B >: A](that: Seq[B]): Int = underlying.lastIndexOfSlice(that)
+  override def lastIndexOfSlice[B >: A](that: Seq[B], end: Int): Int = underlying.lastIndexOfSlice(that, end)
+  override def containsSlice[B](that: Seq[B]): Boolean = underlying.containsSlice(that)
+  override def contains(elem: Any): Boolean = underlying.contains(elem)
+  override def corresponds[B](that: Seq[B])(p: (A,B) => Boolean): Boolean = underlying.corresponds(that)(p)
+  override def indices: Range = underlying.indices
+}
diff --git a/src/library/scala/collection/generic/SetFactory.scala b/src/library/scala/collection/generic/SetFactory.scala
new file mode 100644
index 0000000..3d7dbbf
--- /dev/null
+++ b/src/library/scala/collection/generic/SetFactory.scala
@@ -0,0 +1,44 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+package generic
+
+import mutable.Builder
+
+/** A template for companion objects of `Set` and subclasses thereof.
+ *
+ *  @define coll set
+ *  @define Coll Set
+ *  @define factoryInfo
+ *    This object provides a set of operations needed to create `$Coll` values.
+ *    @author Martin Odersky
+ *    @version 2.8
+ *    @since 2.8
+ *  @define canBuildFromInfo
+ *    The standard `CanBuildFrom` instance for `$Coll` objects.
+ *    @see CanBuildFrom
+ *  @define setCanBuildFromInfo
+ *    The standard `CanBuildFrom` instance for `$Coll` objects.
+ *    @see CanBuildFrom
+ *    @see GenericCanBuildFrom
+ */
+abstract class SetFactory[CC[X] <: Set[X] with SetLike[X, CC[X]]]
+  extends GenericCompanion[CC] {
+    
+  def newBuilder[A]: Builder[A, CC[A]]
+
+  /** $setCanBuildFromInfo
+   */
+  def setCanBuildFrom[A] = new CanBuildFrom[CC[_], A, CC[A]] {
+    def apply(from: CC[_]) = newBuilder[A]
+    def apply() = newBuilder[A]
+  }
+}
diff --git a/src/library/scala/collection/generic/Shrinkable.scala b/src/library/scala/collection/generic/Shrinkable.scala
new file mode 100644
index 0000000..83457d4
--- /dev/null
+++ b/src/library/scala/collection/generic/Shrinkable.scala
@@ -0,0 +1,54 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+package scala.collection
+package generic
+
+/** This trait forms part of collections that can be reduced
+ *  using a `-=` operator.
+ *        
+ *  @author   Martin Odersky
+ *  @version 2.8
+ *  @since   2.8
+ *  @define coll shrinkable collection
+ *  @define Coll Shrinkable
+ */
+trait Shrinkable[-A] { 
+
+  /** Removes a single element from this $coll.
+   *
+   *  @param elem  the element to remove.
+   *  @return the $coll itself
+   */
+  def -=(elem: A): this.type
+
+  /** Removes two or more elements from this $coll.
+   *
+   *  @param elem1 the first element to remove.
+   *  @param elem2 the second element to remove.
+   *  @param elems the remaining elements to remove.
+   *  @return the $coll itself
+   */
+  def -=(elem1: A, elem2: A, elems: A*): this.type = {
+    this -= elem1 
+    this -= elem2
+    this --= elems
+  }
+
+  /** Removes all elements produced by an iterator from this $coll.
+   *
+   *  @param iter  the iterator producing the elements to remove.
+   *  @return the $coll itself
+   */
+  def --=(xs: TraversableOnce[A]): this.type = { xs foreach -= ; this }
+}
+  
+
+  
+
diff --git a/src/library/scala/collection/generic/Sorted.scala b/src/library/scala/collection/generic/Sorted.scala
new file mode 100644
index 0000000..c379178
--- /dev/null
+++ b/src/library/scala/collection/generic/Sorted.scala
@@ -0,0 +1,101 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2006-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+package scala.collection
+package generic
+
+/** Any collection (including maps) whose keys (or elements) are ordered.
+ *
+ *  @author Sean McDirmid
+ *  @since  2.8
+ */
+trait Sorted[K, +This <: Sorted[K, This]] {
+  def ordering : Ordering[K]
+
+  /** The current collection */
+  protected def repr: This
+
+  /** return as a projection the set of keys in this collection */
+  def keySet: SortedSet[K]
+
+  /** Returns the first key of the collection. */
+  def firstKey: K
+
+  /** Returns the last key of the collection. */
+  def lastKey: K
+
+  /** Comparison function that orders keys. */
+  def compare(k0: K, k1: K): Int = ordering.compare(k0, k1);
+ 
+  /** Creates a ranged projection of this collection. Any mutations in the
+   *  ranged projection will update this collection and vice versa.  Note: keys
+   *  are not garuanteed to be consistent between this collection and the projection.
+   *  This is the case for buffers where indexing is relative to the projection. 
+   *
+   *  @param from  The lower-bound (inclusive) of the ranged projection.
+   *               <code>None</code> if there is no lower bound.
+   *  @param until The upper-bound (exclusive) of the ranged projection.
+   *               <code>None</code> if there is no upper bound.
+   */
+  def rangeImpl(from: Option[K], until: Option[K]): This
+
+  /** Creates a ranged projection of this collection with no upper-bound.
+   *
+   *  @param from The lower-bound (inclusive) of the ranged projection.
+   */
+  def from(from: K): This = rangeImpl(Some(from), None)
+
+  /** Creates a ranged projection of this collection with no lower-bound.
+   *
+   *  @param until The upper-bound (exclusive) of the ranged projection.
+   */
+  def until(until: K): This = rangeImpl(None, Some(until))
+  
+  /** Creates a ranged projection of this collection with both a lower-bound
+   *  and an upper-bound.
+   *
+   *  @param from  The upper-bound (exclusive) of the ranged projection.
+   *  @param until ...
+   *  @return      ...
+   */
+  def range(from: K, until: K): This = rangeImpl(Some(from), Some(until))
+  
+  /** Create a range projection of this collection with no lower-bound.
+   *  @param to The upper-bound (inclusive) of the ranged projection.
+   */
+  def to(to: K): This = {
+    // tough!
+    val i = keySet.from(to).iterator
+    if (i.isEmpty) return repr
+    val next = i.next
+    if (next == to)
+      if (i.isEmpty) repr
+      else until(i.next)
+    else
+      until(next)
+  }
+
+  protected def hasAll(j: Iterator[K]): Boolean = {
+    val i = keySet.iterator
+    if (i.isEmpty) return j.isEmpty
+
+    var in = i.next;
+    while (j.hasNext) {
+      val jn = j.next;
+      while ({
+        val n = compare(jn, in);
+        if (n == 0) false;
+        else if (n < 0) return false;
+        else if (!i.hasNext) return false;
+        else true;
+      }) in = i.next;
+    }
+    true
+  }      
+}
diff --git a/src/library/scala/collection/generic/SortedMapFactory.scala b/src/library/scala/collection/generic/SortedMapFactory.scala
new file mode 100644
index 0000000..1e960bf
--- /dev/null
+++ b/src/library/scala/collection/generic/SortedMapFactory.scala
@@ -0,0 +1,35 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+package generic
+
+import mutable.{Builder, MapBuilder}
+
+/** A template for companion objects of mutable.Map and subclasses thereof.
+ *
+ *  @since 2.8
+ */
+abstract class SortedMapFactory[CC[A, B] <: SortedMap[A, B] with SortedMapLike[A, B, CC[A, B]]] {
+
+  type Coll = CC[_, _]
+
+  def empty[A, B](implicit ord: Ordering[A]): CC[A, B]
+
+  def apply[A, B](elems: (A, B)*)(implicit ord: Ordering[A]): CC[A, B] = (newBuilder[A, B](ord) ++= elems).result
+
+  def newBuilder[A, B](implicit ord: Ordering[A]): Builder[(A, B), CC[A, B]] =
+    new MapBuilder[A, B, CC[A, B]](empty(ord))
+
+  class SortedMapCanBuildFrom[A, B](implicit ord: Ordering[A]) extends CanBuildFrom[Coll, (A, B), CC[A, B]] {
+    def apply(from: Coll) = newBuilder[A, B](ord)
+    def apply() = newBuilder[A, B]
+  }
+}
diff --git a/src/library/scala/collection/generic/SortedSetFactory.scala b/src/library/scala/collection/generic/SortedSetFactory.scala
new file mode 100644
index 0000000..9144cc8
--- /dev/null
+++ b/src/library/scala/collection/generic/SortedSetFactory.scala
@@ -0,0 +1,35 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2006-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+package generic
+
+import mutable.{Builder, SetBuilder}
+
+/** A template for companion objects of Set and subclasses thereof.
+ *
+ *  @since 2.8
+ */
+abstract class SortedSetFactory[CC[A] <: SortedSet[A] with SortedSetLike[A, CC[A]]] {
+  type Coll = CC[_]
+
+  def empty[A](implicit ord: Ordering[A]): CC[A]
+
+  def apply[A](elems: A*)(implicit ord: Ordering[A]): CC[A] = (newBuilder[A](ord) ++= elems).result
+
+  def newBuilder[A](implicit ord: Ordering[A]): Builder[A, CC[A]] = new SetBuilder[A, CC[A]](empty)
+
+  implicit def newCanBuildFrom[A](implicit ord : Ordering[A]) : CanBuildFrom[Coll, A, CC[A]] = new SortedSetCanBuildFrom()(ord);
+
+  class SortedSetCanBuildFrom[A](implicit ord: Ordering[A]) extends CanBuildFrom[Coll, A, CC[A]] {
+    def apply(from: Coll) = newBuilder[A](ord)
+    def apply() = newBuilder[A](ord)
+  }
+}
diff --git a/src/library/scala/collection/generic/Subtractable.scala b/src/library/scala/collection/generic/Subtractable.scala
new file mode 100644
index 0000000..87eb81b
--- /dev/null
+++ b/src/library/scala/collection/generic/Subtractable.scala
@@ -0,0 +1,59 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+package scala.collection
+package generic
+
+/** This trait represents collection-like objects that can be reduced 
+ *  using a '+' operator. It defines variants of `-` and `--`
+ *  as convenience methods in terms of single-element removal `-`.
+ *  @tparam   A    the type of the elements of the $coll.
+ *  @tparam   Repr the type of the $coll itself
+ *  @author   Martin Odersky
+ *  @version 2.8
+ *  @since   2.8
+ *  @define  $coll collection
+ *  @define  $Coll Subtractable
+ */
+trait Subtractable[A, +Repr <: Subtractable[A, Repr]] { self =>
+
+  /** The representation object of type `Repr` which contains the collection's elements
+   */
+  protected def repr: Repr
+
+  /** Creates a new $coll from this $coll with an element removed.
+   *  @param elem the element to remove
+   *  @return a new collection that contains all elements of the current $coll
+   *  except one less occurrence of `elem`.
+   */
+  def -(elem: A): Repr
+
+  /** Creates a new $coll from this $coll with some elements removed.
+   *
+   *  This method takes two or more elements to be removed. Another overloaded
+   *  variant of this method handles the case where a single element is
+   *  removed.
+   *  @param elem1 the first element to remove.
+   *  @param elem2 the second element to remove.
+   *  @param elems the remaining elements to remove.
+   *  @return a new $coll that contains all elements of the current $coll
+   *  except one less occurrence of each of the given elements.
+   */
+  def -(elem1: A, elem2: A, elems: A*): Repr =
+    this - elem1 - elem2 -- elems
+
+  /** Creates a new $coll from this $coll by removing all elements of another
+   *  collection.
+   *  
+   *  @param elems     the collection containing the removed elements.
+   *  @return a new $coll that contains all elements of the current $coll
+   *  except one less occurrence of each of the elements of `elems`.
+   */
+  def --(xs: TraversableOnce[A]): Repr = (repr /: xs) (_ - _)
+}
diff --git a/src/library/scala/collection/generic/TraversableFactory.scala b/src/library/scala/collection/generic/TraversableFactory.scala
new file mode 100644
index 0000000..e9caf2b
--- /dev/null
+++ b/src/library/scala/collection/generic/TraversableFactory.scala
@@ -0,0 +1,242 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2006-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+package scala.collection
+package generic
+
+/** A template for companion objects of `Traversable` and subclasses thereof.
+ *  This class provides a set of operations to create `$Coll` objects.
+ *  It is typically inherited by companion objects of subclasses of `Traversable`.
+ *
+ *  @since 2.8
+ *
+ *  @define coll collection
+ *  @define Coll Traversable
+ *  @define factoryInfo
+ *    This object provides a set of operations to create `$Coll` values.
+ *    @author Martin Odersky
+ *    @version 2.8
+ *  @define canBuildFromInfo
+ *    The standard `CanBuildFrom` instance for $Coll objects.
+ *    @see CanBuildFrom
+ *  @define genericCanBuildFromInfo
+ *    The standard `CanBuildFrom` instance for $Coll objects.
+ *    The created value is an instance of class `GenericCanBuildFrom`,
+ *    which forwards calls to create a new builder to the
+ *    `genericBuilder` method of the requesting collection.
+ *    @see CanBuildFrom
+ *    @see GenericCanBuildFrom
+ */
+abstract class TraversableFactory[CC[X] <: Traversable[X] with GenericTraversableTemplate[X, CC]]
+  extends GenericCompanion[CC] {
+
+  /** A generic implementation of the `CanBuildFrom` trait, which forwards
+   *  all calls to `apply(from)` to the `genericBuilder` method of
+   *  $coll `from`, and which forwards all calls of `apply()` to the
+   *  `newBuilder` method of this factory.
+   */
+  class GenericCanBuildFrom[A] extends CanBuildFrom[CC[_], A, CC[A]] {
+    /** Creates a new builder on request of a collection.
+     *  @param from  the collection requesting the builder to be created.
+     *  @return the result of invoking the `genericBuilder` method on `from`.
+     */
+    def apply(from: Coll) = from.genericBuilder[A] 
+    
+    /** Creates a new builder from scratch
+     *  @return the result of invoking the `newBuilder` method of this factory.
+     */
+    def apply() = newBuilder[A]
+  }
+
+  /** Concatenates all argument collections into a single $coll.
+   *
+   *  @param xss the collections that are to be concatenated.
+   *  @return the concatenation of all the collections.
+   */
+  def concat[A](xss: Traversable[A]*): CC[A] = {
+    val b = newBuilder[A]
+    // At present we're using IndexedSeq as a proxy for "has a cheap size method".
+    if (xss forall (_.isInstanceOf[IndexedSeq[_]]))
+      b.sizeHint(xss map (_.size) sum)
+    
+    for (xs <- xss) b ++= xs
+    b.result
+  }
+
+  /** Produces a $coll containing the results of some element computation a number of times.
+   *  @param   n  the number of elements contained in the $coll.
+   *  @param   elem the element computation
+   *  @return  A $coll that contains the results of `n` evaluations of `elem`.
+   */
+  def fill[A](n: Int)(elem: => A): CC[A] = {
+    val b = newBuilder[A]
+    b.sizeHint(n)
+    var i = 0
+    while (i < n) {
+      b += elem
+      i += 1
+    }
+    b.result
+  }
+
+  /** Produces a two-dimensional $coll containing the results of some element computation a number of times.
+   *  @param   n1  the number of elements in the 1st dimension
+   *  @param   n2  the number of elements in the 2nd dimension
+   *  @param   elem the element computation
+   *  @return  A $coll that contains the results of `n1 x n2` evaluations of `elem`.
+   */
+  def fill[A](n1: Int, n2: Int)(elem: => A): CC[CC[A]] = 
+    tabulate(n1)(_ => fill(n2)(elem))
+
+  /** Produces a three-dimensional $coll containing the results of some element computation a number of times.
+   *  @param   n1  the number of elements in the 1st dimension
+   *  @param   n2  the number of elements in the 2nd dimension
+   *  @param   n3  the number of elements in the 3nd dimension
+   *  @param   elem the element computation
+   *  @return  A $coll that contains the results of `n1 x n2 x n3` evaluations of `elem`.
+   */
+  def fill[A](n1: Int, n2: Int, n3: Int)(elem: => A): CC[CC[CC[A]]] = 
+    tabulate(n1)(_ => fill(n2, n3)(elem))
+
+  /** Produces a four-dimensional $coll containing the results of some element computation a number of times.
+   *  @param   n1  the number of elements in the 1st dimension
+   *  @param   n2  the number of elements in the 2nd dimension
+   *  @param   n3  the number of elements in the 3nd dimension
+   *  @param   n4  the number of elements in the 4th dimension
+   *  @param   elem the element computation
+   *  @return  A $coll that contains the results of `n1 x n2 x n3 x n4` evaluations of `elem`.
+   */
+  def fill[A](n1: Int, n2: Int, n3: Int, n4: Int)(elem: => A): CC[CC[CC[CC[A]]]] = 
+    tabulate(n1)(_ => fill(n2, n3, n4)(elem))
+
+  /** Produces a five-dimensional $coll containing the results of some element computation a number of times.
+   *  @param   n1  the number of elements in the 1st dimension
+   *  @param   n2  the number of elements in the 2nd dimension
+   *  @param   n3  the number of elements in the 3nd dimension
+   *  @param   n4  the number of elements in the 4th dimension
+   *  @param   n5  the number of elements in the 5th dimension
+   *  @param   elem the element computation
+   *  @return  A $coll that contains the results of `n1 x n2 x n3 x n4 x n5` evaluations of `elem`.
+   */
+  def fill[A](n1: Int, n2: Int, n3: Int, n4: Int, n5: Int)(elem: => A): CC[CC[CC[CC[CC[A]]]]] = 
+    tabulate(n1)(_ => fill(n2, n3, n4, n5)(elem))
+
+  /** Produces a $coll containing values of a given function over a range of integer values starting from 0.
+   *  @param  n   The number of elements in the $coll
+   *  @param  f   The function computing element values
+   *  @return A $coll consisting of elements `f(0), ..., f(n -1)`
+   */	
+  def tabulate[A](n: Int)(f: Int => A): CC[A] = {
+    val b = newBuilder[A]
+    b.sizeHint(n)
+    var i = 0
+    while (i < n) {
+      b += f(i)
+      i += 1
+    }
+    b.result
+  }
+
+  /** Produces a two-dimensional $coll containing values of a given function over ranges of integer values starting from 0.
+   *  @param   n1  the number of elements in the 1st dimension
+   *  @param   n2  the number of elements in the 2nd dimension
+   *  @param   f   The function computing element values
+   *  @return A $coll consisting of elements `f(i1, i2)`
+   *          for `0 <= i1 < n1` and `0 <= i2 < n2`.
+   */	
+  def tabulate[A](n1: Int, n2: Int)(f: (Int, Int) => A): CC[CC[A]] = 
+    tabulate(n1)(i1 => tabulate(n2)(f(i1, _)))
+
+  /** Produces a three-dimensional $coll containing values of a given function over ranges of integer values starting from 0.
+   *  @param   n1  the number of elements in the 1st dimension
+   *  @param   n2  the number of elements in the 2nd dimension
+   *  @param   n3  the number of elements in the 3nd dimension
+   *  @param   f   The function computing element values
+   *  @return A $coll consisting of elements `f(i1, i2, i3)`
+   *          for `0 <= i1 < n1`, `0 <= i2 < n2`, and `0 <= i3 < n3`.
+   */	
+  def tabulate[A](n1: Int, n2: Int, n3: Int)(f: (Int, Int, Int) => A): CC[CC[CC[A]]] = 
+    tabulate(n1)(i1 => tabulate(n2, n3)(f(i1, _, _)))
+
+  /** Produces a four-dimensional $coll containing values of a given function over ranges of integer values starting from 0.
+   *  @param   n1  the number of elements in the 1st dimension
+   *  @param   n2  the number of elements in the 2nd dimension
+   *  @param   n3  the number of elements in the 3nd dimension
+   *  @param   n4  the number of elements in the 4th dimension
+   *  @param   f   The function computing element values
+   *  @return A $coll consisting of elements `f(i1, i2, i3, i4)`
+   *          for `0 <= i1 < n1`, `0 <= i2 < n2`, `0 <= i3 < n3`, and `0 <= i4 < n4`.
+   */	
+  def tabulate[A](n1: Int, n2: Int, n3: Int, n4: Int)(f: (Int, Int, Int, Int) => A): CC[CC[CC[CC[A]]]] = 
+    tabulate(n1)(i1 => tabulate(n2, n3, n4)(f(i1, _, _, _)))
+
+  /** Produces a five-dimensional $coll containing values of a given function over ranges of integer values starting from 0.
+   *  @param   n1  the number of elements in the 1st dimension
+   *  @param   n2  the number of elements in the 2nd dimension
+   *  @param   n3  the number of elements in the 3nd dimension
+   *  @param   n4  the number of elements in the 4th dimension
+   *  @param   n5  the number of elements in the 5th dimension
+   *  @param   f   The function computing element values
+   *  @return A $coll consisting of elements `f(i1, i2, i3, i4, i5)`
+   *          for `0 <= i1 < n1`, `0 <= i2 < n2`, `0 <= i3 < n3`, `0 <= i4 < n4`, and `0 <= i5 < n5`.
+   */	
+  def tabulate[A](n1: Int, n2: Int, n3: Int, n4: Int, n5: Int)(f: (Int, Int, Int, Int, Int) => A): CC[CC[CC[CC[CC[A]]]]] = 
+    tabulate(n1)(i1 => tabulate(n2, n3, n4, n5)(f(i1, _, _, _, _)))
+
+  /** Produces a $coll containing a sequence of increasing of integers.
+   *
+   *  @param from the first element of the $coll
+   *  @param end the end value of the $coll (the first value NOT contained)
+   *  @return  a $coll with values `start, start + 1, ..., end - 1`
+   */
+  def range(start: Int, end: Int): CC[Int] = range(start, end, 1)
+
+  /** Produces a $coll containing equally spaced values in some integer interval.
+   *  @param start the start value of the $coll
+   *  @param end   the end value of the $coll (the first value NOT contained)
+   *  @param step  the difference between successive elements of the $coll (must be positive or negative)
+   *  @return      a $coll with values `start, start + step, ...` up to, but excluding `end`
+   */
+  def range(start: Int, end: Int, step: Int): CC[Int] = {
+    if (step == 0) throw new IllegalArgumentException("zero step")
+    val b = newBuilder[Int]
+    b.sizeHint(Range.count(start, end, step, false))
+    var i = start
+    while (if (step < 0) end < i else i < end) {
+      b += i
+      i += step
+    }
+    b.result
+  }
+
+  /** Produces a $coll containing repeated applications of a function to a start value.
+   *
+   *  @param start the start value of the $coll
+   *  @param len   the number of elements contained inthe $coll
+   *  @param f     the function that's repeatedly applied
+   *  @return      a $coll with `len` values in the sequence `start, f(start), f(f(start)), ...`
+   */
+  def iterate[A](start: A, len: Int)(f: A => A): CC[A] = {
+    val b = newBuilder[A]
+    if (len > 0) {
+      b.sizeHint(len)
+      var acc = start
+      var i = 1
+      b += acc
+      
+      while (i < len) {
+        acc = f(acc)
+        i += 1
+        b += acc
+      }
+    }
+    b.result
+  }
+}
+
diff --git a/src/library/scala/collection/generic/TraversableForwarder.scala b/src/library/scala/collection/generic/TraversableForwarder.scala
new file mode 100644
index 0000000..aff447d
--- /dev/null
+++ b/src/library/scala/collection/generic/TraversableForwarder.scala
@@ -0,0 +1,88 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection.generic
+import scala.collection._
+
+import mutable.{Buffer, StringBuilder}
+import immutable.{List, Stream}
+// import immutable.{List, Nil, ::, Stream}
+
+/** <p>
+ *    This trait implements a forwarder for traversable objects. It forwards
+ *    all calls to a different iterable object, except for
+ *  </p>
+ *  <ul>
+ *    <li><code>toString</code>, <code>hashCode</code>, <code>equals</code>,
+ *      <code>stringPrefix</code>
+ *    </li>
+ *    <li><code>newBuilder</code>, <code>view</code></li>
+ *    <li>all calls creating a new iterable object of the same kind</li>
+ *  </ul>
+ *  <p>
+ *    The above methods are forwarded by subclass
+ *    <a href="TraversableProxy.html" target="ContentFrame">
+ *    <code>TraversableProxy</code></a>.
+ *  </p>
+ *
+ *  @author  Martin Odersky
+ *  @version 2.8
+ *  @since   2.8
+ */
+trait TraversableForwarder[+A] extends Traversable[A] {
+
+  /** The iterable object to which calls are forwarded */
+  protected def underlying: Traversable[A]
+  
+  override def foreach[B](f: A => B): Unit = underlying.foreach(f)
+  override def isEmpty: Boolean = underlying.isEmpty
+  override def nonEmpty: Boolean = underlying.nonEmpty
+  override def size: Int = underlying.size
+  override def hasDefiniteSize = underlying.hasDefiniteSize
+  override def forall(p: A => Boolean): Boolean = underlying.forall(p)
+  override def exists(p: A => Boolean): Boolean = underlying.exists(p)
+  override def count(p: A => Boolean): Int = underlying.count(p)
+  override def find(p: A => Boolean): Option[A] = underlying.find(p)
+  override def foldLeft[B](z: B)(op: (B, A) => B): B = underlying.foldLeft(z)(op)
+  override def /: [B](z: B)(op: (B, A) => B): B = underlying./:(z)(op)
+  override def foldRight[B](z: B)(op: (A, B) => B): B = underlying.foldRight(z)(op)
+  override def :\ [B](z: B)(op: (A, B) => B): B = underlying.:\(z)(op)
+  override def reduceLeft[B >: A](op: (B, A) => B): B = underlying.reduceLeft(op)
+  override def reduceLeftOption[B >: A](op: (B, A) => B): Option[B] = underlying.reduceLeftOption(op)
+  override def reduceRight[B >: A](op: (A, B) => B): B = underlying.reduceRight(op)
+  override def reduceRightOption[B >: A](op: (A, B) => B): Option[B] = underlying.reduceRightOption(op)
+  override def sum[B >: A](implicit num: Numeric[B]): B = underlying.sum(num)
+  override def product[B >: A](implicit num: Numeric[B]): B = underlying.product(num)
+  override def min[B >: A](implicit cmp: Ordering[B]): A = underlying.min(cmp)
+  override def max[B >: A](implicit cmp: Ordering[B]): A = underlying.max(cmp)
+  override def head: A = underlying.head
+  override def headOption: Option[A] = underlying.headOption
+  override def last: A = underlying.last
+  override def lastOption: Option[A] = underlying.lastOption
+  override def copyToBuffer[B >: A](dest: Buffer[B]) = underlying.copyToBuffer(dest)
+  override def copyToArray[B >: A](xs: Array[B], start: Int, len: Int) = underlying.copyToArray(xs, start, len)
+  override def copyToArray[B >: A](xs: Array[B], start: Int) = underlying.copyToArray(xs, start)
+  override def copyToArray[B >: A](xs: Array[B]) = underlying.copyToArray(xs)
+  override def toArray[B >: A: ClassManifest]: Array[B] = underlying.toArray
+  override def toList: List[A] = underlying.toList
+  override def toIterable: Iterable[A] = underlying.toIterable
+  override def toSeq: Seq[A] = underlying.toSeq
+  override def toIndexedSeq[B >: A] = underlying.toIndexedSeq
+  override def toBuffer[B >: A] = underlying.toBuffer
+  override def toStream: Stream[A] = underlying.toStream
+  override def toSet[B >: A]: immutable.Set[B] = underlying.toSet  
+  override def toMap[T, U](implicit ev: A <:< (T, U)): immutable.Map[T, U] = underlying.toMap(ev)
+  override def mkString(start: String, sep: String, end: String): String = underlying.mkString(start, sep, end)
+  override def mkString(sep: String): String = underlying.mkString(sep)
+  override def mkString: String = underlying.mkString
+  override def addString(b: StringBuilder, start: String, sep: String, end: String): StringBuilder = underlying.addString(b, start, sep, end)
+  override def addString(b: StringBuilder, sep: String): StringBuilder = underlying.addString(b, sep)
+  override def addString(b: StringBuilder): StringBuilder = underlying.addString(b)
+}
diff --git a/src/library/scala/collection/generic/package.scala b/src/library/scala/collection/generic/package.scala
new file mode 100644
index 0000000..0457fef
--- /dev/null
+++ b/src/library/scala/collection/generic/package.scala
@@ -0,0 +1,6 @@
+package scala.collection
+import generic.CanBuildFrom
+
+package object generic {
+  type CanBuild[-Elem, +To] = CanBuildFrom[Nothing, Elem, To]
+}
\ No newline at end of file
diff --git a/src/library/scala/collection/immutable/BitSet.scala b/src/library/scala/collection/immutable/BitSet.scala
index 6ce35d7..b751502 100644
--- a/src/library/scala/collection/immutable/BitSet.scala
+++ b/src/library/scala/collection/immutable/BitSet.scala
@@ -1,53 +1,107 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: BitSet.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.collection.immutable
+package scala.collection
+package immutable
 
+import generic._
+import BitSetLike.{LogWL, updateArray}
+import mutable.{ Builder, AddingBuilder }
 
-/** The class <code>BitSet</code> provides an immutable bitset view on an
- *  int array. Instances can conveniently be created from instances of
- *  Bit indices are between <code>0..(capacity-1)</code> inclusive.
- *
- *  @param size     <code>size</code> represents the number of relevant bits
- *  @param capacity ...
- *  @param ba       <code>ba</code> array of ints of length
- *                  <code>n>>>5</code>
- *  @param copy     <code>copy</code> if yes, then <code>ba</code> is copied
- *                  and updates will not affect this bitset
- *
- *  @author  Burak Emir, Nikolay Mihaylov
- *  @version 1.0
+/** A class for immutable bitsets.
+ *  $bitsetinfo
+ *  @define Coll immutable.BitSet
+ *  @define coll immutable bitset
  */
+ at serializable @SerialVersionUID(1611436763290191562L)
+abstract class BitSet extends Set[Int]  
+                         with scala.collection.BitSet 
+                         with BitSetLike[BitSet] {
+  override def empty = BitSet.empty
 
- at serializable
-/*
- *                This is a strange class! It claims to be immutable but is not.
- *                It claims to be a BitSet but it is not a Set.
- *                Remove it or integrate it into the Set hierarchy.
- *                [Comments by Martin]
- */
-class BitSet(val size: Int, val capacity: Int, ba: Array[Int], copy: Boolean)
-  extends collection.BitSet
-{
-  import compat.Platform.arraycopy
-
-  protected val arr: Array[Int] = {
-    val ba1 = if (ba != null) ba else new Array[Int](0)
-    if (copy) {
-      val arr = new Array[Int](ba1.length)
-      arraycopy(ba1, 0, arr, 0, ba1.length)
-      arr
+  def fromArray(elems: Array[Long]): BitSet = BitSet.fromArray(elems)
+
+  /** Update word at index <code>idx</code>; enlarge set if <code>idx</code>
+   *  outside range of set.
+   */
+  protected def updateWord(idx: Int, w: Long): BitSet
+
+  /** Adds element to bitset, returning a new set.
+   */
+  def + (elem: Int): BitSet = {
+    require(elem >= 0, "bitset element must be >= 0")
+    if (contains(elem)) this
+    else {
+      val idx = elem >> LogWL
+      updateWord(idx, word(idx) | (1L << elem))
     }
-    else
-      ba1
   }
 
+  /** Removes element from bitset, returning a new set
+   */
+  def - (elem: Int): BitSet = {
+    require(elem >= 0, "bitset element must be >= 0")
+    if (contains(elem)) {
+      val idx = elem >> LogWL
+      updateWord(idx, word(idx) & ~(1L << elem))
+    } else this
+  }
+}
+
+/** $factoryInfo
+ *  @define Coll immutable.BitSet
+ *  @define coll immutable bitset
+ */
+object BitSet extends BitSetFactory[BitSet] {
+  /** The empty bitset */
+  val empty: BitSet = new BitSet1(0L)
+  
+  /** An adding builder for immutable Sets. */
+  def newBuilder: Builder[Int, BitSet] = new AddingBuilder[Int, BitSet](empty)
+
+  /** $bitsetCanBuildFrom */
+  implicit def canBuildFrom: CanBuildFrom[BitSet, Int, BitSet] = bitsetCanBuildFrom
+
+  /** A bitset containing all the bits in an array */
+  def fromArray(elems: Array[Long]): BitSet = {
+    val len = elems.length
+    if (len == 0) empty
+    else if (len == 1) new BitSet1(elems(0))
+    else if (len == 2) new BitSet2(elems(0), elems(1))
+    else new BitSetN(elems)
+  }
+
+  private val hashSeed = "BitSet".hashCode
+
+  class BitSet1(val elems: Long) extends BitSet {
+    protected def nwords = 1
+    protected def word(idx: Int) = if (idx == 0) elems else 0L
+    protected def updateWord(idx: Int, w: Long): BitSet = 
+      if (idx == 0) new BitSet1(w)
+      else if (idx == 1) new BitSet2(elems, w)
+      else fromArray(updateArray(Array(elems), idx, w))
+  }
+
+  class BitSet2(val elems0: Long, elems1: Long) extends BitSet {
+    protected def nwords = 2
+    protected def word(idx: Int) = if (idx == 0) elems0 else if (idx == 1) elems1 else 0L
+    protected def updateWord(idx: Int, w: Long): BitSet = 
+      if (idx == 0) new BitSet2(w, elems1)
+      else if (idx == 1) new BitSet2(elems0, w)
+      else fromArray(updateArray(Array(elems0, elems1), idx, w))
+  }
+
+  class BitSetN(val elems: Array[Long]) extends BitSet {
+    protected def nwords = elems.length
+    protected def word(idx: Int) = if (idx < nwords) elems(idx) else 0L
+    protected def updateWord(idx: Int, w: Long): BitSet = fromArray(updateArray(elems, idx, w))
+  }
 }
+
diff --git a/src/library/scala/collection/immutable/DefaultMap.scala b/src/library/scala/collection/immutable/DefaultMap.scala
new file mode 100644
index 0000000..7354234
--- /dev/null
+++ b/src/library/scala/collection/immutable/DefaultMap.scala
@@ -0,0 +1,65 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+package immutable
+
+import generic._
+
+/** A default map which implements the `+` and `-`
+ *  methods of maps. It does so using the default builder for
+ *  maps defined in the `Map` object.
+ *  Instances that inherit from `DefaultMap[A, B]` still have to
+ *  define:
+ *  
+ *  {{{
+ *    def get(key: A): Option[B]
+ *    def iterator: Iterator[(A, B)]
+ *  }}}
+ *  
+ *  It refers back to the original map.
+ *  
+ *  It might also be advisable to override `foreach` or
+ *  `size` if efficient implementations can be found.
+ *  
+ *  @tparam A    the type of the keys contained in this map.
+ *  @tparam B    the type of the values associated with the keys.
+ *  
+ *  @since 2.8
+ */
+trait DefaultMap[A, +B] extends Map[A, B] { self =>
+
+  /** A default implementation which creates a new immutable map.
+   */
+  override def +[B1 >: B](kv: (A, B1)): Map[A, B1] = {
+    val b = Map.newBuilder[A, B1]
+    b ++= this
+    b += ((kv._1, kv._2))
+    b.result
+  }
+
+  /** A default implementation which creates a new immutable map.
+   */
+  override def - (key: A): Map[A, B] = {
+    val b = newBuilder
+    for (kv <- this ; if kv._1 != key) b += kv
+    b.result
+  }
+}
+
+
+
+
+
+
+
+
+
+
diff --git a/src/library/scala/collection/immutable/EmptyMap.scala b/src/library/scala/collection/immutable/EmptyMap.scala
deleted file mode 100644
index 57bce8d..0000000
--- a/src/library/scala/collection/immutable/EmptyMap.scala
+++ /dev/null
@@ -1,39 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: EmptyMap.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-
-package scala.collection.immutable
-
-import Predef.Pair
-
-/** This class implements empty immutable maps
- *  @author  Martin Oderskty
- *  @version 1.0, 019/01/2007
- */
- at serializable
-class EmptyMap[A, +B] extends Map[A, B] {
-
-  def size: Int = 0
-
-  def get(key: A): Option[B] = None
-
-  def elements: Iterator[(A, B)] = Iterator.empty
-
-  def empty[C]: Map[A, C] = new EmptyMap[A, C]
-
-  def update [B1 >: B](key: A, value: B1): Map[A, B1] = 
-    new Map1(key, value)
-
-  def - (key: A): Map[A, B] = this
-}
-  
-
-
diff --git a/src/library/scala/collection/immutable/EmptySet.scala b/src/library/scala/collection/immutable/EmptySet.scala
deleted file mode 100644
index e779dbe..0000000
--- a/src/library/scala/collection/immutable/EmptySet.scala
+++ /dev/null
@@ -1,36 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: EmptySet.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-
-package scala.collection.immutable
-
-/** This class implements empty immutable sets
- *  @author  Martin Oderskty
- *  @version 1.0, 019/01/2007
- */
- at serializable
-class EmptySet[A] extends Set[A] {
-
-  def empty[C]: Set[C] = new EmptySet[C]
-
-  def size: Int = 0
-
-  def contains(elem: A): Boolean = false
-
-  def + (elem: A): Set[A] = new Set1(elem)
-
-  def - (elem: A): Set[A] = this
-
-  def elements: Iterator[A] = Iterator.empty
-}
-  
-
-
diff --git a/src/library/scala/collection/immutable/HashMap.scala b/src/library/scala/collection/immutable/HashMap.scala
index 24756ce..6f9018e 100644
--- a/src/library/scala/collection/immutable/HashMap.scala
+++ b/src/library/scala/collection/immutable/HashMap.scala
@@ -1,164 +1,375 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: HashMap.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.collection.immutable
+package scala.collection
+package immutable
 
-import Predef._
+import generic._
+import annotation.unchecked.uncheckedVariance
 
-/** The canonical factory methods for <a href="HashMap.html">immutable HashMap's</a>.
- *
+/** This class implements immutable maps using a hash trie.
+ *  
+ *  '''Note:''' the builder of a hash map returns specialized representations EmptyMap,Map1,..., Map4
+ *  for maps of size <= 4.
+ *  
+ *  @tparam A      the type of the keys contained in this hash map.
+ *  @tparam B      the type of the values associated with the keys.
+ *  
  *  @author  Martin Odersky
- *  @version 2.0, 19/01/2007
+ *  @author  Tiark Rompf
+ *  @version 2.8
+ *  @since   2.3
+ *  @define Coll immutable.HashMap
+ *  @define coll immutable hash map
+ *  @define mayNotTerminateInf
+ *  @define willNotTerminateInf
  */
-object HashMap {
+ at serializable @SerialVersionUID(2L)
+class HashMap[A, +B] extends Map[A,B] with MapLike[A, B, HashMap[A, B]] {
 
-  /** The empty map of this type */  
-  def empty[A, B] = new HashMap[A, B]
+  override def size: Int = 0
+
+  override def empty = HashMap.empty[A, B]
+
+  def iterator: Iterator[(A,B)] = Iterator.empty
+
+  override def foreach[U](f: ((A, B)) =>  U): Unit = { }
+
+  def get(key: A): Option[B] =
+    get0(key, computeHash(key), 0)
+
+  override def updated [B1 >: B] (key: A, value: B1): HashMap[A, B1] =
+    updated0(key, computeHash(key), 0, value, null)
+
+  override def + [B1 >: B] (kv: (A, B1)): HashMap[A, B1] =
+    updated0(kv._1, computeHash(kv._1), 0, kv._2, kv)
+
+  override def + [B1 >: B] (elem1: (A, B1), elem2: (A, B1), elems: (A, B1) *): HashMap[A, B1] =
+    this + elem1 + elem2 ++ elems
+    // TODO: optimize (might be able to use mutable updates)
+
+  def - (key: A): HashMap[A, B] =
+    removed0(key, computeHash(key), 0)
+
+  protected def elemHashCode(key: A) = if (key == null) 0 else key.##
+
+  protected final def improve(hcode: Int) = {
+    var h: Int = hcode + ~(hcode << 9)
+    h = h ^ (h >>> 14)
+    h = h + (h << 4)
+    h ^ (h >>> 10)
+  }
+  
+  protected def computeHash(key: A) = improve(elemHashCode(key))
+
+  protected def get0(key: A, hash: Int, level: Int): Option[B] = None
+
+  protected def updated0[B1 >: B](key: A, hash: Int, level: Int, value: B1, kv: (A, B1)): HashMap[A, B1] = 
+    new HashMap.HashMap1(key, hash, value, kv)
+
+  protected def removed0(key: A, hash: Int, level: Int): HashMap[A, B] = this
+  
+
+  protected def writeReplace(): AnyRef = new HashMap.SerializationProxy(this)
 
-  /** The canonical factory for this type
-   */
-  def apply[A, B](elems: (A, B)*) = empty[A, B] ++ elems
 }
 
-/** This class implements immutable maps/sets using a hash table.
-  * It is optimized for sequential accesses where the last updated table is accessed most often.
-  * It supports with reasonable efficiency accesses to previous versions of the table by keeping
-  * a change log that's regularly compacted.
-  * It needs to synchronize most methods, so it is less suitable for highly concurrent accesses.
-  *
-  *  @author  Martin Odersky
-  *  @version 2.0, 19/01/2007
-  */
- at serializable
-class HashMap[A, B] extends Map[A,B] with mutable.HashTable[A] {
-  type Entry = mutable.DefaultEntry[A, Any]
-
-  protected var later: HashMap[A, B] = null
-  protected var oldKey: A = _
-  protected var oldValue: Option[B] = _
-  protected var deltaSize: Int = _
-
-  def empty[C]: Map[A, C] = new EmptyMap[A, C]
-
-  def get(key: A): Option[B] = synchronized {
-    var m = this
-    var cnt = 0
-    while (m.later != null) {
-      if (key == m.oldKey) return m.oldValue
-      cnt += 1
-      m = m.later
-    }
-    if (cnt > logLimit) makeCopy(m)
-    val e = m.findEntry(key)
-    if (e == null) None
-    else Some(getValue(e))
+/** $factoryInfo
+ *  @define Coll immutable.HashMap
+ *  @define coll immutable hash map
+ *  
+ *  @author  Tiark Rompf
+ *  @since   2.3
+ */
+object HashMap extends ImmutableMapFactory[HashMap] {
+  /** $mapCanBuildFromInfo */
+  implicit def canBuildFrom[A, B]: CanBuildFrom[Coll, (A, B), HashMap[A, B]] = new MapCanBuildFrom[A, B]
+  def empty[A, B]: HashMap[A, B] = EmptyHashMap.asInstanceOf[HashMap[A, B]]
+  
+  private object EmptyHashMap extends HashMap[Any,Nothing] {
+    
   }
+  
+  // TODO: add HashMap2, HashMap3, ...
+  
+  class HashMap1[A,+B](private var key: A, private[HashMap] var hash: Int, private var value: (B @uncheckedVariance), private var kv: (A,B @uncheckedVariance)) extends HashMap[A,B] {
+    override def size = 1
 
-  def update [B1 >: B](key: A, value: B1): Map[A, B1] = synchronized {
-    makeCopyIfUpdated()
-    val e = findEntry(key)
-    if (e == null) { 
-      markUpdated(key, None, 1)
-      later.addEntry(new Entry(key, value))
-    } else {
-      markUpdated(key, Some(getValue(e)), 0)
-      e.value = value
-    }
-    later
+    override def get0(key: A, hash: Int, level: Int): Option[B] = 
+      if (hash == this.hash && key == this.key) Some(value) else None
+
+    override def updated0[B1 >: B](key: A, hash: Int, level: Int, value: B1, kv: (A, B1)): HashMap[A, B1] = 
+      if (hash == this.hash && key == this.key) new HashMap1(key, hash, value, kv)
+      else {
+        if (hash != this.hash) {
+          //new HashTrieMap[A,B1](level+5, this, new HashMap1(key, hash, value, kv)) 
+          val m = new HashTrieMap[A,B1](0,new Array[HashMap[A,B1]](0),0) // TODO: could save array alloc
+          m.updated0(this.key, this.hash, level, this.value, this.kv).updated0(key, hash, level, value, kv)
+        } else {
+          // 32-bit hash collision (rare, but not impossible)
+          new HashMapCollision1(hash, ListMap.empty.updated(this.key,this.value).updated(key,value))
+        }
+      }
+      
+    override def removed0(key: A, hash: Int, level: Int): HashMap[A, B] = 
+      if (hash == this.hash && key == this.key) HashMap.empty[A,B] else this
+
+    override def iterator: Iterator[(A,B)] = Iterator(ensurePair)
+    override def foreach[U](f: ((A, B)) => U): Unit = f(ensurePair)
+    private[HashMap] def ensurePair: (A,B) = if (kv ne null) kv else { kv = (key, value); kv }
   }
 
-  def - (key: A): Map[A, B] = synchronized {
-    makeCopyIfUpdated()
-    val e = findEntry(key)
-    if (e == null) this 
-    else {
-      markUpdated(key, Some(getValue(e)), -1)
-      later removeEntry key
-      later
-    } 
+  private class HashMapCollision1[A,+B](private[HashMap] var hash: Int, var kvs: ListMap[A,B @uncheckedVariance]) extends HashMap[A,B] {
+    override def size = kvs.size
+
+    override def get0(key: A, hash: Int, level: Int): Option[B] = 
+      if (hash == this.hash) kvs.get(key) else None
+
+    override def updated0[B1 >: B](key: A, hash: Int, level: Int, value: B1, kv: (A, B1)): HashMap[A, B1] = 
+      if (hash == this.hash) new HashMapCollision1(hash, kvs.updated(key, value))
+      else {
+        var m: HashMap[A,B1] = new HashTrieMap[A,B1](0,new Array[HashMap[A,B1]](0),0)
+        // might be able to save some ops here, but it doesn't seem to be worth it
+        for ((k,v) <- kvs)
+          m = m.updated0(k, this.hash, level, v, null)
+        m.updated0(key, hash, level, value, kv)
+      }
+      
+    override def removed0(key: A, hash: Int, level: Int): HashMap[A, B] = 
+      if (hash == this.hash) {
+        val kvs1 = kvs - key
+        if (!kvs1.isEmpty)
+          new HashMapCollision1(hash, kvs1)
+        else
+          HashMap.empty[A,B]
+      } else this
+
+    override def iterator: Iterator[(A,B)] = kvs.iterator
+    override def foreach[U](f: ((A, B)) => U): Unit = kvs.foreach(f)
   }
 
-  override def size: Int = synchronized {
-    var m = this
-    var cnt = 0
-    var s = 0
-    while (m.later != null) {
-      s -= m.deltaSize
-      cnt += 1
-      m = m.later
+
+  class HashTrieMap[A,+B](private var bitmap: Int, private var elems: Array[HashMap[A,B @uncheckedVariance]],
+      private var size0: Int) extends HashMap[A,B] {
+/*
+    def this (level: Int, m1: HashMap1[A,B], m2: HashMap1[A,B]) = {
+      this(((m1.hash >>> level) & 0x1f) | ((m2.hash >>> level) & 0x1f), {
+        val idx1 = (m1.hash >>> level) & 0x1f
+        val idx2 = (m2.hash >>> level) & 0x1f
+        assert(idx1 != idx2, m1.hash + "==" + m2.hash + " at level " + level) // TODO
+        val elems = new Array[HashMap[A,B]](2)
+        if (idx1 < idx2) {
+          elems(0) = m1
+          elems(1) = m2
+        } else {
+          elems(0) = m2
+          elems(1) = m1
+        }
+        elems
+      }, 2)
     }
-    s += m.tableSize
-    if (cnt > logLimit) makeCopy(m)  
-    s
-  }
+*/
+    override def size = size0
 
-  def elements = synchronized {
-    makeCopyIfUpdated()
-    entries map {e => (e.key, getValue(e))}
-  }
-  
-  private def getValue(e: Entry) = 
-    e.value.asInstanceOf[B]
-
-  private def logLimit: Int = Math.sqrt(table.length).toInt
-
-  private def markUpdated(key: A, ov: Option[B], delta: Int) { 
-    val lv = loadFactor
-    later = new HashMap[A, B] {
-      override def initialSize = 0
-      override def loadFactor = lv        
-      table     = HashMap.this.table
-      tableSize = HashMap.this.tableSize
-      threshold = HashMap.this.threshold
+    override def get0(key: A, hash: Int, level: Int): Option[B] = {
+      val index = (hash >>> level) & 0x1f
+      val mask = (1 << index)
+      if (bitmap == - 1) {
+        elems(index & 0x1f).get0(key, hash, level + 5)
+      } else if ((bitmap & mask) != 0) {
+        val offset = Integer.bitCount(bitmap & (mask-1))
+        // TODO: might be worth checking if sub is HashTrieMap (-> monomorphic call site)
+        elems(offset).get0(key, hash, level + 5)
+      } else
+        None
     }
-    oldKey = key
-    oldValue = ov
-    deltaSize = delta
-  }
 
-  private def makeCopy(last: HashMap[A, B]) {
-    def undo(m: HashMap[A, B]) {
-      if (m ne last) {
-        undo(m.later)
-        if (m.deltaSize == 1) removeEntry(m.oldKey)
-        else if (m.deltaSize == 0) findEntry(m.oldKey).value = m.oldValue.get
-        else if (m.deltaSize == -1) addEntry(new Entry(m.oldKey, m.oldValue.get))
+    override def updated0[B1 >: B](key: A, hash: Int, level: Int, value: B1, kv: (A, B1)): HashMap[A, B1] = {
+      val index = (hash >>> level) & 0x1f
+      val mask = (1 << index)
+      val offset = Integer.bitCount(bitmap & (mask-1))
+      if ((bitmap & mask) != 0) {
+        val elemsNew = new Array[HashMap[A,B1]](elems.length)
+        Array.copy(elems, 0, elemsNew, 0, elems.length)
+        val sub = elems(offset)
+        // TODO: might be worth checking if sub is HashTrieMap (-> monomorphic call site)
+        val subNew = sub.updated0(key, hash, level + 5, value, kv)
+        elemsNew(offset) = subNew
+        new HashTrieMap(bitmap, elemsNew, size + (subNew.size - sub.size))
+      } else {
+        val elemsNew = new Array[HashMap[A,B1]](elems.length + 1)
+        Array.copy(elems, 0, elemsNew, 0, offset)
+        elemsNew(offset) = new HashMap1(key, hash, value, kv)
+        Array.copy(elems, offset, elemsNew, offset + 1, elems.length - offset)
+        val bitmapNew = bitmap | mask
+        new HashTrieMap(bitmapNew, elemsNew, size + 1)
       }
     }
-    def copy(e: Entry): Entry = 
-      if (e == null) null
-      else {
-        val rest = copy(e.next)
-        val result = new Entry(e.key, e.value)
-        result.next = rest
-        result
+
+    override def removed0(key: A, hash: Int, level: Int): HashMap[A, B] = {
+      val index = (hash >>> level) & 0x1f
+      val mask = (1 << index)
+      val offset = Integer.bitCount(bitmap & (mask-1))
+      if ((bitmap & mask) != 0) {
+        val sub = elems(offset)
+        // TODO: might be worth checking if sub is HashTrieMap (-> monomorphic call site)
+        val subNew = sub.removed0(key, hash, level + 5)
+        if (subNew.isEmpty) {
+          val bitmapNew = bitmap ^ mask
+          if (bitmapNew != 0) {
+            val elemsNew = new Array[HashMap[A,B]](elems.length - 1)
+            Array.copy(elems, 0, elemsNew, 0, offset)
+            Array.copy(elems, offset + 1, elemsNew, offset, elems.length - offset - 1)
+            val sizeNew = size - sub.size
+            new HashTrieMap(bitmapNew, elemsNew, sizeNew)
+          } else
+            HashMap.empty[A,B]
+        } else {
+          val elemsNew = new Array[HashMap[A,B]](elems.length)
+          Array.copy(elems, 0, elemsNew, 0, elems.length)
+          elemsNew(offset) = subNew
+          val sizeNew = size + (subNew.size - sub.size)
+          new HashTrieMap(bitmap, elemsNew, sizeNew)
+        }
+      } else {
+        this
+      }
+    }
+
+/*
+    override def iterator = {   // TODO: optimize (use a stack to keep track of pos)
+      
+      def iter(m: HashTrieMap[A,B], k: => Stream[(A,B)]): Stream[(A,B)] = {
+        def horiz(elems: Array[HashMap[A,B]], i: Int, k: => Stream[(A,B)]): Stream[(A,B)] = {
+          if (i < elems.length) {
+            elems(i) match {
+              case m: HashTrieMap[A,B] => iter(m, horiz(elems, i+1, k))
+              case m: HashMap1[A,B] => new Stream.Cons(m.ensurePair, horiz(elems, i+1, k))
+            }
+          } else k
+        }
+        horiz(m.elems, 0, k)
+      }
+      iter(this, Stream.empty).iterator
+    }
+*/
+
+
+    override def iterator = new Iterator[(A,B)] {
+      private[this] var depth = 0
+      private[this] var arrayStack = new Array[Array[HashMap[A,B]]](6)
+      private[this] var posStack = new Array[Int](6)
+
+      private[this] var arrayD = elems
+      private[this] var posD = 0
+
+      private[this] var subIter: Iterator[(A,B)] = null // to traverse collision nodes
+
+      def hasNext = (subIter ne null) || depth >= 0
+      
+      def next: (A,B) = {
+        if (subIter ne null) {
+          val el = subIter.next
+          if (!subIter.hasNext)
+            subIter = null
+          el
+        } else
+          next0(arrayD, posD)
+      }
+      
+      @scala.annotation.tailrec private[this] def next0(elems: Array[HashMap[A,B]], i: Int): (A,B) = {
+        if (i == elems.length-1) { // reached end of level, pop stack
+          depth -= 1
+          if (depth >= 0) {
+            arrayD = arrayStack(depth)
+            posD = posStack(depth)
+            arrayStack(depth) = null
+          } else {
+            arrayD = null
+            posD = 0
+          }
+        } else
+          posD += 1
+
+        elems(i) match {
+          case m: HashTrieMap[A,B] => // push current pos onto stack and descend
+            if (depth >= 0) {
+              arrayStack(depth) = arrayD
+              posStack(depth) = posD
+            }
+            depth += 1
+            arrayD = m.elems
+            posD = 0
+            next0(m.elems, 0)
+          case m: HashMap1[A,B] => m.ensurePair
+          case m =>
+            subIter = m.iterator
+            subIter.next
+        }
+      }
+    }
+
+/*
+
+import collection.immutable._
+def time(block: =>Unit) = { val t0 = System.nanoTime; block; println("elapsed: " + (System.nanoTime - t0)/1000000.0) }
+var mOld = OldHashMap.empty[Int,Int]
+var mNew = HashMap.empty[Int,Int]
+time { for (i <- 0 until 100000) mOld = mOld.updated(i,i) }
+time { for (i <- 0 until 100000) mOld = mOld.updated(i,i) }
+time { for (i <- 0 until 100000) mOld = mOld.updated(i,i) }
+time { for (i <- 0 until 100000) mNew = mNew.updated(i,i) }
+time { for (i <- 0 until 100000) mNew = mNew.updated(i,i) }
+time { for (i <- 0 until 100000) mNew = mNew.updated(i,i) }
+time { mOld.iterator.foreach( p => ()) }
+time { mOld.iterator.foreach( p => ()) }
+time { mOld.iterator.foreach( p => ()) }
+time { mNew.iterator.foreach( p => ()) }
+time { mNew.iterator.foreach( p => ()) }
+time { mNew.iterator.foreach( p => ()) }
+
+*/
+
+
+    override def foreach[U](f: ((A, B)) =>  U): Unit = {
+      var i = 0;
+      while (i < elems.length) {
+        elems(i).foreach(f)
+        i += 1
       }
-    val ltable = last.table
-    val s = ltable.length
-    table = new Array[mutable.HashEntry[A, Entry]](s)
-    var i = 0
-    while (i < s) {
-      table(i) = copy(ltable(i).asInstanceOf[Entry])
-      i += 1
     }
-    tableSize = last.tableSize
-    threshold = last.threshold
-    undo(this)
-    later = null
+
   }
+  
+  @serializable  @SerialVersionUID(2L) private class SerializationProxy[A,B](@transient private var orig: HashMap[A, B]) {
+    private def writeObject(out: java.io.ObjectOutputStream) {
+      val s = orig.size
+      out.writeInt(s)
+      for ((k,v) <- orig) {
+        out.writeObject(k)
+        out.writeObject(v)
+      }
+    }
 
-  private def makeCopyIfUpdated() {
-    var m = this
-    while (m.later != null) m = m.later
-    if (m ne this) makeCopy(m)
+    private def readObject(in: java.io.ObjectInputStream) {
+      orig = empty
+      val s = in.readInt()
+      for (i <- 0 until s) {
+        val key = in.readObject().asInstanceOf[A]
+        val value = in.readObject().asInstanceOf[B]
+        orig = orig.updated(key, value)
+      }
+    }
+    
+    private def readResolve(): AnyRef = orig
   }
+
 }
 
diff --git a/src/library/scala/collection/immutable/HashSet.scala b/src/library/scala/collection/immutable/HashSet.scala
index 6b69638..498c7bb 100644
--- a/src/library/scala/collection/immutable/HashSet.scala
+++ b/src/library/scala/collection/immutable/HashSet.scala
@@ -1,136 +1,350 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: HashSet.scala 16881 2009-01-09 16:28:11Z cunei $
 
-package scala.collection.immutable
 
-/** The canonical factory methods for <a href="HashSet.html">immutable HashSet's<la>.
-  *
-  *  @author  Martin Odersky
-  *  @version 2.0, 19/01/2007
-  */
-object HashSet {
+package scala.collection
+package immutable
 
-  /** The empty set of this type.
-   */
-  def empty[A] = new HashSet[A]
+import generic._
+import annotation.unchecked.uncheckedVariance
 
-  /** The canonical factory for this type
-   */
-  def apply[A](elems: A*) = empty[A] ++ elems
+/** This class implements immutable sets using a hash trie.
+ *  
+ *  '''Note:''' the builder of a hash set returns specialized representations `EmptySet`,`Set1`,..., `Set4`
+ *  for sets of `size <= 4`.
+ *  
+ *  @tparam A      the type of the elements contained in this hash set.
+ *  
+ *  @author  Martin Odersky
+ *  @author  Tiark Rompf
+ *  @version 2.8
+ *  @since   2.3
+ *  @define Coll immutable.HashSet
+ *  @define coll immutable hash set
+ */
+ at serializable @SerialVersionUID(2L)
+class HashSet[A] extends Set[A] 
+                    with GenericSetTemplate[A, HashSet]
+                    with SetLike[A, HashSet[A]] {
+  override def companion: GenericCompanion[HashSet] = HashSet
+
+  //class HashSet[A] extends Set[A] with SetLike[A, HashSet[A]] {
+
+  override def size: Int = 0
+
+  override def empty = HashSet.empty[A]
+
+  def iterator: Iterator[A] = Iterator.empty
+
+  override def foreach[U](f: A =>  U): Unit = { }
+
+  def contains(e: A): Boolean = get0(e, computeHash(e), 0)
+
+  override def + (e: A): HashSet[A] = updated0(e, computeHash(e), 0)
+
+  override def + (elem1: A, elem2: A, elems: A*): HashSet[A] =
+    this + elem1 + elem2 ++ elems
+    // TODO: optimize (might be able to use mutable updates)
+
+  def - (e: A): HashSet[A] =
+    removed0(e, computeHash(e), 0)
+
+  protected def elemHashCode(key: A) = if (key == null) 0 else key.##
+
+  protected final def improve(hcode: Int) = {
+    var h: Int = hcode + ~(hcode << 9)
+    h = h ^ (h >>> 14)
+    h = h + (h << 4)
+    h ^ (h >>> 10)
+  }
+  
+  protected def computeHash(key: A) = improve(elemHashCode(key))
+
+  protected def get0(key: A, hash: Int, level: Int): Boolean = false
+
+  protected def updated0(key: A, hash: Int, level: Int): HashSet[A] = 
+    new HashSet.HashSet1(key, hash)
+
+  protected def removed0(key: A, hash: Int, level: Int): HashSet[A] = this
+  
+  protected def writeReplace(): AnyRef = new HashSet.SerializationProxy(this)
 }
 
-/** This class implements immutable maps/sets using a hash table.
-  * It is optimized for sequential accesses where the last updated table is accessed most often.
-  * It supports with reasonable efficiency accesses to previous versions of the table by keeping
-  * a change log that's regularly compacted.
-  * It needs to synchronize most methods, so it is less suitable for highly concurrent accesses.
-  *
-  *  @author  Martin Odersky
-  *  @version 2.0, 19/01/2007
-  */
- at serializable
-class HashSet[A] extends Set[A] with mutable.FlatHashTable[A] {
-  protected var later: HashSet[A] = null
-  protected var changedElem: A = _
-  protected var deleted: Boolean = _
-
-  def empty[C]: Set[C] = new EmptySet[C]
-
-  def contains(elem: A): Boolean = synchronized {
-    var m = this
-    var cnt = 0
-    while (m.later != null) {
-      if (elem == m.changedElem) return m.deleted
-      cnt += 1
-      m = m.later
-    }
-    if (cnt > logLimit) makeCopy(m)
-    m.containsEntry(elem)
+/** $factoryInfo
+ *  @define Coll immutable.HashSet
+ *  @define coll immutable hash set
+ *
+ *  @author  Tiark Rompf
+ *  @since   2.3
+ *  @define Coll immutable.HashSet
+ *  @define coll immutable hash set
+ *  @define mayNotTerminateInf
+ *  @define willNotTerminateInf
+ */
+object HashSet extends ImmutableSetFactory[HashSet] {
+  /** $setCanBuildFromInfo */
+  implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, HashSet[A]] = setCanBuildFrom[A]
+  override def empty[A]: HashSet[A] = EmptyHashSet.asInstanceOf[HashSet[A]]
+  
+  private object EmptyHashSet extends HashSet[Any] {
   }
+  
+  // TODO: add HashSet2, HashSet3, ...
+  
+  class HashSet1[A](private[HashSet] var key: A, private[HashSet] var hash: Int) extends HashSet[A] {
+    override def size = 1
 
-  def + (elem: A): Set[A] = synchronized {
-    makeCopyIfUpdated()
-    if (containsEntry(elem)) this
-    else {
-      markUpdated(elem, false)
-      later addEntry elem
-      later
-    }
+    override def get0(key: A, hash: Int, level: Int): Boolean = 
+      (hash == this.hash && key == this.key)
+
+    override def updated0(key: A, hash: Int, level: Int): HashSet[A] = 
+      if (hash == this.hash && key == this.key) this
+      else {
+        if (hash != this.hash) {
+          //new HashTrieSet[A](level+5, this, new HashSet1(key, hash)) 
+          val m = new HashTrieSet[A](0,new Array[HashSet[A]](0),0) // TODO: could save array alloc
+          m.updated0(this.key, this.hash, level).updated0(key, hash, level)
+        } else {
+          // 32-bit hash collision (rare, but not impossible)
+          new HashSetCollision1(hash, ListSet.empty + this.key + key)
+        }
+      }
+      
+    override def removed0(key: A, hash: Int, level: Int): HashSet[A] = 
+      if (hash == this.hash && key == this.key) HashSet.empty[A] else this
+
+    override def iterator: Iterator[A] = Iterator(key)
+    override def foreach[U](f: A => U): Unit = f(key)
   }
 
-  def - (elem: A): Set[A] = synchronized {
-    makeCopyIfUpdated()
-    if (!containsEntry(elem)) this
-    else {
-      markUpdated(elem, true)
-      later removeEntry elem
-      later
+  private class HashSetCollision1[A](private[HashSet] var hash: Int, var ks: ListSet[A]) extends HashSet[A] {
+    override def size = ks.size
+
+    override def get0(key: A, hash: Int, level: Int): Boolean = 
+      if (hash == this.hash) ks.contains(key) else false
+
+    override def updated0(key: A, hash: Int, level: Int): HashSet[A] = 
+      if (hash == this.hash) new HashSetCollision1(hash, ks + key)
+      else {
+        var m: HashSet[A] = new HashTrieSet[A](0,new Array[HashSet[A]](0),0)
+        // might be able to save some ops here, but it doesn't seem to be worth it
+        for (k <- ks)
+          m = m.updated0(k, this.hash, level)
+        m.updated0(key, hash, level)
+      }
+      
+    override def removed0(key: A, hash: Int, level: Int): HashSet[A] = 
+      if (hash == this.hash) {
+        val ks1 = ks - key
+        if (!ks1.isEmpty)
+          new HashSetCollision1(hash, ks1)
+        else
+          HashSet.empty[A]
+      } else this
+
+    override def iterator: Iterator[A] = ks.iterator
+    override def foreach[U](f: A => U): Unit = ks.foreach(f)
+
+    private def writeObject(out: java.io.ObjectOutputStream) {
+      // this cannot work - reading things in might produce different
+      // hash codes and remove the collision. however this is never called
+      // because no references to this class are ever handed out to client code
+      // and HashTrieSet serialization takes care of the situation
+      error("cannot serialize an immutable.HashSet where all items have the same 32-bit hash code")
+      //out.writeObject(kvs)
     }
-  }
 
-  override def size: Int = synchronized {
-    var m = this
-    var cnt = 0
-    var s = 0
-    while (m.later != null) {
-      if (m.deleted) s += 1 else s -= 1
-      cnt += 1
-      m = m.later
+    private def readObject(in: java.io.ObjectInputStream) {
+      error("cannot deserialize an immutable.HashSet where all items have the same 32-bit hash code")
+      //kvs = in.readObject().asInstanceOf[ListSet[A]]
+      //hash = computeHash(kvs.)
     }
-    s += m.tableSize
-    if (cnt > logLimit) makeCopy(m)  
-    s
-  }
 
-  override def elements = synchronized {
-    makeCopyIfUpdated()
-    // note need to cache because (later versions of) set might be mutated while elements are traversed.
-    val cached = new mutable.ArrayBuffer() ++ super.elements
-    cached.elements
   }
 
-  private def logLimit: Int = Math.sqrt(table.length).toInt
 
-  private def markUpdated(elem: A, del: Boolean) { 
-    val lv = loadFactor
-    later = new HashSet[A] {
-      override def initialSize = 0
-      override def loadFactor = lv
-      table     = HashSet.this.table
-      tableSize = HashSet.this.tableSize
-      threshold = HashSet.this.threshold
+  class HashTrieSet[A](private var bitmap: Int, private var elems: Array[HashSet[A]],
+      private var size0: Int) extends HashSet[A] {
+
+    override def size = size0
+
+    override def get0(key: A, hash: Int, level: Int): Boolean = {
+      val index = (hash >>> level) & 0x1f
+      val mask = (1 << index)
+      if (bitmap == - 1) {
+        elems(index & 0x1f).get0(key, hash, level + 5)
+      } else if ((bitmap & mask) != 0) {
+        val offset = Integer.bitCount(bitmap & (mask-1))
+        // TODO: might be worth checking if sub is HashTrieSet (-> monomorphic call site)
+        elems(offset).get0(key, hash, level + 5)
+      } else
+        false
     }
-    changedElem = elem
-    deleted = del
-  }
 
-  private def makeCopy(last: HashSet[A]) {
-    def undo(m: HashSet[A]) {
-      if (m ne last) {
-        undo(m.later)
-        if (m.deleted) addEntry(m.changedElem)
-        else removeEntry(m.changedElem)
+    override def updated0(key: A, hash: Int, level: Int): HashSet[A] = {
+      val index = (hash >>> level) & 0x1f
+      val mask = (1 << index)
+      val offset = Integer.bitCount(bitmap & (mask-1))
+      if ((bitmap & mask) != 0) {
+        val elemsNew = new Array[HashSet[A]](elems.length)
+        Array.copy(elems, 0, elemsNew, 0, elems.length)
+        val sub = elems(offset)
+        // TODO: might be worth checking if sub is HashTrieSet (-> monomorphic call site)
+        val subNew = sub.updated0(key, hash, level + 5)
+        elemsNew(offset) = subNew
+        new HashTrieSet(bitmap, elemsNew, size + (subNew.size - sub.size))
+      } else {
+        val elemsNew = new Array[HashSet[A]](elems.length + 1)
+        Array.copy(elems, 0, elemsNew, 0, offset)
+        elemsNew(offset) = new HashSet1(key, hash)
+        Array.copy(elems, offset, elemsNew, offset + 1, elems.length - offset)
+        val bitmapNew = bitmap | mask
+        new HashTrieSet(bitmapNew, elemsNew, size + 1)
+      }
+    }
+
+    override def removed0(key: A, hash: Int, level: Int): HashSet[A] = {
+      val index = (hash >>> level) & 0x1f
+      val mask = (1 << index)
+      val offset = Integer.bitCount(bitmap & (mask-1))
+      if ((bitmap & mask) != 0) {
+        val sub = elems(offset)
+        // TODO: might be worth checking if sub is HashTrieMap (-> monomorphic call site)
+        val subNew = sub.removed0(key, hash, level + 5)
+        if (subNew.isEmpty) {
+          val bitmapNew = bitmap ^ mask
+          if (bitmapNew != 0) {
+            val elemsNew = new Array[HashSet[A]](elems.length - 1)
+            Array.copy(elems, 0, elemsNew, 0, offset)
+            Array.copy(elems, offset + 1, elemsNew, offset, elems.length - offset - 1)
+            val sizeNew = size - sub.size
+            new HashTrieSet(bitmapNew, elemsNew, sizeNew)
+          } else
+            HashSet.empty[A]
+        } else {
+          val elemsNew = new Array[HashSet[A]](elems.length)
+          Array.copy(elems, 0, elemsNew, 0, elems.length)
+          elemsNew(offset) = subNew
+          val sizeNew = size + (subNew.size - sub.size)
+          new HashTrieSet(bitmap, elemsNew, sizeNew)
+        }
+      } else {
+        this
+      }
+    }
+
+
+    override def iterator = new Iterator[A] {
+      private[this] var depth = 0
+      private[this] var arrayStack = new Array[Array[HashSet[A]]](6)
+      private[this] var posStack = new Array[Int](6)
+
+      private[this] var arrayD = elems
+      private[this] var posD = 0
+
+      private[this] var subIter: Iterator[A] = null // to traverse collision nodes
+
+      def hasNext = (subIter ne null) || depth >= 0
+      
+      def next: A = {
+        if (subIter ne null) {
+          val el = subIter.next
+          if (!subIter.hasNext)
+            subIter = null
+          el
+        } else
+          next0(arrayD, posD)
+      }
+      
+      @scala.annotation.tailrec private[this] def next0(elems: Array[HashSet[A]], i: Int): A = {
+        if (i == elems.length-1) { // reached end of level, pop stack
+          depth -= 1
+          if (depth >= 0) {
+            arrayD = arrayStack(depth)
+            posD = posStack(depth)
+            arrayStack(depth) = null
+          } else {
+            arrayD = null
+            posD = 0
+          }
+        } else
+          posD += 1
+
+        elems(i) match {
+          case m: HashTrieSet[A] => // push current pos onto stack and descend
+            if (depth >= 0) {
+              arrayStack(depth) = arrayD
+              posStack(depth) = posD
+            }
+            depth += 1
+            arrayD = m.elems
+            posD = 0
+            next0(m.elems, 0)
+          case m: HashSet1[A] => m.key
+          case m =>
+            subIter = m.iterator
+            subIter.next
+        }
+      }
+    }
+
+/*
+
+import collection.immutable._
+def time(block: =>Unit) = { val t0 = System.nanoTime; block; println("elapsed: " + (System.nanoTime - t0)/1000000.0) }
+var mOld = OldHashSet.empty[Int]
+var mNew = HashSet.empty[Int]
+time { for (i <- 0 until 100000) mOld = mOld + i }
+time { for (i <- 0 until 100000) mOld = mOld + i }
+time { for (i <- 0 until 100000) mOld = mOld + i }
+time { for (i <- 0 until 100000) mNew = mNew + i }
+time { for (i <- 0 until 100000) mNew = mNew + i }
+time { for (i <- 0 until 100000) mNew = mNew + i }
+time { mOld.iterator.foreach( p => ()) }
+time { mOld.iterator.foreach( p => ()) }
+time { mOld.iterator.foreach( p => ()) }
+time { mNew.iterator.foreach( p => ()) }
+time { mNew.iterator.foreach( p => ()) }
+time { mNew.iterator.foreach( p => ()) }
+
+*/
+
+
+    override def foreach[U](f: A =>  U): Unit = {
+      var i = 0;
+      while (i < elems.length) {
+        elems(i).foreach(f)
+        i += 1
       }
     }
-    table = new Array[AnyRef](last.table.length)
-    Array.copy(last.table, 0, table, 0, table.length)
-    tableSize = last.tableSize
-    threshold = last.threshold
-    undo(this)
-    later = null
   }
+  
+  @serializable  @SerialVersionUID(2L) private class SerializationProxy[A,B](@transient private var orig: HashSet[A]) {
+    private def writeObject(out: java.io.ObjectOutputStream) {
+      val s = orig.size
+      out.writeInt(s)
+      for (e <- orig) {
+        out.writeObject(e)
+      }
+    }
 
-  private def makeCopyIfUpdated() {
-    var m = this
-    while (m.later != null) m = m.later
-    if (m ne this) makeCopy(m)
+    private def readObject(in: java.io.ObjectInputStream) {
+      orig = empty
+      val s = in.readInt()
+      for (i <- 0 until s) {
+        val e = in.readObject().asInstanceOf[A]
+        orig = orig + e
+      }
+    }
+    
+    private def readResolve(): AnyRef = orig
   }
+
 }
 
diff --git a/src/library/scala/collection/immutable/ImmutableIterator.scala b/src/library/scala/collection/immutable/ImmutableIterator.scala
deleted file mode 100644
index 3486966..0000000
--- a/src/library/scala/collection/immutable/ImmutableIterator.scala
+++ /dev/null
@@ -1,111 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: ImmutableIterator.scala 16894 2009-01-13 13:09:41Z cunei $
-
-package scala.collection.immutable
-
-/** An object for creating immutable iterators.
-  */
-object ImmutableIterator {
-  case object Empty extends ImmutableIterator[Nothing] {
-    def hasNext = false
-    def next = throw new NoSuchElementException
-  }
-
-  private case class NonEmpty[+A](item: A, right: () => ImmutableIterator[A]) extends ImmutableIterator[A] {
-    def hasNext = true
-    def next = Tuple2(item, right())
-  }
-
-  /** Creates an empty immutable iterator.
-   */
-  def empty : ImmutableIterator[Nothing] = Empty
-
-  /** Creates an immutable iterator with one element.
-   */
-  def apply[A](item : A) : ImmutableIterator[A] = NonEmpty(item, () => Empty)
-
-  /** Prepends a lazy immutable iterator (right) with an element (item).
-   */
-  def apply[A](item : A, right : () => ImmutableIterator[A]) : () => ImmutableIterator[A] =
-    () => NonEmpty(item, right)
-
-  /** Appends an immutable iterator (left) with an element (item) followed
-   *  by a lazy immutable iterator (right).
-   */
-  def apply[A](left : ImmutableIterator[A], item : A, right : () => ImmutableIterator[A]) : ImmutableIterator[A] = left match {
-  case NonEmpty(first, middle) => 
-    val rest = NonEmpty(item,right);
-    NonEmpty(first, apply(middle, () => rest));  
-  case Empty => NonEmpty(item, right);
-  }
-
-  /** Concats a lazy immutable iterator (left) with another lazy immutable
-   *  iterator (right).
-   */
-  def apply[A](left: () => ImmutableIterator[A], right: () => ImmutableIterator[A]): () => ImmutableIterator[A] = () => (left() match {
-    case Empty => right()
-    case NonEmpty(item, middle) => NonEmpty(item, apply(middle, right))
-  });
-}
-
-/** A stateless iterator.
- *
- *  @author  Sean McDirmid
- *  @version 1.0
- */
-sealed abstract class ImmutableIterator[+A] {
-
-  /** queries if this iterator has an element to return.
-   */
-  def hasNext: Boolean
-
-  /** returns the next element and immutable iterator as a pair.
-   */
-  def next: Tuple2[A,ImmutableIterator[A]]
-
-  /** Creates a new immutable iterator that appends item to this immutable
-   *  iterator.
-   */
-  def append[B >: A](item: B): ImmutableIterator[B] = append(item, () => ImmutableIterator.Empty)
-
-  /** Creates a new immutable iterator that appends item  and a lazy immutable
-   *  iterator (right) to this immutable iterator.
-   *
-   *  @param item  ...
-   *  @param right ...
-   *  @return      ...
-   */
-  def append[B >: A](item: B, right: () => ImmutableIterator[B]): ImmutableIterator[B] =
-    ImmutableIterator[B](this, item, right)
-
-  /** Creates a new immutable iterator that appends a lazy immutable
-   *  iterator (right) to this immutable iterator.
-   */
-  def append[B >: A](right: () => ImmutableIterator[B]) =
-    ImmutableIterator(() => this, right)()
-
-  private class Elements extends Iterator[A] {
-    private[this] var cursor: ImmutableIterator[A] = ImmutableIterator.this
-    def hasNext = cursor.hasNext
-    def next = {
-      val Tuple2(ret,cursor0) = cursor.next
-      cursor = cursor0
-      ret
-    }
-  }
-
-  /** Converts this immutable iterator into a conventional iterator.
-   */
-  def elements: Iterator[A] = new Elements
-}
-
-
-
-
diff --git a/src/library/scala/collection/immutable/IndexedSeq.scala b/src/library/scala/collection/immutable/IndexedSeq.scala
new file mode 100644
index 0000000..720ed9d
--- /dev/null
+++ b/src/library/scala/collection/immutable/IndexedSeq.scala
@@ -0,0 +1,40 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+package scala.collection
+package immutable
+
+import generic._
+import mutable.{ArrayBuffer, Builder}
+
+/** A subtrait of `collection.IndexedSeq` which represents indexed sequences
+ *  that are guaranteed immutable.
+ *  $indexedSeqInfo
+ */
+trait IndexedSeq[+A] extends Seq[A] 
+                    with scala.collection.IndexedSeq[A] 
+                    with GenericTraversableTemplate[A, IndexedSeq]
+                    with IndexedSeqLike[A, IndexedSeq[A]] { 
+  override def companion: GenericCompanion[IndexedSeq] = IndexedSeq
+}
+
+/** $factoryInfo
+ *  The current default implementation of a $Coll is a `Vector`.
+ *  @define coll indexed sequence
+ *  @define Coll IndexedSeq
+ */
+object IndexedSeq extends SeqFactory[IndexedSeq] {
+  @serializable
+  class Impl[A](buf: ArrayBuffer[A]) extends IndexedSeq[A] {
+    def length = buf.length
+    def apply(idx: Int) = buf.apply(idx)
+  }
+  implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, IndexedSeq[A]] = new GenericCanBuildFrom[A]
+  def newBuilder[A]: Builder[A, IndexedSeq[A]] = Vector.newBuilder[A]
+}
diff --git a/src/library/scala/collection/immutable/IntMap.scala b/src/library/scala/collection/immutable/IntMap.scala
index 217d6c0..3b80220 100644
--- a/src/library/scala/collection/immutable/IntMap.scala
+++ b/src/library/scala/collection/immutable/IntMap.scala
@@ -1,9 +1,28 @@
-package scala.collection.immutable;
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
 
-/**
- * @author David MacIver
+
+
+package scala.collection
+package immutable;
+
+
+
+import scala.collection.generic.CanBuildFrom
+import scala.collection.mutable.Builder
+import scala.collection.mutable.MapBuilder
+
+
+
+/** Utility class for integer maps.
+ *  @author David MacIver
  */
-private[immutable] object IntMapUtils{
+private[immutable] object IntMapUtils {
   def zero(i : Int, mask : Int) = (i & mask) == 0;    
   def mask(i : Int, mask : Int) = i & (complement(mask - 1) ^ mask)
   def hasMatch(key : Int, prefix : Int, m : Int) = mask(key, m) == prefix;
@@ -38,16 +57,33 @@ private[immutable] object IntMapUtils{
 
 import IntMapUtils._
 
-object IntMap{
+/** A companion object for integer maps.
+ *  @since 2.7
+ */
+object IntMap {
+  /** $mapCanBuildFromInfo */
+  implicit def canBuildFrom[A, B] = new CanBuildFrom[IntMap[A], (Int, B), IntMap[B]] {
+    def apply(from: IntMap[A]): Builder[(Int, B), IntMap[B]] = apply()
+    def apply(): Builder[(Int, B), IntMap[B]] = new MapBuilder[Int, B, IntMap[B]](empty[B])
+  }
+  
   def empty[T] : IntMap[T]  = IntMap.Nil;
   def singleton[T](key : Int, value : T) : IntMap[T] = IntMap.Tip(key, value);
   def apply[T](elems : (Int, T)*) : IntMap[T] = 
-    elems.foldLeft(empty[T])((x, y) => x.update(y._1, y._2));
-
-
-  private[immutable] case object Nil extends IntMap[Nothing]{
-    override def equals(that : Any) = this eq that.asInstanceOf[AnyRef] 
+    elems.foldLeft(empty[T])((x, y) => x.updated(y._1, y._2));
+
+  private[immutable] case object Nil extends IntMap[Nothing] {
+    // Important! Without this equals method in place, an infinite
+    // loop from Map.equals => size => pattern-match-on-Nil => equals
+    // develops.  Case objects and custom equality don't mix without
+    // careful handling.
+    override def equals(that : Any) = that match {
+      case (that : AnyRef) if (this eq that) => true;
+      case (that : IntMap[_]) => false; // The only empty IntMaps are eq Nil
+      case that => super.equals(that);
+    }
   };
+
   private[immutable] case class Tip[+T](key : Int, value : T) extends IntMap[T]{
     def withValue[S](s : S) = 
       if (s.asInstanceOf[AnyRef] eq value.asInstanceOf[AnyRef]) this.asInstanceOf[IntMap.Tip[S]];
@@ -114,22 +150,31 @@ private[immutable] class IntMapEntryIterator[V](it : IntMap[V]) extends IntMapIt
 }
 
 private[immutable] class IntMapValueIterator[V](it : IntMap[V]) extends IntMapIterator[V, V](it){
-  def valueOf(tip : IntMap.Tip[V]) = tip.value;
+  def valueOf(tip : IntMap.Tip[V]) = tip.value
 }
 
 private[immutable] class IntMapKeyIterator[V](it : IntMap[V]) extends IntMapIterator[V, Int](it){
-  def valueOf(tip : IntMap.Tip[V]) = tip.key;
+  def valueOf(tip : IntMap.Tip[V]) = tip.key
 }
 
-import IntMap._;
+import IntMap._
 
-/**
- * Specialised immutable map structure for integer keys, based on 
- * <a href="http://citeseer.ist.psu.edu/okasaki98fast.html">Fast Mergeable Integer Maps</a>
- * by Okasaki and Gill. Essentially a trie based on binary digits of the the integers.
+/** Specialised immutable map structure for integer keys, based on 
+ *  <a href="http://citeseer.ist.psu.edu/okasaki98fast.html">Fast Mergeable Integer Maps</a>
+ *  by Okasaki and Gill. Essentially a trie based on binary digits of the integers.
+ *  
+ *  Note: This class is as of 2.8 largely superseded by HashMap. 
+ *  
+ *  @tparam T    type of the values associated with integer keys.
+ *  
+ *  @since 2.7
+ *  @define Coll immutable.IntMap
+ *  @define coll immutable integer map
+ *  @define mayNotTerminateInf
+ *  @define willNotTerminateInf
  */
-sealed abstract class IntMap[+T] extends scala.collection.immutable.Map[Int, T]{
-  def empty[S] : IntMap[S] = IntMap.Nil;
+sealed abstract class IntMap[+T] extends Map[Int, T] with MapLike[Int, T, IntMap[T]] {
+  override def empty: IntMap[T] = IntMap.Nil;
 
   override def toList = {
     val buffer = new scala.collection.mutable.ListBuffer[(Int, T)];
@@ -139,8 +184,10 @@ sealed abstract class IntMap[+T] extends scala.collection.immutable.Map[Int, T]{
 
   /**
    * Iterator over key, value pairs of the map in unsigned order of the keys.
+   * 
+   * @return an iterator over pairs of integer keys and corresponding values.
    */
-  def elements : Iterator[(Int, T)] = this match {
+  def iterator : Iterator[(Int, T)] = this match {
     case IntMap.Nil => Iterator.empty;
     case _ => new IntMapEntryIterator(this);
   }
@@ -148,13 +195,13 @@ sealed abstract class IntMap[+T] extends scala.collection.immutable.Map[Int, T]{
   /**
    * Loops over the key, value pairs of the map in unsigned order of the keys. 
    */
-  override final def foreach(f : ((Int, T)) => Unit) : Unit = this match {
+  override final def foreach[U](f : ((Int, T)) =>  U) : Unit = this match {
     case IntMap.Bin(_, _, left, right) => {left.foreach(f); right.foreach(f); }
     case IntMap.Tip(key, value) => f((key, value));
     case IntMap.Nil => {};
   }
 
-  override def keys : Iterator[Int] = this match {
+  override def keysIterator : Iterator[Int] = this match {
     case IntMap.Nil => Iterator.empty;
     case _ => new IntMapKeyIterator(this);
   }
@@ -171,7 +218,7 @@ sealed abstract class IntMap[+T] extends scala.collection.immutable.Map[Int, T]{
     case IntMap.Nil => {}
   }
 
-  override def values : Iterator[T] = this match {
+  override def valuesIterator : Iterator[T] = this match {
     case IntMap.Nil => Iterator.empty;
     case _ => new IntMapValueIterator(this);
   }
@@ -204,13 +251,13 @@ sealed abstract class IntMap[+T] extends scala.collection.immutable.Map[Int, T]{
     case IntMap.Nil => IntMap.Nil;
   }
 
-  override def transform[S](f : (Int, T) => S) : IntMap[S] = this match {
+  def transform[S](f : (Int, T) => S) : IntMap[S] = this match {
     case b at IntMap.Bin(prefix, mask, left, right) => b.bin(left.transform(f), right.transform(f));
     case t at IntMap.Tip(key, value) => t.withValue(f(key, value));  
     case IntMap.Nil => IntMap.Nil;
   }
 
-  final def size : Int = this match {
+  final override def size : Int = this match {
     case IntMap.Nil => 0;
     case IntMap.Tip(_, _) => 1;
     case IntMap.Bin(_, _, left, right) => left.size + right.size;
@@ -234,26 +281,36 @@ sealed abstract class IntMap[+T] extends scala.collection.immutable.Map[Int, T]{
     case IntMap.Nil => error("key not found");
   } 
 
-  def update[S >: T](key : Int, value : S) : IntMap[S] = this match {
+  def + [S >: T] (kv: (Int, S)): IntMap[S] = updated(kv._1, kv._2)
+
+  override def updated[S >: T](key : Int, value : S) : IntMap[S] = this match {
     case IntMap.Bin(prefix, mask, left, right) => if (!hasMatch(key, prefix, mask)) join(key, IntMap.Tip(key, value), prefix, this);
-                                          else if (zero(key, mask)) IntMap.Bin(prefix, mask, left.update(key, value), right)
-                                          else IntMap.Bin(prefix, mask, left, right.update(key, value)); 
+                                          else if (zero(key, mask)) IntMap.Bin(prefix, mask, left.updated(key, value), right)
+                                          else IntMap.Bin(prefix, mask, left, right.updated(key, value)); 
     case IntMap.Tip(key2, value2) => if (key == key2) IntMap.Tip(key, value);
                              else join(key, IntMap.Tip(key, value), key2, this);
     case IntMap.Nil => IntMap.Tip(key, value);
   }
 
+  @deprecated("use `updated' instead")
+  override def update[S >: T](key: Int, value: S): IntMap[S] = updated(key, value)
+
   /**
    * Updates the map, using the provided function to resolve conflicts if the key is already present.
-   * Equivalent to 
-   * <pre>this.get(key) match { 
-   *         case None => this.update(key, value); 
-   *         case Some(oldvalue) => this.update(key, f(oldvalue, value) }
-   * </pre>
    * 
-   * @param key The key to update
-   * @param value The value to use if there is no conflict
-   * @param f The function used to resolve conflicts.
+   * Equivalent to:
+   * {{{
+   *   this.get(key) match {
+   *     case None => this.update(key, value); 
+   *     case Some(oldvalue) => this.update(key, f(oldvalue, value)
+   *   }
+   * }}}
+   * 
+   * @tparam S     The supertype of values in this `LongMap`.
+   * @param key    The key to update
+   * @param value  The value to use if there is no conflict
+   * @param f      The function used to resolve conflicts.
+   * @return       The updated map.
    */
   def updateWith[S >: T](key : Int, value : S, f : (T, S) => S) : IntMap[S] = this match {
     case IntMap.Bin(prefix, mask, left, right) => if (!hasMatch(key, prefix, mask)) join(key, IntMap.Tip(key, value), prefix, this);
@@ -264,7 +321,7 @@ sealed abstract class IntMap[+T] extends scala.collection.immutable.Map[Int, T]{
     case IntMap.Nil => IntMap.Tip(key, value);
   }
 
-  def -(key : Int) : IntMap[T] = this match {
+  def - (key : Int) : IntMap[T] = this match {
     case IntMap.Bin(prefix, mask, left, right) => 
       if (!hasMatch(key, prefix, mask)) this;
       else if (zero(key, mask)) bin(prefix, mask, left - key, right);
@@ -279,7 +336,9 @@ sealed abstract class IntMap[+T] extends scala.collection.immutable.Map[Int, T]{
    * A combined transform and filter function. Returns an IntMap such that for each (key, value) mapping
    * in this map, if f(key, value) == None the map contains no mapping for key, and if <code>f(key, value)
    * 
-   * @param f The transforming function.
+   * @tparam S  The type of the values in the resulting `LongMap`.
+   * @param f   The transforming function.
+   * @return    The modified map.
    */
   def modifyOrRemove[S](f : (Int, T) => Option[S]) : IntMap[S] = this match {
       case IntMap.Bin(prefix, mask, left, right) => {
@@ -302,8 +361,10 @@ sealed abstract class IntMap[+T] extends scala.collection.immutable.Map[Int, T]{
   /**
    * Forms a union map with that map, using the combining function to resolve conflicts.
    * 
-   * @param that the map to form a union with.
-   * @param f the function used to resolve conflicts between two mappings. 
+   * @tparam S      The type of values in `that`, a supertype of values in `this`.
+   * @param that    The map to form a union with.
+   * @param f       The function used to resolve conflicts between two mappings. 
+   * @return        Union of `this` and `that`, with identical key conflicts resolved using the function `f`.
    */ 
   def unionWith[S >: T](that : IntMap[S], f : (Int, S, S) => S) : IntMap[S] = (this, that) match{
     case (IntMap.Bin(p1, m1, l1, r1), that@(IntMap.Bin(p2, m2, l2, r2))) => 
@@ -327,12 +388,15 @@ sealed abstract class IntMap[+T] extends scala.collection.immutable.Map[Int, T]{
   }
 
   /**
-   * Forms the intersection of these two maps with a combinining function. The resulting map is
+   * Forms the intersection of these two maps with a combining function. The resulting map is
    * a map that has only keys present in both maps and has values produced from the original mappings
    * by combining them with f.
    *
-   * @param that The map to intersect with.
-   * @param f The combining function.
+   * @tparam S      The type of values in `that`.
+   * @tparam R      The type of values in the resulting `LongMap`.
+   * @param that    The map to intersect with.
+   * @param f       The combining function.
+   * @return        Intersection of `this` and `that`, with values for identical keys produced by function `f`.
    */
   def intersectionWith[S, R](that : IntMap[S], f : (Int, T, S) => R) : IntMap[R] = (this, that) match {
     case (IntMap.Bin(p1, m1, l1, r1), that at IntMap.Bin(p2, m2, l2, r2)) => 
@@ -361,15 +425,14 @@ sealed abstract class IntMap[+T] extends scala.collection.immutable.Map[Int, T]{
    * Left biased intersection. Returns the map that has all the same mappings as this but only for keys
    * which are present in the other map. 
    *
-   * @param that The map to intersect with. 
+   * @tparam R      The type of values in `that`.
+   * @param that    The map to intersect with.
+   * @return        A map with all the keys both in `this` and `that`, mapped to corresponding values from `this`.
    */
   def intersection[R](that : IntMap[R]) : IntMap[T] = this.intersectionWith(that, (key : Int, value : T, value2 : R) => value);
 
-  override def ++[S >: T](that : Iterable[(Int, S)]) = that match {
-    case (that : IntMap[_]) => this.unionWith[S](that.asInstanceOf[IntMap[S]], (key, x, y) => y);
-    case that => that.foldLeft(this : IntMap[S])({case (m, (x, y)) => m.update(x, y)});
-  }
-
+  def ++[S >: T](that : IntMap[S]) =
+    this.unionWith[S](that, (key, x, y) => y)
 
   /**
    * The entry with the lowest key value considered in unsigned order.
@@ -377,7 +440,7 @@ sealed abstract class IntMap[+T] extends scala.collection.immutable.Map[Int, T]{
   final def firstKey : Int = this match {
     case Bin(_, _, l, r) => l.firstKey;
     case Tip(k, v) => k;
-    case Nil => error("Empty set")
+    case IntMap.Nil => error("Empty set")
   }
 
   /**
@@ -386,7 +449,6 @@ sealed abstract class IntMap[+T] extends scala.collection.immutable.Map[Int, T]{
   final def lastKey : Int = this match {
     case Bin(_, _, l, r) => r.lastKey;
     case Tip(k, v) => k;
-    case Nil => error("Empty set")
+    case IntMap.Nil => error("Empty set")
   }
 }
-
diff --git a/src/library/scala/collection/immutable/Iterable.scala b/src/library/scala/collection/immutable/Iterable.scala
new file mode 100644
index 0000000..1c3cd9e
--- /dev/null
+++ b/src/library/scala/collection/immutable/Iterable.scala
@@ -0,0 +1,37 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+package immutable
+
+import generic._
+import mutable.Builder
+
+/** A base trait for iterable collections that are guaranteed immutable.
+ *  $iterableInfo
+ *  
+ *  @define Coll immutable.Iterable
+ *  @define coll immutable iterable collection
+ */
+trait Iterable[+A] extends Traversable[A] 
+                      with scala.collection.Iterable[A] 
+                      with GenericTraversableTemplate[A, Iterable]
+                      with IterableLike[A, Iterable[A]] { 
+  override def companion: GenericCompanion[Iterable] = Iterable
+}	
+
+/** $factoryInfo
+ *  @define Coll immutable.Iterable
+ *  @define coll immutable iterable collection
+ */
+object Iterable extends TraversableFactory[Iterable] {
+  implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, Iterable[A]] = new GenericCanBuildFrom[A]
+  def newBuilder[A]: Builder[A, Iterable[A]] = new mutable.ListBuffer
+}
diff --git a/src/library/scala/collection/immutable/LinearSeq.scala b/src/library/scala/collection/immutable/LinearSeq.scala
new file mode 100644
index 0000000..0493ffd
--- /dev/null
+++ b/src/library/scala/collection/immutable/LinearSeq.scala
@@ -0,0 +1,36 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+package immutable
+
+import generic._
+import mutable.Builder
+
+/** A subtrait of `collection.LinearSeq` which represents sequences that
+ *  are guaranteed immutable.
+ *  $linearSeqInfo
+ */
+trait LinearSeq[+A] extends Seq[A] 
+                            with scala.collection.LinearSeq[A] 
+                            with GenericTraversableTemplate[A, LinearSeq]
+                            with LinearSeqLike[A, LinearSeq[A]] {
+  override def companion: GenericCompanion[LinearSeq] = LinearSeq
+}
+
+/** $factoryInfo
+ *  The current default implementation of a $Coll is a `List`.
+ *  @define coll immutable linear sequence
+ *  @define Coll immutable.LinearSeq
+ */
+object LinearSeq extends SeqFactory[LinearSeq] {
+  implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, LinearSeq[A]] = new GenericCanBuildFrom[A]
+  def newBuilder[A]: Builder[A, LinearSeq[A]] = new mutable.ListBuffer
+}
diff --git a/src/library/scala/collection/immutable/List.scala b/src/library/scala/collection/immutable/List.scala
new file mode 100644
index 0000000..bc2957e
--- /dev/null
+++ b/src/library/scala/collection/immutable/List.scala
@@ -0,0 +1,791 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+package immutable
+
+import generic._
+import mutable.{Builder, ListBuffer}
+import annotation.tailrec
+
+/** A class for immutable linked lists representing ordered collections
+ *  of elements of type. 
+ *  
+ *  This class comes with two implementing case classes `scala.Nil` 
+ *  and `scala.::` that implement the abstract members `isEmpty`, 
+ *  `head` and `tail`.
+ *
+ *  @author  Martin Odersky and others
+ *  @version 2.8
+ *  @since   1.0
+ *
+ *  @tparam  A    the type of the list's elements
+ *
+ *  @define Coll List
+ *  @define coll list
+ *  @define thatinfo the class of the returned collection. In the standard library configuration,
+ *    `That` is always `List[B]` because an implicit of type `CanBuildFrom[List, B, That]`
+ *    is defined in object `List`.
+ *  @define $bfinfo an implicit value of class `CanBuildFrom` which determines the
+ *    result class `That` from the current representation type `Repr`
+ *    and the new element type `B`. This is usually the `canBuildFrom` value
+ *    defined in object `List`.
+ *  @define orderDependent 
+ *  @define orderDependentFold
+ *  @define mayNotTerminateInf
+ *  @define willNotTerminateInf
+ */
+sealed abstract class List[+A] extends LinearSeq[A] 
+                                  with Product 
+                                  with GenericTraversableTemplate[A, List]
+                                  with LinearSeqOptimized[A, List[A]] {
+  override def companion: GenericCompanion[List] = List
+
+  import scala.collection.{Iterable, Traversable, Seq, IndexedSeq}
+
+  def isEmpty: Boolean
+  def head: A
+  def tail: List[A]
+
+  // New methods in List
+
+  /** Adds an element at the beginning of this list.
+   *  @param x the element to prepend.
+   *  @return  a list which contains `x` as first element and
+   *           which continues with this list.
+   *  @example `1 :: List(2, 3) = List(2, 3).::(1) = List(1, 2, 3)`
+   *  @usecase def ::(x: A): List[A]
+   */
+  def ::[B >: A] (x: B): List[B] =
+    new scala.collection.immutable.::(x, this)
+
+  /** Adds the elements of a given list in front of this list.
+   *  @param prefix  The list elements to prepend.
+   *  @return a list resulting from the concatenation of the given
+   *    list `prefix` and this list. 
+   *  @example `List(1, 2) ::: List(3, 4) = List(3, 4).:::(List(1, 2)) = List(1, 2, 3, 4)`
+   *  @usecase def :::(prefix: List[A]): List[A]
+   */
+  def :::[B >: A](prefix: List[B]): List[B] =
+    if (isEmpty) prefix
+    else (new ListBuffer[B] ++= prefix).prependToList(this)
+
+  /** Adds the elements of a given list in reverse order in front of this list.
+   *  `xs reverse_::: ys` is equivalent to
+   *  `xs.reverse ::: ys` but is more efficient.
+   *
+   *  @param prefix the prefix to reverse and then prepend
+   *  @return       the concatenation of the reversed prefix and the current list.
+   *  @usecase def reverse_:::(prefix: List[A]): List[A]
+   */
+  def reverse_:::[B >: A](prefix: List[B]): List[B] = {
+    var these: List[B] = this
+    var pres = prefix
+    while (!pres.isEmpty) {
+      these = pres.head :: these
+      pres = pres.tail
+    }
+    these
+  }
+
+  /** Builds a new list by applying a function to all elements of this list.
+   *  Like `xs map f`, but returns `xs` unchanged if function
+   *  `f` maps all elements to themselves (wrt eq).
+   *
+   *  Note: Unlike `map`, `mapConserve` is not tail-recursive.
+   * 
+   *  @param f      the function to apply to each element.
+   *  @tparam B     the element type of the returned collection.
+   *  @return       a list resulting from applying the given function
+   *                `f` to each element of this list and collecting the results.
+   *  @usecase def mapConserve(f: A => A): List[A] 
+   */
+  def mapConserve[B >: A <: AnyRef] (f: A => B): List[B] = {
+    def loop(ys: List[A]): List[B] =
+      if (ys.isEmpty) this
+      else {
+        val head0 = ys.head
+        val head1 = f(head0)
+        if (head1 eq head0.asInstanceOf[AnyRef]) {
+          loop(ys.tail)
+        } else {
+          val ys1 = head1 :: ys.tail.mapConserve(f)
+          if (this eq ys) ys1
+          else {
+            val b = new ListBuffer[B]
+            var xc = this
+            while (xc ne ys) {
+              b += xc.head
+              xc = xc.tail
+            }
+            b.prependToList(ys1)
+          }
+        }
+      }
+    loop(this)
+  }
+
+  // Overridden methods from IterableLike and SeqLike or overloaded variants of such methods
+  
+  override def ++[B >: A, That](that: TraversableOnce[B])(implicit bf: CanBuildFrom[List[A], B, That]): That = {
+    val b = bf(this)
+    if (b.isInstanceOf[ListBuffer[_]]) (this ::: that.toList).asInstanceOf[That]
+    else super.++(that)
+  }
+
+  override def +:[B >: A, That](elem: B)(implicit bf: CanBuildFrom[List[A], B, That]): That = bf match {
+    case _: List.GenericCanBuildFrom[_] => (elem :: this).asInstanceOf[That]
+    case _ => super.+:(elem)(bf)
+  }
+
+  override def toList: List[A] = this
+
+  override def take(n: Int): List[A] = {
+    val b = new ListBuffer[A]
+    var i = 0
+    var these = this
+    while (!these.isEmpty && i < n) {
+      i += 1
+      b += these.head
+      these = these.tail
+    }
+    if (these.isEmpty) this
+    else b.toList
+  }
+
+  override def drop(n: Int): List[A] = {
+    var these = this
+    var count = n
+    while (!these.isEmpty && count > 0) {
+      these = these.tail
+      count -= 1
+    }
+    these
+  }
+
+  override def slice(start: Int, end: Int): List[A] = {
+    var len = end
+    if (start > 0) len -= start
+    drop(start) take len
+  }
+
+  override def takeRight(n: Int): List[A] = {
+    @tailrec
+    def loop(lead: List[A], lag: List[A]): List[A] = lead match {
+      case Nil => lag
+      case _ :: tail => loop(tail, lag.tail)
+    }
+    loop(drop(n), this)
+  }
+  
+  // dropRight is inherited from LinearSeq
+
+  override def splitAt(n: Int): (List[A], List[A]) = {
+    val b = new ListBuffer[A]
+    var i = 0
+    var these = this
+    while (!these.isEmpty && i < n) {
+      i += 1
+      b += these.head
+      these = these.tail
+    }
+    (b.toList, these)
+  }
+
+  override def takeWhile(p: A => Boolean): List[A] = {
+    val b = new ListBuffer[A]
+    var these = this
+    while (!these.isEmpty && p(these.head)) {
+      b += these.head
+      these = these.tail
+    }
+    b.toList
+  }
+
+  override def dropWhile(p: A => Boolean): List[A] = {
+    @tailrec
+    def loop(xs: List[A]): List[A] =
+      if (xs.isEmpty || !p(xs.head)) xs
+      else loop(xs.tail)
+
+    loop(this)
+  }
+
+  override def span(p: A => Boolean): (List[A], List[A]) = {
+    val b = new ListBuffer[A]
+    var these = this
+    while (!these.isEmpty && p(these.head)) {
+      b += these.head
+      these = these.tail
+    }
+    (b.toList, these)
+  }
+
+  override def reverse: List[A] = {
+    var result: List[A] = Nil
+    var these = this
+    while (!these.isEmpty) {
+      result = these.head :: result
+      these = these.tail
+    }
+    result
+  }
+
+  override def stringPrefix = "List"
+
+  override def toStream : Stream[A] = 
+    if (isEmpty) Stream.Empty
+    else new Stream.Cons(head, tail.toStream)
+    
+  /** Like <code>span</code> but with the predicate inverted.
+   */
+  @deprecated("use `span { x => !p(x) }` instead")
+  def break(p: A => Boolean): (List[A], List[A]) = span { x => !p(x) }
+  
+  @deprecated("use `filterNot' instead")
+  def remove(p: A => Boolean): List[A] = filterNot(p)
+
+  /** Computes the difference between this list and the given list
+   *  `that`.
+   *
+   *  @param that the list of elements to remove from this list.
+   *  @return     this list without the elements of the given list
+   *              `that`.
+   */
+  @deprecated("use `list1 filterNot (list2 contains)` instead")
+  def -- [B >: A](that: List[B]): List[B] = {
+    val b = new ListBuffer[B]
+    var these = this
+    while (!these.isEmpty) {
+      if (!that.contains(these.head)) b += these.head
+      these = these.tail
+    }
+    b.toList
+  }
+
+  /** Computes the difference between this list and the given object
+   *  `x`.
+   *
+   *  @param x    the object to remove from this list.
+   *  @return     this list without occurrences of the given object
+   *              `x`.
+   */
+  @deprecated("use `filterNot (_ == x)` instead")
+  def - [B >: A](x: B): List[B] = {
+    val b = new ListBuffer[B]
+    var these = this
+    while (!these.isEmpty) {
+      if (these.head != x) b += these.head
+      these = these.tail
+    }
+    b.toList
+  }
+  
+  @deprecated("use `distinct' instead")
+  def removeDuplicates: List[A] = distinct
+
+  /** <p>
+   *    Sort the list according to the comparison function
+   *    `lt(e1: a, e2: a) => Boolean`,
+   *    which should be true iff `e1` precedes     
+   *    `e2` in the desired ordering.
+   *  !!! todo: move sorting to IterableLike
+   *  </p>
+   *
+   *  @param lt the comparison function
+   *  @return   a list sorted according to the comparison function
+   *            `lt(e1: a, e2: a) => Boolean`.
+   *  @example <pre>
+   *    List("Steve", "Tom", "John", "Bob")
+   *      .sort((e1, e2) => (e1 compareTo e2) < 0) =
+   *    List("Bob", "John", "Steve", "Tom")</pre>
+   */
+  @deprecated("use `sortWith' instead")
+  def sort(lt : (A,A) => Boolean): List[A] = {
+    /** Merge two already-sorted lists */
+    def merge(l1: List[A], l2: List[A]): List[A] = {
+      val res = new ListBuffer[A]
+      var left1 = l1
+      var left2 = l2
+
+      while (!left1.isEmpty && !left2.isEmpty) {
+        if(lt(left1.head, left2.head)) {
+          res += left1.head
+          left1 = left1.tail
+        } else {
+          res += left2.head
+          left2 = left2.tail
+        }
+      }
+
+      res ++= left1
+      res ++= left2
+
+      res.toList
+    }
+
+    /** Split a list into two lists of about the same size */
+    def split(lst: List[A]) = {
+      val res1 = new ListBuffer[A]
+      val res2 = new ListBuffer[A]
+      var left = lst
+
+      while (!left.isEmpty) {
+        res1 += left.head
+        left = left.tail
+        if (!left.isEmpty) {
+          res2 += left.head
+          left = left.tail
+        }
+      }
+
+      (res1.toList, res2.toList)
+    }
+
+
+    /** Merge-sort the specified list */
+    def ms(lst: List[A]): List[A] =
+      lst match {
+        case Nil => lst
+        case x :: Nil => lst
+        case x :: y :: Nil =>
+          if (lt(x,y))
+            lst
+          else
+            y :: x :: Nil
+
+        case lst =>
+          val (l1, l2) = split(lst)
+          val l1s = ms(l1)
+          val l2s = ms(l2)
+          merge(l1s, l2s)
+      }
+
+    ms(this)
+  }
+
+}
+
+/** The empty list.
+ *
+ *  @author  Martin Odersky
+ *  @version 1.0, 15/07/2003
+ *  @since   2.8
+ */
+ at SerialVersionUID(0 - 8256821097970055419L)
+case object Nil extends List[Nothing] {
+  override def isEmpty = true
+  override def head: Nothing =
+    throw new NoSuchElementException("head of empty list")
+  override def tail: List[Nothing] =
+    throw new UnsupportedOperationException("tail of empty list")
+  // Removal of equals method here might lead to an infinite recursion similar to IntMap.equals.
+  override def equals(that: Any) = that match {
+    case that1: Seq[_] => that1.isEmpty
+    case _ => false
+  }
+}
+
+/** A non empty list characterized by a head and a tail.
+ *  @param hd   the first element of the list
+ *  @param tl   the list containing the remaining elements of this list after the first one.
+ *  @tparam B   the type of the list elements.
+ *  @author  Martin Odersky
+ *  @version 1.0, 15/07/2003
+ *  @since   2.8
+ */
+ at SerialVersionUID(0L - 8476791151983527571L)
+final case class ::[B](private var hd: B, private[scala] var tl: List[B]) extends List[B] {
+  override def head : B = hd
+  override def tail : List[B] = tl
+  override def isEmpty: Boolean = false
+
+  import java.io._
+
+  private def writeObject(out: ObjectOutputStream) {
+    var xs: List[B] = this
+    while (!xs.isEmpty) { out.writeObject(xs.head); xs = xs.tail }
+    out.writeObject(ListSerializeEnd)
+  }
+
+  private def readObject(in: ObjectInputStream) {
+    hd = in.readObject.asInstanceOf[B]
+    assert(hd != ListSerializeEnd)
+    var current: ::[B] = this
+    while (true) in.readObject match {
+      case ListSerializeEnd =>
+        current.tl = Nil
+        return
+      case a : Any =>
+        val list : ::[B] = new ::(a.asInstanceOf[B], Nil)
+        current.tl = list
+        current = list
+    }
+  }
+}
+
+/** $factoryInfo
+ *  @define coll list
+ *  @define Coll List
+ */
+object List extends SeqFactory[List] {
+  
+  import scala.collection.{Iterable, Seq, IndexedSeq}
+
+  /** $genericCanBuildFromInfo */
+  implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, List[A]] = new GenericCanBuildFrom[A]
+
+  def newBuilder[A]: Builder[A, List[A]] = new ListBuffer[A]
+
+  override def empty[A]: List[A] = Nil
+
+  override def apply[A](xs: A*): List[A] = xs.toList
+
+  /** Create a sorted list with element values
+   * `v<sub>n+1</sub> = step(v<sub>n</sub>)`
+   * where `v<sub>0</sub> = start`
+   * and elements are in the range between `start` (inclusive)
+   * and `end` (exclusive)
+   *
+   *  @param start the start value of the list
+   *  @param end  the end value of the list
+   *  @param step the increment function of the list, which given `v<sub>n</sub>`,
+   *              computes `v<sub>n+1</sub>`. Must be monotonically increasing
+   *              or decreasing.
+   *  @return     the sorted list of all integers in range [start;end).
+   */
+  @deprecated("use `iterate' instead")
+  def range(start: Int, end: Int, step: Int => Int): List[Int] = {
+    val up = step(start) > start
+    val down = step(start) < start
+    val b = new ListBuffer[Int]
+    var i = start
+    while ((!up || i < end) && (!down || i > end)) {
+      b += i
+      val next = step(i)
+      if (i == next)
+        throw new IllegalArgumentException("the step function did not make any progress on "+ i)
+      i = next
+    }
+    b.toList
+  }
+
+  /** Create a list containing several copies of an element.
+   *
+   *  @param n    the length of the resulting list
+   *  @param elem the element composing the resulting list
+   *  @return     a list composed of n elements all equal to elem
+   */
+  @deprecated("use `fill' instead")
+  def make[A](n: Int, elem: A): List[A] = {
+    val b = new ListBuffer[A]
+    var i = 0
+    while (i < n) {
+      b += elem
+      i += 1
+    }
+    b.toList
+  }
+
+  /** Concatenate all the elements of a given list of lists.
+   *
+   *  @param xss the list of lists that are to be concatenated
+   *  @return    the concatenation of all the lists
+   */
+  @deprecated("use `xss.flatten' instead of `List.flatten(xss)'")
+  def flatten[A](xss: List[List[A]]): List[A] = { 
+    val b = new ListBuffer[A] 
+    for (xs <- xss) {
+      var xc = xs
+      while (!xc.isEmpty) {
+        b += xc.head
+        xc = xc.tail
+      }
+    }
+    b.toList
+  }
+
+  /** Transforms a list of pairs into a pair of lists.
+   *
+   *  @param xs the list of pairs to unzip
+   *  @return a pair of lists.
+   */
+  @deprecated("use `xs.unzip' instead of `List.unzip(xs)'")
+  def unzip[A,B](xs: List[(A,B)]): (List[A], List[B]) = {
+    val b1 = new ListBuffer[A]
+    val b2 = new ListBuffer[B]
+    var xc = xs
+    while (!xc.isEmpty) {
+      b1 += xc.head._1
+      b2 += xc.head._2
+      xc = xc.tail
+    }
+    (b1.toList, b2.toList)
+  }
+
+  /** Transforms an iterable of pairs into a pair of lists.
+   *
+   *  @param xs the iterable of pairs to unzip
+   *  @return a pair of lists.
+   */
+  @deprecated("use `xs.unzip' instead of `List.unzip(xs)'")
+  def unzip[A,B](xs: Iterable[(A,B)]): (List[A], List[B]) = 
+      xs.foldRight[(List[A], List[B])]((Nil, Nil)) {
+        case ((x, y), (xs, ys)) => (x :: xs, y :: ys)
+      }
+
+  /**
+   * Returns the `Left` values in the given `Iterable`
+   * of `Either`s.
+   */
+  @deprecated("use `xs collect { case Left(x: A) => x }' instead of `List.lefts(xs)'")
+  def lefts[A, B](es: Iterable[Either[A, B]]) = 
+    es.foldRight[List[A]](Nil)((e, as) => e match {
+      case Left(a) => a :: as
+      case Right(_) => as
+    })     
+ 
+  /**
+   * Returns the `Right` values in the given`Iterable` of  `Either`s.
+   */
+  @deprecated("use `xs collect { case Right(x: B) => x }' instead of `List.rights(xs)'")
+  def rights[A, B](es: Iterable[Either[A, B]]) = 
+    es.foldRight[List[B]](Nil)((e, bs) => e match {
+      case Left(_) => bs
+      case Right(b) => b :: bs
+    })
+
+  /** Transforms an Iterable of Eithers into a pair of lists.
+   *
+   *  @param xs the iterable of Eithers to separate
+   *  @return a pair of lists.
+   */
+  @deprecated("use `(for (Left(x) <- es) yield x, for (Right(x) <- es) yield x)` instead")  
+  def separate[A,B](es: Iterable[Either[A, B]]): (List[A], List[B]) =
+    es.foldRight[(List[A], List[B])]((Nil, Nil)) {
+      case (Left(a), (lefts, rights)) => (a :: lefts, rights)
+      case (Right(b), (lefts, rights)) => (lefts, b :: rights)
+    }
+
+  /** Converts an iterator to a list.
+   *
+   *  @param it the iterator to convert
+   *  @return   a list that contains the elements returned by successive
+   *            calls to `it.next`
+   */
+  @deprecated("use `it.toList' instead of `List.toList(it)'")
+  def fromIterator[A](it: Iterator[A]): List[A] = it.toList
+
+  /** Converts an array into a list.
+   *
+   *  @param arr the array to convert
+   *  @return    a list that contains the same elements than `arr`
+   *             in the same order
+   */
+  @deprecated("use `array.toList' instead of `List.fromArray(array)'")
+  def fromArray[A](arr: Array[A]): List[A] = fromArray(arr, 0, arr.length)
+
+  /** Converts a range of an array into a list.
+   *
+   *  @param arr   the array to convert
+   *  @param start the first index to consider
+   *  @param len   the length of the range to convert
+   *  @return      a list that contains the same elements than `arr`
+   *               in the same order
+   */
+  @deprecated("use `array.view(start, end).toList' instead of `List.fromArray(array, start, end)'")
+  def fromArray[A](arr: Array[A], start: Int, len: Int): List[A] = {
+    var res: List[A] = Nil
+    var i = start + len
+    while (i > start) {
+      i -= 1
+      res = arr(i) :: res
+    }
+    res
+  }
+  
+  /** Parses a string which contains substrings separated by a
+   *  separator character and returns a list of all substrings.
+   *
+   *  @param str       the string to parse
+   *  @param separator the separator character
+   *  @return          the list of substrings
+   */
+  @deprecated("use `str.split(separator).toList' instead of `List.fromString(str, separator)'")
+  def fromString(str: String, separator: Char): List[String] = {
+    var words: List[String] = Nil
+    var pos = str.length()
+    while (pos > 0) {
+      val pos1 = str.lastIndexOf(separator, pos - 1)
+      if (pos1 + 1 < pos)
+        words = str.substring(pos1 + 1, pos) :: words
+      pos = pos1
+    }
+    words
+  }
+
+  /** Returns the given list of characters as a string.
+   *
+   *  @param xs the list to convert.
+   *  @return   the list in form of a string.
+   */
+  @deprecated("use `xs.mkString' instead of `List.toString(xs)'")
+  def toString(xs: List[Char]): String = {
+    val sb = new StringBuilder()
+    var xc = xs
+    while (!xc.isEmpty) {
+      sb.append(xc.head)
+      xc = xc.tail
+    }
+    sb.toString()
+  }
+
+  /** Like xs map f, but returns `xs` unchanged if function
+   *  `f` maps all elements to themselves.
+   */
+  @deprecated("use `xs.mapConserve(f)' instead of `List.mapConserve(xs, f)'")
+  def mapConserve[A <: AnyRef](xs: List[A])(f: A => A): List[A] = {
+    def loop(ys: List[A]): List[A] =
+      if (ys.isEmpty) xs
+      else {
+        val head0 = ys.head
+        val head1 = f(head0)
+        if (head1 eq head0) {
+          loop(ys.tail)
+        } else {
+          val ys1 = head1 :: mapConserve(ys.tail)(f)
+          if (xs eq ys) ys1
+          else {
+            val b = new ListBuffer[A]
+            var xc = xs
+            while (xc ne ys) {
+              b += xc.head
+              xc = xc.tail
+            }
+            b.prependToList(ys1)
+          }
+        }
+      }
+    loop(xs)
+  }
+
+  /** Returns the list resulting from applying the given function `f`
+   *  to corresponding elements of the argument lists.
+   *
+   *  @param f function to apply to each pair of elements.
+   *  @return `[f(a0,b0), ..., f(an,bn)]` if the lists are 
+   *          `[a0, ..., ak]`, `[b0, ..., bl]` and
+   *          `n = min(k,l)`
+   */
+  @deprecated("use `(xs, ys).zipped.map(f)' instead of `List.map2(xs, ys)(f)'")
+  def map2[A,B,C](xs: List[A], ys: List[B])(f: (A, B) => C): List[C] = {
+    val b = new ListBuffer[C]
+    var xc = xs
+    var yc = ys
+    while (!xc.isEmpty && !yc.isEmpty) {
+      b += f(xc.head, yc.head)
+      xc = xc.tail
+      yc = yc.tail
+    }
+    b.toList
+  }
+
+  /** Returns the list resulting from applying the given function
+   *  `f` to corresponding elements of the argument lists.
+   *
+   *  @param f function to apply to each pair of elements.
+   *  @return  `[f(a<sub>0</sub>,b<sub>0</sub>,c<sub>0</sub>),
+   *           ..., f(a<sub>n</sub>,b<sub>n</sub>,c<sub>n</sub>)]`
+   *           if the lists are `[a<sub>0</sub>, ..., a<sub>k</sub>]`,
+   *           `[b<sub>0</sub>, ..., b<sub>l</sub>]`,
+   *           `[c<sub>0</sub>, ..., c<sub>m</sub>]` and
+   *           `n = min(k,l,m)`
+   */
+  @deprecated("use `(xs, ys, zs).zipped.map(f)' instead of `List.map3(xs, ys, zs)(f)'")
+  def map3[A,B,C,D](xs: List[A], ys: List[B], zs: List[C])(f: (A, B, C) => D): List[D] = {
+    val b = new ListBuffer[D]
+    var xc = xs
+    var yc = ys
+    var zc = zs
+    while (!xc.isEmpty && !yc.isEmpty && !zc.isEmpty) {
+      b += f(xc.head, yc.head, zc.head)
+      xc = xc.tail
+      yc = yc.tail
+      zc = zc.tail
+    }
+    b.toList
+  }
+
+  /** Tests whether the given predicate `p` holds 
+   *  for all corresponding elements of the argument lists.
+   *
+   *  @param p function to apply to each pair of elements.
+   *  @return  `(p(a<sub>0</sub>,b<sub>0</sub>) &&
+   *           ... && p(a<sub>n</sub>,b<sub>n</sub>))]`
+   *           if the lists are `[a<sub>0</sub>, ..., a<sub>k</sub>]`;
+   *           `[b<sub>0</sub>, ..., b<sub>l</sub>]`
+   *           and `n = min(k,l)`
+   */
+  @deprecated("use `(xs, ys).zipped.forall(f)' instead of `List.forall2(xs, ys)(f)'")
+  def forall2[A,B](xs: List[A], ys: List[B])(f: (A, B) => Boolean): Boolean = {
+    var xc = xs
+    var yc = ys
+    while (!xc.isEmpty && !yc.isEmpty) {
+      if (!f(xc.head, yc.head)) return false
+      xc = xc.tail
+      yc = yc.tail
+    }
+    true
+  }
+
+  /** Tests whether the given predicate `p` holds
+   *  for some corresponding elements of the argument lists.
+   *
+   *  @param p function to apply to each pair of elements.
+   *  @return  `n != 0 && (p(a<sub>0</sub>,b<sub>0</sub>) ||
+   *           ... || p(a<sub>n</sub>,b<sub>n</sub>))]` if the lists are
+   *           `[a<sub>0</sub>, ..., a<sub>k</sub>]`,
+   *           `[b<sub>0</sub>, ..., b<sub>l</sub>]` and
+   *           `n = min(k,l)`
+   */
+  @deprecated("use `(xs, ys).zipped.exists(f)' instead of `List.exists2(xs, ys)(f)'")
+  def exists2[A,B](xs: List[A], ys: List[B])(f: (A, B) => Boolean): Boolean = {
+    var xc = xs
+    var yc = ys
+    while (!xc.isEmpty && !yc.isEmpty) {
+      if (f(xc.head, yc.head)) return true
+      xc = xc.tail
+      yc = yc.tail
+    }
+    false
+  }
+
+  /** Transposes a list of lists.
+   *  pre: All element lists have the same length.
+   *
+   *  @param xss the list of lists
+   *  @return    the transposed list of lists
+   */
+  @deprecated("use `xss.transpose' instead of `List.transpose(xss)'")
+  def transpose[A](xss: List[List[A]]): List[List[A]] = {
+    val buf = new ListBuffer[List[A]]
+    var yss = xss
+    while (!yss.head.isEmpty) {
+      buf += (yss map (_.head))
+      yss = (yss map (_.tail))
+    }
+    buf.toList
+  }
+}
+
+/** Only used for list serialization */
+ at SerialVersionUID(0L - 8476791151975527571L)
+private[scala] case object ListSerializeEnd
+
diff --git a/src/library/scala/collection/immutable/ListMap.scala b/src/library/scala/collection/immutable/ListMap.scala
index 20bac63..e7ac23d 100644
--- a/src/library/scala/collection/immutable/ListMap.scala
+++ b/src/library/scala/collection/immutable/ListMap.scala
@@ -1,58 +1,59 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: ListMap.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
+package scala.collection
+package immutable
 
-package scala.collection.immutable
+import generic._
 
-/** The canonical factory of <a href="ListMap.html">ListMap</a>'s */
-object ListMap {
-
-  /** The empty map of this type 
-   *  @deprecated   use <code>empty</code> instead
-   */
-  @deprecated
-  def Empty[A, B] = new ListMap[A, B]
-
-  /** The empty map of this type */
-  def empty[A, B] = new ListMap[A, B]
-
-  /** The canonical factory for this type 
-   */
-  def apply[A, B](elems: (A, B)*) = empty[A, B] ++ elems
+/** $factoryInfo
+ *  @since 1
+ *  @define Coll immutable.ListMap
+ *  @define coll immutable list map
+ */
+object ListMap extends ImmutableMapFactory[ListMap] {
+  /** $mapCanBuildFromInfo */
+  implicit def canBuildFrom[A, B]: CanBuildFrom[Coll, (A, B), ListMap[A, B]] =
+    new MapCanBuildFrom[A, B]
+  def empty[A, B]: ListMap[A, B] = new ListMap
 }
 
 /** This class implements immutable maps using a list-based data
- *  structure. Instances of <code>ListMap</code> represent
+ *  structure. Instances of `ListMap` represent
  *  empty maps; they can be either created by calling the constructor
- *  directly, or by applying the function <code>ListMap.empty</code>.
- *
+ *  directly, or by applying the function `ListMap.empty`.
+ *  
+ *  @tparam A     the type of the keys in this list map.
+ *  @tparam B     the type of the values associated with the keys.
+ *  
  *  @author  Matthias Zenger
- *  @author  Martin Oderskty
+ *  @author  Martin Odersky
  *  @version 2.0, 01/01/2007
+ *  @since   1
+ *  @define Coll immutable.ListMap
+ *  @define coll immutable list map
+ *  @define mayNotTerminateInf
+ *  @define willNotTerminateInf
  */
- at serializable
-class ListMap[A, +B] extends Map[A, B] {
+ at serializable @SerialVersionUID(301002838095710379L)
+class ListMap[A, +B] extends Map[A, B] with MapLike[A, B, ListMap[A, B]] {
 
-  /** Returns a <code>new ListMap</code> instance mapping keys of the
-   *  same type to values of type <code>C</code>.
-   */
-  def empty[C] = ListMap.empty[A, C]
+  override def empty = ListMap.empty
 
   /** Returns the number of mappings in this map.
    *
    *  @return number of mappings in this map.
    */
-  def size: Int = 0
+  override def size: Int = 0
 
-  /** Checks if this map maps <code>key</code> to a value and return the
+  /** Checks if this map maps `key` to a value and return the
    *  value if it exists.
    *
    *  @param  key the key of the mapping of interest
@@ -69,7 +70,24 @@ class ListMap[A, +B] extends Map[A, B] {
    *  @param key  the key element of the updated entry.
    *  @param value the value element of the updated entry.
    */
-  def update [B1 >: B](key: A, value: B1): ListMap[A, B1] = new Node(key, value)
+  override def updated [B1 >: B] (key: A, value: B1): ListMap[A, B1] = new Node[B1](key, value)
+
+  /** Add a key/value pair to this map. 
+   *  @param    kv the key/value pair
+   *  @return   A new map with the new binding added to this map
+   */
+  def + [B1 >: B] (kv: (A, B1)): ListMap[A, B1] = updated(kv._1, kv._2)
+
+  /** Adds two or more elements to this collection and returns
+   *  either the collection itself (if it is mutable), or a new collection
+   *  with the added elements.
+   *
+   *  @param elem1 the first element to add.
+   *  @param elem2 the second element to add.
+   *  @param elems the remaining elements to add.
+   */
+  override def + [B1 >: B] (elem1: (A, B1), elem2: (A, B1), elems: (A, B1) *): ListMap[A, B1] =
+    this + elem1 + elem2 ++ elems
 
   /** This creates a new mapping without the given <code>key</code>.
    *  If the map does not contain a mapping for the given key, the
@@ -81,20 +99,22 @@ class ListMap[A, +B] extends Map[A, B] {
 
   /** Returns an iterator over key-value pairs.
    */
-  def elements: Iterator[(A,B)] =
+  def iterator: Iterator[(A,B)] =
     new Iterator[(A,B)] {
       var self: ListMap[A,B] = ListMap.this
       def hasNext = !self.isEmpty
       def next: (A,B) =
         if (!hasNext) throw new NoSuchElementException("next on empty iterator")
         else { val res = (self.key, self.value); self = self.next; res }
-    }.toList.reverse.elements
+    }.toList.reverseIterator
 
   protected def key: A = throw new NoSuchElementException("empty map")
   protected def value: B = throw new NoSuchElementException("empty map")
   protected def next: ListMap[A, B] = throw new NoSuchElementException("empty map")
-
-  @serializable
+  
+  /** This class represents an entry in the `ListMap`.
+   */
+  @serializable @SerialVersionUID(-6453056603889598734L)
   protected class Node[B1 >: B](override protected val key: A, 
                                 override protected val value: B1) extends ListMap[A, B1] {
     /** Returns the number of mappings in this map.
@@ -136,9 +156,9 @@ class ListMap[A, +B] extends Map[A, B] {
      *  @param k ...
      *  @param v ...
      */
-    override def update [B2 >: B1](k: A, v: B2): ListMap[A, B2] = {
+    override def updated [B2 >: B1](k: A, v: B2): ListMap[A, B2] = {
       val m = if (contains(k)) this - k else this
-      new m.Node(k, v)
+      new m.Node[B2](k, v)
     }
 
     /** Creates a new mapping without the given <code>key</code>.
@@ -157,6 +177,6 @@ class ListMap[A, +B] extends Map[A, B] {
         else new tail.Node(key, value)
       }
 
-    override protected def next: ListMap[A,B1] = ListMap.this
+    override protected def next: ListMap[A, B1] = ListMap.this
   }
 }
diff --git a/src/library/scala/collection/immutable/ListSet.scala b/src/library/scala/collection/immutable/ListSet.scala
index 64326e3..028d73c 100644
--- a/src/library/scala/collection/immutable/ListSet.scala
+++ b/src/library/scala/collection/immutable/ListSet.scala
@@ -1,59 +1,58 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: ListSet.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.collection.immutable
+package scala.collection
+package immutable
 
+import generic._
 
-//import Predef.NoSuchElementException
-
-/** The canonical factory of <a href="ListSet.html">ListSet</a>'s */
-object ListSet {
-
-  /** constructs an empty ListSet
-   *  @deprecated   use <code>empty</code> instead
-   */
-  @deprecated
-  def Empty[A] = new ListSet[A]
-
-  /** The empty set of this type.
-   */
-  def empty[A] = new ListSet[A]
-
-  /** The canonical factory for this type 
-   */
-  def apply[A, B](elems: A*) = empty[A] ++ elems
+/** $factoryInfo
+ *  @define Coll immutable.ListSet
+ *  @define coll immutable list set
+ *  @since 1
+ */
+object ListSet extends ImmutableSetFactory[ListSet] {
+  /** setCanBuildFromInfo */
+  implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, ListSet[A]] = setCanBuildFrom[A]
+  override def empty[A] = new ListSet[A]
 }
 
 
 /** This class implements immutable sets using a list-based data
- *  structure. Instances of <code>ListSet</code> represent
+ *  structure. Instances of `ListSet` represent
  *  empty sets; they can be either created by calling the constructor
- *  directly, or by applying the function <code>ListSet.empty</code>.
- *
+ *  directly, or by applying the function `ListSet.empty`.
+ *  
+ *  @tparam A    the type of the elements contained in this list set.
+ *  
  *  @author  Matthias Zenger
  *  @version 1.0, 09/07/2003
+ *  @since   1
+ *  @define Coll immutable.ListSet
+ *  @define coll immutable list set
+ *  @define mayNotTerminateInf
+ *  @define willNotTerminateInf
  */
 @serializable
-class ListSet[A] extends AnyRef with Set[A] {
+class ListSet[A] extends Set[A] 
+                    with GenericSetTemplate[A, ListSet]
+                    with SetLike[A, ListSet[A]] { self =>
+  override def companion: GenericCompanion[ListSet] = ListSet
 
   /** Returns the number of elements in this set.
    *
    *  @return number of set elements.
    */
-  def size: Int = 0
-
+  override def size: Int = 0
   override def isEmpty: Boolean = true;
 
-  def empty[B] = ListSet.empty[B]
-
   /** Checks if this set contains element <code>elem</code>.
    *
    *  @param  elem    the element to check for membership.
@@ -63,37 +62,26 @@ class ListSet[A] extends AnyRef with Set[A] {
 
   /** This method creates a new set with an additional element.
    */
-  def +(elem: A): ListSet[A] = new Node(elem)
+  def + (elem: A): ListSet[A] = new Node(elem)
 
   /** <code>-</code> can be used to remove a single element from
    *  a set.
    */
-  def -(elem: A): ListSet[A] = this
+  def - (elem: A): ListSet[A] = this
 
   /** Creates a new iterator over all elements contained in this set.
    *
    *  @throws Predef.NoSuchElementException
    *  @return the new iterator
    */
-  def elements: Iterator[A] = new Iterator[A] {
-    var that: ListSet[A] = ListSet.this;
+  def iterator: Iterator[A] = new Iterator[A] {
+    var that: ListSet[A] = self;
     def hasNext = !that.isEmpty;
     def next: A =
       if (!hasNext) throw new NoSuchElementException("next on empty iterator")
       else { val res = that.elem; that = that.next; res }
   }
 
-  /** Compares two sets for equality.
-   *   Two set are equal iff they contain the same elements.
-   */
-  override def equals(obj: Any): Boolean = obj match {
-    case _: scala.collection.Set[_] =>
-      val that = obj.asInstanceOf[scala.collection.Set[A]]
-      (size == that.size) && (toList forall that.contains)
-    case _ =>
-      false
-  }
-
   /**
    *  @throws Predef.NoSuchElementException
    */
@@ -103,14 +91,17 @@ class ListSet[A] extends AnyRef with Set[A] {
    *  @throws Predef.NoSuchElementException
    */
   protected def next: ListSet[A] = throw new NoSuchElementException("Next of an empty set");
-
+  
+  /** Represents an entry in the `ListSet`.
+   */
   @serializable
   protected class Node(override protected val elem: A) extends ListSet[A] {
+
     /** Returns the number of elements in this set.
      *
      *  @return number of set elements.
      */
-    override def size = ListSet.this.size + 1
+    override def size = self.size + 1
         
     /** Checks if this set is empty.
      *
@@ -123,7 +114,7 @@ class ListSet[A] extends AnyRef with Set[A] {
      *  @param  elem    the element to check for membership.
      *  @return true, iff <code>elem</code> is contained in this set.
      */
-    override def contains(e: A) = (e == elem) || ListSet.this.contains(e)
+    override def contains(e: A) = (e == elem) || self.contains(e)
   
     /** This method creates a new set with an additional element.
      */
@@ -132,11 +123,11 @@ class ListSet[A] extends AnyRef with Set[A] {
     /** <code>-</code> can be used to remove a single element from
      *  a set.
      */
-    override def -(e: A): ListSet[A] = if (e == elem) ListSet.this else {
-      val tail = ListSet.this - e; new tail.Node(elem)
+    override def -(e: A): ListSet[A] = if (e == elem) self else {
+      val tail = self - e; new tail.Node(elem)
     }
 
-    override protected def next: ListSet[A] = ListSet.this
+    override protected def next: ListSet[A] = self
     
     override def stringPrefix = "Set"
   }
diff --git a/src/library/scala/collection/immutable/LongMap.scala b/src/library/scala/collection/immutable/LongMap.scala
index e2e1742..4085903 100644
--- a/src/library/scala/collection/immutable/LongMap.scala
+++ b/src/library/scala/collection/immutable/LongMap.scala
@@ -1,10 +1,28 @@
-package scala.collection.immutable;
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
 
-/**
- * @author David MacIver
+
+
+package scala.collection
+package immutable
+
+
+import scala.collection.generic.CanBuildFrom
+import scala.collection.mutable.Builder
+import scala.collection.mutable.MapBuilder
+
+
+
+/** Utility class for long maps.
+ *  @author David MacIver
  */
 private[immutable] object LongMapUtils{
-  def zero(i : Long, mask : Long) = (i & mask) == 0;    
+  def zero(i : Long, mask : Long) = (i & mask) == 0L;
   def mask(i : Long, mask : Long) = i & (complement(mask - 1) ^ mask)
   def hasMatch(key : Long, prefix : Long, m : Long) = mask(key, m) == prefix;
   def unsignedCompare(i : Long, j : Long) = (i < j) ^ (i < 0) ^ (j < 0)
@@ -39,16 +57,30 @@ private[immutable] object LongMapUtils{
 
 import LongMapUtils._
 
+/** A companion object for long maps.
+ *  @since 2.7
+ */
 object LongMap{
+  /** $mapCanBuildFromInfo */
+  implicit def canBuildFrom[A, B] = new CanBuildFrom[LongMap[A], (Long, B), LongMap[B]] {
+    def apply(from: LongMap[A]): Builder[(Long, B), LongMap[B]] = apply()
+    def apply(): Builder[(Long, B), LongMap[B]] = new MapBuilder[Long, B, LongMap[B]](empty[B])
+  }
+  
   def empty[T] : LongMap[T]  = LongMap.Nil;
   def singleton[T](key : Long, value : T) : LongMap[T] = LongMap.Tip(key, value);
   def apply[T](elems : (Long, T)*) : LongMap[T] = 
-    elems.foldLeft(empty[T])((x, y) => x.update(y._1, y._2));
-
-
-  private[immutable] case object Nil extends LongMap[Nothing]{
-    override def equals(that : Any) = this eq that.asInstanceOf[AnyRef] 
+    elems.foldLeft(empty[T])((x, y) => x.updated(y._1, y._2));
+
+  private[immutable] case object Nil extends LongMap[Nothing] {
+    // Important, don't remove this! See IntMap for explanation.
+    override def equals(that : Any) = that match {
+      case (that : AnyRef) if (this eq that) => true;
+      case (that : LongMap[_]) => false; // The only empty LongMaps are eq Nil
+      case that => super.equals(that);
+    }
   };
+
   private[immutable] case class Tip[+T](key : Long, value : T) extends LongMap[T]{
     def withValue[S](s : S) = 
       if (s.asInstanceOf[AnyRef] eq value.asInstanceOf[AnyRef]) this.asInstanceOf[LongMap.Tip[S]];
@@ -125,12 +157,22 @@ private[immutable] class LongMapKeyIterator[V](it : LongMap[V]) extends LongMapI
 import LongMap._;
 
 /**
- * Specialised immutable map structure for long keys, based on 
- * <a href="http://citeseer.ist.psu.edu/okasaki98fast.html">Fast Mergeable Long Maps</a>
- * by Okasaki and Gill. Essentially a trie based on binary digits of the the integers.
+ *  Specialised immutable map structure for long keys, based on 
+ *  <a href="http://citeseer.ist.psu.edu/okasaki98fast.html">Fast Mergeable Long Maps</a>
+ *  by Okasaki and Gill. Essentially a trie based on binary digits of the integers.
+ * 
+ *  Note: This class is as of 2.8 largely superseded by HashMap.
+ *  
+ *  @tparam T      type of the values associated with the long keys.
+ *  
+ *  @since 2.7
+ *  @define Coll immutable.LongMap
+ *  @define coll immutable long integer map
+ *  @define mayNotTerminateInf
+ *  @define willNotTerminateInf
  */
-sealed abstract class LongMap[+T] extends scala.collection.immutable.Map[Long, T]{
-  def empty[S] : LongMap[S] = LongMap.Nil;
+sealed abstract class LongMap[+T] extends Map[Long, T] with MapLike[Long, T, LongMap[T]] {
+  override def empty: LongMap[T] = LongMap.Nil;
 
   override def toList = {
     val buffer = new scala.collection.mutable.ListBuffer[(Long, T)];
@@ -140,8 +182,10 @@ sealed abstract class LongMap[+T] extends scala.collection.immutable.Map[Long, T
 
   /**
    * Iterator over key, value pairs of the map in unsigned order of the keys.
+   * 
+   * @return an iterator over pairs of long keys and corresponding values.
    */
-  def elements : Iterator[(Long, T)] = this match {
+  def iterator: Iterator[(Long, T)] = this match {
     case LongMap.Nil => Iterator.empty;
     case _ => new LongMapEntryIterator(this);
   }
@@ -149,13 +193,13 @@ sealed abstract class LongMap[+T] extends scala.collection.immutable.Map[Long, T
   /**
    * Loops over the key, value pairs of the map in unsigned order of the keys. 
    */
-  override final def foreach(f : ((Long, T)) => Unit) : Unit = this match {
+  override final def foreach[U](f : ((Long, T)) =>  U) : Unit = this match {
     case LongMap.Bin(_, _, left, right) => {left.foreach(f); right.foreach(f); }
     case LongMap.Tip(key, value) => f((key, value));
     case LongMap.Nil => {};
   }
 
-  override def keys : Iterator[Long] = this match {
+  override def keysIterator : Iterator[Long] = this match {
     case LongMap.Nil => Iterator.empty;
     case _ => new LongMapKeyIterator(this);
   }
@@ -172,7 +216,7 @@ sealed abstract class LongMap[+T] extends scala.collection.immutable.Map[Long, T
     case LongMap.Nil => {}
   }
 
-  override def values : Iterator[T] = this match {
+  override def valuesIterator : Iterator[T] = this match {
     case LongMap.Nil => Iterator.empty;
     case _ => new LongMapValueIterator(this);
   }
@@ -205,13 +249,13 @@ sealed abstract class LongMap[+T] extends scala.collection.immutable.Map[Long, T
     case LongMap.Nil => LongMap.Nil;
   }
 
-  override def transform[S](f : (Long, T) => S) : LongMap[S] = this match {
+  def transform[S](f : (Long, T) => S) : LongMap[S] = this match {
     case b at LongMap.Bin(prefix, mask, left, right) => b.bin(left.transform(f), right.transform(f));
     case t at LongMap.Tip(key, value) => t.withValue(f(key, value));  
     case LongMap.Nil => LongMap.Nil;
   }
 
-  final def size : Int = this match {
+  final override def size : Int = this match {
     case LongMap.Nil => 0;
     case LongMap.Tip(_, _) => 1;
     case LongMap.Bin(_, _, left, right) => left.size + right.size;
@@ -235,26 +279,36 @@ sealed abstract class LongMap[+T] extends scala.collection.immutable.Map[Long, T
     case LongMap.Nil => error("key not found");
   } 
 
-  def update[S >: T](key : Long, value : S) : LongMap[S] = this match {
+  def + [S >: T] (kv: (Long, S)): LongMap[S] = updated(kv._1, kv._2)
+
+  override def updated[S >: T](key : Long, value : S) : LongMap[S] = this match {
     case LongMap.Bin(prefix, mask, left, right) => if (!hasMatch(key, prefix, mask)) join(key, LongMap.Tip(key, value), prefix, this);
-                                          else if (zero(key, mask)) LongMap.Bin(prefix, mask, left.update(key, value), right)
-                                          else LongMap.Bin(prefix, mask, left, right.update(key, value)); 
+                                          else if (zero(key, mask)) LongMap.Bin(prefix, mask, left.updated(key, value), right)
+                                          else LongMap.Bin(prefix, mask, left, right.updated(key, value)); 
     case LongMap.Tip(key2, value2) => if (key == key2) LongMap.Tip(key, value);
                              else join(key, LongMap.Tip(key, value), key2, this);
     case LongMap.Nil => LongMap.Tip(key, value);
   }
 
+  @deprecated("use `updated' instead")
+  override def update[S >: T](key: Long, value: S): LongMap[S] = updated(key, value)
+
   /**
    * Updates the map, using the provided function to resolve conflicts if the key is already present.
+   * 
    * Equivalent to 
-   * <pre>this.get(key) match { 
-   *         case None => this.update(key, value); 
-   *         case Some(oldvalue) => this.update(key, f(oldvalue, value) }
-   * </pre>
+   * {{{
+   *   this.get(key) match { 
+   *     case None => this.update(key, value); 
+   *     case Some(oldvalue) => this.update(key, f(oldvalue, value)
+   *   }
+   * }}}
    * 
-   * @param key The key to update
-   * @param value The value to use if there is no conflict
-   * @param f The function used to resolve conflicts.
+   * @tparam S     The supertype of values in this `LongMap`.
+   * @param key    The key to update.
+   * @param value  The value to use if there is no conflict.
+   * @param f      The function used to resolve conflicts.
+   * @return       The updated map.
    */
   def updateWith[S >: T](key : Long, value : S, f : (T, S) => S) : LongMap[S] = this match {
     case LongMap.Bin(prefix, mask, left, right) => if (!hasMatch(key, prefix, mask)) join(key, LongMap.Tip(key, value), prefix, this);
@@ -280,7 +334,9 @@ sealed abstract class LongMap[+T] extends scala.collection.immutable.Map[Long, T
    * A combined transform and filter function. Returns an LongMap such that for each (key, value) mapping
    * in this map, if f(key, value) == None the map contains no mapping for key, and if <code>f(key, value)
    * 
-   * @param f The transforming function.
+   * @tparam S    The type of the values in the resulting `LongMap`.
+   * @param f     The transforming function.
+   * @return      The modified map.
    */
   def modifyOrRemove[S](f : (Long, T) => Option[S]) : LongMap[S] = this match {
       case LongMap.Bin(prefix, mask, left, right) => {
@@ -303,8 +359,10 @@ sealed abstract class LongMap[+T] extends scala.collection.immutable.Map[Long, T
   /**
    * Forms a union map with that map, using the combining function to resolve conflicts.
    * 
-   * @param that the map to form a union with.
-   * @param f the function used to resolve conflicts between two mappings. 
+   * @tparam S      The type of values in `that`, a supertype of values in `this`.
+   * @param that    The map to form a union with.
+   * @param f       The function used to resolve conflicts between two mappings. 
+   * @return        Union of `this` and `that`, with identical key conflicts resolved using the function `f`.
    */ 
   def unionWith[S >: T](that : LongMap[S], f : (Long, S, S) => S) : LongMap[S] = (this, that) match{
     case (LongMap.Bin(p1, m1, l1, r1), that@(LongMap.Bin(p2, m2, l2, r2))) => 
@@ -328,12 +386,15 @@ sealed abstract class LongMap[+T] extends scala.collection.immutable.Map[Long, T
   }
 
   /**
-   * Forms the intersection of these two maps with a combinining function. The resulting map is
+   * Forms the intersection of these two maps with a combining function. The resulting map is
    * a map that has only keys present in both maps and has values produced from the original mappings
    * by combining them with f.
-   *
-   * @param that The map to intersect with.
-   * @param f The combining function.
+   * 
+   * @tparam S      The type of values in `that`.
+   * @tparam R      The type of values in the resulting `LongMap`.
+   * @param that    The map to intersect with.
+   * @param f       The combining function.
+   * @return        Intersection of `this` and `that`, with values for identical keys produced by function `f`.
    */
   def intersectionWith[S, R](that : LongMap[S], f : (Long, T, S) => R) : LongMap[R] = (this, that) match {
     case (LongMap.Bin(p1, m1, l1, r1), that at LongMap.Bin(p2, m2, l2, r2)) => 
@@ -362,13 +423,13 @@ sealed abstract class LongMap[+T] extends scala.collection.immutable.Map[Long, T
    * Left biased intersection. Returns the map that has all the same mappings as this but only for keys
    * which are present in the other map. 
    *
-   * @param that The map to intersect with. 
+   * @tparam R      The type of values in `that`.
+   * @param that    The map to intersect with.
+   * @return        A map with all the keys both in `this` and `that`, mapped to corresponding values from `this`.
    */
   def intersection[R](that : LongMap[R]) : LongMap[T] = this.intersectionWith(that, (key : Long, value : T, value2 : R) => value);
 
-  override def ++[S >: T](that : Iterable[(Long, S)]) = that match {
-    case (that : LongMap[_]) => this.unionWith[S](that.asInstanceOf[LongMap[S]], (key, x, y) => y);
-    case that => that.foldLeft(this : LongMap[S])({case (m, (x, y)) => m.update(x, y)});
-  }
+  def ++[S >: T](that : LongMap[S]) =
+    this.unionWith[S](that, (key, x, y) => y)
 }
 
diff --git a/src/library/scala/collection/immutable/Map.scala b/src/library/scala/collection/immutable/Map.scala
index fc8f117..a4435c6 100644
--- a/src/library/scala/collection/immutable/Map.scala
+++ b/src/library/scala/collection/immutable/Map.scala
@@ -1,251 +1,184 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Map.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.collection.immutable
+package scala.collection
+package immutable
 
-import Predef._
+import generic._
 
-/** <p>An object for creating immutable maps. These are implemented using
-  *         <a href="HashMap.html">immutable hash maps</a>.
-  *  </p>*/
-object Map {
-  def empty[A, B]: Map[A, B] = new EmptyMap[A, B]
-
-  def apply[A, B](elems: (A, B)*) = empty[A, B] ++ elems
-}
-
-/** <p>
- *    This class defines the interface for immutable maps.  Operations
- *    on an immutable map leave the original map unchanged, and return
- *    a new map if needed.
- *  </p>
- *  <p>
- *    Concrete map implementations have to provide functionality for
- *    the abstract methods in <a href="../Map.html" target="contentFrame">
- *    <code>scala.collection.Map</code></a> as well as for 
- *    <code>factory</code>, <code>update</code>, and <code>-</code>.
- *  </p>
+/**
+ * A generic trait for immutable maps. Concrete classes have to provide
+ * functionality for the abstract methods in `Map`:
  *
- *  @author  Matthias Zenger
- *  @author  Erik Stenman
- *  @author  Martin Odersky
- *  @version 1.2, 31/06/2006
+ * {{{
+ *    def get(key: A): Option[B]
+ *    def iterator: Iterator[(A, B)]
+ *    def + [B1 >: B](kv: (A, B1)): Map[A, B1]
+ *    def -(key: A): Map[A, B]
+ * }}}
+ * 
+ * @since 1
  */
-trait Map[A, +B] extends collection.Map[A, B] {
+trait Map[A, +B] extends Iterable[(A, B)] 
+                    with scala.collection.Map[A, B] 
+                    with MapLike[A, B, Map[A, B]] { self =>
 
-  /** This method returns a new map instance of the same class
-   *  mapping keys of the same type to values of type <code>C</code>.
-   */
-  def empty[C]: Map[A, C]
-
-  /** This method allows one to create a new map with an
-   *  additional mapping from <code>key</code>
-   *  to <code>value</code>. If the map contains already a
-   *  mapping for <code>key</code>, it will be overridden by this
-   *  function.
-   *
-   *  @param key   ...
-   *  @param value ...
-   *  @return      the created map
-   *  @deprecated    use <code>+({A, B})</code> instead
-   */
-  def update [B1 >: B] (key: A, value: B1): Map[A, B1]
+  override def empty: Map[A, B] = Map.empty
 
   /** Add a key/value pair to this map. 
-   *  @param    kv the key/value pair.
+   *  @param    key the key
+   *  @param    value the value
    *  @return   A new map with the new binding added to this map
    */
-  def + [B1 >: B] (kv: (A, B1)): Map[A, B1] = update(kv._1, kv._2)
-
-  /** Add two or more key/value pairs to this map. 
-   *  @param    kv1 the first key/value pair.
-   *  @param    kv2 the second key/value pair.
-   *  @param    kvs the remaining key/value pairs.
-   *  @return   A new map with the new bindings added
-   */
-  def + [B1 >: B] (kv1: (A, B1), kv2: (A, B1), kvs: (A, B1)*): Map[A, B1] =
-    this + kv1 + kv2 ++ kvs
+  override def updated [B1 >: B](key: A, value: B1): Map[A, B1]
+  def + [B1 >: B](kv: (A, B1)): Map[A, B1]
 
-  /** Add a sequence of key/value pairs to this map. 
-   *  @param    kvs the iterable object containing all key/value pairs.
-   *  @return   A new map with the new bindings added
-   */
-  def ++ [B1 >: B] (kvs: Iterable[(A, B1)]): Map[A, B1] = 
-    ((this: Map[A, B1]) /: kvs) ((m, kv) => m + kv)
-
-  /** Add a sequence of key/value pairs to this map. 
-   *  @param    kvs the iterator containing all key/value pairs.
-   *  @return   A new map with the new bindings added
-   */   
-  def ++ [B1 >: B] (kvs: Iterator[(A, B1)]): Map[A, B1] =
-    ((this: Map[A, B1]) /: kvs) ((m, kv) => m + kv)
-
-  /** Remove a key from this map
-   *  @param    key the key to be removed
-   *  @return   If the map does not contain a binding for <code>key</code>
-   *            it is returned unchanged. Otherwise, return a new map 
-   *            without a binding for <code>key</code>
-   */
-  def - (key: A): Map[A, B]
-  
-  /** Remove two or more keys from this map
-   *  @param    key1 the first key to be removed
-   *  @param    key2 the second key to be removed
-   *  @param    keys the remaining keys to be removed
-   *  @return   A map without bindings for <code>keys</code>
-   *            If the map is mutable, the bindings are removed in place 
-   *            and the map itself is returned. 
-   *            If the map is immutable, a new map with the bindings removed is returned.
-   */
-  def - (key1: A, key2: A, keys: A*): Map[A, B] = 
-    this - key1 - key2 -- keys
-
-  /** Remove a sequence of keys from this map
-   *  @param    keys the keys to be removed
-   *  @return   A map without bindings for the given keys.
-   *            If the map is mutable, the bindings are removed in place 
-   *            and the map itself is returned. 
-   *            If the map is immutable, a new map with the bindings removed is returned.
-   */
-  def -- (keys: Iterable[A]): Map[A, B] = this -- keys.elements
-
-  /** Remove a sequence of keys from this map
-   *  @param    keys the keys to be removed
-   *  @return   A map without bindings for the given keys.
-   *            If the map is mutable, the bindings are removed in place 
-   *            and the map itself is returned. 
-   *            If the map is immutable, a new map with the bindings removed is returned.
-   */
-  def -- (keys: Iterator[A]): Map[A, B] = 
-    (this /: keys) ((m, key) => m - key)
-
-
-  /** The same map with a given default function */
-  def withDefault[B1 >: B](d: A => B1): Map[A, B1] = new Map[A, B1] {
-    def size = Map.this.size
-    def get(key: A) = Map.this.get(key)
-    def elements = Map.this.elements
-    def empty[C] = Map.this.empty
-    def update [B2 >: B1](key: A, value: B2): Map[A, B2] = 
-      Map.this.update(key, value) withDefault d
-    def -(key: A): Map[A, B1] = Map.this - key withDefault d
-    override def default(key: A): B1 = d(key)
-  }
+  /** The same map with a given default function !!! todo: move to general maps? */
+  def withDefault[B1 >: B](d: A => B1): Map[A, B1] = new Map.WithDefault[A, B1](this, d) 
 
   /** The same map with a given default value */
-  def withDefaultValue[B1 >: B](d: B1): Map[A, B1] = withDefault(x => d)
+  def withDefaultValue[B1 >: B](d: B1): Map[A, B1] = new Map.WithDefault[A, B1](this, x => d)
+}
 
-  /** This function transforms all the values of mappings contained
-   *  in this map with function <code>f</code>.
-   *
-   *  @param f A function over keys and values
-   *  @return  the updated map
-   */
-  def transform[C](f: (A, B) => C): Map[A, C] = {
-    var res = empty[C]
-    foreach { case (key, value) => res = res.update(key, f(key, value)) }
-    res
+/** $factoryInfo
+ *  @define Coll immutable.Map
+ *  @define coll immutable map
+ */
+object Map extends ImmutableMapFactory[Map] {
+  
+  /** $mapCanBuildFromInfo */
+  implicit def canBuildFrom[A, B]: CanBuildFrom[Coll, (A, B), Map[A, B]] = new MapCanBuildFrom[A, B]
+
+  def empty[A, B]: Map[A, B] = EmptyMap.asInstanceOf[Map[A, B]]
+
+  class WithDefault[A, +B](underlying: Map[A, B], d: A => B) extends Map[A, B] {
+    override def size = underlying.size
+    def get(key: A) = underlying.get(key) orElse Some(default(key))
+    def iterator = underlying.iterator
+    override def empty = new WithDefault(underlying.empty, d)
+    override def updated[B1 >: B](key: A, value: B1): WithDefault[A, B1] = new WithDefault[A, B1](underlying.updated[B1](key, value), d)
+    def + [B1 >: B](kv: (A, B1)): WithDefault[A, B1] = updated(kv._1, kv._2)
+    def - (key: A): WithDefault[A, B] = new WithDefault(underlying - key, d)
+    override def default(key: A): B = d(key)
   }
 
-  /** This method removes all the mappings for which the predicate
-   *  <code>p</code> returns <code>false</code>.
-   *
-   *  @param p A prediacte over key-value pairs
-   *  @return  the updated map
-   */
-  override def filter(p: ((A, B)) => Boolean): Map[A, B] = {
-    var res = this
-    foreach {
-      case kv @ (key, _) => if (!p(kv)) { res = res - key }
-    }
-    res
+  @serializable
+  private object EmptyMap extends Map[Any, Nothing] {
+    override def size: Int = 0
+    def get(key: Any): Option[Nothing] = None
+    def iterator: Iterator[(Any, Nothing)] = Iterator.empty
+    override def updated [B1] (key: Any, value: B1): Map[Any, B1] = new Map1(key, value)
+    def + [B1](kv: (Any, B1)): Map[Any, B1] = updated(kv._1, kv._2)
+    def - (key: Any): Map[Any, Nothing] = this
   }
 
-  /** <p>
-   *    This method defines syntactic sugar for adding a
-   *    mapping. It is typically used in the following way:
-   *  </p>
-   *  <pre>
-   *    map + key -> value
-   *  </pre>
-   *  @deprecated  use <code>+({A, B})</code> instead
-   */
-  @deprecated def +(key: A): MapTo = new MapTo(key)
-    
-  /** <code>incl</code> can be used to add many mappings at the same time
-   *  to the map. The method assumes that a mapping is represented
-   *  by a <code>Pair</code> object who's first component denotes the
-   *  key, and who's second component refers to the value.
-   *
-   *  @param mappings ...
-   *  @return         ...
-   *  @deprecated   use <code>+</code> instead
-   */
-  @deprecated def incl[B1 >: B](mappings: (A, B1)*): Map[A, B1] = incl(mappings)
+  @serializable @deprecated("use `Map.empty' instead")
+  class EmptyMap[A,B] extends Map[A,B] {
+    override def size: Int = 0
+    def get(key: A): Option[B] = None
+    def iterator: Iterator[(A, B)] = Iterator.empty
+    override def updated [B1] (key: A, value: B1): Map[A, B1] = new Map1(key, value)
+    def + [B1](kv: (A, B1)): Map[A, B1] = updated(kv._1, kv._2)
+    def - (key: A): Map[A, B] = this
+  }
   
-  /** <code>incl</code> can be used to add many mappings at the same time
-   *  to the map. The method assumes that each mapping is represented
-   *  by an Iterator over <code>Pair</code> objects who's first component 
-   *  denotes the key, and who's second component refers to the value.
-   *
-   *  @deprecated    use <code>++</code> instead
-   */    
-  @deprecated def incl[B1 >: B](map: Iterable[(A, B1)]): Map[A, B1] = {
-    val iter = map.elements
-    var res: Map[A, B1] = this
-    while (iter.hasNext) {
-      val (key, value) = iter.next
-      res = res.update(key, value)
+  @serializable
+  class Map1[A, +B](key1: A, value1: B) extends Map[A, B] {
+    override def size = 1
+    def get(key: A): Option[B] = 
+      if (key == key1) Some(value1) else None
+    def iterator = Iterator((key1, value1))
+    override def updated [B1 >: B] (key: A, value: B1): Map[A, B1] = 
+      if (key == key1) new Map1(key1, value)
+      else new Map2(key1, value1, key, value)
+    def + [B1 >: B](kv: (A, B1)): Map[A, B1] = updated(kv._1, kv._2)
+    def - (key: A): Map[A, B] = 
+      if (key == key1) Map.empty else this
+    override def foreach[U](f: ((A, B)) =>  U): Unit = {
+      f((key1, value1))
     }
-    res
   }
-    
-  /** This method will return a map where all the mappings 
-   *  for the given sequence of keys are removed from the map.
-   *
-   *  @param keys ...
-   *  @return     the updated map
-   *  @deprecated    use <code>-</code> instead
-   */
-  @deprecated def excl(keys: A*): Map[A, B] = excl(keys)
-  
-  /** This method removes all the mappings for keys provided by an
-   *  iterator over the elements of the <code>keys</code> object.
-   *
-   *  @param keys ...
-   *  @return     the updated map
-   *  @deprecated    use <code>--</code> instead   
-   */
-  @deprecated def excl(keys: Iterable[A]): Map[A, B] = {
-    val iter = keys.elements
-    var res = this
-    while (iter.hasNext) {
-      res = res - iter.next
+
+  @serializable
+  class Map2[A, +B](key1: A, value1: B, key2: A, value2: B) extends Map[A, B] {
+    override def size = 2
+    def get(key: A): Option[B] = 
+      if (key == key1) Some(value1) 
+      else if (key == key2) Some(value2)
+      else None
+    def iterator = Iterator((key1, value1), (key2, value2))
+    override def updated [B1 >: B] (key: A, value: B1): Map[A, B1] = 
+      if (key == key1) new Map2(key1, value, key2, value2)
+      else if (key == key2) new Map2(key1, value1, key2, value)
+      else new Map3(key1, value1, key2, value2, key, value)
+    def + [B1 >: B](kv: (A, B1)): Map[A, B1] = updated(kv._1, kv._2)
+    def - (key: A): Map[A, B] = 
+      if (key == key1) new Map1(key2, value2)
+      else if (key == key2) new Map1(key1, value1)
+      else this
+    override def foreach[U](f: ((A, B)) =>  U): Unit = {
+      f((key1, value1)); f((key2, value2))
     }
-    res
   }
 
-  /** This method controls how a mapping is represented in the string
-   *  representation provided by method <code>toString</code>.
-   *
-   *  @param p ...
-   *  @return  the string representation of a map entry
-   */
-  @deprecated def mappingToString[B1 >: B](p: (A, B1)) =
-    p._1.toString() + " -> " + p._2
-    
-  /** @deprecated    use <code>+({A, B})</code> instead
-   */
-  @deprecated class MapTo(key: A) {
-    def -> [B1 >: B](value: B1) = update(key, value)
+  @serializable
+  class Map3[A, +B](key1: A, value1: B, key2: A, value2: B, key3: A, value3: B) extends Map[A, B] {
+    override def size = 3
+    def get(key: A): Option[B] = 
+      if (key == key1) Some(value1) 
+      else if (key == key2) Some(value2)
+      else if (key == key3) Some(value3)
+      else None
+    def iterator = Iterator((key1, value1), (key2, value2), (key3, value3))
+    override def updated [B1 >: B] (key: A, value: B1): Map[A, B1] = 
+      if (key == key1)      new Map3(key1, value, key2, value2, key3, value3)
+      else if (key == key2) new Map3(key1, value1, key2, value, key3, value3)
+      else if (key == key3) new Map3(key1, value1, key2, value2, key3, value)
+      else new Map4(key1, value1, key2, value2, key3, value3, key, value)
+    def + [B1 >: B](kv: (A, B1)): Map[A, B1] = updated(kv._1, kv._2)
+    def - (key: A): Map[A, B] = 
+      if (key == key1)      new Map2(key2, value2, key3, value3)
+      else if (key == key2) new Map2(key1, value1, key3, value3)
+      else if (key == key3) new Map2(key1, value1, key2, value2)
+      else this
+    override def foreach[U](f: ((A, B)) =>  U): Unit = {
+      f((key1, value1)); f((key2, value2)); f((key3, value3))
+    }
+  }
+ 
+  @serializable
+  class Map4[A, +B](key1: A, value1: B, key2: A, value2: B, key3: A, value3: B, key4: A, value4: B) extends Map[A, B] {
+    override def size = 4
+    def get(key: A): Option[B] = 
+      if (key == key1) Some(value1) 
+      else if (key == key2) Some(value2)
+      else if (key == key3) Some(value3)
+      else if (key == key4) Some(value4)
+      else None
+    def iterator = Iterator((key1, value1), (key2, value2), (key3, value3), (key4, value4))
+    override def updated [B1 >: B] (key: A, value: B1): Map[A, B1] = 
+      if (key == key1)      new Map4(key1, value, key2, value2, key3, value3, key4, value4)
+      else if (key == key2) new Map4(key1, value1, key2, value, key3, value3, key4, value4)
+      else if (key == key3) new Map4(key1, value1, key2, value2, key3, value, key4, value4)
+      else if (key == key4) new Map4(key1, value1, key2, value2, key3, value3, key4, value)
+      else new HashMap + ((key1, value1), (key2, value2), (key3, value3), (key4, value4), (key, value))
+    def + [B1 >: B](kv: (A, B1)): Map[A, B1] = updated(kv._1, kv._2)
+    def - (key: A): Map[A, B] = 
+      if (key == key1)      new Map3(key2, value2, key3, value3, key4, value4)
+      else if (key == key2) new Map3(key1, value1, key3, value3, key4, value4)
+      else if (key == key3) new Map3(key1, value1, key2, value2, key4, value4)
+      else if (key == key4) new Map3(key1, value1, key2, value2, key3, value3)
+      else this
+    override def foreach[U](f: ((A, B)) =>  U): Unit = {
+      f((key1, value1)); f((key2, value2)); f((key3, value3)); f((key4, value4))
+    }
   }
 }
 
diff --git a/src/library/scala/collection/immutable/Map1.scala b/src/library/scala/collection/immutable/Map1.scala
deleted file mode 100644
index 6c8a112..0000000
--- a/src/library/scala/collection/immutable/Map1.scala
+++ /dev/null
@@ -1,43 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: Map1.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-
-package scala.collection.immutable
-
-import Predef.Pair
-
-/** This class implements immutable maps with exactly one entry
- *
- *  @author  Martin Oderskty
- *  @version 1.0, 019/01/2007
- */
- at serializable
-class Map1[A, +B](key1: A, value1: B) extends Map[A, B] {
-
-  def size = 1
-
-  def get(key: A): Option[B] = 
-    if (key == key1) Some(value1) else None
-
-  def elements = Iterator.single((key1, value1))
-
-  def empty[B]: Map[A, B] = new EmptyMap[A, B]
-
-  def update [B1 >: B](key: A, value: B1): Map[A, B1] = 
-    if (key == key1) new Map1(key1, value)
-    else new Map2(key1, value1, key, value)
-
-  def - (key: A): Map[A, B] = 
-    if (key == key1) empty else this
-}
-  
-
-
diff --git a/src/library/scala/collection/immutable/Map2.scala b/src/library/scala/collection/immutable/Map2.scala
deleted file mode 100644
index 349d904..0000000
--- a/src/library/scala/collection/immutable/Map2.scala
+++ /dev/null
@@ -1,48 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: Map2.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-
-package scala.collection.immutable
-
-import Predef.Pair
-
-/** This class implements immutable maps with exactly two entries
- *  @author  Martin Oderskty
- *  @version 1.0, 019/01/2007
- */
- at serializable
-class Map2[A, +B](key1: A, value1: B, key2: A, value2: B) extends Map[A, B] {
-
-  def size = 2
-
-  def get(key: A): Option[B] = 
-    if (key == key1) Some(value1) 
-    else if (key == key2) Some(value2)
-    else None
-
-  def elements = Iterator.fromValues(
-    (key1, value1), (key2, value2))
-
-  def empty[C]: Map[A, C] = new EmptyMap[A, C]
-
-  def update [B1 >: B](key: A, value: B1): Map[A, B1] = 
-    if (key == key1) new Map2(key1, value, key2, value2)
-    else if (key == key2) new Map2(key1, value1, key2, value)
-    else new Map3(key1, value1, key2, value2, key, value)
-
-  def - (key: A): Map[A, B] = 
-    if (key == key1) new Map1(key2, value2) 
-    else if (key == key2) new Map1(key1, value1) 
-    else this
-}
-  
-
-
diff --git a/src/library/scala/collection/immutable/Map3.scala b/src/library/scala/collection/immutable/Map3.scala
deleted file mode 100644
index 880b8b8..0000000
--- a/src/library/scala/collection/immutable/Map3.scala
+++ /dev/null
@@ -1,51 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: Map3.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-
-package scala.collection.immutable
-
-import Predef.Pair
-
-/** This class implements immutable maps with exactly three entries
- *  @author  Martin Oderskty
- *  @version 1.0, 019/01/2007
- */
- at serializable
-class Map3[A, +B](key1: A, value1: B, key2: A, value2: B, key3: A, value3: B) extends Map[A, B] {
-
-  def size = 3
-
-  def get(key: A): Option[B] = 
-    if (key == key1) Some(value1) 
-    else if (key == key2) Some(value2)
-    else if (key == key3) Some(value3)
-    else None
-
-  def elements = Iterator.fromValues(
-    (key1, value1), (key2, value2), (key3, value3))
-
-  def empty[C]: Map[A, C] = new EmptyMap[A, C]
-
-  def update [B1 >: B](key: A, value: B1): Map[A, B1] = 
-    if (key == key1) new Map3(key1, value, key2, value2, key3, value3)
-    else if (key == key2) new Map3(key1, value1, key2, value, key3, value3)
-    else if (key == key3) new Map3(key1, value1, key2, value2, key3, value)
-    else new Map4(key1, value1, key2, value2, key3, value3, key, value)
-
-  def - (key: A): Map[A, B] = 
-    if (key == key1) new Map2(key2, value2, key3, value3) 
-    else if (key == key2) new Map2(key1, value1, key3, value3) 
-    else if (key == key3) new Map2(key1, value1, key2, value2) 
-    else this
-}
-  
-
-
diff --git a/src/library/scala/collection/immutable/Map4.scala b/src/library/scala/collection/immutable/Map4.scala
deleted file mode 100644
index 45974d3..0000000
--- a/src/library/scala/collection/immutable/Map4.scala
+++ /dev/null
@@ -1,52 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: Map4.scala 16894 2009-01-13 13:09:41Z cunei $
-
-package scala.collection.immutable
-
-import Predef._
-
-/** This class implements immutable maps with exactly four entries
- *  @author  Martin Oderskty
- *  @version 1.0, 019/01/2007
- */
- at serializable
-class Map4[A, +B](key1: A, value1: B, key2: A, value2: B, key3: A, value3: B, key4: A, value4: B) extends Map[A, B] {
-
-  def size = 4
-
-  def get(key: A): Option[B] = 
-    if      (key == key1) Some(value1) 
-    else if (key == key2) Some(value2)
-    else if (key == key3) Some(value3)
-    else if (key == key4) Some(value4)
-    else None
-
-  def elements = Iterator.fromValues(
-    (key1, value1), (key2, value2), (key3, value3), (key4, value4))
-
-  def empty[C]: Map[A, C] = new EmptyMap[A, C]
-
-  def update [B1 >: B](key: A, value: B1): Map[A, B1] = 
-    if      (key == key1) new Map4(key1, value, key2, value2, key3, value3, key4, value4)
-    else if (key == key2) new Map4(key1, value1, key2, value, key3, value3, key4, value4)
-    else if (key == key3) new Map4(key1, value1, key2, value2, key3, value, key4, value4)
-    else if (key == key4) new Map4(key1, value1, key2, value2, key3, value3, key4, value)
-    else HashMap(key1 -> value1, key2 -> value2, key3 -> value3, key4 -> value4, key -> value)
-
-  def - (key: A): Map[A, B] = 
-    if      (key == key1) new Map3(key2, value2, key3, value3, key4, value4) 
-    else if (key == key2) new Map3(key1, value1, key3, value3, key4, value4) 
-    else if (key == key3) new Map3(key1, value1, key2, value2, key4, value4) 
-    else if (key == key4) new Map3(key1, value1, key2, value2, key3, value3) 
-    else this
-}
-  
-
-
diff --git a/src/library/scala/collection/immutable/MapLike.scala b/src/library/scala/collection/immutable/MapLike.scala
new file mode 100644
index 0000000..76a14a2
--- /dev/null
+++ b/src/library/scala/collection/immutable/MapLike.scala
@@ -0,0 +1,127 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+package immutable
+
+import generic._
+
+/** 
+ *  A generic template for immutable maps from keys of type `A`
+ *  to values of type `B`.
+ *  To implement a concrete map, you need to provide implementations of the
+ *  following methods (where `This` is the type of the actual map implementation):
+ *  
+ *  {{{
+ *    def get(key: A): Option[B]
+ *    def iterator: Iterator[(A, B)]
+ *    def + [B1 >: B](kv: (A, B)): Map[A, B1]
+ *    def - (key: A): This
+ *  }}}
+ *  
+ *  If you wish that transformer methods like `take`, `drop`, `filter` return the 
+ *  same kind of map, you should also override:
+ *  
+ *  {{{
+ *    def empty: This
+ *  }}}
+ *  
+ *  It is also good idea to override methods `foreach` and
+ *  `size` for efficiency.
+ *  
+ *  @param A     the type of the keys contained in this collection.
+ *  @param B     the type of the values associated with the keys.
+ *  @param This  The type of the actual map implementation.
+ *  
+ *  @author  Martin Odersky
+ *  @version 2.8
+ *  @since   2.8
+ *  @define Coll immutable.Map
+ *  @define coll immutable map
+ */
+trait MapLike[A, +B, +This <: MapLike[A, B, This] with Map[A, B]]
+  extends scala.collection.MapLike[A, B, This]
+{ self =>
+
+  import scala.collection.Traversable
+
+  /** A new immutable map containing updating this map with a given key/value mapping. 
+   *  @param    key the key
+   *  @param    value the value
+   *  @return   A new map with the new key/value mapping 
+   */
+  override def updated [B1 >: B](key: A, value: B1): immutable.Map[A, B1] = this + ((key, value))
+
+  /** Add a key/value pair to this map, returning a new map. 
+   *  @param    kv the key/value pair.
+   *  @return   A new map with the new binding added to this map.
+   */
+  def + [B1 >: B] (kv: (A, B1)): immutable.Map[A, B1]
+
+  /** Adds two or more elements to this collection and returns
+   *  a new collection.
+   *
+   *  @param elem1 the first element to add.
+   *  @param elem2 the second element to add.
+   *  @param elems the remaining elements to add.
+   *  @return A new map with the new bindings added to this map.
+   */
+  override def + [B1 >: B] (elem1: (A, B1), elem2: (A, B1), elems: (A, B1) *): immutable.Map[A, B1] =
+    this + elem1 + elem2 ++ elems
+
+  /** Adds a number of elements provided by a traversable object
+   *  and returns a new collection with the added elements.
+   *
+   *  @param xs      the traversable object consisting of key-value pairs.
+   *  @return        a new immutable map with the bindings of this map and those from `xs`.
+   */
+  override def ++[B1 >: B](xs: TraversableOnce[(A, B1)]): immutable.Map[A, B1] = 
+    ((repr: immutable.Map[A, B1]) /: xs) (_ + _)
+
+  /** Filters this map by retaining only keys satisfying a predicate.
+   *  @param  p   the predicate used to test keys
+   *  @return an immutable map consisting only of those key value pairs of this map where the key satisfies
+   *          the predicate `p`. The resulting map wraps the original map without copying any elements.
+   */
+  override def filterKeys(p: A => Boolean): Map[A, B] = new DefaultMap[A, B] {
+    override def foreach[C](f: ((A, B)) => C): Unit = for (kv <- self) if (p(kv._1)) f(kv)
+    def iterator = self.iterator.filter(kv => p(kv._1))
+    override def contains(key: A) = self.contains(key) && p(key)
+    def get(key: A) = if (!p(key)) None else self.get(key)
+  }    
+
+  /** Transforms this map by applying a function to every retrieved value.
+   *  @param  f   the function used to transform values of this map.
+   *  @return a map view which maps every key of this map
+   *          to `f(this(key))`. The resulting map wraps the original map without copying any elements.
+   */
+  override def mapValues[C](f: B => C): Map[A, C] = new DefaultMap[A, C] {
+    override def foreach[D](g: ((A, C)) => D): Unit = for ((k, v) <- self) g((k, f(v)))
+    def iterator = for ((k, v) <- self.iterator) yield (k, f(v))
+    override def size = self.size
+    override def contains(key: A) = self.contains(key)
+    def get(key: A) = self.get(key).map(f)
+  }
+
+  /** This function transforms all the values of mappings contained
+   *  in this map with function `f`.
+   *
+   *  @param f A function over keys and values
+   *  @return  the updated map
+   */
+  def transform[C, That](f: (A, B) => C)(implicit bf: CanBuildFrom[This, (A, C), That]): That = {
+    val b = bf(repr)
+    for ((key, value) <- this) b += ((key, f(key, value)))
+    b.result
+  }
+
+  @deprecated("use `updated' instead")
+  def update[B1 >: B](key: A, value: B1): immutable.Map[A, B1] = updated(key, value).asInstanceOf[immutable.Map[A, B1]]
+}
diff --git a/src/library/scala/collection/immutable/MapProxy.scala b/src/library/scala/collection/immutable/MapProxy.scala
new file mode 100644
index 0000000..68b1a7d
--- /dev/null
+++ b/src/library/scala/collection/immutable/MapProxy.scala
@@ -0,0 +1,40 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+package immutable
+
+/** 
+ *  This is a simple wrapper class for <a href="Map.html"
+ *  target="contentFrame">`scala.collection.immutable.Map`</a>.
+ *  
+ *  It is most useful for assembling customized map abstractions
+ *  dynamically using object composition and forwarding.
+ *
+ *  @author  Matthias Zenger, Martin Odersky
+ *  @version 2.0, 31/12/2006
+ *  @since   2.8
+ */
+trait MapProxy[A, +B] extends Map[A, B] with MapProxyLike[A, B, Map[A, B]] {  
+  override def repr = this
+  private def newProxy[B1 >: B](newSelf: Map[A, B1]): MapProxy[A, B1] =
+    new MapProxy[A, B1] { val self = newSelf }
+
+  override def empty = newProxy(self.empty)
+  override def updated [B1 >: B](key: A, value: B1) = newProxy(self.updated(key, value))
+    
+  override def -(key: A) = newProxy(self - key)
+  override def + [B1 >: B](kv: (A, B1)): Map[A, B1] = newProxy(self + kv)
+  override def + [B1 >: B](elem1: (A, B1), elem2: (A, B1), elems: (A, B1) *) = newProxy(self.+(elem1, elem2, elems: _*))
+  override def ++[B1 >: B](xs: TraversableOnce[(A, B1)]) = newProxy(self ++ xs)
+
+  override def filterKeys(p: A => Boolean) = self.filterKeys(p)
+  override def mapValues[C](f: B => C) = self.mapValues(f)
+}
diff --git a/src/library/scala/collection/immutable/NumericRange.scala b/src/library/scala/collection/immutable/NumericRange.scala
new file mode 100644
index 0000000..a27b26a
--- /dev/null
+++ b/src/library/scala/collection/immutable/NumericRange.scala
@@ -0,0 +1,230 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2006-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+package scala.collection
+package immutable
+
+import mutable.{ Builder, ListBuffer }
+import generic._
+
+/** `NumericRange` is a more generic version of the
+ *  `Range` class which works with arbitrary types.
+ *  It must be supplied with an `Integral` implementation of the
+ *  range type.
+ *  
+ *  Factories for likely types include `Range.BigInt`, `Range.Long`,
+ *  and `Range.BigDecimal`.  `Range.Int` exists for completeness, but
+ *  the `Int`-based `scala.Range` should be more performant.
+ *  
+ *  {{{
+ *     val r1 = new Range(0, 100, 1)
+ *     val veryBig = Int.MaxValue.toLong + 1
+ *     val r2 = Range.Long(veryBig, veryBig + 100, 1)
+ *     assert(r1 sameElements r2.map(_ - veryBig))
+ *  }}}
+ *
+ *  @author  Paul Phillips
+ *  @version 2.8
+ *  @define Coll NumericRange
+ *  @define coll numeric range
+ *  @define mayNotTerminateInf
+ *  @define willNotTerminateInf
+ */
+ at serializable
+abstract class NumericRange[T]
+  (val start: T, val end: T, val step: T, val isInclusive: Boolean)
+  (implicit num: Integral[T])
+extends IndexedSeq[T]
+{
+  /** Note that NumericRange must be invariant so that constructs
+   *  such as
+   * 
+   *    1L to 10 by 5
+   *
+   *  do not infer the range type as AnyVal.
+   */
+  import num._
+  
+  private def fail(msg: String) = throw new IllegalArgumentException(msg)
+  
+  if (step equiv zero)
+    fail("NumericRange step cannot be zero.")
+      
+  // todo? - we could lift the length restriction by implementing a range as a sequence of
+  // subranges and limiting the subranges to MAX_INT.  There's no other way around it because
+  // the generics we inherit assume integer-based indexing (as well they should.)
+  // The second condition is making sure type T can meaningfully be compared to Int.MaxValue.
+  if (genericLength > fromInt(Int.MaxValue) && (Int.MaxValue == toInt(fromInt(Int.MaxValue))))
+    fail("Implementation restricts ranges to Int.MaxValue elements.")
+    
+  // inclusive/exclusiveness captured this way because we do not have any
+  // concept of a "unit", we can't just add an epsilon to an exclusive
+  // endpoint to make it inclusive (as can be done with the int-based Range.)
+  protected def limitTest(x: T) = !isEmpty && isInclusive && equiv(x, end)
+    
+  protected def underlying = collection.immutable.IndexedSeq.empty[T]
+  
+  /** Create a new range with the start and end values of this range and
+   *  a new `step`.
+   */
+  def by(newStep: T): NumericRange[T] = copy(start, end, newStep)
+  
+  /** Create a copy of this range.
+   */
+  def copy(start: T, end: T, step: T): NumericRange[T]
+  
+  override def foreach[U](f: T => U) {
+    var i = start
+    if (step > zero) {
+      while (i < end) {
+        f(i)
+        i += step
+      }
+    } else {
+      while (i > end) {
+        f(i)
+        i += step
+      }
+    }
+    if (limitTest(i)) f(i)
+  }
+  
+  def genericLength: T = {
+    def lim = if (limitTest(end)) one else zero
+    
+    if ((start < end && step < zero) || (start > end && step > zero)) zero
+    else if (equiv(start, end)) lim
+    else {
+      val (steps, left) = (end - start) /% step
+      val last = if (!equiv(left, zero) || isInclusive) one else zero
+      
+      steps + last
+    }
+  }
+  
+  def length: Int = toInt(genericLength)
+  override def isEmpty: Boolean =  
+    if (step > zero)
+      if (isInclusive) end < start
+      else end <= start
+    else
+      if (isInclusive) end > start
+      else end >= start
+
+  def apply(idx: Int): T = {
+    if (idx < 0 || idx >= length) throw new IndexOutOfBoundsException(idx.toString)
+    else start + (fromInt(idx) * step)
+  }
+
+  // a well-typed contains method.
+  def containsTyped(x: T): Boolean = {
+    def divides(d: T, by: T) = equiv(d % by, zero)
+
+    limitTest(x) || (
+      if (step > zero)
+        (start <= x) && (x < end) && divides(x - start, step)
+      else
+        (start >= x) && (x > end) && divides(start - x, step)
+    )
+  }
+  
+  // Motivated by the desire for Double ranges with BigDecimal precision,
+  // we need some way to map a Range and get another Range.  This can't be
+  // done in any fully general way because Ranges are not arbitrary
+  // sequences but step-valued, so we have a custom method only we can call
+  // which we promise to use responsibly.
+  // 
+  // The point of it all is that
+  //
+  //   0.0 to 1.0 by 0.1
+  //
+  // should result in
+  //
+  //   NumericRange[Double](0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0)
+  //
+  // and not 
+  // 
+  //   NumericRange[Double](0.0, 0.1, 0.2, 0.30000000000000004, 0.4, 0.5, 0.6000000000000001, 0.7000000000000001, 0.8, 0.9)
+  //
+  // or perhaps more importantly,
+  //
+  //   (0.1 to 0.3 by 0.1 contains 0.3) == true
+  //
+  private[immutable] def mapRange[A](fm: T => A)(implicit unum: Integral[A]): NumericRange[A] = {    
+    val self = this
+    
+    // XXX This may be incomplete.
+    new NumericRange[A](fm(start), fm(end), fm(step), isInclusive) {
+      def copy(start: A, end: A, step: A): NumericRange[A] =
+        if (isInclusive) NumericRange.inclusive(start, end, step)
+        else NumericRange(start, end, step)
+      
+      private val underlyingRange: NumericRange[T] = self
+      override def foreach[U](f: A => U) { underlyingRange foreach (x => f(fm(x))) }
+      override def isEmpty = underlyingRange.isEmpty
+      override def apply(idx: Int): A = fm(underlyingRange(idx))
+      override def containsTyped(el: A) = underlyingRange exists (x => fm(x) == el)
+    }
+  }
+
+  // The contains situation makes for some interesting code.
+  // I am not aware of any way to avoid a cast somewhere, because 
+  // contains must take an Any.
+  override def contains(x: Any): Boolean =    
+    try {
+      // if we don't verify that x == typedX, then a range
+      // of e.g. Longs will appear to contain an Int because
+      // the cast will perform the conversion.  (As of this writing
+      // it is anticipated that in scala 2.8, 5L != 5 although
+      // this is not yet implemented.)
+      val typedX = x.asInstanceOf[T]
+      containsTyped(typedX) && (x == typedX)
+    }
+    catch { case _: ClassCastException => super.contains(x) }
+
+  override lazy val hashCode = super.hashCode()
+  override def equals(other: Any) = other match {
+    case x: NumericRange[_] => (length == x.length) && (length match {
+      case 0  => true
+      case 1  => x.start == start
+      case n  => x.start == start && x.step == step
+    })
+    case _  => super.equals(other)
+  }
+  override def toString() = {
+    val endStr = if (length > Range.MAX_PRINT) ", ... )" else ")"
+    take(Range.MAX_PRINT).mkString("NumericRange(", ", ", endStr)
+  }
+}
+
+/** A companion object for numeric ranges.
+ */
+object NumericRange {  
+  class Inclusive[T](start: T, end: T, step: T)(implicit num: Integral[T])
+  extends NumericRange(start, end, step, true) {
+    def copy(start: T, end: T, step: T): Inclusive[T] =
+      NumericRange.inclusive(start, end, step)
+      
+    def exclusive: Exclusive[T] = NumericRange(start, end, step)
+  }
+  
+  class Exclusive[T](start: T, end: T, step: T)(implicit num: Integral[T])
+  extends NumericRange(start, end, step, false) {
+    def copy(start: T, end: T, step: T): Exclusive[T] =
+      NumericRange(start, end, step)
+    
+    def inclusive: Inclusive[T] = NumericRange.inclusive(start, end, step)
+  }
+  
+  def apply[T](start: T, end: T, step: T)(implicit num: Integral[T]): Exclusive[T] =
+    new Exclusive(start, end, step)
+  def inclusive[T](start: T, end: T, step: T)(implicit num: Integral[T]): Inclusive[T] = 
+    new Inclusive(start, end, step)
+}
+
diff --git a/src/library/scala/collection/immutable/PagedSeq.scala b/src/library/scala/collection/immutable/PagedSeq.scala
index caf538a..c742071 100644
--- a/src/library/scala/collection/immutable/PagedSeq.scala
+++ b/src/library/scala/collection/immutable/PagedSeq.scala
@@ -1,28 +1,29 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2006-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: PagedSeq.scala 14497 2008-04-04 12:09:06Z washburn $
 
 
-package scala.collection.immutable
+package scala.collection
+package immutable
 
 import java.io._
-import util.matching.Regex
+import scala.util.matching.Regex
 
-
-/** The PagedSeq object defines a lazy implementations of 
+/** The `PagedSeq` object defines a lazy implementations of 
  *  a random access sequence. 
+ *  
+ *  @since 2.7
  */  
 object PagedSeq {
-  final val UndeterminedEnd = Math.MAX_INT
+  final val UndeterminedEnd = Int.MaxValue
 
   /** Constructs a character sequence from a character iterator */
-  def fromIterator[T](source: Iterator[T]): PagedSeq[T] = 
+  def fromIterator[T: ClassManifest](source: Iterator[T]): PagedSeq[T] = 
     new PagedSeq[T]((data: Array[T], start: Int, len: Int) => {
       var i = 0
       while (i < len && source.hasNext) {
@@ -33,8 +34,8 @@ object PagedSeq {
     })
 
   /** Constructs a character sequence from a character iterable */
-  def fromIterable[T](source: Iterable[T]): PagedSeq[T] = 
-    fromIterator(source.elements)
+  def fromIterable[T: ClassManifest](source: Iterable[T]): PagedSeq[T] = 
+    fromIterator(source.iterator)
 
   /** Constructs a character sequence from a string iterator */
   def fromStrings(source: Iterator[String]): PagedSeq[Char] = {
@@ -55,7 +56,7 @@ object PagedSeq {
 
   /** Constructs a character sequence from a string iterable */
   def fromStrings(source: Iterable[String]): PagedSeq[Char] = 
-    fromStrings(source.elements)
+    fromStrings(source.iterator)
 
   /** Constructs a character sequence from a line iterator
    *  Lines do not contain trailing `\n' characters; The method inserts
@@ -77,7 +78,7 @@ object PagedSeq {
    *  a line separator `\n' between any two lines in the sequence.
    */
   def fromLines(source: Iterable[String]): PagedSeq[Char] =
-    fromLines(source.elements)
+    fromLines(source.iterator)
 
   /** Constructs a character sequence from an input reader
    */
@@ -97,7 +98,7 @@ object PagedSeq {
   /** Constructs a character sequence from a scala.io.Source value
    */
   def fromSource(source: io.Source) = 
-    fromLines(source.getLines)
+    fromLines(source.getLines())
 }
 
 
@@ -105,12 +106,23 @@ import PagedSeq._
 
 /** An implementation of lazily computed sequences, where elements are stored
  *  in ``pages'', i.e. arrays of fixed size.
- *
- * @author Martin Odersky 
+ *  
+ *  @tparam T     the type of the elements contained in this paged sequence, with a `ClassManifest` context bound.
+ *  
+ *  @author Martin Odersky 
+ *  @since  2.7
+ *  @define Coll PagedSeq
+ *  @define coll paged sequence
+ *  @define mayNotTerminateInf
+ *  @define willNotTerminateInf
  */
-class PagedSeq[T] protected (more: (Array[T], Int, Int) => Int, 
-                             first: Page[T], start: Int, end: Int) extends RandomAccessSeq[T] {
-
+class PagedSeq[T: ClassManifest] protected(
+  more: (Array[T], Int, Int) => Int, 
+  first1: Page[T],
+  start: Int,
+  end: Int)
+extends scala.collection.IndexedSeq[T]
+{
   /**  A paged sequence is constructed from a method that produces more characters when asked.
    *  The producer method is analogous to the read method in java.io.Reader.
    *  It takes three parameters: an array of characters, a start index, and an end index.
@@ -120,15 +132,15 @@ class PagedSeq[T] protected (more: (Array[T], Int, Int) => Int,
    */  
   def this(more: (Array[T], Int, Int) => Int) = this(more, new Page[T](0), 0, UndeterminedEnd)
   
-  private var current: Page[T] = first
+  private var current: Page[T] = first1
 
-  private def latest = first.latest
+  private def latest = first1.latest
 
   private def addMore() = latest.addMore(more)
 
   private def page(absindex: Int) = {
     if (absindex < current.start) 
-      current = first
+      current = first1
     while (absindex >= current.end && current.next != null)
       current = current.next
     while (absindex >= current.end && !current.isLast) {
@@ -163,11 +175,11 @@ class PagedSeq[T] protected (more: (Array[T], Int, Int) => Int,
   /** the subsequence from index `start' up to and excluding 
    *  the minimum of index `end' and the length of the current sequence.
    */
-  override def slice(_start: Int, _end: Int) = {
+  override def slice(_start: Int, _end: Int): PagedSeq[T] = {
     page(start)
     val s = start + _start
     val e = if (_end == UndeterminedEnd) _end else start + _end
-    var f = first
+    var f = first1
     while (f.end <= s && !f.isLast) f = f.next
     new PagedSeq(more, f, s, e)
   }
@@ -175,12 +187,12 @@ class PagedSeq[T] protected (more: (Array[T], Int, Int) => Int,
   /** the subsequence from index `start' up to the  
    *  length of the current sequence.
    */
-  override def slice(start: Int) = slice(start, UndeterminedEnd)
+  def slice(start: Int): PagedSeq[T] = slice(start, UndeterminedEnd)
 
   /** Convert sequence to string */
   override def toString = {
     val buf = new StringBuilder
-    for (ch <- elements) buf append ch
+    for (ch <- PagedSeq.this.iterator) buf append ch
     buf.toString
   }
 }
@@ -188,14 +200,14 @@ class PagedSeq[T] protected (more: (Array[T], Int, Int) => Int,
 
 /** Page containing up to PageSize characters of the input sequence. 
  */
-private class Page[T](val num: Int) {
+private class Page[T: ClassManifest](val num: Int) {
 
   private final val PageSize = 4096
 
   /** The next page in the sequence */
   var next  : Page[T] = null
 
-  /** A later page in the sequence, serves a cachae for pointing to last page */
+  /** A later page in the sequence, serves a cache for pointing to last page */
   var later : Page[T] = this
 
   /** The number of characters read into this page */
@@ -211,11 +223,11 @@ private class Page[T](val num: Int) {
   /** The index of the first character in this page relative to the whole sequence */ 
   final def start = num * PageSize
 
-  /** The index of the character following the last charcater in this page relative 
+  /** The index of the character following the last character in this page relative 
    *  to the whole sequence */ 
   final def end = start + filled
 
-  /** The currently last page in the sequence; might change as more charcaters are appended */
+  /** The currently last page in the sequence; might change as more characters are appended */
   final def latest: Page[T] = {
     if (later.next != null) later = later.next.latest
     later
diff --git a/src/library/scala/collection/immutable/Queue.scala b/src/library/scala/collection/immutable/Queue.scala
index 547f049..501cc9c 100644
--- a/src/library/scala/collection/immutable/Queue.scala
+++ b/src/library/scala/collection/immutable/Queue.scala
@@ -1,49 +1,48 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Queue.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.collection.immutable
+package scala.collection
+package immutable
 
+import generic._
+import mutable.{ Builder, ListBuffer }
+import annotation.tailrec
 
-//import Predef.NoSuchElementException
-
-object Queue {
-  val Empty: Queue[Nothing] = new Queue()
-}
-
-/** <code>Queue</code> objects implement data structures that allow to
+/** `Queue` objects implement data structures that allow to
  *  insert and retrieve elements in a first-in-first-out (FIFO) manner.
- *
+ *  
  *  @author  Erik Stenman
  *  @version 1.0, 08/07/2003
+ *  @since   1
+ *  @define Coll immutable.Queue
+ *  @define coll immutable queue
+ *  @define mayNotTerminateInf
+ *  @define willNotTerminateInf
  */
 @serializable
-class Queue[+A](elem: A*) extends Seq[A] {
-
-  protected val in: List[A] = Nil
-  protected val out: List[A] = elem.elements.toList
-
-  protected def mkQueue[A](i: List[A], o: List[A]): Queue[A] =
-    new Queue[A]() {
-      override protected val in = i
-      override protected val out = o
-    }
-
-  /** Returns the <code>n</code>-th element of this queue. 
+ at SerialVersionUID(-7622936493364270175L)
+class Queue[+A] protected(protected val in: List[A], protected val out: List[A])
+            extends LinearSeq[A]
+            with GenericTraversableTemplate[A, Queue]
+            with LinearSeqLike[A, Queue[A]] {
+
+  override def companion: GenericCompanion[Queue] = Queue  
+  
+  /** Returns the `n`-th element of this queue. 
    *  The first element is at position 0.
    *
    *  @param  n index of the element to return
-   *  @return   the element at position <code>n</code> in this queue.
+   *  @return   the element at position `n` in this queue.
    *  @throws Predef.NoSuchElementException if the queue is too short.
    */
-  def apply(n: Int): A = {
+  override def apply(n: Int): A = {
     val len = out.length
     if (n < len) out.apply(n)
     else {
@@ -55,7 +54,7 @@ class Queue[+A](elem: A*) extends Seq[A] {
 
   /** Returns the elements in the list as an iterator
    */
-  override def elements: Iterator[A] = (out ::: in.reverse).elements
+  override def iterator: Iterator[A] = (out ::: in.reverse).iterator
 
   /** Checks if the queue is empty.
    *
@@ -63,25 +62,34 @@ class Queue[+A](elem: A*) extends Seq[A] {
    */
   override def isEmpty: Boolean = in.isEmpty && out.isEmpty
 
+  override def head: A =
+    if (out.nonEmpty) out.head 
+    else if (in.nonEmpty) in.last
+    else throw new NoSuchElementException("head on empty queue")
+    
+  override def tail: Queue[A] =
+    if (out.nonEmpty) new Queue(in, out.tail)
+    else if (in.nonEmpty) new Queue(Nil, in.reverse.tail)
+    else throw new NoSuchElementException("tail on empty queue")
+
   /** Returns the length of the queue.
    */
-  def length = in.length + out.length
+  override def length = in.length + out.length
 
   /** Creates a new queue with element added at the end 
    *  of the old queue.
    *
-   *  @deprecated Use the method <code>enqueue</code> from now on.
-   *
    *  @param  elem        the element to insert
    */
-  @deprecated def +[B >: A](elem: B) = mkQueue(elem :: in, out)
+  @deprecated("Use the method <code>enqueue</code> from now on.")
+  def +[B >: A](elem: B) = enqueue(elem)
 
   /** Creates a new queue with element added at the end 
    *  of the old queue.
    *
    *  @param  elem        the element to insert
    */
-  def enqueue[B >: A](elem: B) = mkQueue(elem :: in, out)
+  def enqueue[B >: A](elem: B) = new Queue(elem :: in, out)
 
   /** Returns a new queue with all all elements provided by 
    *  an <code>Iterable</code> object added at the end of 
@@ -89,17 +97,12 @@ class Queue[+A](elem: A*) extends Seq[A] {
    *  The elements are prepended in the order they
    *  are given out by the iterator.
    *
-   *  @deprecated Use the method <code>enqueue</code> from now on.
-   *
    *  @param  iter        an iterable object
    */
-  @deprecated def +[B >: A](iter: Iterable[B]) = {
-    var q: List[B] = in
-    iter.elements.foreach(e => q = e :: q)
-    mkQueue(q, out)
-  }
+  @deprecated("Use the method <code>enqueue</code> from now on.")
+  def +[B >: A](iter: Iterable[B]) = enqueue(iter)
 
-  /** Returns a new queue with all all elements provided by 
+  /** Returns a new queue with all elements provided by 
    *  an <code>Iterable</code> object added at the end of 
    *  the queue. 
    *  The elements are prepended in the order they
@@ -107,11 +110,8 @@ class Queue[+A](elem: A*) extends Seq[A] {
    *
    *  @param  iter        an iterable object
    */
-  def enqueue[B >: A](iter: Iterable[B]) = {
-    var q: List[B] = in
-    iter.elements.foreach(e => q = e :: q)
-    mkQueue(q, out)
-  }
+  def enqueue[B >: A](iter: Iterable[B]) =
+    new Queue(iter.toList.reverse ::: in, out)
 
   /** Returns a tuple with the first element in the queue,
    *  and a new queue with this element removed.
@@ -119,12 +119,10 @@ class Queue[+A](elem: A*) extends Seq[A] {
    *  @throws Predef.NoSuchElementException
    *  @return the first element of the queue.
    */
-  def dequeue: (A, Queue[A]) = {
-    val (newOut, newIn) =
-      if (out.isEmpty) (in.reverse, Nil)
-      else (out, in)
-    if (newOut.isEmpty) throw new NoSuchElementException("queue empty")
-    else (newOut.head, mkQueue(newIn, newOut.tail))
+  def dequeue: (A, Queue[A]) = out match {
+    case Nil if !in.isEmpty => val rev = in.reverse ; (rev.head, new Queue(Nil, rev.tail))
+    case x :: xs            => (x, new Queue(in, xs))
+    case _                  => throw new NoSuchElementException("dequeue on empty queue")
   }
 
   /** Returns the first element in the queue, or throws an error if there
@@ -133,48 +131,24 @@ class Queue[+A](elem: A*) extends Seq[A] {
    *  @throws Predef.NoSuchElementException
    *  @return the first element.
    */
-  def front: A =
-    if (out.isEmpty) {
-      if (in.isEmpty) throw new NoSuchElementException("queue empty") else in.last
-    } else
-      out.head
+  def front: A = head
 
   /** Returns a string representation of this queue. 
    */
   override def toString() = mkString("Queue(", ", ", ")")
+}
 
-  /** Compares two queues for equality by comparing 
-   *  each element in the queues.
-   *
-   *  @return true, iff the two queues are structurally equal.
-   */
-  override def equals(o: Any): Boolean = o match {
-    case q: Queue[_] =>
-      /* A function that compares the element at 
-         position index in q with the element at 
-         the same position in this (queue).
-         If they are equal the next element is
-         compared. */
-      def eqe(index: Int): Boolean = (
-        /* If all elements are compared 
-        the queues are equal. */
-        index >= this.length ||
-        /* Otherwise: compare the elements */
-        (q.apply(index) == this.apply(index) && 
-         /* if they are equal compare the rest. */
-         eqe(index + 1))
-      );
-        /* If the length of the ques are the same,
-         compare each element, starting at index 0. */
-      (q.length == this.length) && eqe(0);
-    
-    case _ => false /* o is not a queue: not equal to this. */
-  }
-
-  override def hashCode(): Int =
-    if (isEmpty) 0
-    else {
-      val q: (A,Queue[A]) = dequeue;
-      q._1.hashCode() + q._2.hashCode()
-    }
+/** $factoryInfo
+ *  @define Coll immutable.Queue
+ *  @define coll immutable queue
+ */
+object Queue extends SeqFactory[Queue] {
+  /** $genericCanBuildFromInfo */
+  implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, Queue[A]] = new GenericCanBuildFrom[A]
+  def newBuilder[A]: Builder[A, Queue[A]] = new ListBuffer[A] mapResult (x => new Queue[A](Nil, x.toList))
+  override def empty[A]: Queue[A] = new Queue[A](Nil, Nil)
+  override def apply[A](xs: A*): Queue[A] = new Queue[A](Nil, xs.toList)
+  
+  @deprecated("Use Queue.empty instead")
+  val Empty: Queue[Nothing] = Queue()
 }
diff --git a/src/library/scala/collection/immutable/Range.scala b/src/library/scala/collection/immutable/Range.scala
new file mode 100644
index 0000000..fbc6a28
--- /dev/null
+++ b/src/library/scala/collection/immutable/Range.scala
@@ -0,0 +1,347 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2006-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+package scala.collection.immutable
+
+/** The `Range` class represents integer values in range
+ *  ''[start;end)'' with non-zero step value `step`.
+ *  It's a special case of an indexed sequence.
+ *  For example:
+ *  
+ *  {{{
+ *     val r1 = 0 until 10
+ *     val r2 = r1.start until r1.end by r1.step + 1
+ *     println(r2.length) // = 5
+ *  }}}
+ *  
+ *  @param start      the start of this range.
+ *  @param end        the exclusive end of the range.
+ *  @param step       the step for the range.
+ *  
+ *  @author Martin Odersky
+ *  @version 2.8
+ *  @since   2.5
+ *  @define Coll Range
+ *  @define coll range
+ *  @define mayNotTerminateInf
+ *  @define willNotTerminateInf
+ *  @define doesNotUseBuilders
+ *    '''Note:''' this method does not use builders to construct a new range,
+ *         and its complexity is O(1).
+ */
+ at serializable @SerialVersionUID(7618862778670199309L)
+class Range(val start: Int, val end: Int, val step: Int) extends IndexedSeq[Int] {
+  
+  require(step != 0)
+
+  protected def copy(start: Int, end: Int, step: Int): Range = new Range(start, end, step)
+
+  /** Create a new range with the `start` and `end` values of this range and
+   *  a new `step`.
+   *  
+   *  @return a new range with a different step
+   */
+  def by(step: Int): Range = copy(start, end, step)
+
+  def isInclusive = false
+
+  override def foreach[@specialized(Unit) U](f: Int => U) {
+    if (fullLength > 0) {
+      val last = this.last
+      var i = start
+      while (i != last) {
+        f(i)
+        i += step
+      }
+      f(i)
+    }
+  }
+
+  override def last: Int = if (step == 1 || step == -1) {
+    end - step
+  } else {
+    val size = end.toLong - start.toLong
+    val inclusiveLast = (size / step.toLong * step.toLong + start.toLong).toInt
+    if (size % step == 0) inclusiveLast - step else inclusiveLast
+  }
+  
+  def length: Int = fullLength.toInt
+  
+  protected def fullLength: Long = if (end > start == step > 0 && start != end)
+    ((last.toLong - start.toLong) / step.toLong + 1)
+  else
+    0
+  
+  final override def isEmpty = length == 0 
+
+  @inline
+  final def apply(idx: Int): Int = {
+    if (idx < 0 || idx >= length) throw new IndexOutOfBoundsException(idx.toString)
+    start + idx * step
+  }
+
+  // take and drop have to be tolerant of large values without overflowing
+  // warning! this is buggy, and gives wrong answers on boundary cases.
+  // The known bugs are avoided by drop not calling it in those cases.
+  // See ticket #3529.  It should be revised.
+  private def locationAfterN(n: Int) = if (n > 0) {
+    if (step > 0)
+      ((start.toLong + step.toLong * n.toLong) min last.toLong).toInt
+    else
+      ((start.toLong + step.toLong * n.toLong) max last.toLong).toInt
+  } else {
+    start
+  }
+
+  /** Creates a new range containing the first `n` elements of this range.
+   *  
+   *  $doesNotUseBuilders
+   *  
+   *  @param n  the number of elements to take.
+   *  @return   a new range consisting of `n` first elements.
+   */
+  final override def take(n: Int): Range =
+    if (n > 0 && length > 0)
+      Range(start, locationAfterN(n - 1), step).inclusive
+    else
+      Range(start, start, step)
+  
+  /** Creates a new range containing all the elements of this range except the first `n` elements.
+   *  
+   *  $doesNotUseBuilders
+   *  
+   *  @param n  the number of elements to drop.
+   *  @return   a new range consisting of all the elements of this range except `n` first elements.
+   */
+  final override def drop(n: Int): Range =
+    if (n >= length) {
+      if (step > 0) copy(end + 1, end, step)
+      else copy(end - 1, end, step)
+    }
+    else copy(locationAfterN(n), end, step)
+  
+  /** Creates a new range containing all the elements of this range except the last one.
+   *  
+   *  $doesNotUseBuilders
+   *  
+   *  @return  a new range consisting of all the elements of this range except the last one.
+   */
+  final override def init: Range = 
+    take(length - 1)
+
+  /** Creates a new range contained in the specified slice of this range.
+   *  
+   *  $doesNotUseBuilders
+   *  
+   *  @param from   the start of the slice.
+   *  @param until  the end of the slice.
+   *  @return       a new range consisting of all the elements of this range contained in the specified slice.
+   */
+  final override def slice(from: Int, until: Int): Range = 
+    drop(from).take(until - from)
+
+  private def skip(p: Int => Boolean): Int = {
+    var s = start
+    if (length > 0) {
+      val last = this.last
+      while ((if (step > 0) s <= last else s >= last) && p(s)) 
+        s += step
+    }
+    s
+  }
+  
+  final override def takeWhile(p: Int => Boolean): Range = Range(start, skip(p), step)
+  final override def dropWhile(p: Int => Boolean): Range = copy(skip(p), end, step)
+  
+  final override def span(p: Int => Boolean): (Range, Range) = {
+    val split = skip(p)
+    (Range(start, split, step), copy(split, end, step))
+  }
+  
+  /** Creates a pair of new ranges, first consisting of elements before `n`, and the second
+   *  of elements after `n`.
+   *  
+   *  $doesNotUseBuilders
+   */
+  final override def splitAt(n: Int) = (take(n), drop(n))
+  
+  /** Creates a new range consisting of the `length - n` last elements of the range.
+   *  
+   *  $doesNotUseBuilders
+   */
+  final override def takeRight(n: Int): Range = drop(length - n)
+  
+  /** Creates a new range consisting of the initial `length - n` elements of the range.
+   *  
+   *  $doesNotUseBuilders
+   */
+  final override def dropRight(n: Int): Range = take(length - n)
+  
+  /** Returns the reverse of this range.
+   *  
+   *  $doesNotUseBuilders
+   */
+  final override def reverse: Range = if (length > 0) new Range.Inclusive(last, start, -step) else this
+
+  /** Make range inclusive.
+   */
+  def inclusive = new Range.Inclusive(start, end, step)
+
+  final def contains(x: Int): Boolean = if (length > 0) { 
+    if (step > 0) start <= x && x <= last && (x - start) % step == 0
+    else start >= x && x >= last && (start - x) % step == 0
+  } else {
+    false
+  }
+
+  override def equals(other: Any) = other match {
+    case x: Range => 
+      length == x.length && 
+      (length == 0 || 
+       start == x.start && 
+       (length == 1 || step == x.step))
+    case _ => 
+      super.equals(other)
+  }
+
+  /* eliminated, so as to not break the hashcode/equals contract 
+  override def hashCode = start + limit + step
+  */
+
+  override def toString() = {
+    val endStr = if (length > Range.MAX_PRINT) ", ... )" else ")"
+    take(Range.MAX_PRINT).mkString("Range(", ", ", endStr)
+  }
+}
+
+/** A companion object for the `Range` class.
+ */
+object Range {
+  private[immutable] val MAX_PRINT = 512  // some arbitrary value
+  
+  /** Calculates the number of elements in a range given start, end, step, and
+   *  whether or not it is inclusive.  Returns -1 if parameters are invalid.
+   */
+  def count(start: Int, end: Int, step: Int): Int = count(start, end, step, false)
+  def count(start: Int, end: Int, step: Int, isInclusive: Boolean): Int = {
+    def last =
+      if (isInclusive && step < 0) end - 1
+      else if (isInclusive && step > 0) end + 1
+      else end
+    
+    if (step == 0) -1
+    else if (start == end) { if (isInclusive) 1 else 0 }
+    else if (end > start != step > 0) -1
+    else if (step == 1 || step == -1) last - start
+    else ((last - start - 1) / step) + 1
+  }
+
+  class Inclusive(start: Int, end: Int, step: Int) extends Range(start, end, step) {
+    override def isInclusive = true
+    override protected def copy(start: Int, end: Int, step: Int): Range = new Inclusive(start, end, step)
+    override def last: Int = if (step == 1 || step == -1) 
+      end 
+    else 
+      ((end.toLong - start.toLong) / step.toLong * step.toLong + start.toLong).toInt
+    protected override def fullLength: Long = if (end > start == step > 0 || start == end)
+      ((last.toLong - start.toLong) / step.toLong + 1)
+    else
+      0
+  }
+
+  /** Make a range from `start` until `end` (exclusive) with given step value.
+   * @note step != 0
+   */
+  def apply(start: Int, end: Int, step: Int): Range = new Range(start, end, step)
+
+  /** Make an range from `start` to `end` inclusive with step value 1.
+   */
+  def apply(start: Int, end: Int): Range with ByOne = new Range(start, end, 1) with ByOne
+
+  /** Make an inclusive range from start to end with given step value.
+   * @note step != 0
+   */
+  def inclusive(start: Int, end: Int, step: Int): Range.Inclusive = new Inclusive(start, end, step)
+
+  /** Make an inclusive range from start to end with step value 1.
+   */
+  def inclusive(start: Int, end: Int): Range.Inclusive with ByOne = new Inclusive(start, end, 1) with ByOne
+
+  trait ByOne extends Range {
+    override final def foreach[@specialized(Unit) U](f: Int => U) {
+      if (length > 0) {
+        val last = this.last
+        var i = start
+        while (i != last) {
+          f(i)
+          i += 1
+        }
+        f(i)
+      }
+    }
+  }
+
+  // BigInt and Long are straightforward generic ranges.
+  object BigInt {
+    def apply(start: BigInt, end: BigInt, step: BigInt) = NumericRange(start, end, step)
+    def inclusive(start: BigInt, end: BigInt, step: BigInt) = NumericRange.inclusive(start, end, step)
+  }
+
+  object Long {
+    def apply(start: Long, end: Long, step: Long) = NumericRange(start, end, step)
+    def inclusive(start: Long, end: Long, step: Long) = NumericRange.inclusive(start, end, step)
+  }
+  
+  // BigDecimal uses an alternative implementation of Numeric in which
+  // it pretends to be Integral[T] instead of Fractional[T].  See Numeric for
+  // details.  The intention is for it to throw an exception anytime
+  // imprecision or surprises might result from anything, although this may
+  // not yet be fully implemented.
+  object BigDecimal {
+    implicit val bigDecAsIntegral = scala.Numeric.BigDecimalAsIfIntegral
+    
+    def apply(start: BigDecimal, end: BigDecimal, step: BigDecimal) =
+      NumericRange(start, end, step)
+    def inclusive(start: BigDecimal, end: BigDecimal, step: BigDecimal) = 
+      NumericRange.inclusive(start, end, step)
+  }
+
+  // Double works by using a BigDecimal under the hood for precise
+  // stepping, but mapping the sequence values back to doubles with
+  // .doubleValue.  This constructs the BigDecimals by way of the
+  // String constructor (valueOf) instead of the Double one, which
+  // is necessary to keep 0.3d at 0.3 as opposed to
+  // 0.299999999999999988897769753748434595763683319091796875 or so.
+  object Double {
+    implicit val bigDecAsIntegral = scala.Numeric.BigDecimalAsIfIntegral
+    implicit val doubleAsIntegral = scala.Numeric.DoubleAsIfIntegral
+    def toBD(x: Double): BigDecimal = scala.BigDecimal valueOf x
+    
+    def apply(start: Double, end: Double, step: Double) =
+      BigDecimal(toBD(start), toBD(end), toBD(step)) mapRange (_.doubleValue)
+    
+    def inclusive(start: Double, end: Double, step: Double) =
+      BigDecimal.inclusive(toBD(start), toBD(end), toBD(step)) mapRange (_.doubleValue)
+  }
+  
+  // As there is no appealing default step size for not-really-integral ranges,
+  // we offer a partially constructed object.
+  class Partial[T, U](f: T => U) {
+    def by(x: T): U = f(x)
+  }
+  
+  // Illustrating genericity with Int Range, which should have the same behavior
+  // as the original Range class.  However we leave the original Range
+  // indefinitely, for performance and because the compiler seems to bootstrap
+  // off it and won't do so with our parameterized version without modifications.
+  object Int {
+    def apply(start: Int, end: Int, step: Int) = NumericRange(start, end, step)
+    def inclusive(start: Int, end: Int, step: Int) = NumericRange.inclusive(start, end, step)
+  }
+}
diff --git a/src/library/scala/collection/immutable/RedBlack.scala b/src/library/scala/collection/immutable/RedBlack.scala
index b350f02..4439da8 100644
--- a/src/library/scala/collection/immutable/RedBlack.scala
+++ b/src/library/scala/collection/immutable/RedBlack.scala
@@ -1,15 +1,21 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2005-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2005-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: RedBlack.scala 16894 2009-01-13 13:09:41Z cunei $
-package scala.collection.immutable
 
- at serializable
+
+package scala.collection
+package immutable
+
+/** A base class containing the implementations for `TreeMaps` and `TreeSets`.
+ *  
+ *  @since 2.3
+ */
+ at serializable @SerialVersionUID(8691885935445612921L)
 abstract class RedBlack[A] {
 
   def isSmaller(x: A, y: A): Boolean
@@ -27,15 +33,17 @@ abstract class RedBlack[A] {
     def isBlack: Boolean
     def lookup(x: A): Tree[B]
     def update[B1 >: B](k: A, v: B1): Tree[B1] = blacken(upd(k, v))
-    def delete(k: A): Tree[B] = del(k)
-
-    def visit[T](input : T)(f : (T,A,B) => Tuple2[Boolean,T]) : Tuple2[Boolean,T];
-    def elements : ImmutableIterator[Pair[A,B]];
-    def elementsSlow: Iterator[Pair[A, B]];
+    def delete(k: A): Tree[B] = blacken(del(k))
+    def foreach[U](f: (A, B) =>  U)
+    @deprecated("use `foreach' instead")
+    def visit[T](input: T)(f: (T, A, B) => (Boolean, T)): (Boolean, T)
+    def toStream: Stream[(A,B)]
+    def iterator: Iterator[(A, B)]
+    @deprecated("use `iterator' instead") def elements = iterator
     def upd[B1 >: B](k: A, v: B1): Tree[B1]
     def del(k: A): Tree[B]
     def smallest: NonEmpty[B]
-    def range(from : Option[A], until : Option[A]) : Tree[B]
+    def range(from: Option[A], until: Option[A]): Tree[B]
     def first : A
     def last : A
     def count : Int
@@ -72,31 +80,100 @@ abstract class RedBlack[A] {
       else if (isSmaller(key, k)) balanceRight(isBlack, key, value, left, right.upd(k, v))
       else mkTree(isBlack, k, v, left, right)
     }
+    // Based on Stefan Kahrs' Haskell version of Okasaki's Red&Black Trees
+    // http://www.cse.unsw.edu.au/~dons/data/RedBlackTree.html
     def del(k: A): Tree[B] = {
-      if (isSmaller(k, key)) mkTree(isBlack, key, value, left.del(k), right)
-      else if (isSmaller(key, k)) mkTree(isBlack, key, value, left, right.del(k))
-      else if (left.isEmpty) right
-      else if (right.isEmpty) left
-      else {
-        val s = right.smallest
-        mkTree(isBlack, s.key, s.value, left, right.del(s.key))
+      def balance(x: A, xv: B, tl: Tree[B], tr: Tree[B]) = (tl, tr) match {
+        case (RedTree(y, yv, a, b), RedTree(z, zv, c, d)) =>
+          RedTree(x, xv, BlackTree(y, yv, a, b), BlackTree(z, zv, c, d))
+        case (RedTree(y, yv, RedTree(z, zv, a, b), c), d) =>
+          RedTree(y, yv, BlackTree(z, zv, a, b), BlackTree(x, xv, c, d))
+        case (RedTree(y, yv, a, RedTree(z, zv, b, c)), d) =>
+          RedTree(z, zv, BlackTree(y, yv, a, b), BlackTree(x, xv, c, d))
+        case (a, RedTree(y, yv, b, RedTree(z, zv, c, d))) =>
+          RedTree(y, yv, BlackTree(x, xv, a, b), BlackTree(z, zv, c, d))
+        case (a, RedTree(y, yv, RedTree(z, zv, b, c), d)) =>
+          RedTree(z, zv, BlackTree(x, xv, a, b), BlackTree(y, yv, c, d))
+        case (a, b) => 
+          BlackTree(x, xv, a, b)
+      }
+      def subl(t: Tree[B]) = t match {
+        case BlackTree(x, xv, a, b) => RedTree(x, xv, a, b)
+        case _ => error("Defect: invariance violation; expected black, got "+t)
+      }
+      def balLeft(x: A, xv: B, tl: Tree[B], tr: Tree[B]) = (tl, tr) match {
+        case (RedTree(y, yv, a, b), c) => 
+          RedTree(x, xv, BlackTree(y, yv, a, b), c)
+        case (bl, BlackTree(y, yv, a, b)) => 
+          balance(x, xv, bl, RedTree(y, yv, a, b))
+        case (bl, RedTree(y, yv, BlackTree(z, zv, a, b), c)) => 
+          RedTree(z, zv, BlackTree(x, xv, bl, a), balance(y, yv, b, subl(c)))
+        case _ => error("Defect: invariance violation at "+right)
+      }
+      def balRight(x: A, xv: B, tl: Tree[B], tr: Tree[B]) = (tl, tr) match {
+        case (a, RedTree(y, yv, b, c)) =>
+          RedTree(x, xv, a, BlackTree(y, yv, b, c))
+        case (BlackTree(y, yv, a, b), bl) =>
+          balance(x, xv, RedTree(y, yv, a, b), bl)
+        case (RedTree(y, yv, a, BlackTree(z, zv, b, c)), bl) =>
+          RedTree(z, zv, balance(y, yv, subl(a), b), BlackTree(x, xv, c, bl))
+        case _ => error("Defect: invariance violation at "+left)
+      }
+      def delLeft = left match {
+        case _: BlackTree[_] => balLeft(key, value, left.del(k), right)
+        case _ => RedTree(key, value, left.del(k), right)
+      }
+      def delRight = right match {
+        case _: BlackTree[_] => balRight(key, value, left, right.del(k))
+        case _ => RedTree(key, value, left, right.del(k))
+      }
+      def append(tl: Tree[B], tr: Tree[B]): Tree[B] = (tl, tr) match {
+        case (Empty, t) => t
+        case (t, Empty) => t
+        case (RedTree(x, xv, a, b), RedTree(y, yv, c, d)) =>
+          append(b, c) match {
+            case RedTree(z, zv, bb, cc) => RedTree(z, zv, RedTree(x, xv, a, bb), RedTree(y, yv, cc, d))
+            case bc => RedTree(x, xv, a, RedTree(y, yv, bc, d))
+          }
+        case (BlackTree(x, xv, a, b), BlackTree(y, yv, c, d)) =>
+          append(b, c) match {
+            case RedTree(z, zv, bb, cc) => RedTree(z, zv, BlackTree(x, xv, a, bb), BlackTree(y, yv, cc, d))
+            case bc => balLeft(x, xv, a, BlackTree(y, yv, bc, d))
+          }
+        case (a, RedTree(x, xv, b, c)) => RedTree(x, xv, append(a, b), c)
+        case (RedTree(x, xv, a, b), c) => RedTree(x, xv, a, append(b, c))
+      }
+      // RedBlack is neither A : Ordering[A], nor A <% Ordered[A]
+      k match {
+        case _ if isSmaller(k, key) => delLeft
+        case _ if isSmaller(key, k) => delRight
+        case _ => append(left, right)
       }
     }
+
     def smallest: NonEmpty[B] = if (left.isEmpty) this else left.smallest
-    def elements : ImmutableIterator[Pair[A,B]] = 
-      left.elements.append(Pair(key,value), () => right.elements)
 
-    def elementsSlow: Iterator[Pair[A, B]] = 
-      left.elementsSlow append Iterator.single(Pair(key, value)) append right.elementsSlow
-      
-    def visit[T](input : T)(f : (T,A,B) => Tuple2[Boolean,T]) : Tuple2[Boolean,T] = {
+    def toStream: Stream[(A,B)] = 
+      left.toStream ++ Stream((key,value)) ++ right.toStream
+
+    def iterator: Iterator[(A, B)] = 
+      left.iterator ++ Iterator.single(Pair(key, value)) ++ right.iterator
+
+    def foreach[U](f: (A, B) => U) {
+      left foreach f
+      f(key, value)
+      right foreach f
+    }
+
+    @deprecated("use `foreach' instead")
+    def visit[T](input: T)(f: (T,A,B) => (Boolean, T)): (Boolean, T) = {
       val left = this.left.visit(input)(f)
       if (!left._1) return left
       val middle = f(left._2, key, value)
       if (!middle._1) return middle
       return this.right.visit(middle._2)(f)
     }
-   override def range(from : Option[A], until : Option[A]) : Tree[B] = {
+   override def range(from: Option[A], until: Option[A]): Tree[B] = {
       if (from == None && until == None) return this
       if (from != None && isSmaller(key, from.get)) return right.range(from, until);
       if (until != None && (isSmaller(until.get,key) || !isSmaller(key,until.get)))
@@ -120,11 +197,15 @@ abstract class RedBlack[A] {
     def upd[B](k: A, v: B): Tree[B] = RedTree(k, v, Empty, Empty)
     def del(k: A): Tree[Nothing] = this
     def smallest: NonEmpty[Nothing] = throw new NoSuchElementException("empty map")
-    def elementsSlow: Iterator[Pair[A, Nothing]] = Iterator.empty
-    def elements : ImmutableIterator[Pair[A,Nothing]] = ImmutableIterator.empty
-    def visit[T](input : T)(f : (T,A,Nothing) => Tuple2[Boolean,T]) = Tuple2(true,input)
+    def iterator: Iterator[(A, Nothing)] = Iterator.empty
+    def toStream: Stream[(A,Nothing)] = Stream.empty
+
+    def foreach[U](f: (A, Nothing) => U) {}
+
+    @deprecated("use `foreach' instead")
+    def visit[T](input: T)(f: (T, A, Nothing) => (Boolean, T)) = (true, input)
 
-    def range(from : Option[A], until : Option[A]) = this
+    def range(from: Option[A], until: Option[A]) = this
     def first = throw new NoSuchElementException("empty map")
     def last = throw new NoSuchElementException("empty map")
     def count = 0
diff --git a/src/library/scala/collection/immutable/Seq.scala b/src/library/scala/collection/immutable/Seq.scala
new file mode 100644
index 0000000..e8dc550
--- /dev/null
+++ b/src/library/scala/collection/immutable/Seq.scala
@@ -0,0 +1,39 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+package immutable
+
+import generic._
+import mutable.Builder
+
+/** A subtrait of `collection.Seq` which represents sequences
+ *  that are guaranteed immutable.
+ *
+ *  $seqInfo
+ *  @define Coll immutable.Seq
+ *  @define coll immutable sequence
+ */
+trait Seq[+A] extends Iterable[A] 
+                      with scala.collection.Seq[A] 
+                      with GenericTraversableTemplate[A, Seq]
+                      with SeqLike[A, Seq[A]] { 
+  override def companion: GenericCompanion[Seq] = Seq
+}
+
+/** $factoryInfo
+ *  @define Coll immutable.Seq
+ *  @define coll immutable sequence
+ */
+object Seq extends SeqFactory[Seq] {
+  /** genericCanBuildFromInfo */
+  implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, Seq[A]] = new GenericCanBuildFrom[A]
+  def newBuilder[A]: Builder[A, Seq[A]] = new mutable.ListBuffer
+}
diff --git a/src/library/scala/collection/immutable/Set.scala b/src/library/scala/collection/immutable/Set.scala
index 8fc47dc..76b659c 100644
--- a/src/library/scala/collection/immutable/Set.scala
+++ b/src/library/scala/collection/immutable/Set.scala
@@ -1,187 +1,148 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Set.scala 16881 2009-01-09 16:28:11Z cunei $
 
 
-package scala.collection.immutable
+package scala.collection
+package immutable
 
+import generic._
 
-/** Canonical factories for immutable sets.  The canonical immutable sets are
-  *  currently implemented using <a href="HashSet.html">immutable hash sets</a>.
-  */ 
-object Set {
-  /** The empty set of this type
-   */
-  def empty[A]: Set[A] = new EmptySet[A]
-
-  /** The canonical factory for this type
-   */
-  def apply[A](elems: A*) = empty[A] ++ elems
+/** A generic trait for immutable sets.
+ *  
+ *  $setnote
+ *  
+ *  @author Matthias Zenger
+ *  @author Martin Odersky
+ *  @version 2.8
+ *  @since   1
+ *  @define Coll immutable.Set
+ *  @define coll immutable set
+ */
+trait Set[A] extends Iterable[A] 
+                with scala.collection.Set[A] 
+                with GenericSetTemplate[A, Set]
+                with SetLike[A, Set[A]] { 
+  override def companion: GenericCompanion[Set] = Set
 }
 
-/** <p>
- *    This class defines the interface for immutable sets.  Operations
- *    on an immutable set leave the original set unchanged, and return
- *    a new set if needed.
- *  </p>
- *  <p>
- *    Concrete set implementations just have to provide functionality for
- *    the abstract methods in <code>scala.collection.Set</code> as well as
- *    for <code>+</code> and <code>-</code>.
- *  </p>
- *  <p>
- *    Note that abstract immutable.Set's are not covariant in their type
- *    parameter.  This is because some implementations cannot support the
- *    <code>+</code> method for arbitrary types.
- *  </p>
- *
- *  @author  Matthias Zenger, Martin Odersky
- *  @version 1.1, 03/05/2004
+/** $factoryInfo
+ *  @define Coll immutable.Set
+ *  @define coll immutable set
  */
-trait Set[A] extends AnyRef with collection.Set[A] {
-
-  /** @return an empty set of arbitrary element type
-   */
-  def empty[B]: Set[B]
-
-  /** Create a new set with an additional element.
-   */
-  def +(elem: A): Set[A]
-
-  /** Add two or more elements to this set. 
-   *  @param    elem1 the first element.
-   *  @param    elem2 the second element.
-   *  @param    elems the remaining elements.
-   *  @return a new set with the elements added.
-   */
-  def + (elem1: A, elem2: A, elems: A*): Set[A] = 
-    this + elem1 + elem2 ++ elems
-
-  /** Add all the elements provided by an iterator
-   *  of the iterable object <code>elems</code> to the set.
-   *
-   *  @param elems  the iterable object containing the elements to be added 
-   *  @return a new set with the elements added.
-   */
-  def ++ (elems: Iterable[A]): Set[A] = 
-    (this /: elems) ((s, elem) => s + elem)
-
-  /** Add all the elements provided by an iterator to the set.
-   *  @param elems  the iterator containing the elements to be added 
-   *  @return a new set with the elements added.
-   */
-  def ++ (elems: Iterator[A]): Set[A] = 
-    (this /: elems) ((s, elem) => s + elem)
-
-  /** <code>incl</code> can be used to add many elements to the set
-   *  at the same time.
-   *  @deprecated use <code>+</code> instead
-   */
-  @deprecated
-  def incl(elems: A*): Set[A] = incl(elems)
-    
-  /** This method will add all the elements provided by an iterator
-   *  of the iterable object <code>that</code> to the set.
-   *  @deprecated use <code>++</code> instead
-   */
-  @deprecated
-  def incl(that: Iterable[A]): Set[A] =
-    that.foldLeft(this)((set, elem) => set + elem)
-
-  /** Remove a single element from a set.
-   *  @param elem the element to be removed
-   *  @return a new set with the element removed.
-   */
-  def -(elem: A): Set[A]
-    
-  /** Remove two or more elements from this set.
-   *
-   *  @param    elem1 the first element.
-   *  @param    elem2 the second element.
-   *  @param    elems the remaining elements.
-   *  @return a new set with the elements removed.
-   */
-  def - (elem1: A, elem2: A, elems: A*): Set[A] = 
-    this - elem1 - elem2 -- elems
-
-  /** Remove all the elements provided by an iterator
-   *  of the iterable object <code>elems</code> from the set.
-   *
-   *  @param elems An iterable object containing the elements to remove from the set.
-   *  @return a new set with the elements removed.
-   */
-  def -- (elems: Iterable[A]): Set[A] = this -- elems.elements
-
-  /** Remove all the elements provided by an iterator
-   *  <code>elems</code> from the set.
-   *
-   *  @param elems An iterator containing the elements to remove from the set.
-   *  @return a new set with the elements removed.
-   */
-  def -- (elems: Iterator[A]): Set[A] =
-    (this /: elems) ((s, elem) => s - elem)
-
-  /** <code>excl</code> removes many elements from the set.
-   */
-  @deprecated
-  def excl(elems: A*): Set[A] = excl(elems)
-    
-  /** This method removes all the elements provided by an iterator
-   *  of the iterable object <code>that</code> from the set.
-   *
-   *  @param that the iterable collection.
-   */
-  @deprecated
-  def excl(that: Iterable[A]): Set[A] =
-    that.foldLeft(this)((set, elem) => set - elem)
-
-  /** This method computes an intersection with set <code>that</code>.
-   *  It removes all the elements that are not present in <code>that</code>.
-   *
-   *  @param that the set to intersect with.
-   */
-  def intersect(that: collection.Set[A]): Set[A] = filter(that.contains)
-
-  /** This method is an alias for <code>intersect</code>. 
-   *  It computes an intersection with set <code>that</code>.
-   *  It removes all the elements that are not present in <code>that</code>.
-   *
-   *  @param that the set to intersect with
-   */
-   override def ** (that: collection.Set[A]): Set[A] = intersect(that)
-
-  /** Returns the set resulting from applying the given function <code>f</code> to each
-   *  element of this set.
-   *
-   *  @param f function to apply to each element.
-   *  @return a set containing <code>f(a0), ..., f(an)</code> 
-   *          if this set contains <code>a0, ..., an</code>.
-   */
-  override def map[B](f: A => B): Set[B] =
-    foldLeft(empty[B])((set: Set[B], elem: A) => set + f(elem))
-
-  /** Applies the given function <code>f</code> to each element of
-   *  this set, then forms the union of all results.
-   *
-   *  @param f function to apply to each element.
-   *  @return a set containing all elements in each <code>f(a0), ..., f(an)</code> 
-   *          if this set contains <code>a0, ..., an</code>.
-   */
-  override def flatMap[B](f: A => Iterable[B]): Set[B] =
-    foldLeft(empty[B])((set: Set[B], elem: A) => set ++ f(elem))
-
-  /** Method <code>filter</code> removes all elements from the set for
-   *  which the predicate <code>p</code> yields the value <code>false</code>.
-   *
-   *  @param p The predicate used to filter the set
-   */
-  override def filter(p: A => Boolean): Set[A] =
-    (this /: toList)((set, elem) => if (p(elem)) set else set - elem)
-
+object Set extends ImmutableSetFactory[Set] {
+  /** $setCanBuildFromInfo */
+  implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, Set[A]] = setCanBuildFrom[A]
+  override def empty[A]: Set[A] = EmptySet.asInstanceOf[Set[A]]
+
+  private val hashSeed = "Set".hashCode 
+
+  /** An optimized representation for immutable empty sets */
+  @serializable
+  private object EmptySet extends Set[Any] {
+    override def size: Int = 0
+    def contains(elem: Any): Boolean = false
+    def + (elem: Any): Set[Any] = new Set1(elem)
+    def - (elem: Any): Set[Any] = this
+    def iterator: Iterator[Any] = Iterator.empty
+    override def foreach[U](f: Any =>  U): Unit = {}
+  }
+
+  @serializable @deprecated("use `Set.empty' instead")
+  class EmptySet[A] extends Set[A] {
+    override def size: Int = 0
+    def contains(elem: A): Boolean = false
+    def + (elem: A): Set[A] = new Set1(elem)
+    def - (elem: A): Set[A] = this
+    def iterator: Iterator[A] = Iterator.empty
+    override def foreach[U](f: A =>  U): Unit = {}
+  }
+  
+  /** An optimized representation for immutable sets of size 1 */
+  @serializable @SerialVersionUID(1233385750652442003L)
+  class Set1[A](elem1: A) extends Set[A] {
+    override def size: Int = 1
+    def contains(elem: A): Boolean = 
+      elem == elem1
+    def + (elem: A): Set[A] = 
+      if (contains(elem)) this
+      else new Set2(elem1, elem)
+    def - (elem: A): Set[A] = 
+      if (elem == elem1) Set.empty
+      else this
+    def iterator: Iterator[A] = 
+      Iterator(elem1)
+    override def foreach[U](f: A =>  U): Unit = {
+      f(elem1)
+    }
+  }
+
+  /** An optimized representation for immutable sets of size 2 */
+  @serializable @SerialVersionUID(-6443011234944830092L)
+  class Set2[A](elem1: A, elem2: A) extends Set[A] {
+    override def size: Int = 2
+    def contains(elem: A): Boolean = 
+      elem == elem1 || elem == elem2
+    def + (elem: A): Set[A] = 
+      if (contains(elem)) this
+      else new Set3(elem1, elem2, elem)
+    def - (elem: A): Set[A] = 
+      if (elem == elem1) new Set1(elem2)
+      else if (elem == elem2) new Set1(elem1)
+      else this
+    def iterator: Iterator[A] = 
+      Iterator(elem1, elem2)
+    override def foreach[U](f: A =>  U): Unit = {
+      f(elem1); f(elem2)
+    }
+  }
+
+  /** An optimized representation for immutable sets of size 3 */
+  @serializable @SerialVersionUID(-3590273538119220064L)
+  class Set3[A](elem1: A, elem2: A, elem3: A) extends Set[A] {
+    override def size: Int = 3
+    def contains(elem: A): Boolean = 
+      elem == elem1 || elem == elem2 || elem == elem3
+    def + (elem: A): Set[A] = 
+      if (contains(elem)) this
+      else new Set4(elem1, elem2, elem3, elem)
+    def - (elem: A): Set[A] = 
+      if (elem == elem1) new Set2(elem2, elem3)
+      else if (elem == elem2) new Set2(elem1, elem3)
+      else if (elem == elem3) new Set2(elem1, elem2)
+      else this
+    def iterator: Iterator[A] = 
+      Iterator(elem1, elem2, elem3)
+    override def foreach[U](f: A =>  U): Unit = {
+      f(elem1); f(elem2); f(elem3)
+    }
+  }
+
+  /** An optimized representation for immutable sets of size 4 */
+  @serializable @SerialVersionUID(-3622399588156184395L)
+  class Set4[A](elem1: A, elem2: A, elem3: A, elem4: A) extends Set[A] {
+    override def size: Int = 4
+    def contains(elem: A): Boolean = 
+      elem == elem1 || elem == elem2 || elem == elem3 || elem == elem4
+    def + (elem: A): Set[A] = 
+      if (contains(elem)) this
+      else new HashSet[A] + (elem1, elem2, elem3, elem4, elem)
+    def - (elem: A): Set[A] = 
+      if (elem == elem1) new Set3(elem2, elem3, elem4)
+      else if (elem == elem2) new Set3(elem1, elem3, elem4)
+      else if (elem == elem3) new Set3(elem1, elem2, elem4)
+      else if (elem == elem4) new Set3(elem1, elem2, elem3)
+      else this
+    def iterator: Iterator[A] = 
+      Iterator(elem1, elem2, elem3, elem4)
+    override def foreach[U](f: A =>  U): Unit = {
+      f(elem1); f(elem2); f(elem3); f(elem4)
+    }
+  }
 }
+
diff --git a/src/library/scala/collection/immutable/Set1.scala b/src/library/scala/collection/immutable/Set1.scala
deleted file mode 100644
index 3b20ceb..0000000
--- a/src/library/scala/collection/immutable/Set1.scala
+++ /dev/null
@@ -1,42 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: Set1.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-
-package scala.collection.immutable
-
-/** This class implements immutable sets with exactly one element.
- *  @author  Martin Oderskty
- *  @version 1.0, 019/01/2007
- */
- at serializable
-class Set1[A](elem1: A) extends Set[A] {
-
-  def empty[C]: Set[C] = new EmptySet[C]
-
-  def size: Int = 1
-
-  def contains(elem: A): Boolean = 
-    elem == elem1
-
-  def + (elem: A): Set[A] = 
-    if (contains(elem)) this
-    else new Set2(elem1, elem)
-
-  def - (elem: A): Set[A] = 
-    if (elem == elem1) empty 
-    else this
-
-  def elements: Iterator[A] = 
-    Iterator.fromValues(elem1)
-}
-  
-
-
diff --git a/src/library/scala/collection/immutable/Set2.scala b/src/library/scala/collection/immutable/Set2.scala
deleted file mode 100644
index 48dbe8e..0000000
--- a/src/library/scala/collection/immutable/Set2.scala
+++ /dev/null
@@ -1,43 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: Set2.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-
-package scala.collection.immutable
-
-/** This class implements immutable sets with exactly two elements.
- *  @author  Martin Oderskty
- *  @version 1.0, 019/01/2007
- */
- at serializable
-class Set2[A](elem1: A, elem2: A) extends Set[A] {
-
-  def empty[C]: Set[C] = new EmptySet[C]
-
-  def size: Int = 2
-
-  def contains(elem: A): Boolean = 
-    elem == elem1 || elem == elem2
-
-  def + (elem: A): Set[A] = 
-    if (contains(elem)) this
-    else new Set3(elem1, elem2, elem)
-
-  def - (elem: A): Set[A] = 
-    if (elem == elem1) new Set1(elem2)
-    else if (elem == elem2) new Set1(elem1)
-    else this
-
-  def elements: Iterator[A] = 
-    Iterator.fromValues(elem1, elem2)
-}
-  
-
-
diff --git a/src/library/scala/collection/immutable/Set3.scala b/src/library/scala/collection/immutable/Set3.scala
deleted file mode 100644
index 175fa8f..0000000
--- a/src/library/scala/collection/immutable/Set3.scala
+++ /dev/null
@@ -1,44 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: Set3.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-
-package scala.collection.immutable
-
-/** This class implements immutable sets with exactly three elements.
- *  @author  Martin Oderskty
- *  @version 1.0, 019/01/2007
- */
- at serializable
-class Set3[A](elem1: A, elem2: A, elem3: A) extends Set[A] {
-
-  def empty[C]: Set[C] = new EmptySet[C]
-
-  def size: Int = 3
-
-  def contains(elem: A): Boolean = 
-    elem == elem1 || elem == elem2 || elem == elem3
-
-  def + (elem: A): Set[A] = 
-    if (contains(elem)) this
-    else new Set4(elem1, elem2, elem3, elem)
-
-  def - (elem: A): Set[A] = 
-    if      (elem == elem1) new Set2(elem2, elem3)
-    else if (elem == elem2) new Set2(elem1, elem3)
-    else if (elem == elem3) new Set2(elem1, elem2)
-    else this
-
-  def elements: Iterator[A] = 
-    Iterator.fromValues(elem1, elem2, elem3)
-}
-  
-
-
diff --git a/src/library/scala/collection/immutable/Set4.scala b/src/library/scala/collection/immutable/Set4.scala
deleted file mode 100644
index bf7ce2e..0000000
--- a/src/library/scala/collection/immutable/Set4.scala
+++ /dev/null
@@ -1,45 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: Set4.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-
-package scala.collection.immutable
-
-/** This class implements immutable sets with exactly four elements.
- *  @author  Martin Oderskty
- *  @version 1.0, 019/01/2007
- */
- at serializable
-class Set4[A](elem1: A, elem2: A, elem3: A, elem4: A) extends Set[A] {
-
-  def empty[C]: Set[C] = new EmptySet[C]
-
-  def size: Int = 4
-
-  def contains(elem: A): Boolean = 
-    elem == elem1 || elem == elem2 || elem == elem3 || elem == elem4
-
-  def + (elem: A): Set[A] = 
-    if (contains(elem)) this
-    else HashSet(elem1, elem2, elem3, elem4, elem)
-
-  def - (elem: A): Set[A] = 
-    if      (elem == elem1) new Set3(elem2, elem3, elem4)
-    else if (elem == elem2) new Set3(elem1, elem3, elem4)
-    else if (elem == elem3) new Set3(elem1, elem2, elem4)
-    else if (elem == elem4) new Set3(elem1, elem2, elem3)
-    else this
-
-  def elements: Iterator[A] = 
-    Iterator.fromValues(elem1, elem2, elem3, elem4)
-}
-  
-
-
diff --git a/src/library/scala/collection/immutable/SetProxy.scala b/src/library/scala/collection/immutable/SetProxy.scala
new file mode 100644
index 0000000..0f28df7
--- /dev/null
+++ b/src/library/scala/collection/immutable/SetProxy.scala
@@ -0,0 +1,32 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+package immutable
+
+/** This is a simple wrapper class for <a href="Set.html"
+ *  target="contentFrame">`scala.collection.immutable.Set`</a>.
+ *  
+ *  It is most useful for assembling customized set abstractions
+ *  dynamically using object composition and forwarding.
+ *  
+ *  @tparam A    type of the elements contained in this set proxy.
+ *  
+ *  @since 2.8
+ */
+trait SetProxy[A] extends Set[A] with SetProxyLike[A, Set[A]] {
+  override def repr = this
+  private def newProxy[B >: A](newSelf: Set[B]): SetProxy[B] =
+    new SetProxy[B] { val self = newSelf }
+  
+  override def empty = newProxy(self.empty)
+  override def + (elem: A) = newProxy(self + elem)
+  override def - (elem: A) = newProxy(self - elem)
+}
diff --git a/src/library/scala/collection/immutable/SortedMap.scala b/src/library/scala/collection/immutable/SortedMap.scala
index 1fcf497..1d448ad 100644
--- a/src/library/scala/collection/immutable/SortedMap.scala
+++ b/src/library/scala/collection/immutable/SortedMap.scala
@@ -1,60 +1,77 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: SortedMap.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.collection.immutable
 
-trait SortedMap[A,+B] extends Map[A,B] with collection.SortedMap[A,B] {
-
-  override def rangeImpl(from: Option[A], until: Option[A]): SortedMap[A,B]
-
-  override def from(from: A) = rangeImpl(Some(from), None)
-
-  override def until(until: A) = rangeImpl(None, Some(until))
-
-  override def range(from: A, until: A) = rangeImpl(Some(from),Some(until))
-
-  override def empty[C]: SortedMap[A, C]
-
-  override def update [B1 >: B] (key: A, value: B1): SortedMap[A, B1]
-
-  override def + [B1 >: B] (kv: Pair[A, B1]): SortedMap[A, B1] = update(kv._1, kv._2)
-                                                               
-  override def + [B1 >: B] (kv1: Pair[A, B1], kv2: Pair[A, B1], kvs: Pair[A, B1]*): SortedMap[A, B1] =
-    this + kv1 + kv2 ++ kvs
-
-  override def ++ [B1 >: B] (kvs: Iterable[Pair[A, B1]]): SortedMap[A, B1] = 
-    ((this: SortedMap[A, B1]) /: kvs) ((m, kv) => m + kv)
-
-  override def ++ [B1 >: B] (kvs: Iterator[Pair[A, B1]]): SortedMap[A, B1] =
-    ((this: SortedMap[A, B1]) /: kvs) ((m, kv) => m + kv)
-
-  override def - (key: A): SortedMap[A, B]
-
-  override def - (key1: A, key2: A, keys: A*): SortedMap[A, B] = 
-    this - key1 - key2 -- keys
-
-  override def -- (keys: Iterable[A]): SortedMap[A, B] = this -- keys.elements
-
-  override def -- (keys: Iterator[A]): SortedMap[A, B] = 
-    (this /: keys) ((m, key) => m - key)
+package scala.collection
+package immutable
+
+import generic._
+import mutable.Builder
+import annotation.unchecked.uncheckedVariance
+
+/** A map whose keys are sorted.
+ *  
+ *  @tparam A     the type of the keys contained in this sorted map.
+ *  @tparam B     the type of the values associated with the keys.
+ *  
+ *  @author Sean McDirmid
+ *  @author Martin Odersky
+ *  @version 2.8
+ *  @since   2.4
+ *  @define Coll immutable.SortedMap
+ *  @define coll immutable sorted map
+ */
+trait SortedMap[A, +B] extends Map[A, B] 
+                         with scala.collection.SortedMap[A, B] 
+                         with MapLike[A, B, SortedMap[A, B]]
+                         with SortedMapLike[A, B, SortedMap[A, B]] {
+
+  override protected[this] def newBuilder : Builder[(A, B), SortedMap[A, B]] = 
+    SortedMap.newBuilder[A, B]
+
+  override def empty: SortedMap[A, B] = SortedMap.empty
+
+  override def updated [B1 >: B](key: A, value: B1): SortedMap[A, B1] = this + ((key, value))
+
+  /** Add a key/value pair to this map. 
+   *  @param    key the key
+   *  @param    value the value
+   *  @return   A new map with the new binding added to this map
+   *  @note     needs to be overridden in subclasses
+   */
+  def + [B1 >: B](kv: (A, B1)): SortedMap[A, B1] = throw new AbstractMethodError("SortedMap.+")
+
+  /** Adds two or more elements to this collection and returns
+   *  a new collection.
+   *
+   *  @param elem1 the first element to add.
+   *  @param elem2 the second element to add.
+   *  @param elems the remaining elements to add.
+   */
+  override def + [B1 >: B] (elem1: (A, B1), elem2: (A, B1), elems: (A, B1) *): SortedMap[A, B1] =
+    this + elem1 + elem2 ++ elems
+
+  /** Adds a number of elements provided by a traversable object
+   *  and returns a new collection with the added elements.
+   *
+   *  @param elems     the traversable object.
+   */
+  override def ++[B1 >: B](xs: TraversableOnce[(A, B1)]): SortedMap[A, B1] = 
+    ((repr: SortedMap[A, B1]) /: xs) (_ + _)
+}
 
-  override def transform[C](f: (A, B) => C): SortedMap[A, C] = {
-    var res = empty[C]
-    foreach { case (key, value) => res = res.update(key, f(key, value)) }
-    res
-  }
-  override def filter(p: Pair[A, B] => Boolean): SortedMap[A, B] = {
-    var res = this
-    foreach {
-      case kv @ (key, _) => if (!p(kv)) { res = res - key }
-    }
-    res
-  }
+/** $factoryInfo
+ *  @define Coll immutable.SortedMap
+ *  @define coll immutable sorted map
+ */
+object SortedMap extends ImmutableSortedMapFactory[SortedMap] {
+  /** $sortedMapCanBuildFromInfo */
+  implicit def canBuildFrom[A, B](implicit ord: Ordering[A]): CanBuildFrom[Coll, (A, B), SortedMap[A, B]] = new SortedMapCanBuildFrom[A, B]
+  def empty[A, B](implicit ord: Ordering[A]): SortedMap[A, B] = TreeMap.empty[A, B]
 }
diff --git a/src/library/scala/collection/immutable/SortedSet.scala b/src/library/scala/collection/immutable/SortedSet.scala
index 5644200..d0168b7 100644
--- a/src/library/scala/collection/immutable/SortedSet.scala
+++ b/src/library/scala/collection/immutable/SortedSet.scala
@@ -1,17 +1,40 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: SortedSet.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.collection.immutable
 
-trait SortedSet[A] extends scala.collection.SortedSet[A] with Set[A] {
-  override def ++ (elems: Iterable[A]): SortedSet[A] = 
-    (this /: elems) ((s, elem) => s + elem)
-  override def +(elem: A): SortedSet[A]
+package scala.collection
+package immutable
+
+import generic._
+import mutable.Builder
+
+/** A subtrait of `collection.SortedSet` which represents sorted sets
+ *  which cannot be mutated.
+ *
+ *  @author Sean McDirmid
+ *  @author Martin Odersky
+ *  @version 2.8
+ *  @since   2.4
+ *  @define Coll immutable.SortedSet
+ *  @define coll immutable sorted set
+ */
+trait SortedSet[A] extends Set[A] with scala.collection.SortedSet[A] with SortedSetLike[A, SortedSet[A]] {
+  /** Needs to be overridden in subclasses. */
+  override def empty: SortedSet[A] = SortedSet.empty[A]
+}
+
+/** $factoryInfo
+ *  @define Coll immutable.SortedSet
+ *  @define coll immutable sorted set
+ */
+object SortedSet extends ImmutableSortedSetFactory[SortedSet] {
+  /** $sortedSetCanBuildFromInfo */
+  implicit def canBuildFrom[A](implicit ord: Ordering[A]): CanBuildFrom[Coll, A, SortedSet[A]] = new SortedSetCanBuildFrom[A]
+  def empty[A](implicit ord: Ordering[A]): SortedSet[A] = TreeSet.empty[A]
 }
diff --git a/src/library/scala/collection/immutable/Stack.scala b/src/library/scala/collection/immutable/Stack.scala
index 23d7198..96463ea 100644
--- a/src/library/scala/collection/immutable/Stack.scala
+++ b/src/library/scala/collection/immutable/Stack.scala
@@ -1,62 +1,75 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Stack.scala 17488 2009-04-14 09:08:24Z dragos $
 
 
-package scala.collection.immutable
+package scala.collection
+package immutable
 
+import generic._
+import mutable.{ ArrayBuffer, Builder }
 
-//import Predef.NoSuchElementException
-
-object Stack {
-  val Empty = new Stack[Nothing]
+/** $factoryInfo
+ *  @define Coll immutable.Stack
+ *  @define coll immutable stack
+ */
+object Stack extends SeqFactory[Stack] {
+  /** $genericCanBuildFromInfo */
+  implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, Stack[A]] = new GenericCanBuildFrom[A]
+  def newBuilder[A]: Builder[A, Stack[A]] = new ArrayBuffer[A] mapResult (buf => new Stack(buf.toList))
+  
+  @deprecated("Use Stack.empty instead")
+  val Empty: Stack[Nothing] = Stack()
 }
 
 /** This class implements immutable stacks using a list-based data
- *  structure. Instances of <code>Stack</code> represent
- *  empty stacks; they can be either created by calling the constructor
- *  directly, or by applying the function <code>Stack.Empty</code>.
+ *  structure.
  *
+ *  '''Note:''' This class exists only for historical reason and as an
+ *           analogue of mutable stacks.
+ *           Instead of an immutable stack you can just use a list.
+ *  
+ *  @tparam A    the type of the elements contained in this stack.
+ *  
  *  @author  Matthias Zenger
  *  @version 1.0, 10/07/2003
+ *  @since   1
+ *  @define Coll immutable.Stack
+ *  @define coll immutable stack
+ *  @define orderDependent
+ *  @define orderDependentFold
+ *  @define mayNotTerminateInf
+ *  @define willNotTerminateInf
  */
- at serializable
-class Stack[+A] extends Seq[A] {
-
+ at serializable @SerialVersionUID(1976480595012942526L)
+class Stack[+A] protected (protected val elems: List[A])
+                    extends LinearSeq[A] 
+                    with GenericTraversableTemplate[A, Stack]
+                    with LinearSeqOptimized[A, Stack[A]] {
+  override def companion: GenericCompanion[Stack] = Stack
+
+  def this() = this(Nil)
+  
   /** Checks if this stack is empty.
    *
    *  @return true, iff there is no element on the stack.
    */
-  override def isEmpty: Boolean = true
+  override def isEmpty: Boolean = elems.isEmpty
 
-  /** Returns the size of this stack.
-   *
-   *  @return the stack size.
-   */
-  def length: Int = 0
-
-  /** Push an element on the stack. 
-   *
-   *  @deprecated Use the method <code>push</code> from now on.
-   *
-   *  @param   elem       the element to push on the stack.
-   *  @return the stack with the new element on top.
-   */
-  @deprecated
-  def +[B >: A](elem: B): Stack[B] = new Node(elem)
+  override def head = elems.head
+  override def tail = new Stack(elems.tail)
 
   /** Push an element on the stack.
    *
    *  @param   elem       the element to push on the stack.
    *  @return the stack with the new element on top.
    */
-  def push[B >: A](elem: B): Stack[B] = new Node(elem)
+  def push[B >: A](elem: B): Stack[B] = new Stack(elem :: elems)
    
   /** Push a sequence of elements onto the stack. The last element
    *  of the sequence will be on top of the new stack.
@@ -64,76 +77,44 @@ class Stack[+A] extends Seq[A] {
    *  @param   elems      the element sequence.
    *  @return the stack with the new elements on top.
    */
-  def push[B >: A](elem1: B, elem2: B, elems: B*): Stack[B] = this.push(elem1).push(elem2) ++ elems
+  def push[B >: A](elem1: B, elem2: B, elems: B*): Stack[B] = 
+    this.push(elem1).push(elem2).pushAll(elems)
    
-  /** Push all elements provided by the given iterable object onto
-   *  the stack. The last element returned by the iterable object
-   *  will be on top of the new stack.
-   *
-   *  @deprecated Use the method <code>push</code> from now on.
-   *
-   *  @param   elems      the iterable object.
-   *  @return the stack with the new elements on top.
-   */
-  @deprecated
-  def +[B >: A](elems: Iterable[B]): Stack[B] =
-    elems.foldLeft(this: Stack[B]){ (stack, elem) => stack + elem }
-
-  /** Push all elements provided by the given iterable object onto
-   *  the stack. The last element returned by the iterable object
-   *  will be on top of the new stack.
-   *
-   *  @param   elems      the iterable object.
-   *  @return the stack with the new elements on top.
-   */
-  def push[B >: A](elems: Iterable[B]): Stack[B] =
-    this ++ elems
-
-  /** Push all elements provided by the given iterator object onto
-   *  the stack. The last element returned by the iterable object
+  /** Push all elements provided by the given traversable object onto
+   *  the stack. The last element returned by the traversable object
    *  will be on top of the new stack.
    *
    *  @param   elems      the iterator object.
    *  @return the stack with the new elements on top.
-   *  @deprecated
    */
-  def ++[B >: A](elems: Iterator[B]): Stack[B] =
-    elems.foldLeft(this: Stack[B]){ (stack, elem) => stack + elem }
-  
-  /** Push all elements provided by the given iterable object onto
-   *  the stack. The last element returned by the iterable object
-   *  will be on top of the new stack.
-   *
-   *  @param   elems      the iterable object.
-   *  @return the stack with the new elements on top.
-   */
-  override def ++[B >: A](elems: Iterable[B]): Stack[B] =
-    this ++ elems.elements
+  def pushAll[B >: A](xs: TraversableOnce[B]): Stack[B] =
+    ((this: Stack[B]) /: xs.toIterator)(_ push _)
 
   /** Returns the top element of the stack. An error is signaled if
    *  there is no element on the stack.
    *
+   *  @throws Predef.NoSuchElementException
    *  @return the top element.
    */
-  def top: A = throw new NoSuchElementException("no element on stack")
-    
+  def top: A =
+    if (!isEmpty) elems.head
+    else throw new NoSuchElementException("top of empty stack")
+
   /** Removes the top element from the stack.
+   *  Note: should return <code>(A, Stack[A])</code> as for queues (mics)
    *
+   *  @throws Predef.NoSuchElementException
    *  @return the new stack without the former top element.
    */
-  def pop: Stack[A] = throw new NoSuchElementException("no element on stack")
-    
-  /** Returns the n-th element of this stack. The bottom element has index
-   *  0, elements above are indexed with increasing numbers.
-   *
-   *  @param   n      the index number.
-   *  @return the n-th element on the stack.
-   */
-  def apply(n: Int): A = reverse.reverseApply(n)
-  
-  private def reverseApply(n: Int): A =
-    if (n > 0) pop.reverseApply(n - 1)
-    else top
+  def pop: Stack[A] =
+    if (!isEmpty) new Stack(elems.tail)
+    else throw new NoSuchElementException("pop of empty stack")
+
+  def pop2: (A, Stack[A]) =
+    if (!isEmpty) (elems.head, new Stack(elems.tail))
+    else throw new NoSuchElementException("pop of empty stack")
+
+  override def reverse: Stack[A] = new Stack(elems.reverse)
 
   /** Returns an iterator over all elements on the stack. The iterator
    *  issues elements in the reversed order they were inserted into the
@@ -141,58 +122,10 @@ class Stack[+A] extends Seq[A] {
    *
    *  @return an iterator over all stack elements.
    */
-  override def elements: Iterator[A] = reverse.reverseElements
-
-  private def reverseElements: Iterator[A] = new Iterator[A] {
-    var that: Stack[A] = Stack.this;
-    def hasNext = !that.isEmpty;
-    def next =
-      if (!hasNext) throw new NoSuchElementException("next on empty iterator")
-      else { val res = that.top; that = that.pop; res }
-  }
-  
-  /** A stack consisting of all elements of this stack in reverse order.
-   */
-  override def reverse: Stack[A] = {
-    // copy-paste from List.reverse
-    var result: Stack[A] = Stack.Empty
-    var these = this
-    while (!these.isEmpty) {
-      result = result push List(these.top) // see #978
-      these = these.pop
-    }
-    result
-  }
-
-  /** Compares this stack with the given object.
-   *
-   *  @return true, iff the two stacks are equal; i.e. they contain the
-   *          same elements in the same order.
-   */
-  override def equals(obj: Any): Boolean = obj match {
-    case that: Stack[_] => this sameElements that
-    case _ => false
-  }
+  override def iterator: Iterator[A] = elems.iterator
 
-  /** Returns the hash code for this stack.
-   *
-   *  @return the hash code of the stack.
-   */
-  override def hashCode(): Int = 0
-
-  /**
-   * Redefines the prefix of the string representation.
+  /** Returns a string representation of this stack. 
    */
-  override def stringPrefix: String = "Stack"
-
-  // Here comes true magic: covariant lists with implicit tail references
-  @serializable
-  protected class Node[+B >: A](elem: B) extends Stack[B] {
-    override def isEmpty: Boolean = false
-    override def length: Int = Stack.this.length + 1
-    override def top: B = elem
-    override def pop: Stack[B] = Stack.this
-    override def hashCode(): Int = elem.hashCode() + Stack.this.hashCode()
-  }
-
+  override def toString() = elems.mkString("Stack(", ", ", ")")
 }
+
diff --git a/src/library/scala/collection/immutable/Stream.scala b/src/library/scala/collection/immutable/Stream.scala
new file mode 100644
index 0000000..b364a51
--- /dev/null
+++ b/src/library/scala/collection/immutable/Stream.scala
@@ -0,0 +1,679 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+package immutable
+
+import generic._
+import mutable.{Builder, StringBuilder, LazyBuilder, ListBuffer}
+import scala.annotation.tailrec
+
+
+
+/** The class `Stream` implements lazy lists where elements
+ *  are only evaluated when they are needed. Here is an example:
+ * 
+ *  {{{
+ *  object Main extends Application {
+ *    
+ *    def from(n: Int): Stream[Int] =
+ *      Stream.cons(n, from(n + 1))
+ *    
+ *    def sieve(s: Stream[Int]): Stream[Int] =
+ *      Stream.cons(s.head, sieve(s.tail filter { _ % s.head != 0 }))
+ *    
+ *    def primes = sieve(from(2))
+ *    
+ *    primes take 10 print
+ *  }
+ *  }}}
+ *  
+ *  @tparam A    the type of the elements contained in this stream.
+ *  
+ *  @author Martin Odersky, Matthias Zenger
+ *  @version 1.1 08/08/03
+ *  @since   2.8
+ *  @define Coll Stream
+ *  @define coll stream
+ *  @define orderDependent
+ *  @define orderDependentFold
+ */
+abstract class Stream[+A] extends LinearSeq[A] 
+                             with GenericTraversableTemplate[A, Stream]
+                             with LinearSeqOptimized[A, Stream[A]] {
+self =>
+  override def companion: GenericCompanion[Stream] = Stream
+
+  import scala.collection.{Traversable, Iterable, Seq, IndexedSeq}
+
+  /** is this stream empty? */
+  def isEmpty: Boolean
+
+  /** The first element of this stream 
+   *  @throws Predef.NoSuchElementException if the stream is empty.
+   */
+  def head: A
+
+  /** A stream consisting of the remaining elements of this stream after the first one.
+   *  @throws Predef.UnsupportedOperationException if the stream is empty.
+   */
+  def tail: Stream[A]
+
+  /** Is the tail of this stream defined? */
+  protected def tailDefined: Boolean
+
+  // Implementation of abstract method in Traversable
+
+  // New methods in Stream
+  
+  /** The stream resulting from the concatenation of this stream with the argument stream.
+   *  @param rest   The stream that gets appended to this stream
+   *  @return       The stream containing elements of this stream and the traversable object.
+   */
+  def append[B >: A](rest: => Traversable[B]): Stream[B] =
+    if (isEmpty) rest.toStream else new Stream.Cons(head, tail append rest)
+
+  /** Forces evaluation of the whole stream and returns it. */
+  def force: Stream[A] = {
+    var these = this
+    while (!these.isEmpty) these = these.tail
+    this
+  }
+
+  /** Prints elements of this stream one by one, separated by commas. */
+  def print() { print(", ") }
+
+  /** Prints elements of this stream one by one, separated by `sep`.
+   *  @param sep   The separator string printed between consecutive elements. 
+   */
+  def print(sep: String) {
+    def loop(these: Stream[A], start: String) {
+      Console.print(start)
+      if (these.isEmpty) Console.print("empty")
+      else { 
+        Console.print(these.head)
+        loop(these.tail, sep) 
+      }
+    }
+    loop(this, "")
+  }
+  
+  override def length: Int = {
+    var len = 0
+    var left = this
+    while (!left.isEmpty) {
+      len += 1
+      left = left.tail
+    }
+    len
+  }
+  
+  /** It's an imperfect world, but at least we can bottle up the
+   *  imperfection in a capsule.
+   */
+  @inline private def asThat[That](x: AnyRef): That     = x.asInstanceOf[That]
+  @inline private def asStream[B](x: AnyRef): Stream[B] = x.asInstanceOf[Stream[B]]
+
+  // Overridden methods from Traversable
+  
+  override def toStream: Stream[A] = this
+
+  override def hasDefiniteSize = {
+    def loop(s: Stream[A]): Boolean = s.isEmpty || s.tailDefined && loop(s.tail)
+    loop(this)
+  }
+
+  /** Create a new stream which contains all elements of this stream
+   *  followed by all elements of Traversable `that`.
+   *  @note It's subtle why this works. We know that if the target type
+   *  of the Builder That is either a Stream, or one of its supertypes, or undefined,
+   *  then StreamBuilder will be chosen for the implicit.
+   *  we recognize that fact and optimize to get more laziness. 
+   */
+  override def ++[B >: A, That](that: TraversableOnce[B])(implicit bf: CanBuildFrom[Stream[A], B, That]): That =
+    // we assume there is no other builder factory on streams and therefore know that That = Stream[A]
+    asThat[That](
+      if (isEmpty) that.toStream
+      else new Stream.Cons(head, asStream[A](tail ++ that))
+    )
+  
+  /**
+   * Create a new stream which contains all intermediate results of applying the operator
+   * to subsequent elements left to right.
+   * @note This works because the target type of the Builder That is a Stream.
+   */
+  override final def scanLeft[B, That](z: B)(op: (B, A) => B)(implicit bf: CanBuildFrom[Stream[A], B, That]): That =
+    asThat[That](
+      if (isEmpty) Stream(z)
+      else new Stream.Cons(z, asStream[B](tail.scanLeft(op(z, head))(op)))
+    )
+
+  /** Returns the stream resulting from applying the given function
+   *  `f` to each element of this stream.
+   *
+   *  @param f function to apply to each element.
+   *  @return  <code>f(a<sub>0</sub>), ..., f(a<sub>n</sub>)</code> if this
+   *           sequence is <code>a<sub>0</sub>, ..., a<sub>n</sub></code>.
+   */
+  override final def map[B, That](f: A => B)(implicit bf: CanBuildFrom[Stream[A], B, That]): That =
+    asThat[That](
+      if (isEmpty) Stream.Empty
+      else new Stream.Cons(f(head), asStream[B](tail map f))
+    )
+    
+  /** Applies the given function `f` to each element of
+   *  this stream, then concatenates the results.
+   *
+   *  @param f  the function to apply on each element.
+   *  @param bf $bfinfo
+   *  @return  <code>f(a<sub>0</sub>) ::: ... ::: f(a<sub>n</sub>)</code> if
+   *           this stream is <code>[a<sub>0</sub>, ..., a<sub>n</sub>]</code>.
+   */
+  override final def flatMap[B, That](f: A => Traversable[B])(implicit bf: CanBuildFrom[Stream[A], B, That]): That =
+    // we assume there is no other builder factory on streams and therefore know that That = Stream[B]
+    // optimisations are not for speed, but for functionality
+    // see tickets #153, #498, #2147, and corresponding tests in run/ (as well as run/stream_flatmap_odds.scala)
+    asThat[That](
+      if (isEmpty) Stream.Empty
+      else {
+        // establish !prefix.isEmpty || nonEmptyPrefix.isEmpty
+        var nonEmptyPrefix = this
+        var prefix = f(nonEmptyPrefix.head).toStream
+        while (!nonEmptyPrefix.isEmpty && prefix.isEmpty) {
+          nonEmptyPrefix = nonEmptyPrefix.tail
+          if(!nonEmptyPrefix.isEmpty)
+            prefix = f(nonEmptyPrefix.head).toStream
+        }
+
+        if (nonEmptyPrefix.isEmpty) Stream.empty
+        else prefix append asStream[B](nonEmptyPrefix.tail flatMap f)
+      }
+    )
+
+  /** Returns all the elements of this stream that satisfy the
+   *  predicate <code>p</code>. The order of the elements is preserved.
+   *
+   *  @param p the predicate used to filter the stream.
+   *  @return the elements of this stream satisfying <code>p</code>.
+   */
+  override def filter(p: A => Boolean): Stream[A] = {
+    // optimization: drop leading prefix of elems for which f returns false
+    // var rest = this dropWhile (!p(_)) - forget DRY principle - GC can't collect otherwise
+    var rest = this
+    while (!rest.isEmpty && !p(rest.head)) rest = rest.tail
+    // private utility func to avoid `this` on stack (would be needed for the lazy arg)
+    if (rest.nonEmpty) Stream.filteredTail(rest, p)
+    else Stream.Empty
+  }
+  
+  override final def withFilter(p: A => Boolean): StreamWithFilter = new StreamWithFilter(p)
+
+  /** A lazier implementation of WithFilter than TraversableLike's.
+   */
+  final class StreamWithFilter(p: A => Boolean) extends WithFilter(p) {    
+    
+    override def map[B, That](f: A => B)(implicit bf: CanBuildFrom[Stream[A], B, That]): That = {
+      def tailMap = asStream[B](tail withFilter p map f)
+      asThat[That](
+        if (isEmpty) Stream.Empty
+        else if (p(head)) new Stream.Cons(f(head), tailMap)
+        else tailMap
+      )
+    }
+    
+    override def flatMap[B, That](f: A => Traversable[B])(implicit bf: CanBuildFrom[Stream[A], B, That]): That = {
+      def tailFlatMap = asStream[B](tail withFilter p flatMap f) 
+      asThat[That](
+        if (isEmpty) Stream.Empty
+        else if (p(head)) f(head).toStream append tailFlatMap
+        else tailFlatMap
+      )
+    }
+
+    override def foreach[B](f: A => B) =
+      for (x <- self) 
+        if (p(x)) f(x)
+    
+    override def withFilter(q: A => Boolean): StreamWithFilter = 
+      new StreamWithFilter(x => p(x) && q(x))
+  }
+
+  /** Apply the given function <code>f</code> to each element of this linear sequence
+   *  (while respecting the order of the elements).
+   *
+   *  @param f the treatment to apply to each element.
+   *  @note  Overridden here as final to trigger tail-call optimization, which replaces
+   *         'this' with 'tail' at each iteration. This is absolutely necessary
+   *         for allowing the GC to collect the underlying stream as elements are
+   *         consumed.
+   */
+  @tailrec
+  override final def foreach[B](f: A => B) {
+    if (!this.isEmpty) {
+      f(head)
+      tail.foreach(f)
+    }
+  }
+  
+  /** Stream specialization of foldLeft which allows GC to collect
+   *  along the way.
+   */
+  @tailrec
+  override final def foldLeft[B](z: B)(op: (B, A) => B): B = {
+    if (this.isEmpty) z
+    else tail.foldLeft(op(z, head))(op)
+  }
+
+  /** Returns all the elements of this stream that satisfy the
+   *  predicate <code>p</code>. The order of the elements is preserved.
+   *
+   *  @param p the predicate used to filter the stream.
+   *  @return the elements of this stream satisfying <code>p</code>.
+   */
+  override def partition(p: A => Boolean): (Stream[A], Stream[A]) = (filter(p(_)), filterNot(p(_)))
+    
+  /** Returns a stream formed from this stream and the specified stream
+   *  <code>that</code> by associating each element of the former with
+   *  the element at the same position in the latter.
+   *  If one of the two streams is longer than the other, its remaining elements are ignored.
+   *
+   *  @return     <code>Stream({a<sub>0</sub>,b<sub>0</sub>}, ...,
+   *              {a<sub>min(m,n)</sub>,b<sub>min(m,n)</sub>)}</code> when
+   *              <code>Stream(a<sub>0</sub>, ..., a<sub>m</sub>)
+   *              zip Stream(b<sub>0</sub>, ..., b<sub>n</sub>)</code> is invoked.
+   */
+  override final def zip[A1 >: A, B, That](that: Iterable[B])(implicit bf: CanBuildFrom[Stream[A], (A1, B), That]): That =
+    // we assume there is no other builder factory on streams and therefore know that That = Stream[(A1, B)]
+    asThat[That](
+      if (this.isEmpty || that.isEmpty) Stream.Empty
+      else new Stream.Cons((this.head, that.head), asStream[(A1, B)](this.tail zip that.tail))
+    )
+
+  /** Zips this iterable with its indices. `s.zipWithIndex` is equivalent to 
+   *  `s zip s.indices`
+   */
+  override def zipWithIndex[A1 >: A, That](implicit bf: CanBuildFrom[Stream[A], (A1, Int), That]): That =
+    this.zip[A1, Int, That](Stream.from(0))
+  
+  /** Write all defined elements of this iterable into given string builder.
+   *  The written text begins with the string <code>start</code> and is finished by the string
+   *  <code>end</code>. Inside, the string representations of defined elements (w.r.t.
+   *  the method <code>toString()</code>) are separated by the string
+   *  <code>sep</code>. The method will not force evaluation of undefined elements. A
+   *  tail of such elements will be represented by a "?" instead.
+   */
+  override def addString(b: StringBuilder, start: String, sep: String, end: String): StringBuilder = {
+    def loop(pre: String, these: Stream[A]) {
+      if (these.isEmpty) b append end
+      else {
+        b append pre append these.head
+        if (these.tailDefined) loop(sep, these.tail)
+        else b append sep append "?" append end
+      }
+    }
+    b append start
+    loop("", this)
+    b
+  }
+
+  override def mkString(start: String, sep: String, end: String): String = {
+    this.force
+    super.mkString(start, sep, end)
+  }
+
+  override def mkString(sep: String): String = {
+    this.force
+    super.mkString(sep)
+  }
+
+  override def mkString: String = {
+    this.force
+    super.mkString
+  }
+
+  override def toString = super.mkString(stringPrefix + "(", ", ", ")")
+
+  /** Returns the <code>n</code> first elements of this stream, or else the whole 
+   *  stream, if it has less than <code>n</code> elements.
+   *
+   *  @param n the number of elements to take.
+   *  @return the <code>n</code> first elements of this stream.
+   */
+  override def take(n: Int): Stream[A] =
+    if (n <= 0 || isEmpty) Stream.Empty
+    else new Stream.Cons(head, if (n == 1) Stream.empty else tail take (n-1))
+  
+  override def splitAt(n: Int): (Stream[A], Stream[A]) = (take(n), drop(n))
+  
+  /** A substream starting at index `from`
+   *  and extending up to (but not including) index `until`.
+   *
+   *  @note This is equivalent to (but possibly more efficient than)
+   *  c.drop(from).take(to - from)
+   *
+   *  @param start   The index of the first element of the returned subsequence
+   *  @param end     The index of the element following the returned subsequence
+   *  @throws IndexOutOfBoundsException if <code>from < 0</code>
+   *          or <code>length < from + len<code>
+   *  @note  Might return different results for different runs, unless this iterable is ordered
+   */
+  override def slice(start: Int, end: Int): Stream[A] = {
+    var len = end
+    if (start > 0) len -= start
+    drop(start) take len
+  }
+
+  /** The stream without its last element.
+   *  @throws Predef.UnsupportedOperationException if the stream is empty.
+   */
+  override def init: Stream[A] =
+    if (isEmpty) super.init
+    else if (tail.isEmpty) Stream.Empty
+    else new Stream.Cons(head, tail.init)
+
+  /** Returns the rightmost <code>n</code> elements from this iterable.
+   *  @param n the number of elements to take
+   */
+  override def takeRight(n: Int): Stream[A] = {
+    var these: Stream[A] = this
+    var lead = this drop n
+    while (!lead.isEmpty) {
+      these = these.tail
+      lead = lead.tail
+    }
+    these
+  }
+
+  // there's nothing we can do about dropRight, so we just keep the definition in LinearSeq
+  
+  /** Returns the longest prefix of this stream whose elements satisfy
+   *  the predicate <code>p</code>.
+   *
+   *  @param p the test predicate.
+   */
+  override def takeWhile(p: A => Boolean): Stream[A] =
+    if (!isEmpty && p(head)) new Stream.Cons(head, tail takeWhile p) 
+    else Stream.Empty
+
+  /** Returns the longest suffix of this iterable whose first element
+   *  does not satisfy the predicate <code>p</code>.
+   *
+   *  @param p the test predicate.
+   */
+  override def dropWhile(p: A => Boolean): Stream[A] = {
+    var these: Stream[A] = this
+    while (!these.isEmpty && p(these.head)) these = these.tail
+    these
+  }
+
+  /** Builds a new stream from this stream in which any duplicates (wrt to ==) removed.
+   *  Among duplicate elements, only the first one is retained in the result stream
+   */
+  override def distinct: Stream[A] =
+    if (isEmpty) this
+    else new Stream.Cons(head, tail.filter(head !=).distinct)
+
+  /** Returns a new sequence of given length containing the elements of this sequence followed by zero
+   *  or more occurrences of given elements. 
+   */
+  override def padTo[B >: A, That](len: Int, elem: B)(implicit bf: CanBuildFrom[Stream[A], B, That]): That = {
+    def loop(len: Int, these: Stream[A]): Stream[B] = 
+      if (these.isEmpty) Stream.fill(len)(elem)
+      else new Stream.Cons(these.head, loop(len - 1, these.tail))
+    
+    asThat[That](loop(len, this))
+// was:    if (bf.isInstanceOf[Stream.StreamCanBuildFrom[_]]) loop(len, this).asInstanceOf[That] 
+//    else super.padTo(len, elem)
+  }
+
+  /** A list consisting of all elements of this list in reverse order.
+   */
+  override def reverse: Stream[A] = {
+    var result: Stream[A] = Stream.Empty
+    var these = this
+    while (!these.isEmpty) {
+      val r = Stream.consWrapper(result).#::(these.head)
+      r.tail // force it!
+      result = r
+      these = these.tail
+    }
+    result
+  }
+
+  override def flatten[B](implicit asTraversable: A => /*<:<!!!*/ Traversable[B]): Stream[B] = {
+    def flatten1(t: Traversable[B]): Stream[B] =
+      if (!t.isEmpty)
+        new Stream.Cons(t.head, flatten1(t.tail))
+      else
+        tail.flatten
+
+    if (isEmpty)
+      Stream.empty
+    else
+      flatten1(asTraversable(head))
+  }
+
+  /** Defines the prefix of this object's <code>toString</code> representation as ``Stream''.
+   */
+  override def stringPrefix = "Stream"
+}
+
+/**
+ * The object <code>Stream</code> provides helper functions
+ * to manipulate streams.
+ *
+ * @author Martin Odersky, Matthias Zenger
+ * @version 1.1 08/08/03
+ * @since   2.8
+ */
+object Stream extends SeqFactory[Stream] {
+  
+  /** The factory for streams.
+   *  @note Methods such as map/flatMap will not invoke the Builder factory,
+   *        but will return a new stream directly, to preserve laziness.
+   *        The new stream is then cast to the factory's result type.
+   *        This means that every CanBuildFrom that takes a
+   *        Stream as its From type parameter must yield a stream as its result parameter.
+   *        If that assumption is broken, cast errors might result.
+   */
+  class StreamCanBuildFrom[A] extends GenericCanBuildFrom[A]
+
+  implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, Stream[A]] = new StreamCanBuildFrom[A]
+  
+  /** Creates a new builder for a stream */
+  def newBuilder[A]: Builder[A, Stream[A]] = new StreamBuilder[A]
+
+  import scala.collection.{Iterable, Seq, IndexedSeq}
+
+  /** A builder for streams
+   *  @note This builder is lazy only in the sense that it does not go downs the spine
+   *        of traversables that are added as a whole. If more laziness can be achieved,
+   *        this builder should be bypassed.
+   */
+  class StreamBuilder[A] extends scala.collection.mutable.LazyBuilder[A, Stream[A]] {
+    def result: Stream[A] = parts.toStream flatMap (_.toStream)
+  }
+
+  object Empty extends Stream[Nothing] { 
+    override def isEmpty = true
+    override def head = throw new NoSuchElementException("head of empty stream")
+    override def tail = throw new UnsupportedOperationException("tail of empty stream")
+    def tailDefined = false
+  }
+
+  /** The empty stream */
+  override def empty[A]: Stream[A] = Empty
+
+  /** A stream consisting of given elements */
+  override def apply[A](xs: A*): Stream[A] = xs.toStream
+
+  /** A wrapper class that adds `#::` for cons and `#:::` for concat as operations
+   *  to streams.
+   */
+  class ConsWrapper[A](tl: => Stream[A]) {
+    def #::(hd: A): Stream[A] = new Stream.Cons(hd, tl)
+    def #:::(prefix: Stream[A]): Stream[A] = prefix append tl
+  }
+
+  /** A wrapper method that adds `#::` for cons and `#::: for concat as operations
+   *  to streams.
+   */
+  implicit def consWrapper[A](stream: => Stream[A]): ConsWrapper[A] = 
+    new ConsWrapper[A](stream)
+
+  /** An extractor that allows to pattern match streams with `#::`.
+   */
+  object #:: {
+    def unapply[A](xs: Stream[A]): Option[(A, Stream[A])] = 
+      if (xs.isEmpty) None
+      else Some((xs.head, xs.tail))
+  }
+
+  @deprecated("use #:: instead") lazy val lazy_:: = #::
+
+  /** An alternative way of building and matching Streams using Stream.cons(hd, tl).
+   */
+  object cons {
+
+    /** A stream consisting of a given first element and remaining elements 
+     *  @param hd   The first element of the result stream
+     *  @param tl   The remaining elements of the result stream
+     */
+    def apply[A](hd: A, tl: => Stream[A]) = new Cons(hd, tl)
+
+    /** Maps a stream to its head and tail */
+    def unapply[A](xs: Stream[A]): Option[(A, Stream[A])] = #::.unapply(xs)
+  }
+
+  /** A lazy cons cell, from which streams are built. */
+  @serializable @SerialVersionUID(-602202424901551803L)
+  final class Cons[+A](hd: A, tl: => Stream[A]) extends Stream[A] {
+    override def isEmpty = false
+    override def head = hd
+    @volatile private[this] var tlVal: Stream[A] = _
+    def tailDefined: Boolean = tlVal ne null
+    override def tail: Stream[A] = {
+      if (!tailDefined)
+        synchronized {
+          if (!tailDefined) tlVal = tl
+        }
+      
+      tlVal 
+    }
+  }
+
+  /** An infinite stream that repeatedly applies a given function to a start value.
+   *
+   *  @param start the start value of the stream
+   *  @param f     the function that's repeatedly applied
+   *  @return      the stream returning the infinite sequence of values `start, f(start), f(f(start)), ...`
+   */
+  def iterate[A](start: A)(f: A => A): Stream[A] = new Cons(start, iterate(f(start))(f))
+
+  override def iterate[A](start: A, len: Int)(f: A => A): Stream[A] =
+    iterate(start)(f) take len
+
+  /**
+   * Create an infinite stream starting at <code>start</code>
+   * and incrementing by step <code>step</code>
+   *
+   * @param start the start value of the stream
+   * @param step the increment value of the stream
+   * @return the stream starting at value <code>start</code>.
+   */
+  def from(start: Int, step: Int): Stream[Int] =
+    new Cons(start, from(start+step, step))
+
+  /**
+   * Create an infinite stream starting at <code>start</code>
+   * and incrementing by 1.
+   *
+   * @param start the start value of the stream
+   * @return the stream starting at value <code>start</code>.
+   */
+  def from(start: Int): Stream[Int] = from(start, 1)
+
+  /**
+   * Create an infinite stream containing the given element expression (which is computed for each
+   * occurrence)
+   *
+   * @param elem the element composing the resulting stream
+   * @return the stream containing an infinite number of elem
+   */
+  def continually[A](elem: => A): Stream[A] = new Cons(elem, continually(elem))
+
+  override def fill[A](n: Int)(elem: => A): Stream[A] = 
+    if (n <= 0) Empty else new Cons(elem, fill(n-1)(elem))
+
+  override def tabulate[A](n: Int)(f: Int => A): Stream[A] = {
+    def loop(i: Int): Stream[A] =
+      if (i >= n) Empty else new Cons(f(i), loop(i+1))
+    loop(0)
+  }
+
+  override def range(start: Int, end: Int, step: Int): Stream[Int] =
+    if (if (step < 0) start <= end else end <= start) Empty
+    else new Cons(start, range(start + step, end, step))
+  
+  private[immutable] def filteredTail[A](stream: Stream[A], p: A => Boolean) = {
+    new Stream.Cons(stream.head, stream.tail filter p)
+  }
+  
+  /** A stream containing all elements of a given iterator, in the order they are produced.
+   *  @param it   The iterator producing the stream's elements
+   */
+  @deprecated("use it.toStream instead")
+  def fromIterator[A](it: Iterator[A]): Stream[A] = it.toStream
+
+  /** The concatenation of a sequence of streams
+   */
+  @deprecated("use xs.flatten instead")
+  def concat[A](xs: Iterable[Stream[A]]): Stream[A] = concat(xs.iterator)
+  
+  /** The concatenation of all streams returned by an iterator
+   */
+  @deprecated("use xs.toStream.flatten instead")
+  def concat[A](xs: Iterator[Stream[A]]): Stream[A] = xs.toStream.flatten //(conforms[Stream[A], scala.collection.Traversable[A]])
+
+  /**
+   * Create a stream with element values
+   * <code>v<sub>n+1</sub> = step(v<sub>n</sub>)</code>
+   * where <code>v<sub>0</sub> = start</code>
+   * and elements are in the range between <code>start</code> (inclusive)
+   * and <code>end</code> (exclusive)
+   * @param start the start value of the stream
+   * @param end the end value of the stream
+   * @param step the increment function of the stream, must be monotonically increasing or decreasing
+   * @return the stream starting at value <code>start</code>.
+   */
+  @deprecated("use `iterate' instead.")
+  def range(start: Int, end: Int, step: Int => Int): Stream[Int] =
+    iterate(start, end - start)(step)
+
+  /**
+   * Create an infinite stream containing the given element.
+   *
+   * @param elem the element composing the resulting stream
+   * @return the stream containing an infinite number of elem
+   */
+  @deprecated("use `continually' instead")
+  def const[A](elem: A): Stream[A] = cons(elem, const(elem))
+
+  /** Create a stream containing several copies of an element.
+   *
+   *  @param n    the length of the resulting stream
+   *  @param elem the element composing the resulting stream
+   *  @return     the stream composed of n elements all equal to elem
+   */
+  @deprecated("use fill(n, elem) instead")
+  def make[A](n: Int, elem: A): Stream[A] = fill(n)(elem)
+}
+
+
diff --git a/src/library/scala/collection/immutable/StringLike.scala b/src/library/scala/collection/immutable/StringLike.scala
new file mode 100644
index 0000000..2a63fa4
--- /dev/null
+++ b/src/library/scala/collection/immutable/StringLike.scala
@@ -0,0 +1,274 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+package immutable
+
+import generic._
+import mutable.Builder
+import scala.util.matching.Regex
+import scala.math.ScalaNumber
+
+/** A companion object for the `StringLike` containing some constants.
+ *  @since 2.8
+ */
+object StringLike {
+
+  // just statics for companion class.
+  private final val LF: Char = 0x0A
+  private final val FF: Char = 0x0C
+  private final val CR: Char = 0x0D
+  private final val SU: Char = 0x1A
+}
+
+import StringLike._
+
+/** A trait describing stringlike collections.
+ *  
+ *  @tparam Repr   The type of the actual collection inheriting `StringLike`.
+ *  
+ *  @since 2.8
+ *  @define Coll String
+ *  @define coll string
+ *  @define orderDependent
+ *  @define orderDependentFold
+ *  @define mayNotTerminateInf
+ *  @define willNotTerminateInf
+ */
+trait StringLike[+Repr] extends IndexedSeqOptimized[Char, Repr] with Ordered[String] {
+self =>
+
+  /** Creates a string builder buffer as builder for this class */
+  protected[this] def newBuilder: Builder[Char, Repr]
+
+  /** Return element at index `n`
+   *  @throws   IndexOutofBoundsException if the index is not valid
+   */
+  def apply(n: Int): Char = toString charAt n
+
+  def length: Int = toString.length
+
+  override def mkString = toString
+
+  /** Return the current string concatenated `n` times.
+   */
+  def * (n: Int): String = {
+    val buf = new StringBuilder
+    for (i <- 0 until n) buf append toString
+    buf.toString
+  }
+
+  override def compare(other: String) = toString compareTo other
+
+  private def isLineBreak(c: Char) = c == LF || c == FF
+  
+  /**
+   *  Strip trailing line end character from this string if it has one.
+   *  
+   *  A line end character is one of
+   *  <ul style="list-style-type: none;">
+   *    <li>LF - line feed   (0x0A hex)</li>
+   *    <li>FF - form feed   (0x0C hex)</li>
+   *  </ul>
+   *  If a line feed character LF is preceded by a carriage return CR
+   *  (0x0D hex), the CR character is also stripped (Windows convention).
+   */
+  def stripLineEnd: String = {
+    val len = toString.length
+    if (len == 0) toString
+    else {
+      val last = apply(len - 1)
+      if (isLineBreak(last))
+        toString.substring(0, if (last == LF && len >= 2 && apply(len - 2) == CR) len - 2 else len - 1)
+      else 
+        toString
+    }
+  }
+  
+  /**
+   *    Return all lines in this string in an iterator, including trailing
+   *    line end characters.
+   * 
+   *    The number of strings returned is one greater than the number of line
+   *    end characters in this string. For an empty string, a single empty
+   *    line is returned. A line end character is one of
+   * 
+   *    <ul style="list-style-type: none;">
+   *      <li>LF - line feed   (0x0A hex)</li>
+   *      <li>FF - form feed   (0x0C hex)</li>
+   *    </ul>
+   */
+  def linesWithSeparators: Iterator[String] = new Iterator[String] {
+    val str = self.toString
+    private val len = str.length
+    private var index = 0
+    def hasNext: Boolean = index < len
+    def next(): String = {
+      if (index >= len) throw new NoSuchElementException("next on empty iterator")
+      val start = index
+      while (index < len && !isLineBreak(apply(index))) index += 1
+      index += 1
+      str.substring(start, index min len)
+    }
+  }
+
+  /** Return all lines in this string in an iterator, excluding trailing line
+   *  end characters, i.e. apply `.stripLineEnd` to all lines
+   *  returned by `linesWithSeparators`.
+   */
+  def lines: Iterator[String] = 
+    linesWithSeparators map (line => new WrappedString(line).stripLineEnd)
+
+  /** Return all lines in this string in an iterator, excluding trailing line
+   *  end characters, i.e. apply `.stripLineEnd` to all lines
+   *  returned by `linesWithSeparators`.
+   */
+  def linesIterator: Iterator[String] = 
+    linesWithSeparators map (line => new WrappedString(line).stripLineEnd)
+
+  /** Returns this string with first character converted to upper case */
+  def capitalize: String =
+    if (toString == null) null
+    else if (toString.length == 0) ""
+    else {
+      val chars = toString.toCharArray
+      chars(0) = chars(0).toUpper
+      new String(chars)
+    }
+
+  /** Returns this string with the given `prefix` stripped. */
+  def stripPrefix(prefix: String) =
+    if (toString.startsWith(prefix)) toString.substring(prefix.length)
+    else toString
+
+  /** Returns this string with the given `suffix` stripped. If this string does not
+    * end with `suffix`, it is returned unchanged. */
+  def stripSuffix(suffix: String) =
+    if (toString.endsWith(suffix)) toString.substring(0, toString.length() - suffix.length)
+    else toString
+
+  /** 
+   *    For every line in this string:
+   * 
+   *    <blockquote>
+   *       Strip a leading prefix consisting of blanks or control characters
+   *       followed by `marginChar` from the line.
+   *    </blockquote>
+   */
+  def stripMargin(marginChar: Char): String = {
+    val buf = new StringBuilder
+    for (line <- linesWithSeparators) {
+      val len = line.length
+      var index = 0
+      while (index < len && line.charAt(index) <= ' ') index += 1
+      buf append
+        (if (index < len && line.charAt(index) == marginChar) line.substring(index + 1) else line)
+    }
+    buf.toString
+  }
+
+  /** 
+   *    For every line in this string:
+   *  
+   *    <blockquote>
+   *       Strip a leading prefix consisting of blanks or control characters
+   *       followed by `|` from the line.
+   *    </blockquote>
+   */
+  def stripMargin: String = stripMargin('|')
+
+  private def escape(ch: Char): String = "\\Q" + ch + "\\E"
+
+  @throws(classOf[java.util.regex.PatternSyntaxException])
+  def split(separator: Char): Array[String] = toString.split(escape(separator))
+
+  @throws(classOf[java.util.regex.PatternSyntaxException])
+  def split(separators: Array[Char]): Array[String] = {
+    val re = separators.foldLeft("[")(_+escape(_)) + "]"
+    toString.split(re)
+  }
+
+  /** You can follow a string with `.r', turning
+   *  it into a Regex. E.g.
+   *
+   *  """A\w*""".r   is the regular expression for identifiers starting with `A'.
+   */
+  def r: Regex = new Regex(toString)
+  
+  def toBoolean: Boolean = parseBoolean(toString)
+  def toByte: Byte       = java.lang.Byte.parseByte(toString)
+  def toShort: Short     = java.lang.Short.parseShort(toString)
+  def toInt: Int         = java.lang.Integer.parseInt(toString)
+  def toLong: Long       = java.lang.Long.parseLong(toString)
+  def toFloat: Float     = java.lang.Float.parseFloat(toString)
+  def toDouble: Double   = java.lang.Double.parseDouble(toString)
+
+  private def parseBoolean(s: String): Boolean =
+    if (s != null) s.toLowerCase match {
+      case "true" => true
+      case "false" => false
+      case _ => throw new NumberFormatException("For input string: \""+s+"\"")
+    }
+    else
+      throw new NumberFormatException("For input string: \"null\"")
+
+  /* !!! causes crash?
+  def toArray: Array[Char] = {
+    val result = new Array[Char](length)
+    toString.getChars(0, length, result, 0)
+    result
+  }
+  */
+
+  private def unwrapArg(arg: Any): AnyRef = arg match {
+    case x: ScalaNumber => x.underlying
+    case x              => x.asInstanceOf[AnyRef]
+  }
+
+  /**
+   *  Uses the underlying string as a pattern (in a fashion similar to
+   *  printf in C), and uses the supplied arguments to fill in the
+   *  holes.
+   *
+   *    The interpretation of the formatting patterns is described in
+   *    <a href="" target="contentFrame" class="java/util/Formatter">
+   *    `java.util.Formatter`</a>, with the addition that
+   *    classes deriving from `ScalaNumber` (such as `scala.BigInt` and
+   *    `scala.BigDecimal`) are unwrapped to pass a type which `Formatter`
+   *    understands.
+   *
+   *
+   *  @param args the arguments used to instantiating the pattern.
+   *  @throws java.lang.IllegalArgumentException
+   */
+  def format(args : Any*): String =
+    java.lang.String.format(toString, args map unwrapArg: _*)
+
+  /** 
+   *  Like `format(args*)` but takes an initial `Locale` parameter
+   *  which influences formatting as in `java.lang.String`'s format.
+   *  
+   *  
+   *    The interpretation of the formatting patterns is described in
+   *    <a href="" target="contentFrame" class="java/util/Formatter">
+   *    `java.util.Formatter`</a>, with the addition that
+   *    classes deriving from `ScalaNumber` (such as `scala.BigInt` and
+   *    `scala.BigDecimal`) are unwrapped to pass a type which `Formatter`
+   *    understands.
+   *  
+   *
+   *  @param locale an instance of `java.util.Locale`
+   *  @param args the arguments used to instantiating the pattern.
+   *  @throws java.lang.IllegalArgumentException
+   */
+  def formatLocal(l: java.util.Locale, args: Any*): String =
+    java.lang.String.format(l, toString, args map unwrapArg: _*)
+}
+
diff --git a/src/library/scala/collection/immutable/StringOps.scala b/src/library/scala/collection/immutable/StringOps.scala
new file mode 100644
index 0000000..c9dfcb0
--- /dev/null
+++ b/src/library/scala/collection/immutable/StringOps.scala
@@ -0,0 +1,51 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+package immutable
+
+import mutable.StringBuilder
+
+/**
+ *  This class serves as a wrapper providing `String`s with all the operations
+ *  found in indexed sequences. Where needed, instances of `String` object
+ *  are implicitly converted into this class.
+ *  
+ *  The difference between this class and `WrappedString` is that calling transformer
+ *  methods such as `filter` and `map` will yield a `String` object, whereas a 
+ *  `WrappedString` will remain a `WrappedString`.
+ *  
+ *  @param repr     the actual representation of this string operations object.
+ *  
+ *  @since 2.8
+ *  @define Coll StringOps
+ *  @define coll string
+ */
+final class StringOps(override val repr: String) extends StringLike[String] {
+
+  override protected[this] def thisCollection: WrappedString = new WrappedString(repr)
+  override protected[this] def toCollection(repr: String): WrappedString = new WrappedString(repr)
+
+  /** Creates a string builder buffer as builder for this class */
+  override protected[this] def newBuilder = new StringBuilder
+  
+  override def slice(from: Int, until: Int): String = {
+    /** Slice must be forgiving on all out of bounds indices and
+     *  substring is not.
+     */
+    val start = from max 0
+    val end   = until min repr.length
+    
+    if (start >= end) ""
+    else repr.substring(start, end)
+  }
+
+  override def toString = repr
+}  
diff --git a/src/library/scala/collection/immutable/Traversable.scala b/src/library/scala/collection/immutable/Traversable.scala
new file mode 100644
index 0000000..819a2c6
--- /dev/null
+++ b/src/library/scala/collection/immutable/Traversable.scala
@@ -0,0 +1,36 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+package immutable
+
+import generic._
+import mutable.Builder
+
+/** A trait for traversable collections that are guaranteed immutable.
+ *  $traversableInfo
+ *  @define mutability immutable
+ */
+trait Traversable[+A] extends scala.collection.Traversable[A] 
+                         with GenericTraversableTemplate[A, Traversable] 
+                         with TraversableLike[A, Traversable[A]]
+                         with Immutable { 
+  override def companion: GenericCompanion[Traversable] = Traversable
+}
+
+/** $factoryInfo
+ *  The current default implementation of a $Coll is a `Vector`.
+ *  @define coll immutable traversable collection
+ *  @define Coll immutable.Traversable
+ */
+object Traversable extends TraversableFactory[Traversable] {
+  implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, Traversable[A]] = new GenericCanBuildFrom[A]
+  def newBuilder[A]: Builder[A, Traversable[A]] = new mutable.ListBuffer
+}
diff --git a/src/library/scala/collection/immutable/Tree.scala b/src/library/scala/collection/immutable/Tree.scala
deleted file mode 100644
index 5e14a11..0000000
--- a/src/library/scala/collection/immutable/Tree.scala
+++ /dev/null
@@ -1,439 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: Tree.scala 16894 2009-01-13 13:09:41Z cunei $
-
-/* General Balanced Trees - highly efficient functional dictionaries.
-**
-** This is a scala version of gb_trees.erl which is
-** copyrighted (C) 1999-2001 by Sven-Olof Nystrom, and Richard Carlsson
-**
-** An efficient implementation of Prof. Arne Andersson's General
-** Balanced Trees. These have no storage overhead compared to plain
-** unbalanced binary trees, and their performance is in general better
-** than AVL trees.
-**
-** NOTE: This code was until 2007-04-01 under a GPL license. The author has
-** given permission to remove that license, so that now this code is under
-** the general license for the Scala libraries. 
-*/
-
-package scala.collection.immutable
-
-
-//import Predef.NoSuchElementException
-
-/** <p>
- *    General Balanced Trees - highly efficient functional dictionaries.
- *  </p>
- *  <p>
- *    An efficient implementation of Prof. Arne Andersson's
- *    <a href="http://citeseer.ist.psu.edu/andersson99general.html"
- *    target="_top">General Balanced Trees</a>. These have no storage overhead
- *    compared to plain unbalanced binary trees, and their performance is in
- *    general better than AVL trees.
- *  </p>
- *  <p>
- *    This implementation does not balance the trees after deletions.
- *    Since deletions don't increase the height of a tree, this should
- *    be OK in most applications. A balance method is provided for those
- *    cases where rebalancing is needed.
- *  </p>
- *  <p>
- *    The tree consists of entries conatining a key with an order.
- *  </p>
- *  <p>
- *    When instanciating the tree an order for the keys has to be
- *    supplied.
- *  </p>
- *
- *  @author  Erik Stenman, Michel Schinz
- *  @version 1.1, 2005-01-20
- */
-
- at serializable
-abstract class Tree[A <% Ordered[A], B]() extends AnyRef {
-  /* Data structure:
-  ** - size:Int - the number of elements in the tree.
-  ** - tree:T, which is composed of nodes of the form:
-  **   - GBNode(key: A, entry:B, smaller:T, bigger:T),
-  **   - and the "empty tree" node GBLeaf.
-  **
-  ** Original balance condition h(T) <= ceil(c * log(|T|)) has been
-  ** changed to the similar (but not quite equivalent) condition
-  ** 2 ^ h(T) <= |T| ^ c.
-  **
-  */
-
-  /** The type returned when creating a new tree.
-   *  This type should be defined by concrete implementations
-   *  e.g. <pre>
-   *  class C[T](...) extends Tree[A,B](...) {
-   *    type This = C[T];
-   *  </pre>
-   */
-  protected type This <: Tree[A,B]
-  protected def getThis: This
-
-  /**
-   *  The type of nodes that the tree is build from.
-   */
-  protected type aNode = GBTree[A,B]
-
-  /** The nodes in the tree.
-   */
-  protected def tree: aNode = GBLeaf[A,B]()
-
-  /** <p>
-   *    This abstract method should be defined by a concrete implementation
-   *    <code>C[T]</code> as something like:
-   *  </p>
-   *  <pre>
-   *    <b>override def</b> New(sz: Int, t: aNode): This {
-   *      <b>new</b> C[T](order) {
-   *        <b>override def</b> size = sz
-   *        <b>override protected def</b> tree: aNode = t
-   *    }
-   *  </pre>
-   *  <p>
-   *     The concrete implementation should also override the def of This
-   *     <code>override type This = C[T];</code>
-   *  </p>
-   */
-  protected def New(sz: Int, t: aNode): This
-
-  /** The size of the tree, returns 0 (zero) if the tree is empty.
-   *
-   *  @return The number of nodes in the tree as an integer.
-   */
-  def size: Int = 0
-
-  /** A new tree with the entry added is returned,
-   *  assuming that key is <em>not</em> in the tree.
-   *
-   *  @param key   ...
-   *  @param entry ...
-   *  @return      ...
-   */
-  protected def add(key: A, entry: B): This = {
-    val newSize = size + 1
-    New(newSize, tree.insert(key, entry, newSize * newSize).node)
-  }
-
-  /** A new tree with the entry added is returned,
-   *  if key is <em>not</em> in the tree, otherwise
-   *  the key is updated with the new entry.
-   */
-  protected def updateOrAdd(key: A, entry: B): This =
-    if (tree.isDefinedAt(key))
-      New(size,tree.update(key,entry))
-    else
-      add(key,entry)
-
-  /** Removes the key from the tree.
-   *
-   *  @param key ...
-   *  @return    ...
-   */
-  protected def deleteAny(key: A): This =
-    if (tree.isDefinedAt(key))
-      delete(key)
-    else
-      getThis
-
-  /** Removes the key from the tree, assumimg that key is present.
-   *
-   *  @param key ...
-   *  @return    ...
-   */
-  private def delete(key: A): This =
-    New(size - 1, tree.delete(key))
-
-  /** Check if this map maps <code>key</code> to a value and return the
-   *  value if it exists.
-   *
-   *  @param  key the key of the mapping of interest
-   *  @return     the value of the mapping, if it exists
-   */
-  protected def findValue(key: A): Option[B] =
-    tree.get(key)
-
-  /** Gives you an iterator over all elements in the tree.
-   *  The iterator structure corresponds to
-   *  the call stack of an in-order traversal.
-   *
-   *  Note: The iterator itself has a state, i.e., it is not functional.
-   */
-  protected def entries: Iterator[B] =
-    new Iterator[B] {
-      var iter = tree.mk_iter(scala.Nil)
-      def hasNext = !iter.isEmpty
-      def next = iter match {
-        case GBNode(_,v,_,t)::iter_tail =>
-          iter = t.mk_iter(iter_tail)
-          v
-        case scala.Nil =>
-          throw new NoSuchElementException("next on empty iterator")
-      }
-    }
-
-  /** Create a new balanced tree from the tree. Might be useful to call
-   *  after many deletions, since deletion does not rebalance the tree.
-   */
-  def balance: This =
-    New(size, tree.balance(size))
-}
-
-protected abstract class InsertTree[A <% Ordered[A],B]() extends AnyRef {
-  def insertLeft(k: A, v: B, t: GBTree[A,B]): InsertTree[A,B]
-  def insertRight(k: A, v: B, t: GBTree[A,B]): InsertTree[A,B]
-  def node: GBTree[A,B]
-}
-
-/**
- *  <code>ITree</code> is an internal class used by
- *  <a href="Tree.html" target="contentFrame"><code>Tree</code></a>.
- */
-private case class ITree[A <% Ordered[A],B](t: GBTree[A,B])
-             extends InsertTree[A,B] {
-  def insertLeft(key: A, value: B, bigger: GBTree[A,B]) =
-    ITree(GBNode(key, value, t, bigger))
-  def insertRight(key: A, value: B, smaller: GBTree[A,B]) =
-    ITree(GBNode(key, value, smaller, t))
-  def node = t
-}
-
-/**
- *  <code>INode</code> is an internal class used by
- *  <a href="Tree.html" target="contentFrame"><code>Tree</code></a>.
- */
-private case class INode[A <% Ordered[A],B](t1: GBTree[A,B],
-                                            height: Int,
-                                            size: Int)
-             extends InsertTree[A,B] {
-  def insertLeft(key: A, value: B, bigger: GBTree[A,B]) =
-    balance_p(GBNode(key, value, t1, bigger), bigger);
-  def insertRight(key: A, value: B, smaller: GBTree[A,B]) =
-    balance_p(GBNode(key, value, smaller, t1),smaller);
-  protected def balance_p(t:GBTree[A,B],subtree:GBTree[A,B]):InsertTree[A,B] = {
-    val (subHeight, subSize) = subtree.count
-    val totalHeight = 2 * Math.max(height, subHeight)
-    val totalSize = size + subSize + 1
-    val BalanceHeight = totalSize * totalSize
-    if (totalHeight > BalanceHeight) ITree(t.balance(totalSize))
-    else INode(t, totalHeight, totalSize)
-  }
-  def node = t1
-}
-
-/**
- *  <code>GBTree</code> is an internal class used by
- *  <a href="Tree.html" target="contentFrame"><code>Tree</code></a>.
- *
- *  @author  Erik Stenman
- *  @version 1.0, 2005-01-20
- */
- at serializable
-protected abstract class GBTree[A <% Ordered[A],B] extends AnyRef {
-  type aNode = GBTree[A,B]
-  type anInsertTree = InsertTree[A,B]
-
-  /** Calculates 2^h, and size, where h is the height of the tree
-  *   and size is the number of nodes in the tree.
-  */
-  def count: (Int,Int)
-  def isDefinedAt(Key: A): Boolean
-  def get(key: A): Option[B]
-  def apply(key: A): B
-  def update(key: A, value: B): aNode
-  def insert(key: A, value: B, size: Int): anInsertTree
-  def toList(acc: List[(A,B)]): List[(A,B)]
-  def mk_iter(iter_tail: List[aNode]): List[aNode]
-  def delete(key: A): aNode
-  def merge(t: aNode): aNode
-  def takeSmallest: (A,B,aNode)
-  def balance(s: Int): GBTree[A,B]
-}
-
-private case class GBLeaf[A <% Ordered[A],B]() extends GBTree[A,B] {
-  def count = (1, 0)
-  def isDefinedAt(key: A) = false
-  def get(_key: A) = None
-  def apply(key: A) = throw new NoSuchElementException("key " + key + " not found")
-  def update(key: A, value: B) = throw new NoSuchElementException("key " + key + " not found")
-  def insert(key: A, value: B, s: Int): anInsertTree = {
-    if (s == 0)
-      INode(GBNode(key, value, this, this), 1, 1)
-    else
-      ITree(GBNode(key, value, this, this))
-  }
-  def toList(acc: List[(A,B)]): List[(A,B)] = acc
-  def mk_iter(iter_tail: List[GBTree[A,B]]) = iter_tail
-  def merge(larger: GBTree[A,B]) = larger
-  def takeSmallest: (A,B, GBTree[A,B]) =
-    throw new NoSuchElementException("takeSmallest on empty tree")
-  def delete(_key: A) = throw new NoSuchElementException("Delete on empty tree.")
-  def balance(s: Int) = this
-  override def hashCode() = 0
-}
-
-private case class GBNode[A <% Ordered[A],B](key: A,
-                                             value: B,
-                                             smaller: GBTree[A,B],
-                                             bigger: GBTree[A,B])
-             extends GBTree[A,B] {
-  def count: (Int,Int) = {
-    val (sHeight, sSize) = smaller.count
-    val (bHeight, bSize) = bigger.count
-    val mySize = sSize + bSize + 1
-    if (mySize == 1)
-      (1, mySize)
-    else
-      (2 * Math.max(sHeight, bHeight), mySize)
-  }
-
-  def isDefinedAt(sKey: A): Boolean =
-    if (sKey < key) smaller.isDefinedAt(sKey)
-    else if (sKey > key) bigger.isDefinedAt(sKey)
-    else true
-
-  def get(sKey: A): Option[B] =
-    if (sKey < key) smaller.get(sKey)
-    else if (sKey > key) bigger.get(sKey)
-    else Some(value)
-
-  def apply(sKey: A): B =
-    if (sKey < key) smaller.apply(sKey)
-    else if (sKey > key) bigger.apply(sKey)
-    else value
-
-  def update(newKey: A, newValue: B): aNode =
-    if (newKey < key)
-      GBNode(key, value, smaller.update(newKey,newValue), bigger)
-    else if (newKey > key)
-      GBNode(key, value, smaller, bigger.update(newKey,newValue))
-    else
-      GBNode(newKey, newValue, smaller, bigger)
-
-  def insert(newKey: A, newValue: B, s: Int): anInsertTree = {
-    if (newKey < key)
-      smaller.insert(newKey, newValue, s / 2).insertLeft(key, value, bigger)
-    else if (newKey > key)
-      bigger.insert(newKey, newValue, s / 2).insertRight(key, value, smaller)
-    else
-      throw new NoSuchElementException("Key exists: " + newKey)
-  }
-
-  def toList(acc: List[(A,B)]): List[(A,B)] =
-    smaller.toList((key, value) :: bigger.toList(acc))
-
-  def mk_iter(iter_tail:List[aNode]):List[aNode] =
-    smaller.mk_iter(this :: iter_tail)
-
-  def delete(sKey:A):aNode = {
-    if (sKey < key)
-      GBNode(key, value, smaller.delete(sKey), bigger)
-    else if (sKey > key)
-      GBNode(key, value, smaller, bigger.delete(sKey))
-    else
-      smaller.merge(bigger)
-  }
-
-  def merge(larger: aNode): GBTree[A,B] = larger match {
-    case GBLeaf() =>
-      this
-    case _ =>
-      val (key1, value1, larger1) = larger.takeSmallest
-      GBNode(key1, value1, this, larger1)
-  }
-
-  def takeSmallest: (A, B, aNode) = smaller match {
-    case GBLeaf() =>
-      (key, value, bigger)
-    case _ =>
-      val (key1, value1, smaller1) = smaller.takeSmallest
-      (key1, value1, GBNode(key, value, smaller1, bigger))
-  }
-
-  /**
-   *  @param s ...
-   *  @return  ...
-   */
-  def balance(s: Int): GBTree[A,B] =
-    balance_list(toList(scala.Nil), s)
-
-  protected def balance_list(list: List[(A,B)], s: Int): GBTree[A,B] = {
-    val empty = GBLeaf[A,B]();
-    def bal(list: List[(A,B)], s: Int): (aNode, List[(A,B)]) = {
-      if (s > 1) {
-        val sm = s - 1
-        val s2 = sm / 2
-        val s1 = sm - s2
-        val (t1, (k, v) :: l1) = bal(list, s1)
-        val (t2, l2) = bal(l1, s2)
-        val t = GBNode(k, v, t1, t2)
-        (t, l2)
-      } else if (s == 1) {
-        val (k,v) :: rest = list
-        (GBNode(k, v, empty, empty), rest)
-      } else
-        (empty, list)
-    }
-    bal(list, s)._1
-  }
-
-  override def hashCode() =
-    value.hashCode() + smaller.hashCode() + bigger.hashCode()
-}
-
-/* Here is the e-mail where the Author agreed to the change in license.
-
-from	Erik Stenman <happi.stenman at gmail.com>
-to	martin odersky <martin.odersky at epfl.ch>,
-date	Tue, Apr 29, 2008 at 3:31 PM
-subject	Re: test
-mailed-by	chara.epfl.ch
-signed-by	gmail.com
-	
-Hi Martin,
-
-I am fine with that change, and since I don't have a scala distribution handy,
-I am also fine with you doing the change yourself. Is that OK?
-
-Sorry for my dead home address, I'll add an English response to it at some time.
-
-I am doing fine, and my family is also doing fine.
-Hope all is well with you too.
-
-Cheers,
-Erik
-- Hide quoted text -
-
-On Tue, Apr 29, 2008 at 3:13 PM, martin odersky <martin.odersky at epfl.ch> wrote:
-
-    Hi Erik,
-
-    I tried to send mail to happi at home.se, but got a response n swedish. I
-    was sort of guessing from the response that it contained an
-    alternative e-mail address and tried to send it there.
-
-    Anyway,  I hope things are going well with you!
-
-    There was some discussion recently about the license of Tree.scala in
-    package collection.immutable. It's GPL, whereas the rest of the Scala
-    library is BSD. It seems this poses problems with Scala being packaged
-    with Fedora. Would it be OK with you to change the license to the
-    general one of Scala libraries? You could simply remove the references
-    to the GPL
-    license in the code and send it back to me if that's OK with you. On
-    the other hand, if there's a problem we'll try something else instead.
-
-    All the best
-
-     -- Martin
-*/
diff --git a/src/library/scala/collection/immutable/TreeHashMap.scala b/src/library/scala/collection/immutable/TreeHashMap.scala
index 449672e..14a671d 100644
--- a/src/library/scala/collection/immutable/TreeHashMap.scala
+++ b/src/library/scala/collection/immutable/TreeHashMap.scala
@@ -1,13 +1,19 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2008, David MacIver              **
+**    / __/ __// _ | / /  / _ |    (c) 2008-2009, David MacIver         **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: $
-package scala.collection.immutable;
+
+package scala.collection
+package immutable
+
+// A dummy to fool ant until reintegration.
+class TreeHashMap
+
+/* TODO: Reintegrate
 
 object TreeHashMap {
   private[TreeHashMap] val _empty = new TreeHashMap[Any, Nothing](IntMap.empty[Nothing]);
@@ -33,8 +39,8 @@ object TreeHashMap {
  * 
  * @author David MacIver
  */
-class TreeHashMap[Key, +Value] private (private val underlying : IntMap[AssocMap[Key, Value]]) extends scala.collection.immutable.Map[Key, Value]{
-  def elements : Iterator[(Key, Value)] = new Iterator[(Key, Value)]{
+class TreeHashMap[Key, +Value] private (private val underlying : IntMap[AssocMap[Key, Value]]) extends Map[Key, Value]{
+  def iterator : Iterator[(Key, Value)] = new Iterator[(Key, Value)]{
     val assocIt = new AssocMapIterator(AssocMap.empty[Key, Value]);
     val intIterator = underlying.values;
 
@@ -45,29 +51,19 @@ class TreeHashMap[Key, +Value] private (private val underlying : IntMap[AssocMap
     }
   }
 
-  def empty[V] = TreeHashMap.empty[Key, V];
+  def empty[V] = TreeHashMap.empty[Key, V]
  
-  private def hash(key : Key) =  {
-    var h = key.hashCode;
+  private def hash(key : Key) = {
+    var h = key.##
     h ^= ((h >>> 20) ^ (h >>> 12));
     h ^ (h >>> 7) ^ (h >>> 4);
   }
 
-  override def stringPrefix="TreeHashMap"  
+  override def stringPrefix = "TreeHashMap"  
 
   override lazy val size = underlying.values.foldLeft(0)((x, y) => x + y.size);
-
-  override def equals(that : Any) = that match {
-    case (that : TreeHashMap[_, _]) => 
-      if (this eq that) true 
-      else if (this.size != that.size) false;
-      else this.underlying == that.underlying;
-    case _ => false;
-  }
-
-  override def hashCode = underlying.hashCode;
-
-  override def foreach(f : ((Key, Value)) => Unit) = underlying.foreachValue(_.foreach(f));     
+  
+  override def foreach[U](f : ((Key, Value)) =>  U) = underlying.foreachValue(_.foreach(f));     
 
   override def toList : List[(Key, Value)] = {
     val buffer = new scala.collection.mutable.ListBuffer[(Key, Value)];
@@ -131,23 +127,24 @@ class TreeHashMap[Key, +Value] private (private val underlying : IntMap[AssocMap
 }
 
 
-private [collection] object AssocMap{
-  val _empty = Nil[Any];
+private [collection] object AssocMap {
+  val _empty = Nil[Any]
   def empty[Key, Value] : AssocMap[Key, Value] = _empty.asInstanceOf[AssocMap[Key, Value]]
   def singleton[Key, Value](key : Key, value : Value) = Cons(key, value, empty);
   def apply[Key, Value](maps : (Key, Value)*) = 
     maps.foldLeft(empty[Key, Value])((x, y) => x.update(y._1, y._2));
 
-  private[collection] case class Nil[Key] extends AssocMap[Key, Nothing];
-  private[collection] case class Cons[S, +T](key : S, value : T, tail : AssocMap[S, T]) extends AssocMap[S, T]
+  private[collection] case class Nil[Key]() extends AssocMap[Key, Nothing]
+  private[collection] case class Cons[S, +T](key: S, value: T, tail: AssocMap[S, T]) extends AssocMap[S, T]
 }
 
-import AssocMap._;
+import AssocMap._
 
-// AssocMap is very similar to ListMap. I don't want to patch ListMap right now, so I've got a separate
-// implementation here to make tweaks to. Long term any of these changes should be merged into ListMap
-// Short term it doesn't really matter because there are almost no viable use cases for ListMap compared
-// to one of the alternatives.
+// AssocMap is very similar to ListMap. I don't want to patch ListMap right
+// now, so I've got a separate implementation here to make tweaks to. Long
+// term any of these changes should be merged into ListMap
+// Short term it doesn't really matter because there are almost no viable
+// use cases for ListMap compared to one of the alternatives.
 private[collection] sealed abstract class AssocMap[Key, +Value] extends immutable.Map[Key, Value]{
   def empty[V] = AssocMap.empty[Key, V]
 
@@ -177,9 +174,11 @@ private[collection] sealed abstract class AssocMap[Key, +Value] extends immutabl
     case Nil() => AssocMap.empty;
   }
 
-  def elements : Iterator[(Key, Value)] = new AssocMapIterator(this);
+  def iterator : Iterator[(Key, Value)] = new AssocMapIterator(this)
+
+  @deprecated("use `iterator' instead") def elements = iterator
 
-  override final def foreach(f : ((Key, Value)) => Unit) = this match {
+  override final def foreach[U](f : ((Key, Value)) =>  U) = this match {
     case Cons(key, value, tail) => { f((key, value)); tail.foreach(f); }
     case Nil() => {}
   }
@@ -216,15 +215,6 @@ private[collection] sealed abstract class AssocMap[Key, +Value] extends immutabl
       }
   }
 
-  override def equals(that : Any) = 
-    if (this eq that.asInstanceOf[AnyRef]) true;
-    else that match {
-      case (that : AssocMap[_, _]) => 
-        if (this.size != that.size) false;
-        else this.sameMappings(that); 
-      case _ => false;
-    } 
-
   final def merge[S >: Value](that : AssocMap[Key, S]) : AssocMap[Key, S] = (this, that) match {
     case (Nil(), that) => that;
     case (_, Nil()) => this;
@@ -239,14 +229,14 @@ private[collection] sealed abstract class AssocMap[Key, +Value] extends immutabl
       else Cons(key2, value2, tail.update(key, value));
   }  
 
-  override def transform[C](f : (Key, Value) => C) : AssocMap[Key, C] = this match {
-    case Nil() => AssocMap.empty[Key, C];
-    case Cons(key, value, tail) => {
-      val newtail = tail.transform(f);
-      val newval = f(key, value);
+  override def transform[C](f: (Key, Value) => C): AssocMap[Key, C] = this match {
+    case Nil() =>
+      AssocMap.empty[Key, C]
+    case Cons(key, value, tail) =>
+      val newtail = tail.transform(f)
+      val newval = f(key, value)
       if ((tail eq newtail) && (value.asInstanceOf[AnyRef] eq newval.asInstanceOf[AnyRef])) this.asInstanceOf[AssocMap[Key, C]];
       else Cons(key, newval, newtail);
-    }
   }
 
   def -(key : Key) : AssocMap[Key, Value]= this match {
@@ -280,3 +270,4 @@ private[collection] class AssocMapIterator[Key, Value](var it : AssocMap[Key, Va
   }
 }
 
+*/
diff --git a/src/library/scala/collection/immutable/TreeMap.scala b/src/library/scala/collection/immutable/TreeMap.scala
index d9a45c8..aca00df 100644
--- a/src/library/scala/collection/immutable/TreeMap.scala
+++ b/src/library/scala/collection/immutable/TreeMap.scala
@@ -1,135 +1,148 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: TreeMap.scala 16894 2009-01-13 13:09:41Z cunei $
 
-// todo: make balanced once Tree.scala is updated to be covariant.
 
-package scala.collection.immutable
+package scala.collection
+package immutable
 
+import generic._
+import mutable.Builder
 
-/** The canonical factory of <a href="TreeMap.html">TreeMap</a>'s. */
-object TreeMap {
-
-  /** The empty map of this type 
-   *  @deprecated   use <code>empty</code> instead
-   */
-  @deprecated
-  def Empty[A <% Ordered[A], B] = empty[A, B]
-
-  /** The empty map of this type */  
-  def empty[A <% Ordered[A], B] = new TreeMap[A, B]
-
-  /** The canonical factory for this type
-   */
-  def apply[A <% Ordered[A], B](elems: (A, B)*) = empty[A, B] ++ elems
+/** $factoryInfo
+ *  @define Coll immutable.TreeMap
+ *  @define coll immutable tree map
+ */
+object TreeMap extends ImmutableSortedMapFactory[TreeMap] {
+  def empty[A, B](implicit ord: Ordering[A]) = new TreeMap[A, B]()(ord)
+  /** $sortedMapCanBuildFromInfo */
+  implicit def canBuildFrom[A, B](implicit ord: Ordering[A]): CanBuildFrom[Coll, (A, B), TreeMap[A, B]] = new SortedMapCanBuildFrom[A, B]
+  private def make[A, B](s: Int, t: RedBlack[A]#Tree[B])(implicit ord: Ordering[A]) = new TreeMap[A, B](s, t)(ord)
 }
 
 /** This class implements immutable maps using a tree.
- *
+ *  
+ *  @tparam A         the type of the keys contained in this tree map.
+ *  @tparam B         the type of the values associated with the keys.
+ *  @param ordering   the implicit ordering used to compare objects of type `A`.
+ *  
  *  @author  Erik Stenman
  *  @author  Matthias Zenger
  *  @version 1.1, 03/05/2004
+ *  @since   1
+ *  @define Coll immutable.TreeMap
+ *  @define coll immutable tree map
+ *  @define orderDependent
+ *  @define orderDependentFold
+ *  @define mayNotTerminateInf
+ *  @define willNotTerminateInf
  */
 @serializable
-class TreeMap[A <% Ordered[A], +B](val size: Int, t: RedBlack[A]#Tree[B])
-extends RedBlack[A] with SortedMap[A, B] {
-
-  def isSmaller(x: A, y: A) = x < y
-
-  def this() = this(0, null)
+class TreeMap[A, +B](override val size: Int, t: RedBlack[A]#Tree[B])(implicit val ordering: Ordering[A])
+  extends RedBlack[A] 
+     with SortedMap[A, B] 
+     with SortedMapLike[A, B, TreeMap[A, B]] 
+     with MapLike[A, B, TreeMap[A, B]] {
+       
+  def isSmaller(x: A, y: A) = ordering.lt(x, y)
+
+  override protected[this] def newBuilder : Builder[(A, B), TreeMap[A, B]] = 
+    TreeMap.newBuilder[A, B]
+
+  def this()(implicit ordering: Ordering[A]) = this(0, null)(ordering)
   
   protected val tree: RedBlack[A]#Tree[B] = if (size == 0) Empty else t
 
-  override def rangeImpl(from : Option[A], until : Option[A]) : SortedMap[A,B] = {
+  override def rangeImpl(from : Option[A], until : Option[A]): TreeMap[A,B] = {
     val ntree = tree.range(from,until)
     new TreeMap[A,B](ntree.count, ntree)
   }
+
   override def firstKey = t.first
   override def lastKey = t.last
-  override def compare(k0: A, k1: A): Int = k0.compare(k1)
+  override def compare(k0: A, k1: A): Int = ordering.compare(k0, k1)
 
-    
-
-  
-  private def newMap[B](s: Int, t: RedBlack[A]#Tree[B]) = new TreeMap[A, B](s, t)
-  
   /** A factory to create empty maps of the same type of keys.
    */
-  def empty[C] = TreeMap.empty[A, C]
+  override def empty: TreeMap[A, B] = TreeMap.empty[A, B](ordering)
 
   /** A new TreeMap with the entry added is returned,
    *  if key is <em>not</em> in the TreeMap, otherwise
    *  the key is updated with the new entry.
    *
-   *  @param key ...
-   *  @param value ...
-   *  @return ...
+   *  @tparam B1     type of the value of the new binding which is a supertype of `B`
+   *  @param key     the key that should be updated
+   *  @param value   the value to be associated with `key`
+   *  @return        a new $coll with the updated binding
    */
-  def update [B1 >: B](key: A, value: B1): TreeMap[A, B1] = {
+  override def updated [B1 >: B](key: A, value: B1): TreeMap[A, B1] = {
     val newsize = if (tree.lookup(key).isEmpty) size + 1 else size
-    newMap(newsize, tree.update(key, value))
+    TreeMap.make(newsize, tree.update(key, value))
   }
 
+  /** Add a key/value pair to this map. 
+   *  @tparam   B1   type of the value of the new binding, a supertype of `B`
+   *  @param    kv   the key/value pair
+   *  @return        A new $coll with the new binding added to this map
+   */
+  override def + [B1 >: B] (kv: (A, B1)): TreeMap[A, B1] = updated(kv._1, kv._2)
+
+  /** Adds two or more elements to this collection and returns
+   *  either the collection itself (if it is mutable), or a new collection
+   *  with the added elements.
+   *  
+   *  @tparam B1   type of the values of the new bindings, a supertype of `B`
+   *  @param elem1 the first element to add.
+   *  @param elem2 the second element to add.
+   *  @param elems the remaining elements to add.
+   *  @return      a new $coll with the updated bindings
+   */
+  override def + [B1 >: B] (elem1: (A, B1), elem2: (A, B1), elems: (A, B1) *): TreeMap[A, B1] =
+    this + elem1 + elem2 ++ elems
+
   /** A new TreeMap with the entry added is returned,
    *  assuming that key is <em>not</em> in the TreeMap.
+   *  
+   *  @tparam B1    type of the values of the new bindings, a supertype of `B`
+   *  @param key    the key to be inserted
+   *  @param value  the value to be associated with `key`
+   *  @return       a new $coll with the inserted binding, if it wasn't present in the map
    */
   def insert [B1 >: B](key: A, value: B1): TreeMap[A, B1] = {
     assert(tree.lookup(key).isEmpty)
-    newMap(size + 1, tree.update(key, value))
+    TreeMap.make(size + 1, tree.update(key, value))
   }
 
   def - (key:A): TreeMap[A, B] = 
     if (tree.lookup(key).isEmpty) this
-    else newMap(size - 1, tree.delete(key))
+    else TreeMap.make(size - 1, tree.delete(key))
 
-  /** Check if this map maps <code>key</code> to a value and return the
+  /** Check if this map maps `key` to a value and return the
    *  value if it exists.
    *
    *  @param  key     the key of the mapping of interest
-   *  @return the value of the mapping, if it exists
+   *  @return         the value of the mapping, if it exists
    */
   override def get(key: A): Option[B] = tree.lookup(key) match {
     case n: NonEmpty[b] => Some(n.value)
     case _ => None
   }
 
-  /** Retrieve the value which is associated with the given key. This
-   *  method throws an exception if there is no mapping from the given
-   *  key to a value.
-   *
-   *  @param  key     the key
-   *  @return the value associated with the given key.
-   *  @throws Error("key not found").
-   */
-  override def apply(key: A): B = tree.lookup(key) match {
-    case n: NonEmpty[b] => n.value
-    case _ => super.apply(key)
-  }
-
   /** Creates a new iterator over all elements contained in this
    *  object.
    *
    *  @return the new iterator
    */
-  def elements: Iterator[Pair[A, B]] = tree.elements.elements
-  
-  override def foreach(f : Tuple2[A,B] => Unit) : Unit = 
-    tree.visit[Unit](())((unit0,a,b) => Tuple2(true, f(Tuple2(a,b))))
-  override def forall(f : Tuple2[A,B] => Boolean) : Boolean = 
-    tree.visit[Boolean](true)((input,a,b) => f(Tuple2(a,b)) match {
-    case ret if input => Tuple2(ret,ret)
-    })._2
-  override def exists(f : Tuple2[A,B] => Boolean) : Boolean = 
-    tree.visit[Boolean](false)((input,a,b) => f(Tuple2(a,b)) match {
-    case ret if !input => Tuple2(!ret,ret)
-    })._2
+  def iterator: Iterator[(A, B)] = tree.toStream.iterator
+
+  override def toStream: Stream[(A, B)] = tree.toStream
   
+  override def foreach[U](f : ((A,B)) =>  U) = tree foreach { case (x, y) => f(x, y) }
 }        
       
 
diff --git a/src/library/scala/collection/immutable/TreeMap.scala.disabled b/src/library/scala/collection/immutable/TreeMap.scala.disabled
deleted file mode 100644
index 0b3bb7a..0000000
--- a/src/library/scala/collection/immutable/TreeMap.scala.disabled
+++ /dev/null
@@ -1,101 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: TreeMap.scala 8997 2006-10-19 20:52:30Z odersky $
-
-package scala.collection.immutable
-
-
-object TreeMap {
-  def Empty[A <% Ordered[A], B] = new TreeMap[A, B]
-}
-
-/** This class implements immutable maps using a tree.
- *
- *  @author  Erik Stenman
- *  @author  Matthias Zenger
- *  @version 1.1, 03/05/2004
- */
-
-[serializable]
-class TreeMap[A <% Ordered[A], B] extends Tree[A, Pair[A, B]] with Map[A, B] {
-
-  override protected type This = TreeMap[A, B]
-  override protected def getThis: This = this
-
-  /** A factory to create empty maps of the same type of keys.
-   */
-  def empty[C] = new TreeMap[A, C]
-
-  /** Creates a new TreeMap from a GBTree and its size.
-   *
-   *  @param sz ...
-   *  @param t ...
-   *  @return ...
-   */
-  protected def New(sz: Int, t: aNode): This = new TreeMap[A, B] {
-    override def size = sz
-    override protected def tree: aNode = t
-  }
-
-  /** A new TreeMap with the entry added is returned,
-   *  if key is <em>not</em> in the TreeMap, otherwise
-   *  the key is updated with the new entry.
-   *
-   *  @param key ...
-   *  @param value ...
-   *  @return ...
-   */
-  def update [B1 >: B](key: A, value: B1) = updateOrAdd(key, {key, value})
-
-  /** A new TreeMap with the entry added is returned,
-   *  assuming that key is <em>not</em> in the TreeMap.
-   */
-  def insert [B1 >: B](key:A, value:B) = add(key, {key, value})
-
-  /** Removes the key from the TreeMap.
-   */
-  def remove(key:A) = deleteAny(key)
-
-  /** Check if this map maps <code>key</code> to a value and return the
-   *  value if it exists.
-   *
-   *  @param  key     the key of the mapping of interest
-   *  @return the value of the mapping, if it exists
-   */
-  override def get(key: A): Option[B] =
-    findValue(key) match {
-      case Some(Pair(_, value)) => Some(value)
-      case _ => None
-    }
-
-  /** Retrieve the value which is associated with the given key. This
-   *  method throws an exception if there is no mapping from the given
-   *  key to a value.
-   *
-   *  @param  key     the key
-   *  @return the value associated with the given key.
-   *  @throws Error("key not found").
-   */
-  override def apply(key: A): B = tree.apply(key)._2
-
-  /** Creates a list of all (key, value) mappings.
-   *
-   *  @return    the list of all mappings
-   */
-  override def toList: List[Pair[A, B]] =
-    tree.toList(scala.Nil) map (._2)
-
-  /** Creates a new iterator over all elements contained in this
-   *  object.
-   *
-   *  @return the new iterator
-   */
-  def elements: Iterator[Pair[A, B]] = entries
-}
-
diff --git a/src/library/scala/collection/immutable/TreeSet.scala b/src/library/scala/collection/immutable/TreeSet.scala
index dd098bc..dd8419d 100644
--- a/src/library/scala/collection/immutable/TreeSet.scala
+++ b/src/library/scala/collection/immutable/TreeSet.scala
@@ -1,105 +1,119 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: TreeSet.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.collection.immutable
+package scala.collection
+package immutable
 
-/** The canonical factory of <a href="TreeSet.html">TreeSet</a>'s. */
+import generic._
+import mutable.{ Builder, AddingBuilder }
 
-object TreeSet {
+/** $factoryInfo
+ *  @define Coll immutable.TreeSet
+ *  @define coll immutable tree set
+ */
+object TreeSet extends ImmutableSortedSetFactory[TreeSet] {
+  implicit def implicitBuilder[A](implicit ordering: Ordering[A]): Builder[A, TreeSet[A]] = newBuilder[A](ordering)
+  override def newBuilder[A](implicit ordering: Ordering[A]): Builder[A, TreeSet[A]] =
+    new AddingBuilder(empty[A](ordering))
 
   /** The empty set of this type
    */
-  def empty[A <% Ordered[A]] = new TreeSet[A]
-
-  /** The canonical factory for this type
-   */
-  def apply[A <% Ordered[A]](elems: A*) : SortedSet[A] = empty[A] ++ elems
+  def empty[A](implicit ordering: Ordering[A]) = new TreeSet[A]
 }
 
 /** This class implements immutable sets using a tree.
- *
+ *  
+ *  @tparam A         the type of the elements contained in this tree set
+ *  @param ordering   the implicit ordering used to compare objects of type `A`
+ *  
  *  @author  Martin Odersky
  *  @version 2.0, 02/01/2007
+ *  @since   1
+ *  @define Coll immutable.TreeSet
+ *  @define coll immutable tree set
+ *  @define orderDependent
+ *  @define orderDependentFold
+ *  @define mayNotTerminateInf
+ *  @define willNotTerminateInf
  */
+ at serializable @SerialVersionUID(-234066569443569402L)
+class TreeSet[A](override val size: Int, t: RedBlack[A]#Tree[Unit])
+                (implicit val ordering: Ordering[A])
+  extends RedBlack[A] with SortedSet[A] with SortedSetLike[A, TreeSet[A]] {
 
- at serializable
-class TreeSet[A <% Ordered[A]](val size: Int, t: RedBlack[A]#Tree[Unit])
-  extends RedBlack[A] with SortedSet[A] {
+  override def stringPrefix = "TreeSet"
 
-  def isSmaller(x: A, y: A) = x < y
+  def isSmaller(x: A, y: A) = compare(x,y) < 0
 
-  def this() = this(0, null)
+  def this()(implicit ordering: Ordering[A]) = this(0, null)(ordering)
   
   protected val tree: RedBlack[A]#Tree[Unit] = if (size == 0) Empty else t
 
   private def newSet(s: Int, t: RedBlack[A]#Tree[Unit]) = new TreeSet[A](s, t)
 
-  /** A factory to create empty maps of the same type of keys.
+  /** A factory to create empty sets of the same type of keys.
    */
-  def empty[B]: Set[B] = ListSet.empty[B]
+  override def empty = TreeSet.empty
 
-  /** A new TreeSet with the entry added is returned,
+  /** Creates a new `TreeSet` with the entry added.
+   *  
+   *  @param elem    a new element to add.
+   *  @return        a new $coll containing `elem` and all the elements of this $coll.
    */
   def + (elem: A): TreeSet[A] = {
     val newsize = if (tree.lookup(elem).isEmpty) size + 1 else size
     newSet(newsize, tree.update(elem, ()))
   }
 
-  /** A new TreeSet with the entry added is returned,
+  /** A new `TreeSet` with the entry added is returned,
    *  assuming that elem is <em>not</em> in the TreeSet.
+   *  
+   *  @param elem    a new element to add.
+   *  @return        a new $coll containing `elem` and all the elements of this $coll.
    */
-  def insert (elem: A): TreeSet[A] = {
+  def insert(elem: A): TreeSet[A] = {
     assert(tree.lookup(elem).isEmpty)
     newSet(size + 1, tree.update(elem, ()))
   }
-
+  
+  /** Creates a new `TreeSet` with the entry removed.
+   *  
+   *  @param elem    a new element to add.
+   *  @return        a new $coll containing all the elements of this $coll except `elem`.
+   */
   def - (elem:A): TreeSet[A] = 
     if (tree.lookup(elem).isEmpty) this
-    else newSet(size - 1, tree.delete(elem))
+    else newSet(size - 1, tree delete elem)
 
-  /** Checks if this set contains element <code>elem</code>.
-   *
+  /** Checks if this set contains element `elem`.
+   *  
    *  @param  elem    the element to check for membership.
-   *  @return true, iff <code>elem</code> is contained in this set.
+   *  @return true, iff `elem` is contained in this set.
    */
   def contains(elem: A): Boolean = !tree.lookup(elem).isEmpty
 
   /** Creates a new iterator over all elements contained in this
    *  object.
-   *
+   *  
    *  @return the new iterator
    */
-  def elements: Iterator[A] = tree.elements.elements map (_._1)
+  def iterator: Iterator[A] = tree.toStream.iterator map (_._1)
 
-  def elementsSlow = tree.elementsSlow map (_._1)
+  override def toStream: Stream[A] = tree.toStream map (_._1)
 
-  override def foreach(f: A => Unit) {
-    tree.visit[Unit](())((unit0, y, unit1) => Tuple2(true, f(y)))
-  }
+  override def foreach[U](f: A =>  U) = tree foreach { (x, y) => f(x) } 
 
-  override def forall(f: A => Boolean): Boolean = 
-    tree.visit[Boolean](true)((input, a, unit) => f(a) match {
-    case ret if input => Tuple2(ret, ret)
-    })._2
-
-  override def exists(f: A => Boolean): Boolean = 
-    tree.visit[Boolean](false)((input, a, unit) => f(a) match {
-    case ret if !input => Tuple2(!ret, ret)
-    })._2
-
-   override def rangeImpl(from: Option[A], until: Option[A]): TreeSet[A] = {
-     val tree = this.tree.range(from, until)
-     newSet(tree.count, tree)
-   }
-   override def firstKey = tree.first
-   override def lastKey = tree.last
-   override def compare(a0: A, a1: A) = a0.compare(a1)
+  override def rangeImpl(from: Option[A], until: Option[A]): TreeSet[A] = {
+    val tree = this.tree.range(from, until)
+    newSet(tree.count, tree)
+  }
+  override def firstKey = tree.first
+  override def lastKey = tree.last
 }
diff --git a/src/library/scala/collection/immutable/UnbalancedTreeMap.scala b/src/library/scala/collection/immutable/UnbalancedTreeMap.scala
deleted file mode 100644
index c65bd44..0000000
--- a/src/library/scala/collection/immutable/UnbalancedTreeMap.scala
+++ /dev/null
@@ -1,143 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: UnbalancedTreeMap.scala 16894 2009-01-13 13:09:41Z cunei $
-
-// todo: make balanced once Tree.scala is updated to be covariant.
-
-package scala.collection.immutable
-
-
-object UnbalancedTreeMap {
-
-  /** The empty map of this type */  
-  def empty[A <% Ordered[A], B] = new UnbalancedTreeMap[A, B]
-
-  /** The canonical factory for this type
-   */
-  def apply[A<% Ordered[A], B](elems: (A, B)*) = empty[A, B] ++ elems
-}
-
-/** This class implements immutable maps using a tree.
- *
- *  @author  Martin Odersky
- *  @version 1.1, 02/01/2007
- */
-
- at serializable
-class UnbalancedTreeMap[A <% Ordered[A], +B] extends Map[A, B] {
-
-  /** A factory to create empty maps of the same type of keys.
-   */
-  def empty[C] = UnbalancedTreeMap.empty[A, C]
-
-  def size: Int = 0
-
-  override def isEmpty: Boolean = true
-
-  protected def add [B1 >: B](key: A, value: B1) = new Node(key, value, this, this)
-  protected def findValue (key: A): UnbalancedTreeMap[A, B] = this
-
-  protected def key: A = throw new NoSuchElementException("empty map")
-  protected def value: B = throw new NoSuchElementException("empty map")
-  protected def smallest: UnbalancedTreeMap[A, B] = throw new NoSuchElementException("empty map")
-    
-  /** A new TreeMap with the entry added is returned,
-   *  if key is <em>not</em> in the TreeMap, otherwise
-   *  the key is updated with the new entry.
-   *
-   *  @param key ...
-   *  @param value ...
-   *  @return ...
-   */
-  def update[B1 >: B](key: A, value: B1) = add(key, value)
-
-  /** A new TreeMap with the entry added is returned,
-   *  assuming that key is <em>not</em> in the TreeMap.
-   */
-  def insert[B1 >: B](key: A, value: B1) = add(key, value)
-
-  def - (key:A): UnbalancedTreeMap[A, B] = this
-
-  /** Check if this map maps <code>key</code> to a value and return the
-   *  value if it exists.
-   *
-   *  @param  key     the key of the mapping of interest
-   *  @return the value of the mapping, if it exists
-   */
-  override def get(key: A): Option[B] = {
-    val t = findValue(key)
-    if (t.isEmpty) None
-    else Some(t.value)
-  }
-
-  /** Retrieve the value which is associated with the given key. This
-   *  method throws an exception if there is no mapping from the given
-   *  key to a value.
-   *
-   *  @param  key     the key
-   *  @return the value associated with the given key.
-   *  @throws Error("key not found").
-   */
-  override def apply(key: A): B = {
-    val t = findValue(key)
-    if (!t.isEmpty) t.value
-    else super.apply(key)
-  }
-
-  /** Creates a new iterator over all elements contained in this
-   *  object.
-   *
-   *  @return the new iterator
-   */
-  def elements: Iterator[(A, B)] = Iterator.empty
-
-  protected class Node[+B](override protected val key: A,
-                           override protected val value: B,
-                           left: UnbalancedTreeMap[A, B],
-                           right: UnbalancedTreeMap[A, B]) extends UnbalancedTreeMap[A, B] 
-  {
-    override def size = left.size + right.size + 1
-
-    override def isEmpty = false
-    
-    override protected def add [B1 >: B](k: A, v: B1) =
-      if (k < key) new Node[B1](key, value, left.add(k, v), right)
-      else if (k > key) new Node[B1](key, value, left, right.add(k, v))
-      else new Node[B1](k, v, left, right)
-
-    override protected def findValue (k: A): UnbalancedTreeMap[A, B] = 
-      if (k < key) left.findValue(k)
-      else if (k > key) right.findValue(k)
-      else this
-
-    override protected def smallest: UnbalancedTreeMap[A, B] = 
-      if (left.isEmpty) this else left.smallest
-
-    override def - (k: A): UnbalancedTreeMap[A, B] =
-      if (k < key) new Node(key, value, left - k, right)
-      else if (k > key) new Node(key, value, left, right - k)
-      else combine(left, right)
-
-    private def combine[B](l: UnbalancedTreeMap[A, B], r: UnbalancedTreeMap[A, B]) = {
-      if (l.isEmpty) r
-      else if (r.isEmpty) l
-      else {
-        val s = r.smallest
-        new Node(s.key, s.value, l, r - s.key)
-      }
-    }
-
-    override def elements: Iterator[(A, B)] =
-      left.elements append Iterator.single((key, value)) append right.elements
-  }
-}        
-      
-
-
-
diff --git a/src/library/scala/collection/immutable/Vector.scala b/src/library/scala/collection/immutable/Vector.scala
new file mode 100644
index 0000000..7cb112c
--- /dev/null
+++ b/src/library/scala/collection/immutable/Vector.scala
@@ -0,0 +1,1178 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+package scala.collection
+package immutable
+
+import scala.annotation.unchecked.uncheckedVariance
+import compat.Platform
+
+import scala.collection.generic._
+import scala.collection.mutable.Builder
+
+
+object Vector extends SeqFactory[Vector] {
+  private[immutable] val BF = new GenericCanBuildFrom[Nothing] {
+    override def apply() = newBuilder[Nothing]
+  }
+  @inline implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, Vector[A]] =
+    BF.asInstanceOf[CanBuildFrom[Coll, A, Vector[A]]]
+  def newBuilder[A]: Builder[A, Vector[A]] = new VectorBuilder[A]
+  private[immutable] val NIL = new Vector[Nothing](0, 0, 0)
+  @inline override def empty[A]: Vector[A] = NIL
+}
+
+
+// in principle, most members should be private. however, access privileges must
+// be carefully chosen to not prevent method inlining
+
+ at serializable
+final class Vector[+A](startIndex: Int, endIndex: Int, focus: Int) extends IndexedSeq[A]
+                 with GenericTraversableTemplate[A, Vector]
+                 with IndexedSeqLike[A, Vector[A]]
+                 with VectorPointer[A @uncheckedVariance] { self =>
+
+override def companion: GenericCompanion[Vector] = Vector
+
+  //assert(startIndex >= 0, startIndex+"<0")
+  //assert(startIndex <= endIndex, startIndex+">"+endIndex)
+  //assert(focus >= 0, focus+"<0")
+  //assert(focus <= endIndex, focus+">"+endIndex)
+
+  private[immutable] var dirty = false
+
+  def length = endIndex - startIndex
+
+  override def lengthCompare(len: Int): Int = length - len
+  
+
+  @inline override def iterator: VectorIterator[A] = {
+    val s = new VectorIterator[A](startIndex, endIndex)
+    s.initFrom(this)
+    if (dirty) s.stabilize(focus)
+    if (s.depth > 1) s.gotoPos(startIndex, startIndex ^ focus)
+    s
+  }
+
+
+  // can still be improved
+  override /*SeqLike*/
+  def reverseIterator: Iterator[A] = new Iterator[A] {
+    private var i = self.length
+    def hasNext: Boolean = 0 < i
+    def next: A = 
+      if (0 < i) {
+        i -= 1
+        self(i)
+      } else Iterator.empty.next
+  }
+
+  // TODO: reverse
+
+  // TODO: check performance of foreach/map etc. should override or not?
+  // Ideally, clients will inline calls to map all the way down, including the iterator/builder methods.
+  // In principle, escape analysis could even remove the iterator/builder allocations and do it
+  // with local variables exclusively. But we're not quite there yet ...
+
+  @deprecated("this method is experimental and will be removed in a future release")
+  @inline def foreachFast[U](f: A => U): Unit = iterator.foreachFast(f)
+  @deprecated("this method is experimental and will be removed in a future release")
+  @inline def mapFast[B, That](f: A => B)(implicit bf: CanBuildFrom[Vector[A], B, That]): That = {
+    val b = bf(repr)
+    foreachFast(x => b += f(x))
+    b.result
+  }
+
+
+  def apply(index: Int): A = {
+    val idx = checkRangeConvert(index)
+    //println("get elem: "+index + "/"+idx + "(focus:" +focus+" xor:"+(idx^focus)+" depth:"+depth+")")
+    getElem(idx, idx ^ focus)
+  }
+  
+  private def checkRangeConvert(index: Int) = {
+    val idx = index + startIndex
+    if (0 <= index && idx < endIndex)
+      idx
+    else
+      throw new IndexOutOfBoundsException(index.toString)
+  }
+
+
+  // SeqLike api
+  
+  @inline override def updated[B >: A, That](index: Int, elem: B)(implicit bf: CanBuildFrom[Vector[A], B, That]): That = {
+    // just ignore bf
+    updateAt(index, elem).asInstanceOf[That]
+  }
+
+  @inline override def +:[B >: A, That](elem: B)(implicit bf: CanBuildFrom[Vector[A], B, That]): That = {
+    // just ignore bf
+    appendFront(elem).asInstanceOf[That]
+  }
+
+  @inline override def :+[B >: A, That](elem: B)(implicit bf: CanBuildFrom[Vector[A], B, That]): That = {
+    // just ignore bf
+    appendBack(elem).asInstanceOf[That]
+  }
+
+  override def take(n: Int): Vector[A] = {
+    if (n <= 0)
+      Vector.empty
+    else if (startIndex + n < endIndex)
+      dropBack0(startIndex + n)
+    else
+      this
+  }
+
+  override def drop(n: Int): Vector[A] = {
+    if (n <= 0)
+      this
+    else if (startIndex + n < endIndex)
+      dropFront0(startIndex + n)
+    else
+      Vector.empty
+  }
+
+  override def takeRight(n: Int): Vector[A] = {
+    if (n <= 0)
+      Vector.empty
+    else if (endIndex - n > startIndex)
+      dropFront0(endIndex - n)
+    else
+      this
+  }
+
+  override def dropRight(n: Int): Vector[A] = {
+    if (n <= 0)
+      this
+    else if (endIndex - n > startIndex)
+      dropBack0(endIndex - n)
+    else
+      Vector.empty
+  }
+
+  override /*IterableLike*/ def head: A = {
+    if (isEmpty) throw new UnsupportedOperationException("empty.head")
+    apply(0)
+  }
+
+  override /*TraversableLike*/ def tail: Vector[A] = {
+    if (isEmpty) throw new UnsupportedOperationException("empty.tail")
+    drop(1)
+  }
+
+  override /*TraversableLike*/ def last: A = {
+    if (isEmpty) throw new UnsupportedOperationException("empty.last")
+    apply(length-1)
+  }
+  
+  override /*TraversableLike*/ def init: Vector[A] = {
+    if (isEmpty) throw new UnsupportedOperationException("empty.init")
+    dropRight(1)
+  }
+
+  override /*IterableLike*/ def slice(from: Int, until: Int): Vector[A] = 
+    take(until).drop(from)
+
+  override /*IterableLike*/ def splitAt(n: Int): (Vector[A], Vector[A]) = (take(n), drop(n))
+  
+    
+  
+  // semi-private api
+
+  private[immutable] def updateAt[B >: A](index: Int, elem: B): Vector[B] = {
+    val idx = checkRangeConvert(index)
+    val s = new Vector[B](startIndex, endIndex, idx)
+    s.initFrom(this)
+    s.dirty = dirty
+    s.gotoPosWritable(focus, idx, focus ^ idx)  // if dirty commit changes; go to new pos and prepare for writing
+    s.display0(idx & 0x1f) = elem.asInstanceOf[AnyRef]
+    s
+  }
+  
+  
+  private def gotoPosWritable(oldIndex: Int, newIndex: Int, xor: Int) = if (dirty) {
+    gotoPosWritable1(oldIndex, newIndex, xor)
+  } else {
+    gotoPosWritable0(newIndex, xor)
+    dirty = true
+  }
+  
+  private def gotoFreshPosWritable(oldIndex: Int, newIndex: Int, xor: Int) = if (dirty) {
+    gotoFreshPosWritable1(oldIndex, newIndex, xor)
+  } else {
+    gotoFreshPosWritable0(oldIndex, newIndex, xor)
+    dirty = true
+  }
+
+  private[immutable] def appendFront[B>:A](value: B): Vector[B] = {
+    if (endIndex != startIndex) {
+      var blockIndex = (startIndex - 1) & ~31
+      var lo = (startIndex - 1) & 31
+
+      if (startIndex != blockIndex + 32) {
+        val s = new Vector(startIndex - 1, endIndex, blockIndex)
+        s.initFrom(this)
+        s.dirty = dirty
+        s.gotoPosWritable(focus, blockIndex, focus ^ blockIndex)
+        s.display0(lo) = value.asInstanceOf[AnyRef]
+        s
+      } else {
+
+        val freeSpace = ((1<<5*(depth)) - endIndex) // free space at the right given the current tree-structure depth
+        val shift = freeSpace & ~((1<<5*(depth-1))-1) // number of elements by which we'll shift right (only move at top level)
+        val shiftBlocks = freeSpace >>> 5*(depth-1) // number of top-level blocks
+
+        //println("----- appendFront " + value + " at " + (startIndex - 1) + " reached block start")
+        if (shift != 0) {
+          // case A: we can shift right on the top level
+          debug
+          //println("shifting right by " + shiftBlocks + " at level " + (depth-1) + " (had "+freeSpace+" free space)")
+
+          if (depth > 1) {
+            val newBlockIndex = blockIndex + shift
+            val newFocus = focus + shift
+            val s = new Vector(startIndex - 1 + shift, endIndex + shift, newBlockIndex)
+            s.initFrom(this)
+            s.dirty = dirty
+            s.shiftTopLevel(0, shiftBlocks) // shift right by n blocks 
+            s.debug
+            s.gotoFreshPosWritable(newFocus, newBlockIndex, newFocus ^ newBlockIndex) // maybe create pos; prepare for writing
+            s.display0(lo) = value.asInstanceOf[AnyRef]
+            //assert(depth == s.depth)
+            s
+          } else {
+            val newBlockIndex = blockIndex + 32
+            val newFocus = focus
+
+            //assert(newBlockIndex == 0)
+            //assert(newFocus == 0)
+
+            val s = new Vector(startIndex - 1 + shift, endIndex + shift, newBlockIndex)
+            s.initFrom(this)
+            s.dirty = dirty
+            s.shiftTopLevel(0, shiftBlocks) // shift right by n elements
+            s.gotoPosWritable(newFocus, newBlockIndex, newFocus ^ newBlockIndex) // prepare for writing
+            s.display0(shift-1) = value.asInstanceOf[AnyRef]
+            s.debug
+            s
+          }
+        } else if (blockIndex < 0) {
+          // case B: we need to move the whole structure
+          val move = (1 << 5*(depth+1)) - (1 << 5*(depth))
+          //println("moving right by " + move + " at level " + (depth-1) + " (had "+freeSpace+" free space)")
+
+          val newBlockIndex = blockIndex + move
+          val newFocus = focus + move
+
+
+          val s = new Vector(startIndex - 1 + move, endIndex + move, newBlockIndex)
+          s.initFrom(this)
+          s.dirty = dirty
+          s.debug
+          s.gotoFreshPosWritable(newFocus, newBlockIndex, newFocus ^ newBlockIndex) // could optimize: we know it will create a whole branch
+          s.display0(lo) = value.asInstanceOf[AnyRef]
+          s.debug
+          //assert(s.depth == depth+1)
+          s
+        } else {
+          val newBlockIndex = blockIndex
+          val newFocus = focus
+
+          val s = new Vector(startIndex - 1, endIndex, newBlockIndex)
+          s.initFrom(this)
+          s.dirty = dirty
+          s.gotoFreshPosWritable(newFocus, newBlockIndex, newFocus ^ newBlockIndex)
+          s.display0(lo) = value.asInstanceOf[AnyRef]
+          //assert(s.depth == depth)
+          s
+        }
+
+      }
+    } else {
+      // empty vector, just insert single element at the back
+      val elems = new Array[AnyRef](32)
+      elems(31) = value.asInstanceOf[AnyRef]
+      val s = new Vector(31,32,0)
+      s.depth = 1
+      s.display0 = elems
+      s
+    }
+  }
+
+  private[immutable] def appendBack[B>:A](value: B): Vector[B] = {
+//    //println("------- append " + value)
+//    debug()
+    if (endIndex != startIndex) {
+      var blockIndex = endIndex & ~31
+      var lo = endIndex & 31
+      
+      if (endIndex != blockIndex) {
+        //println("will make writable block (from "+focus+") at: " + blockIndex)
+        val s = new Vector(startIndex, endIndex + 1, blockIndex)
+        s.initFrom(this)
+        s.dirty = dirty
+        s.gotoPosWritable(focus, blockIndex, focus ^ blockIndex)
+        s.display0(lo) = value.asInstanceOf[AnyRef]
+        s
+      } else {
+        val shift = startIndex & ~((1<<5*(depth-1))-1)
+        val shiftBlocks = startIndex >>> 5*(depth-1)
+
+        //println("----- appendBack " + value + " at " + endIndex + " reached block end")
+        
+        if (shift != 0) {
+          debug
+          //println("shifting left by " + shiftBlocks + " at level " + (depth-1) + " (had "+startIndex+" free space)")
+          if (depth > 1) {
+            val newBlockIndex = blockIndex - shift
+            val newFocus = focus - shift
+            val s = new Vector(startIndex - shift, endIndex + 1 - shift, newBlockIndex)
+            s.initFrom(this)
+            s.dirty = dirty
+            s.shiftTopLevel(shiftBlocks, 0) // shift left by n blocks 
+            s.debug
+            s.gotoFreshPosWritable(newFocus, newBlockIndex, newFocus ^ newBlockIndex)
+            s.display0(lo) = value.asInstanceOf[AnyRef]
+            s.debug
+            //assert(depth == s.depth)
+            s
+          } else {
+            val newBlockIndex = blockIndex - 32
+            val newFocus = focus
+
+            //assert(newBlockIndex == 0)
+            //assert(newFocus == 0)
+
+            val s = new Vector(startIndex - shift, endIndex + 1 - shift, newBlockIndex)
+            s.initFrom(this)
+            s.dirty = dirty
+            s.shiftTopLevel(shiftBlocks, 0) // shift right by n elements
+            s.gotoPosWritable(newFocus, newBlockIndex, newFocus ^ newBlockIndex)
+            s.display0(32 - shift) = value.asInstanceOf[AnyRef]
+            s.debug
+            s
+          }
+        } else {
+          val newBlockIndex = blockIndex
+          val newFocus = focus
+
+          val s = new Vector(startIndex, endIndex + 1, newBlockIndex)
+          s.initFrom(this)
+          s.dirty = dirty
+          s.gotoFreshPosWritable(newFocus, newBlockIndex, newFocus ^ newBlockIndex)
+          s.display0(lo) = value.asInstanceOf[AnyRef]
+          //assert(s.depth == depth+1) might or might not create new level!
+          if (s.depth == depth+1) {
+            //println("creating new level " + s.depth + " (had "+0+" free space)")
+            s.debug
+          }
+          s
+        }
+      }
+    } else {
+      val elems = new Array[AnyRef](32)
+      elems(0) = value.asInstanceOf[AnyRef]
+      val s = new Vector(0,1,0)
+      s.depth = 1
+      s.display0 = elems
+      s
+    }
+  }
+
+
+  // low-level implementation (needs cleanup, maybe move to util class)
+
+  private def shiftTopLevel(oldLeft: Int, newLeft: Int) = (depth - 1) match {
+    case 0 =>
+      display0 = copyRange(display0, oldLeft, newLeft)
+    case 1 =>
+      display1 = copyRange(display1, oldLeft, newLeft)
+    case 2 =>
+      display2 = copyRange(display2, oldLeft, newLeft)
+    case 3 =>
+      display3 = copyRange(display3, oldLeft, newLeft)
+    case 4 =>
+      display4 = copyRange(display4, oldLeft, newLeft)
+    case 5 =>
+      display5 = copyRange(display5, oldLeft, newLeft)
+  }
+
+  private def zeroLeft(array: Array[AnyRef], index: Int): Unit = {
+    var i = 0; while (i < index) { array(i) = null; i+=1 }
+  }
+
+  private def zeroRight(array: Array[AnyRef], index: Int): Unit = {
+    var i = index; while (i < array.length) { array(i) = null; i+=1 }
+  }
+
+  private def copyLeft(array: Array[AnyRef], right: Int): Array[AnyRef] = {
+//    if (array eq null)
+//      println("OUCH!!! " + right + "/" + depth + "/"+startIndex + "/" + endIndex + "/" + focus)
+    val a2 = new Array[AnyRef](array.length)
+    Platform.arraycopy(array, 0, a2, 0, right)
+    a2
+  }
+  private def copyRight(array: Array[AnyRef], left: Int): Array[AnyRef] = {
+    val a2 = new Array[AnyRef](array.length)
+    Platform.arraycopy(array, left, a2, left, a2.length - left)
+    a2
+  }
+
+  private def preClean(depth: Int) = {
+    this.depth = depth
+    (depth - 1) match {
+      case 0 =>
+        display1 = null
+        display2 = null
+        display3 = null
+        display4 = null
+        display5 = null
+      case 1 =>
+        display2 = null
+        display3 = null
+        display4 = null
+        display5 = null
+      case 2 =>
+        display3 = null
+        display4 = null
+        display5 = null
+      case 3 =>
+        display4 = null
+        display5 = null
+      case 4 =>
+        display5 = null
+      case 5 =>
+    }
+  }
+
+  // requires structure is at index cutIndex and writable at level 0
+  private def cleanLeftEdge(cutIndex: Int) = {
+    if (cutIndex < (1 << 5)) {
+      zeroLeft(display0, cutIndex)
+    } else
+    if (cutIndex < (1 << 10)) {
+      zeroLeft(display0, cutIndex & 0x1f)
+      display1 = copyRight(display1, (cutIndex >>>  5))
+    } else
+    if (cutIndex < (1 << 15)) {
+      zeroLeft(display0, cutIndex & 0x1f)
+      display1 = copyRight(display1, (cutIndex >>>  5) & 0x1f)
+      display2 = copyRight(display2, (cutIndex >>> 10))
+    } else
+    if (cutIndex < (1 << 20)) {
+      zeroLeft(display0, cutIndex & 0x1f)
+      display1 = copyRight(display1, (cutIndex >>>  5) & 0x1f)
+      display2 = copyRight(display2, (cutIndex >>> 10) & 0x1f)
+      display3 = copyRight(display3, (cutIndex >>> 15))
+    } else
+    if (cutIndex < (1 << 25)) {
+      zeroLeft(display0, cutIndex & 0x1f)
+      display1 = copyRight(display1, (cutIndex >>>  5) & 0x1f)
+      display2 = copyRight(display2, (cutIndex >>> 10) & 0x1f)
+      display3 = copyRight(display3, (cutIndex >>> 15) & 0x1f)
+      display4 = copyRight(display4, (cutIndex >>> 20))
+    } else
+    if (cutIndex < (1 << 30)) {
+      zeroLeft(display0, cutIndex & 0x1f)
+      display1 = copyRight(display1, (cutIndex >>>  5) & 0x1f)
+      display2 = copyRight(display2, (cutIndex >>> 10) & 0x1f)
+      display3 = copyRight(display3, (cutIndex >>> 15) & 0x1f)
+      display4 = copyRight(display4, (cutIndex >>> 20) & 0x1f)
+      display5 = copyRight(display5, (cutIndex >>> 25))
+    } else {
+      throw new IllegalArgumentException()
+    }
+  }
+
+  // requires structure is writable and at index cutIndex
+  private def cleanRightEdge(cutIndex: Int) = {
+
+    // we're actually sitting one block left if cutIndex lies on a block boundary
+    // this means that we'll end up erasing the whole block!!
+
+    if (cutIndex <= (1 << 5)) {
+      zeroRight(display0, cutIndex)
+    } else
+    if (cutIndex <= (1 << 10)) {
+      zeroRight(display0, ((cutIndex-1) & 0x1f) + 1)
+      display1 = copyLeft(display1, (cutIndex >>>  5))
+    } else
+    if (cutIndex <= (1 << 15)) {
+      zeroRight(display0, ((cutIndex-1) & 0x1f) + 1)
+      display1 = copyLeft(display1, (((cutIndex-1) >>>  5) & 0x1f) + 1)
+      display2 = copyLeft(display2, (cutIndex >>> 10))
+    } else
+    if (cutIndex <= (1 << 20)) {
+      zeroRight(display0, ((cutIndex-1) & 0x1f) + 1)
+      display1 = copyLeft(display1, (((cutIndex-1) >>>  5) & 0x1f) + 1)
+      display2 = copyLeft(display2, (((cutIndex-1) >>> 10) & 0x1f) + 1)
+      display3 = copyLeft(display3, (cutIndex >>> 15))
+    } else
+    if (cutIndex <= (1 << 25)) {
+      zeroRight(display0, ((cutIndex-1) & 0x1f) + 1)
+      display1 = copyLeft(display1, (((cutIndex-1) >>>  5) & 0x1f) + 1)
+      display2 = copyLeft(display2, (((cutIndex-1) >>> 10) & 0x1f) + 1)
+      display3 = copyLeft(display3, (((cutIndex-1) >>> 15) & 0x1f) + 1)
+      display4 = copyLeft(display4, (cutIndex >>> 20))
+    } else
+    if (cutIndex <= (1 << 30)) {
+      zeroRight(display0, ((cutIndex-1) & 0x1f) + 1)
+      display1 = copyLeft(display1, (((cutIndex-1) >>>  5) & 0x1f) + 1)
+      display2 = copyLeft(display2, (((cutIndex-1) >>> 10) & 0x1f) + 1)
+      display3 = copyLeft(display3, (((cutIndex-1) >>> 15) & 0x1f) + 1)
+      display4 = copyLeft(display4, (((cutIndex-1) >>> 20) & 0x1f) + 1)
+      display5 = copyLeft(display5, (cutIndex >>> 25))
+    } else {
+      throw new IllegalArgumentException()
+    }
+  }
+
+  private def requiredDepth(xor: Int) = {
+    if (xor < (1 <<  5)) 1
+    else if (xor < (1 << 10)) 2
+    else if (xor < (1 << 15)) 3
+    else if (xor < (1 << 20)) 4
+    else if (xor < (1 << 25)) 5
+    else if (xor < (1 << 30)) 6
+    else throw new IllegalArgumentException()
+  }
+  
+  private def dropFront0(cutIndex: Int): Vector[A] = {
+    var blockIndex = cutIndex & ~31
+    var lo = cutIndex & 31
+    
+    val xor = cutIndex ^ (endIndex - 1)
+    val d = requiredDepth(xor)
+    val shift = (cutIndex & ~((1 << (5*d))-1))
+
+    //println("cut front at " + cutIndex + ".." + endIndex + " (xor: "+xor+" shift: " + shift + " d: " + d +")")
+    
+/*
+    val s = new Vector(cutIndex-shift, endIndex-shift, blockIndex-shift)
+    s.initFrom(this)
+    if (s.depth > 1)
+      s.gotoPos(blockIndex, focus ^ blockIndex)
+    s.depth = d
+    s.stabilize(blockIndex-shift)
+    s.cleanLeftEdge(cutIndex-shift)
+    s
+*/    
+
+    // need to init with full display iff going to cutIndex requires swapping block at level >= d
+
+    val s = new Vector(cutIndex-shift, endIndex-shift, blockIndex-shift)
+    s.initFrom(this)
+    s.dirty = dirty
+    s.gotoPosWritable(focus, blockIndex, focus ^ blockIndex)
+    s.preClean(d)
+    s.cleanLeftEdge(cutIndex - shift)
+    s
+  }
+
+  private def dropBack0(cutIndex: Int): Vector[A] = {
+    var blockIndex = (cutIndex - 1) & ~31
+    var lo = ((cutIndex - 1) & 31) + 1
+
+    val xor = startIndex ^ (cutIndex - 1)
+    val d = requiredDepth(xor)
+    val shift = (startIndex & ~((1 << (5*d))-1))
+    
+/*    
+    println("cut back at " + startIndex + ".." + cutIndex + " (xor: "+xor+" d: " + d +")")
+    if (cutIndex == blockIndex + 32)
+      println("OUCH!!!")
+*/    
+    val s = new Vector(startIndex-shift, cutIndex-shift, blockIndex-shift)
+    s.initFrom(this)
+    s.dirty = dirty
+    s.gotoPosWritable(focus, blockIndex, focus ^ blockIndex)
+    s.preClean(d)
+    s.cleanRightEdge(cutIndex-shift)
+    s
+  }
+  
+}
+
+
+final class VectorIterator[+A](_startIndex: Int, _endIndex: Int) extends Iterator[A] with VectorPointer[A @uncheckedVariance] {
+
+  private var blockIndex: Int = _startIndex & ~31
+  private var lo: Int = _startIndex & 31
+  private var endIndex: Int = _endIndex
+
+  private var endLo = math.min(endIndex - blockIndex, 32)
+
+  def hasNext = _hasNext
+
+  private var _hasNext = blockIndex + lo < endIndex
+
+  def next(): A = {
+    if (!_hasNext) throw new NoSuchElementException("reached iterator end")
+
+    val res = display0(lo).asInstanceOf[A]
+    lo += 1
+
+    if (lo == endLo) {
+      if (blockIndex + lo < endIndex) {
+        val newBlockIndex = blockIndex+32
+        gotoNextBlockStart(newBlockIndex, blockIndex ^ newBlockIndex)
+
+        blockIndex = newBlockIndex
+        endLo = math.min(endIndex - blockIndex, 32)
+        lo = 0
+      } else {
+        _hasNext = false
+      }
+    }
+
+    res
+  }
+
+  // TODO: drop (important?)
+  
+  @deprecated("this method is experimental and will be removed in a future release")
+  @inline def foreachFast[U](f: A =>  U) { while (hasNext) f(next()) }
+}
+
+
+final class VectorBuilder[A]() extends Builder[A,Vector[A]] with VectorPointer[A @uncheckedVariance] {
+  
+  // possible alternative: start with display0 = null, blockIndex = -32, lo = 32
+  // to avoid allocating initial array if the result will be empty anyways
+  
+  display0 = new Array[AnyRef](32)
+  depth = 1
+  
+  private var blockIndex = 0
+  private var lo = 0
+  
+  def += (elem: A): this.type = {
+    if (lo >= display0.length) {
+      val newBlockIndex = blockIndex+32
+      gotoNextBlockStartWritable(newBlockIndex, blockIndex ^ newBlockIndex)
+      blockIndex = newBlockIndex
+      lo = 0
+    }
+    display0(lo) = elem.asInstanceOf[AnyRef]
+    lo += 1
+    this
+  }
+
+  def result: Vector[A] = {
+    val size = blockIndex + lo
+    if (size == 0)
+      return Vector.empty
+    val s = new Vector[A](0, size, 0) // should focus front or back?
+    s.initFrom(this)
+    if (depth > 1) s.gotoPos(0, size - 1) // we're currently focused to size - 1, not size!
+    s
+  }
+  
+  def clear: Unit = {
+    display0 = new Array[AnyRef](32)
+    depth = 1
+    blockIndex = 0
+    lo = 0
+  }
+}
+
+
+
+private[immutable] trait VectorPointer[T] {
+    private[immutable] var depth: Int = _
+    private[immutable] var display0: Array[AnyRef] = _
+    private[immutable] var display1: Array[AnyRef] = _
+    private[immutable] var display2: Array[AnyRef] = _
+    private[immutable] var display3: Array[AnyRef] = _
+    private[immutable] var display4: Array[AnyRef] = _
+    private[immutable] var display5: Array[AnyRef] = _
+
+    // used
+    private[immutable] final def initFrom[U](that: VectorPointer[U]): Unit = initFrom(that, that.depth)
+    
+    private[immutable] final def initFrom[U](that: VectorPointer[U], depth: Int) = {
+      this.depth = depth
+      (depth - 1) match {
+        case -1 =>
+        case 0 =>
+          display0 = that.display0
+        case 1 =>
+          display1 = that.display1
+          display0 = that.display0
+        case 2 =>
+          display2 = that.display2
+          display1 = that.display1
+          display0 = that.display0
+        case 3 =>
+          display3 = that.display3
+          display2 = that.display2
+          display1 = that.display1
+          display0 = that.display0
+        case 4 =>
+          display4 = that.display4
+          display3 = that.display3
+          display2 = that.display2
+          display1 = that.display1
+          display0 = that.display0
+        case 5 =>
+          display5 = that.display5
+          display4 = that.display4
+          display3 = that.display3
+          display2 = that.display2
+          display1 = that.display1
+          display0 = that.display0
+      }
+    }
+
+
+    // requires structure is at pos oldIndex = xor ^ index
+    private[immutable] final def getElem(index: Int, xor: Int): T = {
+      if (xor < (1 << 5)) { // level = 0
+        display0(index & 31).asInstanceOf[T]
+      } else
+      if (xor < (1 << 10)) { // level = 1
+        display1((index >> 5) & 31).asInstanceOf[Array[AnyRef]](index & 31).asInstanceOf[T]
+      } else
+      if (xor < (1 << 15)) { // level = 2
+        display2((index >> 10) & 31).asInstanceOf[Array[AnyRef]]((index >> 5) & 31).asInstanceOf[Array[AnyRef]](index & 31).asInstanceOf[T]
+      } else
+      if (xor < (1 << 20)) { // level = 3
+        display3((index >> 15) & 31).asInstanceOf[Array[AnyRef]]((index >> 10) & 31).asInstanceOf[Array[AnyRef]]((index >> 5) & 31).asInstanceOf[Array[AnyRef]](index & 31).asInstanceOf[T]
+      } else
+      if (xor < (1 << 25)) { // level = 4
+        display4((index >> 20) & 31).asInstanceOf[Array[AnyRef]]((index >> 15) & 31).asInstanceOf[Array[AnyRef]]((index >> 10) & 31).asInstanceOf[Array[AnyRef]]((index >> 5) & 31).asInstanceOf[Array[AnyRef]](index & 31).asInstanceOf[T]
+      } else
+      if (xor < (1 << 30)) { // level = 5
+        display5((index >> 25) & 31).asInstanceOf[Array[AnyRef]]((index >> 20) & 31).asInstanceOf[Array[AnyRef]]((index >> 15) & 31).asInstanceOf[Array[AnyRef]]((index >> 10) & 31).asInstanceOf[Array[AnyRef]]((index >> 5) & 31).asInstanceOf[Array[AnyRef]](index & 31).asInstanceOf[T]
+      } else { // level = 6
+        throw new IllegalArgumentException()
+      }
+    }
+
+
+    // go to specific position
+    // requires structure is at pos oldIndex = xor ^ index,
+    // ensures structure is at pos index
+    private[immutable] final def gotoPos(index: Int, xor: Int): Unit = {
+      if (xor < (1 << 5)) { // level = 0 (could maybe removed)
+      } else
+      if (xor < (1 << 10)) { // level = 1
+        display0 = display1((index >> 5) & 31).asInstanceOf[Array[AnyRef]]
+      } else
+      if (xor < (1 << 15)) { // level = 2
+        display1 = display2((index >> 10) & 31).asInstanceOf[Array[AnyRef]]
+        display0 = display1((index >>  5) & 31).asInstanceOf[Array[AnyRef]]
+      } else
+      if (xor < (1 << 20)) { // level = 3
+        display2 = display3((index >> 15) & 31).asInstanceOf[Array[AnyRef]]
+        display1 = display2((index >> 10) & 31).asInstanceOf[Array[AnyRef]]
+        display0 = display1((index >>  5) & 31).asInstanceOf[Array[AnyRef]]
+      } else
+      if (xor < (1 << 25)) { // level = 4
+        display3 = display4((index >> 20) & 31).asInstanceOf[Array[AnyRef]]
+        display2 = display3((index >> 15) & 31).asInstanceOf[Array[AnyRef]]
+        display1 = display2((index >> 10) & 31).asInstanceOf[Array[AnyRef]]
+        display0 = display1((index >>  5) & 31).asInstanceOf[Array[AnyRef]]
+      } else
+      if (xor < (1 << 30)) { // level = 5
+        display4 = display5((index >> 25) & 31).asInstanceOf[Array[AnyRef]]
+        display3 = display4((index >> 20) & 31).asInstanceOf[Array[AnyRef]]
+        display2 = display3((index >> 15) & 31).asInstanceOf[Array[AnyRef]]
+        display1 = display2((index >> 10) & 31).asInstanceOf[Array[AnyRef]]
+        display0 = display1((index >>  5) & 31).asInstanceOf[Array[AnyRef]]
+      } else { // level = 6
+        throw new IllegalArgumentException()
+      }
+    }
+
+
+
+    // USED BY ITERATOR
+
+    // xor: oldIndex ^ index
+    private[immutable] final def gotoNextBlockStart(index: Int, xor: Int): Unit = { // goto block start pos
+      if (xor < (1 << 10)) { // level = 1
+        display0 = display1((index >> 5) & 31).asInstanceOf[Array[AnyRef]]
+      } else
+      if (xor < (1 << 15)) { // level = 2
+        display1 = display2((index >> 10) & 31).asInstanceOf[Array[AnyRef]]
+        display0 = display1(0).asInstanceOf[Array[AnyRef]]
+      } else
+      if (xor < (1 << 20)) { // level = 3
+        display2 = display3((index >> 15) & 31).asInstanceOf[Array[AnyRef]]
+        display1 = display2(0).asInstanceOf[Array[AnyRef]]
+        display0 = display1(0).asInstanceOf[Array[AnyRef]]
+      } else
+      if (xor < (1 << 25)) { // level = 4
+        display3 = display4((index >> 20) & 31).asInstanceOf[Array[AnyRef]]
+        display2 = display3(0).asInstanceOf[Array[AnyRef]]
+        display1 = display2(0).asInstanceOf[Array[AnyRef]]
+        display0 = display1(0).asInstanceOf[Array[AnyRef]]
+      } else
+      if (xor < (1 << 30)) { // level = 5
+        display4 = display5((index >> 25) & 31).asInstanceOf[Array[AnyRef]]
+        display3 = display4(0).asInstanceOf[Array[AnyRef]]
+        display2 = display3(0).asInstanceOf[Array[AnyRef]]
+        display1 = display2(0).asInstanceOf[Array[AnyRef]]
+        display0 = display1(0).asInstanceOf[Array[AnyRef]]
+      } else { // level = 6
+        throw new IllegalArgumentException()
+      }
+    }
+
+    // USED BY BUILDER
+
+    // xor: oldIndex ^ index
+    private[immutable] final def gotoNextBlockStartWritable(index: Int, xor: Int): Unit = { // goto block start pos
+      if (xor < (1 << 10)) { // level = 1
+        if (depth == 1) { display1 = new Array(32); display1(0) = display0; depth+=1}
+        display0 = new Array(32)
+        display1((index >>  5) & 31) = display0
+      } else
+      if (xor < (1 << 15)) { // level = 2
+        if (depth == 2) { display2 = new Array(32); display2(0) = display1; depth+=1}
+        display0 = new Array(32)
+        display1 = new Array(32)
+        display1((index >>  5) & 31) = display0
+        display2((index >> 10) & 31) = display1
+      } else
+      if (xor < (1 << 20)) { // level = 3
+        if (depth == 3) { display3 = new Array(32); display3(0) = display2; depth+=1}
+        display0 = new Array(32)
+        display1 = new Array(32)
+        display2 = new Array(32)
+        display1((index >>  5) & 31) = display0
+        display2((index >> 10) & 31) = display1
+        display3((index >> 15) & 31) = display2
+      } else
+      if (xor < (1 << 25)) { // level = 4
+        if (depth == 4) { display4 = new Array(32); display4(0) = display3; depth+=1}
+        display0 = new Array(32)
+        display1 = new Array(32)
+        display2 = new Array(32)
+        display3 = new Array(32)
+        display1((index >>  5) & 31) = display0
+        display2((index >> 10) & 31) = display1
+        display3((index >> 15) & 31) = display2
+        display4((index >> 20) & 31) = display3
+      } else
+      if (xor < (1 << 30)) { // level = 5
+        if (depth == 5) { display5 = new Array(32); display5(0) = display4; depth+=1}
+        display0 = new Array(32)
+        display1 = new Array(32)
+        display2 = new Array(32)
+        display3 = new Array(32)
+        display4 = new Array(32)
+        display1((index >>  5) & 31) = display0
+        display2((index >> 10) & 31) = display1
+        display3((index >> 15) & 31) = display2
+        display4((index >> 20) & 31) = display3
+        display5((index >> 25) & 31) = display4
+      } else { // level = 6
+        throw new IllegalArgumentException()
+      }
+    }
+
+
+
+    // STUFF BELOW USED BY APPEND / UPDATE
+
+    private[immutable] final def copyOf(a: Array[AnyRef]) = {
+      //println("copy")
+      if (a eq null) println ("NULL")
+      val b = new Array[AnyRef](a.length)
+      Platform.arraycopy(a, 0, b, 0, a.length)
+      b
+    }
+
+    private[immutable] final def nullSlotAndCopy(array: Array[AnyRef], index: Int) = {
+      //println("copy and null")
+      val x = array(index)
+      array(index) = null
+      copyOf(x.asInstanceOf[Array[AnyRef]])
+    }
+
+
+    // make sure there is no aliasing
+    // requires structure is at pos index
+    // ensures structure is clean and at pos index and writable at all levels except 0
+
+    private[immutable] final def stabilize(index: Int) = (depth - 1) match {
+      case 5 =>
+        display5 = copyOf(display5)
+        display4 = copyOf(display4)
+        display3 = copyOf(display3)
+        display2 = copyOf(display2)
+        display1 = copyOf(display1)
+        display5((index >> 25) & 31) = display4
+        display4((index >> 20) & 31) = display3
+        display3((index >> 15) & 31) = display2
+        display2((index >> 10) & 31) = display1
+        display1((index >>  5) & 31) = display0
+      case 4 =>
+        display4 = copyOf(display4)
+        display3 = copyOf(display3)
+        display2 = copyOf(display2)
+        display1 = copyOf(display1)
+        display4((index >> 20) & 31) = display3
+        display3((index >> 15) & 31) = display2
+        display2((index >> 10) & 31) = display1
+        display1((index >>  5) & 31) = display0
+      case 3 =>
+        display3 = copyOf(display3)
+        display2 = copyOf(display2)
+        display1 = copyOf(display1)
+        display3((index >> 15) & 31) = display2
+        display2((index >> 10) & 31) = display1
+        display1((index >>  5) & 31) = display0
+      case 2 =>
+        display2 = copyOf(display2)
+        display1 = copyOf(display1)
+        display2((index >> 10) & 31) = display1
+        display1((index >>  5) & 31) = display0
+      case 1 =>
+        display1 = copyOf(display1)
+        display1((index >>  5) & 31) = display0
+      case 0 =>
+    }
+
+
+
+    /// USED IN UPDATE AND APPEND BACK
+    
+    // prepare for writing at an existing position
+
+    // requires structure is clean and at pos oldIndex = xor ^ newIndex,
+    // ensures structure is dirty and at pos newIndex and writable at level 0
+    private[immutable] final def gotoPosWritable0(newIndex: Int, xor: Int): Unit = (depth - 1) match {
+      case 5 => 
+        display5 = copyOf(display5)
+        display4 = nullSlotAndCopy(display5, (newIndex >> 25) & 31).asInstanceOf[Array[AnyRef]]
+        display3 = nullSlotAndCopy(display4, (newIndex >> 20) & 31).asInstanceOf[Array[AnyRef]]
+        display2 = nullSlotAndCopy(display3, (newIndex >> 15) & 31).asInstanceOf[Array[AnyRef]]
+        display1 = nullSlotAndCopy(display2, (newIndex >> 10) & 31).asInstanceOf[Array[AnyRef]]
+        display0 = nullSlotAndCopy(display1, (newIndex >>  5) & 31).asInstanceOf[Array[AnyRef]]
+      case 4 => 
+        display4 = copyOf(display4)
+        display3 = nullSlotAndCopy(display4, (newIndex >> 20) & 31).asInstanceOf[Array[AnyRef]]
+        display2 = nullSlotAndCopy(display3, (newIndex >> 15) & 31).asInstanceOf[Array[AnyRef]]
+        display1 = nullSlotAndCopy(display2, (newIndex >> 10) & 31).asInstanceOf[Array[AnyRef]]
+        display0 = nullSlotAndCopy(display1, (newIndex >>  5) & 31).asInstanceOf[Array[AnyRef]]
+      case 3 => 
+        display3 = copyOf(display3)
+        display2 = nullSlotAndCopy(display3, (newIndex >> 15) & 31).asInstanceOf[Array[AnyRef]]
+        display1 = nullSlotAndCopy(display2, (newIndex >> 10) & 31).asInstanceOf[Array[AnyRef]]
+        display0 = nullSlotAndCopy(display1, (newIndex >>  5) & 31).asInstanceOf[Array[AnyRef]]
+      case 2 => 
+        display2 = copyOf(display2)
+        display1 = nullSlotAndCopy(display2, (newIndex >> 10) & 31).asInstanceOf[Array[AnyRef]]
+        display0 = nullSlotAndCopy(display1, (newIndex >>  5) & 31).asInstanceOf[Array[AnyRef]]
+      case 1 => 
+        display1 = copyOf(display1)
+        display0 = nullSlotAndCopy(display1, (newIndex >>  5) & 31).asInstanceOf[Array[AnyRef]]
+      case 0 => 
+        display0 = copyOf(display0)
+    }
+    
+    
+    // requires structure is dirty and at pos oldIndex,
+    // ensures structure is dirty and at pos newIndex and writable at level 0
+    private[immutable] final def gotoPosWritable1(oldIndex: Int, newIndex: Int, xor: Int): Unit = {
+      if (xor < (1 <<  5)) { // level = 0
+        display0 = copyOf(display0)
+      } else
+      if (xor < (1 << 10)) { // level = 1
+        display1 = copyOf(display1)
+        display1((oldIndex >> 5) & 31) = display0
+        display0 = nullSlotAndCopy(display1, (newIndex >>  5) & 31)
+      } else                                                                               
+      if (xor < (1 << 15)) { // level = 2                                                  
+        display1 = copyOf(display1)
+        display2 = copyOf(display2)
+        display1((oldIndex >>  5) & 31) = display0                                         
+        display2((oldIndex >> 10) & 31) = display1
+        display1 = nullSlotAndCopy(display2, (newIndex >> 10) & 31).asInstanceOf[Array[AnyRef]]
+        display0 = nullSlotAndCopy(display1, (newIndex >>  5) & 31).asInstanceOf[Array[AnyRef]]
+      } else                                                                               
+      if (xor < (1 << 20)) { // level = 3                                                  
+        display1 = copyOf(display1)
+        display2 = copyOf(display2)
+        display3 = copyOf(display3)
+        display1((oldIndex >>  5) & 31) = display0                                         
+        display2((oldIndex >> 10) & 31) = display1                                         
+        display3((oldIndex >> 15) & 31) = display2                                         
+        display2 = nullSlotAndCopy(display3, (newIndex >> 15) & 31).asInstanceOf[Array[AnyRef]]
+        display1 = nullSlotAndCopy(display2, (newIndex >> 10) & 31).asInstanceOf[Array[AnyRef]]
+        display0 = nullSlotAndCopy(display1, (newIndex >>  5) & 31).asInstanceOf[Array[AnyRef]]
+      } else                                                                               
+      if (xor < (1 << 25)) { // level = 4                                                  
+        display1 = copyOf(display1)
+        display2 = copyOf(display2)
+        display3 = copyOf(display3)
+        display4 = copyOf(display4)
+        display1((oldIndex >>  5) & 31) = display0                                         
+        display2((oldIndex >> 10) & 31) = display1                                         
+        display3((oldIndex >> 15) & 31) = display2                                         
+        display4((oldIndex >> 20) & 31) = display3                                         
+        display3 = nullSlotAndCopy(display4, (newIndex >> 20) & 31).asInstanceOf[Array[AnyRef]]
+        display2 = nullSlotAndCopy(display3, (newIndex >> 15) & 31).asInstanceOf[Array[AnyRef]]
+        display1 = nullSlotAndCopy(display2, (newIndex >> 10) & 31).asInstanceOf[Array[AnyRef]]
+        display0 = nullSlotAndCopy(display1, (newIndex >>  5) & 31).asInstanceOf[Array[AnyRef]]
+      } else                                                                               
+      if (xor < (1 << 30)) { // level = 5                                                  
+        display1 = copyOf(display1)
+        display2 = copyOf(display2)
+        display3 = copyOf(display3)
+        display4 = copyOf(display4)
+        display5 = copyOf(display5)
+        display1((oldIndex >>  5) & 31) = display0                                         
+        display2((oldIndex >> 10) & 31) = display1                                         
+        display3((oldIndex >> 15) & 31) = display2                                         
+        display4((oldIndex >> 20) & 31) = display3                                         
+        display5((oldIndex >> 25) & 31) = display4                                         
+        display4 = nullSlotAndCopy(display5, (newIndex >> 25) & 31).asInstanceOf[Array[AnyRef]]
+        display3 = nullSlotAndCopy(display4, (newIndex >> 20) & 31).asInstanceOf[Array[AnyRef]]
+        display2 = nullSlotAndCopy(display3, (newIndex >> 15) & 31).asInstanceOf[Array[AnyRef]]
+        display1 = nullSlotAndCopy(display2, (newIndex >> 10) & 31).asInstanceOf[Array[AnyRef]]
+        display0 = nullSlotAndCopy(display1, (newIndex >>  5) & 31).asInstanceOf[Array[AnyRef]]
+      } else { // level = 6
+        throw new IllegalArgumentException()
+      }
+    }
+
+
+    // USED IN DROP
+    
+    private[immutable] final def copyRange(array: Array[AnyRef], oldLeft: Int, newLeft: Int) = {
+      val elems = new Array[AnyRef](32)
+      Platform.arraycopy(array, oldLeft, elems, newLeft, 32 - math.max(newLeft,oldLeft))
+      elems
+    }
+
+
+
+
+    // USED IN APPEND
+    // create a new block at the bottom level (and possibly nodes on its path) and prepares for writing
+
+    // requires structure is clean and at pos oldIndex,
+    // ensures structure is dirty and at pos newIndex and writable at level 0
+    private[immutable] final def gotoFreshPosWritable0(oldIndex: Int, newIndex: Int, xor: Int): Unit = { // goto block start pos
+      if (xor < (1 << 5)) { // level = 0
+        //println("XXX clean with low xor")
+      } else
+      if (xor < (1 << 10)) { // level = 1
+        if (depth == 1) {
+          display1 = new Array(32)
+          display1((oldIndex >>  5) & 31) = display0
+          depth +=1
+        }
+        display0 = new Array(32)
+      } else
+      if (xor < (1 << 15)) { // level = 2
+        if (depth == 2) {
+          display2 = new Array(32)
+          display2((oldIndex >> 10) & 31) = display1
+          depth +=1
+        }
+        display1 = display2((newIndex >> 10) & 31).asInstanceOf[Array[AnyRef]]
+        if (display1 == null) display1 = new Array(32)
+        display0 = new Array(32)
+      } else
+      if (xor < (1 << 20)) { // level = 3
+        if (depth == 3) {
+          display3 = new Array(32)
+          display3((oldIndex >> 15) & 31) = display2
+          display2 = new Array(32)
+          display1 = new Array(32)
+          depth +=1
+        }
+        display2 = display3((newIndex >> 15) & 31).asInstanceOf[Array[AnyRef]]
+        if (display2 == null) display2 = new Array(32)
+        display1 = display2((newIndex >> 10) & 31).asInstanceOf[Array[AnyRef]]
+        if (display1 == null) display1 = new Array(32)
+        display0 = new Array(32)
+      } else
+      if (xor < (1 << 25)) { // level = 4
+        if (depth == 4) {
+          display4 = new Array(32)
+          display4((oldIndex >> 20) & 31) = display3
+          display3 = new Array(32)
+          display2 = new Array(32)
+          display1 = new Array(32)
+          depth +=1
+        }
+        display3 = display4((newIndex >> 20) & 31).asInstanceOf[Array[AnyRef]]
+        if (display3 == null) display3 = new Array(32)
+        display2 = display3((newIndex >> 15) & 31).asInstanceOf[Array[AnyRef]]
+        if (display2 == null) display2 = new Array(32)
+        display1 = display2((newIndex >> 10) & 31).asInstanceOf[Array[AnyRef]]
+        if (display1 == null) display1 = new Array(32)
+        display0 = new Array(32)
+      } else
+      if (xor < (1 << 30)) { // level = 5
+        if (depth == 5) {
+          display5 = new Array(32)
+          display5((oldIndex >>  25) & 31) = display4
+          display4 = new Array(32)
+          display3 = new Array(32)
+          display2 = new Array(32)
+          display1 = new Array(32)
+          depth +=1
+        }
+        display4 = display5((newIndex >> 20) & 31).asInstanceOf[Array[AnyRef]]
+        if (display4 == null) display4 = new Array(32)
+        display3 = display4((newIndex >> 20) & 31).asInstanceOf[Array[AnyRef]]
+        if (display3 == null) display3 = new Array(32)
+        display2 = display3((newIndex >> 15) & 31).asInstanceOf[Array[AnyRef]]
+        if (display2 == null) display2 = new Array(32)
+        display1 = display2((newIndex >> 10) & 31).asInstanceOf[Array[AnyRef]]
+        if (display1 == null) display1 = new Array(32)
+        display0 = new Array(32)
+      } else { // level = 6
+        throw new IllegalArgumentException()
+      }
+    }
+
+
+    // requires structure is dirty and at pos oldIndex,
+    // ensures structure is dirty and at pos newIndex and writable at level 0
+    private[immutable] final def gotoFreshPosWritable1(oldIndex: Int, newIndex: Int, xor: Int): Unit = {
+      stabilize(oldIndex)
+      gotoFreshPosWritable0(oldIndex, newIndex, xor)
+    }
+
+
+    
+    
+    // DEBUG STUFF
+
+    private[immutable] def debug(): Unit = {
+      return
+/*
+      //println("DISPLAY 5: " + display5 + " ---> " + (if (display5 ne null) display5.map(x=> if (x eq null) "." else x + "->" +x.asInstanceOf[Array[AnyRef]].mkString("")).mkString(" ") else "null"))
+      //println("DISPLAY 4: " + display4 + " ---> " + (if (display4 ne null) display4.map(x=> if (x eq null) "." else x + "->" +x.asInstanceOf[Array[AnyRef]].mkString("")).mkString(" ") else "null"))
+      //println("DISPLAY 3: " + display3 + " ---> " + (if (display3 ne null) display3.map(x=> if (x eq null) "." else x + "->" +x.asInstanceOf[Array[AnyRef]].mkString("")).mkString(" ") else "null"))
+      //println("DISPLAY 2: " + display2 + " ---> " + (if (display2 ne null) display2.map(x=> if (x eq null) "." else x + "->" +x.asInstanceOf[Array[AnyRef]].mkString("")).mkString(" ") else "null"))
+      //println("DISPLAY 1: " + display1 + " ---> " + (if (display1 ne null) display1.map(x=> if (x eq null) "." else x + "->" +x.asInstanceOf[Array[AnyRef]].mkString("")).mkString(" ") else "null"))
+      //println("DISPLAY 0: " + display0 + " ---> " + (if (display0 ne null) display0.map(x=> if (x eq null) "." else x.toString).mkString(" ") else "null"))
+*/
+      //println("DISPLAY 5: " + (if (display5 ne null) display5.map(x=> if (x eq null) "." else x.asInstanceOf[Array[AnyRef]].deepMkString("[","","]")).mkString(" ") else "null"))
+      //println("DISPLAY 4: " + (if (display4 ne null) display4.map(x=> if (x eq null) "." else x.asInstanceOf[Array[AnyRef]].deepMkString("[","","]")).mkString(" ") else "null"))
+      //println("DISPLAY 3: " + (if (display3 ne null) display3.map(x=> if (x eq null) "." else x.asInstanceOf[Array[AnyRef]].deepMkString("[","","]")).mkString(" ") else "null"))
+      //println("DISPLAY 2: " + (if (display2 ne null) display2.map(x=> if (x eq null) "." else x.asInstanceOf[Array[AnyRef]].deepMkString("[","","]")).mkString(" ") else "null"))
+      //println("DISPLAY 1: " + (if (display1 ne null) display1.map(x=> if (x eq null) "." else x.asInstanceOf[Array[AnyRef]].deepMkString("[","","]")).mkString(" ") else "null"))
+      //println("DISPLAY 0: " + (if (display0 ne null) display0.map(x=> if (x eq null) "." else x.toString).mkString(" ") else "null"))
+    }
+
+
+}
+
diff --git a/src/library/scala/collection/immutable/WrappedString.scala b/src/library/scala/collection/immutable/WrappedString.scala
new file mode 100644
index 0000000..0dbf720
--- /dev/null
+++ b/src/library/scala/collection/immutable/WrappedString.scala
@@ -0,0 +1,50 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+package immutable
+
+import generic._
+import mutable.{Builder, StringBuilder}
+import scala.util.matching.Regex
+
+/**
+ *  This class serves as a wrapper augmenting `String`s with all the operations
+ *  found in indexed sequences.
+ *  
+ *  The difference between this class and `StringOps` is that calling transformer
+ *  methods such as `filter` and `map` will yield an object of type `WrappedString` 
+ *  rather than a `String`.
+ *  
+ *  @param self    a string contained within this wrapped string
+ *  
+ *  @since 2.8
+ *  @define Coll WrappedString
+ *  @define coll wrapped string
+ */
+class WrappedString(override val self: String) extends IndexedSeq[Char] with StringLike[WrappedString] with Proxy {
+
+  override protected[this] def thisCollection: WrappedString = this
+  override protected[this] def toCollection(repr: WrappedString): WrappedString = repr
+
+  /** Creates a string builder buffer as builder for this class */
+  override protected[this] def newBuilder = WrappedString.newBuilder
+  
+  override def slice(from: Int, until: Int): WrappedString = 
+    new WrappedString(self.substring(from max 0, until min self.length))
+}
+
+/** A companion object for wrapped strings.
+ *  
+ *  @since 2.8
+ */
+object WrappedString {
+  def newBuilder: Builder[Char, WrappedString] = new StringBuilder() mapResult (new WrappedString(_))
+}
diff --git a/src/library/scala/collection/interfaces/IterableMethods.scala b/src/library/scala/collection/interfaces/IterableMethods.scala
new file mode 100644
index 0000000..c9649f8
--- /dev/null
+++ b/src/library/scala/collection/interfaces/IterableMethods.scala
@@ -0,0 +1,36 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+package scala.collection
+package interfaces
+
+import generic._
+import mutable.Buffer
+import scala.reflect.ClassManifest
+import annotation.unchecked.uncheckedVariance
+
+/**
+ * @since 2.8
+ */
+trait IterableMethods[+A, +This <: IterableLike[A, This] with Iterable[A]] extends TraversableMethods[A, This]
+{
+  // abstract
+  def iterator: Iterator[A]
+
+  // concrete
+  def dropRight(n: Int): Iterable[A]
+  def sameElements[B >: A](that: Iterable[B]): Boolean
+  def sortWith(lt: (A, A) => Boolean)(implicit m: ClassManifest[A @uncheckedVariance]): This
+  def takeRight(n: Int): Iterable[A]
+  def zipAll[B, A1 >: A, That](that: Iterable[B], e1: A1, e2: B)(implicit bf: CanBuildFrom[This, (A1, B), That]): That
+  def zipWithIndex[A1 >: A, That](implicit bf: CanBuildFrom[This, (A1, Int), That]): That
+  def zip[A1 >: A, B, That](that: Iterable[B])(implicit bf: CanBuildFrom[This, (A1, B), That]): That
+  
+  override def view: IterableView[A, This]
+  override def view(from: Int, until: Int): IterableView[A, This]
+}
diff --git a/src/library/scala/collection/interfaces/MapMethods.scala b/src/library/scala/collection/interfaces/MapMethods.scala
new file mode 100644
index 0000000..fd6e7ad
--- /dev/null
+++ b/src/library/scala/collection/interfaces/MapMethods.scala
@@ -0,0 +1,44 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+package scala.collection
+package interfaces
+
+import generic._
+
+/**
+ * @since 2.8
+ */
+trait MapMethods[A, +B, +This <: MapLike[A, B, This] with Map[A, B]]
+extends IterableMethods[(A, B), This]
+with SubtractableMethods[A, This]
+{
+  // abstract
+  def empty: This
+  def get(key: A): Option[B]
+  def iterator: Iterator[(A, B)]
+  def + [B1 >: B] (kv: (A, B1)): Map[A, B1]
+  def - (key: A): This
+
+  // concrete
+  def getOrElse[B1 >: B](key: A, default: => B1): B1
+  def apply(key: A): B
+  def contains(key: A): Boolean
+  def isDefinedAt(key: A): Boolean
+  def keys: Iterable[A]
+  def keysIterator: Iterator[A]
+  def keySet: Set[A]
+  def values: Iterable[B]
+  def valuesIterator: Iterator[B]
+  def default(key: A): B
+  def filterKeys(p: A => Boolean): DefaultMap[A, B]
+  def mapValues[C](f: B => C): DefaultMap[A, C]
+  def updated [B1 >: B](key: A, value: B1): Map[A, B1]
+  def + [B1 >: B] (elem1: (A, B1), elem2: (A, B1), elems: (A, B1) *): Map[A, B1]
+  def ++[B1 >: B](xs: TraversableOnce[(A, B1)]): Map[A, B1]
+}
diff --git a/src/library/scala/collection/interfaces/SeqMethods.scala b/src/library/scala/collection/interfaces/SeqMethods.scala
new file mode 100644
index 0000000..ce5df18
--- /dev/null
+++ b/src/library/scala/collection/interfaces/SeqMethods.scala
@@ -0,0 +1,57 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+package scala.collection
+package interfaces
+
+import generic._
+import mutable.Buffer
+import scala.reflect.ClassManifest
+
+/**
+ * @since 2.8
+ */
+trait SeqMethods[+A, +This <: SeqLike[A, This] with Seq[A]] extends IterableMethods[A, This]
+{
+  // abstract
+  def apply(idx: Int): A
+  def length: Int
+  
+  def contains(elem: Any): Boolean
+  def diff[B >: A, That](that: Seq[B]): This
+  def endsWith[B](that: Seq[B]): Boolean
+  def indexOfSlice[B >: A](that: Seq[B]): Int
+  def indexOfSlice[B >: A](that: Seq[B], fromIndex: Int): Int
+  def indexOf[B >: A](elem: B): Int
+  def indexOf[B >: A](elem: B, from: Int): Int
+  def indexWhere(p: A => Boolean): Int
+  def indexWhere(p: A => Boolean, from: Int): Int
+  def indices: Range
+  def intersect[B >: A, That](that: Seq[B]): This
+  def isDefinedAt(x: Int): Boolean
+  def lastIndexOfSlice[B >: A](that: Seq[B]): Int
+  def lastIndexOfSlice[B >: A](that: Seq[B], fromIndex: Int): Int
+  def lastIndexOf[B >: A](elem: B): Int
+  def lastIndexOf[B >: A](elem: B, end: Int): Int
+  def lastIndexWhere(p: A => Boolean): Int
+  def lastIndexWhere(p: A => Boolean, end: Int): Int
+  def lengthCompare(len: Int): Int
+  def padTo[B >: A, That](len: Int, elem: B)(implicit bf: CanBuildFrom[This, B, That]): That
+  def patch[B >: A, That](from: Int, patch: Seq[B], replaced: Int)(implicit bf: CanBuildFrom[This, B, That]): That 
+  def prefixLength(p: A => Boolean): Int
+  def distinct: This
+  def reverse: This
+  def reverseIterator: Iterator[A]
+  def segmentLength(p: A => Boolean, from: Int): Int
+  def startsWith[B](that: Seq[B]): Boolean
+  def startsWith[B](that: Seq[B], offset: Int): Boolean
+  def union[B >: A, That](that: Seq[B])(implicit bf: CanBuildFrom[This, B, That]): That
+  
+  override def view: SeqView[A, This]
+  override def view(from: Int, until: Int): SeqView[A, This]
+}
diff --git a/src/library/scala/collection/interfaces/SetMethods.scala b/src/library/scala/collection/interfaces/SetMethods.scala
new file mode 100644
index 0000000..e4b3a69
--- /dev/null
+++ b/src/library/scala/collection/interfaces/SetMethods.scala
@@ -0,0 +1,60 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+package scala.collection
+package interfaces
+
+import generic._
+import mutable.Buffer
+import scala.reflect.ClassManifest
+import annotation.unchecked.uncheckedVariance
+
+/**
+ * @since 2.8
+ */
+trait AddableMethods[A, +This <: Addable[A, This]] {
+  protected def repr: This
+  def +(elem: A): This
+  def + (elem1: A, elem2: A, elems: A*): This
+  def ++ (xs: TraversableOnce[A]): This
+}
+
+/**
+ * @since 2.8
+ */
+trait SubtractableMethods[A, +This <: Subtractable[A, This]] {
+  protected def repr: This
+  def -(elem: A): This
+  def -(elem1: A, elem2: A, elems: A*): This
+  def --(xs: TraversableOnce[A]): This
+}
+
+/**
+ * @since 2.8
+ */
+trait SetMethods[A, +This <: SetLike[A, This] with Set[A]]
+extends IterableMethods[A, This]
+with AddableMethods[A, This]
+with SubtractableMethods[A, This]
+{
+  // abstract
+  def empty: This
+  def contains(elem: A): Boolean
+  def + (elem: A): This
+  def - (elem: A): This
+
+  // concrete
+  def apply(elem: A): Boolean
+  def intersect(that: Set[A]): This
+  def &(that: Set[A]): This
+  def union(that: Set[A]): This
+  def | (that: Set[A]): This
+  def diff(that: Set[A]): This
+  def &~(that: Set[A]): This
+  def subsetOf(that: Set[A]): Boolean  
+}
diff --git a/src/library/scala/collection/interfaces/TraversableMethods.scala b/src/library/scala/collection/interfaces/TraversableMethods.scala
new file mode 100644
index 0000000..7e92892
--- /dev/null
+++ b/src/library/scala/collection/interfaces/TraversableMethods.scala
@@ -0,0 +1,109 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+package scala.collection
+package interfaces
+
+import generic._
+import mutable.Buffer
+import scala.reflect.ClassManifest
+
+/**
+ * @since 2.8
+ */
+trait TraversableMethods[+A, +This <: TraversableLike[A, This] with Traversable[A]]
+{
+  // abstract
+  def foreach[U](f: A => U): Unit
+  
+  // maps/iteration
+  def flatMap[B, That](f: A => Traversable[B])(implicit bf: CanBuildFrom[This, B, That]): That
+  def map[B, That](f: A => B)(implicit bf: CanBuildFrom[This, B, That]): That
+  def collect[B, That](pf: PartialFunction[A, B])(implicit bf: CanBuildFrom[This, B, That]): That
+  def scanLeft[B, That](z: B)(op: (B, A) => B)(implicit bf: CanBuildFrom[This, B, That]): That // could be fold or new collection too - where to put it?
+  def scanRight[B, That](z: B)(op: (A, B) => B)(implicit bf: CanBuildFrom[This, B, That]): That
+  
+  // new collections
+  def ++[B >: A, That](xs: TraversableOnce[B])(implicit bf: CanBuildFrom[This, B, That]): That
+  def copyToArray[B >: A](xs: Array[B], start: Int): Unit
+  def copyToArray[B >: A](xs: Array[B], start: Int, len: Int): Unit
+  def copyToBuffer[B >: A](dest: Buffer[B]): Unit
+  
+  // conversions
+  def toArray[B >: A : ClassManifest]: Array[B]
+  def toIterable: Iterable[A]
+  def toList: List[A]
+  def toSeq: Seq[A]
+  def toSet[B >: A]: immutable.Set[B]
+  def toStream: Stream[A]
+  def toIndexedSeq[B >: A]: immutable.IndexedSeq[B]
+  def toBuffer[B >: A]: mutable.Buffer[B]
+  
+  // strings
+  def addString(b: StringBuilder): StringBuilder
+  def addString(b: StringBuilder, sep: String): StringBuilder
+  def addString(b: StringBuilder, start: String, sep: String, end: String): StringBuilder
+  def mkString(sep: String): String
+  def mkString(start: String, sep: String, end: String): String
+  def mkString: String
+  
+  // folds
+  def /: [B](z: B)(op: (B, A) => B): B
+  def :\ [B](z: B)(op: (A, B) => B): B
+  def foldLeft[B](z: B)(op: (B, A) => B): B
+  def foldRight[B](z: B)(op: (A, B) => B): B
+  def reduceLeftOption[B >: A](op: (B, A) => B): Option[B]
+  def reduceLeft[B >: A](op: (B, A) => B): B
+  def reduceRightOption[B >: A](op: (A, B) => B): Option[B]
+  def reduceRight[B >: A](op: (A, B) => B): B
+  
+  // conditions
+  def exists(p: A => Boolean): Boolean
+  def forall(p: A => Boolean): Boolean
+  def hasDefiniteSize: Boolean
+  def isEmpty: Boolean
+  def nonEmpty: Boolean  
+  
+  // element retrieval
+  def find(p: A => Boolean): Option[A]
+  def head: A
+  def headOption: Option[A]
+  def last: A
+  def lastOption: Option[A]
+  
+  // subcollections
+  def drop(n: Int): Traversable[A]
+  def dropWhile(p: A => Boolean): Traversable[A]
+  def filter(p: A => Boolean): Traversable[A]
+  def filterNot(p: A => Boolean): Traversable[A]
+  def init: Traversable[A]
+  def slice(from: Int, until: Int): Traversable[A]
+  def tail: Traversable[A]
+  def take(n: Int): Traversable[A]
+  def takeWhile(p: A => Boolean): Traversable[A]
+  
+  // subdivisions
+  def groupBy[K](f: A => K): Map[K, Traversable[A]]
+  def partition(p: A => Boolean): (Traversable[A], Traversable[A])
+  def span(p: A => Boolean): (Traversable[A], Traversable[A])
+  def splitAt(n: Int): (Traversable[A], Traversable[A])
+
+  // info
+  def count(p: A => Boolean): Int
+  def size: Int
+  def stringPrefix: String
+
+  // views
+  def view: TraversableView[A, This]
+  def view(from: Int, until: Int): TraversableView[A, This]
+
+  // def sum[B >: A](implicit num: Numeric[B]): B    
+  // def product[B >: A](implicit num: Numeric[B]): B   
+  // def min[B >: A](implicit cmp: Ordering[B]): A
+  // def max[B >: A](implicit cmp: Ordering[B]): A
+}
diff --git a/src/library/scala/collection/interfaces/TraversableOnceMethods.scala b/src/library/scala/collection/interfaces/TraversableOnceMethods.scala
new file mode 100644
index 0000000..ab444d1
--- /dev/null
+++ b/src/library/scala/collection/interfaces/TraversableOnceMethods.scala
@@ -0,0 +1,69 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+package scala.collection
+package interfaces
+
+import mutable.Buffer
+
+trait TraversableOnceMethods[+A] {
+  self: TraversableOnce[A] =>
+  
+  def foreach[U](f: A => U): Unit
+  protected[this] def reversed: TraversableOnce[A]
+  
+  // tests
+  def isEmpty: Boolean
+  def nonEmpty: Boolean
+  def hasDefiniteSize: Boolean
+  def isTraversableAgain: Boolean
+  
+  // applying a predicate
+  def forall(p: A => Boolean): Boolean
+  def exists(p: A => Boolean): Boolean
+  def find(p: A => Boolean): Option[A]
+  def count(p: A => Boolean): Int
+  
+  // folds
+  def /:[B](z: B)(op: (B, A) => B): B
+  def :\[B](z: B)(op: (A, B) => B): B
+  def foldLeft[B](z: B)(op: (B, A) => B): B
+  def foldRight[B](z: B)(op: (A, B) => B): B
+  def reduceLeft[B >: A](op: (B, A) => B): B
+  def reduceRight[B >: A](op: (A, B) => B): B
+  def reduceLeftOption[B >: A](op: (B, A) => B): Option[B]
+  def reduceRightOption[B >: A](op: (A, B) => B): Option[B]
+
+  def sum[B >: A](implicit num: Numeric[B]): B
+  def product[B >: A](implicit num: Numeric[B]): B
+  def min[B >: A](implicit cmp: Ordering[B]): A
+  def max[B >: A](implicit cmp: Ordering[B]): A
+
+  // copies and conversions
+  def copyToBuffer[B >: A](dest: Buffer[B]): Unit
+  def copyToArray[B >: A](xs: Array[B], start: Int, len: Int): Unit
+  def copyToArray[B >: A](xs: Array[B], start: Int): Unit
+  def copyToArray[B >: A](xs: Array[B]): Unit
+  
+  def toArray[B >: A : ClassManifest]: Array[B]
+  def toIterable: Iterable[A]
+  def toIterator: Iterator[A]
+  def toList: List[A]
+  def toMap[T, U](implicit ev: A <:< (T, U)): immutable.Map[T, U]
+  def toSet[B >: A]: immutable.Set[B]
+  def toStream: Stream[A]
+  def toTraversable: Traversable[A]
+  
+  def mkString(start: String, sep: String, end: String): String
+  def mkString(sep: String): String
+  def mkString: String
+  
+  def addString(buf: StringBuilder, start: String, sep: String, end: String): StringBuilder
+  def addString(buf: StringBuilder, sep: String): StringBuilder
+  def addString(buf: StringBuilder): StringBuilder
+}
diff --git a/src/library/scala/collection/jcl/ArrayList.scala b/src/library/scala/collection/jcl/ArrayList.scala
deleted file mode 100644
index f97828f..0000000
--- a/src/library/scala/collection/jcl/ArrayList.scala
+++ /dev/null
@@ -1,21 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: ArrayList.scala 16894 2009-01-13 13:09:41Z cunei $
-
-package scala.collection.jcl;
-
-/** Creates a buffer backed by a Java array list.
- *
- *  @author Sean McDirmid
- */
-class ArrayList[A](override val underlying : java.util.ArrayList[A]) extends BufferWrapper[A]  {
-  def this() = this(new java.util.ArrayList[A]);
-  override def clone: ArrayList[A] =
-    new ArrayList[A](underlying.clone().asInstanceOf[java.util.ArrayList[A]])
-}
diff --git a/src/library/scala/collection/jcl/Buffer.scala b/src/library/scala/collection/jcl/Buffer.scala
deleted file mode 100644
index 53edeaf..0000000
--- a/src/library/scala/collection/jcl/Buffer.scala
+++ /dev/null
@@ -1,229 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: Buffer.scala 16894 2009-01-13 13:09:41Z cunei $
-
-package scala.collection.jcl;
-
-/** A mutable sequence that supports element insertion and update.
- *
- *  @author Sean McDirmid
- */
-trait Buffer[A] extends RandomAccessSeq.Mutable[A] with Ranged[Int,A] with MutableSeq[A] with Collection[A] {
-  final protected type SortedSelf = Buffer[A];
-
-  override def projection : Buffer.Projection[A] = new Buffer.Projection[A] {
-    override def elements = Buffer.this.elements
-    override def length = Buffer.this.length
-    override def apply(idx : Int) = Buffer.this.apply(idx)
-    override def transform(f : A => A) = Buffer.this.transform(f)
-  }
-  
-  protected class DefaultBufferIterator extends DefaultSeqIterator with BufferIterator[Int,A] {
-    override def set(a : A) = {
-      if (index == 0) throw new NoSuchElementException
-      Buffer.this.set(index - 1, a)
-    }
-    override def add(a : A) = {
-      Buffer.this.add(index, a)
-    }
-  }
-  override def elements : BufferIterator[Int,A] = new DefaultBufferIterator
-
-  /** The first index of a buffer is 0. */
-  override def firstKey = 0;
-
-  /** The last index of a buffer is its size - 1. */
-  override def lastKey = size - 1;
-
-  /** Indices are compared through subtraction. */
-  final def compare(k0 : Int, k1 : Int) = k0 - k1;
-
-  /** Removes the element at index <code>idx</code> */
-  def remove(idx : Int) = {
-    val i = elements;
-    val ret = i.seek(idx); i.remove; ret;
-  }
-  /** Removes N elements from index <code>idx</code> */
-  def remove(idx : Int, length : Int) = {
-    val i = elements
-    i.seek(idx)
-    for (j <- 0.until(length)) i.remove
-  }
-  /** replaces */
-  def replace(from : Int, length : Int, added : Seq[A]) = {
-    val min = if (length < added.length) length else added.length
-    val i = added.elements
-    var j = 0
-    while (j < length && i.hasNext) {
-      set(from + j, i.next); j = j + 1
-    }
-    assert(j == min)
-    if (i.hasNext) {
-      val slice = added.drop(length)
-      assert(!slice.isEmpty)
-      addAll(from + min, slice)
-    } else if (j < length) {
-      assert(length > min)
-      remove(from + min, length - min)
-    }
-  }
-
-  /** Replaces the element at index "idx" with "a."
-    * @returns the element replaced.
-    */
-  def set(idx : Int, a : A) : A = {
-    val i = elements;
-    val ret = i.seek(idx); i.set(a); ret;
-  }
-
-  /** Equivalent to set except the replaced element is not returned. */
-  def update(idx : Int, a : A) : Unit = set(idx, a);
-
-  /** @returns always true. */
-  def add(a : A) : Boolean = {
-    val i = elements;
-    while (i.hasNext) i.next;
-    i.add(a);
-    true;
-  }
-
-  /** Inserts "a" into this buffer just before the element at index "idx." */
-  def add(idx: Int, a: A): Unit = {
-    val i = elements; i.seek(idx);
-    i.add(a);
-  }
-
-  /** Inserts all elements of <code>that</code> into this buffer just before
-   *  the element at index <code>idx</code>.
-   *
-   *  @param idx  ..
-   *  @param that ..
-   */
-  def addAll(idx: Int, that: Iterable[A]): Unit = {
-    val i = elements; i.seek(idx);
-    for (that <- that) {
-      i.add(that); i.next;
-    }
-  }
-
-  override def transform(f: A => A): Boolean = {
-    var changed = false;
-    val i = elements;
-    while (i.hasNext) {
-      val a0 = i.next;
-      val a1 = f(a0);
-      if (a0 != a1) {
-        i.set(a1); changed = true;
-      }
-    }
-    changed;
-  }
-  override def +(a : A) : this.type = super[Collection].+(a);
-  override def -=(a : A) = super[Collection].-=(a);
-  override def isEmpty = super[MutableSeq].isEmpty;
-  override def rangeImpl(from : Option[Int], until : Option[Int]) : Buffer[A] = new Range(from, until);
-  
-
-  protected class Range(var from : Option[Int], var until : Option[Int]) extends Buffer[A] {
-    if (from == None && until == None) throw new IllegalArgumentException;
-    if (from != None && until != None && !(from.get < until.get)) throw new IllegalArgumentException;
-    override def add(a : A) =
-      if (until == None) Buffer.this.add(a);
-      else {
-        Buffer.this.add(until.get, a);
-        true;
-      }
-    private def translate(idx : Int) = {
-      if (until != None && idx > until.get) throw new IllegalArgumentException;
-      else if (from != None) from.get + idx;
-      else idx;
-    }
-    override def apply(idx : Int) : A = Buffer.this.apply(translate(idx));
-    override def set(idx : Int, a : A) = Buffer.this.set(translate(idx), a);
-    override def add(idx : Int, a : A) = Buffer.this.add(translate(idx), a);
-    override def remove(idx : Int) = Buffer.this.remove(translate(idx));
-    override def length = {
-      if (until != None) {
-        if (from != None) until.get - from.get;
-        else until.get;
-      } else super.length;
-    }
-    override def elements : BufferIterator[Int,A] = new RangeIterator;
-    class RangeIterator extends BufferIterator[Int,A] {
-      val underlying = Buffer.this.elements;
-      if (from != None) underlying.seek(from.get);
-      def hasNext = underlying.hasNext &&
-        (until == None || underlying.nextIndex < until.get);
-      def hasPrevious = underlying.hasPrevious &&
-        (from == None || underlying.previousIndex >= from.get);
-      def next = {
-        if (until != None && underlying.nextIndex >= until.get) throw new NoSuchElementException;
-        underlying.next;
-      }
-      def previous = {
-        if (from != None && underlying.previousIndex < from.get) throw new NoSuchElementException;
-        underlying.previous;
-      }
-      def add(a : A) = {
-        if (until != None && underlying.nextIndex > until.get) throw new NoSuchElementException;
-        if (from != None && underlying.previousIndex < from.get) throw new NoSuchElementException;
-        underlying.add(a);
-        if (until != None) until = Some(until.get + 1);
-      }
-      def set(a : A) = {
-        if (until != None && underlying.nextIndex > until.get) throw new NoSuchElementException;
-        if (from != None && underlying.previousIndex < from.get) throw new NoSuchElementException;
-        underlying.set(a);
-      }
-      def remove = {
-        if (until != None && underlying.nextIndex > until.get) throw new NoSuchElementException;
-        if (from != None && underlying.previousIndex < from.get) throw new NoSuchElementException;
-        underlying.remove;
-      }
-      def nextIndex = {
-        val ret = underlying.nextIndex;
-        if (until != None && ret >= until.get) throw new NoSuchElementException;
-        if (from != None) ret - from.get;
-        else ret;
-      }
-      def previousIndex = {
-        val ret = underlying.previousIndex;
-        if (from != None && ret < from.get) throw new NoSuchElementException;
-        if (from != None) ret - from.get;
-        else ret;
-      }
-    }
-  }
-  /*
-  protected class Map[B](f : A => B) extends super.Map[B](f) with Buffer.Projection[B] {
-    override def elements = Buffer.this.elements.map[B](f);
-    //override def apply(idx : Int) = f(MutableSeq.this.apply(idx));
-    //override def size = length;
-  }
-  */
-}
-object Buffer {
-  def apply[T](list : java.util.List[T]) = new BufferWrapper[T] {
-    val underlying = list
-  }
-  
-  trait Projection0[A] extends MutableSeq.Projection[A] with RandomAccessSeq.Projection[A] {
-    override def projection : Projection0[A] = this
-    override def elements : SeqIterator[Int,A] = new DefaultSeqIterator
-    
-    protected class MapProjection[B](f : A => B) extends super.MapProjection[B](f) with Projection0[B] {
-      override def projection = this
-    }
-    override def map[B](f: A => B) : Projection0[B] = new MapProjection[B](f)
-  }
-  class Projection[A] extends Collection.Projection[A] with RandomAccessSeq.MutableProjection[A] with Projection0[A] with Buffer[A] {
-    override def elements : BufferIterator[Int,A] = new DefaultBufferIterator
-    override def projection : Buffer.Projection[A] = this
-  }
-}
diff --git a/src/library/scala/collection/jcl/BufferIterator.scala b/src/library/scala/collection/jcl/BufferIterator.scala
deleted file mode 100644
index 1731628..0000000
--- a/src/library/scala/collection/jcl/BufferIterator.scala
+++ /dev/null
@@ -1,31 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: BufferIterator.scala 16894 2009-01-13 13:09:41Z cunei $
-
-package scala.collection.jcl;
-
-/** An iterator for a buffer that supports element update and insertion.
- *
- *  @author Sean McDirmid
- */
-trait BufferIterator[K,A] extends SeqIterator[K,A] {
-
-  /** Sets the element before this iterator's cursor to "a."
-   *  Replaces either the last element returned by "next" or,
-   *  if previous was called,
-   *  the next element that would be return by "previous."
-   */
-  def set(a: A): Unit;
-
-  /** Inserts "a" after the iterator's cursor.
-   *  If next was last called, "a" is inserted after the element returned.
-   *  If previous was last called, "a" is inserted before the element returned. 
-   */
-  def add(a: A): Unit;
-}
diff --git a/src/library/scala/collection/jcl/BufferWrapper.scala b/src/library/scala/collection/jcl/BufferWrapper.scala
deleted file mode 100644
index 90c0acc..0000000
--- a/src/library/scala/collection/jcl/BufferWrapper.scala
+++ /dev/null
@@ -1,52 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: BufferWrapper.scala 16894 2009-01-13 13:09:41Z cunei $
-
-package scala.collection.jcl;
-
-/** Wraps Java lists.
- *
- *  @author Sean McDirmid
- */
-trait BufferWrapper[A] extends Buffer[A] with CollectionWrapper[A] {
-  def underlying : java.util.List[A];
-  override def elements : BufferIterator[Int,A] = new IteratorWrapper(underlying.listIterator);
-  override def remove(idx : Int) = underlying.remove(idx).asInstanceOf[A];
-  override def add(a : A) = underlying.add(a);
-  override def add(idx : Int, a : A) = underlying.add(idx,a);
-  override def addAll(idx : Int, that : Iterable[A]) = that match {
-  case that : CollectionWrapper[_] => underlying.addAll(idx, that.underlying); {}
-  case _ => super.addAll(idx, that);
-  }
-  override def indexOf(a : A) = {
-    val result = underlying.indexOf(a);
-    if (result == -1) None;
-    else Some(result);
-  }
-  override def apply(idx : Int) = underlying.get(idx).asInstanceOf[A];
-  override def set(idx : Int, a : A) = underlying.set(idx, a).asInstanceOf[A];
-  override def rangeImpl(from : Option[Int], until : Option[Int]) : Buffer[A] = new Range(from, until);
-  protected class Range(from : Option[Int], until : Option[Int]) extends super.Range(from,until) with BufferWrapper[A] {
-    val underlying = {
-      val fromi = if (from == None) 0 else from.get;
-      val toi = if (until == None) BufferWrapper.this.size else until.get;
-      BufferWrapper.this.underlying.subList(fromi, toi);
-    }
-    override def elements = super[BufferWrapper].elements;
-  }
-  class IteratorWrapper(underlying : java.util.ListIterator[A]) extends MutableIterator.Wrapper[A](underlying) with BufferIterator[Int,A] {
-    def add(a : A) = underlying.add(a);
-    def set(a : A) = underlying.set(a);
-    def hasPrevious = underlying.hasPrevious;
-    def previous = underlying.previous.asInstanceOf[A];
-    def previousIndex = underlying.previousIndex;
-    def nextIndex = underlying.nextIndex;
-  }
-  override def length = underlying.size;
-}
diff --git a/src/library/scala/collection/jcl/Collection.scala b/src/library/scala/collection/jcl/Collection.scala
deleted file mode 100644
index 6db93a3..0000000
--- a/src/library/scala/collection/jcl/Collection.scala
+++ /dev/null
@@ -1,67 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: Collection.scala 16894 2009-01-13 13:09:41Z cunei $
-
-package scala.collection.jcl;
-
-object Collection {
-  val DEFAULT_FILTER : Any => Boolean = x => true;
-  trait Projection[A] extends Collection[A] with MutableIterable.Projection[A] {
-    override def projection = this
-  }
-}
-
-/** Analogous to a Java collection.
- *
- *  @author Sean McDirmid
- */
-trait Collection[A] extends MutableIterable[A] {
-  /** Type-safe version of containsAll.
-   **
-   ** @author Sean McDirmid
-   **/
-  def hasAll(i: Iterable[A]): Boolean = i.forall(elements.has);
-
-  /** Adds "a" to the collection, return true if "a" is actually added. */
-  def add(a: A): Boolean;
-
-  /** Adds all elements in "i" to the collection, return true if any elements are added. */
-  def addAll(i: Iterable[A]): Boolean = {
-    var changed = false;
-    i.foreach(t => changed = add(t) || changed);
-    changed;
-  }
-  /** Operator shortcut for addAll. */
-  def ++(that: Iterable[A]): this.type = {
-    addAll(that); this;
-  }
-
-  /** removes "a" from the collection. */
-  def -=(a : A) : Unit = remove(a);
-
-  /** adds "a" from the collection. */
-  def +=(t : A) : Unit = add(t);
-
-  /** adds "a" from the collection. Useful for chaining. */
-  def +(t : A) : this.type = { add(t); this; }
-
-  /** Transforms each element of the collection in-place according to
-   *  <code>f</code>.
-   *
-   *  @param  f
-   *  @return <code>true</code> if the collection is actually updated.
-   */
-  def transform(f: A => A): Boolean
-  override def projection : Collection.Projection[A] = new Collection.Projection[A] {
-    override def elements = Collection.this.elements
-    override def size = Collection.this.size
-    override def add(a: A): Boolean = Collection.this.add(a)
-    override def transform(f : A => A) = Collection.this.transform(f);
-  }
-}
diff --git a/src/library/scala/collection/jcl/CollectionWrapper.scala b/src/library/scala/collection/jcl/CollectionWrapper.scala
deleted file mode 100644
index b5bc971..0000000
--- a/src/library/scala/collection/jcl/CollectionWrapper.scala
+++ /dev/null
@@ -1,43 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: CollectionWrapper.scala 16894 2009-01-13 13:09:41Z cunei $
-
-package scala.collection.jcl;
-
-/** Used to wrap Java collections in Scala.
- *
- *  @author Sean McDirmid
- */
-trait CollectionWrapper[A] extends Collection[A] with IterableWrapper[A] {
-  /** Override to specify the collection being accessed through this wrapper. 
-   ** Collection operations are then routed through the wrapped Java collection.
-   **/
-  def underlying : java.util.Collection[A];
-  override def has(a : A) = underlying.contains(a);
-  override def elements : MutableIterator[A] = super.elements;
-  override def size = underlying.size;
-
-  override def hasAll(that : Iterable[A]) = that match {
-  case that : CollectionWrapper[_] => 
-    val u = underlying;
-    u.containsAll(that.underlying);
-  case _ => super.hasAll(that);  
-  }
-  override def add(a : A) = underlying.add(a);
-  override def addAll(that : Iterable[A]) = that match {
-  case that : CollectionWrapper[_] => underlying.addAll(that.underlying);
-  case _ => super.addAll(that);
-  }
-  override def toString = underlying.toString;
-  override def hashCode = underlying.hashCode;
-  override def equals(that : Any) = that match {
-    case that: CollectionWrapper[_] => underlying == that.underlying;
-    case _ => super.equals(that);
-  }
-}
diff --git a/src/library/scala/collection/jcl/Conversions.scala b/src/library/scala/collection/jcl/Conversions.scala
deleted file mode 100644
index 932cc01..0000000
--- a/src/library/scala/collection/jcl/Conversions.scala
+++ /dev/null
@@ -1,17 +0,0 @@
-package scala.collection.jcl
-
-object Conversions {
-  implicit def convertSet[T](set : java.util.Set[T]) = Set(set)
-  implicit def convertList[T](set : java.util.List[T]) = Buffer(set)
-  implicit def convertSortedSet[T](set : java.util.SortedSet[T]) = SortedSet(set)
-  implicit def convertMap[T,E](set : java.util.Map[T,E]) = Map(set)
-  implicit def convertSortedMap[T,E](set : java.util.SortedMap[T,E]) = SortedMap(set)
-  
-  implicit def unconvertSet[T](set : SetWrapper[T]) = set.underlying
-  implicit def unconvertCollection[T](set : CollectionWrapper[T]) = set.underlying
-  implicit def unconvertList[T](set : BufferWrapper[T]) = set.underlying
-  implicit def unconvertSortedSet[T](set : SortedSetWrapper[T]) = set.underlying
-  implicit def unconvertMap[T,E](set : MapWrapper[T,E]) = set.underlying
-  implicit def unconvertSortedMap[T,E](set : SortedMapWrapper[T,E]) = set.underlying
-  
-}
\ No newline at end of file
diff --git a/src/library/scala/collection/jcl/HashMap.scala b/src/library/scala/collection/jcl/HashMap.scala
deleted file mode 100644
index 1b19d90..0000000
--- a/src/library/scala/collection/jcl/HashMap.scala
+++ /dev/null
@@ -1,21 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://www.scala-lang.org/           **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: HashMap.scala 16881 2009-01-09 16:28:11Z cunei $
-
-package scala.collection.jcl
-
-/** A map that is backed by a Java hash map.
- *
- *  @author Sean McDirmid
- */
-class HashMap[K, E](override val underlying: java.util.HashMap[K, E]) extends MapWrapper[K, E] {
-  def this() = this(new java.util.HashMap[K, E])
-  override def clone: HashMap[K, E] =
-    new HashMap[K, E](underlying.clone().asInstanceOf[java.util.HashMap[K, E]])
-}
diff --git a/src/library/scala/collection/jcl/HashSet.scala b/src/library/scala/collection/jcl/HashSet.scala
deleted file mode 100644
index db30090..0000000
--- a/src/library/scala/collection/jcl/HashSet.scala
+++ /dev/null
@@ -1,21 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://www.scala-lang.org/           **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: HashSet.scala 16881 2009-01-09 16:28:11Z cunei $
-
-package scala.collection.jcl
-
-/** A hash set that is backed by a Java hash set. 
- *
- *  @author Sean McDirmid
- */
-class HashSet[A](override val underlying: java.util.HashSet[A]) extends SetWrapper[A] {
-  def this() = this(new java.util.HashSet[A])
-  override def clone: HashSet[A] =
-    new HashSet[A](underlying.clone().asInstanceOf[java.util.HashSet[A]])
-}
diff --git a/src/library/scala/collection/jcl/Hashtable.scala b/src/library/scala/collection/jcl/Hashtable.scala
deleted file mode 100644
index a777d4a..0000000
--- a/src/library/scala/collection/jcl/Hashtable.scala
+++ /dev/null
@@ -1,22 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://www.scala-lang.org/           **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: Hashtable.scala 16881 2009-01-09 16:28:11Z cunei $
-
-package scala.collection.jcl
-
-/** A hash set that is backed by a Java hash table. 
- *
- *  @author Sean McDirmid
- */
-class Hashtable[K,E](override val underlying: java.util.Hashtable[K,E]) extends MapWrapper[K,E] {
-  def this() = this(new java.util.Hashtable[K,E])
-
-  override def clone() : Hashtable[K,E] =
-    new Hashtable[K,E](underlying.clone().asInstanceOf[java.util.Hashtable[K,E]])
-}
diff --git a/src/library/scala/collection/jcl/IdentityHashMap.scala b/src/library/scala/collection/jcl/IdentityHashMap.scala
deleted file mode 100644
index 508a59b..0000000
--- a/src/library/scala/collection/jcl/IdentityHashMap.scala
+++ /dev/null
@@ -1,24 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://www.scala-lang.org/           **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: IdentityHashMap.scala 16881 2009-01-09 16:28:11Z cunei $
-
-package scala.collection.jcl
-
-/** A map that is backed by a Java identity hash map, which compares keys
- *  by their reference-based identity as opposed to using equals and hashCode.
- *  An identity hash map will often perform better than traditional hash map
- *  because it can utilize linear probing.
- *
- *  @author Sean McDirmid
- */
-class IdentityHashMap[K, E](override val underlying : java.util.IdentityHashMap[K, E]) extends MapWrapper[K, E] {
-  def this() = this(new java.util.IdentityHashMap[K, E])
-  override def clone: IdentityHashMap[K, E] =
-    new IdentityHashMap[K, E](underlying.clone().asInstanceOf[java.util.IdentityHashMap[K, E]])
-}
diff --git a/src/library/scala/collection/jcl/IterableWrapper.scala b/src/library/scala/collection/jcl/IterableWrapper.scala
deleted file mode 100644
index c6b3efb..0000000
--- a/src/library/scala/collection/jcl/IterableWrapper.scala
+++ /dev/null
@@ -1,32 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: IterableWrapper.scala 16894 2009-01-13 13:09:41Z cunei $
-
-package scala.collection.jcl;
-
-/** A wrapper around a Java collection that only supports remove mutations.
- *
- *  @author Sean McDirmid 
- */
-trait IterableWrapper[A] extends MutableIterable[A] {
-  def underlying: java.util.Collection[A];
-  override def remove(a: A) = underlying.remove(a);
-  override def removeAll(that: Iterable[A]) = that match {
-    case that: IterableWrapper[_] => underlying.removeAll(that.underlying);
-    case _ => super.removeAll(that);
-  }
-  override def retainAll(that : Iterable[A]) = that match {
-    case that : IterableWrapper[_] => underlying.retainAll(that.underlying);
-    case _ => super.retainAll(that);
-  }
-  override def size = underlying.size;
-  override def isEmpty = underlying.isEmpty;
-  override def clear = underlying.clear;
-  override def elements : MutableIterator[A] = new MutableIterator.Wrapper[A](underlying.iterator);
-}
diff --git a/src/library/scala/collection/jcl/LinkedHashMap.scala b/src/library/scala/collection/jcl/LinkedHashMap.scala
deleted file mode 100644
index 26a8751..0000000
--- a/src/library/scala/collection/jcl/LinkedHashMap.scala
+++ /dev/null
@@ -1,22 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://www.scala-lang.org/           **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: LinkedHashMap.scala 16881 2009-01-09 16:28:11Z cunei $
-
-package scala.collection.jcl
-
-/** A map that is backed by a Java linked hash map, which fixes iteration
- *  order in terms of insertion order.
- *
- *  @author Sean McDirmid
- */
-class LinkedHashMap[K, E](override val underlying: java.util.LinkedHashMap[K, E]) extends MapWrapper[K, E] {
-  def this() = this(new java.util.LinkedHashMap[K, E])
-  override def clone: LinkedHashMap[K, E] =
-    new LinkedHashMap[K, E](underlying.clone().asInstanceOf[java.util.LinkedHashMap[K, E]])
-}
diff --git a/src/library/scala/collection/jcl/LinkedHashSet.scala b/src/library/scala/collection/jcl/LinkedHashSet.scala
deleted file mode 100644
index accee8e..0000000
--- a/src/library/scala/collection/jcl/LinkedHashSet.scala
+++ /dev/null
@@ -1,22 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://www.scala-lang.org/           **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: LinkedHashSet.scala 16881 2009-01-09 16:28:11Z cunei $
-
-package scala.collection.jcl
-
-/** A set that is backed by a Java linked hash set, which fixes iteration
- *  order in terms of insertion order.
- *
- *  @author Sean McDirmid
- */
-class LinkedHashSet[A](override val underlying: java.util.LinkedHashSet[A]) extends SetWrapper[A] {
-  def this() = this(new java.util.LinkedHashSet[A])
-  override def clone: LinkedHashSet[A] =
-    new LinkedHashSet[A](underlying.clone().asInstanceOf[java.util.LinkedHashSet[A]])
-}
diff --git a/src/library/scala/collection/jcl/LinkedList.scala b/src/library/scala/collection/jcl/LinkedList.scala
deleted file mode 100644
index 2b83729..0000000
--- a/src/library/scala/collection/jcl/LinkedList.scala
+++ /dev/null
@@ -1,32 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: LinkedList.scala 16894 2009-01-13 13:09:41Z cunei $
-
-package scala.collection.jcl;
-
-/** Creates a buffer backed by a Java linked list. Includes additional
- *  peek/poll/removeFirst/removeLast APIs that are useful in implementing
- *  queues and stacks.
- *
- *  @author Sean McDirmid
- */
-class LinkedList[A](override val underlying : java.util.LinkedList[A]) extends BufferWrapper[A]  {
-  def this() = this(new java.util.LinkedList[A]);
-  override def elements = super[BufferWrapper].elements;
-  override def add(idx : Int, a : A) =
-    if (idx == 0) underlying.addFirst(a);
-    else super.add(idx, a);
-  //def peek = underlying.peek.asInstanceOf[A];
-  //def poll = underlying.poll.asInstanceOf[A];
-  //def removeFirst = underlying.removeFirst.asInstanceOf[A];
-  //def removeLast  = underlying.removeLast.asInstanceOf[A];
-  
-  override def clone: LinkedList[A] =
-    new LinkedList[A](underlying.clone().asInstanceOf[java.util.LinkedList[A]])
-}
diff --git a/src/library/scala/collection/jcl/Map.scala b/src/library/scala/collection/jcl/Map.scala
deleted file mode 100644
index bafb575..0000000
--- a/src/library/scala/collection/jcl/Map.scala
+++ /dev/null
@@ -1,129 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: Map.scala 16894 2009-01-13 13:09:41Z cunei $
-
-package scala.collection.jcl;
-
-/** A mutable map that is compatible with Java maps.
- *
- *  @author Sean McDirmid
- */
-trait Map[K,E] extends MutableIterable[Tuple2[K,E]] with scala.collection.mutable.Map[K,E] {
-  override def clear() = super[MutableIterable].clear;
-  override def isEmpty = super[MutableIterable].isEmpty;
-  override def keySet : Set[K] = new KeySet;
-  override final def keys = keySet.elements;
-  /** The values of this map as a projection, which means
-      removals from the returned collection will remove the element from this map.
-      @returns a projection of this map's elements.  */
-  def valueSet : MutableIterable.Projection[E] = projection.map(_._2);
-  
-  override def put(key : K, elem : E) : Option[E] = throw new java.lang.AbstractMethodError 
-  
-  override def ++=(that : Iterable[(K,E)]) : Unit = 
-    that.foreach(p => put(p._1, p._2));
-  
-  override def removeKey(key : K) : Option[E] = {
-    val i = elements;
-    while (!i.hasNext) {
-      val result = i.next;
-      if (result._1 == key) {
-        i.remove; 
-        return Some(result._2);
-      }
-    }
-    return None;
-  }
-  override def has(pair : Tuple2[K,E]) = get(pair._1) match {
-  case Some(e) if e == pair._2 => true;
-  case _ => false;
-  }
-  override def get(key : K) = elements.find(p => p._1 == key).map(_._2);
-  override def update(key : K, e : E) : Unit = put(key,e);
-  override def +(pair : Tuple2[K,E]) : this.type = {
-    put(pair._1,pair._2); this;
-  }
-  override def +=(pair : Tuple2[K,E]) : Unit = put(pair._1, pair._2);
-  override def -(key : K) : this.type = {
-    removeKey(key); this;
-  }
-  override def remove(p : (K,E)) = get(p._1) match {
-  case Some(p._2) => this -= p._1; true
-  case _ => false;
-  }
-  
-  override def -=(key : K) : Unit = removeKey(key);
-  override def elements : MutableIterator[Tuple2[K,E]];
-  
-  override def projection : Map.Projection[K,E] = new Map.Projection[K,E] {
-    override def elements = Map.this.elements
-    override def size = Map.this.size
-    override def get(k : K) = Map.this.get(k)
-    override def put(k : K, e : E) = Map.this.put(k, e)
-  }
-  /**
-   */
-  def lense[F](f : E => F, g : F => E) : jcl.Map.Projection[K,F] = new Lense[F](f,g);
-  
-  protected class Lense[F](f : E => F, g : F => E) extends jcl.Map.Projection[K,F] {
-    override def elements = Map.this.elements.map(k => Tuple2(k._1, f(k._2)));
-    override def removeKey(key : K) = Map.this.removeKey(key).map(f);
-    override def put(key : K, elem : F) = Map.this.put(key, g(elem)).map(f);
-    override def get(key : K) = Map.this.get(key).map(f);
-    override def lense[G](f0 : F => G, g0 : G => F) : jcl.Map.Projection[K,G] = 
-      Map.this.lense[G](x => f0(f(x)), y => g(g0(y)));
-    override def size = size0;
-  }
-  protected class KeySet extends Set[K] {
-    override def size = Map.this.size;
-    override def add(k : K) = Map.this.put(k, default(k)) == None;
-    override def elements = Map.this.elements.map(_._1);
-    override def has(k : K) = Map.this.contains(k);
-  }
-  override def filterKeys(p : K => Boolean) : Map.Projection[K,E] = new Filter(p); 
-
-  protected class Filter(p : K => Boolean) extends Map.Projection[K,E] {
-    override def elements = {
-      val i = Map.this.elements.filter(e => p(e._1));
-      new MutableIterator[(K,E)] {
-        def next = i.next
-        def hasNext = i.hasNext
-        def remove : Unit = throw new NoSuchMethodException
-      }
-    } 
-   override def removeKey(key : K) = {
-      if (!p(key)) throw new IllegalArgumentException;
-      Map.this.removeKey(key);
-    }
-    override def contains(key : K) = p(key) && Map.this.contains(key);
-    override def put(key : K, elem : E) = {
-      if (!p(key)) throw new IllegalArgumentException;
-      Map.this.put(key, elem);
-    }
-    override def get(key : K) = {
-      if (!p(key)) None;
-      else Map.this.get(key);
-    }
-    override def filterKeys(p0 : K => Boolean) : Map.Projection[K,E] =
-      Map.this.filterKeys(e => p(e) && p0(e));
-
-    override def size = size0;
-  }
-}
-
-object Map {
-  trait MutableIterableProjection[A] extends MutableIterable.Projection[A];
-  trait Projection[K,E] extends MutableIterableProjection[(K,E)] with scala.collection.Map.Projection[K,E] with Map[K,E] {
-    override def projection = this
-    override def map[B](f : ((K,E)) => B) : MutableIterable.Projection[B] = super[MutableIterableProjection].map(f);
-  }
-  def apply[T,E](map0 : java.util.Map[T,E]) = new MapWrapper[T,E] {
-    val underlying = map0
-  }
-}
diff --git a/src/library/scala/collection/jcl/MapWrapper.scala b/src/library/scala/collection/jcl/MapWrapper.scala
deleted file mode 100644
index dfed48c..0000000
--- a/src/library/scala/collection/jcl/MapWrapper.scala
+++ /dev/null
@@ -1,76 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://www.scala-lang.org/           **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: MapWrapper.scala 16881 2009-01-09 16:28:11Z cunei $
-
-package scala.collection.jcl
-
-/** A wrapper around a Java map.
- *
- *  @author Sean McDirmid
- */
-trait MapWrapper[K, E] extends jcl.Map[K, E] {
-  def underlying: java.util.Map[K, E]
-  override def size = underlying.size
-  override def isEmpty = underlying.isEmpty
-  override def clear() = underlying.clear
-
-  override def put(key: K, elem: E) = {
-    //if (elem == null) throw new IllegalArgumentException;
-    val ret = underlying.put(key, elem)
-    if (ret == null) None else Some(ret.asInstanceOf[E])
-  }
-
-  override def get(key : K) : Option[E] = {
-    val ret = underlying.get(key);
-    if (ret == null) None else Some(ret.asInstanceOf[E]);
-  }
-  
-  override def ++=(that : Iterable[Tuple2[K,E]]) : Unit = that match {
-    case that : MapWrapper[_,_] => underlying.putAll(that.underlying);
-    case _ => super.++=(that)
-  }
-
-  override def removeKey(key: K) = {
-    val ret = underlying.remove(key)
-    if (ret == null) None else Some(ret.asInstanceOf[E])
-  }
-
-  override def contains(key: K) = underlying.containsKey(key)
-  override def keySet: Set.Projection[K] = new KeySet
-  override def valueSet: MutableIterable.Projection[E] = new ValueSet
-  override def elements: MutableIterator[Tuple2[K,E]] = new IteratorWrapper
-
-  class IteratorWrapper extends MutableIterator[Tuple2[K,E]] {
-    val underlying = MapWrapper.this.underlying.entrySet.iterator
-    def hasNext = underlying.hasNext
-    def remove = underlying.remove
-    def next = {
-      val next = underlying.next.asInstanceOf[java.util.Map.Entry[K,E]]
-      Tuple2(next.getKey.asInstanceOf[K],next.getValue.asInstanceOf[E])
-    }
-  }
-
-  class KeySet extends super.KeySet with SetWrapper[K] with Set.Projection[K] {
-    val underlying = MapWrapper.this.underlying.keySet
-  }
-
-  class ValueSet extends IterableWrapper[E] with MutableIterable.Projection[E] {
-    override def size = MapWrapper.this.size
-    val underlying = MapWrapper.this.underlying.values
-    override def has(e : E) = MapWrapper.this.underlying.containsValue(e)
-  }
-
-  override def toString = underlying.toString
-  override def hashCode = underlying.hashCode
-
-  override def equals(that : Any) = that match {
-    case that: MapWrapper[_,_] => underlying == that.underlying
-    case _ => super.equals(that)
-  }
-}
diff --git a/src/library/scala/collection/jcl/MutableIterable.scala b/src/library/scala/collection/jcl/MutableIterable.scala
deleted file mode 100644
index 3dc9350..0000000
--- a/src/library/scala/collection/jcl/MutableIterable.scala
+++ /dev/null
@@ -1,110 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: MutableIterable.scala 16894 2009-01-13 13:09:41Z cunei $
-
-package scala.collection.jcl;
-
-/**
- * An iterable collection that supports remove operations.
- * Useful for representing projections of mutable collections that where only 
- * the remove operation makes sense.
- *
- * @author Sean McDirmid
- */
-trait MutableIterable[A] extends scala.Collection[A] {
-  /** @return true if t is in the collection.
-   **/
-  def has(t : A ) : Boolean = elements.contains(t);
-  
-  /** @return true if t was removed from this collection.
-   **/
-  def remove(t : A ) : Boolean = elements.remove(t);
-  /** @return true if any element in that was removed from this collection.
-   **/
-  def removeAll(that : Iterable[A]) : Boolean = {
-    var changed = false;
-    that.foreach(t => changed = elements.remove(t) || changed);
-    changed;
-  }
-  /** Operator shortcut for removeAll. */
-  def --(that : Iterable[A]) : this.type = {
-    removeAll(that); this;
-  }
-  
-  /** @return the collection that t was removed from.
-   */
-  def -(t : A) : this.type = { remove(t); this; }
-  /** retain only elements in the collection that predicate p is true for.
-   */
-  def retainOnly(p : A => Boolean) : Unit = elements.retain(p);
-  /** retain only elements that are also in that.
-   */
-  def retainAll(that : Iterable[A]) : Boolean = elements.retain(s => that.exists(t => t == s));
-
-  /** @return the current number of elements in the collection.
-   */
-  protected def size0 : Int = {
-    var count = 0;
-    val i = elements;
-    while (i.hasNext) { count = count + 1; i.next; }
-    count;
-  }
-    
-  /** clear all elements from the collection.
-   */
-  def clear(): Unit = {
-    val i = elements;
-    while (i.hasNext) {
-      i.next; i.remove;
-    }
-  }
-  override def projection : MutableIterable.Projection[A] = new MutableIterable.Projection[A] {
-    override def elements = MutableIterable.this.elements
-    override def size = MutableIterable.this.size
-    override def remove(t : A ) : Boolean = MutableIterable.this.remove(t)
-    override def filter(p : A => Boolean) : MutableIterable.Projection[A] = super.filter(p)
-  }
-  /** The default implementation of a map over mutable iterable collections. 
-   **/
-  override def elements : MutableIterator[A];
-  protected class Map[B](f : A => B) extends MutableIterable.Projection[B] {
-    override def elements = MutableIterable.this.elements.map(f)
-    override def size = MutableIterable.this.size
-  }
-  trait Filter extends MutableIterable.Projection[A] {
-    protected def p(a : A) : Boolean
-    override def has(a : A) = if (!p(a)) false else MutableIterable.this.has(a);
-    override def remove(a : A) = {
-      if (!p(a)) throw new IllegalArgumentException;
-      MutableIterable.this.remove(a);
-    }
-    override def filter(p0 : A => Boolean) : MutableIterable.Projection[A] = 
-      MutableIterable.this.projection.filter(a => p(a) && p0(a));
-    def elements = {
-      val i = MutableIterable.this.elements.filter(p);
-      new MutableIterator[A] {
-	def next = i.next
-	def hasNext = i.hasNext
-	def remove : Unit = throw new NoSuchMethodException
-      } 
-    }
-    def size = size0;
-  }
-}
-
-object MutableIterable {
-  trait Projection[A] extends MutableIterable[A] with Iterable.Projection[A] {
-    override def projection = this
-    override def map[B](f : A => B) : Projection[B] = new Map[B](f);
-    override def filter(pp : A => Boolean) : Projection[A] = new Filter {
-      def p(a : A) = pp(a)
-    }
-  }
-}
-
diff --git a/src/library/scala/collection/jcl/MutableIterator.scala b/src/library/scala/collection/jcl/MutableIterator.scala
deleted file mode 100644
index c4f926d..0000000
--- a/src/library/scala/collection/jcl/MutableIterator.scala
+++ /dev/null
@@ -1,70 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: MutableIterator.scala 16894 2009-01-13 13:09:41Z cunei $
-
-package scala.collection.jcl;
-
-object MutableIterator {
-  class Wrapper[A](val underlying : java.util.Iterator[A]) extends MutableIterator[A] {
-    def hasNext = underlying.hasNext;
-    def next = underlying.next.asInstanceOf[A];
-    def remove = underlying.remove;
-  }
-}
-
-/** An iterator that supports the remove operation.
- *  These iterators wrap Java iterators, and so have the same fail fast
- *  behavior when dealing with concurrent modifications.
- *
- *  @author Sean McDirmid
- */
-trait MutableIterator[A] extends Iterator[A] {
-  def remove : Unit;
-
-  /* filter doesnt' support remove yet.
-  override def filter(f : A => Boolean) : MutableIterator[A] = {
-    val buffered = this.buffered0;
-    new buffered.Filter(f);
-  }
-  */
-
-  override def map[B](f: A => B) : MutableIterator[B] = new Map(f);
-  /** A type-safe version of contains.
-   **/
-  def has(a: A) = exists(b => a == a);
-
-  /** Finds and removes the first instance of "a" through the iterator.
-   *  After execution, the iterator's cursor is located where the removed
-   *  element existed.
-   *
-   * @param  a ..
-   * @return <code>false</code> if "a" is not encountered in the iterator
-   *         and the iterator's cursor is located at the end of its elements.
-   */
-  def remove(a: A): Boolean = {
-    while (hasNext) 
-      if (next == a) { remove; return true; }
-    return false;
-  }
-  /** Removes all elements in the iterator that predicate "p" returns false on.
-   **/
-  def retain(p : A => Boolean) : Boolean = {
-    var changed = false;
-    while (hasNext) 
-      if (!p(next)) { remove; changed = true; }
-    changed;
-  }
-
-  /** Standard implementation of a mapped iterator. **/
-  class Map[B](f : A => B) extends MutableIterator[B] {
-    def hasNext = MutableIterator.this.hasNext
-    def next = f(MutableIterator.this.next)
-    def remove = MutableIterator.this.remove
-  }
-}
diff --git a/src/library/scala/collection/jcl/MutableSeq.scala b/src/library/scala/collection/jcl/MutableSeq.scala
deleted file mode 100644
index 62d67bb..0000000
--- a/src/library/scala/collection/jcl/MutableSeq.scala
+++ /dev/null
@@ -1,123 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: MutableSeq.scala 16894 2009-01-13 13:09:41Z cunei $
-
-package scala.collection.jcl;
-
-/** A mutable sequence that supports the remove operation and is ordered.
- *
- *  @author Sean McDirmid
- */
-trait MutableSeq[A] extends Seq[A] with MutableIterable[A]  {
-  protected class DefaultSeqIterator extends SeqIterator[Int,A] {
-    protected var index = 0
-    override def hasNext = index < length
-    override def next = {
-      if (!hasNext) throw new NoSuchElementException("no lookahead")
-      index = index + 1
-      MutableSeq.this.apply(index - 1)
-    }
-    override def hasPrevious = index > 0
-    override def previous = {
-      if (!hasPrevious) throw new NoSuchElementException
-      index = index - 1
-      MutableSeq.this.apply(index)
-    }
-    
-    override def nextIndex = index
-    override def previousIndex = {
-      if (index == 0) throw new NoSuchElementException
-      else index - 1
-    }
-    def remove = throw new UnsupportedOperationException
-  }
-  override def elements : SeqIterator[Int,A] = new DefaultSeqIterator
-
-  override def isEmpty = super[MutableIterable].isEmpty;
-
-  override def apply(idx : Int) = elements.seek(idx);
-  override def projection : MutableSeq.Projection[A] = new MutableSeq.Projection[A] {
-    override def length = MutableSeq.this.length
-    override def elements = MutableSeq.this.elements
-    override def apply(idx : Int) = MutableSeq.this.apply(idx)
-  }
-  
-  /** Find the index of "a" in this sequence. 
-   *  @returns None if the "a" is not in this sequence.
-   */
-  def indexOf(a : A) = elements.indexOf(a);
-
-  override def length = {
-    var i = elements;
-    var sz = 0;
-    while (i.hasNext) {
-      sz = sz + 1;
-      i.next;
-    }
-    sz;
-  }
-  protected trait Filter extends MutableSeq.Projection[A] {
-    protected def p(a : A) : Boolean
-    override def elements : SeqIterator[Int,A] = new FilterIterator(MutableSeq.this.elements);
-    class FilterIterator(underlying : SeqIterator[Int,A]) extends SeqIterator[Int,A] {
-      private var index = 0;
-      protected def seekNext : Option[A] = {
-        while (underlying.hasNext) {
-          val next = underlying.next;
-          if (p(next)) return Some(next);
-        }
-        return None;
-      }
-      protected def seekPrevious : Option[A] = {
-        while (underlying.hasPrevious) {
-          val previous = underlying.previous;
-          if (p(previous)) return Some(previous);
-        }
-        return None;
-      }
-      def hasNext : Boolean = seekNext match {
-      case None => false;
-      case Some(_) => underlying.previous; true;
-      }
-      def nextIndex = index;
-      def next = seekNext match {
-      case None => throw new NoSuchElementException;
-      case Some(result) => index = index + 1; result;
-      }
-      def hasPrevious : Boolean = seekPrevious match {
-      case None => false;
-      case Some(_) => underlying.previous; true;
-      }
-      def previousIndex = {
-        if (index == 0) throw new NoSuchElementException;
-        index - 1;
-      }
-      def previous = seekPrevious match {
-      case None => throw new NoSuchElementException;
-      case Some(result) => index = index - 1; result;
-      }
-      def remove = underlying.remove;
-    }
-  }
-  protected class Map[B](f : A => B) extends super.Map[B](f) with MutableSeq.Projection[B] {
-    override def elements = MutableSeq.this.elements.map(f);
-    override def apply(idx : Int) = f(MutableSeq.this.apply(idx));
-    override def size = length;
-  }
-}
-object MutableSeq {
-  trait Projection[A] extends MutableSeq[A] with MutableIterable.Projection[A] with Seq.Projection[A] {
-    override def projection = this
-    override def filter(pp : A => Boolean) : Projection[A] = new Filter {
-      override def p(a : A) = pp(a)
-    }
-    override def map[B](f : A => B) : Projection[B] = new Map[B](f);
-  }
-}
-
diff --git a/src/library/scala/collection/jcl/Ranged.scala b/src/library/scala/collection/jcl/Ranged.scala
deleted file mode 100644
index e2f9120..0000000
--- a/src/library/scala/collection/jcl/Ranged.scala
+++ /dev/null
@@ -1,54 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: Ranged.scala 16894 2009-01-13 13:09:41Z cunei $
-
-package scala.collection.jcl;
-
-/** Any collection (including maps) whose keys (or elements) are ordered.
- *
- *  @author Sean McDirmid
- */
-trait Ranged[K,A] extends scala.collection.Ranged[K,A] with MutableIterable[A] {
-  protected type SortedSelf <: Ranged[K,A];
-
-  /** Comparison function that orders keys. */
-  def compare(k0: K, k1: K): Int;
-
-  /** Creates a ranged projection of this collection. Any mutations in the
-   *  ranged projection will update this collection and vice versa.  Note: keys
-   *  are not garuanteed to be consistent between this collection and the projection.
-   *  This is the case for buffers where indexing is relative to the projection. 
-   *
-   *  @param from  The lower-bound (inclusive) of the ranged projection.
-   *               <code>None</code> if there is no lower bound.
-   *  @param until The upper-bound (exclusive) of the ranged projection.
-   *               <code>None</code> if there is no upper bound.
-   */
-  def rangeImpl(from: Option[K], until: Option[K]) : SortedSelf;
-  /** Creates a ranged projection of this collection with no upper-bound.
-   ** @param from The lower-bound (inclusive) of the ranged projection.
-   **/
-  override final def from(from: K): SortedSelf = rangeImpl(Some(from), None);
-  /** Creates a ranged projection of this collection with no lower-bound.
-   ** @param until The upper-bound (exclusive) of the ranged projection.
-   **/
-  override final def until(until: K): SortedSelf = rangeImpl(None, Some(until));
-  
-  /** Creates a ranged projection of this collection with both a lower-bound and an upper-bound.
-   ** @param from The upper-bound (exclusive) of the ranged projection.
-   **/
-  override final def range(from: K, until: K) : SortedSelf = rangeImpl(Some(from),Some(until));
-
-  /** A wrapper around Java comparators. */
-  protected class Comparator[K <% Ordered[K]] extends java.util.Comparator[Any] {
-    def compare(x0 : Any, x1 : Any) = {
-      x0.asInstanceOf[K].compare(x1.asInstanceOf[K]); //!!!
-    }
-  }
-}
diff --git a/src/library/scala/collection/jcl/SeqIterator.scala b/src/library/scala/collection/jcl/SeqIterator.scala
deleted file mode 100644
index 3e8e7c5..0000000
--- a/src/library/scala/collection/jcl/SeqIterator.scala
+++ /dev/null
@@ -1,58 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: SeqIterator.scala 16894 2009-01-13 13:09:41Z cunei $
-
-package scala.collection.jcl;
-
-/** An iterator for a sequence that can move both forwards and backwards.
- *  over a set of ordered keys.
- *
- *  @author Sean McDirmid
- */
-trait SeqIterator[K,A] extends MutableIterator[A] {
-  /** @returns The index at the iterator's cursor. */
-  def nextIndex: K;
-
-  /** @returns The index of the element before the iterator's cursor. */
-  def previousIndex: K;
-
-  /** @return The previous element, will move the iterator's cursor backwards. */
-  def previous: A;
-
-  /** @return True if and only if the iterator's cursor is not at the beging of the iteration. */
-  def hasPrevious : Boolean;
-
-  /** Winds the iteration forward until index "idx" is found */
-  def seek(idx: K) = {
-    while (nextIndex != idx) next;
-    next;
-  }
-  /** finds the index of the next "a" in this iteration.
-   *
-   *  @param  a ..
-   *  @return <code>None</code> if "a" is not found in the iteration.
-   */
-  def indexOf(a: A): Option[K] = {
-    while (hasNext) {
-      val ret = next;
-      if (ret == a) return Some(previousIndex);
-    }
-    return None;
-  }
-
-  override def map[B](f: A => B) : SeqIterator[K,B] = new Map[B](f);
-  class Map[B](f: A => B) extends super.Map[B](f) with SeqIterator[K,B] {
-    override def hasPrevious = SeqIterator.this.hasPrevious;
-    override def previous = f(SeqIterator.this.previous);
-    override def previousIndex = SeqIterator.this.previousIndex;
-    override def nextIndex = SeqIterator.this.nextIndex;
-    override def map[C](g : B => C) : SeqIterator[K,C] = 
-      SeqIterator.this.map(a => g(f(a)));
-  }
-}
diff --git a/src/library/scala/collection/jcl/Set.scala b/src/library/scala/collection/jcl/Set.scala
deleted file mode 100644
index bdce17f..0000000
--- a/src/library/scala/collection/jcl/Set.scala
+++ /dev/null
@@ -1,72 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: Set.scala 16894 2009-01-13 13:09:41Z cunei $
-
-package scala.collection.jcl
-
-/** Analogous to a Java set.
- *
- *  @author Sean McDirmid
- */
-trait Set[A] extends scala.collection.mutable.Set[A] with Collection[A] {
-  final def contains(a : A) = has(a)
-
-  /** Add will return false if "a" already exists in the set. **/
-  override def add(a: A): Boolean
-
-  override def ++(i: Iterable[A]) : this.type = super[Collection].++(i)
-  override def --(i: Iterable[A]) : this.type = super[Collection].--(i)
-  override def +(t: A) : this.type = super[Collection].+(t)
-  override def -(t: A) : this.type = super[Collection].-(t)
-  override final def retain(f: A => Boolean) = retainOnly(f)
-  override def isEmpty = super[Collection].isEmpty
-  override def clear() = super.clear()
-  override def subsetOf(set : scala.collection.Set[A]) = set match {
-    case set : Set[_] => set.hasAll(this)
-    case set => super.subsetOf(set)
-  }
-
-  override def transform(f: A => A) = {
-    var toAdd : List[A] = Nil
-    val i = elements
-    while (i.hasNext) {
-      val i0 = i.next
-      val i1 = f(i0)
-      if (i0 != i1) {
-        i.remove; toAdd = i1 :: toAdd
-      }
-    }
-    addAll(toAdd)
-  }
-  class Filter(pp : A => Boolean) extends super.Filter with Set.Projection[A] {
-    override def p(a : A) = pp(a)
-    override def retainOnly(p0 : A => Boolean): Unit = 
-      Set.this.retainOnly(e => !p(e) || p0(e))
-    override def add(a : A) = {
-      if (!p(a)) throw new IllegalArgumentException
-      else Set.this.add(a)
-    }
-  }
-  override def projection : Set.Projection[A] = new Set.Projection[A] {
-    override def add(a: A): Boolean = Set.this.add(a)
-    override def elements = Set.this.elements
-    override def size = Set.this.size
-    override def has(a : A) : Boolean = Set.this.has(a)
-  }
-}
-
-object Set {
-  trait Projection[A] extends Collection.Projection[A] with Set[A] {
-    override def filter(p : A => Boolean) : Projection[A] = new Filter(p);
-    override def projection = this
-  }
-  def apply[T](set : java.util.Set[T]) = new SetWrapper[T] {
-    val underlying = set
-  }
-}
diff --git a/src/library/scala/collection/jcl/SetWrapper.scala b/src/library/scala/collection/jcl/SetWrapper.scala
deleted file mode 100644
index 51a8147..0000000
--- a/src/library/scala/collection/jcl/SetWrapper.scala
+++ /dev/null
@@ -1,22 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: SetWrapper.scala 16894 2009-01-13 13:09:41Z cunei $
-
-package scala.collection.jcl;
-
-/** Used to wrap Java sets.
- *
- *  @author Sean McDirmid
- */
-trait SetWrapper[A] extends Set[A] with CollectionWrapper[A] {
-  def underlying: java.util.Set[A];
-  override def isEmpty = super[CollectionWrapper].isEmpty;
-  override def clear() = super[CollectionWrapper].clear;
-  override def size = underlying.size;
-}
diff --git a/src/library/scala/collection/jcl/Sorted.scala b/src/library/scala/collection/jcl/Sorted.scala
deleted file mode 100644
index d133094..0000000
--- a/src/library/scala/collection/jcl/Sorted.scala
+++ /dev/null
@@ -1,46 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: Sorted.scala 16894 2009-01-13 13:09:41Z cunei $
-
-package scala.collection.jcl;
-
-/** Any collection (including maps) whose keys (or elements) are ordered.
- *
- *  @author Sean McDirmid
- */
-trait Sorted[K,A] extends scala.collection.Sorted[K,A] with Ranged[K,A] {
-  override protected type SortedSelf <: Sorted[K,A];
-  /** return as a projection the set of keys in this collection */
-  override def keySet : SortedSet[K];
-  
-  /** Creates a ranged projection of this collection. Any mutations in the
-   *  ranged projection will update this collection and vice versa.  Keys
-   *  are garuanteed to be consistent between the collection and its projection.
-   *
-   *  @param from  The lower-bound (inclusive) of the ranged projection.
-   *               <code>None</code> if there is no lower bound.
-   *  @param until The upper-bound (exclusive) of the ranged projection.
-   *               <code>None</code> if there is no upper bound.
-   */
-  override def rangeImpl(from: Option[K], until: Option[K]) : SortedSelf;
-  
-  /** Create a range projection of this collection with no lower-bound.
-   ** @param to The upper-bound (inclusive) of the ranged projection.
-   **/
-  final override def to(to : K): SortedSelf = {
-    // tough!
-    val i = keySet.from(to).elements;
-    if (!i.hasNext) return this.asInstanceOf[SortedSelf];
-    val next = i.next;
-    if (next == to) {
-      if (!i.hasNext) return this.asInstanceOf[SortedSelf];
-      else return until(i.next);
-    } else return until(next);
-  }
-}
diff --git a/src/library/scala/collection/jcl/SortedMap.scala b/src/library/scala/collection/jcl/SortedMap.scala
deleted file mode 100644
index 95aa404..0000000
--- a/src/library/scala/collection/jcl/SortedMap.scala
+++ /dev/null
@@ -1,103 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: SortedMap.scala 16894 2009-01-13 13:09:41Z cunei $
-
-package scala.collection.jcl;
-
-object SortedMap {
-  trait Projection[K,E] extends Map.Projection[K,E] with SortedMap[K,E] {
-    override def projection = this
-  }
-  def apply[T,E](map0 : java.util.SortedMap[T,E]) = new SortedMapWrapper[T,E] {
-    val underlying = map0
-  }
-}
-/** A map whose keys are sorted.
- *
- *  @author Sean McDirmid
- */
-trait SortedMap[K,E] extends scala.collection.SortedMap[K,E] with Map[K,E] with Sorted[K,Tuple2[K,E]] {
-  final protected type SortedSelf = SortedMap[K,E];
-  override def compare(k0 : K, k1 : K) : Int;
-  override def firstKey : K = elements.next._1;
-  override def lastKey : K = {
-    val i = elements;
-    var last : K = i.next._1;
-    while (i.hasNext) last = i.next._1;
-    last;
-  }
-  override def rangeImpl(from : Option[K], until : Option[K]) : SortedMap[K,E] = Range(from, until);
-  override def keySet : SortedSet.Projection[K] = new KeySet;
-  
-  override def projection : SortedMap.Projection[K,E] = new SortedMap.Projection[K,E] {
-    override def elements = SortedMap.this.elements
-    override def size = SortedMap.this.size
-    override def get(k : K) = SortedMap.this.get(k)
-    override def put(k : K, e : E) = SortedMap.this.put(k, e)
-    override def compare(k0 : K, k1 : K) = SortedMap.this.compare(k0, k1)
-  }
-  
-  override def lense[F](f : E => F, g : F => E) : jcl.SortedMap.Projection[K,F] = new Lense[F](f,g);
-
-  protected class Lense[F](f : E => F, g : F => E) extends super.Lense[F](f,g) with SortedMap.Projection[K,F] {
-    def compare(k0 : K, k1 : K) = SortedMap.this.compare(k0, k1);
-    override def filterKeys(p : K => Boolean) : SortedMap.Projection[K,F] = 
-      SortedMap.this.projection.filterKeys(p).lense(f,g);
-    override def lense[G](f0 : F => G, g0 : G => F) : jcl.SortedMap.Projection[K,G] = 
-      SortedMap.this.lense[G]({x:E => f0(f(x))}, {y:G => g(g0(y))});
-    override def rangeImpl(from : Option[K], until : Option[K]) =
-      SortedMap.this.rangeImpl(from,until).lense(f,g);
-  }
-  protected class KeySet extends super.KeySet with SortedSet.Projection[K] {
-    def compare(k0 : K, k1 : K) = SortedMap.this.compare(k0,k1);
-    override def firstKey = SortedMap.this.firstKey;
-    override def lastKey = SortedMap.this.lastKey;
-    override def rangeImpl(from : Option[K], until : Option[K]) =
-      SortedMap.this.rangeImpl(from,until).keySet;
-  }
-  override def filterKeys(p : K => Boolean) : SortedMap.Projection[K,E] = new Filter(p);
-  protected class Filter(p : K => Boolean) extends super.Filter(p) with SortedMap.Projection[K,E] {
-    def compare(k0 : K, k1 : K) = SortedMap.this.compare(k0,k1);
-    override def filterKeys(p0 : K => Boolean) : SortedMap.Projection[K,E] = 
-      SortedMap.this.filterKeys(k => p(k) && p0(k));
-    override def rangeImpl(from : Option[K], until : Option[K]) : SortedMap.Projection[K,E] = 
-      SortedMap.this.Range(from, until).projection.filterKeys(p);  
-  }
-  protected def Range(from : Option[K], until : Option[K]) : SortedMap.Projection[K,E] = new Range(from,until);
-  protected class Range(from : Option[K], until : Option[K]) extends super.Filter(key => {
-    ((from == None || (compare(from.get,key) <= 0)) &&
-      (until == None || (compare(key,until.get) < 0)));
-  }) with SortedMap.Projection[K,E] {
-    def compare(k0 : K, k1 : K) = SortedMap.this.compare(k0,k1);
-    private def contains0(key : K) = 
-      (from == None || (compare(from.get,key) <= 0)) &&
-        (until == None || (compare(key,until.get) < 0));
-
-    override def contains(key : K) = SortedMap.this.contains(key) && contains0(key);
-    override def get(key : K) = if (!contains0(key)) None else SortedMap.this.get(key);
-    override def put(key : K, elem : E) = {
-      if (!contains0(key)) throw new IllegalArgumentException;
-      SortedMap.this.put(key, elem);
-    }
-    override def rangeImpl(from : Option[K], until : Option[K]) : SortedMap[K,E] = {
-      if (this.from != None && from == None) return rangeImpl(this.from, until);
-      if (this.until != None && until == None) return rangeImpl(from, this.until);
-      if (from != None && compare(this.from.get, from.get) > 0) return rangeImpl(this.from, until);
-      if (until != None && compare(this.until.get, until.get) < 0) return rangeImpl(from, this.until);
-      SortedMap.this.Range(from, until);
-    }
-    override def filterKeys(p : K => Boolean) : SortedMap.Projection[K,E] = new Filter(p);
-    protected class Filter(p : K => Boolean) extends super.Filter(p) with SortedMap.Projection[K,E] {
-      //def compare(k0 : K, k1 : K) = Range.this.compare(k0, k1);
-      override def filterKeys(p0 : K => Boolean) = Range.this.projection.filterKeys(k => p(k) && p0(k));
-      override def rangeImpl(from : Option[K], until : Option[K]) : SortedMap.Projection[K,E] = 
-        Range.this.rangeImpl(from,until).projection.filterKeys(p);
-    }
-  }  
-}
diff --git a/src/library/scala/collection/jcl/SortedMapWrapper.scala b/src/library/scala/collection/jcl/SortedMapWrapper.scala
deleted file mode 100644
index 334798c..0000000
--- a/src/library/scala/collection/jcl/SortedMapWrapper.scala
+++ /dev/null
@@ -1,39 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: SortedMapWrapper.scala 16894 2009-01-13 13:09:41Z cunei $
-
-package scala.collection.jcl;
-
-/** A sorted map that wraps an underlying Java sorted map.
- *
- *  @author Sean McDirmid
- */
-trait SortedMapWrapper[K,E] extends SortedMap[K,E] with MapWrapper[K,E] {
-  override def underlying : java.util.SortedMap[K,E];
-  /** the comparator function of this sorted map is defined in terms
-    * of the underlying sorted map's comparator.
-    */
-  def compare(k0 : K, k1 : K) = underlying.comparator.compare(k0,k1);
-  override def firstKey = underlying.firstKey.asInstanceOf[K];
-  override def lastKey = underlying.lastKey.asInstanceOf[K];
-  override def keySet : SortedSet.Projection[K] = new KeySet;
-  override protected def Range(from : Option[K], until : Option[K]) = new Range(from,until);
-  protected class Range(from : Option[K], until : Option[K]) extends super.Range(from,until) with SortedMapWrapper[K,E] {
-    val underlying = Tuple2(from,until) match {
-    case Tuple2(None,None) => throw new IllegalArgumentException;
-    case Tuple2(Some(from),None) => SortedMapWrapper.this.underlying.tailMap(from);  
-    case Tuple2(None,Some(until)) => SortedMapWrapper.this.underlying.headMap(until);
-    case Tuple2(Some(from),Some(until)) => SortedMapWrapper.this.underlying.subMap(from,until);
-    }
-    override def compare(k0 : K, k1 : K) = super[SortedMapWrapper].compare(k0, k1);
-  }
-  protected class KeySet extends super[SortedMap].KeySet with SetWrapper[K] with SortedSet.Projection[K] {
-    val underlying = SortedMapWrapper.this.underlying.keySet;
-  }
-}
diff --git a/src/library/scala/collection/jcl/SortedSet.scala b/src/library/scala/collection/jcl/SortedSet.scala
deleted file mode 100644
index 7110e31..0000000
--- a/src/library/scala/collection/jcl/SortedSet.scala
+++ /dev/null
@@ -1,99 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: SortedSet.scala 16894 2009-01-13 13:09:41Z cunei $
-
-package scala.collection.jcl;
-import Predef._
-
-object SortedSet {
-  trait Projection[A] extends Set.Projection[A] with SortedSet[A] {
-    override def projection = this
-    override def filter(p : A => Boolean) : Projection[A] = new Filter(p);
-  }
-  def apply[T](set : java.util.SortedSet[T]) = new SortedSetWrapper[T] {
-    val underlying = set
-  }
-  
-}
-
-/** Analogous to a Java sorted set.
- *
- *  @author Sean McDirmid
- */
-trait SortedSet[A] extends scala.collection.SortedSet[A] with jcl.Set[A] with Sorted[A,A] {
-  final protected type SortedSelf = SortedSet[A];
-  override def keySet = this;
-  def compare(a0 : A, a1 : A) : Int;
-  override def firstKey : A = {
-    val i = elements;
-    if (i.hasNext) i.next;
-    else throw new NoSuchElementException;
-  }
-  override def subsetOf(that : scala.collection.Set[A]) = super[SortedSet].subsetOf(that);
-  override def hasAll(that : Iterable[A]) = super[Sorted].hasAll(that.elements);
-  
-  override def lastKey : A = {
-    var last : A = null.asInstanceOf[A];
-    val i = elements;
-    while (i.hasNext) last = i.next;
-    if (last == null) throw new NoSuchElementException;
-    else last;
-  }
-  override def rangeImpl(from : Option[A], until : Option[A]) : SortedSet[A] = new Range(from, until);
-  override def projection : SortedSet.Projection[A] = new SortedSet.Projection[A] {
-    override def compare(a0 : A, a1 : A) = SortedSet.this.compare(a0, a1)
-    override def add(a: A): Boolean = SortedSet.this.add(a)
-    override def elements = SortedSet.this.elements
-    override def size = SortedSet.this.size
-    override def has(a : A) : Boolean = SortedSet.this.has(a)
-  }
-
-  protected class Filter(pp : A => Boolean) extends super.Filter(pp) with SortedSet.Projection[A] {
-    override def p(a : A) = pp(a)
-    def compare(a0 : A, a1 : A) : Int = SortedSet.this.compare(a0, a1);
-    override def filter(p0 : A => Boolean) = SortedSet.this.projection.filter(k => p(k) && p0(k));
-  }
-  protected class Range(from : Option[A], until : Option[A]) extends Filter(key => {
-    (from == None || (compare(from.get,key) <= 0)) &&
-      (until == None || (compare(key,until.get) < 0));
-  }) with SortedSet.Projection[A] {
-    if (from == None && until == None) throw new IllegalArgumentException;
-    if (from != None && until != None && !(SortedSet.this.compare(from.get, until.get) < 0))
-      throw new IllegalArgumentException;
-    //override def elements : MutableIterator[A] = 
-    //  new RangeIterator(SortedSet.this.elements.buffered0);
-    private def contains1(key : A) = 
-      (from == None || (compare(from.get,key) <= 0)) &&
-        (until == None || (compare(key,until.get) < 0));
-    override def has(elem : A) = contains1(elem) && SortedSet.this.has(elem);
-    override def rangeImpl(from : Option[A], until : Option[A]) : SortedSet[A] = {
-      if (this.from != None && from == None) return rangeImpl(this.from, until);
-      if (this.until != None && until == None) return rangeImpl(from, this.until);
-      if (from != None && compare(this.from.get, from.get) > 0) return rangeImpl(this.from, until);
-      if (until != None && compare(this.until.get, until.get) < 0) return rangeImpl(from, this.until);
-      SortedSet.this.rangeImpl(from, until);
-    }
-    /*
-    class RangeIterator(underlying : MutableIterator[A]#Buffered) extends MutableIterator[A] {
-      if (from != None)
-        underlying.seekNext(a => compare(from.get, a) <= 0);
-
-      private def okNext(a : A) =
-        if (until == None) true;
-        else compare(a, until.get) < 0;
-
-      def hasNext = underlying.hasNext && okNext(underlying.peekNext);
-      def next = underlying.seekNext(okNext) match {
-      case Some(result) => underlying.next; result;
-      case None => throw new NoSuchElementException;
-      }
-      def remove = underlying.remove;
-    }*/
-  }
-}
diff --git a/src/library/scala/collection/jcl/SortedSetWrapper.scala b/src/library/scala/collection/jcl/SortedSetWrapper.scala
deleted file mode 100644
index daae97b..0000000
--- a/src/library/scala/collection/jcl/SortedSetWrapper.scala
+++ /dev/null
@@ -1,39 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: SortedSetWrapper.scala 16894 2009-01-13 13:09:41Z cunei $
-
-package scala.collection.jcl;
-
-/** <p>
- *    A wrapper around a Java sorted set.
- *  </p>
- *  <p>
- *    The comparator of the sorted set matches the comparator of this set. 
- *  </p>
- *
- *  @author Sean McDirmid
- */
-trait SortedSetWrapper[A] extends SortedSet[A] with SetWrapper[A] {
-  def underlying : java.util.SortedSet[A];
-  /** delegates to the comparator of the underlying Java sorted set */
-  override def compare(a0 : A, a1 : A) = underlying.comparator.compare(a0, a1);
-  override def firstKey = underlying.first.asInstanceOf[A];
-  override def lastKey  = underlying.last .asInstanceOf[A];
-  override def rangeImpl(from : Option[A], until : Option[A]) : SortedSet[A] = new Range(from,until);
-  protected class Range(from : Option[A], until : Option[A]) extends super.Range(from, until) with SortedSetWrapper[A] {
-    val underlying = Tuple2(from,until) match {
-    case Tuple2(None,Some(until)) => SortedSetWrapper.this.underlying.headSet(until);
-    case Tuple2(Some(from),None)  => SortedSetWrapper.this.underlying.tailSet(from);
-    case Tuple2(Some(from),Some(until)) => SortedSetWrapper.this.underlying.subSet(from,until);
-    case _ => throw new IllegalArgumentException;
-    }
-    override def elements : MutableIterator[A] = super[SortedSetWrapper].elements;
-  }
-  override def toString = super.toString;
-}
diff --git a/src/library/scala/collection/jcl/Tests.scala b/src/library/scala/collection/jcl/Tests.scala
deleted file mode 100644
index fd0cafd..0000000
--- a/src/library/scala/collection/jcl/Tests.scala
+++ /dev/null
@@ -1,79 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: Tests.scala 16894 2009-01-13 13:09:41Z cunei $
-
-package scala.collection.jcl;
-
-import java.lang.Integer;
-
-private[jcl] object Tests {
-
-  def main(args : Array[String]) : Unit = {
-    hashSet;
-    treeSet;
-    treeMap;
-  }
-
-  def treeSet : Unit = {
-    val set = new TreeSet[String];
-    set + "aaa" + "bbb" + "ccc" + "ddd" + "eee" + "fff";
-    Console.println(set);
-    val rset : SortedSet[String] = set.range("b", "e");
-    Console.println(rset);
-    rset + "bad";
-    Console.println(rset);
-    Console.println(set);
-    val fset : SortedSet[String] = rset.projection.filter(_.endsWith("d"));
-    Console.println(fset);
-    fset += "cd";
-    Console.println(set);
-    //set.projection.map(_.length).retain(x => x == 3);
-    Console.println(set);
-    Console.println(rset);
-    Console.println(fset);
-  }
-
-  def treeMap : Unit = {
-    val map = new TreeMap[String,Integer];
-    map + ("bb" -> 3) + ("cc" -> 4) + ("aa" -> 2) + ("dd" -> 5);
-    //Console.println(map);
-    val rmap : SortedMap[String,Integer] = map.range("b", "d");
-    rmap + ("bad" -> 10);
-    Console.println(rmap);
-    //Console.println(map);
-    val fmap : SortedMap[String,Integer] = rmap.projection.filterKeys(k => k.length == 2);
-    Console.println(fmap);
-  }
-
-  def hashSet = {
-    val set = new HashSet[String];
-    set + "hello" + "world" + "you" + "to";
-    Console.println(set);
-    val fset = set.projection.filter(s => s.length <= 3);
-    Console.println(fset);
-    fset += "xxx";
-    Console.println(set);
-    try {
-      fset += "xxxx";
-      throw new Error;
-    } catch {
-      case e : IllegalArgumentException =>
-      case _ => throw new Error;
-    }
-    //val mset : MutableIterable[Int] = set // set.projection.map(s => s.length);
-    //Console.println(mset);
-    //mset.retain(n => n < 5);
-    Console.println(set);
-    val set1 = new HashSet[String] + "1" + "2" + "3";
-    set ++ (set1);
-    Console.println(set);
-    set.transform(s => "x_" + s);
-    Console.println(set);
-  }
-}
diff --git a/src/library/scala/collection/jcl/TreeMap.scala b/src/library/scala/collection/jcl/TreeMap.scala
deleted file mode 100644
index dfb7da7..0000000
--- a/src/library/scala/collection/jcl/TreeMap.scala
+++ /dev/null
@@ -1,24 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://www.scala-lang.org/           **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: TreeMap.scala 16881 2009-01-09 16:28:11Z cunei $
-
-package scala.collection.jcl
-
-/** A sorted map that is backed by a Java tree map.
- *
- * @author Sean McDirmid
- */
-class TreeMap[K <% Ordered[K], E] extends SortedMapWrapper[K, E] { tm =>
-  val underlying = (new java.util.TreeMap[K, E](new Comparator[K]))
-  override def clone: TreeMap[K, E] =
-    new TreeMap[K, E] {
-      override val underlying =
-        tm.underlying.clone().asInstanceOf[java.util.TreeMap[K, E]]
-    }
-}
diff --git a/src/library/scala/collection/jcl/TreeSet.scala b/src/library/scala/collection/jcl/TreeSet.scala
deleted file mode 100644
index adda00c..0000000
--- a/src/library/scala/collection/jcl/TreeSet.scala
+++ /dev/null
@@ -1,26 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://www.scala-lang.org/           **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: TreeSet.scala 16881 2009-01-09 16:28:11Z cunei $
-
-package scala.collection.jcl
-
-/** Creates a sorted set that is backed by an underlying Java tree set.
- *  Elements of the sorted set are ordered with respect to the ordered
- *  view bound of <code>A</code>.
- *
- *  @author Sean McDirmid
- */
-class TreeSet[A <% Ordered[A]] extends SortedSetWrapper[A] { ts =>
-  val underlying = new java.util.TreeSet[A](new Comparator[A])
-  override def clone: TreeSet[A] =
-    new TreeSet[A] {
-      override val underlying =
-        ts.underlying.clone().asInstanceOf[java.util.TreeSet[A]]
-    }
-}
diff --git a/src/library/scala/collection/jcl/WeakHashMap.scala b/src/library/scala/collection/jcl/WeakHashMap.scala
deleted file mode 100644
index 9acf4d3..0000000
--- a/src/library/scala/collection/jcl/WeakHashMap.scala
+++ /dev/null
@@ -1,31 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://www.scala-lang.org/           **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: WeakHashMap.scala 16881 2009-01-09 16:28:11Z cunei $
-
-package scala.collection.jcl
-
-/** <p>
- *    A map that is backed by a Java weak hash map, whose keys are maintained
- *    as weak references.
- *  </p>
- *  <p>
- *    Because keys are weak references, the garbage collector can collect
- *    them if they are not referred to elsewhere.
- *  </p>
- *  <p>
- *    Useful for implementing caches.
- *  </p>
- *
- *  @author Sean McDirmid
- */
-class WeakHashMap[K, E](override val underlying: java.util.WeakHashMap[K, E]) extends MapWrapper[K, E] {
-  def this() = this(new java.util.WeakHashMap[K, E])
-  override def clone: WeakHashMap[K, E] =
-    throw new CloneNotSupportedException("The underlying map doesn't implement the Cloneable interface")
-}
diff --git a/src/library/scala/collection/mutable/AddingBuilder.scala b/src/library/scala/collection/mutable/AddingBuilder.scala
new file mode 100644
index 0000000..af0b605
--- /dev/null
+++ b/src/library/scala/collection/mutable/AddingBuilder.scala
@@ -0,0 +1,36 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+package scala.collection
+package mutable
+
+import generic._
+
+/** The canonical builder for collections that are addable, i.e. that support an efficient `+` method
+ *  which adds an element to the collection.
+ *  
+ *  Collections are built from their empty element using this `+` method.
+ *  @param  empty   the empty element of the collection.
+ *  @tparam Elem    the type of elements that get added to the builder.
+ *  @tparam To      the type of the built collection.
+ *
+ *  @note   "efficient `+`" is not idle talk.  Do not use this on mutable collections or any others
+ *  for which `+` may perform an unshared copy! See GrowingBuilder comments for more.
+ *
+ *  @author Martin Odersky
+ *  @version 2.8
+ *  @since 2.8
+ */
+class AddingBuilder[Elem, To <: Addable[Elem, To] with collection.Iterable[Elem] with collection.IterableLike[Elem, To]](empty: To)
+extends Builder[Elem, To] {
+  protected var elems: To = empty
+  def +=(x: Elem): this.type = { elems = elems + x; this }
+  def clear() { elems = empty }
+  def result: To = elems
+}
diff --git a/src/library/scala/collection/mutable/ArrayBuffer.scala b/src/library/scala/collection/mutable/ArrayBuffer.scala
index 98f3bb5..f70ca19 100644
--- a/src/library/scala/collection/mutable/ArrayBuffer.scala
+++ b/src/library/scala/collection/mutable/ArrayBuffer.scala
@@ -1,76 +1,107 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: ArrayBuffer.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.collection.mutable
+package scala.collection
+package mutable
 
+import generic._
 
-import Predef._
-
-/** An implementation of the <code>Buffer</code> class using an array to
+/** An implementation of the `Buffer` class using an array to
  *  represent the assembled sequence internally. Append, update and random
  *  access take constant time (amortized time). Prepends and removes are
  *  linear in the buffer size.
  *
  *  @author  Matthias Zenger
- *  @version 1.0, 15/03/2004
+ *  @author  Martin Odersky
+ *  @version 2.8
+ *  @since   1
+ *  
+ *  @tparam A    the type of this arraybuffer's elements.
+ *  
+ *  @define Coll ArrayBuffer
+ *  @define coll arraybuffer
+ *  @define thatinfo the class of the returned collection. In the standard library configuration,
+ *    `That` is always `ArrayBuffer[B]` because an implicit of type `CanBuildFrom[ArrayBuffer, B, ArrayBuffer[B]]`
+ *    is defined in object `ArrayBuffer`.
+ *  @define $bfinfo an implicit value of class `CanBuildFrom` which determines the
+ *    result class `That` from the current representation type `Repr`
+ *    and the new element type `B`. This is usually the `canBuildFrom` value
+ *    defined in object `ArrayBuffer`.
+ *  @define orderDependent 
+ *  @define orderDependentFold
+ *  @define mayNotTerminateInf
+ *  @define willNotTerminateInf
  */
- at serializable
-class ArrayBuffer[A] extends RandomAccessSeq.Mutable[A] with Buffer[A] with ResizableArray[A] {
+ at serializable @SerialVersionUID(1529165946227428979L)
+class ArrayBuffer[A](override protected val initialSize: Int) 
+  extends Buffer[A] 
+     with GenericTraversableTemplate[A, ArrayBuffer]
+     with BufferLike[A, ArrayBuffer[A]]
+     with IndexedSeqOptimized[A, ArrayBuffer[A]]
+     with Builder[A, ArrayBuffer[A]] 
+     with ResizableArray[A] {
+
+  override def companion: GenericCompanion[ArrayBuffer] = ArrayBuffer
+
+  import scala.collection.Traversable
+
+  def this() = this(16)
+
+  def clear() { reduceToSize(0) }
+
+  override def sizeHint(len: Int) {
+    if (len > size && len >= 1) {
+      val newarray = new Array[AnyRef](len)
+      compat.Platform.arraycopy(array, 0, newarray, 0, size0)
+      array = newarray
+    }
+  }
+  
   /** Appends a single element to this buffer and returns
-   *  the identity of the buffer. It takes constant time.
+   *  the identity of the buffer. It takes constant amortized time.
    *
    *  @param elem  the element to append.
+   *  @return      the updated buffer.
    */
-  def +=(elem: A) {
+  def +=(elem: A): this.type = {
     ensureSize(size0 + 1)
     array(size0) = elem.asInstanceOf[AnyRef]
     size0 += 1
+    this
   }
 
-  /** Appends a number of elements provided by an iterable object
-   *  via its <code>elements</code> method. The identity of the
-   *  buffer is returned.
+  /** Appends a number of elements provided by a traversable object.
+   *  The identity of the buffer is returned.
    *
-   *  @param iter  the iterable object.
+   *  @param xs    the traversable object.
    *  @return      the updated buffer.
    */
-  override def ++=(iter: Iterable[A]) { iter copyToBuffer this }
-
-  override def ++[B >: A](that: Iterable[B]) : ArrayBuffer[B] = {
-    val buf = new ArrayBuffer[B]
-    this copyToBuffer buf
-    that copyToBuffer buf
-    buf
-  }
-  
-  /** Appends a number of elements in an array
-   *
-   *  @param src    the array
-   *  @param start  the first element to append
-   *  @param len    the number of elements to append           
-   */
-  override def ++=(src: Array[A], start: Int, len: Int) {
-    ensureSize(size0 + len)
-    Array.copy(src, start, array, size0, len)
-    size0 += len
+  override def ++=(xs: TraversableOnce[A]): this.type = xs match {
+    case v: IndexedSeq[_] =>
+      val n = v.length
+      ensureSize(size0 + n)
+      v.copyToArray(array.asInstanceOf[scala.Array[Any]], size0, n)
+      size0 += n
+      this
+    case _ =>
+      super.++=(xs)
   }
 
-  /** Prepends a single element to this buffer and return
+  /** Prepends a single element to this buffer and returns
    *  the identity of the buffer. It takes time linear in 
    *  the buffer size.
    *
    *  @param elem  the element to append.
-   *  @return      the updated buffer.
+   *  @return      the updated buffer. 
    */
-  def +:(elem: A): Buffer[A] = {
+  def +=:(elem: A): this.type = {
     ensureSize(size0 + 1)
     copy(0, 1, size0)
     array(0) = elem.asInstanceOf[AnyRef]
@@ -78,111 +109,79 @@ class ArrayBuffer[A] extends RandomAccessSeq.Mutable[A] with Buffer[A] with Resi
     this
   }
    
-  /** Returns the i-th element of this ArrayBuffer. It takes constant time.
+  /** Prepends a number of elements provided by a traversable object.
+   *  The identity of the buffer is returned.
    *
-   *  @param i  the specified index.
-   *  @return   the i-th element.
-   *  @throws Predef.IndexOutOfBoundException if <code>i</code> is out of bounds.
-   */
-  override def apply(i: Int) = { 
-    if ((i < 0) || (i >= size0))
-      throw new IndexOutOfBoundsException(i.toString())
-    else
-      array(i).asInstanceOf[A]
-  }
-
-  /** Prepends a number of elements provided by an iterable object
-   *  via its <code>elements</code> method. The identity of the
-   *  buffer is returned.
-   *
-   *  @param iter  the iterable object.
+   *  @param xs    the traversable object.
    *  @return      the updated buffer.
    */
-  override def ++:(iter: Iterable[A]): Buffer[A] = { insertAll(0, iter); this }
+  override def ++=:(xs: TraversableOnce[A]): this.type = { insertAll(0, xs.toTraversable); this }
   
-  /** Inserts new elements at the index <code>n</code>. Opposed to method
-   *  <code>update</code>, this method will not replace an element with a
-   *  one. Instead, it will insert a new element at index <code>n</code>.
-   *
+  /** Inserts new elements at the index `n`. Opposed to method
+   *  `update`, this method will not replace an element with a
+   *  one. Instead, it will insert a new element at index `n`.
+   *  
    *  @param n     the index where a new element will be inserted.
-   *  @param iter  the iterable object providing all elements to insert.
-   *  @throws Predef.IndexOutOfBoundsException if <code>n</code> is out of bounds.
+   *  @param seq   the traversable object providing all elements to insert.
+   *  @throws Predef.IndexOutOfBoundsException if `n` is out of bounds.
    */
-  def insertAll(n: Int, iter: Iterable[A]) {
-    if ((n < 0) || (n > size0))
-      throw new IndexOutOfBoundsException("cannot insert element at " + n);
-    val xs = iter.elements.toList
+  def insertAll(n: Int, seq: Traversable[A]) {
+    if (n < 0 || n > size0) throw new IndexOutOfBoundsException(n.toString)
+    val xs = seq.toList
     val len = xs.length
     ensureSize(size0 + len)
     copy(n, n + len, size0 - n)
-    xs.copyToArray(array.asInstanceOf[Array[Any]], n)
+    xs.copyToArray(array.asInstanceOf[scala.Array[Any]], n)
     size0 += len
   }
   
-  /** Replace element at index <code>n</code> with the new element
-   *  <code>newelem</code>. It takes constant time.
-   *
-   *  @param n       the index of the element to replace.
-   *  @param newelem the new element.
-   *  @throws Predef.IndexOutOfBoundsException if <code>n</code> is out of bounds.
-   */
-  def update(n: Int, newelem: A) {
-    if ((n < 0) || (n >= size0))
-      throw new IndexOutOfBoundsException("cannot update element at " + n)
-    else {
-      val res = array(n).asInstanceOf[A]
-      array(n) = newelem.asInstanceOf[AnyRef]
-      res
-    }
-  }
-  
   /** Removes the element on a given index position. It takes time linear in
    *  the buffer size.
-   *
-   *  @param n  the index which refers to the element to delete.
-   *  @return   the updated array buffer.
-   *  @throws Predef.IndexOutOfBoundsException if <code>n</code> is out of bounds.
+   *  
+   *  @param n       the index which refers to the first element to delete.
+   *  @param count   the number of elements to delete
+   *  @throws Predef.IndexOutOfBoundsException if `n` is out of bounds.
    */
-  def remove(n: Int): A = {
-    if ((n < 0) || (n >= size0))
-      throw new IndexOutOfBoundsException("cannot remove element at " + n);
-    val res = array(n).asInstanceOf[A]
-    copy(n + 1, n, size0 - n - 1)
-    size0 -= 1
-    res
+  override def remove(n: Int, count: Int) {
+    require(count >= 0, "removing negative number of elements")
+    if (n < 0 || n > size0 - count) throw new IndexOutOfBoundsException(n.toString)
+    copy(n + count, n, size0 - (n + count))
+    reduceToSize(size0 - count)
   }
-  
-  /** Clears the buffer contents.
+
+  /** Removes the element at a given index position.
+   *  
+   *  @param n  the index which refers to the element to delete.
+   *  @return   the element that was formerly at position `n`.
    */
-  def clear() {
-    size0 = 0
+  def remove(n: Int): A = {
+    val result = apply(n)
+    remove(n, 1)
+    result
   }
-  
+
   /** Return a clone of this buffer.
    *
-   *  @return an <code>ArrayBuffer</code> with the same elements.
+   *  @return an `ArrayBuffer` with the same elements.
    */
-  override def clone(): Buffer[A] = {
-    val res = new ArrayBuffer[A]
-    res ++= this
-    res
-  }
-  
-  /** Checks if two buffers are structurally identical.
-   *
-   *  @return true, iff both buffers contain the same sequence of elements.
-   */
-  override def equals(obj: Any): Boolean = obj match {
-    case that: ArrayBuffer[_] =>
-      this.length == that.length &&
-    elements.zip(that.elements).forall {
-      case (thiselem, thatelem) => thiselem == thatelem
-    }
-    case _ =>
-      false
-  }
+  override def clone(): ArrayBuffer[A] = new ArrayBuffer[A] ++= this
+
+  def result: ArrayBuffer[A] = this
 
   /** Defines the prefix of the string representation.
    */
-  override protected def stringPrefix: String = "ArrayBuffer"
+  override def stringPrefix: String = "ArrayBuffer"
+}
+
+/** Factory object for the `ArrayBuffer` class.
+ *  
+ *  $factoryInfo
+ *  @define coll array buffer
+ *  @define Coll ArrayBuffer
+ */
+object ArrayBuffer extends SeqFactory[ArrayBuffer] {
+  /** $genericCanBuildFromInfo */
+  implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, ArrayBuffer[A]] = new GenericCanBuildFrom[A]
+  def newBuilder[A]: Builder[A, ArrayBuffer[A]] = new ArrayBuffer[A]
 }
+
diff --git a/src/library/scala/collection/mutable/ArrayBuilder.scala b/src/library/scala/collection/mutable/ArrayBuilder.scala
new file mode 100644
index 0000000..64cdc16
--- /dev/null
+++ b/src/library/scala/collection/mutable/ArrayBuilder.scala
@@ -0,0 +1,682 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+package mutable
+
+import generic._
+import scala.reflect.ClassManifest
+
+/** A builder class for arrays.
+ *  
+ *  @since 2.8
+ *  
+ *  @tparam T    the type of the elements for the builder.
+ */
+ at serializable
+abstract class ArrayBuilder[T] extends Builder[T, Array[T]]
+
+/** A companion object for array builders.
+ *  
+ *  @since 2.8
+ */
+object ArrayBuilder {
+  
+  /** Creates a new arraybuilder of type `T`.
+   *  
+   *  @tparam T     type of the elements for the array builder, with a `ClassManifest` context bound.
+   *  @return       a new empty array builder.
+   */
+  def make[T: ClassManifest](): ArrayBuilder[T] =
+    implicitly[ClassManifest[T]].newArrayBuilder() 
+  
+  /** A class for array builders for arrays of reference types.
+   *  
+   *  @tparam T     type of elements for the array builder, subtype of `AnyRef` with a `ClassManifest` context bound.
+   */
+  class ofRef[T <: AnyRef : ClassManifest] extends ArrayBuilder[T] {
+
+    private var elems: Array[T] = _
+    private var capacity: Int = 0
+    private var size: Int = 0
+
+    private def mkArray(size: Int): Array[T] = {
+      val newelems = new Array[T](size)
+      if (this.size > 0) Array.copy(elems, 0, newelems, 0, this.size)
+      newelems
+    }
+
+    private def resize(size: Int) {
+      elems = mkArray(size)
+      capacity = size
+    }
+
+    override def sizeHint(size: Int) {
+      if (capacity < size) resize(size)
+    }
+
+    private def ensureSize(size: Int) {
+      if (capacity < size || capacity == 0) {
+        var newsize = if (capacity == 0) 16 else capacity * 2
+        while (newsize < size) newsize *= 2
+        resize(newsize)
+      } 
+    } 
+
+    def +=(elem: T): this.type = {
+      ensureSize(size + 1)
+      elems(size) = elem
+      size += 1
+      this
+    }
+
+    override def ++=(xs: TraversableOnce[T]): this.type = (xs: AnyRef) match {
+      case xs: WrappedArray.ofRef[_] =>
+        ensureSize(this.size + xs.length)
+        Array.copy(xs.array, 0, elems, this.size, xs.length)
+        size += xs.length
+        this
+      case _ =>
+        super.++=(xs)
+    }
+
+    def clear() {
+      size = 0
+    }
+
+    def result() = {
+      if (capacity != 0 && capacity == size) elems 
+      else mkArray(size)
+    }
+
+    override def equals(other: Any): Boolean = other match {
+      case x: ofRef[_] => (size == x.size) && (elems == x.elems)
+      case _ => false
+    }
+
+    override def toString = "ArrayBuilder.ofRef"
+  }
+  
+  /** A class for array builders for arrays of `byte`s. */
+  class ofByte extends ArrayBuilder[Byte] {
+
+    private var elems: Array[Byte] = _
+    private var capacity: Int = 0
+    private var size: Int = 0
+
+    private def mkArray(size: Int): Array[Byte] = {
+      val newelems = new Array[Byte](size)
+      if (this.size > 0) Array.copy(elems, 0, newelems, 0, this.size)
+      newelems
+    }
+
+    private def resize(size: Int) {
+      elems = mkArray(size)
+      capacity = size
+    }
+
+    override def sizeHint(size: Int) {
+      if (capacity < size) resize(size)
+    }
+
+    private def ensureSize(size: Int) {
+      if (capacity < size || capacity == 0) {
+        var newsize = if (capacity == 0) 16 else capacity * 2
+        while (newsize < size) newsize *= 2
+        resize(newsize)
+      } 
+    } 
+    
+    def +=(elem: Byte): this.type = {
+      ensureSize(size + 1)
+      elems(size) = elem
+      size += 1
+      this
+    }
+
+    override def ++=(xs: TraversableOnce[Byte]): this.type = xs match {
+      case xs: WrappedArray.ofByte =>
+        ensureSize(this.size + xs.length)
+        Array.copy(xs.array, 0, elems, this.size, xs.length)
+        size += xs.length
+        this
+      case _ =>
+        super.++=(xs)
+    }
+
+    def clear() {
+      size = 0
+    }
+
+    def result() = {
+      if (capacity != 0 && capacity == size) elems 
+      else mkArray(size)
+    }
+
+    override def equals(other: Any): Boolean = other match {
+      case x: ofByte => (size == x.size) && (elems == x.elems)
+      case _ => false
+    }
+
+    override def toString = "ArrayBuilder.ofByte"
+  }
+
+  /** A class for array builders for arrays of `short`s. */
+  class ofShort extends ArrayBuilder[Short] {
+
+    private var elems: Array[Short] = _
+    private var capacity: Int = 0
+    private var size: Int = 0
+
+    private def mkArray(size: Int): Array[Short] = {
+      val newelems = new Array[Short](size)
+      if (this.size > 0) Array.copy(elems, 0, newelems, 0, this.size)
+      newelems
+    }
+
+    private def resize(size: Int) {
+      elems = mkArray(size)
+      capacity = size
+    }
+
+    override def sizeHint(size: Int) {
+      if (capacity < size) resize(size)
+    }
+    
+    private def ensureSize(size: Int) {
+      if (capacity < size || capacity == 0) {
+        var newsize = if (capacity == 0) 16 else capacity * 2
+        while (newsize < size) newsize *= 2
+        resize(newsize)
+      } 
+    } 
+
+    def +=(elem: Short): this.type = {
+      ensureSize(size + 1)
+      elems(size) = elem
+      size += 1
+      this
+    }
+
+    override def ++=(xs: TraversableOnce[Short]): this.type = xs match {
+      case xs: WrappedArray.ofShort =>
+        ensureSize(this.size + xs.length)
+        Array.copy(xs.array, 0, elems, this.size, xs.length)
+        size += xs.length
+        this
+      case _ =>
+        super.++=(xs)
+    }
+
+    def clear() {
+      size = 0
+    }
+
+    def result() = {
+      if (capacity != 0 && capacity == size) elems 
+      else mkArray(size)
+    }
+
+    override def equals(other: Any): Boolean = other match {
+      case x: ofShort => (size == x.size) && (elems == x.elems)
+      case _ => false
+    }
+
+    override def toString = "ArrayBuilder.ofShort"
+  }
+
+  /** A class for array builders for arrays of `char`s. */
+  class ofChar extends ArrayBuilder[Char] {
+
+    private var elems: Array[Char] = _
+    private var capacity: Int = 0
+    private var size: Int = 0
+
+    private def mkArray(size: Int): Array[Char] = {
+      val newelems = new Array[Char](size)
+      if (this.size > 0) Array.copy(elems, 0, newelems, 0, this.size)
+      newelems
+    }
+
+    private def resize(size: Int) {
+      elems = mkArray(size)
+      capacity = size
+    }
+
+    override def sizeHint(size: Int) {
+      if (capacity < size) resize(size)
+    }
+    
+    private def ensureSize(size: Int) {
+      if (capacity < size || capacity == 0) {
+        var newsize = if (capacity == 0) 16 else capacity * 2
+        while (newsize < size) newsize *= 2
+        resize(newsize)
+      } 
+    }
+    
+    def +=(elem: Char): this.type = {
+      ensureSize(size + 1)
+      elems(size) = elem
+      size += 1
+      this
+    }
+
+    override def ++=(xs: TraversableOnce[Char]): this.type = xs match {
+      case xs: WrappedArray.ofChar =>
+        ensureSize(this.size + xs.length)
+        Array.copy(xs.array, 0, elems, this.size, xs.length)
+        size += xs.length
+        this
+      case _ =>
+        super.++=(xs)
+    }
+
+    def clear() {
+      size = 0
+    }
+
+    def result() = {
+      if (capacity != 0 && capacity == size) elems 
+      else mkArray(size)
+    }
+
+    override def equals(other: Any): Boolean = other match {
+      case x: ofChar => (size == x.size) && (elems == x.elems)
+      case _ => false
+    }
+
+    override def toString = "ArrayBuilder.ofChar"
+  }
+
+  /** A class for array builders for arrays of `int`s. */
+  class ofInt extends ArrayBuilder[Int] {
+
+    private var elems: Array[Int] = _
+    private var capacity: Int = 0
+    private var size: Int = 0
+
+    private def mkArray(size: Int): Array[Int] = {
+      val newelems = new Array[Int](size)
+      if (this.size > 0) Array.copy(elems, 0, newelems, 0, this.size)
+      newelems
+    }
+
+    private def resize(size: Int) {
+      elems = mkArray(size)
+      capacity = size
+    }
+
+    override def sizeHint(size: Int) {
+      if (capacity < size) resize(size)
+    }
+    
+    private def ensureSize(size: Int) {
+      if (capacity < size || capacity == 0) {
+        var newsize = if (capacity == 0) 16 else capacity * 2
+        while (newsize < size) newsize *= 2
+        resize(newsize)
+      } 
+    }
+    
+    def +=(elem: Int): this.type = {
+      ensureSize(size + 1)
+      elems(size) = elem
+      size += 1
+      this
+    }
+
+    override def ++=(xs: TraversableOnce[Int]): this.type = xs match {
+      case xs: WrappedArray.ofInt =>
+        ensureSize(this.size + xs.length)
+        Array.copy(xs.array, 0, elems, this.size, xs.length)
+        size += xs.length
+        this
+      case _ =>
+        super.++=(xs)
+    }
+
+    def clear() {
+      size = 0
+    }
+
+    def result() = {
+      if (capacity != 0 && capacity == size) elems 
+      else mkArray(size)
+    }
+
+    override def equals(other: Any): Boolean = other match {
+      case x: ofInt => (size == x.size) && (elems == x.elems)
+      case _ => false
+    }
+
+    override def toString = "ArrayBuilder.ofInt"
+  }
+
+  /** A class for array builders for arrays of `long`s. */
+  class ofLong extends ArrayBuilder[Long] {
+
+    private var elems: Array[Long] = _
+    private var capacity: Int = 0
+    private var size: Int = 0
+
+    private def mkArray(size: Int): Array[Long] = {
+      val newelems = new Array[Long](size)
+      if (this.size > 0) Array.copy(elems, 0, newelems, 0, this.size)
+      newelems
+    }
+
+    private def resize(size: Int) {
+      elems = mkArray(size)
+      capacity = size
+    }
+
+    override def sizeHint(size: Int) {
+      if (capacity < size) resize(size)
+    }
+    
+    private def ensureSize(size: Int) {
+      if (capacity < size || capacity == 0) {
+        var newsize = if (capacity == 0) 16 else capacity * 2
+        while (newsize < size) newsize *= 2
+        resize(newsize)
+      } 
+    }
+    
+    def +=(elem: Long): this.type = {
+      ensureSize(size + 1)
+      elems(size) = elem
+      size += 1
+      this
+    }
+
+    override def ++=(xs: TraversableOnce[Long]): this.type = xs match {
+      case xs: WrappedArray.ofLong =>
+        ensureSize(this.size + xs.length)
+        Array.copy(xs.array, 0, elems, this.size, xs.length)
+        size += xs.length
+        this
+      case _ =>
+        super.++=(xs)
+    }
+
+    def clear() {
+      size = 0
+    }
+
+    def result() = {
+      if (capacity != 0 && capacity == size) elems 
+      else mkArray(size)
+    }
+
+    override def equals(other: Any): Boolean = other match {
+      case x: ofLong => (size == x.size) && (elems == x.elems)
+      case _ => false
+    }
+
+    override def toString = "ArrayBuilder.ofLong"
+  }
+
+  /** A class for array builders for arrays of `float`s. */
+  class ofFloat extends ArrayBuilder[Float] {
+
+    private var elems: Array[Float] = _
+    private var capacity: Int = 0
+    private var size: Int = 0
+
+    private def mkArray(size: Int): Array[Float] = {
+      val newelems = new Array[Float](size)
+      if (this.size > 0) Array.copy(elems, 0, newelems, 0, this.size)
+      newelems
+    }
+
+    private def resize(size: Int) {
+      elems = mkArray(size)
+      capacity = size
+    }
+
+    override def sizeHint(size: Int) {
+      if (capacity < size) resize(size)
+    }
+    
+    private def ensureSize(size: Int) {
+      if (capacity < size || capacity == 0) {
+        var newsize = if (capacity == 0) 16 else capacity * 2
+        while (newsize < size) newsize *= 2
+        resize(newsize)
+      } 
+    }
+    
+    def +=(elem: Float): this.type = {
+      ensureSize(size + 1)
+      elems(size) = elem
+      size += 1
+      this
+    }
+
+    override def ++=(xs: TraversableOnce[Float]): this.type = xs match {
+      case xs: WrappedArray.ofFloat =>
+        ensureSize(this.size + xs.length)
+        Array.copy(xs.array, 0, elems, this.size, xs.length)
+        size += xs.length
+        this
+      case _ =>
+        super.++=(xs)
+    }
+
+    def clear() {
+      size = 0
+    }
+
+    def result() = {
+      if (capacity != 0 && capacity == size) elems 
+      else mkArray(size)
+    }
+
+    override def equals(other: Any): Boolean = other match {
+      case x: ofFloat => (size == x.size) && (elems == x.elems)
+      case _ => false
+    }
+
+    override def toString = "ArrayBuilder.ofFloat"
+  }
+
+  /** A class for array builders for arrays of `double`s. */
+  class ofDouble extends ArrayBuilder[Double] {
+
+    private var elems: Array[Double] = _
+    private var capacity: Int = 0
+    private var size: Int = 0
+
+    private def mkArray(size: Int): Array[Double] = {
+      val newelems = new Array[Double](size)
+      if (this.size > 0) Array.copy(elems, 0, newelems, 0, this.size)
+      newelems
+    }
+
+    private def resize(size: Int) {
+      elems = mkArray(size)
+      capacity = size
+    }
+
+    override def sizeHint(size: Int) {
+      if (capacity < size) resize(size)
+    }
+    
+    private def ensureSize(size: Int) {
+      if (capacity < size || capacity == 0) {
+        var newsize = if (capacity == 0) 16 else capacity * 2
+        while (newsize < size) newsize *= 2
+        resize(newsize)
+      } 
+    }
+    
+    def +=(elem: Double): this.type = {
+      ensureSize(size + 1)
+      elems(size) = elem
+      size += 1
+      this
+    }
+
+    override def ++=(xs: TraversableOnce[Double]): this.type = xs match {
+      case xs: WrappedArray.ofDouble =>
+        ensureSize(this.size + xs.length)
+        Array.copy(xs.array, 0, elems, this.size, xs.length)
+        size += xs.length
+        this
+      case _ =>
+        super.++=(xs)
+    }
+
+    def clear() {
+      size = 0
+    }
+
+    def result() = {
+      if (capacity != 0 && capacity == size) elems 
+      else mkArray(size)
+    }
+
+    override def equals(other: Any): Boolean = other match {
+      case x: ofDouble => (size == x.size) && (elems == x.elems)
+      case _ => false
+    }
+
+    override def toString = "ArrayBuilder.ofDouble"
+  }
+
+  /** A class for array builders for arrays of `boolean`s. */
+  class ofBoolean extends ArrayBuilder[Boolean] {
+
+    private var elems: Array[Boolean] = _
+    private var capacity: Int = 0
+    private var size: Int = 0
+
+    private def mkArray(size: Int): Array[Boolean] = {
+      val newelems = new Array[Boolean](size)
+      if (this.size > 0) Array.copy(elems, 0, newelems, 0, this.size)
+      newelems
+    }
+
+    private def resize(size: Int) {
+      elems = mkArray(size)
+      capacity = size
+    }
+
+    override def sizeHint(size: Int) {
+      if (capacity < size) resize(size)
+    }
+    
+    private def ensureSize(size: Int) {
+      if (capacity < size || capacity == 0) {
+        var newsize = if (capacity == 0) 16 else capacity * 2
+        while (newsize < size) newsize *= 2
+        resize(newsize)
+      } 
+    }
+    
+    def +=(elem: Boolean): this.type = {
+      ensureSize(size + 1)
+      elems(size) = elem
+      size += 1
+      this
+    }
+
+    override def ++=(xs: TraversableOnce[Boolean]): this.type = xs match {
+      case xs: WrappedArray.ofBoolean =>
+        ensureSize(this.size + xs.length)
+        Array.copy(xs.array, 0, elems, this.size, xs.length)
+        size += xs.length
+        this
+      case _ =>
+        super.++=(xs)
+    }
+
+    def clear() {
+      size = 0
+    }
+
+    def result() = {
+      if (capacity != 0 && capacity == size) elems 
+      else mkArray(size)
+    }
+
+    override def equals(other: Any): Boolean = other match {
+      case x: ofBoolean => (size == x.size) && (elems == x.elems)
+      case _ => false
+    }
+
+    override def toString = "ArrayBuilder.ofBoolean"
+  }
+
+  /** A class for array builders for arrays of `Unit` type. */
+  class ofUnit extends ArrayBuilder[Unit] {
+
+    private var elems: Array[Unit] = _
+    private var capacity: Int = 0
+    private var size: Int = 0
+
+    private def mkArray(size: Int): Array[Unit] = {
+      val newelems = new Array[Unit](size)
+      if (this.size > 0) Array.copy(elems, 0, newelems, 0, this.size)
+      newelems
+    }
+
+    private def resize(size: Int) {
+      elems = mkArray(size)
+      capacity = size
+    }
+
+    override def sizeHint(size: Int) {
+      if (capacity < size) resize(size)
+    }
+    
+    private def ensureSize(size: Int) {
+      if (capacity < size || capacity == 0) {
+        var newsize = if (capacity == 0) 16 else capacity * 2
+        while (newsize < size) newsize *= 2
+        resize(newsize)
+      } 
+    }
+    
+    def +=(elem: Unit): this.type = {
+      ensureSize(size + 1)
+      elems(size) = elem
+      size += 1
+      this
+    }
+
+    override def ++=(xs: TraversableOnce[Unit]): this.type = xs match {
+      case xs: WrappedArray.ofUnit =>
+        ensureSize(this.size + xs.length)
+        Array.copy(xs.array, 0, elems, this.size, xs.length)
+        size += xs.length
+        this
+      case _ =>
+        super.++=(xs)
+    }
+
+    def clear() {
+      size = 0
+    }
+
+    def result() = {
+      if (capacity != 0 && capacity == size) elems 
+      else mkArray(size)
+    }
+
+    override def equals(other: Any): Boolean = other match {
+      case x: ofUnit => (size == x.size) && (elems == x.elems)
+      case _ => false
+    }
+
+    override def toString = "ArrayBuilder.ofUnit"
+  }
+}
diff --git a/src/library/scala/collection/mutable/ArrayLike.scala b/src/library/scala/collection/mutable/ArrayLike.scala
new file mode 100644
index 0000000..880c62a
--- /dev/null
+++ b/src/library/scala/collection/mutable/ArrayLike.scala
@@ -0,0 +1,67 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+package mutable
+import generic._
+
+/** A common supertrait of `ArrayOps` and `WrappedArray` that factors out most
+ *  operations on arrays and wrapped arrays.
+ *  
+ *  @tparam A     type of the elements contained in the array like object.
+ *  @tparam Repr  the type of the actual collection containing the elements.
+ *  
+ *  @define Coll ArrayLike
+ *  @version 2.8
+ *  @since   2.8
+ */
+trait ArrayLike[A, +Repr] extends IndexedSeqOptimized[A, Repr] { self =>
+
+  /** Creates a possible nested `IndexedSeq` which consists of all the elements
+   *  of this array. If the elements are arrays themselves, the `deep` transformation
+   *  is applied recursively to them. The `stringPrefix` of the `IndexedSeq` is
+   *  "Array", hence the `IndexedSeq` prints like an array with all its
+   *  elements shown, and the same recursively for any subarrays.
+   *
+   *  Example:
+   *  {{{
+   *  Array(Array(1, 2), Array(3, 4)).deep.toString
+   *  }}}
+   *  prints: `Array(Array(1, 2), Array(3, 4))`
+   *
+   *  @return    An possibly nested indexed sequence of consisting of all the elements of the array.
+   */
+  def deep: scala.collection.IndexedSeq[Any] = new scala.collection.IndexedSeq[Any] {
+    def length = self.length
+    def apply(idx: Int): Any = self.apply(idx) match {
+      case x: AnyRef if x.getClass.isArray => WrappedArray.make(x).deep
+      case x => x
+    }
+    override def stringPrefix = "Array"
+  }
+
+  @deprecated("use deep.toString instead")
+  final def deepToString() = 
+    deep.toString
+
+  @deprecated("use deep.mkString instead")
+  final def deepMkString(start: String, sep: String, end: String): String =
+    deep.mkString(start, sep, end)
+
+  @deprecated("use deep.mkString instead")
+  final def deepMkString(sep: String): String = 
+    deepMkString("", sep, "")
+
+  @deprecated("use array1.deep.equals(array2.deep) instead")
+  final def deepEquals(that: Any): Boolean = that match {
+    case x: AnyRef if x.getClass.isArray => deep.equals(WrappedArray.make(x).deep)
+    case _ => false
+  }
+}
diff --git a/src/library/scala/collection/mutable/ArrayOps.scala b/src/library/scala/collection/mutable/ArrayOps.scala
new file mode 100644
index 0000000..d1e1aa2
--- /dev/null
+++ b/src/library/scala/collection/mutable/ArrayOps.scala
@@ -0,0 +1,219 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+package mutable
+import compat.Platform.arraycopy
+
+import scala.reflect.ClassManifest
+
+/** This class serves as a wrapper for `Array`s with all the operations found in
+ *  indexed sequences. Where needed, instances of arrays are implicitly converted
+ *  into this class.
+ *  
+ *  The difference between this class and `WrappedArray` is that calling transformer
+ *  methods such as `filter` and `map` will yield an array, whereas a `WrappedArray`
+ *  will remain a `WrappedArray`.
+ *  
+ *  @since 2.8
+ *  
+ *  @tparam T   type of the elements contained in this array.
+ *  
+ *  @define Coll ArrayOps
+ *  @define orderDependent 
+ *  @define orderDependentFold
+ *  @define mayNotTerminateInf
+ *  @define willNotTerminateInf
+ */
+abstract class ArrayOps[T] extends ArrayLike[T, Array[T]] {
+
+  private def rowBuilder[U]: Builder[U, Array[U]] = 
+    Array.newBuilder(
+      ClassManifest.fromClass(
+        repr.getClass.getComponentType.getComponentType.asInstanceOf[Predef.Class[U]]))
+
+  override def copyToArray[U >: T](xs: Array[U], start: Int, len: Int) {
+    var l = len
+    if (repr.length < l) l = repr.length
+    if (xs.length - start < l) l = xs.length - start max 0 
+    Array.copy(repr, 0, xs, start, l)
+  }
+
+  override def toArray[U >: T : ClassManifest]: Array[U] =
+    if (implicitly[ClassManifest[U]].erasure eq repr.getClass.getComponentType)
+      repr.asInstanceOf[Array[U]]
+    else 
+      super.toArray[U]
+  
+  /** Flattens a two-dimensional array by concatenating all its rows
+   *  into a single array.
+   *  
+   *  @tparam U        Type of row elements.
+   *  @param asArray   A function that converts elements of this array to rows - arrays of type `U`.
+   *  @return          An array obtained by concatenating rows of this array.
+   */
+  def flatten[U](implicit asArray: T => /*<:<!!!*/ Array[U]): Array[U] = {
+    val b = rowBuilder[U]
+    for (xs <- this)
+      b ++= asArray(xs)
+    b.result
+  }
+
+  /** Transposes a two dimensional array.
+   *  
+   *  @tparam U       Type of row elements.
+   *  @param asArray  A function that converts elements of this array to rows - arrays of type `U`.
+   *  @return         An array obtained by replacing elements of this arrays with rows the represent.
+   */
+  def transpose[U](implicit asArray: T => Array[U]): Array[Array[U]] = {
+    val bs = asArray(head) map (_ => rowBuilder[U])
+    for (xs <- this) {
+      var i = 0
+      for (x <- asArray(xs)) {
+        bs(i) += x
+        i += 1
+      }
+    }
+    val bb: Builder[Array[U], Array[Array[U]]] = Array.newBuilder(
+      ClassManifest.fromClass(
+        repr.getClass.getComponentType.asInstanceOf[Predef.Class[Array[U]]]))
+    for (b <- bs) bb += b.result
+    bb.result
+  }
+}
+
+/**
+ * A companion object for `ArrayOps`.
+ * 
+ * @since 2.8
+ */
+object ArrayOps {
+
+  /** A class of `ArrayOps` for arrays containing reference types. */
+  class ofRef[T <: AnyRef](override val repr: Array[T]) extends ArrayOps[T] with ArrayLike[T, Array[T]] {
+
+    override protected[this] def thisCollection: WrappedArray[T] = new WrappedArray.ofRef[T](repr)
+    override protected[this] def toCollection(repr: Array[T]): WrappedArray[T] = new WrappedArray.ofRef[T](repr)
+    override protected[this] def newBuilder = new ArrayBuilder.ofRef[T]()(
+      ClassManifest.classType[T](repr.getClass.getComponentType))
+
+    def length: Int = repr.length
+    def apply(index: Int): T = repr(index)
+    def update(index: Int, elem: T) { repr(index) = elem }
+  } 
+  
+  /** A class of `ArrayOps` for arrays containing `byte`s. */
+  class ofByte(override val repr: Array[Byte]) extends ArrayOps[Byte] with ArrayLike[Byte, Array[Byte]] {
+
+    override protected[this] def thisCollection: WrappedArray[Byte] = new WrappedArray.ofByte(repr)
+    override protected[this] def toCollection(repr: Array[Byte]): WrappedArray[Byte] = new WrappedArray.ofByte(repr)
+    override protected[this] def newBuilder = new ArrayBuilder.ofByte
+
+    def length: Int = repr.length
+    def apply(index: Int): Byte = repr(index)
+    def update(index: Int, elem: Byte) { repr(index) = elem }
+  } 
+
+  /** A class of `ArrayOps` for arrays containing `short`s. */
+  class ofShort(override val repr: Array[Short]) extends ArrayOps[Short] with ArrayLike[Short, Array[Short]] {
+
+    override protected[this] def thisCollection: WrappedArray[Short] = new WrappedArray.ofShort(repr)
+    override protected[this] def toCollection(repr: Array[Short]): WrappedArray[Short] = new WrappedArray.ofShort(repr)
+    override protected[this] def newBuilder = new ArrayBuilder.ofShort
+
+    def length: Int = repr.length
+    def apply(index: Int): Short = repr(index)
+    def update(index: Int, elem: Short) { repr(index) = elem }
+  } 
+
+  /** A class of `ArrayOps` for arrays containing `char`s. */
+  class ofChar(override val repr: Array[Char]) extends ArrayOps[Char] with ArrayLike[Char, Array[Char]] {
+
+    override protected[this] def thisCollection: WrappedArray[Char] = new WrappedArray.ofChar(repr)
+    override protected[this] def toCollection(repr: Array[Char]): WrappedArray[Char] = new WrappedArray.ofChar(repr)
+    override protected[this] def newBuilder = new ArrayBuilder.ofChar
+
+    def length: Int = repr.length
+    def apply(index: Int): Char = repr(index)
+    def update(index: Int, elem: Char) { repr(index) = elem }
+  } 
+
+  /** A class of `ArrayOps` for arrays containing `int`s. */
+  class ofInt(override val repr: Array[Int]) extends ArrayOps[Int] with ArrayLike[Int, Array[Int]] {
+
+    override protected[this] def thisCollection: WrappedArray[Int] = new WrappedArray.ofInt(repr)
+    override protected[this] def toCollection(repr: Array[Int]): WrappedArray[Int] = new WrappedArray.ofInt(repr)
+    override protected[this] def newBuilder = new ArrayBuilder.ofInt
+
+    def length: Int = repr.length
+    def apply(index: Int): Int = repr(index)
+    def update(index: Int, elem: Int) { repr(index) = elem }
+  } 
+
+  /** A class of `ArrayOps` for arrays containing `long`s. */
+  class ofLong(override val repr: Array[Long]) extends ArrayOps[Long] with ArrayLike[Long, Array[Long]] {
+
+    override protected[this] def thisCollection: WrappedArray[Long] = new WrappedArray.ofLong(repr)
+    override protected[this] def toCollection(repr: Array[Long]): WrappedArray[Long] = new WrappedArray.ofLong(repr)
+    override protected[this] def newBuilder = new ArrayBuilder.ofLong
+
+    def length: Int = repr.length
+    def apply(index: Int): Long = repr(index)
+    def update(index: Int, elem: Long) { repr(index) = elem }
+  } 
+
+  /** A class of `ArrayOps` for arrays containing `float`s. */
+  class ofFloat(override val repr: Array[Float]) extends ArrayOps[Float] with ArrayLike[Float, Array[Float]] {
+
+    override protected[this] def thisCollection: WrappedArray[Float] = new WrappedArray.ofFloat(repr)
+    override protected[this] def toCollection(repr: Array[Float]): WrappedArray[Float] = new WrappedArray.ofFloat(repr)
+    override protected[this] def newBuilder = new ArrayBuilder.ofFloat
+
+    def length: Int = repr.length
+    def apply(index: Int): Float = repr(index)
+    def update(index: Int, elem: Float) { repr(index) = elem }
+  } 
+
+  /** A class of `ArrayOps` for arrays containing `double`s. */
+  class ofDouble(override val repr: Array[Double]) extends ArrayOps[Double] with ArrayLike[Double, Array[Double]] {
+
+    override protected[this] def thisCollection: WrappedArray[Double] = new WrappedArray.ofDouble(repr)
+    override protected[this] def toCollection(repr: Array[Double]): WrappedArray[Double] = new WrappedArray.ofDouble(repr)
+    override protected[this] def newBuilder = new ArrayBuilder.ofDouble
+
+    def length: Int = repr.length
+    def apply(index: Int): Double = repr(index)
+    def update(index: Int, elem: Double) { repr(index) = elem }
+  } 
+
+  /** A class of `ArrayOps` for arrays containing `boolean`s. */
+  class ofBoolean(override val repr: Array[Boolean]) extends ArrayOps[Boolean] with ArrayLike[Boolean, Array[Boolean]] {
+
+    override protected[this] def thisCollection: WrappedArray[Boolean] = new WrappedArray.ofBoolean(repr)
+    override protected[this] def toCollection(repr: Array[Boolean]): WrappedArray[Boolean] = new WrappedArray.ofBoolean(repr)
+    override protected[this] def newBuilder = new ArrayBuilder.ofBoolean
+
+    def length: Int = repr.length
+    def apply(index: Int): Boolean = repr(index)
+    def update(index: Int, elem: Boolean) { repr(index) = elem }
+  } 
+
+  /** A class of `ArrayOps` for arrays of `Unit` types. */
+  class ofUnit(override val repr: Array[Unit]) extends ArrayOps[Unit] with ArrayLike[Unit, Array[Unit]] {
+
+    override protected[this] def thisCollection: WrappedArray[Unit] = new WrappedArray.ofUnit(repr)
+    override protected[this] def toCollection(repr: Array[Unit]): WrappedArray[Unit] = new WrappedArray.ofUnit(repr)
+    override protected[this] def newBuilder = new ArrayBuilder.ofUnit
+
+    def length: Int = repr.length
+    def apply(index: Int): Unit = repr(index)
+    def update(index: Int, elem: Unit) { repr(index) = elem }
+  } 
+}
diff --git a/src/library/scala/collection/mutable/ArraySeq.scala b/src/library/scala/collection/mutable/ArraySeq.scala
new file mode 100644
index 0000000..c2f2209
--- /dev/null
+++ b/src/library/scala/collection/mutable/ArraySeq.scala
@@ -0,0 +1,96 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+package mutable
+
+import generic._
+
+/** A class for polymorphic arrays of elements that's represented
+ *  internally by an array of objects. This means that elements of
+ *  primitive types are boxed.
+ *  
+ *  @author Martin Odersky
+ *  @version 2.8
+ *  @since   2.8
+ *  
+ *  @tparam A      type of the elements contained in this array sequence.
+ *  @param length  the length of the underlying array.
+ *  
+ *  @define Coll ArraySeq
+ *  @define coll array sequence
+ *  @define thatinfo the class of the returned collection. In the standard library configuration,
+ *    `That` is always `ArraySeq[B]` because an implicit of type `CanBuildFrom[ArraySeq, B, ArraySeq[B]]`
+ *    is defined in object `ArraySeq`.
+ *  @define $bfinfo an implicit value of class `CanBuildFrom` which determines the
+ *    result class `That` from the current representation type `Repr`
+ *    and the new element type `B`. This is usually the `canBuildFrom` value
+ *    defined in object `ArraySeq`.
+ *  @define orderDependent 
+ *  @define orderDependentFold
+ *  @define mayNotTerminateInf
+ *  @define willNotTerminateInf
+ */
+class ArraySeq[A](override val length: Int)
+extends IndexedSeq[A] 
+   with GenericTraversableTemplate[A, ArraySeq]
+   with IndexedSeqOptimized[A, ArraySeq[A]] { 
+
+  override def companion: GenericCompanion[ArraySeq] = ArraySeq
+
+  val array: Array[AnyRef] = new Array[AnyRef](length)
+
+  def apply(idx: Int): A = {
+    if (idx >= length) throw new IndexOutOfBoundsException(idx.toString)
+    array(idx).asInstanceOf[A]
+  }
+
+  def update(idx: Int, elem: A) { 
+    if (idx >= length) throw new IndexOutOfBoundsException(idx.toString)
+    array(idx) = elem.asInstanceOf[AnyRef]
+  }
+
+  override def foreach[U](f: A =>  U) {
+    var i = 0
+    while (i < length) {
+      f(array(i).asInstanceOf[A])
+      i += 1
+    }
+  }
+
+  /** Fills the given array `xs` with at most `len` elements of
+   *  this traversable starting at position `start`.
+   *  Copying will stop once either the end of the current traversable is reached or
+   *  `len` elements have been copied or the end of the array is reached.
+   *
+   *  @param  xs the array to fill.
+   *  @param  start starting index.
+   *  @param  len number of elements to copy
+   */
+   override def copyToArray[B >: A](xs: Array[B], start: Int, len: Int) {
+     val len1 = len min (xs.length - start) min length
+     Array.copy(array, 0, xs, start, len1)
+   }
+}
+
+/** $factoryInfo
+ *  @define coll array sequence
+ *  @define Coll ArraySeq
+ */
+object ArraySeq extends SeqFactory[ArraySeq] {
+  /** $genericCanBuildFromInfo */
+  implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, ArraySeq[A]] = new GenericCanBuildFrom[A]
+  def newBuilder[A]: Builder[A, ArraySeq[A]] = 
+    new ArrayBuffer[A] mapResult { buf => 
+      val result = new ArraySeq[A](buf.length)
+      buf.copyToArray(result.array.asInstanceOf[Array[Any]], 0)
+      result
+    }
+}
diff --git a/src/library/scala/collection/mutable/ArrayStack.scala b/src/library/scala/collection/mutable/ArrayStack.scala
index d373ced..af10023 100644
--- a/src/library/scala/collection/mutable/ArrayStack.scala
+++ b/src/library/scala/collection/mutable/ArrayStack.scala
@@ -1,168 +1,186 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: ArrayStack.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.collection.mutable;
+package scala.collection
+package mutable
 
-private object Utils{
-  def growArray(x : Array[AnyRef]) = {
-    val y = new Array[AnyRef](x.length * 2);
-    Array.copy(x, 0, y, 0, x.length);
-    y; 
+import generic._
+
+private object Utils {
+  def growArray(x: Array[AnyRef]) = {
+    val y = new Array[AnyRef](x.length * 2)
+    Array.copy(x, 0, y, 0, x.length)
+    y
   }
 
-  def clone(x : Array[AnyRef]) = {
-    val y = new Array[AnyRef](x.length);
-    Array.copy(x, 0, y, 0, x.length);
-    y; 
+  def clone(x: Array[AnyRef]) = {
+    val y = new Array[AnyRef](x.length)
+    Array.copy(x, 0, y, 0, x.length)
+    y
   }
 }
 
-/**
- * Simple stack class backed by an array. Should be significantly faster
- * than the standard mutable stack. 
+/** Simple stack class backed by an array. Should be significantly faster
+ *  than the standard mutable stack. 
  *
- * @author David MacIver
+ *  @author David MacIver
+ *  @since  2.7
+ *  
+ *  @tparam T    type of the elements contained in this array stack.
+ *  
+ *  @define Coll ArrayStack
+ *  @define coll array stack
+ *  @define orderDependent 
+ *  @define orderDependentFold
+ *  @define mayNotTerminateInf
+ *  @define willNotTerminateInf
  */
+ at cloneable @serializable @SerialVersionUID(8565219180626620510L)
 class ArrayStack[T] private(private var table : Array[AnyRef],
-                            private var index : Int) extends Collection[T]{
-  def this() = this(new Array[AnyRef](1), 0);   
+                            private var index : Int) extends scala.collection.Seq[T] with Cloneable[ArrayStack[T]] {
+  def this() = this(new Array[AnyRef](1), 0)
+
+  /** Retrieve n'th element from stack, where top of stack has index 0 */
+  def apply(n: Int): T =
+    table(index - 1 - n).asInstanceOf[T]
 
-  /** 
-   * Push an element onto the stack.
-   *
-   * @param x The element to push
+  /** The number of elements in the stack */
+  def length = index
+
+  /** Push an element onto the stack.
+   *  
+   *  @param x The element to push
    */ 
-  def push(x : T) = {
-    if (index == table.length) table = Utils.growArray(table);
-    table(index) = x.asInstanceOf[AnyRef];
-    index += 1;
+  def push(x: T) {
+    if (index == table.length) table = Utils.growArray(table)
+    table(index) = x.asInstanceOf[AnyRef]
+    index += 1
   }
 
-  /**
-   * Pop the top element off the stack.
+  /** Pop the top element off the stack.
+   *  
+   *  @return the element on top of the stack
    */
-  def pop = {
-    if (index == 0) error("Stack empty");
-    index -= 1;
-    val x = table(index).asInstanceOf[T];
-    table(index) = null;
-    x;
+  def pop: T = {
+    if (index == 0) error("Stack empty")
+    index -= 1
+    val x = table(index).asInstanceOf[T]
+    table(index) = null
+    x
   } 
 
-  /**
-   * View the top element of the stack.
-   */
-  def peek = table(index - 1).asInstanceOf[T]
+  /** View the top element of the stack. */
+  @deprecated("use top instead")
+  def peek = top
 
-  /**
-   * Duplicate the top element of the stack.
+  /** View the top element of the stack.
+   *  
+   *  Does not remove the element on the top. If the stack is empty,
+   *  an exception is thrown.
+   *  
+   *  @return the element on top of the stack.
    */
-  def dup = push(peek);
+  def top: T = table(index - 1).asInstanceOf[T]
 
-  /**
-   * Empties the stack.
+  /** Duplicate the top element of the stack.
+   * 
+   *  After calling this method, the stack will have an additional element at
+   *  the top equal to the element that was previously at the top.
+   *  If the stack is empty, an exception is thrown.
    */
-  def clear = {
-    index = 0;
-    table = new Array(1);
-  }
+  def dup = push(top)
 
-  /**
-   * Empties the stack, passing all elements on it in FIFO order to the 
-   * provided function.
-   *
-   * @param f The function to drain to.
-   */
-  def drain(f : T => Unit) = while(!isEmpty) f(pop);
+  /** Empties the stack. */
+  def clear {
+    index = 0
+    table = new Array(1)
+  }
 
-  /**
-   * Pushes all the provided elements onto the stack.
-   *
-   * @param x The source of elements to push
+  /** Empties the stack, passing all elements on it in LIFO order to the 
+   *  provided function.
+   *  
+   *  @param f The function to drain to.
    */
-  def ++=(x : Iterable[T]) = x.foreach(this +=(_))
-
+  def drain(f: T => Unit) = while (!isEmpty) f(pop)
 
-  /**
-   * Pushes all the provided elements onto the stack.
-   *
-   * @param x The source of elements to push
+  /** Pushes all the provided elements in the traversable object onto the stack.
+   *  
+   *  @param x  The source of elements to push.
+   *  @return   A reference to this stack.
    */
-  def ++=(x : Iterator[T]) = x.foreach(this +=(_))
+  def ++=(xs: TraversableOnce[T]): this.type = { xs foreach += ; this }
 
-  /**
-   *  Alias for push.
-   * 
-   *  @param x The element to push
+  /** Does the same as `push`, but returns the updated stack.
+   *  
+   *  @param x  The element to push.
+   *  @return   A reference to this stack.
    */
-  def +=(x : T) = push(x);
- 
-
-
-  /**
-   * Pop the top two elements off the stack, apply f to them and push the result
-   * back on to the stack.
-   * 
-   * @param f The combining function
+  def +=(x: T): this.type = { push(x); this }
+
+  /** Pop the top two elements off the stack, apply `f` to them and push the result
+   *  back on to the stack.
+   *  
+   *  This function will throw an exception if stack contains fewer than 2 elements.
+   *  
+   *  @param f   The function to apply to the top two elements.
    */
-  def combine(f : (T, T) => T) = push(f(pop, pop));
+  def combine(f: (T, T) => T): Unit = push(f(pop, pop))
   
-  /**
-   * Repeatedly combine the top elements of the stack until the stack contains only
-   * one element.
+  /** Repeatedly combine the top elements of the stack until the stack contains only
+   *  one element.
+   *  
+   *  @param f   The function to apply repeatedly to topmost elements.
    */
-  def reduceWith(f : (T, T) => T) = while(size > 1) combine(f)     
+  def reduceWith(f: (T, T) => T): Unit = while(size > 1) combine(f)
 
-  def size = index;
+  override def size = index
 
-  /**
-   * Evaluates the expression, preserving the contents of the stack so that 
-   * any changes the evaluation makes to the stack contents will be undone after
-   * it completes.
-   *
-   * @param action The action to run.
+  /** Evaluates the expression, preserving the contents of the stack so that 
+   *  any changes the evaluation makes to the stack contents will be undone after
+   *  it completes.
+   *  
+   *  @param action The action to run.
    */
-  def preserving[T](action : => T) = {
-    val oldIndex = index;
-    val oldTable = Utils.clone(table);
+  def preserving[T](action: => T) = {
+    val oldIndex = index
+    val oldTable = Utils.clone(table)
 
-    try{
-      action;
+    try {
+      action
     } finally {
-      index = oldIndex;
-      table = oldTable;
+      index = oldIndex
+      table = oldTable
     }
   }
 
-  override def isEmpty = index == 0;
+  override def isEmpty: Boolean = index == 0
 
-  /**
-   * Iterates over the stack in fifo order.
+  /** Creates and iterator over the stack in LIFO order.
+   *  @return an iterator over the elements of the stack.
    */
-  def elements = new Iterator[T]{
-    var currentIndex = index;
-    def hasNext = currentIndex > 0;
+  def iterator: Iterator[T] = new Iterator[T] {
+    var currentIndex = index
+    def hasNext = currentIndex > 0
     def next = {
-      currentIndex -= 1;
-      table(currentIndex).asInstanceOf[T];
+      currentIndex -= 1
+      table(currentIndex).asInstanceOf[T]
     }
   }
 
-  override def foreach(f : T => Unit){
-    var currentIndex = index;
-    while(currentIndex > 0){
-      currentIndex -= 1;
-      f(table(currentIndex).asInstanceOf[T]);
+  override def foreach[U](f: T =>  U) {
+    var currentIndex = index
+    while (currentIndex > 0) {
+      currentIndex -= 1
+      f(table(currentIndex).asInstanceOf[T])
     }
   }
 
-  override def clone = new ArrayStack[T](Utils.clone(table), index);
+  override def clone = new ArrayStack[T](Utils.clone(table), index)
 }
diff --git a/src/library/scala/collection/mutable/BitSet.scala b/src/library/scala/collection/mutable/BitSet.scala
index 106b5c2..cddb4c6 100644
--- a/src/library/scala/collection/mutable/BitSet.scala
+++ b/src/library/scala/collection/mutable/BitSet.scala
@@ -1,100 +1,122 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: BitSet.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.collection.mutable
+package scala.collection
+package mutable
 
+import generic._
+import BitSetLike.{LogWL, updateArray}
 
-/**
- * The class <code>BitSet</code> implements mutable, resizable Bit sets
+/** A class for mutable bitsets.
+ *  
+ *  $bitsetinfo
  *
- * @author  Burak Emir, Nikolay Mihaylov
- * @version 1.1
- *
- * @param initSize: initial size in bits
+ *  @define Coll BitSet
+ *  @define coll bitset
+ *  @define thatinfo the class of the returned collection. In the standard library configuration,
+ *    `That` is always `BitSet[B]` because an implicit of type `CanBuildFrom[BitSet, B, BitSet]`
+ *    is defined in object `BitSet`.
+ *  @define $bfinfo an implicit value of class `CanBuildFrom` which determines the
+ *    result class `That` from the current representation type `Repr`
+ *    and the new element type `B`. This is usually the `canBuildFrom` value
+ *    defined in object `BitSet`.
+ *  @define orderDependent 
+ *  @define orderDependentFold
+ *  @define mayNotTerminateInf
+ *  @define willNotTerminateInf
  */
+ at serializable @SerialVersionUID(8483111450368547763L)
+class BitSet(protected var elems: Array[Long]) extends Set[Int] 
+                                                  with scala.collection.BitSet 
+                                                  with BitSetLike[BitSet] 
+                                                  with SetLike[Int, BitSet] {
 
- at serializable
-class BitSet(initSize: Int) extends collection.BitSet with Set[Int] {
+  override def empty = BitSet.empty
 
-  import compat.Platform.{arraycopy, arrayclear}
+  /** Creates the bitset of a certain initial size.
+   *  
+   *  @param initSize    initial size of the bitset.
+   */
+  def this(initSize: Int) = this(new Array[Long]((initSize + 63) >> 6 max 1))
 
-  /** default constructor, initial size of 512 bits. */
   def this() = this(0)
 
-  /** Ensures that this bitset can store at least <code>n</code> bits.
-   *
-   *  @param n ...
-   */
-  def ensureCapacity(n: Int): Unit =
-    if (capacity < n) {
-      if (nbits(arr.length) < n) {
-        val newn = memsize(n)
-        var newsize = if (arr.length == 0) newn else arr.length * 2
-        while (newn > newsize)
-          newsize = newsize * 2;
-        val newarr = new Array[Int](newsize)
-        arraycopy(arr, 0, newarr, 0, arr.length)
-        arr = newarr
-      }
-      capacity = n
-    }
-
-  /**
-   * Sets <code>i-th</code> bit to true.
-   * No restriction on <code>i</code>
-   */
-  def +=(i: Int): Unit = {
-    ensureCapacity(i+1)
-    val oldInt = arr(offset(i))
-    val newInt = oldInt | mask(i)
-    if (oldInt != newInt) {
-      arr(offset(i)) = newInt
-      size = size + 1
+  protected def nwords = elems.length
+  protected def word(idx: Int): Long = 
+    if (idx < nwords) elems(idx) else 0L
+
+  private def updateWord(idx: Int, w: Long) {
+    if (idx >= nwords) {
+      var newlen = nwords
+      while (idx >= newlen) newlen = newlen * 2
+      val elems1 = new Array[Long](newlen)
+      Array.copy(elems, 0, elems1, 0, nwords)
+      elems = elems1
     }
+    elems(idx) = w
   }
 
-  /** Clears the <code>i</code>-th bit.
-   *
-   *  @param i the <code>i</code>-th element of the bit set.
-   */
-  def -=(i: Int): Unit = {
-    if (i >= capacity) return;
-    val oldInt = arr(offset(i))
-    val newInt = oldInt & ~mask(i)
-    if (oldInt != newInt) {
-      arr(offset(i)) = newInt
-      size = size - 1
+  protected def fromArray(words: Array[Long]): BitSet = new BitSet(words)
+
+  override def add(elem: Int): Boolean = {
+    require(elem >= 0)
+    if (contains(elem)) false 
+    else {
+      val idx = elem >> LogWL
+      updateWord(idx, word(idx) | (1L << elem))
+      true
     }
   }
 
-  /** Clears all bits of the set.
-   */
-  override def clear(): Unit = {
-    arrayclear(arr)
-    size = 0
+  override def remove(elem: Int): Boolean = {
+    require(elem >= 0)
+    if (contains(elem)) {
+      val idx = elem >> LogWL
+      updateWord(idx, word(idx) & ~(1L << elem))
+      true
+    } else false
   }
 
-  def toImmutable: collection.immutable.BitSet =
-    new immutable.BitSet(size, capacity, arr, true)
+  def += (elem: Int): this.type = { add(elem); this }
+  def -= (elem: Int): this.type = { remove(elem); this }
 
-  override def clone(): BitSet = new BitSet(capacity) {
-    arraycopy(BitSet.this.arr, 0, arr, 0, arr.length)
-    size = BitSet.this.size
-    capacity = BitSet.this.capacity
+  override def clear() {
+    elems = new Array[Long](elems.length)
   }
 
-  var size: Int = 0
-
-  var capacity: Int = initSize
+  /** Wraps this bitset as an immutable bitset backed by the array of bits
+   *  of this bitset.
+   *  
+   *  @note Subsequent changes in this bitset will be reflected in the returned immutable bitset.
+   *  
+   *  @return an immutable set containing all the elements of this set.
+   */
+  def toImmutable = immutable.BitSet.fromArray(elems)
 
-  protected var arr: Array[Int] = new Array[Int](memsize(initSize))
+  override def clone(): BitSet = {
+    val elems1 = new Array[Long](elems.length)
+    Array.copy(elems, 0, elems1, 0, elems.length)
+    new BitSet(elems1)
+  }
+}
 
+/** $factoryInfo
+ *  @define coll bitset
+ *  @define Coll BitSet
+ */
+object BitSet extends BitSetFactory[BitSet] {
+  def empty: BitSet = new BitSet
+  
+  /** A growing builder for mutable Sets. */
+  def newBuilder: Builder[Int, BitSet] = new GrowingBuilder[Int, BitSet](empty)
+
+  /** $bitsetCanBuildFrom */
+  implicit def canBuildFrom: CanBuildFrom[BitSet, Int, BitSet] = bitsetCanBuildFrom
 }
diff --git a/src/library/scala/collection/mutable/Buffer.scala b/src/library/scala/collection/mutable/Buffer.scala
index 5a1d325..c72765f 100644
--- a/src/library/scala/collection/mutable/Buffer.scala
+++ b/src/library/scala/collection/mutable/Buffer.scala
@@ -1,286 +1,46 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Buffer.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.collection.mutable
+package scala.collection
+package mutable
 
-
-import Predef._
+import generic._
 
 /** Buffers are used to create sequences of elements incrementally by
  *  appending, prepending, or inserting new elements. It is also
  *  possible to access and modify elements in a random access fashion
  *  via the index of the element in the current sequence.
- *
- *  @author  Matthias Zenger
- *  @version 1.1, 02/03/2004
+ *  
+ *  @author Matthias Zenger
+ *  @author Martin Odersky
+ *  @version 2.8
+ *  @since   1
+ *  
+ *  @tparam A    type of the elements contained in this buffer.
+ *  
+ *  @define Coll Buffer
+ *  @define coll buffer
  */
 @cloneable
-trait Buffer[A] extends AnyRef
-      with Seq[A]
-      with Scriptable[Message[(Location, A)]]
-      with CloneableCollection
-{
-
-  /** Append a single element to this buffer.
-   *
-   *  @param elem  the element to append.
-   */
-  def +=(elem: A): Unit
-
-  /** Append a two or more elements to this buffer.
-   *
-   *  enable this for 2.8.0!
-   *
-   *  @param elem1 the first element to append.
-   *  @param elem2 the second element to append.
-   *  @param elems the remaining elements to append.
-  def +=(elem1: A, elem2: A, elems: A*): Unit = {
-    this += elem1 
-    this += elem2
-    this ++= elems
-  }
-   */
-
-  /** Append a single element to this buffer and return
-   *  the identity of the buffer.
-   *
-   *  @param elem  the element to append.
-   */
-  def +(elem: A): Buffer[A] = { this += elem; this }
-
-  /** Append two or more elements to this buffer and return
-   *  the identity of the buffer.
-   *
-   *  enable this for 2.8.0!
-   *
-   *  @param elem1 the first element to append.
-   *  @param elem2 the second element to append.
-   *  @param elems the remaining elements to append.
-  def +(elem1: A, elem2: A, elems: A*): Buffer[A] = 
-    this + elem1 + elem2 ++ elems
-   */
-
-  /** Prepend a single element to this buffer and return
-   *  the identity of the buffer.
-   *
-   *  @param elem  the element to append.
-   */
-  def +:(elem: A): Buffer[A]
-
-  /** Appends a number of elements provided by an iterator
-   *
-   *  @param iter  the iterator.
-   */
-  def ++=(iter: Iterator[A]) { iter foreach += }
-
-  /** Appends a number of elements provided by an iterable object
-   *  via its <code>elements</code> method.
-   *
-   *  @param iter  the iterable object.
-   */
-  def ++=(iter: Iterable[A]) { ++=(iter.elements) }
-
-  /** Appends a number of elements in an array
-   *
-   *  @param src    the array
-   *  @param start  the first element to append
-   *  @param len    the number of elements to append           
-   */
-  def ++=(src: Array[A], start: Int, len: Int) {
-    var i = start
-    val end = i + len
-    while (i < end) {
-      this += src(i)
-      i += 1
-    }
-  }
-  /** return a read only alias of this buffer 
-   */
-  def readOnly : Seq[A]
-
-  /** Appends a number of elements provided by an iterable object
-   *  via its <code>elements</code> method. The identity of the
-   *  buffer is returned.
-   *
-   *  @param iter     the iterable object.
-   *  @return       the updated buffer.
-   */
-  def ++(iter: Iterable[A]): Buffer[A] = { this ++= iter; this }
-
-  override def ++[B >: A](that : Iterable[B]) : Seq[B] = {
-    val buf = new ArrayBuffer[B]
-    this copyToBuffer buf
-    that copyToBuffer buf
-    buf
-  }
-   
-  /** Appends a number of elements provided by an iterator
-   *  via its <code>elements</code> method. The identity of the
-   *  buffer is returned.
-   *
-   *  @param iter   the iterator
-   *  @return       the updated buffer.
-   */
-  def ++(iter: Iterator[A]): Buffer[A] = { this ++= iter; this }
-
-  /** Prepends a number of elements provided by an iterable object
-   *  via its <code>elements</code> method. The identity of the
-   *  buffer is returned.
-   *
-   *  @param iter  the iterable object.
-   */
-  def ++:(iter: Iterable[A]): Buffer[A] = {
-    iter.elements.toList.reverse.foreach(e => e +: this)
-    this
-  }
-
-  /** Removes a single element from this buffer, at its first occurrence.
-   *  If the list does not contain that element, it is unchanged
-   *
-   *  @param x  the element to remove.
-   */
-  def -= (x: A) {
-    val i = indexOf(x)
-    if(i != -1) remove(i)
-  }
-
-  /** Appends a sequence of elements to this buffer.
-   *
-   *  @param elems  the elements to append.
-   */
-  def append(elems: A*) { this ++= elems }
-
-  /** Appends a number of elements provided by an iterable object
-   *  via its <code>elements</code> method.
-   *
-   *  @param iter  the iterable object.
-   */
-  def appendAll(iter: Iterable[A]) { this ++= iter }
-
-  /** Prepend an element to this list.
-   *
-   *  @param elem  the element to prepend.
-   */
-  def prepend(elems: A*) { elems ++: this }
-
-  /** Prepends a number of elements provided by an iterable object
-   *  via its <code>elements</code> method. The identity of the
-   *  buffer is returned.
-   *
-   *  @param iter  the iterable object.
-   */
-  def prependAll(iter: Iterable[A]) { iter ++: this }
-
-  /** Inserts new elements at the index <code>n</code>. Opposed to method
-   *  <code>update</code>, this method will not replace an element with a
-   *  one. Instead, it will insert the new elements at index <code>n</code>.
-   *
-   *  @param n      the index where a new element will be inserted.
-   *  @param elems  the new elements to insert.
-   */
-  def insert(n: Int, elems: A*) { insertAll(n, elems) }
-
-  /** Inserts new elements at the index <code>n</code>. Opposed to method
-   *  <code>update</code>, this method will not replace an element with a
-   *  one. Instead, it will insert a new element at index <code>n</code>.
-   *
-   *  @param n     the index where a new element will be inserted.
-   *  @param iter    the iterable object providing all elements to insert.
-   */
-  def insertAll(n: Int, iter: Iterable[A]): Unit
-
-  /** Replace element at index <code>n</code> with the new element
-   *  <code>newelem</code>.
-   *
-   *  @param n       the index of the element to replace.
-   *  @param newelem the new element.
-   */
-  def update(n: Int, newelem: A): Unit
-
-  /** Removes the element on a given index position.
-   *
-   *  @param n  the index which refers to the element to delete.
-   */
-  def remove(n: Int): A
-
-  /** Removes the first <code>n</code> elements.
-   *
-   *  @param n  the number of elements to remove from the beginning
-   *            of this buffer.
-   */
-  def trimStart(n: Int) {
-    var i = n
-    while (i > 0) { remove(0); i -= 1 }
-  }
-
-  /** Removes the last <code>n</code> elements.
-   *
-   *  @param n  the number of elements to remove from the end
-   *            of this buffer.
-   */
-  def trimEnd(n: Int) {
-    var i = n
-    while (i > 0) { remove(length - 1); i -= 1 }
-  }
-
-  /** Clears the buffer contents.
-   */
-  def clear(): Unit
-
-  /** Send a message to this scriptable object.
-   *
-   *  @param cmd  the message to send.
-   */
-  def <<(cmd: Message[(Location, A)]) {
-    cmd match {
-      case Include((l, elem)) => l match {
-        case Start => prepend(elem)
-        case End => append(elem)
-        case Index(n) => insert(n, elem)
-        case _ => throw new UnsupportedOperationException("message " + cmd + " not understood")
-      }
-      case Update((l, elem)) => l match {
-        case Start => update(0, elem)
-        case End => update(length - 1, elem)
-        case Index(n) => update(n, elem)
-        case _ => throw new UnsupportedOperationException("message " + cmd + " not understood")
-      }
-      case Remove((l, _)) => l match {
-        case Start => remove(0)
-        case End => remove(length - 1)
-        case Index(n) => remove(n)
-        case _ => throw new UnsupportedOperationException("message " + cmd + " not understood")
-      }
-      case Reset() => clear
-      case s: Script[_] => s.elements foreach <<
-      case _ => throw new UnsupportedOperationException("message " + cmd + " not understood")
-    }
-  }
-
-  /** Return a clone of this buffer.
-   *
-   *  @return a buffer with the same elements.
-   */
-  override def clone(): Buffer[A] = super.clone().asInstanceOf[Buffer[A]]
-
-  /** The hashCode method always yields an error, since it is not
-   *  safe to use buffers as keys in hash tables.
-   *
-   *  @return never.
-   */
-  override def hashCode(): Int =
-    throw new UnsupportedOperationException("unsuitable as hash key")
+trait Buffer[A] extends Seq[A] 
+                   with GenericTraversableTemplate[A, Buffer]
+                   with BufferLike[A, Buffer[A]] {
+  override def companion: GenericCompanion[Buffer] = Buffer
+}
 
-  /** Defines the prefix of the string representation.
-   */
-  override protected def stringPrefix: String = "Buffer"
-    
+/** $factoryInfo
+ *  @define coll buffer
+ *  @define Coll Buffer
+ */
+object Buffer extends SeqFactory[Buffer] {
+  implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, Buffer[A]] = new GenericCanBuildFrom[A]
+  def newBuilder[A]: Builder[A, Buffer[A]] = new ArrayBuffer
 }
+
diff --git a/src/library/scala/collection/mutable/BufferLike.scala b/src/library/scala/collection/mutable/BufferLike.scala
new file mode 100644
index 0000000..da92296
--- /dev/null
+++ b/src/library/scala/collection/mutable/BufferLike.scala
@@ -0,0 +1,343 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+package mutable
+
+import generic._
+import script._
+import annotation.migration
+
+/** A template trait for buffers of type `Buffer[A]`.
+ * 
+ *  Buffers are used to create sequences of elements incrementally by
+ *  appending, prepending, or inserting new elements. It is also
+ *  possible to access and modify elements in a random access fashion
+ *  via the index of the element in the current sequence.
+ * 
+ *  @tparam A    the type of the elements of the buffer
+ *  @tparam This the type of the buffer itself.
+ *
+ *  $buffernote
+ * 
+ *  @author  Martin Odersky
+ *  @author  Matthias Zenger
+ *  @version 2.8
+ *  @since   2.8
+ *  @define buffernote @note
+ *    This trait provides most of the operations of a `Buffer` independently of its representation.
+ *    It is typically inherited by concrete implementations of buffers.
+ *
+ *    To implement a concrete buffer, you need to provide implementations of the
+ *    following methods:
+ *    {{{
+ *       def apply(idx: Int): A
+ *       def update(idx: Int, elem: A)
+ *       def length: Int
+ *       def clear()
+ *       def +=(elem: A): this.type
+ *       def +=:(elem: A): this.type
+ *       def insertAll(n: Int, iter: Traversable[A])
+ *       def remove(n: Int): A
+ *    }}}
+ *  @define coll buffer
+ *  @define Coll Buffer
+ *  @define add  append
+ *  @define Add  Append
+ *  @define willNotTerminateInf
+ *  @define mayNotTerminateInf
+ *  @define compatMutate
+ *  Note that for backward compatibility reasons, this method
+ *  mutates the collection in place, unlike similar but
+ *  undeprecated methods throughout the collections hierarchy.
+ */
+ at cloneable
+trait BufferLike[A, +This <: BufferLike[A, This] with Buffer[A]] 
+                extends Growable[A]
+                   with Shrinkable[A]
+                   with Scriptable[A]
+                   with Subtractable[A, This]
+                   with Cloneable[This]
+                   with SeqLike[A, This]
+{ self : This =>
+  
+  // Note this does not extend Addable because `+` is being phased out of
+  // all Seq-derived classes.
+
+  import scala.collection.{Iterable, Traversable}
+
+  // Abstract methods from IndexedSeq:
+
+  def apply(n: Int): A
+  def update(n: Int, newelem: A)
+  def length: Int
+
+  // Abstract methods from Growable:
+
+  def +=(elem: A): this.type
+  def clear()
+
+  // Abstract methods new in this class:
+
+  /** Prepends a single element to this buffer.
+   *  @param elem  the element to prepend.
+   *  @return      the buffer itself.
+   */
+  def +=:(elem: A): this.type
+
+  /** Inserts new elements at a given index into this buffer.
+   *
+   *  @param n      the index where new elements are inserted.
+   *  @param elems  the traversable collection containing the elements to insert.
+   *  @throws   IndexOutofBoundsException if the index `n` is not in the valid range
+   *            `0 <= n <= length`.
+   */
+  def insertAll(n: Int, elems: Traversable[A])
+
+   /** Removes the element at a given index from this buffer.
+    *
+    *  @param n  the index which refers to the element to delete.
+    *  @return   the previous element at index `n`
+    *   @throws   IndexOutofBoundsException if the if the index `n` is not in the valid range
+    *            `0 <= n < length`.
+    */
+  def remove(n: Int): A
+
+  /** Removes a number of elements from a given index position.
+   *
+   *  @param n  the index which refers to the first element to remove.
+   *  @param count  the number of elements to remove.
+   *  @throws   IndexOutofBoundsException if the index `n` is not in the valid range
+   *            `0 <= n <= length - count`.
+   *  @throws   IllegalArgumentException if `count < 0`.
+   */
+  def remove(n: Int, count: Int) {
+    for (i <- 0 until count) remove(n)
+  }
+
+  /** Removes a single element from this buffer, at its first occurrence.
+   *  If the buffer does not contain that element, it is unchanged.
+   *
+   *  @param x  the element to remove.
+   *  @return   the buffer itself
+   */
+  def -= (x: A): this.type = {
+    val i = indexOf(x)
+    if (i != -1) remove(i)
+    this
+  }
+  
+  /** Prepends elements to this buffer.
+   *
+   *  @param xs  the TraversableOnce containing the elements to prepend.
+   *  @return the buffer itself.
+   */
+  def ++=:(xs: TraversableOnce[A]): this.type = { insertAll(0, xs.toTraversable); this }
+
+  /** Appends the given elements to this buffer.
+   *
+   *  @param elems  the elements to append.
+   */
+  def append(elems: A*) { appendAll(elems) }
+
+  /** Appends the elements contained in a traversable object to this buffer.
+   *  @param xs  the traversable object containing the elements to append.
+   */
+  def appendAll(xs: TraversableOnce[A]) { this ++= xs }
+
+  /** Prepends given elements to this buffer.
+   *  @param elems  the elements to prepend.
+   */
+  def prepend(elems: A*) { prependAll(elems) } 
+
+  /** Prepends the elements contained in a traversable object to this buffer.
+   *  @param elems  the collection containing the elements to prepend.
+   */
+  def prependAll(xs: TraversableOnce[A]) { xs ++=: this }
+
+  /** Inserts new elements at a given index into this buffer.
+   *
+   *  @param n      the index where new elements are inserted.
+   *  @param elems  the traversable collection containing the elements to insert.
+   *  @throws   IndexOutofBoundsException if the index `n` is not in the valid range
+   *            `0 <= n <= length`.
+   */
+  def insert(n: Int, elems: A*) { insertAll(n, elems) } 
+
+  /** Removes the first ''n'' elements of this buffer.
+   *
+   *  @param n  the number of elements to remove from the beginning
+   *            of this buffer.
+   */
+  def trimStart(n: Int) { remove(0, n) }
+
+  /** Removes the last ''n'' elements of this buffer.
+   *
+   *  @param n  the number of elements to remove from the end
+   *            of this buffer.
+   */
+  def trimEnd(n: Int) { remove(length - n max 0, n) }
+
+  /** Send a message to this scriptable object.
+   *
+   *  @param cmd  the message to send.
+   */
+  def <<(cmd: Message[A]): Unit = cmd match {
+    case Include(Start, x)      => prepend(x)
+    case Include(End, x)        => append(x)
+    case Include(Index(n), x)   => insert(n, x)
+    case Include(NoLo, x)       => this += x
+    
+    case Update(Start, x)       => update(0, x)
+    case Update(End, x)         => update(length - 1, x)
+    case Update(Index(n), x)    => update(n, x)
+    
+    case Remove(Start, x)       => if (this(0) == x) remove(0)
+    case Remove(End, x)         => if (this(length - 1) == x) remove(length - 1)
+    case Remove(Index(n), x)    => if (this(n) == x) remove(n)
+    case Remove(NoLo, x)        => this -= x
+    
+    case Reset()                => clear
+    case s: Script[_]           => s.iterator foreach <<
+    case _                      => throw new UnsupportedOperationException("message " + cmd + " not understood")
+  }
+
+  /** Defines the prefix of this object's `toString` representation.
+   *  @return  a string representation which starts the result of `toString` applied to this set.
+   *           Unless overridden this is simply `"Buffer"`.
+   */
+  override def stringPrefix: String = "Buffer"
+    
+  /** Provide a read-only view of this buffer as a sequence
+   *  @return  A sequence which refers to this buffer for all its operations.
+   */
+  def readOnly: scala.collection.Seq[A] = toSeq
+
+  /** Adds a number of elements in an array
+   *
+   *  @param src    the array
+   *  @param start  the first element to append
+   *  @param len    the number of elements to append
+   */
+  @deprecated("replace by: `buf ++= src.view(start, end)`")
+  def ++=(src: Array[A], start: Int, len: Int) {
+    var i = start
+    val end = i + len
+    while (i < end) {
+      this += src(i)
+      i += 1
+    }
+  }
+
+
+  /** This method prepends elements to the buffer and
+   *  returns the same buffer.
+   *
+   *  $compatMutate
+   *  You are strongly recommended to use `++=:` instead.
+   *
+   *  @param xs   elements to prepend
+   *  @return     this buffer
+   */
+  @deprecated("use ++=: instead")
+  final def ++:(xs: Traversable[A]): This = ++=:(xs)
+ 
+  /** This method prepends elements to the buffer and
+   *  returns the same buffer.
+   *
+   *  $compatMutate
+   *  You are strongly recommended to use `+=:` instead.
+   *
+   *  @param xs   elements to prepend
+   *  @return     this buffer
+   */ 
+  @deprecated("use `+=:' instead") 
+  final def +:(elem: A): This = +=:(elem)
+
+  /** Adds a single element to this collection and returns 
+   *  the collection itself.
+   *
+   *  $compatMutate
+   *  You are strongly recommended to use '+=' instead.
+   *
+   *  @param elem  the element to add.
+   */
+  @deprecated("Use += instead if you intend to add by side effect to an existing collection.\n"+
+              "Use `clone() +=' if you intend to create a new collection.")
+  def + (elem: A): This = { +=(elem); repr }
+
+  /** Adds two or more elements to this collection and returns
+   *  the collection itself.
+   *  
+   *  $compatMutate
+   *  You are strongly recommended to use '++=' instead.
+   *
+   *  @param elem1 the first element to add.
+   *  @param elem2 the second element to add.
+   *  @param elems the remaining elements to add.
+   */
+  @deprecated("Use ++= instead if you intend to add by side effect to an existing collection.\n"+
+              "Use `clone() ++=' if you intend to create a new collection.")
+  def + (elem1: A, elem2: A, elems: A*): This = {
+    this += elem1 += elem2 ++= elems
+    repr
+  } 
+
+  /** Creates a new collection containing both the elements of this collection and the provided
+   *  traversable object.
+   *
+   *  @param xs     the traversable object.
+   *  @return       a new collection consisting of all the elements of this collection and `xs`.
+   */
+  @migration(2, 8,
+    "As of 2.8, ++ always creates a new collection, even on Buffers.\n"+
+    "Use ++= instead if you intend to add by side effect to an existing collection.\n"
+  )
+  def ++(xs: TraversableOnce[A]): This = clone() ++= xs
+
+  /** Creates a new collection with all the elements of this collection except `elem`.
+   *
+   *  @param elem  the element to remove.
+   *  @return      a new collection consisting of all the elements of this collection except `elem`.
+   */
+  @migration(2, 8,
+    "As of 2.8, - always creates a new collection, even on Buffers.\n"+
+    "Use -= instead if you intend to remove by side effect from an existing collection.\n"
+  )
+  override def -(elem: A): This = clone() -= elem
+
+  /** Creates a new collection with all the elements of this collection except the two
+   *  or more specified elements.
+   *
+   *  @param elem1 the first element to remove.
+   *  @param elem2 the second element to remove.
+   *  @param elems the remaining elements to remove.
+   *  @return      a new collection consisting of all the elements of this collection except
+   *               `elem1`, `elem2` and those in `elems`.
+   */
+  @migration(2, 8,
+    "As of 2.8, - always creates a new collection, even on Buffers.\n"+
+    "Use -= instead if you intend to remove by side effect from an existing collection.\n"
+  )
+  override def -(elem1: A, elem2: A, elems: A*): This = clone() -= elem1 -= elem2 --= elems
+
+  /** Creates a new collection with all the elements of this collection except those
+   *  provided by the specified traversable object.
+   *
+   *  @param xs       the traversable object.
+   *  @return         a new collection with all the elements of this collection except
+   *                  those in `xs`
+   */
+  @migration(2, 8,
+    "As of 2.8, -- always creates a new collection, even on Buffers.\n"+
+    "Use --= instead if you intend to remove by side effect from an existing collection.\n"
+  )
+  override def --(xs: TraversableOnce[A]): This = clone() --= xs
+}
diff --git a/src/library/scala/collection/mutable/BufferProxy.scala b/src/library/scala/collection/mutable/BufferProxy.scala
index 3bc69fa..9138381 100644
--- a/src/library/scala/collection/mutable/BufferProxy.scala
+++ b/src/library/scala/collection/mutable/BufferProxy.scala
@@ -1,24 +1,32 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: BufferProxy.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.collection.mutable
+package scala.collection
+package mutable
 
+import generic._
+import script._
 
 /** This is a simple proxy class for <a href="Buffer.html"
- *  target="contentFrame"><code>scala.collection.mutable.Buffer</code></a>.
+ *  target="contentFrame">`scala.collection.mutable.Buffer`</a>.
  *  It is most useful for assembling customized set abstractions
  *  dynamically using object composition and forwarding.
  *
  *  @author  Matthias Zenger
  *  @version 1.0, 16/04/2004
+ *  @since   1
+ *  
+ *  @tparam A     type of the elements the buffer proxy contains.
+ *  
+ *  @define Coll BufferProxy
+ *  @define coll buffer proxy
  */
 trait BufferProxy[A] extends Buffer[A] with Proxy {
 
@@ -26,7 +34,7 @@ trait BufferProxy[A] extends Buffer[A] with Proxy {
 
   def length: Int = self.length
 
-  override def elements: Iterator[A] = self.elements
+  override def iterator: Iterator[A] = self.iterator
 
   def apply(n: Int): A = self.apply(n)
 
@@ -36,99 +44,101 @@ trait BufferProxy[A] extends Buffer[A] with Proxy {
    *  @param elem  the element to append.
    *  @return      the updated buffer.
    */
+  @deprecated("Use += instead if you intend to add by side effect to an existing collection.\n"+
+              "Use `clone() ++=' if you intend to create a new collection.")
   override def +(elem: A): Buffer[A] = self.+(elem)
 
   /** Append a single element to this buffer.
    *
    *  @param elem  the element to append.
    */
-  def +=(elem: A): Unit = self.+=(elem)
+  def +=(elem: A): this.type = { self.+=(elem); this }
 
   override def readOnly = self.readOnly
   
-  /** Appends a number of elements provided by an iterable object
-   *  via its <code>elements</code> method. The identity of the
+  /** Appends a number of elements provided by a traversable object
+   *  via its <code>foreach</code> method. The identity of the
    *  buffer is returned.
    *
-   *  @param iter  the iterable object.
+   *  @param iter  the traversable object.
    *  @return      the updated buffer.
    */
-  override def ++(iter: Iterable[A]): Buffer[A] = self.++(iter)
+  @deprecated("Use ++= instead if you intend to add by side effect to an existing collection.\n"+
+              "Use `clone() ++=` if you intend to create a new collection.")
+  override def ++(xs: TraversableOnce[A]): Buffer[A] = self.++(xs)
 
-  /** Appends a number of elements provided by an iterable object
-   *  via its <code>elements</code> method.
+  /** Appends a number of elements provided by a traversable object.
    *
-   *  @param iter  the iterable object.
+   *  @param xs   the traversable object.
+   *  @return     a reference to this $coll.
    */
-  override def ++=(iter: Iterable[A]): Unit = self.++=(iter)
+  override def ++=(xs: TraversableOnce[A]): this.type = { self.++=(xs); this }
 
   /** Appends a sequence of elements to this buffer.
    *
    *  @param elems  the elements to append.
    */
-  override def append(elems: A*): Unit = self.++=(elems)
+  override def append(elems: A*) { self.++=(elems) }
 
-  /** Appends a number of elements provided by an iterable object
-   *  via its <code>elements</code> method.
+  /** Appends a number of elements provided by a traversable object.
    *
-   *  @param iter  the iterable object.
+   *  @param xs   the traversable object.
    */
-  override def appendAll(iter: Iterable[A]): Unit = self.appendAll(iter)
+  override def appendAll(xs: TraversableOnce[A]) { self.appendAll(xs) }
 
   /** Prepend a single element to this buffer and return
    *  the identity of the buffer.
    *
    *  @param elem  the element to append.
+   *  @return      a reference to this $coll.
    */
-  def +:(elem: A): Buffer[A] = self.+:(elem)
+  def +=:(elem: A): this.type = { self.+=:(elem); this }
 
-  /** Prepends a number of elements provided by an iterable object
-   *  via its <code>elements</code> method. The identity of the
-   *  buffer is returned.
-   *
-   *  @param iter  the iterable object.
-   */
-  override def ++:(iter: Iterable[A]): Buffer[A] = self.++:(iter)
+  override def ++=:(xs: TraversableOnce[A]): this.type = { self.++=:(xs); this }
 
   /** Prepend an element to this list.
    *
    *  @param elem  the element to prepend.
    */
-  override def prepend(elems: A*): Unit = self.prependAll(elems)
+  override def prepend(elems: A*) { self.prependAll(elems) }
 
-  /** Prepends a number of elements provided by an iterable object
-   *  via its <code>elements</code> method. The identity of the
-   *  buffer is returned.
+  /** Prepends a number of elements provided by a traversable object.
+   *  The identity of the buffer is returned.
    *
-   *  @param iter  the iterable object.
+   *  @param xs  the traversable object.
    */
-  override def prependAll(elems: Iterable[A]): Unit = self.prependAll(elems)
+  override def prependAll(xs: TraversableOnce[A]) { self.prependAll(xs) }
 
-  /** Inserts new elements at the index <code>n</code>. Opposed to method
-   *  <code>update</code>, this method will not replace an element with a
-   *  one. Instead, it will insert the new elements at index <code>n</code>.
+  /** Inserts new elements at the index `n`. Opposed to method
+   *  `update`, this method will not replace an element with a
+   *  one. Instead, it will insert the new elements at index `n`.
    *
    *  @param n      the index where a new element will be inserted.
    *  @param elems  the new elements to insert.
    */
-  override def insert(n: Int, elems: A*): Unit = self.insertAll(n, elems)
+  override def insert(n: Int, elems: A*) { self.insertAll(n, elems) }
 
-  /** Inserts new elements at the index <code>n</code>. Opposed to method
-   *  <code>update</code>, this method will not replace an element with a
-   *  one. Instead, it will insert a new element at index <code>n</code>.
+  /** Inserts new elements at the index `n`. Opposed to method
+   *  `update`, this method will not replace an element with a
+   *  one. Instead, it will insert a new element at index `n`.
    *
    *  @param n     the index where a new element will be inserted.
    *  @param iter  the iterable object providing all elements to insert.
    */
-  def insertAll(n: Int, iter: Iterable[A]): Unit = self.insertAll(n, iter)
+  def insertAll(n: Int, iter: scala.collection.Iterable[A]) {
+    self.insertAll(n, iter)
+  }
+
+  override def insertAll(n: Int, iter: scala.collection.Traversable[A]) {
+    self.insertAll(n, iter)
+  }
 
-  /** Replace element at index <code>n</code> with the new element
-   *  <code>newelem</code>.
+  /** Replace element at index `n` with the new element `newelem`.
    *
    *  @param n       the index of the element to replace.
    *  @param newelem the new element.
    */
-  def update(n: Int, newelem: A): Unit = self.update(n, newelem)
+  def update(n: Int, newelem: A) { self.update(n, newelem) }
 
   /** Removes the element on a given index position.
    *
@@ -138,17 +148,17 @@ trait BufferProxy[A] extends Buffer[A] with Proxy {
 
   /** Clears the buffer contents.
    */
-  def clear(): Unit = self.clear
+  def clear() { self.clear }
 
   /** Send a message to this scriptable object.
    *
    *  @param cmd  the message to send.
    */
-  override def <<(cmd: Message[(Location, A)]): Unit = self << cmd
+  override def <<(cmd: Message[A]) { self << cmd }
 
   /** Return a clone of this buffer.
    *
-   *  @return a <code>Buffer</code> with the same elements.
+   *  @return a `Buffer` with the same elements.
    */
   override def clone(): Buffer[A] = new BufferProxy[A] {
     def self = BufferProxy.this.self.clone()
diff --git a/src/library/scala/collection/mutable/Builder.scala b/src/library/scala/collection/mutable/Builder.scala
new file mode 100644
index 0000000..14bc929
--- /dev/null
+++ b/src/library/scala/collection/mutable/Builder.scala
@@ -0,0 +1,106 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+package scala.collection
+package mutable
+
+import generic._
+
+/** The base trait of all builders.
+ *  A builder lets one construct a collection incrementally, by adding
+ *  elements to the builder with `+=` and then converting to the required
+ *  collection type with `result`.
+ *
+ *  @tparam  Elem  the type of elements that get added to the builder.
+ *  @tparam  To    the type of collection that it produced.
+ *
+ *  @since 2.8
+ */
+trait Builder[-Elem, +To] extends Growable[Elem] {
+
+  /** Adds a single element to the builder.
+   *  @param elem the element to be added.
+   *  @return the builder itself.
+   */
+  def +=(elem: Elem): this.type
+  
+  /** Clears the contents of this builder.
+   *  After execution of this method the builder will contain no elements.
+   */
+  def clear()
+
+  /** Produces a collection from the added elements.
+   *  The builder's contents are undefined after this operation.
+   *  @return a collection containing the elements added to this builder.
+   */
+  def result(): To
+
+  /** Gives a hint how many elements are expected to be added
+   *  when the next `result` is called. Some builder classes
+   *  will optimize their representation based on the hint. However,
+   *  builder implementations are still required to work correctly even if the hint is
+   *  wrong, i.e. a different number of elements is added.
+   * 
+   *  @param size  the hint how many elements will be added.
+   */
+  def sizeHint(size: Int) {}
+
+  /** Gives a hint that one expects the `result` of this builder
+   *  to have the same size as the given collection, plus some delta. This will
+   *  provide a hint only if the collection is known to have a cheap
+   *  `size` method. Currently this is assumed ot be the case if and only if
+   *  the collection is of type `IndexedSeqLike`.
+   *  Some builder classes
+   *  will optimize their representation based on the hint. However,
+   *  builder implementations are still required to work correctly even if the hint is
+   *  wrong, i.e. a different number of elements is added.
+   * 
+   *  @param coll  the collection which serves as a hint for the result's size.
+   *  @param delta a correction to add to the `coll.size` to produce the size hint.
+   */
+  def sizeHint(coll: TraversableLike[_, _], delta: Int = 0) {
+    if (coll.isInstanceOf[IndexedSeqLike[_,_]]) {
+      sizeHint(coll.size + delta)
+    }
+  }
+
+  /** Gives a hint how many elements are expected to be added
+   *  when the next `result` is called, together with an upper bound
+   *  given by the size of some other collection. Some builder classes
+   *  will optimize their representation based on the hint. However,
+   *  builder implementations are still required to work correctly even if the hint is
+   *  wrong, i.e. a different number of elements is added.
+   * 
+   *  @param size  the hint how many elements will be added.
+   *  @param boundingColl  the bounding collection. If it is
+   *                       an IndexedSeqLike, then sizes larger 
+   *                       than collection's size are reduced.
+   */
+  def sizeHintBounded(size: Int, boundingColl: TraversableLike[_, _]) {
+    if (boundingColl.isInstanceOf[IndexedSeqLike[_,_]])
+      sizeHint(size min boundingColl.size)
+  }
+
+  /** Creates a new builder by applying a transformation function to
+   *  the results of this builder.
+   *  @param  f     the transformation function.
+   *  @tparam NewTo the type of collection returned by `f`.
+   *  @return a new builder which is the same as the current builder except
+   *          that a transformation function is applied to this builder's result.
+   */	
+  def mapResult[NewTo](f: To => NewTo): Builder[Elem, NewTo] = 
+    new Builder[Elem, NewTo] with Proxy {
+      val self = Builder.this
+      def +=(x: Elem): this.type = { self += x; this }
+      def clear() = self.clear()
+      override def ++=(xs: TraversableOnce[Elem]): this.type = { self ++= xs; this }
+      def result: NewTo = f(self.result)
+    }
+}
+
diff --git a/src/library/scala/collection/mutable/Cloneable.scala b/src/library/scala/collection/mutable/Cloneable.scala
new file mode 100644
index 0000000..f82111f
--- /dev/null
+++ b/src/library/scala/collection/mutable/Cloneable.scala
@@ -0,0 +1,23 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+package mutable
+
+/** A trait for cloneable collections.
+ *  
+ *  @since 2.8
+ *  
+ *  @tparam A    Type of the elements contained in the collection, covariant and with reference types as upperbound.
+ */
+ at cloneable
+trait Cloneable[+A <: AnyRef]  {
+  override def clone: A = super.clone().asInstanceOf[A]
+}
diff --git a/src/library/scala/collection/mutable/CloneableCollection.scala b/src/library/scala/collection/mutable/CloneableCollection.scala
index 0d6ae9b..625b849 100644
--- a/src/library/scala/collection/mutable/CloneableCollection.scala
+++ b/src/library/scala/collection/mutable/CloneableCollection.scala
@@ -1,19 +1,22 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: CloneableCollection.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.collection.mutable
+package scala.collection
+package mutable
 
-/** The J2ME version of the library defined this trait with a clone method
- * to substitute for the lack of Object.clone there
+/** The J2ME version of the library defined this trait with a `clone`
+ *  method to substitute for the lack of `Object.clone` there.
+ *
+ *  @since 2.6
  */
+ at deprecated("use Cloneable instead")
 trait CloneableCollection {
   override def clone(): AnyRef = super.clone()
 }
diff --git a/src/library/scala/collection/mutable/ConcurrentMap.scala b/src/library/scala/collection/mutable/ConcurrentMap.scala
new file mode 100644
index 0000000..5239b48
--- /dev/null
+++ b/src/library/scala/collection/mutable/ConcurrentMap.scala
@@ -0,0 +1,68 @@
+package scala.collection
+package mutable
+
+
+/** A template trait for mutable maps that allow concurrent access.
+ *  
+ *  $concurrentmapinfo
+ *  
+ *  @since 2.8
+ * 
+ *  @tparam A  the key type of the map
+ *  @tparam B  the value type of the map
+ *  
+ *  @define Coll ConcurrentMap
+ *  @define coll concurrent map
+ *  @define concurrentmapinfo
+ *  This is a base trait for all Scala concurrent map implementations. It
+ *  provides all of the methods a `Map` does, with the difference that all the
+ *  changes are atomic. It also describes methods specific to concurrent maps.
+ *  Note: The concurrent maps do not accept `null` for keys or values.
+ *  
+ *  @define atomicop
+ *  This is done atomically.
+ */
+trait ConcurrentMap[A, B] extends Map[A, B] {
+  
+  /**
+   * Associates the given key with a given value, unless the key was already associated with some other value.
+   * $atomicop
+   * 
+   * @param k   key with which the specified value is to be associated with
+   * @param v   value to be associated with the specified key
+   * @return    `Some(oldvalue)` if there was a value `oldvalue` previously associated with the
+   *            specified key, or `None` if there was no mapping for the specified key
+   */
+  def putIfAbsent(k: A, v: B): Option[B]
+  
+  /**
+   * Removes the entry for the specified key if its currently mapped to the specified value.
+   * $atomicop
+   * 
+   * @param k   key for which the entry should be removed
+   * @param v   value expected to be associated with the specified key if the removal is to take place
+   * @return    `true` if the removal took place, `false` otherwise
+   */
+  def remove(k: A, v: B): Boolean
+  
+  /**
+   * Replaces the entry for the given key only if it was previously mapped to a given value.
+   * $atomicop
+   * 
+   * @param k         key for which the entry should be replaced
+   * @param oldvalue  value expected to be associated with the specified key if replacing is to happen
+   * @param newvalue  value to be associated with the specified key
+   * @return          `true` if the entry was replaced, `false` otherwise
+   */
+  def replace(k: A, oldvalue: B, newvalue: B): Boolean
+  
+  /**
+   * Replaces the entry for the given key only if it was previously mapped to some value.
+   * $atomicop
+   * 
+   * @param k   key for which the entry should be replaced
+   * @param v   value to be associated with the specified key
+   * @return    `Some(v)` if the given key was previously mapped to some value `v`, or `None` otherwise
+   */
+  def replace(k: A, v: B): Option[B]  
+}
diff --git a/src/library/scala/collection/mutable/DefaultEntry.scala b/src/library/scala/collection/mutable/DefaultEntry.scala
index 6659d06..ee0e736 100644
--- a/src/library/scala/collection/mutable/DefaultEntry.scala
+++ b/src/library/scala/collection/mutable/DefaultEntry.scala
@@ -1,18 +1,21 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: DefaultEntry.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.collection.mutable
+package scala.collection
+package mutable
 
-import Predef._
 
+
+/** Class used internally for default map model.
+ *  @since 2.3
+ */
 @serializable
 final class DefaultEntry[A, B](val key: A, var value: B) 
       extends HashEntry[A, DefaultEntry[A, B]]
diff --git a/src/library/scala/collection/mutable/DefaultMapModel.scala b/src/library/scala/collection/mutable/DefaultMapModel.scala
index 8ef272e..226a096 100644
--- a/src/library/scala/collection/mutable/DefaultMapModel.scala
+++ b/src/library/scala/collection/mutable/DefaultMapModel.scala
@@ -1,24 +1,22 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://www.scala-lang.org/           **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: DefaultMapModel.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.collection.mutable
+package scala.collection
+package mutable
 
-import Predef._
-
-/** This class is used internally. It implements the mutable <code>Map</code>
- *  class in terms of three functions: <code>findEntry</code>,
- *  <code>addEntry</code>, and <code>entries</code>.
+/** This class is used internally. It implements the mutable `Map`
+ *  class in terms of three functions: `findEntry`, `addEntry`, and `entries`.
  *
  *  @author  Matthias Zenger
  *  @version 1.0, 08/07/2003
+ *  @since   1
  */
 trait DefaultMapModel[A, B] extends Map[A, B] {
 
@@ -31,15 +29,17 @@ trait DefaultMapModel[A, B] extends Map[A, B] {
   def get(key: A): Option[B] = {
     val e = findEntry(key)
     if (e == null) None
-    else Some(e.value);
+    else Some(e.value)
   }
 
-  def update(key: A, value: B) {
+  override def put(key: A, value: B): Option[B] = {
     val e = findEntry(key)
-    if (e == null) addEntry(new Entry(key, value))
-    else e.value = value
+    if (e == null) { addEntry(new Entry(key, value)); None }
+    else { val v = e.value; e.value = value; Some(v) }
   }
 
-  def elements = entries map {e => (e.key, e.value)}
-}
+  def += (kv: (A, B)): this.type = { put(kv._1, kv._2); this }
 
+  def iterator = entries map {e => (e.key, e.value)}
+
+}
diff --git a/src/library/scala/collection/mutable/DoubleLinkedList.scala b/src/library/scala/collection/mutable/DoubleLinkedList.scala
index 6930e57..a366627 100644
--- a/src/library/scala/collection/mutable/DoubleLinkedList.scala
+++ b/src/library/scala/collection/mutable/DoubleLinkedList.scala
@@ -1,52 +1,89 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: DoubleLinkedList.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.collection.mutable
+package scala.collection
+package mutable
 
+import generic._
 
-/** This extensible class may be used as a basis for implementing double
- *  linked lists. Type variable <code>A</code> refers to the element type
- *  of the list, type variable <code>This</code> is used to model self
- *  types of linked lists.
+/** This class implements double linked lists where both the head (`elem`),
+ *  the tail (`next`) and a reference to the previous node (`prev`) are mutable.
  *
- *  @author  Matthias Zenger
- *  @version 1.0, 08/07/2003
+ *  @author Matthias Zenger
+ *  @author Martin Odersky
+ *  @version 2.8
+ *  @since   1
+ *  
+ *  @tparam A     the type of the elements contained in this double linked list.
+ *  
+ *  @define Coll DoubleLinkedList
+ *  @define coll double linked list
+ *  @define thatinfo the class of the returned collection. In the standard library configuration,
+ *    `That` is always `DoubleLinkedList[B]` because an implicit of type `CanBuildFrom[DoubleLinkedList, B, DoubleLinkedList[B]]`
+ *    is defined in object `DoubleLinkedList`.
+ *  @define $bfinfo an implicit value of class `CanBuildFrom` which determines the
+ *    result class `That` from the current representation type `Repr`
+ *    and the new element type `B`. This is usually the `canBuildFrom` value
+ *    defined in object `DoubleLinkedList`.
+ *  @define orderDependent 
+ *  @define orderDependentFold
+ *  @define mayNotTerminateInf
+ *  @define willNotTerminateInf
  */
-abstract class DoubleLinkedList[A, This >: Null <: DoubleLinkedList[A, This]]
-         extends SingleLinkedList[A, This]
-{ self: This =>
-
-  var prev: This
-
-  override def append(that: This): Unit =
-    if (that eq null)
-      ()
-    else if (next eq null) {
-      next = that
-      that.prev = this
-    } else
-      next.append(that)
-
-  override def insert(that: This): Unit = if (that ne null) {
-    that.append(next)
-    next = that
-    that.prev = this
-  }
+ at serializable @SerialVersionUID(-8144992287952814767L)
+class DoubleLinkedList[A]() extends LinearSeq[A]
+                            with GenericTraversableTemplate[A, DoubleLinkedList]
+                            with DoubleLinkedListLike[A, DoubleLinkedList[A]] {
+  next = this
 
-  def remove() {
-    if (next ne null)
-      next.prev = prev
-    if (prev ne null)
-      prev.next = next
-    prev = null
-    next = null
+  /** Creates a node for the double linked list.
+   *  
+   *  @param elem    the element this node contains.
+   *  @param next    the next node in the double linked list.
+   */
+  def this(elem: A, next: DoubleLinkedList[A]) {
+    this()
+    if (next != null) {
+      this.elem = elem
+      this.next = next
+    }
   }
+
+  override def companion: GenericCompanion[DoubleLinkedList] = DoubleLinkedList
+}
+
+/** $factoryInfo
+ *  @define coll double linked list
+ *  @define Coll DoubleLinkedList
+ */
+object DoubleLinkedList extends SeqFactory[DoubleLinkedList] {
+  /** $genericCanBuildFrom */
+  implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, DoubleLinkedList[A]] = new GenericCanBuildFrom[A]
+  def newBuilder[A]: Builder[A, DoubleLinkedList[A]] =
+    new Builder[A, DoubleLinkedList[A]] {
+      var current: DoubleLinkedList[A] = _
+      val emptyList = new DoubleLinkedList[A]()
+      if(null == current)
+        current = emptyList
+
+      def +=(elem: A): this.type = {
+        if (current.nonEmpty)
+          current.insert(new DoubleLinkedList(elem, emptyList))
+        else
+          current = new DoubleLinkedList(elem, emptyList)
+        this
+      }
+
+      def clear() {
+        current = emptyList
+      }
+      def result() = current
+    }
 }
diff --git a/src/library/scala/collection/mutable/DoubleLinkedListLike.scala b/src/library/scala/collection/mutable/DoubleLinkedListLike.scala
new file mode 100644
index 0000000..3a1dacb
--- /dev/null
+++ b/src/library/scala/collection/mutable/DoubleLinkedListLike.scala
@@ -0,0 +1,58 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+package mutable
+
+/** This extensible class may be used as a basis for implementing double
+ *  linked lists. Type variable `A` refers to the element type
+ *  of the list, type variable `This` is used to model self
+ *  types of linked lists.
+ *
+ *  @author  Matthias Zenger
+ *  @version 1.0, 08/07/2003
+ *  @since   2.8
+ *  
+ *  @tparam A    type of the elements contained in the double linked list
+ *  @tparam This the type of the actual linked list holding the elements
+ *  
+ *  @define Coll DoubleLinkedList
+ *  @define coll double linked list
+ */
+trait DoubleLinkedListLike[A, This <: Seq[A] with DoubleLinkedListLike[A, This]] extends LinkedListLike[A, This] { self =>
+  
+  /** A reference to the node in the linked list preceeding the current node. */
+  var prev: This = _
+
+  override def append(that: This): This = 
+    if (isEmpty) 
+      that
+    else {
+      if (next.isEmpty) {
+        next = that
+        if (that.nonEmpty) that.prev = repr
+      } else {
+        next.append(that)
+      }
+      repr
+    }
+
+  override def insert(that: This): Unit = {
+    super.insert(that)
+    if (that.nonEmpty) that.prev = repr
+  }
+
+  def remove() {
+    if (next.nonEmpty)
+      next.prev = prev
+    if (prev.nonEmpty)
+      prev.next = next
+  }
+}
diff --git a/src/library/scala/collection/mutable/FlatHashTable.scala b/src/library/scala/collection/mutable/FlatHashTable.scala
index 8bd07a4..8ea0b54 100644
--- a/src/library/scala/collection/mutable/FlatHashTable.scala
+++ b/src/library/scala/collection/mutable/FlatHashTable.scala
@@ -1,17 +1,25 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: FlatHashTable.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.collection.mutable
+package scala.collection
+package mutable
 
-import Predef._
 
+/** An implementation class backing a `HashSet`.
+ *  
+ *  This trait is used internally. It can be mixed in with various collections relying on
+ *  hash table as an implementation.
+ *  
+ *  @since 2.3
+ *  
+ *  @tparam A   the type of the elements contained in the flat hash table.
+ */
 trait FlatHashTable[A] {
 
   /** The load factor for the hash table; must be < 500 (0.5)
@@ -24,24 +32,66 @@ trait FlatHashTable[A] {
   protected def initialSize: Int = 16
 
   private final val tableDebug = false
+  
+  @transient private[collection] var _loadFactor = loadFactor
 
   /** The actual hash table.
    */
-  protected var table: Array[AnyRef] = 
-    if (initialSize == 0) null else new Array(initialSize)
+  @transient protected var table: Array[AnyRef] = new Array(initialCapacity)
 
   /** The number of mappings contained in this hash table.
    */
-  protected var tableSize = 0
+  @transient protected var tableSize = 0
 
   /** The next size value at which to resize (capacity * load factor).
    */
-  protected var threshold: Int = newThreshold(initialSize)
-
-  /** Returns the number of entires in this hash table.
+  @transient protected var threshold: Int = newThreshold(initialCapacity)
+  
+  import HashTable.powerOfTwo
+  private def capacity(expectedSize: Int) = if (expectedSize == 0) 1 else powerOfTwo(expectedSize)
+  private def initialCapacity = capacity(initialSize)
+  
+  /**
+   * Initializes the collection from the input stream. `f` will be called for each element
+   * read from the input stream in the order determined by the stream. This is useful for
+   * structures where iteration order is important (e.g. LinkedHashSet).
+   * 
+   * The serialization format expected is the one produced by `serializeTo`.
+   */
+  private[collection] def init(in: java.io.ObjectInputStream, f: A => Unit) {
+    in.defaultReadObject
+    
+    _loadFactor = in.readInt
+    assert(_loadFactor > 0)
+    
+    val size = in.readInt
+    assert(size >= 0)
+    
+    table = new Array(capacity(size * loadFactorDenum / _loadFactor))
+    threshold = newThreshold(table.size)
+    
+    var index = 0
+    while (index < size) {
+      val elem = in.readObject.asInstanceOf[A]
+      f(elem)
+      addEntry(elem)
+      index += 1
+    }
+  }
+  
+  /**
+   * Serializes the collection to the output stream by saving the load factor, collection
+   * size and collection elements. `foreach` determines the order in which the elements are saved
+   * to the stream. To deserialize, `init` should be used.
    */
-  def size: Int = tableSize
+  private[collection] def serializeTo(out: java.io.ObjectOutputStream) {
+    out.defaultWriteObject
+    out.writeInt(_loadFactor)
+    out.writeInt(tableSize)
+    iterator.foreach(out.writeObject)
+  }
   
+  /** Finds an entry in the hash table if such an element exists. */
   def findEntry(elem: A): Option[A] = {
     var h = index(elemHashCode(elem))
     var entry = table(h)
@@ -52,6 +102,7 @@ trait FlatHashTable[A] {
     if (null == entry) None else Some(entry.asInstanceOf[A])
   }
 
+  /** Checks whether an element is contained in the hash table. */
   def containsEntry(elem: A): Boolean = {
     var h = index(elemHashCode(elem))
     var entry = table(h)
@@ -62,6 +113,9 @@ trait FlatHashTable[A] {
     null != entry
   }
 
+  /** Add entry if not yet in table.
+   *  @return Returns `true` if a new entry was added, `false` otherwise.
+   */
   def addEntry(elem: A) : Boolean = {
     var h = index(elemHashCode(elem))
     var entry = table(h)
@@ -76,6 +130,7 @@ trait FlatHashTable[A] {
     true
   }
 
+  /** Removes an entry from the hash table, returning an option value with the element, or `None` if it didn't exist. */
   def removeEntry(elem: A) : Option[A] = {
     if (tableDebug) checkConsistent()
     def precedes(i: Int, j: Int) = {
@@ -110,10 +165,10 @@ trait FlatHashTable[A] {
     None
   }
 
-  def elements = new Iterator[A] {
+  def iterator = new Iterator[A] {
     private var i = 0
     def hasNext: Boolean = {
-      while (i < table.length && (null == table(i))) i += 1;
+      while (i < table.length && (null == table(i))) i += 1
       i < table.length
     }
     def next(): A =
@@ -138,10 +193,10 @@ trait FlatHashTable[A] {
   private def checkConsistent() {
     for (i <- 0 until table.length)
       if (table(i) != null && !containsEntry(table(i).asInstanceOf[A]))
-        assert(false, i+" "+table(i)+" "+table.toString)
+        assert(false, i+" "+table(i)+" "+table.mkString)
   }
 
-  protected def elemHashCode(elem: A) = elem.hashCode()
+  protected def elemHashCode(elem: A) = if (elem == null) 0 else elem.hashCode()
 
   protected final def improve(hcode: Int) = {
     var h: Int = hcode + ~(hcode << 9)
@@ -153,12 +208,12 @@ trait FlatHashTable[A] {
   protected final def index(hcode: Int) = improve(hcode) & (table.length - 1)
 
   private def newThreshold(size: Int) = {
-    val lf = loadFactor
+    val lf = _loadFactor
     assert(lf < (loadFactorDenum / 2), "loadFactor too large; must be < 0.5")
     (size.toLong * lf / loadFactorDenum ).toInt
   }
 
-  protected def clear() {
+  protected def clearTable() {
     var i = table.length - 1
     while (i >= 0) { table(i) = null; i -= 1 }
     tableSize = 0
diff --git a/src/library/scala/collection/mutable/GrowingBuilder.scala b/src/library/scala/collection/mutable/GrowingBuilder.scala
new file mode 100644
index 0000000..1711452
--- /dev/null
+++ b/src/library/scala/collection/mutable/GrowingBuilder.scala
@@ -0,0 +1,38 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+package scala.collection
+package mutable
+
+import generic._
+
+/** The canonical builder for collections that are growable, i.e. that support an
+ *  efficient `+=` method which adds an element to the collection.  It is
+ *  almost identical to `AddingBuilder`, but necessitated by the existence of
+ *  classes which are `Growable` but not `Addable`, which is a result of covariance
+ *  interacting surprisingly with any2stringadd thus driving '+' out of the `Seq`
+ *  hierarchy.  The tendrils of original sin should never be underestimated.
+ *
+ *  Addendum: of even greater significance is that '+' on mutable collections now
+ *  creates a new collection.  This means using AddingBuilder on them will create
+ *  a new intermediate collection for every element given to the builder, taking
+ *  '+' from an O(1) to O(n) operation.
+ *
+ *  @author Paul Phillips
+ *  @version 2.8
+ *  @since 2.8
+ *  
+ *  @define Coll GrowingBuilder
+ *  @define coll growing builder
+ */
+class GrowingBuilder[Elem, To <: Growable[Elem]](empty: To) extends Builder[Elem, To] {
+  protected var elems: To = empty
+  def +=(x: Elem): this.type = { elems += x; this }
+  def clear() { elems = empty }
+  def result: To = elems
+}
diff --git a/src/library/scala/collection/mutable/HashEntry.scala b/src/library/scala/collection/mutable/HashEntry.scala
new file mode 100644
index 0000000..7c62dc6
--- /dev/null
+++ b/src/library/scala/collection/mutable/HashEntry.scala
@@ -0,0 +1,17 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://www.scala-lang.org/           **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+package scala.collection
+package mutable
+
+/** Class used internally.
+ *  @since 2.8
+ */
+trait HashEntry [A, E] {
+  val key: A
+  var next: E = _
+}
diff --git a/src/library/scala/collection/mutable/HashMap.scala b/src/library/scala/collection/mutable/HashMap.scala
index bd97d66..16e3075 100644
--- a/src/library/scala/collection/mutable/HashMap.scala
+++ b/src/library/scala/collection/mutable/HashMap.scala
@@ -1,40 +1,122 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: HashMap.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.collection.mutable
+package scala.collection
+package mutable
+
+import generic._
 
-import Predef._
 
 /** This class implements mutable maps using a hashtable.
- *
- *  @author  Matthias Zenger
- *  @author  Martin Odersky
- *  @version 2.0, 31/12/2006
+ *  
+ *  @since 1
+ *  
+ *  @tparam A    the type of the keys contained in this hash map.
+ *  @tparam B    the type of the values assigned to keys in this hash map.
+ *  
+ *  @define Coll mutable.HashMap
+ *  @define coll mutable hash map
+ *  @define thatinfo the class of the returned collection. In the standard library configuration,
+ *    `That` is always `HashMap[A, B]` if the elements contained in the resulting collection are 
+ *    pairs of type `(A, B)`. This is because an implicit of type `CanBuildFrom[HashMap, (A, B), HashMap[A, B]]`
+ *    is defined in object `HashMap`. Otherwise, `That` resolves to the most specific type that doesn't have
+ *    to contain pairs of type `(A, B)`, which is `Iterable`.
+ *  @define $bfinfo an implicit value of class `CanBuildFrom` which determines the
+ *    result class `That` from the current representation type `Repr`
+ *    and the new element type `B`. This is usually the `canBuildFrom` value
+ *    defined in object `HashMap`.
+ *  @define mayNotTerminateInf
+ *  @define willNotTerminateInf
  */
-object HashMap {
+ at serializable @SerialVersionUID(1L)
+class HashMap[A, B] extends Map[A, B] 
+                       with MapLike[A, B, HashMap[A, B]] 
+                       with HashTable[A] {
 
-  /** The empty map of this type */  
-  def empty[A, B] = new HashMap[A, B]
+  override def empty: HashMap[A, B] = HashMap.empty[A, B]
+  override def clear() = clearTable()
+  override def size: Int = tableSize
 
-  /** The canonical factory for this type
-   */
-  def apply[A, B](elems: (A, B)*) = empty[A, B] ++ elems
-}
+  type Entry = DefaultEntry[A, B]
+                         
+  def get(key: A): Option[B] = {
+    val e = findEntry(key)
+    if (e == null) None
+    else Some(e.value)
+  }
+
+  override def put(key: A, value: B): Option[B] = {
+    val e = findEntry(key)
+    if (e == null) { addEntry(new Entry(key, value)); None }
+    else { val v = e.value; e.value = value; Some(v) }
+  }
+
+  override def update(key: A, value: B): Unit = put(key, value)
 
- at serializable
-class HashMap[A, B] extends Map[A,B] with HashTable[A] with DefaultMapModel[A,B] {
+  override def remove(key: A): Option[B] = {
+    val e = removeEntry(key)
+    if (e ne null) Some(e.value)
+    else None
+  }
 
-  def -= (key: A) { removeEntry(key) }
+  def += (kv: (A, B)): this.type = { 
+    val e = findEntry(kv._1)
+    if (e == null) addEntry(new Entry(kv._1, kv._2))
+    else e.value = kv._2
+    this
+  }
 
-  override def clear() = super.clear()
+  def -=(key: A): this.type = { removeEntry(key); this }
 
-  override def clone(): Map[A, B] = new HashMap[A, B] ++ this
+  def iterator = entriesIterator map {e => (e.key, e.value)}
+  
+  override def foreach[C](f: ((A, B)) => C): Unit = foreachEntry(e => f(e.key, e.value))
+  
+  /* Override to avoid tuple allocation in foreach */
+  override def keySet: collection.Set[A] = new DefaultKeySet {
+    override def foreach[C](f: A => C) = foreachEntry(e => f(e.key))
+  }
+  
+  /* Override to avoid tuple allocation in foreach */
+  override def values: collection.Iterable[B] = new DefaultValuesIterable {
+    override def foreach[C](f: B => C) = foreachEntry(e => f(e.value))
+  }
+  
+  /* Override to avoid tuple allocation */
+  override def keysIterator: Iterator[A] = new Iterator[A] {
+    val iter = entriesIterator
+    def hasNext = iter.hasNext
+    def next = iter.next.key
+  }
+  
+  /* Override to avoid tuple allocation */
+  override def valuesIterator: Iterator[B] = new Iterator[B] {
+    val iter = entriesIterator
+    def hasNext = iter.hasNext
+    def next = iter.next.value
+  }
+  
+  private def writeObject(out: java.io.ObjectOutputStream) {
+    serializeTo(out, _.value)
+  }
+  
+  private def readObject(in: java.io.ObjectInputStream) {
+    init[B](in, new Entry(_, _))
+  }
+}
+
+/** $factoryInfo
+ *  @define Coll mutable.HashMap
+ *  @define coll mutable hash map
+ */
+object HashMap extends MutableMapFactory[HashMap] {
+  implicit def canBuildFrom[A, B]: CanBuildFrom[Coll, (A, B), HashMap[A, B]] = new MapCanBuildFrom[A, B]
+  def empty[A, B]: HashMap[A, B] = new HashMap[A, B]
 }
diff --git a/src/library/scala/collection/mutable/HashSet.scala b/src/library/scala/collection/mutable/HashSet.scala
index 30553d9..3dc1927 100644
--- a/src/library/scala/collection/mutable/HashSet.scala
+++ b/src/library/scala/collection/mutable/HashSet.scala
@@ -1,43 +1,85 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: HashSet.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.collection.mutable
+package scala.collection
+package mutable
+
+import generic._
 
 /** This class implements mutable sets using a hashtable.
  *
  *  @author  Matthias Zenger
  *  @author  Martin Odersky
  *  @version 2.0, 31/12/2006
+ *  @since   1
+ *  
+ *  @tparam A     the type of the elements contained in this set.
+ *  
+ *  @define Coll mutable.HashSet
+ *  @define coll mutable hash set
+ *  @define thatinfo the class of the returned collection. In the standard library configuration,
+ *    `That` is always `HashSet[B]` because an implicit of type `CanBuildFrom[HashSet, B, HashSet[B]]`
+ *    is defined in object `HashSet`.
+ *  @define $bfinfo an implicit value of class `CanBuildFrom` which determines the
+ *    result class `That` from the current representation type `Repr`
+ *    and the new element type `B`. This is usually the `canBuildFrom` value
+ *    defined in object `HashSet`.
+ *  @define mayNotTerminateInf
+ *  @define willNotTerminateInf
  */
-object HashSet {
+ at serializable @SerialVersionUID(1L)
+class HashSet[A] extends Set[A] 
+                    with GenericSetTemplate[A, HashSet]
+                    with SetLike[A, HashSet[A]] 
+                    with FlatHashTable[A] {
+  override def companion: GenericCompanion[HashSet] = HashSet
 
-  /** The empty map of this type */  
-  def empty[A] = new HashSet[A]
+  override def size = tableSize
 
-  /** The canonical factory for this type
-   */
-  def apply[A](elems: A*) = empty[A] ++ elems
-}
+  def contains(elem: A): Boolean = containsEntry(elem)
 
- at serializable
-class HashSet[A] extends Set[A] with FlatHashTable[A] {
+  def += (elem: A): this.type = { addEntry(elem); this }
+  def -= (elem: A): this.type = { removeEntry(elem); this }
 
-  def contains(elem: A): Boolean = containsEntry(elem)
+  override def add(elem: A): Boolean = addEntry(elem)
+  override def remove(elem: A): Boolean = removeEntry(elem).isDefined
 
-  def +=(elem: A) { addEntry(elem) }
+  override def clear() = clearTable()
  
-  def -=(elem: A) { removeEntry(elem) }
+  override def foreach[U](f: A =>  U) {
+    var i = 0
+    val len = table.length
+    while (i < len) {
+      val elem = table(i)
+      if (elem ne null) f(elem.asInstanceOf[A])
+      i += 1
+    }
+  }
 
-  override def clear() = super.clear()
+  override def clone() = new HashSet[A] ++= this
+  
+  private def writeObject(s: java.io.ObjectOutputStream) {
+    serializeTo(s)
+  }
+  
+  private def readObject(in: java.io.ObjectInputStream) {
+    init(in, x => x)
+  }
+}
 
-  override def clone(): Set[A] = new HashSet[A] ++ this
+/** $factoryInfo
+ *  @define Coll mutable.HashSet
+ *  @define coll mutable hash set
+ */
+object HashSet extends MutableSetFactory[HashSet] {
+  implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, HashSet[A]] = setCanBuildFrom[A]
+  override def empty[A]: HashSet[A] = new HashSet[A]
 }
 
diff --git a/src/library/scala/collection/mutable/HashTable.scala b/src/library/scala/collection/mutable/HashTable.scala
index 92d4a42..cbb9d68 100644
--- a/src/library/scala/collection/mutable/HashTable.scala
+++ b/src/library/scala/collection/mutable/HashTable.scala
@@ -1,35 +1,39 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://www.scala-lang.org/           **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: HashTable.scala 16881 2009-01-09 16:28:11Z cunei $
 
 
-package scala.collection.mutable
+package scala.collection
+package mutable
 
 /** This class can be used to construct data structures that are based
- *  on hashtables. Class <code>HashTable[A]</code> implements a hashtable
- *  that maps keys of type <code>A</code> to values of the fully abstract
- *  member type <code>Entry</code>. Classes that make use of <code>HashTable</code>
- *  have to provide an implementation for <code>Entry</code> 
+ *  on hashtables. Class `HashTable[A]` implements a hashtable
+ *  that maps keys of type `A` to values of the fully abstract
+ *  member type `Entry`. Classes that make use of `HashTable`
+ *  have to provide an implementation for `Entry`.
  *
  *  There are mainly two parameters that affect the performance of a hashtable:
  *  the <i>initial size</i> and the <i>load factor</i>. The <i>size</i>
  *  refers to the number of <i>buckets</i> in the hashtable, and the <i>load
  *  factor</i> is a measure of how full the hashtable is allowed to get before
  *  its size is automatically doubled. Both parameters may be changed by
- *  overriding the corresponding values in class <code>HashTable</code>.
+ *  overriding the corresponding values in class `HashTable`.
  *
  *  @author  Matthias Zenger
  *  @author  Martin Odersky
  *  @version 2.0, 31/12/2006
+ *  @since   1
+ *  
+ *  @tparam A     type of the elements contained in this hash table.
  */
-trait HashTable[A] extends AnyRef {
-
+trait HashTable[A] {
+  import HashTable._
+  
   protected type Entry >: Null <: HashEntry[A, Entry]
 
   /** The load factor for the hash table (in 0.001 step).
@@ -43,25 +47,70 @@ trait HashTable[A] extends AnyRef {
 
   /** The initial threshold
    */
-  protected def initialThreshold: Int = newThreshold(initialSize)
-
+  protected def initialThreshold: Int = newThreshold(initialCapacity)
+  
+  @transient private[collection] var _loadFactor = loadFactor
+  
   /** The actual hash table.
    */
-  protected var table: Array[HashEntry[A, Entry]] = 
-    if (initialSize == 0) null else new Array(initialSize)
-
+  @transient protected var table: Array[HashEntry[A, Entry]] = new Array(initialCapacity)
+  
   /** The number of mappings contained in this hash table.
    */
-  protected var tableSize: Int = 0
+  @transient protected var tableSize: Int = 0
 
   /** The next size value at which to resize (capacity * load factor).
    */
-  protected var threshold: Int = initialThreshold
-
-  /** Returns the size of this hash table.
+  @transient protected var threshold: Int = initialThreshold
+  
+  private def initialCapacity = capacity(initialSize)
+  
+  /**
+   * Initializes the collection from the input stream. `f` will be called for each key/value pair
+   * read from the input stream in the order determined by the stream. This is useful for
+   * structures where iteration order is important (e.g. LinkedHashMap).
+   */
+  private[collection] def init[B](in: java.io.ObjectInputStream, f: (A, B) => Entry) {
+    in.defaultReadObject
+    
+    _loadFactor = in.readInt
+    assert(_loadFactor > 0)
+    
+    val size = in.readInt
+    assert(size >= 0)
+    
+    table = new Array(capacity(size * loadFactorDenum / _loadFactor))
+    threshold = newThreshold(table.size)
+    
+    var index = 0
+    while (index < size) {
+      addEntry(f(in.readObject.asInstanceOf[A], in.readObject.asInstanceOf[B]))
+      index += 1
+    }
+  }
+  
+  /**
+   * Serializes the collection to the output stream by saving the load factor, collection
+   * size, collection keys and collection values. `value` is responsible for providing a value
+   * from an entry.
+   * 
+   * `foreach` determines the order in which the key/value pairs are saved to the stream. To
+   * deserialize, `init` should be used.
+   */
+  private[collection] def serializeTo[B](out: java.io.ObjectOutputStream, value: Entry => B) {
+    out.defaultWriteObject
+    out.writeInt(loadFactor)
+    out.writeInt(tableSize)
+    foreachEntry { entry =>
+      out.writeObject(entry.key)
+      out.writeObject(value(entry))
+    }
+  }
+  
+  private def capacity(expectedSize: Int) = if (expectedSize == 0) 1 else powerOfTwo(expectedSize)
+  
+  /** Find entry with given key in table, null if not found.
    */
-  def size = tableSize
-
   protected def findEntry(key: A): Entry = {
     val h = index(elemHashCode(key))
     var e = table(h).asInstanceOf[Entry]
@@ -69,6 +118,9 @@ trait HashTable[A] extends AnyRef {
     e
   }
 
+  /** Add entry to table
+   *  pre: no entry with same key exists
+   */
   protected def addEntry(e: Entry) {
     val h = index(elemHashCode(e.key))
     e.next = table(h).asInstanceOf[Entry]
@@ -78,14 +130,16 @@ trait HashTable[A] extends AnyRef {
       resize(2 * table.length)
   }
 
-  protected def removeEntry(key: A) : Option[Entry] = {
+  /** Remove entry from table if present.
+   */
+  protected def removeEntry(key: A) : Entry = {
     val h = index(elemHashCode(key))
     var e = table(h).asInstanceOf[Entry]
     if (e != null) {
       if (elemEquals(e.key, key)) {
         table(h) = e.next
         tableSize = tableSize - 1
-        return Some(e)
+        return e
       } else {
         var e1 = e.next
         while (e1 != null && !elemEquals(e1.key, key)) {
@@ -95,14 +149,16 @@ trait HashTable[A] extends AnyRef {
         if (e1 != null) {
           e.next = e1.next
           tableSize = tableSize - 1
-          return Some(e1)
+          return e1
         }
       }
     }
-    None
+    null
   }
 
-  protected def entries: Iterator[Entry] = new Iterator[Entry] {
+  /** An iterator returning all entries.
+   */
+  protected def entriesIterator: Iterator[Entry] = new Iterator[Entry] {
     val iterTable = table
     var idx = table.length - 1
     var es = iterTable(idx).asInstanceOf[Entry]
@@ -121,17 +177,38 @@ trait HashTable[A] extends AnyRef {
       }
     }
   }
+  
+  /*
+   * We should implement this as a primitive operation over the underlying array, but it can
+   * cause a behaviour change in edge cases where:
+   * - Someone modifies a map during iteration
+   * - The insertion point is close to the iteration point.
+   * 
+   * The reason this happens is that the iterator prefetches the following element before
+   * returning from next (to simplify the implementation of hasNext) while the natural
+   * implementation of foreach does not.
+   * 
+   * It should be mentioned that modifying a map during iteration leads to unpredictable
+   * results with either implementation.
+   */
+  protected final def foreachEntry[C](f: Entry => C) { entriesIterator.foreach(f) }
+
+  /** An iterator returning all entries */
+  @deprecated("use entriesIterator instead")
+  protected def entries: Iterator[Entry] = entriesIterator
 
-  def clear() {
+  /** Remove all entries from table
+   */
+  protected def clearTable() {
     var i = table.length - 1
     while (i >= 0) { table(i) = null; i = i - 1 }
     tableSize = 0
   }
 
   private def newThreshold(size: Int) =
-    ((size.toLong * loadFactor)/loadFactorDenum).toInt
+    ((size.toLong * _loadFactor)/loadFactorDenum).toInt
 
-  private def resize(newSize: Int) = {
+  private def resize(newSize: Int) {
     val oldTable = table
     table = new Array(newSize)
     var i = oldTable.length - 1
@@ -151,7 +228,7 @@ trait HashTable[A] extends AnyRef {
 
   protected def elemEquals(key1: A, key2: A): Boolean = (key1 == key2)
 
-  protected def elemHashCode(key: A) = key.hashCode()
+  protected def elemHashCode(key: A) = if (key == null) 0 else key.##
 
   protected final def improve(hcode: Int) = {
     var h: Int = hcode + ~(hcode << 9)
@@ -163,10 +240,19 @@ trait HashTable[A] extends AnyRef {
   protected final def index(hcode: Int) = improve(hcode) & (table.length - 1)
 }
 
-trait HashEntry[A, E] {
-  val key: A
-  var next: E = _
+private[collection] object HashTable {
+  
+  /**
+   * Returns a power of two >= `target`.
+   */
+  private[collection] def powerOfTwo(target: Int): Int = {
+    /* See http://bits.stephan-brumme.com/roundUpToNextPowerOfTwo.html */
+    var c = target - 1;
+    c |= c >>>  1;
+    c |= c >>>  2;
+    c |= c >>>  4;
+    c |= c >>>  8;
+    c |= c >>> 16;
+    c + 1;
+  }
 }
-
-
-
diff --git a/src/library/scala/collection/mutable/History.scala b/src/library/scala/collection/mutable/History.scala
index 7003fdb..3f9c6d2 100644
--- a/src/library/scala/collection/mutable/History.scala
+++ b/src/library/scala/collection/mutable/History.scala
@@ -1,48 +1,60 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/tPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: History.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.collection.mutable
+package scala.collection
+package mutable
 
 
-/** <code>History[A, B]</code> objects may subscribe to events of
- *  type <code>A</code> published by an object of type <code>B</code>.
+/** `History[A, B]` objects may subscribe to events of
+ *  type `A` published by an object of type `B`.
  *  The history subscriber object records all published events
- *  up to maximum number of <code>maxHistory</code> events.
+ *  up to maximum number of `maxHistory` events.
  *
  *  @author  Matthias Zenger
  *  @version 1.0, 08/07/2003
+ *  @since   1
+ *  
+ *  @tparam Evt   Type of events.
+ *  @tparam Pub   Type of publishers.
  */
 @serializable
-class History[A, B] extends AnyRef with Subscriber[A, B] with Collection[(B, A)] {
-
-  protected val log: Queue[(B, A)] = new Queue[(B, A)]
-
+ at SerialVersionUID(5219213543849892588L)
+class History[Evt, Pub] extends Subscriber[Evt, Pub] with Iterable[(Pub, Evt)]
+{
+  protected val log: Queue[(Pub, Evt)] = new Queue
   val maxHistory: Int = 1000
 
-  /**
-   *  @param pub   ...
-   *  @param event ...
+  /** Notifies this listener with an event by enqueuing it in the log.
+   *  
+   *  @param pub   the publisher.
+   *  @param event the event.
    */
-  def notify(pub: B, event: A): Unit = {
-    if (log.length >= maxHistory) {
-      val old = log.dequeue;
-    }
+  def notify(pub: Pub, event: Evt) {
+    if (log.length >= maxHistory)
+      log.dequeue
+      
     log.enqueue((pub, event))
   }
 
-  def elements: Iterator[(B, A)] = log.elements
-
-  def events: Iterator[A] = log.elements.map { case (_, e) => e }
-
   override def size: Int = log.length
-
-  def clear(): Unit = log.clear
+  def iterator: Iterator[(Pub, Evt)] = log.iterator
+  def events: Iterator[Evt] = log.iterator map (_._2)
+  
+  def clear() { log.clear }
+
+  /** Checks if two history objects are structurally identical.
+   *
+   *  @return true, iff both history objects contain the same sequence of elements.
+   */
+  override def equals(obj: Any): Boolean = obj match {
+    case that: History[_, _] => this.log equals that.log
+    case _                   => false
+  }
 }
diff --git a/src/library/scala/collection/mutable/ImmutableMapAdaptor.scala b/src/library/scala/collection/mutable/ImmutableMapAdaptor.scala
index f450499..d63ce01 100644
--- a/src/library/scala/collection/mutable/ImmutableMapAdaptor.scala
+++ b/src/library/scala/collection/mutable/ImmutableMapAdaptor.scala
@@ -1,33 +1,35 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: ImmutableMapAdaptor.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.collection.mutable
+package scala.collection
+package mutable
 
+import annotation.migration
 
 /** This class can be used as an adaptor to create mutable maps from
- *  immutable map implementations. Only method <code>empty</code> has
+ *  immutable map implementations. Only method `empty` has
  *  to be redefined if the immutable map on which this mutable map is
- *  originally based is not empty. <code>empty</code> is supposed to
+ *  originally based is not empty. `empty` is supposed to
  *  return the representation of an empty map.
  *
  *  @author  Matthias Zenger
  *  @author  Martin Odersky
  *  @version 2.0, 01/01/2007
+ *  @since   1
  */
 @serializable
 class ImmutableMapAdaptor[A, B](protected var imap: immutable.Map[A, B])
 extends Map[A, B]
 {
 
-  def size: Int = imap.size
+  override def size: Int = imap.size
 
   def get(key: A): Option[B] = imap.get(key)
 
@@ -39,27 +41,40 @@ extends Map[A, B]
 
   override def isDefinedAt(key: A) = imap.isDefinedAt(key)
 
-  override def keys: Iterator[A] = imap.keys
-
   override def keySet: collection.Set[A] = imap.keySet
 
-  override def values: Iterator[B] = imap.values
+  override def keysIterator: Iterator[A] = imap.keysIterator
+
+  @migration(2, 8, "As of 2.8, keys returns Iterable[A] rather than Iterator[A].")
+  override def keys: collection.Iterable[A] = imap.keys
+
+  override def valuesIterator: Iterator[B] = imap.valuesIterator
+
+  @migration(2, 8, "As of 2.8, values returns Iterable[B] rather than Iterator[B].")
+  override def values: collection.Iterable[B] = imap.values
 
-  def elements: Iterator[(A, B)] = imap.elements
+  def iterator: Iterator[(A, B)] = imap.iterator
+
+  @deprecated("use `iterator' instead")
+  override def elements = iterator
 
   override def toList: List[(A, B)] = imap.toList
 
-  def update(key: A, value: B): Unit = { imap = imap.update(key, value) }
+  override def update(key: A, value: B): Unit = { imap = imap.updated(key, value) }
+
+  def -= (key: A): this.type = { imap = imap - key; this }
 
-  def -= (key: A): Unit = { imap = imap - key }
+  def += (kv: (A, B)): this.type = { imap = imap + kv; this }
 
   override def clear(): Unit = { imap = imap.empty }
 
-  override def transform(f: (A, B) => B): Unit = { imap = imap.transform(f) }
+  override def transform(f: (A, B) => B): this.type = { imap = imap.transform(f); this }
 
-  override def retain(p: (A, B) => Boolean): Unit = { 
+  override def retain(p: (A, B) => Boolean): this.type = { 
     imap = imap.filter(xy => p(xy._1, xy._2))
+    this
   }
 
   override def toString() = imap.toString()
 }
+
diff --git a/src/library/scala/collection/mutable/ImmutableSetAdaptor.scala b/src/library/scala/collection/mutable/ImmutableSetAdaptor.scala
index 375fafe..4560d01 100644
--- a/src/library/scala/collection/mutable/ImmutableSetAdaptor.scala
+++ b/src/library/scala/collection/mutable/ImmutableSetAdaptor.scala
@@ -1,36 +1,37 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: ImmutableSetAdaptor.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.collection.mutable
+package scala.collection
+package mutable
 
 
 /** This class can be used as an adaptor to create mutable sets from
- *  immutable set implementations. Only method <code>empty</code> has
+ *  immutable set implementations. Only method `empty` has
  *  to be redefined if the immutable set on which this mutable set is
- *  originally based is not empty. <code>empty</code> is supposed to
+ *  originally based is not empty. `empty` is supposed to
  *  return the representation of an empty set.
  *
  *  @author  Matthias Zenger
  *  @version 1.0, 21/07/2003
+ *  @since   1
  */
 @serializable
 class ImmutableSetAdaptor[A](protected var set: immutable.Set[A]) extends Set[A] {
 
-  def size: Int = set.size
+  override def size: Int = set.size
 
   override def isEmpty: Boolean = set.isEmpty
 
   def contains(elem: A): Boolean = set.contains(elem)
 
-  override def foreach(f: A => Unit): Unit = set.foreach(f)
+  override def foreach[U](f: A =>  U): Unit = set.foreach(f)
 
   override def exists(p: A => Boolean): Boolean = set.exists(p)
 
@@ -38,12 +39,15 @@ class ImmutableSetAdaptor[A](protected var set: immutable.Set[A]) extends Set[A]
 
   override def toString = set.toString
 
-  def elements: Iterator[A] = set.elements
+  def iterator: Iterator[A] = set.iterator
 
-  def +=(elem: A): Unit = { set = set + elem }
+  @deprecated("use `iterator' instead") override def elements: Iterator[A] = iterator
 
-  def -=(elem: A): Unit = { set = set - elem }
+  def +=(elem: A): this.type = { set = set + elem; this }
+
+  def -=(elem: A): this.type = { set = set - elem; this }
 
   override def clear(): Unit = { set = set.empty }
 
 }
+
diff --git a/src/library/scala/collection/mutable/IndexedSeq.scala b/src/library/scala/collection/mutable/IndexedSeq.scala
new file mode 100644
index 0000000..128f411
--- /dev/null
+++ b/src/library/scala/collection/mutable/IndexedSeq.scala
@@ -0,0 +1,36 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+package mutable
+
+import generic._
+
+/** A subtrait of `collection.IndexedSeq` which represents sequences
+ *  that can be mutated.
+ *  
+ *  $indexedSeqInfo
+ */
+trait IndexedSeq[A] extends Seq[A] 
+                   with scala.collection.IndexedSeq[A] 
+                   with GenericTraversableTemplate[A, IndexedSeq]
+                   with IndexedSeqLike[A, IndexedSeq[A]] {
+  override def companion: GenericCompanion[IndexedSeq]  = IndexedSeq
+}
+
+/** $factoryInfo
+ *  The current default implementation of a $Coll is an `ArrayBuffer`.
+ *  @define coll mutable indexed sequence
+ *  @define Coll mutable.IndexedSeq
+ */
+object IndexedSeq extends SeqFactory[IndexedSeq] {
+  implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, IndexedSeq[A]] = new GenericCanBuildFrom[A]
+  def newBuilder[A]: Builder[A, IndexedSeq[A]] = new ArrayBuffer[A]
+}
diff --git a/src/library/scala/collection/mutable/IndexedSeqLike.scala b/src/library/scala/collection/mutable/IndexedSeqLike.scala
new file mode 100644
index 0000000..917bc37
--- /dev/null
+++ b/src/library/scala/collection/mutable/IndexedSeqLike.scala
@@ -0,0 +1,73 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+package mutable
+import generic._
+
+/** A subtrait of scala.collection.IndexedSeq which represents sequences
+ *  that can be mutated.
+ *  
+ *  It declares a method `update` which allows updating an element
+ *  at a specific index in the sequence.
+ *
+ *  This trait just implements `iterator` in terms of `apply` and `length`.
+ *  However, see `IndexedSeqOptimized` for an implementation trait that overrides operations
+ *  to make them run faster under the assumption of fast random access with `apply`. 
+ *
+ *  $indexedSeqInfo
+ *  
+ *  @tparam A    the element type of the $coll
+ *  @tparam Repr the type of the actual $coll containing the elements.
+ *
+ *  @define Coll IndexedSeq
+ *  @define coll mutable indexed sequence
+ *  @define indexedSeqInfo
+ *  @author Martin Odersky
+ *  @version 2.8
+ *  @since   2.8
+ *  @define willNotTerminateInf
+ *  @define mayNotTerminateInf
+ */
+trait IndexedSeqLike[A, +Repr] extends scala.collection.IndexedSeqLike[A, Repr] { self =>
+
+  override protected[this] def thisCollection: IndexedSeq[A] = this.asInstanceOf[IndexedSeq[A]]
+  override protected[this] def toCollection(repr: Repr): IndexedSeq[A] = repr.asInstanceOf[IndexedSeq[A]]
+
+  /** Replaces element at given index with a new value.
+   *
+   *  @param n       the index of the element to replace.
+   *  @param elem    the new value.
+   *  @throws   IndexOutofBoundsException if the index is not valid.
+   */
+  def update(idx: Int, elem: A)
+
+  /** Creates a view of this iterable @see Iterable.View
+   */
+  override def view = new IndexedSeqView[A, Repr] { 
+    protected lazy val underlying = self.repr
+    override def iterator = self.iterator
+    override def length = self.length
+    override def apply(idx: Int) = self.apply(idx)
+    override def update(idx: Int, elem: A) = self.update(idx, elem)
+  }
+
+  /** A sub-sequence view  starting at index `from`
+   *  and extending up to (but not including) index `until`.
+   *
+   *  @param from   The index of the first element of the slice
+   *  @param until  The index of the element following the slice
+   *  @note  The difference between `view` and `slice` is that `view` produces
+   *         a view of the current sequence, whereas `slice` produces a new sequence.
+   *
+   *  @note view(from, to)  is equivalent to view.slice(from, to)
+   */ 
+  override def view(from: Int, until: Int) = view.slice(from, until)
+}
diff --git a/src/library/scala/collection/mutable/IndexedSeqOptimized.scala b/src/library/scala/collection/mutable/IndexedSeqOptimized.scala
new file mode 100644
index 0000000..472193e
--- /dev/null
+++ b/src/library/scala/collection/mutable/IndexedSeqOptimized.scala
@@ -0,0 +1,20 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+package mutable
+import generic._
+
+/** A subtrait of scala.collection.IndexedSeq which represents sequences
+ *  that can be mutated.
+ *
+ *  @since 2.8
+ */
+trait IndexedSeqOptimized[A, +Repr] extends IndexedSeqLike[A, Repr] with scala.collection.IndexedSeqOptimized[A, Repr] 
diff --git a/src/library/scala/collection/mutable/IndexedSeqView.scala b/src/library/scala/collection/mutable/IndexedSeqView.scala
new file mode 100644
index 0000000..ef3fb25
--- /dev/null
+++ b/src/library/scala/collection/mutable/IndexedSeqView.scala
@@ -0,0 +1,115 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+package mutable 
+
+import generic._
+
+import TraversableView.NoBuilder
+
+/** A non-strict view of a mutable `IndexedSeq`.
+ *  $viewinfo
+ *  Some of the operations of this class will yield again a mutable indexed sequence,
+ *  others will just yield a plain indexed sequence of type `collection.IndexedSeq`.
+ *  Because this is a leaf class there is no associated `Like' class.
+ *  @author Martin Odersky
+ *  @version 2.8
+ *  @since   2.8
+ *  @tparam A    the element type of the view
+ *  @tparam Coll the type of the underlying collection containing the elements.
+ */
+trait IndexedSeqView[A, +Coll] extends IndexedSeq[A] 
+                                  with IndexedSeqOptimized[A, IndexedSeqView[A, Coll]] 
+                                  with scala.collection.SeqView[A, Coll] 
+                                  with scala.collection.SeqViewLike[A, Coll, IndexedSeqView[A, Coll]] {
+self =>
+
+  def update(idx: Int, elem: A)
+
+  trait Transformed[B] extends IndexedSeqView[B, Coll] with super.Transformed[B] {
+    def update(idx: Int, elem: B)
+  }
+
+  trait Sliced extends Transformed[A] with super.Sliced {
+    override def update(idx: Int, elem: A) = 
+      if (idx + from < until) self.update(idx + from, elem)
+      else throw new IndexOutOfBoundsException(idx.toString)
+    override def slice(from1: Int, until1: Int): Transformed[A] = 
+      newSliced(from1 max 0, until1 max 0)
+  }
+
+  trait Filtered extends Transformed[A] with super.Filtered {
+    override def update(idx: Int, elem: A) = self.update(index(idx), elem)
+  }
+    
+  trait TakenWhile extends Transformed[A] with super.TakenWhile {
+    override def update(idx: Int, elem: A) =
+      if (idx < len) self.update(idx, elem)
+      else throw new IndexOutOfBoundsException(idx.toString)
+  }
+
+  trait DroppedWhile extends Transformed[A] with super.DroppedWhile {
+    override def update(idx: Int, elem: A) =
+      if (idx >= 0) self.update(idx + start, elem)
+      else throw new IndexOutOfBoundsException(idx.toString)
+  }
+
+  trait Reversed extends Transformed[A] with super.Reversed {
+    override def update(idx: Int, elem: A) = self.update(length - 1 - idx, elem)
+  }
+
+  /** Boilerplate method, to override in each subclass
+   *  This method could be eliminated if Scala had virtual classes
+   */
+  protected override def newFiltered(p: A => Boolean): Transformed[A] = new Filtered { val pred = p }
+  protected override def newSliced(_from: Int, _until: Int): Transformed[A] = new Sliced { val from = _from; val until = _until }
+  protected override def newDroppedWhile(p: A => Boolean): Transformed[A] = new DroppedWhile { val pred = p }
+  protected override def newTakenWhile(p: A => Boolean): Transformed[A] = new TakenWhile { val pred = p }
+  protected override def newReversed: Transformed[A] = new Reversed { }
+
+  // Todo: if we replace IndexedSeqView[A, Coll] below by
+  // private[this] type This = IndexedSeqView[A, Coll]
+  // The interpreter will display resX.This.
+  // It shouldn't.
+
+  override def filter(p: A => Boolean): IndexedSeqView[A, Coll] = newFiltered(p)
+  override def init: IndexedSeqView[A, Coll]  = newSliced(0, size - 1).asInstanceOf[IndexedSeqView[A, Coll]]
+  override def drop(n: Int): IndexedSeqView[A, Coll] = newSliced(n max 0, Int.MaxValue).asInstanceOf[IndexedSeqView[A, Coll]]
+  override def take(n: Int): IndexedSeqView[A, Coll] = newSliced(0, n).asInstanceOf[IndexedSeqView[A, Coll]]
+  override def slice(from: Int, until: Int): IndexedSeqView[A, Coll] = newSliced(from max 0, until).asInstanceOf[IndexedSeqView[A, Coll]]
+  override def dropWhile(p: A => Boolean): IndexedSeqView[A, Coll] = newDroppedWhile(p).asInstanceOf[IndexedSeqView[A, Coll]]
+  override def takeWhile(p: A => Boolean): IndexedSeqView[A, Coll] = newTakenWhile(p).asInstanceOf[IndexedSeqView[A, Coll]]
+  override def span(p: A => Boolean): (IndexedSeqView[A, Coll], IndexedSeqView[A, Coll]) = (takeWhile(p), dropWhile(p))
+  override def splitAt(n: Int): (IndexedSeqView[A, Coll], IndexedSeqView[A, Coll]) = (take(n), drop(n))
+  override def reverse: IndexedSeqView[A, Coll] = newReversed.asInstanceOf[IndexedSeqView[A, Coll]]
+}
+
+/** An object containing the necessary implicit definitions to make
+ *  `SeqView`s work. Its definitions are generally not accessed directly by clients.
+ * 
+ * Note that the `canBuildFrom` factories yield `SeqView`s, not `IndexedSewqView`s.
+ * This is intentional, because not all operations yield again a `mutable.IndexedSeqView`.
+ * For instance, `map` just gives a `SeqView`, which reflects the fact that
+ * `map` cannot do its work and maintain a pointer into the original indexed sequence.
+ */
+object IndexedSeqView {
+  type Coll = TraversableView[_, C] forSome {type C <: Traversable[_]}
+  implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, SeqView[A, Seq[_]]] = 
+    new CanBuildFrom[Coll, A, SeqView[A, Seq[_]]] { 
+      def apply(from: Coll) = new NoBuilder 
+      def apply() = new NoBuilder 
+    }
+  implicit def arrCanBuildFrom[A]: CanBuildFrom[TraversableView[_, Array[_]], A, SeqView[A, Array[A]]] = 
+    new CanBuildFrom[TraversableView[_, Array[_]], A, SeqView[A, Array[A]]] { 
+      def apply(from: TraversableView[_, Array[_]]) = new NoBuilder 
+      def apply() = new NoBuilder 
+    }
+}
diff --git a/src/library/scala/collection/mutable/Iterable.scala b/src/library/scala/collection/mutable/Iterable.scala
new file mode 100644
index 0000000..b8c403e
--- /dev/null
+++ b/src/library/scala/collection/mutable/Iterable.scala
@@ -0,0 +1,32 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+package scala.collection
+package mutable
+
+import generic._
+
+/** A base trait for iterable collections that can be mutated.
+ *  $iterableInfo
+ */
+trait Iterable[A] extends Traversable[A] 
+                     with scala.collection.Iterable[A] 
+                     with GenericTraversableTemplate[A, Iterable]
+                     with IterableLike[A, Iterable[A]] { 
+  override def companion: GenericCompanion[Iterable] = Iterable
+}	
+
+/** $factoryInfo
+ *  The current default implementation of a $Coll is an `ArrayBuffer`.
+ *  @define coll mutable iterable collection
+ *  @define Coll mutable.Iterable
+ */
+object Iterable extends TraversableFactory[Iterable] {
+  implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, Iterable[A]] = new GenericCanBuildFrom[A]
+  def newBuilder[A]: Builder[A, Iterable[A]] = new ArrayBuffer
+}
+
diff --git a/src/library/scala/collection/mutable/JavaMapAdaptor.scala b/src/library/scala/collection/mutable/JavaMapAdaptor.scala
deleted file mode 100644
index 1dc6603..0000000
--- a/src/library/scala/collection/mutable/JavaMapAdaptor.scala
+++ /dev/null
@@ -1,69 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: JavaMapAdaptor.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala.collection.mutable
-
-
-/** This class can be used as an adaptor to create mutable maps from
- *  Java classes that implementat the <code>java.util.Map</code> interface.
- *
- *  @author  Matthias Zenger
- *  @version 1.0, 21/07/2003
- *  @deprecated Use <code>scala.collection.jcl.Map(jmap)</code> instead
- */
- at deprecated class JavaMapAdaptor[A, B](jmap: java.util.Map[A, B]) extends Map[A, B] {
-
-  def size: Int = jmap.size()
-
-  def get(key: A): Option[B] =
-    if (jmap.containsKey(key)) Some(jmap.get(key).asInstanceOf[B]) else None
-
-  override def isEmpty: Boolean = jmap.isEmpty()
-
-  override def apply(key: A): B = jmap.get(key).asInstanceOf[B]
-
-  override def contains(key: A): Boolean = jmap.containsKey(key)
-
-  override def isDefinedAt(key: A) = jmap.containsKey(key)
-
-  override def keys: Iterator[A] = new Iterator[A] {
-    val iter = jmap.keySet().iterator()
-    def hasNext = iter.hasNext()
-    def next = iter.next().asInstanceOf[A]
-  }
-
-  override def values: Iterator[B] = new Iterator[B] {
-    val iter = jmap.values().iterator()
-    def hasNext = iter.hasNext()
-    def next = iter.next().asInstanceOf[B]
-  }
-
-  def elements: Iterator[(A, B)] = new Iterator[(A, B)] {
-    val iter = jmap.keySet().iterator()
-    def hasNext = iter.hasNext()
-    def next = {
-      val key = iter.next().asInstanceOf[A]
-      (key, apply(key))
-    }
-  }
-
-  def update(key: A, value: B): Unit = { val x = jmap.put(key, value); }
-
-  def -= (key: A): Unit = { val x = jmap.remove(key); }
-
-  override def clear(): Unit = jmap.clear()
-
-  override def clone(): Map[A, B] = {
-    val res = new HashMap[A, B]
-    res ++= this
-    res
-  }
-}
diff --git a/src/library/scala/collection/mutable/JavaSetAdaptor.scala b/src/library/scala/collection/mutable/JavaSetAdaptor.scala
deleted file mode 100644
index d9d40a6..0000000
--- a/src/library/scala/collection/mutable/JavaSetAdaptor.scala
+++ /dev/null
@@ -1,47 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: JavaSetAdaptor.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala.collection.mutable
-
-
-/** This class can be used as an adaptor to create mutable sets from
- *  Java classes that implement interface <code>java.util.Set</code>.
- *
- *  @author  Matthias Zenger
- *  @version 1.0, 19/09/2003
- *  @deprecated Use <code>scala.collection.jcl.Set(jmap)</code> instead
- */
- at deprecated class JavaSetAdaptor[A](jset: java.util.Set[A]) extends Set[A] {
-
-  def size: Int = jset.size()
-
-  override def isEmpty: Boolean = jset.isEmpty()
-
-  def contains(elem: A): Boolean = jset.contains(elem)
-
-  def elements: Iterator[A] = new Iterator[A] {
-    val iter = jset.iterator()
-    def hasNext = iter.hasNext()
-    def next = iter.next().asInstanceOf[A]
-  }
-
-  def +=(elem: A): Unit = { val x = jset.add(elem); }
-
-  def -=(elem: A): Unit = { val x = jset.remove(elem); }
-
-  override def clear(): Unit = jset.clear()
-
-  override def clone(): Set[A] = {
-    val res = new HashSet[A]
-    res ++= this
-    res
-  }
-}
diff --git a/src/library/scala/collection/mutable/LazyBuilder.scala b/src/library/scala/collection/mutable/LazyBuilder.scala
new file mode 100644
index 0000000..0e1eeeb
--- /dev/null
+++ b/src/library/scala/collection/mutable/LazyBuilder.scala
@@ -0,0 +1,30 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+package scala.collection
+package mutable
+
+import immutable.{List, Nil}
+
+/** A builder that constructs its result lazily. Iterators or iterables to 
+ *  be added to this builder with `++=` are not evaluated until `result` is called.
+ *  
+ *  @since 2.8
+ *  
+ *  @tparam Elem    type of the elements for this builder.
+ *  @tparam To      type of the collection this builder builds.
+ */
+abstract class LazyBuilder[Elem, +To] extends Builder[Elem, To] {
+  /** The different segments of elements to be added to the builder, represented as iterators */
+  protected var parts = new ListBuffer[TraversableOnce[Elem]]
+  def +=(x: Elem): this.type = { parts += List(x); this }
+  override def ++=(xs: TraversableOnce[Elem]): this.type = { parts += xs ; this }
+  def result(): To
+  def clear() { parts.clear() } 
+}
diff --git a/src/library/scala/collection/mutable/LinearSeq.scala b/src/library/scala/collection/mutable/LinearSeq.scala
new file mode 100644
index 0000000..a9172bd
--- /dev/null
+++ b/src/library/scala/collection/mutable/LinearSeq.scala
@@ -0,0 +1,38 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+package mutable
+
+import generic._
+
+/** A subtrait of `collection.LinearSeq` which represents sequences
+ *  that can be mutated.
+ *  $linearSeqInfo
+ *  
+ *  @define Coll LinearSeq
+ *  @define coll linear sequence
+ */
+trait LinearSeq[A] extends Seq[A] 
+                           with scala.collection.LinearSeq[A] 
+                           with GenericTraversableTemplate[A, LinearSeq]
+                           with LinearSeqLike[A, LinearSeq[A]] {
+  override def companion: GenericCompanion[LinearSeq] = LinearSeq
+}
+
+/** $factoryInfo
+ *  The current default implementation of a $Coll is a `MutableList`.
+ *  @define coll mutable linear sequence
+ *  @define Coll mutable.LinearSeq
+ */
+object LinearSeq extends SeqFactory[LinearSeq] {
+  implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, LinearSeq[A]] = new GenericCanBuildFrom[A]
+  def newBuilder[A]: Builder[A, LinearSeq[A]] = new MutableList[A]
+}
diff --git a/src/library/scala/collection/mutable/LinkedEntry.scala b/src/library/scala/collection/mutable/LinkedEntry.scala
new file mode 100644
index 0000000..667d45b
--- /dev/null
+++ b/src/library/scala/collection/mutable/LinkedEntry.scala
@@ -0,0 +1,23 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+package mutable
+
+/** Class for the linked hash map entry, used internally.
+ *  @since 2.8
+ */
+ at serializable
+final class LinkedEntry[A, B](val key: A, var value: B)
+      extends HashEntry[A, LinkedEntry[A, B]] {
+  var earlier: LinkedEntry[A, B] = null
+  var later: LinkedEntry[A, B] = null
+}
+
diff --git a/src/library/scala/collection/mutable/LinkedHashMap.scala b/src/library/scala/collection/mutable/LinkedHashMap.scala
index 7a66384..669599e 100644
--- a/src/library/scala/collection/mutable/LinkedHashMap.scala
+++ b/src/library/scala/collection/mutable/LinkedHashMap.scala
@@ -1,68 +1,149 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: LinkedHashMap.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.collection.mutable
+package scala.collection
+package mutable
 
-import Predef._
+import generic._
 
-/** This class implements mutable maps using a hashtable.
- *
- *  @author  Matthias Zenger
- *  @author  Martin Odersky
- *  @version 2.0, 31/12/2006
+/** $factoryInfo
+ *  @define Coll LinkedHashMap
+ *  @define coll linked hash map
  */
-object LinkedHashMap {
-
-  /** The empty map of this type */  
+object LinkedHashMap extends MutableMapFactory[LinkedHashMap] {
+  implicit def canBuildFrom[A, B]: CanBuildFrom[Coll, (A, B), LinkedHashMap[A, B]] = new MapCanBuildFrom[A, B]
   def empty[A, B] = new LinkedHashMap[A, B]
-
-  /** The canonical factory for this type
-   */
-  def apply[A, B](elems: (A, B)*) = empty[A, B] ++ elems
 }
 
- at serializable
-class LinkedHashMap[A, B] extends Map[A,B] with HashTable[A] with DefaultMapModel[A,B] {
-  private var ordered = List[Entry]()
+/** This class implements mutable maps using a hashtable.
+ *  The iterator and all traversal methods of this class visit elements in the order they were inserted.
+ *  
+ *  @tparam A    the type of the keys contained in this hash map.
+ *  @tparam B    the type of the values assigned to keys in this hash map.
+ *  
+ *  @define Coll LinkedHashMap
+ *  @define coll linked hash map
+ *  @define thatinfo the class of the returned collection. In the standard library configuration,
+ *    `That` is always `LinkedHashMap[A, B]` if the elements contained in the resulting collection are 
+ *    pairs of type `(A, B)`. This is because an implicit of type `CanBuildFrom[LinkedHashMap, (A, B), LinkedHashMap[A, B]]`
+ *    is defined in object `LinkedHashMap`. Otherwise, `That` resolves to the most specific type that doesn't have
+ *    to contain pairs of type `(A, B)`, which is `Iterable`.
+ *  @define $bfinfo an implicit value of class `CanBuildFrom` which determines the
+ *    result class `That` from the current representation type `Repr`
+ *    and the new element type `B`. This is usually the `canBuildFrom` value
+ *    defined in object `LinkedHashMap`.
+ *  @define mayNotTerminateInf
+ *  @define willNotTerminateInf
+ *  @define orderDependent
+ *  @define orderDependentFold
+ */
+ at serializable @SerialVersionUID(1L)
+class LinkedHashMap[A, B] extends Map[A, B] 
+                             with MapLike[A, B, LinkedHashMap[A, B]] 
+                             with HashTable[A] {
+
+  override def empty = LinkedHashMap.empty[A, B]
+  override def size = tableSize
 
-  def remove(key: A): Option[B] = removeEntry(key) match {
-    case None => None
-    case Some(e) => 
-      ordered = ordered.filter(_ ne e)
-      Some(e.value)
-    }
+  type Entry = LinkedEntry[A, B]
 
-  def -= (key: A) { remove(key) }
+  @transient protected var firstEntry: Entry = null 
+  @transient protected var lastEntry: Entry = null 
+
+  def get(key: A): Option[B] = {
+    val e = findEntry(key)
+    if (e == null) None
+    else Some(e.value)
+  }
 
   override def put(key: A, value: B): Option[B] = {
     val e = findEntry(key)
-    if (e == null) {
+    if (e == null) { 
       val e = new Entry(key, value)
-      ordered = e :: ordered
       addEntry(e)
-      None
-    } else {
-      val ret = Some(e.value)
+      updateLinkedEntries(e)
+      None 
+    } else { 
+      val v = e.value
       e.value = value
-      ret
+      Some(v) 
     }
   }
-  override def update(key: A, value: B) { put(key, value) }
 
-  override def clear() {
-    ordered = Nil
-    super.clear()
+  private def updateLinkedEntries(e: Entry) {
+    if (firstEntry == null) firstEntry = e
+    else { lastEntry.later = e; e.earlier = lastEntry }
+    lastEntry = e
   }
 
-  override def clone(): Map[A, B] = new LinkedHashMap[A, B] ++ this
+  override def remove(key: A): Option[B] = {
+    val e = removeEntry(key)
+    if (e eq null) None
+    else {
+      if (e.earlier eq null) firstEntry = e.later
+      else e.earlier.later = e.later
+      if (e.later eq null) lastEntry = e.earlier
+      else e.later.earlier = e.earlier
+      Some(e.value)
+    }
+  }
 
-  override def elements = ordered.reverse.elements map {e => (e.key, e.value)}
+  def += (kv: (A, B)): this.type = { put(kv._1, kv._2); this }
+  def -=(key: A): this.type = { remove(key); this }
+
+  def iterator: Iterator[(A, B)] = new Iterator[(A, B)] {
+    private var cur = firstEntry
+    def hasNext = cur ne null
+    def next = 
+      if (hasNext) { val res = (cur.key, cur.value); cur = cur.later; res }
+      else Iterator.empty.next
+  }
+
+  override def keysIterator: Iterator[A] = new Iterator[A] {
+    private var cur = firstEntry
+    def hasNext = cur ne null
+    def next = 
+      if (hasNext) { val res = cur.key; cur = cur.later; res }
+      else Iterator.empty.next
+  }
+
+  override def valuesIterator: Iterator[B] = new Iterator[B] {
+    private var cur = firstEntry
+    def hasNext = cur ne null
+    def next = 
+      if (hasNext) { val res = cur.value; cur = cur.later; res }
+      else Iterator.empty.next
+  }
+
+  override def foreach[U](f: ((A, B)) => U) = {
+    var cur = firstEntry
+    while (cur ne null) {
+      f((cur.key, cur.value))
+      cur = cur.later
+    }
+  }
+
+  override def clear() {
+    clearTable()
+    firstEntry = null
+  }
+  
+  private def writeObject(out: java.io.ObjectOutputStream) {
+    serializeTo(out, _.value)
+  }
+  
+  private def readObject(in: java.io.ObjectInputStream) {
+    init[B](in, { (key, value) =>
+      val entry = new Entry(key, value)
+      updateLinkedEntries(entry)
+      entry
+    })
+  }
 }
diff --git a/src/library/scala/collection/mutable/LinkedHashSet.scala b/src/library/scala/collection/mutable/LinkedHashSet.scala
index 5702972..4e1d2aa 100644
--- a/src/library/scala/collection/mutable/LinkedHashSet.scala
+++ b/src/library/scala/collection/mutable/LinkedHashSet.scala
@@ -1,49 +1,93 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2005-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2005-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: LinkedHashSet.scala 16881 2009-01-09 16:28:11Z cunei $
 
-package scala.collection.mutable
+package scala.collection
+package mutable
 
+import generic._
 
-object LinkedHashSet {
-  /** The empty map of this type */  
-  def empty[A] = new LinkedHashSet[A]
+/** This class implements mutable sets using a hashtable.
+ *  The iterator and all traversal methods of this class visit elements in the order they were inserted.
+ *
+ *  @author  Matthias Zenger
+ *  @author  Martin Odersky
+ *  @version 2.0, 31/12/2006
+ *  @since   1
+ *  
+ *  @tparam A     the type of the elements contained in this set.
+ *  
+ *  @define Coll LinkedHashSet
+ *  @define coll linked hash set
+ *  @define thatinfo the class of the returned collection. In the standard library configuration,
+ *    `That` is always `LinkedHashSet[B]` because an implicit of type `CanBuildFrom[LinkedHashSet, B, LinkedHashSet[B]]`
+ *    is defined in object `LinkedHashSet`.
+ *  @define $bfinfo an implicit value of class `CanBuildFrom` which determines the
+ *    result class `That` from the current representation type `Repr`
+ *    and the new element type `B`. This is usually the `canBuildFrom` value
+ *    defined in object `LinkedHashSet`.
+ *  @define mayNotTerminateInf
+ *  @define willNotTerminateInf
+ *  @define orderDependent
+ *  @define orderDependentFold
+ */
+ at serializable @SerialVersionUID(1L)
+class LinkedHashSet[A] extends Set[A] 
+                          with GenericSetTemplate[A, LinkedHashSet]
+                          with SetLike[A, LinkedHashSet[A]] 
+                          with FlatHashTable[A] 
+{
+  override def companion: GenericCompanion[LinkedHashSet] = LinkedHashSet
 
-  /** The canonical factory for this type
-   */
-  def apply[A](elems: A*) = empty[A] ++ elems
-}
+  @transient private[this] var ordered = new ListBuffer[A]
 
- at serializable
-class LinkedHashSet[A] extends Set[A] with FlatHashTable[A] {
-  private var ordered = List[A]()
+  override def size = tableSize
 
   def contains(elem: A): Boolean = containsEntry(elem)
 
-  def +=(elem: A) { add(elem) }
+  def += (elem: A): this.type = { add(elem); this }
+  def -= (elem: A): this.type = { remove(elem); this }
+
+  override def add(elem: A): Boolean =
+    if (addEntry(elem)) { ordered += elem; true }
+    else false
+  
+  override def remove(elem: A): Boolean = 
+    removeEntry(elem) match {
+      case None => false
+      case _ => ordered -= elem; true
+    }
   
-  def add(elem: A): Boolean = {
-    if (addEntry(elem)) {
-      ordered = elem :: ordered
-      true
-    } else false
+  override def clear() {
+    ordered.clear()
+    clearTable()
   }
-  def -=(elem: A) { remove(elem) }
-  def remove(elem: A) : Boolean = removeEntry(elem) match {
-    case None => false
-    case Some(elem) => ordered = ordered.filter(_ != elem); true
+
+  override def iterator: Iterator[A] = ordered.iterator
+
+  override def foreach[U](f: A => U) = ordered foreach f
+  
+  private def writeObject(s: java.io.ObjectOutputStream) {
+    serializeTo(s)
   }
   
-  override def clear() {
-    ordered = Nil
-    super.clear()
+  private def readObject(in: java.io.ObjectInputStream) {
+    ordered = new ListBuffer[A]
+    init(in, ordered += )
   }
-  override def clone(): Set[A] = new LinkedHashSet[A] ++ this
-  override def elements = ordered.reverse.elements
 }
+
+/** $factoryInfo
+ *  @define Coll LinkedHashSet
+ *  @define coll linked hash set
+ */
+object LinkedHashSet extends MutableSetFactory[LinkedHashSet] {
+  implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, LinkedHashSet[A]] = setCanBuildFrom[A]
+  override def empty[A]: LinkedHashSet[A] = new LinkedHashSet[A]
+}
+
diff --git a/src/library/scala/collection/mutable/LinkedList.scala b/src/library/scala/collection/mutable/LinkedList.scala
index f545b4e..6e0dd24 100644
--- a/src/library/scala/collection/mutable/LinkedList.scala
+++ b/src/library/scala/collection/mutable/LinkedList.scala
@@ -1,47 +1,68 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: LinkedList.scala 16881 2009-01-09 16:28:11Z cunei $
 
 
-package scala.collection.mutable
+package scala.collection
+package mutable
 
-/** This class implements single linked lists where both the head (<code>elem</code>)
- *  and the tail (<code>next</code>) are mutable.
- *
- *  @author  Matthias Zenger
- *  @version 1.0, 08/07/2003
+import generic._
+
+/** This class implements single linked lists where both the head (`elem`)
+ *  and the tail (`next`) are mutable.
+ *  
+ *  @author Matthias Zenger
+ *  @author Martin Odersky
+ *  @version 2.8
+ *  @since   1
+ *  
+ *  @tparam A     the type of the elements contained in this linked list.
+ *  
+ *  @define Coll LinkedList
+ *  @define coll linked list
+ *  @define thatinfo the class of the returned collection. In the standard library configuration,
+ *    `That` is always `LinkedList[B]` because an implicit of type `CanBuildFrom[LinkedList, B, LinkedList[B]]`
+ *    is defined in object `LinkedList`.
+ *  @define $bfinfo an implicit value of class `CanBuildFrom` which determines the
+ *    result class `That` from the current representation type `Repr`
+ *    and the new element type `B`. This is usually the `canBuildFrom` value
+ *    defined in object `LinkedList`.
+ *  @define orderDependent 
+ *  @define orderDependentFold
+ *  @define mayNotTerminateInf
+ *  @define willNotTerminateInf
  */
- at serializable
-class LinkedList[A](var elem: A, var next: LinkedList[A])
-  extends SingleLinkedList[A, LinkedList[A]]
-{
-
-  /** Compares two lists structurally; i.e. checks if all elements
-   *  contained in this list are also contained in the other list,
-   *  and vice versa.
-   *
-   *  @param that the other list
-   *  @return     <code>true</code> iff both lists contain exactly the
-   *              same mappings.
-   */
-  override def equals(obj: Any): Boolean = obj match {
-    case that: LinkedList[_] => this.toList equals that.toList
-    case _ => false
-  }
+ at serializable @SerialVersionUID(-7308240733518833071L)
+class LinkedList[A]() extends LinearSeq[A] 
+                         with GenericTraversableTemplate[A, LinkedList]
+                         with LinkedListLike[A, LinkedList[A]] {
+  next = this
 
-  /** A hash method compatible with <code>equals</code> 
-   */
-  override def hashCode(): Int =
-    (0 /: elements) ((hash, kv) => hash + kv.hashCode)
+  def this(elem: A, next: LinkedList[A]) {
+    this()
+    if (next != null) {
+      this.elem = elem
+      this.next = next
+    }
+  }
 
-  override protected def stringPrefix: String = "LinkedList"
+  override def companion: GenericCompanion[LinkedList] = LinkedList
 }
 
+/** $factoryInfo
+ *  @define Coll LinkedList
+ *  @define coll linked list
+ */
+object LinkedList extends SeqFactory[LinkedList] {
 
+  override def empty[A]: LinkedList[A] = new LinkedList[A]
 
+  implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, LinkedList[A]] = new GenericCanBuildFrom[A]
+  def newBuilder[A]: Builder[A, LinkedList[A]] =
+    (new MutableList) mapResult ((l: MutableList[A]) => l.toLinkedList)
+}
diff --git a/src/library/scala/collection/mutable/LinkedListLike.scala b/src/library/scala/collection/mutable/LinkedListLike.scala
new file mode 100644
index 0000000..491e75f
--- /dev/null
+++ b/src/library/scala/collection/mutable/LinkedListLike.scala
@@ -0,0 +1,115 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |                                         **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+package mutable
+
+import generic._
+import annotation.tailrec
+
+/** This extensible class may be used as a basis for implementing linked
+ *  list. Type variable `A` refers to the element type of the
+ *  list, type variable `This` is used to model self types of
+ *  linked lists.
+ *
+ *  @author  Matthias Zenger
+ *  @author  Martin Odersky
+ *  @version 1.0, 08/07/2003
+ *  @since   2.8
+ *  
+ *  @tparam A    type of the elements contained in the linked list
+ *  @tparam This the type of the actual linked list holding the elements
+ *  
+ *  @define Coll LinkedList
+ *  @define coll linked list
+ */
+trait LinkedListLike[A, This <: Seq[A] with LinkedListLike[A, This]] extends SeqLike[A, This] { self =>
+  
+  var elem: A = _
+  var next: This = _
+
+  override def isEmpty = next eq this
+
+  override def length: Int = if (isEmpty) 0 else next.length + 1
+
+  override def head: A    = elem
+
+  override def tail: This = {
+    require(nonEmpty, "tail of empty list")
+    next
+  }
+
+  /** Append linked list `that` at current position of this linked list
+   *  @return the list after append (this is the list itself if nonempty,
+   *  or list `that` if list this is empty. )
+   */
+  def append(that: This): This = {
+    @tailrec
+    def loop(x: This) {
+      if (x.next.isEmpty) x.next = that
+      else loop(x.next)
+    }
+    if (isEmpty) that
+    else { loop(repr); repr }
+  }
+
+  /** Insert linked list `that` at current position of this linked list
+   *  @note this linked list must not be empty
+   */
+  def insert(that: This): Unit = {
+    require(nonEmpty, "insert into empty list")
+    if (that.nonEmpty) {
+      next = next.append(that)
+    }
+  }
+
+  override def drop(n: Int): This = {
+    var i = 0
+    var these: This = repr
+    while (i < n && !these.isEmpty) {
+      these = these.next.asInstanceOf[This] // !!! concrete overrides abstract problem
+      i += 1
+    }
+    these
+  }
+
+  private def atLocation[T](n: Int)(f: This => T) = {
+    val loc = drop(n)
+    if (!loc.isEmpty) f(loc)
+    else throw new IndexOutOfBoundsException(n.toString)
+  }
+
+  override def apply(n: Int): A   = atLocation(n)(_.elem)
+  def update(n: Int, x: A): Unit  = atLocation(n)(_.elem = x)
+
+  def get(n: Int): Option[A] = {
+    val loc = drop(n)
+    if (loc.nonEmpty) Some(loc.elem)
+    else None
+  }
+
+  override def iterator: Iterator[A] = new Iterator[A] {
+    var elems = self
+    def hasNext = elems.nonEmpty
+    def next = {
+      val res = elems.elem
+      elems = elems.next
+      res
+    }
+  }
+
+  override def foreach[B](f: A => B) {
+    var these = this
+    while (these.nonEmpty) {
+      f(these.elem)
+      these = these.next
+    }
+  }
+}
diff --git a/src/library/scala/collection/mutable/ListBuffer.scala b/src/library/scala/collection/mutable/ListBuffer.scala
index f6c19f2..166a5c0 100644
--- a/src/library/scala/collection/mutable/ListBuffer.scala
+++ b/src/library/scala/collection/mutable/ListBuffer.scala
@@ -1,169 +1,90 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: ListBuffer.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.collection.mutable
+package scala.collection
+package mutable
 
+import generic._
+import immutable.{List, Nil, ::}
 
-import Predef._
-
-/** A Buffer implementation back up by a list. It provides constant time
+/** A `Buffer` implementation back up by a list. It provides constant time
  *  prepend and append. Most other operations are linear.
  *
  *  @author  Matthias Zenger
- *  @version 1.0, 15/03/2004
+ *  @author  Martin Odersky
+ *  @version 2.8
+ *  @since   1
+ *  
+ *  @tparam A    the type of this list buffer's elements.
+ *  
+ *  @define Coll ListBuffer
+ *  @define coll list buffer
+ *  @define thatinfo the class of the returned collection. In the standard library configuration,
+ *    `That` is always `ListBuffer[B]` because an implicit of type `CanBuildFrom[ListBuffer, B, ListBuffer[B]]`
+ *    is defined in object `ListBuffer`.
+ *  @define $bfinfo an implicit value of class `CanBuildFrom` which determines the
+ *    result class `That` from the current representation type `Repr`
+ *    and the new element type `B`. This is usually the `canBuildFrom` value
+ *    defined in object `ListBuffer`.
+ *  @define orderDependent 
+ *  @define orderDependentFold
+ *  @define mayNotTerminateInf
+ *  @define willNotTerminateInf
  */
- at serializable
-final class ListBuffer[A] extends Buffer[A] {
+ at serializable @SerialVersionUID(3419063961353022661L)
+final class ListBuffer[A] 
+      extends Buffer[A] 
+         with GenericTraversableTemplate[A, ListBuffer]
+         with BufferLike[A, ListBuffer[A]]
+         with Builder[A, List[A]] 
+         with SeqForwarder[A] 
+{ 
+  override def companion: GenericCompanion[ListBuffer] = ListBuffer
+
+  import scala.collection.Traversable
+
   private var start: List[A] = Nil
   private var last0: ::[A] = _
   private var exported: Boolean = false
+  private var len = 0
 
-  /** Prepends a single element to this buffer. It takes constant
-   *  time.
-   *
-   *  @param x  the element to prepend.
-   *  @return   this buffer.
-   */
-  def +: (x: A): Buffer[A] = {
-    if (exported) copy()
-    val newElem = new scala.:: (x, start)
-    if (start.isEmpty) last0 = newElem
-    start = newElem
-    this
-  }
-  
-  
-
-  /** Appends a single element to this buffer. It takes constant
-   *  time.
-   *
-   *  @param x  the element to append.
-   */
-  override def += (x: A) {
-    if (exported) copy()
-    if (start.isEmpty) {
-      last0 = new scala.:: (x, Nil)
-      start = last0
-    } else {
-      val last1 = last0
-      last0 = new scala.:: (x, Nil)
-      last1.tl = last0
-    }
-  }
-
-  /** Removes a single element from the buffer and return
-   *  the identity of the buffer. Same as <code>this -= x; this</code>. It
-   *  takes linear time (except removing the first element, which is done 
-   *  in constant time).
-   *
-   *  @param x  the element to remove.
-   *  @return   this buffer.
-   */
-  def - (x: A): Buffer[A] = { this -= x; this }
-
-  /** Remove a single element from this buffer. It takes linear time
-   *  (except removing the first element, which is done  in constant time).
-   *
-   *  @param x  the element to remove.
-   */
-  override def -= (x: A) {
-    if (exported) copy()
-    if (start.isEmpty) {}
-    else if (start.head == x) start = start.tail
-    else {
-      var cursor = start
-      while (!cursor.tail.isEmpty && cursor.tail.head != x) { cursor = cursor.tail }
-      if (!cursor.tail.isEmpty) {
-        val z = cursor.asInstanceOf[scala.::[A]]
-        if (z.tl == last0)
-          last0 = z
-        z.tl = cursor.tail.tail
-      }
-    }
-  }
-
-  /** Converts this buffer to a list. Takes constant time. The buffer is 
-   *  copied lazily, the first time it is mutated.
-   */
-  override def toList: List[A] = {
-    exported = !start.isEmpty
-    start
-  }
-  /** expose the underlying list but do not mark it as exported */
-  override def readOnly : List[A] = start
-
-  /** Prepends the elements of this buffer to a given list
-   *
-   *  @param xs   the list to which elements are prepended
-   */
-  def prependToList(xs: List[A]): List[A] =
-    if (start.isEmpty) xs
-    else { last0.tl = xs; toList }
-
-  /** Clears the buffer contents.
+  protected def underlying: immutable.Seq[A] = start
+ 
+  /** The current length of the buffer.
+   *  
+   *  This operation takes constant time.
    */
-  def clear() {
-    start = Nil
-    exported = false
-  }
-
-  /** Copy contents of this buffer */
-  private def copy() {
-    var cursor = start
-    val limit = last0.tail
-    clear
-    while (cursor ne limit) {
-      this += cursor.head
-      cursor = cursor.tail
-    }
-  }
-
-  /** Returns the length of this buffer. It takes linear time.
-   *
-   *  @return the length of this buffer.
-   */
-  def length: Int = start.length
+  override def length = len
   
-  // will be faster since this is a list
-  override def isEmpty = start.isEmpty
+  // Implementations of abstract methods in Buffer
 
-  /** Returns the n-th element of this list. This method
-   *  yields an error if the element does not exist. Takes time
-   *  linear in the buffer size.
-   *
-   *  @param n  the position of the element to be returned.
-   *  @return   the n-th element of this buffer.
-   *  @throws Predef.IndexOutOfBoundsException
-   */
-  def apply(n: Int): A = try {
-    start(n)
-  } catch {
-    case ex: Exception =>
-      throw new IndexOutOfBoundsException(n.toString())
-  }
+  override def apply(n: Int): A =
+    if (n < 0 || n >= len) throw new IndexOutOfBoundsException(n.toString())
+    else super.apply(n)
 
-  /** Replaces element at index <code>n</code> with the new element
-   *  <code>newelem</code>. Takes time linear in the buffer size. (except the first
-   *  element, which is updated in constant time).
+  /** Replaces element at index `n` with the new element
+   *  `newelem`. Takes time linear in the buffer size. (except the
+   *  first element, which is updated in constant time).
    *
    *  @param n  the index of the element to replace.
    *  @param x  the new element.
-   *  @throws Predef.IndexOutOfBoundsException if <code>n</code> is out of bounds.
+   *  @throws Predef.IndexOutOfBoundsException if `n` is out of bounds.
    */
   def update(n: Int, x: A) {
     try {
       if (exported) copy()
       if (n == 0) {
-        val newElem = new scala.:: (x, start.tail);
-        if (last0 eq start) last0 = newElem
+        val newElem = new :: (x, start.tail);
+        if (last0 eq start) { 
+          last0 = newElem
+        }	
         start = newElem
       } else {
         var cursor = start
@@ -172,30 +93,75 @@ final class ListBuffer[A] extends Buffer[A] {
           cursor = cursor.tail
           i += 1
         }
-        val newElem = new scala.:: (x, cursor.tail.tail)
-        if (last0 eq cursor.tail) last0 = newElem
-        cursor.asInstanceOf[scala.::[A]].tl = newElem
+        val newElem = new :: (x, cursor.tail.tail)
+        if (last0 eq cursor.tail) {
+          last0 = newElem
+        }	
+        cursor.asInstanceOf[::[A]].tl = newElem
       }
     } catch {
       case ex: Exception => throw new IndexOutOfBoundsException(n.toString())
     }
   }
 
-  /** Inserts new elements at the index <code>n</code>. Opposed to method
-   *  <code>update</code>, this method will not replace an element with a new
-   *  one. Instead, it will insert a new element at index <code>n</code>.
+  /** Appends a single element to this buffer. This operation takes constant time.
+   *
+   *  @param x  the element to append.
+   *  @return   this $coll.
+   */
+  def += (x: A): this.type = {
+    if (exported) copy()
+    if (start.isEmpty) {
+      last0 = new :: (x, Nil)
+      start = last0
+    } else {
+      val last1 = last0
+      last0 = new :: (x, Nil)
+      last1.tl = last0
+    }
+    len += 1
+    this
+  }
+
+  /** Clears the buffer contents.
+   */
+  def clear() {
+    start = Nil
+    exported = false
+    len = 0
+  }
+
+  /** Prepends a single element to this buffer. This operation takes constant
+   *  time.
+   *
+   *  @param x  the element to prepend.
+   *  @return   this $coll.
+   */
+  def +=: (x: A): this.type = {
+    if (exported) copy()
+    val newElem = new :: (x, start)
+    if (start.isEmpty) last0 = newElem
+    start = newElem
+    len += 1
+    this
+  }
+  
+  /** Inserts new elements at the index `n`. Opposed to method
+   *  `update`, this method will not replace an element with a new
+   *  one. Instead, it will insert a new element at index `n`.
    *
    *  @param  n     the index where a new element will be inserted.
    *  @param  iter  the iterable object providing all elements to insert.
-   *  @throws Predef.IndexOutOfBoundsException if <code>n</code> is out of bounds.
+   *  @throws Predef.IndexOutOfBoundsException if `n` is out of bounds.
    */
-  def insertAll(n: Int, iter: Iterable[A]) {
+  def insertAll(n: Int, seq: Traversable[A]) {
     try {
       if (exported) copy()
-      var elems = iter.elements.toList.reverse
+      var elems = seq.toList.reverse
+      len += elems.length
       if (n == 0) {
         while (!elems.isEmpty) {
-          val newElem = new scala.:: (elems.head, start)
+          val newElem = new :: (elems.head, start)
           if (start.isEmpty) last0 = newElem
           start = newElem
           elems = elems.tail
@@ -208,9 +174,9 @@ final class ListBuffer[A] extends Buffer[A] {
           i += 1
         }
         while (!elems.isEmpty) {
-          val newElem = new scala.:: (elems.head, cursor.tail)
+          val newElem = new :: (elems.head, cursor.tail)
           if (cursor.tail.isEmpty) last0 = newElem
-          cursor.asInstanceOf[scala.::[A]].tl = newElem
+          cursor.asInstanceOf[::[A]].tl = newElem
           elems = elems.tail
         }
       }
@@ -220,18 +186,76 @@ final class ListBuffer[A] extends Buffer[A] {
     }
   }
 
-  /** Removes the element on a given index position. Takes time linear in
-   *  the buffer size (except for the first element, which is removed in constant
-   *  time).
+  /** Removes a given number of elements on a given index position. May take
+   *  time linear in the buffer size.
+   *
+   *  @param n         the index which refers to the first element to remove.
+   *  @param count     the number of elements to remove.
+   */
+  override def remove(n: Int, count: Int) {
+    if (exported) copy()
+    val n1 = n max 0
+    val count1 = count min (len - n1)
+    var old = start.head
+    if (n1 == 0) {
+      var c = count1
+      while (c > 0) {
+        start = start.tail
+        c -= 1
+      }
+    } else {
+      var cursor = start
+      var i = 1
+      while (i < n1) {
+        cursor = cursor.tail
+        i += 1
+      }
+      var c = count1
+      while (c > 0) {
+        if (last0 eq cursor.tail) last0 = cursor.asInstanceOf[::[A]]
+        cursor.asInstanceOf[::[A]].tl = cursor.tail.tail
+        c -= 1
+      }
+    }
+    len -= count1
+  }
+
+// Implementation of abstract method in Builder
+
+  def result: List[A] = toList
+
+  /** Converts this buffer to a list. Takes constant time. The buffer is 
+   *  copied lazily, the first time it is mutated.
+   */
+  override def toList: List[A] = {
+    exported = !start.isEmpty
+    start
+  }
+
+// New methods in ListBuffer
+
+  /** Prepends the elements of this buffer to a given list
+   *
+   *  @param xs   the list to which elements are prepended
+   */
+  def prependToList(xs: List[A]): List[A] =
+    if (start.isEmpty) xs
+    else { last0.tl = xs; toList }
+
+// Overrides of methods in Buffer
+
+  /** Removes the element on a given index position. May take time linear in
+   *  the buffer size.
    *
    *  @param  n  the index which refers to the element to delete.
-   *  @return n  the element that was formerly at position <code>n</code>.
-   *  @pre       an element exists at position <code>n</code>
-   *  @throws Predef.IndexOutOfBoundsException if <code>n</code> is out of bounds.
+   *  @return n  the element that was formerly at position `n`.
+   *  @note      an element must exists at position `n`.
+   *  @throws Predef.IndexOutOfBoundsException if `n` is out of bounds.
    */
-  def remove(n: Int): A = try {
+  def remove(n: Int): A = {
+    if (n < 0 || n >= len) throw new IndexOutOfBoundsException(n.toString())
     if (exported) copy()
-    var old = start.head;
+    var old = start.head
     if (n == 0) {
       start = start.tail
     } else {
@@ -242,30 +266,44 @@ final class ListBuffer[A] extends Buffer[A] {
         i += 1
       }
       old = cursor.tail.head
-      if (last0 eq cursor.tail) last0 = cursor.asInstanceOf[scala.::[A]]
-      cursor.asInstanceOf[scala.::[A]].tl = cursor.tail.tail
+      if (last0 eq cursor.tail) last0 = cursor.asInstanceOf[::[A]]
+      cursor.asInstanceOf[::[A]].tl = cursor.tail.tail
     }
+    len -= 1
     old
-  } catch {
-    case ex: Exception =>
-      throw new IndexOutOfBoundsException(n.toString())
   }
 
-  /** <p>
-   *    Returns an iterator over all elements of this list.
-   *  </p>
-   *  <blockquote>
-   *    Note: the iterator can be affected by insertions, updates and
-   *    deletions that are performed afterwards on the buffer. To get
-   *    iterator an over the current buffer snapshot, use
-   *    <code>toList.elements</code>.
-   *  </blockquote>
+  /** Remove a single element from this buffer. May take time linear in the
+   *  buffer size.
    *
-   *  @throws Predef.NoSuchElementException if buffer is empty
+   *  @param x  the element to remove.
+   *  @return   this $coll.
    */
-  override def elements = new Iterator[A] {
+  override def -= (elem: A): this.type = {
+    if (exported) copy()
+    if (start.isEmpty) {}
+    else if (start.head == elem) {
+      start = start.tail
+      len -= 1
+    } else {
+      var cursor = start
+      while (!cursor.tail.isEmpty && cursor.tail.head != elem) { 
+        cursor = cursor.tail 
+      }
+      if (!cursor.tail.isEmpty) {
+        val z = cursor.asInstanceOf[::[A]]
+        if (z.tl == last0)
+          last0 = z
+        z.tl = cursor.tail.tail
+        len -= 1
+      }
+    }
+    this
+  }
+
+  override def iterator = new Iterator[A] {
     var cursor: List[A] = null
-    def hasNext: Boolean = !start.isEmpty && cursor != last0
+    def hasNext: Boolean = !start.isEmpty && (cursor ne last0)
     def next(): A =
       if (!hasNext) {
         throw new NoSuchElementException("next on empty Iterator")
@@ -275,31 +313,45 @@ final class ListBuffer[A] extends Buffer[A] {
       }
   }
 
+  /** expose the underlying list but do not mark it as exported */
+  override def readOnly: List[A] = start
+
+  // Private methods
+
+  /** Copy contents of this buffer */
+  private def copy() {
+    var cursor = start
+    val limit = last0.tail
+    clear
+    while (cursor ne limit) {
+      this += cursor.head
+      cursor = cursor.tail
+    }
+  }
+
+  override def equals(that: Any): Boolean = that match {
+    case that: ListBuffer[_] => this.readOnly equals that.readOnly
+    case _                   => super.equals(that)
+  }
+
   /** Returns a clone of this buffer.
    *
    *  @return a <code>ListBuffer</code> with the same elements.
    */
-  override def clone(): Buffer[A] = (new ListBuffer[A]) ++ this
-
-  /** Checks if two buffers are structurally identical.
-   *
-   *  @return <code>true</code>, iff both buffers contain the same sequence
-   *          of elements.
-   */
-  override def equals(obj: Any): Boolean = obj match {
-    case that: ListBuffer[_] =>
-      (this.length == that.length &&
-       elements.zip(that.elements).forall {
-         case (thiselem, thatelem) => thiselem == thatelem
-       })
-    case _ =>
-      false
-  }
+  override def clone(): ListBuffer[A] = (new ListBuffer[A]) ++= this
 
   /** Defines the prefix of the string representation.
    *
    *  @return the string representation of this buffer.
    */
-  override protected def stringPrefix: String = "ListBuffer"
+  override def stringPrefix: String = "ListBuffer"
 }
 
+/** $factoryInfo
+ *  @define Coll ListBuffer
+ *  @define coll list buffer
+ */
+object ListBuffer extends SeqFactory[ListBuffer] {
+  implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, ListBuffer[A]] = new GenericCanBuildFrom[A]
+  def newBuilder[A]: Builder[A, ListBuffer[A]] = new GrowingBuilder(new ListBuffer[A])
+}
diff --git a/src/library/scala/collection/mutable/ListMap.scala b/src/library/scala/collection/mutable/ListMap.scala
new file mode 100644
index 0000000..2be80fb
--- /dev/null
+++ b/src/library/scala/collection/mutable/ListMap.scala
@@ -0,0 +1,67 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+package mutable
+
+import generic._
+
+/** A simple mutable map backed by a list.
+ * 
+ *  @tparam A    the type of the keys contained in this list map.
+ *  @tparam B    the type of the values assigned to keys in this list map.
+ *  
+ *  @define Coll mutable.ListMap
+ *  @define coll mutable list map
+ *  @define thatinfo the class of the returned collection. In the standard library configuration,
+ *    `That` is always `ListMap[A, B]` if the elements contained in the resulting collection are 
+ *    pairs of type `(A, B)`. This is because an implicit of type `CanBuildFrom[ListMap, (A, B), ListMap[A, B]]`
+ *    is defined in object `ListMap`. Otherwise, `That` resolves to the most specific type that doesn't have
+ *    to contain pairs of type `(A, B)`, which is `Iterable`.
+ *  @define $bfinfo an implicit value of class `CanBuildFrom` which determines the
+ *    result class `That` from the current representation type `Repr`
+ *    and the new element type `B`. This is usually the `canBuildFrom` value
+ *    defined in object `ListMap`.
+ *  @define mayNotTerminateInf
+ *  @define willNotTerminateInf
+ *  @define orderDependent
+ *  @define orderDependentFold
+ */
+ at serializable
+class ListMap[A, B] extends Map[A, B] with MapLike[A, B, ListMap[A, B]] {
+
+  
+  override def empty = ListMap.empty[A, B]
+
+  private var elems: List[(A, B)] = List()
+  private var siz: Int = 0
+
+  def get(key: A): Option[B] = elems find (_._1 == key) map (_._2)
+  def iterator: Iterator[(A, B)] = elems.iterator
+  def += (kv: (A, B)) = { elems = remove(kv._1, elems); elems = kv :: elems; siz += 1; this }
+  def -= (key: A) = { elems = remove(key, elems); this }
+
+  private def remove(key: A, elems: List[(A, B)]): List[(A, B)] = 
+    if (elems.isEmpty) elems
+    else if (elems.head._1 == key) { siz -= 1; elems.tail }
+    else elems.head :: remove(key, elems.tail)
+  
+  override def clear() = elems = List()
+  override def size: Int = siz
+}
+
+/** $factoryInfo
+ *  @define Coll mutable.ListMap
+ *  @define coll mutable list map
+ */
+object ListMap extends MutableMapFactory[ListMap] {
+  implicit def canBuildFrom[A, B]: CanBuildFrom[Coll, (A, B), ListMap[A, B]] = new MapCanBuildFrom[A, B]
+  def empty[A, B]: ListMap[A, B] = new ListMap[A, B]
+}
diff --git a/src/library/scala/collection/mutable/Location.scala b/src/library/scala/collection/mutable/Location.scala
deleted file mode 100644
index da0c223..0000000
--- a/src/library/scala/collection/mutable/Location.scala
+++ /dev/null
@@ -1,29 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: Location.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala.collection.mutable
-
-
-/** Class <code>Location</code> describes locations in messages implemented
- *  by class <code>Message</code>.
- *
- *  @author  Matthias Zenger
- *  @version 1.0, 10/05/2004
- */
-abstract class Location
-
-case object NA extends Location
-
-case object Start extends Location
-
-case object End extends Location
-
-case class Index(n: Int) extends Location
diff --git a/src/library/scala/collection/mutable/Map.scala b/src/library/scala/collection/mutable/Map.scala
index 8e6d35c..13574f9 100644
--- a/src/library/scala/collection/mutable/Map.scala
+++ b/src/library/scala/collection/mutable/Map.scala
@@ -1,274 +1,53 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Map.scala 16881 2009-01-09 16:28:11Z cunei $
 
 
-package scala.collection.mutable
+package scala.collection
+package mutable
 
-import Predef._
+import generic._
 
-
-/** The canonical factory methods for <a href="Map.html">mutable maps</a>.
- *  These currently return <a href="HashMap.html">HashMap's</a>.
+/** A base trait for maps that can be mutated.
+ *  $mapNote
+ *  $mapTags
+ *  @since 1.0
+ *  @author  Matthias Zenger
  */
-object Map {
-
-  /** The empty map of this type; this is implemented as a hashtable */  
-  def empty[A, B]: Map[A, B] = new HashMap[A, B]
-
-  /** The canonical factory for this type
-   */
-  def apply[A, B](elems: (A, B)*) = empty[A, B] ++ elems
+trait Map[A, B] 
+  extends Iterable[(A, B)]
+     with scala.collection.Map[A, B] 
+     with MapLike[A, B, Map[A, B]] {
+
+  override def empty: Map[A, B] = Map.empty
+
+  /** Return a read-only projection of this map.  !!! or just use an (immutable) MapProxy? 
+  def readOnly : scala.collection.Map[A, B] = new scala.collection.Map[A, B] {
+    override def size = self.size
+    override def update(key: A, value: B) = self.update(key, value)
+    override def - (elem: A) = self - elem
+    override def iterator = self.iterator
+    override def foreach[U](f: ((A, B)) =>  U) = self.foreach(f)
+    override def empty[C] = self.empty[C]
+    def get(key: A) = self.get(key)
+  }
+  */
 }
 
-/** This trait represents mutable maps. Concrete map implementations
- *  just have to provide functionality for the abstract methods in
- *  <code>scala.collection.Map</code> as well as for <code>update</code>,
- *  and <code>-=</code>.
- *
- *  @author  Matthias Zenger
- *  @author  Martin Odersky
- *  @version 2.0, 31/12/2006
+/** $factoryInfo
+ *  The current default implementation of a $Coll is a `HashMap`.
+ *  @define coll mutable map
+ *  @define Coll mutable.Map
  */
- at cloneable
-trait Map[A, B] extends AnyRef
-      with collection.Map[A, B]
-      with Scriptable[Message[(A, B)]]
-      with CloneableCollection
-{
-  /** This method allows one to add a new mapping from <code>key</code>
-   *  to <code>value</code> to the map. If the map already contains a
-   *  mapping for <code>key</code>, it will be overridden by this
-   *  function.
-   *
-   * @param key    The key to update
-   * @param value  The new value
-   */
-  def update(key: A, value: B)
-
-  /** Add a key/value pair to this map. 
-   *  @param    kv the key/value pair.
-   */
-  def += (kv: (A, B)) { update(kv._1, kv._2) }
-
-  /** Add two or more key/value pairs to this map. 
-   *  @param    kv1 the first key/value pair.
-   *  @param    kv2 the second key/value pair.
-   *  @param    kvs the remaining key/value pairs.
-   */
-  def += (kv1: (A, B), kv2: (A, B), kvs: (A, B)*) {
-    this += kv1; this += kv2; this ++= kvs
-  }
-
-  /** Add a sequence of key/value pairs to this map. 
-   *  @param    kvs the iterable object containing all key/value pairs.
-   */
-  def ++= (kvs: Iterable[(A, B)]) { this ++= kvs.elements }
-
-  /** Add a sequence of key/value pairs to this map. 
-   *  @param    kvs the iterator containing all key/value pairs.
-   */
-  def ++= (kvs: Iterator[(A, B)]) { kvs foreach += }
-
-  /** Add a key/value pair to this map. 
-   *  @param    kv the key/value pair.
-   *  @return   The map itself with the new binding added in place.
-   */
-  def + (kv: (A, B)): Map[A, B] = { this += kv; this }
-
-  /** Add two or more key/value pairs to this map. 
-   *  @param    kv1 the first key/value pair.
-   *  @param    kv2 the second key/value pair.
-   *  @param    kvs the remaining key/value pairs.
-   *  @return   The map itself with the new bindings added in place.
-   */
-  def + (kv1: (A, B), kv2: (A, B), kvs: (A, B)*): Map[A, B] = { 
-    this.+=(kv1, kv2, kvs: _*); this 
-  }
-
-  /** Add a sequence of key/value pairs to this map. 
-   *  @param    kvs the iterable object containing all key/value pairs.
-   *  @return   The itself map with the new bindings added in place.
-   */
-  def ++ (kvs: Iterable[(A, B)]): Map[A, B] = { this ++= kvs; this }
-
-  /** Add a sequence of key/value pairs to this map. 
-   *  @param    kvs the iterator containing all key/value pairs.
-   *  @return   The itself map with the new bindings added in place.
-   */
-  def ++ (kvs: Iterator[(A, B)]): Map[A, B] = { this ++= kvs; this }
-
-  /** Remove a key from this map, noop if key is not present.
-   *  @param    key the key to be removed
-   */
-  def -= (key: A)
-
-  /** Remove two or more keys from this map
-   *  @param    key1 the first key to be removed
-   *  @param    key2 the second key to be removed
-   *  @param    keys the remaining keys to be removed
-   */
-  def -= (key1: A, key2: A, keys: A*) { this -= key1; this -= key2; this --= keys }
-
-  /** Remove a sequence of keys from this map
-   *  @param    keys the keys to be removed
-   */
-  def --= (keys: Iterable[A]) { this --= keys.elements }
-
-  /** Remove a sequence of keys from this map
-   *  @param    keys the keys to be removed
-   */
-  def --= (keys: Iterator[A]) { keys foreach -= }
-
-  /** Remove a key from this map
-   *  @param    key the key to be removed
-   *  @return   The map itself with the binding for <code>key</code> removed if
-   *            it existed.
-   */
-  def - (key: A): Map[A, B] = { this -= key; this }
-
-  /** Remove <code>key</code> from this map and return the element 
-   *  that the key was previously mapped to (if any).
-   */  
-  def removeKey(key: A): Option[B] = {
-    val ret = get(key)
-    this -= key
-    ret
-  }
-
-  /** Map <code>key</code> to <code>elem</code> in this map and return the element 
-   *  that the key was previously mapped to (if any).
-   */  
-  def put(key: A, elem: B): Option[B] = {
-    val ret = get(key)
-    this(key) = elem
-    ret
-  }
-
-  /** Remove two or more keys from this map
-   *  @param    key1 the first key to be removed
-   *  @param    key2 the second key to be removed
-   *  @param    keys the remaining keys to be removed
-   *  @return   The map itself with all bindings for the given keys removed.
-   */
-  def - (key1: A, key2: A, keys: A*): Map[A, B] = { this.-=(key1, key2, keys: _*); this }
-
-  /** Remove a sequence of keys from this map
-   *  @param    keys the keys to be removed
-   *  @return   The map itself with all bindings for <code>keys</code> removed.
-   */
-  def -- (keys: Iterable[A]): Map[A, B] = { this --= keys; this }
-
-  /** Remove a sequence of keys from this map
-   *  @param    keys the keys to be removed
-   *  @return   The map itself with all bindings for <code>keys</code> removed.
-   */
-  def -- (keys: Iterator[A]): Map[A, B] = { this --= keys; this }
-
-  /** Removes all mappings from the map. After this operation is
-   *  completed, the map is empty.
-   */
-  def clear() { keys foreach -= }
-
-  /** Check if this map maps <code>key</code> to a value.
-    * Return that value if it exists, otherwise put <code>default</code>
-    * as that key's value and return it.
-    */
-  def getOrElseUpdate(key: A, default: => B): B =
-    get(key) match {
-      case Some(v) => v
-      case None => val d = default; this(key) = d; d
-    }
-
-  /** This function transforms all the values of mappings contained
-   *  in this map with function <code>f</code>.
-   *
-   * @param f  The transformation to apply
-   */
-  def transform(f: (A, B) => B) {
-    elements foreach {
-      case (key, value) => update(key, f(key, value))
-    }
-  }
-
-  /** This method retains only those mappings for which the predicate
-   *  <code>p</code> returns <code>true</code>.
-   *
-   * @param p  The test predicate  
-   * @deprecated cannot be type inferred because if retain in Iterable. 
-   */
-  def retain(p: (A, B) => Boolean) {
-    toList foreach {
-      case (key, value) => if (!p(key, value)) -=(key)
-    }
-  }
-
-  /** Send a message to this scriptable object.
-   *
-   *  @param cmd  the message to send.
-   */
-  def <<(cmd: Message[(A, B)]): Unit = cmd match {
-    case Include((k, v)) => update(k, v)
-    case Update((k, v)) => update(k, v)
-    case Remove((k, _)) => this -= k
-    case Reset() => clear
-    case s: Script[_] => s.elements foreach <<
-    case _ => throw new UnsupportedOperationException("message " + cmd + " not understood")
-  }
-
-  /** Return a clone of this map.
-   *
-   *  @return a map with the same elements.
-   */
-  override def clone(): Map[A, B] = super.clone().asInstanceOf[Map[A, B]]
-
-  /** Return a read-only projection of this map */
-  def readOnly: scala.collection.Map[A, B] = new scala.collection.Map[A, B] {
-    override def toString = "ro-" + Map.this.toString
-    override def size = Map.this.size
-    override def elements = Map.this.elements
-    override def get(key: A) = Map.this.get(key)
-  }
-
-  /** This method defines syntactic sugar for adding or modifying
-   *  mappings. It is typically used in the following way:
-   *  <pre>
-   *  map += key -> value
-   *  </pre>
-   *  @deprecated   use <code>+= Pair(key, value)</code>
-   */
-  @deprecated
-  def +=(key: A): MapTo = new MapTo(key)
-
-  /** <code>incl</code> can be used to add many mappings at the same time
-   *  to the map. The method assumes that a mapping is represented
-   *  by a <code>Pair</code> object who's first component denotes the
-   *  key, and who's second component refers to the value.
-   *
-   * @param mappings
-   * @deprecated   use <code>+=</code>
-   */
-  @deprecated
-  def incl(mappings: (A, B)*) { this ++= mappings.elements }
-
-  /** This method will remove all the mappings for the given sequence
-   *  of keys from the map.
-   *
-   * @param keys
-   * @deprecated    use <code>-=</code>
-   */
-  @deprecated
-  def excl(keys: A*) { this --= keys.elements }
-
-  @deprecated
-  class MapTo(key: A) {
-    def ->(value: B) { update(key, value) }
-  }
+object Map extends MutableMapFactory[Map] {
+  /** $canBuildFromInfo */
+  implicit def canBuildFrom[A, B]: CanBuildFrom[Coll, (A, B), Map[A, B]] = new MapCanBuildFrom[A, B]
 
+  def empty[A, B]: Map[A, B] = new HashMap[A, B]
 }
+
diff --git a/src/library/scala/collection/mutable/MapBuilder.scala b/src/library/scala/collection/mutable/MapBuilder.scala
new file mode 100644
index 0000000..0cb2a1b
--- /dev/null
+++ b/src/library/scala/collection/mutable/MapBuilder.scala
@@ -0,0 +1,36 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+package scala.collection
+package mutable
+
+/** The canonical builder for immutable maps, working with the map's `+` method
+ *  to add new elements. 
+ *  Collections are built from their `empty` element using this + method.
+ *  
+ *  @tparam A      Type of the keys for the map this builder creates.
+ *  @tparam B      Type of the values for the map this builder creates.
+ *  @tparam Coll   The type of the actual collection this builder builds.
+ *  @param empty   The empty element of the collection.
+ *
+ *  @since 2.8
+ */
+class MapBuilder[A, B, Coll <: scala.collection.Map[A, B] with scala.collection.MapLike[A, B, Coll]](empty: Coll) 
+extends Builder[(A, B), Coll] {
+  protected var elems: Coll = empty
+  def +=(x: (A, B)): this.type = { 
+    elems = (elems + x).asInstanceOf[Coll]
+      // the cast is necessary because right now we cannot enforce statically that
+      // for every map of type Coll, `+` yields again a Coll. With better support
+      // for hk-types we might be able to enforce this in the future, though.
+    this 
+  }
+  def clear() { elems = empty }
+  def result: Coll = elems
+}
diff --git a/src/library/scala/collection/mutable/MapLike.scala b/src/library/scala/collection/mutable/MapLike.scala
new file mode 100644
index 0000000..09887ec
--- /dev/null
+++ b/src/library/scala/collection/mutable/MapLike.scala
@@ -0,0 +1,246 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+package mutable
+
+import generic._
+import annotation.migration
+
+/** A template trait for mutable maps.
+ *  $mapNote
+ *  $mapTags
+ *  @since   2.8
+ */
+trait MapLike[A, B, +This <: MapLike[A, B, This] with Map[A, B]]
+  extends scala.collection.MapLike[A, B, This]
+     with Builder[(A, B), This] 
+     with Growable[(A, B)]
+     with Shrinkable[A]
+     with Cloneable[This]
+{ self =>
+
+  import scala.collection.Traversable
+
+  /** A common implementation of `newBuilder` for all mutable maps
+   *    in terms of `empty`.
+   * 
+   *    Overrides `MapLike` implementation for better efficiency.
+   */
+  override protected[this] def newBuilder: Builder[(A, B), This] = empty
+
+  /** Adds a new key/value pair to this map and optionally returns previously bound value.
+   *  If the map already contains a
+   *  mapping for the key, it will be overridden by the new value.
+   *
+   * @param key    the key to update
+   * @param value  the new value
+   * @return an option value containing the value associated with the key
+   *         before the `put` operation was executed, or `None` if `key`
+   *         was not defined in the map before.
+   */
+  def put(key: A, value: B): Option[B] = {
+    val r = get(key)
+    update(key, value)
+    r
+  }
+
+  /** Adds a new key/value pair to this map.
+   *  If the map already contains a
+   *  mapping for the key, it will be overridden by the new value.
+   *
+   *  @param key    The key to update
+   *  @param value  The new value
+   */    
+  def update(key: A, value: B) { this += ((key, value)) }
+
+  /** Adds a new key/value pair to this map.
+   *  If the map already contains a
+   *  mapping for the key, it will be overridden by the new value.
+   *  @param    kv the key/value pair.
+   *  @return   the map itself
+   */
+  def += (kv: (A, B)): this.type
+
+  /** Creates a new map consisting of all key/value pairs of the current map
+   *  plus a new pair of a given key and value.
+   *
+   *  @param key    The key to add
+   *  @param value  The new value
+   *  @return       A fresh immutable map with the binding from `key` to
+   *                `value` added to this map.
+   */
+  override def updated[B1 >: B](key: A, value: B1): Map[A, B1] = this + ((key, value))
+
+  /** Creates a new map containing a new key/value mapping and all the key/value mappings
+   *  of this map.
+   *
+   *  Mapping `kv` will override existing mappings from this map with the same key.
+   *
+   *  @param kv    the key/value mapping to be added
+   *  @return      a new map containing mappings of this map and the mapping `kv`.
+   */
+  @migration(2, 8,
+    "As of 2.8, this operation creates a new map.  To add an element as a\n"+
+    "side effect to an existing map and return that map itself, use +=."
+  )
+  def + [B1 >: B] (kv: (A, B1)): Map[A, B1] = clone().asInstanceOf[Map[A, B1]] += kv
+
+  /** Creates a new map containing two or more key/value mappings and all the key/value
+   *  mappings of this map.
+   *  
+   *  Specified mappings will override existing mappings from this map with the same keys.
+   *  
+   *  @param elem1 the first element to add.
+   *  @param elem2 the second element to add.
+   *  @param elems the remaining elements to add.
+   *  @return      a new map containing mappings of this map and two or more specified mappings.
+   */
+  @migration(2, 8,
+    "As of 2.8, this operation creates a new map.  To add an element as a\n"+
+    "side effect to an existing map and return that map itself, use +=."
+  )
+  override def + [B1 >: B] (elem1: (A, B1), elem2: (A, B1), elems: (A, B1) *): Map[A, B1] =
+    clone().asInstanceOf[Map[A, B1]] += elem1 += elem2 ++= elems
+
+  /** Creates a new map containing the key/value mappings provided by the specified traversable object
+   *  and all the key/value mappings of this map.
+   *  
+   *  Note that existing mappings from this map with the same key as those in `xs` will be overriden.
+   *  
+   *  @param xs     the traversable object.
+   *  @return       a new map containing mappings of this map and those provided by `xs`.
+   */
+  @migration(2, 8,
+    "As of 2.8, this operation creates a new map.  To add the elements as a\n"+
+    "side effect to an existing map and return that map itself, use ++=."
+  )
+  override def ++[B1 >: B](xs: TraversableOnce[(A, B1)]): Map[A, B1] =
+    clone().asInstanceOf[Map[A, B1]] ++= xs
+
+  /** Removes a key from this map, returning the value associated previously
+   *  with that key as an option.
+   *  @param    key the key to be removed
+   *  @return   an option value containing the value associated previously with `key`,
+   *            or `None` if `key` was not defined in the map before.
+   */
+  def remove(key: A): Option[B] = {
+    val r = get(key)
+    this -= key
+    r
+  }
+
+  /** Removes a key from this map.
+   *  @param    key the key to be removed
+   *  @return   the map itself.
+   */
+  def -= (key: A): this.type
+
+  /** Creates a new map with all the key/value mappings of this map except the key/value mapping
+   *  with the specified key.
+   *  
+   *  @param    key the key to be removed
+   *  @return   a new map with all the mappings of this map except that with a key `key`.
+   */
+  @migration(2, 8,
+    "As of 2.8, this operation creates a new map.  To remove an element as a\n"+
+    "side effect to an existing map and return that map itself, use -=."
+  )
+  override def -(key: A): This = clone() -= key
+
+  /** If given key is defined in this map, remove it and return associated value as an Option.
+   *  If key is not present return None.
+   *  @param    key the key to be removed
+   */
+  @deprecated("Use `remove' instead") def removeKey(key: A): Option[B] = remove(key)
+
+  /** Removes all bindings from the map. After this operation has completed,
+   *  the map will be empty.
+   */
+  def clear() { keysIterator foreach -= }
+  
+  /** If given key is already in this map, returns associated value.
+   *  
+   *  Otherwise, computes value from given expression `op`, stores with key
+   *  in map and returns that value.
+   *  @param  key the key to test
+   *  @param  op  the computation yielding the value to associate with `key`, if
+   *              `key` is previously unbound.
+   *  @return     the value associated with key (either previously or as a result
+   *              of executing the method).
+   */  
+  def getOrElseUpdate(key: A, op: => B): B =
+    get(key) match {
+      case Some(v) => v
+      case None => val d = op; this(key) = d; d
+    }
+
+  /** Applies a transformation function to all values contained in this map.
+   *  The transformation function produces new values from existing keys
+   *  associated values.
+   * 
+   * @param f  the transformation to apply
+   * @return   the map itself.
+   */
+  def transform(f: (A, B) => B): this.type = {
+    this.iterator foreach {
+      case (key, value) => update(key, f(key, value))
+    }
+    this
+  }
+
+  /** Retains only those mappings for which the predicate
+   *  `p` returns `true`.
+   *
+   * @param p  The test predicate  
+   */
+  def retain(p: (A, B) => Boolean): this.type = {
+    for ((k, v) <- this ; if !p(k, v))
+      this -= k
+
+    this
+  }
+
+  override def clone(): This = empty ++= repr
+
+  /** The result when this map is used as a builder
+   *  @return  the map representation itself.
+   */
+  def result: This = repr
+
+  /** Creates a new map with all the key/value mappings of this map except mappings with keys
+   *  equal to any of the two or more specified keys.
+   *
+   *  @param elem1 the first element to remove.
+   *  @param elem2 the second element to remove.
+   *  @param elems the remaining elements to remove.
+   *  @return      a new map containing all the mappings of this map except mappings
+   *               with a key equal to `elem1`, `elem2` or any of `elems`.
+   */
+  @migration(2, 8,
+    "As of 2.8, this operation creates a new map.  To remove an element as a\n"+
+    "side effect to an existing map and return that map itself, use -=."
+  )
+  override def -(elem1: A, elem2: A, elems: A*): This =
+    clone() -= elem1 -= elem2 --= elems
+
+  /** Creates a new map with all the key/value mappings of this map except mappings with keys
+   *  equal to any of those provided by the specified traversable object.
+   *  
+   *  @param xs       the traversable object.
+   *  @return         a new map with all the key/value mappings of this map except mappings
+   *                  with a key equal to a key from `xs`.
+   */
+  @migration(2, 8,
+    "As of 2.8, this operation creates a new map.  To remove the elements as a\n"+
+    "side effect to an existing map and return that map itself, use --=."
+  )  
+  override def --(xs: TraversableOnce[A]): This = clone() --= xs
+}
diff --git a/src/library/scala/collection/mutable/MapProxy.scala b/src/library/scala/collection/mutable/MapProxy.scala
index 25c5dd9..c328a60 100644
--- a/src/library/scala/collection/mutable/MapProxy.scala
+++ b/src/library/scala/collection/mutable/MapProxy.scala
@@ -1,57 +1,40 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: MapProxy.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.collection.mutable
+package scala.collection
+package mutable
 
-
-/** <p>
- *    This is a simple wrapper class for <a href="Map.html"
- *    target="contentFrame"><code>scala.collection.mutable.Map</code></a>.
- *  </p>
- *  <p>
- *    It is most useful for assembling customized map abstractions
- *    dynamically using object composition and forwarding.
- *  </p>
+/** 
+ *  This trait implements a proxy for <a href="Map.html"
+ *  target="contentFrame"><code>scala.collection.mutable.Map</code></a>.
+ *  
+ *  It is most useful for assembling customized map abstractions
+ *  dynamically using object composition and forwarding.
  *
  *  @author  Matthias Zenger, Martin Odersky
  *  @version 2.0, 31/12/2006
+ *  @since   1
  */
-trait MapProxy[A, B] extends Map[A, B] with collection.MapProxy[A, B] {
-
-  def self: Map[A, B]
+trait MapProxy[A, B] extends Map[A, B] with MapProxyLike[A, B, Map[A, B]] {  
+  private def newProxy[B1 >: B](newSelf: Map[A, B1]): MapProxy[A, B1] =
+    new MapProxy[A, B1] { val self = newSelf }
 
-  override def update(key: A, value: B): Unit = self.update(key, value)
-  override def += (kv: (A, B)) = self += kv
-  override def += (kv1: (A, B), kv2: (A, B), kvs: (A, B)*) = self.+=(kv1, kv2, kvs: _*)
-  override def ++= (kvs: Iterable[(A, B)]) = self ++= kvs
-  override def ++= (kvs: Iterator[(A, B)]) = self ++= kvs
-  override def + (kv: (A, B)): Map[A, B] = self + kv
-  override def + (kv1: (A, B), kv2: (A, B), kvs: (A, B)*): Map[A, B] = self.+(kv1, kv2, kvs: _*)
-  override def ++ (kvs: Iterable[(A, B)]): Map[A, B] = self ++ kvs
-  override def ++ (kvs: Iterator[(A, B)]): Map[A, B] = self ++ kvs
-  override def -= (key: A) = self -= key
-  override def -= (key1: A, key2: A, keys: A*) = self.-=(key1, key2, keys: _*)
-  override def --= (keys: Iterable[A]) = self --= keys
-  override def --= (keys: Iterator[A]) = self --= keys
-  override def - (key: A): Map[A, B] = self - key
-  override def - (key1: A, key2: A, keys: A*): Map[A, B] = self.-(key1, key2, keys: _*)
-  override def -- (keys: Iterable[A]): Map[A, B] = self -- keys
-  override def -- (keys: Iterator[A]): Map[A, B] = self -- keys
-  override def clear(): Unit = self.clear
-  override def transform(f: (A, B) => B) = self transform f
-  override def retain(p: (A, B) => Boolean): Unit = self retain p
-  override def <<(cmd: Message[(A, B)]): Unit = self << cmd
-  override def clone(): Map[A, B] = self.clone()
-  @deprecated
-  override def incl(mappings: (A, B)*): Unit = self.incl(mappings: _*)
-  @deprecated
-  override def excl(keys: A*): Unit = self.excl(keys: _*)
+  override def repr = this
+  override def empty: MapProxy[A, B] = new MapProxy[A, B] { val self = MapProxy.this.self.empty }
+  override def updated [B1 >: B](key: A, value: B1) = newProxy(self.updated(key, value))
+  
+  override def + [B1 >: B] (kv: (A, B1)): Map[A, B1] = newProxy(self + kv)
+  override def + [B1 >: B] (elem1: (A, B1), elem2: (A, B1), elems: (A, B1) *) = newProxy(self.+(elem1, elem2, elems: _*))
+  override def ++[B1 >: B](xs: TraversableOnce[(A, B1)]) = newProxy(self ++ xs)
+  override def -(key: A) = newProxy(self - key)
+  
+  override def += (kv: (A, B)) = { self += kv ; this }
+  override def -= (key: A) = { self -= key ; this }
 }
diff --git a/src/library/scala/collection/mutable/Message.scala b/src/library/scala/collection/mutable/Message.scala
deleted file mode 100644
index f591a03..0000000
--- a/src/library/scala/collection/mutable/Message.scala
+++ /dev/null
@@ -1,82 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: Message.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala.collection.mutable
-
-
-import Predef._
-
-/** Class <code>Message</code> represents messages that are issued by observable
- *  collection classes whenever a data structure is changed. Class <code>Message</code>
- *  has several subclasses for the various kinds of events: <code>Update</code>
- *  <code>Remove</code>, <code>Include</code>, <code>Reset</code>, and
- *  <code>Script</code>.
- *
- *  @author  Matthias Zenger
- *  @version 1.0, 08/07/2003
- */
-trait Message[+A]
-
-/** This observable update refers to inclusion operations that add new elements
- *  to collection classes.
- *
- *  @author  Matthias Zenger
- *  @version 1.0, 08/07/2003
- */
-case class Include[+I](elem: I) extends Message[I]
-
-/** This observable update refers to destructive modification operations
- *  of elements from collection classes.
- *
- *  @author  Matthias Zenger
- *  @version 1.0, 08/07/2003
- */
-case class Update[+A](elem: A) extends Message[A]
-
-/** This observable update refers to removal operations of elements
- *  from collection classes.
- *
- *  @author  Matthias Zenger
- *  @version 1.0, 08/07/2003
- */
-case class Remove[+A](elem: A) extends Message[A]
-
-/** This command refers to reset operations.
- *
- *  @author  Matthias Zenger
- *  @version 1.0, 08/07/2003
- */
-case class Reset[+A]() extends Message[A]
-
-/** Objects of this class represent compound messages consisting
- *  of a sequence of other messages.
- *
- *  @author  Matthias Zenger
- *  @version 1.0, 10/05/2004
- */
-class Script[A] extends ArrayBuffer[Message[A]] with Message[A] {
-
-  override def toString(): String = {
-    var res = "Script("
-    var it = elements
-    var i = 1
-    while (it.hasNext) {
-      if (i > 1)
-        res = res + ", "
-      res = res + "[" + i + "] " + it.next
-      i = i + 1
-    }
-    res + ")"
-  }
-
-  override def hashCode(): Int =
-    throw new UnsupportedOperationException("scripts are not suitable as hash keys")
-}
diff --git a/src/library/scala/collection/mutable/MultiMap.scala b/src/library/scala/collection/mutable/MultiMap.scala
index cf226d9..6e4a8f0 100644
--- a/src/library/scala/collection/mutable/MultiMap.scala
+++ b/src/library/scala/collection/mutable/MultiMap.scala
@@ -1,41 +1,90 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: MultiMap.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.collection.mutable
+package scala.collection
+package mutable
 
 
-/** This class is typically used as a mixin. It turns maps which map <code>A</code>
- *  to <code>Set[B]</code> objects into multi maps which map <code>A</code> to
- *  <code>B</code> objects.
+/** A trait for mutable maps with multiple values assigned to a key.
+ *  
+ *  This class is typically used as a mixin. It turns maps which map `A`
+ *  to `Set[B]` objects into multi maps which map `A` to
+ *  `B` objects.
  *
+ *  @define coll multimap
+ *  @define Coll MultiMap
  *  @author  Matthias Zenger
- *  @version 1.0, 08/07/2003
+ *  @author  Martin Odersky 
+ *  @version 2.8
+ *  @since   1
  */
 trait MultiMap[A, B] extends Map[A, Set[B]] {
+  /** Creates a new set.
+   *  
+   *  Classes that use this trait as a mixin can override this method
+   *  to have the desired implementation of sets assigned to new keys.
+   *  By default this is `HashSet`.
+   *  
+   *  @return An empty set of values of type `B`.
+   */
   protected def makeSet: Set[B] = new HashSet[B]
 
-  def add(key: A, value: B): Unit = get(key) match {
-    case None =>
-      val set = makeSet
-      set += value
-      this(key) = set
-    case Some(set) =>
-      set += value
-  }
+  @deprecated("use addBinding instead")
+  def add(key: A, value: B): this.type = addBinding(key, value)
 
-  def remove(key: A, value: B) = get(key) match {
-    case None =>
-    case Some(set) => set -= value
+  /** Assigns the specified `value` to a specified `key`, replacing
+   *  the existing value assigned to that `key` if it is equal to
+   *  the specified value. Otherwise, simply adds another binding to
+   *  the `key`.
+   *  
+   *  @param key    The key to which to bind the new value.
+   *  @param value  The value to bind to the key.
+   *  @return       A reference to this multimap.
+   */
+  def addBinding(key: A, value: B): this.type = {
+    get(key) match {
+      case None =>
+        val set = makeSet
+        set += value
+        this(key) = set
+      case Some(set) =>
+        set += value
+    }
+    this
   }
 
+  /** Removes the binding of `value` to `key` if it exists.
+   *  
+   *  If this was the last value assigned to the specified key, the
+   *  set assigned to that key will be removed as well.
+   *  
+   *  @param key     The key of the binding.
+   *  @param value   The value to remove.
+   *  @return        A reference to this multimap.
+   */
+  def removeBinding(key: A, value: B): this.type = {
+    get(key) match {
+      case None =>
+        case Some(set) =>
+          set -= value
+          if (set.isEmpty) this -= key
+    }
+    this
+  }
+  
+  /** Checks if there exists a binding to `key` such that it satisfies the predicate `p`.
+   *  
+   *  @param key   The key for which the predicate is checked.
+   *  @param p     The predicate which a value assigned to the key must satisfy.
+   *  @return      A boolean if such a binding exists
+   */
   def entryExists(key: A, p: B => Boolean): Boolean = get(key) match {
     case None => false
     case Some(set) => set exists p
diff --git a/src/library/scala/collection/mutable/MutableList.scala b/src/library/scala/collection/mutable/MutableList.scala
index 63b2a7c..2389961 100644
--- a/src/library/scala/collection/mutable/MutableList.scala
+++ b/src/library/scala/collection/mutable/MutableList.scala
@@ -1,82 +1,136 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: MutableList.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.collection.mutable
+package scala.collection
+package mutable
 
+import generic._
+import immutable.{List, Nil}
 
-//import Predef.NoSuchElementException
-
-/** This class is used internally to represent mutable lists. It is the
- *  basis for the implementation of the classes <code>Buffer</code>,
- *  <code>Stack</code>, and <code>Queue</code>.
- *
+// !!! todo: convert to LinkedListBuffer?
+/** 
+ *  This class is used internally to represent mutable lists. It is the
+ *  basis for the implementation of the classes
+ *  `Stack`, and `Queue`.
+ *  
  *  @author  Matthias Zenger
- *  @version 1.0, 08/07/2003
+ *  @author  Martin Odersky
+ *  @version 2.8
+ *  @since   1
  */
-trait MutableList[A] extends Seq[A] with PartialFunction[Int, A] {
+ at serializable @SerialVersionUID(5938451523372603072L)
+class MutableList[A] extends LinearSeq[A]
+                        with LinearSeqOptimized[A, MutableList[A]]
+                        with Builder[A, MutableList[A]] {
+
+  override protected[this] def newBuilder = new MutableList[A]
 
-  protected var first0: LinkedList[A] = null
-  protected var last0: LinkedList[A] = null
+  protected var first0: LinkedList[A] = new LinkedList[A]
+  protected var last0: LinkedList[A] = _ // undefined if first0.isEmpty 
   protected var len: Int = 0
 
-  /** Returns the length of this list.
+  /** Is the list empty?
    */
-  def length: Int = len
+  override def isEmpty = len == 0
 
-  /** Returns the <code>n</code>th element of this list. This method
-   *  yields an error if the element does not exist.
+  /** Returns the first element in this list
    */
-  def apply(n: Int): A = get(n) match {
-    case None => throw new NoSuchElementException("element not found")
-    case Some(value) => value
+  override def head: A = first0.head
+
+  /** Returns the rest of this list
+   */
+  override def tail: MutableList[A] = {
+    require(nonEmpty, "tail of empty list")
+    val tl = new MutableList[A]
+    tl.first0 = first0.tail
+    tl.last0 = last0
+    tl.len = len - 1
+    tl
   }
 
+  /** Prepends a single element to this list. This operation takes constant
+   *  time.
+   *  @param elem  the element to prepend.
+   *  @return   this $coll.
+   */
+  def +=: (elem: A): this.type = { prependElem(elem); this }
+
+  /** Returns the length of this list.
+   */
+  override def length: Int = len
+
+  /** Returns the <code>n</code>th element of this list.
+   *  @throws IndexOutofBoundsException if index does not exist.
+   */
+  override def apply(n: Int): A = first0.apply(n)
+
+  /** Updates the <code>n</code>th element of this list to a new value.
+   *  @throws IndexOutofBoundsException if index does not exist.
+   */
+  def update(n: Int, x: A): Unit = first0.update(n, x)
+
   /** Returns the <code>n</code>th element of this list or <code>None</code>
-   *  if this element does not exist.
+   *  if index does not exist.
    */
   def get(n: Int): Option[A] = first0.get(n)
 
-  protected def prependElem(elem: A): Unit = {
+  protected def prependElem(elem: A) {
     first0 = new LinkedList[A](elem, first0)
-    if (len == 0)
-      last0 = first0
+    if (len == 0) last0 = first0
     len = len + 1
   }
 
   protected def appendElem(elem: A): Unit =
-    if (len == 0)
+    if (len == 0) {
       prependElem(elem)
-    else {
-      last0.next = new LinkedList[A](elem, null)
+    } else {
+      last0.next = new LinkedList[A]
       last0 = last0.next
+      last0.elem = elem
+      last0.next = new LinkedList[A] // for performance, use sentinel `object' instead?
       len = len + 1
     }
 
-  protected def reset() {
-    first0 = null
-    last0 = null
-    len = 0
-  }
+  @deprecated("use clear instead")
+  def reset() { clear() }
 
   /** Returns an iterator over all elements of this list.
    */
-  override def elements: Iterator[A] =
-    if (first0 eq null) Nil.elements else first0.elements
+  override def iterator: Iterator[A] = first0.iterator
 
-  override def last = last0.elem
+  override def last = {
+    if (isEmpty) throw new NoSuchElementException("MutableList.empty.last")
+    last0.elem
+  }
 
   /** Returns an instance of <code>scala.List</code> containing the same
    *  sequence of elements.
    */
-  override def toList: List[A] = if (first0 eq null) Nil else first0.toList
+  override def toList: List[A] = first0.toList
+
+  /** Returns the current list of elements as a linked List
+   *  sequence of elements.
+   */
+  private[mutable] def toLinkedList: LinkedList[A] = first0
+
+  /** Appends a single element to this buffer. This takes constant time.
+   *
+   *  @param elem  the element to append.
+   */
+  def +=(elem: A): this.type = { appendElem(elem); this }
+
+  def clear() {
+    first0 = new LinkedList[A]
+    last0 = first0
+    len = 0
+  }
 
-  override protected def stringPrefix: String = "MutableList"
+  def result = this
 }
diff --git a/src/library/scala/collection/mutable/ObservableBuffer.scala b/src/library/scala/collection/mutable/ObservableBuffer.scala
index 283500e..1a7cb36 100644
--- a/src/library/scala/collection/mutable/ObservableBuffer.scala
+++ b/src/library/scala/collection/mutable/ObservableBuffer.scala
@@ -1,65 +1,51 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: ObservableBuffer.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.collection.mutable
+package scala.collection
+package mutable
 
-
-//import Predef.UnsupportedOperationException
+import script._
 
 /** This class is typically used as a mixin. It adds a subscription
- *  mechanism to the <code>Buffer</code> class into which this abstract
- *  class is mixed in. Class <code>ObservableBuffer</code> publishes
- *  events of the type <code>Message</code>.
+ *  mechanism to the `Buffer` class into which this abstract
+ *  class is mixed in. Class `ObservableBuffer` publishes
+ *  events of the type `Message`.
  *
  *  @author  Matthias Zenger
  *  @version 1.0, 08/07/2003
+ *  @since   1
  */
-trait ObservableBuffer[A, This <: ObservableBuffer[A, This]] 
-      extends Buffer[A]
-      with Publisher[Message[(Location, A)]
-      with Undoable, This]
-{ self: This =>
-
-  abstract override def +(element: A): Buffer[A] = {
-    super.+(element)
-    publish(new Include((End, element)) with Undoable {
+trait ObservableBuffer[A] extends Buffer[A] with Publisher[Message[A] with Undoable]
+{ 
+  type Pub <: ObservableBuffer[A]
+  
+  abstract override def +=(element: A): this.type = {
+    super.+=(element)
+    publish(new Include(End, element) with Undoable {
       def undo() { trimEnd(1) }
     })
     this
   }
-
-  abstract override def +:(element: A): Buffer[A] = {
-    super.+:(element);
-    publish(new Include((Start, element)) with Undoable {
+  
+  abstract override def +=:(element: A): this.type = {
+    super.+=:(element)
+    publish(new Include(Start, element) with Undoable {
       def undo() { trimStart(1) }
     })
     this
   }
 
-  abstract override def insertAll(n: Int, iter: Iterable[A]): Unit = {
-    super.insertAll(n, iter)
-    var i = n
-    val it = iter.elements
-    while (it.hasNext) {
-      publish(new Include((Index(i), it.next)) with Undoable {
-        def undo { remove(i) }
-      })
-      i = i + 1
-    }
-  }
-
   abstract override def update(n: Int, newelement: A): Unit = {
     val oldelement = apply(n)
     super.update(n, newelement)
-    publish(new Update((Index(n), newelement)) with Undoable {
+    publish(new Update(Index(n), newelement) with Undoable {
       def undo { update(n, oldelement) }
     })
   }
@@ -67,7 +53,7 @@ trait ObservableBuffer[A, This <: ObservableBuffer[A, This]]
   abstract override def remove(n: Int): A = {
     val oldelement = apply(n)
     super.remove(n)
-    publish(new Remove((Index(n), oldelement)) with Undoable {
+    publish(new Remove(Index(n), oldelement) with Undoable {
       def undo { insert(n, oldelement) }
     })
     oldelement
diff --git a/src/library/scala/collection/mutable/ObservableMap.scala b/src/library/scala/collection/mutable/ObservableMap.scala
index 3006d02..190f334 100644
--- a/src/library/scala/collection/mutable/ObservableMap.scala
+++ b/src/library/scala/collection/mutable/ObservableMap.scala
@@ -1,52 +1,62 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: ObservableMap.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.collection.mutable
+package scala.collection
+package mutable
+
+import script._
 
 
 /** This class is typically used as a mixin. It adds a subscription
- *  mechanism to the <code>Map</code> class into which this abstract
- *  class is mixed in. Class <code>ObservableMap</code> publishes
- *  events of the type <code>Message</code>.
+ *  mechanism to the `Map` class into which this abstract
+ *  class is mixed in. Class `ObservableMap` publishes
+ *  events of the type `Message`.
  *
  *  @author  Matthias Zenger
  *  @author  Martin Odersky
  *  @version 2.0, 31/12/2006
+ *  @since   1
  */
-trait ObservableMap[A, B, This <: ObservableMap[A, B, This]] 
-      extends Map[A, B]
-      with Publisher[Message[(A, B)]
-      with Undoable, This]
-{ self: This =>
-
-  abstract override def update(key: A, value: B): Unit = get(key) match {
-    case None =>
-      super.update(key, value)
-      publish(new Include((key, value)) with Undoable {
-        def undo = -=(key)
-      })
-    case Some(old) =>
-      super.update(key, value)
-      publish(new Update((key, value)) with Undoable {
-        def undo = update(key, old)
-      })
+trait ObservableMap[A, B] extends Map[A, B] with Publisher[Message[(A, B)] with Undoable]
+{ 
+  
+  type Pub <: ObservableMap[A, B]
+
+  abstract override def += (kv: (A, B)): this.type = {
+    val (key, value) = kv
+    
+    get(key) match {
+      case None =>
+        super.+=(kv)
+        publish(new Include((key, value)) with Undoable {
+          def undo = -=(key)
+        })
+      case Some(old) =>
+        super.+=(kv)
+        publish(new Update((key, value)) with Undoable {
+          def undo = +=((key, old))
+        })
+    }
+    this
   }
 
-  abstract override def -= (key: A): Unit = get(key) match {
-    case None =>
-    case Some(old) =>
-      super.-=(key)
-      publish(new Remove((key, old)) with Undoable {
-        def undo = update(key, old)
-      })
+  abstract override def -= (key: A): this.type = {
+    get(key) match {
+      case None =>
+      case Some(old) =>
+        super.-=(key)
+        publish(new Remove((key, old)) with Undoable {
+          def undo = update(key, old)
+        })
+    }
+    this
   }
 
   abstract override def clear(): Unit = {
diff --git a/src/library/scala/collection/mutable/ObservableSet.scala b/src/library/scala/collection/mutable/ObservableSet.scala
index 1f47c1a..dcacc67 100644
--- a/src/library/scala/collection/mutable/ObservableSet.scala
+++ b/src/library/scala/collection/mutable/ObservableSet.scala
@@ -1,39 +1,46 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: ObservableSet.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.collection.mutable
+package scala.collection
+package mutable
 
+import script._
 
 /** This class is typically used as a mixin. It adds a subscription
- *  mechanism to the <code>Set</code> class into which this abstract
- *  class is mixed in. Class <code>ObservableSet</code> publishes
- *  events of the type <code>Message</code>.
+ *  mechanism to the `Set` class into which this abstract
+ *  class is mixed in. Class `ObservableSet` publishes
+ *  events of the type `Message`.
  *
  *  @author  Matthias Zenger
  *  @version 1.0, 08/07/2003
+ *  @since   1
  */
-trait ObservableSet[A, This <: ObservableSet[A, This]] 
-      extends Set[A]
-      with Publisher[Message[A]
-      with Undoable, This]
-{ self: This =>
-
-  abstract override def +=(elem: A): Unit = if (!contains(elem)) {
-    super.+=(elem)
-    publish(new Include(elem) with Undoable { def undo = -=(elem) })
+trait ObservableSet[A] extends Set[A] with Publisher[Message[A] with Undoable]
+{ 
+
+  type Pub <: ObservableSet[A]
+
+  abstract override def +=(elem: A): this.type = {
+    if (!contains(elem)) {
+      super.+=(elem)
+      publish(new Include(elem) with Undoable { def undo = -=(elem) })
+    }
+    this
   }
 
-  abstract override def -=(elem: A): Unit = if (contains(elem)) {
-    super.-=(elem)
-    publish(new Remove(elem) with Undoable { def undo = +=(elem) })
+  abstract override def -=(elem: A): this.type = {
+    if (contains(elem)) {
+      super.-=(elem)
+      publish(new Remove(elem) with Undoable { def undo = +=(elem) })
+    }
+    this
   }
 
   abstract override def clear(): Unit = {
diff --git a/src/library/scala/collection/mutable/OpenHashMap.scala b/src/library/scala/collection/mutable/OpenHashMap.scala
index 212a05d..86e4b59 100644
--- a/src/library/scala/collection/mutable/OpenHashMap.scala
+++ b/src/library/scala/collection/mutable/OpenHashMap.scala
@@ -1,26 +1,36 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: OpenHashMap.scala 16881 2009-01-09 16:28:11Z cunei $
 
 
-package scala.collection.mutable;
+package scala.collection
+package mutable
 
-object OpenHashMap{
+
+/** 
+ *  @define Coll OpenHashMap
+ *  @define coll open hash map
+ *  
+ *  @since 2.7
+ */
+object OpenHashMap {
   def apply[K, V](elems : (K, V)*) = {
     val dict = new OpenHashMap[K, V];
     elems.foreach({case (x, y) => dict(x) = y});
     dict;
   }
 
-  private[mutable] class Entry[Key, Value](val key : Key, 
-                                           val hash : Int,
-                                           var value : Option[Value])
+  def empty[K, V] = new OpenHashMap[K, V];
+
+  final private class OpenEntry[Key, Value](val key: Key,
+                                            val hash: Int,
+                                            var value: Option[Value])
+                extends HashEntry[Key, OpenEntry[Key, Value]]
 
   private[mutable] def highestOneBit(j : Int) = { // This should really go somewhere central as we're now code sharing by cut and paste. :(
     var i = j;
@@ -35,44 +45,62 @@ object OpenHashMap{
   private[mutable] def nextPowerOfTwo(i : Int) = highestOneBit(i) << 1; 
 }
 
-import OpenHashMap.Entry;
-
-/**
- * A mutable hash map based on an open hashing scheme. The precise scheme is undefined,
- * but it should make a reasonable effort to ensure that an insert with consecutive hash
- * codes is not unneccessarily penalised. In particular, mappings of consecutive integer
- * keys should work without significant performance loss.
- *
- * @author David MacIver
+/** A mutable hash map based on an open hashing scheme. The precise scheme is undefined,
+ *  but it should make a reasonable effort to ensure that an insert with consecutive hash
+ *  codes is not unneccessarily penalised. In particular, mappings of consecutive integer
+ *  keys should work without significant performance loss.
+ *  
+ *  @tparam Key          type of the keys in this map.
+ *  @tparam Value        type of the values in this map.
+ *  @param initialSize   the initial size of the internal hash table.
+ *  
+ *  @author David MacIver
+ *  @since  2.7
+ *  
+ *  @define Coll OpenHashMap
+ *  @define coll open hash map
+ *  @define mayNotTerminateInf
+ *  @define willNotTerminateInf
  */
-class OpenHashMap[Key, Value](initialSize : Int) extends scala.collection.mutable.Map[Key, Value]{
+class OpenHashMap[Key, Value](initialSize : Int)
+extends Map[Key, Value]
+   with MapLike[Key, Value, OpenHashMap[Key, Value]] {
+
+  import OpenHashMap.OpenEntry
+  type Entry = OpenEntry[Key, Value]
+
+  /**
+   * A default constructor creates a hashmap with initial size 8.
+   */
   def this() = this(8);
 
+  override def empty: OpenHashMap[Key, Value] = OpenHashMap.empty[Key, Value]
+
   private[this] val actualInitialSize = OpenHashMap.nextPowerOfTwo(initialSize);
 
   private var mask = actualInitialSize - 1;;
-  private var table : Array[Entry[Key, Value]] = new Array[Entry[Key, Value]](actualInitialSize);
+  private var table : Array[Entry] = new Array[Entry](actualInitialSize);
   private var _size = 0;
   private var deleted = 0; 
  
   // Used for tracking inserts so that iterators can determine in concurrent modification has occurred.
   private[this] var modCount = 0;
 
-  def size = _size;
+  override def size = _size;
   private[this] def size_=(s : Int) = _size = s;
-
+  
+  /** Returns a mangled hash code of the provided key. */
   protected def hashOf(key : Key) = {
-    var h = key.hashCode;
+    var h = key.##
     h ^= ((h >>> 20) ^ (h >>> 12));
     h ^ (h >>> 7) ^ (h >>> 4);
-    h
   }
 
   private[this] def growTable = {
     val oldSize = mask + 1;
     val newSize = 4 * oldSize;
     val oldTable = table;
-    table = new Array[Entry[Key, Value]](newSize);
+    table = new Array[Entry](newSize);
     mask = newSize - 1;     
     oldTable.foreach( entry =>
       if (entry != null && entry.value != None) addEntry(entry));
@@ -96,35 +124,45 @@ class OpenHashMap[Key, Value](initialSize : Int) extends scala.collection.mutabl
     index;
   }
 
-  private[this] def addEntry(entry : Entry[Key, Value]) = 
+  private[this] def addEntry(entry : Entry) = 
     if (entry != null) table(findIndex(entry.key, entry.hash)) = entry;
 
-  def update(key : Key, value : Value){
-    update(key, hashOf(key), value);
+  override def update(key : Key, value : Value) {
+    put(key, hashOf(key), value);
   }
 
-  private def update(key : Key, hash : Int, value : Value) {
+  def += (kv: (Key, Value)): this.type = { put(kv._1, kv._2); this }
+  def -= (key: Key): this.type = { remove(key); this }
+
+  override def put(key : Key, value : Value): Option[Value] = 
+    put(key, hashOf(key), value)
+
+  private def put(key : Key, hash : Int, value : Value): Option[Value] = {
     if (2 * (size + deleted) > mask) growTable;
     val index = findIndex(key, hash);
     val entry = table(index);
     if (entry == null) {
-      table(index) = new Entry(key, hash, Some(value));
+      table(index) = new OpenEntry(key, hash, Some(value));
       modCount += 1;
       size += 1;
-    }
-    else {
+      None
+    } else {
+      val res = entry.value
       if (entry.value == None) { size += 1; modCount += 1 }
       entry.value = Some(value);
+      res
     }
-  } 
+  }
 
-  def -=(key : Key) = {
+  override def remove(key : Key): Option[Value] = {
     val index = findIndex(key);
     if (table(index) != null && table(index).value != None){      
+      val res = table(index).value
       table(index).value = None;
       size -= 1;
       deleted += 1;
-    }
+      res
+    } else None
   }
 
   def get(key : Key) : Option[Value] = {
@@ -148,11 +186,12 @@ class OpenHashMap[Key, Value](initialSize : Int) extends scala.collection.mutabl
     None;
   }
  
-  /**
-   * An iterator over the elements of this map. Use of this iterator follows the same
-   * contract for concurrent modification as the foreach method.
+  /** An iterator over the elements of this map. Use of this iterator follows the same
+   *  contract for concurrent modification as the foreach method.
+   *  
+   *  @return   the iterator
    */ 
-  def elements = new Iterator[(Key, Value)]{
+  def iterator = new Iterator[(Key, Value)]{
     var index = 0;
     val initialModCount = modCount;
 
@@ -171,26 +210,27 @@ class OpenHashMap[Key, Value](initialSize : Int) extends scala.collection.mutabl
     }
   }
 
-  override def clone : OpenHashMap[Key, Value] = {
+  override def clone = {
     val it = new OpenHashMap[Key, Value]
-    foreachUndeletedEntry(entry => it.update(entry.key, entry.hash, entry.value.get));
+    foreachUndeletedEntry(entry => it.put(entry.key, entry.hash, entry.value.get));
     it
   }
 
   /**
-   * Loop over the key, value mappings of this map.
-   *
-   * The behaviour of modifying the map during an iteration is as follows: 
-   *
-   * <ul>
-   *  <li>Deleting a mapping is always permitted.</li>
-   *  <li>Changing the value of mapping which is already present is permitted.</li>
-   *  <li>Anything else is not permitted. It will usually, but not always, throw an exception.</li>
-   * </ul>
-   *
-   * @param  f The function to apply to each key, value mapping.
+   *  Loop over the key, value mappings of this map.
+   *  
+   *  The behaviour of modifying the map during an iteration is as follows: 
+   *  
+   *   <ul>
+   *    <li>Deleting a mapping is always permitted.</li>
+   *    <li>Changing the value of mapping which is already present is permitted.</li>
+   *    <li>Anything else is not permitted. It will usually, but not always, throw an exception.</li>
+   *   </ul>
+   * 
+   *  @tparam U  The return type of the specified function `f`, return result of which is ignored.
+   *  @param f   The function to apply to each key, value mapping.
    */ 
-  override def foreach(f : ((Key, Value)) => Unit){
+  override def foreach[U](f : ((Key, Value)) => U) {
     val startModCount = modCount;
     foreachUndeletedEntry(entry => {
       if (modCount != startModCount) error("Concurrent Modification")
@@ -198,15 +238,19 @@ class OpenHashMap[Key, Value](initialSize : Int) extends scala.collection.mutabl
     );  
   }
 
-  private[this] def foreachUndeletedEntry(f : Entry[Key, Value] => Unit){
+  private[this] def foreachUndeletedEntry(f : Entry => Unit){
     table.foreach(entry => if (entry != null && entry.value != None) f(entry));
   }
-
-  override def transform(f : (Key, Value) => Value) =
+  
+  override def transform(f : (Key, Value) => Value) = {
     foreachUndeletedEntry(entry => entry.value = Some(f(entry.key, entry.value.get)));
+    this
+  }
 
-  override def retain(f : (Key, Value) => Boolean) =
+  override def retain(f : (Key, Value) => Boolean) = {
     foreachUndeletedEntry(entry => if (!f(entry.key, entry.value.get)) {entry.value = None; size -= 1; deleted += 1} );
+    this
+  }
 
   override def stringPrefix = "OpenHashMap"
 }
diff --git a/src/library/scala/collection/mutable/PriorityQueue.scala b/src/library/scala/collection/mutable/PriorityQueue.scala
index b628568..bfa8e11 100644
--- a/src/library/scala/collection/mutable/PriorityQueue.scala
+++ b/src/library/scala/collection/mutable/PriorityQueue.scala
@@ -1,48 +1,120 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: PriorityQueue.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.collection.mutable
+package scala.collection
+package mutable
 
+import generic._
+import annotation.migration
 
-//import Predef.{NoSuchElementException, UnsupportedOperationException}
-
-/** This class implements priority queues using a heap. The
- *  elements of the queue have to be ordered in terms of the
- *  <code>Ordered[T]</code> class.
- *
+/** This class implements priority queues using a heap.
+ *  To prioritize elements of type T there must be an implicit
+ *  Ordering[T] available at creation.
+ *  
+ *  @tparam A    type of the elements in this priority queue.
+ *  @param ord   implicit ordering used to compare the elements of type `A`.
+ *  
  *  @author  Matthias Zenger
  *  @version 1.0, 03/05/2004
+ *  @since   1
+ *  
+ *  @define Coll PriorityQueue
+ *  @define coll priority queue
+ *  @define orderDependent
+ *  @define orderDependentFold
+ *  @define mayNotTerminateInf
+ *  @define willNotTerminateInf
  */
-
 @serializable @cloneable
-class PriorityQueue[A <% Ordered[A]] extends ResizableArray[A] with CloneableCollection {
-  size0 = size0 + 1 // we do not use array(0)
+class PriorityQueue[A](implicit ord: Ordering[A]) 
+      extends Seq[A]
+      with SeqLike[A, PriorityQueue[A]]
+      with Growable[A]
+      with Cloneable[PriorityQueue[A]]
+      with Builder[A, PriorityQueue[A]]
+{
+  import ord._
+
+  private final class ResizableArrayAccess[A] extends ResizableArray[A] {
+    @inline def p_size0 = size0
+    @inline def p_size0_=(s: Int) = size0 = s
+    @inline def p_array = array
+    @inline def p_ensureSize(n: Int) = super.ensureSize(n)
+    @inline def p_swap(a: Int, b: Int) = super.swap(a, b)
+  }
+
+  protected[this] override def newBuilder = new PriorityQueue[A]
+
+  private val resarr = new ResizableArrayAccess[A]
+
+  resarr.p_size0 += 1                           // we do not use array(0)
+  override def length: Int = resarr.length - 1  // adjust length accordingly
+  override def size: Int = length
+  override def isEmpty: Boolean = resarr.p_size0 < 2
+  override def repr = this
+  
+  // hey foreach, our 0th element doesn't exist
+  override def foreach[U](f: A => U) {
+    var i = 1
+    while (i < resarr.p_size0) {
+      f(toA(resarr.p_array(i)))
+      i += 1
+    }
+  }
+
+  def update(idx: Int, elem: A) {
+    if (idx < 0 || idx >= size) throw new IndexOutOfBoundsException("Indices must be nonnegative and lesser than the size.")
+
+    var i = 0
+    val iter = iterator
+    clear
+    while (iter.hasNext) {
+      val curr = iter.next
+      if (i == idx) this += elem
+      else this += curr
+      i += 1
+    }
+  }
 
+  def apply(idx: Int) = {
+    if (idx < 0 || idx >= size) throw new IndexOutOfBoundsException("Indices must be nonnegative and lesser than the size.")
+    
+    var left = idx
+    val iter = iterator
+    var curr = iter.next
+    while (left > 0) {
+      curr = iter.next
+      left -= 1
+    }
+    curr
+  }
+
+  def result = clone
+
+  private def toA(x: AnyRef): A = x.asInstanceOf[A]
   protected def fixUp(as: Array[AnyRef], m: Int): Unit = {
     var k: Int = m
-    while ((k > 1) && (as(k / 2).asInstanceOf[A] < as(k).asInstanceOf[A])) {
-      swap(k, k / 2)
+    while (k > 1 && toA(as(k / 2)) < toA(as(k))) {
+      resarr.p_swap(k, k / 2)
       k = k / 2
-    }
+    }    
   }
-
-  protected def fixDown(as: Array[AnyRef], m: Int, n: Int): Unit = {
+  
+  protected def fixDown(as: Array[AnyRef], m: Int, n: Int): Unit = {    
     var k: Int = m
-    var loop: Boolean = true
-    while (loop && (n >= 2 * k)) {
+    while (n >= 2 * k) {
       var j = 2 * k
-      if ((j < n) && (as(j).asInstanceOf[A] < as(j + 1).asInstanceOf[A]))
-        j = j + 1;
-      if (!(as(k).asInstanceOf[A] < as(j).asInstanceOf[A]))
-        loop = false
+      if (j < n && toA(as(j)) < toA(as(j + 1)))
+        j += 1
+      if (toA(as(k)) >= toA(as(j)))
+        return
       else {
         val h = as(k)
         as(k) = as(j)
@@ -51,57 +123,50 @@ class PriorityQueue[A <% Ordered[A]] extends ResizableArray[A] with CloneableCol
       }
     }
   }
-
-  /** Checks if the queue is empty.
-   *
-   *  @return true, iff there is no element in the queue.
-   */
-  override def isEmpty: Boolean = size0 < 2
-
-  /** Inserts a single element into the priority queue.
-   *
-   *  @param  elem        the element to insert
-   */
-  def +=(elem: A): Unit = {
-    ensureSize(size0+1)
-    array(size0) = elem.asInstanceOf[AnyRef]
-    fixUp(array, size0)
-    size0 = size0 + 1
-  }
-
-  def +(elem: A): PriorityQueue[A] = { this += elem; this }
   
+  @deprecated(
+    "Use += instead if you intend to add by side effect to an existing collection.\n"+
+    "Use `clone() +=' if you intend to create a new collection."
+  )
+  def +(elem: A): PriorityQueue[A] = { this.clone() += elem }
+
   /** Add two or more elements to this set. 
    *  @param    elem1 the first element.
    *  @param    kv2 the second element.
    *  @param    kvs the remaining elements.
    */
-  def += (elem1: A, elem2: A, elems: A*) { this += elem1; this += elem2; this ++= elems }
+  @deprecated(
+    "Use ++= instead if you intend to add by side effect to an existing collection.\n"+
+    "Use `clone() ++=' if you intend to create a new collection."
+  )
+  def +(elem1: A, elem2: A, elems: A*) = { this.clone().+=(elem1, elem2, elems : _*) }
 
-  def + (elem1: A, elem2: A, elems: A*) = { this.+=(elem1, elem2, elems: _*); this }
-
-  /** Adds all elements provided by an <code>Iterable</code> object
-   *  into the priority queue.
+  /** Inserts a single element into the priority queue.
    *
-   *  @param  iter        an iterable object
+   *  @param  elem        the element to insert.
+   *  @return             this $coll.
    */
-  def ++=(iter: Iterable[A]): Unit = this ++= iter.elements
+  def +=(elem: A): this.type = {
+    resarr.p_ensureSize(resarr.p_size0 + 1)
+    resarr.p_array(resarr.p_size0) = elem.asInstanceOf[AnyRef]
+    fixUp(resarr.p_array, resarr.p_size0)
+    resarr.p_size0 += 1
+    this
+  }
 
-  /** Adds all elements provided by an iterator into the priority queue.
+  /** Adds all elements provided by a `TraversableOnce` object
+   *  into the priority queue.
    *
-   *  @param  it        an iterator
+   *  @param  xs    a traversable object.
+   *  @return       a new priority queue containing elements of both `xs` and `this`.
    */
-  def ++=(it: Iterator[A]): Unit = it foreach { e => this += e }
-
-  def ++(iter: Iterable[A]): PriorityQueue[A] = { this ++= iter; this }
-
-  def ++(iter: Iterator[A]): PriorityQueue[A] = { this ++= iter; this }
+  def ++(xs: TraversableOnce[A]) = { this.clone() ++= xs }
 
   /** Adds all elements to the queue.
    *
    *  @param  elems       the elements to add.
    */
-  def enqueue(elems: A*): Unit = (this ++= elems)
+  def enqueue(elems: A*): Unit = { this ++= elems }
 
   /** Returns the element with the highest priority in the queue,
    *  and removes this element from the queue.
@@ -110,11 +175,11 @@ class PriorityQueue[A <% Ordered[A]] extends ResizableArray[A] with CloneableCol
    *  @return   the element with the highest priority.
    */
   def dequeue(): A =
-    if (size0 > 1) {
-      size0 = size0 - 1
-      swap(1, size0)
-      fixDown(array, 1, size0 - 1)
-      array(size0).asInstanceOf[A]
+    if (resarr.p_size0 > 1) {
+      resarr.p_size0 = resarr.p_size0 - 1
+      resarr.p_swap(1, resarr.p_size0)
+      fixDown(resarr.p_array, 1, resarr.p_size0 - 1)
+      toA(resarr.p_array(resarr.p_size0))
     } else
       throw new NoSuchElementException("no element to remove from heap")
 
@@ -123,45 +188,66 @@ class PriorityQueue[A <% Ordered[A]] extends ResizableArray[A] with CloneableCol
    *
    *  @return   the element with the highest priority.
    */
-  def max: A = if (size0 > 1) array(1).asInstanceOf[A] else throw new NoSuchElementException("queue is empty")
+  def max: A = if (resarr.p_size0 > 1) toA(resarr.p_array(1)) else throw new NoSuchElementException("queue is empty")
 
   /** Removes all elements from the queue. After this operation is completed,
    *  the queue will be empty.
    */
-  def clear(): Unit = { size0 = 1 }
+  def clear(): Unit = { resarr.p_size0 = 1 }
 
-  /** Returns an iterator which yiels all the elements of the priority
+  /** Returns an iterator which yields all the elements of the priority
    *  queue in descending priority order.
    *
    *  @return  an iterator over all elements sorted in descending order.
    */
-  override def elements: Iterator[A] = new Iterator[A] {
-    val as: Array[AnyRef] = new Array[AnyRef](size0)
-    Array.copy(array, 0, as, 0, size0)
-    var i = size0 - 1
+  override def iterator: Iterator[A] = new Iterator[A] {
+    val as: Array[AnyRef] = new Array[AnyRef](resarr.p_size0)
+    Array.copy(resarr.p_array, 0, as, 0, resarr.p_size0)
+    var i = resarr.p_size0 - 1
     def hasNext: Boolean = i > 0
     def next(): A = {
-      val res = as(1).asInstanceOf[A]
+      val res = toA(as(1))
       as(1) = as(i)
       i = i - 1
       fixDown(as, 1, i)
       res
     }
   }
-
-  /** Checks if two queues are structurally identical.
-   *
-   *  @return true, iff both queues contain the same sequence of elements.
+  
+  
+  /** Returns the reverse of this queue. The priority queue that gets
+   *  returned will have an inversed ordering - if for some elements
+   *  `x` and `y` the original queue's ordering
+   *  had `compare` returning an integer ''w'', the new one will return ''-w'',
+   *  assuming the original ordering abides its contract.
+   *  
+   *  Note that the order of the elements will be reversed unless the
+   *  `compare` method returns 0. In this case, such elements
+   *  will be subsequent, but their corresponding subinterval may be inappropriately
+   *  reversed. However, due to the compare-equals contract, they will also be equal.
+   *  
+   *  @return   A reversed priority queue.
    */
-  override def equals(obj: Any): Boolean = obj match {
-    case that: PriorityQueue[_] =>
-      (this.elements zip that.elements) forall {
-        case (thiselem, thatelem) => thiselem == thatelem
-      }
-    case _ =>
-      false
+  override def reverse = {
+    val revq = new PriorityQueue[A]()(new math.Ordering[A] {
+      def compare(x: A, y: A) = ord.compare(y, x)
+    })
+    for (i <- 1 until resarr.length) revq += resarr(i)
+    revq
   }
-
+  
+  override def reverseIterator = new Iterator[A] {
+    val arr = new Array[Any](PriorityQueue.this.size)
+    iterator.copyToArray(arr)
+    var i = arr.size - 1
+    def hasNext: Boolean = i >= 0
+    def next(): A = {
+      val curr = arr(i)
+      i -= 1
+      curr.asInstanceOf[A]
+    }
+  }
+  
   /** The hashCode method always yields an error, since it is not
    *  safe to use mutable queues as keys in hash tables.
    *
@@ -172,25 +258,32 @@ class PriorityQueue[A <% Ordered[A]] extends ResizableArray[A] with CloneableCol
 
   /** Returns a regular queue containing the same elements.
    */
-  def toQueue: Queue[A] = {
-    val res = new Queue[A]
-    res ++= this
-    res
-  }
+  def toQueue: Queue[A] = new Queue[A] ++= this.iterator
 
   /** Returns a textual representation of a queue as a string.
    *
    *  @return the string representation of this queue.
    */
   override def toString() = toList.mkString("PriorityQueue(", ", ", ")")
+  override def toList = this.iterator.toList
 
   /** This method clones the priority queue.
    *
    *  @return  a priority queue with the same elements.
    */
-  override def clone(): PriorityQueue[A] = {
-    val res = new PriorityQueue[A]
-    res ++= this
-    res
-  }
+  override def clone(): PriorityQueue[A] = new PriorityQueue[A] ++= this.iterator
+
+  // def printstate {
+  //   println("-----------------------")
+  //   println("Size: " + resarr.p_size0)
+  //   println("Internal array: " + resarr.p_array.toList)
+  //   println(toString)
+  // }
 }
+
+// !!! TODO - but no SortedSeqFactory (yet?)
+// object PriorityQueue extends SeqFactory[PriorityQueue] {  
+//   def empty[A](implicit ord: Ordering[A]): PriorityQueue[A] = new PriorityQueue[A](ord)
+//   implicit def canBuildFrom[A](implicit ord: Ordering[A]): CanBuildFrom[Coll, A, PriorityQueue] = 
+// }
+// 
\ No newline at end of file
diff --git a/src/library/scala/collection/mutable/PriorityQueueProxy.scala b/src/library/scala/collection/mutable/PriorityQueueProxy.scala
index c4e2710..f1b25ab 100644
--- a/src/library/scala/collection/mutable/PriorityQueueProxy.scala
+++ b/src/library/scala/collection/mutable/PriorityQueueProxy.scala
@@ -1,28 +1,26 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: PriorityQueueProxy.scala 16894 2009-01-13 13:09:41Z cunei $
 
+package scala.collection
+package mutable
 
-package scala.collection.mutable
-
-
-/** This class implements priority queues using a heap. The
+/** This class servers as a proxy for priority queues. The
  *  elements of the queue have to be ordered in terms of the
- *  <code>Ordered[T]</code> class.
+ *  `Ordered[T]` class.
  *
  *  @author  Matthias Zenger
  *  @version 1.0, 03/05/2004
+ *  @since   1
  */
-abstract class PriorityQueueProxy[A <% Ordered[A]] extends PriorityQueue[A]
-         with RandomAccessSeqProxy[A]
+abstract class PriorityQueueProxy[A](implicit ord: Ordering[A]) extends PriorityQueue[A]
+         with Proxy
 {
-
   def self: PriorityQueue[A]
 
   /** Creates a new iterator over all elements contained in this
@@ -30,7 +28,7 @@ abstract class PriorityQueueProxy[A <% Ordered[A]] extends PriorityQueue[A]
    *
    *  @return the new iterator
    */
-  override def elements: Iterator[A] = self.elements
+  override def iterator: Iterator[A] = self.iterator
 
   /** Returns the length of this priority queue.
    */
@@ -46,20 +44,16 @@ abstract class PriorityQueueProxy[A <% Ordered[A]] extends PriorityQueue[A]
    *
    *  @param  elem        the element to insert
    */
-  override def +=(elem: A): Unit = self += elem
-
-  /** Adds all elements provided by an <code>Iterable</code> object
-   *  into the priority queue.
-   *
-   *  @param  iter        an iterable object
-   */
-  override def ++=(iter: Iterable[A]): Unit = self ++= iter
+  override def +=(elem: A): this.type = { self += elem; this }
 
   /** Adds all elements provided by an iterator into the priority queue.
    *
    *  @param  it        an iterator
    */
-  override def ++=(it: Iterator[A]): Unit = self ++= it
+  override def ++=(it: TraversableOnce[A]): this.type = {
+    self ++= it
+    this
+  }
 
   /** Adds all elements to the queue.
    *
diff --git a/src/library/scala/collection/mutable/Publisher.scala b/src/library/scala/collection/mutable/Publisher.scala
index a5f6834..223cb7a 100644
--- a/src/library/scala/collection/mutable/Publisher.scala
+++ b/src/library/scala/collection/mutable/Publisher.scala
@@ -1,48 +1,66 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Publisher.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.collection.mutable
+package scala.collection
+package mutable
 
 
-/** <code>Publisher[A,This]</code> objects publish events of type <code>A</code>
+/** `Publisher[A,This]` objects publish events of type `A`
  *  to all registered subscribers. When subscribing, a subscriber may specify
  *  a filter which can be used to constrain the number of events sent to the
  *  subscriber. Subscribers may suspend their subscription, or reactivate a
- *  suspended subscription. Class <code>Publisher</code> is typically used
- *  as a mixin. The type variable <code>This</code> models self types.
+ *  suspended subscription. Class `Publisher` is typically used
+ *  as a mixin. The abstract type `Pub` models the type of the publisher itself.
+ *  
+ *  @tparam Evt      type of the published event.
  *
  *  @author  Matthias Zenger
- *  @version 1.0, 08/07/2003
+ *  @author  Martin Odersky
+ *  @version 2.8
+ *  @since   1
  */
-trait Publisher[A, This <: Publisher[A, This]] { self: This =>
-  private val filters = new HashMap[Subscriber[A, This],
-                                    scala.collection.mutable.Set[A => Boolean]]
-                            with MultiMap[Subscriber[A, This], A => Boolean]
-  private val suspended = new HashSet[Subscriber[A, This]]
+trait Publisher[Evt] { 
 
-  def subscribe(sub: Subscriber[A, This]): Unit =
-    subscribe(sub, event => true)
+  type Pub <: Publisher[Evt]
+  type Sub = Subscriber[Evt, Pub]
+  type Filter = Evt => Boolean
 
-  def subscribe(sub: Subscriber[A, This], filter: A => Boolean): Unit =
-    filters.add(sub, filter)
-
-  def suspendSubscription(sub: Subscriber[A, This]): Unit = suspended += sub
-
-  def activateSubscription(sub: Subscriber[A, This]): Unit = suspended -= sub
-
-  def removeSubscription(sub: Subscriber[A, This]): Unit = filters -= sub
+  /** The publisher itself of type `Pub'. Implemented by a cast from `this' here.
+   *  Needs to be overridden if the actual publisher is different from `this'.
+   */
+  protected val self: Pub = this.asInstanceOf[Pub]
+  
+  private val filters = new HashMap[Sub, Set[Filter]] with MultiMap[Sub, Filter]
+  private val suspended = new HashSet[Sub]
 
+  def subscribe(sub: Sub) { subscribe(sub, event => true) }
+  def subscribe(sub: Sub, filter: Filter) { filters.addBinding(sub, filter) }
+  def suspendSubscription(sub: Sub) { suspended += sub }
+  def activateSubscription(sub: Sub) { suspended -= sub }
+  def removeSubscription(sub: Sub) { filters -= sub }
   def removeSubscriptions() { filters.clear }
 
-  protected def publish(event: A): Unit =
+  protected def publish(event: Evt) {
     filters.keys.foreach(sub =>
-      if (filters.entryExists(sub, p => p(event))) sub.notify(this, event))
+      if (!suspended.contains(sub) &&
+          filters.entryExists(sub, p => p(event)))
+        sub.notify(self, event)
+    )
+  }
+
+  /** Checks if two publishers are structurally identical.
+   *
+   *  @return true, iff both publishers contain the same sequence of elements.
+   */
+  override def equals(obj: Any): Boolean = obj match {
+    case that: Publisher[_] => filters == that.filters && suspended == that.suspended
+    case _                  => false
+  }
 }
diff --git a/src/library/scala/collection/mutable/Queue.scala b/src/library/scala/collection/mutable/Queue.scala
index 02352ff..0444650 100644
--- a/src/library/scala/collection/mutable/Queue.scala
+++ b/src/library/scala/collection/mutable/Queue.scala
@@ -1,61 +1,40 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Queue.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.collection.mutable
+package scala.collection
+package mutable
 
+import generic._
 
-//import Predef.{NoSuchElementException, UnsupportedOperationException}
-
-/** <code>Queue</code> objects implement data structures that allow to
+/** `Queue` objects implement data structures that allow to
  *  insert and retrieve elements in a first-in-first-out (FIFO) manner.
  *
  *  @author  Matthias Zenger
- *  @version 1.1, 03/05/2004
+ *  @author  Martin Odersky
+ *  @version 2.8
+ *  @since   1
+ *  
+ *  @define Coll mutable.Queue
+ *  @define coll mutable queue
+ *  @define orderDependent 
+ *  @define orderDependentFold
+ *  @define mayNotTerminateInf
+ *  @define willNotTerminateInf
  */
 @serializable @cloneable
-class Queue[A] extends MutableList[A] with CloneableCollection {
-
-  /** Checks if the queue is empty.
-   *
-   *  @return true, iff there is no element in the queue.
-   */
-  override def isEmpty: Boolean = (first0 eq null)
-
-  /** Inserts a single element at the end of the queue.
-   *
-   *  @param  elem        the element to insert
-   */
-  def +=(elem: A): Unit = appendElem(elem)
-
-  /** Adds all elements provided by an <code>Iterable</code> object
-   *  at the end of the queue. The elements are prepended in the order they
-   *  are given out by the iterator.
-   *
-   *  @param  iter        an iterable object
-   */
-  def ++=(iter: Iterable[A]): Unit = this ++= iter.elements
-
-  /** Adds all elements provided by an iterator
-   *  at the end of the queue. The elements are prepended in the order they
-   *  are given out by the iterator.
-   *
-   *  @param  it        an iterator
-   */
-  def ++=(it: Iterator[A]): Unit = it foreach appendElem
-
+class Queue[A] extends MutableList[A] with Cloneable[Queue[A]] {
   /** Adds all elements to the queue.
    *
    *  @param  elems       the elements to add.
    */
-  def enqueue(elems: A*): Unit = (this ++= elems)
+  def enqueue(elems: A*): Unit = this ++= elems
 
   /** Returns the first element in the queue, and removes this element
    *  from the queue.
@@ -64,13 +43,12 @@ class Queue[A] extends MutableList[A] with CloneableCollection {
    *  @return the first element of the queue.
    */
   def dequeue(): A =
-    if (first0 eq null)
+    if (isEmpty)
       throw new NoSuchElementException("queue empty")
     else {
       val res = first0.elem
       first0 = first0.next
-      if (first0 eq null) last0 = null
-      len = len - 1
+      len -= 1
       res
     }
 
@@ -81,23 +59,32 @@ class Queue[A] extends MutableList[A] with CloneableCollection {
    *  @return the first element of the queue for which p yields true
    */
   def dequeueFirst(p: A => Boolean): Option[A] =
-    if (first0 eq null)
+    if (isEmpty)
       None
     else if (p(first0.elem)) {
       val res: Option[A] = Some(first0.elem)
       first0 = first0.next
-      len = len - 1
-      if (first0 eq null) {
-        last0 = null
-      } else if (first0.next eq null) {
-        last0 = first0
-      }
+      len -= 1
       res
-    } else
-      extractFirst(first0, p) match {
-        case None => None
-        case Some(cell) => Some(cell.elem)
-      }
+    } else {
+      val optElem = removeFromList(p)
+      if (optElem != None) len -= 1
+      optElem
+    }
+
+  private def removeFromList(p: A => Boolean): Option[A] = {
+    var leftlst = first0
+    var res: Option[A] = None
+    while (leftlst.next.nonEmpty && !p(leftlst.next.elem)) {
+      leftlst = leftlst.next
+    }
+    if (leftlst.next.nonEmpty) {
+      res = Some(leftlst.next.elem)
+      if (leftlst.next eq last0) last0 = leftlst
+      leftlst.next = leftlst.next.next
+    }
+    res
+  }
 
   /** Returns all elements in the queue which satisfy the
    *  given predicate, and removes those elements from the queue.
@@ -107,44 +94,49 @@ class Queue[A] extends MutableList[A] with CloneableCollection {
    *             p yields true.
    */
   def dequeueAll(p: A => Boolean): Seq[A] = {
-    if (first0 eq null)
+    if (first0.isEmpty)
       Seq.empty
     else {
       val res = new ArrayBuffer[A]
-      while ((first0 ne null) && p(first0.elem)) {
+      while ((first0.nonEmpty) && p(first0.elem)) {
         res += first0.elem
         first0 = first0.next
-        len = len - 1
-        if (first0 eq null) {
-          last0 = null
-        } else if (first0.next eq null) {
-          last0 = first0
-        }
-      }
-      var cell: Option[LinkedList[A]] = extractFirst(first0, p)
-      while (!cell.isEmpty) {
-        res += cell.get.elem
-        cell = extractFirst(cell.get, p)
+        len -= 1
       }
-      res
+      if (first0.isEmpty) res
+      else removeAllFromList(p, res)
     }
   }
 
-  private def extractFirst(start: LinkedList[A], p: A => Boolean): Option[LinkedList[A]] = {
+  private def removeAllFromList(p: A => Boolean, res: ArrayBuffer[A]): ArrayBuffer[A] = {
+    var leftlst = first0
+    while (leftlst.next.nonEmpty) {
+      if (p(leftlst.next.elem)) {
+	res += leftlst.next.elem
+	if (leftlst.next eq last0) last0 = leftlst
+	leftlst.next = leftlst.next.next
+	len -= 1
+      } else leftlst = leftlst.next
+    }
+    res
+  }
+
+  /** Return the proper suffix of this list which starts with the first element that satisfies `p`.
+   *  That element is unlinked from the list. If no element satisfies `p`, return None.
+   */
+  def extractFirst(start: LinkedList[A], p: A => Boolean): Option[LinkedList[A]] = {
     if (isEmpty) None
     else {
       var cell = start
-      while ((cell.next ne null) && !p(cell.next.elem)) {
+      while ((cell.next.nonEmpty) && !p(cell.next.elem)) {
         cell = cell.next
       }
-      if (cell.next eq null)
+      if (cell.next.isEmpty)
         None
       else {
         val res: Option[LinkedList[A]] = Some(cell.next)
         cell.next = cell.next.next
-        if (cell.next eq null)
-          last0 = cell
-        len = len - 1
+        len -= 1
         res
       }
     }
@@ -156,47 +148,9 @@ class Queue[A] extends MutableList[A] with CloneableCollection {
    *  @return the first element.
    */
   def front: A = first0.elem
+}
 
-  /** Removes all elements from the queue. After this operation is completed,
-   *  the queue will be empty.
-   */
-  def clear(): Unit = reset
-
-  /** Checks if two queues are structurally identical.
-   *
-   *  @return true, iff both queues contain the same sequence of elements.
-   */
-  override def equals(obj: Any): Boolean = obj match {
-    case that: Queue[_] =>
-      (this.elements zip that.elements) forall {
-        case (thiselem, thatelem) => thiselem == thatelem
-      }
-    case _ =>
-      false
-  }
-
-  /** The hashCode method always yields an error, since it is not
-   *  safe to use mutable queues as keys in hash tables.
-   *
-   *  @throws Predef.UnsupportedOperationException
-   *  @return never.
-   */
-  override def hashCode(): Int =
-    throw new UnsupportedOperationException("unsuitable as hash key")
-
-  /** Returns a textual representation of a queue as a string.
-   *
-   *  @return the string representation of this queue.
-   */
-  override def toString() = toList.mkString("Queue(", ", ", ")")
-
-  /** This method clones the queue.
-   *
-   *  @return  a queue with the same elements.
-   */
-  override def clone(): Queue[A] = {
-    val res = new Queue[A]
-    res ++= this
-    res
-  }
+// !!! TODO - integrate
+object Queue {
+  def apply[A](xs: A*): Queue[A] = new Queue[A] ++= xs
 }
diff --git a/src/library/scala/collection/mutable/QueueProxy.scala b/src/library/scala/collection/mutable/QueueProxy.scala
index afe3f18..9444dfd 100644
--- a/src/library/scala/collection/mutable/QueueProxy.scala
+++ b/src/library/scala/collection/mutable/QueueProxy.scala
@@ -1,24 +1,26 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: QueueProxy.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.collection.mutable
+package scala.collection
+package mutable
 
-
-/** <code>Queue</code> objects implement data structures that allow to
+/** `Queue` objects implement data structures that allow to
  *  insert and retrieve elements in a first-in-first-out (FIFO) manner.
- *
+ *  
+ *  @tparam A   type of the elements in this queue proxy.
+ *  
  *  @author  Matthias Zenger
  *  @version 1.1, 03/05/2004
+ *  @since   1
  */
-trait QueueProxy[A] extends Queue[A] with SeqProxy[A] {
+trait QueueProxy[A] extends Queue[A] with Proxy {
 
   def self: Queue[A]
 
@@ -42,15 +44,7 @@ trait QueueProxy[A] extends Queue[A] with SeqProxy[A] {
    *
    *  @param  elem        the element to insert
    */
-  override def +=(elem: A): Unit = self += elem
-
-  /** Adds all elements provided by an <code>Iterable</code> object
-   *  at the end of the queue. The elements are prepended in the order they
-   *  are given out by the iterator.
-   *
-   *  @param  iter        an iterable object
-   */
-  override def ++=(iter: Iterable[A]): Unit = self ++= iter
+  override def +=(elem: A): this.type = { self += elem; this }
 
   /** Adds all elements provided by an iterator
    *  at the end of the queue. The elements are prepended in the order they
@@ -58,7 +52,10 @@ trait QueueProxy[A] extends Queue[A] with SeqProxy[A] {
    *
    *  @param  iter        an iterator
    */
-  override def ++=(it: Iterator[A]): Unit = self ++= it
+  override def ++=(it: TraversableOnce[A]): this.type = {
+    self ++= it
+    this
+  }
 
   /** Adds all elements to the queue.
    *
@@ -89,7 +86,7 @@ trait QueueProxy[A] extends Queue[A] with SeqProxy[A] {
    *
    *  @return an iterator over all queue elements.
    */
-  override def elements: Iterator[A] = self.elements
+  override def iterator: Iterator[A] = self.iterator
 
   /** This method clones the queue.
    *
diff --git a/src/library/scala/collection/mutable/ResizableArray.scala b/src/library/scala/collection/mutable/ResizableArray.scala
index cc29d1b..9b44467 100644
--- a/src/library/scala/collection/mutable/ResizableArray.scala
+++ b/src/library/scala/collection/mutable/ResizableArray.scala
@@ -1,85 +1,102 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: ResizableArray.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.collection.mutable
+package scala.collection
+package mutable
 
-import Predef._
+import generic._
 
 /** This class is used internally to implement data structures that
  *  are based on resizable arrays.
- *  //todo enrich with more efficient operations
+ *  
+ *  @tparam A    type of the elements contained in this resizeable array.
  *
  *  @author  Matthias Zenger, Burak Emir
- *  @version 1.0, 03/05/2004
+ *  @author Martin Odersky
+ *  @version 2.8
+ *  @since   1
  */
-trait ResizableArray[A] extends RandomAccessSeq[A] {
+trait ResizableArray[A] extends IndexedSeq[A] 
+                           with GenericTraversableTemplate[A, ResizableArray]
+                           with IndexedSeqOptimized[A, ResizableArray[A]] { 
+
+  override def companion: GenericCompanion[ResizableArray] = ResizableArray
 
   protected def initialSize: Int = 16
-  protected var array: Array[AnyRef] = new Array[AnyRef](initialSize)
-  private var size1: Int = 0
-  protected def size0: Int = size1
-  protected def size0_=(sz: Int) { size1 = sz }
+  protected var array: Array[AnyRef] = new Array[AnyRef](math.max(initialSize, 1))
+
+  protected var size0: Int = 0
 
   //##########################################################################
-  // implement/override methods of Seq[A]
+  // implement/override methods of IndexedSeq[A]
 
   /** Returns the length of this resizable array.
    */
   def length: Int = size0
 
-  def apply(i: Int) = array(i).asInstanceOf[A]
+  def apply(idx: Int) = {
+    if (idx >= size0) throw new IndexOutOfBoundsException(idx.toString)
+    array(idx).asInstanceOf[A]
+  }
 
-  /** remove elements of this array at indices after <code>sz</code> 
-   */
-  def reduceToSize(sz: Int) {
-    if (sz > size0) throw new IllegalArgumentException
-    size0 = sz
+  def update(idx: Int, elem: A) { 
+    if (idx >= size0) throw new IndexOutOfBoundsException(idx.toString)
+    array(idx) = elem.asInstanceOf[AnyRef]
   }
 
-  /** Fills the given array <code>xs</code> with the elements of
-   *  this sequence starting at position <code>start</code>.
+  override def foreach[U](f: A =>  U) {
+    var i = 0
+    while (i < size) {
+      f(array(i).asInstanceOf[A])
+      i += 1
+    }
+  }
+
+  /** Fills the given array <code>xs</code> with at most `len` elements of
+   *  this traversable starting at position `start`.
+   *  Copying will stop once either the end of the current traversable is reached or
+   *  `len` elements have been copied or the end of the array is reached.
    *
    *  @param  xs the array to fill.
    *  @param  start starting index.
+   *  @param  len number of elements to copy
    */
-  override def copyToArray[B >: A](xs: Array[B], start: Int) {
-    Array.copy(array, 0, xs, start, size0)
-  }
+   override def copyToArray[B >: A](xs: Array[B], start: Int, len: Int) {
+     val len1 = len min (xs.length - start) min length
+     Array.copy(array, 0, xs, start, len1)
+   }
 
-  /** Copy all elements to a buffer 
-   *  @param   The buffer to which elements are copied
-   */
-  override def copyToBuffer[B >: A](dest: Buffer[B]) {
-    dest.++=(runtime.ScalaRunTime.boxArray(array).asInstanceOf[Array[B]], 0, size0)
-  }
+  //##########################################################################
 
-  /** Returns a new iterator over all elements of this resizable array.
+  /** remove elements of this array at indices after <code>sz</code> 
    */
-  override def elements: Iterator[A] = new Iterator[A] {
-    var i = 0
-    def hasNext: Boolean = i < size0
-    def next(): A = { i = i + 1; array(i - 1).asInstanceOf[A] }
+  def reduceToSize(sz: Int) {
+    require(sz <= size0)
+    while (size0 > sz) {
+      size0 -= 1
+      array(size0) = null
+    }
   }
 
-  //##########################################################################
-
   /** ensure that the internal array has at n cells */
   protected def ensureSize(n: Int) {
     if (n > array.length) {
       var newsize = array.length * 2
       while (n > newsize)
         newsize = newsize * 2
+    // println("Internal array before, size " + size0 + ": " + array.toList)
       val newar: Array[AnyRef] = new Array(newsize)
       Array.copy(array, 0, newar, 0, size0)
+    // println("Internal array after,  size " + size0 + ": " + array.toList)
       array = newar
+    // println("New array after,  size      " + size0 + ": " + newar.toList)
     }
   }
 
@@ -97,3 +114,8 @@ trait ResizableArray[A] extends RandomAccessSeq[A] {
     Array.copy(array, m, array, n, len)
   }
 }
+
+object ResizableArray extends SeqFactory[ResizableArray] {
+  implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, ResizableArray[A]] = new GenericCanBuildFrom[A]
+  def newBuilder[A]: Builder[A, ResizableArray[A]] = new ArrayBuffer[A]
+}
diff --git a/src/library/scala/collection/mutable/RevertableHistory.scala b/src/library/scala/collection/mutable/RevertableHistory.scala
deleted file mode 100644
index 77bce23..0000000
--- a/src/library/scala/collection/mutable/RevertableHistory.scala
+++ /dev/null
@@ -1,33 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: RevertableHistory.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala.collection.mutable
-
-
-/** A revertable history is a <code>History</code> object which supports
- *  an undo operation. Type variable <code>A</code> refers to the type
- *  of the published events, <code>B</code> denotes the publisher type.
- *  Type <code>B</code> is typically a subtype of <code>Publisher</code>.
- *  
- *  @author  Matthias Zenger
- *  @version 1.0, 08/07/2003
- */
- at serializable
-class RevertableHistory[A <: Undoable, B] extends History[A, B] with Undoable {
-
-  /** Rollback the full history.
-   */
-  def undo: Unit = {
-    val old = log.toList.reverse
-    clear
-    old.foreach { case (sub, event) => event.undo }
-  }
-}
diff --git a/src/library/scala/collection/mutable/RevertibleHistory.scala b/src/library/scala/collection/mutable/RevertibleHistory.scala
new file mode 100644
index 0000000..922ce61
--- /dev/null
+++ b/src/library/scala/collection/mutable/RevertibleHistory.scala
@@ -0,0 +1,37 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+package mutable
+
+
+/** A revertible history is a `History` object which supports
+ *  an undo operation. Type variable `Evt` refers to the type
+ *  of the published events, `Pub` denotes the publisher type.
+ *  Type `Pub` is typically a subtype of `Publisher`.
+ *  
+ *  @tparam Evt   type of the events
+ *  @tparam Pub   type of the publisher
+ *  
+ *  @author  Matthias Zenger
+ *  @version 1.0, 08/07/2003
+ *  @since   2.8
+ */
+ at serializable
+class RevertibleHistory[Evt <: Undoable, Pub] extends History[Evt, Pub] with Undoable {
+
+  /** Rollback the full history.
+   */
+  def undo: Unit = {
+    val old = log.toList.reverse
+    clear
+    old.foreach { case (sub, event) => event.undo }
+  }
+}
diff --git a/src/library/scala/collection/mutable/Scriptable.scala b/src/library/scala/collection/mutable/Scriptable.scala
deleted file mode 100644
index 628adba..0000000
--- a/src/library/scala/collection/mutable/Scriptable.scala
+++ /dev/null
@@ -1,26 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://www.scala-lang.org/           **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: Scriptable.scala 16881 2009-01-09 16:28:11Z cunei $
-
-
-package scala.collection.mutable
-
-
-/** Classes that mix in the <code>Scriptable</code> class allow
- *  messages to be sent to objects of that class.
- *
- *  @author  Matthias Zenger
- *  @version 1.0, 09/05/2004
- */
-trait Scriptable[A] {
-
-    /** Send a message to this scriptable object.
-     */
-    def <<(cmd: A): Unit
-}
diff --git a/src/library/scala/collection/mutable/Seq.scala b/src/library/scala/collection/mutable/Seq.scala
new file mode 100644
index 0000000..4ce8cf4
--- /dev/null
+++ b/src/library/scala/collection/mutable/Seq.scala
@@ -0,0 +1,50 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+package mutable
+
+import generic._
+
+
+/** A subtrait of `collection.Seq` which represents sequences
+ *  that can be mutated.
+ *
+ *  $seqInfo
+ * 
+ *  The class adds an `update` method to `collection.Seq`.
+ *  
+ *  @define Coll mutable.Seq
+ *  @define coll mutable sequence
+ */
+trait Seq[A] extends Iterable[A] 
+                     with scala.collection.Seq[A] 
+                     with GenericTraversableTemplate[A, Seq]
+                     with SeqLike[A, Seq[A]] { 
+  override def companion: GenericCompanion[Seq] = Seq
+
+  /** Replaces element at given index with a new value.
+   *
+   *  @param n       the index of the element to replace.
+   *  @param lem     the new value.
+   *  @throws   IndexOutofBoundsException if the index is not valid.
+   */
+  def update(idx: Int, elem: A)
+}
+
+/** $factoryInfo
+ *  The current default implementation of a $Coll is an `ArrayBuffer`.
+ *  @define coll mutable sequence
+ *  @define Coll mutable.Seq
+ */
+object Seq extends SeqFactory[Seq] {
+  implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, Seq[A]] = new GenericCanBuildFrom[A]
+  def newBuilder[A]: Builder[A, Seq[A]] = new ArrayBuffer
+}
diff --git a/src/library/scala/collection/mutable/Set.scala b/src/library/scala/collection/mutable/Set.scala
index 8a1bd90..f57287d 100644
--- a/src/library/scala/collection/mutable/Set.scala
+++ b/src/library/scala/collection/mutable/Set.scala
@@ -1,216 +1,38 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Set.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.collection.mutable
+package scala.collection
+package mutable
 
-import Predef._
+import generic._
 
-
-/** The canonical factory methods for <a href="Set.html">mutable sets</a>.
- *  Currently these return <a href="HashSet.html">HashSet's</a>.
+/** A base trait for sets that can be mutated.
+ *  $setNote
+ *  $setTags
+ *  @since 1.0
+ *  @author Matthias Zenger
  */
-object Set {
-
-  /** The empty map of this type; this is implemented as a hashtable */  
-  def empty[A]: Set[A] = new HashSet[A]
-
-  /** The canonical factory for this type
-   */
-  def apply[A](elems: A*) = empty[A] ++ elems
+trait Set[A] extends Iterable[A]
+                with scala.collection.Set[A]
+                with GenericSetTemplate[A, Set]
+                with SetLike[A, Set[A]] {
+  override def companion: GenericCompanion[Set] = Set
 }
-
-/** This class represents mutable sets. Concrete set implementations
- *  just have to provide functionality for the abstract methods in
- *  <a href="../Set.html" target="contentFrame">
- *  <code>scala.collection.Set</code></a> as well as for <code>+=</code>,
- *  <code>-= and <code>clear</code>.
- *
- *  @author  Matthias Zenger
- *  @version 1.1, 09/05/2004
+                
+/** $factoryInfo
+ *  The current default implementation of a $Coll is a `HashSet`.
+ *  @define coll mutable set
+ *  @define Coll mutable.Set
  */
- at cloneable
-trait Set[A] extends collection.Set[A] with Scriptable[Message[A]] with CloneableCollection {
-
-  /** This method allows one to add or remove an element <code>elem</code>
-   *  from this set depending on the value of parameter <code>included</code>.
-   *  Typically, one would use the following syntax:
-   *  <pre>set(elem) = true</pre>
-   *
-   */
-  def update(elem: A, included: Boolean) {
-    if (included) this += elem else this -= elem
-  }
-
-  /** Add a new element to the set.
-   *
-   *  @param elem the element to be added
-   */
-  def +=(elem: A)
-
-  /** Add two or more elements to this set. 
-   *  @param    elem1 the first element.
-   *  @param    elem2 the second element.
-   *  @param    elems the remaining elements.
-   */
-  def += (elem1: A, elem2: A, elems: A*) { this += elem1; this += elem2; this ++= elems }
-
-  /** Add all the elements provided by an iterator
-   *  of the iterable object <code>that</code> to the set.
-   *  @param elems  the iterable object containing the elements to be added 
-   */
-  def ++=(elems: Iterable[A]): Unit = ++=(elems.elements)
-
-  /** Add all the elements provided by an iterator
-   *  <code>elems</code> to the set.
-   *  @param elems  the iterator containing the elements to be added 
-   */
-  def ++=(elems: Iterator[A]) { elems foreach += }
-
-  /** Add a new element to the set.
-   *  @return the set itself with the element added.
-   *
-   *  @param elem the element to be added
-   */
-  def + (elem: A): Set[A] = { +=(elem); this }
-
-  /** Add two or more elements to this set. 
-   *  @param    elem1 the first element.
-   *  @param    kv2 the second element.
-   *  @param    kvs the remaining elements.
-   *  @return the set itself with the elements added.
-   */
-  def + (elem1: A, elem2: A, elems: A*): Set[A] = { this.+=(elem1, elem2, elems: _*); this }
-
-  /** Add all the elements provided by an iterator
-   *  of the iterable object <code>elems</code> to the set.
-   *
-   *  @param elems  the iterable object containing the elements to be added 
-   *  @return the set itself with the elements added.
-   */
-  def ++ (elems: Iterable[A]): Set[A] = { this ++= elems; this }
-
-  /** Add all the elements provided by an iterator
-   *  <code>elems</code> to the set.
-   *  @param elems  the iterator containing the elements to be added 
-   */
-  def ++ (elems: Iterator[A]): Set[A] = { this ++= elems; this }
-
-  /** <code>incl</code> can be used to add many elements to the set
-   *  at the same time.
-   *  @deprecated   use <code>++=</code> instead
-   */
-  @deprecated
-  def incl(elems: A*): Unit = ++=(elems.elements)
-
-  /** Removes a single element from a set. 
-   *  @param elem  The element to be removed.
-   */
-  def -=(elem: A)
-
-  /** Remove two or more elements from this set. 
-   *  @param    elem1 the first element.
-   *  @param    elem2 the second element.
-   *  @param    elems the remaining elements.
-   */
-  def -= (elem1: A, elem2: A, elems: A*) { this -= elem1; this -= elem2; this --= elems }
-
-  /** Remove all the elements provided by an iterator
-   *  of the iterable object <code>elems</code> from the set.
-   */
-  def --=(elems: Iterable[A]): Unit = --=(elems.elements)
-
-  /** Remove all the elements provided by an iterator
-   *  <code>elems</code> from the set.
-   */
-  def --=(elems: Iterator[A]) { elems foreach -= }
-
-  /** Remove a new element from the set.
-   *  @return the set itself with the element removed.
-   *
-   *  @param elem the element to be removed
-   */
-  def - (elem: A): Set[A] = { -=(elem); this }
-
-  /** Remove two or more elements from this set. 
-   *  @param    elem1 the first element.
-   *  @param    elem2 the second element.
-   *  @param    elems the remaining elements.
-   *  @return the set itself with the elements removed.
-   */
-  def - (elem1: A, elem2: A, elems: A*): Set[A] = { this.-=(elem1, elem2, elems: _*); this }
-
-  /** Remove all the elements provided by an iterator
-   *  of the iterable object <code>elems</code> from the set.
-   *
-   *  @param elems An iterable object containing the elements to remove from the set.
-   *  @return the set itself with the elements removed.
-   */
-  def -- (elems: Iterable[A]): Set[A] = { this --= elems; this }
-
-  /** Remove all the elements provided by an iterator
-   *  <code>elems</code> from the set.
-   *  @param elems An iterator containing the elements to remove from the set.
-   *  @return the set itself with the elements removed.
-   */
-  def -- (elems: Iterator[A]): Set[A] = { this --= elems; this }
-
-  /** <code>excl</code> removes many elements from the set.
-   */
-  @deprecated
-  def excl(elems: A*): Unit = --=(elems.elements)
-
-  /** This method computes an intersection with set <code>that</code>.
-   *  It removes all the elements that are not present in <code>that</code>.
-   *
-   *  @param that the set to intersect with.
-   */
-  def intersect(that: Set[A]) { retain(that.contains) }
-
-  /** Method <code>retain removes all elements from the set for
-   *  which the predicate <code>p</code> yields the value <code>false</code>.
-   */
-  def retain(p: A => Boolean): Unit = toList.foreach {
-    elem => if (!p(elem)) -=(elem)
-  }
-
-  /** Removes all elements from the set. After this operation is completed,
-   *  the set will be empty.
-   */
-  def clear() { elements foreach -= }
-
-  /** Send a message to this scriptable object.
-   *
-   *  @param cmd  the message to send.
-   *  @throws <code>Predef.UnsupportedOperationException</code>
-   *  if the message was not understood.
-   */
-  def <<(cmd: Message[A]): Unit = cmd match {
-    case Include(elem) => this += elem
-    case Remove(elem) => this -= elem
-    case Reset() => clear
-    case s: Script[_] => s.elements foreach <<
-    case _ => throw new UnsupportedOperationException("message " + cmd + " not understood")
-  }
-
-  /** Return a clone of this set.
-   *
-   *  @return  a set with the same elements.
-   */
-  override def clone(): Set[A] = super.clone().asInstanceOf[Set[A]]
-
-  /** Return a read-only projection of this set */
-  def readOnly : scala.collection.Set[A] = new scala.collection.Set[A] {
-    def contains(item : A) = Set.this.contains(item)
-    override def toString = "ro-" + Set.this.toString
-    override def size = Set.this.size
-    override def elements = Set.this.elements
-  }
+object Set extends MutableSetFactory[Set] {
+  implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, Set[A]] = setCanBuildFrom[A]
+  override def empty[A]: Set[A] = HashSet.empty[A]
 }
+
diff --git a/src/library/scala/collection/mutable/SetBuilder.scala b/src/library/scala/collection/mutable/SetBuilder.scala
new file mode 100644
index 0000000..2400a5e
--- /dev/null
+++ b/src/library/scala/collection/mutable/SetBuilder.scala
@@ -0,0 +1,23 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+package scala.collection
+package mutable
+
+import generic._
+
+/** The canonical builder for mutable Sets.
+ *  
+ *  @tparam A      The type of the elements that will be contained in this set.
+ *  @tparam Coll   The type of the actual collection this set builds.
+ *  @param empty   The empty element of the collection.
+ *  @since 2.8
+ */
+class SetBuilder[A, Coll <: Addable[A, Coll] with collection.Iterable[A] with collection.IterableLike[A, Coll]](empty: Coll) 
+extends AddingBuilder[A, Coll](empty) { }
diff --git a/src/library/scala/collection/mutable/SetLike.scala b/src/library/scala/collection/mutable/SetLike.scala
new file mode 100644
index 0000000..77521bf
--- /dev/null
+++ b/src/library/scala/collection/mutable/SetLike.scala
@@ -0,0 +1,236 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+package mutable
+
+import generic._
+import script._
+import scala.annotation.migration
+
+/** A template trait for mutable sets of type `mutable.Set[A]`.
+ *  @tparam A    the type of the elements of the set
+ *  @tparam This the type of the set itself.
+ *
+ *  $setnote
+ * 
+ *  @author  Martin Odersky
+ *  @version 2.8
+ *  @since 2.8
+ *
+ *  @define setnote
+ *  @note
+ *    This trait provides most of the operations of a `mutable.Set` independently of its representation.
+ *    It is typically inherited by concrete implementations of sets.
+ * 
+ *    To implement a concrete mutable set, you need to provide implementations
+ *    of the following methods:
+ *    {{{
+ *       def contains(elem: A): Boolean
+ *       def iterator: Iterator[A]
+ *       def += (elem: A): this.type
+ *       def -= (elem: A): this.type</pre>
+ *    }}}
+ *    If you wish that methods like `take`,
+ *    `drop`, `filter` return the same kind of set,
+ *    you should also override:
+ *    {{{
+ *       def empty: This</pre>
+ *    }}}
+ *    It is also good idea to override methods `foreach` and
+ *    `size` for efficiency.
+ *  @define addDuplicates
+ *    Note that duplicates (elements for which `equals` yields true) will be
+ *    removed, but it is not specified whether it will be an element of this
+ *    set or a newly added element.
+ *  @define coll mutable set
+ *  @define Coll mutable.Set
+ */
+trait SetLike[A, +This <: SetLike[A, This] with Set[A]] 
+  extends scala.collection.SetLike[A, This]
+     with Scriptable[A]
+     with Builder[A, This]
+     with Growable[A]
+     with Shrinkable[A] 
+     with Cloneable[mutable.Set[A]] 
+{ self =>
+  
+  /** A common implementation of `newBuilder` for all mutable sets
+   *  in terms of `empty`. Overrides the implementation in `collection.SetLike`
+   *  for better efficiency.
+   */
+  override protected[this] def newBuilder: Builder[A, This] = empty
+  
+  @migration(2, 8, "Set.map now returns a Set, so it will discard duplicate values.")
+  override def map[B, That](f: A => B)(implicit bf: CanBuildFrom[This, B, That]): That = super.map(f)(bf)
+
+  /** Adds an element to this $coll.
+   *
+   *  @param elem the element to be added
+   *  @return `true` if the element was not yet present in the set, `false` otherwise.
+   */
+  def add(elem: A): Boolean = {
+    val r = contains(elem)
+    this += elem
+    r
+  }
+
+  /** Removes an element from this set.
+   *
+   *  @param elem  The element to be removed.
+   *  @return  `true` if the element was previously present in the set, `false` otherwise.
+   */
+  def remove(elem: A): Boolean = {
+    val r = contains(elem)
+    this -= elem
+    r
+  }
+
+  /** Updates the presence of a single element in this set.
+   *
+   * This method allows one to add or remove an element `elem`
+   *  from this set depending on the value of parameter `included`.
+   *  Typically, one would use the following syntax:
+   *  {{{
+   *     set(elem) = true  // adds element
+   *     set(elem) = false // removes element
+   *  }}}
+   *
+   *  @param elem     the element to be added or removed
+   *  @param included a flag indicating whether element should be included or excluded.
+   */
+  def update(elem: A, included: Boolean) {
+    if (included) this += elem else this -= elem
+  }
+
+  // abstract methods from Growable/Shrinkable
+  
+  /** Adds a single element to the set. */
+  def +=(elem: A): this.type
+  def -=(elem: A): this.type
+
+  /** Removes all elements from the set for which do not satisfy a predicate.
+   *  @param  p  the predicate used to test elements. Only elements for
+   *             which `p` returns `true` are retained in the set; all others
+   *             are removed.
+   */
+  def retain(p: A => Boolean): Unit = for (elem <- this.toList) if (!p(elem)) this -= elem
+
+  /** Removes all elements from the set. After this operation is completed,
+   *  the set will be empty.
+   */
+  def clear() { foreach(-=) }
+
+  override def clone(): This = empty ++= repr
+
+  /** The result when this set is used as a builder
+   *  @return  the set representation itself.
+   */
+  def result: This = repr
+
+  /** Creates a new set consisting of all the elements of this set and `elem`.
+   *  
+   *  $addDuplicates
+   *  
+   *  @param elem  the element to add.
+   *  @return      a new set consisting of elements of this set and `elem`.
+   */
+  @migration(2, 8,
+    "As of 2.8, this operation creates a new set.  To add an element as a\n"+
+    "side effect to an existing set and return that set itself, use +=."
+  )
+  override def + (elem: A): This = clone() += elem
+
+  /** Creates a new set consisting of all the elements of this set and two or more
+   *  specified elements.
+   *  
+   *  $addDuplicates
+   *  
+   *  @param elem1 the first element to add.
+   *  @param elem2 the second element to add.
+   *  @param elems the remaining elements to add.
+   *  @return      a new set consisting of all the elements of this set, `elem1`,
+   *               `elem2` and those in `elems`.
+   */
+  @migration(2, 8,
+    "As of 2.8, this operation creates a new set.  To add the elements as a\n"+
+    "side effect to an existing set and return that set itself, use +=."
+  )
+  override def + (elem1: A, elem2: A, elems: A*): This =
+    clone() += elem1 += elem2 ++= elems
+
+  /** Creates a new set consisting of all the elements of this set and those
+   *  provided by the specified traversable object.
+   *
+   *  $addDuplicates
+   *
+   *  @param xs        the traversable object.
+   *  @return          a new set cconsisting of elements of this set and those in `xs`.
+   */
+  @migration(2, 8,
+    "As of 2.8, this operation creates a new set.  To add the elements as a\n"+
+    "side effect to an existing set and return that set itself, use ++=."
+  )
+  override def ++(xs: TraversableOnce[A]): This = clone() ++= xs
+
+  /** Creates a new set consisting of all the elements of this set except `elem`.
+   *
+   *  @param elem  the element to remove.
+   *  @return      a new set consisting of all the elements of this set except `elem`.
+   */
+  @migration(2, 8,
+    "As of 2.8, this operation creates a new set.  To remove the element as a\n"+
+    "side effect to an existing set and return that set itself, use -=."
+  )
+  override def -(elem: A): This = clone() -= elem
+
+  /** Creates a new set consisting of all the elements of this set except the two
+   *  or more specified elements.
+   *
+   *  @param elem1 the first element to remove.
+   *  @param elem2 the second element to remove.
+   *  @param elems the remaining elements to remove.
+   *  @return      a new set consisting of all the elements of this set except
+   *               `elem1`, `elem2` and `elems`.
+   */
+  @migration(2, 8,
+    "As of 2.8, this operation creates a new set.  To remove the elements as a\n"+
+    "side effect to an existing set and return that set itself, use -=."
+  )
+  override def -(elem1: A, elem2: A, elems: A*): This =
+    clone() -= elem1 -= elem2 --= elems
+
+  /** Creates a new set consisting of all the elements of this set except those
+   *  provided by the specified traversable object.
+   *
+   *  @param xs       the traversable object.
+   *  @return         a new set consisting of all the elements of this set except
+   *                  elements from `xs`.
+   */
+  @migration(2, 8,
+    "As of 2.8, this operation creates a new set.  To remove the elements as a\n"+
+    "side effect to an existing set and return that set itself, use --=."
+  )
+  override def --(xs: TraversableOnce[A]): This = clone() --= xs
+
+  /** Send a message to this scriptable object.
+   *
+   *  @param cmd  the message to send.
+   *  @throws `Predef.UnsupportedOperationException`
+   *  if the message was not understood.
+   */
+   def <<(cmd: Message[A]): Unit = cmd match {
+     case Include(_, x)     => this += x
+     case Remove(_, x)      => this -= x
+     case Reset()           => clear
+     case s: Script[_]      => s.iterator foreach <<
+     case _                 => throw new UnsupportedOperationException("message " + cmd + " not understood")
+   }
+}
diff --git a/src/library/scala/collection/mutable/SetProxy.scala b/src/library/scala/collection/mutable/SetProxy.scala
index 7f0d055..1fc4cea 100644
--- a/src/library/scala/collection/mutable/SetProxy.scala
+++ b/src/library/scala/collection/mutable/SetProxy.scala
@@ -1,16 +1,14 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: SetProxy.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala.collection.mutable
 
+package scala.collection
+package mutable
 
 /** This is a simple wrapper class for <a href="Set.html"
  *  target="contentFrame"><code>scala.collection.mutable.Set</code></a>.
@@ -19,38 +17,14 @@ package scala.collection.mutable
  *
  *  @author  Matthias Zenger
  *  @version 1.1, 09/05/2004
+ *  @since   1
  */
-trait SetProxy[A] extends Set[A] with collection.SetProxy[A] {
-
-  def self: Set[A]
-
-  override def update(elem: A, included: Boolean): Unit = self(elem) = included
-
-  def +=(elem: A): Unit = self += elem
-
-  override def ++=(that: Iterable[A]): Unit = self ++= that
-
-  override def ++=(it: Iterator[A]): Unit = self ++= it
-
-  override def incl(elems: A*): Unit = self ++= elems
-
-  def -=(elem: A): Unit = self -= elem
-
-  override def --=(that: Iterable[A]): Unit = self --= that
-
-  override def --=(it: Iterator[A]): Unit = self --= it
-
-  override def excl(elems: A*): Unit = self --= elems
-
-  override def intersect(that: Set[A]): Unit = self.intersect(that)
-
-  override def clear(): Unit = self.clear
-
-  override def retain(p: A => Boolean): Unit =  self.retain(p)
-
-  override def <<(cmd: Message[A]): Unit = self << cmd
-
-  override def clone(): Set[A] = new SetProxy[A] {
-    def self = SetProxy.this.self.clone()
-  }
+trait SetProxy[A] extends Set[A] with SetProxyLike[A, Set[A]] {  
+  override def repr = this
+  override def empty = new SetProxy[A] { val self = SetProxy.this.self.empty }
+  override def + (elem: A) = { self += elem ; this }
+  override def - (elem: A) = { self -= elem ; this }  
+
+  def +=(elem: A) = { self += elem; this }
+  def -=(elem: A) = { self -= elem; this }
 }
diff --git a/src/library/scala/collection/mutable/SingleLinkedList.scala b/src/library/scala/collection/mutable/SingleLinkedList.scala
deleted file mode 100644
index c7eea52..0000000
--- a/src/library/scala/collection/mutable/SingleLinkedList.scala
+++ /dev/null
@@ -1,62 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: SingleLinkedList.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala.collection.mutable
-
-/** This extensible class may be used as a basis for implementing linked
- *  list. Type variable <code>A</code> refers to the element type of the
- *  list, type variable <code>This</code> is used to model self types of
- *  linked lists.
- *
- *  @author  Matthias Zenger
- *  @version 1.0, 08/07/2003
- */
-abstract class SingleLinkedList[A, This >: Null <: SingleLinkedList[A, This]]
-         extends AnyRef with Seq[A]
-{ self: This =>
-
-  var elem: A
-
-  var next: This
-
-  def length: Int = 1 + (if (next eq null) 0 else next.length)
-
-  def append(that: This): Unit =
-    if (next eq null) next = that else next.append(that)
-
-  def insert(that: This): Unit = if (that ne null) {
-    that.append(next)
-    next = that
-  }
-
-  def apply(n: Int): A =
-    if (n == 0) elem
-    else if (next eq null) throw new IndexOutOfBoundsException("unknown element")
-    else next.apply(n - 1)
-
-  def get(n: Int): Option[A] =
-    if (n == 0) Some(elem)
-    else if (next eq null) None
-    else next.get(n - 1)
-
-  override def elements: Iterator[A] = new Iterator[A] {
-    var elems = SingleLinkedList.this
-    def hasNext = (elems ne null)
-    def next = {
-      val res = elems.elem
-      elems = elems.next
-      res;
-    }
-  }
-
-  override def toList: List[A] = elements toList
-
-}
diff --git a/src/library/scala/collection/mutable/Stack.scala b/src/library/scala/collection/mutable/Stack.scala
index a62a04d..4efe5b6 100644
--- a/src/library/scala/collection/mutable/Stack.scala
+++ b/src/library/scala/collection/mutable/Stack.scala
@@ -1,67 +1,82 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Stack.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.collection.mutable
+package scala.collection
+package mutable
 
+import generic._
+import collection.immutable.{List, Nil}
+import collection.Iterator
+import annotation.migration
 
 /** A stack implements a data structure which allows to store and retrieve
  *  objects in a last-in-first-out (LIFO) fashion.
- *
+ *  
+ *  @tparam A    type of the elements contained in this stack.
+ *  
  *  @author  Matthias Zenger
- *  @version 1.1, 03/05/2004
+ *  @author  Martin Odersky
+ *  @version 2.8
+ *  @since   1
+ *  @define Coll Stack
+ *  @define coll stack
+ *  @define orderDependent
+ *  @define orderDependentFold
+ *  @define mayNotTerminateInf
+ *  @define willNotTerminateInf
  */
 @serializable @cloneable
-class Stack[A] extends Seq[A] with CloneableCollection {
-  private var stack: immutable.Stack[A] = immutable.Stack.Empty
+class Stack[A] private (var elems: List[A]) extends scala.collection.Seq[A] with Cloneable[Stack[A]] {
+
+  def this() = this(Nil)
 
   /** Checks if the stack is empty.
    *
    *  @return true, iff there is no element on the stack
    */
-  override def isEmpty: Boolean = stack.isEmpty
-  
-  override def length = stack.length
-  
-  override def apply(index: Int) = stack(index)
+  override def isEmpty: Boolean = elems.isEmpty
 
-  /** Pushes a single element on top of the stack.
-   *
-   *  @param  elem        the element to push onto the stack
-   */
-  def +=(elem: A) {
-    this push elem
-  }
+  /** The number of elements in the stack */
+  override def length = elems.length
 
-  /** Pushes all elements provided by an <code>Iterable</code> object
-   *  on top of the stack. The elements are pushed in the order they
-   *  are given out by the iterator.
+  /** Retrieve n'th element from stack, where top of stack has index 0 */
+  override def apply(index: Int) = elems(index)
+
+  /** Push an element on the stack.
    *
-   *  @param  iter        an iterable object
+   *  @param   elem       the element to push on the stack.
+   *  @return the stack with the new element on top.
    */
-  def ++=(iter: Iterable[A]): Unit = stack = stack ++ iter
+  def push(elem: A): this.type = { elems = elem :: elems; this }
 
-  /** Pushes all elements provided by an iterator
-   *  on top of the stack. The elements are pushed in the order they
-   *  are given out by the iterator.
+  /** Push two or more elements onto the stack. The last element
+   *  of the sequence will be on top of the new stack.
    *
-   *  @param  iter        an iterator
+   *  @param   elems      the element sequence.
+   *  @return the stack with the new elements on top.
    */
-  def ++=(it: Iterator[A]): Unit = stack = stack ++ it
+  def push(elem1: A, elem2: A, elems: A*): this.type =
+    this.push(elem1).push(elem2).pushAll(elems)
 
-  /** Pushes a sequence of elements on top of the stack. The first element
-   *  is pushed first, etc.
+  /** Push all elements in the given traversable object onto
+   *  the stack. The last element in the traversable object
+   *  will be on top of the new stack.
    *
-   *  @param  elems       a sequence of elements
+   *  @param xs the traversable object.
+   *  @return the stack with the new elements on top.
    */
-  def push(elems: A*): Unit = (this ++= elems)
+  def pushAll(xs: TraversableOnce[A]): this.type = { xs foreach push ; this }
+
+  @deprecated("use pushAll")
+  @migration(2, 8, "Stack ++= now pushes arguments on the stack from left to right.")
+  def ++=(xs: TraversableOnce[A]): this.type = pushAll(xs)
 
   /** Returns the top element of the stack. This method will not remove
    *  the element from the stack. An error is signaled if there is no
@@ -71,7 +86,7 @@ class Stack[A] extends Seq[A] with CloneableCollection {
    *  @return the top element
    */
   def top: A =
-    stack.top
+    elems.head
 
   /** Removes the top element from the stack.
    *
@@ -79,8 +94,8 @@ class Stack[A] extends Seq[A] with CloneableCollection {
    *  @return the top element
    */
   def pop(): A = {
-    val res = stack.top
-    stack = stack.pop
+    val res = elems.head
+    elems = elems.tail
     res
   }
 
@@ -88,52 +103,37 @@ class Stack[A] extends Seq[A] with CloneableCollection {
    * Removes all elements from the stack. After this operation completed,
    * the stack will be empty.
    */
-  def clear(): Unit = stack = immutable.Stack.Empty
+  def clear(): Unit = elems = Nil
 
   /** Returns an iterator over all elements on the stack. This iterator
    *  is stable with respect to state changes in the stack object; i.e.
    *  such changes will not be reflected in the iterator. The iterator
-   *  issues elements in the order they were inserted into the stack
-   *  (FIFO order).
+   *  issues elements in the reversed order they were inserted into the stack
+   *  (LIFO order).
    *
    *  @return an iterator over all stack elements.
    */
-  override def elements: Iterator[A] = stack.elements
+  @migration(2, 8, "Stack iterator and foreach now traverse in FIFO order.")
+  override def iterator: Iterator[A] = elems.iterator
 
-  /** Creates a list of all stack elements in FIFO order.
+  /** Creates a list of all stack elements in LIFO order.
    *
    *  @return the created list.
    */
-  override def toList: List[A] = stack.toList
-  
-  /** Checks if two stacks are structurally identical.
-   *
-   *  @return true, iff both stacks contain the same sequence of elements.
-   */
-  override def equals(obj: Any): Boolean = obj match {
-    case that: Stack[_] =>
-      this.stack == that.stack
-    case _ =>
-      false
-  }
+  @migration(2, 8, "Stack iterator and foreach now traverse in FIFO order.")
+  override def toList: List[A] = elems
 
-  /** The hashCode method always yields an error, since it is not
-   *  safe to use mutable stacks as keys in hash tables.
-   *
-   *  @return never.
-   */
-  override def hashCode(): Int =
-    throw new UnsupportedOperationException("unsuitable as hash key")
+  @migration(2, 8, "Stack iterator and foreach now traverse in FIFO order.")
+  override def foreach[U](f: A => U): Unit = super.foreach(f)
 
   /** This method clones the stack.
    *
    *  @return  a stack with the same elements.
    */
-  override def clone(): Stack[A] = {
-    val res = new Stack[A]
-    res ++= this
-    res
-  }
+  override def clone(): Stack[A] = new Stack[A](elems)
+}
 
-  override protected def stringPrefix: String = "Stack"
+// !!! TODO - integrate
+object Stack {
+  def apply[A](xs: A*): Stack[A] = new Stack[A] pushAll xs
 }
diff --git a/src/library/scala/collection/mutable/StackProxy.scala b/src/library/scala/collection/mutable/StackProxy.scala
index 1f27b24..3ef0145 100644
--- a/src/library/scala/collection/mutable/StackProxy.scala
+++ b/src/library/scala/collection/mutable/StackProxy.scala
@@ -1,24 +1,27 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: StackProxy.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.collection.mutable
+package scala.collection
+package mutable
 
 
 /** A stack implements a data structure which allows to store and retrieve
  *  objects in a last-in-first-out (LIFO) fashion.
- *
+ *  
+ *  @tparam A   type of the elements in this stack proxy.
+ *  
  *  @author  Matthias Zenger
  *  @version 1.0, 10/05/2004
+ *  @since   1
  */
-trait StackProxy[A] extends Stack[A] with SeqProxy[A] {
+trait StackProxy[A] extends Stack[A] with Proxy {
 
   def self: Stack[A]
 
@@ -42,7 +45,12 @@ trait StackProxy[A] extends Stack[A] with SeqProxy[A] {
    *
    *  @param  elem        the element to push onto the stack
    */
-  override def +=(elem: A): Unit = self += elem
+  def +=(elem: A): this.type = {
+    self push elem
+    this
+  }
+
+  override def pushAll(xs: TraversableOnce[A]): this.type = { self pushAll xs; this }
 
   /** Pushes all elements provided by an <code>Iterable</code> object
    *  on top of the stack. The elements are pushed in the order they
@@ -50,22 +58,13 @@ trait StackProxy[A] extends Stack[A] with SeqProxy[A] {
    *
    *  @param  iter        an iterable object
    */
-    override def ++=(iter: Iterable[A]): Unit = self ++= iter
+  @deprecated("use pushAll") override def ++=(xs: TraversableOnce[A]): this.type = { self ++= xs ; this }
 
-  /** Pushes all elements provided by an iterator
-   *  on top of the stack. The elements are pushed in the order they
-   *  are given out by the iterator.
-   *
-   *  @param  iter        an iterator
-   */
-  override def ++=(it: Iterator[A]): Unit = self ++= it
 
-  /** Pushes a sequence of elements on top of the stack. The first element
-   *  is pushed first, etc.
-   *
-   *  @param  elems       a sequence of elements
-   */
-  override def push(elems: A*): Unit = self ++= elems
+  override def push(elem1: A, elem2: A, elems: A*): this.type = {
+    self.push(elem1).push(elem2).pushAll(elems)
+    this
+  }
 
   /** Returns the top element of the stack. This method will not remove
    *  the element from the stack. An error is signaled if there is no
@@ -93,7 +92,7 @@ trait StackProxy[A] extends Stack[A] with SeqProxy[A] {
    *
    *  @return an iterator over all stack elements.
    */
-  override def elements: Iterator[A] = self.elements
+  override def iterator: Iterator[A] = self.iterator
 
   /** Creates a list of all stack elements in FIFO order.
    *
diff --git a/src/library/scala/collection/mutable/StringBuilder.scala b/src/library/scala/collection/mutable/StringBuilder.scala
new file mode 100644
index 0000000..e0d6d38
--- /dev/null
+++ b/src/library/scala/collection/mutable/StringBuilder.scala
@@ -0,0 +1,433 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2006-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+package scala.collection
+package mutable
+
+import java.lang.{ StringBuilder => JavaStringBuilder }
+import annotation.migration
+
+/** A builder for mutable sequence of characters.  This class provides an API
+ *  mostly compatible with java.lang.StringBuilder, except where there are conflicts
+ *  with the Scala collections API (such as the `reverse` method.)
+ *
+ *  @author Stephane Micheloud
+ *  @author Martin Odersky
+ *  @version 2.8
+ *  @since   2.7
+ */
+ at serializable
+ at SerialVersionUID(0 - 8525408645367278351L)
+final class StringBuilder(private val underlying: JavaStringBuilder)
+      extends Builder[Char, String]
+         with java.lang.CharSequence
+         with IndexedSeq[Char] 
+         with IndexedSeqOptimized[Char, IndexedSeq[Char]] {
+  
+  /** Constructs a string builder initialized with String initValue
+   *  and with additional Char capacity initCapacity.
+   */
+  def this(initCapacity: Int, initValue: String) =
+    this(new JavaStringBuilder(initValue.length + initCapacity) append initValue)
+
+  /** Constructs a string builder with no characters in it and an 
+   *  initial capacity of 16 characters.
+   */
+  def this() = this(16, "")
+
+  /** Constructs a string builder with no characters in it and an 
+   *  initial capacity specified by the capacity argument. 
+   *
+   *  @param  capacity  the initial capacity.
+   *  @throws NegativeArraySizeException  if capacity < 0.
+   */
+  def this(capacity: Int) = this(capacity, "")
+
+  /** Constructs a string builder with initial characters 
+   *  equal to characters of `str`.
+   */
+  def this(str: String) = this(16, str)
+
+  def toArray: Array[Char] = {
+    val arr = new Array[Char](length)
+    underlying.getChars(0, length, arr, 0)
+    arr
+  }
+  
+  def length: Int = underlying.length()
+  def length_=(n: Int) { underlying.setLength(n) }
+ 
+  /** Clears the builder contents.
+   */
+  def clear(): Unit = setLength(0)
+
+  /** Sets the length of the character sequence.  If the current sequence
+   *  is shorter than the given length, it is padded with nulls; if it is
+   *  longer, it is truncated.
+   *
+   *  @param  len  the new length
+   *  @throws IndexOutOfBoundsException if the argument is negative.
+   */
+  def setLength(len: Int) { underlying setLength len }
+
+  /** Returns the current capacity, which is the size of the underlying array.
+   *  A new array will be allocated if the current capacity is exceeded.
+   *
+   *  @return  the capacity
+   */
+  def capacity: Int = underlying.capacity()
+
+  @deprecated("Use `ensureCapacity' instead. An assignment is misleading because\n"+
+              "it can never decrease the capacity.")
+  def capacity_=(n: Int) { ensureCapacity(n) }
+
+  /** Ensure that the capacity is at least the given argument.
+   *  If the argument is greater than the current capacity, new
+   *  storage will be allocated with size equal to the given
+   *  argument or to (2 * capacity + 2), whichever is larger.
+   *
+   *  @param newCapacity    the minimum desired capacity.
+   */
+  def ensureCapacity(newCapacity: Int): Unit = underlying ensureCapacity newCapacity
+      
+  /** Returns the Char at the specified index, counting from 0 as in Arrays.
+   *
+   *  @param  index   the index to look up
+   *  @return         the Char at the given index.
+   *  @throws IndexOutOfBoundsException  if the index is out of bounds.
+   */
+  def charAt(index: Int): Char = underlying charAt index
+
+  /** Equivalent to charAt.
+   */
+  def apply(index: Int): Char = underlying charAt index
+
+  /** Removes the Char at the specified index.  The sequence is
+   *  shortened by one.
+   *
+   *  @param  index  The index to remove.
+   *  @return        This StringBuilder.
+   *  @throws IndexOutOfBoundsException  if the index is out of bounds.
+   */
+  def deleteCharAt(index: Int): StringBuilder = {
+    underlying deleteCharAt index
+    this
+  }
+
+  /** Update the sequence at the given index to hold the specified Char.
+   *
+   *  @param  index   the index to modify.
+   *  @param  ch      the new Char.
+   *  @throws IndexOutOfBoundsException  if the index is out of bounds.
+   */
+  def setCharAt(index: Int, ch: Char): Unit = underlying.setCharAt(index, ch)
+
+  /** Equivalent to setCharAt.
+   */
+  def update(i: Int, c: Char): Unit = setCharAt(i, c)
+
+  /** Returns a new String made up of a subsequence of this sequence,
+   *  beginning at the given index and extending to the end of the sequence.
+   *
+   *  target.substring(start)  is equivalent to  target.drop(start)
+   * 
+   *  @param  start  The starting index, inclusive.
+   *  @return        The new String.
+   *  @throws IndexOutOfBoundsException  if the index is out of bounds.
+   */
+  def substring(start: Int): String = substring(start, length)
+
+  /** Returns a new String made up of a subsequence of this sequence,
+   *  beginning at the start index (inclusive) and extending to the
+   *  end index (exclusive).
+   *
+   *  target.substring(start, end)  is equivalent to  target.slice(start, end).mkString
+   *
+   *  @param  start  The beginning index, inclusive.
+   *  @param  end    The ending index, exclusive.
+   *  @return The new String.
+   *  @throws StringIndexOutOfBoundsException If either index is out of bounds,
+   *          or if start > end.
+   */
+  def substring(start: Int, end: Int): String = underlying.substring(start, end)
+
+  /** For implementing CharSequence.
+   */
+  def subSequence(start: Int, end: Int): java.lang.CharSequence = substring(start, end)
+
+  /** Appends the given Char to the end of the sequence.
+   */
+  def +=(x: Char): this.type = { append(x); this }
+
+  /** !!! This should create a new sequence.
+   */
+  def +(x: Char): this.type = { +=(x); this }
+
+  /** Appends the string representation of the given argument,
+   *  which is converted to a String with String.valueOf.
+   *
+   *  @param  x   an <code>Any</code> object.
+   *  @return     this StringBuilder.
+   */
+  def append(x: Any): StringBuilder = {
+    underlying append String.valueOf(x)
+    this
+  }
+
+  /** Appends the given String to this sequence.
+   *
+   *  @param  s   a String.
+   *  @return     this StringBuilder.
+   */
+  def append(s: String): StringBuilder = {
+    underlying append s
+    this
+  }
+
+  /** Appends the specified string builder to this sequence.
+   *
+   *  @param sb
+   *  @return 
+   */
+  def append(sb: StringBuilder): StringBuilder = {
+    underlying append sb
+    this
+  }
+
+  /** Appends all the Chars in the given Seq[Char] to this sequence.
+   *
+   *  @param  xs  the characters to be appended.
+   *  @return     this StringBuilder.
+   */
+  def appendAll(xs: TraversableOnce[Char]): StringBuilder = appendAll(xs.toArray)
+
+  /** Appends all the Chars in the given Array[Char] to this sequence.
+   *
+   *  @param  xs  the characters to be appended.
+   *  @return     a reference to this object.
+   */
+  def appendAll(xs: Array[Char]): StringBuilder = {
+    underlying append xs
+    this
+  }
+
+  /** Appends a portion of the given Array[Char] to this sequence.
+   *
+   *  @param  xs      the Array containing Chars to be appended.
+   *  @param  offset  the index of the first Char to append.
+   *  @param  len     the numbers of Chars to append.
+   *  @return         this StringBuilder.
+   */
+  def appendAll(xs: Array[Char], offset: Int, len: Int): StringBuilder = {
+    underlying.append(xs, offset, len)
+    this
+  }
+
+  /** Append the String representation of the given primitive type
+   *  to this sequence.  The argument is converted to a String with
+   *  String.valueOf.
+   *
+   *  @param   x  a primitive value
+   *  @return     This StringBuilder.
+   */
+  def append(x: Boolean): StringBuilder = { underlying append x ; this }
+  def append(x: Byte): StringBuilder = { underlying append x ; this }
+  def append(x: Short): StringBuilder = { underlying append x ; this }
+  def append(x: Int): StringBuilder = { underlying append x ; this }
+  def append(x: Long): StringBuilder = { underlying append x ; this }
+  def append(x: Float): StringBuilder = { underlying append x ; this }
+  def append(x: Double): StringBuilder = { underlying append x ; this }
+  def append(x: Char): StringBuilder = { underlying append x ; this }
+
+  /** Remove a subsequence of Chars from this sequence, starting at the
+   *  given start index (inclusive) and extending to the end index (exclusive)
+   *  or to the end of the String, whichever comes first.
+   *
+   *  @param  start  The beginning index, inclusive.
+   *  @param  end    The ending index, exclusive.
+   *  @return        This StringBuilder.
+   *  @throws StringIndexOutOfBoundsException   if start < 0 || start > end
+   */
+  def delete(start: Int, end: Int): StringBuilder = {
+    underlying.delete(start, end)
+    this
+  }
+
+  /** Replaces a subsequence of Chars with the given String.  The semantics
+   *  are as in delete, with the String argument then inserted at index 'start'.
+   * 
+   *  @param  start  The beginning index, inclusive.
+   *  @param  end    The ending index, exclusive.
+   *  @param  str    The String to be inserted at the start index.
+   *  @return        This StringBuilder.
+   *  @throws StringIndexOutOfBoundsException if start < 0, start > length, or start > end
+   */
+  def replace(start: Int, end: Int, str: String): StringBuilder = {
+    underlying.replace(start, end, str)
+    this
+  }
+
+  /** Inserts a subarray of the given Array[Char] at the given index
+   *  of this sequence.
+   *
+   * @param  index   index at which to insert the subarray.
+   * @param  str     the Array from which Chars will be taken.
+   * @param  offset  the index of the first Char to insert.
+   * @param  len     the number of Chars from 'str' to insert.
+   * @return         This StringBuilder.
+   *
+   * @throws StringIndexOutOfBoundsException  if index < 0, index > length,
+   *         offset < 0, len < 0, or (offset + len) > str.length.
+   */
+  def insertAll(index: Int, str: Array[Char], offset: Int, len: Int): StringBuilder = {
+    underlying.insert(index, str, offset, len)
+    this
+  }
+
+  /** Inserts the String representation (via String.valueOf) of the given
+   *  argument into this sequence at the given index.
+   *
+   *  @param  index   the index at which to insert.
+   *  @param  x       a value.
+   *  @return         this StringBuilder.
+   *  @throws StringIndexOutOfBoundsException  if the index is out of bounds.
+   */
+  def insert(index: Int, x: Any): StringBuilder = insert(index, String.valueOf(x))
+  
+  /** Inserts the String into this character sequence.
+   *
+   *  @param  index the index at which to insert.
+   *  @param  x     a String.
+   *  @return       this StringBuilder.
+   *  @throws StringIndexOutOfBoundsException  if the index is out of bounds.
+   */
+  def insert(index: Int, x: String): StringBuilder = {
+    underlying.insert(index, x)
+    this
+  }
+
+  /** Inserts the given Seq[Char] into this sequence at the given index.
+   *
+   *  @param  index the index at which to insert.
+   *  @param  xs    the Seq[Char].
+   *  @return       this StringBuilder.
+   *  @throws StringIndexOutOfBoundsException  if the index is out of bounds.
+   */
+  def insertAll(index: Int, xs: TraversableOnce[Char]): StringBuilder = insertAll(index, xs.toArray)
+
+  /** Inserts the given Array[Char] into this sequence at the given index.
+   *
+   *  @param  index the index at which to insert.
+   *  @param  xs    the Array[Char].
+   *  @return       this StringBuilder.
+   *  @throws StringIndexOutOfBoundsException  if the index is out of bounds.
+   */
+  def insertAll(index: Int, xs: Array[Char]): StringBuilder = {
+    underlying.insert(index, xs)
+    this
+  }
+
+  /** Calls String.valueOf on the given primitive value, and inserts the
+   *  String at the given index.
+   *
+   *  @param  index the offset position.
+   *  @param  x     a primitive value.
+   *  @return       this StringBuilder.
+   */
+  def insert(index: Int, x: Boolean): StringBuilder = insert(index, String.valueOf(x))
+  def insert(index: Int, x: Byte): StringBuilder    = insert(index, String.valueOf(x))
+  def insert(index: Int, x: Short): StringBuilder   = insert(index, String.valueOf(x))
+  def insert(index: Int, x: Int): StringBuilder     = insert(index, String.valueOf(x))
+  def insert(index: Int, x: Long): StringBuilder    = insert(index, String.valueOf(x))
+  def insert(index: Int, x: Float): StringBuilder   = insert(index, String.valueOf(x))
+  def insert(index: Int, x: Double): StringBuilder  = insert(index, String.valueOf(x))
+  def insert(index: Int, x: Char): StringBuilder    = insert(index, String.valueOf(x))
+  
+  @deprecated("Use appendAll instead. This method is deprecated because of the\n"+
+              "possible confusion with `append(Any)'.")
+  def append(x: Seq[Char]): StringBuilder = appendAll(x)
+
+  @deprecated("use appendAll instead. This method is deprecated because\n"+
+              "of the possible confusion with `append(Any)'.")
+  def append(x: Array[Char]): StringBuilder = appendAll(x)
+
+  @deprecated("use appendAll instead. This method is deprecated because\n"+
+              "of the possible confusion with `append(Any, Int, Int)'.")
+  def append(x: Array[Char], offset: Int, len: Int): StringBuilder = appendAll(x, offset, len)
+
+  @deprecated("use insertAll instead. This method is deprecated because of the\n"+
+              "possible confusion with `insert(Int, Any, Int, Int)'.")
+  def insert(index: Int, str: Array[Char], offset: Int, len: Int): StringBuilder = 
+    insertAll(index, str, offset, len)
+
+  @deprecated("use insertAll instead. This method is deprecated because of\n"+
+              "the possible confusion with `insert(Int, Any)'.")
+  def insert(at: Int, x: Seq[Char]): StringBuilder = insertAll(at, x)
+
+  @deprecated("use insertAll instead. This method is deprecated because of\n"+
+              "the possible confusion with `insert(Int, Any)'.")
+  def insert(at: Int, x: Array[Char]): StringBuilder = insertAll(at, x)
+
+  /** Finds the index of the first occurrence of the specified substring.
+   *
+   *  @param    str       the target string to search for
+   *  @return             the first applicable index where target occurs, or -1 if not found.
+   */
+  def indexOf(str: String): Int = underlying.indexOf(str)
+
+  /** Finds the index of the first occurrence of the specified substring.
+   *
+   *  @param    str       the target string to search for
+   *  @param    fromIndex the smallest index in the source string to consider
+   *  @return             the first applicable index where target occurs, or -1 if not found.
+   */
+  def indexOf(str: String, fromIndex: Int): Int = underlying.indexOf(str, fromIndex)
+
+  /** Finds the index of the last occurrence of the specified substring.
+   *
+   *  @param    str       the target string to search for
+   *  @return             the last applicable index where target occurs, or -1 if not found.
+   */
+  def lastIndexOf(str: String): Int = underlying.lastIndexOf(str)
+
+  /** Finds the index of the last occurrence of the specified substring.
+   *
+   *  @param    str       the target string to search for
+   *  @param    fromIndex the smallest index in the source string to consider
+   *  @return             the last applicable index where target occurs, or -1 if not found.
+   */
+  def lastIndexOf(str: String, fromIndex: Int): Int = underlying.lastIndexOf(str, fromIndex)
+  
+  /** Creates a new StringBuilder with the reversed contents of this one.
+   *  If surrogate pairs are present, they are treated as indivisible units: each
+   *  pair will appear in the same order in the updated sequence.
+   *
+   *  @return   the reversed StringBuilder
+   */
+  @migration(2, 8, "Since 2.8 reverse returns a new instance.  Use 'reverseContents' to update in place.")
+  override def reverse: StringBuilder = new StringBuilder(new JavaStringBuilder(underlying) reverse)
+  
+  override def clone(): StringBuilder = new StringBuilder(new JavaStringBuilder(underlying))
+
+  /** Like reverse, but destructively updates the target StringBuilder.
+   *
+   *  @return   the reversed StringBuilder (same as the target StringBuilder)
+   */
+  def reverseContents(): StringBuilder = {
+    underlying.reverse()
+    this
+  }
+
+  /** Returns a new String representing the data in this sequence.
+   *
+   *  @return  the current contents of this sequence as a String
+   */
+  override def toString = underlying.toString
+  
+  def result(): String = toString
+}
diff --git a/src/library/scala/collection/mutable/Subscriber.scala b/src/library/scala/collection/mutable/Subscriber.scala
index cb3a7bf..a89745b 100644
--- a/src/library/scala/collection/mutable/Subscriber.scala
+++ b/src/library/scala/collection/mutable/Subscriber.scala
@@ -1,15 +1,15 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Subscriber.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.collection.mutable
+package scala.collection
+package mutable
 
 
 /** <code>Subscriber[A, B]</code> objects may subscribe to events of
@@ -18,8 +18,10 @@ package scala.collection.mutable
  *  target="contentFrame"><code>Publisher</code></a>.
  *
  *  @author  Matthias Zenger
- *  @version 1.0, 08/07/2003
+ *  @author  Martin Odersky
+ *  @version 2.8
+ *  @since   1
  */
-trait Subscriber[-A, -B] {
-  def notify(pub: B, event: A): Unit
+trait Subscriber[-Evt, -Pub] {
+  def notify(pub: Pub, event: Evt): Unit
 }
diff --git a/src/library/scala/collection/mutable/SynchronizedBuffer.scala b/src/library/scala/collection/mutable/SynchronizedBuffer.scala
index 9625621..c9f11ff 100644
--- a/src/library/scala/collection/mutable/SynchronizedBuffer.scala
+++ b/src/library/scala/collection/mutable/SynchronizedBuffer.scala
@@ -1,31 +1,39 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: SynchronizedBuffer.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.collection.mutable
+package scala.collection
+package mutable
 
+import script._
 
-/** This class should be used as a mixin. It synchronizes the <code>Buffer</code>
+/** This class should be used as a mixin. It synchronizes the `Buffer`
  *  methods of the class into which it is mixed in.
- *
+ *  
+ *  @tparam A    type of the elements contained in this buffer.
+ *  
  *  @author  Matthias Zenger
  *  @version 1.0, 08/07/2003
+ *  @since   1
+ *  @define Coll SynchronizedBuffer
+ *  @define coll synchronized buffer
  */
 trait SynchronizedBuffer[A] extends Buffer[A] {
 
+  import scala.collection.Traversable
+
   abstract override def length: Int = synchronized {
     super.length
   }
 
-  abstract override def elements: Iterator[A] = synchronized {
-    super.elements
+  abstract override def iterator: Iterator[A] = synchronized {
+    super.iterator
   }
 
   abstract override def apply(n: Int): A = synchronized {
@@ -37,7 +45,7 @@ trait SynchronizedBuffer[A] extends Buffer[A] {
    *
    *  @param elem  the element to append.
    */
-  override def +(elem: A): Buffer[A] = synchronized {
+  override def +(elem: A): Self = synchronized {
     super.+(elem)
   }
 
@@ -45,27 +53,27 @@ trait SynchronizedBuffer[A] extends Buffer[A] {
    *
    *  @param elem  the element to append.
    */
-  abstract override def +=(elem: A): Unit = synchronized {
+  abstract override def +=(elem: A): this.type = synchronized[this.type] {
     super.+=(elem)
   }
 
-  /** Appends a number of elements provided by an iterable object
-   *  via its <code>elements</code> method. The identity of the
-   *  buffer is returned.
+  /** Appends a number of elements provided by a traversable object via
+   *  its `foreach` method.
+   *  The identity of the buffer is returned.
    *
-   *  @param iter  the iterable object.
+   *  @param xs the traversable object.
    */
-  override def ++(iter: Iterable[A]): Buffer[A] = synchronized {
-    super.++(iter)
+  override def ++(xs: TraversableOnce[A]): Self = synchronized {
+    super.++(xs)
   }
 
-  /** Appends a number of elements provided by an iterable object
-   *  via its <code>elements</code> method.
+  /** Appends a number of elements provided by a traversable object
+   *  via its `foreach` method.
    *
    *  @param iter  the iterable object.
    */
-  override def ++=(iter: Iterable[A]): Unit = synchronized {
-    super.++=(iter)
+  override def ++=(xs: TraversableOnce[A]): this.type = synchronized[this.type] {
+    super.++=(xs)
   }
 
   /** Appends a sequence of elements to this buffer.
@@ -76,13 +84,13 @@ trait SynchronizedBuffer[A] extends Buffer[A] {
     super.++=(elems)
   }
 
-  /** Appends a number of elements provided by an iterable object
-   *  via its <code>elements</code> method.
+  /** Appends a number of elements provided by a traversable object
+   *  via its <code>foreach</code> method.
    *
-   *  @param iter  the iterable object.
+   *  @param xs the traversable object.
    */
-  override def appendAll(iter: Iterable[A]): Unit = synchronized {
-    super.appendAll(iter)
+  override def appendAll(xs: TraversableOnce[A]): Unit = synchronized {
+    super.appendAll(xs)
   }
 
   /** Prepend a single element to this buffer and return
@@ -90,36 +98,32 @@ trait SynchronizedBuffer[A] extends Buffer[A] {
    *
    *  @param elem  the element to append.
    */
-  abstract override def +:(elem: A): Buffer[A] = synchronized {
-    super.+:(elem)
+  abstract override def +=:(elem: A): this.type = synchronized[this.type] {
+    super.+=:(elem)
   }
 
-  /** Prepends a number of elements provided by an iterable object
-   *  via its <code>elements</code> method. The identity of the
+  /** Prepends a number of elements provided by a traversable object
+   *  via its <code>foreach</code> method. The identity of the
    *  buffer is returned.
    *
-   *  @param iter  the iterable object.
+   *  @param xs the traversable object.
    */
-  override def ++:(iter: Iterable[A]): Buffer[A] = synchronized {
-    super.++:(iter)
-  }
+  override def ++=:(xs: TraversableOnce[A]): this.type = synchronized[this.type] { super.++=:(xs) }
 
   /** Prepend an element to this list.
    *
    *  @param elem  the element to prepend.
    */
-  override def prepend(elems: A*): Unit = synchronized {
-    super.prependAll(elems)
-  }
+  override def prepend(elems: A*): Unit = prependAll(elems)
 
-  /** Prepends a number of elements provided by an iterable object
-   *  via its <code>elements</code> method. The identity of the
+  /** Prepends a number of elements provided by a traversable object
+   *  via its <code>foreach</code> method. The identity of the
    *  buffer is returned.
    *
-   *  @param iter  the iterable object.
+   *  @param xs the traversable object.
    */
-  override def prependAll(elems: Iterable[A]): Unit = synchronized {
-    super.prependAll(elems)
+  override def prependAll(xs: TraversableOnce[A]): Unit = synchronized {
+    super.prependAll(xs)
   }
 
   /** Inserts new elements at the index <code>n</code>. Opposed to method
@@ -138,10 +142,10 @@ trait SynchronizedBuffer[A] extends Buffer[A] {
    *  one. Instead, it will insert a new element at index <code>n</code>.
    *
    *  @param n     the index where a new element will be inserted.
-   *  @param iter  the iterable object providing all elements to insert.
+   *  @param xs    the traversable object providing all elements to insert.
    */
-  abstract override def insertAll(n: Int, iter: Iterable[A]): Unit = synchronized {
-     super.insertAll(n, iter)
+  abstract override def insertAll(n: Int, xs: Traversable[A]): Unit = synchronized {
+     super.insertAll(n, xs)
   }
 
   /** Replace element at index <code>n</code> with the new element
@@ -168,7 +172,7 @@ trait SynchronizedBuffer[A] extends Buffer[A] {
     super.clear
   }
 
-  override def <<(cmd: Message[(Location, A)]): Unit = synchronized {
+  override def <<(cmd: Message[A]): Unit = synchronized {
     super.<<(cmd)
   }
 
@@ -176,7 +180,7 @@ trait SynchronizedBuffer[A] extends Buffer[A] {
    *
    *  @return an <code>ArrayBuffer</code> with the same elements.
    */
-  override def clone(): Buffer[A] = synchronized {
+  override def clone(): Self = synchronized {
     super.clone()
   }
 
diff --git a/src/library/scala/collection/mutable/SynchronizedMap.scala b/src/library/scala/collection/mutable/SynchronizedMap.scala
index 7402906..db56946 100644
--- a/src/library/scala/collection/mutable/SynchronizedMap.scala
+++ b/src/library/scala/collection/mutable/SynchronizedMap.scala
@@ -1,153 +1,63 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: SynchronizedMap.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.collection.mutable
+package scala.collection
+package mutable
 
+import annotation.migration
 
-/** This class should be used as a mixin. It synchronizes the <code>Map</code>
+/** This class should be used as a mixin. It synchronizes the `Map`
  *  functions of the class into which it is mixed in.
- *
+ *  
+ *  @tparam A     type of the keys contained in this map.
+ *  @tparam B     type of the values associated with keys.
+ *  
  *  @author  Matthias Zenger, Martin Odersky
  *  @version 2.0, 31/12/2006
+ *  @since   1
+ *  @define Coll SynchronizedMap
+ *  @define coll synchronized map
  */
 trait SynchronizedMap[A, B] extends Map[A, B] {
 
-  abstract override def size: Int = synchronized {
-    super.size
-  }
-
-  abstract override def get(key: A): Option[B] = synchronized {
-    super.get(key)
-  }
-
-  override def isEmpty: Boolean = synchronized {
-    super.isEmpty
-  }
-
-  override def apply(key: A): B = synchronized {
-    super.apply(key)
-  }
-
-  override def contains(key: A): Boolean = synchronized {
-    super.contains(key)
-  }
-
-  override def isDefinedAt(key: A) = synchronized {
-    super.isDefinedAt(key)
-  }
-
-  override def keys: Iterator[A] = synchronized {
-    super.keys
-  }
-
-  override def keySet: collection.Set[A] = synchronized {
-    super.keySet
-  }
-
-  override def values: Iterator[B] = synchronized {
-    super.values
-  }
-
-  abstract override def elements: Iterator[(A, B)] = synchronized {
-    super.elements
-  }
-
-  override def toList: List[(A, B)] = synchronized {
-    super.toList
-  }
-
-  abstract override def update(key: A, value: B): Unit = synchronized {
-    super.update(key, value)
-  }
-
-  override def += (kv: (A, B)): Unit = synchronized { 
-    super.+=(kv) 
-  }
-
-  /** Add two or more key/value pairs to this map. 
-   *  @param    kv1 the key/first value pair.
-   *  @param    kv2 the second key/first value pair.
-   *  @param    kvs the remaining key/first value pairs.
-   */
-  override def += (kv1: (A, B), kv2: (A, B), kvs: (A, B)*): Unit = synchronized {
-    super.+=(kv1, kv2, kvs: _*)
-  }
-
-  override def ++=(map: Iterable[(A, B)]): Unit = synchronized {
-    super.++=(map)
-  }
-
-  override def ++=(it: Iterator[(A, B)]): Unit = synchronized {
-    super.++=(it)
-  }
-
-  @deprecated
-  override def incl(mappings: (A, B)*): Unit = synchronized {
-    super.incl(mappings: _*)
-  }
-
-  abstract override def -=(key: A): Unit = synchronized {
-    super.-=(key)
-  }
-
-  override def -= (key1: A, key2: A, keys: A*): Unit = synchronized { 
-    super.-=(key1, key2, keys: _*)
-  }
-
-  override def --=(keys: Iterable[A]): Unit = synchronized {
-    super.--=(keys)
-  }
-
-  override def --=(it: Iterator[A]): Unit = synchronized {
-    super.--=(it)
-  }
-
-  @deprecated
-  override def excl(keys: A*): Unit = synchronized {
-    super.excl(keys: _*)
-  }
-
-  override def clear(): Unit = synchronized {
-    super.clear
-  }
-
-  override def getOrElseUpdate(key: A, default: => B): B = synchronized {
-    super.getOrElseUpdate(key, default)
-  }
-
-  override def transform(f: (A, B) => B): Unit = synchronized {
-    super.transform(f)
-  }
-
-  override def retain(p: (A, B) => Boolean): Unit = synchronized {
-    super.retain(p)
-  }
-
-  override def toString() = synchronized {
-    super.toString()
-  }
-
-  override def equals(that: Any): Boolean = synchronized {
-    super.equals(that)
-  }
-  
-  override def hashCode(): Int = synchronized {
-    super.hashCode()
-  }
-
-  override def <<(cmd: Message[(A, B)]): Unit = synchronized {
-    super.<<(cmd)
-  }
-
-  override def clone(): Map[A, B] = synchronized {
-    super.clone()
-  }
+  abstract override def get(key: A): Option[B] = synchronized { super.get(key) }
+  abstract override def iterator: Iterator[(A, B)] = synchronized { super.iterator }
+  abstract override def += (kv: (A, B)): this.type = synchronized[this.type] { super.+=(kv) }
+  abstract override def -= (key: A): this.type = synchronized[this.type] { super.-=(key) }
+
+  override def size: Int = synchronized { super.size }
+  override def put(key: A, value: B): Option[B] = synchronized { super.put(key, value) }
+  override def update(key: A, value: B): Unit = synchronized { super.update(key, value) }
+  override def remove(key: A): Option[B] = synchronized { super.remove(key) }
+  override def clear(): Unit = synchronized { super.clear() }
+  override def getOrElseUpdate(key: A, default: => B): B = synchronized { super.getOrElseUpdate(key, default) }
+  override def transform(f: (A, B) => B): this.type = synchronized[this.type] { super.transform(f) }
+  override def retain(p: (A, B) => Boolean): this.type = synchronized[this.type] { super.retain(p) }
+  @migration(2, 8, "As of 2.8, values returns Iterable[B] rather than Iterator[B].")
+  override def values: collection.Iterable[B] = synchronized { super.values }
+  override def valuesIterator: Iterator[B] = synchronized { super.valuesIterator }
+  override def clone(): Self = synchronized { super.clone() }
+  override def foreach[U](f: ((A, B)) => U) = synchronized { super.foreach(f) }
+  override def apply(key: A): B = synchronized { super.apply(key) }
+  override def keySet: collection.Set[A] = synchronized { super.keySet }
+  @migration(2, 8, "As of 2.8, keys returns Iterable[A] rather than Iterator[A].")
+  override def keys: collection.Iterable[A] = synchronized { super.keys }
+  override def keysIterator: Iterator[A] = synchronized { super.keysIterator }
+  override def isEmpty: Boolean = synchronized { super.isEmpty }
+  override def contains(key: A): Boolean = synchronized {super.contains(key) }
+  override def isDefinedAt(key: A) = synchronized { super.isDefinedAt(key) }
+
+  // @deprecated("See Map.+ for explanation") override def +(kv: (A, B)): this.type = synchronized[this.type] { super.+(kv) }
+  // can't override -, -- same type!
+  // @deprecated override def -(key: A): Self = synchronized { super.-(key) }
+
+  // !!! todo: also add all other methods 
 }
+
diff --git a/src/library/scala/collection/mutable/SynchronizedPriorityQueue.scala b/src/library/scala/collection/mutable/SynchronizedPriorityQueue.scala
index db79489..1ec4505 100644
--- a/src/library/scala/collection/mutable/SynchronizedPriorityQueue.scala
+++ b/src/library/scala/collection/mutable/SynchronizedPriorityQueue.scala
@@ -1,25 +1,29 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: SynchronizedPriorityQueue.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.collection.mutable
+package scala.collection
+package mutable
 
-
-/** This class implements synchronized priority queues using a heap.
- *  The elements of the queue have to be ordered in terms of the
- *  <code>Ordered[T]</code> class.
- *
+/** This class implements synchronized priority queues using a binary heap.
+ *  The elements of the queue have to be ordered in terms of the `Ordered[T]` class.
+ *  
+ *  @tparam A    type of the elements contained in this synchronized priority queue
+ *  @param ord   implicit ordering used to compared elements of type `A`
+ *  
  *  @author  Matthias Zenger
  *  @version 1.0, 03/05/2004
+ *  @since   1
+ *  @define Coll SynchronizedPriorityQueue
+ *  @define coll synchronized priority queue
  */
-class SynchronizedPriorityQueue[A <% Ordered[A]] extends PriorityQueue[A] {
+class SynchronizedPriorityQueue[A](implicit ord: Ordering[A]) extends PriorityQueue[A] {
 
   /** Checks if the queue is empty.
    *
@@ -31,20 +35,23 @@ class SynchronizedPriorityQueue[A <% Ordered[A]] extends PriorityQueue[A] {
    *
    *  @param  elem        the element to insert
    */
-  override def +=(elem: A): Unit = synchronized { super.+=(elem) }
-
-  /** Adds all elements provided by an <code>Iterable</code> object
-   *  into the priority queue.
-   *
-   *  @param  iter        an iterable object
-   */
-  override def ++=(iter: Iterable[A]): Unit = synchronized { super.++=(iter) }
-
-  /** Adds all elements provided by an iterator into the priority queue.
+  override def +=(elem: A): this.type = {
+    synchronized {
+      super.+=(elem)
+    }
+    this
+  }
+
+  /** Adds all elements of a traversable object into the priority queue.
    *
-   *  @param  it        an iterator
+   *  @param  xs        a traversable object
    */
-  override def ++=(it: Iterator[A]): Unit = synchronized { super.++=(it) }
+  override def ++=(xs: TraversableOnce[A]): this.type = {
+    synchronized {
+      super.++=(xs)
+    }
+    this
+  }
 
   /** Adds all elements to the queue.
    *
@@ -71,12 +78,12 @@ class SynchronizedPriorityQueue[A <% Ordered[A]] extends PriorityQueue[A] {
    */
   override def clear(): Unit = synchronized { super.clear }
 
-  /** Returns an iterator which yiels all the elements of the priority
+  /** Returns an iterator which yield all the elements of the priority
    *  queue in descending priority order.
    *
    *  @return  an iterator over all elements sorted in descending order.
    */
-  override def elements: Iterator[A] = synchronized { super.elements }
+  override def iterator: Iterator[A] = synchronized { super.iterator }
 
   /** Checks if two queues are structurally identical.
    *
@@ -84,13 +91,6 @@ class SynchronizedPriorityQueue[A <% Ordered[A]] extends PriorityQueue[A] {
    */
   override def equals(that: Any): Boolean = synchronized { super.equals(that) }
 
-  /** The hashCode method always yields an error, since it is not
-   *  safe to use mutable queues as keys in hash tables.
-   *
-   *  @return never.
-   */
-  override def hashCode(): Int = synchronized { super.hashCode() }
-
   /** Returns a textual representation of a queue as a string.
    *
    *  @return the string representation of this queue.
diff --git a/src/library/scala/collection/mutable/SynchronizedQueue.scala b/src/library/scala/collection/mutable/SynchronizedQueue.scala
index aa82c25..fa0875f 100644
--- a/src/library/scala/collection/mutable/SynchronizedQueue.scala
+++ b/src/library/scala/collection/mutable/SynchronizedQueue.scala
@@ -1,25 +1,31 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: SynchronizedQueue.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.collection.mutable
+package scala.collection
+package mutable
 
 
-/** This is a synchronized version of the <code>Queue[T]</code> class. It
+/** This is a synchronized version of the `Queue[T]` class. It
  *  implements a data structure that allows one to insert and retrieve
  *  elements in a first-in-first-out (FIFO) manner.
- *
+ *  
+ *  @tparam A     type of elements contained in this synchronized queue.
+ *  
  *  @author  Matthias Zenger
  *  @version 1.0, 03/05/2004
+ *  @since   1
+ *  @define Coll SynchronizedQueue
+ *  @define coll synchronized queue
  */
 class SynchronizedQueue[A] extends Queue[A] {
+  import scala.collection.Traversable
 
   /** Checks if the queue is empty.
    *
@@ -31,23 +37,15 @@ class SynchronizedQueue[A] extends Queue[A] {
    *
    *  @param  elem        the element to insert
    */
-  override def +=(elem: A): Unit = synchronized { super.+=(elem) }
+  override def +=(elem: A): this.type = synchronized[this.type] { super.+=(elem) }
 
-  /** Adds all elements provided by an <code>Iterable</code> object
+  /** Adds all elements provided by a `TraversableOnce` object
    *  at the end of the queue. The elements are prepended in the order they
    *  are given out by the iterator.
    *
-   *  @param  iter        an iterable object
+   *  @param  xs        a traversable object
    */
-  override def ++=(iter: Iterable[A]): Unit = synchronized { super.++=(iter) }
-
-  /** Adds all elements provided by an iterator
-   *  at the end of the queue. The elements are prepended in the order they
-   *  are given out by the iterator.
-   *
-   *  @param  it        an iterator
-   */
-  override def ++=(it: Iterator[A]): Unit = synchronized { super.++=(it) }
+  override def ++=(xs: TraversableOnce[A]): this.type = synchronized[this.type] { super.++=(xs) }
 
   /** Adds all elements to the queue.
    *
@@ -80,13 +78,6 @@ class SynchronizedQueue[A] extends Queue[A] {
    */
   override def equals(that: Any): Boolean = synchronized { super.equals(that) }
 
-  /** The hashCode method always yields an error, since it is not
-   *  safe to use mutable queues as keys in hash tables.
-   *
-   *  @return never.
-   */
-  override def hashCode(): Int = synchronized { super.hashCode() }
-
   /** Returns a textual representation of a queue as a string.
    *
    *  @return the string representation of this queue.
diff --git a/src/library/scala/collection/mutable/SynchronizedSet.scala b/src/library/scala/collection/mutable/SynchronizedSet.scala
index 8aec355..1a2561e 100644
--- a/src/library/scala/collection/mutable/SynchronizedSet.scala
+++ b/src/library/scala/collection/mutable/SynchronizedSet.scala
@@ -1,24 +1,30 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: SynchronizedSet.scala 16894 2009-01-13 13:09:41Z cunei $
 
+package scala.collection
+package mutable
 
-package scala.collection.mutable
+import script._
 
-
-/** This class should be used as a mixin. It synchronizes the <code>Set</code>
+/** This class should be used as a mixin. It synchronizes the `Set`
  *  functions of the class into which it is mixed in.
- *
+ *  
+ *  @tparam A    type of the elements contained in this synchronized set.
+ *  
  *  @author  Matthias Zenger
  *  @version 1.0, 08/07/2003
+ *  @since   1
+ *  @define Coll SynchronizedSet
+ *  @define coll synchronized set
  */
 trait SynchronizedSet[A] extends Set[A] {
+  import scala.collection.Traversable
 
   abstract override def size: Int = synchronized {
     super.size
@@ -32,43 +38,35 @@ trait SynchronizedSet[A] extends Set[A] {
     super.contains(elem)
   }
 
-  abstract override def update(elem: A, included: Boolean): Unit = synchronized {
-    super.update(elem, included)
-  }
-
-  abstract override def +=(elem: A): Unit = synchronized {
+  abstract override def +=(elem: A): this.type = synchronized[this.type] {
     super.+=(elem)
   }
 
-  override def ++=(that: Iterable[A]) = synchronized {
-    super.++=(that)
+  override def ++=(xs: TraversableOnce[A]): this.type = synchronized[this.type] {
+    super.++=(xs)
   }
 
-  override def ++=(it: Iterator[A]) = synchronized {
-    super.++=(it)
-  }
-
-  override def incl(elems: A*): Unit = synchronized {
-    super.++=(elems)
+  abstract override def -=(elem: A): this.type = synchronized[this.type] {
+    super.-=(elem)
   }
 
-  abstract override def -=(elem: A): Unit = synchronized {
-    super.-=(elem)
+  override def --=(xs: TraversableOnce[A]): this.type = synchronized[this.type] {
+    super.--=(xs)
   }
 
-  override def --=(that: Iterable[A]) = synchronized {
-    super.--=(that)
+  override def update(elem: A, included: Boolean): Unit = synchronized {
+    super.update(elem, included)
   }
 
-  override def --=(it: Iterator[A]) = synchronized {
-    super.--=(it)
+  override def add(elem: A): Boolean = synchronized {
+    super.add(elem)
   }
 
-  override def excl(elems: A*): Unit = synchronized {
-    super.--=(elems)
+  override def remove(elem: A): Boolean = synchronized {
+    super.remove(elem)
   }
 
-  override def intersect(that: Set[A]) = synchronized {
+  override def intersect(that: scala.collection.Set[A]) = synchronized {
     super.intersect(that)
   }
 
@@ -80,7 +78,7 @@ trait SynchronizedSet[A] extends Set[A] {
     super.subsetOf(that)
   }
 
-  override def foreach(f: A => Unit) = synchronized {
+  override def foreach[U](f: A =>  U) = synchronized {
     super.foreach(f)
   }
 
@@ -100,7 +98,7 @@ trait SynchronizedSet[A] extends Set[A] {
     super.<<(cmd)
   }
 
-  override def clone(): Set[A] = synchronized {
+  override def clone(): Self = synchronized {
     super.clone()
   }
 }
diff --git a/src/library/scala/collection/mutable/SynchronizedStack.scala b/src/library/scala/collection/mutable/SynchronizedStack.scala
index 2d57383..67ff321 100644
--- a/src/library/scala/collection/mutable/SynchronizedStack.scala
+++ b/src/library/scala/collection/mutable/SynchronizedStack.scala
@@ -1,25 +1,31 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: SynchronizedStack.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.collection.mutable
+package scala.collection
+package mutable
 
 
-/** This is a synchronized version of the <code>Stack[T]</code> class. It
+/** This is a synchronized version of the `Stack[T]` class. It
  *  implements a data structure which allows to store and retrieve
  *  objects in a last-in-first-out (LIFO) fashion.
- * 
+ *  
+ *  @tparam A    type of the elements contained in this stack.
+ *  
  *  @author  Matthias Zenger
  *  @version 1.0, 03/05/2004
+ *  @since   1
+ *  @define Coll SynchronizedStack
+ *  @define coll synchronized stack
  */
 class SynchronizedStack[A] extends Stack[A] {
+  import scala.collection.Traversable
 
   /** Checks if the stack is empty.
    *
@@ -31,30 +37,25 @@ class SynchronizedStack[A] extends Stack[A] {
    *
    *  @param  elem        the element to push onto the stack
    */
-  override def +=(elem: A): Unit = synchronized { super.+=(elem) }
+  override def push(elem: A): this.type = synchronized[this.type] { super.push(elem) }
 
-  /** Pushes all elements provided by an <code>Iterable</code> object
-   *  on top of the stack. The elements are pushed in the order they
-   *  are given out by the iterator.
+  /** Push two or more elements onto the stack. The last element
+   *  of the sequence will be on top of the new stack.
    *
-   *  @param  iter        an iterable object
+   *  @param elem1      the first element to push.
+   *  @param elem2      the second element to push.
+   *  @param elems      the element sequence that will be pushed.
+   *  @return           the stack with the new elements on top.
    */
-  override def ++=(iter: Iterable[A]): Unit = synchronized { super.++=(iter) }
+  override def push(elem1: A, elem2: A, elems: A*): this.type = synchronized[this.type] { super.push(elem1, elem2, elems: _*) }
 
-  /** Pushes all elements provided by an iterator
-   *  on top of the stack. The elements are pushed in the order they
-   *  are given out by the iterator.
+  /** Pushes all elements provided by a traversable object
+   *  on top of the stack. The elements are pushed in the order the
+   *  traversable object is traversed.
    *
-   *  @param  iter        an iterator
+   *  @param  xs        a traversable object
    */
-    override def ++=(it: Iterator[A]): Unit = synchronized { super.++=(it) }
-
-  /** Pushes a sequence of elements on top of the stack. The first element
-   *  is pushed first, etc.
-   *
-   *  @param  elems       a sequence of elements
-   */
-  override def push(elems: A*): Unit = synchronized { super.++=(elems) }
+  override def pushAll(xs: TraversableOnce[A]): this.type = synchronized[this.type] { super.pushAll(elems) } 
 
   /** Returns the top element of the stack. This method will not remove
    *  the element from the stack. An error is signaled if there is no
@@ -82,7 +83,7 @@ class SynchronizedStack[A] extends Stack[A] {
    *
    *  @return an iterator over all stack elements.
    */
-  override def elements: Iterator[A] = synchronized { super.elements }
+  override def iterator: Iterator[A] = synchronized { super.iterator }
 
   /** Creates a list of all stack elements in FIFO order.
    *
@@ -90,19 +91,6 @@ class SynchronizedStack[A] extends Stack[A] {
    */
   override def toList: List[A] = synchronized { super.toList }
 
-  /** Checks if two stacks are structurally identical.
-   *
-   *  @return true, iff both stacks contain the same sequence of elements.
-   */
-    override def equals(that: Any): Boolean = synchronized { super.equals(that) }
-
-  /** The hashCode method always yields an error, since it is not
-   *  safe to use mutable stacks as keys in hash tables.
-   *
-   *  @return never.
-   */
-  override def hashCode(): Int = synchronized { super.hashCode() }
-
   /** Returns a textual representation of a stack as a string.
    *
    *  @return the string representation of this stack.
diff --git a/src/library/scala/collection/mutable/Traversable.scala b/src/library/scala/collection/mutable/Traversable.scala
new file mode 100644
index 0000000..e5c0b31
--- /dev/null
+++ b/src/library/scala/collection/mutable/Traversable.scala
@@ -0,0 +1,37 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+package mutable
+
+import generic._
+
+/** A trait for traversable collections that can be mutated.
+ *  $traversableInfo
+ *  @define mutability mutable
+ */
+trait Traversable[A] extends scala.collection.Traversable[A] 
+                        with GenericTraversableTemplate[A, Traversable] 
+                        with TraversableLike[A, Traversable[A]]
+                        with Mutable { 
+  override def companion: GenericCompanion[Traversable] = Traversable
+}
+
+/** $factoryInfo
+ *  The current default implementation of a $Coll is an `ArrayBuffer`.
+ *  @define coll mutable traversable collection
+ *  @define Coll mutable.Traversable
+ */
+object Traversable extends TraversableFactory[Traversable] {
+  implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, Traversable[A]] = new GenericCanBuildFrom[A]
+  def newBuilder[A]: Builder[A, Traversable[A]] = new ArrayBuffer
+}
+
+  
diff --git a/src/library/scala/collection/mutable/Undoable.scala b/src/library/scala/collection/mutable/Undoable.scala
index f7154a2..1a7f67a 100644
--- a/src/library/scala/collection/mutable/Undoable.scala
+++ b/src/library/scala/collection/mutable/Undoable.scala
@@ -1,26 +1,26 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Undoable.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.collection.mutable
+package scala.collection
+package mutable
 
 
-/** Classes that mix in the <code>Undoable</code> class provide an operation
- *  <code>undo</code> which can be used to undo the last operation.
+/** Classes that mix in the `Undoable` class provide an operation
+ *  `undo` which can be used to undo the last operation.
  *
  *  @author  Matthias Zenger
  *  @version 1.0, 08/07/2003
+ *  @since   1
  */
 trait Undoable {
-
-    /** Undo the last operation.
-     */
-    def undo()
+  /** Undo the last operation.
+   */
+  def undo(): Unit
 }
diff --git a/src/library/scala/collection/mutable/WeakHashMap.scala b/src/library/scala/collection/mutable/WeakHashMap.scala
new file mode 100644
index 0000000..1f8fbab
--- /dev/null
+++ b/src/library/scala/collection/mutable/WeakHashMap.scala
@@ -0,0 +1,51 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+package mutable
+
+import JavaConversions._
+import generic._
+
+
+/** A hash map with references to entries which are weakly reachable.
+ *  
+ *  @tparam A      type of keys contained in this map
+ *  @tparam B      type of values associated with the keys
+ *  
+ *  @since 2.8
+ *  @define Coll WeakHashMap
+ *  @define coll weak hash map
+ *  @define thatinfo the class of the returned collection. In the standard library configuration,
+ *    `That` is always `WeakHashMap[A, B]` if the elements contained in the resulting collection are 
+ *    pairs of type `(A, B)`. This is because an implicit of type `CanBuildFrom[WeakHashMap, (A, B), WeakHashMap[A, B]]`
+ *    is defined in object `WeakHashMap`. Otherwise, `That` resolves to the most specific type that doesn't have
+ *    to contain pairs of type `(A, B)`, which is `Iterable`.
+ *  @define $bfinfo an implicit value of class `CanBuildFrom` which determines the
+ *    result class `That` from the current representation type `Repr`
+ *    and the new element type `B`. This is usually the `canBuildFrom` value
+ *    defined in object `WeakHashMap`.
+ *  @define mayNotTerminateInf
+ *  @define willNotTerminateInf
+ */
+class WeakHashMap[A, B] extends JMapWrapper[A, B](new java.util.WeakHashMap)
+			   with JMapWrapperLike[A, B, WeakHashMap[A, B]] {
+  override def empty = new WeakHashMap[A, B]
+}
+
+/** $factoryInfo
+ *  @define Coll WeakHashMap
+ *  @define coll weak hash map
+ */
+object WeakHashMap extends MutableMapFactory[WeakHashMap] {
+  implicit def canBuildFrom[A, B]: CanBuildFrom[Coll, (A, B), WeakHashMap[A, B]] = new MapCanBuildFrom[A, B]
+  def empty[A, B]: WeakHashMap[A, B] = new WeakHashMap[A, B]
+}
+
diff --git a/src/library/scala/collection/mutable/WrappedArray.scala b/src/library/scala/collection/mutable/WrappedArray.scala
new file mode 100644
index 0000000..5385033
--- /dev/null
+++ b/src/library/scala/collection/mutable/WrappedArray.scala
@@ -0,0 +1,174 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+package mutable
+
+import scala.reflect.ClassManifest
+import scala.collection.generic._
+
+/**
+ *  A class representing `Array[T]`.
+ *  
+ *  @tparam T    type of the elements in this wrapped array.
+ *
+ *  @author  Martin Odersky, Stephane Micheloud
+ *  @version 1.0
+ *  @since 2.8
+ *  @define Coll WrappedArray
+ *  @define coll wrapped array
+ *  @define orderDependent 
+ *  @define orderDependentFold
+ *  @define mayNotTerminateInf
+ *  @define willNotTerminateInf
+ */
+abstract class WrappedArray[T] extends IndexedSeq[T] with ArrayLike[T, WrappedArray[T]] {
+
+  override protected[this] def thisCollection: WrappedArray[T] = this
+  override protected[this] def toCollection(repr: WrappedArray[T]): WrappedArray[T] = repr
+
+  /** The manifest of the element type */
+  def elemManifest: ClassManifest[T]
+
+  /** The length of the array */
+  def length: Int
+
+  /** The element at given index */
+  def apply(index: Int): T
+
+  /** Update element at given index */
+  def update(index: Int, elem: T): Unit
+
+  /** The underlying array */
+  def array: Array[T]                       
+
+  override def toArray[U >: T : ClassManifest]: Array[U] =
+    if (implicitly[ClassManifest[U]].erasure eq array.getClass.getComponentType)
+      array.asInstanceOf[Array[U]]
+    else 
+      super.toArray[U]
+                                                                            
+  override def stringPrefix = "WrappedArray"
+  
+  /** Clones this object, including the underlying Array. */
+  override def clone: WrappedArray[T] = WrappedArray make array.clone()
+ 
+  /** Creates new builder for this collection ==> move to subclasses
+   */
+  override protected[this] def newBuilder: Builder[T, WrappedArray[T]] = 
+    new WrappedArrayBuilder[T](elemManifest)
+}
+
+/** A companion object used to create instances of `WrappedArray`.
+ */
+object WrappedArray {  
+  def make[T](x: AnyRef): WrappedArray[T] = x match {
+    case x: Array[AnyRef] => wrapRefArray[AnyRef](x).asInstanceOf[WrappedArray[T]]
+    case x: Array[Int] => wrapIntArray(x).asInstanceOf[WrappedArray[T]]
+    case x: Array[Double] => wrapDoubleArray(x).asInstanceOf[WrappedArray[T]]
+    case x: Array[Long] => wrapLongArray(x).asInstanceOf[WrappedArray[T]]
+    case x: Array[Float] => wrapFloatArray(x).asInstanceOf[WrappedArray[T]]
+    case x: Array[Char] => wrapCharArray(x).asInstanceOf[WrappedArray[T]]
+    case x: Array[Byte] => wrapByteArray(x).asInstanceOf[WrappedArray[T]]
+    case x: Array[Short] => wrapShortArray(x).asInstanceOf[WrappedArray[T]]
+    case x: Array[Boolean] => wrapBooleanArray(x).asInstanceOf[WrappedArray[T]]
+    case x: Array[Unit] => wrapUnitArray(x).asInstanceOf[WrappedArray[T]]
+  }
+
+  implicit def canBuildFrom[T](implicit m: ClassManifest[T]): CanBuildFrom[WrappedArray[_], T, WrappedArray[T]] =
+    new CanBuildFrom[WrappedArray[_], T, WrappedArray[T]] {
+      def apply(from: WrappedArray[_]): Builder[T, WrappedArray[T]] =
+        ArrayBuilder.make[T]()(m) mapResult WrappedArray.make[T]
+      def apply: Builder[T, WrappedArray[T]] =
+        ArrayBuilder.make[T]()(m) mapResult WrappedArray.make[T]
+  }
+    
+  def newBuilder[A]: Builder[A, IndexedSeq[A]] = new ArrayBuffer
+
+  @serializable
+  final class ofRef[T <: AnyRef](val array: Array[T]) extends WrappedArray[T] {
+    lazy val elemManifest = ClassManifest.classType[T](array.getClass.getComponentType)
+    def length: Int = array.length
+    def apply(index: Int): T = array(index).asInstanceOf[T]
+    def update(index: Int, elem: T) { array(index) = elem }
+  }
+
+  @serializable
+  final class ofByte(val array: Array[Byte]) extends WrappedArray[Byte] {
+    def elemManifest = ClassManifest.Byte
+    def length: Int = array.length
+    def apply(index: Int): Byte = array(index)
+    def update(index: Int, elem: Byte) { array(index) = elem }
+  }
+
+  @serializable
+  final class ofShort(val array: Array[Short]) extends WrappedArray[Short] {
+    def elemManifest = ClassManifest.Short
+    def length: Int = array.length
+    def apply(index: Int): Short = array(index)
+    def update(index: Int, elem: Short) { array(index) = elem }
+  }
+
+  @serializable
+  final class ofChar(val array: Array[Char]) extends WrappedArray[Char] {
+    def elemManifest = ClassManifest.Char
+    def length: Int = array.length
+    def apply(index: Int): Char = array(index)
+    def update(index: Int, elem: Char) { array(index) = elem }
+  }
+
+  @serializable
+  final class ofInt(val array: Array[Int]) extends WrappedArray[Int] {
+    def elemManifest = ClassManifest.Int
+    def length: Int = array.length
+    def apply(index: Int): Int = array(index)
+    def update(index: Int, elem: Int) { array(index) = elem }
+  }
+
+  @serializable
+  final class ofLong(val array: Array[Long]) extends WrappedArray[Long] {
+    def elemManifest = ClassManifest.Long
+    def length: Int = array.length
+    def apply(index: Int): Long = array(index)
+    def update(index: Int, elem: Long) { array(index) = elem }
+  }
+
+  @serializable
+  final class ofFloat(val array: Array[Float]) extends WrappedArray[Float] {
+    def elemManifest = ClassManifest.Float
+    def length: Int = array.length
+    def apply(index: Int): Float = array(index)
+    def update(index: Int, elem: Float) { array(index) = elem }
+  }
+
+  @serializable
+  final class ofDouble(val array: Array[Double]) extends WrappedArray[Double] {
+    def elemManifest = ClassManifest.Double
+    def length: Int = array.length
+    def apply(index: Int): Double = array(index)
+    def update(index: Int, elem: Double) { array(index) = elem }
+  }
+
+  @serializable
+  final class ofBoolean(val array: Array[Boolean]) extends WrappedArray[Boolean] {
+    def elemManifest = ClassManifest.Boolean
+    def length: Int = array.length
+    def apply(index: Int): Boolean = array(index)
+    def update(index: Int, elem: Boolean) { array(index) = elem }
+  }
+
+  @serializable
+  final class ofUnit(val array: Array[Unit]) extends WrappedArray[Unit] {
+    def elemManifest = ClassManifest.Unit
+    def length: Int = array.length
+    def apply(index: Int): Unit = array(index)
+    def update(index: Int, elem: Unit) { array(index) = elem }
+  }
+}
diff --git a/src/library/scala/collection/mutable/WrappedArrayBuilder.scala b/src/library/scala/collection/mutable/WrappedArrayBuilder.scala
new file mode 100644
index 0000000..345e481
--- /dev/null
+++ b/src/library/scala/collection/mutable/WrappedArrayBuilder.scala
@@ -0,0 +1,70 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+package mutable
+
+import generic._
+import scala.reflect.ClassManifest
+
+/** A builder class for arrays.
+ *  
+ *  @tparam A         type of elements that can be added to this builder.
+ *  @param manifest   class manifest for objects of type `A`.
+ *  
+ *  @since 2.8
+ */
+class WrappedArrayBuilder[A](manifest: ClassManifest[A]) extends Builder[A, WrappedArray[A]] {
+
+  private var elems: WrappedArray[A] = _
+  private var capacity: Int = 0
+  private var size: Int = 0
+
+  private def mkArray(size: Int): WrappedArray[A] = {
+    val newelems = manifest.newWrappedArray(size)
+    if (this.size > 0) Array.copy(elems.array, 0, newelems.array, 0, this.size)
+    newelems
+  }
+
+  private def resize(size: Int) {
+    elems = mkArray(size)
+    capacity = size
+  }
+  
+  override def sizeHint(size: Int) {
+    if (capacity < size) resize(size)
+  }
+
+  private def ensureSize(size: Int) {
+    if (capacity < size) {
+      var newsize = if (capacity == 0) 16 else capacity * 2
+      while (newsize < size) newsize *= 2
+      resize(newsize)
+    }
+  } 
+  
+  def +=(elem: A): this.type = {
+    ensureSize(size + 1)
+    elems(size) = elem
+    size += 1
+    this
+  }
+
+  def clear() {
+    size = 0
+  }
+
+  def result() = {
+    if (capacity != 0 && capacity == size) elems 
+    else mkArray(size)
+  }
+
+  // todo: add ++=
+}
diff --git a/src/library/scala/collection/package.scala b/src/library/scala/collection/package.scala
new file mode 100644
index 0000000..ad0c27d
--- /dev/null
+++ b/src/library/scala/collection/package.scala
@@ -0,0 +1,79 @@
+package scala
+
+/**
+ * Contains the base traits and objects needed to use and extend Scala's collection library.
+ *
+ * == Guide ==
+ *
+ * A detailed guide for the collections library is avaialble 
+ * at [[http://www.scala-lang.org/docu/files/collections-api]].
+ *
+ * == Using Collections ==
+ *
+ * It is convienient to treat all collections as either 
+ * a [[scala.collection.Traversable]] or [[scala.collection.Iterable]], as 
+ * these traits define the vast majority of operations
+ * on a collection.
+ *
+ * Collections can, of course, be treated as specifically as needed, and
+ * the library is designed to ensure that 
+ * the methods that transform collections will return a collection of the same
+ * type: {{{
+ * scala> val array = Array(1,2,3,4,5,6)
+ * array: Array[Int] = Array(1, 2, 3, 4, 5, 6)
+ * 
+ * scala> array map { _.toString }
+ * res0: Array[java.lang.String] = Array(1, 2, 3, 4, 5, 6)
+ * 
+ * scala> val list = List(1,2,3,4,5,6)
+ * list: List[Int] = List(1, 2, 3, 4, 5, 6)
+ * 
+ * scala> list map { _.toString }
+ * res1: List[java.lang.String] = List(1, 2, 3, 4, 5, 6)
+ * 
+ * }}}
+ * 
+ * == Creating Collections ==
+ *
+ * The most common way to create a collection is to use the companion objects as factories.
+ * Of these, the three most common 
+ * are [[scala.collection.immutable.Seq]], [[scala.collection.immutable.Set]], and [[scala.collection.immutable.Map]].  Their 
+ * companion objects are all available
+ * as type aliases the either the [[scala]] package or in `scala.Predef`, and can be used
+ * like so:
+ * {{{
+ * scala> val seq = Seq(1,2,3,4,1)
+ * seq: Seq[Int] = List(1, 2, 3, 4, 1)
+ * 
+ * scala> val set = Set(1,2,3,4,1)
+ * set: scala.collection.immutable.Set[Int] = Set(1, 2, 3, 4)
+ *
+ * scala> val map = Map(1 -> "one",2 -> "two", 3 -> "three",2 -> "too")
+ * map: scala.collection.immutable.Map[Int,java.lang.String] = Map((1,one), (2,too), (3,three))
+ * }}}
+ *
+ * It is also typical to use the [[scala.collection.immutable]] collections over those
+ * in [[scala.collection.mutable]]; The types aliased in the [[scala]] package and
+ * the `scala.Predef` object are the immutable versions.
+ *
+ * Also note that the collections library was carefully designed to include several implementations of
+ * each of the three basic collection types. These implementations have specific performance
+ * characteristics which are described 
+ * in [[http://www.scala-lang.org/docu/files/collections-api the guide]].
+ *
+ * === Converting between Java Collections ===
+ *
+ * The `JavaConversions` object provides implicit defs that will allow mostly seamless integration
+ * between Java Collections-based APIs and the Scala collections library.
+ *
+ */
+package object collection {
+  import scala.collection.generic.CanBuildFrom // can't refer to CanBuild here
+
+  /** Provides a CanBuildFrom instance that builds a specific target collection (`To') irrespective of the original collection (`From').
+   */
+  def breakOut[From, T, To](implicit b : CanBuildFrom[Nothing, T, To]) =
+    new CanBuildFrom[From, T, To] { // TODO: could we just return b instead?
+      def apply(from: From) = b.apply() ; def apply() = b.apply()
+    }
+}
diff --git a/src/library/scala/collection/readme-if-you-want-to-add-something.txt b/src/library/scala/collection/readme-if-you-want-to-add-something.txt
new file mode 100644
index 0000000..6700cb7
--- /dev/null
+++ b/src/library/scala/collection/readme-if-you-want-to-add-something.txt
@@ -0,0 +1,50 @@
+Conventions for Collection Implementors
+
+Martin Odersky
+19 Mar 2010
+
+This note describes some conventions which must be followed to keep
+the collection libraries consistent.
+
+We distinguish in the following between two kinds of methods
+
+ - ``Accessors'' access some of the elements of a collection, but return a result which
+   is unrelated to the collection. 
+   Example of accessors are: head, foldLeft, indexWhere, toSeq.
+
+ - ``Transformers'' access elements of a collection and produce a new collection of related
+   type as a result. The relation might either be direct (same type as receiver)
+   or indirect, linked by a CanBuildFrom implicit.
+   Example of transformers are: filter, map, groupBy, zip.
+
+1. Proxies
+
+Every collection type has a Proxy class that forwards all operations to
+an underlying collection. Proxy methods are all implemented in classes
+with names ending in `ProxyLike'. If you add a new method to a collection 
+class you need to add the same method to the corresponding ProxyLike class.
+
+2. Forwarders
+
+Classes Traversable, Iterable, and Seq also have forwarders, which
+forward all collection-specific accessor operations to an underlying
+collection. These are defined as classes with names ending
+in `Forwarder' in package collection.generic.  If you add a new
+accessor method to a Seq or one of its collection superclasses, you
+need to add the same method to the corresponding forwarder class.
+
+3. Views
+
+Classes Traversable, Iterable, Seq, IndexedSeq, and mutable.IndexedSeq
+support views. Their operations are all defined in classes with names
+ending in `ViewLike'. If you add a new transformer method to one of
+the above collection classes, you need to add the same method to the
+corresponding view class. Failure to do so will cause the
+corresponding method to fail at runtime with an exception like
+UnsupportedOperationException("coll.newBuilder"). If there is no good
+way to implement the operation in question lazily, there's a fallback
+using the newForced method. See the definition of sorted in trait
+SeqViewLike as an example.
+
+
+ 
diff --git a/src/library/scala/collection/script/Location.scala b/src/library/scala/collection/script/Location.scala
new file mode 100644
index 0000000..55ee613
--- /dev/null
+++ b/src/library/scala/collection/script/Location.scala
@@ -0,0 +1,27 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+package script
+
+
+/** Class <code>Location</code> describes locations in messages implemented by
+ *  class <a href="Message.html" target="contentFrame"><code>Message</code></a>.
+ *
+ *  @author  Matthias Zenger
+ *  @version 1.0, 10/05/2004
+ *  @since   2.8
+ */
+
+sealed abstract class Location
+case object Start extends Location
+case object End extends Location
+case object NoLo extends Location
+case class Index(n: Int) extends Location
diff --git a/src/library/scala/collection/script/Message.scala b/src/library/scala/collection/script/Message.scala
new file mode 100644
index 0000000..bf813a4
--- /dev/null
+++ b/src/library/scala/collection/script/Message.scala
@@ -0,0 +1,85 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+package script
+
+import mutable.ArrayBuffer
+
+/** Class <code>Message</code> represents messages that are issued by observable
+ *  collection classes whenever a data structure is changed. Class <code>Message</code>
+ *  has several subclasses for the various kinds of events: <code>Update</code>
+ *  <code>Remove</code>, <code>Include</code>, <code>Reset</code>, and
+ *  <code>Script</code>.
+ *
+ *  @author  Matthias Zenger
+ *  @version 1.0, 08/07/2003
+ *  @since   2.8
+ */
+trait Message[+A]
+
+/** This observable update refers to inclusion operations that add new elements
+ *  to collection classes.
+ *
+ *  @author  Matthias Zenger
+ *  @version 1.0, 08/07/2003
+ */
+case class Include[+A](location: Location, elem: A) extends Message[A] {
+  def this(elem: A) = this(NoLo, elem)
+}
+
+/** This observable update refers to destructive modification operations
+ *  of elements from collection classes.
+ *
+ *  @author  Matthias Zenger
+ *  @version 1.0, 08/07/2003
+ */
+case class Update[+A](location: Location, elem: A) extends Message[A] {
+  def this(elem: A) = this(NoLo, elem)
+}
+
+/** This observable update refers to removal operations of elements
+ *  from collection classes.
+ *
+ *  @author  Matthias Zenger
+ *  @version 1.0, 08/07/2003
+ */
+case class Remove[+A](location: Location, elem: A) extends Message[A] {
+  def this(elem: A) = this(NoLo, elem)
+}
+
+/** This command refers to reset operations.
+ *
+ *  @author  Matthias Zenger
+ *  @version 1.0, 08/07/2003
+ */
+case class Reset[+A]() extends Message[A]
+
+/** Objects of this class represent compound messages consisting
+ *  of a sequence of other messages.
+ *
+ *  @author  Matthias Zenger
+ *  @version 1.0, 10/05/2004
+ */
+class Script[A] extends ArrayBuffer[Message[A]] with Message[A] {
+
+  override def toString(): String = {
+    var res = "Script("
+    var it = this.iterator
+    var i = 1
+    while (it.hasNext) {
+      if (i > 1)
+        res = res + ", "
+      res = res + "[" + i + "] " + it.next
+      i = i + 1
+    }
+    res + ")"
+  }
+}
diff --git a/src/library/scala/collection/script/Scriptable.scala b/src/library/scala/collection/script/Scriptable.scala
new file mode 100644
index 0000000..ccee3c4
--- /dev/null
+++ b/src/library/scala/collection/script/Scriptable.scala
@@ -0,0 +1,26 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.collection
+package script
+
+
+/** Classes that mix in the <code>Scriptable</code> class allow
+ *  messages to be sent to objects of that class.
+ *
+ *  @author  Matthias Zenger
+ *  @version 1.0, 09/05/2004
+ *  @since   2.8
+ */
+trait Scriptable[A] {
+  /** Send a message to this scriptable object.
+   */
+  def <<(cmd: Message[A]): Unit
+}
diff --git a/src/library/scala/compat/Platform.scala b/src/library/scala/compat/Platform.scala
index d1542ff..b615cdf 100644
--- a/src/library/scala/compat/Platform.scala
+++ b/src/library/scala/compat/Platform.scala
@@ -1,32 +1,40 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Platform.scala 16881 2009-01-09 16:28:11Z cunei $
 
 
 package scala.compat
 
-
 import java.lang.System
-import Predef._
 
 object Platform {
 
   type StackOverflowError = java.lang.StackOverflowError
   type ConcurrentModificationException = java.util.ConcurrentModificationException
 
-  /**
-   *  @param src     ..
-   *  @param srcPos  ..
-   *  @param dest    ..
-   *  @param destPos ..
-   *  @param length  ..
-   */
+  /** Copies `length` elements of array `src` starting at position `srcPos` to the
+    * array `dest` starting at position `destPos`. If `src eq dest`, the copying will
+    * behave as if the elements copied from `src` were first copied to a temporary
+    * array before being copied back into the array at the destination positions.
+    * @param src     A non-null array as source for the copy.
+    * @param srcPos  The starting index in the source array.
+    * @param dest    A non-null array as destination for the copy.
+    * @param destPos The starting index in the destination array.
+    * @param length  The number of elements to be copied.
+    * @throws java.lang.NullPointerException If either `src` or `dest` are `null`.
+    * @throws java.lang.ArrayStoreException If either `src` or `dest` are not of type
+    *                [java.lang.Array]; or if the element type of `src` is not
+    *                compatible with that of `dest`.
+    * @throws java.lang.IndexOutOfBoundsException If either srcPos` or `destPos` are
+    *                outside of the bounds of their respective arrays; or if `length`
+    *                is negative; or if there are less than `length` elements available
+    *                after `srcPos` or `destPos` in `src` and `dest` respectively. */
+  @inline
   def arraycopy(src: AnyRef, srcPos: Int, dest: AnyRef, destPos: Int, length: Int) {
     System.arraycopy(src, srcPos, dest, destPos, length)
   }
@@ -38,23 +46,30 @@ object Platform {
    *  @param length    ..
    *  @return          ..
    */
+  @inline
   def createArray(elemClass: Class[_], length: Int): AnyRef =
     java.lang.reflect.Array.newInstance(elemClass, length)
 
+  @inline
   def arrayclear(arr: Array[Int]) { java.util.Arrays.fill(arr, 0) }
 
+  @inline
   def getClassForName(name: String): Class[_] = java.lang.Class.forName(name)
 
-  val EOL = System.getProperty("line.separator", "\n")
+  val EOL = util.Properties.lineSeparator
 
+  /** The current time in milliseconds. The time is counted since 1 January 1970
+    * UTC.
+    * 
+    * Note that the operating system timer used to obtain this value may be less
+    * precise than a millisecond. */
+  @inline
   def currentTime: Long = System.currentTimeMillis()
 
+  @inline
   def collectGarbage: Unit = System.gc()
 
   /** The name of the default character set encoding as a string */
-  def defaultCharsetName: String = {
-    import java.io._
-    new OutputStreamWriter(new ByteArrayOutputStream).getEncoding()
-  }
-
+  @inline
+  def defaultCharsetName: String = java.nio.charset.Charset.defaultCharset.name
 }
diff --git a/src/library/scala/concurrent/Channel.scala b/src/library/scala/concurrent/Channel.scala
index 5eaf455..865d018 100644
--- a/src/library/scala/concurrent/Channel.scala
+++ b/src/library/scala/concurrent/Channel.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Channel.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala.concurrent
@@ -16,28 +15,28 @@ package scala.concurrent
  *  @author  Martin Odersky
  *  @version 1.0, 10/03/2003
  */
-class Channel[a] {
-  class LinkedList[a] {
-    var elem: a = _
-    var next: LinkedList[a] = null
+class Channel[A] {
+  class LinkedList[A] {
+    var elem: A = _
+    var next: LinkedList[A] = null
   }
-  private var written = new LinkedList[a] // FIFO buffer, realized through
+  private var written = new LinkedList[A] // FIFO buffer, realized through
   private var lastWritten = written       // aliasing of a linked list
   private var nreaders = 0
 
   /**
    *  @param x ...
    */
-  def write(x: a) = synchronized {
+  def write(x: A) = synchronized {
     lastWritten.elem = x
-    lastWritten.next = new LinkedList[a]
+    lastWritten.next = new LinkedList[A]
     lastWritten = lastWritten.next
     if (nreaders > 0) notify()
   }
 
-  def read: a = synchronized {
+  def read: A = synchronized {
     while (null == written.next) {
-      nreaders = nreaders + 1; wait(); nreaders = nreaders - 1
+      nreaders += 1; wait(); nreaders -= 1
     }
     val x = written.elem
     written = written.next
diff --git a/src/library/scala/concurrent/DelayedLazyVal.scala b/src/library/scala/concurrent/DelayedLazyVal.scala
new file mode 100644
index 0000000..40b41b4
--- /dev/null
+++ b/src/library/scala/concurrent/DelayedLazyVal.scala
@@ -0,0 +1,48 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+package scala.concurrent
+
+import ops.future
+
+/** A <code>DelayedLazyVal</code> is a wrapper for lengthy
+ *  computations which have a valid partially computed result.
+ *  The first argument is a function for obtaining the result
+ *  at any given point in time, and the second is the lengthy
+ *  computation.  Once the computation is complete, the apply()
+ *  method will stop recalculating it and return a fixed value
+ *  from that point forward.
+ *
+ *  @param  f      the function to obtain the current value at any point in time
+ *  @param  body   the computation to run to completion in another thread
+ *
+ *  @author  Paul Phillips
+ *  @version 2.8
+ */
+class DelayedLazyVal[T](f: () => T, body: => Unit) {
+  @volatile private[this] var _isDone = false
+  private[this] lazy val complete = f()
+
+  /** Whether the computation is complete.
+   *
+   *  @return true if the computation is complete.
+   */
+  def isDone = _isDone
+  
+  /** The current result of f(), or the final result if complete.
+   *
+   *  @return the current value
+   */
+  def apply(): T = if (isDone) complete else f()
+  
+  future {
+    body
+    _isDone = true
+  }
+}
diff --git a/src/library/scala/concurrent/FutureTaskRunner.scala b/src/library/scala/concurrent/FutureTaskRunner.scala
new file mode 100644
index 0000000..de3184a
--- /dev/null
+++ b/src/library/scala/concurrent/FutureTaskRunner.scala
@@ -0,0 +1,17 @@
+package scala.concurrent
+
+/** The <code>FutureTaskRunner</code> trait...
+ *  
+ *  @author Philipp Haller
+ */
+trait FutureTaskRunner extends TaskRunner {
+
+  type Future[T]
+
+  implicit def futureAsFunction[S](x: Future[S]): () => S
+
+  def submit[S](task: Task[S]): Future[S]
+
+  def managedBlock(blocker: ManagedBlocker): Unit
+
+}
diff --git a/src/library/scala/concurrent/JavaConversions.scala b/src/library/scala/concurrent/JavaConversions.scala
new file mode 100644
index 0000000..1dbf883
--- /dev/null
+++ b/src/library/scala/concurrent/JavaConversions.scala
@@ -0,0 +1,50 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.concurrent
+
+import java.util.concurrent.{ExecutorService, Executor}
+
+/** The <code>JavaConversions</code> object...
+ *  
+ *  @author Philipp Haller
+ */
+object JavaConversions {
+
+  implicit def asTaskRunner(exec: ExecutorService): FutureTaskRunner =
+    new ThreadPoolRunner {
+      override protected def executor =
+        exec
+
+      def shutdown() =
+        exec.shutdown()
+    }
+
+  implicit def asTaskRunner(exec: Executor): TaskRunner =
+    new TaskRunner {
+      type Task[T] = Runnable
+
+      implicit def functionAsTask[T](fun: () => T): Task[T] = new Runnable {
+        def run() { fun() }
+      }
+
+      def execute[S](task: Task[S]) {
+        exec.execute(task)
+      }
+
+      def managedBlock(blocker: ManagedBlocker) {
+        blocker.block()
+      }
+
+      def shutdown() {
+        // do nothing
+      }
+    }
+}
diff --git a/src/library/scala/concurrent/Lock.scala b/src/library/scala/concurrent/Lock.scala
index 5263cb0..678d6fe 100644
--- a/src/library/scala/concurrent/Lock.scala
+++ b/src/library/scala/concurrent/Lock.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Lock.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala.concurrent
diff --git a/src/library/scala/concurrent/MailBox.scala b/src/library/scala/concurrent/MailBox.scala
index 733ae21..c73b1ab 100644
--- a/src/library/scala/concurrent/MailBox.scala
+++ b/src/library/scala/concurrent/MailBox.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: MailBox.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala.concurrent
diff --git a/src/library/scala/concurrent/ManagedBlocker.scala b/src/library/scala/concurrent/ManagedBlocker.scala
new file mode 100644
index 0000000..4eb871d
--- /dev/null
+++ b/src/library/scala/concurrent/ManagedBlocker.scala
@@ -0,0 +1,34 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.concurrent
+
+/** The <code>ManagedBlocker</code> trait...
+ *  
+ *  @author Philipp Haller
+ */
+trait ManagedBlocker {
+
+  /**
+   * Possibly blocks the current thread, for example waiting for
+   * a lock or condition.
+   * @return true if no additional blocking is necessary (i.e.,
+   * if isReleasable would return true).
+   * @throws InterruptedException if interrupted while waiting
+   * (the method is not required to do so, but is allowed to).
+   */
+  def block(): Boolean
+
+  /**
+   * Returns true if blocking is unnecessary.
+   */
+  def isReleasable: Boolean
+
+}
diff --git a/src/library/scala/concurrent/SyncChannel.scala b/src/library/scala/concurrent/SyncChannel.scala
index ccada92..1c025bc 100644
--- a/src/library/scala/concurrent/SyncChannel.scala
+++ b/src/library/scala/concurrent/SyncChannel.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: SyncChannel.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala.concurrent
diff --git a/src/library/scala/concurrent/SyncVar.scala b/src/library/scala/concurrent/SyncVar.scala
index a0acb13..88afa0f 100644
--- a/src/library/scala/concurrent/SyncVar.scala
+++ b/src/library/scala/concurrent/SyncVar.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: SyncVar.scala 18846 2009-10-01 07:30:14Z phaller $
 
 
 package scala.concurrent
@@ -14,7 +13,7 @@ package scala.concurrent
 
 /** The class <code>SyncVar</code> ...
  *
- *  @author  Martin Odersky, Stepan Koltsov
+ *  @author  Martin Odersky
  *  @version 1.0, 10/03/2003
  */
 class SyncVar[A] {
@@ -27,7 +26,21 @@ class SyncVar[A] {
     if (exception.isEmpty) value
     else throw exception.get
   }
-  
+
+  def get(timeout: Long): Option[A] = synchronized {
+    if (!isDefined) {
+      try {
+        wait(timeout)
+      } catch {
+        case _: InterruptedException =>
+      }
+    }
+    if (exception.isEmpty) {
+      if (isDefined) Some(value) else None
+    } else
+      throw exception.get
+  }
+
   def take() = synchronized {
     try {
       get
@@ -48,20 +61,7 @@ class SyncVar[A] {
     isDefined = true
     notifyAll()
   }
-  
-  /**
-   *  @deprecated Will be removed in 2.8. SyncVar should not allow exception by design.
-   */
-  @deprecated def setWithCatch(x: => A) = synchronized {
-    try {
-      this set x
-    } catch {
-      case e =>
-        this setException e
-        throw e
-    }
-  }
-  
+
   def put(x: A) = synchronized {
     while (isDefined) wait()
     set(x)
diff --git a/src/library/scala/concurrent/TIMEOUT.scala b/src/library/scala/concurrent/TIMEOUT.scala
index 8e7d019..cd2d861 100644
--- a/src/library/scala/concurrent/TIMEOUT.scala
+++ b/src/library/scala/concurrent/TIMEOUT.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: TIMEOUT.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala.concurrent
diff --git a/src/library/scala/concurrent/TaskRunner.scala b/src/library/scala/concurrent/TaskRunner.scala
new file mode 100644
index 0000000..ceee851
--- /dev/null
+++ b/src/library/scala/concurrent/TaskRunner.scala
@@ -0,0 +1,27 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.concurrent
+
+/** The <code>TaskRunner</code> trait...
+ *  
+ *  @author Philipp Haller
+ */
+trait TaskRunner {
+
+  type Task[T]
+
+  implicit def functionAsTask[S](fun: () => S): Task[S]
+
+  def execute[S](task: Task[S]): Unit
+
+  def shutdown(): Unit
+
+}
diff --git a/src/library/scala/concurrent/TaskRunners.scala b/src/library/scala/concurrent/TaskRunners.scala
new file mode 100644
index 0000000..be63092
--- /dev/null
+++ b/src/library/scala/concurrent/TaskRunners.scala
@@ -0,0 +1,37 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.concurrent
+
+import java.util.concurrent.{ThreadPoolExecutor, LinkedBlockingQueue, TimeUnit}
+
+/** The <code>TaskRunners</code> object...
+ *  
+ *  @author Philipp Haller
+ */
+object TaskRunners {
+
+  implicit val threadRunner: FutureTaskRunner =
+    new ThreadRunner
+
+  implicit val threadPoolRunner: FutureTaskRunner = {
+    val numCores = Runtime.getRuntime().availableProcessors()
+    val keepAliveTime = 60000L
+    val workQueue = new LinkedBlockingQueue[Runnable]
+    val exec = new ThreadPoolExecutor(numCores,
+                                      numCores,
+                                      keepAliveTime,
+                                      TimeUnit.MILLISECONDS,
+                                      workQueue,
+                                      new ThreadPoolExecutor.CallerRunsPolicy)
+    JavaConversions.asTaskRunner(exec)
+  }
+
+}
diff --git a/src/library/scala/concurrent/ThreadPoolRunner.scala b/src/library/scala/concurrent/ThreadPoolRunner.scala
new file mode 100644
index 0000000..56d2d4e
--- /dev/null
+++ b/src/library/scala/concurrent/ThreadPoolRunner.scala
@@ -0,0 +1,51 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.concurrent
+
+import java.util.concurrent.{ExecutorService, Callable, TimeUnit}
+
+/** The <code>ThreadPoolRunner</code> trait uses
+ *  a <code>java.util.concurrent.ExecutorService</code>
+ *  to run submitted tasks.
+ *  
+ *  @author Philipp Haller
+ */
+trait ThreadPoolRunner extends FutureTaskRunner {
+
+  type Task[T] = Callable[T] with Runnable
+  type Future[T] = java.util.concurrent.Future[T]
+
+  private class RunCallable[S](fun: () => S) extends Runnable with Callable[S] {
+    def run() = fun()
+    def call() = fun()
+  }
+
+  implicit def functionAsTask[S](fun: () => S): Task[S] =
+    new RunCallable(fun)
+
+  implicit def futureAsFunction[S](x: Future[S]): () => S =
+    () => x.get()
+
+  protected def executor: ExecutorService
+
+  def submit[S](task: Task[S]): Future[S] = {
+    executor.submit[S](task)
+  }
+
+  def execute[S](task: Task[S]) {
+    executor execute task
+  }
+
+  def managedBlock(blocker: ManagedBlocker) {
+    blocker.block()
+  }
+
+}
diff --git a/src/library/scala/concurrent/ThreadRunner.scala b/src/library/scala/concurrent/ThreadRunner.scala
new file mode 100644
index 0000000..bf6613d
--- /dev/null
+++ b/src/library/scala/concurrent/ThreadRunner.scala
@@ -0,0 +1,59 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.concurrent
+
+import java.lang.Thread
+
+/** The <code>ThreadRunner</code> trait...
+ *  
+ *  @author Philipp Haller
+ */
+class ThreadRunner extends FutureTaskRunner {
+
+  type Task[T] = () => T
+  type Future[T] = () => T
+
+  implicit def functionAsTask[S](fun: () => S): Task[S] = fun
+  implicit def futureAsFunction[S](x: Future[S]): () => S = x
+
+  /* If expression computed successfully return it in `Right`,
+   * otherwise return exception in `Left`.
+   */
+  private def tryCatch[A](body: => A): Either[Exception, A] =
+    try Right(body) catch {
+      case ex: Exception => Left(ex)
+    }
+
+  def execute[S](task: Task[S]) {
+    val runnable = new Runnable {
+      def run() { tryCatch(task()) }
+    }
+    (new Thread(runnable)).start()
+  }
+
+  def submit[S](task: Task[S]): Future[S] = {
+    val result = new SyncVar[Either[Exception, S]]
+    val runnable = new Runnable {
+      def run() { result set tryCatch(task()) }
+    }
+    (new Thread(runnable)).start()
+    () => result.get.fold[S](throw _, identity _)
+  }
+
+  def managedBlock(blocker: ManagedBlocker) {
+    blocker.block()
+  }
+
+  def shutdown() {
+    // do nothing
+  }
+
+}
diff --git a/src/library/scala/concurrent/jolib.scala b/src/library/scala/concurrent/jolib.scala
deleted file mode 100644
index 403803d..0000000
--- a/src/library/scala/concurrent/jolib.scala
+++ /dev/null
@@ -1,80 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: jolib.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala.concurrent
-
-
-/**
- * Library for using join-calculus concurrent primitives in Scala.
- *
- * @author  Vincent Cremet
- * @version 1.0, 17/10/2003
- */ 
- at deprecated object jolib {
-
-  type Pattern = List[Signal]
-
-  type Rule = PartialFunction[List[Any], Unit]
-
-  /////////////////// JOIN DEFINITION /////////////////////////
-
-  class Join {
-
-    private var ruls: List[(Pattern, Rule)] = null
-
-    def canMatch(p: Pattern) =
-      p forall { s => !s.queue.isEmpty }
-    
-    def values(p: Pattern): List[Any] =
-      p map { s => s.queue.dequeue: Any }
-
-    def rules(rs: (Pattern, Rule)*) =
-      ruls = rs.asInstanceOf[List[(Pattern, Rule)]]
-
-    def tryMatch =
-      ruls find { case (p, _) => canMatch(p) } match {
-        case None => () => ()
-        case Some((p, r)) => {
-          val args = values(p)
-          () => concurrent.ops.spawn(r(args))
-        }
-      }
-
-  }
-
-  /////////////////// SIGNALS /////////////////////////
-  
-  abstract class Signal(join: Join) {
-    type C
-    val queue = new collection.mutable.Queue[C]
-    def tryReduction(x: C) {
-      val continuation = join synchronized {
-        queue.enqueue(x)
-        join.tryMatch
-      }
-      continuation()
-    }
-  }
-
-  abstract class Asynchr(join: Join) extends Signal(join) {
-    def apply(x: C): Unit = tryReduction(x)
-  }
-
-  abstract class Synchr[A](join: Join) extends Signal(join) {
-    type C <: SyncVar[A]
-    def apply(x: C): A = {
-      tryReduction(x)
-      x.get
-    }
-  }
-
-}
-
diff --git a/src/library/scala/concurrent/ops.scala b/src/library/scala/concurrent/ops.scala
index 97cbf83..8d0bc5a 100644
--- a/src/library/scala/concurrent/ops.scala
+++ b/src/library/scala/concurrent/ops.scala
@@ -1,57 +1,50 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: ops.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala.concurrent
 
-
 import java.lang.Thread
+import scala.util.control.Exception.allCatch
 
 /** The object <code>ops</code> ...
  *
- *  @author  Martin Odersky, Stepan Koltsov
- *  @version 1.0, 12/03/2003
+ *  @author  Martin Odersky, Stepan Koltsov, Philipp Haller
  */
-object ops {
+object ops
+{
+  val defaultRunner: FutureTaskRunner = TaskRunners.threadRunner
+
   /**
-   *  If expression computed successfully return it in <code>Left</code>,
-   *  otherwise return exception in <code>Right</code>.
+   *  If expression computed successfully return it in `Right`,
+   *  otherwise return exception in `Left`.
    */
-  private def tryCatch[A](left: => A): Either[A, Throwable] = {
-    try {
-      Left(left)
-    } catch {
-      case t => Right(t)
-    }
-  }
+  private def tryCatch[A](body: => A): Either[Throwable, A] =
+    allCatch[A] either body
+
+  private def getOrThrow[T <: Throwable, A](x: Either[T, A]): A =
+    x.fold[A](throw _, identity _)
 
   /** Evaluates an expression asynchronously.
    *
    *  @param  p the expression to evaluate
    */
-  def spawn(p: => Unit) = {
-    val t = new Thread() { override def run() = p }
-    t.start()
+  def spawn(p: => Unit)(implicit runner: TaskRunner = defaultRunner): Unit = {
+    runner execute runner.functionAsTask(() => p)
   }
 
   /**
    *  @param p ...
    *  @return  ...
    */
-  def future[A](p: => A): () => A = {
-    val result = new SyncVar[Either[A, Throwable]]
-    spawn { result set tryCatch(p) }
-    () => result.get match {
-    	case Left(a) => a
-    	case Right(t) => throw t
-    }
+  def future[A](p: => A)(implicit runner: FutureTaskRunner = defaultRunner): () => A = {
+    runner.futureAsFunction(runner submit runner.functionAsTask(() => p))
   }
 
   /**
@@ -60,12 +53,9 @@ object ops {
    *  @return   ...
    */
   def par[A, B](xp: => A, yp: => B): (A, B) = {
-    val y = new SyncVar[Either[B, Throwable]]
+    val y = new SyncVar[Either[Throwable, B]]
     spawn { y set tryCatch(yp) }
-    (xp, y.get match {
-    	case Left(b) => b
-    	case Right(t) => throw t
-    })
+    (xp, getOrThrow(y.get))
   }
 
   /**
diff --git a/src/library/scala/concurrent/pilib.scala b/src/library/scala/concurrent/pilib.scala
index f51e30f..9be8d0e 100644
--- a/src/library/scala/concurrent/pilib.scala
+++ b/src/library/scala/concurrent/pilib.scala
@@ -1,17 +1,15 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: pilib.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala.concurrent
 
-
 /** <p>
  *    Library for using Pi-calculus concurrent primitives in
  *    <a href="http://scala-lang.org/" target="_top">Scala</a>. As an
@@ -33,6 +31,8 @@ package scala.concurrent
  */ 
 object pilib {
 
+  import TaskRunners.threadRunner
+
   //////////////////////////////// SPAWN /////////////////////////////////
 
   /**
diff --git a/src/library/scala/deprecated.scala b/src/library/scala/deprecated.scala
index 03bbf3b..50a6601 100644
--- a/src/library/scala/deprecated.scala
+++ b/src/library/scala/deprecated.scala
@@ -1,18 +1,24 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: deprecated.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala
 
+import annotation.target._
+
 /**
  * An annotation that designates the definition to which it is applied as deprecated.
  * Access to the member then generates a deprecated warning.
+ *
+ * @since 2.3
  */
-class deprecated extends StaticAnnotation {}
+ at getter @setter @beanGetter @beanSetter
+class deprecated(message: String) extends StaticAnnotation {
+  def this() = this("")
+}
diff --git a/src/library/scala/inline.scala b/src/library/scala/inline.scala
index 7f07846..1e91be2 100644
--- a/src/library/scala/inline.scala
+++ b/src/library/scala/inline.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: inline.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala
diff --git a/src/library/scala/io/BufferedSource.scala b/src/library/scala/io/BufferedSource.scala
index a9c4e82..44077f4 100644
--- a/src/library/scala/io/BufferedSource.scala
+++ b/src/library/scala/io/BufferedSource.scala
@@ -1,92 +1,31 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: BufferedSource.scala 16881 2009-01-09 16:28:11Z cunei $
 
 
 package scala.io
 
-import java.io.InputStream
-import java.nio.{ByteBuffer, CharBuffer}
-import java.nio.channels.{ByteChannel, Channels, ReadableByteChannel}
-import java.nio.charset.{Charset, CharsetDecoder}
-
-object BufferedSource {
-
-  /** same as fromInputStream(inpStream, Charset.forName(enc), buffer_size, do_reset) */
-  def fromInputStream(inpStream: InputStream, enc: String, buffer_size: Int, do_reset: () => Source): BufferedSource =
-    fromInputStream(inpStream, Charset.forName(enc), buffer_size, do_reset)
-
-  /** same as fromInputStream(inpStream, charSet.newDecoder(), buffer_size, do_reset) */
-  def fromInputStream(inpStream: InputStream, charSet: Charset, buffer_size: Int, do_reset: () => Source): BufferedSource =
-    fromInputStream(inpStream, charSet.newDecoder(), buffer_size, do_reset)
-
-  /** constructs a BufferedSource instance from an input stream, using given decoder */
-  def fromInputStream(inpStream: InputStream, decoder: CharsetDecoder, buffer_size: Int, do_reset: () => Source): BufferedSource = {
-    val byteChannel = Channels.newChannel(inpStream)
-    return new {
-      val buf_size = buffer_size
-     } with BufferedSource(byteChannel, decoder) {
-      override def reset = do_reset()
-      def close { inpStream.close }
-    }
-  }
-}
+import java.io.{ InputStream, BufferedReader, InputStreamReader }
+import Source.DefaultBufSize
 
 /** This object provides convenience methods to create an iterable
  *  representation of a source file.
  *
- *  @author  Burak Emir
- *  @version 1.0, 19/08/2004
+ *  @author  Burak Emir, Paul Phillips
  */
-abstract class BufferedSource(byteChannel: ReadableByteChannel, decoder: CharsetDecoder) extends Source {
-
-  val buf_size: Int
-
-  def close: Unit
-
-  val byteBuffer = ByteBuffer.allocate(buf_size)
-  var charBuffer = CharBuffer.allocate(buf_size)
-  byteBuffer.position(byteBuffer.limit())
-  charBuffer.position(charBuffer.limit())
-  decoder.reset()
-  var endOfInput = false
-
-  def fillBuffer() = {
-    byteBuffer.compact()
-    charBuffer.compact()
-    var num_bytes = byteChannel.read(byteBuffer)
-    while (0 == num_bytes) {
-      Thread.sleep(1);  // wait 1 ms for new data
-      num_bytes = byteChannel.read(byteBuffer) 
-    }
-    endOfInput = (num_bytes == -1)
-    byteBuffer.flip()
-    decoder.decode(byteBuffer, charBuffer, endOfInput)
-    if (endOfInput) decoder.flush(charBuffer)
-    charBuffer.flip()
-  }
-  override val iter = new Iterator[Char] {
-    var buf_char = { 
-      fillBuffer() 
-      if (endOfInput) ' ' else charBuffer.get()
-    }
-    def hasNext = { charBuffer.remaining() > 0 || !endOfInput}
-    def next = { 
-      val c = buf_char
-      if (charBuffer.remaining() == 0) {
-        fillBuffer()
-      }
-      if (!endOfInput) {
-        buf_char = charBuffer.get()
-      }
-      c
-    }
+class BufferedSource(inputStream: InputStream, bufferSize: Int)(implicit val codec: Codec) extends Source {  
+  def this(inputStream: InputStream)(implicit codec: Codec) = this(inputStream, DefaultBufSize)(codec)
+  def reader() = new InputStreamReader(inputStream, codec.decoder)
+  def bufferedReader() = new BufferedReader(reader(), bufferSize)
+  
+  override val iter = {
+    val reader = bufferedReader()    
+    Iterator continually (codec wrap reader.read()) takeWhile (_ != -1) map (_.toChar)
   }
 }
 
diff --git a/src/library/scala/io/BytePickle.scala b/src/library/scala/io/BytePickle.scala
index d41f4b7..4ca76ce 100644
--- a/src/library/scala/io/BytePickle.scala
+++ b/src/library/scala/io/BytePickle.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: BytePickle.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala.io
@@ -65,12 +64,12 @@ object BytePickle {
   def refDef: PU[RefDef] = new PU[RefDef] {
     def appP(b: RefDef, s: Array[Byte]): Array[Byte] =
       b match {
-        case Ref() => Array.concat(s, (List[Byte](0)).toArray)
-        case Def() => Array.concat(s, (List[Byte](1)).toArray)
+        case Ref() => Array.concat(s, Array[Byte](0))
+        case Def() => Array.concat(s, Array[Byte](1))
       };
     def appU(s: Array[Byte]): (RefDef, Array[Byte]) =
-      if (s(0) == 0) (Ref(), s.subArray(1, s.length))
-      else (Def(), s.subArray(1, s.length));
+      if (s(0) == (0: Byte)) (Ref(), s.slice(1, s.length))
+      else (Def(), s.slice(1, s.length));
   }
 
   val REF = 0
@@ -91,7 +90,7 @@ object BytePickle {
         } while ((b & 0x80) != 0);
         x
       }
-      (readNat, s.subArray(num, s.length))
+      (readNat, s.slice(num, s.length))
     }
   }
 
@@ -229,7 +228,7 @@ object BytePickle {
     sequ(j, pa, (x: a) => lift(i(x)))
 
   def appendByte(a: Array[Byte], b: Int): Array[Byte] =
-    Array.concat(a, (List[Byte](b.asInstanceOf[Byte])).toArray)
+    Array.concat(a, Array(b.toByte))
 
   def nat2Bytes(x: Int): Array[Byte] = {
     val buf = new ArrayBuffer[Byte]
@@ -260,19 +259,22 @@ object BytePickle {
         } while ((b & 0x80) != 0);
         x
       }
-      (readNat, new UnPicklerState(s.stream.subArray(num, s.stream.length), s.dict))
+      (readNat, new UnPicklerState(s.stream.slice(num, s.stream.length), s.dict))
     }
   }
 
   def byte: SPU[Byte] = new SPU[Byte] {
     def appP(b: Byte, s: PicklerState): PicklerState =
-      new PicklerState(Array.concat(s.stream, (List[Byte](b)).toArray), s.dict);
+      new PicklerState(Array.concat(s.stream, Array(b)), s.dict)
     def appU(s: UnPicklerState): (Byte, UnPicklerState) =
-      (s.stream(0), new UnPicklerState(s.stream.subArray(1, s.stream.length), s.dict));
+      (s.stream(0), new UnPicklerState(s.stream.slice(1, s.stream.length), s.dict));
   }
 
-  def string: SPU[String] =
-    share(wrap((a: Array[Byte]) => UTF8Codec.decode(a, 0, a.length), (s:String) => UTF8Codec.encode(s), bytearray));
+  def string: SPU[String] = share(wrap(
+    (a: Array[Byte]) => Codec toUTF8 a mkString,
+    (s: String) => Codec fromUTF8 s,
+    bytearray
+  ))
 
   def bytearray: SPU[Array[Byte]] = {
     wrap((l:List[Byte]) => l.toArray, (_.toList), list(byte))
diff --git a/src/library/scala/io/Codec.scala b/src/library/scala/io/Codec.scala
new file mode 100644
index 0000000..7db7805
--- /dev/null
+++ b/src/library/scala/io/Codec.scala
@@ -0,0 +1,120 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+package scala.io
+
+import java.nio.charset.{ Charset, CharsetDecoder, CharsetEncoder, CharacterCodingException, CodingErrorAction => Action }
+
+// Some notes about encodings for use in refining this implementation.
+//
+// Emails: encoding recorded in header, e.g. Content-Type: charset= "iso-8859-1"
+// HTML: optional content-type meta tag.
+//   <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
+// XML: optional encoding parameter.
+//   <?xml version="1.0" encoding="ISO8859-1" ?>
+//
+// MacRoman vs. UTF-8: see http://jira.codehaus.org/browse/JRUBY-3576
+// -Dfile.encoding: see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4375816
+
+/** A class for character encoding/decoding preferences.
+ *
+ */
+class Codec(val charSet: Charset) {
+  type Configure[T] = (T => T, Boolean)
+  type Handler      = CharacterCodingException => Int
+  
+  // these variables allow configuring the Codec object, and then
+  // all decoders and encoders retrieved from it will use these settings.
+  private[this] var _onMalformedInput: Action         = null
+  private[this] var _onUnmappableCharacter: Action    = null
+  private[this] var _encodingReplacement: Array[Byte] = null
+  private[this] var _decodingReplacement: String      = null
+  private[this] var _onCodingException: Handler       = e => throw e
+  
+  // these methods can be chained to configure the variables above
+  def onMalformedInput(newAction: Action): this.type = { _onMalformedInput = newAction ; this }
+  def onUnmappableCharacter(newAction: Action): this.type = { _onUnmappableCharacter = newAction ; this }
+  def decodingReplaceWith(newReplacement: String): this.type = { _decodingReplacement = newReplacement ; this }
+  def encodingReplaceWith(newReplacement: Array[Byte]): this.type = { _encodingReplacement = newReplacement ; this }
+  def onCodingException(handler: Handler): this.type = { _onCodingException = handler ; this }
+  
+  def name = charSet.name
+  def encoder =
+    applyFunctions[CharsetEncoder](charSet.newEncoder(),
+      (_ onMalformedInput _onMalformedInput, _onMalformedInput != null),
+      (_ onUnmappableCharacter _onUnmappableCharacter, _onUnmappableCharacter != null),
+      (_ replaceWith _encodingReplacement, _encodingReplacement != null)
+    )
+    
+  def decoder = 
+    applyFunctions[CharsetDecoder](charSet.newDecoder(),
+      (_ onMalformedInput _onMalformedInput, _onMalformedInput != null),
+      (_ onUnmappableCharacter _onUnmappableCharacter, _onUnmappableCharacter != null),
+      (_ replaceWith _decodingReplacement, _decodingReplacement != null)
+    )
+  
+  def wrap(body: => Int): Int =
+    try body catch { case e: CharacterCodingException => _onCodingException(e) }
+
+  // call a series of side effecting methods on an object, finally returning the object
+  private def applyFunctions[T](x: T, fs: Configure[T]*) =
+    fs.foldLeft(x)((x, pair) => pair match {
+      case (f, cond) => if (cond) f(x) else x
+    })
+}
+
+trait LowPriorityCodecImplicits {
+  self: Codec.type =>
+
+  /** The Codec of Last Resort. */
+  implicit def fallbackSystemCodec: Codec = defaultCharsetCodec
+}
+
+object Codec extends LowPriorityCodecImplicits {
+  final val ISO8859 = Charset forName "ISO-8859-1"
+  final val UTF8    = Charset forName "UTF-8"
+  
+  /** Optimistically these two possible defaults will be the same thing.
+   *  In practice this is not necessarily true, and in fact Sun classifies
+   *  the fact that you can influence anything at all via -Dfile.encoding
+   *  as an accident, with any anomalies considered "not a bug".
+   */
+  def defaultCharsetCodec                   = apply(Charset.defaultCharset)
+  def fileEncodingCodec                     = apply(util.Properties.encodingString)
+  def default                               = defaultCharsetCodec
+  
+  def apply(encoding: String): Codec        = new Codec(Charset forName encoding)
+  def apply(charSet: Charset): Codec        = new Codec(charSet)
+  def apply(decoder: CharsetDecoder): Codec = {
+    val _decoder = decoder
+    new Codec(decoder.charset()) { override def decoder = _decoder }
+  }
+  
+  def toUTF8(bytes: Array[Byte]): Array[Char] = {
+    val bbuffer = java.nio.ByteBuffer wrap bytes
+    val cbuffer = UTF8 decode bbuffer
+    val chars = new Array[Char](cbuffer.remaining())
+    cbuffer get chars
+    
+    chars
+  }
+  
+  def fromUTF8(cs: CharSequence): Array[Byte] = {
+    val cbuffer = java.nio.CharBuffer wrap cs
+    val bbuffer = UTF8 encode cbuffer
+    val bytes = new Array[Byte](bbuffer.remaining())
+    bbuffer get bytes
+    
+    bytes
+  }
+  
+  implicit def string2codec(s: String) = apply(s)
+  implicit def charset2codec(c: Charset) = apply(c)
+  implicit def decoder2codec(cd: CharsetDecoder) = apply(cd)
+}
diff --git a/src/library/scala/io/Position.scala b/src/library/scala/io/Position.scala
index f6f1854..0c7a11c 100644
--- a/src/library/scala/io/Position.scala
+++ b/src/library/scala/io/Position.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Position.scala 16881 2009-01-09 16:28:11Z cunei $
 
 
 package scala.io
@@ -60,9 +59,6 @@ object Position {
   /** The first position in a source file */
   final val FIRSTPOS    = encode(1, 1)
 
-    //########################################################################
-    // Public Functions
-
   /** Encodes a position into a single integer. */
   final def encode(line: Int, column: Int): Int = {
     var line1, column1 = 0
@@ -73,17 +69,18 @@ object Position {
     if (column < 0)
       throw new IllegalArgumentException(line + "," + column + " not allowed")
 
-    {if (line >= LINE_MASK) {
+    if (line >= LINE_MASK) {
       line1 = LINE_MASK
       column1 = 0
-    } else {
+    }
+    else {
       line1 = line
       if (column > COLUMN_MASK)
         column1 = COLUMN_MASK
       else 
         column1 = column
-    }}
-    {(line1 << COLUMN_BITS) | column1;}
+    }
+    (line1 << COLUMN_BITS) | column1
   }
 
   /** Returns the line number of the encoded position. */
@@ -96,10 +93,10 @@ object Position {
 
   /** Returns a string representation of the encoded position. */
   def toString(pos: Int): String = {
-    val sb = new StringBuilder()
-    sb.append(line(pos))
-    sb.append(':')
-    sb.append(column(pos))
+    val sb = new StringBuilder
+    sb append line(pos)
+    sb append ':'
+    sb append column(pos)
     sb.toString()
   }
 }
diff --git a/src/library/scala/io/Source.scala b/src/library/scala/io/Source.scala
index e1aece5..96f8180 100644
--- a/src/library/scala/io/Source.scala
+++ b/src/library/scala/io/Source.scala
@@ -1,400 +1,354 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Source.scala 16881 2009-01-09 16:28:11Z cunei $
 
 
 package scala.io
 
-
-import java.io.{BufferedInputStream, File, FileInputStream, InputStream,
-                PrintStream}
-import java.nio.{ByteBuffer, CharBuffer}
-import java.nio.charset.Charset
-import java.net.{URI, URL}
+import java.io.{ FileInputStream, InputStream, PrintStream, File => JFile }
+import java.net.{ URI, URL }
 
 /** This object provides convenience methods to create an iterable
  *  representation of a source file.
  *
- *  @author  Burak Emir
+ *  @author  Burak Emir, Paul Phillips
  *  @version 1.0, 19/08/2004
  */
 object Source {
-
   val DefaultBufSize = 2048
-
-  val NoReset: () => Source = () => throw new UnsupportedOperationException()
-
-  /** Creates a <code>Source</code> instance from the given array of bytes,
-   *  with empty description.
-   *
-   *  @param bytes ...
-   *  @return      the created <code>Source</code> instance.
+  
+  /** Creates a <code>Source</code> from System.in.
    */
-  def fromBytes(bytes: Array[Byte]): Source =
-    fromString(new String(bytes))
-
-  /** Creates Source from array of bytes with given encoding, with
-   *  empty description.
+  def stdin = fromInputStream(System.in)
+  
+  /** Creates a Source from an Iterable.
    *
-   *  @param bytes ...
-   *  @param enc   ...
-   *  @return      ...
+   *  @param    iterable  the Iterable
+   *  @return   the Source
    */
-  def fromBytes(bytes: Array[Byte], enc: String): Source =
-    fromString(new String(bytes, enc))
+  def fromIterable(iterable: Iterable[Char]): Source = new Source {
+    val iter = iterable.iterator
+  } withReset(() => fromIterable(iterable))
 
-  /** Creates a <code>Source</code> instance from a single character.
-   *
-   *  @param c ...
-   *  @return  the create <code>Source</code> instance.
+  /** Creates a Source instance from a single character.
    */
-  def fromChar(c: Char): Source = {
-    val it = Iterator.single(c)
-    new Source {
-      def reset() = fromChar(c)
-      val iter = it
-    }
-  }
+  def fromChar(c: Char): Source = fromIterable(Array(c))
 
   /** creates Source from array of characters, with empty description.
-   *
-   *  @param chars ...
-   *  @return      ...
    */
-  def fromChars(chars: Array[Char]): Source = {
-    val it = chars.elements
-    new Source {
-      def reset() = fromChars(chars)
-      val iter = it
-    }
-  }
+  def fromChars(chars: Array[Char]): Source = fromIterable(chars)
 
-  /** creates Source from string, with empty description.
-   *
-   *  @param s ...
-   *  @return  ...
+  /** creates Source from a String, with no description.
    */
-  def fromString(s: String): Source = {
-    val it = s.elements
-    new Source {
-      def reset() = fromString(s)
-      val iter = it
-    }
-  }
-
+  def fromString(s: String): Source = fromIterable(s)
+  
   /** creates Source from file with given name, setting its description to
    *  filename.
    */
-  def fromFile(name: String): Source =
-    fromFile(name, util.Properties.encodingString)
+  def fromFile(name: String)(implicit codec: Codec): BufferedSource =
+    fromFile(new JFile(name))(codec)
 
   /** creates Source from file with given name, using given encoding, setting
    *  its description to filename.
    */
-  def fromFile(name: String, enc: String): Source =
-    fromFile(new File(name), enc)
+  def fromFile(name: String, enc: String): BufferedSource =
+    fromFile(name)(Codec(enc))
 
   /** creates <code>Source</code> from file with given file: URI
    */
-  def fromFile(uri: URI): Source =
-    fromFile(uri, util.Properties.encodingString)
+  def fromFile(uri: URI)(implicit codec: Codec): BufferedSource =
+    fromFile(new JFile(uri))(codec)
 
   /** creates Source from file with given file: URI
    */
-  def fromFile(uri: URI, enc: String): Source =
-    fromFile(new File(uri), enc)
+  def fromFile(uri: URI, enc: String): BufferedSource =
+    fromFile(uri)(Codec(enc))
 
   /** creates Source from file, using default character encoding, setting its
    *  description to filename.
    */
-  def fromFile(file: File): Source =
-    fromFile(file, util.Properties.encodingString, Source.DefaultBufSize)
+  def fromFile(file: JFile)(implicit codec: Codec): BufferedSource =
+    fromFile(file, Source.DefaultBufSize)(codec)
 
   /** same as fromFile(file, enc, Source.DefaultBufSize)
    */
-  def fromFile(file: File, enc: String): Source = 
-    fromFile(file, enc, Source.DefaultBufSize)
+  def fromFile(file: JFile, enc: String): BufferedSource = 
+    fromFile(file)(Codec(enc))
+
+  def fromFile(file: JFile, enc: String, bufferSize: Int): BufferedSource =
+    fromFile(file, bufferSize)(Codec(enc))
 
   /** Creates Source from <code>file</code>, using given character encoding,
    *  setting its description to filename. Input is buffered in a buffer of
    *  size <code>bufferSize</code>.
    */
-  def fromFile(file: File, enc: String, bufferSize: Int): Source = {
-    val inpStream = new FileInputStream(file)
-    val size = if (bufferSize > 0) bufferSize else Source.DefaultBufSize
-    setFileDescriptor(file, 
-      BufferedSource.fromInputStream(inpStream, enc, size, { () => fromFile(file, enc, size)}))
+  def fromFile(file: JFile, bufferSize: Int)(implicit codec: Codec): BufferedSource = {
+    val inputStream = new FileInputStream(file)
+
+    createBufferedSource(
+      inputStream,
+      bufferSize,
+      () => fromFile(file, bufferSize)(codec),
+      () => inputStream.close()
+    )(codec) withDescription ("file:" + file.getAbsolutePath)
   }
 
-  /** This method sets the descr property of the given source to a string of the form "file:"+path
-   *  @param file the file whose path we want to describe
-   *  @param s    the source whose property we set
-   *  @return     s
+  /** Create a <code>Source</code> from array of bytes, decoding
+   *  the bytes according to codec.
+   *
+   *  @param bytes ...
+   *  @param enc   ...
+   *  @return      the created <code>Source</code> instance.
    */
-  private def setFileDescriptor(file: File, s: Source): Source = {
-    s.descr = new StringBuilder("file:").append(file.getAbsolutePath()).toString();
-    s
-  }
+  def fromBytes(bytes: Array[Byte])(implicit codec: Codec): Source =
+    fromString(new String(bytes, codec.name))
 
-  /**
-   *  @param s    ...
-   *  @return     ...
-   *  @deprecated use fromURL(s, enc)
+  def fromBytes(bytes: Array[Byte], enc: String): Source =
+    fromBytes(bytes)(Codec(enc))
+
+  /** Create a <code>Source</code> from array of bytes, assuming
+   *  one byte per character (ISO-8859-1 encoding.)
    */
-  def fromURL(s: String): Source =
-    fromURL(new URL(s))
+  def fromRawBytes(bytes: Array[Byte]): Source =
+    fromString(new String(bytes, Codec.ISO8859.name))
 
-  /** same as fromURL(new URL(s), enc) 
+  /** creates <code>Source</code> from file with given file: URI
    */
-  def fromURL(s: String, enc:String): Source =
-    fromURL(new URL(s), enc)
+  def fromURI(uri: URI)(implicit codec: Codec): BufferedSource =
+    fromFile(new JFile(uri))(codec)
 
-  /**
-   *  @param url  ...
-   *  @return     ...
-   *  @deprecated use fromURL(url, enc)
+  /** same as fromURL(new URL(s))(Codec(enc))
    */
-  def fromURL(url: URL): Source = {
-    val it = new Iterator[Char] {
-      var data: Int = _
-      def hasNext = {data != -1}
-      def next = {val x = data.asInstanceOf[Char]; data = bufIn.read(); x}
-      val in = url.openStream()
-      val bufIn = new BufferedInputStream(in)
-      data = bufIn.read()
-    }
-    val s = new Source {
-      def reset() = fromURL(url)
-      val iter = it
-    }
-    s.descr = url.toString()
-    s
-  }
+  def fromURL(s: String, enc: String): BufferedSource =
+    fromURL(s)(Codec(enc))
 
-  /** same as fromInputStream(url.openStream(), enc) 
+  /** same as fromURL(new URL(s))
    */
-  def fromURL(url: URL, enc:String): Source = 
-    fromInputStream(url.openStream(), enc)
-  
-  /** reads data from <code>istream</code> into a byte array, and calls
-   *  <code>fromBytes</code> with given encoding <code>enc</code>. 
-   *  If <code>maxlen</code> is given, reads not more bytes than <code>maxlen</code>;
-   *  if <code>maxlen</code> was not given, or <code>was <= 0</code>, then
-   *  whole <code>istream</code> is read and closed afterwards.
-   * 
-   *  @param istream the input stream from which to read
-   *  @param enc the encoding to apply to the bytes
-   *  @param maxlen optionally, a positive int specifying maximum number of bytes to read
+  def fromURL(s: String)(implicit codec: Codec): BufferedSource =
+    fromURL(new URL(s))(codec)
+
+  /** same as fromInputStream(url.openStream())(Codec(enc))
    */
-  @deprecated def fromInputStream(istream: InputStream, enc: String, maxlen: Option[Int]): Source = {
-    val limit = maxlen match { case Some(i) => i; case None => 0 }
-    val bi = new BufferedInputStream(istream, Source.DefaultBufSize)
-    val bytes = new collection.mutable.ArrayBuffer[Byte]()
-    var b = 0
-    var i = 0
-    while( {b = bi.read; i += 1; b} != -1 && (limit <= 0 || i < limit)) {
-      bytes += b.toByte; 
-    }
-    if(limit <= 0) bi.close
-    fromBytes(bytes.toArray, enc)
-  }
+  def fromURL(url: URL, enc: String): BufferedSource =
+    fromURL(url)(Codec(enc))
 
-  /** same as BufferedSource.fromInputStream(is, enc, Source.DefaultBufSize) 
+  /** same as fromInputStream(url.openStream())(codec)
    */
-  def fromInputStream(is: InputStream, enc: String): Source = 
-    BufferedSource.fromInputStream(is, enc, Source.DefaultBufSize, { () => fromInputStream(is, enc) })
+  def fromURL(url: URL)(implicit codec: Codec): BufferedSource =
+    fromInputStream(url.openStream())(codec)  
+
+  /** Reads data from inputStream with a buffered reader, using the encoding
+   *  in implicit parameter codec.
+   * 
+   *  @param  inputStream  the input stream from which to read
+   *  @param  bufferSize   buffer size (defaults to Source.DefaultBufSize)
+   *  @param  reset        a () => Source which resets the stream (if unset, reset() will throw an Exception)
+   *  @param  close        a () => Unit method which closes the stream (if unset, close() will do nothing)
+   *  @param  codec        (implicit) a scala.io.Codec specifying behavior (defaults to Codec.default)
+   *  @return              the buffered source
+   */
+  def createBufferedSource(
+    inputStream: InputStream,
+    bufferSize: Int = DefaultBufSize,
+    reset: () => Source = null,
+    close: () => Unit = null
+  )(implicit codec: Codec): BufferedSource = {
+    // workaround for default arguments being unable to refer to other parameters
+    val resetFn = if (reset == null) () => createBufferedSource(inputStream, bufferSize, reset, close)(codec) else reset
+    
+    new BufferedSource(inputStream, bufferSize)(codec) withReset resetFn withClose close
+  }
   
-  /** same as BufferedSource.fromInputStream(is, "utf-8", Source.DefaultBufSize) */
-  def fromInputStream(is: InputStream): Source = 
-    BufferedSource.fromInputStream(is, "utf-8", Source.DefaultBufSize, { () => fromInputStream(is) })
+  def fromInputStream(is: InputStream, enc: String): BufferedSource =
+    fromInputStream(is)(Codec(enc))
   
+  def fromInputStream(is: InputStream)(implicit codec: Codec): BufferedSource =
+    createBufferedSource(is, reset = () => fromInputStream(is)(codec), close = () => is.close())(codec)
 }
 
 /** The class <code>Source</code> implements an iterable representation
- *  of source files. Calling method <code>reset</code> returns an identical,
- *  resetted source.
+ *  of source data.  Calling method <code>reset</code> returns an identical,
+ *  resetted source, where possible.
  *
  *  @author  Burak Emir
  *  @version 1.0
  */
 abstract class Source extends Iterator[Char] {
-
-  // ------ protected values
-
   /** the actual iterator */
   protected val iter: Iterator[Char]
 
-  protected var cline = 1
-  protected var ccol = 1
-
   // ------ public values
 
-  /** position of last character returned by next*/
-  var pos = 0
-
-  /** the last character returned by next.
-   *  the value before the first call to next is undefined.
-   */
-  var ch: Char = _
-
   /** description of this source, default empty */
   var descr: String = ""
 
   var nerrors = 0
   var nwarnings = 0
 
-  /** default col increment for tabs '\t', set to 4 initially
-   */
-  var tabinc = 4
-
-  //
-  // -- methods
-  //
-
-  /** convenience method, returns given line (not including newline)
+  /** Convenience method, returns given line (not including newline)
    *  from Source.
    *
    *  @param line the line index, first line is 1
-   *  @return     the character string of the specified line.
-   *  @throws scala.compat.Platform.IllegalArgumentException
+   *  @return     the specified line.
    *
    */
-  def getLine(line: Int): String = { // faster than getLines.drop(line).next
-    // todo: should @throws scala.compat.Platform.IndexOutOfBoundsException
-    if (line < 1) throw new IllegalArgumentException(line.toString);
-    val buf = new StringBuilder()
-    val it = reset
-    var i = 0
-
-    while (it.hasNext && i < (line-1))
-      if ('\n' == it.next)
-        i += 1;
-
-    if (!it.hasNext) // this should not happen
-      throw new IllegalArgumentException(
-        "line " + line + " does not exist"
-      );
-
-    var ch = it.next
-    while (it.hasNext && '\n' != ch) {
-      buf append ch
-      ch = it.next
-    }
-
-    if ('\n' != ch)
-      buf append ch
-
-    val res = buf.toString()
-    buf setLength 0  // hopefully help collector to deallocate StringBuilder
-    res
-  }
-
-  /** returns an iterator who returns lines (including newline character). 
-   *  a line ends in \n.
-   */
-  def getLines: Iterator[String] = new Iterator[String] {
-    val buf = new StringBuilder
-    def next = {
-      var ch = iter.next
-      while(ch != '\n' && iter.hasNext) {
-        buf append ch
-        ch = iter.next
+  @deprecated("Use a collections method such as getLines().toIndexedSeq for random access.")
+  def getLine(line: Int): String = lineNum(line)
+  private def lineNum(line: Int): String = getLines() drop (line - 1) next
+  
+  class LineIterator() extends Iterator[String] {
+    private[this] val sb = new StringBuilder
+
+    lazy val iter: BufferedIterator[Char] = Source.this.iter.buffered
+    def isNewline(ch: Char) = ch == '\r' || ch == '\n'
+    def getc() = iter.hasNext && {
+      val ch = iter.next
+      if (ch == '\n') false
+      else if (ch == '\r') {
+        if (iter.hasNext && iter.head == '\n')
+          iter.next
+
+        false
+      }
+      else {
+        sb append ch
+        true
       }
-      buf.append(ch)
-      val res = buf.toString()
-      buf setLength 0  // clean things up for next call of "next"
-      res
     }
     def hasNext = iter.hasNext
+    def next = {
+      sb.clear
+      while (getc()) { }
+      sb.toString
+    }
   }
+
+  /** Returns an iterator who returns lines (NOT including newline character(s)).
+   *  It will treat any of \r\n, \r, or \n as a line separator (longest match) - if
+   *  you need more refined behavior you can subclass Source#LineIterator directly.
+   */
+  def getLines(): Iterator[String] = new LineIterator()
+
   /** Returns <code>true</code> if this source has more characters.
    */
   def hasNext = iter.hasNext
 
-  /** returns next character and has the following side-effects: updates 
-   *  position (ccol and cline) and assigns the character to ch
+  /** Returns next character.
    */
-  def next = {
-    ch = iter.next
-    pos = Position.encode(cline,ccol)
-    ch match {
-      case '\n' =>
-        ccol = 1
-        cline += 1
-      case '\t' =>
-        ccol += tabinc
-      case _ =>
-        ccol += 1
+  def next: Char = positioner.next
+
+  class Positioner {
+    /** the last character returned by next. */
+    var ch: Char = _
+
+    /** position of last character returned by next */
+    var pos = 0
+
+    /** current line and column */
+    var cline = 1
+    var ccol = 1
+
+    /** default col increment for tabs '\t', set to 4 initially */
+    var tabinc = 4
+
+    def next: Char = {
+      ch = iter.next
+      pos = Position.encode(cline, ccol)
+      ch match {
+        case '\n' =>
+          ccol = 1
+          cline += 1
+        case '\t' =>
+          ccol += tabinc
+        case _ =>
+          ccol += 1
+      }
+      ch
     }
-    ch
   }
-
-  /** Reports an error message to console.
-   *
-   *  @param pos ...
-   *  @param msg the error message to report
-   */
-  def reportError(pos: Int, msg: String) {
-    reportError(pos, msg, java.lang.System.out)
+  object NoPositioner extends Positioner {
+    override def next: Char = iter.next
   }
+  def ch = positioner.ch
+  def pos = positioner.pos
 
   /** Reports an error message to the output stream <code>out</code>.
    *
-   *  @param pos ...
+   *  @param pos the source position (line/column)
    *  @param msg the error message to report
-   *  @param out ...
+   *  @param out PrintStream to use (optional: defaults to <code>Console.err</code>)
    */
-  def reportError(pos: Int, msg: String, out: PrintStream) {
-    nerrors = nerrors + 1
+  def reportError(
+    pos: Int, 
+    msg: String, 
+    out: PrintStream = Console.err)
+  {
+    nerrors += 1
     report(pos, msg, out)
   }
 
+  private def spaces(n: Int) = List.fill(n)(' ').mkString
   /**
-   *  @param pos ...
+   *  @param pos the source position (line/column)
    *  @param msg the error message to report
-   *  @param out ...
+   *  @param out PrintStream to use
    */
   def report(pos: Int, msg: String, out: PrintStream) {
-    val buf = new StringBuilder
-    val line = Position.line(pos)
-    val col = Position.column(pos)
-    buf.append(descr + ":" + line + ":" + col + ": " + msg)
-    buf.append(getLine(line))
-    var i = 1
-    while (i < col) {
-      buf.append(' ')
-      i += 1
-    }
-    buf.append('^')
-    out.println(buf.toString)
-  }
+    val line  = Position line pos
+    val col   = Position column pos
 
-  /** Reports a warning message to <code>java.lang.System.out</code>.
-   *
-   *  @param pos ...
-   *  @param msg the warning message to report
-   */
-  def reportWarning(pos: Int, msg: String) {
-    reportWarning(pos, msg, java.lang.System.out)
+    out println "%s:%d:%d: %s%s%s^".format(descr, line, col, msg, lineNum(line), spaces(col - 1))
   }
 
   /**
-   *  @param pos ...
+   *  @param pos the source position (line/column)
    *  @param msg the warning message to report
-   *  @param out ...
+   *  @param out PrintStream to use (optional: defaults to <code>Console.out</code>)
    */
-  def reportWarning(pos: Int, msg: String, out: PrintStream) {
-    nwarnings = nwarnings + 1
+  def reportWarning(
+    pos: Int, 
+    msg: String, 
+    out: PrintStream = Console.out)
+  {
+    nwarnings += 1
     report(pos, "warning! " + msg, out)
   }
+  
+  private[this] var resetFunction: () => Source = null
+  private[this] var closeFunction: () => Unit = null
+  private[this] var positioner: Positioner = new Positioner
+  
+  def withReset(f: () => Source): this.type = {
+    resetFunction = f
+    this
+  }
+  def withClose(f: () => Unit): this.type = {
+    closeFunction = f
+    this
+  }
+  def withDescription(text: String): this.type = {
+    descr = text
+    this
+  }
+  // we'd like to default to no positioning, but for now we break
+  // less by defaulting to status quo.
+  def withPositioning(on: Boolean): this.type = {
+    positioner = if (on) new Positioner else NoPositioner
+    this
+  }
 
-  /** the actual reset method */
-  def reset(): Source
+  /** The close() method closes the underlying resource. */
+  def close() {
+    if (closeFunction != null) closeFunction()
+  }
 
+  /** The reset() method creates a fresh copy of this Source. */
+  def reset(): Source = 
+    if (resetFunction != null) resetFunction()
+    else throw new UnsupportedOperationException("Source's reset() method was not set.")
 }
diff --git a/src/library/scala/io/UTF8Codec.scala b/src/library/scala/io/UTF8Codec.scala
index 95b949c..c26ba4c 100644
--- a/src/library/scala/io/UTF8Codec.scala
+++ b/src/library/scala/io/UTF8Codec.scala
@@ -1,13 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: UTF8Codec.scala 16881 2009-01-09 16:28:11Z cunei $
-
 
 package scala.io
 
@@ -15,105 +13,52 @@ package scala.io
  *  @author  Martin Odersky
  *  @version 1.0, 04/10/2004
  */
-object UTF8Codec {
-
+object UTF8Codec
+{
   final val UNI_REPLACEMENT_CHAR: Int = 0x0000FFFD
+  final val UNI_REPLACEMENT_BYTES = Array[Byte](-17, -65, -67)
+  
+  // Note, from http://unicode.org/faq/utf_bom.html#utf8-5
+  //
+  // A different issue arises if an unpaired surrogate is encountered when converting
+  // ill-formed UTF-16 data. By represented such an unpaired surrogate on its own as a
+  // 3-byte sequence, the resulting UTF-8 data stream would become ill-formed.
+  // While it faithfully reflects the nature of the input, Unicode conformance
+  // requires that encoding form conversion always results in valid data stream.
+  // Therefore a converter must treat this as an error.
+  //
+  // Some useful locations:
+  //    http://www.cl.cam.ac.uk/~mgk25/ucs/examples/UTF-8-test.txt
 
-  /** convert a codepoint to utf-8 bytes
-   * @author buraq
-   * @param ch codepoint
-   */
-  def encode(ch1: Int): Array[Byte] = {
-    var ch = ch1
-    val byteMask = 0xBF
-    val byteMark = 0x80 
-    var bytesToWrite = 0
-    val firstByteMark = List[Byte](0x00.asInstanceOf[Byte], 0x00.asInstanceOf[Byte], 0xC0.asInstanceOf[Byte], 0xE0.asInstanceOf[Byte], 0xF0.asInstanceOf[Byte], 0xF8.asInstanceOf[Byte], 0xFC.asInstanceOf[Byte])
-
-    if      (ch < 0x80)        { bytesToWrite = 1 }
-    else if (ch < 0x800)       { bytesToWrite = 2 }
-    else if (ch < 0x10000)     { bytesToWrite = 3 }
-    else if (ch <= 0x0010FFFF) { bytesToWrite = 4 }
-    else return encode(UNI_REPLACEMENT_CHAR)
-    
-    val res = new Array[Byte](bytesToWrite)
-
-    var bw = bytesToWrite
-    if(bw>=4) { 
-      res(3) = ((ch | byteMark) & byteMask).asInstanceOf[Byte]; ch = ch >> 6; bw -= 1
-    }
-    if(bw>=3) { 
-      res(2) = ((ch | byteMark) & byteMask).asInstanceOf[Byte]; ch = ch >> 6; bw -= 1
-    }
-    if(bw>=2) { 
-      res(1) = ((ch | byteMark) & byteMask).asInstanceOf[Byte]; ch = ch >> 6; bw -= 1
-    }
-    if(bw>=1) { 
-      res(0) = (ch | firstByteMark(bytesToWrite)).asInstanceOf[Byte]
+  @deprecated("""Use new String(Array(ch), 0, 1).getBytes("UTF-8") instead""")
+  def encode(ch: Int): Array[Byte] =
+    if ((Character getType ch) == Character.SURROGATE.toInt) UNI_REPLACEMENT_BYTES
+    else try new String(Array(ch), 0, 1) getBytes "UTF-8" catch {
+      case _: IllegalArgumentException  => UNI_REPLACEMENT_BYTES
     }
-    return res
-  }
 
+  @deprecated("Use Codec.fromUTF8 instead")
   def encode(src: Array[Char], from: Int, dst: Array[Byte], to: Int, len: Int): Int = {
-    var i = from
-    var j = to
-    val end = from + len
-    while (i < end) {
-      val ch = src(i)
-      i += 1
-      if (ch < 128) {
-        dst(j) = ch.toByte
-        j += 1
-      }
-      else if (ch <= 0x3FF) {
-        dst(j)   = (0xC0 | (ch >> 6)).toByte
-        dst(j+1) = (0x80 | (ch & 0x3F)).toByte
-        j += 2
-      } else {
-        dst(j)   = (0xE0 | (ch >> 12)).toByte
-        dst(j+1) = (0x80 | ((ch >> 6) & 0x3F)).toByte
-        dst(j+2) = (0x80 | (ch & 0x3F)).toByte
-        j += 3
-      }
-    }
-    j
+    val bytes = Codec fromUTF8 src.slice(from, from + len)
+    Array.copy(bytes, 0, dst, to, bytes.length)
+    bytes.length
   }
 
+  @deprecated("Use Codec.fromUTF8 instead")
   def encode(s: String, dst: Array[Byte], to: Int): Int =
-    encode(s.toCharArray(), 0, dst, to, s.length())
-
-  def encode(s: String): Array[Byte] = {
-    val dst = new Array[Byte](s.length() * 3)
-    val len = encode(s, dst, 0)
-    dst.subArray(0, len)
-  }
+    encode(s.toArray, 0, dst, to, s.length)
 
-  def decode(src: Array[Byte], from: Int,
-             dst: Array[Char], to: Int, len: Int): Int =
-  {
-    var i = from
-    var j = to
-    val end = from + len
-    while (i < end) {
-      var b = src(i) & 0xFF
-      i += 1
-      if (b >= 0xE0) {
-        b = ((b & 0x0F) << 12) | (src(i) & 0x3F) << 6
-        b = b | (src(i+1) & 0x3F)
-        i += 2
-      } else if (b >= 0xC0) {
-        b = ((b & 0x1F) << 6) | (src(i) & 0x3F)
-        i += 1
-      }
-      dst(j) = b.toChar
-      j += 1
-    }
-    j
-  }
+  @deprecated("Use Codec.fromUTF8 instead")
+  def encode(s: String): Array[Byte] = Codec fromUTF8 s
 
-  def decode(src: Array[Byte], from: Int, len: Int): String = {
-    val cs = new Array[Char](len)
-    new String(cs, 0, decode(src, 0, cs, 0, len))
+  @deprecated("Use Codec.toUTF8 instead")
+  def decode(src: Array[Byte], from: Int, dst: Array[Char], to: Int, len: Int): Int = {
+    val chars = Codec toUTF8 src.slice(from, from + len)
+    Array.copy(chars, 0, dst, to, chars.length)
+    chars.length
   }
 
+  @deprecated("Use Codec.toUTF8 instead")
+  def decode(src: Array[Byte], from: Int, len: Int): String =
+    Codec toUTF8 src.slice(from, from + len) mkString
 }
diff --git a/src/library/scala/math/BigDecimal.scala b/src/library/scala/math/BigDecimal.scala
new file mode 100644
index 0000000..4b5379b
--- /dev/null
+++ b/src/library/scala/math/BigDecimal.scala
@@ -0,0 +1,405 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+package scala.math
+
+import java.{ lang => jl }
+import java.math.{ MathContext, BigDecimal => BigDec }
+import scala.collection.immutable.NumericRange
+
+import annotation.migration
+
+/** 
+ *  @author  Stephane Micheloud
+ *  @version 1.0
+ *  @since 2.7
+ */
+object BigDecimal {
+  private val minCached = -512
+  private val maxCached = 512
+  
+  val defaultMathContext = MathContext.UNLIMITED
+
+  val MinLong = new BigDecimal(BigDec valueOf Long.MinValue, defaultMathContext)
+  val MaxLong = new BigDecimal(BigDec valueOf Long.MaxValue, defaultMathContext)
+  
+  /** Cache ony for defaultMathContext using BigDecimals in a small range. */
+  private lazy val cache = new Array[BigDecimal](maxCached - minCached + 1)
+
+  @serializable
+  object RoundingMode extends Enumeration(java.math.RoundingMode.values map (_.toString) : _*) {
+    type RoundingMode = Value
+    val UP, DOWN, CEILING, FLOOR, HALF_UP, HALF_DOWN, HALF_EVEN, UNNECESSARY = Value
+  }
+  
+  /** Constructs a <code>BigDecimal</code> using the java BigDecimal static
+   *  valueOf constructor.
+   *
+   *  @param  d the specified double value
+   *  @return the constructed <code>BigDecimal</code>
+   */
+  def valueOf(d: Double): BigDecimal = apply(BigDec valueOf d)
+  def valueOf(d: Double, mc: MathContext): BigDecimal = apply(BigDec valueOf d, mc)
+
+  /** Constructs a <code>BigDecimal</code> whose value is equal to that of the
+   *  specified <code>Integer</code> value.
+   *
+   *  @param i the specified integer value
+   *  @return  the constructed <code>BigDecimal</code>
+   */
+  def apply(i: Int): BigDecimal = apply(i, defaultMathContext)
+  def apply(i: Int, mc: MathContext): BigDecimal =
+    if (mc == defaultMathContext && minCached <= i && i <= maxCached) {
+      val offset = i - minCached
+      var n = cache(offset)
+      if (n eq null) { n = new BigDecimal(BigDec.valueOf(i), mc); cache(offset) = n }
+      n
+    }
+    else new BigDecimal(BigDec.valueOf(i), mc)
+
+  /** Constructs a <code>BigDecimal</code> whose value is equal to that of the
+   *  specified long value.
+   *
+   *  @param l the specified long value
+   *  @return  the constructed <code>BigDecimal</code>
+   */
+  def apply(l: Long): BigDecimal =
+    if (minCached <= l && l <= maxCached) apply(l.toInt)
+    else new BigDecimal(BigDec.valueOf(l), defaultMathContext)  
+    
+  def apply(l: Long, mc: MathContext): BigDecimal =
+    new BigDecimal(new BigDec(l, mc), mc)
+
+  /** Constructs a <code>BigDecimal</code> whose unscaled value is equal to that
+   *  of the specified long value.
+   *
+   *  @param  unscaledVal the value
+   *  @param  scale       the scale
+   *  @return the constructed <code>BigDecimal</code>
+   */
+  def apply(unscaledVal: Long, scale: Int): BigDecimal =
+    apply(BigInt(unscaledVal), scale)
+
+  def apply(unscaledVal: Long, scale: Int, mc: MathContext): BigDecimal =
+    apply(BigInt(unscaledVal), scale, mc)
+
+  /** Constructs a <code>BigDecimal</code> whose value is equal to that of the
+   *  specified double value.
+   *
+   *  @param d the specified <code>Double</code> value
+   *  @return  the constructed <code>BigDecimal</code>
+   */
+  def apply(d: Double): BigDecimal = apply(d, defaultMathContext)  
+  // note we don't use the static valueOf because it doesn't let us supply
+  // a MathContext, but we should be duplicating its logic, modulo caching.
+  def apply(d: Double, mc: MathContext): BigDecimal =
+    new BigDecimal(new BigDec(jl.Double.toString(d), mc), mc)
+
+  /** Translates a character array representation of a <code>BigDecimal</code>
+   *  into a <code>BigDecimal</code>.
+   */
+  def apply(x: Array[Char]): BigDecimal = apply(x, defaultMathContext)
+  def apply(x: Array[Char], mc: MathContext): BigDecimal =
+    new BigDecimal(new BigDec(x.mkString, mc), mc)
+    
+  /** Translates the decimal String representation of a <code>BigDecimal</code>
+   *  into a <code>BigDecimal</code>.
+   */
+  def apply(x: String): BigDecimal = apply(x, defaultMathContext)
+  def apply(x: String, mc: MathContext): BigDecimal = 
+    new BigDecimal(new BigDec(x, mc), mc)
+
+  /** Constructs a <code>BigDecimal</code> whose value is equal to that of the
+   *  specified <code>BigInt</code> value.
+   *
+   *  @param x the specified <code>BigInt</code> value
+   *  @return  the constructed <code>BigDecimal</code>
+   */
+  def apply(x: BigInt): BigDecimal = apply(x, defaultMathContext)
+  def apply(x: BigInt, mc: MathContext): BigDecimal =
+    new BigDecimal(new BigDec(x.bigInteger, mc), mc)
+  
+  /** Constructs a <code>BigDecimal</code> whose unscaled value is equal to that
+   *  of the specified <code>BigInt</code> value.
+   *
+   *  @param unscaledVal the specified <code>BigInt</code> value
+   *  @param scale       the scale 
+   *  @return  the constructed <code>BigDecimal</code>
+   */  
+  def apply(unscaledVal: BigInt, scale: Int): BigDecimal = apply(unscaledVal, scale, defaultMathContext)
+  def apply(unscaledVal: BigInt, scale: Int, mc: MathContext): BigDecimal =
+    new BigDecimal(new BigDec(unscaledVal.bigInteger, scale, mc), mc)
+  
+  def apply(bd: BigDec): BigDecimal = apply(bd, defaultMathContext)
+  def apply(bd: BigDec, mc: MathContext): BigDecimal = new BigDecimal(bd, mc)
+
+  /** Implicit conversion from <code>Int</code> to <code>BigDecimal</code>. */
+  implicit def int2bigDecimal(i: Int): BigDecimal = apply(i)
+
+  /** Implicit conversion from <code>Long</code> to <code>BigDecimal</code>. */
+  implicit def long2bigDecimal(l: Long): BigDecimal = apply(l)
+
+  /** Implicit conversion from <code>Double</code> to <code>BigDecimal</code>. */
+  implicit def double2bigDecimal(d: Double): BigDecimal = valueOf(d, defaultMathContext)
+}
+
+/** 
+ *  @author  Stephane Micheloud
+ *  @version 1.0
+ */
+ at serializable
+class BigDecimal(
+  val bigDecimal: BigDec,
+  val mc: MathContext)
+extends ScalaNumber with ScalaNumericConversions
+{
+  def this(bigDecimal: BigDec) = this(bigDecimal, BigDecimal.defaultMathContext)
+  import BigDecimal.RoundingMode._
+  
+  /** Cuts way down on the wrapper noise. */
+  private implicit def bigdec2BigDecimal(x: BigDec): BigDecimal = new BigDecimal(x, mc)
+
+  /** Returns the hash code for this BigDecimal.
+   *  Note that this does not use the underlying java object's
+   *  hashCode because we compare BigDecimals with compareTo
+   *  which deems 2 == 2.00, whereas in java these are unequal
+   *  with unequal hashCodes.
+   */
+  override def hashCode(): Int =
+    if (isWhole) unifiedPrimitiveHashcode
+    else doubleValue.##
+
+  /** Compares this BigDecimal with the specified value for equality.
+   */
+  override def equals (that: Any): Boolean = that match {
+    case that: BigDecimal     => this equals that 
+    case that: BigInt         => this.toBigIntExact exists (that equals _)
+    case _: Float | _: Double => unifiedPrimitiveEquals(that)
+    case x                    => isWhole && this <= BigDecimal.MaxLong && this >= BigDecimal.MinLong && unifiedPrimitiveEquals(x)
+  }
+  
+  protected[math] def isWhole = (this remainder 1) == BigDecimal(0)
+  def underlying = bigDecimal
+
+  /** Compares this BigDecimal with the specified BigDecimal for equality.
+   */
+  def equals (that: BigDecimal): Boolean = compare(that) == 0
+
+  /** Compares this BigDecimal with the specified BigDecimal
+   */
+  def compare (that: BigDecimal): Int = this.bigDecimal compareTo that.bigDecimal
+
+  /** Less-than-or-equals comparison of BigDecimals
+   */
+  def <= (that: BigDecimal): Boolean = compare(that) <= 0
+
+  /** Greater-than-or-equals comparison of BigDecimals
+   */
+  def >= (that: BigDecimal): Boolean = compare(that) >= 0
+
+  /** Less-than of BigDecimals
+   */
+  def <  (that: BigDecimal): Boolean = compare(that) <  0
+
+  /** Greater-than comparison of BigDecimals
+   */
+  def >  (that: BigDecimal): Boolean = compare(that) > 0
+
+  /** Addition of BigDecimals
+   */
+  def +  (that: BigDecimal): BigDecimal = this.bigDecimal.add(that.bigDecimal, mc)
+
+  /** Subtraction of BigDecimals
+   */
+  def -  (that: BigDecimal): BigDecimal = this.bigDecimal.subtract(that.bigDecimal, mc)
+
+  /** Multiplication of BigDecimals
+   */
+  def *  (that: BigDecimal): BigDecimal = this.bigDecimal.multiply(that.bigDecimal, mc)
+
+  /** Division of BigDecimals
+   */
+  def /  (that: BigDecimal): BigDecimal = this.bigDecimal.divide(that.bigDecimal, mc)
+  
+  /** Division and Remainder - returns tuple containing the result of 
+   *  divideToIntegralValue and the remainder.
+   */
+  def /% (that: BigDecimal): (BigDecimal, BigDecimal) =
+    this.bigDecimal.divideAndRemainder(that.bigDecimal, mc) match {
+      case Array(q, r)  => (q, r)
+    }
+  
+  /** Divide to Integral value.
+   */
+  def quot (that: BigDecimal): BigDecimal =
+    this.bigDecimal.divideToIntegralValue(that.bigDecimal, mc)
+
+  /** Returns the minimum of this and that
+   */
+  def min (that: BigDecimal): BigDecimal = this.bigDecimal min that.bigDecimal
+
+  /** Returns the maximum of this and that
+   */
+  def max (that: BigDecimal): BigDecimal = this.bigDecimal max that.bigDecimal
+
+  /** Remainder after dividing this by that.
+   */
+  def remainder (that: BigDecimal): BigDecimal = this.bigDecimal.remainder(that.bigDecimal, mc)
+  
+  /** Remainder after dividing this by that.
+   */
+  def % (that: BigDecimal): BigDecimal = this.remainder(that)
+  
+  /** Returns a BigDecimal whose value is this ** n.
+   */
+  def pow (n: Int): BigDecimal = this.bigDecimal.pow(n, mc)
+
+  /** Returns a BigDecimal whose value is the negation of this BigDecimal
+   */
+  def unary_- : BigDecimal = this.bigDecimal.negate(mc)
+  
+  /** Returns the absolute value of this BigDecimal
+   */
+  def abs: BigDecimal = this.bigDecimal abs mc
+
+  /** Returns the sign of this BigDecimal, i.e. 
+   *   -1 if it is less than 0, 
+   *   +1 if it is greater than 0
+   *   0  if it is equal to 0
+   */
+  def signum: Int = this.bigDecimal.signum()
+
+  /** Returns the precision of this <code>BigDecimal</code>.
+   */
+  def precision: Int = this.bigDecimal.precision()
+  
+  /** Returns a BigDecimal rounded according to the MathContext settings.
+   */
+  def round(mc: MathContext): BigDecimal = this.bigDecimal round mc
+
+  /** Returns the scale of this <code>BigDecimal</code>.
+   */
+  def scale: Int = this.bigDecimal.scale()
+  
+  /** Returns the size of an ulp, a unit in the last place, of this BigDecimal.
+   */
+  def ulp: BigDecimal = this.bigDecimal.ulp
+  
+  /** Returns a new BigDecimal based on the supplied MathContext.
+   */
+  def apply(mc: MathContext): BigDecimal = BigDecimal(this.bigDecimal.toString, mc)
+
+  /** Returns a <code>BigDecimal</code> whose scale is the specified value, and whose value is
+   *  numerically equal to this BigDecimal's.
+   */
+  def setScale(scale: Int): BigDecimal = this.bigDecimal setScale scale
+
+  def setScale(scale: Int, mode: RoundingMode): BigDecimal =
+    this.bigDecimal.setScale(scale, mode.id)
+
+  /** Converts this BigDecimal to a <tt>byte</tt>. 
+   *  If the BigDecimal is too big to fit in a byte, only the low-order 8 bits are returned. 
+   *  Note that this conversion can lose information about the overall magnitude of the 
+   *  BigDecimal value as well as return a result with the opposite sign.
+   */
+  override def byteValue   = intValue.toByte
+
+  /** Converts this BigDecimal to a <tt>short</tt>. 
+   *  If the BigDecimal is too big to fit in a byte, only the low-order 16 bits are returned. 
+   *  Note that this conversion can lose information about the overall magnitude of the 
+   *  BigDecimal value as well as return a result with the opposite sign.
+   */
+  override def shortValue  = intValue.toShort
+
+  /** Converts this BigDecimal to a <tt>char</tt>. 
+   *  If the BigDecimal is too big to fit in a char, only the low-order 16 bits are returned. 
+   *  Note that this conversion can lose information about the overall magnitude of the 
+   *  BigDecimal value and that it always returns a positive result.
+   */
+  def charValue   = intValue.toChar
+
+  /** Converts this BigDecimal to an <tt>int</tt>. 
+   *  If the BigDecimal is too big to fit in a char, only the low-order 32 bits
+   *  are returned. Note that this conversion can lose information about the
+   *  overall magnitude of the BigDecimal value as well as return a result with
+   *  the opposite sign.
+   */
+  def intValue    = this.bigDecimal.intValue
+
+  /** Converts this BigDecimal to a <tt>Long</tt>.
+   *  If the BigDecimal is too big to fit in a char, only the low-order 64 bits
+   *  are returned. Note that this conversion can lose information about the
+   *  overall magnitude of the BigDecimal value as well as return a result with
+   *  the opposite sign.
+   */
+  def longValue   = this.bigDecimal.longValue
+
+  /** Converts this BigDecimal to a <tt>float</tt>.
+   *  if this BigDecimal has too great a magnitude to represent as a float,
+   *  it will be converted to <code>Float.NEGATIVE_INFINITY</code> or
+   *  <code>Float.POSITIVE_INFINITY</code> as appropriate.
+   */
+  def floatValue  = this.bigDecimal.floatValue
+
+  /** Converts this BigDecimal to a <tt>Double</tt>. 
+   *  if this BigDecimal has too great a magnitude to represent as a double, 
+   *  it will be converted to <code>Double.NEGATIVE_INFINITY</code> or
+   *  <code>Double.POSITIVE_INFINITY</code> as appropriate. 
+   */
+  def doubleValue = this.bigDecimal.doubleValue
+  
+  /** This BigDecimal as an exact value.
+   */
+  def toByteExact = bigDecimal.byteValueExact
+  def toShortExact = bigDecimal.shortValueExact
+  def toIntExact = bigDecimal.intValueExact
+  def toLongExact = bigDecimal.longValueExact
+
+  /** Creates a partially constructed NumericRange[BigDecimal] in range
+   *  <code>[start;end)</code>, where start is the target BigDecimal.  The step
+   *  must be supplied via the "by" method of the returned object in order
+   *  to receive the fully constructed range.  For example:
+   * <pre>
+   * val partial = BigDecimal(1.0) to 2.0       // not usable yet
+   * val range = partial by 0.01                // now a NumericRange
+   * val range2 = BigDecimal(0) to 1.0 by 0.01  // all at once of course is fine too
+   * </pre>
+   *
+   *  @param end    the end value of the range (exclusive)
+   *  @return       the partially constructed NumericRange
+   */
+  def until(end: BigDecimal): Range.Partial[BigDecimal, NumericRange.Exclusive[BigDecimal]] =
+    new Range.Partial(until(end, _))
+
+  /** Same as the one-argument <code>until</code>, but creates the range immediately. */
+  def until(end: BigDecimal, step: BigDecimal) = Range.BigDecimal(this, end, step)
+  
+  /** Like <code>until</code>, but inclusive of the end value. */
+  def to(end: BigDecimal): Range.Partial[BigDecimal, NumericRange.Inclusive[BigDecimal]] =
+    new Range.Partial(to(end, _))
+  
+  /** Like <code>until</code>, but inclusive of the end value. */
+  def to(end: BigDecimal, step: BigDecimal) = Range.BigDecimal.inclusive(this, end, step)
+
+  /** Converts this <code>BigDecimal</code> to a scala.BigInt.
+   */
+  def toBigInt(): BigInt = new BigInt(this.bigDecimal.toBigInteger())
+  
+  /** Converts this <code>BigDecimal</code> to a scala.BigInt if it
+   *  can be done losslessly, returning Some(BigInt) or None.
+   */
+  def toBigIntExact(): Option[BigInt] =
+    try Some(new BigInt(this.bigDecimal.toBigIntegerExact()))
+    catch { case _: ArithmeticException => None }
+
+  /** Returns the decimal String representation of this BigDecimal.
+   */
+  override def toString(): String = this.bigDecimal.toString()
+
+}
diff --git a/src/library/scala/math/BigInt.scala b/src/library/scala/math/BigInt.scala
new file mode 100644
index 0000000..af9ef1b
--- /dev/null
+++ b/src/library/scala/math/BigInt.scala
@@ -0,0 +1,376 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2006-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.math
+
+import java.math.BigInteger
+
+/** 
+ *  @author  Martin Odersky
+ *  @version 1.0, 15/07/2003
+ *  @since 2.1
+ */
+object BigInt {
+
+  private val minCached = -1024
+  private val maxCached = 1024
+  private val cache = new Array[BigInt](maxCached - minCached + 1)
+  
+  val MinLong = BigInt(Long.MinValue)
+  val MaxLong = BigInt(Long.MaxValue)
+
+  /** Constructs a <code>BigInt</code> whose value is equal to that of the
+   *  specified integer value.
+   *
+   *  @param i the specified integer value
+   *  @return  the constructed <code>BigInt</code>
+   */
+  def apply(i: Int): BigInt =
+    if (minCached <= i && i <= maxCached) {
+      val offset = i - minCached
+      var n = cache(offset)
+      if (n eq null) { n = new BigInt(BigInteger.valueOf(i)); cache(offset) = n }
+      n
+    } else new BigInt(BigInteger.valueOf(i))
+
+  /** Constructs a <code>BigInt</code> whose value is equal to that of the
+   *  specified long value.
+   *
+   *  @param l the specified long value
+   *  @return  the constructed <code>BigInt</code>
+   */
+  def apply(l: Long): BigInt =
+    if (minCached <= l && l <= maxCached) apply(l.toInt)
+    else new BigInt(BigInteger.valueOf(l))
+
+  /** Translates a byte array containing the two's-complement binary 
+   *  representation of a BigInt into a BigInt.
+   */
+  def apply(x: Array[Byte]): BigInt = 
+    new BigInt(new BigInteger(x))
+
+  /** Translates the sign-magnitude representation of a BigInt into a BigInt.
+   */
+  def apply(signum: Int, magnitude: Array[Byte]): BigInt =
+    new BigInt(new BigInteger(signum, magnitude))
+  
+  /** Constructs a randomly generated positive BigInt that is probably prime, 
+   *  with the specified bitLength.
+   */
+  def apply(bitlength: Int, certainty: Int, rnd: scala.util.Random): BigInt =
+    new BigInt(new BigInteger(bitlength, certainty, rnd.self))
+
+  /** Constructs a randomly generated BigInt, uniformly distributed over the
+   *  range 0 to (2 ^ numBits - 1), inclusive.
+   *
+   *  @param numbits ...
+   *  @param rnd     ...
+   *  @return        ...
+   */
+  def apply(numbits: Int, rnd: scala.util.Random): BigInt =
+    new BigInt(new BigInteger(numbits, rnd.self))
+
+  /** Translates the decimal String representation of a BigInt into a BigInt.
+   */
+  def apply(x: String): BigInt = 
+    new BigInt(new BigInteger(x))
+
+  /** Translates the string representation of a BigInt in the
+   *  specified <code>radix</code> into a BigInt.
+   *
+   *  @param x     ...
+   *  @param radix ...
+   *  @return      ...
+   */
+  def apply(x: String, radix: Int): BigInt =
+    new BigInt(new BigInteger(x, radix))
+
+  /** Returns a positive BigInt that is probably prime, with the specified bitLength.
+   */
+  def probablePrime(bitLength: Int, rnd: scala.util.Random): BigInt =
+    new BigInt(BigInteger.probablePrime(bitLength, rnd.self))
+
+  /** Implicit conversion from <code>int</code> to <code>BigInt</code>.
+   */
+  implicit def int2bigInt(i: Int): BigInt = apply(i)
+
+  /** Implicit conversion from long to BigInt
+   */
+  implicit def long2bigInt(l: Long): BigInt = apply(l)
+}
+
+/** 
+ *  @author  Martin Odersky
+ *  @version 1.0, 15/07/2003
+ */
+ at serializable
+class BigInt(val bigInteger: BigInteger) extends ScalaNumber with ScalaNumericConversions
+{
+  /** Returns the hash code for this BigInt. */
+  override def hashCode(): Int =
+    if (this >= BigInt.MinLong && this <= BigInt.MaxLong) unifiedPrimitiveHashcode
+    else bigInteger.##
+
+  /** Compares this BigInt with the specified value for equality.
+   */
+  override def equals(that: Any): Boolean = that match {
+    case that: BigInt     => this equals that
+    case that: BigDecimal => that.toBigIntExact exists (this equals _)
+    case x                => (this <= BigInt.MaxLong && this >= BigInt.MinLong) && unifiedPrimitiveEquals(x)
+  }
+  
+  protected[math] def isWhole = true
+  def underlying = bigInteger
+
+  /** Compares this BigInt with the specified BigInt for equality.
+   */
+  def equals (that: BigInt): Boolean = compare(that) == 0
+
+  /** Compares this BigInt with the specified BigInt
+   */
+  def compare (that: BigInt): Int = this.bigInteger.compareTo(that.bigInteger)
+
+  /** Less-than-or-equals comparison of BigInts
+   */
+  def <= (that: BigInt): Boolean = compare(that) <= 0
+
+  /** Greater-than-or-equals comparison of BigInts
+   */
+  def >= (that: BigInt): Boolean = compare(that) >= 0
+
+  /** Less-than of BigInts
+   */
+  def <  (that: BigInt): Boolean = compare(that) <  0
+
+  /** Greater-than comparison of BigInts
+   */
+  def >  (that: BigInt): Boolean = compare(that) > 0
+
+  /** Addition of BigInts
+   */
+  def +  (that: BigInt): BigInt = new BigInt(this.bigInteger.add(that.bigInteger))
+
+  /** Subtraction of BigInts
+   */
+  def -  (that: BigInt): BigInt = new BigInt(this.bigInteger.subtract(that.bigInteger))
+
+  /** Multiplication of BigInts
+   */
+  def *  (that: BigInt): BigInt = new BigInt(this.bigInteger.multiply(that.bigInteger))
+
+  /** Division of BigInts
+   */
+  def /  (that: BigInt): BigInt = new BigInt(this.bigInteger.divide(that.bigInteger))
+
+  /** Remainder of BigInts
+   */
+  def %  (that: BigInt): BigInt = new BigInt(this.bigInteger.remainder(that.bigInteger))
+
+  /** Returns a pair of two BigInts containing (this / that) and (this % that).
+   */
+  def /% (that: BigInt): (BigInt, BigInt) = {
+    val dr = this.bigInteger.divideAndRemainder(that.bigInteger)
+    (new BigInt(dr(0)), new BigInt(dr(1)))
+  }
+
+  /** Leftshift of BigInt
+   */
+  def << (n: Int): BigInt = new BigInt(this.bigInteger.shiftLeft(n))
+
+  /** (Signed) rightshift of BigInt
+   */
+  def >> (n: Int): BigInt = new BigInt(this.bigInteger.shiftRight(n))
+
+  /** Bitwise and of BigInts
+   */
+  def &  (that: BigInt): BigInt = new BigInt(this.bigInteger.and(that.bigInteger))
+
+  /** Bitwise or of BigInts
+   */
+  def |  (that: BigInt): BigInt = new BigInt(this.bigInteger.or (that.bigInteger))
+
+  /** Bitwise exclusive-or of BigInts
+   */
+  def ^  (that: BigInt): BigInt = new BigInt(this.bigInteger.xor(that.bigInteger))
+
+  /** Bitwise and-not of BigInts. Returns a BigInt whose value is (this & ~that).
+   */
+  def &~ (that: BigInt): BigInt = new BigInt(this.bigInteger.andNot(that.bigInteger))
+
+  /** Returns the greatest common divisor of abs(this) and abs(that)
+   */
+  def gcd (that: BigInt): BigInt = new BigInt(this.bigInteger.gcd(that.bigInteger))
+
+  /** Returns a BigInt whose value is (this mod m).
+   *  This method differs from `%' in that it always returns a non-negative BigInt.
+   */
+  def mod (that: BigInt): BigInt = new BigInt(this.bigInteger.mod(that.bigInteger))
+
+  /** Returns the minimum of this and that
+   */
+  def min (that: BigInt): BigInt = new BigInt(this.bigInteger.min(that.bigInteger))
+
+  /** Returns the maximum of this and that
+   */
+  def max (that: BigInt): BigInt = new BigInt(this.bigInteger.max(that.bigInteger))
+  
+  /** Returns a BigInt whose value is (<tt>this</tt> raised to the power of <tt>exp</tt>).
+   */
+  def pow (exp: Int): BigInt = new BigInt(this.bigInteger.pow(exp))
+
+  /** Returns a BigInt whose value is
+   *  (<tt>this</tt> raised to the power of <tt>exp</tt> modulo <tt>m</tt>).
+   */
+  def modPow (exp: BigInt, m: BigInt): BigInt =
+    new BigInt(this.bigInteger.modPow(exp.bigInteger, m.bigInteger))
+
+  /** Returns a BigInt whose value is (the inverse of <tt>this</tt> modulo <tt>m</tt>).
+   */
+  def modInverse (m: BigInt): BigInt = new BigInt(this.bigInteger.modInverse(m.bigInteger))
+
+  /** Returns a BigInt whose value is the negation of this BigInt
+   */
+  def unary_- : BigInt   = new BigInt(this.bigInteger.negate())
+  
+  /** Returns the absolute value of this BigInt
+   */
+  def abs: BigInt = new BigInt(this.bigInteger.abs())
+
+  /** Returns the sign of this BigInt, i.e. 
+   *   -1 if it is less than 0, 
+   *   +1 if it is greater than 0
+   *   0  if it is equal to 0
+   */
+  def signum: Int = this.bigInteger.signum()
+
+  /** Returns the bitwise complement of this BigNum
+   */
+  def ~ : BigInt   = new BigInt(this.bigInteger.not())
+
+  /** Returns true if and only if the designated bit is set.
+   */
+  def testBit (n: Int): Boolean = this.bigInteger.testBit(n)
+
+  /** Returns a BigInt whose value is equivalent to this BigInt with the designated bit set.
+   */
+  def setBit  (n: Int): BigInt  = new BigInt(this.bigInteger.setBit(n))
+
+  /** Returns a BigInt whose value is equivalent to this BigInt with the designated bit cleared.
+   */
+  def clearBit(n: Int): BigInt  = new BigInt(this.bigInteger.clearBit(n))
+
+  /** Returns a BigInt whose value is equivalent to this BigInt with the designated bit flipped.
+   */
+  def flipBit (n: Int): BigInt  = new BigInt(this.bigInteger.flipBit(n))
+
+  /** Returns the index of the rightmost (lowest-order) one bit in this BigInt
+   * (the number of zero bits to the right of the rightmost one bit).
+   */
+  def lowestSetBit: Int         = this.bigInteger.getLowestSetBit()
+
+  /** Returns the number of bits in the minimal two's-complement representation of this BigInt, 
+   *  excluding a sign bit.
+   */
+  def bitLength: Int            = this.bigInteger.bitLength()
+  
+  /** Returns the number of bits in the two's complement representation of this BigInt 
+   *  that differ from its sign bit.
+   */
+  def bitCount: Int             = this.bigInteger.bitCount()
+
+  /** Returns true if this BigInt is probably prime, false if it's definitely composite.
+   *  @param certainty  a measure of the uncertainty that the caller is willing to tolerate: 
+   *                    if the call returns true the probability that this BigInt is prime 
+   *                    exceeds (1 - 1/2 ^ certainty). 
+   *                    The execution time of this method is proportional to the value of 
+   *                    this parameter.
+   */
+  def isProbablePrime(certainty: Int) = this.bigInteger.isProbablePrime(certainty)
+  
+  /** Converts this BigInt to a <tt>byte</tt>. 
+   *  If the BigInt is too big to fit in a byte, only the low-order 8 bits are returned. 
+   *  Note that this conversion can lose information about the overall magnitude of the 
+   *  BigInt value as well as return a result with the opposite sign.
+   */
+  override def byteValue   = intValue.toByte
+
+  /** Converts this BigInt to a <tt>short</tt>. 
+   *  If the BigInt is too big to fit in a byte, only the low-order 16 bits are returned. 
+   *  Note that this conversion can lose information about the overall magnitude of the 
+   *  BigInt value as well as return a result with the opposite sign.
+   */
+  override def shortValue  = intValue.toShort
+
+  /** Converts this BigInt to a <tt>char</tt>. 
+   *  If the BigInt is too big to fit in a char, only the low-order 16 bits are returned. 
+   *  Note that this conversion can lose information about the overall magnitude of the 
+   *  BigInt value and that it always returns a positive result.
+   */
+  def charValue   = intValue.toChar
+
+  /** Converts this BigInt to an <tt>int</tt>. 
+   *  If the BigInt is too big to fit in a char, only the low-order 32 bits
+   *  are returned. Note that this conversion can lose information about the
+   *  overall magnitude of the BigInt value as well as return a result with
+   *  the opposite sign.
+   */
+  def intValue    = this.bigInteger.intValue
+
+  /** Converts this BigInt to a <tt>long</tt>.
+   *  If the BigInt is too big to fit in a char, only the low-order 64 bits
+   *  are returned. Note that this conversion can lose information about the
+   *  overall magnitude of the BigInt value as well as return a result with
+   *  the opposite sign.
+   */
+  def longValue   = this.bigInteger.longValue
+
+  /** Converts this BigInt to a <tt>float</tt>.
+   *  if this BigInt has too great a magnitude to represent as a float,
+   *  it will be converted to <code>Float.NEGATIVE_INFINITY</code> or
+   *  <code>Float.POSITIVE_INFINITY</code> as appropriate.
+   */
+  def floatValue  = this.bigInteger.floatValue
+
+  /** Converts this BigInt to a <tt>double</tt>. 
+   *  if this BigInt has too great a magnitude to represent as a double, 
+   *  it will be converted to <code>Double.NEGATIVE_INFINITY</code> or
+   *  <code>Double.POSITIVE_INFINITY</code> as appropriate. 
+   */
+  def doubleValue = this.bigInteger.doubleValue
+
+  /** Create a NumericRange[BigInt] in range <code>[start;end)</code>
+   *  with the specified step, where start is the target BigInt.
+   *
+   *  @param end    the end value of the range (exclusive)
+   *  @param step   the distance between elements (defaults to 1)
+   *  @return       the range
+   */
+  def until(end: BigInt, step: BigInt = BigInt(1)) = Range.BigInt(this, end, step)
+  
+  /** Like until, but inclusive of the end value.
+   */
+  def to(end: BigInt, step: BigInt = BigInt(1)) = Range.BigInt.inclusive(this, end, step)
+
+  /** Returns the decimal String representation of this BigInt.
+   */
+  override def toString(): String = this.bigInteger.toString()
+
+  /** Returns the String representation in the specified radix of this BigInt.
+   */
+  def toString(radix: Int): String = this.bigInteger.toString(radix)
+
+  /** Returns a byte array containing the two's-complement representation of
+   *  this BigInt. The byte array will be in big-endian byte-order: the most
+   *  significant byte is in the zeroth element. The array will contain the
+   *  minimum number of bytes required to represent this BigInt, including at
+   *  least one sign bit.
+   */
+  def toByteArray: Array[Byte] = this.bigInteger.toByteArray()
+}
diff --git a/src/library/scala/math/Equiv.scala b/src/library/scala/math/Equiv.scala
new file mode 100644
index 0000000..0998319
--- /dev/null
+++ b/src/library/scala/math/Equiv.scala
@@ -0,0 +1,45 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.math
+
+/** <p>
+ *    A trait for representing equivalence relations.  It is important to 
+ *    distinguish between a type that can be compared for equality or 
+ *    equivalence and a representation of equivalence on some type. This 
+ *    trait is for representing the latter.  
+ *  </p>
+ *  <p>
+ *    An <a href="http://en.wikipedia.org/wiki/Equivalence_relation">equivalence 
+ *    relation</a> is a binary relation on a type. This relation is exposed as
+ *    the <code>equiv</code> method of the <code>Equiv</code> trait. This
+ *    relation must be:
+ *  </p>
+ *  <ul>
+ *   <li>reflexive: <code>equiv(x, x) == true</code>, for any <code>x</code> of 
+ *     type <code>T</code>.</li>
+ *   <li>symmetric: <code>equiv(x, y) == equiv(y, x)</code>, for any
+ *     <code>x</code> and <code>y</code> of type <code>T</code>.</li>
+ *   <li>transitive: if <code>equiv(x, y) == true</code> and <code>equiv(y, z) == true</code> 
+ *     then <code>equiv(x, z) == true</code>, for any <code>x</code>, <code>y</code>,
+ *     and <code>z</code> of type <code>T</code>.</li>
+ *  </ul>
+ *
+ *  @author  Geoffrey Washburn
+ *  @version 1.0, 2008-04-03
+ *  @since 2.7
+ */
+
+trait Equiv[T] {
+  /** Returns <code>true</code> iff <code>x</code> is equivalent to
+   *  <code>y</code>.  
+   */
+  def equiv(x: T, y: T): Boolean 
+}
diff --git a/src/library/scala/math/Fractional.scala b/src/library/scala/math/Fractional.scala
new file mode 100644
index 0000000..827cf1d
--- /dev/null
+++ b/src/library/scala/math/Fractional.scala
@@ -0,0 +1,24 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.math
+
+/**
+ * @since 2.8
+ */
+trait Fractional[T] extends Numeric[T] {
+  def div(x: T, y: T): T
+  
+  class FractionalOps(lhs: T) extends Ops(lhs) {
+    def /(rhs: T) = div(lhs, rhs)
+  }
+  override implicit def mkNumericOps(lhs: T): FractionalOps =
+    new FractionalOps(lhs)
+}
diff --git a/src/library/scala/math/Integral.scala b/src/library/scala/math/Integral.scala
new file mode 100644
index 0000000..0029a1e
--- /dev/null
+++ b/src/library/scala/math/Integral.scala
@@ -0,0 +1,26 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.math
+
+/**
+ * @since 2.8
+ */
+trait Integral[T] extends Numeric[T] {
+  def quot(x: T, y: T): T
+  def rem(x: T, y: T): T
+  
+  class IntegralOps(lhs: T) extends Ops(lhs) {
+    def /(rhs: T) = quot(lhs, rhs)
+    def %(rhs: T) = rem(lhs, rhs)
+    def /%(rhs: T) = (quot(lhs, rhs), rem(lhs, rhs))
+  }
+  override implicit def mkNumericOps(lhs: T): IntegralOps = new IntegralOps(lhs)
+}
diff --git a/src/library/scala/math/Numeric.scala b/src/library/scala/math/Numeric.scala
new file mode 100644
index 0000000..0c12b13
--- /dev/null
+++ b/src/library/scala/math/Numeric.scala
@@ -0,0 +1,202 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.math
+
+/**
+ * @since 2.8
+ */
+object Numeric {
+  trait BigIntIsIntegral extends Integral[BigInt] {
+    def plus(x: BigInt, y: BigInt): BigInt = x + y
+    def minus(x: BigInt, y: BigInt): BigInt = x - y
+    def times(x: BigInt, y: BigInt): BigInt = x * y
+    def quot(x: BigInt, y: BigInt): BigInt = x / y
+    def rem(x: BigInt, y: BigInt): BigInt = x % y
+    def negate(x: BigInt): BigInt = -x
+    def fromInt(x: Int): BigInt = BigInt(x)
+    def toInt(x: BigInt): Int = x.intValue
+    def toLong(x: BigInt): Long = x.longValue
+    def toFloat(x: BigInt): Float = x.longValue.toFloat
+    def toDouble(x: BigInt): Double = x.longValue.toDouble
+  }
+  implicit object BigIntIsIntegral extends BigIntIsIntegral with Ordering.BigIntOrdering
+  
+  trait IntIsIntegral extends Integral[Int] {
+    def plus(x: Int, y: Int): Int = x + y
+    def minus(x: Int, y: Int): Int = x - y
+    def times(x: Int, y: Int): Int = x * y
+    def quot(x: Int, y: Int): Int = x / y
+    def rem(x: Int, y: Int): Int = x % y
+    def negate(x: Int): Int = -x
+    def fromInt(x: Int): Int = x
+    def toInt(x: Int): Int = x
+    def toLong(x: Int): Long = x
+    def toFloat(x: Int): Float = x
+    def toDouble(x: Int): Double = x
+  }
+  implicit object IntIsIntegral extends IntIsIntegral with Ordering.IntOrdering
+  
+  trait ShortIsIntegral extends Integral[Short] {
+    def plus(x: Short, y: Short): Short = (x + y).toShort
+    def minus(x: Short, y: Short): Short = (x - y).toShort
+    def times(x: Short, y: Short): Short = (x * y).toShort
+    def quot(x: Short, y: Short): Short = (x / y).toShort
+    def rem(x: Short, y: Short): Short = (x % y).toShort
+    def negate(x: Short): Short = (-x).toShort
+    def fromInt(x: Int): Short = x.toShort
+    def toInt(x: Short): Int = x.toInt
+    def toLong(x: Short): Long = x.toLong
+    def toFloat(x: Short): Float = x.toFloat
+    def toDouble(x: Short): Double = x.toDouble
+  }
+  implicit object ShortIsIntegral extends ShortIsIntegral with Ordering.ShortOrdering
+  
+  trait ByteIsIntegral extends Integral[Byte] {
+    def plus(x: Byte, y: Byte): Byte = (x + y).toByte
+    def minus(x: Byte, y: Byte): Byte = (x - y).toByte
+    def times(x: Byte, y: Byte): Byte = (x * y).toByte
+    def quot(x: Byte, y: Byte): Byte = (x / y).toByte
+    def rem(x: Byte, y: Byte): Byte = (x % y).toByte
+    def negate(x: Byte): Byte = (-x).toByte
+    def fromInt(x: Int): Byte = x.toByte
+    def toInt(x: Byte): Int = x.toInt
+    def toLong(x: Byte): Long = x.toLong
+    def toFloat(x: Byte): Float = x.toFloat
+    def toDouble(x: Byte): Double = x.toDouble
+  }
+  implicit object ByteIsIntegral extends ByteIsIntegral with Ordering.ByteOrdering
+  
+  trait CharIsIntegral extends Integral[Char] {
+    def plus(x: Char, y: Char): Char = (x + y).toChar
+    def minus(x: Char, y: Char): Char = (x - y).toChar
+    def times(x: Char, y: Char): Char = (x * y).toChar
+    def quot(x: Char, y: Char): Char = (x / y).toChar
+    def rem(x: Char, y: Char): Char = (x % y).toChar
+    def negate(x: Char): Char = (-x).toChar
+    def fromInt(x: Int): Char = x.toChar
+    def toInt(x: Char): Int = x.toInt
+    def toLong(x: Char): Long = x.toLong
+    def toFloat(x: Char): Float = x.toFloat
+    def toDouble(x: Char): Double = x.toDouble
+  }
+  implicit object CharIsIntegral extends CharIsIntegral with Ordering.CharOrdering
+  
+  trait LongIsIntegral extends Integral[Long] {
+    def plus(x: Long, y: Long): Long = x + y
+    def minus(x: Long, y: Long): Long = x - y
+    def times(x: Long, y: Long): Long = x * y
+    def quot(x: Long, y: Long): Long = x / y
+    def rem(x: Long, y: Long): Long = x % y
+    def negate(x: Long): Long = -x
+    def fromInt(x: Int): Long = x
+    def toInt(x: Long): Int = x.toInt
+    def toLong(x: Long): Long = x
+    def toFloat(x: Long): Float = x
+    def toDouble(x: Long): Double = x
+  }
+  implicit object LongIsIntegral extends LongIsIntegral with Ordering.LongOrdering
+  
+  trait FloatIsFractional extends Fractional[Float] {
+    def plus(x: Float, y: Float): Float = x + y
+    def minus(x: Float, y: Float): Float = x - y
+    def times(x: Float, y: Float): Float = x * y 
+    def div(x: Float, y: Float): Float = x / y
+    def negate(x: Float): Float = -x
+    def fromInt(x: Int): Float = x
+    def toInt(x: Float): Int = x.toInt
+    def toLong(x: Float): Long = x.toLong
+    def toFloat(x: Float): Float = x
+    def toDouble(x: Float): Double = x
+  }
+  implicit object FloatIsFractional extends FloatIsFractional with Ordering.FloatOrdering
+  
+  trait DoubleIsConflicted extends Numeric[Double] {
+    def plus(x: Double, y: Double): Double = x + y
+    def minus(x: Double, y: Double): Double = x - y
+    def times(x: Double, y: Double): Double = x * y
+    def negate(x: Double): Double = -x
+    def fromInt(x: Int): Double = x
+    def toInt(x: Double): Int = x.toInt
+    def toLong(x: Double): Long = x.toLong
+    def toFloat(x: Double): Float = x.toFloat
+    def toDouble(x: Double): Double = x
+  }
+  trait DoubleIsFractional extends DoubleIsConflicted with Fractional[Double] {
+    def div(x: Double, y: Double): Double = x / y
+  }
+  trait DoubleAsIfIntegral extends DoubleIsConflicted with Integral[Double] {
+    def quot(x: Double, y: Double): Double = (BigDecimal(x) / BigDecimal(y)).doubleValue
+    def rem(x: Double, y: Double): Double = (BigDecimal(x) remainder BigDecimal(y)).doubleValue
+  }
+  
+  trait BigDecimalIsConflicted extends Numeric[BigDecimal] {
+    def plus(x: BigDecimal, y: BigDecimal): BigDecimal = x + y
+    def minus(x: BigDecimal, y: BigDecimal): BigDecimal = x - y
+    def times(x: BigDecimal, y: BigDecimal): BigDecimal = x * y
+    def negate(x: BigDecimal): BigDecimal = -x
+    def fromInt(x: Int): BigDecimal = BigDecimal(x)
+    def toInt(x: BigDecimal): Int = x.intValue
+    def toLong(x: BigDecimal): Long = x.longValue
+    def toFloat(x: BigDecimal): Float = x.floatValue
+    def toDouble(x: BigDecimal): Double = x.doubleValue
+  }
+  
+  trait BigDecimalIsFractional extends BigDecimalIsConflicted with Fractional[BigDecimal] {
+    def div(x: BigDecimal, y: BigDecimal): BigDecimal = x / y
+  }
+  trait BigDecimalAsIfIntegral extends BigDecimalIsConflicted with Integral[BigDecimal] {
+    def quot(x: BigDecimal, y: BigDecimal): BigDecimal = x / y
+    def rem(x: BigDecimal, y: BigDecimal): BigDecimal = x remainder y
+  }
+
+  // For Double and BigDecimal we offer implicit Fractional objects, but also one
+  // which acts like an Integral type, which is useful in NumericRange.
+  implicit object BigDecimalIsFractional extends BigDecimalIsFractional with Ordering.BigDecimalOrdering  
+  object BigDecimalAsIfIntegral extends BigDecimalAsIfIntegral with Ordering.BigDecimalOrdering
+  
+  implicit object DoubleIsFractional extends DoubleIsFractional with Ordering.DoubleOrdering
+  object DoubleAsIfIntegral extends DoubleAsIfIntegral with Ordering.DoubleOrdering
+}
+
+trait Numeric[T] extends Ordering[T] {
+  def plus(x: T, y: T): T
+  def minus(x: T, y: T): T
+  def times(x: T, y: T): T
+  def negate(x: T): T
+  def fromInt(x: Int): T
+  def toInt(x: T): Int
+  def toLong(x: T): Long
+  def toFloat(x: T): Float
+  def toDouble(x: T): Double
+  
+  def zero = fromInt(0)
+  def one = fromInt(1)
+  
+  def abs(x: T): T = if (lt(x, zero)) negate(x) else x
+  def signum(x: T): Int =
+    if (lt(x, zero)) -1
+    else if (gt(x, zero)) 1
+    else 0
+  
+  class Ops(lhs: T) {
+    def +(rhs: T) = plus(lhs, rhs)
+    def -(rhs: T) = minus(lhs, rhs)
+    def *(rhs: T) = times(lhs, rhs)
+    def unary_-() = negate(lhs)
+    def abs(): T = Numeric.this.abs(lhs)
+    def signum(): Int = Numeric.this.signum(lhs)
+    def toInt(): Int = Numeric.this.toInt(lhs)
+    def toLong(): Long = Numeric.this.toLong(lhs)
+    def toFloat(): Float = Numeric.this.toFloat(lhs)
+    def toDouble(): Double = Numeric.this.toDouble(lhs)    
+  }
+  implicit def mkNumericOps(lhs: T): Ops = new Ops(lhs)
+}
diff --git a/src/library/scala/math/Ordered.scala b/src/library/scala/math/Ordered.scala
new file mode 100644
index 0000000..9be984d
--- /dev/null
+++ b/src/library/scala/math/Ordered.scala
@@ -0,0 +1,56 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.math
+
+/** A trait for totally ordered data.
+ *
+ * Note that since version 2006-07-24 this trait is no longer covariant in a.
+ *
+ * It is important that the equals method for an instance of 
+ * Ordered[A] be consistent with the compare method.  However, 
+ * due to limitations inherent in the type erasure semantics, 
+ * there is no reasonable way to provide a default implementation
+ * of equality for instances of Ordered[A].  Therefore, if you need
+ * to be able to use equality on an instance of Ordered[A] you must 
+ * provide it yourself either when inheiriting or instantiating. 
+ *
+ * It is important that the hashCode method for an instance of 
+ * Ordered[A] be consistent with the compare method. However, 
+ * it is not possible to provide a sensible default implementation.
+ * Therefore, if you need to be able compute the hash of an 
+ * instance of Ordered[A] you must provide it yourself either when 
+ * inheiriting or instantiating. 
+ *
+ *  @author  Martin Odersky
+ *  @version 1.1, 2006-07-24 
+ */
+trait Ordered[A] extends java.lang.Comparable[A] {
+
+  /** Result of comparing <code>this</code> with operand <code>that</code>.
+   *  returns <code>x</code> where
+   *  <code>x < 0</code>    iff    <code>this < that</code>
+   *  <code>x == 0</code>   iff    <code>this == that</code>
+   *  <code>x > 0</code>    iff    <code>this > that</code>
+   */
+  def compare(that: A): Int
+
+  def <  (that: A): Boolean = (this compare that) <  0
+  def >  (that: A): Boolean = (this compare that) >  0
+  def <= (that: A): Boolean = (this compare that) <= 0
+  def >= (that: A): Boolean = (this compare that) >= 0
+  def compareTo(that: A): Int = compare(that)
+}
+
+object Ordered {  
+  /** Lens from Ordering[T] to Ordered[T] */
+  implicit def orderingToOrdered[T](x: T)(implicit ord: Ordering[T]): Ordered[T] = 
+    new Ordered[T] { def compare(that: T): Int = ord.compare(x, that) }
+}
diff --git a/src/library/scala/math/Ordering.scala b/src/library/scala/math/Ordering.scala
new file mode 100644
index 0000000..085486d
--- /dev/null
+++ b/src/library/scala/math/Ordering.scala
@@ -0,0 +1,376 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.math
+
+import java.util.Comparator
+
+/** A trait for representing total orderings.  It is important to 
+ * distinguish between a type that has a total order and a representation 
+ * of total  ordering on some type.  This trait is for representing the 
+ * latter.  
+ *
+ * A <a href="http://en.wikipedia.org/wiki/Total_order">total ordering</a> 
+ * is a binary relation on a type <code>T</code> that is also an equivalence relation
+ * and partial ordering on values of type <code>T</code>.  This relation is exposed as
+ * the <code>compare</code> method of the <code>Ordering</code> trait.   
+ * This relation must be:
+ * <ul>
+ * <li>reflexive: <code>compare(x, x) == 0</code>, for any <code>x</code> of 
+ * type <code>T</code>.</li>
+ * <li>symmetry: <code>compare(x, y) == z</code> and <code>compare(y, x) == w</code>
+ * then <code>math.signum(z) == -math.signum(w)</code>, for any <code>x</code> and <code>y</code> of 
+ * type <code>T</code> and <code>z</code> and <code>w</code> of type <code>Int</code>.</li>
+ * <li>transitive: if <code>compare(x, y) == z</code> and <code>compare(y, w) == v</code> 
+ * and <code>math.signum(z) >= 0</code> and <code>math.signum(v) >= 0</code> then
+ * <code>compare(x, w) == u</code> and <code>math.signum(z + v) == math.signum(u)</code>,
+ * for any <code>x</code>, <code>y</code>,
+ * and <code>w</code> of type <code>T</code> and <code>z</code>, <code>v</code>, and <code>u</code>
+ * of type <code>Int</code>.</li>
+ * </ul>
+ *
+ * @author Geoffrey Washburn
+ * @version 0.9.5, 2008-04-15
+ * @since 2.7
+ */
+ at serializable
+trait Ordering[T] extends Comparator[T] with PartialOrdering[T] { 
+  outer =>
+  
+  /** An Ordering is defined at all x and y. */
+  def tryCompare(x: T, y: T) = Some(compare(x, y))
+  
+ /** Returns a negative integer iff <code>x</code> comes before 
+   * <code>y</code> in the ordering, returns 0 iff <code>x</code> 
+   * is the same in the ordering as <code>y</code>, and returns a 
+   * positive number iff <code>x</code> comes after
+   * <code>y</code> in the ordering.
+   */
+  def compare(x: T, y: T): Int
+
+ /** Returns <code>true</code> iff <code>x</code> comes before 
+   *  <code>y</code> in the ordering.
+   */
+  override def lteq(x: T, y: T): Boolean = compare(x, y) <= 0
+
+  /** Returns <code>true</code> iff <code>y</code> comes before
+   *  <code>x</code> in the ordering. 
+   */
+  override def gteq(x: T, y: T): Boolean = compare(x, y) >= 0
+
+  /** Returns <code>true</code> iff <code>x</code> comes before 
+   *  <code>y</code> in the ordering and is not the same as <code>y</code>.
+   */
+  override def lt(x: T, y: T): Boolean = compare(x, y) < 0
+
+  /** Returns <code>true</code> iff <code>y</code> comes before 
+   *  <code>x</code> in the ordering and is not the same as <code>x</code>.
+   */
+  override def gt(x: T, y: T): Boolean = compare(x, y) > 0
+
+  /** Returns <code>true</code> iff <code>x</code> is equivalent to
+   *  <code>y</code> in the ordering. 
+   */
+  override def equiv(x: T, y: T): Boolean = compare(x, y) == 0
+  
+  /** Returns the argument which comes later in the ordering. */
+  def max(x: T, y: T): T = if (gteq(x, y)) x else y
+  
+  /** Returns the argument which comes earlier in the ordering. */
+  def min(x: T, y: T): T = if (lteq(x, y)) x else y
+ 
+  override def reverse: Ordering[T] = new Ordering[T]{
+    override def reverse = outer
+    def compare(x: T, y: T) = outer.compare(y, x)
+  }
+  
+  /** Given a function U => T, creates Ordering[U]. */
+  def on[U](f: U => T): Ordering[U] = new Ordering[U] {
+    def compare(x: U, y: U) = outer.compare(f(x), f(y))
+  }
+ 
+  class Ops(lhs: T) {
+    def <(rhs: T) = lt(lhs, rhs)
+    def <=(rhs: T) = lteq(lhs, rhs)
+    def >(rhs: T) = gt(lhs, rhs)
+    def >=(rhs: T) = gteq(lhs, rhs)
+    def equiv(rhs: T) = Ordering.this.equiv(lhs, rhs)
+    def max(rhs: T): T = Ordering.this.max(lhs, rhs)
+    def min(rhs: T): T = Ordering.this.min(lhs, rhs)
+  }
+  implicit def mkOrderingOps(lhs: T): Ops = new Ops(lhs)
+}
+
+/** This would conflict with all the nice implicit Orderings
+ *  available, but thanks to the magic of prioritized implicits
+ *  via subclassing we can make Ordered[A] => Ordering[A] only
+ *  turn up if nothing else works.
+ */
+trait LowPriorityOrderingImplicits {
+  implicit def ordered[A <: Ordered[A]]: Ordering[A] = new Ordering[A] {
+    def compare(x: A, y: A) = x.compare(y)
+  }
+}
+
+object Ordering extends LowPriorityOrderingImplicits {
+
+  def apply[T](implicit ord : Ordering[T]) = ord
+  
+  def fromLessThan[T](cmp: (T, T) => Boolean): Ordering[T] = new Ordering[T] {
+    def compare(x: T, y: T) = if (cmp(x, y)) -1 else if (cmp(y, x)) 1 else 0
+    // overrides to avoid multiple comparisons
+    override def lt(x: T, y: T): Boolean = cmp(x, y)
+    override def gt(x: T, y: T): Boolean = cmp(y, x)
+    override def gteq(x: T, y: T): Boolean = !cmp(x, y)
+    override def lteq(x: T, y: T): Boolean = !cmp(y, x)
+  }
+  
+  def by[T, S: Ordering](f: T => S): Ordering[T] = fromLessThan((x, y) => implicitly[Ordering[S]].lt(f(x), f(y)))
+  
+  trait UnitOrdering extends Ordering[Unit] {
+    def compare(x: Unit, y: Unit) = 0
+  }
+  implicit object Unit extends UnitOrdering
+
+  trait BooleanOrdering extends Ordering[Boolean] {
+    def compare(x: Boolean, y: Boolean) = (x, y) match {
+      case (false, true) => -1
+      case (true, false) => 1
+      case _ => 0
+    }
+  }
+  implicit object Boolean extends BooleanOrdering
+
+  trait ByteOrdering extends Ordering[Byte] {
+    def compare(x: Byte, y: Byte) = x.toInt - y.toInt
+  }
+  implicit object Byte extends ByteOrdering
+
+  trait CharOrdering extends Ordering[Char] {
+    def compare(x: Char, y: Char) = x.toInt - y.toInt
+  }
+  implicit object Char extends CharOrdering
+
+  trait ShortOrdering extends Ordering[Short] {
+    def compare(x: Short, y: Short) = x.toInt - y.toInt
+  }
+  implicit object Short extends ShortOrdering
+  
+  trait IntOrdering extends Ordering[Int] {
+    def compare(x: Int, y: Int) = 
+      if (x < y) -1
+      else if (x == y) 0
+      else 1
+  }
+  implicit object Int extends IntOrdering
+
+  trait LongOrdering extends Ordering[Long] {
+    def compare(x: Long, y: Long) = 
+      if (x < y) -1
+      else if (x == y) 0
+      else 1
+  }
+  implicit object Long extends LongOrdering
+
+  trait FloatOrdering extends Ordering[Float] {
+    def compare(x: Float, y: Float) = java.lang.Float.compare(x, y)
+  }
+  implicit object Float extends FloatOrdering
+
+  trait DoubleOrdering extends Ordering[Double] {
+    def compare(x: Double, y: Double) = java.lang.Double.compare(x, y)
+  }
+  implicit object Double extends DoubleOrdering
+
+  trait BigIntOrdering extends Ordering[BigInt] {
+    def compare(x: BigInt, y: BigInt) = x.compare(y)
+  }
+  implicit object BigInt extends BigIntOrdering
+  
+  trait BigDecimalOrdering extends Ordering[BigDecimal] {
+    def compare(x: BigDecimal, y: BigDecimal) = x.compare(y)
+  }
+  implicit object BigDecimal extends BigDecimalOrdering
+
+  trait StringOrdering extends Ordering[String] {
+    def compare(x: String, y: String) = x.compareTo(y)
+  }
+  implicit object String extends StringOrdering
+
+  implicit def Option[T](implicit ord: Ordering[T]) : Ordering[Option[T]] = 
+    new Ordering[Option[T]] {
+      def compare(x : Option[T], y : Option[T]) = (x, y) match {
+        case (None, None) => 0
+        case (None, _) => -1
+        case (_, None) => 1
+        case (Some(x), Some(y)) => ord.compare(x, y)
+      }
+    }
+
+  implicit def Iterable[T](implicit ord: Ordering[T]): Ordering[Iterable[T]] = 
+    new Ordering[Iterable[T]] {
+      def compare(x: Iterable[T], y: Iterable[T]): Int = {
+        val xe = x.iterator
+        val ye = y.iterator
+
+        while (xe.hasNext && ye.hasNext) {
+          val res = ord.compare(xe.next, ye.next)
+          if (res != 0) return res
+        }
+
+        Boolean.compare(xe.hasNext, ye.hasNext)
+      }
+    }
+
+  implicit def Tuple2[T1, T2](implicit ord1: Ordering[T1], ord2: Ordering[T2]): Ordering[(T1, T2)] = 
+    new Ordering[(T1, T2)]{
+      def compare(x: (T1, T2), y: (T1, T2)): Int = {
+        val compare1 = ord1.compare(x._1, y._1)
+        if (compare1 != 0) return compare1
+        val compare2 = ord2.compare(x._2, y._2)
+        if (compare2 != 0) return compare2
+        0
+      }
+    }
+
+  implicit def Tuple3[T1, T2, T3](implicit ord1: Ordering[T1], ord2: Ordering[T2], ord3: Ordering[T3]) : Ordering[(T1, T2, T3)] = 
+    new Ordering[(T1, T2, T3)]{
+      def compare(x: (T1, T2, T3), y: (T1, T2, T3)): Int = {
+        val compare1 = ord1.compare(x._1, y._1)
+        if (compare1 != 0) return compare1
+        val compare2 = ord2.compare(x._2, y._2)
+        if (compare2 != 0) return compare2
+        val compare3 = ord3.compare(x._3, y._3)
+        if (compare3 != 0) return compare3
+        0
+      }
+    }
+
+  implicit def Tuple4[T1, T2, T3, T4](implicit ord1: Ordering[T1], ord2: Ordering[T2], ord3: Ordering[T3], ord4: Ordering[T4]) : Ordering[(T1, T2, T3, T4)] = 
+    new Ordering[(T1, T2, T3, T4)]{
+      def compare(x: (T1, T2, T3, T4), y: (T1, T2, T3, T4)): Int = {
+        val compare1 = ord1.compare(x._1, y._1)
+        if (compare1 != 0) return compare1
+        val compare2 = ord2.compare(x._2, y._2)
+        if (compare2 != 0) return compare2
+        val compare3 = ord3.compare(x._3, y._3)
+        if (compare3 != 0) return compare3
+        val compare4 = ord4.compare(x._4, y._4)
+        if (compare4 != 0) return compare4
+        0
+      }
+    }
+
+  implicit def Tuple5[T1, T2, T3, T4, T5](implicit ord1: Ordering[T1], ord2: Ordering[T2], ord3: Ordering[T3], ord4: Ordering[T4], ord5: Ordering[T5]): Ordering[(T1, T2, T3, T4, T5)] = 
+    new Ordering[(T1, T2, T3, T4, T5)]{
+      def compare(x: (T1, T2, T3, T4, T5), y: Tuple5[T1, T2, T3, T4, T5]): Int = {
+        val compare1 = ord1.compare(x._1, y._1)
+        if (compare1 != 0) return compare1
+        val compare2 = ord2.compare(x._2, y._2)
+        if (compare2 != 0) return compare2
+        val compare3 = ord3.compare(x._3, y._3)
+        if (compare3 != 0) return compare3
+        val compare4 = ord4.compare(x._4, y._4)
+        if (compare4 != 0) return compare4
+        val compare5 = ord5.compare(x._5, y._5)
+        if (compare5 != 0) return compare5
+        0
+      }
+    }
+
+  implicit def Tuple6[T1, T2, T3, T4, T5, T6](implicit ord1: Ordering[T1], ord2: Ordering[T2], ord3: Ordering[T3], ord4: Ordering[T4], ord5: Ordering[T5], ord6: Ordering[T6]): Ordering[(T1, T2, T3, T4, T5, T6)] = 
+    new Ordering[(T1, T2, T3, T4, T5, T6)]{
+      def compare(x: (T1, T2, T3, T4, T5, T6), y: (T1, T2, T3, T4, T5, T6)): Int = {
+        val compare1 = ord1.compare(x._1, y._1)
+        if (compare1 != 0) return compare1
+        val compare2 = ord2.compare(x._2, y._2)
+        if (compare2 != 0) return compare2
+        val compare3 = ord3.compare(x._3, y._3)
+        if (compare3 != 0) return compare3
+        val compare4 = ord4.compare(x._4, y._4)
+        if (compare4 != 0) return compare4
+        val compare5 = ord5.compare(x._5, y._5)
+        if (compare5 != 0) return compare5
+        val compare6 = ord6.compare(x._6, y._6)
+        if (compare6 != 0) return compare6
+        0
+      }
+    }
+
+  implicit def Tuple7[T1, T2, T3, T4, T5, T6, T7](implicit ord1: Ordering[T1], ord2: Ordering[T2], ord3: Ordering[T3], ord4: Ordering[T4], ord5: Ordering[T5], ord6: Ordering[T6], ord7: Ordering[T7]): Ordering[(T1, T2, T3, T4, T5, T6, T7)] = 
+    new Ordering[(T1, T2, T3, T4, T5, T6, T7)]{
+      def compare(x: (T1, T2, T3, T4, T5, T6, T7), y: (T1, T2, T3, T4, T5, T6, T7)): Int = {
+        val compare1 = ord1.compare(x._1, y._1)
+        if (compare1 != 0) return compare1
+        val compare2 = ord2.compare(x._2, y._2)
+        if (compare2 != 0) return compare2
+        val compare3 = ord3.compare(x._3, y._3)
+        if (compare3 != 0) return compare3
+        val compare4 = ord4.compare(x._4, y._4)
+        if (compare4 != 0) return compare4
+        val compare5 = ord5.compare(x._5, y._5)
+        if (compare5 != 0) return compare5
+        val compare6 = ord6.compare(x._6, y._6)
+        if (compare6 != 0) return compare6
+        val compare7 = ord7.compare(x._7, y._7)
+        if (compare7 != 0) return compare7
+        0
+      }
+    }
+
+  implicit def Tuple8[T1, T2, T3, T4, T5, T6, T7, T8](implicit ord1: Ordering[T1], ord2: Ordering[T2], ord3: Ordering[T3], ord4: Ordering[T4], ord5: Ordering[T5], ord6: Ordering[T6], ord7: Ordering[T7], ord8: Ordering[T8]): Ordering[(T1, T2, T3, T4, T5, T6, T7, T8)] = 
+    new Ordering[(T1, T2, T3, T4, T5, T6, T7, T8)]{
+      def compare(x: (T1, T2, T3, T4, T5, T6, T7, T8), y: (T1, T2, T3, T4, T5, T6, T7, T8)): Int = {
+        val compare1 = ord1.compare(x._1, y._1)
+        if (compare1 != 0) return compare1
+        val compare2 = ord2.compare(x._2, y._2)
+        if (compare2 != 0) return compare2
+        val compare3 = ord3.compare(x._3, y._3)
+        if (compare3 != 0) return compare3
+        val compare4 = ord4.compare(x._4, y._4)
+        if (compare4 != 0) return compare4
+        val compare5 = ord5.compare(x._5, y._5)
+        if (compare5 != 0) return compare5
+        val compare6 = ord6.compare(x._6, y._6)
+        if (compare6 != 0) return compare6
+        val compare7 = ord7.compare(x._7, y._7)
+        if (compare7 != 0) return compare7
+        val compare8 = ord8.compare(x._8, y._8)
+        if (compare8 != 0) return compare8
+        0
+      }
+    }
+
+  implicit def Tuple9[T1, T2, T3, T4, T5, T6, T7, T8, T9](implicit ord1: Ordering[T1], ord2: Ordering[T2], ord3: Ordering[T3], ord4: Ordering[T4], ord5: Ordering[T5], ord6: Ordering[T6], ord7: Ordering[T7], ord8 : Ordering[T8], ord9: Ordering[T9]): Ordering[(T1, T2, T3, T4, T5, T6, T7, T8, T9)] = 
+    new Ordering[(T1, T2, T3, T4, T5, T6, T7, T8, T9)]{
+      def compare(x: (T1, T2, T3, T4, T5, T6, T7, T8, T9), y: (T1, T2, T3, T4, T5, T6, T7, T8, T9)): Int = {
+        val compare1 = ord1.compare(x._1, y._1)
+        if (compare1 != 0) return compare1
+        val compare2 = ord2.compare(x._2, y._2)
+        if (compare2 != 0) return compare2
+        val compare3 = ord3.compare(x._3, y._3)
+        if (compare3 != 0) return compare3
+        val compare4 = ord4.compare(x._4, y._4)
+        if (compare4 != 0) return compare4
+        val compare5 = ord5.compare(x._5, y._5)
+        if (compare5 != 0) return compare5
+        val compare6 = ord6.compare(x._6, y._6)
+        if (compare6 != 0) return compare6
+        val compare7 = ord7.compare(x._7, y._7)
+        if (compare7 != 0) return compare7
+        val compare8 = ord8.compare(x._8, y._8)
+        if (compare8 != 0) return compare8
+        val compare9 = ord9.compare(x._9, y._9)
+        if (compare9 != 0) return compare9
+        0
+      }
+    }
+
+}
diff --git a/src/library/scala/math/PartialOrdering.scala b/src/library/scala/math/PartialOrdering.scala
new file mode 100644
index 0000000..7637e20
--- /dev/null
+++ b/src/library/scala/math/PartialOrdering.scala
@@ -0,0 +1,85 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.math
+
+/** <p>
+ *    A trait for representing partial orderings.  It is important to
+ *    distinguish between a type that has a partial order and a representation 
+ *    of partial ordering on some type.  This trait is for representing the
+ *    latter.  
+ *  </p>
+ *  <p>
+ *    A <a href="http://en.wikipedia.org/wiki/Partial_order">partial ordering</a> 
+ *    is a binary relation on a type <code>T</code> that is also an equivalence 
+ *    relation on values of type <code>T</code>.  This relation is exposed as
+ *    the <code>lteq</code> method of the <code>PartialOrdering</code> trait.  
+ *    This relation must be:
+ *  </p>
+ *  <ul>
+ *    <li>reflexive: <code>lteq(x, x) == true</code>, for any <code>x</code> of 
+ *      type <code>T</code>.</li>
+ *    <li>anti-symmetric: <code>lteq(x, y) == true</code> and
+ *      <code>lteq(y, x) == true</code> then <code>equiv(x, y)</code>, for any
+ *      <code>x</code> and <code>y</code> of type <code>T</code>.</li>
+ *    <li>transitive: if <code>lteq(x, y) == true</code> and
+ *      <code>lteq(y, z) == true</code> then <code>lteq(x, z) == true</code>,
+ *      for any <code>x</code>, <code>y</code>, and <code>z</code> of type
+ *      <code>T</code>.</li>
+ * </ul>
+ *
+ *  @author  Geoffrey Washburn
+ *  @version 1.0, 2008-04-0-3
+ *  @since 2.7
+ */
+
+trait PartialOrdering[T] extends Equiv[T] {
+  outer =>
+  
+  /** Result of comparing <code>x</code> with operand <code>y</code>.
+   *  Returns <code>None</code> if operands are not comparable.
+   *  If operands are comparable, returns <code>Some(r)</code> where
+   *  <code>r < 0</code>    iff    <code>x < y</code>
+   *  <code>r == 0</code>   iff    <code>x == y</code>
+   *  <code>r > 0</code>    iff    <code>x > y</code>
+   */
+  def tryCompare(x: T, y: T): Option[Int]
+  
+  /** Returns <code>true</code> iff <code>x</code> comes before 
+   *  <code>y</code> in the ordering.
+   */
+  def lteq(x: T, y: T): Boolean
+
+  /** Returns <code>true</code> iff <code>y</code> comes before
+   *  <code>x</code> in the ordering. 
+   */
+  def gteq(x: T, y: T): Boolean = lteq(y, x)
+
+  /** Returns <code>true</code> iff <code>x</code> comes before 
+   *  <code>y</code> in the ordering and is not the same as <code>y</code>.
+   */
+  def lt(x: T, y: T): Boolean = lteq(x, y) && !equiv(x, y)
+
+  /** Returns <code>true</code> iff <code>y</code> comes before 
+   *  <code>x</code> in the ordering and is not the same as <code>x</code>.
+   */
+  def gt(x: T, y: T): Boolean = gteq(x, y) && !equiv(x, y)
+
+  /** Returns <code>true</code> iff <code>x</code> is equivalent to
+   *  <code>y</code> in the ordering. 
+   */
+  def equiv(x: T, y: T): Boolean = lteq(x,y) && lteq(y,x)
+
+  def reverse : PartialOrdering[T] = new PartialOrdering[T] {
+    override def reverse = outer
+    def lteq(x: T, y: T) = outer.lteq(y, x)
+    def tryCompare(x: T, y: T) = outer.tryCompare(y, x)
+  }
+}
diff --git a/src/library/scala/math/PartiallyOrdered.scala b/src/library/scala/math/PartiallyOrdered.scala
new file mode 100644
index 0000000..2e863ec
--- /dev/null
+++ b/src/library/scala/math/PartiallyOrdered.scala
@@ -0,0 +1,49 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.math
+
+/** A class for partially ordered data.
+ *
+ *  @author  Martin Odersky
+ *  @version 1.0, 23/04/2004
+ */
+trait PartiallyOrdered[+A] {
+
+  /** Result of comparing <code>this</code> with operand <code>that</code>.
+   *  Returns <code>None</code> if operands are not comparable.
+   *  If operands are comparable, returns <code>Some(x)</code> where
+   *  <code>x < 0</code>    iff    <code>this < that</code>
+   *  <code>x == 0</code>   iff    <code>this == that</code>
+   *  <code>x > 0</code>    iff    <code>this > that</code>
+   */
+  def tryCompareTo [B >: A <% PartiallyOrdered[B]](that: B): Option[Int]
+
+  def <  [B >: A <% PartiallyOrdered[B]](that: B): Boolean =
+    (this tryCompareTo that) match {
+      case Some(x) if x < 0 => true
+      case _ => false
+    }
+  def >  [B >: A <% PartiallyOrdered[B]](that: B): Boolean =
+    (this tryCompareTo that) match {
+      case Some(x) if x > 0 => true
+      case _ => false
+    }
+  def <= [B >: A <% PartiallyOrdered[B]](that: B): Boolean =
+    (this tryCompareTo that) match {
+      case Some(x) if x <= 0 => true
+      case _ => false
+    }
+  def >= [B >: A <% PartiallyOrdered[B]](that: B): Boolean =
+    (this tryCompareTo that) match {
+      case Some(x) if x >= 0 => true
+      case _ => false
+    }
+}
diff --git a/src/library/scala/math/ScalaNumber.java b/src/library/scala/math/ScalaNumber.java
new file mode 100644
index 0000000..4aa9204
--- /dev/null
+++ b/src/library/scala/math/ScalaNumber.java
@@ -0,0 +1,21 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2006-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.math;
+
+/** A marker class for Number types introduced by Scala
+ *  @author  Martin Odersky, Paul Phillips
+ *  @version 2.8
+ *  @since 2.8
+ */
+public abstract class ScalaNumber extends java.lang.Number {
+  protected abstract boolean isWhole();
+  public abstract Object underlying();
+}
diff --git a/src/library/scala/math/ScalaNumericConversions.scala b/src/library/scala/math/ScalaNumericConversions.scala
new file mode 100644
index 0000000..aa310b3
--- /dev/null
+++ b/src/library/scala/math/ScalaNumericConversions.scala
@@ -0,0 +1,60 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+package scala.math
+
+import java.{ lang => jl }
+
+/** Conversions which present a consistent conversion interface
+ *  across all the numeric types.
+ */
+trait ScalaNumericConversions extends ScalaNumber {  
+  def toChar = intValue.toChar
+  def toByte = byteValue
+  def toShort = shortValue
+  def toInt = intValue
+  def toLong = longValue
+  def toFloat = floatValue
+  def toDouble = doubleValue
+  
+  def isValidByte = isWhole && (toByte == toInt)
+  def isValidShort = isWhole && (toShort == toInt)
+  def isValidInt = isWhole && (toInt == toLong)
+  def isValidChar = isWhole && (toInt >= Char.MinValue && toInt <= Char.MaxValue)
+  
+  protected def unifiedPrimitiveHashcode() = {
+    val lv = toLong
+    if (lv >= Int.MinValue && lv <= Int.MaxValue) lv.toInt
+    else lv.##
+  }
+
+  /** Should only be called after all known non-primitive
+   *  types have been excluded.  This method won't dispatch
+   *  anywhere else after checking against the primitives
+   *  to avoid infinite recursion between equals and this on
+   *  unknown "Number" variants.
+   *
+   *  Additionally, this should only be called if the numeric
+   *  type is happy to be converted to Long, Float, and Double.
+   *  If for instance a BigInt much larger than the Long range is 
+   *  sent here, it will claim equality with whatever Long is left
+   *  in its lower 64 bits.  Or a BigDecimal with more precision
+   *  than Double can hold: same thing.  There's no way given the
+   *  interface available here to prevent this error.
+   */
+  protected def unifiedPrimitiveEquals(x: Any) = x match {
+    case x: Char    => isValidChar && (toInt == x.toInt)
+    case x: Byte    => isValidByte && (toByte == x)
+    case x: Short   => isValidShort && (toShort == x)
+    case x: Int     => isValidInt && (toInt == x)
+    case x: Long    => toLong == x
+    case x: Float   => toFloat == x
+    case x: Double  => toDouble == x
+    case _          => false
+  }
+}
diff --git a/src/library/scala/math/package.scala b/src/library/scala/math/package.scala
new file mode 100644
index 0000000..fb8d5f7
--- /dev/null
+++ b/src/library/scala/math/package.scala
@@ -0,0 +1,30 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+package scala
+
+/** The package object <code>scala.math</code> contains methods for performing basic numeric
+ *  operations such as the elementary exponential, logarithm, square root, and
+ *  trigonometric functions.
+ */
+
+package object math extends MathCommon {
+  // These are new in 2.8, so they don't belong in the deprecated scala.Math.
+  
+  def log10(x: Double): Double = java.lang.Math.log10(x)
+  def cbrt(x: Double): Double = java.lang.Math.cbrt(x)
+  
+  def ulp(x: Double): Double = java.lang.Math.ulp(x)
+  def ulp(x: Float): Float = java.lang.Math.ulp(x)
+  def sinh(x: Double): Double = java.lang.Math.sinh(x)
+  def cosh(x: Double): Double = java.lang.Math.cosh(x)
+  def tanh(x: Double):Double = java.lang.Math.tanh(x)
+  def hypot(x: Double, y: Double): Double = java.lang.Math.hypot(x, y)
+  def expm1(x: Double): Double = java.lang.Math.expm1(x)
+  def log1p(x: Double): Double = java.lang.Math.log1p(x)
+}
\ No newline at end of file
diff --git a/src/library/scala/mobile/Code.scala b/src/library/scala/mobile/Code.scala
index ec611fd..daeb2dd 100644
--- a/src/library/scala/mobile/Code.scala
+++ b/src/library/scala/mobile/Code.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Code.scala 16881 2009-01-09 16:28:11Z cunei $
 
 
 package scala.mobile
@@ -160,24 +159,14 @@ class Code(clazz: java.lang.Class[_]) {
   ////////////////////// private functions ///////////////////////
 
   private def boxValue(value: Any) = value match {
-    /** Should use java.lang.Byte.valueOf(Byte), but only available
-     * in Java 1.5 and above. */
-    case x: Byte    => (new java.lang.Byte(x),        java.lang.Byte.TYPE)
-    case x: Boolean => (java.lang.Boolean.valueOf(x), java.lang.Boolean.TYPE)
-    /** Should use java.lang.Character.valueOf(Char), but only available
-     * in Java 1.5 and above. */
-    case x: Char    => (new java.lang.Character(x),   java.lang.Character.TYPE)
-    /** Should use java.lang.Short.valueOf(Short), but only available
-     * in Java 1.5 and above. */
-    case x: Short   => (new java.lang.Short(x),       java.lang.Short.TYPE)
-    /** Should use java.lang.Integer.valueOf(Int), but only available
-     * in Java 1.5 and above. */
-    case x: Int     => (new java.lang.Integer(x),     java.lang.Integer.TYPE)
-    /** Should use java.lang.Long.valueOf(Long), but only available
-     * in Java 1.5 and above. */
-    case x: Long    => (new java.lang.Long(x),        java.lang.Long.TYPE)
-    case x: Float   => (new java.lang.Float(x),       java.lang.Float.TYPE)
-    case x: Double  => (new java.lang.Double(x),      java.lang.Double.TYPE)
+    case x: Byte    => (java.lang.Byte.valueOf(x),        java.lang.Byte.TYPE)
+    case x: Boolean => (java.lang.Boolean.valueOf(x),     java.lang.Boolean.TYPE)
+    case x: Char    => (java.lang.Character.valueOf(x),   java.lang.Character.TYPE)
+    case x: Short   => (java.lang.Short.valueOf(x),       java.lang.Short.TYPE)
+    case x: Int     => (java.lang.Integer.valueOf(x),     java.lang.Integer.TYPE)
+    case x: Long    => (java.lang.Long.valueOf(x),        java.lang.Long.TYPE)
+    case x: Float   => (java.lang.Float.valueOf(x),       java.lang.Float.TYPE)
+    case x: Double  => (java.lang.Double.valueOf(x),      java.lang.Double.TYPE)
     case _          =>
       val x = value.asInstanceOf[JObject]
       (x, x.getClass())
diff --git a/src/library/scala/mobile/Location.scala b/src/library/scala/mobile/Location.scala
index 15e997f..4b5f131 100644
--- a/src/library/scala/mobile/Location.scala
+++ b/src/library/scala/mobile/Location.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Location.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala.mobile
diff --git a/src/library/scala/native.scala b/src/library/scala/native.scala
index d86806d..8f5f3e8 100644
--- a/src/library/scala/native.scala
+++ b/src/library/scala/native.scala
@@ -1,24 +1,23 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: native.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala
 
-/**
- * Marker for native methods.
- * <p>
- *   <code>@native def f(x: Int, y: List[Long]): String = ..</code>
- * </p>
- * <p>
- *   Method body is not generated if method is marked with <code>@native</code>,
- *   but it is type checked when present.
- * </p>
- */
+/** Marker for native methods.
+  *
+  * {{{
+  * @native def f(x: Int, y: List[Long]): String = ...
+  * }}}
+  *
+  * Method body is not generated if method is marked with `@native`,
+  * but it is type checked when present.
+  *
+  * @since 2.6 */
 class native extends StaticAnnotation {}
diff --git a/src/library/scala/noinline.scala b/src/library/scala/noinline.scala
index c885ec5..18270e7 100644
--- a/src/library/scala/noinline.scala
+++ b/src/library/scala/noinline.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: noinline.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala
@@ -17,5 +16,6 @@ package scala
  *
  * @author Lex Spoon
  * @version 1.0, 2007-5-21
+ * @since 2.5
  */
 class noinline extends StaticAnnotation
diff --git a/src/library/scala/package.scala b/src/library/scala/package.scala
new file mode 100644
index 0000000..09eced4
--- /dev/null
+++ b/src/library/scala/package.scala
@@ -0,0 +1,157 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+/**
+ * Core Scala types. They are always available without an explicit import.
+ */
+package object scala {
+  type Throwable = java.lang.Throwable
+  type Exception = java.lang.Exception
+  type Error     = java.lang.Error
+
+  type RuntimeException                = java.lang.RuntimeException
+  type NullPointerException            = java.lang.NullPointerException
+  type ClassCastException              = java.lang.ClassCastException
+  type IndexOutOfBoundsException       = java.lang.IndexOutOfBoundsException
+  type ArrayIndexOutOfBoundsException  = java.lang.ArrayIndexOutOfBoundsException
+  type StringIndexOutOfBoundsException = java.lang.StringIndexOutOfBoundsException
+  type UnsupportedOperationException   = java.lang.UnsupportedOperationException
+  type IllegalArgumentException        = java.lang.IllegalArgumentException
+  type NoSuchElementException          = java.util.NoSuchElementException
+  type NumberFormatException           = java.lang.NumberFormatException
+  type AbstractMethodError             = java.lang.AbstractMethodError
+  
+  type TraversableOnce[+A] = scala.collection.TraversableOnce[A]
+
+  type Traversable[+A] = scala.collection.Traversable[A]
+  val Traversable = scala.collection.Traversable
+
+  type Iterable[+A] = scala.collection.Iterable[A]
+  val Iterable = scala.collection.Iterable
+
+  type Seq[+A] = scala.collection.Seq[A]
+  val Seq = scala.collection.Seq
+
+  type IndexedSeq[+A] = scala.collection.IndexedSeq[A]
+  val IndexedSeq = scala.collection.IndexedSeq
+
+  type Iterator[+A] = scala.collection.Iterator[A]
+  val Iterator = scala.collection.Iterator
+
+  type BufferedIterator[+A] = scala.collection.BufferedIterator[A]
+
+  type List[+A] = scala.collection.immutable.List[A]
+  val List = scala.collection.immutable.List
+
+  val Nil = scala.collection.immutable.Nil
+  
+  type ::[A] = scala.collection.immutable.::[A]
+  val :: = scala.collection.immutable.::
+
+  type Stream[+A] = scala.collection.immutable.Stream[A]
+  val Stream = scala.collection.immutable.Stream
+  val #:: = scala.collection.immutable.Stream.#::
+
+  type Vector[+A] = scala.collection.immutable.Vector[A]
+  val Vector = scala.collection.immutable.Vector
+  
+  type StringBuilder = scala.collection.mutable.StringBuilder
+
+  type Range = scala.collection.immutable.Range
+  val Range = scala.collection.immutable.Range
+
+  // Migrated from Predef
+
+  val $scope = scala.xml.TopScope
+  def currentThread = java.lang.Thread.currentThread()
+  
+  // Numeric types which were moved into scala.math.*
+  
+  type BigDecimal = scala.math.BigDecimal
+  val BigDecimal = scala.math.BigDecimal
+  
+  type BigInt = scala.math.BigInt
+  val BigInt = scala.math.BigInt
+  
+  type Equiv[T] = scala.math.Equiv[T]
+  type Fractional[T] = scala.math.Fractional[T]
+  type Integral[T] = scala.math.Integral[T]
+
+  type Numeric[T] = scala.math.Numeric[T]
+  val Numeric = scala.math.Numeric
+  
+  type Ordered[T] = scala.math.Ordered[T]
+  val Ordered = scala.math.Ordered
+  
+  type Ordering[T] = scala.math.Ordering[T]
+  val Ordering = scala.math.Ordering
+  
+  type PartialOrdering[T] = scala.math.PartialOrdering[T]  
+  type PartiallyOrdered[T] = scala.math.PartiallyOrdered[T]
+  
+  @deprecated("Use Tuple1(x) to create a 1-tuple.")
+  def Tuple[A1](x1: A1) = Tuple1(x1)
+  @deprecated("Use ((x1, x2, ...)) syntax to create Tuples")
+  def Tuple[A1, A2](x1: A1, x2: A2) = Tuple2(x1, x2)
+  @deprecated("Use ((x1, x2, ...)) syntax to create Tuples")
+  def Tuple[A1, A2, A3](x1: A1, x2: A2, x3: A3) = Tuple3(x1, x2, x3)
+  @deprecated("Use ((x1, x2, ...)) syntax to create Tuples")
+  def Tuple[A1, A2, A3, A4](x1: A1, x2: A2, x3: A3, x4: A4) = Tuple4(x1, x2, x3, x4)
+  @deprecated("Use ((x1, x2, ...)) syntax to create Tuples")
+  def Tuple[A1, A2, A3, A4, A5](x1: A1, x2: A2, x3: A3, x4: A4, x5: A5) = Tuple5(x1, x2, x3, x4, x5)
+  @deprecated("Use ((x1, x2, ...)) syntax to create Tuples")
+  def Tuple[A1, A2, A3, A4, A5, A6](x1: A1, x2: A2, x3: A3, x4: A4, x5: A5, x6: A6) = Tuple6(x1, x2, x3, x4, x5, x6)
+  @deprecated("Use ((x1, x2, ...)) syntax to create Tuples")
+  def Tuple[A1, A2, A3, A4, A5, A6, A7](x1: A1, x2: A2, x3: A3, x4: A4, x5: A5, x6: A6, x7: A7) = Tuple7(x1, x2, x3, x4, x5, x6, x7)
+  @deprecated("Use ((x1, x2, ...)) syntax to create Tuples")
+  def Tuple[A1, A2, A3, A4, A5, A6, A7, A8](x1: A1, x2: A2, x3: A3, x4: A4, x5: A5, x6: A6, x7: A7, x8: A8) = Tuple8(x1, x2, x3, x4, x5, x6, x7, x8)
+  @deprecated("Use ((x1, x2, ...)) syntax to create Tuples")
+  def Tuple[A1, A2, A3, A4, A5, A6, A7, A8, A9](x1: A1, x2: A2, x3: A3, x4: A4, x5: A5, x6: A6, x7: A7, x8: A8, x9: A9) = Tuple9(x1, x2, x3, x4, x5, x6, x7, x8, x9)
+  @deprecated("Use ((x1, x2, ...)) syntax to create Tuples")
+  def Tuple[A1, A2, A3, A4, A5, A6, A7, A8, A9, A10](x1: A1, x2: A2, x3: A3, x4: A4, x5: A5, x6: A6, x7: A7, x8: A8, x9: A9, x10: A10) = Tuple10(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10)
+  @deprecated("Use ((x1, x2, ...)) syntax to create Tuples")
+  def Tuple[A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11](x1: A1, x2: A2, x3: A3, x4: A4, x5: A5, x6: A6, x7: A7, x8: A8, x9: A9, x10: A10, x11: A11) = Tuple11(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11)
+  @deprecated("Use ((x1, x2, ...)) syntax to create Tuples")
+  def Tuple[A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12](x1: A1, x2: A2, x3: A3, x4: A4, x5: A5, x6: A6, x7: A7, x8: A8, x9: A9, x10: A10, x11: A11, x12: A12) = Tuple12(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12)
+  @deprecated("Use ((x1, x2, ...)) syntax to create Tuples")
+  def Tuple[A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13](x1: A1, x2: A2, x3: A3, x4: A4, x5: A5, x6: A6, x7: A7, x8: A8, x9: A9, x10: A10, x11: A11, x12: A12, x13: A13) = Tuple13(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13)
+  @deprecated("Use ((x1, x2, ...)) syntax to create Tuples")
+  def Tuple[A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14](x1: A1, x2: A2, x3: A3, x4: A4, x5: A5, x6: A6, x7: A7, x8: A8, x9: A9, x10: A10, x11: A11, x12: A12, x13: A13, x14: A14) = Tuple14(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14)
+  @deprecated("Use ((x1, x2, ...)) syntax to create Tuples")
+  def Tuple[A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15](x1: A1, x2: A2, x3: A3, x4: A4, x5: A5, x6: A6, x7: A7, x8: A8, x9: A9, x10: A10, x11: A11, x12: A12, x13: A13, x14: A14, x15: A15) = Tuple15(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15)
+  @deprecated("Use ((x1, x2, ...)) syntax to create Tuples")
+  def Tuple[A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16](x1: A1, x2: A2, x3: A3, x4: A4, x5: A5, x6: A6, x7: A7, x8: A8, x9: A9, x10: A10, x11: A11, x12: A12, x13: A13, x14: A14, x15: A15, x16: A16) = Tuple16(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16)
+  @deprecated("Use ((x1, x2, ...)) syntax to create Tuples")
+  def Tuple[A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17](x1: A1, x2: A2, x3: A3, x4: A4, x5: A5, x6: A6, x7: A7, x8: A8, x9: A9, x10: A10, x11: A11, x12: A12, x13: A13, x14: A14, x15: A15, x16: A16, x17: A17) = Tuple17(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17)
+  @deprecated("Use ((x1, x2, ...)) syntax to create Tuples")
+  def Tuple[A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18](x1: A1, x2: A2, x3: A3, x4: A4, x5: A5, x6: A6, x7: A7, x8: A8, x9: A9, x10: A10, x11: A11, x12: A12, x13: A13, x14: A14, x15: A15, x16: A16, x17: A17, x18: A18) = Tuple18(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17, x18)
+  @deprecated("Use ((x1, x2, ...)) syntax to create Tuples")
+  def Tuple[A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19](x1: A1, x2: A2, x3: A3, x4: A4, x5: A5, x6: A6, x7: A7, x8: A8, x9: A9, x10: A10, x11: A11, x12: A12, x13: A13, x14: A14, x15: A15, x16: A16, x17: A17, x18: A18, x19: A19) = Tuple19(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17, x18, x19)
+  @deprecated("Use ((x1, x2, ...)) syntax to create Tuples")
+  def Tuple[A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19, A20](x1: A1, x2: A2, x3: A3, x4: A4, x5: A5, x6: A6, x7: A7, x8: A8, x9: A9, x10: A10, x11: A11, x12: A12, x13: A13, x14: A14, x15: A15, x16: A16, x17: A17, x18: A18, x19: A19, x20: A20) = Tuple20(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17, x18, x19, x20)
+  @deprecated("Use ((x1, x2, ...)) syntax to create Tuples")
+  def Tuple[A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19, A20, A21](x1: A1, x2: A2, x3: A3, x4: A4, x5: A5, x6: A6, x7: A7, x8: A8, x9: A9, x10: A10, x11: A11, x12: A12, x13: A13, x14: A14, x15: A15, x16: A16, x17: A17, x18: A18, x19: A19, x20: A20, x21: A21) = Tuple21(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17, x18, x19, x20, x21)
+  @deprecated("Use ((x1, x2, ...)) syntax to create Tuples")
+  def Tuple[A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15, A16, A17, A18, A19, A20, A21, A22](x1: A1, x2: A2, x3: A3, x4: A4, x5: A5, x6: A6, x7: A7, x8: A8, x9: A9, x10: A10, x11: A11, x12: A12, x13: A13, x14: A14, x15: A15, x16: A16, x17: A17, x18: A18, x19: A19, x20: A20, x21: A21, x22: A22) = Tuple22(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17, x18, x19, x20, x21, x22)
+  
+  @deprecated("use <code>java.lang.Integer</code> instead")
+  type Integer = java.lang.Integer
+  @deprecated("use <code>java.lang.Character</code> instead")
+  type Character = java.lang.Character
+
+  @deprecated("use Iterable instead") type Collection[+A] = Iterable[A]
+  @deprecated("use Iterable instead") val Collection = Iterable
+
+  @deprecated("use Seq instead") type Sequence[+A] = scala.collection.Seq[A]
+  @deprecated("use Seq instead") val Sequence = scala.collection.Seq
+
+  @deprecated("use IndexedSeq instead") type RandomAccessSeq[+A] = scala.collection.IndexedSeq[A]
+  @deprecated("use IndexedSeq instead") val RandomAccessSeq = scala.collection.IndexedSeq
+}
diff --git a/src/library/scala/ref/PhantomReference.scala b/src/library/scala/ref/PhantomReference.scala
index dda3cd3..01c401b 100644
--- a/src/library/scala/ref/PhantomReference.scala
+++ b/src/library/scala/ref/PhantomReference.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2006-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: PhantomReference.scala 16894 2009-01-13 13:09:41Z cunei $
 
 package scala.ref
 
@@ -15,6 +14,11 @@ package scala.ref
  */
 class PhantomReference[+T <: AnyRef](value: T, queue: ReferenceQueue[T]) extends ReferenceWrapper[T] {
   val underlying: java.lang.ref.PhantomReference[_ <: T] = 
-    new java.lang.ref.PhantomReference[T](value, queue.underlying.asInstanceOf[java.lang.ref.ReferenceQueue[T]])
+    new PhantomReferenceWithWrapper[T](value, queue, this)
 }
-                                      
+
+/**
+ *  @author Philipp Haller
+ */
+private class PhantomReferenceWithWrapper[T <: AnyRef](value: T, queue: ReferenceQueue[T], val wrapper: PhantomReference[T])
+  extends java.lang.ref.PhantomReference[T](value, queue.underlying.asInstanceOf[java.lang.ref.ReferenceQueue[T]]) with ReferenceWithWrapper[T]
diff --git a/src/library/scala/ref/Reference.scala b/src/library/scala/ref/Reference.scala
index 175621e..64a0dc9 100644
--- a/src/library/scala/ref/Reference.scala
+++ b/src/library/scala/ref/Reference.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2006-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Reference.scala 16894 2009-01-13 13:09:41Z cunei $
 
 package scala.ref
 
@@ -15,11 +14,10 @@ package scala.ref
  * @author Sean McDirmid
  */
 trait Reference[+T <: AnyRef] extends Function0[T] {
-  @deprecated def isValid: Boolean
   /** return the underlying value */
   def apply(): T
   /** return <code>Some</code> underlying if it hasn't been collected, otherwise <code>None</code> */
-  def get : Option[T]
+  def get: Option[T]
   override def toString = get.map(_.toString).getOrElse("<deleted>")
   def clear(): Unit
   def enqueue(): Boolean
diff --git a/src/library/scala/ref/ReferenceQueue.scala b/src/library/scala/ref/ReferenceQueue.scala
index a82c6d1..d019005 100644
--- a/src/library/scala/ref/ReferenceQueue.scala
+++ b/src/library/scala/ref/ReferenceQueue.scala
@@ -1,27 +1,31 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2006-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: ReferenceQueue.scala 16894 2009-01-13 13:09:41Z cunei $
 
 package scala.ref
 
 /**
  *  @author Sean McDirmid
+ *  @author Philipp Haller
  */
 class ReferenceQueue[+T <: AnyRef] {
+
   private[ref] val underlying: java.lang.ref.ReferenceQueue[_ <: T] = new java.lang.ref.ReferenceQueue[T]
   override def toString = underlying.toString
-  protected class Wrapper[U <: AnyRef](val underlying: java.lang.ref.Reference[U]) extends ReferenceWrapper[U]
-  protected def Wrapper[U <: AnyRef](ref: java.lang.ref.Reference[U]) = ref match {
-    case null => None
-    case ref => Some(new Wrapper(ref))
-  }
+
+  protected def Wrapper(jref: java.lang.ref.Reference[_]): Option[Reference[T]] =
+    jref match {
+      case null => None
+      case ref => Some(ref.asInstanceOf[ReferenceWithWrapper[T]].wrapper)
+    }
+
   def poll: Option[Reference[T]] = Wrapper(underlying.poll)
   def remove: Option[Reference[T]] = Wrapper(underlying.remove)
   def remove(timeout: Long): Option[Reference[T]] = Wrapper(underlying.remove(timeout))
+
 }
diff --git a/src/library/scala/ref/ReferenceWrapper.scala b/src/library/scala/ref/ReferenceWrapper.scala
index d0884d2..a343de1 100644
--- a/src/library/scala/ref/ReferenceWrapper.scala
+++ b/src/library/scala/ref/ReferenceWrapper.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2006-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: ReferenceWrapper.scala 16894 2009-01-13 13:09:41Z cunei $
 
 package scala.ref
 
@@ -15,13 +14,12 @@ package scala.ref
  */
 trait ReferenceWrapper[+T <: AnyRef] extends Reference[T] with Proxy {
   val underlying: java.lang.ref.Reference[_ <: T]
-  @deprecated def isValid = underlying.get != null
   override def get = {
-    val ret = underlying.get.asInstanceOf[T]
+    val ret = underlying.get
     if (ret eq null) None else Some(ret)
   }
   def apply() = {
-    val ret = underlying.get.asInstanceOf[T]
+    val ret = underlying.get
     if (ret eq null) throw new NoSuchElementException
     ret
   }
@@ -31,3 +29,10 @@ trait ReferenceWrapper[+T <: AnyRef] extends Reference[T] with Proxy {
   
   def self = underlying
 }
+
+/**
+ *  @author Philipp Haller
+ */
+private trait ReferenceWithWrapper[T <: AnyRef] {
+  val wrapper: ReferenceWrapper[T]
+}
diff --git a/src/library/scala/ref/SoftReference.scala b/src/library/scala/ref/SoftReference.scala
index 9f70c32..a9beb5c 100644
--- a/src/library/scala/ref/SoftReference.scala
+++ b/src/library/scala/ref/SoftReference.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2006-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: SoftReference.scala 16894 2009-01-13 13:09:41Z cunei $
 
 package scala.ref
 
@@ -15,7 +14,12 @@ package scala.ref
  */
 class SoftReference[+T <: AnyRef](value : T, queue : ReferenceQueue[T]) extends ReferenceWrapper[T] {
   def this(value : T) = this(value, null);
-  val underlying: java.lang.ref.SoftReference[_ <: T] = 
-    if (queue == null) new java.lang.ref.SoftReference[T](value);
-    else new java.lang.ref.SoftReference[T](value, queue.underlying.asInstanceOf[java.lang.ref.ReferenceQueue[T]])
+  val underlying: java.lang.ref.SoftReference[_ <: T] =
+    new SoftReferenceWithWrapper[T](value, queue, this)
 }
+
+/**
+ *  @author Philipp Haller
+ */
+private class SoftReferenceWithWrapper[T <: AnyRef](value: T, queue: ReferenceQueue[T], val wrapper: SoftReference[T])
+  extends java.lang.ref.SoftReference[T](value, if (queue == null) null else queue.underlying.asInstanceOf[java.lang.ref.ReferenceQueue[T]]) with ReferenceWithWrapper[T]
diff --git a/src/library/scala/ref/WeakReference.scala b/src/library/scala/ref/WeakReference.scala
index 4e67b1b..fe9491d 100644
--- a/src/library/scala/ref/WeakReference.scala
+++ b/src/library/scala/ref/WeakReference.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2006-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: WeakReference.scala 16894 2009-01-13 13:09:41Z cunei $
 
 package scala.ref
 
@@ -16,6 +15,11 @@ package scala.ref
 class WeakReference[+T <: AnyRef](value: T, queue: ReferenceQueue[T]) extends ReferenceWrapper[T] {
   def this(value: T) = this(value, null)
   val underlying: java.lang.ref.WeakReference[_ <: T] = 
-    if (queue == null) new java.lang.ref.WeakReference[T](value)
-    else new java.lang.ref.WeakReference[T](value, queue.underlying.asInstanceOf[java.lang.ref.ReferenceQueue[T]])
+    new WeakReferenceWithWrapper[T](value, queue, this)
 }
+
+/**
+ *  @author Philipp Haller
+ */
+private class WeakReferenceWithWrapper[T <: AnyRef](value: T, queue: ReferenceQueue[T], val wrapper: WeakReference[T])
+  extends java.lang.ref.WeakReference[T](value, if (queue == null) null else queue.underlying.asInstanceOf[java.lang.ref.ReferenceQueue[T]]) with ReferenceWithWrapper[T]
diff --git a/src/library/scala/reflect/BeanDescription.scala b/src/library/scala/reflect/BeanDescription.scala
index 6eebbfe..fde6a92 100644
--- a/src/library/scala/reflect/BeanDescription.scala
+++ b/src/library/scala/reflect/BeanDescription.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: BeanDescription.scala 16881 2009-01-09 16:28:11Z cunei $
 
 package scala.reflect
 
diff --git a/src/library/scala/reflect/BeanDisplayName.scala b/src/library/scala/reflect/BeanDisplayName.scala
index e261fc5..629e3da 100644
--- a/src/library/scala/reflect/BeanDisplayName.scala
+++ b/src/library/scala/reflect/BeanDisplayName.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: BeanDisplayName.scala 16881 2009-01-09 16:28:11Z cunei $
 
 package scala.reflect
 
diff --git a/src/library/scala/reflect/BeanInfo.scala b/src/library/scala/reflect/BeanInfo.scala
index 311f165..4b5403c 100644
--- a/src/library/scala/reflect/BeanInfo.scala
+++ b/src/library/scala/reflect/BeanInfo.scala
@@ -1,18 +1,17 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: BeanInfo.scala 16881 2009-01-09 16:28:11Z cunei $
 
 package scala.reflect
 
 /** <p>
- *    This attribute indicates that a JavaBean-compliant BeanInfo
- *    class should be generated for this attributed Scala class. 
+ *    This annotation indicates that a JavaBean-compliant BeanInfo
+ *    class should be generated for this annotated Scala class. 
  *    A val becomes a read-only property. A var becomes a read-write
  *    property. A def becomes a method. 
  *  </p>
diff --git a/src/library/scala/reflect/BeanInfoSkip.scala b/src/library/scala/reflect/BeanInfoSkip.scala
index a6ca1fd..56654c9 100644
--- a/src/library/scala/reflect/BeanInfoSkip.scala
+++ b/src/library/scala/reflect/BeanInfoSkip.scala
@@ -1,16 +1,15 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: BeanInfoSkip.scala 16881 2009-01-09 16:28:11Z cunei $
 
 package scala.reflect
 
-/** This attribute indicates that bean information should
+/** This annotation indicates that bean information should
  *  <strong>not</strong> be generated for the val, var, or def that it is
  *  attached to.  
  *
diff --git a/src/library/scala/reflect/BeanProperty.scala b/src/library/scala/reflect/BeanProperty.scala
index 9823784..d784774 100644
--- a/src/library/scala/reflect/BeanProperty.scala
+++ b/src/library/scala/reflect/BeanProperty.scala
@@ -1,33 +1,34 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: BeanProperty.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala.reflect
 
+import annotation.target._
+
 /** <p>
- *    This attribute adds a setter and a getter method, following the
- *    Java Bean convention (first letter of the property is capitalized)
- *    used by popular Java web frameworks. For example:
+ *    When attached to a field, this annotation adds a setter and a getter
+ *    method following the  Java Bean convention. For example:
  *  </p><pre>
  *    @BeanProperty
  *    <b>var</b> status = ""</pre>
  *  <p>
- *    adds the following methods to the <b>generated</b> code
+ *    adds the following methods to the class:
  *  </p><pre>
  *    <b>def</b> setStatus(s: String) { <b>this</b>.status = s }
  *    <b>def</b> getStatus: String = <b>this</b>.status
  *  </pre>
  *  <p>
- *    However, you cannot call <code>setStatus</code> from
- *    <a href="http://scala-lang.org/" target="_top">Scala</a>,
- *    you should use the normal Scala access and assignment.
+ *    For fields of type <code>Boolean</code>, if you need a getter
+ *    named <code>isStatus</code>, use the
+ *    <code>scala.reflect.BooleanBeanProperty</code> annotation instead.
  *  </p>
  */
+ at field
 class BeanProperty extends StaticAnnotation
diff --git a/src/library/scala/reflect/BooleanBeanProperty.scala b/src/library/scala/reflect/BooleanBeanProperty.scala
new file mode 100644
index 0000000..f90f11f
--- /dev/null
+++ b/src/library/scala/reflect/BooleanBeanProperty.scala
@@ -0,0 +1,23 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.reflect
+
+import annotation.target._
+
+/** <p>
+ *    This annotation has the same functionality as
+ *    <code>scala.reflect.BeanProperty</code>, but the generated
+ *    Bean getter will be named <code>isFieldName</code> instead
+ *    of <code>getFieldName</code>.
+ *  </p>
+ */
+ at field
+class BooleanBeanProperty extends StaticAnnotation
diff --git a/src/library/scala/reflect/ClassManifest.scala b/src/library/scala/reflect/ClassManifest.scala
new file mode 100644
index 0000000..3b05a58
--- /dev/null
+++ b/src/library/scala/reflect/ClassManifest.scala
@@ -0,0 +1,232 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.reflect
+
+import scala.runtime._
+import scala.collection.immutable.{List, Nil}
+import scala.collection.mutable.{WrappedArray, ArrayBuilder}
+
+/** <p>
+  *   A <code>ClassManifest[T]</code> is an opaque descriptor for type <code>T</code>.
+  *   Currently, its only use is to give access to the erasure of the type as a
+  *   <code>Class</code> instance.
+  * </p>
+  * <p>
+  *   <b>BE AWARE</b>: The different type-relation operators are all forwarded 
+  *   to the erased type as an approximation of the final semantics where
+  *   these operators should be on the unerased type.
+  * </p>
+  */
+ at serializable
+trait ClassManifest[T] extends OptManifest[T] with Equals {
+
+  /** A class representing the type U to which T would be erased. Note
+    * that there is no subtyping relationship between T and U. */
+  def erasure: Predef.Class[_]
+
+  /** Tests whether the type represented by this manifest is a subtype of
+    * the type represented by `that' manifest. BE AWARE: the current
+    * implementation is an approximation, as the test is done on the
+    * erasure of the type. */
+  def <:<(that: ClassManifest[_]): Boolean = {
+    def subtype(sub: Predef.Class[_], sup: Predef.Class[_]): Boolean = {
+      val subSuperClass = sub.getSuperclass
+      val subSuperInterfaces = sub.getInterfaces.toList
+      val subSuper =
+        (if (subSuperClass == null) Nil else List(subSuperClass)) ::: subSuperInterfaces
+      (subSuper contains sup) || (subSuper exists (subtype(_, sup)))
+    }
+    def subargs(args1: List[OptManifest[_]], args2: List[OptManifest[_]]): Boolean = {
+      (args1 zip args2) forall { 
+        case (x: ClassManifest[_], y: ClassManifest[_]) => x <:< y // !!! [Martin] this is wrong, need to take variance into account
+        case (NoManifest, NoManifest) => true
+        case _ => false
+      }
+    }
+    
+    import Manifest.{ AnyVal, Nothing, Null }
+    
+    that match {
+      // All types which conform to AnyVal will override <:<.
+      case _: AnyValManifest[_]     => false
+      // Anything which conforms to a bottom type will override <:<.
+      case AnyVal | Nothing | Null  => false
+      case _  =>
+        (this.erasure == that.erasure || subtype(this.erasure, that.erasure)) &&
+        subargs(this.typeArguments, that.typeArguments)
+    }
+  }
+  
+  /** Tests whether the type represented by this manifest is a supertype 
+    * of the type represented by `that' manifest. BE AWARE: the current
+    * implementation is an approximation, as the test is done on the
+    * erasure of the type. */
+  def >:>(that: ClassManifest[_]): Boolean =
+    that <:< this
+  
+  def canEqual(other: Any) = other match {
+    case _: ClassManifest[_]  => true
+    case _                    => false
+  }
+ 
+  /** Tests whether the type represented by this manifest is equal to the
+    * type represented by `that' manifest. BE AWARE: the current
+    * implementation is an approximation, as the test is done on the
+    * erasure of the type. */
+  override def equals(that: Any): Boolean = that match {
+    case m: ClassManifest[_] if m canEqual this => this.erasure == m.erasure
+    case _ => false
+  }
+  override def hashCode = this.erasure.##
+
+  protected def arrayClass[T](tp: Predef.Class[_]): Predef.Class[Array[T]] = 
+    java.lang.reflect.Array.newInstance(tp, 0).getClass.asInstanceOf[Predef.Class[Array[T]]]
+
+  def arrayManifest: ClassManifest[Array[T]] = 
+    ClassManifest.classType[Array[T]](arrayClass[T](erasure))
+
+  def newArray(len: Int): Array[T] =
+    java.lang.reflect.Array.newInstance(erasure, len).asInstanceOf[Array[T]]
+
+  def newArray2(len: Int): Array[Array[T]] =
+    java.lang.reflect.Array.newInstance(arrayClass[T](erasure), len)
+      .asInstanceOf[Array[Array[T]]]
+
+  def newArray3(len: Int): Array[Array[Array[T]]] =
+    java.lang.reflect.Array.newInstance(arrayClass[Array[T]](arrayClass[T](erasure)), len)
+      .asInstanceOf[Array[Array[Array[T]]]]
+
+  def newArray4(len: Int): Array[Array[Array[Array[T]]]] =
+    java.lang.reflect.Array.newInstance(arrayClass[Array[Array[T]]](arrayClass[Array[T]](arrayClass[T](erasure))), len)
+      .asInstanceOf[Array[Array[Array[Array[T]]]]]
+
+  def newArray5(len: Int): Array[Array[Array[Array[Array[T]]]]] =
+    java.lang.reflect.Array.newInstance(arrayClass[Array[Array[Array[T]]]](arrayClass[Array[Array[T]]](arrayClass[Array[T]](arrayClass[T](erasure)))), len)
+      .asInstanceOf[Array[Array[Array[Array[Array[T]]]]]]
+
+  def newWrappedArray(len: Int): WrappedArray[T] =
+    // it's safe to assume T <: AnyRef here because the method is overridden for all value type manifests
+    new WrappedArray.ofRef[T with AnyRef](newArray(len).asInstanceOf[Array[T with AnyRef]]).asInstanceOf[WrappedArray[T]]
+  
+  def newArrayBuilder(): ArrayBuilder[T] = 
+    // it's safe to assume T <: AnyRef here because the method is overridden for all value type manifests
+    new ArrayBuilder.ofRef[T with AnyRef]()(this.asInstanceOf[ClassManifest[T with AnyRef]]).asInstanceOf[ArrayBuilder[T]]
+  
+  def typeArguments: List[OptManifest[_]] = List()
+
+  protected def argString = 
+    if (typeArguments.nonEmpty) typeArguments.mkString("[", ", ", "]")
+    else if (erasure.isArray) "["+ClassManifest.fromClass(erasure.getComponentType)+"]"
+    else ""
+}
+
+/** <p>
+  *   This object is used by the compiler and <b>should not be used in client
+  *   code</b>. The object <code>Manifest</code> defines factory methods for
+  *   manifests.
+  * </p>
+  * <p>
+  *   <b>BE AWARE</b>: The factory for refinement types is missing and
+  *   will be implemented in a later version of this class.
+  * </p>
+  */
+object ClassManifest {
+
+  val Byte = Manifest.Byte
+  val Short = Manifest.Short
+  val Char = Manifest.Char
+  val Int = Manifest.Int
+  val Long = Manifest.Long
+  val Float = Manifest.Float
+  val Double = Manifest.Double
+  val Boolean = Manifest.Boolean
+  val Unit = Manifest.Unit
+  val Any = Manifest.Any
+  val Object = Manifest.Object
+  val AnyVal = Manifest.AnyVal
+  val Nothing = Manifest.Nothing
+  val Null = Manifest.Null
+
+  def fromClass[T](clazz: Predef.Class[T]): ClassManifest[T] = clazz match {
+    case java.lang.Byte.TYPE => Byte.asInstanceOf[ClassManifest[T]]
+    case java.lang.Short.TYPE => Short.asInstanceOf[ClassManifest[T]]
+    case java.lang.Character.TYPE => Char.asInstanceOf[ClassManifest[T]]
+    case java.lang.Integer.TYPE => Int.asInstanceOf[ClassManifest[T]]
+    case java.lang.Long.TYPE => Long.asInstanceOf[ClassManifest[T]]
+    case java.lang.Float.TYPE => Float.asInstanceOf[ClassManifest[T]]
+    case java.lang.Double.TYPE => Double.asInstanceOf[ClassManifest[T]]
+    case java.lang.Boolean.TYPE => Boolean.asInstanceOf[ClassManifest[T]]
+    case java.lang.Void.TYPE => Unit.asInstanceOf[ClassManifest[T]]
+    case _ => classType[T with AnyRef](clazz).asInstanceOf[ClassManifest[T]]
+  }
+
+  def singleType[T <: AnyRef](value: AnyRef): Manifest[T] = Manifest.singleType(value)
+
+  /** ClassManifest for the class type `clazz', where `clazz' is
+    * a top-level or static class.
+    * @note This no-prefix, no-arguments case is separate because we
+    *       it's called from ScalaRunTime.boxArray itself. If we
+    *       pass varargs as arrays into this, we get an infinitely recursive call
+    *       to boxArray. (Besides, having a separate case is more efficient)
+    */
+  def classType[T <: AnyRef](clazz: Predef.Class[_]): ClassManifest[T] =
+    new ClassTypeManifest[T](None, clazz, Nil)
+
+  /** ClassManifest for the class type `clazz[args]', where `clazz' is
+    * a top-level or static class and `args` are its type arguments */
+  def classType[T <: AnyRef](clazz: Predef.Class[_], arg1: OptManifest[_], args: OptManifest[_]*): ClassManifest[T] =
+    new ClassTypeManifest[T](None, clazz, arg1 :: args.toList)
+
+  /** ClassManifest for the class type `clazz[args]', where `clazz' is
+    * a class with non-package prefix type `prefix` and type arguments `args`.
+    */
+  def classType[T <: AnyRef](prefix: OptManifest[_], clazz: Predef.Class[_], args: OptManifest[_]*): ClassManifest[T] =
+    new ClassTypeManifest[T](Some(prefix), clazz, args.toList)
+
+  /** Manifest for the class type `clazz[args]', where `clazz' is
+    * a top-level or static class. */
+  @serializable
+  private class ClassTypeManifest[T <: AnyRef](prefix: Option[OptManifest[_]], 
+                                               val erasure: Predef.Class[_], 
+                                               override val typeArguments: List[OptManifest[_]]) extends ClassManifest[T] {
+    override def toString = 
+      (if (prefix.isEmpty) "" else prefix.get.toString+"#") + 
+      (if (erasure.isArray) "Array" else erasure.getName) +
+      argString
+   }
+
+  def arrayType[T](arg: OptManifest[_]): ClassManifest[Array[T]] = arg match {
+    case NoManifest => Object.asInstanceOf[ClassManifest[Array[T]]]
+    case m: ClassManifest[_] => m.asInstanceOf[ClassManifest[T]].arrayManifest
+  }
+  
+  /** ClassManifest for the abstract type `prefix # name'. `upperBound' is not
+    * strictly necessary as it could be obtained by reflection. It was
+    * added so that erasure can be calculated without reflection. */
+  def abstractType[T](prefix: OptManifest[_], name: String, clazz: Predef.Class[_], args: OptManifest[_]*): ClassManifest[T] =
+    new (ClassManifest[T] @serializable) {
+      def erasure = clazz
+      override val typeArguments = args.toList
+      override def toString = prefix.toString+"#"+name+argString
+    }
+
+  /** ClassManifest for the abstract type `prefix # name'. `upperBound' is not
+    * strictly necessary as it could be obtained by reflection. It was
+    * added so that erasure can be calculated without reflection.
+    * todo: remove after next boostrap
+    */
+  def abstractType[T](prefix: OptManifest[_], name: String, upperbound: ClassManifest[_], args: OptManifest[_]*): ClassManifest[T] =
+    new (ClassManifest[T] @serializable) {
+      def erasure = upperbound.erasure
+      override val typeArguments = args.toList
+      override def toString = prefix.toString+"#"+name+argString
+    }
+}
diff --git a/src/library/scala/reflect/Code.scala b/src/library/scala/reflect/Code.scala
index b6a9e21..36537ba 100644
--- a/src/library/scala/reflect/Code.scala
+++ b/src/library/scala/reflect/Code.scala
@@ -1,20 +1,17 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Code.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala.reflect
 
-import Predef.Error
-
 /** This type is required by the compiler and <b>should not be used in client code</b>. */
-class Code[Type](val tree: Tree)
+class Code[T](val tree: Tree)
 
 /** This type is required by the compiler and <b>should not be used in client code</b>. */
 object Code {
diff --git a/src/library/scala/reflect/Manifest.scala b/src/library/scala/reflect/Manifest.scala
index c60c71f..a042b20 100644
--- a/src/library/scala/reflect/Manifest.scala
+++ b/src/library/scala/reflect/Manifest.scala
@@ -1,16 +1,19 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2007-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Manifest.scala 16625 2008-11-25 16:04:12Z michelou $
 
 
 package scala.reflect
 
+import scala.runtime._
+import scala.collection.mutable._
+import scala.collection.immutable.{List, Nil}
+
 /** <p>
   *   A <code>Manifest[T]</code> is an opaque descriptor for type <code>T</code>.
   *   Currently, its only use is to give access to the erasure of the type as a
@@ -23,46 +26,36 @@ package scala.reflect
   * </p>
   */
 @serializable
-trait Manifest[T] {
-
-  /** A class representing the type U to which T would be erased. Note
-    * that there is no subtyping relationship between T and U. */
-  def erasure: Predef.Class[U] forSome { type U }
-
-  /** Tests whether the type represented by this manifest is a subtype of
-    * the type represented by `that' manifest. BE AWARE: the current
-    * implementation is an approximation, as the test is done on the
-    * erasure of the type. */
-  def <:<(that: Manifest[_]): Boolean = {
-    def subtype(sub: Predef.Class[_], sup: Predef.Class[_]): Boolean = {
-      val subSuperClass = sub.getSuperclass
-      val subSuperInterfaces = sub.getInterfaces.toList
-      val subSuper =
-        (if (subSuperClass == null) Nil else List(subSuperClass)) ::: subSuperInterfaces
-      (subSuper contains sup) || (subSuper exists (subtype(_, sup)))
-    }
-    this.erasure == that.erasure || subtype(this.erasure, that.erasure)
-  }
-  
-  /** Tests whether the type represented by this manifest is a supertype 
-    * of the type represented by `that' manifest. BE AWARE: the current
-    * implementation is an approximation, as the test is done on the
-    * erasure of the type. */
-  def >:>(that: Manifest[_]): Boolean =
-    that <:< this
-    
-  /** Tests whether the type represented by this manifest is equal to the
-    * type represented by `that' manifest. BE AWARE: the current
-    * implementation is an approximation, as the test is done on the
-    * erasure of the type. */
+trait Manifest[T] extends ClassManifest[T] with Equals {
+  override def typeArguments: List[Manifest[_]] = List()
+
+  override def arrayManifest: Manifest[Array[T]] = 
+    Manifest.classType[Array[T]](arrayClass[T](erasure))
+
+  override def canEqual(that: Any): Boolean = that match {
+    case _: Manifest[_]   => true
+    case _                => false
+  }
   override def equals(that: Any): Boolean = that match {
-    case m:Manifest[_] => this.erasure == m.erasure
-    case _ => false
+    case m: Manifest[_] if m canEqual this  => (this <:< m) && (m <:< this)
+    case _                                  => false
   }
-    
+  override def hashCode = this.erasure.##  
 }
 
-/** <p>
+ at serializable
+trait AnyValManifest[T] extends Manifest[T] with Equals {
+  import Manifest.{ Any, AnyVal }
+  override def <:<(that: ClassManifest[_]): Boolean = (that eq this) || (that eq Any) || (that eq AnyVal)
+  override def canEqual(other: Any) = other match {
+    case _: AnyValManifest[_] => true
+    case _                    => false
+  }
+  override def equals(that: Any): Boolean = this eq that.asInstanceOf[AnyRef]
+  override def hashCode = System.identityHashCode(this)
+}
+
+/** <ps>
   *   This object is used by the compiler and <b>should not be used in client
   *   code</b>. The object <code>Manifest</code> defines factory methods for
   *   manifests.
@@ -73,85 +66,199 @@ trait Manifest[T] {
   * </p>
   */
 object Manifest {
+  val Byte: AnyValManifest[Byte] = new (AnyValManifest[Byte] @serializable) {
+    def erasure = java.lang.Byte.TYPE
+    override def toString = "Byte"
+    override def newArray(len: Int): Array[Byte] = new Array[Byte](len)
+    override def newWrappedArray(len: Int): WrappedArray[Byte] = new WrappedArray.ofByte(new Array[Byte](len))
+    override def newArrayBuilder(): ArrayBuilder[Byte] = new ArrayBuilder.ofByte()
+    private def readResolve(): Any = Manifest.Byte
+  }
+
+  val Short: AnyValManifest[Short] = new (AnyValManifest[Short] @serializable) {
+    def erasure = java.lang.Short.TYPE
+    override def toString = "Short"
+    override def newArray(len: Int): Array[Short] = new Array[Short](len)
+    override def newWrappedArray(len: Int): WrappedArray[Short] = new WrappedArray.ofShort(new Array[Short](len))
+    override def newArrayBuilder(): ArrayBuilder[Short] = new ArrayBuilder.ofShort()
+    private def readResolve(): Any = Manifest.Short
+  }
+
+  val Char: AnyValManifest[Char] = new (AnyValManifest[Char] @serializable) {
+    def erasure = java.lang.Character.TYPE
+    override def toString = "Char"
+    override def newArray(len: Int): Array[Char] = new Array[Char](len)
+    override def newWrappedArray(len: Int): WrappedArray[Char] = new WrappedArray.ofChar(new Array[Char](len))
+    override def newArrayBuilder(): ArrayBuilder[Char] = new ArrayBuilder.ofChar()
+    private def readResolve(): Any = Manifest.Char
+  }
+
+  val Int: AnyValManifest[Int] = new (AnyValManifest[Int] @serializable) {
+    def erasure = java.lang.Integer.TYPE
+    override def toString = "Int"
+    override def newArray(len: Int): Array[Int] = new Array[Int](len)
+    override def newWrappedArray(len: Int): WrappedArray[Int] = new WrappedArray.ofInt(new Array[Int](len))
+    override def newArrayBuilder(): ArrayBuilder[Int] = new ArrayBuilder.ofInt()
+    private def readResolve(): Any = Manifest.Int
+  }
+
+  val Long: AnyValManifest[Long] = new (AnyValManifest[Long] @serializable) {
+    def erasure = java.lang.Long.TYPE
+    override def toString = "Long"
+    override def newArray(len: Int): Array[Long] = new Array[Long](len)
+    override def newWrappedArray(len: Int): WrappedArray[Long] = new WrappedArray.ofLong(new Array[Long](len))
+    override def newArrayBuilder(): ArrayBuilder[Long] = new ArrayBuilder.ofLong()
+    private def readResolve(): Any = Manifest.Long
+  }
+
+  val Float: AnyValManifest[Float] = new (AnyValManifest[Float] @serializable) {
+    def erasure = java.lang.Float.TYPE
+    override def toString = "Float"
+    override def newArray(len: Int): Array[Float] = new Array[Float](len)
+    override def newWrappedArray(len: Int): WrappedArray[Float] = new WrappedArray.ofFloat(new Array[Float](len))
+    override def newArrayBuilder(): ArrayBuilder[Float] = new ArrayBuilder.ofFloat()
+    private def readResolve(): Any = Manifest.Float
+  }
+
+  val Double: AnyValManifest[Double] = new (AnyValManifest[Double] @serializable) {
+    def erasure = java.lang.Double.TYPE
+    override def toString = "Double"
+    override def newArray(len: Int): Array[Double] = new Array[Double](len)
+    override def newWrappedArray(len: Int): WrappedArray[Double] = new WrappedArray.ofDouble(new Array[Double](len))
+    override def newArrayBuilder(): ArrayBuilder[Double] = new ArrayBuilder.ofDouble()
+    private def readResolve(): Any = Manifest.Double
+  }
+
+  val Boolean: AnyValManifest[Boolean] = new (AnyValManifest[Boolean] @serializable) {
+    def erasure = java.lang.Boolean.TYPE
+    override def toString = "Boolean"
+    override def newArray(len: Int): Array[Boolean] = new Array[Boolean](len)
+    override def newWrappedArray(len: Int): WrappedArray[Boolean] = new WrappedArray.ofBoolean(new Array[Boolean](len))
+    override def newArrayBuilder(): ArrayBuilder[Boolean] = new ArrayBuilder.ofBoolean()
+    private def readResolve(): Any = Manifest.Boolean
+  }
+
+  val Unit: AnyValManifest[Unit] = new (AnyValManifest[Unit] @serializable) {
+    def erasure = java.lang.Void.TYPE
+    override def toString = "Unit"
+    override def newArray(len: Int): Array[Unit] = new Array[Unit](len)
+    override def newWrappedArray(len: Int): WrappedArray[Unit] = new WrappedArray.ofUnit(new Array[Unit](len))
+    override def newArrayBuilder(): ArrayBuilder[Unit] = new ArrayBuilder.ofUnit()
+    private def readResolve(): Any = Manifest.Unit
+  }
+
+  val Any: Manifest[Any] = new ClassTypeManifest[Any](None, classOf[java.lang.Object], List()) {
+    override def toString = "Any"
+    override def <:<(that: ClassManifest[_]): Boolean = (that eq this)
+    override def equals(that: Any): Boolean = this eq that.asInstanceOf[AnyRef]
+    override def hashCode = System.identityHashCode(this)
+    private def readResolve(): Any = Manifest.Any
+  }
+
+  val Object: Manifest[Object] = new ClassTypeManifest[Object](None, classOf[java.lang.Object], List()) {
+    override def toString = "Object"
+    override def <:<(that: ClassManifest[_]): Boolean = (that eq this) || (that eq Any)
+    override def equals(that: Any): Boolean = this eq that.asInstanceOf[AnyRef]
+    override def hashCode = System.identityHashCode(this)
+    private def readResolve(): Any = Manifest.Object
+  }
+
+  val AnyVal: Manifest[AnyVal] = new ClassTypeManifest[AnyVal](None, classOf[java.lang.Object], List()) {
+    override def toString = "AnyVal"
+    override def <:<(that: ClassManifest[_]): Boolean = (that eq this) || (that eq Any)
+    override def equals(that: Any): Boolean = this eq that.asInstanceOf[AnyRef]
+    override def hashCode = System.identityHashCode(this)
+    private def readResolve(): Any = Manifest.AnyVal
+  }
+
+  val Null: Manifest[Null] = new ClassTypeManifest[Null](None, classOf[java.lang.Object], List()) {
+    override def toString = "Null"
+    override def <:<(that: ClassManifest[_]): Boolean =
+      (that ne null) && (that ne Nothing) && !(that <:< AnyVal)
+    override def equals(that: Any): Boolean = this eq that.asInstanceOf[AnyRef]
+    override def hashCode = System.identityHashCode(this)
+    private def readResolve(): Any = Manifest.Null
+  }
+
+  val Nothing: Manifest[Nothing] = new ClassTypeManifest[Nothing](None, classOf[java.lang.Object], List()) {
+    override def toString = "Nothing"
+    override def <:<(that: ClassManifest[_]): Boolean = (that ne null)
+    override def equals(that: Any): Boolean = this eq that.asInstanceOf[AnyRef]
+    override def hashCode = System.identityHashCode(this)
+    private def readResolve(): Any = Manifest.Nothing
+  }
 
   /** Manifest for the singleton type `value.type'. */
-  def singleType[T](value: Any): Manifest[T] =
+  def singleType[T <: AnyRef](value: AnyRef): Manifest[T] =
     new (Manifest[T] @serializable) {
-      lazy val erasure =
-        value match {
-          case anyRefValue: AnyRef => anyRefValue.getClass
-          case anyValue => error("There is no singleton type for AnyVal values")
-        }
+      /** Note - this was doing a type match on value to exclude AnyVal, which does not work.
+       *  Pattern matching _: AnyRef matches everything because of boxing.
+       */
+      lazy val erasure = value.getClass
       override lazy val toString = value.toString + ".type"
     }
 
+  /** Manifest for the class type `clazz[args]', where `clazz' is
+    * a top-level or static class.
+    * @note This no-prefix, no-arguments case is separate because we
+    *       it's called from ScalaRunTime.boxArray itself. If we
+    *       pass varargs as arrays into this, we get an infinitely recursive call
+    *       to boxArray. (Besides, having a separate case is more efficient)
+    */
+  def classType[T](clazz: Predef.Class[_]): Manifest[T] =
+    new ClassTypeManifest[T](None, clazz, Nil)
+
   /** Manifest for the class type `clazz', where `clazz' is
-    * a top-level or static class. */
-  def classType[T](clazz: Predef.Class[T]): Manifest[T] =
-    new (Manifest[T] @serializable) {
-      val erasure = clazz
-      override lazy val toString = erasure.getName
-    }
+    * a top-level or static class and args are its type arguments. */
+  def classType[T](clazz: Predef.Class[T], arg1: Manifest[_], args: Manifest[_]*): Manifest[T] =
+    new ClassTypeManifest[T](None, clazz, arg1 :: args.toList)
 
   /** Manifest for the class type `clazz[args]', where `clazz' is
-    * a top-level or static class. */
-  def classType[T](clazz: Predef.Class[_], args: Manifest[_]*): Manifest[T] =
-    new (Manifest[T] @serializable) {
-      val erasure = clazz
-      val typeArguments: Seq[Manifest[_]] = args
-      override def <:<(that: Manifest[_]): Boolean = {
-        try {
-          val meth = that.getClass().getMethod("typeArguments", null)
-          val args1 = meth.invoke(that, null).asInstanceOf[Array[Manifest[_]]]
-          super.<:<(that) && args.equalsWith(args1)((x, y) => x <:< y)
-        } catch {
-          case _ => false
-        }
-      }
-      override lazy val toString =
-        (if (erasure.isArray) "Array" else erasure.getName) +
-        typeArguments.mkString("[", ", ", "]")
-    }
+    * a class with non-package prefix type `prefix` and type arguments `args`.
+    */
+  def classType[T](prefix: Manifest[_], clazz: Predef.Class[_], args: Manifest[_]*): Manifest[T] =
+    new ClassTypeManifest[T](Some(prefix), clazz, args.toList)
 
-  /** Manifest for the class type `prefix # clazz'. */
-  def classType[T](prefix: Manifest[_], clazz: Predef.Class[_]): Manifest[T] =
-    new (Manifest[T] @serializable) {
-      val erasure = clazz
-      override lazy val toString = prefix.toString + "#" + erasure.getName
-    }
+  /** Manifest for the class type `clazz[args]', where `clazz' is
+    * a top-level or static class. */
+  @serializable
+  private class ClassTypeManifest[T](prefix: Option[Manifest[_]], 
+                                     val erasure: Predef.Class[_], 
+                                     override val typeArguments: List[Manifest[_]]) extends Manifest[T] {
+    override def toString = 
+      (if (prefix.isEmpty) "" else prefix.get.toString+"#") +
+      (if (erasure.isArray) "Array" else erasure.getName) +
+      argString
+   }
 
-  /** Manifest for the class type `prefix # clazz[args]'. */
-  def classType[T](prefix: Manifest[_], clazz: Predef.Class[_], args: Manifest[_]*): Manifest[T] =
-    new (Manifest[T] @serializable) {
-      val erasure = clazz
-      val typeArguments: Seq[Manifest[_]] = args
-      override lazy val toString =
-        prefix.toString + "#" + erasure.getName + typeArguments.mkString("[", ", ", "]")
-    }
+  def arrayType[T](arg: Manifest[_]): Manifest[Array[T]] = 
+    arg.asInstanceOf[Manifest[T]].arrayManifest
 
   /** Manifest for the abstract type `prefix # name'. `upperBound' is not
     * strictly necessary as it could be obtained by reflection. It was
     * added so that erasure can be calculated without reflection. */
-  def abstractType[T](prefix: Manifest[_], name: String, upperBound: Manifest[_]): Manifest[T] =
+  def abstractType[T](prefix: Manifest[_], name: String, clazz: Predef.Class[_], args: Manifest[_]*): Manifest[T] =
     new (Manifest[T] @serializable) {
-      lazy val erasure = upperBound.erasure
-      override lazy val toString = prefix.toString + "#" + name
+      def erasure = clazz
+      override val typeArguments = args.toList
+      override def toString = prefix.toString+"#"+name+argString
     }
 
-  /** Manifest for the abstract type `prefix # name[args]'. */
-  def abstractType[T](prefix: Manifest[_], name: String, upperBound: Manifest[_], args: Manifest[_]*): Manifest[T] =
+  /** Manifest for the unknown type `_ >: L <: U' in an existential.
+    */
+  def wildcardType[T](lowerBound: Manifest[_], upperBound: Manifest[_]): Manifest[T] =
     new (Manifest[T] @serializable) {
-      lazy val erasure = upperBound.erasure
-      val typeArguments: Seq[Manifest[_]] = args
-      override lazy val toString =
-        prefix.toString + "#" + name + typeArguments.mkString("[", ", ", "]")
+      def erasure = upperBound.erasure
+      override def toString = 
+        "_" +
+        (if (lowerBound eq Nothing) "" else " >: "+lowerBound) + 
+        (if (upperBound eq Nothing) "" else " <: "+upperBound)
     }
 
   /** Manifest for the intersection type `parents_0 with ... with parents_n'. */
   def intersectionType[T](parents: Manifest[_]*): Manifest[T] =
     new (Manifest[T] @serializable) {
-      lazy val erasure = parents.first.erasure
-      override lazy val toString = parents.mkString(" with ")
+      def erasure = parents.head.erasure
+      override def toString = parents.mkString(" with ")
     }
-  
 }
diff --git a/src/library/scala/reflect/NameTransformer.scala b/src/library/scala/reflect/NameTransformer.scala
new file mode 100644
index 0000000..92f4959
--- /dev/null
+++ b/src/library/scala/reflect/NameTransformer.scala
@@ -0,0 +1,154 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.reflect
+
+/**
+ *  @author  Martin Odersky
+ */
+object NameTransformer {
+  private val nops = 128
+  private val ncodes = 26 * 26
+
+  private class OpCodes(val op: Char, val code: String, val next: OpCodes)
+
+  private val op2code = new Array[String](nops)
+  private val code2op = new Array[OpCodes](ncodes)
+
+  private def enterOp(op: Char, code: String) = {
+    op2code(op) = code
+    val c = (code.charAt(1) - 'a') * 26 + code.charAt(2) - 'a'
+    code2op(c) = new OpCodes(op, code, code2op(c))
+  }
+
+  /* Note: decoding assumes opcodes are only ever lowercase. */
+  enterOp('~', "$tilde")
+  enterOp('=', "$eq")
+  enterOp('<', "$less")
+  enterOp('>', "$greater")
+  enterOp('!', "$bang")
+  enterOp('#', "$hash")
+  enterOp('%', "$percent")
+  enterOp('^', "$up")
+  enterOp('&', "$amp")
+  enterOp('|', "$bar")
+  enterOp('*', "$times")
+  enterOp('/', "$div")
+  enterOp('+', "$plus")
+  enterOp('-', "$minus")
+  enterOp(':', "$colon")
+  enterOp('\\', "$bslash")
+  enterOp('?', "$qmark")
+  enterOp('@', "$at")
+
+  /** Replace operator symbols by corresponding "<code>$op_name</code>".
+   *
+   *  @param name ...
+   *  @return     ...
+   */
+  def encode(name: String): String = {
+    var buf: StringBuilder = null
+    val len = name.length()
+    var i = 0
+    while (i < len) {
+      val c = name charAt i
+      if (c < nops && (op2code(c) ne null)) {
+        if (buf eq null) {
+          buf = new StringBuilder()
+          buf.append(name.substring(0, i))
+        }
+        buf.append(op2code(c))
+      /* Handle glyphs that are not valid Java/JVM identifiers */
+      } 
+      else if (!Character.isJavaIdentifierPart(c)) {
+        if (buf eq null) {
+          buf = new StringBuilder()
+          buf.append(name.substring(0, i))
+        }
+        buf.append("$u%04X".format(c.toInt))
+      }
+      else if (buf ne null) {
+        buf.append(c)
+      }
+      i += 1
+    }
+    if (buf eq null) name else buf.toString()
+  }
+
+  /** Replace <code>$op_name</code> by corresponding operator symbol.
+   *
+   *  @param name0 ...
+   *  @return      ...
+   */
+  def decode(name0: String): String = {
+    //System.out.println("decode: " + name);//DEBUG
+    val name = if (name0.endsWith("<init>")) name0.substring(0, name0.length() - ("<init>").length()) + "this"
+               else name0;
+    var buf: StringBuilder = null
+    val len = name.length()
+    var i = 0
+    while (i < len) {
+      var ops: OpCodes = null
+      var unicode = false
+      val c = name charAt i
+      if (c == '$' && i + 2 < len) {
+        val ch1 = name.charAt(i+1)
+        if ('a' <= ch1 && ch1 <= 'z') {
+          val ch2 = name.charAt(i+2)
+          if ('a' <= ch2 && ch2 <= 'z') {
+            ops = code2op((ch1 - 'a') * 26 + ch2 - 'a')
+            while ((ops ne null) && !name.startsWith(ops.code, i)) ops = ops.next
+            if (ops ne null) {
+              if (buf eq null) {
+                buf = new StringBuilder()
+                buf.append(name.substring(0, i))
+              }
+              buf.append(ops.op)
+              i += ops.code.length()
+            }
+            /* Handle the decoding of Unicode glyphs that are 
+             * not valid Java/JVM identifiers */
+          } else if ((len - i) >= 6 && // Check that there are enough characters left
+                     ch1 == 'u' && 
+                     ((Character.isDigit(ch2)) || 
+                     ('A' <= ch2 && ch2 <= 'F'))) {
+            /* Skip past "$u", next four should be hexadecimal */
+            val hex = name.substring(i+2, i+6)
+            try {
+              val str = Integer.parseInt(hex, 16).toChar
+              if (buf eq null) {
+                buf = new StringBuilder()
+                buf.append(name.substring(0, i))
+              }
+              buf.append(str)
+              /* 2 for "$u", 4 for hexadecimal number */
+              i += 6
+              unicode = true
+            } catch {
+              case _:NumberFormatException =>
+                /* <code>hex</code> did not decode to a hexadecimal number, so
+                 * do nothing. */
+            }
+                       }
+        }
+      }
+      /* If we didn't see an opcode or encoded Unicode glyph, and the
+        buffer is non-empty, write the current character and advance
+         one */ 
+      if ((ops eq null) && !unicode) { 
+        if (buf ne null)
+          buf.append(c) 
+        i += 1 
+      } 
+    }
+    //System.out.println("= " + (if (buf == null) name else buf.toString()));//DEBUG
+    if (buf eq null) name else buf.toString()
+  }
+}
diff --git a/src/library/scala/reflect/NoManifest.scala b/src/library/scala/reflect/NoManifest.scala
new file mode 100644
index 0000000..d0497d4
--- /dev/null
+++ b/src/library/scala/reflect/NoManifest.scala
@@ -0,0 +1,18 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.reflect
+
+/** <p> One of the branches of an OptManifest
+  */
+ at serializable
+object NoManifest extends OptManifest[Nothing] {
+  override def toString = "<?>"
+}
diff --git a/src/library/scala/reflect/OptManifest.scala b/src/library/scala/reflect/OptManifest.scala
new file mode 100644
index 0000000..a4d8f54
--- /dev/null
+++ b/src/library/scala/reflect/OptManifest.scala
@@ -0,0 +1,22 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.reflect
+
+/** <p>
+ *    A <code>OptManifest[T]</code> is an optional <a href="Manifest.html"
+ *    target="ContentFrame"><code>Manifest</code></a>.<br/>
+ *    It is either a <code>Manifest</code> or the value <code>NoManifest</code>.
+ *  </p>
+ *
+ *  @author Martin Odersky
+ */
+ at serializable
+trait OptManifest[+T] 
diff --git a/src/library/scala/reflect/Print.scala b/src/library/scala/reflect/Print.scala
index 49d878e..adf3860 100644
--- a/src/library/scala/reflect/Print.scala
+++ b/src/library/scala/reflect/Print.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Print.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala.reflect
@@ -16,7 +15,7 @@ object Print extends Function1[Any, String] {
 
   def apply(any: Any): String = any match {
     case x: Code[_] =>
-      apply(x)
+      apply(x.tree)
     case x: Tree =>
       apply(x)
     case x: Symbol =>
@@ -27,9 +26,6 @@ object Print extends Function1[Any, String] {
       "UnknownAny"
   }
 
-  def apply[A](code: Code[A]): String =
-    Print(code.tree)
-
   def apply(tree: Tree): String = tree match {
     case reflect.Ident(sym) =>
       Print(sym)
@@ -106,9 +102,8 @@ object Print extends Function1[Any, String] {
     case reflect.MethodType(formals, resultType) =>
       formals.map(Print).mkString("(", ", ", ")") + " => " + Print(resultType)
     case reflect.PolyType(typeParams, typeBounds, resultType) =>
-      (List.map2(typeParams, typeBounds)
-        ((tp, tb) => "[" + Print(tb._1) + " :> " + Print(tp) + " :> " + Print(tb._2) + "]")).
-          mkString("[", ", ", "]") + " -> " + Print(resultType)
+      val z = (typeParams, typeBounds).zip map { case (tp, tb) => "[" + Print(tb._1) + " :> " + Print(tp) + " :> " + Print(tb._2) + "]" }
+      z.mkString("[", ", ", "]") + " -> " + Print(resultType)
     case _ =>
       "???"
   }
diff --git a/src/library/scala/reflect/ScalaBeanInfo.scala b/src/library/scala/reflect/ScalaBeanInfo.scala
index c22ee2f..96a62d1 100644
--- a/src/library/scala/reflect/ScalaBeanInfo.scala
+++ b/src/library/scala/reflect/ScalaBeanInfo.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: ScalaBeanInfo.scala 16881 2009-01-09 16:28:11Z cunei $
 
 package scala.reflect
 
diff --git a/src/library/scala/reflect/ScalaLongSignature.java b/src/library/scala/reflect/ScalaLongSignature.java
new file mode 100644
index 0000000..1ffd6d2
--- /dev/null
+++ b/src/library/scala/reflect/ScalaLongSignature.java
@@ -0,0 +1,13 @@
+package scala.reflect;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**  */
+ at Retention(RetentionPolicy.RUNTIME)
+ at Target(ElementType.TYPE)
+public @interface ScalaLongSignature {
+    public String[] bytes();
+}
diff --git a/src/library/scala/reflect/ScalaSignature.java b/src/library/scala/reflect/ScalaSignature.java
new file mode 100644
index 0000000..d1cdbc0
--- /dev/null
+++ b/src/library/scala/reflect/ScalaSignature.java
@@ -0,0 +1,13 @@
+package scala.reflect;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**  */
+ at Retention(RetentionPolicy.RUNTIME)
+ at Target(ElementType.TYPE)
+public @interface ScalaSignature {
+    public String bytes();
+}
diff --git a/src/library/scala/reflect/Symbol.scala b/src/library/scala/reflect/Symbol.scala
index 8df7126..6cc8f0c 100644
--- a/src/library/scala/reflect/Symbol.scala
+++ b/src/library/scala/reflect/Symbol.scala
@@ -1,18 +1,15 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Symbol.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala.reflect
 
-import Predef._
-
 /** This type is required by the compiler and <b>should not be used in client code</b>. */
 abstract class Symbol {
   val owner: Symbol
diff --git a/src/library/scala/reflect/Tree.scala b/src/library/scala/reflect/Tree.scala
index 13408b8..ff7fc73 100644
--- a/src/library/scala/reflect/Tree.scala
+++ b/src/library/scala/reflect/Tree.scala
@@ -1,16 +1,17 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Tree.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala.reflect
 
+import collection.immutable.{List, Nil}
+
 /** This type is required by the compiler and <b>should not be used in client code</b>. */
 abstract class Tree
 
diff --git a/src/library/scala/reflect/Type.scala b/src/library/scala/reflect/Type.scala
index 7ca637b..f8f3bae 100644
--- a/src/library/scala/reflect/Type.scala
+++ b/src/library/scala/reflect/Type.scala
@@ -1,17 +1,16 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Type.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala.reflect
 
-import Predef._
+import collection.immutable.List
 
 /** This type is required by the compiler and <b>should not be used in client code</b>. */
 abstract class Type
@@ -48,7 +47,7 @@ case class TypeBounds(lo: Type, hi: Type) extends Type
 
 /** This type is required by the compiler and <b>should not be used in client code</b>.
   * <code>(formals1 ... formalsn) restpe</code> */
-case class MethodType(formals: List[Type], restpe: Type) extends Type
+case class MethodType(formals: List[Symbol], restpe: Type) extends Type
 
 
 /** This type is required by the compiler and <b>should not be used in client code</b>. */
@@ -56,7 +55,7 @@ case class PolyType(typeParams: List[Symbol], typeBounds: List[(Type, Type)], re
 
 
 /** This type is required by the compiler and <b>should not be used in client code</b>. */
-class ImplicitMethodType(formals: List[Type], restpe: Type)
+class ImplicitMethodType(formals: List[Symbol], restpe: Type)
 extends MethodType(formals, restpe)
 
 
diff --git a/src/library/scala/reflect/generic/AnnotationInfos.scala b/src/library/scala/reflect/generic/AnnotationInfos.scala
new file mode 100644
index 0000000..f668908
--- /dev/null
+++ b/src/library/scala/reflect/generic/AnnotationInfos.scala
@@ -0,0 +1,42 @@
+package scala.reflect
+package generic
+
+trait AnnotationInfos { self: Universe =>
+
+  type AnnotationInfo <: AnyRef
+  val AnnotationInfo: AnnotationInfoExtractor
+
+  abstract class AnnotationInfoExtractor {
+    def apply(atp: Type, args: List[Tree], assocs: List[(Name, ClassfileAnnotArg)]): AnnotationInfo
+    def unapply(info: AnnotationInfo): Option[(Type, List[Tree], List[(Name, ClassfileAnnotArg)])]
+  }
+
+  type ClassfileAnnotArg <: AnyRef
+  implicit def classfileAnnotArgManifest: ClassManifest[ClassfileAnnotArg] // need a precise manifest to pass to UnPickle's toArray call
+
+  type LiteralAnnotArg <: ClassfileAnnotArg
+  val LiteralAnnotArg: LiteralAnnotArgExtractor
+
+  type ArrayAnnotArg <: ClassfileAnnotArg
+  val ArrayAnnotArg: ArrayAnnotArgExtractor
+
+  type NestedAnnotArg <: ClassfileAnnotArg
+  val NestedAnnotArg: NestedAnnotArgExtractor
+
+  abstract class LiteralAnnotArgExtractor {
+    def apply(const: Constant): LiteralAnnotArg
+    def unapply(arg: LiteralAnnotArg): Option[Constant]
+  }
+
+  abstract class ArrayAnnotArgExtractor {
+    def apply(const: Array[ClassfileAnnotArg]): ArrayAnnotArg
+    def unapply(arg: ArrayAnnotArg): Option[Array[ClassfileAnnotArg]]
+  }
+
+  abstract class NestedAnnotArgExtractor {
+    def apply(anninfo: AnnotationInfo): NestedAnnotArg
+    def unapply(arg: NestedAnnotArg): Option[AnnotationInfo]
+  }
+}
+  
+  
diff --git a/src/library/scala/reflect/generic/ByteCodecs.scala b/src/library/scala/reflect/generic/ByteCodecs.scala
new file mode 100644
index 0000000..278bd88
--- /dev/null
+++ b/src/library/scala/reflect/generic/ByteCodecs.scala
@@ -0,0 +1,224 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+package scala.reflect.generic
+
+object ByteCodecs { 
+
+  def avoidZero(src: Array[Byte]): Array[Byte] = {
+    var i = 0
+    val srclen = src.length
+    var count = 0
+    while (i < srclen) {
+      if (src(i) == 0x7f) count += 1
+      i += 1
+    }
+    val dst = new Array[Byte](srclen + count)
+    i = 0
+    var j = 0
+    while (i < srclen) {
+      val in = src(i)
+      if (in == 0x7f) {
+        dst(j) = (0xc0).toByte
+        dst(j + 1) = (0x80).toByte
+        j += 2
+      } else {
+        dst(j) = (in + 1).toByte
+        j += 1
+      }
+      i += 1
+    }
+    dst
+  }
+
+  def regenerateZero(src: Array[Byte]): Int = {
+    var i = 0
+    val srclen = src.length
+    var j = 0
+    while (i < srclen) {
+      val in: Int = src(i) & 0xff
+      if (in == 0xc0 && (src(i + 1) & 0xff) == 0x80) {
+        src(j) = 0x7f
+        i += 2
+      } else {
+        src(j) = (in - 1).toByte
+        i += 1
+      }
+      j += 1
+    }
+    j
+  }
+
+  def encode8to7(src: Array[Byte]): Array[Byte] = {
+    val srclen = src.length
+    val dstlen = (srclen * 8 + 6) / 7
+    val dst = new Array[Byte](dstlen)
+    var i = 0
+    var j = 0
+    while (i + 6 < srclen) {
+      var in: Int = src(i) & 0xff
+      dst(j) = (in & 0x7f).toByte
+      var out: Int = in >>> 7
+      in = src(i + 1) & 0xff
+      dst(j + 1) = (out | (in << 1) & 0x7f).toByte
+      out = in >>> 6
+      in = src(i + 2) & 0xff
+      dst(j + 2) = (out | (in << 2) & 0x7f).toByte
+      out = in >>> 5
+      in = src(i + 3) & 0xff
+      dst(j + 3) = (out | (in << 3) & 0x7f).toByte
+      out = in >>> 4
+      in = src(i + 4) & 0xff
+      dst(j + 4) = (out | (in << 4) & 0x7f).toByte
+      out = in >>> 3
+      in = src(i + 5) & 0xff
+      dst(j + 5) = (out | (in << 5) & 0x7f).toByte
+      out = in >>> 2
+      in = src(i + 6) & 0xff
+      dst(j + 6) = (out | (in << 6) & 0x7f).toByte
+      out = in >>> 1
+      dst(j + 7) = out.toByte
+      i += 7
+      j += 8
+    }
+    if (i < srclen) {
+      var in: Int = src(i) & 0xff
+      dst(j) = (in & 0x7f).toByte; j += 1
+      var out: Int = in >>> 7
+      if (i + 1 < srclen) {
+        in = src(i + 1) & 0xff
+        dst(j) = (out | (in << 1) & 0x7f).toByte; j += 1
+        out = in >>> 6
+        if (i + 2 < srclen) {
+          in = src(i + 2) & 0xff
+          dst(j) = (out | (in << 2) & 0x7f).toByte; j += 1
+          out = in >>> 5
+          if (i + 3 < srclen) {
+            in = src(i + 3) & 0xff
+            dst(j) = (out | (in << 3) & 0x7f).toByte; j += 1
+            out = in >>> 4
+            if (i + 4 < srclen) {
+              in = src(i + 4) & 0xff
+              dst(j) = (out | (in << 4) & 0x7f).toByte; j += 1
+              out = in >>> 3
+              if (i + 5 < srclen) {
+                in = src(i + 5) & 0xff
+                dst(j) = (out | (in << 5) & 0x7f).toByte; j += 1
+                out = in >>> 2
+              }
+            }
+          }
+        }
+      }
+      if (j < dstlen) dst(j) = out.toByte
+    }
+    dst
+  }
+
+  @deprecated("use 2-argument version instead")
+  def decode7to8(src: Array[Byte], srclen: Int, dstlen: Int) { decode7to8(src, srclen) }
+
+  def decode7to8(src: Array[Byte], srclen: Int): Int = {
+    var i = 0
+    var j = 0
+    val dstlen = (srclen * 7 + 7) / 8
+    while (i + 7 < srclen) {
+      var out: Int = src(i)
+      var in: Byte = src(i + 1)
+      src(j) = (out | (in & 0x01) << 7).toByte
+      out = in >>> 1
+      in = src(i + 2)
+      src(j + 1) = (out | (in & 0x03) << 6).toByte
+      out = in >>> 2
+      in = src(i + 3)
+      src(j + 2) = (out | (in & 0x07) << 5).toByte
+      out = in >>> 3
+      in = src(i + 4)
+      src(j + 3) = (out | (in & 0x0f) << 4).toByte
+      out = in >>> 4
+      in = src(i + 5)
+      src(j + 4) = (out | (in & 0x1f) << 3).toByte
+      out = in >>> 5
+      in = src(i + 6)
+      src(j + 5) = (out | (in & 0x3f) << 2).toByte
+      out = in >>> 6
+      in = src(i + 7)
+      src(j + 6) = (out | in << 1).toByte
+      i += 8
+      j += 7
+    }
+    if (i < srclen) {
+      var out: Int = src(i)
+      if (i + 1 < srclen) {
+        var in: Byte = src(i + 1)
+        src(j) = (out | (in & 0x01) << 7).toByte; j += 1
+        out = in >>> 1
+        if (i + 2 < srclen) {
+          in = src(i + 2)
+          src(j) = (out | (in & 0x03) << 6).toByte; j += 1
+          out = in >>> 2
+          if (i + 3 < srclen) {
+            in = src(i + 3)
+            src(j) = (out | (in & 0x07) << 5).toByte; j += 1
+            out = in >>> 3
+            if (i + 4 < srclen) {
+              in = src(i + 4)
+              src(j) = (out | (in & 0x0f) << 4).toByte; j += 1
+              out = in >>> 4
+              if (i + 5 < srclen) {
+                in = src(i + 5)
+                src(j) = (out | (in & 0x1f) << 3).toByte; j += 1
+                out = in >>> 5
+                if (i + 6 < srclen) {
+                  in = src(i + 6)
+                  src(j) = (out | (in & 0x3f) << 2).toByte; j += 1
+                  out = in >>> 6
+                }
+              }
+            }
+          }
+        }
+      }
+      if (j < dstlen) src(j) = out.toByte
+    }
+    dstlen
+  }
+
+  def encode(xs: Array[Byte]): Array[Byte] = avoidZero(encode8to7(xs))
+
+  @deprecated("use 1-argument version instead")
+  def decode(xs: Array[Byte], dstlen: Int) { decode(xs) }
+
+  /**
+   * Destructively decodes array xs and returns the length of the decoded array.
+   *
+   * Sometimes returns (length+1) of the decoded array. Example:
+   *
+   *   scala> val enc = reflect.generic.ByteCodecs.encode(Array(1,2,3))
+   *   enc: Array[Byte] = Array(2, 5, 13, 1)
+   *
+   *   scala> reflect.generic.ByteCodecs.decode(enc)
+   *   res43: Int = 4
+   *
+   *   scala> enc
+   *   res44: Array[Byte] = Array(1, 2, 3, 0)
+   *
+   * However, this does not always happen.
+   */
+  def decode(xs: Array[Byte]): Int = {
+    val len = regenerateZero(xs)
+    decode7to8(xs, len)
+  }
+}
+
+      
+      
+      
+      
+      
+  
+    
diff --git a/src/library/scala/reflect/generic/Constants.scala b/src/library/scala/reflect/generic/Constants.scala
new file mode 100644
index 0000000..60aced5
--- /dev/null
+++ b/src/library/scala/reflect/generic/Constants.scala
@@ -0,0 +1,235 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
+ * @author  Martin Odersky
+ */
+
+package scala.reflect
+package generic
+
+import java.lang.Integer.toOctalString
+import PickleFormat._
+
+trait Constants { self: Universe =>
+
+  import definitions._
+
+  final val NoTag      = LITERAL - LITERAL
+  final val UnitTag    = LITERALunit - LITERAL
+  final val BooleanTag = LITERALboolean - LITERAL
+  final val ByteTag    = LITERALbyte - LITERAL
+  final val ShortTag   = LITERALshort - LITERAL
+  final val CharTag    = LITERALchar - LITERAL
+  final val IntTag     = LITERALint - LITERAL
+  final val LongTag    = LITERALlong - LITERAL
+  final val FloatTag   = LITERALfloat - LITERAL
+  final val DoubleTag  = LITERALdouble - LITERAL
+  final val StringTag  = LITERALstring - LITERAL
+  final val NullTag    = LITERALnull - LITERAL
+  final val ClassTag   = LITERALclass - LITERAL
+  // For supporting java enumerations inside java annotations (see ClassfileParser)
+  final val EnumTag    = LITERALenum - LITERAL
+
+  case class Constant(value: Any) {
+
+    val tag: Int =
+      if (value.isInstanceOf[Unit]) UnitTag
+      else if (value.isInstanceOf[Boolean]) BooleanTag
+      else if (value.isInstanceOf[Byte]) ByteTag
+      else if (value.isInstanceOf[Short]) ShortTag
+      else if (value.isInstanceOf[Char]) CharTag
+      else if (value.isInstanceOf[Int]) IntTag
+      else if (value.isInstanceOf[Long]) LongTag
+      else if (value.isInstanceOf[Float]) FloatTag
+      else if (value.isInstanceOf[Double]) DoubleTag
+      else if (value.isInstanceOf[String]) StringTag
+      else if (value.isInstanceOf[AbsType]) ClassTag
+      else if (value.isInstanceOf[AbsSymbol]) EnumTag
+      else if (value == null) NullTag
+      else throw new Error("bad constant value: " + value)
+
+    def isNumeric: Boolean = ByteTag <= tag && tag <= DoubleTag
+
+    def tpe: Type = tag match {
+      case UnitTag    => UnitClass.tpe
+      case BooleanTag => BooleanClass.tpe
+      case ByteTag    => ByteClass.tpe
+      case ShortTag   => ShortClass.tpe
+      case CharTag    => CharClass.tpe
+      case IntTag     => IntClass.tpe
+      case LongTag    => LongClass.tpe
+      case FloatTag   => FloatClass.tpe
+      case DoubleTag  => DoubleClass.tpe
+      case StringTag  => StringClass.tpe
+      case NullTag    => NullClass.tpe
+      case ClassTag   => ClassType(value.asInstanceOf[Type])
+      case EnumTag    =>
+        // given (in java): "class A { enum E { VAL1 } }"
+        //  - symbolValue: the symbol of the actual enumeration value (VAL1)
+        //  - .owner: the ModuleClasSymbol of the enumeration (object E)
+        //  - .linkedClassOfClass: the ClassSymbol of the enumeration (class E)
+        symbolValue.owner.linkedClassOfClass.tpe
+    }
+
+    /** We need the equals method to take account of tags as well as values.
+     *
+     *  @param other ...
+     *  @return      ...
+     */
+    override def equals(other: Any): Boolean = other match {
+      case that: Constant => 
+        this.tag == that.tag && 
+        (this.value == that.value || this.isNaN && that.isNaN)
+      case _ => false
+    }
+
+    def isNaN = value match {
+      case f: Float => f.isNaN
+      case d: Double => d.isNaN
+      case _ => false
+    }
+
+    def booleanValue: Boolean = 
+      if (tag == BooleanTag) value.asInstanceOf[Boolean]
+      else throw new Error("value " + value + " is not a boolean");
+
+    def byteValue: Byte = tag match {
+      case ByteTag   => value.asInstanceOf[Byte]
+      case ShortTag  => value.asInstanceOf[Short].toByte
+      case CharTag   => value.asInstanceOf[Char].toByte
+      case IntTag    => value.asInstanceOf[Int].toByte
+      case LongTag   => value.asInstanceOf[Long].toByte
+      case FloatTag  => value.asInstanceOf[Float].toByte
+      case DoubleTag => value.asInstanceOf[Double].toByte
+      case _         => throw new Error("value " + value + " is not a Byte")
+    }
+
+    def shortValue: Short = tag match {
+      case ByteTag   => value.asInstanceOf[Byte].toShort
+      case ShortTag  => value.asInstanceOf[Short]
+      case CharTag   => value.asInstanceOf[Char].toShort
+      case IntTag    => value.asInstanceOf[Int].toShort
+      case LongTag   => value.asInstanceOf[Long].toShort
+      case FloatTag  => value.asInstanceOf[Float].toShort
+      case DoubleTag => value.asInstanceOf[Double].toShort
+      case _         => throw new Error("value " + value + " is not a Short")
+    }
+
+    def charValue: Char = tag match {
+      case ByteTag   => value.asInstanceOf[Byte].toChar
+      case ShortTag  => value.asInstanceOf[Short].toChar
+      case CharTag   => value.asInstanceOf[Char]
+      case IntTag    => value.asInstanceOf[Int].toChar
+      case LongTag   => value.asInstanceOf[Long].toChar
+      case FloatTag  => value.asInstanceOf[Float].toChar
+      case DoubleTag => value.asInstanceOf[Double].toChar
+      case _         => throw new Error("value " + value + " is not a Char")
+    }
+
+    def intValue: Int = tag match {
+      case ByteTag   => value.asInstanceOf[Byte].toInt
+      case ShortTag  => value.asInstanceOf[Short].toInt
+      case CharTag   => value.asInstanceOf[Char].toInt
+      case IntTag    => value.asInstanceOf[Int]
+      case LongTag   => value.asInstanceOf[Long].toInt
+      case FloatTag  => value.asInstanceOf[Float].toInt
+      case DoubleTag => value.asInstanceOf[Double].toInt
+      case _         => throw new Error("value " + value + " is not an Int")
+    }
+
+    def longValue: Long = tag match {
+      case ByteTag   => value.asInstanceOf[Byte].toLong
+      case ShortTag  => value.asInstanceOf[Short].toLong
+      case CharTag   => value.asInstanceOf[Char].toLong
+      case IntTag    => value.asInstanceOf[Int].toLong
+      case LongTag   => value.asInstanceOf[Long]
+      case FloatTag  => value.asInstanceOf[Float].toLong
+      case DoubleTag => value.asInstanceOf[Double].toLong
+      case _         => throw new Error("value " + value + " is not a Long")
+    }
+
+    def floatValue: Float = tag match {
+      case ByteTag   => value.asInstanceOf[Byte].toFloat
+      case ShortTag  => value.asInstanceOf[Short].toFloat
+      case CharTag   => value.asInstanceOf[Char].toFloat
+      case IntTag    => value.asInstanceOf[Int].toFloat
+      case LongTag   => value.asInstanceOf[Long].toFloat
+      case FloatTag  => value.asInstanceOf[Float]
+      case DoubleTag => value.asInstanceOf[Double].toFloat
+      case _         => throw new Error("value " + value + " is not a Float")
+    }
+
+    def doubleValue: Double = tag match {
+      case ByteTag   => value.asInstanceOf[Byte].toDouble
+      case ShortTag  => value.asInstanceOf[Short].toDouble
+      case CharTag   => value.asInstanceOf[Char].toDouble
+      case IntTag    => value.asInstanceOf[Int].toDouble
+      case LongTag   => value.asInstanceOf[Long].toDouble
+      case FloatTag  => value.asInstanceOf[Float].toDouble
+      case DoubleTag => value.asInstanceOf[Double]
+      case _         => throw new Error("value " + value + " is not a Double")
+    }
+
+    /** Convert constant value to conform to given type.
+     *
+     *  @param pt ...
+     *  @return   ...
+     */
+    def convertTo(pt: Type): Constant = {
+      val target = pt.typeSymbol
+      if (target == tpe.typeSymbol)
+        this
+      else if (target == ByteClass && ByteTag <= tag && tag <= IntTag &&
+          -128 <= intValue && intValue <= 127) 
+        Constant(byteValue)
+      else if (target == ShortClass && ByteTag <= tag && tag <= IntTag &&
+               -32768 <= intValue && intValue <= 32767) 
+        Constant(shortValue)
+      else if (target == CharClass && ByteTag <= tag && tag <= IntTag  &&
+               0 <= intValue && intValue <= 65635)
+        Constant(charValue)
+      else if (target == IntClass && ByteTag <= tag && tag <= IntTag)
+        Constant(intValue)
+      else if (target == LongClass && ByteTag <= tag && tag <= LongTag)
+        Constant(longValue)
+      else if (target == FloatClass && ByteTag <= tag && tag <= FloatTag)
+        Constant(floatValue)
+      else if (target == DoubleClass && ByteTag <= tag && tag <= DoubleTag)
+        Constant(doubleValue)
+      else {
+        null
+      }
+    }
+
+    def stringValue: String =
+      if (value == null) "null"
+      else if (tag == ClassTag) signature(typeValue)
+      else value.toString()
+
+    def escapedStringValue: String = {
+      def escape(text: String): String = {
+        val buf = new StringBuilder
+        for (c <- text.iterator)
+          if (c.isControl)
+            buf.append("\\0" + toOctalString(c.asInstanceOf[Int]))
+          else
+            buf.append(c)
+        buf.toString
+      }
+      tag match {
+        case NullTag   => "null"
+        case StringTag => "\"" + escape(stringValue) + "\""
+        case ClassTag  => "classOf[" + signature(typeValue) + "]"
+        case CharTag   => escape("\'" + charValue + "\'")
+        case LongTag   => longValue.toString() + "L"
+        case _         => value.toString()
+      }
+    }
+
+    def typeValue: Type = value.asInstanceOf[Type]
+
+    def symbolValue: Symbol = value.asInstanceOf[Symbol]
+
+    override def hashCode: Int =
+      if (value == null) 0 else value.## * 41 + 17
+  }
+}
diff --git a/src/library/scala/reflect/generic/Flags.scala b/src/library/scala/reflect/generic/Flags.scala
new file mode 100644
index 0000000..a23cb61
--- /dev/null
+++ b/src/library/scala/reflect/generic/Flags.scala
@@ -0,0 +1,199 @@
+package scala.reflect
+package generic
+
+object Flags extends Flags
+
+class Flags {
+
+  // modifiers
+  final val IMPLICIT      = 0x00000200   
+  final val FINAL         = 0x00000020
+  final val PRIVATE       = 0x00000004
+  final val PROTECTED     = 0x00000001
+
+  final val SEALED        = 0x00000400
+  final val OVERRIDE      = 0x00000002
+  final val CASE          = 0x00000800
+  final val ABSTRACT      = 0x00000008    // abstract class, or used in conjunction
+                                          // with abstract override.
+                                          // Note difference to DEFERRED!
+
+  final val DEFERRED      = 0x00000010    // was `abstract' for members | trait is virtual
+  final val METHOD        = 0x00000040    // a method
+  final val MODULE        = 0x00000100    // symbol is module or class implementing a module
+  final val INTERFACE     = 0x00000080    // symbol is an interface (i.e. a trait which defines only abstract methods)
+
+  final val MUTABLE       = 0x00001000    // symbol is a mutable variable.
+  final val PARAM         = 0x00002000    // symbol is a (value or type) parameter to a method
+  final val PACKAGE       = 0x00004000    // symbol is a java package
+  // available: 0x00008000
+
+  final val COVARIANT     = 0x00010000    // symbol is a covariant type variable
+  final val CAPTURED      = 0x00010000    // variable is accessed from nested function.
+                                          // Set by LambdaLift
+  final val BYNAMEPARAM   = 0x00010000    // parameter is by name
+  final val CONTRAVARIANT = 0x00020000    // symbol is a contravariant type variable
+  final val LABEL         = 0x00020000    // method symbol is a label. Set by TailCall
+  final val INCONSTRUCTOR = 0x00020000    // class symbol is defined in this/superclass
+                                          // constructor.
+  final val ABSOVERRIDE   = 0x00040000    // combination of abstract & override
+  final val LOCAL         = 0x00080000    // symbol is local to current class (i.e. private[this] or protected[this]
+                                          // pre: PRIVATE or PROTECTED are also set
+  final val JAVA          = 0x00100000    // symbol was defined by a Java class
+  final val SYNTHETIC     = 0x00200000    // symbol is compiler-generated
+  final val STABLE        = 0x00400000    // functions that are assumed to be stable
+                                          // (typically, access methods for valdefs)
+                                          // or classes that do not contain abstract types.
+  final val STATIC        = 0x00800000    // static field, method or class
+
+  final val CASEACCESSOR  = 0x01000000    // symbol is a case parameter (or its accessor)
+  final val TRAIT         = 0x02000000    // symbol is a trait
+  final val DEFAULTPARAM  = 0x02000000    // the parameter has a default value
+  final val BRIDGE        = 0x04000000    // function is a bridge method. Set by Erasure
+  final val ACCESSOR      = 0x08000000    // a value or variable accessor (getter or setter)
+
+  final val SUPERACCESSOR = 0x10000000    // a super accessor
+  final val PARAMACCESSOR = 0x20000000    // for field definitions generated for primary constructor
+                                          //   parameters (no matter if it's a 'val' parameter or not)
+                                          // for parameters of a primary constructor ('val' or not)
+                                          // for the accessor methods generated for 'val' or 'var' parameters
+  final val MODULEVAR     = 0x40000000    // for variables: is the variable caching a module value
+  final val SYNTHETICMETH = 0x40000000    // for methods: synthetic method, but without SYNTHETIC flag
+  final val MONOMORPHIC   = 0x40000000    // for type symbols: does not have type parameters
+  final val LAZY          = 0x80000000L   // symbol is a lazy val. can't have MUTABLE unless transformed by typer
+
+  final val IS_ERROR      = 0x100000000L  // symbol is an error symbol
+  final val OVERLOADED    = 0x200000000L  // symbol is overloaded
+  final val LIFTED        = 0x400000000L  // class has been lifted out to package level
+                                          // local value has been lifted out to class level
+                                          // todo: make LIFTED = latePRIVATE?
+  final val MIXEDIN       = 0x800000000L  // term member has been mixed in
+  final val EXISTENTIAL   = 0x800000000L  // type is an existential parameter or skolem
+
+  final val EXPANDEDNAME  = 0x1000000000L // name has been expanded with class suffix
+  final val IMPLCLASS     = 0x2000000000L // symbol is an implementation class
+  final val PRESUPER      = 0x2000000000L // value is evaluated before super call
+  final val TRANS_FLAG    = 0x4000000000L // transient flag guaranteed to be reset
+                                          // after each phase.
+
+  final val LOCKED        = 0x8000000000L // temporary flag to catch cyclic dependencies
+  final val SPECIALIZED   = 0x10000000000L// symbol is a generated specialized member
+  final val DEFAULTINIT   = 0x20000000000L// symbol is a generated specialized member
+  final val VBRIDGE       = 0x40000000000L// symbol is a varargs bridge
+
+  // pickling and unpickling of flags
+
+  // The flags from 0x001 to 0x800 are different in the raw flags
+  // and in the pickled format.
+
+  private final val IMPLICIT_PKL   = 0x00000001   
+  private final val FINAL_PKL      = 0x00000002
+  private final val PRIVATE_PKL    = 0x00000004
+  private final val PROTECTED_PKL  = 0x00000008
+
+  private final val SEALED_PKL     = 0x00000010
+  private final val OVERRIDE_PKL   = 0x00000020
+  private final val CASE_PKL       = 0x00000040
+  private final val ABSTRACT_PKL   = 0x00000080
+
+  private final val DEFERRED_PKL   = 0x00000100
+  private final val METHOD_PKL     = 0x00000200
+  private final val MODULE_PKL     = 0x00000400
+  private final val INTERFACE_PKL  = 0x00000800
+
+  private final val PKL_MASK       = 0x00000FFF
+
+  final val PickledFlags: Long  = 0xFFFFFFFFL
+
+  private val r2p = {
+    def rawFlagsToPickledAux(flags:Int) = {
+      var pflags=0
+      if ((flags & IMPLICIT )!=0) pflags|=IMPLICIT_PKL
+      if ((flags & FINAL    )!=0) pflags|=FINAL_PKL
+      if ((flags & PRIVATE  )!=0) pflags|=PRIVATE_PKL
+      if ((flags & PROTECTED)!=0) pflags|=PROTECTED_PKL
+      if ((flags & SEALED   )!=0) pflags|=SEALED_PKL
+      if ((flags & OVERRIDE )!=0) pflags|=OVERRIDE_PKL
+      if ((flags & CASE     )!=0) pflags|=CASE_PKL
+      if ((flags & ABSTRACT )!=0) pflags|=ABSTRACT_PKL
+      if ((flags & DEFERRED )!=0) pflags|=DEFERRED_PKL
+      if ((flags & METHOD   )!=0) pflags|=METHOD_PKL
+      if ((flags & MODULE   )!=0) pflags|=MODULE_PKL
+      if ((flags & INTERFACE)!=0) pflags|=INTERFACE_PKL
+      pflags
+    }
+    val v=new Array[Int](PKL_MASK+1)
+    var i=0
+    while (i<=PKL_MASK) {
+      v(i)=rawFlagsToPickledAux(i)
+      i+=1
+    }
+    v
+  }
+
+  private val p2r = {
+    def pickledToRawFlagsAux(pflags:Int) = {
+      var flags=0
+      if ((pflags & IMPLICIT_PKL )!=0) flags|=IMPLICIT
+      if ((pflags & FINAL_PKL    )!=0) flags|=FINAL
+      if ((pflags & PRIVATE_PKL  )!=0) flags|=PRIVATE
+      if ((pflags & PROTECTED_PKL)!=0) flags|=PROTECTED
+      if ((pflags & SEALED_PKL   )!=0) flags|=SEALED
+      if ((pflags & OVERRIDE_PKL )!=0) flags|=OVERRIDE
+      if ((pflags & CASE_PKL     )!=0) flags|=CASE
+      if ((pflags & ABSTRACT_PKL )!=0) flags|=ABSTRACT
+      if ((pflags & DEFERRED_PKL )!=0) flags|=DEFERRED
+      if ((pflags & METHOD_PKL   )!=0) flags|=METHOD
+      if ((pflags & MODULE_PKL   )!=0) flags|=MODULE
+      if ((pflags & INTERFACE_PKL)!=0) flags|=INTERFACE
+      flags
+    }
+    val v=new Array[Int](PKL_MASK+1)
+    var i=0
+    while (i<=PKL_MASK) {
+      v(i)=pickledToRawFlagsAux(i)
+      i+=1
+    }
+    v
+  }
+
+  def rawFlagsToPickled(flags:Long):Long =
+    (flags & ~PKL_MASK) | r2p(flags.toInt & PKL_MASK)
+
+  def pickledToRawFlags(pflags:Long):Long =
+    (pflags & ~PKL_MASK) | p2r(pflags.toInt & PKL_MASK)
+
+  // List of the raw flags, in pickled order
+  protected val pickledListOrder = {
+    def findBit(m:Long):Int = {
+      var mask=m
+      var i=0
+      while (i <= 62) {
+        if ((mask&1) == 1L) return i
+        mask >>= 1
+        i += 1
+      }
+      throw new AssertionError()
+    }
+    val v=new Array[Long](63)
+    v(findBit(IMPLICIT_PKL ))=IMPLICIT
+    v(findBit(FINAL_PKL    ))=FINAL
+    v(findBit(PRIVATE_PKL  ))=PRIVATE
+    v(findBit(PROTECTED_PKL))=PROTECTED
+    v(findBit(SEALED_PKL   ))=SEALED
+    v(findBit(OVERRIDE_PKL ))=OVERRIDE
+    v(findBit(CASE_PKL     ))=CASE
+    v(findBit(ABSTRACT_PKL ))=ABSTRACT
+    v(findBit(DEFERRED_PKL ))=DEFERRED
+    v(findBit(METHOD_PKL   ))=METHOD
+    v(findBit(MODULE_PKL   ))=MODULE
+    v(findBit(INTERFACE_PKL))=INTERFACE
+    var i=findBit(PKL_MASK+1)
+    while (i <= 62) {
+      v(i)=1L << i
+      i += 1
+    }
+    v.toList
+  }
+
+}
diff --git a/src/library/scala/reflect/generic/Names.scala b/src/library/scala/reflect/generic/Names.scala
new file mode 100644
index 0000000..e8e01b5
--- /dev/null
+++ b/src/library/scala/reflect/generic/Names.scala
@@ -0,0 +1,21 @@
+package scala.reflect
+package generic
+
+trait Names { 
+
+  type Name >: Null <: AnyRef
+
+  def newTermName(cs: Array[Char], offset: Int, len: Int): Name
+  def newTermName(cs: Array[Byte], offset: Int, len: Int): Name
+  def newTermName(s: String): Name
+
+  def mkTermName(name: Name): Name
+
+  def newTypeName(cs: Array[Char], offset: Int, len: Int): Name
+  def newTypeName(cs: Array[Byte], offset: Int, len: Int): Name
+  def newTypeName(s: String): Name
+
+  def mkTypeName(name: Name): Name
+}
+  
+  
diff --git a/src/library/scala/reflect/generic/PickleBuffer.scala b/src/library/scala/reflect/generic/PickleBuffer.scala
new file mode 100644
index 0000000..b7fef43
--- /dev/null
+++ b/src/library/scala/reflect/generic/PickleBuffer.scala
@@ -0,0 +1,187 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
+ * @author  Martin Odersky
+ */
+
+package scala.reflect
+package generic
+
+/** Variable length byte arrays, with methods for basic pickling and unpickling.
+ *
+ *  @param data The initial buffer
+ *  @param from The first index where defined data are found
+ *  @param to   The first index where new data can be written
+ */
+class PickleBuffer(data: Array[Byte], from: Int, to: Int) {
+
+  var bytes = data
+  var readIndex = from
+  var writeIndex = to
+
+  /** Double bytes array */
+  private def dble() {
+    val bytes1 = new Array[Byte](bytes.length * 2)
+    Array.copy(bytes, 0, bytes1, 0, writeIndex)
+    bytes = bytes1
+  }
+
+  def ensureCapacity(capacity: Int) =
+    while (bytes.length < writeIndex + capacity) dble()
+
+  // -- Basic output routines --------------------------------------------
+
+  /** Write a byte of data */
+  def writeByte(b: Int) {
+    if (writeIndex == bytes.length) dble()
+    bytes(writeIndex) = b.toByte
+    writeIndex += 1
+  }
+
+  /** Write a natural number in big endian format, base 128.
+   *  All but the last digits have bit 0x80 set.
+   */
+  def writeNat(x: Int) =
+    writeLongNat(x.toLong & 0x00000000FFFFFFFFL)
+
+  /**
+   * Like writeNat, but for longs. This is not the same as
+   * writeLong, which writes in base 256. Note that the
+   * binary representation of LongNat is identical to Nat
+   * if the long value is in the range Int.MIN_VALUE to
+   * Int.MAX_VALUE.
+   */
+  def writeLongNat(x: Long) {
+    def writeNatPrefix(x: Long) {
+      val y = x >>> 7
+      if (y != 0L) writeNatPrefix(y)
+      writeByte(((x & 0x7f) | 0x80).toInt)
+    }
+    val y = x >>> 7
+    if (y != 0L) writeNatPrefix(y)
+    writeByte((x & 0x7f).toInt)
+  }
+
+  /** Write a natural number <code>x</code> at position <code>pos</code>.
+   *  If number is more than one byte, shift rest of array to make space.
+   *
+   *  @param pos ...
+   *  @param x   ...
+   */
+  def patchNat(pos: Int, x: Int) {
+    def patchNatPrefix(x: Int) {
+      writeByte(0)
+      Array.copy(bytes, pos, bytes, pos+1, writeIndex - (pos+1))
+      bytes(pos) = ((x & 0x7f) | 0x80).toByte
+      val y = x >>> 7
+      if (y != 0) patchNatPrefix(y)
+    }
+    bytes(pos) = (x & 0x7f).toByte
+    val y = x >>> 7
+    if (y != 0) patchNatPrefix(y)
+  }
+
+  /** Write a long number <code>x</code> in signed big endian format, base 256.
+   *
+   *  @param x The long number to be written.
+   */
+  def writeLong(x: Long) {
+    val y = x >> 8
+    val z = x & 0xff
+    if (-y != (z >> 7)) writeLong(y)
+    writeByte(z.toInt)
+  }
+
+  // -- Basic input routines --------------------------------------------
+
+  /** Peek at the current byte without moving the read index */
+  def peekByte(): Int = bytes(readIndex)
+
+  /** Read a byte */
+  def readByte(): Int = {
+    val x = bytes(readIndex); readIndex += 1; x
+  }
+
+  /** Read a natural number in big endian format, base 128.
+   *  All but the last digits have bit 0x80 set.*/
+  def readNat(): Int = readLongNat().toInt
+
+  def readLongNat(): Long = {
+    var b = 0L
+    var x = 0L
+    do {
+      b = readByte()
+      x = (x << 7) + (b & 0x7f)
+    } while ((b & 0x80) != 0L);
+    x
+  }
+
+  /** Read a long number in signed big endian format, base 256. */
+  def readLong(len: Int): Long = {
+    var x = 0L
+    var i = 0
+    while (i < len) {
+      x = (x << 8) + (readByte() & 0xff)
+      i += 1
+    }
+    val leading = 64 - (len << 3)
+    x << leading >> leading
+  }
+
+  /** Returns the buffer as a sequence of (Int, Array[Byte]) representing
+   *  (tag, data) of the individual entries.  Saves and restores buffer state.
+   */
+
+  def toIndexedSeq: IndexedSeq[(Int, Array[Byte])] = {
+    val saved = readIndex
+    readIndex = 0
+    readNat() ; readNat()     // discarding version
+    val result = new Array[(Int, Array[Byte])](readNat())
+    
+    result.indices foreach { index =>
+      val tag = readNat()
+      val len = readNat()
+      val bytes = data.slice(readIndex, len + readIndex)
+      readIndex += len
+      
+      result(index) = tag -> bytes
+    }
+
+    readIndex = saved
+    result.toIndexedSeq
+  }
+
+  /** Perform operation <code>op</code> until the condition
+   *  <code>readIndex == end</code> is satisfied.
+   *  Concatenate results into a list.
+   *
+   *  @param end ...
+   *  @param op  ...
+   *  @return    ...
+   */
+  def until[T](end: Int, op: () => T): List[T] =
+    if (readIndex == end) List() else op() :: until(end, op);
+
+  /** Perform operation <code>op</code> the number of
+   *  times specified.  Concatenate the results into a list.
+   */
+  def times[T](n: Int, op: ()=>T): List[T] =
+    if (n == 0) List() else op() :: times(n-1, op)
+
+  /** Pickle = majorVersion_Nat minorVersion_Nat nbEntries_Nat {Entry}
+   *  Entry  = type_Nat length_Nat [actual entries]
+   * 
+   *  Assumes that the ..Version_Nat are already consumed.
+   *
+   *  @return an array mapping entry numbers to locations in
+   *  the byte array where the entries start.
+   */
+  def createIndex: Array[Int] = {
+    val index = new Array[Int](readNat()) // nbEntries_Nat
+    for (i <- 0 until index.length) {
+      index(i) = readIndex
+      readByte() // skip type_Nat
+      readIndex = readNat() + readIndex // read length_Nat, jump to next entry
+    }
+    index
+  }
+}
diff --git a/src/library/scala/reflect/generic/PickleFormat.scala b/src/library/scala/reflect/generic/PickleFormat.scala
new file mode 100644
index 0000000..be9a900
--- /dev/null
+++ b/src/library/scala/reflect/generic/PickleFormat.scala
@@ -0,0 +1,223 @@
+package scala.reflect
+package generic
+
+/** This object provides constants for pickling attributes.
+ *
+ *  If you extend the format, be sure to increase the
+ *  version minor number.
+ *
+ *  @author Martin Odersky
+ *  @version 1.0
+ */
+object PickleFormat {
+
+/***************************************************
+ * Symbol table attribute format:
+ *   Symtab         = nentries_Nat {Entry}
+ *   Entry          = 1 TERMNAME len_Nat NameInfo
+ *                  | 2 TYPENAME len_Nat NameInfo
+ *                  | 3 NONEsym len_Nat
+ *                  | 4 TYPEsym len_Nat SymbolInfo
+ *                  | 5 ALIASsym len_Nat SymbolInfo
+ *                  | 6 CLASSsym len_Nat SymbolInfo [thistype_Ref]
+ *                  | 7 MODULEsym len_Nat SymbolInfo
+ *                  | 8 VALsym len_Nat [defaultGetter_Ref /* no longer needed*/] SymbolInfo [alias_Ref]
+ *                  | 9 EXTref len_Nat name_Ref [owner_Ref]
+ *                  | 10 EXTMODCLASSref len_Nat name_Ref [owner_Ref]
+ *                  | 11 NOtpe len_Nat
+ *                  | 12 NOPREFIXtpe len_Nat
+ *                  | 13 THIStpe len_Nat sym_Ref
+ *                  | 14 SINGLEtpe len_Nat type_Ref sym_Ref
+ *                  | 15 CONSTANTtpe len_Nat constant_Ref
+ *                  | 16 TYPEREFtpe len_Nat type_Ref sym_Ref {targ_Ref}
+ *                  | 17 TYPEBOUNDStpe len_Nat tpe_Ref tpe_Ref
+ *                  | 18 REFINEDtpe len_Nat classsym_Ref {tpe_Ref}
+ *                  | 19 CLASSINFOtpe len_Nat classsym_Ref {tpe_Ref}
+ *                  | 20 METHODtpe len_Nat tpe_Ref {sym_Ref}
+ *                  | 21 POLYTtpe len_Nat tpe_Ref {sym_Ref}
+ *                  | 22 IMPLICITMETHODtpe len_Nat tpe_Ref {sym_Ref} /* no longer needed */
+ *                  | 52 SUPERtpe len_Nat tpe_Ref tpe_Ref
+ *                  | 24 LITERALunit len_Nat
+ *                  | 25 LITERALboolean len_Nat value_Long
+ *                  | 26 LITERALbyte len_Nat value_Long
+ *                  | 27 LITERALshort len_Nat value_Long
+ *                  | 28 LITERALchar len_Nat value_Long
+ *                  | 29 LITERALint len_Nat value_Long
+ *                  | 30 LITERALlong len_Nat value_Long
+ *                  | 31 LITERALfloat len_Nat value_Long
+ *                  | 32 LITERALdouble len_Nat value_Long
+ *                  | 33 LITERALstring len_Nat name_Ref
+ *                  | 34 LITERALnull len_Nat
+ *                  | 35 LITERALclass len_Nat tpe_Ref
+ *                  | 36 LITERALenum len_Nat sym_Ref
+ *                  | 40 SYMANNOT len_Nat sym_Ref AnnotInfoBody
+ *                  | 41 CHILDREN len_Nat sym_Ref {sym_Ref}
+ *                  | 42 ANNOTATEDtpe len_Nat [sym_Ref /* no longer needed */] tpe_Ref {annotinfo_Ref}
+ *                  | 43 ANNOTINFO len_Nat AnnotInfoBody
+ *                  | 44 ANNOTARGARRAY len_Nat {constAnnotArg_Ref}
+ *                  | 47 DEBRUIJNINDEXtpe len_Nat level_Nat index_Nat
+ *                  | 48 EXISTENTIALtpe len_Nat type_Ref {symbol_Ref}
+ *                  | 49 TREE len_Nat 1 EMPTYtree
+ *                  | 49 TREE len_Nat 2 PACKAGEtree type_Ref sym_Ref mods_Ref name_Ref {tree_Ref}
+ *                  | 49 TREE len_Nat 3 CLASStree type_Ref sym_Ref mods_Ref name_Ref tree_Ref {tree_Ref}
+ *                  | 49 TREE len_Nat 4 MODULEtree type_Ref sym_Ref mods_Ref name_Ref tree_Ref
+ *                  | 49 TREE len_Nat 5 VALDEFtree type_Ref sym_Ref mods_Ref name_Ref tree_Ref tree_Ref
+ *                  | 49 TREE len_Nat 6 DEFDEFtree type_Ref sym_Ref mods_Ref name_Ref numtparams_Nat {tree_Ref} numparamss_Nat {numparams_Nat {tree_Ref}} tree_Ref tree_Ref
+ *                  | 49 TREE len_Nat 7 TYPEDEFtree type_Ref sym_Ref mods_Ref name_Ref tree_Ref {tree_Ref}
+ *                  | 49 TREE len_Nat 8 LABELtree type_Ref sym_Ref tree_Ref {tree_Ref}
+ *                  | 49 TREE len_Nat 9 IMPORTtree type_Ref sym_Ref tree_Ref {name_Ref name_Ref}
+ *                  | 49 TREE len_Nat 11 DOCDEFtree type_Ref sym_Ref string_Ref tree_Ref
+ *                  | 49 TREE len_Nat 12 TEMPLATEtree type_Ref sym_Ref numparents_Nat {tree_Ref} tree_Ref {tree_Ref}
+ *                  | 49 TREE len_Nat 13 BLOCKtree type_Ref tree_Ref {tree_Ref}
+ *                  | 49 TREE len_Nat 14 CASEtree type_Ref tree_Ref tree_Ref tree_Ref
+ *                  | 49 TREE len_Nat 15 SEQUENCEtree type_Ref {tree_Ref}
+ *                  | 49 TREE len_Nat 16 ALTERNATIVEtree type_Ref {tree_Ref}
+ *                  | 49 TREE len_Nat 17 STARtree type_Ref {tree_Ref}
+ *                  | 49 TREE len_Nat 18 BINDtree type_Ref sym_Ref name_Ref tree_Ref
+ *                  | 49 TREE len_Nat 19 UNAPPLYtree type_Ref tree_Ref {tree_Ref} 
+ *                  | 49 TREE len_Nat 20 ARRAYVALUEtree type_Ref tree_Ref {tree_Ref} 
+ *                  | 49 TREE len_Nat 21 FUNCTIONtree type_Ref sym_Ref tree_Ref {tree_Ref} 
+ *                  | 49 TREE len_Nat 22 ASSIGNtree type_Ref tree_Ref tree_Ref 
+ *                  | 49 TREE len_Nat 23 IFtree type_Ref tree_Ref tree_Ref tree_Ref 
+ *                  | 49 TREE len_Nat 24 MATCHtree type_Ref tree_Ref {tree_Ref} 
+ *                  | 49 TREE len_Nat 25 RETURNtree type_Ref sym_Ref tree_Ref
+ *                  | 49 TREE len_Nat 26 TREtree type_Ref tree_Ref tree_Ref {tree_Ref} 
+ *                  | 49 TREE len_Nat 27 THROWtree type_Ref tree_Ref 
+ *                  | 49 TREE len_Nat 28 NEWtree type_Ref tree_Ref 
+ *                  | 49 TREE len_Nat 29 TYPEDtree type_Ref tree_Ref tree_Ref 
+ *                  | 49 TREE len_Nat 30 TYPEAPPLYtree type_Ref tree_Ref {tree_Ref} 
+ *                  | 49 TREE len_Nat 31 APPLYtree type_Ref tree_Ref {tree_Ref} 
+ *                  | 49 TREE len_Nat 32 APPLYDYNAMICtree type_Ref sym_Ref tree_Ref {tree_Ref} 
+ *                  | 49 TREE len_Nat 33 SUPERtree type_Ref sym_Ref tree_Ref name_Ref
+ *                  | 49 TREE len_Nat 34 THIStree type_Ref sym_Ref  name_Ref
+ *                  | 49 TREE len_Nat 35 SELECTtree type_Ref sym_Ref tree_Ref name_Ref
+ *                  | 49 TREE len_Nat 36 IDENTtree type_Ref sym_Ref name_Ref
+ *                  | 49 TREE len_Nat 37 LITERALtree type_Ref constant_Ref 
+ *                  | 49 TREE len_Nat 38 TYPEtree type_Ref 
+ *                  | 49 TREE len_Nat 39 ANNOTATEDtree type_Ref tree_Ref tree_Ref
+ *                  | 49 TREE len_Nat 40 SINGLETONTYPEtree type_Ref tree_Ref 
+ *                  | 49 TREE len_Nat 41 SELECTFROMTYPEtree type_Ref tree_Ref name_Ref 
+ *                  | 49 TREE len_Nat 42 COMPOUNDTYPEtree type_Ref tree_Ref 
+ *                  | 49 TREE len_Nat 43 APPLIEDTYPEtree type_Ref tree_Ref {tree_Ref} 
+ *                  | 49 TREE len_Nat 44 TYPEBOUNDStree type_Ref tree_Ref tree_Ref
+ *                  | 49 TREE len_Nat 45 EXISTENTIALTYPEtree type_Ref tree_Ref {tree_Ref} 
+ *                  | 50 MODIFIERS len_Nat flags_Long privateWithin_Ref
+ *   SymbolInfo     = name_Ref owner_Ref flags_LongNat [privateWithin_Ref] info_Ref
+ *   NameInfo       = <character sequence of length len_Nat in Utf8 format>
+ *   NumInfo        = <len_Nat-byte signed number in big endian format>
+ *   Ref            = Nat
+ *   AnnotInfoBody  = info_Ref {annotArg_Ref} {name_Ref constAnnotArg_Ref}
+ *   AnnotArg       = Tree | Constant
+ *   ConstAnnotArg  = Constant | AnnotInfo | AnnotArgArray
+ *
+ *   len is remaining length after `len'.
+ */
+  val MajorVersion = 5
+  val MinorVersion = 0
+
+  final val TERMname = 1
+  final val TYPEname = 2
+  final val NONEsym = 3
+  final val TYPEsym = 4
+  final val ALIASsym = 5
+  final val CLASSsym = 6
+  final val MODULEsym = 7
+  final val VALsym = 8
+  final val EXTref = 9
+  final val EXTMODCLASSref = 10
+  final val NOtpe = 11
+  final val NOPREFIXtpe = 12
+  final val THIStpe = 13
+  final val SINGLEtpe = 14
+  final val CONSTANTtpe = 15
+  final val TYPEREFtpe = 16
+  final val TYPEBOUNDStpe = 17
+  final val REFINEDtpe = 18
+  final val CLASSINFOtpe = 19
+  final val METHODtpe = 20
+  final val POLYtpe = 21
+  final val IMPLICITMETHODtpe = 22
+
+  final val LITERAL = 23   // base line for literals
+  final val LITERALunit = 24
+  final val LITERALboolean = 25
+  final val LITERALbyte = 26
+  final val LITERALshort = 27
+  final val LITERALchar = 28
+  final val LITERALint = 29
+  final val LITERALlong = 30
+  final val LITERALfloat = 31
+  final val LITERALdouble = 32
+  final val LITERALstring = 33
+  final val LITERALnull = 34
+  final val LITERALclass = 35
+  final val LITERALenum = 36
+  final val SYMANNOT = 40
+  final val CHILDREN = 41
+  final val ANNOTATEDtpe = 42
+  final val ANNOTINFO = 43
+  final val ANNOTARGARRAY = 44
+
+  final val SUPERtpe = 46
+  final val DEBRUIJNINDEXtpe = 47
+  final val EXISTENTIALtpe = 48
+
+  final val TREE = 49      // prefix code that means a tree is coming
+    final val EMPTYtree = 1
+    final val PACKAGEtree = 2
+    final val CLASStree = 3
+    final val MODULEtree = 4
+    final val VALDEFtree = 5
+    final val DEFDEFtree = 6
+    final val TYPEDEFtree = 7
+    final val LABELtree = 8
+    final val IMPORTtree = 9
+    final val DOCDEFtree = 11
+    final val TEMPLATEtree = 12
+    final val BLOCKtree = 13
+    final val CASEtree = 14
+    // This node type has been removed.
+    // final val SEQUENCEtree = 15
+    final val ALTERNATIVEtree = 16
+    final val STARtree = 17
+    final val BINDtree = 18
+    final val UNAPPLYtree = 19
+    final val ARRAYVALUEtree = 20
+    final val FUNCTIONtree = 21
+    final val ASSIGNtree = 22
+    final val IFtree = 23
+    final val MATCHtree = 24
+    final val RETURNtree = 25
+    final val TREtree = 26
+    final val THROWtree = 27
+    final val NEWtree = 28
+    final val TYPEDtree = 29
+    final val TYPEAPPLYtree = 30
+    final val APPLYtree = 31
+    final val APPLYDYNAMICtree = 32
+    final val SUPERtree = 33
+    final val THIStree = 34
+    final val SELECTtree = 35
+    final val IDENTtree = 36
+    final val LITERALtree = 37
+    final val TYPEtree = 38
+    final val ANNOTATEDtree = 39
+    final val SINGLETONTYPEtree = 40
+    final val SELECTFROMTYPEtree = 41
+    final val COMPOUNDTYPEtree = 42
+    final val APPLIEDTYPEtree = 43
+    final val TYPEBOUNDStree = 44
+    final val EXISTENTIALTYPEtree = 45
+
+  final val MODIFIERS = 50
+
+  final val firstSymTag = NONEsym
+  final val lastSymTag = VALsym
+  final val lastExtSymTag = EXTMODCLASSref
+
+
+  //The following two are no longer accurate, because ANNOTATEDtpe,
+  //SUPERtpe, ... are not in the same range as the other types
+  //final val firstTypeTag = NOtpe
+  //final val lastTypeTag = POLYtpe
+}
diff --git a/src/library/scala/reflect/generic/Scopes.scala b/src/library/scala/reflect/generic/Scopes.scala
new file mode 100644
index 0000000..3ef81b4
--- /dev/null
+++ b/src/library/scala/reflect/generic/Scopes.scala
@@ -0,0 +1,15 @@
+package scala.reflect
+package generic
+
+trait Scopes { self: Universe =>
+
+  abstract class AbsScope extends Iterable[Symbol] {
+    def enter(sym: Symbol): Symbol
+  }
+
+  type Scope <: AbsScope
+
+  def newScope(): Scope
+}
+  
+  
diff --git a/src/library/scala/reflect/generic/StandardDefinitions.scala b/src/library/scala/reflect/generic/StandardDefinitions.scala
new file mode 100644
index 0000000..c33b9ea
--- /dev/null
+++ b/src/library/scala/reflect/generic/StandardDefinitions.scala
@@ -0,0 +1,66 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
+ * @author  Martin Odersky
+ */
+
+package scala.reflect
+package generic
+
+trait StandardDefinitions { self: Universe =>
+
+  val definitions: AbsDefinitions
+ 
+  abstract class AbsDefinitions {
+
+    // outer packages and their classes
+    def RootPackage: Symbol
+    def RootClass: Symbol
+    def EmptyPackage: Symbol
+    def EmptyPackageClass: Symbol
+
+    def ScalaPackage: Symbol
+    def ScalaPackageClass: Symbol
+
+    // top types
+    def AnyClass   : Symbol
+    def AnyValClass: Symbol
+    def AnyRefClass: Symbol
+    def ObjectClass: Symbol
+
+    // bottom types
+    def NullClass   : Symbol
+    def NothingClass: Symbol
+    
+    // the scala value classes
+    def UnitClass   : Symbol
+    def ByteClass   : Symbol
+    def ShortClass  : Symbol
+    def CharClass   : Symbol
+    def IntClass    : Symbol
+    def LongClass   : Symbol
+    def FloatClass  : Symbol
+    def DoubleClass : Symbol
+    def BooleanClass: Symbol
+    
+    // fundamental reference classes
+    def SymbolClass : Symbol
+    def StringClass : Symbol
+    def ClassClass  : Symbol
+
+    // fundamental modules
+    def PredefModule: Symbol
+
+    // fundamental type constructions
+    def ClassType(arg: Type): Type
+
+    /** The string representation used by the given type in the VM.
+     */
+    def signature(tp: Type): String
+
+    /** Is symbol one of the value classes? */
+    def isValueClass(sym: Symbol): Boolean
+
+    /** Is symbol one of the numeric value classes? */
+    def isNumericValueClass(sym: Symbol): Boolean
+  }
+}
diff --git a/src/library/scala/reflect/generic/StdNames.scala b/src/library/scala/reflect/generic/StdNames.scala
new file mode 100644
index 0000000..a72e6e1
--- /dev/null
+++ b/src/library/scala/reflect/generic/StdNames.scala
@@ -0,0 +1,26 @@
+package scala.reflect
+package generic
+
+trait StdNames { self: Universe =>
+
+  val nme: StandardNames
+
+  class StandardNames {
+    val EXPAND_SEPARATOR_STRING = "$$"
+    val LOCAL_SUFFIX_STRING = " "
+
+    val ANON_CLASS_NAME    = newTermName("$anon")
+    val ANON_FUN_NAME      = newTermName("$anonfun")
+    val EMPTY_PACKAGE_NAME = newTermName("<empty>")
+    val IMPORT             = newTermName("<import>")
+    val REFINE_CLASS_NAME  = newTermName("<refinement>")
+    val ROOT               = newTermName("<root>")
+    val ROOTPKG            = newTermName("_root_")
+    val EMPTY              = newTermName("")
+
+    /** The expanded name of `name' relative to this class `base` with given `separator` 
+     */
+    def expandedName(name: Name, base: Symbol, separator: String = EXPAND_SEPARATOR_STRING): Name = 
+      newTermName(base.fullName('$') + separator + name)
+  }
+}
diff --git a/src/library/scala/reflect/generic/Symbols.scala b/src/library/scala/reflect/generic/Symbols.scala
new file mode 100644
index 0000000..718b34b
--- /dev/null
+++ b/src/library/scala/reflect/generic/Symbols.scala
@@ -0,0 +1,195 @@
+package scala.reflect
+package generic
+
+import Flags._
+
+trait Symbols { self: Universe =>
+
+  type Symbol >: Null <: AbsSymbol
+
+  abstract class AbsSymbol { this: Symbol =>
+
+    /** The owner of this symbol.
+     */
+    def owner: Symbol
+
+    /** The flags of this symbol */
+    def flags: Long
+
+    /** The name of the symbol as a member of the `Name` type.
+     */
+    def name: Name
+
+    /** The name of the symbol before decoding, e.g. `$eq$eq` instead of `==`.
+     */
+    def encodedName: String
+
+    /** The decoded name of the symbol, e.g. `==` instead of `$eq$eq`.
+     */
+    def decodedName: String = stripLocalSuffix(NameTransformer.decode(encodedName))
+
+    /** The encoded full path name of this symbol, where outer names and inner names
+     *  are separated by `separator` characters.
+     *  Never translates expansions of operators back to operator symbol.
+     *  Never adds id.
+     */
+    final def fullName(separator: Char): String = stripLocalSuffix {
+      if (isRoot || isRootPackage || this == NoSymbol) this.toString
+      else if (owner.isEffectiveRoot) encodedName
+      else owner.enclClass.fullName(separator) + separator + encodedName
+    }
+
+    private def stripLocalSuffix(s: String) = s stripSuffix nme.LOCAL_SUFFIX_STRING
+
+    /** The encoded full path name of this symbol, where outer names and inner names
+     *  are separated by periods.
+     */
+    final def fullName: String = fullName('.')
+
+    /** Does symbol have ANY flag in `mask` set? */
+    final def hasFlag(mask: Long): Boolean = (flags & mask) != 0L
+    
+    /** Does symbol have ALL the flags in `mask` set? */
+    final def hasAllFlags(mask: Long): Boolean = (flags & mask) == mask
+
+    /** Set when symbol has a modifier of the form private[X], NoSymbol otherwise.
+     */
+    def privateWithin: Symbol  
+
+    /** The raw info of the type
+     */
+    def rawInfo: Type
+
+    /** The type of the symbol
+     */
+    def tpe: Type = info
+
+    /** The info of the symbol. This is like tpe, except for class symbols where the `info`
+     *  describes the contents of the class whereas the `tpe` is a reference to the class. 
+     */
+    def info: Type = {
+      val tp = rawInfo
+      tp.complete(this)
+      tp
+    }
+
+    /** If this symbol is a class or trait, its self type, otherwise the type of the symbol itse;lf
+     */
+    def typeOfThis: Type
+
+    def owner_=(sym: Symbol)         { throw new UnsupportedOperationException("owner_= inapplicable for " + this) }
+    def flags_=(flags: Long)         { throw new UnsupportedOperationException("flags_= inapplicable for " + this) }
+    def info_=(tp: Type)             { throw new UnsupportedOperationException("info_= inapplicable for " + this) }
+    def typeOfThis_=(tp: Type)       { throw new UnsupportedOperationException("typeOfThis_= inapplicable for " + this) }
+    def privateWithin_=(sym: Symbol) { throw new UnsupportedOperationException("privateWithin_= inapplicable for " + this) }
+    def sourceModule_=(sym: Symbol)  { throw new UnsupportedOperationException("sourceModule_= inapplicable for " + this) }
+    def addChild(sym: Symbol)        { throw new UnsupportedOperationException("addChild inapplicable for " + this) }
+    def addAnnotation(annot: AnnotationInfo) { throw new UnsupportedOperationException("addAnnotation inapplicable for " + this) }
+
+    /** For a module class its linked class, for a plain class
+     *  the module class of its linked module.
+     *  For instance
+     *    object Foo
+     *    class Foo
+     *
+     *  Then object Foo has a `moduleClass' (invisible to the user, the backend calls it Foo$
+     *  linkedClassOfClass goes from class Foo$ to class Foo, and back.
+     */
+    def linkedClassOfClass: Symbol
+
+    /** The module corresponding to this module class (note that this
+     *  is not updated when a module is cloned), or NoSymbol if this is not a ModuleClass
+     */
+    def sourceModule: Symbol = NoSymbol
+
+    /** If symbol is an object definition, it's implied associated class,
+     *  otherwise NoSymbol
+     */
+    def moduleClass: Symbol
+
+// flags and kind tests
+
+    def isTerm         = false  // to be overridden
+    def isType         = false  // to be overridden
+    def isClass        = false  // to be overridden
+    def isAliasType    = false  // to be overridden
+    def isAbstractType = false  // to be overridden
+    private[scala] def isSkolem = false // to be overridden
+
+          def isTrait: Boolean = isClass && hasFlag(TRAIT) // refined later for virtual classes.
+    final def hasDefault = isParameter && hasFlag(DEFAULTPARAM)
+    final def isAbstractClass = isClass && hasFlag(ABSTRACT)
+    // XXX This is unlikely to be correct: it's not looking for the ABSOVERRIDE flag?
+    final def isAbstractOverride = isTerm && hasFlag(ABSTRACT) && hasFlag(OVERRIDE)
+    final def isBridge = hasFlag(BRIDGE)
+    final def isCase = hasFlag(CASE)
+    final def isCaseAccessor = hasFlag(CASEACCESSOR)
+    final def isContravariant = isType && hasFlag(CONTRAVARIANT)
+    final def isCovariant = isType && hasFlag(COVARIANT)
+    final def isDeferred = hasFlag(DEFERRED) && !isClass
+    final def isEarlyInitialized: Boolean = isTerm && hasFlag(PRESUPER)
+    final def isExistentiallyBound = isType && hasFlag(EXISTENTIAL)
+    final def isFinal = hasFlag(FINAL)
+    final def isGetterOrSetter = hasFlag(ACCESSOR)
+    final def isImplClass = isClass && hasFlag(IMPLCLASS) // Is this symbol an implementation class for a mixin?
+    final def isImplicit = hasFlag(IMPLICIT)
+    final def isInterface = hasFlag(INTERFACE)
+    final def isJavaDefined = hasFlag(JAVA)
+    final def isLazy = hasFlag(LAZY)
+    final def isMethod = isTerm && hasFlag(METHOD)
+    final def isModule = isTerm && hasFlag(MODULE)
+    final def isModuleClass = isClass && hasFlag(MODULE)
+    final def isMutable = hasFlag(MUTABLE)
+    final def isOverloaded = hasFlag(OVERLOADED)
+    final def isOverride = hasFlag(OVERRIDE)
+    final def isParamAccessor = hasFlag(PARAMACCESSOR)
+    final def isParameter = hasFlag(PARAM)
+    final def isRefinementClass = isClass && name == mkTypeName(nme.REFINE_CLASS_NAME)
+    final def isSealed = isClass && (hasFlag(SEALED) || definitions.isValueClass(this))
+    final def isSourceMethod = isTerm && (flags & (METHOD | STABLE)) == METHOD // exclude all accessors!!!
+    final def isSuperAccessor = hasFlag(SUPERACCESSOR)
+    final def isSynthetic = hasFlag(SYNTHETIC)
+    final def isTypeParameter = isType && isParameter && !isSkolem
+
+    /** Access tests */
+    final def isPrivate = hasFlag(PRIVATE)
+    final def isPrivateLocal = hasFlag(PRIVATE) && hasFlag(LOCAL)
+    final def isProtected = hasFlag(PROTECTED)
+    final def isProtectedLocal = hasFlag(PROTECTED) && hasFlag(LOCAL)
+    final def isPublic = !hasFlag(PRIVATE | PROTECTED) && privateWithin == NoSymbol
+
+    /** Package tests */
+    final def isEmptyPackage = isPackage && name == nme.EMPTY_PACKAGE_NAME
+    final def isEmptyPackageClass = isPackageClass && name == mkTypeName(nme.EMPTY_PACKAGE_NAME)
+    final def isPackage = isModule && hasFlag(PACKAGE)
+    final def isPackageClass = isClass && hasFlag(PACKAGE)
+    final def isRoot = isPackageClass && owner == NoSymbol 
+    final def isRootPackage = isPackage && owner == NoSymbol
+
+    /** Is this symbol an effective root for fullname string?
+     */
+    def isEffectiveRoot = isRoot || isEmptyPackageClass
+
+    // creators 
+    
+    def newAbstractType(name: Name, pos: Position = NoPosition): Symbol
+    def newAliasType(name: Name, pos: Position = NoPosition): Symbol
+    def newClass(name: Name, pos: Position = NoPosition): Symbol
+    def newMethod(name: Name, pos: Position = NoPosition): Symbol
+    def newModule(name: Name, clazz: Symbol, pos: Position = NoPosition): Symbol
+    def newModuleClass(name: Name, pos: Position = NoPosition): Symbol
+    def newValue(name: Name, pos: Position = NoPosition): Symbol
+
+    // access to related symbols
+
+    /** The next enclosing class */
+    def enclClass: Symbol = if (isClass) this else owner.enclClass
+
+    /** The next enclosing method */
+    def enclMethod: Symbol = if (isSourceMethod) this else owner.enclMethod
+  }
+
+  val NoSymbol: Symbol
+}
+  
+  
diff --git a/src/library/scala/reflect/generic/Trees.scala b/src/library/scala/reflect/generic/Trees.scala
new file mode 100644
index 0000000..0dad63f
--- /dev/null
+++ b/src/library/scala/reflect/generic/Trees.scala
@@ -0,0 +1,739 @@
+package scala.reflect
+package generic
+
+import java.io.{PrintWriter, StringWriter}
+import Flags._
+
+trait Trees { self: Universe =>
+
+  abstract class AbsTreePrinter(out: PrintWriter) {
+    def print(tree: Tree)
+    def flush()
+  }
+
+  def newTreePrinter(out: PrintWriter): AbsTreePrinter
+
+  private[scala] var nodeCount = 0
+
+  /** @param privateWithin the qualifier for a private (a type name)
+   *    or nme.EMPTY.toTypeName, if none is given.
+   *  @param annotations the annotations for the definition.
+   *    <strong>Note:</strong> the typechecker drops these annotations,
+   *    use the AnnotationInfo's (Symbol.annotations) in later phases. 
+   */  
+  case class Modifiers(flags: Long, privateWithin: Name, annotations: List[Tree], positions: Map[Long, Position]) {
+    def isAbstract      = hasFlag(ABSTRACT )
+    def isAccessor      = hasFlag(ACCESSOR )
+    def isArgument      = hasFlag(PARAM    )
+    def isCase          = hasFlag(CASE     )
+    def isContravariant = hasFlag(CONTRAVARIANT)  // marked with `-'
+    def isCovariant     = hasFlag(COVARIANT    )  // marked with `+'
+    def isDeferred      = hasFlag(DEFERRED )
+    def isFinal         = hasFlag(FINAL    )
+    def isImplicit      = hasFlag(IMPLICIT )
+    def isLazy          = hasFlag(LAZY     )
+    def isOverride      = hasFlag(OVERRIDE )
+    def isPrivate       = hasFlag(PRIVATE  )
+    def isProtected     = hasFlag(PROTECTED)
+    def isPublic        = !isPrivate && !isProtected
+    def isSealed        = hasFlag(SEALED   )
+    def isSynthetic     = hasFlag(SYNTHETIC)
+    def isTrait         = hasFlag(TRAIT    )
+    def isVariable      = hasFlag(MUTABLE  )
+    
+    def hasFlag(flag: Long) = (flag & flags) != 0L
+    def & (flag: Long): Modifiers = {
+      val flags1 = flags & flag
+      if (flags1 == flags) this
+      else Modifiers(flags1, privateWithin, annotations, positions)
+    }
+    def &~ (flag: Long): Modifiers = {
+      val flags1 = flags & (~flag)
+      if (flags1 == flags) this
+      else Modifiers(flags1, privateWithin, annotations, positions)
+    }
+    def | (flag: Long): Modifiers = {
+      val flags1 = flags | flag
+      if (flags1 == flags) this
+      else Modifiers(flags1, privateWithin, annotations, positions)
+    }
+    def withAnnotations(annots: List[Tree]) =
+      if (annots.isEmpty) this
+      else copy(annotations = annotations ::: annots)
+    def withPosition(flag: Long, position: Position) =
+      copy(positions = positions + (flag -> position))
+  }
+
+  def Modifiers(flags: Long, privateWithin: Name): Modifiers = Modifiers(flags, privateWithin, List(), Map.empty)
+  def Modifiers(flags: Long): Modifiers = Modifiers(flags, mkTypeName(nme.EMPTY))
+
+  lazy val NoMods = Modifiers(0)
+
+  abstract class Tree extends Product {
+    val id = nodeCount
+    nodeCount += 1
+
+    private[this] var rawpos: Position = NoPosition
+
+    def pos = rawpos
+    def pos_=(pos: Position) = rawpos = pos
+    def setPos(pos: Position): this.type = { rawpos = pos; this }
+
+    private[this] var rawtpe: Type = _
+
+    def tpe = rawtpe
+    def tpe_=(t: Type) = rawtpe = t
+
+    /** Set tpe to give `tp` and return this.
+     */
+    def setType(tp: Type): this.type = { rawtpe = tp; this } 
+
+    /** Like `setType`, but if this is a previously empty TypeTree
+     *  that fact is remembered so that resetType will snap back.
+     */
+    def defineType(tp: Type): this.type = setType(tp)
+    
+    def symbol: Symbol = null
+    def symbol_=(sym: Symbol) { throw new UnsupportedOperationException("symbol_= inapplicable for " + this) }
+    def setSymbol(sym: Symbol): this.type = { symbol = sym; this }
+    
+    def hasSymbol = false
+    def isDef = false
+    def isEmpty = false
+
+    /** The direct child trees of this tree
+     *  EmptyTrees are always omitted. Lists are collapsed.
+     */
+    def children: List[Tree] = {
+      def subtrees(x: Any): List[Tree] = x match {
+        case EmptyTree => List()
+        case t: Tree => List(t)
+        case xs: List[_] => xs flatMap subtrees
+        case _ => List()
+      }
+      productIterator.toList flatMap subtrees
+    }
+
+    /** In compiler: Make a copy of this tree, keeping all attributes,
+     *  except that all positions are focussed (so nothing
+     *  in this tree will be found when searching by position).
+     *  If not in compiler may also return tree unchanged.
+     */
+    private[scala] def duplicate: this.type = 
+      duplicateTree(this).asInstanceOf[this.type]
+
+    private[scala] def copyAttrs(tree: Tree): this.type = {
+      pos = tree.pos
+      tpe = tree.tpe
+      if (hasSymbol) symbol = tree.symbol
+      this
+    }
+
+    override def toString(): String = {
+      val buffer = new StringWriter()
+      val printer = newTreePrinter(new PrintWriter(buffer))
+      printer.print(this)
+      printer.flush()
+      buffer.toString     
+    }
+
+    override def hashCode(): Int = super.hashCode()
+
+    override def equals(that: Any): Boolean = that match {
+      case t: Tree => this eq t
+      case _ => false
+    }
+  }
+
+  private[scala] def duplicateTree(tree: Tree): Tree = tree
+
+  trait SymTree extends Tree {
+    override def hasSymbol = true
+    override var symbol: Symbol = NoSymbol
+  }
+
+  trait RefTree extends SymTree {
+    def name: Name
+  }
+
+  abstract class DefTree extends SymTree {
+    def name: Name
+    override def isDef = true
+  }
+
+  trait TermTree extends Tree 
+
+  /** A tree for a type.  Note that not all type trees implement
+    * this trait; in particular, Ident's are an exception. */
+  trait TypTree extends Tree 
+
+// ----- tree node alternatives --------------------------------------
+
+  /** The empty tree */
+  case object EmptyTree extends TermTree {
+    super.tpe_=(NoType)
+    override def tpe_=(t: Type) = 
+      if (t != NoType) throw new UnsupportedOperationException("tpe_=("+t+") inapplicable for <empty>")
+    override def isEmpty = true
+  }
+
+  abstract class MemberDef extends DefTree {
+    def mods: Modifiers
+    def keyword: String = this match {
+      case TypeDef(_, _, _, _)      => "type"
+      case ClassDef(mods, _, _, _)  => if (mods.isTrait) "trait" else "class"
+      case DefDef(_, _, _, _, _, _) => "def"
+      case ModuleDef(_, _, _)       => "object"
+      case PackageDef(_, _)         => "package"
+      case ValDef(mods, _, _, _)    => if (mods.isVariable) "var" else "val"
+      case _ => ""
+    }
+    final def hasFlag(mask: Long): Boolean = (mods.flags & mask) != 0L
+  }
+
+  /** Package clause
+   */
+  case class PackageDef(pid: RefTree, stats: List[Tree])
+       extends MemberDef {
+    def name = pid.name
+    def mods = NoMods
+  }
+
+  abstract class ImplDef extends MemberDef {
+    def impl: Template
+  }
+
+  /** Class definition */
+  case class ClassDef(mods: Modifiers, name: Name, tparams: List[TypeDef], impl: Template)
+       extends ImplDef
+
+  /** Singleton object definition
+   */
+  case class ModuleDef(mods: Modifiers, name: Name, impl: Template)
+       extends ImplDef
+
+  abstract class ValOrDefDef extends MemberDef {
+    def tpt: Tree
+    def rhs: Tree
+  }
+
+  /** Value definition
+   */
+  case class ValDef(mods: Modifiers, name: Name, tpt: Tree, rhs: Tree) extends ValOrDefDef
+
+  /** Method definition
+   */
+  case class DefDef(mods: Modifiers, name: Name, tparams: List[TypeDef],
+                    vparamss: List[List[ValDef]], tpt: Tree, rhs: Tree) extends ValOrDefDef
+
+  /** Abstract type, type parameter, or type alias */
+  case class TypeDef(mods: Modifiers, name: Name, tparams: List[TypeDef], rhs: Tree) 
+       extends MemberDef 
+
+  /** <p>
+   *    Labelled expression - the symbols in the array (must be Idents!) 
+   *    are those the label takes as argument 
+   *  </p>
+   *  <p>
+   *    The symbol that is given to the labeldef should have a MethodType
+   *    (as if it were a nested function)
+   *  </p>
+   *  <p>
+   *    Jumps are apply nodes attributed with label symbol, the arguments
+   *    will get assigned to the idents.
+   *  </p>
+   *  <p>
+   *  Note: on 2005-06-09 Martin, Iuli, Burak agreed to have forward
+   *        jumps within a Block.
+   *  </p>
+   */
+  case class LabelDef(name: Name, params: List[Ident], rhs: Tree)
+       extends DefTree with TermTree 
+
+
+  /** Import selector
+   *
+   * Representation of an imported name its optional rename and their optional positions
+   * 
+   * @param name      the imported name
+   * @param namePos   its position or -1 if undefined
+   * @param rename    the name the import is renamed to (== name if no renaming)
+   * @param renamePos the position of the rename or -1 if undefined
+   */
+  case class ImportSelector(name: Name, namePos: Int, rename: Name, renamePos: Int)
+  
+  /** Import clause
+   *
+   *  @param expr
+   *  @param selectors
+   */
+  case class Import(expr: Tree, selectors: List[ImportSelector])
+       extends SymTree 
+    // The symbol of an Import is an import symbol @see Symbol.newImport
+    // It's used primarily as a marker to check that the import has been typechecked.
+
+  /** Instantiation template of a class or trait
+   *
+   *  @param parents
+   *  @param body
+   */
+  case class Template(parents: List[Tree], self: ValDef, body: List[Tree])
+       extends SymTree {
+    // the symbol of a template is a local dummy. @see Symbol.newLocalDummy
+    // the owner of the local dummy is the enclosing trait or class.
+    // the local dummy is itself the owner of any local blocks
+    // For example:
+    //
+    // class C { 
+    //   def foo // owner is C 
+    //   { 
+    //      def bar  // owner is local dummy
+    //   }
+    // System.err.println("TEMPLATE: " + parents)
+  }
+
+  /** Block of expressions (semicolon separated expressions) */
+  case class Block(stats: List[Tree], expr: Tree)
+       extends TermTree
+
+  /** Case clause in a pattern match, eliminated by TransMatch 
+   *  (except for occurrences in switch statements)
+   */
+  case class CaseDef(pat: Tree, guard: Tree, body: Tree)
+       extends Tree
+
+  /** Alternatives of patterns, eliminated by TransMatch, except for
+   *  occurrences in encoded Switch stmt (=remaining Match(CaseDef(...))
+   */
+  case class Alternative(trees: List[Tree])
+       extends TermTree
+
+  /** Repetition of pattern, eliminated by TransMatch */
+  case class Star(elem: Tree)
+       extends TermTree
+
+  /** Bind of a variable to a rhs pattern, eliminated by TransMatch
+   *
+   *  @param name
+   *  @param body
+   */
+  case class Bind(name: Name, body: Tree)
+       extends DefTree 
+
+  case class UnApply(fun: Tree, args: List[Tree]) 
+       extends TermTree
+
+  /** Array of expressions, needs to be translated in backend,
+   */
+  case class ArrayValue(elemtpt: Tree, elems: List[Tree])
+       extends TermTree
+
+  /** Anonymous function, eliminated by analyzer */
+  case class Function(vparams: List[ValDef], body: Tree)
+       extends TermTree with SymTree 
+    // The symbol of a Function is a synthetic value of name nme.ANON_FUN_NAME
+    // It is the owner of the function's parameters.
+
+  /** Assignment */
+  case class Assign(lhs: Tree, rhs: Tree)
+       extends TermTree
+
+  /** Conditional expression */
+  case class If(cond: Tree, thenp: Tree, elsep: Tree)
+       extends TermTree
+
+  /** <p>
+   *    Pattern matching expression  (before <code>TransMatch</code>)
+   *    Switch statements            (after TransMatch)
+   *  </p>
+   *  <p>
+   *    After <code>TransMatch</code>, cases will satisfy the following
+   *    constraints:
+   *  </p>
+   *  <ul>
+   *    <li>all guards are EmptyTree,</li>
+   *    <li>all patterns will be either <code>Literal(Constant(x:Int))</code>
+   *      or <code>Alternative(lit|...|lit)</code></li>
+   *    <li>except for an "otherwise" branch, which has pattern
+   *      <code>Ident(nme.WILDCARD)</code></li>
+   *  </ul>
+   */
+  case class Match(selector: Tree, cases: List[CaseDef])
+       extends TermTree
+
+  /** Return expression */
+  case class Return(expr: Tree)
+       extends TermTree with SymTree
+    // The symbol of a Return node is the enclosing method.
+
+  case class Try(block: Tree, catches: List[CaseDef], finalizer: Tree)
+       extends TermTree
+
+  /** Throw expression */
+  case class Throw(expr: Tree)
+       extends TermTree
+
+  /** Object instantiation
+   *  One should always use factory method below to build a user level new.
+   *
+   *  @param tpt    a class type
+   */
+  case class New(tpt: Tree) extends TermTree 
+
+  /** Type annotation, eliminated by explicit outer */
+  case class Typed(expr: Tree, tpt: Tree)
+       extends TermTree
+
+  // Martin to Sean: Should GenericApply/TypeApply/Apply not be SymTree's? After all, 
+  // ApplyDynamic is a SymTree.
+  abstract class GenericApply extends TermTree {
+    val fun: Tree
+    val args: List[Tree]
+  }
+
+  /** Type application */
+  case class TypeApply(fun: Tree, args: List[Tree])
+       extends GenericApply {
+    override def symbol: Symbol = fun.symbol
+    override def symbol_=(sym: Symbol) { fun.symbol = sym }
+  }
+
+  /** Value application */
+  case class Apply(fun: Tree, args: List[Tree])
+       extends GenericApply {
+    override def symbol: Symbol = fun.symbol
+    override def symbol_=(sym: Symbol) { fun.symbol = sym }
+  }
+
+  /** Dynamic value application. 
+   *  In a dynamic application   q.f(as)
+   *   - q is stored in qual
+   *   - as is stored in args
+   *   - f is stored as the node's symbol field.
+   */
+  case class ApplyDynamic(qual: Tree, args: List[Tree]) 
+       extends TermTree with SymTree
+    // The symbol of an ApplyDynamic is the function symbol of `qual', or NoSymbol, if there is none.
+
+  /** Super reference */
+  case class Super(qual: Name, mix: Name)
+       extends TermTree with SymTree
+    // The symbol of a Super is the class _from_ which the super reference is made.
+    // For instance in C.super(...), it would be C.
+
+  /** Self reference */
+  case class This(qual: Name)
+        extends TermTree with SymTree
+    // The symbol of a This is the class to which the this refers.
+    // For instance in C.this, it would be C.
+
+  /** Designator <qualifier> . <name> */
+  case class Select(qualifier: Tree, name: Name)
+       extends RefTree 
+
+  /** Identifier <name> */
+  case class Ident(name: Name)
+       extends RefTree 
+
+  class BackQuotedIdent(name: Name) extends Ident(name)
+
+  /** Literal */
+  case class Literal(value: Constant)
+        extends TermTree {
+    assert(value ne null)
+  }
+
+  def Literal(value: Any): Literal =
+    Literal(Constant(value))
+
+  type TypeTree <: AbsTypeTree
+  val TypeTree: TypeTreeExtractor
+
+  abstract class TypeTreeExtractor {
+    def apply(): TypeTree
+    def unapply(tree: TypeTree): Boolean
+  }
+  
+  class Traverser {
+    protected var currentOwner: Symbol = definitions.RootClass
+    def traverse(tree: Tree): Unit = tree match {
+      case EmptyTree =>
+        ;
+      case PackageDef(pid, stats) =>
+        traverse(pid)
+        atOwner(tree.symbol.moduleClass) {
+          traverseTrees(stats)
+        }
+      case ClassDef(mods, name, tparams, impl) =>
+        atOwner(tree.symbol) {
+          traverseTrees(mods.annotations); traverseTrees(tparams); traverse(impl)
+        }
+      case ModuleDef(mods, name, impl) =>
+        atOwner(tree.symbol.moduleClass) {
+          traverseTrees(mods.annotations); traverse(impl)
+        }
+      case ValDef(mods, name, tpt, rhs) =>
+        atOwner(tree.symbol) {
+          traverseTrees(mods.annotations); traverse(tpt); traverse(rhs)
+        }
+      case DefDef(mods, name, tparams, vparamss, tpt, rhs) =>
+        atOwner(tree.symbol) {
+          traverseTrees(mods.annotations); traverseTrees(tparams); traverseTreess(vparamss); traverse(tpt); traverse(rhs)
+        }
+      case TypeDef(mods, name, tparams, rhs) =>
+        atOwner(tree.symbol) {
+          traverseTrees(mods.annotations); traverseTrees(tparams); traverse(rhs)
+        }
+      case LabelDef(name, params, rhs) =>
+        traverseTrees(params); traverse(rhs)
+      case Import(expr, selectors) =>
+        traverse(expr)
+      case Annotated(annot, arg) =>
+        traverse(annot); traverse(arg)
+      case Template(parents, self, body) =>
+        traverseTrees(parents)
+        if (!self.isEmpty) traverse(self)
+        traverseStats(body, tree.symbol)
+      case Block(stats, expr) =>
+        traverseTrees(stats); traverse(expr)
+      case CaseDef(pat, guard, body) =>
+        traverse(pat); traverse(guard); traverse(body)
+      case Alternative(trees) =>
+        traverseTrees(trees)
+      case Star(elem) =>
+        traverse(elem)
+      case Bind(name, body) =>
+        traverse(body)
+      case UnApply(fun, args) =>
+        traverse(fun); traverseTrees(args)
+      case ArrayValue(elemtpt, trees) =>
+        traverse(elemtpt); traverseTrees(trees)
+      case Function(vparams, body) =>
+        atOwner(tree.symbol) {
+          traverseTrees(vparams); traverse(body)
+        }
+      case Assign(lhs, rhs) =>
+        traverse(lhs); traverse(rhs)
+      case If(cond, thenp, elsep) =>
+        traverse(cond); traverse(thenp); traverse(elsep)
+      case Match(selector, cases) =>
+        traverse(selector); traverseTrees(cases)
+      case Return(expr) =>
+        traverse(expr)
+      case Try(block, catches, finalizer) =>
+        traverse(block); traverseTrees(catches); traverse(finalizer)
+      case Throw(expr) =>
+        traverse(expr)
+      case New(tpt) =>
+        traverse(tpt)
+      case Typed(expr, tpt) =>
+        traverse(expr); traverse(tpt)
+      case TypeApply(fun, args) =>
+        traverse(fun); traverseTrees(args)
+      case Apply(fun, args) =>
+        traverse(fun); traverseTrees(args)
+      case ApplyDynamic(qual, args) =>
+        traverse(qual); traverseTrees(args)
+      case Super(_, _) =>
+        ;
+      case This(_) =>
+        ;
+      case Select(qualifier, selector) =>
+        traverse(qualifier)
+      case Ident(_) =>
+        ;
+      case Literal(_) =>
+        ;
+      case TypeTree() =>
+        ;
+      case SingletonTypeTree(ref) =>
+        traverse(ref)
+      case SelectFromTypeTree(qualifier, selector) =>
+        traverse(qualifier)
+      case CompoundTypeTree(templ) =>
+        traverse(templ)
+      case AppliedTypeTree(tpt, args) =>
+        traverse(tpt); traverseTrees(args)
+      case TypeBoundsTree(lo, hi) =>
+        traverse(lo); traverse(hi)
+      case ExistentialTypeTree(tpt, whereClauses) =>
+        traverse(tpt); traverseTrees(whereClauses)
+      case SelectFromArray(qualifier, selector, erasure) =>
+        traverse(qualifier)
+    }
+
+    def traverseTrees(trees: List[Tree]) {
+      trees foreach traverse
+    }
+    def traverseTreess(treess: List[List[Tree]]) {
+      treess foreach traverseTrees
+    }
+    def traverseStats(stats: List[Tree], exprOwner: Symbol) {
+      stats foreach (stat =>
+        if (exprOwner != currentOwner) atOwner(exprOwner)(traverse(stat))
+        else traverse(stat)
+      )
+    }
+
+    def atOwner(owner: Symbol)(traverse: => Unit) {
+      val prevOwner = currentOwner
+      currentOwner = owner
+      traverse
+      currentOwner = prevOwner
+    }
+  }
+
+  /** A synthetic term holding an arbitrary type.  Not to be confused with
+    * with TypTree, the trait for trees that are only used for type trees.
+    * TypeTree's are inserted in several places, but most notably in
+    * <code>RefCheck</code>, where the arbitrary type trees are all replaced by
+    * TypeTree's. */
+  abstract class AbsTypeTree extends TypTree {
+    override def symbol = if (tpe == null) null else tpe.typeSymbol
+    override def isEmpty = (tpe eq null) || tpe == NoType
+  }
+
+  /** A tree that has an annotation attached to it. Only used for annotated types and
+   *  annotation ascriptions, annotations on definitions are stored in the Modifiers.
+   *  Eliminated by typechecker (typedAnnotated), the annotations are then stored in
+   *  an AnnotatedType.
+   */
+  case class Annotated(annot: Tree, arg: Tree) extends Tree 
+
+  /** Singleton type, eliminated by RefCheck */
+  case class SingletonTypeTree(ref: Tree)
+        extends TypTree
+
+  /** Type selection <qualifier> # <name>, eliminated by RefCheck */
+  case class SelectFromTypeTree(qualifier: Tree, name: Name)
+       extends TypTree with RefTree
+
+  /** Intersection type <parent1> with ... with <parentN> { <decls> }, eliminated by RefCheck */
+  case class CompoundTypeTree(templ: Template)
+       extends TypTree
+
+  /** Applied type <tpt> [ <args> ], eliminated by RefCheck */
+  case class AppliedTypeTree(tpt: Tree, args: List[Tree])
+       extends TypTree {
+    override def symbol: Symbol = tpt.symbol
+    override def symbol_=(sym: Symbol) { tpt.symbol = sym }
+  }
+
+  case class TypeBoundsTree(lo: Tree, hi: Tree)
+       extends TypTree
+
+  case class ExistentialTypeTree(tpt: Tree, whereClauses: List[Tree])
+       extends TypTree
+
+  /** Array selection <qualifier> . <name> only used during erasure */
+  case class SelectFromArray(qualifier: Tree, name: Name, erasure: Type)
+       extends TermTree with RefTree { }
+
+/* A standard pattern match 
+  case EmptyTree =>
+  case PackageDef(pid, stats) =>
+     // package pid { stats }
+  case ClassDef(mods, name, tparams, impl) =>
+     // mods class name [tparams] impl   where impl = extends parents { defs }
+  case ModuleDef(mods, name, impl) =>                             (eliminated by refcheck)
+     // mods object name impl  where impl = extends parents { defs }
+  case ValDef(mods, name, tpt, rhs) =>
+     // mods val name: tpt = rhs   
+     // note missing type information is expressed by tpt = TypeTree()
+  case DefDef(mods, name, tparams, vparamss, tpt, rhs) =>
+     // mods def name[tparams](vparams_1)...(vparams_n): tpt = rhs
+     // note missing type information is expressed by tpt = TypeTree()
+  case TypeDef(mods, name, tparams, rhs) =>                       (eliminated by erasure)
+     // mods type name[tparams] = rhs
+     // mods type name[tparams] >: lo <: hi,  where lo, hi are in a TypeBoundsTree, 
+                                              and DEFERRED is set in mods
+  case LabelDef(name, params, rhs) =>
+     // used for tailcalls and like
+     // while/do are desugared to label defs as follows:
+     // while (cond) body ==> LabelDef($L, List(), if (cond) { body; L$() } else ())
+     // do body while (cond) ==> LabelDef($L, List(), body; if (cond) L$() else ())
+  case Import(expr, selectors) =>                                 (eliminated by typecheck)
+     // import expr.{selectors}
+     // Selectors are a list of pairs of names (from, to).
+     // The last (and maybe only name) may be a nme.WILDCARD
+     // for instance
+     //   import qual.{x, y => z, _}  would be represented as
+     //   Import(qual, List(("x", "x"), ("y", "z"), (WILDCARD, null)))
+  case Template(parents, self, body) =>
+     // extends parents { self => body }
+     // if self is missing it is represented as emptyValDef
+  case Block(stats, expr) =>
+     // { stats; expr }
+  case CaseDef(pat, guard, body) =>                               (eliminated by transmatch/explicitouter)
+    // case pat if guard => body
+  case Alternative(trees) =>                                      (eliminated by transmatch/explicitouter)
+    // pat1 | ... | patn
+  case Star(elem) =>                                              (eliminated by transmatch/explicitouter)
+    // pat*
+  case Bind(name, body) =>                                        (eliminated by transmatch/explicitouter)
+    // name @ pat
+  case UnApply(fun: Tree, args)                                   (introduced by typer, eliminated by transmatch/explicitouter)
+    // used for unapply's
+  case ArrayValue(elemtpt, trees) =>                              (introduced by uncurry)
+    // used to pass arguments to vararg arguments
+    // for instance, printf("%s%d", foo, 42) is translated to after uncurry to:
+    // Apply(
+    //   Ident("printf"), 
+    //   Literal("%s%d"), 
+    //   ArrayValue(<Any>, List(Ident("foo"), Literal(42))))
+  case Function(vparams, body) =>                                 (eliminated by lambdaLift)
+    // vparams => body  where vparams:List[ValDef]
+  case Assign(lhs, rhs) =>
+    // lhs = rhs
+  case If(cond, thenp, elsep) =>
+    // if (cond) thenp else elsep
+  case Match(selector, cases) =>
+    // selector match { cases }
+  case Return(expr) =>
+    // return expr
+  case Try(block, catches, finalizer) =>
+    // try block catch { catches } finally finalizer where catches: List[CaseDef]
+  case Throw(expr) =>
+    // throw expr
+  case New(tpt) =>
+    // new tpt   always in the context: (new tpt).<init>[targs](args)
+  case Typed(expr, tpt) =>                                        (eliminated by erasure)
+    // expr: tpt
+  case TypeApply(fun, args) =>
+    // fun[args]
+  case Apply(fun, args) =>
+    // fun(args)
+    // for instance fun[targs](args)  is expressed as  Apply(TypeApply(fun, targs), args)
+  case ApplyDynamic(qual, args)                                   (introduced by erasure, eliminated by cleanup)
+    // fun(args)
+  case Super(qual, mix) =>
+    // qual.super[mix]     if qual and/or mix is empty, ther are nme.EMPTY.toTypeName
+  case This(qual) =>
+    // qual.this
+  case Select(qualifier, selector) =>
+    // qualifier.selector
+  case Ident(name) =>
+    // name
+    // note: type checker converts idents that refer to enclosing fields or methods
+    // to selects; name ==> this.name
+  case Literal(value) =>
+    // value
+  case TypeTree() =>                                              (introduced by refcheck)
+    // a type that's not written out, but given in the tpe attribute
+  case Annotated(annot, arg) =>                                   (eliminated by typer)
+    // arg @annot  for types,  arg: @annot for exprs
+  case SingletonTypeTree(ref) =>                                  (eliminated by uncurry)
+    // ref.type
+  case SelectFromTypeTree(qualifier, selector) =>                 (eliminated by uncurry)
+    // qualifier # selector, a path-dependent type p.T is expressed as p.type # T
+  case CompoundTypeTree(templ: Template) =>                       (eliminated by uncurry)
+    // parent1 with ... with parentN { refinement }
+  case AppliedTypeTree(tpt, args) =>                              (eliminated by uncurry)
+    // tpt[args]
+  case TypeBoundsTree(lo, hi) =>                                  (eliminated by uncurry)
+    // >: lo <: hi
+  case ExistentialTypeTree(tpt, whereClauses) =>                  (eliminated by uncurry)
+    // tpt forSome { whereClauses }
+
+*/
+}
diff --git a/src/library/scala/reflect/generic/Types.scala b/src/library/scala/reflect/generic/Types.scala
new file mode 100644
index 0000000..7ecc09c
--- /dev/null
+++ b/src/library/scala/reflect/generic/Types.scala
@@ -0,0 +1,156 @@
+package scala.reflect
+package generic
+
+trait Types { self: Universe =>
+
+  abstract class AbsType {
+    def typeSymbol: Symbol
+    def decl(name: Name): Symbol
+
+    /** Is this type completed (i.e. not a lazy type)?
+     */
+    def isComplete: Boolean = true
+    
+    /** If this is a lazy type, assign a new type to `sym'. */
+    def complete(sym: Symbol) {}
+
+    /** Convert toString avoiding infinite recursions by cutting off
+     *  after `maxTostringRecursions` recursion levels. Uses `safeToString`
+     *  to produce a string on each level.
+     */
+    override def toString: String =
+      if (tostringRecursions >= maxTostringRecursions)
+        "..."
+      else
+        try {
+          tostringRecursions += 1
+          safeToString
+        } finally {
+          tostringRecursions -= 1
+        }
+
+    /** Method to be implemented in subclasses.
+     *  Converts this type to a string in calling toString for its parts.
+     */
+    def safeToString: String = super.toString
+  }
+
+  type Type >: Null <: AbsType
+
+  val NoType: Type
+  val NoPrefix: Type
+  
+  type ThisType <: Type
+  val ThisType: ThisTypeExtractor
+
+  type TypeRef <: Type
+  val TypeRef: TypeRefExtractor
+
+  type SingleType <: Type
+  val SingleType: SingleTypeExtractor
+  
+  type SuperType <: Type 
+  val SuperType: SuperTypeExtractor
+
+  type TypeBounds <: Type
+  val TypeBounds: TypeBoundsExtractor
+
+  type CompoundType <: Type
+
+  type RefinedType <: CompoundType
+  val RefinedType: RefinedTypeExtractor
+
+  type ClassInfoType <: CompoundType
+  val ClassInfoType: ClassInfoTypeExtractor
+
+  type ConstantType <: Type
+  val ConstantType: ConstantTypeExtractor
+
+  type MethodType <: Type
+  val MethodType: MethodTypeExtractor
+
+  type PolyType <: Type
+  val PolyType: PolyTypeExtractor
+  
+  type ExistentialType <: Type
+  val ExistentialType: ExistentialTypeExtractor
+  
+  type AnnotatedType <: Type
+  val AnnotatedType: AnnotatedTypeExtractor
+
+  type LazyType <: Type with AbsLazyType
+    
+  trait AbsLazyType extends AbsType {
+    override def isComplete: Boolean = false
+    override def complete(sym: Symbol)
+    override def safeToString = "<?>"
+  }
+
+  abstract class ThisTypeExtractor {
+    def apply(sym: Symbol): Type
+    def unapply(tpe: ThisType): Option[Symbol]
+  }
+
+  abstract class SingleTypeExtractor {
+    def apply(pre: Type, sym: Symbol): Type
+    def unapply(tpe: SingleType): Option[(Type, Symbol)]
+  }
+
+  abstract class SuperTypeExtractor {
+    def apply(thistpe: Type, supertpe: Type): Type
+    def unapply(tpe: SuperType): Option[(Type, Type)]
+  }
+
+  abstract class TypeRefExtractor {
+    def apply(pre: Type, sym: Symbol, args: List[Type]): Type
+    def unapply(tpe: TypeRef): Option[(Type, Symbol, List[Type])]
+  }
+
+  abstract class TypeBoundsExtractor {
+    def apply(lo: Type, hi: Type): TypeBounds
+    def unapply(tpe: TypeBounds): Option[(Type, Type)]
+  }
+
+  abstract class RefinedTypeExtractor {
+    def apply(parents: List[Type], decls: Scope): RefinedType
+    def apply(parents: List[Type], decls: Scope, clazz: Symbol): RefinedType
+    def unapply(tpe: RefinedType): Option[(List[Type], Scope)]
+  }
+
+  abstract class ClassInfoTypeExtractor {
+    def apply(parents: List[Type], decls: Scope, clazz: Symbol): ClassInfoType
+    def unapply(tpe: ClassInfoType): Option[(List[Type], Scope, Symbol)]
+  }
+
+  abstract class ConstantTypeExtractor {
+    def apply(value: Constant): ConstantType
+    def unapply(tpe: ConstantType): Option[Constant]
+  }
+
+  abstract class MethodTypeExtractor {
+    def apply(params: List[Symbol], resultType: Type): MethodType
+    def unapply(tpe: MethodType): Option[(List[Symbol], Type)]
+  }
+
+  abstract class PolyTypeExtractor {
+    def apply(typeParams: List[Symbol], resultType: Type): PolyType
+    def unapply(tpe: PolyType): Option[(List[Symbol], Type)]
+  }
+
+  abstract class ExistentialTypeExtractor {
+    def apply(quantified: List[Symbol], underlying: Type): ExistentialType
+    def unapply(tpe: ExistentialType): Option[(List[Symbol], Type)]
+  }
+
+  abstract class AnnotatedTypeExtractor {
+    def apply(annotations: List[AnnotationInfo], underlying: Type, selfsym: Symbol): AnnotatedType
+    def unapply(tpe: AnnotatedType): Option[(List[AnnotationInfo], Type, Symbol)]
+  }
+
+  /** The maximum number of recursions allowed in toString
+   */
+  final val maxTostringRecursions = 50
+
+  private var tostringRecursions = 0
+}
+
diff --git a/src/library/scala/reflect/generic/UnPickler.scala b/src/library/scala/reflect/generic/UnPickler.scala
new file mode 100644
index 0000000..d0f5a0d
--- /dev/null
+++ b/src/library/scala/reflect/generic/UnPickler.scala
@@ -0,0 +1,774 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
+ * @author  Martin Odersky
+ */
+
+package scala.reflect
+package generic
+
+import java.io.IOException
+import java.lang.{Float, Double}
+
+import Flags._
+import PickleFormat._
+import collection.mutable.{HashMap, ListBuffer}
+import annotation.switch
+
+/** @author Martin Odersky
+ *  @version 1.0
+ */
+abstract class UnPickler { 
+
+  val global: Universe
+  import global._
+
+  /** Unpickle symbol table information descending from a class and/or module root
+   *  from an array of bytes.
+   *  @param bytes      bytearray from which we unpickle
+   *  @param offset     offset from which unpickling starts
+   *  @param classroot  the top-level class which is unpickled, or NoSymbol if inapplicable
+   *  @param moduleroot the top-level module which is unpickled, or NoSymbol if inapplicable
+   *  @param filename   filename associated with bytearray, only used for error messages
+   */
+  def unpickle(bytes: Array[Byte], offset: Int, classRoot: Symbol, moduleRoot: Symbol, filename: String) {
+    try {
+      scan(bytes, offset, classRoot, moduleRoot, filename)
+    } catch {
+      case ex: IOException =>
+        throw ex
+      case ex: Throwable =>
+        /*if (settings.debug.value)*/ ex.printStackTrace()
+        throw new RuntimeException("error reading Scala signature of "+filename+": "+ex.getMessage())
+    }
+  }
+
+  /** To be implemented in subclasses. Like `unpickle` but without the catch-all error handling.
+   */
+  def scan(bytes: Array[Byte], offset: Int, classRoot: Symbol, moduleRoot: Symbol, filename: String)
+
+  abstract class Scan(bytes: Array[Byte], offset: Int, classRoot: Symbol, moduleRoot: Symbol, filename: String) extends PickleBuffer(bytes, offset, -1) {
+    //println("unpickle " + classRoot + " and " + moduleRoot)//debug
+
+    protected def debug = false
+
+    checkVersion()
+
+    /** A map from entry numbers to array offsets */
+    private val index = createIndex
+
+    /** A map from entry numbers to symbols, types, or annotations */
+    private val entries = new Array[AnyRef](index.length)
+    
+    /** A map from symbols to their associated `decls' scopes */
+    private val symScopes = new HashMap[Symbol, Scope]
+
+    //println("unpickled " + classRoot + ":" + classRoot.rawInfo + ", " + moduleRoot + ":" + moduleRoot.rawInfo);//debug
+
+    def run() {
+      for (i <- 0 until index.length) {
+        if (isSymbolEntry(i))
+          at(i, readSymbol)
+        else if (isSymbolAnnotationEntry(i))
+          at(i, {() => readSymbolAnnotation(); null})
+        else if (isChildrenEntry(i))
+          at(i, {() => readChildren(); null})
+      }
+    }
+
+    private def checkVersion() {
+      val major = readNat()
+      val minor = readNat()
+      if (major != MajorVersion || minor > MinorVersion)
+        throw new IOException("Scala signature " + classRoot.decodedName + 
+                              " has wrong version\n expected: " + 
+                              MajorVersion + "." + MinorVersion + 
+                              "\n found: " + major + "." + minor +
+                              " in "+filename)
+    }
+
+    /** The `decls' scope associated with given symbol */
+    protected def symScope(sym: Symbol) = symScopes.get(sym) match {
+      case None => val s = newScope; symScopes(sym) = s; s
+      case Some(s) => s
+    }
+
+    /** Does entry represent an (internal) symbol */
+    protected def isSymbolEntry(i: Int): Boolean = {
+      val tag = bytes(index(i)).toInt
+      (firstSymTag <= tag && tag <= lastSymTag &&
+       (tag != CLASSsym || !isRefinementSymbolEntry(i)))
+    }
+
+    /** Does entry represent an (internal or external) symbol */
+    protected def isSymbolRef(i: Int): Boolean = {
+      val tag = bytes(index(i))
+      (firstSymTag <= tag && tag <= lastExtSymTag)
+    }
+
+    /** Does entry represent a name? */
+    protected def isNameEntry(i: Int): Boolean = {
+      val tag = bytes(index(i)).toInt
+      tag == TERMname || tag == TYPEname
+    }
+
+    /** Does entry represent a symbol annotation? */
+    protected def isSymbolAnnotationEntry(i: Int): Boolean = {
+      val tag = bytes(index(i)).toInt
+      tag == SYMANNOT
+    }
+
+    /** Does the entry represent children of a symbol? */
+    protected def isChildrenEntry(i: Int): Boolean = {
+      val tag = bytes(index(i)).toInt
+      tag == CHILDREN
+    }
+
+    /** Does entry represent a refinement symbol? 
+     *  pre: Entry is a class symbol
+     */
+    protected def isRefinementSymbolEntry(i: Int): Boolean = {
+      val savedIndex = readIndex
+      readIndex = index(i)
+      val tag = readByte().toInt
+      assert(tag == CLASSsym)
+      
+      readNat(); // read length
+      val result = readNameRef() == mkTypeName(nme.REFINE_CLASS_NAME)
+      readIndex = savedIndex
+      result
+    }
+
+    /** If entry at <code>i</code> is undefined, define it by performing
+     *  operation <code>op</code> with <code>readIndex at start of i'th
+     *  entry. Restore <code>readIndex</code> afterwards.
+     */
+    protected def at[T <: AnyRef](i: Int, op: () => T): T = {
+      var r = entries(i)
+      if (r eq null) {
+        val savedIndex = readIndex
+        readIndex = index(i)
+        r = op()
+        assert(entries(i) eq null, entries(i))
+        entries(i) = r
+        readIndex = savedIndex
+      }
+      r.asInstanceOf[T]
+    }
+
+    /** Read a name */
+    protected def readName(): Name = {
+      val tag = readByte()
+      val len = readNat()
+      tag match {
+        case TERMname => newTermName(bytes, readIndex, len)
+        case TYPEname => newTypeName(bytes, readIndex, len)
+        case _ => errorBadSignature("bad name tag: " + tag)
+      }
+    }
+
+    /** Read a symbol */
+    protected def readSymbol(): Symbol = {
+      val tag = readByte()
+      val end = readNat() + readIndex
+      var sym: Symbol = NoSymbol
+      tag match {
+        case EXTref | EXTMODCLASSref =>
+          val name = readNameRef()
+          val owner = if (readIndex == end) definitions.RootClass else readSymbolRef()
+          def fromName(name: Name) = 
+            if (mkTermName(name) == nme.ROOT) definitions.RootClass
+            else if (name == nme.ROOTPKG) definitions.RootPackage
+            else if (tag == EXTref) owner.info.decl(name)
+            else owner.info.decl(name).moduleClass
+          sym = fromName(name)
+          // If sym not found try with expanded name.
+          // This can happen if references to private symbols are
+          // read from outside; for instance when checking the children of a class
+          // (see t1722)
+          if (sym == NoSymbol) sym = fromName(nme.expandedName(name, owner))
+
+          // If the owner is overloaded (i.e. a method), it's not possible to select the
+          // right member => return NoSymbol. This can only happen when unpickling a tree.
+          // the "case Apply" in readTree() takes care of selecting the correct alternative
+          //  after parsing the arguments.
+          if (sym == NoSymbol && !owner.isOverloaded) errorMissingRequirement(name, owner)
+            
+        case NONEsym =>
+          sym = NoSymbol
+
+        case _ => // symbols that were pickled with Pickler.writeSymInfo
+          var defaultGetter: Symbol = NoSymbol // @deprecated, to be removed for 2.8 final
+          var nameref = readNat()
+          if (tag == VALsym && isSymbolRef(nameref)) {  // @deprecated, to be removed for 2.8 final
+            defaultGetter = at(nameref, readSymbol)
+            nameref = readNat()
+          }
+          val name = at(nameref, readName)
+          val owner = readSymbolRef()
+          val flags = pickledToRawFlags(readLongNat())
+          var privateWithin: Symbol = NoSymbol
+          var inforef = readNat()
+          if (isSymbolRef(inforef)) {
+            privateWithin = at(inforef, readSymbol)
+            inforef = readNat()
+          }
+          tag match {
+            case TYPEsym =>
+              sym = owner.newAbstractType(name)
+            case ALIASsym =>
+              sym = owner.newAliasType(name)
+            case CLASSsym =>
+              sym = 
+                if (name == classRoot.name && owner == classRoot.owner)
+                  (if ((flags & MODULE) != 0L) moduleRoot.moduleClass
+                   else classRoot)
+                else 
+                  if ((flags & MODULE) != 0L) owner.newModuleClass(name)
+                  else owner.newClass(name)
+              if (readIndex != end) sym.typeOfThis = newLazyTypeRef(readNat())
+            case MODULEsym =>
+              val clazz = at(inforef, readType).typeSymbol
+              sym = 
+                if (name == moduleRoot.name && owner == moduleRoot.owner) moduleRoot
+                else {
+                  val m = owner.newModule(name, clazz)
+                  clazz.sourceModule = m
+                  m
+                }
+            case VALsym =>
+              sym = if (name == moduleRoot.name && owner == moduleRoot.owner) { assert(false); NoSymbol }
+                    else if ((flags & METHOD) != 0) owner.newMethod(name)
+                    else owner.newValue(name)
+            case _ =>
+              noSuchSymbolTag(tag, end, name, owner)
+          }
+          sym.flags = flags & PickledFlags
+          sym.privateWithin = privateWithin
+          if (readIndex != end) assert(sym hasFlag (SUPERACCESSOR | PARAMACCESSOR), sym)
+          if (sym hasFlag SUPERACCESSOR) assert(readIndex != end)
+          sym.info = 
+            if (readIndex != end) newLazyTypeRefAndAlias(inforef, readNat())
+            else newLazyTypeRef(inforef)
+          if (sym.owner.isClass && sym != classRoot && sym != moduleRoot && 
+              !sym.isModuleClass && !sym.isRefinementClass && !sym.isTypeParameter && !sym.isExistentiallyBound)
+            symScope(sym.owner) enter sym
+      }
+      sym
+    }
+
+    def noSuchSymbolTag(tag: Int, end: Int, name: Name, owner: Symbol) = 
+      errorBadSignature("bad symbol tag: " + tag)
+
+    /** Read a type */
+    protected def readType(): Type = {
+      val tag = readByte()
+      val end = readNat() + readIndex
+      (tag: @switch) match {
+        case NOtpe =>
+          NoType
+        case NOPREFIXtpe =>
+          NoPrefix
+        case THIStpe =>
+          ThisType(readSymbolRef())
+        case SINGLEtpe =>
+          SingleType(readTypeRef(), readSymbolRef()) // !!! was singleType
+        case SUPERtpe =>
+          val thistpe = readTypeRef()
+          val supertpe = readTypeRef()
+          SuperType(thistpe, supertpe)
+        case CONSTANTtpe =>
+          ConstantType(readConstantRef())
+        case TYPEREFtpe =>
+          val pre = readTypeRef()
+          val sym = readSymbolRef()
+          var args = until(end, readTypeRef)
+          TypeRef(pre, sym, args)
+        case TYPEBOUNDStpe =>
+          TypeBounds(readTypeRef(), readTypeRef())
+        case REFINEDtpe =>
+          val clazz = readSymbolRef()
+          RefinedType(until(end, readTypeRef), symScope(clazz), clazz)
+        case CLASSINFOtpe =>
+          val clazz = readSymbolRef()
+          ClassInfoType(until(end, readTypeRef), symScope(clazz), clazz)
+        case METHODtpe | IMPLICITMETHODtpe =>
+          val restpe = readTypeRef()
+          val params = until(end, readSymbolRef)
+          // if the method is overloaded, the params cannot be determined (see readSymbol) => return NoType.
+          // Only happen for trees, "case Apply" in readTree() takes care of selecting the correct
+          // alternative after parsing the arguments.
+          if (params.contains(NoSymbol) || restpe == NoType) NoType
+          else MethodType(params, restpe)
+        case POLYtpe =>
+          val restpe = readTypeRef()
+          val typeParams = until(end, readSymbolRef)
+          PolyType(typeParams, restpe)
+        case EXISTENTIALtpe =>
+          val restpe = readTypeRef()
+          ExistentialType(until(end, readSymbolRef), restpe)
+        case ANNOTATEDtpe =>
+          var typeRef = readNat()
+          val selfsym = if (isSymbolRef(typeRef)) {
+            val s = at(typeRef, readSymbol)
+            typeRef = readNat()
+            s
+          } else NoSymbol // selfsym can go.
+          val tp = at(typeRef, readType)
+          val annots = until(end, readAnnotationRef)
+          if (selfsym == NoSymbol) AnnotatedType(annots, tp, selfsym)
+          else tp 
+        case _ =>
+          noSuchTypeTag(tag, end)
+      }
+    }
+
+    def noSuchTypeTag(tag: Int, end: Int): Type =
+      errorBadSignature("bad type tag: " + tag)
+
+    /** Read a constant */
+    protected def readConstant(): Constant = {
+      val tag = readByte().toInt
+      val len = readNat()
+      (tag: @switch) match {
+        case LITERALunit    => Constant(())
+        case LITERALboolean => Constant(readLong(len) != 0L)
+        case LITERALbyte    => Constant(readLong(len).toByte)
+        case LITERALshort   => Constant(readLong(len).toShort)
+        case LITERALchar    => Constant(readLong(len).toChar)
+        case LITERALint     => Constant(readLong(len).toInt)
+        case LITERALlong    => Constant(readLong(len))
+        case LITERALfloat   => Constant(Float.intBitsToFloat(readLong(len).toInt))
+        case LITERALdouble  => Constant(Double.longBitsToDouble(readLong(len)))
+        case LITERALstring  => Constant(readNameRef().toString())
+        case LITERALnull    => Constant(null)
+        case LITERALclass   => Constant(readTypeRef())
+        case LITERALenum    => Constant(readSymbolRef())
+        case _              => noSuchConstantTag(tag, len)
+      }
+    }
+
+    def noSuchConstantTag(tag: Int, len: Int): Constant =
+      errorBadSignature("bad constant tag: " + tag)
+
+    /** Read children and store them into the corresponding symbol.
+     */
+    protected def readChildren() {
+      val tag = readByte()
+      assert(tag == CHILDREN)
+      val end = readNat() + readIndex
+      val target = readSymbolRef()
+      while (readIndex != end) target addChild readSymbolRef()
+    }
+
+    /** Read an annotation argument, which is pickled either
+     *  as a Constant or a Tree.
+     */
+    protected def readAnnotArg(i: Int): Tree = {
+      if (bytes(index(i)) == TREE) {
+        at(i, readTree)
+      } else {
+        val const = at(i, readConstant)
+        global.Literal(const).setType(const.tpe)
+      }
+    }
+
+    /** Read a ClassfileAnnotArg (argument to a classfile annotation)
+     */
+    protected def readClassfileAnnotArg(i: Int): ClassfileAnnotArg = bytes(index(i)) match {
+      case ANNOTINFO =>
+        NestedAnnotArg(at(i, readAnnotation))
+      case ANNOTARGARRAY =>
+        at(i, () => {
+          readByte() // skip the `annotargarray` tag
+          val end = readNat() + readIndex
+          ArrayAnnotArg(until(end, () => readClassfileAnnotArg(readNat())).toArray(classfileAnnotArgManifest))
+        })
+      case _ =>
+        LiteralAnnotArg(at(i, readConstant))
+    }
+
+    /** Read an AnnotationInfo. Not to be called directly, use
+     *  readAnnotation or readSymbolAnnotation
+     */
+    protected def readAnnotationInfo(end: Int): AnnotationInfo = {
+      val atp = readTypeRef()
+      val args = new ListBuffer[Tree]
+      val assocs = new ListBuffer[(Name, ClassfileAnnotArg)]
+      while (readIndex != end) {
+        val argref = readNat()
+        if (isNameEntry(argref)) {
+          val name = at(argref, readName)
+          val arg = readClassfileAnnotArg(readNat())
+          assocs += ((name, arg))
+        }
+        else
+          args += readAnnotArg(argref)
+      }
+      AnnotationInfo(atp, args.toList, assocs.toList)
+    }
+
+    /** Read an annotation and as a side effect store it into
+     *  the symbol it requests. Called at top-level, for all
+     *  (symbol, annotInfo) entries. */
+    protected def readSymbolAnnotation() {
+      val tag = readByte()
+      if (tag != SYMANNOT)
+        errorBadSignature("symbol annotation expected ("+ tag +")")
+      val end = readNat() + readIndex
+      val target = readSymbolRef()
+      target.addAnnotation(readAnnotationInfo(end))
+    }
+
+    /** Read an annotation and return it. Used when unpickling
+     *  an ANNOTATED(WSELF)tpe or a NestedAnnotArg */
+    protected def readAnnotation(): AnnotationInfo = {
+      val tag = readByte()
+      if (tag != ANNOTINFO)
+        errorBadSignature("annotation expected (" + tag + ")")
+      val end = readNat() + readIndex
+      readAnnotationInfo(end)
+    }
+
+    /* Read an abstract syntax tree */
+    protected def readTree(): Tree = {
+      val outerTag = readByte()
+      if (outerTag != TREE)
+        errorBadSignature("tree expected (" + outerTag + ")")
+      val end = readNat() + readIndex
+      val tag = readByte()
+      val tpe = if (tag == EMPTYtree) NoType else readTypeRef()
+      
+      // Set by the three functions to follow.  If symbol is non-null
+      // after the the new tree 't' has been created, t has its Symbol
+      // set to symbol; and it always has its Type set to tpe.
+      var symbol: Symbol = null
+      var mods: Modifiers = null
+      var name: Name = null
+
+      /** Read a Symbol, Modifiers, and a Name */
+      def setSymModsName() {
+        symbol = readSymbolRef()
+        mods = readModifiersRef()
+        name = readNameRef()
+      }
+      /** Read a Symbol and a Name */
+      def setSymName() {
+        symbol = readSymbolRef()
+        name = readNameRef()
+      }
+      /** Read a Symbol */
+      def setSym() {
+        symbol = readSymbolRef()
+      }
+
+      val t = tag match {
+        case EMPTYtree =>
+          EmptyTree
+
+        case PACKAGEtree =>
+          setSym()
+          // val discardedSymbol = readSymbolRef()  // XXX is symbol intentionally not set?
+          val pid = readTreeRef().asInstanceOf[RefTree]
+          val stats = until(end, readTreeRef)
+          PackageDef(pid, stats)
+
+        case CLASStree =>
+          setSymModsName()
+          val impl = readTemplateRef()
+          val tparams = until(end, readTypeDefRef)
+          ClassDef(mods, name, tparams, impl)
+
+        case MODULEtree =>
+          setSymModsName()
+          ModuleDef(mods, name, readTemplateRef())
+
+        case VALDEFtree =>
+          setSymModsName()
+          val tpt = readTreeRef()
+          val rhs = readTreeRef()
+          ValDef(mods, name, tpt, rhs)
+
+        case DEFDEFtree =>
+          setSymModsName()
+          val tparams = times(readNat(), readTypeDefRef)
+          val vparamss = times(readNat(), () => times(readNat(), readValDefRef))
+          val tpt = readTreeRef()
+          val rhs = readTreeRef()
+          
+          DefDef(mods, name, tparams, vparamss, tpt, rhs)
+
+        case TYPEDEFtree =>
+          setSymModsName()
+          val rhs = readTreeRef()
+          val tparams = until(end, readTypeDefRef)
+          TypeDef(mods, name, tparams, rhs)
+
+        case LABELtree =>
+          setSymName()
+          val rhs = readTreeRef()
+          val params = until(end, readIdentRef)
+          LabelDef(name, params, rhs)
+
+        case IMPORTtree =>
+          setSym()
+          val expr = readTreeRef()
+          val selectors = until(end, () => {
+            val from = readNameRef()
+            val to = readNameRef()
+            ImportSelector(from, -1, to, -1)
+          })
+
+          Import(expr, selectors)
+
+        case TEMPLATEtree =>
+          setSym()
+          val parents = times(readNat(), readTreeRef)
+          val self = readValDefRef()
+          val body = until(end, readTreeRef)
+
+          Template(parents, self, body)
+
+        case BLOCKtree =>
+          val expr = readTreeRef()
+          val stats = until(end, readTreeRef)
+          Block(stats, expr)
+
+        case CASEtree =>
+          val pat = readTreeRef()
+          val guard = readTreeRef()
+          val body = readTreeRef()
+          CaseDef(pat, guard, body)
+
+        case ALTERNATIVEtree =>
+          Alternative(until(end, readTreeRef))
+
+        case STARtree =>
+          Star(readTreeRef())
+
+        case BINDtree =>
+          setSymName()
+          Bind(name, readTreeRef())
+
+        case UNAPPLYtree =>
+          val fun = readTreeRef()
+          val args = until(end, readTreeRef)
+          UnApply(fun, args)
+
+        case ARRAYVALUEtree =>
+          val elemtpt = readTreeRef()
+          val trees = until(end, readTreeRef)
+          ArrayValue(elemtpt, trees)
+
+        case FUNCTIONtree =>
+          setSym()
+          val body = readTreeRef()
+          val vparams = until(end, readValDefRef)
+          Function(vparams, body)
+
+        case ASSIGNtree =>
+          val lhs = readTreeRef()
+          val rhs = readTreeRef()
+          Assign(lhs, rhs)
+
+        case IFtree =>
+          val cond = readTreeRef()
+          val thenp = readTreeRef()
+          val elsep = readTreeRef()
+          If(cond, thenp, elsep)
+
+        case MATCHtree =>
+          val selector = readTreeRef()
+          val cases = until(end, readCaseDefRef)
+          Match(selector, cases)
+
+        case RETURNtree =>
+          setSym()
+          Return(readTreeRef())
+
+        case TREtree =>
+          val block = readTreeRef()
+          val finalizer = readTreeRef()
+          val catches = until(end, readCaseDefRef)
+          Try(block, catches, finalizer)
+
+        case THROWtree =>
+          Throw(readTreeRef())
+
+        case NEWtree =>
+          New(readTreeRef())
+
+        case TYPEDtree =>
+          val expr = readTreeRef()
+          val tpt = readTreeRef()
+          Typed(expr, tpt)
+
+        case TYPEAPPLYtree =>
+          val fun = readTreeRef()
+          val args = until(end, readTreeRef)
+          TypeApply(fun, args)
+
+        case APPLYtree =>
+          val fun = readTreeRef()
+          val args = until(end, readTreeRef)
+          if (fun.symbol.isOverloaded) {
+            fun.setType(fun.symbol.info)
+            inferMethodAlternative(fun, args map (_.tpe), tpe)
+          }
+          Apply(fun, args)
+
+        case APPLYDYNAMICtree =>
+          setSym()
+          val qual = readTreeRef()
+          val args = until(end, readTreeRef)
+          ApplyDynamic(qual, args)
+
+        case SUPERtree =>
+          setSym()
+          val qual = readNameRef()
+          val mix = readNameRef()
+          Super(qual, mix)
+
+        case THIStree =>
+          setSym()
+          This(readNameRef())
+
+        case SELECTtree =>
+          setSym()
+          val qualifier = readTreeRef()
+          val selector = readNameRef()
+          Select(qualifier, selector)
+
+        case IDENTtree =>
+          setSymName()
+          Ident(name)
+
+        case LITERALtree =>
+          global.Literal(readConstantRef())
+
+        case TYPEtree =>
+          TypeTree()
+
+        case ANNOTATEDtree =>
+          val annot = readTreeRef()
+          val arg = readTreeRef()
+          Annotated(annot, arg)
+
+        case SINGLETONTYPEtree =>
+          SingletonTypeTree(readTreeRef())
+
+        case SELECTFROMTYPEtree =>
+          val qualifier = readTreeRef()
+          val selector = readNameRef()
+          SelectFromTypeTree(qualifier, selector)
+
+        case COMPOUNDTYPEtree =>
+          CompoundTypeTree(readTemplateRef())
+
+        case APPLIEDTYPEtree =>
+          val tpt = readTreeRef()
+          val args = until(end, readTreeRef)
+          AppliedTypeTree(tpt, args)
+
+        case TYPEBOUNDStree =>
+          val lo = readTreeRef()
+          val hi = readTreeRef()
+          TypeBoundsTree(lo, hi)
+
+        case EXISTENTIALTYPEtree =>
+          val tpt = readTreeRef()
+          val whereClauses = until(end, readTreeRef)
+          ExistentialTypeTree(tpt, whereClauses)
+
+        case _ =>
+          noSuchTreeTag(tag, end)
+      }
+
+      if (symbol == null) t setType tpe
+      else t setSymbol symbol setType tpe      
+    }
+
+    def noSuchTreeTag(tag: Int, end: Int) = 
+      errorBadSignature("unknown tree type (" + tag + ")")
+
+    def readModifiers(): Modifiers = {
+      val tag = readNat()
+      if (tag != MODIFIERS)
+        errorBadSignature("expected a modifiers tag (" + tag + ")")
+      val end = readNat() + readIndex
+      val pflagsHi = readNat()
+      val pflagsLo = readNat()
+      val pflags = (pflagsHi.toLong << 32) + pflagsLo
+      val flags = pickledToRawFlags(pflags)
+      val privateWithin = readNameRef()
+      Modifiers(flags, privateWithin, Nil, Map.empty)
+    }
+
+    /* Read a reference to a pickled item */
+    protected def readNameRef(): Name = at(readNat(), readName)
+    protected def readSymbolRef(): Symbol = at(readNat(), readSymbol)
+    protected def readTypeRef(): Type = at(readNat(), readType)
+    protected def readConstantRef(): Constant = at(readNat(), readConstant)
+    protected def readAnnotationRef(): AnnotationInfo =
+      at(readNat(), readAnnotation)
+    protected def readModifiersRef(): Modifiers =
+      at(readNat(), readModifiers)
+    protected def readTreeRef(): Tree =
+      at(readNat(), readTree)
+
+    protected def readTemplateRef(): Template =
+      readTreeRef() match {
+        case templ:Template => templ
+        case other =>
+          errorBadSignature("expected a template (" + other + ")")
+      }
+    protected def readCaseDefRef(): CaseDef =
+      readTreeRef() match {
+        case tree:CaseDef => tree
+        case other =>
+          errorBadSignature("expected a case def (" + other + ")")
+      }
+    protected def readValDefRef(): ValDef =
+      readTreeRef() match {
+        case tree:ValDef => tree
+        case other =>
+          errorBadSignature("expected a ValDef (" + other + ")")
+      }
+    protected def readIdentRef(): Ident =
+      readTreeRef() match {
+        case tree:Ident => tree
+        case other =>
+          errorBadSignature("expected an Ident (" + other + ")")
+      }
+    protected def readTypeDefRef(): TypeDef =
+      readTreeRef() match {
+        case tree:TypeDef => tree
+        case other =>
+          errorBadSignature("expected an TypeDef (" + other + ")")
+      }
+
+    protected def errorBadSignature(msg: String) =
+      throw new RuntimeException("malformed Scala signature of " + classRoot.name + " at " + readIndex + "; " + msg)
+
+    protected def errorMissingRequirement(msg: String): Nothing =
+      if (debug) errorBadSignature(msg)
+      else throw new IOException("class file needed by "+classRoot.name+" is missing.\n"+msg) 
+
+    protected def errorMissingRequirement(name: Name, owner: Symbol): Nothing = 
+      errorMissingRequirement("reference " + NameTransformer.decode(name.toString) + " of " + owner.tpe + " refers to nonexisting symbol.")
+
+    /** pre: `fun` points to a symbol with an overloaded type.
+     *  Selects the overloaded alternative of `fun` which best matches given
+     *  argument types `argtpes` and result type `restpe`. Stores this alternative as
+     *  the symbol of `fun`.
+     */
+    def inferMethodAlternative(fun: Tree, argtpes: List[Type], restpe: Type)
+
+    /** Create a lazy type which when completed returns type at index `i`. */
+    def newLazyTypeRef(i: Int): LazyType
+
+    /** Create a lazy type which when completed returns type at index `i` and sets alias
+     *  of completed symbol to symbol at index `j`
+     */
+    def newLazyTypeRefAndAlias(i: Int, j: Int): LazyType
+  }
+}
diff --git a/src/library/scala/reflect/generic/Universe.scala b/src/library/scala/reflect/generic/Universe.scala
new file mode 100644
index 0000000..91dfb2d
--- /dev/null
+++ b/src/library/scala/reflect/generic/Universe.scala
@@ -0,0 +1,16 @@
+package scala.reflect
+package generic
+
+abstract class Universe extends Symbols
+                           with Types 
+                           with Constants 
+                           with Scopes
+                           with Names
+                           with StdNames
+                           with Trees
+                           with AnnotationInfos
+                           with StandardDefinitions {
+  type Position
+  val NoPosition: Position
+}
+    
diff --git a/src/library/scala/remote.scala b/src/library/scala/remote.scala
index c352a19..bcbc597 100644
--- a/src/library/scala/remote.scala
+++ b/src/library/scala/remote.scala
@@ -1,20 +1,16 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: remote.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala
 
 /**
  * An annotation that designates the class to which it is applied as remotable.
- *
- * @see Method <a href="ScalaObject.html#$tag()">$tag</a> in trait
- *      <a href="ScalaObject.html">scala.ScalaObject</a>.
  */
 class remote extends StaticAnnotation {}
diff --git a/src/library/scala/runtime/AbstractFunction0.scala b/src/library/scala/runtime/AbstractFunction0.scala
new file mode 100644
index 0000000..0856489
--- /dev/null
+++ b/src/library/scala/runtime/AbstractFunction0.scala
@@ -0,0 +1,19 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+// $Id$
+
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  
+
+package scala.runtime
+
+
+
+abstract class AbstractFunction0[@specialized +R] extends Function0[R] {
+
+}
diff --git a/src/library/scala/runtime/AbstractFunction1.scala b/src/library/scala/runtime/AbstractFunction1.scala
new file mode 100644
index 0000000..8689eb3
--- /dev/null
+++ b/src/library/scala/runtime/AbstractFunction1.scala
@@ -0,0 +1,18 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  
+
+package scala.runtime
+
+
+
+abstract class AbstractFunction1[@specialized(scala.Int, scala.Long, scala.Float, scala.Double) -T1, @specialized(scala.Unit, scala.Boolean, scala.Int, scala.Float, scala.Long, scala.Double) +R] extends Function1[T1, R] {
+
+}
diff --git a/src/library/scala/runtime/AbstractFunction10.scala b/src/library/scala/runtime/AbstractFunction10.scala
new file mode 100644
index 0000000..cdb30df
--- /dev/null
+++ b/src/library/scala/runtime/AbstractFunction10.scala
@@ -0,0 +1,18 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  
+
+package scala.runtime
+
+
+
+abstract class AbstractFunction10[-T1, -T2, -T3, -T4, -T5, -T6, -T7, -T8, -T9, -T10, +R] extends Function10[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, R] {
+
+}
diff --git a/src/library/scala/runtime/AbstractFunction11.scala b/src/library/scala/runtime/AbstractFunction11.scala
new file mode 100644
index 0000000..430b1d9
--- /dev/null
+++ b/src/library/scala/runtime/AbstractFunction11.scala
@@ -0,0 +1,18 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  
+
+package scala.runtime
+
+
+
+abstract class AbstractFunction11[-T1, -T2, -T3, -T4, -T5, -T6, -T7, -T8, -T9, -T10, -T11, +R] extends Function11[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, R] {
+
+}
diff --git a/src/library/scala/runtime/AbstractFunction12.scala b/src/library/scala/runtime/AbstractFunction12.scala
new file mode 100644
index 0000000..665b5a6
--- /dev/null
+++ b/src/library/scala/runtime/AbstractFunction12.scala
@@ -0,0 +1,18 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  
+
+package scala.runtime
+
+
+
+abstract class AbstractFunction12[-T1, -T2, -T3, -T4, -T5, -T6, -T7, -T8, -T9, -T10, -T11, -T12, +R] extends Function12[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, R] {
+
+}
diff --git a/src/library/scala/runtime/AbstractFunction13.scala b/src/library/scala/runtime/AbstractFunction13.scala
new file mode 100644
index 0000000..be25f4b
--- /dev/null
+++ b/src/library/scala/runtime/AbstractFunction13.scala
@@ -0,0 +1,18 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  
+
+package scala.runtime
+
+
+
+abstract class AbstractFunction13[-T1, -T2, -T3, -T4, -T5, -T6, -T7, -T8, -T9, -T10, -T11, -T12, -T13, +R] extends Function13[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, R] {
+
+}
diff --git a/src/library/scala/runtime/AbstractFunction14.scala b/src/library/scala/runtime/AbstractFunction14.scala
new file mode 100644
index 0000000..8a60161
--- /dev/null
+++ b/src/library/scala/runtime/AbstractFunction14.scala
@@ -0,0 +1,18 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  
+
+package scala.runtime
+
+
+
+abstract class AbstractFunction14[-T1, -T2, -T3, -T4, -T5, -T6, -T7, -T8, -T9, -T10, -T11, -T12, -T13, -T14, +R] extends Function14[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, R] {
+
+}
diff --git a/src/library/scala/runtime/AbstractFunction15.scala b/src/library/scala/runtime/AbstractFunction15.scala
new file mode 100644
index 0000000..45b6574
--- /dev/null
+++ b/src/library/scala/runtime/AbstractFunction15.scala
@@ -0,0 +1,18 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  
+
+package scala.runtime
+
+
+
+abstract class AbstractFunction15[-T1, -T2, -T3, -T4, -T5, -T6, -T7, -T8, -T9, -T10, -T11, -T12, -T13, -T14, -T15, +R] extends Function15[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, R] {
+
+}
diff --git a/src/library/scala/runtime/AbstractFunction16.scala b/src/library/scala/runtime/AbstractFunction16.scala
new file mode 100644
index 0000000..329e196
--- /dev/null
+++ b/src/library/scala/runtime/AbstractFunction16.scala
@@ -0,0 +1,18 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  
+
+package scala.runtime
+
+
+
+abstract class AbstractFunction16[-T1, -T2, -T3, -T4, -T5, -T6, -T7, -T8, -T9, -T10, -T11, -T12, -T13, -T14, -T15, -T16, +R] extends Function16[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, R] {
+
+}
diff --git a/src/library/scala/runtime/AbstractFunction17.scala b/src/library/scala/runtime/AbstractFunction17.scala
new file mode 100644
index 0000000..93a6614
--- /dev/null
+++ b/src/library/scala/runtime/AbstractFunction17.scala
@@ -0,0 +1,18 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  
+
+package scala.runtime
+
+
+
+abstract class AbstractFunction17[-T1, -T2, -T3, -T4, -T5, -T6, -T7, -T8, -T9, -T10, -T11, -T12, -T13, -T14, -T15, -T16, -T17, +R] extends Function17[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, R] {
+
+}
diff --git a/src/library/scala/runtime/AbstractFunction18.scala b/src/library/scala/runtime/AbstractFunction18.scala
new file mode 100644
index 0000000..bb7dff8
--- /dev/null
+++ b/src/library/scala/runtime/AbstractFunction18.scala
@@ -0,0 +1,18 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  
+
+package scala.runtime
+
+
+
+abstract class AbstractFunction18[-T1, -T2, -T3, -T4, -T5, -T6, -T7, -T8, -T9, -T10, -T11, -T12, -T13, -T14, -T15, -T16, -T17, -T18, +R] extends Function18[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, R] {
+
+}
diff --git a/src/library/scala/runtime/AbstractFunction19.scala b/src/library/scala/runtime/AbstractFunction19.scala
new file mode 100644
index 0000000..8278b58
--- /dev/null
+++ b/src/library/scala/runtime/AbstractFunction19.scala
@@ -0,0 +1,18 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  
+
+package scala.runtime
+
+
+
+abstract class AbstractFunction19[-T1, -T2, -T3, -T4, -T5, -T6, -T7, -T8, -T9, -T10, -T11, -T12, -T13, -T14, -T15, -T16, -T17, -T18, -T19, +R] extends Function19[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, R] {
+
+}
diff --git a/src/library/scala/runtime/AbstractFunction2.scala b/src/library/scala/runtime/AbstractFunction2.scala
new file mode 100644
index 0000000..6bfa629
--- /dev/null
+++ b/src/library/scala/runtime/AbstractFunction2.scala
@@ -0,0 +1,18 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  
+
+package scala.runtime
+
+
+
+abstract class AbstractFunction2[@specialized(scala.Int, scala.Long, scala.Double) -T1, @specialized(scala.Int, scala.Long, scala.Double) -T2, @specialized(scala.Unit, scala.Boolean, scala.Int, scala.Float, scala.Long, scala.Double) +R] extends Function2[T1, T2, R] {
+
+}
diff --git a/src/library/scala/runtime/AbstractFunction20.scala b/src/library/scala/runtime/AbstractFunction20.scala
new file mode 100644
index 0000000..c0b32af
--- /dev/null
+++ b/src/library/scala/runtime/AbstractFunction20.scala
@@ -0,0 +1,18 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  
+
+package scala.runtime
+
+
+
+abstract class AbstractFunction20[-T1, -T2, -T3, -T4, -T5, -T6, -T7, -T8, -T9, -T10, -T11, -T12, -T13, -T14, -T15, -T16, -T17, -T18, -T19, -T20, +R] extends Function20[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, R] {
+
+}
diff --git a/src/library/scala/runtime/AbstractFunction21.scala b/src/library/scala/runtime/AbstractFunction21.scala
new file mode 100644
index 0000000..9db8788
--- /dev/null
+++ b/src/library/scala/runtime/AbstractFunction21.scala
@@ -0,0 +1,18 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  
+
+package scala.runtime
+
+
+
+abstract class AbstractFunction21[-T1, -T2, -T3, -T4, -T5, -T6, -T7, -T8, -T9, -T10, -T11, -T12, -T13, -T14, -T15, -T16, -T17, -T18, -T19, -T20, -T21, +R] extends Function21[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, R] {
+
+}
diff --git a/src/library/scala/runtime/AbstractFunction22.scala b/src/library/scala/runtime/AbstractFunction22.scala
new file mode 100644
index 0000000..cef231f
--- /dev/null
+++ b/src/library/scala/runtime/AbstractFunction22.scala
@@ -0,0 +1,18 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  
+
+package scala.runtime
+
+
+
+abstract class AbstractFunction22[-T1, -T2, -T3, -T4, -T5, -T6, -T7, -T8, -T9, -T10, -T11, -T12, -T13, -T14, -T15, -T16, -T17, -T18, -T19, -T20, -T21, -T22, +R] extends Function22[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, R] {
+
+}
diff --git a/src/library/scala/runtime/AbstractFunction3.scala b/src/library/scala/runtime/AbstractFunction3.scala
new file mode 100644
index 0000000..31bd4e3
--- /dev/null
+++ b/src/library/scala/runtime/AbstractFunction3.scala
@@ -0,0 +1,18 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  
+
+package scala.runtime
+
+
+
+abstract class AbstractFunction3[-T1, -T2, -T3, +R] extends Function3[T1, T2, T3, R] {
+
+}
diff --git a/src/library/scala/runtime/AbstractFunction4.scala b/src/library/scala/runtime/AbstractFunction4.scala
new file mode 100644
index 0000000..cce976a
--- /dev/null
+++ b/src/library/scala/runtime/AbstractFunction4.scala
@@ -0,0 +1,18 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  
+
+package scala.runtime
+
+
+
+abstract class AbstractFunction4[-T1, -T2, -T3, -T4, +R] extends Function4[T1, T2, T3, T4, R] {
+
+}
diff --git a/src/library/scala/runtime/AbstractFunction5.scala b/src/library/scala/runtime/AbstractFunction5.scala
new file mode 100644
index 0000000..278256b
--- /dev/null
+++ b/src/library/scala/runtime/AbstractFunction5.scala
@@ -0,0 +1,18 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  
+
+package scala.runtime
+
+
+
+abstract class AbstractFunction5[-T1, -T2, -T3, -T4, -T5, +R] extends Function5[T1, T2, T3, T4, T5, R] {
+
+}
diff --git a/src/library/scala/runtime/AbstractFunction6.scala b/src/library/scala/runtime/AbstractFunction6.scala
new file mode 100644
index 0000000..fa91ec1
--- /dev/null
+++ b/src/library/scala/runtime/AbstractFunction6.scala
@@ -0,0 +1,18 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  
+
+package scala.runtime
+
+
+
+abstract class AbstractFunction6[-T1, -T2, -T3, -T4, -T5, -T6, +R] extends Function6[T1, T2, T3, T4, T5, T6, R] {
+
+}
diff --git a/src/library/scala/runtime/AbstractFunction7.scala b/src/library/scala/runtime/AbstractFunction7.scala
new file mode 100644
index 0000000..7691b02
--- /dev/null
+++ b/src/library/scala/runtime/AbstractFunction7.scala
@@ -0,0 +1,18 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  
+
+package scala.runtime
+
+
+
+abstract class AbstractFunction7[-T1, -T2, -T3, -T4, -T5, -T6, -T7, +R] extends Function7[T1, T2, T3, T4, T5, T6, T7, R] {
+
+}
diff --git a/src/library/scala/runtime/AbstractFunction8.scala b/src/library/scala/runtime/AbstractFunction8.scala
new file mode 100644
index 0000000..f070ca4
--- /dev/null
+++ b/src/library/scala/runtime/AbstractFunction8.scala
@@ -0,0 +1,18 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  
+
+package scala.runtime
+
+
+
+abstract class AbstractFunction8[-T1, -T2, -T3, -T4, -T5, -T6, -T7, -T8, +R] extends Function8[T1, T2, T3, T4, T5, T6, T7, T8, R] {
+
+}
diff --git a/src/library/scala/runtime/AbstractFunction9.scala b/src/library/scala/runtime/AbstractFunction9.scala
new file mode 100644
index 0000000..b07df02
--- /dev/null
+++ b/src/library/scala/runtime/AbstractFunction9.scala
@@ -0,0 +1,18 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+// generated by genprod on Thu Apr 29 17:52:16 CEST 2010  
+
+package scala.runtime
+
+
+
+abstract class AbstractFunction9[-T1, -T2, -T3, -T4, -T5, -T6, -T7, -T8, -T9, +R] extends Function9[T1, T2, T3, T4, T5, T6, T7, T8, T9, R] {
+
+}
diff --git a/src/library/scala/runtime/AnyValCompanion.scala b/src/library/scala/runtime/AnyValCompanion.scala
new file mode 100644
index 0000000..5032789
--- /dev/null
+++ b/src/library/scala/runtime/AnyValCompanion.scala
@@ -0,0 +1,86 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.runtime
+
+/** A common supertype for companion classes of primitive types.
+ *
+ *  A common trait for /companion/ objects of primitive types comes handy
+ *  when parameterizing code on types. For instance, the specialized
+ *  annotation is passed a sequence of types on which to specialize:
+ *  {{{
+ *     class Tuple1[@specialized(Unit, Int, Double) T]
+ *  }}}
+ * 
+ */
+sealed trait AnyValCompanion
+
+/** A object representing 'object scala.Unit'. It should never be used
+ *  directly.
+ */
+object Unit extends AnyValCompanion {
+  override def toString = "object scala.Unit"
+}
+
+/** A object representing 'object scala.Boolean'. It should never be used
+ *  directly.
+ */
+object Boolean extends AnyValCompanion {
+  override def toString = "object scala.Boolean"
+}
+
+/** A object representing 'object scala.Byte'. It should never be used
+ *  directly.
+ */
+object Byte extends AnyValCompanion {
+  override def toString = "object scala.Byte"
+}
+
+/** A object representing 'object scala.Short'. It should never be used
+ *  directly.
+ */
+object Short extends AnyValCompanion {
+  override def toString = "object scala.Short"
+}
+
+/** A object representing 'object scala.Char'. It should never be used
+ *  directly.
+ */
+object Char extends AnyValCompanion {
+  override def toString = "object scala.Char"
+}
+
+/** A object representing 'object scala.Int'. It should never be used
+ *  directly.
+ */
+object Int extends AnyValCompanion {
+  override def toString = "object scala.Int"
+}
+
+/** A object representing 'object scala.Long'. It should never be used
+ *  directly.
+ */
+object Long extends AnyValCompanion {
+  override def toString = "object scala.Long"
+}
+
+/** A object representing 'object scala.Float'. It should never be used
+ *  directly.
+ */
+object Float extends AnyValCompanion {
+  override def toString = "object scala.Float"
+}
+
+/** A object representing 'object scala.Double'. It should never be used
+ *  directly.
+ */
+object Double extends AnyValCompanion {
+  override def toString = "object scala.Double"
+}
diff --git a/src/library/scala/runtime/ArrayRuntime.java b/src/library/scala/runtime/ArrayRuntime.java
new file mode 100644
index 0000000..b382fdf
--- /dev/null
+++ b/src/library/scala/runtime/ArrayRuntime.java
@@ -0,0 +1,16 @@
+package scala.runtime;
+
+/**
+ * Methods on Java arrays
+ */
+class ArrayRuntime {
+  static boolean[] cloneArray(boolean[] array) { return array.clone(); }
+  static byte[] cloneArray(byte[] array) { return array.clone(); }
+  static short[] cloneArray(short[] array) { return array.clone(); }
+  static char[] cloneArray(char[] array) { return array.clone(); }
+  static int[] cloneArray(int[] array) { return array.clone(); }
+  static long[] cloneArray(long[] array) { return array.clone(); }
+  static float[] cloneArray(float[] array) { return array.clone(); }
+  static double[] cloneArray(double[] array) { return array.clone(); }
+  static Object[] cloneArray(Object[] array) { return array.clone(); }
+}
diff --git a/src/library/scala/runtime/BooleanRef.java b/src/library/scala/runtime/BooleanRef.java
index 3580122..bf43b47 100644
--- a/src/library/scala/runtime/BooleanRef.java
+++ b/src/library/scala/runtime/BooleanRef.java
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: BooleanRef.java 16881 2009-01-09 16:28:11Z cunei $
 
 
 package scala.runtime;
diff --git a/src/library/scala/runtime/Boxed.scala b/src/library/scala/runtime/Boxed.scala
new file mode 100644
index 0000000..96c7638
--- /dev/null
+++ b/src/library/scala/runtime/Boxed.scala
@@ -0,0 +1,17 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.runtime
+
+trait Boxed {
+
+}
+  
+  
diff --git a/src/library/scala/runtime/BoxedAnyArray.scala b/src/library/scala/runtime/BoxedAnyArray.scala
deleted file mode 100644
index 1b7db44..0000000
--- a/src/library/scala/runtime/BoxedAnyArray.scala
+++ /dev/null
@@ -1,320 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: BoxedAnyArray.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala.runtime
-
-
-import Predef._
-import compat.Platform
-
-/**
- * Arrays created by <code>new Array[T](length)</code> where <code>T</code>
- * is a type variable.
- *
- * @author Martin Odersky
- */
- at serializable
-final class BoxedAnyArray(val length: Int) extends BoxedArray {
-
-  def this(dim1: Int, dim2: Int) = {
-    this(dim1);
-    initializeWith(i => new BoxedAnyArray(dim2))
-  }
-
-  def this(dim1: Int, dim2: Int, dim3: Int) = {
-    this(dim1);
-    initializeWith(i => new BoxedAnyArray(dim2, dim3))
-  }
-
-  def this(dim1: Int, dim2: Int, dim3: Int, dim4: Int) = {
-    this(dim1);
-    initializeWith(i => new BoxedAnyArray(dim2, dim3, dim4))
-  }
-
-  def this(dim1: Int, dim2: Int, dim3: Int, dim4: Int, dim5: Int) = {
-    this(dim1);
-    initializeWith(i => new BoxedAnyArray(dim2, dim3, dim4, dim5))
-  }
-
-  def this(dim1: Int, dim2: Int, dim3: Int, dim4: Int, dim5: Int, dim6: Int) = {
-    this(dim1);
-    initializeWith(i => new BoxedAnyArray(dim2, dim3, dim4, dim5, dim6))
-  }
-
-  def this(dim1: Int, dim2: Int, dim3: Int, dim4: Int, dim5: Int, dim6: Int, dim7: Int) = {
-    this(dim1);
-    initializeWith(i => new BoxedAnyArray(dim2, dim3, dim4, dim5, dim6, dim7))
-  }
-
-  def this(dim1: Int, dim2: Int, dim3: Int, dim4: Int, dim5: Int, dim6: Int, dim7: Int, dim8: Int) = {
-    this(dim1);
-    initializeWith(i => new BoxedAnyArray(dim2, dim3, dim4, dim5, dim6, dim7, dim8))
-  }
-
-  def this(dim1: Int, dim2: Int, dim3: Int, dim4: Int, dim5: Int, dim6: Int, dim7: Int, dim8: Int, dim9: Int) = {
-    this(dim1);
-    initializeWith(i => new BoxedAnyArray(dim2, dim3, dim4, dim5, dim6, dim7, dim8, dim9))
-  }
-
-  private def initializeWith(elem: Int => Any) = {
-    for (i <- 0 until length) update(i, elem(i))
-  }
-
-  private var boxed = new Array[AnyRef](length)
-  private val hash = boxed.hashCode()
-  private var unboxed: AnyRef = null
-  private var elemClass: Class[_] = null
-
-  def apply(index: Int): Any = synchronized {
-    if (unboxed eq null)
-      boxed(index);
-    else if (elemClass eq classOf[Int])
-      Int.box(unboxed.asInstanceOf[Array[Int]](index))
-    else if (elemClass eq classOf[Double])
-      Double.box(unboxed.asInstanceOf[Array[Double]](index))
-    else if (elemClass eq classOf[Float])
-      Float.box(unboxed.asInstanceOf[Array[Float]](index))
-    else if (elemClass eq classOf[Long])
-      Long.box(unboxed.asInstanceOf[Array[Long]](index))
-    else if (elemClass eq classOf[Char])
-      Char.box(unboxed.asInstanceOf[Array[Char]](index))
-    else if (elemClass eq classOf[Byte])
-      Byte.box(unboxed.asInstanceOf[Array[Byte]](index))
-    else if (elemClass eq classOf[Short])
-      Short.box(unboxed.asInstanceOf[Array[Short]](index))
-    else if (elemClass eq classOf[Boolean])
-      Boolean.box(unboxed.asInstanceOf[Array[Boolean]](index))
-    else
-      unboxed.asInstanceOf[Array[AnyRef]](index)
-  }
-
-  def update(index: Int, _elem: Any): Unit = synchronized {
-    val elem = _elem.asInstanceOf[AnyRef]
-    if (unboxed eq null)
-      boxed(index) = elem
-    else if (elemClass eq classOf[Int])
-      unboxed.asInstanceOf[Array[Int]](index) = Int.unbox(elem)
-    else if (elemClass eq classOf[Double])
-      unboxed.asInstanceOf[Array[Double]](index) = Double.unbox(elem)
-    else if (elemClass eq classOf[Float])
-      unboxed.asInstanceOf[Array[Float]](index) = Float.unbox(elem)
-    else if (elemClass eq classOf[Long])
-      unboxed.asInstanceOf[Array[Long]](index) = Long.unbox(elem)
-    else if (elemClass eq classOf[Char])
-      unboxed.asInstanceOf[Array[Char]](index) = Char.unbox(elem)
-    else if (elemClass eq classOf[Byte])
-      unboxed.asInstanceOf[Array[Byte]](index) = Byte.unbox(elem)
-    else if (elemClass eq classOf[Short])
-      unboxed.asInstanceOf[Array[Short]](index) = Short.unbox(elem)
-    else if (elemClass eq classOf[Boolean])
-      unboxed.asInstanceOf[Array[Boolean]](index) = Boolean.unbox(elem)
-    else
-      unboxed.asInstanceOf[Array[AnyRef]](index) = elem
-  }
-
-  def unbox(elemTag: String): AnyRef =
-    if (elemTag eq ScalaRunTime.IntTag) unbox(classOf[Int])
-    else if (elemTag eq ScalaRunTime.DoubleTag) unbox(classOf[Double])
-    else if (elemTag eq ScalaRunTime.FloatTag) unbox(classOf[Float])
-    else if (elemTag eq ScalaRunTime.LongTag) unbox(classOf[Long])
-    else if (elemTag eq ScalaRunTime.CharTag) unbox(classOf[Char])
-    else if (elemTag eq ScalaRunTime.ByteTag) unbox(classOf[Byte])
-    else if (elemTag eq ScalaRunTime.ShortTag) unbox(classOf[Short])
-    else if (elemTag eq ScalaRunTime.BooleanTag) unbox(classOf[Boolean])
-    else unbox(Platform.getClassForName(elemTag))
-
-  def unbox(elemClass: Class[_]): AnyRef = synchronized {
-    if (unboxed eq null) {
-      this.elemClass = elemClass;
-      if (elemClass eq classOf[Int]) {
-        val newvalue = new Array[Int](length)
-        var i = 0
-        while (i < length) {
-          newvalue(i) = Int.unbox(boxed(i))
-          i += 1
-        }
-        unboxed = newvalue
-      } else if (elemClass eq classOf[Double]) {
-        val newvalue = new Array[Double](length)
-        var i = 0
-        while (i < length) {
-          newvalue(i) = Double.unbox(boxed(i))
-          i += 1
-        }
-        unboxed = newvalue;
-      } else if (elemClass eq classOf[Float]) {
-        val newvalue = new Array[Float](length)
-        var i = 0
-        while (i < length) {
-          newvalue(i) = Float.unbox(boxed(i))
-          i += 1
-        }
-        unboxed = newvalue;
-      } else if (elemClass eq classOf[Long]) {
-        val newvalue = new Array[Long](length)
-        var i = 0
-        while (i < length) {
-          newvalue(i) = Long.unbox(boxed(i))
-          i += 1
-        }
-        unboxed = newvalue;
-      } else if (elemClass eq classOf[Char]) {
-        val newvalue = new Array[Char](length)
-        var i = 0
-        while (i < length) {
-          newvalue(i) = Char.unbox(boxed(i))
-          i += 1
-        }
-        unboxed = newvalue
-      } else if (elemClass eq classOf[Byte]) {
-        val newvalue = new Array[Byte](length)
-        var i = 0
-        while (i < length) {
-          newvalue(i) = Byte.unbox(boxed(i))
-          i += 1
-        }
-        unboxed = newvalue;
-      } else if (elemClass eq classOf[Short]) {
-        val newvalue = new Array[Short](length)
-        var i = 0
-        while (i < length) {
-          newvalue(i) = Short.unbox(boxed(i))
-          i += 1
-        }
-        unboxed = newvalue;
-      } else if (elemClass eq classOf[Boolean]) {
-        val newvalue = new Array[Boolean](length)
-        var i = 0
-        while (i < length) {
-          newvalue(i) = Boolean.unbox(boxed(i))
-          i += 1
-        }
-        unboxed = newvalue;
-      } else if (elemClass == classOf[AnyRef]) {
-        // todo: replace with ScalaRunTime.AnyRef.class
-        unboxed = boxed
-      } else {
-        unboxed = Platform.createArray(elemClass, length)
-        if (elemClass.isArray) {
-          var i = 0
-          while (i < length) {
-            boxed(i) match {
-              case ba: BoxedArray => boxed(i) = ba.unbox(elemClass.getComponentType())
-              case _ =>
-            }
-            i += 1
-          }
-        }
-        Platform.arraycopy(boxed, 0, unboxed, 0, length)
-      }
-      boxed = null
-    }
-    unboxed
-  }
-
-  override def equals(other: Any): Boolean = (
-    other.isInstanceOf[BoxedAnyArray] && (this eq (other.asInstanceOf[BoxedAnyArray])) ||
-    (if (unboxed eq null) boxed == other else unboxed == other)
-  )
-
-  override def hashCode(): Int = hash
-
-  def value: AnyRef = {
-    if (unboxed eq null) throw new NotDefinedError("BoxedAnyArray.value")
-    unboxed
-  }
-
-  private def adapt(other: AnyRef): AnyRef =
-    if (this.unboxed eq null)
-      other match {
-        case that: BoxedAnyArray =>
-          if (that.unboxed eq null) {
-            that.boxed
-          } else {
-            if (ScalaRunTime.isValueClass(that.elemClass)) unbox(that.elemClass); 
-            that.unboxed
-          }
-        case that: BoxedArray =>
-          adapt(that.value)
-        case that: Array[Int] =>
-          unbox(ScalaRunTime.IntTag); that
-        case that: Array[Double] =>
-          unbox(ScalaRunTime.DoubleTag); that
-        case that: Array[Float] =>
-          unbox(ScalaRunTime.FloatTag); that
-        case that: Array[Long] =>
-          unbox(ScalaRunTime.LongTag); that
-        case that: Array[Char] =>
-          unbox(ScalaRunTime.CharTag); that
-        case that: Array[Short] =>
-          unbox(ScalaRunTime.ShortTag); that
-        case that: Array[Byte] =>
-          unbox(ScalaRunTime.ByteTag); that
-        case that: Array[Boolean] =>
-          unbox(ScalaRunTime.BooleanTag); that
-        case _ =>
-          other
-      }
-    else
-      other match {
-        case that: BoxedAnyArray =>
-          if (that.unboxed ne null) that.unboxed
-          else if (ScalaRunTime.isValueClass(this.elemClass)) that.unbox(this.elemClass)
-          else that.boxed
-        case that: BoxedArray =>
-          adapt(that.value)
-        case _ =>
-          other
-      }
-
-  override def copyFrom(src: AnyRef, from: Int, to: Int, len: Int) {
-    val src1 = adapt(src)
-    Array.copy(src1, from, if (unboxed ne null) unboxed else boxed, to, len)
-  }
-
-  override def copyTo(from: Int, dest: AnyRef, to: Int, len: Int) {
-    var dest1 = adapt(dest)
-    Array.copy(if (unboxed ne null) unboxed else boxed, from, dest1, to, len)
-  }
-
-  override def subArray(start: Int, end: Int): AnyRef = {
-    val result = new BoxedAnyArray(end - start);
-    Array.copy(this, start, result, 0, end - start)
-    result
-  }
-
-  final override def filter(p: Any => Boolean): BoxedArray = {
-    val include = new Array[Boolean](length)
-    var len = 0
-    var i = 0
-    while (i < length) {
-      if (p(this(i))) { include(i) = true; len += 1 }
-      i += 1
-    }
-    val result = new BoxedAnyArray(len)
-    len = 0
-    i = 0
-    while (len < result.length) {
-      if (include(i)) { result(len) = this(i); len += 1 }
-      i += 1
-    }
-    result
-  }
-  override protected def newArray(length : Int, elements : Iterator[Any]) = {
-    val result = new BoxedAnyArray(length)
-    var i = 0
-    while (elements.hasNext) {
-      result(i) = elements.next
-      i += 1
-    }
-    result
-  }
-}
diff --git a/src/library/scala/runtime/BoxedArray.scala b/src/library/scala/runtime/BoxedArray.scala
deleted file mode 100644
index e9c2ecb..0000000
--- a/src/library/scala/runtime/BoxedArray.scala
+++ /dev/null
@@ -1,187 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: BoxedArray.scala 16881 2009-01-09 16:28:11Z cunei $
-
-
-package scala.runtime
-
-
-import Predef._
-import collection.mutable.ArrayBuffer
-
-/**
- *  <p>A class representing <code>Array[T]</code></p>
- *
- *  @author  Martin Odersky, Stephane Micheloud
- *  @version 1.0
- */
-abstract class BoxedArray extends Array.Array0[Any] {
-  /** The length of the array */
-  def length: Int
-
-  /** The element at given index */
-  def apply(index: Int): Any
-
-  /** Update element at given index */
-  def update(index: Int, elem: Any): Unit
-
-  /** Convert to Java array.
-   *  @param elemTag    Either one of the tags ".N" where N is the name of a primitive type
-   *                    (@see ScalaRunTime), or a full class name.
-   */
-  //todo: remove
-  def unbox(elemTag: String): AnyRef
-
-  def unbox(elemClass: Class[_]): AnyRef
-
-  override def isDefinedAt(x: Int): Boolean = 0 <= x && x < length
-
-  @serializable protected class AnyIterator extends Iterator[Any] {
-    var index = 0
-    def hasNext: Boolean = index < length
-    def next(): Any = { val i = index; index = i + 1; apply(i) }
-  }
-  override def elements = new AnyIterator
-
-  /** The underlying array value
-   */
-  def value: AnyRef
-
-  def copyFrom(src: AnyRef, from: Int, to: Int, len: Int): Unit = 
-    Array.copy(src, from, value, to, len)
-
-  def copyTo(from: Int, dest: AnyRef, to: Int, len: Int): Unit = {
-    Array.copy(value, from, dest, to, len)
-  }
-
-  /** Fills the given array <code>xs</code> with the elements of
-   *  this sequence starting at position <code>start</code>.
-   *
-   *  @param  xs the array to fill.
-   *  @param  start starting index.
-   *  @pre    the array must be large enough to hold all elements.
-   */
-  override def copyToArray[B](xs: Array[B], start: Int): Unit =
-    copyTo(0, xs, start, length)
-
-  // todo: add a copyToBuffer
-
-  // todo: eliminate
-  def subArray(from: Int, end: Int): AnyRef
-
-  final override def map[b](f: Any => b): Array[b] = {
-    val len = length
-    val result = new Array[b](len)
-    var i = 0
-    while (i < len) {
-      result(i) = f(apply(i))
-      i += 1
-    }
-    result
-  }
-
-  final override def flatMap[b](f: Any => Iterable[b]): Array[b] = {
-    val buf = new ArrayBuffer[b]
-    val len = length
-    var i = 0
-    while (i < len) {
-      buf ++= f(apply(i))
-      i += 1
-    }
-    buf.toArray
-  }
-  
-  final override def ++[b >: Any](that: Iterable[b]): Array[b] = super.++(that).toArray
-
-  final def zip[b](that: Array[b]): Array[(Any,b)] = {
-    val len = this.length min that.length
-    val result = new Array[(Any,b)](len)
-    var i = 0
-    while (i < len) {
-      result(i) = (this(i), that(i))
-      i += 1
-    }
-    result
-  }
-  
-  final def zipWithIndex: Array[(Any,Int)] = {
-    val len = length
-    val result = new Array[(Any,Int)](len)
-    var i = 0
-    while (i < len) {
-      result(i) = (this(i), i)
-      i += 1
-    }
-    result
-  }
-
-  /** Returns an array that contains all indices of this array */
-  def indices: Array[Int] = Array.range(0, length)
-
-  final def deepToString() = deepMkString(stringPrefix + "(", ", ", ")")
-
-  final def deepMkString(start: String, sep: String, end: String): String = {
-    def _deepToString(x: Any) = x match {
-      case a: AnyRef if ScalaRunTime.isArray(a) =>
-        ScalaRunTime.boxArray(a).deepMkString(start, sep, end)
-      case _ =>
-        ScalaRunTime.stringOf(x)
-    }
-    val buf = new StringBuilder()
-    buf.append(start)
-    val elems = elements
-    if (elems.hasNext) buf.append(_deepToString(elems.next))
-    while (elems.hasNext) {
-      buf.append(sep); buf.append(_deepToString(elems.next))
-    }
-    buf.append(end)
-    buf.toString
-  }
-
-  final def deepMkString(sep: String): String = this.deepMkString("", sep, "")
-
-  final def deepEquals(that: Any): Boolean = {
-    def _deepEquals(x1: Any, x2: Any) = (x1, x2) match {
-      case (a1: BoxedArray, a2: BoxedArray) =>
-        _sameElements(a1, a2)
-      case (a1: AnyRef, a2: AnyRef)
-           if ScalaRunTime.isArray(a1) && ScalaRunTime.isArray(a2) =>
-        _sameElements(ScalaRunTime.boxArray(a1), ScalaRunTime.boxArray(a2))
-      case _ =>
-        x1.equals(x2)
-    }
-    def _sameElements(a1: BoxedArray, a2: BoxedArray): Boolean = {
-      val it1 = a1.elements
-      val it2 = a2.elements
-      var res = true
-      while (res && it1.hasNext && it2.hasNext)
-        res = _deepEquals(it1.next, it2.next)
-      !it1.hasNext && !it2.hasNext && res
-    }
-    that match {
-      case a: BoxedArray =>
-        _sameElements(this, a)
-      case a: AnyRef if ScalaRunTime.isArray(a) =>
-        _sameElements(this, ScalaRunTime.boxArray(a))
-      case _ =>
-        false
-    }
-  }
-  override final def stringPrefix: String = "Array"
-    
-  protected def newArray(length : Int, elements : Iterator[Any]) : BoxedArray
-  override def projection : scala.Array.Projection[Any] = new scala.Array.Projection[Any] {
-    def update(idx : Int, what : Any) : Unit = BoxedArray.this.update(idx, what)
-    def length = BoxedArray.this.length
-    def apply(idx : Int) = BoxedArray.this.apply(idx)
-    override def stringPrefix = "ArrayP"
-    protected def newArray[B >: Any](length : Int, elements : Iterator[Any]) = 
-      BoxedArray.this.newArray(length, elements).asInstanceOf[Array[B]]
-  }
-}
diff --git a/src/library/scala/runtime/BoxedBooleanArray.scala b/src/library/scala/runtime/BoxedBooleanArray.scala
deleted file mode 100644
index 6ac8562..0000000
--- a/src/library/scala/runtime/BoxedBooleanArray.scala
+++ /dev/null
@@ -1,65 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: BoxedBooleanArray.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala.runtime
-
-
-import Predef._
-
- at serializable
-final class BoxedBooleanArray(val value: Array[Boolean]) extends BoxedArray {
-
-  def length: Int = value.length
-
-  def apply(index: Int): Any = Boolean.box(value(index))
-
-  def update(index: Int, elem: Any) {
-    value(index) = Boolean.unbox(elem.asInstanceOf[AnyRef])
-  }
-
-  def unbox(elemTag: String): AnyRef = value
-  def unbox(elemClass: Class[_]): AnyRef = value
-
-  override def equals(other: Any) =
-    value == other ||
-    other.isInstanceOf[BoxedBooleanArray] && value == other.asInstanceOf[BoxedBooleanArray].value
-
-  override def hashCode(): Int = value.hashCode()
-
-  def subArray(start: Int, end: Int): Array[Boolean] = {
-    val result = new Array[Boolean](end - start)
-    Array.copy(value, start, result, 0, end - start)
-    result
-  }
-
-  final override def filter(p: Any => Boolean): BoxedArray = {
-    val include = new Array[Boolean](value.length)
-    var len = 0
-    var i = 0
-    while (i < value.length) {
-      if (p(value(i))) { include(i) = true; len += 1 }
-      i += 1
-    }
-    val result = new Array[Boolean](len)
-    len = 0
-    i = 0
-    while (len < result.length) {
-      if (include(i)) { result(len) = value(i); len += 1 }
-      i += 1
-    }
-    new BoxedBooleanArray(result)
-  }
-  override protected def newArray(length : Int, elements : Iterator[Any]) = {
-    val result = new Array[Boolean](length)
-    elements.map(_.asInstanceOf[Boolean]).copyToArray(result, 0)
-    new BoxedBooleanArray(result)
-  }
-}
diff --git a/src/library/scala/runtime/BoxedByteArray.scala b/src/library/scala/runtime/BoxedByteArray.scala
deleted file mode 100644
index e8be882..0000000
--- a/src/library/scala/runtime/BoxedByteArray.scala
+++ /dev/null
@@ -1,65 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: BoxedByteArray.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala.runtime
-
-
-import Predef._
-
- at serializable
-final class BoxedByteArray(val value: Array[Byte]) extends BoxedArray {
-
-  def length: Int = value.length
-
-  def apply(index: Int): Any = Byte.box(value(index))
-
-  def update(index: Int, elem: Any) {
-    value(index) = Byte.unbox(elem.asInstanceOf[AnyRef])
-  }
-
-  def unbox(elemTag: String): AnyRef = value
-  def unbox(elemClass: Class[_]): AnyRef = value
-
-  override def equals(other: Any) =
-    value == other ||
-    other.isInstanceOf[BoxedByteArray] && value == other.asInstanceOf[BoxedByteArray].value
-
-  override def hashCode(): Int = value.hashCode();
-
-  def subArray(start: Int, end: Int): Array[Byte] = {
-    val result = new Array[Byte](end - start)
-    Array.copy(value, start, result, 0, end - start)
-    result
-  }
-
-  final override def filter(p: Any => Boolean): BoxedArray = {
-    val include = new Array[Boolean](value.length)
-    var len = 0
-    var i = 0
-    while (i < value.length) {
-      if (p(value(i))) { include(i) = true; len += 1 }
-      i += 1
-    }
-    val result = new Array[Byte](len)
-    len = 0
-    i = 0
-    while (len < result.length) {
-      if (include(i)) { result(len) = value(i); len += 1 }
-      i += 1
-    }
-    new BoxedByteArray(result)
-  }
-  override protected def newArray(length : Int, elements : Iterator[Any]) = {
-    val result = new Array[Byte](length)
-    elements.map(_.asInstanceOf[Byte]).copyToArray(result, 0)
-    new BoxedByteArray(result)
-  }
-}
diff --git a/src/library/scala/runtime/BoxedCharArray.scala b/src/library/scala/runtime/BoxedCharArray.scala
deleted file mode 100644
index 688fb47..0000000
--- a/src/library/scala/runtime/BoxedCharArray.scala
+++ /dev/null
@@ -1,66 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: BoxedCharArray.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala.runtime
-
-
-import Predef._
-
- at serializable
-final class BoxedCharArray(val value: Array[Char]) extends BoxedArray {
-
-  def length: Int = value.length
-
-  def apply(index: Int): Any = Char.box(value(index))
-
-  def update(index: Int, elem: Any) {
-    value(index) = Char.unbox(elem.asInstanceOf[AnyRef])
-  }
-
-  def unbox(elemTag: String): AnyRef = value
-  def unbox(elemClass: Class[_]): AnyRef = value
-
-  override def equals(other: Any) = (
-    value == other ||
-    other.isInstanceOf[BoxedCharArray] && value == other.asInstanceOf[BoxedCharArray].value
-  );
-
-  override def hashCode(): Int = value.hashCode();
-
-  def subArray(start: Int, end: Int): Array[Char] = {
-    val result = new Array[Char](end - start)
-    Array.copy(value, start, result, 0, end - start)
-    result
-  }
-
-  final override def filter(p: Any => Boolean): BoxedArray = {
-    val include = new Array[Boolean](value.length)
-    var len = 0
-    var i = 0
-    while (i < value.length) {
-      if (p(value(i))) { include(i) = true; len += 1 }
-      i += 1
-    }
-    val result = new Array[Char](len)
-    len = 0
-    i = 0
-    while (len < result.length) {
-      if (include(i)) { result(len) = value(i); len += 1 }
-      i += 1
-    }
-    new BoxedCharArray(result)
-  }
-  override protected def newArray(length : Int, elements : Iterator[Any]) = {
-    val result = new Array[Char](length)
-    elements.map(_.asInstanceOf[Char]).copyToArray(result, 0)
-    new BoxedCharArray(result)
-  }
-}
diff --git a/src/library/scala/runtime/BoxedDoubleArray.scala b/src/library/scala/runtime/BoxedDoubleArray.scala
deleted file mode 100644
index 86f957b..0000000
--- a/src/library/scala/runtime/BoxedDoubleArray.scala
+++ /dev/null
@@ -1,65 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: BoxedDoubleArray.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala.runtime
-
-
-import Predef._
-
- at serializable
-final class BoxedDoubleArray(val value: Array[Double]) extends BoxedArray {
-
-  def length: Int = value.length
-
-  def apply(index: Int): Any = Double.box(value(index))
-
-  def update(index: Int, elem: Any) {
-    value(index) = Double.unbox(elem.asInstanceOf[AnyRef])
-  }
-
-  def unbox(elemTag: String): AnyRef = value
-  def unbox(elemClass: Class[_]): AnyRef = value
-
-  override def equals(other: Any) =
-    value == other ||
-    other.isInstanceOf[BoxedDoubleArray] && value == other.asInstanceOf[BoxedDoubleArray].value
-
-  override def hashCode(): Int = value.hashCode()
-
-  def subArray(start: Int, end: Int): Array[Double] = {
-    val result = new Array[Double](end - start)
-    Array.copy(value, start, result, 0, end - start)
-    result
-  }
-
-  final override def filter(p: Any => Boolean): BoxedArray = {
-    val include = new Array[Boolean](value.length)
-    var len = 0
-    var i = 0
-    while (i < value.length) {
-      if (p(value(i))) { include(i) = true; len += 1 }
-      i += 1
-    }
-    val result = new Array[Double](len)
-    len = 0
-    i = 0
-    while (len < result.length) {
-      if (include(i)) { result(len) = value(i); len += 1 }
-      i += 1
-    }
-    new BoxedDoubleArray(result)
-  }
-  override protected def newArray(length : Int, elements : Iterator[Any]) = {
-    val result = new Array[Double](length)
-    elements.map(_.asInstanceOf[Double]).copyToArray(result, 0)
-    new BoxedDoubleArray(result)
-  }
-}
diff --git a/src/library/scala/runtime/BoxedFloatArray.scala b/src/library/scala/runtime/BoxedFloatArray.scala
deleted file mode 100644
index dc17e49..0000000
--- a/src/library/scala/runtime/BoxedFloatArray.scala
+++ /dev/null
@@ -1,65 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: BoxedFloatArray.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala.runtime
-
-
-import Predef._
-
- at serializable
-final class BoxedFloatArray(val value: Array[Float]) extends BoxedArray {
-
-  def length: Int = value.length
-
-  def apply(index: Int): Any = Float.box(value(index))
-
-  def update(index: Int, elem: Any) {
-    value(index) = Float.unbox(elem.asInstanceOf[AnyRef])
-  }
-
-  def unbox(elemTag: String): AnyRef = value
-  def unbox(elemClass: Class[_]): AnyRef = value
-
-  override def equals(other: Any) =
-    value == other ||
-    other.isInstanceOf[BoxedFloatArray] && value == other.asInstanceOf[BoxedFloatArray].value
-
-  override def hashCode(): Int = value.hashCode()
-
-  def subArray(start: Int, end: Int): Array[Float] = {
-    val result = new Array[Float](end - start)
-    Array.copy(value, start, result, 0, end - start)
-    result
-  }
-
-  final override def filter(p: Any => Boolean): BoxedArray = {
-    val include = new Array[Boolean](value.length)
-    var len = 0
-    var i = 0
-    while (i < value.length) {
-      if (p(value(i))) { include(i) = true; len += 1 }
-      i += 1
-    }
-    val result = new Array[Float](len)
-    len = 0
-    i = 0
-    while (len < result.length) {
-      if (include(i)) { result(len) = value(i); len += 1 }
-      i += 1
-    }
-    new BoxedFloatArray(result)
-  }
-  override protected def newArray(length : Int, elements : Iterator[Any]) = {
-    val result = new Array[Float](length)
-    elements.map(_.asInstanceOf[Float]).copyToArray(result, 0)
-    new BoxedFloatArray(result)
-  }
-}
diff --git a/src/library/scala/runtime/BoxedIntArray.scala b/src/library/scala/runtime/BoxedIntArray.scala
deleted file mode 100644
index 4459585..0000000
--- a/src/library/scala/runtime/BoxedIntArray.scala
+++ /dev/null
@@ -1,67 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: BoxedIntArray.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala.runtime
-
-
-import Predef._
-
- at serializable
-final class BoxedIntArray(val value: Array[Int]) extends BoxedArray {
-
-  def length: Int = value.length
-
-  def apply(index: Int): Any = Int.box(value(index))
-
-  def update(index: Int, elem: Any) {
-    value(index) = Int.unbox(elem.asInstanceOf[AnyRef])
-  }
-
-  def unbox(elemTag: String): AnyRef = value
-  def unbox(elemClass: Class[_]): AnyRef = value
-
-  override def equals(other: Any) =
-    value == other ||
-    other.isInstanceOf[BoxedIntArray] && value == other.asInstanceOf[BoxedIntArray].value
-
-  override def hashCode(): Int = value.hashCode()
-
-  def subArray(start: Int, end: Int): Array[Int] = {
-    val result = new Array[Int](end - start)
-    Array.copy(value, start, result, 0, end - start)
-    result
-  }
-
-  final override def filter(p: Any => Boolean): BoxedArray = {
-    val include = new Array[Boolean](value.length)
-    var len = 0
-    var i = 0
-    while (i < value.length) {
-      if (p(value(i))) { include(i) = true; len += 1 }
-      i += 1
-    }
-    val result = new Array[Int](len)
-    len = 0
-    i = 0
-    while (len < result.length) {
-      if (include(i)) { result(len) = value(i); len += 1 }
-      i += 1
-    }
-    new BoxedIntArray(result)
-  }
-  override protected def newArray(length : Int, elements : Iterator[Any]) = {
-    val result = new Array[Int](length)
-    elements.map(_.asInstanceOf[Int]).copyToArray(result, 0)
-    new BoxedIntArray(result)
-  }
-
-  
-}
diff --git a/src/library/scala/runtime/BoxedLongArray.scala b/src/library/scala/runtime/BoxedLongArray.scala
deleted file mode 100644
index ce89d32..0000000
--- a/src/library/scala/runtime/BoxedLongArray.scala
+++ /dev/null
@@ -1,65 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: BoxedLongArray.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala.runtime
-
-
-import Predef._
-
- at serializable
-final class BoxedLongArray(val value: Array[Long]) extends BoxedArray {
-
-  def length: Int = value.length
-
-  def apply(index: Int): Any = Long.box(value(index))
-
-  def update(index: Int, elem: Any) {
-    value(index) = Long.unbox(elem.asInstanceOf[AnyRef])
-  }
-
-  def unbox(elemTag: String): AnyRef = value
-  def unbox(elemClass: Class[_]): AnyRef = value
-
-  override def equals(other: Any) =
-    value == other ||
-    other.isInstanceOf[BoxedLongArray] && value == other.asInstanceOf[BoxedLongArray].value
-
-  override def hashCode(): Int = value.hashCode()
-
-  def subArray(start: Int, end: Int): Array[Long] = {
-    val result = new Array[Long](end - start)
-    Array.copy(value, start, result, 0, end - start)
-    result
-  }
-
-  final override def filter(p: Any => Boolean): BoxedArray = {
-    val include = new Array[Boolean](value.length)
-    var len = 0
-    var i = 0
-    while (i < value.length) {
-      if (p(value(i))) { include(i) = true; len += 1 }
-      i += 1
-    }
-    val result = new Array[Long](len)
-    len = 0
-    i = 0
-    while (len < result.length) {
-      if (include(i)) { result(len) = value(i); len += 1 }
-      i += 1
-    }
-    new BoxedLongArray(result)
-  }
-  override protected def newArray(length : Int, elements : Iterator[Any]) = {
-    val result = new Array[Long](length)
-    elements.map(_.asInstanceOf[Long]).copyToArray(result, 0)
-    new BoxedLongArray(result)
-  }
-}
diff --git a/src/library/scala/runtime/BoxedObjectArray.scala b/src/library/scala/runtime/BoxedObjectArray.scala
deleted file mode 100644
index 4a3bb5c..0000000
--- a/src/library/scala/runtime/BoxedObjectArray.scala
+++ /dev/null
@@ -1,72 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: BoxedObjectArray.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala.runtime
-
-
-import Predef._
-import compat.Platform.createArray
-
- at serializable
-final class BoxedObjectArray(val value: Array[AnyRef]) extends BoxedArray {
-
-  def length: Int = value.length
-
-  def apply(index: Int): Any = value(index)
-
-  def update(index: Int, elem: Any) { 
-    value(index) = elem.asInstanceOf[AnyRef] 
-  }
-
-  def unbox(elemTag: String): AnyRef = value
-  def unbox(elemClass: Class[_]): AnyRef = value
-
-  override def equals(other: Any): Boolean =
-    value == other ||
-    other.isInstanceOf[BoxedObjectArray] && value == other.asInstanceOf[BoxedObjectArray].value
-
-  override def hashCode(): Int = value.hashCode()
-
-  private def create(length: Int): Array[AnyRef] = {
-    createArray(value.getClass().getComponentType(), length).asInstanceOf[Array[AnyRef]]
-  }
-
-  override def subArray(start: Int, end: Int): Array[AnyRef] = {
-    val result = create(end - start)
-    Array.copy(value, start, result, 0, end - start)
-    result
-  }    
-
-  final override def filter(p: Any => Boolean): BoxedArray = {
-    val include = new Array[Boolean](value.length)
-    var len = 0
-    var i = 0
-    while (i < value.length) {
-      if (p(value(i))) { include(i) = true; len += 1 }
-      i += 1
-    }
-    val result = create(len)
-    len = 0
-    i = 0
-    while (len < result.length) {
-      if (include(i)) { result(len) = value(i); len += 1 }
-      i += 1
-    }
-    new BoxedObjectArray(result)
-  }
-
-  override protected def newArray(length: Int, elements: Iterator[Any]) = {
-    val result = create(length)
-    elements.map(_.asInstanceOf[AnyRef]).copyToArray(result, 0)
-    new BoxedObjectArray(result)
-  }
-}
-
diff --git a/src/library/scala/runtime/BoxedShortArray.scala b/src/library/scala/runtime/BoxedShortArray.scala
deleted file mode 100644
index 0ffa9b3..0000000
--- a/src/library/scala/runtime/BoxedShortArray.scala
+++ /dev/null
@@ -1,65 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: BoxedShortArray.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala.runtime
-
-
-import Predef._
-
- at serializable
-final class BoxedShortArray(val value: Array[Short]) extends BoxedArray {
-
-  def length: Int = value.length
-
-  def apply(index: Int): Any = Short.box(value(index))
-
-  def update(index: Int, elem: Any) {
-    value(index) = Short.unbox(elem.asInstanceOf[AnyRef])
-  }
-
-  def unbox(elemTag: String): AnyRef = value
-  def unbox(elemClass: Class[_]): AnyRef = value
-
-  override def equals(other: Any) =
-    value == other ||
-    other.isInstanceOf[BoxedShortArray] && value == other.asInstanceOf[BoxedShortArray].value
-
-  override def hashCode(): Int = value.hashCode()
-
-  def subArray(start: Int, end: Int): Array[Short] = {
-    val result = new Array[Short](end - start)
-    Array.copy(value, start, result, 0, end - start)
-    result
-  }
-
-  final override def filter(p: Any => Boolean): BoxedArray = {
-    val include = new Array[Boolean](value.length)
-    var len = 0
-    var i = 0
-    while (i < value.length) {
-      if (p(value(i))) { include(i) = true; len += 1 }
-      i += 1
-    }
-    val result = new Array[Short](len)
-    len = 0
-    i = 0
-    while (len < result.length) {
-      if (include(i)) { result(len) = value(i); len += 1 }
-      i += 1
-    }
-    new BoxedShortArray(result)
-  }
-  override protected def newArray(length : Int, elements : Iterator[Any]) = {
-    val result = new Array[Short](length)
-    elements.map(_.asInstanceOf[Short]).copyToArray(result, 0)
-    new BoxedShortArray(result)
-  }
-}
diff --git a/src/library/scala/runtime/BoxedUnit.java b/src/library/scala/runtime/BoxedUnit.java
index 1eea5af..f88ace2 100644
--- a/src/library/scala/runtime/BoxedUnit.java
+++ b/src/library/scala/runtime/BoxedUnit.java
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: BoxedUnit.java 16881 2009-01-09 16:28:11Z cunei $
 
 
 package scala.runtime;
@@ -16,6 +15,8 @@ public final class BoxedUnit implements java.io.Serializable {
     private static final long serialVersionUID = 8405543498931817370L;
 
     public final static BoxedUnit UNIT = new BoxedUnit();
+	
+    public final static Class<Void> TYPE = java.lang.Void.TYPE;
 
     private BoxedUnit() { }
 
diff --git a/src/library/scala/runtime/BoxesRunTime.java b/src/library/scala/runtime/BoxesRunTime.java
index ba573e5..cc799ef 100644
--- a/src/library/scala/runtime/BoxesRunTime.java
+++ b/src/library/scala/runtime/BoxesRunTime.java
@@ -1,21 +1,23 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2006-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: BoxesRunTime.java 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala.runtime;
 
+import java.io.*;
+import scala.math.ScalaNumber;
+
 /** An object (static class) that defines methods used for creating,
   * reverting, and calculating with, boxed values. There are four classes
   * of methods in this object:
-  *   - High-performance value boxing methods that feed from a pre-
-  *     computed map of instances for the most common instanciations.
+  *   - Convenience boxing methods which call the static valueOf method
+  *     on the boxed class, thus utilizing the JVM boxing cache.
   *   - Convenience unboxing methods returning default value on null.
   *   - The generalised comparison method to be used when an object may
   *     be a boxed value.
@@ -25,240 +27,247 @@ package scala.runtime;
   * @author  Martin Odersky
   * @contributor Stepan Koltsov
   * @version 2.0 */
-public class BoxesRunTime {
-
+public final class BoxesRunTime
+{    
     private static final int CHAR = 0, BYTE = 1, SHORT = 2, INT = 3, LONG = 4, FLOAT = 5, DOUBLE = 6, OTHER = 7;
     
     private static int typeCode(Object a) {
-        if (a instanceof Integer) return INT;
-        if (a instanceof Character) return CHAR;
-        if (a instanceof Long) return LONG;
-        if (a instanceof Double) return DOUBLE;
-        if (a instanceof Float) return FLOAT;
-        if (a instanceof Byte) return BYTE;
-        if (a instanceof Short) return SHORT;
+        if (a instanceof java.lang.Integer) return INT;
+        if (a instanceof java.lang.Byte) return BYTE;
+        if (a instanceof java.lang.Character) return CHAR;
+        if (a instanceof java.lang.Long) return LONG;
+        if (a instanceof java.lang.Double) return DOUBLE;
+        if (a instanceof java.lang.Short) return SHORT;
+        if (a instanceof java.lang.Float) return FLOAT;
         return OTHER;
     }
-        
-/* BOXING ... BOXING ... BOXING ... BOXING ... BOXING ... BOXING ... BOXING ... BOXING */
-    
-    private static int charLowBound = 0;
-    private static int charUpBound = 255;
-    private static Character[] charCache = new Character[charUpBound - charLowBound + 1];
-    
-    private static int byteLowBound = -128;
-    private static int byteUpBound = 127;
-    private static Byte[] byteCache = new Byte[byteUpBound - byteLowBound + 1];
     
-    private static int shortLowBound = -128;
-    private static int shortUpBound = 127;
-    private static Short[] shortCache = new Short[shortUpBound - shortLowBound + 1];
-    
-    private static int intLowBound = -128;
-    private static int intUpBound = 1024;
-    private static Integer[] intCache = new Integer[intUpBound - intLowBound + 1];
-    
-    private static int longLowBound = -128;
-    private static int longUpBound = 1024;
-    private static Long[] longCache = new Long[longUpBound - longLowBound + 1];
-    
-    static {
-        int idx = 0;
-        while (idx <= charUpBound - charLowBound) {
-            charCache[idx] = new Character((char)(idx + charLowBound));
-            idx = idx + 1;
-        }
-        idx = 0;
-        while (idx <= byteUpBound - byteLowBound) {
-            byteCache[idx] = new Byte((byte)(idx + byteLowBound));
-            idx = idx + 1;
-        }
-        idx = 0;
-        while (idx <= shortUpBound - shortLowBound) {
-            shortCache[idx] = new Short((short)(idx + shortLowBound));
-            idx = idx + 1;
-        }
-        idx = 0;
-        while (idx <= intUpBound - intLowBound) {
-            intCache[idx] = new Integer((int)(idx + intLowBound));
-            idx = idx + 1;
-        }
-        idx = 0;
-        while (idx <= longUpBound - longLowBound) {
-            longCache[idx] = new Long((long)(idx + longLowBound));
-            idx = idx + 1;
-        }
+    private static String boxDescription(Object a) {
+      return "" + a.getClass().getSimpleName() + "(" + a + ")";
     }
-    
-    public static Boolean boxToBoolean(boolean b) {
-        return b ? Boolean.TRUE : Boolean.FALSE;
+        
+/* BOXING ... BOXING ... BOXING ... BOXING ... BOXING ... BOXING ... BOXING ... BOXING */
+
+    public static java.lang.Boolean boxToBoolean(boolean b) {
+        return java.lang.Boolean.valueOf(b);
     }
     
-    public static Character boxToCharacter(char c) {
-        if (c >= charLowBound && c <= charUpBound)
-            return charCache[(int)c - charLowBound];
-        return new Character(c); 
+    public static java.lang.Character boxToCharacter(char c) {
+        return java.lang.Character.valueOf(c);
     }
     
-    public static Byte boxToByte(byte b) {
-        if (b >= byteLowBound && b <= byteUpBound)
-            return byteCache[(int)b - byteLowBound];
-        return new Byte(b); 
+    public static java.lang.Byte boxToByte(byte b) {
+        return java.lang.Byte.valueOf(b);
     }
     
-    public static Short boxToShort(short s) {
-        if (s >= shortLowBound && s <= shortUpBound)
-            return shortCache[(int)s - shortLowBound];
-        return new Short(s); 
+    public static java.lang.Short boxToShort(short s) {
+        return java.lang.Short.valueOf(s);
     }
     
-    public static Integer boxToInteger(int i) {
-        if (i >= intLowBound && i <= intUpBound)
-            return intCache[(int)i - intLowBound];
-        return new Integer(i); 
+    public static java.lang.Integer boxToInteger(int i) {
+        return java.lang.Integer.valueOf(i);
     }
     
-    public static Long boxToLong(long l) {
-        if (l >= longLowBound && l <= longUpBound)
-            return longCache[(int)l - longLowBound];
-        return new Long(l);
+    public static java.lang.Long boxToLong(long l) {
+        return java.lang.Long.valueOf(l);
     }
     
-    public static Float boxToFloat(float f) {
-        return new Float(f);
+    public static java.lang.Float boxToFloat(float f) {
+        return java.lang.Float.valueOf(f);
     }
     
-    public static Double boxToDouble(double d) {
-        return new Double(d);
+    public static java.lang.Double boxToDouble(double d) {
+        return java.lang.Double.valueOf(d);
     }
         
 /* UNBOXING ... UNBOXING ... UNBOXING ... UNBOXING ... UNBOXING ... UNBOXING ... UNBOXING */
     
     public static boolean unboxToBoolean(Object b) {
-        return b == null ? false : ((Boolean)b).booleanValue();
+        return b == null ? false : ((java.lang.Boolean)b).booleanValue();
     }
     
     public static char unboxToChar(Object c) {
-        return c == null ? 0 : ((Character)c).charValue();
+        return c == null ? 0 : ((java.lang.Character)c).charValue();
     }
     
     public static byte unboxToByte(Object b) {
-        return b == null ? 0 : ((Byte)b).byteValue();
+        return b == null ? 0 : ((java.lang.Byte)b).byteValue();
     }
     
     public static short unboxToShort(Object s) {
-        return s == null ? 0 : ((Short)s).shortValue();
+        return s == null ? 0 : ((java.lang.Short)s).shortValue();
     }
 
     public static int unboxToInt(Object i) {
-        return i == null ? 0 : ((Integer)i).intValue();
+        return i == null ? 0 : ((java.lang.Integer)i).intValue();
     }
     
     public static long unboxToLong(Object l) {
-        return l == null ? 0 : ((Long)l).longValue();
+        return l == null ? 0 : ((java.lang.Long)l).longValue();
     }
     
     public static float unboxToFloat(Object f) {
-        return f == null ? 0.0f : ((Float)f).floatValue();
+        return f == null ? 0.0f : ((java.lang.Float)f).floatValue();
     }
     
     public static double unboxToDouble(Object d) {
-        return d == null ? 0.0d : ((Double)d).doubleValue();
+        return d == null ? 0.0d : ((java.lang.Double)d).doubleValue();
     }
-    
-    /*
-    public static boolean unboxToBoolean(Object b) {
-        if (b == null)
-          throw new ClassCastException("null is no Boolean value");
-        return ((Boolean)b).booleanValue();
-    }
-    
-    public static char unboxToChar(Object c) {
-        if (c == null)
-          throw new ClassCastException("null is no Char value");
-        return ((Character)c).charValue();
+
+    /* COMPARISON ... COMPARISON ... COMPARISON ... COMPARISON ... COMPARISON ... COMPARISON */
+    
+    private static int eqTypeCode(Number a) {
+        if ((a instanceof java.lang.Integer) || (a instanceof java.lang.Byte)) return INT;
+        if (a instanceof java.lang.Long) return LONG;
+        if (a instanceof java.lang.Double) return DOUBLE;
+        if (a instanceof java.lang.Short) return INT;
+        if (a instanceof java.lang.Float) return FLOAT;
+        return OTHER;
     }
     
-    public static byte unboxToByte(Object b) {
-        if (b == null)
-          throw new ClassCastException("null is no Byte value");
-        return ((Byte)b).byteValue();
+    public static boolean equals(Object x, Object y) {      
+        if (x == y) return true;
+        return equals2(x, y);
     }
-    
-    public static short unboxToShort(Object s) {
-        if (s == null)
-          throw new ClassCastException("null is no Short value");
-        return ((Short)s).shortValue();
+
+    /** Since all applicable logic has to be present in the equals method of a ScalaNumber
+     *  in any case, we dispatch to it as soon as we spot one on either side.
+     */
+    public static boolean equals2(Object x, Object y) {
+        if (x instanceof java.lang.Number)
+            return equalsNumObject((java.lang.Number)x, y);
+        if (x instanceof java.lang.Character)
+            return equalsCharObject((java.lang.Character)x, y);
+        if (x == null)
+            return y == null;
+          
+        return x.equals(y);
+    }
+    
+    public static boolean equalsNumObject(java.lang.Number xn, Object y) {
+        if (y instanceof java.lang.Number)
+            return equalsNumNum(xn, (java.lang.Number)y);
+        if (y instanceof java.lang.Character)
+            return equalsNumChar(xn, (java.lang.Character)y);
+        if (xn == null)
+            return y == null;
+          
+        return xn.equals(y);
+    }
+    
+    public static boolean equalsNumNum(java.lang.Number xn, java.lang.Number yn) {
+        int xcode = eqTypeCode(xn);
+        int ycode = eqTypeCode(yn);
+        switch (ycode > xcode ? ycode : xcode) {
+        case INT:
+            return xn.intValue() == yn.intValue();
+        case LONG:
+            return xn.longValue() == yn.longValue();
+        case FLOAT:
+            return xn.floatValue() == yn.floatValue();
+        case DOUBLE:
+            return xn.doubleValue() == yn.doubleValue();
+        default:
+            if ((yn instanceof ScalaNumber) && !(xn instanceof ScalaNumber))
+                return yn.equals(xn);
+        }
+        if (xn == null)
+            return yn == null;
+            
+        return xn.equals(yn);
+    }
+    
+    public static boolean equalsCharObject(java.lang.Character xc, Object y) {
+        if (y instanceof java.lang.Character)
+            return xc.charValue() == ((java.lang.Character)y).charValue();
+        if (y instanceof java.lang.Number)
+            return equalsNumChar((java.lang.Number)y, xc);
+        if (xc == null)
+            return y == null;
+             
+        return xc.equals(y);
     }
 
-    public static int unboxToInt(Object i) {
-        if (i == null)
-          throw new ClassCastException("null is no Int value");
-        return ((Integer)i).intValue();
+    private static boolean equalsNumChar(java.lang.Number xn, java.lang.Character yc) {
+        char ch = yc.charValue();
+        switch (eqTypeCode(xn)) {
+        case INT:
+            return xn.intValue() == ch;
+        case LONG:
+            return xn.longValue() == ch;
+        case FLOAT:
+            return xn.floatValue() == ch;
+        case DOUBLE:
+            return xn.doubleValue() == ch;
+        default:
+            if (xn == null)
+                return yc == null;
+                
+            return xn.equals(yc);
+        }
+    }
+    
+    /** Hashcode algorithm is driven by the requirements imposed
+     *  by primitive equality semantics, namely that equal objects
+     *  have equal hashCodes.  The first priority are the integral/char
+     *  types, which already have the same hashCodes for the same
+     *  values except for Long.  So Long's hashCode is altered to
+     *  conform to Int's for all values in Int's range.
+     *
+     *  Float is problematic because it's far too small to hold
+     *  all the Ints, so for instance Int.MaxValue.toFloat claims
+     *  to be == to each of the largest 64 Ints.  There is no way
+     *  to preserve equals/hashCode alignment without compromising
+     *  the hashCode distribution, so Floats are only guaranteed
+     *  to have the same hashCode for whole Floats in the range
+     *  Short.MinValue to Short.MaxValue (2^16 total.)
+     *
+     *  Double has its hashCode altered to match the entire Int range,
+     *  but is not guaranteed beyond that.  (But could/should it be?
+     *  The hashCode is only 32 bits so this is a more tractable
+     *  issue than Float's, but it might be better simply to exclude it.)
+     *
+     *  Note: BigInt and BigDecimal, being arbitrary precision, could
+     *  be made consistent with all other types for the Int range, but
+     *  as yet have not.
+     *
+     *  Note: Among primitives, Float.NaN != Float.NaN, but the boxed
+     *  verisons are equal.  This still needs reconciliation.
+     */
+    public static int hashFromLong(java.lang.Long n) {
+        int iv = n.intValue();
+        if (iv == n.longValue()) return iv;
+        else return n.hashCode();
+    }
+    public static int hashFromDouble(java.lang.Double n) {
+        int iv = n.intValue();    
+        double dv = n.doubleValue();
+        if (iv == dv) return iv;
+  
+        long lv = n.longValue();
+        if (lv == dv) return java.lang.Long.valueOf(lv).hashCode();
+        else return n.hashCode();
+    }
+    public static int hashFromFloat(java.lang.Float n) {
+        int iv = n.intValue();    
+        float fv = n.floatValue();
+        if (iv == fv) return iv;
+
+        long lv = n.longValue();
+        if (lv == fv) return java.lang.Long.valueOf(lv).hashCode();
+        else return n.hashCode();
     }
-    
-    public static long unboxToLong(Object l) {
-        if (l == null)
-          throw new ClassCastException("null is no Long value");
-        return ((Long)l).longValue();
+    public static int hashFromNumber(java.lang.Number n) {
+      if (n instanceof java.lang.Long) return hashFromLong((java.lang.Long)n);
+      else if (n instanceof java.lang.Double) return hashFromDouble((java.lang.Double)n);
+      else if (n instanceof java.lang.Float) return hashFromFloat((java.lang.Float)n);
+      else return n.hashCode();
     }
-    
-    public static float unboxToFloat(Object f) {
-        if (f == null)
-          throw new ClassCastException("null is no Float value");
-        return ((Float)f).floatValue();
+    public static int hashFromObject(Object a) {
+      if (a instanceof Number) return hashFromNumber((Number)a);
+      else return a.hashCode();
     }
     
-    public static double unboxToDouble(Object d) {
-        if (d == null)
-          throw new ClassCastException("null is no Double value");
-        return ((Double)d).doubleValue();
-    }
-    */
-        
-/* COMPARISON ... COMPARISON ... COMPARISON ... COMPARISON ... COMPARISON ... COMPARISON */
-
-    /** A rich implementation of the <code>equals</code> method that overrides the
-      * default equals because Java's boxed primitives are utterly broken. This equals
-      * is inserted instead of a normal equals by the Scala compiler (in the
-      * ICode phase, method <code>genEqEqPrimitive</code>) only when either
-      * side of the comparison is a subclass of <code>AnyVal</code>, of
-      * <code>java.lang.Number</code>, of <code>java.lang.Character</code> or
-      * is exactly <code>Any</code> or <code>AnyRef</code>. */
-    public static boolean equals(Object a, Object b) {
-        if (a == null || b == null)
-            return a == b;
-        if (a.equals(b))
-            return true;
-        if (a instanceof Number || a instanceof Character || b instanceof Number || b instanceof Character) {
-            int acode = typeCode(a);
-            int bcode = typeCode(b);
-            int maxcode = (acode < bcode) ? bcode : acode;
-            if (maxcode <= INT) {
-                int aa = (acode == CHAR) ? ((Character) a).charValue() : ((Number) a).intValue();
-                int bb = (bcode == CHAR) ? ((Character) b).charValue() : ((Number) b).intValue();
-                return aa == bb;
-            }
-            if (maxcode <= LONG) {
-                long aa = (acode == CHAR) ? ((Character) a).charValue() : ((Number) a).longValue();
-                long bb = (bcode == CHAR) ? ((Character) b).charValue() : ((Number) b).longValue();
-                return aa == bb;
-            }
-            if (maxcode <= FLOAT) {
-                float aa = (acode == CHAR) ? ((Character) a).charValue() : ((Number) a).floatValue();
-                float bb = (bcode == CHAR) ? ((Character) b).charValue() : ((Number) b).floatValue();
-                return aa == bb;
-            }
-            if (maxcode <= DOUBLE) {
-                double aa = (acode == CHAR) ? ((Character) a).charValue() : ((Number) a).doubleValue();
-                double bb = (bcode == CHAR) ? ((Character) b).charValue() : ((Number) b).doubleValue();
-                return aa == bb;
-            }
-			return b.equals(a);
-        }
-        return false;
-    }
-        
 /* OPERATORS ... OPERATORS ... OPERATORS ... OPERATORS ... OPERATORS ... OPERATORS ... OPERATORS ... OPERATORS */
         
     /** arg1 + arg2 */
@@ -267,23 +276,23 @@ public class BoxesRunTime {
         int code2 = typeCode(arg2);
         int maxcode = (code1 < code2) ? code2 : code1;
         if (maxcode <= INT) {
-            int val1 = (code1 == CHAR) ? ((Character) arg1).charValue() : ((Number) arg1).intValue();
-            int val2 = (code2 == CHAR) ? ((Character) arg2).charValue() : ((Number) arg2).intValue();
+            int val1 = (code1 == CHAR) ? ((java.lang.Character) arg1).charValue() : ((java.lang.Number) arg1).intValue();
+            int val2 = (code2 == CHAR) ? ((java.lang.Character) arg2).charValue() : ((java.lang.Number) arg2).intValue();
             return boxToInteger(val1 + val2);
         }
         if (maxcode <= LONG) {
-            long val1 = (code1 == CHAR) ? ((Character) arg1).charValue() : ((Number) arg1).longValue();
-            long val2 = (code2 == CHAR) ? ((Character) arg2).charValue() : ((Number) arg2).longValue();
+            long val1 = (code1 == CHAR) ? ((java.lang.Character) arg1).charValue() : ((java.lang.Number) arg1).longValue();
+            long val2 = (code2 == CHAR) ? ((java.lang.Character) arg2).charValue() : ((java.lang.Number) arg2).longValue();
             return boxToLong(val1 + val2);
         }
         if (maxcode <= FLOAT) {
-            float val1 = (code1 == CHAR) ? ((Character) arg1).charValue() : ((Number) arg1).floatValue();
-            float val2 = (code2 == CHAR) ? ((Character) arg2).charValue() : ((Number) arg2).floatValue();
+            float val1 = (code1 == CHAR) ? ((java.lang.Character) arg1).charValue() : ((java.lang.Number) arg1).floatValue();
+            float val2 = (code2 == CHAR) ? ((java.lang.Character) arg2).charValue() : ((java.lang.Number) arg2).floatValue();
             return boxToFloat(val1 + val2);
         }
         if (maxcode <= DOUBLE) {
-            double val1 = (code1 == CHAR) ? ((Character) arg1).charValue() : ((Number) arg1).doubleValue();
-            double val2 = (code2 == CHAR) ? ((Character) arg2).charValue() : ((Number) arg2).doubleValue();
+            double val1 = (code1 == CHAR) ? ((java.lang.Character) arg1).charValue() : ((java.lang.Number) arg1).doubleValue();
+            double val2 = (code2 == CHAR) ? ((java.lang.Character) arg2).charValue() : ((java.lang.Number) arg2).doubleValue();
             return boxToDouble(val1 + val2);
         }
         throw new NoSuchMethodException();
@@ -295,23 +304,23 @@ public class BoxesRunTime {
         int code2 = typeCode(arg2);
         int maxcode = (code1 < code2) ? code2 : code1;
         if (maxcode <= INT) {
-            int val1 = (code1 == CHAR) ? ((Character) arg1).charValue() : ((Number) arg1).intValue();
-            int val2 = (code2 == CHAR) ? ((Character) arg2).charValue() : ((Number) arg2).intValue();
+            int val1 = (code1 == CHAR) ? ((java.lang.Character) arg1).charValue() : ((java.lang.Number) arg1).intValue();
+            int val2 = (code2 == CHAR) ? ((java.lang.Character) arg2).charValue() : ((java.lang.Number) arg2).intValue();
             return boxToInteger(val1 - val2);
         }
         if (maxcode <= LONG) {
-            long val1 = (code1 == CHAR) ? ((Character) arg1).charValue() : ((Number) arg1).longValue();
-            long val2 = (code2 == CHAR) ? ((Character) arg2).charValue() : ((Number) arg2).longValue();
+            long val1 = (code1 == CHAR) ? ((java.lang.Character) arg1).charValue() : ((java.lang.Number) arg1).longValue();
+            long val2 = (code2 == CHAR) ? ((java.lang.Character) arg2).charValue() : ((java.lang.Number) arg2).longValue();
             return boxToLong(val1 - val2);
         }
         if (maxcode <= FLOAT) {
-            float val1 = (code1 == CHAR) ? ((Character) arg1).charValue() : ((Number) arg1).floatValue();
-            float val2 = (code2 == CHAR) ? ((Character) arg2).charValue() : ((Number) arg2).floatValue();
+            float val1 = (code1 == CHAR) ? ((java.lang.Character) arg1).charValue() : ((java.lang.Number) arg1).floatValue();
+            float val2 = (code2 == CHAR) ? ((java.lang.Character) arg2).charValue() : ((java.lang.Number) arg2).floatValue();
             return boxToFloat(val1 - val2);
         }
         if (maxcode <= DOUBLE) {
-            double val1 = (code1 == CHAR) ? ((Character) arg1).charValue() : ((Number) arg1).doubleValue();
-            double val2 = (code2 == CHAR) ? ((Character) arg2).charValue() : ((Number) arg2).doubleValue();
+            double val1 = (code1 == CHAR) ? ((java.lang.Character) arg1).charValue() : ((java.lang.Number) arg1).doubleValue();
+            double val2 = (code2 == CHAR) ? ((java.lang.Character) arg2).charValue() : ((java.lang.Number) arg2).doubleValue();
             return boxToDouble(val1 - val2);
         }
         throw new NoSuchMethodException();
@@ -323,23 +332,23 @@ public class BoxesRunTime {
         int code2 = typeCode(arg2);
         int maxcode = (code1 < code2) ? code2 : code1;
         if (maxcode <= INT) {
-            int val1 = (code1 == CHAR) ? ((Character) arg1).charValue() : ((Number) arg1).intValue();
-            int val2 = (code2 == CHAR) ? ((Character) arg2).charValue() : ((Number) arg2).intValue();
+            int val1 = (code1 == CHAR) ? ((java.lang.Character) arg1).charValue() : ((java.lang.Number) arg1).intValue();
+            int val2 = (code2 == CHAR) ? ((java.lang.Character) arg2).charValue() : ((java.lang.Number) arg2).intValue();
             return boxToInteger(val1 * val2);
         }
         if (maxcode <= LONG) {
-            long val1 = (code1 == CHAR) ? ((Character) arg1).charValue() : ((Number) arg1).longValue();
-            long val2 = (code2 == CHAR) ? ((Character) arg2).charValue() : ((Number) arg2).longValue();
+            long val1 = (code1 == CHAR) ? ((java.lang.Character) arg1).charValue() : ((java.lang.Number) arg1).longValue();
+            long val2 = (code2 == CHAR) ? ((java.lang.Character) arg2).charValue() : ((java.lang.Number) arg2).longValue();
             return boxToLong(val1 * val2);
         }
         if (maxcode <= FLOAT) {
-            float val1 = (code1 == CHAR) ? ((Character) arg1).charValue() : ((Number) arg1).floatValue();
-            float val2 = (code2 == CHAR) ? ((Character) arg2).charValue() : ((Number) arg2).floatValue();
+            float val1 = (code1 == CHAR) ? ((java.lang.Character) arg1).charValue() : ((java.lang.Number) arg1).floatValue();
+            float val2 = (code2 == CHAR) ? ((java.lang.Character) arg2).charValue() : ((java.lang.Number) arg2).floatValue();
             return boxToFloat(val1 * val2);
         }
         if (maxcode <= DOUBLE) {
-            double val1 = (code1 == CHAR) ? ((Character) arg1).charValue() : ((Number) arg1).doubleValue();
-            double val2 = (code2 == CHAR) ? ((Character) arg2).charValue() : ((Number) arg2).doubleValue();
+            double val1 = (code1 == CHAR) ? ((java.lang.Character) arg1).charValue() : ((java.lang.Number) arg1).doubleValue();
+            double val2 = (code2 == CHAR) ? ((java.lang.Character) arg2).charValue() : ((java.lang.Number) arg2).doubleValue();
             return boxToDouble(val1 * val2);
         }
         throw new NoSuchMethodException();
@@ -351,23 +360,23 @@ public class BoxesRunTime {
         int code2 = typeCode(arg2);
         int maxcode = (code1 < code2) ? code2 : code1;
         if (maxcode <= INT) {
-            int val1 = (code1 == CHAR) ? ((Character) arg1).charValue() : ((Number) arg1).intValue();
-            int val2 = (code2 == CHAR) ? ((Character) arg2).charValue() : ((Number) arg2).intValue();
+            int val1 = (code1 == CHAR) ? ((java.lang.Character) arg1).charValue() : ((java.lang.Number) arg1).intValue();
+            int val2 = (code2 == CHAR) ? ((java.lang.Character) arg2).charValue() : ((java.lang.Number) arg2).intValue();
             return boxToInteger(val1 / val2);
         }
         if (maxcode <= LONG) {
-            long val1 = (code1 == CHAR) ? ((Character) arg1).charValue() : ((Number) arg1).longValue();
-            long val2 = (code2 == CHAR) ? ((Character) arg2).charValue() : ((Number) arg2).longValue();
+            long val1 = (code1 == CHAR) ? ((java.lang.Character) arg1).charValue() : ((java.lang.Number) arg1).longValue();
+            long val2 = (code2 == CHAR) ? ((java.lang.Character) arg2).charValue() : ((java.lang.Number) arg2).longValue();
             return boxToLong(val1 / val2);
         }
         if (maxcode <= FLOAT) {
-            float val1 = (code1 == CHAR) ? ((Character) arg1).charValue() : ((Number) arg1).floatValue();
-            float val2 = (code2 == CHAR) ? ((Character) arg2).charValue() : ((Number) arg2).floatValue();
+            float val1 = (code1 == CHAR) ? ((java.lang.Character) arg1).charValue() : ((java.lang.Number) arg1).floatValue();
+            float val2 = (code2 == CHAR) ? ((java.lang.Character) arg2).charValue() : ((java.lang.Number) arg2).floatValue();
             return boxToFloat(val1 / val2);
         }
         if (maxcode <= DOUBLE) {
-            double val1 = (code1 == CHAR) ? ((Character) arg1).charValue() : ((Number) arg1).doubleValue();
-            double val2 = (code2 == CHAR) ? ((Character) arg2).charValue() : ((Number) arg2).doubleValue();
+            double val1 = (code1 == CHAR) ? ((java.lang.Character) arg1).charValue() : ((java.lang.Number) arg1).doubleValue();
+            double val2 = (code2 == CHAR) ? ((java.lang.Character) arg2).charValue() : ((java.lang.Number) arg2).doubleValue();
             return boxToDouble(val1 / val2);
         }
         throw new NoSuchMethodException();
@@ -379,23 +388,23 @@ public class BoxesRunTime {
         int code2 = typeCode(arg2);
         int maxcode = (code1 < code2) ? code2 : code1;
         if (maxcode <= INT) {
-            int val1 = (code1 == CHAR) ? ((Character) arg1).charValue() : ((Number) arg1).intValue();
-            int val2 = (code2 == CHAR) ? ((Character) arg2).charValue() : ((Number) arg2).intValue();
+            int val1 = (code1 == CHAR) ? ((java.lang.Character) arg1).charValue() : ((java.lang.Number) arg1).intValue();
+            int val2 = (code2 == CHAR) ? ((java.lang.Character) arg2).charValue() : ((java.lang.Number) arg2).intValue();
             return boxToInteger(val1 % val2);
         }
         if (maxcode <= LONG) {
-            long val1 = (code1 == CHAR) ? ((Character) arg1).charValue() : ((Number) arg1).longValue();
-            long val2 = (code2 == CHAR) ? ((Character) arg2).charValue() : ((Number) arg2).longValue();
+            long val1 = (code1 == CHAR) ? ((java.lang.Character) arg1).charValue() : ((java.lang.Number) arg1).longValue();
+            long val2 = (code2 == CHAR) ? ((java.lang.Character) arg2).charValue() : ((java.lang.Number) arg2).longValue();
             return boxToLong(val1 % val2);
         }
         if (maxcode <= FLOAT) {
-            float val1 = (code1 == CHAR) ? ((Character) arg1).charValue() : ((Number) arg1).floatValue();
-            float val2 = (code2 == CHAR) ? ((Character) arg2).charValue() : ((Number) arg2).floatValue();
+            float val1 = (code1 == CHAR) ? ((java.lang.Character) arg1).charValue() : ((java.lang.Number) arg1).floatValue();
+            float val2 = (code2 == CHAR) ? ((java.lang.Character) arg2).charValue() : ((java.lang.Number) arg2).floatValue();
             return boxToFloat(val1 % val2);
         }
         if (maxcode <= DOUBLE) {
-            double val1 = (code1 == CHAR) ? ((Character) arg1).charValue() : ((Number) arg1).doubleValue();
-            double val2 = (code2 == CHAR) ? ((Character) arg2).charValue() : ((Number) arg2).doubleValue();
+            double val1 = (code1 == CHAR) ? ((java.lang.Character) arg1).charValue() : ((java.lang.Number) arg1).doubleValue();
+            double val2 = (code2 == CHAR) ? ((java.lang.Character) arg2).charValue() : ((java.lang.Number) arg2).doubleValue();
             return boxToDouble(val1 % val2);
         }
         throw new NoSuchMethodException();
@@ -406,24 +415,24 @@ public class BoxesRunTime {
         int code1 = typeCode(arg1);
         int code2 = typeCode(arg2);
         if (code1 <= INT) {
-            int val1 = (code1 == CHAR) ? ((Character) arg1).charValue() : ((Number) arg1).intValue();
+            int val1 = (code1 == CHAR) ? ((java.lang.Character) arg1).charValue() : ((java.lang.Number) arg1).intValue();
             if (code2 <= INT) {
-                int val2 = (code2 == CHAR) ? ((Character) arg2).charValue() : ((Number) arg2).intValue();
+                int val2 = (code2 == CHAR) ? ((java.lang.Character) arg2).charValue() : ((java.lang.Number) arg2).intValue();
                 return boxToInteger(val1 >> val2);
             }
             if (code2 <= LONG) {
-                long val2 = (code2 == CHAR) ? ((Character) arg2).charValue() : ((Number) arg2).longValue();
+                long val2 = (code2 == CHAR) ? ((java.lang.Character) arg2).charValue() : ((java.lang.Number) arg2).longValue();
                 return boxToInteger(val1 >> val2);
             }
         }
         if (code1 <= LONG) {
-            long val1 = (code1 == CHAR) ? ((Character) arg1).charValue() : ((Number) arg1).longValue();
+            long val1 = (code1 == CHAR) ? ((java.lang.Character) arg1).charValue() : ((java.lang.Number) arg1).longValue();
             if (code2 <= INT) {
-                int val2 = (code2 == CHAR) ? ((Character) arg2).charValue() : ((Number) arg2).intValue();
+                int val2 = (code2 == CHAR) ? ((java.lang.Character) arg2).charValue() : ((java.lang.Number) arg2).intValue();
                 return boxToLong(val1 >> val2);
             }
             if (code2 <= LONG) {
-                long val2 = (code2 == CHAR) ? ((Character) arg2).charValue() : ((Number) arg2).longValue();
+                long val2 = (code2 == CHAR) ? ((java.lang.Character) arg2).charValue() : ((java.lang.Number) arg2).longValue();
                 return boxToLong(val1 >> val2);
             }
         }
@@ -435,24 +444,24 @@ public class BoxesRunTime {
         int code1 = typeCode(arg1);
         int code2 = typeCode(arg2);
         if (code1 <= INT) {
-            int val1 = (code1 == CHAR) ? ((Character) arg1).charValue() : ((Number) arg1).intValue();
+            int val1 = (code1 == CHAR) ? ((java.lang.Character) arg1).charValue() : ((java.lang.Number) arg1).intValue();
             if (code2 <= INT) {
-                int val2 = (code2 == CHAR) ? ((Character) arg2).charValue() : ((Number) arg2).intValue();
+                int val2 = (code2 == CHAR) ? ((java.lang.Character) arg2).charValue() : ((java.lang.Number) arg2).intValue();
                 return boxToInteger(val1 << val2);
             }
             if (code2 <= LONG) {
-                long val2 = (code2 == CHAR) ? ((Character) arg2).charValue() : ((Number) arg2).longValue();
+                long val2 = (code2 == CHAR) ? ((java.lang.Character) arg2).charValue() : ((java.lang.Number) arg2).longValue();
                 return boxToInteger(val1 << val2);
             }
         }
         if (code1 <= LONG) {
-            long val1 = (code1 == CHAR) ? ((Character) arg1).charValue() : ((Number) arg1).longValue();
+            long val1 = (code1 == CHAR) ? ((java.lang.Character) arg1).charValue() : ((java.lang.Number) arg1).longValue();
             if (code2 <= INT) {
-                int val2 = (code2 == CHAR) ? ((Character) arg2).charValue() : ((Number) arg2).intValue();
+                int val2 = (code2 == CHAR) ? ((java.lang.Character) arg2).charValue() : ((java.lang.Number) arg2).intValue();
                 return boxToLong(val1 << val2);
             }
             if (code2 <= LONG) {
-                long val2 = (code2 == CHAR) ? ((Character) arg2).charValue() : ((Number) arg2).longValue();
+                long val2 = (code2 == CHAR) ? ((java.lang.Character) arg2).charValue() : ((java.lang.Number) arg2).longValue();
                 return boxToLong(val1 << val2);
             }
         }
@@ -464,24 +473,24 @@ public class BoxesRunTime {
         int code1 = typeCode(arg1);
         int code2 = typeCode(arg2);
         if (code1 <= INT) {
-            int val1 = (code1 == CHAR) ? ((Character) arg1).charValue() : ((Number) arg1).intValue();
+            int val1 = (code1 == CHAR) ? ((java.lang.Character) arg1).charValue() : ((java.lang.Number) arg1).intValue();
             if (code2 <= INT) {
-                int val2 = (code2 == CHAR) ? ((Character) arg2).charValue() : ((Number) arg2).intValue();
+                int val2 = (code2 == CHAR) ? ((java.lang.Character) arg2).charValue() : ((java.lang.Number) arg2).intValue();
                 return boxToInteger(val1 >>> val2);
             }
             if (code2 <= LONG) {
-                long val2 = (code2 == CHAR) ? ((Character) arg2).charValue() : ((Number) arg2).longValue();
+                long val2 = (code2 == CHAR) ? ((java.lang.Character) arg2).charValue() : ((java.lang.Number) arg2).longValue();
                 return boxToInteger(val1 >>> val2);
             }
         }
         if (code1 <= LONG) {
-            long val1 = (code1 == CHAR) ? ((Character) arg1).charValue() : ((Number) arg1).longValue();
+            long val1 = (code1 == CHAR) ? ((java.lang.Character) arg1).charValue() : ((java.lang.Number) arg1).longValue();
             if (code2 <= INT) {
-                int val2 = (code2 == CHAR) ? ((Character) arg2).charValue() : ((Number) arg2).intValue();
+                int val2 = (code2 == CHAR) ? ((java.lang.Character) arg2).charValue() : ((java.lang.Number) arg2).intValue();
                 return boxToLong(val1 >>> val2);
             }
             if (code2 <= LONG) {
-                long val2 = (code2 == CHAR) ? ((Character) arg2).charValue() : ((Number) arg2).longValue();
+                long val2 = (code2 == CHAR) ? ((java.lang.Character) arg2).charValue() : ((java.lang.Number) arg2).longValue();
                 return boxToLong(val1 >>> val2);
             }
         }
@@ -492,19 +501,19 @@ public class BoxesRunTime {
     public static Object negate(Object arg) throws NoSuchMethodException {
         int code = typeCode(arg);
         if (code <= INT) {
-            int val = (code == CHAR) ? ((Character) arg).charValue() : ((Number) arg).intValue();
+            int val = (code == CHAR) ? ((java.lang.Character) arg).charValue() : ((java.lang.Number) arg).intValue();
             return boxToInteger(-val);
         }
         if (code <= LONG) {
-            long val = (code == CHAR) ? ((Character) arg).charValue() : ((Number) arg).longValue();
+            long val = (code == CHAR) ? ((java.lang.Character) arg).charValue() : ((java.lang.Number) arg).longValue();
             return boxToLong(-val);
         }
         if (code <= FLOAT) {
-            float val = (code == CHAR) ? ((Character) arg).charValue() : ((Number) arg).floatValue();
+            float val = (code == CHAR) ? ((java.lang.Character) arg).charValue() : ((java.lang.Number) arg).floatValue();
             return boxToFloat(-val);
         }
         if (code <= DOUBLE) {
-            double val = (code == CHAR) ? ((Character) arg).charValue() : ((Number) arg).doubleValue();
+            double val = (code == CHAR) ? ((java.lang.Character) arg).charValue() : ((java.lang.Number) arg).doubleValue();
             return boxToDouble(-val);
         }
         throw new NoSuchMethodException();
@@ -514,19 +523,19 @@ public class BoxesRunTime {
     public static Object positive(Object arg) throws NoSuchMethodException {
         int code = typeCode(arg);
         if (code <= INT) {
-            int val = (code == CHAR) ? ((Character) arg).charValue() : ((Number) arg).intValue();
+            int val = (code == CHAR) ? ((java.lang.Character) arg).charValue() : ((java.lang.Number) arg).intValue();
             return boxToInteger(+val);
         }
         if (code <= LONG) {
-            long val = (code == CHAR) ? ((Character) arg).charValue() : ((Number) arg).longValue();
+            long val = (code == CHAR) ? ((java.lang.Character) arg).charValue() : ((java.lang.Number) arg).longValue();
             return boxToLong(+val);
         }
         if (code <= FLOAT) {
-            float val = (code == CHAR) ? ((Character) arg).charValue() : ((Number) arg).floatValue();
+            float val = (code == CHAR) ? ((java.lang.Character) arg).charValue() : ((java.lang.Number) arg).floatValue();
             return boxToFloat(+val);
         }
         if (code <= DOUBLE) {
-            double val = (code == CHAR) ? ((Character) arg).charValue() : ((Number) arg).doubleValue();
+            double val = (code == CHAR) ? ((java.lang.Character) arg).charValue() : ((java.lang.Number) arg).doubleValue();
             return boxToDouble(+val);
         }
         throw new NoSuchMethodException();
@@ -538,19 +547,19 @@ public class BoxesRunTime {
             if (!((arg1 instanceof Boolean) && (arg2 instanceof Boolean))) {
                 throw new NoSuchMethodException();
             }
-            return boxToBoolean(((Boolean) arg1).booleanValue() & ((Boolean) arg2).booleanValue());
+            return boxToBoolean(((java.lang.Boolean) arg1).booleanValue() & ((java.lang.Boolean) arg2).booleanValue());
         }
         int code1 = typeCode(arg1);
         int code2 = typeCode(arg2);
         int maxcode = (code1 < code2) ? code2 : code1;
         if (maxcode <= INT) {
-            int val1 = (code1 == CHAR) ? ((Character) arg1).charValue() : ((Number) arg1).intValue();
-            int val2 = (code2 == CHAR) ? ((Character) arg2).charValue() : ((Number) arg2).intValue();
+            int val1 = (code1 == CHAR) ? ((java.lang.Character) arg1).charValue() : ((java.lang.Number) arg1).intValue();
+            int val2 = (code2 == CHAR) ? ((java.lang.Character) arg2).charValue() : ((java.lang.Number) arg2).intValue();
             return boxToInteger(val1 & val2);
         }
         if (maxcode <= LONG) {
-            long val1 = (code1 == CHAR) ? ((Character) arg1).charValue() : ((Number) arg1).longValue();
-            long val2 = (code2 == CHAR) ? ((Character) arg2).charValue() : ((Number) arg2).longValue();
+            long val1 = (code1 == CHAR) ? ((java.lang.Character) arg1).charValue() : ((java.lang.Number) arg1).longValue();
+            long val2 = (code2 == CHAR) ? ((java.lang.Character) arg2).charValue() : ((java.lang.Number) arg2).longValue();
             return boxToLong(val1 & val2);
         }
         throw new NoSuchMethodException();
@@ -562,19 +571,19 @@ public class BoxesRunTime {
             if (!((arg1 instanceof Boolean) && (arg2 instanceof Boolean))) {
                 throw new NoSuchMethodException();
             }
-            return boxToBoolean(((Boolean) arg1).booleanValue() | ((Boolean) arg2).booleanValue());
+            return boxToBoolean(((java.lang.Boolean) arg1).booleanValue() | ((java.lang.Boolean) arg2).booleanValue());
         }
         int code1 = typeCode(arg1);
         int code2 = typeCode(arg2);
         int maxcode = (code1 < code2) ? code2 : code1;
         if (maxcode <= INT) {
-            int val1 = (code1 == CHAR) ? ((Character) arg1).charValue() : ((Number) arg1).intValue();
-            int val2 = (code2 == CHAR) ? ((Character) arg2).charValue() : ((Number) arg2).intValue();
+            int val1 = (code1 == CHAR) ? ((java.lang.Character) arg1).charValue() : ((java.lang.Number) arg1).intValue();
+            int val2 = (code2 == CHAR) ? ((java.lang.Character) arg2).charValue() : ((java.lang.Number) arg2).intValue();
             return boxToInteger(val1 | val2);
         }
         if (maxcode <= LONG) {
-            long val1 = (code1 == CHAR) ? ((Character) arg1).charValue() : ((Number) arg1).longValue();
-            long val2 = (code2 == CHAR) ? ((Character) arg2).charValue() : ((Number) arg2).longValue();
+            long val1 = (code1 == CHAR) ? ((java.lang.Character) arg1).charValue() : ((java.lang.Number) arg1).longValue();
+            long val2 = (code2 == CHAR) ? ((java.lang.Character) arg2).charValue() : ((java.lang.Number) arg2).longValue();
             return boxToLong(val1 | val2);
         }
         throw new NoSuchMethodException();
@@ -586,19 +595,19 @@ public class BoxesRunTime {
             if (!((arg1 instanceof Boolean) && (arg2 instanceof Boolean))) {
                 throw new NoSuchMethodException();
             }
-            return boxToBoolean(((Boolean) arg1).booleanValue() ^ ((Boolean) arg2).booleanValue());
+            return boxToBoolean(((java.lang.Boolean) arg1).booleanValue() ^ ((java.lang.Boolean) arg2).booleanValue());
         }
         int code1 = typeCode(arg1);
         int code2 = typeCode(arg2);
         int maxcode = (code1 < code2) ? code2 : code1;
         if (maxcode <= INT) {
-            int val1 = (code1 == CHAR) ? ((Character) arg1).charValue() : ((Number) arg1).intValue();
-            int val2 = (code2 == CHAR) ? ((Character) arg2).charValue() : ((Number) arg2).intValue();
+            int val1 = (code1 == CHAR) ? ((java.lang.Character) arg1).charValue() : ((java.lang.Number) arg1).intValue();
+            int val2 = (code2 == CHAR) ? ((java.lang.Character) arg2).charValue() : ((java.lang.Number) arg2).intValue();
             return boxToInteger(val1 ^ val2);
         }
         if (maxcode <= LONG) {
-            long val1 = (code1 == CHAR) ? ((Character) arg1).charValue() : ((Number) arg1).longValue();
-            long val2 = (code2 == CHAR) ? ((Character) arg2).charValue() : ((Number) arg2).longValue();
+            long val1 = (code1 == CHAR) ? ((java.lang.Character) arg1).charValue() : ((java.lang.Number) arg1).longValue();
+            long val2 = (code2 == CHAR) ? ((java.lang.Character) arg2).charValue() : ((java.lang.Number) arg2).longValue();
             return boxToLong(val1 ^ val2);
         }
         throw new NoSuchMethodException();
@@ -607,7 +616,7 @@ public class BoxesRunTime {
     /** arg1 && arg2 */
     public static Object takeConditionalAnd(Object arg1, Object arg2) throws NoSuchMethodException {
         if ((arg1 instanceof Boolean) && (arg2 instanceof Boolean)) {
-            return boxToBoolean(((Boolean) arg1).booleanValue() && ((Boolean) arg2).booleanValue());
+            return boxToBoolean(((java.lang.Boolean) arg1).booleanValue() && ((java.lang.Boolean) arg2).booleanValue());
         }
         throw new NoSuchMethodException();
     }
@@ -615,7 +624,7 @@ public class BoxesRunTime {
     /** arg1 || arg2 */
     public static Object takeConditionalOr(Object arg1, Object arg2) throws NoSuchMethodException {
         if ((arg1 instanceof Boolean) && (arg2 instanceof Boolean)) {
-            return boxToBoolean(((Boolean) arg1).booleanValue() || ((Boolean) arg2).booleanValue());
+            return boxToBoolean(((java.lang.Boolean) arg1).booleanValue() || ((java.lang.Boolean) arg2).booleanValue());
         }
         throw new NoSuchMethodException();
     }
@@ -624,11 +633,11 @@ public class BoxesRunTime {
     public static Object complement(Object arg) throws NoSuchMethodException {
         int code = typeCode(arg);
         if (code <= INT) {
-            int val = (code == CHAR) ? ((Character) arg).charValue() : ((Number) arg).intValue();
+            int val = (code == CHAR) ? ((java.lang.Character) arg).charValue() : ((java.lang.Number) arg).intValue();
             return boxToInteger(~val);
         }
         if (code <= LONG) {
-            long val = (code == CHAR) ? ((Character) arg).charValue() : ((Number) arg).longValue();
+            long val = (code == CHAR) ? ((java.lang.Character) arg).charValue() : ((java.lang.Number) arg).longValue();
             return boxToLong(~val);
         }
         throw new NoSuchMethodException();
@@ -637,7 +646,7 @@ public class BoxesRunTime {
     /** !arg */
     public static Object takeNot(Object arg) throws NoSuchMethodException {
         if (arg instanceof Boolean) {
-          return boxToBoolean(!((Boolean) arg).booleanValue());
+          return boxToBoolean(!((java.lang.Boolean) arg).booleanValue());
         }
         throw new NoSuchMethodException();
     }
@@ -655,23 +664,23 @@ public class BoxesRunTime {
         int code2 = typeCode(arg2);
         int maxcode = (code1 < code2) ? code2 : code1;
         if (maxcode <= INT) {
-            int val1 = (code1 == CHAR) ? ((Character) arg1).charValue() : ((Number) arg1).intValue();
-            int val2 = (code2 == CHAR) ? ((Character) arg2).charValue() : ((Number) arg2).intValue();
+            int val1 = (code1 == CHAR) ? ((java.lang.Character) arg1).charValue() : ((java.lang.Number) arg1).intValue();
+            int val2 = (code2 == CHAR) ? ((java.lang.Character) arg2).charValue() : ((java.lang.Number) arg2).intValue();
             return boxToBoolean(val1 < val2);
         }
         if (maxcode <= LONG) {
-            long val1 = (code1 == CHAR) ? ((Character) arg1).charValue() : ((Number) arg1).longValue();
-            long val2 = (code2 == CHAR) ? ((Character) arg2).charValue() : ((Number) arg2).longValue();
+            long val1 = (code1 == CHAR) ? ((java.lang.Character) arg1).charValue() : ((java.lang.Number) arg1).longValue();
+            long val2 = (code2 == CHAR) ? ((java.lang.Character) arg2).charValue() : ((java.lang.Number) arg2).longValue();
             return boxToBoolean(val1 < val2);
         }
         if (maxcode <= FLOAT) {
-            float val1 = (code1 == CHAR) ? ((Character) arg1).charValue() : ((Number) arg1).floatValue();
-            float val2 = (code2 == CHAR) ? ((Character) arg2).charValue() : ((Number) arg2).floatValue();
+            float val1 = (code1 == CHAR) ? ((java.lang.Character) arg1).charValue() : ((java.lang.Number) arg1).floatValue();
+            float val2 = (code2 == CHAR) ? ((java.lang.Character) arg2).charValue() : ((java.lang.Number) arg2).floatValue();
             return boxToBoolean(val1 < val2);
         }
         if (maxcode <= DOUBLE) {
-            double val1 = (code1 == CHAR) ? ((Character) arg1).charValue() : ((Number) arg1).doubleValue();
-            double val2 = (code2 == CHAR) ? ((Character) arg2).charValue() : ((Number) arg2).doubleValue();
+            double val1 = (code1 == CHAR) ? ((java.lang.Character) arg1).charValue() : ((java.lang.Number) arg1).doubleValue();
+            double val2 = (code2 == CHAR) ? ((java.lang.Character) arg2).charValue() : ((java.lang.Number) arg2).doubleValue();
             return boxToBoolean(val1 < val2);
         }
         throw new NoSuchMethodException();
@@ -682,23 +691,23 @@ public class BoxesRunTime {
         int code2 = typeCode(arg2);
         int maxcode = (code1 < code2) ? code2 : code1;
         if (maxcode <= INT) {
-            int val1 = (code1 == CHAR) ? ((Character) arg1).charValue() : ((Number) arg1).intValue();
-            int val2 = (code2 == CHAR) ? ((Character) arg2).charValue() : ((Number) arg2).intValue();
+            int val1 = (code1 == CHAR) ? ((java.lang.Character) arg1).charValue() : ((java.lang.Number) arg1).intValue();
+            int val2 = (code2 == CHAR) ? ((java.lang.Character) arg2).charValue() : ((java.lang.Number) arg2).intValue();
             return boxToBoolean(val1 <= val2);
         }
         if (maxcode <= LONG) {
-            long val1 = (code1 == CHAR) ? ((Character) arg1).charValue() : ((Number) arg1).longValue();
-            long val2 = (code2 == CHAR) ? ((Character) arg2).charValue() : ((Number) arg2).longValue();
+            long val1 = (code1 == CHAR) ? ((java.lang.Character) arg1).charValue() : ((java.lang.Number) arg1).longValue();
+            long val2 = (code2 == CHAR) ? ((java.lang.Character) arg2).charValue() : ((java.lang.Number) arg2).longValue();
             return boxToBoolean(val1 <= val2);
         }
         if (maxcode <= FLOAT) {
-            float val1 = (code1 == CHAR) ? ((Character) arg1).charValue() : ((Number) arg1).floatValue();
-            float val2 = (code2 == CHAR) ? ((Character) arg2).charValue() : ((Number) arg2).floatValue();
+            float val1 = (code1 == CHAR) ? ((java.lang.Character) arg1).charValue() : ((java.lang.Number) arg1).floatValue();
+            float val2 = (code2 == CHAR) ? ((java.lang.Character) arg2).charValue() : ((java.lang.Number) arg2).floatValue();
             return boxToBoolean(val1 <= val2);
         }
         if (maxcode <= DOUBLE) {
-            double val1 = (code1 == CHAR) ? ((Character) arg1).charValue() : ((Number) arg1).doubleValue();
-            double val2 = (code2 == CHAR) ? ((Character) arg2).charValue() : ((Number) arg2).doubleValue();
+            double val1 = (code1 == CHAR) ? ((java.lang.Character) arg1).charValue() : ((java.lang.Number) arg1).doubleValue();
+            double val2 = (code2 == CHAR) ? ((java.lang.Character) arg2).charValue() : ((java.lang.Number) arg2).doubleValue();
             return boxToBoolean(val1 <= val2);
         }
         throw new NoSuchMethodException();
@@ -709,23 +718,23 @@ public class BoxesRunTime {
         int code2 = typeCode(arg2);
         int maxcode = (code1 < code2) ? code2 : code1;
         if (maxcode <= INT) {
-            int val1 = (code1 == CHAR) ? ((Character) arg1).charValue() : ((Number) arg1).intValue();
-            int val2 = (code2 == CHAR) ? ((Character) arg2).charValue() : ((Number) arg2).intValue();
+            int val1 = (code1 == CHAR) ? ((java.lang.Character) arg1).charValue() : ((java.lang.Number) arg1).intValue();
+            int val2 = (code2 == CHAR) ? ((java.lang.Character) arg2).charValue() : ((java.lang.Number) arg2).intValue();
             return boxToBoolean(val1 >= val2);
         }
         if (maxcode <= LONG) {
-            long val1 = (code1 == CHAR) ? ((Character) arg1).charValue() : ((Number) arg1).longValue();
-            long val2 = (code2 == CHAR) ? ((Character) arg2).charValue() : ((Number) arg2).longValue();
+            long val1 = (code1 == CHAR) ? ((java.lang.Character) arg1).charValue() : ((java.lang.Number) arg1).longValue();
+            long val2 = (code2 == CHAR) ? ((java.lang.Character) arg2).charValue() : ((java.lang.Number) arg2).longValue();
             return boxToBoolean(val1 >= val2);
         }
         if (maxcode <= FLOAT) {
-            float val1 = (code1 == CHAR) ? ((Character) arg1).charValue() : ((Number) arg1).floatValue();
-            float val2 = (code2 == CHAR) ? ((Character) arg2).charValue() : ((Number) arg2).floatValue();
+            float val1 = (code1 == CHAR) ? ((java.lang.Character) arg1).charValue() : ((java.lang.Number) arg1).floatValue();
+            float val2 = (code2 == CHAR) ? ((java.lang.Character) arg2).charValue() : ((java.lang.Number) arg2).floatValue();
             return boxToBoolean(val1 >= val2);
         }
         if (maxcode <= DOUBLE) {
-            double val1 = (code1 == CHAR) ? ((Character) arg1).charValue() : ((Number) arg1).doubleValue();
-            double val2 = (code2 == CHAR) ? ((Character) arg2).charValue() : ((Number) arg2).doubleValue();
+            double val1 = (code1 == CHAR) ? ((java.lang.Character) arg1).charValue() : ((java.lang.Number) arg1).doubleValue();
+            double val2 = (code2 == CHAR) ? ((java.lang.Character) arg2).charValue() : ((java.lang.Number) arg2).doubleValue();
             return boxToBoolean(val1 >= val2);
         }
         throw new NoSuchMethodException();
@@ -736,109 +745,109 @@ public class BoxesRunTime {
         int code2 = typeCode(arg2);
         int maxcode = (code1 < code2) ? code2 : code1;
         if (maxcode <= INT) {
-            int val1 = (code1 == CHAR) ? ((Character) arg1).charValue() : ((Number) arg1).intValue();
-            int val2 = (code2 == CHAR) ? ((Character) arg2).charValue() : ((Number) arg2).intValue();
+            int val1 = (code1 == CHAR) ? ((java.lang.Character) arg1).charValue() : ((java.lang.Number) arg1).intValue();
+            int val2 = (code2 == CHAR) ? ((java.lang.Character) arg2).charValue() : ((java.lang.Number) arg2).intValue();
             return boxToBoolean(val1 > val2);
         }
         if (maxcode <= LONG) {
-            long val1 = (code1 == CHAR) ? ((Character) arg1).charValue() : ((Number) arg1).longValue();
-            long val2 = (code2 == CHAR) ? ((Character) arg2).charValue() : ((Number) arg2).longValue();
+            long val1 = (code1 == CHAR) ? ((java.lang.Character) arg1).charValue() : ((java.lang.Number) arg1).longValue();
+            long val2 = (code2 == CHAR) ? ((java.lang.Character) arg2).charValue() : ((java.lang.Number) arg2).longValue();
             return boxToBoolean(val1 > val2);
         }
         if (maxcode <= FLOAT) {
-            float val1 = (code1 == CHAR) ? ((Character) arg1).charValue() : ((Number) arg1).floatValue();
-            float val2 = (code2 == CHAR) ? ((Character) arg2).charValue() : ((Number) arg2).floatValue();
+            float val1 = (code1 == CHAR) ? ((java.lang.Character) arg1).charValue() : ((java.lang.Number) arg1).floatValue();
+            float val2 = (code2 == CHAR) ? ((java.lang.Character) arg2).charValue() : ((java.lang.Number) arg2).floatValue();
             return boxToBoolean(val1 > val2);
         }
         if (maxcode <= DOUBLE) {
-            double val1 = (code1 == CHAR) ? ((Character) arg1).charValue() : ((Number) arg1).doubleValue();
-            double val2 = (code2 == CHAR) ? ((Character) arg2).charValue() : ((Number) arg2).doubleValue();
+            double val1 = (code1 == CHAR) ? ((java.lang.Character) arg1).charValue() : ((java.lang.Number) arg1).doubleValue();
+            double val2 = (code2 == CHAR) ? ((java.lang.Character) arg2).charValue() : ((java.lang.Number) arg2).doubleValue();
             return boxToBoolean(val1 > val2);
         }
         throw new NoSuchMethodException();
     }
         
     /** arg.toChar */
-    public static Character toCharacter(Object arg) throws NoSuchMethodException {
-        if (arg instanceof Character) return (Character)arg;
-        if (arg instanceof Byte) return boxToCharacter((char)unboxToByte(arg));
-        if (arg instanceof Short) return boxToCharacter((char)unboxToShort(arg));
-        if (arg instanceof Integer) return boxToCharacter((char)unboxToInt(arg));
-        if (arg instanceof Long) return boxToCharacter((char)unboxToLong(arg));
-        if (arg instanceof Float) return boxToCharacter((char)unboxToFloat(arg));
-        if (arg instanceof Double) return boxToCharacter((char)unboxToDouble(arg));
+    public static java.lang.Character toCharacter(Object arg) throws NoSuchMethodException {
+        if (arg instanceof java.lang.Integer) return boxToCharacter((char)unboxToInt(arg));
+        if (arg instanceof java.lang.Short) return boxToCharacter((char)unboxToShort(arg));
+        if (arg instanceof java.lang.Character) return (java.lang.Character)arg;
+        if (arg instanceof java.lang.Long) return boxToCharacter((char)unboxToLong(arg));
+        if (arg instanceof java.lang.Byte) return boxToCharacter((char)unboxToByte(arg));
+        if (arg instanceof java.lang.Float) return boxToCharacter((char)unboxToFloat(arg));
+        if (arg instanceof java.lang.Double) return boxToCharacter((char)unboxToDouble(arg));
         throw new NoSuchMethodException();
     }
 
     /** arg.toByte */
-    public static Byte toByte(Object arg) throws NoSuchMethodException {
-        if (arg instanceof Character) return boxToByte((byte)unboxToChar(arg));
-        if (arg instanceof Byte) return (Byte)arg;
-        if (arg instanceof Short) return boxToByte((byte)unboxToShort(arg));
-        if (arg instanceof Integer) return boxToByte((byte)unboxToInt(arg));
-        if (arg instanceof Long) return boxToByte((byte)unboxToLong(arg));
-        if (arg instanceof Float) return boxToByte((byte)unboxToFloat(arg));
-        if (arg instanceof Double) return boxToByte((byte)unboxToDouble(arg));
+    public static java.lang.Byte toByte(Object arg) throws NoSuchMethodException {
+        if (arg instanceof java.lang.Integer) return boxToByte((byte)unboxToInt(arg));
+        if (arg instanceof java.lang.Character) return boxToByte((byte)unboxToChar(arg));
+        if (arg instanceof java.lang.Byte) return (java.lang.Byte)arg;
+        if (arg instanceof java.lang.Long) return boxToByte((byte)unboxToLong(arg));
+        if (arg instanceof java.lang.Short) return boxToByte((byte)unboxToShort(arg));
+        if (arg instanceof java.lang.Float) return boxToByte((byte)unboxToFloat(arg));
+        if (arg instanceof java.lang.Double) return boxToByte((byte)unboxToDouble(arg));
         throw new NoSuchMethodException();
     }
 
     /** arg.toShort */
-    public static Short toShort(Object arg) throws NoSuchMethodException {
-        if (arg instanceof Character) return boxToShort((short)unboxToChar(arg));
-        if (arg instanceof Byte) return boxToShort((short)unboxToByte(arg));
-        if (arg instanceof Short) return (Short)arg;
-        if (arg instanceof Integer) return boxToShort((short)unboxToInt(arg));
-        if (arg instanceof Long) return boxToShort((short)unboxToLong(arg));
-        if (arg instanceof Float) return boxToShort((short)unboxToFloat(arg));
-        if (arg instanceof Double) return boxToShort((short)unboxToDouble(arg));
+    public static java.lang.Short toShort(Object arg) throws NoSuchMethodException {
+        if (arg instanceof java.lang.Integer) return boxToShort((short)unboxToInt(arg));
+        if (arg instanceof java.lang.Long) return boxToShort((short)unboxToLong(arg));
+        if (arg instanceof java.lang.Character) return boxToShort((short)unboxToChar(arg));
+        if (arg instanceof java.lang.Byte) return boxToShort((short)unboxToByte(arg));
+        if (arg instanceof java.lang.Short) return (java.lang.Short)arg;
+        if (arg instanceof java.lang.Float) return boxToShort((short)unboxToFloat(arg));
+        if (arg instanceof java.lang.Double) return boxToShort((short)unboxToDouble(arg));
         throw new NoSuchMethodException();
     }
 
     /** arg.toInt */
-    public static Integer toInteger(Object arg) throws NoSuchMethodException {
-        if (arg instanceof Character) return boxToInteger((int)unboxToChar(arg));
-        if (arg instanceof Byte) return boxToInteger((int)unboxToByte(arg));
-        if (arg instanceof Short) return boxToInteger((int)unboxToShort(arg));
-        if (arg instanceof Integer) return (Integer)arg;
-        if (arg instanceof Long) return boxToInteger((int)unboxToLong(arg));
-        if (arg instanceof Float) return boxToInteger((int)unboxToFloat(arg));
-        if (arg instanceof Double) return boxToInteger((int)unboxToDouble(arg));
+    public static java.lang.Integer toInteger(Object arg) throws NoSuchMethodException {
+        if (arg instanceof java.lang.Integer) return (java.lang.Integer)arg;
+        if (arg instanceof java.lang.Long) return boxToInteger((int)unboxToLong(arg));
+        if (arg instanceof java.lang.Double) return boxToInteger((int)unboxToDouble(arg));
+        if (arg instanceof java.lang.Float) return boxToInteger((int)unboxToFloat(arg));
+        if (arg instanceof java.lang.Character) return boxToInteger((int)unboxToChar(arg));
+        if (arg instanceof java.lang.Byte) return boxToInteger((int)unboxToByte(arg));
+        if (arg instanceof java.lang.Short) return boxToInteger((int)unboxToShort(arg));
         throw new NoSuchMethodException();
     }
 
     /** arg.toLong */
-    public static Long toLong(Object arg) throws NoSuchMethodException {
-        if (arg instanceof Character) return boxToLong((long)unboxToChar(arg));
-        if (arg instanceof Byte) return boxToLong((long)unboxToByte(arg));
-        if (arg instanceof Short) return boxToLong((long)unboxToShort(arg));
-        if (arg instanceof Integer) return boxToLong((long)unboxToInt(arg));
-        if (arg instanceof Long) return (Long)arg;
-        if (arg instanceof Float) return boxToLong((long)unboxToFloat(arg));
-        if (arg instanceof Double) return boxToLong((long)unboxToDouble(arg));
+    public static java.lang.Long toLong(Object arg) throws NoSuchMethodException {
+        if (arg instanceof java.lang.Integer) return boxToLong((long)unboxToInt(arg));
+        if (arg instanceof java.lang.Double) return boxToLong((long)unboxToDouble(arg));
+        if (arg instanceof java.lang.Float) return boxToLong((long)unboxToFloat(arg));
+        if (arg instanceof java.lang.Long) return (java.lang.Long)arg;
+        if (arg instanceof java.lang.Character) return boxToLong((long)unboxToChar(arg));
+        if (arg instanceof java.lang.Byte) return boxToLong((long)unboxToByte(arg));
+        if (arg instanceof java.lang.Short) return boxToLong((long)unboxToShort(arg));
         throw new NoSuchMethodException();
     }
 
     /** arg.toFloat */
-    public static Float toFloat(Object arg) throws NoSuchMethodException {
-        if (arg instanceof Character) return boxToFloat((float)unboxToChar(arg));
-        if (arg instanceof Byte) return boxToFloat((float)unboxToByte(arg));
-        if (arg instanceof Short) return boxToFloat((float)unboxToShort(arg));
-        if (arg instanceof Integer) return boxToFloat((float)unboxToInt(arg));
-        if (arg instanceof Long) return boxToFloat((float)unboxToLong(arg));
-        if (arg instanceof Float) return (Float)arg;
-        if (arg instanceof Double) return boxToFloat((float)unboxToDouble(arg));
+    public static java.lang.Float toFloat(Object arg) throws NoSuchMethodException {
+        if (arg instanceof java.lang.Integer) return boxToFloat((float)unboxToInt(arg));
+        if (arg instanceof java.lang.Long) return boxToFloat((float)unboxToLong(arg));
+        if (arg instanceof java.lang.Float) return (java.lang.Float)arg;
+        if (arg instanceof java.lang.Double) return boxToFloat((float)unboxToDouble(arg));
+        if (arg instanceof java.lang.Character) return boxToFloat((float)unboxToChar(arg));
+        if (arg instanceof java.lang.Byte) return boxToFloat((float)unboxToByte(arg));
+        if (arg instanceof java.lang.Short) return boxToFloat((float)unboxToShort(arg));
         throw new NoSuchMethodException();
     }
 
     /** arg.toDouble */
-    public static Double toDouble(Object arg) throws NoSuchMethodException {
-        if (arg instanceof Character) return boxToDouble((double)unboxToChar(arg));
-        if (arg instanceof Byte) return boxToDouble((double)unboxToByte(arg));
-        if (arg instanceof Short) return boxToDouble((double)unboxToShort(arg));
-        if (arg instanceof Integer) return boxToDouble((double)unboxToInt(arg));
-        if (arg instanceof Long) return boxToDouble((double)unboxToLong(arg));
-        if (arg instanceof Float) return boxToDouble((double)unboxToFloat(arg));
-        if (arg instanceof Double) return (Double)arg;
+    public static java.lang.Double toDouble(Object arg) throws NoSuchMethodException {
+        if (arg instanceof java.lang.Integer) return boxToDouble((double)unboxToInt(arg));
+        if (arg instanceof java.lang.Float) return boxToDouble((double)unboxToFloat(arg));
+        if (arg instanceof java.lang.Double) return (java.lang.Double)arg;
+        if (arg instanceof java.lang.Long) return boxToDouble((double)unboxToLong(arg));
+        if (arg instanceof java.lang.Character) return boxToDouble((double)unboxToChar(arg));
+        if (arg instanceof java.lang.Byte) return boxToDouble((double)unboxToByte(arg));
+        if (arg instanceof java.lang.Short) return boxToDouble((double)unboxToShort(arg));
         throw new NoSuchMethodException();
     }
     
diff --git a/src/library/scala/runtime/ByteRef.java b/src/library/scala/runtime/ByteRef.java
index d9d13ed..fc0b4c7 100644
--- a/src/library/scala/runtime/ByteRef.java
+++ b/src/library/scala/runtime/ByteRef.java
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org                **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: ByteRef.java 16881 2009-01-09 16:28:11Z cunei $
 
 
 package scala.runtime;
@@ -17,5 +16,5 @@ public class ByteRef implements java.io.Serializable {
 
     public byte elem;
     public ByteRef(byte elem) { this.elem = elem; }
-    public String toString() { return Byte.toString(elem); }
+    public String toString() { return java.lang.Byte.toString(elem); }
 }
diff --git a/src/library/scala/runtime/CharRef.java b/src/library/scala/runtime/CharRef.java
index 7bd2a0a..48d712b 100644
--- a/src/library/scala/runtime/CharRef.java
+++ b/src/library/scala/runtime/CharRef.java
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: CharRef.java 16881 2009-01-09 16:28:11Z cunei $
 
 
 package scala.runtime;
@@ -17,5 +16,5 @@ public class CharRef implements java.io.Serializable {
 
     public char elem;
     public CharRef(char elem) { this.elem = elem; }
-    public String toString() { return Character.toString(elem); }
+    public String toString() { return java.lang.Character.toString(elem); }
 }
diff --git a/src/library/scala/runtime/DoubleRef.java b/src/library/scala/runtime/DoubleRef.java
index 8e31f7d..d112841 100644
--- a/src/library/scala/runtime/DoubleRef.java
+++ b/src/library/scala/runtime/DoubleRef.java
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: DoubleRef.java 16881 2009-01-09 16:28:11Z cunei $
 
 
 package scala.runtime;
@@ -17,5 +16,5 @@ public class DoubleRef implements java.io.Serializable {
 
     public double elem;
     public DoubleRef(double elem) { this.elem = elem; }
-    public String toString() { return Double.toString(elem); }
+    public String toString() { return java.lang.Double.toString(elem); }
 }
diff --git a/src/library/scala/runtime/DynamicDispatch.java-notyet b/src/library/scala/runtime/DynamicDispatch.java-notyet
new file mode 100644
index 0000000..744ee79
--- /dev/null
+++ b/src/library/scala/runtime/DynamicDispatch.java-notyet
@@ -0,0 +1,42 @@
+package scala.runtime;
+
+import java.dyn.CallSite;
+import java.dyn.MethodHandle;
+
+/**
+ * This class resolves calls through refinement types. The
+ * bootstrap method is called when an invokedynamic is found
+ * by the Java VM.
+ * 
+ * Note: Requires Java 7 with invoke dynamic support (see JSR 292)
+ *
+ * @author Iulian Dragos
+ * @see JSR292
+ */
+public class DynamicDispatch {
+
+    /**
+     * Resolve an invoke dynamic in Scala code. invokedynamic calls appear
+     * when a method defined by a refinement type is called. It is resolved
+     * by looking up a method with the same name and types in the receiver
+     * object. It is guaranteed by the type checker that such a method 
+     * exists.
+     *
+     * The current implementation is not correct, a call site being 
+     * always bootstrapped to a method handle. A bound call site should be
+     * guarded by a test on the receiver type. Such code should either
+     * be generated by the compiler, or by this bootstrap method using
+     * one of the code combinators provided in java.dyn.*. 
+     *
+     * ATM, they are not yet available in the JVM.
+     */
+    public static Object bootstrapInvokeDynamic(CallSite cs, Object... args) {
+        println(cs);
+        
+        MethodHandle mh = MethodHandles.findVirtual(cs.callerClass(),
+                                                    cs.name(),
+                                                    cs.type());
+        cs.setTarget(mh);
+        return mh(args);
+    }
+}
diff --git a/src/library/scala/runtime/ExceptionHandling.java b/src/library/scala/runtime/ExceptionHandling.java
deleted file mode 100644
index 09e5c19..0000000
--- a/src/library/scala/runtime/ExceptionHandling.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: ExceptionHandling.java 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala.runtime;
-
-
-public abstract class ExceptionHandling {
-
-  public static Throwable tryCatch(Runnable runnable) {
-    try {
-      runnable.run();
-      return null;
-    } catch (Throwable exception) {
-      return exception;
-    }
-  }
-
-}
diff --git a/src/library/scala/runtime/FloatRef.java b/src/library/scala/runtime/FloatRef.java
index 5d25502..1fec0e5 100644
--- a/src/library/scala/runtime/FloatRef.java
+++ b/src/library/scala/runtime/FloatRef.java
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: FloatRef.java 16881 2009-01-09 16:28:11Z cunei $
 
 
 package scala.runtime;
@@ -17,5 +16,5 @@ public class FloatRef implements java.io.Serializable {
 
     public float elem;
     public FloatRef(float elem) { this.elem = elem; }
-    public String toString() { return Float.toString(elem); }
+    public String toString() { return java.lang.Float.toString(elem); }
 }
diff --git a/src/library/scala/runtime/IntRef.java b/src/library/scala/runtime/IntRef.java
index f95320a..647cffe 100644
--- a/src/library/scala/runtime/IntRef.java
+++ b/src/library/scala/runtime/IntRef.java
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: IntRef.java 16881 2009-01-09 16:28:11Z cunei $
 
 
 package scala.runtime;
@@ -17,5 +16,5 @@ public class IntRef implements java.io.Serializable {
 
     public int elem;
     public IntRef(int elem) { this.elem = elem; }
-    public String toString() { return Integer.toString(elem); }
+    public String toString() { return java.lang.Integer.toString(elem); }
 }
diff --git a/src/library/scala/runtime/LongRef.java b/src/library/scala/runtime/LongRef.java
index 13563df..708fc12 100644
--- a/src/library/scala/runtime/LongRef.java
+++ b/src/library/scala/runtime/LongRef.java
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: LongRef.java 16881 2009-01-09 16:28:11Z cunei $
 
 
 package scala.runtime;
@@ -17,5 +16,5 @@ public class LongRef implements java.io.Serializable {
 
     public long elem;
     public LongRef(long elem) { this.elem = elem; }
-    public String toString() { return Long.toString(elem); }
+    public String toString() { return java.lang.Long.toString(elem); }
 }
diff --git a/src/library/scala/runtime/MethodCache.scala b/src/library/scala/runtime/MethodCache.scala
new file mode 100644
index 0000000..d205afd
--- /dev/null
+++ b/src/library/scala/runtime/MethodCache.scala
@@ -0,0 +1,83 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http:///               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.runtime
+
+import java.lang.reflect.{ Method => JMethod }
+import java.lang.{ Class => JClass }
+
+import scala.annotation.tailrec
+
+/** An element of a polymorphic object cache.
+  * This class is refered to by the CleanUp phase. Each PolyMethodCache chain
+  * must only relate to one method as PolyMethodCache does not identify
+  * the method name and argument types. In practice, one variable will be
+  * generated per call point, and will uniquely relate to the method called
+  * at that point, making the method name and argument types irrelevant. **/
+/* TODO: if performance is acceptable, PolyMethodCache should be made generic on the method type */
+sealed abstract class MethodCache {
+  /** Searches for a cached method in the MethodCache chain that
+  * is compatible with receiver class "forReceiver". If none is cached,
+  * "null" is returned. If "null is returned", find's caller should look-
+  * up the right method using whichever means it prefers, and add it to
+  * the cache for later use. */
+  def find(forReceiver: JClass[_]): JMethod
+  def add(forReceiver: JClass[_], forMethod: JMethod): MethodCache
+}
+
+final class EmptyMethodCache extends MethodCache {
+
+  def find(forReceiver: JClass[_]): JMethod = null
+      
+  def add(forReceiver: JClass[_], forMethod: JMethod): MethodCache =
+    new PolyMethodCache(this, forReceiver, forMethod, 1)
+  
+}
+
+final class MegaMethodCache(
+  private[this] val forName: String,
+  private[this] val forParameterTypes: Array[JClass[_]]
+) extends MethodCache {
+
+  def find(forReceiver: JClass[_]): JMethod =
+    forReceiver.getMethod(forName, forParameterTypes:_*)
+      
+  def add(forReceiver: JClass[_], forMethod: JMethod): MethodCache = this
+  
+}
+
+final class PolyMethodCache(
+  private[this] val next: MethodCache,
+  private[this] val receiver: JClass[_],
+  private[this] val method: JMethod,
+  private[this] val complexity: Int
+) extends MethodCache {
+  
+  /** To achieve tail recursion this must be a separate method
+   *  from find, because the type of next is not PolyMethodCache.
+   */
+  @tailrec private def findInternal(forReceiver: JClass[_]): JMethod =
+    if (forReceiver eq receiver) method
+    else next match {
+      case x: PolyMethodCache => x findInternal forReceiver
+      case _                  => next find forReceiver
+    }
+  
+  def find(forReceiver: JClass[_]): JMethod = findInternal(forReceiver)
+      
+  // TODO: come up with a more realistic number
+  final private val MaxComplexity = 160    
+  
+  def add(forReceiver: JClass[_], forMethod: JMethod): MethodCache =
+    if (complexity < MaxComplexity)
+      new PolyMethodCache(this, forReceiver, forMethod, complexity + 1)
+    else
+      new MegaMethodCache(forMethod.getName, forMethod.getParameterTypes)
+}
diff --git a/src/library/scala/runtime/NonLocalReturnControl.scala b/src/library/scala/runtime/NonLocalReturnControl.scala
new file mode 100644
index 0000000..f8843e9
--- /dev/null
+++ b/src/library/scala/runtime/NonLocalReturnControl.scala
@@ -0,0 +1,15 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.runtime
+
+import scala.util.control.ControlThrowable
+
+class NonLocalReturnControl[T](val key: AnyRef, val value: T) extends ControlThrowable
diff --git a/src/library/scala/runtime/NonLocalReturnException.scala b/src/library/scala/runtime/NonLocalReturnException.scala
deleted file mode 100644
index 6afc08b..0000000
--- a/src/library/scala/runtime/NonLocalReturnException.scala
+++ /dev/null
@@ -1,23 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: NonLocalReturnException.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala.runtime
-
-
-import Predef.RuntimeException
-
-class NonLocalReturnException[T](val key: AnyRef, val value: T) extends RuntimeException {
-  /*
-   * For efficiency reasons we do not fill in
-   * the execution stack trace.
-   */
-  override def fillInStackTrace(): Throwable = this
-}
diff --git a/src/library/scala/runtime/Nothing$.scala b/src/library/scala/runtime/Nothing$.scala
index bb6139c..fd66996 100644
--- a/src/library/scala/runtime/Nothing$.scala
+++ b/src/library/scala/runtime/Nothing$.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Nothing$.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala.runtime
diff --git a/src/library/scala/runtime/Null$.scala b/src/library/scala/runtime/Null$.scala
index 764c0bb..25662e1 100644
--- a/src/library/scala/runtime/Null$.scala
+++ b/src/library/scala/runtime/Null$.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Null$.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala.runtime
diff --git a/src/library/scala/runtime/ObjectRef.java b/src/library/scala/runtime/ObjectRef.java
index ebd0306..a1567b6 100644
--- a/src/library/scala/runtime/ObjectRef.java
+++ b/src/library/scala/runtime/ObjectRef.java
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: ObjectRef.java 16881 2009-01-09 16:28:11Z cunei $
 
 
 package scala.runtime;
diff --git a/src/library/scala/runtime/RichBoolean.scala b/src/library/scala/runtime/RichBoolean.scala
index 3a316c5..bfff5da 100644
--- a/src/library/scala/runtime/RichBoolean.scala
+++ b/src/library/scala/runtime/RichBoolean.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: RichBoolean.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala.runtime
diff --git a/src/library/scala/runtime/RichByte.scala b/src/library/scala/runtime/RichByte.scala
index e91586d..52ec045 100644
--- a/src/library/scala/runtime/RichByte.scala
+++ b/src/library/scala/runtime/RichByte.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: RichByte.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala.runtime
diff --git a/src/library/scala/runtime/RichChar.scala b/src/library/scala/runtime/RichChar.scala
index 2ba22e4..58c3979 100644
--- a/src/library/scala/runtime/RichChar.scala
+++ b/src/library/scala/runtime/RichChar.scala
@@ -1,19 +1,17 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2006-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: RichChar.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala.runtime
 
-
 import java.lang.Character
-import Predef.NoSuchElementException
+import collection.immutable.NumericRange
 
 /** <p>
  *    For example, in the following code
@@ -45,31 +43,53 @@ final class RichChar(x: Char) extends Proxy with Ordered[Char] {
   def isDigit: Boolean = Character.isDigit(x)
   def isLetter: Boolean = Character.isLetter(x)
   def isLetterOrDigit: Boolean = Character.isLetterOrDigit(x)
-  def isLowerCase: Boolean = Character.isLowerCase(x)
-  def isUpperCase: Boolean = Character.isUpperCase(x)
   def isWhitespace: Boolean = Character.isWhitespace(x)
+  def isSpaceChar: Boolean = Character.isSpaceChar(x)
+  def isHighSurrogate: Boolean = Character.isHighSurrogate(x)
+  def isLowSurrogate: Boolean = Character.isLowSurrogate(x)
+  def isSurrogate: Boolean = isHighSurrogate || isLowSurrogate
+  def isUnicodeIdentifierStart: Boolean = Character.isUnicodeIdentifierStart(x)
+  def isUnicodeIdentifierPart: Boolean = Character.isUnicodeIdentifierPart(x)
+  def isIdentifierIgnorable: Boolean = Character.isIdentifierIgnorable(x)
+  def isMirrored: Boolean = Character.isMirrored(x)
+  
+  def isLower: Boolean = Character.isLowerCase(x)
+  def isUpper: Boolean = Character.isUpperCase(x)
+  def isTitleCase: Boolean = Character.isTitleCase(x)
+  
+  def toLower: Char = Character.toLowerCase(x)
+  def toUpper: Char = Character.toUpperCase(x)
+  def toTitleCase: Char = Character.toTitleCase(x)
+  
+  def getType: Int = Character.getType(x)
+  def getNumericValue: Int = Character.getNumericValue(x)
+  def getDirectionality: Byte = Character.getDirectionality(x)
+  def reverseBytes: Char = Character.reverseBytes(x)
+  
+  // Java 5 Character methods not added:
+  //
+  // public static boolean isDefined(char ch)
+  // public static boolean isJavaIdentifierStart(char ch)
+  // public static boolean isJavaIdentifierPart(char ch)
 
-  def toLowerCase: Char = Character.toLowerCase(x)
-  def toUpperCase: Char = Character.toUpperCase(x)
+  @deprecated("Use ch.toLower instead")
+  def toLowerCase: Char = toLower
+  @deprecated("Use ch.toUpper instead")
+  def toUpperCase: Char = toUpper
+  
+  @deprecated("Use ch.isLower instead")
+  def isLowerCase: Boolean = isLower
+  @deprecated("Use ch.isUpper instead")
+  def isUpperCase: Boolean = isUpper
   
-  /** Create a <code>RandomAccessSeq.Projection[Char]</code> over the characters from 'x' to 'y' - 1
+  /** Create a <code>[Char]</code> over the characters from 'x' to 'limit' - 1
    */
-  def until(limit: Char): RandomAccessSeq.Projection[Char] =
-    if (limit <= x) RandomAccessSeq.empty.projection
-    else
-      new RandomAccessSeq.Projection[Char] {
-        def length = limit - x
-        def apply(i: Int): Char = {
-          Predef.require(i >= 0 && i < length)
-          (x + i).toChar
-        }
-        override def stringPrefix = "RandomAccessSeq.Projection"
-      }
-
-  //def until(y: Char): Iterator[Char] = to(y)
+  def until(limit: Char): NumericRange[Char] = 
+    new NumericRange.Exclusive(x, limit, 1.toChar)
 
-  /** Create a <code>RandomAccessSeq.Projection[Char]</code> over the characters from 'x' to 'y'
+  /** Create a <code>IndexedSeqView[Char]</code> over the characters from 'x' to 'limit'
    */
-  def to(y: Char): RandomAccessSeq.Projection[Char] = until((y + 1).toChar)
+  def to(limit: Char): NumericRange[Char] = 
+    new NumericRange.Inclusive(x, limit, 1.toChar)
 
 }
diff --git a/src/library/scala/runtime/RichDouble.scala b/src/library/scala/runtime/RichDouble.scala
index eadce6d..8a438ad 100644
--- a/src/library/scala/runtime/RichDouble.scala
+++ b/src/library/scala/runtime/RichDouble.scala
@@ -1,33 +1,46 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: RichDouble.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala.runtime
 
+import scala.collection.immutable.{Range, NumericRange}
 
 final class RichDouble(x: Double) extends Proxy with Ordered[Double] {
-
   // Proxy.self
   def self: Any = x
 
-  // Ordered[Double].compare
-  //def compare(y: Double): Int = if (x < y) -1 else if (x > y) 1 else 0
   def compare(y: Double): Int = java.lang.Double.compare(x, y)
 
-  def min(y: Double): Double = Math.min(x, y)
-  def max(y: Double): Double = Math.max(x, y)
-  def abs: Double = Math.abs(x)
+  def min(y: Double): Double = math.min(x, y)
+  def max(y: Double): Double = math.max(x, y)
+  def abs: Double = math.abs(x)
+
+  def round: Long = math.round(x)
+  def ceil: Double = math.ceil(x)
+  def floor: Double = math.floor(x)
+
+  /** See <code>BigDecimal.until</code>. */
+  def until(end: Double): Range.Partial[Double, NumericRange[Double]] =  
+    new Range.Partial(until(end, _))
 
-  def round: Long = Math.round(x)
-  def ceil: Double = Math.ceil(x)
-  def floor: Double = Math.floor(x)
+  /** See <code>BigDecimal.until</code>. */
+  def until(end: Double, step: Double): NumericRange[Double] =
+    Range.Double(x, end, step)
+  
+  /** See <code>BigDecimal.to</code>. */
+  def to(end: Double): Range.Partial[Double, NumericRange[Double]] =
+    new Range.Partial(to(end, _))
+  
+  /** See <code>BigDecimal.to</code>. */
+  def to(end: Double, step: Double): NumericRange[Double] =
+    Range.Double.inclusive(x, end, step)
 
   /** Converts an angle measured in degrees to an approximately equivalent
    *  angle measured in radians.
@@ -35,15 +48,15 @@ final class RichDouble(x: Double) extends Proxy with Ordered[Double] {
    *  @param  x an angle, in degrees
    *  @return the measurement of the angle <code>x</code> in radians.
    */
-  def toRadians: Double = Math.toRadians(x)
+  def toRadians: Double = math.toRadians(x)
 
   /** Converts an angle measured in radians to an approximately equivalent
-   *  angle measured in degrees.
+   *  angle measured in degrees
    *
    *  @param  x angle, in radians
    *  @return the measurement of the angle <code>x</code> in degrees.
    */
-  def toDegrees: Double = Math.toDegrees(x)
+  def toDegrees: Double = math.toDegrees(x)
 
   // isNaN is provided by the implicit conversion to java.lang.Double
   // def isNaN: Boolean = java.lang.Double.isNaN(x)
diff --git a/src/library/scala/runtime/RichException.scala b/src/library/scala/runtime/RichException.scala
index 2720296..a806a3c 100644
--- a/src/library/scala/runtime/RichException.scala
+++ b/src/library/scala/runtime/RichException.scala
@@ -1,28 +1,17 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: RichException.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala.runtime
 
-import Predef._
 import compat.Platform.EOL
 
 final class RichException(exc: Throwable) {
-
-  def getStackTraceString: String = {
-    val s = new StringBuilder()
-    for (trElem <- exc.getStackTrace()) {
-      s.append(trElem.toString())
-      s.append(EOL)
-    }
-    s.toString()
-  }
-
+  def getStackTraceString = exc.getStackTrace().mkString("", EOL, EOL)
 }
diff --git a/src/library/scala/runtime/RichFloat.scala b/src/library/scala/runtime/RichFloat.scala
index a444eb4..e8e351b 100644
--- a/src/library/scala/runtime/RichFloat.scala
+++ b/src/library/scala/runtime/RichFloat.scala
@@ -1,19 +1,16 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: RichFloat.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala.runtime
 
 
-import Predef._
-
 final class RichFloat(x: Float) extends Proxy with Ordered[Float] {
 
   // Proxy.self
@@ -23,13 +20,13 @@ final class RichFloat(x: Float) extends Proxy with Ordered[Float] {
   //def compare(y: Float): Int = if (x < y) -1 else if (x > y) 1 else 0
   def compare(y: Float): Int = java.lang.Float.compare(x, y)
 
-  def min(y: Float) = Math.min(x, y)
-  def max(y: Float) = Math.max(x, y)
-  def abs: Float = Math.abs(x)
+  def min(y: Float) = math.min(x, y)
+  def max(y: Float) = math.max(x, y)
+  def abs: Float = math.abs(x)
 
-  def round: Int = Math.round(x)
-  def ceil: Float = Math.ceil(x).toFloat
-  def floor: Float = Math.floor(x).toFloat
+  def round: Int = math.round(x)
+  def ceil: Float = math.ceil(x).toFloat
+  def floor: Float = math.floor(x).toFloat
 
   /** Converts an angle measured in degrees to an approximately equivalent
    *  angle measured in radians.
@@ -37,7 +34,7 @@ final class RichFloat(x: Float) extends Proxy with Ordered[Float] {
    *  @param  x an angle, in degrees
    *  @return the measurement of the angle <code>x</code> in radians.
    */
-  def toRadians: Float = Math.toRadians(x).toFloat
+  def toRadians: Float = math.toRadians(x).toFloat
 
   /** Converts an angle measured in radians to an approximately equivalent
    *  angle measured in degrees.
@@ -45,7 +42,7 @@ final class RichFloat(x: Float) extends Proxy with Ordered[Float] {
    *  @param  x angle, in radians
    *  @return the measurement of the angle <code>x</code> in degrees.
    */
-  def toDegrees: Float = Math.toDegrees(x).toFloat
+  def toDegrees: Float = math.toDegrees(x).toFloat
 
   // isNaN is provided by the implicit conversion to java.lang.Float
   // def isNaN: Boolean = java.lang.Float.isNaN(x)
diff --git a/src/library/scala/runtime/RichInt.scala b/src/library/scala/runtime/RichInt.scala
index 0ee6c0d..5ae7f9c 100644
--- a/src/library/scala/runtime/RichInt.scala
+++ b/src/library/scala/runtime/RichInt.scala
@@ -1,18 +1,19 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: RichInt.scala 16881 2009-01-09 16:28:11Z cunei $
 
 
 package scala.runtime
 
+import collection.immutable.Range
 
-final class RichInt(start: Int) extends Proxy with Ordered[Int] {
+
+final class RichInt(val start: Int) extends Proxy with Ordered[Int] {
 
   // Proxy
   def self: Any = start
@@ -20,14 +21,12 @@ final class RichInt(start: Int) extends Proxy with Ordered[Int] {
   // Ordered[Int]
   def compare(that: Int): Int = if (start < that) -1 else if (start > that) 1 else 0
 
-  /** See <code>Iterator.range</code>. */
-  def until(end: Int): Range = new Range(start, end, 1)
-
-  /** See <code>Iterator.range</code>. */
-  def until(end: Int, step: Int): Range = new Range(start, end, step)
-
+  def until(end: Int): Range with Range.ByOne = Range(start, end)
+  def until(end: Int, step: Int): Range = Range(start, end, step)
+  
   /** like <code>until</code>, but includes the last index */
-  def to(end: Int) = new Range.Inclusive(start, end, 1)
+  def to(end: Int): Range.Inclusive with Range.ByOne = Range.inclusive(start, end)
+  def to(end: Int, step: Int): Range.Inclusive = Range.inclusive(start, end, step)
 
   def min(that: Int): Int = if (start < that) start else that
   def max(that: Int): Int = if (start > that) start else that
diff --git a/src/library/scala/runtime/RichLong.scala b/src/library/scala/runtime/RichLong.scala
index bee4b2f..311559e 100644
--- a/src/library/scala/runtime/RichLong.scala
+++ b/src/library/scala/runtime/RichLong.scala
@@ -1,16 +1,16 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: RichLong.scala 16881 2009-01-09 16:28:11Z cunei $
 
 
 package scala.runtime
 
+import scala.collection.immutable.{Range, NumericRange}
 
 final class RichLong(x: Long) extends Proxy with Ordered[Long] {
 
@@ -20,6 +20,19 @@ final class RichLong(x: Long) extends Proxy with Ordered[Long] {
   // Ordered[Long].compare
   def compare(y: Long): Int = if (x < y) -1 else if (x > y) 1 else 0
 
+  /** Create a NumericRange[Long] in range <code>[start;end)</code>
+   *  with the specified step, where start is the target Long.
+   *
+   *  @param end    the end value of the range (exclusive)
+   *  @param step   the distance between elements (defaults to 1)
+   *  @return       the range
+   */
+  def until(end: Long, step: Long = 1L): NumericRange.Exclusive[Long] = Range.Long(x, end, step)
+  
+  /** Like until, but inclusive of the end value.
+   */
+  def to(end: Long, step: Long = 1L): NumericRange.Inclusive[Long] = Range.Long.inclusive(x, end, step)
+
   def min(y: Long): Long = if (x < y) x else y
   def max(y: Long): Long = if (x > y) x else y
   def abs: Long = if (x < 0) -x else x
diff --git a/src/library/scala/runtime/RichShort.scala b/src/library/scala/runtime/RichShort.scala
index 1847c66..0fa34b2 100644
--- a/src/library/scala/runtime/RichShort.scala
+++ b/src/library/scala/runtime/RichShort.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: RichShort.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala.runtime
diff --git a/src/library/scala/runtime/RichString.scala b/src/library/scala/runtime/RichString.scala
deleted file mode 100644
index 8b55189..0000000
--- a/src/library/scala/runtime/RichString.scala
+++ /dev/null
@@ -1,262 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: RichString.scala 16881 2009-01-09 16:28:11Z cunei $
-
-
-package scala.runtime
-
-import Predef._
-import scala.util.matching.Regex
-
-final class RichString(val self: String) extends Proxy with RandomAccessSeq[Char] with Ordered[String] {
-  import RichString._  
-  override def apply(n: Int) = self charAt n
-  override def length = self.length
-  override def toString = self
-  override def mkString = self
-
-  override def slice(from: Int, until: Int): RichString = {
-    val len = self.length
-    new RichString(
-      if (from >= until || from >= len)
-        ""
-      else {
-        val from0 = if (from < 0) 0 else from
-        val until0 = if (until > len) len else until
-        self.substring(from0, until0)
-      }
-    )
-  }
-
-  //override def ++ [B >: A](that: Iterable[B]): Seq[B] = {
-  override def ++[B >: Char](that: Iterable[B]): RandomAccessSeq[B] = that match {
-    case that: RichString => new RichString(self + that.self) 
-    case that => super.++(that)
-  }
-  
-  override def take(until: Int): RichString = slice(0, until)
-
-  override def drop(from: Int): RichString = slice(from, self.length)
-
-  override def startsWith[B](that: Seq[B]) = that match {
-    case that: RichString => self startsWith that.self
-    case that => super.startsWith(that)
-  }
-
-  override def endsWith[B](that: Seq[B]) = that match {
-    case that: RichString => self endsWith that.self
-    case that => super.endsWith(that)
-  }
-
-  override def indexOf[B](that: Seq[B]) = that match {
-    case that: RichString => self indexOf that.self
-    case that => super.indexOf(that)
-  }
-
-  override def containsSlice[B](that: Seq[B]) = that match {
-    case that: RichString => self contains that.self
-    case that => super.containsSlice(that)
-  }
-
-  override def reverse: RichString = {
-    val buf = new StringBuilder
-    var i = self.length - 1
-    while (i >= 0) {
-      buf append (self charAt i)
-      i -= 1
-    }
-    new RichString(buf.toString)
-  }
-  
-  /** return n times the current string 
-   */
-  def * (n: Int): String = {
-    val buf = new StringBuilder
-    for (i <- 0 until n) buf append self
-    buf.toString
-  }
-
-  override def compare(other: String) = self compareTo other
-
-  private def isLineBreak(c: Char) = c == LF || c == FF
-
-  /** <p>
-   *    Strip trailing line end character from this string if it has one.
-   *    A line end character is one of
-   *  </p>
-   *  <ul style="list-style-type: none;">
-   *    <li>LF - line feed   (0x0A hex)</li>
-   *    <li>FF - form feed   (0x0C hex)</li>
-   *  </ul>
-   *  <p>
-   *    If a line feed character LF is preceded by a carriage return CR
-   *    (0x0D hex), the CR character is also stripped (Windows convention).
-   *  </p>
-   */
-  def stripLineEnd: String = {
-    val len = self.length
-    if (len == 0) self
-    else {
-      val last = apply(len - 1)
-      if (isLineBreak(last))
-        self.substring(0, if (last == LF && len >= 2 && apply(len - 2) == CR) len - 2 else len - 1)
-      else 
-        self
-    }
-  }
-
-  /** <p>
-   *    Return all lines in this string in an iterator, including trailing
-   *    line end characters.
-   *  </p>
-   *  <p>
-   *    The number of strings returned is one greater than the number of line
-   *    end characters in this string. For an empty string, a single empty
-   *    line is returned. A line end character is one of
-   *  </p>
-   *  <ul style="list-style-type: none;">
-   *    <li>LF - line feed   (0x0A hex)</li>
-   *    <li>FF - form feed   (0x0C hex)</li>
-   *  </ul>
-   */
-  def linesWithSeparators = new Iterator[String] {
-    val len = self.length
-    var index = 0
-    def hasNext: Boolean = index < len
-    def next(): String = {
-      if (index >= len) throw new NoSuchElementException("next on empty iterator")
-      val start = index
-      while (index < len && !isLineBreak(apply(index))) index += 1
-      index += 1
-      self.substring(start, index min len)
-    }
-  }
-
-  /** Return all lines in this string in an iterator, excluding trailing line
-   *  end characters, i.e. apply <code>.stripLineEnd</code> to all lines
-   *  returned by <code>linesWithSeparators</code>.
-   */
-  def lines: Iterator[String] = 
-    linesWithSeparators map (line => new RichString(line).stripLineEnd)
-
-  /** Returns this string with first character converted to upper case */
-  def capitalize: String =
-    if (self == null) null
-    else if (self.length == 0) ""
-    else {
-      val chars = self.toCharArray
-      chars(0) = chars(0).toUpperCase
-      new String(chars)
-    }
-
-  /** <p>
-   *    For every line in this string:
-   *  </p>
-   *  <blockquote>
-   *     Strip a leading prefix consisting of blanks or control characters
-   *     followed by <code>marginChar</code> from the line.
-   *  </blockquote>
-   */
-  def stripMargin(marginChar: Char): String = {
-    val buf = new StringBuilder
-    for (line <- linesWithSeparators) {
-      val len = line.length
-      var index = 0
-      while (index < len && line.charAt(index) <= ' ') index += 1
-      buf append
-        (if (index < len && line.charAt(index) == marginChar) line.substring(index + 1) else line)
-    }
-    buf.toString
-  }
-
-  /** <p>
-   *    For every line in this string:
-   *  </p>
-   *  <blockquote>
-   *     Strip a leading prefix consisting of blanks or control characters
-   *     followed by <code>|</code> from the line.
-   *  </blockquote>
-   */
-  def stripMargin: String = stripMargin('|')
-
-  // NB. "\\Q" + '\\' + "\\E" works on Java 1.5 and newer, but not on Java 1.4
-  private def escape(ch: Char): String = ch match {
-    case '\\' => "\\\\"
-    case _ => "\\Q"+ch+"\\E"
-  }
-
-  @throws(classOf[java.util.regex.PatternSyntaxException])
-  def split(separator: Char): Array[String] = self.split(escape(separator))
-
-  @throws(classOf[java.util.regex.PatternSyntaxException])
-  def split(separators: Array[Char]): Array[String] = {
-    val re = separators.foldLeft("[")(_+escape(_)) + "]"
-    self.split(re)
-  }
-
-  /** You can follow a string with `.r', turning
-   *  it into a Regex. E.g.
-   *
-   *  """A\w*""".r   is the regular expression for identifiers starting with `A'.
-   */
-  def r: Regex = new Regex(self)
-  
-  def toBoolean: Boolean = parseBoolean(self)
-  def toByte: Byte       = java.lang.Byte.parseByte(self)
-  def toShort: Short     = java.lang.Short.parseShort(self)
-  def toInt: Int         = java.lang.Integer.parseInt(self)
-  def toLong: Long       = java.lang.Long.parseLong(self)
-  def toFloat: Float     = java.lang.Float.parseFloat(self)
-  def toDouble: Double   = java.lang.Double.parseDouble(self)
-
-  def toArray: Array[Char] = {
-    val result = new Array[Char](length)
-    self.getChars(0, length, result, 0)
-    result
-  }
-
-
-  /** <p>
-   *  Uses the underlying string as a pattern (in a fashion similar to
-   *  printf in C), and uses the supplied arguments to fill in the
-   *  holes.  Only works on Java 1.5 or higher!
-   *  </p>
-   *  <p>
-   *    The interpretation of the formatting patterns is described in
-   *    <a href="" target="contentFrame" class="java/util/Formatter">
-   *    <code>java.util.Formatter</code></a>.
-   *  </p>
-   *
-   *  @param args the arguments used to instantiating the pattern.
-   *  @throws java.lang.IllegalArgumentException
-   */
-  def format(args : Any*) : String = {
-    val m =  classOf[String].getDeclaredMethod("format", classOf[String], classOf[Array[Object]])
-    m.invoke(null, self, 
-	     args.asInstanceOf[scala.runtime.BoxedObjectArray].
-             unbox(args.getClass).asInstanceOf[Array[Object]]).asInstanceOf[String]
-  }
-}
-
-object RichString {
-  // just statics for rich string.
-  private final val LF: Char = 0x0A
-  private final val FF: Char = 0x0C
-  private final val CR: Char = 0x0D
-  private final val SU: Char = 0x1A
-
-  private def parseBoolean(s: String): Boolean =
-    if (s != null) s.toLowerCase match {
-      case "true" => true
-      case "false" => false
-      case _ => throw new NumberFormatException("For input string: \""+s+"\"")
-    }
-    else
-      throw new NumberFormatException("For input string: \"null\"")
-}
diff --git a/src/library/scala/runtime/RichStringBuilder.scala b/src/library/scala/runtime/RichStringBuilder.scala
deleted file mode 100644
index a530ce5..0000000
--- a/src/library/scala/runtime/RichStringBuilder.scala
+++ /dev/null
@@ -1,57 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: RichStringBuilder.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala.runtime
-
-
-import Predef._
-import scala.collection.mutable.{Buffer,ArrayBuffer}
-
-final class RichStringBuilder(val self : StringBuilder) extends RandomAccessSeq.Mutable[Char] with Proxy with Buffer[Char] {
-  override def length = self.length
-  override def apply(idx : Int) = self.charAt(idx)
-  override def mkString = self.toString
-  override def update(idx : Int, c : Char) = self.setCharAt(idx, c)
-  override def +=(c: Char): Unit = self append c
-  override def ++=(iter: Iterable[Char]): Unit = iter match {
-  case str : RichString => self append str.self
-  case str : Array[Char] => self append str
-  case iter => super.++=(iter)
-  }
-  override def ++(iter: Iterable[Char]): RichStringBuilder = { this ++= iter; this }
-  override def ++[B >: Char](that : Iterable[B]) : RandomAccessSeq[B] = {
-    val buf = new ArrayBuffer[B]
-    this copyToBuffer buf
-    that copyToBuffer buf
-    buf
-  }
-
-  
-  override def insertAll(idx: Int, iter: Iterable[Char]): Unit = iter match {
-  case str : RichString => self.insert(idx, str)
-  case str : Array[Char] => self.insert(idx, str)
-  case iter => 
-    val i = iter.elements
-    var jdx = idx
-    while (i.hasNext) {
-      self.insert(jdx, i.next)
-      jdx = jdx + 1
-    }
-  }
-  override def +:(c : Char) = self.insert(0, c)
-  def ensureSize(size : Int) = self.ensureCapacity(size)
-  override def remove(idx : Int) = {
-    val c = self.charAt(idx)
-    self.deleteCharAt(idx)
-    c
-  }
-  override def clear = self.setLength(0)
-}
diff --git a/src/library/scala/runtime/RichUnit.scala b/src/library/scala/runtime/RichUnit.scala
new file mode 100644
index 0000000..982ec8b
--- /dev/null
+++ b/src/library/scala/runtime/RichUnit.scala
@@ -0,0 +1,22 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.runtime
+
+/** This class exists only as a dummy subclass so that there are two ambiguous
+ *  implicit conversions from Unit to some subclass to Object.
+ *  It's important that this class should NOT inherit from Ordered.
+ *
+ *  Note - in reality the ambiguity is successfully introduced by any2stringadd
+ *  and orderingToOrdered, and adding an implicit from () => RichUnit actually
+ *  resolves the ambiguity by being more specific, and succeeds! So this class
+ *  is probably useless, and unitWrapper has been removed from Predef.
+ */
+final class RichUnit {}
diff --git a/src/library/scala/runtime/ScalaRunTime.scala b/src/library/scala/runtime/ScalaRunTime.scala
index 6b915a6..c7876c2 100644
--- a/src/library/scala/runtime/ScalaRunTime.scala
+++ b/src/library/scala/runtime/ScalaRunTime.scala
@@ -1,150 +1,225 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: ScalaRunTime.scala 16965 2009-01-21 16:12:22Z dragos $
 
 
 package scala.runtime
 
-
-import Predef._
+import scala.reflect.ClassManifest
+import scala.collection.{ Seq, IndexedSeq, TraversableView }
+import scala.collection.mutable.WrappedArray
+import scala.collection.immutable.{ NumericRange, List, Stream, Nil, :: }
+import scala.xml.{ Node, MetaData }
+import scala.util.control.ControlThrowable
 
 /* The object <code>ScalaRunTime</code> provides ...
  */
 object ScalaRunTime {
+  def isArray(x: AnyRef): Boolean = isArray(x, 1)
+  def isArray(x: Any, atLevel: Int): Boolean = 
+    x != null && isArrayClass(x.asInstanceOf[AnyRef].getClass, atLevel)
 
-  /** Names for primitive types, used by array unboxing */
-  val ByteTag = ".Byte"
-  val ShortTag = ".Short"
-  val CharTag = ".Char"
-  val IntTag = ".Int"
-  val LongTag = ".Long"
-  val FloatTag = ".Float"
-  val DoubleTag = ".Double"
-  val BooleanTag = ".Boolean"
-
-  def isArray(x: AnyRef): Boolean = (x != null && x.getClass.isArray) || (x != null && x.isInstanceOf[BoxedArray])
-  def isValueTag(tag: String) = tag.charAt(0) == '.'
-  def isValueClass(clazz: Class[_]) = clazz.isPrimitive()
-  
-  def forceBoxedArray[A <: Any](xs: Seq[A]): Array[A] = {
-    val array = new Array[A](xs.length)
+  private def isArrayClass(clazz: Class[_], atLevel: Int): Boolean =
+    clazz.isArray && (atLevel == 1 || isArrayClass(clazz.getComponentType, atLevel - 1))
+
+  def isValueClass(clazz: Class[_]) = clazz.isPrimitive() 
+
+  /** Retrieve generic array element */
+  def array_apply(xs: AnyRef, idx: Int): Any = xs match {
+    case x: Array[AnyRef]  => x(idx).asInstanceOf[Any]
+    case x: Array[Int]     => x(idx).asInstanceOf[Any]
+    case x: Array[Double]  => x(idx).asInstanceOf[Any]
+    case x: Array[Long]    => x(idx).asInstanceOf[Any]
+    case x: Array[Float]   => x(idx).asInstanceOf[Any]
+    case x: Array[Char]    => x(idx).asInstanceOf[Any]
+    case x: Array[Byte]    => x(idx).asInstanceOf[Any]
+    case x: Array[Short]   => x(idx).asInstanceOf[Any]
+    case x: Array[Boolean] => x(idx).asInstanceOf[Any]
+    case x: Array[Unit]    => x(idx).asInstanceOf[Any]
+    case null => throw new NullPointerException
+  }
+
+  /** update generic array element */
+  def array_update(xs: AnyRef, idx: Int, value: Any): Unit = xs match {
+    case x: Array[AnyRef]  => x(idx) = value.asInstanceOf[AnyRef]
+    case x: Array[Int]     => x(idx) = value.asInstanceOf[Int]
+    case x: Array[Double]  => x(idx) = value.asInstanceOf[Double]
+    case x: Array[Long]    => x(idx) = value.asInstanceOf[Long]
+    case x: Array[Float]   => x(idx) = value.asInstanceOf[Float]
+    case x: Array[Char]    => x(idx) = value.asInstanceOf[Char]
+    case x: Array[Byte]    => x(idx) = value.asInstanceOf[Byte]
+    case x: Array[Short]   => x(idx) = value.asInstanceOf[Short]
+    case x: Array[Boolean] => x(idx) = value.asInstanceOf[Boolean]
+    case x: Array[Unit]    => x(idx) = value.asInstanceOf[Unit]
+    case null => throw new NullPointerException
+  }    
+
+  /** Get generic array length */
+  def array_length(xs: AnyRef): Int = xs match {
+    case x: Array[AnyRef]  => x.length
+    case x: Array[Int]     => x.length
+    case x: Array[Double]  => x.length
+    case x: Array[Long]    => x.length
+    case x: Array[Float]   => x.length
+    case x: Array[Char]    => x.length
+    case x: Array[Byte]    => x.length
+    case x: Array[Short]   => x.length
+    case x: Array[Boolean] => x.length
+    case x: Array[Unit]    => x.length
+    case null => throw new NullPointerException
+  }    
+
+  def array_clone(xs: AnyRef): AnyRef = xs match {
+    case x: Array[AnyRef]  => ArrayRuntime.cloneArray(x)
+    case x: Array[Int]     => ArrayRuntime.cloneArray(x)
+    case x: Array[Double]  => ArrayRuntime.cloneArray(x)
+    case x: Array[Long]    => ArrayRuntime.cloneArray(x)
+    case x: Array[Float]   => ArrayRuntime.cloneArray(x)
+    case x: Array[Char]    => ArrayRuntime.cloneArray(x)
+    case x: Array[Byte]    => ArrayRuntime.cloneArray(x)
+    case x: Array[Short]   => ArrayRuntime.cloneArray(x)
+    case x: Array[Boolean] => ArrayRuntime.cloneArray(x)
+    case x: Array[Unit]    => x
+    case null => throw new NullPointerException
+  }
+
+  /** Convert a numeric value array to an object array.
+   *  Needed to deal with vararg arguments of primitive types that are passed
+   *  to a generic Java vararg parameter T ...
+   */
+  def toObjectArray(src: AnyRef): Array[Object] = {
+    val length = array_length(src)
+    val dest = new Array[Object](length)
+    for (i <- 0 until length)
+      array_update(dest, i, array_apply(src, i))
+    dest
+  }
+
+  def toArray[T](xs: scala.collection.Seq[T]) = {
+    val arr = new Array[AnyRef](xs.length)
     var i = 0
-    for (x <- xs.elements) { array(i) = x; i += 1 }
-    array
+    for (x <- xs) {
+      arr(i) = x.asInstanceOf[AnyRef]
+      i += 1
+    }
+    arr
   }
 
   def checkInitialized[T <: AnyRef](x: T): T = 
     if (x == null) throw new UninitializedError else x
 
-  abstract class Try[a] {
-    def Catch[b >: a](handler: PartialFunction[Throwable, b]): b
-    def Finally(handler: Unit): a
+  abstract class Try[+A] {
+    def Catch[B >: A](handler: PartialFunction[Throwable, B]): B
+    def Finally(fin: => Unit): A
   }
 
-  def Try[a](block: => a): Try[a] = new Try[a] with Runnable {
-    var result: a = _
-    var exception: Throwable = ExceptionHandling.tryCatch(this)
-
-    def run(): Unit = result = block
-
-    def Catch[b >: a](handler: PartialFunction[Throwable, b]): b =
-      if (exception eq null)
-        result.asInstanceOf[b]
-      // !!! else if (exception is LocalReturn)
-      // !!!   // ...
-      else if (handler isDefinedAt exception)
-        handler(exception)
-      else
-        throw exception
-
-    def Finally(handler: Unit): a =
-      if (exception eq null)
-        result.asInstanceOf[a]
-      else
-        throw exception
-  }
+  def Try[A](block: => A): Try[A] = new Try[A] with Runnable {
+    private var result: A = _
+    private var exception: Throwable = 
+      try   { run() ; null }
+      catch { 
+        case e: ControlThrowable  => throw e  // don't catch non-local returns etc
+        case e: Throwable         => e
+      }
+
+    def run() { result = block }
+
+    def Catch[B >: A](handler: PartialFunction[Throwable, B]): B =
+      if (exception == null) result
+      else if (handler isDefinedAt exception) handler(exception)
+      else throw exception
+
+    def Finally(fin: => Unit): A = {
+      fin
 
-  def caseFields(x: Product): List[Any] = {
-    val arity = x.productArity
-    def fields(from: Int): List[Any] =
-      if (from == arity) List()
-      else x.productElement(from) :: fields(from + 1)
-    fields(0)
+      if (exception == null) result
+      else throw exception
+    }
   }
 
   def _toString(x: Product): String =
-    caseFields(x).mkString(x.productPrefix + "(", ",", ")")
+    x.productIterator.mkString(x.productPrefix + "(", ",", ")")
 
+  // def _hashCodeJenkins(x: Product): Int =
+  //   scala.util.JenkinsHash.hashSeq(x.productPrefix.toSeq ++ x.productIterator.toSeq)
+  
   def _hashCode(x: Product): Int = {
-    var code = x.getClass().hashCode()
     val arr =  x.productArity
+    var code = arr
     var i = 0
     while (i < arr) {
       val elem = x.productElement(i)
-      code = code * 41 + (if (elem == null) 0 else elem.hashCode())
+      code = code * 41 + (if (elem == null) 0 else elem.##)
       i += 1
     }
     code
   }
 
+  /** Fast path equality method for inlining; used when -optimise is set.
+   */
+  @inline def inlinedEquals(x: Object, y: Object): Boolean = 
+    if (x eq y) true
+    else if (x eq null) false
+    else if (x.isInstanceOf[java.lang.Number]) BoxesRunTime.equalsNumObject(x.asInstanceOf[java.lang.Number], y)
+    else if (x.isInstanceOf[java.lang.Character]) BoxesRunTime.equalsCharObject(x.asInstanceOf[java.lang.Character], y)
+    else x.equals(y)
+
   def _equals(x: Product, y: Any): Boolean = y match {
-    case y1: Product if x.productArity == y1.productArity =>
-      val arity = x.productArity
-      var i = 0
-      while (i < arity && x.productElement(i) == y1.productElement(i))
-        i += 1
-      i == arity
-    case _ =>
-      false
+    case y: Product if x.productArity == y.productArity => x.productIterator sameElements y.productIterator
+    case _                                              => false
   }
-
-  def _equalsWithVarArgs(x: Product, y: Any): Boolean = y match {
-    case y1: Product if x.productArity == y1.productArity =>
-      val arity = x.productArity
-      var i = 0
-      while (i < arity - 1 && x.productElement(i) == y1.productElement(i))
-        i += 1
-      i == arity - 1 && {
-        x.productElement(i) match {
-          case xs: Seq[_] =>
-            y1.productElement(i) match {
-              case ys: Seq[_] => xs sameElements ys
-            }
-        }
-      }
-    case _ =>
-      false
+  
+  // hashcode -----------------------------------------------------------
+  //
+  // Note that these are the implementations called by ##, so they
+  // must not call ## themselves.
+ 
+  @inline def hash(x: Any): Int =
+    if (x.isInstanceOf[java.lang.Number]) BoxesRunTime.hashFromNumber(x.asInstanceOf[java.lang.Number])
+    else x.hashCode
+  
+  @inline def hash(dv: Double): Int = {
+    val iv = dv.toInt
+    if (iv == dv) return iv
+    
+    val lv = dv.toLong
+    if (lv == dv) return lv.hashCode
+    else dv.hashCode
   }
-
-  //def checkDefined[T >: Null](x: T): T = 
-  //  if (x == null) throw new UndefinedException else x
-
-  def Seq[a](xs: a*): Seq[a] = null // interpreted specially by new backend.
-
-  def arrayValue(x: BoxedArray, elemTag: String): AnyRef =
-    if (x eq null) null else x.unbox(elemTag)
-
-  def arrayValue(x: BoxedArray, elemClass: Class[_]): AnyRef =
-    if (x eq null) null else x.unbox(elemClass)
-
-  def boxArray(value: AnyRef): BoxedArray = value match {
-    case x: Array[Byte] => new BoxedByteArray(x)
-    case x: Array[Short] => new BoxedShortArray(x)
-    case x: Array[Char] => new BoxedCharArray(x)
-    case x: Array[Int] => new BoxedIntArray(x)
-    case x: Array[Long] => new BoxedLongArray(x)
-    case x: Array[Float] => new BoxedFloatArray(x)
-    case x: Array[Double] => new BoxedDoubleArray(x)
-    case x: Array[Boolean] => new BoxedBooleanArray(x)
-    case x: Array[AnyRef] => new BoxedObjectArray(x)
-    case x: BoxedArray => x
+  @inline def hash(fv: Float): Int = {
+    val iv = fv.toInt
+    if (iv == fv) return iv
+    
+    val lv = fv.toLong
+    if (lv == fv) return lv.hashCode
+    else fv.hashCode
   }
+  @inline def hash(lv: Long): Int = {
+    val iv = lv.toInt
+    if (iv == lv) iv else lv.hashCode
+  }
+  @inline def hash(x: Int): Int = x
+  @inline def hash(x: Short): Int = x.toInt
+  @inline def hash(x: Byte): Int = x.toInt
+  @inline def hash(x: Char): Int = x.toInt
+  
+  @inline def hash(x: Number): Int  = runtime.BoxesRunTime.hashFromNumber(x)
+  @inline def hash(x: java.lang.Long): Int = {
+    val iv = x.intValue
+    if (iv == x.longValue) iv else x.hashCode
+  }
+
+  /** A helper method for constructing case class equality methods,
+   *  because existential types get in the way of a clean outcome and
+   *  it's performing a series of Any/Any equals comparisons anyway.
+   *  See ticket #2867 for specifics.
+   */
+  def sameElements(xs1: Seq[Any], xs2: Seq[Any]) = xs1 sameElements xs2
 
   /** Given any Scala value, convert it to a String.
    *
@@ -159,9 +234,35 @@ object ScalaRunTime {
    * @return a string representation of <code>arg</code>
    *
    */  
-  def stringOf(arg : Any): String = arg match {
-    case null => "null"
-    case (arg : AnyRef) if isArray(arg) => boxArray(arg).deepToString
-    case arg => arg.toString
+  def stringOf(arg: Any): String = {
+    import collection.{SortedSet, SortedMap}
+    def mapTraversable(x: Traversable[_], f: Any => String) = x match {
+      case ss: SortedSet[_] => ss.map(f)
+      case ss: SortedMap[_, _] => ss.map(f)
+      case _ => x.map(f)
+    }
+    def inner(arg: Any): String = arg match {
+      case null                     => "null"
+      // Node extends NodeSeq extends Seq[Node] strikes again
+      case x: Node                  => x toString
+      // Not to mention MetaData extends Iterable[MetaData]
+      case x: MetaData              => x toString
+      // Range/NumericRange have a custom toString to avoid walking a gazillion elements
+      case x: Range                 => x toString
+      case x: NumericRange[_]       => x toString
+      case x: AnyRef if isArray(x)  => WrappedArray make x map inner mkString ("Array(", ", ", ")")
+      case x: TraversableView[_, _] => x.toString
+      case x: Traversable[_] if !x.hasDefiniteSize => x.toString
+      case x: Traversable[_]        => 
+        // Some subclasses of AbstractFile implement Iterable, then throw an
+        // exception if you call iterator.  What a world.
+        // And they can't be infinite either.
+        if (x.getClass.getName startsWith "scala.tools.nsc.io") x.toString
+        else (mapTraversable(x, inner)) mkString (x.stringPrefix + "(", ", ", ")")
+      case x                        => x toString
+    }
+    val s = inner(arg)
+    val nl = if (s contains "\n") "\n" else ""
+    nl + s + "\n"    
   }
 }
diff --git a/src/library/scala/runtime/ShortRef.java b/src/library/scala/runtime/ShortRef.java
index d4ff38b..76db3de 100644
--- a/src/library/scala/runtime/ShortRef.java
+++ b/src/library/scala/runtime/ShortRef.java
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: ShortRef.java 16881 2009-01-09 16:28:11Z cunei $
 
 
 package scala.runtime;
@@ -17,4 +16,5 @@ public class ShortRef implements java.io.Serializable {
 
     public short elem;
     public ShortRef(short elem) { this.elem = elem; }
+    public String toString() { return java.lang.Short.toString(elem); }
 }
diff --git a/src/library/scala/runtime/StreamCons.scala b/src/library/scala/runtime/StreamCons.scala
deleted file mode 100644
index 2e34efc..0000000
--- a/src/library/scala/runtime/StreamCons.scala
+++ /dev/null
@@ -1,17 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: StreamCons.scala 16881 2009-01-09 16:28:11Z cunei $
-
-
-package scala.runtime
-
-final class StreamCons[T](xs: => Stream[T]) {
-  def lazy_:: (x: T): Stream[T] = Stream.cons(x, xs)
-  def lazy_::: (ys: Stream[T]): Stream[T] = ys append xs
-}
diff --git a/src/library/scala/runtime/StringAdd.scala b/src/library/scala/runtime/StringAdd.scala
index 536f47a..5ec865e 100644
--- a/src/library/scala/runtime/StringAdd.scala
+++ b/src/library/scala/runtime/StringAdd.scala
@@ -1,19 +1,16 @@
 /*                                                                      *\
 **     ________ ___   __   ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ |_|                                         **
 **                                                                      **
 \*                                                                      */
 
-// $Id: StringAdd.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala.runtime
 
 
-import Predef._
-
 final class StringAdd(self: Any) {
 
   def +(other: String) = String.valueOf(self) + other
@@ -21,7 +18,6 @@ final class StringAdd(self: Any) {
   /** Returns string formatted according to given <code>format</code> string.
    *  Format strings are as for <code>String.format</code>
    *  (@see java.lang.String.format).
-   *  Only works on Java 1.5 or higher!
    */
   def formatted(fmtstr: String): String = fmtstr format self
 }
diff --git a/src/library/scala/runtime/TraitSetter.java b/src/library/scala/runtime/TraitSetter.java
new file mode 100644
index 0000000..d9907c0
--- /dev/null
+++ b/src/library/scala/runtime/TraitSetter.java
@@ -0,0 +1,6 @@
+package scala.runtime;
+
+/** A marker annotation to tag a setter of a mutable variable in a trait
+ */
+public @interface TraitSetter {
+}
\ No newline at end of file
diff --git a/src/library/scala/runtime/VolatileBooleanRef.java b/src/library/scala/runtime/VolatileBooleanRef.java
new file mode 100644
index 0000000..6741dd3
--- /dev/null
+++ b/src/library/scala/runtime/VolatileBooleanRef.java
@@ -0,0 +1,20 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.runtime;
+
+
+public class VolatileBooleanRef implements java.io.Serializable {
+    private static final long serialVersionUID = -5730524563015615974L;
+    
+    volatile public boolean elem;
+    public VolatileBooleanRef(boolean elem) { this.elem = elem; }
+    public String toString() { return "" + elem; }
+}
diff --git a/src/library/scala/runtime/VolatileByteRef.java b/src/library/scala/runtime/VolatileByteRef.java
new file mode 100644
index 0000000..4cddb3e
--- /dev/null
+++ b/src/library/scala/runtime/VolatileByteRef.java
@@ -0,0 +1,20 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org                **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.runtime;
+
+
+public class VolatileByteRef implements java.io.Serializable {
+    private static final long serialVersionUID = -100666928446877072L;
+
+    volatile public byte elem;
+    public VolatileByteRef(byte elem) { this.elem = elem; }
+    public String toString() { return java.lang.Byte.toString(elem); }
+}
diff --git a/src/library/scala/runtime/VolatileCharRef.java b/src/library/scala/runtime/VolatileCharRef.java
new file mode 100644
index 0000000..76cc126
--- /dev/null
+++ b/src/library/scala/runtime/VolatileCharRef.java
@@ -0,0 +1,20 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.runtime;
+
+
+public class VolatileCharRef implements java.io.Serializable {
+    private static final long serialVersionUID = 6537214938268005702L;
+
+    volatile public char elem;
+    public VolatileCharRef(char elem) { this.elem = elem; }
+    public String toString() { return java.lang.Character.toString(elem); }
+}
diff --git a/src/library/scala/runtime/VolatileDoubleRef.java b/src/library/scala/runtime/VolatileDoubleRef.java
new file mode 100644
index 0000000..4720638
--- /dev/null
+++ b/src/library/scala/runtime/VolatileDoubleRef.java
@@ -0,0 +1,19 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.runtime;
+
+public class VolatileDoubleRef implements java.io.Serializable {
+    private static final long serialVersionUID = 8304402127373655534L;
+
+    volatile public double elem;
+    public VolatileDoubleRef(double elem) { this.elem = elem; }
+    public String toString() { return java.lang.Double.toString(elem); }
+}
diff --git a/src/library/scala/runtime/VolatileFloatRef.java b/src/library/scala/runtime/VolatileFloatRef.java
new file mode 100644
index 0000000..e69dd3a
--- /dev/null
+++ b/src/library/scala/runtime/VolatileFloatRef.java
@@ -0,0 +1,20 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.runtime;
+
+
+public class VolatileFloatRef implements java.io.Serializable {
+    private static final long serialVersionUID = -5793980990371366933L;
+
+    volatile public float elem;
+    public VolatileFloatRef(float elem) { this.elem = elem; }
+    public String toString() { return java.lang.Float.toString(elem); }
+}
diff --git a/src/library/scala/runtime/VolatileIntRef.java b/src/library/scala/runtime/VolatileIntRef.java
new file mode 100644
index 0000000..88a8e6b
--- /dev/null
+++ b/src/library/scala/runtime/VolatileIntRef.java
@@ -0,0 +1,19 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.runtime;
+
+public class VolatileIntRef implements java.io.Serializable {
+    private static final long serialVersionUID = 1488197132022872888L;
+    
+    volatile public int elem;
+    public VolatileIntRef(int elem) { this.elem = elem; }
+    public String toString() { return java.lang.Integer.toString(elem); }
+}
diff --git a/src/library/scala/runtime/VolatileLongRef.java b/src/library/scala/runtime/VolatileLongRef.java
new file mode 100644
index 0000000..d7e094e
--- /dev/null
+++ b/src/library/scala/runtime/VolatileLongRef.java
@@ -0,0 +1,20 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.runtime;
+
+
+public class VolatileLongRef implements java.io.Serializable {
+    private static final long serialVersionUID = -3567869820105829499L;
+
+    volatile public long elem;
+    public VolatileLongRef(long elem) { this.elem = elem; }
+    public String toString() { return java.lang.Long.toString(elem); }
+}
diff --git a/src/library/scala/runtime/VolatileObjectRef.java b/src/library/scala/runtime/VolatileObjectRef.java
new file mode 100644
index 0000000..2549b58
--- /dev/null
+++ b/src/library/scala/runtime/VolatileObjectRef.java
@@ -0,0 +1,20 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.runtime;
+
+
+public class VolatileObjectRef implements java.io.Serializable {
+    private static final long serialVersionUID = -9055728157600312291L;
+
+    volatile public Object elem;
+    public VolatileObjectRef(Object elem) { this.elem = elem; }
+    public String toString() { return "" + elem; }
+}
diff --git a/src/library/scala/runtime/VolatileShortRef.java b/src/library/scala/runtime/VolatileShortRef.java
new file mode 100644
index 0000000..ccb160f
--- /dev/null
+++ b/src/library/scala/runtime/VolatileShortRef.java
@@ -0,0 +1,20 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.runtime;
+
+
+public class VolatileShortRef implements java.io.Serializable {
+    private static final long serialVersionUID = 4218441291229072313L;
+
+    volatile public short elem;
+    public VolatileShortRef(short elem) { this.elem = elem; }
+    public String toString() { return java.lang.Short.toString(elem); }
+}
diff --git a/src/library/scala/serializable.scala b/src/library/scala/serializable.scala
index 29c6d21..6269359 100644
--- a/src/library/scala/serializable.scala
+++ b/src/library/scala/serializable.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: serializable.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala
diff --git a/src/library/scala/specialized.scala b/src/library/scala/specialized.scala
new file mode 100644
index 0000000..f4ce207
--- /dev/null
+++ b/src/library/scala/specialized.scala
@@ -0,0 +1,33 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala
+
+/** Annotate type parameters on which code should be automatically
+ *  specialized. For example:
+ *  <code>
+ *    class MyList[@specialized T] ...
+ *  </code>
+ *
+ *  Type T can be specialized on a subset of the primitive types by
+ *  specifying a list of primitive types to specialize at:
+ *
+ *  <code>
+ *   class MyList[@specialized(Int, Double, Boolean) T] ..
+ *  </code>
+ *
+ *  @since 2.8
+ */
+class specialized(types: runtime.AnyValCompanion*) extends StaticAnnotation {
+  def this() {
+    this(Unit, Boolean, Byte, Short, Char, Int, Long, Float, Double)
+  }
+}
+
diff --git a/src/library/scala/testing/Benchmark.scala b/src/library/scala/testing/Benchmark.scala
index 9b9c8e1..8e29d74 100644
--- a/src/library/scala/testing/Benchmark.scala
+++ b/src/library/scala/testing/Benchmark.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Benchmark.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala.testing
@@ -70,18 +69,16 @@ trait Benchmark {
   def prefix: String = getClass().getName()
 
   /**
-   * The entry point. It takes two arguments (n), (name) 
+   * The entry point. It takes two arguments (n),
    *  and an optional argument multiplier (mult).
-   *  (n) is the number of consecutive runs, (name) the name 
-   *  of a log file where to append the times.
-   *  if (mult) is present, the same thing is repeated (mult)
+   *  (n) is the number of consecutive runs,
+   *  if (mult) is present, the n runs are repeated (mult)
    *  times.
    */
   def main(args: Array[String]) {
-    if (args.length > 1) {
-      val logFile = new java.io.FileWriter(args(1), true) // append, not overwrite
-      if (args.length >= 3)
-         multiplier = args(2).toInt
+    if (args.length > 0) {
+      val logFile = new java.io.OutputStreamWriter(System.out)
+      if (args.length > 1) multiplier = args(1).toInt
       logFile.write(prefix)
       for (t <- runBenchmark(args(0).toInt))
         logFile.write("\t\t" + t)
@@ -89,8 +86,13 @@ trait Benchmark {
       logFile.write(Platform.EOL)
       logFile.flush()
     } else {
-      Console.println("Usage: scala benchmarks.program <runs> <logfile>")
-      Console.println("   or: scala benchmarks.program <runs> <logfile> <multiplier>")
+      println("Usage: scala benchmarks.program <runs> ")
+      println("   or: scala benchmarks.program <runs> <multiplier>")
+      println("""
+    The benchmark is run <runs> times, forcing a garbage collection between runs. The optional
+    <multiplier> causes the benchmark to be repeated <multiplier> times, each time for <runs>
+    executions.
+      """)
     }
   }
 }
diff --git a/src/library/scala/testing/SUnit.scala b/src/library/scala/testing/SUnit.scala
index 556586a..f1a4365 100644
--- a/src/library/scala/testing/SUnit.scala
+++ b/src/library/scala/testing/SUnit.scala
@@ -1,17 +1,17 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: SUnit.scala 16881 2009-01-09 16:28:11Z cunei $
 
 
 package scala.testing
 
 import scala.collection.mutable.ArrayBuffer
+import xml.{ Node, NodeSeq }
 
 /**
  * <p>
@@ -44,13 +44,10 @@ import scala.collection.mutable.ArrayBuffer
  *   a <code>main</code> method, for convenience.
  * </p>
  *
- * @deprecated SUnit will be removed in 2.8.0. There are several free and
- * sophisticated testing frameworks for Scala available, examples are
- * "ScalaTest", "ScalaCheck" or "Specs".
- *
  * @author Burak Emir
  */
- at deprecated
+ at deprecated("SUnit will be removed in 2.8.0. There are several free and sophisticated testing\n"+
+            "frameworks for Scala available, examples are \"ScalaTest\", \"ScalaCheck\" or \"Specs\".")
 object SUnit {
 
   /** <p>
@@ -128,7 +125,7 @@ object SUnit {
       buf.length
 
     def failures() =
-      buf.elements map { x => new TestFailure(x) }
+      buf.iterator map { x => new TestFailure(x) }
   }
 
   /** The class <code>TestSuite</code> runs a composite of test cases.
@@ -153,12 +150,9 @@ object SUnit {
 
   /** an AssertFailed is thrown for a failed assertion */
   case class AssertFailed(msg: String, stackTrace: Boolean) extends RuntimeException {
-    private val msg0 = if (stackTrace) {
-      import java.io._
-      val wrt = new StringWriter
-      printStackTrace(new PrintWriter(wrt))
-      wrt.toString
-    } else msg
+    private val msg0 =
+      if (stackTrace) super.getStackTrace().map(_.toString + "\n").mkString
+      else msg
     override def toString() =
       if (msg0 eq null) "failed assertion: " + msg else msg0
   }
@@ -243,6 +237,25 @@ object SUnit {
       assertTrue("(no message)", actual)
     }
 
+    /** Temporary patchwork trying to nurse xml forward. */
+    def assertEqualsXML(msg: String, expected: NodeSeq, actual: NodeSeq) {
+      if (!expected.xml_==(actual))
+        fail(msg, expected, actual)
+    }
+    def assertEqualsXML(msg: String, expected: Seq[Node], actual: Seq[Node]) {
+      assertEqualsXML(msg, expected: NodeSeq, actual: NodeSeq)
+    }
+    
+    def assertEqualsXML(expected: NodeSeq, actual: NodeSeq) {
+      assertEqualsXML("(no message)", expected, actual)
+    }
+
+    def assertSameElementsXML(actual: Seq[Node], expected: Seq[Node]) {
+      val res = (actual: NodeSeq) xml_sameElements expected
+
+      assert(res, "\nassertSameElementsXML:\n  actual = %s\n  expected = %s".format(actual, expected))
+    }
+
     /** throws <code>AssertFailed</code> with given message <code>msg</code>.
      */
     def fail(msg: String) {
diff --git a/src/library/scala/testing/Show.scala b/src/library/scala/testing/Show.scala
index 375db1d..1a3ccbe 100644
--- a/src/library/scala/testing/Show.scala
+++ b/src/library/scala/testing/Show.scala
@@ -1,18 +1,33 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
 package scala.testing
 
-/** Classes inheriting trait `Show` can test their member methods using the notattion
- *  'meth(arg_1, ..., arg_n), where `meth' is the name of the method and `arg_1,...,arg_n' are
- *  the arguments. The only difference to a normal method call is the leading quote character (').
- *  A quoted method call like the one above will produces a legible diagnostic to be printed on Console.
- *  It is of the form
- * 
- *    meth(arg_1, ..., arg_n)  gives  <result>
- * 
- *  where <result> is the result of evaluating the call.
+/** <p>
+ *    Classes inheriting trait <code>Show</code> can test their member methods
+ *    using the notattion <code>meth(arg<sub>1</sub>, ..., arg<sub>n</sub>)</code>,
+ *    where <code>meth</code> is the name of the method and
+ *    <code>arg<sub>1</sub>,...,arg<sub>n</sub></code> are the arguments.
+ *    The only difference to a normal method call is the leading quote
+ *    character ('). A quoted method call like the one above will produces a
+ *    legible diagnostic to be printed on <a href="../Console.html"
+ *    target="ContentFrame"><code>Console</code></a>. It is of the form
+ *  </p><pre>
+ *    meth(arg<sub>1</sub>, ..., arg<sub>n</sub>)  gives  <result></pre>
+ *  <p>
+ *    where <code><result></code> is the result of evaluating the call.
+ *  </p>
  */
 trait Show {
 
-  /** The result class of wrapper `symApply`. 
+  /** The result class of wrapper <code>symApply</code>. 
    *  Prints out diagnostics of method applications.
    */
   class SymApply(f: Symbol) {
diff --git a/src/library/scala/text/Document.scala b/src/library/scala/text/Document.scala
index 15edcd8..b44741d 100644
--- a/src/library/scala/text/Document.scala
+++ b/src/library/scala/text/Document.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Document.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala.text
diff --git a/src/library/scala/throws.scala b/src/library/scala/throws.scala
index 4f09c6b..62dfc8f 100644
--- a/src/library/scala/throws.scala
+++ b/src/library/scala/throws.scala
@@ -1,30 +1,28 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
-*/
+\*                                                                      */
 
-// $Id: throws.scala 16881 2009-01-09 16:28:11Z cunei $
 
 
 package scala
 
-import Predef._
-
 /** <p>
  *    Annotation for specifying the exceptions thrown by a method.
  *    For example:
- *  </p><pre>
- *    <b>class</b> Reader(fname: String) {
- *      <b>private val</b> in =
- *        <b>new</b> BufferedReader(<b>new</b> <a class="java/io/FileReader" href="" target="_top">FileReader</a>(fname))
- *      @throws(classOf[<a class="java/io/IOException" href="" target="_top">IOException</a>])
- *      <b>def</b> read() = in.read()
- *    }</pre>
+ * {{{
+ * class Reader(fname: String) {
+ *   private val in = new BufferedReader(new FileReader(fname))
+ *   @throws(classOf[IOException])
+ *   def read() = in.read()
+ * }
+ * }}}
  *
  * @author  Nikolay Mihaylov
  * @version 1.0, 19/05/2006
+ * @since   2.1
  */
 class throws(clazz: Class[_]) extends StaticAnnotation
diff --git a/src/library/scala/transient.scala b/src/library/scala/transient.scala
index 3d4ac37..12aa15f 100644
--- a/src/library/scala/transient.scala
+++ b/src/library/scala/transient.scala
@@ -1,14 +1,16 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: transient.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala
 
+import annotation.target._
+
+ at field
 class transient extends StaticAnnotation
diff --git a/src/library/scala/unchecked.scala b/src/library/scala/unchecked.scala
index 12da117..7cdce63 100644
--- a/src/library/scala/unchecked.scala
+++ b/src/library/scala/unchecked.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: unchecked.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala
@@ -39,5 +38,7 @@ package scala
  *    <a href="MatchError.html"><code>MatchError</code></a>
  *    will be raised at runtime.
  *  </p>
+ *
+ *  @since 2.4
  */
 class unchecked extends Annotation {}
diff --git a/src/library/scala/unsealed.scala b/src/library/scala/unsealed.scala
deleted file mode 100644
index 1391508..0000000
--- a/src/library/scala/unsealed.scala
+++ /dev/null
@@ -1,17 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: unsealed.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala
-
-/** @deprecated   use <a href="unchecked.html">
- *  <code>@unchecked</code></a> instead.
- */
- at deprecated class unsealed extends Annotation
diff --git a/src/library/scala/util/DynamicVariable.scala b/src/library/scala/util/DynamicVariable.scala
index ce3381e..1b195e2 100644
--- a/src/library/scala/util/DynamicVariable.scala
+++ b/src/library/scala/util/DynamicVariable.scala
@@ -1,18 +1,16 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2006-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: DynamicVariable.scala 16881 2009-01-09 16:28:11Z cunei $
 
 
 package scala.util
 
 
-import Predef._
 import java.lang.InheritableThreadLocal
 
 /** <p>
@@ -42,8 +40,8 @@ import java.lang.InheritableThreadLocal
  *  </pre></blockquote>
  *  <p>
  *    Each thread gets its own stack of bindings.  When a 
- *    new thread is created, the fluid gets a copy of
- *    the stack of bindings from the parent thread, and 
+ *    new thread is created, the DynamicVariable gets a copy
+ *    of the stack of bindings from the parent thread, and 
  *    from then on the bindings for the new thread
  *    are independent of those for the original thread.
  *  </p>
@@ -63,7 +61,7 @@ class DynamicVariable[T](init: T) {
   /** Set the value of the variable while executing the specified
     * thunk.
     *
-    * @param newval The value to which to set the fluid
+    * @param newval The value to which to set the variable
     * @param thunk The code to evaluate under the new setting
     */
   def withValue[S](newval: T)(thunk: =>S): S = {
diff --git a/src/library/scala/util/Marshal.scala b/src/library/scala/util/Marshal.scala
index 9875a37..32c0a15 100644
--- a/src/library/scala/util/Marshal.scala
+++ b/src/library/scala/util/Marshal.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2008-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2008-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: $
 
 
 package scala.util
@@ -19,9 +18,9 @@ package scala.util
  */
 object Marshal {
   import java.io._
-  import scala.reflect.Manifest
+  import scala.reflect.ClassManifest
 
-  def dump[A](o: A)(implicit m: Manifest[A]): Array[Byte] = {
+  def dump[A](o: A)(implicit m: ClassManifest[A]): Array[Byte] = {
     val ba = new ByteArrayOutputStream(512)
     val out = new ObjectOutputStream(ba)
     out.writeObject(m)
@@ -30,15 +29,22 @@ object Marshal {
     ba.toByteArray()
   }
 
+  @throws(classOf[IOException])
   @throws(classOf[ClassCastException])
-  def load[A](buffer: Array[Byte])(implicit expected: Manifest[A]): A = {
+  @throws(classOf[ClassNotFoundException])
+  def load[A](buffer: Array[Byte])(implicit expected: ClassManifest[A]): A = {
     val in = new ObjectInputStream(new ByteArrayInputStream(buffer))
-    val found = in.readObject.asInstanceOf[Manifest[_]]
-    if (! (found <:< expected))
+    val found = in.readObject.asInstanceOf[ClassManifest[_]]
+    if (found <:< expected) {
+      val o = in.readObject.asInstanceOf[A]
+      in.close()
+      o
+    } else {
+      in.close()
       throw new ClassCastException("type mismatch;"+
         "\n found   : "+found+
         "\n required: "+expected)
-    in.readObject.asInstanceOf[A]
+    }
   }
 
 }
diff --git a/src/library/scala/util/Properties.scala b/src/library/scala/util/Properties.scala
index 65b07b9..d64bc7a 100644
--- a/src/library/scala/util/Properties.scala
+++ b/src/library/scala/util/Properties.scala
@@ -1,58 +1,127 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2006-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Properties.scala 16881 2009-01-09 16:28:11Z cunei $
-
 
 package scala.util
 
-/** A utility to load the library properties from a Java properties file
- *  included in the jar.
- *
- *  @author Stephane Micheloud
- */
-object Properties {
+import java.io.{ IOException, PrintWriter }
 
-  /** The name of the properties file */
-  private val propFilename = "/library.properties"
+/** Loads library.properties from the jar. */
+object Properties extends PropertiesTrait {
+  protected def propCategory    = "library"
+  protected def pickJarBasedOn  = classOf[ScalaObject]
+}
 
+private[scala] trait PropertiesTrait
+{
+  protected def propCategory: String      // specializes the remainder of the values
+  protected def pickJarBasedOn: Class[_]  // props file comes from jar containing this
+  
+  /** The name of the properties file */
+  protected val propFilename = "/" + propCategory + ".properties"
+  
   /** The loaded properties */
-  private val props = {
+  protected lazy val scalaProps: java.util.Properties = {
     val props = new java.util.Properties
-    val stream = classOf[Application].getResourceAsStream(propFilename)
-    if (stream != null)
-      props.load(stream)
+    val stream = pickJarBasedOn getResourceAsStream propFilename
+    if (stream ne null)
+      quietlyDispose(props load stream, stream.close)
+    
     props
-  }
-
-  /** The version number of the jar this was loaded from, or
-    * "(unknown)" if it cannot be determined.
-    */
-  val versionString: String = {
-    val defaultString = "(unknown)"
-    "version " + props.getProperty("version.number")
-  }
+  }    
   
-  val copyrightString: String = {
-    val defaultString = "(c) 2002-2009 LAMP/EPFL"
-    props.getProperty("copyright.string", defaultString)
-  }
+  private def quietlyDispose(action: => Unit, disposal: => Unit) =
+    try     { action }
+    finally { 
+        try     { disposal }
+        catch   { case _: IOException => }
+    }
+  
+  def propIsSet(name: String)                   = System.getProperty(name) != null
+  def propIsSetTo(name: String, value: String)  = propOrNull(name) == value
+  def propOrElse(name: String, alt: String)     = System.getProperty(name, alt)
+  def propOrEmpty(name: String)                 = propOrElse(name, "")
+  def propOrNull(name: String)                  = propOrElse(name, null)
+  def propOrNone(name: String)                  = Option(propOrNull(name))
+  def propOrFalse(name: String)                 = propOrNone(name) exists (x => List("yes", "on", "true") contains x.toLowerCase)
+  def setProp(name: String, value: String)      = System.setProperty(name, value)
+  def clearProp(name: String)                   = System.clearProperty(name)
 
-  val encodingString: String = {
-    val defaultString = "UTF8" //"ISO-8859-1"
-    props.getProperty("file.encoding", defaultString)
+  def envOrElse(name: String, alt: String)      = Option(System getenv name) getOrElse alt
+  def envOrNone(name: String)                   = Option(System getenv name)
+  
+  // for values based on propFilename
+  def scalaPropOrElse(name: String, alt: String): String  = scalaProps.getProperty(name, alt)
+  def scalaPropOrEmpty(name: String): String              = scalaPropOrElse(name, "")
+  
+  /** The version number of the jar this was loaded from plus "version " prefix,
+   *  or "version (unknown)" if it cannot be determined.
+   */   
+  val versionString         = "version " + scalaPropOrElse("version.number", "(unknown)")
+  val copyrightString       = scalaPropOrElse("copyright.string", "(c) 2002-2010 LAMP/EPFL")
+  
+  /** This is the encoding to use reading in source files, overridden with -encoding
+   *  Note that it uses "prop" i.e. looks in the scala jar, not the system properties.
+   */
+  def sourceEncoding        = scalaPropOrElse("file.encoding", "UTF-8")
+  
+  /** This is the default text encoding, overridden (unreliably) with
+   *  JAVA_OPTS="-Dfile.encoding=Foo"
+   */
+  def encodingString        = propOrElse("file.encoding", "UTF-8")
+  
+  /** The default end of line character.
+   */  
+  def lineSeparator         = propOrElse("line.separator", "\n")
+  
+  /** Various well-known properties.
+   */
+  def javaClassPath         = propOrEmpty("java.class.path")
+  def javaHome              = propOrEmpty("java.home")
+  def javaVendor            = propOrEmpty("java.vendor")
+  def javaVersion           = propOrEmpty("java.version")
+  def javaVmInfo            = propOrEmpty("java.vm.info")
+  def javaVmName            = propOrEmpty("java.vm.name")
+  def javaVmVendor          = propOrEmpty("java.vm.vendor")
+  def javaVmVersion         = propOrEmpty("java.vm.version")
+  def osName                = propOrEmpty("os.name")
+  def scalaHome             = propOrEmpty("scala.home")
+  def tmpDir                = propOrEmpty("java.io.tmpdir")
+  def userDir               = propOrEmpty("user.dir")
+  def userHome              = propOrEmpty("user.home")
+  def userName              = propOrEmpty("user.name")
+  
+  /** Some derived values.
+   */
+  def isWin                 = osName startsWith "Windows"
+  def isMac                 = javaVendor startsWith "Apple"
+  
+  def versionMsg            = "Scala %s %s -- %s".format(propCategory, versionString, copyrightString)
+  def scalaCmd              = if (isWin) "scala.bat" else "scala"
+  def scalacCmd             = if (isWin) "scalac.bat" else "scalac"
+  
+  /** Can the java version be determined to be at least as high as the argument?
+   *  Hard to properly future proof this but at the rate 1.7 is going we can leave
+   *  the issue for our cyborg grandchildren to solve.
+   */
+  def isJavaAtLeast(version: String) = {
+    val okVersions = version match {
+      case "1.5"    => List("1.5", "1.6", "1.7")
+      case "1.6"    => List("1.6", "1.7")
+      case "1.7"    => List("1.7")
+      case _        => Nil
+    }
+    okVersions exists (javaVersion startsWith _)
   }
 
-  private val writer = new java.io.PrintWriter(Console.err, true)
-
-  val versionMsg = "Scala library " + versionString + " -- " + copyrightString
-
+  // provide a main method so version info can be obtained by running this
   def main(args: Array[String]) {
-    writer.println(versionMsg)
+    val writer = new PrintWriter(Console.err, true)
+    writer println versionMsg
   }
-}
+}  
diff --git a/src/library/scala/util/Random.scala b/src/library/scala/util/Random.scala
index 88a44f8..8fb534b 100644
--- a/src/library/scala/util/Random.scala
+++ b/src/library/scala/util/Random.scala
@@ -1,21 +1,24 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2006-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Random.scala 16881 2009-01-09 16:28:11Z cunei $
 
 
 package scala.util
 
+import collection.immutable.List
+
 /**
  *  @author Stephane Micheloud
  *
  */
 class Random(val self: java.util.Random) {
+  import collection.mutable.ArrayBuffer
+  import collection.generic.CanBuildFrom
 
   /** Creates a new random number generator using a single long seed. */
   def this(seed: Long) = this(new java.util.Random(seed))
@@ -24,7 +27,7 @@ class Random(val self: java.util.Random) {
   def this(seed: Int) = this(seed.toLong)
 
   /** Creates a new random number generator. */
-  def this() = this(compat.Platform.currentTime)
+  def this() = this(new java.util.Random())
 
   /** Returns the next pseudorandom, uniformly distributed boolean value
    *  from this random number generator's sequence.
@@ -50,7 +53,7 @@ class Random(val self: java.util.Random) {
    *  double value with mean 0.0 and standard deviation 1.0 from this
    *  random number generator's sequence.
    */
-  //def nextGaussian(): Double = self.nextGaussian()
+  def nextGaussian(): Double = self.nextGaussian()
 
   /** Returns the next pseudorandom, uniformly distributed int value
    *  from this random number generator's sequence.
@@ -67,7 +70,76 @@ class Random(val self: java.util.Random) {
    *  from this random number generator's sequence.
    */
   def nextLong(): Long = self.nextLong()
+  
+  /** Returns a pseudorandomly generated String.  This routine does
+   *  not take any measures to preserve the randomness of the distribution
+   *  in the face of factors like unicode's variable-length encoding,
+   *  so please don't use this for anything important.  It's primarily
+   *  intended for generating test data.
+   *
+   *  @param  length    the desired length of the String
+   *  @return           the String
+   */
+  def nextString(length: Int) = {
+    def safeChar() = {
+      val surrogateStart: Int = 0xD800
+      val res = nextInt(surrogateStart - 1) + 1
+      res.toChar
+    }
+    
+    List.fill(length)(safeChar()).mkString
+  }
+  
+  /** Returns the next pseudorandom, uniformly distributed value
+   *  from the ASCII range 33-126.
+   */
+  def nextPrintableChar(): Char = {
+    val (low, high) = (33, 126)
+    (self.nextInt(high - low) + low).toChar
+  }
 
   def setSeed(seed: Long) { self.setSeed(seed) }
- 
+    
+  /** Returns a new collection of the same type in a randomly chosen order.
+   * 
+   *  @param  coll    the TraversableOnce to shuffle
+   *  @return         the shuffled TraversableOnce
+   */
+  def shuffle[T, CC[X] <: TraversableOnce[X]](xs: CC[T])(implicit bf: CanBuildFrom[CC[T], T, CC[T]]): CC[T] = {
+    val buf = new ArrayBuffer[T] ++= xs
+        
+    def swap(i1: Int, i2: Int) {
+      val tmp = buf(i1)
+      buf(i1) = buf(i2)
+      buf(i2) = tmp
+    }
+    
+    for (n <- buf.length to 2 by -1) {
+      val k = nextInt(n)
+      swap(n - 1, k)
+    }
+    
+    bf(xs) ++= buf result
+  }
+
+}
+
+/** The object <code>Random</code> offers a default implementation
+ *  of scala.util.Random and random-related convenience methods.
+ *
+ *  @since 2.8
+ */
+object Random extends Random {
+  
+  /** Returns a Stream of pseudorandomly chosen alphanumeric characters,
+   *  equally chosen from A-Z, a-z, and 0-9.
+   * 
+   *  @since 2.8
+   */
+  def alphanumeric: Stream[Char] = {
+    def isAlphaNum(c: Char) = (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9')
+
+    Stream continually nextPrintableChar filter isAlphaNum
+  }
+
 }
diff --git a/src/library/scala/util/Sorting.scala b/src/library/scala/util/Sorting.scala
index c123c8a..d2d6d16 100644
--- a/src/library/scala/util/Sorting.scala
+++ b/src/library/scala/util/Sorting.scala
@@ -6,58 +6,55 @@
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Sorting.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala.util
-
-/** <p>
- *    The Sorting object provides functions that can sort various kinds of
- *    objects. You can provide a comparison function, or you can request a sort
- *    of items that are viewable as <code>Ordered</code>. Some sorts that
- *    operate directly on a subset of value types are also provided. These
- *    implementations are derived from those in the Sun JDK.
- *  </p>
- *  <p>
- *    Note that stability doesn't matter for value types, so use the quickSort
- *    variants for those. <code>stableSort</code> is intended to be used with
- *    objects when the prior ordering should be preserved, where possible.
- *  </p>
- *
- *  @author  Ross Judson
- *  @version 1.0
- */
+import scala.reflect.ClassManifest
+
+/** The Sorting object provides functions that can sort various kinds of
+  * objects. You can provide a comparison function, or you can request a sort
+  * of items that are viewable as <code>Ordered</code>. Some sorts that
+  * operate directly on a subset of value types are also provided. These
+  * implementations are derived from those in the Sun JDK.
+  *
+  * Note that stability doesn't matter for value types, so use the quickSort
+  * variants for those. <code>stableSort</code> is intended to be used with
+  * objects when the prior ordering should be preserved, where possible.
+  *
+  * @author  Ross Judson
+  * @version 1.0
+  */
 object Sorting {
 
   /** Provides implicit access to sorting on arbitrary sequences of orderable
    *  items. This doesn't quite work the way that I want yet -- K should be
    *  bounded as viewable, but the compiler rejects that.
    */
-  implicit def seq2RichSort[K <: Ordered[K]](s: Seq[K]) = new RichSorting[K](s)
+  // implicit def seq2RichSort[K <: Ordered[K] : ClassManifest](s: Seq[K]) = new RichSorting[K](s)
 
   /** Quickly sort an array of Doubles. */
-  def quickSort(a: Array[Double]) = sort1(a, 0, a.length)
+  def quickSort(a: Array[Double]) { sort1(a, 0, a.length) }
 
-  /** Quickly sort an array of items that are viewable as ordered. */
-  def quickSort[K <% Ordered[K]](a: Array[K]) = sort1(a, 0, a.length)
+  /** Quickly sort an array of items with an implicit Ordering. */
+  def quickSort[K](a: Array[K])(implicit ord: Ordering[K]) { sort1(a, 0, a.length) }
 
   /** Quickly sort an array of Ints. */
-  def quickSort(a: Array[Int]) = sort1(a, 0, a.length)
+  def quickSort(a: Array[Int]) { sort1(a, 0, a.length) }
 
   /** Quickly sort an array of Floats. */
-  def quickSort(a: Array[Float]) = sort1(a, 0, a.length)
+  def quickSort(a: Array[Float]) { sort1(a, 0, a.length) }
 
   /** Sort an array of K where K is Ordered, preserving the existing order
-      where the values are equal. */  
-  def stableSort[K <% Ordered[K]](a: Array[K]) {
-    stableSort(a, 0, a.length-1, new Array[K](a.length), (a:K, b:K) => a < b)
+    * where the values are equal. */      
+  def stableSort[K](a: Array[K])(implicit m: ClassManifest[K], ord: Ordering[K]) {
+    stableSort(a, 0, a.length-1, new Array[K](a.length), ord.lt _)
   }
 
   /** Sorts an array of <code>K</code> given an ordering function
    *  <code>f</code>. <code>f</code> should return <code>true</code> iff
    *  its first parameter is strictly less than its second parameter.
    */
-  def stableSort[K](a: Array[K], f: (K,K) => Boolean) {
+  def stableSort[K : ClassManifest](a: Array[K], f: (K,K) => Boolean) {
     stableSort(a, 0, a.length-1, new Array[K](a.length), f)
   }
 
@@ -69,15 +66,15 @@ object Sorting {
    *  @param  f the comparison function.
    *  @return the sorted sequence of items.
    */
-  def stableSort[K](a: Seq[K], f: (K,K) => Boolean): Array[K] = {
+  def stableSort[K : ClassManifest](a: Seq[K], f: (K,K) => Boolean): Array[K] = {
     val ret = a.toArray
     stableSort(ret, f)
     ret
   }
 
   /** Sorts an arbitrary sequence of items that are viewable as ordered. */
-  def stableSort[K <% Ordered[K]](a: Seq[K]): Array[K] =
-    stableSort(a, (a:K, b:K) => a < b)
+  def stableSort[K](a: Seq[K])(implicit m: ClassManifest[K], ord: Ordering[K]): Array[K] =
+    stableSort(a, ord.lt _)
 
   /** Stably sorts a sequence of items given an extraction function that will
    *  return an ordered key from an item.
@@ -86,10 +83,11 @@ object Sorting {
    *  @param  f the comparison function.
    *  @return the sorted sequence of items.
    */
-  def stableSort[K, M <% Ordered[M]](a: Seq[K], f: K => M): Array[K] =
-    stableSort(a, (a: K, b: K) => f(a) < f(b))
+  def stableSort[K, M](a: Seq[K], f: K => M)(implicit m: ClassManifest[K], ord: Ordering[M]): Array[K] =
+    stableSort(a)(m, ord on f)
 
-  private def sort1[K <% Ordered[K]](x: Array[K], off: Int, len: Int) {
+  private def sort1[K](x: Array[K], off: Int, len: Int)(implicit ord: Ordering[K]) {
+    import ord._
     def swap(a: Int, b: Int) {
       val t = x(a)
       x(a) = x(b)
@@ -173,9 +171,9 @@ object Sorting {
 
         // Swap partition elements back to middle
         val n = off + len
-        var s = Math.min(a-off, b-a)
+        var s = math.min(a-off, b-a)
         vecswap(off, b-s, s)
-        s = Math.min(d-c, n-d-1)
+        s = math.min(d-c, n-d-1)
         vecswap(b,   n-s, s)
 
         // Recursively sort non-partition-elements
@@ -274,9 +272,9 @@ object Sorting {
 
         // Swap partition elements back to middle
         val n = off + len
-        var s = Math.min(a-off, b-a)
+        var s = math.min(a-off, b-a)
         vecswap(off, b-s, s)
-        s = Math.min(d-c, n-d-1)
+        s = math.min(d-c, n-d-1)
         vecswap(b,   n-s, s)
 
         // Recursively sort non-partition-elements
@@ -382,9 +380,9 @@ object Sorting {
 
         // Swap partition elements back to middle
         val n = off + len
-        var s = Math.min(a-off, b-a)
+        var s = math.min(a-off, b-a)
         vecswap(off, b-s, s)
-        s = Math.min(d-c, n-d-1)
+        s = math.min(d-c, n-d-1)
         vecswap(b,   n-s, s)
 
         // Recursively sort non-partition-elements
@@ -490,9 +488,9 @@ object Sorting {
 
         // Swap partition elements back to middle
         val n = off + len
-        var s = Math.min(a-off, b-a)
+        var s = math.min(a-off, b-a)
         vecswap(off, b-s, s)
-        s = Math.min(d-c, n-d-1)
+        s = math.min(d-c, n-d-1)
         vecswap(b,   n-s, s)
 
         // Recursively sort non-partition-elements
@@ -507,7 +505,7 @@ object Sorting {
     sort2(off, len)
   }
 
-  private def stableSort[K](a: Array[K], lo: Int, hi: Int, scratch: Array[K], f: (K,K) => Boolean) {
+  private def stableSort[K : ClassManifest](a: Array[K], lo: Int, hi: Int, scratch: Array[K], f: (K,K) => Boolean) {
     if (lo < hi) {
       val mid = (lo+hi) / 2
       stableSort(a, lo, mid, scratch, f)
@@ -531,51 +529,6 @@ object Sorting {
       }
     }
   }
-
-  // for testing
-  def main(args: Array[String]) {
-    val tuples = Array(
-      (1, "one"), (1, "un"), (3, "three"), (2, "deux"),
-      (2, "two"), (0, "zero"), (3, "trois")
-    )
-    val integers = Array(
-      3, 4, 0, 4, 5, 0, 3, 3, 0
-    )
-    val doubles = Array(
-      3.4054752250314283E9,
-      4.9663151227666664E10,
-// 0.0/0.0 is interpreted as Nan      
-//      0.0/0.0,
-      4.9663171987125E10,
-      5.785996973446602E9,
-//      0.0/0.0,
-      3.973064849653333E10,
-      3.724737288678125E10,
-//      0.0/0.0
-    )
-    val floats = Array(
-      3.4054752250314283E9f,
-      4.9663151227666664E10f,
-//      0.0f/0.0f,
-      4.9663171987125E10f,
-      5.785996973446602E9f,
-//      0.0f/0.0f,
-      3.973064849653333E10f,
-      3.724737288678125E10f,
-//      0.0f/0.0f
-    )
-    Sorting quickSort tuples
-    println(tuples.toList)
-
-    Sorting quickSort integers
-    println(integers.toList)
-
-    Sorting quickSort doubles
-    println(doubles.toList)
-
-    Sorting quickSort floats
-    println(floats.toList)
-  }
 }
 
 /** <p>
@@ -584,8 +537,7 @@ object Sorting {
  *    the items are ordered.
  *  </p>
  */
-class RichSorting[K <: Ordered[K]](s: Seq[K]) {
-
+class RichSorting[K](s: Seq[K])(implicit m: ClassManifest[K], ord: Ordering[K]) {
   /** Returns an array with a sorted copy of the RichSorting's sequence.
    */
   def sort = Sorting.stableSort(s)
diff --git a/src/library/scala/util/automata/BaseBerrySethi.scala b/src/library/scala/util/automata/BaseBerrySethi.scala
index b7f066e..8d9a958 100644
--- a/src/library/scala/util/automata/BaseBerrySethi.scala
+++ b/src/library/scala/util/automata/BaseBerrySethi.scala
@@ -1,101 +1,61 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: BaseBerrySethi.scala 16881 2009-01-09 16:28:11Z cunei $
 
 
 package scala.util.automata
 
 
-import scala.util.regexp.Base
+import scala.util.regexp.{ Base }
 
-import scala.collection.mutable
-import scala.collection.immutable
+import scala.collection.{ mutable, immutable }
+import mutable.{ HashMap }
+import immutable.{ Set }
+
+// todo: replace global variable pos with acc
 
 /** this turns a regexp over A into a NondetWorkAutom over A using the
  *  celebrated position automata construction (also called Berry-Sethi or
  *  Glushkov)
  */
 abstract class BaseBerrySethi {
-  
   val lang: Base
-  import lang.{Alt,Eps,Meta,RegExp,Sequ,Star}
+  import lang.{ Alt, Eps, Meta, RegExp, Sequ, Star }
 
   protected var pos = 0
 
-  protected var globalFirst: immutable.Set[Int] = _
-
   // results which hold all info for the NondetWordAutomaton
-  protected var follow: mutable.HashMap[Int, immutable.Set[Int]] = _
+  protected var follow: HashMap[Int, Set[Int]] = _
 
   protected var finalTag: Int = _
 
-  protected var finals: immutable.TreeMap[Int, Int] = _     // final states
+  protected var finals: immutable.Map[Int, Int] = _     // final states
 
   // constants --------------------------
 
-  final val emptySet:immutable.Set[Int] = new immutable.TreeSet[Int]()
+  final val emptySet: Set[Int] = Set()
+  
+  private def doComp(r: RegExp, compFunction: RegExp => Set[Int]) = r match {
+    case x: Alt   => (x.rs map compFirst).foldLeft(emptySet)(_ ++ _)
+    case Eps      => emptySet
+    case x: Meta  => compFunction(x.r)
+    case x: Sequ  =>
+      val (l1, l2) = x.rs span (_.isNullable)
+      ((l1 ++ (l2 take 1)) map compFunction).foldLeft(emptySet)(_ ++ _)
+    case Star(t)  => compFunction(t)
+    case _        => throw new IllegalArgumentException("unexpected pattern " + r.getClass())
+  }
 
   /** computes first( r ) for the word regexp r */
-  protected def compFirst(r: RegExp): immutable.Set[Int] = r match {
-    case x:Alt => 
-      var tmp = emptySet
-      val it = x.rs.elements                       // union
-      while (it.hasNext) { tmp = tmp ++ compFirst(it.next) }
-      tmp
-    case Eps =>
-      emptySet
-    //case x:Letter => emptySet + posMap(x);  // singleton set
-    case x:Meta =>
-      compFirst(x.r)
-    case x:Sequ =>
-      var tmp = emptySet;
-      val it = x.rs.elements;                       // union
-      while (it.hasNext) { 
-	val z = it.next
-	tmp = tmp ++ compFirst(z)
-	if (!z.isNullable)
-          return tmp
-      }
-      tmp
-    case Star(t) =>
-      compFirst(t)
-    case _ =>
-      throw new IllegalArgumentException("unexpected pattern " + r.getClass())
-  }
+  protected def compFirst(r: RegExp): Set[Int] = doComp(r, compFirst)
 
   /** computes last( r ) for the regexp r */
-  protected def compLast(r: RegExp): immutable.Set[Int] = r match {
-    case x:Alt =>
-      var tmp = emptySet
-      val it = x.rs.elements                      // union
-      while (it.hasNext) { tmp = tmp ++ compFirst(it.next) }
-      tmp
-    case Eps =>
-      emptySet
-    //case x:Letter => emptySet + posMap(x) // singleton set
-    case x:Meta =>
-      compLast(x.r)
-    case x:Sequ => 
-      var tmp = emptySet
-      val it = x.rs.elements.toList.reverse.elements       // union
-      while (it.hasNext) { 
-        val z = it.next
-        tmp = tmp ++ compLast(z)
-        if (!z.isNullable)
-          return tmp
-      }
-      tmp
-    case Star(t) =>
-      compLast(t)
-    case _ =>
-      throw new IllegalArgumentException("unexpected pattern " + r.getClass())
-  }
+  protected def compLast(r: RegExp): Set[Int] = doComp(r, compLast)
 
   /** Starts from the right-to-left
    *  precondition: pos is final
@@ -104,24 +64,17 @@ abstract class BaseBerrySethi {
    *  @param r ...
    *  @return  ...
    */
-  protected def compFollow(r: Seq[RegExp]): immutable.Set[Int] = {
-    var first = emptySet
-    var fol = emptySet
-    if (r.length > 0) {//non-empty expr
-
-      val it = r.elements.toList.reverse.elements
-
-      fol = fol + pos // don't modify pos !      
-      while (it.hasNext) { 
-        val p = it.next
-        first = compFollow1(fol, p)
-        fol =
-          if (p.isNullable) fol ++ first
-          else first
-      }
-    }
-    this.follow.update(0, fol /*first*/)
-    fol
+  protected def compFollow(rs: Seq[RegExp]): Set[Int] = {
+    follow(0) =
+      if (rs.isEmpty) emptySet
+      else rs.foldRight(Set(pos))((p, fol) => {
+        val first = compFollow1(fol, p)
+        
+        if (p.isNullable) fol ++ first
+        else first
+      })
+      
+    follow(0)
   }
 
   /** returns the first set of an expression, setting the follow set along 
@@ -131,45 +84,20 @@ abstract class BaseBerrySethi {
    *  @param r    ...
    *  @return     ...
    */
-  protected def compFollow1(fol1: immutable.Set[Int], r: RegExp): immutable.Set[Int] = {
-    var fol = fol1
-    r match {
-  
-      case x:Alt => 
-        var first = emptySet
-        val it = x.rs.elements.toList.reverse.elements
-        while (it.hasNext)
-          first = first ++ compFollow1(fol, it.next);
-        first
-
-      /*
-      case x:Letter =>
-        val i = posMap( x );
-        this.follow.update( i, fol );
-        emptySet + i;
-      */
-      case x:Meta =>
-        compFollow1(fol1, x.r)
-
-      case x:Star =>
-        fol = fol ++ compFirst(x.r)
-        compFollow1(fol, x.r)
-
-      case x:Sequ =>
-        var first = emptySet
-        val it = x.rs.elements.toList.reverse.elements
-        while (it.hasNext) {
-          val p = it.next
-          first = compFollow1(fol, p)
-          fol =
-            if (p.isNullable) fol ++ first
-            else first
-        }
-        first
-
-      case _ =>
-        throw new IllegalArgumentException("unexpected pattern: " + r.getClass())
-    }
+  protected def compFollow1(fol1: Set[Int], r: RegExp): Set[Int] = r match {
+    case x: Alt     => Set(x.rs reverseMap (compFollow1(fol1, _)) flatten: _*)
+    case x: Meta    => compFollow1(fol1, x.r)
+    case x: Star    => compFollow1(fol1 ++ compFirst(x.r), x.r)
+    case x: Sequ    => 
+      var first = emptySet
+      x.rs.foldRight(fol1) { (p, fol) =>
+        val first = compFollow1(fol, p)
+
+        if (p.isNullable) fol ++ first
+        else first
+      }
+      first
+    case _          => throw new IllegalArgumentException("unexpected pattern: " + r.getClass())
   }
 
   /** returns "Sethi-length" of a pattern, creating the set of position
@@ -177,21 +105,12 @@ abstract class BaseBerrySethi {
    *
    *  @param r ...
    */
-  // todo: replace global variable pos with acc
   protected def traverse(r: RegExp): Unit = r match {
     // (is tree automaton stuff, more than Berry-Sethi)
-    case x:Alt =>  
-      val it = x.rs.elements
-      while (it.hasNext) traverse(it.next)
-    case x:Sequ =>
-      val it = x.rs.elements
-      while (it.hasNext) traverse(it.next)
-    case x:Meta =>
-      traverse(x.r)
-    case Star(t) =>
-      traverse(t)
-    case _ =>
-      throw new IllegalArgumentException("unexp pattern " + r.getClass())
+    case x: Alt   => x.rs foreach traverse
+    case x: Sequ  => x.rs foreach traverse
+    case x: Meta  => traverse(x.r)
+    case Star(t)  => traverse(t)
+    case _        => throw new IllegalArgumentException("unexp pattern " + r.getClass())
   }
-
 }
diff --git a/src/library/scala/util/automata/DetWordAutom.scala b/src/library/scala/util/automata/DetWordAutom.scala
index 8566825..b9c4c9e 100644
--- a/src/library/scala/util/automata/DetWordAutom.scala
+++ b/src/library/scala/util/automata/DetWordAutom.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: DetWordAutom.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala.util.automata
@@ -31,23 +30,9 @@ abstract class DetWordAutom[T <: AnyRef] {
   val delta: Array[Map[T,Int]]
   val default: Array[Int]
 
-  /**
-   *  @param q ...
-   *  @return  ...
-   */
   def isFinal(q: Int) = finals(q) != 0
-
-  /**
-   *  @param q ...
-   *  @return  ...
-   */
   def isSink(q: Int) = delta(q).isEmpty && default(q) == q
 
-  /**
-   *  @param q     ...
-   *  @param label ...
-   *  @return      ...
-   */
   def next(q: Int, label: T) = {
     delta(q).get(label) match {
       case Some(p) => p
@@ -59,25 +44,15 @@ abstract class DetWordAutom[T <: AnyRef] {
     val sb = new StringBuilder("[DetWordAutom  nstates=")
     sb.append(nstates)
     sb.append(" finals=")
-    var map = new scala.collection.immutable.ListMap[Int,Int]
-    var j = 0; while( j < nstates ) {
-      if (j < finals.length) 
-        map = map.update(j, finals(j))
-      j += 1
-    }
+    val map = Map(finals.zipWithIndex map (_.swap): _*)
     sb.append(map.toString())
     sb.append(" delta=\n")
+    
     for (i <- 0 until nstates) {
-      sb.append( i )
-      sb.append("->")
-      sb.append(delta(i).toString())
-      sb.append('\n')
-      if (i < default.length) {
-        sb.append("_>")
-        sb.append(default(i).toString())
-        sb.append('\n')
-      }
+      sb append "%d->%s\n".format(i, delta(i))
+      if (i < default.length)
+        sb append "_>%s\n".format(default(i))
     }
-    sb.toString()
+    sb.toString
   }
 }
diff --git a/src/library/scala/util/automata/Inclusion.scala b/src/library/scala/util/automata/Inclusion.scala
index c4db5bd..dd70da3 100644
--- a/src/library/scala/util/automata/Inclusion.scala
+++ b/src/library/scala/util/automata/Inclusion.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Inclusion.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala.util.automata
diff --git a/src/library/scala/util/automata/NondetWordAutom.scala b/src/library/scala/util/automata/NondetWordAutom.scala
index 1a614b2..d7484b9 100644
--- a/src/library/scala/util/automata/NondetWordAutom.scala
+++ b/src/library/scala/util/automata/NondetWordAutom.scala
@@ -1,18 +1,17 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: NondetWordAutom.scala 16881 2009-01-09 16:28:11Z cunei $
 
 
 package scala.util.automata
 
-
-import scala.collection.{immutable, mutable, Set, Map}
+import scala.collection.{ immutable, mutable, Set, Seq, Map }
+import immutable.{ BitSet }
 
 /** A nondeterministic automaton. States are integers, where
  *  0 is always the only initial state. Transitions are represented
@@ -21,14 +20,14 @@ import scala.collection.{immutable, mutable, Set, Map}
  *  All states are reachable. Accepting states are those for which
  *  the partial function 'finals' is defined.
  */
-abstract class NondetWordAutom[T <: AnyRef] {
-
+abstract class NondetWordAutom[T <: AnyRef]
+{
   val nstates: Int
   val labels: Seq[T]
 
   val finals: Array[Int] // 0 means not final
-  val delta: Array[Map[T, immutable.BitSet]]
-  val default: Array[immutable.BitSet]
+  val delta: Array[Map[T, BitSet]]
+  val default: Array[BitSet]
 
   /** returns true if the state is final */
   final def isFinal(state: Int) = finals(state) > 0
@@ -37,76 +36,28 @@ abstract class NondetWordAutom[T <: AnyRef] {
   final def finalTag(state: Int) = finals(state)
   
   /** returns true if the set of states contains at least one final state */
-  final def containsFinal(Q: immutable.BitSet): Boolean = {
-    val it = Q.elements
-    while (it.hasNext) 
-      if (isFinal(it.next))
-        return true
-    return false
-  }
+  final def containsFinal(Q: BitSet): Boolean = Q exists isFinal
   
   /** returns true if there are no accepting states */
-  final def isEmpty = {
-    var r = true
-    var j = 0; while(r && (j < nstates)) {
-      if (isFinal(j)) 
-        r = false
-    }
-    r
-  }
+  final def isEmpty = (0 until nstates) forall (x => !isFinal(x))
 
   /** returns a bitset with the next states for given state and label */
-  def next(q: Int, a: T): immutable.BitSet = {
-    delta(q).get(a) match {
-      case Some(bs) => bs
-      case _        => default(q)
-    }
-  }
+  def next(q: Int, a: T): BitSet = delta(q).getOrElse(a, default(q))
 
   /** returns a bitset with the next states for given state and label */
-  def next(Q: immutable.BitSet, a: T): immutable.BitSet = {
-    val x = new mutable.BitSet(nstates)
-    for (q <- Q) {
-      for (i <- next(q,a)) {
-        x += i
-      }
-    }
-    x.toImmutable
-  }
-
-
-  def nextDefault(Q: immutable.BitSet): immutable.BitSet = {
-    val x = new mutable.BitSet(nstates)
-    for (q <- Q) {
-      for (i <- default(q)) { //@todo: OR
-        x += i
-      }
-    }
-    x.toImmutable
-  }
+  def next(Q: BitSet, a: T): BitSet = next(Q, next(_, a))
+  def nextDefault(Q: BitSet): BitSet = next(Q, default)
+  
+  private def next(Q: BitSet, f: (Int) => BitSet): BitSet =
+    (Q map f).foldLeft(BitSet.empty)(_ ++ _)
 
+  private def finalStates = 0 until nstates filter isFinal
   override def toString = {
-    val sb = new StringBuilder("[NondetWordAutom  nstates=")
-    sb.append(nstates)
-    sb.append("  finals=")
-    var map = new scala.collection.immutable.ListMap[Int,Int]
-    var j = 0; while (j < nstates) {
-      if (isFinal(j))
-        map = map.update(j, finals(j));
-      j += 1
-    }
-    sb.append(map.toString)
-    sb.append("  delta=\n")
-    for (i <- 0 until nstates) {
-      sb.append("    ")
-      sb.append( i )
-      sb.append("->")
-      sb.append(delta(i).toString)
-      sb.append("\n    ")
-      sb.append(" _>")
-      sb.append(default(i).toString)
-      sb.append('\n')
-    }
-    sb.toString()
+    
+    val finalString = Map(finalStates map (j => j -> finals(j)) : _*).toString
+    val deltaString = (0 until nstates) .
+      map (i => "   %d->%s\n    _>%s\n".format(i, delta(i), default(i))) mkString
+    
+    "[NondetWordAutom  nstates=%d  finals=%s  delta=\n%s".format(nstates, finalString, deltaString)
   }
 }
diff --git a/src/library/scala/util/automata/SubsetConstruction.scala b/src/library/scala/util/automata/SubsetConstruction.scala
index 1b10878..584208e 100644
--- a/src/library/scala/util/automata/SubsetConstruction.scala
+++ b/src/library/scala/util/automata/SubsetConstruction.scala
@@ -1,171 +1,103 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: SubsetConstruction.scala 16894 2009-01-13 13:09:41Z cunei $
-
 
 package scala.util.automata
 
-
 class SubsetConstruction[T <: AnyRef](val nfa: NondetWordAutom[T]) {
   import nfa.labels
-  import scala.collection.{immutable, mutable, Map}
-  import immutable.{BitSet, TreeMap, TreeSet}
-
-  implicit def toOrdered(bs: BitSet): Ordered[BitSet] = new Ordered[BitSet] {
-    def compare(that: BitSet): Int = {
-        val it1 = bs.elements
-        val it2 = that.elements
-        var res = 0
-        while((0 == res) && it1.hasNext) {
-          while((0 == res) && it2.hasNext) {
-            if (!it1.hasNext)
-              res = -1
-            else {
-              val i1 = it1.next
-              val i2 = it2.next
-              if (i1 < i2)
-                res = -1
-              else if (i1 > i2)
-                res = 1
-            }
-          }
-          if (it1.hasNext)
-            res = 1
-        }
-        if (it2.hasNext)
-          res = -1
-        res
-    }
-
-    override def equals(other: Any): Boolean = 
-        other match { case that: BitSet => compare(that) == 0
-                      case that: AnyRef => this.eq(that)
-                      case _ => false }
-
-      //case _ => -(other.compare(this))
-  }
-
-  /** the set {0} */
-  final val _initialBitSet = {
-    val rbs = new mutable.BitSet(1)
-    rbs += 0
-    rbs.toImmutable
-  }
-
-  /** the set {} */
-  final val _sinkBitSet = new mutable.BitSet(1).toImmutable
+  import collection.{ mutable, Map }
+  import collection.immutable.BitSet
 
-  final val _emptyBitSet = new scala.collection.mutable.BitSet(1).toImmutable
-
-  def selectTag(Q: BitSet, finals: Array[Int]) = {
-    val it = Q.elements
-    var mintag = Math.MAX_INT
-    while (it.hasNext) {
-      val tag = finals(it.next)
-      if ((0 < tag) && (tag < mintag))
-        mintag = tag
-    }
-    mintag
-  }
+  def selectTag(Q: BitSet, finals: Array[Int]) =
+    Q map finals filter (_ > 0) min
   
-  def determinize: DetWordAutom[T] = {
-    
+  def determinize: DetWordAutom[T] = {    
     // for assigning numbers to bitsets
-    var indexMap    = new TreeMap[BitSet, Int]
-    var invIndexMap = new TreeMap[Int, BitSet]
+    var indexMap    = Map[BitSet, Int]()
+    var invIndexMap = Map[Int, BitSet]()
     var ix = 0
-
+  
     // we compute the dfa with states = bitsets
-    var states   = new TreeSet[BitSet]()
-    val delta    = new mutable.HashMap[BitSet,
-                                       mutable.HashMap[T, BitSet]]
-    var deftrans = new TreeMap[BitSet, BitSet]
-    var finals   = new TreeMap[BitSet, Int]
-
-    val q0 = _initialBitSet
-    states = states + q0
+    val q0 = BitSet(0)            // the set { 0 }
+    val sink = BitSet.empty       // the set { }
     
-    val sink = _emptyBitSet
-    states = states + sink
-
-    deftrans = deftrans.update(q0,sink);
-    deftrans = deftrans.update(sink,sink);
-
-    val rest = new mutable.Stack[BitSet]();
-
+    var states = Set(q0, sink)    // initial set of sets
+    val delta    = new mutable.HashMap[BitSet, mutable.HashMap[T, BitSet]]
+    var deftrans = Map(q0 -> sink, sink -> sink)  // initial transitions
+    var finals: Map[BitSet, Int]  = Map()
+    
+    val rest = new mutable.Stack[BitSet]
+    rest.push(sink, q0)
+    
+    def addFinal(q: BitSet) {
+      if (nfa containsFinal q)
+        finals = finals.updated(q, selectTag(q, nfa.finals))
+    }
     def add(Q: BitSet) {
       if (!states.contains(Q)) {
         states = states + Q
-        rest.push(Q)
-        if (nfa.containsFinal(Q))
-          finals = finals.update(Q, selectTag(Q,nfa.finals));
+        rest push Q
+        addFinal(Q)
       }
     }
-    rest.push(sink) 
-    val sinkIndex = 1
-    rest.push(q0)
+
+    addFinal(q0)                          // initial state may also be a final state
+
     while (!rest.isEmpty) {
-      // assign a number to this bitset
       val P = rest.pop
-      indexMap = indexMap.update(P,ix)
-      invIndexMap = invIndexMap.update(ix,P)
+      // assign a number to this bitset
+      indexMap = indexMap.updated(P, ix)
+      invIndexMap = invIndexMap.updated(ix, P)
       ix += 1
-
-      // make transitiion map
+  
+      // make transition map
       val Pdelta = new mutable.HashMap[T, BitSet]
       delta.update(P, Pdelta)
-
-      val it = labels.elements; while(it.hasNext) {
-        val label = it.next
-        val Q = nfa.next(P,label)
-	Pdelta.update(label, Q)
+  
+      labels foreach { label => 
+        val Q = nfa.next(P, label)
+        Pdelta.update(label, Q)
         add(Q)
       }
-
+  
       // collect default transitions
-      val Pdef = nfa.nextDefault(P)
-      deftrans = deftrans.update(P, Pdef)
+      val Pdef = nfa nextDefault P
+      deftrans = deftrans.updated(P, Pdef)
       add(Pdef)
-    };
+    }
 
     // create DetWordAutom, using indices instead of sets
     val nstatesR = states.size
     val deltaR = new Array[Map[T,Int]](nstatesR)
     val defaultR = new Array[Int](nstatesR)
     val finalsR = new Array[Int](nstatesR)
-  
-    for (w <- states) {
-      val Q = w
+    
+    for (Q <- states) {
       val q = indexMap(Q)
       val trans = delta(Q)
       val transDef = deftrans(Q)
       val qDef = indexMap(transDef)
       val ntrans = new mutable.HashMap[T,Int]()
-      val it = trans.keys; while(it.hasNext) {
-        val label = it.next
-        val p = indexMap(trans(label))
+            
+      for ((label, value) <- trans) {
+        val p = indexMap(value)
         if (p != qDef)
           ntrans.update(label, p)
       }
-      deltaR.update(q, ntrans)
-      defaultR.update(q, qDef)
-
-      //cleanup? leave to garbage collector?
-      //delta.remove(Q);
-      //default.remove(Q);
-      
+  
+      deltaR(q) = ntrans
+      defaultR(q) = qDef
     }
-
-    for (fQ <- finals.keys) finalsR(indexMap(fQ)) = finals(fQ)
+  
+    finals foreach { case (k,v) => finalsR(indexMap(k)) = v }
 
     new DetWordAutom [T] {
-      //type _labelT = SubsetConstruction.this.nfa._labelT;
       val nstates = nstatesR
       val delta = deltaR
       val default = defaultR
diff --git a/src/library/scala/util/automata/WordBerrySethi.scala b/src/library/scala/util/automata/WordBerrySethi.scala
index 6dc8a86..38cd018 100644
--- a/src/library/scala/util/automata/WordBerrySethi.scala
+++ b/src/library/scala/util/automata/WordBerrySethi.scala
@@ -1,20 +1,20 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: WordBerrySethi.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala.util.automata
 
-import scala.collection.{immutable, mutable, Map}
+import scala.collection.{ immutable, mutable, Map }
+import immutable.{ Set }
+import mutable.{ HashSet, HashMap }
 import scala.util.regexp.WordExp
 
-
 /** This class turns a regexp into a NondetWordAutom using the
  *  celebrated position automata construction (also called Berry-Sethi or
  *  Glushkov)
@@ -23,38 +23,28 @@ import scala.util.regexp.WordExp
  *  @version 1.0
  */
 abstract class WordBerrySethi extends BaseBerrySethi {
-
   override val lang: WordExp
 
-  type _labelT = this.lang._labelT
-
-  import lang.{Alt, Eps, Letter, Meta, RegExp, Sequ, Star}
+  import lang.{ Alt, Eps, Letter, Meta, RegExp, Sequ, Star }
 
-
-  protected var labels:mutable.HashSet[_labelT] = _
+  protected var labels: HashSet[lang._labelT] = _
   // don't let this fool you, only labelAt is a real, surjective mapping
-  protected var labelAt: immutable.TreeMap[Int, _labelT] = _ // new alphabet "gamma"
+  protected var labelAt: immutable.Map[Int, lang._labelT] = _ // new alphabet "gamma"
 
-  protected var deltaq: Array[mutable.HashMap[_labelT,List[Int]]] = _ // delta
+  protected var deltaq: Array[HashMap[lang._labelT, List[Int]]] = _ // delta
 
   protected var defaultq: Array[List[Int]] = _ // default transitions
 
-  protected var initials:immutable.Set[Int] = _
-  //NondetWordAutom revNfa
-
-  // maps a letter to an Integer ( the position )
-  // is not *really* needed (preorder determines position!)
-  //protected var posMap: mutable.HashMap[RegExp, Int] = _;
+  protected var initials: Set[Int] = _
 
   /** Computes <code>first(r)</code> where the word regexp <code>r</code>.
    *
    *  @param r the regular expression
    *  @return  the computed set <code>first(r)</code>
    */
-  protected override def compFirst(r: RegExp): immutable.Set[Int] = r match {
-    case x:Letter => emptySet + x.pos //posMap(x);  // singleton set
-    case Eps      => emptySet /*ignore*/
-    case _        => super.compFirst(r)
+  protected override def compFirst(r: RegExp): Set[Int] = r match {
+    case x: Letter  => Set(x.pos)
+    case _          => super.compFirst(r)
   }
 
   /** Computes <code>last(r)</code> where the word regexp <code>r</code>.
@@ -62,10 +52,9 @@ abstract class WordBerrySethi extends BaseBerrySethi {
    *  @param r the regular expression
    *  @return  the computed set <code>last(r)</code>
    */
-  protected override def compLast(r: RegExp): immutable.Set[Int] = r match {
-    case x:Letter => emptySet + x.pos //posMap(x) // singleton set
-    case Eps      => emptySet /*ignore*/
-    case _        => super.compLast(r)
+  protected override def compLast(r: RegExp): Set[Int] = r match {
+    case x: Letter  => Set(x.pos)
+    case _          => super.compLast(r)
   }
 
   /** Returns the first set of an expression, setting the follow set along 
@@ -75,38 +64,25 @@ abstract class WordBerrySethi extends BaseBerrySethi {
    *  @param r    the regular expression
    *  @return     the computed set
    */
-  protected override def compFollow1(fol1: immutable.Set[Int], r: RegExp): immutable.Set[Int] =
-    r match {
-      case x:Letter =>
-        //val i = posMap(x)
-        val i = x.pos
-        this.follow.update(i, fol1)
-        emptySet + i
-      case Eps =>
-        emptySet /*ignore*/
-      case _ =>
-        super.compFollow1(fol1, r)
+  protected override def compFollow1(fol1: Set[Int], r: RegExp): Set[Int] = r match {
+      case x: Letter  => follow(x.pos) = fol1 ; Set(x.pos)
+      case Eps        => emptySet
+      case _          => super.compFollow1(fol1, r)
     }
 
   /** returns "Sethi-length" of a pattern, creating the set of position
    *  along the way
    */
 
-
   /** called at the leaves of the regexp */
-  protected def seenLabel(r: RegExp, i: Int, label: _labelT) {
-    //Console.println("seenLabel (1)");
-    //this.posMap.update(r, i)
-    this.labelAt = this.labelAt.update(i, label)
-    //@ifdef if( label != Wildcard ) {
-      this.labels += label
-    //@ifdef }
+  protected def seenLabel(r: RegExp, i: Int, label: lang._labelT) {
+    labelAt = labelAt.updated(i, label)
+    this.labels += label
   }
 
-  // overriden in BindingBerrySethi
-  protected def seenLabel(r: RegExp, label: _labelT): Int = {
-    //Console.println("seenLabel (2)");
-    pos = pos + 1
+  // overridden in BindingBerrySethi
+  protected def seenLabel(r: RegExp, label: lang._labelT): Int = {
+    pos += 1
     seenLabel(r, pos, label)
     pos
   }
@@ -114,151 +90,74 @@ abstract class WordBerrySethi extends BaseBerrySethi {
   // todo: replace global variable pos with acc
   override def traverse(r: RegExp): Unit = r match {
     case a @ Letter(label) => a.pos = seenLabel(r, label)
-    case Eps               => /*ignore*/
+    case Eps               => // ignore
     case _                 => super.traverse(r)
   }
 
 
-  protected def makeTransition(src: Int, dest: Int, label: _labelT ) {
-    //@ifdef compiler if( label == Wildcard )
-    //@ifdef compiler   defaultq.update(src, dest::defaultq( src ))
-    //@ifdef compiler else 
+  protected def makeTransition(src: Int, dest: Int, label: lang._labelT) {
     val q = deltaq(src)
-    q.update(label, dest::(q.get(label) match {
-      case Some(x) => x
-      case _       => Nil
-    }))
+    q.update(label, dest :: q.getOrElse(label, Nil))
   }
 
   protected def initialize(subexpr: Seq[RegExp]): Unit = {
-    //this.posMap = new mutable.HashMap[RegExp,Int]()
-    this.labelAt = new immutable.TreeMap[Int, _labelT]()
-    this.follow = new mutable.HashMap[Int, immutable.Set[Int]]()
-    this.labels = new mutable.HashSet[_labelT]()
-
+    this.labelAt = immutable.Map()
+    this.follow = HashMap()
+    this.labels = HashSet()
     this.pos = 0
 
     // determine "Sethi-length" of the regexp
-    //activeBinders = new Vector()
-    var it = subexpr.elements
-    while (it.hasNext) 
-      traverse(it.next)
-
-    //assert(activeBinders.isEmpty())
-    this.initials = emptySet + 0
+    subexpr foreach traverse
+    
+    this.initials = Set(0)
   }
 
   protected def initializeAutom() {
-    finals   = immutable.TreeMap.empty[Int, Int] // final states
-    deltaq   = new Array[mutable.HashMap[_labelT, List[Int]]](pos) // delta
-    defaultq = new Array[List[Int]](pos) // default transitions
-
-    var j = 0
-    while (j < pos) {
-      deltaq(j) = new mutable.HashMap[_labelT,List[Int]]()
+    finals   = immutable.Map.empty[Int, Int]                    // final states
+    deltaq   = new Array[HashMap[lang._labelT, List[Int]]](pos) // delta
+    defaultq = new Array[List[Int]](pos)                        // default transitions
+    
+    for (j <- 0 until pos) {
+      deltaq(j) = HashMap[lang._labelT, List[Int]]()
       defaultq(j) = Nil
-      j += 1
     }
   }
 
-  protected def collectTransitions(): Unit = {  // make transitions
-    //Console.println("WBS.collectTrans, this.follow.keys = "+this.follow.keys)
-    //Console.println("WBS.collectTrans, pos = "+this.follow.keys)
-    var j = 0; while (j < pos) {
-      //Console.println("WBS.collectTrans, j = "+j)
-      val fol = this.follow(j)
-      val it = fol.elements
-      while (it.hasNext) {
-        val k = it.next
-        if (pos == k)
-          finals = finals.update(j, finalTag)
-        else
-          makeTransition( j, k, labelAt(k))
-      }
-      j += 1
+  protected def collectTransitions(): Unit =                // make transitions
+    for (j <- 0 until pos ; val fol = follow(j) ; k <- fol) {
+      if (pos == k) finals = finals.updated(j, finalTag)
+      else makeTransition(j, k, labelAt(k))
     }
-  }
 
-  def automatonFrom(pat: RegExp, finalTag: Int): NondetWordAutom[_labelT] = {
+  def automatonFrom(pat: RegExp, finalTag: Int): NondetWordAutom[lang._labelT] = {
     this.finalTag = finalTag
 
     pat match {
-      case x:Sequ =>
+      case x: Sequ =>
         // (1,2) compute follow + first
         initialize(x.rs)
-        pos = pos + 1
-        globalFirst = compFollow(x.rs)
+        pos += 1
+        compFollow(x.rs)  // this used to be assigned to var globalFirst and then never used.
 
-        //System.out.print("someFirst:");debugPrint(someFirst);
         // (3) make automaton from follow sets
         initializeAutom()
         collectTransitions()
 
         if (x.isNullable) // initial state is final
-          finals = finals.update(0, finalTag)
-
-        var delta1: immutable.TreeMap[Int, Map[_labelT, List[Int]]] =
-          new immutable.TreeMap[Int, Map[_labelT, List[Int]]]
-
-        var i = 0
-        while (i < deltaq.length) {
-          delta1 = delta1.update(i, deltaq(i))
-          i += 1
-        }
-        val finalsArr = new Array[Int](pos)
-
-        {
-          var k = 0; while (k < pos) {
-            finalsArr(k) = finals.get(k) match {
-              case Some(z) => z
-              case None => 0 // 0 == not final
-            };
-            k += 1
-          }
-        }
-
-        val initialsArr = new Array[Int](initials.size)
-        val it = initials.elements
-
-        {
-          var k = 0; while (k < initials.size) {
-            initialsArr(k) = it.next
-            k += 1
-          }
-        }
+          finals = finals.updated(0, finalTag)
+          
+        val delta1      = immutable.Map(deltaq.zipWithIndex map (_.swap): _*)
+        val finalsArr   = 0 until pos map (k => finals.getOrElse(k, 0)) toArray  // 0 == not final
+        val initialsArr = initials.toArray
 
-        val deltaArr = new Array[Map[_labelT, immutable.BitSet]](pos)
+        val deltaArr: Array[Map[lang._labelT, immutable.BitSet]] = 
+          (0 until pos map { x =>
+            HashMap(delta1(x).toSeq map { case (k, v) => k -> immutable.BitSet(v: _*) } : _*)
+          }) toArray
 
-        {
-          var k = 0; while(k < pos) {
-            val labels = delta1(k).keys
-            val hmap =
-              new mutable.HashMap[_labelT, immutable.BitSet]
-            for (lab <- labels) {
-              val trans = delta1(k)
-              val x = new mutable.BitSet(pos)
-              for (q <- trans(lab))
-                x += q
-              hmap.update(lab, x.toImmutable)
-            }
-            deltaArr(k) = hmap
-            k += 1
-          }
-        }
-        val defaultArr = new Array[immutable.BitSet](pos)
-
-        {
-          var k = 0; while(k < pos) {
-            val x = new mutable.BitSet(pos)
-            for (q <- defaultq(k))
-              x += q
-            defaultArr(k) = x.toImmutable
-            k += 1
-          }
-        }
+        val defaultArr  = 0 until pos map (k => immutable.BitSet(defaultq(k): _*)) toArray
 
-        new NondetWordAutom[_labelT] {
-          type _labelT = WordBerrySethi.this._labelT
+        new NondetWordAutom[lang._labelT] {
           val nstates  = pos
           val labels   = WordBerrySethi.this.labels.toList
           val initials = initialsArr
@@ -267,35 +166,7 @@ abstract class WordBerrySethi extends BaseBerrySethi {
           val default  = defaultArr
         }
       case z =>
-       val z1 = z.asInstanceOf[this.lang._regexpT]
-       automatonFrom(Sequ(z1), finalTag)
+       automatonFrom(Sequ(z.asInstanceOf[this.lang._regexpT]), finalTag)
     }
   }
-
-  /*
-   void print1() {
-   System.out.println("after sethi-style processing");
-   System.out.println("#positions:" + pos);
-   System.out.println("posMap:");
-
-   for (Iterator it = this.posMap.keySet().iterator();
-   it.hasNext(); ) {
-   Tree t = (Tree) it.next();
-                  switch(t) {
-                  case Literal( _ ):
-                        System.out.print( "(" + t.toString() + " -> ");
-                        String s2 = ((Integer) posMap.get(t)).toString();
-                        System.out.print( s2 +") ");
-                  }
-            }
-            System.out.println("\nfollow: ");
-            for (int j = 1; j < pos; j++ ) {
-                  TreeSet fol = (TreeSet) this.follow.get(new Integer(j));
-                  System.out.print("("+j+" -> "+fol.toString()+") ");
-                  //debugPrint( fol );
-                  System.out.println();
-            }
-
-      }
-    */
-}
+}
\ No newline at end of file
diff --git a/src/library/scala/util/control/Breaks.scala b/src/library/scala/util/control/Breaks.scala
new file mode 100644
index 0000000..5ca1aa9
--- /dev/null
+++ b/src/library/scala/util/control/Breaks.scala
@@ -0,0 +1,64 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.util.control
+
+/** A class that can be instantiated for the break control abstraction.
+ *  Example usage:<pre>
+ *
+ *  val mybreaks = new Breaks
+ *  import</b> mybreaks.{break, breakable}
+ *
+ *  breakable {
+ *    <b>for</b> (...) {
+ *      <b>if</b> (...) break
+ *    }
+ *  }</pre>
+ *
+ *  Calls to break from one instantiation of Breaks will never
+ *  target breakable objects of some other instantion.
+ */  
+class Breaks {
+
+  private val breakException = new BreakControl
+
+  /** A block from which one can exit with a `break''. */
+  def breakable(op: => Unit) {
+    try {
+      op
+    } catch {
+      case ex: BreakControl => 
+        if (ex ne breakException) throw ex
+    }
+  }
+
+  /* Break from dynamically closest enclosing breakable block
+   * @note this might be different than the statically closest enclosing
+   * block!
+   */
+  def break { throw breakException }
+} 
+
+/** An object that can be used for the break control abstraction.
+ *  Example usage:<pre>
+ *
+ *  <b>import</b> Breaks.{break, breakable}
+ *
+ *  breakable {
+ *    <b>for</b> (...) {
+ *      <b>if</b> (...) break
+ *    }
+ *  }</pre>
+ *
+ */  
+object Breaks extends Breaks
+
+private class BreakControl extends ControlThrowable
+
diff --git a/src/library/scala/util/control/ControlThrowable.scala b/src/library/scala/util/control/ControlThrowable.scala
new file mode 100644
index 0000000..9fde68d
--- /dev/null
+++ b/src/library/scala/util/control/ControlThrowable.scala
@@ -0,0 +1,38 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+package scala.util.control
+
+/**
+ * A marker trait indicating that the <code>Throwable</code> it is mixed
+ * into is intended for flow control.
+ *
+ * <p>Note that <code>Throwable</code> subclasses which extend this trait
+ * may extend any other <code>Throwable</code> subclass (eg.
+ * <code>RuntimeException</code>) and are not required to extend
+ * <code>Throwable</code> directly.</p>
+ * 
+ * <p>Instances of <code>Throwable</code> subclasses marked in
+ * this way should not normally be caught. Where catch-all behaviour is
+ * required <code>ControlThrowable</code>s should be propagated, for
+ * example,</p>
+ *
+ * <pre>
+ *  import scala.util.control.ControlThrowable
+ *
+ *  try {
+ *    // Body might throw arbitrarily
+ * } catch {
+ *   case ce : ControlThrowable => throw ce // propagate
+ *   case t : Exception => log(t)           // log and suppress
+ * </pre>
+ *
+ * @author Miles Sabin
+ */
+trait ControlThrowable extends Throwable with NoStackTrace
diff --git a/src/library/scala/util/control/Exception.scala b/src/library/scala/util/control/Exception.scala
new file mode 100644
index 0000000..c343809
--- /dev/null
+++ b/src/library/scala/util/control/Exception.scala
@@ -0,0 +1,214 @@
+package scala.util.control
+
+import collection.immutable.List
+
+/** Classes representing the components of exception handling.
+ *  Each class is independently composable.  Some common uses:
+ *  
+ *  <pre>
+ *  <b>import</b> scala.util.control.Exception._
+ *  <b>import</b> java.net._
+ *
+ *  <b>val</b> s = "http://www.scala-lang.org/"
+ *  <b>val</b> x1 = catching(classOf[MalformedURLException]) opt new URL(s)
+ *  <b>val</b> x2 = catching(classOf[MalformedURLException], classOf[NullPointerException]) either new URL(s)
+ *  </pre>
+ *  @author Paul Phillips
+ */
+
+import java.lang.reflect.InvocationTargetException
+
+object Exception
+{
+  // We get lots of crashes using this, so for now we just use Class[_]
+  // type ExClass = Class[_ <: Throwable]
+  
+  type Catcher[+T] = PartialFunction[Throwable, T]
+  type ExceptionCatcher[+T] = PartialFunction[Exception, T]
+  
+  // due to the magic of contravariance, Throwable => T is a subtype of 
+  // Exception => T, not the other way around.  So we manually construct
+  // a Throwable => T and simply rethrow the non-Exceptions.
+  implicit def fromExceptionCatcher[T](pf: ExceptionCatcher[T]): Catcher[T] = {
+    new PartialFunction[Throwable, T] {
+      def isDefinedAt(x: Throwable) = x match {
+        case e: Exception if pf.isDefinedAt(e)  => true
+        case _                                  => false
+      }      
+      def apply(x: Throwable) = x match {
+        case e: Exception if pf.isDefinedAt(e)  => pf(e)
+        case e                                  => throw e
+      }
+    }
+  }
+
+  trait Described { 
+    protected val name: String
+    private var _desc: String = ""
+    def desc = _desc
+    def withDesc(s: String): this.type = {
+      _desc = s
+      this
+    }
+    override def toString() = name + "(" + desc + ")"
+  }
+  
+  /** A container class for finally code. */
+  class Finally private[Exception](body: => Unit) extends Described {
+    protected val name = "Finally"
+    
+    def and(other: => Unit): Finally = new Finally({ body ; other })
+    def invoke(): Unit = { body }
+  }
+  
+  /** A container class for catch/finally logic. */
+  class Catch[+T] private[Exception](
+    private[Exception] val pf: Catcher[T],
+    private[Exception] val fin: Option[Finally])
+  extends Described
+  {
+    def this(pf: Catcher[T]) = this(pf, None)
+    protected val name = "Catch"
+    
+    /** Create a new Catch with additional exception handling logic. */
+    def or[U >: T](pf2: Catcher[U]): Catch[U] = new Catch(pf orElse pf2, fin)
+    def or[U >: T](other: Catch[U]): Catch[U] = or(other.pf)
+    
+    /** Apply this catch logic to the supplied body. */
+    def apply[U >: T](body: => U): U = {      
+      try     { body }
+      catch   { case e if pf.isDefinedAt(e) => pf(e) }
+      finally { fin.map(_.invoke()) }
+    }
+    
+    /* Create an empty Try container with this Catch and the supplied Finally */
+    def andFinally(body: => Unit): Catch[T] = fin match {
+      case None     => new Catch(pf, Some(new Finally(body)))
+      case Some(f)  => new Catch(pf, Some(f and body))
+    }
+    
+    /** Apply this catch logic to the supplied body, mapping the result
+     *  into Option[T] - None if any exception was caught, Some(T) otherwise.
+     */
+    def opt[U >: T](body: => U): Option[U] = toOption(Some(body))
+    
+    /** Apply this catch logic to the supplied body, mapping the result
+     *  into Either[Throwable, T] - Left(exception) if an exception was caught,
+     *  Right(T) otherwise.
+     */
+    def either[U >: T](body: => U): Either[Throwable, U] = toEither(Right(body))
+    
+    /** Create a new Catch with the same isDefinedAt logic as this one,
+      * but with the supplied apply method replacing the current one. */
+    def withApply[U](f: (Throwable) => U): Catch[U] = {
+      val pf2 = new PartialFunction[Throwable, U] {
+        def isDefinedAt(x: Throwable) = pf isDefinedAt x
+        def apply(x: Throwable) = f(x)
+      }
+      new Catch(pf2, fin)
+    }
+
+    /** Convenience methods. */
+    def toOption: Catch[Option[T]] = withApply(_ => None)
+    def toEither: Catch[Either[Throwable, T]] = withApply(Left(_))
+  }
+  
+  /** A container class for Try logic */
+  class Try[+T] private[Exception](body: => T, val catcher: Catch[T]) {    
+    /** Execute "body" using catch/finally logic "catcher" */
+    def apply(): T                    = catcher(body)
+    def apply[U >: T](other: => U): U = catcher(other)
+        
+    /** As apply, but map caught exceptions to None and success to Some(T) */
+    def opt(): Option[T]                      = catcher opt body
+    def opt[U >: T](other: => U): Option[U]   = catcher opt other
+    
+    /** As apply, but map caught exceptions to Left(ex) and success to Right(x) */
+    def either(): Either[Throwable, T]                    = catcher either body
+    def either[U >: T](other: => U): Either[Throwable, U] = catcher either other
+    
+    /** Create a new Try with the supplied body replacing the current body */
+    def tryInstead[U >: T](other: => U) = new Try(other, catcher)
+    
+    /** Create a new Try with the supplied logic appended to the existing Catch logic. */
+    def or[U >: T](pf: Catcher[U]) = new Try(body, catcher or pf)
+
+    /** Create a new Try with the supplied code appended to the existing Finally. */
+    def andFinally(fin: => Unit) = new Try(body, catcher andFinally fin)
+    
+    override def toString() = List("Try(<body>)", catcher.toString) mkString " "
+  }
+  
+  final val nothingCatcher: PartialFunction[Throwable, Nothing] =
+    new PartialFunction[Throwable, Nothing] {
+      def isDefinedAt(x: Throwable) = false
+      def apply(x: Throwable) = throw x
+    }
+
+  /** A Catch object which catches everything. */
+  final def allCatch[T]: Catch[T] = new Catch[T]({ case x => throw x }) withDesc "<everything>"
+  
+  /** The empty Catch object. */
+  final val noCatch: Catch[Nothing] = new Catch(nothingCatcher) withDesc "<nothing>"
+  
+  /** Creates a Catch object which will catch any of the supplied exceptions.
+    * Since the returned Catch object has no specific logic defined and will simply
+    * rethrow the exceptions it catches, you will typically want to call "opt" or
+    * "either" on the return value, or assign custom logic by calling "withApply".
+    */
+  def catching[T](exceptions: Class[_]*): Catch[T] =
+    new Catch(pfFromExceptions(exceptions : _*)) withDesc exceptions.map(_.getName).mkString(", ")
+  def catching[T](c: Catcher[T]): Catch[T] = new Catch(c)
+  
+  /** Creates a Catch object which catches and ignores any of the supplied exceptions. */
+  def ignoring(exceptions: Class[_]*): Catch[Unit] =
+    catching(exceptions: _*) withApply (_ => ())
+  
+  /** Creates a Catch object which maps all the supplied exceptions to 'None'. */
+  def failing[T](exceptions: Class[_]*): Catch[Option[T]] =
+    catching(exceptions: _*) withApply (_ => None)
+  
+  /** Returns a partially constructed Catch object, which you must give
+    * an exception handler function as an argument to "by".  Example:
+    * handling(ex1, ex2) by (_.printStackTrace)
+    */
+  class By[T,R](f: T => R) {
+    def by(x: T): R = f(x)
+  }
+  def handling[T](exceptions: Class[_]*) = {
+    def fun(f: Throwable => T) = catching(exceptions: _*) withApply f    
+    new By[Throwable => T, Catch[T]](fun _)
+  }
+  
+  /** Returns a Catch object with no catch logic and the argument as Finally. */
+  def ultimately[T](body: => Unit): Catch[T] = noCatch andFinally body
+  
+  /** Experimental */
+  def saving[A](oldVal: A, newVal: A, setter: (A) => Unit): Catch[Nothing] = {
+    new Catch(nothingCatcher, Some(new Finally(setter(oldVal)))) {
+      override def apply[U](body: => U): U = {
+        setter(newVal)
+        super.apply(body)
+      }
+    }
+  }
+
+  /** Creates a Catch object which unwraps any of the supplied exceptions. */
+  def unwrapping[T](exceptions: Class[_]*): Catch[T] = {
+    def unwrap(x: Throwable): Throwable =
+      if (wouldMatch(x, exceptions) && x.getCause != null) unwrap(x.getCause)
+      else x
+    
+    catching(exceptions: _*) withApply (x => throw unwrap(x))
+  }
+  
+  /** Private **/
+  private def wouldMatch(x: Throwable, classes: collection.Seq[Class[_]]): Boolean = 
+    classes exists (_ isAssignableFrom x.getClass)
+  
+  private def pfFromExceptions(exceptions: Class[_]*) = 
+    new PartialFunction[Throwable, Nothing] {
+      def apply(x: Throwable) = throw x
+      def isDefinedAt(x: Throwable) = wouldMatch(x, exceptions)
+    }  
+}
diff --git a/src/library/scala/util/control/NoStackTrace.scala b/src/library/scala/util/control/NoStackTrace.scala
new file mode 100644
index 0000000..6693891
--- /dev/null
+++ b/src/library/scala/util/control/NoStackTrace.scala
@@ -0,0 +1,20 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+package scala.util.control
+
+/** A trait for exceptions which, for efficiency reasons, do not
+ *  fill in the stack trace.
+ *
+ *  @author   Paul Phillips
+ *  @since    2.8
+ */
+trait NoStackTrace extends Throwable
+{
+  override def fillInStackTrace(): Throwable = this
+}
diff --git a/src/library/scala/util/control/TailCalls.scala b/src/library/scala/util/control/TailCalls.scala
new file mode 100644
index 0000000..d4a194b
--- /dev/null
+++ b/src/library/scala/util/control/TailCalls.scala
@@ -0,0 +1,56 @@
+package scala.util.control
+
+/** Methods exported by this object implement tail calls via trampolining.
+ *  Tail calling methods have to return their result using `done` or call the next
+ *  method using `tailcall`. Both return a `TailRec` object. The result of evaluating
+ *  a tailcalling function can be retrieved from a `Tailrec` value using method result`.
+ *  Here's a usage example:
+ *  {{{
+ *  import scala.util.control.TailCalls._
+ *
+ *  def isEven(xs: List[Int]): TailRec[Boolean] =
+ *    if (xs.isEmpty) done(true) else tailcall(isOdd(xs.tail))
+ *
+ *  def isOdd(xs: List[Int]): TailRec[Boolean] =
+ *   if (xs.isEmpty) done(false) else tailcall(isEven(xs.tail)) 
+ *
+ *  isEven((1 to 100000).toList).result
+ *  }}}
+ */
+object TailCalls {
+
+  /** This class represents a tailcalling computation.
+   */
+  abstract class TailRec[+A] {
+    /** Returns the result of the tailcalling computation
+     */
+    def result: A = {
+      def loop(body: TailRec[A]): A = body match {
+        case Call(rest) => loop(rest())
+        case Done(result) => result
+      }
+      loop(this)
+    }
+  }
+
+  /** Internal class representing a tailcall */
+  protected case class Call[A](rest: () => TailRec[A]) extends TailRec[A]
+
+  /** Internal class representing the final result return from a tailcalling computation */
+  protected case class Done[A](override val result: A) extends TailRec[A]
+
+  /** Performs a tailcall
+   *  @param rest  the expression to be evaluated in the tailcall
+   *  @return a `TailRec` object representing the expression `rest`
+   */
+  def tailcall[A](rest: => TailRec[A]): TailRec[A] = new Call(() => rest)
+
+  /** Used to return final result from tailcalling computation
+   *  @param  `result` the result value
+   *  @return a `TailRec` object representing a computation which immediately returns `result`
+   */
+  def done[A](result: A): TailRec[A] = new Done(result)
+  
+}
+
+
diff --git a/src/library/scala/util/grammar/HedgeRHS.scala b/src/library/scala/util/grammar/HedgeRHS.scala
index 9c59d75..6d72bbb 100644
--- a/src/library/scala/util/grammar/HedgeRHS.scala
+++ b/src/library/scala/util/grammar/HedgeRHS.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: HedgeRHS.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala.util.grammar
diff --git a/src/library/scala/util/grammar/TreeRHS.scala b/src/library/scala/util/grammar/TreeRHS.scala
index 8cc8c70..36f3884 100644
--- a/src/library/scala/util/grammar/TreeRHS.scala
+++ b/src/library/scala/util/grammar/TreeRHS.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: TreeRHS.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala.util.grammar
diff --git a/src/library/scala/util/logging/ConsoleLogger.scala b/src/library/scala/util/logging/ConsoleLogger.scala
index 7e428b2..61950a3 100644
--- a/src/library/scala/util/logging/ConsoleLogger.scala
+++ b/src/library/scala/util/logging/ConsoleLogger.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: ConsoleLogger.scala 16980 2009-01-27 11:05:48Z washburn $
 
 
 package scala.util.logging
@@ -21,8 +20,6 @@ package scala.util.logging
 trait ConsoleLogger extends Logged {
 
   /** logs argument to Console using <code>Console.println</code>
-   *
-   *  @param msg ...
    */
   override def log(msg: String): Unit = Console.println(msg)
 }
diff --git a/src/library/scala/util/logging/Logged.scala b/src/library/scala/util/logging/Logged.scala
index 66641ee..ecf25e2 100644
--- a/src/library/scala/util/logging/Logged.scala
+++ b/src/library/scala/util/logging/Logged.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Logged.scala 16980 2009-01-27 11:05:48Z washburn $
 
 
 package scala.util.logging
diff --git a/src/library/scala/util/matching/Regex.scala b/src/library/scala/util/matching/Regex.scala
index 236a898..0eb514f 100644
--- a/src/library/scala/util/matching/Regex.scala
+++ b/src/library/scala/util/matching/Regex.scala
@@ -1,17 +1,18 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2007-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Regex.scala 16881 2009-01-09 16:28:11Z cunei $
 
 
 package scala.util.matching
 
 import java.util.regex.{Pattern, Matcher}
+import collection.immutable.List
+import collection.{Iterator, Seq}
 
 /** This class provides methods for creating and using regular expressions.
  *  It is based on the regular expressions of the JDK since 1.4.
@@ -30,6 +31,8 @@ import java.util.regex.{Pattern, Matcher}
  *  @param regex      A string representing a regular expression
  *  @param groupNames A mapping from names to indices in capture groups
  */
+ at serializable
+ at SerialVersionUID(-2094783597747625537L)
 class Regex(regex: String, groupNames: String*) {
 
   import Regex._
@@ -57,7 +60,7 @@ class Regex(regex: String, groupNames: String*) {
   /** Return all matches of this regexp in given character sequence as an iterator 
    */
   def findAllIn(source: java.lang.CharSequence) = new Regex.MatchIterator(source, this, groupNames)
-
+  
   /** Return optionally first matching string of this regexp in given character sequence,
    *  None if it does not exist.
    */
@@ -102,6 +105,32 @@ class Regex(regex: String, groupNames: String*) {
     val m = pattern.matcher(target)
     m.replaceAll(replacement)
   }
+  
+  /**
+   * Replaces all matches using a replacer function.
+   * 
+   * @param target      The string to match.
+   * @param replacer    The function which maps a match to another string.
+   * @return            The target string after replacements.
+   */
+  def replaceAllIn(target: java.lang.CharSequence, replacer: Match => String): String = {
+    val it = new Regex.MatchIterator(target, this, groupNames).replacementData
+    while (it.hasNext) {
+      val matchdata = it.next
+      it.replace(replacer(matchdata))
+    }
+    it.replaced
+  }
+  
+  def replaceSomeIn(target: java.lang.CharSequence, replacer: Match => Option[String]): String = {
+    val it = new Regex.MatchIterator(target, this, groupNames).replacementData
+    while (it.hasNext) {
+      val matchdata = it.next
+      val replaceopt = replacer(matchdata)
+      if (replaceopt != None) it.replace(replaceopt.get)
+    }
+    it.replaced
+  }
 
   /** Replaces the first match by a string.
    *
@@ -114,12 +143,22 @@ class Regex(regex: String, groupNames: String*) {
     m.replaceFirst(replacement)
   }
 
+  /** Splits the provided character sequence around matches of this
+   *  regexp.
+   *
+   *  @param toSplit The character sequence to split
+   *  @return        The array of strings computed by splitting the
+   *                 input around matches of this regexp
+   */
+  def split(toSplit: java.lang.CharSequence): Array[String] =
+    pattern.split(toSplit)
+
   /** The string defining the regular expression */
   override def toString = regex
 }
 
 /** This object defines inner classes that describe
- *  regex matches. The class hirrachy is as follows.
+ *  regex matches. The class hierarchy is as follows.
  *
  *            MatchData     
  *              |      \    
@@ -194,7 +233,7 @@ object Regex {
       if (end(i) >= 0) source.subSequence(end(i), source.length)
       else null
 
-    private lazy val nameToIndex: Map[String, Int] = Map() ++ ("" :: groupNames.toList).zipWithIndex
+    private lazy val nameToIndex: Map[String, Int] = Map[String, Int]() ++ ("" :: groupNames.toList).zipWithIndex
 
     /** Returns the group with given name
      *
@@ -213,7 +252,7 @@ object Regex {
 
   }
  
-  /** A case class for a succesful match.
+  /** A case class for a successful match.
    */
   class Match(val source: java.lang.CharSequence, 
               matcher: Matcher, 
@@ -249,13 +288,18 @@ object Regex {
   object Match {
     def unapply(m: Match): Some[String] = Some(m.matched)
   }
+  
+  /** An extractor object that yields groups in the match. */
+  object Groups {
+    def unapplySeq(m: Match): Option[Seq[String]] = if (m.groupCount > 0) Some(1 to m.groupCount map m.group) else None
+  }
 
   /** A class to step through a sequence of regex matches
    */
   class MatchIterator(val source: java.lang.CharSequence, val regex: Regex, val groupNames: Seq[String]) 
   extends Iterator[String] with MatchData { self =>
 
-    private val matcher = regex.pattern.matcher(source)
+    protected val matcher = regex.pattern.matcher(source)
     private var nextSeen = false
 
     /** Is there another match? */
@@ -293,6 +337,31 @@ object Regex {
       def hasNext = self.hasNext
       def next = { self.next; new Match(source, matcher, groupNames).force }
     }
+    
+    /** Convert to an iterator that yields MatchData elements instead of Strings and has replacement support */
+    private[matching] def replacementData = new Iterator[Match] with Replacement {
+      def matcher = self.matcher
+      def hasNext = self.hasNext
+      def next = { self.next; new Match(source, matcher, groupNames).force }
+    }
+  }
+  
+  /**
+   * A trait able to build a string with replacements assuming it has a matcher.
+   * Meant to be mixed in with iterators.
+   */
+  private[matching] trait Replacement {
+    protected def matcher: Matcher
+    
+    private var sb = new java.lang.StringBuffer
+    
+    def replaced = {
+      val newsb = new java.lang.StringBuffer(sb)
+      matcher.appendTail(newsb)
+      newsb.toString
+    }
+    
+    def replace(rs: String) = matcher.appendReplacement(sb, rs)
   }
 }
 
diff --git a/src/library/scala/util/parsing/CharInputStreamIterator.scala b/src/library/scala/util/parsing/CharInputStreamIterator.scala
deleted file mode 100644
index c5047d8..0000000
--- a/src/library/scala/util/parsing/CharInputStreamIterator.scala
+++ /dev/null
@@ -1,52 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: CharInputStreamIterator.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala.util.parsing
-
-
-import java.io.InputStream
-import java.io.{IOException, EOFException}
-
-/** This class ...
- *
- *  @author  Burak Emir
- *  @version 1.0
- *
- *  @deprecated use classes from <a target="contentFrame" href="input.html">
- *              <code>scala.util.parsing.input</code></a> instead.
- */
- at deprecated
-class CharInputStreamIterator(in: InputStream) extends Iterator[Char] {
-
-  private var ch: Int = _
-  private var chSet = false
-  private var error: IOException = null
-
-  private def lookahead() {
-    try {
-      ch = in.read(); chSet = ch >= 0
-    } catch {
-      case ex: EOFException => ch = -1
-      case ex: IOException => ch = 1; error = ex
-    }
-  }
-
-  def hasNext: Boolean = {
-    if (!chSet) lookahead()
-    chSet
-  }
-
-  def next(): Char = {
-    if (!chSet) lookahead()
-    chSet = false
-    ch.asInstanceOf[Char]
-  }
-}
diff --git a/src/library/scala/util/parsing/Parsers.scala b/src/library/scala/util/parsing/Parsers.scala
deleted file mode 100644
index 5baf536..0000000
--- a/src/library/scala/util/parsing/Parsers.scala
+++ /dev/null
@@ -1,90 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: Parsers.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala.util.parsing
-
-/** Documentation for this class is currently missing. 
- *  However, the Scala By Examples document contains a 
- *  chapter on combinator parsing that comes close.
- *
- *  @author  Burak Emir
- *  @version 1.0
- *
- *  @deprecated use <a target="contentFrame" href="combinator/Parsers.html">
- *              <code>scala.util.parsing.combinator.Parsers</code></a>
- *              instead.
- */
- at deprecated
-abstract class Parsers {
-
-  type inputType
-
-  abstract class Parser[A] {
-
-    type Result = Option[(A, inputType)]
-
-    def apply(in: inputType): Result
-
-    def filter(pred: A => Boolean) = new Parser[A] {
-      def apply(in: inputType): Result = Parser.this.apply(in) match {
-        case None => None
-        case Some((x, in1)) => if (pred(x)) Some((x, in1)) else None
-      }
-    }
-
-    def map[B](f: A => B) = new Parser[B] {
-      def apply(in: inputType): Result = Parser.this.apply(in) match {
-        case None => None
-        case Some((x, in1)) => Some((f(x), in1))
-      }
-    }
-
-    def flatMap[B](f: A => Parser[B]) = new Parser[B] {
-      def apply(in: inputType): Result = Parser.this.apply(in) match {
-        case None => None
-        case Some((x, in1)) => f(x).apply(in1)
-      }
-    }
-
-    def ||| (p: => Parser[A]) = new Parser[A] {
-      def apply(in: inputType): Result = Parser.this.apply(in) match {
-        case None => p(in)
-        case s => s
-      }
-    }
-
-    def &&& [B](p: => Parser[B]): Parser[B] =
-      for (_ <- this; val x <- p) yield x
-  }
-
-  def not[A](p: Parser[A]) = new Parser[Unit] {
-    def apply(in: inputType): Result = p.apply(in) match {
-      case None => Some(((), in))
-      case Some(_) => None
-    }
-  }
-
-  def succeed[A](x: A) = new Parser[A] {
-    def apply(in: inputType): Result = Some((x, in))
-  }
-
-  def rep[A](p: Parser[A]): Parser[List[A]] =
-    rep1(p) ||| succeed(List())
-
-  def rep1[A](p: Parser[A]): Parser[List[A]] =
-    for (x <- p; val xs <- rep(p)) yield x :: xs
-
-  def repWith[A, B](p: Parser[A], sep: Parser[B]): Parser[List[A]] =
-    for (x <- p; val xs <- rep(sep &&& p)) yield x :: xs
-
-  def opt[A](p: Parser[A]): Parser[List[A]] =
-    (for (x <- p) yield List(x)) ||| succeed(List())
-}
diff --git a/src/library/scala/util/parsing/SimpleTokenizer.scala b/src/library/scala/util/parsing/SimpleTokenizer.scala
deleted file mode 100644
index c8005f9..0000000
--- a/src/library/scala/util/parsing/SimpleTokenizer.scala
+++ /dev/null
@@ -1,68 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: SimpleTokenizer.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala.util.parsing
-
-/** This class ...
- *
- *  @author  Burak Emir
- *  @version 1.0
- *
- *  @deprecated use <a target="contentFrame" href="combinator/lexical/StdLexical.html">
- *              <code>scala.util.parsing.combinator.lexical.StdLexical</code></a>
- *              instead.
- */
- at deprecated
-class SimpleTokenizer(in: Iterator[Char], delimiters: String) extends Iterator[String] {
-
-  private def max(x: Int, y: Char): Int = if (x > y) x else y
-
-  val tracing = false
-
-  private def delimArray: Array[Boolean] = {
-    val ds = List.fromString(delimiters)
-    val da = new Array[Boolean]((0 /: ds)(max) + 1)
-    for (ch <- ds) da(ch) = true
-    da
-  }
-
-  private val isdelim = delimArray
-  private def isDelimiter(ch: Int) = ch >= 0 && ch < isdelim.length && isdelim(ch)
-
-  private val EOI = -1
-
-  private def nextChar(): Int = if (in.hasNext) in.next else EOI
-
-  private var ch: Int = nextChar
-
-  private val buf = new StringBuilder()
-
-  def hasNext: Boolean = ch != EOI
-
-  def next(): String = {
-    while (ch <= ' ' && ch != EOI) ch = nextChar()
-    if (ch == EOI) ""
-    else {
-      buf setLength 0
-      if (isDelimiter(ch)) {
-        buf append ch.asInstanceOf[Char]; ch = nextChar()
-      } else {
-        while (ch > ' ' && ch != EOI && !isDelimiter(ch)) {
-          buf append ch.asInstanceOf[Char]
-          ch = nextChar()
-        }
-      }
-      if (tracing) Console.println("<" + buf.toString() + ">")
-      buf.toString()
-    }
-  }
-}
-
diff --git a/src/library/scala/util/parsing/ast/AbstractSyntax.scala b/src/library/scala/util/parsing/ast/AbstractSyntax.scala
index 39f1cb3..45a4a07 100644
--- a/src/library/scala/util/parsing/ast/AbstractSyntax.scala
+++ b/src/library/scala/util/parsing/ast/AbstractSyntax.scala
@@ -1,6 +1,6 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2006-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
diff --git a/src/library/scala/util/parsing/ast/Binders.scala b/src/library/scala/util/parsing/ast/Binders.scala
index 7eced0c..69288e4 100644
--- a/src/library/scala/util/parsing/ast/Binders.scala
+++ b/src/library/scala/util/parsing/ast/Binders.scala
@@ -1,6 +1,6 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2006-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
@@ -92,7 +92,7 @@ trait Binders extends AbstractSyntax with Mappable {
    */
   class Scope[binderType <: NameElement] extends Iterable[binderType]{
     private val substitution: Map[binderType, Element] = 
-      new scala.collection.jcl.LinkedHashMap[binderType, Element] // a LinkedHashMap is ordered by insertion order -- important!
+      new scala.collection.mutable.LinkedHashMap[binderType, Element] // a LinkedHashMap is ordered by insertion order -- important!
     
     /** Returns a unique number identifying this Scope (only used for representation purposes).
      */
@@ -102,20 +102,20 @@ trait Binders extends AbstractSyntax with Mappable {
      * For a typical let-binding, this is just the variable name. For an argument list to a method body,
      * there is one binder per formal argument.
      */
-    def elements = substitution.keys    
+    def iterator = substitution.keysIterator
     
     /** Return the `i'th binder in this scope.*/
-    def apply(i: Int): binderType = elements.toList(i)
+    def apply(i: Int): binderType = this.iterator.toList(i)
     
     /** Returns true if this container has a binder equal (==) to `b'
      */
     def binds(b: binderType): Boolean = substitution.contains(b)
     
     def indexFor(b: binderType): Option[Int] = {
-      val iter = elements.counted
-      for (that <- iter) {
+      val iter = this.iterator.zipWithIndex
+      for ((that, count) <- iter) {
         if (that.name == b.name) // TODO: why do name equals and structural equals differ?
-          return Some(iter.count)
+          return Some(count + 1)
         else
           Console.println(that+"!="+b)
       }
@@ -127,10 +127,8 @@ trait Binders extends AbstractSyntax with Mappable {
      * (e.g. the variable name in a local variable declaration) 
      *
      * @param b a new binder that is distinct from the existing binders in this scope, 
-     *           and shares their conceptual scope
-     * @pre canAddBinder(b)
-     * @post binds(b)
-     * @post getElementFor(b) eq b
+     *           and shares their conceptual scope. canAddBinder(b)` must hold.`
+     * @return `binds(b)` and `getElementFor(b) eq b` will hold.
      */
     def addBinder(b: binderType) { substitution += Pair(b, b) }
 
@@ -140,7 +138,7 @@ trait Binders extends AbstractSyntax with Mappable {
      *       linked to its `UnderBinder' (i.e., while parsing, BoundElements may be added to the Scope
      *       associated to the UnderBinder, but after that, no changes are allowed, except for substitution)?
      *
-     * @returns true if `b' had not been added yet 
+     * @return true if `b' had not been added yet 
      */
     def canAddBinder(b: binderType): Boolean = !binds(b)
 
@@ -150,30 +148,28 @@ trait Binders extends AbstractSyntax with Mappable {
      * a proxy for the element it is bound to by its binder, `substitute' may thus be thought of
      * as replacing all the bound occurrences of the given binder `b' by their new value `value'.
      *
-     * @param b    the binder whose bound occurrences should be given a new value
+     * @param b    the binder whose bound occurrences should be given a new value. `binds(b)` must hold.
      * @param value the new value for the bound occurrences of `b'
-     * @pre binds(b)
-     * @post getElementFor(b) eq value
+     * @return `getElementFor(b) eq value` will hold.
      */
     def substitute(b: binderType, value: Element): Unit = substitution(b) = value
     
     /** Returns the current value for the bound occurrences of `b'.
      *
-     * @param b the contained binder whose current value should be returned
-     * @pre binds(b)
+     * @param b the contained binder whose current value should be returned `binds(b)` must hold.
      */
     def getElementFor(b: binderType): Element = substitution(b)    
 
-    override def toString: String =  elements.toList.mkString("[",", ","]")+"!"+id // TODO show substitution?
+    override def toString: String =  this.iterator.toList.mkString("[",", ","]")+"!"+id // TODO show substitution?
 
     /** Returns a list of strings that represent the binder elements, each tagged with this scope's id.*/
-    def bindersToString: List[String] = (for(val b <- elements) yield b+"!"+id).toList
+    def bindersToString: List[String] = (for(b <- this.iterator) yield b+"!"+id).toList
     
     /** Return a new inheriting scope that won't check whether binding is respected until the scope is left (so as to support forward references) **/
     def allowForwardRef: Scope[binderType] = this // TODO
 
     /** Return a nested scope -- binders entered into it won't be visible in this scope, but if this scope allows forward references, 
-        the binding in the returned scope also does, and thus the check that all variables are bound is deferred until this scope is left  **/
+      * the binding in the returned scope also does, and thus the check that all variables are bound is deferred until this scope is left  **/
     def nested: Scope[binderType] = this // TODO
     
     def onEnter {}
@@ -193,7 +189,7 @@ trait Binders extends AbstractSyntax with Mappable {
    * A `BoundElement' is represented textually by its bound element, followed by its scope's `id'.
    * For example: `x at 1' represents the variable `x' that is bound in the scope with `id' `1'.
    *
-   * @invar scope.binds(el)
+   * @note `scope.binds(el)` holds before and after.
    */
   case class BoundElement[boundElement <: NameElement](el: boundElement, scope: Scope[boundElement]) extends NameElement with Proxy with BindingSensitive { 
     /** Returns the element this `BoundElement' stands for. 
@@ -276,7 +272,7 @@ trait Binders extends AbstractSyntax with Mappable {
   implicit def ScopeIsMappable[bt <: NameElement <% Mappable[bt]](scope: Scope[bt]): Mappable[Scope[bt]] = 
     new Mappable[Scope[bt]] {
       def gmap(f: Mapper): Scope[bt] = { val newScope = new Scope[bt]()
-        for(val b <- scope) newScope.addBinder(f(b))
+        for(b <- scope) newScope.addBinder(f(b))
         newScope
       }
     }  
@@ -300,7 +296,7 @@ trait Binders extends AbstractSyntax with Mappable {
    *
    * The name `sequence' comes from the fact that this method's type is equal to the type of monadic sequence.
    *
-   * @pre !orig.isEmpty implies orig.forall(ub => ub.scope eq orig(0).scope)
+   * @note `!orig.isEmpty` implies `orig.forall(ub => ub.scope eq orig(0).scope)`
    * 
    */
   def sequence[bt <: NameElement, st <% Mappable[st]](orig: List[UnderBinder[bt, st]]): UnderBinder[bt, List[st]] = 
diff --git a/src/library/scala/util/parsing/combinator/ImplicitConversions.scala b/src/library/scala/util/parsing/combinator/ImplicitConversions.scala
index ef7dd6a..c078378 100644
--- a/src/library/scala/util/parsing/combinator/ImplicitConversions.scala
+++ b/src/library/scala/util/parsing/combinator/ImplicitConversions.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2006-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: ImplicitConversions.scala 16894 2009-01-13 13:09:41Z cunei $
 
 package scala.util.parsing.combinator
 
diff --git a/src/library/scala/util/parsing/combinator/JavaTokenParsers.scala b/src/library/scala/util/parsing/combinator/JavaTokenParsers.scala
index f0ae8c4..f4f1412 100644
--- a/src/library/scala/util/parsing/combinator/JavaTokenParsers.scala
+++ b/src/library/scala/util/parsing/combinator/JavaTokenParsers.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2006-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: JavaTokenParsers.scala 17022 2009-02-03 17:38:58Z milessabin $
 
 package scala.util.parsing.combinator
 
diff --git a/src/library/scala/util/parsing/combinator/PackratParsers.scala b/src/library/scala/util/parsing/combinator/PackratParsers.scala
new file mode 100644
index 0000000..d0b5d2f
--- /dev/null
+++ b/src/library/scala/util/parsing/combinator/PackratParsers.scala
@@ -0,0 +1,327 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2006-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+package scala.util.parsing.combinator
+
+import scala.collection.mutable._
+import scala.util.parsing.combinator._
+import scala.util.parsing.input.Position
+import scala.util.parsing.input.Reader
+
+/**
+ *  <p>
+ *    <code>PackratParsers</code> is a component that extends the parser combinators
+ *    provided by <a href="Parsers.html"><code>Parsers</code></a> with a memoization facility
+ *    (``Packrat Parsing'').
+ *  </p>
+ *  <p>
+ *    Packrat Parsing is a technique for implementing backtracking, recursive-descent parsers, with the
+ *    advantage that it guarantees unlimited lookahead and a linear parse time. Using this technique,
+ *    left recursive grammars can also be accepted.
+ *  </p>
+ *  <p>
+ *    Using <code>PackratParsers</code> is very similar to using <code>Parsers</code>:
+ *  <ul>
+ *    <li> any class/trait that extends <code>Parsers</code> (directly or through a subclass) can
+ *         mix in <code>PackratParsers</code>. Example:
+ *         <code>object MyGrammar extends StandardTokenParsers with PackratParsers </code>
+ *    <li> each grammar production previously declared as a <code>def</code> without formal parameters
+ *         becomes a <code>lazy val</code>, and its type is changed from <code>Parser[Elem]</code>
+ *         to <code>PackratParser[Elem]</code>. So, for example, <code>def production: Parser[Int] = {...}</code> 
+ *         becomes <code>lazy val production: PackratParser[Int] = {...}</code>
+ *    <li> Important: using <code>PackratParser</code>s is not an ``all or nothing'' decision. They
+ *         can be free mixed with regular <code>Parser</code>s in a single grammar.
+ *  </ul>
+ *  </p>
+ *  <p>
+ *    Cached parse results are attached to the <i>input</i>, not the grammar.
+ *    Therefore, <code>PackratsParser</code>s require a <code>PackratReader</code> as input, which
+ *    adds memoization to an underlying <code>Reader</code>. Programmers can create <code>PackratReader</code>
+ *    objects either manually, as in <code>production(new PackratReader(new lexical.Scanner("input")))</code>,
+ *    but the common way should be to rely on the combinator <code>phrase</code> to wrap a given
+ *    input with a <code>PackratReader</code> if the input is not one itself.
+ *  </p>
+ *
+ * @see Bryan Ford: "Packrat Parsing: Simple, Powerful, Lazy, Linear Time." ICFP'02
+ * @see Alessandro Warth, James R. Douglass, Todd Millstein: "Packrat Parsers Can Support Left Recursion." PEPM'08
+ *  
+ * @since 2.8
+ * @author Manohar Jonnalagedda, Tiark Rompf
+ */
+
+trait PackratParsers extends Parsers {
+  
+  //type Input = PackratReader[Elem]
+  
+  /**
+   * A specialized <code>Reader</code> class that wraps an underlying <code>Reader</code>
+   * and provides memoization of parse results.
+   */
+  class PackratReader[+T](underlying: Reader[T]) extends Reader[T]  { outer =>
+    
+    /*
+     * caching of intermediate parse results and information about recursion
+     */
+     
+    private[PackratParsers] val cache: HashMap[(Parser[_], Position), MemoEntry[_]] = HashMap.empty
+  
+
+    private[PackratParsers] def getFromCache[T](p: Parser[T]): Option[MemoEntry[T]] = {
+      cache.get((p, pos)).asInstanceOf[Option[MemoEntry[T]]]
+    }
+    
+    private[PackratParsers] def updateCacheAndGet[T](p: Parser[T], w: MemoEntry[T]): MemoEntry[T] = {
+      cache.put((p, pos),w)
+      w
+    }
+
+    /* a cache for storing parser heads: allows to know which parser is involved
+       in a recursion*/
+    private[PackratParsers] val recursionHeads: HashMap[Position, Head] = HashMap.empty
+
+    //a stack that keeps a list of all involved rules
+    private[PackratParsers] var lrStack: List[LR] = Nil
+
+
+
+ 
+    override def source: java.lang.CharSequence = underlying.source
+    override def offset: Int = underlying.offset
+
+    def first: T = underlying.first
+    def rest: Reader[T] = new PackratReader(underlying.rest) {
+      override private[PackratParsers] val cache = outer.cache
+      override private[PackratParsers] val recursionHeads = outer.recursionHeads
+      lrStack = outer.lrStack
+    }
+  
+    def pos: Position = underlying.pos
+    def atEnd: Boolean = underlying.atEnd
+  }
+
+  
+  /**
+   *  <p>
+   *    A parser generator delimiting whole phrases (i.e. programs).
+   *  </p>
+   *  <p>
+   *    Overridden to make sure any input passed to the argument parser
+   *    is wrapped in a <code>PackratReader</code>.
+   *  </p>
+   */
+  override def phrase[T](p: Parser[T]) = {
+    val q = super.phrase(p)
+    new PackratParser[T] {
+      def apply(in: Input) = in match {
+        case in: PackratReader[_] => q(in)
+        case in => q(new PackratReader(in))
+      }
+    }
+  }
+
+
+  private def getPosFromResult(r: ParseResult[_]): Position = r.next.pos
+ 
+  // auxiliary data structures
+ 
+  private case class MemoEntry[+T](var r: Either[LR,ParseResult[_]]){
+    def getResult: ParseResult[T] = r match {
+      case Left(LR(res,_,_)) => res.asInstanceOf[ParseResult[T]]
+      case Right(res) => res.asInstanceOf[ParseResult[T]]
+    }
+  }
+  
+  private case class LR(var seed: ParseResult[_], var rule: Parser[_], var head: Option[Head]){
+    def getPos: Position = getPosFromResult(seed)
+  }
+  
+  private case class Head(var headParser: Parser[_], var involvedSet: List[Parser[_]], var evalSet: List[Parser[_]]){
+    def getHead = headParser
+  }
+  
+  /** 
+   * The root class of packrat parsers. 
+   */
+  abstract class PackratParser[+T] extends super.Parser[T]
+  
+  /**
+   * Implicitly convert a parser to a packrat parser.
+   * The conversion is triggered by giving the appropriate target type: 
+   * val myParser: PackratParser[MyResult] = aParser
+   */
+  implicit def parser2packrat[T](p: => super.Parser[T]): PackratParser[T] = {
+    lazy val q = p
+    memo(super.Parser {in => q(in)})
+  }
+
+
+  /*
+   * An unspecified function that is called when a packrat reader is applied.
+   * It verifies whether we are in the process of growing a parse or not. 
+   * In the former case, it makes sure that rules involved in the recursion are evaluated. 
+   * It also prevents non-involved rules from getting evaluated further
+   */
+  
+  private def recall(p: super.Parser[_], in: PackratReader[Elem]): Option[MemoEntry[_]] = {
+    val cached = in.getFromCache(p)
+    val head = in.recursionHeads.get(in.pos)
+    
+    head match {
+      case None => /*no heads*/ cached
+      case Some(h at Head(hp, involved, evalSet)) => {
+        //heads found
+        if(cached == None && !(hp::involved contains p)) {
+          //Nothing in the cache, and p is not involved
+          return Some(MemoEntry(Right(Failure("dummy ",in))))
+        }
+        if(evalSet contains p){
+          //something in cache, and p is in the evalSet
+          //remove the rule from the evalSet of the Head
+          h.evalSet = h.evalSet.filterNot(_==p)
+          val tempRes = p(in)
+          //we know that cached has an entry here
+          val tempEntry: MemoEntry[_] = cached.get // match {case Some(x: MemoEntry[_]) => x}
+          //cache is modified
+          tempEntry.r = Right(tempRes)
+        }
+        cached
+      }
+    }
+  }
+  
+  /*
+   * setting up the left-recursion. We have the LR for the rule head
+   * we modify the involvedSets of all LRs in the stack, till we see
+   * the current parser again
+   */
+  private def setupLR(p: Parser[_], in: PackratReader[_], recDetect: LR): Unit = {
+    if(recDetect.head == None) recDetect.head = Some(Head(p, Nil, Nil))
+    
+    in.lrStack.takeWhile(_.rule != p).foreach {x =>
+      x.head = recDetect.head
+      recDetect.head.map(h => h.involvedSet = x.rule::h.involvedSet)
+    }
+  }
+  
+  /*
+   * growing, if needed the recursion
+   * check whether the parser we are growing is the head of the rule.
+   * Not => no grow
+   */
+   
+  /*
+   * Once the result of the recall function is known, if it is nil, then we need to store a dummy
+failure into the cache (much like in the previous listings) and compute the future parse. If it
+is not, however, this means we have detected a recursion, and we use the setupLR function
+to update each parser involved in the recursion.
+   */
+  
+  private def lrAnswer[T](p: Parser[T], in: PackratReader[Elem], growable: LR): ParseResult[T] = growable match {
+    //growable will always be having a head, we can't enter lrAnswer otherwise
+    case LR(seed ,rule, Some(head)) => 
+      if(head.getHead != p) /*not head rule, so not growing*/ seed.asInstanceOf[ParseResult[T]]
+      else {
+        in.updateCacheAndGet(p, MemoEntry(Right[LR, ParseResult[T]](seed.asInstanceOf[ParseResult[T]])))
+        seed match {
+          case f at Failure(_,_) => f
+          case e at Error(_,_) => e
+          case s at Success(_,_) => /*growing*/ grow(p, in, head)
+        }
+      }
+    case _=> throw new Exception("lrAnswer with no head !!")
+  }
+
+  //p here should be strict (cannot be non-strict) !!
+  //failing left-recursive grammars: This is done by simply storing a failure if nothing is found
+
+  /** 
+   * Explicitly convert a given parser to a memoizing packrat parser.
+   * In most cases, client code should avoid calling <code>memo</code> directly
+   * and rely on implicit conversion instead.
+   */
+  def memo[T](p: super.Parser[T]): PackratParser[T] = {
+    new PackratParser[T] {
+      def apply(in: Input) = {
+        /*
+         * transformed reader
+         */
+        val inMem = in.asInstanceOf[PackratReader[Elem]]
+        
+        //look in the global cache if in a recursion
+        val m = recall(p, inMem)
+        m match {
+          //nothing has been done due to recall
+          case None =>
+            val base = LR(Failure("Base Failure",in), p, None)
+            inMem.lrStack = base::inMem.lrStack
+            //cache base result
+            inMem.updateCacheAndGet(p,MemoEntry(Left(base)))
+            //parse the input
+            val tempRes = p(in)
+            //the base variable has passed equality tests with the cache
+            inMem.lrStack = inMem.lrStack.tail
+            //check whether base has changed, if yes, we will have a head
+            base.head match {
+              case None => 
+                /*simple result*/
+                inMem.updateCacheAndGet(p,MemoEntry(Right(tempRes)))
+                tempRes
+              case s at Some(_) =>
+                /*non simple result*/
+                base.seed = tempRes
+                //the base variable has passed equality tests with the cache
+                val res = lrAnswer(p, inMem, base)
+                res
+            }
+            
+          case Some(mEntry) => {
+            //entry found in cache
+            mEntry match {
+              case MemoEntry(Left(recDetect)) => {
+                setupLR(p, inMem, recDetect)
+                //all setupLR does is change the heads of the recursions, so the seed will stay the same
+                recDetect match {case LR(seed, _, _) => seed.asInstanceOf[ParseResult[T]]}
+              }
+              case MemoEntry(Right(res: ParseResult[_])) => res.asInstanceOf[ParseResult[T]]
+            }
+          }
+        }
+      }
+    }
+  } 
+  
+  private def grow[T](p: super.Parser[T], rest: PackratReader[Elem], head: Head): ParseResult[T] = {
+    //store the head into the recursionHeads
+    rest.recursionHeads.put(rest.pos, head /*match {case Head(hp,involved,_) => Head(hp,involved,involved)}*/)
+    val oldRes: ParseResult[T] = rest.getFromCache(p).get match {
+      case MemoEntry(Right(x)) => x.asInstanceOf[ParseResult[T]]
+      case _ => throw new Exception("impossible match")
+    }
+
+    //resetting the evalSet of the head of the recursion at each beginning of growth
+    head.evalSet = head.involvedSet
+    val tempRes = p(rest); tempRes match {
+      case s at Success(_,_) => 
+        if(getPosFromResult(oldRes) < getPosFromResult(tempRes)) {
+          rest.updateCacheAndGet(p, MemoEntry(Right(s)))
+          grow(p, rest, head)
+        } else {
+          //we're done with growing, we can remove data from recursion head
+          rest.recursionHeads -= rest.pos
+          rest.getFromCache(p).get match {
+            case MemoEntry(Right(x: ParseResult[_])) => x.asInstanceOf[ParseResult[T]]
+            case _ => throw new Exception("impossible match")
+          }
+        }
+      case f => 
+        rest.recursionHeads -= rest.pos
+        /*rest.updateCacheAndGet(p, MemoEntry(Right(f)));*/oldRes
+    }
+  }
+}
diff --git a/src/library/scala/util/parsing/combinator/Parsers.scala b/src/library/scala/util/parsing/combinator/Parsers.scala
index bd94f80..3544e83 100644
--- a/src/library/scala/util/parsing/combinator/Parsers.scala
+++ b/src/library/scala/util/parsing/combinator/Parsers.scala
@@ -1,20 +1,19 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2006-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Parsers.scala 16894 2009-01-13 13:09:41Z cunei $
 
 package scala.util.parsing.combinator
 
 import scala.util.parsing.input._
-import scala.collection.mutable.{Map=>MutableMap}
+import scala.collection.mutable.ListBuffer
+import scala.annotation.tailrec
 
 // TODO: better error handling (labelling like parsec's <?>)
-// TODO: memoisation (like packrat parsers?) 
 
 /** <p>
  *    <code>Parsers</code> is a component that <i>provides</i> generic
@@ -48,35 +47,21 @@ import scala.collection.mutable.{Map=>MutableMap}
  *    of the input.
  *  </p>
  *
- * @requires Elem the type of elements the provided parsers consume 
- *              (When consuming invidual characters, a parser is typically called a ``scanner'', 
- *               which produces ``tokens'' that are consumed by what is normally called a ``parser''.
- *               Nonetheless, the same principles apply, regardless of the input type.)</p>
- *<p>
- * @provides Input = Reader[Elem] 
- *              The type of input the parsers in this component expect.</p>
- *<p>
- * @provides Parser[+T] extends (Input => ParseResult[T]) 
- *              Essentially, a `Parser[T]' is a function from `Input' to `ParseResult[T]'.</p>
- *<p>
- * @provides ParseResult[+T] is like an `Option[T]', in the sense that it is either
- *              `Success[T]', which consists of some result (:T) (and the rest of the input) or
- *              `Failure[T]', which provides an error message (and the rest of the input).</p>
- *
  * @author Martin Odersky, Iulian Dragos, Adriaan Moors 
  */
 trait Parsers {
-  /** the type of input elements */
+  /** the type of input elements the provided parsers consume (When consuming invidual characters, a parser is typically
+   * called a ``scanner'', which produces ``tokens'' that are consumed by what is normally called a ``parser''.
+   * Nonetheless, the same principles apply, regardless of the input type.) */
   type Elem
 
-  /** The parser input is an abstract reader of input elements */
+  /** The parser input is an abstract reader of input elements, i.e. the type of input the parsers in this component
+   * expect. */
   type Input = Reader[Elem]
 
-  /** A base class for parser results. 
-   *  A result is either successful or not (failure may be fatal, i.e.,
-   *  an Error, or not, i.e., a Failure)
-   *  On success, provides a result of type <code>T</code>. 
-   */
+  /** A base class for parser results. A result is either successful or not (failure may be fatal, i.e., an Error, or
+   * not, i.e., a Failure). On success, provides a result of type `T` which consists of some result (and the rest of
+   * the input). */
   sealed abstract class ParseResult[+T] {
     /** Functional composition of ParseResults
      * 
@@ -154,6 +139,15 @@ trait Parsers {
 
     def get: Nothing = error("No result when parsing failed")
   }
+  /** An extractor so NoSuccess(msg, next) can be used in matches.
+   */
+  object NoSuccess {
+    def unapply[T](x: ParseResult[T]) = x match {
+      case Failure(msg, next)   => Some(msg, next)
+      case Error(msg, next)     => Some(msg, next)
+      case _                    => None
+    }
+  }
   
   /** The failure case of ParseResult: contains an error-message and the remaining input.
    * Parsing will back-track when a failure occurs.
@@ -293,7 +287,7 @@ trait Parsers {
      *          characters accepts.</p>
      * 
      * @param q a parser that accepts if p consumes less characters.
-     * @return a `Parser' that returns the result of the parser consuming the most characteres (out of `p' and `q').
+     * @return a `Parser' that returns the result of the parser consuming the most characters (out of `p' and `q').
      */
     def ||| [U >: T](q: => Parser[U]): Parser[U] = new Parser[U] {
       def apply(in: Input) = {
@@ -305,8 +299,7 @@ trait Parsers {
           case (s1 @ Success(_, _), _) => s1
           case (_, s2 @ Success(_, _)) => s2
           case (e1 @ Error(_, _), _) => e1
-          case (f1 @ Failure(_, next1), f2 @ Failure(_, next2)) => if (next2.pos < next1.pos) f1 else f2
-          case (f1 @ Failure(_, next1), e2 @ Error(_, next2)) => if (next2.pos < next1.pos) f1 else e2
+          case (f1 @ Failure(_, next1), ns2 @ NoSuccess(_, next2)) => if (next2.pos < next1.pos) f1 else ns2
         }
       }
       override def toString = "|||"
@@ -354,7 +347,7 @@ trait Parsers {
     def ^? [U](f: PartialFunction[T, U]): Parser[U] = ^?(f, r => "Constructor function not defined at "+r)
     
        
-    /** A parser combinator that parameterises a subsequent parser with the result of this one
+    /** A parser combinator that parameterizes a subsequent parser with the result of this one
      *
      *<p>
      * Use this combinator when a parser depends on the result of a previous parser. `p' should be
@@ -530,8 +523,7 @@ trait Parsers {
     val r = p(in)
     println(name +" --> "+ r)
     r
-  } 
-
+  }
   
   /** A parser generator for repetitions.
    *  
@@ -582,36 +574,24 @@ trait Parsers {
    * @return A parser that returns a list of results produced by first applying `f' and then 
    *         repeatedly `p' to the input (it only succeeds if `f' matches).
    */
-  def rep1[T](first: => Parser[T], p: => Parser[T]): Parser[List[T]] = Parser{ in0 =>
-    val xs = new scala.collection.mutable.ListBuffer[T]
-    var in = in0
-
-    var res = first(in)
-
-    while(res.successful) {
-      xs += res.get
-      in = res.next
-      res = p(in)
+  def rep1[T](first: => Parser[T], p: => Parser[T]): Parser[List[T]] = Parser { in =>
+    val elems = new ListBuffer[T]
+
+    def continue(in: Input): ParseResult[List[T]] = {
+      val p0 = p    // avoid repeatedly re-evaluating by-name parser
+      @tailrec def applyp(in0: Input): ParseResult[List[T]] = p0(in0) match {
+        case Success(x, rest) => elems += x ; applyp(rest)
+        case _                => Success(elems.toList, in0)
+      }
+      
+      applyp(in)
     }
 
-    // assert(res.isInstanceOf[NoSuccess])
-
-    res match {
-      case e: Error => e
-      case _  => 
-        if (!xs.isEmpty) {
-          // the next parser should start parsing where p failed, 
-          // since `!p(in).successful', the next input to be consumed is `in'
-          Success(xs.toList, in)  // TODO: I don't think in == res.next holds
-        }
-        else {
-          Failure(res.asInstanceOf[NoSuccess].msg, in0)
-        }
+    first(in) match {
+      case Success(x, rest) => elems += x ; continue(rest)
+      case ns: NoSuccess    => ns
     }
   }
-  
-  //= first ~ rep(p) ^^ { case ~(x, xs) => x :: xs }
-  
 
   /** A parser generator for a specified number of repetitions.
    *  
@@ -623,16 +603,26 @@ trait Parsers {
    * @return A parser that returns a list of results produced by repeatedly applying `p' to the input
    *        (and that only succeeds if `p' matches exactly `n' times).
    */  
-  def repN[T](n: Int, p: => Parser[T]): Parser[List[T]] = 
-    if(n==0) success(Nil) else p ~ repN(n-1, p) ^^ { case ~(x, xs) => x :: xs }
+  def repN[T](num: Int, p: => Parser[T]): Parser[List[T]] = 
+    if (num == 0) success(Nil) else Parser { in =>
+      val elems = new ListBuffer[T]
+      val p0 = p    // avoid repeatedly re-evaluating by-name parser
+      
+      @tailrec def applyp(in0: Input): ParseResult[List[T]] =
+        if (elems.length == num) Success(elems.toList, in0)
+        else p0(in0) match {
+          case Success(x, rest)   => elems += x ; applyp(rest)
+          case ns: NoSuccess      => return ns
+        }
+      
+      applyp(in)
+    }
   
   /** A parser generator for non-empty repetitions.
    *  
-   *  <p>rep1sep(first, p, q) starts by using `first', followed by repeatedly uses of `p' interleaved with `q' 
-   *                to parse the input, until `p' fails. `first' must succeed (the result is a `List' of the 
-   *                consecutive results of `first' and `p')</p>
+   *  <p>rep1sep(p, q) repeatedly applies `p' interleaved with `q' to parse the input, until `p' fails.
+   *                The parser `p' must succeed at least once.</p>
    *
-   * @param first a `Parser' that is to be applied to the first element of input
    * @param p a `Parser' that is to be applied successively to the input
    * @param q a `Parser' that parses the elements that separate the elements parsed by `p' 
    *          (interleaved with `q')   
@@ -640,9 +630,10 @@ trait Parsers {
    *         (and that only succeeds if `p' matches at least once).
    *         The results of `p' are collected in a list. The results of `q' are discarded.    
    */
-  def rep1sep[T](p: => Parser[T], q: => Parser[Any]): Parser[List[T]] = 
-    p ~ (q ~ rep1sep(p, q) ^^ { case x ~ y => y } | success(List())) ^^ { case x ~ y => x :: y }
+  def rep1sep[T](p : => Parser[T], q : => Parser[Any]): Parser[List[T]] = 
+    p ~ rep(q ~> p) ^^ {case x~y => x::y} 
    
+
   /** A parser generator that, roughly, generalises the rep1sep generator so that `q', which parses the separator,
    * produces a left-associative function that combines the elements it separates.
    *
@@ -670,7 +661,7 @@ trait Parsers {
         
   /** A parser generator that generalises the rep1sep generator so that `q', which parses the separator,
    * produces a right-associative function that combines the elements it separates. Additionally,
-   * The right-most (last) element and the left-most combinating function have to be supplied.
+   * The right-most (last) element and the left-most combining function have to be supplied.
    * 
    * rep1sep(p: Parser[T], q) corresponds to chainr1(p, q ^^ cons, cons, Nil) (where val cons = (x: T, y: List[T]) => x :: y)
    *
@@ -701,12 +692,24 @@ trait Parsers {
    */
   def not[T](p: => Parser[T]): Parser[Unit] = Parser { in =>
     p(in) match {
-      case s @ Success(_, _) => Failure("Expected failure", in)
-      case e @ Error(_, _) => Success((), in)
-      case f @ Failure(msg, next) => Success((), in)
+      case Success(_, _)  => Failure("Expected failure", in)
+      case _              => Success((), in)
     }
   }  
-  
+
+  /** A parser generator for guard expressions. The resulting parser will fail or succeed 
+   * just like the one given as parameter but it will not consume any input.
+   *
+   * @param p a `Parser' that is to be applied to the input
+   * @return A parser that returns success if and only if 'p' succeeds but never consumes any input
+   */
+  def guard[T](p: => Parser[T]): Parser[T] = Parser { in =>
+    p(in) match{
+      case s@ Success(s1,_) => Success(s1, in)
+      case e => e
+    }
+  }
+
   
   /** `positioned' decorates a parser's result with the start position of the input it consumed. 
    * 
diff --git a/src/library/scala/util/parsing/combinator/RegexParsers.scala b/src/library/scala/util/parsing/combinator/RegexParsers.scala
index 73e0755..0a9c6c8 100644
--- a/src/library/scala/util/parsing/combinator/RegexParsers.scala
+++ b/src/library/scala/util/parsing/combinator/RegexParsers.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2006-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: RegexParsers.scala 16894 2009-01-13 13:09:41Z cunei $
 
 package scala.util.parsing.combinator
 
@@ -66,6 +65,25 @@ trait RegexParsers extends Parsers {
       }
     }
   }
+  
+  /** `positioned' decorates a parser's result with the start position of the input it consumed. 
+   * If whitespace is being skipped, then it is skipped before the start position is recorded.
+   * 
+   * @param p a `Parser' whose result conforms to `Positional'.
+   * @return A parser that has the same behaviour as `p', but which marks its result with the 
+   *         start position of the input it consumed after whitespace has been skipped, if it
+   *         didn't already have a position.
+   */
+  override def positioned[T <: Positional](p: => Parser[T]): Parser[T] = {
+    val pp = super.positioned(p)
+    new Parser[T] {
+      def apply(in: Input) = {
+        val offset = in.offset
+        val start = handleWhiteSpace(in.source, offset)
+        pp(in.drop (start - offset))
+      }
+    }
+  }
 
   override def phrase[T](p: Parser[T]): Parser[T] =
     super.phrase(p <~ opt("""\z""".r))
diff --git a/src/library/scala/util/parsing/combinator/lexical/Lexical.scala b/src/library/scala/util/parsing/combinator/lexical/Lexical.scala
index c57d8f1..cbc83b0 100644
--- a/src/library/scala/util/parsing/combinator/lexical/Lexical.scala
+++ b/src/library/scala/util/parsing/combinator/lexical/Lexical.scala
@@ -1,18 +1,19 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2006-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Lexical.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.util.parsing.combinator.lexical
+package scala.util.parsing
+package combinator
+package lexical
 
-import scala.util.parsing.syntax._
-import scala.util.parsing.input.CharArrayReader.EofCh
+import token._
+import input.CharArrayReader.EofCh
 
 /** <p>
  *    This component complements the <code>Scanners</code> component with
diff --git a/src/library/scala/util/parsing/combinator/lexical/Scanners.scala b/src/library/scala/util/parsing/combinator/lexical/Scanners.scala
index e588c36..71ba047 100644
--- a/src/library/scala/util/parsing/combinator/lexical/Scanners.scala
+++ b/src/library/scala/util/parsing/combinator/lexical/Scanners.scala
@@ -1,18 +1,19 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2006-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Scanners.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.util.parsing.combinator.lexical
+package scala.util.parsing
+package combinator
+package lexical
 
-import scala.util.parsing.syntax._
-import scala.util.parsing.input._
+import token._
+import input._
 
 /** <p>
  *    This component provides core functionality for lexical parsers.
@@ -22,13 +23,6 @@ import scala.util.parsing.input._
  *    {@see StdLexical}, for more functionality.
  *  </p>
  *
- *  @requires token      a parser that produces a token (from a stream of characters)
- *  @requires whitespace a unit-parser for white-space
- *  @provides Scanner    essentially a parser that parses a stream of characters
- *                       to produce `Token's, which are typically passed to a
- *                       syntactical parser (which operates on `Token's, not on
- *                       individual characters).
- *
  *  @author Martin Odersky, Adriaan Moors 
  */
 trait Scanners extends Parsers {
diff --git a/src/library/scala/util/parsing/combinator/lexical/StdLexical.scala b/src/library/scala/util/parsing/combinator/lexical/StdLexical.scala
index c0c74ba..6cdd07e 100644
--- a/src/library/scala/util/parsing/combinator/lexical/StdLexical.scala
+++ b/src/library/scala/util/parsing/combinator/lexical/StdLexical.scala
@@ -1,18 +1,19 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2006-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: StdLexical.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.util.parsing.combinator.lexical
+package scala.util.parsing
+package combinator
+package lexical
 
-import scala.util.parsing.syntax._
-import scala.util.parsing.input.CharArrayReader.EofCh
+import token._
+import input.CharArrayReader.EofCh
 import collection.mutable.HashSet
 
 /** <p>
@@ -35,7 +36,7 @@ import collection.mutable.HashSet
 class StdLexical extends Lexical with StdTokens {
   // see `token' in `Scanners'
   def token: Parser[Token] = 
-    ( letter ~ rep( letter | digit )                    ^^ { case first ~ rest => processIdent(first :: rest mkString "") }
+    ( identChar ~ rep( identChar | digit )              ^^ { case first ~ rest => processIdent(first :: rest mkString "") }
     | digit ~ rep( digit )                              ^^ { case first ~ rest => NumericLit(first :: rest mkString "") }
     | '\'' ~ rep( chrExcept('\'', '\n', EofCh) ) ~ '\'' ^^ { case '\'' ~ chars ~ '\'' => StringLit(chars mkString "") }
     | '\"' ~ rep( chrExcept('\"', '\n', EofCh) ) ~ '\"' ^^ { case '\"' ~ chars ~ '\"' => StringLit(chars mkString "") }
@@ -45,6 +46,9 @@ class StdLexical extends Lexical with StdTokens {
     | delim                                             
     | failure("illegal character")
     )
+  
+  // legal identifier chars other than digits
+  def identChar = letter | elem('_')
 
   // see `whitespace in `Scanners'
   def whitespace: Parser[Any] = rep(
@@ -68,23 +72,19 @@ class StdLexical extends Lexical with StdTokens {
   protected def processIdent(name: String) = 
     if (reserved contains name) Keyword(name) else Identifier(name)
 
-  private var _delim: Parser[Token] = null
-  protected def delim: Parser[Token] = {
-    if (_delim eq null) { // construct parser for delimiters by |'ing together the parsers for the individual delimiters, 
-    // starting with the longest one (hence the sort + reverse) -- otherwise a delimiter D will never be matched if 
-    // there is another delimiter that is a prefix of D   
-      def parseDelim(s: String): Parser[Token] = accept(s.toList) ^^ { x => Keyword(s) }
-      
-      val d = new Array[String](delimiters.size)
-      delimiters.copyToArray(d,0)
-      scala.util.Sorting.quickSort(d) 
-      _delim = d.toList.reverse.map(parseDelim).reduceRight[Parser[Token]](_ | _) // no offence :-)      
-    }
+  private lazy val _delim: Parser[Token] = {
+    // construct parser for delimiters by |'ing together the parsers for the individual delimiters, 
+    // starting with the longest one -- otherwise a delimiter D will never be matched if there is
+    // another delimiter that is a prefix of D   
+    def parseDelim(s: String): Parser[Token] = accept(s.toList) ^^ { x => Keyword(s) }
     
-    _delim
+    val d = new Array[String](delimiters.size)
+    delimiters.copyToArray(d, 0)
+    scala.util.Sorting.quickSort(d)
+    (d.toList map parseDelim).foldRight(failure("no matching delimiter"): Parser[Token])((x, y) => y | x)
   }
+  protected def delim: Parser[Token] = _delim
 
   private def lift[T](f: String => T)(xs: List[Char]): T = f(xs.mkString("", "", ""))
-
   private def lift2[T](f: String => T)(p: ~[Char, List[Char]]): T = lift(f)(p._1 :: p._2)
 }
diff --git a/src/library/scala/util/parsing/combinator/syntactical/StandardTokenParsers.scala b/src/library/scala/util/parsing/combinator/syntactical/StandardTokenParsers.scala
index 301d89e..f5b024f 100644
--- a/src/library/scala/util/parsing/combinator/syntactical/StandardTokenParsers.scala
+++ b/src/library/scala/util/parsing/combinator/syntactical/StandardTokenParsers.scala
@@ -1,18 +1,18 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2006-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: StandardTokenParsers.scala 16894 2009-01-13 13:09:41Z cunei $
 
+package scala.util.parsing
+package combinator
+package syntactical
 
-package scala.util.parsing.combinator.syntactical
-
-import scala.util.parsing.syntax._
-import scala.util.parsing.combinator.lexical.StdLexical 
+import token._
+import lexical.StdLexical 
 
 /** This component provides primitive parsers for the standard tokens defined in `StdTokens'.
 *
@@ -21,4 +21,10 @@ import scala.util.parsing.combinator.lexical.StdLexical
 class StandardTokenParsers extends StdTokenParsers {
   type Tokens = StdTokens
   val lexical = new StdLexical
+
+  //an implicit keyword function that gives a warning when a given word is not in the reserved/delimiters list
+  override implicit def keyword(chars : String): Parser[String] = 
+    if(lexical.reserved.contains(chars) || lexical.delimiters.contains(chars)) super.keyword(chars)
+    else failure("You are trying to parse \""+chars+"\", but it is neither contained in the delimiters list, nor in the reserved keyword list of your lexical object")
+
 }
diff --git a/src/library/scala/util/parsing/combinator/syntactical/StdTokenParsers.scala b/src/library/scala/util/parsing/combinator/syntactical/StdTokenParsers.scala
index 51adfdf..3320089 100644
--- a/src/library/scala/util/parsing/combinator/syntactical/StdTokenParsers.scala
+++ b/src/library/scala/util/parsing/combinator/syntactical/StdTokenParsers.scala
@@ -1,17 +1,19 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2006-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: StdTokenParsers.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.util.parsing.combinator.syntactical
+package scala.util.parsing
+package combinator
+package syntactical
 
-import scala.util.parsing.syntax._
+import token._
+import collection.mutable.HashMap
 
 /** This component provides primitive parsers for the standard tokens defined in `StdTokens'.
 *
@@ -21,13 +23,17 @@ trait StdTokenParsers extends TokenParsers {
   type Tokens <: StdTokens
   import lexical.{Keyword, NumericLit, StringLit, Identifier}
 
+  protected val keywordCache : HashMap[String, Parser[String]] = HashMap.empty
+
   /** A parser which matches a single keyword token.
    *
    * @param chars    The character string making up the matched keyword. 
    * @return a `Parser' that matches the given string
    */
-  implicit def keyword(chars: String): Parser[String] = accept(Keyword(chars)) ^^ (_.chars)
-
+//  implicit def keyword(chars: String): Parser[String] = accept(Keyword(chars)) ^^ (_.chars)
+    implicit def keyword(chars: String): Parser[String] = 
+      keywordCache.getOrElseUpdate(chars, accept(Keyword(chars)) ^^ (_.chars))
+ 
   /** A parser which matches a numeric literal */
   def numericLit: Parser[String] = 
     elem("number", _.isInstanceOf[NumericLit]) ^^ (_.chars)
diff --git a/src/library/scala/util/parsing/combinator/syntactical/TokenParsers.scala b/src/library/scala/util/parsing/combinator/syntactical/TokenParsers.scala
index 28f9557..8a993fb 100644
--- a/src/library/scala/util/parsing/combinator/syntactical/TokenParsers.scala
+++ b/src/library/scala/util/parsing/combinator/syntactical/TokenParsers.scala
@@ -1,29 +1,23 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2006-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: TokenParsers.scala 16894 2009-01-13 13:09:41Z cunei $
 
+package scala.util.parsing
+package combinator
+package syntactical
 
-package scala.util.parsing.combinator.syntactical
-
-/** <p>
- *    This is the core component for token-based parsers. 
- *  </p>
- *  <p>
- *    @requires lexical a component providing the tokens consumed by the
- *    parsers in this component.
- *  </p>
+/** This is the core component for token-based parsers.
  *
  *  @author Martin Odersky, Adriaan Moors
  */
 trait TokenParsers extends Parsers {
   /** Tokens is the abstract type of the `Token's consumed by the parsers in this component*/
-  type Tokens <: scala.util.parsing.syntax.Tokens
+  type Tokens <: token.Tokens
   
   /** lexical is the component responsible for consuming some basic kind of
    *  input (usually character-based) and turning it into the tokens
diff --git a/src/library/scala/util/parsing/combinator/testing/RegexTest.scala b/src/library/scala/util/parsing/combinator/testing/RegexTest.scala
index 301f544..2997360 100644
--- a/src/library/scala/util/parsing/combinator/testing/RegexTest.scala
+++ b/src/library/scala/util/parsing/combinator/testing/RegexTest.scala
@@ -1,4 +1,3 @@
-// $Id: RegexTest.scala 14415 2008-03-19 00:53:09Z mihaylov $
 
 package scala.util.parsing.combinator.testing
 
diff --git a/src/library/scala/util/parsing/combinator/testing/Tester.scala b/src/library/scala/util/parsing/combinator/testing/Tester.scala
index da2bb38..e50a2df 100644
--- a/src/library/scala/util/parsing/combinator/testing/Tester.scala
+++ b/src/library/scala/util/parsing/combinator/testing/Tester.scala
@@ -1,14 +1,14 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2006-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Tester.scala 16894 2009-01-13 13:09:41Z cunei $
 
 package scala.util.parsing.combinator.testing
+import scala.util.parsing.combinator._
 
 import scala.util.parsing.combinator.lexical.Lexical
 import scala.util.parsing.combinator.syntactical.TokenParsers
diff --git a/src/library/scala/util/parsing/combinator/token/StdTokens.scala b/src/library/scala/util/parsing/combinator/token/StdTokens.scala
new file mode 100644
index 0000000..414072b
--- /dev/null
+++ b/src/library/scala/util/parsing/combinator/token/StdTokens.scala
@@ -0,0 +1,37 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2006-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |                                         **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+package scala.util.parsing
+package combinator
+package token
+
+/** This component provides the standard `Token's for a simple, Scala-like language. 
+ *
+ * @author Martin Odersky, Adriaan Moors
+ */
+trait StdTokens extends Tokens {
+  /** The class of keyword tokens */
+  case class Keyword(chars: String) extends Token {
+    override def toString = "`"+chars+"'"
+  }
+
+  /** The class of numeric literal tokens */
+  case class NumericLit(chars: String) extends Token {
+    override def toString = chars
+  }
+
+  /** The class of string literal tokens */
+  case class StringLit(chars: String) extends Token {
+    override def toString = "\""+chars+"\""
+  }    
+
+  /** The class of identifier tokens */
+  case class Identifier(chars: String) extends Token {
+    override def toString = "identifier "+chars
+  }
+}
diff --git a/src/library/scala/util/parsing/combinator/token/Tokens.scala b/src/library/scala/util/parsing/combinator/token/Tokens.scala
new file mode 100644
index 0000000..7a12c8a
--- /dev/null
+++ b/src/library/scala/util/parsing/combinator/token/Tokens.scala
@@ -0,0 +1,40 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2006-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |                                         **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+package scala.util.parsing
+package combinator
+package token
+
+/** This component provides the notion of `Token', the unit of information that is passed from lexical
+ * parsers in the `Lexical' component to the parsers in the `TokenParsers' component.
+ *
+ * @author Martin Odersky, Adriaan Moors
+ */
+trait Tokens {
+  /** Objects of this type are produced by a lexical parser or ``scanner'', and consumed by a parser
+   * {@see scala.util.parsing.combinator.syntactical.TokenParsers}.
+   */
+  abstract class Token {
+    def chars: String
+  }
+  
+  /** A class of error tokens. Error tokens are used to communicate
+   *  errors detected during lexical analysis 
+   */
+  case class ErrorToken(msg: String) extends Token {
+    def chars = "*** error: "+msg
+  }
+
+  /** A class for end-of-file tokens */
+  case object EOF extends Token {
+    def chars = "<eof>"
+  }
+
+  /** This token is produced by a scanner {@see Scanner} when scanning failed. */
+  def errorToken(msg: String): Token = new ErrorToken(msg)  
+}
diff --git a/src/library/scala/util/parsing/combinatorold/$tilde.scala b/src/library/scala/util/parsing/combinatorold/$tilde.scala
deleted file mode 100644
index dce0627..0000000
--- a/src/library/scala/util/parsing/combinatorold/$tilde.scala
+++ /dev/null
@@ -1,16 +0,0 @@
-package scala.util.parsing.combinatorold;
-
-// p ~ q ~ r ^^ {case a ~ b ~ c => }
-case class ~[+a, +b](_1: a, _2: b)  // extends Pair[a, b]
-
-// shortcut for scala.util.parsing.combinatorold.~(_, _) -- just ~(_, _) resolves to unary_~
-object mkTilde { def apply[a, b](_1: a, _2: b) = scala.util.parsing.combinatorold.~(_1, _2) }
-
-
-  //def flatten[t, s <: (~[t, s] \/ t)](p: ~[t, s]): List[t] = p match {
-  //  case hd ~ tl => hd :: flatten(tl)
-  //  case a ~ b => List(a, b)
-  //}
-  //def flatten[t, s <: ~[t, s]](p: ~[t, s]): List[t] = p._1 :: flatten(p)
-  //def flatten[t](p: ~[t, t]): List[t] = List(p._1, p._2)
-                                                 
diff --git a/src/library/scala/util/parsing/combinatorold/ImplicitConversions.scala b/src/library/scala/util/parsing/combinatorold/ImplicitConversions.scala
deleted file mode 100644
index d38b39f..0000000
--- a/src/library/scala/util/parsing/combinatorold/ImplicitConversions.scala
+++ /dev/null
@@ -1,36 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-package scala.util.parsing.combinatorold
-
-/** This object contains implicit conversions that come in handy when using the `^^' combinator 
- * {@see Parsers} to construct an AST from the concrete syntax.
- *<p>
- * The reason for this is that the sequential composition combinator (`~') combines its constituents
- * into a ~. When several `~'s are combined, this results in nested `~'s (to the left).
- * The `flatten*' coercions makes it easy to apply an `n'-argument function to a nested ~ of
- * depth (`n-1')</p>
- *<p>
- * The `headOptionTailToFunList' converts a function that takes a List[A] to a function that 
- * accepts a ~[A, Option[List[A]]] (this happens when, e.g., parsing something of the following
- * shape: p ~ opt("." ~ repsep(p, ".")) -- where `p' is a parser that yields an A)</p>
- *
- * @author Martin Odersky, Iulian Dragos, Adriaan Moors 
- */
-trait ImplicitConversions { self: Parsers => 
-  implicit def flatten2[A, B, C]         (f: (A, B) => C) = 
-    (p: ~[A, B]) => p match {case a ~ b => f(a, b)}
-  implicit def flatten3[A, B, C, D]      (f: (A, B, C) => D) = 
-    (p: ~[~[A, B], C]) => p match {case a ~ b ~ c => f(a, b, c)}
-  implicit def flatten4[A, B, C, D, E]   (f: (A, B, C, D) => E) = 
-    (p: ~[~[~[A, B], C], D]) => p match {case a ~ b ~ c ~ d => f(a, b, c, d)}
-  implicit def flatten5[A, B, C, D, E, F](f: (A, B, C, D, E) => F) = 
-    (p: ~[~[~[~[A, B], C], D], E]) => p match {case a ~ b ~ c ~ d ~ e=> f(a, b, c, d, e)}
-  implicit def headOptionTailToFunList[A, T] (f: List[A] => T)= 
-    (p: ~[A, Option[List[A]]]) => f(p._1 :: (p._2 match { case Some(xs) => xs case None => Nil}))
-}
diff --git a/src/library/scala/util/parsing/combinatorold/Parsers.scala b/src/library/scala/util/parsing/combinatorold/Parsers.scala
deleted file mode 100644
index ca1e335..0000000
--- a/src/library/scala/util/parsing/combinatorold/Parsers.scala
+++ /dev/null
@@ -1,960 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: Parsers.scala 16894 2009-01-13 13:09:41Z cunei $
-
-package scala.util.parsing.combinatorold
-
-import scala.util.parsing.input._
-import scala.collection.mutable.{Map=>MutableMap}
-
-// TODO: better error handling (labelling like parsec's <?>)
-// TODO: memoisation (like packrat parsers?) 
-
-/** <p>
- *    <code>Parsers</code> is a component that <i>provides</i> generic
- *    parser combinators.
- *  </p>
- *  <p>
- *    It <i>requires</i> the type of the elements these parsers should parse 
- *    (each parser is polymorphic in the type of result it produces).
- *  </p>
- *  <p>
- *    There are two aspects to the result of a parser: (1) success or failure,
- *    and (2) the result. A <code>Parser[T]</code> provides both kinds of
- *    information, but a <code>UnitParser</code> only signals success/failure.
- *    When composing a `UnitParser' with a normal <code>Parser</code>, the
- *    <code>UnitParser</code> only contributes to whether the combined parser
- *    is successful (i.e., its result is discarded).
- *  </p>
- *  <p>
- *    The term ``parser combinator'' refers to the fact that these parsers
- *    are constructed from primitive parsers and composition operators, such
- *    as sequencing, alternation, optionality, repetition, lifting, and so on.
- *  </p>
- *  <p>
- *    A ``primitive parser'' is a parser that accepts or rejects a single
- *    piece of input, based on a certain criterion, such as whether the
- *    input...
- *  </p><ul>
- *    <li> is equal to some given object, </li>
- *    <li> satisfies a certain predicate, </li>
- *    <li> is in the domain of a given partial function,.... </li>
- *  </ul>
- *  <p>
- *    Even more primitive parsers always produce the same result, irrespective
- *    of the input.
- *  </p>
- *
- * @requires Elem the type of elements the provided parsers consume 
- *              (When consuming invidual characters, a parser is typically called a ``scanner'', 
- *               which produces ``tokens'' that are consumed by what is normally called a ``parser''.
- *               Nonetheless, the same principles apply, regardless of the input type.)</p>
- *<p>
- * @provides Input = Reader[Elem] 
- *              The type of input the parsers in this component expect.</p>
- *<p>
- * @provides Parser[+T] extends (Input => ParseResult[T]) 
- *              Essentially, a `Parser[T]' is a function from `Input' to `ParseResult[T]'.</p>
- *<p>
- * @provides ParseResult[+T] is like an `Option[T]', in the sense that it is either
- *              `Success[T]', which consists of some result (:T) (and the rest of the input) or
- *              `Failure[T]', which provides an error message (and the rest of the input).</p>
- *
- * @author Martin Odersky, Iulian Dragos, Adriaan Moors 
- */
-trait Parsers {
-  /** the type of input elements */
-  type Elem
-
-  /** The parser input is an abstract reader of input elements */
-  type Input = Reader[Elem]
-
-  /** A base class for parser results. 
-   *  A result is either successful or not (failure may be fatal, i.e.,
-   *  an Error, or not, i.e., a Failure)
-   *  On success, provides a result of type <code>T</code>. 
-   */
-  sealed abstract class ParseResult[+T] {
-    /** Functional composition of ParseResults
-     * 
-     * @param `f' the function to be lifted over this result
-     * @return `f' applied to the result of this `ParseResult', packaged up as a new `ParseResult'
-     */
-    def map[U](f: T => U): ParseResult[U]
-    
-    /** Partial functional composition of ParseResults
-     * 
-     * @param `f' the partial function to be lifted over this result
-     * @param error a function that takes the same argument as `f' and produces an error message 
-     *        to explain why `f' wasn't applicable (it is called when this is the case)
-     * @return <i>if `f' f is defined at the result in this `ParseResult',</i>
-     *         `f' applied to the result of this `ParseResult', packaged up as a new `ParseResult'.
-     *         If `f' is not defined, `Failure'.
-     */
-    def mapPartial[U](f: PartialFunction[T, U], error: T => String): ParseResult[U]   
-    
-    def isEmpty = !successful
-    
-    /** Returns the embedded result */
-    def get: T
-    
-    def getOrElse[B >: T](default: => B): B = 
-        if (isEmpty) default else this.get
-    
-    val next: Input
-    
-    val successful: Boolean
-  }
-
-  /** The success case of ParseResult: contains the result and the remaining input.
-   *
-   *  @param result The parser's output 
-   *  @param next   The parser's remaining input
-   */
-  case class Success[+T](result: T, override val next: Input) extends ParseResult[T] {
-    def map[U](f: T => U) = Success(f(result), next)
-    def mapPartial[U](f: PartialFunction[T, U], error: T => String): ParseResult[U] 
-       = if(f.isDefinedAt(result)) Success(f(result), next) 
-         else Failure(error(result), next)
-
-    def get: T = result
-    
-    /** The toString method of a Success */
-    override def toString = "["+next.pos+"] parsed: "+result
-    
-    val successful = true
-  }
-
-  /** A common super-class for unsuccessful parse results
-   */
-  sealed abstract class NoSuccess(val msg: String, override val next: Input) extends ParseResult[Nothing] { // when we don't care about the difference between Failure and Error
-    val successful = false
-
-    def map[U](f: Nothing => U) = this
-    def mapPartial[U](f: PartialFunction[Nothing, U], error: Nothing => String): ParseResult[U] = this
-
-    def get: Nothing = error("No result when parsing failed")
-  }
-  
-  /** The failure case of ParseResult: contains an error-message and the remaining input.
-   * Parsing will back-track when a failure occurs.
-   *
-   *  @param msg    An error message string describing the failure.
-   *  @param next   The parser's unconsumed input at the point where the failure occurred.
-   */
-  case class Failure(override val msg: String, override val next: Input) extends NoSuccess(msg, next) {
-    /** The toString method of a Failure yields an error message */
-    override def toString = "["+next.pos+"] failure: "+msg+"\n\n"+next.pos.longString
-  }
-  
-  /** The fatal failure case of ParseResult: contains an error-message and the remaining input.
-   * No back-tracking is done when a parser returns an `Error' 
-   *
-   *  @param msg    An error message string describing the error.
-   *  @param next   The parser's unconsumed input at the point where the error occurred.
-   */
-  case class Error(override val msg: String, override val next: Input) extends NoSuccess(msg, next) {
-    /** The toString method of an Error yields an error message */
-    override def toString = "["+next.pos+"] error: "+msg+"\n\n"+next.pos.longString
-  }
-  
-  /** The root class of parsers. 
-   *  Parsers are functions from the Input type to ParseResult 
-   */
-  abstract class Parser[+T] extends (Input => ParseResult[T]) {
-    /** An unspecified method that defines the behaviour of this parser.
-     */
-    def apply(in: Input): ParseResult[T]
-
-                                      
-    // the operator formerly known as +++, ++, &, but now, behold the venerable ~
-    // it's short, light (looks like whitespace), has few overloaded meaning (thanks to the recent change from ~ to unary_~)
-    // and we love it!
-                                      
-    /** A parser combinator for sequential composition 
-     *
-     * <p> `p ~ q' succeeds if `p' succeeds and `q' succeeds on the input
-     *          left over by `p'.</p>
-     * 
-     * @param q a parser that will be executed after `p' (this parser) succeeds
-     * @return a `Parser' that -- on success -- returns a `~' (like a Pair, but easier to pattern match on) 
-     *         that contains the result of `p' and that of `q'. 
-     *         The resulting parser fails if either `p' or `q' fails.
-     */
-    def ~ [U](q: => Parser[U]): Parser[~[T, U]] = new Parser[~[T, U]] {
-      def apply(in: Input) = seq(Parser.this, q)((x, y) => new ~(x,y))(in)
-      override def toString = "~"
-    }
-   
-     /* not really useful: V cannot be inferred because Parser is covariant in first type parameter (V is always trivially Nothing)
-    def ~~ [U, V](q: => Parser[U])(implicit combine: (T, U) => V): Parser[V] = new Parser[V] {
-      def apply(in: Input) = seq(Parser.this, q)((x, y) => combine(x,y))(in)
-    }  */   
-     
-    /** A parser combinator for sequential composition with a unit-parser 
-     *
-     * <p> `p ~ q' succeeds if `p' succeeds and `q' succeeds on the input
-     *          left over by `p'.</p>
-     *
-     * @param q a parser (convertible to a UnitParser) that will be executed after `p' (this parser)
-     *          succeeds
-     * @return a `Parser' that -- on success -- returns the result of `p'.
-     *         The resulting parser fails if either `p' or `q' fails.
-     */ 
-    def ~ [Q <% UnitParser](q: => Q): Parser[T] = new Parser[T] {
-      def apply(in: Input) = seq(Parser.this, q)((x, y) => x)(in)
-      override def toString = "~"
-    }
-    
-    /** A parser combinator for non-back-tracking sequential composition 
-     *
-     *<p>`p ~! q' succeeds if `p' succeeds and `q' succeeds on the input
-     *          left over by `p'. In case of failure, no back-tracking is performed 
-     *          (in an earlier parser produced by the | combinator).</p>
-     * 
-     * @param q a parser that will be executed after `p' (this parser) succeeds
-     * @return a `Parser' that -- on success -- returns a `~' (like a Pair, but easier to pattern match on) 
-     *         that contains the result of `p' and that of `q'. 
-     *         The resulting parser fails if either `p' or `q' fails, this failure is fatal.
-     */
-    def ~! [U](q: => Parser[U]): Parser[~[T, U]] = new Parser[~[T, U]] with OnceParser[~[T, U]] {
-      def apply(in: Input) = seq(Parser.this, commit(q))((x, y) => new ~(x,y))(in)
-      override def toString = "~!"
-    }
-    
-    /** A parser combinator for non-back-tracking sequential composition with a unit-parser
-     *
-     *<p>`p ~! q' succeeds if `p' succeeds and `q' succeeds on the input
-     *          left over by `p'. In case of failure, no back-tracking is performed 
-     *          (in an earlier parser produced by the | combinator).</p>
-     * 
-     * @param q a parser that will be executed after `p' (this parser) succeeds
-     * @return a `Parser' that -- on success -- returns the result of `p'.
-     *         The resulting parser fails if either `p' or `q' fails, this failure is fatal.
-     */
-    def ~! [Q <% UnitParser](q: => Q): Parser[T] = new Parser[T] with OnceParser[T] {
-      def apply(in: Input) = seq(Parser.this, commit(q))((x, y) => x)(in)
-      override def toString = "~!"
-    }
-
-    /** A parser combinator for alternative composition 
-     *
-     *<p>`p | q' succeeds if `p' succeeds or `q' succeeds
-     *          Note that `q' is only tried if `p's failure is non-fatal (i.e., back-tracking is
-     *          allowed).</p>
-     * 
-     * @param q a parser that will be executed if `p' (this parser) fails (and allows back-tracking)
-     * @return a `Parser' that returns the result of the first parser to succeed (out of `p' and `q')
-     *         The resulting parser succeeds if (and only if) <ul>
-     *           <li> `p' succeeds, <i>or</i>  </li>
-     *           <li> if `p' fails allowing back-tracking and `q' succeeds. </li> </ul>
-     */
-    def | [U >: T](q: => Parser[U]): Parser[U] = new Parser[U] {
-      def apply(in: Input) = Parser.this(in) match {
-        case s1 @ Success(_, _) => s1
-        case e1 @ Error(_, _) => e1
-        case f1 @ Failure(_, next1) => q(in) match {
-              case s2 @ Success(_, _) => s2
-              case f2 @ Failure(_, next2) => if (next2.pos < next1.pos) f1 else f2
-              case e2 @ Error(_, next2) => if (next2.pos < next1.pos) f1 else e2
-        }
-      }
-      override def toString = "|"
-    }
-    
-    /** A parser combinator for alternative with longest match composition 
-     *
-     *<p>`p ||| q' succeeds if `p' succeeds or `q' succeeds
-     *          If `p' and `q' both succeed, the parser that consumed the most
-     *          characters accepts.</p>
-     * 
-     * @param q a parser that accepts if p consumes less characters.
-     * @return a `Parser' that returns the result of the parser consuming the most characteres (out of `p' and `q').
-     */
-    def ||| [U >: T](q: => Parser[U]): Parser[U] = new Parser[U] {
-      def apply(in: Input) = {
-        val res1 = Parser.this(in)
-        val res2 = q(in)
-        
-        (res1, res2) match {
-          case (s1 @ Success(_, next1), s2 @ Success(_, next2)) => if (next2.pos < next1.pos) s1 else s2
-          case (s1 @ Success(_, _), _) => s1
-          case (_, s2 @ Success(_, _)) => s2
-          case (e1 @ Error(_, _), _) => e1
-          case (f1 @ Failure(_, next1), f2 @ Failure(_, next2)) => if (next2.pos < next1.pos) f1 else f2
-          case (f1 @ Failure(_, next1), e2 @ Error(_, next2)) => if (next2.pos < next1.pos) f1 else e2
-        }
-      }
-      override def toString = "|||"
-    }
-
-    /** A parser combinator for function application 
-     *
-     *<p>`p ^^ f' succeeds if `p' succeeds; it returns `f' applied to the result of `p'.</p>
-     *
-     * @param f a function that will be applied to this parser's result (see `map' in `ParseResult').
-     * @return a parser that has the same behaviour as the current parser, but whose result is
-     *         transformed by `f'.
-     */
-    def ^^ [U](f: T => U): Parser[U] = new Parser[U] {
-      def apply(in: Input) = Parser.this(in).map(f)
-      override def toString = Parser.this.toString+"^^"
-    }    
-    
-    /** A parser combinator for partial function application 
-     *
-     *<p>`p ^? (f, error)' succeeds if `p' succeeds AND `f' is defined at the result of `p'; 
-     *  in that case, it returns `f' applied to the result of `p'. If `f' is not applicable,
-     *  error(the result of `p') should explain why.</p>
-     *
-     * @param f a partial function that will be applied to this parser's result 
-     *          (see `mapPartial' in `ParseResult').
-     * @param error a function that takes the same argument as `f' and produces an error message 
-     *        to explain why `f' wasn't applicable
-     * @return a parser that succeeds if the current parser succeeds <i>and</i> `f' is applicable 
-     *         to the result. If so, the result will be transformed by `f'.     
-     */
-    def ^? [U](f: PartialFunction[T, U], error: T => String): Parser[U] = new Parser[U] {
-      def apply(in: Input) = Parser.this(in).mapPartial(f, error)
-      override def toString = Parser.this.toString+"^?"
-    }    
-     
-    /** A parser combinator for partial function application 
-     *
-     *<p>`p ^? f' succeeds if `p' succeeds AND `f' is defined at the result of `p'; 
-     *  in that case, it returns `f' applied to the result of `p'.</p>
-     *
-     * @param f a partial function that will be applied to this parser's result 
-     *          (see `mapPartial' in `ParseResult').
-     * @return a parser that succeeds if the current parser succeeds <i>and</i> `f' is applicable 
-     *         to the result. If so, the result will be transformed by `f'.     
-     */
-    def ^? [U](f: PartialFunction[T, U]): Parser[U] = new Parser[U] {
-      def apply(in: Input) = Parser.this(in).mapPartial(f, result => "Constructor function not defined at "+result)
-      override def toString = Parser.this.toString+"^?"
-    }       
-    
-       
-    /** A parser combinator that parameterises a subsequent parser with the result of this one
-     *
-     *<p>
-     * Use this combinator when a parser depends on the result of a previous parser. `p' should be
-     * a function that takes the result from the first parser and returns the second parser.</p>
-     *
-     *<p> `p into fq' (with `fq' typically `{x => q}') first applies `p', and then, if `p' successfully  
-     *    returned result `r', applies `fq(r)' to the rest of the input. </p>
-     *
-     *<p> From: G. Hutton. Higher-order functions for parsing. J. Funct. Program., 2(3):323--343, 1992. </p>
-     *
-     * @param fq a function that, given the result from this parser, returns the second parser to be applied
-     * @return a parser that succeeds if this parser succeeds (with result `x') and if then `fq(x)' succeeds
-     */
-    def into[U](fq: T => Parser[U]): Parser[U] = new Parser[U] {
-       def apply(in: Input) = Parser.this(in) match {
-         case Success(result, next) => fq(result)(next)
-         case ns: NoSuccess => ns
-       }
-     }
-    
-    // shortcuts for combinators:
-    
-    /** Returns into(fq) */
-    def >>[U](fq: T => Parser[U])=into(fq)
-    
-    
-    /** Returns a parser that repeatedly parses what this parser parses
-     *
-     * @return rep(this) 
-     */
-    def * = rep(this)
-    
-    /** Returns a parser that repeatedly parses what this parser parses, interleaved with the `sep' parser.
-     *
-     * @return repsep(this, sep)
-     */
-    def *[Q <% UnitParser](sep: => Q) = repsep(this, sep)
-    
-    /** Returns a parser that repeatedly parses what this parser parses, interleaved with the `sep' parser.
-     * The `sep' parser specifies how the results parsed by this parser should be combined.
-     *
-     * @return chainl1(this, sep) 
-     */    
-    def *[U >: T](sep: => Parser[(U, U) => U]) = chainl1(this, sep)
-    
-    // TODO: improve precedence? a ~ b*(",") = a ~ (b*(","))  should be true 
-    
-    /** Returns a parser that repeatedly (at least once) parses what this parser parses.
-     *
-     * @return rep1(this) 
-     */      
-    def + = rep1(this)
-    
-    /** Returns a parser that optionally parses what this parser parses.
-     *
-     * @return opt(this) 
-     */       
-    def ? = opt(this)
-  }
-
-  /** The root class of special parsers returning the trivial result <code>Unit</code>
-   *  These compose differently from normal parsers in that the <code>Unit</code>
-   *  result in a sequential or function composition is dropped.
-   */
-  abstract class UnitParser extends (Input => ParseResult[Unit]) {
-                                      
-    /** An unspecified method that defines the behaviour of this parser.
-     */
-    def apply(in: Input): ParseResult[Unit]
-
-    /** A parser combinator for sequential composition 
-     *
-     *<p>`p ~ q' succeeds if `p' succeeds and `q' succeeds on the input
-     *          left over by `p'.</p>
-     * 
-     * @param q a parser that will be executed after `p' (this parser) succeeds
-     * @return a `Parser' that -- on success -- returns the result of `q'. 
-     *         The resulting parser fails if either `p' or `q' fails.
-     */
-    def ~ [U](q: => Parser[U]): Parser[U] = new Parser[U] {
-      def apply(in: Input): ParseResult[U] = seq(UnitParser.this, q)((x, y) => y)(in)
-      override def toString = "~"
-    }
-     
-    /** A parser combinator for sequential composition with a unit-parser 
-     *
-     * <p>`p ~ q' succeeds if `p' succeeds and `q' succeeds on the input
-     *          left over by `p'.</p>
-     *
-     * @param q a parser (convertible to a UnitParser) that will be executed after `p' (this parser)
-     *          succeeds
-     * @return a `UnitParser' that fails if either `p' or `q' fails. 
-     */ 
-    def ~ [A <% UnitParser](q: => A): UnitParser = new UnitParser {
-      def apply(in: Input): ParseResult[Unit] = seq(UnitParser.this, q)((x, y) => y)(in)
-      override def toString = "~"
-    }
-     
-    /** A parser combinator for non-back-tracking sequential composition 
-     *
-     *  <p>`p ~! q' succeeds if `p' succeeds and `q' succeeds on the input
-     *          left over by `p'. In case of failure, no back-tracking is performed 
-     *          (in an earlier parser produced by the | combinator).</p>
-     * 
-     * @param q a parser that will be executed after `p' (this parser) succeeds
-     * @return a `Parser' that -- on success -- returns the result of `q`. 
-     *         The resulting parser fails if either `p' or `q' fails, this failure is fatal.
-     */
-    def ~! [U](q: => Parser[U]): Parser[U] = new Parser[U] with OnceParser[U] {
-      def apply(in: Input) = seq(UnitParser.this, commit(q))((x, y) => y)(in)
-      override def toString = "~!"
-    }
-
-    /** A parser combinator for non-back-tracking sequential composition with a unit-parser
-     *
-     *  <p>`p ~! q' succeeds if `p' succeeds and `q' succeeds on the input
-     *          left over by `p'. In case of failure, no back-tracking is performed 
-     *          (in an earlier parser produced by the | combinator).</p>
-     * 
-     * @param q a parser that will be executed after `p' (this parser) succeeds
-     * @return a `UnitParser' that fails if either `p' or `q' fails, this failure is fatal.
-     */
-    def ~! [Q <% UnitParser](q: => Q): UnitParser = new UnitParser with UnitOnceParser {
-      def apply(in: Input) = seq(UnitParser.this, commit(q))((x, y) => y)(in)
-      override def toString = "~!"
-    }
-
-     /** A parser combinator for alternative composition 
-     *
-     *<p>`p | q' succeeds if `p' succeeds or `q' succeeds
-     *          Note that `q' is only tried if `p's failure is non-fatal (i.e., back-tracking is
-     *          allowed).</p>
-     * 
-     * @param q a parser that will be executed if `p' (this parser) fails (and allows back-tracking)
-     * @return a `Parser' succeeds if (and only if) <ul>
-     *           <li> `p' succeeds, <i>or</i>  </li>
-     *           <li> if `p' fails allowing back-tracking and `q' succeeds. </li> </ul>
-     */
-    def | [Q <% UnitParser](q: => Q): UnitParser = new UnitParser {
-      def apply(in: Input) = UnitParser.this(in) match {
-        case s1 @ Success(_, _) => s1
-        case e1 @ Error(_, _) => e1
-        case f1 @ Failure(_, next1) => q(in) match {
-              case s2 @ Success(_, _) => s2
-              case f2 @ Failure(_, next2) => if (next2.pos < next1.pos) f1 else f2
-              case e2 @ Error(_, next2) => if (next2.pos < next1.pos) f1 else e2
-        }
-      }
-      override def toString = "|"
-    }
-    
-    /** A parser combinator for alternative with longest match composition 
-     *
-     *<p>`p ||| q' succeeds if `p' succeeds or `q' succeeds
-     *          If `p' and `q' both succeed, the parser that consumed the most
-     *          characters accepts.</p>
-     * 
-     * @param q a parser that accepts if p consumes less characters.
-     * @return a `Parser' that returns the result of the parser consuming the most characteres (out of `p' and `q').
-     */
-    def ||| [Q <% UnitParser](q: => Q): UnitParser = new UnitParser {
-      def apply(in: Input) = {
-        val res1 = UnitParser.this(in)
-        val res2 = q(in)
-        
-        (res1, res2) match {
-          case (s1 @ Success(_, next1), s2 @ Success(_, next2)) => if (next2.pos < next1.pos) s1 else s2
-          case (s1 @ Success(_, _), _) => s1
-          case (_, s2 @ Success(_, _)) => s2
-          case (e1 @ Error(_, _), _) => e1
-          case (f1 @ Failure(_, next1), f2 @ Failure(_, next2)) => if (next2.pos < next1.pos) f1 else f2
-          case (f1 @ Failure(_, next1), e2 @ Error(_, next2)) => if (next2.pos < next1.pos) f1 else e2
-        }
-      }
-      override def toString = "|||"
-    }
-     
-     
-    /** A parser combinator for function application 
-     *
-     *  <p>`p ^^ v' succeeds if `p' succeeds; it returns `v'.</p>
-     *
-     * @param v a value that's used as the result of the returned Parser (if it was successful).
-     * @return a parser that has the same behaviour as the current parser, but whose result is
-     *         consists of `v'.
-     */
-    def ^^ [U](v: U): Parser[U] = new Parser[U] {
-      def apply(in: Input) = UnitParser.this(in).map(x => v)
-      override def toString = UnitParser.this.toString+"^^"
-    }
-  }
-
-  // TODO: can this implemented in ParseResult, like map?
-  /** A helper method for sequential composition of (unit-)parsers
-  */
-  private def seq[T, U, V](p: => Input => ParseResult[T], q: => Input => ParseResult[U])
-                          (compose: (T, U) => V)
-                          (in: Input): ParseResult[V] 
-    = p(in) match {
-      case Success(x, next1) => q(next1) match {
-          case Success(y, next2) => Success(compose(x, y), next2)
-          case ns: NoSuccess => ns
-        }
-      case ns: NoSuccess => ns
-    }
-  
-  /** Wrap a parser so that its failures become errors (the | combinator will give up as soon as 
-   *  it encounters an error, on failure it simply tries the next alternative) 
-   */
-  def commit[T](p: => Parser[T]) = new Parser[T] {
-    def apply(in: Input) = p(in) match{
-      case s @ Success(_, _) => s
-      case e @ Error(_, _) => e
-      case f @ Failure(msg, next) => Error(msg, next)
-    }
-  }
-  
-  /** Wrap a parser so that its failures become errors (the | combinator will give up as soon as 
-   *  it encounters an error, on failure it simply tries the next alternative) 
-   */
-  def commit[Q <% UnitParser](p: => Q) = new UnitParser {
-    def apply(in: Input) = p(in) match{
-      case s @ Success(_, _) => s
-      case e @ Error(_, _) => e
-      case f @ Failure(msg, next) => Error(msg, next)
-    }
-  }
-  
-  /** Wrap a parser so that its failures&errors become success and vice versa -- it never consumes any input 
-   */
-  def not[Q <% UnitParser](p: => Q) = new UnitParser {
-    def apply(in: Input) = p(in) match{
-      case s @ Success(_, _) => Failure("Expected failure", in)
-      case e @ Error(_, _) => Success((), in)
-      case f @ Failure(msg, next) => Success((), in)
-    }
-  }  
-  
-	/*trait ElemFun
-  case class EFCons(hd: Elem => ElemFun, tl: ElemFun) extends ElemFun
-  case class EFNil(res: Boolean) extends ElemFun*/
-
-   
-  /** A parser matching input elements that satisfy a given predicate
-   *
-   * <p>elem(kind, p) succeeds if the input starts with an element `e' for which p(e) is true.</p>
-   *
-   * @param  kind   The element kind, used for error messages
-   * @param  p      A predicate that determines which elements match.
-   * @return 
-   */
-  def elem(kind: String, p: Elem => Boolean) = new Parser[Elem] {
-    def apply(in: Input) =
-      if (p(in.first)) Success(in.first, in.rest)
-      else Failure(kind+" expected", in)
-  }  
-   
-  /** A parser that matches only the given element `e'
-   *
-   * <p>elem(e) succeeds if the input starts with an element `e'</p>
-   *
-   * @param e the `Elem' that must be the next piece of input for the returned parser to succeed
-   * @return a `Parser' that succeeds if `e' is the next available input (and returns it).
-   */
-  def elem(e: Elem): Parser[Elem] = new Parser[Elem] {
-    def apply(in: Input) =
-      if (in.first == e) Success(e, in.rest)
-      else Failure("`"+e+"' expected but " + in.first + " found", in)
-  }
-  
-  
-  /** A parser that matches only the given element `e' 
-   *<p>
-   * The method is implicit so that elements can automatically be lifted to their unit-parsers. 
-   * For example, when parsing `Token's, Identifier("new") (which is a `Token') can be used directly,
-   * instead of first creating a `UnitParser' using accept(Identifier("new")).</p>
-   *
-   * @param e the `Elem' that must be the next piece of input for the returned parser to succeed
-   * @return a `UnitParser' that succeeds if `e' is the next available input.
-   */
-  implicit def accept(e: Elem): UnitParser = new UnitParser {
-    def apply(in: Input) =
-      if (in.first == e) Success((), in.rest)
-      else Failure("`"+e+"' expected but " + in.first + " found", in)
-  }
-   
-  /** A parser that matches only the given list of element `es'
-   *
-   * <p>accept(es) succeeds if the input subsequently provides the elements in the list `es'.</p>
-   *
-   * @param  es the list of expected elements
-   * @return a UnitParser that recognizes a specified list of elements
-   */
-  def accept[ES <% List[Elem]](es: ES): UnitParser = new UnitParser {
-    def apply(in0: Input) = {
-      var res = new scala.collection.mutable.ListBuffer[Elem]
-      var these: List[Elem] = es
-      var in = in0
-      
-      while(!these.isEmpty && in.first == these.head) {
-        these = these.tail
-        in = in.rest
-      }
-       
-      if (these.isEmpty) Success((), in)
-      else Failure("Expected: '"+these.head+"', found: '"+in.first+"'", in0)
-    }
-  }    
-
-  /** The parser that matches an element in the domain of the partial function `f'
-   *<p>
-   * If `f' is defined on the first element in the input, `f' is applied to it to produce 
-   * this parser's result.</p>
-   *<p>
-   * Example: The parser <code>accept("name", {case Identifier(n) => Name(n)})</code> 
-   *          accepts an <code>Identifier(n)</code> and returns a <code>Name(n)</code>.</p>
-   *
-   * @param expected a description of the kind of element this parser expects (for error messages)
-   * @param f a partial function that determines when this parser is successful and what its output is
-   * @return A parser that succeeds if `f' is applicable to the first element of the input, 
-   *         applying `f' to it to produce the result.
-   */
-  def accept[U](expected: String, f: PartialFunction[Elem, U]): Parser[U] = new Parser[U] {
-    def apply(in: Input) =
-      if (f.isDefinedAt(in.first)) Success(f(in.first), in.rest)
-      else Failure(expected+" expected", in)
-  }
-
-  /** A parser that always fails 
-   *
-   * @param msg The error message describing the failure. 
-   * @return A parser that always fails with the specified error message.
-   */
-  def failure(msg: String) = new Parser[Nothing] {
-    def apply(in: Input) = Failure(msg, in)
-  }
-
-  /** A unit-parser that always fails 
-   *
-   * @param msg The error message describing the failure. 
-   * @return A parser that always fails with the specified error message.
-   */  
-  def fail(msg: String) = new UnitParser {
-    def apply(in: Input) = Failure(msg, in)
-  }
-
-  /** A parser that always succeeds 
-   *
-   * @param v The result for the parser
-   * @return A parser that always succeeds, with the given result `v'
-   */
-  def success[T](v: T) = new Parser[T] {
-    def apply(in: Input) = Success(v, in)
-  }
-
-  /** A unit-parser that always succeeds  */
-  def success = new UnitParser {
-    def apply(in: Input) = Success((), in)
-  }
-  
-  /** A unit-parser that always succeeds, discarding `p's result
-  *
-  * @param p The parser whose result is to be discarded
-  * @return A parser that always succeeds, with the empty result
-  */
-  implicit def discard[T](p: => Parser[T]) = new UnitParser {
-    def apply(in: Input) = p(in) map {(x) => ()}
-  }
-  
-  
-  def log[T](p: => Parser[T])(name: String): Parser[T] = new Parser[T] {
-    def apply(in: Input) = {println("trying "+name+" at "+in.pos); val r = p(in); println(name+" --> "+r); r }
-  }
-  
-  def log[Q <% UnitParser](p: => Q)(name: String): UnitParser = new UnitParser {
-    def apply(in: Input) = {println("trying "+name+" at "+in.pos); val r = p(in); println(name+" --> "+r); r }
-  }
-    
-    
-  /** A parser generator for repetitions.
-   *  
-   * <p> rep(p)   repeatedly uses `p' to parse the input until `p' fails (the result is a List 
-   *  of the consecutive results of `p') </p>
-   *
-   * @param p a `Parser' that is to be applied successively to the input
-   * @return A parser that returns a list of results produced by repeatedly applying `p' to the input.
-   */
-  def rep[T](p: => Parser[T]): Parser[List[T]] = rep1(p) | success(List())
-
-  /** A parser generator for repetitions.
-   *  
-   * <p> rep(p)   repeatedly uses `p' to parse the input until `p' fails</p>
-   *
-   * @param p a `Parser' that is to be applied successively to the input
-   * @return A parser that repeatedly applies `p' to the input.
-   */  
-  def rep[Q <% UnitParser](p: => Q): UnitParser = rep1(p) | success
-    
-  /** A parser generator for interleaved repetitions.
-   *  
-   * <p> repsep(p, q)   repeatedly uses `p' interleaved with `q' to parse the input, until `p' fails.
-   *  (The result is a `List' of the results of `p'.) </p>
-   *
-   * <p>Example: <code>repsep(term, ",")</code> parses a comma-separated list of term's, 
-   *          yielding a list of these terms</p>
-   *
-   * @param p a `Parser' that is to be applied successively to the input
-   * @param q a `UnitParser' that parses the elements that separate the elements parsed by `p'
-   * @return A parser that returns a list of results produced by repeatedly applying `p' (interleaved
-   *         with `q') to the input.
-   */
-  def repsep[T, Q <% UnitParser](p: => Parser[T], q: => Q): Parser[List[T]] = 
-    rep1sep(p, q) | success(List())
-  
-  /** A parser generator for non-empty repetitions.
-   *  
-   * <p> rep1(p) repeatedly uses `p' to parse the input until `p' fails -- `p' must succeed at least
-   *             once (the result is a `List' of the consecutive results of `p')</p>
-   *
-   * @param p a `Parser' that is to be applied successively to the input
-   * @return A parser that returns a list of results produced by repeatedly applying `p' to the input
-   *        (and that only succeeds if `p' matches at least once).
-   */
-  def rep1[T](p: => Parser[T]): Parser[List[T]] = rep1(p, p)
-  
-  /** A parser generator for non-empty repetitions.
-   *  
-   * <p> rep1(f, p) first uses `f' (which must succeed) and then repeatedly uses `p' to 
-   *     parse the input until `p' fails 
-   *     (the result is a `List' of the consecutive results of `f' and `p')</p>
-   *
-   * @param first a `Parser' that parses the first piece of input
-   * @param p a `Parser' that is to be applied successively to the rest of the input (if any)
-   * @return A parser that returns a list of results produced by first applying `f' and then 
-   *         repeatedly `p' to the input (it only succeeds if `f' matches).
-   */
-  def rep1[T](first: => Parser[T], p: => Parser[T]): Parser[List[T]] = first ~ rep(p) ^^ { case ~(x, xs) => x :: xs }
-  
-  /* new Parser[List[T]] {
-    def apply(in0: Input) = {
-      val xs = new scala.collection.mutable.ListBuffer[T]
-      var in = in0
-      
-      var res = first(in)
-      
-      while(res.successful) {
-        xs += res.get
-        in = res.next
-        res = p(in)
-      }
-      
-      if (!xs.isEmpty) Success(xs.toList, res.next)
-      else Failure("TODO", TODO)
-    }
-  }*/
-
-  /** A parser generator for a specified number of repetitions.
-   *  
-   * <p> repN(n, p)  uses `p' exactly `n' time to parse the input 
-   *       (the result is a `List' of the `n' consecutive results of `p')</p>
-   *
-   * @param p a `Parser' that is to be applied successively to the input
-   * @param n the exact number of times `p' must succeed
-   * @return A parser that returns a list of results produced by repeatedly applying `p' to the input
-   *        (and that only succeeds if `p' matches exactly `n' times).
-   */  
-  def repN[T](n: Int, p: => Parser[T]): Parser[List[T]] = 
-    if(n==0) success(Nil) else p ~ repN(n-1, p) ^^ { case ~(x, xs) => x :: xs }
-  
-  /** A parser generator for non-empty repetitions.
-   *  
-   * <p> rep1(p) repeatedly uses `p' to parse the input until `p' fails -- `p' must succeed at least
-   *             once</p>
-   *
-   * @param p a `Parser' that is to be applied successively to the input
-   * @return A unitparser that repeatedly applies `p' to the input
-   *        (and that only succeeds if `p' matches at least once).
-   */
-  def rep1[Q <% UnitParser](p: => Q): UnitParser = 
-    p ~ rep(p)
-  
-  /** A parser generator for a specified number of repetitions.
-   *  
-   * <p> repN(n, p)  uses `p' exactly `n' time to parse the input</p>
-   *
-   * @param p a `Parser' that is to be applied successively to the input
-   * @param n the exact number of times `p' must succeed
-   * @return A unitparser that repeatedly applies `p' to the input
-   *        (and that only succeeds if `p' matches at exactly `n' times).
-   */  
-  def repN[Q <% UnitParser](n: Int, p: => Q): UnitParser = 
-    if(n==0) success else p ~ repN(n-1, p) 
-   
-  /** A parser generator for non-empty repetitions.
-   *  
-   *  <p>rep1sep(first, p, q) starts by using `first', followed by repeatedly uses of `p' interleaved with `q' 
-   *                to parse the input, until `p' fails. `first' must succeed (the result is a `List' of the 
-   *                consecutive results of `first' and `p')</p>
-   *
-   * @param first a `Parser' that is to be applied to the first element of input
-   * @param p a `Parser' that is to be applied successively to the input
-   * @param q a `UnitParser' that parses the elements that separate the elements parsed by `p' 
-   *          (interleaved with `q')   
-   * @return A parser that returns a list of results produced by repeatedly applying `p' to the input
-   *        (and that only succeeds if `p' matches at least once).
-   */
-  def rep1sep[T, Q <% UnitParser](first: => Parser[T], p: => Parser[T], q: => Q): Parser[List[T]] = 
-    first ~ rep(q ~ p) ^^ { case x ~ y => x :: y }
-
-  def rep1sep[T, Q <% UnitParser](p: => Parser[T], q: => Q): Parser[List[T]] = rep1sep(p, p, q)
-   
-  /** A parser generator that, roughly, generalises the rep1sep generator so that `q', which parses the separator,
-   * produces a left-associative function that combines the elements it separates.
-   *
-   * <p> From: J. Fokker. Functional parsers. In J. Jeuring and E. Meijer, editors, Advanced Functional Programming, volume 925 of Lecture Notes in Computer Science, pages 1--23. Springer, 1995.</p>
-   *
-   * @param p a parser that parses the elements
-   * @param q a parser that parses the token(s) separating the elements, yielding a left-associative function that 
-   *          combines two elements into one 
-   */
-  def chainl1[T](p: => Parser[T], q: => Parser[(T, T) => T]): Parser[T] = 
-    p ~ rep(q ~ p) ^^ {case x ~ xs => xs.foldLeft(x)((a, f_b) => f_b._1(a, f_b._2))}  // ((a, {f, b}) => f(a, b)) 
-
-  /** A parser generator that, roughly, generalises the rep1sep generator so that `q', which parses the separator,
-   * produces a left-associative function that combines the elements it separates.
-   *
-   * @param first a parser that parses the first element
-   * @param p a parser that parses the subsequent elements
-   * @param q a parser that parses the token(s) separating the elements, yielding a left-associative function that 
-   *          combines two elements into one 
-   */
-  def chainl1[T, U](first: => Parser[T], p: => Parser[U], q: => Parser[(T, U) => T]): Parser[T] = 
-    first ~ rep(q ~ p) ^^ {case x ~ xs => xs.foldLeft(x)((a, f_b) => f_b._1(a, f_b._2))}  // ((a, {f, b}) => f(a, b)) 
-        
-  /** A parser generator that generalises the rep1sep generator so that `q', which parses the separator,
-   * produces a right-associative function that combines the elements it separates. Additionally,
-   * The right-most (last) element and the left-most combinating function have to be supplied.
-   * 
-   * rep1sep(p: Parser[T], q) corresponds to chainr1(p, q ^^ cons, cons, Nil) (where val cons = (x: T, y: List[T]) => x :: y)
-   *
-   * @param p a parser that parses the elements
-   * @param q a parser that parses the token(s) separating the elements, yielding a right-associative function that 
-   *          combines two elements into one 
-   * @param combine the "last" (left-most) combination function to be applied
-   * @param first   the "first" (right-most) element to be combined
-   */
-  def chainr1[T, U](p: Parser[T], q: Parser[(T, U) => U], combine: (T, U) => U, first: U): Parser[U] = 
-    p ~ rep(q ~ p) ^^ {case x ~ xs => 
-                          (new ~(combine, x) :: xs).foldRight(first)((f_a, b) => f_a._1(f_a._2, b))}  // (({f, a}, b) => f(a, b))     
-    
-  /** A parser generator for optional sub-phrases.
-   *  
-   *  <p>opt(p) is a parser that returns `Some(x)' if `p' returns `x' and `None' if `p' fails</p>
-   *
-   * @param p A `Parser' that is tried on the input
-   * @return a `Parser' that always succeeds: either with the result provided by `p' or 
-   *         with the empty result
-   */
-  def opt[T](p: => Parser[T]): Parser[Option[T]] = 
-    p ^^ (x => Some(x)) | success(None)
-
-
-  /** Turns a unit-parser into a boolean-parser that denotes whether the unit-parser succeeded.
-   */
-  def opt[Q <% UnitParser](q: => Q): Parser[Boolean] = q ^^ true | success(false) 
-    
-    
-  /** `positioned' decorates a parser's result with the start position of the input it consumed. 
-   * 
-   * @param p a `Parser' whose result conforms to `Positional'.
-   * @return A parser that has the same behaviour as `p', but which marks its result with the 
-   *         start position of the input it consumed, if it didn't already have a position.
-   */
-  def positioned[T <: Positional](p: => Parser[T]): Parser[T] = new Parser[T] {
-    def apply(in: Input) = p(in) match {
-      case Success(t, in1) => Success(if (t.pos == NoPosition) t setPos in.pos else t, in1)
-      case ns: NoSuccess => ns
-    }
-  }
-
-  /** <code>positioned</code> decorates a unit-parser so that it returns the
-   *  start position of the input it consumed. 
-   * 
-   *  @param p a `UnitParser'.
-   *  @return  A parser that has the same behaviour as `p', but which returns
-   *           the start position of the input it consumed.
-   */
-  def positioned[Q <% UnitParser](p: => Q) = new Parser[Position] {
-    def apply(in: Input) = p(in) match {
-      case Success(_, in1) => Success(in.pos, in1) 
-      case ns: NoSuccess => ns
-    }
-  }
-  
-  /** A parser whose ~ combinator disallows back-tracking.
-   */
-  trait OnceParser[+T] extends Parser[T] {
-    override def ~ [U](q: => Parser[U]): Parser[~[T, U]] = new Parser[~[T, U]] with OnceParser[~[T, U]] {
-      def apply(in: Input) = seq(OnceParser.this, commit(q))((x, y) => new ~(x, y))(in)
-    }
-    override def ~ [Q <% UnitParser](q: => Q): Parser[T] = new Parser[T] with OnceParser[T] {
-      def apply(in: Input) = seq(OnceParser.this, commit(q))((x, y) => x)(in)
-    }
-  }
-  
-  /** A parser whose ~ combinator disallows back-tracking.
-   */
-  trait UnitOnceParser extends UnitParser {
-    override def ~ [U](q: => Parser[U]): Parser[U] = new Parser[U] with OnceParser[U]{
-      def apply(in: Input): ParseResult[U] = seq(UnitOnceParser.this, commit(q))((x, y) => y)(in)
-    }
-    override def ~ [A <% UnitParser](q: => A): UnitParser = new UnitOnceParser {
-      def apply(in: Input): ParseResult[Unit] = seq(UnitOnceParser.this, commit(q))((x, y) => y)(in)
-    }
-  }
-}
diff --git a/src/library/scala/util/parsing/combinatorold/lexical/Lexical.scala b/src/library/scala/util/parsing/combinatorold/lexical/Lexical.scala
deleted file mode 100644
index 69e69ea..0000000
--- a/src/library/scala/util/parsing/combinatorold/lexical/Lexical.scala
+++ /dev/null
@@ -1,41 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: Lexical.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala.util.parsing.combinatorold.lexical
-
-import scala.util.parsing.syntax._
-import scala.util.parsing.input.CharArrayReader.EofCh
-
-/** <p>
- *    This component complements the <code>Scanners</code> component with
- *    common operations for lexical parsers.
- *  </p>
- *  <p>
- *   {@see StdLexical} for a concrete implementation for a simple, Scala-like
- *   language.
- *  </p>
- *
- * @author Martin Odersky, Adriaan Moors
- */
-abstract class Lexical extends Scanners with Tokens {
-
-  /** A character-parser that matches a letter (and returns it)*/
-  def letter = elem("letter", _.isLetter)
-
-  /** A character-parser that matches a digit (and returns it)*/  
-  def digit = elem("digit", _.isDigit)
-
-  /** A character-parser that matches any character except the ones given in `cs' (and returns it)*/  
-  def chrExcept(cs: Char*) = elem("", ch => (cs forall (ch !=)))
-
-  /** A character-parser that matches a white-space character (and returns it)*/  
-  def whitespaceChar = elem("space char", ch => ch <= ' ' && ch != EofCh)
-}
diff --git a/src/library/scala/util/parsing/combinatorold/lexical/Scanners.scala b/src/library/scala/util/parsing/combinatorold/lexical/Scanners.scala
deleted file mode 100644
index 93d64ff..0000000
--- a/src/library/scala/util/parsing/combinatorold/lexical/Scanners.scala
+++ /dev/null
@@ -1,77 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: Scanners.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala.util.parsing.combinatorold.lexical
-
-import scala.util.parsing.syntax._
-import scala.util.parsing.input._
-
-/** <p>
- *    This component provides core functionality for lexical parsers.
- *  </p>
- *  <p>
- *    See its subclasses {@see Lexical} and -- most interestingly
- *    {@see StdLexical}, for more functionality.
- *  </p>
- *
- *  @requires token      a parser that produces a token (from a stream of characters)
- *  @requires whitespace a unit-parser for white-space
- *  @provides Scanner    essentially a parser that parses a stream of characters
- *                       to produce `Token's, which are typically passed to a
- *                       syntactical parser (which operates on `Token's, not on
- *                       individual characters).
- *
- *  @author Martin Odersky, Adriaan Moors 
- */
-trait Scanners extends Parsers {
-  type Elem = Char
-  type Token
-  
-  /** This token is produced by a scanner {@see Scanner} when scanning failed. */
-  def errorToken(msg: String): Token
-  
-  /** a parser that produces a token (from a stream of characters) */
-  def token: Parser[Token]
-  
-  /** a parser for white-space -- its result will be discarded */
-  def whitespace: Parser[Any]
-
-  /** <p>
-   *    <code>Scanner</code> is essentially(*) a parser that produces `Token's
-   *    from a stream of characters. The tokens it produces are typically
-   *    passed to parsers in <code>TokenParsers</code>.
-   *  </p>
-   *  <p>
-   *   Note: (*) <code>Scanner</code> is really a `Reader' of `Token's
-   *  </p>
-   */
-  class Scanner(in: Reader[Char]) extends Reader[Token] {
-    /** Convenience constructor (makes a character reader out of the given string) */
-    def this(in: String) = this(new CharArrayReader(in.toCharArray()))
-    private val (tok, rest1, rest2) = whitespace(in) match {
-      case Success(_, in1) => 
-        token(in1) match {
-          case Success(tok, in2) => (tok, in1, in2)
-          case ns: NoSuccess => (errorToken(ns.msg), ns.next, skip(ns.next))
-        }
-      case ns: NoSuccess => (errorToken(ns.msg), ns.next, skip(ns.next))
-    }
-    private def skip(in: Reader[Char]) = if (in.atEnd) in else in.rest
-
-    override def source: java.lang.CharSequence = in.source
-    override def offset: Int = in.offset
-    def first = tok
-    def rest = new Scanner(rest2)
-    def pos = rest1.pos
-    def atEnd = in.atEnd || (whitespace(in) match { case Success(_, in1) => in1.atEnd case _ => false })
-  }
-}
-
diff --git a/src/library/scala/util/parsing/combinatorold/lexical/StdLexical.scala b/src/library/scala/util/parsing/combinatorold/lexical/StdLexical.scala
deleted file mode 100644
index dd6cffe..0000000
--- a/src/library/scala/util/parsing/combinatorold/lexical/StdLexical.scala
+++ /dev/null
@@ -1,97 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: StdLexical.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala.util.parsing.combinatorold.lexical
-
-import scala.util.parsing.syntax._
-import scala.util.parsing.input.CharArrayReader.EofCh
-import collection.mutable.HashSet
-
-/** <p>
- *    This component provides a standard lexical parser for a simple, Scala-like language. 
- *    It parses keywords and identifiers, numeric literals (integers), strings, and delimiters. 
- *  </p>
- *  <p>
- *    To distinguish between identifiers and keywords, it uses a set of reserved identifiers: 
- *    every string contained in `reserved' is returned as a keyword token.
- *    (Note that "=>" is hard-coded as a keyword.) 
- *    Additionally, the kinds of delimiters can be specified by the `delimiters' set.
- *  </p>
- *  <p>
- *    Usually this component is used to break character-based input into bigger tokens,
- *    which are then passed to a token-parser {@see TokenParsers}.
- *  </p>
- *
- * @author Martin Odersky, Iulian Dragos, Adriaan Moors 
- */
-class StdLexical extends Lexical with StdTokens {
-  
-  // override this parser to change the characters allowed at the beginning of an identifier
-  def identBegin: Parser[Char] = ('_' ^^ '_') | letter
-
-  // override this parser to change the characters allowed in an identifier (i.e., after the first character)
-  def identCont: Parser[Char] = ('_' ^^ '_') | letter | digit
-       
-  // see `token' in `Scanners'
-  def token: Parser[Token] = 
-    ( identBegin ~ rep( identCont )                     ^^ lift2(processIdent)
-    | digit ~ rep( digit )                              ^^ lift2(NumericLit)
-    | '\'' ~ rep( chrExcept('\'', '\n', EofCh) ) ~ '\'' ^^ lift(StringLit)
-    | '\"' ~ rep( chrExcept('\"', '\n', EofCh) ) ~ '\"' ^^ lift(StringLit)
-    | EofCh                                             ^^ EOF
-    | '\'' ~ failure("unclosed string literal")
-    | '\"' ~ failure("unclosed string literal")
-    | delim                                             
-    | failure("illegal character")
-    )
-
-  // see `whitespace in `Scanners'
-  def whitespace: Parser[Any] = rep(
-      whitespaceChar
-    | '/' ~ '*' ~ comment
-    | '/' ~ '/' ~ rep( chrExcept(EofCh, '\n') )
-    | '/' ~ '*' ~ failure("unclosed comment")
-    )
-
-  protected def comment: Parser[Any] = (
-      '*' ~ '/'  ^^ ' ' 
-    | chrExcept(EofCh) ~ comment
-    )
-
-  /** The set of reserved identifiers: these will be returned as `Keyword's */
-  val reserved = new HashSet[String]
-
-  /** The set of delimiters (ordering does not matter) */
-  val delimiters = new HashSet[String]
-
-  protected def processIdent(name: String) = 
-    if (reserved contains name) Keyword(name) else Identifier(name)
-
-  private var _delim: Parser[Token] = null
-  protected def delim: Parser[Token] = {
-    if(_delim eq null) { // construct parser for delimiters by |'ing together the parsers for the individual delimiters, 
-    // starting with the longest one (hence the sort + reverse) -- otherwise a delimiter D will never be matched if 
-    // there is another delimiter that is a prefix of D   
-      def parseDelim(s: String): Parser[Token] = accept(s.toList) ^^ Keyword(s)
-      
-      val d = new Array[String](delimiters.size)
-      delimiters.copyToArray(d,0)
-      scala.util.Sorting.quickSort(d) 
-      _delim = d.toList.reverse.map(parseDelim).reduceRight[Parser[Token]](_ | _) // no offence :-)      
-    }
-    
-    _delim
-  }
-
-  private def lift[T](f: String => T)(xs: List[Char]): T = f(xs.mkString("", "", ""))
-
-  private def lift2[T](f: String => T)(p: ~[Char, List[Char]]): T = lift(f)(p._1 :: p._2)
-}
diff --git a/src/library/scala/util/parsing/combinatorold/syntactical/BindingParsers.scala b/src/library/scala/util/parsing/combinatorold/syntactical/BindingParsers.scala
deleted file mode 100644
index 61f0a46..0000000
--- a/src/library/scala/util/parsing/combinatorold/syntactical/BindingParsers.scala
+++ /dev/null
@@ -1,143 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: BindingParsers.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala.util.parsing.combinatorold.syntactical
-
-import scala.util.parsing.ast._
-
-//DISCLAIMER: this code is highly experimental!
-  
-/** <p>
- *    This component augments the generic parsers with support for variable binding.
- *  </p>
- *  <p>
- *    Use <code>bind</code> to decorate a parser that parses a binder (e.g.,
- *    the name of a local variable or an argument name in a list of formal
- *    arguments): besides the parser, it requires a fresh <code>Binder</code>
- *    object, which serves as a container for one or more binders with the same
- *    scope. The result of the parser is added to the binder's elements. Note
- *    that semantic equality (<code>equals</code>) is used to link a binder to
- *    its bound occurrences (along with its scope, of course).
- *  </p>
- *  <p>
- *    For example, here's how you'd write a parser (<code>p</code>) for a let
- *    construct (assuming <code>b: Binder[Name]</code>):
- *  </p><pre>
- *   "val" ~! bind(name, b) ~ ":" ~ typeP ~ "=" ~ term ~ "in" ~ in(term, b),</pre>
- *  <p>
- *    This can be read as ``The parser that matches <code>val</code> (and then
- *    does not back-track anymore), a name -- which represents a binder we'll
- *    call <code>b</code> -- a colon, a type, an equals sign, a term, the
- *    keyword <code>in</code> and finally a term where `b' is in scope.''
- *  </p>
- *  <p>
- *    The result of this parser is a nested tuple of depth 3, containing a
- *    Type, a <code>Term</code> and an <code>UnderBinder[Name, Term]</code>.
- *    Note that the binder itself is discarded (the <code>UnderBinder</code>
- *    keeps track of it).
- *  </p>
- *  <p>
- *    <code>newScope</code> makes an empty scope so that you can use
- *    <code>into</code> to pass it to a function that makes a parser
- *    whose bound variables end up in this scope:
- *    In our example, it would be used like this (with <code>b</code> free
- *    in <code>p</code>):
- *  </p><pre>
- *    newScope[Name] into { b => p }</pre>
- *  <p>
- *    Finally, <code>bound(p)</code> constructs a parser that checks that the
- *    result of <code>p</code> is bound by some binder <code>b</code> (i.e.,
- *    <code>b</code> has an element which <code>equals</code> the result of
- *    <code>p</code>) in the current scope (as delineated by 
- *    <code>in(scopeP, b)</code>, where <code>p</code> is called during
- *    `scopeP'). If scoping is indeed respected, <code>bound(p)</code> 
- *    wraps the result of <code>p</code> in a <code>BoundElement</code>.
- *  </p>
- *
- * @author Adriaan Moors
- */
-trait BindingParsers extends Parsers with Binders {
-  /** A shortcut for `success(new Scope[t])'
-   * 
-   * Typically used in combination with the `into' combiner as follows:
-   * <pre>newScope[Name] into { b => 
-   *    "val" ~! bind(name, b) ~ ":" ~ typeP ~ "=" ~ term ~ "in" ~ in(term, b)}</pre>
-   */
-  def newScope[T <: NameElement] = success(new Scope[T])
-
-  def nested[T <: NameElement](s: Scope[T]) = success(s.nested)
-
-  // TODO: make `bind' and `in' methods of Scope?
-  
-  /** Generate a UnitParser that parses a binder
-   *
-   * The result of `binderParser' (a binder) will be added to the binder container `binder',
-   * so that `b' can later be used to refer to the binder parsed by `binderParser' (e.g., in the 
-   *  `in' combinator)
-   *
-   * @param binderParser a parser that parses a binder (e.g., a variable name)
-   * @param scope        a scope that will contain the parsed binder
-   * @return a parser with the same behaviour as `binderParser', except that its result will be 
-   *          added to `scope' and not returned.
-   */ 
-  def bind[bt <: NameElement](binderParser: Parser[bt], scope: Scope[bt]) = new UnitParser {
-    def apply(in: Input): ParseResult[Unit] = { 
-      binderParser(in).map(x => scope.addBinder(x))
-    }
-  }
-   
-  /** <p>
-   *    Parse something that is in the scope of the given binders.
-   *  </p>
-   *  <p>
-   *    During the execution of <code>scopeParser</code>, the binders in
-   *    <code>binder</code> are active: see <code>bound</code> for more
-   *    information. The result of the decorated parser is wrapped in an
-   *    <code>UnderBinder</code>.
-   *  </p>
-   *
-   * @param scopeParser the parser that parses something that is in the scope of `binder'
-   * @param binder      a container of binders, typically populated by `bind'
-   * @return a parser that has the same behaviour as `scopeParser', but whose result is wrapped 
-   *          in an `UnderBinder'
-   */
-  def in[scopeT <% Mappable[scopeT], bt <: NameElement ](scopeParser: Parser[scopeT], scope: Scope[bt]) = new Parser[UnderBinder[bt, scopeT]] {
-    def apply(in: Input): ParseResult[UnderBinder[bt, scopeT]] = inScope(scope){
-      scopeParser(in).map(x => UnderBinder(scope, x))
-    }
-  }
-   
-  /** A parser that checks that there are no unbound variables.
-   *
-   * `bound(p)' succeeds if the element parsed by p is bound by an active binder (see `in')
-   * 
-   * @param boundElementParser a parser that parses an element that must be bound
-   * @return a parser that succeeds if the element parsed by `boundElementParser' was bound,
-   *          wrapping its result in a `BoundElement'
-   */
-  def bound[bt <: NameElement](boundElementParser: Parser[bt]) = 
-    boundElementParser ^? ({case x: NameElement if !findScope(x).isEmpty => BoundElement(x, findScope(x).get)}, (x: bt) => """Unbound variable `"""+x+"""'""")
-   
-
-  private var binderEnv: BinderEnv = EmptyBinderEnv 
-  protected def inScope[bt <: NameElement, res](scope: Scope[bt])(block: => res) :res = {
-    val oldEnv = binderEnv // save old environment
-    
-    // bring binders in the scope in scope
-    for(val b <- scope) binderEnv = binderEnv.extend(b, scope)
-    
-    // return the result of running block (in which these binders are in scope)
-    // before returning, the binderEnv is restored to its old value
-    return_{scope.onEnter; block} andDo {scope.onLeft; binderEnv = oldEnv}
-  }
-
-  protected def findScope[bt <: NameElement](x: bt): Option[Scope[bt]] = binderEnv(x)
-}
diff --git a/src/library/scala/util/parsing/combinatorold/syntactical/StdTokenParsers.scala b/src/library/scala/util/parsing/combinatorold/syntactical/StdTokenParsers.scala
deleted file mode 100644
index 6a3c0cf..0000000
--- a/src/library/scala/util/parsing/combinatorold/syntactical/StdTokenParsers.scala
+++ /dev/null
@@ -1,44 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: StdTokenParsers.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala.util.parsing.combinatorold.syntactical
-
-import scala.util.parsing.syntax._
-
-/** This component provides primitive parsers for the standard tokens defined in `StdTokens'.
-*
-* @author Martin Odersky, Adriaan Moors
- */
-trait StdTokenParsers extends TokenParsers {
-  type Tokens <: StdTokens
-  import lexical.{Keyword, NumericLit, StringLit, Identifier}
-
-  /** A parser which matches a single keyword token.
-   *
-   * @param chars    The character string making up the matched keyword. 
-   * @return a `UnitParser' that matches the given string
-   */
-  implicit def keyword(chars: String): UnitParser = accept(Keyword(chars))
-
-  /** A parser which matches a numeric literal */
-  def numericLit: Parser[String] = 
-    elem("number", _.isInstanceOf[NumericLit]) ^^ (_.chars)
-
-  /** A parser which matches a string literal */
-  def stringLit: Parser[String] = 
-    elem("string literal", _.isInstanceOf[StringLit]) ^^ (_.chars)
-
-  /** A parser which matches an identifier */
-  def ident: Parser[String] = 
-    elem("identifier", _.isInstanceOf[Identifier]) ^^ (_.chars)
-}
-
-
diff --git a/src/library/scala/util/parsing/combinatorold/syntactical/TokenParsers.scala b/src/library/scala/util/parsing/combinatorold/syntactical/TokenParsers.scala
deleted file mode 100644
index 3ba337a..0000000
--- a/src/library/scala/util/parsing/combinatorold/syntactical/TokenParsers.scala
+++ /dev/null
@@ -1,64 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: TokenParsers.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala.util.parsing.combinatorold.syntactical
-
-/** <p>
- *    This is the core component for token-based parsers. 
- *  </p>
- *  <p>
- *    @requires lexical a component providing the tokens consumed by the
- *    parsers in this component.
- *  </p>
- *
- *  @author Martin Odersky, Adriaan Moors
- */
-trait TokenParsers extends Parsers {
-  /** Tokens is the abstract type of the `Token's consumed by the parsers in this component*/
-  type Tokens <: scala.util.parsing.syntax.Tokens
-  
-  /** lexical is the component responsible for consuming some basic kind of
-   *  input (usually character-based) and turning it into the tokens
-   *  understood by these parsers.
-   */
-  val lexical: Tokens
-
-  /** The input-type for these parsers*/
-  type Elem = lexical.Token
-  
-  /** <p>
-   *    A parser generator delimiting whole phrases (i.e. programs).
-   *  </p>
-   *  <p>
-   *    <code>phrase(p)</code> succeeds if <code>p</code> succeeds and
-   *    no input is left over after <code>p</code>.
-   *  </p>
-   *
-   *  @param p the parser that must consume all input for the resulting parser
-   *           to succeed.
-   *  @return  a parser that has the same result as `p', but that only succeeds
-   *           if <code>p</code> consumed all the input.
-   */
-  def phrase[t](p: Parser[t]) = new Parser[t] {
-    def apply(in: Input) = p(in) match {
-      case s @ Success(out, in1) if in1.atEnd => s
-      case s @ Success(out, in1) => Failure("end of input expected", in1)
-      case f @ Failure(_, in1) => in1.first match {
-        case lexical.ErrorToken(msg)  => Failure(msg, in1)
-        case lexical.EOF  => Failure("unexpected end of input", in1)
-        case t  => Failure("unexpected token "+t, in1)        
-      }
-      case f => f
-    }
-  }       
-}
-
-
diff --git a/src/library/scala/util/parsing/combinatorold/testing/Tester.scala b/src/library/scala/util/parsing/combinatorold/testing/Tester.scala
deleted file mode 100644
index 548def7..0000000
--- a/src/library/scala/util/parsing/combinatorold/testing/Tester.scala
+++ /dev/null
@@ -1,45 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-package scala.util.parsing.combinatorold.testing
-
-import scala.util.parsing.combinatorold.lexical.Lexical
-import scala.util.parsing.combinatorold.syntactical.TokenParsers
-
-/** <p>
- *    Facilitates testing a given parser on various input strings.
- *  </p>
- *  <p>
- *    Example use:
- *  </p><pre>
- *    <b>val</b> syntactic = <b>new</b> MyParsers</pre>
- *  <p>
- *    and
- *  </p><pre>
- *    <b>val</b> parser = syntactic.term</pre>
- *  <p>
- *    (if MyParsers extends TokenParsers with a parser called `term')
- *  </p>
- *
- * @author Martin Odersky, Adriaan Moors
- */
-abstract class Tester {
-
-  val syntactic: TokenParsers { val lexical: Lexical }
-  val parser: syntactic.Parser[Any]
-
-
-  /** Scans a String (using a `syntactic.lexical.Scanner'), parses it
-   *  using <code>phrase(parser)</code>, and  prints the input and the
-   *  parsed result to the console. 
-   */
-  def test(in: String) {
-    Console.println("\nin : "+in)
-    Console.println(syntactic.phrase[Any](parser)(new syntactic.lexical.Scanner(in)))
-  }
-}
diff --git a/src/library/scala/util/parsing/input/CharArrayPosition.scala b/src/library/scala/util/parsing/input/CharArrayPosition.scala
deleted file mode 100644
index 0d6ae51..0000000
--- a/src/library/scala/util/parsing/input/CharArrayPosition.scala
+++ /dev/null
@@ -1,45 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: CharArrayPosition.scala 16894 2009-01-13 13:09:41Z cunei $
-
-package scala.util.parsing.input
-
-/** <code>CharArrayPosition</code> implements the general <code>Position</code>
- *  class for documents represented by an <code>Array</code> of `char's.
- *
- *  @param source The contents of the document in which this position is contained
- *  @param line   The line number of the position (1-based)
- *  @param columm The column number of the position (1-based)
- *
- * @author Martin Odersky, Adriaan Moors 
- * @deprecated; use OffsetPosition instead
- */
- at deprecated
-class CharArrayPosition(val source: Array[Char], val line: Int, val column: Int) extends Position {
-
-  // TODO: this could be implemented more high-level: 
-  // return the string representation of the sub-array of source that starts
-  // after the (lnum-1)'ed '\n' up to (but not including) the (lnum)'ed '\n' 
-  protected def lineContents = {
-    var i = 0
-    var l = 1
-    while (i < source.length && l < line) {
-      while (i < source.length && source(i) != '\n') i += 1
-      i += 1
-      l += 1
-    }
-    var chars = new StringBuffer
-    while (i < source.length && source(i) != '\n') {
-      chars append source(i)
-      i += 1
-    }
-    chars.toString
-  }
-}
-    
diff --git a/src/library/scala/util/parsing/input/CharArrayReader.scala b/src/library/scala/util/parsing/input/CharArrayReader.scala
index e251a7b..05a10de 100644
--- a/src/library/scala/util/parsing/input/CharArrayReader.scala
+++ b/src/library/scala/util/parsing/input/CharArrayReader.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2006-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: CharArrayReader.scala 16894 2009-01-13 13:09:41Z cunei $
 
 package scala.util.parsing.input
 
@@ -16,9 +15,6 @@ package scala.util.parsing.input
  */
 object CharArrayReader {
   final val EofCh = '\032'
-
-  /** @deprecated  This should probably be LF instead? */
-  @deprecated final val CR = '\015'
 }
 
 /** A character array reader reads a stream of characters (keeping track of their positions) 
diff --git a/src/library/scala/util/parsing/input/CharSequenceReader.scala b/src/library/scala/util/parsing/input/CharSequenceReader.scala
index efd88c1..8c98965 100644
--- a/src/library/scala/util/parsing/input/CharSequenceReader.scala
+++ b/src/library/scala/util/parsing/input/CharSequenceReader.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2006-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: CharSequenceReader.scala 16894 2009-01-13 13:09:41Z cunei $
 
 package scala.util.parsing.input
 
diff --git a/src/library/scala/util/parsing/input/NoPosition.scala b/src/library/scala/util/parsing/input/NoPosition.scala
index 3d76454..6e89125 100644
--- a/src/library/scala/util/parsing/input/NoPosition.scala
+++ b/src/library/scala/util/parsing/input/NoPosition.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2006-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: NoPosition.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala.util.parsing.input
diff --git a/src/library/scala/util/parsing/input/OffsetPosition.scala b/src/library/scala/util/parsing/input/OffsetPosition.scala
index 90166a4..a07e6fd 100644
--- a/src/library/scala/util/parsing/input/OffsetPosition.scala
+++ b/src/library/scala/util/parsing/input/OffsetPosition.scala
@@ -1,6 +1,6 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2006-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
diff --git a/src/library/scala/util/parsing/input/PagedSeqReader.scala b/src/library/scala/util/parsing/input/PagedSeqReader.scala
index 43f2ce9..a30798c 100644
--- a/src/library/scala/util/parsing/input/PagedSeqReader.scala
+++ b/src/library/scala/util/parsing/input/PagedSeqReader.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2006-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: PagedSeqReader.scala 14416 2008-03-19 01:17:25Z mihaylov $
 
 package scala.util.parsing.input
 
diff --git a/src/library/scala/util/parsing/input/Position.scala b/src/library/scala/util/parsing/input/Position.scala
index 0f88db0..553aa53 100644
--- a/src/library/scala/util/parsing/input/Position.scala
+++ b/src/library/scala/util/parsing/input/Position.scala
@@ -1,6 +1,6 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2006-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
@@ -53,7 +53,7 @@ trait Position {
    *<pre>    List(this, is, a, line, from, the, document)
    *                  ^</pre>
    */
-  def longString = lineContents+"\n"+(" " * (column - 1))+"^"
+  def longString = lineContents+"\n"+lineContents.take(column-1).map{x => if (x == '\t') x else ' ' } + "^"
 
   /** Compare this position to another, by first comparing their line numbers,
    * and then -- if necessary -- using the columns to break a tie.
diff --git a/src/library/scala/util/parsing/input/Positional.scala b/src/library/scala/util/parsing/input/Positional.scala
index 090b525..63929df 100644
--- a/src/library/scala/util/parsing/input/Positional.scala
+++ b/src/library/scala/util/parsing/input/Positional.scala
@@ -1,6 +1,6 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2006-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
diff --git a/src/library/scala/util/parsing/input/Reader.scala b/src/library/scala/util/parsing/input/Reader.scala
index a64f9b8..dedc43e 100644
--- a/src/library/scala/util/parsing/input/Reader.scala
+++ b/src/library/scala/util/parsing/input/Reader.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2006-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Reader.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala.util.parsing.input
diff --git a/src/library/scala/util/parsing/input/StreamReader.scala b/src/library/scala/util/parsing/input/StreamReader.scala
index 6173b4e..4b3bd69 100644
--- a/src/library/scala/util/parsing/input/StreamReader.scala
+++ b/src/library/scala/util/parsing/input/StreamReader.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2006-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: StreamReader.scala 16894 2009-01-13 13:09:41Z cunei $
 
 package scala.util.parsing.input
 
diff --git a/src/library/scala/util/parsing/json/JSON.scala b/src/library/scala/util/parsing/json/JSON.scala
index 94fe8d9..7a0a974 100644
--- a/src/library/scala/util/parsing/json/JSON.scala
+++ b/src/library/scala/util/parsing/json/JSON.scala
@@ -1,15 +1,17 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2006-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: JSON.scala 16881 2009-01-09 16:28:11Z cunei $
 
 
 package scala.util.parsing.json
+import scala.util.parsing.combinator._
+import scala.util.parsing.combinator.syntactical._
+import scala.util.parsing.combinator.lexical._
 
 /** 
  * This object provides a simple interface to the JSON parser class. The default conversion
@@ -38,9 +40,34 @@ object JSON extends Parser {
    * array it will be be a list of individual elements.
    *
    * @param input the given JSON string.
-   * @return      an optional list of of elements. 
+   * @return      an optional list of of elements.
+   *
+   * @deprecated Use parseFull or parseRaw as needed.
+   */
+  def parse(input: String): Option[List[Any]] = parseRaw(input).map(unRaw).flatMap({
+    case l : List[_] => Some(l)
+    case _ => None
+  })
+  
+  /**
+   * This method converts "raw" results back into the original, deprecated
+   * form.
+   */
+  private def unRaw (in : Any) : Any = in match {
+    case JSONObject(obj) => obj.map({ case (k,v) => (k,unRaw(v))}).toList
+    case JSONArray(list) => list.map(unRaw)
+    case x => x
+  }
+
+  /**
+   * Parse the given JSON string and return a list of elements. If the
+   * string is a JSON object it will be a JSONObject. If it's a JSON 
+   * array it will be be a JSONArray.
+   *
+   * @param input the given JSON string.
+   * @return      an optional JSONType element.
    */
-  def parse(input: String): Option[List[Any]] =
+  def parseRaw(input : String) : Option[JSONType] = 
     phrase(root)(new lexical.Scanner(input)) match {
       case Success(result, _) => Some(result)
       case _ => None
@@ -55,7 +82,7 @@ object JSON extends Parser {
    * @return      an optional list or map.
    */
   def parseFull(input: String): Option[Any] =
-    parse(input) match {
+    parseRaw(input) match {
       case Some(data) => Some(resolveType(data))
       case None => None
     }
@@ -64,20 +91,12 @@ object JSON extends Parser {
    * A utility method to resolve a parsed JSON list into objects or 
    * arrays. See the parse method for details.
    */
-  def resolveType(input: List[_]): Any = {
-    var objMap = Map[String, Any]()
-    
-    if (input.forall { 
-      case (key: String, value: List[_]) =>
-        objMap += (key -> resolveType(value))
-        true
-      case (key : String, value : Any) =>
-        objMap += (key -> value)
-        true
-      case _ => false
-    }) objMap
-    else
-      input
+  def resolveType(input: Any): Any = input match {
+    case JSONObject(data) => data.transform {
+      case (k,v) => resolveType(v)
+    }
+    case JSONArray(data) => data.map(resolveType)
+    case x => x
   }
   
   /**
diff --git a/src/library/scala/util/parsing/json/Lexer.scala b/src/library/scala/util/parsing/json/Lexer.scala
index 736571c..347d317 100644
--- a/src/library/scala/util/parsing/json/Lexer.scala
+++ b/src/library/scala/util/parsing/json/Lexer.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2006-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Lexer.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala.util.parsing.json
@@ -83,7 +82,7 @@ class Lexer extends StdLexical with ImplicitConversions {
 
   private def unicodeBlock = hexDigit ~ hexDigit ~ hexDigit ~ hexDigit ^^ {
     case a ~ b ~ c ~ d =>
-      new String(io.UTF8Codec.encode(Integer.parseInt(List(a, b, c, d) mkString "", 16)), "UTF-8")
+      new String(Array(Integer.parseInt(List(a, b, c, d) mkString "", 16)), 0, 1)
   }
 
   //private def lift[T](f: String => T)(xs: List[Any]): T = f(xs mkString "")
diff --git a/src/library/scala/util/parsing/json/Parser.scala b/src/library/scala/util/parsing/json/Parser.scala
index 5943b22..b4e0e82 100644
--- a/src/library/scala/util/parsing/json/Parser.scala
+++ b/src/library/scala/util/parsing/json/Parser.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2006-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Parser.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala.util.parsing.json
@@ -16,6 +15,31 @@ import scala.util.parsing.combinator.syntactical._
 import scala.util.parsing.combinator.lexical._
 
 /**
+ *  A marker class for the JSON result types.
+ * 
+ *  @author Derek Chen-Becker <"java"+ at +"chen-becker"+"."+"org">
+ */
+sealed abstract class JSONType
+
+/**
+ *  Represents a JSON Object (map). 
+ *  @author Derek Chen-Becker <"java"+ at +"chen-becker"+"."+"org">
+ */
+case class JSONObject (obj : Map[Any,Any]) extends JSONType {
+  override def toString = "{" + obj.map({ case (k,v) => k + " : " + v }).mkString(", ") + "}"
+}
+
+/**
+ *  Represents a JSON Array (list). 
+ *  @author Derek Chen-Becker <"java"+ at +"chen-becker"+"."+"org">
+ */
+case class JSONArray (list : List[Any]) extends JSONType {
+  override def toString = "[" + list.mkString(", ") + "]"
+}
+
+/**
+ *  The main JSON Parser.
+ * 
  *  @author Derek Chen-Becker <"java"+ at +"chen-becker"+"."+"org">
  */
 class Parser extends StdTokenParsers with ImplicitConversions {
@@ -40,8 +64,8 @@ class Parser extends StdTokenParsers with ImplicitConversions {
   
   // Define the grammar
   def root       = jsonObj | jsonArray
-  def jsonObj    = "{" ~> repsep(objEntry, ",") <~ "}"
-  def jsonArray  = "[" ~> repsep(value, ",") <~ "]"
+  def jsonObj    = "{" ~> repsep(objEntry, ",") <~ "}" ^^ { case vals : List[_] => JSONObject(Map(vals : _*)) }
+  def jsonArray  = "[" ~> repsep(value, ",") <~ "]" ^^ { case vals : List[_] => JSONArray(vals) }
   def objEntry   = stringVal ~ (":" ~> value) ^^ { case x ~ y => (x, y) }
   def value: Parser[Any] = (jsonObj | jsonArray | number | "true" ^^^ true | "false" ^^^ false | "null" ^^^ null | stringVal)
   def stringVal  = accept("string", { case lexical.StringLit(n) => n} )
diff --git a/src/library/scala/util/parsing/syntax/StdTokens.scala b/src/library/scala/util/parsing/syntax/StdTokens.scala
deleted file mode 100644
index 842a9b7..0000000
--- a/src/library/scala/util/parsing/syntax/StdTokens.scala
+++ /dev/null
@@ -1,35 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-package scala.util.parsing.syntax
-
-/** This component provides the standard `Token's for a simple, Scala-like language. 
- *
- * @author Martin Odersky, Adriaan Moors
- */
-trait StdTokens extends Tokens {
-  /** The class of keyword tokens */
-  case class Keyword(chars: String) extends Token {
-    override def toString = "`"+chars+"'"
-  }
-
-  /** The class of numeric literal tokens */
-  case class NumericLit(chars: String) extends Token {
-    override def toString = chars
-  }
-
-  /** The class of string literal tokens */
-  case class StringLit(chars: String) extends Token {
-    override def toString = "\""+chars+"\""
-  }    
-
-  /** The class of identifier tokens */
-  case class Identifier(chars: String) extends Token {
-    override def toString = "identifier "+chars
-  }
-}
diff --git a/src/library/scala/util/parsing/syntax/Tokens.scala b/src/library/scala/util/parsing/syntax/Tokens.scala
deleted file mode 100644
index 2a77fc0..0000000
--- a/src/library/scala/util/parsing/syntax/Tokens.scala
+++ /dev/null
@@ -1,38 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2006-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-package scala.util.parsing.syntax
-
-/** This component provides the notion of `Token', the unit of information that is passed from lexical
- * parsers in the `Lexical' component to the parsers in the `TokenParsers' component.
- *
- * @author Martin Odersky, Adriaan Moors
- */
-trait Tokens {
-  /** Objects of this type are produced by a lexical parser or ``scanner'', and consumed by a parser
-   * {@see scala.util.parsing.combinator.syntactical.TokenParsers}.
-   */
-  abstract class Token {
-    def chars: String
-  }
-  
-  /** A class of error tokens. Error tokens are used to communicate
-   *  errors detected during lexical analysis 
-   */
-  case class ErrorToken(msg: String) extends Token {
-    def chars = "*** error: "+msg
-  }
-
-  /** A class for end-of-file tokens */
-  case object EOF extends Token {
-    def chars = "<eof>"
-  }
-
-  /** This token is produced by a scanner {@see Scanner} when scanning failed. */
-  def errorToken(msg: String): Token = new ErrorToken(msg)  
-}
diff --git a/src/library/scala/util/parsing/syntax/package.scala b/src/library/scala/util/parsing/syntax/package.scala
new file mode 100644
index 0000000..9dc909c
--- /dev/null
+++ b/src/library/scala/util/parsing/syntax/package.scala
@@ -0,0 +1,19 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2006-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |                                         **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+package scala.util.parsing
+
+import scala.util.parsing.combinator.token
+
+/** If deprecating the whole package worked, that's what would best
+ *  be done, but it doesn't (yet) so it isn't.
+ */
+package object syntax {
+  @deprecated("Moved to scala.util.parsing.combinator.token") type Tokens = token.Tokens
+  @deprecated("Moved to scala.util.parsing.combinator.token") type StdTokens = token.StdTokens
+}
diff --git a/src/library/scala/util/regexp/Base.scala b/src/library/scala/util/regexp/Base.scala
index acc52bc..dfc579f 100644
--- a/src/library/scala/util/regexp/Base.scala
+++ b/src/library/scala/util/regexp/Base.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Base.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala.util.regexp
@@ -16,46 +15,43 @@ package scala.util.regexp
  *  @author  Burak Emir
  *  @version 1.0
  */
-abstract class Base {
-
+abstract class Base
+{
   type _regexpT <: RegExp
 
   abstract class RegExp {
     val isNullable: Boolean
   }
-
-  /** Alt( R,R,R* ) */
-  case class Alt(rs: _regexpT*)  extends RegExp {
-
-    // check rs \in R,R,R*
-    // @todo: flattening
-    if ({ val it = rs.elements; !it.hasNext || {it.next; !it.hasNext }})
-      throw new SyntaxError("need at least 2 branches in Alt");
-
-    final val isNullable = {
-      val it = rs.elements
-      while (it.hasNext && it.next.isNullable) {}
-      !it.hasNext
-    }
+  
+  object Alt {
+    /** Alt( R,R,R* ) */
+    def apply(rs: _regexpT*) = 
+      if (rs.size < 2) throw new SyntaxError("need at least 2 branches in Alt")
+      else new Alt(rs: _*)
+    // Can't enforce that statically without changing the interface
+    // def apply(r1: _regexpT, r2: _regexpT, rs: _regexpT*) = new Alt(Seq(r1, r2) ++ rs: _*)
+    def unapplySeq(x: Alt) = Some(x.rs)
   }
 
-  case class Sequ(rs: _regexpT*) extends RegExp {
-    // @todo: flattening
-    // check rs \in R,R* 
-    if ({ val it = rs.elements; !it.hasNext }) 
-      throw new SyntaxError("need at least 1 item in Sequ")
-
-    final val isNullable = {
-      val it = rs.elements
-      while (it.hasNext && it.next.isNullable) {}
-      !it.hasNext
-    }
+  class Alt private (val rs: _regexpT*) extends RegExp {
+    final val isNullable = rs exists (_.isNullable)
+  }
+  
+  object Sequ {
+    /** Sequ( R,R* ) */
+    def apply(rs: _regexpT*) = if (rs.isEmpty) Eps else new Sequ(rs: _*)
+    def unapplySeq(x: Sequ) = Some(x.rs)  
+  }
+  
+  class Sequ private (val rs: _regexpT*) extends RegExp {
+    final val isNullable = rs forall (_.isNullable)
   }
 
   case class Star(r: _regexpT) extends RegExp {
     final lazy val isNullable = true
   }
 
+  // The empty Sequ.
   case object Eps extends RegExp {
     final lazy val isNullable = true
     override def toString() = "Eps"
@@ -66,11 +62,4 @@ abstract class Base {
     final val isNullable = r1.isNullable
     def r = r1
   }
-
-  final def mkSequ(rs: _regexpT *): RegExp =
-    if (!rs.elements.hasNext)
-      Eps
-    else
-      Sequ(rs:_*)
-
 }
diff --git a/src/library/scala/util/regexp/PointedHedgeExp.scala b/src/library/scala/util/regexp/PointedHedgeExp.scala
index 8c2d866..83b9dbf 100644
--- a/src/library/scala/util/regexp/PointedHedgeExp.scala
+++ b/src/library/scala/util/regexp/PointedHedgeExp.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: PointedHedgeExp.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala.util.regexp
diff --git a/src/library/scala/util/regexp/SyntaxError.scala b/src/library/scala/util/regexp/SyntaxError.scala
index 940cb8e..367d2d1 100644
--- a/src/library/scala/util/regexp/SyntaxError.scala
+++ b/src/library/scala/util/regexp/SyntaxError.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: SyntaxError.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala.util.regexp
diff --git a/src/library/scala/util/regexp/WordExp.scala b/src/library/scala/util/regexp/WordExp.scala
index a544a93..411a588 100644
--- a/src/library/scala/util/regexp/WordExp.scala
+++ b/src/library/scala/util/regexp/WordExp.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: WordExp.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala.util.regexp
diff --git a/src/library/scala/volatile.scala b/src/library/scala/volatile.scala
index abe821e..7c9d972 100644
--- a/src/library/scala/volatile.scala
+++ b/src/library/scala/volatile.scala
@@ -1,14 +1,16 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: volatile.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala
 
+import annotation.target._
+
+ at field
 class volatile extends StaticAnnotation
diff --git a/src/library/scala/xml/Atom.scala b/src/library/scala/xml/Atom.scala
index 815c15f..c9c68a4 100644
--- a/src/library/scala/xml/Atom.scala
+++ b/src/library/scala/xml/Atom.scala
@@ -1,13 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Atom.scala 16894 2009-01-13 13:09:41Z cunei $
-
 
 package scala.xml
 
@@ -18,26 +16,25 @@ package scala.xml
  *  @param text the text contained in this node, may not be <code>null</code>.
  */
 @serializable
-class Atom[+A](val data: A) extends SpecialNode {  
-
-  data.asInstanceOf[AnyRef] match {
-    case null => new IllegalArgumentException("cannot construct Atom(null)")
-    case _ =>
+class Atom[+A](val data: A) extends SpecialNode
+{  
+  if (data == null)
+    throw new IllegalArgumentException("cannot construct Atom(null)")
+
+  override def basisForHashCode: Seq[Any] = Seq(data)
+  override def strict_==(other: Equality) = other match {
+    case x: Atom[_] => data == x.data
+    case _          => false
   }
-  final override def typeTag$: Int = -1
-
-  /** the constant "#PCDATA"
-   */
-  def label = "#PCDATA"
-
-  override def equals(x: Any) = x match {
-    case s:Atom[_] => data == s.data 
-    case _         => false
+  override def canEqual(other: Any) = other match {
+    case _: Atom[_] => true
+    case _          => false
   }
 
-  /** hashcode for this Text */
-  override def hashCode() = 
-    data.hashCode()
+  final override def doCollectNamespaces = false
+  final override def doTransform         = false
+  
+  def label = "#PCDATA"
 
   /** Returns text, with some characters escaped according to the XML
    *  specification.
@@ -45,7 +42,7 @@ class Atom[+A](val data: A) extends SpecialNode {
    *  @param  sb ...
    *  @return ...
    */
-  def toString(sb: StringBuilder) =
+  def buildString(sb: StringBuilder) =
     Utility.escape(data.toString(), sb)
 
   override def text: String = data.toString()
diff --git a/src/library/scala/xml/Attribute.scala b/src/library/scala/xml/Attribute.scala
new file mode 100644
index 0000000..7a4aaec
--- /dev/null
+++ b/src/library/scala/xml/Attribute.scala
@@ -0,0 +1,91 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+package scala.xml
+
+/** Attribute defines the interface shared by both
+ *  PrefixedAttribute and UnprefixedAttribute
+ */
+
+object Attribute {
+  def unapply(x: Attribute) = x match {
+    case PrefixedAttribute(_, key, value, next) => Some(key, value, next)
+    case UnprefixedAttribute(key, value, next)  => Some(key, value, next)
+    case _                                      => None
+  }
+
+  /** Convenience functions which choose Un/Prefixedness appropriately */
+  def apply(key: String, value: Seq[Node], next: MetaData): Attribute =
+    new UnprefixedAttribute(key, value, next)
+    
+  def apply(pre: String, key: String, value: String, next: MetaData): Attribute =
+    if (pre == null || pre == "") new UnprefixedAttribute(key, value, next)
+    else new PrefixedAttribute(pre, key, value, next)
+    
+  def apply(pre: String, key: String, value: Seq[Node], next: MetaData): Attribute =
+    if (pre == null || pre == "") new UnprefixedAttribute(key, value, next)
+    else new PrefixedAttribute(pre, key, value, next)
+    
+  def apply(pre: Option[String], key: String, value: Seq[Node], next: MetaData): Attribute =
+    pre match {
+      case None     => new UnprefixedAttribute(key, value, next)
+      case Some(p)  => new PrefixedAttribute(p, key, value, next)
+    }  
+}
+
+abstract trait Attribute extends MetaData
+{
+  def pre: String        // will be null if unprefixed
+  val key: String
+  val value: Seq[Node]
+  val next: MetaData
+  
+  def apply(key: String): Seq[Node]
+  def apply(namespace: String, scope: NamespaceBinding, key: String): Seq[Node]
+  def copy(next: MetaData): Attribute
+
+  def remove(key: String) =
+    if (!isPrefixed && this.key == key) next
+    else copy(next remove key)
+  
+  def remove(namespace: String, scope: NamespaceBinding, key: String) =
+    if (isPrefixed && this.key == key && (scope getURI pre) == namespace) next
+    else next.remove(namespace, scope, key)
+
+  def isPrefixed: Boolean = pre != null
+  def getNamespace(owner: Node): String
+  def wellformed(scope: NamespaceBinding): Boolean = {
+    val arg = if (isPrefixed) scope getURI pre else null    
+    (next(arg, scope, key) == null) && (next wellformed scope)
+  }
+  
+  override def canEqual(other: Any) = other match {
+    case _: Attribute   => true
+    case _              => false
+  }
+  override def strict_==(other: Equality) = other match {
+    case x: Attribute   => (pre == x.pre) && (key == x.key) && (value sameElements x.value)
+    case _              => false
+  }
+  override def basisForHashCode = List(pre, key, value)
+  
+  /** Appends string representation of only this attribute to stringbuffer.
+   */
+  def toString1(sb: StringBuilder) {
+    if (value == null)
+      return
+    if (isPrefixed)
+      sb append pre append ':'
+    
+    sb append key append '='
+    val sb2 = new StringBuilder()
+    Utility.sequenceToXML(value, TopScope, sb2, true)    
+    Utility.appendQuoted(sb2.toString(), sb)
+  }
+}
diff --git a/src/library/scala/xml/Comment.scala b/src/library/scala/xml/Comment.scala
index 3e6811b..afca506 100644
--- a/src/library/scala/xml/Comment.scala
+++ b/src/library/scala/xml/Comment.scala
@@ -1,44 +1,33 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Comment.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala.xml
 
+
 /** The class <code>Comment</code> implements an XML node for comments.
  *
  * @author Burak Emir
  * @param text the text contained in this node, may not contain "--"
  */
-case class Comment(commentText: String) extends SpecialNode {  
-
-  final override def typeTag$: Int = -3
-
-  if (commentText.indexOf("--") != -1) 
-    throw new IllegalArgumentException("text containts \"--\"")
-
-  /** structural equality */
-  override def equals(x: Any): Boolean = x match {
-    case Comment(x) => x.equals(commentText)
-    case _ => false
-  }
-
-  /** the constant "#REM" */
+case class Comment(commentText: String) extends SpecialNode
+{  
   def label = "#REM"
-
-  /** hashcode for this Comment */
-  override def hashCode() = commentText.hashCode()
-
   override def text = ""
+  final override def doCollectNamespaces = false
+  final override def doTransform         = false
+
+  if (commentText contains "--")
+    throw new IllegalArgumentException("text contains \"--\"")
 
   /** Appends "<!-- text -->" to this string buffer.
    */
-  override def toString(sb: StringBuilder) =
-    sb.append("<!--").append(commentText).append("-->")
+  override def buildString(sb: StringBuilder) =
+    sb append ("<!--" + commentText + "-->")
 }
diff --git a/src/library/scala/xml/Document.scala b/src/library/scala/xml/Document.scala
index e7786b5..0f9a567 100644
--- a/src/library/scala/xml/Document.scala
+++ b/src/library/scala/xml/Document.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Document.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala.xml
@@ -19,6 +18,7 @@ package scala.xml
  *  @author  Burak Emir
  *  @version 1.0, 26/04/2005
  */
+ at serializable @SerialVersionUID(-2289320563321795109L)
 class Document extends NodeSeq with pull.XMLEvent {
 
   /** An ordered list of child information items, in document
@@ -85,5 +85,9 @@ class Document extends NodeSeq with pull.XMLEvent {
   // methods for NodeSeq
 
   def theSeq: Seq[Node] = this.docElem
-
+  
+  override def canEqual(other: Any) = other match {
+    case _: Document  => true
+    case _            => false
+  }
 }
diff --git a/src/library/scala/xml/Elem.scala b/src/library/scala/xml/Elem.scala
index 12fb0fc..f5ef300 100644
--- a/src/library/scala/xml/Elem.scala
+++ b/src/library/scala/xml/Elem.scala
@@ -1,13 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Elem.scala 16881 2009-01-09 16:28:11Z cunei $
-
 
 package scala.xml
 
@@ -19,16 +17,17 @@ package scala.xml
  * Copyright 2008 Google Inc. All Rights Reserved.
  * @author Burak Emir <bqe at google.com>
  */
-object Elem {
-
+object Elem
+{
   def apply(prefix: String,label: String, attributes: MetaData, scope: NamespaceBinding, child: Node*) = 
     new Elem(prefix,label,attributes,scope,child:_*)
 
-  def unapplySeq(n:Node) = if (n.isInstanceOf[SpecialNode] || n.isInstanceOf[Group]) None else
-    Some(Tuple5(n.prefix, n.label, n.attributes, n.scope, n.child))
-  
-
+  def unapplySeq(n: Node) = n match {
+    case _: SpecialNode | _: Group  => None
+    case _                          => Some((n.prefix, n.label, n.attributes, n.scope, n.child))
+  }
 }
+
 /** The case class <code>Elem</code> extends the <code>Node</code> class,
  *  providing an immutable data object representing an XML element.
  *
@@ -41,49 +40,53 @@ object Elem {
  * Copyright 2008 Google Inc. All Rights Reserved.
  * @author Burak Emir <bqe at google.com>
  */
-// "val" is redundant for non-overriding arguments
- at serializable class Elem(override val prefix: String,
-                val label: String,
-                override val attributes: MetaData,
-                override val scope: NamespaceBinding,
-                val child: Node*) extends Node {
-
-  if ((null != prefix) && 0 == prefix.length())
+ at serializable
+class Elem(
+  override val prefix: String,
+  val label: String,
+  override val attributes: MetaData,
+  override val scope: NamespaceBinding,
+  val child: Node*)
+extends Node
+{
+  final override def doCollectNamespaces = true
+  final override def doTransform         = true
+    
+  if (prefix == "")
     throw new IllegalArgumentException("prefix of zero length, use null instead")
 
-  if (null == scope)
-    throw new IllegalArgumentException("scope is null, try xml.TopScope for empty scope")
+  if (scope == null)
+    throw new IllegalArgumentException("scope is null, use xml.TopScope for empty scope")
 
   //@todo: copy the children, 
   //  setting namespace scope if necessary
   //  cleaning adjacent text nodes if necessary
 
-  final override def typeTag$: Int = 0
-
-  override def hashCode(): Int =
-    Utility.hashCode(prefix, label, attributes.hashCode(), scope.hashCode(), child)
+  override def basisForHashCode: Seq[Any] = prefix :: label :: attributes :: child.toList
 
   /** Returns a new element with updated attributes, resolving namespace uris from this element's scope.
    *  See MetaData.update for details.
    *  @param  updates MetaData with new and updated attributes
    *  @return a new symbol with updated attributes
    */
-  final def %(updates: MetaData): Elem = 
-    Elem(prefix, 
-         label, 
-         MetaData.update(attributes, scope, updates), 
-         scope,
-         child:_*)
-
-   /** Returns concatenation of <code>text(n)</code> for each child
-    *  <code>n</code>.
-    */
-   override def text = {
-     val sb = new StringBuilder()
-     val it = child.elements
-     while (it.hasNext)
-       sb.append(it.next.text)
-     sb.toString()
-   }
+  final def %(updates: MetaData): Elem =
+    copy(attributes = MetaData.update(attributes, scope, updates))
+  
+  /** Returns a copy of this element with any supplied arguments replacing
+   *  this element's value for that field.
+   *
+   *  @return a new symbol with updated attributes
+   */
+  def copy(
+    prefix: String = this.prefix,
+    label: String = this.label,
+    attributes: MetaData = this.attributes,
+    scope: NamespaceBinding = this.scope,
+    child: Seq[Node] = this.child.toSeq
+  ): Elem = Elem(prefix, label, attributes, scope, child: _*)
 
+  /** Returns concatenation of <code>text(n)</code> for each child
+   *  <code>n</code>.
+   */
+  override def text = child map (_.text) mkString
 }
diff --git a/src/library/scala/xml/EntityRef.scala b/src/library/scala/xml/EntityRef.scala
index 652b8e8..d7a1aed 100644
--- a/src/library/scala/xml/EntityRef.scala
+++ b/src/library/scala/xml/EntityRef.scala
@@ -1,16 +1,17 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: EntityRef.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala.xml
 
+
+
 /** The class <code>EntityRef</code> implements an XML node for entity
  *  references.
  *
@@ -19,30 +20,17 @@ package scala.xml
  * @param   text the text contained in this node.
  */
 case class EntityRef(entityName: String) extends SpecialNode {
-
-  final override def typeTag$: Int = -5
-
-  /** structural equality */
-  override def equals(x: Any): Boolean = x match {
-    case EntityRef(x) => x.equals(entityName)
-    case _ => false
-  }
-
-  /** the constant "#ENTITY"
-   */
+  final override def doCollectNamespaces = false
+  final override def doTransform         = false
   def label = "#ENTITY"
 
-  override def hashCode() = entityName.hashCode()
-
-  /** ...
-   */
   override def text = entityName match {
     case "lt"   => "<"
     case "gt"   => ">"
     case "amp"  => "&"
     case "apos" => "'"
     case "quot" => "\""
-    case _ => val sb = new StringBuilder(); toString(sb).toString() 
+    case _      => Utility.sbToString(buildString)
   }
 
   /** Appends "& entityName;" to this string buffer.
@@ -50,7 +38,7 @@ case class EntityRef(entityName: String) extends SpecialNode {
    *  @param  sb the string buffer.
    *  @return the modified string buffer <code>sb</code>.
    */
-  override def toString(sb: StringBuilder) = 
+  override def buildString(sb: StringBuilder) = 
     sb.append("&").append(entityName).append(";")
 
 }
diff --git a/src/library/scala/xml/Equality.scala b/src/library/scala/xml/Equality.scala
new file mode 100644
index 0000000..67be5f8
--- /dev/null
+++ b/src/library/scala/xml/Equality.scala
@@ -0,0 +1,115 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+package scala.xml
+
+/** In an attempt to contain the damage being inflicted on
+ *  consistency by the ad hoc equals methods spread around
+ *  xml, the logic is centralized and all the xml classes
+ *  go through the xml.Equality trait.  There are two forms
+ *  of xml comparison.
+ *
+ *  1) def strict_==(other: xml.Equality)
+ *
+ *  This one tries to honor the little things like symmetry
+ *  and hashCode contracts.  The equals method routes all
+ *  comparisons through this.
+ *
+ *  2) xml_==(other: Any)
+ *
+ *  This one picks up where strict_== leaves off.  It might
+ *  declare any two things equal.
+ *
+ *  As things stood, the logic not only made a mockery of
+ *  the collections equals contract, but also laid waste to
+ *  that of case classes.
+ *
+ *  Among the obstacles to sanity are/were:
+ *
+ *    Node extends NodeSeq extends Seq[Node]
+ *    MetaData extends Iterable[MetaData]
+ *    The hacky "Group" xml node which throws exceptions
+ *      with wild abandon, so don't get too close
+ *    Rampant asymmetry and impossible hashCodes
+ *    Most classes claiming to be equal to "String" if
+ *      some specific stringification of it was the same.
+ *      String was never going to return the favor.
+ */
+
+object Equality {
+  def asRef(x: Any): AnyRef = x.asInstanceOf[AnyRef]
+  
+  /** Note - these functions assume strict equality has already failed.
+   */
+  def compareBlithely(x1: AnyRef, x2: String): Boolean = x1 match {
+    case x: Atom[_]   => x.data == x2
+    case x: NodeSeq   => x.text == x2
+    case _            => false
+  }
+  def compareBlithely(x1: AnyRef, x2: Node): Boolean = x1 match {
+    case x: NodeSeq if x.length == 1  => x2 == x(0)
+    case _                            => false
+  }
+  def compareBlithely(x1: AnyRef, x2: AnyRef): Boolean = {
+    if (x1 == null || x2 == null)
+      return (x1 eq x2)
+
+    x2 match {
+      case s: String  => compareBlithely(x1, s)
+      case n: Node    => compareBlithely(x1, n)
+      case _          => false
+    }
+  }
+}
+import Equality._
+
+private[xml]
+trait Equality extends scala.Equals {
+  def basisForHashCode: Seq[Any]
+  def strict_==(other: Equality): Boolean
+  def strict_!=(other: Equality) = !strict_==(other)
+
+  private def hashOf(x: Any) = if (x == null) 1 else x.##
+  
+  /** We insist we're only equal to other xml.Equality implementors,
+   *  which heads off a lot of inconsistency up front.
+   */
+  override def canEqual(other: Any): Boolean = other match {
+    case x: Equality    => true
+    case _              => false
+  }
+
+  /** It's be nice to make these final, but there are probably
+   *  people out there subclassing the XML types, especially when
+   *  it comes to equals.  However WE at least can pretend they
+   *  are final since clearly individual classes cannot be trusted
+   *  to maintain a semblance of order.
+   */
+  override def hashCode() = basisForHashCode match {
+    case Nil      => 0
+    case x :: xs  => hashOf(x) * 41 + (xs map hashOf).foldLeft(0)(_ * 7 + _)
+  }
+  override def equals(other: Any) = doComparison(other, false)
+  final def xml_==(other: Any)    = doComparison(other, true)
+  final def xml_!=(other: Any)    = !xml_==(other)
+
+  /** The "blithe" parameter expresses the caller's unconcerned attitude
+   *  regarding the usual constraints on equals.  The method is thereby
+   *  given carte blanche to declare any two things equal.
+   */
+  private def doComparison(other: Any, blithe: Boolean) = {
+    val strictlyEqual = other match {
+      case x: AnyRef if this eq x => true
+      case x: Equality            => (x canEqual this) && (this strict_== x)
+      case _                      => false
+    }
+    
+    strictlyEqual || (blithe && compareBlithely(this, asRef(other)))
+  }
+}
+
diff --git a/src/library/scala/xml/Group.scala b/src/library/scala/xml/Group.scala
index 2286d34..5b893c5 100644
--- a/src/library/scala/xml/Group.scala
+++ b/src/library/scala/xml/Group.scala
@@ -1,13 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Group.scala 16894 2009-01-13 13:09:41Z cunei $
-
 
 package scala.xml
 
@@ -17,55 +15,27 @@ package scala.xml
  *  @version 1.0
  */
 @serializable
-case class Group(val nodes: Seq[Node]) extends Node {
-
+final case class Group(val nodes: Seq[Node]) extends Node {
   override def theSeq = nodes
-
-  /** structural equality */
-  override def equals(x: Any) = x match {
-    case z:Group     => (length == z.length) && sameElements(z)
-    case z:Node      => (length == 1) && z == apply(0)
-    case z:Seq[_]    => sameElements(z)
-    case z:String    => text == z
-    case _           => false
+  
+  override def canEqual(other: Any) = other match {
+    case x: Group => true
+    case _        => false
   }
-
-  /**
-   * @throws Predef.UnsupportedOperationException (always)
-   */
-  final def label =
-    throw new UnsupportedOperationException("class Group does not support method 'label'")
-
-  /**
-   * @throws Predef.UnsupportedOperationException (always)
-   */
-  final override def attributes =
-    throw new UnsupportedOperationException("class Group does not support method 'attributes'")
-
-  /**
-   * @throws Predef.UnsupportedOperationException (always)
-   */
-  final override def namespace =
-    throw new UnsupportedOperationException("class Group does not support method 'namespace'")
-
-  /**
-   * @throws Predef.UnsupportedOperationException (always)
-   */
-  final override def child =
-    throw new UnsupportedOperationException("class Group does not support method 'child'")
-
-  /**
-   * @throws Predef.UnsupportedOperationException (always)
-   */
-  def toString(sb: StringBuilder) =
-    throw new UnsupportedOperationException(
-      "class Group does not support method toString(StringBuilder)")
-
-  override def text = { // same impl as NodeSeq
-    val sb = new StringBuilder()
-    val it = elements
-    while (it.hasNext)
-      sb.append(it.next.text)
-    sb.toString()
+  override def strict_==(other: Equality) = other match {
+    case Group(xs)  => nodes sameElements xs
+    case _          => false
   }
+  override def basisForHashCode = nodes
+  
+  /** Since Group is very much a hack it throws an exception if you
+   *  try to do anything with it.
+   */
+  private def fail(msg: String) = throw new UnsupportedOperationException("class Group does not support method '%s'" format msg)
+  
+  def label                           = fail("label")
+  override def attributes             = fail("attributes")
+  override def namespace              = fail("namespace")
+  override def child                  = fail("child")
+  def buildString(sb: StringBuilder)  = fail("toString(StringBuilder)")
 }
diff --git a/src/library/scala/xml/HasKeyValue.scala b/src/library/scala/xml/HasKeyValue.scala
index 9191a5a..1ec117a 100644
--- a/src/library/scala/xml/HasKeyValue.scala
+++ b/src/library/scala/xml/HasKeyValue.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: HasKeyValue.scala 16894 2009-01-13 13:09:41Z cunei $
 
 package scala.xml
 
@@ -20,6 +19,7 @@ package scala.xml
  *
  *  @author Burak Emir
  */
+ at deprecated("Use UnprefixedAttribute's extractor")
 class HasKeyValue(key: String) {
   def unapplySeq(x: MetaData): Option[Seq[Node]] = x.get(key)
 }
diff --git a/src/library/scala/xml/MalformedAttributeException.scala b/src/library/scala/xml/MalformedAttributeException.scala
index e8a79bc..a85995d 100644
--- a/src/library/scala/xml/MalformedAttributeException.scala
+++ b/src/library/scala/xml/MalformedAttributeException.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: MalformedAttributeException.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala.xml
diff --git a/src/library/scala/xml/MetaData.scala b/src/library/scala/xml/MetaData.scala
index 16dea8e..0a5cb47 100644
--- a/src/library/scala/xml/MetaData.scala
+++ b/src/library/scala/xml/MetaData.scala
@@ -1,16 +1,18 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: MetaData.scala 16894 2009-01-13 13:09:41Z cunei $
-
 
 package scala.xml
 
+import Utility.sbToString
+import annotation.tailrec
+
+
 /**
  * Copyright 2008 Google Inc. All Rights Reserved.
  * @author Burak Emir <bqe at google.com>
@@ -23,32 +25,23 @@ object MetaData {
    * the attributes in new_tail, but does not guarantee to preserve the relative order of attribs.
    * Duplicates can be removed with normalize.
    */
+  @tailrec
   def concatenate(attribs: MetaData, new_tail: MetaData): MetaData =
-    if (attribs eq Null)
-      new_tail
-    else
-      concatenate(attribs.next, attribs.copy(new_tail)) // tail-recursive
+    if (attribs eq Null) new_tail
+    else concatenate(attribs.next, attribs copy new_tail)
 
   /**
    * returns normalized MetaData, with all duplicates removed and namespace prefixes resolved to
    *  namespace URIs via the given scope.
    */
-  def normalize(attribs: MetaData, scope: NamespaceBinding): MetaData = {
-    import collection.mutable.HashSet
-    def iterate(md: MetaData, normalized_attribs: MetaData, map: HashSet[String]): MetaData = {
-      if (md eq Null)
-        normalized_attribs
-      else {
-        val universal_key = getUniversalKey(md, scope)
-        if (map.contains(universal_key))
-          iterate(md.next, normalized_attribs, map)
-        else {
-          map += universal_key
-          iterate(md.next, md.copy(normalized_attribs), map)
-        } 
-      }
+  def normalize(attribs: MetaData, scope: NamespaceBinding): MetaData = {    
+    def iterate(md: MetaData, normalized_attribs: MetaData, set: Set[String]): MetaData = {
+      lazy val key = getUniversalKey(md, scope)
+      if (md eq Null) normalized_attribs
+      else if (set(key)) iterate(md.next, normalized_attribs, set)
+      else iterate(md.next, md copy normalized_attribs, set + key)
     }
-    iterate(attribs, Null, new HashSet[String])
+    iterate(attribs, Null, Set())
   }
  
   /**
@@ -79,29 +72,17 @@ object MetaData {
  * @author Burak Emir <bqe at google.com>
  */
 @serializable
-abstract class MetaData extends Collection[MetaData] {
-
-  /** updates this MetaData with the MetaData given as argument. All attributes that occur in updates
-   *  are part of the resulting MetaData. If an unprefixed attribute occurs in both this instance and 
-   *  updates, only the one in updates is part of the result (avoiding duplicates). However, for 
-   *  prefixed attributes no duplicate-detection is attempted, the method 
-   *  append(updates: MetaData, scope:NamespaceBinding) should be used instead.
-   *
-   *  @param updates MetaData with new attributes and updated attributes
-   *  @return a new MetaData instance that contains the combined attributes of this and updates
-   */
-  def append(updates: MetaData): MetaData =
-    MetaData.update(this, TopScope, updates)
-
-  /** updates this MetaData with the MetaData given as argument. All attributes that occur in updates
+abstract class MetaData extends Iterable[MetaData] with Equality
+{
+  /** Updates this MetaData with the MetaData given as argument. All attributes that occur in updates
    *  are part of the resulting MetaData. If an attribute occurs in both this instance and 
    *  updates, only the one in updates is part of the result (avoiding duplicates). For prefixed
-   *  attributes, namespaces are resolved using the given scope.
+   *  attributes, namespaces are resolved using the given scope, which defaults to TopScope.
    *
    *  @param updates MetaData with new and updated attributes
    *  @return a new MetaData instance that contains old, new and updated attributes
    */
-  def append(updates: MetaData, scope: NamespaceBinding): MetaData =
+  def append(updates: MetaData, scope: NamespaceBinding = TopScope): MetaData =
     MetaData.update(this, scope, updates)
 
   /**
@@ -132,13 +113,6 @@ abstract class MetaData extends Collection[MetaData] {
    */
   def apply(namespace_uri:String, scp:NamespaceBinding, k:String): Seq[Node]
 
-  /**
-   *  @param m ...
-   *  @return  <code>true</code> iff ...
-   */
-  def containedIn1(m: MetaData): Boolean =
-    m.equals1(this) || containedIn1(m.next)
-
   /** returns a copy of this MetaData item with next field set to argument.
    *
    *  @param next ...
@@ -157,39 +131,24 @@ abstract class MetaData extends Collection[MetaData] {
 
   def isPrefixed: Boolean
 
-  /** deep equals method */
-  override def equals(that: Any) =
-    that match {
-      case m: MetaData =>
-        var res = (this.length == m.length) && (this.hashCode() == m.hashCode())
-        val it = this.elements
-        while (res && it.hasNext) { res = it.next.containedIn1(m) }
-        res
-      case _ =>
-        false
-    }
-
-  /** returns an iterator on attributes */
-  def elements: Iterator[MetaData] = new Iterator[MetaData] {
-    var x: MetaData = MetaData.this
-    def hasNext = Null != x
-    def next = {
-      val y = x
-      x = x.next
-      y
-    }
+  override def canEqual(other: Any) = other match {
+    case _: MetaData  => true
+    case _            => false
   }
-  def size : Int = 1 + {
-    if (Null == next) 0 else next.size
+  override def strict_==(other: Equality) = other match {
+    case m: MetaData  => this.toSet == m.toSet
+    case _            => false
   }
+  def basisForHashCode: Seq[Any] = List(this.toSet)
 
-  /** shallow equals method */
-  def equals1(that: MetaData): Boolean
+  /** Returns an iterator on attributes */
+  def iterator: Iterator[MetaData] = Iterator.single(this) ++ next.iterator  
+  override def size: Int = 1 + iterator.length
 
   /** filters this sequence of meta data */
-  override def filter(f: MetaData => Boolean): MetaData = {
-    if (f(this)) copy(next filter f) else next filter f
-  }
+  override def filter(f: MetaData => Boolean): MetaData =
+    if (f(this)) copy(next filter f)
+    else next filter f
 
   /** returns key of this MetaData item */
   def key: String
@@ -197,8 +156,18 @@ abstract class MetaData extends Collection[MetaData] {
   /** returns value of this MetaData item */
   def value: Seq[Node]
 
-  /** maps this sequence of meta data */
-  def map(f: MetaData => Text): List[Text] = f(this)::(next map f)
+  /** Returns a String containing "prefix:key" if the first key is
+   *  prefixed, and "key" otherwise.
+   */
+  def prefixedKey = this match {
+    case x: Attribute if x.isPrefixed => x.pre + ":" + key
+    case _                            => key
+  }
+  
+  /** Returns a Map containing the attributes stored as key/value pairs.
+   */
+  def asAttrMap: Map[String, String] =
+    iterator map (x => (x.prefixedKey, x.value.text)) toMap
 
   /** returns Null or the next MetaData item */
   def next: MetaData
@@ -209,16 +178,12 @@ abstract class MetaData extends Collection[MetaData] {
    * @param  key
    * @return value in Some(Seq[Node]) if key is found, None otherwise
    */
-  final def get(key: String): Option[Seq[Node]] = apply(key) match {
-    case null => None
-    case x    => Some(x)
-  }
+  final def get(key: String): Option[Seq[Node]] = Option(apply(key))
 
   /** same as get(uri, owner.scope, key) */
   final def get(uri: String, owner: Node, key: String): Option[Seq[Node]] =
     get(uri, owner.scope, key)
 
-
   /** gets value of qualified (prefixed) attribute with given key.
    *
    * @param  uri namespace of key
@@ -227,32 +192,19 @@ abstract class MetaData extends Collection[MetaData] {
    * @return value as Some[Seq[Node]] if key is found, None otherwise
    */
   final def get(uri: String, scope: NamespaceBinding, key: String): Option[Seq[Node]] =
-    apply(uri, scope, key) match {
-      case null => None
-      case x    => Some(x)
-    }
-
-  override def hashCode(): Int
+    Option(apply(uri, scope, key))
 
-  def toString1(): String = {
-    val sb = new StringBuilder()
-    toString1(sb)
-    sb.toString()
-  }
+  def toString1(): String = sbToString(toString1)
 
-  //appends string representations of single attribute to StringBuilder
-  def toString1(sb:StringBuilder): Unit
+  // appends string representations of single attribute to StringBuilder
+  def toString1(sb: StringBuilder): Unit
 
-  override def toString(): String = {
-    val sb = new StringBuilder()
-    toString(sb)
-    sb.toString()
-  }
+  override def toString(): String = sbToString(buildString)
 
-  def toString(sb: StringBuilder): StringBuilder = {
+  def buildString(sb: StringBuilder): StringBuilder = {
     sb.append(' ')
     toString1(sb)
-    next.toString(sb)
+    next.buildString(sb)
   }
 
   /**
@@ -265,7 +217,7 @@ abstract class MetaData extends Collection[MetaData] {
    *  @param key ...
    *  @return    ...
    */
-  def remove(key:String): MetaData
+  def remove(key: String): MetaData
 
   /**
    *  @param namespace ...
@@ -283,5 +235,4 @@ abstract class MetaData extends Collection[MetaData] {
    */
   final def remove(namespace: String, owner: Node, key: String): MetaData =
     remove(namespace, owner.scope, key)
-
 }
diff --git a/src/library/scala/xml/NamespaceBinding.scala b/src/library/scala/xml/NamespaceBinding.scala
index 1985e8c..3b29f2e 100644
--- a/src/library/scala/xml/NamespaceBinding.scala
+++ b/src/library/scala/xml/NamespaceBinding.scala
@@ -1,17 +1,17 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: NamespaceBinding.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala.xml
 
-import Predef._
+import Utility.sbToString
+
 
 /** The class <code>NamespaceBinding</code> represents namespace bindings
  *  and scopes. The binding for the default namespace is treated as a null
@@ -21,51 +21,43 @@ import Predef._
  *  @author  Burak Emir
  *  @version 1.0
  */
- at serializable
-class NamespaceBinding(val prefix: String,
-                       val uri: String,
-                       val parent: NamespaceBinding) extends AnyRef {
-
-  private val serialVersionUID = 0 - 2518644165573446725L
-
-  if (null != prefix && 0 == prefix.length())
+ at SerialVersionUID(0 - 2518644165573446725L)
+case class NamespaceBinding(prefix: String, uri: String, parent: NamespaceBinding) extends AnyRef with Equality
+{
+  if (prefix == "")
     throw new IllegalArgumentException("zero length prefix not allowed")
 
   def getURI(_prefix: String): String =
-    if (prefix == _prefix) uri else parent.getURI(_prefix)
+    if (prefix == _prefix) uri else parent getURI _prefix
 
-  /** Returns some prefix that is mapped to the prefix.
+  /** Returns some prefix that is mapped to the URI.
    *
-   *  @param _uri
-   *  @return
+   * @param _uri the input URI
+   * @return the prefix that is mapped to the input URI, or null
+   * if no prefix is mapped to the URI.
    */
   def getPrefix(_uri: String): String =
-    if (_uri == uri) uri else parent.getURI(_uri)
+    if (_uri == uri) prefix else parent getPrefix _uri
 
-  override def toString(): String = {
-    val sb = new StringBuilder()
-    toString(sb, TopScope)
-    sb.toString()
+  override def toString(): String = sbToString(buildString(_, TopScope))
+  override def canEqual(other: Any) = other match {
+    case _: NamespaceBinding  => true
+    case _                    => false
   }
-
-  def toString(stop: NamespaceBinding): String = {
-    val sb = new StringBuilder()
-    toString(sb, stop)
-    sb.toString()
+  override def strict_==(other: Equality) = other match {
+    case x: NamespaceBinding  => (prefix == x.prefix) && (uri == x.uri) && (parent == x.parent)
+    case _                    => false
   }
+  def basisForHashCode: Seq[Any] = List(prefix, uri, parent)
 
-  def toString(sb: StringBuilder, stop: NamespaceBinding): Unit = {
-    if (this ne stop) { // contains?
-      sb.append(" xmlns")
-      if (prefix ne null) {
-        sb.append(':').append(prefix)
-      }
-      sb.append('=')
-      .append('"')
-      .append(uri)
-      .append('"');
-      parent.toString(sb, stop) // copy(ignore)
-    }
-  }
+  def buildString(stop: NamespaceBinding): String = sbToString(buildString(_, stop))
+  def buildString(sb: StringBuilder, stop: NamespaceBinding): Unit = {
+    if (this eq stop) return    // contains?
 
+    val s = " xmlns%s=\"%s\"".format(
+      (if (prefix != null) ":" + prefix else ""),
+      (if (uri != null) uri else "")
+    )
+    parent.buildString(sb append s, stop) // copy(ignore)
+  }
 }
diff --git a/src/library/scala/xml/Node.scala b/src/library/scala/xml/Node.scala
index 08459eb..fd67dda 100644
--- a/src/library/scala/xml/Node.scala
+++ b/src/library/scala/xml/Node.scala
@@ -1,13 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Node.scala 16894 2009-01-13 13:09:41Z cunei $
-
 
 package scala.xml
 
@@ -18,15 +16,13 @@ package scala.xml
  * @version 1.0
  */
 object Node {
-
   /** the constant empty attribute sequence */
   final def NoAttributes: MetaData = Null
 
   /** the empty namespace */
   val EmptyNamespace = ""
 
-  def unapplySeq(n: Node) = Some(Tuple3(n.label, n.attributes, n.child))
-
+  def unapplySeq(n: Node) = Some((n.label, n.attributes, n.child))
 }
 
 /**
@@ -46,7 +42,11 @@ abstract class Node extends NodeSeq {
 
   /** used internally. Atom/Molecule = -1 PI = -2 Comment = -3 EntityRef = -5
    */ 
-  def typeTag$: Int = 0
+  def isAtom = this.isInstanceOf[Atom[_]]
+  
+  /** The logic formerly found in typeTag$, as best I could infer it. */
+  def doCollectNamespaces = true  // if (tag >= 0) DO collect namespaces
+  def doTransform         = true  // if (tag < 0) DO NOT transform
 
   /**
    *  method returning the namespace bindings of this node. by default, this
@@ -107,6 +107,10 @@ abstract class Node extends NodeSeq {
    * @return all children of this node
    */
   def child: Seq[Node]
+  
+  /** Children which do not stringify to "" (needed for equality)
+   */
+  def nonEmptyChildren: Seq[Node] = child filterNot (_.toString == "")
 
   /**
    * Descendant axis (all descendants of this node, not including node itself) 
@@ -120,32 +124,24 @@ abstract class Node extends NodeSeq {
    * includes all text nodes, element nodes, comments and processing instructions.
    */
   def descendant_or_self: List[Node] = this :: descendant
-
-  /**
-   * Returns true if x is structurally equal to this node. Compares prefix,
-   * label, attributes and children.
-   *
-   * @param x ...
-   * @return  <code>true</code> if ..
-   */
-  override def equals(x: Any): Boolean = x match {
-    case g:Group => false
-    case that: Node =>
-      ((that.prefix == this.prefix )
-       &&(that.label == this.label )
-       &&(that.attributes ==  this.attributes)
-       && that.child.sameElements(this.child)) // sameElements
-    case _ => false
+  
+  override def canEqual(other: Any) = other match {
+    case x: Group   => false
+    case x: Node    => true
+    case _          => false
+  }
+  override def basisForHashCode: Seq[Any] = prefix :: label :: attributes :: nonEmptyChildren.toList
+  override def strict_==(other: Equality) = other match {
+    case _: Group => false
+    case x: Node  =>
+      (prefix == x.prefix) &&
+      (label == x.label) &&
+      (attributes == x.attributes) &&
+      // (scope == x.scope)               // note - original code didn't compare scopes so I left it as is.
+      (nonEmptyChildren sameElements x.nonEmptyChildren)
+    case _        =>
+      false
   }
-
-  /** <p>
-   *    Returns a hashcode. The default implementation here calls only
-   *    super.hashcode (which is the same as for objects). A more useful
-   *    implementation can be invoked by calling 
-   *  <code>Utility.hashCode(pre, label, attributes.hashCode(), child)</code>.
-   *  </p>
-   */
-  override def hashCode(): Int = super.hashCode
 
   // implementations of NodeSeq methods
 
@@ -160,15 +156,15 @@ abstract class Node extends NodeSeq {
    * @param stripComment if true, strips comment nodes from result
    * @return ...
    */
-  def toString(stripComment: Boolean): String =
-    Utility.toXML(this, stripComment)
+  def buildString(stripComments: Boolean): String =
+    Utility.toXML(this, stripComments = stripComments).toString
 
   /**
    * Same as <code>toString(false)</code>.
    *
    * @see <code><a href="#toString">toString(Boolean)</a></code>
    */
-  override def toString(): String = toString(false)
+  override def toString(): String = buildString(false)
 
   /**
    * Appends qualified name of this node to <code>StringBuilder</code>.
@@ -196,9 +192,10 @@ abstract class Node extends NodeSeq {
    *  Martin to Burak: to do: if you make this method abstract, the compiler will now
    *  complain if there's no implementation in a subclass. Is this what we want? Note that
    *  this would break doc/DocGenator and doc/ModelToXML, with an error message like:
-doc\DocGenerator.scala:1219: error: object creation impossible, since there is a deferred declaration of method text in class Node of type => String which is not implemented in a subclass
-    new SpecialNode {
-    ^
-   */
+   * {{{
+   * doc\DocGenerator.scala:1219: error: object creation impossible, since there is a deferred declaration of method text in class Node of type => String which is not implemented in a subclass
+   * new SpecialNode {
+   * ^
+   * }}} */
   override def text: String = super.text
 }
diff --git a/src/library/scala/xml/NodeBuffer.scala b/src/library/scala/xml/NodeBuffer.scala
index 928ac32..aeff072 100644
--- a/src/library/scala/xml/NodeBuffer.scala
+++ b/src/library/scala/xml/NodeBuffer.scala
@@ -1,13 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: NodeBuffer.scala 16894 2009-01-13 13:09:41Z cunei $
-
 
 package scala.xml
 
@@ -38,24 +36,14 @@ class NodeBuffer extends scala.collection.mutable.ArrayBuffer[Node] {
    * @return  this nodebuffer
    */
   def &+(o: Any): NodeBuffer = {
-    o match { 
-      case null | _:Unit | Text("")=>
-	// ignore
-
-      case it:Iterator[_] =>
-        while (it.hasNext) 
-          this &+ it.next
-
-      case n:Node =>
-        super.+(n)
-
-      case ns:Iterable[_] =>
-        this &+ ns.elements
-
-      case d =>
-        super.+(new Atom(d))
+    o match {
+      case null | _: Unit | Text("")  => // ignore
+      case it: Iterator[_]            => it foreach &+
+      case n: Node                    => super.+=(n)
+      case ns: Iterable[_]            => this &+ ns.iterator
+      case ns: Array[_]               => this &+ ns.iterator
+      case d                          => super.+=(new Atom(d))
     }
-    this 
+    this
   }
-
 }
diff --git a/src/library/scala/xml/NodeSeq.scala b/src/library/scala/xml/NodeSeq.scala
index 2c31588..e59de20 100644
--- a/src/library/scala/xml/NodeSeq.scala
+++ b/src/library/scala/xml/NodeSeq.scala
@@ -1,16 +1,18 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: NodeSeq.scala 16881 2009-01-09 16:28:11Z cunei $
 
 
 package scala.xml
 
+import collection.{ mutable, immutable, generic, SeqLike }
+import mutable.{ Builder, ListBuffer }
+import generic.{ CanBuildFrom }
 
 /** This object ...
  *
@@ -18,11 +20,18 @@ package scala.xml
  *  @version 1.0
  */
 object NodeSeq {
-  final val Empty = new NodeSeq { def theSeq = Nil }
+  final val Empty = fromSeq(Nil)
   def fromSeq(s: Seq[Node]): NodeSeq = new NodeSeq {
     def theSeq = s
   }
-  implicit def view(s: Seq[Node]): NodeSeq = fromSeq(s)
+  type Coll = NodeSeq
+  implicit def canBuildFrom: CanBuildFrom[Coll, Node, NodeSeq] = 
+    new CanBuildFrom[Coll, Node, NodeSeq] { 
+      def apply(from: Coll) = newBuilder 
+      def apply() = newBuilder 
+    }
+  def newBuilder: Builder[Node, NodeSeq] = new ListBuffer[Node] mapResult fromSeq
+  implicit def seqToNodeSeq(s: Seq[Node]): NodeSeq = fromSeq(s)
 }
 
 /** This class implements a wrapper around <code>Seq[Node]</code> that
@@ -31,178 +40,114 @@ object NodeSeq {
  *  @author  Burak Emir
  *  @version 1.0
  */
-abstract class NodeSeq extends Seq[Node] {
-  import NodeSeq.view // import view magic for NodeSeq wrappers
+abstract class NodeSeq extends immutable.Seq[Node] with SeqLike[Node, NodeSeq] with Equality {
+  import NodeSeq.seqToNodeSeq // import view magic for NodeSeq wrappers
+
+  /** Creates a list buffer as builder for this class */
+  override protected[this] def newBuilder = NodeSeq.newBuilder
+
   def theSeq: Seq[Node]
   def length = theSeq.length
-  override def elements = theSeq.elements
-  def apply(i: Int): Node = theSeq.apply(i)
-
+  override def iterator = theSeq.iterator
+  
+  def apply(i: Int): Node = theSeq(i)
   def apply(f: Node => Boolean): NodeSeq = filter(f)
 
-  /** structural equality */
-  override def equals(x: Any) = x match {
-    case z:Node      => (length == 1) && z == apply(0)
-    case z:Seq[_]    => sameElements(z)
-    case z:String    => text == z
-    case _           => false;
+  def xml_sameElements[A](that: Iterable[A]): Boolean = {
+    val these = this.iterator
+    val those = that.iterator
+    while (these.hasNext && those.hasNext)
+      if (these.next xml_!= those.next)
+        return false
+
+    !these.hasNext && !those.hasNext
+  }
+  def basisForHashCode: Seq[Any] = theSeq
+  override def canEqual(other: Any) = other match {
+    case _: NodeSeq   => true
+    case _            => false
+  }
+  override def strict_==(other: Equality) = other match {
+    case x: NodeSeq => (length == x.length) && (theSeq sameElements x.theSeq)
+    case _          => false
   }
 
-  /** Projection function. Similar to XPath, use <code>this \ "foo"</code>
-   *  to get a list of all elements of this sequence that are labelled with
-   *  <code>"foo"</code>. Use <code>\ "_"</code> as a wildcard. Use 
-   *  <code>ns \ "@foo"</code> to get the unprefixed attribute "foo". 
-   *  Use <code>ns \ "@{uri}foo"</code> to get the prefixed attribute 
-   *  "pre:foo" whose prefix "pre" is resolved to the namespace "uri". 
-   *  For attribute projections, the resulting NodeSeq attribute values are
-   *  wrapped in a Group.
-   *  There is no support for searching a prefixed attribute by
-   *  its literal prefix.
+  /** Projection function, which returns  elements of `this` sequence based on the string `that`. Use:
+   *   - `this \ "foo"` to get a list of all elements that are labelled with `"foo"`;
+   *   - `\ "_"` to get a list of all elements (wildcard);
+   *   - `ns \ "@foo"` to get the unprefixed attribute `"foo"`;
+   *   - `ns \ "@{uri}foo"` to get the prefixed attribute `"pre:foo"` whose prefix `"pre"` is resolved to the
+   *     namespace `"uri"`.
+   *
+   *  For attribute projections, the resulting [[scala.xml.NodeSeq]] attribute values are wrapped in a
+   *  [[scala.xml.Group]].
+   *
+   *  There is no support for searching a prefixed attribute by its literal prefix.
+   *
    *  The document order is preserved.
    *
    *  @param that ...
    *  @return     ...
    */
-  def \(that: String): NodeSeq = that match {
-    case "_" =>
-      var zs: List[Node] = Nil
-      val it = this.elements
-      while (it.hasNext) {
-        val x = it.next
-        val jt = x.child.elements
-        while (jt.hasNext) {
-          val y = jt.next
-          if (y.typeTag$ != -1)
-            zs = y::zs
+  def \(that: String): NodeSeq = {
+    def fail = throw new IllegalArgumentException(that)
+    def atResult = {
+      lazy val y = this(0)
+      val attr = 
+        if (that.length == 1) fail
+        else if (that(1) == '{') {
+          val i = that indexOf '}'
+          if (i == -1) fail                  
+          val (uri, key) = (that.substring(2,i), that.substring(i+1, that.length()))
+          if (uri == "" || key == "") fail
+          else y.attribute(uri, key)
         }
+        else y.attribute(that drop 1)
+        
+      attr match {
+        case Some(x)  => Group(x)
+        case _        => NodeSeq.Empty
       }
-      NodeSeq.fromSeq(zs.reverse)
-
-    case _ if (that.charAt(0) == '@') && (this.length == 1) =>
-      if (that.length() == 1)
-        throw new IllegalArgumentException(that)
-      if (that.charAt(1) == '{') {
-        val i = that.indexOf('}')
-        if (i == -1)
-          throw new IllegalArgumentException(that)
-        val (uri, key) = (that.substring(2,i), that.substring(i+1, that.length()))
-        if (uri == "" || key == "")
-          throw new IllegalArgumentException(that)
-        val y = this(0)
-        y.attribute(uri, key) match {
-          case Some(x) => Group(x)
-          case _       => NodeSeq.Empty
-        }
-      } else {
-        val k = that.substring(1)
-        val y = this(0)
-        y.attribute(k) match {
-          case Some(x) => Group(x)
-          case _       => NodeSeq.Empty
-        }
-      }
-
-    case _   =>
-      var zs: List[Node] = Nil
-      val it = this.elements
-      while (it.hasNext) {
-        val x = it.next
-        val jt = x.child.elements
-        while (jt.hasNext) {
-          val y = jt.next
-          if (y.label == that)
-            zs = y::zs
-        }
-      }
-      NodeSeq.fromSeq(zs.reverse)
+    }
+    
+    def makeSeq(cond: (Node) => Boolean) =
+      NodeSeq fromSeq (this flatMap (_.child) filter cond)
+      
+    that match {
+      case ""                                         => fail
+      case "_"                                        => makeSeq(!_.isAtom)
+      case _ if (that(0) == '@' && this.length == 1)  => atResult
+      case _                                          => makeSeq(_.label == that)
+    }
   }
 
-  /** projection function. Similar to XPath, use <code>this \\ 'foo</code>
-   *  to get a list of all elements of this sequence that are labelled with
-   *  <code>"foo"</code>. Use <code>\\ "_"</code> as a wildcard.  Use 
-   *  <code>ns \\ "@foo"</code> to get the unprefixed attribute "foo". 
-   *  Use <code>ns \\ "@{uri}foo"</code> to get each prefixed attribute 
-   *  "pre:foo" whose prefix "pre" is resolved to the namespace "uri". 
-   *  For attribute projections, the resulting NodeSeq attribute values are
-   *  wrapped in a Group.
-   *  There is no support for searching a prefixed attribute by
-   *  its literal prefix.
+  /** Projection function, which returns elements of `this` sequence and of all its subsequences, based on
+   *  the string `that`. Use:
+   *   - `this \\ 'foo` to get a list of all elements that are labelled with `"foo"`;
+   *   - `\\ "_"` to get a list of all elements (wildcard);
+   *   - `ns \\ "@foo"` to get the unprefixed attribute `"foo"`;
+   *   - `ns \\ "@{uri}foo"` to get each prefixed attribute `"pre:foo"` whose prefix `"pre"` is resolved to the
+   *     namespace `"uri"`.
+   *
+   *  For attribute projections, the resulting [[scala.xml.NodeSeq]] attribute values are wrapped in a
+   *  [[scala.xml.Group]].
+   *
+   *  There is no support for searching a prefixed attribute by its literal prefix.
+   *
    *  The document order is preserved.
    *
    *  @param that ...
    *  @return     ...
    */
-  def \\ (that: String): NodeSeq = that match {
-    case "_" =>
-      var zs: List[Node] = Nil
-      val it = this.elements
-      while (it.hasNext) {
-        val x = it.next
-        val jt = x.descendant_or_self.elements
-        while (jt.hasNext) {
-          val y = jt.next
-          if (y.typeTag$ != -1)
-            zs = y::zs
-        }
-      }
-      zs.reverse
-
-    case _ if that.charAt(0) == '@' =>
-      var zs: List[Node] = Nil
-      val it = this.elements
-      while (it.hasNext) {
-        val x = it.next
-        val jt = x.descendant_or_self.elements
-        while (jt.hasNext) {
-          val y = jt.next
-          if (y.typeTag$ != -1) {
-            val kt = (y \ that).elements
-            while (kt.hasNext) {
-              zs = (kt.next)::zs
-            }
-          }
-        }
-      }
-      zs.reverse
-
-    case _ =>
-      var zs: List[Node] = Nil
-      val it = this.elements
-      while (it.hasNext) {
-        val x = it.next
-        val jt = x.descendant_or_self.elements
-        while (jt.hasNext) {
-          val y = jt.next
-          if (y.typeTag$ != -1 && y.label == that)
-            zs = y::zs
-        }
-      }
-    zs.reverse
-  }
-
-  override def toString(): String = theSeq.elements.foldLeft ("") { 
-    (s: String, x: Node) => s + x.toString() 
-  }
-/*
-  def map(f: Node => NodeSeq): NodeSeq = flatMap(f)
-
-  def flatMap(f: Node => NodeSeq): NodeSeq = {
-    val y = toList flatMap { x => f(x).toList }
-    y
-  }
-
-  override def filter(f: Node => Boolean): NodeSeq = {
-    val x = toList filter f
-    x
-  }
-*/
-
-  def text: String = {
-    val sb = new StringBuilder()
-    val it = elements
-    while (it.hasNext) {
-      sb.append(it.next.text)
+  def \\ (that: String): NodeSeq = {
+    def filt(cond: (Node) => Boolean) = this flatMap (_.descendant_or_self) filter cond
+    that match {
+      case "_"                  => filt(!_.isAtom)
+      case _ if that(0) == '@'  => filt(!_.isAtom) flatMap (_ \ that)
+      case _                    => filt(x => !x.isAtom && x.label == that)
     }
-    sb.toString()
   }
+
+  override def toString(): String = theSeq.mkString
+  def text: String                = this map (_.text) mkString
 }
diff --git a/src/library/scala/xml/NodeTraverser.scala b/src/library/scala/xml/NodeTraverser.scala
deleted file mode 100644
index 440c56a..0000000
--- a/src/library/scala/xml/NodeTraverser.scala
+++ /dev/null
@@ -1,37 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: NodeTraverser.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala.xml
-
-/** This class ...
- *
- *  @author  Burak Emir
- *  @version 1.0
- */
-abstract class NodeTraverser extends parsing.MarkupHandler {
-
-  def traverse(n: Node): Unit = n match {
-    case x:ProcInstr =>
-      procInstr(0, x.target, x.text)
-    case x:Comment =>
-      comment(0, x.text)
-    case x:Text =>
-      text(0, x.data)
-    case x:EntityRef =>
-      entityRef(0, x.entityName)
-    case _ =>
-      elemStart(0, n.prefix, n.label, n.attributes, n.scope)
-      for (m <- n.child) traverse(m)
-      elem(0, n.prefix, n.label, n.attributes, n.scope, NodeSeq.fromSeq(n.child))
-      elemEnd(0, n.prefix, n.label)
-  }
-
-}
diff --git a/src/library/scala/xml/Null.scala b/src/library/scala/xml/Null.scala
index e436fad..6ddd50e 100644
--- a/src/library/scala/xml/Null.scala
+++ b/src/library/scala/xml/Null.scala
@@ -1,81 +1,59 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Null.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala.xml
 
-case object Null extends MetaData {
-
-  /** appends given MetaData items to this MetaData list */
-  override def append(m: MetaData): MetaData = m
-
-  override def containedIn1(m: MetaData): Boolean = false
-  
-  /** returns its argument */
-  def copy(next: MetaData) = next
-
-  override def elements = Iterator.empty
+import Utility.{ isNameStart }
 
+/** Essentially, every method in here is a dummy, returning Zero[T].
+ *  It provides a backstop for the unusual collection defined by MetaData,
+ *  sort of a linked list of tails.
+ */
+case object Null extends MetaData {    
+  override def iterator = Iterator.empty
+  override def append(m: MetaData, scope: NamespaceBinding = TopScope): MetaData = m
   override def filter(f: MetaData => Boolean): MetaData = this
 
-  /** returns null */
+  def copy(next: MetaData) = next
   def getNamespace(owner: Node) = null
 
-  final override def hasNext = false
-
-  final override def length = 0
-
-  final override def length(i: Int) = i
-
-  def isPrefixed = false
-
-  /** deep equals method */
-  override def equals(that: Any) = that match {
-    case m: MetaData => m.length == 0
-    case _ => false
-  }
-
-  def equals1(that:MetaData) = that.length == 0
-
+  override def hasNext = false
+  def next = null
   def key = null
-
   def value = null
+  def isPrefixed = false
 
-  override def map(f: MetaData => Text): List[Text] = Nil
-
-  def next = null
+  override def length = 0
+  override def length(i: Int) = i
+  
+  override def strict_==(other: Equality) = other match {
+    case x: MetaData  => x.length == 0
+    case _            => false
+  }
+  override def basisForHashCode: Seq[Any] = Nil
 
-  /** null */
+  def apply(namespace: String, scope: NamespaceBinding, key: String) = null
   def apply(key: String) = {
-    if(!Parsing.isNameStart (key charAt 0))
+    if (!isNameStart(key.head))
       throw new IllegalArgumentException("not a valid attribute name '"+key+"', so can never match !")
+      
     null
   }
 
-  /** gets value of qualified (prefixed) attribute with given key */
-  def apply(namespace: String, scope: NamespaceBinding, key: String) = null
-
-  override def hashCode(): Int = 0
-
+  def toString1(sb: StringBuilder) = ()
   override def toString1(): String = ""
-
-  //appends string representations of single attribute to StringBuilder
-  def toString1(sb:StringBuilder) = {}
-
   override def toString(): String = ""
 
-  override def toString(sb: StringBuilder): StringBuilder = sb
-
+  override def buildString(sb: StringBuilder): StringBuilder = sb
   override def wellformed(scope: NamespaceBinding) = true
 
   def remove(key: String) = this
-
   def remove(namespace: String, scope: NamespaceBinding, key: String) = this
 }
diff --git a/src/library/scala/xml/PCData.scala b/src/library/scala/xml/PCData.scala
index c2b67d9..76cf233 100644
--- a/src/library/scala/xml/PCData.scala
+++ b/src/library/scala/xml/PCData.scala
@@ -1,4 +1,3 @@
-// $Id: PCData.scala 14241 2008-03-03 14:53:47Z washburn $
 
 package scala.xml
 
@@ -7,25 +6,15 @@ package scala.xml
  *  and is to be preserved as CDATA section in the output.
  */
 case class PCData(_data: String) extends Atom[String](_data) {
-  /* The following code is a derivative work of scala.xml.Text */
   if (null == data)
     throw new IllegalArgumentException("tried to construct PCData with null")
 
-  final override def equals(x: Any) = x match {
-    case s: String  => s.equals(data)
-    case s: Atom[_] => data == s.data
-    case _ => false
-  }
-
   /** Returns text, with some characters escaped according to the XML
    *  specification.
    *
    *  @param  sb ...
    *  @return ...
    */
-  override def toString(sb: StringBuilder) = {
-    sb.append("<![CDATA[")
-    sb.append(data)
-    sb.append("]]>")
-  }
+  override def buildString(sb: StringBuilder) =
+    sb append "<![CDATA[%s]]>".format(data)
 }
diff --git a/src/library/scala/xml/Parsing.scala b/src/library/scala/xml/Parsing.scala
deleted file mode 100644
index 0b99328..0000000
--- a/src/library/scala/xml/Parsing.scala
+++ /dev/null
@@ -1,105 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: Parsing.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala.xml
-
-
-/** The object <code>Parsing</code> ...
- *
- *  @author  Burak Emir
- *  @version 1.0
- *
- *  @deprecated use either <code>parsing.TokenTests</code> or
- *              <code>Utilty</code> (helper functions for parsing XML fragments).
- */
-object Parsing {
-  
-  /** <pre>(#x20 | #x9 | #xD | #xA)</pre> */
-  final def isSpace(ch: Char): Boolean = ch match {
-    case '\u0009' | '\u000A' | '\u000D' | '\u0020' => true
-    case _                                         => false
-  }
-
-  /** <pre>(#x20 | #x9 | #xD | #xA)+</pre> */
-  final def isSpace(cs: Seq[Char]): Boolean = {
-    val it = cs.elements
-    it.hasNext && it.forall { isSpace }
-  }
-
-  /** <pre>NameChar ::= Letter | Digit | '.' | '-' | '_' | ':' 
-   *             | CombiningChar | Extender</pre>
-   *
-   * see [4] and Appendix B of XML 1.0 specification
-   */
-  def isNameChar(ch: Char) = isNameStart(ch) || (ch match {
-    case '.' | '-' | ':' => true
-    case _ => java.lang.Character.getType(ch).asInstanceOf[Byte] match {
-      case java.lang.Character.COMBINING_SPACING_MARK => true  // Mc
-      case java.lang.Character.ENCLOSING_MARK => true          // Me
-      case java.lang.Character.NON_SPACING_MARK => true        // Mn
-      case java.lang.Character.MODIFIER_LETTER => true         // Lm
-      case java.lang.Character.DECIMAL_DIGIT_NUMBER => true    // Nd
-      case _ => false
-    }
-  });
-
-  /** <pre>NameStart ::= ( Letter | '_' )</pre>
-   *  where Letter means in one of the Unicode general 
-   *  categories { Ll, Lu, Lo, Lt, Nl }
-   *
-   *  We do not allow a name to start with ':'.
-   *  see [3] and Appendix B of XML 1.0 specification
-   */ 
-  def isNameStart(ch: Char) = 
-    java.lang.Character.getType(ch).asInstanceOf[Byte] match {
-      case java.lang.Character.LOWERCASE_LETTER => true
-      case java.lang.Character.UPPERCASE_LETTER => true
-      case java.lang.Character.OTHER_LETTER     => true
-      case java.lang.Character.TITLECASE_LETTER => true
-      case java.lang.Character.LETTER_NUMBER    => true
-      case _ => ch == '_'
-    }
-  
-  /** <pre>Name ::= ( Letter | '_' ) (NameChar)*</pre>
-   *
-   *  see  [5] of XML 1.0 specification
-   */
-  def isName(s: String): Boolean =
-    if (s.length() > 0) {
-      val z: Seq[Char] = s
-      val y = z.elements
-      if (isNameStart(y.next)) {
-        while (y.hasNext && isNameChar(y.next)) {}
-        !y.hasNext
-      } else false
-    } else false
-
-  def isPubIDChar(c: Char) = c match {
-    case '\u0020' | '\u000D' | '\u000A' => true
-    case _ if
-      ('0' < c && c < '9')||('a' < c && c < 'z')||('A' < c && c < 'Z') => true
-    case '-' | '\''| '(' | ')' | '+' | ',' | '.' | '/' | ':'  | '=' | 
-         '?' | ';' | '!' | '*' | '#' | '@' | '$' | '_' | '%'           => true
-    case _ => false
-  }
-
-  def checkSysID(s: String): Boolean =
-    s.indexOf('"') == -1 || s.indexOf('\'') == -1
-
-  def checkPubID(s: String): Boolean =
-    if (s.length() > 0) {
-      val z:Seq[Char] = s
-      val y = z.elements
-      while (y.hasNext && isPubIDChar(y.next)) {}
-      !y.hasNext
-    } else true
-
-}
diff --git a/src/library/scala/xml/PrefixedAttribute.scala b/src/library/scala/xml/PrefixedAttribute.scala
index de2dd5e..9c505f6 100644
--- a/src/library/scala/xml/PrefixedAttribute.scala
+++ b/src/library/scala/xml/PrefixedAttribute.scala
@@ -1,13 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: PrefixedAttribute.scala 16894 2009-01-13 13:09:41Z cunei $
-
 
 package scala.xml
 
@@ -18,36 +16,26 @@ package scala.xml
  *  @param value the attribute value, which may not be null
  *  @param next  ...
  */
-class PrefixedAttribute(val pre: String,
-                        val key: String,
-                        val value: Seq[Node],
-                        val next: MetaData) extends MetaData {
-
-  if(value eq null)
+class PrefixedAttribute(
+  val pre: String,
+  val key: String,
+  val value: Seq[Node],
+  val next: MetaData)
+extends Attribute
+{
+  if (value eq null)
     throw new UnsupportedOperationException("value is null")
 
   /** same as this(key, Utility.parseAttributeValue(value), next) */
   def this(pre: String, key: String, value: String, next: MetaData) = 
     this(pre, key, Text(value), next)
 
-  /*
-   // the problem here is the fact that we cannot remove the proper attribute from
-   // next, and thus cannot guarantee that hashcodes are computed properly
-  def this(pre: String, key: String, value: scala.AllRef, next: MetaData) = 
-    throw new UnsupportedOperationException("can't construct prefixed nil attributes")
- */
-
   /** Returns a copy of this unprefixed attribute with the given
    *  next field.
    */
   def copy(next: MetaData) = 
     new PrefixedAttribute(pre, key, value, next)
 
-  def equals1(m: MetaData) =
-     (m.isPrefixed &&
-      (m.asInstanceOf[PrefixedAttribute].pre == pre) &&
-      (m.key == key) && (m.value sameElements value))
-
   def getNamespace(owner: Node) = 
     owner.getNamespace(pre)
 
@@ -62,39 +50,8 @@ class PrefixedAttribute(val pre: String,
     else 
       next(namespace, scope, key)
   }
-
-  /** returns true */
-  final def isPrefixed = true
-
-  /** returns the hashcode. 
-   */
-  override def hashCode() = 
-    pre.hashCode() * 41 + key.hashCode() * 7 + next.hashCode()
-    
-
-  /** appends string representation of only this attribute to stringbuffer */
-  def toString1(sb:StringBuilder): Unit = if(value ne null) {
-    sb.append(pre)
-    sb.append(':')
-    sb.append(key)
-    sb.append('=')
-    val sb2 = new StringBuilder()
-    for (c <- value) Utility.toXML(c, TopScope, sb2, true)
-    Utility.appendQuoted(sb2.toString(), sb)
-  }
-
-  def wellformed(scope: NamespaceBinding): Boolean =
-    (null == next(scope.getURI(pre), scope, key) && 
-     next.wellformed(scope))
-
-  def remove(key: String) = 
-    copy(next.remove(key))
-
-  def remove(namespace: String, scope: NamespaceBinding, key: String): MetaData =
-    if (key == this.key && scope.getURI(pre) == namespace)
-      next
-    else
-      next.remove(namespace, scope, key)
-  
 }
 
+object PrefixedAttribute {
+  def unapply(x: PrefixedAttribute) = Some(x.pre, x.key, x.value, x.next)
+}
diff --git a/src/library/scala/xml/PrettyPrinter.scala b/src/library/scala/xml/PrettyPrinter.scala
index 215c20e..f7bfb91 100644
--- a/src/library/scala/xml/PrettyPrinter.scala
+++ b/src/library/scala/xml/PrettyPrinter.scala
@@ -1,29 +1,28 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: PrettyPrinter.scala 16894 2009-01-13 13:09:41Z cunei $
-
 
 package scala.xml
 
-import scala.collection.Map
+import Utility.sbToString
 
 /** Class for pretty printing. After instantiating, you can use the
- *  toPrettyXML methods to convert XML to a formatted string. The class 
- *  can be reused to pretty print any number of XML nodes.
+ *  format() and formatNode() methods to convert XML to a formatted
+ *  string. The class can be reused to pretty print any number of
+ *  XML nodes.
  *
  *  @author  Burak Emir
  *  @version 1.0
  *
  *  @param width the width to fit the output into
- *  @step  indentation
+ *  @param step  indentation
  */
-class PrettyPrinter( width:Int, step:Int ) {
+class PrettyPrinter(width: Int, step: Int) {
 
   class BrokenException() extends java.lang.Exception
 
@@ -37,7 +36,6 @@ class PrettyPrinter( width:Int, step:Int ) {
   protected var items: List[Item] = Nil
 
   protected var cur = 0
-  //protected var pmap:Map[String,String] = _
 
   protected def reset() = {
     cur = 0
@@ -52,7 +50,7 @@ class PrettyPrinter( width:Int, step:Int ) {
    */
   protected def cut(s: String, ind: Int): List[Item] = {
     val tmp = width - cur
-    if (s.length < tmp)
+    if (s.length <= tmp)
       return List(Box(ind, s))
     val sb = new StringBuilder()
     var i = s.indexOf(' ')
@@ -82,19 +80,13 @@ class PrettyPrinter( width:Int, step:Int ) {
    *  @param s   ...
    *  @return    ...
    */
-  protected def makeBox(ind: Int, s: String) = {
-    if (cur < ind)
-      cur == ind
+  protected def makeBox(ind: Int, s: String) =
     if (cur + s.length > width) {            // fits in this line
-      items = Box(ind, s) :: items
+      items ::= Box(ind, s)
       cur += s.length
-    } else try {
-      for (b <- cut(s, ind).elements)  // break it up
-        items = b :: items
-    } catch {
-      case _:BrokenException => makePara(ind, s) // give up, para
-    }
-  }
+    } 
+    else try cut(s, ind) foreach (items ::= _)            // break it up
+    catch { case _: BrokenException => makePara(ind, s) } // give up, para
 
   // dont respect indent in para, but afterwards
   protected def makePara(ind: Int, s: String) = {
@@ -113,46 +105,51 @@ class PrettyPrinter( width:Int, step:Int ) {
    *  @return  ...
    */
   protected def leafTag(n: Node) = {
-    val sb = new StringBuilder("<")
-    n.nameToString(sb)
-    //Utility.appendPrefixedName( n.prefix, n.label, pmap, sb );
-    n.attributes.toString(sb)
-    //Utility.attr2xml( n.scope, n.attributes, pmap, sb );
-    sb.append("/>")
-    sb.toString()
+    def mkLeaf(sb: StringBuilder) {
+      sb append '<'
+      n nameToString sb
+      n.attributes buildString sb
+      sb append "/>"
+    }
+    sbToString(mkLeaf)
   }
 
   protected def startTag(n: Node, pscope: NamespaceBinding): (String, Int) = {
-    val sb = new StringBuilder("<")
-    n.nameToString(sb) //Utility.appendPrefixedName( n.prefix, n.label, pmap, sb );
-    val i = sb.length + 1
-    n.attributes.toString(sb)
-    n.scope.toString(sb, pscope)
-    sb.append('>')
-    (sb.toString(), i)
+    var i = 0
+    def mkStart(sb: StringBuilder) {
+      sb append '<'
+      n nameToString sb
+      i = sb.length + 1
+      n.attributes buildString sb
+      n.scope.buildString(sb, pscope)
+      sb append '>'
+    }
+    (sbToString(mkStart), i)
   }
 
-  protected def endTag(n: Node) = {
-    val sb = new StringBuilder("</")
-    n.nameToString(sb) //Utility.appendPrefixedName( n.prefix, n.label, pmap, sb );
-    sb.append('>')
-    sb.toString()
+  protected def endTag(n: Node) = {  
+    def mkEnd(sb: StringBuilder) {
+      sb append "</"
+      n nameToString sb
+      sb append '>'
+    }
+    sbToString(mkEnd)
   }
 
   protected def childrenAreLeaves(n: Node): Boolean = {
-    val it = n.child.elements
-    while (it.hasNext)
-      it.next match {
-        case _:Atom[_] | _:Comment | _:EntityRef | _:ProcInstr =>
-        case _:Node =>
-          return false
-      }
-    true
+    def isLeaf(l: Node) = l match {
+      case _:Atom[_] | _:Comment | _:EntityRef | _:ProcInstr  => true
+      case _                                                  => false
+    }
+    n.child forall isLeaf
   }
 
   protected def fits(test: String) =
     test.length < width - cur
 
+  private def doPreserve(node: Node) =
+    node.attribute(XML.namespace, XML.space).map(_.toString == XML.preserve) getOrElse false
+      
   /** @param tail: what we'd like to sqeeze in */
   protected def traverse(node: Node, pscope: NamespaceBinding, ind: Int): Unit =  node match {
 
@@ -161,15 +158,13 @@ class PrettyPrinter( width:Int, step:Int ) {
       case _:Atom[_] | _:Comment | _:EntityRef | _:ProcInstr => 
         makeBox( ind, node.toString().trim() )
       case g @ Group(xs) =>
-        traverse(xs.elements, pscope, ind)
+        traverse(xs.iterator, pscope, ind)
       case _ =>
         val test = {
           val sb = new StringBuilder()
           Utility.toXML(node, pscope, sb, false)
-          if (node.attribute("http://www.w3.org/XML/1998/namespace", "space") == "preserve")
-            sb.toString()
-          else
-            TextBuffer.fromString(sb.toString()).toText(0)._data
+          if (doPreserve(node)) sb.toString
+          else TextBuffer.fromString(sb.toString()).toText(0).data
         }
         if (childrenAreLeaves(node) && fits(test)) {
           makeBox(ind, test)
@@ -179,7 +174,7 @@ class PrettyPrinter( width:Int, step:Int ) {
           if (stg.length < width - cur) { // start tag fits
             makeBox(ind, stg)
             makeBreak()
-            traverse(node.child.elements, node.scope, ind + step)
+            traverse(node.child.iterator, node.scope, ind + step)
             makeBox(ind, etg)
           } else if (len2 < width - cur) {
             // <start label + attrs + tag + content + end tag
@@ -187,7 +182,7 @@ class PrettyPrinter( width:Int, step:Int ) {
             makeBreak() // todo: break the rest in pieces
             /*{ //@todo
              val sq:Seq[String] = stg.split(" ");
-             val it = sq.elements;
+             val it = sq.iterator;
              it.next;
              for (c <- it) {
                makeBox(ind+len2-2, c)
@@ -196,7 +191,7 @@ class PrettyPrinter( width:Int, step:Int ) {
              }*/
             makeBox(ind, stg.substring(len2, stg.length))
             makeBreak()
-            traverse(node.child.elements, node.scope, ind + step)
+            traverse(node.child.iterator, node.scope, ind + step)
             makeBox(cur, etg)
             makeBreak()
           } else { // give up
@@ -252,14 +247,6 @@ class PrettyPrinter( width:Int, step:Int ) {
 
   // public convenience methods
 
-  /** returns a formatted string containing well-formed XML with 
-   *  default namespace prefix mapping
-   *
-   *  @param n the node to be serialized
-   *  @return  ...
-   */
-  def format(n: Node): String = format(n, null) //Utility.defaultPrefixes(n))
-
   /** Returns a formatted string containing well-formed XML with 
    *  given namespace to prefix mapping.
    *
@@ -267,42 +254,24 @@ class PrettyPrinter( width:Int, step:Int ) {
    *  @param pmap the namespace to prefix mapping
    *  @return     ...
    */
-  def format(n: Node, pscope: NamespaceBinding): String = {
-    val sb = new StringBuilder()
-    format(n, pscope, sb)
-    sb.toString()
-  }
-
-  /** Returns a formatted string containing well-formed XML nodes with
-   *  default namespace prefix mapping.
-   *
-   *  @param nodes ...
-   *  @return      ...
-   */
-  def formatNodes(nodes: Seq[Node]): String =
-    formatNodes(nodes, null)
+  def format(n: Node, pscope: NamespaceBinding = null): String =
+    sbToString(format(n, pscope, _))
 
   /** Returns a formatted string containing well-formed XML.
    *
-   *  @param nodes the sequence of nodes to be serialized
-   *  @param pmap  the namespace to prefix mapping
+   *  @param nodes  the sequence of nodes to be serialized
+   *  @param pscope the namespace to prefix mapping
    */
-  def formatNodes(nodes: Seq[Node], pscope: NamespaceBinding): String = {
-    var sb = new StringBuilder()
-    formatNodes(nodes, pscope, sb)
-    sb.toString()
-  }
+  def formatNodes(nodes: Seq[Node], pscope: NamespaceBinding = null): String = 
+    sbToString(formatNodes(nodes, pscope, _))
 
   /** Appends a formatted string containing well-formed XML with
    *  the given namespace to prefix mapping to the given stringbuffer.
    *
-   *  @param n    the node to be serialized
-   *  @param pmap the namespace to prefix mapping
-   *  @param sb   the string buffer to which to append to
+   *  @param nodes  the nodes to be serialized
+   *  @param pscope the namespace to prefix mapping
+   *  @param sb     the string buffer to which to append to
    */
   def formatNodes(nodes: Seq[Node], pscope: NamespaceBinding, sb: StringBuilder): Unit =
-    for (n <- nodes.elements) {
-      sb.append(format(n, pscope))
-    }
-
+    nodes foreach (n => sb append format(n, pscope))
 }
diff --git a/src/library/scala/xml/ProcInstr.scala b/src/library/scala/xml/ProcInstr.scala
index 2f2085d..0008bf4 100644
--- a/src/library/scala/xml/ProcInstr.scala
+++ b/src/library/scala/xml/ProcInstr.scala
@@ -1,13 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: ProcInstr.scala 16894 2009-01-13 13:09:41Z cunei $
-
 
 package scala.xml
 
@@ -17,48 +15,24 @@ package scala.xml
  * @param  target target name of this PI
  * @param  text   text contained in this node, may not contain "?>"
  */
-case class ProcInstr(target:String, proctext:String) extends SpecialNode {  
-
+case class ProcInstr(target: String, proctext: String) extends SpecialNode
+{  
   if (!Utility.isName(target))
     throw new IllegalArgumentException(target+" must be an XML Name")
-  else if (text.indexOf("?>") != -1)
+  if (proctext contains "?>")
     throw new IllegalArgumentException(proctext+" may not contain \"?>\"")
-
-  final override def typeTag$: Int = -2
-
-  (target: Seq[Char]) match {
-    case Seq('X'|'x','M'|'m','L'|'l') =>
-      throw new IllegalArgumentException(target+" is reserved")
-    case _ =>
-  }
+  if (target.toLowerCase == "xml")
+    throw new IllegalArgumentException(target+" is reserved")
   
-  /** structural equality */
-  override def equals(x: Any): Boolean = x match {
-    case ProcInstr(x, y) => x.equals(target) && y.equals(proctext)
-    case _ => false
-  }
-
-  /** the constant "#PI" */
-  final def label = "#PI"
-
-  /** hashcode for this PI */
-  override def hashCode() = target.hashCode() * 7 + proctext.hashCode()
-
+  final override def doCollectNamespaces = false
+  final override def doTransform         = false
 
+  final def label   = "#PI"  
   override def text = ""
 
   /** appends "<?" target (" "+text)?+"?>" 
    *  to this stringbuffer.
    */
-  override def toString(sb: StringBuilder) = {
-    sb
-    .append("<?")
-    .append(target);
-    if (proctext.length() > 0) {
-      sb
-      .append(' ')
-      .append(proctext);
-    }
-    sb.append("?>")
-  }
+  override def buildString(sb: StringBuilder) =
+    sb append "<?%s%s?>".format(target, (if (proctext == "") "" else " " + proctext))
 }
diff --git a/src/library/scala/xml/QNode.scala b/src/library/scala/xml/QNode.scala
index 8e5be9d..331f138 100644
--- a/src/library/scala/xml/QNode.scala
+++ b/src/library/scala/xml/QNode.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: QNode.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala.xml
@@ -18,7 +17,5 @@ package scala.xml
  * @version 1.0
  */
 object QNode {
-
-  def unapplySeq(n:Node) = Some (Tuple4(n.scope.getURI(n.prefix), n.label, n.attributes, n.child))
-
+  def unapplySeq(n: Node) = Some((n.scope.getURI(n.prefix), n.label, n.attributes, n.child))
 }
diff --git a/src/library/scala/xml/SpecialNode.scala b/src/library/scala/xml/SpecialNode.scala
index 83f0167..1b5a8a7 100644
--- a/src/library/scala/xml/SpecialNode.scala
+++ b/src/library/scala/xml/SpecialNode.scala
@@ -1,13 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: SpecialNode.scala 16894 2009-01-13 13:09:41Z cunei $
-
 
 package scala.xml
 
@@ -21,8 +19,8 @@ package scala.xml
  *
  *  @author Burak Emir
  */
-abstract class SpecialNode extends Node with pull.XMLEvent {
-
+abstract class SpecialNode extends Node with pull.XMLEvent
+{
   /** always empty */
   final override def attributes = Null
 
@@ -33,6 +31,5 @@ abstract class SpecialNode extends Node with pull.XMLEvent {
   final def child = Nil
 
   /** append string representation to the given stringbuffer */
-  def toString(sb: StringBuilder): StringBuilder
-
+  def buildString(sb: StringBuilder): StringBuilder
 }
diff --git a/src/library/scala/xml/Text.scala b/src/library/scala/xml/Text.scala
index fdbcfce..5d9b78f 100644
--- a/src/library/scala/xml/Text.scala
+++ b/src/library/scala/xml/Text.scala
@@ -1,16 +1,30 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Text.scala 16894 2009-01-13 13:09:41Z cunei $
-
 
 package scala.xml
 
+// XXX This attempt to make Text not a case class revealed a bug in the pattern
+// matcher (see ticket #2883) so I've put the case back.  (It was/is desirable that
+// it not be a case class because it is using the antipattern of passing constructor
+// parameters to the superclass where they become vals, but since they will also be
+// vals in the subclass, it acquires an underscore to avoid a name clash.)
+//
+// object Text {
+//   def apply(data: String) =
+//     if (data != null) new Text(data)
+//     else throw new IllegalArgumentException("tried to construct Text with null")
+//     
+//   def unapply(other: Any): Option[String] = other match {
+//     case x: Text  => Some(x.data)
+//     case _        => None
+//   }
+// }
 
 /** The class <code>Text</code> implements an XML node for text (PCDATA).
  *  It is used in both non-bound and bound XML representations.
@@ -19,17 +33,10 @@ package scala.xml
  *
  *  @param text the text contained in this node, may not be null.
  */
-case class Text(_data: String) extends Atom[String](_data) {
-
-  if (null == data)
-    throw new java.lang.NullPointerException("tried to construct Text with null")
-
-  final override def equals(x: Any) = x match {
-    case s:String  => s == data
-    case s:Text    => data == s.data
-    case s:Atom[_] => data == s.data
-    case _ => false
-  }
+case class Text(_data: String) extends Atom[String](_data)
+{
+  if (_data == null)
+    throw new IllegalArgumentException("tried to construct Text with null")
 
   /** Returns text, with some characters escaped according to the XML
    *  specification.
@@ -37,7 +44,6 @@ case class Text(_data: String) extends Atom[String](_data) {
    *  @param  sb ...
    *  @return ... 
    */
-  override def toString(sb: StringBuilder) =
+  override def buildString(sb: StringBuilder) =
     Utility.escape(data, sb)
-
 }
diff --git a/src/library/scala/xml/TextBuffer.scala b/src/library/scala/xml/TextBuffer.scala
index e83070e..84420c3 100644
--- a/src/library/scala/xml/TextBuffer.scala
+++ b/src/library/scala/xml/TextBuffer.scala
@@ -1,19 +1,18 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: TextBuffer.scala 16881 2009-01-09 16:28:11Z cunei $
-
 
 package scala.xml
 
+import Utility.isSpace
 
 object TextBuffer {
-  def fromString(str: String): TextBuffer = new TextBuffer().append(str)
+  def fromString(str: String): TextBuffer = new TextBuffer() append str
 }
 
 /** The class <code>TextBuffer</code> is for creating text nodes without
@@ -21,22 +20,20 @@ object TextBuffer {
  *  appended with the <code>append</code> method will be replaced by a single
  *  space character, and leading and trailing space will be removed completely.
  */
-class TextBuffer {
-
+class TextBuffer
+{
   val sb = new StringBuilder()
-  var ws = true
-
-  def appendSpace         = if(!ws) { ws = true;  sb.append(' ') } else {}
-  def appendChar(c: Char) =         { ws = false; sb.append( c ) }
 
   /** Appends this string to the text buffer, trimming whitespaces as needed.
    *
    *  @param  cs ...
    *  @return ...
    */
-  def append(cs: Seq[Char]): TextBuffer = {
-    for (c <- cs)
-      if (Utility.isSpace(c)) appendSpace else appendChar(c)
+  def append(cs: Seq[Char]): this.type = {
+    cs foreach { c => 
+      if (!isSpace(c)) sb append c
+      else if (sb.isEmpty || !isSpace(sb.last)) sb append ' '
+    }
     this
   }
 
@@ -44,17 +41,8 @@ class TextBuffer {
    *
    *  @return the text without whitespaces.
    */
-  def toText: Seq[Text] = {
-    var len = sb.length /* invariant */
-    if (len == 0) return Nil
-
-    if (Utility.isSpace(sb.charAt(len - 1))) {
-      len -= 1
-      sb.length = len
-    }
-    if (len == 0) return Nil
-
-    List(Text(sb.toString()))
+  def toText: Seq[Text] = sb.toString.trim match {
+    case "" => Nil
+    case s  => Seq(Text(s))
   }
-
 }
diff --git a/src/library/scala/xml/TopScope.scala b/src/library/scala/xml/TopScope.scala
index e6eeb7e..9e5114d 100644
--- a/src/library/scala/xml/TopScope.scala
+++ b/src/library/scala/xml/TopScope.scala
@@ -1,39 +1,29 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: TopScope.scala 16894 2009-01-13 13:09:41Z cunei $
 
 package scala.xml
 
-import Predef._
-
 /** top level namespace scope. only contains the predefined binding
  *  for the "xml" prefix which is bound to 
  *  "http://www.w3.org/XML/1998/namespace"
  */
-case object TopScope extends NamespaceBinding(null, null, null) {
-
+object TopScope extends NamespaceBinding(null, null, null)
+{
+  import XML.{ xml, namespace }
+  
   override def getURI(prefix1: String): String =
-    if(prefix1 == "xml" /*XML.xml*/)
-      "http://www.w3.org/XML/1998/namespace"
-    else
-      null
+    if (prefix1 == xml) namespace else null
 
   override def getPrefix(uri1: String): String =
-    if (uri1 == "http://www.w3.org/XML/1998/namespace" /*XML.namespace*/)
-      "xml" //XML.xml
-    else
-      null
+    if (uri1 == namespace) xml else null
 
   override def toString() = ""
-
-  override def toString(stop: NamespaceBinding) = ""
-
-  override def toString(sb: StringBuilder, ignore: NamespaceBinding) = {}
-
+  override def buildString(stop: NamespaceBinding) = ""
+  override def buildString(sb: StringBuilder, ignore: NamespaceBinding) = {}
 }
diff --git a/src/library/scala/xml/TypeSymbol.scala b/src/library/scala/xml/TypeSymbol.scala
index 93ef81c..b9bd696 100644
--- a/src/library/scala/xml/TypeSymbol.scala
+++ b/src/library/scala/xml/TypeSymbol.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: TypeSymbol.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala.xml
diff --git a/src/library/scala/xml/Unparsed.scala b/src/library/scala/xml/Unparsed.scala
index fafd017..7911310 100644
--- a/src/library/scala/xml/Unparsed.scala
+++ b/src/library/scala/xml/Unparsed.scala
@@ -1,12 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Unparsed.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala.xml
@@ -15,22 +14,18 @@ package scala.xml
  *  are off regarding wellformedness etc.
  *
  * @author Burak Emir
- * @param _data content in this node, may not be null.
+ * @param data content in this node, may not be null.
  */
-case class Unparsed(_data: String) extends Atom[String](_data) {
-
+class Unparsed(data: String) extends Atom[String](data)
+{
   if (null == data)
-    throw new java.lang.NullPointerException("tried to construct Unparsed with null")
-
-  final override def equals(x: Any) = x match {
-    case s:String   => s == data
-    case s:Text     => data == s.data
-    case s:Unparsed => data == s.data
-    case s:Atom[_]  => data == s.data
-    case _ => false
-  }
+    throw new IllegalArgumentException("tried to construct Unparsed with null")
 
   /** returns text, with some characters escaped according to XML spec */
-  override def toString(sb: StringBuilder) = sb append data
+  override def buildString(sb: StringBuilder) = sb append data
+}
 
+object Unparsed {
+  def apply(data: String) = new Unparsed(data)
+  def unapply(x: Unparsed) = Some(x.data)
 }
diff --git a/src/library/scala/xml/UnprefixedAttribute.scala b/src/library/scala/xml/UnprefixedAttribute.scala
index ecf40a8..2a3d1c0 100644
--- a/src/library/scala/xml/UnprefixedAttribute.scala
+++ b/src/library/scala/xml/UnprefixedAttribute.scala
@@ -1,13 +1,11 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: UnprefixedAttribute.scala 16894 2009-01-13 13:09:41Z cunei $
-
 
 package scala.xml
 
@@ -15,28 +13,27 @@ package scala.xml
  *  
  *  @author Burak Emir
  */
-class UnprefixedAttribute(val key: String, val value: Seq[Node], next1: MetaData) extends MetaData {
-
+class UnprefixedAttribute(
+  val key: String,
+  val value: Seq[Node],
+  next1: MetaData)
+extends Attribute
+{
+  final val pre = null
   val next = if (value ne null) next1 else next1.remove(key)
 
   /** same as this(key, Text(value), next) */
   def this(key: String, value: String, next: MetaData) = 
-    this(key, if (value ne null) Text(value) else {val z:NodeSeq=null;z}, next)
+    this(key, if (value ne null) Text(value) else null: NodeSeq, next)
 
   /** same as this(key, value.get, next), or no attribute if value is None */
   def this(key: String, value: Option[Seq[Node]], next: MetaData) = 
-    this(key, if (!value.isEmpty) value.get else {val z:NodeSeq=null;z}, next)
+    this(key, value.orNull, next)
 
   /** returns a copy of this unprefixed attribute with the given next field*/
-  def copy(next: MetaData) = 
-    new UnprefixedAttribute(key, value, next)
+  def copy(next: MetaData) = new UnprefixedAttribute(key, value, next)
 
-  def equals1(m: MetaData) =
-    !m.isPrefixed && (m.key == key) && (m.value sameElements value)
-
-  /** returns null */
-  final def getNamespace(owner: Node): String = 
-    null
+  final def getNamespace(owner: Node): String = null
 
   /**
    * Gets value of unqualified (unprefixed) attribute with given key, null if not found
@@ -57,35 +54,7 @@ class UnprefixedAttribute(val key: String, val value: Seq[Node], next1: MetaData
    */
   def apply(namespace: String, scope: NamespaceBinding, key: String): Seq[Node] = 
     next(namespace, scope, key)
-
-  /** returns the hashcode.
-   */
-  override def hashCode() = 
-    key.hashCode() * 7 + { if(value ne null) value.hashCode() * 53 else 0 } + next.hashCode()
-  
-  /** returns false */
-  final def isPrefixed = false
-
-  /** appends string representation of only this attribute to stringbuffer.
-   *
-   *  @param sb ..
-   */
-  def toString1(sb: StringBuilder): Unit = if (value ne null) {
-    sb.append(key)
-    sb.append('=')
-    val sb2 = new StringBuilder()
-    for (c <- value) Utility.toXML(c, TopScope, sb2, true)
-    Utility.appendQuoted(sb2.toString(), sb)
-  }
-
-  def wellformed(scope: NamespaceBinding): Boolean = 
-    (null == next(null, scope, key)) && next.wellformed(scope)
-
-  def remove(key: String) = 
-    if (this.key == key) next else copy(next.remove(key))
-  
-  def remove(namespace: String, scope: NamespaceBinding, key: String): MetaData =
-    next.remove(namespace, scope, key)
-
 }
-
+object UnprefixedAttribute {
+  def unapply(x: UnprefixedAttribute) = Some(x.key, x.value, x.next)
+}
diff --git a/src/library/scala/xml/Utility.scala b/src/library/scala/xml/Utility.scala
index a484f89..d7d8d6c 100644
--- a/src/library/scala/xml/Utility.scala
+++ b/src/library/scala/xml/Utility.scala
@@ -1,17 +1,18 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Utility.scala 16857 2009-01-07 20:34:03Z cunei $
 
 
 package scala.xml
 
-import collection.mutable.{Set, HashSet}
+import collection.mutable
+import mutable.{ Set, HashSet }
+import parsing.XhtmlEntities
 
 /**
  * The <code>Utility</code> object provides utility functions for processing
@@ -19,8 +20,18 @@ import collection.mutable.{Set, HashSet}
  *
  * @author Burak Emir
  */
-object Utility extends AnyRef with parsing.TokenTests {
-
+object Utility extends AnyRef with parsing.TokenTests 
+{
+  implicit def implicitSbToString(sb: StringBuilder) = sb.toString()
+  
+  // helper for the extremely oft-repeated sequence of creating a
+  // StringBuilder, passing it around, and then grabbing its String.
+  private [xml] def sbToString(f: (StringBuilder) => Unit): String = {
+    val sb = new StringBuilder
+    f(sb)
+    sb.toString
+  }
+  private[xml] def isAtomAndNotText(x: Node) = x.isAtom && !x.isInstanceOf[Text]
 
   /** trims an element - call this method, when you know that it is an
    *  element (and not a text node) so you know that it will not be trimmed
@@ -61,10 +72,6 @@ object Utility extends AnyRef with parsing.TokenTests {
 		  Elem(pre,lab,sort(md),scp, (child map sort):_*)
 	  case _ => n
   }
-													  
-  /** @deprecated a string might also be Atom(s) - define your own conversion
-   */
-  @deprecated def view(s: String): Text = Text(s)
 
   /**
    * Escapes the characters < > & and " from string.
@@ -72,9 +79,25 @@ object Utility extends AnyRef with parsing.TokenTests {
    * @param text ...
    * @return     ...
    */
-  final def escape(text: String): String =
-    escape(text, new StringBuilder()).toString()
-
+  final def escape(text: String): String = sbToString(escape(text, _))
+  
+  object Escapes {
+    /** For reasons unclear escape and unescape are a long ways from
+      * being logical inverses. */
+    val pairs = Map(
+      "lt"    -> '<',
+      "gt"    -> '>',
+      "amp"   -> '&',
+      "quot"  -> '"'
+      // enigmatic comment explaining why this isn't escaped --
+      // is valid xhtml but not html, and IE doesn't know it, says jweb
+      // "apos"  -> '\''
+    )
+    val escMap    = pairs map { case (s, c) => c-> ("&%s;" format s) }
+    val unescMap  = pairs ++ Map("apos"  -> '\'')
+  }
+  import Escapes.{ escMap, unescMap }
+  
   /**
    * Appends escaped string to <code>s</code>.
    *
@@ -83,17 +106,29 @@ object Utility extends AnyRef with parsing.TokenTests {
    * @return     ...
    */
   final def escape(text: String, s: StringBuilder): StringBuilder = {
-    for (c <- text.elements) c match {
-      case '<' => s.append("<")
-      case '>' => s.append(">")
-      case '&' => s.append("&")
-      case '"' => s.append(""")
-      //case '\'' => s.append("'") // is valid xhtml but not html, and IE doesn't know it, says jweb
-      case _   => s.append(c)
+    // Implemented per XML spec: 
+    // http://www.w3.org/International/questions/qa-controls
+    // imperative code 3x-4x faster than current implementation
+    // dpp (David Pollak) 2010/02/03
+    val len = text.length
+    var pos = 0
+    while (pos < len) {
+      text.charAt(pos) match {
+        case '<' => s.append("<")
+        case '>' => s.append(">")
+        case '&' => s.append("&")
+        case '"' => s.append(""")
+        case '\n' => s.append('\n')
+        case '\r' => s.append('\r')
+        case '\t' => s.append('\t')
+        case c => if (c >= ' ') s.append(c)
+      }
+      
+      pos += 1
     }
     s
   }
-
+  
   /**
    * Appends unescaped string to <code>s</code>, amp becomes &
    * lt becomes < etc..
@@ -103,15 +138,8 @@ object Utility extends AnyRef with parsing.TokenTests {
    * @return    <code>null</code> if <code>ref</code> was not a predefined
    *            entity.
    */
-  final def unescape(ref: String, s: StringBuilder): StringBuilder = 
-    ref match {
-      case "lt"   => s.append('<')
-      case "gt"   => s.append('>')
-      case "amp"  => s.append('&')
-      case "quot" => s.append('"')
-      case "apos" => s.append('\'')
-      case _   => null
-    }
+  final def unescape(ref: String, s: StringBuilder): StringBuilder =
+    (unescMap get ref) map (s append _) orNull
 
   /**
    * Returns a set of all namespaces used in a sequence of nodes 
@@ -120,13 +148,8 @@ object Utility extends AnyRef with parsing.TokenTests {
    * @param nodes ...
    * @return      ...
    */
-  def collectNamespaces(nodes: Seq[Node]): Set[String] = {
-    var m = new HashSet[String]()
-    val it = nodes.elements
-    while (it.hasNext)
-      collectNamespaces(it.next, m);
-    m
-  }
+  def collectNamespaces(nodes: Seq[Node]): mutable.Set[String] = 
+    nodes.foldLeft(new HashSet[String]) { (set, x) => collectNamespaces(x, set) ; set }
 
   /**
    * Adds all namespaces in node to set.
@@ -134,8 +157,8 @@ object Utility extends AnyRef with parsing.TokenTests {
    * @param n   ...
    * @param set ...
    */
-  def collectNamespaces(n: Node, set: Set[String]) {
-    if (n.typeTag$ >= 0) {
+  def collectNamespaces(n: Node, set: mutable.Set[String]) {
+    if (n.doCollectNamespaces) {
       set += n.namespace
       for (a <- n.attributes) a match {
         case _:PrefixedAttribute =>
@@ -146,94 +169,76 @@ object Utility extends AnyRef with parsing.TokenTests {
         collectNamespaces(i, set)
     }
   }
-
-  /**
-   * Returs the string representation of an XML node, with comments stripped
-   * the comments.
-   *
-   * @param n the XML node
-   * @return  the string representation of node <code>n</code>.
-   *
-   * @see "toXML(Node, Boolean)"
-   */
-  def toXML(n: Node): String = toXML(n, true)
-
-  /**
-   * Return the string representation of a Node. uses namespace mapping from
-   *  <code>defaultPrefixes(n)</code>.
-   *
-   * @param n            the XML node
-   * @param stripComment ...
-   * @return             ...
-   *
-   * @todo define a way to escape literal characters to &xx; references
-   */
-  def toXML(n: Node, stripComment: Boolean): String = {
-    val sb = new StringBuilder()
-    toXML(n, TopScope, sb, stripComment)
-    sb.toString()
-  }
-
-
-  /** 
-   * Appends a tree to the given stringbuffer within given namespace scope.
-   *
-   * @param n            the node
-   * @param pscope       the parent scope
-   * @param sb           stringbuffer to append to
-   * @param stripComment if true, strip comments
-   */
-  def toXML(x: Node, pscope: NamespaceBinding, sb: StringBuilder, stripComment: Boolean) {
+  
+  // def toXML(
+  //   x: Node,
+  //   pscope: NamespaceBinding = TopScope,
+  //   sb: StringBuilder = new StringBuilder,
+  //   stripComments: Boolean = false,
+  //   decodeEntities: Boolean = true,
+  //   preserveWhitespace: Boolean = false,
+  //   minimizeTags: Boolean = false): String =
+  // {
+  //   toXMLsb(x, pscope, sb, stripComments, decodeEntities, preserveWhitespace, minimizeTags)
+  //   sb.toString()
+  // }
+
+  def toXML(
+    x: Node,
+    pscope: NamespaceBinding = TopScope,
+    sb: StringBuilder = new StringBuilder,
+    stripComments: Boolean = false,
+    decodeEntities: Boolean = true,
+    preserveWhitespace: Boolean = false,
+    minimizeTags: Boolean = false): StringBuilder =
+  {
     x match {
-
-      case c: Comment if !stripComment =>
-        c.toString(sb)
-
-      case x: SpecialNode =>
-        x.toString(sb)
-
+      case c: Comment => if (!stripComments) c buildString sb else sb
+      case x: SpecialNode => x buildString sb
       case g: Group =>
-        for (c <- g.nodes) toXML(c, x.scope, sb, stripComment)
-
+        g.nodes foreach {toXML(_, x.scope, sb, stripComments, decodeEntities, preserveWhitespace, minimizeTags)}
+        sb
       case _  =>
         // print tag with namespace declarations
         sb.append('<')
         x.nameToString(sb)
-        if (x.attributes ne null) x.attributes.toString(sb)
-        x.scope.toString(sb, pscope)
-        sb.append('>')
-        sequenceToXML(x.child, x.scope, sb, stripComment)
-        sb.append("</")
-        x.nameToString(sb)
-        sb.append('>')
+        if (x.attributes ne null) x.attributes.buildString(sb)
+        x.scope.buildString(sb, pscope)
+        if (x.child.isEmpty && minimizeTags) {
+          // no children, so use short form: <xyz .../>
+          sb.append(" />")
+        } else {
+          // children, so use long form: <xyz ...>...</xyz>
+          sb.append('>')
+          sequenceToXML(x.child, x.scope, sb, stripComments, decodeEntities, preserveWhitespace, minimizeTags)
+          sb.append("</")
+          x.nameToString(sb)
+          sb.append('>')
+        }
     }
   }
 
-  /**
-   * @param children     ...
-   * @param pscope       ...
-   * @param sb           ...
-   * @param stripComment ...
-   */
-  def sequenceToXML(children: Seq[Node], pscope: NamespaceBinding,
-                    sb: StringBuilder, stripComment: Boolean) {
-    if (children.isEmpty) {
-      return
-    } else if (children forall { 
-      case y: Atom[_] => !y.isInstanceOf[Text] 
-      case _ => false
-    }) { // add space
-      val it = children.elements
+  def sequenceToXML(
+    children: Seq[Node],
+    pscope: NamespaceBinding = TopScope,
+    sb: StringBuilder = new StringBuilder,
+    stripComments: Boolean = false,
+    decodeEntities: Boolean = true,
+    preserveWhitespace: Boolean = false,
+    minimizeTags: Boolean = false): Unit =
+  {
+    if (children.isEmpty) return
+    else if (children forall isAtomAndNotText) { // add space
+      val it = children.iterator
       val f = it.next
-      toXML(f, pscope, sb, stripComment)
+      toXML(f, pscope, sb, stripComments, decodeEntities, preserveWhitespace, minimizeTags)
       while (it.hasNext) {
         val x = it.next
         sb.append(' ')
-        toXML(x, pscope, sb, stripComment)
+        toXML(x, pscope, sb, stripComments, decodeEntities, preserveWhitespace, minimizeTags)
       }
-    } else {
-      for (c <- children) toXML(c, pscope, sb, stripComment)
     }
+    else children foreach { toXML(_, pscope, sb, stripComments, decodeEntities, preserveWhitespace, minimizeTags) }
   }
 
   /**
@@ -242,9 +247,9 @@ object Utility extends AnyRef with parsing.TokenTests {
    * @param name ...
    * @return     ... 
    */
-  final def prefix(name: String): Option[String] = {
-    val i = name.indexOf(':'.asInstanceOf[Int])
-    if (i != -1) Some(name.substring(0, i)) else None
+  final def prefix(name: String): Option[String] = (name indexOf ':') match {
+    case -1   => None
+    case i    => Some(name.substring(0, i))
   }
 
   /**
@@ -255,70 +260,20 @@ object Utility extends AnyRef with parsing.TokenTests {
    * @param attribHashCode
    * @param children
    */
-  def hashCode(pre: String, label: String, attribHashCode: Int, scpeHash: Int, children: Seq[Node]) = {
-    ( if(pre ne null) {41 * pre.hashCode() % 7} else {0})
-    + label.hashCode() * 53
+  def hashCode(pre: String, label: String, attribHashCode: Int, scpeHash: Int, children: Seq[Node]) = (
+    ( if(pre ne null) {41 * pre.## % 7} else {0})
+    + label.## * 53
     + attribHashCode * 7
     + scpeHash * 31
-    + children.hashCode()
-  }
-
-  /**
-   * Returns a hashcode for the given constituents of a node
-   *
-   * @param uri
-   * @param label
-   * @param attribs
-   * @param children
-  def hashCode(uri: String, label: String, attribs: scala.collection.mutable.HashMap[(String,String),String], scpe: Int, children: Seq[Node]): Int = {
-    41 * uri.hashCode() % 7 + label.hashCode() + attribs.toList.hashCode() + scpe + children.hashCode()
-  }
-   */
-
-  /**
-   * @param s ...
-   * @return  ...
-   */
-  def systemLiteralToString(s: String): String = {
-    val sb = new StringBuilder()
-    systemLiteralToString(sb, s)
-    sb.toString()
-  }
-
-  /**
-   * @param sb ...
-   * @param s  ...
-   * @return   ...
-   */
-  def systemLiteralToString(sb: StringBuilder, s: String): StringBuilder = {
-    sb.append("SYSTEM ")
-    appendQuoted(s, sb)
-  }
-
-  /**
-   * @param s ...
-   * @return  ...
-   */
-  def publicLiteralToString(s: String): String = {
-    val sb = new StringBuilder()
-    publicLiteralToString(sb, s)
-    sb.toString()
-  }
-
-  /**
-   * @param sb ...
-   * @param s  ...
-   * @return   ...
-   */
-  def publicLiteralToString(sb: StringBuilder, s: String): StringBuilder = {
-    sb.append("PUBLIC \"").append(s).append('"')
-  }
+    + {
+      var c = 0
+      val i = children.iterator
+      while(i.hasNext) c = c * 41 + i.next.##
+      c
+    }
+  )
 
-  def appendQuoted(s: String): String = {
-    val sb = new StringBuilder()
-    appendQuoted(s, sb)
-    sb.toString()
-  }
+  def appendQuoted(s: String): String = sbToString(appendQuoted(s, _))
 
   /**
    * Appends "s" if string <code>s</code> does not contain ",
@@ -329,7 +284,7 @@ object Utility extends AnyRef with parsing.TokenTests {
    * @return   ...
    */
   def appendQuoted(s: String, sb: StringBuilder) = {
-    val ch = if (s.indexOf('"'.asInstanceOf[Int]) == -1) '"' else '\'';
+    val ch = if (s contains '"') '\'' else '"'
     sb.append(ch).append(s).append(ch)
   }
 
@@ -355,17 +310,12 @@ object Utility extends AnyRef with parsing.TokenTests {
    * @return      ...
    */
   def getName(s: String, index: Int): String = {
-    var i = index;
-    val sb = new StringBuilder();
-    if (i < s.length) {
-      var c = s.charAt(i);
-      if (isNameStart(s.charAt(i)))  
-        while (i < s.length && { c = s.charAt(i); isNameChar(c)}) {
-          sb.append(c)
-          i = i + 1
-        }
-      sb.toString()
-    } else null
+    if (index >= s.length) null
+    else {
+      val xs = s drop index
+      if (xs.nonEmpty && isNameStart(xs.head)) xs takeWhile isNameChar
+      else ""
+    }
   }
 
   /**
@@ -402,45 +352,44 @@ object Utility extends AnyRef with parsing.TokenTests {
    * @return      ...
    */
   def parseAttributeValue(value: String): Seq[Node] = {
-    val zs: Seq[Char] = value
     val sb  = new StringBuilder
     var rfb: StringBuilder = null
     val nb = new NodeBuffer()
-    val it = zs.elements
+    
+    val it = value.iterator
     while (it.hasNext) {
       var c = it.next
-      c match {
-        case '&' => // entity! flush buffer into text node
-          it.next match {
-            case '#' =>
-              c = it.next
-              val theChar = parseCharRef ({ ()=> c },{ () => c = it.next },{s => throw new RuntimeException(s)})
-              sb.append(theChar)
-
-            case x =>
-              if (rfb eq null) rfb = new StringBuilder()
-              rfb.append(x)
-              c = it.next
-              while (c != ';') {
-                rfb.append(c)
-                c = it.next
-              }
-              val ref = rfb.toString() 
-              rfb.setLength(0)
-              unescape(ref,sb) match {
-                case null => 
-                  if (sb.length > 0) {          // flush buffer
-                    nb += Text(sb.toString())
-                    sb.setLength(0)
-                  }
-                  nb += EntityRef(sb.toString()) // add entityref
-                case _ =>
+      // entity! flush buffer into text node
+      if (c == '&') {
+        c = it.next
+        if (c == '#') {
+          c = it.next
+          val theChar = parseCharRef ({ ()=> c },{ () => c = it.next },{s => throw new RuntimeException(s)})
+          sb.append(theChar)
+        }
+        else {
+          if (rfb eq null) rfb = new StringBuilder()
+          rfb append c
+          c = it.next
+          while (c != ';') {
+            rfb.append(c)
+            c = it.next
+          }
+          val ref = rfb.toString() 
+          rfb.setLength(0)
+          unescape(ref,sb) match {
+            case null => 
+              if (sb.length > 0) {          // flush buffer
+                nb += Text(sb.toString())
+                sb.setLength(0)
               }
+              nb += EntityRef(sb.toString()) // add entityref
+            case _ =>
           }
-        case x   => 
-          sb.append(x)
+        }
       }
-    } 
+      else sb append c
+    }
     if (sb.length > 0) { // flush buffer
       val x = Text(sb.toString())
       if (nb.length == 0)
@@ -485,7 +434,6 @@ object Utility extends AnyRef with parsing.TokenTests {
       }
       nextch()
     }
-    new String(io.UTF8Codec.encode(i), "utf8")
+    new String(Array(i), 0, 1)
   }
-
 }
diff --git a/src/library/scala/xml/XML.scala b/src/library/scala/xml/XML.scala
index 7dcaf3e..75c85a5 100644
--- a/src/library/scala/xml/XML.scala
+++ b/src/library/scala/xml/XML.scala
@@ -1,22 +1,34 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: XML.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
 package scala.xml
 
-
-import Predef._
-import scala.xml.parsing.NoBindingFactoryAdapter
-import org.xml.sax.InputSource
-import java.io.{File, FileDescriptor, FileInputStream, FileOutputStream}
-import java.io.{InputStream, Reader, StringReader, Writer}
+import parsing.NoBindingFactoryAdapter
+import factory.XMLLoader
+import java.io.{ File, FileDescriptor, FileInputStream, FileOutputStream }
+import java.io.{ InputStream, Reader, StringReader, Writer }
+import java.nio.channels.Channels
+import scala.util.control.Exception.ultimately
+
+object Source
+{
+  def fromFile(file: File)              = new InputSource(new FileInputStream(file))
+  def fromFile(fd: FileDescriptor)      = new InputSource(new FileInputStream(fd))
+  def fromFile(name: String)            = new InputSource(new FileInputStream(name))
+
+  def fromInputStream(is: InputStream)  = new InputSource(is)
+  def fromReader(reader: Reader)        = new InputSource(reader)
+  def fromSysId(sysID: String)          = new InputSource(sysID)
+  def fromString(string: String)        = fromReader(new StringReader(string))
+}
+import Source._
 
 /** The object <code>XML</code> provides constants, and functions to load
  *  and save XML elements. Use this when data binding is not desired, i.e.
@@ -25,8 +37,8 @@ import java.io.{InputStream, Reader, StringReader, Writer}
  *  @author  Burak Emir
  *  @version 1.0, 25/04/2005
  */
-object XML {
-
+object XML extends XMLLoader[Elem]
+{  
   val xml       = "xml"
   val xmlns     = "xmlns"
   val namespace = "http://www.w3.org/XML/1998/namespace"
@@ -34,85 +46,19 @@ object XML {
   val space     = "space"
   val lang      = "lang"
   val encoding  = "ISO-8859-1"
-
-  // functions for generic xml loading, saving
-
-  /** loads XML from given file, using XML parser in JDK. */
-  final def loadFile(file: File): Elem = 
-    new NoBindingFactoryAdapter().loadXML(new InputSource( 
-      new FileInputStream(file)
-    ))
-
-  /** loads XML from given file descriptor, using XML parser in JDK.
-   *
-   *  @param fileDesc ...
-   *  @return         ...
-   */
-  final def loadFile(fileDesc: FileDescriptor): Elem = 
-    new NoBindingFactoryAdapter().loadXML(new InputSource( 
-      new FileInputStream(fileDesc)
-    ))
-
-  /** loads XML from given file, using XML parser in JDK. */
-  final def loadFile(fileName: String): Elem = 
-    new NoBindingFactoryAdapter().loadXML(new InputSource( 
-      new FileInputStream(fileName)
-    ));
-
-  /** loads XML from given InputStream, using XML parser in JDK. */
-  final def load( is:InputStream ): Elem = 
-    new NoBindingFactoryAdapter().loadXML(new InputSource(is))
-
-  /** loads XML from given Reader, using XML parser in JDK. */
-  final def load(reader: Reader): Elem = 
-    new NoBindingFactoryAdapter().loadXML(new InputSource(reader))
-
-  /** loads XML from given sysID, using XML parser in JDK. */
-  final def load(sysID: String): Elem = 
-    new NoBindingFactoryAdapter().loadXML(new InputSource(sysID))
   
-  /** loads XML from a given input source, using XML parser in JDK.
-   *
-   *  @param source ...
-   *  @return       ...
-   */
-  final def load(source: InputSource): Elem = 
-    new NoBindingFactoryAdapter().loadXML(source)
+  /** Returns an XMLLoader whose load* methods will use the supplied SAXParser. */
+  def withSAXParser(p: SAXParser): XMLLoader[Elem] =
+    new XMLLoader[Elem] { override val parser: SAXParser = p }
 
-  /** loads XML from a string, using XML parser in JDK. */
-  final def loadString(string: String): Elem = 
-    load(new StringReader(string))
-
-  /** Saves XML to filename with encoding ISO-8859-1 without xml-decl without
-   *  <code>doctype</code>.
-   *
-   *  @param filename ...
-   *  @param node     ...
-   */
-  final def save(filename: String, node: Node): Unit = 
-    save(filename, node, encoding)
-
-  /** saves XML to filename with given encoding, without xml-decl without
-   *  <code>doctype</code>.
-   *
-   *  @param filename ...
-   *  @param node     ...
-   *  @param enc      ...
-   */
-  final def save(filename: String, node: Node, enc: String): Unit = 
-    saveFull(filename, node, enc, false, null);
-
-  /** saves a node to a file with given filename using encoding iso-8859-1
-   *  optionally with xmldecl and doctype declaration.
-   *
-   *  @param filename the filename
-   *  @param node     the xml node we want to write
-   *  @param xmlDecl  if true, write xml declaration
-   *  @param doctype  if not null, write doctype declaration
-   */
+  @deprecated("Use save() instead")
   final def saveFull(filename: String, node: Node, xmlDecl: Boolean, doctype: dtd.DocType): Unit = 
-    saveFull(filename, node, encoding, xmlDecl, doctype)
-
+    save(filename, node, encoding, xmlDecl, doctype)
+    
+  @deprecated("Use save() instead")  
+  final def saveFull(filename: String, node: Node, enc: String, xmlDecl: Boolean, doctype: dtd.DocType): Unit = 
+    save(filename, node, enc, xmlDecl, doctype)
+  
   /** Saves a node to a file with given filename using given encoding
    *  optionally with xmldecl and doctype declaration.
    *
@@ -122,22 +68,20 @@ object XML {
    *  @param xmlDecl  if true, write xml declaration
    *  @param doctype  if not null, write doctype declaration
    */
-
-  final def saveFull(filename: String, node: Node, enc: String, xmlDecl: Boolean, doctype: dtd.DocType) {
-    var fos: FileOutputStream = null
-    var w: Writer = null
-    try {
-      // using NIO classes of JDK 1.4
-      import java.io.{FileOutputStream, Writer}
-      import java.nio.channels.{Channels, FileChannel}
-      
-      fos = new FileOutputStream(filename)
-      w = Channels.newWriter(fos.getChannel(), enc)
-      write(w, node, enc, xmlDecl, doctype) 
-    } finally {
-      w.close()
-      fos.close()
-    }
+  final def save(
+    filename: String,
+    node: Node,
+    enc: String = encoding,
+    xmlDecl: Boolean = false,
+    doctype: dtd.DocType = null
+    ): Unit = 
+  {
+    val fos = new FileOutputStream(filename)
+    val w = Channels.newWriter(fos.getChannel(), enc)
+    
+    ultimately(w.close())(
+      write(w, node, enc, xmlDecl, doctype)
+    )
   }
 
   /** Writes the given node using writer, optionally with xml decl and doctype.
@@ -153,6 +97,6 @@ object XML {
     /* TODO: optimize by giving writer parameter to toXML*/
     if (xmlDecl) w.write("<?xml version='1.0' encoding='" + enc + "'?>\n")
     if (doctype ne null) w.write( doctype.toString() + "\n")
-    w.write(Utility.toXML(node))
+    w.write(Utility.toXML(node).toString)
   }
 }
diff --git a/src/library/scala/xml/Xhtml.scala b/src/library/scala/xml/Xhtml.scala
index bfa85b5..2a126fb 100644
--- a/src/library/scala/xml/Xhtml.scala
+++ b/src/library/scala/xml/Xhtml.scala
@@ -1,60 +1,69 @@
-// $Id: Xhtml.scala 14416 2008-03-19 01:17:25Z mihaylov $
 
 package scala.xml
 
 import parsing.XhtmlEntities
+import Utility.{ sbToString, isAtomAndNotText }
 
 /* (c) David Pollak  2007 WorldWide Conferencing, LLC */
 
-object Xhtml {
-
-  def toXhtml(n: Node, stripComment: Boolean, convertAmp: Boolean): String = {
-    val sb = new StringBuilder()
-    toXhtml(n, TopScope, sb, stripComment, convertAmp)
-    sb.toString()
-  }
-
-  /** 
-   * Appends a tree to the given stringbuffer within given namespace scope.
-   *
-   * @param n            the node
-   * @param pscope       the parent scope
-   * @param sb           stringbuffer to append to
-   * @param stripComment if true, strip comments
+object Xhtml
+{
+  /**
+   * Convenience function: same as toXhtml(node, false, false)
+   * 
+   * @param node      the node
    */
-  def toXhtml(x: Node, pscope: NamespaceBinding, sb: StringBuilder, stripComment: Boolean, convertAmp: Boolean): Unit = {
+  def toXhtml(node: Node): String = sbToString(sb => toXhtml(x = node, sb = sb))
+  
+  /**
+   * Convenience function: amounts to calling toXhtml(node) on each
+   * node in the sequence.
+   * 
+   * @param nodeSeq   the node sequence
+   */  
+  def toXhtml(nodeSeq: NodeSeq): String = sbToString(sb => sequenceToXML(nodeSeq: Seq[Node], sb = sb))    
+   
+  /** Elements which we believe are safe to minimize if minimizeTags is true.
+   *  See http://www.w3.org/TR/xhtml1/guidelines.html#C_3 
+   */
+  private val minimizableElements =
+    List("base", "meta", "link", "hr", "br", "param", "img", "area", "input", "col")
+ 
+  def toXhtml(
+    x: Node, 
+    pscope: NamespaceBinding = TopScope,
+    sb: StringBuilder = new StringBuilder,
+    stripComments: Boolean = false,
+    decodeEntities: Boolean = false,
+    preserveWhitespace: Boolean = false,
+    minimizeTags: Boolean = true): Unit =
+  {    
+    def decode(er: EntityRef) = XhtmlEntities.entMap.get(er.entityName) match {
+      case Some(chr) if chr.toInt >= 128  => sb.append(chr)
+      case _                              => er.buildString(sb)
+    }
+    def shortForm = 
+      minimizeTags &&
+      (x.child == null || x.child.length == 0) && 
+      (minimizableElements contains x.label)
+    
     x match {
-
-      case c: Comment if !stripComment =>
-        c.toString(sb)
-
-      case er: EntityRef if convertAmp =>
-        XhtmlEntities.entMap.get(er.entityName) match {
-          case Some(chr) if chr.toInt >= 128 => sb.append(chr)
-          case _ => er.toString(sb)
-        }
-      
-      case x: SpecialNode =>
-        x.toString(sb)
-
-      case g: Group =>
-        for (c <- g.nodes) toXhtml(c, x.scope, sb, stripComment, convertAmp)
+      case c: Comment                       => if (!stripComments) c buildString sb
+      case er: EntityRef if decodeEntities  => decode(er)
+      case x: SpecialNode                   => x buildString sb
+      case g: Group                         =>
+        g.nodes foreach { toXhtml(_, x.scope, sb, stripComments, decodeEntities, preserveWhitespace, minimizeTags) }
 
       case _  =>
-        if (((x.child eq null) || (x.child.length == 0)) && x.label != "div" && x.label != "script" && x.label != "textarea") {
-          sb.append('<')
-          x.nameToString(sb)
-          if (x.attributes ne null) x.attributes.toString(sb)
-          x.scope.toString(sb, pscope)
-          sb.append(" />")
-        } else {
-          // print tag with namespace declarations
-          sb.append('<')
-          x.nameToString(sb)
-          if (x.attributes ne null) x.attributes.toString(sb)
-          x.scope.toString(sb, pscope)
+        sb.append('<')
+        x.nameToString(sb)
+        if (x.attributes ne null) x.attributes.buildString(sb)
+        x.scope.buildString(sb, pscope)
+        
+        if (shortForm) sb.append(" />")
+        else {
           sb.append('>')
-          sequenceToXML(x.child, x.scope, sb, stripComment, convertAmp)
+          sequenceToXML(x.child, x.scope, sb, stripComments, decodeEntities, preserveWhitespace, minimizeTags)
           sb.append("</")
           x.nameToString(sb)
           sb.append('>')
@@ -63,27 +72,25 @@ object Xhtml {
   }
 
   /**
-   * @param children     ...
-   * @param pscope       ...
-   * @param sb           ...
-   * @param stripComment ...
+   * Amounts to calling toXhtml(node, ...) with the given parameters on each node.
    */
-  def sequenceToXML(children: Seq[Node], pscope: NamespaceBinding,
-                    sb: StringBuilder, stripComment: Boolean, convertAmp: Boolean): Unit = {
+  def sequenceToXML(
+    children: Seq[Node],
+    pscope: NamespaceBinding = TopScope,
+    sb: StringBuilder = new StringBuilder,
+    stripComments: Boolean = false,
+    decodeEntities: Boolean = false,
+    preserveWhitespace: Boolean = false,
+    minimizeTags: Boolean = true): Unit =
+  {
     if (children.isEmpty)
       return
-    else if (children forall { y => y.isInstanceOf[Atom[_]] && !y.isInstanceOf[Text] }) { // add space
-      val it = children.elements
-      val f = it.next
-      toXhtml(f, pscope, sb, stripComment, convertAmp)
-      while (it.hasNext) {
-        val x = it.next
-        sb.append(' ')
-        toXhtml(x, pscope, sb, stripComment, convertAmp)
-      }
-    } else {
-      for (c <- children) toXhtml(c, pscope, sb, stripComment, convertAmp)
+      
+    val doSpaces = children forall isAtomAndNotText // interleave spaces
+    for (c <- children.take(children.length - 1)) {
+      toXhtml(c, pscope, sb, stripComments, decodeEntities, preserveWhitespace, minimizeTags)
+      if (doSpaces) sb append ' '
     }
+    toXhtml(children.last, pscope, sb, stripComments, decodeEntities, preserveWhitespace, minimizeTags)
   }
 }
-
diff --git a/src/library/scala/xml/dtd/ContentModel.scala b/src/library/scala/xml/dtd/ContentModel.scala
index 760217f..c0c9e42 100644
--- a/src/library/scala/xml/dtd/ContentModel.scala
+++ b/src/library/scala/xml/dtd/ContentModel.scala
@@ -1,18 +1,20 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: ContentModel.scala 16857 2009-01-07 20:34:03Z cunei $
 
 
-package scala.xml.dtd
+package scala.xml
+package dtd
 
-import scala.util.regexp.WordExp
-import scala.util.automata.{DetWordAutom, SubsetConstruction, WordBerrySethi}
+import util.regexp.WordExp
+import util.automata._
+import Utility.sbToString
+import PartialFunction._
 
 object ContentModel extends WordExp {
   type _labelT = ElemName
@@ -23,168 +25,97 @@ object ContentModel extends WordExp {
   }
 
   case class ElemName(name: String) extends Label {
-    override def toString() = "ElemName(\""+name+"\")"
+    override def toString() = """ElemName("%s")""" format name
   }
 
-  def isMixed(cm: ContentModel) = cm.isInstanceOf[MIXED]
+  def isMixed(cm: ContentModel) = cond(cm) { case _: MIXED => true }
   def containsText(cm: ContentModel) = (cm == PCDATA) || isMixed(cm)
-
   def parse(s: String): ContentModel = ContentModelParser.parse(s)
 
-  def getLabels(r: RegExp): scala.collection.Set[String] = {
-    val s = new scala.collection.mutable.HashSet[String]()
-    def traverse1(xs: Seq[RegExp]) {
-      val it = xs.elements
-      while (it.hasNext) traverse(it.next)
-    }
-    def traverse(r: RegExp) {
-      r match { // !!! check for match translation problem
-        case Letter(ElemName(name)) => s += name
-        case Star(  x @ _  ) => traverse( x ) // bug if x at _*
-        case Sequ( xs @ _* ) => traverse1(xs)
-        case Alt(  xs @ _* ) => traverse1(xs)
-      }
+  def getLabels(r: RegExp): Set[String] = {    
+    def traverse(r: RegExp): Set[String] = r match { // !!! check for match translation problem
+      case Letter(ElemName(name)) => Set(name)
+      case Star(  x @ _  ) => traverse( x ) // bug if x at _*
+      case Sequ( xs @ _* ) => Set(xs map traverse flatten: _*)
+      case Alt(  xs @ _* ) => Set(xs map traverse flatten: _*)
     }
+    
     traverse(r)
-    return s
   }
 
-  def toString(r: RegExp): String = {
-    val sb = new StringBuilder()
-    toString(r, sb)
-    sb.toString()
-  }
+  def buildString(r: RegExp): String = sbToString(buildString(r, _))
 
   /* precond: rs.length >= 1 */
-  private def toString(rs: Seq[RegExp], sb: StringBuilder, sep: Char) {
-    val it = rs.elements
-    val fst = it.next
-    toString(fst, sb)
-    for (z <- it) {
-      sb.append(sep)
-      toString(z, sb)
+  private def buildString(rs: Seq[RegExp], sb: StringBuilder, sep: Char) {
+    buildString(rs.head, sb)
+    for (z <- rs.tail) {
+      sb append sep
+      buildString(z, sb)
     }
     sb
   }
 
-  def toString(c: ContentModel, sb: StringBuilder): StringBuilder = c match {
-    case ANY => 
-      sb.append("ANY")
-    case EMPTY => 
-      sb.append("EMPTY")
-    case PCDATA => 
-      sb.append("(#PCDATA)")
-    case ELEMENTS( _ ) | MIXED( _ ) => 
-      c.toString(sb)
+  def buildString(c: ContentModel, sb: StringBuilder): StringBuilder = c match {
+    case ANY                    => sb append "ANY"
+    case EMPTY                  => sb append "EMPTY"
+    case PCDATA                 => sb append "(#PCDATA)"
+    case ELEMENTS(_) | MIXED(_) => c buildString sb
   }
 
-  def toString(r: RegExp, sb:StringBuilder): StringBuilder = r match {  // !!! check for match translation problem
-    case Eps => 
-      sb
-    case Sequ(rs @ _*) => 
-      sb.append( '(' ); toString(rs, sb, ','); sb.append( ')' )
-    case Alt(rs @ _*) =>
-      sb.append( '(' ); toString(rs, sb, '|');  sb.append( ')' )
-    case Star(r: RegExp) => 
-      sb.append( '(' ); toString(r, sb); sb.append( ")*" )
-    case Letter(ElemName(name)) =>
-      sb.append(name)
-  }
+  def buildString(r: RegExp, sb: StringBuilder): StringBuilder =
+    r match {  // !!! check for match translation problem
+      case Eps => 
+        sb
+      case Sequ(rs @ _*) => 
+        sb.append( '(' ); buildString(rs, sb, ','); sb.append( ')' )
+      case Alt(rs @ _*) =>
+        sb.append( '(' ); buildString(rs, sb, '|');  sb.append( ')' )
+      case Star(r: RegExp) => 
+        sb.append( '(' ); buildString(r, sb); sb.append( ")*" )
+      case Letter(ElemName(name)) =>
+        sb.append(name)
+    }
 
 }
 
-sealed abstract class ContentModel {
-
-  override def toString(): String = {
-    val sb = new StringBuilder()
-    toString(sb)
-    sb.toString()
-  }
-
-  def toString(sb:StringBuilder): StringBuilder;
-  /*
-  def validate(cs: NodeSeq): Boolean = this.match {
-    case ANY         => true
-    case EMPTY       => cs.length == 0
-    case PCDATA      => cs.length == 0
-                     || (cs.length == 1 && cs(0).isInstanceOf[Text])
-    case m at MIXED(r)    => m.runDFA(cs)
-    case e at ELEMENTS(r) => e.runDFA(cs)
-  }
-  */
+sealed abstract class ContentModel
+{
+  override def toString(): String = sbToString(buildString)
+  def buildString(sb: StringBuilder): StringBuilder
 }
 
 case object PCDATA extends ContentModel {
-  override def toString(sb: StringBuilder): StringBuilder = sb.append("(#PCDATA)")
+  override def buildString(sb: StringBuilder): StringBuilder = sb.append("(#PCDATA)")
 }
 case object EMPTY extends ContentModel {
-  override def toString(sb: StringBuilder): StringBuilder = sb.append("EMPTY")
+  override def buildString(sb: StringBuilder): StringBuilder = sb.append("EMPTY")
 }
 case object ANY extends ContentModel {
-  override def toString(sb: StringBuilder): StringBuilder = sb.append("ANY")
+  override def buildString(sb: StringBuilder): StringBuilder = sb.append("ANY")
 }
 sealed abstract class DFAContentModel extends ContentModel {
-  import ContentModel.ElemName
+  import ContentModel.{ ElemName, Translator }
   def r: ContentModel.RegExp
-  private var _dfa: DetWordAutom[ContentModel.ElemName] = null
-
-  def dfa = {
-    if (null == _dfa) {
-      val nfa = ContentModel.Translator.automatonFrom(r, 1);
-      _dfa = new SubsetConstruction(nfa).determinize;
-    }
-    _dfa
+  
+  lazy val dfa: DetWordAutom[ElemName] = {
+    val nfa = Translator.automatonFrom(r, 1)
+    new SubsetConstruction(nfa).determinize
   }
 }
+
 case class MIXED(r: ContentModel.RegExp) extends DFAContentModel {
-  import ContentModel.{Alt, Eps, RegExp}
-  /*
-  def getIterator(ns:NodeSeq) = new Iterator[String] {
-    def cond(n:Node) = 
-      !n.isInstanceOf[Text] && !n.isInstanceOf[SpecialNode];
-Console.println("ns = "+ns);
-    val jt = ns.elements;
-    def hasNext = jt.hasNext;
-    def next = {
-      var r: Node = jt.next;
-      while(!cond(r) && jt.hasNext)  {
-        Console.println("skipping "+r);
-        r = jt.next;
-      }
-      Console.println("MIXED, iterator.next, r = "+r);
-      if(Text("") == r) 
-        null 
-      else 
-        r.label
-    }
-  }
-  */
-  override def toString(sb: StringBuilder): StringBuilder =  {
-    sb.append("(#PCDATA|")
-    ContentModel.toString(Alt(r.asInstanceOf[Alt].rs.toList.drop(1):_*):RegExp, sb);
-    sb.append(")*");
+  import ContentModel.{ Alt, RegExp }
+
+  override def buildString(sb: StringBuilder): StringBuilder = {
+    val newAlt = r match { case Alt(rs @ _*) => Alt(rs drop 1: _*) }
+
+    sb append "(#PCDATA|"
+    ContentModel.buildString(newAlt: RegExp, sb)
+    sb append ")*"
   }
 }
 
-case class  ELEMENTS(r:ContentModel.RegExp) extends DFAContentModel {
-  /*
-  def getIterator(ns:NodeSeq) = new Iterator[String] {
-    val jt = ns.elements.buffered;
-    def hasNext = jt.hasNext;
-    def next = {
-      var r: Node = jt.next;
-      while(r.isInstanceOf[SpecialNode] && jt.hasNext) {
-        r = jt.head; 
-        jt.next;
-      }
-      Console.println("MIXED, iterator.next, r = "+r);
-      if(r.isInstanceOf[Text]) 
-        throw ValidationException("Text not allowed here!") 
-      else 
-        r.label
-    }
-  } 
-  */
-  override def toString(sb: StringBuilder): StringBuilder =  
-    ContentModel.toString(r, sb)
+case class ELEMENTS(r: ContentModel.RegExp) extends DFAContentModel {
+  override def buildString(sb: StringBuilder): StringBuilder =  
+    ContentModel.buildString(r, sb)
 }
diff --git a/src/library/scala/xml/dtd/ContentModelParser.scala b/src/library/scala/xml/dtd/ContentModelParser.scala
index ca0440b..1009688 100644
--- a/src/library/scala/xml/dtd/ContentModelParser.scala
+++ b/src/library/scala/xml/dtd/ContentModelParser.scala
@@ -1,16 +1,14 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://www.scala-lang.org/           **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: ContentModelParser.scala 16857 2009-01-07 20:34:03Z cunei $
-
-
-package scala.xml.dtd
 
+package scala.xml
+package dtd
 
 /** Parser for regexps (content models in DTD element declarations) */
 
@@ -79,30 +77,12 @@ object ContentModelParser extends Scanner { // a bit too permissive concerning #
 
   //                      (' S? mixed ::= '#PCDATA' S? ')'
   //                                    | '#PCDATA' (S? '|' S? atom)* S? ')*'
-  /*
-  def mixed = {
-    accept( TOKEN_PCDATA );
-    sOpt;
-    if( token == RPAREN ) 
-      PCDATA_
-    else {
-      val t = choiceRest( PCDATA_ );
-      if( !isMixed( t ) )
-        error("mixed content models must be like (#PCDATA.|.|.|.)*");
-      accept( RPAREN );
-      // lax: (workaround for buggy Java XML parser in JDK1.4.2)
-      if( token == STAR ) accept( STAR ); 
-      // strict:
-      // accept( STAR );
-      Star( t )
-    }
-  }
-*/
+
   //       '(' S? regexp ::= cp S? [seqRest|choiceRest] ')' [ '+' | '*' | '?' ]
   def regexp: RegExp = {
     val p = particle;
     sOpt;
-    maybeSuffix( token match {
+    maybeSuffix(token match {
       case RPAREN  => nextToken; p
       case CHOICE  => val q = choiceRest( p );accept( RPAREN ); q
       case COMMA   => val q = seqRest( p );   accept( RPAREN ); q
diff --git a/src/library/scala/xml/dtd/DTD.scala b/src/library/scala/xml/dtd/DTD.scala
index d5bb85e..bfb9ad1 100644
--- a/src/library/scala/xml/dtd/DTD.scala
+++ b/src/library/scala/xml/dtd/DTD.scala
@@ -1,45 +1,35 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: DTD.scala 16857 2009-01-07 20:34:03Z cunei $
 
+package scala.xml
+package dtd
 
-package scala.xml.dtd
-
-import scala.collection.mutable.{HashMap, Map}
+import collection.mutable
+import mutable.HashMap
 
 /** A document type declaration.
  *
  *  @author Burak Emir
  */
 abstract class DTD {
-
-  var externalID: ExternalID = null
-
-  def notations: Seq[NotationDecl] = Nil
-
+  var externalID: ExternalID            = null
+  var decls: List[Decl]                 = Nil
+  def notations: Seq[NotationDecl]      = Nil
   def unparsedEntities: Seq[EntityDecl] = Nil
 
-  var elem: Map[String, ElemDecl]    = new HashMap[String, ElemDecl]()
-
-  var attr: Map[String, AttListDecl] = new HashMap[String, AttListDecl]()
-
-  var ent:  Map[String, EntityDecl]  = new HashMap[String, EntityDecl]()
-
-  var decls: List[Decl] = Nil
-
-  override def toString() = {
-    val sb = new StringBuilder("DTD [\n")
-    if (null != externalID)
-      sb.append(externalID.toString()).append('\n')
-    for (d <- decls) 
-      sb.append(d.toString()).append('\n')
-    sb.append("]").toString()
-  }
+  var elem: mutable.Map[String, ElemDecl]    = new HashMap[String, ElemDecl]()
+  var attr: mutable.Map[String, AttListDecl] = new HashMap[String, AttListDecl]()
+  var ent:  mutable.Map[String, EntityDecl]  = new HashMap[String, EntityDecl]()
 
+  override def toString() =
+    "DTD [\n%s%s]".format(
+      Option(externalID) getOrElse "",
+      decls.mkString("", "\n", "\n")
+    )
 }
diff --git a/src/library/scala/xml/dtd/Decl.scala b/src/library/scala/xml/dtd/Decl.scala
index 7c74cef..4394eca 100644
--- a/src/library/scala/xml/dtd/Decl.scala
+++ b/src/library/scala/xml/dtd/Decl.scala
@@ -1,41 +1,42 @@
 /*                     __                                               *\
  **     ________ ___   / /  ___     Scala API                            **
- **    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+ **    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
  **  __\ \/ /__/ __ |/ /__/ __ |    http://www.scala-lang.org/           **
  ** /____/\___/_/ |_/____/_/ | |                                         **
  **                          |/                                          **
  \*                                                                      */
 
-// $Id: Decl.scala 16857 2009-01-07 20:34:03Z cunei $
 
+package scala.xml
+package dtd
 
-package scala.xml.dtd
-
+import Utility.sbToString
 
 abstract class Decl
 
 abstract class MarkupDecl extends Decl {
-  def toString(sb: StringBuilder): StringBuilder
+  def buildString(sb: StringBuilder): StringBuilder
 }
 
 /** an element declaration 
  */
 case class ElemDecl(name: String, contentModel: ContentModel)
-extends MarkupDecl with DtdTypeSymbol {
-  override def toString(sb: StringBuilder): StringBuilder = {
+extends MarkupDecl
+{
+  override def buildString(sb: StringBuilder): StringBuilder = {
     sb
     .append("<!ELEMENT ")
     .append(name)
     .append(' ');
 
-    ContentModel.toString(contentModel, sb);
+    ContentModel.buildString(contentModel, sb);
     sb.append('>');
   }
 }
 
 case class AttListDecl(name: String, attrs:List[AttrDecl])
-extends MarkupDecl with DtdTypeSymbol {
-  override def toString(sb: StringBuilder): StringBuilder = {
+extends MarkupDecl {
+  override def buildString(sb: StringBuilder): StringBuilder = {
     sb
     .append("<!ATTLIST ")
     .append(name)
@@ -49,12 +50,11 @@ extends MarkupDecl with DtdTypeSymbol {
  *  directly.
  */
 case class AttrDecl(name: String, tpe: String, default: DefaultDecl) {
-  override def toString(): String = 
-    toString(new StringBuilder()).toString();
+  override def toString(): String = sbToString(buildString)
 
-  def toString(sb: StringBuilder): StringBuilder = {
+  def buildString(sb: StringBuilder): StringBuilder = {
     sb.append("  ").append(name).append(' ').append(tpe).append(' ');
-    default.toString(sb)
+    default.buildString(sb)
   }
 
 }
@@ -64,37 +64,37 @@ abstract class EntityDecl extends MarkupDecl
 
 /** a parsed general entity declaration */
 case class ParsedEntityDecl(name: String, entdef: EntityDef) extends EntityDecl {
-  override def toString(sb: StringBuilder): StringBuilder = {
+  override def buildString(sb: StringBuilder): StringBuilder = {
     sb.append("<!ENTITY ").append( name ).append(' ');
-    entdef.toString(sb).append('>')
+    entdef.buildString(sb).append('>')
   }
 }
 
 /** a parameter entity declaration */
 case class ParameterEntityDecl(name: String, entdef: EntityDef) extends EntityDecl {
-  override def toString(sb: StringBuilder): StringBuilder = {
+  override def buildString(sb: StringBuilder): StringBuilder = {
     sb.append("<!ENTITY % ").append( name ).append(' ');
-    entdef.toString(sb).append('>')
+    entdef.buildString(sb).append('>')
   }
 }
 
 /** an unparsed entity declaration */
 case class UnparsedEntityDecl( name:String, extID:ExternalID, notation:String ) extends EntityDecl {
-  override def toString(sb: StringBuilder): StringBuilder = {
+  override def buildString(sb: StringBuilder): StringBuilder = {
     sb.append("<!ENTITY ").append( name ).append(' ');
-    extID.toString(sb).append(" NDATA ").append(notation).append('>');
+    extID.buildString(sb).append(" NDATA ").append(notation).append('>');
   }
 }
 /** a notation declaration */
 case class NotationDecl( name:String, extID:ExternalID ) extends MarkupDecl {
-  override def toString(sb: StringBuilder): StringBuilder = {
+  override def buildString(sb: StringBuilder): StringBuilder = {
     sb.append("<!NOTATION ").append( name ).append(' ');
-    extID.toString(sb)
+    extID.buildString(sb)
   }
 }
 
 abstract class EntityDef {
-  def toString(sb: StringBuilder): StringBuilder
+  def buildString(sb: StringBuilder): StringBuilder
 }
 
 case class IntDef(value:String) extends EntityDef {
@@ -109,7 +109,7 @@ case class IntDef(value:String) extends EntityDef {
         val n = tmp.substring(ix, iz);
 
         if( !Utility.isName( n )) 
-          throw new IllegalArgumentException("interal entity def: \""+n+"\" must be an XML Name");
+          throw new IllegalArgumentException("internal entity def: \""+n+"\" must be an XML Name");
 
         tmp = tmp.substring(iz+1, tmp.length());
         ix  = tmp.indexOf('%');
@@ -118,14 +118,14 @@ case class IntDef(value:String) extends EntityDef {
   }
   validateValue();
 
-  override def toString(sb: StringBuilder): StringBuilder = 
+  override def buildString(sb: StringBuilder): StringBuilder = 
     Utility.appendQuoted(value, sb);
 
 }
 
 case class ExtDef(extID:ExternalID) extends EntityDef {
-  override def toString(sb: StringBuilder): StringBuilder = 
-    extID.toString(sb);
+  override def buildString(sb: StringBuilder): StringBuilder = 
+    extID.buildString(sb);
 }
 
 
@@ -134,7 +134,7 @@ case class PEReference(ent:String) extends MarkupDecl {
   if( !Utility.isName( ent )) 
     throw new IllegalArgumentException("ent must be an XML Name");
   
-  override def toString(sb: StringBuilder): StringBuilder = 
+  override def buildString(sb: StringBuilder): StringBuilder = 
     sb.append('%').append(ent).append(';');
 }
 
@@ -143,24 +143,22 @@ case class PEReference(ent:String) extends MarkupDecl {
 
 abstract class DefaultDecl {
   override def toString(): String
-  def toString(sb: StringBuilder): StringBuilder
+  def buildString(sb: StringBuilder): StringBuilder
 }
 
 case object REQUIRED extends DefaultDecl {
   override def toString(): String = "#REQUIRED"
-  override def toString(sb: StringBuilder) = sb.append("#REQUIRED")
+  override def buildString(sb: StringBuilder) = sb.append("#REQUIRED")
 }
 
 case object IMPLIED extends DefaultDecl {
   override def toString(): String = "#IMPLIED"
-  override def toString(sb: StringBuilder) = sb.append("#IMPLIED")
+  override def buildString(sb: StringBuilder) = sb.append("#IMPLIED")
 }
 
 case class DEFAULT(fixed: Boolean, attValue: String) extends DefaultDecl {
-  override def toString(): String = 
-    toString(new StringBuilder()).toString();
-
-  override def toString(sb: StringBuilder): StringBuilder = {
+  override def toString(): String = sbToString(buildString)
+  override def buildString(sb: StringBuilder): StringBuilder = {
     if (fixed) sb.append("#FIXED ")
     Utility.appendEscapedQuoted(attValue, sb)
   }
diff --git a/src/library/scala/xml/dtd/DocType.scala b/src/library/scala/xml/dtd/DocType.scala
index 997a32e..4e301a6 100644
--- a/src/library/scala/xml/dtd/DocType.scala
+++ b/src/library/scala/xml/dtd/DocType.scala
@@ -1,15 +1,14 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: DocType.scala 16857 2009-01-07 20:34:03Z cunei $
 
-
-package scala.xml.dtd
+package scala.xml
+package dtd
 
 /** An XML node for document type declaration.
  *
@@ -19,27 +18,17 @@ package scala.xml.dtd
  *  @param  extID  None, or Some(external ID of this doctype)
  *  @param  intSubset sequence of internal subset declarations
  */
-case class DocType(name: String, extID: ExternalID, intSubset: Seq[dtd.Decl]) {  
-
+case class DocType(name: String, extID: ExternalID, intSubset: Seq[dtd.Decl])
+{
   if (!Utility.isName(name))
-    throw new IllegalArgumentException(name+" must be an XML Name");
-
-  /** hashcode for this processing instruction */
-  final override def hashCode() =
-    name.hashCode() + 7 * extID.hashCode() + 41*intSubset.toList.hashCode();
+    throw new IllegalArgumentException(name+" must be an XML Name")
 
   /** returns "<!DOCTYPE + name + extID? + ("["+intSubSet+"]")? >" */
   final override def toString() = {
-    val sb = new StringBuilder("<!DOCTYPE ")
-    sb.append(name)
-    sb.append(' ')
-    sb.append(extID.toString())
-    if (intSubset.length > 0) {
-      sb.append('[')
-      for (d <- intSubset) sb.append(d.toString())
-      sb.append(']')
-    }
-    sb.append('>')
-    sb.toString()
+    def intString = 
+      if (intSubset.isEmpty) ""
+      else intSubset.mkString("[", "", "]")
+      
+    """<!DOCTYPE %s %s%s>""".format(name, extID.toString, intString)
   }
 }
diff --git a/src/library/scala/xml/dtd/DtdTypeSymbol.scala b/src/library/scala/xml/dtd/DtdTypeSymbol.scala
deleted file mode 100644
index 48dbf9f..0000000
--- a/src/library/scala/xml/dtd/DtdTypeSymbol.scala
+++ /dev/null
@@ -1,15 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://www.scala-lang.org/           **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: DtdTypeSymbol.scala 16857 2009-01-07 20:34:03Z cunei $
-
-
-package scala.xml.dtd
-
-
-trait DtdTypeSymbol
diff --git a/src/library/scala/xml/dtd/ElementValidator.scala b/src/library/scala/xml/dtd/ElementValidator.scala
index 5abee34..5a6c09c 100644
--- a/src/library/scala/xml/dtd/ElementValidator.scala
+++ b/src/library/scala/xml/dtd/ElementValidator.scala
@@ -1,34 +1,38 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://www.scala-lang.org/           **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: ElementValidator.scala 16857 2009-01-07 20:34:03Z cunei $
 
 
-package scala.xml.dtd
-
+package scala.xml
+package dtd
 
+import PartialFunction._
 import ContentModel.ElemName
+import MakeValidationException._    // @todo other exceptions
+
 import scala.util.automata._
+import scala.collection.mutable.BitSet
 
 /** validate children and/or attributes of an element
  *  exceptions are created but not thrown.
  */
 class ElementValidator() extends Function1[Node,Boolean] {
-
-  var exc: List[ValidationException] = Nil
+  
+  private var exc: List[ValidationException] = Nil
 
   protected var contentModel: ContentModel           = _
   protected var dfa:          DetWordAutom[ElemName] = _
   protected var adecls:       List[AttrDecl]         = _
 
   /** set content model, enabling element validation */
-  def setContentModel(cm:ContentModel) = {
-    contentModel = cm; cm match {
+  def setContentModel(cm: ContentModel) = {
+    contentModel = cm
+    cm match {
       case ELEMENTS(r) =>
         val nfa = ContentModel.Translator.automatonFrom(r, 1)
         dfa = new SubsetConstruction(nfa).determinize
@@ -42,134 +46,84 @@ class ElementValidator() extends Function1[Node,Boolean] {
   /** set meta data, enabling attribute validation */
   def setMetaData(adecls: List[AttrDecl]) { this.adecls = adecls }
 
-  def getIterator(nodes: Seq[Node], skipPCDATA: Boolean): Iterator[ElemName] = 
-    nodes.toList
-	 .filter { x => x match {
-           case y:SpecialNode => y match { 
-             
-             case a:Atom[_] if (a.data.isInstanceOf[String] && 
-                                a.data.asInstanceOf[String].trim.length == 0 ) => 
-                false; // always skip all-whitespace nodes
-
-              case _ => 
-                !skipPCDATA
-
-            }
-            case _ =>
-              x.namespace eq null
-          }}
-          . map { x => ElemName(x.label) }
-          . elements;
+  def getIterable(nodes: Seq[Node], skipPCDATA: Boolean): Iterable[ElemName] = {
+    def isAllWhitespace(a: Atom[_]) = cond(a.data) { case s: String if s.trim == "" => true }
+    
+    nodes.filter {
+      case y: SpecialNode => y match {
+        case a: Atom[_] if isAllWhitespace(a) => false  // always skip all-whitespace nodes
+        case _                                => !skipPCDATA
+      }
+      case x                                  => x.namespace eq null
+    } . map (x => ElemName(x.label))
+  }  
 
   /** check attributes, return true if md corresponds to attribute declarations in adecls.
    */
   def check(md: MetaData): Boolean = {
-    //@todo other exceptions
-    import MakeValidationException._;
-    val len: Int = exc.length;
-    var j = 0;
-    var ok = new scala.collection.mutable.BitSet(adecls.length);
-    def find(Key:String): AttrDecl = {
-      var attr: AttrDecl = null;
-      val jt = adecls.elements; while(j < adecls.length) {
-        jt.next match {
-          case a @ AttrDecl(Key, _, _) => attr = a; ok += j; j = adecls.length;
-          case _                       => j = j + 1;
+    val len: Int = exc.length
+    var ok = new BitSet(adecls.length)
+    
+    for (attr <- md) {
+      def attrStr = attr.value.toString
+      def find(Key: String): Option[AttrDecl] = {
+        adecls.zipWithIndex find {
+          case (a @ AttrDecl(Key, _, _), j) => ok += j ; return Some(a)
+          case _                            => false
         }
+        None
       }
-      attr
-    }
-    val it = md.elements; while(it.hasNext) {
-      val attr = it.next
-      j = 0
-      find(attr.key) match {
-
-        case null => 
-          //Console.println("exc");
-          exc = fromUndefinedAttribute( attr.key ) :: exc;
 
-        case AttrDecl(_, tpe, DEFAULT(true, fixedValue)) if(attr.value != fixedValue) => 
-          exc = fromFixedAttribute( attr.key, fixedValue, attr.value.toString) :: exc;
+      find(attr.key) match {
+        case None =>
+          exc ::= fromUndefinedAttribute(attr.key)
 
-        case s =>
-          //Console.println("s: "+s);
+        case Some(AttrDecl(_, tpe, DEFAULT(true, fixedValue))) if attrStr != fixedValue => 
+          exc ::= fromFixedAttribute(attr.key, fixedValue, attrStr)
 
+        case _ =>
       }
     }
     
-    //val missing = ok.toSet(false); FIXME: it doesn't seem to be used anywhere
-    j = 0
-    var kt = adecls.elements
-    while (kt.hasNext) {
-      kt.next match {
-        case AttrDecl(key, tpe, REQUIRED) if !ok(j) => 
-          exc = fromMissingAttribute( key, tpe ) :: exc;
-          j = j + 1;
-        case _ =>
-          j = j + 1;
-      }
+    adecls.zipWithIndex foreach {
+      case (AttrDecl(key, tpe, REQUIRED), j) if !ok(j) => exc ::= fromMissingAttribute(key, tpe)
+      case _ =>
     }
+
     exc.length == len //- true if no new exception
   }
 
   /** check children, return true if conform to content model
-   *  @pre contentModel != null
+   *  @note contentModel != null
    */
   def check(nodes: Seq[Node]): Boolean = contentModel match {
-    case ANY =>
-      true
-
-    case EMPTY =>
-      !getIterator(nodes, false).hasNext
-
-    case PCDATA =>
-      !getIterator(nodes, true).hasNext
-
-    case MIXED(ContentModel.Alt(branches @ _*))  => //@todo
+    case ANY    => true
+    case EMPTY  => getIterable(nodes, false).isEmpty
+    case PCDATA => getIterable(nodes, true).isEmpty
+    case MIXED(ContentModel.Alt(branches @ _*))  =>   // @todo
       val j = exc.length
-      def find(Key: String): Boolean = {
-        var res = false
-        val jt = branches.elements
-        while (jt.hasNext && !res) 
-          jt.next match { // !!! check for match translation problem
-            case ContentModel.Letter(ElemName(Key)) => res = true;
-            case _                                  =>
-          }
-        res
-      }
-    
-      var it = getIterator(nodes, true); while(it.hasNext) {
-        var label = it.next.name;
-        if (!find(label)) {
-          exc = MakeValidationException.fromUndefinedElement(label) :: exc;
-        }
+      def find(Key: String): Boolean =
+        branches exists { case ContentModel.Letter(ElemName(Key)) => true ; case _ => false }
+      
+      getIterable(nodes, true) map (_.name) filterNot find foreach {
+        exc ::= MakeValidationException fromUndefinedElement _
       }
+      (exc.length == j)   // - true if no new exception
 
-      (exc.length == j) //- true if no new exception
-
-    case _:ELEMENTS => 
-      var q = 0
-      val it = getIterator(nodes, false)
-      while (it.hasNext) {
-        val e = it.next      
-        dfa.delta(q).get(e) match {
-          case Some(p) => q = p
-          case _       => throw ValidationException("element "+e+" not allowed here")
+    case _: ELEMENTS =>
+      dfa isFinal {
+        getIterable(nodes, false).foldLeft(0) { (q, e) =>
+          (dfa delta q).getOrElse(e, throw ValidationException("element %s not allowed here" format e))
         }
       }
-      dfa.isFinal(q) //- true if arrived in final state
   }
 
   /** applies various validations - accumulates error messages in exc
-   *  @todo: fail on first error, ignore other errors (rearranging conditions)
+   *  @todo fail on first error, ignore other errors (rearranging conditions)
    */
-  def apply(n: Node): Boolean = {
+  def apply(n: Node): Boolean =
     //- ? check children
-    var res = (null == contentModel) || check( n.child );	  
-      
+    ((contentModel == null) || check(n.child)) &&
     //- ? check attributes
-    res = ((null == adecls) || check( n.attributes )) && res;      
-
-    res
-  }	
+    ((adecls == null) || check(n.attributes))
 }
diff --git a/src/library/scala/xml/dtd/ExternalID.scala b/src/library/scala/xml/dtd/ExternalID.scala
index b7a7a7c..b307f5c 100644
--- a/src/library/scala/xml/dtd/ExternalID.scala
+++ b/src/library/scala/xml/dtd/ExternalID.scala
@@ -1,31 +1,41 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://www.scala-lang.org/           **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: ExternalID.scala 16857 2009-01-07 20:34:03Z cunei $
-
-
-package scala.xml.dtd
 
+package scala.xml
+package dtd
 
 /** an ExternalIDs - either PublicID or SystemID
  *
  *  @author Burak Emir
  */
-abstract class ExternalID  {
-
-  /** returns "PUBLIC "+publicLiteral+" SYSTEM "+systemLiteral */
-  override def toString(): String
-
-  /** returns "PUBLIC "+publicLiteral+" SYSTEM "+systemLiteral */
-  def toString(sb: StringBuilder): StringBuilder
+abstract class ExternalID extends parsing.TokenTests
+{
+  def quoted(s: String) = {
+    val c = if (s contains '"') '\'' else '"'
+    c + s + c
+  }
 
+  // public != null: PUBLIC " " publicLiteral " " [systemLiteral]
+  // public == null: SYSTEM " " systemLiteral
+  override def toString(): String = {
+    lazy val quotedSystemLiteral = quoted(systemId)
+    lazy val quotedPublicLiteral = quoted(publicId)
+    
+    if (publicId == null) "SYSTEM " + quotedSystemLiteral
+    else "PUBLIC " + quotedPublicLiteral +
+      (if (systemId == null) "" else " " + quotedSystemLiteral)
+  }
+  def buildString(sb: StringBuilder): StringBuilder =
+    sb.append(this.toString())
+  
   def systemId: String
-
+  def publicId: String
 }
 
 /** a system identifier
@@ -33,18 +43,11 @@ abstract class ExternalID  {
  *  @author Burak Emir
  *  @param  systemLiteral the system identifier literal
  */
-case class SystemID(systemId: String) extends ExternalID with parsing.TokenTests {  
+case class SystemID(systemId: String) extends ExternalID {
+  val publicId = null
 
-  if( !checkSysID(systemId) )
-    throw new IllegalArgumentException(
-      "can't use both \" and ' in systemLiteral"
-    )
-  /** returns " SYSTEM "+systemLiteral */
-  override def toString() = 
-    Utility.systemLiteralToString(systemId)
-
-  override def toString(sb: StringBuilder): StringBuilder = 
-    Utility.systemLiteralToString(sb, systemId)
+  if (!checkSysID(systemId))
+    throw new IllegalArgumentException("can't use both \" and ' in systemId")
 }
 
 
@@ -54,17 +57,12 @@ case class SystemID(systemId: String) extends ExternalID with parsing.TokenTests
  *  @param  publicLiteral the public identifier literal
  *  @param  systemLiteral (can be null for notation pubIDs) the system identifier literal
  */
-case class PublicID(publicId: String, systemId: String)
-extends ExternalID with parsing.TokenTests {
-
+case class PublicID(publicId: String, systemId: String) extends ExternalID {
   if (!checkPubID(publicId))
-    throw new IllegalArgumentException(
-      "publicId must consist of PubidChars"
-    )
-  if ((systemId ne null) && !checkSysID(systemId))
-    throw new IllegalArgumentException(
-      "can't use both \" and ' in systemId"
-    )
+    throw new IllegalArgumentException("publicId must consist of PubidChars")
+
+  if (systemId != null && !checkSysID(systemId))
+    throw new IllegalArgumentException("can't use both \" and ' in systemId")
 
   /** the constant "#PI" */
   def label = "#PI"
@@ -74,18 +72,4 @@ extends ExternalID with parsing.TokenTests {
 
   /** always empty */
   def child = Nil
-
-  /** returns " PUBLIC "+publicId+" "+systemId */
-  override def toString() =
-    toString(new StringBuilder()).toString()
-
-  /** appends "PUBLIC "+publicId+" "+systemId to argument */
-  override def toString(sb: StringBuilder): StringBuilder = {
-    Utility.publicLiteralToString(sb, publicId)
-    if (systemId ne null) {
-      sb.append(' ')
-      Utility.appendQuoted(systemId, sb)
-    }
-    sb
-  }
 }
diff --git a/src/library/scala/xml/dtd/Scanner.scala b/src/library/scala/xml/dtd/Scanner.scala
index 0a96b1f..d6caa4c 100644
--- a/src/library/scala/xml/dtd/Scanner.scala
+++ b/src/library/scala/xml/dtd/Scanner.scala
@@ -1,16 +1,14 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Scanner.scala 16857 2009-01-07 20:34:03Z cunei $
-
-
-package scala.xml.dtd
 
+package scala.xml
+package dtd
 
 /** Scanner for regexps (content models in DTD element declarations) 
  *  todo: cleanup
@@ -28,7 +26,7 @@ class Scanner extends Tokens with parsing.TokenTests {
   /** initializes the scanner on input s */
   final def initScanner(s: String) {
     value = ""
-    it = (s).elements
+    it = (s).iterator
     token = 1+END
     next
     nextToken
@@ -49,10 +47,7 @@ class Scanner extends Tokens with parsing.TokenTests {
     if (c == d) next else error("expected '"+d+"' found '"+c+"' !");
   }
 
-  final def accS(ds: Seq[Char]) { 
-    val jt = ds.elements
-    while (jt.hasNext) { acc(jt.next) }
-  }
+  final def accS(ds: Seq[Char]) { ds foreach acc }
 
   final def readToken: Int = 
     if (isSpace(c)) {
diff --git a/src/library/scala/xml/dtd/Tokens.scala b/src/library/scala/xml/dtd/Tokens.scala
index a20d1e5..94f6b9a 100644
--- a/src/library/scala/xml/dtd/Tokens.scala
+++ b/src/library/scala/xml/dtd/Tokens.scala
@@ -1,15 +1,15 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://www.scala-lang.org/           **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Tokens.scala 16857 2009-01-07 20:34:03Z cunei $
 
 
-package scala.xml.dtd
+package scala.xml
+package dtd
 
 
 class Tokens {
diff --git a/src/library/scala/xml/dtd/ValidationException.scala b/src/library/scala/xml/dtd/ValidationException.scala
index 3d490f4..3aeea5c 100644
--- a/src/library/scala/xml/dtd/ValidationException.scala
+++ b/src/library/scala/xml/dtd/ValidationException.scala
@@ -1,15 +1,15 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://www.scala-lang.org/           **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: ValidationException.scala 16857 2009-01-07 20:34:03Z cunei $
 
 
-package scala.xml.dtd
+package scala.xml
+package dtd
 
 
 case class ValidationException(e: String) extends Exception(e)
@@ -31,17 +31,13 @@ object MakeValidationException {
   def fromUndefinedAttribute(key: String) = 
     new ValidationException("attribute " + key +" not allowed here")
 
-  def fromMissingAttribute(allKeys: scala.collection.Set[String]) = {
+  def fromMissingAttribute(allKeys: Set[String]) = {
     val sb = new StringBuilder("missing value for REQUIRED attribute")
     if (allKeys.size > 1) sb.append('s');
-    val it = allKeys.elements
-    while (it.hasNext) {
-      sb.append('\'').append(it.next).append('\'') 
-    }
+    allKeys foreach (k => sb append "'%s'".format(k))
     new ValidationException(sb.toString())
   }
 
   def fromMissingAttribute(key: String, tpe: String) =
-    new ValidationException("missing value for REQUIRED attribute "+key+" of type "+tpe)
-
+    new ValidationException("missing value for REQUIRED attribute %s of type %s".format(key, tpe))
 }
diff --git a/src/library/scala/xml/factory/Binder.scala b/src/library/scala/xml/factory/Binder.scala
index 53e3d5b..3796fe8 100644
--- a/src/library/scala/xml/factory/Binder.scala
+++ b/src/library/scala/xml/factory/Binder.scala
@@ -1,18 +1,17 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Binder.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.xml.factory
+package scala.xml
+package factory
 
-
-import scala.xml.parsing.ValidatingMarkupHandler
+import parsing.ValidatingMarkupHandler
 
 /**
  *  @author Burak Emir
diff --git a/src/library/scala/xml/factory/LoggedNodeFactory.scala b/src/library/scala/xml/factory/LoggedNodeFactory.scala
index a8f3db7..b0574ba 100644
--- a/src/library/scala/xml/factory/LoggedNodeFactory.scala
+++ b/src/library/scala/xml/factory/LoggedNodeFactory.scala
@@ -1,15 +1,15 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: LoggedNodeFactory.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.xml.factory
+package scala.xml
+package factory
 
 
 /** <p>
@@ -58,7 +58,7 @@ with scala.util.logging.Logged {
     if (logNode)
       log("[makeNode for "+label+"]");
 
-    val hash = Utility.hashCode(pre, label, attrSeq.hashCode(), scope.hashCode(), children)
+    val hash = Utility.hashCode(pre, label, attrSeq.##, scope.##, children)
 
     /*
     if(logCompressLevel >= FULL) {
diff --git a/src/library/scala/xml/factory/NodeFactory.scala b/src/library/scala/xml/factory/NodeFactory.scala
index 7edd19d..8e04b3e 100644
--- a/src/library/scala/xml/factory/NodeFactory.scala
+++ b/src/library/scala/xml/factory/NodeFactory.scala
@@ -1,77 +1,61 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: NodeFactory.scala 16894 2009-01-13 13:09:41Z cunei $
 
+package scala.xml
+package factory
 
-package scala.xml.factory;
+import parsing.{ FactoryAdapter, NoBindingFactoryAdapter }
+import java.io.{ InputStream, Reader, StringReader, File, FileDescriptor, FileInputStream }
 
-
-trait NodeFactory[A <: Node] {
-
-  val ignoreComments  = false;
-  val ignoreProcInstr = false;
+trait NodeFactory[A <: Node]
+{
+  val ignoreComments  = false
+  val ignoreProcInstr = false
 
   /* default behaviour is to use hash-consing */
-  val cache = new collection.mutable.HashMap[Int, List[A]]();
+  val cache = new collection.mutable.HashMap[Int, List[A]]
 
-  protected def create(pre: String, name: String, attrs: MetaData, scope: NamespaceBinding, children:Seq[Node]): A;
+  protected def create(pre: String, name: String, attrs: MetaData, scope: NamespaceBinding, children:Seq[Node]): A
   
   protected def construct(hash: Int, old:List[A], pre: String, name: String, attrSeq:MetaData, scope: NamespaceBinding, children:Seq[Node]): A = {
-    val el = create(pre, name, attrSeq, scope, children);
-    cache.update( hash, el::old );
+    val el = create(pre, name, attrSeq, scope, children)
+    cache.update(hash, el :: old)
     el
   }
   
-  /** faster equality, because */
-  def eqElements(ch1:Seq[Node], ch2:Seq[Node]): Boolean = {
-    (ch1.length == ch2.length) && {
-      val it1 = ch1.elements;
-      val it2 = ch2.elements;
-      var res = true;
-      while(res && it1.hasNext) {
-        res = it1.next.eq(it2.next);
-      }
-      res
-    }
-  }
-
-  def nodeEquals(n: Node, pre: String, name: String, attrSeq:MetaData, scope: NamespaceBinding, children:Seq[Node]) = (
-    (n.prefix == pre)
-    &&(n.label == name)
-    &&(n.attributes == attrSeq)
-  // scope??
-    &&(eqElements(n.child,children)));
+  def eqElements(ch1: Seq[Node], ch2: Seq[Node]): Boolean =
+    ch1.view.zipAll(ch2.view, null, null) forall { case (x,y) => x eq y }
+
+  def nodeEquals(n: Node, pre: String, name: String, attrSeq:MetaData, scope: NamespaceBinding, children: Seq[Node]) =
+    n.prefix == pre &&
+    n.label == name &&
+    n.attributes == attrSeq && 
+    // scope?
+    eqElements(n.child, children)
   
-  def makeNode(pre: String, name: String, attrSeq:MetaData, scpe: NamespaceBinding, children:Seq[Node]): A = {
-    //Console.println("NodeFactory::makeNode("+pre+","+name+","+attrSeq+","+scpe+","+children+")");
-    val hash    = Utility.hashCode( pre, name, attrSeq.hashCode(), scpe.hashCode(), children ) ;
-    cache.get( hash ) match {
-      case Some(list) => // find structurally equal
-        val it     = list.elements;
-        val lookup = it.find { x => nodeEquals(x, pre, name, attrSeq, scpe, children) };
-        lookup match {
-          case Some(x) =>         
-            //Console.println("[cache hit !]"+x);
-            x; // return cached elem
-          case _       => construct(hash, list, pre, name, attrSeq, scpe, children);
+  def makeNode(pre: String, name: String, attrSeq: MetaData, scope: NamespaceBinding, children: Seq[Node]): A = {
+    val hash = Utility.hashCode( pre, name, attrSeq.##, scope.##, children)
+    def cons(old: List[A]) = construct(hash, old, pre, name, attrSeq, scope, children)
+    
+    (cache get hash) match {
+      case Some(list) =>    // find structurally equal
+        list.find(nodeEquals(_, pre, name, attrSeq, scope, children)) match {
+          case Some(x)    => x
+          case _          => cons(list)
         }
-      case _          => construct(hash, Nil, pre, name, attrSeq, scpe, children)
+      case None           => cons(Nil)
     }
   }
   
-  def makeText(s: String) = 
-    Text( s );
-
-  def makeComment(s: String): Seq[Comment] = 
-    if(ignoreComments) Nil else List(Comment( s ));
-
-  def makeProcInstr(t: String, s: String): Seq[ProcInstr] = 
-    if(ignoreProcInstr) Nil else List(ProcInstr(t, s));
-  
+  def makeText(s: String) = Text(s)
+  def makeComment(s: String): Seq[Comment]  = 
+    if (ignoreComments) Nil else List(Comment(s))
+  def makeProcInstr(t: String, s: String): Seq[ProcInstr] =
+    if (ignoreProcInstr) Nil else List(ProcInstr(t, s))
 }
diff --git a/src/library/scala/xml/factory/XMLLoader.scala b/src/library/scala/xml/factory/XMLLoader.scala
new file mode 100644
index 0000000..aff3907
--- /dev/null
+++ b/src/library/scala/xml/factory/XMLLoader.scala
@@ -0,0 +1,60 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |                                         **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+package scala.xml
+package factory
+
+import javax.xml.parsers.SAXParserFactory
+import parsing.{ FactoryAdapter, NoBindingFactoryAdapter }
+import java.io.{ InputStream, Reader, StringReader, File, FileDescriptor, FileInputStream }
+import java.net.URL
+
+/** Presents collection of XML loading methods which use the parser
+ *  created by "def parser".
+ */ 
+trait XMLLoader[T <: Node]
+{
+  import scala.xml.Source._
+  def adapter: FactoryAdapter = new NoBindingFactoryAdapter()
+  
+  /* Override this to use a different SAXParser. */
+  def parser: SAXParser = {
+    val f = SAXParserFactory.newInstance()
+    f.setNamespaceAware(false)
+    f.newSAXParser()
+  }
+  
+  /** Loads XML from the given InputSource, using the supplied parser.
+   *  The methods available in scala.xml.XML use the XML parser in the JDK.
+   */
+  def loadXML(source: InputSource, parser: SAXParser): T = {
+    val newAdapter = adapter
+    
+    newAdapter.scopeStack push TopScope
+    parser.parse(source, newAdapter)
+    newAdapter.scopeStack.pop
+    
+    newAdapter.rootElem.asInstanceOf[T]
+  }
+
+  /** Loads XML from the given file, file descriptor, or filename. */
+  def loadFile(file: File): T          = loadXML(fromFile(file), parser)
+  def loadFile(fd: FileDescriptor): T  = loadXML(fromFile(fd), parser)
+  def loadFile(name: String): T        = loadXML(fromFile(name), parser)
+  
+  /** loads XML from given InputStream, Reader, sysID, InputSource, or URL. */
+  def load(is: InputStream): T         = loadXML(fromInputStream(is), parser)
+  def load(reader: Reader): T          = loadXML(fromReader(reader), parser)
+  def load(sysID: String): T           = loadXML(fromSysId(sysID), parser)
+  def load(source: InputSource): T     = loadXML(source, parser)
+  def load(url: URL): T                = loadXML(fromInputStream(url.openStream()), parser)
+
+  /** Loads XML from the given String. */
+  def loadString(string: String): T    = loadXML(fromString(string), parser)
+}
diff --git a/src/library/scala/xml/include/CircularIncludeException.scala b/src/library/scala/xml/include/CircularIncludeException.scala
index 3227c86..1dc566f 100644
--- a/src/library/scala/xml/include/CircularIncludeException.scala
+++ b/src/library/scala/xml/include/CircularIncludeException.scala
@@ -1,14 +1,14 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: CircularIncludeException.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.xml.include
+package scala.xml
+package include
 
 /**
  * <p>
diff --git a/src/library/scala/xml/include/UnavailableResourceException.scala b/src/library/scala/xml/include/UnavailableResourceException.scala
index ad4262f..fd67423 100644
--- a/src/library/scala/xml/include/UnavailableResourceException.scala
+++ b/src/library/scala/xml/include/UnavailableResourceException.scala
@@ -1,14 +1,14 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: UnavailableResourceException.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.xml.include
+package scala.xml
+package include
 
 /**
  * <p>
diff --git a/src/library/scala/xml/include/XIncludeException.scala b/src/library/scala/xml/include/XIncludeException.scala
index 5ab1659..02c45e1 100644
--- a/src/library/scala/xml/include/XIncludeException.scala
+++ b/src/library/scala/xml/include/XIncludeException.scala
@@ -1,14 +1,14 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: XIncludeException.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.xml.include
+package scala.xml
+package include
 
 /**
  * <p>
@@ -42,7 +42,7 @@ class XIncludeException(message: String) extends Exception(message) {
    * This method allows you to store the original exception.
    *
    * @param   nestedException   the underlying exception which 
-   caused the XIncludeException to be thrown
+   * caused the XIncludeException to be thrown
    */
   def setRootCause(nestedException: Throwable ) {
     this.rootCause = nestedException
diff --git a/src/library/scala/xml/include/sax/EncodingHeuristics.scala b/src/library/scala/xml/include/sax/EncodingHeuristics.scala
index 01defb4..0381320 100644
--- a/src/library/scala/xml/include/sax/EncodingHeuristics.scala
+++ b/src/library/scala/xml/include/sax/EncodingHeuristics.scala
@@ -1,177 +1,105 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: EncodingHeuristics.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.xml.include.sax
+package scala.xml
+package include.sax
+import scala.xml.include._
 
-import java.io.{IOException, InputStreamReader, InputStream}
+import java.io.InputStream
+import scala.util.matching.Regex
 
 /**
  * <p>
  * <code>EncodingHeuristics</code> reads from a stream
  * (which should be buffered) and attempts to guess
  * what the encoding of the text in the stream is.
- * Byte order marks are stripped from the stream.
  * If it fails to determine the type of the encoding,
  * it returns the default UTF-8. 
  * </p>
- * <p>
- *   Translated from Elliotte Rusty Harold's Java source
- * </p>
  *
  * @author Burak Emir
+ * @author Paul Phillips
  */
-object EncodingHeuristics {
+object EncodingHeuristics
+{
+  object EncodingNames {
+    // UCS-4 isn't yet implemented in java releases anyway...
+    val bigUCS4       = "UCS-4"
+    val littleUCS4    = "UCS-4"
+    val unusualUCS4   = "UCS-4"
+    val bigUTF16      = "UTF-16BE"
+    val littleUTF16   = "UTF-16LE"
+    val utf8          = "UTF-8"
+    val default       = utf8
+  }
+  import EncodingNames._
 
   /**
     * <p>
-    * This utility method ????.
+    * This utility method attempts to determine the XML character encoding
+    * by examining the input stream, as specified here:
+    *    http://www.w3.org/TR/xml/#sec-guessing
     * </p>
     *
     * @param in   <code>InputStream</code> to read from. 
     * @return String  The name of the encoding.
-    * @throws IOException if the stream cannot be reset back to where it was when
-    *                     the method was invoked.
+    * @throws IOException if the stream cannot be reset
     */    
   def readEncodingFromStream(in: InputStream): String = {
-    //System.err.println("EncodingHeuristics::readEncodingFromStream");
+    var ret: String = null    
+    val bytesToRead = 1024 // enough to read most XML encoding declarations
+    def resetAndRet = { in.reset ; ret }
+    
     // This may fail if there are a lot of space characters before the end
     // of the encoding declaration
-    in.mark(1024)
-    var ret: String = null
-    try {
-      // lots of things can go wrong here. If any do, I just return null
-      // so that we'll fall back on the encoding declaration or the
-      // UTF-8 default
-      val byte1 = in.read()
-      val byte2 = in.read()
-      if (byte1 == 0xFE && byte2 == 0xFF) {
-        // don't reset because the byte order mark should not be included????
-        ret =  "UnicodeBig"; // name for big-endian????         
-      }
-      else if (byte1 == 0xFF && byte2 == 0xFE) {
-        // don't reset because the byte order mark should not be included????
-        // will the reader throw away the byte order mark or will it return it????
-        ret =  "UnicodeLittle"  
-      }
-
-      /* In accordance with the Character Model [Character Model], 
-       when the text format is a Unicode encoding, the XInclude 
-       processor must fail the inclusion when the text in the 
-       selected range is non-normalized. When transcoding characters 
-       to a Unicode encoding from a legacy encoding, a normalizing transcoder must be used. */
-      
-      val byte3 = in.read()
-      // check for UTF-8 byte order mark
-      if (byte1 == 0xEF && byte2 == 0xBB && byte3 == 0xBF) {
-        // don't reset because the byte order mark should not be included????
-        // in general what happens if text document includes non-XML legal chars????
-        ret =  "UTF-8";          
-      }
-      
-      val byte4 = in.read();
-      if (byte1 == 0x00 && byte2 == 0x00 && byte3 == 0xFE && byte4 == 0xFF) {
-        // don't reset because the byte order mark should not be included????
-        ret =  "UCS-4"; // right name for big-endian UCS-4 in Java 1.4????         
-      }
-      else if (byte1 == 0x00 && byte2 == 0x00 && byte3 == 0xFF && byte4 == 0xFE) {
-        // don't reset because the byte order mark should not be included????
-        ret =  "UCS-4"; // right name for little-endian UCS-4 in Java 1.4????         
-      }
+    in mark bytesToRead
+    val bytes = (in.read, in.read, in.read, in.read)
+    
+    // first look for byte order mark
+    ret = bytes match {
+      case (0x00, 0x00, 0xFE, 0xFF) => bigUCS4
+      case (0xFF, 0xFE, 0x00, 0x00) => littleUCS4
+      case (0x00, 0x00, 0xFF, 0xFE) => unusualUCS4
+      case (0xFE, 0xFF, 0x00, 0x00) => unusualUCS4
+      case (0xFE, 0xFF, _   , _   ) => bigUTF16
+      case (0xFF, 0xFE, _   , _   ) => littleUTF16
+      case (0xEF, 0xBB, 0xBF, _   ) => utf8
+      case _                        => null
+    }
+    if (ret != null)
+      return resetAndRet
+    
+    def readASCIIEncoding: String = {
+      val data = new Array[Byte](bytesToRead - 4)
+      val length = in.read(data, 0, bytesToRead - 4)
 
-      // no byte order mark present; first character must be 
-      // less than sign or white space
-      // Let's look for less-than signs first
-      if (byte1 == 0x00 && byte2 == 0x00 && byte3 == 0x00 && byte4 == '<') {
-        in.reset()
-        ret =  "UCS-4"  // right name for big-endian UCS-4 in Java 1.4????
-      }
-      else if (byte1 == '<' && byte2 == 0x00 && byte3 == 0x00 && byte4 == 0x00) {
-        in.reset()
-        ret =  "UCS-4"  // right name for little-endian UCS-4 in Java 1.4????
-      }
-      else if (byte1 == 0x00 && byte2 == '<' && byte3 == 0x00 && byte4 == '?') {
-        in.reset()
-        ret =  "UnicodeBigUnmarked"
-      }
-      else if (byte1 == '<' && byte2 == 0x00 && byte3 == '?' && byte4 == 0x00) {
-        in.reset()
-        ret =  "UnicodeLittleUnmarked" 
+      // Use Latin-1 (ISO-8859-1) because all byte sequences are legal.
+      val declaration = new String(data, 0, length, "ISO-8859-1")
+      val regexp = """(?m).*?encoding\s*=\s*["'](.+?)['"]""".r
+      (regexp findFirstMatchIn declaration) match {
+        case None     => default
+        case Some(md) => md.subgroups(0)
       }
-      else if (byte1 == '<' && byte2 == '?' && byte3 == 'x' && byte4 == 'm') {
-        // ASCII compatible, must read encoding declaration 
-        // 1024 bytes will be far enough to read most XML declarations
-        val data = new Array[Byte](1024)
-        data(0) = byte1.asInstanceOf[Byte]
-        data(1) = byte2.asInstanceOf[Byte]
-        data(2) = byte3.asInstanceOf[Byte]
-        data(3) = byte4.asInstanceOf[Byte]
-        val length = in.read(data, 4, 1020) + 4;
-        // Use Latin-1 (ISO-8859-1) because it's ASCII compatible and
-        // all byte sequences are legal Latin-1 sequences so I don't have
-        // to worry about encoding errors if I slip past the 
-        // end of the XML/text declaration
-        val declaration = new String(data, 0, length, "8859_1");
-        // if any of these throw a StringIndexOutOfBoundsException
-        // we just fall into the catch bloclk and return null
-        // since this can't be well-formed XML
-        var position = declaration.indexOf("encoding") + 8;
-        var c: Char = '\0'  // bogus init value
-        // get rid of white space before equals sign
-        do {
-          c = declaration.charAt(position)
-          position += 1        
-        } while (c == ' ' || c == '\t' || c == '\r' || c == '\n') ;
-        if (c != '=') { // malformed
-          in.reset()
-          ret =  "UTF-8"
-        }
-        // get rid of white space after equals sign
-        do {
-          c = declaration.charAt(position)
-          position += 1
-        } while (c == ' ' || c == '\t' || c == '\r' || c == '\n') ;
-        var delimiter: Char = c
-        if (delimiter != '\'' && delimiter != '"') { // malformed
-          in.reset()
-          ret =  "UTF-8"
-        }
-        // now positioned to read encoding name
-        val encodingName = new StringBuffer()
-        do {
-          c = declaration.charAt(position)
-          position += 1
-          encodingName.append(c)
-        } while(c != delimiter)
-        encodingName.setLength(encodingName.length() - 1)  // rm delim
-        in.reset()
-        ret =  encodingName.toString()
-      }
-        else if (byte1 == 0x4C && byte2 == 0x6F && byte3 == 0xA7 && byte4 == 0x94) {
-          // EBCDIC compatible, must read encoding declaration 
-          // ???? 
-        }
-      
-    } catch { 
-      case e: Exception =>
-        in.reset()
-        ret = "UTF-8"
     }
-
-    // no XML or text declaration present
-    //System.err.println("exit EncodingHeuristics::readEncodingFromStream");
-
-    if (ret != null)
-      ret
-    else {
-      in.reset()
-      "UTF-8"
+          
+    // no byte order mark present; first character must be '<' or whitespace        
+    ret = bytes match {    
+      case (0x00, 0x00, 0x00, '<' ) => bigUCS4
+      case ('<' , 0x00, 0x00, 0x00) => littleUCS4
+      case (0x00, 0x00, '<' , 0x00) => unusualUCS4
+      case (0x00, '<' , 0x00, 0x00) => unusualUCS4
+      case (0x00, '<' , 0x00, '?' ) => bigUTF16     // XXX must read encoding
+      case ('<' , 0x00, '?' , 0x00) => littleUTF16  // XXX must read encoding
+      case ('<' , '?' , 'x' , 'm' ) => readASCIIEncoding
+      case (0x4C, 0x6F, 0xA7, 0x94) => utf8         // XXX EBCDIC
+      case _                        => utf8         // no XML or text declaration present
     }
-  }  
+    resetAndRet
+  }
 }
diff --git a/src/library/scala/xml/include/sax/Main.scala b/src/library/scala/xml/include/sax/Main.scala
index f889575..e4f644b 100644
--- a/src/library/scala/xml/include/sax/Main.scala
+++ b/src/library/scala/xml/include/sax/Main.scala
@@ -1,106 +1,82 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Main.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.xml.include.sax
+package scala.xml
+package include.sax
 
-import org.xml.sax.SAXException
-import org.xml.sax.SAXParseException
-import org.xml.sax.EntityResolver
-import org.xml.sax.helpers.XMLReaderFactory
+import scala.xml.include._
+import scala.util.control.Exception.{ catching, ignoring }
 import org.xml.sax.XMLReader
+import org.xml.sax.helpers.XMLReaderFactory
 
 object Main {
+  private val namespacePrefixes = "http://xml.org/sax/features/namespace-prefixes"
+  private val lexicalHandler = "http://xml.org/sax/properties/lexical-handler"
   
-    /**
-      * The driver method for xinc
-      * Output is written to System.out via Conolse
-      * </p>
-      *
-      * @param args  contains the URLs and/or filenames
-      *              of the documents to be procesed.
-      */
-    def main(args: Array[String]) {
-      var parser: XMLReader = null
-      var err = false
-      try {
-        parser = XMLReaderFactory.createXMLReader()
-      } 
-      catch { 
-        case e:SAXException =>
-          try {
-            parser = XMLReaderFactory.createXMLReader(
-              "org.apache.xerces.parsers.SAXParser")
-          } catch {
-            case e2:SAXException =>
-              System.err.println("Could not find an XML parser")
-              err = true
-          }
-      }
+  /**
+  * The driver method for xinc
+  * Output is written to System.out via Conolse
+  * </p>
+  *
+  * @param args  contains the URLs and/or filenames
+  *              of the documents to be processed.
+  */
+  def main(args: Array[String]) {
+    def saxe[T](body: => T) = catching[T](classOf[SAXException]) opt body
+    def error(msg: String) = System.err.println(msg)
+    
+    val parser: XMLReader =
+      saxe[XMLReader](XMLReaderFactory.createXMLReader()) getOrElse (
+        saxe[XMLReader](XMLReaderFactory.createXMLReader(XercesClassName)) getOrElse (
+          return error("Could not find an XML parser")
+        )
+      )
 
-      if(err) return;
-      // Need better namespace handling
+    // Need better namespace handling    
+    try parser.setFeature(namespacePrefixes, true)
+    catch { case e: SAXException => return System.err.println(e) }
+    
+    if (args.isEmpty)
+      return
+    
+    def dashR = args.size >= 2 && args(0) == "-r"
+    val args2 = if (dashR) args drop 2 else args
+    val resolver: Option[EntityResolver] =
+      if (dashR) None
+      else catching(classOf[Exception]) opt {
+          val r = Class.forName(args(1)).newInstance().asInstanceOf[EntityResolver]
+          parser setEntityResolver r
+          r
+        } orElse (return error("Could not load requested EntityResolver"))
+    
+    for (arg <- args2) {
       try {
-        parser.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
-      }
-      catch { 
-        case e:SAXException =>
-          System.err.println(e)
-          err = true
-      }   
-      if (err) return
-      
-      if (args.length == 0) return
-      var resolver: EntityResolver = null
-      var arg: Int = 0
-      if (args(0).equals("-r")) {
-        try {
-          resolver = Class.forName(args(1)).newInstance().asInstanceOf[EntityResolver];
-          parser.setEntityResolver(resolver);
-        }
-        catch { 
-          case ex:Exception => 
-            System.err.println("Could not load requested EntityResolver")
-            err = true
+        val includer = new XIncludeFilter()
+        includer setParent parser
+        val s = new XIncluder(System.out, "UTF-8")
+        includer setContentHandler s
+        
+        resolver map (includer setEntityResolver _)
+        // SAXException here means will not support comments
+        ignoring(classOf[SAXException]) {
+          includer.setProperty(lexicalHandler, s)
+          s setFilter includer
         }
-        arg = 2
+        includer parse arg
       }
-      if (err) return
-      
-      while (arg < args.length) {
-        try {
-          val includer = new XIncludeFilter();
-          includer.setParent(parser)
-          val s = new XIncluder(System.out, "UTF-8")
-          includer.setContentHandler(s)
-          if (resolver != null) includer.setEntityResolver(resolver)
-          try {
-            includer.setProperty(
-              "http://xml.org/sax/properties/lexical-handler",
-              s)
-            s.setFilter(includer)
-          }
-          catch { 
-            case e:SAXException => // Will not support comments
-          }
-          includer.parse(args(arg))
-        }
-        catch { 
-          case e:SAXParseException =>
-            System.err.println(e)
-            System.err.println("Problem in " + e.getSystemId() 
-                               + " at line " + e.getLineNumber())
-          case e: Exception => // be specific about exceptions????
-            System.err.println(e)
-            e.printStackTrace()
-        }
-        arg += 1
+      catch {
+        case e: SAXParseException =>
+          error(e.toString)
+          error("Problem in %s at line %d".format(e.getSystemId, e.getLineNumber))
+        case e: SAXException =>
+          error(e.toString)          
       }
     }
+  }
 }
diff --git a/src/library/scala/xml/include/sax/XIncludeFilter.scala b/src/library/scala/xml/include/sax/XIncludeFilter.scala
index 9922894..cac457c 100644
--- a/src/library/scala/xml/include/sax/XIncludeFilter.scala
+++ b/src/library/scala/xml/include/sax/XIncludeFilter.scala
@@ -1,34 +1,23 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: XIncludeFilter.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.xml.include.sax
+package scala.xml
+package include.sax
 
-import org.xml.sax.Attributes
-import org.xml.sax.SAXException
-import org.xml.sax.XMLReader
-import org.xml.sax.EntityResolver
-import org.xml.sax.Locator
-import org.xml.sax.helpers.XMLReaderFactory
-import org.xml.sax.helpers.XMLFilterImpl
-import org.xml.sax.helpers.NamespaceSupport
-import org.xml.sax.helpers.AttributesImpl
+import scala.xml.include._
 
-import java.net.URL
-import java.net.URLConnection
-import java.net.MalformedURLException
-import java.io.UnsupportedEncodingException
-import java.io.IOException
-import java.io.InputStream
-import java.io.BufferedInputStream
-import java.io.InputStreamReader
+import org.xml.sax.{ Attributes, XMLReader, Locator }
+import org.xml.sax.helpers.{ XMLReaderFactory, XMLFilterImpl, NamespaceSupport, AttributesImpl }
+
+import java.io.{ InputStream, BufferedInputStream, InputStreamReader, IOException, UnsupportedEncodingException }
 import java.util.Stack
+import java.net.{ URL, MalformedURLException }
 
 /**
  * <p>
@@ -362,61 +351,49 @@ class XIncludeFilter extends XMLFilterImpl {
                            be downloaded from the specified URL.
     */
   private def includeXMLDocument(url: String) {
-    var source: URL = null
-    try {
-      val base = bases.peek().asInstanceOf[URL]
-      source = new URL(base, url)
-    }
-    catch { 
-      case e:MalformedURLException => 
-        val ex = new UnavailableResourceException("Unresolvable URL " + url
-                                                  + getLocation());
-        ex.setRootCause(e)
-        throw new SAXException("Unresolvable URL " + url + getLocation(), ex)
-    }
-
-    try {
-      // make this more robust
-      var parser: XMLReader = null
-      try {
-        parser = XMLReaderFactory.createXMLReader()       
-      } catch {
-        case e:SAXException =>
-          try {
-            parser = XMLReaderFactory.createXMLReader(
-              "org.apache.xerces.parsers.SAXParser"
-            );
-          } catch {
-            case e2: SAXException =>
-              System.err.println("Could not find an XML parser")
-          }
+    val source =
+      try new URL(bases.peek(), url)
+      catch {
+        case e: MalformedURLException =>
+          val ex = new UnavailableResourceException("Unresolvable URL " + url + getLocation())
+          ex setRootCause e
+          throw new SAXException("Unresolvable URL " + url + getLocation(), ex)
       }
-      if(parser != null) {
-        parser.setContentHandler(this)
-        val resolver = this.getEntityResolver()
-        if (resolver != null) parser.setEntityResolver(resolver);
-        // save old level and base
-        val previousLevel = level
-        this.level = 0
-        if (bases.contains(source)) {
-          val e = new CircularIncludeException(
-            "Circular XInclude Reference to " + source + getLocation()
-          );
-          throw new SAXException("Circular XInclude Reference", e)
+    
+    try {
+      val parser: XMLReader =
+        try XMLReaderFactory.createXMLReader()
+        catch {
+          case e: SAXException  =>
+            try XMLReaderFactory.createXMLReader(XercesClassName)
+            catch { case _: SAXException => return System.err.println("Could not find an XML parser") }
         }
-        bases.push(source)
-        atRoot = true
-        parser.parse(source.toExternalForm())
-        // restore old level and base
-        this.level = previousLevel
-        bases.pop()
-      }
+
+      parser setContentHandler this
+      val resolver = this.getEntityResolver()
+      if (resolver != null)
+        parser setEntityResolver resolver
+        
+      // save old level and base
+      val previousLevel = level
+      this.level = 0
+      if (bases contains source)
+        throw new SAXException(
+          "Circular XInclude Reference",
+          new CircularIncludeException("Circular XInclude Reference to " + source + getLocation())
+        )
+
+      bases push source
+      atRoot = true
+      parser parse source.toExternalForm()
+      
+      // restore old level and base
+      this.level = previousLevel
+      bases.pop()
     }
     catch { 
-      case e:IOException =>
-        throw new SAXException("Document not found: " 
-                               + source.toExternalForm() + getLocation(), e)
+      case e: IOException =>
+        throw new SAXException("Document not found: " + source.toExternalForm() + getLocation(), e)
     }
-    
   }
 }
diff --git a/src/library/scala/xml/include/sax/XIncluder.scala b/src/library/scala/xml/include/sax/XIncluder.scala
index b4082ab..0b06bba 100644
--- a/src/library/scala/xml/include/sax/XIncluder.scala
+++ b/src/library/scala/xml/include/sax/XIncluder.scala
@@ -1,29 +1,21 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: XIncluder.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.xml.include.sax
+package scala.xml
+package include.sax
 
-import org.xml.sax.SAXException
-import org.xml.sax.SAXParseException
-import org.xml.sax.ContentHandler
-import org.xml.sax.EntityResolver
-import org.xml.sax.helpers.XMLReaderFactory
-import org.xml.sax.XMLReader
-import org.xml.sax.Locator
-import org.xml.sax.Attributes
-import org.xml.sax.ext.LexicalHandler
+import scala.xml.include._
+import collection.mutable.Stack
 
-import java.io.{File, IOException, OutputStream, OutputStreamWriter,
-                UnsupportedEncodingException, Writer}
-import java.net.{MalformedURLException, URL}
-import java.util.Stack
+import org.xml.sax.{ ContentHandler, XMLReader, Locator, Attributes }
+import org.xml.sax.ext.LexicalHandler
+import java.io.{ File, OutputStream, OutputStreamWriter, Writer, IOException }
 
 /** XIncluder is a SAX <code>ContentHandler</code> 
  * that writes its XML document onto an output stream after resolving
@@ -33,8 +25,7 @@ import java.util.Stack
  *   based on Eliotte Rusty Harold's SAXXIncluder
  * </p>
  */
-class XIncluder(outs:OutputStream, encoding:String) extends Object 
-with ContentHandler with LexicalHandler {
+class XIncluder(outs: OutputStream, encoding: String) extends ContentHandler with LexicalHandler {
 
   var out = new OutputStreamWriter(outs, encoding)
 
@@ -151,7 +142,7 @@ with ContentHandler with LexicalHandler {
   def startDTD(name: String, publicID: String, systemID: String) {
     inDTD = true
     // if this is the source document, output a DOCTYPE declaration
-    if (entities.size() == 0) {
+    if (entities.isEmpty) {
       var id = ""
       if (publicID != null) id = " PUBLIC \"" + publicID + "\" \"" + systemID + '"';
       else if (systemID != null) id = " SYSTEM \"" + systemID + '"';
@@ -167,7 +158,7 @@ with ContentHandler with LexicalHandler {
   def endDTD() {}
     
   def startEntity(name: String) {
-    entities.push(name)
+    entities push name
   }
 
   def endEntity(name: String) {
diff --git a/src/library/scala/xml/package.scala b/src/library/scala/xml/package.scala
new file mode 100644
index 0000000..e37f87b
--- /dev/null
+++ b/src/library/scala/xml/package.scala
@@ -0,0 +1,11 @@
+package scala
+
+package object xml {
+  val XercesClassName = "org.apache.xerces.parsers.SAXParser"
+  
+  type SAXException       = org.xml.sax.SAXException
+  type SAXParseException  = org.xml.sax.SAXParseException
+  type EntityResolver     = org.xml.sax.EntityResolver
+  type InputSource        = org.xml.sax.InputSource
+  type SAXParser          = javax.xml.parsers.SAXParser
+}
\ No newline at end of file
diff --git a/src/library/scala/xml/parsing/ConstructingHandler.scala b/src/library/scala/xml/parsing/ConstructingHandler.scala
index 599e52d..f2dd7e5 100644
--- a/src/library/scala/xml/parsing/ConstructingHandler.scala
+++ b/src/library/scala/xml/parsing/ConstructingHandler.scala
@@ -1,23 +1,23 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: ConstructingHandler.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.xml.parsing
+package scala.xml
+package parsing
 
 /** Implementation of MarkupHandler that constructs nodes.
  *
  *  @author  Burak Emir
  *  @version 1.0
  */
-abstract class ConstructingHandler extends MarkupHandler {
-
+abstract class ConstructingHandler extends MarkupHandler
+{
   val preserveWS: Boolean
 
   def elem(pos: Int, pre: String, label: String, attrs: MetaData,
@@ -27,13 +27,7 @@ abstract class ConstructingHandler extends MarkupHandler {
   def procInstr(pos: Int, target: String, txt: String) =
     ProcInstr(target, txt)
 
-  def comment(pos: Int, txt: String) =
-    Comment(txt)
-
-  def entityRef(pos: Int, n: String) =
-    EntityRef(n)
-
-  def text(pos: Int, txt:String) =
-    Text(txt)
-
+  def comment(pos: Int, txt: String)  = Comment(txt)
+  def entityRef(pos: Int, n: String)  = EntityRef(n)
+  def text(pos: Int, txt: String)     = Text(txt)
 }
diff --git a/src/library/scala/xml/parsing/ConstructingParser.scala b/src/library/scala/xml/parsing/ConstructingParser.scala
index a1e4908..b5a8f0b 100644
--- a/src/library/scala/xml/parsing/ConstructingParser.scala
+++ b/src/library/scala/xml/parsing/ConstructingParser.scala
@@ -1,58 +1,49 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: ConstructingParser.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.xml.parsing
+package scala.xml
+package parsing
 
 import java.io.File
-
 import scala.io.Source
 
 object ConstructingParser {
+  def fromFile(inp: File, preserveWS: Boolean) =
+    new ConstructingParser(Source.fromFile(inp), preserveWS) initialize
 
-  def fromFile(inp: File, preserveWS: Boolean) = {
-    val p = new ConstructingParser(Source.fromFile(inp), preserveWS)
-    p.nextch
-    p
-  }
-
-  def fromSource(inp: Source, preserveWS: Boolean) = {
-    val p = new ConstructingParser(inp, preserveWS)
-    p.nextch
-    p
-  }
+  def fromSource(inp: Source, preserveWS: Boolean) =
+    new ConstructingParser(inp, preserveWS) initialize
 }
 
 /** An xml parser. parses XML and invokes callback methods of a MarkupHandler.
- *  Don't forget to call next.ch on a freshly instantiated parser in order to
- *  initialize it. If you get the parser from the object method, initialization
- *  is already done for you.
- *
- *<pre>
-object parseFromURL {
-  def main(args:Array[String]): Unit = {
-    val url = args(0);
-    val src = scala.io.Source.fromURL(url);
-    val cpa = scala.xml.parsing.ConstructingParser.fromSource(src, false); // fromSource initializes automatically
-    val doc = cpa.document();
-
-    // let's see what it is
-    val ppr = new scala.xml.PrettyPrinter(80,5);
-    val ele = doc.docElem;
-    Console.println("finished parsing");
-    val out = ppr.format(ele);
-    Console.println(out);
-  }
-}
-</pre>
- */
+  * Don't forget to call next.ch on a freshly instantiated parser in order to
+  * initialize it. If you get the parser from the object method, initialization
+  * is already done for you.
+  *
+  * {{{
+  * object parseFromURL {
+  *   def main(args:Array[String]): Unit = {
+  *     val url = args(0);
+  *     val src = scala.io.Source.fromURL(url);
+  *     val cpa = scala.xml.parsing.ConstructingParser.fromSource(src, false); // fromSource initializes automatically
+  *     val doc = cpa.document();
+  *
+  *     // let's see what it is
+  *     val ppr = new scala.xml.PrettyPrinter(80,5);
+  *     val ele = doc.docElem;
+  *     Console.println("finished parsing");
+  *     val out = ppr.format(ele);
+  *     Console.println(out);
+  *   }
+  * }
+  * }}} */
 class ConstructingParser(val input: Source, val preserveWS: Boolean)
 extends  ConstructingHandler
 with     ExternalSources
diff --git a/src/library/scala/xml/parsing/DefaultMarkupHandler.scala b/src/library/scala/xml/parsing/DefaultMarkupHandler.scala
index 3899064..c215b8b 100644
--- a/src/library/scala/xml/parsing/DefaultMarkupHandler.scala
+++ b/src/library/scala/xml/parsing/DefaultMarkupHandler.scala
@@ -1,18 +1,18 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: DefaultMarkupHandler.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.xml.parsing
+package scala.xml
+package parsing
 
 
-/** default implemenation of markup handler always returns NodeSeq.Empty */
+/** default implementation of markup handler always returns NodeSeq.Empty */
 abstract class DefaultMarkupHandler extends MarkupHandler {
 
   def elem(pos: Int, pre: String, label: String, attrs: MetaData,
diff --git a/src/library/scala/xml/parsing/ExternalSources.scala b/src/library/scala/xml/parsing/ExternalSources.scala
index db6b09f..ad283d9 100644
--- a/src/library/scala/xml/parsing/ExternalSources.scala
+++ b/src/library/scala/xml/parsing/ExternalSources.scala
@@ -1,17 +1,18 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: ExternalSources.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.xml.parsing
+package scala.xml
+package parsing
 
 import java.net.URL
+import java.io.File.separator
 
 import scala.io.Source
 
@@ -19,46 +20,8 @@ import scala.io.Source
  *  @author  Burak Emir
  *  @version 1.0
  */
-trait ExternalSources { self: ExternalSources with MarkupParser with MarkupHandler =>
-
-  private def externalSourceFromURL(url: URL): Source = {
-    import java.io.{BufferedReader, InputStreamReader}
-    val in =
-      new BufferedReader(
-        new InputStreamReader(
-	  url.openStream()))
-
-    //@todo: replace this hack with proper Source implementation
-
-    val str = new StringBuilder()
-    var inputLine: String = null
-    
-    //while (inputLine = in.readLine()) != null) {
-    while ({inputLine = in.readLine(); inputLine} ne null) {
-      // Console.println(inputLine)  // DEBUG
-      str.append(inputLine)
-      str.append('\n')  // readable output
-    }
-    in.close()
-    
-    class MyClass extends Source {
-
-      def newIter = new Iterator[Char] {
-        var i = -1
-        private val len = str.length-1
-        def hasNext = i < len
-        def next = { i += 1; str.charAt(i) }
-      }
-
-      val iter = newIter
-
-      def reset: Source = new MyClass
-
-      /*override var*/ descr = url.toExternalForm()
-    }
-
-    new MyClass
-  }
+trait ExternalSources { 
+  self: ExternalSources with MarkupParser with MarkupHandler =>
 
   /** ...
    *
@@ -67,16 +30,13 @@ trait ExternalSources { self: ExternalSources with MarkupParser with MarkupHandl
    */
   def externalSource(systemId: String): Source = {
     if (systemId startsWith "http:")
-      return externalSourceFromURL(new URL(systemId))
-
-    var fileStr = input.descr
-
-    if (input.descr startsWith "file:") {
-      fileStr = input.descr.substring(5, input.descr.length)
-    } else
-      fileStr = fileStr.substring(0,
-                                  fileStr.lastIndexOf(java.io.File.separator)+1)
+      return Source fromURL new URL(systemId)
+      
+    val fileStr: String = input.descr match {
+      case x if x startsWith "file:"  => x drop 5
+      case x                          => x take ((x lastIndexOf separator) + 1)
+    }
+    
     Source.fromFile(fileStr + systemId)
   }
-
 }
diff --git a/src/library/scala/xml/parsing/FactoryAdapter.scala b/src/library/scala/xml/parsing/FactoryAdapter.scala
index 26f0081..e0fe20f 100644
--- a/src/library/scala/xml/parsing/FactoryAdapter.scala
+++ b/src/library/scala/xml/parsing/FactoryAdapter.scala
@@ -1,38 +1,47 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: FactoryAdapter.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.xml.parsing
+package scala.xml
+package parsing
 
-import java.io.{InputStream, Reader, File, FileDescriptor, FileInputStream}
-import scala.collection.mutable.{HashMap,Stack}
+import java.io.{ InputStream, Reader, File, FileDescriptor, FileInputStream }
+import collection.mutable.Stack
 
-import org.xml.sax.{Attributes, InputSource}
-
-import org.xml.sax.SAXException
-import org.xml.sax.SAXNotRecognizedException
-import org.xml.sax.SAXNotSupportedException
-import org.xml.sax.SAXParseException
+import org.xml.sax.Attributes
 import org.xml.sax.helpers.DefaultHandler
 
-import javax.xml.parsers.SAXParserFactory
-import javax.xml.parsers.ParserConfigurationException
-import javax.xml.parsers.SAXParser
+// can be mixed into FactoryAdapter if desired
+trait ConsoleErrorHandler extends DefaultHandler
+{  
+  // ignore warning, crimson warns even for entity resolution!
+  override def warning(ex: SAXParseException): Unit = { }
+  override def error(ex: SAXParseException): Unit = printError("Error", ex) 
+  override def fatalError(ex: SAXParseException): Unit = printError("Fatal Error", ex)
 
+  protected def printError(errtype: String, ex: SAXParseException): Unit =
+    Console.withOut(Console.err) {
+      val s = "[%s]:%d:%d: %s".format(
+        errtype, ex.getLineNumber, ex.getColumnNumber, ex.getMessage)
+      Console.println(s)
+      Console.flush
+    }
+}
 
 /** SAX adapter class, for use with Java SAX parser. Keeps track of 
  *  namespace bindings, without relying on namespace handling of the 
  *  underlying SAX parser.
  */
-abstract class FactoryAdapter extends DefaultHandler() {
-      
+abstract class FactoryAdapter extends DefaultHandler with factory.XMLLoader[Node]
+{
+  var rootElem: Node = null
+  
   val buffer      = new StringBuilder()
   val attribStack = new Stack[MetaData]
   val hStack      = new Stack[Node]   // [ element ] contains siblings
@@ -56,7 +65,7 @@ abstract class FactoryAdapter extends DefaultHandler() {
    * @return a new XML element.
    */
   def createNode(pre: String, elemName: String, attribs: MetaData,
-                 scope: NamespaceBinding, chIter: List[Node]): Node //abstract 
+                 scope: NamespaceBinding, chIter: List[Node]): Node // abstract 
   
   /** creates a Text node.
    * @param text
@@ -80,242 +89,103 @@ abstract class FactoryAdapter extends DefaultHandler() {
   * @param length
   */
   override def characters(ch: Array[Char], offset: Int, length: Int): Unit = {
-    if (capture) {
-      if (normalizeWhitespace) {
-        // normalizing whitespace is not compliant, but useful */
-	var i: Int = offset
-        var ws = false
-        while (i < offset + length) {
-          if (ch(i).isWhitespace) {
-            if (!ws) {
-              buffer.append(' ')
-              ws = true
-            }
-          } else {
-            buffer.append(ch(i))
-            ws = false
-          }
-	  i += 1
-        }
-      } else { // compliant:report every character
-        buffer.append(ch, offset, length)
+    if (!capture) return
+    // compliant: report every character
+    else if (!normalizeWhitespace) buffer.appendAll(ch, offset, length)
+    // normalizing whitespace is not compliant, but useful
+    else {
+      var it = ch.slice(offset, offset + length).iterator
+      while (it.hasNext) {
+        val c = it.next
+        val isSpace = c.isWhitespace
+        buffer append (if (isSpace) ' ' else c)
+        if (isSpace)
+          it = it dropWhile (_.isWhitespace)
       }
-    }          
+    }
   }
 
-  //var elemCount = 0; //STATISTICS
+  private def splitName(s: String) = {
+    val idx = s indexOf ':'
+    if (idx < 0) (null, s)
+    else (s take idx, s drop (idx + 1))
+  }
 
   /* ContentHandler methods */
 
-  /* Start prefix mapping - use default impl. 
-   def startPrefixMapping( prefix:String , uri:String ):Unit = {} 
-   */
-
   /* Start element. */
-  override def startElement(uri: String, _localName: String,
-                            qname: String, attributes: Attributes): Unit = {
-    /*elemCount = elemCount + 1; STATISTICS */
+  override def startElement(
+    uri: String,
+    _localName: String,
+    qname: String,
+    attributes: Attributes): Unit =
+  {
     captureText()
-    //Console.println("FactoryAdapter::startElement("+uri+","+_localName+","+qname+","+attributes+")");
-    tagStack.push(curTag)
-    curTag = qname; //localName ;
-
-    val colon = qname.indexOf(':'.asInstanceOf[Int])
-    val localName = if(-1 == colon) qname else qname.substring(colon+1,qname.length())
-
-    //Console.println("FactoryAdapter::startElement - localName ="+localName);
+    tagStack push curTag
+    curTag = qname
 
+    val localName = splitName(qname)._2
     capture = nodeContainsText(localName)
 
-    hStack.push(null)
+    hStack push null
     var m: MetaData = Null
-
-    var scpe = scopeStack.top
-    for (i <- List.range(0, attributes.getLength())) {
-      //val attrType = attributes.getType(i); // unused for now
-      val qname = attributes.getQName(i)
-      val value = attributes.getValue(i)
-      val colon = qname.indexOf(':'.asInstanceOf[Int])
-      if (-1 != colon) {                     // prefixed attribute
-        val pre = qname.substring(0, colon)
-        val key = qname.substring(colon+1, qname.length())
-        if ("xmlns" /*XML.xmlns*/ == pre)
-          scpe = value.length() match {
-            case 0 => new NamespaceBinding(key, null,  scpe)
-            case _ => new NamespaceBinding(key, value, scpe)
-          }
-        else
-          m = new PrefixedAttribute(pre, key, Text(value), m)
-      } else if ("xmlns" /*XML.xmlns*/ == qname)
-        scpe = value.length() match {
-          case 0 => new NamespaceBinding(null, null,  scpe)
-          case _ => new NamespaceBinding(null, value, scpe)
-        }
+    var scpe: NamespaceBinding = 
+      if (scopeStack.isEmpty) TopScope
+      else scopeStack.top
+    
+    for (i <- 0 until attributes.getLength()) {
+      val qname = attributes getQName i
+      val value = attributes getValue i
+      val (pre, key) = splitName(qname)
+      def nullIfEmpty(s: String) = if (s == "") null else s
+      
+      if (pre == "xmlns" || (pre == null && qname == "xmlns")) {
+        val arg = if (pre == null) null else key
+        scpe = new NamespaceBinding(arg, nullIfEmpty(value), scpe)
+      }
       else
-        m = new UnprefixedAttribute(qname, Text(value), m)
+        m = Attribute(Option(pre), key, Text(value), m)
     }
-    scopeStack.push(scpe)
-    attribStack.push(m)
-    ()
-  } // startElement(String,String,String,Attributes)
+    
+    scopeStack push scpe
+    attribStack push m
+  }
   
 
   /** captures text, possibly normalizing whitespace
    */
   def captureText(): Unit = {
-    if (capture) {
-      val text = buffer.toString()
-      if (text.length() > 0 && !text.equals(" ")) {
-        hStack.push(createText(text))
-      }
-    }
-    buffer.setLength(0)
+    if (capture && buffer.length > 0)
+      hStack push createText(buffer.toString)
+    
+    buffer.clear()
   }
-
+  
   /** End element.
    * @param uri
    * @param localName
    * @param qname
    * @throws org.xml.sax.SAXException if ..
    */
-  override def endElement(uri: String , _localName: String , qname: String): Unit = {
+  override def endElement(uri: String , _localName: String, qname: String): Unit = {  
     captureText()
-
     val metaData = attribStack.pop
-
+  
     // reverse order to get it right
-    var v: List[Node] = Nil
-    var child: Node = hStack.pop
-    while (child ne null) {
-      v = child::v
-      child = hStack.pop
-    }
-
-    val colon = qname.indexOf(':'.asInstanceOf[Int])
-    val localName =
-      if (-1 == colon) qname
-      else qname.substring(colon+1, qname.length())  
-
+    val v = (Iterator continually hStack.pop takeWhile (_ != null)).toList.reverse
+    val (pre, localName) = splitName(qname)
     val scp = scopeStack.pop
-    // create element
-    val pre = if (-1 == colon) null else qname.substring(0, colon)
+  
+    // create element    
     rootElem = createNode(pre, localName, metaData, scp, v)
-
-    hStack.push(rootElem)
-
-    // set
+    hStack push rootElem
     curTag = tagStack.pop
-
-    capture =
-      if (curTag ne null) nodeContainsText(curTag) // root level
-      else false
-  } // endElement(String,String,String)
+    capture = curTag != null && nodeContainsText(curTag) // root level
+  }
   
   /** Processing instruction.
   */
   override def processingInstruction(target: String, data: String) {
-    for (pi <- createProcInstr(target, data))
-      hStack.push(pi)
+    hStack pushAll createProcInstr(target, data)
   }
-  
-  //
-  // ErrorHandler methods
-  //
-
-  /** Warning.*/
-  override def warning(ex: SAXParseException): Unit = {
-    // ignore warning, crimson warns even for entity resolution!
-    //printError("Warning", ex);
-  }
-
-  /** Error.     */
-  override def error(ex: SAXParseException): Unit =
-    printError("Error", ex) 
-
-  /** Fatal error.*/
-  override def fatalError(ex: SAXParseException): Unit =
-    printError("Fatal Error", ex)
-
-  //
-  // Protected methods
-  //
-
-  /** Prints the error message */
-  protected def printError(errtype: String, ex: SAXParseException): Unit =
-    Console.withOut(Console.err) {
-    Console.print("[")
-    Console.print(errtype)
-    Console.print("] ")
-
-    var systemId = ex.getSystemId()
-    if (systemId ne null) {
-      val index = systemId.lastIndexOf('/'.asInstanceOf[Int])
-      if (index != -1)
-        systemId = systemId.substring(index + 1)
-      //Console.print(systemId)
-    }
-
-    Console.print(':')
-    Console.print(ex.getLineNumber())
-    Console.print(':')
-    Console.print(ex.getColumnNumber())
-    Console.print(": ")
-    Console.print(ex.getMessage())
-    Console.println
-    Console.flush
-  }
-
-  var rootElem: Node = null:Node
-
-  //FactoryAdapter
-  // MAIN
-  //
-
-  /** load XML document
-   * @param source
-   * @return a new XML document object
-   */
-  def loadXML(source: InputSource): Node = {
-    // create parser
-    val parser: SAXParser = try {
-      val f = SAXParserFactory.newInstance()
-      f.setNamespaceAware(false)
-      f.newSAXParser()
-    } catch {
-      case e: Exception =>
-        Console.err.println("error: Unable to instantiate parser")
-        throw e
-    }
-      
-    // parse file
-    scopeStack.push(TopScope)
-    parser.parse(source, this)
-    scopeStack.pop
-    return rootElem
-  } // loadXML
-
-  /** loads XML from given file */
-  def loadFile(file: File): Node =
-    loadXML(new InputSource(new FileInputStream(file)))
-  
-  /** loads XML from given file descriptor */
-  def loadFile(fileDesc: FileDescriptor): Node =
-    loadXML(new InputSource(new FileInputStream(fileDesc)))
-  
-  /** loads XML from given file */
-  def loadFile(fileName: String): Node =
-    loadXML(new InputSource(new FileInputStream(fileName)))
-  
-  /** loads XML from given InputStream */
-  def load(is: InputStream): Node =
-    loadXML(new InputSource(is))
-
-  /** loads XML from given Reader */
-  def load(reader: Reader): Node =
-    loadXML(new InputSource(reader))
-
-  /** loads XML from given sysID */
-  def load(sysID: String): Node =
-    loadXML(new InputSource(sysID))
-
 }
diff --git a/src/library/scala/xml/parsing/FatalError.scala b/src/library/scala/xml/parsing/FatalError.scala
index 8651c20..d2d6cf3 100644
--- a/src/library/scala/xml/parsing/FatalError.scala
+++ b/src/library/scala/xml/parsing/FatalError.scala
@@ -1,15 +1,16 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: FatalError.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.xml.parsing;
+package scala.xml
+package parsing
 
-
-case class FatalError(msg:String) extends java.lang.RuntimeException(msg);
+/** !!! This is poorly named, but I guess it's in the API.
+ */
+case class FatalError(msg: String) extends java.lang.RuntimeException(msg)
diff --git a/src/library/scala/xml/parsing/MarkupHandler.scala b/src/library/scala/xml/parsing/MarkupHandler.scala
index 151b309..7788d5e 100644
--- a/src/library/scala/xml/parsing/MarkupHandler.scala
+++ b/src/library/scala/xml/parsing/MarkupHandler.scala
@@ -1,17 +1,18 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: MarkupHandler.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.xml.parsing
+package scala.xml
+package parsing
 
-import scala.collection.mutable.{HashMap, Map}
+import collection.mutable
+import mutable.HashMap
 import scala.io.Source
 import scala.util.logging.Logged
 import scala.xml.dtd._
@@ -25,39 +26,28 @@ import scala.xml.dtd._
  *  @todo can we ignore more entity declarations (i.e. those with extIDs)?
  *  @todo expanding entity references
  */
-abstract class MarkupHandler extends AnyRef with Logged {
-
-  // impl. of Logged
-  //def log(msg:String) = {}
-
-  /** returns true is this markup handler is validing */
+abstract class MarkupHandler extends Logged
+{
+  /** returns true is this markup handler is validating */
   val isValidating: Boolean = false
 
   var decls: List[Decl] = Nil
+  var ent: mutable.Map[String, EntityDecl] = new HashMap[String, EntityDecl]()
 
-  var ent: Map[String, EntityDecl] = new HashMap[String, EntityDecl]()
-
-  def lookupElemDecl(Label: String): ElemDecl =  {
-    def lookup(xs:List[Decl]): ElemDecl = xs match {
-      case (z @ ElemDecl(Label, _)) :: zs => return z
-      case _::zs                        => lookup(zs)
-      case _                            => return null
-    }
-    lookup(decls)
-  }
-
-  def replacementText(entityName: String): Source = ent.get(entityName) match {
-    case Some(ParsedEntityDecl(_, IntDef(value))) =>
-      Source.fromString(value)
-    case Some(ParameterEntityDecl(_, IntDef(value))) =>
-      Source.fromString(" "+value+" ")
-    case Some(_) =>
-      Source.fromString("<!-- "+entityName+"; -->")
-    case None =>
-      Source.fromString("<!-- unknown entity "+entityName+"; -->")
+  def lookupElemDecl(Label: String): ElemDecl = {
+    for (z @ ElemDecl(Label, _) <- decls)
+      return z
+      
+    null
   }
 
- //def checkChildren(pos:int, pre: String, label:String,ns:NodeSeq): Unit = {}
+  def replacementText(entityName: String): Source =
+    Source fromString ((ent get entityName) match {
+      case Some(ParsedEntityDecl(_, IntDef(value)))     => value
+      case Some(ParameterEntityDecl(_, IntDef(value)))  => " %s " format value
+      case Some(_)                                      => "<!-- %s; -->" format entityName
+      case None                                         => "<!-- unknown entity %s; -->" format entityName
+    })
 
   def endDTD(n: String): Unit = ()
 
@@ -79,7 +69,7 @@ abstract class MarkupHandler extends AnyRef with Logged {
    */
   def elemEnd(pos: Int, pre: String, label: String): Unit = ()
 
-  /** callback method invoked by MarkupParser after parsing an elementm,
+  /** callback method invoked by MarkupParser after parsing an element,
    *  between the elemStart and elemEnd callbacks
    *
    *  @param pos      the position in the source file
@@ -92,19 +82,10 @@ abstract class MarkupHandler extends AnyRef with Logged {
   def elem(pos: Int, pre: String, label: String, attrs: MetaData, scope: NamespaceBinding, args: NodeSeq): NodeSeq
 
   /** callback method invoked by MarkupParser after parsing PI.
-   *
-   *  @param pos      the position in the source file
-   *  @param target   ...
-   *  @param txt      ...
-   *  @return         ...
    */
   def procInstr(pos: Int, target: String, txt: String): NodeSeq
 
   /** callback method invoked by MarkupParser after parsing comment.
-   *
-   *  @param pos      the position in the source file
-   *  @param comment  ...
-   *  @return         ...
    */
   def comment(pos: Int, comment: String): NodeSeq
 
@@ -122,38 +103,24 @@ abstract class MarkupHandler extends AnyRef with Logged {
   def elemDecl(n: String, cmstr: String): Unit = ()
 
   def attListDecl(name: String, attList: List[AttrDecl]): Unit = ()
-
-  def parameterEntityDecl(name: String, edef: EntityDef) {
-    //log("parameterEntityDecl("+name+","+edef+")");
+  
+  private def someEntityDecl(name: String, edef: EntityDef, f: (String, EntityDef) => EntityDecl): Unit =
     edef match {
-      case _:ExtDef if !isValidating =>
-        ; // ignore (cf REC-xml 4.4.1)
-      case _ =>
-        val y =  ParameterEntityDecl(name, edef)
-        decls = y :: decls
+      case _: ExtDef if !isValidating =>  // ignore (cf REC-xml 4.4.1)
+      case _  =>
+        val y = f(name, edef)
+        decls ::= y
         ent.update(name, y)
-        //log("ent.get(..) = "+ent.get(name))
     }
-  }
 
-  def parsedEntityDecl(name: String, edef: EntityDef): Unit = edef match {
-    case _:ExtDef if !isValidating =>
-      ; // ignore (cf REC-xml 4.8 and 4.4.1)
-    case _ =>
-      val y = ParsedEntityDecl(name, edef)
-      decls = y :: decls
-      ent.update(name, y)
-  }
+  def parameterEntityDecl(name: String, edef: EntityDef): Unit =
+    someEntityDecl(name, edef, ParameterEntityDecl.apply _)
 
-  def unparsedEntityDecl(name: String, extID: ExternalID, notat: String): Unit =
-    {}
+  def parsedEntityDecl(name: String, edef: EntityDef): Unit = 
+    someEntityDecl(name, edef, ParsedEntityDecl.apply _)
 
+  def peReference(name: String) { decls ::= PEReference(name) }
+  def unparsedEntityDecl(name: String, extID: ExternalID, notat: String): Unit = ()
   def notationDecl(notat: String, extID: ExternalID): Unit = ()
-
-  def peReference(name: String) { decls = PEReference(name) :: decls }
-
-  /** report a syntax error */
   def reportSyntaxError(pos: Int, str: String): Unit
-
 }
-
diff --git a/src/library/scala/xml/parsing/MarkupParser.scala b/src/library/scala/xml/parsing/MarkupParser.scala
index 016ed93..0841f22 100644
--- a/src/library/scala/xml/parsing/MarkupParser.scala
+++ b/src/library/scala/xml/parsing/MarkupParser.scala
@@ -1,18 +1,17 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: MarkupParser.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala.xml.parsing
+package scala.xml
+package parsing
 
 import scala.io.Source
 import scala.xml.dtd._
+import Utility.Escapes.{ pairs => unescape }
 
 /**
  * An XML parser.
@@ -28,7 +27,20 @@ import scala.xml.dtd._
  * @author  Burak Emir
  * @version 1.0
  */
-trait MarkupParser extends AnyRef with TokenTests { self:  MarkupParser with MarkupHandler =>
+trait MarkupParser extends MarkupParserCommon with TokenTests
+{ 
+  self: MarkupParser with MarkupHandler =>
+  
+  type PositionType = Int
+  type InputType    = Source
+  type ElementType  = NodeSeq
+  type AttributesType = (MetaData, NamespaceBinding)
+  type NamespaceType = NamespaceBinding
+
+  def truncatedError(msg: String): Nothing = throw FatalError(msg)
+  def errorNoEnd(tag: String) = throw FatalError("expected closing tag of " + tag)
+  
+  def xHandleError(that: Char, msg: String) = reportSyntaxError(msg)
 
   val input: Source
 
@@ -42,6 +54,15 @@ trait MarkupParser extends AnyRef with TokenTests { self:  MarkupParser with Mar
   //
 
   var curInput: Source = input
+  def lookahead(): BufferedIterator[Char] = new BufferedIterator[Char] {
+    val stream = curInput.toStream
+    curInput = Source.fromIterable(stream)
+    val underlying = Source.fromIterable(stream).buffered
+    
+    def hasNext = underlying.hasNext
+    def next = underlying.next
+    def head = underlying.head
+  }    
 
   /** the handler of the markup, returns this */
   private val handle: MarkupHandler = this
@@ -52,10 +73,9 @@ trait MarkupParser extends AnyRef with TokenTests { self:  MarkupParser with Mar
   /** holds the position in the source file */
   var pos: Int = _
 
-
   /* used when reading external subset */
   var extIndex = -1
-
+  
   /** holds temporary values of pos */
   var tmppos: Int = _
 
@@ -87,60 +107,19 @@ trait MarkupParser extends AnyRef with TokenTests { self:  MarkupParser with Mar
     xToken('>')
     md
   }
-
-  /** <? prolog ::= xml S?
-   *  // this is a bit more lenient than necessary...
+  
+  /** Factored out common code.
    */
-  def prolog(): Tuple3[Option[String], Option[String], Option[Boolean]] = {
-
-    //Console.println("(DEBUG) prolog")
-    var n = 0
+  private def prologOrTextDecl(isProlog: Boolean): (Option[String], Option[String], Option[Boolean]) = {
     var info_ver: Option[String] = None
     var info_enc: Option[String] = None
     var info_stdl: Option[Boolean] = None
 
     var m = xmlProcInstr()
-
-    xSpaceOpt
-
-    m("version") match {
-      case null  => ;
-      case Text("1.0") => info_ver = Some("1.0"); n += 1
-      case _     => reportSyntaxError("cannot deal with versions != 1.0")
-    }
-
-    m("encoding") match {
-      case null => ;
-      case Text(enc) =>
-        if (!isValidIANAEncoding(enc))
-          reportSyntaxError("\"" + enc + "\" is not a valid encoding")
-        else {
-          info_enc = Some(enc)
-          n += 1
-        }
-    }
-    m("standalone") match {
-      case null => ;
-      case Text("yes") => info_stdl = Some(true);  n += 1
-      case Text("no")  => info_stdl = Some(false); n += 1
-      case _     => reportSyntaxError("either 'yes' or 'no' expected")
-    }
-
-    if (m.length - n != 0) {
-      reportSyntaxError("VersionInfo EncodingDecl? SDDecl? or '?>' expected!");
-    }
-    //Console.println("[MarkupParser::prolog] finished parsing prolog!");
-    Tuple3(info_ver,info_enc,info_stdl)
-  }
-
-  /** prolog, but without standalone */
-  def textDecl(): Tuple2[Option[String],Option[String]] = {
-
-    var info_ver: Option[String] = None
-    var info_enc: Option[String] = None
-
-    var m = xmlProcInstr()
     var n = 0
+    
+    if (isProlog)
+      xSpaceOpt
 
     m("version") match {
       case null => ;
@@ -158,14 +137,34 @@ trait MarkupParser extends AnyRef with TokenTests { self:  MarkupParser with Mar
           n += 1
         }
     }
+    
+    if (isProlog) {
+      m("standalone") match {
+        case null => ;
+        case Text("yes") => info_stdl = Some(true);  n += 1
+        case Text("no")  => info_stdl = Some(false); n += 1
+        case _     => reportSyntaxError("either 'yes' or 'no' expected")
+      }
+    }
 
     if (m.length - n != 0) {
-      reportSyntaxError("VersionInfo EncodingDecl? or '?>' expected!");
+      val s = if (isProlog) "SDDecl? " else ""
+      reportSyntaxError("VersionInfo EncodingDecl? %sor '?>' expected!" format s)
     }
-    //Console.println("[MarkupParser::textDecl] finished parsing textdecl");
-    Tuple2(info_ver, info_enc);
+    
+    (info_ver, info_enc, info_stdl)
   }
 
+  /** <? prolog ::= xml S?
+   *  // this is a bit more lenient than necessary...
+   */
+  def prolog(): (Option[String], Option[String], Option[Boolean]) =
+    prologOrTextDecl(true)
+
+  /** prolog, but without standalone */
+  def textDecl(): (Option[String], Option[String]) =
+    prologOrTextDecl(false) match { case (x1, x2, _)  => (x1, x2) }
+
   /**
    *[22]        prolog     ::=          XMLDecl? Misc* (doctypedecl Misc*)?
    *[23]        XMLDecl    ::=          '<?xml' VersionInfo EncodingDecl? SDDecl? S? '?>'
@@ -176,8 +175,6 @@ trait MarkupParser extends AnyRef with TokenTests { self:  MarkupParser with Mar
    */
 
   def document(): Document = {
-
-    //Console.println("(DEBUG) document")
     doc = new Document()
 
     this.dtd = null
@@ -190,7 +187,6 @@ trait MarkupParser extends AnyRef with TokenTests { self:  MarkupParser with Mar
     nextch // is prolog ?
     var children: NodeSeq = null
     if ('?' == ch) {
-      //Console.println("[MarkupParser::document] starts with xml declaration");
       nextch;
       info_prolog = prolog()
       doc.version    = info_prolog._1
@@ -198,10 +194,8 @@ trait MarkupParser extends AnyRef with TokenTests { self:  MarkupParser with Mar
       doc.standAlone = info_prolog._3
 
       children = content(TopScope) // DTD handled as side effect
-    } else {
-      //Console.println("[MarkupParser::document] does not start with xml declaration");
- //
-
+    }
+    else {
       val ts = new NodeBuffer();
       content1(TopScope, ts); // DTD handled as side effect
       ts &+ content(TopScope);
@@ -214,7 +208,7 @@ trait MarkupParser extends AnyRef with TokenTests { self:  MarkupParser with Mar
       case _:ProcInstr => ;
       case _:Comment => ;
       case _:EntityRef => // todo: fix entities, shouldn't be "special"
-        reportSyntaxError("no entity references alllowed here");
+        reportSyntaxError("no entity references allowed here");
       case s:SpecialNode =>
         if (s.toString().trim().length > 0) //non-empty text nodes not allowed
           elemCount = elemCount + 2;
@@ -234,11 +228,25 @@ trait MarkupParser extends AnyRef with TokenTests { self:  MarkupParser with Mar
 
   /** append Unicode character to name buffer*/
   protected def putChar(c: Char) = cbuf.append(c)
+  
+  /** As the current code requires you to call nextch once manually
+   *  after construction, this method formalizes that suboptimal reality.
+   */
+  def initialize: this.type = {
+    nextch
+    this
+  }
 
-  //var xEmbeddedBlock = false;
+  def ch_returning_nextch = { val res = ch ; nextch ; res }
+  def mkProcInstr(position: Int, name: String, text: String): NodeSeq =
+    handle.procInstr(position, name, text)
 
+  def mkAttributes(name: String, pscope: NamespaceBinding) =
+    if (isNameStart (ch)) xAttributes(pscope)
+    else (Null, pscope)
+  
   /** this method assign the next character to ch and advances in input */
-  def nextch {
+  def nextch = {
     if (curInput.hasNext) {
       ch = curInput.next
       pos = curInput.pos
@@ -253,25 +261,7 @@ trait MarkupParser extends AnyRef with TokenTests { self:  MarkupParser with Mar
         ch = 0.asInstanceOf[Char]
       }
     }
-  }
-
-  //final val enableEmbeddedExpressions: Boolean = false;
-
-  /** munch expected XML token, report syntax error for unexpected
-  */
-  def xToken(that: Char) {
-    if (ch == that)
-      nextch
-    else  {
-      reportSyntaxError("'" + that + "' expected instead of '" + ch + "'")
-      error("FATAL")
-    }
-  }
-
-  def xToken(that: Seq[Char]): Unit = {
-    val it = that.elements;
-    while (it.hasNext)
-      xToken(it.next);
+    ch
   }
 
   /** parse attribute and create namespace scope, metadata
@@ -313,27 +303,6 @@ trait MarkupParser extends AnyRef with TokenTests { self:  MarkupParser with Mar
     (aMap,scope)
   }
 
-  /** attribute value, terminated by either ' or ". value may not contain <.
-   *       AttValue     ::= `'` { _  } `'`
-   *                      | `"` { _ } `"`
-   */
-  def xAttributeValue(): String = {
-    val endch = ch
-    nextch
-    while (ch != endch) {
-      if ('<' == ch)
-        reportSyntaxError( "'<' not allowed in attrib value" );
-      putChar(ch)
-      nextch
-    }
-    nextch
-    val str = cbuf.toString()
-    cbuf.length = 0
-
-    // well-formedness constraint
-    normalizeAttributeValue(str)
-  }
-
   /** entity value, terminated by either ' or ". value may not contain <.
    *       AttValue     ::= `'` { _  } `'`
    *                      | `"` { _ } `"`
@@ -341,7 +310,7 @@ trait MarkupParser extends AnyRef with TokenTests { self:  MarkupParser with Mar
   def xEntityValue(): String = {
     val endch = ch
     nextch
-    while (ch != endch) {
+    while (ch != endch && !eof) {
       putChar(ch)
       nextch
     }
@@ -351,96 +320,23 @@ trait MarkupParser extends AnyRef with TokenTests { self:  MarkupParser with Mar
     str
   }
 
-
-  /** parse a start or empty tag.
-   *  [40] STag         ::= '<' Name { S Attribute } [S] 
-   *  [44] EmptyElemTag ::= '<' Name { S Attribute } [S] 
-   */
-  protected def xTag(pscope:NamespaceBinding): Tuple3[String, MetaData, NamespaceBinding] = {
-    val qname = xName
-
-    xSpaceOpt
-    val (aMap: MetaData, scope: NamespaceBinding) = {
-      if (isNameStart(ch)) 
-        xAttributes(pscope)
-      else 
-        (Null, pscope)
-    }
-    (qname, aMap, scope)
-  }
-
-  /** [42]  '<' xmlEndTag ::=  '<' '/' Name S? '>'
-   */
-  def xEndTag(n: String) = {
-    xToken('/')
-    val m = xName
-    if (n != m)
-      reportSyntaxError("expected closing tag of " + n/* +", not "+m*/);
-    xSpaceOpt
-    xToken('>')
-  }
-
   /** '<! CharData ::= [CDATA[ ( {char} - {char}"]]>"{char} ) ']]>'
    *
    * see [15]
    */
   def xCharData: NodeSeq = {
     xToken("[CDATA[")
-    val pos1 = pos
-    val sb: StringBuilder = new StringBuilder()
-    while (true) {
-      if (ch==']'  &&
-         { sb.append(ch); nextch; ch == ']' } &&
-         { sb.append(ch); nextch; ch == '>' } ) {
-        sb.length = sb.length - 2
-        nextch; 
-        return handle.text( pos1, sb.toString() );
-      } else sb.append( ch );
-      nextch; 
-    }
-    throw FatalError("this cannot happen");
-  };
-
-  /** CharRef ::= "&#" '0'..'9' {'0'..'9'} ";"
-   *            | "&#x" '0'..'9'|'A'..'F'|'a'..'f' { hexdigit } ";"
-   *
-   * see [66]
-   */
-  def xCharRef(ch: () => Char, nextch: () => Unit): String = {
-    Utility.parseCharRef(ch, nextch, reportSyntaxError _)
-    /*
-    val hex  = (ch() == 'x') && { nextch(); true };
-    val base = if (hex) 16 else 10;
-    var i = 0;
-    while (ch() != ';') {
-      ch() match {
-        case '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' =>
-          i = i * base + Character.digit( ch(), base );
-        case 'a' | 'b' | 'c' | 'd' | 'e' | 'f'
-           | 'A' | 'B' | 'C' | 'D' | 'E' | 'F' =>
-          if (! hex) 
-            reportSyntaxError("hex char not allowed in decimal char ref\n"
-                         +"Did you mean to write &#x ?");
-          else 
-            i = i * base + Character.digit(ch(), base);
-        case _ =>
-          reportSyntaxError("character '" + ch() + " not allowed in char ref\n");
-      }
-      nextch();
-    }
-    new String(Array(i.asInstanceOf[char]))
-    */
+    def mkResult(pos: Int, s: String): NodeSeq = PCData(s)
+    xTakeUntil(mkResult, () => pos, "]]>")
   }
 
-
   /** Comment ::= '<!--' ((Char - '-') | ('-' (Char - '-')))* '-->'
    *
    * see [15]
    */
   def xComment: NodeSeq = {
     val sb: StringBuilder = new StringBuilder()
-    xToken('-')
-    xToken('-')
+    xToken("--")
     while (true) { 
       if (ch == '-'  && { sb.append(ch); nextch; ch == '-' }) {
         sb.length = sb.length - 1
@@ -485,69 +381,45 @@ trait MarkupParser extends AnyRef with TokenTests { self:  MarkupParser with Mar
   def content(pscope: NamespaceBinding): NodeSeq = {
     var ts = new NodeBuffer
     var exit = eof
-    while (! exit) {
-      //Console.println("in content, ch = '"+ch+"' line="+scala.io.Position.line(pos));
-      /*      if( xEmbeddedBlock ) {
-       ts.append( xEmbeddedExpr );
-       } else {*/
-        tmppos = pos;
-        exit = eof;
-        if(!eof) 
-          ch match {
-          case '<' => // another tag
-            //Console.println("before ch = '"+ch+"' line="+scala.io.Position.line(pos)+" pos="+pos);
-            nextch; 
-            //Console.println("after ch = '"+ch+"' line="+scala.io.Position.line(pos)+" pos="+pos);
-
-            if('/' ==ch)
-              exit = true;                    // end tag
-            else
-              content1(pscope, ts)
-          //case '{' => 
-/*            if( xCheckEmbeddedBlock ) {
-              ts.appendAll(xEmbeddedExpr);
-            } else {*/
-          //    val str = new StringBuilder("{");
-          //    str.append(xText);
-          //    appendText(tmppos, ts, str.toString());
-            /*}*/
-          // postcond: xEmbeddedBlock == false!
-          case '&' => // EntityRef or CharRef 
-            nextch;
-            ch match {
-              case '#' => // CharacterRef
-                nextch;
-                val theChar = handle.text( tmppos, 
-                                          xCharRef ({ ()=> ch },{ () => nextch }) );
-                xToken(';');
-                ts &+ theChar ;
-              case _ => // EntityRef
-                val n = xName
-                xToken(';')
-                n match {
-                  case "lt"    => ts &+ '<'
-                  case "gt"    => ts &+ '>'
-                  case "amp"   => ts &+ '&'
-                  case "quot" => ts &+ '"'
-                  case _ =>
-                    /*
-                     ts + handle.entityRef( tmppos, n ) ;
-                     */
-                    push(n)
-                }
-            }
-          case _ => // text content
-            //Console.println("text content?? pos = "+pos);
-            appendText(tmppos, ts, xText);
-          // here xEmbeddedBlock might be true
+    // todo: optimize seq repr.
+    def done = new NodeSeq { val theSeq = ts.toList }
+
+    while (!exit) {
+      tmppos = pos
+      exit = eof
+      
+      if (eof)
+        return done
+      
+      ch match {
+        case '<' => // another tag
+          nextch match {
+            case '/'    => exit = true  // end tag
+            case _      => content1(pscope, ts)
           }
-    /*}*/
-    }
-    val list = ts.toList
-    // 2do: optimize seq repr.
-    new NodeSeq {
-      val theSeq = list
+
+        // postcond: xEmbeddedBlock == false!
+        case '&' => // EntityRef or CharRef 
+          nextch match {
+            case '#'  =>  // CharacterRef
+              nextch
+              val theChar = handle.text(tmppos, xCharRef(() => ch, () => nextch))
+              xToken(';');
+              ts &+ theChar
+            case _ =>     // EntityRef
+              val n = xName
+              xToken(';')
+            
+              if (unescape contains n) {
+                handle.entityRef(tmppos, n)
+                ts &+ unescape(n)
+              } else push(n)
+          }
+        case _ => // text content
+          appendText(tmppos, ts, xText);
+      }
     }
+    done
   } // content(NamespaceBinding)
 
   /** externalID ::= SYSTEM S syslit
@@ -597,47 +469,17 @@ trait MarkupParser extends AnyRef with TokenTests { self:  MarkupParser with Mar
     if ((null != extID) && isValidating) {
 
       pushExternal(extID.systemId)
-      //val extSubsetSrc = externalSource( extID.systemId );
-
       extIndex = inpStack.length
-      /*
-       .indexOf(':') != -1) { // assume URI
-         Source.fromFile(new java.net.URI(extID.systemLiteral));
-       } else {
-         Source.fromFile(extID.systemLiteral);
-       }
-      */
-      //Console.println("I'll print it now");
-      //val old = curInput;
-      //tmppos = curInput.pos;
-      //val oldch = ch;
-      //curInput = extSubsetSrc;
-      //pos = 0;
-      //nextch;
 
       extSubset()
-
       pop()
-
       extIndex = -1
-
-      //curInput = old;
-      //pos = curInput.pos;
-      //ch = curInput.ch;
-      //eof = false;
-      //while(extSubsetSrc.hasNext)
-      //Console.print(extSubsetSrc.next);
-
-      //Console.println("returned from external, current ch = "+ch )
     }
 
     if ('[' == ch) { // internal subset
       nextch
       /* TODO */
-      //Console.println("hello");
       intSubset()
-      //while(']' != ch)
-      //  nextch;
       // TODO: do the DTD parsing?? ?!?!?!?!!
       xToken(']')
       xSpaceOpt
@@ -664,15 +506,14 @@ trait MarkupParser extends AnyRef with TokenTests { self:  MarkupParser with Mar
    */
   def element1(pscope: NamespaceBinding): NodeSeq = {
     val pos = this.pos
-    val Tuple3(qname, aMap, scope) = xTag(pscope)
-    val Tuple2(pre, local) = Utility.prefix(qname) match {
-      case Some(p) => (p,qname.substring(p.length+1, qname.length))
-      case _       => (null,qname)
+    val (qname, (aMap, scope)) = xTag(pscope)
+    val (pre, local) = Utility.prefix(qname) match {
+      case Some(p) => (p, qname drop p.length+1)
+      case _       => (null, qname)
     }
     val ts = {
       if (ch == '/') {  // empty element
-        xToken('/')
-        xToken('>')
+        xToken("/>")
         handle.elemStart(pos, pre, local, aMap, scope)
         NodeSeq.Empty
       }
@@ -689,88 +530,21 @@ trait MarkupParser extends AnyRef with TokenTests { self:  MarkupParser with Mar
     res
   }
 
-  //def xEmbeddedExpr: MarkupType;
-
-  /** Name ::= (Letter | '_' | ':') (NameChar)*
-   *
-   *  see  [5] of XML 1.0 specification
-   */
-  def xName: String = {
-    if (isNameStart(ch)) {
-      while (isNameChar(ch)) {
-        putChar(ch)
-        nextch
-      }
-      val n = cbuf.toString().intern()
-      cbuf.length = 0
-      n
-    } else {
-      reportSyntaxError("name expected")
-      ""
-    }
-  }
-
-  /** scan [S] '=' [S]*/
-  def xEQ = { xSpaceOpt; xToken('='); xSpaceOpt }
-
-  /** skip optional space S? */
-  def xSpaceOpt = while (isSpace(ch) && !eof) { nextch; }
-
-  /** scan [3] S ::= (#x20 | #x9 | #xD | #xA)+ */
-  def xSpace =
-    if (isSpace(ch)) { nextch; xSpaceOpt }
-    else reportSyntaxError("whitespace expected")
-
-  /** '<?' ProcInstr ::= Name [S ({Char} - ({Char}'>?' {Char})]'?>'
-   *
-   * see [15]
-   */
-  def xProcInstr: NodeSeq = {
-    val sb:StringBuilder = new StringBuilder()
-    val n = xName
-    if (isSpace(ch)) {
-      xSpace
-      while (true) {
-        if (ch == '?' && { sb.append( ch ); nextch; ch == '>' }) {
-          sb.length = sb.length - 1;
-          nextch;
-          return handle.procInstr(tmppos, n, sb.toString);
-        } else
-          sb.append(ch);
-        nextch
-      }
-    };
-    xToken('?')
-    xToken('>')
-    handle.procInstr(tmppos, n, sb.toString)
-  }
-
   /** parse character data.
    *   precondition: xEmbeddedBlock == false (we are not in a scala block)
    */
   def xText: String = {
-    //if( xEmbeddedBlock ) throw FatalError("internal error: encountered embedded block"); // assert
-
-    /*if( xCheckEmbeddedBlock )
-      return ""
-    else {*/
-    //Console.println("in xText! ch = '"+ch+"'");
-      var exit = false;
-      while (! exit) {
-        //Console.println("LOOP in xText! ch = '"+ch+"' + pos="+pos);
-        putChar(ch);
-        val opos = pos;
-        nextch;
-
-        //Console.println("STILL LOOP in xText! ch = '"+ch+"' + pos="+pos+" opos="+opos);
-        
+    var exit = false;
+    while (! exit) {
+      putChar(ch);
+      val opos = pos;
+      nextch;
 
-        exit = eof || /*{ nextch; xCheckEmbeddedBlock }||*/( ch == '<' ) || ( ch == '&' );
-      }
-      val str = cbuf.toString();
-      cbuf.length = 0;
-      str
-    /*}*/
+      exit = eof || ( ch == '<' ) || ( ch == '&' )
+    }
+    val str = cbuf.toString();
+    cbuf.length = 0;
+    str
   }
 
   /** attribute value, terminated by either ' or ". value may not contain <.
@@ -782,7 +556,7 @@ trait MarkupParser extends AnyRef with TokenTests { self:  MarkupParser with Mar
     if (ch != '\'' && ch != '"')
       reportSyntaxError("quote ' or \" expected");
     nextch
-    while (ch != endch) {
+    while (ch != endch && !eof) {
       putChar(ch)
       nextch
     }
@@ -792,14 +566,13 @@ trait MarkupParser extends AnyRef with TokenTests { self:  MarkupParser with Mar
     str
   }
 
-
   /* [12]       PubidLiteral ::=        '"' PubidChar* '"' | "'" (PubidChar - "'")* "'" */
   def pubidLiteral(): String = {
     val endch = ch
     if (ch!='\'' && ch != '"')
       reportSyntaxError("quote ' or \" expected");
     nextch
-    while (ch != endch) {
+    while (ch != endch && !eof) {
       putChar(ch)
       //Console.println("hello '"+ch+"'"+isPubIDChar(ch));
       if (!isPubIDChar(ch))
@@ -871,34 +644,16 @@ trait MarkupParser extends AnyRef with TokenTests { self:  MarkupParser with Mar
               val ent = xName
               xToken(';')
               xSpaceOpt
-            /*
-              Console.println("hello, pushing!");
-            {
-              val test =  replacementText(ent);
-              while(test.hasNext)
-                Console.print(test.next);
-            } */
+
               push(ent)
               xSpaceOpt
-              //Console.println("hello, getting name");
               val stmt = xName
-              //Console.println("hello, got name");
               xSpaceOpt
-            //Console.println("how can we be eof = "+eof);
 
-            // eof = true because not external?!
-              //if(!eof)
-              //  error("expected only INCLUDE or IGNORE");
-
-              //pop();
-
-              //Console.println("hello, popped");
               stmt match {
                 // parameter entity
-                case "INCLUDE" =>
-                  doInclude()
-                case "IGNORE" =>
-                  doIgnore()
+                case "INCLUDE"  => doInclude()
+                case "IGNORE"   => doIgnore()
               }
             case 'I' =>
               nextch
@@ -942,12 +697,11 @@ trait MarkupParser extends AnyRef with TokenTests { self:  MarkupParser with Mar
     case _ if isSpace(ch) =>
       xSpace
     case _ =>
-      reportSyntaxError("markupdecl: unexpected character '"+ch+"' #" + ch.asInstanceOf[Int])
+      reportSyntaxError("markupdecl: unexpected character '"+ch+"' #" + ch.toInt)
       nextch
   }
 
-  /**  "rec-xml/#ExtSubset" pe references may not occur within markup 
-   declarations 
+  /**  "rec-xml/#ExtSubset" pe references may not occur within markup declarations 
    */
   def intSubset() {
     //Console.println("(DEBUG) intSubset()")
@@ -983,11 +737,10 @@ trait MarkupParser extends AnyRef with TokenTests { self:  MarkupParser with Mar
     val n = xName
     xSpace
     var attList: List[AttrDecl] = Nil
+    
     // later: find the elemDecl for n
     while ('>' != ch) {
       val aname = xName
-      //Console.println("attribute name: "+aname);
-      var defdecl: DefaultDecl = null
       xSpace
       // could be enumeration (foo,bar) parse this later :-/
       while ('"' != ch && '\'' != ch && '#' != ch && '<' != ch) {
@@ -997,29 +750,24 @@ trait MarkupParser extends AnyRef with TokenTests { self:  MarkupParser with Mar
       }
       val atpe = cbuf.toString()
       cbuf.length = 0
-      //Console.println("attr type: "+atpe);
-      ch match {
+      
+      val defdecl: DefaultDecl = ch match {
         case '\'' | '"' =>
-          val defValue = xAttributeValue() // default value
-          defdecl = DEFAULT(false, defValue)
+          DEFAULT(false, xAttributeValue())
 
         case '#' =>
           nextch
           xName match {
-            case "FIXED" =>
-              xSpace
-              val defValue = xAttributeValue() // default value
-              defdecl = DEFAULT(true, defValue)
-            case "IMPLIED" =>
-              defdecl = IMPLIED
-            case "REQUIRED" =>
-              defdecl = REQUIRED
+            case "FIXED"    => xSpace ; DEFAULT(true, xAttributeValue())
+            case "IMPLIED"  => IMPLIED
+            case "REQUIRED" => REQUIRED
           }
         case _ =>
+          null
       }
       xSpaceOpt
 
-      attList = AttrDecl(aname, atpe, defdecl) :: attList
+      attList ::= AttrDecl(aname, atpe, defdecl)
       cbuf.length = 0
     }
     nextch
@@ -1106,27 +854,11 @@ trait MarkupParser extends AnyRef with TokenTests { self:  MarkupParser with Mar
     handle.notationDecl(notat, extID)
   }
 
-  /**
-   * report a syntax error
-   */
-  def reportSyntaxError(pos: Int, str: String) {
-    curInput.reportError(pos, str)
-    //error("MarkupParser::synerr") // DEBUG
-  }
-
+  def reportSyntaxError(pos: Int, str: String): Unit = curInput.reportError(pos, str)
   def reportSyntaxError(str: String): Unit = reportSyntaxError(pos, str)
-
-  /**
-   * report a syntax error
-   */
-  def reportValidationError(pos: Int, str: String) {
-    curInput.reportError(pos, str)
-  }
+  def reportValidationError(pos: Int, str: String): Unit = reportSyntaxError(pos, str)
 
   def push(entityName: String) {
-    //Console.println("BEFORE PUSHING  "+ch)
-    //Console.println("BEFORE PUSHING  "+pos)
-    //Console.print("[PUSHING "+entityName+"]")
     if (!eof)
       inpStack = curInput :: inpStack
 
@@ -1134,26 +866,11 @@ trait MarkupParser extends AnyRef with TokenTests { self:  MarkupParser with Mar
     nextch
   }
 
-  /*
-  def push(src:Source) = {
-    curInput = src
-    nextch
-  }
-  */
-
   def pushExternal(systemId: String) {
-    //Console.print("BEFORE PUSH, curInput = $"+curInput.descr)
-    //Console.println(" stack = "+inpStack.map { x => "$"+x.descr })
-
-    //Console.print("[PUSHING EXTERNAL "+systemId+"]")
     if (!eof)
       inpStack = curInput :: inpStack
 
     curInput = externalSource(systemId)
-
-    //Console.print("AFTER PUSH, curInput = $"+curInput.descr)
-    //Console.println(" stack = "+inpStack.map { x => "$"+x.descr })
-
     nextch
   }
 
@@ -1163,53 +880,5 @@ trait MarkupParser extends AnyRef with TokenTests { self:  MarkupParser with Mar
     ch = curInput.ch
     pos = curInput.pos
     eof = false // must be false, because of places where entity refs occur
-    //Console.println("\n AFTER POP, curInput = $"+curInput.descr);
-    //Console.println(inpStack.map { x => x.descr });
   }
-
-  /** for the moment, replace only character references 
-   *  see spec 3.3.3
-   *  precond: cbuf empty
-   */
-  def normalizeAttributeValue(attval: String): String = {
-    val s: Seq[Char] = attval
-    val it = s.elements
-    while (it.hasNext) {
-      it.next match {
-        case ' '|'\t'|'\n'|'\r' => 
-          cbuf.append(' ');
-        case '&' => it.next match {
-          case '#' =>
-            var c = it.next
-            val s = xCharRef ({ () => c }, { () => c = it.next })
-            cbuf.append(s)
-          case nchar =>
-            val nbuf = new StringBuilder()
-            var d = nchar
-            do {
-              nbuf.append(d)
-              d = it.next
-            } while(d != ';');
-            nbuf.toString() match {
-              case "lt"    => cbuf.append('<')
-              case "gt"    => cbuf.append('>')
-              case "amp"   => cbuf.append('&')
-              case "apos"  => cbuf.append('\'')
-              case "quot"  => cbuf.append('"')
-              case "quote" => cbuf.append('"')
-              case name =>
-                cbuf.append('&')
-                cbuf.append(name)
-                cbuf.append(';')
-            }
-        }
-        case c =>
-          cbuf.append(c)
-      }
-    }
-    val name = cbuf.toString()
-    cbuf.length = 0
-    name
-  }
-
 }
diff --git a/src/library/scala/xml/parsing/MarkupParserCommon.scala b/src/library/scala/xml/parsing/MarkupParserCommon.scala
new file mode 100644
index 0000000..09d115b
--- /dev/null
+++ b/src/library/scala/xml/parsing/MarkupParserCommon.scala
@@ -0,0 +1,263 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+package scala.xml
+package parsing
+
+import scala.io.Source
+import scala.xml.dtd._
+import scala.annotation.switch
+import Utility.Escapes.{ pairs => unescape }
+
+object MarkupParserCommon {
+  final val SU = '\u001A'
+}
+import MarkupParserCommon._ 
+
+/** This is not a public trait - it contains common code shared
+ *  between the library level XML parser and the compiler's.
+ *  All members should be accessed through those.
+ */
+private[scala] trait MarkupParserCommon extends TokenTests {
+  protected def unreachable = Predef.error("Cannot be reached.")
+  
+  // type HandleType       // MarkupHandler, SymbolicXMLBuilder
+  type InputType        // Source, CharArrayReader
+  type PositionType     // Int, Position
+  type ElementType      // NodeSeq, Tree
+  type NamespaceType    // NamespaceBinding, Any
+  type AttributesType   // (MetaData, NamespaceBinding), mutable.Map[String, Tree]
+
+  def mkAttributes(name: String, pscope: NamespaceType): AttributesType
+  def mkProcInstr(position: PositionType, name: String, text: String): ElementType
+
+  /** parse a start or empty tag.
+   *  [40] STag         ::= '<' Name { S Attribute } [S] 
+   *  [44] EmptyElemTag ::= '<' Name { S Attribute } [S] 
+   */
+  protected def xTag(pscope: NamespaceType): (String, AttributesType) = {
+    val name = xName
+    xSpaceOpt
+     
+    (name, mkAttributes(name, pscope))
+  }
+  
+  /** '<?' ProcInstr ::= Name [S ({Char} - ({Char}'>?' {Char})]'?>'
+   *
+   * see [15]
+   */
+  def xProcInstr: ElementType = {
+    val n = xName
+    xSpaceOpt
+    xTakeUntil(mkProcInstr(_, n, _), () => tmppos, "?>")
+  }
+
+  /** attribute value, terminated by either ' or ". value may not contain <.
+   *  @param endch either ' or "
+   */
+  def xAttributeValue(endCh: Char): String = {
+    val buf = new StringBuilder      
+    while (ch != endCh) {
+      // well-formedness constraint
+      if (ch == '<') return errorAndResult("'<' not allowed in attrib value", "")
+      else if (ch == SU) truncatedError("")
+      else buf append ch_returning_nextch
+    }
+    ch_returning_nextch
+    // @todo: normalize attribute value
+    buf.toString
+  }
+  
+  def xAttributeValue(): String = {
+    val str = xAttributeValue(ch_returning_nextch)
+    // well-formedness constraint
+    normalizeAttributeValue(str)
+  }
+  
+  private def takeUntilChar(it: Iterator[Char], end: Char): String = {
+    val buf = new StringBuilder
+    while (it.hasNext) it.next match {
+      case `end`  => return buf.toString
+      case ch     => buf append ch
+    }
+    error("Expected '%s'".format(end))
+  }
+
+  /** [42]  '<' xmlEndTag ::=  '<' '/' Name S? '>'
+   */
+  def xEndTag(startName: String) {
+    xToken('/')
+    if (xName != startName)
+      errorNoEnd(startName)
+
+    xSpaceOpt
+    xToken('>')
+  }
+  
+  /** actually, Name ::= (Letter | '_' | ':') (NameChar)*  but starting with ':' cannot happen
+   *  Name ::= (Letter | '_') (NameChar)*
+   *
+   *  see  [5] of XML 1.0 specification
+   *
+   *  pre-condition:  ch != ':' // assured by definition of XMLSTART token
+   *  post-condition: name does neither start, nor end in ':'
+   */
+  def xName: String = {
+    if (ch == SU)
+      truncatedError("")
+    else if (!isNameStart(ch))
+      return errorAndResult("name expected, but char '%s' cannot start a name" format ch, "")
+    
+    val buf = new StringBuilder
+
+    do buf append ch_returning_nextch
+    while (isNameChar(ch))
+    
+    if (buf.last == ':') {
+      reportSyntaxError( "name cannot end in ':'" )
+      buf.toString dropRight 1
+    }
+    else buf.toString
+  }
+  
+  private def attr_unescape(s: String) = s match {
+    case "lt"     => "<"
+    case "gt"     => ">"
+    case "amp"    => "&"
+    case "apos"   => "'"
+    case "quot"   => "\""
+    case "quote"  => "\""
+    case _        => "&" + s + ";"
+  }
+  
+  /** Replaces only character references right now.
+   *  see spec 3.3.3
+   */
+  private def normalizeAttributeValue(attval: String): String = {
+    val buf = new StringBuilder
+    val it = attval.iterator.buffered
+    
+    while (it.hasNext) buf append (it.next match {
+      case ' ' | '\t' | '\n' | '\r' => " "
+      case '&' if it.head == '#'    => it.next ; xCharRef(it)
+      case '&'                      => attr_unescape(takeUntilChar(it, ';'))
+      case c                        => c
+    })
+    
+    buf.toString
+  }  
+  
+  /** CharRef ::= "&#" '0'..'9' {'0'..'9'} ";"
+   *            | "&#x" '0'..'9'|'A'..'F'|'a'..'f' { hexdigit } ";"
+   *
+   * see [66]
+   */
+  def xCharRef(ch: () => Char, nextch: () => Unit): String =
+    Utility.parseCharRef(ch, nextch, reportSyntaxError _)
+
+  def xCharRef(it: Iterator[Char]): String = {
+    var c = it.next
+    Utility.parseCharRef(() => c, () => { c = it.next }, reportSyntaxError _)    
+  }
+
+  def xCharRef: String = xCharRef(() => ch, () => nextch)
+  
+  /** Create a lookahead reader which does not influence the input */
+  def lookahead(): BufferedIterator[Char]
+  
+  /** The library and compiler parsers had the interesting distinction of
+   *  different behavior for nextch (a function for which there are a total
+   *  of two plausible behaviors, so we know the design space was fully
+   *  explored.) One of them returned the value of nextch before the increment
+   *  and one of them the new value.  So to unify code we have to at least
+   *  temporarily abstract over the nextchs.
+   */
+  def ch: Char
+  def nextch: Char
+  def ch_returning_nextch: Char
+  def eof: Boolean
+
+  // def handle: HandleType
+  var tmppos: PositionType
+
+  def xHandleError(that: Char, msg: String): Unit
+  def reportSyntaxError(str: String): Unit
+  def reportSyntaxError(pos: Int, str: String): Unit
+  
+  def truncatedError(msg: String): Nothing
+  def errorNoEnd(tag: String): Nothing
+
+  protected def errorAndResult[T](msg: String, x: T): T = {
+    reportSyntaxError(msg)
+    x
+  }
+
+  def xToken(that: Char) {
+    if (ch == that) nextch
+    else xHandleError(that, "'%s' expected instead of '%s'".format(that, ch))
+  }
+  def xToken(that: Seq[Char]) { that foreach xToken }
+  
+  /** scan [S] '=' [S]*/
+  def xEQ = { xSpaceOpt; xToken('='); xSpaceOpt }
+
+  /** skip optional space S? */
+  def xSpaceOpt = while (isSpace(ch) && !eof) nextch
+
+  /** scan [3] S ::= (#x20 | #x9 | #xD | #xA)+ */
+  def xSpace =
+    if (isSpace(ch)) { nextch; xSpaceOpt }
+    else xHandleError(ch, "whitespace expected")
+    
+  /** Apply a function and return the passed value */
+  def returning[T](x: T)(f: T => Unit): T = { f(x) ; x }
+ 
+  /** Execute body with a variable saved and restored after execution */
+  def saving[A,B](getter: A, setter: (A) => Unit)(body: => B): B = {
+    val saved = getter
+    try body
+    finally setter(saved)
+  }  
+    
+  /** Take characters from input stream until given String "until"
+   *  is seen.  Once seen, the accumulated characters are passed
+   *  along with the current Position to the supplied handler function.
+   */
+  protected def xTakeUntil[T](
+    handler: (PositionType, String) => T,
+    positioner: () => PositionType,
+    until: String): T =
+  {
+    val sb = new StringBuilder
+    val head = until charAt 0
+    val rest = until drop 1
+    
+    while (true) {
+      if (ch == head && peek(rest))
+        return handler(positioner(), sb.toString)
+      else if (ch == SU)
+        truncatedError("")  // throws TruncatedXMLControl in compiler
+      
+      sb append ch
+      nextch
+    }
+    unreachable
+  }
+
+  /** Create a non-destructive lookahead reader and see if the head
+   *  of the input would match the given String.  If yes, return true
+   *  and drop the entire String from input; if no, return false
+   *  and leave input unchanged.
+   */
+  private def peek(lookingFor: String): Boolean =
+    (lookahead() take lookingFor.length sameElements lookingFor.iterator) && {
+      // drop the chars from the real reader (all lookahead + orig)
+      (0 to lookingFor.length) foreach (_ => nextch)
+      true
+    }
+}
diff --git a/src/library/scala/xml/parsing/NoBindingFactoryAdapter.scala b/src/library/scala/xml/parsing/NoBindingFactoryAdapter.scala
index 21f6437..4ccf9ed 100644
--- a/src/library/scala/xml/parsing/NoBindingFactoryAdapter.scala
+++ b/src/library/scala/xml/parsing/NoBindingFactoryAdapter.scala
@@ -1,62 +1,36 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: NoBindingFactoryAdapter.scala 16894 2009-01-13 13:09:41Z cunei $
 
+package scala.xml
+package parsing
 
-package scala.xml.parsing;
-
-
-import scala.xml.factory.NodeFactory;
-import org.xml.sax.InputSource;
+import factory.NodeFactory
 
 /** nobinding adaptor providing callbacks to parser to create elements.
 *   implements hash-consing
 */
-class NoBindingFactoryAdapter extends FactoryAdapter with NodeFactory[Elem] {
-  
-  // -- FactoryAdapter methods
-
-  /** returns true. Every XML node may contain text that the application needs
-  **/
-  def nodeContainsText( label:java.lang.String ): Boolean = true;
-  
-
-  // methods for NodeFactory[Elem]
-
-  /** constructs an instance of scala.xml.Elem */
-  protected def create(pre: String, label: String, attrs: MetaData, scpe: NamespaceBinding, children:Seq[Node]): Elem = {
-     Elem( pre, label, attrs, scpe, children:_* );
-  }
-
-  // -- methods for FactoryAdapter
-
-  /** creates a node. never creates the same node twice, using hash-consing 
-  */
-  def createNode(pre:String, label: String, attrs: MetaData, scpe: NamespaceBinding, children: List[Node] ): Elem = {
-    //Console.println("NoBindingFactoryAdapter::createNode("+pre+","+label+","+attrs+","+scpe+","+children+")");
-    Elem( pre, label, attrs, scpe, children:_* );
-    //makeNode(pre, label, attrs, scpe, children);
-  }
+class NoBindingFactoryAdapter extends FactoryAdapter with NodeFactory[Elem]
+{
+  /** True.  Every XML node may contain text that the application needs */
+  def nodeContainsText(label: String) = true
+
+  /** From NodeFactory.  Constructs an instance of scala.xml.Elem */
+  protected def create(pre: String, label: String, attrs: MetaData, scope: NamespaceBinding, children: Seq[Node]): Elem =
+     Elem(pre, label, attrs, scope, children: _*)
+
+  /** From FactoryAdapter.  Creates a node. never creates the same node twice, using hash-consing. */
+  def createNode(pre: String, label: String, attrs: MetaData, scope: NamespaceBinding, children: List[Node]): Elem =
+    Elem(pre, label, attrs, scope, children: _*)
   
-  /** creates a text node
-  */
-  def createText( text:String ) = 
-    Text( text );
-
-  /** create a processing instruction
-  */
-  def createProcInstr(target: String, data: String) = 
-    makeProcInstr(target, data)
-    
-  /** loads an XML document, returning a Symbol node.
-  */
-  override def loadXML( source:InputSource ):Elem = 
-    super.loadXML( source ).asInstanceOf[ Elem ];
+  /** Creates a text node. */
+  def createText(text: String) = Text(text)
 
+  /** Creates a processing instruction. */
+  def createProcInstr(target: String, data: String) = makeProcInstr(target, data)
 }
diff --git a/src/library/scala/xml/parsing/TokenTests.scala b/src/library/scala/xml/parsing/TokenTests.scala
index 1918a53..e7b8eb7 100644
--- a/src/library/scala/xml/parsing/TokenTests.scala
+++ b/src/library/scala/xml/parsing/TokenTests.scala
@@ -1,16 +1,15 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |                                         **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: TokenTests.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.xml.parsing;
-
+package scala.xml
+package parsing
 
 /**
  * Helper functions for parsing XML fragments
@@ -18,33 +17,33 @@ package scala.xml.parsing;
 trait TokenTests {
 
   /** (#x20 | #x9 | #xD | #xA) */
-  final def isSpace( ch:Char ): Boolean = ch match {
+  final def isSpace(ch: Char): Boolean = ch match {
     case '\u0009' | '\u000A' | '\u000D' | '\u0020' => true
-    case _                                         => false;
+    case _                                         => false
   }
-
   /** (#x20 | #x9 | #xD | #xA)+ */
-  final def isSpace(cs: Seq[Char]): Boolean = {
-    val it = cs.elements;
-    it.hasNext && it.forall { isSpace };
-  }
+  final def isSpace(cs: Seq[Char]): Boolean = cs.nonEmpty && (cs forall isSpace)
+  
+  /** These are 99% sure to be redundant but refactoring on the safe side. */
+  def isAlpha(c: Char) = (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')
+  def isAlphaDigit(c: Char) = isAlpha(c) || (c >= '0' && c <= '9')
 
   /** NameChar ::= Letter | Digit | '.' | '-' | '_' | ':' 
    *             | CombiningChar | Extender
    *
    * see [4] and Appendix B of XML 1.0 specification
   */
-  def isNameChar(ch: Char) = isNameStart(ch) || (ch match {
-    case '.' | '-' | ':' => true;
-    case _ => java.lang.Character.getType( ch ).asInstanceOf[Byte] match {
-      case java.lang.Character.COMBINING_SPACING_MARK => true; // Mc
-      case java.lang.Character.ENCLOSING_MARK => true;         // Me
-      case java.lang.Character.NON_SPACING_MARK => true;       // Mn
-      case java.lang.Character.MODIFIER_LETTER => true;        // Lm
-      case java.lang.Character.DECIMAL_DIGIT_NUMBER => true;   // Nd
-      case _ => false;
-    }
-  });
+  def isNameChar(ch: Char) = {
+    import java.lang.Character._
+    // The constants represent groups Mc, Me, Mn, Lm, and Nd.
+
+    isNameStart(ch) || (getType(ch).toByte match {
+      case COMBINING_SPACING_MARK | 
+              ENCLOSING_MARK | NON_SPACING_MARK |
+              MODIFIER_LETTER | DECIMAL_DIGIT_NUMBER    => true
+      case _                                            => ".-:" contains ch
+    })
+  }
 
   /** NameStart ::= ( Letter | '_' )
    *  where Letter means in one of the Unicode general 
@@ -53,48 +52,27 @@ trait TokenTests {
    *  We do not allow a name to start with ':'.
    *  see [3] and Appendix B of XML 1.0 specification
    */ 
-  def isNameStart(ch: Char) = 
-    java.lang.Character.getType(ch).asInstanceOf[Byte] match {
-      case java.lang.Character.LOWERCASE_LETTER => true;
-      case java.lang.Character.UPPERCASE_LETTER => true;
-      case java.lang.Character.OTHER_LETTER     => true;
-      case java.lang.Character.TITLECASE_LETTER => true;
-      case java.lang.Character.LETTER_NUMBER    => true;
-      case _ => ch match {
-        case '_' => true
-        case _ => false;
-      }
+  def isNameStart(ch: Char) = {
+    import java.lang.Character._
+    
+    getType(ch).toByte match {
+      case LOWERCASE_LETTER |
+              UPPERCASE_LETTER | OTHER_LETTER |
+              TITLECASE_LETTER | LETTER_NUMBER    => true
+      case _                                      => ch == '_'
     }
+  }
   
   /** Name ::= ( Letter | '_' ) (NameChar)*
    *
    *  see  [5] of XML 1.0 specification
    */
-  def isName(s: String): Boolean = {
-    if( s.length() > 0 ) {
-      val y           = s.elements;
-      if (isNameStart(y.next)) {
-        while (y.hasNext && isNameChar(y.next)) {};
-        !y.hasNext
-      } else false;
-    } else false;
-  }
+  def isName(s: String) =
+    s.nonEmpty && isNameStart(s.head) && (s.tail forall isNameChar)
 
-  def isPubIDChar(ch: Char): Boolean = {
-    //Console.println("char: '" + ch + "'");
-    ch match {
-      case '\u0020' | '\u000D' | '\u000A' => true;
-      case _ if
-        (('0' <= ch && ch <= '9') || ('a' <= ch && ch <= 'z') ||
-         ('A' <= ch && ch <= 'Z')) => true;
-      case '-' | '\''| '(' | ')' | '+' | ',' | '.' |
-           '/' | ':' | '=' | '?' | ';' | '!' | '*' |
-           '#' | '@' | '$' | '_' | '%' => true
-      case _ =>
-        //Console.println("false: '" + ch + "'");
-        false;
-    }
-  }
+  def isPubIDChar(ch: Char): Boolean =
+    isAlphaDigit(ch) || (isSpace(ch) && ch != '\u0009') ||
+    ("""-\()+,./:=?;!*#@$_%""" contains ch)
 
   /**
    * Returns true if the encoding name is a valid IANA encoding.
@@ -104,43 +82,13 @@ trait TokenTests {
    *
    * @param ianaEncoding The IANA encoding name.
    */
-  def isValidIANAEncoding(ianaEncoding: Seq[Char]): Boolean = {
-    val it = ianaEncoding.elements;
-    if (!it.hasNext)
-      return false;
-    
-    var c = it.next;
-    if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')) {
-      while (it.hasNext) {
-        c = it.next;
-        if ((c < 'A' || c > 'Z') && (c < 'a' || c > 'z') &&
-            (c < '0' || c > '9') && c != '.' && c != '_' &&
-            c != '-') {
-              return false;
-            }
-      }
-      return true;
-    } else 
-      return false;
-  } // isValidIANAEncoding(String): Boolean
-  
-  def checkSysID( s:String ): Boolean = {
-    s.indexOf('"'.asInstanceOf[Int]) == -1 || s.indexOf('\''.asInstanceOf[Int]) == -1 
-  }
-    
-  def checkPubID(s: String): Boolean = {
-    //Console.println("checkPubID of \""+s+"\"");
-    if (s.length() > 0) {
-      val y = s.elements;
-      var c = ' ';
-      while (y.hasNext && isPubIDChar(c)) { 
-        //Console.println(c);
-        c = y.next
-      };
-      !y.hasNext
-    }
-    else
-      true
-  }
+  def isValidIANAEncoding(ianaEncoding: Seq[Char]) = {
+    def charOK(c: Char) = isAlphaDigit(c) || ("._-" contains c)
 
+    ianaEncoding.nonEmpty && isAlpha(ianaEncoding.head) &&
+    (ianaEncoding.tail forall charOK)
+  }
+  
+  def checkSysID(s: String) = List('"', '\'') exists (c => !(s contains c))
+  def checkPubID(s: String) = s forall isPubIDChar
 }
diff --git a/src/library/scala/xml/parsing/ValidatingMarkupHandler.scala b/src/library/scala/xml/parsing/ValidatingMarkupHandler.scala
index 8b35973..498214f 100644
--- a/src/library/scala/xml/parsing/ValidatingMarkupHandler.scala
+++ b/src/library/scala/xml/parsing/ValidatingMarkupHandler.scala
@@ -1,16 +1,15 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: ValidatingMarkupHandler.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.xml.parsing
-
+package scala.xml
+package parsing
 
 import scala.xml.dtd._
 import scala.util.logging.Logged
@@ -51,7 +50,7 @@ abstract class ValidatingMarkupHandler extends MarkupHandler with Logged {
       log("advanceDFA(trans): " + trans)
       trans.get(ContentModel.ElemName(label)) match {
           case Some(qNew) => qCurrent = qNew
-          case _          => reportValidationError(pos, "DTD says, wrong element, expected one of "+trans.keys.toString());
+          case _          => reportValidationError(pos, "DTD says, wrong element, expected one of "+trans.keys);
         }
     }
     // advance in current automaton
diff --git a/src/library/scala/xml/parsing/XhtmlEntities.scala b/src/library/scala/xml/parsing/XhtmlEntities.scala
index 75bfbe7..8517bc8 100644
--- a/src/library/scala/xml/parsing/XhtmlEntities.scala
+++ b/src/library/scala/xml/parsing/XhtmlEntities.scala
@@ -1,10 +1,21 @@
-// $Id: XhtmlEntities.scala 13983 2008-02-14 01:54:12Z mihaylov $
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
 
-package scala.xml.parsing
 
-import scala.xml.dtd.{IntDef, ParsedEntityDecl}
+package scala.xml
+package parsing
 
-/* (c) David Pollak 2007 WorldWide Conferencing, LLC */
+import scala.xml.dtd.{ IntDef, ParsedEntityDecl }
+
+/** <p>
+ *    (c) David Pollak 2007 WorldWide Conferencing, LLC.
+ *  </p>
+ */
 object XhtmlEntities {
   val entList = List(("quot",34), ("amp",38), ("lt",60), ("gt",62), ("nbsp",160), ("iexcl",161), ("cent",162), ("pound",163), ("curren",164), ("yen",165),
       ("euro",8364), ("brvbar",166), ("sect",167), ("uml",168), ("copy",169), ("ordf",170), ("laquo",171), ("shy",173), ("reg",174), ("trade",8482), 
@@ -34,7 +45,7 @@ object XhtmlEntities {
       ("xi",958), ("omicron",959), ("pi",960), ("rho",961), ("sigmaf",962), ("sigma",963), ("tau",964), ("upsilon",965), ("phi",966), ("chi",967), 
       ("psi",968), ("omega",969), ("thetasym",977), ("upsih",978), ("piv",982))
    
-  val entMap: Map[String, Char] = Map.empty ++ entList.map { case (name, value) => (name, value.toChar)}
+  val entMap: Map[String, Char] = Map.empty[String, Char] ++ entList.map { case (name, value) => (name, value.toChar)}
   
   val entities = entList.
         map { case (name, value) => (name, new ParsedEntityDecl(name, new IntDef(value.toChar.toString)))}
diff --git a/src/library/scala/xml/parsing/XhtmlParser.scala b/src/library/scala/xml/parsing/XhtmlParser.scala
index 5f8bf2d..0647add 100644
--- a/src/library/scala/xml/parsing/XhtmlParser.scala
+++ b/src/library/scala/xml/parsing/XhtmlParser.scala
@@ -1,55 +1,36 @@
-// $Id: XhtmlParser.scala 13983 2008-02-14 01:54:12Z mihaylov $
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
 
-package scala.xml.parsing
 
-import scala.io.{Source}
+package scala.xml
+package parsing
 
-/**
- * Extends the Markup Parser to do the right thing (tm) with PCData blocks.
- * (c) David Pollak, 2007 WorldWide Conferencing, LLC
- */
-trait PCDataMarkupParser[PCM <: MarkupParser with MarkupHandler] extends MarkupParser { self: PCM =>
-
-  /** '<! CharData ::= [CDATA[ ( {char} - {char}"]]>"{char} ) ']]>'
-   *
-   * see [15]
-   */
-  override def xCharData: NodeSeq = {
-    xToken("[CDATA[")
-    val pos1 = pos
-    val sb: StringBuilder = new StringBuilder()
-    while (true) {
-      if (ch==']'  &&
-          { sb.append(ch); nextch; ch == ']' } &&
-          { sb.append(ch); nextch; ch == '>' } ) {
-            sb.setLength(sb.length - 2);
-            nextch; 
-            return PCData(sb.toString)
-          } else sb.append( ch );
-      nextch; 
-    }
-    // bq: (todo) increase grace when meeting CDATA section
-    throw FatalError("this cannot happen");
-  }
-}
+import scala.io.Source
 
-/**
- * An XML Parser that preserves CDATA blocks and knows about HtmlEntities.
- * (c) David Pollak, 2007 WorldWide Conferencing, LLC
+/** <p>
+ *    An XML Parser that preserves CDATA blocks and knows about HtmlEntities.
+ *  </p>
+ *  <p>
+ *    (c) David Pollak, 2007 WorldWide Conferencing, LLC.
+ *  </p>
  */
-class XhtmlParser(val input: Source) extends ConstructingHandler with PCDataMarkupParser[XhtmlParser] with ExternalSources  {
+class XhtmlParser(val input: Source) extends ConstructingHandler with MarkupParser with ExternalSources  {
   val preserveWS = true
   ent ++= XhtmlEntities()
 }
 
-/**
- * Convenience method that instantiates, initializes and runs an XhtmlParser
- * (c) Burak Emir
+/** <p>
+ *    Convenience method that instantiates, initializes and runs an XhtmlParser.
+ *  </p>
+ *  <p>
+ *    (c) Burak Emir
+ *  </p>
  */
 object XhtmlParser {
-  def apply(source: Source): NodeSeq = {
-    val p = new XhtmlParser(source)
-    p.nextch
-    p.document
-  }
+  def apply(source: Source): NodeSeq = new XhtmlParser(source).initialize.document
 }
diff --git a/src/library/scala/xml/path/Expression.scala b/src/library/scala/xml/path/Expression.scala
deleted file mode 100644
index e5a8f66..0000000
--- a/src/library/scala/xml/path/Expression.scala
+++ /dev/null
@@ -1,66 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |                                         **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: Expression.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala.xml.path;
-
-
-object Expression {
-
-  final def testFromString(x: String): Test = {
-    x.charAt(0) match {
-      case '*' if( x.length() == 1 ) => WildcardTest;
-      case _                         => NameTest(x);
-    }
-  }
-  
-  case class FExp(e:Expr, c:Cond) {
-    def eval(n: Node): NodeSeq = new NodeSeq { val theSeq=Nil}; // @todo
-  }
-  
-  abstract class GenExp ;
-  case class Attrib(test: NameTest, e: Expr) extends GenExp;
-
-  abstract class Expr extends GenExp {
-    def \ (x: String) = 
-      if( x=="*") 
-        Child(WildcardTest, this)
-      else
-        Child(NameTest(x), this);
-    
-    def \\ (x: String) = 
-      if( x=="*") 
-        DescOrSelf(WildcardTest, this)
-      else
-        DescOrSelf(NameTest(x), this);
-    
-    def apply(c: Cond) = FExp(this, c);
-    
-    def eval(n: Node): NodeSeq = new NodeSeq { val theSeq=Nil}; // @todo
-  }
-  
-  case object Root extends Expr;
-  
-  case class Child(test: Test, e: Expr) extends Expr;
-  case class DescOrSelf(test: Test, e: Expr) extends Expr;
-  
-  
-  abstract class Test;
-  
-  case object WildcardTest extends Test; //                "x \ *  "
-  case class  NameTest(label: String) extends Test; //     "x \ bar"
-  
-  
-  abstract class Cond; 
-  
-  case class Exists(p: GenExp) extends Cond ;  //          "p [ p ]"
-  case class Equals(p: Expr, c:String) extends Cond ; //   "p [ @p == bla ]"
-    
-}
diff --git a/src/library/scala/xml/persistent/CachedFileStorage.scala b/src/library/scala/xml/persistent/CachedFileStorage.scala
index 3470e25..b2096d3 100644
--- a/src/library/scala/xml/persistent/CachedFileStorage.scala
+++ b/src/library/scala/xml/persistent/CachedFileStorage.scala
@@ -1,14 +1,14 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: CachedFileStorage.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.xml.persistent
+package scala.xml
+package persistent
 
 import java.io.{File, FileOutputStream} 
 import java.nio.ByteBuffer
@@ -73,12 +73,12 @@ extends java.lang.Thread with scala.util.logging.Logged {
     import scala.io.Source
     import scala.xml.parsing.ConstructingParser
     log("[load]\nloading "+theFile)
-    val src = Source.fromFile( theFile )
+    val src = Source.fromFile(theFile)
     log("parsing "+theFile)
     val res = ConstructingParser.fromSource(src,false).document.docElem(0)
     switch
     log("[load done]")
-    res.child.elements
+    res.child.iterator
   }
   
   /** saves the XML to file */
diff --git a/src/library/scala/xml/persistent/Index.scala b/src/library/scala/xml/persistent/Index.scala
index 5b8d05f..92825f9 100644
--- a/src/library/scala/xml/persistent/Index.scala
+++ b/src/library/scala/xml/persistent/Index.scala
@@ -1,15 +1,15 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Index.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.xml.persistent
+package scala.xml
+package persistent
 
 /** an Index returns some unique key that is part of a node
  */
diff --git a/src/library/scala/xml/persistent/IndexedStorage.scala b/src/library/scala/xml/persistent/IndexedStorage.scala
deleted file mode 100644
index c4dd94c..0000000
--- a/src/library/scala/xml/persistent/IndexedStorage.scala
+++ /dev/null
@@ -1,48 +0,0 @@
-/*                     __                                               *\
-**     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
-**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
-** /____/\___/_/ |_/____/_/ | |                                         **
-**                          |/                                          **
-\*                                                                      */
-
-// $Id: IndexedStorage.scala 16894 2009-01-13 13:09:41Z cunei $
-
-
-package scala.xml.persistent
-
-import scala.collection.mutable
-import java.io.File
-
-/** indexed multiset of xml trees. The index may be an arbitrary totally
- * type, especially one can construct indices by selecting parts of
- * xml nodes.
- */
-class IndexedStorage[A](file:  File, index: Index[A]) //@todo
-extends CachedFileStorage(file) {
-
-  private var theMap: mutable.Map[A,Node] = new mutable.HashMap[A,Node]()
-
-  super.initialNodes.foreach { x:Node => this += x }
-
-  this.dirty = false
-
-  def += (e: Node): Unit = synchronized { 
-    log("added element at index '"+index(e)+"'")
-    dirty = true
-    theMap(index(e)) = e
-  }
-  
-  def -= (e: Node): Unit = synchronized { 
-    log("removed element at index '"+index(e)+"'")
-    dirty = true
-    theMap -= index( e )
-  }
-  
-  def nodes: Iterator[Node] = synchronized { 
-    theMap.values
-  }
-
-  def lookup(n: A): Option[Node] = theMap.get(n)
-
-}
diff --git a/src/library/scala/xml/persistent/SetStorage.scala b/src/library/scala/xml/persistent/SetStorage.scala
index cbab0b7..b5e8e51 100644
--- a/src/library/scala/xml/persistent/SetStorage.scala
+++ b/src/library/scala/xml/persistent/SetStorage.scala
@@ -1,14 +1,14 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: SetStorage.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.xml.persistent
+package scala.xml
+package persistent
 
 import scala.collection.mutable
 import java.io.File
@@ -27,7 +27,7 @@ class SetStorage(file: File) extends CachedFileStorage(file) {
   {
     val it = super.initialNodes
     dirty = it.hasNext
-    for(val x <- it) {
+    for(x <- it) {
       theSet += x;
     }
   }
@@ -38,6 +38,6 @@ class SetStorage(file: File) extends CachedFileStorage(file) {
 
   def -= (e: Node): Unit = synchronized { this.dirty = true; theSet -= e }
 
-  def nodes = synchronized { theSet.elements }
+  def nodes = synchronized { theSet.iterator }
 
 }
diff --git a/src/library/scala/xml/pull/XMLEvent.scala b/src/library/scala/xml/pull/XMLEvent.scala
index 7f7d831..375483c 100644
--- a/src/library/scala/xml/pull/XMLEvent.scala
+++ b/src/library/scala/xml/pull/XMLEvent.scala
@@ -1,36 +1,59 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: XMLEvent.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.xml.pull
+package scala.xml
+package pull
 
-/** This class represents an XML event for pull parsing.
- *  Pull parsing means that during the traversal of the XML
- *  tree we are parsing, each "event" is returned to the caller
- *  and the traversal is suspended.
+/** An XML event for pull parsing.  All events received during
+ * parsing will be one of the subclasses of this trait.
  */
 trait XMLEvent
 
-/** An element is encountered the first time */
+/** 
+ * An Element's start tag was encountered.
+ * @param pre prefix, if any, on the element.  This is the `xs` in `<xs:string>foo</xs:string>`.
+ * @param label the name of the element, not including the prefix
+ * @param attrs any attributes on the element
+ */
 case class EvElemStart(pre: String, label: String, attrs: MetaData, scope: NamespaceBinding) extends XMLEvent 
 
-/** An element is encountered the last time */
+/** 
+ * An Element's end tag was encountered.
+ * @param pre prefix, if any, on the element.  This is the `xs` in `<xs:string>foo</xs:string>`.
+ * @param label the name of the element, not including the prefix
+ */
 case class EvElemEnd(pre: String, label: String) extends XMLEvent 
-/** A text node is encountered */
+
+/** 
+ * A text node was encountered.
+ * @param text the text that was found
+ */
 case class EvText(text: String) extends XMLEvent
 
-/** An entity reference is encountered */
+/** An entity reference was encountered.
+ * @param the name of the entity, e.g. `gt` when encountering the entity `>` 
+ */
 case class EvEntityRef(entity: String) extends XMLEvent
 
-/** A processing instruction is encountered */
+/** 
+ * A processing instruction was encountered.
+ * @param target the "PITarget" of the processing instruction.  For the instruction `<?foo bar="baz"?>`, the target would 
+ * be `foo`
+ * @param text the remainder of the instruction.  For the instruction `<?foo bar="baz"?>`, the text would
+ * be `bar="baz"`
+ * @see [[http://www.w3.org/TR/REC-xml/#sec-pi]]
+ */
 case class EvProcInstr(target: String, text: String) extends XMLEvent
 
-/** A comment is encountered */
+/** 
+ * A comment was encountered 
+ * @param text the text of the comment
+ */
 case class EvComment(text: String) extends XMLEvent
diff --git a/src/library/scala/xml/pull/XMLEventReader.scala b/src/library/scala/xml/pull/XMLEventReader.scala
index 43ad99f..ea84cbf 100644
--- a/src/library/scala/xml/pull/XMLEventReader.scala
+++ b/src/library/scala/xml/pull/XMLEventReader.scala
@@ -1,146 +1,146 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2003-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: XMLEventReader.scala 16894 2009-01-13 13:09:41Z cunei $
 
+package scala.xml
+package pull
 
-package scala.xml.pull
-
-
-import java.lang.{Runnable, Thread}
+import java.util.concurrent.LinkedBlockingQueue
+import java.nio.channels.ClosedChannelException
 
 import scala.io.Source
-import scala.xml.parsing.{ExternalSources, MarkupHandler, MarkupParser}
+import scala.xml.parsing.{ ExternalSources, MarkupHandler, MarkupParser }
 
-/** <p>
- *   A pull parser that offers to view an XML document as a series of events.
- *   Please note that this API might change. Here's how to use this class
- *  </p><pre>
- *  <b>import</b> scala.xml._
- *  <b>import</b> scala.xml.pull._
- *  <b>import</b> scala.io.Source
- *
- *  <b>object</b> reader {
- *    <b>val</b> src = Source.fromString("<hello><world/></hello>")
- *    <b>val</b> er = new XMLEventReader().initialize(src)
- * 
- *    <b>def</b> main(args: Array[String]) {
- *      Console.println(er.next)
- *      Console.println(er.next)
- *    }
- *  }
- *  </pre>
+/** 
+ * Main entry point into creating an event-based XML parser.  Treating this 
+ * as a [[scala.collection.Iterator]] will provide access to the generated events.
+ * @param src A [[scala.io.Source]] for XML data to parse
  *
  *  @author Burak Emir
+ *  @author Paul Phillips
  */
-class XMLEventReader extends Iterator[XMLEvent] {
-
-  var src:Source = null
-  def getSource = this.src
-  def initialize(src: Source): this.type = {
-    this.src = src
-    this.parserThread = new Thread(new Parser())
-    this.parserThread.start()
-    this
-  }
-
-  // -- this part of the class is for communication with the thread
-  var xmlEvent: XMLEvent = null
-  var continue: Boolean = true
-  
-  def myresume = synchronized {
-    while (continue) {
-      wait()
-    }
-    continue = true
-    notify()
-  }
-  def getAndClearEvent: XMLEvent = synchronized {
-    while (xmlEvent eq null) {
-      wait()
-    }
-    val r = xmlEvent
-    xmlEvent = null
-    r
-  }
-  def setEvent(e: XMLEvent) { 
-    xmlEvent = e
-  }
+class XMLEventReader(src: Source) extends ProducerConsumerIterator[XMLEvent]
+{
+  // We implement a pull parser as an iterator, but since we may be operating on
+  // a stream (e.g. XML over a network) there may be arbitrarily long periods when
+  // the queue is empty.  Fortunately the ProducerConsumerIterator is ideally
+  // suited to this task, possibly because it was written for use by this class.
+    
+  // to override as necessary
+  val preserveWS = true
   
-  def doNotify(): NodeSeq = synchronized {
-    XMLEventReader.this.continue = false
-    notify()
-    while (!XMLEventReader.this.continue) {
-      try { wait() } catch { 
-       case _: java.lang.InterruptedException => /* ignore */
-	  }  
-	}
-    NodeSeq.Empty
-  }
-
-  // iterator methods
-
-  def next: XMLEvent = {
-    myresume
-    val r = getAndClearEvent
-    r
-  }
+  override val MaxQueueSize = 1000
+  protected case object POISON extends XMLEvent
+  val EndOfStream = POISON
   
-  def hasNext = true
-
-  // After calling stop, one must call initialize to be able to get new events.
+  // thread machinery
+  private[this] val parser = new Parser(src)
+  private[this] val parserThread = new Thread(parser, "XMLEventReader")
+  parserThread.start
+  // enqueueing the poison object is the reliable way to cause the
+  // iterator to terminate; hasNext will return false once it sees it.
+  // Calling interrupt() on the parserThread is the only way we can get
+  // it to stop producing tokens since it's lost deep in document() -
+  // we cross our fingers the interrupt() gets to its target, but if it
+  // fails for whatever reason the iterator correctness is not impacted,
+  // only performance (because it will finish the entire XML document,
+  // or at least as much as it can fit in the queue.)
   def stop = {
-    continue = true;
-    parserThread.interrupt();
-    parserThread = null;
+    produce(POISON)
+    parserThread.interrupt()
   }
-
-  var parserThread: Thread = null
-
-  class Parser extends MarkupHandler with MarkupParser with ExternalSources with Runnable {
-
-    val preserveWS = true
-    lazy val input = XMLEventReader.this.getSource
-	// document must contain one element - avoid spurious syntax error
-    final val ignore_node = <ignore/>
-
-    override def elemStart(pos: Int, pre: String, label: String, attrs: MetaData, scope: NamespaceBinding) {
-      setEvent(EvElemStart(pre, label, attrs, scope)); doNotify
-    }
-
-    override def elemEnd(pos: Int, pre: String, label: String) {
-      setEvent(EvElemEnd(pre, label)); doNotify
+  
+  private class Parser(val input: Source) extends MarkupHandler with MarkupParser with ExternalSources with Runnable {
+    val preserveWS = XMLEventReader.this.preserveWS
+
+    // this is Parser's way to add to the queue - the odd return type
+    // is to conform to MarkupHandler's interface
+    def setEvent(es: XMLEvent*): NodeSeq = {
+      es foreach produce        
+      NodeSeq.Empty
     }
 
-    final def elem(pos: Int, pre: String, label: String, attrs: MetaData, pscope: NamespaceBinding, nodes: NodeSeq): NodeSeq = 
-      ignore_node
-
-    def procInstr(pos: Int, target: String, txt: String): NodeSeq = {
-      setEvent(EvProcInstr(target, txt)); doNotify
+    override def elemStart(pos: Int, pre: String, label: String, attrs: MetaData, scope: NamespaceBinding) {
+      setEvent(EvElemStart(pre, label, attrs, scope))
     }
-
-    def comment(pos: Int, txt: String): NodeSeq = {
-      setEvent(EvComment(txt)); doNotify
+    override def elemEnd(pos: Int, pre: String, label: String) { 
+      setEvent(EvElemEnd(pre, label))
     }
 
-    def entityRef(pos: Int, n: String): NodeSeq = {
-      setEvent(EvEntityRef(n)); doNotify
-    }
+    // this is a dummy to satisfy MarkupHandler's API
+    final def elem(pos: Int, pre: String, label: String, attrs: MetaData, pscope: NamespaceBinding, nodes: NodeSeq): NodeSeq = <ignore/>
 
-    def text(pos: Int, txt:String): NodeSeq = {
-      setEvent(EvText(txt)); doNotify
-    }
+    def procInstr(pos: Int, target: String, txt: String)  = setEvent(EvProcInstr(target, txt))
+    def comment(pos: Int, txt: String)                    = setEvent(EvComment(txt))
+    def entityRef(pos: Int, n: String)                    = setEvent(EvEntityRef(n))
+    def text(pos: Int, txt:String)                        = setEvent(EvText(txt))
 
     override def run() {
       curInput = input
-      this.nextch
-      doNotify()
-      this.document()
+      interruptibly { this.initialize.document() }
+      setEvent(POISON)
     }
   }
 }
+
+// An iterator designed for one or more producers to generate
+// elements, and a single consumer to iterate.  Iteration will continue
+// until closeIterator() is called, after which point producers
+// calling produce() will receive interruptions.
+//
+// Since hasNext may block indefinitely if nobody is producing,
+// there is also an available() method which will return true if
+// the next call hasNext is guaranteed not to block.
+//
+// This is not thread-safe for multiple consumers!
+trait ProducerConsumerIterator[T >: Null] extends Iterator[T]
+{
+  // abstract - iterator-specific distinguished object for marking eos
+  val EndOfStream: T
+  
+  // defaults to unbounded - override to positive Int if desired
+  val MaxQueueSize = -1
+  
+  def interruptibly[T](body: => T): Option[T] = try Some(body) catch {
+    case _: InterruptedException    => Thread.currentThread.interrupt() ; None
+    case _: ClosedChannelException  => None
+  }    
+  
+  private[this] lazy val queue =
+    if (MaxQueueSize < 0) new LinkedBlockingQueue[T]()
+    else new LinkedBlockingQueue[T](MaxQueueSize)
+  private[this] var buffer: T = _
+  private def fillBuffer() = {
+    buffer = interruptibly(queue.take) getOrElse EndOfStream
+    isElement(buffer)
+  }
+  private def isElement(x: T) = x != null && x != EndOfStream  
+  private def eos() = buffer == EndOfStream
+  
+  // public producer interface - this is the only method producers call, so
+  // LinkedBlockingQueue's synchronization is all we need.
+  def produce(x: T): Unit = if (!eos) interruptibly(queue put x)
+
+  // consumer/iterator interface - we need not synchronize access to buffer
+  // because we required there to be only one consumer.
+  def hasNext() = !eos && (buffer != null || fillBuffer)
+  def next() = {
+    if (eos) throw new NoSuchElementException("ProducerConsumerIterator")
+    if (buffer == null) fillBuffer
+    
+    drainBuffer
+  }
+  def available() = isElement(buffer) || isElement(queue.peek)
+  
+  private def drainBuffer() = {
+    assert(!eos)
+    val res = buffer
+    buffer = null
+    res
+  }
+}
diff --git a/src/library/scala/xml/pull/package.scala b/src/library/scala/xml/pull/package.scala
new file mode 100644
index 0000000..3742c55
--- /dev/null
+++ b/src/library/scala/xml/pull/package.scala
@@ -0,0 +1,41 @@
+package scala.xml
+
+/**
+ * Classes needed to view an XML document as a series of events.  The document
+ * is parsed by an [[scala.xml.pull.XMLEventReader]] instance.  You can treat it as
+ * an [[scala.collection.Iterator]] to retrieve the events, which are all
+ * subclasses of [[scala.xml.pull.XMLEvent]].
+ *
+ * {{{
+ * scala> val source = Source.fromString("""<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+ * <?instruction custom value="customvalue"?>
+ * <!DOCTYPE foo [
+ *   <!ENTITY bar "BAR">
+ * ]><foo>Hello<!-- this is a comment --><bar>&bar;</bar><bar>></bar></foo>""")
+ *
+ * source: scala.io.Source = non-empty iterator
+ *
+ * scala> val reader = new XMLEventReader(source)
+ * reader: scala.xml.pull.XMLEventReader = non-empty iterator
+ *
+ * scala> reader.foreach{ println(_) }
+ * EvProcInstr(instruction,custom value="customvalue")
+ * EvText(
+ * )
+ * EvElemStart(null,foo,,)
+ * EvText(Hello)
+ * EvComment( this is a comment )
+ * EvElemStart(null,bar,,)
+ * EvText(BAR)
+ * EvElemEnd(null,bar)
+ * EvElemStart(null,bar,,)
+ * EvEntityRef(gt)
+ * EvElemEnd(null,bar)
+ * EvElemEnd(null,foo)
+ * EvText(
+ *
+ * )
+ *
+ * }}}
+ */
+package object pull
diff --git a/src/library/scala/xml/transform/BasicTransformer.scala b/src/library/scala/xml/transform/BasicTransformer.scala
index 69816c2..09d7ea9 100644
--- a/src/library/scala/xml/transform/BasicTransformer.scala
+++ b/src/library/scala/xml/transform/BasicTransformer.scala
@@ -1,153 +1,64 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: BasicTransformer.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.xml.transform
+package scala.xml
+package transform
 
 /** A class for XML transformations.
  *
  *  @author  Burak Emir
  *  @version 1.0
  */
-abstract class BasicTransformer extends Function1[Node,Node] {
-
-  protected case class NeedsCopy(result: Seq[Node]) extends Throwable
-
-  /** Returns a new node buffer with the first <code>pos</code> elements
-   *  from <code>ns</code>.
-   *
-   *  @param pos ..
-   *  @param ns  ..
-   *  @return    ..
-   */
-  protected def buffer(pos: Int, ns: Seq[Node]): NodeBuffer = {
-    val nb = new NodeBuffer()
-    var jt = ns.elements
-    var j = 0; while (j < pos-1) {
-      nb.append(jt.next)
-      j += 1
-    }
-    nb
-  }
-
-  /** Turns a nodebuffer into a sequence, so hashcode works.
-   *
-   *  @param nb ..
-   *  @return   ..
-   */
-  protected def freeze(nb: NodeBuffer): Seq[Node] = {
-    val arr = new Array[Node](nb.length)
-    var i = 0
-    val it = nb.elements; while (it.hasNext) {
-      arr(i) = it.next
-      i += 1
-    }
-    val seq: Seq[Node] = arr
-    seq
-  }
-
-  protected def single(ns: Seq[Node]) =
-    1 == ns.length
-
+abstract class BasicTransformer extends Function1[Node,Node]
+{
   /**
    *  @param n  ...
    *  @param ns ...
    *  @return   ...
    */
   protected def unchanged(n: Node, ns: Seq[Node]) =
-    single(ns) && (ns.elements.next.eq(n))
+    ns.length == 1 && (ns.head == n)
 
   /** Call transform(Node) for each node in ns, append results
    *  to NodeBuffer.
    */
-  def transform(it: Iterator[Node], nb: NodeBuffer): Seq[Node] = {
-    while (it.hasNext)
-      nb ++= transform(it.next);
-    freeze(nb)
-  }
+  def transform(it: Iterator[Node], nb: NodeBuffer): Seq[Node] =
+    it.foldLeft(nb)(_ ++= transform(_)).toSeq
 
   /** Call transform(Node) to each node in ns, yield ns if nothing changes,
    *  otherwise a new sequence of concatenated results.
    */
   def transform(ns: Seq[Node]): Seq[Node] = {
-    var i = 0
-    val it = ns.elements
-    try {
-      while (it.hasNext) {
-        val n = it.next
-        val n2 = transform(n)
-        if (!unchanged(n, n2)) {
-          throw NeedsCopy(n2)
-        }
-        i += 1
-      }
-      ns
-    } catch {
-      case NeedsCopy(n2) =>
-        val nb = buffer(i, ns)
-        nb ++= (n2:Iterable[xml.Node])
-        transform(it, nb)
-    }
+    val (xs1, xs2) = ns span (n => unchanged(n, transform(n)))
+    
+    if (xs2.isEmpty) ns
+    else xs1 ++ transform(xs2.head) ++ transform(xs2.tail)
   }
 
   def transform(n: Node): Seq[Node] = {
-    if (n.typeTag$ < 0)
-      n
-    else {
-      val ch = n.child
-      val nch = transform(ch)
-      if (ch.eq(nch))
-        n
-      else
-        Elem(n.prefix, n.label, n.attributes, n.scope, nch:_*)
+    if (n.doTransform) n match {
+      case Group(xs)  => Group(transform(xs)) // un-group the hack Group tag
+      case _          =>
+        val ch = n.child
+        val nch = transform(ch)
+        
+        if (ch eq nch) n
+        else           Elem(n.prefix, n.label, n.attributes, n.scope, nch: _*)
     }
+    else n
   }
 
   def apply(n: Node): Node = {
     val seq = transform(n)
-    if (!single(seq))
+    if (seq.length > 1)
       throw new UnsupportedOperationException("transform must return single node for root");
-    else seq.elements.next
-  }
-}
-
-/*
-class IdentityTransformer extends BasicTransformer {
-  override def transform(n: Node): Seq[Node] = n.match {
-    case <world/> => <xml-world/>
-    case _ => super.transform(n);
-  }
-}
-
-object Foo with Application {
-
-  val tr = new IdentityTransformer;
-  val n = tr( <hello><world/></hello> );
-  Console.println(n);
-
-  val tr2 = new RewriteRule {
-    final override val name = "A rule";
-    override def transform(n: Node) = n.match {
-      case <a/> => <b/><c/>
-      case _    => n
-    }
-  }
-  val tr3 = new RewriteRule {
-    final override val name = "E rule";
-    override def transform(n: Node) = n.match {
-      case <e/> => <f><f/></f>
-      case _    => n
-    }
+    else seq.head
   }
-  val tr4 = new RuleTransformer(tr2, tr3);
-  val m = tr4( <hello><a/><e/></hello> );
-  Console.println(m);
 }
-*/
diff --git a/src/library/scala/xml/transform/RewriteRule.scala b/src/library/scala/xml/transform/RewriteRule.scala
index 438214b..1b6a0cb 100644
--- a/src/library/scala/xml/transform/RewriteRule.scala
+++ b/src/library/scala/xml/transform/RewriteRule.scala
@@ -1,15 +1,15 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: RewriteRule.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.xml.transform
+package scala.xml
+package transform
 
 /** a RewriteRule, when applied to a term, yields either
  *  the resulting of rewriting or the term itself it the rule
diff --git a/src/library/scala/xml/transform/RuleTransformer.scala b/src/library/scala/xml/transform/RuleTransformer.scala
index 1abef2b..2105d14 100644
--- a/src/library/scala/xml/transform/RuleTransformer.scala
+++ b/src/library/scala/xml/transform/RuleTransformer.scala
@@ -1,25 +1,17 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala API                            **
-**    / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: RuleTransformer.scala 16894 2009-01-13 13:09:41Z cunei $
 
 
-package scala.xml.transform
+package scala.xml
+package transform
 
 class RuleTransformer(rules: RewriteRule*) extends BasicTransformer {
-  override def transform(n: Node): Seq[Node] = {
-    var m: Seq[Node] = super.transform(n)
-    val it = rules.elements; while (it.hasNext) {
-      val rule = it.next
-      val m2 = rule.transform(m)
-      //if(!m2.eq(m)) Console.println("applied rule \""+rule.name+"\"");
-      m = m2
-    }
-    m
-  }
+  override def transform(n: Node): Seq[Node] =
+    rules.foldLeft(super.transform(n)) { (res, rule) => rule transform res }
 }
diff --git a/src/manual/scala/man1/Command.scala b/src/manual/scala/man1/Command.scala
index 0aac5a3..abc2b42 100644
--- a/src/manual/scala/man1/Command.scala
+++ b/src/manual/scala/man1/Command.scala
@@ -1,8 +1,7 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author Stephane Micheloud
  */
-//$Id: Command.scala 16894 2009-01-13 13:09:41Z cunei $
 
 package scala.man1
 
@@ -47,7 +46,7 @@ trait Command {
 
   def bugs = Section("REPORTING BUGS",
 
-    "Report bugs to " & Mono("<scala at listes.epfl.ch>") & ".")
+    "Report bugs to " & Mono("http://lampsvn.epfl.ch/trac/scala") & ".")
 
   //private val df = new java.text.SimpleDateFormat("MMM d, yyyy")
   //private val rightNow = new java.util.Date()
diff --git a/src/manual/scala/man1/fsc.scala b/src/manual/scala/man1/fsc.scala
index e8da920..18edcc5 100644
--- a/src/manual/scala/man1/fsc.scala
+++ b/src/manual/scala/man1/fsc.scala
@@ -1,8 +1,7 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author Stephane Micheloud
  */
-//$Id: fsc.scala 16894 2009-01-13 13:09:41Z cunei $
 
 package scala.man1
 
@@ -142,7 +141,8 @@ object fsc extends Command {
     Link(Bold("sbaz") & "(1)", "sbaz.html") & ", " &
     Link(Bold("scala") & "(1)", "scala.html") & ", " &
     Link(Bold("scalac") & "(1)", "scalac.html") & ", " &
-    Link(Bold("scaladoc") & "(1)", "scaladoc.html"))
+    Link(Bold("scaladoc") & "(1)", "scaladoc.html") & ", " &
+    Link(Bold("scalap") & "(1)", "scalap.html"))
 
   def manpage = new Document {
     title = command
diff --git a/src/manual/scala/man1/sbaz.scala b/src/manual/scala/man1/sbaz.scala
index 961b61a..41675c8 100644
--- a/src/manual/scala/man1/sbaz.scala
+++ b/src/manual/scala/man1/sbaz.scala
@@ -1,8 +1,7 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author Stephane Micheloud
  */
-//$Id: sbaz.scala 16894 2009-01-13 13:09:41Z cunei $
 
 package scala.man1
 
@@ -182,7 +181,8 @@ object sbaz extends Command {
     Link(Bold("fsc") & "(1)", "fsc.html") & ", " &
     Link(Bold("scala") & "(1)", "scala.html") & ", " &
     Link(Bold("scalac") & "(1)", "scalac.html") & ", " &
-    Link(Bold("scaladoc") & "(1)", "scaladoc.html"))
+    Link(Bold("scaladoc") & "(1)", "scaladoc.html") & ", " &
+    Link(Bold("scalap") & "(1)", "scalap.html"))
 
   def manpage = new Document {
     title = command
diff --git a/src/manual/scala/man1/scala.scala b/src/manual/scala/man1/scala.scala
index d6b471c..d3c2dcb 100644
--- a/src/manual/scala/man1/scala.scala
+++ b/src/manual/scala/man1/scala.scala
@@ -1,8 +1,7 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author Stephane Micheloud
  */
-//$Id: scala.scala 16894 2009-01-13 13:09:41Z cunei $
 
 package scala.man1
 
@@ -249,7 +248,8 @@ object scala extends Command {
     Link(Bold("fsc") & "(1)", "fsc.html") & ", " &
     Link(Bold("sbaz") & "(1)", "sbaz.html") & ", " &
     Link(Bold("scalac") & "(1)", "scalac.html") & ", " &
-    Link(Bold("scaladoc") & "(1)", "scaladoc.html"))
+    Link(Bold("scaladoc") & "(1)", "scaladoc.html") & ", " &
+    Link(Bold("scalap") & "(1)", "scalap.html"))
 
   def manpage = new Document {
     title = command
diff --git a/src/manual/scala/man1/scalac.scala b/src/manual/scala/man1/scalac.scala
index 8f943aa..7a51ea0 100644
--- a/src/manual/scala/man1/scalac.scala
+++ b/src/manual/scala/man1/scalac.scala
@@ -1,8 +1,7 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author Stephane Micheloud
  */
-//$Id: scalac.scala 16881 2009-01-09 16:28:11Z cunei $
 
 package scala.man1
 
@@ -125,8 +124,8 @@ object scalac extends Command {
         Definition(
           CmdOption("target:", Argument("target")),
           SeqPara(
-            "Specify which backend to use (" & Mono("jvm-1.5,jvm-1.4," &
-            "msil,cldc") & ").",
+            "Specify which backend to use (" & Mono("jvm-1.5," &
+            "msil") & ").",
             "The default value is " & Mono("\"jvm-1.5\"") & " (was " &
             Mono("\"jvm-1.4\"") & " up to Scala version 2.6.1).")),
         Definition(
@@ -351,7 +350,8 @@ object scalac extends Command {
     Link(Bold("fsc") & "(1)", "fsc.html") & ", " &
     Link(Bold("sbaz") & "(1)", "sbaz.html") & ", " &
     Link(Bold("scala") & "(1)", "scala.html") & ", " &
-    Link(Bold("scaladoc") & "(1)", "scaladoc.html"))
+    Link(Bold("scaladoc") & "(1)", "scaladoc.html") & ", " &
+    Link(Bold("scalap") & "(1)", "scalap.html"))
 
   def manpage = new Document {
     title = command
diff --git a/src/manual/scala/man1/scaladoc.scala b/src/manual/scala/man1/scaladoc.scala
index d72a569..5a072c1 100644
--- a/src/manual/scala/man1/scaladoc.scala
+++ b/src/manual/scala/man1/scaladoc.scala
@@ -1,8 +1,8 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright LAMP/EPFL
  * @author Stephane Micheloud
+ * @author Gilles Dubochet
  */
-//$Id: scaladoc.scala 16894 2009-01-13 13:09:41Z cunei $
 
 package scala.man1
 
@@ -45,105 +45,113 @@ object scaladoc extends Command {
     CmdOption("d") & "(see " & Link(Bold("OPTIONS"), "#options") & ", below).",
 
     // tags are defined in class "scala.tools.nsc.doc.DocGenerator"
-    "Supported tag comments are:",
-
-    BulletList(
-      Mono("@author"), Mono("@deprecated"),
-      Mono("@exception") & " (two arguments)",
-      Mono("@param") & " (two arguments)", Mono("@pre"),
-      Mono("@return"), Mono("@see"), Mono("@since"),
-      Mono("@throws") & " (two arguments)",
-      Mono("@todo"), Mono("@version")),
-
-    "See also online document \"" & Link("How to Write Doc Comments for the Javadoc Tool",
-    "http://java.sun.com/j2se/javadoc/writingdoccomments/") & "\" from Sun.")
+    "The recognised format of comments in source is described in the " & Link("online documentation",
+    "http://lampsvn.epfl.ch/trac/scala/wiki/Scaladoc"))
 
   val options = Section("OPTIONS",
 
-    "The generator has a set of standard options that are supported on the " &
-    "current development environment and will be supported in future releases.",
-
     Section("Standard Options",
       DefinitionList(
         Definition(
           CmdOption("d", Argument("directory")),
-          "Specify where to place generated class files."),
+          "Specify where to generate documentation."),
         Definition(
-          CmdOption("access:<access>"),
-          "Show only public, protected/public (default) or all classes " &
-          "and members (" & Mono("public") & ",protected,private)"),
+          CmdOption("version"),
+          "Print product version and exit."),
         Definition(
-          CmdOption("windowtitle", Argument("windowtitle")),
-          "Specify window title of generated HTML documentation"),
+          /*CmdOption("?") & "| " &*/ CmdOption("help"),
+          "Print a synopsis of available options."))),
+
+    Section("Documentation Options",
+      DefinitionList(
         Definition(
-          CmdOption("doctitle", Argument("doctitle")),
-          "Include title for the overview page"),
+          CmdOption("doc-title", Argument("title")),
+          "Define the overall title of the documentation, typically the name of the library being documented."),
         Definition(
-          CmdOption("stylesheetfile", Argument("stylesheetfile")),
-          "File to change style of the generated documentation"),
+          CmdOption("doc-version", Argument("version")),
+          "Define the overall version number of the documentation, typically the version of the library being documented."),
         Definition(
-          CmdOption("header", Argument("pageheader")),
-          "Include header text for each page"),
+          CmdOption("doc-source-url", Argument("url")),
+          "Define a URL to be concatenated with source locations for link to source files."))),
+
+    Section("Compiler Options",
+      DefinitionList(
         Definition(
-          CmdOption("footer", Argument("pagefooter")),
-          "Include footer text for each page"),
+          CmdOption("verbose"),
+          "Output messages about what the compiler is doing"),
         Definition(
-          CmdOption("top", Argument("pagetop")),
-          "Include top text for each page"),
+          CmdOption("deprecation"),
+          SeqPara(
+            "Indicate whether source should be compiled with deprecation " &
+            "information; defaults to " & Mono("off") & " (" &
+            "accepted values are: " & Mono("on") & ", " & Mono("off") &
+            ", " & Mono("yes") & " and " & Mono("no") & ")",
+            "Available since Scala version 2.2.1")),
         Definition(
-          CmdOption("bottom", Argument("pagebottom")),
-          "Include bottom text for each page"),
+          CmdOption("classpath", Argument("path")),
+          SeqPara(
+            "Specify where to find user class files (on Unix-based systems " &
+            "a colon-separated list of paths, on Windows-based systems, a " &
+            "semicolon-separate list of paths). This does not override the " &
+            "built-in (" & Mono("\"boot\"") & ") search path.",
+            "The default class path is the current directory. Setting the " &
+            Mono("CLASSPATH") & " variable or using the " & Mono("-classpath") & " " &
+            "command-line option overrides that default, so if you want to " &
+            "include the current directory in the search path, you must " &
+            "include " & Mono("\".\"") & " in the new settings.")),
         Definition(
-          CmdOption("version"),
-          "Print product version and exit."),
+          CmdOption("sourcepath", Argument("path")),
+          "Specify where to find input source files."),
         Definition(
-          /*CmdOption("?") & "| " &*/ CmdOption("help"),
-          "Print a synopsis of standard options."))))
-
-  val examples = Section("EXAMPLES",
-
-    DefinitionList(
-      Definition(
-        "Generate documentation for a Scala program",
-        CmdLine("HelloWorld.scala")),
-      Definition(
-        "Generation documentation for a Scala program to the destination " &
-        "directory " & Bold("classes"),
-        CmdLine(CmdOption("d", "api") & "HelloWorld.scala")),
-      Definition(
-        "Generate documentation for all Scala files found in the source " &
-        "directory " & Bold("src") & " to the destination directory " &
-        Bold("api"),
-        CmdLine(CmdOption("d", "api") & "src/*.scala"))))
+          CmdOption("bootclasspath", Argument("path")),
+          "Override location of bootstrap class files (where to find the " &
+          "standard built-in classes, such as \"" & Mono("scala.List") & "\")."),
+        Definition(
+          CmdOption("extdirs", Argument("dirs")),
+          "Override location of installed extensions."),
+        Definition(
+          CmdOption("encoding", Argument("encoding")),
+          SeqPara(
+            "Specify character encoding used by source files.",
+            "The default value is platform-specific (Linux: " & Mono("\"UTF8\"") &
+            ", Windows: " & Mono("\"Cp1252\"") & "). Executing the following " &
+            "code in the Scala interpreter will return the default value " &
+            "on your system:",
+            MBold("    scala> ") &
+            Mono("new java.io.InputStreamReader(System.in).getEncoding"))))))
 
   val exitStatus = Section("EXIT STATUS",
 
     MBold(command) & " returns a zero exist status if it succeeds to process " &
     "the specified input files. Non zero is returned in case of failure.")
 
+  override val authors = Section("AUTHORS",
+    
+    "This version of Scaladoc was written by Gilles Dubochet with contributions by Pedro Furlanetto and Johannes Rudolph. " &
+    "It is based on the original Scaladoc (Sean McDirmid, Geoffrey Washburn, Vincent Cremet and Stéphane Michleoud), " &
+    "on vScaladoc (David Bernard), as well as on an unreleased version of Scaladoc 2 (Manohar Jonnalagedda).")
+
   val seeAlso = Section("SEE ALSO",
 
     Link(Bold("fsc") & "(1)", "fsc.html") & ", " &
     Link(Bold("sbaz") & "(1)", "sbaz.html") & ", " &
     Link(Bold("scala") & "(1)", "scala.html") & ", " &
-    Link(Bold("scalac") & "(1)", "scalac.html"))
+    Link(Bold("scalac") & "(1)", "scalac.html") & ", " &
+    Link(Bold("scalap") & "(1)", "scalap.html"))
 
   def manpage = new Document {
     title = command
-    date = "May 1, 2007"
-    author = "Stephane Micheloud"
-    version = "0.4"
+    date = "2 June 2010"
+    author = "Gilles Dubochet"
+    version = "2.0"
     sections = List(
       name,
       synopsis,
       parameters,
       description,
       options,
-      examples,
       exitStatus,
       authors,
-      bugs,
-      copyright,
       seeAlso)
   }
 }
diff --git a/src/manual/scala/man1/scalap.scala b/src/manual/scala/man1/scalap.scala
new file mode 100644
index 0000000..d9fc6d1
--- /dev/null
+++ b/src/manual/scala/man1/scalap.scala
@@ -0,0 +1,108 @@
+/* NSC -- new Scala compiler
+ * Copyright 2005-2010 LAMP/EPFL
+ * @author Stephane Micheloud
+ */
+
+package scala.man1
+
+object scalap extends Command {
+  import _root_.scala.tools.docutil.ManPage._
+
+  protected def cn = new Error().getStackTrace()(0).getClassName()
+
+  val name = Section("NAME",
+
+    MBold(command) & " " & NDash & " Scala class file decoder for the " &
+    Link("Scala 2", "http://scala-lang.org/") & " language")
+
+  val synopsis = Section("SYNOPSIS",
+
+    CmdLine(" [ " & Argument("options") & " ] " & Argument("class name")))
+
+  val parameters = Section("PARAMETERS",
+
+    DefinitionList(
+      Definition(
+        Mono(Argument("options")),
+        "Command line options. See " & Link(Bold("OPTIONS"), "#options") &
+        " below."),
+      Definition(
+        Mono(Argument("class name")),
+        "Full-qualified name of a class to be decoded (such as " &
+        Mono("hello.HelloWorld") & ").")))
+
+  val description = Section("DESCRIPTION",
+
+    "The " & MBold(command) & " tool reads a class file generated by the" &
+    "Scala compiler, and displays object and class definitions.",
+
+    "By default, " & MBold(command) & " looks for the given class file " &
+    "in the current directory. You can specify a separate classpath with " &
+    CmdOption("classpath") & "(see " & Link(Bold("OPTIONS"), "#options") & ", below).")
+
+  val options = Section("OPTIONS",
+
+    "The decoder has a set of standard options that are supported on the " &
+    "current development environment and will be supported in future releases.",
+
+    Section("Standard Options",
+      DefinitionList(
+        Definition(
+          CmdOption("help"),
+          "Display this usage message."),
+        Definition(
+          CmdOption("private"),
+          "Print private definitions."),
+        Definition(
+          CmdOption("verbose"),
+          "Print out additional information."),
+        Definition(
+          CmdOption("version"),
+          "Print product version and exit."),
+        Definition(
+          CmdOption("cp") & "| " & CmdOption("classpath"),
+          "Specify where to find user class files."))))
+
+  val examples = Section("EXAMPLES",
+
+    DefinitionList(
+      Definition(
+        "Display definitions for a generated class file",
+        CmdLine("hello.HelloWorld"))))
+
+  val exitStatus = Section("EXIT STATUS",
+
+    MBold(command) & " returns a zero exist status if it succeeds to process " &
+    "the specified input files. Non zero is returned in case of failure.")
+
+  override val authors = Section("AUTHOR",
+
+    "Written by Ilya Sergey.")
+
+  val seeAlso = Section("SEE ALSO",
+
+    Link(Bold("fsc") & "(1)", "fsc.html") & ", " &
+    Link(Bold("sbaz") & "(1)", "sbaz.html") & ", " &
+    Link(Bold("scala") & "(1)", "scala.html") & ", " &
+    Link(Bold("scalac") & "(1)", "scalac.html") & ", " &
+    Link(Bold("scaladoc") & "(1)", "scaladoc.html"))
+
+  def manpage = new Document {
+    title = command
+    date = "June 8, 2006"
+    author = "Stephane Micheloud"
+    version = "0.2"
+    sections = List(
+      name,
+      synopsis,
+      parameters,
+      description,
+      options,
+      examples,
+      exitStatus,
+      authors,
+      bugs,
+      copyright,
+      seeAlso)
+  }
+}
diff --git a/src/manual/scala/tools/docutil/EmitHtml.scala b/src/manual/scala/tools/docutil/EmitHtml.scala
index 7722cc8..20348ad 100644
--- a/src/manual/scala/tools/docutil/EmitHtml.scala
+++ b/src/manual/scala/tools/docutil/EmitHtml.scala
@@ -1,9 +1,8 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author Stephane Micheloud
  * Adapted from Lex Spoon's sbaz manual
  */
-//$Id: EmitHtml.scala 16881 2009-01-09 16:28:11Z cunei $
 
 package scala.tools.docutil
 
diff --git a/src/manual/scala/tools/docutil/EmitManPage.scala b/src/manual/scala/tools/docutil/EmitManPage.scala
index 97c64c6..2183ae3 100644
--- a/src/manual/scala/tools/docutil/EmitManPage.scala
+++ b/src/manual/scala/tools/docutil/EmitManPage.scala
@@ -1,9 +1,8 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author Stephane Micheloud
  * Adapted from Lex Spoon's sbaz manual
  */
-//$Id: EmitManPage.scala 16894 2009-01-13 13:09:41Z cunei $
 
 package scala.tools.docutil
 
@@ -149,7 +148,7 @@ object EmitManPage {
     out.println(".\\\" ##########################################################################")
     out.println(".\\\" #                      __                                                #")
     out.println(".\\\" #      ________ ___   / /  ___     Scala 2 On-line Manual Pages          #")
-    out.println(".\\\" #     / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL              #")
+    out.println(".\\\" #     / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL              #")
     out.println(".\\\" #   __\\ \\/ /__/ __ |/ /__/ __ |                                          #")
     out.println(".\\\" #  /____/\\___/_/ |_/____/_/ | |    http://scala-lang.org/                #")
     out.println(".\\\" #                           |/                                           #")
diff --git a/src/manual/scala/tools/docutil/ManMaker.scala b/src/manual/scala/tools/docutil/ManMaker.scala
index 2ef87fb..b947e3d 100644
--- a/src/manual/scala/tools/docutil/ManMaker.scala
+++ b/src/manual/scala/tools/docutil/ManMaker.scala
@@ -17,7 +17,7 @@ class ManMaker extends Task {
 
 
   def setCommand(input: String) {
-    command = List.fromArray(input.split(",")).flatMap { s =>
+    command = input.split(",").toList.flatMap { s =>
       val st = s.trim()
       if (st != "") List(st) else Nil
     }
diff --git a/src/manual/scala/tools/docutil/ManPage.scala b/src/manual/scala/tools/docutil/ManPage.scala
index 22c1fd7..83790e1 100644
--- a/src/manual/scala/tools/docutil/ManPage.scala
+++ b/src/manual/scala/tools/docutil/ManPage.scala
@@ -1,9 +1,8 @@
 /* NSC -- new Scala compiler
- * Copyright 2005-2009 LAMP/EPFL
+ * Copyright 2005-2010 LAMP/EPFL
  * @author Stephane Micheloud
  * Adapted from Lex Spoon's sbaz manual
  */
-//$Id: ManPage.scala 16894 2009-01-13 13:09:41Z cunei $
 
 package scala.tools.docutil
 
diff --git a/src/manual/scala/tools/docutil/resources/images/external.gif b/src/manual/scala/tools/docutil/resources/images/external.gif
index dc962b7..3f90b6a 100644
Binary files a/src/manual/scala/tools/docutil/resources/images/external.gif and b/src/manual/scala/tools/docutil/resources/images/external.gif differ
diff --git a/src/manual/scala/tools/docutil/resources/images/scala_logo.png b/src/manual/scala/tools/docutil/resources/images/scala_logo.png
index f89a81c..a1c3972 100644
Binary files a/src/manual/scala/tools/docutil/resources/images/scala_logo.png and b/src/manual/scala/tools/docutil/resources/images/scala_logo.png differ
diff --git a/src/manual/scala/tools/docutil/resources/index.html b/src/manual/scala/tools/docutil/resources/index.html
index 7808cd9..452c1fc 100644
--- a/src/manual/scala/tools/docutil/resources/index.html
+++ b/src/manual/scala/tools/docutil/resources/index.html
@@ -8,7 +8,7 @@
   <meta http-equiv="Content-Style-Type" content="text/css"/>
   <meta http-equiv="Content-Language" content="en"/>
   <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
-  <meta name="Copyright" content="(C) 2002-2009 LAMP/EPFL"/>
+  <meta name="Copyright" content="(C) 2002-2010 LAMP/EPFL"/>
   <meta name="Language" content="en"/>
   <meta name="Description" content="The Scala Programming Language"/>
   <meta name="Author" content="Stephane Micheloud"/>
@@ -45,14 +45,15 @@
 <ul class="ContentList">
   <li>
     <a href="#basic"><b class="SansSerif">Basic Tools</b></a> (<code>sbaz</code>,
-    <code>fsc</code>, <code>scala</code>, <code>scalac</code>, <code>scaladoc</code>)
+    <code>fsc</code>, <code>scala</code>, <code>scalac</code>, <code>scaladoc</code>,
+    <code>scalap</code>)
   </li>
 </ul>
 </div>
 
 <p style="font-size: 90%; margin-left: 2em; margin-right: 2em;">
   <b>NOTE</b> - Some tools have separate reference pages for Windows, Linux and Solaris
-  to accommodate minor differences in configuration and usage -- for example, the character 
+  to accommodate minor differences in configuration and usage -- for example, the character
   used to specify directory separators may be different.
 </p>
 
@@ -86,7 +87,7 @@
   </td>
   <td>
     [<a class="external"
-    href="http://java.sun.com/j2se/1.5.0/docs/tooldocs/solaris/classpath.html">Solaris and Linux</a>] 
+    href="http://java.sun.com/j2se/1.5.0/docs/tooldocs/solaris/classpath.html">Solaris and Linux</a>]
     [<a class="external"
     href="http://java.sun.com/j2se/1.5.0/docs/tooldocs/windows/classpath.html">Windows</a>]
   </td>
@@ -98,7 +99,7 @@
   </td>
   <td>
     [<a class="external"
-    href="http://java.sun.com/j2se/1.5.0/docs/tooldocs/findingclasses.html">Solaris, Linux and Windows</a>] 
+    href="http://java.sun.com/j2se/1.5.0/docs/tooldocs/findingclasses.html">Solaris, Linux and Windows</a>]
   </td>
 </tr>
 </table>
@@ -174,12 +175,23 @@
       [<a href="scaladoc.html">Solaris, Linux and Windows</a>]
     </td>
   </tr>
+  <tr>
+    <td width="13%" valign="top">
+      <span class="tool">scalap</span>
+    </td>
+    <td width="70%" valign="top">
+      The Scala class file decoder.
+    </td>
+    <td width="17%" valign="top">
+      [<a href="scalap.html">Solaris, Linux and Windows</a>]
+    </td>
+  </tr>
 </table>
 
   <hr/>
 
   <div style="font-size:x-small;">
-    Copyright (c) 2002-2009 <a href="http://www.epfl.ch/">EPFL</a>,
+    Copyright (c) 2002-2010 <a href="http://www.epfl.ch/">EPFL</a>,
     Lausanne, unless specified otherwise.<br/>
     All rights reserved.
   </div>
diff --git a/src/mono/bin/scala-net b/src/mono/bin/scala-net
deleted file mode 100644
index a654f00..0000000
--- a/src/mono/bin/scala-net
+++ /dev/null
@@ -1,60 +0,0 @@
-#!/bin/sh
-
-##############################################################################
-# @NAME@ @VERSION@
-##############################################################################
-# @COPYRIGHT@
-#
-# This is free software; see the distribution for copying conditions.
-# There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A
-# PARTICULAR PURPOSE.
-##############################################################################
-
-cygwin=false;
-darwin=false;
-case "`uname`" in
-    CYGWIN*) cygwin=true ;;
-    Darwin*) darwin=true ;;
-esac
-
-# Finding the root folder for this Scala distribution
-SOURCE=$0;
-SCRIPT=`basename "$SOURCE"`;
-while [ -h "$SOURCE" ]; do
-    SCRIPT=`basename "$SOURCE"`;
-    LOOKUP=`ls -ld "$SOURCE"`;
-    TARGET=`expr "$LOOKUP" : '.*-> \(.*\)$'`;
-    if expr "${TARGET:-.}/" : '/.*/$' > /dev/null; then
-        SOURCE=${TARGET:-.};
-    else
-        SOURCE=`dirname "$SOURCE"`/${TARGET:-.};
-    fi;
-done;
-SCALA_HOME=`dirname "$SOURCE"`/..;
-SCALA_HOME=`cd "$SCALA_HOME"; pwd`;
-if $cygwin; then
-    SCALA_HOME=`cygpath --windows --short-name "$SCALA_HOME"`
-    SCALA_HOME=`cygpath --unix "$SCALA_HOME"`
-fi
-
-if [ ! -x "$MONO" ] ; then
-   if [ -d "$MONO_HOME" ] ; then
-       MONO="$MONO_HOME/bin/mono"
-   else
-       MONO="mono"
-   fi
-fi
-
-MSIL_LIBPATH="$SCALA_HOME/lib"
-[ -z "$MONO_PATH" ] || MSIL_LIBPATH="$MSIL_LIBPATH:$MONO_PATH"
-
-if $cygwin; then
-    if [ "$OS" = "Windows_NT" ] && cygpath -m .>/dev/null 2>/dev/null ; then
-        format=mixed
-    else
-        format=windows
-    fi
-    MSIL_LIBPATH=`cygpath --path --$format "$MSIL_LIBPATH"`
-fi
-
-env MONO_PATH="$MSIL_LIBPATH" $MONO "$@"
diff --git a/src/mono/bin/scala-net.bat b/src/mono/bin/scala-net.bat
deleted file mode 100644
index 8018f1c..0000000
--- a/src/mono/bin/scala-net.bat
+++ /dev/null
@@ -1,81 +0,0 @@
- at echo off
-
-rem ##########################################################################
-rem # @NAME@ @VERSION@
-rem ##########################################################################
-rem # @COPYRIGHT@
-rem #
-rem # This is free software; see the distribution for copying conditions.
-rem # There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A
-rem # PARTICULAR PURPOSE.
-rem ##########################################################################
-
-rem We adopt the following conventions:
-rem - System/user environment variables start with a letter
-rem - Local batch variables start with an underscore ('_')
-
-if "%OS%"=="Windows_NT" (
-  @setlocal
-  call :set_home
-  set _ARGS=%*
-) else (
-  set _SCALA_HOME=%SCALA_HOME%
-  rem The following line tests SCALA_HOME instead of _SCALA_HOME, because
-  rem the above change to _SCALA_HOME is not visible within this block.
-  if "%SCALA_HOME%"=="" goto error1
-  call :set_args
-)
-
-rem We use the value of the MONO environment variable if defined
-set _MONO=%MONO%
-if "%_MONO%"=="" (
-  if exist "%MONO_HOME%" (
-    set _MONO=%MONO_HOME%\bin\mono.exe
-  ) else (
-    call :find_mono mono.exe
-  )
-)
-
-set _MSIL_LIBPATH=%_SCALA_HOME%\lib
-if not "%MONO_PATH%"=="" (
-  set _MSIL_LIBPATH=%_MSIL_LIBPATH%;%MONO_PATH%
-)
-
-set MONO_PATH=%_MSIL_LIBPATH%
-%_MONO% %_ARGS%
-goto end
-
-rem ##########################################################################
-rem # subroutines
-
-rem Variable "%~dps0" works on WinXP SP2 or newer
-rem (see http://support.microsoft.com/?kbid=833431)
-rem set _SCALA_HOME=%~dps0..
-:set_home
-  set _BIN_DIR=
-  for %%i in (%~sf0) do set _BIN_DIR=%_BIN_DIR%%%~dpsi
-  set _SCALA_HOME=%_BIN_DIR%..
-goto :eof
-
-:find_mono
-  set _MONO=%~$PATH:1
-goto :eof
-
-:set_args
-  set _ARGS=
-  :loop
-  rem Argument %1 may contain quotes so we use parentheses here
-  if (%1)==() goto :eof
-  set _ARGS=%_ARGS% %1
-  shift
-  goto loop
-
-rem ##########################################################################
-rem # errors
-
-:error1
-echo ERROR: environment variable SCALA_HOME is undefined. It should point to your installation directory.
-goto end
-
-:end
-if "%OS%"=="Windows_NT" @endlocal
diff --git a/src/mono/bin/scalac-net b/src/mono/bin/scalac-net
deleted file mode 100644
index e3442b3..0000000
--- a/src/mono/bin/scalac-net
+++ /dev/null
@@ -1,86 +0,0 @@
-#!/bin/sh
-
-##############################################################################
-# @NAME@ @VERSION@
-##############################################################################
-# @COPYRIGHT@
-#
-# This is free software; see the distribution for copying conditions.
-# There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A
-# PARTICULAR PURPOSE.
-##############################################################################
-
-cygwin=false;
-darwin=false;
-case "`uname`" in
-    CYGWIN*) cygwin=true ;;
-    Darwin*) darwin=true ;;
-esac
-
-# Finding the root folder for this Scala distribution
-SOURCE=$0;
-SCRIPT=`basename "$SOURCE"`;
-while [ -h "$SOURCE" ]; do
-    SCRIPT=`basename "$SOURCE"`;
-    LOOKUP=`ls -ld "$SOURCE"`;
-    TARGET=`expr "$LOOKUP" : '.*-> \(.*\)$'`;
-    if expr "${TARGET:-.}/" : '/.*/$' > /dev/null; then
-        SOURCE=${TARGET:-.};
-    else
-        SOURCE=`dirname "$SOURCE"`/${TARGET:-.};
-    fi;
-done;
-SCALA_HOME=`dirname "$SOURCE"`/..;
-SCALA_HOME=`cd "$SCALA_HOME"; pwd`;
-if $cygwin; then
-    SCALA_HOME=`cygpath --windows --short-name "$SCALA_HOME"`
-    SCALA_HOME=`cygpath --unix "$SCALA_HOME"`
-fi
-
-# Constructing the extension classpath
-EXTENSION_CLASSPATH=""
-if [ -z "$EXTENSION_CLASSPATH" ] ; then
-    for ext in `ls -d "$SCALA_HOME"/lib/*` ; do
-        if [ -z "$EXTENSION_CLASSPATH" ] ; then
-            EXTENSION_CLASSPATH="$ext"
-        else
-            EXTENSION_CLASSPATH="$EXTENSION_CLASSPATH:$ext"
-        fi
-    done
-fi
-
-# Setting the boot class-path to be the standard library (either as a JAR or a folder)
-BOOT_CLASSPATH=""
-if [ -z "$BOOT_CLASSPATH" ] ; then
-    if [ -f "$SCALA_HOME/lib/scala-library.jar" ] ; then
-        BOOT_CLASSPATH="$SCALA_HOME/lib/scala-library.jar"
-    elif [ -d "$SCALA_HOME/lib/library" ] ; then
-        BOOT_CLASSPATH="$SCALA_HOME/lib/library"
-    fi
-fi
-
-if [ ! -x "$ILASM" ] ; then
-    if [ -d "$MONO_HOME" ] ; then
-        ILASM="$MONO_HOME/bin/ilasm"
-    else
-        ILASM="ilasm"
-    fi
-fi
-
-MSIL_LIBPATH="$SCALA_HOME/lib/predef.dll:$SCALA_HOME/lib/scalaruntime.dll:$SCALA_HOME/lib/mscorlib.dll"
-[ -z "$MONO_PATH" ] || MSIL_LIBPATH="$MSIL_LIBPATH:$MONO_PATH"
-
-if $cygwin; then
-    if [ "$OS" = "Windows_NT" ] && cygpath -m .>/dev/null 2>/dev/null ; then
-        format=mixed
-    else
-        format=windows
-    fi
-    SCALA_HOME=`cygpath --$format "$SCALA_HOME"`
-    EXTENSION_CLASSPATH=`cygpath --path --$format "$EXTENSION_CLASSPATH"`
-    BOOT_CLASSPATH=`cygpath --path --$format "$BOOT_CLASSPATH"`
-    MSIL_LIBPATH=`cygpath --path --$format "$MSIL_LIBPATH"`
-    ILASM=`cygpath --$format "$COMSPEC"`" /C "`cygpath --windows "$ILASM"`
-fi
-
-${JAVACMD:=java} ${JAVA_OPTS:=-Xmx256M -Xms16M} -Xbootclasspath/a:"$BOOT_CLASSPATH" -cp "$EXTENSION_CLASSPATH" -Dscala.home="$SCALA_HOME" -Denv.classpath="$CLASSPATH" -Dmsil.libpath="$MSIL_LIBPATH" -Dmsil.ilasm="$ILASM" scala.tools.nsc.Main -target:msil "$@"
diff --git a/src/mono/bin/scalac-net.bat b/src/mono/bin/scalac-net.bat
deleted file mode 100644
index 27f080e..0000000
--- a/src/mono/bin/scalac-net.bat
+++ /dev/null
@@ -1,116 +0,0 @@
- at echo off
-
-rem ##########################################################################
-rem # @NAME@ @VERSION@
-rem ##########################################################################
-rem # @COPYRIGHT@
-rem #
-rem # This is free software; see the distribution for copying conditions.
-rem # There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A
-rem # PARTICULAR PURPOSE.
-rem ##########################################################################
-
-rem We adopt the following conventions:
-rem - System/user environment variables start with a letter
-rem - Local batch variables start with an underscore ('_')
-
-if "%OS%"=="Windows_NT" (
-  @setlocal
-  call :set_home
-  set _ARGS=%*
-) else (
-  set _SCALA_HOME=%SCALA_HOME%
-  rem The following line tests SCALA_HOME instead of _SCALA_HOME, because
-  rem the above change to _SCALA_HOME is not visible within this block.
-  if "%SCALA_HOME%"=="" goto error1
-  call :set_args
-)
-
-rem We use the value of the JAVACMD environment variable if defined
-set _JAVACMD=%JAVACMD%
-if "%_JAVACMD%"=="" set _JAVACMD=java
-
-rem We use the value of the JAVA_OPTS environment variable if defined
-set _JAVA_OPTS=%JAVA_OPTS%
-if "%_JAVA_OPTS%"=="" set _JAVA_OPTS=-Xmx256M -Xms16M
-
-set _EXTENSION_CLASSPATH=
-if "%_EXTENSION_CLASSPATH%"=="" (
-  for %%f in ("%_SCALA_HOME%\lib\*") do call :add_cpath "%%f"
-  if "%OS%"=="Windows_NT" (
-    for /d %%f in ("%_SCALA_HOME%\lib\*") do call :add_cpath "%%f"
-  )
-)
-
-set _BOOT_CLASSPATH=
-if "%_BOOT_CLASSPATH%"=="" (
-  if exist "%_SCALA_HOME%\lib\scala-library.jar" (
-    set _BOOT_CLASSPATH=%_SCALA_HOME%\lib\scala-library.jar
-  )
-  if exist "%_SCALA_HOME%\lib\library" (
-    set _BOOT_CLASSPATH=%_SCALA_HOME%\lib\library
-  )
-)
-
-rem We use the value of the ILASM environment variable if defined
-set _ILASM=%ILASM%
-if "%_ILASM%"=="" (
-  if exist "%MONO_HOME%" (
-    set _ILASM=%MONO_HOME%\bin\ilasm.bat
-  ) else (
-    call :find_ilasm ilasm.exe
-  )
-)
-
-set _MSIL_LIBPATH=%_SCALA_HOME%\lib\predef.dll;%_SCALA_HOME%\lib\scalaruntime.dll;%_SCALA_HOME%\lib\mscorlib.dll
-if not "%MONO_PATH%"=="" (
-  set _MSIL_LIBPATH=%_MSIL_LIBPATH%;%MONO_PATH%
-)
-
-set _PROPS=-Dscala.home="%_SCALA_HOME%" -Denv.classpath="%CLASSPATH%" -Dmsil.libpath="%_MSIL_LIBPATH%" -Dmsil.ilasm="%_ILASM%" 
-
-%_JAVACMD% -Xbootclasspath/a:"%_BOOT_CLASSPATH%" %_JAVA_OPTS% %_PROPS% -cp "%_EXTENSION_CLASSPATH%" scala.tools.nsc.Main -target:msil %_ARGS%
-goto end
-
-rem ##########################################################################
-rem # subroutines
-
-:add_cpath
-  if "%_EXTENSION_CLASSPATH%"=="" (
-    set _EXTENSION_CLASSPATH=%~1
-  ) else (
-    set _EXTENSION_CLASSPATH=%_EXTENSION_CLASSPATH%;%~1
-  )
-goto :eof
-
-rem Variable "%~dps0" works on WinXP SP2 or newer
-rem (see http://support.microsoft.com/?kbid=833431)
-rem set _SCALA_HOME=%~dps0..
-:set_home
-  set _BIN_DIR=
-  for %%i in (%~sf0) do set _BIN_DIR=%_BIN_DIR%%%~dpsi
-  set _SCALA_HOME=%_BIN_DIR%..
-goto :eof
-
-:find_ilasm
-  set _ILASM=%~$PATH:1
-goto :eof
-
-:set_args
-  set _ARGS=
-  :loop
-  rem Argument %1 may contain quotes so we use parentheses here
-  if (%1)==() goto :eof
-  set _ARGS=%_ARGS% %1
-  shift
-  goto loop
-
-rem ##########################################################################
-rem # errors
-
-:error1
-echo ERROR: environment variable SCALA_HOME is undefined. It should point to your installation directory.
-goto end
-
-:end
-if "%OS%"=="Windows_NT" @endlocal
diff --git a/src/msil/ch/epfl/lamp/compiler/msil/Assembly.java b/src/msil/ch/epfl/lamp/compiler/msil/Assembly.java
new file mode 100644
index 0000000..0d7102c
--- /dev/null
+++ b/src/msil/ch/epfl/lamp/compiler/msil/Assembly.java
@@ -0,0 +1,253 @@
+/*
+ * System.Reflection-like API for access to .NET assemblies (DLL & EXE)
+ */
+
+
+package ch.epfl.lamp.compiler.msil;
+
+import ch.epfl.lamp.compiler.msil.util.Table;
+import ch.epfl.lamp.compiler.msil.util.Table.AssemblyDef;
+import ch.epfl.lamp.compiler.msil.util.Table.ModuleDef;
+
+import java.util.HashMap;
+import java.util.Iterator;
+import java.io.File;
+import java.io.FileNotFoundException;
+
+/**
+ * Defines an Assembly, which is a reusable, versionable, and self-describing
+ * building block of a common language runtime application.
+ *
+ * @author Nikolay Mihaylov
+ * @version 1.0
+ */
+public abstract class Assembly extends CustomAttributeProvider {
+
+    //##########################################################################
+    // static members
+
+    // all the assemblies
+    public static final HashMap assemblies = new HashMap();
+
+    /** Loads an assembly from the specified path. */
+    public static Assembly LoadFrom(String assemblyFileName) {
+	File afile = new File(assemblyFileName);
+	return LoadFrom(afile.getParentFile(), afile.getName());
+    }
+
+    /** Loads an assembly with the given name from the given directory. */
+    public static Assembly LoadFrom(File dir, String name) {
+	File file = null;
+	PEFile pefile = null;
+// 	try {
+// 	    if (dir == null)
+// 		dir = new File(".");
+// 	    dir = dir.getCanonicalFile();
+// 	} catch (java.io.IOException e) {}
+
+	if (name.endsWith(".exe") || name.endsWith(".EXE") ||
+	    name.endsWith(".dll") || name.endsWith(".DLL"))
+	    {
+		file = new File(dir, name);
+		pefile = getPEFile(file);
+		name = name.substring(0, name.length() - 4);
+	    }
+
+	File adir = pefile == null ? new File(dir, name) : null;
+
+	if (pefile == null) {
+	    file = new File(dir, name + ".dll");
+	    pefile = getPEFile(file);
+	}
+	if (pefile == null) {
+	    file = new File(dir, name + ".DLL");
+	    pefile = getPEFile(file);
+	}
+	if (pefile == null && adir.exists()) {
+	    file = new File(adir, name + ".dll");
+	    pefile = getPEFile(file);
+	}
+	if (pefile == null && adir.exists()) {
+	    file = new File(adir, name + ".DLL");
+	    pefile = getPEFile(file);
+	}
+
+	if (pefile == null) {
+	    file = new File(dir, name + ".exe");
+	    pefile = getPEFile(file);
+	}
+	if (pefile == null) {
+	    file = new File(dir, name + ".EXE");
+	    pefile = getPEFile(file);
+	}
+	if (pefile == null && adir.exists()) {
+	    file = new File(adir, name + ".exe");
+	    pefile = getPEFile(file);
+	}
+	if (pefile == null && adir.exists()) {
+	    file = new File(adir, name + ".EXE");
+	    pefile = getPEFile(file);
+	}
+
+	if (pefile == null)
+	    throw new RuntimeException("Cannot find assembly " + new File(dir, name));
+	return getPEAssembly(pefile);
+    }
+
+    private static Assembly getPEAssembly(PEFile pefile) {
+	AssemblyDef assem = pefile.AssemblyDef;
+	if (assem == null)
+	    throw new RuntimeException("File " + pefile
+				       + " does not contain a manifest");
+	assem.readRow(1);
+	String name = pefile.getString(assem.Name);
+	Assembly a = (Assembly) assemblies.get(name);
+	if (a != null) {
+	    return a;
+	}
+
+	AssemblyName an = new AssemblyName();
+	an.Name = pefile.getString(assem.Name);
+	an.Version = new Version(assem.MajorVersion, assem.MinorVersion,
+				 assem.BuildNumber, assem.RevisionNumber);
+	an.SetPublicKey(pefile.getBlob(assem.PublicKey));
+	return new PEAssembly(pefile, an);
+    }
+
+    protected static PEFile getPEFile(File f) {
+	PEFile pefile = null;
+	try { pefile = new PEFile(f.getAbsolutePath()); }
+	catch (FileNotFoundException e) {}
+	catch (RuntimeException e) {}
+	return pefile;
+    }
+
+    //##########################################################################
+    // public fields
+
+    /** The entry point of this assembly. */
+    public MethodInfo EntryPoint;
+
+    /** the display name of the assembly. */
+    public final String FullName;
+
+    //##########################################################################
+    // constructor
+
+    protected Assembly(AssemblyName an, boolean external) {
+	assemblyName = an;
+	FullName = an.toString();
+    if(external) {
+	  assemblies.put(an.Name, this);
+    }
+	//System.out.println("assemblies after adding the current one: " + assemblies);
+    }
+
+    protected Assembly(AssemblyName an) {
+      this(an, false);
+    }
+
+    protected static Assembly getAssembly(String name) {
+	return (Assembly) assemblies.get(name);
+    }
+
+    //##########################################################################
+    // instrumental methods
+
+    /** @return the file from which this assembly was loaded. */
+    public File getFile() {
+	throw new RuntimeException("Not supported");
+    }
+
+    /** Gets the specified module in this assembly. Works on filenames. */
+    public Module GetModule(String name) {
+	initModules();
+	return (Module)modulesMap.get(name);
+    }
+
+    /** Get all the modules of the assembly. */
+    public Module[] GetModules() {
+	initModules();
+	return (Module[])modulesMap.values().
+	    toArray(new Module[modulesMap.size()]);
+    }
+
+    /** Get the corresponding type. */
+    public Type GetType(String name) {
+	initModules();
+	Iterator modules = modulesMap.values().iterator();
+	Type t = null;
+	while (t == null && modules.hasNext()) {
+	    t = ((Module)modules.next()).GetType(name);
+	}
+	return t;
+    }
+
+    /** @return an array of all types defined in the assembly. */
+    public synchronized Type[] GetTypes() {
+ 	if (types != null)
+	    return (Type[])types.clone();
+	initModules();
+
+	Iterator modules = modulesMap.values().iterator();
+	Type[] newTypes = ((Module)modules.next()).GetTypes();
+	while (modules.hasNext()) {
+	    Module module = (Module)modules.next();
+	    Type[] mtypes = module.GetTypes();
+	    Type[] oldTypes = newTypes;
+	    newTypes = new Type[oldTypes.length + mtypes.length];
+	    System.arraycopy(oldTypes, 0, newTypes, 0, oldTypes.length);
+	    System.arraycopy(mtypes, 0, newTypes, oldTypes.length, mtypes.length);
+	}
+	types = newTypes;
+	return (Type[]) types.clone();
+    }
+
+    public AssemblyName GetName() {
+	return assemblyName;
+    }
+
+    public String toString() {
+	return FullName;
+    }
+
+    //##########################################################################
+    // protected members
+
+    // the assembly name
+    protected final AssemblyName assemblyName;
+
+    // all the types exported by the assembly
+    protected Type[] types = null;
+
+    // the module defined in this assembly (only one right now)
+    private final HashMap/*<String, Module>*/ modulesMap = new HashMap();
+
+    protected void addType(Type type) {
+	Type.addType(type);
+    }
+
+    protected void addModule(String name, Module module) {
+	modulesMap.put(name, module);
+    }
+
+    private boolean initModules = true;
+    protected final void initModules() {
+	if (initModules) {
+	    loadModules();
+	    initModules = false;
+	}
+    }
+
+    /** used for lazy construction of the Assembly. */
+    protected abstract void loadModules();
+
+    void dumpTypes() {
+	Type[] types = GetTypes();
+	for (int i = 0; i < types.length; i++)
+	    System.out.println(types[i]);
+    }
+
+    //##########################################################################
+
+}  // class Assembly
diff --git a/src/msil/ch/epfl/lamp/compiler/msil/AssemblyName.java b/src/msil/ch/epfl/lamp/compiler/msil/AssemblyName.java
new file mode 100644
index 0000000..acdcb32
--- /dev/null
+++ b/src/msil/ch/epfl/lamp/compiler/msil/AssemblyName.java
@@ -0,0 +1,96 @@
+/*
+ * System.Reflection-like API for access to .NET assemblies (DLL & EXE)
+ */
+
+
+package ch.epfl.lamp.compiler.msil;
+
+import javax.crypto.Mac;
+
+import java.security.MessageDigest;
+
+import ch.epfl.lamp.compiler.msil.util.Table;
+
+/**
+ * Fully describes an assembly's unique identity.
+ * Right now it's only the name
+ *
+ * @author Nikolay Mihaylov
+ * @version 1.0
+ */
+public class AssemblyName {
+
+    //##########################################################################
+    // public interface
+
+    /** The simple, unencrypted name of the assembly. */
+    public String Name;
+
+    /**
+     * Gets or sets the major, minor, revision, and build numbers
+     * of the assembly.
+     */
+    public Version Version;
+
+    /**
+     * Gets a strong name consisting of a public key, a given name,
+     * and version parts.
+     */
+    public byte[] GetPublicKeyToken() {
+	return publicKeyToken == null ? null : (byte[]) publicKeyToken.clone();
+    }
+
+    /**
+     * Sets a strong name consisting of a public key, a given name,
+     * and version parts.
+     */
+    public void SetPublicKeyToken(byte[] key) {
+	this.publicKeyToken = key.length == 0 ? null : (byte[]) key.clone();
+    }
+
+    /**
+     * Returns the public key identifying the originator of the assembly.
+     */
+    public byte[] GetPublicKey() {
+	return publicKey == null ? null : (byte[]) publicKey.clone();
+    }
+
+    /**
+     * Sets the public key identifying the originator of the assembly.
+     */
+    public void SetPublicKey(byte[] key) {
+	if (key.length > 0) {
+	    this.publicKey = (byte[]) key.clone();
+	    byte[] hash = sha.digest(key);
+	    byte[] keyToken = new byte[8];
+	    for (int i = 0; i < keyToken.length; i++)
+		keyToken[i] = hash[hash.length - 1 - i];
+	    this.publicKeyToken = keyToken;
+	    //System.out.println("Pubic key and key token of assembly " + this + ":");
+	    //System.out.println("\tPublic key = " + Table.bytes2hex(key));
+	    //System.out.println("\tKey token  = " + Table.bytes2hex(keyToken));
+	}
+    }
+
+    public String toString() {
+	return Name + ", Version=" + Version;
+    }
+
+    //##########################################################################
+
+    private byte[] publicKeyToken;
+
+    private byte[] publicKey;
+
+    private static final MessageDigest sha;
+    static {
+	MessageDigest md = null;
+	try {
+	    md = MessageDigest.getInstance("SHA");
+	} catch (java.security.NoSuchAlgorithmException e) {}
+	sha = md;
+    }
+
+    //##########################################################################
+
+} // class AssemblyName
diff --git a/src/msil/ch/epfl/lamp/compiler/msil/Attribute.java b/src/msil/ch/epfl/lamp/compiler/msil/Attribute.java
new file mode 100644
index 0000000..aefb6fd
--- /dev/null
+++ b/src/msil/ch/epfl/lamp/compiler/msil/Attribute.java
@@ -0,0 +1,557 @@
+/*
+ * System.Reflection-like API for access to .NET assemblies (DLL & EXE)
+ */
+
+
+package ch.epfl.lamp.compiler.msil;
+
+import ch.epfl.lamp.compiler.msil.util.Signature;
+
+import java.util.Map;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.Iterator;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.io.UnsupportedEncodingException;
+
+/**
+ * Describes custom attribute instances.
+ *
+ * @author Nikolay Mihaylov
+ * @version 1.0
+ */
+public class Attribute {
+
+    //##########################################################################
+
+    private final ConstructorInfo constr;
+
+    private final byte[] value;
+
+    Attribute(ConstructorInfo constr, byte[] value) {
+        assert constr != null;
+	this.constr = constr;
+        assert value != null : constr.toString();
+	this.value = value;
+    }
+
+    //##########################################################################
+    // public interface
+
+    /** @return the type (class) of the attribute. */
+    public Type GetType() { return constr.DeclaringType; }
+
+    /** @return the constructor of this attribute. */
+    public ConstructorInfo getConstructor() {
+	return constr;
+    }
+
+    /** @return the Blob with serialized constructor & named arguments. */
+    public byte[] getValue() {
+	byte[] value = new byte[this.value.length];
+	System.arraycopy(this.value, 0, value, 0, value.length);
+	return value;
+    }
+
+    /**@return an array with the arguments to the attribute's constructor. */
+    public Object[] getConstructorArguments() {
+        parseBlob();
+        Object[] cas = new Object[constrArgs.length];
+        System.arraycopy(constrArgs, 0, cas, 0, cas.length);
+        return cas;
+    }
+
+    /** @return the named argument with the given name. */
+    public NamedArgument getNamedArgument(String name) {
+        return (NamedArgument)namedArgs.get(name);
+    }
+
+    /** @return an array of all named arguments for this attribute. */
+    public NamedArgument[] getNamedArguments() {
+        NamedArgument[] nargs =
+            (NamedArgument[])namedArgs.values().toArray(NamedArgument.EMPTY);
+        return nargs;
+    }
+
+    /** @return a string representation of this attribute. */
+    public String toString() {
+        parseBlob();
+	ParameterInfo[] params = constr.GetParameters();
+	assert params.length == constrArgs.length : this.constr;
+        StringBuffer str = new StringBuffer();
+	str.append('[');
+	str.append(constr.DeclaringType.FullName);
+        str.append('(');
+        for (int i = 0; i < constrArgs.length; i++) {
+            if (i > 0)
+                str.append(", ");
+	    Type t = params[i].ParameterType;
+	    if (t.IsEnum()) {
+		str.append('(');
+		str.append(t.FullName);
+		str.append(')');
+	    }
+            formatValue(str, constrArgs[i]);
+        }
+        NamedArgument[] nargs = getNamedArguments();
+        for (int i = 0; i < nargs.length; i++) {
+            str.append(", ").append(nargs[i]);
+            }
+        str.append(")]");
+	return str.toString();
+    }
+
+    //#########################################################################
+
+    private static final Map type2id = new HashMap();
+    private static final Map id2type = new HashMap();
+    static {
+        map("Boolean", Signature.ELEMENT_TYPE_BOOLEAN);
+        map("Char", Signature.ELEMENT_TYPE_CHAR);
+        map("SByte", Signature.ELEMENT_TYPE_I1);
+        map("Byte", Signature.ELEMENT_TYPE_U1);
+        map("Int16", Signature.ELEMENT_TYPE_I2);
+        map("UInt16", Signature.ELEMENT_TYPE_U2);
+        map("Int32", Signature.ELEMENT_TYPE_I4);
+        map("UInt32", Signature.ELEMENT_TYPE_U4);
+        map("Int64", Signature.ELEMENT_TYPE_I8);
+        map("UInt64", Signature.ELEMENT_TYPE_U8);
+        map("Single", Signature.ELEMENT_TYPE_R4);
+        map("Double", Signature.ELEMENT_TYPE_R8);
+        map("String", Signature.ELEMENT_TYPE_STRING);
+        map("Type", Signature.X_ELEMENT_TYPE_TYPE);
+        map("Object", Signature.ELEMENT_TYPE_OBJECT);
+    }
+    private static void map(String type, int id) {
+        Type t = Type.GetType("System." + type);
+        assert type != null : type + " -> " + id;
+        Integer i = new Integer(id);
+        type2id.put(t, i);
+        id2type.put(i, t);
+    }
+    private static int getTypeId(Type type) {
+        Integer id = (Integer)type2id.get(type);
+        assert id != null : type;
+        return id.intValue();
+    }
+
+    private Object[] constrArgs;
+    private Map namedArgs;
+    private ByteBuffer buf;
+
+    private void parseBlob() {
+        try { parseBlob0(); }
+        catch (RuntimeException e) {
+            throw new RuntimeException(PEFile.bytes2hex(value), e);
+        }
+    }
+
+    private void parseBlob0() {
+        if (buf != null)
+            return;
+        buf = ByteBuffer.wrap(value);
+        buf.order(ByteOrder.LITTLE_ENDIAN);
+
+        short sig = buf.getShort();
+        assert sig == 1 : PEFile.bytes2hex(value);
+        ParameterInfo[] params = constr.GetParameters();
+        constrArgs = new Object[params.length];
+        for (int i = 0; i < params.length; i++) {
+            constrArgs[i] = parseElement(params[i].ParameterType);
+        }
+
+        int ncount = buf.getShort();
+        namedArgs = new LinkedHashMap();
+        for (int i = 0; i < ncount; i++) {
+            int designator = buf.get();
+            assert designator == Signature.X_ELEMENT_KIND_FIELD
+                || designator == Signature.X_ELEMENT_KIND_PROPERTY
+                : "0x" + PEFile.byte2hex(designator);
+            Type type = parseType();
+            String name = parseString();
+            Object value = parseElement(type);
+            NamedArgument narg =
+                new NamedArgument(designator, name, type, value);
+            namedArgs.put(name, narg);
+        }
+    }
+
+    private Object parseElement(Type type) {
+        if (type.IsArray())
+	    return parseArray(type.GetElementType());
+	if (type.IsEnum())
+	    return parseElement(type.getUnderlyingType());
+	return parseElement(getTypeId(type));
+    }
+
+    private Object parseElement(int id) {
+        switch (id) {
+        case Signature.ELEMENT_TYPE_BOOLEAN:
+            return new Boolean(buf.get() == 0 ? false : true);
+        case Signature.ELEMENT_TYPE_CHAR:
+            return new Character(buf.getChar());
+        case Signature.ELEMENT_TYPE_I1:
+        case Signature.ELEMENT_TYPE_U1:
+            return new Byte(buf.get());
+        case Signature.ELEMENT_TYPE_I2:
+        case Signature.ELEMENT_TYPE_U2:
+            return new Short(buf.getShort());
+        case Signature.ELEMENT_TYPE_I4:
+        case Signature.ELEMENT_TYPE_U4:
+            return new Integer(buf.getInt());
+        case Signature.ELEMENT_TYPE_I8:
+        case Signature.ELEMENT_TYPE_U8:
+            return new Long(buf.getLong());
+        case Signature.ELEMENT_TYPE_R4:
+            return new Float(buf.getFloat());
+        case Signature.ELEMENT_TYPE_R8:
+            return new Double(buf.getDouble());
+        case Signature.ELEMENT_TYPE_STRING:
+            return parseString();
+        case Signature.X_ELEMENT_TYPE_TYPE:
+                return getType();
+        case Signature.ELEMENT_TYPE_OBJECT:
+            Type type = parseType();
+            return new BoxedArgument(type, parseElement(type));
+        default:
+            throw new RuntimeException("Unknown type id: " + id);
+        }
+    }
+
+    private Object parseArray(Type type) {
+	if (type.IsEnum())
+	    return parseArray(type.getUnderlyingType());
+	return parseArray(getTypeId(type));
+    }
+
+    private Object parseArray(int id) {
+        switch (id) {
+        case Signature.ELEMENT_TYPE_BOOLEAN:
+            return parseBooleanArray();
+        case Signature.ELEMENT_TYPE_CHAR:
+            return parseCharArray();
+        case Signature.ELEMENT_TYPE_I1:
+        case Signature.ELEMENT_TYPE_U1:
+            return parseByteArray();
+        case Signature.ELEMENT_TYPE_I2:
+        case Signature.ELEMENT_TYPE_U2:
+            return parseShortArray();
+        case Signature.ELEMENT_TYPE_I4:
+        case Signature.ELEMENT_TYPE_U4:
+            return parseIntArray();
+        case Signature.ELEMENT_TYPE_I8:
+        case Signature.ELEMENT_TYPE_U8:
+            return parseLongArray();
+        case Signature.ELEMENT_TYPE_R4:
+            return parseFloatArray();
+        case Signature.ELEMENT_TYPE_R8:
+            return parseDoubleArray();
+        case Signature.ELEMENT_TYPE_STRING:
+            return parseStringArray();
+        case Signature.X_ELEMENT_TYPE_ENUM:
+	    return parseArray(getType());
+        default:
+            throw new RuntimeException("Unknown type id: " + id);
+        }
+    }
+
+    private Type parseType() {
+        int id = buf.get();
+        switch (id) {
+        case Signature.ELEMENT_TYPE_SZARRAY:
+            return Type.mkArray(parseType(), 1);
+        case Signature.X_ELEMENT_TYPE_ENUM:
+            return getType();
+        default:
+            Type t = (Type)id2type.get(new Integer(id));
+            assert t != null : PEFile.byte2hex(id);
+            return t;
+        }
+    }
+
+    private Type getType() {
+        String typename = parseString();
+        int i = typename.indexOf(',');
+        // fully qualified assembly name follows
+        // just strip it on the assumtion theat the
+        // assembly is referenced in the externs and the
+        // type will be found
+        String name = (i < 0) ? typename : typename.substring(0, i);
+        Type t = Type.GetType(name);
+        if (t == null && i > 0) {
+            int j = typename.indexOf(',', i + 1);
+            if (j > 0) {
+                String assemName = typename.substring(i + 1, j);
+                try {
+                    Assembly.LoadFrom(assemName);
+                } catch (Throwable e) {
+                    throw new RuntimeException(typename, e);
+                }
+                t = Type.GetType(name);
+            }
+        }
+        assert t != null : typename;
+        return t;
+    }
+
+    private boolean[] parseBooleanArray() {
+        boolean[] arr = new boolean[buf.getInt()];
+        for (int i = 0; i < arr.length; i++)
+            arr[i] = buf.get() == 0 ? false : true;
+        return arr;
+    }
+
+    private char[] parseCharArray() {
+        char[] arr = new char[buf.getInt()];
+        for (int i = 0; i < arr.length; i++)
+            arr[i] = buf.getChar();
+        return arr;
+    }
+
+    private byte[] parseByteArray() {
+        byte[] arr = new byte[buf.getInt()];
+        for (int i = 0; i < arr.length; i++)
+            arr[i] = buf.get();
+        return arr;
+    }
+
+    private short[] parseShortArray() {
+        short[] arr = new short[buf.getInt()];
+        for (int i = 0; i < arr.length; i++)
+            arr[i] = buf.getShort();
+        return arr;
+    }
+
+    private int[] parseIntArray() {
+        int[] arr = new int[buf.getInt()];
+        for (int i = 0; i < arr.length; i++)
+            arr[i] = buf.getInt();
+        return arr;
+    }
+
+    private long[] parseLongArray() {
+        long[] arr = new long[buf.getInt()];
+        for (int i = 0; i < arr.length; i++)
+            arr[i] = buf.getLong();
+        return arr;
+    }
+
+    private float[] parseFloatArray() {
+        float[] arr = new float[buf.getInt()];
+        for (int i = 0; i < arr.length; i++)
+            arr[i] = buf.getFloat();
+        return arr;
+    }
+
+    private double[] parseDoubleArray() {
+        double[] arr = new double[buf.getInt()];
+        for (int i = 0; i < arr.length; i++)
+            arr[i] = buf.getDouble();
+        return arr;
+    }
+
+    private String[] parseStringArray() {
+        String[] arr = new String[buf.getInt()];
+        for (int i = 0; i < arr.length; i++)
+            arr[i] = parseString();
+        return arr;
+    }
+
+    private String parseString() {
+        String str = null;
+        int length = parseLength();
+        if (length < 0)
+            return null;
+        try { str = new String(value, buf.position(), length, "UTF-8" ); }
+        catch (UnsupportedEncodingException e) { throw new Error(e); }
+        buf.position(buf.position() + length);
+        return str;
+    }
+
+    private int getByte() {
+        return (buf.get() + 0x0100) & 0xff;
+    }
+
+    public int parseLength() {
+	int length = getByte();
+        // check for invalid length format: the first, second or third
+        // most significant bits should be 0; if all are 1 the length is invalid.
+        if ((length & 0xe0) == 0xe0)
+            return -1;
+	if ((length & 0x80) != 0) {
+	    length = ((length & 0x7f) << 8) | getByte();
+	    if ((length & 0x4000) != 0)
+		length = ((length & 0x3fff) << 16) | (getByte()<<8) | getByte();
+	}
+	return length;
+    }
+
+    //##########################################################################
+    private static void formatValue(StringBuffer str, Object o) {
+        Class c = (o == null) ? null : o.getClass();
+        if (c == null) {
+            str.append("<null>");
+        } else if (c == String.class) {
+            str.append('"');
+            str.append(o);
+            str.append('"');
+        } else if (c == Character.class) {
+            str.append('\'');
+            str.append(o);
+            str.append('\'');
+        } else if (c == boolean[].class) {
+            str.append("new boolean[] {");
+            boolean[] arr = (boolean[])o;
+            for (int i = 0; i < arr.length; i++) {
+                if (i > 0) str.append(", ");
+                str.append(arr[i]);
+            }
+            str.append('}');
+        } else if (c == char[].class) {
+            str.append("new short[] {");
+            short[] arr = (short[])o;
+            for (int i = 0; i < arr.length; i++) {
+                if (i > 0) str.append(", ");
+                str.append(arr[i]);
+            }
+            str.append('}');
+        } else if (c == byte[].class) {
+            str.append("new byte[] {");
+            byte[] arr = (byte[])o;
+            for (int i = 0; i < arr.length; i++) {
+                if (i > 0) str.append(", ");
+                str.append(arr[i]);
+            }
+            str.append('}');
+        } else if (c == short[].class) {
+            str.append("new short[] {");
+            short[] arr = (short[])o;
+            for (int i = 0; i < arr.length; i++) {
+                if (i > 0) str.append(", ");
+                str.append(arr[i]);
+            }
+            str.append('}');
+        } else if (c == int[].class) {
+            str.append("new int[] {");
+            int[] arr = (int[])o;
+            for (int i = 0; i < arr.length; i++) {
+                if (i > 0) str.append(", ");
+                str.append(arr[i]);
+            }
+            str.append('}');
+        } else if (c == long[].class) {
+            str.append("new long[] {");
+            long[] arr = (long[])o;
+            for (int i = 0; i < arr.length; i++) {
+                if (i > 0) str.append(", ");
+                str.append(arr[i]);
+            }
+            str.append('}');
+        } else if (c == float[].class) {
+            str.append("new float[] {");
+            float[] arr = (float[])o;
+            for (int i = 0; i < arr.length; i++) {
+                if (i > 0) str.append(", ");
+                str.append(arr[i]);
+            }
+            str.append('}');
+        } else if (c == double[].class) {
+            str.append("new double[] {");
+            double[] arr = (double[])o;
+            for (int i = 0; i < arr.length; i++) {
+                if (i > 0) str.append(", ");
+                str.append(arr[i]);
+            }
+            str.append('}');
+        } else if (c == String[].class) {
+            str.append("new String[] {");
+            String[] arr = (String[])o;
+            for (int i = 0; i < arr.length; i++) {
+                if (i > 0) str.append(", ");
+                formatValue(str, arr[i]);
+            }
+            str.append('}');
+	} else if (o instanceof Type) {
+	    str.append("typeof(");
+	    str.append(o);
+	    str.append(")");
+        } else
+            str.append(o);
+    }
+
+    //##########################################################################
+
+    /** Represents named arguments (assigned outside of the constructor)
+     *  of a custom attribute
+     */
+    public static class NamedArgument {
+
+        /** Designates if the named argument corresponds to a field or property.
+         *  Possible values:
+         *      Signature.X_ELEMENT_KIND_FIELD = 0x53
+         *      Signature.X_ELEMENT_KIND_PROPERTY = 0x54
+         */
+        public final int designator;
+
+        /** The name of the field/property. */
+        public final String name;
+
+        /** Type of the field/property. */
+        public final Type type;
+
+        /** The value for the field/property. */
+        public final Object value;
+
+        /** An empty array NamedArgument. */
+        public static final NamedArgument[] EMPTY = new NamedArgument[0];
+
+        public NamedArgument(int designator, String name,Type type,Object value)
+        {
+            this.designator = designator;
+            this.name = name;
+            this.type = type;
+            this.value = value;
+        }
+
+        /** @return <b>true</b> if the named argument specifies a field;
+         *  <b>false<b> otherwise.
+         */
+        public boolean isField() {
+            return designator == Signature.X_ELEMENT_KIND_FIELD;
+        }
+
+        /** @return <b>true</b> if the named argument specifies a property;
+         *  <b>false<b> otherwise.
+         */
+        public boolean isProperty() {
+            return designator == Signature.X_ELEMENT_KIND_PROPERTY;
+        }
+
+        /** @return a string representation of the named argument. */
+        public String toString() {
+            StringBuffer str = new StringBuffer(name);
+            str.append(" = ");
+            if (type.IsEnum())
+                str.append('(').append(type.FullName).append(')');
+            formatValue(str, value);
+            return str.toString();
+        }
+    }
+
+    //##########################################################################
+
+    protected static final class BoxedArgument {
+        public final Type type;
+        public final Object value;
+        public BoxedArgument(Type type, Object value) {
+            this.type = type; this.value = value;
+        }
+        public String toString() {
+            return "(" + type.FullName + ")" + value;
+        }
+    }
+
+    //##########################################################################
+
+}  // class Attribute
diff --git a/src/msil/ch/epfl/lamp/compiler/msil/BindingFlags.java b/src/msil/ch/epfl/lamp/compiler/msil/BindingFlags.java
new file mode 100644
index 0000000..cac2319
--- /dev/null
+++ b/src/msil/ch/epfl/lamp/compiler/msil/BindingFlags.java
@@ -0,0 +1,169 @@
+/*
+ * System.Reflection-like API for access to .NET assemblies (DLL & EXE)
+ */
+
+
+package ch.epfl.lamp.compiler.msil;
+
+/**
+ * Specifies flags that control binding and the way in which
+ * the search for members and types is conducted by reflection.
+ *
+ * Note: You must specify Instance or Static along with Public or NonPublic
+ * or no members will be returned.
+ *
+ * @author Nikolay Mihaylov
+ * @version 1.0
+ */
+public abstract class BindingFlags {
+
+    //##########################################################################
+
+    // disallows extending the class;
+    private BindingFlags() {}
+
+    /**
+     * Specifies no binding flag.
+     */
+    public static final int Default = 0x0000;
+
+    /**
+     * Specifies that the case of the member name should not be considered
+     * when binding.
+     */
+    public static final int IgnoreCase = 0x0001;
+
+    /**
+     * Specifies that only members declared at the level of the supplied type's
+     * hierarchy should be considered. Inherited members are not considered.
+     */
+    public static final int DeclaredOnly = 0x0002;
+
+    /**
+     * Specifies that instance members are to be included in the search.
+     */
+    public static final int Instance = 0x0004;
+
+    /**
+     * Specifies that static members are to be included in the search.
+     */
+    public static final int Static = 0x0008;
+
+    /**
+     * Specifies that public members are to be included in the search.
+     */
+    public static final int Public = 0x0010;
+
+    /**
+     * Specifies that non-public members are to be included in the search.
+     */
+    public static final int NonPublic = 0x0020;
+
+    /**
+     * Specifies that static members up the hierarchy should be returned.
+     * Static members include fields, methods, events, and properties.
+     * Nested types are not returned.
+     */
+    public static final int FlattenHierarchy = 0x0040;
+
+    /**
+     * Specifies that a method is to be invoked. This may not be a constructor
+     * or a type initializer.
+     */
+    public static final int InvokeMethod = 0x0100;
+
+    /**
+     * Specifies that Reflection should create an instance of
+     * the specified type. Calls the constructor that matches
+     * the given arguments. The supplied member name is ignored.
+     * If the type of lookup is not specified, (Instance | Public)
+     * will apply. It is not possible to call a type initializer.
+     */
+    public static final int CreateInstance = 0x0200;
+
+    /**
+     * Specifies that the value of the specified field should be returned.
+     */
+    public static final int GetField = 0x0400;
+
+    /**
+     * Specifies that the value of the specified field should be set.
+     */
+    public static final int SetField = 0x0800;
+
+    /**
+     * Specifies that the value of the specified property should be returned.
+     */
+    public static final int GetProperty = 0x1000;
+
+    /**
+     * Specifies that the value of the specified property should be set.
+     * For COM properties, specifying this binding flag is equivalent to
+     * specifying PutDispProperty and PutRefDispProperty.
+     */
+    public static final int SetProperty = 0x2000;
+
+    /**
+     * Specifies that the PROPPUT member on a COM object should be invoked.
+     * PROPPUT specifies a property-setting function that uses a value.
+     * Use PutDispProperty if a property has both PROPPUT and PROPPUTREF
+     * and you need to distinguish which one is called.
+     */
+    public static final int PutDispProperty = 0x4000;
+
+
+    /**
+     * Specifies that the PROPPUTREF member on a COM object should be invoked.
+     * PROPPUTREF specifies a property-setting function that uses a reference
+     * instead of a value. Use PutRefDispProperty if a property has both
+     * PROPPUT and PROPPUTREF and you need to distinguish which one is called.
+     */
+    public static final int PutRefDispProperty = 0x8000;
+
+    /**
+     * Specifies that types of the supplied arguments must exactly match
+     * the types of the corresponding formal parameters. Reflection
+     * throws an exception if the caller supplies a non-null Binder object,
+     * since that implies that the caller is supplying BindToXXX
+     * implementations that will pick the appropriate method.
+     * Reflection models the accessibility rules of the common type system.
+     * For example, if the caller is in the same assembly, the caller
+     * does not need special permissions for internal members. Otherwise,
+     * the caller needs ReflectionPermission. This is consistent with
+     * lookup of members that are protected, private, and so on.
+     * The general principle is that ChangeType should perform only
+     * widening coercions, which never lose data. An example of a
+     * widening coercion is coercing a value that is a 32-bit signed integer
+     * to a value that is a 64-bit signed integer. This is distinguished
+     * from a narrowing coercion, which may lose data. An example of
+     * a narrowing coercion is coercing a 64-bit signed integer to
+     * a 32-bit signed integer.
+     * The default binder ignores this flag, while custom binders can
+     * implement the semantics of this flag.
+     */
+    public static final int ExactBinding = 0x10000;
+
+    /**
+     * Used in COM interop to specify that the return value of the member
+     * can be ignored.
+     */
+    public static final int IgnoreReturn = 0x100000 ;
+
+    /**
+     * Returns the set of members whose parameter count matches the number
+     * of supplied arguments. This binding flag is used for methods with
+     * parameters that have default values and methods with variable arguments
+     * (varargs). This flag should only be used with Type.InvokeMember.
+     * Parameters with default values are used only in calls where trailing
+     * arguments are omitted. They must be the last arguments.
+     */
+    public static final int OptionalParamBinding = 0x40000;
+
+    /**
+     * Not implemented.
+     */
+    public static final int SuppressChangeType = 0x20000;
+
+    //##########################################################################
+
+}  // class BindingFlags
diff --git a/src/msil/ch/epfl/lamp/compiler/msil/CallingConventions.java b/src/msil/ch/epfl/lamp/compiler/msil/CallingConventions.java
new file mode 100644
index 0000000..50bf9fb
--- /dev/null
+++ b/src/msil/ch/epfl/lamp/compiler/msil/CallingConventions.java
@@ -0,0 +1,75 @@
+/*
+ * System.Reflection-like API for access to .NET assemblies (DLL & EXE)
+ */
+
+
+package ch.epfl.lamp.compiler.msil;
+
+
+/**
+ * Calling conventions
+ *
+ * @author Nikolay Mihaylov
+ * @version 1.0
+ */
+public abstract class CallingConventions {
+
+    //########################################################################
+
+    /**
+     * Specifies the default calling convention as determined by the
+     * common language runtime.
+     */
+    public static final short Standard = (short) 0x0001;
+
+    /**
+     * Specifies the calling convention for methods with variable arguments.
+     */
+    public static final short VarArgs = (short) 0x0002;
+
+    /**
+     * Specifies that either the Standard or the VarArgs calling
+     * convention may be used.
+     */
+    public static final short Any = Standard | VarArgs;
+
+    /**
+     * Specifies an instance or virtual method (not a static method).
+     * At run-time, the called method is passed a pointer to the target
+     * object as its first argument (the this pointer). The signature
+     * stored in metadata does not include the type of this first argument,
+     * because the method is known and its owner class can be discovered
+     * from metadata.
+     */
+    public static final short HasThis = (short) 0x0020;
+
+    /**
+     * Specifies that the signature is a function-pointer signature,
+     * representing a call to an instance or virtual method (not a static
+     * method). If ExplicitThis is set, HasThis must also be set. The first
+     * argument passed to the called method is still a this pointer, but the
+     * type of the first argument is now unknown. Therefore, a token that
+     * describes the type (or class) of the this pointer is explicitly stored
+     * into its metadata signature.
+     */
+    public static final short ExplicitThis = (short) 0x0040;
+
+    //########################################################################
+
+    private CallingConventions() {}
+
+    public static String toString(int callConv) {
+	StringBuffer s = new StringBuffer();
+
+	if ((callConv & HasThis) != 0) {
+	    s.append("instance");
+	    if ((callConv & ExplicitThis) != 0)
+		s.append(" explicit");
+	}
+
+	return s.toString();
+    }
+
+    //##########################################################################
+
+}  // class CallingConventions
diff --git a/src/msil/ch/epfl/lamp/compiler/msil/ConstructorInfo.java b/src/msil/ch/epfl/lamp/compiler/msil/ConstructorInfo.java
new file mode 100644
index 0000000..99e5c5f
--- /dev/null
+++ b/src/msil/ch/epfl/lamp/compiler/msil/ConstructorInfo.java
@@ -0,0 +1,54 @@
+/*
+ * System.Reflection-like API for access to .NET assemblies (DLL & EXE)
+ */
+
+
+package ch.epfl.lamp.compiler.msil;
+
+/**
+ * Discovers the attributes of a class constructor and provides
+ * access to constructor metadata.
+ * ConstructorInfo is used to discover the attributes of a constructor
+ * as well as to invoke a constructor. Objects are created by invoking
+ * either the GetConstructors or GetConstructor method of a Type object.
+ *
+ * @author Nikolay Mihaylov
+ * @version 1.0
+ */
+public class ConstructorInfo extends MethodBase {
+    //##########################################################################
+
+    public final int MemberType() { return MemberTypes.Constructor; }
+
+    public final boolean IsConstructor() { return true; }
+
+    protected static final String CTOR = ".ctor";
+    protected static final String CCTOR = ".cctor";
+    protected static final ConstructorInfo[] EMPTY_ARRAY =
+	new ConstructorInfo[0];
+
+    protected static String getName(int attrs) {
+	return (attrs & MethodAttributes.Static) == 0 ? CTOR : CCTOR;
+    }
+
+    /** Protected constructor */
+    protected ConstructorInfo(Type declType, int attrs, Type[] paramTypes) {
+	super(getName(attrs), declType, attrs, paramTypes);
+	assert declType != null : "Owner can't be 'null' for a constructor!";
+    }
+
+    protected ConstructorInfo(Type declType, int attrs, ParameterInfo[] params)
+    {
+	super(getName(attrs), declType, attrs, params);
+	assert declType != null : "Owner can't be 'null' for a constructor!";
+    }
+
+
+    public String toString() {
+	return MethodAttributes.toString(Attributes) + " " + Type.VOID() +
+	    " " + DeclaringType.FullName + "::" + Name + params2String();
+    }
+
+    //##########################################################################
+
+} // class ConstructorInfo
diff --git a/src/msil/ch/epfl/lamp/compiler/msil/CustomAttributeProvider.java b/src/msil/ch/epfl/lamp/compiler/msil/CustomAttributeProvider.java
new file mode 100644
index 0000000..0e58c18
--- /dev/null
+++ b/src/msil/ch/epfl/lamp/compiler/msil/CustomAttributeProvider.java
@@ -0,0 +1,82 @@
+/*
+ * System.Reflection-like API for access to .NET assemblies (DLL & EXE)
+ */
+
+
+package ch.epfl.lamp.compiler.msil;
+
+import java.util.List;
+import java.util.LinkedList;
+import java.util.Iterator;
+
+/**
+ * @author Nikolay Mihaylov
+ * @version 1.0
+ */
+public abstract class CustomAttributeProvider implements ICustomAttributeProvider {
+
+    //##########################################################################
+
+    protected List/*<Attribute>*/ custAttrs;
+    private static final Object[] EMPTY = new Object[0];
+
+    //TODO: take inherit into account
+    public Object[] GetCustomAttributes(boolean inherit) {
+	initAttributes(null);
+	return custAttrs.size() == 0 ? EMPTY
+            : custAttrs.toArray(new Attribute[custAttrs.size()]);
+    }
+
+    //TODO: take inherit into account
+    public Object[] GetCustomAttributes(Type attributeType, boolean inherit) {
+	initAttributes(attributeType);
+        List tAttrs = null;
+        if (constrType == attributeType)
+            tAttrs = custAttrs;
+        else {
+            tAttrs = new LinkedList();
+            for (Iterator attrs = custAttrs.iterator(); attrs.hasNext(); ) {
+                Attribute a = (Attribute) attrs.next();
+                if (a.GetType() == attributeType) tAttrs.add(a);
+            }
+        }
+	return tAttrs.size() == 0 ? EMPTY
+            : tAttrs.toArray(new Attribute[tAttrs.size()]);
+    }
+
+    //TODO: take inherit into account
+    public boolean IsDefined(Type attributeType, boolean inherit) {
+	initAttributes(attributeType);
+        if (constrType == attributeType)
+            return custAttrs.size() > 0;
+	Iterator attrs = custAttrs.iterator();
+	while (attrs.hasNext()) {
+	    if (((Attribute)attrs.next()).GetType() == attributeType)
+		return true;
+	}
+	return false;
+// 	return inherit && (DeclaringClass.BaseType != null)
+// 	    && DeclaringClass.BaseType.IsDefined(inherit);
+    }
+
+    protected void addCustomAttribute(ConstructorInfo constr, byte[] value) {
+        Attribute attr = new Attribute(constr, value);
+        assert constrType == null || constrType == attr.GetType();
+        if (custAttrs == null)
+            custAttrs = new LinkedList();
+	custAttrs.add(attr);
+    }
+
+    private void initAttributes(Type atype) {
+	if (custAttrs != null
+            && (constrType == null || constrType == atype))
+	    return;
+	custAttrs = new LinkedList();
+        constrType = atype;
+	loadCustomAttributes(atype);
+    }
+
+    protected void loadCustomAttributes(Type atype) {}
+
+    private Type constrType;
+}
diff --git a/src/msil/ch/epfl/lamp/compiler/msil/EventAttributes.java b/src/msil/ch/epfl/lamp/compiler/msil/EventAttributes.java
new file mode 100644
index 0000000..a183993
--- /dev/null
+++ b/src/msil/ch/epfl/lamp/compiler/msil/EventAttributes.java
@@ -0,0 +1,32 @@
+/*
+ * System.Reflection-like API for access to .NET assemblies (DLL & EXE)
+ */
+
+
+package ch.epfl.lamp.compiler.msil;
+
+/**
+ * Specifies flags that describe the attributes of a an event.
+ *
+ * @author Nikolay Mihaylov
+ * @version 1.0
+ */
+public final class EventAttributes {
+
+    //##########################################################################
+
+    /** Specifies that the event has no attributes. */
+    public static final short None = 0x000;
+
+    /** Specifies a reserved flag for CLR use only. */
+    public static final short ReservedMask = 0x0400;
+
+    /** Specifies that the event is special in a way described by the name. */
+    public static final short SpecialName = 0x0200;
+
+    /** Specifies the the CLR should check name encoding. */
+    public static final short RTSpecialName = 0x0400;
+
+    //##########################################################################
+
+} // class EventAttributes
diff --git a/src/msil/ch/epfl/lamp/compiler/msil/EventInfo.java b/src/msil/ch/epfl/lamp/compiler/msil/EventInfo.java
new file mode 100644
index 0000000..3ccba79
--- /dev/null
+++ b/src/msil/ch/epfl/lamp/compiler/msil/EventInfo.java
@@ -0,0 +1,58 @@
+/*
+ * System.Reflection-like API for access to .NET assemblies (DLL & EXE)
+ */
+
+
+package ch.epfl.lamp.compiler.msil;
+
+
+/**
+ * Discovers the attributes of an event
+ * and provides access to event metadata.
+ *
+ * @author Nikolay Mihaylov
+ * @version 1.0
+ */
+public class EventInfo extends MemberInfo {
+
+    //##########################################################################
+
+    public final int MemberType() { return MemberTypes.Event; }
+
+    /** Attributes associated with the event. */
+    public final short Attributes;
+
+    /** The Type object for the underlying event-handler delegate
+     *  associated with this event.
+     */
+    public final Type EventHandlerType;
+
+    public MethodInfo GetAddMethod() { return addMethod; }
+
+    public MethodInfo GetRemoveMethod() { return removeMethod; }
+
+    public String toString() {
+        return "" + EventHandlerType + " " + Name;
+    }
+
+    //##########################################################################
+
+    protected static final EventInfo[] EMPTY_ARRAY = new EventInfo[0];
+
+    protected MethodInfo addMethod;
+
+    protected MethodInfo removeMethod;
+
+    protected EventInfo(String name, Type declType, short attr,
+                        Type handlerType, MethodInfo add, MethodInfo remove)
+    {
+        super(name, declType);
+        Attributes = attr;
+        EventHandlerType = handlerType;
+        this.addMethod = add;
+        this.removeMethod = remove;
+    }
+
+    //##########################################################################
+
+} // class EventInfo
diff --git a/src/msil/ch/epfl/lamp/compiler/msil/FieldAttributes.java b/src/msil/ch/epfl/lamp/compiler/msil/FieldAttributes.java
new file mode 100644
index 0000000..d7d1bb3
--- /dev/null
+++ b/src/msil/ch/epfl/lamp/compiler/msil/FieldAttributes.java
@@ -0,0 +1,119 @@
+/*
+ * System.Reflection-like API for access to .NET assemblies (DLL & EXE)
+ */
+
+
+package ch.epfl.lamp.compiler.msil;
+
+/**
+ * Specifies flags that describe the attributes of a field.
+ *
+ * @author Nikolay Mihaylov
+ * @version 1.0
+ */
+public final class FieldAttributes {
+
+    //##########################################################################
+
+    /** Specifies the access level of a given field. */
+    public static final short FieldAccessMask = 0x0007;
+
+    /** Member not refereneceable. */
+    public static final short CompilerControlled = 0x0000;
+
+    /** Field is accessible only by the parent type. */
+    public static final short Private = 0x0001;
+
+    /** Field is accessible only by subtypes in this assembly. */
+    public static final short FamANDAssem = 0x0002;
+
+    /** Field is accessible throughout the assembly. */
+    public static final short Assembly = 0x0003;
+
+    /** Field is accessible only by type and subtypes. */
+    public static final short Family = 0x0004;
+
+    /** Field is accessible by subtypes anywhere,
+     *  as well as throughout this assembly. */
+    public static final short FamORAssem  = 0x0005;
+
+    /** Specifies that the field is accessible by any member
+     *  for whom this scope is visible. */
+    public static final short Public = 0x0006;
+
+    //##########################################################################
+    //
+
+    /** Field represents the defined type, or else it is per-instance. */
+    public static final short Static = 0x0010;
+
+    /** Field is initialized only and cannot be written after initialization. */
+    public static final short InitOnly = 0x0020;
+
+    /** Value is compile-time constant. */
+    public static final short Literal = 0x0040;
+
+    /** Field does not have to be serialized when the type is remoted. */
+    public static final short NotSerialized = 0x0080;
+
+    /** Field is special. */
+    public static final short SpecialName = 0x0200;
+
+    //##########################################################################
+    // Interop attributes
+
+    /** Implementation is forwarded through PInvoke */
+    public static final short PinvokeImpl = 0x2000;
+
+
+    //##########################################################################
+    // Additional flags
+
+    /** CLI provides 'special' behavior depending upon the name of the field */
+    public static final short RTSpecialName = 0x0400;
+
+    /** Field has marshalling information. */
+    public static final short HasFieldMarshal = 0x1000;
+
+    /** Field has a default value. */
+    public static final short HasDefault = (short)0x8000;
+
+    /** Field has a Relative Virtual Address (RVA). The RVA is the location
+     *  of the method body in the current image, as an address relative
+     *  to the start of the image file in which it is located. */
+    public static final short HasFieldRVA = 0x0100;
+
+    //##########################################################################
+    //
+
+    public static String toString(short attrs) {
+	StringBuffer str = new StringBuffer();
+	switch (attrs & FieldAccessMask) {
+	case CompilerControlled: str.append("compilercontrolled"); break;
+	case Private:            str.append("private"); break;
+	case FamANDAssem:        str.append("famandassem"); break;
+	case Assembly:           str.append("assembly"); break;
+	case Family:             str.append("family"); break;
+	case FamORAssem:         str.append("famorassem"); break;
+	case Public:             str.append("public"); break;
+	}
+	if ((attrs & Static) != 0) str.append(" static");
+	if ((attrs & InitOnly) != 0) str.append(" initonly");
+	if ((attrs & Literal) != 0) str.append(" literal");
+	if ((attrs & NotSerialized) != 0) str.append(" notserialized");
+	if ((attrs & SpecialName) != 0) str.append(" specialname");
+	if ((attrs & PinvokeImpl) != 0) str.append("");
+	if ((attrs & RTSpecialName) != 0) str.append(" rtspecialname");
+	if ((attrs & HasFieldMarshal) != 0) str.append(" marshal(<native type>)");
+	//if ((attrs & HasDefault) != 0) str.append(" default(???)");
+	return str.toString();
+    }
+
+    //##########################################################################
+
+    // makes the class uninstantiable
+    private FieldAttributes() {}
+
+    //##########################################################################
+
+}  // class FieldAttributes
diff --git a/src/msil/ch/epfl/lamp/compiler/msil/FieldInfo.java b/src/msil/ch/epfl/lamp/compiler/msil/FieldInfo.java
new file mode 100644
index 0000000..9649dab
--- /dev/null
+++ b/src/msil/ch/epfl/lamp/compiler/msil/FieldInfo.java
@@ -0,0 +1,112 @@
+/*
+ * System.Reflection-like API for access to .NET assemblies (DLL & EXE)
+ */
+
+
+package ch.epfl.lamp.compiler.msil;
+
+/**
+ * Discovers the attributes of a field and provides access to field metadata.
+ *
+ * @author Nikolay Mihaylov
+ * @version 1.0
+ */
+public class FieldInfo extends MemberInfo {
+
+    //##########################################################################
+    // public interface
+
+    public final int MemberType() { return MemberTypes.Field; }
+
+    /** Attributes associated with this field. */
+    public final short Attributes;
+
+    /** Type of the field represented by this FieldInfo object. */
+    public final Type FieldType;
+
+    protected final Object value;
+
+    public final boolean IsStatic() {
+	return (Attributes & FieldAttributes.Static)   != 0;
+    }
+
+    public final boolean IsInitOnly() {
+	return (Attributes & FieldAttributes.InitOnly) != 0;
+    }
+
+    public final boolean IsLiteral() {
+ 	return (Attributes & FieldAttributes.Literal) != 0;
+
+    }
+
+    public final boolean IsPublic() {
+	return (Attributes & FieldAttributes.FieldAccessMask)
+	    == FieldAttributes.Public;
+    }
+
+    public final boolean IsPrivate() {
+	return (Attributes & FieldAttributes.FieldAccessMask)
+	    == FieldAttributes.Private;
+    }
+
+    public final boolean IsFamily() {
+	return (Attributes & FieldAttributes.FieldAccessMask)
+	    == FieldAttributes.Family;
+    }
+
+    public final boolean IsAssembly() {
+	return (Attributes & FieldAttributes.FieldAccessMask)
+	    == FieldAttributes.Assembly;
+    }
+
+    public final boolean IsFamilyOrAssembly() {
+	return (Attributes & FieldAttributes.FieldAccessMask)
+	    == FieldAttributes.FamORAssem;
+    }
+
+    public final boolean IsFamilyAndAssembly() {
+	return (Attributes & FieldAttributes.FieldAccessMask)
+	    == FieldAttributes.FamANDAssem;
+    }
+    public final boolean IsSpecialName() {
+ 	return (Attributes & FieldAttributes.SpecialName) != 0;
+    }
+
+    public final boolean IsPinvokeImpl() {
+ 	return (Attributes & FieldAttributes.PinvokeImpl) != 0;
+    }
+
+    public final boolean IsNotSerialized() {
+ 	return (Attributes & FieldAttributes.NotSerialized) != 0;
+    }
+
+    public String toString() {
+	return FieldAttributes.toString(Attributes) + " " +
+	    FieldType + " " + DeclaringType.FullName + "::" +  Name;
+    }
+
+    //##########################################################################
+
+    protected static final FieldInfo[] EMPTY_ARRAY = new FieldInfo[0];
+
+    /** Initializes a new instance of the FieldInfo class. */
+    protected FieldInfo(String name, Type declType, int attrs, Type fieldType) {
+	this(name, declType, attrs, fieldType, null);
+    }
+
+    protected FieldInfo(String name, Type declType,
+			int attrs, Type fieldType, Object value)
+    {
+	super(name, declType);
+	FieldType = fieldType;
+	Attributes = (short) attrs;
+	this.value = value;
+    }
+
+    /**
+     */
+    public Object getValue() { return value; }
+
+    //##########################################################################
+
+}  // class FieldInfo
diff --git a/src/msil/ch/epfl/lamp/compiler/msil/ICustomAttributeProvider.java b/src/msil/ch/epfl/lamp/compiler/msil/ICustomAttributeProvider.java
new file mode 100644
index 0000000..9271859
--- /dev/null
+++ b/src/msil/ch/epfl/lamp/compiler/msil/ICustomAttributeProvider.java
@@ -0,0 +1,57 @@
+/*
+ * System.Reflection-like API for access to .NET assemblies (DLL & EXE)
+ */
+
+
+package ch.epfl.lamp.compiler.msil;
+
+/**
+ * Provides custom attributes for reflection objects that support them.
+ *
+ * @author Nikolay Mihaylov
+ * @version 1.0
+ */
+public interface ICustomAttributeProvider {
+
+    //##########################################################################
+    // interface method definitions
+
+    /** Returns an array of all of the custom attributes
+     *  defined on this member, excluding named attributes,
+     * 	or an empty array if there are no custom attributes.
+     *
+     *  @param inherit - When true, look up the hierarchy chain
+     *                   for the inherited custom attribute.
+     *  @return - An array of Objects representing custom attributes,
+     *            or an empty array.
+     */
+    public Object[] GetCustomAttributes(boolean inherit);
+
+
+    /** Returns an array of custom attributes defined on this member,
+     *  identified by type, or an empty array
+     *  if there are no custom attributes of that type.
+     *
+     *  @param attributeType - The type of the custom attributes.
+     *  @param inherit - When true, look up the hierarchy chain
+     *                   for the inherited custom attribute.
+     *  @return - An array of Objects representing custom attributes,
+     *            or an empty array.
+     */
+    public Object[] GetCustomAttributes(Type attributeType, boolean inherit);
+
+
+    /** Indicates whether one or more instance of attributeType
+     *  is defined on this member
+     *
+     *  @param attributeType - The type of the custom attributes
+     *  @param inherit - When true, look up the hierarchy chain
+     *                   for the inherited custom attribute.
+     *  @return - true if the attributeType is defined on this member;
+     *            false otherwise.
+     */
+    public boolean IsDefined(Type attributeType, boolean inherit);
+
+    //##########################################################################
+
+}  // interface ICustomAttributeProvider
diff --git a/src/msil/ch/epfl/lamp/compiler/msil/MemberInfo.java b/src/msil/ch/epfl/lamp/compiler/msil/MemberInfo.java
new file mode 100644
index 0000000..65ff1b2
--- /dev/null
+++ b/src/msil/ch/epfl/lamp/compiler/msil/MemberInfo.java
@@ -0,0 +1,47 @@
+/*
+ * System.Reflection-like API for access to .NET assemblies (DLL & EXE)
+ */
+
+
+package ch.epfl.lamp.compiler.msil;
+
+/**
+ * The root class of the Reflection hierarchy.
+ *
+ * @author Nikolay Mihaylov
+ * @version 1.0
+ */
+public abstract class MemberInfo extends CustomAttributeProvider {
+
+    //##########################################################################
+
+    /** The name of this member. */
+    public final String Name;
+
+    /**
+     * The class that declares this member.
+     * Note: if the MemberInfo object is a global member,
+     * (that is, it was obtained from Module.GetMethods,
+     * which returns global methods on a module), then DeclaringType
+     * will be a null reference.
+     */
+    public final Type DeclaringType;
+
+    /** An enumerated value from the MemberTypes class,
+     *  specifying a constructor, event, field, method,
+     *  property, type information, all, or custom. */
+    public abstract int MemberType();
+
+    //##########################################################################
+    // protected members
+
+    protected static final MemberInfo[] EMPTY_ARRAY = new MemberInfo[0];
+
+    protected MemberInfo(String name, Type declType) {
+	Name = name;
+	DeclaringType = declType;
+    }
+
+    //########################################################################
+
+}  // class MemberInfo
diff --git a/src/msil/ch/epfl/lamp/compiler/msil/MemberTypes.java b/src/msil/ch/epfl/lamp/compiler/msil/MemberTypes.java
new file mode 100644
index 0000000..5f49ad3
--- /dev/null
+++ b/src/msil/ch/epfl/lamp/compiler/msil/MemberTypes.java
@@ -0,0 +1,81 @@
+/*
+ * System.Reflection-like API for access to .NET assemblies (DLL & EXE)
+ */
+
+
+package ch.epfl.lamp.compiler.msil;
+
+/**
+ * Marks each type of member that is defined as a derived class of MemberInfo.
+ *
+ * @author Nikolay Mihaylov
+ * @version 1.0
+ */
+public final class MemberTypes {
+
+    //##########################################################################
+
+    /** Specifies that the member is a constructor,
+     *  representing a ConstructorInfo member. */
+    public static final int Constructor = 0x01;
+
+
+    /** Specifies that the member is an event,
+     *  representing an EventInfo member. */
+    public static final int Event = 0x02;
+
+
+    /** Specifies that the member is a field,
+     *	representing a FieldInfo member. */
+    public static final int Field = 0x04;
+
+
+    /** Specifies that the member is a method,
+     *  representing a MethodInfo member. */
+    public static final int Method = 0x08;
+
+
+    /** Specifies that the member is a property,
+     *  representing a PropertyInfo member.
+     */
+    public static final int Property = 0x10;
+
+    /** Specifies that the member is a type,
+     *  representing a TypeInfo member. */
+    public static final int TypeInfo = 0x20;
+
+
+    /** Specifies that the member is a custom member type. */
+    public static final int Custom = 0x40;
+
+
+    /** Specifies that the member is a nested type,
+     *  extending MemberInfo. */
+    public static final int NestedType = 0x80;
+
+
+    /** Specifies all member types. */
+    public static final int All =
+	Constructor | Event | Field | Method | Property | TypeInfo | NestedType;
+
+
+    public static String toString(int memberType) {
+	if ((memberType & Constructor) != 0) return "Constructor";
+	if ((memberType & Event) != 0) return "Event";
+	if ((memberType & Field) != 0) return "Field";
+	if ((memberType & Method) != 0) return "Method";
+	if ((memberType & Property) != 0) return "Property";
+	if ((memberType & TypeInfo) != 0) return "TypeInfo";
+	if ((memberType & Custom) != 0) return "Custom";
+	if ((memberType & NestedType) != 0) return "NestedType";
+	return "Unknown MemberType: " + memberType;
+    }
+
+    //##########################################################################
+
+    // makes the class uninstantiable
+    private MemberTypes() {}
+
+    //##########################################################################
+
+}  // class MemberTypes
diff --git a/src/msil/ch/epfl/lamp/compiler/msil/MethodAttributes.java b/src/msil/ch/epfl/lamp/compiler/msil/MethodAttributes.java
new file mode 100644
index 0000000..a703c38
--- /dev/null
+++ b/src/msil/ch/epfl/lamp/compiler/msil/MethodAttributes.java
@@ -0,0 +1,158 @@
+/*
+ * System.Reflection-like API for access to .NET assemblies (DLL & EXE)
+ */
+
+
+package ch.epfl.lamp.compiler.msil;
+
+/** Specifies flags for method attributes.
+ *
+ * @author Nikolay Mihaylov
+ * @version 1.0
+ */
+public final class MethodAttributes {
+
+    //##########################################################################
+    // Method access attributes
+
+    /** Bitmask used to retrieve accessibility information. */
+    public static final short MemberAccessMask = 0x0007;
+
+    ///** Member not referenceable*/
+    //public static final short CompilerConstrolled = 0x0000;
+
+    /** Indicates that the member cannot be referenced. */
+    public static final short PrivateScope = 0x0000;
+
+    /** Method is accessible only by the current class. */
+    public static final short Private = 0x0001;
+
+    /** Method is accessible to members of this type
+     *  and its derived types that are in this assembly only. */
+    public static final short FamANDAssem = 0x0002;
+
+    /** Method is accessible to any class of this assembly. */
+    public static final short Assembly = 0x0003;
+
+    /** Method is accessible only to members of this class
+     *  and its derived classes. */
+    public static final short Family = 0x0004;
+
+    /** Method is accessible to derived classes anywhere,
+     *  as well as to any class in the assembly. */
+    public static final short FamORAssem = 0x0005;
+
+    /** Method is accessible to any object for which this object is in scope. */
+    public static final short Public = 0x0006;
+
+
+    //##########################################################################
+    // Flags
+
+    /** Method is defined on the type; otherwise, it is defined per instance. */
+    public static final short Static = 0x0010;
+
+    /** Method cannot be overridden. */
+    public static final short Final = 0x0020;
+
+    /** Method is virtual. */
+    public static final short Virtual = 0x0040;
+
+    /** Method hides by name and signature; otherwise, by name only. */
+    public static final short HideBySig  = 0x0080;
+
+
+    //##########################################################################
+    // vtable attributes
+
+    /** Bitmask used to retrieve vtable attributes. */
+    public static final short VtableLayoutMask = 0x0100;
+
+    /** Method reuses existing slot in the vtable. */
+    public static final short ReuseSlot = 0x0000;
+
+
+    /** Method always gets a new slot in the vtable. */
+    public static final short NewSlot = 0x0100;
+
+
+    //##########################################################################
+    // Flags
+
+    /** Method does not provide implementation. */
+    public static final short Abstract = 0x0400;
+
+    /** Method is special. */
+    public static final short SpecialName = 0x0800;
+
+
+    //##########################################################################
+    // Interop attributes
+
+    /** Method implementation is forwarded through PInvoke. */
+    public static final short PInvokeImpl = 0x2000;
+
+    /** Reserved: shall be zero for conforming implementations.
+     *  Managed method is exported by thunk to unmanaged code. */
+    public static final short UnmanagedExport = 0x0008;
+
+
+    //##########################################################################
+    // Additional flags
+
+    /** CLI provides special behavior, depending on the name of the method. */
+    public static final short RTSpecialName = 0x1000;
+
+    /** Method has security associated with it.
+     * Reserved flag for runtime use only.
+     */
+    public static final short HasSecurity = 0x00000040;
+
+    /**
+     * Indicates that the method calls another method containing security code.
+     * Reserved flag for runtime use only.
+     */
+    public static final short RequireSecObject = 0x00004000;
+
+    /** Indicates a reserved flag for runtime use only. */
+    public static final short ReservedMask = 0x0000;
+
+
+    //##########################################################################
+
+    public static String toString(short attrs) {
+	StringBuffer str = new StringBuffer(accessFlagsToString(attrs));
+	if ((attrs & Static) != 0) str.append(" static");
+	if ((attrs & Final) != 0) str.append(" final");
+	if ((attrs & Virtual) != 0) str.append(" virtual");
+	if ((attrs & Abstract) != 0) str.append(" abstract");
+	if ((attrs & HideBySig) != 0) str.append(" hidebysig");
+	if ((attrs & NewSlot) != 0) str.append(" newslot");
+	if ((attrs & SpecialName) != 0) str.append(" specialname");
+	if ((attrs & PInvokeImpl) != 0) str.append(" pinvokeimpl(?!?)");
+	if ((attrs & RTSpecialName) != 0) str.append(" rtspecialname");
+	return str.toString();
+
+    }
+
+    public static String accessFlagsToString(short attrs) {
+	switch (attrs & MemberAccessMask) {
+	case PrivateScope: return "compilercontrolled";
+	case Private:      return "private";
+	case FamANDAssem:  return "famandassem";
+	case Assembly:     return "assembly";
+	case Family:       return "family";
+	case FamORAssem:   return "famorassem";
+	case Public:       return "public";
+	default: return "xxx";
+	}
+    }
+
+    //##########################################################################
+
+    // makes the class uninstantiable
+    private MethodAttributes() {}
+
+    //##########################################################################
+
+}  // class Method Attributes
diff --git a/src/msil/ch/epfl/lamp/compiler/msil/MethodBase.java b/src/msil/ch/epfl/lamp/compiler/msil/MethodBase.java
new file mode 100644
index 0000000..793ee36
--- /dev/null
+++ b/src/msil/ch/epfl/lamp/compiler/msil/MethodBase.java
@@ -0,0 +1,144 @@
+/*
+ * System.Reflection-like API for access to .NET assemblies (DLL & EXE)
+ */
+
+
+package ch.epfl.lamp.compiler.msil;
+
+/**
+ * The common superclass of MemberInfo and ConstructorInfo
+ *
+ * @author Nikolay Mihaylov
+ * @version 1.0
+ */
+public abstract class MethodBase extends MemberInfo {
+
+    //##########################################################################
+    // public interface
+
+    /** The attributes associated with this method/constructor. */
+    public final short Attributes;
+
+    /***/
+    public final short CallingConvention;
+
+    public abstract boolean IsConstructor();
+
+    public final boolean IsAbstract() {
+	return (Attributes & MethodAttributes.Abstract) != 0;
+    }
+
+    public final boolean IsFinal() {
+	return (Attributes& MethodAttributes.Final)    != 0;
+    }
+
+    public final boolean IsVirtual() {
+	return (Attributes& MethodAttributes.Virtual)  != 0;
+    }
+
+    public final boolean IsStatic() {
+	return (Attributes & MethodAttributes.Static)   != 0;
+    }
+
+    public final boolean IsHideBySig() {
+ 	return (Attributes & MethodAttributes.HideBySig) != 0;
+    }
+
+    public final boolean IsSpecialName() {
+ 	return (Attributes & MethodAttributes.SpecialName) != 0;
+    }
+
+
+    public final boolean IsPublic() {
+	return (Attributes & MethodAttributes.MemberAccessMask)
+	    == MethodAttributes.Public;
+    }
+
+    public final boolean IsPrivate() {
+	return (Attributes & MethodAttributes.MemberAccessMask)
+	    == MethodAttributes.Private;
+    }
+
+    public final boolean IsFamily() {
+	return (Attributes & MethodAttributes.MemberAccessMask)
+	    == MethodAttributes.Family;
+    }
+
+    public final boolean IsAssembly() {
+	return (Attributes & MethodAttributes.MemberAccessMask)
+	    == MethodAttributes.Assembly;
+    }
+
+    public final boolean IsFamilyOrAssembly() {
+	return (Attributes & MethodAttributes.MemberAccessMask)
+	    == MethodAttributes.FamORAssem;
+    }
+
+    public final boolean IsFamilyAndAssembly() {
+	return (Attributes & MethodAttributes.MemberAccessMask)
+	    == MethodAttributes.FamANDAssem;
+    }
+
+
+    /** Returns the parameters of the method/constructor. */
+    public ParameterInfo[] GetParameters() {
+	return (ParameterInfo[]) params.clone();
+    }
+
+    public int GetMethodImplementationFlags() { return implAttributes; }
+
+    //##########################################################################
+
+    /** Method parameters. */
+    protected ParameterInfo[] params;
+
+    protected short implAttributes;
+
+    protected MethodBase(String name, Type declType, int attrs, Type[] paramTypes)
+    {
+	this(name, declType, attrs);
+	assert paramTypes != null;
+	params = new ParameterInfo[paramTypes.length];
+	for (int i = 0; i < params.length; i++)
+	    params[i] = new ParameterInfo(null, paramTypes[i], 0, i);
+    }
+
+    protected MethodBase(String name, Type declType, int attrs,
+			 ParameterInfo[] params)
+    {
+	this(name, declType, attrs);
+	this.params = params;
+    }
+
+    /**
+     */
+    private MethodBase(String name, Type declType, int attrs) {
+	super(name, declType);
+
+	Attributes = (short) attrs;
+
+	if (IsConstructor()) {
+	    attrs |= MethodAttributes.SpecialName;
+	    attrs |= MethodAttributes.RTSpecialName;
+	}
+
+	CallingConvention = (short) (CallingConventions.Standard
+	    | (IsStatic() ? (short)0 : CallingConventions.HasThis));
+   }
+
+    //##########################################################################
+    // internal methods
+
+    protected String params2String() {
+	StringBuffer s = new StringBuffer("(");
+	for (int i = 0; i < params.length; i++) {
+	    if (i > 0) s.append(", ");
+	    s.append(params[i].ParameterType);
+	}
+	s.append(")");
+	return s.toString();
+    }
+
+    //##########################################################################
+
+}  // class MethodBase
diff --git a/src/msil/ch/epfl/lamp/compiler/msil/MethodImplAttributes.java b/src/msil/ch/epfl/lamp/compiler/msil/MethodImplAttributes.java
new file mode 100644
index 0000000..8e8d879
--- /dev/null
+++ b/src/msil/ch/epfl/lamp/compiler/msil/MethodImplAttributes.java
@@ -0,0 +1,116 @@
+/*
+ * System.Reflection-like API for access to .NET assemblies (DLL & EXE)
+ */
+
+
+package ch.epfl.lamp.compiler.msil;
+
+/**
+ * Method implementation attributes
+ * @author Nikolay Mihaylov
+ * @version 1.0
+ */
+public abstract class MethodImplAttributes {
+
+    //##########################################################################
+
+    /**
+     * Specifies flags about code type. 3
+     */
+    public static final short CodeTypeMask = (short) 0x0003;
+
+    /**
+     * Specifies that the method implementation is in MSIL. 0
+     */
+    public static final short IL = (short) 0x0000;
+
+    /**
+     * Specifies that the method implementation is native. 1
+     */
+    public static final short Native = (short) 0x0001;
+
+    /**
+     * This member supports the .NET Framework infrastructure and
+     * is not intended to be used directly from your code. 2
+     */
+    public static final short OPTIL = (short) 0x0002;
+
+    /**
+     * Specifies that the method implementation is provided by the runtime. 3
+     */
+    public static final short Runtime = (short) 0x0003;
+
+
+
+    /**
+     * Specifies whether the code is managed or unmanaged. 4
+     */
+    public static final short ManagedMask = (short) 0x0004;
+
+    /**
+     * Specifies that the method implementation is managed, otherwise unmanaged.
+     */
+    public static final short Managed = (short) 0x0000;
+
+    /**
+     * Specifies that the method implementation is unmanaged, otherwise managed.
+     */
+    public static final short Unmanaged = (short) 0x0004;
+
+
+
+    /**
+     * Specifies that the method cannot be inlined. 8
+     */
+    public static final short NoInlining = (short) 0x0008;
+
+    /**
+     * Specifies that the method is not defined. 16
+     */
+    public static final short ForwardRef = (short) 0x0010;
+
+    /**
+     * Specifies that the method is single-threaded through the body.
+     * You can also use the C# lock statement or the Visual Basic
+     * Lock function for this purpose. 32
+     */
+    public static final short Synchronized = (short) 0x0020;
+
+    /**
+     * Specifies that the method signature is exported exactly as declared. 128
+     */
+    public static final short PreserveSig = (short) 0x0080;
+
+    /**
+     * Specifies an internal call. 4096
+     */
+    public static final short InternalCall = (short) 0x1000;
+
+    /**
+     * Specifies a range check value. 65535
+     */
+    public static final short MaxMethodImplVal = (short) 0xffff;
+
+    //##########################################################################
+
+    public static String toString(int implAttr) {
+	StringBuffer s = new StringBuffer();
+	switch (implAttr & CodeTypeMask) {
+	case IL: s.append("cil"); break;
+	case Native: s.append("native"); break;
+	case Runtime: s.append("runtime"); break;
+	}
+	switch (implAttr & ManagedMask) {
+	case Managed: s.append(" managed"); break;
+	case Unmanaged: s.append(" unmanaged"); break;
+	}
+	if ((implAttr & NoInlining) != 0) s.append(" noinlining");
+	if ((implAttr & ForwardRef) != 0) s.append(" forwardref");
+	if ((implAttr & Synchronized) != 0) s.append(" synchronized");
+	if ((implAttr & InternalCall) != 0) s.append(" internalcall");
+	return s.toString();
+    }
+
+    //##########################################################################
+
+} // class MethodImplAttributes
diff --git a/src/msil/ch/epfl/lamp/compiler/msil/MethodInfo.java b/src/msil/ch/epfl/lamp/compiler/msil/MethodInfo.java
new file mode 100644
index 0000000..5e227fb
--- /dev/null
+++ b/src/msil/ch/epfl/lamp/compiler/msil/MethodInfo.java
@@ -0,0 +1,56 @@
+/*
+ * System.Reflection-like API for access to .NET assemblies (DLL & EXE)
+ */
+
+
+package ch.epfl.lamp.compiler.msil;
+
+/**
+ * Discovers the attributes of a method and provides access to method metadata.
+ *
+ * @author Nikolay Mihaylov
+ * @version 1.0
+ */
+public class MethodInfo extends MethodBase {
+
+    //##########################################################################
+    // public members
+
+    public final int MemberType() { return MemberTypes.Method; }
+
+    public final boolean IsConstructor() { return false; }
+
+    /** The return type of this method.
+     */
+    public final Type ReturnType;
+
+    //##########################################################################
+    // protected members
+
+    protected static final MethodInfo[] EMPTY_ARRAY = new MethodInfo[0];
+
+    /**
+     * Constructor Initializes a new instance of the MethodInfo class.
+     */
+    protected MethodInfo(String name, Type declType,
+			 int attrs, Type returnType, Type[] paramTypes )
+    {
+	super(name, declType, attrs, paramTypes);
+	ReturnType = returnType;
+    }
+
+    protected MethodInfo(String name, Type declType,
+			 int attrs, Type returnType, ParameterInfo[] params )
+    {
+	super(name, declType, attrs, params);
+	ReturnType = returnType;
+    }
+
+    public String toString() {
+ 	return MethodAttributes.toString(Attributes) + " " + ReturnType +
+	    " " + DeclaringType + "::" + Name + params2String();
+    }
+
+    //##########################################################################
+
+}  // class MethodInfo
diff --git a/src/msil/ch/epfl/lamp/compiler/msil/Module.java b/src/msil/ch/epfl/lamp/compiler/msil/Module.java
new file mode 100644
index 0000000..8dd5e71
--- /dev/null
+++ b/src/msil/ch/epfl/lamp/compiler/msil/Module.java
@@ -0,0 +1,155 @@
+/*
+ * System.Reflection-like API for access to .NET assemblies (DLL & EXE)
+ */
+
+
+package ch.epfl.lamp.compiler.msil;
+
+import java.util.Map;
+import java.util.HashMap;
+
+/**
+ * Defines and represents a module. Get an instance of ModuleBuilder
+ * by calling DefineDynamicModule
+ * A module is a portable executable file of type .dll or .exe consisting
+ * of one or more classes and interfaces. There may be multiple namespaces
+ * contained in a single module, and a namespace may span multiple modules.
+ * One or more modules deployed as a unit compose an assembly.
+ *
+ * @author Nikolay Mihaylov
+ * @version 1.0
+ */
+public abstract class Module extends CustomAttributeProvider {
+
+    //##########################################################################
+    // public fields
+
+    /** String representing the name of the module with the path removed. */
+    public final String Name;
+
+    /** String representing the fully qualified name and path to this module. */
+    public final String FullyQualifiedName;
+
+    /** String representing the name of the module. */
+    public String ScopeName;
+
+    /** The Assembly the Module belongs to. */
+    public final Assembly Assembly;
+
+    //##########################################################################
+    // constructor
+
+    protected Module(String name, String filename,
+		     String scopeName, Assembly assembly)
+    {
+	this.Name = name;
+	this.FullyQualifiedName = filename;
+	this.ScopeName = scopeName;
+	this.Assembly = assembly;
+    }
+
+    //##########################################################################
+    // public methods
+
+    /** Returns the specified class, performing a case-sensitive search. */
+    public Type GetType(String name) {
+        initTypes();
+	return (Type) typesMap.get(name);
+    }
+
+    /**
+     * @return all the classes defined within this module.
+     */
+    public Type[] GetTypes() {
+        initTypes();
+	return (Type[]) types.clone();
+    }
+
+    /**
+     * @return the global field with the specified name.
+     */
+    public FieldInfo GetField(String name) {
+	for (int i = 0; i < fields.length; i++)
+	    if (fields[i].Name.equals(name))
+		return fields[i];
+	return null;
+    }
+
+    /**
+     * @return an array of the global fields of the module
+     */
+    public FieldInfo[] GetFields() {
+	return (FieldInfo[]) fields.clone();
+    }
+
+    /**
+     * @return - the global method with the specified name
+     */
+    public MethodInfo GetMethod(String name) {
+	for (int i = 0; i < methods.length; i++)
+	    if (methods[i].Name.equals(name))
+		return methods[i];
+	return null;
+    }
+
+    /**
+     * @return - an array of all the global methods defined in this modules.
+     */
+    public MethodInfo[] GetMethods() {
+	return (MethodInfo[]) methods.clone();
+    }
+
+    /**
+     */
+    public String toString() { return Name; }
+
+    //########################################################################
+    // protected members
+
+    // all the types defined in this module
+    protected final Map typesMap = new HashMap();
+
+    // all the types defined in this module
+    protected Type[] types;
+
+    // the global fields of the module
+    protected FieldInfo[] fields = FieldInfo.EMPTY_ARRAY;
+
+    // the global methods of the module
+    protected MethodInfo[] methods = MethodInfo.EMPTY_ARRAY;
+
+    protected Type addType(Type type) {
+	addType(type.FullName, type);
+	Assembly.addType(type);
+	return type;
+    }
+
+    protected Type addType(String name, Type type) {
+	assert type!= null;
+	typesMap.put(name, type);
+	return type;
+    }
+
+    private boolean initTypes = true;
+    protected final void initTypes() {
+        if (initTypes) {
+            loadTypes();
+            initTypes = false;
+        }
+    }
+
+    protected void loadTypes() {}
+
+    private boolean initGlobals = true;
+    protected final void initGlobals() {
+        if (initGlobals) {
+            loadGlobals();
+            initGlobals = false;
+        }
+    }
+
+    protected void loadGlobals() {}
+
+    //##########################################################################
+
+}  // class Module
diff --git a/src/msil/ch/epfl/lamp/compiler/msil/PEAssembly.java b/src/msil/ch/epfl/lamp/compiler/msil/PEAssembly.java
new file mode 100644
index 0000000..a31db16
--- /dev/null
+++ b/src/msil/ch/epfl/lamp/compiler/msil/PEAssembly.java
@@ -0,0 +1,69 @@
+/*
+ * System.Reflection-like API for access to .NET assemblies (DLL & EXE)
+ */
+
+
+package ch.epfl.lamp.compiler.msil;
+
+import ch.epfl.lamp.compiler.msil.util.Table;
+import ch.epfl.lamp.compiler.msil.util.Table.*;
+
+import java.io.File;
+
+import java.util.Map;
+import java.util.HashMap;
+
+/** Represents an assembly that resides in a real .NET assembly
+ *
+ * @author Nikolay Mihaylov
+ * @version 1.0
+ */
+final class PEAssembly extends Assembly {
+
+    private final PEFile pefile;
+
+    private PEModule mainModule;
+
+    public PEAssembly(PEFile pefile, AssemblyName an) {
+	super(an, true);
+	this.pefile = pefile;
+	String name = pefile.ModuleDef(1).getName();
+	mainModule = new PEModule(pefile, 1, name, this);
+	addModule(name, mainModule);
+        //initModules();
+    }
+
+    protected void loadModules() {
+	File parentDir = pefile.getParentFile();
+	FileDef fd = pefile.FileDef;
+	for (int row = 1; row <= fd.rows; row++) {
+	    fd.readRow(row);
+	    String filename = fd.getName();
+	    File f = new File(parentDir, filename);
+	    PEFile pe = Assembly.getPEFile(f);
+	    if (pe == null) {
+		f = new File(filename);
+		pe = Assembly.getPEFile(f);
+		if (pe == null)
+		    continue;
+// 		throw new RuntimeException("Cannot find file " + filename +
+// 					   " referenced by assembly " + this);
+	    }
+	    String name = pe.ModuleDef(1).getName();
+	    PEModule module = new PEModule(pe, 1, name, this);
+	    addModule(name, module);
+	}
+    }
+
+    public File getFile() {
+	return pefile.getUnderlyingFile();
+    }
+
+    protected void loadCustomAttributes(Type attributeType) {
+        initModules();
+        mainModule.initAttributes(this, 1, Table.AssemblyDef.ID, attributeType);
+    }
+
+    //##########################################################################
+
+} // class PEAssembly
diff --git a/src/msil/ch/epfl/lamp/compiler/msil/PEFile.java b/src/msil/ch/epfl/lamp/compiler/msil/PEFile.java
new file mode 100644
index 0000000..3a03865
--- /dev/null
+++ b/src/msil/ch/epfl/lamp/compiler/msil/PEFile.java
@@ -0,0 +1,877 @@
+/*
+ * System.Reflection-like API for access to .NET assemblies (DLL & EXE)
+ */
+
+
+package ch.epfl.lamp.compiler.msil;
+
+import ch.epfl.lamp.compiler.msil.util.*;
+import ch.epfl.lamp.compiler.msil.util.Table.*;
+
+import ch.epfl.lamp.compiler.msil.Type;
+import ch.epfl.lamp.compiler.msil.Module;
+
+import java.io.File;
+import java.io.RandomAccessFile;
+import java.io.PrintStream;
+import java.io.IOException;
+import java.io.FileNotFoundException;
+
+import java.nio.ByteBuffer;
+import java.nio.channels.FileChannel;
+import java.nio.MappedByteBuffer;
+
+import java.util.Date;
+
+/**
+ * A class that represents a .NET PE/COFF image.
+ *
+ * @author Nikolay Mihaylov
+ * @version 1.0
+ * @see <a href="http://www.ecma-international.org/publications/standards/Ecma-335.htm">Standard ECMA-335:  Common Language Infrastructure (CLI), 4th edition (June 2006)</a>
+ */
+public class PEFile {
+
+    //##########################################################################
+
+    public static final int INT_SIZE = 4;
+
+    protected final int PE_SIGNATURE_OFFSET;
+    protected final int COFF_HEADER_OFFSET;
+    protected final int PE_HEADER_OFFSET;
+
+    protected final int numOfSections;
+    protected final int CLI_RVA;
+    protected final int CLI_Length;
+    public final int rvaMetadata;
+    public final int posMetadata;
+    protected final int numOfStreams;
+    protected final int optHeaderSize;
+
+    protected final File underlyingFile;
+    protected final RandomAccessFile file;
+    protected final MappedByteBuffer buf;
+
+    protected final PESection [] sections;
+
+    public PEStream Meta, Strings, US, Blob, GUID;
+
+    private final Table [] tables = new Table[Table.MAX_NUMBER];
+
+    public final boolean isDLL;
+
+    protected final int heapSizes;
+    public final boolean StringIsShort, BlobIsShort, GUIDIsShort;
+
+    protected PEModule pemodule = null;
+
+    //##########################################################################
+    // PEFile constructor
+
+    private static void fileFormatCheck(boolean cond, String s) {
+	if (cond)
+	    throw new RuntimeException(s);
+    }
+
+    /**
+     */
+    public PEFile(String filename) throws FileNotFoundException {
+	this.underlyingFile = new File(filename);
+	this.file = new RandomAccessFile(underlyingFile, "r");
+	FileChannel fc = file.getChannel();
+	MappedByteBuffer bb = null;
+	try {
+	    bb = fc.map(FileChannel.MapMode.READ_ONLY, 0L, fc.size());
+ 	} catch (IOException e) { throw new RuntimeException(e); }
+
+    /** Ecma 335, 25 File format extensions to PE:
+     *
+     *  "Unless stated otherwise, all binary values are stored in little-endian format."
+     */
+
+	bb.order(java.nio.ByteOrder.LITTLE_ENDIAN);
+	this.buf = bb;
+
+    /** Ecma 335, 25.2.1 MS-DOS header:
+     *
+     *  "The PE format starts with an MS-DOS stub of exactly the following 128 bytes to
+     *  be placed at the front of the module."
+     *
+     *  We are only checking for MZ (Mark Zbikowski)
+     */
+
+	seek(0);
+	fileFormatCheck(readByte() != 0x4d, "Invalid PE file format: " + filename); // 'M'
+	fileFormatCheck(readByte() != 0x5a, "Invalid PE file format: " + filename); // 'Z'
+
+    /** Ecma 335, 25.2.1 MS-DOS header:
+     *
+     *  "At offset 0x3c in the DOS header is a 4-byte unsigned integer offset, lfanew,
+     *  to the PE signature (shall be “PE\0\0”), immediately followed by the PE file header.
+     */
+
+	seek(0x3c);
+	PE_SIGNATURE_OFFSET = readInt();
+	seek(PE_SIGNATURE_OFFSET);
+
+	fileFormatCheck(readByte() != 0x50, "Invalid PE file format: " + filename); // 'P'
+	fileFormatCheck(readByte() != 0x45, "Invalid PE file format: " + filename); // 'E'
+    fileFormatCheck(readByte() != 0x00, "Invalid PE file format: " + filename); //  0
+    fileFormatCheck(readByte() != 0x00, "Invalid PE file format: " + filename); //  0 
+
+	//trace("PE signature offset = 0x" + Table.int2hex(PE_SIGNATURE_OFFSET));
+
+	COFF_HEADER_OFFSET = PE_SIGNATURE_OFFSET + 4;
+	PE_HEADER_OFFSET = COFF_HEADER_OFFSET + 20;
+
+	seek(COFF_HEADER_OFFSET);
+	skip(2);
+    /** Ecma 335, 25.2.2: "Number of sections; indicates size of the Section Table" */
+	numOfSections = readShort();
+	//trace("Number of sections = " + numOfSections);
+
+    /** Ecma 335, 25.2.2: "Time and date the file was created in seconds since
+     *  January 1st 1970 00:00:00 or 0."
+     */
+	Date timeStamp = new Date(readInt() * 1000L);
+	//trace("Time stamp = " + timeStamp);
+
+	skip(2 * INT_SIZE);
+	optHeaderSize = readShort();
+	int characteristics = readShort();
+	isDLL = (characteristics & 0x2000) != 0;
+	//trace("Characteristics = " + Integer.toHexString(characteristics));
+
+	seek(PE_HEADER_OFFSET + 208); // p.157, Partition II
+
+ 	CLI_RVA = readInt();
+	CLI_Length = readInt();
+	//trace("CLI_RVA = 0x" + Table.int2hex(CLI_RVA));
+	//trace("CLI_Length = 0x" + Table.int2hex(CLI_Length));
+
+	sections = new PESection[numOfSections];
+
+	seek(PE_HEADER_OFFSET + optHeaderSize); // go to the sections descriptors
+
+	for (int i = 0; i < numOfSections; i++) {
+	    seek(PE_HEADER_OFFSET + optHeaderSize + i * 40);
+	    sections[i] = new PESection(this);
+	    //sections[i].dump(System.out);
+	}
+
+	seek(fromRVA(CLI_RVA));
+	skip(8);
+	rvaMetadata = readInt();
+	posMetadata = fromRVA(rvaMetadata);
+	//trace("rvaMetadata = 0x" + Table.int2hex(rvaMetadata));
+	//trace("posMetadata = 0x" + Table.int2hex(posMetadata));
+
+	seek(posMetadata);
+	int magic = readInt();
+	//trace("Magic metadata signature = 0x" + Table.int2hex(magic));
+	fileFormatCheck(magic != 0x424a5342, "Invalid metadata signature!");
+	skip(8);
+
+	int strlength = readInt();
+	//trace("version name string length = " + strlength);
+	skip(strlength);
+	align(INT_SIZE, posMetadata);
+	//trace("position of flags = 0x" + Table.int2hex((int)pos()));
+	skip(2); // ignore the flags
+	numOfStreams = readShort();
+	//trace("Number of metadata streams = " + numOfStreams);
+
+	for (int i = 0; i < numOfStreams; i++) {
+	    PEStream strm = new PEStream(this);
+	    //strm.dump(System.out);
+	    if (strm.name.equals("#~")
+		|| strm.name.equals("#-"))    Meta = strm;
+	    if (strm.name.equals("#Strings")) Strings = strm;
+	    if (strm.name.equals("#US"))      US = strm;
+	    if (strm.name.equals("#Blob"))    Blob = strm;
+	    if (strm.name.equals("#GUID"))    GUID = strm;
+	}
+
+	seek(Meta.offset);
+	skip(6);
+	heapSizes = readByte();
+	StringIsShort = (heapSizes & 0x01) == 0;
+	GUIDIsShort   = (heapSizes & 0x02) == 0;
+	BlobIsShort   = (heapSizes & 0x04) == 0;
+
+	skip(1);
+	long tablesMask = readLong();
+	long nonStandardTables = tablesMask & ~Table.VALID_TABLES_MASK;
+	skip(8); //go to the list of number of rows
+	for (int i = 0; i < tables.length; i++) {
+	    tables[i] = Table.newTable
+		(this, i, ((tablesMask >> i) & 0x01) != 0 ? readInt() : 0);
+	}
+
+	initIndexSize();
+	initTableRefs();
+	// populate the tables from the CLI image file
+	long start = pos();
+	for (int i = 0; i < tables.length; i++)
+	    start = tables[i].init(start);
+
+    } // PEFile()
+
+
+    public final int[] indexSize = new int[Table.TABLE_SET_LENGTH];
+
+    private void initIndexSize() {
+	for (int i = 0; i < Table.TABLE_SET_LENGTH; i++) {
+	    indexSize[i] = 2;
+	    int[] tableSet = Table.TableSet[i];
+	    int treshold = (65536 >> Table.NoBits[i]);
+	    for (int j = 0; j < tableSet.length; j++) {
+		if (tableSet[j] >= 0) {
+		    Table t = tables[tableSet[j]];
+		    if (t.rows >= treshold) {
+			indexSize[i] = 4;
+			break;
+		    }
+		}
+	    }
+	}
+    }
+
+    protected void initModule(PEModule module) {
+	if (pemodule != null)
+	    throw new RuntimeException("File " + this
+				       + " has already been assigned module "
+				       + pemodule + "; new module is " + module);
+	this.pemodule = module;
+    }
+
+    //##########################################################################
+
+    public ModuleDef ModuleDef;
+    public ModuleDef ModuleDef(int i) {
+	ModuleDef.readRow(i);
+	return ModuleDef;
+    }
+
+    public TypeRef TypeRef;
+
+    public TypeDef TypeDef;
+    public TypeDef TypeDef(int i) {
+	TypeDef.readRow(i);
+	return TypeDef;
+    }
+
+    public FieldTrans FieldTrans;
+    public FieldTrans FieldTrans(int i) {
+	FieldTrans.readRow(i);
+	return FieldTrans;
+    }
+
+    public FieldDef FieldDef;
+    public FieldDef FieldDef(int i) {
+	FieldDef.readRow(i);
+	return FieldDef;
+    }
+
+    public MethodTrans MethodTrans;
+    public MethodTrans MethodTrans(int i) {
+	MethodTrans.readRow(i);
+	return MethodTrans;
+    }
+
+    public MethodDef MethodDef;
+    public MethodDef MethodDef(int i) { MethodDef.readRow(i); return MethodDef; }
+
+
+    public ParamDef ParamDef;
+    public ParamDef ParamDef(int i) { ParamDef.readRow(i); return ParamDef; }
+
+    public InterfaceImpl InterfaceImpl;
+    public MemberRef MemberRef;
+    public Constant Constant;
+    public CustomAttribute CustomAttribute;
+    public FieldMarshal FieldMarshal;
+    public DeclSecurity DeclSecurity;
+    public ClassLayout ClassLayout;
+    public FieldLayout FieldLayout;
+    public StandAloneSig StandAloneSig;
+    public EventMap EventMap;
+    public EventDef EventDef;
+    public PropertyMap PropertyMap;
+    public PropertyDef PropertyDef;
+    public MethodSemantics MethodSemantics;
+    public MethodImpl MethodImpl;
+    public ModuleRef ModuleRef;
+    public TypeSpec TypeSpec;
+    public ImplMap ImplMap;
+    public FieldRVA FieldRVA;
+    public AssemblyDef AssemblyDef;
+    public AssemblyRef AssemblyRef;
+    public FileDef FileDef;
+    public ExportedType ExportedType;
+    public ManifestResource ManifestResource;
+    public NestedClass NestedClass;
+
+
+    private void initTableRefs() {
+	ModuleDef = (ModuleDef) getTable(Table.ModuleDef.ID);
+	TypeRef = (TypeRef) getTable(Table.TypeRef.ID);
+	TypeDef = (TypeDef) getTable(Table.TypeDef.ID);
+	FieldTrans = (FieldTrans) getTable(Table.FieldTrans.ID);
+	FieldDef = (FieldDef) getTable(Table.FieldDef.ID);
+	MethodTrans = (MethodTrans) getTable(Table.MethodTrans.ID);
+	MethodDef = (MethodDef) getTable(Table.MethodDef.ID);
+	ParamDef = (ParamDef) getTable(Table.ParamDef.ID);
+	InterfaceImpl = (InterfaceImpl) getTable(Table.InterfaceImpl.ID);
+	MemberRef = (MemberRef) getTable(Table.MemberRef.ID);
+	Constant = (Constant) getTable(Table.Constant.ID);
+	CustomAttribute = (CustomAttribute) getTable(Table.CustomAttribute.ID);
+	FieldMarshal = (FieldMarshal) getTable(Table.FieldMarshal.ID);
+	DeclSecurity = (DeclSecurity) getTable(Table.DeclSecurity.ID);
+	ClassLayout = (ClassLayout) getTable(Table.ClassLayout.ID);
+	FieldLayout = (FieldLayout) getTable(Table.FieldLayout.ID);
+	StandAloneSig = (StandAloneSig) getTable(Table.StandAloneSig.ID);
+	EventMap = (EventMap) getTable(Table.EventMap.ID);
+	EventDef = (EventDef) getTable(Table.EventDef.ID);
+	PropertyMap = (PropertyMap) getTable(Table.PropertyMap.ID);
+	PropertyDef = (PropertyDef) getTable(Table.PropertyDef.ID);
+	MethodSemantics = (MethodSemantics) getTable(Table.MethodSemantics.ID);
+	MethodImpl = (MethodImpl) getTable(Table.MethodImpl.ID);
+	ModuleRef = (ModuleRef) getTable(Table.ModuleRef.ID);
+	TypeSpec = (TypeSpec) getTable(Table.TypeSpec.ID);
+	ImplMap = (ImplMap) getTable(Table.ImplMap.ID);
+	FieldRVA = (FieldRVA) getTable(Table.FieldRVA.ID);
+	AssemblyDef = (AssemblyDef) getTable(Table.AssemblyDef.ID);
+	AssemblyRef = (AssemblyRef) getTable(Table.AssemblyRef.ID);
+	FileDef = (FileDef) getTable(Table.FileDef.ID);
+	ExportedType = (ExportedType) getTable(Table.ExportedType.ID);
+	NestedClass = (NestedClass) getTable(Table.NestedClass.ID);
+	ManifestResource =
+	    (ManifestResource) getTable(Table.ManifestResource.ID);
+    }
+
+    public static String long2hex(long a) {
+	StringBuffer str = new StringBuffer("0000000000000000");
+	str.append(Long.toHexString(a));
+	int l = str.length();
+	return str.substring(l - 16, l);
+    }
+
+    public static String int2hex(int a) {
+	StringBuffer str = new StringBuffer("00000000");
+	str.append(Integer.toHexString(a));
+	int l = str.length();
+	return str.substring(l - 8, l);
+    }
+
+    public static String short2hex(int a) {
+	StringBuffer str = new StringBuffer("0000");
+	str.append(Integer.toHexString(a));
+	int l = str.length();
+	return str.substring(l - 4, l);
+    }
+
+    public static String byte2hex(int a) {
+	StringBuffer str = new StringBuffer("00");
+	str.append(Integer.toHexString(a));
+	int l = str.length();
+	return str.substring(l - 2, l);
+    }
+
+    public static String bytes2hex(byte[] buf) {
+	StringBuffer str = new StringBuffer();
+	for (int i = 0; i < buf.length; i++) {
+	    str.append(byte2hex(buf[i]));
+	    if (i < buf.length - 1)
+		str.append(" ");
+	}
+	return str.toString();
+    }
+
+    //##########################################################################
+    // filename
+
+    public File getUnderlyingFile() {
+	return underlyingFile;
+    }
+
+    /**
+     * @return the absolute path of the file
+     */
+    public String getAbsolutePath() {
+	return underlyingFile.getAbsolutePath();
+    }
+
+    /**
+     * @return the name of this file
+     */
+    public String getName() {
+	return underlyingFile.getName();
+    }
+
+    /**
+     * @return
+     */
+    public String getParent() {
+	return underlyingFile.getParent();
+    }
+
+    /**
+     * @return the file representing the directory the file belongs to
+     */
+    public File getParentFile() {
+	return underlyingFile.getParentFile();
+    }
+
+    public String toString() {
+	return getAbsolutePath();
+    }
+
+    //##########################################################################
+    // file pointer manipulation methods
+
+    /** Returns the current position in the file. */
+    public int pos() {
+	return buf.position();
+    }
+
+    /** Go to the specified position in the file. */
+    public void seek(int pos) {
+	buf.position(pos);
+    }
+
+
+    /** Align the current position in the file. */
+    public void align(int base) { align(base, 0); }
+
+    /** Align the current position in a section starting at offset. */
+    public void align(int base, int offset) {
+	int p = pos() - offset;
+	seek( offset + ((p % base) == 0 ? p : (p/base + 1) * base));
+    }
+
+    /** Computes the position in the file that corresponds to the given RVA. */
+    public int fromRVA(int rva) {
+	int i;
+	for(i = 0; i < numOfSections; i++)
+	    if(sections[i].virtAddr <= rva &&
+	       rva <= (sections[i].virtAddr + sections[i].virtSize))
+		return rva - sections[i].virtAddr + sections[i].realAddr;
+	throw new RuntimeException("RVA 0x" + Integer.toHexString(rva) +
+				   " is not within this file's sections!");
+    }
+
+    /** Go to the specified RVA (Relative Virtual Address). */
+    public void gotoRVA(int rva) {
+	seek(fromRVA(rva));
+    }
+
+    /** Move the forward in the file by the specified number of bytes. */
+    public void skip(int n) {
+	buf.position(buf.position() + n);
+    }
+
+    /**
+     * Returns a memory mapped little-endian buffer
+     * for the specified region of the file.
+     */
+    public MappedByteBuffer mapBuffer(long offset, int size) {
+ 	try {
+	    MappedByteBuffer b = file.getChannel()
+		.map(FileChannel.MapMode.READ_ONLY, offset, size);
+	    b.order(java.nio.ByteOrder.LITTLE_ENDIAN);
+	    return b;
+ 	} catch (IOException e) { throw new RuntimeException(e); }
+    }
+
+    /** Returns a buffer from the given offset to the end of the file. */
+    public ByteBuffer getBuffer(long offset, int size) {
+	buf.mark();
+	buf.position((int)offset);
+	ByteBuffer bb = buf.slice();
+	buf.reset();
+	bb.limit(size);
+	bb.order(java.nio.ByteOrder.LITTLE_ENDIAN);
+	return bb;
+    }
+
+    //##########################################################################
+    // file read methods
+
+    /**
+     * Read bs.length number of bytes
+     */
+    public void read(byte[] bs) {
+	buf.get(bs);
+    }
+
+    /**
+     * Read 1-byte integer from the current position in the file.
+     */
+    public int readByte() {
+	return buf.get();
+    }
+
+    /**
+     * Read 2-byte integer from the current position in the file.
+     */
+    public int readShort() {
+	return buf.getShort();
+    }
+
+    /**
+     * Read 4-byte integer from the current position in the file.
+     */
+    public int readInt() {
+	return buf.getInt();
+    }
+
+    /**
+     * Read 8-byte integer from the current position in the file.
+     */
+    public long readLong() {
+	return buf.getLong();
+    }
+
+    /**
+     * @return the size of string indeces for this file.
+     */
+    public int getStringIndexSize() {
+	return StringIsShort ? 2 : 4;
+    }
+
+    /**
+     * @return the size of GUID indeces for this file.
+     */
+    public int getGUIDIndexSize() {
+	return GUIDIsShort ? 2 : 4;
+    }
+
+    /**
+     * @return the size of Blob indeces for this file.
+     */
+    public int getBlobIndexSize() {
+	return BlobIsShort ? 2 : 4;
+    }
+
+    /**
+     * @return the size of the index to tableID for this file;
+     * @param tableID the ID of the table
+     */
+    public int getTableIndexSize(int tableID) {
+	return tables[tableID].isShort ? 2 : 4;
+    }
+
+    /**
+     * @return the size of the index to a set of tables with the given @param TableSetID
+     * @param tableSetID the ID of the table set
+     */
+    public int getTableSetIndexSize(int tableSetID) {
+	return indexSize[tableSetID];
+    }
+
+    /**
+     * Read a String index from the current position in the file.
+     * @return an index into the String stream
+     */
+    public int readStringIndex() {
+	return StringIsShort ? readShort() : readInt();
+    }
+
+    /**
+     * Read a GUID index from the current position in the file.
+     * @return an index in to the GUID stream
+     */
+    public int readGUIDIndex() {
+	return GUIDIsShort ? readShort() : readInt();
+    }
+
+    /**
+     * Read a Blob index from the current position in the file.
+     * @return an index into the Blob stream
+     */
+    public int readBlobIndex() {
+	return BlobIsShort ? readShort() : readInt();
+    }
+
+    /** Read an entry interpreted as index into table @param tableID. */
+    public int readTableIndex(int tableId) {
+	return tables[tableId].isShort ? readShort() : readInt();
+    }
+
+    /***/
+    public int readTableSetIndex(int tableSetId) {
+	return indexSize[tableSetId] == 2 ? readShort() : readInt();
+    }
+
+    /**
+     * Read a string from the String stream
+     * @return the string at the given position
+     * @param pos the position of the string in the String stream
+     */
+    public String getString(int pos) {
+	String s = Strings.getString(pos);
+	return s;//.length() == 0 ? null : s;
+    }
+
+    /**
+     * Read a string from the US (User Strings) stream
+     * @return the string at the given position
+     * @param pos the position of the string in the US stream
+     */
+    public String getUString(int pos) {
+	return US.getString(pos);
+    }
+
+    /**
+     * Read a blob from the Blob Stream
+     * @return the blob at the given position
+     * @param pos the position of the blob in the Blob stream
+     */
+    public byte[] getBlob(int pos) {
+	return Blob.getBlob(pos);
+    }
+
+    /***/
+    public Sig getSignature(int pos) {
+	//return new Sig(getBlob(pos));
+	return Blob.getSignature(pos);
+    }
+
+    /***/
+    public byte[] getGUID(int pos) {
+	return GUID.getGUID(pos);
+    }
+
+    /**
+     * @return the table with the corresponding ID.
+     */
+    public final Table getTable(int tableID) {
+	return tables[tableID];
+    }
+
+    //##########################################################################
+
+    /***/
+    void trace(String msg) {
+	System.out.println("[trace] " + msg);
+    }
+
+    //##########################################################################
+
+    public Sig newSignature(ByteBuffer buf) {
+	return new Sig(buf);
+    }
+
+    /**
+     */
+    public class Sig implements Signature {
+
+	//######################################################################
+	// instance members
+
+	protected final ByteBuffer buf;
+	protected final int pos;
+	protected final int length;
+
+	public Sig(ByteBuffer buf) {
+	    this.buf = buf;
+	    //int tmpPos = buf.position();
+	    length = decodeInt();
+	    this.pos = buf.position();
+	}
+
+	public String toString() {
+	    StringBuffer b = new StringBuffer("(");
+	    reset();
+	    for (int i = 0; i < length; i++) {
+		b.append(byte2hex(readByte()));
+		if (i < length - 1)
+		    b.append(" ");
+	    }
+	    return b.append(")").toString();
+	}
+
+	public Sig reset() { buf.position(pos); return this; }
+
+	public int pos() { return buf.position() - pos; }
+
+	/** @return the byte at the current position in the signature Blob.
+	 *  Stay at the same position
+	 */
+	public int getByte() {
+	    return (buf.get(buf.position()) + 0x100) & 0xff;
+	}
+
+	/** @return the byte at the current position in the signature Blob.
+	 *  Move to the next byte.
+	 */
+	public int readByte() { return (buf.get() + 0x100) & 0xff; }
+
+	/** Skip the current byte if equal to the given value. */
+	public void skipByte(int b) { if (b == getByte()) buf.get(); }
+
+	/** Decodes an integer from the signature Blob.
+	 *  @return the decoded integer
+	 */
+	public int decodeInt() {
+	    int res = readByte();
+	    if ((res & 0x80) != 0) {
+		res = ((res & 0x7f) << 8) | readByte();
+		if ((res & 0x4000) != 0)
+		    res = ((res & 0x3fff)<<16) | (readByte()<<8) | readByte();
+	    }
+	    return res;
+	}
+
+	/** @return - the type encoded at the current position in the signature
+	 *  according to 22.2.12
+	 */
+	public Type decodeType() {
+	    try { return decodeType0(); }
+	    catch (RuntimeException e) {
+		System.out.println("" + pos() + "@" + this);
+		throw e;
+	    }
+	}
+
+	public Type decodeType0() {
+	    Type type = null;
+	    int desc = readByte();
+	    switch (desc) {
+	    case ELEMENT_TYPE_BOOLEAN:type = Type.GetType("System.Boolean"); break;
+	    case ELEMENT_TYPE_CHAR:   type = Type.GetType("System.Char"); break;
+	    case ELEMENT_TYPE_I1:     type = Type.GetType("System.SByte"); break;
+	    case ELEMENT_TYPE_U1:     type = Type.GetType("System.Byte"); break;
+	    case ELEMENT_TYPE_I2:     type = Type.GetType("System.Int16"); break;
+	    case ELEMENT_TYPE_U2:     type = Type.GetType("System.UInt16"); break;
+	    case ELEMENT_TYPE_I4:     type = Type.GetType("System.Int32"); break;
+	    case ELEMENT_TYPE_U4:     type = Type.GetType("System.UInt32"); break;
+	    case ELEMENT_TYPE_I8:     type = Type.GetType("System.Int64"); break;
+	    case ELEMENT_TYPE_U8:     type = Type.GetType("System.UInt64"); break;
+	    case ELEMENT_TYPE_R4:     type = Type.GetType("System.Single"); break;
+	    case ELEMENT_TYPE_R8:     type = Type.GetType("System.Double"); break;
+	    case ELEMENT_TYPE_OBJECT: type = Type.GetType("System.Object"); break;
+	    case ELEMENT_TYPE_STRING: type = Type.GetType("System.String"); break;
+	    case ELEMENT_TYPE_I:      type = Type.GetType("System.IntPtr"); break;
+	    case ELEMENT_TYPE_U:      type = Type.GetType("System.UIntPtr"); break;
+	    case ELEMENT_TYPE_PTR:        // Followed by <type> token.
+		if (getByte() == ELEMENT_TYPE_VOID) {
+		    readByte();
+		    type = Type.mkPtr(Type.GetType("System.Void"));
+		} else type = Type.mkPtr(decodeType());
+		break;
+	    case ELEMENT_TYPE_BYREF:      // Followed by <type> token.
+	    case ELEMENT_TYPE_VALUETYPE:  // Followed by <type> token
+		//System.out.println("Signature.getType(): valuetype");
+		//type = pemodule.getTypeDefOrRef(decodeInt());
+	    case ELEMENT_TYPE_CLASS:
+		// Followed by <type> token
+		type = pemodule.getTypeDefOrRef(decodeInt());
+		if (type == null) throw new RuntimeException();
+		break;
+
+	    case ELEMENT_TYPE_SZARRAY:    // Single-dim array with 0 lower bound.
+		skipCustomMods();
+		type = Type.mkArray(decodeType(), 1);
+		break;
+	    case ELEMENT_TYPE_ARRAY:
+		// <type> <rank> <boundsCount> <bound1> ... <loCount> <lo1> ...
+		Type elem = decodeType();
+		int rank = decodeInt();
+		int numSizes = decodeInt();
+		for (int i = 0; i < numSizes; i++)
+		    decodeInt();
+		int numLoBounds = decodeInt();
+		for (int i = 0; i < numLoBounds; i++)
+		    decodeInt();
+		type = Type.mkArray(elem, rank);
+		break;
+
+	    case ELEMENT_TYPE_FNPTR:
+		// Followed by full method signature.
+	    case ELEMENT_TYPE_END:
+		// Marks end of a list
+	    case ELEMENT_TYPE_CMOD_REQD:
+		// Required modifier : followed by a TypeDef or TypeRef token.
+	    case ELEMENT_TYPE_CMOD_OPT:
+		// Optional modifier : followed by a TypeDef or TypeRef token.
+	    case ELEMENT_TYPE_INTERNAL:
+		// Implemented within the CLI.
+	    case ELEMENT_TYPE_MODIFIER:
+		// Or'd with following element types.
+	    case ELEMENT_TYPE_SENTINEL:
+		// Sentinel for varargs method signature.
+	    case ELEMENT_TYPE_PINNED:
+		// Denotes a local variable that points at a pinned object.
+	    default:
+		throw new RuntimeException(byte2hex(desc) +
+					   "@" + pos() + " in " + this);
+
+	    }
+	    if (type == null) throw new RuntimeException();
+	    return type;
+	} // getType()
+
+	public Type decodeFieldType() {
+	    skipByte(FIELD);
+	    skipCustomMods();
+	    return decodeType();
+	}
+
+	/** decodes the return type of a method signature (22.2.11). */
+	public Type decodeRetType() {
+	    skipCustomMods();
+	    switch (getByte()) {
+	    case ELEMENT_TYPE_VOID:
+		readByte();
+		return Type.GetType("System.Void");
+	    case ELEMENT_TYPE_TYPEDBYREF:
+		return Type.GetType("System.TypedReference");
+	    case ELEMENT_TYPE_BYREF:
+		skipByte(ELEMENT_TYPE_BYREF);
+		return decodeType();
+	    default:
+		return decodeType();
+	    }
+	}
+
+	public Type decodeParamType() {
+	    skipCustomMods();
+	    switch (getByte()) {
+	    case ELEMENT_TYPE_BYREF:
+		skipByte(ELEMENT_TYPE_BYREF);
+		return decodeType();
+	    case ELEMENT_TYPE_TYPEDBYREF:
+		return Type.GetType("System.TypedReference");
+	    default:
+		return decodeType();
+	    }
+	}
+
+	public void skipCustomMods() {
+	    while (getByte() == ELEMENT_TYPE_CMOD_OPT
+		   || getByte() == ELEMENT_TYPE_CMOD_REQD)
+		{
+                    // skip the tag 23.2.7
+                    readByte();
+                    // skip the TypeDefOrRefEncoded (23.2.8)
+                    readByte();
+                    readByte();
+
+                    // @FIXME: could be 4 bytes, not always 2...
+
+                    //Type t = decodeType();
+		    //System.err.println("CMOD: " + t);
+		    //if (getByte() == ELEMENT_TYPE_CMOD_REQD)
+                      //throw new RuntimeException("Reqired CMOD: " + t);
+		}
+	}
+
+	//######################################################################
+
+    }  // class Sig
+
+    //##########################################################################
+
+}  // class PEFile
diff --git a/src/msil/ch/epfl/lamp/compiler/msil/PEModule.java b/src/msil/ch/epfl/lamp/compiler/msil/PEModule.java
new file mode 100644
index 0000000..67242f9
--- /dev/null
+++ b/src/msil/ch/epfl/lamp/compiler/msil/PEModule.java
@@ -0,0 +1,335 @@
+/*
+ * System.Reflection-like API for access to .NET assemblies (DLL & EXE)
+ */
+
+
+package ch.epfl.lamp.compiler.msil;
+
+import ch.epfl.lamp.compiler.msil.PEFile;
+import ch.epfl.lamp.compiler.msil.PEFile.Sig;
+import ch.epfl.lamp.compiler.msil.util.Table;
+import ch.epfl.lamp.compiler.msil.util.Table.*;
+
+import java.util.Map;
+import java.util.HashMap;
+import java.util.ArrayList;
+import java.util.Iterator;
+
+/** Represents a module corresponding to a PE/COFF file
+ *
+ * @author Nikolay Mihaylov
+ * @version 1.0
+ */
+final class PEModule extends Module {
+
+    //##########################################################################
+
+    protected final PEFile pefile;
+
+    private final int definingRow;
+
+    private Type[] typeRefs = null;
+
+    protected PEModule(PEFile pefile, int definingRow, String scopeName,
+		       Assembly assem)
+    {
+	super(pefile.getName(), pefile.getAbsolutePath(), scopeName, assem);
+	this.pefile = pefile;
+        this.definingRow = definingRow;
+	pefile.initModule(this);
+	pefile.TypeDef.load(); // load into memory
+	//loadTypes();
+	//pefile.FieldDef.load();
+	//pefile.MethodDef.load();
+	loadGlobals();
+    }
+
+    //##########################################################################
+
+    public Type GetType(String typeName) {
+        initTypes();
+	Object o = typesMap.get(typeName);
+	if (o == null) {
+	    //System.out.println("PEModule.GetType(): Unable to find type "
+	    //                   + typeName + " int module " + this);
+	    return null;
+	}
+	return o instanceof Type ? (Type)o
+	    : getTypeDef(((Integer)o).intValue());
+    }
+
+
+    /** Load information about the types defined in this module.
+     */
+    protected void loadTypes() {
+	typeRefs = new Type[pefile.TypeRef.rows];
+	final int nbTypes = pefile.TypeDef.rows;
+	for (int row = 2; row <= nbTypes; row++) {
+	    String name = pefile.TypeDef(row).getFullName();
+	    typesMap.put(name, new Integer(row));
+	}
+	this.types = new Type[nbTypes - 1];
+	for (int row = 2; row <= nbTypes; row++) {
+	    getTypeDef(row);
+	}
+    }
+
+    /** Return the type defined at the given row in the TypeDef table.
+     */
+    Type getTypeDef(int row) {
+	if (this.types[row - 2] != null)
+	    return this.types[row - 2];
+
+	TypeDef type = pefile.TypeDef(row);
+	int attrs = type.Flags;
+	String name = type.getFullName();
+
+	Type declType = null;
+	if (TypeAttributes.isNested(attrs)) {
+	    for (int i = 1; i <= pefile.NestedClass.rows; i++) {
+		pefile.NestedClass.readRow(i);
+		if (pefile.NestedClass.NestedClass == row)
+		    declType = getTypeDef
+			(pefile.NestedClass.EnclosingClass);
+	    }
+	}
+	Type t = new PEType
+            (this, attrs, name, declType, Type.AuxAttr.None, pefile, row);
+	types[row - 2] = t;
+	addType(t);
+	return t;
+    }
+
+    /**
+     * Load the desription of the module-global fields and methods
+     */
+    protected void loadGlobals() {
+	//TODO:
+    }
+
+    protected void loadCustomAttributes(Type attributeType) {
+        initAttributes(this, 1, Table.ModuleDef.ID, attributeType);
+    }
+
+    /** Return the type referenced by the given row in the TypeRef table.
+     */
+    Type getTypeRef(int row) {
+        return getTypeRef(row, null);
+    }
+
+    /** Return the type referenced by the given row in the TypeRef table
+     *  only if it resides in the given assembly.
+     *  <i>Used by initCustomAttributes to avoid unnecessary loading
+     *  of referenced assemblies.</i>
+     */
+    Type getTypeRef(int row, Assembly inAssembly) {
+	Type type = typeRefs[row - 1];
+	if (type != null)
+	    return type;
+
+	Table.TypeRef tr = pefile.TypeRef;
+	tr.readRow(row);
+	int tableId = Table.getTableId(Table._ResolutionScope,
+				       tr.ResolutionScope);
+	int refRow = tr.ResolutionScope >> Table.NoBits[Table._ResolutionScope];
+	String typeName = tr.getFullName();
+	pefile.getTable(tableId).readRow(refRow);
+	switch (tableId) {
+	case AssemblyRef.ID:
+	    String name = pefile.AssemblyRef.getName();
+            if (inAssembly != null && !inAssembly.GetName().Name.equals(name))
+                return null;
+            Assembly assem = getAssembly(name);
+	    type = assem.GetType(typeName);
+	    if (type == null) {
+                // HACK: the IKVM.OpenJDK.Core assembly is compiled against mscorlib.dll v2.0
+                // The MSIL library cannot parse the v2.0 mscorlib because of generics, so we
+                // use the v1.0
+                // However, the java.io.FileDescriptor.FlushFileBuffers method uses a type
+                // Microsoft.Win32.SafeHandles.SafeFileHandle, which only exists in mscorlib
+                // v2.0
+                // For now, jsut return Object (fine as long as we don't use that method).
+                Assembly asmb = getAssembly("mscorlib");
+                type = asmb.GetType("System.Object");
+		//throw new RuntimeException("Failed to locate type " +
+                                           //typeName + " in assembly " + assem);
+	    }
+	    break;
+	case ModuleDef.ID:
+	    assert refRow == 1;
+	    type = this.GetType(typeName);
+	    //assert type != null;
+	    break;
+	case TypeRef.ID:
+	    type = getTypeRef(refRow);
+	    break;
+	case ModuleRef.ID:
+            type = getAssembly(pefile.ModuleRef.getName()).GetType(typeName);
+	default:
+	    throw new RuntimeException(refRow + "@" + pefile.getTable(tableId).getTableName()/* PEFile.byte2hex(tableId)*/);
+	}
+	if (typeRefs[row - 1] != null)
+	    System.out.println("TypeRef[" + PEFile.short2hex(row) + "] " +
+			       "changing type " + typeRefs[row - 1] +
+			       " for type " + type);
+	typeRefs[row - 1] = type;
+	assert type != null : "Couldn't find type " + typeName;
+	return type;
+    }
+
+    private Assembly getAssembly(String name) {
+        Assembly assem = Assembly.getAssembly(name);
+        if (assem != null)
+            return assem;
+        java.io.File dir = pefile.getParentFile();
+        assem = Assembly.LoadFrom(dir, name);
+        if (assem != null)
+            return assem;
+        try {
+            dir = pefile.getUnderlyingFile().getCanonicalFile().getParentFile();
+        } catch (java.io.IOException e) {
+            throw new RuntimeException(e);
+        }
+        assem = Assembly.LoadFrom(dir, name);
+        if (assem != null)
+            return assem;
+        throw new RuntimeException("Cannot find assembly: " + name);
+
+    }
+
+    /** Return the type corresponding to TypeDefOrRef coded index.
+     *  @param index - TypeDefOrRef coded index according to 23.2.6.
+     */
+    public Type getTypeDefOrRef(int index) {
+	int tableId = Table.getTableId(Table._TypeDefOrRef, index);
+	int row = index >> Table.NoBits[Table._TypeDefOrRef];
+	Type type = null;
+	switch (tableId) {
+	case Table.TypeDef.ID:
+	    type = getTypeDef(row);
+	    break;
+	case Table.TypeRef.ID:
+	    return getTypeRef(row);
+	case Table.TypeSpec.ID:
+	    throw new RuntimeException("PEModule.getTypeDefOrRef(): TypeSpec");
+	default:
+	    throw new RuntimeException("PEModule.getTypeDefOrRef(): oops!");
+	}
+	return type;
+    }
+
+    /** Returns the method defined at the given row of the MethodDef table
+     *  by looking up the type that defines the method.
+     */
+    MethodBase getMethod(int row) {
+	for (int i = 0; i < types.length; i++) {
+	    PEType type = (PEType)types[i]; 
+	    if ((type.methodListBeg <= row) && (row < type.methodListEnd)) {
+		type.initMethods();
+		return type.methoddefs[row - type.methodListBeg];
+	    }
+	}
+	throw new RuntimeException("In module " + this
+				   + ": cannot find type defining method 0x"
+				   + PEFile.int2hex(row));
+    }
+
+    /** Returns the member referenced by the given row of the MemberRef table.
+     */
+    protected MemberInfo getMemberRef(int row) {
+        return getMemberRef(row, null);
+    }
+
+    /** Returns the member referenced by the given row of the MemberRef table
+     *  if defined in the given assembly.
+     *  <i>Used by initCustomAttributes to avoid unnecessary loading of
+     *  referenced assemblies</i>
+     */
+    protected MemberInfo getMemberRef(int row, Assembly inAssembly) {
+	MemberInfo member = null;
+	MemberRef mref = pefile.MemberRef;
+	mref.readRow(row);
+	int mtbl = Table.getTableId(Table._MemberRefParent, mref.Class);
+	int mind = Table.getTableIndex(Table._MemberRefParent, mref.Class);
+	switch (mtbl) {
+	case TypeRef.ID:
+	    Type type = getTypeRef(mind, inAssembly);
+            if (type == null)
+                return null;
+            Sig sig = mref.getSignature();
+            int callconv = sig.readByte(); // should be 0x20
+            int paramCount = sig.decodeInt();
+	    //sig.skipByte(Signature.ELEMENT_TYPE_BYREF); //from MethodDef
+	    Type retType = sig.decodeRetType();
+	    Type[] paramType = new Type[paramCount];
+	    for (int i = 0; i < paramCount; i++)
+		paramType[i] = sig.decodeParamType();
+
+            String memberName = mref.getName();
+            if (memberName.equals(ConstructorInfo.CTOR) ||
+                memberName.equals(ConstructorInfo.CCTOR))
+            {
+                member = type.GetConstructor(paramType);
+            } else {
+                member = type.GetMethod(memberName, paramType);
+            }
+            assert member != null : type + "::" + memberName;
+	    break;
+	case ModuleRef.ID:
+	case MethodDef.ID:
+	case TypeSpec.ID:
+	    throw new RuntimeException("initCustomAttributes: "
+                                       + pefile.getTable(mtbl).getTableName());
+	}
+	return member;
+    }
+
+    protected void initCustomAttributes(Type attributeType) {
+        initAttributes(this, definingRow, Table.ModuleDef.ID, attributeType);
+    }
+
+    // explicitly only package-visible
+    void initAttributes(CustomAttributeProvider cap, int definingRow,
+                         int sourceTableId, Type attributeType)
+    {
+	int parentIndex = Table.encodeIndex(definingRow,
+                                            Table._HasCustomAttribute,
+                                            sourceTableId);
+	Table.CustomAttribute attrs = pefile.CustomAttribute;
+	for (int row = 1; row <= attrs.rows; row++) {
+            ConstructorInfo attrConstr = null;
+	    attrs.readRow(row);
+	    if (attrs.Parent == parentIndex) {
+		int tableId = Table.getTableId(Table._CustomAttributeType,
+					       attrs.Type);
+		int ind = Table.getTableIndex(Table._CustomAttributeType,
+					      attrs.Type);
+		switch (tableId) {
+		case MethodDef.ID:
+		    attrConstr = (ConstructorInfo)this.getMethod(ind);
+		    break;
+		case MemberRef.ID:
+		    //System.out.println(PEFile.short2hex(ind) + "@MemberRef");
+                    Assembly attrAssem =
+                        attributeType == null ? null : attributeType.Assembly();
+		    MemberInfo mi = this.getMemberRef(ind, attrAssem);
+                    if (mi != null) {
+                        assert mi instanceof ConstructorInfo
+                            : "Expected ConstructorInfo; found " + mi;
+                        attrConstr = (ConstructorInfo)mi;
+                    }
+		    break;
+		default:
+		    throw new RuntimeException();
+		}
+                if (attrConstr != null
+                    && (attrConstr.DeclaringType == attributeType
+                        || attributeType == null))
+                    cap.addCustomAttribute(attrConstr, attrs.getValue());
+	    }
+	}
+    }
+
+    //##########################################################################
+
+} // class PEModule
diff --git a/src/msil/ch/epfl/lamp/compiler/msil/PEType.java b/src/msil/ch/epfl/lamp/compiler/msil/PEType.java
new file mode 100644
index 0000000..ace364d
--- /dev/null
+++ b/src/msil/ch/epfl/lamp/compiler/msil/PEType.java
@@ -0,0 +1,398 @@
+/*
+ * System.Reflection-like API for access to .NET assemblies (DLL & EXE)
+ */
+
+
+package ch.epfl.lamp.compiler.msil;
+
+import ch.epfl.lamp.compiler.msil.PEFile.Sig;
+
+import ch.epfl.lamp.compiler.msil.util.Table;
+import ch.epfl.lamp.compiler.msil.util.Table.*;
+import ch.epfl.lamp.compiler.msil.util.Signature;
+
+import java.util.ArrayList;
+
+/**
+ * Represents a type from a .NET assembly
+ *
+ * @author Nikolay Mihaylov
+ * @version 1.0
+ */
+final class PEType extends Type implements Signature {
+
+    //##########################################################################
+
+    /** The PEFile that holds the description of the type. */
+    final PEFile file;
+
+    /** The number of the row in the TypeDef table defining the type. */
+    final int definingRow;
+
+    /** The row of the first method in the MethodDef table. */
+    final int methodListBeg;
+
+    /** The row of the last method in the MethodDef table + 1. */
+    final int methodListEnd;
+
+    /** @param definingRow - the index in the TypeDef table where
+     *  the type description is.
+     */
+    PEType(PEModule module,
+	   int attributes,
+	   String fullName,
+	   Type declType,
+	   int auxAttr,
+	   PEFile file,
+	   int definingRow)
+    {
+	super(module, attributes, fullName, null, null, declType, auxAttr);
+	this.file = file;
+	this.definingRow = definingRow;
+	methodListBeg = file.TypeDef(definingRow).MethodList;
+	methodListEnd = definingRow < file.TypeDef.rows
+	    ? file.TypeDef(definingRow + 1).MethodList
+	    : file.MethodDef.rows + 1;
+    }
+
+    //##########################################################################
+    // lazy type construction methods
+
+    protected void loadBaseType() {
+	TypeDef type = file.TypeDef(definingRow);
+	baseType = type.Extends == 0 ? null
+	    : ((PEModule)Module).getTypeDefOrRef(type.Extends);
+    }
+
+    protected void loadFields() {
+	// the list of the declared fields starts from the
+	// FieldList index in the TypeDef table up to the smaller of the:
+	//  - the last row of the FieldDef table
+	//  - the start of the next list of fields determined by the
+	// FieldList index of the next row in the TypeDef table
+	final ArrayList fields = new ArrayList();
+	int fieldListBeg = file.TypeDef(definingRow).FieldList;
+	int fieldListEnd = file.FieldDef.rows + 1;
+	if (definingRow < file.TypeDef.rows)
+	    fieldListEnd = file.TypeDef(definingRow + 1).FieldList;
+
+	for (int row = fieldListBeg; row < fieldListEnd; row++) {
+	    int frow = file.FieldTrans.rows == 0
+		? row : file.FieldTrans(row).Field;
+	    int attrs = file.FieldDef(frow).Flags;
+	    String name = file.FieldDef.getName();
+	    //System.out.println("\t-->Loading field: " + name);
+	    Sig sig = file.FieldDef.getSignature();
+	    Type fieldType = sig.decodeFieldType();
+	    Object val = null;
+	    Table.Constant consts = file.Constant;
+	    for (int i = 1; i <= consts.rows; i++) {
+		consts.readRow(i);
+		int tableId = Table.getTableId(Table._HasConstant,consts.Parent);
+		int refRow = consts.Parent >> Table.NoBits[Table._HasConstant];
+		if (tableId == Table.FieldDef.ID && refRow == frow)
+		    val = consts.getValue();
+	    }
+	    FieldInfo field =
+		new PEFieldInfo(row, name, attrs, fieldType, val);
+	    if (field.Name.equals("value__") && field.IsSpecialName())
+		{
+		    assert underlyingType == null : underlyingType.toString();
+		    underlyingType = field.FieldType;
+		}
+	    fields.add(field);
+	}
+	this.fields = (FieldInfo[])
+	    fields.toArray(FieldInfo.EMPTY_ARRAY);
+	fields.clear();
+    }
+
+    protected MethodBase[] methoddefs;
+    protected MethodInfo getMethod(int n) {
+        return (MethodInfo)methoddefs[n - methodListBeg];
+    }
+    protected void loadMethods() {
+	methoddefs = new MethodBase[methodListEnd - methodListBeg];
+
+	final ArrayList methods = new ArrayList();
+	final ArrayList constrs = new ArrayList();
+	PEModule pemodule = (PEModule) Module;
+	for (int row = methodListBeg; row < methodListEnd; row++) {
+	    int mrow = file.MethodTrans.rows == 0
+		? row : file.MethodTrans(row).Method;
+	    int attrs = file.MethodDef(mrow).Flags;
+	    String name = file.MethodDef.getName();
+	    Sig sig = file.MethodDef.getSignature();
+	    int callConv = sig.readByte();
+	    int paramCount = sig.decodeInt();
+	    sig.skipByte(Signature.ELEMENT_TYPE_BYREF);
+	    Type retType = sig.decodeRetType();
+	    Type[] paramType = new Type[paramCount];
+	    for (int i = 0; i < paramCount; i++)
+		paramType[i] = sig.decodeParamType();
+
+	    ParameterInfo[] params = new ParameterInfo[paramCount];
+	    int paramListBeg = file.MethodDef.ParamList;
+	    int paramListEnd = file.ParamDef.rows + 1;
+	    // if not the last method
+	    if (file.MethodDef.currentRow() < file.MethodDef.rows) {
+		paramListEnd = file.MethodDef(mrow + 1).ParamList;
+	    }
+	    for (int i = paramListBeg; i < paramListEnd; i++) {
+		int pattr = file.ParamDef(i).Flags;
+		String paramName = file.ParamDef.getName();
+		int seq = file.ParamDef.Sequence;
+		if (seq == 0) {
+		    //System.out.println("Retval attributes 0x" +
+		    //		       PEFile.short2hex(pattr));
+		} else {
+		    params[seq - 1] = new ParameterInfo
+			(paramName, paramType[seq - 1], pattr, seq - 1);
+		}
+	    }
+	    for (int i = 0; i < params.length; i++) {
+		if (params[i] == null)
+		    params[i] = new ParameterInfo(null, paramType[i], 0, 0);
+	    }
+	    MethodBase method = null;
+	    if ((attrs & MethodAttributes.SpecialName) != 0
+		&& (attrs & MethodAttributes.RTSpecialName) != 0
+		&& (name.equals(ConstructorInfo.CTOR)
+		    || name.equals(ConstructorInfo.CCTOR)))
+		method = new PEConstructorInfo(row, attrs, params);
+	    else
+		method = new PEMethodInfo(row, name, attrs, retType, params);
+	    (method.IsConstructor() ? constrs : methods).add(method);
+	    methoddefs[row - methodListBeg] = method;
+	}
+
+	this.constructors = (ConstructorInfo[])
+	    constrs.toArray(ConstructorInfo.EMPTY_ARRAY);
+	this.methods = (MethodInfo[])
+	    methods.toArray(MethodInfo.EMPTY_ARRAY);
+	constrs.clear(); methods.clear();
+    }
+
+    protected void loadProperties() {
+	final PropertyMap pmap = file.PropertyMap;
+	if (pmap == null) {
+	    properties = PropertyInfo.EMPTY_ARRAY;
+	    return;
+	}
+
+        final PropertyDef pdef = file.PropertyDef;
+        int propListBeg =  -1;
+        int propListEnd = pdef.rows + 1;
+	for (int i = 1; i <= pmap.rows; i++) {
+	    pmap.readRow(i);
+	    if (pmap.Parent == this.definingRow) {
+                propListBeg = pmap.PropertyList;
+                if (i < pmap.rows) {
+                    pmap.readRow(i + 1);
+                    propListEnd = pmap.PropertyList;
+                }
+                break;
+            }
+        }
+	if (propListBeg < 0) {
+	    properties = PropertyInfo.EMPTY_ARRAY;
+	    return;
+	}
+
+	final ArrayList properties = new ArrayList();
+        for (int i = propListBeg; i < propListEnd; i++) {
+            pdef.readRow(i);
+            Sig sig = pdef.getSignature();
+            int b = sig.readByte();
+            b &= ~HASTHIS;
+            int paramCount = sig.readByte();
+            assert b == PROPERTY;
+            Type propType = sig.decodeType();
+            int index = Table.encodeIndex(i, Table._HasSemantics,
+                                          Table.PropertyDef.ID);
+            MethodSemantics msem = file.MethodSemantics;
+            MethodInfo getter = null, setter = null;
+            for (int j = 1; j <= msem.rows; j++) {
+                msem.readRow(j);
+                if (msem.Association != index)
+                    continue;
+                if (msem.isGetter())
+                    getter = getMethod(msem.Method);
+                else if (msem.isSetter())
+                    setter = getMethod(msem.Method);
+                else
+                    System.err.println("PEType.loadProperties(): !?!");
+            }
+            properties.add
+                (new PEPropertyInfo(i, pdef.getName(), (short)pdef.Flags,
+                                    propType, getter, setter));
+	}
+	this.properties = (PropertyInfo[]) properties
+	    .toArray(PropertyInfo.EMPTY_ARRAY);
+    }
+
+    protected void loadEvents() {
+        EventMap emap = file.EventMap;
+        if (emap == null) {
+            this.events = EventInfo.EMPTY_ARRAY;
+            return;
+        }
+
+        final EventDef edef = file.EventDef;
+        int eventListBeg = -1;
+        int eventListEnd = edef.rows + 1;
+        for (int i = 1; i <= emap.rows; i++) {
+            emap.readRow(i);
+            if (emap.Parent == this.definingRow) {
+                eventListBeg = emap.EventList;
+                if (i < emap.rows) {
+                    emap.readRow(i + 1);
+                    eventListEnd = emap.EventList;
+                }
+                break;
+            }
+        }
+        if (eventListBeg < 0) {
+            this.events = EventInfo.EMPTY_ARRAY;
+            return;
+        }
+
+        final ArrayList events = new ArrayList();
+        final MethodSemantics msem = file.MethodSemantics;
+        for (int i = eventListBeg; i < eventListEnd; i++) {
+            edef.readRow(i);
+            final Type handler =
+                ((PEModule)Module).getTypeDefOrRef(edef.EventType);
+            int index =
+                Table.encodeIndex(i, Table._HasSemantics, Table.EventDef.ID);
+            MethodInfo add = null, remove = null;
+            for (int j = 1; j <= msem.rows; j++) {
+                msem.readRow(j);
+                if (msem.Association != index)
+                    continue;
+                if (msem.isAddOn())
+                    add = getMethod(msem.Method);
+                else if (msem.isRemoveOn())
+                    remove = getMethod(msem.Method);
+                else {}
+            }
+            events.add(new PEEventInfo(i, edef.getName(),
+                                       (short)edef.EventFlags,
+                                       handler, add, remove));
+        }
+        this.events = (EventInfo[]) events
+            .toArray(EventInfo.EMPTY_ARRAY);
+    }
+
+    protected void loadNestedTypes() {
+	final ArrayList nested = new ArrayList();
+	for (int i = 1; i <= file.NestedClass.rows; i++) {
+	    file.NestedClass.readRow(i);
+	    if (file.NestedClass.EnclosingClass == this.definingRow)
+		nested.add(((PEModule)Module)
+			   .getTypeDef(file.NestedClass.NestedClass));
+	}
+	this.nestedTypes = (Type[]) nested.toArray(Type.EmptyTypes);
+    }
+
+    protected void loadInterfaces() {
+	// get the interfaces implemented by this class
+	interfaces = Type.EmptyTypes;
+	int index = file.InterfaceImpl.findType(definingRow);
+	if (index > 0) {
+	    ArrayList ifaces = new ArrayList();
+	    for (int i = index; i <= file.InterfaceImpl.rows; i++) {
+		file.InterfaceImpl.readRow(i);
+		if (file.InterfaceImpl.Class != definingRow)
+		    break;
+		ifaces.add(((PEModule)Module)
+			   .getTypeDefOrRef(file.InterfaceImpl.Interface));
+	    }
+	    interfaces = (Type[]) ifaces.toArray(new Type[ifaces.size()]);
+	}
+    }
+
+    protected void loadCustomAttributes(Type attributeType) {
+	initAttributes(this, definingRow, Table.TypeDef.ID, attributeType);
+    }
+
+    private void initAttributes(CustomAttributeProvider cap, int definingRow,
+                                 int sourceTableId, Type attributeType)
+    {
+        ((PEModule)this.Module).initAttributes
+            (cap, definingRow, sourceTableId, attributeType);
+    }
+
+    //##########################################################################
+
+    private class PEFieldInfo extends FieldInfo {
+	private final int definingRow;
+	public PEFieldInfo(int definingRow, String name,
+                           int attrs, Type fieldType, Object value)
+	{
+	    super(name, PEType.this, attrs, fieldType, value);
+	    this.definingRow = definingRow;
+	}
+	protected void loadCustomAttributes(Type attributeType) {
+	    PEType.this.initAttributes
+                (this, definingRow, Table.FieldDef.ID, attributeType);
+	}
+    }
+
+    private class PEMethodInfo extends MethodInfo {
+	private final int definingRow;
+	public PEMethodInfo(int row, String name,
+                            int attrs, Type retType, ParameterInfo[] params)
+	{
+	    super(name, PEType.this, attrs, retType, params);
+	    this.definingRow = row;
+	}
+	protected void loadCustomAttributes(Type attributeType) {
+	    PEType.this.initAttributes
+                (this, definingRow, Table.MethodDef.ID, attributeType);
+	}
+    }
+
+    private class PEConstructorInfo extends ConstructorInfo {
+	private final int definingRow;
+	public PEConstructorInfo(int row, int attrs, ParameterInfo[] params) {
+	    super(PEType.this, attrs, params);
+	    this.definingRow = row;
+	}
+	protected void loadCustomAttributes(Type attributeType) {
+	    PEType.this.initAttributes
+                (this, definingRow, Table.MethodDef.ID, attributeType);
+	}
+    }
+
+    private class PEPropertyInfo extends PropertyInfo {
+	private final int definingRow;
+	public PEPropertyInfo(int row, String name, short attrs, Type propType,
+                              MethodInfo getter, MethodInfo setter)
+	{
+	    super(name, PEType.this, attrs, propType, getter, setter);
+	    this.definingRow = row;
+	}
+	protected void loadCustomAttributes(Type attributeType) {
+	    PEType.this.initAttributes
+                (this, definingRow, Table.PropertyDef.ID, attributeType);
+	}
+    }
+
+    private class PEEventInfo extends EventInfo {
+        private final int definingRow;
+        public PEEventInfo(int row, String name, short attrs, Type handler,
+                           MethodInfo add, MethodInfo remove)
+        {
+            super(name, PEType.this, attrs, handler, add, remove);
+            this.definingRow = row;
+        }
+        protected void loadCustomAttributes(Type attributeType) {
+            PEType.this.initAttributes
+                (this, definingRow, Table.EventDef.ID, attributeType);
+        }
+    }
+
+    //##########################################################################
+
+}  // class PEType
diff --git a/src/msil/ch/epfl/lamp/compiler/msil/ParameterAttributes.java b/src/msil/ch/epfl/lamp/compiler/msil/ParameterAttributes.java
new file mode 100644
index 0000000..d436036
--- /dev/null
+++ b/src/msil/ch/epfl/lamp/compiler/msil/ParameterAttributes.java
@@ -0,0 +1,72 @@
+/*
+ * System.Reflection-like API for access to .NET assemblies (DLL & EXE)
+ */
+
+
+package ch.epfl.lamp.compiler.msil;
+
+/**
+ * Defines the attributes that may be associated with a parameter.
+ *
+ * @author Nikolay Mihaylov
+ * @version 1.0
+ */
+public final class ParameterAttributes {
+
+    // just to make the class uninstantiable
+    private ParameterAttributes() {}
+
+    //##########################################################################
+
+    /** Specifies that there is no parameter attribute. */
+    public static final short None = 0x0000;
+
+    /** Specifies that the parameter is an input parameter. */
+    public static final short In = 0x0001;
+
+    /** Specifies that the parameter is an output parameter. */
+    public static final short Out = 0x0002;
+
+    /** Specifies that the parameter is a locale identifier. */
+    public static final short Lcid = 0x0004;
+
+    /** Specifies that the parameter is a return value. */
+    public static final short Retval = 0x0008;
+
+    /** Specifies that the parameter is optional.
+     *  Attention: In the specification the value is 0x0004 but
+     *  in mscorlib.dll that it Lcid and Optional is 0x0010
+     */
+    public static final short Optional = 0x0010;
+
+    /** Specifies that the parameter has a default value. */
+    public static final short HasDefault = 0x1000;
+
+    /** Specifies that the parameter has field marshaling information. */
+    public static final short HasFieldMarshal = 0x2000;
+
+    /** Reserved. */
+    public static final short Reserved3 = 0x4000;
+
+    /** Reserved. */
+    public static final short Reserved4 = (short)0x8000;
+
+    /** Specifies that the parameter is reserved. */
+    public static final short ReservedMask = (short)0xf000;
+
+    /** Reserved: shall be zero in all conforming implementations. */
+    public static final short Unused = (short) 0xcfe0;
+
+    public static final String toString(int attrs) {
+	StringBuffer s = new StringBuffer();
+	if ((attrs & In) != 0) s.append("in ");
+	if ((attrs & Out) != 0) s.append("out ");
+	if ((attrs & Optional) != 0) s.append("opt ");
+	if ((attrs & HasDefault) != 0) s.append("default(???) ");
+	if ((attrs & HasFieldMarshal) != 0) s.append("marshal(???) ");
+	return s.toString();
+    }
+
+    //##########################################################################
+
+}  // class ParameterAttributes
diff --git a/src/msil/ch/epfl/lamp/compiler/msil/ParameterInfo.java b/src/msil/ch/epfl/lamp/compiler/msil/ParameterInfo.java
new file mode 100644
index 0000000..877d7aa
--- /dev/null
+++ b/src/msil/ch/epfl/lamp/compiler/msil/ParameterInfo.java
@@ -0,0 +1,76 @@
+/*
+ * System.Reflection-like API for access to .NET assemblies (DLL & EXE)
+ */
+
+
+package ch.epfl.lamp.compiler.msil;
+
+/**
+ * Discovers the attributes of a parameter and provides access to
+ * parameter metadata.
+ *
+ * @author Nikolay Mihaylov
+ * @version 1.0
+ */
+public class ParameterInfo extends CustomAttributeProvider {
+
+    //##########################################################################
+
+    /** Attributes of the parameter. */
+    public final short Attributes;
+
+    /** Name of the parameter. */
+    public final String Name;
+
+    /** Type of the parameter. */
+    public final Type ParameterType;
+
+    /** Position of the parameter in the parameter list. */
+    public final int Position;
+
+    //##########################################################################
+
+    /** Is this an input parameter? */
+    public final boolean IsIn() {
+        return (Attributes & ParameterAttributes.In) != 0;
+    }
+
+    /** Is this an output parameter? */
+    public final boolean IsOut() {
+        return (Attributes & ParameterAttributes.Out) != 0;
+    }
+
+    /** Is this an Lcid? */
+    public final boolean IsLcid() {
+        return (Attributes & ParameterAttributes.Lcid) != 0;
+    }
+
+    /** Is this a return value? */
+    public final boolean IsRetval() {
+        return (Attributes & ParameterAttributes.Retval) != 0;
+    }
+
+    /** Is this an optional parameter? */
+    public final boolean IsOptional() {
+        return (Attributes & ParameterAttributes.Optional) != 0;
+    }
+
+    //##########################################################################
+    // members not part of the public Reflection.ParameterInfo interface
+
+    /** Initializes a new instance of the ParameterInfo class. */
+    protected ParameterInfo(String name, Type type, int attr, int pos) {
+	Name = name;
+	ParameterType = type;
+	Attributes = (short)attr;
+	Position = pos;
+    }
+
+    public String toString() {
+        return ParameterAttributes.toString(Attributes) + ParameterType + " "
+            + Name;
+    }
+
+    //##########################################################################
+
+}  // class ParameterInfo
diff --git a/src/msil/ch/epfl/lamp/compiler/msil/PropertyAttributes.java b/src/msil/ch/epfl/lamp/compiler/msil/PropertyAttributes.java
new file mode 100644
index 0000000..b1bec64
--- /dev/null
+++ b/src/msil/ch/epfl/lamp/compiler/msil/PropertyAttributes.java
@@ -0,0 +1,45 @@
+/*
+ * System.Reflection-like API for access to .NET assemblies (DLL & EXE)
+ */
+
+
+package ch.epfl.lamp.compiler.msil;
+
+/**
+ * Attributes applcicable to properties
+ *
+ * @author Nikolay Mihaylov
+ * @version 1.0
+ */
+public final class PropertyAttributes {
+
+    // makes the class uninstantiable
+    private PropertyAttributes() {}
+
+    //##########################################################################
+
+    /** Specifies that the property is special, with the name describing
+     *  how the property is special.
+     */
+    public static final short SpecialName = 0x0200;
+
+    /** Specifies that the metadata internal APIs check the name encoding.
+     */
+    public static final short RTSpecialName = 0x0400;
+
+    /** Specifies that the property has a default value.
+     */
+    public static final short HasDefault = 0x1000;
+
+    //##########################################################################
+
+    public static String toString(short attrs) {
+	StringBuffer str = new StringBuffer();
+	if ((attrs & SpecialName) != 0) str.append("specialname ");
+	if ((attrs & RTSpecialName) != 0) str.append("rtspecialname ");
+	return str.toString();
+    }
+
+    //##########################################################################
+
+} // class PropertyAttributes
diff --git a/src/msil/ch/epfl/lamp/compiler/msil/PropertyInfo.java b/src/msil/ch/epfl/lamp/compiler/msil/PropertyInfo.java
new file mode 100644
index 0000000..4b7cef8
--- /dev/null
+++ b/src/msil/ch/epfl/lamp/compiler/msil/PropertyInfo.java
@@ -0,0 +1,104 @@
+/*
+ * System.Reflection-like API for access to .NET assemblies (DLL & EXE)
+ */
+
+
+package ch.epfl.lamp.compiler.msil;
+
+/**
+ * Discovers the attributes of a property
+ * and provides access to property metadata.
+ *
+ * @author Nikolay Mihaylov
+ * @version 1.0
+ */
+public class PropertyInfo extends MemberInfo {
+
+    //##########################################################################
+
+    public final int MemberType() { return MemberTypes.Property; }
+
+    public final short Attributes;
+
+    public final boolean CanRead;
+
+    public final boolean CanWrite;
+
+    public final Type PropertyType;
+
+    /** Returns an array of the public get and set accessors for this property.
+     */
+    public MethodInfo[] GetAccessors() {
+	return GetAccessors(false);
+    }
+
+    /** Returns an array of the public or non-public <b>get</b>
+     *  and <b>set</b> accessors for this property.
+     */
+    public MethodInfo[] GetAccessors(boolean nonPublic) {
+	MethodInfo getter = GetGetMethod(nonPublic);
+	MethodInfo setter = GetSetMethod(nonPublic);
+	if (getter == null)
+	    if (setter == null) return MethodInfo.EMPTY_ARRAY;
+	    else return new MethodInfo[]{setter};
+	else if (setter == null) return new MethodInfo[] {getter};
+	else return new MethodInfo[] {getter, setter};
+    }
+
+    /** Returns the public <b>get</b> accessor for this property.
+     */
+    public MethodInfo GetGetMethod() {
+	return GetGetMethod(false);
+    }
+
+    /** Returns the public or non-public <b>get</b> accessor for this property.
+     */
+    public MethodInfo GetGetMethod(boolean nonPublic) {
+	return nonPublic ? getter
+	    : getter == null || getter.IsPublic() ? getter : null;
+    }
+
+    /** Returns the public <b>set</b> accessor for this property.
+     */
+    public MethodInfo GetSetMethod() {
+	return GetSetMethod(false);
+    }
+
+    /** Returns the public or non-public <b>set</b> accessor for this property.
+     */
+    public MethodInfo GetSetMethod(boolean nonPublic) {
+	return nonPublic ? setter
+	    : setter == null || setter.IsPublic() ? setter : null;
+    }
+
+    public String toString() {
+	MethodInfo m = getter != null ? getter : setter;
+	return MethodAttributes.accessFlagsToString
+	    ((getter != null ? getter : setter).Attributes)
+	    +  " " + PropertyAttributes.toString(Attributes)
+	    + DeclaringType + "::" + Name;
+    }
+
+    //##########################################################################
+    // protected members
+
+    protected static final PropertyInfo[] EMPTY_ARRAY = new PropertyInfo[0];
+
+    protected MethodInfo getter;
+    protected MethodInfo setter;
+
+    protected PropertyInfo(String name, Type declType, short attr,
+			   Type propType, MethodInfo getter, MethodInfo setter)
+    {
+	super(name, declType);
+	Attributes = attr;
+	PropertyType = propType;
+	this.getter = getter;
+	this.setter = setter;
+	CanRead = getter != null;
+	CanWrite = setter != null;
+    }
+
+    //##########################################################################
+
+} // class PropertyInfo
diff --git a/src/msil/ch/epfl/lamp/compiler/msil/Type.java b/src/msil/ch/epfl/lamp/compiler/msil/Type.java
new file mode 100644
index 0000000..f7d4498
--- /dev/null
+++ b/src/msil/ch/epfl/lamp/compiler/msil/Type.java
@@ -0,0 +1,1041 @@
+/*
+ * System.Reflection-like API for access to .NET assemblies (DLL & EXE)
+ */
+
+
+package ch.epfl.lamp.compiler.msil;
+
+import java.util.Map;
+import java.util.HashMap;
+import java.util.List;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.Arrays;
+
+/**
+ * Represents type declarations: class types, interface types, array types,
+ * value types, and enumeration types.
+ *
+ * @author Nikolay Mihaylov
+ * @version 1.0
+ */
+public abstract class Type extends MemberInfo {
+
+    //##########################################################################
+    // public static members
+
+    /** Empty array of type Type. */
+    public static final Type[] EmptyTypes = new Type[0];
+
+    /** Separates names in the namespace of the Type. */
+    public static final char Delimiter = '.';
+
+    //##########################################################################
+    // public properties
+
+    /** The fully qualified name of the Type. */
+    public final String FullName;
+
+    /** The namespace of the Type. */
+    public final String Namespace;
+
+    /** The type from which the current Type directly inherits. */
+    public final Type BaseType() {
+        initBaseType();
+        return baseType;
+    }
+    protected Type baseType;
+
+    /** The attributes associated with the Type. */
+    public final int Attributes;
+
+    /** The sssembly that the type is declared in. */
+    public final Assembly Assembly() { return Module.Assembly; }
+
+    /** The module (the EXE/DLL) in which the current Type is defined. */
+    public final Module Module;
+
+    public final int MemberType() {
+        return DeclaringType == null
+            ? MemberTypes.TypeInfo : MemberTypes.NestedType;
+    }
+
+    //##########################################################################
+    // internal members
+
+    // Fields declared by this class
+    protected FieldInfo[] fields;
+
+    // Methods declared by this class
+    protected MethodInfo[] methods;
+
+    // Constructors of this class
+    protected ConstructorInfo[] constructors;
+
+    // Properties of the class
+    protected PropertyInfo[] properties;
+
+    // Events of the class
+    protected EventInfo[] events;
+
+    // Interfaces implemented by this class
+    protected Type[] interfaces;
+
+    // Nested types declared by this class
+    protected Type[] nestedTypes;
+
+    // holds the element type of array, pointer and byref types
+    private final Type elemType;
+
+    // the underlying type of an enumeration. null if the type is not enum.
+    protected Type underlyingType;
+
+    private int auxAttr;
+
+    //##########################################################################
+    // Map with all the types known so far and operations on it
+
+    private static final Map types = new HashMap();
+
+    protected static Type getType(String name) {
+	return (Type) types.get(name);
+    }
+
+    protected static Type addType(Type t) {
+	Type oldType = (Type) types.put(t.FullName, t);
+// 	if (oldType != null)
+// 	    throw new RuntimeException("The type: [" + t.Assembly + "]" + t
+// 				       + " replaces the type: [" +
+// 				       oldType.Assembly + "]" + oldType);
+ 	return t;
+    }
+
+    //##########################################################################
+
+    /** The main constructor. */
+    protected Type(Module module,
+		   int attr,
+		   String fullName,
+		   Type baseType,
+		   Type[] interfaces,
+		   Type declType,
+		   int auxAttr,
+		   Type elemType)
+    {
+	super(fullName.lastIndexOf(Delimiter) < 0 ? fullName :
+	      fullName.substring(fullName.lastIndexOf(Delimiter) + 1,
+				 fullName.length()),
+	      declType);
+
+	Module = module;
+	Attributes = attr;
+	this.baseType = baseType;
+	if (DeclaringType == null) {
+	    FullName = fullName;
+	    int i = FullName.lastIndexOf(Delimiter);
+	    Namespace = (i < 0) ? "" : FullName.substring(0,i);
+	} else {
+	    FullName = declType.FullName + "+" + fullName;
+	    Namespace = DeclaringType.Namespace;
+	}
+
+	this.interfaces = interfaces;
+	this.elemType = elemType;
+	this.auxAttr = auxAttr;
+    }
+
+    public final boolean IsAbstract() {
+	return (Attributes & TypeAttributes.Abstract) != 0;
+
+    }
+    public final boolean IsPublic() {
+	return (Attributes & TypeAttributes.VisibilityMask)
+	    == TypeAttributes.Public;
+    }
+
+    public final boolean IsNotPublic() {
+	return (Attributes & TypeAttributes.VisibilityMask)
+	    == TypeAttributes.NotPublic;
+    }
+
+    public final boolean IsNestedPublic() {
+	return (Attributes & TypeAttributes.VisibilityMask)
+	    == TypeAttributes.NestedPublic;
+    }
+
+    public final boolean IsNestedPrivate() {
+	return (Attributes & TypeAttributes.VisibilityMask)
+	    == TypeAttributes.NestedPrivate;
+    }
+
+    public final boolean IsNestedFamily() {
+	return (Attributes & TypeAttributes.VisibilityMask)
+	    == TypeAttributes.NestedFamily;
+    }
+
+    public final boolean IsNestedAssembly() {
+	return (Attributes & TypeAttributes.VisibilityMask)
+	    == TypeAttributes.NestedAssembly;
+    }
+
+    public final boolean IsNestedFamORAssem() {
+	return (Attributes & TypeAttributes.VisibilityMask)
+	    == TypeAttributes.NestedFamORAssem;
+    }
+
+    public final boolean IsNestedFamANDAssem() {
+	return (Attributes & TypeAttributes.VisibilityMask)
+	    == TypeAttributes.NestedFamANDAssem;
+    }
+
+    public final boolean IsSealed() {
+	return (Attributes & TypeAttributes.Sealed) != 0;
+    }
+
+    public final boolean IsSpecialName() {
+	return (Attributes & TypeAttributes.SpecialName) != 0;
+    }
+
+    public final boolean IsClass() {
+	return  (Attributes & TypeAttributes.ClassSemanticsMask)
+	    == TypeAttributes.Class;
+    }
+
+    public final boolean IsInterface(){
+	return  (Attributes & TypeAttributes.ClassSemanticsMask)
+	    == TypeAttributes.Interface;
+    }
+
+    public final boolean IsAutoLayout() {
+        return  (Attributes & TypeAttributes.LayoutMask)
+	    == TypeAttributes.AutoLayout;
+    }
+    public final boolean IsExplictitLayout() {
+        return  (Attributes & TypeAttributes.LayoutMask)
+	    == TypeAttributes.ExplicitLayout;
+    }
+    public final boolean IsLayoutSequential() {
+        return  (Attributes & TypeAttributes.LayoutMask)
+	    == TypeAttributes.SequentialLayout;
+    }
+
+    public final boolean IsImport() {
+	return (Attributes & TypeAttributes.Import) != 0;
+    }
+    public final boolean IsSerializable() {
+	return (Attributes & TypeAttributes.Serializable) != 0;
+    }
+
+    public final boolean IsAnsiClass() {
+	return (Attributes & TypeAttributes.StringFormatMask)
+	    == TypeAttributes.AnsiClass;
+    }
+
+    public final boolean IsUnicodeClass() {
+	return (Attributes & TypeAttributes.StringFormatMask)
+	    == TypeAttributes.UnicodeClass;
+    }
+    public final boolean IsAutoClass() {
+	return (Attributes & TypeAttributes.StringFormatMask)
+	    == TypeAttributes.AutoClass;
+    }
+
+    public final boolean IsArray() {
+	return (auxAttr & AuxAttr.Array) != 0;
+    }
+    public final boolean IsByRef() {
+	return (auxAttr & AuxAttr.ByRef) != 0;
+    }
+    public final boolean IsPointer() {
+	return (auxAttr & AuxAttr.Pointer) != 0;
+    }
+    public final boolean IsPrimitive() {
+	return (auxAttr & AuxAttr.Primitive) != 0;
+    }
+    public final boolean IsValueType() {
+	return BaseType() == VALUE_TYPE() || IsEnum();
+    }
+    public final boolean IsEnum() {
+	return BaseType() == ENUM();
+    }
+
+    public final boolean HasElementType() {
+	return IsArray() || IsPointer() || IsByRef();
+    }
+
+    //public final boolean IsCOMObject;
+    //public final boolean IsContextful;
+    //public final boolean IsMarshalByRef;
+
+    protected Type(Module module,
+		   int attr,
+		   String fullName,
+		   Type baseType,
+		   Type[] interfaces,
+		   Type declType,
+		   int auxAttr)
+    {
+	this(module, attr, fullName, baseType, interfaces,
+	     declType, auxAttr, null);
+    }
+
+    //##########################################################################
+
+    static final class PrimitiveType extends Type {
+	public PrimitiveType(Module module,
+			     int attributes,
+			     String fullName,
+			     Type baseType,
+			     Type[] interfaces,
+			     Type declType,
+			     int auxAttr,
+			     Type elemType)
+	{
+	    super(module, attributes, fullName,
+		  baseType, interfaces, declType, auxAttr, elemType);
+	}
+    }
+
+    protected static final class AuxAttr {
+	public static final int None      = 0x0000;
+	public static final int Array     = 0x0001;
+	public static final int ByRef     = 0x0002;
+	public static final int Pointer   = 0x0008;
+	public static final int Primitive = 0x0010;
+    }
+
+    /***/
+    public static Type mkArray(Type elemType, int rank) {
+	StringBuffer arrSig = new StringBuffer("[");
+ 	for (int i = 0; i < rank; i++) {
+ 	    if (i > 0) arrSig.append(',');
+ 	}
+	arrSig.append(']');
+	Type array = getType(elemType.FullName + arrSig);
+	if (array != null)
+	    return array;
+	array = new PrimitiveType(elemType.Module,
+				  TypeAttributes.Public
+				  | TypeAttributes.Sealed
+				  | TypeAttributes.Serializable,
+				  elemType.FullName + arrSig,
+				  ARRAY(), EmptyTypes, null,
+				  AuxAttr.Array, elemType);
+	return addType(array);
+    }
+
+    /***/
+    public static Type mkPtr(Type elemType) {
+	String name = elemType.FullName + "*";
+	Type type = getType(name);
+	if (type != null) return type;
+	type = new PrimitiveType(elemType.Module,
+				 TypeAttributes.NotPublic,
+				 name, null, EmptyTypes, null,
+				 AuxAttr.Pointer, elemType);
+	return addType(type);
+    }
+
+    //##########################################################################
+    // public methods
+
+    /**
+     * Return the type with the specified signature parameters.
+     * For example, the fully qualified name for a class might look like this:
+     * TopNamespace.SubNameSpace.ContainingClass+NestedClass,MyAssembly
+     */
+    public static Type GetType(String fullName) {
+	Type type = getType(fullName);
+	if (type != null) return type;
+
+	// check if it's an array type; TODO: make array type handling more robust
+	int i = fullName.lastIndexOf('[');
+	int j = fullName.lastIndexOf(']');
+	if (i >= 0)
+	    if (j > i && j == (fullName.length() - 1)) {
+		String elementTypeName = fullName.substring(0, i);
+		Type elementType = GetType(elementTypeName);
+		if (elementType == null)
+		    throw new RuntimeException
+			("Unknown element type '" + elementTypeName +
+			 "' for the array type: " + fullName);
+		int rank = j - i;
+		for (int k = i + 1; k < j; k++) {
+		    if (fullName.charAt(k) != ',')
+			throw new RuntimeException
+			    ("Malformed type name: " + fullName);
+		}
+		return mkArray(elementType, rank);
+	    } else
+		throw new RuntimeException("Malformed type name: " + fullName);
+
+	// check if it's a pointer type
+	if (fullName.charAt(fullName.length() - 1) == '*')
+	    return addType
+		(mkPtr(GetType(fullName.substring(0, fullName.length()-1))));
+
+	// check if it's a nested class
+	i = fullName.lastIndexOf('+');
+	if (i > 0) {
+	    if (i == 0 || i == (fullName.length() - 1))
+		throw new RuntimeException("malformedTypeName");
+	    Type enclosing = GetType(fullName.substring(0, i));
+	    return enclosing == null ? null
+		: enclosing.GetNestedType(fullName.substring(i + 1));
+	}
+
+	//System.out.println("Looking for type: " + fullName + " (" + fullName.length() + ")");
+	// try in the assemblies
+	Iterator assems = ch.epfl.lamp.compiler.msil.Assembly.
+	    assemblies.values().iterator();
+	while (type == null && assems.hasNext()) {
+	    Assembly assem = ((Assembly) assems.next());
+	    type = assem.GetType(fullName);
+	    //System.out.println("\tin assemby " + assem + " -> " + type);
+	}
+
+	Type type2 = getType(fullName);
+	if (type == type2) return type;
+	return type == null ? null : addType(type);
+    }
+
+    /**
+     * @return the type of the object encompassed or referenced to
+     * by the current array, pointer or reference type.
+     */
+    public Type GetElementType() {
+	return elemType;
+    }
+
+    /**
+     * @return the type underlying an enumeration type.
+     */
+    public Type getUnderlyingType() {
+	if (!IsEnum()) return null;
+	// this would force the loading of the underlying type from the
+	// the type of the value__ field of the enumeration
+	initFields();
+	return underlyingType;
+    }
+
+    //##########################################################################
+    // GetField/s/
+
+    /** Searches for the field with the specified name. */
+    public FieldInfo GetField(String name) {
+	initFields();
+	for (int i = 0; i < fields.length; i++)
+	    if (fields[i].Name.equals(name) && !fields[i].IsPrivate())
+		return fields[i];
+	return null;
+    }
+
+    /**
+     */
+    public FieldInfo GetField(String name, int bindingFlags) {
+	FieldInfo[] fields = this.GetFields(bindingFlags);
+	for (int i = 0; i < fields.length; i++)
+	    if (name.equals(fields[i].Name))
+		return fields[i];
+	return null;
+    }
+
+    /** Gets the fields of the current Type. */
+    public FieldInfo[] GetFields() {
+	return GetFields(BindingFlags.Instance | BindingFlags.Public);
+    }
+
+    /**
+     */
+    public FieldInfo[] GetFields(int bindingFlags) {
+ 	initFields();
+	final FieldInfo[] fields =
+	    getAllFields((bindingFlags & BindingFlags.DeclaredOnly) != 0);
+	final boolean getInstance = (bindingFlags & BindingFlags.Instance) != 0;
+	final boolean getStatic = (bindingFlags & BindingFlags.Static) != 0;
+	final boolean getPublic = (bindingFlags & BindingFlags.Public) != 0;
+	final boolean getNonPublic =
+	    (bindingFlags & BindingFlags.NonPublic) != 0;
+
+	int cnt = 0;
+	for (int i = 0; i < fields.length; i++) {
+	    FieldInfo field = fields[i];
+	    boolean accessible = (getPublic && field.IsPublic())
+		|| (getNonPublic && !field.IsPublic());
+	    if (accessible
+		// strip off the private fields up the hierarchy
+		&& ((field.DeclaringType == this)
+		    || ((field.DeclaringType != this) && !field.IsPrivate()))
+		&& ((getInstance && !field.IsStatic())
+		    || ((getStatic && field.IsStatic()) &&
+			(field.DeclaringType == this
+			 || (bindingFlags & BindingFlags.FlattenHierarchy) != 0))
+		    )
+		)
+		fields[cnt++] = field;
+	}
+	FieldInfo [] resFields = new FieldInfo[cnt];
+	System.arraycopy(fields, 0, resFields, 0, cnt);
+	return resFields;
+    }
+
+    protected FieldInfo[] getAllFields(boolean declaredOnly) {
+	initFields();
+	FieldInfo [] inherited = BaseType() == null || declaredOnly
+	    ? FieldInfo.EMPTY_ARRAY
+	    : BaseType().getAllFields(declaredOnly);
+	FieldInfo[] allFields =
+	    new FieldInfo[inherited.length + this.fields.length];
+	System.arraycopy(inherited, 0, allFields, 0, inherited.length);
+	System.arraycopy(this.fields, 0,
+			 allFields, inherited.length, this.fields.length);
+	return allFields;
+    }
+
+    //##########################################################################
+    // GetConstructor/s/
+
+    /** Searches for a public instance constructor whose parameters
+     *  match the types in the specified array. */
+    public ConstructorInfo GetConstructor(Type[] paramTypes) {
+	initMethods();
+	for (int i = 0; i < constructors.length; i++) {
+	    if (equalParameters(constructors[i].GetParameters(), paramTypes))
+		return constructors[i];
+	}
+	return null;
+    }
+
+    /** Returns all public instance constructors defined for the current Type.*/
+    public ConstructorInfo[] GetConstructors() {
+	return GetConstructors(BindingFlags.Instance | BindingFlags.Public);
+    }
+
+    /***/
+    public ConstructorInfo[] GetConstructors(int bindingFlags) {
+	initMethods();
+	final boolean getInstance = (bindingFlags & BindingFlags.Instance) != 0;
+	final boolean getStatic = (bindingFlags & BindingFlags.Static) != 0;
+	final boolean getPublic = (bindingFlags & BindingFlags.Public) != 0;
+	final boolean getNonPublic =
+	    (bindingFlags & BindingFlags.NonPublic) != 0;
+
+	ConstructorInfo[] constrs =
+	    new ConstructorInfo[this.constructors.length];
+	int cnt = 0;
+	for (int i = 0; i < this.constructors.length; i++) {
+	    ConstructorInfo constr = this.constructors[i];
+	    boolean accessible = (getPublic && constr.IsPublic())
+		|| (getNonPublic && !constr.IsPublic());
+	    if (accessible
+		&& ((getInstance && !constr.IsStatic())
+		    || (getStatic && constr.IsStatic())))
+		constrs[cnt++] = constr;
+	}
+	ConstructorInfo [] resConstrs = new ConstructorInfo[cnt];
+	System.arraycopy(constrs, 0, resConstrs, 0, cnt);
+	return resConstrs;
+    }
+
+    //##########################################################################
+    // GetMethod/s/
+
+    /** Searches for the specified public method whose parameters
+     *  match the specified argument types. */
+    public MethodInfo GetMethod(String name, Type[] paramTypes) {
+        return GetMethod(name, paramTypes, null);
+    }
+
+    public MethodInfo GetMethod(String name, Type[] paramTypes, Type retType) {
+	initMethods();
+	MethodInfo method = findMethod(methods, name, paramTypes, retType);
+	if (method != null)
+	    return method;
+	if (BaseType() != null) {
+	    method = BaseType().GetMethod(name, paramTypes, retType);
+	    if (method != null)
+		return method;
+	}
+// 	StringBuffer str = new StringBuffer(name);
+// 	str.append('(');
+// 	for (int i = 0; i < paramTypes.length; i++) {
+// 	    if (i > 0) str.append(", ");
+// 	    str.append(paramTypes[i]);
+// 	}
+// 	str.append(')');
+// 	System.out.println("Cannot find method " + str + ":");
+// 	System.out.println("Methods of class " + this);
+// 	for (int i = 0; i < methods.length; i++)
+// 	    System.out.println("\t" + methods[i]);
+	return null;
+    }
+
+    /**
+     */
+    protected static MethodInfo findMethod(MethodInfo[] methods,
+					   String name,
+					   Type[] paramTypes,
+                                           Type retType)
+    {
+	for (int i = 0; i < methods.length; i++)
+	    if (name.equals(methods[i].Name)
+		&& equalParameters(methods[i].GetParameters(), paramTypes)
+                && (retType == null || methods[i].ReturnType == retType))
+		return methods[i];
+	return null;
+    }
+
+    /**
+     */
+    protected static boolean equalParameters(ParameterInfo[] params,
+					    Type[] paramTypes)
+    {
+	if (params.length != paramTypes.length)
+	    return false;
+	for (int i = 0; i < params.length; i++) {
+// 	    System.out.println(params[i].ParameterType + " == " + paramTypes[i]
+// 			       + " = " + (params[i].ParameterType == paramTypes[i]));
+	    if (params[i].ParameterType != paramTypes[i])
+		return false;
+	}
+	return true;
+    }
+
+    /**
+     */
+    public MethodInfo GetMethod(String name, Type[] paramTypes, int bindingFlags) {
+	MethodInfo[] methods = GetMethods(bindingFlags);
+	MethodInfo method =  findMethod(methods, name, paramTypes, null);
+	if (method == null) {
+	    StringBuffer str = new StringBuffer(name);
+	    str.append('(');
+	    for (int i = 0; i < paramTypes.length; i++) {
+		if (i > 0) str.append(", ");
+		str.append(paramTypes[i]);
+	    }
+	    str.append(')');
+	    System.out.println("Cannot find method " + str + ":");
+	    System.out.println("Methods of class " + this);
+	    for (int i = 0; i < methods.length; i++)
+		System.out.println("\t" + methods[i]);
+	}
+	return method;
+    }
+
+    /** Returns all public methods of the current Type. */
+    public MethodInfo[] GetMethods() {
+	return GetMethods(BindingFlags.Instance | BindingFlags.Public);
+    }
+
+    /**
+     */
+    public MethodInfo[] GetMethods(int bindingFlags) {
+	initMethods();
+	final MethodInfo[] methods =
+	    getAllMethods((bindingFlags & BindingFlags.DeclaredOnly) != 0);
+	//System.out.println("" + this + ".GetMethods(int) -> " + methods.length);
+	final boolean getInstance = (bindingFlags & BindingFlags.Instance) != 0;
+	final boolean getStatic = (bindingFlags & BindingFlags.Static) != 0;
+	final boolean getPublic = (bindingFlags & BindingFlags.Public) != 0;
+	final boolean getNonPublic =
+	    (bindingFlags & BindingFlags.NonPublic) != 0;
+
+	int cnt = 0;
+	for (int i = 0; i < methods.length; i++) {
+	    MethodInfo method = methods[i];
+	    boolean accessible = (getPublic && method.IsPublic())
+		|| (getNonPublic && !method.IsPublic());
+	    if (accessible
+		// strip off the private methods up the hierarchy
+		&& ((method.DeclaringType == this)
+		    || ((method.DeclaringType != this) && !method.IsPrivate()))
+		&& ((getInstance && !method.IsStatic())
+		    || ((getStatic && method.IsStatic()) &&
+			(method.DeclaringType == this
+			 || (bindingFlags & BindingFlags.FlattenHierarchy) != 0))
+		    )
+		)
+		methods[cnt++] = method;
+	}
+	MethodInfo [] resMethods = new MethodInfo[cnt];
+	System.arraycopy(methods, 0, resMethods, 0, cnt);
+	return resMethods;
+    }
+
+    protected MethodInfo[] getAllMethods(boolean declaredOnly) {
+	initMethods();
+	MethodInfo[] inherited = BaseType() == null || declaredOnly
+	    ? MethodInfo.EMPTY_ARRAY
+	    : BaseType().getAllMethods(declaredOnly);
+	MethodInfo[] allMethods =
+	    new MethodInfo[inherited.length + this.methods.length];
+	System.arraycopy(inherited, 0, allMethods, 0, inherited.length);
+	System.arraycopy(this.methods, 0,
+			 allMethods, inherited.length, this.methods.length);
+	return allMethods;
+    }
+
+    //##########################################################################
+    // GetProperty/ies/
+
+    /** Returns all public properties of the current Type.
+     */
+    public PropertyInfo[] GetProperties() {
+	initProperties();
+	return (PropertyInfo[]) properties.clone();
+    }
+
+    /** Returns the properties of the current class
+     *  that satisfy the binding constrints.
+     */
+    public PropertyInfo[] GetProperties(int bindingFlags) {
+	initProperties();
+	return (PropertyInfo[]) properties.clone();
+    }
+
+    /** Returns the public property with the given name.
+     */
+    public PropertyInfo GetProperty(String name) {
+	initProperties();
+	for (int i = 0; i < properties.length; i++)
+	    if (name.equals(properties[i].Name))
+		return properties[i];
+	return null;
+    }
+
+    /** Returns the property with the given name
+     *  that satisfies the binding constraints.
+     */
+    public PropertyInfo GetProperty(String name, int bindingFlags) {
+	throw new RuntimeException("Method not implemented yet");
+    }
+
+    //##########################################################################
+    // GetEvent(s)
+
+    public EventInfo[] GetEvents() {
+        initEvents();
+        return (EventInfo[]) events.clone();
+    }
+
+    //##########################################################################
+    // GetNestedType/s/
+
+    /** Searches for nested type with the specified name. */
+    public Type GetNestedType(String name) {
+	initNestedTypes();
+	for (int i = 0; i < nestedTypes.length; i++)
+	    if (nestedTypes[i].Name.equals(name))
+		return nestedTypes[i];
+	return null;
+    }
+
+    /** Returns all types nested within the current Type. */
+    public Type[] GetNestedTypes() {
+	initNestedTypes();
+	return (Type[]) nestedTypes.clone();
+    }
+
+    //##########################################################################
+    // GetInterface/s/
+
+    /** Searches for an Interface with the given name implemented by this type
+     */
+    public Type GetInterface(String name) {
+	return GetInterface(name, false);
+    }
+
+    /** Searches for the specified interface,
+     * specifying whether to do a case-sensitive search.
+     * @param name - the name of the interface to get
+     * @param ignoreCase <b>true</b> to perform a case-insensitive search for name
+     *                   <b>false</b> to perform a case-sensitive search for name
+     * @return A Type object representing the interface with the specified name,
+     *         implemented or inherited by the current Type, if found;
+     *         otherwise, a null reference
+     */
+    public Type GetInterface(String name, boolean ignoreCase) {
+	initInterfaces();
+	for (int i = 0; i < interfaces.length; i++) {
+	    Type iface = interfaces[i];
+	    if (ignoreCase) {
+		if (name.equalsIgnoreCase(iface.Name)) return iface;
+		if (name.equalsIgnoreCase(iface.FullName)) return iface;
+	    } else {
+		if (name.equals(iface.Name)) return iface;
+		if (name.equals(iface.FullName)) return iface;
+	    }
+	}
+	return BaseType() == null ? null
+	    : BaseType().GetInterface(name, ignoreCase);
+    }
+
+    /** Returns the interfaces implemented or inherited by the current Type. */
+    public Type[] GetInterfaces() {
+	initInterfaces();
+	if (BaseType() == null) return interfaces;
+
+	Type[] ifaces = interfaces;
+	int count = 0;
+	for (int i = 0; i < interfaces.length; i++) {
+	    if (BaseType().GetInterface(interfaces[i].FullName) == null)
+		ifaces[count++] = ifaces[i];
+	}
+	Type[] baseTypeIfaces = BaseType().GetInterfaces();
+
+	Type[] res = new Type[baseTypeIfaces.length + count];
+	System.arraycopy(baseTypeIfaces, 0, res, 0, baseTypeIfaces.length);
+	System.arraycopy(ifaces, 0, res, baseTypeIfaces.length, count);
+
+	return res;
+    }
+
+
+    public boolean isSubtypeOf(Type that) {
+	if (this == that || BaseType() == that || that == OBJECT()) return true;
+	initInterfaces();
+	for (int i = 0; i < interfaces.length; i++)
+	    if (interfaces[i].isSubtypeOf(that))
+		return true;
+	boolean res = BaseType() == null ? false : BaseType().isSubtypeOf(that);
+// 	if (!res) {
+// 	    System.out.println(dumpType(this) + " not a subtype of " +
+// 			       dumpType(that));
+// 	}
+	return res;
+    }
+
+    private static String formatType(Type t) {
+	if (t == null) return "<null>";
+	String cname = t.getClass().getName();
+	int k = cname.lastIndexOf(".");
+	if (k >= 0)
+	    cname = cname.substring(k + 1);
+	return  "[" + t.Assembly().GetName() + "]" + t +
+	    "(" + cname + "#" + Integer.toHexString(t.hashCode()) + ")";
+    }
+    private static String dumpType(Type t) {
+	StringBuffer str = new StringBuffer();
+	str.append(formatType(t) + " : ");
+	str.append(formatType(t.BaseType()));
+	Type[] ifaces = t.GetInterfaces();
+	for (int i = 0; i < ifaces.length; i++)
+	    str.append(", " + formatType(ifaces[i]));
+	return str.toString();
+    }
+
+    //##########################################################################
+    // GetMember/s/
+
+    protected MemberInfo[] members;
+
+    public MemberInfo[] GetMember(String name) {
+	aggregateMembers();
+	List l = new ArrayList();
+	for (int i = 0; i < members.length; i++) {
+	    if (name.equals(members[i].Name))
+		l.add(members[i]);
+	}
+	return (MemberInfo[])l.toArray(MemberInfo.EMPTY_ARRAY);
+    }
+
+    protected void aggregateMembers() {
+	if (members != null)
+	    return;
+	initFields();
+	initMethods();
+	initProperties();
+	initNestedTypes();
+	// the List returned by Arrays.asList doesn't support the addAll method
+	// so we have to wrap it in ArrayList
+	List l = new ArrayList(Arrays.asList(fields));
+	l.addAll(Arrays.asList(constructors));
+	l.addAll(Arrays.asList(methods));
+	l.addAll(Arrays.asList(properties));
+	l.addAll(Arrays.asList(nestedTypes));
+	members = (MemberInfo[]) l.toArray(MemberInfo.EMPTY_ARRAY);
+    }
+
+    //##########################################################################
+    // non-standard methods that return only members declared in this type
+
+    /**
+     * Return only the fields declared in this type.
+     */
+    public FieldInfo[] getFields() {
+	initFields();
+	FieldInfo[] fields = new FieldInfo[this.fields.length];
+	System.arraycopy(this.fields, 0, fields, 0, fields.length);
+	return fields;
+    }
+
+    /**
+     * Return only the conrtuctors declared in this type.
+     */
+    public ConstructorInfo[] getConstructors() {
+	initMethods();
+	ConstructorInfo[] ctors = new ConstructorInfo[constructors.length];
+	System.arraycopy(constructors, 0, ctors, 0, ctors.length);
+	return ctors;
+    }
+
+    /**
+     * Return only the methods declared in this type.
+     */
+    public MethodInfo[] getMethods() {
+	initMethods();
+	MethodInfo[] methods = new MethodInfo[this.methods.length];
+	System.arraycopy(this.methods, 0, methods, 0, methods.length);
+	return methods;
+    }
+
+    /**
+     * Return only the properties declared in this type.
+     */
+    public PropertyInfo[] getProperties() {
+	initProperties();
+	PropertyInfo[] props = new PropertyInfo[properties.length];
+	System.arraycopy(properties, 0, props, 0, props.length);
+	return props;
+    }
+
+    /**
+     * Return only the interfaces directly implemented by this type.
+     */
+    public Type[] getInterfaces() {
+	initInterfaces();
+	Type[] ifaces = new Type[interfaces.length];
+	System.arraycopy(interfaces, 0, ifaces, 0, ifaces.length);
+	return ifaces;
+    }
+
+    /**
+     * Return the types declared in this type.
+     */
+    public Type[] getNestedTypes() {
+	initNestedTypes();
+	Type[] nested = new Type[nestedTypes.length];
+	System.arraycopy(nestedTypes, 0, nested, 0, nested.length);
+	return nested;
+    }
+
+    //##########################################################################
+
+    public String toString() {
+	return FullName;
+    }
+
+    //##########################################################################
+    // lazy type construction members
+
+    private boolean initBaseType = true;
+    protected final void initBaseType() {
+        if (initBaseType) {
+            loadBaseType();
+            initBaseType = false;
+        }
+    }
+    protected void loadBaseType() {}
+
+    private boolean initInterfaces = true;
+    protected void initInterfaces() {
+	if (initInterfaces) {
+	    loadInterfaces();
+	    initInterfaces = false;
+	}
+	assert interfaces != null : "In type " + this;
+    }
+    protected void loadInterfaces() {}
+
+    private boolean initNestedTypes = true;
+    protected void initNestedTypes() {
+	if (initNestedTypes) {
+	    loadNestedTypes();
+	    initNestedTypes = false;
+	}
+	assert nestedTypes != null : "In type " + this;
+    }
+    protected void loadNestedTypes() {}
+
+    private boolean initFields = true;
+    protected void initFields() {
+	if (initFields) {
+	    loadFields();
+	    initFields = false;
+	}
+	assert fields != null : "In type " + this;
+    }
+    protected void loadFields() {}
+
+    private boolean initMethods = true;
+    protected void initMethods() {
+	if (initMethods) {
+	    loadMethods();
+	    initMethods = false;
+	}
+	assert constructors != null : "In type " + this;
+	assert methods != null : "In type " + this;
+    }
+    protected void loadMethods() {}
+
+    private boolean initProperties = true;
+    protected void initProperties() {
+	if (initProperties) {
+	    initMethods();
+	    loadProperties();
+	    initProperties = false;
+	}
+	assert properties != null : "In type " + this;
+    }
+    protected void loadProperties() {}
+
+    private boolean initEvents = true;
+    protected void initEvents() {
+	if (initEvents) {
+	    initMethods();
+	    loadEvents();
+	    initEvents = false;
+	}
+	assert events != null : "In type " + this;
+    }
+    protected void loadEvents() {}
+
+    //##########################################################################
+
+    //##########################################################################
+    // static members
+
+    private static Assembly MSCORLIB;
+    private static Module   MSCORLIB_DLL;
+
+    public static Type OBJECT() { return __OBJECT; }
+    public static Type STRING() { return __STRING; }
+    public static Type ARRAY() { return __ARRAY; }
+    public static Type VOID() { return __VOID; }
+    public static Type ENUM() { return __ENUM; }
+    public static Type VALUE_TYPE() { return __VALUE_TYPE; }
+
+    private static Type __OBJECT;
+    private static Type __STRING;
+    private static Type __ARRAY;
+    private static Type __VOID;
+    private static Type __ENUM;
+    private static Type __VALUE_TYPE;
+
+    public static void initMSCORLIB(Assembly mscorlib) {
+        if (MSCORLIB != null)
+            throw new RuntimeException("mscorlib already initialized");
+	MSCORLIB = mscorlib;
+	MSCORLIB_DLL = MSCORLIB.GetModules()[0];
+
+	__OBJECT = mscorlib.GetType("System.Object");
+	__STRING = mscorlib.GetType("System.String");
+	__ARRAY  = mscorlib.GetType("System.Array");
+	__VOID   = mscorlib.GetType("System.Void");
+	__ENUM   = mscorlib.GetType("System.Enum");
+	__VALUE_TYPE   = mscorlib.GetType("System.ValueType");
+    }
+
+    //##########################################################################
+
+}  // class Type
diff --git a/src/msil/ch/epfl/lamp/compiler/msil/TypeAttributes.java b/src/msil/ch/epfl/lamp/compiler/msil/TypeAttributes.java
new file mode 100644
index 0000000..8f489fa
--- /dev/null
+++ b/src/msil/ch/epfl/lamp/compiler/msil/TypeAttributes.java
@@ -0,0 +1,190 @@
+/*
+ * System.Reflection-like API for access to .NET assemblies (DLL & EXE)
+ */
+
+
+package ch.epfl.lamp.compiler.msil;
+
+/**
+ * Specifies type attributes.
+ *
+ * @author Nikolay Mihaylov
+ * @version 1.0
+ */
+public final class TypeAttributes {
+
+    //##########################################################################
+    // Visibilty attributes
+
+    /** Bitmask used to retrieve visibility information. */
+    public static final int VisibilityMask = 0x00000007;
+
+    /** Class has no public scope. */
+    public static final int NotPublic = 0x00000000;
+
+    /** Class has public scope. */
+    public static final int Public = 0x00000001;
+
+    /** Class is nested with public visibility. */
+    public static final int NestedPublic =  0x00000002;
+
+    /** Class is nested with private visibility. */
+    public static final int NestedPrivate = 0x00000003;
+
+    /** Class is nested with family visibility, and is thus accessible
+     *  only by methods within its own type and any subtypes. */
+    public static final int NestedFamily = 0x00000004;
+
+    /** Class is nested with assembly visibility, and is thus accessible
+     *  only by methods within its assembly. */
+    public static final int NestedAssembly = 0x00000005;
+
+    /** Class is nested with assembly and family visibility, and is thus accessible
+     *  only by methods lying in the intersection of its family and assembly. */
+    public static final int NestedFamANDAssem = 0x00000006;
+
+    /** Class is nested with family or assembly visibility, and is thus accessible
+     *  only by methods lying in the union of its family and assembly. */
+    public static final int NestedFamORAssem = 0x00000007;
+
+    //##########################################################################
+    // Class layout attributes
+
+    /** Bitmask used to retrieve class layout information. */
+    public static final int LayoutMask = 0x00000018;
+
+    /** Class fields are automatically laid out by the CLR. */
+    public static final int AutoLayout = 0x00000000;
+
+    /** Class fields are laid out sequentially, in the order that the fields
+     *  were emitted to the metadata. */
+    public static final int SequentialLayout = 0x00000008;
+
+    /** Class fields are laid out at the specified offsets. */
+    public static final int ExplicitLayout = 0x00000010;
+
+    //##########################################################################
+    // Class semantics attributes
+
+    /** Bitmask used to retrieve class semantics information. */
+    public static final int ClassSemanticsMask = 0x00000020;
+
+    /** Type is a class. */
+    public static final int Class = 0x00000000;
+
+    /** Type is an interface. */
+    public static final int Interface = 0x00000020;
+
+    //##########################################################################
+    // Special semantics in addition to class semantics
+
+    /** Class is abstract. */
+    public static final int Abstract = 0x00000080;
+
+    /** Class is cannot be extended. */
+    public static final int Sealed = 0x00000100;
+
+    /** Class is special in a way denoted by the name. */
+    public static final int SpecialName = 0x00000400;
+
+    //##########################################################################
+    // Implementation attributes
+
+    /** Class/interface is imported from another module. */
+    public static final int Import = 0x00001000;
+
+    /** Class can be serialized. */
+    public static final int Serializable = 0x00002000;
+
+    //##########################################################################
+    // String formatting attributes
+
+    /** Bitmask used to retrieve string information for native interop. */
+    public static final int StringFormatMask = 0x00030000;
+
+    /** LPTSTR is interpreted as ANSI. */
+    public static final int AnsiClass = 0x00000000;
+
+    /** LPTSTR is interpreted as UNICODE. */
+    public static final int UnicodeClass = 0x00010000;
+
+    /** LPTSTR is interpreted automatically. */
+    public static final int AutoClass = 0x00020000;
+
+    //##########################################################################
+    // Class initialization attributes
+
+    /** Initialize the class before first static field access. */
+    public static final int BeforeFieldInit = 0x00100000;
+
+    //##########################################################################
+    // Additional flags
+
+    /** CLI provides 'special' behavior, depending upon the name of the type. */
+    public static final int RTSpecialName = 0x00000800;
+
+    /** Type has security associate with it. */
+    public static final int HasSecurity = 0x00040000;
+
+    //##########################################################################
+
+    public static String accessModsToString(int attrs) {
+	switch (attrs & VisibilityMask) {
+	case NotPublic: return "private";
+	case Public: return "public";
+	case NestedPublic: return "nested public";
+	case NestedPrivate: return "nested private";
+	case NestedFamily: return "nested family";
+	case NestedAssembly: return "nested assembly";
+	case NestedFamANDAssem: return "nested famandassem";
+	case NestedFamORAssem: return "nested famorassem";
+	default:
+	    throw new RuntimeException();
+	}
+    }
+
+    /** Returns a string representation of the given attributes. */
+    public static String toString(int attrs) {
+	StringBuffer str = new StringBuffer(accessModsToString(attrs));
+	switch (attrs & LayoutMask) {
+	case AutoLayout: str.append(" auto"); break;
+	case SequentialLayout: str.append(" sequential"); break;
+	case ExplicitLayout: str.append(" explicit"); break;
+	}
+	switch (attrs & StringFormatMask) {
+	case AnsiClass: str.append(" ansi"); break;
+	case UnicodeClass: str.append(" unicode"); break;
+	case AutoClass: str.append(" autochar"); break;
+	}
+	if ((attrs & Interface) != 0) str.append(" interface");
+	if ((attrs & Abstract) != 0) str.append(" abstract");
+	if ((attrs & Sealed) != 0) str.append(" sealed");
+	if ((attrs & BeforeFieldInit) != 0) str.append(" beforefieldinit");
+	if ((attrs & Serializable) != 0) str.append(" serializable");
+	if ((attrs & SpecialName) != 0) str.append(" specialname");
+	if ((attrs & RTSpecialName) != 0) str.append(" rtspecialname");
+	return str.toString();
+    }
+
+    /***/
+    public static final boolean isNested(int attrs) {
+	switch (attrs & VisibilityMask) {
+	case NestedPublic:
+	case NestedPrivate:
+	case NestedFamily:
+	case NestedAssembly:
+	case NestedFamANDAssem:
+	case NestedFamORAssem:
+	    return true;
+	default: return false;
+	}
+    }
+
+    //##########################################################################
+
+    // makes the class uninstantiable
+    private TypeAttributes() {}
+
+    //##########################################################################
+
+}  // class TypeAttributes
diff --git a/src/msil/ch/epfl/lamp/compiler/msil/Version.java b/src/msil/ch/epfl/lamp/compiler/msil/Version.java
new file mode 100644
index 0000000..ad4b09b
--- /dev/null
+++ b/src/msil/ch/epfl/lamp/compiler/msil/Version.java
@@ -0,0 +1,71 @@
+/*
+ * System.Reflection-like API for access to .NET assemblies (DLL & EXE)
+ */
+
+
+package ch.epfl.lamp.compiler.msil;
+
+
+/**
+ * Represents the version number for a common language runtime assembly
+ *
+ * @author Nikolay Mihaylov
+ * @version 1.0
+ */
+public final class Version {
+
+    //##########################################################################
+    // public interface
+
+    /**
+     * Gets the value of the major component of the version
+     * number for this instance.
+     */
+    public final int  Major;
+
+    /**
+     * Gets the value of the minor component of the version
+     * number for this instance.
+     */
+    public final int Minor;
+
+    /**
+     * Gets the value of the build component of the version
+     * number for this instance.
+     */
+    public final int Build;
+
+    /**
+     * Gets the value of the revision component of the version
+     * number for this instance.
+     */
+    public final int Revision;
+
+    /**
+     * Initializes a new instance of the Version class.
+     */
+    public Version() {
+	this(0,0,0,0);
+    }
+
+    /**
+     * Initializes a new instance of the Version class with
+     * the specified major, minor, build, and revision numbers.
+     */
+    public Version(int major, int minor, int build, int revision) {
+	this.Major = major;
+	this.Minor = minor;
+	this.Build = build;
+	this.Revision = revision;
+    }
+
+    /**
+     * Converts the value of this instance to its equivalent String representation
+     */
+    public String toString() {
+	return "" + Major + "." + Minor + "." + Build + "." +  Revision;
+    }
+
+    //##########################################################################
+
+} // class Version
diff --git a/src/msil/ch/epfl/lamp/compiler/msil/emit/AssemblyBuilder.scala b/src/msil/ch/epfl/lamp/compiler/msil/emit/AssemblyBuilder.scala
new file mode 100644
index 0000000..2c4011e
--- /dev/null
+++ b/src/msil/ch/epfl/lamp/compiler/msil/emit/AssemblyBuilder.scala
@@ -0,0 +1,124 @@
+/*
+ * System.Reflection.Emit-like API for writing .NET assemblies to MSIL
+ */
+
+
+package ch.epfl.lamp.compiler.msil.emit
+
+import ch.epfl.lamp.compiler.msil._
+import java.util.HashMap
+import java.util.HashSet
+import java.util.ArrayList
+import java.io.IOException
+
+/**
+ * Defines and represents a dynamic assembly.
+ * A dynamic assembly is an assembly that is created using the compiler.msil
+ * emit APIs. The dynamic modules in the assembly are saved when the dynamic
+ * assembly is saved using the Save method. To generate an executable, the
+ * SetEntryPoint method must be called to identify the method that is the
+ * entry point to the assembly. Assemblies are saved as DLL by default,
+ * unless SetEntryPoint requests the generation of a console application
+ * or a Windows-based application.
+ *
+ * @author Nikolay Mihaylov
+ * @version 1.0
+ */
+class AssemblyBuilder(name: AssemblyName)
+      extends Assembly(name)
+      with ICustomAttributeSetter
+      with Visitable
+{
+    //##########################################################################
+    // public methods
+
+    /**
+     * Defines a dynamic module with the given name that will be saved
+     * to the specified file. No symbol information is emitted.
+     */
+    def DefineDynamicModule(name: String, fileName: String): ModuleBuilder = {
+	val module = new ModuleBuilder(name, fileName, "" + null, this)
+	addModule(name, module)
+	return module
+    }
+
+    /** Returns the dynamic module with the specified name. */
+    def GetDynamicModule(name: String): ModuleBuilder = {
+	return GetModule(name).asInstanceOf[ModuleBuilder]
+    }
+
+    /** Saves this dynamic assembly to disk. */
+    @throws(classOf[IOException])
+    def Save(fileName: String) {
+    generatedFiles = new ArrayList()
+	ILPrinterVisitor.printAssembly(this, fileName)
+    }
+
+    @throws(classOf[IOException])
+    def Save(destPath: String, sourceFilesPath: String) {
+    generatedFiles = new ArrayList()
+    ILPrinterVisitor.printAssembly(this, destPath, sourceFilesPath)
+    }
+
+    /** Returns the list of generated files from calling Save(). */
+    def GetGeneratedFiles(): Array[String] = {
+    return generatedFiles.toArray(new Array[String](generatedFiles.size())).asInstanceOf[Array[String]]
+    }
+
+    /** Sets the entry point for this dynamic assembly. */
+    def SetEntryPoint(entryMethod: MethodInfo) {
+	EntryPoint = entryMethod
+    }
+
+    /** Sets a custom attribute. */
+    def SetCustomAttribute(constr: ConstructorInfo, value: Array[Byte]) {
+	addCustomAttribute(constr, value)
+    }
+
+    //##########################################################################
+    // protected members
+
+    // the access properties -  Save, Run, RunAndSave
+    private var access : Int = _
+
+    // all extern assemblies used in this assembly builder
+    protected var externAssemblies = new HashSet[Assembly]()
+
+    // register an extern assembly
+    protected def registerExternAssembly(assembly: Assembly) {
+	externAssemblies.add(assembly)
+    }
+
+    // get all extern Assemblies used in this Assembly Builder
+    def getExternAssemblies(): Array[Assembly] = {
+	externAssemblies = new HashSet[Assembly](Assembly.assemblies.values().asInstanceOf[java.util.Collection[Assembly]])
+	externAssemblies.remove(this)
+	return externAssemblies.toArray(new Array[Assembly](0)).asInstanceOf[Array[Assembly]]
+    }
+
+    def loadModules() {}
+
+    // contains list of generated .msil files after calling Save()
+    var generatedFiles: ArrayList[String] = new ArrayList[String]()
+
+    //##########################################################################
+    //##########################################################################
+
+    /** the apply method for a visitor */
+    @throws(classOf[IOException])
+    def apply(v: Visitor) {
+	v.caseAssemblyBuilder(this)
+    }
+
+    //##########################################################################
+}
+
+object AssemblyBuilderFactory {
+    /**
+     * Defines a dynamic assembly with the specified name.
+     */
+    def DefineDynamicAssembly(name: AssemblyName): AssemblyBuilder = {
+    //Assembly.reset()
+    return new AssemblyBuilder(name)
+    }
+}
diff --git a/src/msil/ch/epfl/lamp/compiler/msil/emit/ConstructorBuilder.scala b/src/msil/ch/epfl/lamp/compiler/msil/emit/ConstructorBuilder.scala
new file mode 100644
index 0000000..ddd4708
--- /dev/null
+++ b/src/msil/ch/epfl/lamp/compiler/msil/emit/ConstructorBuilder.scala
@@ -0,0 +1,64 @@
+/*
+ * System.Reflection.Emit-like API for writing .NET assemblies to MSIL
+ */
+
+
+package ch.epfl.lamp.compiler.msil.emit
+
+import ch.epfl.lamp.compiler.msil.ConstructorInfo
+import ch.epfl.lamp.compiler.msil.Type
+import java.io.IOException
+
+/**
+ * Defines and represents a constructor of a dynamic class.
+ * ConstructorBuilder is used to fully describe a constructor in
+ * Microsoft intermediate language (MSIL), including the name, attributes,
+ * signature, and constructor body. It is used in conjunction with the
+ * TypeBuilder class to create classes at run time. Call DefineConstructor
+ * to get an instance of ConstructorBuilder.
+ *
+ * @author Nikolay Mihaylov
+ * @version 1.0
+ */
+class ConstructorBuilder(declType: Type, attrs: Int, paramTypes: Array[Type])
+      extends ConstructorInfo(declType, attrs, paramTypes)
+      with ICustomAttributeSetter
+      with Visitable
+{
+
+    //##########################################################################
+    // public interface
+
+    /** Defines a parameter of this constructor. */
+    def DefineParameter(pos: Int, attr: Int, name: String): ParameterBuilder = {
+	val param = new ParameterBuilder(name, params(pos).ParameterType, attr, pos)
+	params(pos) = param
+	return param
+    }
+
+    /** Returns an ILGenerator for this constructor. */
+    def GetILGenerator(): ILGenerator = {
+	return ilGenerator
+    }
+
+    /** Sets a custom attribute. */
+    def SetCustomAttribute(constr: ConstructorInfo, value: Array[Byte]) {
+	addCustomAttribute(constr, value)
+    }
+
+    //##########################################################################
+
+    /** The apply method for a visitor. */
+    @throws(classOf[IOException])
+    def apply(v: Visitor) {
+	v.caseConstructorBuilder(this)
+    }
+
+    //##########################################################################
+
+    // the Intermediate Language Generator
+    // it contains the method's body
+    protected var ilGenerator: ILGenerator = new ILGenerator(this)
+
+    //##########################################################################
+}
diff --git a/src/msil/ch/epfl/lamp/compiler/msil/emit/FieldBuilder.scala b/src/msil/ch/epfl/lamp/compiler/msil/emit/FieldBuilder.scala
new file mode 100644
index 0000000..3ea0638
--- /dev/null
+++ b/src/msil/ch/epfl/lamp/compiler/msil/emit/FieldBuilder.scala
@@ -0,0 +1,57 @@
+/*
+ * System.Reflection.Emit-like API for writing .NET assemblies to MSIL
+ */
+
+
+package ch.epfl.lamp.compiler.msil.emit
+
+import ch.epfl.lamp.compiler.msil.FieldInfo
+import ch.epfl.lamp.compiler.msil.Type
+import ch.epfl.lamp.compiler.msil.FieldAttributes
+import ch.epfl.lamp.compiler.msil.ConstructorInfo
+import java.io.IOException
+
+/**
+ * Discovers the attributes of a field and provides access to field metadata.
+ *
+ * @author Nikolay Mihaylov
+ * @version 1.0
+ */
+class FieldBuilder(name: String, declType: Type, attrs: Int, fieldType: Type)
+      extends FieldInfo(name, declType, attrs, fieldType)
+      with ICustomAttributeSetter
+      with Visitable
+{
+
+    //##########################################################################
+    // public interface
+
+    /** Sets a custom attribute. */
+    def SetCustomAttribute(constr: ConstructorInfo, value: Array[Byte]) {
+	addCustomAttribute(constr, value)
+    }
+
+    //##########################################################################
+
+    /** the apply method for a visitor */
+    @throws(classOf[IOException])
+    def apply(v: Visitor) {
+	v.caseFieldBuilder(this)
+    }
+
+    //##########################################################################
+
+    protected var defaultValue: Object = _
+
+    /** Sets the default value of this field. */
+    def SetConstant(defaultValue: Object) {
+        this.defaultValue = defaultValue
+    }
+
+    /** Specifies the field layout. */
+    def SetOffset(iOffset: Int) {
+	//this.fieldOffset = FieldAttributes.Offset.Value(iOffset)
+    }
+
+    //##########################################################################
+}
diff --git a/src/msil/ch/epfl/lamp/compiler/msil/emit/ICustomAttributeSetter.scala b/src/msil/ch/epfl/lamp/compiler/msil/emit/ICustomAttributeSetter.scala
new file mode 100644
index 0000000..5d74d3a
--- /dev/null
+++ b/src/msil/ch/epfl/lamp/compiler/msil/emit/ICustomAttributeSetter.scala
@@ -0,0 +1,18 @@
+/*
+ * System.Reflection.Emit-like API for writing .NET assemblies to MSIL
+ */
+
+
+package ch.epfl.lamp.compiler.msil.emit
+
+import ch.epfl.lamp.compiler.msil.ConstructorInfo
+
+/**
+ * Declares the possibility to set a custom attribute for a member
+ *
+ * @author Nikolay Mihaylov
+ * @version 1.0
+ */
+trait ICustomAttributeSetter {
+    def SetCustomAttribute(constr: ConstructorInfo, value: Array[Byte])
+}
diff --git a/src/msil/ch/epfl/lamp/compiler/msil/emit/ILGenerator.scala b/src/msil/ch/epfl/lamp/compiler/msil/emit/ILGenerator.scala
new file mode 100644
index 0000000..1c75953
--- /dev/null
+++ b/src/msil/ch/epfl/lamp/compiler/msil/emit/ILGenerator.scala
@@ -0,0 +1,537 @@
+/*
+ * System.Reflection.Emit-like API for writing .NET assemblies to MSIL
+ */
+
+
+package ch.epfl.lamp.compiler.msil.emit
+
+import ch.epfl.lamp.compiler.msil._
+import ch.epfl.lamp.compiler.msil.util.Table
+import java.util.ArrayList
+import java.util.Stack
+import java.util.Iterator
+import java.util.Map
+import java.util.HashMap
+import java.io.IOException
+import ILGenerator._
+
+/**
+ * Generates Microsoft intermediate language (MSIL) instructions.
+ *
+ * @author Nikolay Mihaylov
+ * @version 1.0
+ */
+ final class ILGenerator(_owner: MethodBase) extends Visitable {
+
+    //##########################################################################
+    // public interface
+
+    /**
+     * Puts the specified instruction onto the stream of instructions.
+     */
+    def Emit(opcode: OpCode) {
+	// switch opcode
+        if (opcode == OpCode.Ret) {
+	   emit(opcode, null, 0)
+        } else {
+           emit(opcode, null)
+	}
+    }
+
+    /**
+     * Puts the specified instruction and character argument onto
+     * the Microsoft intermediate language (MSIL) stream of instructions.
+     */
+    def Emit(opcode: OpCode, arg: Char) {
+	emit(opcode,new Character(arg))
+    }
+
+    /**
+     * Puts the specified instruction and metadata token for the
+     * specified constructor onto the Microsoft intermediate language
+     * (MSIL) stream of instructions.
+     */
+    def Emit(opcode: OpCode, arg: ConstructorInfo) {
+	assert(arg != null)
+	// newobj
+	// pop size is the number of parameters
+	emit(opcode,arg, OpCode.PUSH_size(opcode.CEE_push) -
+	     arg.GetParameters().length)
+    }
+
+    /**
+     * Puts the specified instruction onto the Microsoft intermediate language (MSIL)
+     * stream followed by the index of the given local variable.
+     */
+    def Emit(opcode: OpCode, arg: LocalBuilder) {
+	assert(arg != null)
+	// ldarg    | ldarg.s  | ldarga
+	// ldarga.s  | ldloc    | ldloc.s  | ldloca
+	// ldloca.s  | starg    | starg.s  | stloc
+	// stloc.s
+
+	// <instr_var> <localname>
+	emit(opcode, arg)
+    }
+
+
+    /**
+     * Puts the specified instruction and numerical argument onto
+     * the Microsoft intermediate language (MSIL) stream of instructions.
+     */
+    def Emit(opcode: OpCode, arg: Double) {
+	// ldc.r4 | ldc.r8
+	emit(opcode, new java.lang.Double(arg))
+    }
+
+    /**
+     * Puts the specified instruction and metadata token for the
+     * specified field onto the Microsoft intermediate language (MSIL)
+     * stream of instructions.
+     */
+    def Emit(opcode: OpCode,arg: FieldInfo) {
+	assert(arg != null)
+	// ldfld | ldflda | ldsfld | ldsflda | stfld | stsfld
+	emit(opcode,arg)
+    }
+
+    /**
+     * Puts the specified instruction and numerical argument onto
+     * the Microsoft intermediate language (MSIL) stream of instructions.
+     */
+    def Emit(opcode: OpCode, arg: Short ) {
+	emit(opcode, new java.lang.Short(arg))
+    }
+
+    /**
+     * Puts the specified instruction and numerical argument onto
+     * the Microsoft intermediate language (MSIL) stream of instructions.
+     */
+    def Emit(opcode: OpCode, arg: Int) {
+	// ldc.i4 | ldc.i4.s | unaligned
+	emit(opcode, new java.lang.Integer(arg))
+    }
+
+    /**
+     * Puts the specified instruction and numerical argument onto
+     * the Microsoft intermediate language (MSIL) stream of instructions.
+     */
+    def Emit(opcode: OpCode, arg: Long) {
+	// ldc.i8
+	emit(opcode, new java.lang.Long(arg))
+    }
+
+    /**
+     * Puts the specified instruction onto the Microsoft intermediate
+     * language (MSIL) stream and leaves space to include a label when
+     * fixes are done.
+     */
+    def Emit(opcode: OpCode,label: Label) {
+	assert(label != null)
+	// beq    | beq.s    | bge    | bge.s    |
+	// bge.un    | bge.un.s   | bgt    | bgt.s    | bgt.un | bgt.un.s |
+	// ble       | ble.s      | ble.un | ble.un.s | blt    | blt.s    |
+	// blt.un    | blt.un.s   | bne.un | bne.un.s | br     | br.s     |
+	// brfalse   | brfalse.s  | brtrue | brtrue.s | leave  | leave.s
+
+	emit(opcode, label)
+	// is the label initialized ? if true backward jump else forward jump
+	if (label.isInitialized()) {
+// 	    if (arg.stacksize != lastLabel.stacksize) {
+// 		System.err.println("ILGenerator.Emit: Stack depth differs depending on path:");
+// 		System.err.println("\tmethod = " + owner);
+// 		System.err.println("\tPC = 0x" + Table.short2hex(lastLabel.address));
+// 	    }
+	    //assert arg.stacksize == lastLabel.stacksize;
+	}
+	else {
+	    label.setStacksize(lastLabel.getStacksize())
+	}
+    }
+
+    /**
+     * Puts the specified instruction onto the Microsoft intermediate
+     * language (MSIL) stream and leaves space to include a label when
+     * fixes are done.
+     */
+    def Emit(opcode: OpCode, arg: Array[Label] ) {
+	assert(arg != null)
+	// switch
+
+	// <instr> ::= <instr_switch> ( <labels> )
+	// Examples:
+	// switch (0x3, -14, Label1)
+	// switch (5, Label2)
+	emit(opcode, arg, arg.length)
+    }
+
+    /**
+     * Puts the specified instruction onto the Microsoft intermediate
+     * language (MSIL) stream followed by the metadata token for the
+     * given method.
+     */
+    def Emit(opcode: OpCode,arg: MethodInfo) {
+	assert(arg != null)
+	// call  | callvirt | jmp | ldftn | ldvirtftn
+	// pop size is the number of parameters
+	// pop 1 more if method is not static !
+	// push size is either 0 (void Method) either 1
+	assert(arg.ReturnType != null, "No ReturnType: " + arg.DeclaringType + "::" + arg.Name)
+
+	val popush: Int = if (opcode == OpCode.Ldftn || 
+            opcode == OpCode.Ldvirtftn || 
+            opcode == OpCode.Jmp) 
+        {
+           OpCode.PUSH_size(opcode.CEE_push) - OpCode.POP_size(opcode.CEE_pop)
+        } else if (opcode == OpCode.Calli || opcode == OpCode.Callvirt) {
+	        (if(arg.ReturnType == VOID) 0 else 1) - arg.GetParameters().length - 1
+        } else {
+	        (if(arg.ReturnType == VOID) 0 else 1) - arg.GetParameters().length
+	}
+	emit(opcode, arg, popush)
+    }
+
+    /**
+     * Puts the specified instruction and numerical argument onto
+     * the Microsoft intermediate language (MSIL) stream of instructions.
+     */
+    def Emit(opcode: OpCode, arg: Float ) {
+	emit(opcode, new java.lang.Float(arg))
+    }
+
+    /**
+     * Puts the specified instruction onto the Microsoft intermediate
+     * language (MSIL) stream followed by the metadata token for the
+     * given string.
+     */
+    def Emit(opcode: OpCode, arg: String ) {
+	assert(arg != null)
+	// ldstr
+	emit(opcode, arg)
+    }
+
+    /**
+     * Puts the specified instruction onto the Microsoft intermediate
+     * language (MSIL) stream followed by the metadata token for the
+     * given type.
+     */
+    def Emit(opcode: OpCode, arg: Type) {
+	assert(arg != null)
+	// box     | castclass | cpobj    | initobj | isinst    |
+	// ldelema | ldobj     | mkrefany | newarr  | refanyval |
+	// sizeof  | stobj     | unbox
+
+	emit(opcode, arg)
+    }
+
+    /**
+     * Puts a call or callvirt instruction onto the Microsoft intermediate
+     * language (MSIL) stream.
+     */
+    def EmitCall(opcode: OpCode, arg: MethodInfo,
+			 optionalParameterTypes: Array[Type]) {
+	assert(arg != null)
+	// pop size is the number of parameters
+	// push size is either 0 (void Method) either 1
+	//System.out.println(arg.ReturnType.Size + " " + arg.GetParameters().length);
+	emit(opcode, arg, (if(arg.ReturnType == VOID) 0 else 1) -
+	     arg.GetParameters().length)
+    }
+
+    /**
+     * Emits the Microsoft intermediate language (MSIL) necessary to
+     * call WriteLine with the given field.
+     */
+    def EmitWriteLine(arg: FieldInfo) {
+	// first load field info
+	// if static use OpCode.Ldsfld
+	if (arg.IsStatic())
+	    Emit(OpCodes.Ldsfld, arg)
+	else
+	    Emit(OpCodes.Ldfld, arg)
+	// then call System.Console.WriteLine(arg.Type)
+	val t: Type = Type.GetType("System.Console")
+	val argsType: Array[Type] = new Array[Type](1)
+	argsType(0) = arg.FieldType
+	val m: MethodInfo = t.GetMethod("WriteLine", argsType)
+	EmitCall(OpCode.Call, m, null)
+    }
+
+    /**
+     * Emits the Microsoft intermediate language (MSIL) necessary
+     * to call WriteLine with the given local variable.
+     */
+    def EmitWriteLine(arg: LocalBuilder) {
+	// first load local variable
+	Emit(OpCodes.Ldloc, arg)
+	// then call System.Console.WriteLine(arg.Type)
+	val t: Type = Type.GetType("System.Console")
+	val argsType: Array[Type] = new Array[Type](1)
+	argsType(0) = arg.LocalType
+	val m: MethodInfo = t.GetMethod("WriteLine", argsType)
+	EmitCall(OpCode.Call, m, null)
+    }
+
+    /**
+     * Emits the Microsoft intermediate language (MSIL) to call
+     * WriteLine with a string.
+     */
+    def EmitWriteLine(arg: String) {
+	// first load string
+	Emit(OpCode.Ldstr, arg)
+	// then call System.Console.WriteLine(string)
+	val t: Type = Type.GetType("System.Console")
+	val argsType: Array[Type] = new Array[Type](1)
+	argsType(0) = Type.GetType("System.String")
+	val m: MethodInfo = t.GetMethod("WriteLine", argsType)
+	EmitCall(OpCode.Call, m, null)
+    }
+
+    /**
+     * Declares a local variable.
+     */
+    def DeclareLocal(localType: Type): LocalBuilder = {
+	val l: LocalBuilder = new LocalBuilder(locals, localType)
+    locals = locals + 1
+	localList.add(l)
+	return l
+    }
+
+    /**
+     * Returns a new label that can be used as a token for branching.
+     * In order to set the position of the label within the stream, you
+     * must call MarkLabel. This is just a token and does not yet represent
+     * any particular location within the stream.
+     */
+    def DefineLabel():Label = {
+	new Label.NormalLabel()
+    }
+
+    /**
+     * Marks the Microsoft intermediate language (MSIL) stream's
+     * current position with the given label.
+     */
+    def MarkLabel(label: Label) {
+	label.mergeWith(lastLabel)
+	/*
+	label.address = lastLabel.address;
+	//label.stacksize = lastLabel.stacksize;
+	if (label.stacksize >= 0)
+	    lastLabel.stacksize = label.stacksize;
+	*/
+    }
+
+    /** Begins a lexical scope. */
+    def BeginScope() {
+	emitSpecialLabel(Label.NewScope)
+    }
+
+    /** Ends a lexical scope. */
+    def EndScope() {
+	emitSpecialLabel(Label.EndScope)
+    }
+
+    /**
+     * Begins an exception block for a non-filtered exception.
+     * The label for the end of the block. This will leave you in the correct
+     * place to execute finally blocks or to finish the try.
+     */
+    def BeginExceptionBlock() {
+        emitSpecialLabel(Label.Try)
+        val endExc: Label = new Label.NormalLabel() // new Label(lastLabel) ???
+        excStack.push(Label.Try, endExc)
+	return endExc
+    }
+
+    /** Begins a catch block. */
+    def BeginCatchBlock(exceptionType: Type) {
+        val kind = excStack.peekKind()
+        if (kind == Label.Kind.Try ||
+            kind == Label.Kind.Catch) {
+        /* ok */
+        } else {
+            throw new RuntimeException("Catch should follow either a try or catch")
+	}
+        val endExc: Label = excStack.popLabel()
+	Emit(OpCodes.Leave, endExc)
+	// the CLI automatically provide the exception object on the evaluation stack
+	// we adjust the stacksize
+	lastLabel.incStacksize()
+        excStack.push(Label.Catch, endExc)
+        emitSpecialLabel(Label.Catch, exceptionType)
+    }
+
+    /** Ends an exception block. */
+    def EndExceptionBlock() {
+        val kind = excStack.peekKind()
+        if (kind == Label.Kind.Try) {
+	    throw new RuntimeException("Try block with neither catch nor finally")
+        } else if (kind == Label.Kind.Catch) {
+	    Emit(OpCodes.Leave, excStack.peekLabel())
+        } else if (kind == Label.Kind.Finally) {
+	    Emit(OpCodes.Endfinally)
+	}
+        MarkLabel(excStack.popLabel())
+        emitSpecialLabel(Label.EndTry)
+    }
+
+    /**
+     * Begins a finally block in the Microsoft intermediate language
+     * (MSIL) instruction stream.
+     */
+    def BeginFinallyBlock() {
+        val endExc: Label = excStack.popLabel()
+	Emit(OpCodes.Leave, endExc)
+        excStack.push(Label.Finally, endExc)
+	emitSpecialLabel(Label.Finally)
+    }
+
+    /**
+     * Emits an instruction to throw an exception.
+     */
+    def ThrowException(exceptionType: Type) {
+	assert(exceptionType != null)
+	if (!exceptionType.isSubtypeOf(Type.GetType("System.Exception")))
+	    throw new RuntimeException
+		(exceptionType + " doesn't extend System.Exception" )
+	val ctor: ConstructorInfo = exceptionType.GetConstructor(Type.EmptyTypes)
+	if (ctor == null)
+	    throw new RuntimeException("Type " + exceptionType
+				       + "doesn't have a default constructor")
+	Emit(OpCodes.Newobj, ctor)
+	Emit(OpCodes.Throw)
+    }
+
+    /**
+     * sets the line of the source file corresponding to the next instruction
+     */
+    def setPosition(line: Int) {
+	if (line != 0)
+	    lineNums.put(lastLabel, Integer.toString(line))
+    }
+
+    def setPosition(line: Int, filename: String) {
+	if (line != 0)
+	    lineNums.put(lastLabel, line + "  '" + filename + "'")
+    }
+
+    def getLocals(): Array[LocalBuilder] = {
+	  localList.toArray(new Array[LocalBuilder](0)).asInstanceOf[Array[LocalBuilder]]
+    }
+
+    def getLabelIterator(): Iterator[Label] = {
+	  labelList.iterator()
+    }
+    def getOpcodeIterator(): Iterator[OpCode] = {
+	  opcodeList.iterator()
+    }
+    def getArgumentIterator(): Iterator[Object] = {
+	  argumentList.iterator()
+    }
+
+    //##########################################################################
+    // private implementation details
+
+
+
+    // the local variable list
+    private final val localList: ArrayList[LocalBuilder] = new ArrayList[LocalBuilder]()
+
+    // the label list, the opcode list and the opcode argument list
+    // labelList is an array of Label
+    // opcodeList is an array of OpCode
+    // argumentList is an array of Object (null if no argument)
+    private final val labelList: ArrayList[Label] = new ArrayList[Label]()
+    private final val opcodeList: ArrayList[OpCode] = new ArrayList[OpCode]()
+    private final val argumentList: ArrayList[Object] = new ArrayList[Object]()
+
+    // the program counter (pc)
+    // also called the stream's current position
+    private var pc: Int = 0
+
+    // last label
+    private var lastLabel: Label = new Label.NormalLabel(pc,0)
+
+    // the maximum size of stack
+    private var maxstack: Int = 0
+
+    // the number of the locals
+    private var locals: Int = 0
+
+    // stack of label for exception mechanism
+    private var excStack: ExceptionStack = new ExceptionStack()
+
+    // the method info owner of this ILGenerator
+    var owner: MethodBase = _owner
+
+    val lineNums: Map[Label, String] = new HashMap[Label, String]()
+
+
+    def getMaxStacksize(): Int = { this.maxstack }
+
+    // private emit with Object Argument
+    private def emit(opcode: OpCode, arg: Object) {
+	emit(opcode, arg, opcode.CEE_popush)
+    }
+
+    // private emit with Object Argument and override POPUSH
+    private def emit(opcode: OpCode, arg: Object, overridePOPUSH: Int) {
+	// add label, opcode and argument
+	labelList.add(lastLabel)
+	opcodeList.add(opcode)
+	argumentList.add(arg)
+	// compute new lastLabel (next label)
+	val stackSize: Int = lastLabel.getStacksize() + overridePOPUSH
+	if (stackSize < 0) {
+	    throw new RuntimeException("ILGenerator.emit(): Stack underflow in method: " + owner)
+	}
+	if (stackSize > maxstack)
+	    maxstack = stackSize
+	var address: Int = lastLabel.getAddress() + opcode.CEE_length
+        if (opcode.CEE_opcode == OpCode.CEE_SWITCH) {
+            address = address + 4*arg.asInstanceOf[Array[Label]].length
+        }
+	lastLabel = new Label.NormalLabel(address, stackSize)
+	pc = pc + 1
+    }
+
+    private def emitSpecialLabel(l: Label) {
+        emitSpecialLabel(l, null)
+    }
+    private def emitSpecialLabel(l: Label, catchType: Type) {
+        labelList.add(l)
+        opcodeList.add(null)
+        argumentList.add(catchType)
+    }
+
+    //##########################################################################
+    //
+    @throws(classOf[IOException])
+    def apply(v: Visitor)  {
+	v.caseILGenerator(this)
+    }
+
+    //##########################################################################
+}  // class ILGenerator
+
+
+object ILGenerator {
+  
+   val VOID: Type = Type.GetType("System.Void")
+   val NO_LABEL: String = ""
+   
+    private final class ExceptionStack {
+        private val labels: Stack[Label] = new Stack[Label]()
+        private val kinds: Stack[Label] = new Stack[Label]()
+        def ExceptionStack() {}
+        def pop() { labels.pop(); kinds.pop() }
+        def push(kind: Label, label: Label) {
+            kinds.push(kind); labels.push(label)
+        }
+        def peekKind(): Label.Kind = {kinds.peek().asInstanceOf[Label].getKind() }
+        def peekLabel(): Label = { labels.peek().asInstanceOf[Label] }
+        def popLabel(): Label = { kinds.pop(); labels.pop().asInstanceOf[Label]}
+    }
+  
+}
+
diff --git a/src/msil/ch/epfl/lamp/compiler/msil/emit/ILPrinterVisitor.scala b/src/msil/ch/epfl/lamp/compiler/msil/emit/ILPrinterVisitor.scala
new file mode 100644
index 0000000..86a386a
--- /dev/null
+++ b/src/msil/ch/epfl/lamp/compiler/msil/emit/ILPrinterVisitor.scala
@@ -0,0 +1,734 @@
+/*
+ * System.Reflection.Emit-like API for writing .NET assemblies in MSIL
+ */
+
+
+package ch.epfl.lamp.compiler.msil.emit
+
+import java.io.File
+import java.io.FileWriter
+import java.io.BufferedWriter
+import java.io.PrintWriter
+import java.io.IOException
+import java.util.Iterator
+import java.util.HashMap
+import java.util.Arrays
+import java.util.Comparator
+
+import ch.epfl.lamp.compiler.msil._
+import ch.epfl.lamp.compiler.msil.util.Table
+
+/**
+ * The MSIL printer Visitor. It prints a complete
+ * assembly in a single or multiple files. Then this file can be compiled by ilasm.
+ *
+ * @author Nikolay Mihaylov
+ * @version 1.0
+ */
+abstract class ILPrinterVisitor extends Visitor {
+
+    import ILPrinterVisitor._
+    import OpCode._
+
+    //##########################################################################
+
+    protected final val assemblyNameComparator =
+        new Comparator[Assembly]() {
+            def compare(o1: Assembly, o2: Assembly): Int = {
+                val a1 = o1.asInstanceOf[Assembly]
+                val a2 = o2.asInstanceOf[Assembly]
+                return a1.GetName().Name.compareTo(a2.GetName().Name)
+            }
+        }
+
+    // the output file writer
+    protected var out: PrintWriter = null
+
+    // the left margin
+    private var lmargin = 0
+
+    // indicate a newline
+    private var newline = true
+
+    // print types without or with members?
+    protected var nomembers: Boolean = false
+
+    // external assemblies
+    protected var as: Array[Assembly] = null
+
+    private def align() {
+	if (newline)
+	    padding = lmargin
+	printPadding()
+	newline = false
+    }
+    private def indent() {
+	lmargin += TAB
+    }
+    private def undent() {
+	lmargin -= TAB
+	assert(lmargin >= 0)
+    }
+
+    private var padding = 0
+    private def pad(n: Int) {
+	assert(n >= 0, "negative padding: " + n)
+        padding += n
+    }
+    private def printPadding() {
+	if (padding <= 0)
+	    return
+	while (padding > SPACES_LEN) {
+	    out.print(SPACES)
+	    padding -= SPACES_LEN
+	}
+        out.print(SPACES.substring(0, padding))
+        padding = 0
+    }
+
+    // methods to print code
+    protected def print(s: String)  { align(); out.print(s)}
+    protected def print(o: Object)  { align(); out.print(o) }
+    protected def print(c: Char)    { align(); out.print(c) }
+    protected def print(`val`: Int) { align(); out.print(`val`)}
+    protected def print(`val`: Long){ align(); out.print(`val`)}
+    protected def println()         { out.println(); newline = true; padding = 0 }
+    protected def println(c: Char)  { print(c); println() }
+    protected def println(i: Int)   { print(i); println() }
+    protected def println(l: Long)  { print(l); println() }
+    protected def println(s: String){ print(s); println() }
+    protected def println(o: Object){ print(o); println() }
+    protected def printName(name: String) {
+	var ch = name.charAt(0)
+	//if (Character.isLetter(ch) && Character.isLowerCase(ch)) {
+	if (ch != '.') {
+	    print('\''); print(name); print('\'')
+	} else
+	    print(name)
+    }
+
+	protected def printAssemblyBoilerplate() {
+	// print all the external assemblies
+    for (j <- 0 until as.length) {
+	    printAssemblySignature(as(j), true)
+	}
+	// print assembly declaration
+	printAssemblySignature(currAssembly, false)
+	}
+
+    // the entrypoint method
+    protected var entryPoint: MethodInfo = null
+
+    // current opcode argument
+    protected var argument: Object = null
+
+    /***/
+    @throws(classOf[IOException])
+    protected def print(vAble: Visitable) {
+	if (vAble != null)
+	    vAble.apply(this)
+    }
+
+    /**
+     * Visit an AssemblyBuilder
+     */
+    @throws(classOf[IOException])
+    def caseAssemblyBuilder(assemblyBuilder: AssemblyBuilder)
+
+    protected var currentModule: Module = null
+    /**
+     * Visit a ModuleBuilder
+     */
+    @throws(classOf[IOException])
+    def caseModuleBuilder(module: ModuleBuilder)
+
+    protected var currentType: Type = null
+    /**
+     * Visit a TypeBuilder
+     */
+    @throws(classOf[IOException])
+    def caseTypeBuilder(`type`: TypeBuilder) {
+	currentType = `type`
+	if (!`type`.Namespace.equals("") && `type`.DeclaringType == null) {
+	    print(".namespace \'" ); print(`type`.Namespace); println("\'")
+	    println("{"); indent()
+	}
+	print(".class ")
+	// <classHead> ::=
+	// <classAttr>* <id>
+	// [extends <typeReference>]
+	// [implements <typeReference> [, <typeReference>]*]
+	print(TypeAttributes.toString(`type`.Attributes))
+	print(" \'"); print(`type`.Name); print("\'")
+	if (`type`.BaseType() != null) {
+	    println()
+	    print("       extends    ")
+	    printReference(`type`.BaseType())
+	}
+	var ifaces: Array[Type] = `type`.getInterfaces()
+	if (ifaces.length > 0) {
+	    println()
+	    print("       implements ")
+        for (i <- 0 until ifaces.length) {
+		if (i > 0) {
+		    println(",")
+		    print("                  ")
+		}
+		printReference(ifaces(i))
+	    }
+	}
+	println()
+	println("{")
+	indent()
+	if (!nomembers && `type`.sourceFilename != null)
+	    println(".line  " + `type`.sourceLine
+		    + "  '" + `type`.sourceFilename + "'")
+        if (!nomembers) {
+            printAttributes(`type`)
+        }
+	// print nested classes
+    val nested = `type`.nestedTypeBuilders.iterator()
+    while(nested.hasNext())
+      print(nested.next().asInstanceOf[TypeBuilder])
+
+	// print each field
+    val fields = `type`.fieldBuilders.iterator()
+    while(fields.hasNext())
+	  print(fields.next().asInstanceOf[FieldBuilder])
+
+	// print each constructor
+	val constrs = `type`.constructorBuilders.iterator()
+	while (constrs.hasNext())
+	    print(constrs.next().asInstanceOf[ConstructorBuilder])
+
+	// print each method
+	val methods = `type`.methodBuilders.iterator()
+	while (methods.hasNext()) {
+	    val method = methods.next().asInstanceOf[MethodBuilder]
+	    assert(method.DeclaringType == `type`)
+	    print(method)
+	}
+
+	undent(); println("}")
+	if (!`type`.Namespace.equals("") && `type`.DeclaringType == null) {
+	    undent(); println("}")
+	}
+	currentType = null
+    }
+
+    /**
+     * Visit a FieldBuilder
+     */
+    @throws(classOf[IOException])
+    def caseFieldBuilder(field: FieldBuilder) {
+        if (nomembers) return
+	// [[int32]] <fieldAttr>* <type> <id> [= <fieldInit> | at <dataLabel>]
+	print(".field ")
+	print(FieldAttributes.toString(field.Attributes))
+	print(" "); printSignature(field.FieldType)
+	print(" \'"); print(field.Name); print("\'")
+	if (field.IsLiteral()) {
+	    print(" = ")
+	    val value = field.getValue()
+	    if (value == null) {
+		print("nullref")
+	    } else if (value.isInstanceOf[String]) {
+		print(msilString(value.asInstanceOf[String]))
+	    } else if (value.isInstanceOf[Boolean]) {
+		print("bool (")
+		print(if((value.asInstanceOf[Boolean]).booleanValue()) { "true" } else { "false" })
+		print(")")
+	    } else if (value.isInstanceOf[Byte]) {
+		print("int8 (")
+		print(value)
+		print(")")
+	    } else if (value.isInstanceOf[java.lang.Short]) {
+		print("int16 (")
+		print(value)
+		print(")")
+	    } else if (value.isInstanceOf[Character]) {
+		print("char (")
+		print((value.asInstanceOf[Character]).charValue())
+		print(")")
+	    } else if (value.isInstanceOf[Integer]) {
+		print("int32 (")
+		print((value.asInstanceOf[Integer]).intValue())
+		print(")")
+	    } else if (value.isInstanceOf[Long]) {
+		print("int64 (")
+		print((value.asInstanceOf[Long]).longValue())
+		print(")")
+	    } else if (value.isInstanceOf[Float]) {
+		// !!! check if encoding is correct
+		val bits = java.lang.Float.floatToRawIntBits((value.asInstanceOf[Float]).floatValue())
+		// float32(float32(...)) != float32(...)
+		print("float32 (float32 (")
+		print(bits)
+		print("))")
+	    } else if (value.isInstanceOf[Double]) {
+		// !!! check if encoding is correct
+		var bits = java.lang.Double.doubleToRawLongBits((value.asInstanceOf[Double]).doubleValue())
+		// float64(float64(...)) != float64(...)
+		print("float64 (float64 (")
+		print(bits)
+		print("))")
+	    } else {
+		throw new Error("ILPrinterVisitor: Illegal default value: "
+				+ value.getClass())
+	    }
+	}
+	println()
+        printAttributes(field)
+    }
+
+    /**
+     * Visit a ConstructorBuilder
+     */
+    @throws(classOf[IOException])
+    def caseConstructorBuilder(constr: ConstructorBuilder) {
+        if (nomembers) return
+	print(".method "); printHeader(constr, VOID)
+	println(); println("{"); indent()
+        printAttributes(constr)
+	try {
+	    print(constr.GetILGenerator())
+	} catch {
+        case e : RuntimeException => {
+	       System.err.println("In method " + constr)
+	       e.printStackTrace()
+        }
+	}
+	undent(); println("}")
+    }
+
+    /**
+     * Visit a MethodBuilder
+     */
+    @throws(classOf[IOException])
+    def caseMethodBuilder(method: MethodBuilder) {
+        if (nomembers) return
+	print(".method "); printHeader(method, method.ReturnType)
+	if (method.IsAbstract()
+	    || (method.DeclaringType != null
+		&& method.DeclaringType.IsInterface()
+		&& !method.IsStatic()))
+	    {
+		println(" {"); indent()
+                printAttributes(method)
+                undent(); println("}")
+	    } else {
+		println(); println("{"); indent()
+                printAttributes(method)
+		if (method == entryPoint)
+		    println(".entrypoint")
+		try {
+		    print(method.GetILGenerator())
+		} catch {
+            case e: RuntimeException =>
+		      System.err.println("In method " + method)
+		      e.printStackTrace()
+		}
+		undent(); println("}")
+	    }
+    }
+
+    /**
+     * Visit a ParameterBuilder
+     */
+    @throws(classOf[IOException])
+    def caseParameterBuilder(param: ParameterBuilder) {
+	print(ParameterAttributes.toString(param.Attributes))
+	printSignature(param.ParameterType)
+	//print(' ') print(marshal)
+	print(' '); printName(param.Name)
+    }
+
+    /**
+     * Visit an ILGenerator
+     */
+    @throws(classOf[IOException])
+    def caseILGenerator(code: ILGenerator) {
+	// print maxstack
+	println(".maxstack   " + code.getMaxStacksize())
+	// get the local variables
+	var locals: Array[LocalBuilder] = code.getLocals()
+	if (locals.length > 0) {
+	    println(".locals init (")
+	    indent()
+        for (i <- 0 until locals.length) {
+		if (i > 0) println(",")
+		print(locals(i))
+	    } // end while
+	    undent()
+	    println(")")
+	}
+	// get 3 iterators for the 3 lists
+	val itL = code.getLabelIterator()
+	val itO = code.getOpcodeIterator()
+	val itA = code.getArgumentIterator()
+	// iterate over each opcode
+	while (itO.hasNext()) {
+	    // first print label
+	    val label = itL.next().asInstanceOf[Label]
+	    var o = code.lineNums.get(label)
+	    if (o != null)
+		println(".line       " + o)
+	    argument = itA.next().asInstanceOf[Object]
+	    printLabel(label)
+            val o2 = itO.next()
+            if (o2 != null) {
+                print("   ")
+                print(o2.asInstanceOf[OpCode])
+            }
+	    println()
+	} // end while
+    }
+
+    /**
+     * visit an OpCode
+     */
+    @throws(classOf[IOException])
+    def caseOpCode(opCode: OpCode) {
+	var opString = opCode.toString()
+	print(opString)
+	pad(12 - opString.length())
+
+	// switch opcode
+        if (opCode == OpCode.Ldstr) {
+            print(msilString(argument.toString()))
+        } else if(opCode == OpCode.Switch) {
+	    // switch ( <labels> )
+	    print("(")
+	    val targets = argument.asInstanceOf[Array[Label]]
+            val m = targets.length
+            for (i <- 0 until m) {
+	        if (i != 0) print(", ")
+		print(targets(i))
+	    } // end for
+	    print(")")
+        } else if(opCode == OpCode.Call || opCode == OpCode.Callvirt || opCode == OpCode.Jmp || opCode == OpCode.Ldftn || opCode == OpCode.Ldvirtftn) {
+        // call  | callvirt | jmp | ldftn | ldvirtftn
+        // <instr_method> <callConv> <type> [ <typeSpec> :: ] <methodName>
+	    printSignature(argument.asInstanceOf[MethodBase])
+        } else if (opCode == OpCode.Newobj) {
+	    printSignature(argument.asInstanceOf[ConstructorInfo])
+    // ldfld | ldflda | ldsfld | ldsflda | stfld | stsfld
+        } else if (opCode == OpCode.Ldfld || opCode == OpCode.Ldflda || opCode == OpCode.Ldsfld || opCode == OpCode.Ldsflda || opCode == OpCode.Stfld || opCode == OpCode.Stsfld) {
+	    printSignature(argument.asInstanceOf[FieldInfo])
+        } else if (opCode == OpCode.Castclass || opCode == OpCode.Isinst || opCode == OpCode.Ldobj || opCode == OpCode.Newarr) {
+	    printSignature(argument.asInstanceOf[Type])
+        } else if (opCode == OpCode.Box || opCode == OpCode.Unbox || opCode == OpCode.Ldtoken) {
+	    printReference(argument.asInstanceOf[Type])
+        } else if (opCode == OpCode.Ldloc || opCode == OpCode.Ldloc_S || opCode == OpCode.Ldloca || opCode == OpCode.Ldloca_S || opCode == OpCode.Stloc || opCode == OpCode.Stloc_S) {
+	    val loc = argument.asInstanceOf[LocalBuilder]
+	    print(loc.slot); print("\t// "); printSignature(loc.LocalType)
+	    print(" \'"); print(loc.name); print("\'")
+	    //print("'") print(((LocalBuilder)argument).name) print("'")
+        } else {
+	    // by default print toString argument if any
+	    if (argument != null)
+		print(argument)
+	} // end switch
+    }
+
+    /**
+     * Visit a Label
+     */
+    def printLabel(label: Label) {
+       val kind = label.getKind()
+       if (kind == Label.Kind.Normal) {
+          print(label+ ": ")
+       } else if (kind == Label.Kind.NewScope) {
+          print("{"); indent()
+       } else if (kind == Label.Kind.EndScope) {
+	  undent(); print("}")
+       } else if (kind == Label.Kind.Try) {
+          print(".try {"); indent()
+       } else if (kind == Label.Kind.Catch) {
+	  undent()
+	  println("}")
+	  print("catch ")
+	  printReference(argument.asInstanceOf[Type])
+	  print(" {")
+	  indent()
+       } else if (kind == Label.Kind.Filter) {
+	  undent()
+	  println("}")
+	  print("filter {")
+	  indent()
+       } else if (kind == Label.Kind.EndFilter) {
+	  print("endfilter")
+	  undent()
+	  println("}")
+       } else if (kind == Label.Kind.Finally) {
+	  undent()
+	  println("}")
+	  print("finally {")
+	  indent()
+       } else if (kind == Label.Kind.EndTry) {
+	  undent()
+	  print("}")
+       }
+    }
+
+    /**
+     * Visit a LocalBuilder
+     */
+    @throws(classOf[IOException])
+    def caseLocalBuilder(localBuilder: LocalBuilder) {
+	// print type
+	printSignature(localBuilder.LocalType)
+	// space
+	print(" \'")
+	// print name
+	print(localBuilder.name)
+	print("\'")
+    }
+
+
+    //##########################################################################
+
+    def printAssemblySignature(assem: Assembly, extern: Boolean) {
+        print(".assembly ")
+        if (extern)
+            print("extern ")
+        val an = assem.GetName()
+	printName(an.Name); println()
+	println("{")
+        if (!extern)
+            printAttributes(assem)
+	val v = an.Version
+	if (v != null) {
+	    print("    .ver "); print(v.Major); print(':'); print(v.Minor)
+	    print(':'); print(v.Build); print(':')
+	    print(v.Revision); println()
+	}
+	var key = an.GetPublicKeyToken()
+	if (key != null) {
+	    print("    .publickeytoken = ("); print(PEFile.bytes2hex(key))
+	    println(")")
+	} else {
+	    key = an.GetPublicKey()
+	    if (key != null) {
+		print("    .publickey = ("); print(PEFile.bytes2hex(key))
+		println(")")
+	    }
+	}
+	println("}")
+    }
+
+
+    def printSignature(field: FieldInfo) {
+	printSignature(field.FieldType)
+	//print(' ') print(owner)
+	print(' ')
+	//if (field.IsStatic && field.DeclaringType != currentType) {
+	    printReference(field.DeclaringType)
+	    print("::")
+	    //}
+	printName(field.Name)
+    }
+
+    // print method head
+    @throws(classOf[IOException])
+    def printHeader(method: MethodBase, returnType: Type) {
+	print(MethodAttributes.toString(method.Attributes))
+	print(' '); print(CallingConventions.toString(method.CallingConvention))
+	print(' '); printSignature(returnType)
+	//print(' ') print(marshal)
+	print(' '); printName(method.Name)
+	val params = method.GetParameters()
+	print('(')
+	for (i <- 0 until params.length) {
+	    if (i > 0) print(", ")
+	    print(params(i).asInstanceOf[ParameterBuilder])
+	}
+	print(") ")
+
+	print(MethodImplAttributes
+	      .toString(method.GetMethodImplementationFlags()))
+    }
+
+
+    def printSignature(method: MethodBase) {
+	var returnType: Type = null
+	if (method.isInstanceOf[MethodInfo])
+	    returnType = (method.asInstanceOf[MethodInfo]).ReturnType
+	else if (method.isInstanceOf[ConstructorInfo])
+	    returnType = VOID
+	else
+	    throw new RuntimeException()
+
+	val s = CallingConventions.toString(method.CallingConvention)
+	print(s)
+	if (s.length() > 0) print(' ')
+	printSignature(returnType)
+	//print(' ') print(owner)
+	print(' '); printReference(method.DeclaringType)
+	print("::"); printName(method.Name)
+
+	var params = method.GetParameters()
+	print("(")
+	for (i <- 0 until params.length) {
+	    if (i > 0) print(", ")
+	    printSignature(params(i).ParameterType)
+	}
+	print(")")
+    }
+
+    def printSignature(`type`: Type) {
+	val sig : Object = primitive.get(`type`)
+	if (sig != null) {
+	    print(sig)
+	    return
+	}
+
+	if (`type`.HasElementType()) {
+	    printSignature(`type`.GetElementType())
+	    if (`type`.IsArray())
+		print("[]")
+	    else if (`type`.IsPointer())
+		print('*')
+	    else if (`type`.IsByRef())
+		print('&')
+	} else {
+	    print(if(`type`.IsValueType()) "valuetype " else "class ")
+	    printReference(`type`)
+	}
+    }
+
+    def printReference(`type`: Type) {
+	if (`type`.Assembly() != currentModule.Assembly) {
+	    print('['); print(`type`.Assembly().GetName().Name); print("]")
+	} else if (`type`.Module != currentModule) {
+	    print("[.module "); print(`type`.Module.Name); print("]")
+	}
+	printTypeName(`type`)
+    }
+
+    def printTypeName(`type`: Type) {
+	if (`type`.DeclaringType != null) {
+	    printTypeName(`type`.DeclaringType)
+	    print('/')
+	    printName(`type`.Name)
+	} else {
+	    printName(`type`.FullName)
+    }
+    }
+
+    def printAttributes(icap: ICustomAttributeProvider) {
+        var attrs = icap.GetCustomAttributes(false)
+        for (i <- 0 until attrs.length) {
+            print(".custom ")
+            printSignature((attrs(i).asInstanceOf[Attribute]).getConstructor())
+            print(" = (")
+            print(PEFile.bytes2hex((attrs(i).asInstanceOf[Attribute]).getValue()))
+            println(")")
+        }
+    }
+
+    //##########################################################################
+
+}  // class ILPrinterVisitor
+
+object ILPrinterVisitor {
+    final val VOID: Type = Type.GetType("System.Void")
+    protected final val TAB = 4
+
+    protected final val SPACES = "                                "
+    protected final val SPACES_LEN = SPACES.length()
+
+    def hasControlChars(str: String): Boolean = {
+    for(i <- 0 until str.length()) {
+        var ch = str.charAt(i)
+        ch match {
+          case '\b' =>
+          case '\t' =>
+          case '\n' =>
+          case '\f' =>
+          case '\r' =>
+          case _    => if(Character.isISOControl(ch)) return true
+        }
+    }
+    return false
+    }
+        
+    final val EMPTY: String = ""
+    def msilString(s: String): String = {
+    if (hasControlChars(s)) {
+        try {
+        return "bytearray (" + PEFile.bytes2hex(s.getBytes("UTF-16LE")) + ")"
+        } catch {
+          case e : java.io.UnsupportedEncodingException => throw new RuntimeException(e)
+        }
+    }   
+    var str = new StringBuffer(s)
+    var ss = EMPTY
+    var i = 0
+    while(i < str.length()) {
+        ss = EMPTY
+        val c = str.charAt(i)
+        c match {
+          case '\b' => ss = "\\b"
+          case '\t' => ss = "\\t"
+          case '\n' => ss = "\\n"
+          case '\f' => ss = "\\f"
+          case '\r' => ss = "\\r"
+          case '\"' => ss = "\\\""
+          case '\'' => ss = "\\\'"
+          case '\\' => ss = "\\\\"
+          case  _   => if (Character.isISOControl(c))
+                         ss = "\\u" + PEFile.int2hex(Character.getNumericValue(c))
+        }
+        if (ss != EMPTY) {
+        str.replace(i, i + 1, ss)
+        i = i + ss.length() - 1
+        }
+        i = i + 1
+    }
+    return "\"" + str.toString() + "\""
+    }
+
+    /**
+     * the main printer method
+     */
+    @throws(classOf[IOException])
+    def printAssembly(assemblyBuilder: AssemblyBuilder, fileName: String) {
+      assemblyBuilder.apply(new SingleFileILPrinterVisitor(fileName))
+    }
+
+    @throws(classOf[IOException])
+    def printAssembly(assemblyBuilder: AssemblyBuilder, destPath: String, sourceFilesPath: String) {
+      assemblyBuilder.apply(new MultipleFilesILPrinterVisitor(destPath, sourceFilesPath))
+    }
+
+    /** The current assembly */
+    var currAssembly: Assembly = _
+
+    final var primitive = new HashMap[Type, String]()
+    def addPrimitive(name: String, sig: String) {
+      var `type` =
+      Type.GetType(name)
+      assert(`type` != null, "Cannot lookup primitive type " + `type`)
+      primitive.put(`type`, sig)
+    }
+
+    addPrimitive("System.Object", "object")
+    addPrimitive("System.String", "string")
+    addPrimitive("System.Void", "void")
+    addPrimitive("System.Boolean", "bool")
+    addPrimitive("System.Char", "char")
+    addPrimitive("System.SByte", "int8")
+    addPrimitive("System.Byte", "unsigned int8")
+    addPrimitive("System.Int16", "int16")
+    addPrimitive("System.UInt16", "unsigned int16")
+    addPrimitive("System.Int32", "int32")
+    addPrimitive("System.UInt32", "unsigned int32")
+    addPrimitive("System.Int64", "int64")
+    addPrimitive("System.UInt64", "unsigned int64")
+    addPrimitive("System.IntPtr", "native int")
+    addPrimitive("System.UIntPtr", "unsigned native int")
+    addPrimitive("System.Single", "float32")
+    addPrimitive("System.Double", "float64")
+    addPrimitive("System.TypedReference", "typedref")
+}
diff --git a/src/msil/ch/epfl/lamp/compiler/msil/emit/Label.scala b/src/msil/ch/epfl/lamp/compiler/msil/emit/Label.scala
new file mode 100644
index 0000000..22c1b11
--- /dev/null
+++ b/src/msil/ch/epfl/lamp/compiler/msil/emit/Label.scala
@@ -0,0 +1,148 @@
+/*
+ * System.Reflection.Emit-like API for writing .NET assemblies to MSIL
+ */
+
+
+package ch.epfl.lamp.compiler.msil.emit
+
+import ch.epfl.lamp.compiler.msil.Type
+
+/**
+ * Represents a label in the instruction stream. Label is used in conjunction
+ * with the ILGenerator class.
+ *
+ * @author Nikolay Mihaylov
+ * @version 1.0
+ */
+abstract class Label protected {
+    import Label._
+    def isInitialized(): Boolean
+    def getKind(): Kind
+    def getAddress(): Int
+    def getStacksize(): Int
+    def setStacksize(stacksize: Int): Unit
+    def incStacksize(): Unit
+    def mergeWith(that: Label): Unit
+}
+
+object Label {
+    final val DUMMY: Int = -((1<<31)-1)
+
+    //##########################################################################
+
+    final class NormalLabel(_address: Int, _stacksize: Int) extends Label {
+
+        //##########################################################################
+        // protected constructors
+
+        //the position of the label
+        private var address: Int = _address
+
+        //the stacksize at the label
+        private var stacksize: Int = _stacksize
+
+	def this() {
+          this(-1, DUMMY)
+        }
+
+        def this(that: NormalLabel) {
+          this(that.getAddress(), that.getStacksize())
+        }
+
+        //##########################################################################
+        // instrumental methods only used by ILGenerator
+
+        def isInitialized() = (getAddress() != -1) || (stacksize != DUMMY)
+
+        def getAddress() = address
+
+        def getStacksize() = stacksize
+
+        def setStacksize(stacksize: Int) {
+            assert(stacksize >= 0)
+            this.stacksize = stacksize
+        }
+
+        def incStacksize() {
+            stacksize = stacksize + 1
+        }
+
+        def getKind(): Kind = Kind.Normal
+
+        def mergeWith(that: Label) {
+            //assert address < 0 : "this.address = " + address + " that.address = " + that.address
+            address = that.getAddress()
+
+            // 	assert stacksize == that.stacksize
+            // 	    : "this.stacksize = " + stacksize + " that.stacksize = "
+            // 	    + that.stacksize
+            // 	stacksize = that.stacksize
+            val ss: Int = math.max(stacksize, that.getStacksize())
+            stacksize = ss
+            that.setStacksize(ss)
+        }
+
+        //##########################################################################
+        //
+
+        /**
+         * the toString Method return the label name
+         * it's "IL" + address
+         */
+        override def toString(): String = {
+            var pad: String = ""
+            if (address < 16) pad = "000"
+            else if (address < 256) pad = "00"
+            else if (address < 4096) pad = "0"
+            return "IL_"  + pad + Integer.toHexString(address)
+        }
+
+        def getString(): String = {
+            val name = super.toString()
+            val i: Int = name.lastIndexOf('.')
+            return name.substring(i+1, name.length())
+        }
+    }
+
+    //########################################################################
+    // Special Labels
+
+    final class SpecialLabel(_kind: Label.Kind) extends Label {
+        private final var kind: Label.Kind = _kind
+        def isInitialized() = true
+        def getAddress(): Int = { throw new RuntimeException("" + kind.toString()) }
+        def getStacksize(): Int = { throw new RuntimeException("" + kind.toString()) }
+        def setStacksize(stacksize: Int) { throw new RuntimeException(kind.toString()) }
+        def incStacksize() { throw new RuntimeException(kind.toString()) }
+        def getKind(): Kind = kind
+        def mergeWith(that: Label) { throw new RuntimeException(kind.toString()) }
+        override def toString(): String = "Label(" + kind.toString() + ")"
+    }
+
+    final val NewScope: Label = new SpecialLabel(Kind.NewScope)
+    final val EndScope: Label = new SpecialLabel(Kind.EndScope)
+    final val Try: Label = new SpecialLabel(Kind.Try)
+    final val Catch: Label = new SpecialLabel(Kind.Catch)
+    final val Filter: Label = new SpecialLabel(Kind.Filter)
+    final val EndFilter: Label = new SpecialLabel(Kind.EndFilter)
+    final val Finally: Label = new SpecialLabel(Kind.Finally)
+    final val EndTry: Label = new SpecialLabel(Kind.EndTry)
+
+    final class Kind() {}
+
+    final object Kind {
+        final val Normal: Kind = new Kind()
+
+	final val NewScope: Kind = new Kind()
+	final val EndScope: Kind = new Kind()
+
+        final val Try: Kind = new Kind()
+        final val Catch: Kind = new Kind()
+        final val Filter: Kind = new Kind()
+        final val EndFilter: Kind = new Kind()
+        final val Finally: Kind = new Kind()
+        final val EndTry: Kind = new Kind()
+    }
+
+    //##########################################################################
+}
diff --git a/src/msil/ch/epfl/lamp/compiler/msil/emit/LocalBuilder.scala b/src/msil/ch/epfl/lamp/compiler/msil/emit/LocalBuilder.scala
new file mode 100644
index 0000000..73bca46
--- /dev/null
+++ b/src/msil/ch/epfl/lamp/compiler/msil/emit/LocalBuilder.scala
@@ -0,0 +1,44 @@
+/**
+ * System.Reflection.Emit-like API for writing .NET assemblies to MSIL
+ */
+
+
+package ch.epfl.lamp.compiler.msil.emit
+
+import ch.epfl.lamp.compiler.msil.Type
+
+/**
+ * Represents a local variable within a method or constructor.
+ *
+ * @author Nikolay Mihaylov
+ * @version 1.0
+ */
+class LocalBuilder(_slot : Int, localType : Type) extends Visitable {
+
+    /**
+     * the type of the local variable.
+     */
+    var LocalType : Type = localType
+
+    // the name of the local variable
+    var name : String = "L_" + slot
+
+    // the slot occupied by this local in the corresponding ILGenerator
+    var slot : Int = _slot
+
+    /**
+     * Sets the name of this local variable.
+     */
+    def SetLocalSymInfo(name : String) {
+	    this.name = name
+    }
+
+    override def toString() : String = name
+
+    /**
+     * the apply method for a visitor
+     */
+    def apply(v : Visitor) {
+	    v.caseLocalBuilder(this)
+    }
+}
diff --git a/src/msil/ch/epfl/lamp/compiler/msil/emit/MethodBuilder.scala b/src/msil/ch/epfl/lamp/compiler/msil/emit/MethodBuilder.scala
new file mode 100644
index 0000000..237d8fd
--- /dev/null
+++ b/src/msil/ch/epfl/lamp/compiler/msil/emit/MethodBuilder.scala
@@ -0,0 +1,70 @@
+/*
+ * System.Reflection.Emit-like API for writing .NET assemblies to MSIL
+ */
+
+
+package ch.epfl.lamp.compiler.msil.emit
+
+import ch.epfl.lamp.compiler.msil.MethodInfo
+import ch.epfl.lamp.compiler.msil.ParameterInfo
+import ch.epfl.lamp.compiler.msil.Type
+import ch.epfl.lamp.compiler.msil.ConstructorInfo
+import java.io.IOException
+
+/**
+ * Defines and represents a method of a dynamic class.
+ *
+ * @author Nikolay Mihaylov
+ * @version 1.0
+ */
+class MethodBuilder(name: String, declType: Type, attrs: Int, returnType: Type, paramTypes: Array[Type])
+      extends MethodInfo(name, declType, attrs, returnType, paramTypes)
+      with ICustomAttributeSetter
+      with Visitable
+{
+
+    //##########################################################################
+    // public interface
+
+    /** Defines a parameter of this method. TODO: Parameters are indexed staring
+     *  from number 1 for the first parameter
+     */
+    def DefineParameter(pos: Int, attr: Int, name: String): ParameterBuilder = {
+	val param = new ParameterBuilder(name, params(pos).ParameterType, attr, pos)
+	params(pos) = param
+	return param
+    }
+
+    /** Returns an ILGenerator for this method. */
+    def GetILGenerator(): ILGenerator = {
+	if (ilGenerator == null)
+	    throw new RuntimeException
+		("No code generator available for this method: " + this)
+	return ilGenerator
+    }
+
+    /** Sets a custom attribute. */
+    def SetCustomAttribute(constr: ConstructorInfo, value: Array[Byte]) {
+	addCustomAttribute(constr, value)
+    }
+
+    //##########################################################################
+
+    /** The apply method for a visitor. */
+    @throws(classOf[IOException])
+    def apply(v: Visitor) {
+	v.caseMethodBuilder(this)
+    }
+
+    //##########################################################################
+
+    // the Intermediate Language Generator
+    // it contains the method's body
+    protected final val ilGenerator : ILGenerator =
+	  if (DeclaringType == null // global method
+	      || !DeclaringType.IsInterface())
+	      new ILGenerator(this)
+	  else null
+
+    //##########################################################################
+}
diff --git a/src/msil/ch/epfl/lamp/compiler/msil/emit/ModuleBuilder.scala b/src/msil/ch/epfl/lamp/compiler/msil/emit/ModuleBuilder.scala
new file mode 100644
index 0000000..a2d2848
--- /dev/null
+++ b/src/msil/ch/epfl/lamp/compiler/msil/emit/ModuleBuilder.scala
@@ -0,0 +1,133 @@
+/*
+ * System.Reflection.Emit-like API for writing .NET assemblies to MSIL
+ */
+
+
+package ch.epfl.lamp.compiler.msil.emit
+
+import ch.epfl.lamp.compiler.msil._
+import java.util.HashMap
+import java.util.ArrayList
+import java.io.IOException
+
+/**
+ * Defines and represents a module. Get an instance of ModuleBuilder
+ * by calling DefineDynamicModule
+ *
+ * @author Nikolay Mihaylov
+ * @version 1.0
+ */
+class ModuleBuilder(name: String, fullname: String, scopeName: String, assembly: Assembly)
+      extends Module(name, fullname, scopeName, assembly)
+      with ICustomAttributeSetter
+      with Visitable
+{
+
+    //##########################################################################
+    // public interface
+
+    /**
+     * Complete the global function definitions for this dynamic module.
+     * This method should be called when the user is done with defining
+     * all of the global functions within this dynamic module. After calling
+     * this function, no more new global functions or new global data are
+     * allowed.
+     */
+    def CreateGlobalFunctions() {
+	if (globalsCreated)
+	    throw new RuntimeException("Global functions are already created")
+	this.fields = fieldBuilders.toArray(fields).asInstanceOf[Array[FieldInfo]]
+	this.methods = methodBuilders.toArray(methods).asInstanceOf[Array[MethodInfo]]
+	globalsCreated = true
+    }
+
+    /**
+     * Constructs a TypeBuilder for a type with the specified name
+     */
+    def DefineType(typeName: String): TypeBuilder = {
+	return DefineType(typeName, 0, null, Type.EmptyTypes)
+    }
+
+    /**
+     * Constructs a TypeBuilder for a type with the specified name
+     * and specified attributes
+     */
+    def DefineType(typeName: String, attributes: Int): TypeBuilder = {
+	return DefineType(typeName, attributes, null, Type.EmptyTypes)
+    }
+
+    /**
+     * Constructs a TypeBuilder given type name, its attributes,
+     * and the type that the defined type extends.
+     */
+    def DefineType(typeName: String, attributes: Int,
+				  baseType: Type): TypeBuilder = {
+	return DefineType(typeName, attributes, baseType, Type.EmptyTypes)
+    }
+
+    /**
+     * Constructs a TypeBuilder given the Full specification of a type,
+     * Given the type name, attributes, the type that the defined type
+     * extends, and the interfaces that the defined type implements.
+     */
+    def DefineType(typeName: String,
+				  attributes: Int,
+				  baseType: Type,
+				  interfaces: Array[Type]): TypeBuilder =
+    {
+	var t: Type = GetType(typeName) // Module.GetType(String)
+	if (t != null)
+	    throw new RuntimeException
+		("Type [" + Assembly + "]" + typeName + "' already exists!")
+	val `type` =
+	    new TypeBuilder(this, attributes, typeName, baseType, interfaces, null)
+	addType(`type`)
+	return `type`
+    }
+
+    /**
+     * Defines a global method given its name, attributes, return type, and
+     * parameter types.
+     */
+    def DefineGlobalMethod(name: String, attributes: Int,
+					    returnType: Type, paramTypes: Array[Type]): MethodBuilder =
+    {
+	val method =
+	    new MethodBuilder(name, null, attributes, returnType, paramTypes)
+	methodBuilders.add(method)
+	return method
+    }
+
+
+    override def GetTypes(): Array[Type] = {
+	return typesMap.values().toArray(Type.EmptyTypes).asInstanceOf[Array[Type]]
+    }
+
+    /** Sets a custom attribute. */
+    def SetCustomAttribute(constr: ConstructorInfo, value: Array[Byte]) {
+	addCustomAttribute(constr, value)
+    }
+
+    //##########################################################################
+    // internal members
+
+    var globalsCreated = false
+    protected var fieldBuilders = new ArrayList[FieldInfo]()
+    protected var methodBuilders = new ArrayList[MethodInfo]()
+
+    override def addType(t: Type): Type = {
+	return super.addType(t)
+    }
+
+    //##########################################################################
+
+    /**
+     * the apply method for a visitor
+     */
+    @throws(classOf[IOException])
+    def apply(v: Visitor) {
+	v.caseModuleBuilder(this)
+    }
+
+    //##########################################################################
+}
diff --git a/src/msil/ch/epfl/lamp/compiler/msil/emit/MultipleFilesILPrinterVisitor.scala b/src/msil/ch/epfl/lamp/compiler/msil/emit/MultipleFilesILPrinterVisitor.scala
new file mode 100644
index 0000000..99ca08f
--- /dev/null
+++ b/src/msil/ch/epfl/lamp/compiler/msil/emit/MultipleFilesILPrinterVisitor.scala
@@ -0,0 +1,138 @@
+/*
+ * System.Reflection.Emit-like API for writing .NET assemblies in MSIL
+ */
+
+
+package ch.epfl.lamp.compiler.msil.emit
+
+import java.io.File
+import java.io.FileWriter
+import java.io.BufferedWriter
+import java.io.PrintWriter
+import java.io.IOException
+import java.util.Iterator
+import java.util.HashMap
+import java.util.Arrays
+
+import ch.epfl.lamp.compiler.msil._
+import ch.epfl.lamp.compiler.msil.emit
+import ch.epfl.lamp.compiler.msil.util.Table
+
+/**
+ * The MSIL printer Visitor. It prints a complete
+ * assembly into separate files. Then these files can be compiled by ilasm.
+ *
+ * @author Nikolay Mihaylov
+ * @author Daniel Lorch
+ * @version 1.0
+ */
+final class MultipleFilesILPrinterVisitor(destPath: String, sourceFilesPath: String) extends ILPrinterVisitor {
+   /**
+     * Visit an AssemblyBuilder
+     */
+    @throws(classOf[IOException])
+    def caseAssemblyBuilder(assemblyBuilder: AssemblyBuilder) {
+	ILPrinterVisitor.currAssembly = assemblyBuilder
+
+	// first get the entryPoint
+	this.entryPoint = assemblyBuilder.EntryPoint
+
+	// all external assemblies
+	as = assemblyBuilder.getExternAssemblies()
+	Arrays.sort(as, assemblyNameComparator)
+
+	// print each module
+	var m: Array[Module] = assemblyBuilder.GetModules()
+        nomembers = true
+        for(val i <- 0 until m.length) {
+	    print(m(i).asInstanceOf[ModuleBuilder])
+	}
+
+        nomembers = false
+        for(val i <- 0 until m.length) {
+	    print(m(i).asInstanceOf[ModuleBuilder])
+	}
+	ILPrinterVisitor.currAssembly = null
+    }
+
+    /**
+     * Visit a ModuleBuilder
+     */
+    @throws(classOf[IOException])
+    def caseModuleBuilder(module: ModuleBuilder) {
+    val assemblyBuilder = ILPrinterVisitor.currAssembly.asInstanceOf[AssemblyBuilder]
+
+	// print module declaration
+	currentModule = module
+
+	// global methods typically contain the main method
+	if (!module.globalsCreated)
+	    module.CreateGlobalFunctions()
+
+	var m: Array[MethodInfo] = module.GetMethods()
+
+	// "Types" contain all the classes
+	var t: Array[Type] = module.GetTypes()
+        for(val i <- 0 until t.length) {
+        val tBuilder       = t(i).asInstanceOf[TypeBuilder]
+        val sourceFilename = tBuilder.sourceFilename
+        val sourceFilepath = new File(tBuilder.sourceFilepath).getCanonicalPath
+        val sourcePath     = new File(sourceFilesPath).getCanonicalPath
+		var append         = false
+
+        if(!sourceFilepath.startsWith(sourcePath)) {
+            throw new IOException("Source file " + sourceFilename + " must lie inside sourcepath " + sourcePath)
+        }
+
+        assert(sourceFilepath.endsWith(".scala"), "Source file doesn't end with .scala")
+        val relativeFilename = sourceFilepath.substring(sourcePath.length, sourceFilepath.length() - 6) + ".msil"
+        val fileName         = new File(destPath, relativeFilename)
+        if(assemblyBuilder.generatedFiles.contains(fileName.getPath)) {
+            append = true
+        } else {
+            fileName.getParentFile().mkdirs()
+            assemblyBuilder.generatedFiles.add(fileName.getPath)
+        }
+
+	    out = new PrintWriter(new BufferedWriter(new FileWriter(fileName, append)))
+		// only write assembly boilerplate and class prototypes
+		if (!append && nomembers) {
+			printAssemblyBoilerplate()
+			
+			print(".module \'"); print(module.Name); println("\'")
+		    printAttributes(module)	
+        }
+
+	    print(t(i).asInstanceOf[TypeBuilder])
+	    out.close()
+	}
+	
+    // now write the global methods (typically contains the "main" method)
+	if(!nomembers) {
+       var globalMethods: File = new File(destPath, ILPrinterVisitor.currAssembly.GetName().Name + ".msil")
+       val append = assemblyBuilder.generatedFiles.contains(globalMethods.getPath)
+		
+		out = new PrintWriter(new BufferedWriter(new FileWriter(globalMethods, append)))
+
+        // make sure we're the first in the list (ilasm uses the first file name to guess the output file name)
+        assemblyBuilder.generatedFiles.add(0, globalMethods.getPath)
+
+		// if this file hasn't been created by one of the classes, write boilerplate
+		if(!append) {
+			printAssemblyBoilerplate()
+			
+			print(".module \'"); print(module.Name); println("\'")
+		    printAttributes(module)	
+		}
+
+                for(val i <- 0 until m.length) {
+	   		print(m(i).asInstanceOf[MethodBuilder])
+		}
+	
+		out.close()
+	}
+
+	currentModule = null
+    }
+
+}  // class MultipleFilesILPrinterVisitor
diff --git a/src/msil/ch/epfl/lamp/compiler/msil/emit/OpCode.scala b/src/msil/ch/epfl/lamp/compiler/msil/emit/OpCode.scala
new file mode 100644
index 0000000..e772943
--- /dev/null
+++ b/src/msil/ch/epfl/lamp/compiler/msil/emit/OpCode.scala
@@ -0,0 +1,1934 @@
+/*
+ * System.Reflection.Emit-like API for writing .NET assemblies to MSIL
+ */
+
+
+package ch.epfl.lamp.compiler.msil.emit
+
+import java.io.IOException
+
+/** Describes a Microsoft intermediate language (MSIL) instruction.
+ *
+ *  @author  Nikolay Mihaylov
+ *  @version 1.0
+ */
+class OpCode extends Visitable {
+    import OpCode._
+
+    /** The Operation Code of Microsoft intermediate language (MSIL) instruction. */
+    var CEE_opcode : Int = _
+
+    /** The name of the Microsoft intermediate language (MSIL) instruction. */
+    var CEE_string: String = _
+
+    /** The type of Microsoft intermediate language (MSIL) instruction. */
+    var CEE_code: Short = _
+
+    /** How the Microsoft intermediate language (MSIL) instruction pops the stack. */
+    var CEE_pop: Byte = _
+
+    /** How the Microsoft intermediate language (MSIL) instruction pushes operand onto the stack. */
+    var CEE_push: Byte = _
+
+    /** Describes the type of flow control. */
+    var CEE_flow: Byte = _
+
+    /** ????? */
+    var CEE_inline: Byte = _
+
+    var CEE_length: Byte = _
+
+    var CEE_popush: Byte = _
+
+    /**
+     * the apply method for a visitor
+     */
+    @throws(classOf[IOException])
+    def apply(v: Visitor) {
+	v.caseOpCode(this)
+    }
+
+    protected def length(): Byte = {
+	val code = OpCode.length(CEE_code)
+	val inline = OpCode.INLINE_length(CEE_inline)
+	return if(inline < 0) { -1 } else { (code + inline).toByte }
+    }
+
+    protected def popush(): Byte = {
+	val pop = OpCode.POP_size(CEE_pop)
+	val push = OpCode.PUSH_size(CEE_push)
+	return if(pop < 0 || push < 0) { OpCode.POPUSH_SPECIAL } else { (push - pop).toByte }
+    }
+
+    override def toString(): String = {
+	return CEE_string
+    }
+}
+
+object OpCode {
+
+    //########################################################################
+    // Common Execution Environment opcodes
+
+    final val CEE_NOP            : Int = 0x0000
+    final val CEE_BREAK          : Int = 0x0001
+    final val CEE_LDARG_0        : Int = 0x0002
+    final val CEE_LDARG_1        : Int = 0x0003
+    final val CEE_LDARG_2        : Int = 0x0004
+    final val CEE_LDARG_3        : Int = 0x0005
+    final val CEE_LDLOC_0        : Int = 0x0006
+    final val CEE_LDLOC_1        : Int = 0x0007
+    final val CEE_LDLOC_2        : Int = 0x0008
+    final val CEE_LDLOC_3        : Int = 0x0009
+    final val CEE_STLOC_0        : Int = 0x000A
+    final val CEE_STLOC_1        : Int = 0x000B
+    final val CEE_STLOC_2        : Int = 0x000C
+    final val CEE_STLOC_3        : Int = 0x000D
+    final val CEE_LDARG_S        : Int = 0x000E
+    final val CEE_LDARGA_S       : Int = 0x000F
+    final val CEE_STARG_S        : Int = 0x0010
+    final val CEE_LDLOC_S        : Int = 0x0011
+    final val CEE_LDLOCA_S       : Int = 0x0012
+    final val CEE_STLOC_S        : Int = 0x0013
+    final val CEE_LDNULL         : Int = 0x0014
+    final val CEE_LDC_I4_M1      : Int = 0x0015
+    final val CEE_LDC_I4_0       : Int = 0x0016
+    final val CEE_LDC_I4_1       : Int = 0x0017
+    final val CEE_LDC_I4_2       : Int = 0x0018
+    final val CEE_LDC_I4_3       : Int = 0x0019
+    final val CEE_LDC_I4_4       : Int = 0x001A
+    final val CEE_LDC_I4_5       : Int = 0x001B
+    final val CEE_LDC_I4_6       : Int = 0x001C
+    final val CEE_LDC_I4_7       : Int = 0x001D
+    final val CEE_LDC_I4_8       : Int = 0x001E
+    final val CEE_LDC_I4_S       : Int = 0x001F
+    final val CEE_LDC_I4         : Int = 0x0020
+    final val CEE_LDC_I8         : Int = 0x0021
+    final val CEE_LDC_R4         : Int = 0x0022
+    final val CEE_LDC_R8         : Int = 0x0023
+    final val CEE_UNUSED49       : Int = 0x0024
+    final val CEE_DUP            : Int = 0x0025
+    final val CEE_POP            : Int = 0x0026
+    final val CEE_JMP            : Int = 0x0027
+    final val CEE_CALL           : Int = 0x0028
+    final val CEE_CALLI          : Int = 0x0029
+    final val CEE_RET            : Int = 0x002A
+    final val CEE_BR_S           : Int = 0x002B
+    final val CEE_BRFALSE_S      : Int = 0x002C
+    final val CEE_BRTRUE_S       : Int = 0x002D
+    final val CEE_BEQ_S          : Int = 0x002E
+    final val CEE_BGE_S          : Int = 0x002F
+    final val CEE_BGT_S          : Int = 0x0030
+    final val CEE_BLE_S          : Int = 0x0031
+    final val CEE_BLT_S          : Int = 0x0032
+    final val CEE_BNE_UN_S       : Int = 0x0033
+    final val CEE_BGE_UN_S       : Int = 0x0034
+    final val CEE_BGT_UN_S       : Int = 0x0035
+    final val CEE_BLE_UN_S       : Int = 0x0036
+    final val CEE_BLT_UN_S       : Int = 0x0037
+    final val CEE_BR             : Int = 0x0038
+    final val CEE_BRFALSE        : Int = 0x0039
+    final val CEE_BRTRUE         : Int = 0x003A
+    final val CEE_BEQ            : Int = 0x003B
+    final val CEE_BGE            : Int = 0x003C
+    final val CEE_BGT            : Int = 0x003D
+    final val CEE_BLE            : Int = 0x003E
+    final val CEE_BLT            : Int = 0x003F
+    final val CEE_BNE_UN         : Int = 0x0040
+    final val CEE_BGE_UN         : Int = 0x0041
+    final val CEE_BGT_UN         : Int = 0x0042
+    final val CEE_BLE_UN         : Int = 0x0043
+    final val CEE_BLT_UN         : Int = 0x0044
+    final val CEE_SWITCH         : Int = 0x0045
+    final val CEE_LDIND_I1       : Int = 0x0046
+    final val CEE_LDIND_U1       : Int = 0x0047
+    final val CEE_LDIND_I2       : Int = 0x0048
+    final val CEE_LDIND_U2       : Int = 0x0049
+    final val CEE_LDIND_I4       : Int = 0x004A
+    final val CEE_LDIND_U4       : Int = 0x004B
+    final val CEE_LDIND_I8       : Int = 0x004C
+    final val CEE_LDIND_I        : Int = 0x004D
+    final val CEE_LDIND_R4       : Int = 0x004E
+    final val CEE_LDIND_R8       : Int = 0x004F
+    final val CEE_LDIND_REF      : Int = 0x0050
+    final val CEE_STIND_REF      : Int = 0x0051
+    final val CEE_STIND_I1       : Int = 0x0052
+    final val CEE_STIND_I2       : Int = 0x0053
+    final val CEE_STIND_I4       : Int = 0x0054
+    final val CEE_STIND_I8       : Int = 0x0055
+    final val CEE_STIND_R4       : Int = 0x0056
+    final val CEE_STIND_R8       : Int = 0x0057
+    final val CEE_ADD            : Int = 0x0058
+    final val CEE_SUB            : Int = 0x0059
+    final val CEE_MUL            : Int = 0x005A
+    final val CEE_DIV            : Int = 0x005B
+    final val CEE_DIV_UN         : Int = 0x005C
+    final val CEE_REM            : Int = 0x005D
+    final val CEE_REM_UN         : Int = 0x005E
+    final val CEE_AND            : Int = 0x005F
+    final val CEE_OR             : Int = 0x0060
+    final val CEE_XOR            : Int = 0x0061
+    final val CEE_SHL            : Int = 0x0062
+    final val CEE_SHR            : Int = 0x0063
+    final val CEE_SHR_UN         : Int = 0x0064
+    final val CEE_NEG            : Int = 0x0065
+    final val CEE_NOT            : Int = 0x0066
+    final val CEE_CONV_I1        : Int = 0x0067
+    final val CEE_CONV_I2        : Int = 0x0068
+    final val CEE_CONV_I4        : Int = 0x0069
+    final val CEE_CONV_I8        : Int = 0x006A
+    final val CEE_CONV_R4        : Int = 0x006B
+    final val CEE_CONV_R8        : Int = 0x006C
+    final val CEE_CONV_U4        : Int = 0x006D
+    final val CEE_CONV_U8        : Int = 0x006E
+    final val CEE_CALLVIRT       : Int = 0x006F
+    final val CEE_CPOBJ          : Int = 0x0070
+    final val CEE_LDOBJ          : Int = 0x0071
+    final val CEE_LDSTR          : Int = 0x0072
+    final val CEE_NEWOBJ         : Int = 0x0073
+    final val CEE_CASTCLASS      : Int = 0x0074
+    final val CEE_ISINST         : Int = 0x0075
+    final val CEE_CONV_R_UN      : Int = 0x0076
+    final val CEE_UNUSED58       : Int = 0x0077
+    final val CEE_UNUSED1        : Int = 0x0078
+    final val CEE_UNBOX          : Int = 0x0079
+    final val CEE_THROW          : Int = 0x007A
+    final val CEE_LDFLD          : Int = 0x007B
+    final val CEE_LDFLDA         : Int = 0x007C
+    final val CEE_STFLD          : Int = 0x007D
+    final val CEE_LDSFLD         : Int = 0x007E
+    final val CEE_LDSFLDA        : Int = 0x007F
+    final val CEE_STSFLD         : Int = 0x0080
+    final val CEE_STOBJ          : Int = 0x0081
+    final val CEE_CONV_OVF_I1_UN : Int = 0x0082
+    final val CEE_CONV_OVF_I2_UN : Int = 0x0083
+    final val CEE_CONV_OVF_I4_UN : Int = 0x0084
+    final val CEE_CONV_OVF_I8_UN : Int = 0x0085
+    final val CEE_CONV_OVF_U1_UN : Int = 0x0086
+    final val CEE_CONV_OVF_U2_UN : Int = 0x0087
+    final val CEE_CONV_OVF_U4_UN : Int = 0x0088
+    final val CEE_CONV_OVF_U8_UN : Int = 0x0089
+    final val CEE_CONV_OVF_I_UN  : Int = 0x008A
+    final val CEE_CONV_OVF_U_UN  : Int = 0x008B
+    final val CEE_BOX            : Int = 0x008C
+    final val CEE_NEWARR         : Int = 0x008D
+    final val CEE_LDLEN          : Int = 0x008E
+    final val CEE_LDELEMA        : Int = 0x008F
+    final val CEE_LDELEM_I1      : Int = 0x0090
+    final val CEE_LDELEM_U1      : Int = 0x0091
+    final val CEE_LDELEM_I2      : Int = 0x0092
+    final val CEE_LDELEM_U2      : Int = 0x0093
+    final val CEE_LDELEM_I4      : Int = 0x0094
+    final val CEE_LDELEM_U4      : Int = 0x0095
+    final val CEE_LDELEM_I8      : Int = 0x0096
+    final val CEE_LDELEM_I       : Int = 0x0097
+    final val CEE_LDELEM_R4      : Int = 0x0098
+    final val CEE_LDELEM_R8      : Int = 0x0099
+    final val CEE_LDELEM_REF     : Int = 0x009A
+    final val CEE_STELEM_I       : Int = 0x009B
+    final val CEE_STELEM_I1      : Int = 0x009C
+    final val CEE_STELEM_I2      : Int = 0x009D
+    final val CEE_STELEM_I4      : Int = 0x009E
+    final val CEE_STELEM_I8      : Int = 0x009F
+    final val CEE_STELEM_R4      : Int = 0x00A0
+    final val CEE_STELEM_R8      : Int = 0x00A1
+    final val CEE_STELEM_REF     : Int = 0x00A2
+    final val CEE_UNUSED2        : Int = 0x00A3
+    final val CEE_UNUSED3        : Int = 0x00A4
+    final val CEE_UNUSED4        : Int = 0x00A5
+    final val CEE_UNUSED5        : Int = 0x00A6
+    final val CEE_UNUSED6        : Int = 0x00A7
+    final val CEE_UNUSED7        : Int = 0x00A8
+    final val CEE_UNUSED8        : Int = 0x00A9
+    final val CEE_UNUSED9        : Int = 0x00AA
+    final val CEE_UNUSED10       : Int = 0x00AB
+    final val CEE_UNUSED11       : Int = 0x00AC
+    final val CEE_UNUSED12       : Int = 0x00AD
+    final val CEE_UNUSED13       : Int = 0x00AE
+    final val CEE_UNUSED14       : Int = 0x00AF
+    final val CEE_UNUSED15       : Int = 0x00B0
+    final val CEE_UNUSED16       : Int = 0x00B1
+    final val CEE_UNUSED17       : Int = 0x00B2
+    final val CEE_CONV_OVF_I1    : Int = 0x00B3
+    final val CEE_CONV_OVF_U1    : Int = 0x00B4
+    final val CEE_CONV_OVF_I2    : Int = 0x00B5
+    final val CEE_CONV_OVF_U2    : Int = 0x00B6
+    final val CEE_CONV_OVF_I4    : Int = 0x00B7
+    final val CEE_CONV_OVF_U4    : Int = 0x00B8
+    final val CEE_CONV_OVF_I8    : Int = 0x00B9
+    final val CEE_CONV_OVF_U8    : Int = 0x00BA
+    final val CEE_UNUSED50       : Int = 0x00BB
+    final val CEE_UNUSED18       : Int = 0x00BC
+    final val CEE_UNUSED19       : Int = 0x00BD
+    final val CEE_UNUSED20       : Int = 0x00BE
+    final val CEE_UNUSED21       : Int = 0x00BF
+    final val CEE_UNUSED22       : Int = 0x00C0
+    final val CEE_UNUSED23       : Int = 0x00C1
+    final val CEE_REFANYVAL      : Int = 0x00C2
+    final val CEE_CKFINITE       : Int = 0x00C3
+    final val CEE_UNUSED24       : Int = 0x00C4
+    final val CEE_UNUSED25       : Int = 0x00C5
+    final val CEE_MKREFANY       : Int = 0x00C6
+    final val CEE_UNUSED59       : Int = 0x00C7
+    final val CEE_UNUSED60       : Int = 0x00C8
+    final val CEE_UNUSED61       : Int = 0x00C9
+    final val CEE_UNUSED62       : Int = 0x00CA
+    final val CEE_UNUSED63       : Int = 0x00CB
+    final val CEE_UNUSED64       : Int = 0x00CC
+    final val CEE_UNUSED65       : Int = 0x00CD
+    final val CEE_UNUSED66       : Int = 0x00CE
+    final val CEE_UNUSED67       : Int = 0x00CF
+    final val CEE_LDTOKEN        : Int = 0x00D0
+    final val CEE_CONV_U2        : Int = 0x00D1
+    final val CEE_CONV_U1        : Int = 0x00D2
+    final val CEE_CONV_I         : Int = 0x00D3
+    final val CEE_CONV_OVF_I     : Int = 0x00D4
+    final val CEE_CONV_OVF_U     : Int = 0x00D5
+    final val CEE_ADD_OVF        : Int = 0x00D6
+    final val CEE_ADD_OVF_UN     : Int = 0x00D7
+    final val CEE_MUL_OVF        : Int = 0x00D8
+    final val CEE_MUL_OVF_UN     : Int = 0x00D9
+    final val CEE_SUB_OVF        : Int = 0x00DA
+    final val CEE_SUB_OVF_UN     : Int = 0x00DB
+    final val CEE_ENDFINALLY     : Int = 0x00DC
+    final val CEE_LEAVE          : Int = 0x00DD
+    final val CEE_LEAVE_S        : Int = 0x00DE
+    final val CEE_STIND_I        : Int = 0x00DF
+    final val CEE_CONV_U         : Int = 0x00E0
+    final val CEE_UNUSED26       : Int = 0x00E1
+    final val CEE_UNUSED27       : Int = 0x00E2
+    final val CEE_UNUSED28       : Int = 0x00E3
+    final val CEE_UNUSED29       : Int = 0x00E4
+    final val CEE_UNUSED30       : Int = 0x00E5
+    final val CEE_UNUSED31       : Int = 0x00E6
+    final val CEE_UNUSED32       : Int = 0x00E7
+    final val CEE_UNUSED33       : Int = 0x00E8
+    final val CEE_UNUSED34       : Int = 0x00E9
+    final val CEE_UNUSED35       : Int = 0x00EA
+    final val CEE_UNUSED36       : Int = 0x00EB
+    final val CEE_UNUSED37       : Int = 0x00EC
+    final val CEE_UNUSED38       : Int = 0x00ED
+    final val CEE_UNUSED39       : Int = 0x00EE
+    final val CEE_UNUSED40       : Int = 0x00EF
+    final val CEE_UNUSED41       : Int = 0x00F0
+    final val CEE_UNUSED42       : Int = 0x00F1
+    final val CEE_UNUSED43       : Int = 0x00F2
+    final val CEE_UNUSED44       : Int = 0x00F3
+    final val CEE_UNUSED45       : Int = 0x00F4
+    final val CEE_UNUSED46       : Int = 0x00F5
+    final val CEE_UNUSED47       : Int = 0x00F6
+    final val CEE_UNUSED48       : Int = 0x00F7
+    final val CEE_PREFIX7        : Int = 0x00F8
+    final val CEE_PREFIX6        : Int = 0x00F9
+    final val CEE_PREFIX5        : Int = 0x00FA
+    final val CEE_PREFIX4        : Int = 0x00FB
+    final val CEE_PREFIX3        : Int = 0x00FC
+    final val CEE_PREFIX2        : Int = 0x00FD
+    final val CEE_PREFIX1        : Int = 0x00FE
+    final val CEE_PREFIXREF      : Int = 0x00FF
+
+    final val CEE_ARGLIST         : Int = 0x0100
+    final val CEE_CEQ             : Int = 0x0101
+    final val CEE_CGT             : Int = 0x0102
+    final val CEE_CGT_UN          : Int = 0x0103
+    final val CEE_CLT             : Int = 0x0104
+    final val CEE_CLT_UN          : Int = 0x0105
+    final val CEE_LDFTN           : Int = 0x0106
+    final val CEE_LDVIRTFTN       : Int = 0x0107
+    final val CEE_UNUSED56        : Int = 0x0108
+    final val CEE_LDARG           : Int = 0x0109
+    final val CEE_LDARGA          : Int = 0x010A
+    final val CEE_STARG           : Int = 0x010B
+    final val CEE_LDLOC           : Int = 0x010C
+    final val CEE_LDLOCA          : Int = 0x010D
+    final val CEE_STLOC           : Int = 0x010E
+    final val CEE_LOCALLOC        : Int = 0x010F
+    final val CEE_UNUSED57        : Int = 0x0110
+    final val CEE_ENDFILTER       : Int = 0x0111
+    final val CEE_UNALIGNED       : Int = 0x0112
+    final val CEE_VOLATILE        : Int = 0x0113
+    final val CEE_TAILCALL        : Int = 0x0114
+    final val CEE_INITOBJ         : Int = 0x0115
+    final val CEE_UNUSED68        : Int = 0x0116
+    final val CEE_CPBLK           : Int = 0x0117
+    final val CEE_INITBLK         : Int = 0x0118
+    final val CEE_UNUSED69        : Int = 0x0119
+    final val CEE_RETHROW         : Int = 0x011A
+    final val CEE_UNUSED51        : Int = 0x011B
+    final val CEE_SIZEOF          : Int = 0x011C
+    final val CEE_REFANYTYPE      : Int = 0x011D
+    final val CEE_UNUSED52        : Int = 0x011E
+    final val CEE_UNUSED53        : Int = 0x011F
+    final val CEE_UNUSED54        : Int = 0x0120
+    final val CEE_UNUSED55        : Int = 0x0121
+    final val CEE_UNUSED70        : Int = 0x0122
+
+    final val CEE_ILLEGAL         : Int = 0x0140
+    final val CEE_MACRO_END       : Int = 0x0141
+
+    final val CEE_BRNULL          : Int = 0x0180 // CEE_BRFALSE
+    final val CEE_BRNULL_S        : Int = 0x0181 // CEE_BRFALSE_S
+    final val CEE_BRZERO          : Int = 0x0182 // CEE_BRFALSE
+    final val CEE_BRZERO_S        : Int = 0x0183 // CEE_BRFALSE_S
+    final val CEE_BRINST          : Int = 0x0184 // CEE_BRTRUE
+    final val CEE_BRINST_S        : Int = 0x0185 // CEE_BRTRUE_S
+    final val CEE_LDIND_U8        : Int = 0x0186 // CEE_LDIND_I8
+    final val CEE_LDELEM_U8       : Int = 0x0187 // CEE_LDELEM_I8
+    final val CEE_LDC_I4_M1x      : Int = 0x0188 // CEE_LDC_I4_M1
+    final val CEE_ENDFAULT        : Int = 0x0189 // CEE_ENDFINALLY
+
+    final val CEE_BRNONZERO       : Int = 0x01C0 // CEE_BRTRUE
+    final val CEE_BRNONZERO_S     : Int = 0x01C1 // CEE_BRTRUE_S
+
+    final val CEE_BRNOT           : Int = 0x01C2
+    final val CEE_BRNOT_S         : Int = 0x01C3
+    final val CEE_NOCODE          : Int = 0x01C4
+
+    final val CEE_count           : Int = 0x0200
+
+
+    //########################################################################
+    // Opcode's amount and type of poped data
+
+    final val POP_NONE          : Byte        = 0x00
+    final val POP_1             : Byte        = 0x01
+    final val POP_1_1           : Byte        = 0x02
+    final val POP_I             : Byte        = 0x03
+    final val POP_I_1           : Byte        = 0x04
+    final val POP_I_I           : Byte        = 0x05
+    final val POP_I_I8          : Byte        = 0x06
+    final val POP_I_R4          : Byte        = 0x07
+    final val POP_I_R8          : Byte        = 0x08
+    final val POP_I_I_I         : Byte        = 0x09
+    final val POP_REF           : Byte        = 0x0A
+    final val POP_REF_1         : Byte        = 0x0B
+    final val POP_REF_I         : Byte        = 0x0C
+    final val POP_REF_I_I       : Byte        = 0x0D
+    final val POP_REF_I_I8      : Byte        = 0x0E
+    final val POP_REF_I_R4      : Byte        = 0x0F
+    final val POP_REF_I_R8      : Byte        = 0x10
+    final val POP_REF_I_REF     : Byte        = 0x11
+    final val POP_SPECIAL       : Byte        = 0x12
+    final val POP_count         : Int         = 0x13
+    final val POP_size          : Array[Byte] = new Array[Byte](POP_count)
+
+	POP_size(POP_NONE)              =  0
+	POP_size(POP_1)                 =  1
+	POP_size(POP_1_1)               =  2
+	POP_size(POP_I)                 =  1
+	POP_size(POP_I_1)               =  2
+	POP_size(POP_I_I)               =  2
+	POP_size(POP_I_I8)              =  2
+	POP_size(POP_I_R4)              =  2
+	POP_size(POP_I_R8)              =  2
+	POP_size(POP_I_I_I)             =  3
+	POP_size(POP_REF)               =  1
+	POP_size(POP_REF_1)             =  2
+	POP_size(POP_REF_I)             =  2
+	POP_size(POP_REF_I_I)           =  3
+	POP_size(POP_REF_I_I8)          =  3
+	POP_size(POP_REF_I_R4)          =  3
+	POP_size(POP_REF_I_R8)          =  3
+	POP_size(POP_REF_I_REF)         =  3
+	POP_size(POP_SPECIAL)           = -1
+
+    //########################################################################
+    // Opcode's amount and type of pushed data
+
+    final val PUSH_NONE         : Byte        = 0x00
+    final val PUSH_1            : Byte        = 0x01
+    final val PUSH_1_1          : Byte        = 0x02
+    final val PUSH_I            : Byte        = 0x03
+    final val PUSH_I8           : Byte        = 0x04
+    final val PUSH_R4           : Byte        = 0x05
+    final val PUSH_R8           : Byte        = 0x06
+    final val PUSH_REF          : Byte        = 0x07
+    final val PUSH_SPECIAL      : Byte        = 0x08
+    final val PUSH_count        : Int         = 0x09
+    final val PUSH_size         : Array[Byte] = new Array[Byte](PUSH_count)
+  
+	PUSH_size(PUSH_NONE)             =  0
+	PUSH_size(PUSH_1)                =  1
+	PUSH_size(PUSH_1_1)              =  2
+	PUSH_size(PUSH_I)                =  1
+	PUSH_size(PUSH_I8)               =  1
+	PUSH_size(PUSH_R4)               =  1
+	PUSH_size(PUSH_R8)               =  1
+	PUSH_size(PUSH_REF)              =  1
+	PUSH_size(PUSH_SPECIAL)          = -1
+
+    //########################################################################
+    // Opcode's amount of moved data
+
+    final val POPUSH_SPECIAL    : Byte        = -128
+
+    //########################################################################
+    // Opcode's inline argument types
+
+    final val INLINE_NONE       : Byte        = 0x00
+    final val INLINE_VARIABLE_S : Byte        = 0x01
+    final val INLINE_TARGET_S   : Byte        = 0x02
+    final val INLINE_I_S        : Byte        = 0x03
+    final val INLINE_VARIABLE   : Byte        = 0x04
+    final val INLINE_TARGET     : Byte        = 0x05
+    final val INLINE_I          : Byte        = 0x06
+    final val INLINE_I8         : Byte        = 0x07
+    final val INLINE_R          : Byte        = 0x08
+    final val INLINE_R8         : Byte        = 0x09
+    final val INLINE_STRING     : Byte        = 0x0A
+    final val INLINE_TYPE       : Byte        = 0x0B
+    final val INLINE_FIELD      : Byte        = 0x0C
+    final val INLINE_METHOD     : Byte        = 0x0D
+    final val INLINE_SIGNATURE  : Byte        = 0x0E
+    final val INLINE_TOKEN      : Byte        = 0x0F
+    final val INLINE_SWITCH     : Byte        = 0x10
+    final val INLINE_count      : Int         = 0x11
+    final val INLINE_length     : Array[Byte] = new Array[Byte](INLINE_count)
+
+	INLINE_length(INLINE_NONE)       =  0
+	INLINE_length(INLINE_VARIABLE_S) =  1
+	INLINE_length(INLINE_TARGET_S)   =  1
+	INLINE_length(INLINE_I_S)        =  1
+	INLINE_length(INLINE_VARIABLE)   =  2
+	INLINE_length(INLINE_TARGET)     =  4
+	INLINE_length(INLINE_I)          =  4
+	INLINE_length(INLINE_I8)         =  8
+	INLINE_length(INLINE_R)          =  4
+	INLINE_length(INLINE_R8)         =  8
+	INLINE_length(INLINE_STRING)     =  4
+	INLINE_length(INLINE_TYPE)       =  4
+	INLINE_length(INLINE_FIELD)      =  4
+	INLINE_length(INLINE_METHOD)     =  4
+	INLINE_length(INLINE_SIGNATURE)  =  4
+	INLINE_length(INLINE_SWITCH)     =  4
+	INLINE_length(INLINE_TOKEN)      =  4
+
+    //########################################################################
+    // Opcode's control flow implications
+
+    final val FLOW_META         : Byte = 0x00
+    final val FLOW_NEXT         : Byte = 0x01
+    final val FLOW_BRANCH       : Byte = 0x02
+    final val FLOW_COND_BRANCH  : Byte = 0x03
+    final val FLOW_BREAK        : Byte = 0x04
+    final val FLOW_CALL         : Byte = 0x05
+    final val FLOW_RETURN       : Byte = 0x06
+    final val FLOW_THROW        : Byte = 0x07
+    final val FLOW_count        : Int  = 0x08
+
+    //########################################################################
+    // Init methods for Opcode
+
+    def opcode(that: OpCode, opcode: Int, string: String, code: Int,
+			pop: Byte, push: Byte, inline: Byte, flow: Byte) {
+	that.CEE_opcode = opcode
+	that.CEE_string = string
+	that.CEE_code = code.toShort
+	that.CEE_pop = pop
+	that.CEE_push = push
+	that.CEE_inline = inline
+	that.CEE_flow = flow
+	that.CEE_length = that.length()
+	that.CEE_popush = that.popush()
+    }
+
+    def length(code: Int): Byte = {
+	if ((code & 0xFFFFFF00) == 0xFFFFFF00) return 1
+	if ((code & 0xFFFFFF00) == 0xFFFFFE00) return 2
+	return 0
+    }
+
+    //########################################################################
+    // case OpCode
+
+    /**
+     * Adds two values and pushes the result onto the evaluation stack.
+     */
+    final val Add = new OpCode()
+    opcode(Add, CEE_ADD, "add", 0xFFFFFF58, POP_1_1, PUSH_1, INLINE_NONE, FLOW_NEXT)	
+
+    /**
+     * Fills space if bytecodes are patched. No meaningful operation is performed
+     * although a processing cycle can be consumed.
+     */
+    final val Nop = new OpCode()
+	opcode(Nop, CEE_NOP, "nop", 0xFFFFFF00, POP_NONE, PUSH_NONE, INLINE_NONE , FLOW_NEXT)
+
+    /**
+     * Signals the Common Language Infrastructure (CLI) to inform the debugger that
+     * a break point has been tripped.
+     */
+    final val Break = new OpCode()
+	opcode(Break, CEE_BREAK, "break"    , 0xFFFFFF01, POP_NONE, PUSH_NONE   , INLINE_NONE , FLOW_BREAK)
+
+    /**
+     * Loads the argument at index 0 onto the evaluation stack.
+     */
+    final val Ldarg_0 = new OpCode()
+	opcode(Ldarg_0, CEE_LDARG_0  , "ldarg.0"  , 0xFFFFFF02, POP_NONE, PUSH_1 , INLINE_NONE , FLOW_NEXT)
+
+    /**
+     * Loads the argument at index 1 onto the evaluation stack.
+     */
+    final val Ldarg_1 = new OpCode()
+	opcode(Ldarg_1, CEE_LDARG_1  , "ldarg.1"  , 0xFFFFFF03, POP_NONE, PUSH_1 , INLINE_NONE , FLOW_NEXT)
+
+    /**
+     * Loads the argument at index 2 onto the evaluation stack.
+     */
+    final val Ldarg_2 = new OpCode()
+	opcode(Ldarg_2, CEE_LDARG_2  , "ldarg.2"  , 0xFFFFFF04, POP_NONE, PUSH_1 , INLINE_NONE , FLOW_NEXT)
+
+    /**
+     * Loads the argument at index 3 onto the evaluation stack.
+     */
+    final val Ldarg_3 = new OpCode()
+	opcode(Ldarg_3, CEE_LDARG_3  , "ldarg.3"  , 0xFFFFFF05, POP_NONE, PUSH_1 , INLINE_NONE , FLOW_NEXT)
+
+    /**
+     * Loads the local variable at index 0 onto the evaluation stack.
+     */
+    final val Ldloc_0 = new OpCode()
+	opcode(Ldloc_0, CEE_LDLOC_0  , "ldloc.0"  , 0xFFFFFF06, POP_NONE, PUSH_1 , INLINE_NONE , FLOW_NEXT)
+
+    /**
+     * Loads the local variable at index 1 onto the evaluation stack.
+     */
+    final val Ldloc_1 = new OpCode()
+	opcode(Ldloc_1, CEE_LDLOC_1  , "ldloc.1"  , 0xFFFFFF07, POP_NONE, PUSH_1 , INLINE_NONE , FLOW_NEXT)
+
+    /**
+     * Loads the local variable at index 2 onto the evaluation stack.
+     */
+    final val Ldloc_2 = new OpCode()
+	opcode(Ldloc_2, CEE_LDLOC_2  , "ldloc.2"  , 0xFFFFFF08, POP_NONE, PUSH_1 , INLINE_NONE , FLOW_NEXT)
+
+    /**
+     * Loads the local variable at index 3 onto the evaluation stack.
+     */
+    final val Ldloc_3 = new OpCode()
+	opcode(Ldloc_3, CEE_LDLOC_3  , "ldloc.3"  , 0xFFFFFF09, POP_NONE, PUSH_1 , INLINE_NONE , FLOW_NEXT)
+
+    /**
+     * Pops the current value from the top of the evaluation stack and
+     * stores it in a the local variable list at index 0.
+     */
+    final val Stloc_0 = new OpCode()
+	opcode(Stloc_0, CEE_STLOC_0  , "stloc.0"  , 0xFFFFFF0A, POP_1   , PUSH_NONE, INLINE_NONE , FLOW_NEXT)
+
+    /**
+     * Pops the current value from the top of the evaluation stack and
+     * stores it in a the local variable list at index 1.
+     */
+    final val Stloc_1 = new OpCode()
+	opcode(Stloc_1, CEE_STLOC_1  , "stloc.1"  , 0xFFFFFF0B, POP_1   , PUSH_NONE, INLINE_NONE , FLOW_NEXT)
+
+    /**
+     * Pops the current value from the top of the evaluation stack and
+     * stores it in a the local variable list at index 2.
+     */
+    final val Stloc_2 = new OpCode()
+	opcode(Stloc_2, CEE_STLOC_2  , "stloc.2"  , 0xFFFFFF0C, POP_1   , PUSH_NONE, INLINE_NONE , FLOW_NEXT)
+
+    /**
+     * Pops the current value from the top of the evaluation stack and
+     * stores it in a the local variable list at index 3.
+     */
+    final val Stloc_3 = new OpCode()
+	opcode(Stloc_3, CEE_STLOC_3  , "stloc.3"  , 0xFFFFFF0D, POP_1   , PUSH_NONE, INLINE_NONE , FLOW_NEXT)
+
+    /**
+     * Loads the argument (referenced by a specified short form index)
+     * onto the evaluation stack.
+     */
+    final val Ldarg_S = new OpCode()
+	opcode(Ldarg_S, CEE_LDARG_S  , "ldarg.s"  , 0xFFFFFF0E, POP_NONE, PUSH_1 , INLINE_VARIABLE_S, FLOW_NEXT)
+
+    /**
+     * Load an argument address, in short form, onto the evaluation stack.
+     */
+    final val Ldarga_S = new OpCode()
+	opcode(Ldarga_S, CEE_LDARGA_S , "ldarga.s" , 0xFFFFFF0F, POP_NONE, PUSH_I , INLINE_VARIABLE_S, FLOW_NEXT)
+
+    /**
+     * Loads the local variable at a specific index onto the evaluation stack,
+     * short form.
+     */
+    final val Ldloc_S = new OpCode()
+	opcode(Ldloc_S, CEE_LDLOC_S  , "ldloc.s"  , 0xFFFFFF11, POP_NONE, PUSH_1 , INLINE_VARIABLE_S, FLOW_NEXT)
+
+    /**
+     * Loads the address of the local variable at a specific index onto
+     * the evaluation stack, short form.
+     */
+    final val Ldloca_S = new OpCode()
+	opcode(Ldloca_S, CEE_LDLOCA_S , "ldloca.s" , 0xFFFFFF12, POP_NONE, PUSH_I , INLINE_VARIABLE_S, FLOW_NEXT)
+
+    /**
+     * Stores the value on top of the evaluation stack in the argument slot
+     * at a specified index, short form.
+     */
+    final val Starg_S = new OpCode()
+	opcode(Starg_S, CEE_STARG_S  , "starg.s"  , 0xFFFFFF10, POP_1   , PUSH_NONE , INLINE_VARIABLE_S, FLOW_NEXT)
+
+    /**
+     * Pops the current value from the top of the evaluation stack and stores it
+     * in a the local variable list at index (short form).
+     */
+    final val Stloc_S = new OpCode()
+	opcode(Stloc_S, CEE_STLOC_S  , "stloc.s"  , 0xFFFFFF13, POP_1   , PUSH_NONE, INLINE_VARIABLE_S, FLOW_NEXT)
+
+    /**
+     * Pushes a null reference (type O) onto the evaluation stack.
+     */
+    final val Ldnull = new OpCode()
+	opcode(Ldnull, CEE_LDNULL   , "ldnull"   , 0xFFFFFF14, POP_NONE, PUSH_REF , INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Pushes the integer value of -1 onto the evaluation stack as an int32.  
+     */
+    final val Ldc_I4_M1 = new OpCode()
+	opcode(Ldc_I4_M1, CEE_LDC_I4_M1, "ldc.i4.m1", 0xFFFFFF15, POP_NONE, PUSH_I, INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Pushes the integer value of 0 onto the evaluation stack as an int32. 
+     */
+    final val Ldc_I4_0 = new OpCode()
+	opcode(Ldc_I4_0, CEE_LDC_I4_0 , "ldc.i4.0" , 0xFFFFFF16, POP_NONE, PUSH_I, INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Pushes the integer value of 1 onto the evaluation stack as an int32. 
+     */
+    final val Ldc_I4_1 = new OpCode()
+	opcode(Ldc_I4_1, CEE_LDC_I4_1 , "ldc.i4.1" , 0xFFFFFF17, POP_NONE, PUSH_I, INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Pushes the integer value of 2 onto the evaluation stack as an int32. 
+     */
+    final val Ldc_I4_2 = new OpCode()
+	opcode(Ldc_I4_2, CEE_LDC_I4_2 , "ldc.i4.2" , 0xFFFFFF18, POP_NONE, PUSH_I, INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Pushes the integer value of 3 onto the evaluation stack as an int32. 
+     */
+    final val Ldc_I4_3 = new OpCode()
+	opcode(Ldc_I4_3, CEE_LDC_I4_3 , "ldc.i4.3" , 0xFFFFFF19, POP_NONE, PUSH_I, INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Pushes the integer value of 4 onto the evaluation stack as an int32.  
+     */
+    final val Ldc_I4_4 = new OpCode()
+	opcode(Ldc_I4_4, CEE_LDC_I4_4 , "ldc.i4.4" , 0xFFFFFF1A, POP_NONE, PUSH_I, INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Pushes the integer value of 5 onto the evaluation stack as an int32. 
+     */
+    final val Ldc_I4_5 = new OpCode()
+	opcode(Ldc_I4_5, CEE_LDC_I4_5 , "ldc.i4.5" , 0xFFFFFF1B, POP_NONE, PUSH_I, INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Pushes the integer value of 6 onto the evaluation stack as an int32.
+     */
+    final val Ldc_I4_6 = new OpCode()
+	opcode(Ldc_I4_6, CEE_LDC_I4_6 , "ldc.i4.6", 0xFFFFFF1C, POP_NONE, PUSH_I, INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Pushes the integer value of 7 onto the evaluation stack as an int32. 
+     */
+    final val Ldc_I4_7 = new OpCode()
+	opcode(Ldc_I4_7, CEE_LDC_I4_7 , "ldc.i4.7", 0xFFFFFF1D, POP_NONE   , PUSH_I, INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Pushes the integer value of 8 onto the evaluation stack as an int32. 
+     */
+    final val Ldc_I4_8 = new OpCode()
+	opcode(Ldc_I4_8, CEE_LDC_I4_8 , "ldc.i4.8", 0xFFFFFF1E, POP_NONE   , PUSH_I, INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Pushes the supplied int8 value onto the evaluation stack as an int32, short form.
+     */
+    final val Ldc_I4_S = new OpCode()
+	opcode(Ldc_I4_S, CEE_LDC_I4_S , "ldc.i4.s", 0xFFFFFF1F, POP_NONE   , PUSH_I, INLINE_I_S, FLOW_NEXT)
+
+    /**
+     * Pushes a supplied value of type int32 onto the evaluation stack as an int32. 
+     */
+    final val Ldc_I4 = new OpCode()
+	opcode(Ldc_I4, CEE_LDC_I4, "ldc.i4"  , 0xFFFFFF20, POP_NONE   , PUSH_I, INLINE_I  , FLOW_NEXT)
+
+    /**
+     *  Pushes a supplied value of type int64 onto the evaluation stack as an int64.  
+     */
+    final val Ldc_I8 = new OpCode()
+	opcode(Ldc_I8, CEE_LDC_I8, "ldc.i8"  , 0xFFFFFF21, POP_NONE   , PUSH_I8, INLINE_I8 , FLOW_NEXT)
+
+    /**
+     * Pushes a supplied value of type float32 onto the evaluation stack as type F (float). 
+     */
+    final val Ldc_R4 = new OpCode()
+	opcode(Ldc_R4, CEE_LDC_R4, "ldc.r4"  , 0xFFFFFF22, POP_NONE   , PUSH_R4, INLINE_R  , FLOW_NEXT)
+
+    /**
+     * Pushes a supplied value of type float64 onto the evaluation stack as type F (float). 
+     */
+    final val Ldc_R8 = new OpCode()
+	opcode(Ldc_R8, CEE_LDC_R8, "ldc.r8"  , 0xFFFFFF23, POP_NONE   , PUSH_R8, INLINE_R8 , FLOW_NEXT)
+
+    /**
+     * Copies the current topmost value on the evaluation stack, and then pushes the copy 
+     * onto the evaluation stack. 
+     */
+    final val Dup = new OpCode()
+	opcode(Dup, CEE_DUP , "dup"     , 0xFFFFFF25, POP_1      , PUSH_1_1 , INLINE_NONE  , FLOW_NEXT)
+
+    /**
+     * Removes the value currently on top of the evaluation stack. 
+     */
+    final val Pop = new OpCode()
+	opcode(Pop, CEE_POP , "pop"     , 0xFFFFFF26, POP_1      , PUSH_NONE , INLINE_NONE  , FLOW_NEXT)
+ 
+    /**
+     * Exits current method and jumps to specified method. 
+     */
+    final val Jmp = new OpCode()
+	opcode(Jmp, CEE_JMP , "jmp"     , 0xFFFFFF27, POP_NONE   , PUSH_NONE , INLINE_METHOD, FLOW_CALL)
+
+    /**
+     * Calls the method indicated by the passed method descriptor. 
+     */
+    final val Call = new OpCode()
+	opcode(Call, CEE_CALL , "call"    , 0xFFFFFF28, POP_SPECIAL, PUSH_SPECIAL, INLINE_METHOD    , FLOW_CALL)
+
+    /**
+     * Calls the method indicated on the evaluation stack (as a pointer to an entry point) 
+     * with arguments described by a calling convention. 
+     */
+    final val Calli = new OpCode()
+	opcode(Calli, CEE_CALLI, "calli"   , 0xFFFFFF29, POP_SPECIAL, PUSH_SPECIAL, INLINE_SIGNATURE , FLOW_CALL)
+
+    /**
+     * Returns from the current method, pushing a return value (if present) from the caller's 
+     * evaluation stack onto the callee's evaluation stack. 
+     */
+    final val Ret = new OpCode()
+	opcode(Ret, CEE_RET  , "ret"     , 0xFFFFFF2A, POP_SPECIAL, PUSH_NONE, INLINE_NONE      , FLOW_RETURN)
+ 
+    /**
+     * Unconditionally transfers control to a target instruction (short form). 
+     */
+    final val Br_S = new OpCode()
+	opcode(Br_S, CEE_BR_S , "br.s"    , 0xFFFFFF2B, POP_NONE, PUSH_NONE, INLINE_TARGET_S  , FLOW_BRANCH)
+
+    /**
+     * Transfers control to a target instruction if value is false, a null reference, or zero. 
+     */
+    final val Brfalse_S = new OpCode()
+	opcode(Brfalse_S, CEE_BRFALSE_S,"brfalse.s", 0xFFFFFF2C, POP_I, PUSH_NONE, INLINE_TARGET_S, FLOW_COND_BRANCH)
+
+    /**
+     * Transfers control to a target instruction (short form) if value is true, not null, or non-zero. 
+     */
+    final val Brtrue_S = new OpCode()
+	opcode(Brtrue_S, CEE_BRTRUE_S , "brtrue.s", 0xFFFFFF2D, POP_I, PUSH_NONE, INLINE_TARGET_S, FLOW_COND_BRANCH)
+
+    /**
+     * Transfers control to a target instruction (short form) if two values are equal.
+     */
+    final val Beq_S = new OpCode()
+	opcode(Beq_S, CEE_BEQ_S, "beq.s", 0xFFFFFF2E, POP_1_1 , PUSH_NONE, INLINE_TARGET_S  , FLOW_COND_BRANCH)
+
+    /**
+     * Transfers control to a target instruction (short form) if the first value is greater than 
+     * or equal to the second value. 
+     */
+    final val Bge_S = new OpCode()
+	opcode(Bge_S, CEE_BGE_S, "bge.s", 0xFFFFFF2F, POP_1_1 , PUSH_NONE, INLINE_TARGET_S, FLOW_COND_BRANCH)
+
+    /**
+     * Transfers control to a target instruction (short form) if the first value is greater than 
+     * the second value. 
+     */
+    final val Bgt_S = new OpCode()
+	opcode(Bgt_S, CEE_BGT_S, "bgt.s"    , 0xFFFFFF30, POP_1_1 , PUSH_NONE, INLINE_TARGET_S  , FLOW_COND_BRANCH)
+
+    /**
+     * Transfers control to a target instruction (short form) if the first value is less than 
+     * or equal to the second value.
+     */
+    final val Ble_S = new OpCode()
+	opcode(Ble_S, CEE_BLE_S, "ble.s"    , 0xFFFFFF31, POP_1_1 , PUSH_NONE, INLINE_TARGET_S  , FLOW_COND_BRANCH)
+
+    /**
+     * Transfers control to a target instruction (short form) if the first value is less than 
+     * the second value. 
+     */
+    final val Blt_S = new OpCode()
+	opcode(Blt_S, CEE_BLT_S, "blt.s", 0xFFFFFF32, POP_1_1, PUSH_NONE, INLINE_TARGET_S, FLOW_COND_BRANCH)
+
+    /**
+     * Transfers control to a target instruction (short form) when two unsigned integer values 
+     * or unordered float values are not equal. 
+     */
+    final val Bne_Un_S = new OpCode()
+	opcode(Bne_Un_S, CEE_BNE_UN_S, "bne.un.s", 0xFFFFFF33, POP_1_1 , PUSH_NONE, INLINE_TARGET_S, FLOW_COND_BRANCH)
+
+    /**
+     * Transfers control to a target instruction (short form) if if the the first value is greather 
+     * than the second value, when comparing unsigned integer values or unordered float values. 
+     */
+    final val Bge_Un_S = new OpCode()
+	opcode(Bge_Un_S, CEE_BGE_UN_S, "bge.un.s", 0xFFFFFF34, POP_1_1, PUSH_NONE, INLINE_TARGET_S, FLOW_COND_BRANCH)
+
+    /**
+     * Transfers control to a target instruction (short form) if the first value is greater than 
+     * the second value, when comparing unsigned integer values or unordered float values. 
+     */
+    final val Bgt_Un_S = new OpCode()
+	opcode(Bgt_Un_S, CEE_BGT_UN_S, "bgt.un.s", 0xFFFFFF35, POP_1_1, PUSH_NONE, INLINE_TARGET_S, FLOW_COND_BRANCH)
+
+    /**
+     * Transfers control to a target instruction (short form) if the first value is less than 
+     * or equal to the second value, when comparing unsigned integer values or unordered float values. 
+     */
+    final val Ble_Un_S = new OpCode()
+	opcode(Ble_Un_S, CEE_BLE_UN_S , "ble.un.s", 0xFFFFFF36, POP_1_1, PUSH_NONE, INLINE_TARGET_S, FLOW_COND_BRANCH)
+
+    /**
+     * Transfers control to a target instruction (short form) if the first value is less than 
+     * the second value, when comparing unsigned integer values or unordered float values. 
+     */
+    final val Blt_Un_S = new OpCode()
+	opcode(Blt_Un_S, CEE_BLT_UN_S, "blt.un.s", 0xFFFFFF37, POP_1_1, PUSH_NONE, INLINE_TARGET_S, FLOW_COND_BRANCH)
+
+    /**
+     * Unconditionally transfers control to a target instruction. 
+     */
+    final val Br = new OpCode()
+	opcode(Br, CEE_BR       , "br"       , 0xFFFFFF38, POP_NONE, PUSH_NONE, INLINE_TARGET, FLOW_BRANCH)
+
+    /**
+     * Transfers control to a target instruction if value is false, a null reference 
+     * (Nothing in Visual Basic), or zero. 
+     */
+    final val Brfalse = new OpCode()
+	opcode(Brfalse, CEE_BRFALSE, "brfalse", 0xFFFFFF39, POP_I, PUSH_NONE, INLINE_TARGET, FLOW_COND_BRANCH)
+
+    /**
+     * Transfers control to a target instruction if value is true, not null, or non-zero. 
+     */
+    final val Brtrue = new OpCode()
+	opcode(Brtrue, CEE_BRTRUE , "brtrue", 0xFFFFFF3A, POP_I   , PUSH_NONE, INLINE_TARGET, FLOW_COND_BRANCH)
+
+    /**
+     * Transfers control to a target instruction if two values are equal.
+     */
+    final val Beq = new OpCode()
+	opcode(Beq, CEE_BEQ, "beq", 0xFFFFFF3B, POP_1_1 , PUSH_NONE, INLINE_TARGET, FLOW_COND_BRANCH)
+
+    /**
+     * Transfers control to a target instruction if the first value is greater than or 
+     * equal to the second value.
+     */
+    final val Bge = new OpCode()
+	opcode(Bge, CEE_BGE, "bge", 0xFFFFFF3C, POP_1_1 , PUSH_NONE, INLINE_TARGET, FLOW_COND_BRANCH)
+
+    /**
+     * Transfers control to a target instruction if the first value is greater than the second value.
+     */
+    final val Bgt = new OpCode()
+	opcode(Bgt, CEE_BGT, "bgt", 0xFFFFFF3D, POP_1_1 , PUSH_NONE, INLINE_TARGET, FLOW_COND_BRANCH)
+
+    /**
+     * Transfers control to a target instruction if the first value is less than or equal 
+     * to the second value.
+     */
+    final val Ble = new OpCode()
+	opcode(Ble, CEE_BLE, "ble", 0xFFFFFF3E, POP_1_1 , PUSH_NONE, INLINE_TARGET, FLOW_COND_BRANCH)
+
+    /**
+     *  Transfers control to a target instruction if the first value is less than the second value. 
+     */
+    final val Blt = new OpCode()
+	opcode(Blt, CEE_BLT, "blt", 0xFFFFFF3F, POP_1_1 , PUSH_NONE, INLINE_TARGET, FLOW_COND_BRANCH)
+
+    /**
+     * Transfers control to a target instruction when two unsigned integer values or 
+     * unordered float values are not equal. 
+     */
+    final val Bne_Un = new OpCode()
+	opcode(Bne_Un, CEE_BNE_UN , "bne.un", 0xFFFFFF40, POP_1_1 , PUSH_NONE, INLINE_TARGET, FLOW_COND_BRANCH)
+
+    /**
+     * Transfers control to a target instruction if the the first value is greather than 
+     * the second value, when comparing unsigned integer values or unordered float values.
+     */
+    final val Bge_Un = new OpCode()
+	opcode(Bge_Un, CEE_BGE_UN , "bge.un", 0xFFFFFF41, POP_1_1 , PUSH_NONE, INLINE_TARGET, FLOW_COND_BRANCH)
+
+    /**
+     * Transfers control to a target instruction if the first value is greater than the 
+     * second value, when comparing unsigned integer values or unordered float values. 
+     */
+    final val Bgt_Un = new OpCode()
+	opcode(Bgt_Un, CEE_BGT_UN , "bgt.un", 0xFFFFFF42, POP_1_1 , PUSH_NONE, INLINE_TARGET, FLOW_COND_BRANCH)
+
+    /**
+     * Transfers control to a target instruction if the first value is less than or equal to 
+     * the second value, when comparing unsigned integer values or unordered float values. 
+     */
+    final val Ble_Un = new OpCode()
+	opcode(Ble_Un, CEE_BLE_UN , "ble.un"   , 0xFFFFFF43, POP_1_1 , PUSH_NONE, INLINE_TARGET, FLOW_COND_BRANCH)
+
+    /**
+     * Transfers control to a target instruction if the first value is less than the second value, 
+     * when comparing unsigned integer values or unordered float values. 
+     */
+    final val Blt_Un = new OpCode()
+	opcode(Blt_Un, CEE_BLT_UN , "blt.un", 0xFFFFFF44, POP_1_1 , PUSH_NONE, INLINE_TARGET, FLOW_COND_BRANCH)
+
+    /**
+     * Implements a jump table. 
+     */
+    final val Switch = new OpCode()
+	opcode(Switch, CEE_SWITCH , "switch", 0xFFFFFF45, POP_I   , PUSH_NONE, INLINE_SWITCH, FLOW_COND_BRANCH)
+
+    /**
+     * Loads a value of type int8 as an int32 onto the evaluation stack indirectly. 
+     */
+    final val Ldind_I1 = new OpCode()
+	opcode(Ldind_I1, CEE_LDIND_I1 , "ldind.i1" , 0xFFFFFF46, POP_I   , PUSH_I  , INLINE_NONE, FLOW_NEXT)
+
+    /**
+     *  Loads a value of type int16 as an int32 onto the evaluation stack indirectly.
+     */
+    final val Ldind_I2 = new OpCode()
+	opcode(Ldind_I2, CEE_LDIND_I2 , "ldind.i2" , 0xFFFFFF48, POP_I   , PUSH_I  , INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Loads a value of type int32 as an int32 onto the evaluation stack indirectly. 
+     */
+    final val Ldind_I4 = new OpCode()
+	opcode(Ldind_I4, CEE_LDIND_I4 , "ldind.i4" , 0xFFFFFF4A, POP_I   , PUSH_I  , INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Loads a value of type int64 as an int64 onto the evaluation stack indirectly. 
+     */
+    final val Ldind_I8 = new OpCode()
+	opcode(Ldind_I8, CEE_LDIND_I8 , "ldind.i8" , 0xFFFFFF4C, POP_I   , PUSH_I8 , INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Loads a value of type natural int as a natural int onto the evaluation stack indirectly. 
+     */
+    final val Ldind_I = new OpCode()
+	opcode(Ldind_I, CEE_LDIND_I  , "ldind.i"  , 0xFFFFFF4D, POP_I   , PUSH_I  , INLINE_NONE, FLOW_NEXT)
+
+    /**
+     *  Loads a value of type float32 as a type F (float) onto the evaluation stack indirectly. 
+     */
+    final val Ldind_R4 = new OpCode()
+	opcode(Ldind_R4, CEE_LDIND_R4 , "ldind.r4" , 0xFFFFFF4E, POP_I   , PUSH_R4 , INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Loads a value of type float64 as a type F (float) onto the evaluation stack indirectly. 
+     */
+    final val Ldind_R8 = new OpCode()
+	opcode(Ldind_R8, CEE_LDIND_R8 , "ldind.r8" , 0xFFFFFF4F, POP_I   , PUSH_R8 , INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Loads an object reference as a type O (object reference) onto the evaluation stack indirectly. 
+     */
+    final val Ldind_Ref = new OpCode()
+	opcode(Ldind_Ref, CEE_LDIND_REF, "ldind.ref", 0xFFFFFF50, POP_I   , PUSH_REF, INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Loads a value of type unsigned int8 as an int32 onto the evaluation stack indirectly. 
+     */
+    final val Ldind_U1 = new OpCode()
+	opcode(Ldind_U1, CEE_LDIND_U1 , "ldind.u1" , 0xFFFFFF47, POP_I   , PUSH_I  , INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Loads a value of type unsigned int16 as an int32 onto the evaluation stack indirectly. 
+     */
+    final val Ldind_U2 = new OpCode()
+	opcode(Ldind_U2, CEE_LDIND_U2 , "ldind.u2" , 0xFFFFFF49, POP_I   , PUSH_I  , INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Loads a value of type unsigned int32 as an int32 onto the evaluation stack indirectly. 
+     */
+    final val Ldind_U4 = new OpCode()
+	opcode(Ldind_U4, CEE_LDIND_U4 , "ldind.u4" , 0xFFFFFF4B, POP_I   , PUSH_I  , INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Stores a object reference value at a supplied address. 
+     */
+    final val Stind_Ref = new OpCode()
+	opcode(Stind_Ref, CEE_STIND_REF, "stind.ref", 0xFFFFFF51, POP_I_I , PUSH_NONE, INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Stores a value of type int8 at a supplied address. 
+     */
+    final val Stind_I1 = new OpCode()
+	opcode(Stind_I1, CEE_STIND_I1 , "stind.i1", 0xFFFFFF52, POP_I_I , PUSH_NONE, INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Stores a value of type int16 at a supplied address. 
+     */
+    final val Stind_I2 = new OpCode()
+	opcode(Stind_I2, CEE_STIND_I2 , "stind.i2", 0xFFFFFF53, POP_I_I , PUSH_NONE, INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Stores a value of type int32 at a supplied address. 
+     */
+    final val Stind_I4 = new OpCode()
+	opcode(Stind_I4, CEE_STIND_I4 , "stind.i4", 0xFFFFFF54, POP_I_I , PUSH_NONE, INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Stores a value of type int64 at a supplied address. 
+     */
+    final val Stind_I8 = new OpCode()
+	opcode(Stind_I8, CEE_STIND_I8 , "stind.i8", 0xFFFFFF55, POP_I_I8, PUSH_NONE, INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Stores a value of type float32 at a supplied address. 
+     */
+    final val Stind_R4 = new OpCode()
+	opcode(Stind_R4, CEE_STIND_R4 , "stind.r4", 0xFFFFFF56, POP_I_R4, PUSH_NONE, INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Stores a value of type float64 at a supplied address. 
+     */
+    final val Stind_R8 = new OpCode()
+	opcode(Stind_R8, CEE_STIND_R8 , "stind.r8", 0xFFFFFF57, POP_I_R8, PUSH_NONE, INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Subtracts one value from another and pushes the result onto the evaluation stack. 
+     */
+    final val Sub = new OpCode()
+	opcode(Sub, CEE_SUB, "sub"    , 0xFFFFFF59, POP_1_1, PUSH_1 , INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Multiplies two values and pushes the result on the evaluation stack. 
+     */
+    final val Mul = new OpCode()
+	opcode(Mul, CEE_MUL, "mul"    , 0xFFFFFF5A, POP_1_1, PUSH_1 , INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Divides two values and pushes the result as a floating-point (type F) or 
+     * quotient (type int32) onto the evaluation stack.
+     */
+    final val Div = new OpCode()
+	opcode(Div, CEE_DIV, "div"    , 0xFFFFFF5B, POP_1_1, PUSH_1 , INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Divides two unsigned integer values and pushes the result (int32) onto the evaluation stack. 
+     */
+    final val Div_Un = new OpCode()
+	opcode(Div_Un, CEE_DIV_UN, "div.un" , 0xFFFFFF5C, POP_1_1, PUSH_1 , INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Divides two values and pushes the remainder onto the evaluation stack. 
+     */
+    final val Rem = new OpCode()
+	opcode(Rem, CEE_REM   , "rem"    , 0xFFFFFF5D, POP_1_1, PUSH_1 , INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Divides two unsigned values and pushes the remainder onto the evaluation stack. 
+     */
+    final val Rem_Un = new OpCode()
+	opcode(Rem_Un, CEE_REM_UN, "rem.un" , 0xFFFFFF5E, POP_1_1, PUSH_1 , INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Computes the bitwise AND of two values and pushes the result onto the evaluation stack.
+     */
+    final val And = new OpCode()
+	opcode(And, CEE_AND, "and"    , 0xFFFFFF5F, POP_1_1, PUSH_1 , INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Compute the bitwise complement of the two integer values on top of the stack and 
+     * pushes the result onto the evaluation stack. 
+     */
+    final val Or = new OpCode()
+	opcode(Or, CEE_OR , "or"     , 0xFFFFFF60, POP_1_1, PUSH_1 , INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Computes the bitwise XOR of the top two values on the evaluation stack, 
+     * pushing the result onto the evaluation stack. 
+     */
+    final val Xor = new OpCode()
+	opcode(Xor, CEE_XOR, "xor"    , 0xFFFFFF61, POP_1_1, PUSH_1 , INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Shifts an integer value to the left (in zeroes) by a specified number of bits,
+     *  pushing the result onto the evaluation stack.
+     */
+    final val Shl = new OpCode()
+	opcode(Shl, CEE_SHL, "shl"    , 0xFFFFFF62, POP_1_1, PUSH_1 , INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Shifts an integer value (in sign) to the right by a specified number of bits, 
+     * pushing the result onto the evaluation stack. 
+     */
+    final val Shr = new OpCode()
+	opcode(Shr, CEE_SHR, "shr"    , 0xFFFFFF63, POP_1_1, PUSH_1 , INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Shifts an unsigned integer value (in zeroes) to the right by a specified number of bits, 
+     * pushing the result onto the evaluation stack. 
+     */
+    final val Shr_Un = new OpCode()
+	opcode(Shr_Un, CEE_SHR_UN, "shr.un" , 0xFFFFFF64, POP_1_1, PUSH_1 , INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Negates a value and pushes the result onto the evaluation stack. 
+     */
+    final val Neg = new OpCode()
+	opcode(Neg, CEE_NEG , "neg"    , 0xFFFFFF65, POP_1  , PUSH_1 , INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Computes the bitwise complement of the integer value on top of the stack and pushes 
+     * the result onto the evaluation stack as the same type.
+     */
+    final val Not = new OpCode()
+	opcode(Not, CEE_NOT , "not"    , 0xFFFFFF66, POP_1  , PUSH_1 , INLINE_NONE, FLOW_NEXT)
+
+    /**
+     *  Converts the value on top of the evaluation stack to int8, then extends (pads) it to int32. 
+     */
+    final val Conv_I1 = new OpCode()
+	opcode(Conv_I1, CEE_CONV_I1, "conv.i1", 0xFFFFFF67, POP_1  , PUSH_I , INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Converts the value on top of the evaluation stack to int16, then extends (pads) it to int32. 
+     */
+    final val Conv_I2 = new OpCode()
+	opcode(Conv_I2, CEE_CONV_I2, "conv.i2", 0xFFFFFF68, POP_1  , PUSH_I , INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Converts the value on top of the evaluation stack to int32. 
+     */
+    final val Conv_I4 = new OpCode()
+	opcode(Conv_I4, CEE_CONV_I4, "conv.i4", 0xFFFFFF69, POP_1  , PUSH_I , INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Converts the value on top of the evaluation stack to int64. 
+     */
+    final val Conv_I8 = new OpCode()
+	opcode(Conv_I8, CEE_CONV_I8, "conv.i8", 0xFFFFFF6A, POP_1  , PUSH_I8, INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Converts the value on top of the evaluation stack to float32. 
+     */
+    final val Conv_R4 = new OpCode()
+	opcode(Conv_R4, CEE_CONV_R4, "conv.r4", 0xFFFFFF6B, POP_1  , PUSH_R4, INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Converts the value on top of the evaluation stack to float64. 
+     */
+    final val Conv_R8 = new OpCode()
+	opcode(Conv_R8, CEE_CONV_R8, "conv.r8", 0xFFFFFF6C, POP_1  , PUSH_R8, INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Converts the value on top of the evaluation stack to unsigned int32, and extends it to int32. 
+     */
+    final val Conv_U4 = new OpCode()
+	opcode(Conv_U4, CEE_CONV_U4, "conv.u4", 0xFFFFFF6D, POP_1  , PUSH_I , INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Converts the value on top of the evaluation stack to unsigned int64, and extends it to int64. 
+     */
+    final val Conv_U8 = new OpCode()
+	opcode(Conv_U8, CEE_CONV_U8, "conv.u8", 0xFFFFFF6E, POP_1  , PUSH_I8, INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Calls a late-bound method on an object, pushing the return value onto the evaluation stack. 
+     */
+    final val Callvirt = new OpCode()
+	opcode(Callvirt, CEE_CALLVIRT, "callvirt", 0xFFFFFF6F,POP_SPECIAL,PUSH_SPECIAL,INLINE_METHOD,FLOW_CALL)
+
+    /**
+     * Copies the value type located at the address of an object (type &, * or natural int) 
+     * to the address of the destination object (type &, * or natural int). 
+     */
+    final val Cpobj = new OpCode()
+	opcode(Cpobj, CEE_CPOBJ , "cpobj" , 0xFFFFFF70, POP_I_I , PUSH_NONE, INLINE_TYPE  , FLOW_NEXT)
+
+    /**
+     * Copies the value type object pointed to by an address to the top of the evaluation stack. 
+     */
+    final val Ldobj = new OpCode()
+	opcode(Ldobj, CEE_LDOBJ , "ldobj" , 0xFFFFFF71, POP_I    , PUSH_1   , INLINE_TYPE  , FLOW_NEXT)
+
+    /**
+     * Pushes a new object reference to a string literal stored in the metadata. 
+     */
+    final val Ldstr = new OpCode()
+	opcode(Ldstr, CEE_LDSTR , "ldstr" , 0xFFFFFF72, POP_NONE  , PUSH_REF , INLINE_STRING, FLOW_NEXT)
+
+    /**
+     * Creates a new object or a new instance of a value type, pushing an object reference 
+     * (type O) onto the evaluation stack. 
+     */
+    final val Newobj = new OpCode()
+	opcode(Newobj, CEE_NEWOBJ, "newobj", 0xFFFFFF73, POP_SPECIAL , PUSH_REF , INLINE_METHOD, FLOW_CALL)
+
+    /**
+     * Attempts to cast an object passed by reference to the specified class. 
+     */
+    final val Castclass = new OpCode()
+	opcode(Castclass, CEE_CASTCLASS, "castclass", 0xFFFFFF74, POP_REF  , PUSH_REF , INLINE_TYPE  , FLOW_NEXT)
+
+    /**
+     * Tests whether an object reference (type O) is an instance of a particular class.
+     */
+    final val Isinst = new OpCode()
+	opcode(Isinst, CEE_ISINST   , "isinst"   , 0xFFFFFF75, POP_REF  , PUSH_I   , INLINE_TYPE  , FLOW_NEXT)
+
+    /**
+     *  Converts the unsigned integer value on top of the evaluation stack to float32. 
+     */
+    final val Conv_R_Un = new OpCode()
+	opcode(Conv_R_Un, CEE_CONV_R_UN, "conv.r.un", 0xFFFFFF76, POP_1    , PUSH_R8  , INLINE_NONE  , FLOW_NEXT)
+
+    /**
+     * Converts the boxed representation of a value type to its unboxed form. 
+     */
+    final val Unbox = new OpCode()
+	opcode(Unbox, CEE_UNBOX  , "unbox"  , 0xFFFFFF79, POP_REF  , PUSH_I   , INLINE_TYPE  , FLOW_NEXT)
+
+    /**
+     * Throws the exception object currently on the evaluation stack. 
+     */
+    final val Throw = new OpCode()
+	opcode(Throw, CEE_THROW  , "throw"  , 0xFFFFFF7A, POP_REF  , PUSH_NONE, INLINE_NONE  , FLOW_THROW)
+
+    /**
+     *  Finds the value of a field in the object whose reference is currently 
+     * on the evaluation stack. 
+     */
+    final val Ldfld = new OpCode()
+	opcode(Ldfld, CEE_LDFLD  , "ldfld"  , 0xFFFFFF7B, POP_REF  , PUSH_1   , INLINE_FIELD , FLOW_NEXT)
+
+    /**
+     *  Finds the address of a field in the object whose reference is currently 
+     * on the evaluation stack. 
+     */
+    final val Ldflda = new OpCode()
+	opcode(Ldflda, CEE_LDFLDA , "ldflda" , 0xFFFFFF7C, POP_REF  , PUSH_I   , INLINE_FIELD , FLOW_NEXT)
+
+    /**
+     * Pushes the value of a static field onto the evaluation stack. 
+     */
+    final val Ldsfld = new OpCode()
+	opcode(Ldsfld, CEE_LDSFLD , "ldsfld" , 0xFFFFFF7E, POP_NONE , PUSH_1   , INLINE_FIELD , FLOW_NEXT)
+
+    /**
+     * Pushes the address of a static field onto the evaluation stack. 
+     */
+    final val Ldsflda = new OpCode()
+	opcode(Ldsflda, CEE_LDSFLDA, "ldsflda", 0xFFFFFF7F, POP_NONE , PUSH_I   , INLINE_FIELD , FLOW_NEXT)
+
+    /**
+     *  Replaces the value stored in the field of an object reference or pointer with a new value. 
+     */
+    final val Stfld = new OpCode()
+	opcode(Stfld, CEE_STFLD  , "stfld"  , 0xFFFFFF7D, POP_REF_1, PUSH_NONE, INLINE_FIELD , FLOW_NEXT)
+
+    /**
+     * Replaces the value of a static field with a value from the evaluation stack. 
+     */
+    final val Stsfld = new OpCode()
+	opcode(Stsfld, CEE_STSFLD , "stsfld" , 0xFFFFFF80, POP_1    , PUSH_NONE, INLINE_FIELD , FLOW_NEXT)
+
+    /**
+     * Copies a value of a specified type from the evaluation stack into a supplied memory address. 
+     */
+    final val Stobj = new OpCode()
+	opcode(Stobj, CEE_STOBJ  , "stobj"  , 0xFFFFFF81, POP_I_1, PUSH_NONE, INLINE_TYPE  , FLOW_NEXT)
+
+    /**
+     * Converts the unsigned value on top of the evaluation stack to signed int8 and 
+     * extends it to int32, throwing OverflowException on overflow.
+     */
+    final val Conv_Ovf_I1_Un = new OpCode()
+	opcode(Conv_Ovf_I1_Un, CEE_CONV_OVF_I1_UN, "conv.ovf.i1.un", 0xFFFFFF82, POP_1,PUSH_I,INLINE_NONE, FLOW_NEXT)
+
+    /**
+     *  Converts the unsigned value on top of the evaluation stack to signed int16 and 
+     * extends it to int32, throwing OverflowException on overflow. 
+     */
+    final val Conv_Ovf_I2_Un = new OpCode()
+	opcode(Conv_Ovf_I2_Un, CEE_CONV_OVF_I2_UN, "conv.ovf.i2.un", 0xFFFFFF83,POP_1,PUSH_I, INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Converts the unsigned value on top of the evaluation stack to signed int32, 
+     * throwing OverflowException on overflow. 
+     */
+    final val Conv_Ovf_I4_Un = new OpCode()
+	opcode(Conv_Ovf_I4_Un, CEE_CONV_OVF_I4_UN, "conv.ovf.i4.un", 0xFFFFFF84,POP_1,PUSH_I, INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Converts the unsigned value on top of the evaluation stack to signed int64, 
+     * throwing OverflowException on overflow. 
+     */
+    final val Conv_Ovf_I8_Un = new OpCode()
+	opcode(Conv_Ovf_I8_Un, CEE_CONV_OVF_I8_UN, "conv.ovf.i8.un", 0xFFFFFF85,POP_1,PUSH_I8, INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Converts the unsigned value on top of the evaluation stack to signed natural int, 
+     * throwing OverflowException on overflow. 
+     */
+    final val Conv_Ovf_I_Un = new OpCode()
+	opcode(Conv_Ovf_I_Un, CEE_CONV_OVF_I_UN , "conv.ovf.i.un" , 0xFFFFFF8A,POP_1,PUSH_I, INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Converts the unsigned value on top of the evaluation stack to unsigned int8 and 
+     * extends it to int32, throwing OverflowException on overflow. 
+     */
+    final val Conv_Ovf_U1_Un = new OpCode()
+	opcode(Conv_Ovf_U1_Un, CEE_CONV_OVF_U1_UN, "conv.ovf.u1.un", 0xFFFFFF86,POP_1,PUSH_I, INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Converts the unsigned value on top of the evaluation stack to unsigned int16 and 
+     * extends it to int32, throwing OverflowException on overflow. 
+     */
+    final val Conv_Ovf_U2_Un = new OpCode()
+	opcode(Conv_Ovf_U2_Un, CEE_CONV_OVF_U2_UN, "conv.ovf.u2.un", 0xFFFFFF87,POP_1,PUSH_I, INLINE_NONE, FLOW_NEXT)
+    
+    /**
+     * Converts the unsigned value on top of the evaluation stack to unsigned int32, 
+     * throwing OverflowException on overflow. 
+     */
+    final val Conv_Ovf_U4_Un = new OpCode()
+	opcode(Conv_Ovf_U4_Un, CEE_CONV_OVF_U4_UN, "conv.ovf.u4.un", 0xFFFFFF88,POP_1,PUSH_I, INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Converts the unsigned value on top of the evaluation stack to unsigned int64, 
+     * throwing OverflowException on overflow. 
+     */
+    final val Conv_Ovf_U8_Un = new OpCode()
+	opcode(Conv_Ovf_U8_Un, CEE_CONV_OVF_U8_UN, "conv.ovf.u8.un", 0xFFFFFF89,POP_1,PUSH_I8, INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Converts the unsigned value on top of the evaluation stack to unsigned natural int, 
+     * throwing OverflowException on overflow. 
+     */
+    final val Conv_Ovf_U_Un = new OpCode()
+	opcode(Conv_Ovf_U_Un, CEE_CONV_OVF_U_UN , "conv.ovf.u.un" , 0xFFFFFF8B,POP_1,PUSH_I, INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Converts a value type to an object reference (type O).
+     */
+    final val Box = new OpCode()
+	opcode(Box, CEE_BOX       , "box"       , 0xFFFFFF8C, POP_1  , PUSH_REF , INLINE_TYPE , FLOW_NEXT)
+
+    /**
+     * Pushes an object reference to a new zero-based, one-dimensional array whose elements 
+     * are of a specific type onto the evaluation stack. 
+     */
+    final val Newarr = new OpCode()
+	opcode(Newarr, CEE_NEWARR, "newarr"    , 0xFFFFFF8D, POP_I  , PUSH_REF , INLINE_TYPE , FLOW_NEXT)
+
+    /**
+     * Pushes the number of elements of a zero-based, one-dimensional array 
+     * onto the evaluation stack. 
+     */
+    final val Ldlen = new OpCode()
+	opcode(Ldlen, CEE_LDLEN, "ldlen", 0xFFFFFF8E, POP_REF, PUSH_I,INLINE_NONE , FLOW_NEXT)
+
+    /**
+     * Loads the address of the array element at a specified array index onto 
+     * the top of the evaluation stack as type & (managed pointer).
+     */
+    final val Ldelema = new OpCode()
+	opcode(Ldelema, CEE_LDELEMA, "ldelema"   , 0xFFFFFF8F, POP_REF_I, PUSH_I, INLINE_TYPE , FLOW_NEXT)
+
+    /**
+     * Loads the element with type natural int at a specified array index onto the top 
+     * of the evaluation stack as a natural int. 
+     */
+    final val Ldelem_I = new OpCode()
+	opcode(Ldelem_I, CEE_LDELEM_I, "ldelem.i"  , 0xFFFFFF97, POP_REF_I, PUSH_I, INLINE_NONE , FLOW_NEXT)
+
+    /**
+     * Loads the element with type int8 at a specified array index onto the top of the 
+     * evaluation stack as an int32. 
+     */
+    final val Ldelem_I1 = new OpCode()
+	opcode(Ldelem_I1, CEE_LDELEM_I1, "ldelem.i1" , 0xFFFFFF90, POP_REF_I, PUSH_I, INLINE_NONE , FLOW_NEXT)
+
+    /**
+     * Loads the element with type int16 at a specified array index onto the top of 
+     * the evaluation stack as an int32. 
+     */
+    final val Ldelem_I2 = new OpCode()
+	opcode(Ldelem_I2, CEE_LDELEM_I2, "ldelem.i2" , 0xFFFFFF92, POP_REF_I, PUSH_I, INLINE_NONE , FLOW_NEXT)
+
+    /**
+     *  Loads the element with type int32 at a specified array index onto the top of the 
+     * evaluation stack as an int32.  
+     */
+    final val Ldelem_I4 = new OpCode()
+	opcode(Ldelem_I4, CEE_LDELEM_I4, "ldelem.i4" , 0xFFFFFF94, POP_REF_I, PUSH_I, INLINE_NONE , FLOW_NEXT)
+
+    /**
+     *  Loads the element with type int64 at a specified array index onto the top of the 
+     * evaluation stack as an int64.
+     */
+    final val Ldelem_I8 = new OpCode()
+	opcode(Ldelem_I8, CEE_LDELEM_I8, "ldelem.i8" , 0xFFFFFF96, POP_REF_I, PUSH_I8, INLINE_NONE , FLOW_NEXT)
+
+    /**
+     * Loads the element with type float32 at a specified array index onto the top of the 
+     * evaluation stack as type F (float) 
+     */
+    final val Ldelem_R4 = new OpCode()
+	opcode(Ldelem_R4, CEE_LDELEM_R4, "ldelem.r4" , 0xFFFFFF98, POP_REF_I, PUSH_R4, INLINE_NONE , FLOW_NEXT)
+
+    /**
+     * Loads the element with type float64 at a specified array index onto the top of the 
+     * evaluation stack as type F (float) .
+     */
+    final val Ldelem_R8 = new OpCode()
+	opcode(Ldelem_R8, CEE_LDELEM_R8, "ldelem.r8" , 0xFFFFFF99, POP_REF_I, PUSH_R8, INLINE_NONE , FLOW_NEXT)
+
+    /**
+     * Loads the element containing an object reference at a specified array index onto 
+     * the top of the evaluation stack as type O (object reference). 
+     */
+    final val Ldelem_Ref = new OpCode()
+	opcode(Ldelem_Ref, CEE_LDELEM_REF, "ldelem.ref", 0xFFFFFF9A, POP_REF_I, PUSH_REF, INLINE_NONE , FLOW_NEXT)
+
+    /**
+     * Loads the element with type unsigned int8 at a specified array index onto the top 
+     * of the evaluation stack as an int32.  
+     */
+    final val Ldelem_U1 = new OpCode()
+	opcode(Ldelem_U1, CEE_LDELEM_U1, "ldelem.u1" , 0xFFFFFF91, POP_REF_I, PUSH_I, INLINE_NONE , FLOW_NEXT)
+
+    /**
+     * Loads the element with type unsigned int16 at a specified array index onto the top 
+     * of the evaluation stack as an int32.
+     */
+    final val Ldelem_U2 = new OpCode()
+	opcode(Ldelem_U2, CEE_LDELEM_U2, "ldelem.u2" , 0xFFFFFF93, POP_REF_I, PUSH_I, INLINE_NONE , FLOW_NEXT)
+
+    /**
+     * Loads the element with type unsigned int32 at a specified array index onto the top 
+     * of the evaluation stack as an int32.  
+     */
+    final val Ldelem_U4 = new OpCode()
+	opcode(Ldelem_U4, CEE_LDELEM_U4, "ldelem.u4" , 0xFFFFFF95, POP_REF_I, PUSH_I, INLINE_NONE , FLOW_NEXT)
+
+    /**
+     *  Replaces the array element at a given index with the natural int value on 
+     * the evaluation stack. 
+     */
+    final val Stelem_I = new OpCode()
+	opcode(Stelem_I, CEE_STELEM_I, "stelem.i", 0xFFFFFF9B, POP_REF_I_I, PUSH_NONE, INLINE_NONE , FLOW_NEXT)
+
+    /**
+     * Replaces the array element at a given index with the int8 value on the evaluation stack. 
+     */
+    final val Stelem_I1 = new OpCode()
+	opcode(Stelem_I1, CEE_STELEM_I1, "stelem.i1", 0xFFFFFF9C, POP_REF_I_I, PUSH_NONE, INLINE_NONE, FLOW_NEXT)
+
+    /**
+     *  Replaces the array element at a given index with the int16 value on the evaluation stack. 
+     */
+    final val Stelem_I2 = new OpCode()
+	opcode(Stelem_I2, CEE_STELEM_I2, "stelem.i2", 0xFFFFFF9D, POP_REF_I_I, PUSH_NONE, INLINE_NONE, FLOW_NEXT)
+
+    /**
+     *  Replaces the array element at a given index with the int32 value on the evaluation stack. 
+     */
+    final val Stelem_I4 = new OpCode()
+	opcode(Stelem_I4, CEE_STELEM_I4, "stelem.i4", 0xFFFFFF9E, POP_REF_I_I, PUSH_NONE, INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Replaces the array element at a given index with the int64 value on the evaluation stack. 
+     */
+    final val Stelem_I8 = new OpCode()
+	opcode(Stelem_I8, CEE_STELEM_I8,"stelem.i8", 0xFFFFFF9F, POP_REF_I_I8, PUSH_NONE, INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Replaces the array element at a given index with the float32 value on the evaluation stack. 
+     */
+    final val Stelem_R4 = new OpCode()
+	opcode(Stelem_R4, CEE_STELEM_R4,"stelem.r4", 0xFFFFFFA0, POP_REF_I_R4, PUSH_NONE, INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Replaces the array element at a given index with the float64 value on the evaluation stack. 
+     */
+    final val Stelem_R8 = new OpCode()
+	opcode(Stelem_R8, CEE_STELEM_R8,"stelem.r8", 0xFFFFFFA1, POP_REF_I_R8, PUSH_NONE, INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Replaces the array element at a given index with the object ref value (type O) 
+     * on the evaluation stack. 
+     */
+    final val Stelem_Ref = new OpCode()
+	opcode(Stelem_Ref, CEE_STELEM_REF,"stelem.ref",0xFFFFFFA2,POP_REF_I_REF,PUSH_NONE, INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Converts the signed value on top of the evaluation stack to signed int8 and 
+     * extends it to int32, throwing OverflowException on overflow. 
+     */
+    final val Conv_Ovf_I1 = new OpCode()
+	opcode(Conv_Ovf_I1, CEE_CONV_OVF_I1, "conv.ovf.i1", 0xFFFFFFB3, POP_1, PUSH_I , INLINE_NONE , FLOW_NEXT)
+
+    /**
+     * Converts the signed value on top of the evaluation stack to signed int16 and 
+     * extending it to int32, throwing OverflowException on overflow. 
+     */
+    final val Conv_Ovf_I2 = new OpCode()
+	opcode(Conv_Ovf_I2, CEE_CONV_OVF_I2, "conv.ovf.i2", 0xFFFFFFB5, POP_1, PUSH_I , INLINE_NONE , FLOW_NEXT)
+
+    /**
+     * Converts the signed value on top of the evaluation stack to signed int32, 
+     * throwing OverflowException on overflow. 
+     */
+    final val Conv_Ovf_I4 = new OpCode()
+	opcode(Conv_Ovf_I4, CEE_CONV_OVF_I4, "conv.ovf.i4", 0xFFFFFFB7, POP_1, PUSH_I , INLINE_NONE , FLOW_NEXT)
+
+    /**
+     * Converts the signed value on top of the evaluation stack to signed int64, 
+     * throwing OverflowException on overflow. 
+     */
+    final val Conv_Ovf_I8 = new OpCode()
+	opcode(Conv_Ovf_I8, CEE_CONV_OVF_I8, "conv.ovf.i8", 0xFFFFFFB9, POP_1, PUSH_I8, INLINE_NONE , FLOW_NEXT)
+
+    /**
+     * Converts the signed value on top of the evaluation stack to unsigned int8 and 
+     * extends it to int32, throwing OverflowException on overflow. 
+     */
+    final val Conv_Ovf_U1 = new OpCode()
+	opcode(Conv_Ovf_U1, CEE_CONV_OVF_U1, "conv.ovf.u1", 0xFFFFFFB4, POP_1, PUSH_I , INLINE_NONE , FLOW_NEXT)
+
+    /**
+     * Converts the signed value on top of the evaluation stack to unsigned int16 and 
+     * extends it to int32, throwing OverflowException on overflow. 
+     */
+    final val Conv_Ovf_U2 = new OpCode()
+	opcode(Conv_Ovf_U2, CEE_CONV_OVF_U2, "conv.ovf.u2", 0xFFFFFFB6, POP_1, PUSH_I , INLINE_NONE , FLOW_NEXT)
+
+    /**
+     *  Converts the signed value on top of the evaluation stack to unsigned int32, 
+     * throwing OverflowException on overflow. 
+     */
+    final val Conv_Ovf_U4 = new OpCode()
+	opcode(Conv_Ovf_U4, CEE_CONV_OVF_U4, "conv.ovf.u4", 0xFFFFFFB8, POP_1, PUSH_I , INLINE_NONE , FLOW_NEXT)
+
+    /**
+     * Converts the signed value on top of the evaluation stack to unsigned int64, 
+     * throwing OverflowException on overflow. 
+     */
+    final val Conv_Ovf_U8 = new OpCode()
+	opcode(Conv_Ovf_U8, CEE_CONV_OVF_U8, "conv.ovf.u8", 0xFFFFFFBA, POP_1, PUSH_I8, INLINE_NONE , FLOW_NEXT)
+
+    /**
+     *  Retrieves the address (type &) embedded in a typed reference. 
+     */
+    final val Refanyval = new OpCode()
+	opcode(Refanyval, CEE_REFANYVAL, "refanyval", 0xFFFFFFC2, POP_1, PUSH_I   , INLINE_TYPE  , FLOW_NEXT)
+
+    /**
+     * Retrieves the type token embedded in a typed reference .  
+     */
+    final val Refanytype = new OpCode()
+	opcode(Refanytype, CEE_REFANYTYPE, "refanytype", 0xFFFFFE1D, POP_1    , PUSH_I   , INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Throws ArithmeticException if value is not a finite number.
+     */
+    final val Ckfinite = new OpCode()
+	opcode(Ckfinite, CEE_CKFINITE, "ckfinite" , 0xFFFFFFC3, POP_1, PUSH_R8  , INLINE_NONE  , FLOW_NEXT)
+
+    /**
+     * Pushes a typed reference to an instance of a specific type onto the evaluation stack. 
+     */
+    final val Mkrefany = new OpCode()
+	opcode(Mkrefany, CEE_MKREFANY, "mkrefany" , 0xFFFFFFC6, POP_I, PUSH_1   , INLINE_TYPE  , FLOW_NEXT)
+
+    /**
+     * Converts a metadata token to its runtime representation, pushing it onto the evaluation stack. 
+     */
+    final val Ldtoken = new OpCode()
+	opcode(Ldtoken, CEE_LDTOKEN    , "ldtoken"   , 0xFFFFFFD0, POP_NONE, PUSH_I, INLINE_TOKEN , FLOW_NEXT)
+
+    /**
+     * Converts the value on top of the evaluation stack to unsigned int8, and extends it to int32. 
+     */
+    final val Conv_U1 = new OpCode()
+	opcode(Conv_U1, CEE_CONV_U1    , "conv.u1"   , 0xFFFFFFD2, POP_1, PUSH_I, INLINE_NONE  , FLOW_NEXT)
+
+    /**
+     * Converts the value on top of the evaluation stack to unsigned int16, and extends it to int32. 
+     */
+    final val Conv_U2 = new OpCode()
+	opcode(Conv_U2, CEE_CONV_U2    , "conv.u2"   , 0xFFFFFFD1, POP_1, PUSH_I, INLINE_NONE  , FLOW_NEXT)
+
+    /**
+     * Converts the value on top of the evaluation stack to natural int. 
+     */
+    final val Conv_I = new OpCode()
+	opcode(Conv_I, CEE_CONV_I     , "conv.i"    , 0xFFFFFFD3, POP_1, PUSH_I, INLINE_NONE  , FLOW_NEXT)
+
+    /**
+     * Converts the signed value on top of the evaluation stack to signed natural int, 
+     * throwing OverflowException on overflow.
+     */
+    final val Conv_Ovf_I = new OpCode()
+	opcode(Conv_Ovf_I, CEE_CONV_OVF_I , "conv.ovf.i", 0xFFFFFFD4, POP_1, PUSH_I, INLINE_NONE  , FLOW_NEXT)
+
+    /**
+     * Converts the signed value on top of the evaluation stack to unsigned natural int, 
+     * throwing OverflowException on overflow.
+     */
+    final val Conv_Ovf_U = new OpCode()
+	opcode(Conv_Ovf_U, CEE_CONV_OVF_U , "conv.ovf.u", 0xFFFFFFD5, POP_1, PUSH_I, INLINE_NONE  , FLOW_NEXT)
+
+    /**
+     * Adds two integers, performs an overflow check, and pushes the result 
+     * onto the evaluation stack. 
+     */
+    final val Add_Ovf = new OpCode()
+	opcode(Add_Ovf, CEE_ADD_OVF    , "add.ovf"   , 0xFFFFFFD6, POP_1_1, PUSH_1, INLINE_NONE  , FLOW_NEXT)
+
+    /**
+     *  Adds two unsigned integer values, performs an overflow check, and pushes the result 
+     * onto the evaluation stack. 
+     */
+    final val Add_Ovf_Un = new OpCode()
+	opcode(Add_Ovf_Un, CEE_ADD_OVF_UN , "add.ovf.un", 0xFFFFFFD7, POP_1_1, PUSH_1, INLINE_NONE  , FLOW_NEXT)
+
+    /**
+     * Multiplies two integer values, performs an overflow check, and pushes the result 
+     * onto the evaluation stack. 
+     */
+    final val Mul_Ovf = new OpCode()
+	opcode(Mul_Ovf, CEE_MUL_OVF    , "mul.ovf"   , 0xFFFFFFD8, POP_1_1, PUSH_1, INLINE_NONE  , FLOW_NEXT)
+
+    /**
+     * Multiplies two unsigned integer values , performs an overflow check , 
+     * and pushes the result onto the evaluation stack. 
+     */
+    final val Mul_Ovf_Un = new OpCode()
+	opcode(Mul_Ovf_Un, CEE_MUL_OVF_UN , "mul.ovf.un", 0xFFFFFFD9, POP_1_1, PUSH_1, INLINE_NONE  , FLOW_NEXT)
+ 
+    /**
+     * Subtracts one integer value from another, performs an overflow check, 
+     * and pushes the result onto the evaluation stack. 
+     */
+    final val Sub_Ovf = new OpCode()
+	opcode(Sub_Ovf, CEE_SUB_OVF   , "sub.ovf"   , 0xFFFFFFDA, POP_1_1, PUSH_1, INLINE_NONE  , FLOW_NEXT)
+
+    /**
+     * Subtracts one unsigned integer value from another, performs an overflow check, 
+     * and pushes the result onto the evaluation stack. 
+     */
+    final val Sub_Ovf_Un = new OpCode()
+	opcode(Sub_Ovf_Un, CEE_SUB_OVF_UN, "sub.ovf.un", 0xFFFFFFDB, POP_1_1, PUSH_1, INLINE_NONE  , FLOW_NEXT)
+
+    /**
+     * Transfers control from the fault or finally clause of an exception block back to 
+     * the Common Language Infrastructure (CLI) exception handler. 
+     */
+    final val Endfinally = new OpCode()
+	opcode(Endfinally, CEE_ENDFINALLY, "endfinally", 0xFFFFFFDC, POP_NONE, PUSH_NONE, INLINE_NONE, FLOW_RETURN)
+
+    /**
+     * Exits a protected region of code, unconditionally tranferring control 
+     * to a specific target instruction. 
+     */
+    final val Leave = new OpCode()
+	opcode(Leave, CEE_LEAVE, "leave", 0xFFFFFFDD, POP_NONE, PUSH_NONE, INLINE_TARGET, FLOW_BRANCH)
+
+    /**
+     * Exits a protected region of code, unconditionally tranferring control 
+     * to a target instruction (short form). 
+     */
+    final val Leave_S = new OpCode()
+	opcode(Leave_S, CEE_LEAVE_S, "leave.s", 0xFFFFFFDE, POP_NONE, PUSH_NONE, INLINE_TARGET_S, FLOW_BRANCH)
+
+    /**
+     * Stores a value of type natural int at a supplied address. 
+     */
+    final val Stind_I = new OpCode()
+	opcode(Stind_I, CEE_STIND_I, "stind.i", 0xFFFFFFDF, POP_I_I , PUSH_NONE, INLINE_NONE, FLOW_NEXT)
+
+    /**
+     *  Converts the value on top of the evaluation stack to unsigned natural int, 
+     * and extends it to natural int. 
+     */
+    final val Conv_U = new OpCode()
+	opcode(Conv_U, CEE_CONV_U, "conv.u", 0xFFFFFFE0, POP_1   , PUSH_I   , INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Returns an unmanaged pointer to the argument list of the current method. 
+     */
+    final val Arglist = new OpCode()
+	opcode(Arglist, CEE_ARGLIST, "arglist"  , 0xFFFFFE00, POP_NONE, PUSH_I   , INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Compares two values. If they are equal, the integer value 1 (int32) is pushed 
+     * onto the evaluation stack otherwise 0 (int32) is pushed onto the evaluation stack. 
+     */
+    final val Ceq = new OpCode()
+	opcode(Ceq, CEE_CEQ, "ceq", 0xFFFFFE01, POP_1_1 , PUSH_I, INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Compares two values. If the first value is greater than the second, 
+     * the integer value 1 (int32) is pushed onto the evaluation stack 
+     * otherwise 0 (int32) is pushed onto the evaluation stack. 
+     */
+    final val Cgt = new OpCode()
+	opcode(Cgt, CEE_CGT, "cgt", 0xFFFFFE02, POP_1_1 , PUSH_I, INLINE_NONE, FLOW_NEXT)
+
+    /**
+     *  Compares two unsigned or unordered values. If the first value is greater than 
+     * the second, the integer value 1 (int32) is pushed onto the evaluation stack 
+     * otherwise 0 (int32) is pushed onto the evaluation stack. 
+     */
+    final val Cgt_Un = new OpCode()
+	opcode(Cgt_Un, CEE_CGT_UN, "cgt.un", 0xFFFFFE03, POP_1_1 , PUSH_I, INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Compares two values. If the first value is less than the second, 
+     * the integer value 1 (int32) is pushed onto the evaluation stack 
+     * otherwise 0 (int32) is pushed onto the evaluation stack. 
+     */
+    final val Clt = new OpCode()
+	opcode(Clt, CEE_CLT, "clt"      , 0xFFFFFE04, POP_1_1 , PUSH_I   , INLINE_NONE, FLOW_NEXT)
+ 
+    /**
+     *  Compares the unsigned or unordered values value1 and value2. If value1 is 
+     * less than value2, then the integer value 1 (int32) is pushed onto the 
+     * evaluation stack otherwise 0 (int32) is pushed onto the evaluation stack. 
+     */
+    final val Clt_Un = new OpCode()
+	opcode(Clt_Un, CEE_CLT_UN , "clt.un"   , 0xFFFFFE05, POP_1_1 , PUSH_I   , INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Pushes an unmanaged pointer (type natural int) to the native code implementing 
+     * a specific method onto the evaluation stack. 
+     */
+    final val Ldftn = new OpCode()
+	opcode(Ldftn, CEE_LDFTN , "ldftn"    , 0xFFFFFE06, POP_NONE, PUSH_I   , INLINE_METHOD, FLOW_NEXT)
+
+    /**
+     * Pushes an unmanaged pointer (type natural int) to the native code implementing 
+     * a particular virtual method associated with a specified object onto the evaluation stack. 
+     */
+    final val Ldvirtftn = new OpCode()
+	opcode(Ldvirtftn, CEE_LDVIRTFTN, "ldvirtftn", 0xFFFFFE07, POP_REF , PUSH_I   , INLINE_METHOD, FLOW_NEXT)
+
+    /**
+     * Loads an argument (referenced by a specified index value) onto the stack. 
+     */
+    final val Ldarg = new OpCode()
+	opcode(Ldarg, CEE_LDARG , "ldarg"    , 0xFFFFFE09, POP_NONE, PUSH_1   , INLINE_VARIABLE  , FLOW_NEXT)
+
+    /**
+     * Load an argument address onto the evaluation stack. 
+     */
+    final val Ldarga = new OpCode()
+	opcode(Ldarga, CEE_LDARGA , "ldarga", 0xFFFFFE0A, POP_NONE, PUSH_I, INLINE_VARIABLE  , FLOW_NEXT)
+
+    /**
+     * Loads the local variable at a specific index onto the evaluation stack. 
+     */
+    final val Ldloc = new OpCode()
+	opcode(Ldloc, CEE_LDLOC, "ldloc", 0xFFFFFE0C, POP_NONE, PUSH_1   , INLINE_VARIABLE  , FLOW_NEXT)
+
+    /**
+     *  Loads the address of the local variable at a specific index onto the evaluation stack. 
+     */
+    final val Ldloca = new OpCode()
+	opcode(Ldloca, CEE_LDLOCA, "ldloca", 0xFFFFFE0D, POP_NONE, PUSH_I, INLINE_VARIABLE  , FLOW_NEXT)
+
+    /**
+     *  Stores the value on top of the evaluation stack in the argument slot at a specified index. 
+     */
+    final val Starg = new OpCode()
+	opcode(Starg, CEE_STARG, "starg", 0xFFFFFE0B, POP_1   , PUSH_NONE, INLINE_VARIABLE  , FLOW_NEXT)
+
+    /**
+     * Pops the current value from the top of the evaluation stack and stores it in a 
+     * the local variable list at a specified index. 
+     */
+    final val Stloc = new OpCode()
+	opcode(Stloc, CEE_STLOC, "stloc", 0xFFFFFE0E, POP_1   , PUSH_NONE, INLINE_VARIABLE  , FLOW_NEXT)
+
+    /**
+     * Allocates a certain number of bytes from the local dynamic memory pool and pushes the 
+     * address (a transient pointer, type *) of the first allocated Byte onto the evaluation stack.
+     */
+    final val Localloc = new OpCode()
+	opcode(Localloc, CEE_LOCALLOC, "localloc"  , 0xFFFFFE0F, POP_I, PUSH_I, INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Transfers control from the filter clause of an exception back to the 
+     * Common Language Infrastructure (CLI) exception handler. 
+     */
+    final val Endfilter = new OpCode()
+	opcode(Endfilter, CEE_ENDFILTER, "endfilter" , 0xFFFFFE11, POP_I   , PUSH_NONE, INLINE_NONE, FLOW_RETURN)
+
+    /**
+     * Indicates that an address currently atop the evaluation stack might not be aligned 
+     * to the natural size of the immediately following ldind, stind, ldfld, stfld, ldobj, 
+     * stobj, initblk, or cpblk instruction. 
+     */
+    final val Unaligned = new OpCode()
+	opcode(Unaligned, CEE_UNALIGNED, "unaligned.", 0xFFFFFE12, POP_NONE, PUSH_NONE, INLINE_I_S , FLOW_META)
+
+    /**
+     * Specifies that an address currently atop the evaluation stack might be volatile, 
+     * and the results of reading that location cannot be cached or that multiple stores 
+     * to that location cannot be suppressed. 
+     */
+    final val Volatile = new OpCode()
+	opcode(Volatile, CEE_VOLATILE, "volatile." , 0xFFFFFE13, POP_NONE, PUSH_NONE, INLINE_NONE, FLOW_META)
+
+    /**
+     * Performs a postfixed method call instruction such that the current method's stack 
+     * frame is removed before the actual call instruction is executed. 
+     */
+    final val Tailcall = new OpCode()
+	opcode(Tailcall, CEE_TAILCALL, "tail."     , 0xFFFFFE14, POP_NONE, PUSH_NONE, INLINE_NONE, FLOW_META)
+
+    /**
+     * Initializes all the fields of the object at a specific address to a null reference 
+     * or a 0 of the appropriate primitive type. 
+     */
+    final val Initobj = new OpCode()
+	opcode(Initobj, CEE_INITOBJ , "initobj"   , 0xFFFFFE15, POP_I   , PUSH_NONE, INLINE_TYPE, FLOW_NEXT)
+
+    /**
+     * Copies a specified number bytes from a source address to a destination address .  
+     */
+    final val Cpblk = new OpCode()
+	opcode(Cpblk, CEE_CPBLK , "cpblk"     , 0xFFFFFE17, POP_I_I_I, PUSH_NONE, INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Initializes a specified block of memory at a specific address to a given size 
+     * and initial value. 
+     */
+    final val Initblk = new OpCode()
+	opcode(Initblk, CEE_INITBLK , "initblk"   , 0xFFFFFE18, POP_I_I_I, PUSH_NONE, INLINE_NONE, FLOW_NEXT)
+
+    /**
+     * Rethrows the current exception. 
+     */
+    final val Rethrow = new OpCode()
+	opcode(Rethrow, CEE_RETHROW , "rethrow", 0xFFFFFE1A, POP_NONE , PUSH_NONE, INLINE_NONE, FLOW_THROW)
+
+    /**
+     * Pushes the size, in bytes, of a supplied value type onto the evaluation stack.
+     */
+    final val Sizeof = new OpCode()
+	opcode(Sizeof, CEE_SIZEOF, "sizeof", 0xFFFFFE1C, POP_NONE , PUSH_I   , INLINE_TYPE, FLOW_NEXT)
+
+
+
+    //##########################################################################
+}
diff --git a/src/msil/ch/epfl/lamp/compiler/msil/emit/OpCodes.scala b/src/msil/ch/epfl/lamp/compiler/msil/emit/OpCodes.scala
new file mode 100644
index 0000000..a9ab2f1
--- /dev/null
+++ b/src/msil/ch/epfl/lamp/compiler/msil/emit/OpCodes.scala
@@ -0,0 +1,1195 @@
+/*
+ * System.Reflection.Emit-like API for writing .NET assemblies to MSIL
+ */
+
+
+package ch.epfl.lamp.compiler.msil.emit
+
+
+/**
+ * Provides field representations of the Microsoft Intermediate Language (MSIL)
+ * instructions for emission by the ILGenerator class members (such as Emit).
+ *
+ * @author Nikolay Mihaylov
+ * @version 1.0
+ */
+object OpCodes {
+
+    //##########################################################################
+
+    /**
+     * Adds two values and pushes the result onto the evaluation stack.
+     */
+     final val Add = OpCode.Add
+
+    /**
+     * Fills space if bytecodes are patched. No meaningful operation is performed 
+     * although a processing cycle can be consumed.
+     */
+     final val Nop = OpCode.Nop
+
+    /**
+     * Signals the Common Language Infrastructure (CLI) to inform the debugger that 
+     * a break point has been tripped.
+     */
+     final val Break = OpCode.Break
+
+    /**
+     * Loads the argument at index 0 onto the evaluation stack.
+     */
+     final val Ldarg_0 = OpCode.Ldarg_0
+
+    /**
+     * Loads the argument at index 1 onto the evaluation stack.
+     */
+     final val Ldarg_1 = OpCode.Ldarg_1
+
+    /**
+     * Loads the argument at index 2 onto the evaluation stack.
+     */
+     final val Ldarg_2 = OpCode.Ldarg_2
+
+    /**
+     * Loads the argument at index 3 onto the evaluation stack.
+     */
+     final val Ldarg_3 = OpCode.Ldarg_3
+
+    /**
+     * Loads the local variable at index 0 onto the evaluation stack.
+     */
+     final val Ldloc_0 = OpCode.Ldloc_0
+
+    /**
+     * Loads the local variable at index 1 onto the evaluation stack.
+     */
+     final val Ldloc_1 = OpCode.Ldloc_1
+
+    /**
+     * Loads the local variable at index 2 onto the evaluation stack.
+     */
+     final val Ldloc_2 = OpCode.Ldloc_2
+
+    /**
+     * Loads the local variable at index 3 onto the evaluation stack.
+     */
+     final val Ldloc_3 = OpCode.Ldloc_3
+
+    /**
+     * Pops the current value from the top of the evaluation stack and 
+     * stores it in a the local variable list at index 0.
+     */
+     final val Stloc_0 = OpCode.Stloc_0
+
+    /**
+     * Pops the current value from the top of the evaluation stack and 
+     * stores it in a the local variable list at index 1.
+     */
+     final val Stloc_1 = OpCode.Stloc_1
+
+    /**
+     * Pops the current value from the top of the evaluation stack and 
+     * stores it in a the local variable list at index 2.
+     */
+     final val Stloc_2 = OpCode.Stloc_2
+
+    /**
+     * Pops the current value from the top of the evaluation stack and 
+     * stores it in a the local variable list at index 3.
+     */
+     final val Stloc_3 = OpCode.Stloc_3
+
+    /**
+     * Loads the argument (referenced by a specified short form index) 
+     * onto the evaluation stack.
+     */
+     final val Ldarg_S = OpCode.Ldarg_S
+
+    /**
+     * Load an argument address, in short form, onto the evaluation stack.
+     */
+     final val Ldarga_S = OpCode.Ldarga_S
+
+    /**
+     * Loads the local variable at a specific index onto the evaluation stack, 
+     * short form.
+     */
+     final val Ldloc_S = OpCode.Ldloc_S
+
+    /**
+     * Loads the address of the local variable at a specific index onto 
+     * the evaluation stack, short form.
+     */
+     final val Ldloca_S = OpCode.Ldloca_S
+
+    /**
+     * Stores the value on top of the evaluation stack in the argument slot 
+     * at a specified index, short form. 
+     */
+     final val Starg_S = OpCode.Starg_S
+
+    /**
+     * Pops the current value from the top of the evaluation stack and stores it 
+     * in a the local variable list at index (short form). 
+     */
+     final val Stloc_S = OpCode.Stloc_S
+
+    /**
+     * Pushes a null reference (type O) onto the evaluation stack. 
+     */
+     final val Ldnull = OpCode.Ldnull
+
+    /**
+     * Pushes the integer value of -1 onto the evaluation stack as an int32.  
+     */
+     final val Ldc_I4_M1 = OpCode.Ldc_I4_M1
+
+    /**
+     * Pushes the integer value of 0 onto the evaluation stack as an int32. 
+     */
+     final val Ldc_I4_0 = OpCode.Ldc_I4_0
+
+    /**
+     * Pushes the integer value of 1 onto the evaluation stack as an int32. 
+     */
+     final val Ldc_I4_1 = OpCode.Ldc_I4_1
+
+    /**
+     * Pushes the integer value of 2 onto the evaluation stack as an int32. 
+     */
+     final val Ldc_I4_2 = OpCode.Ldc_I4_2
+
+    /**
+     * Pushes the integer value of 3 onto the evaluation stack as an int32. 
+     */
+     final val Ldc_I4_3 = OpCode.Ldc_I4_3
+
+    /**
+     * Pushes the integer value of 4 onto the evaluation stack as an int32.  
+     */
+     final val Ldc_I4_4 = OpCode.Ldc_I4_4
+
+    /**
+     * Pushes the integer value of 5 onto the evaluation stack as an int32. 
+     */
+     final val Ldc_I4_5 = OpCode.Ldc_I4_5
+
+    /**
+     * Pushes the integer value of 6 onto the evaluation stack as an int32.
+     */
+     final val Ldc_I4_6 = OpCode.Ldc_I4_6
+
+    /**
+     * Pushes the integer value of 7 onto the evaluation stack as an int32. 
+     */
+     final val Ldc_I4_7 = OpCode.Ldc_I4_7
+
+    /**
+     * Pushes the integer value of 8 onto the evaluation stack as an int32. 
+     */
+     final val Ldc_I4_8 = OpCode.Ldc_I4_8
+
+    /**
+     * Pushes the supplied int8 value onto the evaluation stack as an int32, short form.
+     */
+     final val Ldc_I4_S = OpCode.Ldc_I4_S
+
+    /**
+     * Pushes a supplied value of type int32 onto the evaluation stack as an int32. 
+     */
+     final val Ldc_I4 = OpCode.Ldc_I4
+
+    /**
+     *  Pushes a supplied value of type int64 onto the evaluation stack as an int64.  
+     */
+     final val Ldc_I8 = OpCode.Ldc_I8
+
+    /**
+     * Pushes a supplied value of type float32 onto the evaluation stack as type F (float). 
+     */
+     final val Ldc_R4 = OpCode.Ldc_R4
+
+    /**
+     * Pushes a supplied value of type float64 onto the evaluation stack as type F (float). 
+     */
+     final val Ldc_R8 = OpCode.Ldc_R8
+
+    /**
+     * Copies the current topmost value on the evaluation stack, and then pushes the copy 
+     * onto the evaluation stack. 
+     */
+     final val Dup = OpCode.Dup
+
+    /**
+     * Removes the value currently on top of the evaluation stack. 
+     */
+     final val Pop = OpCode.Pop
+
+    /**
+     * Exits current method and jumps to specified method. 
+     */
+     final val Jmp = OpCode.Jmp
+
+    /**
+     * Calls the method indicated by the passed method descriptor. 
+     */
+     final val Call = OpCode.Call
+
+    /**
+     * Calls the method indicated on the evaluation stack (as a pointer to an entry point) 
+     * with arguments described by a calling convention. 
+     */
+     final val Calli = OpCode.Calli
+
+    /**
+     * Returns from the current method, pushing a return value (if present) from the caller's 
+     * evaluation stack onto the callee's evaluation stack. 
+     */
+     final val Ret = OpCode.Ret
+
+    /**
+     * Unconditionally transfers control to a target instruction (short form). 
+     */
+     final val Br_S = OpCode.Br_S
+
+    /**
+     * Transfers control to a target instruction if value is false, a null reference, or zero. 
+     */
+     final val Brfalse_S = OpCode.Brfalse_S
+
+    /**
+     * Transfers control to a target instruction (short form) if value is true, not null, or non-zero. 
+     */
+     final val Brtrue_S = OpCode.Brtrue_S
+
+    /**
+     * Transfers control to a target instruction (short form) if two values are equal.
+     */
+     final val Beq_S = OpCode.Beq_S
+
+    /**
+     * Transfers control to a target instruction (short form) if the first value is greater than 
+     * or equal to the second value. 
+     */
+     final val Bge_S = OpCode.Bge_S
+
+    /**
+     * Transfers control to a target instruction (short form) if the first value is greater than 
+     * the second value. 
+     */
+     final val Bgt_S = OpCode.Bgt_S
+
+    /**
+     * Transfers control to a target instruction (short form) if the first value is less than 
+     * or equal to the second value.
+     */
+     final val Ble_S = OpCode.Ble_S
+
+    /**
+     * Transfers control to a target instruction (short form) if the first value is less than 
+     * the second value. 
+     */
+     final val Blt_S = OpCode.Blt_S
+
+    /**
+     * Transfers control to a target instruction (short form) when two unsigned integer values 
+     * or unordered float values are not equal. 
+     */
+     final val Bne_Un_S = OpCode.Bne_Un_S
+
+    /**
+     * Transfers control to a target instruction (short form) if if the the first value is greather 
+     * than the second value, when comparing unsigned integer values or unordered float values. 
+     */
+     final val Bge_Un_S = OpCode.Bge_Un_S
+
+    /**
+     * Transfers control to a target instruction (short form) if the first value is greater than 
+     * the second value, when comparing unsigned integer values or unordered float values. 
+     */
+     final val Bgt_Un_S = OpCode.Bgt_Un_S
+
+    /**
+     * Transfers control to a target instruction (short form) if the first value is less than 
+     * or equal to the second value, when comparing unsigned integer values or unordered float values. 
+     */
+     final val Ble_Un_S = OpCode.Ble_Un_S
+
+    /**
+     * Transfers control to a target instruction (short form) if the first value is less than 
+     * the second value, when comparing unsigned integer values or unordered float values. 
+     */
+     final val Blt_Un_S = OpCode.Blt_Un_S
+
+    /**
+     * Unconditionally transfers control to a target instruction. 
+     */
+     final val Br = OpCode.Br
+
+    /**
+     * Transfers control to a target instruction if value is false, a null reference 
+     * (Nothing in Visual Basic), or zero. 
+     */
+     final val Brfalse = OpCode.Brfalse
+
+    /**
+     * Transfers control to a target instruction if value is true, not null, or non-zero. 
+     */
+     final val Brtrue = OpCode.Brtrue
+
+    /**
+     * Transfers control to a target instruction if two values are equal.
+     */
+     final val Beq = OpCode.Beq
+
+    /**
+     * Transfers control to a target instruction if the first value is greater than or 
+     * equal to the second value.
+     */
+     final val Bge = OpCode.Bge
+
+    /**
+     * Transfers control to a target instruction if the first value is greater than the second value.
+     */
+     final val Bgt = OpCode.Bgt
+
+    /**
+     * Transfers control to a target instruction if the first value is less than or equal 
+     * to the second value.
+     */
+     final val Ble = OpCode.Ble
+
+    /**
+     *  Transfers control to a target instruction if the first value is less than the second value. 
+     */
+     final val Blt = OpCode.Blt
+
+    /**
+     * Transfers control to a target instruction when two unsigned integer values or 
+     * unordered float values are not equal. 
+     */
+     final val Bne_Un = OpCode.Bne_Un
+
+    /**
+     * Transfers control to a target instruction if the the first value is greather than 
+     * the second value, when comparing unsigned integer values or unordered float values.
+     */
+     final val Bge_Un = OpCode.Bge_Un
+
+    /**
+     * Transfers control to a target instruction if the first value is greater than the 
+     * second value, when comparing unsigned integer values or unordered float values. 
+     */
+     final val Bgt_Un = OpCode.Bgt_Un
+
+    /**
+     * Transfers control to a target instruction if the first value is less than or equal to 
+     * the second value, when comparing unsigned integer values or unordered float values. 
+     */
+     final val Ble_Un = OpCode.Ble_Un
+
+    /**
+     * Transfers control to a target instruction if the first value is less than the second value, 
+     * when comparing unsigned integer values or unordered float values. 
+     */
+     final val Blt_Un = OpCode.Blt_Un
+
+    /**
+     * Implements a jump table. 
+     */
+     final val Switch = OpCode.Switch
+
+    /**
+     * Loads a value of type int8 as an int32 onto the evaluation stack indirectly. 
+     */
+     final val Ldind_I1 = OpCode.Ldind_I1
+
+    /**
+     *  Loads a value of type int16 as an int32 onto the evaluation stack indirectly.
+     */
+     final val Ldind_I2 = OpCode.Ldind_I2
+
+    /**
+     * Loads a value of type int32 as an int32 onto the evaluation stack indirectly. 
+     */
+     final val Ldind_I4 = OpCode.Ldind_I4
+
+    /**
+     * Loads a value of type int64 as an int64 onto the evaluation stack indirectly. 
+     */
+     final val Ldind_I8 = OpCode.Ldind_I8
+
+    /**
+     * Loads a value of type natural int as a natural int onto the evaluation stack indirectly. 
+     */
+     final val Ldind_I = OpCode.Ldind_I
+
+    /**
+     *  Loads a value of type float32 as a type F (float) onto the evaluation stack indirectly. 
+     */
+     final val Ldind_R4 = OpCode.Ldind_R4
+
+    /**
+     * Loads a value of type float64 as a type F (float) onto the evaluation stack indirectly. 
+     */
+     final val Ldind_R8 = OpCode.Ldind_R8
+
+    /**
+     * Loads an object reference as a type O (object reference) onto the evaluation stack indirectly. 
+     */
+     final val Ldind_Ref = OpCode.Ldind_Ref
+
+    /**
+     * Loads a value of type unsigned int8 as an int32 onto the evaluation stack indirectly. 
+     */
+     final val Ldind_U1 = OpCode.Ldind_U1
+
+    /**
+     * Loads a value of type unsigned int16 as an int32 onto the evaluation stack indirectly. 
+     */
+     final val Ldind_U2 = OpCode.Ldind_U2
+
+    /**
+     * Loads a value of type unsigned int32 as an int32 onto the evaluation stack indirectly. 
+     */
+     final val Ldind_U4 = OpCode.Ldind_U4
+
+    /**
+     * Stores a object reference value at a supplied address. 
+     */
+     final val Stind_Ref = OpCode.Stind_Ref
+
+    /**
+     * Stores a value of type int8 at a supplied address. 
+     */
+     final val Stind_I1 = OpCode.Stind_I1
+
+    /**
+     * Stores a value of type int16 at a supplied address. 
+     */
+     final val Stind_I2 = OpCode.Stind_I2
+
+    /**
+     * Stores a value of type int32 at a supplied address. 
+     */
+     final val Stind_I4 = OpCode.Stind_I4
+
+    /**
+     * Stores a value of type int64 at a supplied address. 
+     */
+     final val Stind_I8 = OpCode.Stind_I8
+
+    /**
+     * Stores a value of type float32 at a supplied address. 
+     */
+     final val Stind_R4 = OpCode.Stind_R4
+
+    /**
+     * Stores a value of type float64 at a supplied address. 
+     */
+     final val Stind_R8 = OpCode.Stind_R8
+
+    /**
+     * Subtracts one value from another and pushes the result onto the evaluation stack. 
+     */
+     final val Sub = OpCode.Sub
+
+    /**
+     * Multiplies two values and pushes the result on the evaluation stack. 
+     */
+     final val Mul = OpCode.Mul
+
+    /**
+     * Divides two values and pushes the result as a floating-point (type F) or 
+     * quotient (type int32) onto the evaluation stack.
+     */
+     final val Div = OpCode.Div
+
+    /**
+     * Divides two unsigned integer values and pushes the result (int32) onto the evaluation stack. 
+     */
+     final val Div_Un = OpCode.Div_Un
+
+    /**
+     * Divides two values and pushes the remainder onto the evaluation stack. 
+     */
+     final val Rem = OpCode.Rem
+
+    /**
+     * Divides two unsigned values and pushes the remainder onto the evaluation stack. 
+     */
+     final val Rem_Un = OpCode.Rem_Un
+
+    /**
+     * Computes the bitwise AND of two values and pushes the result onto the evaluation stack.
+     */
+     final val And = OpCode.And
+
+    /**
+     * Compute the bitwise complement of the two integer values on top of the stack and 
+     * pushes the result onto the evaluation stack. 
+     */
+     final val Or = OpCode.Or
+
+    /**
+     * Computes the bitwise XOR of the top two values on the evaluation stack, 
+     * pushing the result onto the evaluation stack. 
+     */
+     final val Xor = OpCode.Xor
+
+    /**
+     * Shifts an integer value to the left (in zeroes) by a specified number of bits,
+     *  pushing the result onto the evaluation stack.
+     */
+     final val Shl = OpCode.Shl
+
+    /**
+     * Shifts an integer value (in sign) to the right by a specified number of bits, 
+     * pushing the result onto the evaluation stack. 
+     */
+     final val Shr = OpCode.Shr
+
+    /**
+     * Shifts an unsigned integer value (in zeroes) to the right by a specified number of bits, 
+     * pushing the result onto the evaluation stack. 
+     */
+     final val Shr_Un = OpCode.Shr_Un
+
+    /**
+     * Negates a value and pushes the result onto the evaluation stack. 
+     */
+     final val Neg = OpCode.Neg
+
+    /**
+     * Computes the bitwise complement of the integer value on top of the stack and pushes 
+     * the result onto the evaluation stack as the same type.
+     */
+     final val Not = OpCode.Not
+
+    /**
+     *  Converts the value on top of the evaluation stack to int8, then extends (pads) it to int32. 
+     */
+     final val Conv_I1 = OpCode.Conv_I1
+
+    /**
+     * Converts the value on top of the evaluation stack to int16, then extends (pads) it to int32. 
+     */
+     final val Conv_I2 = OpCode.Conv_I2
+
+    /**
+     * Converts the value on top of the evaluation stack to int32. 
+     */
+     final val Conv_I4 = OpCode.Conv_I4
+
+    /**
+     * Converts the value on top of the evaluation stack to int64. 
+     */
+     final val Conv_I8 = OpCode.Conv_I8
+
+    /**
+     * Converts the value on top of the evaluation stack to float32. 
+     */
+     final val Conv_R4 = OpCode.Conv_R4
+
+    /**
+     * Converts the value on top of the evaluation stack to float64. 
+     */
+     final val Conv_R8 = OpCode.Conv_R8
+
+    /**
+     * Converts the value on top of the evaluation stack to unsigned int32, and extends it to int32. 
+     */
+     final val Conv_U4 = OpCode.Conv_U4
+
+    /**
+     * Converts the value on top of the evaluation stack to unsigned int64, and extends it to int64. 
+     */
+     final val Conv_U8 = OpCode.Conv_U8
+
+    /**
+     * Calls a late-bound method on an object, pushing the return value onto the evaluation stack. 
+     */
+     final val Callvirt = OpCode.Callvirt
+
+    /**
+     * Copies the value type located at the address of an object (type &, * or natural int) 
+     * to the address of the destination object (type &, * or natural int). 
+     */
+     final val Cpobj = OpCode.Cpobj
+
+    /**
+     * Copies the value type object pointed to by an address to the top of the evaluation stack. 
+     */
+     final val Ldobj = OpCode.Ldobj
+
+    /**
+     * Pushes a new object reference to a string literal stored in the metadata. 
+     */
+     final val Ldstr = OpCode.Ldstr
+
+    /**
+     * Creates a new object or a new instance of a value type, pushing an object reference 
+     * (type O) onto the evaluation stack. 
+     */
+     final val Newobj = OpCode.Newobj
+
+    /**
+     * Attempts to cast an object passed by reference to the specified class. 
+     */
+     final val Castclass = OpCode.Castclass
+
+    /**
+     * Tests whether an object reference (type O) is an instance of a particular class.
+     */
+     final val Isinst = OpCode.Isinst
+
+    /**
+     *  Converts the unsigned integer value on top of the evaluation stack to float32. 
+     */
+     final val Conv_R_Un = OpCode.Conv_R_Un
+
+    /**
+     * Converts the boxed representation of a value type to its unboxed form. 
+     */
+     final val Unbox = OpCode.Unbox
+
+    /**
+     * Throws the exception object currently on the evaluation stack. 
+     */
+     final val Throw = OpCode.Throw
+
+    /**
+     *  Finds the value of a field in the object whose reference is currently 
+     * on the evaluation stack. 
+     */
+     final val Ldfld = OpCode.Ldfld
+
+    /**
+     *  Finds the address of a field in the object whose reference is currently 
+     * on the evaluation stack. 
+     */
+     final val Ldflda = OpCode.Ldflda
+
+    /**
+     * Pushes the value of a static field onto the evaluation stack. 
+     */
+     final val Ldsfld = OpCode.Ldsfld
+
+    /**
+     * Pushes the address of a static field onto the evaluation stack. 
+     */
+     final val Ldsflda = OpCode.Ldsflda
+
+    /**
+     *  Replaces the value stored in the field of an object reference or pointer with a new value. 
+     */
+     final val Stfld = OpCode.Stfld
+
+    /**
+     * Replaces the value of a static field with a value from the evaluation stack. 
+     */
+     final val Stsfld = OpCode.Stsfld
+
+    /**
+     * Copies a value of a specified type from the evaluation stack into a supplied memory address. 
+     */
+     final val Stobj = OpCode.Stobj
+
+    /**
+     * Converts the unsigned value on top of the evaluation stack to signed int8 and 
+     * extends it to int32, throwing OverflowException on overflow.
+     */
+     final val Conv_Ovf_I1_Un = OpCode.Conv_Ovf_I1_Un
+
+    /**
+     *  Converts the unsigned value on top of the evaluation stack to signed int16 and 
+     * extends it to int32, throwing OverflowException on overflow. 
+     */
+     final val Conv_Ovf_I2_Un = OpCode.Conv_Ovf_I2_Un
+
+    /**
+     * Converts the unsigned value on top of the evaluation stack to signed int32, 
+     * throwing OverflowException on overflow. 
+     */
+     final val Conv_Ovf_I4_Un = OpCode.Conv_Ovf_I4_Un
+
+    /**
+     * Converts the unsigned value on top of the evaluation stack to signed int64, 
+     * throwing OverflowException on overflow. 
+     */
+     final val Conv_Ovf_I8_Un = OpCode.Conv_Ovf_I8_Un
+
+    /**
+     * Converts the unsigned value on top of the evaluation stack to signed natural int, 
+     * throwing OverflowException on overflow. 
+     */
+     final val Conv_Ovf_I_Un = OpCode.Conv_Ovf_I_Un
+
+    /**
+     * Converts the unsigned value on top of the evaluation stack to unsigned int8 and 
+     * extends it to int32, throwing OverflowException on overflow. 
+     */
+     final val Conv_Ovf_U1_Un = OpCode.Conv_Ovf_U1_Un
+
+    /**
+     * Converts the unsigned value on top of the evaluation stack to unsigned int16 and 
+     * extends it to int32, throwing OverflowException on overflow. 
+     */
+     final val Conv_Ovf_U2_Un = OpCode.Conv_Ovf_U2_Un
+
+    /**
+     * Converts the unsigned value on top of the evaluation stack to unsigned int32, 
+     * throwing OverflowException on overflow. 
+     */
+     final val Conv_Ovf_U4_Un = OpCode.Conv_Ovf_U4_Un
+
+    /**
+     * Converts the unsigned value on top of the evaluation stack to unsigned int64, 
+     * throwing OverflowException on overflow. 
+     */
+     final val Conv_Ovf_U8_Un = OpCode.Conv_Ovf_U8_Un
+
+    /**
+     * Converts the unsigned value on top of the evaluation stack to unsigned natural int, 
+     * throwing OverflowException on overflow. 
+     */
+     final val Conv_Ovf_U_Un = OpCode.Conv_Ovf_U_Un
+
+    /**
+     * Converts a value type to an object reference (type O).
+     */
+     final val Box = OpCode.Box
+
+    /**
+     * Pushes an object reference to a new zero-based, one-dimensional array whose elements 
+     * are of a specific type onto the evaluation stack. 
+     */
+     final val Newarr = OpCode.Newarr
+
+    /**
+     * Pushes the number of elements of a zero-based, one-dimensional array 
+     * onto the evaluation stack. 
+     */
+     final val Ldlen = OpCode.Ldlen
+
+    /**
+     * Loads the address of the array element at a specified array index onto 
+     * the top of the evaluation stack as type & (managed pointer).
+     */
+     final val Ldelema = OpCode.Ldelema
+
+    /**
+     * Loads the element with type natural int at a specified array index onto the top 
+     * of the evaluation stack as a natural int. 
+     */
+     final val Ldelem_I = OpCode.Ldelem_I
+
+    /**
+     * Loads the element with type int8 at a specified array index onto the top of the 
+     * evaluation stack as an int32. 
+     */
+     final val Ldelem_I1 = OpCode.Ldelem_I1
+
+    /**
+     * Loads the element with type int16 at a specified array index onto the top of 
+     * the evaluation stack as an int32. 
+     */
+     final val Ldelem_I2 = OpCode.Ldelem_I2
+
+    /**
+     *  Loads the element with type int32 at a specified array index onto the top of the 
+     * evaluation stack as an int32.  
+     */
+     final val Ldelem_I4 = OpCode.Ldelem_I4
+
+    /**
+     *  Loads the element with type int64 at a specified array index onto the top of the 
+     * evaluation stack as an int64.
+     */
+     final val Ldelem_I8 = OpCode.Ldelem_I8
+
+    /**
+     * Loads the element with type float32 at a specified array index onto the top of the 
+     * evaluation stack as type F (float) 
+     */
+     final val Ldelem_R4 = OpCode.Ldelem_R4
+
+    /**
+     * Loads the element with type float64 at a specified array index onto the top of the 
+     * evaluation stack as type F (float) .
+     */
+     final val Ldelem_R8 = OpCode.Ldelem_R8
+
+    /**
+     * Loads the element containing an object reference at a specified array index onto 
+     * the top of the evaluation stack as type O (object reference). 
+     */
+     final val Ldelem_Ref = OpCode.Ldelem_Ref
+
+    /**
+     * Loads the element with type unsigned int8 at a specified array index onto the top 
+     * of the evaluation stack as an int32.  
+     */
+     final val Ldelem_U1 = OpCode.Ldelem_U1
+
+    /**
+     * Loads the element with type unsigned int16 at a specified array index onto the top 
+     * of the evaluation stack as an int32.
+     */
+     final val Ldelem_U2 = OpCode.Ldelem_U2
+
+    /**
+     * Loads the element with type unsigned int32 at a specified array index onto the top 
+     * of the evaluation stack as an int32.  
+     */
+     final val Ldelem_U4 = OpCode.Ldelem_U4
+
+    /**
+     *  Replaces the array element at a given index with the natural int value on 
+     * the evaluation stack. 
+     */
+     final val Stelem_I = OpCode.Stelem_I
+
+    /**
+     * Replaces the array element at a given index with the int8 value on the evaluation stack. 
+     */
+     final val Stelem_I1 = OpCode.Stelem_I1
+
+    /**
+     *  Replaces the array element at a given index with the int16 value on the evaluation stack. 
+     */
+     final val Stelem_I2 = OpCode.Stelem_I2
+
+    /**
+     *  Replaces the array element at a given index with the int32 value on the evaluation stack. 
+     */
+     final val Stelem_I4 = OpCode.Stelem_I4
+
+    /**
+     * Replaces the array element at a given index with the int64 value on the evaluation stack. 
+     */
+     final val Stelem_I8 = OpCode.Stelem_I8
+
+    /**
+     * Replaces the array element at a given index with the float32 value on the evaluation stack. 
+     */
+     final val Stelem_R4 = OpCode.Stelem_R4
+
+    /**
+     * Replaces the array element at a given index with the float64 value on the evaluation stack. 
+     */
+     final val Stelem_R8 = OpCode.Stelem_R8
+
+    /**
+     * Replaces the array element at a given index with the object ref value (type O) 
+     * on the evaluation stack. 
+     */
+     final val Stelem_Ref = OpCode.Stelem_Ref
+
+    /**
+     * Converts the signed value on top of the evaluation stack to signed int8 and 
+     * extends it to int32, throwing OverflowException on overflow. 
+     */
+     final val Conv_Ovf_I1 = OpCode.Conv_Ovf_I1
+
+    /**
+     * Converts the signed value on top of the evaluation stack to signed int16 and 
+     * extending it to int32, throwing OverflowException on overflow. 
+     */
+     final val Conv_Ovf_I2 = OpCode.Conv_Ovf_I2
+
+    /**
+     * Converts the signed value on top of the evaluation stack to signed int32, 
+     * throwing OverflowException on overflow. 
+     */
+     final val Conv_Ovf_I4 = OpCode.Conv_Ovf_I4
+
+    /**
+     * Converts the signed value on top of the evaluation stack to signed int64, 
+     * throwing OverflowException on overflow. 
+     */
+     final val Conv_Ovf_I8 = OpCode.Conv_Ovf_I8
+
+    /**
+     * Converts the signed value on top of the evaluation stack to unsigned int8 and 
+     * extends it to int32, throwing OverflowException on overflow. 
+     */
+     final val Conv_Ovf_U1 = OpCode.Conv_Ovf_U1
+
+    /**
+     * Converts the signed value on top of the evaluation stack to unsigned int16 and 
+     * extends it to int32, throwing OverflowException on overflow. 
+     */
+     final val Conv_Ovf_U2 = OpCode.Conv_Ovf_U2
+
+    /**
+     *  Converts the signed value on top of the evaluation stack to unsigned int32, 
+     * throwing OverflowException on overflow. 
+     */
+     final val Conv_Ovf_U4 = OpCode.Conv_Ovf_U4
+
+    /**
+     * Converts the signed value on top of the evaluation stack to unsigned int64, 
+     * throwing OverflowException on overflow. 
+     */
+     final val Conv_Ovf_U8 = OpCode.Conv_Ovf_U8
+
+    /**
+     *  Retrieves the address (type &) embedded in a typed reference. 
+     */
+     final val Refanyval = OpCode.Refanyval
+
+    /**
+     * Retrieves the type token embedded in a typed reference .  
+     */
+     final val Refanytype = OpCode.Refanytype
+
+    /**
+     * Throws ArithmeticException if value is not a finite number.
+     */
+     final val Ckfinite = OpCode.Ckfinite
+
+    /**
+     * Pushes a typed reference to an instance of a specific type onto the evaluation stack. 
+     */
+     final val Mkrefany = OpCode.Mkrefany
+
+    /**
+     * Converts a metadata token to its runtime representation, pushing it onto the evaluation stack. 
+     */
+     final val Ldtoken = OpCode.Ldtoken
+
+    /**
+     * Converts the value on top of the evaluation stack to unsigned int8, and extends it to int32. 
+     */
+     final val Conv_U1 = OpCode.Conv_U1
+
+    /**
+     * Converts the value on top of the evaluation stack to unsigned int16, and extends it to int32. 
+     */
+     final val Conv_U2 = OpCode.Conv_U2
+
+    /**
+     * Converts the value on top of the evaluation stack to natural int. 
+     */
+     final val Conv_I = OpCode.Conv_I
+
+    /**
+     * Converts the signed value on top of the evaluation stack to signed natural int, 
+     * throwing OverflowException on overflow.
+     */
+     final val Conv_Ovf_I = OpCode.Conv_Ovf_I
+
+    /**
+     * Converts the signed value on top of the evaluation stack to unsigned natural int, 
+     * throwing OverflowException on overflow.
+     */
+     final val Conv_Ovf_U = OpCode.Conv_Ovf_U
+
+    /**
+     * Adds two integers, performs an overflow check, and pushes the result 
+     * onto the evaluation stack. 
+     */
+     final val Add_Ovf = OpCode.Add_Ovf
+
+    /**
+     *  Adds two unsigned integer values, performs an overflow check, and pushes the result 
+     * onto the evaluation stack. 
+     */
+     final val Add_Ovf_Un = OpCode.Add_Ovf_Un
+
+    /**
+     * Multiplies two integer values, performs an overflow check, and pushes the result 
+     * onto the evaluation stack. 
+     */
+     final val Mul_Ovf = OpCode.Mul_Ovf
+
+    /**
+     * Multiplies two unsigned integer values , performs an overflow check , 
+     * and pushes the result onto the evaluation stack. 
+     */
+     final val Mul_Ovf_Un = OpCode.Mul_Ovf_Un
+
+    /**
+     * Subtracts one integer value from another, performs an overflow check, 
+     * and pushes the result onto the evaluation stack. 
+     */
+     final val Sub_Ovf = OpCode.Sub_Ovf
+
+    /**
+     * Subtracts one unsigned integer value from another, performs an overflow check, 
+     * and pushes the result onto the evaluation stack. 
+     */
+     final val Sub_Ovf_Un = OpCode.Sub_Ovf_Un
+
+    /**
+     * Transfers control from the fault or finally clause of an exception block back to 
+     * the Common Language Infrastructure (CLI) exception handler. 
+     */
+     final val Endfinally = OpCode.Endfinally
+
+    /**
+     * Exits a protected region of code, unconditionally tranferring control 
+     * to a specific target instruction. 
+     */
+     final val Leave = OpCode.Leave
+
+    /**
+     * Exits a protected region of code, unconditionally tranferring control 
+     * to a target instruction (short form). 
+     */
+     final val Leave_S = OpCode.Leave_S
+
+    /**
+     * Stores a value of type natural int at a supplied address. 
+     */
+     final val Stind_I = OpCode.Stind_I
+
+    /**
+     *  Converts the value on top of the evaluation stack to unsigned natural int, 
+     * and extends it to natural int. 
+     */
+     final val Conv_U = OpCode.Conv_U
+
+    /**
+     * Returns an unmanaged pointer to the argument list of the current method. 
+     */
+     final val Arglist = OpCode.Arglist
+
+    /**
+     * Compares two values. If they are equal, the integer value 1 (int32) is pushed 
+     * onto the evaluation stack otherwise 0 (int32) is pushed onto the evaluation stack. 
+     */
+     final val Ceq = OpCode.Ceq
+
+    /**
+     * Compares two values. If the first value is greater than the second, 
+     * the integer value 1 (int32) is pushed onto the evaluation stack 
+     * otherwise 0 (int32) is pushed onto the evaluation stack. 
+     */
+     final val Cgt = OpCode.Cgt
+
+    /**
+     *  Compares two unsigned or unordered values. If the first value is greater than 
+     * the second, the integer value 1 (int32) is pushed onto the evaluation stack 
+     * otherwise 0 (int32) is pushed onto the evaluation stack. 
+     */
+     final val Cgt_Un = OpCode.Cgt_Un
+
+    /**
+     * Compares two values. If the first value is less than the second, 
+     * the integer value 1 (int32) is pushed onto the evaluation stack 
+     * otherwise 0 (int32) is pushed onto the evaluation stack. 
+     */
+     final val Clt = OpCode.Clt
+
+    /**
+     *  Compares the unsigned or unordered values value1 and value2. If value1 is 
+     * less than value2, then the integer value 1 (int32) is pushed onto the 
+     * evaluation stack otherwise 0 (int32) is pushed onto the evaluation stack. 
+     */
+     final val Clt_Un = OpCode.Clt_Un
+
+    /**
+     * Pushes an unmanaged pointer (type natural int) to the native code implementing 
+     * a specific method onto the evaluation stack. 
+     */
+     final val Ldftn = OpCode.Ldftn
+
+    /**
+     * Pushes an unmanaged pointer (type natural int) to the native code implementing 
+     * a particular virtual method associated with a specified object onto the evaluation stack. 
+     */
+     final val Ldvirtftn = OpCode.Ldvirtftn
+
+    /**
+     * Loads an argument (referenced by a specified index value) onto the stack. 
+     */
+     final val Ldarg = OpCode.Ldarg
+
+    /**
+     * Load an argument address onto the evaluation stack. 
+     */
+     final val Ldarga = OpCode.Ldarga
+
+    /**
+     * Loads the local variable at a specific index onto the evaluation stack. 
+     */
+     final val Ldloc = OpCode.Ldloc
+
+    /**
+     *  Loads the address of the local variable at a specific index onto the evaluation stack. 
+     */
+     final val Ldloca = OpCode.Ldloca
+
+    /**
+     *  Stores the value on top of the evaluation stack in the argument slot at a specified index. 
+     */
+     final val Starg = OpCode.Starg
+
+    /**
+     * Pops the current value from the top of the evaluation stack and stores it in a 
+     * the local variable list at a specified index. 
+     */
+     final val Stloc = OpCode.Stloc
+
+    /**
+     * Allocates a certain number of bytes from the local dynamic memory pool and pushes the 
+     * address (a transient pointer, type *) of the first allocated Byte onto the evaluation stack.
+     */
+     final val Localloc = OpCode.Localloc
+
+    /**
+     * Transfers control from the filter clause of an exception back to the 
+     * Common Language Infrastructure (CLI) exception handler. 
+     */
+     final val Endfilter = OpCode.Endfilter
+
+    /**
+     * Indicates that an address currently atop the evaluation stack might not be aligned 
+     * to the natural size of the immediately following ldind, stind, ldfld, stfld, ldobj, 
+     * stobj, initblk, or cpblk instruction. 
+     */
+     final val Unaligned = OpCode.Unaligned
+
+    /**
+     * Specifies that an address currently atop the evaluation stack might be volatile, 
+     * and the results of reading that location cannot be cached or that multiple stores 
+     * to that location cannot be suppressed. 
+     */
+     final val Volatile = OpCode.Volatile
+
+    /**
+     * Performs a postfixed method call instruction such that the current method's stack 
+     * frame is removed before the actual call instruction is executed. 
+     */
+     final val Tailcall = OpCode.Tailcall
+
+    /**
+     * Initializes all the fields of the object at a specific address to a null reference 
+     * or a 0 of the appropriate primitive type. 
+     */
+     final val Initobj = OpCode.Initobj
+
+    /**
+     * Copies a specified number bytes from a source address to a destination address .  
+     */
+     final val Cpblk = OpCode.Cpblk
+
+    /**
+     * Initializes a specified block of memory at a specific address to a given size 
+     * and initial value. 
+     */
+     final val Initblk = OpCode.Initblk
+
+    /**
+     * Rethrows the current exception. 
+     */
+     final val Rethrow = OpCode.Rethrow
+
+    /**
+     * Pushes the size, in bytes, of a supplied value type onto the evaluation stack.
+     */
+     final val Sizeof = OpCode.Sizeof
+
+    //##########################################################################
+}
diff --git a/src/msil/ch/epfl/lamp/compiler/msil/emit/ParameterBuilder.scala b/src/msil/ch/epfl/lamp/compiler/msil/emit/ParameterBuilder.scala
new file mode 100644
index 0000000..8f9d81a
--- /dev/null
+++ b/src/msil/ch/epfl/lamp/compiler/msil/emit/ParameterBuilder.scala
@@ -0,0 +1,44 @@
+/*
+ * System.Reflection.Emit-like API for writing .NET assemblies to MSIL
+ */
+
+
+package ch.epfl.lamp.compiler.msil.emit
+
+import ch.epfl.lamp.compiler.msil.Type
+import ch.epfl.lamp.compiler.msil.ConstructorInfo
+import ch.epfl.lamp.compiler.msil.ParameterInfo
+import java.io.IOException
+
+/**
+ * Creates or associates parameter information.
+ * Parameter attributes need to consistent with the method signature.
+ * If you specify Out attributes for a parameter, you should ensure that
+ * the type of that method parameter is a ByRef type
+ *
+ * @author Nikolay Mihaylov
+ * @version 1.0
+ */
+class ParameterBuilder(name: String, tpe: Type, attr: Int, pos: Int)
+      extends ParameterInfo(name, tpe, attr, pos)
+      with ICustomAttributeSetter
+      with Visitable
+{
+
+    //##########################################################################
+
+    /** Sets a custom attribute. */
+    def SetCustomAttribute(constr: ConstructorInfo, value: Array[Byte]) {
+	addCustomAttribute(constr, value)
+    }
+
+    //##########################################################################
+
+    /** The apply method for a visitor */
+    @throws(classOf[IOException])
+    def apply(v: Visitor) {
+	v.caseParameterBuilder(this)
+    }
+
+    //##########################################################################
+}
diff --git a/src/msil/ch/epfl/lamp/compiler/msil/emit/SingleFileILPrinterVisitor.scala b/src/msil/ch/epfl/lamp/compiler/msil/emit/SingleFileILPrinterVisitor.scala
new file mode 100644
index 0000000..0332fcf
--- /dev/null
+++ b/src/msil/ch/epfl/lamp/compiler/msil/emit/SingleFileILPrinterVisitor.scala
@@ -0,0 +1,93 @@
+/*
+ * System.Reflection.Emit-like API for writing .NET assemblies in MSIL
+ */
+
+
+package ch.epfl.lamp.compiler.msil.emit
+
+import java.io.FileWriter
+import java.io.BufferedWriter
+import java.io.PrintWriter
+import java.io.IOException
+import java.util.Iterator
+import java.util.HashMap
+import java.util.Arrays
+
+import ch.epfl.lamp.compiler.msil._
+import ch.epfl.lamp.compiler.msil.emit
+import ch.epfl.lamp.compiler.msil.util.Table
+
+/**
+ * The MSIL printer Visitor. It prints a complete
+ * assembly in a single file. Then this file can be compiled by ilasm.
+ *
+ * @author Nikolay Mihaylov
+ * @author Daniel Lorch
+ * @version 1.0
+ */
+final class SingleFileILPrinterVisitor(_fileName: String) extends ILPrinterVisitor {
+    var fileName: String = _fileName
+
+    out = new PrintWriter(new BufferedWriter(new FileWriter(fileName)))
+    
+   /**
+     * Visit an AssemblyBuilder
+     */
+   @throws(classOf[IOException])
+   def caseAssemblyBuilder(assemblyBuilder: AssemblyBuilder) {
+	ILPrinterVisitor.currAssembly = assemblyBuilder
+
+	// first get the entryPoint
+	this.entryPoint = assemblyBuilder.EntryPoint
+
+	// all external assemblies
+	as = assemblyBuilder.getExternAssemblies()
+	Arrays.sort(as, assemblyNameComparator)
+
+        assemblyBuilder.generatedFiles.add(fileName)
+	printAssemblyBoilerplate()
+
+	// print each module
+        var m: Array[Module] = assemblyBuilder.GetModules()
+        nomembers = true
+        for(val i <- 0 until m.length) {
+	    print(m(i).asInstanceOf[ModuleBuilder])
+	}
+
+        nomembers = false
+        for(val i <- 0 until m.length) {
+	    print(m(i).asInstanceOf[ModuleBuilder])
+	}
+	// close out file
+	out.close()
+	ILPrinterVisitor.currAssembly = null
+    }
+
+    /**
+     * Visit a ModuleBuilder
+     */
+    @throws(classOf[IOException])
+    def caseModuleBuilder(module: ModuleBuilder) {
+	// print module declaration
+	currentModule = module
+        if (nomembers) {
+            print(".module \'"); print(module.Name); println("\'")
+            printAttributes(module)
+        }
+
+	if (!module.globalsCreated)
+	    module.CreateGlobalFunctions()
+
+	var m: Array[MethodInfo] = module.GetMethods()
+        for(val i <- 0 until m.length) {
+	    print(m(i).asInstanceOf[MethodBuilder])
+	}
+
+	var t: Array[Type] = module.GetTypes()
+        for(val i <- 0 until t.length) {
+	    print(t(i).asInstanceOf[TypeBuilder])
+	}
+	currentModule = null
+    }
+
+}  // class SingleFileILPrinterVisitor
diff --git a/src/msil/ch/epfl/lamp/compiler/msil/emit/TypeBuilder.scala b/src/msil/ch/epfl/lamp/compiler/msil/emit/TypeBuilder.scala
new file mode 100644
index 0000000..7421220
--- /dev/null
+++ b/src/msil/ch/epfl/lamp/compiler/msil/emit/TypeBuilder.scala
@@ -0,0 +1,233 @@
+/*
+ * System.Reflection.Emit-like API for writing .NET assemblies to MSIL
+ */
+
+
+package ch.epfl.lamp.compiler.msil.emit
+
+import ch.epfl.lamp.compiler.msil._
+import java.util.HashMap
+import java.util.ArrayList
+import java.util.Iterator
+import java.io.IOException
+
+/**
+ * Defines and creates new instances of classes during runtime.
+ *
+ * @author Nikolay Mihaylov
+ * @version 1.0
+ */
+class TypeBuilder (module: Module, attributes: Int, fullName: String, baseType: Type, interfaces: Array[Type], declType: Type)
+      extends Type(module, attributes, fullName, baseType, interfaces, declType, 0)
+      with ICustomAttributeSetter
+      with Visitable
+{
+    import TypeBuilder._
+
+    //##########################################################################
+    // public members
+
+    /** 'Bakes' the type. */
+    def CreateType(): Type = {
+	fields = fieldBuilders.toArray(new Array[FieldInfo](fieldBuilders.size())).asInstanceOf[Array[FieldInfo]]
+	methods = methodBuilders.toArray(new Array[MethodInfo](methodBuilders.size())).asInstanceOf[Array[MethodInfo]]
+	constructors = constructorBuilders.toArray(new Array[ConstructorInfo](constructorBuilders.size())).asInstanceOf[Array[ConstructorInfo]]
+	nestedTypes = nestedTypeBuilders.toArray(new Array[Type](nestedTypeBuilders.size())).asInstanceOf[Array[Type]]
+
+	raw = false
+	if (DeclaringType == null)
+	    Module.asInstanceOf[ModuleBuilder].addType(this)
+	return this
+    }
+
+    /**
+     * Adds a new field to the class, with the given name, 
+     * attributes and field type.
+     */
+    def DefineField(name: String, `type`: Type, attrs: Short): FieldBuilder = {
+	val field: FieldBuilder = new FieldBuilder(name, this, attrs, `type`)
+	fieldBuilders.add(field)
+	return field
+    }
+
+    /**
+     * Adds a new method to the class, with the given name and 
+     * method signature.
+     */
+    def DefineMethod(name: String, attrs: Short, returnType: Type, paramTypes: Array[Type]): MethodBuilder = {
+	val method = new MethodBuilder(name, this, attrs, returnType, paramTypes)
+    val methods = methodBuilders.iterator()
+    while(methods.hasNext()) {
+        val m = methods.next().asInstanceOf[MethodInfo]
+	    if (methodsEqual(m, method))
+		throw new RuntimeException("["+ Assembly() +
+                   "] Method has already been defined: " + m)
+	}
+	methodBuilders.add(method)
+	return method
+    }
+
+    /**
+     * Adds a new constructor to the class, with the given attributes 
+     * and signature.
+     */
+    def DefineConstructor(attrs: Short, callingConvention: Short, paramTypes: Array[Type]): ConstructorBuilder = {
+	val constr = new ConstructorBuilder(this, attrs, paramTypes)
+	constructorBuilders.add(constr)
+	return constr
+    }
+
+    /**
+     * Defines a nested type given its name.
+     */
+    def DefineNestedType(name: String, attributes: Int, baseType: Type, interfaces: Array[Type]): TypeBuilder = {
+    val nested = nestedTypeBuilders.iterator()
+    while(nested.hasNext()) {
+        val nt = nested.next().asInstanceOf[TypeBuilder]
+		if (nt.Name.equals(name)) {
+		    val message = "Nested type " + name + " has already been defined: " + nt
+		    throw new RuntimeException(message)
+		}
+	    }
+	val t = new TypeBuilder(Module, attributes, name, baseType, interfaces, this)
+	nestedTypeBuilders.add(t)
+	return t
+    }
+
+    /** Get the field with the corresponding name. */
+    override def GetField(name: String): FieldInfo = {
+	testRaw(name)
+	return super.GetField(name)
+    }
+
+    /** Get all fields of the current Type. */
+    override def GetFields(): Array[FieldInfo] = {
+	testRaw("<GetFields>")
+	return super.GetFields()
+    }
+
+    /**
+     * Searches for a public instance constructor whose parameters
+     * match the types in the specified array.
+     */
+    override def GetConstructor(params: Array[Type]): ConstructorInfo = {
+	testRaw(".ctor" + types2String(params))
+	return super.GetConstructor(params)
+    }
+
+    /**
+     * Returns all the public constructors defined for the current Type.
+     */
+    override def GetConstructors(): Array[ConstructorInfo] = {
+	testRaw("<GetConstructors>")
+	return super.GetConstructors()
+    }
+
+    /**
+     * Searches for the specified public method whose parameters 
+     * match the specified argument types.
+     */
+    override def GetMethod(name: String, params: Array[Type]): MethodInfo = {
+	testRaw(name + types2String(params))
+	return super.GetMethod(name, params)
+    }
+
+    /** Returns all the public methods of the current Type. */
+    override def GetMethods(): Array[MethodInfo] = {
+	testRaw("<GetMethods>")
+	return super.GetMethods()
+    }
+
+    /** Searches for the nested type with the specified name. */
+    override def GetNestedType(name: String): Type = {
+      testRaw(name)
+      super.GetNestedType(name)
+    }
+
+    /** Returns all the types nested within the current Type. */
+    override def GetNestedTypes(): Array[Type] = {
+      testRaw("<GetNestedTypes>")
+      super.GetNestedTypes()
+    }
+
+    /** Returns a Type object that represents a one-dimensional array of the current type */
+    def MakeArrayType(): Type = {
+      Type.mkArray(this, 1)
+    }
+
+    /** Sets a custom attribute. */
+    def SetCustomAttribute(constr: ConstructorInfo, value: Array[Byte]) {
+	addCustomAttribute(constr, value)
+    }
+
+    def setPosition(sourceLine: Int, sourceFilename: String) {
+	this.sourceLine = sourceLine
+	this.sourceFilename = sourceFilename
+    }
+
+    def setSourceFilepath(sourceFilepath: String) {
+    this.sourceFilepath = sourceFilepath
+    }
+
+    //##########################################################################
+    // protected members
+
+    var sourceLine: Int = _
+    var sourceFilename: String = _
+    var sourceFilepath: String = _
+
+    var fieldBuilders = new ArrayList[FieldBuilder]()
+    var methodBuilders = new ArrayList[MethodBuilder]()
+    var constructorBuilders = new ArrayList[ConstructorBuilder]()
+    var nestedTypeBuilders = new ArrayList[TypeBuilder]()
+
+    // shows if the type is 'raw', i.e. still subject to changes
+    private var raw = true
+
+    // throws an exception if the type is 'raw',
+    // i.e. not finalized by call to CreateType
+    protected def testRaw(member: String) {
+	if (raw)
+	    throw new RuntimeException("Not supported for TypeBuilder before CreateType(): " +
+		 FullName + "::" + member)
+    }
+
+    //##########################################################################
+    // public members not part of the Reflection.Emit.TypeBuilder interface.
+
+    /** The apply method for a visitor. */
+    @throws(classOf[IOException])
+    def apply(v: Visitor) {
+	v.caseTypeBuilder(this)
+    }
+
+    //##########################################################################
+
+}  // class TypeBuilder
+
+object TypeBuilder {
+    def types2String(types: Array[Type]): String = {
+    var s = new StringBuffer("(")
+    for(val i <- 0 until types.length) {
+        if (i > 0) s.append(", ")
+        s.append(types(i))
+    }
+    s.append(")")
+    return s.toString()
+    }
+
+    def methodsEqual(m1: MethodInfo, m2: MethodInfo): Boolean = {
+    if (!m1.Name.equals(m2.Name))
+        return false
+    if (m1.ReturnType != m2.ReturnType)
+        return false
+    val p1 = m1.GetParameters()
+    val p2 = m2.GetParameters()
+    if (p1.length != p2.length)
+        return false
+    for(val i <- 0 until p1.length)
+        if (p1(i).ParameterType != p2(i).ParameterType)
+        return false
+    return true
+     }
+}
diff --git a/src/msil/ch/epfl/lamp/compiler/msil/emit/Visitable.scala b/src/msil/ch/epfl/lamp/compiler/msil/emit/Visitable.scala
new file mode 100644
index 0000000..28ec801
--- /dev/null
+++ b/src/msil/ch/epfl/lamp/compiler/msil/emit/Visitable.scala
@@ -0,0 +1,24 @@
+/*
+ * System.Reflection.Emit-like API for writing .NET assemblies to MSIL
+ */
+
+
+package ch.epfl.lamp.compiler.msil.emit
+
+import java.io.IOException
+
+/**
+ * The Visitable interface
+ */
+trait Visitable {
+
+    //##########################################################################
+
+    /**
+     * the visitable method to apply a visitor
+     */
+    @throws(classOf[IOException])
+    def apply(v: Visitor): Unit
+
+    //##########################################################################
+}
diff --git a/src/msil/ch/epfl/lamp/compiler/msil/emit/Visitor.scala b/src/msil/ch/epfl/lamp/compiler/msil/emit/Visitor.scala
new file mode 100644
index 0000000..d4b84cd
--- /dev/null
+++ b/src/msil/ch/epfl/lamp/compiler/msil/emit/Visitor.scala
@@ -0,0 +1,58 @@
+/*
+ * System.Reflection.Emit-like API for writing .NET assemblies to MSIL
+ */
+
+
+package ch.epfl.lamp.compiler.msil.emit
+
+import java.io.IOException
+
+/**
+ * The Visitor interface to walk through the MSIL code Builder hierarchy.
+ */
+trait Visitor {
+
+    //##########################################################################
+
+    /** Visit an AssemblyBuilder */
+    @throws(classOf[IOException])
+    def caseAssemblyBuilder(assemblyBuilder: AssemblyBuilder): Unit
+
+    /** Visit a ModuleBuilder */
+    @throws(classOf[IOException])
+    def caseModuleBuilder(moduleBuilder: ModuleBuilder): Unit
+
+    /** Visit a TypeBuilder */
+    @throws(classOf[IOException])
+    def caseTypeBuilder(typeBuilder: TypeBuilder): Unit
+
+    /** Visit a FieldBuilder */
+    @throws(classOf[IOException])
+    def caseFieldBuilder(fieldBuilder: FieldBuilder): Unit
+
+    /** Visit a ConstructorBuilder */
+    @throws(classOf[IOException])
+    def caseConstructorBuilder(constructorBuilder: ConstructorBuilder): Unit
+
+    /** Visit a MethodBuilder */
+    @throws(classOf[IOException])
+    def caseMethodBuilder(methodBuilder: MethodBuilder): Unit
+
+    /** Visit a ParameterBuilder */
+    @throws(classOf[IOException])
+    def caseParameterBuilder(parameterBuilder: ParameterBuilder): Unit
+
+    /** Visit an ILGenerator */
+    @throws(classOf[IOException])
+    def caseILGenerator(iLGenerator: ILGenerator): Unit
+
+    /** Visit an OpCode */
+    @throws(classOf[IOException])
+    def caseOpCode(opCode: OpCode): Unit
+
+    /** Visit a LocalBuilder */
+    @throws(classOf[IOException])
+    def caseLocalBuilder(localBuilder: LocalBuilder): Unit
+
+    //##########################################################################
+}
diff --git a/src/msil/ch/epfl/lamp/compiler/msil/tests/CustomAttributesTest.java b/src/msil/ch/epfl/lamp/compiler/msil/tests/CustomAttributesTest.java
new file mode 100644
index 0000000..9a6e28a
--- /dev/null
+++ b/src/msil/ch/epfl/lamp/compiler/msil/tests/CustomAttributesTest.java
@@ -0,0 +1,31 @@
+
+package ch.epfl.lamp.compiler.msil.tests;
+
+import ch.epfl.lamp.compiler.msil.*;
+import ch.epfl.lamp.compiler.msil.util.Table;
+
+import java.io.PrintStream;
+
+public class CustomAttributesTest {
+    public static void main(String[] args) {
+	if (args.length < 1) {
+	    System.err.println("You must supply a filename!");
+	    System.exit(1);
+	}
+
+	Assembly assem = Assembly.LoadFrom(args[0]);
+	Type.initMSCORLIB(assem);
+
+	testCustomAttributes();
+    }
+
+    public static void testCustomAttributes() {
+	Object[] attrs = Type.GetType("System.ObsoleteAttribute")
+	    .GetCustomAttributes(false);
+	assert attrs != null;
+	for (int i = 0; i < attrs.length; i++) {
+	    System.out.println("\t" + attrs[i]);
+	}
+    }
+
+}
diff --git a/src/msil/ch/epfl/lamp/compiler/msil/tests/JavaTypeTest.java b/src/msil/ch/epfl/lamp/compiler/msil/tests/JavaTypeTest.java
new file mode 100644
index 0000000..96ec1bf
--- /dev/null
+++ b/src/msil/ch/epfl/lamp/compiler/msil/tests/JavaTypeTest.java
@@ -0,0 +1,18 @@
+
+package ch.epfl.lamp.compiler.msil.tests;
+
+import ch.epfl.lamp.compiler.msil.*;
+import ch.epfl.lamp.compiler.msil.util.VJSAssembly;
+
+public class JavaTypeTest {
+
+    public static void main(String[] args) {
+	if (args.length < 1) {
+	    System.err.println("usage: java test.JavaTypeTest classname");
+	    System.exit(1);
+	}
+
+	Type type = VJSAssembly.VJSLIB.GetType(args[0]);
+	MembersTest.dumpType(System.out, type);
+    }
+}
diff --git a/src/msil/ch/epfl/lamp/compiler/msil/tests/MembersTest.java b/src/msil/ch/epfl/lamp/compiler/msil/tests/MembersTest.java
new file mode 100644
index 0000000..37a5c6e
--- /dev/null
+++ b/src/msil/ch/epfl/lamp/compiler/msil/tests/MembersTest.java
@@ -0,0 +1,100 @@
+
+package ch.epfl.lamp.compiler.msil.tests;
+
+import ch.epfl.lamp.compiler.msil.*;
+import ch.epfl.lamp.compiler.msil.util.Table;
+
+import java.io.PrintStream;
+
+public class MembersTest {
+
+    public static void main(String[] args) {
+	if (args.length < 1) {
+	    System.err.println
+		("usage: java test.MembersTest assembly [classname]");
+	    System.exit(1);
+	}
+
+	Assembly mscorlib = Assembly.LoadFrom("mscorlib.dll");
+	Type.initMSCORLIB(mscorlib);
+	Assembly assem = Assembly.LoadFrom(args[0]);
+	if (args.length > 1) {
+	    Type type = assem.GetType(args[1]);
+	    if (type != null)
+		dumpMember(System.out, type);
+	    else System.err.println("Cannot find type " + args[1]
+				    + " in " + assem);
+	} else {
+	    Type[] types = assem.GetTypes();
+	    System.out.println("Number of types in assembly " + assem
+			       + " -> " + types.length);
+            dumpCustomAttributes(System.out, "assembly: ", assem);
+            Module[] modules = assem.GetModules();
+            for (int i = 0; i < modules.length; i++) {
+                dumpCustomAttributes(System.out, "module " + modules[i] + ": ",
+                                     modules[i]);
+            }
+            dumpMembers(System.out, types);
+	}
+    }
+
+    public static final void dumpMember(PrintStream out, MemberInfo member) {
+        try {
+            if (member.MemberType() == MemberTypes.TypeInfo
+                || member.MemberType() == MemberTypes.NestedType) {
+                Type type = (Type)member;
+                dumpCustomAttributes(out, "", type);
+                out.print(TypeAttributes.accessModsToString(type.Attributes));
+                out.print(type.IsInterface() ? " interface " : " class ");
+                out.print(type);
+                if (type.BaseType() != null)
+                    out.println(" extends " + type.BaseType());
+                Type[] ifaces = type.GetInterfaces();
+                if (ifaces.length > 0) {
+                    out.print("\timplements ");
+                    for (int i = 0; i < ifaces.length; i++) {
+                        out.print(ifaces[i]);
+                        if (i < (ifaces.length - 1))
+                            out.print(", ");
+                    }
+                    out.println();
+                }
+                out.println("{");
+                int all = BindingFlags.Public | BindingFlags.DeclaredOnly// | BindingFlags.NonPublic
+                    | BindingFlags.Instance | BindingFlags.Static;
+                dumpMembers(out, type.GetNestedTypes());
+                dumpMembers(out, type.GetFields(all));
+                dumpMembers(out, type.GetConstructors(all));
+                dumpMembers(out, type.GetMethods(all));
+                dumpMembers(out, type.GetProperties(all));
+                dumpMembers(out, type.GetEvents());
+                out.println("}");
+            } else {
+                dumpCustomAttributes(out, "", member);
+                out.print(MemberTypes.toString(member.MemberType()));
+                out.print(": "); out.print(member);
+                out.println();
+            }
+        } catch (Throwable e) {
+            String message = MemberTypes.toString(member.MemberType())
+                + ": " + member;
+            throw new RuntimeException(message, e);
+        }
+    }
+
+    public static void dumpCustomAttributes(PrintStream out,
+                                            String prefix,
+                                            ICustomAttributeProvider att)
+    {
+        Object[] attrs = att.GetCustomAttributes(false);
+        for (int j = 0; j < attrs.length; j++)
+            out.println(prefix + attrs[j]);
+    }
+
+    public static void dumpMembers(PrintStream out, MemberInfo[] members) {
+	for (int i = 0; i < members.length; i++) {
+            dumpMember(out, members[i]);
+	}
+    }
+
+}
diff --git a/src/msil/ch/epfl/lamp/compiler/msil/tests/TableDump.java b/src/msil/ch/epfl/lamp/compiler/msil/tests/TableDump.java
new file mode 100644
index 0000000..1df389b
--- /dev/null
+++ b/src/msil/ch/epfl/lamp/compiler/msil/tests/TableDump.java
@@ -0,0 +1,311 @@
+
+package ch.epfl.lamp.compiler.msil.tests;
+
+import ch.epfl.lamp.compiler.msil.PEFile;
+import ch.epfl.lamp.compiler.msil.util.Table;
+import ch.epfl.lamp.compiler.msil.util.Table.*;
+
+import java.io.PrintStream;
+import java.io.FileNotFoundException;
+
+public class TableDump extends PEFile {
+
+    //##########################################################################
+
+    public TableDump(String filename) throws FileNotFoundException {
+	super(filename);
+    }
+
+    /***/
+    public void dump(PrintStream out) {
+	out.println("CLI RVA: " + CLI_RVA);
+	out.println("Optional header size: " + optHeaderSize);
+	out.println("Number of sections: " + numOfSections);
+	out.println();
+
+	for (int i = 0; i < sections.length; i++) {
+	    sections[i].dump(out);
+	    out.println();
+	}
+
+	out.println("MetaData Offset:   0x" + Integer.toHexString(posMetadata));
+	out.println("Number of streams: " + numOfStreams);
+
+	out.println("#~ stream");       Meta.dump(out);    out.println();
+	out.println("#Strings stream"); Strings.dump(out); out.println();
+	if (US != null) {
+	    out.println("#US stream");      US.dump(out);      out.println();
+	}
+	out.println("#GUID stream");    GUID.dump(out);    out.println();
+	out.println("#Blob stream");    Blob.dump(out);    out.println();
+
+	out.println("Heap Sizes IndexedSeq = 0x0" + Integer.toHexString(heapSizes));
+	out.println();
+
+ 	for(int i = 0; i < Table.MAX_NUMBER; i++)
+ 	    if(getTable(i).rows > 0) {
+ 		dump(out, getTable(i));
+ 		out.println();
+ 	    }
+
+    }
+
+    /** Dumps the contents of this table. */
+    public void dump(PrintStream out, Table table) {
+	out.println("Table:" + "  ID = 0x" + byte2hex(table.id));
+	out.println("\tname = " + table.getTableName());
+	out.println("\trows =  " + table.rows);
+	//out.println("\tStart pos in file = 0x" + Long.toHexString(table.start));
+ 	for (int i = 1; i <= table.rows; i++)
+ 	    dumpRow(out, table, i);
+    }
+
+    public void dumpIndex(PrintStream out, int tableSetId, int index) {
+	int tableId = Table.getTableId(tableSetId, index);
+	int row =  Table.getTableIndex(tableSetId, index);
+	out.print(getTable(tableId).getTableName());
+        out.print('[');
+	out.print(getTable(tableId).isShort ? short2hex(row) : int2hex(row));
+        out.print(']');
+    }
+
+    public void dumpRow(PrintStream out, Table table, int row) {
+	table.readRow(row);
+	out.print(table.getTableName());
+	out.print("[" + short2hex(row) + "]: ");
+	dumpRow(out, table);
+	out.println();
+    }
+
+    /** Prints the current content of the fields of the class. */
+    public void dumpRow(PrintStream out, Table table) {
+	if (table instanceof ModuleDef) {
+	    ModuleDef t = (ModuleDef)table;
+	    out.print("Generation = 0x" + short2hex(t.Generation));
+	    out.print("; Name = " + getString(t.Name));
+	    //out.print("; Mvid = (" + bytes2hex(getGUID(Mvid)) + ")");
+	} else if (table instanceof TypeRef) {
+	    TypeRef t = (TypeRef)table;
+	    out.print("FullName = " + t.getFullName());
+	    out.print("; ResolutionScope = 0x" + int2hex(t.ResolutionScope));
+	} else if (table instanceof TypeDef) {
+	    TypeDef t = (TypeDef)table;
+	    out.print("Flags = 0x"); out.print(int2hex(t.Flags));
+	    out.print("; FullName = "); out.print(t.getFullName());
+	    out.print("; Extends = ");
+	    dumpIndex(out, Table._TypeDefOrRef, t.Extends);
+	    out.print("; FieldList = "); out.print(t.FieldList);
+	    out.print("; MethodList = "); out.print(t.MethodList);
+	} else if (table instanceof FieldTrans) {
+	    FieldTrans t = (FieldTrans)table;
+	    out.print("Field = "); out.print(t.Field);
+	} else if (table instanceof FieldDef) {
+	    FieldDef t = (FieldDef)table;
+	    out.print("Flags = 0x" + short2hex(t.Flags));
+	    out.print("; Name = " + t.getName());
+	    out.print("; Signature = (" +
+		      bytes2hex(getBlob(t.Signature)) + ")");
+	} else if (table instanceof MethodTrans) {
+	    MethodTrans t = (MethodTrans)table;
+	    out.print("Method = "); out.print(t.Method);
+	} else if (table instanceof MethodDef) {
+	    MethodDef t = (MethodDef)table;
+	    out.print("Flags = 0x" + short2hex(t.Flags));
+	    out.print("; Name = " + t.getName());
+	    out.print("; ParamList = " + t.ParamList);
+	    out.print("; Signature = (" +
+		      bytes2hex(getBlob(t.Signature)) + ")");
+	} else if (table instanceof ParamDef) {
+	    ParamDef t = (ParamDef)table;
+	    out.print("Flags = 0x" + short2hex(t.Flags));
+	    out.print("; Name = " + t.getName());
+	    out.print("; Sequence = " + t.Sequence);
+	} else if (table instanceof InterfaceImpl) {
+	    InterfaceImpl t = (InterfaceImpl)table;
+	    out.print("Class = 0x" + short2hex(t.Class));// + " (ref to: ");
+	    //TypeDef td = (TypeDef) getTable(TypeDef.ID);
+	    //td.readRow(Class);
+	    //td.dumpRow(out);
+	    out.print("; Interface = 0x" + short2hex(t.Interface));
+	} else if (table instanceof MemberRef) {
+	    MemberRef t = (MemberRef)table;
+	    out.print("Name = " + t.getName());
+	    out.print("; Signature = (" +
+		      bytes2hex(getBlob(t.Signature)) + ")");
+	    out.print("; Class = " + t.Class);
+	} else if (table instanceof Constant) {
+	    Constant t = (Constant)table;
+	    out.print("Parent = "); dumpIndex(out, Table._HasConstant, t.Parent);
+	    out.print("; Type = 0x" + byte2hex(t.Type));
+ 	    out.print("; Value = (" + bytes2hex(getBlob(t.Value)));
+	    out.print("); Value = " + t.getValue());
+	} else if (table instanceof CustomAttribute) {
+	    CustomAttribute t = (CustomAttribute)table;
+	    //out.print("Parent = 0x" + int2hex(t.Parent));
+	    out.print("Parent = ");
+            dumpIndex(out, Table._HasCustomAttribute, t.Parent);
+	    //out.print("; Type = 0x" + short2hex(t.Type));
+	    out.print("; Type = ");
+            dumpIndex(out, Table._CustomAttributeType, t.Type);
+	    out.print("; Value = (" + bytes2hex(t.getValue()) + ")");
+	} else if (table instanceof FieldMarshal) {
+	    FieldMarshal t = (FieldMarshal)table;
+	    out.print("NativeType = (");
+	    out.print(bytes2hex(getBlob(t.NativeType)) + ")");
+	} else if (table instanceof DeclSecurity) {
+	    DeclSecurity t = (DeclSecurity)table;
+	    out.print("Action = 0x" + short2hex(t.Action));
+	    out.print("; PermissionSet = (" +
+		      bytes2hex(getBlob(t.PermissionSet)) + ")");
+	} else if (table instanceof ClassLayout) {
+	    ClassLayout t = (ClassLayout)table;
+	    out.print("PackingSize = 0x" + short2hex(t.PackingSize));
+	    out.print("; ClassSize = 0x" + int2hex(t.ClassSize));
+	    out.print(": Parent = " + t.Parent + " (ref to: ");
+	    dumpRow(out, this.TypeDef(t.Parent));
+	    out.print(")");
+	} else if (table instanceof FieldLayout) {
+	    FieldLayout t = (FieldLayout)table;
+	    out.print("Offset = 0x" + int2hex(t.Offset));
+	    out.print("; Field = (ref to: ");
+	    dumpRow(out, this.FieldDef(t.Field));
+	    out.print(")");
+	} else if (table instanceof StandAloneSig) {
+	    StandAloneSig t = (StandAloneSig)table;
+	    out.print("StandAloneSig: Signature = (" +
+		      bytes2hex(getBlob(t.Signature)) + ")");
+	} else if (table instanceof EventMap) {
+	    EventMap t = (EventMap)table;
+	    out.print("Parent = 0x" + int2hex(t.Parent) + " (ref to: ");
+	    dumpRow(out, this.TypeDef(t.Parent));
+	    out.print("); EventList = 0x"); out.print(int2hex(t.EventList));
+	} else if (table instanceof EventDef) {
+	    EventDef t = (EventDef)table;
+	    out.print("EventFlags = 0x" + short2hex(t.EventFlags));
+	    out.print("; Name = " + t.getName());
+            out.print("; EventType = 0x" + int2hex(t.EventType));
+	} else if (table instanceof PropertyMap) {
+	    PropertyMap t = (PropertyMap)table;
+	    out.print("Parent = " + t.Parent + " (ref to: ");
+	    dumpRow(out, this.TypeDef(t.Parent));
+	    out.print(")");
+	} else if (table instanceof PropertyDef) {
+	    PropertyDef t = (PropertyDef)table;
+	    out.print("Flags = 0x" + short2hex(t.Flags));
+	    out.print("; Name = " + t.getName());
+	    out.print("; Type = (" + bytes2hex(getBlob(t.Type)) + ")");
+	} else if (table instanceof MethodSemantics) {
+	    MethodSemantics t = (MethodSemantics)table;
+	    out.print("Semantics = 0x" + short2hex(t.Semantics));
+	    out.print("; Method = 0x" + int2hex(t.Method) + " (ref to: ");
+	    dumpRow(out, this.MethodDef(t.Method));
+	    out.print("); Association = 0x" + int2hex(t.Association));
+	} else if (table instanceof MethodImpl) {
+	    MethodImpl t = (MethodImpl)table;
+	    out.print("Class = (ref to: ");
+	    dumpRow(out, this.TypeDef(t.Class));
+	    out.print(")");
+	} else if (table instanceof ModuleRef) {
+	    ModuleRef t = (ModuleRef)table;
+	    out.print("Name = " + t.getName());
+	} else if (table instanceof TypeSpec) {
+	    TypeSpec t = (TypeSpec)table;
+	    out.print("Signature = (" +
+		      bytes2hex(getBlob(t.Signature)) + ")");
+	} else if (table instanceof ImplMap) {
+	    ImplMap t = (ImplMap)table;
+	    out.print("ImportName = " + getString(t.ImportName));
+	} else if (table instanceof FieldRVA) {
+	    FieldRVA t = (FieldRVA)table;
+	    out.print("RVA = 0x" + int2hex(t.RVA));
+	    out.print("; Field = (ref to: ");
+	    dumpRow(out, this.FieldDef(t.Field));
+	    out.print(")");
+	} else if (table instanceof AssemblyDef) {
+	    AssemblyDef t = (AssemblyDef)table;
+	    out.print("Flags = 0x" + int2hex(t.Flags));
+	    out.print(" ; Name = " + getString(t.Name));
+	    out.print("; Culture = " + getString(t.Culture));
+	    out.print(" ; Version = " + t.MajorVersion + ".");
+	    out.print(t.MinorVersion + "." + t.BuildNumber);
+	    out.print("." + t.RevisionNumber);
+	    out.print("; HashAlgId = 0x" + int2hex(t.HashAlgId));
+	    out.print("; PublicKey = (");
+	    out.print(bytes2hex(getBlob(t.PublicKey)) + ")");
+	} else if (table instanceof AssemblyProcessor) {
+	    AssemblyProcessor t = (AssemblyProcessor)table;
+	    out.print("Processor = 0x" + int2hex(t.Processor));
+	} else if (table instanceof AssemblyOS) {
+	    AssemblyOS t = (AssemblyOS)table;
+	    out.print("!?!");
+	} else if (table instanceof AssemblyRef) {
+	    AssemblyRef t = (AssemblyRef)table;
+	    out.print("Flags = 0x" + int2hex(t.Flags));
+	    out.print("; Name = " + getString(t.Name));
+	    out.print("; Culture = " + getString(t.Culture));
+	    out.print("; Version = " + t.MajorVersion + "." + t.MinorVersion);
+	    out.print("." + t.BuildNumber + "." + t.RevisionNumber);
+	    out.print("; PublicKeyOrToken = (" +
+		      bytes2hex(getBlob(t.PublicKeyOrToken)) + ")");
+	    out.print("; HashValue = (" +
+		      bytes2hex(getBlob(t.HashValue)) + ")");
+	} else if (table instanceof AssemblyRefProcessor) {
+	    AssemblyRefProcessor t = (AssemblyRefProcessor)table;
+	    out.print("!?!");
+	} else if (table instanceof AssemblyRefOS) {
+	    AssemblyRefOS t = (AssemblyRefOS)table;
+	    out.print("!?!");
+	} else if (table instanceof FileDef) {
+	    FileDef t = (FileDef)table;
+	    out.print("Flags = 0x" + int2hex(t.Flags));
+	    out.print("; Name = " + t.getName());
+	    out.print("; HashValue = (" + bytes2hex(getBlob(t.HashValue)) +")");
+	} else if (table instanceof ExportedType) {
+	    ExportedType t = (ExportedType)table;
+	    out.print("FullName = " + t.getFullName());
+	} else if (table instanceof ManifestResource) {
+	    ManifestResource t = (ManifestResource)table;
+	    out.print("Name = " + getString(t.Name));
+	    out.print("; Flags = 0x" + int2hex(t.Flags));
+	} else if (table instanceof NestedClass) {
+	    NestedClass t = (NestedClass)table;
+	    out.print(this.TypeDef(t.EnclosingClass).getFullName());
+	    out.print("/");
+	    out.print(this.TypeDef(t.NestedClass).getFullName());
+	} else
+	    throw new RuntimeException("Unknown table " + table.getClass());
+    }
+
+    //##########################################################################
+
+    public static void main(String[] args) {
+	if (args.length < 1) {
+	    System.err.println("You must supply a filename!");
+	    System.exit(1);
+	}
+
+	TableDump file = null;
+	try {
+	    file = new TableDump(args[0]);
+	} catch (FileNotFoundException e) { e.printStackTrace(); }
+
+	if (args.length > 1) {
+            nextarg:
+	    for (int i = 1; i < args.length; i++) {
+		String name = args[i];
+		for (int tableId = 0; tableId < Table.MAX_NUMBER; tableId++) {
+		    Table table = file.getTable(tableId);
+		    if ((table.rows > 0) && name.equals(table.getTableName())) {
+			file.dump(System.out, table);
+			System.out.println();
+			continue nextarg;
+		    }
+		}
+                System.err.println("No such table: " + name);
+	    }
+	} else
+	    file.dump(System.out);
+    }
+
+    //##########################################################################
+}
diff --git a/src/msil/ch/epfl/lamp/compiler/msil/tests/Test.java b/src/msil/ch/epfl/lamp/compiler/msil/tests/Test.java
new file mode 100644
index 0000000..2c5946a
--- /dev/null
+++ b/src/msil/ch/epfl/lamp/compiler/msil/tests/Test.java
@@ -0,0 +1,92 @@
+
+package test;
+
+import ch.epfl.lamp.compiler.msil.*;
+import ch.epfl.lamp.compiler.msil.util.Table;
+
+import java.io.PrintStream;
+
+public class Test {
+    public static void main(String[] args) {
+	if (args.length < 1) {
+	    System.err.println("You must supply a filename!");
+	    System.exit(1);
+	}
+
+	Assembly assem = Assembly.LoadFrom(args[0]);
+	Type.initMSCORLIB(assem);
+
+	//"System.Collections.ArrayList"
+	if (args.length >= 2) {
+	    Type t = Type.GetType(args[1]);
+	    dumpType(System.out, t);
+	} else {
+	    dumpAssembly(assem);
+	}
+    }
+
+
+    public static void dumpAssembly(Assembly assem) {
+	Module[] modules = assem.GetModules();
+// 	System.out.println("Modules in assembly " + assem +
+// 			   " (" + modules.length + ")");
+// 	for (int i = 0; i < modules.length; i++) {
+// 	    System.out.println("\t" + modules[i]);
+// 	}
+
+ 	Type[] types = modules[0].GetTypes();
+// 	System.out.println("Types in assembly " + assem +
+// 			   " (" + types.length + ")");
+	for (int i = 0; i < types.length; i++) {
+	    System.out.println("#" + i + " -> " + types[i]);
+	    types[i].completeType();
+	}
+    }
+
+    public static final void dumpType(PrintStream out, Type type) {
+	out.println("Type = " + type);
+	out.println("Name = " + type.Name);
+	out.println("Namespace = " + type.Namespace);
+	out.println("FullName = " + type.FullName);
+	out.println("Attributes = " + TypeAttributes.toString(type.Attributes));
+	out.println("BaseType = " + type.BaseType);
+	Type[] ifaces = type.GetInterfaces();
+	if (ifaces != null) {
+	    for (int i = 0; i < ifaces.length; i++)
+		out.println("\timplements " + ifaces[i]);
+	}
+	out.println("Assembly = " + type.Assembly);
+	out.println("Module = " + type.Module);
+	out.println("DeclaringType = " + type.DeclaringType);
+	out.println("IsInterface = " + type.IsInterface);
+	out.println("IsAbstract = " + type.IsAbstract);
+
+	FieldInfo[] fields = type.GetFields(BindingFlags.Instance
+					    | BindingFlags.Static
+					    | BindingFlags.NonPublic);
+	out.println("\nFields (" + fields.length + "):");
+	for (int i = 0; i < fields.length; i++) {
+	    out.println("\t" + fields[i]);
+	    out.println("\t\tDeclaringType = " + fields[i].DeclaringType);
+	    out.println("\t\tReflectedType = " + fields[i].ReflectedType);
+	}
+
+	ConstructorInfo[] constrs = type.GetConstructors();
+	out.println("\nConstructors (" + constrs.length + "):");
+	for (int i = 0; i < constrs.length; i++) {
+	    out.println("\t" + constrs[i]);
+	}
+
+// 	MethodInfo[] methods = type.GetMethods(BindingFlags.Instance
+// 					       | BindingFlags.Static
+// 					       | BindingFlags.Public
+// 					       | BindingFlags.NonPublic);
+	MethodInfo[] methods = type.GetMethods();
+	out.println("\nMethods (" + methods.length + "):");
+	for (int i = 0; i < methods.length; i++) {
+	    out.println("\t" + methods[i]);
+	    out.println("\t\tDeclaringType = " + methods[i].DeclaringType);
+	    out.println("\t\tReflectedType = " + methods[i].ReflectedType);
+	}
+    }
+}
diff --git a/src/msil/ch/epfl/lamp/compiler/msil/util/PESection.java b/src/msil/ch/epfl/lamp/compiler/msil/util/PESection.java
new file mode 100644
index 0000000..454a94e
--- /dev/null
+++ b/src/msil/ch/epfl/lamp/compiler/msil/util/PESection.java
@@ -0,0 +1,57 @@
+/*
+ * System.Reflection-like API for acces to .NET assemblies (DLL & EXE)
+ */
+
+
+package ch.epfl.lamp.compiler.msil.util;
+
+import ch.epfl.lamp.compiler.msil.PEFile;
+
+import java.io.PrintStream;
+
+/** Describes a section from a PE/COFF file
+ *
+ * @author Nikolay Mihaylov
+ * @version 1.0
+ */
+public final class PESection {
+
+    private final PEFile file;
+    private final long sectionStart;
+
+    public final String name;
+    public final int virtAddr;
+    public final int virtSize;
+    public final int realAddr;
+    public final int realSize;
+    public final int flags;
+
+    private static final byte[] buf = new byte[8];
+
+    public PESection(PEFile file) {
+	this.file = file;
+	sectionStart = file.pos();
+	file.read(buf);
+ 	int i;
+ 	for(i = 7; (i >= 0) && (0 == buf[i]); i--);
+ 	name = new String(buf, 0, i + 1);
+	virtSize = file.readInt();
+	virtAddr = file.readInt();
+	realSize = file.readInt();
+	realAddr = file.readInt();
+	file.skip(3 * PEFile.INT_SIZE);
+	flags = file.readInt();
+    }
+
+
+    public void dump(PrintStream out) {
+	out.println("Section name:    " + name +
+		   " (name.length=" + name.length() + ")");
+	out.println("Virtual Address: 0x" + PEFile.int2hex(virtAddr));
+	out.println("Virtual Size:    0x" + PEFile.int2hex(virtSize));
+	out.println("Real Address:    0x" + PEFile.int2hex(realAddr));
+	out.println("Real Size:       0x" + PEFile.int2hex(realSize));
+	out.println("Flags:           0x" + PEFile.int2hex(flags));
+    }
+
+} // class PESection
diff --git a/src/msil/ch/epfl/lamp/compiler/msil/util/PEStream.java b/src/msil/ch/epfl/lamp/compiler/msil/util/PEStream.java
new file mode 100644
index 0000000..ef04387
--- /dev/null
+++ b/src/msil/ch/epfl/lamp/compiler/msil/util/PEStream.java
@@ -0,0 +1,199 @@
+/*
+ * System.Reflection-like API for acces to .NET assemblies (DLL & EXE)
+ */
+
+
+package ch.epfl.lamp.compiler.msil.util;
+
+import ch.epfl.lamp.compiler.msil.PEFile;
+import ch.epfl.lamp.compiler.msil.PEFile.Sig;
+
+import java.io.PrintStream;
+import java.io.IOException;
+
+import java.nio.ByteBuffer;
+import java.nio.channels.FileChannel;
+
+/**
+ * Implements support for CLI streams within a PE file.
+ *
+ * @author Nikolay Mihaylov
+ * @version 1.0
+ */
+public final class PEStream implements Signature {
+
+    //##########################################################################
+    // Members
+
+    /** The name of the stream. */
+    public final String name;
+
+    /** The offset of the stream from the beginning of the file. */
+    public final int offset;
+
+    /** The size of the stream in bytes; shall be multiple of 4. */
+    public final int size;
+
+    private final PEFile file;
+
+    private final ByteBuffer buffer;
+
+    //##########################################################################
+
+    /** The PEStream class constructor.
+     *  @param file - the PEFile to which this stream belongs
+     */
+    public PEStream(PEFile file) {
+	this.file = file;
+	offset = file.fromRVA(file.rvaMetadata + file.readInt());
+	size = file.readInt();
+	buffer = file.getBuffer(offset, size);
+
+	int i = 0;
+	byte [] _buf = new byte [16];
+	do {
+	    _buf[i] = (byte) file.readByte();
+	    i++;
+	} while(0 != _buf[i-1]);
+	name = new String(_buf, 0, i - 1);
+
+	file.align(PEFile.INT_SIZE, file.posMetadata);
+	//assert size % 4 == 0;
+    }
+
+    /** Move to the specified position in the stream. */
+    private  void seek(int pos) {
+	try {
+	    buffer.position(pos);
+	} catch (IllegalArgumentException e) {
+	    System.err.println("\nSeek failed in file " + file
+			       + " for position " + pos
+			       + " of stream " + name + " (" + buffer + ")");
+	    throw e;
+	}
+    }
+
+    /** Return a string from the specified position in the stream. */
+    public String getString(int pos) {
+	seek(pos);
+	buffer.mark();
+	int i;
+	for (i = 0; getByte() != 0; i++);
+	byte[] buf = new byte[i];
+	buffer.reset(); // go back to the marked position
+	buffer.get(buf);
+	try {
+	    return new String(buf, "UTF-8");
+	} catch (java.io.UnsupportedEncodingException e) {
+	    throw new RuntimeException(e);
+	}
+    }
+
+    /** Read a byte from the stream. */
+    public int getByte() {
+	return (buffer.get() + 0x0100) & 0xff;
+    }
+
+    /** Return the GUID at the given position in the stream. */
+    public byte[] getGUID(int pos) {
+	seek(pos);
+	byte[] buf = new byte[32]; // 128-bit GUID
+	try {
+	    buffer.get(buf);
+	} catch (Exception e) {
+	    System.err.println();
+	    System.err.println("PEStream.getBlob(): Exception for pos = " +
+			       pos + " and buf.length = " + buf.length);
+	    System.err.println("\tbuffer = " + buffer);
+	    e.printStackTrace();
+	    throw new RuntimeException();
+	}
+	return buf;
+    }
+
+    public int readLength() {
+	int length = getByte();
+	if ((length & 0x80) != 0) {
+	    length = ((length & 0x7f) << 8) | getByte();
+	    if ((length & 0x4000) != 0)
+		length = ((length & 0x3fff) << 16) | (getByte()<<8) | getByte();
+	}
+	return length;
+    }
+
+    /** Return a blob from the specified position in the stream. */
+    public byte[] getBlob(int pos) {
+	seek(pos);
+	// the length indicates the number of bytes
+	// AFTER the encoded size of the blob
+	int length = readLength();
+	byte[] buf = new byte[length];
+	buffer.get(buf);
+	return buf;
+    }
+
+    /***/
+    public Sig getSignature(int pos) {
+	seek(pos);
+	return file.newSignature(buffer);
+    }
+
+    /**
+     */
+    public Object getConstant(int type, int pos) {
+	Object val = null;
+	seek(pos);
+	int length = readLength(); // skip over the blob length field
+	switch (type) {
+	case ELEMENT_TYPE_BOOLEAN:
+	    assert length == 1;
+	    return buffer.get() == 0 ? Boolean.FALSE : Boolean.TRUE;
+	case ELEMENT_TYPE_CHAR:
+	    assert length == 2 : "length == " + length;
+	    return new Character(buffer.getChar());
+	case ELEMENT_TYPE_I1:
+	case ELEMENT_TYPE_U1:
+	    assert length == 1;
+	    return new Byte(buffer.get());
+	case ELEMENT_TYPE_I2:
+	case ELEMENT_TYPE_U2:
+	    assert length == 2;
+	    return new Short(buffer.getShort());
+	case ELEMENT_TYPE_I4:
+	case ELEMENT_TYPE_U4:
+	    assert length == 4;
+	    return new Integer(buffer.getInt());
+	case ELEMENT_TYPE_I8:
+	case ELEMENT_TYPE_U8:
+	    assert length == 8;
+	    return new Long(buffer.getLong());
+	case ELEMENT_TYPE_R4:
+	    assert length == 4;
+	    return new Float(buffer.getFloat());
+	case ELEMENT_TYPE_R8:
+	    assert length == 8;
+	    return new Double(buffer.getDouble());
+	case ELEMENT_TYPE_STRING:
+// 	    length /= 2;
+// 	    char[] chars = new char[length];
+// 	    for (int i = 0; i < length; i++)
+// 		chars[i] = buffer.getChar();
+// 	    val = new String(chars);
+	    try {
+		return new String(getBlob(pos), "UTF-16LE");
+	    } catch(java.io.UnsupportedEncodingException e) {
+		throw new RuntimeException(e);
+	    }
+	default: throw new RuntimeException("Illegal constant type: " + type);
+	}
+    }
+
+    public void dump(PrintStream out) {
+	out.println("Stream name:   " + name + " (length " +
+		   name.length() + " characters)");
+	out.println("Stream offset: 0x" + PEFile.int2hex(offset));
+	out.println("Stream size:   0x" + PEFile.int2hex(size));
+    }
+
+    //##########################################################################
+}  // class PEStream
diff --git a/src/msil/ch/epfl/lamp/compiler/msil/util/Signature.java b/src/msil/ch/epfl/lamp/compiler/msil/util/Signature.java
new file mode 100644
index 0000000..b70f9ab
--- /dev/null
+++ b/src/msil/ch/epfl/lamp/compiler/msil/util/Signature.java
@@ -0,0 +1,118 @@
+/*
+ * System.Reflection-like API for acces to .NET assemblies (DLL & EXE)
+ */
+
+
+package ch.epfl.lamp.compiler.msil.util;
+
+import ch.epfl.lamp.compiler.msil.Type;
+
+/**
+ * Signatures
+ *
+ * @author Nikolay Mihaylov
+ * @version 1.0
+ */
+public interface Signature {
+
+    //##########################################################################
+
+    /** Marks end of a list. */
+    public static final int  ELEMENT_TYPE_END = 0x00;
+    /** void */
+    public static final int  ELEMENT_TYPE_VOID = 0x01;
+    /** boolean */
+    public static final int  ELEMENT_TYPE_BOOLEAN = 0x02;
+    /** char */
+    public static final int  ELEMENT_TYPE_CHAR = 0x03;
+    /** signed byte */
+    public static final int  ELEMENT_TYPE_I1 = 0x04;
+    /** byte */
+    public static final int  ELEMENT_TYPE_U1 = 0x05;
+    /** short */
+    public static final int  ELEMENT_TYPE_I2 = 0x06;
+    /** unsigned short */
+    public static final int  ELEMENT_TYPE_U2 = 0x07;
+    /** int */
+    public static final int  ELEMENT_TYPE_I4 = 0x08;
+    /** unsigned int */
+    public static final int  ELEMENT_TYPE_U4 = 0x09;
+    /** long */
+    public static final int  ELEMENT_TYPE_I8 = 0x0a;
+    /** unsigned long */
+    public static final int  ELEMENT_TYPE_U8 = 0x0b;
+    /** float */
+    public static final int  ELEMENT_TYPE_R4 = 0x0c;
+    /** double */
+    public static final int  ELEMENT_TYPE_R8 = 0x0d;
+    /** string */
+    public static final int  ELEMENT_TYPE_STRING = 0x0e;
+    /** Followed by <type> token. */
+    public static final int  ELEMENT_TYPE_PTR = 0x0f;
+    /** Followed by <type> token. */
+    public static final int  ELEMENT_TYPE_BYREF = 0x10;
+    /** Followed by <type> token */
+    public static final int  ELEMENT_TYPE_VALUETYPE = 0x11;
+    /** Followed by <type> token */
+    public static final int  ELEMENT_TYPE_CLASS = 0x12;
+    /** <type> <rank> <boundsCount> <bound1> ... <loCount> <lo1> ... */
+    public static final int  ELEMENT_TYPE_ARRAY = 0x14;
+    /***/
+    public static final int  ELEMENT_TYPE_TYPEDBYREF = 0x16;
+    /** System.IntPtr */
+    public static final int  ELEMENT_TYPE_I = 0x18;
+    /** System.UIntPtr */
+    public static final int  ELEMENT_TYPE_U = 0x19;
+    /** Followed by full method signature. */
+    public static final int  ELEMENT_TYPE_FNPTR = 0x1b;
+    /** System.Object. */
+    public static final int  ELEMENT_TYPE_OBJECT = 0x1c;
+    /** Single-dim array with 0 lower bound. */
+    public static final int  ELEMENT_TYPE_SZARRAY = 0x1d;
+    /** Required modifier : followed by a TypeDef or TypeRef token. */
+    public static final int  ELEMENT_TYPE_CMOD_REQD = 0x1f;
+    /** Optional modifier : followed by a TypeDef or TypeRef token. */
+    public static final int  ELEMENT_TYPE_CMOD_OPT = 0x20;
+    /** Implemented within the CLI. */
+    public static final int  ELEMENT_TYPE_INTERNAL = 0x21;
+    /** Or'd with following element types. */
+    public static final int  ELEMENT_TYPE_MODIFIER = 0x40;
+    /** Sentinel for varargs method signature. */
+    public static final int  ELEMENT_TYPE_SENTINEL = 0x41;
+    /**Denotes a local variable that points at a pinned object. */
+    public static final int  ELEMENT_TYPE_PINNED = 0x45;
+
+    //##########################################################################
+    // signature designators
+
+    public static final int HASTHIS = 0x20;
+    public static final int EXPLICITTHIS = 0x40;
+    public static final int DEFAULT = 0x00;
+    public static final int VARARG = 0x05;
+    public static final int SENTINEL = 0x41;
+    public static final int C = 0x01;
+    public static final int STDCALL = 0x02;
+    public static final int THISCALL = 0x03;
+    public static final int FASTCALL = 0x04;
+    public static final int FIELD = 0x06;
+    public static final int PROPERTY = 0x08;
+    public static final int LOCAL_SIG = 0x07;
+
+    //##########################################################################
+    // extra IDs used in the serialization format of named arguments 
+    // to custom attributes. Reverse-engineered from compiled C# example
+
+    /** What follows is a string with the full name of the type. */
+    public static final int X_ELEMENT_TYPE_TYPE = 0x50;
+
+    /** What follows is a string with the full name of the enumeration type*/
+    public static final int X_ELEMENT_TYPE_ENUM = 0x55;
+
+    /** The named argument specifies a field. */
+    public static final int X_ELEMENT_KIND_FIELD = 0x53;
+
+    /** The named argument specifies a property. */
+    public static final int X_ELEMENT_KIND_PROPERTY = 0x54;
+
+    //##########################################################################
+}  // interface Signature
diff --git a/src/msil/ch/epfl/lamp/compiler/msil/util/Table.java b/src/msil/ch/epfl/lamp/compiler/msil/util/Table.java
new file mode 100644
index 0000000..ba9d317
--- /dev/null
+++ b/src/msil/ch/epfl/lamp/compiler/msil/util/Table.java
@@ -0,0 +1,1599 @@
+/*
+ * System.Reflection-like API for acces to .NET Assemblies
+ */
+
+
+package ch.epfl.lamp.compiler.msil.util;
+
+import ch.epfl.lamp.compiler.msil.PEFile;
+import ch.epfl.lamp.compiler.msil.PEFile.Sig;
+
+import java.io.PrintStream;
+import java.nio.ByteBuffer;
+import java.nio.MappedByteBuffer;
+
+/**
+ * Represents a table in a .NET assembly
+ *
+ * @author Nikolay Mihaylov
+ * @version 1.0
+ */
+public abstract class Table {
+
+    //##########################################################################
+
+    public static final int MAX_NUMBER = 64;
+
+    public static final long VALID_TABLES_MASK = 0x03ff3fb7ff57L;
+
+    //##########################################################################
+    // fields and methods for handling predefined sets of tables
+
+    public static final int TABLE_SET_LENGTH = 12;
+
+    public static final int _TypeDefOrRef = 0;
+    public static final int _HasConstant = 1;
+    public static final int _HasCustomAttribute = 2;
+    public static final int _HasFieldMarshal = 3;
+    public static final int _HasDeclSecurity = 4;
+    public static final int _MemberRefParent = 5;
+    public static final int _HasSemantics = 6;
+    public static final int _MethodDefOrRef = 7;
+    public static final int _MemberForwarded = 8;
+    public static final int _Implementation = 9;
+    public static final int _CustomAttributeType = 10;
+    public static final int _ResolutionScope = 11;
+
+
+    public static final int[][] TableSet = new int[TABLE_SET_LENGTH][];
+    static {
+	TableSet[_TypeDefOrRef] =
+	    new int[] {TypeDef.ID, TypeRef.ID, TypeSpec.ID};
+	TableSet[_HasConstant] =
+	    new int[] {FieldDef.ID, ParamDef.ID, PropertyDef.ID};
+	TableSet[_HasCustomAttribute] =
+	    new int[] {MethodDef.ID, FieldDef.ID, TypeRef.ID, TypeDef.ID,
+		       ParamDef.ID, InterfaceImpl.ID, MemberRef.ID, ModuleDef.ID,
+		       -1, PropertyDef.ID, EventDef.ID, -1, ModuleRef.ID,
+		       TypeSpec.ID, AssemblyDef.ID, AssemblyRef.ID,
+		       FileDef.ID, ExportedType.ID, ManifestResource.ID};
+	TableSet[_HasFieldMarshal] =
+	    new int[] {FieldDef.ID, ParamDef.ID};
+	TableSet[_HasDeclSecurity] =
+	    new int[] {TypeDef.ID, MethodDef.ID, AssemblyDef.ID};
+	TableSet[_MemberRefParent] =
+	    new int[] {-1, TypeRef.ID, ModuleRef.ID, MethodDef.ID, TypeSpec.ID};
+	TableSet[_HasSemantics] =
+	    new int[] {EventDef.ID, PropertyDef.ID};
+	TableSet[_MethodDefOrRef] =
+	    new int[] {MethodDef.ID, MemberRef.ID};
+	TableSet[_MemberForwarded] =
+	    new int[] {FieldDef.ID, MethodDef.ID};
+	TableSet[_Implementation] =
+	    new int[] {FileDef.ID, AssemblyRef.ID, ExportedType.ID};
+	TableSet[_CustomAttributeType] =
+	    new int[] {-1, -1, MethodDef.ID, MemberRef.ID, -1};
+	TableSet[_ResolutionScope] =
+	    new int[] {ModuleDef.ID, ModuleRef.ID, AssemblyRef.ID, TypeRef.ID};
+    }
+
+    public static final int[] NoBits =
+	new int[] {2, 2, 5, 1, 2, 3, 1, 1, 1, 2, 3, 2};
+
+    public static int getMask(int tableSetId) {
+	return (1 << NoBits[tableSetId]) - 1;
+    }
+
+    public static int getTableId(int tableSet, int index) {
+	return TableSet[tableSet][index & getMask(tableSet)];
+    }
+
+    public static int getTableIndex(int tableSet, int index) {
+	return index >> NoBits[tableSet];
+    }
+
+    public static int encodeIndex(int index, int tableSetId, int tableId) {
+	int[] tableSet = TableSet[tableSetId];
+	for (int i = 0; i < tableSet.length; i++) {
+	    if (tableSet[i] == tableId)
+		return (index << NoBits[tableSetId]) | i;
+	}
+	throw new RuntimeException("Cannot find table #" + tableId +
+				   " in table set #" + tableSetId);
+    }
+
+    //##########################################################################
+
+    private static final String [] tableName = {
+	"Module",              "TypeRef",          "TypeDef", "   FieldTrans",
+	"Field",               "MethodTrans",      "Method",      "",
+	"Param",               "InterfaceImpl",    "MemberRef",   "Constant",
+	"CustomAttribute",     "FieldMarshal",     "DeclSecurity","ClassLayout",
+	"FieldLayout",         "StandAloneSig",    "EventMap",    "",
+	"Event",               "PropertyMap",      "",            "Property",
+	"MethodSemantics",     "MethodImpl",       "ModuleRef",   "TypeSpec",
+	"ImplMap",             "FieldRVA",         "",            "",
+	"Assembly",            "AssemblyProcessor","AssemblyOS",  "AssemblyRef",
+	"AssemblyRefProcessor","AssemblyRefOS",    "File",        "ExportedType",
+	"ManifestResource",    "NestedClass",      "",            "",
+	"",                    "",                 "",            "",//0x28-0x2f
+	"",                    "",                 "",            "",
+	"",                    "",                 "",            "",//0x30-0x37
+	"",                    "",                 "",            "",
+	"",                    "",                 "",            "" //0x37-0x3f
+    };
+
+    /** Creates a table with the given id and number of rows.
+     */
+    public static Table newTable(PEFile file, int id, int rows) {
+	Table table = null;
+	switch(id) {
+	case ModuleDef.ID:         table = new ModuleDef(file, rows); break;
+ 	case TypeRef.ID:           table = new TypeRef(file, rows); break;
+ 	case TypeDef.ID:           table = new TypeDef(file, rows); break;
+	case FieldTrans.ID:        table = new FieldTrans(file, rows); break;
+	case FieldDef.ID:          table = new FieldDef(file, rows); break;
+	case MethodTrans.ID:       table = new MethodTrans(file, rows); break;
+	case MethodDef.ID:         table = new MethodDef(file, rows); break;
+	case ParamDef.ID:          table = new ParamDef(file, rows); break;
+	case InterfaceImpl.ID:     table = new InterfaceImpl(file, rows); break;
+	case MemberRef.ID:         table = new MemberRef(file, rows); break;
+	case Constant.ID:          table = new Constant(file, rows); break;
+	case CustomAttribute.ID:   table = new CustomAttribute(file, rows); break;
+	case FieldMarshal.ID:      table = new FieldMarshal(file, rows); break;
+	case DeclSecurity.ID:      table = new DeclSecurity(file, rows); break;
+	case ClassLayout.ID:       table = new ClassLayout(file, rows); break;
+	case FieldLayout.ID:       table = new FieldLayout(file, rows); break;
+	case StandAloneSig.ID:     table = new StandAloneSig(file, rows); break;
+	case EventMap.ID:          table = new EventMap(file, rows); break;
+	case EventDef.ID:          table = new EventDef(file, rows); break;
+	case PropertyMap.ID:       table = new PropertyMap(file, rows); break;
+	case PropertyDef.ID:       table = new PropertyDef(file, rows); break;
+	case MethodSemantics.ID:   table = new MethodSemantics(file, rows); break;
+	case MethodImpl.ID:        table = new MethodImpl(file, rows); break;
+	case ModuleRef.ID:         table = new ModuleRef(file, rows); break;
+	case TypeSpec.ID:          table = new TypeSpec(file, rows); break;
+	case ImplMap.ID:           table = new ImplMap(file, rows); break;
+	case FieldRVA.ID:          table = new FieldRVA(file, rows); break;
+	case AssemblyDef.ID:       table = new AssemblyDef(file, rows); break;
+	case AssemblyProcessor.ID: table = new AssemblyProcessor(file, rows); break;
+	case AssemblyOS.ID:        table = new AssemblyOS(file, rows); break;
+	case AssemblyRef.ID:       table = new AssemblyRef(file, rows); break;
+	case AssemblyRefProcessor.ID:
+	    table = new AssemblyRefProcessor(file, rows); break;
+	case AssemblyRefOS.ID:     table = new AssemblyRefOS(file, rows); break;
+	case FileDef.ID:           table = new FileDef(file, rows); break;
+	case ExportedType.ID:      table = new ExportedType(file, rows); break;
+	case ManifestResource.ID:  table = new ManifestResource(file, rows); break;
+	case NestedClass.ID:       table = new NestedClass(file, rows); break;
+	default:
+	    table = new Empty(id);
+	}
+// 	System.out.println("created table " + table.getName() + " with "
+// 			   + table.rows + " rows");
+	return table;
+    }
+
+
+    //##########################################################################
+    // public fields
+
+    /** Number of rows in the table. */
+    public final int rows;
+
+    /** Table ID as specified in Partition II. */
+    public final int id;
+
+    /** The file to which the table belongs. */
+    protected final PEFile file;
+
+    /** Memory mapped buffer wrapping the table. */
+    protected ByteBuffer buffer;
+
+    /**
+     * specified wheter a new memory-mapped byte buffer should be created
+     * for this table.
+     */
+    protected boolean newMapping = false;
+
+    /** Tells wheter the table is indexed by 2-byte (short) integer
+     *  or by 4-byte integer. */
+    public final boolean isShort;
+
+    private int rowSize = -1;
+
+    // the starting position of the table relative to the beginning of the file
+    private long start = -1;
+
+    // the number of the row who can be accessed via the fields of the table
+    private int currentRow = 0;
+
+    //##########################################################################
+
+    protected Table(PEFile file, int id, int rows) {
+	this.file = file;
+	this.id = id;
+	this.rows = rows;//file.readInt();
+	this.isShort = rows < (1 << 16);
+// 	assert ((1L << id) & VALID_TABLES_MASK) != 0
+// 	    : "Table does not have a vaid ID: " + byte2hex(id);
+    }
+
+    /**
+     * Additional table initialization.
+     * @return the starting position of the next table in the stream.
+     */
+    public final long init(long start) {
+	if (rows < 1)
+	    return start;
+	if (this.start == -1)
+	    this.start = start;
+	else throw new RuntimeException
+		 ("Cannot re-initialize table \'" + getTableName() + "\'");
+	rowSize = getRowSize();
+	int size = rows * rowSize();
+	buffer = this.newMapping ? file.mapBuffer(start, size)
+	    : file.getBuffer(start, size);
+	return start + size;
+    }
+
+
+    public final String getTableName() {
+	return 0 <= id && id < MAX_NUMBER ? tableName[id] : "<NoTable>";
+    }
+
+    /**
+     * @return the size of the row in bytes
+     */
+    public final int rowSize() {
+	return rowSize;
+    }
+
+    /**
+     * if the underlying buffer is memory-mapped, load its contents into memory
+     */
+    public void load() {
+	if (buffer instanceof MappedByteBuffer)
+	    ((MappedByteBuffer)buffer).load();
+    }
+
+    /***/
+    public final int readByte() {
+	return (buffer.get() + 0x100) & 0xff;
+    }
+
+    /***/
+    public final int readShort() {
+	return (buffer.getShort() + 0x10000) & 0xffff;
+    }
+
+    /***/
+    public final int readInt() {
+	return buffer.getInt();
+    }
+
+    /***/
+    public final int readStringIndex() {
+	return file.StringIsShort ? readShort() : readInt();
+    }
+
+    /***/
+    public final int readBlobIndex() {
+	return file.BlobIsShort ? readShort() : readInt();
+    }
+
+    /***/
+    public final int readGUIDIndex() {
+	return file.GUIDIsShort ? readShort() : readInt();
+    }
+
+    /***/
+    public final int readTableIndex(int tableId) {
+	return file.getTable(tableId).isShort ? readShort() : readInt();
+    }
+
+    /***/
+    public final int readTableSetIndex(int tableSetId) {
+	return file.indexSize[tableSetId] == 2 ? readShort() : readInt();
+    }
+
+    /** Read the specified row and populate the fields of the instance. */
+    public final void readRow(int row) {
+	seekRow(row);
+	int lastSeek = buffer.position();
+	populateFields();
+	int rowSizeRead = (int) (buffer.position() - lastSeek);
+	if (rowSizeRead != rowSize())
+	    throw new RuntimeException("Table ID=0x" + PEFile.byte2hex(id) +
+				       ": read row size = " + rowSizeRead +
+				       "; expected row size = " + rowSize());
+	currentRow = row;
+    }
+
+    /** Seeks in the file the position of the specified row. */
+    protected final void seekRow(int row) {
+	assert row > 0 && row <= rows
+	    : "Index " + row + " is not within the table with #rows = " + rows;
+	buffer.position((row - 1)* rowSize());
+    }
+
+    public final int currentRow() { return currentRow; }
+
+    public final void nextRow() { readRow(currentRow() + 1); }
+
+    //##########################################################################
+    // abstract members
+
+    /** Assigns values to the fields of the class. */
+    protected abstract void populateFields();
+
+    /** Returns the size of a row in bytes. */
+    protected abstract int getRowSize();
+
+    //##########################################################################
+    // a table with 0 rows
+
+    private static final class Empty extends Table {
+	public Empty(int id) {
+	    super(null, id, 0);
+	}
+	protected int getRowSize() { return 0; }
+	protected void populateFields() {
+	    throw new RuntimeException("Table 0x" + PEFile.byte2hex(id));
+	}
+    }
+
+    //##########################################################################
+    // table Module; ID=0x00; p115, 21.27
+
+    public static final class ModuleDef extends Table {
+	public static final int ID = 0x00;
+
+	/** 2-byte value; reserved - shall be 0. */
+	public int Generation;
+
+	/** Index into #String. */
+	public int Name;
+
+	/** Index into #GUID; used to distinguish between
+	 *  two version of the same module. */
+	public int Mvid;
+
+	/** Index into #GUID; reserved - shall be 0. */
+	public int EncId;
+
+	/** Index into #GUID; reseved - shall be 0. */
+	public int EncBaseId;
+
+	public ModuleDef(PEFile file, int rows) { super(file, ID, rows); }
+
+	protected void populateFields() {
+	    Generation = readShort();
+	    Name = readStringIndex();
+	    Mvid = readGUIDIndex();
+	    EncId = readGUIDIndex();
+	    EncBaseId = readGUIDIndex();
+	}
+
+	protected int getRowSize() {
+	    return 2 + file.getStringIndexSize() + 3*file.getGUIDIndexSize();
+	}
+
+	public String getName() {
+	    return file.getString(Name);
+	}
+
+    } // class ModuleDef
+
+    //##########################################################################
+    // table TypeRef; ID=0x01; p125, 21.35
+
+    public static final class TypeRef extends Table {
+	public static final int ID = 0x1;
+
+	/** A ResolutionScope coded index. */
+	public int ResolutionScope;
+
+	/** Index into #String. */
+	public int Name;
+
+	/** Index into #String. */
+	public int Namespace;
+
+	public TypeRef(PEFile file, int rows) { super(file, ID, rows); }
+
+	protected void populateFields() {
+	    ResolutionScope = readTableSetIndex(_ResolutionScope);
+	    Name = readStringIndex();
+	    Namespace = readStringIndex();
+	}
+
+	protected int getRowSize() {
+	    return file.getTableSetIndexSize(_ResolutionScope) +
+		2 * file.getStringIndexSize();
+	}
+
+	public String getFullName() {
+	    String namespace = file.getString(Namespace);
+	    return namespace.length() == 0 ? file.getString(Name)
+		: namespace + "." + file.getString(Name);
+	}
+
+    } // class TypeRef
+
+    //##########################################################################
+    // table TypeDef; ID=0x02; p120, 21.34
+
+    public static final class TypeDef extends Table {
+	public static final int ID = 0x02;
+
+	/** 4-byte bitmask of type TypeAttributes (22.1.14). */
+	public int Flags;
+
+	/** Index into #String. */
+	public int Name;
+
+	/** Index into #String. */
+	public int Namespace;
+
+	/** TypeDefOrRef coded index. */
+	public int Extends;
+
+	/** Index into Field table.
+	 */
+	public int FieldList;
+
+	/** Index into Method table. */
+	public int MethodList;
+
+
+	public TypeDef(PEFile file, int rows) {
+	    super(file, ID, rows);
+	    this.newMapping = true;
+	}
+
+	public String getFullName() {
+	    String namespace = file.getString(Namespace);
+	    return namespace.length() == 0 ? file.getString(Name)
+		: namespace + "." + file.getString(Name);
+	}
+
+	protected void populateFields() {
+	    Flags = readInt();
+	    Name = readStringIndex();
+	    Namespace = readStringIndex();
+	    Extends = readTableSetIndex(_TypeDefOrRef);
+	    FieldList = readTableIndex(FieldDef.ID);
+	    MethodList = readTableIndex(MethodDef.ID);
+	}
+
+	protected int getRowSize() {
+	    return 4 + 2*file.getStringIndexSize() +
+		file.getTableSetIndexSize(_TypeDefOrRef) +
+		file.getTableIndexSize(FieldDef.ID) +
+		file.getTableIndexSize(MethodDef.ID);
+	}
+
+    } // class TypeDef
+
+    //##########################################################################
+    // Table FieldTrans; ID=0x03; undocumented
+
+    /**
+     * Undocumented table. Appears to be used for translating the Field entry
+     * in the TypeDef(0x02) table into the real entry in the Fields(0x06) table
+     */
+    public static final class FieldTrans extends Table {
+	public static final int ID = 0x03;
+
+	public int Field;
+
+	public FieldTrans(PEFile file, int rows) {
+	    super(file, ID, rows);
+	    newMapping = true;
+	}
+
+	protected void populateFields() {
+	    Field = readTableIndex(FieldDef.ID);
+	}
+
+	protected int getRowSize() {
+	    return file.getTableIndexSize(FieldDef.ID);
+	}
+
+    }
+
+    //##########################################################################
+    // table Field; ID=0x04; p102, 21.15
+
+    public static final class FieldDef extends Table {
+	public static final int ID = 0x04;
+
+	/** 2-byte bitmask of type FieldAttributes (22.1.5). */
+	public int Flags;
+
+	/** Index into #String. */
+	public int Name;
+
+	/** Index into #Blob. */
+	public int Signature;
+
+	public FieldDef(PEFile file, int rows) {
+	    super(file, ID, rows);
+	    newMapping = true;
+	}
+
+	protected void populateFields() {
+	    Flags = readShort();
+	    Name = readStringIndex();
+	    Signature = readBlobIndex();
+	}
+
+	protected int getRowSize() {
+	    return 2 + file.getStringIndexSize() + file.getBlobIndexSize();
+	}
+
+	public String getName() { return file.getString(Name); }
+
+	public Sig getSignature() { return file.getSignature(Signature); }
+
+    } //class FieldDef
+
+    //##########################################################################
+    // Table MethodTrans; ID=0x05; undocumented
+
+    /**
+     * Undocumented table. Appears to be used for translating the Method entry
+     * in the TypeDef(0x02) table into the real entry in the Methods(0x06) table
+     */
+    public static final class MethodTrans extends Table {
+	public static final int ID = 0x05;
+
+	public int Method;
+
+	public MethodTrans(PEFile file, int rows) {
+	    super(file, ID, rows);
+	    newMapping = true;
+	}
+
+	protected void populateFields() {
+	    Method = readTableIndex(FieldDef.ID);
+	}
+
+	protected int getRowSize() {
+	    return file.getTableIndexSize(MethodDef.ID);
+	}
+
+    }
+
+    //##########################################################################
+    // table MethodDef; ID=0x06; p110, 21.24
+
+    public static final class MethodDef extends Table {
+	public static final int ID = 0x06;
+
+	/** 4-byte constant. */
+	public int RVA;
+
+	/** 2-byte bitmask of type MethodImplAttributes (22.1.10). */
+	public int ImplFlags;
+
+	/** 2-byte bitmask of type MethodAttributes (22.1.9). */
+	public int Flags;
+
+	/** Index into #String. */
+	public int Name;
+
+	/** Index into #Blob. */
+	public int Signature;
+
+	/** Index into Param Table. */
+	public int ParamList;
+
+	public MethodDef(PEFile file, int rows) {
+	    super(file, ID, rows);
+	    newMapping = true;
+	}
+
+	protected void populateFields() {
+	    RVA = readInt();
+	    ImplFlags = readShort();
+	    Flags = readShort();
+	    Name = readStringIndex();
+	    Signature = readBlobIndex();
+	    ParamList = readTableIndex(ParamDef.ID);
+	}
+
+	protected int getRowSize() {
+	    return 8 + file.getStringIndexSize() + file.getBlobIndexSize() +
+		file.getTableIndexSize(ParamDef.ID);
+	}
+
+	public String getName() { return file.getString(Name); }
+
+	public Sig getSignature() { return file.getSignature(Signature); }
+    } // class Method
+
+    //##########################################################################
+    // table Param; ID=0x08; p116, 21.30
+
+    public static final class ParamDef extends Table {
+	public static final int ID = 0x08;
+
+	/** 2-byte bitmask of type ParamAttributes (22.1.12). */
+	public int Flags;
+
+	/** 2-byte constant. */
+	public int Sequence;
+
+	/** Index into #String. */
+	public int Name;
+
+	public ParamDef(PEFile file, int rows) {
+	    super(file, ID, rows);
+	    newMapping = true;
+	}
+
+	protected void populateFields() {
+	    Flags = readShort();
+	    Sequence = readShort();
+	    Name = readStringIndex();
+	}
+
+	protected int getRowSize() { return 4 + file.getStringIndexSize(); }
+
+	public String getName() { return file.getString(Name); }
+
+    } // class Param
+
+    //##########################################################################
+    // table InterfaceImpl, ID=0x09; p107, 21.21
+
+    public static final class InterfaceImpl extends Table {
+	public static final int ID = 0x09;
+
+	/** Index into TypeDef table. */
+	public int Class;
+
+	/** Index into TypeDefOrRef table set. */
+	public int Interface;
+
+	public InterfaceImpl(PEFile file, int rows) { super(file, ID, rows); }
+
+	protected void populateFields() {
+	    Class = readTableIndex(TypeDef.ID);
+	    Interface = readTableSetIndex(_TypeDefOrRef);
+	}
+
+	protected int getRowSize() {
+	    return file.getTableIndexSize(TypeDef.ID) +
+		file.getTableSetIndexSize(_TypeDefOrRef);
+	}
+
+	/** finds the index of the first entry
+	 * @param targetIndex - index in the TypeDef table - the type to look for
+	 * @return the index of the first interface for the given type;
+	 *         0 if the type doesn't implement any interfaces
+	 */
+
+	// binary search implementation
+// 	public int findType(int targetIndex) {
+// 	    int l = 1, h = rows;
+// 	    int classIndex;
+// 	    while (l <= h) {
+// 		int mid = (l + h) / 2;
+// 		seekRow(mid);
+// 		classIndex = readTableIndex(TypeDef.ID);
+// 		if (targetIndex <= classIndex) h = mid - 1;
+// 		else l = mid + 1;
+// 	    }
+// 	    return (targetIndex == classIndex) ? h : 0;
+// 	}
+
+	//linear search implementation
+	public int findType(int targetIndex) {
+	    for (int i = 1; i <= rows; i++) {
+		seekRow(i);
+		if (targetIndex == readTableIndex(TypeDef.ID))
+		    return i;
+	    }
+	    return 0;
+	}
+
+    } // class InterfaceImpl
+
+    //##########################################################################
+    // table MemberRef; ID=0x0a; p109, 21.23
+
+    public static final class MemberRef extends Table {
+	public static final int ID = 0x0a;
+
+	/** Index into MemberRefParent table set. */
+	public int Class;
+
+	/** Index into #String. */
+	public int Name;
+
+	/** Index into #Blob. */
+	public int Signature;
+
+	public MemberRef(PEFile file, int rows) { super(file, ID, rows); }
+
+	protected void populateFields() {
+	    Class = readTableSetIndex(_MemberRefParent);
+	    Name = readStringIndex();
+	    Signature = readBlobIndex();
+	}
+
+	protected int getRowSize() {
+	    return file.getTableSetIndexSize(_MemberRefParent) +
+		file.getStringIndexSize() + file.getBlobIndexSize();
+	}
+
+	public String getName() {
+	    return file.getString(Name);
+	}
+
+	public Sig getSignature() {
+	    return file.getSignature(Signature);
+	}
+
+    } // class MemberRef
+
+    //##########################################################################
+    // table Constant; ID=0x0b; p95, 21.9
+
+    public static final class Constant extends Table {
+	public static final int ID = 0x0b;
+
+	/** 1-byte constant followed by 1-byte padding 0 (see 22.1.15). */
+	public int Type;
+
+	/** Index into HasConst table set. */
+	public int Parent;
+
+	/** Index into #Blob. */
+	public int Value;
+
+	public Constant(PEFile file, int rows) { super(file, ID, rows); }
+
+	protected void populateFields() {
+	    Type = readShort();
+	    Parent = readTableSetIndex(_HasConstant);
+	    Value = readBlobIndex();
+	}
+
+	protected int getRowSize() {
+	    return 2 + file.getTableSetIndexSize(_HasConstant) +
+		file.getBlobIndexSize();
+	}
+
+	public Object getValue() {
+	    if (Type == Signature.ELEMENT_TYPE_CLASS)
+		return null;
+	    return file.Blob.getConstant(Type, Value);
+	}
+
+
+    } // class Constant
+
+    //##########################################################################
+    // table CustomAttribute; ID=0x0c; p95, 21.10
+
+    public static final class CustomAttribute extends Table {
+	public static final int ID = 0x0c;
+
+	/** Index into any metadata table, except the CustomAttribute itself;
+	 *  more precisely - index into HasCustomAttribute table set.
+	 */
+	public int Parent;
+
+	/** Index into the CustomAttributeType table set. */
+	public int Type;
+
+	/** Index into #Blob. */
+	public int Value;
+
+	public CustomAttribute(PEFile file, int rows) { super(file, ID, rows); }
+
+	protected void populateFields() {
+	    Parent = readTableSetIndex(_HasCustomAttribute);
+	    Type = readTableSetIndex(_CustomAttributeType);
+	    Value = readBlobIndex();
+	}
+
+	protected int getRowSize() {
+	    return file.getTableSetIndexSize(_HasCustomAttribute) +
+		file.getTableSetIndexSize(_CustomAttributeType) +
+		file.getBlobIndexSize();
+	}
+
+	public byte[] getValue() {
+	    return Value == 0 ? null : file.getBlob(Value);
+	}
+    } // class CustomAttribute
+
+    //##########################################################################
+    // table FieldMarshal; ID=0x0d; p105, 21.17
+
+    public static final class FieldMarshal extends Table {
+	public static final int ID = 0x0d;
+
+	/** Index into HasFieldMarshal table set. */
+	public int Parent;
+
+	/** Index into #Blob. */
+	public int NativeType;
+
+	public FieldMarshal(PEFile file, int rows) { super(file, ID, rows); }
+
+	protected void populateFields() {
+	    Parent = readTableSetIndex(_HasFieldMarshal);
+	    NativeType = readBlobIndex();
+	}
+
+	protected int getRowSize() {
+	    return file.getTableSetIndexSize(_HasFieldMarshal) +
+		file.getBlobIndexSize();
+	}
+
+    } // class FieldMarshal
+
+    //##########################################################################
+    // table DeclSecurity; ID=0x0e; p97, 21.11
+
+    public static final class DeclSecurity extends Table {
+	public static final int ID = 0x0e;
+
+	/** 2-byte value. */
+	public int Action;
+
+	/** Index into HasDeclSecurity table set. */
+	public int Parent;
+
+	/** Index into #Blob. */
+	public int PermissionSet;
+
+	public DeclSecurity(PEFile file, int rows) { super(file, ID, rows); }
+
+	protected void populateFields() {
+	    Action = readShort();
+	    Parent = readTableSetIndex(_HasDeclSecurity);
+	    PermissionSet = readBlobIndex();
+	}
+
+	protected int getRowSize() {
+	    return 2 + file.getTableSetIndexSize(_HasDeclSecurity) +
+		file.getBlobIndexSize();
+	}
+
+    } // class DeclSecurity
+
+    //##########################################################################
+    // table ClassLayout; ID=0x0f, p92, 21.8
+
+    public static final class ClassLayout extends Table {
+	public static final int ID = 0x0f;
+
+	/** 2-byte constant. */
+	public int PackingSize;
+
+	/** 4-byte constant. */
+	public int ClassSize;
+
+	/** Index into TypeDef table. */
+	public int Parent;
+
+	public ClassLayout(PEFile file, int rows) { super(file, ID, rows); }
+
+	protected void populateFields() {
+	    PackingSize = readShort();
+	    ClassSize = readInt();
+	    Parent = readTableIndex(TypeDef.ID);
+	}
+
+	protected int getRowSize() {
+	    return 6 + file.getTableIndexSize(TypeDef.ID);
+	}
+
+    } // class ClassLayout
+
+    //##########################################################################
+    // table FieldLayout; ID=0x10; p104, 21.16
+
+    public static final class FieldLayout extends Table {
+	public static final int ID = 0x10;
+
+	/** 4-byte constant. */
+	public int Offset;
+
+	/** Index into the Field table. */
+	public int Field;
+
+	public FieldLayout(PEFile file, int rows) { super(file, ID, rows); }
+
+	protected void populateFields() {
+	    Offset = readInt();
+	    Field = readTableIndex(FieldDef.ID);
+	}
+
+	protected int getRowSize() {
+	    return 4 + file.getTableIndexSize(FieldDef.ID);
+	}
+
+    } // class FieldLayout
+
+    //##########################################################################
+    // table StandAloneSig; ID=0x11; p119, 21.33
+
+    public static final class StandAloneSig extends Table {
+	public static final int ID = 0x11;
+
+	/** Index into #Blob. */
+	public int Signature;
+
+	public StandAloneSig(PEFile file, int rows) { super(file, ID, rows); }
+
+	protected void populateFields() {
+	    Signature = readBlobIndex();
+	}
+
+	protected int getRowSize() { return file.getBlobIndexSize(); }
+
+    } // class StandAloneSig
+
+    //##########################################################################
+    // table EventMap; ID=0x12; p99, 21.12
+
+    public static final class EventMap extends Table {
+	public static final int ID = 0x12;
+
+	/** Index into the TypeDef table. */
+	public int Parent;
+
+	/** Index into the Event table. */
+	public int EventList;
+
+	public EventMap(PEFile file, int rows) { super(file, ID, rows); }
+
+	protected void populateFields() {
+	    Parent = readTableIndex(TypeDef.ID);
+	    EventList = readTableIndex(EventDef.ID);
+	}
+
+	protected int getRowSize() {
+	    return file.getTableIndexSize(TypeDef.ID) +
+		file.getTableIndexSize(EventDef.ID);
+	}
+
+    } // class EventMap
+
+    //##########################################################################
+    // table Event; ID=0x14; p99, 21.13
+
+    public static final class EventDef extends Table {
+	public static final int ID = 0x14;
+
+	/** 2-byte bitmask of type EventAttribute (22.1.4). */
+	public int EventFlags;
+
+	/** Index into #String. */
+	public int Name;
+
+	/** Index into TypeDefOrRef table set. [This corresponds to the Type
+	 *  of the event; it is not the Type that owns the event]
+	 */
+	public int EventType;
+
+	public EventDef(PEFile file, int rows) { super(file, ID, rows); }
+
+	protected void populateFields() {
+	    EventFlags = readShort();
+	    Name = readStringIndex();
+	    EventType = readTableSetIndex(_TypeDefOrRef);
+	}
+
+	protected int getRowSize() {
+	    return 2 + file.getStringIndexSize() +
+		file.getTableSetIndexSize(_TypeDefOrRef);
+	}
+
+	public String getName() { return file.getString(Name); }
+
+    } // class EventDef
+
+    //##########################################################################
+    // table PropertyMap; ID=0x15; p119, 21.32
+
+    public static final class PropertyMap extends Table {
+	public static final int ID = 0x15;
+
+	/** Index into the TypeDef table. */
+	public int Parent;
+
+	/** Index into the Property table. */
+	public int PropertyList;
+
+	public PropertyMap(PEFile file, int rows) { super(file, ID, rows); }
+
+	protected void populateFields() {
+	    Parent = readTableIndex(TypeDef.ID);
+	    PropertyList = readTableIndex(PropertyDef.ID);
+	}
+
+	protected int getRowSize() {
+	    return file.getTableIndexSize(TypeDef.ID) +
+		file.getTableIndexSize(PropertyDef.ID);
+	}
+
+    } // class PropertyMap
+
+    //##########################################################################
+    // table Property; ID=0x17; p117, 21.31
+
+    public static final class PropertyDef extends Table {
+	public static final int ID = 0x17;
+
+	/** 2-byte bitmask of type PropertyAttributes (22.1.13). */
+	public int Flags;
+
+	/** Index into #String. */
+	public int Name;
+
+	/** Index into #Blob. (Indexes the signature in the #Blob) */
+	public int Type;
+
+	public PropertyDef(PEFile file, int rows) { super(file, ID, rows); }
+
+	protected void populateFields() {
+	    Flags = readShort();
+	    Name = readStringIndex();
+	    Type = readBlobIndex();
+	}
+
+	protected int getRowSize() {
+	    return 2 + file.getStringIndexSize() +
+		file.getBlobIndexSize();
+	}
+
+	public String getName() { return file.getString(Name); }
+
+	public Sig getSignature() { return file.getSignature(Type); }
+
+    } // class PropertyDef
+
+    //##########################################################################
+    // table MethodSemantics; ID=0x18; p114, 21.26
+
+    public static final class MethodSemantics extends Table {
+	public static final int ID = 0x18;
+
+	/** 2-byte bitmaks of type MethodSemanticsAttribute (22.1.11). */
+	public int Semantics;
+
+	/** Index into the Method table. */
+	public int Method;
+
+	/** Index into Event or Property table (HasSemantics table set). */
+	public int Association;
+
+	public MethodSemantics(PEFile file, int rows) { super(file, ID, rows); }
+
+	protected void populateFields() {
+	    Semantics = readShort();
+	    Method = readTableIndex(MethodDef.ID);
+	    Association = readTableSetIndex(_HasSemantics);
+	}
+
+	protected int getRowSize() {
+	    return 2 + file.getTableIndexSize(MethodDef.ID) +
+		file.getTableSetIndexSize(_HasSemantics);
+	}
+
+        public boolean isGetter()   { return (Semantics & Getter)   != 0; }
+        public boolean isSetter()   { return (Semantics & Setter)   != 0; }
+        public boolean isOther()    { return (Semantics & Other)    != 0; }
+        public boolean isAddOn()    { return (Semantics & AddOn)    != 0; }
+        public boolean isRemoveOn() { return (Semantics & RemoveOn) != 0; }
+        public boolean isFire()     { return (Semantics & Fire)     != 0; }
+
+        private static final short Setter   = (short)0x0001;
+        private static final short Getter   = (short)0x0002;
+        private static final short Other    = (short)0x0004;
+        private static final short AddOn    = (short)0x0008;
+        private static final short RemoveOn = (short)0x0010;
+        private static final short Fire     = (short)0x0020;
+
+    } // class MethodSemantics
+
+
+    //##########################################################################
+    // table MethodImpl; ID=0x19; p113, 21.25
+
+    public static final class MethodImpl extends Table {
+	public static final int ID = 0x19;
+
+	/** Index into the TypeDef table. */
+	public int Class;
+
+	/** Index into MethodDefOrRef table set. */
+	public int MethodBody;
+
+	/** Index into MethodDefOrRef table set. */
+	public int MethodDeclaration;
+
+	public MethodImpl(PEFile file, int rows) { super(file, ID, rows); }
+
+	protected void populateFields() {
+	    Class = readTableIndex(TypeDef.ID);
+	    MethodBody = readTableSetIndex(_MethodDefOrRef);
+	    MethodDeclaration = readTableSetIndex(_MethodDefOrRef);
+	}
+
+	protected int getRowSize() {
+	    return file.getTableIndexSize(TypeDef.ID) +
+		2 * file.getTableSetIndexSize(_MethodDefOrRef);
+	}
+
+    } // class MethodImpl
+
+    //##########################################################################
+    // table ModuleRef; ID=0x1a; p116, 21.28
+
+    public static final class ModuleRef extends Table {
+	public static final int ID = 0x1a;
+
+	/** Index into #String. */
+	public int Name;
+
+	public ModuleRef(PEFile file, int rows) { super(file, ID, rows); }
+
+	protected void populateFields() {
+	    Name = readStringIndex();
+	}
+
+	protected int getRowSize() { return file.getStringIndexSize(); }
+
+	public String getName() { return file.getString(Name); }
+
+    } // class ModuleRef
+
+    //##########################################################################
+    // table TypeSpec; ID=0x1b; p126, 21.36
+
+    public static final class TypeSpec extends Table {
+	public static final int ID = 0x1b;
+
+	/** Index into #Blob, where the blob is formatted
+	 *  as specified in 22.2.15
+	 */
+	public int Signature;
+
+	public TypeSpec(PEFile file, int rows) { super(file, ID, rows); }
+
+	protected void populateFields() {
+	    Signature = readBlobIndex();
+	}
+
+	protected int getRowSize() { return file.getBlobIndexSize(); }
+
+	public Sig getSignature() { return file.getSignature(Signature); }
+    } // class TypeSpec
+
+    //##########################################################################
+    // table ImplMap; ID=0x1c; p107, 21.20
+
+    public static final class ImplMap extends Table {
+	public static final int ID = 0x1c;
+
+	/** 2-byte bitmask of type PInvokeAttributes (22.1.7). */
+	public int MappingFlags;
+
+	/** Index into MemberForwarded table set. */
+	public int MemberForwarded;
+
+	/** Index into #String. */
+	public int ImportName;
+
+	/** Index into the ModuleRef table. */
+	public int ImportScope;
+
+	public ImplMap(PEFile file, int rows) { super(file, ID, rows); }
+
+	protected void populateFields() {
+	    MappingFlags = readShort();
+	    MemberForwarded = readTableSetIndex(_MemberForwarded);
+	    ImportName = readStringIndex();
+	    ImportScope = readTableIndex(ModuleRef.ID);
+	}
+
+	protected int getRowSize() {
+	    return 2 + file.getTableSetIndexSize(_MemberForwarded) +
+		file.getStringIndexSize() +
+		file.getTableIndexSize(ModuleRef.ID);
+	}
+
+    } // class ImplMap
+
+    //##########################################################################
+    // table FieldRVA; ID=0x1d; p106, 21.18
+
+    public static final class FieldRVA extends Table {
+	public static final int ID = 0x1d;
+
+	/** 4-byte constant. */
+	public int RVA;
+
+	/** Index into the Field table. */
+	public int Field;
+
+	public FieldRVA(PEFile file, int rows) { super(file, ID, rows); }
+
+	protected void populateFields() {
+	    RVA = readInt();
+	    Field = readTableIndex(Table.FieldDef.ID);
+	}
+
+	protected int getRowSize() {
+	    return 4 + file.getTableIndexSize(FieldDef.ID);
+	}
+
+    }
+
+    //##########################################################################
+    // table Assembly; ID=0x20; p90, 21.2
+
+    public static final class AssemblyDef extends Table {
+	public static final int ID = 0x20;
+
+	/** 4-byte constatnt of type AssemblyHashAlgorithm, clause 22.1.1 */
+	public int HashAlgId;
+
+	/** 2-byte constant */
+	public int MajorVersion;
+
+	/** 2-byte constant */
+	public int MinorVersion;
+
+	/** 2-byte constant */
+	public int BuildNumber;
+
+	/** 2-byte constant */
+	public int RevisionNumber;
+
+	/** 4-byte constant */
+	public int Flags;
+
+	/** index into #Blob */
+	public int PublicKey;
+
+	/** index into #String */
+	public int Name;
+
+	/** index into #String */
+	public int Culture;
+
+	public AssemblyDef(PEFile file, int rows) { super(file, ID, rows); }
+
+	protected void populateFields() {
+	    HashAlgId = readInt();
+	    MajorVersion = readShort();
+	    MinorVersion = readShort();
+	    BuildNumber = readShort();
+	    RevisionNumber = readShort();
+	    Flags = readInt();
+	    PublicKey = readBlobIndex();
+	    Name = readStringIndex();
+	    Culture = readStringIndex();
+	}
+
+	protected int getRowSize() {
+	    return 16 + file.getBlobIndexSize() + 2*file.getStringIndexSize();
+	}
+
+    } // class AssemblyDef
+
+    //##########################################################################
+    // table AssemblyProcessor; ID=0x21; p91, 21.4
+
+    public static final class AssemblyProcessor extends Table {
+	public static final int ID = 0x21;
+
+	/** 4-byte constant. */
+	public int Processor;
+
+	public AssemblyProcessor(PEFile file, int rows) { super(file, ID, rows); }
+
+	protected void populateFields() {
+	    Processor = readInt();
+	}
+
+	protected int getRowSize() { return 4; }
+
+    }
+
+    //##########################################################################
+    // table AssemblyOS; ID = 0x22; p90, 21.3
+
+    public static final class AssemblyOS extends Table {
+	public static final int ID = 0x22;
+
+	/** 4-byte constant. */
+	public int OSPlatformID;
+
+	/** 4-byte constant. */
+	public int OSMajorVersion;
+
+	/** 4-byte constant. */
+	public int OSMinorVersion;
+
+	public AssemblyOS(PEFile file, int rows) { super(file, ID, rows); }
+
+	protected void populateFields() {
+	    OSPlatformID = readInt();
+	    OSMajorVersion = readInt();
+	    OSMinorVersion = readInt();
+	}
+
+	protected int getRowSize() { return 12; }
+
+    }
+
+    //##########################################################################
+    // table AssemblyRef; ID = 0x23; pp91, 21.5
+
+    public static final class AssemblyRef extends Table {
+	public static final int ID = 0x23;
+
+	/** 2-byte constant. */
+	public int MajorVersion;
+
+	/** 2-byte constant. */
+	public int MinorVersion;
+
+	/** 2-byte constant. */
+	public int BuildNumber;
+
+	/** 2-byte constant. */
+	public int RevisionNumber;
+
+	/** 4-byte bitmask of type AssemblyFlags (22.1.2). */
+	public int Flags;
+
+	/** index into #Blob. */
+	public int PublicKeyOrToken;
+
+	/** index into #String. */
+	public int Name;
+
+	/** index into #String. */
+	public int Culture;
+
+	/** index into #Blob. */
+	public int HashValue;
+
+	public AssemblyRef(PEFile file, int rows) { super(file, ID, rows); }
+
+	protected void populateFields() {
+	    MajorVersion = readShort();
+	    MinorVersion = readShort();
+	    BuildNumber = readShort();
+	    RevisionNumber = readShort();
+	    Flags = readInt();
+	    PublicKeyOrToken = readBlobIndex();
+	    Name = readStringIndex();
+	    Culture = readStringIndex();
+	    HashValue = readBlobIndex();
+	}
+
+	protected int getRowSize() {
+	    return 12 + 2*file.getBlobIndexSize() + 2*file.getStringIndexSize();
+	}
+
+	public String getName() { return file.getString(Name); }
+    }
+
+    //##########################################################################
+    // table AssemblyRefProcessor; ID=0x24; p92, 21.7
+
+    public static final class AssemblyRefProcessor extends Table {
+	public static final int ID = 0x24;
+
+	/** 4-byte constant. */
+	public int Processor;
+
+	/** Index into the AssemblyRef table. */
+	public int AssemblyRef;
+
+	public AssemblyRefProcessor(PEFile file, int rows) { super(file, ID, rows); }
+
+	protected void populateFields() {
+	    Processor = readInt();
+	    AssemblyRef = readTableIndex(Table.AssemblyRef.ID);
+	}
+
+	protected int getRowSize() {
+	    return 4 + file.getTableIndexSize(Table.AssemblyRef.ID);
+	}
+
+    } // class AssemblyRefProcessor
+
+    //##########################################################################
+    // table AssemblyRefOS; ID=0x25; p92, 21.6
+
+    public static final class AssemblyRefOS extends Table {
+	public static final int ID = 0x25;
+
+	/** 4-byte constant. */
+	public int OSPlatformId;
+
+	/** 4-byte constant. */
+	public int OSMajorVersion;
+
+	/** 4-byte constant. */
+	public int OSMinorVersion;
+
+	/** Index into the AssemblyRef table. */
+	public int AssemblyRef;
+
+	public AssemblyRefOS(PEFile file, int rows) { super(file, ID, rows); }
+
+	protected void populateFields() {
+	    OSPlatformId = readInt();
+	    OSMajorVersion = readInt();
+	    OSMinorVersion = readInt();
+	    AssemblyRef = readTableIndex(Table.AssemblyRef.ID);
+	}
+
+	protected int getRowSize() {
+	    return 12 + file.getTableIndexSize(Table.AssemblyRef.ID);
+	}
+
+    } // class AssemblyRefOS
+
+    //##########################################################################
+    // table File; ID=0x26; p106, 21.19
+
+    public static final class FileDef extends Table {
+	public static final int ID = 0x26;
+
+	/** 4-byte bitmask of type FileAttributes (22.1.6). */
+	public int Flags;
+
+	/** Index into #String. */
+	public int Name;
+
+	/** Index into #Blob. */
+	public int HashValue;
+
+	public FileDef(PEFile file, int rows) { super(file, ID, rows); }
+
+	protected void populateFields() {
+	    Flags = readInt();
+	    Name = readStringIndex();
+	    HashValue = readBlobIndex();
+	}
+
+	protected int getRowSize() {
+	    return 4 + file.getStringIndexSize() + file.getBlobIndexSize();
+	}
+
+	public String getName() {
+	    return file.getString(Name);
+	}
+
+    } // class FileDef
+
+    //##########################################################################
+    // table ExportedType; ID=0x27; p100, 21.14
+
+    public static final class ExportedType extends Table {
+	public static final int ID = 0x27;
+
+	/** 4-byte bitmask of type TypeAttribute (22.1.6). */
+	public int Flags;
+
+	/** 4-byte index into a TypeDef table of
+	 *  another module in this assembly.
+	 */
+	public int TypeDefId;
+
+	/** Index into #String. */
+	public int TypeName;
+
+	/** Index into #Stream. */
+	public int TypeNamespace;
+
+	/** Index into one of two tables as follows:
+	 *   - 'File' table, where that entry says which module
+	 *     in the current assembly holds the TypeDef
+	 *   - 'ExportedType' table, where that entry is
+	 *     the enclosing Type of the current nested Type
+	 */
+	public int Implementation;
+
+	public ExportedType(PEFile file, int rows) { super(file, ID, rows); }
+
+	protected void populateFields() {
+	    Flags = readInt();
+	    TypeDefId = readInt();
+	    TypeName = readStringIndex();
+	    TypeNamespace = readStringIndex();
+	    Implementation = readTableSetIndex(_Implementation);
+	}
+
+	protected int getRowSize() {
+	    return 8 + 2*file.getStringIndexSize() +
+		file.getTableSetIndexSize(_Implementation);
+	}
+
+	public String getFullName() {
+	    String namespace = file.getString(TypeNamespace);
+	    return namespace.length() == 0 ? file.getString(TypeName)
+		: namespace + "." + file.getString(TypeName);
+	}
+
+    } // class ExportedType
+
+    //##########################################################################
+    // table ManifestResource; ID=0x28; p108, 21.22
+
+    public static final class ManifestResource extends Table {
+	public static final int ID = 0x28;
+
+	/** 4-byte constant. */
+	public int Offset;
+
+	/** 4-byte bitmask of type ManifestResourceAttributes (22.1.8). */
+	public int Flags;
+
+	/** Index into #String. */
+	public int Name;
+
+	/** Index into the Implementation table set. */
+	public int Implementation;
+
+	public ManifestResource(PEFile file, int rows) { super(file, ID, rows); }
+
+	protected void populateFields() {
+	    Offset = readInt();
+	    Flags = readInt();
+	    Name = readStringIndex();
+	    Implementation = readTableSetIndex(_Implementation);
+	}
+
+	protected int getRowSize() {
+	    return  8 + file.getStringIndexSize() +
+		file.getTableSetIndexSize(_Implementation);
+	}
+
+    } // class ManifestResource
+
+    //##########################################################################
+    // table NestedClass; ID=0x29; p116, 21.29
+
+    public static final class NestedClass extends Table {
+	public static final int ID = 0x29;
+
+	/** Index into the TypeDef table. */
+	public int NestedClass;
+
+	/** Index into the TypeDef table. */
+	public int EnclosingClass;
+
+	public NestedClass(PEFile file, int rows) { super(file, ID, rows); }
+
+	protected void populateFields() {
+	    NestedClass = readTableIndex(TypeDef.ID);
+	    EnclosingClass = readTableIndex(TypeDef.ID);
+	}
+
+	protected int getRowSize() {
+	    return 2 * file.getTableIndexSize(TypeDef.ID);
+	}
+
+    } // class NestedClass
+
+    //##########################################################################
+
+}  // class Table
diff --git a/src/partest-alternative/README b/src/partest-alternative/README
new file mode 100644
index 0000000..c7673fe
--- /dev/null
+++ b/src/partest-alternative/README
@@ -0,0 +1,50 @@
+If you're looking for something to read, I suggest running ../test/partest
+with no arguments, which at this moment prints this:
+
+Usage: partest [<options>] [<test> <test> ...]
+  <test>: a path to a test designator, typically a .scala file or a directory.
+          Examples: files/pos/test1.scala, files/res/bug785
+
+  Test categories:
+    --all          run all tests (default, unless no options given)
+    --pos          Compile files that are expected to build
+    --neg          Compile files that are expected to fail
+    --run          Test JVM backend
+    --jvm          Test JVM backend
+    --res          Run resident compiler scenarii
+    --buildmanager Run Build Manager scenarii
+    --scalacheck   Run Scalacheck tests
+    --script       Run script files
+    --shootout     Run shootout tests
+    --scalap       Run scalap tests
+
+  Test "smart" categories:
+    --grep         run all tests with a source file containing <expr>
+    --failed       run all tests which failed on the last run
+
+  Specifying paths and additional flags, ~ means repository root:
+    --rootdir      path from ~ to partest (default: test)
+    --builddir     path from ~ to test build (default: build/pack)
+    --srcdir       path from --rootdir to sources (default: files)
+    --javaopts     flags to java on all runs (overrides JAVA_OPTS)
+    --scalacopts   flags to scalac on all tests (overrides SCALAC_OPTS)
+    --pack         alias for --builddir build/pack
+    --quick        alias for --builddir build/quick
+
+  Options influencing output:
+    --trace        show the individual steps taken by each test
+    --show-diff    show diff between log and check file
+    --show-log     show log on failures
+    --dry-run      do not run tests, only show their traces.
+    --terse        be less verbose (almost silent except for failures)
+    --verbose      be more verbose (additive with --trace)
+    --debug        maximum debugging output
+    --ansi         print output in color
+
+  Other options:
+    --timeout      Timeout in seconds
+    --cleanup      delete all stale files and dirs before run
+    --nocleanup    do not delete any logfiles or object dirs
+    --stats        collect and print statistics about the tests
+    --validate     examine test filesystem for inconsistencies
+    --version      print version
diff --git a/src/partest-alternative/scala/tools/partest/Actions.scala b/src/partest-alternative/scala/tools/partest/Actions.scala
new file mode 100644
index 0000000..96ac1ba
--- /dev/null
+++ b/src/partest-alternative/scala/tools/partest/Actions.scala
@@ -0,0 +1,231 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala Parallel Testing               **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+package scala.tools
+package partest
+
+import util._
+import nsc.io._
+
+trait Actions {
+  partest: Universe =>
+  
+  class TestSequence(val actions: List[TestStep]) extends AbsTestSequence {
+  }
+
+  implicit def createSequence(xs: List[TestStep]) = new TestSequence(xs)
+  
+  trait ExecSupport {
+    self: TestEntity =>
+    
+    def execEnv: Map[String, String] = {
+      val map = assembleEnvironment()
+      val cwd = execCwd.toList map ("CWD" -> _.path)
+      
+      map ++ cwd
+    }
+    def execCwd = if (commandFile.isFile) Some(sourcesDir) else None
+  
+    def runExec(args: List[String]): Boolean = {
+      val cmd     = fromArgs(args)
+
+      if (isVerbose) {
+        trace("runExec: " + execEnv.mkString("ENV(", "\n", "\n)"))
+        execCwd foreach (x => trace("CWD(" + x + ")"))
+      }
+      
+      trace("runExec: " + cmd)
+      isDryRun || execAndLog(cmd)
+    }
+    
+    /** Runs <code>command</code> redirecting standard out and
+     *  error out to <code>output</code> file.
+     */
+    private def runCommandOld(command: String, output: java.io.File): Int = {
+      import java.io._
+      import nest.StreamAppender
+      
+      // NestUI.verbose("running command:\n"+command)
+      val proc = Runtime.getRuntime.exec(command)
+      val in = proc.getInputStream
+      val err = proc.getErrorStream
+      val writer = new PrintWriter(new FileWriter(output), true)
+      val inApp = StreamAppender(in, writer)
+      val errApp = StreamAppender(err, writer)
+      val async = new Thread(errApp)
+      async.start()
+      inApp.run()
+      async.join()
+      writer.close()
+
+      try proc.exitValue()
+      catch { case _: IllegalThreadStateException => 0 }
+    }
+    
+    /** Exec a process to run a command.  Assumes 0 exit value is success.
+     *  Of necessity, also treats no available exit value as success.
+     */
+    protected def execAndLog(cmd: String): Boolean = {
+      runCommandOld(cmd, logFile.jfile) == 0
+      
+      // var proc: Process = null
+      // 
+      // val result = interruptMeIn(cmd, testTimeout) {
+      //   loggingResult { 
+      //     proc = Process.exec(toArgs(cmd), execEnv, execCwd.orNull, true)
+      //     proc.slurp()
+      //   }
+      //   proc != null && (proc.waitFor() == 0)
+      // }
+      // result getOrElse {
+      //   warning("Process never terminated: '%s'" format cmd)
+      //   if (proc != null)
+      //     proc.destroy()
+      //   
+      //   false
+      // }
+    }
+  }
+  
+  trait ScriptableTest {
+    self: TestEntity =>
+    
+    /** Translates a line from a .cmds file into a teststep.
+     */
+    def customTestStep(line: String): TestStep = {
+      trace("customTestStep: " + line)
+      val (cmd, rest) = line span (x => !Character.isWhitespace(x))
+      def qualify(name: String) = sourcesDir / name path
+      val args = toArgs(rest) map qualify
+      def fail: TestStep = (_: TestEntity) => error("Parse error: did not understand '%s'" format line)
+      
+      val f: TestEntity => Boolean = cmd match {
+        case "scalac"   => _ scalac args
+        case "javac"    => _ javac args
+        case "scala"    => _ runScala args
+        case _          => fail
+      }
+      f
+    }
+  }
+  
+  trait CompilableTest extends CompileExecSupport {
+    self: TestEntity =>
+    
+    def sourceFiles   = location.walk collect { case f: File if isJavaOrScala(f) => f } toList    
+    def allSources    = sourceFiles map (_.path)
+    def scalaSources  = sourceFiles filter isScala map (_.path)
+    def javaSources   = sourceFiles filter isJava map (_.path)
+    
+    /** If there are mixed java and scala files, the standard compilation
+     *  sequence is:
+     *
+     *    scalac with all files
+     *    javac with only java files
+     *    scalac with only scala files
+     *  
+     *  This should be expanded to encompass other strategies so we know how
+     *  well they're working or not working - notably, it would be very useful
+     *  to know exactly when and how two-pass compilation fails.
+     */
+    def compile() = {
+      trace("compile: " + sourceFiles)
+      
+      def compileJava()   = javac(javaSources)
+      def compileScala()  = scalac(scalaSources)
+      def compileAll()    = scalac(allSources)
+      def compileMixed()  = compileAll() && compileJava() && compileScala()
+      
+      if (scalaSources.nonEmpty && javaSources.nonEmpty) compileMixed()
+      else compileScala()
+    }
+  }
+  
+  trait DiffableTest {
+    self: TestEntity =>
+
+    def checkFile: File   = withExtension("check").toFile
+    def checkFileRequired =
+      returning(checkFile.isFile)(res => if (!res) warnAndLog("A checkFile at '%s' is mandatory.\n" format checkFile.path))
+
+    lazy val sourceFileNames = sourceFiles map (_.name)
+    
+    /** Given the difficulty of verifying that any selective approach works
+     *  everywhere, the algorithm now is to look for the name of any known
+     *  source file for this test, and if seen, remove all the non-whitespace
+     *  preceding it.  (Paths with whitespace don't work anyway.) This should
+     *  wipe out all slashes, backslashes, C:\, cygwin/windows differences,
+     *  and whatever else makes a simple diff not simple.
+     *
+     *  The log and check file are both transformed, which I don't think is
+     *  correct -- only the log should be -- but doing it this way until I
+     *  can clarify martin's comments in #3283.
+     */
+    def normalizePaths(s: String) =
+      sourceFileNames.foldLeft(s)((res, name) => res.replaceAll("""\S+\Q%s\E""" format name, name))
+
+    /** The default cleanup normalizes paths relative to sourcesDir,
+     *  absorbs line terminator differences by going to lines and back,
+     *  and trims leading or trailing whitespace.
+     */
+    def diffCleanup(f: File) = safeLines(f) map normalizePaths mkString "\n" trim
+    
+    /** diffFiles requires actual Files as arguments but the output we want
+     *  is the post-processed versions of log/check, so we resort to tempfiles.
+     */
+    lazy val diffOutput = {
+      if (!checkFile.exists) "" else {
+        val input   = diffCleanup(checkFile)
+        val output  = diffCleanup(logFile)
+        def asFile(s: String) = returning(File.makeTemp("partest-diff"))(_ writeAll s)
+      
+        if (input == output) ""
+        else diffFiles(asFile(input), asFile(output))
+      }
+    }
+    private def checkTraceName  = tracePath(checkFile)
+    private def logTraceName    = tracePath(logFile)
+    private def isDiffConfirmed = checkFile.exists && (diffOutput == "")
+    
+    private def sendTraceMsg() {
+      def result =
+        if (isDryRun) ""
+        else if (isDiffConfirmed) " [passed]"
+        else if (checkFile.exists) " [failed]"
+        else " [unchecked]"
+      
+      trace("diff %s %s%s".format(checkTraceName, logTraceName, result))
+    }
+
+    /** If optional is true, a missing check file is considered
+     *  a successful diff.  Necessary since many categories use
+     *  checkfiles in an ad hoc manner.
+     */
+    def runDiff() = {
+      sendTraceMsg()
+      
+      def updateCheck = (
+        isUpdateCheck && {
+          val formatStr = "** diff %s %s: " + (
+            if (checkFile.exists) "failed, updating '%s' and marking as passed."
+            else if (diffOutput == "") "not creating checkFile at '%s' as there is no output."
+            else "was unchecked, creating '%s' for future tests."
+          ) + "\n"
+          
+          normal(formatStr.format(checkTraceName, logTraceName, checkFile.path))
+          if (diffOutput != "") normal(diffOutput)
+
+          checkFile.writeAll(diffCleanup(logFile), "\n")
+          true
+        }
+      )
+      
+      isDryRun || isDiffConfirmed || (updateCheck || !checkFile.exists)
+    }
+  }
+}
diff --git a/src/partest-alternative/scala/tools/partest/Alarms.scala b/src/partest-alternative/scala/tools/partest/Alarms.scala
new file mode 100644
index 0000000..8ebf0b6
--- /dev/null
+++ b/src/partest-alternative/scala/tools/partest/Alarms.scala
@@ -0,0 +1,86 @@
+/* NEST (New Scala Test)
+ * Copyright 2007-2010 LAMP/EPFL
+ * @author Paul Phillips
+ */
+
+package scala.tools
+package partest
+
+import java.util.{ Timer, TimerTask }
+
+trait Alarms {
+  self: Universe =>
+  
+  def interruptMeIn[T](debugMsg: String, seconds: Int)(body: => T): Option[T] = {
+    val thisThread  = currentThread
+    val alarm       = new SimpleAlarm(seconds * 1000) set thisThread.interrupt()
+    debug("interruptMeIn(%d) '%s'".format(seconds, debugMsg))
+    
+    try     { Some(body) }
+    catch   { case _: InterruptedException => debug("Received interrupted exception.") ; None }
+    finally { debug("Cancelling interruptMeIn '%s'" format debugMsg) ; alarm.cancel() ; Thread.interrupted() }
+  }
+
+  case class AlarmerAction(secs: Int, action: () => Unit) extends Runnable {
+    override def run() = action()
+  }
+  
+  /** Set any number of alarms up with tuples of the form:
+   *    seconds to alarm -> Function0[Unit] to execute
+   */
+  class Alarmer(alarms: AlarmerAction*) {
+    import java.util.concurrent._
+    
+    val exec = Executors.newSingleThreadScheduledExecutor()
+    alarms foreach (x => exec.schedule(x, x.secs, TimeUnit.SECONDS))
+    exec.shutdown()
+
+    def cancelAll() = exec.shutdownNow()
+  }
+  
+  class SimpleAlarm(timeout: Long) {
+    private val alarm = new Timer
+
+    /** Start a timer, running the given body if it goes off.
+     */
+    def set(body: => Unit) = returning(new TimerTask { def run() = body })(alarm.schedule(_, timeout))
+    
+    /** Cancel the timer.
+     */
+    def cancel() = alarm.cancel()
+  }
+  
+  trait TestAlarms {
+    test: TestEntity =>
+    
+    private def warning1 = AlarmerAction(testWarning, () => warning(
+      """|I've been waiting %s seconds for this to complete:
+         |  %s
+         |It may be stuck, or if not, it should be broken into smaller tests.
+         |""".stripMargin.format(testWarning, test))
+    )
+    private def warning2 = AlarmerAction(testWarning * 2, () => warning(
+      """|Now I've been waiting %s seconds for this to complete:
+         |  %s
+         |If partest seems hung it would be a good place to look.
+         |""".stripMargin.format(testWarning * 2, test))
+    )
+    
+    def startAlarms(onTimeout: => Unit) =
+      if (isNoAlarms) new Alarmer() // for alarm debugging
+      else new Alarmer(Seq(warning1, warning2, AlarmerAction(testTimeout, () => onTimeout)): _*)
+  }
+  
+  // Thread.setDefaultUncaughtExceptionHandler(new UncaughtException)
+  // class UncaughtException extends Thread.UncaughtExceptionHandler {
+  //   def uncaughtException(t: Thread, e: Throwable) {
+  //     Console.println("Uncaught in %s: %s".format(t, e))
+  //   }
+  // }
+  // 
+  // lazy val logger = File("/tmp/partest.log").bufferedWriter()
+  // def flog(msg: String) = logger synchronized {
+  //   logger write (msg + "\n")
+  //   logger.flush()
+  // }
+}
diff --git a/src/partest-alternative/scala/tools/partest/BuildContributors.scala b/src/partest-alternative/scala/tools/partest/BuildContributors.scala
new file mode 100644
index 0000000..0df5ef1
--- /dev/null
+++ b/src/partest-alternative/scala/tools/partest/BuildContributors.scala
@@ -0,0 +1,102 @@
+/* NEST (New Scala Test)
+ * Copyright 2007-2010 LAMP/EPFL
+ */
+
+package scala.tools
+package partest
+
+import nsc.io._
+import nsc.util.ClassPath
+
+trait BuildContributors {
+  universe: Universe =>
+  
+  /** A trait mixed into types which contribute a portion of the values.
+   *  The basic mechanism is the TestBuild, TestCategory, and TestEntity
+   *  can each contribute to each value.  They are assembled at the last
+   *  moment by the ContributorAssembler (presently the TestEntity.)
+   */
+  trait BuildContributor {    
+    def javaFlags: List[String]
+    def scalacFlags: List[String]
+    def classpathPaths: List[Path]
+    def buildProperties: List[(String, Any)]
+    def buildEnvironment: Map[String, String]
+  }
+  
+  trait ContributorAssembler {    
+    def contributors: List[BuildContributor]
+    def assemble[T](what: BuildContributor => List[T]): List[T] = contributors flatMap what
+    
+    /** !!! This will need work if we want to achieve real composability,
+     *  but it can wait for the demand.
+     */
+    def assembleScalacArgs(args: List[String])  = assemble(_.scalacFlags) ++ args
+    def assembleJavaArgs(args: List[String])    = assemble(_.javaFlags) ++ args
+    def assembleProperties()                    = assemble(_.buildProperties)
+    def assembleClasspaths(paths: List[Path])   = assemble(_.classpathPaths) ++ paths    
+    def assembleEnvironment()                   = assemble(_.buildEnvironment.toList).toMap
+
+    def createClasspathString() = ClassPath fromPaths (assembleClasspaths(Nil) : _*)
+    def createPropertyString()  = assembleProperties() map { case (k, v) => "-D%s=%s".format(k, v.toString) }    
+  }
+  
+  trait BuildContribution extends BuildContributor {
+    self: TestBuild =>
+
+    /** The base classpath and system properties.
+     *  !!! TODO - this should adjust itself depending on the build
+     *  being tested, because pack and quick at least need different jars.
+     */
+    def classpathPaths    = List[Path](library, compiler, partest, fjbg) ++ forkJoinPath
+    def buildProperties   = List(
+      "scala.home"          -> testBuildDir,
+      "partest.lib"         -> library,   // used in jvm/inner
+      "java.awt.headless"   -> true,
+      "user.language"       -> "en",
+      "user.country"        -> "US",
+      "partest.debug"       -> isDebug,
+      "partest.verbose"     -> isVerbose
+      // Disabled because there are no natives tests.
+      // "java.library.path"   -> srcLibDir
+    )
+    def javaFlags: List[String]   = toArgs(javaOpts)
+    def scalacFlags: List[String] = toArgs(scalacOpts)
+    
+    /** We put the build being tested's /bin directory in the front of the
+     *  path so the scripts and such written to execute "scala" will use this
+     *  build and not whatever happens to be on their path.
+     */
+    private def modifiedPath  = ClassPath.join(scalaBin.path, Properties.envOrElse("PATH", ""))
+    def buildEnvironment      = Map("PATH" -> modifiedPath)
+  }
+  
+  trait CategoryContribution extends BuildContributor {
+    self: DirBasedCategory =>
+
+    /** Category-wide classpath additions placed in <category>/lib. */
+    private def libContents = root / "lib" ifDirectory (_.list.toList)
+
+    def classpathPaths    = libContents getOrElse Nil
+    def buildProperties   = Nil
+    def javaFlags         = Nil
+    def scalacFlags       = Nil
+    def buildEnvironment  = Map()
+  }
+
+  trait TestContribution extends BuildContributor with ContributorAssembler {
+    self: TestEntity =>
+    
+    def jarsInTestDir     = location.walk collect { case f: File if f hasExtension "jar" => f } toList
+
+    def contributors      = List(build, category, self)
+    def javaFlags         = safeArgs(javaOptsFile)
+    def scalacFlags       = safeArgs(scalaOptsFile)
+    def classpathPaths    = jarsInTestDir :+ outDir
+    def buildProperties   = List(
+      "partest.output"  -> outDir.toAbsolute,         // used in jvm/inner
+      "partest.cwd"     -> outDir.parent.toAbsolute   // used in shootout tests
+    )
+    def buildEnvironment  = Map("JAVA_OPTS" -> fromArgs(assembleJavaArgs(Nil)))
+  }
+}
\ No newline at end of file
diff --git a/src/partest-alternative/scala/tools/partest/Categories.scala b/src/partest-alternative/scala/tools/partest/Categories.scala
new file mode 100644
index 0000000..e838a1e
--- /dev/null
+++ b/src/partest-alternative/scala/tools/partest/Categories.scala
@@ -0,0 +1,70 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala Parallel Testing               **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+package scala.tools
+package partest
+
+import nsc.Settings
+import nsc.io._
+import nsc.util.{ ClassPath }
+
+trait Categories {
+  self: Universe =>
+  
+  trait TestCategory extends AbsTestCategory {
+    def kind: String
+    def startMessage: String = "Executing test group"
+    def testSequence: TestSequence
+
+    class TestSettings(entity: TestEntity, error: String => Unit) extends Settings(error) {
+      def this(entity: TestEntity) = this(entity, Console println _)
+      
+      deprecation.value   = false
+      encoding.value      = "ISO-8859-1"
+      classpath.value     = entity.testClasspath
+      outdir.value        = entity.outDir.path
+    }
+
+    def createSettings(entity: TestEntity): TestSettings = new TestSettings(entity)
+    def createTest(location: Path): TestEntity =
+      if (location.isFile) TestFile(this, location.toFile)
+      else if (location.isDirectory) TestDirectory(this, location.toDirectory)
+      else error("Failed to create test at '%s'" format location)
+    
+    /** Category test identification.
+     */
+    def denotesTestFile(p: Path)  = p.isFile && (p hasExtension "scala")
+    def denotesTestDir(p: Path)   = p.isDirectory && !ignorePath(p)
+    def denotesTest(p: Path)      = denotesTestDir(p) || denotesTestFile(p)
+    
+    /** This should verify that all necessary files are present.
+     *  By default it delegates to denotesTest.
+     */
+    def denotesValidTest(p: Path) = denotesTest(p)
+  }
+  
+  abstract class DirBasedCategory(val kind: String) extends TestCategory with CategoryContribution {
+    lazy val root = Directory(src / kind).normalize
+    def enumerate = root.list filter denotesTest map createTest toList
+    
+    /** Standard actions.  These can be overridden either on the
+     *  Category level or by individual tests.
+     */     
+    def compile: TestStep         = (_: TestEntity).compile()
+    def checkFileRequired: TestStep  = (_: TestEntity).checkFileRequired
+    def diff: TestStep            = (_: TestEntity).diff()
+    def run: TestStep             = (_: TestEntity).run()
+    def exec: TestStep            = (_: TestEntity).exec()
+    
+    /** Combinators.
+     */
+    def not(f: TestStep): TestStep = !f(_: TestEntity)
+    
+    override def toString = kind
+  }
+}
\ No newline at end of file
diff --git a/src/partest-alternative/scala/tools/partest/Compilable.scala b/src/partest-alternative/scala/tools/partest/Compilable.scala
new file mode 100644
index 0000000..48a4adc
--- /dev/null
+++ b/src/partest-alternative/scala/tools/partest/Compilable.scala
@@ -0,0 +1,106 @@
+/* NEST (New Scala Test)
+ * Copyright 2007-2010 LAMP/EPFL
+ */
+
+package scala.tools
+package partest
+
+import scala.tools.nsc.io._
+import scala.tools.nsc.{ Global, Settings, CompilerCommand, FatalError }
+import scala.tools.nsc.util.{ ClassPath }
+import scala.tools.nsc.reporters.{ Reporter, ConsoleReporter }
+
+trait PartestCompilation {
+  self: Universe =>
+  
+  trait CompileExecSupport extends ExecSupport {
+    self: TestEntity =>
+  
+    def javacpArg   = "-classpath " + testClasspath
+    def scalacpArg  = "-usejavacp"
+
+    /** Not used, requires tools.jar.
+     */
+    // def javacInternal(args: List[String]) = {
+    //   import com.sun.tools.javac.Main
+    //   Main.compile(args.toArray, logWriter)
+    // }
+
+    def javac(args: List[String]): Boolean = {
+      val allArgString = fromArgs(javacpArg :: javacOpts :: args)
+      
+      // javac -d outdir -classpath <basepath> <files>
+      val cmd = "%s -d %s %s".format(javacCmd, outDir, allArgString)
+      def traceMsg =
+        if (isVerbose) cmd
+        else "%s -d %s %s".format(tracePath(Path(javacCmd)), tracePath(outDir), fromArgs(args))
+  
+      trace(traceMsg)
+
+      isDryRun || execAndLog(cmd)
+    }
+    
+    def scalac(args: List[String]): Boolean = {
+      val allArgs = assembleScalacArgs(args)      
+      val (global, files) = newGlobal(allArgs)
+      def nonFileArgs = if (isVerbose) global.settings.recreateArgs else assembleScalacArgs(Nil)
+      def traceArgs   = fromArgs(nonFileArgs ++ (files map tracePath))
+      def traceMsg    = "scalac " + traceArgs
+    
+      trace(traceMsg)
+      isDryRun || global.partestCompile(files, true)
+    }
+      
+    /** Actually running the test, post compilation.
+     *  Normally args will be List("Test", "jvm"), main class and arg to it.
+     */
+    def runScala(args: List[String]): Boolean = {
+      val scalaRunnerClass = "scala.tools.nsc.MainGenericRunner"
+
+      // java $JAVA_OPTS <javaopts> -classpath <cp>
+      val javaCmdAndOptions = javaCmd +: assembleJavaArgs(List(javacpArg))
+      // MainGenericRunner -usejavacp <scalacopts> Test jvm
+      val scalaCmdAndOptions = List(scalaRunnerClass, scalacpArg) ++ assembleScalacArgs(args)
+      // Assembled
+      val cmd = fromArgs(javaCmdAndOptions ++ createPropertyString() ++ scalaCmdAndOptions)
+      
+      def traceMsg = if (isVerbose) cmd else fromArgs(javaCmd :: args)
+      trace("runScala: " + traceMsg)
+    
+      isDryRun || execAndLog(cmd)
+    }
+    
+    def newReporter(settings: Settings) = new ConsoleReporter(settings, Console.in, logWriter)
+
+    class PartestGlobal(settings: Settings, val creporter: ConsoleReporter) extends Global(settings, creporter) {    
+      def partestCompile(files: List[String], printSummary: Boolean): Boolean = {
+        try   { new Run compile files }
+        catch {
+          case FatalError(msg)    => creporter.error(null, "fatal error: " + msg)
+          case ae: AssertionError => creporter.error(null, ""+ae)
+          case te: TypeError      => creporter.error(null, ""+te)
+          case ex                 =>
+            creporter.error(null, ""+ex)
+            throw ex
+        }
+
+        if (printSummary)
+          creporter.printSummary
+        
+        creporter.flush()
+        !creporter.hasErrors
+      }
+    }
+    
+    def newGlobal(args: List[String]): (PartestGlobal, List[String]) = {
+      val settings  = category createSettings self
+      val command   = new CompilerCommand(args, settings)
+      val reporter  = newReporter(settings)
+    
+      if (!command.ok)
+        debug("Error parsing arguments: '%s'".format(args mkString ", "))
+    
+      (new PartestGlobal(command.settings, reporter), command.files)
+    }
+  }
+}
diff --git a/src/partest-alternative/scala/tools/partest/Config.scala b/src/partest-alternative/scala/tools/partest/Config.scala
new file mode 100644
index 0000000..e0d5eaf
--- /dev/null
+++ b/src/partest-alternative/scala/tools/partest/Config.scala
@@ -0,0 +1,129 @@
+/* NEST (New Scala Test)
+ * Copyright 2007-2010 LAMP/EPFL
+ */
+
+package scala.tools
+package partest
+
+import io._
+import nsc.io._
+import Properties._
+
+trait Config {
+  universe: Universe =>
+  
+  lazy val src    = absolutize(srcDir).toDirectory
+  lazy val build  = new TestBuild()
+
+  def javaHomeEnv = envOrElse("JAVA_HOME", null)
+  def javaCmd     = envOrElse("JAVACMD", "java")
+  def javacCmd    = Option(javaHomeEnv) map (x => Path(x) / "bin" / "javac" path) getOrElse "javac"
+  
+  /** Values related to actors.  The timeouts are in seconds.  On a dry
+   *  run we only allocate one worker so the output isn't interspersed.
+   */
+  def workerTimeout   = 3600                                          // 1 hour, probably overly generous
+  def numWorkers      = if (isDryRun) 1 else propOrElse("partest.actors", "8").toInt
+  def expectedErrors  = propOrElse("partest.errors", "0").toInt
+  def poolSize        = (wrapAccessControl(propOrNone("actors.corePoolSize")) getOrElse "16").toInt
+  
+  def allScalaFiles = src.deepFiles filter (_ hasExtension "scala")
+  def allObjDirs    = src.deepDirs  filter (_ hasExtension "obj")
+  def allLogFiles   = src.deepFiles filter (_ hasExtension "log")
+  def allClassFiles = src.deepFiles filter (_ hasExtension "class")
+  
+  class TestBuild() extends BuildContribution {
+    import nsc.util.ClassPath
+
+    /** Scala core libs.
+     */
+    val library       = pathForComponent("library")
+    val compiler      = pathForComponent("compiler")
+    val partest       = pathForComponent("partest")
+    val scalap        = pathForComponent("scalap", "%s.jar")
+
+    /** Scala supplementary libs - these are not all needed for all build targets,
+     *  and some of them are copied inside other jars in later targets.  However quick
+     *  for instance cannot be run without some of these.
+     */
+    val fjbg          = pathForLibrary("fjbg")
+    val msil          = pathForLibrary("msil")
+    val forkjoin      = pathForLibrary("forkjoin")
+    val scalacheck    = pathForLibrary("scalacheck")
+    
+    /** Other interesting paths.
+     */
+    val scalaBin      = testBuildDir / "bin"
+    
+    /** A hack for now to get quick running.
+     */
+    def needsForkJoin = {
+      val loader    = nsc.util.ScalaClassLoader.fromURLs(List(library.toURL))
+      val fjMarker  = "scala.concurrent.forkjoin.ForkJoinTask"
+      val clazz     = loader.tryToLoadClass(fjMarker)
+      
+      if (clazz.isDefined) debug("Loaded ForkJoinTask OK, don't need jar.")
+      else debug("Could not load ForkJoinTask, putting jar on classpath.")
+      
+      clazz.isEmpty
+    }
+    lazy val forkJoinPath: List[Path] = if (needsForkJoin) List(forkjoin) else Nil
+    
+    /** Internal **/
+    private def repo  = partestDir.parent.normalize
+    // XXX - is this needed? Where?
+    //
+    // private val pluginOptionString = "-Xplugin:"
+    // private def updatedPluginPath(options: String): String = {
+    //   val (pluginArgs, rest) = toArgs(options) partition (_ startsWith pluginOptionString)
+    //   // join all plugin paths as one classpath
+    //   val pluginPaths = ClassPath.join(pluginArgs map (_ stripPrefix pluginOptionString): _*)
+    //   // map all paths to absolute
+    //   val newPath = ClassPath.map(pluginPaths, x => absolutize(x).path)
+    //   // recreate option
+    //   val pluginOption = if (newPath == "") None else Some(pluginOptionString + newPath)
+    // 
+    //   fromArgs(rest ::: pluginOption.toList)
+    // }
+    
+    private def pathForComponent(what: String, jarFormat: String = "scala-%s.jar"): Path = {
+      def asDir = testBuildDir / "classes" / what
+      def asJar = testBuildDir / "lib" / jarFormat.format(what)
+
+      if (asDir.isDirectory) asDir
+      else if (asJar.isFile) asJar
+      else ""
+    }
+    private def pathForLibrary(what: String) = File(repo / "lib" / (what + ".jar"))
+  }
+  
+  def printConfigBanner() = {
+    debug("Java VM started with arguments: '%s'" format fromArgs(Process.javaVmArguments))
+    debug("System Properties:\n" + util.allPropertiesString())
+    
+    normal(configBanner())
+  }
+
+  /** Treat an access control failure as None. */
+  private def wrapAccessControl[T](body: => Option[T]): Option[T] =
+    try body catch { case _: java.security.AccessControlException => None }
+
+  private def configBanner() = {
+    val javaBin  = Path(javaHome) / "bin"
+    val javaInfoString = "%s (build %s, %s)".format(javaVmName, javaVmVersion, javaVmInfo)
+
+    List(
+      "Scala compiler classes in: " + testBuildDir,
+      "Scala version is:          " + nsc.Properties.versionMsg,
+      "Scalac options are:        " + universe.scalacOpts,
+      "Java binaries in:          " + javaBin,
+      "Java runtime is:           " + javaInfoString,
+      "Java runtime options:      " + (Process.javaVmArguments mkString " "),
+      "Javac options are:         " + universe.javacOpts,
+      "Java options are:          " + universe.javaOpts,
+      "Source directory is:       " + src,
+      "Selected categories:       " + (selectedCategories mkString " "),
+      ""
+    ) mkString "\n"
+  }
+}
diff --git a/src/partest-alternative/scala/tools/partest/Dispatcher.scala b/src/partest-alternative/scala/tools/partest/Dispatcher.scala
new file mode 100644
index 0000000..ba0f231
--- /dev/null
+++ b/src/partest-alternative/scala/tools/partest/Dispatcher.scala
@@ -0,0 +1,162 @@
+/* NEST (New Scala Test)
+ * Copyright 2007-2010 LAMP/EPFL
+ * @author Philipp Haller
+ */
+
+package scala.tools
+package partest
+
+import scala.tools.nsc.io._
+import scala.actors.{ Actor, TIMEOUT }
+import scala.actors.Actor._
+import scala.collection.immutable
+import scala.util.control.Exception.ultimately
+
+/** The machinery for concurrent execution of tests.  Each Worker
+ *  is given a bundle of tests, which it runs sequentially and then
+ *  sends a report back to the dispatcher.
+ */
+trait Dispatcher {
+  partest: Universe =>
+  
+  /** The public entry point.  The given filter narrows down the list of
+   *  tests to run.
+   */
+  def runSelection(categories: List[TestCategory], filt: TestEntity => Boolean = _ => true): CombinedTestResults = {
+    // Setting scala.home informs tests where to obtain their jars.
+    setProp("scala.home", testBuildDir.path)
+    
+    val allTests  = allCategories flatMap (_.enumerate)
+    val selected  = allTests filter filt
+    val groups    = selected groupBy (_.category)
+    val count     = selected.size
+    
+    if (count == 0) return CombinedTestResults(0, 0, 0, Nil)
+    else if (count == allTests.size) verbose("Running all %d tests." format count)
+    else verbose("Running %d/%d tests: %s".format(count, allTests.size, toStringTrunc(selected map (_.label) mkString ", ")))
+
+    allCategories collect { case x if groups contains x => runCategory(x, groups(x)) } reduceLeft (_ ++ _)
+  }
+  
+  private def parallelizeTests(tests: List[TestEntity]): immutable.Map[TestEntity, TestResult] = {
+    // propagate verbosity
+    if (isDebug) scala.actors.Debug.level = 3
+
+    // "If elected, I guarantee a slice of tests for every worker!"
+    val groups = tests grouped ((tests.size / numWorkers) + 1) toList
+
+    // "Workers, line up for assignments!"
+    val workers =
+      for ((slice, workerNum) <- groups.zipWithIndex) yield {
+        returning(new Worker(workerNum)) { worker =>
+          worker.start()
+          worker ! TestsToRun(slice)
+        }
+      }
+
+    normal("Started %d workers with ~%d tests each.\n".format(groups.size, groups.head.size))
+
+    /** Listening for news from the proletariat.
+     */
+    (workers map { w =>
+      receiveWithin(workerTimeout * 1000) {
+        case ResultsOfRun(resultMap)  => resultMap
+        case TIMEOUT                  =>
+          warning("Worker %d timed out." format w.workerNum)
+          // mark all the worker's tests as having timed out - should be hard to miss
+          // immutable.Map[TestEntity, TestResult]()
+          groups(w.workerNum) map (x => (x -> new Timeout(x))) toMap
+      }
+    }) reduceLeft (_ ++ _)
+  }
+
+  private def runCategory(category: TestCategory, tests: List[TestEntity]): CombinedTestResults = {
+    val kind = category.kind
+    normal("%s (%s tests in %s)\n".format(category.startMessage, tests.size, category))
+    
+    val (milliSeconds, resultMap) = timed2(parallelizeTests(tests))
+    val (passed, failed)          = resultsToStatistics(resultMap mapValues (_.state))
+    val failures                  = resultMap.values filterNot (_.passed) toList
+
+    CombinedTestResults(passed, failed, milliSeconds, failures)
+  }
+
+  /** A Worker is given a bundle of tests and runs them all sequentially.
+   */
+  class Worker(val workerNum: Int) extends Actor {    
+    def act() {
+      react { case TestsToRun(tests) =>
+        val master = sender
+        runTests(tests)(results => master ! ResultsOfRun(results))
+      }
+    }
+
+    /** Runs the tests.  Passes the result Map to onCompletion when done.
+     */
+    private def runTests(tests: List[TestEntity])(onCompletion: immutable.Map[TestEntity, TestResult] => Unit) {
+      var results       = new immutable.HashMap[TestEntity, TestResult] // maps tests to results
+      val numberOfTests = tests.size
+      val testIterator  = tests.iterator
+      def processed     = results.size
+      def isComplete    = testIterator.isEmpty
+      
+      def atThreshold(num: Double) = {
+        require(num >= 0 && num <= 1.0)
+        ((processed - 1).toDouble / numberOfTests <= num) && (processed.toDouble / numberOfTests >= num)
+      }
+      
+      def extraMessage = {
+        // for now quiet for normal people
+        if (isVerbose || isTrace || isDebug) {
+          if (isComplete) "(#%d 100%%)" format workerNum
+          else if (isVerbose) "(#%d %d/%d)".format(workerNum, processed, numberOfTests)
+          else if (isTrace && atThreshold(0.5)) "(#%d 50%%)" format workerNum
+          else ""
+        }
+        else ""
+      }
+      
+      def countAndReport(result: TestResult) {
+        val TestResult(test, state) = result
+        // refuse to count an entity twice
+        if (results contains test)
+          return warning("Received duplicate result for %s: was %s, now %s".format(test, results(test), state))
+          
+        // increment the counter for this result state
+        results += (test -> result)
+
+        // show on screen
+        if (isDryRun) normal("\n")   // blank line between dry run traces
+        else result show extraMessage
+
+        // remove log if successful
+        if (result.passed)
+          test.deleteLog()
+
+        // Respond to master if this Worker is complete
+        if (isComplete)
+          onCompletion(results)        
+      }
+      
+      Actor.loopWhile(testIterator.hasNext) {
+        val parent = self        
+        // pick a test and set some alarms
+        val test    = testIterator.next
+        val alarmer = test startAlarms (parent ! new Timeout(test))
+
+        actor {
+          ultimately(alarmer.cancelAll()) {
+            // Calling isSuccess forces the lazy val "process" inside the test, running it.
+            val res = test.isSuccess
+            // Cancel the alarms and alert the media.
+            parent ! TestResult(test, res)
+          }
+        }
+
+        react {
+          case x: TestResult  => countAndReport(x)
+        }
+      }
+    }
+  }
+}
\ No newline at end of file
diff --git a/src/partest-alternative/scala/tools/partest/Entities.scala b/src/partest-alternative/scala/tools/partest/Entities.scala
new file mode 100644
index 0000000..6bae604
--- /dev/null
+++ b/src/partest-alternative/scala/tools/partest/Entities.scala
@@ -0,0 +1,74 @@
+/* NEST (New Scala Test)
+ * Copyright 2007-2010 LAMP/EPFL
+ * @author Philipp Haller
+ */
+
+package scala.tools
+package partest
+
+import nsc.io._
+
+trait Entities {
+  self: Universe =>
+
+  abstract class TestEntity extends AbsTestEntity
+                               with TestContribution
+                               with TestHousekeeping
+                               with TestAlarms
+                               with EntityLogging
+                               with CompilableTest
+                               with ScriptableTest
+                               with DiffableTest {
+    def location: Path
+    def category: TestCategory
+    
+    lazy val label          = location.stripExtension
+    lazy val testClasspath  = returning(createClasspathString())(x => vtrace("testClasspath: " + x))
+    
+    /** Was this test successful? Calling this for the first time forces
+     *  lazy val "process" which actually runs the test.
+     */
+    def isSuccess = process
+    
+    /** Some standard files, which may or may not be present.
+     */
+    def scalaOptsFile = withExtension("flags").toFile     // opts to scalac
+    def javaOptsFile  = withExtension("javaopts").toFile  // opts to java (but not javac)
+    def commandFile   = withExtension("cmds").toFile      // sequence of commands to execute
+    def logFile       = withExtension("log").toFile       // collected output
+    
+    /** Some standard directories.
+     */
+    def outDir        = withExtension("obj").toDirectory  // output dir, e.g. files/pos/t14.obj
+    def categoryDir   = location.parent.normalize         // category dir, e.g. files/pos/
+    def sourcesDir    = location ifDirectory (_.normalize) getOrElse categoryDir
+    
+    /** Standard arguments for run, exec, diff.
+     */
+    def argumentsToRun  = List("Test", "jvm")
+    def argumentsToExec = List(location.path)
+
+    /** Using a .cmds file for a custom test sequence.
+     */
+    def commandList   = safeLines(commandFile) 
+    def testSequence  =
+      if (commandFile.isFile && commandList.nonEmpty) commandList map customTestStep
+      else category.testSequence
+    
+    def run()   = runScala(argumentsToRun)
+    def exec()  = runExec(argumentsToExec)
+    def diff()  = runDiff() // checkFile, logFile
+
+    /** The memoized result of the test run.
+     */
+    private lazy val process = {
+      val outcome   = runWrappers(testSequence.actions forall (f => f(this)))
+      
+      // an empty outcome means we've been interrupted and are shutting down.
+      outcome getOrElse false
+    }
+  }
+
+  case class TestDirectory(category: TestCategory, location: Directory) extends TestEntity { }
+  case class TestFile(category: TestCategory, location: File) extends TestEntity { }
+}
diff --git a/src/partest-alternative/scala/tools/partest/Housekeeping.scala b/src/partest-alternative/scala/tools/partest/Housekeeping.scala
new file mode 100644
index 0000000..80f1171
--- /dev/null
+++ b/src/partest-alternative/scala/tools/partest/Housekeeping.scala
@@ -0,0 +1,187 @@
+/* NEST (New Scala Test)
+ * Copyright 2007-2010 LAMP/EPFL
+ */
+
+package scala.tools
+package partest
+
+import scala.util.control.Exception.catching
+import util._
+import nsc.io._
+import Process.runtime
+import Properties._
+
+/** An agglomeration of code which is low on thrills.  Hopefully
+ *  it operates so quietly in the background that you never have to
+ *  look at this file.
+ */
+trait Housekeeping {
+  self: Universe =>
+
+  /** Orderly shutdown on ctrl-C. */
+  @volatile private var _shuttingDown = false
+  protected def setShuttingDown() = {
+    /** Whatever we want to do as shutdown begins goes here. */
+    if (!_shuttingDown) {
+      warning("Received shutdown signal, partest is cleaning up...\n")
+      _shuttingDown = true
+    }
+  }
+  def isShuttingDown = _shuttingDown
+  
+  /** Execute some code with a shutdown hook in place.  This is
+   *  motivated by the desire not to leave the filesystem full of
+   *  junk when someone ctrl-Cs a test run.
+   */
+  def withShutdownHook[T](hook: => Unit)(body: => T): Option[T] =
+    /** Java doesn't like it if you keep adding and removing shutdown
+     *  hooks after shutdown has begun, so we trap the failure.
+     */
+    catching(classOf[IllegalStateException]) opt {
+      val t = new Thread() { 
+        override def run() = {
+          setShuttingDown()
+          hook 
+        }
+      }
+      runtime addShutdownHook t
+      
+      try body
+      finally runtime removeShutdownHook t
+    }
+
+  /** Search for a directory, possibly given only a name, by starting
+   *  at the current dir and walking upward looking for it at each level.
+   */
+  protected def searchForDir(name: String): Directory = {
+    val result = Path(name) ifDirectory (x => x.normalize) orElse {    
+      val cwd = Directory.Current getOrElse error("user.dir property not set")
+      val dirs = cwd :: cwd.parents map (_ / name)
+    
+      Path onlyDirs dirs map (_.normalize) headOption
+    }
+    
+    result getOrElse error("Fatal: could not find directory '%s'" format name)
+  }
+  
+  /** Paths we ignore for most purposes.
+   */
+  def ignorePath(x: Path) = {
+    (x.name startsWith ".") ||
+    (x.isDirectory && ((x.name == "lib") || x.hasExtension("obj", "svn")))
+  }
+  /** Make a possibly relative path absolute using partestDir as the base.
+   */
+  def absolutize(path: String) = Path(path) toAbsoluteWithRoot partestDir
+  
+  /** Go on a deleting binge.
+   */
+  def cleanupAll() {
+    if (isNoCleanup)
+      return
+      
+    val (dirCount, fileCount) = (cleanupObjDirs(), cleanupLogs() + cleanupJunk())
+    if (dirCount + fileCount > 0)
+      normal("Cleaned up %d directories and %d files.\n".format(dirCount, fileCount))
+  }
+
+  def cleanupObjDirs()  = countTrue(allObjDirs collect { case x if x.exists => x.deleteRecursively() })
+  def cleanupJunk()     = countTrue(allClassFiles collect { case x if x.exists => x.delete() })
+  def cleanupLogs()     = countTrue(allLogFiles collect { case x if x.exists => x.delete() })
+  
+  /** Look through every file in the partest directory and ask around
+   *  to make sure someone knows him.  Complain about strangers.
+   */
+  def validateAll() {
+    def denotesTest(p: Path)  = allCategories exists (_ denotesTest p)
+    def isMSILcheck(p: Path)  = p.name endsWith "-msil.check"
+    
+    def analyzeCategory(cat: DirBasedCategory) = {
+      val allTests    = cat.enumerate
+      val otherPaths  = cat.root walkFilter (x => !ignorePath(x)) filterNot (cat denotesTest _) filterNot isMSILcheck toList
+      val count       = otherPaths.size
+      
+      println("Validating %d non-test paths in %s.".format(count, cat.kind))
+      
+      for (path <- otherPaths) {
+        (allTests find (_ acknowledges path)) match {
+          case Some(test)   => if (isVerbose) println("  OK: '%s' is claimed by '%s'".format(path, test.label))
+          case _            => println(">> Unknown path '%s'" format path)
+        }
+      }
+    }
+    
+    allCategories collect { case x: DirBasedCategory => analyzeCategory(x) }
+  }
+  
+  trait TestHousekeeping {
+    self: TestEntity =>
+
+    /** Calculating derived files.  Given a test like
+     *    files/run/foo.scala  or  files/run/foo/ 
+     *  This creates paths like foo.check, foo.flags, etc.
+     */
+    def withExtension(extension: String) = categoryDir / "%s.%s".format(label, extension)
+
+    /** True for a path if this test acknowledges it belongs to this test.
+     *  Overridden by some categories.
+     */
+    def acknowledges(path: Path): Boolean = {
+      val loc = location.normalize
+      val knownPaths = List(scalaOptsFile, javaOptsFile, commandFile, logFile, checkFile) ++ jarsInTestDir
+      def isContainedSource = location.isDirectory && isJavaOrScala(path) && (path.normalize startsWith loc)
+      
+      (knownPaths exists (_ isSame path)) || isContainedSource
+    }
+    
+    /** This test "responds to" this String.  This could mean anything -- it's a
+     *  way of specifying ad-hoc collections of tests to exercise only a subset of tests.
+     *  At present it looks for the given String in all the test sources.
+     */
+    def respondsToString(str: String) = containsString(str)
+    def containsString(str: String)   = {
+      debug("Checking %s for \"%s\"".format(sourceFiles mkString ", ", str))
+      sourceFiles map safeSlurp exists (_ contains str)
+    }
+    
+    def possiblyTimed[T](body: => T): T = {
+      if (isStats) timed(recordTestTiming(label, _))(body)
+      else body
+    }
+    
+    private def prepareForTestRun() = {
+      // make sure we have a clean slate
+      deleteLog(force = true)
+      if (outDir.exists)
+        outDir.deleteRecursively()
+      
+      // recreate object dir
+      outDir createDirectory true
+    }
+    def deleteOutDir() = outDir.deleteRecursively()
+    def deleteShutdownHook() = { debug("Shutdown hook deleting " + outDir) ; deleteOutDir() }
+    
+    protected def runWrappers[T](body: => T): Option[T] = {
+      prepareForTestRun()
+
+      withShutdownHook(deleteShutdownHook()) {
+        loggingOutAndErr {
+          val result = possiblyTimed { body }
+          if (!isNoCleanup)
+            deleteOutDir()
+
+          result
+        }
+      }
+    }
+    
+    override def toString = location.path
+    override def equals(other: Any) = other match {
+      case x: TestEntity  => location.normalize == x.location.normalize
+      case _              => false
+    }
+    override def hashCode = location.normalize.hashCode
+  }
+
+  private def countTrue(f: => Iterator[Boolean]) = f filter (_ == true) length
+}
\ No newline at end of file
diff --git a/src/partest-alternative/scala/tools/partest/Partest.scala b/src/partest-alternative/scala/tools/partest/Partest.scala
new file mode 100644
index 0000000..b0ce12e
--- /dev/null
+++ b/src/partest-alternative/scala/tools/partest/Partest.scala
@@ -0,0 +1,81 @@
+/* NEST (New Scala Test)
+ * Copyright 2007-2010 LAMP/EPFL
+ */
+
+package scala.tools
+package partest
+
+import nsc.io._
+import nsc.util._
+import category.AllCategories
+
+/** Global object for a Partest run.  It is completely configured by the list
+ *  of arguments passed to the constructor (although there are a few properties
+ *  and environment variables which can influence matters.) See PartestSpec.scala
+ *  for the complete list.
+ */
+class Partest(args: List[String]) extends {
+  val parsed = PartestSpec(args: _*)
+} with Universe with PartestSpec with cmd.Instance with AllCategories {
+  
+  if (parsed.propertyArgs.nonEmpty)
+    debug("Partest property args: " + fromArgs(parsed.propertyArgs))
+    
+  debug("Partest created with args: " + fromArgs(args))
+  
+  def helpMsg     = PartestSpec.helpMsg
+
+  // The abstract values from Universe.
+  lazy val testBuildDir   = searchForDir(buildDir)
+  lazy val partestDir     = searchForDir(rootDir)
+  lazy val allCategories  = List(Pos, Neg, Run, Jvm, Res, Shootout, Scalap, Scalacheck, BuildManager, Script)
+  lazy val selectedCategories = if (isAllImplied) allCategories else specifiedCats
+
+  def specifiedTests  = parsed.residualArgs map (x => Path(x).normalize)
+  def specifiedKinds  = testKinds filter (x => isSet(x) || (runSets contains x))
+  def specifiedCats   = specifiedKinds flatMap (x => allCategories find (_.kind == x))
+  def isAllImplied    = isAll || (specifiedTests.isEmpty && specifiedKinds.isEmpty)
+  
+  /** Assembles a filter based on command line options which restrict the test set
+   *  --grep limits to only matching tests
+   *  --failed limits to only recently failed tests (log file is present)
+   *  --<category> limits to only the given tests and categories (but --all overrides)
+   *  path/to/Test limits to only the given tests and categories
+   */
+  lazy val filter = {    
+    def indivFilter(test: TestEntity)     = specifiedTests contains test.location.normalize
+    def categoryFilter(test: TestEntity)  = specifiedCats contains test.category
+    def indivOrCat(test: TestEntity)      = isAllImplied || indivFilter(test) || categoryFilter(test)  // combines previous two
+    
+    def failedFilter(test: TestEntity)    = !isFailed || (test.logFile exists)
+    def grepFilter(test: TestEntity)      = grepExpr.isEmpty || (test containsString grepExpr.get)
+    def combinedFilter(x: TestEntity)     = indivOrCat(x) && failedFilter(x) && grepFilter(x)   // combines previous three
+    
+    combinedFilter _
+  }
+    
+  def launchTestSuite() = {
+    def onTimeout() = {
+      warning("Partest test run timed out after " + timeout + " seconds.\n")
+      System.exit(-1)
+    }
+    val alarm = new Alarmer(AlarmerAction(timeout, () => onTimeout()))
+    
+    try runSelection(selectedCategories, filter)
+    finally alarm.cancelAll()
+  }
+}
+
+object Partest {  
+  def fromBuild(dir: String, args: String*): Partest      = apply("--builddir" +: dir +: args: _*)
+  def apply(args: String*): Partest                       = new Partest(args.toList)
+  
+  // builds without partest jars won't actually work
+  def starr()   = fromBuild("")
+  def locker()  = fromBuild("build/locker")
+  def quick()   = fromBuild("build/quick")
+  def pack()    = fromBuild("build/pack")
+  def strap()   = fromBuild("build/strap")
+  def dist()    = fromBuild("dists/latest")
+}
+
diff --git a/src/partest-alternative/scala/tools/partest/PartestSpec.scala b/src/partest-alternative/scala/tools/partest/PartestSpec.scala
new file mode 100644
index 0000000..81efb49
--- /dev/null
+++ b/src/partest-alternative/scala/tools/partest/PartestSpec.scala
@@ -0,0 +1,104 @@
+/* NEST (New Scala Test)
+ * Copyright 2007-2010 LAMP/EPFL
+ * @author  Paul Phillips
+ */
+
+package scala.tools
+package partest
+
+import nsc.io._
+import cmd._
+
+/** This takes advantage of bits of scala goodness to fully define a command
+ *  line program with a minimum of duplicated code.  When the specification object
+ *  is created, the vals are evaluated in order and each of them side effects
+ *  a private accumulator.  What emerges is a full list of the valid unary
+ *  and binary arguments, as well as autogenerated help.
+ */
+trait PartestSpec extends Spec with Meta.StdOpts with Interpolation {
+  def referenceSpec       = PartestSpec
+  def programInfo         = Spec.Info("partest", "", "scala.tools.partest.Runner")
+  private val kind        = new Spec.Accumulator[String]()
+  protected def testKinds = kind.get
+  
+  private implicit val tokenizeString = FromString.ArgumentsFromString    // String => List[String]
+  
+  help("""
+    |# Pro Tip! Instant bash completion: `partest --bash` (note backticks)
+    |Usage: partest [<options>] [<test> <test> ...]
+    |  <test>: a path to a test designator, typically a .scala file or a directory.
+    |          Examples: files/pos/test1.scala, files/res/bug785
+    |
+    |  Test categories:""".stripMargin)
+
+  val isAll         = ("all"                / "run all tests (default, unless no options given)" --?)
+                      (kind("pos")          / "Compile files that are expected to build" --?)
+                      (kind("neg")          / "Compile files that are expected to fail" --?)
+                      (kind("run")          / "Test JVM backend" --?)
+                      (kind("jvm")          / "Test JVM backend" --?)
+                      (kind("res")          / "Run resident compiler scenarii" --?)
+                      (kind("buildmanager") / "Run Build Manager scenarii" --?)
+                      (kind("scalacheck")   / "Run Scalacheck tests" --?)
+                      (kind("script")       / "Run script files" --?)
+                      (kind("shootout")     / "Run shootout tests" --?)
+                      (kind("scalap")       / "Run scalap tests" --?)
+
+  heading             ("""Test "smart" categories:""")
+  val grepExpr      = "grep"        / "run all tests with a source file containing <expr>"    --|
+  val isFailed      = "failed"      / "run all tests which failed on the last run"            --?
+  
+  heading             ("Specifying paths and additional flags, ~ means repository root:")
+
+  val rootDir       = "rootdir"     / "path from ~ to partest"                        defaultTo "test"
+  val buildDir      = "builddir"    / "path from ~ to test build"                     defaultTo "build/pack"
+  val srcDir        = "srcdir"      / "path from --rootdir to sources"                defaultTo "files"
+  val javaOpts      = "javaopts"    / "flags to java on all runs"                  defaultToEnv "JAVA_OPTS"
+  val javacOpts     = "javacopts"   / "flags to javac on all runs"                 defaultToEnv "JAVAC_OPTS"
+  val scalacOpts    = "scalacopts"  / "flags to scalac on all tests"               defaultToEnv "SCALAC_OPTS"
+  
+                      "pack"        / ""                                               expandTo ("--builddir", "build/pack")
+                      "quick"       / ""                                               expandTo ("--builddir", "build/quick")
+  
+  heading             ("Options influencing output:")
+  val isTrace       = "trace"       / "show the individual steps taken by each test" --?
+  val isShowDiff    = "show-diff"   / "show diff between log and check file"  --?
+  val isShowLog     = "show-log"    / "show log on failures" --?
+  val isDryRun      = "dry-run"     / "do not run tests, only show their traces." --?
+  val isTerse       = "terse"       / "be less verbose (almost silent except for failures)" --?
+  val isVerbose     = "verbose"     / "be more verbose (additive with --trace)" --?
+  val isDebug       = "debug"       / "maximum debugging output" --?
+  val isAnsi        = "ansi"        / "print output in color" --?
+  
+  heading             ("Other options:")
+  val timeout       = "timeout"       / "Overall timeout in seconds"                defaultTo 7200
+  val testWarning   = "test-warning"  / "Test warning in seconds"                   defaultTo 90
+  val testTimeout   = "test-timeout"  / "Test timeout in seconds"                   defaultTo 900
+  val isCleanup     = "cleanup"       / "delete all stale files and dirs before run" --?
+  val isNoCleanup   = "nocleanup"     / "do not delete any logfiles or object dirs" --?
+  val isStats       = "stats"         / "collect and print statistics about the tests" --?
+  val isValidate    = "validate"      / "examine test filesystem for inconsistencies" --?
+  val isUpdateCheck = "update-check"  / "overwrite checkFile if diff fails" --?
+  
+                      "version"       / "print version"   --> runAndExit(println(Properties.versionMsg))
+
+  // no help for anything below this line - secret options
+  // mostly intended for property configuration.
+  val runSets       = ("runsets"  --^) getOrElse Nil
+  val isNoAlarms    = "noalarms"  --?
+  val isInsideAnt   = "is-in-ant" --?
+}
+
+object PartestSpec extends PartestSpec with Property {
+  lazy val propMapper = new PropertyMapper(PartestSpec) {
+    override def isPassThrough(key: String) = key == "partest.options"
+  }
+  
+  type ThisCommandLine = PartestCommandLine
+  class PartestCommandLine(args: List[String]) extends SpecCommandLine(args) {
+    override def errorFn(msg: String) = printAndExit("Error: " + msg)
+    
+    def propertyArgs = PartestSpec.propertyArgs
+  }
+  
+  override def creator(args: List[String]): PartestCommandLine = new PartestCommandLine(args)
+}
diff --git a/src/partest-alternative/scala/tools/partest/Properties.scala b/src/partest-alternative/scala/tools/partest/Properties.scala
new file mode 100644
index 0000000..a1ad1e5
--- /dev/null
+++ b/src/partest-alternative/scala/tools/partest/Properties.scala
@@ -0,0 +1,17 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala Parallel Testing               **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+package scala.tools
+package partest
+
+/** Loads partest.properties from the jar. */
+object Properties extends scala.util.PropertiesTrait {
+  protected def propCategory    = "partest"
+  protected def pickJarBasedOn  = classOf[Application]
+}
diff --git a/src/partest-alternative/scala/tools/partest/Results.scala b/src/partest-alternative/scala/tools/partest/Results.scala
new file mode 100644
index 0000000..9bf9c53
--- /dev/null
+++ b/src/partest-alternative/scala/tools/partest/Results.scala
@@ -0,0 +1,121 @@
+/* NEST (New Scala Test)
+ * Copyright 2007-2010 LAMP/EPFL
+ */
+
+package scala.tools
+package partest
+
+import scala.collection.immutable
+
+trait Results {
+  self: Universe =>
+
+  /** A collection of tests for a Worker.
+   */
+  case class TestsToRun(entities: List[TestEntity])
+  
+  /** The response from a Worker who has been given TestsToRun.
+   */
+  case class ResultsOfRun(results: immutable.Map[TestEntity, TestResult])
+  
+  /** The result of a single test.  (0: OK, 1: FAILED, 2: TIMEOUT)
+   */
+  sealed abstract class TestResult(val state: Int, val description: String) {
+    def entity: TestEntity
+    
+    def passed = state == 0
+    def colorize(s: String): String
+    def show(msg: String) =
+      if (!isShuttingDown)
+        showResult(colorize(description), msg)
+
+    private def outputPrefix  = if (isInsideAnt) "" else markNormal("partest: ")
+    private def name          = src relativize entity.location   // e.g. "neg/test.scala"
+    private def showResult(status: String, extraMsg: String) =      
+      normal(outputPrefix + "[...]/%-40s [%s] %s\n".format(name, status, extraMsg))
+    
+    override def equals(other: Any) = other match {
+      case x: TestResult  => entity == x.entity
+      case _              => false
+    }
+    override def hashCode = entity.hashCode
+    override def toString = "%s [%s]".format(entity, description)
+  }
+
+  class Success(val entity: TestEntity) extends TestResult(0, "   OK   ") {
+    def colorize(s: String) = markSuccess(s)
+    override def show(msg: String) = if (!isTerse) super.show(msg)
+  }
+  class Failure(val entity: TestEntity) extends TestResult(1, " FAILED ") {
+    def colorize(s: String) = markFailure(s)
+    
+    override def show(msg: String) = {
+      super.show(msg)
+
+      if (isShowDiff || isTrace)
+        normal(entity.diffOutput)
+        
+      if (isShowLog || isTrace)
+        normal(toStringTrunc(entity.failureMessage(), 1600))
+    }
+    override def toString = List(super.toString, toStringTrunc(entity.failureMessage(), 400)) mkString "\n"
+  }
+  class Timeout(val entity: TestEntity) extends TestResult(2, "TIME OUT") {
+    def colorize(s: String) = markFailure(s)
+  }
+  
+  object TestResult {
+    def apply(entity: TestEntity, success: Boolean) =
+      if (success) new Success(entity)
+      else new Failure(entity)
+
+    def apply(entity: TestEntity, state: Int) = state match {
+      case 0  => new Success(entity)
+      case 1  => new Failure(entity)
+      case 2  => new Timeout(entity)
+    }
+    def unapply(x: Any) = x match {
+      case x: TestResult  => Some((x.entity, x.state))
+      case _              => None
+    }
+  } 
+  
+  /** The combined results of any number of tests.
+   */
+  case class CombinedTestResults(
+    passed: Int, 
+    failed: Int,
+    elapsedMilliseconds: Long,
+    failures: List[TestResult]
+  ) {
+    // housekeeping
+    val elapsedSecs = elapsedMilliseconds / 1000
+    val elapsedMins = elapsedSecs / 60
+    val elapsedHrs  = elapsedMins / 60
+    val dispMins = elapsedMins - elapsedHrs  * 60
+    val dispSecs = elapsedSecs - elapsedMins * 60
+    
+    def total       = passed + failed
+    def hasFailures = failed > 0
+    def exitCode    = if (expectedErrors == failed) 0 else 1
+    
+    def ++(x: CombinedTestResults) = CombinedTestResults(
+      passed + x.passed,
+      failed + x.failed,
+      elapsedMilliseconds + x.elapsedMilliseconds,
+      failures ::: x.failures
+    )
+    
+    def elapsedString   = "%02d:%02d:%02d".format(elapsedHrs, dispMins, dispSecs)
+    def failuresString  = {
+      if (failures.isEmpty) ""
+      else "Summary of failures:" :: failures mkString ("\n", "\n", "")
+    }
+    
+    override def toString =
+      if (total == 0) "There were no tests to run."
+      else if (isDryRun) "%d tests would be run." format total
+      else if (hasFailures) "%d of %d tests failed (elapsed time: %s)".format(failed, total, elapsedString) + failuresString
+      else "All %d tests were successful (elapsed time: %s)".format(total, elapsedString)
+  }
+}
\ No newline at end of file
diff --git a/src/partest-alternative/scala/tools/partest/Runner.scala b/src/partest-alternative/scala/tools/partest/Runner.scala
new file mode 100644
index 0000000..90bccac
--- /dev/null
+++ b/src/partest-alternative/scala/tools/partest/Runner.scala
@@ -0,0 +1,36 @@
+/* NEST (New Scala Test)
+ * Copyright 2007-2010 LAMP/EPFL
+ * @author Philipp Haller
+ */
+
+package scala.tools
+package partest
+
+import nsc.io._
+
+object Runner {
+  def main(args: Array[String]) {
+    val runner = Partest(args: _*)
+    import runner._
+
+    if (args.isEmpty) return println(helpMsg)
+    if (isValidate) return validateAll()
+    
+    printConfigBanner()
+
+    if (isCleanup)
+      cleanupAll()
+
+    val result    = launchTestSuite()
+    val exitCode  = result.exitCode
+    val message   = "\n" + result + "\n"
+  
+    if (exitCode == 0) success(message)
+    else failure(message)
+
+    if (isStats)
+      showTestStatistics()
+
+    System exit exitCode
+  }
+}
diff --git a/src/partest-alternative/scala/tools/partest/Statistics.scala b/src/partest-alternative/scala/tools/partest/Statistics.scala
new file mode 100644
index 0000000..13a045a
--- /dev/null
+++ b/src/partest-alternative/scala/tools/partest/Statistics.scala
@@ -0,0 +1,46 @@
+/* NEST (New Scala Test)
+ * Copyright 2007-2010 LAMP/EPFL
+ * @author Philipp Haller
+ */
+
+package scala.tools
+package partest
+
+import scala.collection.mutable.HashMap
+
+trait Statistics {  
+  /** Only collected when --stats is given. */
+  lazy val testStatistics = new HashMap[String, Long]
+
+  /** Given function and block of code, evaluates code block,
+   *  calls function with milliseconds elapsed, and returns block result.
+   */
+  def timed[T](f: Long => Unit)(body: => T): T = {
+    val start = System.currentTimeMillis
+    val result = body
+    val end = System.currentTimeMillis
+    
+    f(end - start)
+    result
+  }
+  /** Times body and returns both values.
+   */
+  def timed2[T](body: => T): (Long, T) = {
+    var milliSeconds = 0L
+    val result = timed(x => milliSeconds = x)(body)
+    
+    (milliSeconds, result)
+  }
+  
+  def resultsToStatistics(results: Iterable[(_, Int)]): (Int, Int) =
+    (results partition (_._2 == 0)) match { 
+      case (winners, losers) => (winners.size, losers.size)
+    }
+
+  def recordTestTiming(name: String, milliseconds: Long) =
+    synchronized { testStatistics(name) = milliseconds }
+
+  def showTestStatistics() {
+    testStatistics.toList sortBy (-_._2) foreach { case (k, v) => println("%s: %.2f seconds".format(k, (v.toDouble / 1000))) }
+  }
+}
diff --git a/src/partest-alternative/scala/tools/partest/Universe.scala b/src/partest-alternative/scala/tools/partest/Universe.scala
new file mode 100644
index 0000000..1e04b8a
--- /dev/null
+++ b/src/partest-alternative/scala/tools/partest/Universe.scala
@@ -0,0 +1,96 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala Parallel Testing               **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+package scala.tools
+package partest
+
+import nsc.io._
+import category.AllCategories
+import io.Logging
+
+/** The high level view of the partest infrastructure.
+ */
+abstract class Universe 
+      extends Entities
+      with BuildContributors
+      with Logging
+      with Dispatcher
+      with Statistics
+      with Housekeeping
+      with Results
+      with PartestCompilation
+      with PartestSpec
+      with Config
+      with Alarms
+      with Actions 
+      with Categories {
+
+  /** The abstract values from which all else is derived. */
+  def partestDir: Directory
+  def testBuildDir: Directory
+  def allCategories: List[TestCategory]
+  def selectedCategories: List[TestCategory]
+  
+  /** Some plausibly abstract types. */
+  type TestBuild    <: BuildContributor   // e.g. quick, pack
+  type TestCategory <: AbsTestCategory    // e.g. pos, neg, run
+  type TestEntity   <: AbsTestEntity      // e.g. files/pos/test25.scala
+  type TestSequence <: AbsTestSequence    // e.g. compile, run, diff
+
+  /** Although TestStep isn't much more than Function1 right now,
+   *  it exists this way so it can become more capable.
+   */
+  implicit def f1ToTestStep(f: TestEntity => Boolean): TestStep =
+    new TestStep { def apply(test: TestEntity) = f(test) }
+  
+  abstract class TestStep extends (TestEntity => Boolean) {    
+    def apply(test: TestEntity): Boolean
+  }
+
+  /** An umbrella category of tests, such as "pos" or "run".
+   */
+  trait AbsTestCategory extends BuildContributor {
+    type TestSettings
+    
+    def kind: String
+    def testSequence: TestSequence
+    def denotesTest(location: Path): Boolean
+    
+    def createTest(location: Path): TestEntity
+    def createSettings(entity: TestEntity): TestSettings
+    def enumerate: List[TestEntity]
+  }
+  
+  /** A single test.  It may involve multiple files, but only a 
+   *  single path is used to designate it.
+   */
+  trait AbsTestEntity extends BuildContributor {  
+    def category: TestCategory
+    def location: Path
+    def onException(x: Throwable): Unit
+    def testClasspath: String
+    
+    /** Most tests will use the sequence defined by the category,
+     *  but the test can override and define a custom sequence.
+     */
+    def testSequence: TestSequence
+    
+    /** True if this test recognizes the given path as a piece of it.
+     *  For validation purposes.
+     */
+    def acknowledges(path: Path): Boolean
+  }
+  
+  /** Every TestEntity is partly characterized by a series of actions
+   *  which are applied to the TestEntity in the given order.  The test
+   *  passes if all those actions return true, fails otherwise.
+   */
+  trait AbsTestSequence {
+    def actions: List[TestStep]
+  }
+}
\ No newline at end of file
diff --git a/src/partest-alternative/scala/tools/partest/ant/JavaTask.scala b/src/partest-alternative/scala/tools/partest/ant/JavaTask.scala
new file mode 100644
index 0000000..998d69a
--- /dev/null
+++ b/src/partest-alternative/scala/tools/partest/ant/JavaTask.scala
@@ -0,0 +1,57 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala Parallel Testing               **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+package scala.tools
+package partest
+package ant
+
+import org.apache.tools.ant.Task
+import org.apache.tools.ant.taskdefs.Java
+import org.apache.tools.ant.types.Environment
+
+import scala.tools.nsc.io._
+import scala.tools.nsc.util.ClassPath
+import cmd.Spec._
+
+class JavaTask extends Java {
+  override def getTaskName()      = "partest"
+  private val scalaRunnerClass    = "scala.tools.nsc.MainGenericRunner"  
+  private val partestRunnerClass  = "scala.tools.partest.Runner"
+  def defaultJvmArgs              = "-Xms64M -Xmx768M -Xss768K -XX:MaxPermSize=96M"
+
+  protected def rootDir           = prop("partest.rootdir") getOrElse (baseDir / "test").path
+  protected def partestJVMArgs    = prop("partest.jvm.args") getOrElse defaultJvmArgs
+  protected def runnerArgs        = List("-usejavacp", partestRunnerClass, "--javaopts", partestJVMArgs)
+
+  private def baseDir             = Directory(getProject.getBaseDir)
+  private def prop(s: String)     = Option(getProject getProperty s)
+  private def jvmline(s: String)  = returning(createJvmarg())(_ setLine s)
+  private def addArg(s: String)   = returning(createArg())(_ setValue s)
+  
+  private def newKeyValue(key: String, value: String) =
+    returning(new Environment.Variable)(x => { x setKey key ; x setValue value })
+
+  def setDefaults() {
+    setFork(true)
+    setFailonerror(true)
+    getProject.setSystemProperties()
+    setClassname(scalaRunnerClass)
+    addSysproperty(newKeyValue("partest.is-in-ant", "true"))
+    jvmline(partestJVMArgs)
+    runnerArgs foreach addArg
+
+    // do we want basedir or rootDir to be the cwd?
+    // setDir(Path(rootDir).jfile)
+  }
+  
+  override def init() = {
+    super.init()
+    setDefaults()
+  }
+}
+
diff --git a/src/partest-alternative/scala/tools/partest/antlib.xml b/src/partest-alternative/scala/tools/partest/antlib.xml
new file mode 100644
index 0000000..af36f11
--- /dev/null
+++ b/src/partest-alternative/scala/tools/partest/antlib.xml
@@ -0,0 +1,3 @@
+<antlib>
+  <taskdef name="partest" classname="scala.tools.partest.ant.JavaTask"/>
+</antlib>
diff --git a/src/partest-alternative/scala/tools/partest/category/AllCategories.scala b/src/partest-alternative/scala/tools/partest/category/AllCategories.scala
new file mode 100644
index 0000000..422b6bc
--- /dev/null
+++ b/src/partest-alternative/scala/tools/partest/category/AllCategories.scala
@@ -0,0 +1,20 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala Parallel Testing               **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+package scala.tools
+package partest
+package category
+
+trait AllCategories extends Compiler with Analysis with Runner {
+  self: Universe =>
+  
+  object Pos extends DirBasedCategory("pos") { lazy val testSequence: TestSequence = List(compile) }
+  object Neg extends DirBasedCategory("neg") { lazy val testSequence: TestSequence = List(checkFileRequired, not(compile), diff) }
+  object Run extends DirBasedCategory("run") { lazy val testSequence: TestSequence = List(compile, run, diff) }
+  object Jvm extends DirBasedCategory("jvm") { lazy val testSequence: TestSequence = List(compile, run, diff) }
+}
diff --git a/src/partest-alternative/scala/tools/partest/category/Analysis.scala b/src/partest-alternative/scala/tools/partest/category/Analysis.scala
new file mode 100644
index 0000000..d6a162b
--- /dev/null
+++ b/src/partest-alternative/scala/tools/partest/category/Analysis.scala
@@ -0,0 +1,64 @@
+/* NEST (New Scala Test)
+ * Copyright 2007-2010 LAMP/EPFL
+ */
+
+package scala.tools
+package partest
+package category
+
+import java.lang.{ ClassLoader => JavaClassLoader }
+import java.net.URL
+import nsc.util.ScalaClassLoader
+import nsc.io._
+
+class PartestClassLoader(urls: Array[URL], parent: JavaClassLoader) extends ScalaClassLoader.URLClassLoader(urls, parent) {
+  def this(urls: Array[URL])  = this(urls, null)
+  def bytes(path: String)     = findBytesForClassName(path)
+  def singleton(path: String) = tryToInitializeClass(path).get getField "MODULE$" get null
+
+  /** Calls a method in an object via reflection.
+   */
+  def apply[T](className: String, methodName: String)(args: Any*): T = {
+    def fail = error("Reflection failed on %s.%s".format(className, methodName))
+    val clazz = tryToLoadClass(className) getOrElse fail
+    val obj = singleton(className)
+    val m = clazz.getMethods find (x => x.getName == methodName && x.getParameterTypes.size == args.size) getOrElse fail
+
+    m.invoke(obj, args map (_.asInstanceOf[AnyRef]): _*).asInstanceOf[T]
+  }
+}
+
+trait Analysis {
+  self: Universe =>
+  
+  object Scalap extends DirBasedCategory("scalap") {
+    val testSequence: TestSequence = List(checkFileRequired, compile, run, diff)
+    override def denotesTest(p: Path) = p.isDirectory && (p.toDirectory.files exists (_.name == "result.test"))
+    override def createTest(location: Path) = new ScalapTest(location)
+    
+    class ScalapTest(val location: Path) extends TestEntity {
+      val category      = Scalap
+      val scalapMain    = "scala.tools.scalap.Main$"
+      val scalapMethod  = "decompileScala"
+
+      override def classpathPaths = super.classpathPaths :+ build.scalap
+      override def checkFile      = File(location / "result.test")
+
+      private def runnerURLs        = build.classpathPaths ::: classpathPaths map (_.toURL)
+      private def createClassLoader = new PartestClassLoader(runnerURLs.toArray, this.getClass.getClassLoader)
+      
+      val isPackageObject = containsString("package object")
+      val suffix          = if (isPackageObject) ".package" else ""
+      val className       = location.name.capitalize + suffix
+
+      override def run() = loggingResult {
+        def loader  = createClassLoader
+        def bytes   = loader.bytes(className)
+        
+        trace("scalap %s".format(className))
+        if (isDryRun) ""
+        else loader[String](scalapMain, scalapMethod)(bytes, isPackageObject)
+      }
+    }
+  }
+}
diff --git a/src/partest-alternative/scala/tools/partest/category/Compiler.scala b/src/partest-alternative/scala/tools/partest/category/Compiler.scala
new file mode 100644
index 0000000..7ff62f8
--- /dev/null
+++ b/src/partest-alternative/scala/tools/partest/category/Compiler.scala
@@ -0,0 +1,140 @@
+/* NEST (New Scala Test)
+ * Copyright 2007-2010 LAMP/EPFL
+ */
+
+package scala.tools
+package partest
+package category
+
+import nsc.io._
+import nsc.reporters._
+import nsc.{ Settings, CompilerCommand }
+import scala.tools.nsc.interactive.RefinedBuildManager
+import util.copyPath
+
+trait Compiler {
+  self: Universe =>
+
+  /** Resident Compiler.
+   *  $SCALAC -d dir.obj -Xresident -sourcepath . "$@"
+   */
+  object Res extends DirBasedCategory("res") {
+    lazy val testSequence: TestSequence = List(checkFileRequired, compile, diff)
+    
+    override def denotesTest(p: Path)       = p.isDirectory && resFile(p).isFile
+    override def createTest(location: Path) = new ResidentTest(location.toDirectory)
+        
+    override def createSettings(entity: TestEntity): TestSettings =    
+      returning(super.createSettings(entity)) { settings =>
+        settings.resident.value   = true
+        settings.sourcepath.value = entity.sourcesDir.path
+      }
+    
+    class ResidentTest(val location: Directory) extends TestEntity {
+      val category = Res
+      override def sourcesDir     = categoryDir
+
+      override def acknowledges(p: Path) = 
+        super.acknowledges(p) || (resFile(location) isSame p)
+      
+      private def residentCompilerCommands = safeLines(resFile(location))
+      private def compileResident(global: PartestGlobal, lines: List[String]) = {        
+        def printPrompt = global inform "nsc> "
+        val results =
+          lines map { line =>
+            printPrompt
+            trace("compile " + line)
+            isDryRun || global.partestCompile(toArgs(line) map (categoryDir / _ path), false)
+          }
+      
+        printPrompt
+
+        /** Note - some res tests are really "neg" style tests, so we can't
+         *  use the return value of the compile.  The diff catches failures.
+         */
+        true  // results forall (_ == true)
+      }
+
+      override def compile() = compileResident(newGlobal(Nil)._1, residentCompilerCommands)
+    }
+    private[Res] def resFile(p: Path) = p.toFile addExtension "res"
+  }
+
+  object BuildManager extends DirBasedCategory("buildmanager") {
+    lazy val testSequence: TestSequence = List(checkFileRequired, compile, diff)
+    override def denotesTest(p: Path) = p.isDirectory && testFile(p).isFile
+    override def createTest(location: Path) = new BuildManagerTest(location.toDirectory)
+    
+    override def createSettings(entity: TestEntity): TestSettings =
+      returning[TestSettings](super.createSettings(entity)) { settings =>
+        settings.Ybuildmanagerdebug.value = true
+        settings.sourcepath.value = entity.sourcesDir.path
+      }
+    
+    class PartestBuildManager(settings: Settings, val reporter: ConsoleReporter) extends RefinedBuildManager(settings) {
+      def errorFn(msg: String) = Console println msg
+      
+      override protected def newCompiler(newSettings: Settings) =  
+        new BuilderGlobal(newSettings, reporter)
+      
+      private def filesToSet(pre: String, fs: List[String]): Set[AbstractFile] =
+        fs flatMap (s => Option(AbstractFile getFile (Path(settings.sourcepath.value) / s path))) toSet
+      
+      def buildManagerCompile(line: String): Boolean = {
+        val prompt = "builder > "     
+        reporter printMessage (prompt + line)
+        val command = new CompilerCommand(toArgs(line), settings)
+        val files   = filesToSet(settings.sourcepath.value, command.files)
+        
+        update(files, Set.empty)
+        true
+      }
+    }
+
+    private[BuildManager] def testFile(p: Path) = (p / p.name addExtension "test").toFile
+
+    class BuildManagerTest(val location: Directory) extends TestEntity {
+      val category = BuildManager
+      
+      override def sourcesDir     = outDir
+      override def sourceFiles    = Path onlyFiles (location walkFilter (_ != changesDir) filter isJavaOrScala toList)
+      override def checkFile      = File(location / location.name addExtension "check")
+      
+      override def acknowledges(p: Path) = super.acknowledges(p) || (p isSame testFile(location))
+      
+      def buildManagerCommands  = safeLines(testFile(location))
+      def changesDir            = Directory(location / (location.name + ".changes"))
+      
+      override def compile() = {
+        val settings = createSettings(this)
+        val pbm      = new PartestBuildManager(settings, newReporter(settings))
+        
+        // copy files
+        for (source <- sourceFiles) {
+          val target = outDir / (location.normalize relativize source)
+          copyPath(source, target.toFile)
+        }
+        
+        def runUpdate(line: String) = {
+          val Array(srcName, replacement) = line split "=>"
+          copyPath(File(changesDir / replacement), File(outDir / srcName))
+        }
+ 
+        def sendCommand(line: String): Boolean = {
+          val compileRegex  = """^>>compile (.*)$""".r
+          val updateRegex   = """^>>update\s+(.*)""".r
+          trace("send: " + (line drop 2))
+          
+          isDryRun || (line match {
+            case compileRegex(xs)   => pbm.buildManagerCompile(xs)
+            case updateRegex(line)  => runUpdate(line)
+          })
+        }
+        
+        // send each line to the build manager
+        buildManagerCommands forall sendCommand
+      }
+    }
+  }
+}
+
diff --git a/src/partest-alternative/scala/tools/partest/category/Runner.scala b/src/partest-alternative/scala/tools/partest/category/Runner.scala
new file mode 100644
index 0000000..54aa0b8
--- /dev/null
+++ b/src/partest-alternative/scala/tools/partest/category/Runner.scala
@@ -0,0 +1,108 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala Parallel Testing               **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+package scala.tools
+package partest
+package category
+
+import nsc.io._
+
+trait Runner {
+  self: Universe =>
+
+  /** Shootout.
+   */
+  object Shootout extends DirBasedCategory("shootout") {
+    lazy val testSequence: TestSequence = List(compile, run, diff)
+    
+    override def denotesTest(p: Path)       = isScala(p) && runner(p).isFile
+    override def createTest(location: Path) = new ShootoutTest(location.toFile)
+    
+    class ShootoutTest(val location: File) extends TestEntity {
+      val category = Shootout
+      // The files in shootout are very free form, so acknowledge anything close.
+      override def acknowledges(p: Path) =
+        (p.parent.normalize isSame Shootout.root) && (p.name startsWith label)
+      
+      private def generated     = File(outDir / "test.scala")
+      private def runnerFile    = runner(location)
+      override def sourceFiles  = List(generated)
+      
+      override def compile() = {
+        trace("generate %s from %s, %s".format(tracePath(generated), tracePath(location), tracePath(runnerFile)))
+        // generate source file (even on dry run, we need the path)
+        generated.writeAll(location.slurp(), runnerFile.slurp())
+        
+        // compile generated file
+        super.compile()
+      }
+    }
+
+    private[Shootout] def runner(p: Path) = p addExtension "runner" toFile
+  }
+  
+  object Scalacheck extends DirBasedCategory("scalacheck") {
+    lazy val testSequence: TestSequence = List(compile, run)
+    override def createTest(location: Path) = new ScalacheckTest(location)
+    
+    class ScalacheckTest(val location: Path) extends TestEntity {
+      val category = Scalacheck
+      
+      import build.{ scalacheck, forkjoin }
+      import org.scalacheck.Properties
+      import org.scalacheck.Test.{ checkProperties, defaultParams, Result }
+
+      override def classpathPaths = super.classpathPaths ::: List(scalacheck, forkjoin)
+      private def arrayURLs = Array(scalacheck, outDir) map (_.toURL)
+      
+      /** For reasons I'm not entirely clear on, I've written all this
+       *  to avoid a source dependency on scalacheck.
+       */
+      class ScalacheckClassLoader extends PartestClassLoader(arrayURLs, this.getClass.getClassLoader) {
+        type ScalacheckResult = { def passed: Boolean }
+
+        def propCallback(name: String, passed: Int, discarded: Int): Unit = ()
+        def testCallback(name: String, result: AnyRef): Unit = ()
+        
+        val test    = singleton("Test$")
+        val params  = apply[AnyRef]("org.scalacheck.Test$", "defaultParams")()
+        val result  = apply[Seq[(String, AnyRef)]]("org.scalacheck.Test$", "checkProperties")(test, params, propCallback _, testCallback _)
+        
+        def allResults() = 
+          for ((prop, res) <- result) yield {
+            ScalacheckTest.this.trace("%s: %s".format(prop, res))            
+            res.asInstanceOf[ScalacheckResult].passed
+          }
+          
+        def check() = allResults forall (_ == true)
+      }
+
+      override def run() = {
+        trace("scalacheck runs via classloader with: %s".format(arrayURLs mkString ", "))
+        isDryRun || (new ScalacheckClassLoader check)
+      }
+    }
+  }
+  
+  object Script extends DirBasedCategory("script") {
+    val testSequence: TestSequence = List(exec, diff)    
+    override def createTest(location: Path) = new ScriptTest(location)
+    
+    class ScriptTest(val location: Path) extends TestEntity {
+      val category    = Script
+      val scriptFile  = if (location.isDirectory) location / (label + ".scala") else location
+      val argsFile    = withExtension("args").toFile
+      def batFile     = scriptFile changeExtension "bat"
+      def script      = if (Properties.isWin) batFile else scriptFile
+
+      override def acknowledges(p: Path) = super.acknowledges(p) || (List(argsFile, batFile) exists (_ isSame p))
+      override def execCwd = Some(sourcesDir)
+      override def argumentsToExec = script.path :: safeArgs(argsFile)
+    }
+  }
+}
\ No newline at end of file
diff --git a/src/partest-alternative/scala/tools/partest/io/ANSIWriter.scala b/src/partest-alternative/scala/tools/partest/io/ANSIWriter.scala
new file mode 100644
index 0000000..e77384c
--- /dev/null
+++ b/src/partest-alternative/scala/tools/partest/io/ANSIWriter.scala
@@ -0,0 +1,58 @@
+/* NEST (New Scala Test)
+ * Copyright 2007-2010 LAMP/EPFL
+ * @author Philipp Haller
+ */
+
+package scala.tools
+package partest
+package io
+
+import java.io.{ Writer, PrintWriter, OutputStream, OutputStreamWriter }
+
+object ANSIWriter {
+  val NONE = 0
+  val SOME = 1
+  val MANY = 2
+
+  def apply(isAnsi: Boolean) = if (isAnsi) MANY else NONE  
+}
+import ANSIWriter._
+
+class ANSIWriter(writer: Writer) extends PrintWriter(writer, true) {  
+  def this(out: OutputStream) = this(new OutputStreamWriter(out))
+  def colorful: Int = NONE
+  
+  protected val manyColors = List(
+    Console.BOLD + Console.BLACK,
+    Console.BOLD + Console.GREEN,
+    Console.BOLD + Console.RED,
+    Console.BOLD + Console.YELLOW,
+    Console.RESET
+  )
+  protected val someColors = List(
+    Console.BOLD + Console.BLACK,
+    Console.RESET,
+    Console.BOLD + Console.BLACK,
+    Console.BOLD + Console.BLACK,
+    Console.RESET
+  )
+  protected val noColors = List("", "", "", "", "")
+  
+  lazy val List(_outline, _success, _failure, _warning, _default) = colorful match {
+    case NONE => noColors
+    case SOME => someColors
+    case MANY => manyColors
+    case _    => noColors
+  }
+  
+  private def wrprint(msg: String): Unit = synchronized {
+    print(msg)
+    flush()
+  }
+
+  def outline(msg: String) = wrprint(_outline + msg + _default)
+  def success(msg: String) = wrprint(_success + msg + _default)
+  def failure(msg: String) = wrprint(_failure + msg + _default)
+  def warning(msg: String) = wrprint(_warning + msg + _default)
+  def normal(msg: String) = wrprint(_default + msg)
+}
diff --git a/src/partest-alternative/scala/tools/partest/io/Diff.java b/src/partest-alternative/scala/tools/partest/io/Diff.java
new file mode 100644
index 0000000..57e0a2b
--- /dev/null
+++ b/src/partest-alternative/scala/tools/partest/io/Diff.java
@@ -0,0 +1,873 @@
+
+package scala.tools.partest.io;
+
+import java.util.Hashtable;
+
+/** A class to compare IndexedSeqs of objects.  The result of comparison
+    is a list of <code>change</code> objects which form an
+    edit script.  The objects compared are traditionally lines
+    of text from two files.  Comparison options such as "ignore
+    whitespace" are implemented by modifying the <code>equals</code>
+    and <code>hashcode</code> methods for the objects compared.
+<p>
+   The basic algorithm is described in: </br>
+   "An O(ND) Difference Algorithm and its Variations", Eugene Myers,
+   Algorithmica Vol. 1 No. 2, 1986, p 251.  
+<p>
+   This class outputs different results from GNU diff 1.15 on some
+   inputs.  Our results are actually better (smaller change list, smaller
+   total size of changes), but it would be nice to know why.  Perhaps
+   there is a memory overwrite bug in GNU diff 1.15.
+
+  @author Stuart D. Gathman, translated from GNU diff 1.15
+    Copyright (C) 2000  Business Management Systems, Inc.
+<p>
+    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 1, or (at your option)
+    any later version.
+<p>
+    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.
+<p>
+    You should have received a copy of the <a href=COPYING.txt>
+    GNU General Public License</a>
+    along with this program; if not, write to the Free Software
+    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+
+ */
+
+public class Diff {
+
+  /** Prepare to find differences between two arrays.  Each element of
+      the arrays is translated to an "equivalence number" based on
+      the result of <code>equals</code>.  The original Object arrays
+      are no longer needed for computing the differences.  They will
+      be needed again later to print the results of the comparison as
+      an edit script, if desired.
+   */
+  public Diff(Object[] a,Object[] b) {
+    Hashtable h = new Hashtable(a.length + b.length);
+    filevec[0] = new file_data(a,h);
+    filevec[1] = new file_data(b,h);
+  }
+
+  /** 1 more than the maximum equivalence value used for this or its
+     sibling file. */
+  private int equiv_max = 1;
+
+  /** When set to true, the comparison uses a heuristic to speed it up.
+    With this heuristic, for files with a constant small density
+    of changes, the algorithm is linear in the file size.  */
+  public boolean heuristic = false;
+
+  /** When set to true, the algorithm returns a guarranteed minimal
+      set of changes.  This makes things slower, sometimes much slower. */
+  public boolean no_discards = false;
+
+  private int[] xvec, yvec;	/* IndexedSeqs being compared. */
+  private int[] fdiag;		/* IndexedSeq, indexed by diagonal, containing
+				   the X coordinate of the point furthest
+				   along the given diagonal in the forward
+				   search of the edit matrix. */
+  private int[] bdiag;		/* IndexedSeq, indexed by diagonal, containing
+				   the X coordinate of the point furthest
+				   along the given diagonal in the backward
+				   search of the edit matrix. */
+  private int fdiagoff, bdiagoff;
+  private final file_data[] filevec = new file_data[2];
+  private int cost;
+
+  /** Find the midpoint of the shortest edit script for a specified
+     portion of the two files.
+
+     We scan from the beginnings of the files, and simultaneously from the ends,
+     doing a breadth-first search through the space of edit-sequence.
+     When the two searches meet, we have found the midpoint of the shortest
+     edit sequence.
+
+     The value returned is the number of the diagonal on which the midpoint lies.
+     The diagonal number equals the number of inserted lines minus the number
+     of deleted lines (counting only lines before the midpoint).
+     The edit cost is stored into COST; this is the total number of
+     lines inserted or deleted (counting only lines before the midpoint).
+
+     This function assumes that the first lines of the specified portions
+     of the two files do not match, and likewise that the last lines do not
+     match.  The caller must trim matching lines from the beginning and end
+     of the portions it is going to specify.
+
+     Note that if we return the "wrong" diagonal value, or if
+     the value of bdiag at that diagonal is "wrong",
+     the worst this can do is cause suboptimal diff output.
+     It cannot cause incorrect diff output.  */
+
+  private int diag (int xoff, int xlim, int yoff, int ylim) {
+    final int[] fd = fdiag;	// Give the compiler a chance.
+    final int[] bd = bdiag;	// Additional help for the compiler.
+    final int[] xv = xvec;		// Still more help for the compiler.
+    final int[] yv = yvec;		// And more and more . . .
+    final int dmin = xoff - ylim;	// Minimum valid diagonal.
+    final int dmax = xlim - yoff;	// Maximum valid diagonal.
+    final int fmid = xoff - yoff;	// Center diagonal of top-down search.
+    final int bmid = xlim - ylim;	// Center diagonal of bottom-up search.
+    int fmin = fmid, fmax = fmid;	// Limits of top-down search.
+    int bmin = bmid, bmax = bmid;	// Limits of bottom-up search.
+    /* True if southeast corner is on an odd
+				     diagonal with respect to the northwest. */
+    final boolean odd = (fmid - bmid & 1) != 0;	
+
+    fd[fdiagoff + fmid] = xoff;
+    bd[bdiagoff + bmid] = xlim;
+
+    for (int c = 1;; ++c)
+      {
+	int d;			/* Active diagonal. */
+	boolean big_snake = false;
+
+	/* Extend the top-down search by an edit step in each diagonal. */
+	if (fmin > dmin)
+	  fd[fdiagoff + --fmin - 1] = -1;
+	else
+	  ++fmin;
+	if (fmax < dmax)
+	  fd[fdiagoff + ++fmax + 1] = -1;
+	else
+	  --fmax;
+	for (d = fmax; d >= fmin; d -= 2)
+	  {
+	    int x, y, oldx, tlo = fd[fdiagoff + d - 1], thi = fd[fdiagoff + d + 1];
+
+	    if (tlo >= thi)
+	      x = tlo + 1;
+	    else
+	      x = thi;
+	    oldx = x;
+	    y = x - d;
+	    while (x < xlim && y < ylim && xv[x] == yv[y]) {
+	      ++x; ++y;
+	    }
+	    if (x - oldx > 20)
+	      big_snake = true;
+	    fd[fdiagoff + d] = x;
+	    if (odd && bmin <= d && d <= bmax && bd[bdiagoff + d] <= fd[fdiagoff + d])
+	      {
+		cost = 2 * c - 1;
+		return d;
+	      }
+	  }
+
+	/* Similar extend the bottom-up search. */
+	if (bmin > dmin)
+	  bd[bdiagoff + --bmin - 1] = Integer.MAX_VALUE;
+	else
+	  ++bmin;
+	if (bmax < dmax)
+	  bd[bdiagoff + ++bmax + 1] = Integer.MAX_VALUE;
+	else
+	  --bmax;
+	for (d = bmax; d >= bmin; d -= 2)
+	  {
+	    int x, y, oldx, tlo = bd[bdiagoff + d - 1], thi = bd[bdiagoff + d + 1];
+
+	    if (tlo < thi)
+	      x = tlo;
+	    else
+	      x = thi - 1;
+	    oldx = x;
+	    y = x - d;
+	    while (x > xoff && y > yoff && xv[x - 1] == yv[y - 1]) {
+	      --x; --y;
+	    }
+	    if (oldx - x > 20)
+	      big_snake = true;
+	    bd[bdiagoff + d] = x;
+	    if (!odd && fmin <= d && d <= fmax && bd[bdiagoff + d] <= fd[fdiagoff + d])
+	      {
+		cost = 2 * c;
+		return d;
+	      }
+	  }
+
+	/* Heuristic: check occasionally for a diagonal that has made
+	   lots of progress compared with the edit distance.
+	   If we have any such, find the one that has made the most
+	   progress and return it as if it had succeeded.
+
+	   With this heuristic, for files with a constant small density
+	   of changes, the algorithm is linear in the file size.  */
+
+	if (c > 200 && big_snake && heuristic)
+	  {
+	    int best = 0;
+	    int bestpos = -1;
+
+	    for (d = fmax; d >= fmin; d -= 2)
+	      {
+		int dd = d - fmid;
+		if ((fd[fdiagoff + d] - xoff)*2 - dd > 12 * (c + (dd > 0 ? dd : -dd)))
+		  {
+		    if (fd[fdiagoff + d] * 2 - dd > best
+			&& fd[fdiagoff + d] - xoff > 20
+			&& fd[fdiagoff + d] - d - yoff > 20)
+		      {
+			int k;
+			int x = fd[fdiagoff + d];
+
+			/* We have a good enough best diagonal;
+			   now insist that it end with a significant snake.  */
+			for (k = 1; k <= 20; k++)
+			  if (xvec[x - k] != yvec[x - d - k])
+			    break;
+
+			if (k == 21)
+			  {
+			    best = fd[fdiagoff + d] * 2 - dd;
+			    bestpos = d;
+			  }
+		      }
+		  }
+	      }
+	    if (best > 0)
+	      {
+		cost = 2 * c - 1;
+		return bestpos;
+	      }
+
+	    best = 0;
+	    for (d = bmax; d >= bmin; d -= 2)
+	      {
+		int dd = d - bmid;
+		if ((xlim - bd[bdiagoff + d])*2 + dd > 12 * (c + (dd > 0 ? dd : -dd)))
+		  {
+		    if ((xlim - bd[bdiagoff + d]) * 2 + dd > best
+			&& xlim - bd[bdiagoff + d] > 20
+			&& ylim - (bd[bdiagoff + d] - d) > 20)
+		      {
+			/* We have a good enough best diagonal;
+			   now insist that it end with a significant snake.  */
+			int k;
+			int x = bd[bdiagoff + d];
+
+			for (k = 0; k < 20; k++)
+			  if (xvec[x + k] != yvec[x - d + k])
+			    break;
+			if (k == 20)
+			  {
+			    best = (xlim - bd[bdiagoff + d]) * 2 + dd;
+			    bestpos = d;
+			  }
+		      }
+		  }
+	      }
+	    if (best > 0)
+	      {
+		cost = 2 * c - 1;
+		return bestpos;
+	      }
+	  }
+      }
+  }
+
+  /** Compare in detail contiguous subsequences of the two files
+     which are known, as a whole, to match each other.
+
+     The results are recorded in the IndexedSeqs filevec[N].changed_flag, by
+     storing a 1 in the element for each line that is an insertion or deletion.
+
+     The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
+
+     Note that XLIM, YLIM are exclusive bounds.
+     All line numbers are origin-0 and discarded lines are not counted.  */
+
+  private void compareseq (int xoff, int xlim, int yoff, int ylim) {
+    /* Slide down the bottom initial diagonal. */
+    while (xoff < xlim && yoff < ylim && xvec[xoff] == yvec[yoff]) {
+      ++xoff; ++yoff;
+    }
+    /* Slide up the top initial diagonal. */
+    while (xlim > xoff && ylim > yoff && xvec[xlim - 1] == yvec[ylim - 1]) {
+      --xlim; --ylim;
+    }
+    
+    /* Handle simple cases. */
+    if (xoff == xlim)
+      while (yoff < ylim)
+	filevec[1].changed_flag[1+filevec[1].realindexes[yoff++]] = true;
+    else if (yoff == ylim)
+      while (xoff < xlim)
+	filevec[0].changed_flag[1+filevec[0].realindexes[xoff++]] = true;
+    else
+      {
+	/* Find a point of correspondence in the middle of the files.  */
+
+	int d = diag (xoff, xlim, yoff, ylim);
+	int c = cost;
+	int f = fdiag[fdiagoff + d];
+	int b = bdiag[bdiagoff + d];
+
+	if (c == 1)
+	  {
+	    /* This should be impossible, because it implies that
+	       one of the two subsequences is empty,
+	       and that case was handled above without calling `diag'.
+	       Let's verify that this is true.  */
+	    throw new IllegalArgumentException("Empty subsequence");
+	  }
+	else
+	  {
+	    /* Use that point to split this problem into two subproblems.  */
+	    compareseq (xoff, b, yoff, b - d);
+	    /* This used to use f instead of b,
+	       but that is incorrect!
+	       It is not necessarily the case that diagonal d
+	       has a snake from b to f.  */
+	    compareseq (b, xlim, b - d, ylim);
+	  }
+      }
+  }
+
+  /** Discard lines from one file that have no matches in the other file.
+   */
+
+  private void discard_confusing_lines() {
+    filevec[0].discard_confusing_lines(filevec[1]);
+    filevec[1].discard_confusing_lines(filevec[0]);
+  }
+
+  private boolean inhibit = false;
+
+  /** Adjust inserts/deletes of blank lines to join changes
+     as much as possible.
+   */
+
+  private void shift_boundaries() {
+    if (inhibit)
+      return;
+    filevec[0].shift_boundaries(filevec[1]);
+    filevec[1].shift_boundaries(filevec[0]);
+  }
+
+  public interface ScriptBuilder {
+  /** Scan the tables of which lines are inserted and deleted,
+     producing an edit script. 
+   @param changed0 true for lines in first file which do not match 2nd
+   @param len0 number of lines in first file
+   @param changed1 true for lines in 2nd file which do not match 1st
+   @param len1 number of lines in 2nd file
+   @return a linked list of changes - or null
+   */
+    public change build_script(
+      boolean[] changed0,int len0,
+      boolean[] changed1,int len1
+    );
+  }
+
+  /** Scan the tables of which lines are inserted and deleted,
+     producing an edit script in reverse order.  */
+
+  static class ReverseScript implements ScriptBuilder {
+    public  change build_script(
+	final boolean[] changed0,int len0,
+	final boolean[] changed1,int len1)
+    {
+      change script = null;
+      int i0 = 0, i1 = 0;
+      while (i0 < len0 || i1 < len1) {
+	if (changed0[1+i0] || changed1[1+i1]) {
+	    int line0 = i0, line1 = i1;
+
+	    /* Find # lines changed here in each file.  */
+	    while (changed0[1+i0]) ++i0;
+	    while (changed1[1+i1]) ++i1;
+
+	    /* Record this change.  */
+	    script = new change(line0, line1, i0 - line0, i1 - line1, script);
+	}
+
+	/* We have reached lines in the two files that match each other.  */
+	i0++; i1++;
+      }
+
+      return script;
+    }
+  }
+
+  static class ForwardScript implements ScriptBuilder {
+    /** Scan the tables of which lines are inserted and deleted,
+       producing an edit script in forward order.  */
+    public change build_script(
+	  final boolean[] changed0,int len0,
+	  final boolean[] changed1,int len1)
+    {
+      change script = null;
+      int i0 = len0, i1 = len1;
+
+      while (i0 >= 0 || i1 >= 0)
+	{
+	  if (changed0[i0] || changed1[i1])
+	    {
+	      int line0 = i0, line1 = i1;
+
+	      /* Find # lines changed here in each file.  */
+	      while (changed0[i0]) --i0;
+	      while (changed1[i1]) --i1;
+
+	      /* Record this change.  */
+	      script = new change(i0, i1, line0 - i0, line1 - i1, script);
+	    }
+
+	  /* We have reached lines in the two files that match each other.  */
+	  i0--; i1--;
+	}
+
+      return script;
+    }
+  }
+
+  /** Standard ScriptBuilders. */
+  public final static ScriptBuilder
+    forwardScript = new ForwardScript(),
+    reverseScript = new ReverseScript();
+
+  /* Report the differences of two files.  DEPTH is the current directory
+     depth. */
+  public final change diff_2(final boolean reverse) {
+    return diff(reverse ? reverseScript : forwardScript);
+  }
+
+  /** Get the results of comparison as an edit script.  The script 
+     is described by a list of changes.  The standard ScriptBuilder
+     implementations provide for forward and reverse edit scripts.
+     Alternate implementations could, for instance, list common elements 
+     instead of differences.
+     @param bld	an object to build the script from change flags
+     @return the head of a list of changes
+   */
+  public change diff(final ScriptBuilder bld) {
+
+    /* Some lines are obviously insertions or deletions
+       because they don't match anything.  Detect them now,
+       and avoid even thinking about them in the main comparison algorithm.  */
+
+    discard_confusing_lines ();
+
+    /* Now do the main comparison algorithm, considering just the
+       undiscarded lines.  */
+
+    xvec = filevec[0].undiscarded;
+    yvec = filevec[1].undiscarded;
+
+    int diags =
+      filevec[0].nondiscarded_lines + filevec[1].nondiscarded_lines + 3;
+    fdiag = new int[diags];
+    fdiagoff = filevec[1].nondiscarded_lines + 1;
+    bdiag = new int[diags];
+    bdiagoff = filevec[1].nondiscarded_lines + 1;
+
+    compareseq (0, filevec[0].nondiscarded_lines,
+		0, filevec[1].nondiscarded_lines);
+    fdiag = null;
+    bdiag = null;
+
+    /* Modify the results slightly to make them prettier
+       in cases where that can validly be done.  */
+
+    shift_boundaries ();
+
+    /* Get the results of comparison in the form of a chain
+       of `struct change's -- an edit script.  */
+    return bld.build_script(
+      filevec[0].changed_flag,
+      filevec[0].buffered_lines,
+      filevec[1].changed_flag,
+      filevec[1].buffered_lines
+    );
+
+  }
+
+  /** The result of comparison is an "edit script": a chain of change objects.
+     Each change represents one place where some lines are deleted
+     and some are inserted.
+     
+     LINE0 and LINE1 are the first affected lines in the two files (origin 0).
+     DELETED is the number of lines deleted here from file 0.
+     INSERTED is the number of lines inserted here in file 1.
+
+     If DELETED is 0 then LINE0 is the number of the line before
+     which the insertion was done; vice versa for INSERTED and LINE1.  */
+
+  public static class change {
+    /** Previous or next edit command. */
+    public change link;		
+    /** # lines of file 1 changed here.  */
+    public final int inserted;	
+    /** # lines of file 0 changed here.  */
+    public final int deleted;		
+    /** Line number of 1st deleted line.  */
+    public final int line0;		
+    /** Line number of 1st inserted line.  */
+    public final int line1;		
+
+    /** Cons an additional entry onto the front of an edit script OLD.
+       LINE0 and LINE1 are the first affected lines in the two files (origin 0).
+       DELETED is the number of lines deleted here from file 0.
+       INSERTED is the number of lines inserted here in file 1.
+
+       If DELETED is 0 then LINE0 is the number of the line before
+       which the insertion was done; vice versa for INSERTED and LINE1.  */
+    public change(int line0, int line1, int deleted, int inserted, change old) {
+      this.line0 = line0;
+      this.line1 = line1;
+      this.inserted = inserted;
+      this.deleted = deleted;
+      this.link = old;
+      //System.err.println(line0+","+line1+","+inserted+","+deleted);
+    }
+  }
+
+  /** Data on one input file being compared.  
+   */
+
+  class file_data {
+
+    /** Allocate changed array for the results of comparison.  */
+    void clear() {
+      /* Allocate a flag for each line of each file, saying whether that line
+	 is an insertion or deletion.
+	 Allocate an extra element, always zero, at each end of each IndexedSeq.
+       */
+      changed_flag = new boolean[buffered_lines + 2];
+    }
+
+    /** Return equiv_count[I] as the number of lines in this file
+       that fall in equivalence class I.
+         @return the array of equivalence class counts.
+     */
+    int[] equivCount() {
+      int[] equiv_count = new int[equiv_max];
+      for (int i = 0; i < buffered_lines; ++i)
+	++equiv_count[equivs[i]];
+      return equiv_count;
+    }
+
+    /** Discard lines that have no matches in another file.
+
+       A line which is discarded will not be considered by the actual
+       comparison algorithm; it will be as if that line were not in the file.
+       The file's `realindexes' table maps virtual line numbers
+       (which don't count the discarded lines) into real line numbers;
+       this is how the actual comparison algorithm produces results
+       that are comprehensible when the discarded lines are counted.
+<p>
+       When we discard a line, we also mark it as a deletion or insertion
+       so that it will be printed in the output.  
+      @param f the other file   
+     */
+    void discard_confusing_lines(file_data f) {
+      clear();
+    /* Set up table of which lines are going to be discarded. */
+      final byte[] discarded = discardable(f.equivCount());
+
+    /* Don't really discard the provisional lines except when they occur
+       in a run of discardables, with nonprovisionals at the beginning
+       and end.  */
+      filterDiscards(discarded);
+
+    /* Actually discard the lines. */
+      discard(discarded);
+    }
+
+    /** Mark to be discarded each line that matches no line of another file.
+       If a line matches many lines, mark it as provisionally discardable.  
+       @see equivCount()
+       @param counts The count of each equivalence number for the other file.
+       @return 0=nondiscardable, 1=discardable or 2=provisionally discardable
+       	for each line
+     */
+
+    private byte[] discardable(final int[] counts) {
+      final int end = buffered_lines;
+      final byte[] discards = new byte[end];
+      final int[] equivs = this.equivs;
+      int many = 5;
+      int tem = end / 64;
+
+      /* Multiply MANY by approximate square root of number of lines.
+	 That is the threshold for provisionally discardable lines.  */
+      while ((tem = tem >> 2) > 0)
+	many *= 2;
+
+      for (int i = 0; i < end; i++)
+	{
+	  int nmatch;
+	  if (equivs[i] == 0)
+	    continue;
+	  nmatch = counts[equivs[i]];
+	  if (nmatch == 0)
+	    discards[i] = 1;
+	  else if (nmatch > many)
+	    discards[i] = 2;
+	}
+      return discards;
+    }
+
+    /** Don't really discard the provisional lines except when they occur
+       in a run of discardables, with nonprovisionals at the beginning
+       and end.  */
+
+    private void filterDiscards(final byte[] discards) {
+	final int end = buffered_lines;
+
+	for (int i = 0; i < end; i++)
+	  {
+	    /* Cancel provisional discards not in middle of run of discards.  */
+	    if (discards[i] == 2)
+	      discards[i] = 0;
+	    else if (discards[i] != 0)
+	      {
+		/* We have found a nonprovisional discard.  */
+		int j;
+		int length;
+		int provisional = 0;
+
+		/* Find end of this run of discardable lines.
+		   Count how many are provisionally discardable.  */
+		for (j = i; j < end; j++)
+		  {
+		    if (discards[j] == 0)
+		      break;
+		    if (discards[j] == 2)
+		      ++provisional;
+		  }
+
+		/* Cancel provisional discards at end, and shrink the run.  */
+		while (j > i && discards[j - 1] == 2) {
+		  discards[--j] = 0; --provisional;
+		}
+
+		/* Now we have the length of a run of discardable lines
+		   whose first and last are not provisional.  */
+		length = j - i;
+
+		/* If 1/4 of the lines in the run are provisional,
+		   cancel discarding of all provisional lines in the run.  */
+		if (provisional * 4 > length)
+		  {
+		    while (j > i)
+		      if (discards[--j] == 2)
+			discards[j] = 0;
+		  }
+		else
+		  {
+		    int consec;
+		    int minimum = 1;
+		    int tem = length / 4;
+
+		    /* MINIMUM is approximate square root of LENGTH/4.
+		       A subrun of two or more provisionals can stand
+		       when LENGTH is at least 16.
+		       A subrun of 4 or more can stand when LENGTH >= 64.  */
+		    while ((tem = tem >> 2) > 0)
+		      minimum *= 2;
+		    minimum++;
+
+		    /* Cancel any subrun of MINIMUM or more provisionals
+		       within the larger run.  */
+		    for (j = 0, consec = 0; j < length; j++)
+		      if (discards[i + j] != 2)
+			consec = 0;
+		      else if (minimum == ++consec)
+			/* Back up to start of subrun, to cancel it all.  */
+			j -= consec;
+		      else if (minimum < consec)
+			discards[i + j] = 0;
+
+		    /* Scan from beginning of run
+		       until we find 3 or more nonprovisionals in a row
+		       or until the first nonprovisional at least 8 lines in.
+		       Until that point, cancel any provisionals.  */
+		    for (j = 0, consec = 0; j < length; j++)
+		      {
+			if (j >= 8 && discards[i + j] == 1)
+			  break;
+			if (discards[i + j] == 2) {
+			  consec = 0; discards[i + j] = 0;
+			}
+			else if (discards[i + j] == 0)
+			  consec = 0;
+			else
+			  consec++;
+			if (consec == 3)
+			  break;
+		      }
+
+		    /* I advances to the last line of the run.  */
+		    i += length - 1;
+
+		    /* Same thing, from end.  */
+		    for (j = 0, consec = 0; j < length; j++)
+		      {
+			if (j >= 8 && discards[i - j] == 1)
+			  break;
+			if (discards[i - j] == 2) {
+			  consec = 0; discards[i - j] = 0;
+			}
+			else if (discards[i - j] == 0)
+			  consec = 0;
+			else
+			  consec++;
+			if (consec == 3)
+			  break;
+		      }
+		  }
+	      }
+	  }
+      }
+
+    /** Actually discard the lines.
+      @param discards flags lines to be discarded
+     */
+    private void discard(final byte[] discards) {
+      final int end = buffered_lines;
+      int j = 0;
+      for (int i = 0; i < end; ++i)
+	if (no_discards || discards[i] == 0)
+	  {
+	    undiscarded[j] = equivs[i];
+	    realindexes[j++] = i;
+	  }
+	else
+	  changed_flag[1+i] = true;
+      nondiscarded_lines = j;
+    }
+
+    file_data(Object[] data,Hashtable h) {
+      buffered_lines = data.length;
+
+      equivs = new int[buffered_lines]; 
+      undiscarded = new int[buffered_lines];
+      realindexes = new int[buffered_lines];
+
+      for (int i = 0; i < data.length; ++i) {
+        Integer ir = (Integer)h.get(data[i]);
+	if (ir == null)
+	  h.put(data[i],new Integer(equivs[i] = equiv_max++));
+	else
+	  equivs[i] = ir.intValue();
+      }
+    }
+
+    /** Adjust inserts/deletes of blank lines to join changes
+       as much as possible.
+
+       We do something when a run of changed lines include a blank
+       line at one end and have an excluded blank line at the other.
+       We are free to choose which blank line is included.
+       `compareseq' always chooses the one at the beginning,
+       but usually it is cleaner to consider the following blank line
+       to be the "change".  The only exception is if the preceding blank line
+       would join this change to other changes.  
+      @param f the file being compared against
+    */
+
+    void shift_boundaries(file_data f) {
+      final boolean[] changed = changed_flag;
+      final boolean[] other_changed = f.changed_flag;
+      int i = 0;
+      int j = 0;
+      int i_end = buffered_lines;
+      int preceding = -1;
+      int other_preceding = -1;
+
+      for (;;)
+	{
+	  int start, end, other_start;
+
+	  /* Scan forwards to find beginning of another run of changes.
+	     Also keep track of the corresponding point in the other file.  */
+
+	  while (i < i_end && !changed[1+i])
+	    {
+	      while (other_changed[1+j++])
+		/* Non-corresponding lines in the other file
+		   will count as the preceding batch of changes.  */
+		other_preceding = j;
+	      i++;
+	    }
+
+	  if (i == i_end)
+	    break;
+
+	  start = i;
+	  other_start = j;
+
+	  for (;;)
+	    {
+	      /* Now find the end of this run of changes.  */
+
+	      while (i < i_end && changed[1+i]) i++;
+	      end = i;
+
+	      /* If the first changed line matches the following unchanged one,
+		 and this run does not follow right after a previous run,
+		 and there are no lines deleted from the other file here,
+		 then classify the first changed line as unchanged
+		 and the following line as changed in its place.  */
+
+	      /* You might ask, how could this run follow right after another?
+		 Only because the previous run was shifted here.  */
+
+	      if (end != i_end
+		  && equivs[start] == equivs[end]
+		  && !other_changed[1+j]
+		  && end != i_end
+		  && !((preceding >= 0 && start == preceding)
+		       || (other_preceding >= 0
+			   && other_start == other_preceding)))
+		{
+		  changed[1+end++] = true;
+		  changed[1+start++] = false;
+		  ++i;
+		  /* Since one line-that-matches is now before this run
+		     instead of after, we must advance in the other file
+		     to keep in synch.  */
+		  ++j;
+		}
+	      else
+		break;
+	    }
+
+	  preceding = i;
+	  other_preceding = j;
+	}
+    }
+
+    /** Number of elements (lines) in this file. */
+    final int buffered_lines;
+
+    /** IndexedSeq, indexed by line number, containing an equivalence code for
+       each line.  It is this IndexedSeq that is actually compared with that
+       of another file to generate differences. */
+    private final int[]	    equivs;
+
+    /** IndexedSeq, like the previous one except that
+       the elements for discarded lines have been squeezed out.  */
+    final int[]	   undiscarded;
+
+    /** IndexedSeq mapping virtual line numbers (not counting discarded lines)
+       to real ones (counting those lines).  Both are origin-0.  */
+    final int[]	   realindexes;
+
+    /** Total number of nondiscarded lines. */
+    int		    nondiscarded_lines;
+
+    /** Array, indexed by real origin-1 line number,
+       containing true for a line that is an insertion or a deletion.
+       The results of comparison are stored here.  */
+    boolean[]	    changed_flag;
+
+  }
+}
diff --git a/src/partest-alternative/scala/tools/partest/io/DiffPrint.java b/src/partest-alternative/scala/tools/partest/io/DiffPrint.java
new file mode 100644
index 0000000..21ab311
--- /dev/null
+++ b/src/partest-alternative/scala/tools/partest/io/DiffPrint.java
@@ -0,0 +1,606 @@
+
+package scala.tools.partest.io;
+
+import java.io.*;
+import java.util.Vector;
+import java.util.Date;
+//import com.objectspace.jgl.predicates.UnaryPredicate;
+
+interface UnaryPredicate {
+  boolean execute(Object obj);
+}
+
+/** A simple framework for printing change lists produced by <code>Diff</code>.
+    @see bmsi.util.Diff
+    @author Stuart D. Gathman
+    Copyright (C) 2000 Business Management Systems, Inc.
+<p>
+    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 1, or (at your option)
+    any later version.
+<p>
+    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.
+<p>
+    You should have received a copy of the GNU General Public License
+    along with this program; if not, write to the Free Software
+    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+public class DiffPrint {
+  /** A Base class for printing edit scripts produced by Diff.
+      This class divides the change list into "hunks", and calls
+      <code>print_hunk</code> for each hunk.  Various utility methods
+      are provided as well.
+   */
+  public static abstract class Base {
+    protected Base(Object[] a,Object[] b, Writer w) {
+      outfile = new PrintWriter(w);
+      file0 = a;
+      file1 = b;
+    }
+    /** Set to ignore certain kinds of lines when printing
+	an edit script.  For example, ignoring blank lines or comments.
+     */
+    protected UnaryPredicate ignore = null;
+
+    /** Set to the lines of the files being compared.
+     */
+    protected Object[] file0, file1;
+
+    /** Divide SCRIPT into pieces by calling HUNKFUN and
+       print each piece with PRINTFUN.
+       Both functions take one arg, an edit script.
+
+       PRINTFUN takes a subscript which belongs together (with a null
+       link at the end) and prints it.  */
+    public void print_script(Diff.change script) {
+      Diff.change next = script;
+
+      while (next != null)
+	{
+	  Diff.change t, end;
+
+	  /* Find a set of changes that belong together.  */
+	  t = next;
+	  end = hunkfun(next);
+
+	  /* Disconnect them from the rest of the changes,
+	     making them a hunk, and remember the rest for next iteration.  */
+	  next = end.link;
+	  end.link = null;
+	  //if (DEBUG)
+	  //  debug_script(t);
+
+	  /* Print this hunk.  */
+	  print_hunk(t);
+
+	  /* Reconnect the script so it will all be freed properly.  */
+	  end.link = next;
+	}
+	outfile.flush();
+    }
+
+    /** Called with the tail of the script
+       and returns the last link that belongs together with the start
+       of the tail. */
+
+    protected Diff.change hunkfun(Diff.change hunk) {
+      return hunk;
+    }
+
+    protected int first0, last0, first1, last1, deletes, inserts;
+    protected PrintWriter outfile;
+
+    /** Look at a hunk of edit script and report the range of lines in each file
+      that it applies to.  HUNK is the start of the hunk, which is a chain
+      of `struct change'.  The first and last line numbers of file 0 are stored
+      in *FIRST0 and *LAST0, and likewise for file 1 in *FIRST1 and *LAST1. 
+      Note that these are internal line numbers that count from 0.
+
+      If no lines from file 0 are deleted, then FIRST0 is LAST0+1.
+
+      Also set *DELETES nonzero if any lines of file 0 are deleted
+      and set *INSERTS nonzero if any lines of file 1 are inserted.
+      If only ignorable lines are inserted or deleted, both are
+      set to 0.  */
+
+    protected void analyze_hunk(Diff.change hunk) {
+      int f0, l0 = 0, f1, l1 = 0, show_from = 0, show_to = 0;
+      int i;
+      Diff.change next;
+      boolean nontrivial = (ignore == null);
+
+      show_from = show_to = 0;
+
+      f0 = hunk.line0;
+      f1 = hunk.line1;
+
+      for (next = hunk; next != null; next = next.link)
+	{
+	  l0 = next.line0 + next.deleted - 1;
+	  l1 = next.line1 + next.inserted - 1;
+	  show_from += next.deleted;
+	  show_to += next.inserted;
+	  for (i = next.line0; i <= l0 && ! nontrivial; i++)
+	    if (!ignore.execute(file0[i]))
+	      nontrivial = true;
+	  for (i = next.line1; i <= l1 && ! nontrivial; i++)
+	    if (!ignore.execute(file1[i]))
+	      nontrivial = true;
+	}
+
+      first0 = f0;
+      last0 = l0;
+      first1 = f1;
+      last1 = l1;
+
+      /* If all inserted or deleted lines are ignorable,
+	 tell the caller to ignore this hunk.  */
+
+      if (!nontrivial)
+	show_from = show_to = 0;
+
+      deletes = show_from;
+      inserts = show_to;
+    }
+
+    /** Print the script header which identifies the files compared. */
+    protected void print_header(String filea, String fileb) { }
+
+    protected abstract void print_hunk(Diff.change hunk);
+    
+    protected void print_1_line(String pre,Object linbuf) {
+      outfile.println(pre + linbuf.toString());
+    }
+
+    /** Print a pair of line numbers with SEPCHAR, translated for file FILE.
+       If the two numbers are identical, print just one number.
+
+       Args A and B are internal line numbers.
+       We print the translated (real) line numbers.  */
+
+    protected void print_number_range (char sepchar, int a, int b) {
+      /* Note: we can have B < A in the case of a range of no lines.
+	 In this case, we should print the line number before the range,
+	 which is B.  */
+      if (++b > ++a)
+	outfile.print("" + a + sepchar + b);
+      else
+	outfile.print(b);
+    }
+
+    public static char change_letter(int inserts, int deletes) {
+      if (inserts == 0)
+	return 'd';
+      else if (deletes == 0)
+	return 'a';
+      else
+	return 'c';
+    }
+  }
+
+  /** Print a change list in the standard diff format.
+   */
+  public static class NormalPrint extends Base {
+
+    public NormalPrint(Object[] a,Object[] b, Writer w) {
+      super(a,b,w);
+    }
+
+    /** Print a hunk of a normal diff.
+       This is a contiguous portion of a complete edit script,
+       describing changes in consecutive lines.  */
+
+    protected void print_hunk (Diff.change hunk) {
+
+      /* Determine range of line numbers involved in each file.  */
+      analyze_hunk(hunk);
+      if (deletes == 0 && inserts == 0)
+	return;
+
+      /* Print out the line number header for this hunk */
+      print_number_range (',', first0, last0);
+      outfile.print(change_letter(inserts, deletes));
+      print_number_range (',', first1, last1);
+      outfile.println();
+
+      /* Print the lines that the first file has.  */
+      if (deletes != 0)
+	for (int i = first0; i <= last0; i++)
+	  print_1_line ("< ", file0[i]);
+
+      if (inserts != 0 && deletes != 0)
+	outfile.println("---");
+
+      /* Print the lines that the second file has.  */
+      if (inserts != 0)
+	for (int i = first1; i <= last1; i++)
+	  print_1_line ("> ", file1[i]);
+    }
+  }
+
+  /** Prints an edit script in a format suitable for input to <code>ed</code>.
+      The edit script must be generated with the reverse option to
+      be useful as actual <code>ed</code> input.
+   */
+  public static class EdPrint extends Base {
+
+    public EdPrint(Object[] a,Object[] b, Writer w) {
+      super(a,b,w);
+    }
+
+    /** Print a hunk of an ed diff */
+    protected void print_hunk(Diff.change hunk) {
+
+      /* Determine range of line numbers involved in each file.  */
+      analyze_hunk (hunk);
+      if (deletes == 0 && inserts == 0)
+	return;
+
+      /* Print out the line number header for this hunk */
+      print_number_range (',', first0, last0);
+      outfile.println(change_letter(inserts, deletes));
+
+      /* Print new/changed lines from second file, if needed */
+      if (inserts != 0)
+	{
+	  boolean inserting = true;
+	  for (int i = first1; i <= last1; i++)
+	    {
+	      /* Resume the insert, if we stopped.  */
+	      if (! inserting)
+		outfile.println(i - first1 + first0 + "a");
+	      inserting = true;
+
+	      /* If the file's line is just a dot, it would confuse `ed'.
+		 So output it with a double dot, and set the flag LEADING_DOT
+		 so that we will output another ed-command later
+		 to change the double dot into a single dot.  */
+
+	      if (".".equals(file1[i]))
+		{
+		  outfile.println("..");
+		  outfile.println(".");
+		  /* Now change that double dot to the desired single dot.  */
+		  outfile.println(i - first1 + first0 + 1 + "s/^\\.\\././");
+		  inserting = false;
+		}
+	      else
+		/* Line is not `.', so output it unmodified.  */
+		print_1_line ("", file1[i]);
+	    }
+
+	  /* End insert mode, if we are still in it.  */
+	  if (inserting)
+	    outfile.println(".");
+	}
+    }
+  }
+
+  /** Prints an edit script in context diff format.  This and its
+    'unified' variation is used for source code patches.
+   */
+  public static class ContextPrint extends Base {
+
+    protected int context = 3;
+
+    public ContextPrint(Object[] a,Object[] b, Writer w) {
+      super(a,b,w);
+    }
+
+    protected void print_context_label (String mark, File inf, String label) {
+      if (label != null)
+	outfile.println(mark + ' ' + label);
+      else if (inf.lastModified() > 0)
+        // FIXME: use DateFormat to get precise format needed.
+	outfile.println(
+	  mark + ' ' + inf.getPath() + '\t' + new Date(inf.lastModified())
+	);
+      else
+	/* Don't pretend that standard input is ancient.  */
+	outfile.println(mark + ' ' + inf.getPath());
+    }
+
+    public void print_header(String filea,String fileb) {
+      print_context_label ("***", new File(filea), filea);
+      print_context_label ("---", new File(fileb), fileb);
+    }
+
+    /** If function_regexp defined, search for start of function. */
+    private String find_function(Object[] lines, int start) {
+      return null;
+    }
+
+    protected void print_function(Object[] file,int start) {
+      String function = find_function (file0, first0);
+      if (function != null) {
+	outfile.print(" ");
+	outfile.print(
+	  (function.length() < 40) ? function : function.substring(0,40)
+	);
+      }
+    }
+
+    protected void print_hunk(Diff.change hunk) {
+
+      /* Determine range of line numbers involved in each file.  */
+
+      analyze_hunk (hunk);
+
+      if (deletes == 0 && inserts == 0)
+	return;
+
+      /* Include a context's width before and after.  */
+
+      first0 = Math.max(first0 - context, 0);
+      first1 = Math.max(first1 - context, 0);
+      last0 = Math.min(last0 + context, file0.length - 1);
+      last1 = Math.min(last1 + context, file1.length - 1);
+
+
+      outfile.print("***************");
+
+      /* If we looked for and found a function this is part of,
+	 include its name in the header of the diff section.  */
+      print_function (file0, first0);
+
+      outfile.println();
+      outfile.print("*** ");
+      print_number_range (',', first0, last0);
+      outfile.println(" ****");
+
+      if (deletes != 0) {
+	Diff.change next = hunk;
+
+	for (int i = first0; i <= last0; i++) {
+	  /* Skip past changes that apply (in file 0)
+	     only to lines before line I.  */
+
+	  while (next != null && next.line0 + next.deleted <= i)
+	    next = next.link;
+
+	  /* Compute the marking for line I.  */
+
+	  String prefix = " ";
+	  if (next != null && next.line0 <= i)
+	    /* The change NEXT covers this line.
+	       If lines were inserted here in file 1, this is "changed".
+	       Otherwise it is "deleted".  */
+	    prefix = (next.inserted > 0) ? "!" : "-";
+
+	  print_1_line (prefix, file0[i]);
+	}
+      }
+
+      outfile.print("--- ");
+      print_number_range (',', first1, last1);
+      outfile.println(" ----");
+
+      if (inserts != 0) {
+	Diff.change next = hunk;
+
+	for (int i = first1; i <= last1; i++) {
+	  /* Skip past changes that apply (in file 1)
+	     only to lines before line I.  */
+
+	  while (next != null && next.line1 + next.inserted <= i)
+	    next = next.link;
+
+	  /* Compute the marking for line I.  */
+
+	  String prefix = " ";
+	  if (next != null && next.line1 <= i)
+	    /* The change NEXT covers this line.
+	       If lines were deleted here in file 0, this is "changed".
+	       Otherwise it is "inserted".  */
+	    prefix = (next.deleted > 0) ? "!" : "+";
+
+	  print_1_line (prefix, file1[i]);
+	}
+      }
+    }
+  }
+
+  /** Prints an edit script in context diff format.  This and its
+    'unified' variation is used for source code patches.
+   */
+  public static class UnifiedPrint extends ContextPrint {
+
+    public UnifiedPrint(Object[] a,Object[] b, Writer w) {
+      super(a,b,w);
+    }
+
+    public void print_header(String filea,String fileb) {
+      print_context_label ("---", new File(filea), filea);
+      print_context_label ("+++", new File(fileb), fileb);
+    }
+
+    private void print_number_range (int a, int b) {
+      //translate_range (file, a, b, &trans_a, &trans_b);
+
+      /* Note: we can have B < A in the case of a range of no lines.
+	 In this case, we should print the line number before the range,
+	 which is B.  */
+      if (b < a)
+	outfile.print(b + ",0");
+      else
+        super.print_number_range(',',a,b);
+    }
+
+    protected void print_hunk(Diff.change hunk) {
+      /* Determine range of line numbers involved in each file.  */
+      analyze_hunk (hunk);
+
+      if (deletes == 0 && inserts == 0)
+	return;
+
+      /* Include a context's width before and after.  */
+
+      first0 = Math.max(first0 - context, 0);
+      first1 = Math.max(first1 - context, 0);
+      last0 = Math.min(last0 + context, file0.length - 1);
+      last1 = Math.min(last1 + context, file1.length - 1);
+
+
+
+      outfile.print("@@ -");
+      print_number_range (first0, last0);
+      outfile.print(" +");
+      print_number_range (first1, last1);
+      outfile.print(" @@");
+
+      /* If we looked for and found a function this is part of,
+	 include its name in the header of the diff section.  */
+      print_function(file0,first0);
+
+      outfile.println();
+
+      Diff.change next = hunk;
+      int i = first0;
+      int j = first1;
+
+      while (i <= last0 || j <= last1) {
+
+	/* If the line isn't a difference, output the context from file 0. */
+
+	if (next == null || i < next.line0) {
+	  outfile.print(' ');
+	  print_1_line ("", file0[i++]);
+	  j++;
+	}
+	else {
+	  /* For each difference, first output the deleted part. */
+
+	  int k = next.deleted;
+	  while (k-- > 0) {
+	    outfile.print('-');
+	    print_1_line ("", file0[i++]);
+	  }
+
+	  /* Then output the inserted part. */
+
+	  k = next.inserted;
+	  while (k-- > 0) {
+	    outfile.print('+');
+	    print_1_line ("", file1[j++]);
+	  }
+
+	  /* We're done with this hunk, so on to the next! */
+
+	  next = next.link;
+	}
+      }
+    }
+  }
+
+
+  /** Read a text file into an array of String.  This provides basic diff
+     functionality.  A more advanced diff utility will use specialized
+     objects to represent the text lines, with options to, for example,
+     convert sequences of whitespace to a single space for comparison
+     purposes.
+   */
+  static String[] slurp(String file) throws IOException {
+    BufferedReader rdr = new BufferedReader(new FileReader(file));
+    Vector s = new Vector();
+    for (;;) {
+      String line = rdr.readLine();
+      if (line == null) break;
+      s.addElement(line);
+    }
+    String[] a = new String[s.size()];
+    s.copyInto(a);
+    return a;
+  }
+
+  public static void main(String[] argv) throws IOException {
+    String filea = argv[argv.length - 2];
+    String fileb = argv[argv.length - 1];
+    String[] a = slurp(filea);
+    String[] b = slurp(fileb);
+    Diff d = new Diff(a,b);
+    char style = 'n';
+    for (int i = 0; i < argv.length - 2; ++i) {
+      String f = argv[i];
+      if (f.startsWith("-")) {
+        for (int j = 1; j < f.length(); ++j) {
+	  switch (f.charAt(j)) {
+	  case 'e':	// Ed style
+	    style = 'e'; break;
+	  case 'c':	// Context diff
+	    style = 'c'; break;
+	  case 'u':
+	    style = 'u'; break;
+	  }
+	}
+      }
+    }
+    boolean reverse = style == 'e';
+    Diff.change script = d.diff_2(reverse);
+    if (script == null)
+      System.err.println("No differences");
+    else {
+      Base p;
+      Writer w = new OutputStreamWriter(System.out);
+      switch (style) {
+      case 'e':
+        p = new EdPrint(a,b,w); break;
+      case 'c':
+        p = new ContextPrint(a,b,w); break;
+      case 'u':
+        p = new UnifiedPrint(a,b,w); break;
+      default:
+        p = new NormalPrint(a,b,w);
+      }
+      p.print_header(filea,fileb);
+      p.print_script(script);
+    }
+  }
+
+  public static void doDiff(String[] argv, Writer w) throws IOException {
+    String filea = argv[argv.length - 2];
+    String fileb = argv[argv.length - 1];
+    String[] a = slurp(filea);
+    String[] b = slurp(fileb);
+    Diff d = new Diff(a,b);
+    char style = 'n';
+    for (int i = 0; i < argv.length - 2; ++i) {
+      String f = argv[i];
+      if (f.startsWith("-")) {
+        for (int j = 1; j < f.length(); ++j) {
+	  switch (f.charAt(j)) {
+	  case 'e':	// Ed style
+	    style = 'e'; break;
+	  case 'c':	// Context diff
+	    style = 'c'; break;
+	  case 'u':
+	    style = 'u'; break;
+	  }
+	}
+      }
+    }
+    boolean reverse = style == 'e';
+    Diff.change script = d.diff_2(reverse);
+    if (script == null)
+      w.write("No differences\n");
+    else {
+      Base p;
+      switch (style) {
+      case 'e':
+        p = new EdPrint(a,b,w); break;
+      case 'c':
+        p = new ContextPrint(a,b,w); break;
+      case 'u':
+        p = new UnifiedPrint(a,b,w); break;
+      default:
+        p = new NormalPrint(a,b,w);
+      }
+      p.print_header(filea,fileb);
+      p.print_script(script);
+    }
+  }
+
+}
diff --git a/src/partest-alternative/scala/tools/partest/io/JUnitReport.scala b/src/partest-alternative/scala/tools/partest/io/JUnitReport.scala
new file mode 100644
index 0000000..72b56b5
--- /dev/null
+++ b/src/partest-alternative/scala/tools/partest/io/JUnitReport.scala
@@ -0,0 +1,38 @@
+/* NEST (New Scala Test)
+ * Copyright 2007-2010 LAMP/EPFL
+ */
+
+package scala.tools
+package partest
+package io
+
+/** This is disabled for the moment but I can fix it up if anyone
+ *  is using it.
+ */
+class JUnitReport {
+  // create JUnit Report xml files if directory was specified
+  // def junitReport(dir: Directory) = {
+  //   dir.mkdir()
+  //   val report = testReport(set.kind, results, succs, fails)
+  //   XML.save("%s/%s.xml".format(d.toAbsolute.path, set.kind), report)
+  // }  
+
+  // def oneResult(res: (TestEntity, Int)) =
+  //   <testcase name={res._1.path}>{
+  //    res._2 match {
+  //      case 0 => scala.xml.NodeSeq.Empty
+  //       case 1 => <failure message="Test failed"/>
+  //       case 2 => <failure message="Test timed out"/>
+  //    } 
+  //  }</testcase>
+  // 
+  // def testReport(kind: String, results: Iterable[(TestEntity, Int)], succs: Int, fails: Int) = {
+  //   <testsuite name={kind} tests={(succs + fails).toString} failures={fails.toString}>
+  //    <properties/>
+  //    {
+  //      results.map(oneResult(_))
+  //    }
+  //   </testsuite>
+  // }
+  //
+}
\ No newline at end of file
diff --git a/src/partest-alternative/scala/tools/partest/io/Logging.scala b/src/partest-alternative/scala/tools/partest/io/Logging.scala
new file mode 100644
index 0000000..72e4fd1
--- /dev/null
+++ b/src/partest-alternative/scala/tools/partest/io/Logging.scala
@@ -0,0 +1,137 @@
+package scala.tools
+package partest
+package io
+
+import java.io.{ StringWriter, PrintWriter, Writer }
+import scala.tools.nsc.io._
+import scala.util.control.ControlThrowable
+
+trait Logging {
+  universe: Universe =>
+  
+  class PartestANSIWriter extends ANSIWriter(Console.out) {
+    override def colorful: Int = ANSIWriter(universe.isAnsi)
+    private def printIf(cond: Boolean, msg: String) =
+      if (cond) { outline("debug: ") ; println(msg) }
+    
+    val verbose = printIf(isVerbose || isDebug, _: String)
+    val debug   = printIf(isDebug, _: String)
+  }
+  
+  lazy val NestUI = new PartestANSIWriter()
+  
+  import NestUI.{ _outline, _success, _failure, _warning, _default }
+  
+  def markOutline(msg: String) = _outline + msg + _default
+  def markSuccess(msg: String) = _success + msg + _default
+  def markFailure(msg: String) = _failure + msg + _default
+  def markWarning(msg: String) = _warning + msg + _default
+  def markNormal(msg: String)  = _default + msg
+
+  def outline(msg: String) = NestUI outline msg
+  def success(msg: String) = NestUI success msg
+  def failure(msg: String) = NestUI failure msg
+  def warning(msg: String) = NestUI warning msg
+  def  normal(msg: String) = NestUI normal msg
+
+  def verbose(msg: String) = NestUI verbose msg
+  def   debug(msg: String) = NestUI debug msg
+  
+  trait EntityLogging {
+    self: TestEntity =>
+    
+    lazy val logWriter = new LogWriter(logFile)
+    
+    /** Redirect stdout and stderr to logFile, run body, return result.
+     */
+    def loggingOutAndErr[T](body: => T): T = {
+      val log = logFile.printStream(append = true)
+
+      try Console.withOut(log) {
+        Console.withErr(log) {
+          body
+        }
+      }
+      finally log.close()
+    }
+
+    /** What to print in a failure summary.
+     */
+    def failureMessage() = if (diffOutput != "") diffOutput else safeSlurp(logFile)
+    
+    /** For tracing.  Outputs a line describing the next action.  tracePath
+     *  is a path wrapper which prints name or full path depending on verbosity.
+     */
+    def trace(msg: String) = if (isTrace || isDryRun) System.err.println(">> [%s] %s".format(label, msg))
+    
+    def tracePath(path: Path): String   = if (isVerbose) path.path else path.name
+    def tracePath(path: String): String = tracePath(Path(path))
+    
+    /** v == verbose.
+     */
+    def vtrace(msg: String)   = if (isVerbose) trace(msg)
+
+    /** Run body, writes result to logFile.  Any throwable is
+     *  caught, stringified, and written to the log.
+     */
+    def loggingResult(body: => String) =
+      try returning(true)(_ => logFile writeAll body)
+      catch {
+        case x: ControlThrowable      => throw x
+        case x: InterruptedException  => debug(this + " received interrupt, failing.\n") ; false
+        case x: Throwable             => logException(x) 
+      }
+    
+    def throwableToString(x: Throwable): String = {
+      val w = new StringWriter
+      x.printStackTrace(new PrintWriter(w))
+      w.toString
+    }
+    
+    def warnAndLog(str: String) = {
+      warning(toStringTrunc(str, 800))
+      logWriter append str
+    }
+    
+    def warnAndLogException(msg: String, ex: Throwable) =
+      warnAndLog(msg + throwableToString(ex))
+
+    def deleteLog(force: Boolean = false) =
+      if (universe.isNoCleanup && !force) debug("Not cleaning up " + logFile)
+      else logFile.deleteIfExists()
+
+    def onException(x: Throwable)    { logException(x) }
+    def logException(x: Throwable) = {
+      val msg = throwableToString(x)
+      if (!isTerse)
+        normal(msg)
+
+      logWriter append msg
+      false
+    }
+  }
+  
+  /** A writer which doesn't create the file until a write comes in.
+   */
+  class LazilyCreatedWriter(log: File) extends Writer {
+    @volatile private var isCreated = false
+    private lazy val underlying = {
+      isCreated = true
+      log.bufferedWriter()
+    }
+
+    def flush() = if (isCreated) underlying.flush()
+    def close() = if (isCreated) underlying.close()
+    def write(chars: Array[Char], off: Int, len: Int) = {
+      underlying.write(chars, off, len)
+      underlying.flush()
+    }
+  }
+
+  class LogWriter(log: File) extends PrintWriter(new LazilyCreatedWriter(log), true) {
+    override def print(s: String) = {
+      super.print(s)
+      flush()
+    }
+  }
+}
\ No newline at end of file
diff --git a/src/partest-alternative/scala/tools/partest/nest/StreamAppender.scala b/src/partest-alternative/scala/tools/partest/nest/StreamAppender.scala
new file mode 100644
index 0000000..a1177ae
--- /dev/null
+++ b/src/partest-alternative/scala/tools/partest/nest/StreamAppender.scala
@@ -0,0 +1,94 @@
+/* NEST (New Scala Test)
+ * Copyright 2007-2010 LAMP/EPFL
+ * @author Philipp Haller
+ */
+
+// $Id$
+
+package scala.tools.partest
+package nest
+
+import java.io._
+
+object StreamAppender {
+  def wrapIn(in: InputStream): BufferedReader = new BufferedReader(new InputStreamReader(in))
+  def wrapIn(reader: Reader): BufferedReader = new BufferedReader(reader)
+  def wrapIn(str: String): BufferedReader = new BufferedReader(new StringReader(str))
+  
+  def wrapOut(out: OutputStream): PrintWriter = new PrintWriter(new OutputStreamWriter(out), true)
+  def wrapOut(writer: Writer): PrintWriter = new PrintWriter(writer, true)
+  def wrapOut(): PrintWriter = wrapOut(new StringWriter)
+
+  def apply(reader: BufferedReader, writer: Writer): StreamAppender =
+    new StreamAppender(reader, wrapOut(writer))
+
+  def apply(reader: Reader, writer: Writer): StreamAppender =
+    apply(wrapIn(reader), writer)
+  
+  def apply(in: InputStream, writer: Writer): StreamAppender =
+    apply(wrapIn(in), writer)
+  
+  def apply(str: String, writer: Writer): StreamAppender =
+    apply(wrapIn(str), writer)
+  
+  def apply(in: File, out: File): StreamAppender =
+    apply(new FileReader(in), new FileWriter(out))
+
+  def appendToString(in1: InputStream, in2: InputStream): String = {
+    val swriter1 = new StringWriter
+    val swriter2 = new StringWriter
+    val app1 = StreamAppender(wrapIn(in1), swriter1)
+    val app2 = StreamAppender(wrapIn(in2), swriter2)
+
+    val async = new Thread(app2)
+    async.start()
+    app1.run()
+    async.join()
+    swriter1.toString + swriter2.toString
+  }
+/*
+  private def inParallel(t1: Runnable, t2: Runnable, t3: Runnable) {
+    val thr1 = new Thread(t1)
+    val thr2 = new Thread(t2)
+    thr1.start()
+    thr2.start()
+    t3.run()
+    thr1.join()
+    thr2.join()
+  }
+*/
+  private def inParallel(t1: Runnable, t2: Runnable) {
+    val thr = new Thread(t2)
+    thr.start()
+    t1.run()
+    thr.join()
+  }
+
+  def concat(in: InputStream, err: InputStream, out: OutputStream) = new Runnable {
+    override def run() {
+      val outWriter = wrapOut(out)
+      val inApp = StreamAppender(in, outWriter)
+
+      val errStringWriter = new StringWriter
+      val errApp = StreamAppender(wrapIn(err), errStringWriter)
+
+      inParallel(inApp, errApp)
+
+      // append error string to out
+      StreamAppender(errStringWriter.toString, outWriter).run()
+    }
+  }
+}
+
+class StreamAppender(reader: BufferedReader, writer: PrintWriter) extends Runnable {
+  override def run() = runAndMap(identity)
+  private def lines() = Iterator continually reader.readLine() takeWhile (_ != null)
+  def closeAll() = {
+    reader.close()
+    writer.close()
+  }
+
+  def runAndMap(f: String => String) =
+    try lines() map f foreach (writer println _)
+    catch { case e: IOException => e.printStackTrace() }
+}
diff --git a/src/partest-alternative/scala/tools/partest/package.scala b/src/partest-alternative/scala/tools/partest/package.scala
new file mode 100644
index 0000000..0a2f2f9
--- /dev/null
+++ b/src/partest-alternative/scala/tools/partest/package.scala
@@ -0,0 +1,45 @@
+/* NEST (New Scala Test)
+ * Copyright 2007-2010 LAMP/EPFL
+ */
+
+package scala.tools
+
+import nsc.io.{ File, Path, Process, Directory }
+import java.nio.charset.CharacterCodingException
+
+package object partest {  
+  /** The CharacterCodingExceptions are thrown at least on windows trying
+   *  to read a file like script/utf-8.scala
+   */
+  private[partest] def safeSlurp(f: File) = 
+    try if (f.exists) f.slurp() else ""
+    catch { case _: CharacterCodingException  => "" }
+
+  private[partest] def safeLines(f: File)     = safeSlurp(f) split """\r\n|\r|\n""" toList
+  private[partest] def safeArgs(f: File)      = toArgs(safeSlurp(f))  
+  private[partest] def isJava(f: Path)        = f.isFile && (f hasExtension "java")
+  private[partest] def isScala(f: Path)       = f.isFile && (f hasExtension "scala")
+  private[partest] def isJavaOrScala(f: Path) = isJava(f) || isScala(f)
+  
+  private[partest] def toArgs(line: String) = cmd toArgs line
+  private[partest] def fromArgs(args: List[String]) = cmd fromArgs args
+
+  /** Strings, argument lists, etc. */
+  
+  private[partest] def fromAnyArgs(args: List[Any]) = args mkString " " // separate to avoid accidents
+  private[partest] def toStringTrunc(x: Any, max: Int = 240) = {
+    val s = x.toString
+    if (s.length < max) s
+    else (s take max) + " [...]"
+  }
+  private[partest] def setProp(k: String, v: String) = scala.util.Properties.setProp(k, v)
+
+  /** Pretty self explanatory. */
+  def printAndExit(msg: String): Unit = {
+    println(msg)
+    exit(1)
+  }
+
+  /** Apply a function and return the passed value */
+  def returning[T](x: T)(f: T => Unit): T = { f(x) ; x }
+}
\ No newline at end of file
diff --git a/src/partest-alternative/scala/tools/partest/util/package.scala b/src/partest-alternative/scala/tools/partest/util/package.scala
new file mode 100644
index 0000000..d56542e
--- /dev/null
+++ b/src/partest-alternative/scala/tools/partest/util/package.scala
@@ -0,0 +1,61 @@
+/* NEST (New Scala Test)
+ * Copyright 2007-2010 LAMP/EPFL
+ */
+
+package scala.tools
+package partest
+
+import java.util.{ Timer, TimerTask }
+import java.io.StringWriter
+import nsc.io._
+
+/** Misc code still looking for a good home.
+ */
+package object util {
+  
+  def allPropertiesString() = javaHashtableToString(System.getProperties)
+
+  private def javaHashtableToString(table: java.util.Hashtable[_,_]) = {
+    import collection.JavaConversions._
+    (table.toList map { case (k, v) => "%s -> %s\n".format(k, v) }).sorted mkString
+  }
+  
+  def filesToSet(pre: String, fs: List[String]): Set[AbstractFile] =
+    fs flatMap (x => Option(AbstractFile getFile (Path(pre) / x).path)) toSet
+  
+  /** Copies one Path to another Path, trying to be sensible when one or the
+   *  other is a Directory.  Returns true if it believes it succeeded.
+   */
+  def copyPath(from: Path, to: Path): Boolean = {
+    if (!to.parent.isDirectory)
+      to.parent.createDirectory(force = true)
+    
+    def copyDir = {
+      val sub = to / from.name createDirectory true
+      from.toDirectory.list forall (x => copyPath(x, sub))
+    }
+    (from.isDirectory, to.isDirectory) match {
+      case (true, true)   => copyDir
+      case (true, false)  => false
+      case (false, true)  => from.toFile copyTo (to / from.name)
+      case (false, false) => from.toFile copyTo to
+    }
+  }
+
+  /**
+  * Compares two files using a Java implementation of the GNU diff
+  * available at http://www.bmsi.com/java/#diff.
+  *
+  * @param  f1  the first file to be compared
+  * @param  f2  the second file to be compared
+  * @return the text difference between the compared files
+  */
+  def diffFiles(f1: File, f2: File): String = {
+    val diffWriter = new StringWriter
+    val args = Array(f1.toAbsolute.path, f2.toAbsolute.path)
+
+    io.DiffPrint.doDiff(args, diffWriter)
+    val result = diffWriter.toString
+    if (result == "No differences") "" else result
+  }
+}
diff --git a/src/partest/README b/src/partest/README
index 9064397..81876fc 100644
--- a/src/partest/README
+++ b/src/partest/README
@@ -1,14 +1,11 @@
 How partest choses the compiler / library:
 
-  * ''-Dscalatest.build=build/four-pack'' -> will search for libraries in
+  * ''-Dpartest.build=build/four-pack'' -> will search for libraries in
     ''lib'' directory of given path
-  * ''--pack'' -> will set ''scalatest.build=build/pack'', and run all tests.
+  * ''--pack'' -> will set ''partest.build=build/pack'', and run all tests.
     add ''--[kind]'' to run a selected set of tests.
-  * ''--[four]'' -> will set ''scalatest.build=build-four-pack'' and
-    ''scalatest.scalac_opts=-target:jvm-1.4'', and run all tests.
-    add ''--kind'' to run a selected set of tests.
   * auto detection:
-    - scalatest.build property -> ''bin'' / ''lib'' directories
+    - partest.build property -> ''bin'' / ''lib'' directories
     - distribution (''dists/latest'')
     - supersabbus pack (''build/pack'')
     - sabbus quick (''build/quick'')
@@ -26,10 +23,10 @@ Other arguments:
   * --neg          next files test a compilation failure
   * --run          next files test the interpreter and all backends
   * --jvm          next files test the JVM backend
-  * --jvm5         next files test the JVM backend
   * --res          next files test the resident compiler
+  * --buildmanager next files test the build manager
   * --shootout     next files are shootout tests
   * --script       next files test the script runner
-  * ''-Dscalatest.scalac_opts=-target:jvm-1.4'' -> add compiler options
+  * ''-Dpartest.scalac_opts=...'' -> add compiler options
   * ''--verbose'' -> print verbose messages
   * ''-Dpartest.debug=true'' -> print debug messages
diff --git a/src/partest/scala/tools/partest/PartestDefaults.scala b/src/partest/scala/tools/partest/PartestDefaults.scala
new file mode 100644
index 0000000..7cff3a7
--- /dev/null
+++ b/src/partest/scala/tools/partest/PartestDefaults.scala
@@ -0,0 +1,30 @@
+package scala.tools
+package partest
+
+import nsc.io.{ File, Path, Process, Directory }
+import util.{ PathResolver }
+import nsc.Properties.{ propOrElse, propOrNone, propOrEmpty }
+
+object PartestDefaults {
+  import nsc.Properties._
+  private def wrapAccessControl[T](body: => Option[T]): Option[T] =
+    try body catch { case _: java.security.AccessControlException => None }
+  
+  def testRootName  = propOrNone("partest.root")
+  def srcDirName    = propOrElse("partest.srcdir", "files")
+  def testRootDir   = testRootName map (x => Directory(x))
+
+  def classPath   = PathResolver.Environment.javaUserClassPath    // XXX
+
+  def javaCmd     = propOrElse("partest.javacmd", "java")
+  def javacCmd    = propOrElse("partest.javac_cmd", "javac")
+  def javaOpts    = propOrElse("partest.java_opts", "")
+  def scalacOpts  = propOrElse("partest.scalac_opts", "-deprecation")
+
+  def testBuild   = propOrNone("partest.build")
+  def errorCount  = propOrElse("partest.errors", "0").toInt
+  def numActors   = propOrElse("partest.actors", "8").toInt
+  def poolSize    = wrapAccessControl(propOrNone("actors.corePoolSize"))
+
+  def timeout     = "1200000"
+}
diff --git a/src/partest/scala/tools/partest/PartestTask.scala b/src/partest/scala/tools/partest/PartestTask.scala
index 2137f3e..113088f 100644
--- a/src/partest/scala/tools/partest/PartestTask.scala
+++ b/src/partest/scala/tools/partest/PartestTask.scala
@@ -1,314 +1,287 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala Parallel Testing               **
-**    / __/ __// _ | / /  / _ |    (c) 2007-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: PartestTask.scala 16932 2009-01-16 16:31:52Z phaller $
+// $Id$
 
-package scala.tools.partest
+package scala.tools
+package partest
 
 import scala.actors.Actor._
+import scala.util.Properties.setProp
+import scala.tools.nsc.io.{ Directory, Path => SPath }
+import nsc.Settings
+import nsc.util.ClassPath
+import util.PathResolver
+import scala.tools.ant.sabbus.CompilationPathProperty
 
 import java.io.File
 import java.net.URLClassLoader
+import java.lang.reflect.Method
 
 import org.apache.tools.ant.Task
 import org.apache.tools.ant.types.{Path, Reference, FileSet}
 
-class PartestTask extends Task {
+class PartestTask extends Task with CompilationPathProperty {
 
-  def addConfiguredPosTests(input: FileSet): Unit =
+  def addConfiguredPosTests(input: FileSet) {
     posFiles = Some(input)
+  }
 
-  def addConfiguredPos5Tests(input: FileSet): Unit =
-    pos5Files = Some(input)
-
-  def addConfiguredNegTests(input: FileSet): Unit =
+  def addConfiguredNegTests(input: FileSet) {
     negFiles = Some(input)
+  }
 
-  def addConfiguredRunTests(input: FileSet): Unit =
+  def addConfiguredRunTests(input: FileSet) {
     runFiles = Some(input)
+  }
 
-  def addConfiguredJvmTests(input: FileSet): Unit =
+  def addConfiguredJvmTests(input: FileSet) {
     jvmFiles = Some(input)
+  }
 
-  def addConfiguredJvm5Tests(input: FileSet): Unit =
-    jvm5Files = Some(input)
-
-  def addConfiguredResidentTests(input: FileSet): Unit =
+  def addConfiguredResidentTests(input: FileSet) {
     residentFiles = Some(input)
+  }
+  
+  def addConfiguredBuildManagerTests(input: FileSet) {
+    buildManagerFiles = Some(input)
+  }
+  
+  def addConfiguredScalacheckTests(input: FileSet) {
+    scalacheckFiles = Some(input)
+  }
 
-  def addConfiguredScriptTests(input: FileSet): Unit =
+  def addConfiguredScriptTests(input: FileSet) {
     scriptFiles = Some(input)
+  }
 
-  def addConfiguredShootoutTests(input: FileSet): Unit =
+  def addConfiguredShootoutTests(input: FileSet) {
     shootoutFiles = Some(input)
+  }
+
+  def addConfiguredScalapTests(input: FileSet) {
+    scalapFiles = Some(input)
+  }
+  
+  def setSrcDir(input: String) {
+    srcDir = Some(input)
+  }
 
-  def setClasspath(input: Path): Unit =
+  def setClasspath(input: Path) {
     if (classpath.isEmpty)
       classpath = Some(input)
     else
       classpath.get.append(input)
-  
+  }
+
   def createClasspath(): Path = {
     if (classpath.isEmpty) classpath = Some(new Path(getProject()))
     classpath.get.createPath()
   }
   
-  def setClasspathref(input: Reference): Unit =
+  def setClasspathref(input: Reference) {
     createClasspath().setRefid(input)
+  }
   
-  def setShowLog(input: Boolean): Unit =
+  def setShowLog(input: Boolean) {
     showLog = input
+  }
   
-  def setShowDiff(input: Boolean): Unit =
+  def setShowDiff(input: Boolean) {
     showDiff = input
+  }
   
-  def setErrorOnFailed(input: Boolean): Unit =
+  def setErrorOnFailed(input: Boolean) {
     errorOnFailed = input
+  }
     
-  def setJavaCmd(input: File): Unit =
+  def setJavaCmd(input: File) {
     javacmd = Some(input)
+  }
 
-  def setJavacCmd(input: File): Unit =
+  def setJavacCmd(input: File) {
     javaccmd = Some(input)
+  }
 
-  def setScalacOpts(opts: String): Unit =
+  def setScalacOpts(opts: String) {
     scalacOpts = Some(opts)
+  }
 
-  def setTimeout(delay: String): Unit =
+  def setTimeout(delay: String) {
     timeout = Some(delay)
+  }
 
-  def setDebug(input: Boolean): Unit =
+  def setDebug(input: Boolean) {
     debug = input
+  }
+  
+  def setJUnitReportDir(input: File) {
+    jUnitReportDir = Some(input)
+  }
 
   private var classpath: Option[Path] = None
+  private var srcDir: Option[String] = None
   private var javacmd: Option[File] = None
   private var javaccmd: Option[File] = None
   private var showDiff: Boolean = false
   private var showLog: Boolean = false
   private var runFailed: Boolean = false
   private var posFiles: Option[FileSet] = None
-  private var pos5Files: Option[FileSet] = None
   private var negFiles: Option[FileSet] = None
   private var runFiles: Option[FileSet] = None
   private var jvmFiles: Option[FileSet] = None
-  private var jvm5Files: Option[FileSet] = None
   private var residentFiles: Option[FileSet] = None
+  private var buildManagerFiles: Option[FileSet] = None
+  private var scalacheckFiles: Option[FileSet] = None
   private var scriptFiles: Option[FileSet] = None
   private var shootoutFiles: Option[FileSet] = None
+  private var scalapFiles: Option[FileSet] = None
   private var errorOnFailed: Boolean = false
   private var scalacOpts: Option[String] = None
   private var timeout: Option[String] = None
+  private var jUnitReportDir: Option[File] = None
   private var debug = false
 
-  private def getFilesAndDirs(fileSet: Option[FileSet]): Array[File] =
-    if (!fileSet.isEmpty) {
-      val files = fileSet.get
-      val dir = files.getDir(getProject)
-      val fileTests = (files.getDirectoryScanner(getProject).getIncludedFiles map { fs =>
-        new File(dir, fs) })
-      val dirTests = dir.listFiles(new java.io.FileFilter {
-        def accept(file: File) =
-          file.isDirectory &&
-          (!file.getName().equals(".svn")) &&
-          (!file.getName().endsWith(".obj"))
-      })
-      (dirTests ++ fileTests).toArray
-    }
-    else
-      Array()
-
-  private def getPosFiles: Array[File] =
-    getFilesAndDirs(posFiles)
-
-  private def getPos5Files: Array[File] =
-    getFilesAndDirs(pos5Files)
-  
-  private def getNegFiles: Array[File] =
-    if (!negFiles.isEmpty) {
-      val files = negFiles.get
-      (files.getDirectoryScanner(getProject).getIncludedFiles map { fs => new File(files.getDir(getProject), fs) })
-    }
-    else
-      Array()
-  
-  private def getRunFiles: Array[File] =
-    if (!runFiles.isEmpty) {
-      val files = runFiles.get
-      (files.getDirectoryScanner(getProject).getIncludedFiles map { fs => new File(files.getDir(getProject), fs) })
-    }
-    else
-      Array()
-
-  private def getJvmFiles: Array[File] =
-    getFilesAndDirs(jvmFiles)
-  
-  private def getJvm5Files: Array[File] =
-    getFilesAndDirs(jvm5Files)
-  
-  private def getResidentFiles: Array[File] =
-    if (!residentFiles.isEmpty) {
-      val files = residentFiles.get
-      (files.getDirectoryScanner(getProject).getIncludedFiles map { fs => new File(files.getDir(getProject), fs) })
-    }
-    else
-      Array()
-
-  private def getScriptFiles: Array[File] =
-    if (!scriptFiles.isEmpty) {
-      val files = scriptFiles.get
-      (files.getDirectoryScanner(getProject).getIncludedFiles map { fs => new File(files.getDir(getProject), fs) })
-    }
-    else
-      Array()
-
-  private def getShootoutFiles: Array[File] =
-    if (!shootoutFiles.isEmpty) {
-      val files = shootoutFiles.get
-      (files.getDirectoryScanner(getProject).getIncludedFiles map { fs => new File(files.getDir(getProject), fs) })
-    }
-    else
-      Array()
+  def fileSetToDir(fs: FileSet) = Directory(fs getDir getProject)
+  def fileSetToArray(fs: FileSet): Array[SPath] = {
+    val root = fileSetToDir(fs)
+    (fs getDirectoryScanner getProject).getIncludedFiles map (root / _)
+  }
 
-  override def execute(): Unit = {
-    if (debug)
-      System.setProperty("partest.debug", "true")
+  private def getFiles(fileSet: Option[FileSet]): Array[File] = fileSet match {
+    case None     => Array()
+    case Some(fs) => fileSetToArray(fs) filterNot (_ hasExtension "log") map (_.jfile)
+  }
 
-    if (classpath.isEmpty)
-      error("Mandatory attribute 'classpath' is not set.")
+  private def getFilesAndDirs(fileSet: Option[FileSet]): Array[File] = fileSet match {
+    case None     => Array()
+    case Some(fs) =>
+      def shouldExclude(name: String) = (name endsWith ".obj") || (name startsWith ".")
+    
+      val fileTests = getFiles(Some(fs)) filterNot (x => shouldExclude(x.getName))
+      val dirTests: Iterator[SPath] = fileSetToDir(fs).dirs filterNot (x => shouldExclude(x.name))
+      val dirResult = dirTests.toList.toArray map (_.jfile)
       
-    val scalaLibrary =
-      (classpath.get.list map { fs => new File(fs) }) find { f =>
+      dirResult ++ fileTests
+  }
+
+  private def getPosFiles          = getFilesAndDirs(posFiles)
+  private def getNegFiles          = getFilesAndDirs(negFiles)
+  private def getRunFiles          = getFiles(runFiles)
+  private def getJvmFiles          = getFilesAndDirs(jvmFiles)
+  private def getResidentFiles     = getFiles(residentFiles)
+  private def getBuildManagerFiles = getFilesAndDirs(buildManagerFiles)
+  private def getScalacheckFiles   = getFiles(scalacheckFiles)
+  private def getScriptFiles       = getFiles(scriptFiles)
+  private def getShootoutFiles     = getFiles(shootoutFiles)
+  private def getScalapFiles       = getFiles(scalapFiles)
+
+  override def execute() {
+    if (isPartestDebug)
+      setProp("partest.debug", "true")
+    
+    srcDir foreach (x => setProp("partest.srcdir", x))
+    
+    val classpath = this.compilationPath getOrElse error("Mandatory attribute 'compilationPath' is not set.")
+    
+    val scalaLibrary = {
+      (classpath.list map { fs => new File(fs) }) find { f =>
         f.getName match {
           case "scala-library.jar" => true
           case "library" if (f.getParentFile.getName == "classes") => true
           case _ => false
         }
       }
+    } getOrElse error("Provided classpath does not contain a Scala library.") 
     
-    if (scalaLibrary.isEmpty)
-      error("Provided classpath does not contain a Scala library.") 
-    
-    val classloader = this.getClass.getClassLoader
-    
-    val antRunner: AnyRef =
-      classloader.loadClass("scala.tools.partest.nest.AntRunner").newInstance().asInstanceOf[AnyRef]
-    val antFileManager: AnyRef =
-      antRunner.getClass.getMethod("fileManager", Array[Class[_]](): _*).invoke(antRunner, Array[Object](): _*)
-    
-    val runMethod =
-      antRunner.getClass.getMethod("reflectiveRunTestsForFiles", Array(classOf[Array[File]], classOf[String]): _*)
-  
-    def runTestsForFiles(kindFiles: Array[File], kind: String): (Int, Int) = {
-      val result = runMethod.invoke(antRunner, Array(kindFiles, kind): _*).asInstanceOf[Int]
-      (result >> 16, result & 0x00FF)
-    }
-    
-    def setFileManagerBooleanProperty(name: String, value: Boolean) = {
-      val setMethod =
-        antFileManager.getClass.getMethod(name+"_$eq", Array(classOf[Boolean]): _*)
-      setMethod.invoke(antFileManager, Array(java.lang.Boolean.valueOf(value)): _*)
-    }
+    val antRunner = new scala.tools.partest.nest.AntRunner
+    val antFileManager = antRunner.fileManager
     
-    def setFileManagerStringProperty(name: String, value: String) = {
-      val setMethod =
-        antFileManager.getClass.getMethod(name+"_$eq", Array(classOf[String]): _*)
-      setMethod.invoke(antFileManager, Array(value): _*)
-    }
+    antFileManager.showDiff = showDiff
+    antFileManager.showLog = showLog
+    antFileManager.failed = runFailed
+    antFileManager.CLASSPATH = ClassPath.join(classpath.list: _*)
+    antFileManager.LATEST_LIB = scalaLibrary.getAbsolutePath
     
-    setFileManagerBooleanProperty("showDiff", showDiff)
-    setFileManagerBooleanProperty("showLog", showLog)
-    setFileManagerBooleanProperty("failed", runFailed)
-    if (!javacmd.isEmpty)
-      setFileManagerStringProperty("JAVACMD", javacmd.get.getAbsolutePath)
-    if (!javaccmd.isEmpty)
-      setFileManagerStringProperty("JAVAC_CMD", javaccmd.get.getAbsolutePath)
-    setFileManagerStringProperty("CLASSPATH", classpath.get.list.mkString(File.pathSeparator))
-    setFileManagerStringProperty("LATEST_LIB", scalaLibrary.get.getAbsolutePath)
-    if (!scalacOpts.isEmpty)
-      setFileManagerStringProperty("SCALAC_OPTS", scalacOpts.get)
-    if (!timeout.isEmpty)
-      setFileManagerStringProperty("timeout", timeout.get)
-
-    var allSucesses: Int = 0
-    var allFailures: Int = 0
+    javacmd foreach (x => antFileManager.JAVACMD = x.getAbsolutePath)
+    javaccmd foreach (x => antFileManager.JAVAC_CMD = x.getAbsolutePath)
+    scalacOpts foreach (antFileManager.SCALAC_OPTS = _)
+    timeout foreach (antFileManager.timeout = _)
     
-    if (getPosFiles.size > 0) {
-      log("Compiling files that are expected to build")
-      val (successes, failures) = runTestsForFiles(getPosFiles, "pos")
-      allSucesses += successes
-      allFailures += failures
-    }
-
-    if (getPos5Files.size > 0) {
-      log("Compiling files that are expected to build")
-      val (successes, failures) = runTestsForFiles(getPos5Files, "pos")
-      allSucesses += successes
-      allFailures += failures
-    }
-    
-    if (getNegFiles.size > 0) {
-      log("Compiling files that are expected to fail")
-      val (successes, failures) = runTestsForFiles(getNegFiles, "neg")
-      allSucesses += successes
-      allFailures += failures
-    }
-    
-    if (getRunFiles.size > 0) {
-      log("Compiling and running files")
-      val (successes, failures) = runTestsForFiles(getRunFiles, "run")
-      allSucesses += successes
-      allFailures += failures
-    }
-
-    if (getJvmFiles.size > 0) {
-      log("Compiling and running files")
-      val (successes, failures) = runTestsForFiles(getJvmFiles, "jvm")
-      allSucesses += successes
-      allFailures += failures
-    }
-
-    if (getJvm5Files.size > 0) {
-      log("Compiling and running files")
-      val (successes, failures) = runTestsForFiles(getJvm5Files, "jvm5")
-      allSucesses += successes
-      allFailures += failures
-    }
+    type TFSet = (Array[File], String, String)
+    val testFileSets = List(
+      (getPosFiles, "pos", "Compiling files that are expected to build"),
+      (getNegFiles, "neg", "Compiling files that are expected to fail"),
+      (getRunFiles, "run", "Compiling and running files"),
+      (getJvmFiles, "jvm", "Compiling and running files"),
+      (getResidentFiles, "res", "Running resident compiler scenarii"),
+      (getBuildManagerFiles, "buildmanager", "Running Build Manager scenarii"),
+      (getScalacheckFiles, "scalacheck", "Running scalacheck tests"),
+      (getScriptFiles, "script", "Running script files"),
+      (getShootoutFiles, "shootout", "Running shootout tests"),
+      (getScalapFiles, "scalap", "Running scalap tests")
+    )
     
-    if (getResidentFiles.size > 0) {
-      log("Running resident compiler scenarii")
-      val (successes, failures) = runTestsForFiles(getResidentFiles, "res")
-      allSucesses += successes
-      allFailures += failures
-    }
-
-    if (getScriptFiles.size > 0) {
-      log("Running script files")
-      val (successes, failures) = runTestsForFiles(getScriptFiles, "script")
-      allSucesses += successes
-      allFailures += failures
-    }
+    def runSet(set: TFSet): (Int, Int, Iterable[String]) = {
+      val (files, name, msg) = set
+      if (files.isEmpty) (0, 0, List())
+      else {
+        log(msg)
+        val results: Iterable[(String, Int)] = antRunner.reflectiveRunTestsForFiles(files, name)
+        val (succs, fails) = resultsToStatistics(results)
+
+        val failed: Iterable[String] = results collect {
+          case (path, 1)    => path + " [FAILED]"
+          case (path, 2)    => path + " [TIMOUT]"
+        }
 
-    if (getShootoutFiles.size > 0) {
-      log("Running shootout tests")
-      val (successes, failures) = runTestsForFiles(getShootoutFiles, "shootout")
-      allSucesses += successes
-      allFailures += failures
+        // create JUnit Report xml files if directory was specified
+        jUnitReportDir foreach { d =>
+          d.mkdir
+          
+          val report = testReport(name, results, succs, fails)
+          scala.xml.XML.save(d.getAbsolutePath+"/"+name+".xml", report)
+        }
+        
+        (succs, fails, failed)
+      }
     }
 
-    if ((getPosFiles.size + getNegFiles.size + getRunFiles.size + getResidentFiles.size + getScriptFiles.size + getShootoutFiles.size) == 0)
-      log("There where no tests to run.")
-    else if (allFailures == 0)
-      log("Test suite finished with no failures.")
-    else if (errorOnFailed)
-      error("Test suite finished with " + allFailures + " case" + (if (allFailures > 1) "s" else "") + " failing.")
-    else
-      log("Test suite finished with " + allFailures + " case" + (if (allFailures > 1) "s" else "") + " failing.")
+    val _results = testFileSets map runSet
+    val allSuccesses = _results map (_._1) sum
+    val allFailures = _results map (_._2) sum
+    val allFailedPaths = _results flatMap (_._3)
+
+    def f = if (errorOnFailed && allFailures > 0) error(_) else log(_: String)
+    def s = if (allFailures > 1) "s" else ""
+    val msg =
+      if (allFailures > 0)
+        "Test suite finished with %d case%s failing:\n".format(allFailures, s)+
+        allFailedPaths.mkString("\n")
+      else if (allSuccesses == 0) "There were no tests to run."
+      else "Test suite finished with no failures."
     
+    f(msg)
   }
-  
+  def oneResult(res: (String, Int)) =
+    <testcase name={res._1}>{
+  	  res._2 match {
+  	    case 0 => scala.xml.NodeSeq.Empty
+        case 1 => <failure message="Test failed"/>
+        case 2 => <failure message="Test timed out"/>
+  	  } 
+  	}</testcase>
+   
+  def testReport(kind: String, results: Iterable[(String, Int)], succs: Int, fails: Int) =
+    <testsuite name={kind} tests={(succs + fails).toString} failures={fails.toString}>
+  	  <properties/>
+  	  {
+  	    results.map(oneResult(_))
+  	  }
+    </testsuite>
 }
diff --git a/src/partest/scala/tools/partest/nest/AntRunner.scala b/src/partest/scala/tools/partest/nest/AntRunner.scala
index c36f45d..f409c9a 100644
--- a/src/partest/scala/tools/partest/nest/AntRunner.scala
+++ b/src/partest/scala/tools/partest/nest/AntRunner.scala
@@ -1,38 +1,29 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala Parallel Testing               **
-**    / __/ __// _ | / /  / _ |    (c) 2007-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: AntRunner.scala 16881 2009-01-09 16:28:11Z cunei $
 
-package scala.tools.partest.nest
-
-import scala.actors.Actor._
+package scala.tools.partest
+package nest
 
 import java.io.File
-import java.net.URLClassLoader
-
-import org.apache.tools.ant.Task
-import org.apache.tools.ant.types.{Path, Reference, FileSet}
+import scala.tools.nsc.io.{ Directory }
 
 class AntRunner extends DirectRunner {
   
   val fileManager = new FileManager {
-    
     var JAVACMD: String = "java"
     var JAVAC_CMD: String = "javac"
     var CLASSPATH: String = _
-    var EXT_CLASSPATH: String = _
     var LATEST_LIB: String = _
-
-  }
-  
-  def reflectiveRunTestsForFiles(kindFiles: Array[File], kind: String): Int = {
-    val (succs, fails) = runTestsForFiles(kindFiles.toList, kind)
-    succs << 16 | fails
+    val testRootPath: String = "test"
+    val testRootDir: Directory = Directory(testRootPath)
   }
   
+  def reflectiveRunTestsForFiles(kindFiles: Array[File], kind: String) = 
+    runTestsForFiles(kindFiles.toList, kind)
 }
diff --git a/src/partest/scala/tools/partest/nest/CompileManager.scala b/src/partest/scala/tools/partest/nest/CompileManager.scala
index be364dc..3ddba89 100644
--- a/src/partest/scala/tools/partest/nest/CompileManager.scala
+++ b/src/partest/scala/tools/partest/nest/CompileManager.scala
@@ -1,270 +1,197 @@
 /* NEST (New Scala Test)
- * Copyright 2007-2009 LAMP/EPFL
+ * Copyright 2007-2010 LAMP/EPFL
  * @author Philipp Haller
  */
 
-// $Id: CompileManager.scala 18847 2009-10-01 07:38:11Z phaller $
+// $Id$
 
-package scala.tools.partest.nest
+package scala.tools.partest
+package nest
 
-import scala.tools.nsc.{Global, Settings, CompilerCommand, FatalError}
-import scala.tools.nsc.reporters.{Reporter, ConsoleReporter}
+import scala.tools.nsc.{ Global, Settings, CompilerCommand, FatalError, io }
+import scala.tools.nsc.reporters.{ Reporter, ConsoleReporter }
+import scala.tools.nsc.util.ClassPath
+import scala.tools.util.PathResolver
+import io.Path
 
-import java.io.{File, BufferedReader, PrintWriter, FileReader, FileWriter, StringWriter}
+import java.io.{ File, BufferedReader, PrintWriter, FileReader, Writer, FileWriter, StringWriter }
+import File.pathSeparator
 
-class ExtConsoleReporter(override val settings: Settings, reader: BufferedReader, var writer: PrintWriter) extends ConsoleReporter(settings, reader, writer) {
-  def this(settings: Settings) = {
-    this(settings, Console.in, new PrintWriter(new FileWriter("/dev/null")))
-  }
-  def hasWarnings: Boolean = WARNING.count != 0
+class ExtConsoleReporter(override val settings: Settings, reader: BufferedReader, var writer: PrintWriter)
+extends ConsoleReporter(settings, reader, writer) { 
+  def this(settings: Settings) = this(settings, Console.in, new PrintWriter(new FileWriter("/dev/null")))
 }
 
 abstract class SimpleCompiler {
   def compile(out: Option[File], files: List[File], kind: String, log: File): Boolean
 }
 
-class TestSettings(fileMan: FileManager) extends {
-  override val bootclasspathDefault =
-    System.getProperty("sun.boot.class.path", "") + File.pathSeparator +
-    fileMan.LATEST_LIB
-  override val extdirsDefault =
-    System.getProperty("java.ext.dirs", "")
-} with Settings(x => ())
+class TestSettings(fileMan: FileManager) extends Settings(_ => ()) { }
 
 class DirectCompiler(val fileManager: FileManager) extends SimpleCompiler {
   def newGlobal(settings: Settings, reporter: Reporter): Global =
     new Global(settings, reporter)
 
   def newGlobal(settings: Settings, logWriter: FileWriter): Global = {
-    val rep = new ExtConsoleReporter(settings,
-                                     Console.in,
-                                     new PrintWriter(logWriter))
+    val rep = newReporter(settings, logWriter)
     rep.shortname = true
     newGlobal(settings, rep)
   }
 
-  def newSettings = {
+  def newSettings(out: Option[String]) = {
     val settings = new TestSettings(fileManager)
+    settings.usejavacp.value = true
     settings.deprecation.value = true
     settings.nowarnings.value = false
-    settings.encoding.value = "iso-8859-1"
+    settings.encoding.value = "ISO-8859-1"    // XXX why?
+
+    val classpathElements = settings.classpath.value :: fileManager.LATEST_LIB :: out.toList
+    settings.classpath.value = ClassPath.join(classpathElements: _*)
+    out foreach (settings.outdir.value = _)
+        
     settings
   }
 
-  def newReporter(sett: Settings) = new ExtConsoleReporter(sett,
-                                                           Console.in,
-                                                           new PrintWriter(new StringWriter))
+  def newReporter(sett: Settings, writer: Writer = new StringWriter) =
+    new ExtConsoleReporter(sett, Console.in, new PrintWriter(writer))
+
+  private def updatePluginPath(options: String): String = {
+    val dir = fileManager.testRootDir
+    def absolutize(path: String) = Path(path) match {
+      case x if x.isAbsolute  => x.path
+      case x                  => (fileManager.testRootDir / x).toAbsolute.path
+    }
+    
+    val (opt1, opt2) = (options split "\\s").toList partition (_ startsWith "-Xplugin:")
+    val plugins = opt1 map (_ stripPrefix "-Xplugin:") flatMap (_ split pathSeparator) map absolutize
+    val pluginOption = if (opt1.isEmpty) Nil else List("-Xplugin:" + (plugins mkString pathSeparator))
+    
+    (opt2 ::: pluginOption) mkString " "
+  }
 
   def compile(out: Option[File], files: List[File], kind: String, log: File): Boolean = {
-    val testSettings = newSettings
+    val testSettings = newSettings(out map (_.getAbsolutePath))
     val logWriter = new FileWriter(log)
     
     // check whether there is a ".flags" file
-    val testBase = {
-      val logBase = fileManager.basename(log.getName)
-      logBase.substring(0, logBase.length-4)
-    }
-    val argsFile = new File(log.getParentFile, testBase+".flags")
-    val argString = if (argsFile.exists) {
-      val fileReader = new FileReader(argsFile)
-      val reader = new BufferedReader(fileReader)
-      val options = reader.readLine()
-      reader.close()
-      options
-    } else ""
+    val flagsFileName = "%s.flags" format (basename(log.getName) dropRight 4) // 4 is "-run" or similar
+    val argString = (io.File(log).parent / flagsFileName) ifFile (x => updatePluginPath(x.slurp())) getOrElse ""
     val allOpts = fileManager.SCALAC_OPTS+" "+argString
+    val args = (allOpts split "\\s").toList
+    
     NestUI.verbose("scalac options: "+allOpts)
-    val args = List.fromArray(allOpts.split("\\s"))
-    val command = new CompilerCommand(args, testSettings, x => {}, false)
+    
+    val command = new CompilerCommand(args, testSettings)
     val global = newGlobal(command.settings, logWriter)
     val testRep: ExtConsoleReporter = global.reporter.asInstanceOf[ExtConsoleReporter]
-
-    val test: TestFile = kind match {
-      case "pos"      => PosTestFile(files(0), fileManager, out.isEmpty)
-      case "neg"      => NegTestFile(files(0), fileManager, out.isEmpty)
-      case "run"      => RunTestFile(files(0), fileManager, out.isEmpty)
-      case "jvm"      => JvmTestFile(files(0), fileManager, out.isEmpty)
-      case "jvm5"     => Jvm5TestFile(files(0), fileManager, out.isEmpty)
-      case "shootout" => ShootoutTestFile(files(0), fileManager, out.isEmpty)
-      case "scalacheck" =>
-        ScalaCheckTestFile(files(0), fileManager, out.isEmpty)
-    }
-    test.defineSettings(command.settings)
-    out match {
-      case Some(outDir) =>
-        command.settings.outdir.value = outDir.getAbsolutePath
-        command.settings.classpath.value = command.settings.classpath.value+
-          File.pathSeparator+outDir.getAbsolutePath
-      case None =>
-        // do nothing
+    
+    val testFileFn: (File, FileManager) => TestFile = kind match {
+      case "pos"        => PosTestFile.apply
+      case "neg"        => NegTestFile.apply
+      case "run"        => RunTestFile.apply
+      case "jvm"        => JvmTestFile.apply
+      case "shootout"   => ShootoutTestFile.apply
+      case "scalap"     => ScalapTestFile.apply
+      case "scalacheck" => ScalaCheckTestFile.apply
     }
-
-    val toCompile = files.map(_.getPath)
+    val test: TestFile = testFileFn(files.head, fileManager)
+    test.defineSettings(command.settings, out.isEmpty)
+    val toCompile = files map (_.getPath)
+    
     try {
       NestUI.verbose("compiling "+toCompile)
-      try {
-        (new global.Run) compile toCompile
-      } catch {
+      try new global.Run compile toCompile
+      catch {
         case FatalError(msg) =>
           testRep.error(null, "fatal error: " + msg)
       }
+      
       testRep.printSummary
       testRep.writer.flush
       testRep.writer.close
-    } catch {
-      case e: Exception =>
+    }
+    catch {
+      case e =>
         e.printStackTrace()
         return false
-    } finally {
-      logWriter.close()
     }
+    finally logWriter.close()
+    
     !testRep.hasErrors
   }
 }
 
-class ReflectiveCompiler(val fileManager: ConsoleFileManager) extends SimpleCompiler {
-  import fileManager.{latestCompFile, latestPartestFile}
-
-  val sepUrls = Array(latestCompFile.toURL, latestPartestFile.toURL)
-  //NestUI.verbose("constructing URLClassLoader from URLs "+latestCompFile+" and "+latestPartestFile)
-
-  val sepLoader = new java.net.URLClassLoader(sepUrls, null)
-
-  val sepCompilerClass =
-    sepLoader.loadClass("scala.tools.partest.nest.DirectCompiler")
-  val sepCompiler = sepCompilerClass.newInstance()
-
-  // needed for reflective invocation
-  val fileClass = Class.forName("java.io.File")
-  val stringClass = Class.forName("java.lang.String")
-  val sepCompileMethod =
-    sepCompilerClass.getMethod("compile", Array(fileClass, stringClass): _*)
-  val sepCompileMethod2 =
-    sepCompilerClass.getMethod("compile", Array(fileClass, stringClass, fileClass): _*)
-
-  /* This method throws java.lang.reflect.InvocationTargetException
-   * if the compiler crashes.
-   * This exception is handled in the shouldCompile and shouldFailCompile
-   * methods of class CompileManager.
-   */
-  def compile(out: Option[File], files: List[File], kind: String, log: File): Boolean = {
-    val fileArgs: Array[AnyRef] = Array(out, files, kind, log)
-    val res = sepCompileMethod2.invoke(sepCompiler, fileArgs: _*).asInstanceOf[java.lang.Boolean]
-    res.booleanValue()
-  }
-}
+// class ReflectiveCompiler(val fileManager: ConsoleFileManager) extends SimpleCompiler {
+//   import fileManager.{latestCompFile, latestPartestFile}
+// 
+//   val sepUrls = Array(latestCompFile.toURI.toURL, latestPartestFile.toURI.toURL)
+//   //NestUI.verbose("constructing URLClassLoader from URLs "+latestCompFile+" and "+latestPartestFile)
+// 
+//   val sepLoader = new java.net.URLClassLoader(sepUrls, null)
+// 
+//   val sepCompilerClass =
+//     sepLoader.loadClass("scala.tools.partest.nest.DirectCompiler")
+//   val sepCompiler = sepCompilerClass.newInstance()
+// 
+//   // needed for reflective invocation
+//   val fileClass = Class.forName("java.io.File")
+//   val stringClass = Class.forName("java.lang.String")
+//   val sepCompileMethod =
+//     sepCompilerClass.getMethod("compile", fileClass, stringClass)
+//   val sepCompileMethod2 =
+//     sepCompilerClass.getMethod("compile", fileClass, stringClass, fileClass)
+// 
+//   /* This method throws java.lang.reflect.InvocationTargetException
+//    * if the compiler crashes.
+//    * This exception is handled in the shouldCompile and shouldFailCompile
+//    * methods of class CompileManager.
+//    */
+//   def compile(out: Option[File], files: List[File], kind: String, log: File): Boolean = {
+//     val res = sepCompileMethod2.invoke(sepCompiler, out, files, kind, log).asInstanceOf[java.lang.Boolean]
+//     res.booleanValue()
+//   }
+// }
 
 class CompileManager(val fileManager: FileManager) {
-
-  import scala.actors.Actor._
-  import scala.actors.{Actor, Exit, TIMEOUT}
-
-  import java.util.{Timer, TimerTask}
-
   var compiler: SimpleCompiler = new /*ReflectiveCompiler*/ DirectCompiler(fileManager)
 
-  val timer = new Timer
-
   var numSeparateCompilers = 1
   def createSeparateCompiler() = {
     numSeparateCompilers += 1
     compiler = new /*ReflectiveCompiler*/ DirectCompiler(fileManager)
   }
 
-  val delay = fileManager.timeout.toLong
-
-  def withTimeout(files: List[File])(thunk: => Boolean): Boolean = {
-    createSeparateCompiler()
-
-    val parent = self
-    /*self.trapExit = true
-    val child = link {
-      parent ! (self, thunk)
-    }
-
-    receiveWithin(delay) {
-      case TIMEOUT =>
-        println("compilation timed out")
-        false
-      case Exit(from, reason) if from == child =>
-        val From = from
-        reason match {
-          case 'normal =>
-            receive {
-              case (From, result: Boolean) => result
-            }
-          case t: Throwable =>
-            NestUI.verbose("while invoking compiler ("+files+"):")
-            NestUI.verbose("caught "+t)
-            t.printStackTrace
-            if (t.getCause != null)
-              t.getCause.printStackTrace
-            false
-        }
-    }*/
-
-    val ontimeout = new TimerTask {
-      def run() {
-        parent ! 'timeout
-      }
-    }
-    timer.schedule(ontimeout, delay)
-
-    actor {
-      val result = try {
-        thunk
-      } catch {
-        case t: Throwable =>
-          NestUI.verbose("while invoking compiler ("+files+"):")
-          NestUI.verbose("caught "+t)
-          t.printStackTrace
-          if (t.getCause != null)
-            t.getCause.printStackTrace
-          false
-      }
-      parent ! result
-    }
-    receive {
-      case 'timeout =>
-        println("compilation timed out")
-        false
-      case r: Boolean =>
-        r
-    }
-  }
-
   /* This method returns true iff compilation succeeds.
    */
-  def shouldCompile(files: List[File], kind: String, log: File): Boolean =
-    withTimeout(files) {
-      compiler.compile(None, files, kind, log)
-    }
+  def shouldCompile(files: List[File], kind: String, log: File): Boolean = {
+    createSeparateCompiler()
+    compiler.compile(None, files, kind, log)
+  }
 
   /* This method returns true iff compilation succeeds.
    */
-  def shouldCompile(out: File, files: List[File], kind: String, log: File): Boolean =
-    withTimeout(files) {
-      compiler.compile(Some(out), files, kind, log)
-    }
+  def shouldCompile(out: File, files: List[File], kind: String, log: File): Boolean = {
+    createSeparateCompiler()
+    compiler.compile(Some(out), files, kind, log)
+  }
 
   /* This method returns true iff compilation fails
    * _and_ the compiler does _not_ crash or loop.
    *
    * If the compiler crashes, this method returns false.
    */
-  def shouldFailCompile(files: List[File], kind: String, log: File): Boolean =
-    withTimeout(files) {
-      !compiler.compile(None, files, kind, log)
-    }
+  def shouldFailCompile(files: List[File], kind: String, log: File): Boolean = {
+    createSeparateCompiler()
+    !compiler.compile(None, files, kind, log)
+  }
 
   /* This method returns true iff compilation fails
    * _and_ the compiler does _not_ crash or loop.
    *
    * If the compiler crashes, this method returns false.
    */
-  def shouldFailCompile(out: File, files: List[File], kind: String, log: File): Boolean =
-    withTimeout(files) {
-      !compiler.compile(Some(out), files, kind, log)
-    }
-
+  def shouldFailCompile(out: File, files: List[File], kind: String, log: File): Boolean = {
+    createSeparateCompiler()
+    !compiler.compile(Some(out), files, kind, log)
+  }
 }
diff --git a/src/partest/scala/tools/partest/nest/ConsoleFileManager.scala b/src/partest/scala/tools/partest/nest/ConsoleFileManager.scala
index 806daf8..c48f536 100644
--- a/src/partest/scala/tools/partest/nest/ConsoleFileManager.scala
+++ b/src/partest/scala/tools/partest/nest/ConsoleFileManager.scala
@@ -1,30 +1,39 @@
 /* NEST (New Scala Test)
- * Copyright 2007-2009 LAMP/EPFL
+ * Copyright 2007-2010 LAMP/EPFL
  * @author Philipp Haller
  */
 
-// $Id: ConsoleFileManager.scala 16881 2009-01-09 16:28:11Z cunei $
+// $Id$
 
-package scala.tools.partest.nest
+package scala.tools.partest
+package nest
 
-import java.io.{File, FilenameFilter, IOException, StringWriter}
+import java.io.{ File, FilenameFilter, IOException, StringWriter }
 import java.net.URI
-
-class ConsoleFileManager extends FileManager {
-
-  var testBuild = System.getProperty("scalatest.build")
+import scala.util.Properties.{ propOrElse, scalaCmd, scalacCmd }
+import scala.tools.util.PathResolver
+import scala.tools.nsc.{ Settings }
+import scala.tools.nsc.{ io, util }
+import util.{ ClassPath }
+import io.{ Path, Directory }
+import File.pathSeparator
+import ClassPath.{ join }
+import PathResolver.{ Environment, Defaults }
+import RunnerUtils._
+
+
+class ConsoleFileManager extends FileManager {  
+  var testBuild: Option[String] = PartestDefaults.testBuild
+  def testBuildFile = testBuild map (testParent / _)
+  
   var testClasses: Option[String] = None
 
-  val debug: Boolean =
-    (System.getProperty("partest.debug", "false") equals "true") ||
-    (System.getProperty("scalatest.debug", "false") equals "true")
-
   def this(buildPath: String, rawClasses: Boolean) = {
     this()
     if (rawClasses)
       testClasses = Some(buildPath)
     else
-      testBuild = buildPath
+      testBuild = Some(buildPath)
     // re-run because initialization of default
     // constructor must be updated
     findLatest()
@@ -39,120 +48,59 @@ class ConsoleFileManager extends FileManager {
     SCALAC_OPTS = SCALAC_OPTS+" "+moreOpts
   }
 
-  var CLASSPATH = System.getProperty("java.class.path", ".")
-  NestUI.verbose("CLASSPATH: "+CLASSPATH)
-
-  var JAVACMD   = System.getProperty("scalatest.javacmd", "java")
-  var JAVAC_CMD = System.getProperty("scalatest.javac_cmd", "javac")
+  lazy val srcDir        = PathSettings.srcDir
+  lazy val testRootDir   = PathSettings.testRoot
+  lazy val testRootPath  = testRootDir.toAbsolute.path  
+  def testParent    = testRootDir.parent
 
-  val prefixFile = {
-    val cwd = System.getProperty("user.dir")
-    if (cwd != null)
-      (new File(cwd)).getCanonicalFile
-    else
-      error("user.dir property not set")
-  }
-  val PREFIX = prefixFile.getAbsolutePath
-
-/* 
-if [ -d "$PREFIX/test" ]; then 
-    TESTROOT="$PREFIX/test"; 
-elif [ -d "$PREFIX/misc/scala-test" ]; then 
-    TESTROOT="$PREFIX/misc/scala-test"; 
-else 
-    abort "Test directory not found"; 
-*/ 
-
-  val testRootFile = {
-    val testRootProp = System.getProperty("scalatest.root")
-    val testroot =
-      if (testRootProp != null)
-        new File(testRootProp)
-      else {
-        // case 1: cwd is `test`
-        if (prefixFile.getName == "test" && (new File(prefixFile, "files")).exists)
-          prefixFile
-        else {
-        // case 2: cwd is `test/..`
-          val test = new File(prefixFile, "test")
-          val scalaTest = new File(new File(prefixFile, "misc"), "scala-test")
-          if (test.isDirectory)
-            test
-          else if (scalaTest.isDirectory)
-            scalaTest
-          else
-            error("Test directory not found")
-        }
-      }
-    testroot.getCanonicalFile
-  }
-  val TESTROOT = testRootFile.getAbsolutePath
-
-  var srcDirName: String = ""
+  var CLASSPATH   = PartestDefaults.classPath
+  var JAVACMD     = PartestDefaults.javaCmd
+  var JAVAC_CMD   = PartestDefaults.javacCmd
+  
 
-  val srcDir: File = {
-    val srcDirProp = System.getProperty("partest.srcdir")
-    val src =
-      if (srcDirProp != null) {
-        srcDirName = srcDirProp
-        new File(testRootFile, srcDirName)
-      } else {
-        srcDirName = "files"
-        new File(testRootFile, srcDirName)
-      }
-    if (src.isDirectory)
-      src.getCanonicalFile
-    else {
-      val path = TESTROOT + File.separator + "files"
-      NestUI.failure("Source directory \"" + path + "\" not found")
-      exit(1)
-    }
+  NestUI.verbose("CLASSPATH: "+CLASSPATH)
+  
+  if (!srcDir.isDirectory) {
+    NestUI.failure("Source directory \"" + srcDir.path + "\" not found")
+    exit(1)
   }
-
-  LIB_DIR = (new File(testRootFile.getParentFile, "lib")).getCanonicalFile.getAbsolutePath
-
-  CLASSPATH = CLASSPATH + File.pathSeparator + {
-    val libs = new File(srcDir, "lib")
+  
+  CLASSPATH = {
+    val libs = (srcDir / Directory("lib")).files filter (_ hasExtension "jar") map (_.normalize.path)
+    
     // add all jars in libs
-    (libs.listFiles(new FilenameFilter {
-      def accept(dir: File, name: String) = name endsWith ".jar"
-    }) map {file => file.getCanonicalFile.getAbsolutePath}).mkString(""+File.pathSeparator)
+    (CLASSPATH :: libs.toList) mkString pathSeparator
   }
 
   def findLatest() {
-    val testParent = testRootFile.getParentFile
     NestUI.verbose("test parent: "+testParent)
 
-    def prefixFileWith(parent: File, relPath: String): File =
-      (new File(parent, relPath)).getCanonicalFile
-
-    def prefixFile(relPath: String): File =
-      prefixFileWith(testParent, relPath)
+    def prefixFileWith(parent: File, relPath: String) = (io.File(parent) / relPath).normalize
+    def prefixFile(relPath: String) = (testParent / relPath).normalize
 
     if (!testClasses.isEmpty) {
-      testClassesFile = (new File(testClasses.get)).getCanonicalFile
-      NestUI.verbose("Running with classes in "+testClassesFile)
-      latestFile        = prefixFileWith(testClassesFile.getParentFile, "bin")
-      latestLibFile     = prefixFileWith(testClassesFile, "library")
-      latestActFile     = prefixFileWith(testClassesFile, "library")
-      latestCompFile    = prefixFileWith(testClassesFile, "compiler")
-      latestPartestFile = prefixFileWith(testClassesFile, "partest")
-      latestFjbgFile    = prefixFile("lib/fjbg.jar")
+      testClassesDir = Path(testClasses.get).normalize.toDirectory
+      NestUI.verbose("Running with classes in "+testClassesDir)
+      
+      latestFile        = testClassesDir.parent / "bin"
+      latestLibFile     = testClassesDir / "library"
+      latestCompFile    = testClassesDir / "compiler"
+      latestPartestFile = testClassesDir / "partest"
+      latestFjbgFile    = testParent / "lib" / "fjbg.jar"
+    }
+    else if (testBuild.isDefined) {
+      val dir = Path(testBuild.get)
+      NestUI.verbose("Running on "+dir)
+      latestFile        = dir / "bin"
+      latestLibFile     = dir / "lib/scala-library.jar"
+      latestCompFile    = dir / "lib/scala-compiler.jar"
+      latestPartestFile = dir / "lib/scala-partest.jar"
     }
-    else if (testBuild != null) {
-      testBuildFile = prefixFile(testBuild)
-      NestUI.verbose("Running on "+testBuild)
-      latestFile        = prefixFile(testBuild+"/bin")
-      latestLibFile     = prefixFile(testBuild+"/lib/scala-library.jar")
-      latestActFile     = prefixFile(testBuild+"/lib/scala-library.jar")
-      latestCompFile    = prefixFile(testBuild+"/lib/scala-compiler.jar")
-      latestPartestFile = prefixFile(testBuild+"/lib/scala-partest.jar")
-    } else {
+    else {
       def setupQuick() {
         NestUI.verbose("Running build/quick")
         latestFile        = prefixFile("build/quick/bin")
         latestLibFile     = prefixFile("build/quick/classes/library")
-        latestActFile     = prefixFile("build/quick/classes/library")
         latestCompFile    = prefixFile("build/quick/classes/compiler")
         latestPartestFile = prefixFile("build/quick/classes/partest")
       }
@@ -162,7 +110,6 @@ else
         val p = testParent.getParentFile
         latestFile        = prefixFileWith(p, "bin")
         latestLibFile     = prefixFileWith(p, "lib/scala-library.jar")
-        latestActFile     = prefixFileWith(p, "lib/scala-library.jar")
         latestCompFile    = prefixFileWith(p, "lib/scala-compiler.jar")
         latestPartestFile = prefixFileWith(p, "lib/scala-partest.jar")
       }
@@ -171,7 +118,6 @@ else
         NestUI.verbose("Running dists/latest")
         latestFile        = prefixFile("dists/latest/bin")
         latestLibFile     = prefixFile("dists/latest/lib/scala-library.jar")
-        latestActFile     = prefixFile("dists/latest/lib/scala-library.jar")
         latestCompFile    = prefixFile("dists/latest/lib/scala-compiler.jar")
         latestPartestFile = prefixFile("dists/latest/lib/scala-partest.jar")
       }
@@ -180,130 +126,65 @@ else
         NestUI.verbose("Running build/pack")
         latestFile        = prefixFile("build/pack/bin")
         latestLibFile     = prefixFile("build/pack/lib/scala-library.jar")
-        latestActFile     = prefixFile("build/pack/lib/scala-library.jar")
         latestCompFile    = prefixFile("build/pack/lib/scala-compiler.jar")
         latestPartestFile = prefixFile("build/pack/lib/scala-partest.jar")
       }
 
-      def max(a: Long, b: Long) = if (a > b) a else b
-
-      val dists = new File(testParent, "dists")
-      val build = new File(testParent, "build")
-      // in case of an installed dist, testRootFile is one level deeper
-      val bin = new File(testParent.getParentFile, "bin")
+      val dists = testParent / "dists"
+      val build = testParent / "build"
+      // in case of an installed dist, testRootDir is one level deeper
+      val bin = testParent.parent / "bin"
+      
+      def mostRecentOf(base: String, names: String*) =
+        names map (x => prefixFile(base + "/" + x).lastModified) reduceLeft (_ max _)
 
       // detect most recent build
-      val quickTime =
-        max(prefixFile("build/quick/classes/compiler/compiler.properties").lastModified,
-            prefixFile("build/quick/classes/library/library.properties").lastModified)
-      val packTime =
-        max(prefixFile("build/pack/lib/scala-compiler.jar").lastModified,
-            prefixFile("build/pack/lib/scala-library.jar").lastModified)
-      val distTime =
-        max(prefixFile("dists/latest/lib/scala-compiler.jar").lastModified,
-            prefixFile("dists/latest/lib/scala-library.jar").lastModified)
-      val instTime = {
-        val p = testParent.getParentFile
-        max(prefixFileWith(p, "lib/scala-compiler.jar").lastModified,
-            prefixFileWith(p, "lib/scala-library.jar").lastModified)
-      }
-
-      if (quickTime > packTime) {   // pack ruled out
-        if (quickTime > distTime) { // dist ruled out
-          if (quickTime > instTime) // inst ruled out
-            setupQuick()
-          else
-            setupInst()
-        } else {                    // quick ruled out
-          if (distTime > instTime)  // inst ruled out
-            setupDist()
-          else
-            setupInst()
-        }
-      } else {                      // quick ruled out
-        if (packTime > distTime) {  // dist ruled out
-          if (packTime > instTime)  // inst ruled out
-            setupPack()
-          else
-            setupInst()
-        } else {                    // pack ruled out
-          if (distTime > instTime)  // inst ruled out
-            setupDist()
-          else
-            setupInst()
-        }
-      }
+      val quickTime = mostRecentOf("build/quick/classes", "compiler/compiler.properties", "library/library.properties")
+      val packTime  = mostRecentOf("build/pack/lib", "scala-compiler.jar", "scala-library.jar")
+      val distTime  = mostRecentOf("dists/latest/lib", "scala-compiler.jar", "scala-library.jar")
+      val instTime  = mostRecentOf("lib", "scala-compiler.jar", "scala-library.jar")
+      
+      val pairs = Map(
+        (quickTime, () => setupQuick()),
+        (packTime,  () => setupPack()),
+        (distTime,  () => setupDist()),
+        (instTime,  () => setupInst())
+      )
+      
+      // run setup based on most recent time
+      pairs(pairs.keys max)()
+      
       latestFjbgFile = prefixFile("lib/fjbg.jar")
     }
-
-    BIN_DIR = latestFile.getAbsolutePath
+    
     LATEST_LIB = latestLibFile.getAbsolutePath
-    LATEST_COMP = latestCompFile.getAbsolutePath
-    LATEST_PARTEST = latestPartestFile.getAbsolutePath
-
-    // detect whether we are running on Windows
-    val osName = System.getProperty("os.name")
-    NestUI.verbose("OS: "+osName)
-
-    val scalaCommand = if (osName startsWith "Windows")
-      "scala.bat" else "scala"
-    val scalacCommand = if (osName startsWith "Windows")
-      "scalac.bat" else "scalac"
-
-    SCALA = (new File(latestFile, scalaCommand)).getAbsolutePath
-    SCALAC_CMD = (new File(latestFile, scalacCommand)).getAbsolutePath
   }
-
-  var BIN_DIR: String = ""
+  
   var LATEST_LIB: String = ""
-  var LATEST_COMP: String = ""
-  var LATEST_PARTEST: String = ""
-  var SCALA: String = ""
-  var SCALAC_CMD: String = ""
 
   var latestFile: File = _
   var latestLibFile: File = _
-  var latestActFile: File = _
   var latestCompFile: File = _
   var latestPartestFile: File = _
   var latestFjbgFile: File = _
-  var testBuildFile: File = _
-  var testClassesFile: File = _
+  var testClassesDir: Directory = _
   // initialize above fields
   findLatest()
 
-  var testFiles: List[File] = List()
+  var testFiles: List[io.Path] = Nil
 
-  def getFiles(kind: String, doCheck: Boolean, filter: Option[(String, Boolean)]): List[File] = {
-    val dir = new File(srcDir, kind)
-    NestUI.verbose("look in "+dir+" for tests")
-    if (dir.isDirectory) {
-      if (!testFiles.isEmpty) {
-        val dirpath = dir.getAbsolutePath
-        testFiles filter { _.getParentFile.getAbsolutePath == dirpath }
-      } else if (doCheck) filter match {
-        case Some((ending, enableDirs)) =>
-          val filter = new FilenameFilter {
-            def accept(dir: File, name: String) =
-              name.endsWith(ending) ||
-              (enableDirs && (name != ".svn") && (!name.endsWith(".obj")) &&
-              (new File(dir, name)).isDirectory)
-          }
-          dir.listFiles(filter).toList
-        case None =>
-          val filter = new FilenameFilter {
-            def accept(dir: File, name: String) = name != ".svn"
-          }
-          dir.listFiles(filter).toList
-      } else // skip
-          Nil
-    } else {
-      NestUI.failure("Directory \"" + dir.getPath + "\" not found")
-      Nil
-    }
-  }
+  def getFiles(kind: String, cond: Path => Boolean): List[File] = {
+    def ignoreDir(p: Path) = List("svn", "obj") exists (p hasExtension _)
 
-  def getFiles(kind: String, doCheck: Boolean): List[File] =
-    getFiles(kind, doCheck, Some((".scala", true)))
-  
+    val dir = Directory(srcDir / kind)
+
+    if (dir.isDirectory) NestUI.verbose("look in %s for tests" format dir)
+    else NestUI.failure("Directory '%s' not found" format dir)      
+    
+    val files =
+      if (testFiles.nonEmpty) testFiles filter (_.parent isSame dir)
+      else dir.list filterNot ignoreDir filter cond toList
+
+    ( if (failed) files filter (x => logFileExists(x, kind)) else files ) map (_.jfile)
+  }
 }
diff --git a/src/partest/scala/tools/partest/nest/ConsoleRunner.scala b/src/partest/scala/tools/partest/nest/ConsoleRunner.scala
index 4c937c5..6e5f344 100644
--- a/src/partest/scala/tools/partest/nest/ConsoleRunner.scala
+++ b/src/partest/scala/tools/partest/nest/ConsoleRunner.scala
@@ -1,193 +1,187 @@
 /* NEST (New Scala Test)
- * Copyright 2007-2009 LAMP/EPFL
+ * Copyright 2007-2010 LAMP/EPFL
  * @author Philipp Haller
  */
 
-// $Id: ConsoleRunner.scala 18847 2009-10-01 07:38:11Z phaller $
+// $Id$
 
-package scala.tools.partest.nest
+package scala.tools.partest
+package nest
 
 import java.io.{File, PrintStream, FileOutputStream, BufferedReader,
                 InputStreamReader, StringWriter, PrintWriter}
-
-class ConsoleRunner extends DirectRunner with RunnerUtils {
-
-  case class TestSet(loc: String,
-                     filter: Option[(String, Boolean)],
-                     kind: String,
-                     msg: String)
+import utils.Properties._
+import RunnerUtils._
+import scala.tools.nsc.Properties.{ versionMsg, setProp }
+import scala.tools.nsc.util.CommandLineParser
+import scala.tools.nsc.io
+import io.{ Path, Process }
+
+class ConsoleRunner extends DirectRunner {
+  import PathSettings.{ srcDir, testRoot }
+  
+  case class TestSet(kind: String, filter: Path => Boolean, msg: String)
 
   val testSets = {
-    val fileFilter = Some((".scala", true))
+    val pathFilter: Path => Boolean = _ hasExtension "scala"
+
     List(
-      TestSet("pos", fileFilter, "pos",
-              "Testing compiler (on files whose compilation should succeed)"),
-      TestSet("pos5", fileFilter, "pos",
-              "Testing compiler (on files whose compilation should succeed on 1.5 JVM)"),
-      TestSet("neg",  fileFilter, "neg",
-              "Testing compiler (on files whose compilation should fail)"),
-      TestSet("run",  fileFilter, "run", "Testing JVM backend"),
-      TestSet("jvm",  fileFilter, "jvm", "Testing JVM backend"),
-      TestSet("jvm5", fileFilter, "jvm5", "Testing JVM backend"),
-      TestSet("res",  Some((".res", false)), "res",
-              "Testing resident compiler"),
-      TestSet("shootout", fileFilter, "shootout", "Testing shootout tests"),
-      TestSet("script", fileFilter, "script", "Testing script tests"),
-      TestSet("scalacheck", fileFilter, "scalacheck", "Testing ScalaCheck tests"))
+      TestSet("pos", pathFilter, "Testing compiler (on files whose compilation should succeed)"),
+      TestSet("neg", pathFilter, "Testing compiler (on files whose compilation should fail)"),
+      TestSet("run", pathFilter, "Testing JVM backend"),
+      TestSet("jvm", pathFilter, "Testing JVM backend"),
+      TestSet("res", x => x.isFile && (x hasExtension "res"), "Testing resident compiler"),              
+      TestSet("buildmanager", _.isDirectory, "Testing Build Manager"),
+      TestSet("shootout", pathFilter, "Testing shootout tests"),
+      TestSet("script", pathFilter, "Testing script tests"),
+      TestSet("scalacheck", pathFilter, "Testing ScalaCheck tests"),
+      TestSet("scalap", _.isDirectory, "Run scalap decompiler tests")
+    )
   }
 
   var fileManager: ConsoleFileManager = _
 
-  private val version = System.getProperty("java.version", "")
-  private val isJava5 = version matches "1.[5|6|7].*"
-  private var runAll = false
   private var testFiles: List[File] = List()
-  private val errors =
-    Integer.parseInt(System.getProperty("scalatest.errors", "0"))
+  private val errors = PartestDefaults.errorCount
+  private val testSetKinds  = testSets map (_.kind)
+  private val testSetArgs   = testSets map ("--" + _.kind)
+  private val testSetArgMap = testSetArgs zip testSets toMap
+  
+  def denotesTestSet(arg: String) = testSetArgs contains arg
+  def denotesTestFile(arg: String) = (arg endsWith ".scala") || (arg endsWith ".res")
+  def denotesTestDir(arg: String) = Path(arg).isDirectory
+  def denotesTestPath(arg: String) = denotesTestDir(arg) || denotesTestFile(arg)
+
+  private def printVersion { NestUI outline (versionMsg + "\n") }
+  
+  private val unaryArgs = List(
+    "--pack", "--all", "--verbose", "--show-diff", "--show-log",
+    "--failed", "--version", "--ansi", "--debug"
+  ) ::: testSetArgs
+  
+  private val binaryArgs = List(
+    "--grep", "--srcpath", "--buildpath", "--classpath"
+  )
 
-  def denotesTestSet(arg: String) =
-    testSets exists { set => arg == "--" + set.loc }
+  def main(argstr: String) {
+    val parsed = CommandLineParser(argstr) withUnaryArgs unaryArgs withBinaryArgs binaryArgs
+    val args = parsed.residualArgs
+    
+    /** Early return on no args, version, or invalid args */
+    if (argstr == "") return NestUI.usage()
+    if (parsed isSet "--version") return printVersion
+    if (args exists (x => !denotesTestPath(x))) {
+      val invalid = (args filterNot denotesTestPath).head
+      NestUI.failure("Invalid argument '%s'\n" format invalid)
+      return NestUI.usage()
+    }
 
-  def denotesTestFile(arg: String) =
-    arg.endsWith(".scala") || arg.endsWith(".res")
+    parsed get "--srcpath" foreach (x => setProp("partest.srcdir", x))
+    
+    fileManager =      
+      if (parsed isSet "--buildpath") new ConsoleFileManager(parsed("--buildpath"))
+      else if (parsed isSet "--classpath") new ConsoleFileManager(parsed("--classpath"), true)
+      else if (parsed isSet "--pack") new ConsoleFileManager("build/pack")
+      else new ConsoleFileManager  // auto detection, see ConsoleFileManager.findLatest
+    
+    def argNarrowsTests(x: String) = denotesTestSet(x) || denotesTestFile(x) || denotesTestDir(x)
+
+    NestUI._verbose       = parsed isSet "--verbose"
+    fileManager.showDiff  = parsed isSet "--show-diff"
+    fileManager.showLog   = parsed isSet "--show-log"
+    fileManager.failed    = parsed isSet "--failed"
+    
+    if (parsed isSet "--ansi") NestUI initialize NestUI.MANY
+    if (parsed isSet "--timeout") fileManager.timeout = parsed("--timeout")
+    if (parsed isSet "--debug") setProp("partest.debug", "true")
+    
+    def addTestFile(file: File) = {
+      if (!file.exists)
+        NestUI.failure("Test file '%s' not found, skipping.\n" format file)
+      else {
+        NestUI.verbose("adding test file " + file)
+        testFiles +:= file
+      }
+    }
 
-  def denotesTestDir(arg: String) =
-    (new File(arg)).isDirectory
+    // If --grep is given we suck in every file it matches.
+    parsed get "--grep" foreach { expr =>
+      val allFiles = srcDir.deepList() filter (_ hasExtension "scala") map (_.toFile) toList
+      val files = allFiles filter (_.slurp() contains expr)
+      
+      if (files.isEmpty) NestUI.failure("--grep string '%s' matched no files." format expr)
+      else NestUI.verbose("--grep string '%s' matched %d file(s)".format(expr, files.size)) 
 
-  def main(argstr: String) {
-    // tokenize args. filter: "".split("\\s") yields Array("")
-    var args = List.fromArray(argstr.split("\\s")).remove(_ == "")
-
-    if (args.length == 0)
-      NestUI.usage()
-    else {
-      // find out which build to test
-      val (buildPath, args1) = searchAndRemovePath("--buildpath", args)
-      val (classPath, args2) = searchAndRemovePath("--classpath", args1)
-      val (srcPath, args3) = searchAndRemovePath("--srcpath", args2)
-      args = args3
-
-      if (!srcPath.isEmpty)
-        System.setProperty("partest.srcdir", srcPath.get)
-
-      fileManager =
-        if (!buildPath.isEmpty)
-          new ConsoleFileManager(buildPath.get)
-        else if (!classPath.isEmpty)
-          new ConsoleFileManager(classPath.get, true)
-        else if (args contains "--pack") {
-          args = args.remove(_ == "--pack") // will create a result file '--pack' otherwise
-          new ConsoleFileManager("build/pack")
-        } else if (args contains "--four") {
-          args = args.remove(_ == "--four")
-          new ConsoleFileManager("build/four-pack", false, "-target:jvm-1.4")
-        } else // auto detection, see ConsoleFileManager.findLatest
-          new ConsoleFileManager
-
-      if (!args.exists(denotesTestSet(_)) &&
-          !args.exists(denotesTestFile(_)) &&
-          !args.exists(denotesTestDir(_)))
-        runAll = true
-
-      var enabled = List[TestSet]()
-
-      for (arg <- args) {
-        (testSets find { set => arg == "--" + set.loc }) match {
-          case Some(set) => enabled = set :: enabled
-          case None      => arg match {
-            case "--all"          => runAll = true
-            case "--verbose"      => NestUI._verbose = true
-            case "--show-diff"    => fileManager.showDiff = true
-            case "--show-log"     => fileManager.showLog = true
-            case "--failed"       => fileManager.failed = true
-            case "--version"      => //todo: printVersion
-            case "--ansi"         => NestUI.initialize(NestUI.MANY)
-            case _ =>
-              if (denotesTestFile(arg) || denotesTestDir(arg)) {
-                val file = new File(arg)
-                if (file.exists) {
-                  NestUI.verbose("adding test file "+file)
-                  testFiles = file :: testFiles
-                } else {
-                  NestUI.failure("File \"" + arg + "\" not found\n")
-                  System.exit(1)
-                }
-              } else {
-                NestUI.failure("Invalid option \""+arg+"\"\n")
-                NestUI.usage()
-              }
-          }
-        }
-      }
-      NestUI.verbose("enabled test sets: "+enabled)
-      NestUI.verbose("runAll: "+runAll)
-
-      val dir =
-        if (!fileManager.testClasses.isEmpty)
-          fileManager.testClassesFile
-        else if (fileManager.testBuild != null)
-          fileManager.testBuildFile
-        else
-          fileManager.latestCompFile.getParentFile.getParentFile.getCanonicalFile
-      NestUI.outline("Scala compiler classes in: "+dir+"\n")
-
-      val scalaVersion = "Scala compiler "+
-        scala.tools.nsc.Properties.versionString+
-        " -- "+
-        scala.tools.nsc.Properties.copyrightString
-
-      NestUI.outline("Scala version is:          "+scalaVersion+"\n")
-      NestUI.outline("Scalac options are:        "+fileManager.SCALAC_OPTS+"\n")
-
-      val vmBin  = System.getProperty("java.home", "")+File.separator+"bin"
-      val vmName = System.getProperty("java.vm.name", "")+" (build "+
-                   System.getProperty("java.vm.version", "")+", "+
-                   System.getProperty("java.vm.info", "")+")"
-      val vmOpts = fileManager.JAVA_OPTS
-      NestUI.outline("Java binaries in:          "+vmBin+"\n")
-      NestUI.outline("Java runtime is:           "+vmName+"\n")
-      NestUI.outline("Java options are:          "+vmOpts+"\n")
-      NestUI.outline("Source directory is:       "+fileManager.srcDir.getAbsolutePath+"\n")
-
-      val start = System.currentTimeMillis
-
-      val (successes, failures) = testCheckAll(enabled)
-
-      val end = System.currentTimeMillis
-      val total = successes + failures
-
-      val elapsedSecs = (end - start)/1000
-      val elapsedMins = elapsedSecs/60
-      val elapsedHrs  = elapsedMins/60
-      val dispMins = elapsedMins - elapsedHrs  * 60
-      val dispSecs = elapsedSecs - elapsedMins * 60
-      val dispElapsed = {
-        def form(num: Long) = if (num < 10) "0"+num else ""+num
-        form(elapsedHrs)+":"+form(dispMins)+":"+form(dispSecs)
+      files foreach (x => addTestFile(x.jfile))
+    }
+    args foreach (x => addTestFile(new File(x)))
+    
+    // If no file arguments were given, we assume --all
+    val enabledTestSets: List[TestSet] = {
+      val enabledArgs = testSetArgs filter parsed.isSet
+      
+      if (args.isEmpty && !(parsed isSet "--grep") && (enabledArgs.isEmpty || (parsed isSet "--all"))) testSets
+      else enabledArgs map testSetArgMap
+    }
+    
+    val dir =
+      if (fileManager.testClasses.isDefined) fileManager.testClassesDir
+      else fileManager.testBuildFile getOrElse {
+        fileManager.latestCompFile.getParentFile.getParentFile.getCanonicalFile
       }
 
-      println
-      if (failures == 0)
-        NestUI.success("All of "+total+" tests were successful (elapsed time: "+dispElapsed+")\n")
-      else
-        NestUI.failure(failures+" of "+total+" tests failed (elapsed time: "+dispElapsed+")\n")
+    val vmBin  = javaHome + File.separator + "bin"
+    val vmName = "%s (build %s, %s)".format(javaVmName, javaVmVersion, javaVmInfo)
+    val vmOpts = fileManager.JAVA_OPTS
+    
+    NestUI.verbose("enabled test sets: " + (enabledTestSets map (_.kind) mkString " "))
 
-      if (failures == errors)
-        System.exit(0)
-      else
-        System.exit(1)
+    List(
+      "Scala compiler classes in: " + dir,
+      "Scala version is:          " + versionMsg,
+      "Scalac options are:        " + fileManager.SCALAC_OPTS,
+      "Java binaries in:          " + vmBin,
+      "Java runtime is:           " + vmName,
+      "Java options are:          " + vmOpts,
+      "Source directory is:       " + srcDir,
+      ""
+    ) foreach (x => NestUI outline (x + "\n"))
+
+    val start = System.currentTimeMillis
+    val (successes, failures) = testCheckAll(enabledTestSets)
+    val end = System.currentTimeMillis
+    
+    val total = successes + failures
+    
+    val elapsedSecs = (end - start)/1000
+    val elapsedMins = elapsedSecs/60
+    val elapsedHrs  = elapsedMins/60
+    val dispMins = elapsedMins - elapsedHrs  * 60
+    val dispSecs = elapsedSecs - elapsedMins * 60
+    
+    val dispElapsed = {
+      def form(num: Long) = if (num < 10) "0"+num else ""+num
+      form(elapsedHrs)+":"+form(dispMins)+":"+form(dispSecs)
     }
+
+    println
+    if (failures == 0)
+      NestUI.success("All of "+total+" tests were successful (elapsed time: "+dispElapsed+")\n")
+    else
+      NestUI.failure(failures+" of "+total+" tests failed (elapsed time: "+dispElapsed+")\n")
+
+    System exit ( if (failures == errors) 0 else 1 )
   }
 
   def runTests(testSet: TestSet): (Int, Int) = {
-    val TestSet(loc, filter, kind, msg) = testSet
-    val files = fileManager.getFiles(loc, true, filter)
-    if (!files.isEmpty) {
-      NestUI.outline("\n"+msg+"\n")
-      runTestsForFiles(files, kind)
-    } else {
-      NestUI.failure("test dir empty\n")
-      (0, 0)
+    val TestSet(kind, filter, msg) = testSet    
+
+    fileManager.getFiles(kind, filter) match {
+      case Nil    => NestUI.verbose("test dir empty\n") ; (0, 0)
+      case files  =>
+        NestUI.verbose("test files: "+files)
+        NestUI.outline("\n"+msg+"\n")
+        resultsToStatistics(runTestsForFiles(files, kind))
     }
   }
 
@@ -195,50 +189,20 @@ class ConsoleRunner extends DirectRunner with RunnerUtils {
    * @return (success count, failure count)
    */
   def testCheckAll(enabledSets: List[TestSet]): (Int, Int) = {
-    def runTestsFiles = if (!testFiles.isEmpty) {
-      def absName(f: File): String = f.getAbsoluteFile.getCanonicalPath
-
-      def kindOf(f: File): String = {
-        val firstName = absName(f)
-        val len = fileManager.srcDirName.length
-        val filesPos = firstName.indexOf(fileManager.srcDirName)
-        if (filesPos == -1) {
-          NestUI.failure("invalid test file: "+firstName+"\n")
-          Predef.exit(1)
-        } else {
-          val k = firstName.substring(filesPos+len+1, filesPos+len+1+3)
-          val short = if (k == "jvm") {
-            if (firstName.substring(filesPos+len+1, filesPos+len+1+4) == "jvm5") "jvm5"
-            else k
-          } else k
-          val shortKinds = List("pos", "neg", "run", "jvm", "jvm5", "res")
-          if (shortKinds contains short) short
-          else short match {
-            case "sho" => "shootout"
-            case "scr" => "script"
-            case "sca" => "scalacheck"
-          }
-        }
-      }
-
-      val fstKind = kindOf(testFiles.head)
-      NestUI.verbose("all test files expected to have kind "+fstKind)
-      if (!testFiles.forall(kindOf(_) equals fstKind)) {
-        NestUI.failure("test files have different kinds\n")
-        Predef.exit(1)
-      } else {
+    def kindOf(f: File) = (srcDir relativize Path(f).normalize).segments.head
+        
+    val (valid, invalid) = testFiles partition (x => testSetKinds contains kindOf(x))
+    invalid foreach (x => NestUI.failure("Invalid test file '%s', skipping.\n" format x))
+    
+    val runTestsFileLists =
+      for ((kind, files) <- valid groupBy kindOf toList) yield {
         NestUI.outline("\nTesting individual files\n")
-        runTestsForFiles(testFiles, fstKind)
+        resultsToStatistics(runTestsForFiles(files, kind))
       }
-    } else (0, 0)
-
-    val runSets =
-      if (runAll) testSets // run all test sets
-      else enabledSets
-    NestUI.verbose("run sets: "+runSets)
 
-    val results = List(runTestsFiles) ::: (runSets map runTests)
-    results reduceLeft { (p: (Int, Int), q: (Int, Int)) =>
-      (p._1+q._1, p._2+q._2) }
+    NestUI.verbose("Run sets: "+enabledSets)
+    val results = runTestsFileLists ::: (enabledSets map runTests)
+    
+    (results map (_._1) sum, results map (_._2) sum)
   }
 }
diff --git a/src/partest/scala/tools/partest/nest/Diff.java b/src/partest/scala/tools/partest/nest/Diff.java
index 0327272..280dc5a 100644
--- a/src/partest/scala/tools/partest/nest/Diff.java
+++ b/src/partest/scala/tools/partest/nest/Diff.java
@@ -1,10 +1,9 @@
-// $Id$
 
 package scala.tools.partest.nest;
 
 import java.util.Hashtable;
 
-/** A class to compare vectors of objects.  The result of comparison
+/** A class to compare IndexedSeqs of objects.  The result of comparison
     is a list of <code>change</code> objects which form an
     edit script.  The objects compared are traditionally lines
     of text from two files.  Comparison options such as "ignore
@@ -50,7 +49,7 @@ public class Diff {
       an edit script, if desired.
    */
   public Diff(Object[] a,Object[] b) {
-    Hashtable h = new Hashtable(a.length + b.length);
+    Hashtable<Object, Integer> h = new Hashtable<Object, Integer>(a.length + b.length);
     filevec[0] = new file_data(a,h);
     filevec[1] = new file_data(b,h);
   }
@@ -68,12 +67,12 @@ public class Diff {
       set of changes.  This makes things slower, sometimes much slower. */
   public boolean no_discards = false;
 
-  private int[] xvec, yvec;	/* Vectors being compared. */
-  private int[] fdiag;		/* Vector, indexed by diagonal, containing
+  private int[] xvec, yvec;	/* IndexedSeqs being compared. */
+  private int[] fdiag;		/* IndexedSeq, indexed by diagonal, containing
 				   the X coordinate of the point furthest
 				   along the given diagonal in the forward
 				   search of the edit matrix. */
-  private int[] bdiag;		/* Vector, indexed by diagonal, containing
+  private int[] bdiag;		/* IndexedSeq, indexed by diagonal, containing
 				   the X coordinate of the point furthest
 				   along the given diagonal in the backward
 				   search of the edit matrix. */
@@ -275,7 +274,7 @@ public class Diff {
   /** Compare in detail contiguous subsequences of the two files
      which are known, as a whole, to match each other.
 
-     The results are recorded in the vectors filevec[N].changed_flag, by
+     The results are recorded in the IndexedSeqs filevec[N].changed_flag, by
      storing a 1 in the element for each line that is an insertion or deletion.
 
      The subsequence of file 0 is [XOFF, XLIM) and likewise for file 1.
@@ -538,7 +537,7 @@ public class Diff {
     void clear() {
       /* Allocate a flag for each line of each file, saying whether that line
 	 is an insertion or deletion.
-	 Allocate an extra element, always zero, at each end of each vector.
+	 Allocate an extra element, always zero, at each end of each IndexedSeq.
        */
       changed_flag = new boolean[buffered_lines + 2];
     }
@@ -745,7 +744,7 @@ public class Diff {
       nondiscarded_lines = j;
     }
 
-    file_data(Object[] data,Hashtable h) {
+    file_data(Object[] data, Hashtable<Object, Integer> h) {
       buffered_lines = data.length;
 
       equivs = new int[buffered_lines]; 
@@ -753,9 +752,9 @@ public class Diff {
       realindexes = new int[buffered_lines];
 
       for (int i = 0; i < data.length; ++i) {
-        Integer ir = (Integer)h.get(data[i]);
+        Integer ir = h.get(data[i]);
 	if (ir == null)
-	  h.put(data[i],new Integer(equivs[i] = equiv_max++));
+	  h.put(data[i], new Integer(equivs[i] = equiv_max++));
 	else
 	  equivs[i] = ir.intValue();
       }
@@ -849,16 +848,16 @@ public class Diff {
     /** Number of elements (lines) in this file. */
     final int buffered_lines;
 
-    /** Vector, indexed by line number, containing an equivalence code for
-       each line.  It is this vector that is actually compared with that
+    /** IndexedSeq, indexed by line number, containing an equivalence code for
+       each line.  It is this IndexedSeq that is actually compared with that
        of another file to generate differences. */
     private final int[]	    equivs;
 
-    /** Vector, like the previous one except that
+    /** IndexedSeq, like the previous one except that
        the elements for discarded lines have been squeezed out.  */
     final int[]	   undiscarded;
 
-    /** Vector mapping virtual line numbers (not counting discarded lines)
+    /** IndexedSeq mapping virtual line numbers (not counting discarded lines)
        to real ones (counting those lines).  Both are origin-0.  */
     final int[]	   realindexes;
 
diff --git a/src/partest/scala/tools/partest/nest/DiffPrint.java b/src/partest/scala/tools/partest/nest/DiffPrint.java
index d1c381d..4fdfd86 100644
--- a/src/partest/scala/tools/partest/nest/DiffPrint.java
+++ b/src/partest/scala/tools/partest/nest/DiffPrint.java
@@ -1,4 +1,3 @@
-// $Id$
 
 package scala.tools.partest.nest;
 
@@ -506,7 +505,7 @@ public class DiffPrint {
    */
   static String[] slurp(String file) throws IOException {
     BufferedReader rdr = new BufferedReader(new FileReader(file));
-    Vector s = new Vector();
+    Vector<String> s = new Vector<String>();
     for (;;) {
       String line = rdr.readLine();
       if (line == null) break;
diff --git a/src/partest/scala/tools/partest/nest/DirectRunner.scala b/src/partest/scala/tools/partest/nest/DirectRunner.scala
index 2201b7f..22664c6 100644
--- a/src/partest/scala/tools/partest/nest/DirectRunner.scala
+++ b/src/partest/scala/tools/partest/nest/DirectRunner.scala
@@ -1,42 +1,37 @@
 /* NEST (New Scala Test)
- * Copyright 2007-2009 LAMP/EPFL
+ * Copyright 2007-2010 LAMP/EPFL
  * @author Philipp Haller
  */
 
-// $Id: DirectRunner.scala 16881 2009-01-09 16:28:11Z cunei $
+// $Id$
 
-package scala.tools.partest.nest
+package scala.tools.partest
+package nest
 
 import java.io.{File, PrintStream, FileOutputStream, BufferedReader,
                 InputStreamReader, StringWriter, PrintWriter}
 import java.util.StringTokenizer
+import scala.util.Properties.{ setProp }
+import scala.tools.nsc.io.Directory
 
 import scala.actors.Actor._
+import scala.actors.TIMEOUT
 
 trait DirectRunner {
 
   def fileManager: FileManager
+  
+  import PartestDefaults.numActors
 
-  private val numActors = Integer.parseInt(System.getProperty("scalatest.actors", "8"))
-
-  if ((System.getProperty("partest.debug", "false") equals "true") ||
-      (System.getProperty("scalatest.debug", "false") equals "true"))
+  if (isPartestDebug)
     scala.actors.Debug.level = 3
-
-  {
-    val coreProp = try {
-      System.getProperty("actors.corePoolSize")
-    } catch {
-      case ace: java.security.AccessControlException =>
-        null
-    }
-    if (coreProp == null) {
-      scala.actors.Debug.info("actors.corePoolSize not defined")
-      System.setProperty("actors.corePoolSize", "16")
-    }
+  
+  if (PartestDefaults.poolSize.isEmpty) {
+    scala.actors.Debug.info("actors.corePoolSize not defined")
+    setProp("actors.corePoolSize", "16")
   }
 
-  def runTestsForFiles(kindFiles: List[File], kind: String): (Int, Int) = {
+  def runTestsForFiles(kindFiles: List[File], kind: String): scala.collection.immutable.Map[String, Int] = {    
     val len = kindFiles.length
     val (testsEach, lastFrag) = (len/numActors, len%numActors)
     val last = numActors-1
@@ -50,28 +45,34 @@ trait DirectRunner {
         worker ! RunTests(kind, toTest)
       worker
     }
-    var succs = 0; var fails = 0
+
     var logsToDelete: List[File] = List()
     var outdirsToDelete: List[File] = List()
+    var results = new scala.collection.immutable.HashMap[String, Int]
     workers foreach { w =>
-      receive {
-        case Results(s, f, logs, outdirs) =>
-          logsToDelete = logsToDelete ::: logs.filter(_.toDelete)
-          outdirsToDelete = outdirsToDelete ::: outdirs
-          succs += s
-          fails += f
+      receiveWithin(3600 * 1000) {
+        case Results(res, logs, outdirs) =>
+          logsToDelete :::= logs filter (_.toDelete)
+          outdirsToDelete :::= outdirs
+          results ++= res
+        case TIMEOUT =>
+          // add at least one failure
+          NestUI.verbose("worker timed out; adding failed test")
+          results += ("worker timed out; adding failed test" -> 2)
       }
     }
-    logsToDelete.foreach { log =>
-      NestUI.verbose("deleting "+log)
-      fileManager.deleteRecursive(log)
-    }
-    outdirsToDelete.foreach { outdir =>
-      NestUI.verbose("deleting "+outdir)
-      fileManager.deleteRecursive(outdir)
+    
+    if (isPartestDebug)
+      fileManager.showTestTimings()
+
+    if (!isPartestDebug) {
+      for (x <- logsToDelete ::: outdirsToDelete) {
+        NestUI.verbose("deleting "+x)
+        Directory(x).deleteRecursively()
+      }
     }
     
-    (succs, fails)
+    results
   }
 
 }
diff --git a/src/partest/scala/tools/partest/nest/FileManager.scala b/src/partest/scala/tools/partest/nest/FileManager.scala
index f5102e0..fe4546d 100644
--- a/src/partest/scala/tools/partest/nest/FileManager.scala
+++ b/src/partest/scala/tools/partest/nest/FileManager.scala
@@ -1,29 +1,21 @@
 /* NEST (New Scala Test)
- * Copyright 2007-2009 LAMP/EPFL
+ * Copyright 2007-2010 LAMP/EPFL
  * @author Philipp Haller
  */
 
-// $Id: FileManager.scala 16881 2009-01-09 16:28:11Z cunei $
+// $Id$
 
-package scala.tools.partest.nest
+package scala.tools.partest
+package nest
 
-import java.io.{File, FilenameFilter, IOException, StringWriter}
+import java.io.{File, FilenameFilter, IOException, StringWriter,
+                FileInputStream, FileOutputStream, BufferedReader,
+                FileReader, PrintWriter, FileWriter}
 import java.net.URI
+import scala.tools.nsc.io.{ Path, Directory }
+import scala.collection.mutable.HashMap
 
-trait FileManager {
-
-  def basename(name: String): String = {
-    val inx = name.lastIndexOf(".")
-    if (inx < 0) name else name.substring(0, inx)
-  }
-
-  def deleteRecursive(dir: File) {
-    if (dir.isDirectory) {
-      for (file <- dir.list) deleteRecursive(new File(dir, file))
-    }
-    dir.delete
-  }
-  
+trait FileManager {  
   /**
    * Compares two files using a Java implementation of the GNU diff
    * available at http://www.bmsi.com/java/#diff.
@@ -33,35 +25,86 @@ trait FileManager {
    * @return the text difference between the compared files
    */
   def compareFiles(f1: File, f2: File): String = {
-    var res = ""
-    try {
-      val diffWriter = new StringWriter
-      val args = Array(f1.getCanonicalPath(), f2.getCanonicalPath())
-      DiffPrint.doDiff(args, diffWriter)
-      res = diffWriter.toString
-      if (res.startsWith("No"))
-        res = ""
-    } catch {
-      case e: IOException =>
-        e.printStackTrace()
-    }
-    res
+    val diffWriter = new StringWriter
+    val args = Array(f1.getCanonicalPath(), f2.getCanonicalPath())
+    
+    DiffPrint.doDiff(args, diffWriter)
+    val res = diffWriter.toString
+    if (res startsWith "No") "" else res
   }
   
-  
+  def testRootDir: Directory
+  def testRootPath: String
+
   var JAVACMD: String
   var JAVAC_CMD: String
 
   var CLASSPATH: String
   var LATEST_LIB: String
-  var LIB_DIR: String = ""
 
   var showDiff = false
   var showLog = false
   var failed = false
 
-  var SCALAC_OPTS = System.getProperty("scalatest.scalac_opts", "-deprecation")
-  var JAVA_OPTS   = System.getProperty("scalatest.java_opts", "")
+  var SCALAC_OPTS = PartestDefaults.scalacOpts
+  var JAVA_OPTS   = PartestDefaults.javaOpts
+  var timeout     = PartestDefaults.timeout
+  
+  /** Only when --debug is given. */
+  lazy val testTimings = new HashMap[String, Long]
+  def recordTestTiming(name: String, milliseconds: Long) =
+    synchronized { testTimings(name) = milliseconds }
+  def showTestTimings() {
+    testTimings.toList sortBy (-_._2) foreach { case (k, v) => println("%s: %s".format(k, v)) }
+  }
+
+  def getLogFile(dir: File, fileBase: String, kind: String): LogFile =
+    new LogFile(dir, fileBase + "-" + kind + ".log")
 
-  var timeout = "2400000"
+  def getLogFile(file: File, kind: String): LogFile = {
+    val dir = file.getParentFile
+    val fileBase = basename(file.getName)
+    getLogFile(dir, fileBase, kind)
+  }
+
+  def logFileExists(file: File, kind: String) =
+    getLogFile(file, kind).canRead
+  
+  def overwriteFileWith(dest: File, file: File) =
+    dest.isFile && copyFile(file, dest)
+  
+  
+  def copyFile(from: File, dest: File): Boolean = {
+    def copyFile0(from: File, to: File): Boolean =
+      try {
+        val appender = StreamAppender(from, to)
+        appender.run()
+        appender.closeAll()
+        true
+      } catch {
+        case _: IOException => false
+      }
+    
+    if (from.isDirectory) {
+      assert(dest.isDirectory, "cannot copy directory to file")
+      val subDir:Directory = Path(dest) / Directory(from.getName)
+      subDir.createDirectory()
+      from.listFiles.toList.forall(copyFile(_, subDir))
+    } else
+      copyFile0(from, if (dest.isDirectory) new File(dest, from.getName) else dest)
+  }
+
+  def mapFile(file: File, suffix: String, dir: File, replace: String => String) {
+    val tmpFile = File.createTempFile("tmp", suffix, dir) // prefix required by API
+    
+    val appender = StreamAppender(file, tmpFile)    
+    appender.runAndMap(replace)
+    appender.closeAll()
+
+    val appender2 = StreamAppender(tmpFile, file)
+    appender2.run()
+    appender2.closeAll()
+    
+    tmpFile.delete()
+  }
 }
diff --git a/src/partest/scala/tools/partest/nest/NestRunner.scala b/src/partest/scala/tools/partest/nest/NestRunner.scala
index 2b2c7ba..1585218 100644
--- a/src/partest/scala/tools/partest/nest/NestRunner.scala
+++ b/src/partest/scala/tools/partest/nest/NestRunner.scala
@@ -1,11 +1,12 @@
 /* NEST (New Scala Test)
- * Copyright 2007-2009 LAMP/EPFL
+ * Copyright 2007-2010 LAMP/EPFL
  * @author Philipp Haller
  */
 
-// $Id: NestRunner.scala 16881 2009-01-09 16:28:11Z cunei $
+// $Id$
 
-package scala.tools.partest.nest
+package scala.tools.partest
+package nest
 
 object NestRunner {
   def main(args: Array[String]) {
diff --git a/src/partest/scala/tools/partest/nest/NestUI.scala b/src/partest/scala/tools/partest/nest/NestUI.scala
index b7a3724..cb16a06 100644
--- a/src/partest/scala/tools/partest/nest/NestUI.scala
+++ b/src/partest/scala/tools/partest/nest/NestUI.scala
@@ -1,10 +1,12 @@
 /* NEST (New Scala Test)
+ * Copyright 2007-2010 LAMP/EPFL
  * @author Philipp Haller
  */
 
-// $Id: NestUI.scala 16103 2008-09-15 17:43:28Z phaller $
+// $Id$
 
-package scala.tools.partest.nest
+package scala.tools.partest
+package nest
 
 import java.io.PrintWriter
 
@@ -68,19 +70,20 @@ object NestUI {
     println("  <options>:")
     println
     println("  Test categories:")
-    println("    --all        run all tests")
-    println("    --pos        run compilation tests (success)")
-    println("    --neg        run compilation tests (failure)")
-    println("    --run        run interpreter and backend tests")
-    println("    --jvm        run JVM backend tests")
-    println("    --jvm5       run JVM backend tests (-target:jvm-1.5)")
-    println("    --res        run resident compiler tests")
-    println("    --script     run script runner tests")
-    println("    --shootout   run shootout tests")
+    println("    --all           run all tests")
+    println("    --pos           run compilation tests (success)")
+    println("    --neg           run compilation tests (failure)")
+    println("    --run           run interpreter and backend tests")
+    println("    --jvm           run JVM backend tests")
+    println("    --res           run resident compiler tests")
+    println("    --buildmanager  run Build Manager tests")
+    println("    --scalacheck    run ScalaCheck tests")
+    println("    --script        run script runner tests")
+    println("    --shootout      run shootout tests")
+    println("    --grep <expr>    run all tests whose source file contains <expr>")
     println
     println("  Other options:")
     println("    --pack       pick compiler/library in build/pack, and run all tests")
-    println("    --four       pick compiler/library in build/four-pack, and run all tests")
     println("    --show-log   show log")
     println("    --show-diff  show diff between log and check file")
     println("    --failed     run only those tests that failed during the last run")
@@ -90,14 +93,15 @@ object NestUI {
     println("    --classpath  set (absolute) path to build classes")
     println("    --srcpath    set (relative) path to test source files")
     println("                 ex.: --srcpath pending")
+    println("    --debug      enable debugging output")
     println
-    println("version 0.9.2")
+    println(utils.Properties.versionString)
     println("maintained by Philipp Haller (EPFL)")
     exit(1)
   }
 
-
   var _verbose = false
+  var _debug = false
 
   def verbose(msg: String) {
     if (_verbose) {
@@ -105,5 +109,10 @@ object NestUI {
       println(msg)
     }
   }
-
+  def debug(msg: String) {
+    if (isPartestDebug) {
+      outline("debug: ")
+      println(msg)
+    }
+  }
 }
diff --git a/src/partest/scala/tools/partest/nest/PathSettings.scala b/src/partest/scala/tools/partest/nest/PathSettings.scala
new file mode 100644
index 0000000..7942b1a
--- /dev/null
+++ b/src/partest/scala/tools/partest/nest/PathSettings.scala
@@ -0,0 +1,41 @@
+/* NEST (New Scala Test)
+ * Copyright 2007-2010 LAMP/EPFL
+ */
+
+package scala.tools.partest
+package nest
+
+import scala.tools.nsc.Properties.{ setProp, propOrEmpty, propOrNone, propOrElse }
+import scala.tools.nsc.util.ClassPath
+import scala.tools.nsc.io
+import io.{ Path, File, Directory }
+import RunnerUtils._
+import java.net.URLClassLoader
+
+object PathSettings {
+  import PartestDefaults.{ testRootDir, srcDirName }
+    
+  private def cwd = Directory.Current getOrElse error("user.dir property not set")
+  private def isPartestDir(d: Directory) = (d.name == "test") && (d / srcDirName isDirectory)
+  
+  // Directory <root>/test
+  lazy val testRoot: Directory = testRootDir getOrElse {
+    val candidates: List[Directory] = (cwd :: cwd.parents) flatMap (d => List(d, Directory(d / "test")))
+    
+    candidates find isPartestDir getOrElse error("Directory 'test' not found.")
+  }
+  
+  // Directory <root>/test/files
+  lazy val srcDir = Directory(testRoot / srcDirName normalize)
+  
+  // Directory <root>/test/files/lib
+  lazy val srcLibDir = Directory(srcDir / "lib")
+  
+  lazy val scalaCheck = srcLibDir.files find (_.name startsWith "scalacheck") getOrElse {
+    error("No scalacheck jar found in '%s'" format srcLibDir)
+  }
+}
+
+class PathSettings() {
+  // def classpathAsURLs: List[URL]
+}
diff --git a/src/partest/scala/tools/partest/nest/ReflectiveRunner.scala b/src/partest/scala/tools/partest/nest/ReflectiveRunner.scala
index 98838df..2e0bb5b 100644
--- a/src/partest/scala/tools/partest/nest/ReflectiveRunner.scala
+++ b/src/partest/scala/tools/partest/nest/ReflectiveRunner.scala
@@ -1,11 +1,19 @@
 /* NEST (New Scala Test)
- * Copyright 2007-2009 LAMP/EPFL
+ * Copyright 2007-2010 LAMP/EPFL
  * @author Philipp Haller
  */
 
-// $Id: ReflectiveRunner.scala 16881 2009-01-09 16:28:11Z cunei $
+// $Id$
 
-package scala.tools.partest.nest
+package scala.tools.partest
+package nest
+
+import scala.tools.nsc.Properties.{ setProp, propOrEmpty }
+import scala.tools.nsc.util.ClassPath
+import scala.tools.nsc.io
+import io.Path
+import RunnerUtils._
+import java.net.URLClassLoader
 
 /* This class is used to load an instance of DirectRunner using
  * a custom class loader.
@@ -14,13 +22,17 @@ package scala.tools.partest.nest
  * the main NestRunner can be started merely by putting its
  * class on the classpath (ideally).
  */
-class ReflectiveRunner extends RunnerUtils {
+class ReflectiveRunner {
   // TODO: we might also use fileManager.CLASSPATH
   // to use the same classes as used by `scala` that
-  // was used to start the runner.
+  // was used to start the runner.  
+  val sepRunnerClassName = "scala.tools.partest.nest.ConsoleRunner"
 
   def main(args: String) {
-    val argList = List.fromArray(args.split("\\s"))
+    val argList = (args.split("\\s")).toList
+    
+    if (isPartestDebug)
+      showAllJVMInfo
 
     // find out which build to test
     val buildPath = searchPath("--buildpath", argList)
@@ -32,60 +44,45 @@ class ReflectiveRunner extends RunnerUtils {
         new ConsoleFileManager(classPath.get, true)
       else if (argList contains "--pack")
         new ConsoleFileManager("build/pack")
-      else if (argList contains "--four")
-        new ConsoleFileManager("build/four-pack", false, "-target:jvm-1.4")
       else // auto detection
         new ConsoleFileManager
 
-    import fileManager.{latestCompFile, latestLibFile, latestActFile,
-                        latestPartestFile, latestFjbgFile}
-
-    val sepUrls = Array(latestCompFile.toURL, latestLibFile.toURL,
-                        latestActFile.toURL, latestPartestFile.toURL,
-                        latestFjbgFile.toURL)
+    import fileManager.
+      { latestCompFile, latestLibFile, latestPartestFile, latestFjbgFile }
+    val files =
+      Array(latestCompFile, latestLibFile, latestPartestFile, latestFjbgFile) map (x => io.File(x))
 
-    val sepLoader = new java.net.URLClassLoader(sepUrls, null)
+    val sepUrls   = files map (_.toURL)
+    val sepLoader = new URLClassLoader(sepUrls, null)
 
-    if (fileManager.debug) {
-      println("Loading classes from:")
-      sepUrls foreach { url => println(url) }
+    if (isPartestDebug)
+      println("Loading classes from:\n" + sepUrls.mkString("\n"))
+    
+    val paths = classPath match {
+      case Some(cp) => Nil
+      case _        => files.toList map (_.path)
     }
+    val newClasspath = ClassPath.join(paths: _*)
+    
+    setProp("java.class.path", newClasspath)
+    setProp("scala.home", "")
+    
+    if (isPartestDebug)
+      for (prop <- List("java.class.path", "sun.boot.class.path", "java.ext.dirs"))
+        println(prop + ": " + propOrEmpty(prop))
 
     try {
-      val paths = if (!classPath.isEmpty)
-        Array(latestCompFile.getPath, latestLibFile.getPath,
-              latestActFile.getPath, latestPartestFile.getPath,
-              latestFjbgFile.getPath)
-      else
-        Array(latestCompFile.getPath, latestLibFile.getPath,
-              latestActFile.getPath, latestPartestFile.getPath)
-      val newClasspath = paths.mkString(java.io.File.pathSeparator)
-      System.setProperty("java.class.path", newClasspath)
-      System.setProperty("env.classpath", newClasspath)
-      System.setProperty("scala.home", "")
-      if (fileManager.debug) {
-        println("java.class.path: "+System.getProperty("java.class.path"))
-        println("env.classpath: "+System.getProperty("env.classpath"))
-        println("sun.boot.class.path: "+System.getProperty("sun.boot.class.path"))
-        println("java.ext.dirs: "+System.getProperty("java.ext.dirs"))
-      }
-      
-      val sepRunnerClass =
-        sepLoader.loadClass("scala.tools.partest.nest.ConsoleRunner")
-
-      val sepRunner = sepRunnerClass.newInstance()
-
-      val stringClass = Class.forName("java.lang.String")
-      val sepMainMethod =
-        sepRunnerClass.getMethod("main", Array(stringClass): _*)
-
+      val sepRunnerClass  = sepLoader loadClass sepRunnerClassName
+      val sepRunner       = sepRunnerClass.newInstance()
+      val sepMainMethod   = sepRunnerClass.getMethod("main", Array(classOf[String]): _*)
       val cargs: Array[AnyRef] = Array(args)
       sepMainMethod.invoke(sepRunner, cargs: _*)
-    } catch {
+    }
+    catch {
       case cnfe: ClassNotFoundException =>
         cnfe.printStackTrace()
-        NestUI.failure("scala.tools.partest.nest.ConsoleRunner could not be loaded from: \n")
-        sepUrls foreach { url => NestUI.failure(url+"\n") }
+        NestUI.failure(sepRunnerClassName +" could not be loaded from:\n")
+        sepUrls foreach (x => NestUI.failure(x + "\n"))
     }
   }
 }
diff --git a/src/partest/scala/tools/partest/nest/RunnerUtils.scala b/src/partest/scala/tools/partest/nest/RunnerUtils.scala
index 2cfee0a..50d540c 100644
--- a/src/partest/scala/tools/partest/nest/RunnerUtils.scala
+++ b/src/partest/scala/tools/partest/nest/RunnerUtils.scala
@@ -1,35 +1,29 @@
+/* NEST (New Scala Test)
+ * Copyright 2007-2010 LAMP/EPFL
+ * @author Philipp Haller
+ */
 
-package scala.tools.partest.nest
+// $Id$
 
-trait RunnerUtils {
+package scala.tools.partest
+package nest
 
-  def searchPath(option: String, as: List[String]): Option[String] = {
-    val Option = option
-    as match {
-      case Option :: r :: rs => Some(r)
-      case other :: rest => searchPath(option, rest)
-      case List() => None
-    }
+object RunnerUtils {
+  def splitArgs(str: String) = str split "\\s" filterNot (_ == "") toList
+  
+  def searchPath(option: String, as: List[String]): Option[String] = as match {
+    case `option` :: r :: _ => Some(r)
+    case _ :: rest          => searchPath(option, rest)
+    case Nil                => None
   }
 
-  def searchAndRemovePath(option: String, as: List[String]): (Option[String], List[String]) = {
-    val Option = option
-    def search(before: List[String], after: List[String]): (Option[String], List[String]) = after match {
-      case Option :: r :: rs => (Some(r), before ::: rs)
-      case other :: rest => search(before ::: List(other), rest)
-      case List() => (None, before)
-    }
-    search(List(), as)
+  def searchAndRemovePath(option: String, as: List[String]) = (as indexOf option) match {
+    case -1   => (None, as)
+    case idx  => (Some(as(idx + 1)), (as take idx) ::: (as drop (idx + 2)))
   }
 
-  def searchAndRemoveOption(option: String, as: List[String]): (Boolean, List[String]) = {
-    val Option = option
-    def search(before: List[String], after: List[String]): (Boolean, List[String]) = after match {
-      case Option :: rest => (true, before ::: rest)
-      case other :: rest => search(before ::: List(other), rest)
-      case List() => (false, before)
-    }
-    search(List(), as)
+  def searchAndRemoveOption(option: String, as: List[String]) = (as indexOf option) match {
+    case -1   => (false, as)
+    case idx  => (true, (as take idx) ::: (as drop (idx + 1)))
   }
-
 }
diff --git a/src/partest/scala/tools/partest/nest/StreamAppender.scala b/src/partest/scala/tools/partest/nest/StreamAppender.scala
index 8d10632..a1177ae 100644
--- a/src/partest/scala/tools/partest/nest/StreamAppender.scala
+++ b/src/partest/scala/tools/partest/nest/StreamAppender.scala
@@ -1,35 +1,44 @@
 /* NEST (New Scala Test)
- * Copyright 2007-2009 LAMP/EPFL
+ * Copyright 2007-2010 LAMP/EPFL
  * @author Philipp Haller
  */
 
-// $Id: StreamAppender.scala 16881 2009-01-09 16:28:11Z cunei $
+// $Id$
 
-package scala.tools.partest.nest
+package scala.tools.partest
+package nest
 
-import java.io.{Writer, PrintWriter, Reader, BufferedReader,
-                IOException, InputStream, StringWriter, InputStreamReader,
-                OutputStreamWriter, StringReader, OutputStream}
+import java.io._
 
 object StreamAppender {
-  def apply(reader: BufferedReader, writer: Writer) = {
-    val pwriter = new PrintWriter(writer, true)
-    new StreamAppender(reader, pwriter)
-  }
+  def wrapIn(in: InputStream): BufferedReader = new BufferedReader(new InputStreamReader(in))
+  def wrapIn(reader: Reader): BufferedReader = new BufferedReader(reader)
+  def wrapIn(str: String): BufferedReader = new BufferedReader(new StringReader(str))
+  
+  def wrapOut(out: OutputStream): PrintWriter = new PrintWriter(new OutputStreamWriter(out), true)
+  def wrapOut(writer: Writer): PrintWriter = new PrintWriter(writer, true)
+  def wrapOut(): PrintWriter = wrapOut(new StringWriter)
 
-  def apply(reader: Reader, writer: Writer) = {
-    val bufReader = new BufferedReader(reader)
-    val pwriter = new PrintWriter(writer, true)
-    new StreamAppender(bufReader, pwriter)
-  }
+  def apply(reader: BufferedReader, writer: Writer): StreamAppender =
+    new StreamAppender(reader, wrapOut(writer))
+
+  def apply(reader: Reader, writer: Writer): StreamAppender =
+    apply(wrapIn(reader), writer)
+  
+  def apply(in: InputStream, writer: Writer): StreamAppender =
+    apply(wrapIn(in), writer)
+  
+  def apply(str: String, writer: Writer): StreamAppender =
+    apply(wrapIn(str), writer)
+  
+  def apply(in: File, out: File): StreamAppender =
+    apply(new FileReader(in), new FileWriter(out))
 
   def appendToString(in1: InputStream, in2: InputStream): String = {
     val swriter1 = new StringWriter
     val swriter2 = new StringWriter
-    val reader1 = new BufferedReader(new InputStreamReader(in1))
-    val reader2 = new BufferedReader(new InputStreamReader(in2))
-    val app1 = StreamAppender(reader1, swriter1)
-    val app2 = StreamAppender(reader2, swriter2)
+    val app1 = StreamAppender(wrapIn(in1), swriter1)
+    val app2 = StreamAppender(wrapIn(in2), swriter2)
 
     val async = new Thread(app2)
     async.start()
@@ -37,8 +46,8 @@ object StreamAppender {
     async.join()
     swriter1.toString + swriter2.toString
   }
-
-  def inParallel(t1: Runnable, t2: Runnable, t3: Runnable) {
+/*
+  private def inParallel(t1: Runnable, t2: Runnable, t3: Runnable) {
     val thr1 = new Thread(t1)
     val thr2 = new Thread(t2)
     thr1.start()
@@ -47,8 +56,8 @@ object StreamAppender {
     thr1.join()
     thr2.join()
   }
-
-  def inParallel(t1: Runnable, t2: Runnable) {
+*/
+  private def inParallel(t1: Runnable, t2: Runnable) {
     val thr = new Thread(t2)
     thr.start()
     t1.run()
@@ -57,34 +66,29 @@ object StreamAppender {
 
   def concat(in: InputStream, err: InputStream, out: OutputStream) = new Runnable {
     override def run() {
-      val outWriter = new PrintWriter(new OutputStreamWriter(out), true)
-      val inApp = new StreamAppender(new BufferedReader(new InputStreamReader(in)),
-                                     outWriter)
+      val outWriter = wrapOut(out)
+      val inApp = StreamAppender(in, outWriter)
+
       val errStringWriter = new StringWriter
-      val errApp = StreamAppender(new BufferedReader(new InputStreamReader(err)),
-                                  errStringWriter)
+      val errApp = StreamAppender(wrapIn(err), errStringWriter)
+
       inParallel(inApp, errApp)
 
       // append error string to out
-      val errStrApp = new StreamAppender(new BufferedReader(new StringReader(errStringWriter.toString)),
-                                         outWriter)
-      errStrApp.run()
+      StreamAppender(errStringWriter.toString, outWriter).run()
     }
   }
 }
 
 class StreamAppender(reader: BufferedReader, writer: PrintWriter) extends Runnable {
   override def run() = runAndMap(identity)
-  def runAndMap(f:String=>String): Unit = {
-    try {
-      var line = reader.readLine()
-      while (line != null) {
-        writer.println(f(line))
-        line = reader.readLine()
-      }
-    } catch {
-      case e: IOException =>
-        e.printStackTrace()
-    }
+  private def lines() = Iterator continually reader.readLine() takeWhile (_ != null)
+  def closeAll() = {
+    reader.close()
+    writer.close()
   }
+
+  def runAndMap(f: String => String) =
+    try lines() map f foreach (writer println _)
+    catch { case e: IOException => e.printStackTrace() }
 }
diff --git a/src/partest/scala/tools/partest/nest/TestFile.scala b/src/partest/scala/tools/partest/nest/TestFile.scala
index 8e8ee2c..4deaf8f 100644
--- a/src/partest/scala/tools/partest/nest/TestFile.scala
+++ b/src/partest/scala/tools/partest/nest/TestFile.scala
@@ -1,108 +1,49 @@
 /* NEST (New Scala Test)
- * Copyright 2007-2009 LAMP/EPFL
+ * Copyright 2007-2010 LAMP/EPFL
  * @author Philipp Haller
  */
 
-// $Id: TestFile.scala 16881 2009-01-09 16:28:11Z cunei $
+// $Id$
 
-package scala.tools.partest.nest
+package scala.tools.partest
+package nest
 
-import java.io.{File, BufferedReader, FileReader}
+import java.io.{ File => JFile }
 import scala.tools.nsc.Settings
-
-class TestFile(kind: String, val file: File, val fileManager: FileManager, createOutDir: Boolean) {
-  val dir = file.getParentFile
-  val dirpath = dir.getAbsolutePath
-  val fileBase: String = basename(file.getName)
-
-  // @mutates settings
-  protected def baseSettings(settings: Settings) {
-    settings.classpath.value = settings.classpath.value+
-      File.pathSeparator+dirpath
-    if (createOutDir)
-      settings.outdir.value = {
-        val outDir = new File(dir, fileBase + "-" + kind + ".obj")
-        if (!outDir.exists)
-          outDir.mkdir()
-        outDir.toString
-      }
+import scala.tools.nsc.io._
+
+abstract class TestFile(kind: String) {  
+  def file: JFile
+  def fileManager: FileManager
+	
+  val dir = file.toAbsolute.parent
+  val fileBase = file.stripExtension
+  lazy val objectDir = dir / "%s-%s.obj".format(fileBase, kind) createDirectory true
+  val flags: Option[String] = dir / "%s.flags".format(fileBase) ifFile { _.slurp().trim }
+  
+  def setOutDirTo = objectDir
+
+  def defineSettings(settings: Settings, setOutDir: Boolean) = {
+    settings.classpath append dir.path
+    if (setOutDir)
+      settings.outdir.value = setOutDirTo.path
     
-    // add additional flags found in 'testname.flags'
-    val flagsFile = new File(dir, fileBase + ".flags")
-    if (flagsFile.exists) {
-      val reader = new BufferedReader(new java.io.FileReader(flagsFile))
-      val flags = reader.readLine
-      if (flags ne null)
-        settings.parseParams(flags, error)
-    }
-  }
-
-  def defineSettings(settings: Settings) {
-    baseSettings(settings)
-  }
-
-  private def basename(name: String): String = {
-    val inx = name.lastIndexOf(".")
-    if (inx < 0) name else name.substring(0, inx)
-  }
-
-  override def toString(): String = kind+" "+file
-}
-
-case class PosTestFile(override val file: File, override val fileManager: FileManager, createOutDir: Boolean) extends TestFile("pos", file, fileManager, createOutDir) {
-  override def defineSettings(settings: Settings) {
-    baseSettings(settings)
-    settings.classpath.value = settings.classpath.value+
-      File.pathSeparator+fileManager.CLASSPATH
-  }
-}
-
-case class NegTestFile(override val file: File, override val fileManager: FileManager, createOutDir: Boolean) extends TestFile("neg", file, fileManager, createOutDir) {
-  override def defineSettings(settings: Settings) {
-    baseSettings(settings)
-    settings.classpath.value = settings.classpath.value+
-      File.pathSeparator+fileManager.CLASSPATH
-  }
-}
-
-case class RunTestFile(override val file: File, override val fileManager: FileManager, createOutDir: Boolean) extends TestFile("run", file, fileManager, createOutDir) {
-  override def defineSettings(settings: Settings) {
-    baseSettings(settings)
-    settings.classpath.value = settings.classpath.value+
-      File.pathSeparator+fileManager.CLASSPATH
-  }
-}
-
-case class ScalaCheckTestFile(override val file: File, override val fileManager: FileManager, createOutDir: Boolean) extends TestFile("scalacheck", file, fileManager, createOutDir) {
-  override def defineSettings(settings: Settings) {
-    baseSettings(settings)
-    settings.classpath.value = settings.classpath.value+
-      File.pathSeparator+fileManager.CLASSPATH
+    flags foreach (settings processArgumentString _)
+    settings.classpath append fileManager.CLASSPATH
   }
-}
 
-case class JvmTestFile(override val file: File, override val fileManager: FileManager, createOutDir: Boolean) extends TestFile("jvm", file, fileManager, createOutDir) {
-  override def defineSettings(settings: Settings) {
-    baseSettings(settings)
-    settings.classpath.value = settings.classpath.value+
-      File.pathSeparator+fileManager.CLASSPATH
-  }
+  override def toString(): String = "%s %s".format(kind, file)
 }
 
-case class Jvm5TestFile(override val file: File, override val fileManager: FileManager, createOutDir: Boolean) extends TestFile("jvm5", file, fileManager, createOutDir) {
-  override def defineSettings(settings: Settings) {
-    baseSettings(settings)
-    settings.classpath.value = settings.classpath.value+
-      File.pathSeparator+fileManager.CLASSPATH
-    settings.target.value = "jvm-1.5"
-  }
+case class PosTestFile(file: JFile, fileManager: FileManager) extends TestFile("pos")
+case class NegTestFile(file: JFile, fileManager: FileManager) extends TestFile("neg")
+case class RunTestFile(file: JFile, fileManager: FileManager) extends TestFile("run") 
+case class BuildManagerTestFile(file: JFile, fileManager: FileManager) extends TestFile("bm")
+case class ScalaCheckTestFile(file: JFile, fileManager: FileManager) extends TestFile("scalacheck")
+case class JvmTestFile(file: JFile, fileManager: FileManager) extends TestFile("jvm")
+case class ShootoutTestFile(file: JFile, fileManager: FileManager) extends TestFile("shootout") {
+  override def setOutDirTo = file.parent
 }
-
-case class ShootoutTestFile(override val file: File, override val fileManager: FileManager, createOutDir: Boolean) extends TestFile("shootout", file, fileManager, createOutDir) {
-  override def defineSettings(settings: Settings) {
-    baseSettings(settings)
-    settings.classpath.value = settings.classpath.value+
-      File.pathSeparator+fileManager.CLASSPATH
-    settings.outdir.value = file.getParent
-  }
+case class ScalapTestFile(file: JFile, fileManager: FileManager) extends TestFile("scalap") {
+  override def setOutDirTo = file.parent
 }
diff --git a/src/partest/scala/tools/partest/nest/Worker.scala b/src/partest/scala/tools/partest/nest/Worker.scala
index a94f551..3c1095f 100644
--- a/src/partest/scala/tools/partest/nest/Worker.scala
+++ b/src/partest/scala/tools/partest/nest/Worker.scala
@@ -1,24 +1,43 @@
 /* NEST (New Scala Test)
+ * Copyright 2007-2010 LAMP/EPFL
  * @author Philipp Haller
  */
 
-// $Id: Worker.scala 18847 2009-10-01 07:38:11Z phaller $
+// $Id$
 
-package scala.tools.partest.nest
+package scala.tools.partest
+package nest
 
-import java.io.{File, FileInputStream, FileOutputStream, PrintStream,
-                PrintWriter, StringWriter, FileWriter, InputStreamReader,
-                FileReader, OutputStreamWriter, BufferedReader}
+import java.io._
+import java.net.{ URLClassLoader, URL }
+import java.util.{ Timer, TimerTask }
 
-import java.net.URL
+import scala.util.Properties.{ isWin }
+import scala.tools.nsc.{ ObjectRunner, Settings, CompilerCommand, Global }
+import scala.tools.nsc.io.{ AbstractFile, PlainFile, Path, Directory, File => SFile }
+import scala.tools.nsc.reporters.ConsoleReporter
+import scala.tools.nsc.util.{ ClassPath, FakePos }
+import ClassPath.{ join, split }
 
-import scala.tools.nsc.{ObjectRunner, GenericRunnerCommand}
-
-import scala.actors.{Actor, Exit, TIMEOUT}
+import scala.actors.{ Actor, Exit, TIMEOUT }
 import scala.actors.Actor._
+import scala.tools.scalap.scalax.rules.scalasig.{ByteCode, ClassFileParser, ScalaSigAttributeParsers}
+
+import scala.collection.immutable.{ HashMap, Map => ImmMap }
+import scala.collection.Map
+
+import scala.tools.nsc.interactive.{BuildManager, RefinedBuildManager}
 
 case class RunTests(kind: String, files: List[File])
-case class Results(succ: Int, fail: Int, logs: List[LogFile], outdirs: List[File])
+case class Results(results: ImmMap[String, Int], logs: List[LogFile], outdirs: List[File])
+
+case class LogContext(file: LogFile, writers: Option[(StringWriter, PrintWriter)])
+
+abstract class TestResult {
+  def file: File
+}
+case class Result(override val file: File, context: LogContext) extends TestResult
+case class Timeout(override val file: File) extends TestResult
 
 class LogFile(parent: File, child: String) extends File(parent, child) {
   var toDelete = false
@@ -26,31 +45,26 @@ class LogFile(parent: File, child: String) extends File(parent, child) {
 
 class Worker(val fileManager: FileManager) extends Actor {
   import fileManager._
-  import scala.tools.nsc.{Settings, CompilerCommand, Global}
-  import scala.tools.nsc.reporters.ConsoleReporter
-  import scala.tools.nsc.util.FakePos
 
   var reporter: ConsoleReporter = _
+  val timer = new Timer
 
-  def error(msg: String) {
-    reporter.error(FakePos("scalac"),
-                   msg + "\n  scalac -help  gives more information")
-  }
+  def error(msg: String): Unit = reporter.error(
+    FakePos("scalac"),
+    msg + "\n  scalac -help  gives more information"
+  )
 
   def act() {
     react {
       case RunTests(kind, files) =>
-        NestUI.verbose("received "+files.length+" to test")
-        val (succ, fail) = runTests(kind, files)
-        sender ! Results(succ, fail, createdLogFiles, createdOutputDirs)
+        // NestUI.verbose("received "+files.length+" to test")
+        val master = sender
+        runTests(kind, files) { results => 
+          master ! Results(results, createdLogFiles, createdOutputDirs)
+        }
     }
   }
 
-  private def basename(name: String): String = {
-    val inx = name.lastIndexOf(".")
-    if (inx < 0) name else name.substring(0, inx)
-  }
-
   def printInfoStart(file: File, printer: PrintWriter) {
     NestUI.outline("testing: ", printer)
     val filesdir = file.getAbsoluteFile.getParentFile.getParentFile
@@ -68,7 +82,7 @@ class Worker(val fileManager: FileManager) extends Actor {
         file.getAbsolutePath.substring(filesPathLen)
       }
     }
-    NestUI.normal("[...]"+name+List.toString(List.make(totalWidth-name.length, ' ')), printer)
+    NestUI.normal("[...]%s%s".format(name, " " * (totalWidth - name.length)), printer)
   }
 
   def printInfoEnd(success: Boolean, printer: PrintWriter) {
@@ -78,92 +92,72 @@ class Worker(val fileManager: FileManager) extends Actor {
     NestUI.normal("]\n", printer)
   }
 
-  var log = ""
-  var createdLogFiles: List[LogFile] = List()
-  var createdOutputDirs: List[File] = List()
-
-  def createLogFile(dir: File, fileBase: String, kind: String): LogFile = {
-    val logFile = new LogFile(dir, fileBase + "-" + kind + ".log")
-    createdLogFiles = logFile :: createdLogFiles
-    logFile
+  def printInfoTimeout(printer: PrintWriter) {
+    NestUI.normal("[", printer)
+    NestUI.failure("TIMOUT", printer)
+    NestUI.normal("]\n", printer)
   }
 
+  var log = ""
+  var createdLogFiles: List[LogFile] = Nil
+  var createdOutputDirs: List[File] = Nil
+
   def createLogFile(file: File, kind: String): LogFile = {
-    val dir = file.getParentFile
-    val fileBase = basename(file.getName)
-    createLogFile(dir, fileBase, kind)
+    val logFile = fileManager.getLogFile(file, kind)
+    createdLogFiles ::= logFile
+    logFile
   }
 
   def createOutputDir(dir: File, fileBase: String, kind: String): File = {
-    val outDir = new File(dir, fileBase + "-" + kind + ".obj")
-    if (!outDir.exists)
-      outDir.mkdir()
-    createdOutputDirs = outDir :: createdOutputDirs
-    outDir
+    val outDir = Path(dir) / Directory("%s-%s.obj".format(fileBase, kind))
+    outDir.createDirectory()
+    createdOutputDirs ::= outDir.jfile
+    outDir.jfile
   }
 
   /* Note: not yet used/tested. */
-  def execTestObjectRunner(file: File, outDir: File, logFile: File) {
-    val consFM = new ConsoleFileManager
-    import consFM.{latestCompFile, latestLibFile, latestActFile,
-                   latestPartestFile}
-
-    val classpath: List[URL] =
-      outDir.toURL ::
-      //List(file.getParentFile.toURL) :::
-      List(latestCompFile.toURL, latestLibFile.toURL,
-           latestActFile.toURL, latestPartestFile.toURL) :::
-      (List.fromString(CLASSPATH, File.pathSeparatorChar) map { x =>
-        (new File(x)).toURL })
-    NestUI.verbose("ObjectRunner classpath: "+classpath)
-
-    try {
-      // configure input/output files
-      val logOut    = new FileOutputStream(logFile)
-      val logWriter = new PrintStream(logOut)
-
-      // grab global lock
-      fileManager.synchronized {
-
-        val oldStdOut = System.out
-        val oldStdErr = System.err
-        System.setOut(logWriter)
-        System.setErr(logWriter)
-
-        /*
-         " -Djava.library.path="+logFile.getParentFile.getAbsolutePath+
-         " -Dscalatest.output="+outDir.getAbsolutePath+
-         " -Dscalatest.lib="+LATEST_LIB+
-         " -Dscalatest.cwd="+outDir.getParent+
-         " -Djavacmd="+JAVACMD+
-         */
-
-        System.setProperty("java.library.path", logFile.getParentFile.getCanonicalFile.getAbsolutePath)
-        System.setProperty("scalatest.output", outDir.getCanonicalFile.getAbsolutePath)
-        System.setProperty("scalatest.lib", LATEST_LIB)
-        System.setProperty("scalatest.cwd", outDir.getParent)
-
-        ObjectRunner.run(classpath, "Test", List("jvm"))
-
-        logWriter.flush()
-        logWriter.close()
-
-        System.setOut(oldStdOut)
-        System.setErr(oldStdErr)
-      }
-
-      /*val out = new FileOutputStream(logFile, true)
-      Console.withOut(new PrintStream(out)) {
-        ObjectRunner.run(classpath, "Test", List("jvm"))
-      }
-      out.flush
-      out.close*/
-    } catch {
-      case e: Exception =>
-        NestUI.verbose(e+" ("+file.getPath+")")
-        e.printStackTrace()
-    }
-  }
+  // def execTestObjectRunner(file: File, outDir: File, logFile: File) {
+  //   val consFM = new ConsoleFileManager
+  // 
+  //   val classpath: List[URL] = {
+  //     import consFM.{ latestCompFile, latestLibFile, latestPartestFile }
+  //     val units = (
+  //       List(outDir, latestCompFile, latestLibFile, latestPartestFile) :::
+  //       ((CLASSPATH split File.pathSeparatorChar).toList map (x => new File(x)))
+  //     )
+  //     units map (_.toURI.toURL)
+  //   }
+  // 
+  //   NestUI.verbose("ObjectRunner classpath: "+classpath)
+  // 
+  //   try {
+  //     // configure input/output files
+  //     val logOut    = new FileOutputStream(logFile)
+  //     val logWriter = new PrintStream(logOut)
+  // 
+  //     // grab global lock
+  //     fileManager.synchronized {
+  //       withOutputRedirected(logWriter) {
+  //         System.setProperty("java.library.path", logFile.getParentFile.getCanonicalFile.getAbsolutePath)
+  //         System.setProperty("partest.output", outDir.getCanonicalFile.getAbsolutePath)
+  //         System.setProperty("partest.lib", LATEST_LIB)
+  //         System.setProperty("partest.cwd", outDir.getParent)
+  //         ObjectRunner.run(classpath, "Test", List("jvm"))
+  //       }
+  //     }
+  // 
+  //     /*val out = new FileOutputStream(logFile, true)
+  //     Console.withOut(new PrintStream(out)) {
+  //       ObjectRunner.run(classpath, "Test", List("jvm"))
+  //     }
+  //     out.flush
+  //     out.close*/
+  //   } catch {
+  //     case e: Exception =>
+  //       NestUI.verbose(e+" ("+file.getPath+")")
+  //       e.printStackTrace()
+  //   }
+  // }
 
   def javac(outDir: File, files: List[File], output: File): Boolean = {
     // compile using command-line javac compiler
@@ -176,7 +170,7 @@ class Worker(val fileManager: FileManager) extends Actor {
 
     val cmd = javacCmd+
       " -d "+outDir.getAbsolutePath+
-      " -classpath "+outDir+File.pathSeparator+CLASSPATH+
+      " -classpath "+ join(outDir.toString, CLASSPATH) +
       " "+files.mkString(" ")
 
     val (success, msg) = try {
@@ -209,55 +203,66 @@ class Worker(val fileManager: FileManager) extends Actor {
     val in = proc.getInputStream
     val err = proc.getErrorStream
     val writer = new PrintWriter(new FileWriter(output), true)
-    val inApp = new StreamAppender(new BufferedReader(new InputStreamReader(in)),
-                                   writer)
-    val errApp = new StreamAppender(new BufferedReader(new InputStreamReader(err)),
-                                    writer)
+    val inApp = StreamAppender(in, writer)
+    val errApp = StreamAppender(err, writer)
     val async = new Thread(errApp)
     async.start()
     inApp.run()
     async.join()
     writer.close()
-    try {
-      proc.exitValue()
-    } catch {
-      case e: IllegalThreadStateException => 0
-    }
+    
+    try proc.exitValue()
+    catch { case _: IllegalThreadStateException => 0 }
   }
 
   def execTest(outDir: File, logFile: File, fileBase: String) {
     // check whether there is a ".javaopts" file
     val argsFile = new File(logFile.getParentFile, fileBase+".javaopts")
     val argString = if (argsFile.exists) {
-      NestUI.verbose("argsFile: "+argsFile)
+      NestUI.verbose("Found javaopts file: "+argsFile)
       val fileReader = new FileReader(argsFile)
       val reader = new BufferedReader(fileReader)
       val options = reader.readLine()
       reader.close()
+      NestUI.verbose("Found javaopts file '%s', using options: '%s'".format(argsFile, options))
       options
     } else ""
-    NestUI.verbose("JAVA_OPTS: "+argString)
-
-    val cp = System.getProperty("java.class.path", ".")
-    NestUI.verbose("java.class.path: "+cp)
 
     def quote(path: String) = "\""+path+"\""
 
-    val cmd =
-      JAVACMD+
-      " "+argString+
-      " "+JAVA_OPTS+
-      " -classpath "+outDir+File.pathSeparator+CLASSPATH+
-      " -Djava.library.path="+logFile.getParentFile.getAbsolutePath+
-      " -Dscalatest.output="+outDir.getAbsolutePath+
-      " -Dscalatest.lib="+LATEST_LIB+
-      " -Dscalatest.cwd="+outDir.getParent+
-      " -Djavacmd="+JAVACMD+
-      " -Duser.language=en -Duser.country=US"+
-      " scala.tools.nsc.MainGenericRunner"+
-      " Test jvm"
-    NestUI.verbose(cmd)
-
+    // Note! As this currently functions, JAVA_OPTS must precede argString
+    // because when an option is repeated to java only the last one wins.
+    // That means until now all the .javaopts files were being ignored because
+    // they all attempt to change options which are also defined in
+    // partest.java_opts, leading to debug output like:
+    //
+    // debug: Found javaopts file 'files/shootout/message.scala-2.javaopts', using options: '-Xss32k'
+    // debug: java -Xss32k -Xss2m -Xms256M -Xmx1024M -classpath [...]
+    val propertyOptions = List(
+      "-Djava.library.path="+logFile.getParentFile.getAbsolutePath,
+      "-Dpartest.output="+outDir.getAbsolutePath,
+      "-Dpartest.lib="+LATEST_LIB,
+      "-Dpartest.cwd="+outDir.getParent,
+      "-Djavacmd="+JAVACMD,
+      "-Duser.language=en -Duser.country=US"
+    ) ::: (
+      if (isPartestDebug) List("-Dpartest.debug=true") else Nil
+    )
+
+    val cmd = ( 
+      List(
+        JAVACMD,
+        JAVA_OPTS,
+        argString,
+        "-classpath " + join(outDir.toString, CLASSPATH)
+      ) ::: propertyOptions ::: List(
+        "scala.tools.nsc.MainGenericRunner",
+        "-usejavacp",
+        "Test",
+        "jvm"
+      )
+    ) mkString " "
+    
     runCommand(cmd, logFile)
 
     if (fileManager.showLog) {
@@ -270,72 +275,63 @@ class Worker(val fileManager: FileManager) extends Actor {
       log = swriter.toString
     }
   }
-
-  def existsCheckFile(dir: File, fileBase: String, kind: String) = {
-    val checkFile = {
-      val chkFile = new File(dir, fileBase + ".check")
-      if (chkFile.isFile)
-        chkFile
-      else
-        new File(dir, fileBase + "-" + kind + ".check")
-    }
-    checkFile.exists && checkFile.canRead
+  
+  def getCheckFile(dir: File, fileBase: String, kind: String) = {
+    def chkFile(s: String) = Directory(dir) / "%s%s.check".format(fileBase, s)
+    val checkFile = if (chkFile("").isFile) chkFile("") else chkFile("-" + kind)
+    
+    if (checkFile.canRead) Some(checkFile) else None
   }
 
-  def compareOutput(dir: File, fileBase: String, kind: String, logFile: File): String = {
+  def existsCheckFile(dir: File, fileBase: String, kind: String) = 
+    getCheckFile(dir, fileBase, kind).isDefined
+
+  def compareOutput(dir: File, fileBase: String, kind: String, logFile: File): String =
     // if check file exists, compare with log file
-    val checkFile = {
-      val chkFile = new File(dir, fileBase + ".check")
-      if (chkFile.isFile)
-        chkFile
-      else
-        new File(dir, fileBase + "-" + kind + ".check")
-    }
-    if (!checkFile.exists || !checkFile.canRead) {
-      val reader = new BufferedReader(new FileReader(logFile))
-      val swriter = new StringWriter
-      val pwriter = new PrintWriter(swriter, true)
-      val appender = new StreamAppender(reader, pwriter)
-      appender.run()
-      swriter.toString
-    }
-    else fileManager.compareFiles(logFile, checkFile)
-  }
+    getCheckFile(dir, fileBase, kind) match {
+      case Some(f)  => fileManager.compareFiles(logFile, f.jfile)
+      case _        => file2String(logFile)
+    }    
 
-  def file2String(logFile: File) = {
-    val logReader = new BufferedReader(new FileReader(logFile))
-    val strWriter = new StringWriter
-    val logWriter = new PrintWriter(strWriter, true)
-    val logAppender = new StreamAppender(logReader, logWriter)
-    logAppender.run()
-    logReader.close()
-    strWriter.toString
-  }
+  def file2String(logFile: File) = SFile(logFile).slurp()
+  def isJava(f: File) = SFile(f) hasExtension "java"
+  def isScala(f: File) = SFile(f) hasExtension "scala"
+  def isJavaOrScala(f: File) = isJava(f) || isScala(f)
 
   /** Runs a list of tests.
    *
    * @param kind  The test kind (pos, neg, run, etc.)
    * @param files The list of test files
    */
-  def runTests(kind: String, files: List[File]): (Int, Int) = {
+  def runTests(kind: String, files: List[File])(topcont: ImmMap[String, Int] => Unit) {
     val compileMgr = new CompileManager(fileManager)
     var errors = 0
     var succeeded = true
     var diff = ""
     var log = ""
+    
+    def fail(what: Any) {
+      NestUI.verbose("scalac: compilation of "+what+" failed\n")
+      succeeded = false
+    }
+    def diffCheck(latestDiff: String) = {
+      diff = latestDiff
+      if (latestDiff != "") {
+        NestUI.verbose("output differs from log file\n")
+        succeeded = false
+      }
+    }
 
     /** 1. Creates log file and output directory.
      *  2. Runs <code>script</code> function, providing log file and
      *     output directory as arguments.
-     *  3. Prints test result.
-     *  4. Shows log/diff if enabled.
      */
-    def runInContext(file: File, kind: String, script: (File, File) => Unit) {
+    def runInContext(file: File, kind: String, script: (File, File) => Unit): LogContext = {
       // when option "--failed" is provided
       // execute test only if log file is present
       // (which means it failed before)
       val logFile = createLogFile(file, kind)
-      if (!fileManager.failed || (logFile.exists && logFile.canRead)) {
+      if (!fileManager.failed || logFile.canRead) {
         val swr = new StringWriter
         val wr = new PrintWriter(swr)
         succeeded = true
@@ -351,7 +347,15 @@ class Worker(val fileManager: FileManager) extends Actor {
 
         // run test-specific code
         try {
-          script(logFile, outDir)
+          if (isPartestDebug) {
+            val t1 = System.currentTimeMillis
+            script(logFile, outDir)
+            val t2 = System.currentTimeMillis
+            fileManager.recordTestTiming(file.getPath, t2 - t1)
+          }
+          else {
+            script(logFile, outDir)
+          }
         } catch {
           case e: Exception =>
             val writer = new PrintWriter(new FileWriter(logFile), true)
@@ -360,180 +364,275 @@ class Worker(val fileManager: FileManager) extends Actor {
             succeeded = false
         }
 
-        if (!succeeded) {
-          errors += 1
-          NestUI.verbose("incremented errors: "+errors)
-        } else {
-          // delete log file only if test was successful
-          logFile.toDelete = true
-        }
-
-        printInfoEnd(succeeded, wr)
-        wr.flush()
-        swr.flush() //TODO: needed?
-        NestUI.normal(swr.toString)
-        if (!succeeded && fileManager.showDiff && diff != "")
-          NestUI.normal(diff)
-        else if (!succeeded && fileManager.showLog)
-          showLog(logFile)
-      }
+        LogContext(logFile, Some((swr, wr)))
+      } else
+        LogContext(logFile, None)
     }
 
     def compileFilesIn(dir: File, kind: String, logFile: File, outDir: File) {
-      val testFiles = dir.listFiles.toList
-      val javaFiles = testFiles.filter(_.getName.endsWith(".java"))
-      val scalaFiles = testFiles.filter(_.getName.endsWith(".scala"))
-      if (!(scalaFiles.isEmpty && javaFiles.isEmpty) &&
-          !compileMgr.shouldCompile(outDir, javaFiles ::: scalaFiles, kind, logFile)) {
-        NestUI.verbose("compilation of "+scalaFiles+" failed\n")
-        succeeded = false
-      } else
-        if (!javaFiles.isEmpty) {
+      val testFiles = dir.listFiles.toList filter isJavaOrScala
+
+      def isInGroup(f: File, num: Int) = SFile(f).stripExtension endsWith ("_" + num)
+      val groups = (0 to 9).toList map (num => testFiles filter (f => isInGroup(f, num)))
+      val noGroupSuffix = testFiles filterNot (groups.flatten contains)
+
+      def compileGroup(g: List[File]) {
+        val (scalaFiles, javaFiles) = g partition isScala
+
+        if (scalaFiles.nonEmpty) {
+          if (!compileMgr.shouldCompile(outDir, javaFiles ::: scalaFiles, kind, logFile))
+            fail(g)
+        }
+        
+        if (succeeded && javaFiles.nonEmpty) {
           succeeded = javac(outDir, javaFiles, logFile)
-          if (succeeded) {
-            scalaFiles foreach { scalaFile =>
-              if (!compileMgr.shouldCompile(outDir, List(scalaFile), kind, logFile)) {
-                NestUI.verbose("compilation of "+scalaFile+" failed\n")
-                succeeded = false
-              }
-            }
-          }
+          if (succeeded && scalaFiles.nonEmpty && !compileMgr.shouldCompile(outDir, scalaFiles, kind, logFile))
+            fail(scalaFiles)
         }
+      }      
+      
+      if (noGroupSuffix.nonEmpty)
+        compileGroup(noGroupSuffix)
+      
+      groups foreach (grp => if (succeeded) compileGroup(grp))
     }
 
     def failCompileFilesIn(dir: File, kind: String, logFile: File, outDir: File) {
-      val testFiles = dir.listFiles.toList
-      val javaFiles = testFiles.filter(_.getName.endsWith(".java"))
-      val scalaFiles = testFiles.filter(_.getName.endsWith(".scala"))
-      if (!(scalaFiles.isEmpty && javaFiles.isEmpty) &&
-          !compileMgr.shouldFailCompile(outDir, javaFiles ::: scalaFiles, kind, logFile)) {
-        NestUI.verbose("compilation of "+scalaFiles+" failed\n")
-        succeeded = false
+      val testFiles   = dir.listFiles.toList
+      val sourceFiles = testFiles filter isJavaOrScala
+      
+      if (sourceFiles.nonEmpty) {
+        if (!compileMgr.shouldFailCompile(outDir, sourceFiles, kind, logFile))
+          fail(testFiles filter isScala)
       }
     }
-
-    def runJvmTest(file: File, kind: String) {
+    
+    def runTestCommon(file: File, kind: String, expectFailure: Boolean)(onSuccess: (File, File) => Unit): LogContext =
       runInContext(file, kind, (logFile: File, outDir: File) => {
+ 
         if (file.isDirectory) {
-          compileFilesIn(file, kind, logFile, outDir)
-        } else if (!compileMgr.shouldCompile(List(file), kind, logFile)) {
-          NestUI.verbose("compilation of "+file+" failed\n")
-          succeeded = false
+          val f = if (expectFailure) failCompileFilesIn _ else compileFilesIn _
+          f(file, kind, logFile, outDir)
         }
-        if (succeeded) { // run test
-          val fileBase = basename(file.getName)
-          val dir      = file.getParentFile
+        else {
+          val f: (List[File], String, File) => Boolean =
+            if (expectFailure) compileMgr.shouldFailCompile _
+            else compileMgr.shouldCompile _
+            
+          if (!f(List(file), kind, logFile))
+            fail(file)
+        }
+        
+        if (succeeded)  // run test
+          onSuccess(logFile, outDir)
+      })
 
-          //TODO: detect whether we have to use Runtime.exec
-          val useRuntime = true
+    def runJvmTest(file: File, kind: String): LogContext =
+      runTestCommon(file, kind, expectFailure = false)((logFile, outDir) => {
+        val fileBase = basename(file.getName)
+        val dir      = file.getParentFile
+
+        //TODO: detect whether we have to use Runtime.exec
+        // val useRuntime = true
+        // 
+        // if (useRuntime)
+        //   execTest(outDir, logFile, fileBase)
+        // else
+        //   execTestObjectRunner(file, outDir, logFile)
+        // // NestUI.verbose(this+" finished running "+fileBase)
+        execTest(outDir, logFile, fileBase)
+
+        diffCheck(compareOutput(dir, fileBase, kind, logFile))
+      })
 
-          if (useRuntime)
-            execTest(outDir, logFile, fileBase)
-          else
-            execTestObjectRunner(file, outDir, logFile)
-          NestUI.verbose(this+" finished running "+fileBase)
+    def processSingleFile(file: File): LogContext = kind match {
+      case "scalacheck" =>
+        runTestCommon(file, kind, expectFailure = false)((logFile, outDir) => {
+          val consFM = new ConsoleFileManager
+          import consFM.{ latestCompFile, latestLibFile, latestPartestFile }
+          
+          NestUI.verbose("compilation of "+file+" succeeded\n")
 
-          diff = compareOutput(dir, fileBase, kind, logFile)
-          if (!diff.equals("")) {
-            NestUI.verbose("output differs from log file\n")
-            succeeded = false
+          val scalacheckURL = PathSettings.scalaCheck.toURL
+          val outURL = outDir.getCanonicalFile.toURI.toURL
+          val classpath: List[URL] =
+            List(outURL, scalacheckURL, latestCompFile.toURI.toURL, latestLibFile.toURI.toURL, latestPartestFile.toURI.toURL).distinct
+          
+          NestUI.debug("scalacheck urls")
+          classpath foreach (x => NestUI.debug(x.toString))
+
+          val logWriter = new PrintStream(new FileOutputStream(logFile))
+          
+          withOutputRedirected(logWriter) {
+            ObjectRunner.run(classpath, "Test", Nil)
           }
-        }
+          
+          NestUI.verbose(SFile(logFile).slurp())
+          // obviously this must be improved upon
+          succeeded = SFile(logFile).lines() forall (_ contains " OK")
       })
-    }
 
-    kind match {
-      case "scalacheck" => for (file <- files)
-        runInContext(file, kind, (logFile: File, outDir: File) => {
-          if (file.isDirectory) {
-            compileFilesIn(file, kind, logFile, outDir)
-          } else if (!compileMgr.shouldCompile(List(file), kind, logFile)) {
-            NestUI.verbose("compilation of "+file+" failed\n")
-            succeeded = false
-          }
-          if (succeeded) {
-            NestUI.verbose("compilation of "+file+" succeeded\n")
-
-            val libs = new File(fileManager.LIB_DIR)
-            val urls = List((new File(libs, "ScalaCheck.jar")).toURL,
-                            (new File(libs, "ScalaCheckHelper.jar")).toURL)
-            val outURL = outDir.getCanonicalFile.toURL
-            val urlArr = (outURL :: urls).toArray
-            NestUI.verbose("loading classes from:")
-            urlArr foreach {url => NestUI.verbose(url.toString)}
-            val loader = new java.net.URLClassLoader(urlArr, fileManager.getClass.getClassLoader)
-            
-            (try {
-              Some(Class.forName("ScalaCheckHelper", true, loader))
-            } catch {
-              case se: SecurityException => None
-              case cnfe: ClassNotFoundException => None
-            }) match {
-              case None =>
-                NestUI.verbose("cannot find ScalaCheckHelper class")
-                succeeded = false
-              case Some(clazz) =>
-                val method = clazz.getMethod("passed", Array(classOf[File], classOf[Array[URL]]): _*)
-                val res = method.invoke(null, Array(logFile, urlArr): _*).asInstanceOf[String]
-                NestUI.verbose("ScalaCheck result: "+res)
-                succeeded = res.equals("ok")
-            }
-          }
+      case "pos" =>
+        runTestCommon(file, kind, expectFailure = false)((_, _) => ())
+
+      case "neg" =>      
+        runTestCommon(file, kind, expectFailure = true)((logFile, outDir) => {
+          // compare log file to check file
+          val fileBase = basename(file.getName)
+          val dir      = file.getParentFile
+
+          diffCheck(
+            // diff is contents of logFile
+            if (!existsCheckFile(dir, fileBase, kind)) file2String(logFile)
+            else compareOutput(dir, fileBase, kind, logFile)
+          )
         })
-      case "pos" => for (file <- files)
-        runInContext(file, kind, (logFile: File, outDir: File) => {
-          if (file.isDirectory) {
-            compileFilesIn(file, kind, logFile, outDir)
-          } else if (!compileMgr.shouldCompile(List(file), kind, logFile)) {
-            NestUI.verbose("compilation of "+file+" failed\n")
+
+      case "run" | "jvm" =>
+        runJvmTest(file, kind)
+
+      case "buildmanager" =>
+        val logFile = createLogFile(file, kind)
+        if (!fileManager.failed || logFile.canRead) {
+          val swr = new StringWriter
+          val wr = new PrintWriter(swr)
+          succeeded = true; diff = ""
+          printInfoStart(file, wr)
+          val (outDir, testFile, changesDir, fileBase) = 
+          
+          if (!file.isDirectory) {
             succeeded = false
-          }
-        })
-      case "neg" =>
-        for (file <- files) {
-          runInContext(file, kind, (logFile: File, outDir: File) => {
-            if (file.isDirectory) {
-              failCompileFilesIn(file, kind, logFile, outDir)
-            } else if (!compileMgr.shouldFailCompile(List(file), kind, logFile)) {
+            (null, null, null, null)
+          } else {
+            val fileBase: String = basename(file.getName)
+            NestUI.verbose(this+" running test "+fileBase)
+            val outDir = createOutputDir(file, fileBase, kind)
+            if (!outDir.exists) outDir.mkdir()
+            val testFile = new File(file, fileBase + ".test")
+            val changesDir = new File(file, fileBase + ".changes")
+            if (changesDir.isFile || !testFile.isFile) {
+              // if changes exists then it has to be a dir
+              if (!testFile.isFile) NestUI.verbose("invalid build manager test file")
+              if (changesDir.isFile) NestUI.verbose("invalid build manager changes directory")
               succeeded = false
+              (null, null, null, null)
+            } else {
+              copyTestFiles(file, outDir)
+              NestUI.verbose("outDir:  "+outDir)
+              NestUI.verbose("logFile: "+logFile)
+              (outDir, testFile, changesDir, fileBase)
             }
-            if (succeeded) { // compare log file to check file
-              val fileBase = basename(file.getName)
-              val dir      = file.getParentFile
-              if (!existsCheckFile(dir, fileBase, kind)) {
-                // diff is contents of logFile
-                diff = file2String(logFile)
-              } else
-                diff = compareOutput(dir, fileBase, kind, logFile)
-
-              if (!diff.equals("")) {
-                NestUI.verbose("output differs from log file\n")
-                succeeded = false
+          }
+            
+          if (succeeded) {
+            // Pre-conditions satisfied
+              
+            try {
+              val sourcepath = outDir.getAbsolutePath+File.separator
+
+              // configure input/output files
+              val logWriter = new PrintStream(new FileOutputStream(logFile))
+              val testReader = new BufferedReader(new FileReader(testFile))
+              val logConsoleWriter = new PrintWriter(logWriter)
+
+              // create proper settings for the compiler
+              val settings = new Settings(error)
+              settings.outdir.value = outDir.getCanonicalFile.getAbsolutePath
+              settings.sourcepath.value = sourcepath
+              settings.classpath.value = fileManager.CLASSPATH
+              settings.Ybuildmanagerdebug.value = true
+
+              // simulate Build Manager loop
+              val prompt = "builder > "
+              reporter = new ConsoleReporter(settings, scala.Console.in, logConsoleWriter)
+              val bM: BuildManager =
+                  new RefinedBuildManager(settings) {
+                    override protected def newCompiler(settings: Settings) =
+                        new BuilderGlobal(settings, reporter) 
+                  }
+              
+              val testCompile = (line: String) => {
+                NestUI.verbose("compiling " + line)
+                val args = (line split ' ').toList
+                val command = new CompilerCommand(args, settings)
+                bM.update(filesToSet(settings.sourcepath.value, command.files), Set.empty)
+                !reporter.hasErrors
               }
+              
+              val updateFiles = (line: String) => {
+                NestUI.verbose("updating " + line)
+                val res = 
+                  ((line split ' ').toList).forall(u => {
+                    (u split "=>").toList match {
+                        case origFileName::(newFileName::Nil) =>
+                          val newFile = new File(changesDir, newFileName)
+                          if (newFile.isFile) {
+                            val v = overwriteFileWith(new File(outDir, origFileName), newFile)
+                            if (!v)
+                              NestUI.verbose("'update' operation on " + u + " failed")
+                            v
+                          } else {
+                            NestUI.verbose("File " + newFile + " is invalid") 
+                            false
+                          }
+                        case a =>
+                          NestUI.verbose("Other =: " + a)
+                          false
+                    }
+                  })
+                if (!res)
+                  NestUI.verbose("updating failed")
+                else
+                  NestUI.verbose("updating succeeded")
+                res
+              }
+
+              def loop() {
+                val command = testReader.readLine()
+                if ((command ne null) && command.length() > 0) {
+                  val commandResult = command match {
+                    case s if (s.startsWith(">>update "))   =>
+                      updateFiles(s.stripPrefix(">>update "))
+                    case s if (s.startsWith(">>compile "))  =>
+                      val files = s.stripPrefix(">>compile ")
+                      logWriter.println(prompt + files)
+                      testCompile(files) // In the end, it can finish with an error
+                    case _                                  =>
+                      NestUI.verbose("wrong command in test file: " + command)
+                      false
+                    }
+                
+                  if (commandResult) loop()
+                    
+                } else {
+                  NestUI.verbose("finished")
+                  succeeded = true 
+                }
+              }
+            
+              withOutputRedirected(logWriter) {
+                loop()
+                testReader.close()
+              }
+              fileManager.mapFile(logFile, "tmp", file, _.replace(sourcepath, "").
+                      replaceAll(java.util.regex.Matcher.quoteReplacement("\\"), "/"))
+
+              diffCheck(compareOutput(file, fileBase, kind, logFile))
             }
-          })
-        }
-      case "run" =>
-        for (file <- files) {
-          runJvmTest(file, kind)
-        }
-      case "jvm" =>
-        for (file <- files) {
-          runJvmTest(file, kind)
-        }
-      case "jvm5" =>
-        for (file <- files) {
-          runJvmTest(file, kind)
-        }
+            LogContext(logFile, Some((swr, wr)))
+          } else 
+            LogContext(logFile, None)
+        } else
+          LogContext(logFile, None)
+
       case "res" => {
-        for (file <- files) {
           // when option "--failed" is provided
           // execute test only if log file is present
           // (which means it failed before)
 
           //val (logFileOut, logFileErr) = createLogFiles(file, kind)
           val logFile = createLogFile(file, kind)
-          if (!fileManager.failed || (logFile.exists && logFile.canRead)) {
+          if (!fileManager.failed || logFile.canRead) {
             val swr = new StringWriter
             val wr = new PrintWriter(swr)
             succeeded = true; diff = ""; log = ""
@@ -563,7 +662,7 @@ class Worker(val fileManager: FileManager) extends Actor {
               "-d "+outDir.getCanonicalFile.getAbsolutePath+
               " -Xresident"+
               " -sourcepath "+sourcepath
-            val argList = List.fromString(argString, ' ')
+            val argList = argString split ' ' toList
 
             // configure input/output files
             val logOut    = new FileOutputStream(logFile)
@@ -575,8 +674,8 @@ class Worker(val fileManager: FileManager) extends Actor {
             val settings = new Settings(error)
             settings.sourcepath.value = sourcepath
             settings.classpath.value = fileManager.CLASSPATH
-            reporter = new ConsoleReporter(settings, Console.in, logConsoleWriter)
-            val command = new CompilerCommand(argList, settings, error, false)
+            reporter = new ConsoleReporter(settings, scala.Console.in, logConsoleWriter)
+            val command = new CompilerCommand(argList, settings)
             object compiler extends Global(command.settings, reporter)
 
             // simulate resident compiler loop
@@ -584,11 +683,11 @@ class Worker(val fileManager: FileManager) extends Actor {
 
             val resCompile = (line: String) => {
               NestUI.verbose("compiling "+line)
-              val cmdArgs = List.fromString(line, ' ') map { fs => new File(dir, fs).getAbsolutePath }
+              val cmdArgs = (line split ' ').toList map (fs => new File(dir, fs).getAbsolutePath)
               NestUI.verbose("cmdArgs: "+cmdArgs)
               val sett = new Settings(error)
               sett.sourcepath.value = sourcepath
-              val command = new CompilerCommand(cmdArgs, sett, error, true)
+              val command = new CompilerCommand(cmdArgs, sett)
               (new compiler.Run) compile command.files
             }
 
@@ -596,6 +695,7 @@ class Worker(val fileManager: FileManager) extends Actor {
               logWriter.print(prompt)
               val line = resReader.readLine()
               if ((line ne null) && line.length() > 0) {
+/*
                 val parent = self
                 self.trapExit = true
                 val child = link {
@@ -617,90 +717,48 @@ class Worker(val fileManager: FileManager) extends Actor {
                       false
                   }
                 }
-
+*/
+                action(line)
                 loop(action)
               }
             }
-            val oldStdOut = System.out
-            val oldStdErr = System.err
-            System.setOut(logWriter)
-            System.setErr(logWriter)
-            loop(resCompile)
-            resReader.close()
-            logWriter.flush()
-            logWriter.close()
-    
-            System.setOut(oldStdOut)
-            System.setErr(oldStdErr)
-
-            val tempLogFile = new File(dir, fileBase+".temp.log")
-            val logFileReader = new BufferedReader(new FileReader(logFile))
-            val tempLogFilePrinter = new PrintWriter(new FileWriter(tempLogFile))
-            val appender =
-              new StreamAppender(logFileReader, tempLogFilePrinter)
-
-	    // function that removes a given string from another string
-	    def removeFrom(line: String, path: String): String = {
-              // find `path` in `line`
-              val index = line.indexOf(path)
-              if (index != -1) {
-                line.substring(0, index) + line.substring(index + path.length, line.length)
-              } else line
-            }
-
-            appender.runAndMap({ s =>
-              val woPath = removeFrom(s, dir.getAbsolutePath/*.replace(File.separatorChar,'/')*/+File.separator)
-              // now replace single '\' with '/'
-              woPath.replace('\\', '/')
-            })
-            logFileReader.close()
-            tempLogFilePrinter.close()
             
-            val tempLogFileReader = new BufferedReader(new FileReader(tempLogFile))
-            val logFilePrinter= new PrintWriter(new FileWriter(logFile), true)
-            (new StreamAppender(tempLogFileReader, logFilePrinter)).run
-            tempLogFileReader.close()
-            logFilePrinter.close()
-            
-            tempLogFile.delete()
+            withOutputRedirected(logWriter) {
+              loop(resCompile)
+              resReader.close()
+            }
             
-            diff = compareOutput(dir, fileBase, kind, logFile)
-            if (!diff.equals("")) {
-              NestUI.verbose("output differs from log file\n")
-              succeeded = false
+            def replaceSlashes(s: String): String = {
+                val path = dir.getAbsolutePath+File.separator
+                // find `path` in `line`
+                val index = s.indexOf(path)
+                val line =
+                  if (index != -1)
+                    s.substring(0, index) + s.substring(index + path.length, s.length)
+                  else s
+                line.replace('\\', '/')
             }
 
+            fileManager.mapFile(logFile, "tmp", dir, replaceSlashes)
+            diffCheck(compareOutput(dir, fileBase, kind, logFile))
+
             } catch {
               case e: Exception =>
 	        e.printStackTrace()
                 succeeded = false
             }
 
-            // delete log file only if test was successful
-            if (succeeded)
-              logFile.toDelete = true
-
-            if (!succeeded) {
-              errors += 1
-              NestUI.verbose("incremented errors: "+errors)
-            }
-            printInfoEnd(succeeded, wr)           
-            wr.flush()
-            swr.flush()
-            NestUI.normal(swr.toString)
-
-            if (!succeeded && fileManager.showDiff) NestUI.normal(diff)
-            if (!succeeded && fileManager.showLog) showLog(logFile)
-          }
+            LogContext(logFile, Some((swr, wr)))
+          } else
+            LogContext(logFile, None)
         }
-      }
+
       case "shootout" => {
-        for (file <- files) {
           // when option "--failed" is provided
           // execute test only if log file is present
           // (which means it failed before)
           val logFile = createLogFile(file, kind)
-          if (!fileManager.failed || (logFile.exists && logFile.canRead)) {
+          if (!fileManager.failed || logFile.canRead) {
             val swr = new StringWriter
             val wr = new PrintWriter(swr)
             succeeded = true; diff = ""; log = ""
@@ -734,14 +792,17 @@ class Worker(val fileManager: FileManager) extends Actor {
               } else {
                 NestUI.verbose("compilation of "+testFile+"succeeded")
                 // -------- run test --------
-                
-                //TODO: detect whether we have to use Runtime.exec
-                val useRuntime = true
 
-                if (useRuntime)
-                  execTest(outDir, logFile, fileBase)
-                else
-                  execTestObjectRunner(file, outDir, logFile)
+                //TODO: detect whether we have to use Runtime.exec
+                // val useRuntime = true
+                // 
+                // if (useRuntime)
+                //   execTest(outDir, logFile, fileBase)
+                // else
+                //   execTestObjectRunner(file, outDir, logFile)
+                
+                execTest(outDir, logFile, fileBase)
+                  
                 NestUI.verbose(this+" finished running "+fileBase)
               } // successful compile
             } catch { // *catch-all*
@@ -750,38 +811,65 @@ class Worker(val fileManager: FileManager) extends Actor {
                 succeeded = false
             }
 
-            diff = compareOutput(dir, fileBase, kind, logFile)
-            if (!diff.equals("")) {
-              NestUI.verbose("output differs from log file\n")
-              succeeded = false
-            }
+            diffCheck(compareOutput(dir, fileBase, kind, logFile))
 
-            // delete log file only if test was successful
-            if (succeeded)
-              logFile.toDelete = true
+            LogContext(logFile, Some((swr, wr)))
+          } else
+            LogContext(logFile, None)
+        }
 
-            if (!succeeded) {
-              errors += 1
-              NestUI.verbose("incremented errors: "+errors)
-            }
-            printInfoEnd(succeeded, wr)           
-            wr.flush()
-            swr.flush()
-            NestUI.normal(swr.toString)
+      case "scalap" => {
+
+        runInContext(file, kind, (logFile: File, outDir: File) => {
+          val sourceDir = file.getParentFile
+          val sourceDirName = sourceDir.getName
+
+          // 1. Find file with result text
+          val results = sourceDir.listFiles(new FilenameFilter {
+            def accept(dir: File, name: String) = name == "result.test"
+          })
+          
+          if (results.length != 1) {
+            NestUI.verbose("Result file not found in directory " + sourceDirName + " \n")
+          } else {
+            val resFile = results(0)
+            // 2. Compile source file
+            if (!compileMgr.shouldCompile(outDir, List(file), kind, logFile)) {
+              NestUI.verbose("compilerMgr failed to compile %s to %s".format(file, outDir))
+              succeeded = false
+            } else {
+
+              // 3. Decompile file and compare results
+              val isPackageObject = sourceDir.getName.startsWith("package")
+              val className = sourceDirName.capitalize + (if (!isPackageObject) "" else ".package")
+              val url = outDir.toURI.toURL
+              val loader = new URLClassLoader(Array(url), getClass.getClassLoader)
+              val clazz = loader.loadClass(className)
+
+              val byteCode = ByteCode.forClass(clazz)
+              val result = scala.tools.scalap.Main.decompileScala(byteCode.bytes, isPackageObject)
+
+              try {
+                val fstream = new FileWriter(logFile);
+                val out = new BufferedWriter(fstream);
+                out.write(result)
+                out.close();
+              } catch {
+                case e: IOException => NestUI.verbose(e.getMessage()); succeeded = false
+              }
 
-            if (!succeeded && fileManager.showDiff) NestUI.normal(diff)
-            if (!succeeded && fileManager.showLog) showLog(logFile)
+              diffCheck(fileManager.compareFiles(logFile, resFile))
+            }
           }
-        }
+        })
       }
+
       case "script" => {
-        val osName = System.getProperty("os.name", "")
-        for (file <- files) {
           // when option "--failed" is provided
           // execute test only if log file is present
           // (which means it failed before)
           val logFile = createLogFile(file, kind)
-          if (!fileManager.failed || (logFile.exists && logFile.canRead)) {
+          if (!fileManager.failed || logFile.canRead) {
             val swr = new StringWriter
             val wr = new PrintWriter(swr)
             succeeded = true; diff = ""; log = ""
@@ -803,7 +891,7 @@ class Worker(val fileManager: FileManager) extends Actor {
 
             try {
               val cmdString =
-                if (osName startsWith "Windows") {
+                if (isWin) {
                   val batchFile = new File(file.getParentFile, fileBase+".bat")
                   NestUI.verbose("batchFile: "+batchFile)
                   batchFile.getAbsolutePath
@@ -821,43 +909,148 @@ class Worker(val fileManager: FileManager) extends Actor {
               async.start()
               inApp.run()
               async.join()
-          
+
               writer.close()
 
-              diff = compareOutput(file.getParentFile, fileBase, kind, logFile)
-              if (!diff.equals("")) {
-                NestUI.verbose("output differs from log file\n")
-                succeeded = false
-              }
+              diffCheck(compareOutput(file.getParentFile, fileBase, kind, logFile))
             } catch { // *catch-all*
               case e: Exception =>
                 NestUI.verbose("caught "+e)
                 succeeded = false
             }
 
-            // delete log file only if test was successful
-            if (succeeded)
-              logFile.toDelete = true
-            
-            if (!succeeded) {
-              errors += 1
-              NestUI.verbose("incremented errors: "+errors)
-            }
-            printInfoEnd(succeeded, wr)           
+            LogContext(logFile, Some((swr, wr)))
+          } else
+            LogContext(logFile, None)
+      }
+    }
+
+    def reportAll(results: ImmMap[String, Int], cont: ImmMap[String, Int] => Unit) {
+      // NestUI.verbose("finished testing "+kind+" with "+errors+" errors")
+      // NestUI.verbose("created "+compileMgr.numSeparateCompilers+" separate compilers")
+      timer.cancel()
+      cont(results)
+    }
+
+    def reportResult(state: Int, logFile: Option[LogFile], writers: Option[(StringWriter, PrintWriter)]) {
+      val good = (state == 0)
+      if (!good) {
+        errors += 1
+        NestUI.verbose("incremented errors: "+errors)
+      }
+
+      try {
+        // delete log file only if test was successful
+        if (good && !logFile.isEmpty && !isPartestDebug)
+          logFile.get.toDelete = true
+
+        writers match {
+          case Some((swr, wr)) =>
+            if (state == 2)
+              printInfoTimeout(wr)
+            else
+              printInfoEnd(good, wr)
             wr.flush()
             swr.flush()
             NestUI.normal(swr.toString)
+            if (state == 1 && fileManager.showDiff && diff != "")
+              NestUI.normal(diff)
+            if (state == 1 && fileManager.showLog)
+              showLog(logFile.get)
+          case None =>
+        }
+      } catch {
+        case npe: NullPointerException =>
+      }
+    }
 
-            if (!succeeded && fileManager.showDiff) NestUI.normal(diff)
-            if (!succeeded && fileManager.showLog) showLog(logFile)
-          }
+    val numFiles = files.size
+    if (numFiles == 0)
+      reportAll(ImmMap(), topcont)
+
+    // maps canonical file names to the test result (0: OK, 1: FAILED, 2: TIMOUT)
+    var status = new HashMap[String, Int]
+
+    var fileCnt = 1
+    Actor.loopWhile(fileCnt <= numFiles) {
+      val parent = self
+
+      actor {
+        val testFile = files(fileCnt-1)
+
+        val ontimeout = new TimerTask {
+          def run() = parent ! Timeout(testFile)
         }
+        timer.schedule(ontimeout, fileManager.timeout.toLong)
+
+        val context = try {
+          processSingleFile(testFile)
+        } catch {
+          case t: Throwable =>
+            NestUI.verbose("while invoking compiler ("+files+"):")
+            NestUI.verbose("caught "+t)
+            t.printStackTrace
+            if (t.getCause != null)
+              t.getCause.printStackTrace
+            LogContext(null, None)
+        }
+        parent ! Result(testFile, context)
+      }
+
+      react {
+        case res: TestResult =>
+          val path = res.file.getCanonicalPath
+          status.get(path) match {
+            case Some(stat) => // ignore message
+            case None =>
+              res match {
+                case Timeout(_) =>
+                  status = status + (path -> 2)
+                  val swr = new StringWriter
+                  val wr = new PrintWriter(swr)
+                  printInfoStart(res.file, wr)
+                  succeeded = false
+                  reportResult(2, None, Some((swr, wr)))
+                case Result(_, logs) =>
+                  status = status + (path -> (if (succeeded) 0 else 1))
+                  reportResult(
+                    if (succeeded) 0 else 1,
+                    if (logs != null) Some(logs.file) else None,
+                    if (logs != null) logs.writers else None)
+              }
+              if (fileCnt == numFiles)
+                reportAll(status, topcont)
+              fileCnt += 1
+          }
       }
     }
-    NestUI.verbose("finished testing "+kind+" with "+errors+" errors")
-    NestUI.verbose("created "+compileMgr.numSeparateCompilers+" separate compilers")
-    compileMgr.timer.cancel()
-    (files.length-errors, errors)
+  }
+  
+  private def withOutputRedirected(out: PrintStream)(func: => Unit) {
+    val oldStdOut = System.out
+    val oldStdErr = System.err
+
+    try {
+      System.setOut(out)
+      System.setErr(out)
+      func
+      out.flush()
+      out.close()
+    } finally {
+      System.setOut(oldStdOut)
+      System.setErr(oldStdErr)
+    }
+  }
+  
+  private def filesToSet(pre: String, fs: List[String]): Set[AbstractFile] =
+    fs flatMap (s => Option(AbstractFile getFile (pre + s))) toSet
+  
+  private def copyTestFiles(testDir: File, destDir: File) {
+    val invalidExts = List("changes", "svn", "obj")
+    testDir.listFiles.toList filter (
+            f => (isJavaOrScala(f) && f.isFile) || 
+                 (f.isDirectory && !(invalidExts.contains(SFile(f).extension)))) foreach
+      { f => fileManager.copyFile(f, destDir) }
   }
 
   def showLog(logFile: File) {
diff --git a/src/partest/scala/tools/partest/package.scala b/src/partest/scala/tools/partest/package.scala
new file mode 100644
index 0000000..55cbe01
--- /dev/null
+++ b/src/partest/scala/tools/partest/package.scala
@@ -0,0 +1,40 @@
+/* NEST (New Scala Test)
+ * Copyright 2007-2010 LAMP/EPFL
+ */
+
+package scala.tools
+
+import java.io.{ File => JFile }
+import nsc.io.{ Path, Process, Directory }
+import util.{ PathResolver }
+import nsc.Properties.{ propOrElse, propOrNone, propOrEmpty }
+
+package object partest { 
+  import nest.NestUI
+  
+  implicit private[partest] def temporaryPath2File(x: Path): JFile = x.jfile
+  implicit private[partest] def temporaryFile2Path(x: JFile): Path = Path(x)
+  
+  def basename(name: String): String = Path(name).stripExtension
+  def resultsToStatistics(results: Iterable[(_, Int)]): (Int, Int) = {
+    val (files, failures) = results map (_._2 == 0) partition (_ == true)
+    (files.size, failures.size)
+  }
+  
+  def vmArgString = {    
+    val str = Process.javaVmArguments mkString " "
+    "Java VM started with arguments: '%s'" format str
+  }
+  
+  def allPropertiesString = {
+    import collection.JavaConversions._
+    System.getProperties.toList.sorted map { case (k, v) => "%s -> %s\n".format(k, v) } mkString
+  }
+  
+  def showAllJVMInfo {
+    NestUI.verbose(vmArgString)
+    NestUI.verbose(allPropertiesString)
+  }
+   
+  def isPartestDebug = propOrEmpty("partest.debug") == "true"
+}
\ No newline at end of file
diff --git a/src/partest/scala/tools/partest/utils/PrintMgr.scala b/src/partest/scala/tools/partest/utils/PrintMgr.scala
index 5883915..1053313 100644
--- a/src/partest/scala/tools/partest/utils/PrintMgr.scala
+++ b/src/partest/scala/tools/partest/utils/PrintMgr.scala
@@ -1,14 +1,15 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala Parallel Testing               **
-**    / __/ __// _ | / /  / _ |    (c) 2007-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: PrintMgr.scala 16881 2009-01-09 16:28:11Z cunei $
+// $Id$
 
-package scala.tools.partest.utils
+package scala.tools.partest
+package utils
 
 /**
  * @author Thomas Hofer
diff --git a/src/partest/scala/tools/partest/utils/Properties.scala b/src/partest/scala/tools/partest/utils/Properties.scala
index 05796ca..bc72995 100644
--- a/src/partest/scala/tools/partest/utils/Properties.scala
+++ b/src/partest/scala/tools/partest/utils/Properties.scala
@@ -1,57 +1,17 @@
 /*                     __                                               *\
 **     ________ ___   / /  ___     Scala Parallel Testing               **
-**    / __/ __// _ | / /  / _ |    (c) 2007-2009, LAMP/EPFL             **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
 **  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
 ** /____/\___/_/ |_/____/_/ | |                                         **
 **                          |/                                          **
 \*                                                                      */
 
-// $Id: Properties.scala 16894 2009-01-13 13:09:41Z cunei $
 
-package scala.tools.partest.utils
+package scala.tools.partest
+package utils
 
-/** A utility to load the library properties from a Java properties file
- *  included in the jar.
- *
- *  @author Stephane Micheloud
- */
-object Properties {
-
-  /** The name of the properties file */
-  private val propFilename = "/partest.properties"
-
-  /** The loaded properties */
-  private val props = {
-    val props = new java.util.Properties
-    val stream = classOf[Application].getResourceAsStream(propFilename)
-    if (stream != null)
-      props.load(stream)
-    props
-  }
-
-  /** The version number of the jar this was loaded from, or
-    * "(unknown)" if it cannot be determined.
-    */
-  val versionString: String = {
-    val defaultString = "(unknown)"
-    "version " + props.getProperty("version.number")
-  }
-  
-  val copyrightString: String = {
-    val defaultString = "(c) 2002-2009 LAMP/EPFL"
-    props.getProperty("copyright.string", defaultString)
-  }
-
-  val encodingString: String = {
-    val defaultString = "ISO-8859-1"
-    props.getProperty("file.encoding", defaultString)
-  }
-
-  private val writer = new java.io.PrintWriter(Console.err, true)
-
-  val versionMsg = "Scala partest " + versionString + " -- " + copyrightString
-
-  def main(args: Array[String]) {
-    writer.println(versionMsg)
-  }
+/** Loads partest.properties from the jar. */
+object Properties extends scala.util.PropertiesTrait {
+  protected def propCategory    = "partest"
+  protected def pickJarBasedOn  = classOf[Application]
 }
diff --git a/src/scalap/decoder.properties b/src/scalap/decoder.properties
new file mode 100644
index 0000000..f8e296a
--- /dev/null
+++ b/src/scalap/decoder.properties
@@ -0,0 +1,2 @@
+version.number=2.0.1
+copyright.string=(c) 2002-2010 LAMP/EPFL
diff --git a/src/scalap/scala/tools/scalap/Arguments.scala b/src/scalap/scala/tools/scalap/Arguments.scala
new file mode 100644
index 0000000..39f74cb
--- /dev/null
+++ b/src/scalap/scala/tools/scalap/Arguments.scala
@@ -0,0 +1,204 @@
+/*     ___ ____ ___   __   ___   ___
+**    / _// __// _ | / /  / _ | / _ \  Scala classfile decoder
+**  __\ \/ /__/ __ |/ /__/ __ |/ ___/  (c) 2003-2010, LAMP/EPFL
+** /____/\___/_/ |_/____/_/ |_/_/      http://scala-lang.org/
+**
+*/
+
+
+package scala.tools.scalap
+
+import scala.collection.mutable._
+
+
+object Arguments {
+
+  case class Parser(optionPrefix: Char) {
+
+    val options: Set[String] = new HashSet
+    val prefixes: Set[String] = new HashSet
+    val optionalArgs: Set[String] = new HashSet
+    val prefixedBindings: Map[String, Char] = new HashMap
+    val optionalBindings: Map[String, Char] = new HashMap
+
+    def error(message: String): Unit = Console.println(message)
+
+    def withOption(option: String): Parser = {
+      options += option
+      this
+    }
+
+    def withOptionalArg(option: String): Parser = {
+      optionalArgs += option
+      this
+    }
+
+    def withOptionalBinding(option: String, separator: Char): Parser = {
+      optionalBindings(option) = separator
+      this
+    }
+
+    def withPrefixedArg(prefix: String): Parser = {
+      prefixes += prefix
+      this
+    }
+
+    def withPrefixedBinding(prefix: String, separator: Char): Parser = {
+      prefixedBindings(prefix) = separator
+      this
+    }
+
+    def parseBinding(str: String, separator: Char): (String, String) = {
+      val eqls = str.indexOf(separator)
+      if (eqls < 0) {
+        error("missing '" + separator + "' in binding '" + str + "'")
+        Pair("", "")
+      } else
+        Pair(str.substring(0, eqls).trim(),
+           str.substring(eqls + 1).trim())
+    }
+
+    def parse(args: Array[String]): Arguments = {
+      val res = new Arguments
+      parse(args, res)
+      res
+    }
+
+    def parse(args: Array[String], res: Arguments) {
+      if (args != null) {
+        var i = 0
+        while (i < args.length)
+          if ((args(i) == null) || (args(i).length() == 0))
+            i += 1
+          else if (args(i).charAt(0) != optionPrefix) {
+            res.addOther(args(i))
+            i += 1
+          } else if (options contains args(i)) {
+            res.addOption(args(i))
+            i += 1
+          } else if (optionalArgs contains args(i)) {
+            if ((i + 1) == args.length) {
+              error("missing argument for '" + args(i) + "'")
+              i += 1
+            } else {
+              res.addArgument(args(i), args(i + 1))
+              i += 2
+            }
+          } else if (optionalBindings contains args(i)) {
+            if ((i + 1) == args.length) {
+              error("missing argument for '" + args(i) + "'")
+              i += 1
+            } else {
+              res.addBinding(args(i),
+                parseBinding(args(i + 1), optionalBindings(args(i))));
+              i += 2
+            }
+          } else {
+            var iter = prefixes.iterator
+            val j = i
+            while ((i == j) && iter.hasNext) {
+              val prefix = iter.next
+              if (args(i) startsWith prefix) {
+                res.addPrefixed(prefix, args(i).substring(prefix.length()).trim());
+                i += 1
+              }
+            }
+            if (i == j) {
+              val iter = prefixedBindings.keysIterator;
+              while ((i == j) && iter.hasNext) {
+                val prefix = iter.next
+                if (args(i) startsWith prefix) {
+                  val arg = args(i).substring(prefix.length()).trim()
+                  i = i + 1
+                  res.addBinding(prefix,
+                    parseBinding(arg, prefixedBindings(prefix)));
+                }
+              }
+              if (i == j) {
+                error("unknown option '" + args(i) + "'")
+                i = i + 1
+              }
+            }
+          }
+      }
+    }
+  }
+
+  def parse(options: String*)(args: Array[String]): Arguments = {
+    val parser = new Parser('-')
+    val iter = options.iterator
+    while (iter.hasNext)
+      parser withOption iter.next
+    parser.parse(args)
+  }
+}
+
+class Arguments {
+
+  private val options: Set[String] = new HashSet
+  private val arguments: Map[String, String] = new HashMap
+  private val prefixes: Map[String, Set[String]] = new HashMap
+  private val bindings: Map[String, Map[String, String]] = new HashMap
+  private val others: Buffer[String] = new ListBuffer
+
+  def addOption(option: String): Unit = options += option
+
+  def addArgument(option: String, arg: String) {
+    arguments(option) = arg
+  }
+
+  def addPrefixed(prefix: String, arg: String): Unit =
+    if (prefixes isDefinedAt prefix)
+      prefixes(prefix) += arg
+    else {
+      prefixes(prefix) = new HashSet
+      prefixes(prefix) += arg
+    }
+
+  def addBinding(tag: String, key: String, value: String): Unit =
+    if (key.length() > 0) {
+      if (bindings isDefinedAt tag)
+        bindings(tag)(key) = value
+      else {
+        bindings(tag) = new HashMap
+        bindings(tag)(key) = value
+      }
+    }
+
+  def addBinding(tag: String, binding: Pair[String, String]) {
+    addBinding(tag, binding._1, binding._2)
+  }
+
+  def addOther(arg: String): Unit = others += arg
+
+  def contains(option: String): Boolean = options contains option
+
+  def getArgument(option: String): Option[String] = arguments get option
+
+  def getSuffixes(prefix: String): Set[String] =
+    prefixes.get(prefix) match {
+      case None => new HashSet
+      case Some(set) => set
+    }
+
+  def containsSuffix(prefix: String, suffix: String): Boolean =
+    prefixes.get(prefix) match {
+      case None => false
+      case Some(set) => set contains suffix
+    }
+
+  def getBindings(tag: String): Map[String, String] =
+    bindings.get(tag) match {
+      case None => new HashMap
+      case Some(map) => map
+    }
+
+  def getBinding(option: String, key: String): Option[String] =
+    bindings.get(option) match {
+      case None => None
+      case Some(map) => map get key
+    }
+
+  def getOthers: List[String] = others.toList
+
+}
diff --git a/src/scalap/scala/tools/scalap/ByteArrayReader.scala b/src/scalap/scala/tools/scalap/ByteArrayReader.scala
new file mode 100644
index 0000000..8b3d5ff
--- /dev/null
+++ b/src/scalap/scala/tools/scalap/ByteArrayReader.scala
@@ -0,0 +1,112 @@
+/*     ___ ____ ___   __   ___   ___
+**    / _// __// _ | / /  / _ | / _ \    Scala classfile decoder
+**  __\ \/ /__/ __ |/ /__/ __ |/ ___/    (c) 2003-2010, LAMP/EPFL
+** /____/\___/_/ |_/____/_/ |_/_/        http://scala-lang.org/
+**
+*/
+
+
+package scala.tools.scalap
+
+
+class ByteArrayReader(content: Array[Byte]) {
+  import java.io._
+
+  /** the buffer containing the file
+   */
+  val buf: Array[Byte] = content
+
+  /** the current input pointer
+   */
+  var bp: Int = 0
+
+  /** return byte at offset 'pos'
+   */
+  def byteAt(pos: Int): Byte = buf(pos)
+
+  /** read a byte
+   */
+  def nextByte: Byte = {
+    bp += 1
+    buf(bp - 1)
+  }
+
+  /** read some bytes
+   */
+  def nextBytes(len: Int): Array[Byte] = {
+    val res = new Array[Byte](len)
+    System.arraycopy(buf, bp, res, 0, len)
+    bp += len
+    res
+  }
+
+  /** read a character
+   */
+  def nextChar: Char = {
+    bp += 2
+    getChar(bp - 2)
+  }
+
+  /** read an integer
+   */
+  def nextInt: Int = {
+    bp += 4
+    getInt(bp - 4)
+  }
+
+  /** read a long
+   */
+  def nextLong: Long = {
+    bp += 8
+    getLong(bp - 8)
+  }
+
+  /** read a float
+   */
+  def nextFloat: Float = java.lang.Float.intBitsToFloat(nextInt)
+
+  /** read a double
+   */
+  def nextDouble: Double = java.lang.Double.longBitsToDouble(nextLong)
+
+  /** read an UTF8 encoded string
+   */
+  def nextUTF8(len: Int): String = {
+    val cs = scala.io.Codec.toUTF8(buf.slice(bp, bp + len))
+    bp += len
+    new String(cs)
+  }
+
+  /** extract a character at position bp from buf
+   */
+  def getChar(bp: Int): Char =
+    (((buf(bp) & 0xff) << 8) + (buf(bp + 1) & 0xff)).asInstanceOf[Char]
+
+  /** extract an integer at position bp from buf
+   */
+  def getInt(bp: Int): Int =
+    ((buf(bp  ) & 0xff) << 24) +
+    ((buf(bp + 1) & 0xff) << 16) +
+    ((buf(bp + 2) & 0xff) << 8) +
+     (buf(bp + 3) & 0xff)
+
+  /** extract a long integer at position bp from buf
+   */
+  def getLong(bp: Int): Long =
+    (getInt(bp).toLong << 32) + (getInt(bp + 4).toLong & 0xffffffffL)
+
+  /** extract a float at position bp from buf
+   */
+  def getFloat(bp: Int): Float = java.lang.Float.intBitsToFloat(getInt(bp))
+
+  /** extract a double at position bp from buf
+   */
+  def getDouble(bp: Int): Double = java.lang.Double.longBitsToDouble(getLong(bp))
+
+   /** skip next 'n' bytes
+  */
+  def skip(n: Int) {
+    bp += n
+  }
+
+}
diff --git a/src/scalap/scala/tools/scalap/Classfile.scala b/src/scalap/scala/tools/scalap/Classfile.scala
new file mode 100644
index 0000000..d7d48e6
--- /dev/null
+++ b/src/scalap/scala/tools/scalap/Classfile.scala
@@ -0,0 +1,129 @@
+/*     ___ ____ ___   __   ___   ___
+**    / _// __// _ | / /  / _ | / _ \    Scala classfile decoder
+**  __\ \/ /__/ __ |/ /__/ __ |/ ___/    (c) 2003-2010, LAMP/EPFL
+** /____/\___/_/ |_/____/_/ |_/_/
+**
+*/
+
+
+package scala.tools.scalap
+
+
+class Classfile(in: ByteArrayReader) {
+  import Classfiles._
+  
+  type UTF8 = Pool#UTF8
+
+  assert(in.nextInt == JAVA_MAGIC)
+  val minorVersion = in.nextChar
+  val majorVersion = in.nextChar
+  val pool = new Pool()
+  val flags = in.nextChar
+  val classname = in.nextChar
+  val superclass = in.nextChar
+  val interfaces = readInterfaces
+  val fields = readMembers(true)
+  val methods = readMembers(false)
+  val attribs = readAttribs
+  def scalaSigAttribute = attribs find (_.toString == Main.SCALA_SIG)
+  
+  def readAttribs = {
+    val n = in.nextChar
+    var attribs: List[Attribute] = Nil
+    var i = 0
+    while (i < n) {
+      attribs = Attribute(in.nextChar, in.nextBytes(in.nextInt)) :: attribs
+      i = i + 1
+    }
+    attribs
+  }
+
+  def readMembers(field: Boolean) = {
+    val n = in.nextChar
+    var members: List[Member] = Nil
+    var i = 0
+    while (i < n) {
+      members = Member(field, in.nextChar, in.nextChar, in.nextChar, readAttribs) :: members
+      i = i + 1
+    }
+    members
+  }
+
+  def readInterfaces = {
+    val n = in.nextChar
+    var intfs: List[Int] = Nil
+    var i = 0
+    while (i < n) {
+      intfs = in.nextChar :: intfs
+      i = i + 1
+    }
+    intfs
+  }
+
+  class Pool() {
+    sealed abstract class PoolEntry(val tag: Int) {
+      def typeString = constantTagToString(tag)
+    }
+    case class UTF8(str: String) extends PoolEntry(CONSTANT_UTF8) { override def toString = "\"" + str + "\"" }
+    case class ClassRef(classId: Int) extends PoolEntry(CONSTANT_CLASS) { override def toString = "Class(%s)".format(entries(classId)) }
+    case class FieldRef(classId: Int, memberId: Int) extends PoolEntry(CONSTANT_FIELDREF)
+    case class MethodRef(classId: Int, memberId: Int) extends PoolEntry(CONSTANT_METHODREF) { 
+      // //Method java/lang/Object."<init>":()V
+      override def toString() = "Method %s.\"%s\"".format(entries(classId), entries(memberId))
+    }
+    case class IntfMethodRef(classId: Int, memberId: Int) extends PoolEntry(CONSTANT_INTFMETHODREF)
+    case class StringConst(strId: Int) extends PoolEntry(CONSTANT_STRING)
+    case class IntegerConst(x: Int) extends PoolEntry(CONSTANT_INTEGER)
+    case class FloatConst(x: Float) extends PoolEntry(CONSTANT_FLOAT)
+    case class LongConst(x: Long) extends PoolEntry(CONSTANT_LONG)
+    case class DoubleConst(x: Double) extends PoolEntry(CONSTANT_DOUBLE)
+    case class NameAndType(nameId: Int, typeId: Int) extends PoolEntry(CONSTANT_NAMEANDTYPE)
+    case object Empty extends PoolEntry(0) { }
+
+    val entries = {
+      val pool = new Array[PoolEntry](in.nextChar)
+      var i = 1
+      while (i < pool.length) {
+        val tag = in.nextByte
+        // Double sized entry
+        if (tag == CONSTANT_LONG || tag == CONSTANT_DOUBLE) {
+          pool(i) = if (tag == CONSTANT_LONG) LongConst(in.nextLong) else DoubleConst(in.nextDouble)
+          i = i + 1
+          pool(i) = Empty
+        }
+        else pool(i) = tag match {
+          case CONSTANT_UTF8            => UTF8(in.nextUTF8(in.nextChar))
+          case CONSTANT_UNICODE         => in.skip(in.nextChar) ; Empty
+          case CONSTANT_CLASS           => ClassRef(in.nextChar)
+          case CONSTANT_STRING          => StringConst(in.nextChar)
+          case CONSTANT_FIELDREF        => FieldRef(in.nextChar, in.nextChar)
+          case CONSTANT_METHODREF       => MethodRef(in.nextChar, in.nextChar)
+          case CONSTANT_INTFMETHODREF   => IntfMethodRef(in.nextChar, in.nextChar)
+          case CONSTANT_NAMEANDTYPE     => NameAndType(in.nextChar, in.nextChar)
+          case CONSTANT_INTEGER         => IntegerConst(in.nextInt)
+          case CONSTANT_FLOAT           => FloatConst(in.nextFloat)
+        }
+        
+        i += 1
+      }
+      pool
+    }
+    
+    lazy val length = entries.length
+    def apply(x: Int) = entries(x)
+    def stringOf(x: Int) = apply(x).toString
+    override def toString = (
+      for ((x, i) <- entries.zipWithIndex ; if x != null) yield 
+        "const #%d = %s\t%s\n".format(i + 1, x.typeString, x)
+    ).mkString
+  }
+    
+  /** **/
+  case class Member(field: Boolean, flags: Int, name: Int, tpe: Int, attribs: List[Attribute])
+  case class Attribute(name: Int, data: Array[Byte]) {
+    override def toString = (pool(name): @unchecked) match {
+      case pool.UTF8(s) => s
+    }
+    def reader: ByteArrayReader = new ByteArrayReader(data)
+  }
+}
diff --git a/src/scalap/scala/tools/scalap/Classfiles.scala b/src/scalap/scala/tools/scalap/Classfiles.scala
new file mode 100644
index 0000000..fc0ae7c
--- /dev/null
+++ b/src/scalap/scala/tools/scalap/Classfiles.scala
@@ -0,0 +1,71 @@
+/*     ___ ____ ___   __   ___   ___
+**    / _// __// _ | / /  / _ | / _ \    Scala classfile decoder
+**  __\ \/ /__/ __ |/ /__/ __ |/ ___/    (c) 2003-2010, LAMP/EPFL
+** /____/\___/_/ |_/____/_/ |_/_/        http://scala-lang.org/
+**
+*/
+
+
+package scala.tools.scalap
+
+
+object Classfiles {
+  final val JAVA_MAGIC = 0xCAFEBABE
+  final val JAVA_MAJOR_VERSION = 45
+  final val JAVA_MINOR_VERSION = 3
+
+  final val CONSTANT_UTF8 = 1
+  final val CONSTANT_UNICODE = 2
+  final val CONSTANT_INTEGER = 3
+  final val CONSTANT_FLOAT = 4
+  final val CONSTANT_LONG = 5
+  final val CONSTANT_DOUBLE = 6
+  final val CONSTANT_CLASS = 7
+  final val CONSTANT_STRING = 8
+  final val CONSTANT_FIELDREF = 9
+  final val CONSTANT_METHODREF = 10
+  final val CONSTANT_INTFMETHODREF = 11
+  final val CONSTANT_NAMEANDTYPE = 12
+  
+  final val constantTagToString = Map(
+    CONSTANT_UTF8 -> "UTF8",
+    CONSTANT_UNICODE -> "Unicode",
+    CONSTANT_INTEGER -> "Int",
+    CONSTANT_FLOAT -> "Float",
+    CONSTANT_LONG -> "Long",
+    CONSTANT_DOUBLE -> "Double",
+    CONSTANT_CLASS -> "class",
+    CONSTANT_STRING -> "Asciz",
+    CONSTANT_FIELDREF -> "Field",
+    CONSTANT_METHODREF -> "Method",
+    CONSTANT_INTFMETHODREF -> "InterfaceMethod",
+    CONSTANT_NAMEANDTYPE -> "NameAndType"
+  )
+
+  final val BAD_ATTR = 0x00000
+  final val SOURCEFILE_ATTR = 0x00001
+  final val SYNTHETIC_ATTR = 0x00002
+  final val DEPRECATED_ATTR = 0x00004
+  final val CODE_ATTR = 0x00008
+  final val EXCEPTIONS_ATTR = 0x00010
+  final val CONSTANT_VALUE_ATTR = 0x00020
+  final val LINE_NUM_TABLE_ATTR = 0x00040
+  final val LOCAL_VAR_TABLE_ATTR = 0x00080
+  final val INNERCLASSES_ATTR = 0x08000
+  final val META_ATTR = 0x10000
+  final val SCALA_ATTR = 0x20000
+
+  final val SOURCEFILE_N = "SourceFile"
+  final val SYNTHETIC_N = "Synthetic"
+  final val DEPRECATED_N = "Deprecated"
+  final val CODE_N = "Code"
+  final val EXCEPTIONS_N = "Exceptions"
+  final val CONSTANT_VALUE_N = "ConstantValue"
+  final val LINE_NUM_TABLE_N = "LineNumberTable"
+  final val LOCAL_VAR_TABLE_N = "LocalVariableTable"
+  final val INNERCLASSES_N = "InnerClasses"
+  final val META_N = "JacoMeta"
+  final val SCALA_N = "ScalaSignature"
+  final val CONSTR_N = "<init>"
+}
+
diff --git a/src/scalap/scala/tools/scalap/CodeWriter.scala b/src/scalap/scala/tools/scalap/CodeWriter.scala
new file mode 100644
index 0000000..e5a214c
--- /dev/null
+++ b/src/scalap/scala/tools/scalap/CodeWriter.scala
@@ -0,0 +1,134 @@
+/*     ___ ____ ___   __   ___   ___
+**    / _// __// _ | / /  / _ | / _ \    Scala classfile decoder
+**  __\ \/ /__/ __ |/ /__/ __ |/ ___/    (c) 2003-2010, LAMP/EPFL
+** /____/\___/_/ |_/____/_/ |_/_/        http://scala-lang.org/
+**
+*/
+
+
+package scala.tools.scalap
+
+import java.io._
+
+
+class CodeWriter(writer: Writer) {
+
+  private val nl = compat.Platform.EOL
+  private var step = "  "
+  private var level = 0
+  private var align = false
+  private var space = false
+  private var line = false
+
+  def getWriter = writer
+
+  def getIndentLevel = level
+
+  def setIndentLevel(level: Int): CodeWriter = {
+    this.level = level
+    this
+  }
+
+  def getIndentWidth = if (step == null) -1 else step.length()
+
+  def setIndentWidth(width: Int): CodeWriter = 
+    setIndentString(List.fill(width)(' ').mkString)
+
+  def getIndentString = step;
+
+  def setIndentString(step: String): CodeWriter = {
+    this.step = step
+    this
+  }
+
+  def indent: CodeWriter = {
+    level += 1
+    this
+  }
+
+  def undent: CodeWriter = {
+    level -= 1
+    this
+  }
+
+  def newline: CodeWriter = {
+    if (step == null)
+      newspace
+    else if (!line) {
+      try {
+        writer.write(nl)
+      } catch {
+        case e => error("IO error")
+      }
+      line = align
+      align = true
+      space = false
+      this
+    } else
+      this
+  }
+
+  def newspace: CodeWriter = {
+    space = !align
+    this
+  }
+
+  def * : Unit = {}
+
+  def println: CodeWriter = newline
+
+  def println(value: Boolean): CodeWriter = print(value).newline
+
+  def println(value: Byte): CodeWriter = print(value).newline
+
+  def println(value: Short): CodeWriter = print(value).newline
+
+  def println(value: Char): CodeWriter = print(value).newline
+
+  def println(value: Int): CodeWriter = print(value).newline
+
+  def println(value: Long): CodeWriter = print(value).newline
+
+  def println(value: Float): CodeWriter = print(value).newline
+
+  def println(value: Double): CodeWriter = print(value).newline
+
+  def println(value: String): CodeWriter = print(value).newline
+
+  def print(value: Boolean): CodeWriter = print(String.valueOf(value))
+
+  def print(value: Byte): CodeWriter = print(String.valueOf(value))
+
+  def print(value: Short): CodeWriter = print(String.valueOf(value))
+
+  def print(value: Char): CodeWriter = print(String.valueOf(value))
+
+  def print(value: Int): CodeWriter = print(String.valueOf(value))
+
+  def print(value: Long): CodeWriter = print(String.valueOf(value))
+
+  def print(value: Float): CodeWriter = print(String.valueOf(value))
+
+  def print(value: Double): CodeWriter = print(String.valueOf(value))
+
+  def print(value: String): CodeWriter = try {
+    if (align) {
+      var i = 0
+      while (i < level) {
+        writer.write(step)
+        i += 1
+      }
+    }
+    if (space)
+      writer.write(" ")
+    writer.write(value)
+    align = false
+    space = false
+    line = false
+    this
+  } catch {
+    case e => error("IO error")
+  }
+
+  override def toString(): String = writer.toString()
+}
diff --git a/src/scalap/scala/tools/scalap/Decode.scala b/src/scalap/scala/tools/scalap/Decode.scala
new file mode 100644
index 0000000..291fbff
--- /dev/null
+++ b/src/scalap/scala/tools/scalap/Decode.scala
@@ -0,0 +1,101 @@
+/*     ___ ____ ___   __   ___   ___
+**    / _// __// _ | / /  / _ | / _ \  Scala classfile decoder
+**  __\ \/ /__/ __ |/ /__/ __ |/ ___/  (c) 2003-2010, LAMP/EPFL
+** /____/\___/_/ |_/____/_/ |_/_/      http://scala-lang.org/
+**
+*/
+
+// $Id$
+
+package scala.tools.scalap
+
+import scala.tools.scalap.scalax.rules.scalasig._
+import scala.tools.nsc.util.ScalaClassLoader
+import scala.tools.nsc.util.ScalaClassLoader.getSystemLoader
+import scala.reflect.generic.ByteCodecs
+
+import ClassFileParser.{ ConstValueIndex, Annotation }
+import Main.{ SCALA_SIG, SCALA_SIG_ANNOTATION, BYTES_VALUE }
+
+/** Temporary decoder.  This would be better off in the scala.tools.nsc
+ *  but right now the compiler won't acknowledge scala.tools.scalap
+ *  when it's bootstrapping, so the reference has to go from here to there.
+ */
+object Decode {
+  private def getAliasSymbol(t: Type): Symbol = t match {
+    case TypeRefType(_, s, _)   => s
+    case PolyType(typeRef, _)   => getAliasSymbol(typeRef)
+    case _                      => NoSymbol
+  }
+  
+  /** Return the classfile bytes representing the scala sig classfile attribute.
+   *  This has been obsoleted by the switch to annotations.
+   */
+  def scalaSigBytes(name: String): Option[Array[Byte]] = scalaSigBytes(name, getSystemLoader())
+  def scalaSigBytes(name: String, classLoader: ScalaClassLoader): Option[Array[Byte]] = {
+    val bytes = classLoader.findBytesForClassName(name)
+    val reader = new ByteArrayReader(bytes)
+    val cf = new Classfile(reader)
+    cf.scalaSigAttribute map (_.data) 
+  }
+  
+  /** Return the bytes representing the annotation
+   */
+  def scalaSigAnnotationBytes(name: String): Option[Array[Byte]] = scalaSigAnnotationBytes(name, getSystemLoader())
+  def scalaSigAnnotationBytes(name: String, classLoader: ScalaClassLoader): Option[Array[Byte]] = {  
+    val bytes     = classLoader.findBytesForClassName(name)
+    val byteCode  = ByteCode(bytes)
+    val classFile = ClassFileParser.parse(byteCode)
+    import classFile._
+        
+    classFile annotation SCALA_SIG_ANNOTATION map { case Annotation(_, els) =>
+      val bytesElem = els find (x => constant(x.elementNameIndex) == BYTES_VALUE) get
+      val _bytes    = bytesElem.elementValue match { case ConstValueIndex(x) => constantWrapped(x) }
+      val bytes     = _bytes.asInstanceOf[StringBytesPair].bytes
+      val length    = ByteCodecs.decode(bytes)
+      
+      bytes take length
+    }
+  }
+
+  /** private[scala] so nobody gets the idea this is a supported interface.
+   */
+  private[scala] def caseParamNames(path: String): Option[List[String]] = {
+    val (outer, inner) = (path indexOf '$') match {
+      case -1   => (path, "")
+      case x    => (path take x, path drop (x + 1))
+    }
+    
+    for {
+      clazz <- getSystemLoader.tryToLoadClass[AnyRef](outer)
+      ssig <- ScalaSigParser.parse(clazz)
+    }
+    yield {
+      val f: PartialFunction[Symbol, List[String]] =
+        if (inner == "") {
+          case x: MethodSymbol if x.isCaseAccessor && (x.name endsWith " ") => List(x.name dropRight 1)
+        }
+        else {
+          case x: ClassSymbol if x.name == inner  =>
+            val xs = x.children filter (child => child.isCaseAccessor && (child.name endsWith " "))
+            xs.toList map (_.name dropRight 1)
+        }
+      
+      (ssig.symbols collect f).flatten toList
+    }
+  }
+  
+  /** Returns a map of Alias -> Type for the given package.
+   */
+  private[scala] def typeAliases(pkg: String) = {
+    for {
+      clazz <- getSystemLoader.tryToLoadClass[AnyRef](pkg + ".package")
+      ssig <- ScalaSigParser.parse(clazz)
+    }
+    yield {
+      val typeAliases = ssig.symbols collect { case x: AliasSymbol => x }
+      Map(typeAliases map (x => (x.name, getAliasSymbol(x.infoType).path)): _*)
+    }
+  }
+}  
+
diff --git a/src/scalap/scala/tools/scalap/JavaWriter.scala b/src/scalap/scala/tools/scalap/JavaWriter.scala
new file mode 100644
index 0000000..1a7b600
--- /dev/null
+++ b/src/scalap/scala/tools/scalap/JavaWriter.scala
@@ -0,0 +1,241 @@
+/*     ___ ____ ___   __   ___   ___
+**    / _// __// _ | / /  / _ | / _ \    Scala classfile decoder
+**  __\ \/ /__/ __ |/ /__/ __ |/ ___/    (c) 2003-2010, LAMP/EPFL
+** /____/\___/_/ |_/____/_/ |_/_/        http://scala-lang.org/
+**
+*/
+
+
+package scala.tools.scalap
+
+import java.io._
+
+
+class JavaWriter(classfile: Classfile, writer: Writer) extends CodeWriter(writer) {
+
+  val cf = classfile
+
+  def flagsToStr(clazz: Boolean, flags: Int): String = {
+    val buffer = new StringBuffer()
+    var x: StringBuffer = buffer
+    if (((flags & 0x0007) == 0) &&
+      ((flags & 0x0002) != 0))
+      x = buffer.append("private ")
+    if ((flags & 0x0004) != 0)
+      x = buffer.append("protected ")
+    if ((flags & 0x0010) != 0)
+      x = buffer.append("final ")
+    if ((flags & 0x0400) != 0)
+      x = if (clazz) buffer.append("abstract ")
+          else buffer.append("/*deferred*/ ")
+    buffer.toString()
+  }
+
+  def nameToClass(str: String): String = {
+    val res = Names.decode(str.replace('/', '.'))
+    if (res == "java.lang.Object") "scala.Any" else res
+  }
+
+  def nameToClass0(str: String) = {
+    val res = Names.decode(str.replace('/', '.'))
+    if (res == "java.lang.Object") "scala.AnyRef" else res
+  }
+
+  def nameToSimpleClass(str: String) =
+    Names.decode(str.substring(str.lastIndexOf('/') + 1))
+
+  def nameToPackage(str: String) = {
+    val inx = str.lastIndexOf('/')
+    val name = if (inx == -1) str else str.substring(0, inx).replace('/', '.')
+    Names.decode(name)
+  }
+
+  def sigToType(str: String): String =
+    sigToType(str, 0)._1
+
+  def sigToType(str: String, i: Int): (String, Int) = str.charAt(i) match {
+    case 'B' => ("scala.Byte", i + 1)
+    case 'C' => ("scala.Char", i + 1)
+    case 'D' => ("scala.Double", i + 1)
+    case 'F' => ("scala.Float", i + 1)
+    case 'I' => ("scala.Int", i + 1)
+    case 'J' => ("scala.Long", i + 1)
+    case 'S' => ("scala.Short", i + 1)
+    case 'V' => ("scala.Unit", i + 1)
+    case 'Z' => ("scala.Boolean", i + 1)
+    case 'L' =>
+      val j = str.indexOf(';', i)
+      (nameToClass(str.substring(i + 1, j)), j + 1)
+    case '[' =>
+      val (tpe, j) = sigToType(str, i + 1)
+      ("scala.Array[" + tpe + "]", j)
+    case '(' =>
+      val (tpe, j) = sigToType0(str, i + 1)
+      ("(" + tpe, j)
+    case ')' =>
+      val (tpe, j) = sigToType(str, i + 1)
+      ("): " + tpe, j)
+  }
+
+  def sigToType0(str: String, i: Int): (String, Int) =
+    if (str.charAt(i) == ')')
+      sigToType(str, i)
+    else {
+      val (tpe, j) = sigToType(str, i)
+      if (str.charAt(j) == ')') {
+        val (rest, k) = sigToType(str, j)
+        (tpe + rest, k)
+      } else {
+        val (rest, k) = sigToType0(str, j)
+        (tpe + ", " + rest, k)
+      }
+    }
+
+  def getName(n: Int): String = {
+    import cf.pool._
+    
+    cf.pool(n) match {
+      case UTF8(str) => str
+      case StringConst(m) => getName(m)
+      case ClassRef(m) => getName(m)
+      case _ => "<error>"
+    }
+  }
+
+  def getClassName(n: Int): String = nameToClass(getName(n))
+
+  def getSimpleClassName(n: Int): String = nameToSimpleClass(getName(n))
+
+  def getPackage(n: Int): String = nameToPackage(getName(n))
+
+  def getType(n: Int): String = sigToType(getName(n))
+
+  def isStatic(flags: Int) = (flags & 0x0008) != 0
+
+  def isInterface(flags: Int) = (flags & 0x0200) != 0
+
+  def isConstr(name: String) = (name == "<init>")
+
+  def printField(flags: Int, name: Int, tpe: Int, attribs: List[cf.Attribute]) {
+    print(flagsToStr(false, flags))
+    if ((flags & 0x0010) != 0)
+      print("val " + Names.decode(getName(name)))
+    else
+      print("final var " + Names.decode(getName(name)))
+    print(": " + getType(tpe) + ";").newline
+  }
+
+  def printMethod(flags: Int, name: Int, tpe: Int, attribs: List[cf.Attribute]) {
+    if (getName(name) == "<init>")
+    print(flagsToStr(false, flags))
+    attribs find {
+      case cf.Attribute(name, _) => getName(name) == "JacoMeta"
+    } match {
+      case Some(cf.Attribute(_, data)) =>
+        val mp = new MetaParser(getName(
+          ((data(0) & 0xff) << 8) + (data(1) & 0xff)).trim())
+        mp.parse match {
+          case None =>
+            if (getName(name) == "<init>") {
+              print("def this" + getType(tpe) + ";").newline
+            } else {
+              print("def " + Names.decode(getName(name)))
+              print(getType(tpe) + ";").newline
+            }
+          case Some(str) =>
+            if (getName(name) == "<init>")
+              print("def this" + str + ";").newline
+            else
+              print("def " + Names.decode(getName(name)) + str + ";").newline
+        }
+      case None =>
+        if (getName(name) == "<init>") {
+          print("def this" + getType(tpe) + ";").newline
+        } else {
+          print("def " + Names.decode(getName(name)))
+          print(getType(tpe) + ";").newline
+      }
+    }
+    attribs find {
+      case cf.Attribute(name, _) => getName(name) == "Exceptions"
+    } match {
+      case Some(cf.Attribute(_, data)) =>
+        val n = ((data(0) & 0xff) << 8) + (data(1) & 0xff)
+        indent.print("throws ")
+        for (i <- Iterator.range(0, n) map {x => 2 * (x + 1)}) {
+          val inx = ((data(i) & 0xff) << 8) + (data(i+1) & 0xff)
+          if (i > 2) print(", ")
+          print(getClassName(inx).trim())
+        }
+        undent.newline
+      case None =>
+    }
+  }
+
+  def printClassHeader {
+    if (isInterface(cf.flags)) {
+      print("trait " + getSimpleClassName(cf.classname))
+    } else {
+      print("class " + getSimpleClassName(cf.classname))
+      if (cf.pool(cf.superclass) != null)
+        print(" extends " + nameToClass0(getName(cf.superclass)))
+    }
+    cf.interfaces foreach {
+      n => print(" with " + getClassName(n))
+    }
+  }
+
+  def printClass {
+    val pck = getPackage(cf.classname);
+    if (pck.length() > 0)
+      println("package " + pck + ";")
+    print(flagsToStr(true, cf.flags))
+    cf.attribs find {
+      case cf.Attribute(name, _) => getName(name) == "JacoMeta"
+    } match {
+      case None =>
+        printClassHeader;
+      case Some(cf.Attribute(_, data)) =>
+        val mp = new MetaParser(getName(
+          ((data(0) & 0xff) << 8) + (data(1) & 0xff)).trim());
+        mp.parse match {
+          case None => printClassHeader;
+          case Some(str) =>
+            if (isInterface(cf.flags))
+              print("trait " + getSimpleClassName(cf.classname) + str);
+            else
+              print("class " + getSimpleClassName(cf.classname) + str);
+        }
+    }
+    var statics: List[cf.Member] = Nil
+    print(" {").indent.newline
+    cf.fields foreach {
+      case m at cf.Member(_, flags, name, tpe, attribs) =>
+        if (isStatic(flags))
+          statics = m :: statics
+        else
+          printField(flags, name, tpe, attribs)
+    }
+    cf.methods foreach {
+      case m at cf.Member(_, flags, name, tpe, attribs) =>
+        if (isStatic(flags))
+          statics = m :: statics
+        else
+          printMethod(flags, name, tpe, attribs)
+    }
+    undent.print("}").newline
+    if (!statics.isEmpty) {
+      print("object " + getSimpleClassName(cf.classname) + " {")
+      indent.newline
+      statics foreach {
+        case cf.Member(true, flags, name, tpe, attribs) =>
+          printField(flags, name, tpe, attribs)
+        case cf.Member(false, flags, name, tpe, attribs) =>
+          if (getName(name) != "<clinit>")
+            printMethod(flags, name, tpe, attribs)
+      }
+      undent.print("}").newline
+    }
+  }
+
+}
diff --git a/src/scalap/scala/tools/scalap/Main.scala b/src/scalap/scala/tools/scalap/Main.scala
new file mode 100644
index 0000000..5372ca4
--- /dev/null
+++ b/src/scalap/scala/tools/scalap/Main.scala
@@ -0,0 +1,280 @@
+/*     ___ ____ ___   __   ___   ___
+**    / _// __// _ | / /  / _ | / _ \  Scala classfile decoder
+**  __\ \/ /__/ __ |/ /__/ __ |/ ___/  (c) 2003-2010, LAMP/EPFL
+** /____/\___/_/ |_/____/_/ |_/_/      http://scala-lang.org/
+**
+*/
+
+
+package scala.tools.scalap
+
+import java.io.{PrintStream, OutputStreamWriter, ByteArrayOutputStream}
+import scalax.rules.scalasig._
+import tools.nsc.util.{ ClassPath }
+import tools.util.PathResolver
+import ClassPath.DefaultJavaContext
+import tools.nsc.io.{PlainFile, AbstractFile}
+
+/**The main object used to execute scalap on the command-line.
+ *
+ * @author Matthias Zenger, Stephane Micheloud, Burak Emir, Ilya Sergey
+ */
+object Main {
+  val SCALA_SIG = "ScalaSig"
+  val SCALA_SIG_ANNOTATION = "Lscala/reflect/ScalaSignature;"
+  val BYTES_VALUE = "bytes"
+
+  val versionMsg = "Scala classfile decoder " +
+          Properties.versionString + " -- " +
+          Properties.copyrightString + "\n"
+
+  /**Verbose program run?
+   */
+  var verbose = false
+  var printPrivates = false
+
+  /**Prints usage information for scalap.
+   */
+  def usage {
+    Console.println("usage: scalap {<option>} <name>")
+    Console.println("where <name> is fully-qualified class name or <package_name>.package for package objects")
+    Console.println("and <option> is")
+    Console.println("  -private           print private definitions")
+    Console.println("  -verbose           print out additional information")
+    Console.println("  -version           print out the version number of scalap")
+    Console.println("  -help              display this usage message")
+    Console.println("  -classpath <path>  specify where to find user class files")
+    Console.println("  -cp <path>         specify where to find user class files")
+  }
+
+  def isScalaFile(bytes: Array[Byte]): Boolean = {
+    val byteCode = ByteCode(bytes)
+    val classFile = ClassFileParser.parse(byteCode)
+    classFile.attribute("ScalaSig").isDefined
+  }
+
+  /**Processes the given Java class file.
+   *
+   * @param clazz the class file to be processed.
+   */
+  def processJavaClassFile(clazz: Classfile) {
+    // construct a new output stream writer
+    val out = new OutputStreamWriter(Console.out)
+    val writer = new JavaWriter(clazz, out)
+    // print the class
+    writer.printClass
+    out.flush()
+  }
+
+  def isPackageObjectFile(s: String) = s != null && (s.endsWith(".package") || s == "package")
+
+  def parseScalaSignature(scalaSig: ScalaSig, isPackageObject: Boolean) = {
+    val baos = new ByteArrayOutputStream
+    val stream = new PrintStream(baos)
+    val syms = scalaSig.topLevelClasses ::: scalaSig.topLevelObjects
+    syms.head.parent match {
+    //Partial match
+      case Some(p) if (p.name != "<empty>") => {
+        val path = p.path
+        if (!isPackageObject) {
+          stream.print("package ");
+          stream.print(path);
+          stream.print("\n")
+        } else {
+          val i = path.lastIndexOf(".")
+          if (i > 0) {
+            stream.print("package ");
+            stream.print(path.substring(0, i))
+            stream.print("\n")
+          }
+        }
+      }
+      case _ =>
+    }
+    // Print classes
+    val printer = new ScalaSigPrinter(stream, printPrivates)
+    for (c <- syms) {
+      printer.printSymbol(c)
+    }
+    baos.toString
+  }
+  
+  def decompileScala(bytes: Array[Byte], isPackageObject: Boolean): String = {    
+    val byteCode = ByteCode(bytes)
+    val classFile = ClassFileParser.parse(byteCode)
+
+    ScalaSigParser.parse(classFile) match {
+      case Some(scalaSig) => parseScalaSignature(scalaSig, isPackageObject)
+      case None           => ""
+    }
+  }
+
+  /**Executes scalap with the given arguments and classpath for the
+   *  class denoted by <code>classname</code>.
+   *
+   * @param args...
+   * @param path...
+   * @param classname...
+   */
+  def process(args: Arguments, path: ClassPath[AbstractFile])(classname: String): Unit = {
+    // find the classfile
+    val encName = Names.encode(
+      if (classname == "scala.AnyRef") "java.lang.Object"
+      else classname)
+    val cls = path.findClass(encName)
+    if (cls.isDefined && cls.get.binary.isDefined) {
+      val cfile = cls.get.binary.get
+      if (verbose) {
+        Console.println(Console.BOLD + "FILENAME" + Console.RESET + " = " + cfile.path)
+      }
+      val bytes = cfile.toByteArray
+      if (isScalaFile(bytes)) {
+        Console.println(decompileScala(bytes, isPackageObjectFile(encName)))
+      } else {
+        // construct a reader for the classfile content
+        val reader = new ByteArrayReader(cfile.toByteArray)
+        // parse the classfile
+        val clazz = new Classfile(reader)
+        processJavaClassFile(clazz)
+      }
+      // if the class corresponds to the artificial class scala.Any.
+      // (see member list in class scala.tool.nsc.symtab.Definitions)
+    } else if (classname == "scala.Any") {
+      Console.println("package scala")
+      Console.println("class Any {")
+      Console.println("  final def ==(scala.Any): scala.Boolean")
+      Console.println("  final def !=(scala.Any): Boolean")
+      Console.println("  def equals(scala.Any): scala.Boolean")
+      Console.println("  def hashCode(): scala.Int")
+      Console.println("  def toString(): java.lang.String")
+      Console.println("  final def isInstanceOf[a]: scala.Boolean")
+      Console.println("  final def asInstanceOf[a]: a")
+      Console.println("}")
+      // if the class corresponds to the artificial class scala.AnyRef.
+    } else if (classname == "scala.AnyRef") {
+      Console.println("package scala")
+      Console.println("class AnyRef extends Any {")
+      Console.println("  def equals(scala.Any): scala.Boolean")
+      Console.println("  def hashCode(): scala.Int")
+      Console.println("  def toString(): java.lang.String")
+      Console.println("}")
+      // if the class corresponds to the artificial class scala.AnyVal.
+    } else if (classname == "scala.AnyVal") {
+      Console.println("package scala")
+      Console.println("sealed class AnyVal extends Any")
+      // if the class corresponds to the artificial class scala.Boolean.
+    } else if (classname == "scala.Boolean") {
+      Console.println("package scala")
+      Console.println("sealed abstract class Boolean extends AnyVal {")
+      Console.println("  def &&(p: => scala.Boolean): scala.Boolean  // boolean and")
+      Console.println("  def ||(p: => scala.Boolean): scala.Boolean  // boolean or")
+      Console.println("  def & (x: scala.Boolean): scala.Boolean     // boolean strict and")
+      Console.println("  def | (x: scala.Boolean): scala.Boolean     // boolean stric or")
+      Console.println("  def ==(x: scala.Boolean): scala.Boolean     // boolean equality")
+      Console.println("  def !=(x: scala.Boolean): scala.Boolean     // boolean inequality")
+      Console.println("  def !: scala.Boolean                        // boolean negation")
+      Console.println("}")
+      // if the class corresponds to the artificial class scala.Int.
+    } else if (classname == "scala.Int") {
+      Console.println("package scala")
+      Console.println("sealed abstract class Int extends AnyVal {")
+      Console.println("  def ==(that: scala.Double): scala.Boolean")
+      Console.println("  def ==(that: scala.Float): scala.Boolean")
+      Console.println("  def ==(that: scala.Long): scala.Boolean")
+      Console.println("  def ==(that: scala.Int): scala.Boolean")
+      Console.println("  def ==(that: scala.Short): scala.Boolean")
+      Console.println("  def ==(that: scala.Byte): scala.Boolean")
+      Console.println("  def ==(that: scala.Char): scala.Boolean")
+      Console.println("  /* analogous for !=, <, >, <=, >= */")
+      Console.println
+      Console.println("  def + (that: scala.Double): scala.Double // double addition")
+      Console.println("  def + (that: scala.Float): scala.Float   // float addition")
+      Console.println("  def + (that: scala.Long): scala.Long     // long addition")
+      Console.println("  def + (that: scala.Int): scala.Int       // int addition")
+      Console.println("  def + (that: scala.Short): scala.Int     // int addition")
+      Console.println("  def + (that: scala.Byte): scala.Int      // int addition")
+      Console.println("  def + (that: scala.Char): scala.Int      // int addition")
+      Console.println("  /* analogous for -, *, /, % */")
+      Console.println
+      Console.println("  def & (that: scala.Long): scala.Long     // long bitwise and")
+      Console.println("  def & (that: scala.Int): scala.Int       // int bitwise and")
+      Console.println("  def & (that: scala.Short): scala.Int     // int bitwise and")
+      Console.println("  def & (that: scala.Byte): scala.Int      // int bitwise and")
+      Console.println("  def & (that: scala.Char): scala.Int      // int bitwise and")
+      Console.println("  /* analogous for |, ^ */")
+      Console.println
+      Console.println("  def <<(cnt: scala.Int): scala.Int        // int left shift")
+      Console.println("  def <<(cnt: scala.Long): scala.Int       // long left shift")
+      Console.println("  /* analogous for >>, >>> */")
+      Console.println
+      Console.println("  def + : scala.Int                        // int identity")
+      Console.println("  def - : scala.Int                        // int negation")
+      Console.println("  def ~ : scala.Int                        // int bitwise negation")
+      Console.println
+      Console.println("  def toByte: scala.Byte                   // convert to Byte")
+      Console.println("  def toShort: scala.Short                 // convert to Short")
+      Console.println("  def toChar: scala.Char                   // convert to Char")
+      Console.println("  def toInt: scala.Int                     // convert to Int")
+      Console.println("  def toLong: scala.Long                   // convert to Long")
+      Console.println("  def toFloat: scala.Float                 // convert to Float")
+      Console.println("  def toDouble: scala.Double               // convert to Double")
+      Console.println("}")
+      // if the class corresponds to the artificial class scala.Nothing.
+    } else if (classname == "scala.Nothing") {
+      Console.println("package scala")
+      Console.println("sealed abstract class Nothing")
+      // if the class corresponds to the artificial class scala.Null.
+    } else if (classname == "scala.Null") {
+      Console.println("package scala")
+      Console.println("sealed abstract class Null")
+    } else
+      Console.println("class/object " + classname + " not found.")
+  }
+
+  /**The main method of this object.
+   */
+  def main(args: Array[String]) {
+    // print usage information if there is no command-line argument
+    if (args.length == 0)
+      usage
+    // otherwise parse the arguments...
+    else {
+      val arguments = Arguments.Parser('-')
+              .withOption("-private")
+              .withOption("-verbose")
+              .withOption("-version")
+              .withOption("-help")
+              .withOptionalArg("-classpath")
+              .withOptionalArg("-cp")
+              .parse(args);
+      if (arguments contains "-version")
+        Console.println(versionMsg)
+      if (arguments contains "-help")
+        usage
+      verbose = arguments contains "-verbose"
+      printPrivates = arguments contains "-private"
+      // construct a custom class path
+      def cparg = List("-classpath", "-cp") map (arguments getArgument _) reduceLeft (_ orElse _)
+      val path = cparg map (PathResolver fromPathString _) getOrElse EmptyClasspath
+      // print the classpath if output is verbose
+      if (verbose) {
+        Console.println(Console.BOLD + "CLASSPATH" + Console.RESET + " = " + path)
+      }
+      // process all given classes
+      arguments.getOthers.foreach(process(arguments, path))
+    }
+  }
+
+  object EmptyClasspath extends ClassPath[AbstractFile] {
+    /**
+     * The short name of the package (without prefix)
+     */
+    def name: String = ""
+    def asURLs = Nil
+    def asClasspathString = ""
+    val context = DefaultJavaContext
+    val classes: List[ClassRep] = Nil
+    val packages: List[ClassPath[AbstractFile]] = Nil
+    val sourcepaths: List[AbstractFile] = Nil
+  }
+}
diff --git a/src/scalap/scala/tools/scalap/MetaParser.scala b/src/scalap/scala/tools/scalap/MetaParser.scala
new file mode 100644
index 0000000..2b75d97
--- /dev/null
+++ b/src/scalap/scala/tools/scalap/MetaParser.scala
@@ -0,0 +1,183 @@
+/*     ___ ____ ___   __   ___   ___
+**    / _// __// _ | / /  / _ | / _ \    Scala classfile decoder
+**  __\ \/ /__/ __ |/ /__/ __ |/ ___/    (c) 2003-2010, LAMP/EPFL
+** /____/\___/_/ |_/____/_/ |_/_/        http://scala-lang.org/
+**
+*/
+
+
+package scala.tools.scalap
+
+import java.io._
+import java.util._
+
+
+/** a parser class for parsing meta type information in classfiles
+ *  generated by pico.
+ */
+class MetaParser(meta: String) {
+  val scanner = new StringTokenizer(meta, "()[], \t<;", true)
+  var token: String = _
+  val res = new StringBuffer
+
+  private def nextToken: String = {
+    do {
+      token = scanner.nextToken().trim()
+    } while (token.length() == 0)
+    token
+  }
+
+  protected def parseType: Unit = {
+    if (token startsWith "?")
+      res.append(token.substring(1))
+    else
+      res.append(token)
+    nextToken
+    if (token == "[") {
+      do {
+        res.append(if (token == ",") ", " else "[")
+        nextToken
+        parseType
+      } while (token == ",")
+      nextToken
+      res.append("]")
+    }
+  }
+
+  def parse: Option[String] =
+    if (scanner.hasMoreTokens()) {
+      nextToken
+      try {
+        if (!scanner.hasMoreTokens())
+          None
+        else if (token == "class")
+          Some(parseMetaClass)
+        else if (token == "method")
+          Some(parseMetaMethod)
+        else if (token == "field")
+          Some(parseMetaField)
+        else if (token == "constr")
+          Some(parseConstrField)
+        else
+          None
+      } catch {
+        case _ => None
+      }
+    } else
+      None;
+
+  protected def parseMetaClass: String = {
+    nextToken
+    if (token == "[") {
+      do {
+        res.append(if (token == "[") "[" else ", ")
+        nextToken
+        if (token == "+") {
+          nextToken
+          res.append('+')
+        } else if (token == "-") {
+          nextToken
+          res.append('-')
+        }
+        res.append(token.substring(1))
+        nextToken
+        if (token == "<") {
+          nextToken
+          res.append(" <: ")
+          parseType
+        }
+      } while (token == ",")
+      nextToken
+      res.append("]")
+    }
+    if (token == "extends") {
+      do {
+        if (token == "extends")
+          res.append(" extends ")
+        else
+          res.append(" with ")
+        nextToken
+        parseType
+      } while (token == "with")
+    }
+    res.toString();
+  }
+
+  protected def parseMetaMethod: String = {
+    nextToken
+    if (token == "[") {
+      nextToken
+      if (token == "]") {
+        nextToken
+      } else {
+        var loop = true
+        res.append("[")
+        while (loop) {
+          res.append(token.substring(1));
+          nextToken;
+          if (token == "<") {
+            nextToken;
+            res.append(" <: ")
+            parseType
+          }
+          if (token == ",") {
+            nextToken
+            res.append(", ")
+          } else
+            loop = false
+        }
+        nextToken
+        res.append("]")
+      }
+    }
+    if (token == "(") {
+      do {
+        if (token == ",") {
+          nextToken;
+          if (token != ")")
+            res.append(", ")
+        } else {
+          nextToken;
+          res.append("(")
+        }
+        if (token != ")") {
+          if (token == "def") {
+            nextToken;
+            res.append("def ")
+          }
+          parseType
+        }
+      } while (token == ",")
+      nextToken
+      res.append("): ")
+      parseType
+    } else {
+      res.append(": ")
+      parseType
+    }
+    res.toString()
+  }
+
+  protected def parseMetaField: String = {
+    nextToken
+    res.append(": ")
+    parseType
+    res.toString()
+  }
+
+  protected def parseConstrField: String = {
+    nextToken
+    if (token == "(") {
+      do {
+        res.append(if (token == "(") "(" else ", ")
+        nextToken
+        if (token != ")")
+          parseType
+      } while (token == ",")
+      nextToken
+      res.append(")")
+    } else {
+    }
+    res.toString()
+  }
+}
diff --git a/src/scalap/scala/tools/scalap/Names.scala b/src/scalap/scala/tools/scalap/Names.scala
new file mode 100644
index 0000000..a916ea1
--- /dev/null
+++ b/src/scalap/scala/tools/scalap/Names.scala
@@ -0,0 +1,96 @@
+/*     ___ ____ ___   __   ___   ___
+**    / _// __// _ | / /  / _ | / _ \    Scala classfile decoder
+**  __\ \/ /__/ __ |/ /__/ __ |/ ___/    (c) 2003-2010, LAMP/EPFL
+** /____/\___/_/ |_/____/_/ |_/_/        http://scala-lang.org/
+**
+*/
+
+
+package scala.tools.scalap
+
+
+object Names {
+
+  val operatorName = new Array[String](128)
+  operatorName('$') = "$"
+  operatorName('~') = "$tilde"
+  operatorName('=') = "$eq"
+  operatorName('<') = "$less"
+  operatorName('>') = "$greater"
+  operatorName('!') = "$bang"
+  operatorName('#') = "$hash"
+  operatorName('%') = "$percent"
+  operatorName('^') = "$up"
+  operatorName('&') = "$amp"
+  operatorName('|') = "$bar"
+  operatorName('*') = "$times"
+  operatorName('/') = "$div"
+  operatorName('\\') = "$bslash"
+  operatorName('+') = "$plus"
+  operatorName('-') = "$minus"
+  operatorName(':') = "$colon"
+
+  /** Replace operator symbols by corresponding "$op_name" in names.
+   */
+  def encode(name: String): String = {
+    var i = 0
+    val len = name.length()
+    val res = new StringBuffer()
+    while (i < len) {
+      val c = name.charAt(i)
+      if (c < 128) {
+        val nop = operatorName(c)
+        if (nop == null)
+          res.append(c)
+        else
+          res.append(nop)
+      } else
+        res.append(c)
+      i = i + 1
+     }
+     res.toString()
+  }
+
+  /** Replace "$op_name" by corresponding operator symbols in names.
+   */
+  def decode(name: String): String = {
+    var i = 0
+    val len = name.length()
+    val res = new StringBuffer()
+    while (i < len) {
+      val c = name.charAt(i)
+      if (c == '$') {
+        var j = len
+        while (j > i) {
+          val prefix = name.substring(i, j)
+          val c = lookup(prefix)
+          if (c != null) {
+            i = j
+            res.append(c)
+          } else
+            j = j - 1
+        }
+      } else {
+        i = i + 1
+        res.append(c)
+      }
+    }
+    res.toString()
+  }
+
+  /** Looks up the array entry for the operator name.
+   */
+  def lookup(string: String): String = {
+    var i = 0
+    var res: String = null
+    while (i < 128) {
+      if (string.equals(operatorName(i))) {
+        res = String.valueOf(i.asInstanceOf[Char])
+        i = 128
+      }
+      i = i + 1
+    }
+    res
+  }
+
+}
diff --git a/src/scalap/scala/tools/scalap/Properties.scala b/src/scalap/scala/tools/scalap/Properties.scala
new file mode 100644
index 0000000..4cdbe69
--- /dev/null
+++ b/src/scalap/scala/tools/scalap/Properties.scala
@@ -0,0 +1,16 @@
+/*     ___ ____ ___   __   ___   ___
+**    / _// __// _ | / /  / _ | / _ \  Scala classfile decoder
+**  __\ \/ /__/ __ |/ /__/ __ |/ ___/  (c) 2003-2010, LAMP/EPFL
+** /____/\___/_/ |_/____/_/ |_/_/      http://scala-lang.org/
+**
+*/
+
+
+package scala.tools.scalap
+
+/** Loads decoder.properties from the jar. */
+object Properties extends scala.util.PropertiesTrait
+{
+  protected def propCategory    = "decoder"
+  protected def pickJarBasedOn  = classOf[Classfile]
+}
diff --git a/src/scalap/scala/tools/scalap/scalax/rules/Arrows.scala b/src/scalap/scala/tools/scalap/scalax/rules/Arrows.scala
new file mode 100644
index 0000000..5316974
--- /dev/null
+++ b/src/scalap/scala/tools/scalap/scalax/rules/Arrows.scala
@@ -0,0 +1,37 @@
+package scala.tools.scalap
+package scalax
+package rules
+
+trait Arrows extends UnitFunctors  {
+  type Arr[-A, +B] <: Arrow[A, B]
+  type M[+B] = Arr[Nothing, B]
+  
+  def arrow[A, B](f : A => B) : Arr[A, B]
+  def diag[A] = arrow[A, (A, A)] { a => (a, a) }
+  
+  override def unit[B](b : => B) : M[B] = arrow { any : Any => b }
+  
+  trait Arrow[-A, +B] extends Functor[B] { this : Arr[A, B] =>
+    
+    def map[C](f : B => C) = comp(arrow(f))
+    def comp[C](bc : => Arr[B, C]) : Arr[A, C]
+    def fst[C] : Arr[(A, C), (B, C)]
+  }
+}
+
+trait ApplicativeArrows extends Arrows {
+  type Arr[-A, +B] <: ApplicativeArrow[A, B]
+
+  def app[A, B] : Arr[(Arr[A, B], A), B]
+  
+  trait ApplicativeArrow[-A, +B] extends Arrow[A, B] { self : Arr[A, B] =>
+    def flatMap[SubA <: A, C](f : B => Arr[SubA, C]) : Arr[SubA, C] =
+      diag[SubA].comp(map(f).fst[SubA]).comp(app[SubA, C])
+  }
+}
+
+trait ArrowMonads extends ApplicativeArrows with Monads {
+  type Arr[-A, +B] <: ApplicativeArrow[A, B] with Monad[B]
+
+  override def unit[A](a : => A) : M[A] = arrow[Unit, A](Unit => a)
+}
diff --git a/src/scalap/scala/tools/scalap/scalax/rules/Functors.scala b/src/scalap/scala/tools/scalap/scalax/rules/Functors.scala
new file mode 100644
index 0000000..981cc47
--- /dev/null
+++ b/src/scalap/scala/tools/scalap/scalax/rules/Functors.scala
@@ -0,0 +1,81 @@
+// -----------------------------------------------------------------------------
+//
+//  Scalax - The Scala Community Library
+//  Copyright (c) 2005-8 The Scalax Project. All rights reserved.
+//
+//  The primary distribution site is http://scalax.scalaforge.org/
+//
+//  This software is released under the terms of the Revised BSD License.
+//  There is NO WARRANTY.  See the file LICENSE for the full text.
+//
+// -----------------------------------------------------------------------------
+
+package scala.tools.scalap
+package scalax
+package rules
+
+trait Functor[+A] { 
+  type M[+A] <: Functor[A]
+  def map[B](f : A => B) : M[B]
+}
+
+trait Filter[+A] { 
+  type M[+A] <: Filter[A]
+  def filter(f : A => Boolean) : M[A]
+}
+
+trait Plus[+A] { 
+  type M[+A] <: Plus[A]
+  def plus[B >: A](other : => M[B]) : M[B]
+}
+
+trait OrElse[+A] { 
+  type M[+A] <: OrElse[A]
+  def orElse[B >: A](other : => M[B]) : M[B]
+}
+
+trait Units {
+  type M[+A]
+  def unit : M[Unit]
+  def unit[A](a : => A) : M[A]
+}
+
+trait Zero {
+  type M[+A]
+  def zero : M[Nothing]
+}
+
+trait Functors {
+  type M[+A] <: Functor[A]
+  
+  trait Functor[+A] extends rules.Functor[A] { this : M[A] =>
+    type M[+A] = Functors.this.M[A]
+  }
+ 
+  trait ZeroFunctor extends Functor[Nothing] { this : M[Nothing] =>
+    override def map[B](f : Nothing => B) : M[B] = this
+    def filter(f : Nothing => Boolean) : M[Nothing] = this
+    def plus[B](other : => M[B]) : M[B] = other
+    def orElse[B](other : => M[B]) : M[B] = other
+  }
+}
+
+/** One of the 'unit' definitions must be overridden in concrete subclasses */
+trait UnitFunctors extends Units with Functors {
+  def unit : M[Unit] = unit(())
+  def unit[A](a : => A) : M[A] = unit map { Unit => a }
+}
+
+
+trait Monoidals extends UnitFunctors {
+  type M[+A] <: Monoidal[A]
+    
+  implicit def app[A, B](fab : M[A => B]) = (fa : M[A]) => fa applyTo fab
+  implicit def appUnit[A, B](a2b : A => B) = app(unit(a2b))
+  
+  /** One of 'and' and 'applyTo' definitions must be overridden in concrete subclasses */
+  trait Monoidal[+A] extends Functor[A] { self : M[A] =>
+    def and[B](fb : => M[B]) : M[(A, B)] = ((a : A) => (b : B) => (a, b))(this)(fb)
+    def applyTo[B](fab : M[A => B]) : M[B] = fab and this map { case (f, a) => f(a) }
+  }
+}
diff --git a/src/scalap/scala/tools/scalap/scalax/rules/Input.scala b/src/scalap/scala/tools/scalap/scalax/rules/Input.scala
new file mode 100644
index 0000000..7b85a34
--- /dev/null
+++ b/src/scalap/scala/tools/scalap/scalax/rules/Input.scala
@@ -0,0 +1,68 @@
+// -----------------------------------------------------------------------------
+//
+//  Scalax - The Scala Community Library
+//  Copyright (c) 2005-8 The Scalax Project. All rights reserved.
+//
+//  The primary distribution site is http://scalax.scalaforge.org/
+//
+//  This software is released under the terms of the Revised BSD License.
+//  There is NO WARRANTY.  See the file LICENSE for the full text.
+//
+// -----------------------------------------------------------------------------
+
+package scala.tools.scalap
+package scalax
+package rules
+
+trait Input[+A] extends Iterable[A] { 
+
+  def next : Result[Input[A], A, Nothing]
+  def index : Int
+
+  def iterator = new Iterator[A] {
+    private var input : Input[A] = Input.this
+    private var result = input.next
+
+    def hasNext = result != Failure
+    def next = {
+      val Success(input, value) = result
+      this.input = input
+      this.result = input.next
+      value
+    }
+  }
+}
+
+
+class ArrayInput[A](val array : Array[A], val index : Int) extends Input[A] {
+  def this(array : Array[A]) = this(array, 0)
+
+  lazy val next : Result[ArrayInput[A], A, Nothing] = if (index >= array.length) Failure
+      else Success(new ArrayInput[A](array, index + 1), array(index))
+ 
+  override lazy val toString = this.iterator.mkString("\"", "", "\"")
+}
+
+
+class IterableInput[A](iterator : Iterator[A], val index : Int) extends Input[A] {
+  def this(iterable : Iterable[A]) = this(iterable.iterator, 0)
+
+  lazy val next : Result[IterableInput[A], A, Nothing] = if (!iterator.hasNext) Failure
+      else Success(new IterableInput(iterator, index + 1), iterator.next)
+
+  override lazy val toString = this.iterator.mkString("\"", "", "\"")
+}
+
+
+/** View one type of input as another based on a transformation rule */
+class View[A, B](
+    transform : Input[A] => Result[Input[A], B, Nothing],
+    val input : Input[A],
+    val index : Int)
+    extends Input[B] {
+
+  def next : Result[Input[B], B, Nothing] = transform(input) match {
+    case Success(context, b) => Success(new View(transform, context, index + 1), b)
+    case _ => Failure
+  }
+}
diff --git a/src/scalap/scala/tools/scalap/scalax/rules/Memoisable.scala b/src/scalap/scala/tools/scalap/scalax/rules/Memoisable.scala
new file mode 100644
index 0000000..b619432
--- /dev/null
+++ b/src/scalap/scala/tools/scalap/scalax/rules/Memoisable.scala
@@ -0,0 +1,61 @@
+// -----------------------------------------------------------------------------
+//
+//  Scalax - The Scala Community Library
+//  Copyright (c) 2005-8 The Scalax Project. All rights reserved.
+//
+//  The primary distribution site is http://scalax.scalaforge.org/
+//
+//  This software is released under the terms of the Revised BSD License.
+//  There is NO WARRANTY.  See the file LICENSE for the full text.
+//
+// -----------------------------------------------------------------------------
+
+package scala.tools.scalap
+package scalax
+package rules
+
+import scala.collection.mutable.HashMap
+
+trait MemoisableRules extends Rules {
+  def memo[In <: Memoisable, Out, A, X](key : AnyRef)(toRule : => In => Result[Out, A, X]) = {
+    lazy val rule = toRule
+    from[In] { in => in.memo(key, rule(in)) }
+  }
+  
+  override def ruleWithName[In, Out, A, X](name : String, f : In => rules.Result[Out, A, X]) = super.ruleWithName(name, (in : In) => in match {
+      case s : Memoisable => s.memo(name, f(in))
+      case _ => f(in)
+    })
+}
+
+trait Memoisable {
+  def memo[A](key : AnyRef, a : => A) : A
+}
+
+
+object DefaultMemoisable {
+  var debug = false
+}
+
+trait DefaultMemoisable extends Memoisable {
+  protected val map = new HashMap[AnyRef, Any]
+
+  def memo[A](key : AnyRef, a : => A) = {
+    map.getOrElseUpdate(key, compute(key, a)).asInstanceOf[A]
+  }
+  
+  protected def compute[A](key : AnyRef, a : => A): Any = a match {
+    case success : Success[_, _] => onSuccess(key, success); success
+    case other => 
+      if(DefaultMemoisable.debug) println(key + " -> " + other) 
+      other
+  }
+  
+  protected def onSuccess[S, T](key : AnyRef,  result : Success[S, T])  { 
+    val Success(out, t) = result
+    if(DefaultMemoisable.debug) println(key + " -> " + t + " (" + out + ")") 
+  }
+}
+
+
+
diff --git a/src/scalap/scala/tools/scalap/scalax/rules/Monad.scala b/src/scalap/scala/tools/scalap/scalax/rules/Monad.scala
new file mode 100644
index 0000000..70596bb
--- /dev/null
+++ b/src/scalap/scala/tools/scalap/scalax/rules/Monad.scala
@@ -0,0 +1,46 @@
+// -----------------------------------------------------------------------------
+//
+//  Scalax - The Scala Community Library
+//  Copyright (c) 2005-8 The Scalax Project. All rights reserved.
+//
+//  The primary distribution site is http://scalax.scalaforge.org/
+//
+//  This software is released under the terms of the Revised BSD License.
+//  There is NO WARRANTY.  See the file LICENSE for the full text.
+//
+// -----------------------------------------------------------------------------
+
+package scala.tools.scalap
+package scalax
+package rules
+
+trait Monad[+A] extends Functor[A] { 
+  type M[+A] <: Monad[A]
+  def flatMap[B](f : A => M[B]) : M[B]
+}
+
+trait Monads extends UnitFunctors {
+  type M[+A] <: Monad[A]
+  
+  trait Monad[+A] extends Functor[A] with rules.Monad[A] { this : M[A] =>
+    def map[B](f : A => B) = flatMap { a => unit(f(a)) }
+  }
+  
+  trait ZeroMonad extends Monad[Nothing] with ZeroFunctor { this : M[Nothing] =>
+    def flatMap[B](f : Nothing => M[B]) : M[B] = this
+  }
+}
+
+
+trait StateReader extends Monads {
+  type S
+  
+  def get : M[S]
+  def read[A](f : S => A) : M[A]
+  def set(s : => S) : M[S]
+  def update(f : S => S) : M[S]
+}
+
+
+
+
diff --git a/src/scalap/scala/tools/scalap/scalax/rules/Result.scala b/src/scalap/scala/tools/scalap/scalax/rules/Result.scala
new file mode 100644
index 0000000..8722819
--- /dev/null
+++ b/src/scalap/scala/tools/scalap/scalax/rules/Result.scala
@@ -0,0 +1,72 @@
+// -----------------------------------------------------------------------------
+//
+//  Scalax - The Scala Community Library
+//  Copyright (c) 2005-8 The Scalax Project. All rights reserved.
+//
+//  The primary distribution site is http://scalax.scalaforge.org/
+//
+//  This software is released under the terms of the Revised BSD License.
+//  There is NO WARRANTY.  See the file LICENSE for the full text.
+//
+// -----------------------------------------------------------------------------
+
+package scala.tools.scalap
+package scalax
+package rules;
+
+/** Represents the combined value of two rules applied in sequence.
+ *
+ * @see the Scala parser combinator
+ */
+case class ~[+A, +B](_1 : A, _2 : B) {
+  override def toString = "(" + _1 + " ~ " + _2 + ")"
+}
+  
+
+sealed abstract class Result[+Out, +A, +X] {
+  def out : Out
+  def value : A
+  def error : X
+  
+  implicit def toOption : Option[A]
+  
+  def map[B](f : A => B) : Result[Out, B, X]
+  def mapOut[Out2](f : Out => Out2) : Result[Out2, A, X]
+  def map[Out2, B](f : (Out, A) => (Out2, B)) : Result[Out2, B, X]
+  def flatMap[Out2, B](f : (Out, A) => Result[Out2, B, Nothing]) : Result[Out2, B, X]
+  def orElse[Out2 >: Out, B >: A](other : => Result[Out2, B, Nothing]) : Result[Out2, B, X]
+}
+
+case class Success[+Out, +A](out : Out, value : A) extends Result[Out, A, Nothing] {
+  def error = throw new ScalaSigParserError("No error")
+
+  def toOption = Some(value)
+  
+  def map[B](f : A => B) : Result[Out, B, Nothing] = Success(out, f(value))
+  def mapOut[Out2](f : Out => Out2) : Result[Out2, A, Nothing] = Success(f(out), value)
+  def map[Out2, B](f : (Out, A) => (Out2, B)) : Success[Out2, B] = f(out, value) match { case (out2, b) => Success(out2, b) }
+  def flatMap[Out2, B](f : (Out, A) => Result[Out2, B, Nothing]) : Result[Out2, B, Nothing]= f(out, value)
+  def orElse[Out2 >: Out, B >: A](other : => Result[Out2, B, Nothing]) : Result[Out2, B, Nothing] = this
+}
+
+sealed abstract class NoSuccess[+X] extends Result[Nothing, Nothing, X] {
+  def out = throw new ScalaSigParserError("No output")
+  def value = throw new ScalaSigParserError("No value")
+
+  def toOption = None
+  
+  def map[B](f : Nothing => B) = this
+  def mapOut[Out2](f : Nothing => Out2) = this
+  def map[Out2, B](f : (Nothing, Nothing) => (Out2, B)) = this
+  def flatMap[Out2, B](f : (Nothing, Nothing) => Result[Out2, B, Nothing]) = this
+  def orElse[Out2, B](other : => Result[Out2, B, Nothing]) = other
+}
+
+case object Failure extends NoSuccess[Nothing] {
+  def error = throw new ScalaSigParserError("No error")
+}
+
+case class ScalaSigParserError(msg: String) extends RuntimeException(msg)
+
+case class Error[+X](error : X) extends NoSuccess[X] {
+}
diff --git a/src/scalap/scala/tools/scalap/scalax/rules/Rule.scala b/src/scalap/scala/tools/scalap/scalax/rules/Rule.scala
new file mode 100644
index 0000000..10f03af
--- /dev/null
+++ b/src/scalap/scala/tools/scalap/scalax/rules/Rule.scala
@@ -0,0 +1,177 @@
+// -----------------------------------------------------------------------------
+//
+//  Scalax - The Scala Community Library
+//  Copyright (c) 2005-8 The Scalax Project. All rights reserved.
+//
+//  The primary distribution site is http://scalax.scalaforge.org/
+//
+//  This software is released under the terms of the Revised BSD License.
+//  There is NO WARRANTY.  See the file LICENSE for the full text.
+//
+// -----------------------------------------------------------------------------
+
+package scala.tools.scalap
+package scalax
+package rules
+
+/** A Rule is a function from some input to a Result.  The result may be:
+  * <ul>
+  * <li>Success, with a value of some type and an output that may serve as the input to subsequent rules.</li> 
+  * <li>Failure. A failure may result in some alternative rule being applied.</li>
+  * <li>Error.  No further rules should be attempted.</li>
+  * </ul>
+  *
+  * @author Andrew Foggin
+  *   
+  * Inspired by the Scala parser combinator.
+  */
+trait Rule[-In, +Out, +A, +X] extends (In => Result[Out, A, X]) { 
+  val factory : Rules
+  import factory._
+  
+  def as(name : String) = ruleWithName(name, this)
+  
+  def flatMap[Out2, B, X2 >: X](fa2ruleb : A => Out => Result[Out2, B, X2]) = mapResult { 
+      case Success(out, a) => fa2ruleb(a)(out)
+      case Failure => Failure
+      case err @ Error(_) => err
+  }
+  
+  def map[B](fa2b : A => B) = flatMap { a => out => Success(out, fa2b(a)) }
+
+  def filter(f : A => Boolean) = flatMap { a => out => if(f(a)) Success(out, a) else Failure }
+
+  def mapResult[Out2, B, Y](f : Result[Out, A, X] => Result[Out2, B, Y]) = rule { 
+    in : In => f(apply(in))
+  }
+  
+  def orElse[In2 <: In, Out2 >: Out, A2 >: A, X2 >: X](other : => Rule[In2, Out2, A2, X2]) : Rule[In2, Out2, A2, X2] = new Choice[In2, Out2, A2, X2] {
+    val factory = Rule.this.factory
+    lazy val choices = Rule.this :: other :: Nil
+  }
+
+  def orError[In2 <: In] = this orElse(error[In2])
+
+  def |[In2 <: In, Out2 >: Out, A2 >: A, X2 >: X](other : => Rule[In2, Out2, A2, X2]) = orElse(other)
+
+  def ^^[B](fa2b : A => B) = map(fa2b)
+  
+  def ^^?[B](pf : PartialFunction[A, B]) = filter (pf.isDefinedAt(_)) ^^ pf 
+      
+  def ??(pf : PartialFunction[A, Any]) = filter (pf.isDefinedAt(_))
+  
+  def -^[B](b : B) = map { any => b }
+ 
+  /** Maps an Error */
+  def !^[Y](fx2y : X => Y) = mapResult { 
+    case s @ Success(_, _) => s
+    case Failure => Failure
+    case Error(x) => Error(fx2y(x))
+  }
+    
+  def >>[Out2, B, X2 >: X](fa2ruleb : A => Out => Result[Out2, B, X2]) = flatMap(fa2ruleb)
+  
+  def >->[Out2, B, X2 >: X](fa2resultb : A => Result[Out2, B, X2]) = flatMap { a => any => fa2resultb(a) }
+  
+  def >>?[Out2, B, X2 >: X](pf : PartialFunction[A, Rule[Out, Out2, B, X2]]) = filter(pf isDefinedAt _) flatMap pf
+  
+  def >>&[B, X2 >: X](fa2ruleb : A => Out => Result[Any, B, X2]) = flatMap { a => out => fa2ruleb(a)(out) mapOut { any => out } }
+  
+  def ~[Out2, B, X2 >: X](next : => Rule[Out, Out2, B, X2]) = for (a <- this; b <- next) yield new ~(a, b)
+
+  def ~-[Out2, B, X2 >: X](next : => Rule[Out, Out2, B, X2]) = for (a <- this; b <- next) yield a
+  
+  def -~[Out2, B, X2 >: X](next : => Rule[Out, Out2, B, X2]) = for (a <- this; b <- next) yield b
+  
+  def ~++[Out2, B >: A, X2 >: X](next : => Rule[Out, Out2, Seq[B], X2]) = for (a <- this; b <- next) yield a :: b.toList
+
+  /** Apply the result of this rule to the function returned by the next rule */
+  def ~>[Out2, B, X2 >: X](next : => Rule[Out, Out2, A => B, X2]) = for (a <- this; fa2b <- next) yield fa2b(a)
+  
+  /** Apply the result of this rule to the function returned by the previous rule */
+  def <~:[InPrev, B, X2 >: X](prev : => Rule[InPrev, In, A => B, X2]) = for (fa2b <- prev; a <- this) yield fa2b(a)
+    
+  def ~![Out2, B, X2 >: X](next : => Rule[Out, Out2, B, X2]) = for (a <- this; b <- next orError) yield new ~(a, b)
+  
+  def ~-![Out2, B, X2 >: X](next : => Rule[Out, Out2, B, X2]) = for (a <- this; b <- next orError) yield a
+  
+  def -~![Out2, B, X2 >: X](next : => Rule[Out, Out2, B, X2]) = for (a <- this; b <- next orError) yield b
+  
+  def -[In2 <: In](exclude : => Rule[In2, Any, Any, Any]) = !exclude -~ this
+      
+  /** ^~^(f) is equivalent to ^^ { case b1 ~ b2 => f(b1, b2) } 
+   */
+  def ^~^[B1, B2, B >: A <% B1 ~ B2, C](f : (B1, B2) => C) = map { a =>
+    (a : B1 ~ B2) match { case b1 ~ b2 => f(b1, b2) } 
+  }
+    
+  /** ^~~^(f) is equivalent to ^^ { case b1 ~ b2 ~ b3 => f(b1, b2, b3) } 
+   */
+  def ^~~^[B1, B2, B3, B >: A <% B1 ~ B2 ~ B3, C](f : (B1, B2, B3) => C) = map { a =>
+    (a : B1 ~ B2 ~ B3) match { case b1 ~ b2 ~ b3 => f(b1, b2, b3) } 
+  }
+    
+  /** ^~~~^(f) is equivalent to ^^ { case b1 ~ b2 ~ b3 ~ b4 => f(b1, b2, b3, b4) } 
+   */
+  def ^~~~^[B1, B2, B3, B4, B >: A <% B1 ~ B2 ~ B3 ~ B4, C](f : (B1, B2, B3, B4) => C) = map { a =>
+    (a : B1 ~ B2 ~ B3 ~ B4) match { case b1 ~ b2 ~ b3 ~ b4 => f(b1, b2, b3, b4) } 
+  }
+     
+  /** ^~~~~^(f) is equivalent to ^^ { case b1 ~ b2 ~ b3 ~ b4 ~ b5 => f(b1, b2, b3, b4, b5) } 
+   */
+  def ^~~~~^[B1, B2, B3, B4, B5, B >: A <% B1 ~ B2 ~ B3 ~ B4 ~ B5, C](f : (B1, B2, B3, B4, B5) => C) = map { a =>
+    (a : B1 ~ B2 ~ B3 ~ B4 ~ B5) match { case b1 ~ b2 ~ b3 ~ b4 ~ b5 => f(b1, b2, b3, b4, b5) } 
+  }
+      
+  /** ^~~~~~^(f) is equivalent to ^^ { case b1 ~ b2 ~ b3 ~ b4 ~ b5 ~ b6 => f(b1, b2, b3, b4, b5, b6) } 
+   */
+  def ^~~~~~^[B1, B2, B3, B4, B5, B6, B >: A <% B1 ~ B2 ~ B3 ~ B4 ~ B5 ~ B6, C](f : (B1, B2, B3, B4, B5, B6) => C) = map { a =>
+    (a : B1 ~ B2 ~ B3 ~ B4 ~ B5 ~ B6) match { case b1 ~ b2 ~ b3 ~ b4 ~ b5 ~ b6 => f(b1, b2, b3, b4, b5, b6) } 
+  }
+       
+  /** ^~~~~~~^(f) is equivalent to ^^ { case b1 ~ b2 ~ b3 ~ b4 ~ b5 ~ b6 => f(b1, b2, b3, b4, b5, b6) } 
+   */
+  def ^~~~~~~^[B1, B2, B3, B4, B5, B6, B7, B >: A <% B1 ~ B2 ~ B3 ~ B4 ~ B5 ~ B6 ~ B7, C](f : (B1, B2, B3, B4, B5, B6, B7) => C) = map { a =>
+    (a : B1 ~ B2 ~ B3 ~ B4 ~ B5 ~ B6 ~ B7) match { case b1 ~ b2 ~ b3 ~ b4 ~ b5 ~ b6 ~b7 => f(b1, b2, b3, b4, b5, b6, b7) } 
+  }
+   
+  /** >~>(f) is equivalent to >> { case b1 ~ b2 => f(b1, b2) } 
+   */
+  def >~>[Out2, B1, B2, B >: A <% B1 ~ B2, C, X2 >: X](f : (B1, B2) => Out => Result[Out2, C, X2]) = flatMap { a =>
+    (a : B1 ~ B2) match { case b1 ~ b2 => f(b1, b2) } 
+  }
+
+  /** ^-^(f) is equivalent to ^^ { b2 => b1 => f(b1, b2) } 
+   */
+  def ^-^ [B1, B2 >: A, C](f : (B1, B2) => C) = map { b2 : B2 => b1 : B1 => f(b1, b2) } 
+    
+ /** ^~>~^(f) is equivalent to ^^ { case b2 ~ b3 => b1 => f(b1, b2, b3) } 
+  */
+ def ^~>~^ [B1, B2, B3, B >: A <% B2 ~ B3, C](f : (B1, B2, B3) => C) = map { a => 
+   (a : B2 ~ B3) match { case b2 ~ b3 => b1 : B1 => f(b1, b2, b3) } 
+ }
+}
+  
+
+trait Choice[-In, +Out, +A, +X] extends Rule[In, Out, A, X] {
+  def choices : List[Rule[In, Out, A, X]]
+    
+  def apply(in : In) = {
+    def oneOf(list : List[Rule[In, Out, A, X]]) : Result[Out, A, X] = list match {
+      case Nil => Failure
+      case first :: rest => first(in) match {
+        case Failure => oneOf(rest)
+        case result => result
+      }
+    }
+    oneOf(choices)
+  }
+    
+  override def orElse[In2 <: In, Out2 >: Out, A2 >: A, X2 >: X](other : => Rule[In2, Out2, A2, X2]) : Rule[In2, Out2, A2, X2] = new Choice[In2, Out2, A2, X2] {
+    val factory = Choice.this.factory
+    lazy val choices = Choice.this.choices ::: other :: Nil
+  }
+}
+
+               
+
diff --git a/src/scalap/scala/tools/scalap/scalax/rules/Rules.scala b/src/scalap/scala/tools/scalap/scalax/rules/Rules.scala
new file mode 100644
index 0000000..e44ff10
--- /dev/null
+++ b/src/scalap/scala/tools/scalap/scalax/rules/Rules.scala
@@ -0,0 +1,146 @@
+// -----------------------------------------------------------------------------
+//
+//  Scalax - The Scala Community Library
+//  Copyright (c) 2005-8 The Scalax Project. All rights reserved.
+//
+//  The primary distribution site is http://scalax.scalaforge.org/
+//
+//  This software is released under the terms of the Revised BSD License.
+//  There is NO WARRANTY.  See the file LICENSE for the full text.
+//
+// -----------------------------------------------------------------------------
+
+package scala.tools.scalap
+package scalax
+package rules
+
+trait Name {
+  def name : String
+  override def toString = name
+}
+
+/** A factory for rules.
+  * 
+  * @author Andrew Foggin
+  *
+  * Inspired by the Scala parser combinator.
+  */
+trait Rules {
+  implicit def rule[In, Out, A, X](f : In => Result[Out, A, X]) : Rule[In, Out, A, X] = new DefaultRule(f)
+
+  implicit def inRule[In, Out, A, X](rule : Rule[In, Out, A, X]) : InRule[In, Out, A, X] = new InRule(rule)
+  implicit def seqRule[In, A, X](rule : Rule[In, In, A, X]) : SeqRule[In, A, X] = new SeqRule(rule)
+  
+  def from[In] = new {
+    def apply[Out, A, X](f : In => Result[Out, A, X]) = rule(f)
+  }
+  
+  def state[s] = new StateRules {
+    type S = s
+    val factory = Rules.this
+  }
+  
+  def success[Out, A](out : Out, a : A) = rule { in : Any => Success(out, a) }
+  
+  def failure = rule { in : Any => Failure }
+  
+  def error[In] = rule { in : In => Error(in) }
+  def error[X](err : X) = rule { in : Any => Error(err) }
+      
+  def oneOf[In, Out, A, X](rules : Rule[In, Out, A, X] *) : Rule[In, Out, A, X] = new Choice[In, Out, A, X] {
+    val factory = Rules.this
+    val choices = rules.toList
+  }
+    
+  def ruleWithName[In, Out, A, X](_name : String, f : In => Result[Out, A, X]) : Rule[In, Out, A, X] with Name = 
+    new DefaultRule(f) with Name {
+      val name = _name
+    }
+
+  class DefaultRule[In, Out, A, X](f : In => Result[Out, A, X]) extends Rule[In, Out, A, X] {
+    val factory = Rules.this
+    def apply(in : In) = f(in)
+  }
+  
+ /** Converts a rule into a function that throws an Exception on failure. */
+  def expect[In, Out, A, Any](rule : Rule[In, Out, A, Any]) : In => A = (in) => rule(in) match {
+    case Success(_, a) => a
+    case Failure => throw new ScalaSigParserError("Unexpected failure")
+    case Error(x) => throw new ScalaSigParserError("Unexpected error: " + x)
+  }
+}
+
+/** A factory for rules that apply to a particular context.
+  *
+  * @requires S the context to which rules apply.
+  *
+  * @author Andrew Foggin
+  *
+  * Inspired by the Scala parser combinator.
+  */
+trait StateRules {
+  type S
+  type Rule[+A, +X] = rules.Rule[S, S, A, X]
+  
+  val factory : Rules
+  import factory._
+  
+  def apply[A, X](f : S => Result[S, A, X]) = rule(f)
+
+  def unit[A](a : => A) = apply { s => Success(s, a) }
+  def read[A](f : S => A) = apply { s => Success(s, f(s)) }
+  
+  def get = apply { s => Success(s, s) }
+  def set(s : => S) = apply { oldS => Success(s, oldS) }
+
+  def update(f : S => S) = apply { s => Success(s, f(s)) }
+  
+  def nil = unit(Nil)
+  def none = unit(None)
+  
+  /** Create a rule that identities if f(in) is true. */
+  def cond(f : S => Boolean) = get filter f
+
+  /** Create a rule that succeeds if all of the given rules succeed.
+      @param rules the rules to apply in sequence.
+  */
+  def allOf[A, X](rules : Seq[Rule[A, X]]) = {
+    def rep(in : S, rules : List[Rule[A, X]], results : List[A]) : Result[S, List[A], X] = {
+      rules match {
+        case Nil => Success(in, results.reverse)
+        case rule::tl => rule(in) match {
+          case Failure => Failure
+          case Error(x) => Error(x)
+          case Success(out, v) => rep(out, tl, v::results)
+        }
+      }
+    }
+    in : S => rep(in, rules.toList, Nil)
+  }
+
+
+  /** Create a rule that succeeds with a list of all the provided rules that succeed.
+      @param rules the rules to apply in sequence.
+  */
+  def anyOf[A, X](rules : Seq[Rule[A, X]]) = allOf(rules.map(_ ?)) ^^ { opts => opts.flatMap(x => x) }
+  
+  /** Repeatedly apply a rule from initial value until finished condition is met. */
+  def repeatUntil[T, X](rule : Rule[T => T, X])(finished : T => Boolean)(initial : T) = apply { 
+    // more compact using HoF but written this way so it's tail-recursive
+    def rep(in : S, t : T) : Result[S, T, X] = {
+      if (finished(t)) Success(in, t) 
+      else rule(in) match {
+        case Success(out, f) => rep(out, f(t))
+        case Failure => Failure
+        case Error(x) => Error(x)
+      }
+    }
+    in => rep(in, initial)
+  }
+  
+
+}
+
+trait RulesWithState extends Rules with StateRules {
+  val factory = this
+}
diff --git a/src/scalap/scala/tools/scalap/scalax/rules/SeqRule.scala b/src/scalap/scala/tools/scalap/scalax/rules/SeqRule.scala
new file mode 100644
index 0000000..e534c15
--- /dev/null
+++ b/src/scalap/scala/tools/scalap/scalax/rules/SeqRule.scala
@@ -0,0 +1,101 @@
+// -----------------------------------------------------------------------------
+//
+//  Scalax - The Scala Community Library
+//  Copyright (c) 2005-8 The Scalax Project. All rights reserved.
+//
+//  The primary distribution site is http://scalax.scalaforge.org/
+//
+//  This software is released under the terms of the Revised BSD License.
+//  There is NO WARRANTY.  See the file LICENSE for the full text.
+//
+// -----------------------------------------------------------------------------
+
+package scala.tools.scalap
+package scalax
+package rules
+
+/** 
+ * A workaround for the difficulties of dealing with
+ * a contravariant 'In' parameter type...
+ */
+class InRule[In, +Out, +A, +X](rule : Rule[In, Out, A, X]) {
+  
+  def mapRule[Out2, B, Y](f : Result[Out, A, X] => In => Result[Out2, B, Y]) : Rule[In, Out2, B, Y] = rule.factory.rule { 
+    in : In => f(rule(in))(in)
+  }
+
+  /** Creates a rule that succeeds only if the original rule would fail on the given context. */
+  def unary_! : Rule[In, In, Unit, Nothing] = mapRule { 
+    case Success(_, _) => in : In => Failure
+    case _ => in : In => Success(in, ())
+  }
+
+  /** Creates a rule that succeeds if the original rule succeeds, but returns the original input. */
+  def & : Rule[In, In, A, X] = mapRule {
+    case Success(_, a) => in : In => Success(in, a)
+    case Failure => in : In => Failure
+    case Error(x) => in : In => Error(x)
+  }
+}
+
+class SeqRule[S, +A, +X](rule : Rule[S, S, A, X]) {
+  import rule.factory._
+
+  def ? = rule mapRule { 
+    case Success(out, a) => in : S => Success(out, Some(a))
+    case Failure => in : S => Success(in, None)
+    case Error(x) => in : S => Error(x)
+  }
+  
+  /** Creates a rule that always succeeds with a Boolean value.  
+   *  Value is 'true' if this rule succeeds, 'false' otherwise */
+  def -? = ? map { _ isDefined }
+        
+  def * = from[S] { 
+    // tail-recursive function with reverse list accumulator
+    def rep(in : S, acc : List[A]) : Result[S, List[A], X] = rule(in) match {
+       case Success(out, a) => rep(out, a :: acc)
+       case Failure => Success(in, acc.reverse)
+       case err : Error[_] => err
+    }
+    in => rep(in, Nil)
+  }
+  
+  def + = rule ~++ *
+    
+  def ~>?[B >: A, X2 >: X](f : => Rule[S, S, B => B, X2]) = for (a <- rule; fs <- f?) yield fs.foldLeft[B](a) { (b, f) => f(b) }
+  
+  def ~>*[B >: A, X2 >: X](f : => Rule[S, S, B => B, X2]) = for (a <- rule; fs <- f*) yield fs.foldLeft[B](a) { (b, f) => f(b) }
+    
+  def ~*~[B >: A, X2 >: X](join : => Rule[S, S, (B, B) => B, X2]) = {
+    this ~>* (for (f <- join; a <- rule) yield f(_ : B, a))
+  }
+  
+  /** Repeats this rule one or more times with a separator (which is discarded) */
+  def +/[X2 >: X](sep : => Rule[S, S, Any, X2]) = rule ~++ (sep -~ rule *)
+
+  /** Repeats this rule zero or more times with a separator (which is discarded) */
+  def */[X2 >: X](sep : => Rule[S, S, Any, X2]) = +/(sep) | state[S].nil
+  
+  def *~-[Out, X2 >: X](end : => Rule[S, Out, Any, X2]) = (rule - end *) ~- end
+  def +~-[Out, X2 >: X](end : => Rule[S, Out, Any, X2]) = (rule - end +) ~- end
+
+  /** Repeats this rule num times */
+  def times(num : Int) : Rule[S, S, Seq[A], X] = from[S] { 
+    val result = new collection.mutable.ArraySeq[A](num)
+    // more compact using HoF but written this way so it's tail-recursive
+    def rep(i : Int, in : S) : Result[S, Seq[A], X] = {
+      if (i == num) Success(in, result)
+      else rule(in) match {
+       case Success(out, a) => {
+         result(i) = a
+         rep(i + 1, out)
+       }
+       case Failure => Failure
+       case err : Error[_] => err
+      }
+    }
+    in => rep(0, in)
+  }
+}
+
diff --git a/src/scalap/scala/tools/scalap/scalax/rules/scalasig/ClassFileParser.scala b/src/scalap/scala/tools/scalap/scalax/rules/scalasig/ClassFileParser.scala
new file mode 100644
index 0000000..ed63923
--- /dev/null
+++ b/src/scalap/scala/tools/scalap/scalax/rules/scalasig/ClassFileParser.scala
@@ -0,0 +1,246 @@
+package scala.tools.scalap
+package scalax
+package rules
+package scalasig
+
+
+import java.io.IOException
+
+import scala._
+import scala.Predef._
+
+object ByteCode {
+  def apply(bytes : Array[Byte]) = new ByteCode(bytes, 0, bytes.length)
+
+  def forClass(clazz : Class[_]) = {
+    val name = clazz.getName
+    val subPath = name.substring(name.lastIndexOf('.') + 1) + ".class"
+    val in = clazz.getResourceAsStream(subPath)
+    
+    try {
+      var rest = in.available()
+      val bytes = new Array[Byte](rest)
+      while (rest > 0) {
+        val res = in.read(bytes, bytes.length - rest, rest)
+        if (res == -1) throw new IOException("read error")
+        rest -= res
+      }
+      ByteCode(bytes)
+      
+    } finally { 
+      in.close() 
+    }
+  }
+}
+
+/** Represents a chunk of raw bytecode.  Used as input for the parsers
+ */
+class ByteCode(val bytes : Array[Byte], val pos : Int, val length : Int) {
+  
+  assert(pos >= 0 && length >= 0 && pos + length <= bytes.length)
+  
+  def nextByte = if (length == 0) Failure else Success(drop(1), bytes(pos))
+  def next(n : Int) = if (length >= n) Success(drop(n), take(n)) else Failure
+  
+  def take(n : Int) = new ByteCode(bytes, pos, n)
+  def drop(n : Int) = new ByteCode(bytes, pos + n, length - n)
+  
+  def fold[X](x : X)(f : (X, Byte) => X) : X = {
+    var result = x
+    var i = pos
+    while (i < pos + length) {
+      result = f(result, bytes(i))
+      i += 1
+    }
+    result
+  }
+  
+  override def toString = length + " bytes"
+
+  def toInt = fold(0) { (x, b) => (x << 8) + (b & 0xFF)}
+  def toLong = fold(0L) { (x, b) => (x << 8) + (b & 0xFF)}
+
+  /**
+   * Transforms array subsequence of the current buffer into the UTF8 String and
+   * stores and array of bytes for the decompiler
+   */
+  def toUTF8StringAndBytes = {
+    val chunk: Array[Byte] = bytes drop pos take length
+    StringBytesPair(io.Codec.toUTF8(chunk).mkString, chunk)
+  }
+
+  def byte(i : Int) = bytes(pos) & 0xFF
+}
+
+/**
+ * The wrapper for decode UTF-8 string
+ */
+case class StringBytesPair(string: String, bytes: Array[Byte])
+
+/** Provides rules for parsing byte-code.
+*/
+trait ByteCodeReader extends RulesWithState {
+  type S = ByteCode
+  type Parser[A] = Rule[A, String]
+    
+  val byte = apply(_ nextByte)
+  
+  val u1 = byte ^^ (_ & 0xFF)
+  val u2 = bytes(2) ^^ (_ toInt)
+  val u4 = bytes(4) ^^ (_ toInt) // should map to Long??
+  
+  def bytes(n : Int) = apply(_ next n)  
+}
+
+object ClassFileParser extends ByteCodeReader {
+  def parse(byteCode : ByteCode) = expect(classFile)(byteCode)
+  def parseAnnotations(byteCode: ByteCode) = expect(annotations)(byteCode)
+  
+  val magicNumber = (u4 filter (_ == 0xCAFEBABE)) | error("Not a valid class file")
+  val version = u2 ~ u2 ^^ { case minor ~ major => (major,  minor) }
+  val constantPool = (u2 ^^ ConstantPool) >> repeatUntil(constantPoolEntry)(_ isFull)
+  
+  // NOTE currently most constants just evaluate to a string description
+  // TODO evaluate to useful values
+  val utf8String = (u2 >> bytes) ^^ add1 { raw => pool => raw.toUTF8StringAndBytes }
+  val intConstant = u4 ^^ add1 { x => pool => x }
+  val floatConstant = bytes(4) ^^ add1 { raw => pool => "Float: TODO" }
+  val longConstant = bytes(8) ^^ add2 { raw => pool => raw.toLong }
+  val doubleConstant = bytes(8) ^^ add2 { raw => pool => "Double: TODO" }
+  val classRef = u2 ^^ add1 { x => pool => "Class: " + pool(x) }
+  val stringRef = u2 ^^ add1 { x => pool => "String: " + pool(x) }
+  val fieldRef = memberRef("Field")
+  val methodRef = memberRef("Method")
+  val interfaceMethodRef = memberRef("InterfaceMethod")
+  val nameAndType = u2 ~ u2 ^^ add1 { case name ~ descriptor => pool => "NameAndType: " + pool(name) + ", " + pool(descriptor) }
+  
+  val constantPoolEntry = u1 >> {
+    case 1 => utf8String
+    case 3 => intConstant
+    case 4 => floatConstant
+    case 5 => longConstant
+    case 6 => doubleConstant
+    case 7 => classRef
+    case 8 => stringRef
+    case 9 => fieldRef
+    case 10 => methodRef
+    case 11 => interfaceMethodRef
+    case 12 => nameAndType
+  }
+  
+  val interfaces = u2 >> u2.times
+  
+  // bytes are parametrizes by the length, declared in u4 section
+  val attribute = u2 ~ (u4 >> bytes) ^~^ Attribute
+  // parse attributes u2 times
+  val attributes = u2 >> attribute.times
+
+  // parse runtime-visible annotations
+  abstract class ElementValue
+  case class AnnotationElement(elementNameIndex: Int, elementValue: ElementValue)
+  case class ConstValueIndex(index: Int) extends ElementValue
+  case class EnumConstValue(typeNameIndex: Int, constNameIndex: Int) extends ElementValue
+  case class ClassInfoIndex(index: Int) extends ElementValue
+  case class Annotation(typeIndex: Int, elementValuePairs: Seq[AnnotationElement]) extends ElementValue
+  case class ArrayValue(values: Seq[ElementValue]) extends ElementValue
+
+  def element_value: Parser[ElementValue] = u1 >> {
+    case 'B'|'C'|'D'|'F'|'I'|'J'|'S'|'Z'|'s' => u2 ^^ ConstValueIndex
+    case 'e' => u2 ~ u2 ^~^ EnumConstValue
+    case 'c' => u2 ^^ ClassInfoIndex
+    case '@' => annotation //nested annotation
+    case '[' => u2 >> element_value.times ^^ ArrayValue
+  }
+
+  val element_value_pair = u2 ~ element_value ^~^ AnnotationElement
+  val annotation: Parser[Annotation] = u2 ~ (u2 >> element_value_pair.times) ^~^ Annotation
+  val annotations = u2 >> annotation.times
+
+  val field = u2 ~ u2 ~ u2 ~ attributes ^~~~^ Field
+  val fields = u2 >> field.times
+  
+  val method = u2 ~ u2 ~ u2 ~ attributes ^~~~^ Method
+  val methods = u2 >> method.times
+  
+  val header = magicNumber -~ u2 ~ u2 ~ constantPool ~ u2 ~ u2 ~ u2 ~ interfaces ^~~~~~~^ ClassFileHeader
+  val classFile = header ~ fields ~ methods ~ attributes ~- !u1 ^~~~^ ClassFile 
+
+  // TODO create a useful object, not just a string
+  def memberRef(description : String) = u2 ~ u2 ^^ add1 {
+    case classRef ~ nameAndTypeRef => pool => description + ": " + pool(classRef) + ", " + pool(nameAndTypeRef)
+  }
+
+  def add1[T](f : T => ConstantPool => Any)(raw : T)(pool : ConstantPool) = pool add f(raw)
+  def add2[T](f : T => ConstantPool => Any)(raw : T)(pool : ConstantPool) = pool add f(raw) add { pool => "<empty>" }
+}
+
+case class ClassFile(
+    header : ClassFileHeader,
+    fields : Seq[Field],
+    methods : Seq[Method],
+    attributes : Seq[Attribute]) {
+  
+  def majorVersion = header.major
+  def minorVersion = header.minor
+  
+  def className = constant(header.classIndex)
+  def superClass = constant(header.superClassIndex)
+  def interfaces = header.interfaces.map(constant)
+    
+  def constant(index : Int) = header.constants(index) match {
+    case StringBytesPair(str, _) => str
+    case z => z
+  }
+
+  def constantWrapped(index: Int) = header.constants(index)
+    
+  def attribute(name : String) = attributes.find {attrib => constant(attrib.nameIndex) == name }
+
+  val RUNTIME_VISIBLE_ANNOTATIONS = "RuntimeVisibleAnnotations"
+  def annotations = (attributes.find(attr => constant(attr.nameIndex) == RUNTIME_VISIBLE_ANNOTATIONS)
+          .map(attr => ClassFileParser.parseAnnotations(attr.byteCode)))
+
+  def annotation(name: String) = annotations.flatMap(seq => seq.find(annot => constant(annot.typeIndex) == name))
+}
+  
+case class Attribute(nameIndex : Int, byteCode : ByteCode)
+case class Field(flags : Int, nameIndex : Int, descriptorIndex : Int, attributes : Seq[Attribute])
+case class Method(flags : Int, nameIndex : Int, descriptorIndex : Int, attributes : Seq[Attribute])
+  
+case class ClassFileHeader(
+    minor : Int, 
+    major : Int, 
+    constants : ConstantPool, 
+    flags : Int,
+    classIndex : Int,
+    superClassIndex : Int,
+    interfaces : Seq[Int]) {
+    
+  def constant(index : Int) = constants(index)
+}
+  
+case class ConstantPool(len : Int) {
+  val size = len - 1
+  
+  private val buffer = new scala.collection.mutable.ArrayBuffer[ConstantPool => Any]
+  private val values = Array.fill[Option[Any]](size)(None)
+    
+  def isFull = buffer.length >= size
+  
+  def apply(index : Int) = {
+    // Note constant pool indices are 1-based
+    val i = index - 1
+    values(i) getOrElse {
+      val value = buffer(i)(this)
+      buffer(i) = null
+      values(i) = Some(value)
+      value
+    }
+  }
+    
+  def add(f : ConstantPool => Any) = {
+    buffer += f
+    this
+  }
+}
+
diff --git a/src/scalap/scala/tools/scalap/scalax/rules/scalasig/Flags.scala b/src/scalap/scala/tools/scalap/scalax/rules/scalasig/Flags.scala
new file mode 100644
index 0000000..7bc4129
--- /dev/null
+++ b/src/scalap/scala/tools/scalap/scalax/rules/scalasig/Flags.scala
@@ -0,0 +1,69 @@
+package scala.tools.scalap
+package scalax
+package rules
+package scalasig
+
+trait Flags {
+  def hasFlag(flag : Long) : Boolean
+  
+  def isImplicit = hasFlag(0x00000001)
+  def isFinal = hasFlag(0x00000002)
+  def isPrivate = hasFlag(0x00000004)
+  def isProtected = hasFlag(0x00000008)
+    
+  def isSealed = hasFlag(0x00000010)
+  def isOverride = hasFlag(0x00000020)
+  def isCase = hasFlag(0x00000040)
+  def isAbstract = hasFlag(0x00000080)
+
+  def isDeferred = hasFlag(0x00000100)
+  def isMethod = hasFlag(0x00000200)
+  def isModule = hasFlag(0x00000400)
+  def isInterface = hasFlag(0x00000800)
+
+  def isMutable = hasFlag(0x00001000)
+  def isParam = hasFlag(0x00002000)
+  def isPackage = hasFlag(0x00004000)
+  def isDeprecated = hasFlag(0x00008000)
+
+  def isCovariant = hasFlag(0x00010000)
+  def isCaptured = hasFlag(0x00010000)
+
+  def isByNameParam = hasFlag(0x00010000)
+  def isContravariant = hasFlag(0x00020000)
+  def isLabel = hasFlag(0x00020000) // method symbol is a label. Set by TailCall
+  def isInConstructor = hasFlag(0x00020000) // class symbol is defined in this/superclass constructor
+
+  def isAbstractOverride = hasFlag(0x00040000)
+  def isLocal = hasFlag(0x00080000)
+
+  def isJava = hasFlag(0x00100000)
+  def isSynthetic = hasFlag(0x00200000)
+  def isStable = hasFlag(0x00400000)
+  def isStatic = hasFlag(0x00800000)
+
+  def isCaseAccessor = hasFlag(0x01000000)
+  def isTrait = hasFlag(0x02000000)
+  def isBridge = hasFlag(0x04000000)
+  def isAccessor = hasFlag(0x08000000)
+
+  def isSuperAccessor = hasFlag(0x10000000)
+  def isParamAccessor = hasFlag(0x20000000)
+
+  def isModuleVar = hasFlag(0x40000000) // for variables: is the variable caching a module value
+  def isSyntheticMethod = hasFlag(0x40000000) // for methods: synthetic method, but without SYNTHETIC flag
+  def isMonomorphic = hasFlag(0x40000000) // for type symbols: does not have type parameters
+  def isLazy = hasFlag(0x80000000L) // symbol is a lazy val. can't have MUTABLE unless transformed by typer
+
+  def isError = hasFlag(0x100000000L)
+  def isOverloaded = hasFlag(0x200000000L)
+  def isLifted = hasFlag(0x400000000L)
+
+  def isMixedIn = hasFlag(0x800000000L)
+  def isExistential = hasFlag(0x800000000L)
+
+  def isExpandedName = hasFlag(0x1000000000L)
+  def isImplementationClass = hasFlag(0x2000000000L)
+  def isPreSuper = hasFlag(0x2000000000L)
+
+}
diff --git a/src/scalap/scala/tools/scalap/scalax/rules/scalasig/ScalaSig.scala b/src/scalap/scala/tools/scalap/scalax/rules/scalasig/ScalaSig.scala
new file mode 100644
index 0000000..8acde2f
--- /dev/null
+++ b/src/scalap/scala/tools/scalap/scalax/rules/scalasig/ScalaSig.scala
@@ -0,0 +1,351 @@
+/*     ___ ____ ___   __   ___   ___
+**    / _// __// _ | / /  / _ | / _ \    Scala classfile decoder
+**  __\ \/ /__/ __ |/ /__/ __ |/ ___/    (c) 2003-2010, LAMP/EPFL
+** /____/\___/_/ |_/____/_/ |_/_/        http://scala-lang.org/
+**
+*/
+
+
+package scala.tools.scalap
+package scalax
+package rules
+package scalasig
+
+import ClassFileParser.{ ConstValueIndex, Annotation }
+import scala.reflect.generic.ByteCodecs
+
+object ScalaSigParser {
+  import Main.{ SCALA_SIG, SCALA_SIG_ANNOTATION, BYTES_VALUE }
+  
+  def scalaSigFromAnnotation(classFile: ClassFile): Option[ScalaSig] = {
+    import classFile._
+
+    classFile.annotation(SCALA_SIG_ANNOTATION) map {
+      case Annotation(_, elements) =>
+        val bytesElem = elements.find(elem => constant(elem.elementNameIndex) == BYTES_VALUE).get
+        val bytes = ((bytesElem.elementValue match {case ConstValueIndex(index) => constantWrapped(index)})
+                .asInstanceOf[StringBytesPair].bytes)
+        val length = ByteCodecs.decode(bytes)
+        
+        ScalaSigAttributeParsers.parse(ByteCode(bytes.take(length)))
+    }
+  }
+
+  def scalaSigFromAttribute(classFile: ClassFile) : Option[ScalaSig] =
+    classFile.attribute(SCALA_SIG).map(_.byteCode).map(ScalaSigAttributeParsers.parse)
+  
+  def parse(classFile: ClassFile): Option[ScalaSig] = {
+    val scalaSig  = scalaSigFromAttribute(classFile)
+    
+    scalaSig match {
+      // No entries in ScalaSig attribute implies that the signature is stored in the annotation
+      case Some(ScalaSig(_, _, entries)) if entries.length == 0 =>
+        scalaSigFromAnnotation(classFile)
+      case x => x
+    }
+  }
+    
+  def parse(clazz : Class[_]): Option[ScalaSig] = {
+    val byteCode  = ByteCode.forClass(clazz)
+    val classFile = ClassFileParser.parse(byteCode)
+
+    parse(classFile)
+  }
+}
+
+object ScalaSigAttributeParsers extends ByteCodeReader  {
+  def parse(byteCode : ByteCode) = expect(scalaSig)(byteCode)
+
+  val nat = apply {
+    def natN(in : ByteCode, x : Int) : Result[ByteCode, Int, Nothing] = in.nextByte match {
+      case Success(out, b) => {
+        val y = (x << 7) + (b & 0x7f)
+        if ((b & 0x80) == 0) Success(out, y) else natN(out, y)
+      }
+      case _ => Failure
+    }
+    in => natN(in, 0)
+  }
+
+  val rawBytes = nat >> bytes
+  val entry = nat ~ rawBytes
+  val symtab = nat >> entry.times
+  val scalaSig = nat ~ nat ~ symtab ^~~^ ScalaSig
+
+  val utf8 = read(x => x.toUTF8StringAndBytes.string)
+  val longValue = read(_ toLong)
+}
+
+case class ScalaSig(majorVersion : Int, minorVersion : Int, table : Seq[Int ~ ByteCode]) extends DefaultMemoisable {
+
+  case class Entry(index : Int, entryType : Int, byteCode : ByteCode) extends DefaultMemoisable {
+    def scalaSig = ScalaSig.this
+
+    def setByteCode(byteCode : ByteCode) = Entry(index, entryType, byteCode)
+  }
+
+  def hasEntry(index : Int) = table isDefinedAt index
+
+  def getEntry(index : Int) = {
+    val entryType ~ byteCode = table(index)
+    Entry(index, entryType, byteCode)
+  }
+
+  def parseEntry(index : Int) = applyRule(ScalaSigParsers.parseEntry(ScalaSigEntryParsers.entry)(index))
+
+  implicit def applyRule[A](parser : ScalaSigParsers.Parser[A]) = ScalaSigParsers.expect(parser)(this)
+
+  override def toString = "ScalaSig version " + majorVersion + "." + minorVersion + {
+    for (i <- 0 until table.size) yield i + ":\t" + parseEntry(i) // + "\n\t" + getEntry(i)
+  }.mkString("\n", "\n", "")
+
+  lazy val symbols : Seq[Symbol] = ScalaSigParsers.symbols
+
+  lazy val topLevelClasses : List[ClassSymbol] = ScalaSigParsers.topLevelClasses
+  lazy val topLevelObjects : List[ObjectSymbol] = ScalaSigParsers.topLevelObjects
+}
+
+object ScalaSigParsers extends RulesWithState with MemoisableRules {
+  type S = ScalaSig
+  type Parser[A] = Rule[A, String]
+
+  val symTab = read(_.table)
+  val size = symTab ^^ (_.size)
+
+  def entry(index : Int) = memo(("entry", index)) {
+    cond(_ hasEntry index) -~ read(_ getEntry index) >-> { entry => Success(entry, entry.entryType) }
+  }
+
+  def parseEntry[A](parser : ScalaSigEntryParsers.EntryParser[A])(index : Int) : Parser[A] =
+    entry(index) -~ parser >> { a => entry => Success(entry.scalaSig, a) }
+
+  def allEntries[A](f : ScalaSigEntryParsers.EntryParser[A]) = size >> { n => anyOf((0 until n) map parseEntry(f)) }
+
+  lazy val entries = allEntries(ScalaSigEntryParsers.entry) as "entries"
+  lazy val symbols = allEntries(ScalaSigEntryParsers.symbol) as "symbols"
+  lazy val methods = allEntries(ScalaSigEntryParsers.methodSymbol) as "methods"
+  lazy val attributes = allEntries(ScalaSigEntryParsers.attributeInfo) as "attributes"
+
+  lazy val topLevelClasses = allEntries(ScalaSigEntryParsers.topLevelClass)
+  lazy val topLevelObjects = allEntries(ScalaSigEntryParsers.topLevelObject)
+}
+
+object ScalaSigEntryParsers extends RulesWithState with MemoisableRules {
+  import ScalaSigAttributeParsers.{nat, utf8, longValue}
+
+  type S = ScalaSig#Entry
+  type EntryParser[A] = Rule[A, String]
+
+  implicit def byteCodeEntryParser[A](rule : ScalaSigAttributeParsers.Parser[A]) : EntryParser[A] = apply { entry =>
+    rule(entry.byteCode) mapOut (entry setByteCode _)
+  }
+
+  def toEntry[A](index : Int) = apply { sigEntry => ScalaSigParsers.entry(index)(sigEntry.scalaSig) }
+
+  def parseEntry[A](parser : EntryParser[A])(index : Int) = (toEntry(index) -~ parser)
+
+  implicit def entryType(code : Int) = key filter (_ == code)
+
+  val index = read(_.index)
+  val key = read(_.entryType)
+
+  lazy val entry : EntryParser[Any] = symbol | typeEntry | literal | name | attributeInfo | annotInfo | children | get
+
+  val ref = byteCodeEntryParser(nat)
+
+  val termName = 1 -~ utf8
+  val typeName = 2 -~ utf8
+
+  val name = termName | typeName as "name"
+
+  def refTo[A](rule : EntryParser[A]) : EntryParser[A] = ref >>& parseEntry(rule)
+
+  lazy val nameRef = refTo(name)
+  lazy val symbolRef = refTo(symbol)
+  lazy val typeRef = refTo(typeEntry)
+  lazy val constantRef = refTo(literal)
+
+  val symbolInfo = nameRef ~ symbolRef ~ nat ~ (symbolRef?) ~ ref ~ get ^~~~~~^ SymbolInfo
+
+  def symHeader(key: Int) = (key -~ none | (key + 64) -~ nat)
+
+  def symbolEntry(key : Int) = symHeader(key) -~ symbolInfo
+
+  /***************************************************
+   * Symbol table attribute format:
+   *   Symtab         = nentries_Nat {Entry}
+   *   Entry          = 1 TERMNAME len_Nat NameInfo
+   *                  | 2 TYPENAME len_Nat NameInfo
+   *                  | 3 NONEsym len_Nat
+   *                  | 4 TYPEsym len_Nat SymbolInfo
+   *                  | 5 ALIASsym len_Nat SymbolInfo
+   *                  | 6 CLASSsym len_Nat SymbolInfo [thistype_Ref]
+   *                  | 7 MODULEsym len_Nat SymbolInfo
+   *                  | 8 VALsym len_Nat [defaultGetter_Ref /* no longer needed*/] SymbolInfo [alias_Ref]
+   *                  | 9 EXTref len_Nat name_Ref [owner_Ref]
+   *                  | 10 EXTMODCLASSref len_Nat name_Ref [owner_Ref]
+   *                  | 11 NOtpe len_Nat
+   *                  | 12 NOPREFIXtpe len_Nat
+   *                  | 13 THIStpe len_Nat sym_Ref
+   *                  | 14 SINGLEtpe len_Nat type_Ref sym_Ref
+   *                  | 15 CONSTANTtpe len_Nat constant_Ref
+   *                  | 16 TYPEREFtpe len_Nat type_Ref sym_Ref {targ_Ref}
+   *                  | 17 TYPEBOUNDStpe len_Nat tpe_Ref tpe_Ref
+   *                  | 18 REFINEDtpe len_Nat classsym_Ref {tpe_Ref}
+   *                  | 19 CLASSINFOtpe len_Nat classsym_Ref {tpe_Ref}
+   *                  | 20 METHODtpe len_Nat tpe_Ref {sym_Ref}
+   *                  | 21 POLYTtpe len_Nat tpe_Ref {sym_Ref}
+   *                  | 22 IMPLICITMETHODtpe len_Nat tpe_Ref {sym_Ref} /* no longer needed */
+   *                  | 52 SUPERtpe len_Nat tpe_Ref tpe_Ref
+   *                  | 24 LITERALunit len_Nat
+   *                  | 25 LITERALboolean len_Nat value_Long
+   *                  | 26 LITERALbyte len_Nat value_Long
+   *                  | 27 LITERALshort len_Nat value_Long
+   *                  | 28 LITERALchar len_Nat value_Long
+   *                  | 29 LITERALint len_Nat value_Long
+   *                  | 30 LITERALlong len_Nat value_Long
+   *                  | 31 LITERALfloat len_Nat value_Long
+   *                  | 32 LITERALdouble len_Nat value_Long
+   *                  | 33 LITERALstring len_Nat name_Ref
+   *                  | 34 LITERALnull len_Nat
+   *                  | 35 LITERALclass len_Nat tpe_Ref
+   *                  | 36 LITERALenum len_Nat sym_Ref
+   *                  | 40 SYMANNOT len_Nat sym_Ref AnnotInfoBody
+   *                  | 41 CHILDREN len_Nat sym_Ref {sym_Ref}
+   *                  | 42 ANNOTATEDtpe len_Nat [sym_Ref /* no longer needed */] tpe_Ref {annotinfo_Ref}
+   *                  | 43 ANNOTINFO len_Nat AnnotInfoBody
+   *                  | 44 ANNOTARGARRAY len_Nat {constAnnotArg_Ref}
+   *                  | 47 DEBRUIJNINDEXtpe len_Nat level_Nat index_Nat
+   *                  | 48 EXISTENTIALtpe len_Nat type_Ref {symbol_Ref}
+   */
+  val noSymbol = 3 -^ NoSymbol
+  val typeSymbol = symbolEntry(4) ^^ TypeSymbol as "typeSymbol"
+  val aliasSymbol = symbolEntry(5) ^^ AliasSymbol as "alias"
+  val classSymbol = symbolEntry(6) ~ (ref?) ^~^ ClassSymbol as "class"
+  val objectSymbol = symbolEntry(7) ^^ ObjectSymbol as "object"
+  val methodSymbol = symHeader(8) -~ /*(ref?) -~*/ symbolInfo ~ (ref?) ^~^ MethodSymbol as "method"
+  val extRef = 9 -~ nameRef ~ (symbolRef?) ~ get ^~~^ ExternalSymbol as "extRef"
+  val extModClassRef = 10 -~ nameRef ~ (symbolRef?) ~ get ^~~^ ExternalSymbol as "extModClassRef"
+
+  lazy val symbol : EntryParser[Symbol] = oneOf(
+      noSymbol,
+      typeSymbol,
+      aliasSymbol,
+      classSymbol,
+      objectSymbol,
+      methodSymbol,
+      extRef,
+      extModClassRef) as "symbol"
+
+  val classSymRef = refTo(classSymbol)
+  val attribTreeRef = ref
+  val typeLevel = nat
+  val typeIndex = nat
+
+  lazy val typeEntry : EntryParser[Type] = oneOf(
+      11 -^ NoType,
+      12 -^ NoPrefixType,
+      13 -~ symbolRef ^^ ThisType,
+      14 -~ typeRef ~ symbolRef ^~^ SingleType,
+      15 -~ constantRef ^^ ConstantType,
+      16 -~ typeRef ~ symbolRef ~ (typeRef*) ^~~^ TypeRefType,
+      17 -~ typeRef ~ typeRef ^~^ TypeBoundsType,
+      18 -~ classSymRef ~ (typeRef*) ^~^ RefinedType,
+      19 -~ symbolRef ~ (typeRef*) ^~^ ClassInfoType,
+      20 -~ typeRef ~ (symbolRef*) ^~^ MethodType,
+      21 -~ typeRef ~ (refTo(typeSymbol)*) ^~^ PolyType,
+      22 -~ typeRef ~ (symbolRef*) ^~^ ImplicitMethodType,
+      42 -~ typeRef ~ (attribTreeRef*) ^~^ AnnotatedType,
+      51 -~ typeRef ~ symbolRef ~ (attribTreeRef*) ^~~^ AnnotatedWithSelfType,
+      47 -~ typeLevel ~ typeIndex ^~^ DeBruijnIndexType,
+      48 -~ typeRef ~ (symbolRef*) ^~^ ExistentialType) as "type"
+
+  lazy val literal = oneOf(
+      24 -^ (),
+      25 -~ longValue ^^ (_ != 0L),
+      26 -~ longValue ^^ (_.toByte),
+      27 -~ longValue ^^ (_.toShort),
+      28 -~ longValue ^^ (_.toChar),
+      29 -~ longValue ^^ (_.toInt),
+      30 -~ longValue ^^ (_.toLong),
+      31 -~ longValue ^^ (l => java.lang.Float.intBitsToFloat(l.toInt)),
+      32 -~ longValue ^^ (java.lang.Double.longBitsToDouble),
+      33 -~ nameRef,
+      34 -^ null,
+      35 -~ typeRef)
+
+  lazy val attributeInfo = 40 -~ symbolRef ~ typeRef ~ (constantRef?) ~ (nameRef ~ constantRef *) ^~~~^ AttributeInfo // sym_Ref info_Ref {constant_Ref} {nameRef constantRef}
+  lazy val children = 41 -~ (nat*) ^^ Children //sym_Ref {sym_Ref}
+  lazy val annotInfo = 43 -~ (nat*) ^^ AnnotInfo // attarg_Ref {constant_Ref attarg_Ref}
+
+  lazy val topLevelClass = classSymbol filter isTopLevelClass
+  lazy val topLevelObject = objectSymbol filter isTopLevel
+
+  def isTopLevel(symbol : Symbol) = symbol.parent match {
+    case Some(ext : ExternalSymbol) => true
+    case _ => false
+  }
+  def isTopLevelClass (symbol : Symbol) = !symbol.isModule && isTopLevel(symbol)
+}
+
+  case class AttributeInfo(symbol : Symbol, typeRef : Type, value : Option[Any], values : Seq[String ~ Any]) // sym_Ref info_Ref {constant_Ref} {nameRef constantRef}
+  case class Children(symbolRefs : Seq[Int]) //sym_Ref {sym_Ref}
+
+  case class AnnotInfo(refs : Seq[Int]) // attarg_Ref {constant_Ref attarg_Ref}
+
+  /***************************************************
+   *                  | 49 TREE len_Nat 1 EMPTYtree
+   *                  | 49 TREE len_Nat 2 PACKAGEtree type_Ref sym_Ref mods_Ref name_Ref {tree_Ref}
+   *                  | 49 TREE len_Nat 3 CLASStree type_Ref sym_Ref mods_Ref name_Ref tree_Ref {tree_Ref}
+   *                  | 49 TREE len_Nat 4 MODULEtree type_Ref sym_Ref mods_Ref name_Ref tree_Ref
+   *                  | 49 TREE len_Nat 5 VALDEFtree type_Ref sym_Ref mods_Ref name_Ref tree_Ref tree_Ref
+   *                  | 49 TREE len_Nat 6 DEFDEFtree type_Ref sym_Ref mods_Ref name_Ref numtparams_Nat {tree_Ref} numparamss_Nat {numparams_Nat {tree_Ref}} tree_Ref tree_Ref
+   *                  | 49 TREE len_Nat 7 TYPEDEFtree type_Ref sym_Ref mods_Ref name_Ref tree_Ref {tree_Ref}
+   *                  | 49 TREE len_Nat 8 LABELtree type_Ref sym_Ref tree_Ref {tree_Ref}
+   *                  | 49 TREE len_Nat 9 IMPORTtree type_Ref sym_Ref tree_Ref {name_Ref name_Ref}
+   *                  | 49 TREE len_Nat 11 DOCDEFtree type_Ref sym_Ref string_Ref tree_Ref
+   *                  | 49 TREE len_Nat 12 TEMPLATEtree type_Ref sym_Ref numparents_Nat {tree_Ref} tree_Ref {tree_Ref}
+   *                  | 49 TREE len_Nat 13 BLOCKtree type_Ref tree_Ref {tree_Ref}
+   *                  | 49 TREE len_Nat 14 CASEtree type_Ref tree_Ref tree_Ref tree_Ref
+   *                  | 49 TREE len_Nat 15 SEQUENCEtree type_Ref {tree_Ref}
+   *                  | 49 TREE len_Nat 16 ALTERNATIVEtree type_Ref {tree_Ref}
+   *                  | 49 TREE len_Nat 17 STARtree type_Ref {tree_Ref}
+   *                  | 49 TREE len_Nat 18 BINDtree type_Ref sym_Ref name_Ref tree_Ref
+   *                  | 49 TREE len_Nat 19 UNAPPLYtree type_Ref tree_Ref {tree_Ref}
+   *                  | 49 TREE len_Nat 20 ARRAYVALUEtree type_Ref tree_Ref {tree_Ref}
+   *                  | 49 TREE len_Nat 21 FUNCTIONtree type_Ref sym_Ref tree_Ref {tree_Ref}
+   *                  | 49 TREE len_Nat 22 ASSIGNtree type_Ref tree_Ref tree_Ref
+   *                  | 49 TREE len_Nat 23 IFtree type_Ref tree_Ref tree_Ref tree_Ref
+   *                  | 49 TREE len_Nat 24 MATCHtree type_Ref tree_Ref {tree_Ref}
+   *                  | 49 TREE len_Nat 25 RETURNtree type_Ref sym_Ref tree_Ref
+   *                  | 49 TREE len_Nat 26 TREtree type_Ref tree_Ref tree_Ref {tree_Ref}
+   *                  | 49 TREE len_Nat 27 THROWtree type_Ref tree_Ref
+   *                  | 49 TREE len_Nat 28 NEWtree type_Ref tree_Ref
+   *                  | 49 TREE len_Nat 29 TYPEDtree type_Ref tree_Ref tree_Ref
+   *                  | 49 TREE len_Nat 30 TYPEAPPLYtree type_Ref tree_Ref {tree_Ref}
+   *                  | 49 TREE len_Nat 31 APPLYtree type_Ref tree_Ref {tree_Ref}
+   *                  | 49 TREE len_Nat 32 APPLYDYNAMICtree type_Ref sym_Ref tree_Ref {tree_Ref}
+   *                  | 49 TREE len_Nat 33 SUPERtree type_Ref sym_Ref tree_Ref name_Ref
+   *                  | 49 TREE len_Nat 34 THIStree type_Ref sym_Ref  name_Ref
+   *                  | 49 TREE len_Nat 35 SELECTtree type_Ref sym_Ref tree_Ref name_Ref
+   *                  | 49 TREE len_Nat 36 IDENTtree type_Ref sym_Ref name_Ref
+   *                  | 49 TREE len_Nat 37 LITERALtree type_Ref constant_Ref
+   *                  | 49 TREE len_Nat 38 TYPEtree type_Ref
+   *                  | 49 TREE len_Nat 39 ANNOTATEDtree type_Ref tree_Ref tree_Ref
+   *                  | 49 TREE len_Nat 40 SINGLETONTYPEtree type_Ref tree_Ref
+   *                  | 49 TREE len_Nat 41 SELECTFROMTYPEtree type_Ref tree_Ref name_Ref
+   *                  | 49 TREE len_Nat 42 COMPOUNDTYPEtree type_Ref tree_Ref
+   *                  | 49 TREE len_Nat 43 APPLIEDTYPEtree type_Ref tree_Ref {tree_Ref}
+   *                  | 49 TREE len_Nat 44 TYPEBOUNDStree type_Ref tree_Ref tree_Ref
+   *                  | 49 TREE len_Nat 45 EXISTENTIALTYPEtree type_Ref tree_Ref {tree_Ref}
+   *                  | 50 MODIFIERS len_Nat flags_Long privateWithin_Ref
+   *   SymbolInfo     = name_Ref owner_Ref flags_LongNat [privateWithin_Ref] info_Ref
+   *   NameInfo       = <character sequence of length len_Nat in Utf8 format>
+   *   NumInfo        = <len_Nat-byte signed number in big endian format>
+   *   Ref            = Nat
+   *   AnnotInfoBody  = info_Ref {annotArg_Ref} {name_Ref constAnnotArg_Ref}
+   *   AnnotArg       = Tree | Constant
+   *   ConstAnnotArg  = Constant | AnnotInfo | AnnotArgArray
+   *
+   *   len is remaining length after `len'.
+   */
diff --git a/src/scalap/scala/tools/scalap/scalax/rules/scalasig/ScalaSigPrinter.scala b/src/scalap/scala/tools/scalap/scalax/rules/scalasig/ScalaSigPrinter.scala
new file mode 100644
index 0000000..915087a
--- /dev/null
+++ b/src/scalap/scala/tools/scalap/scalax/rules/scalasig/ScalaSigPrinter.scala
@@ -0,0 +1,440 @@
+/*     ___ ____ ___   __   ___   ___
+**    / _// __// _ | / /  / _ | / _ \  Scala classfile decoder
+**  __\ \/ /__/ __ |/ /__/ __ |/ ___/  (c) 2003-2010, LAMP/EPFL
+** /____/\___/_/ |_/____/_/ |_/_/      http://scala-lang.org/
+**
+*/
+
+
+package scala.tools.scalap
+package scalax
+package rules
+package scalasig
+
+import java.io.{PrintStream, ByteArrayOutputStream}
+import java.util.regex.Pattern
+
+import scala.tools.scalap.scalax.util.StringUtil
+import reflect.NameTransformer
+import java.lang.String
+
+class ScalaSigPrinter(stream: PrintStream, printPrivates: Boolean) {
+  import stream._
+
+  val CONSTRUCTOR_NAME = "<init>"
+
+  case class TypeFlags(printRep: Boolean)
+
+  def printSymbol(symbol: Symbol) {printSymbol(0, symbol)}
+
+  def printSymbolAttributes(s: Symbol, onNewLine: Boolean, indent: => Unit) = s match {
+    case t: SymbolInfoSymbol => {
+      for (a <- t.attributes) {
+        indent; print(toString(a))
+        if (onNewLine) print("\n") else print(" ")
+      }
+    }
+    case _ =>
+  }
+
+  def printSymbol(level: Int, symbol: Symbol) {
+    if (!symbol.isLocal &&
+            !(symbol.isPrivate && !printPrivates)) {
+      def indent() {for (i <- 1 to level) print("  ")}
+
+      printSymbolAttributes(symbol, true, indent)
+      symbol match {
+        case o: ObjectSymbol =>
+          if (!isCaseClassObject(o)) {
+            indent
+            if (o.name == "package") {
+              // print package object
+              printPackageObject(level, o)
+            } else {
+              printObject(level, o)
+            }
+          }
+        case c: ClassSymbol if !refinementClass(c) && !c.isModule =>
+          indent
+          printClass(level, c)
+        case m: MethodSymbol =>
+          printMethod(level, m, indent)
+        case a: AliasSymbol =>
+          indent
+          printAlias(level, a)
+        case t: TypeSymbol if !t.isParam && !t.name.matches("_\\$\\d+")=>
+          indent
+          printTypeSymbol(level, t)
+        case s =>
+      }
+    }
+  }
+
+  def isCaseClassObject(o: ObjectSymbol): Boolean = {
+    val TypeRefType(prefix, classSymbol: ClassSymbol, typeArgs) = o.infoType
+    o.isFinal && (classSymbol.children.find(x => x.isCase && x.isInstanceOf[MethodSymbol]) match {
+      case Some(_) => true
+      case None => false
+    })
+  }
+
+  private def underCaseClass(m: MethodSymbol) = m.parent match {
+    case Some(c: ClassSymbol) => c.isCase
+    case _ => false
+  }
+
+
+  private def printChildren(level: Int, symbol: Symbol) {
+    for (child <- symbol.children) printSymbol(level + 1, child)
+  }
+
+  def printWithIndent(level: Int, s: String) {
+    def indent() {for (i <- 1 to level) print("  ")}
+    indent;
+    print(s)
+  }
+
+  def printModifiers(symbol: Symbol) {
+    // print private access modifier
+    if (symbol.isPrivate) print("private ")
+    else if (symbol.isProtected) print("protected ")
+    else symbol match {
+      case sym: SymbolInfoSymbol => sym.symbolInfo.privateWithin match {
+        case Some(t: Symbol) => print("private[" + t.name +"] ")
+        case _ =>
+      }
+      case _ =>
+    }
+
+    if (symbol.isSealed) print("sealed ")
+    if (symbol.isImplicit) print("implicit ")
+    if (symbol.isFinal && !symbol.isInstanceOf[ObjectSymbol]) print("final ")
+    if (symbol.isOverride) print("override ")
+    if (symbol.isAbstract) symbol match {
+      case c@(_: ClassSymbol | _: ObjectSymbol) if !c.isTrait => print("abstract ")
+      case _ => ()
+    }
+    if (symbol.isCase && !symbol.isMethod) print("case ")
+  }
+
+  private def refinementClass(c: ClassSymbol) = c.name == "<refinement>"
+
+  def printClass(level: Int, c: ClassSymbol) {
+    if (c.name == "<local child>" /*scala.tools.nsc.symtab.StdNames.LOCALCHILD.toString()*/ ) {
+      print("\n")
+    } else {
+      printModifiers(c)
+      val defaultConstructor = if (c.isCase) getPrinterByConstructor(c) else ""
+      if (c.isTrait) print("trait ") else print("class ")
+      print(processName(c.name))
+      val it = c.infoType
+      val classType = it match {
+        case PolyType(typeRef, symbols) => PolyTypeWithCons(typeRef, symbols, defaultConstructor)
+        case ClassInfoType(a, b) if c.isCase => ClassInfoTypeWithCons(a, b, defaultConstructor)
+        case _ => it
+      }
+      printType(classType)
+      print(" {")
+      //Print class selftype
+      c.selfType match {
+        case Some(t: Type) => print("\n"); print(" this : " + toString(t) + " =>")
+        case None =>
+      }
+      print("\n")
+      printChildren(level, c)
+      printWithIndent(level, "}\n")
+    }
+  }
+
+  def getPrinterByConstructor(c: ClassSymbol) = {
+    c.children.find {
+      case m: MethodSymbol if m.name == CONSTRUCTOR_NAME => true
+      case _ => false
+    } match {
+      case Some(m: MethodSymbol) =>
+        val baos = new ByteArrayOutputStream
+        val stream = new PrintStream(baos)
+        val printer = new ScalaSigPrinter(stream, printPrivates)
+        printer.printMethodType(m.infoType, false)(())
+        baos.toString
+      case None =>
+        ""
+    }
+  }
+
+  def printPackageObject(level: Int, o: ObjectSymbol) {
+    printModifiers(o)
+    print("package ")
+    print("object ")
+    val poName = o.symbolInfo.owner.name
+    print(processName(poName))
+    val TypeRefType(prefix, classSymbol: ClassSymbol, typeArgs) = o.infoType
+    printType(classSymbol)
+    print(" {\n")
+    printChildren(level, classSymbol)
+    printWithIndent(level, "}\n")
+
+  }
+
+  def printObject(level: Int, o: ObjectSymbol) {
+    printModifiers(o)
+    print("object ")
+    print(processName(o.name))
+    val TypeRefType(prefix, classSymbol: ClassSymbol, typeArgs) = o.infoType
+    printType(classSymbol)
+    print(" {\n")
+    printChildren(level, classSymbol)
+    printWithIndent(level, "}\n")
+  }
+
+  def genParamNames(t: {def paramTypes: Seq[Type]}): List[String] = t.paramTypes.toList.map(x => {
+    var str = toString(x)
+    val j = str.indexOf("[")
+    if (j > 0) str = str.substring(0, j)
+    str = StringUtil.trimStart(str, "=> ")
+    var i = str.lastIndexOf(".")
+    val res = if (i > 0) str.substring(i + 1) else str
+    if (res.length > 1) StringUtil.decapitalize(res.substring(0, 1)) else res.toLowerCase
+  })
+
+  def printMethodType(t: Type, printResult: Boolean)(cont: => Unit): Unit = {
+
+    def _pmt(mt: Type {def resultType: Type; def paramSymbols: Seq[Symbol]}) = {
+
+      val paramEntries = mt.paramSymbols.map({
+        case ms: MethodSymbol => ms.name + " : " + toString(ms.infoType)(TypeFlags(true))
+        case _ => "^___^"
+      })
+
+      // Print parameter clauses
+      print(paramEntries.mkString(
+        "(" + (mt match {case _: ImplicitMethodType => "implicit "; case _ => ""})
+        , ", ", ")"))
+
+      // Print result type
+      mt.resultType match {
+        case mt: MethodType => printMethodType(mt, printResult)({})
+        case imt: ImplicitMethodType => printMethodType(imt, printResult)({})
+        case x => if (printResult) {
+          print(" : ");
+          printType(x)
+        }
+      }
+    }
+
+    t match {
+      case mt at MethodType(resType, paramSymbols) => _pmt(mt)
+      case mt at ImplicitMethodType(resType, paramSymbols) => _pmt(mt)
+      case pt at PolyType(mt, typeParams) => {
+        print(typeParamString(typeParams))
+        printMethodType(mt, printResult)({})
+      }
+      //todo consider another method types
+      case x => print(" : "); printType(x)
+    }
+
+    // Print rest of the symbol output
+    cont
+  }
+
+  def printMethod(level: Int, m: MethodSymbol, indent: () => Unit) {
+    def cont = print(" = { /* compiled code */ }")
+
+    val n = m.name
+    if (underCaseClass(m) && n == CONSTRUCTOR_NAME) return
+    if (n.matches(".+\\$default\\$\\d+")) return // skip default function parameters
+    if (n.startsWith("super$")) return // do not print auxiliary qualified super accessors
+    if (m.isAccessor && n.endsWith("_$eq")) return
+    indent()
+    printModifiers(m)
+    if (m.isAccessor) {
+      val indexOfSetter = m.parent.get.children.indexWhere(x => x.isInstanceOf[MethodSymbol] &&
+              x.asInstanceOf[MethodSymbol].name == n + "_$eq")
+      print(if (indexOfSetter > 0) "var " else "val ")
+    } else {
+      print("def ")
+    }
+    n match {
+      case CONSTRUCTOR_NAME =>
+        print("this")
+        printMethodType(m.infoType, false)(cont)
+      case name =>
+        val nn = processName(name)
+        print(nn)
+        printMethodType(m.infoType, true)(
+          {if (!m.isDeferred) print(" = { /* compiled code */ }" /* Print body only for non-abstract methods */ )}
+          )
+    }
+    print("\n")
+  }
+
+  def printAlias(level: Int, a: AliasSymbol) {
+    print("type ")
+    print(processName(a.name))
+    printType(a.infoType, " = ")
+    print("\n")
+    printChildren(level, a)
+  }
+
+  def printTypeSymbol(level: Int, t: TypeSymbol) {
+    print("type ")
+    print(processName(t.name))
+    printType(t.infoType)
+    print("\n")
+  }
+
+  def toString(attrib: AttributeInfo): String  = {
+    val buffer = new StringBuffer
+    buffer.append(toString(attrib.typeRef, "@"))
+    if (attrib.value.isDefined) {
+      buffer.append("(")
+      val value = attrib.value.get
+      val stringVal = value.isInstanceOf[String]
+      if (stringVal) buffer.append("\"")
+      val stringValue = valueToString(value)
+      val isMultiline = stringVal && (stringValue.contains("\n")
+              || stringValue.contains("\r"))
+      if (isMultiline) buffer.append("\"\"")
+      buffer.append(valueToString(value))
+      if (isMultiline) buffer.append("\"\"")
+      if (stringVal) buffer.append("\"")
+      buffer.append(")")
+    }
+    if (!attrib.values.isEmpty) {
+      buffer.append(" {")
+      for (name ~ value <- attrib.values) {
+        buffer.append(" val ")
+        buffer.append(processName(name))
+        buffer.append(" = ")
+        buffer.append(valueToString(value))
+      }
+      buffer.append(valueToString(attrib.value))
+      buffer.append(" }")
+    }
+    buffer.toString
+  }
+
+  def valueToString(value: Any): String = value match {
+    case t: Type => toString(t)
+    // TODO string, char, float, etc.
+    case _ => value.toString
+  }
+
+  implicit object _tf extends TypeFlags(false)
+
+  def printType(sym: SymbolInfoSymbol)(implicit flags: TypeFlags): Unit = printType(sym.infoType)(flags)
+
+  def printType(t: Type)(implicit flags: TypeFlags): Unit = print(toString(t)(flags))
+
+  def printType(t: Type, sep: String)(implicit flags: TypeFlags): Unit = print(toString(t, sep)(flags))
+
+  def toString(t: Type)(implicit flags: TypeFlags): String = toString(t, "")(flags)
+
+  def toString(t: Type, sep: String)(implicit flags: TypeFlags): String = {
+    // print type itself
+    t match {
+      case ThisType(symbol) => sep + processName(symbol.path) + ".type"
+      case SingleType(typeRef, symbol) => sep + processName(symbol.path) + ".type"
+      case ConstantType(constant) => sep + (constant match {
+        case null => "scala.Null"
+        case _: Unit => "scala.Unit"
+        case _: Boolean => "scala.Boolean"
+        case _: Byte => "scala.Byte"
+        case _: Char => "scala.Char"
+        case _: Short => "scala.Short"
+        case _: Int => "scala.Int"
+        case _: Long => "scala.Long"
+        case _: Float => "scala.Float"
+        case _: Double => "scala.Double"
+        case _: String => "java.lang.String"
+        case c: Class[_] => "java.lang.Class[" + c.getComponentType.getCanonicalName.replace("$", ".") + "]"
+      })
+      case TypeRefType(prefix, symbol, typeArgs) => sep + (symbol.path match {
+        case "scala.<repeated>" => flags match {
+          case TypeFlags(true) => toString(typeArgs.head) + "*"
+          case _ => "scala.Seq" + typeArgString(typeArgs)
+        }
+        case "scala.<byname>" => "=> " + toString(typeArgs.head)
+        case _ => {
+          val path = StringUtil.cutSubstring(symbol.path)(".package") //remove package object reference
+          StringUtil.trimStart(processName(path) + typeArgString(typeArgs), "<empty>.")
+        }
+      })
+      case TypeBoundsType(lower, upper) => {
+        val lb = toString(lower)
+        val ub = toString(upper)
+        val lbs = if (!lb.equals("scala.Nothing")) " >: " + lb else ""
+        val ubs = if (!ub.equals("scala.Any")) " <: " + ub else ""
+        lbs + ubs
+      }
+      case RefinedType(classSym, typeRefs) => sep + typeRefs.map(toString).mkString("", " with ", "")
+      case ClassInfoType(symbol, typeRefs) => sep + typeRefs.map(toString).mkString(" extends ", " with ", "")
+      case ClassInfoTypeWithCons(symbol, typeRefs, cons) => sep + typeRefs.map(toString).
+              mkString(cons + " extends ", " with ", "")
+
+      case ImplicitMethodType(resultType, _) => toString(resultType, sep)
+      case MethodType(resultType, _) => toString(resultType, sep)
+
+      case PolyType(typeRef, symbols) => typeParamString(symbols) + toString(typeRef, sep)
+      case PolyTypeWithCons(typeRef, symbols, cons) => typeParamString(symbols) + processName(cons) + toString(typeRef, sep)
+      case AnnotatedType(typeRef, attribTreeRefs) => {
+        toString(typeRef, sep)
+      }
+      case AnnotatedWithSelfType(typeRef, symbol, attribTreeRefs) => toString(typeRef, sep)
+      //case DeBruijnIndexType(typeLevel, typeIndex) =>
+      case ExistentialType(typeRef, symbols) => {
+        val refs = symbols.map(toString _).filter(!_.startsWith("_")).map("type " + _)
+        toString(typeRef, sep) + (if (refs.size > 0) refs.mkString(" forSome {", "; ", "}") else "")
+      }
+      case _ => sep + t.toString
+    }
+  }
+
+  def getVariance(t: TypeSymbol) = if (t.isCovariant) "+" else if (t.isContravariant) "-" else ""
+
+  def toString(symbol: Symbol): String = symbol match {
+    case symbol: TypeSymbol => {
+      val attrs = (for (a <- symbol.attributes) yield toString(a)).mkString(" ")
+      val atrs = if (attrs.length > 0) attrs.trim + " " else ""
+      atrs + getVariance(symbol) + processName(symbol.name) + toString(symbol.infoType)
+    }
+    case s => symbol.toString
+  }
+
+  def typeArgString(typeArgs: Seq[Type]): String =
+    if (typeArgs.isEmpty) ""
+    else typeArgs.map(toString).map(StringUtil.trimStart(_, "=> ")).mkString("[", ", ", "]")
+
+  def typeParamString(params: Seq[Symbol]): String =
+    if (params.isEmpty) ""
+    else params.map(toString).mkString("[", ", ", "]")
+
+  val _syms = Map("\\$bar" -> "|", "\\$tilde" -> "~",
+    "\\$bang" -> "!", "\\$up" -> "^", "\\$plus" -> "+",
+    "\\$minus" -> "-", "\\$eq" -> "=", "\\$less" -> "<",
+    "\\$times" -> "*", "\\$div" -> "/", "\\$bslash" -> "\\\\",
+    "\\$greater" -> ">", "\\$qmark" -> "?", "\\$percent" -> "%",
+    "\\$amp" -> "&", "\\$colon" -> ":", "\\$u2192" -> "→",
+    "\\$hash" -> "#")
+  val pattern = Pattern.compile(_syms.keys.foldLeft("")((x, y) => if (x == "") y else x + "|" + y))
+  val placeholderPattern = "_\\$(\\d)+"
+
+  private def stripPrivatePrefix(name: String) = {
+    val i = name.lastIndexOf("$$")
+    if (i > 0) name.substring(i + 2) else name
+  }
+
+  def processName(name: String) = {
+    val stripped = stripPrivatePrefix(name)
+    val m = pattern.matcher(stripped)
+    var temp = stripped
+    while (m.find) {
+      val key = m.group
+      val re = "\\" + key
+      temp = temp.replaceAll(re, _syms(re))
+    }
+    val result = temp.replaceAll(placeholderPattern, "_")
+    NameTransformer.decode(result)
+  }
+
+}
diff --git a/src/scalap/scala/tools/scalap/scalax/rules/scalasig/SourceFileAttributeParser.scala b/src/scalap/scala/tools/scalap/scalax/rules/scalasig/SourceFileAttributeParser.scala
new file mode 100644
index 0000000..fc5a75c
--- /dev/null
+++ b/src/scalap/scala/tools/scalap/scalax/rules/scalasig/SourceFileAttributeParser.scala
@@ -0,0 +1,28 @@
+package scala.tools.scalap
+package scalax
+package rules
+package scalasig
+
+/**
+ * @author ilyas
+ */
+
+object SourceFileAttributeParser extends ByteCodeReader {
+  val sourceFile = u2 ^^ SourceFileInfo
+
+  def parse(byteCode: ByteCode) = expect(sourceFile)(byteCode)
+}
+
+/**
+ *
+ * SourceFile_attribute {
+    	u2 attribute_name_index;
+    	u4 attribute_length;
+    	u2 sourcefile_index;
+    }
+ *
+ * Contains only file index in ConstantPool, first two fields are already treated
+ * by {@link scalax.rules.scalasig.ClassFile.attribute#attribute}
+ */
+case class SourceFileInfo(sourceFileIndex: Int)
+
diff --git a/src/scalap/scala/tools/scalap/scalax/rules/scalasig/Symbol.scala b/src/scalap/scala/tools/scalap/scalax/rules/scalasig/Symbol.scala
new file mode 100644
index 0000000..da2d4cd
--- /dev/null
+++ b/src/scalap/scala/tools/scalap/scalax/rules/scalasig/Symbol.scala
@@ -0,0 +1,73 @@
+package scala.tools.scalap
+package scalax
+package rules
+package scalasig
+
+import ScalaSigEntryParsers._
+
+trait Symbol extends Flags {
+  def name : String
+  def parent : Option[Symbol]
+  def children : Seq[Symbol]
+
+  def path : String = parent.map(_.path + ".").getOrElse("") + name
+}
+
+case object NoSymbol extends Symbol {
+  def name = "<no symbol>"
+  def parent = None
+  def hasFlag(flag : Long) = false
+  def children = Nil
+}
+
+abstract class ScalaSigSymbol extends Symbol {
+  def applyRule[A](rule : EntryParser[A]) : A = expect(rule)(entry)
+  def applyScalaSigRule[A](rule : ScalaSigParsers.Parser[A]) = ScalaSigParsers.expect(rule)(entry.scalaSig)
+    
+  def entry : ScalaSig#Entry
+  def index = entry.index
+
+  lazy val children : Seq[Symbol] = applyScalaSigRule(ScalaSigParsers.symbols) filter (_.parent == Some(this))
+  lazy val attributes : Seq[AttributeInfo] = applyScalaSigRule(ScalaSigParsers.attributes) filter (_.symbol == this)
+}
+
+case class ExternalSymbol(name : String, parent : Option[Symbol], entry : ScalaSig#Entry) extends ScalaSigSymbol {
+  override def toString = path
+  def hasFlag(flag : Long) = false
+}
+
+case class SymbolInfo(name : String, owner : Symbol, flags : Int, privateWithin : Option[AnyRef], info : Int, entry : ScalaSig#Entry) {
+  def symbolString(any : AnyRef) = any match {
+    case sym : SymbolInfoSymbol => sym.index.toString
+    case other => other.toString
+  }
+    
+  override def toString = name + ", owner=" + symbolString(owner) + ", flags=" + flags.toHexString + ", info=" + info + (privateWithin match {
+    case Some(any) => ", privateWithin=" + symbolString(any)
+    case None => " "
+  })
+}
+
+abstract class SymbolInfoSymbol extends ScalaSigSymbol {
+  def symbolInfo : SymbolInfo
+  
+  def entry = symbolInfo.entry
+  def name = symbolInfo.name
+  def parent = Some(symbolInfo.owner)
+  def hasFlag(flag : Long) = (symbolInfo.flags & flag) != 0L
+
+  lazy val infoType = applyRule(parseEntry(typeEntry)(symbolInfo.info))
+}
+
+case class TypeSymbol(symbolInfo : SymbolInfo) extends SymbolInfoSymbol{
+  override def path = name
+}
+
+case class AliasSymbol(symbolInfo : SymbolInfo) extends SymbolInfoSymbol{
+  override def path = name
+}
+case class ClassSymbol(symbolInfo : SymbolInfo, thisTypeRef : Option[Int]) extends SymbolInfoSymbol {
+  lazy val selfType = thisTypeRef.map{(x: Int) => applyRule(parseEntry(typeEntry)(x))}
+}
+case class ObjectSymbol(symbolInfo : SymbolInfo) extends SymbolInfoSymbol
+case class MethodSymbol(symbolInfo : SymbolInfo, aliasRef : Option[Int]) extends SymbolInfoSymbol
diff --git a/src/scalap/scala/tools/scalap/scalax/rules/scalasig/Type.scala b/src/scalap/scala/tools/scalap/scalax/rules/scalasig/Type.scala
new file mode 100644
index 0000000..c991df6
--- /dev/null
+++ b/src/scalap/scala/tools/scalap/scalax/rules/scalasig/Type.scala
@@ -0,0 +1,26 @@
+package scala.tools.scalap
+package scalax
+package rules
+package scalasig
+
+abstract class Type
+
+case object NoType extends Type
+case object NoPrefixType extends Type
+
+case class ThisType(symbol : Symbol) extends Type
+case class SingleType(typeRef : Type, symbol : Symbol) extends Type
+case class ConstantType(constant : Any) extends Type
+case class TypeRefType(prefix : Type, symbol : Symbol, typeArgs : Seq[Type]) extends Type
+case class TypeBoundsType(lower : Type, upper : Type) extends Type
+case class RefinedType(classSym : Symbol, typeRefs : List[Type]) extends Type
+case class ClassInfoType(symbol : Symbol, typeRefs : Seq[Type]) extends Type
+case class ClassInfoTypeWithCons(symbol : Symbol, typeRefs : Seq[Type], cons: String) extends Type
+case class MethodType(resultType : Type, paramSymbols : Seq[Symbol]) extends Type
+case class PolyType(typeRef : Type, symbols : Seq[TypeSymbol]) extends Type
+case class PolyTypeWithCons(typeRef : Type, symbols : Seq[TypeSymbol], cons: String) extends Type
+case class ImplicitMethodType(resultType : Type, paramSymbols : Seq[Symbol]) extends Type
+case class AnnotatedType(typeRef : Type, attribTreeRefs : List[Int]) extends Type
+case class AnnotatedWithSelfType(typeRef : Type, symbol : Symbol, attribTreeRefs : List[Int]) extends Type
+case class DeBruijnIndexType(typeLevel : Int, typeIndex : Int) extends Type
+case class ExistentialType(typeRef : Type, symbols : Seq[Symbol]) extends Type
diff --git a/src/scalap/scala/tools/scalap/scalax/util/StringUtil.scala b/src/scalap/scala/tools/scalap/scalax/util/StringUtil.scala
new file mode 100644
index 0000000..6077ede
--- /dev/null
+++ b/src/scalap/scala/tools/scalap/scalax/util/StringUtil.scala
@@ -0,0 +1,19 @@
+package scala.tools.scalap
+package scalax
+package util
+
+import java.beans.Introspector
+
+/**
+ * @author ilyas
+ */
+
+object StringUtil {
+
+  def trimStart(s: String, prefix: String) = if (s != null && s.startsWith(prefix)) s.substring(prefix.length) else s
+
+  def decapitalize(s: String) = Introspector.decapitalize(s)
+
+  def cutSubstring(dom: String)(s: String) = if (dom != null && s != null) dom.replace(s, "") else dom
+
+}
diff --git a/src/swing/doc/README b/src/swing/doc/README
index dcd7470..cdfee01 100644
--- a/src/swing/doc/README
+++ b/src/swing/doc/README
@@ -36,4 +36,4 @@ Notes:
 Visual appearance of combo boxes using the GTK LaF is broken on JDKs < 1.7b30. 
 This is a Java Swing problem.
 
-To download the latest version, go to http://lamp.epfl.ch/~imaier or use sbaz.
\ No newline at end of file
+To download the latest version, go to http://lamp.epfl.ch/~imaier or use sbaz.
diff --git a/src/swing/doc/build.xml b/src/swing/doc/build.xml
index e47d93c..20e1411 100644
--- a/src/swing/doc/build.xml
+++ b/src/swing/doc/build.xml
@@ -80,4 +80,4 @@
             quiet="yes"
             failonerror="no"/>
   </target>
-</project>
\ No newline at end of file
+</project>
diff --git a/src/swing/scala/swing/AbstractButton.scala b/src/swing/scala/swing/AbstractButton.scala
index 2d3955b..4325944 100644
--- a/src/swing/scala/swing/AbstractButton.scala
+++ b/src/swing/scala/swing/AbstractButton.scala
@@ -1,8 +1,17 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
 package scala.swing
 
-import java.awt.{Dimension, Insets}
-import javax.swing.{AbstractButton => JAbstractButton, Icon}
 import event._
+import javax.swing.{AbstractButton => JAbstractButton, Icon}
 
 /**
  * Base class of all button-like widgets, such as push buttons, 
@@ -10,7 +19,7 @@ import event._
  * 
  * @see javax.swing.AbstractButton
  */
-abstract class AbstractButton extends Component with Action.Trigger with Publisher {
+abstract class AbstractButton extends Component with Action.Trigger.Wrapper with Publisher {
   override lazy val peer: JAbstractButton = new JAbstractButton with SuperMixin {}
 
   def text: String = peer.getText
@@ -31,13 +40,6 @@ abstract class AbstractButton extends Component with Action.Trigger with Publish
   def rolloverSelectedIcon: Icon = peer.getRolloverSelectedIcon
   def rolloverSelectedIcon_=(b: Icon) = peer.setRolloverSelectedIcon(b)
   
-  private var _action: Action = Action.NoAction
-  def action: Action = _action
-  def action_=(a: Action) { _action = a; peer.setAction(a.peer) }
-  
-  //1.6: def hideActionText: Boolean = peer.getHideActionText
-  //def hideActionText_=(b: Boolean) = peer.setHideActionText(b)
-  
   peer.addActionListener(Swing.ActionListener { e =>
     publish(ButtonClicked(AbstractButton.this))
   })
diff --git a/src/swing/scala/swing/Action.scala b/src/swing/scala/swing/Action.scala
index 91c729f..8d73c23 100644
--- a/src/swing/scala/swing/Action.scala
+++ b/src/swing/scala/swing/Action.scala
@@ -1,19 +1,44 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
 package scala.swing
 
 import javax.swing.{KeyStroke, Icon}
 import java.awt.event.ActionListener
 
 object Action {
+  /**
+   * Special action that has an empty title and all default properties and does nothing.
+   * Use this as a "null action", i.e., to tell components that they do not have any 
+   * associated action. A component may then obtain its properties from its direct members 
+   * instead of from its action.
+   * In Java Swing, one would use `null` instead of a designated action.
+   */
   case object NoAction extends Action("") { def apply() {} }
   
   object Trigger {
-    abstract trait Wrapper extends Component with Action.Trigger { 
-      self: Component {
-        def peer: javax.swing.JComponent { 
-          def addActionListener(a: ActionListener) 
-          def removeActionListener(a: ActionListener)
-        }
-      } =>
+    trait Wrapper extends Action.Trigger { 
+      def peer: javax.swing.JComponent { 
+        def addActionListener(a: ActionListener) 
+        def removeActionListener(a: ActionListener)
+        def setAction(a: javax.swing.Action)
+        def getAction(): javax.swing.Action
+      }
+      
+      // TODO: we need an action cache
+      private var _action: Action = Action.NoAction
+      def action: Action = _action
+      def action_=(a: Action) { _action = a; peer.setAction(a.peer) }
+      
+      //1.6: def hideActionText: Boolean = peer.getHideActionText
+      //def hideActionText_=(b: Boolean) = peer.setHideActionText(b)
     }
   }
     
@@ -28,8 +53,11 @@ object Action {
     //def hideActionText_=(b: Boolean)
   }
   
-  def apply(title: String)(block: =>Unit) = new Action(title) { 
-    def apply() { block }
+  /**
+   * Convenience method to create an action with a given title and body to run.
+   */
+  def apply(title: String)(body: =>Unit) = new Action(title) { 
+    def apply() { body }
   }
 }
 
@@ -107,7 +135,7 @@ abstract class Action(title0: String) {
   def accelerator: Option[KeyStroke] = 
     toOption(peer.getValue(javax.swing.Action.ACCELERATOR_KEY))
   def accelerator_=(k: Option[KeyStroke]) { 
-    peer.putValue(javax.swing.Action.ACCELERATOR_KEY, toNull(k)) 
+    peer.putValue(javax.swing.Action.ACCELERATOR_KEY, k orNull)
   } 
   
   /**
@@ -119,7 +147,7 @@ abstract class Action(title0: String) {
   /*/**
    * Only honored if not <code>None</code>. For various buttons.
    */
-   1.6: def selected: Option[Boolean] = toOption(peer.getValue(javax.swing.Action.SELECTED_KEY))
+   1.6: def selected: Option[Boolean] = Option(peer.getValue(javax.swing.Action.SELECTED_KEY))
    def selected_=(b: Option[Boolean]) { 
    peer.putValue(javax.swing.Action.SELECTED_KEY, 
                  if (b == None) null else new java.lang.Boolean(b.get)) 
diff --git a/src/swing/scala/swing/Adjustable.scala b/src/swing/scala/swing/Adjustable.scala
new file mode 100644
index 0000000..bc5dc64
--- /dev/null
+++ b/src/swing/scala/swing/Adjustable.scala
@@ -0,0 +1,53 @@
+package scala.swing
+
+import java.awt.{Adjustable => JAdjustable}
+
+object Adjustable {
+  trait Wrapper extends Oriented.Wrapper with Adjustable {
+    def peer: JAdjustable with OrientedMixin
+
+    def unitIncrement = peer.getUnitIncrement
+    def unitIncrement_=(i: Int) = peer.setUnitIncrement(i)
+    def blockIncrement = peer.getBlockIncrement
+    def blockIncrement_=(i: Int) = peer.setBlockIncrement(i)
+
+    def value = peer.getValue
+    def value_=(v: Int) = peer.setValue(v)
+
+    def visibleAmount = peer.getVisibleAmount
+    def visibleAmount_=(v: Int) = peer.setVisibleAmount(v)
+
+    def minimum = peer.getMinimum
+    def minimum_=(m: Int) = peer.setMinimum(m)
+    def maximum = peer.getMaximum
+    def maximum_=(m: Int) = peer.setMaximum(m)
+  }
+}
+
+trait Adjustable extends Oriented {
+  def unitIncrement: Int
+  def unitIncrement_=(i: Int)
+  def blockIncrement: Int
+  def blockIncrement_=(i: Int)
+
+  def value: Int
+  def value_=(v : Int)
+
+  def visibleAmount: Int
+  def visibleAmount_=(v: Int)
+
+  def minimum: Int
+  def minimum_=(m: Int)
+  def maximum: Int
+  def maximum_=(m: Int)
+    
+// Needs implementation of AdjustmentEvent
+//
+//    val adjustments: Publisher = new Publisher {
+//		peer.addAdjustmentListener(new AdjustmentListener {
+//			def adjustmentValueChanged(e: java.awt.event.AdjustmentEvent) { 
+//				publish(new AdjustmentEvent(e))
+//			}
+//		})
+//   	}
+}
diff --git a/src/swing/scala/swing/Alignment.scala b/src/swing/scala/swing/Alignment.scala
index 57cf143..439727c 100644
--- a/src/swing/scala/swing/Alignment.scala
+++ b/src/swing/scala/swing/Alignment.scala
@@ -1,3 +1,13 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
 package scala.swing
 
 import javax.swing.SwingConstants._
diff --git a/src/swing/scala/swing/Applet.scala b/src/swing/scala/swing/Applet.scala
index dac0058..b2590a4 100644
--- a/src/swing/scala/swing/Applet.scala
+++ b/src/swing/scala/swing/Applet.scala
@@ -1,15 +1,28 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
 package scala.swing
 
 import javax.swing.JApplet
 
-/**
- * Clients should implement the ui field. See the SimpleApplet demo for an example.
- * 
- * Note: <code>Applet</code> extends <code>javax.swing.JApplet</code> to satisfy 
- * Java's applet loading mechanism. The usual component wrapping scheme doesn't 
- * work here. 
- * 
- * @see javax.swing.JApplet
+/** <p>
+ *    Clients should implement the ui field. See the <code>SimpleApplet</code>
+ *    demo for an example.
+ *  </p>
+ *  <p>
+ *    <b>Note</b>: <code>Applet</code> extends <code>javax.swing.JApplet</code>
+ *    to satisfy Java's applet loading mechanism. The usual component wrapping
+ *    scheme doesn't  work here. 
+ *  </p>
+ *
+ *  @see javax.swing.JApplet
  */
 abstract class Applet extends JApplet { outer =>
   val ui: UI
diff --git a/src/swing/scala/swing/BorderPanel.scala b/src/swing/scala/swing/BorderPanel.scala
index 67e645c..9941270 100644
--- a/src/swing/scala/swing/BorderPanel.scala
+++ b/src/swing/scala/swing/BorderPanel.scala
@@ -1,3 +1,13 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
 package scala.swing
 
 import java.awt.BorderLayout
@@ -40,5 +50,11 @@ class BorderPanel extends Panel with LayoutContainer {
     wrapPosition(layoutManager.getConstraints(comp.peer).asInstanceOf[String])
   
   protected def areValid(c: Constraints): (Boolean, String) = (true, "")
-  protected def add(c: Component, l: Constraints) { peer.add(c.peer, l.toString) }
+  protected def add(c: Component, l: Constraints) {
+    // we need to remove previous components with the same constraints as the new one, 
+    // otherwise the layout manager loses track of the old one
+    val old = layoutManager.getLayoutComponent(l.toString)
+    if(old != null) peer.remove(old)
+    peer.add(c.peer, l.toString)
+  }
 }
diff --git a/src/swing/scala/swing/BoxPanel.scala b/src/swing/scala/swing/BoxPanel.scala
index 9363f0d..f39cb74 100644
--- a/src/swing/scala/swing/BoxPanel.scala
+++ b/src/swing/scala/swing/BoxPanel.scala
@@ -1,3 +1,13 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
 package scala.swing
 
 /**
diff --git a/src/swing/scala/swing/BufferWrapper.scala b/src/swing/scala/swing/BufferWrapper.scala
index 8383dfd..cfd9b51 100644
--- a/src/swing/scala/swing/BufferWrapper.scala
+++ b/src/swing/scala/swing/BufferWrapper.scala
@@ -1,3 +1,13 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
 package scala.swing
 
 import scala.collection.mutable.Buffer
@@ -6,25 +16,20 @@ import scala.collection.mutable.Buffer
  * Default partial implementation for buffer adapters.
  */
 protected[swing] abstract class BufferWrapper[A] extends Buffer[A] { outer =>
-  def clear { for (i <- 0 to length) remove(0) }
+  def clear() { for (i <- 0 until length) remove(0) }
   def update(n: Int, a: A) {
-    remove(0)
+    remove(n)
     insertAt(n, a)
   }
-  def insertAll(n: Int, iter: Iterable[A]) {
+  def insertAll(n: Int, elems: scala.collection.Traversable[A]) {
     var i = n
-    for(el <- iter) {
+    for (el <- elems) {
       insertAt(i, el)
       i += 1
     }
   }
   protected def insertAt(n: Int, a: A)
   
-  def readOnly : RandomAccessSeq[A] = new RandomAccessSeq[A] {
-    def length = outer.length
-    def apply(idx : Int) = outer.apply(idx)
-    override def stringPrefix = outer.stringPrefix + "RO"
-  }
-  def +:(a: A): this.type = { insertAt(0, a); this }
-  def elements = Iterator.range(0,length).map(apply(_))
+  def +=:(a: A): this.type = { insertAt(0, a); this }
+  def iterator = Iterator.range(0,length).map(apply(_))
 }
diff --git a/src/swing/scala/swing/Button.scala b/src/swing/scala/swing/Button.scala
index b363230..8525919 100644
--- a/src/swing/scala/swing/Button.scala
+++ b/src/swing/scala/swing/Button.scala
@@ -1,7 +1,21 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
 package scala.swing
 
-import javax.swing._
 import event._
+import javax.swing._
+
+object Button {
+  def apply(text0: String)(op: => Unit) = new Button(Action(text0)(op))
+}
 
 /**
  * A button that can be clicked, usually to perform some action.
diff --git a/src/swing/scala/swing/ButtonGroup.scala b/src/swing/scala/swing/ButtonGroup.scala
index d3a4a76..39aa612 100644
--- a/src/swing/scala/swing/ButtonGroup.scala
+++ b/src/swing/scala/swing/ButtonGroup.scala
@@ -1,7 +1,17 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
 package scala.swing
 
-import javax.swing.{AbstractButton => JAbstractButton,Icon}
 import event._
+import javax.swing.{AbstractButton => JAbstractButton,Icon}
 import scala.collection._
 import scala.collection.mutable.Buffer
 
@@ -15,13 +25,13 @@ class ButtonGroup(initialButtons: AbstractButton*) {
   val peer: javax.swing.ButtonGroup = new javax.swing.ButtonGroup
   
   val buttons: mutable.Set[AbstractButton] = new mutable.Set[AbstractButton] { 
-    def -=(b: AbstractButton) { peer.remove(b.peer) }
-    def +=(b: AbstractButton) { peer.add(b.peer) }
-    def contains(b: AbstractButton) = elements.contains(b)
-    def size = peer.getButtonCount
-    def elements: Iterator[AbstractButton] = new Iterator[AbstractButton] {
+    def -=(b: AbstractButton): this.type = { peer.remove(b.peer); this }
+    def +=(b: AbstractButton): this.type = { peer.add(b.peer); this }
+    def contains(b: AbstractButton) = this.iterator.contains(b)
+    override def size = peer.getButtonCount
+    def iterator: Iterator[AbstractButton] = new Iterator[AbstractButton] {
       val enum = peer.getElements
-      def next = Component.wrapperFor[AbstractButton](enum.nextElement.asInstanceOf[javax.swing.JComponent])
+      def next = UIElement.cachedWrapper[AbstractButton](enum.nextElement)
       def hasNext = enum.hasMoreElements
     }
   }
diff --git a/src/swing/scala/swing/CheckBox.scala b/src/swing/scala/swing/CheckBox.scala
index d8176a8..a15e6b2 100644
--- a/src/swing/scala/swing/CheckBox.scala
+++ b/src/swing/scala/swing/CheckBox.scala
@@ -1,3 +1,13 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
 package scala.swing
 
 import javax.swing._
@@ -13,4 +23,4 @@ class CheckBox(text: String) extends ToggleButton {
 
   def borderPaintedFlat: Boolean = peer.isBorderPaintedFlat
   def borderPaintedFlat_=(flat: Boolean) { peer.setBorderPaintedFlat(flat) }
-}
\ No newline at end of file
+}
diff --git a/src/swing/scala/swing/ComboBox.scala b/src/swing/scala/swing/ComboBox.scala
index fd50487..9a47518 100644
--- a/src/swing/scala/swing/ComboBox.scala
+++ b/src/swing/scala/swing/ComboBox.scala
@@ -1,10 +1,19 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
 package scala.swing
 
 import event._
 import javax.swing.{JList, JComponent, JComboBox, JTextField, ComboBoxModel, AbstractListModel, ListCellRenderer}
 import java.awt.event.ActionListener
 
-
 object ComboBox {
   /**
    * An editor for a combo box. Let's you edit the currently selected item.
@@ -110,12 +119,18 @@ object ComboBox {
   implicit def intEditor(c: ComboBox[Int]): Editor[Int] = new BuiltInEditor(c)(s => s.toInt, s => s.toString)
   implicit def floatEditor(c: ComboBox[Float]): Editor[Float] = new BuiltInEditor(c)(s => s.toFloat, s => s.toString)
   implicit def doubleEditor(c: ComboBox[Double]): Editor[Double] = new BuiltInEditor(c)(s => s.toDouble, s => s.toString)
-   
+  
   def newConstantModel[A](items: Seq[A]): ComboBoxModel = {
     new AbstractListModel with ComboBoxModel {
       private var selected = items(0)
       def getSelectedItem: AnyRef = selected.asInstanceOf[AnyRef]
-      def setSelectedItem(a: Any) { selected = a.asInstanceOf[A] } 
+      def setSelectedItem(a: Any) { 
+        if ((selected != null && selected != a) ||
+            selected == null && a != null) {
+          selected = a.asInstanceOf[A]
+          fireContentsChanged(this, -1, -1)
+        }
+      } 
       def getElementAt(n: Int) = items(n).asInstanceOf[AnyRef]
       def getSize = items.size
     }
@@ -188,8 +203,8 @@ class ComboBox[A](items: Seq[A]) extends Component with Publisher {
     peer.setEditor(editor(this).comboBoxPeer)
   }
   
-  def prototypeDisplayValue: Option[A] = Swing.toOption(peer.getPrototypeDisplayValue)
+  def prototypeDisplayValue: Option[A] = toOption[A](peer.getPrototypeDisplayValue)
   def prototypeDisplayValue_=(v: Option[A]) { 
-    peer.setPrototypeDisplayValue(Swing.toNull(v.map(_.asInstanceOf[AnyRef]))) 
+    peer.setPrototypeDisplayValue(v map toAnyRef orNull)
   }
-}
\ No newline at end of file
+}
diff --git a/src/swing/scala/swing/Component.scala b/src/swing/scala/swing/Component.scala
index 5a41876..50a1579 100644
--- a/src/swing/scala/swing/Component.scala
+++ b/src/swing/scala/swing/Component.scala
@@ -1,59 +1,85 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
 package scala.swing
 
 import event._
 
-import java.awt.{Dimension, Point}
+import java.awt.Graphics
 import java.awt.event._
 import javax.swing.JComponent
 import javax.swing.border.Border
 
+/**
+ * Utility methods, mostly for wrapping components.
+ */
 object Component {
-  private val ClientKey = "scala.swingWrapper"
-  
-  /**
-   * Returns the wrapper for a given peer, null if there is no wrapper 
-   * for the given component.
-   */
-  protected[swing] def wrapperFor[C<:Component](c: javax.swing.JComponent): C =
-    c.getClientProperty(ClientKey).asInstanceOf[C]
-  
   /**
    * Wraps a given Java Swing Component into a new wrapper.
    */
-  def wrap(c: JComponent): Component = new Component {
-    override lazy val peer = c
+  def wrap(c: JComponent): Component = {
+    val w = UIElement.cachedWrapper[Component](c)
+    if (w != null) w 
+    else new Component { override lazy val peer = c }
   }
 }
 
 /**
  * Base class for all UI elements that can be displayed in a window.
+ * Components are publishers that fire the following event classes: 
+ * ComponentEvent, FocusEvent, FontChanged, ForegroundChanged, BackgroundChanged.
+ * 
+ * @note [Java Swing] Unlike in Java Swing, not all components are also containers.
  *
  * @see javax.swing.JComponent
+ * @see http://java.sun.com/products/jfc/tsc/articles/painting/ for the component 
+ * painting mechanism
  */
-abstract class Component extends UIElement with Publisher {
+abstract class Component extends UIElement {
   override lazy val peer: javax.swing.JComponent = new javax.swing.JComponent with SuperMixin {}
   var initP: JComponent = null
-  peer.putClientProperty(Component.ClientKey, this)
   
   /**
    * This trait is used to redirect certain calls from the peer to the wrapper 
    * and back. Useful to expose methods that can be customized by overriding.
    */
   protected trait SuperMixin extends JComponent {
-    override def paintComponent(g: java.awt.Graphics) {
-      Component.this.paintComponent(g)
+    override def paintComponent(g: Graphics) {
+      Component.this.paintComponent(g.asInstanceOf[Graphics2D])
     }
-    def __super__paintComponent(g: java.awt.Graphics) {
+    def __super__paintComponent(g: Graphics) {
       super.paintComponent(g)
     }
-    override def paint(g: java.awt.Graphics) {
-      Component.this.paint(g)
+    override def paintBorder(g: Graphics) {
+      Component.this.paintBorder(g.asInstanceOf[Graphics2D])
+    }
+    def __super__paintBorder(g: Graphics) {
+      super.paintBorder(g)
+    }
+    override def paintChildren(g: Graphics) {
+      Component.this.paintChildren(g.asInstanceOf[Graphics2D])
+    }
+    def __super__paintChildren(g: Graphics) {
+      super.paintChildren(g)
+    }
+    
+    override def paint(g: Graphics) {
+      Component.this.paint(g.asInstanceOf[Graphics2D])
     }
-    def __super__paint(g: java.awt.Graphics) { 
+    def __super__paint(g: Graphics) { 
       super.paint(g)
     }
   }
-
+  
+  def name: String = peer.getName
+  def name_=(s: String) = peer.setName(s)
   
   /**
    * Used by certain layout managers, e.g., BoxLayout or OverlayLayout to 
@@ -76,12 +102,12 @@ abstract class Component extends UIElement with Publisher {
   def tooltip: String = peer.getToolTipText
   def tooltip_=(t: String) = peer.setToolTipText(t)
   
-  def inputVerifier: this.type => Boolean = { a =>
-    peer.getInputVerifier().verify(a.peer)
+  def inputVerifier: Component => Boolean = { a =>
+    peer.getInputVerifier.verify(a.peer)
   }
-  def inputVerifier_=(v: this.type => Boolean) { 
+  def inputVerifier_=(v: Component => Boolean) { 
     peer.setInputVerifier(new javax.swing.InputVerifier {
-      def verify(c: javax.swing.JComponent) = v(Component.wrapperFor(c))
+      def verify(c: javax.swing.JComponent) = v(UIElement.cachedWrapper[Component](c))
     })
   }
 
@@ -90,44 +116,19 @@ abstract class Component extends UIElement with Publisher {
   }
   def verifyOnTraversal_=(v: (Component, Component) => Boolean) { 
     peer.setInputVerifier(new javax.swing.InputVerifier {
-      def verify(c: javax.swing.JComponent) = v(Component.wrapperFor(c))
+      def verify(c: javax.swing.JComponent) = v(UIElement.cachedWrapper[Component](c))
     })
   }*/
   
-  peer.addComponentListener(new java.awt.event.ComponentListener {
-    def componentHidden(e: java.awt.event.ComponentEvent) { 
-      publish(ComponentHidden(Component.this)) 
-    }
-    def componentShown(e: java.awt.event.ComponentEvent) { 
-      publish(ComponentShown(Component.this)) 
-    }
-    def componentMoved(e: java.awt.event.ComponentEvent) { 
-      publish(ComponentMoved(Component.this)) 
-    }
-    def componentResized(e: java.awt.event.ComponentEvent) { 
-      publish(ComponentResized(Component.this)) 
-    }
-  })
+  
 
-  peer.addFocusListener(new java.awt.event.FocusListener {
-    def other(e: java.awt.event.FocusEvent) = e.getOppositeComponent match {
-      case c: JComponent => Some(Component.wrapperFor(c))
-      case _ => None
-    }
-    
-    def focusGained(e: java.awt.event.FocusEvent) { 
-      publish(FocusGained(Component.this, other(e), e.isTemporary)) 
-    }
-    def focusLost(e: java.awt.event.FocusEvent) {
-      publish(FocusLost(Component.this, other(e), e.isTemporary)) 
-    }
-  })
+  @deprecated("Use mouse instead") lazy val Mouse = mouse
   
   /**
    * Contains publishers for various mouse events. They are separated for 
    * efficiency reasons.
    */
-  object Mouse {
+  object mouse {
     /**
      * Publishes clicks, presses and releases.
      */
@@ -136,16 +137,13 @@ abstract class Component extends UIElement with Publisher {
         def mouseEntered(e: java.awt.event.MouseEvent) { }
         def mouseExited(e: java.awt.event.MouseEvent) { }
         def mouseClicked(e: java.awt.event.MouseEvent) { 
-          publish(MouseClicked(Component.wrapperFor(e.getSource.asInstanceOf[JComponent]), 
-                               e.getPoint, e.getModifiersEx, e.getClickCount, e.isPopupTrigger)(e.getWhen))
+          publish(new MouseClicked(e))
         }
         def mousePressed(e: java.awt.event.MouseEvent) { 
-          publish(MousePressed(Component.wrapperFor(e.getSource.asInstanceOf[JComponent]), 
-                               e.getPoint, e.getModifiersEx, e.getClickCount, e.isPopupTrigger)(e.getWhen))
+          publish(new MousePressed(e))
         }
         def mouseReleased(e: java.awt.event.MouseEvent) { 
-          publish(MouseReleased(Component.wrapperFor(e.getSource.asInstanceOf[JComponent]), 
-                                e.getPoint, e.getModifiersEx, e.getClickCount, e.isPopupTrigger)(e.getWhen))
+          publish(new MouseReleased(e))
         }
       })
     }
@@ -155,12 +153,10 @@ abstract class Component extends UIElement with Publisher {
     val moves: Publisher = new Publisher {
       peer.addMouseListener(new MouseListener {
         def mouseEntered(e: java.awt.event.MouseEvent) { 
-          publish(MouseEntered(Component.wrapperFor(e.getSource.asInstanceOf[JComponent]), 
-                               e.getPoint, e.getModifiersEx)(e.getWhen))
+          publish(new MouseEntered(e))
         }
         def mouseExited(e: java.awt.event.MouseEvent) {
-          publish(MouseExited(Component.wrapperFor(e.getSource.asInstanceOf[JComponent]), 
-                              e.getPoint, e.getModifiersEx)(e.getWhen))
+          publish(new MouseExited(e))
         }
         def mouseClicked(e: java.awt.event.MouseEvent) {}
         def mousePressed(e: java.awt.event.MouseEvent) { }
@@ -168,65 +164,124 @@ abstract class Component extends UIElement with Publisher {
       })
       peer.addMouseMotionListener(new MouseMotionListener {
         def mouseMoved(e: java.awt.event.MouseEvent) { 
-          publish(MouseMoved(Component.wrapperFor(e.getSource.asInstanceOf[JComponent]), 
-                             e.getPoint, e.getModifiersEx)(e.getWhen))
+          publish(new MouseMoved(e))
         }
         def mouseDragged(e: java.awt.event.MouseEvent) { 
-          publish(MouseDragged(Component.wrapperFor(e.getSource.asInstanceOf[JComponent]), 
-                               e.getPoint, e.getModifiersEx)(e.getWhen))
+          publish(new MouseDragged(e))
         }
       })
     }
     /**
      * Publishes mouse wheel moves.
      */
-    val wheel: Publisher = new Publisher {
-      peer.addMouseWheelListener(new MouseWheelListener {
-        def mouseWheelMoved(e: java.awt.event.MouseWheelEvent) { 
-          publish(MouseWheelMoved(Component.wrapperFor(e.getSource.asInstanceOf[JComponent]), 
-                             e.getPoint, e.getModifiersEx, e.getWheelRotation)(e.getWhen)) }
-      })
+    val wheel: Publisher = new LazyPublisher {
+      // We need to subscribe lazily and unsubscribe, since components in scroll panes capture 
+      // mouse wheel events if there is a listener installed. See ticket #1442.
+      lazy val l = new MouseWheelListener {
+          def mouseWheelMoved(e: java.awt.event.MouseWheelEvent) { 
+            publish(new MouseWheelMoved(e)) }
+        }
+      def onFirstSubscribe() = peer.addMouseWheelListener(l)
+      def onLastUnsubscribe() = peer.removeMouseWheelListener(l)
     }
   }
+  
+  object keys extends Publisher {
+    peer.addKeyListener(new KeyListener {
+      def keyPressed(e: java.awt.event.KeyEvent) { publish(new KeyPressed(e)) }
+      def keyReleased(e: java.awt.event.KeyEvent) { publish(new KeyReleased(e)) }
+      def keyTyped(e: java.awt.event.KeyEvent) { publish(new KeyTyped(e)) }
+    })
+  }
+  
+  def focusable: Boolean = peer.isFocusable
+  def focusable_=(b: Boolean) = peer.setFocusable(b)
+  def requestFocus() = peer.requestFocus()
+  def requestFocusInWindow() = peer.requestFocusInWindow()
+  def hasFocus: Boolean = peer.isFocusOwner
+  
+  protected override def onFirstSubscribe {
+    super.onFirstSubscribe
+    // TODO: deprecated, remove after 2.8
+    peer.addComponentListener(new java.awt.event.ComponentListener {
+      def componentHidden(e: java.awt.event.ComponentEvent) { 
+        publish(ComponentHidden(Component.this)) 
+      }
+      def componentShown(e: java.awt.event.ComponentEvent) { 
+        publish(ComponentShown(Component.this)) 
+      }
+      def componentMoved(e: java.awt.event.ComponentEvent) { 
+        publish(ComponentMoved(Component.this)) 
+      }
+      def componentResized(e: java.awt.event.ComponentEvent) { 
+        publish(ComponentResized(Component.this)) 
+      }
+    })
 
+    peer.addFocusListener(new java.awt.event.FocusListener {
+      def other(e: java.awt.event.FocusEvent) = e.getOppositeComponent match {
+        case c: JComponent => Some(UIElement.cachedWrapper[Component](c))
+        case _ => None
+      }
+    
+      def focusGained(e: java.awt.event.FocusEvent) { 
+        publish(FocusGained(Component.this, other(e), e.isTemporary)) 
+      }
+      def focusLost(e: java.awt.event.FocusEvent) {
+        publish(FocusLost(Component.this, other(e), e.isTemporary)) 
+      }
+    })
   
-  peer.addPropertyChangeListener(new java.beans.PropertyChangeListener {
-    def propertyChange(e: java.beans.PropertyChangeEvent) { 
-      e.getPropertyName match {
-        case "font" => publish(FontChanged(Component.this))
-        case "background" => publish(ForegroundChanged(Component.this))
-        case "foreground" => publish(BackgroundChanged(Component.this))
-        case _ =>
-        /*case "focusable" =>
-        case "focusTraversalKeysEnabled" =>
-        case "forwardFocusTraversalKeys" =>
-        case "backwardFocusTraversalKeys" =>
-        case "upCycleFocusTraversalKeys" =>
-        case "downCycleFocusTraversalKeys" =>
-        case "focusTraversalPolicy" =>
-        case "focusCycleRoot" =>*/
+    peer.addPropertyChangeListener(new java.beans.PropertyChangeListener {
+      def propertyChange(e: java.beans.PropertyChangeEvent) { 
+        e.getPropertyName match {
+          case "font" => publish(FontChanged(Component.this))
+          case "background" => publish(BackgroundChanged(Component.this))
+          case "foreground" => publish(ForegroundChanged(Component.this))
+          case _ =>
+          /*case "focusable" =>
+          case "focusTraversalKeysEnabled" =>
+          case "forwardFocusTraversalKeys" =>
+          case "backwardFocusTraversalKeys" =>
+          case "upCycleFocusTraversalKeys" =>
+          case "downCycleFocusTraversalKeys" =>
+          case "focusTraversalPolicy" =>
+          case "focusCycleRoot" =>*/
+        }
       }
-    }
-  })
+    })
+  }
   
   def revalidate() { peer.revalidate() }
   
-  def requestFocus() { peer.requestFocus() }
-  
   /**
    * For custom painting, users should usually override this method.
    */
-  protected def paintComponent(g: java.awt.Graphics) {
+  protected def paintComponent(g: Graphics2D) {
     peer match {
       case peer: SuperMixin => peer.__super__paintComponent(g)
-      case _ => // it's a wrapper created on the fly
+      case _ => 
+    }
+  }
+  
+  protected def paintBorder(g: Graphics2D) {
+    peer match {
+      case peer: SuperMixin => peer.__super__paintBorder(g)
+      case _ => 
+    }
+  }
+  
+  protected def paintChildren(g: Graphics2D) {
+    peer match {
+      case peer: SuperMixin => peer.__super__paintChildren(g)
+      case _ => 
     }
   }
   
-  protected def paint(g: java.awt.Graphics) {
+  def paint(g: Graphics2D) {
     peer match {
       case peer: SuperMixin => peer.__super__paint(g)
-      case _ => // it's a wrapper created on the fly
+      case _ => peer.paint(g)
     }
   }
    
diff --git a/src/swing/scala/swing/Container.scala b/src/swing/scala/swing/Container.scala
index 58931f2..d4ac241 100644
--- a/src/swing/scala/swing/Container.scala
+++ b/src/swing/scala/swing/Container.scala
@@ -1,3 +1,13 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
 package scala.swing
 
 import event._
@@ -5,43 +15,50 @@ import scala.collection.mutable.Buffer
 
 object Container {
   /**
-   * Utility trait for wrapping containers.
+   * Utility trait for wrapping containers. Provides an immutable 
+   * implementation of the contents member.
    */
-  trait Wrapper extends Component with Container {
+  trait Wrapper extends Container with Publisher {
+    override def peer: javax.swing.JComponent
+    
     protected val _contents = new Content
     def contents: Seq[Component] = _contents
   
     protected class Content extends BufferWrapper[Component] {
-      def wrap(c: java.awt.Component): Component = Component.wrapperFor(c.asInstanceOf[javax.swing.JComponent])
       override def clear { peer.removeAll() }
-      def remove(n: Int): Component = { 
+      override def remove(n: Int): Component = { 
         val c = peer.getComponent(n)
         peer.remove(n)
-        wrap(c)
+        UIElement.cachedWrapper[Component](c)
       }
       protected def insertAt(n: Int, c: Component) { peer.add(c.peer, n) }
-      def +=(c: Component) { peer.add(c.peer) }
+      def +=(c: Component): this.type = { peer.add(c.peer) ; this }
       def length = peer.getComponentCount
-      def apply(n: Int) = wrap(peer.getComponent(n))
+      def apply(n: Int) = UIElement.cachedWrapper[Component](peer.getComponent(n))
     }
   
     peer.addContainerListener(new java.awt.event.ContainerListener {
       def componentAdded(e: java.awt.event.ContainerEvent) { 
         publish(ComponentAdded(Wrapper.this, 
-                               Component.wrapperFor(e.getChild.asInstanceOf[javax.swing.JComponent]))) 
+          UIElement.cachedWrapper[Component](e.getChild.asInstanceOf[javax.swing.JComponent]))) 
       }
       def componentRemoved(e: java.awt.event.ContainerEvent) { 
         publish(ComponentRemoved(Wrapper.this, 
-                                 Component.wrapperFor(e.getChild.asInstanceOf[javax.swing.JComponent]))) 
+          UIElement.cachedWrapper[Component](e.getChild.asInstanceOf[javax.swing.JComponent]))) 
       }
     })
   }
 }
 
 /**
- * A UI element that can contain <code>Component</code>s, such as windows, 
- * panels, and menus.
+ * The base traits for UI elements that can contain <code>Component</code>s.
+ * 
+ * @note [Java Swing] This is not the wrapper for java.awt.Container but a trait 
+ * that extracts a common interface for components, menus, and windows.
  */
 trait Container extends UIElement {
+  /**
+   * The child components of this container.
+   */
   def contents: Seq[Component]
-}
\ No newline at end of file
+}
diff --git a/src/swing/scala/swing/Dialog.scala b/src/swing/scala/swing/Dialog.scala
deleted file mode 100644
index 4fff540..0000000
--- a/src/swing/scala/swing/Dialog.scala
+++ /dev/null
@@ -1,81 +0,0 @@
-package scala.swing
-
-import javax.swing.{Icon, JOptionPane}
-
-/**
- * Simple predefined dialogs.
- * 
- * @see javax.swing.JOptionPane
- */
-object Dialog {
-  /**
-   * The message type of a dialog.
-   */
-  object Message extends Enumeration {
-    val Error = Value(JOptionPane.ERROR_MESSAGE)
-    val Info = Value(JOptionPane.INFORMATION_MESSAGE)
-    val Warning = Value(JOptionPane.WARNING_MESSAGE)
-    val Question = Value(JOptionPane.QUESTION_MESSAGE)
-    val Plain = Value(JOptionPane.PLAIN_MESSAGE)
-  }
-  
-  /**
-   * The possible answers a user can select.
-   */
-  object Options extends Enumeration {
-    val Default = Value(JOptionPane.DEFAULT_OPTION)
-    val YesNo = Value(JOptionPane.YES_NO_OPTION)
-    val YesNoCancel = Value(JOptionPane.YES_NO_CANCEL_OPTION)
-    val OkCancel = Value(JOptionPane.OK_CANCEL_OPTION)
-  }
-  
-  /**
-   * The selected result of dialog.
-   */
-  object Result extends Enumeration {
-    val Yes = Value(JOptionPane.YES_OPTION)
-    val Ok = Yes
-    val No = Value(JOptionPane.NO_OPTION)
-    val Cancel = Value(JOptionPane.CANCEL_OPTION)
-    val Closed = Value(JOptionPane.CLOSED_OPTION)
-  }
-  
-  
-  def showConfirmation(parent: Component, message: String, title: String, 
-     optionType: Options.Value, messageType: Message.Value, icon: Icon): Result.Value =
-     Result(JOptionPane.showConfirmDialog(parent.peer, message, title, 
-                                   optionType.id, messageType.id, Swing.wrapIcon(icon)))
-  def showConfirmation(parent: Component, message: String, title: String, 
-     optionType: Options.Value): Result.Value =
-     Result(JOptionPane.showConfirmDialog(parent.peer, message, title, 
-                                   optionType.id))
-  
-  def showOptions(parent: Component, message: String, title: String, 
-     optionType: Options.Value, messageType: Message.Value, icon: Icon, 
-     entries: Seq[Any], initialEntry: Int): Result.Value = {
-       val r = JOptionPane.showOptionDialog(parent.peer, message, title, 
-                                   optionType.id, messageType.id, Swing.wrapIcon(icon), 
-                                   entries.map(_.asInstanceOf[AnyRef]).toArray, entries(initialEntry))
-       Result(r)
-     }
-
-  def showInput[A](parent: Component, message: String, title: String,
-                   messageType: Message.Value, icon: Icon, 
-     entries: Seq[A], initialEntry: A): Option[A] = {
-       val e = if (entries.isEmpty) null
-               else entries.map(_.asInstanceOf[AnyRef]).toArray
-       val r = JOptionPane.showInputDialog(parent.peer, message, title,
-       		                               messageType.id, Swing.wrapIcon(icon), 
-       		                               e, initialEntry)
-       Swing.toOption(r)
-  }
-  def showMessage(parent: Component, message: String, title: String, 
-     messageType: Message.Value, icon: Icon) {
-     JOptionPane.showMessageDialog(parent.peer, message, title, 
-                                   messageType.id, Swing.wrapIcon(icon))
-  }
-
-  def showMessage(parent: Component, message: String) {
-     JOptionPane.showMessageDialog(parent.peer, message)
-  }
-}
diff --git a/src/swing/scala/swing/EditorPane.scala b/src/swing/scala/swing/EditorPane.scala
new file mode 100644
index 0000000..042596b
--- /dev/null
+++ b/src/swing/scala/swing/EditorPane.scala
@@ -0,0 +1,31 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+package scala.swing
+
+import event._
+import javax.swing._
+import javax.swing.text._
+import java.awt.event._
+
+/**
+ * A text component that allows multiline text input and display.
+ *
+ * @see javax.swing.JEditorPane
+ */
+class EditorPane(contentType0: String, text0: String) extends TextComponent {
+	override lazy val peer: JEditorPane = new JEditorPane(contentType0, text0) with SuperMixin
+	def this() = this("text/plain", "")
+	
+	def contentType: String = peer.getContentType
+	def contentType_=(t: String) = peer.setContentType(t)
+	
+	def editorKit: EditorKit = peer.getEditorKit
+	def editorKit_=(k: EditorKit) = peer.setEditorKit(k)
+}
diff --git a/src/swing/scala/swing/FileChooser.scala b/src/swing/scala/swing/FileChooser.scala
index d0ca40e..0c4fae2 100644
--- a/src/swing/scala/swing/FileChooser.scala
+++ b/src/swing/scala/swing/FileChooser.scala
@@ -1,3 +1,13 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
 package scala.swing
 
 import java.io.File
@@ -37,9 +47,10 @@ class FileChooser(dir: File) {
   
   def this() = this(null)
   
-  def showOpenDialog(over: Component): Result.Value = Result(peer.showOpenDialog(over.peer))
-  def showSaveDialog(over: Component): Result.Value = Result(peer.showSaveDialog(over.peer))
-  def showDialog(over: Component, approveText: String): Result.Value = Result(peer.showDialog(over.peer, approveText))
+  import Swing._
+  def showOpenDialog(over: Component): Result.Value = Result(peer.showOpenDialog(nullPeer(over)))
+  def showSaveDialog(over: Component): Result.Value = Result(peer.showSaveDialog(nullPeer(over)))
+  def showDialog(over: Component, approveText: String): Result.Value = Result(peer.showDialog(nullPeer(over), approveText))
   
   def controlButtonsAreShown: Boolean = peer.getControlButtonsAreShown
   def controlButtonsAreShown_=(b: Boolean) { peer.setControlButtonsAreShown(b) }
@@ -47,7 +58,7 @@ class FileChooser(dir: File) {
   def title: String = peer.getDialogTitle
   def title_=(t: String) { peer.setDialogTitle(t) }
   
-  def accessory: Component = Component.wrapperFor(peer.getAccessory)
+  def accessory: Component = UIElement.cachedWrapper[Component](peer.getAccessory)
   def accessory_=(c: Component) { peer.setAccessory(c.peer) }
   
   def fileHidingEnabled: Boolean = peer.isFileHidingEnabled
@@ -63,7 +74,7 @@ class FileChooser(dir: File) {
   def selectedFiles_=(files: File*) { peer.setSelectedFiles(files.toArray) }
   
   def multiSelectionEnabled: Boolean = peer.isMultiSelectionEnabled  
-  def multiSelectionEnable_=(b: Boolean) { peer.setMultiSelectionEnabled(b) }
+  def multiSelectionEnabled_=(b: Boolean) { peer.setMultiSelectionEnabled(b) }
   
   def iconFor(f: File) = peer.getIcon(f)
   def descriptionFor(f: File) = peer.getDescription(f)
@@ -72,4 +83,31 @@ class FileChooser(dir: File) {
   def traversable(f: File) = peer.isTraversable(f)
   
   def acceptAllFileFilter = peer.getAcceptAllFileFilter
+  
+  /*peer.addPropertyChangeListener(new java.beans.PropertyChangeListener {
+    def propertyChange(e: java.beans.PropertyChangeEvent) {
+      import JFileChooser._
+      e.getPropertyName match {
+        case APPROVE_BUTTON_TEXT_CHANGED_PROPERTY =>
+        case ACCESSORY_CHANGED_PROPERTY =>
+        case APPROVE_BUTTON_MNEMONIC_CHANGED_PROPERTY =>
+        case APPROVE_BUTTON_TEXT_CHANGED_PROPERTY =>
+        case APPROVE_BUTTON_TOOL_TIP_TEXT_CHANGED_PROPERTY =>
+        case CHOOSABLE_FILE_FILTER_CHANGED_PROPERTY =>
+        case CONTROL_BUTTONS_ARE_SHOWN_CHANGED_PROPERTY =>
+        case DIALOG_TITLE_CHANGED_PROPERTY =>
+        case DIALOG_TYPE_CHANGED_PROPERTY =>
+        case DIRECTORY_CHANGED_PROPERTY =>
+        case FILE_FILTER_CHANGED_PROPERTY =>
+        case FILE_HIDING_CHANGED_PROPERTY =>
+        case FILE_SELECTION_MODE_CHANGED_PROPERTY =>
+        case FILE_SYSTEM_VIEW_CHANGED_PROPERTY =>
+        case FILE_VIEW_CHANGED_PROPERTY =>
+        case MULTI_SELECTION_ENABLED_CHANGED_PROPERTY =>
+        case SELECTED_FILE_CHANGED_PROPERTY =>
+        case SELECTED_FILES_CHANGED_PROPERTY =>
+        case _ => 
+      }
+    }
+  })*/
 }
diff --git a/src/swing/scala/swing/FlowPanel.scala b/src/swing/scala/swing/FlowPanel.scala
index e561c66..f823849 100644
--- a/src/swing/scala/swing/FlowPanel.scala
+++ b/src/swing/scala/swing/FlowPanel.scala
@@ -1,6 +1,17 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
 package scala.swing
 
 import java.awt.FlowLayout
+import javax.swing.JPanel
 
 object FlowPanel {
   object Alignment extends Enumeration {
@@ -18,11 +29,16 @@ object FlowPanel {
  * 
  * @see java.awt.FlowLayout
  */
-class FlowPanel(alignment: FlowPanel.Alignment.Value) extends Panel with SequentialContainer.Wrapper {
-  override lazy val peer: javax.swing.JPanel = new javax.swing.JPanel(new java.awt.FlowLayout(alignment.id))
-  def this() = this(FlowPanel.Alignment.Center)
+class FlowPanel(alignment: FlowPanel.Alignment.Value)(contents0: Component*) extends Panel with SequentialContainer.Wrapper {
+  override lazy val peer: JPanel = 
+    new JPanel(new java.awt.FlowLayout(alignment.id)) with SuperMixin
+  def this(contents0: Component*) = this(FlowPanel.Alignment.Center)(contents0: _*)
+  def this() = this(FlowPanel.Alignment.Center)()
+  
+  contents ++= contents0
+  
   private def layoutManager = peer.getLayout.asInstanceOf[java.awt.FlowLayout]
-    
+  
   def vGap: Int = layoutManager.getVgap
   def vGap_=(n: Int) { layoutManager.setVgap(n) }
   def hGap: Int = layoutManager.getHgap
diff --git a/src/swing/scala/swing/Font.scala b/src/swing/scala/swing/Font.scala
new file mode 100644
index 0000000..6eebd66
--- /dev/null
+++ b/src/swing/scala/swing/Font.scala
@@ -0,0 +1,70 @@
+package scala.swing
+
+/*object Font {  
+  def apply(fontFormat: Int, fontFile: java.io.File) = java.awt.Font.createFont(fontFormat, fontFile) 
+  def apply(fontFormat: Int, fontStream: java.io.InputStream) = java.awt.Font.createFont(fontFormat, fontStream) 
+  def decode(str: String) = java.awt.Font.decode(str)
+  
+  /* TODO: finish implementation
+  /**
+   * See [java.awt.Font.getFont].
+   */
+  def get(attributes: Map[_ <: java.text.AttributedCharacterIterator.Attribute, _]) = 
+    java.awt.Font.getFont(ImmutableMapWrapper(attributes))
+    
+  import java.{util => ju}
+  private case class ImmutableMapWrapper[A, B](underlying : Map[A, B])(m : ClassManifest[A]) extends ju.AbstractMap[A, B] {
+    self =>
+    override def size = underlying.size
+
+    override def put(k : A, v : B) = 
+      throw new UnsupportedOperationException("This is a wrapper that does not support mutation")
+    override def remove(k : AnyRef) = 
+      throw new UnsupportedOperationException("This is a wrapper that does not support mutation")
+    
+    override def entrySet : ju.Set[ju.Map.Entry[A, B]] = new ju.AbstractSet[ju.Map.Entry[A, B]] {
+      def size = self.size
+
+      def iterator = new ju.Iterator[ju.Map.Entry[A, B]] {
+        val ui = underlying.iterator
+        var prev : Option[A] = None
+        
+        def hasNext = ui.hasNext
+      
+        def next = {
+          val (k, v) = ui.next
+          prev = Some(k)
+          new ju.Map.Entry[A, B] {
+            def getKey = k
+            def getValue = v
+            def setValue(v1 : B) = self.put(k, v1)
+            override def equals(other : Any) = other match {
+              case e : ju.Map.Entry[_, _] => k == e.getKey && v == e.getValue
+              case _ => false
+            }
+          }
+        }
+        
+        def remove = prev match {
+          case Some(k) => val v = self.remove(k.asInstanceOf[AnyRef]) ; prev = None ; v
+          case _ => throw new IllegalStateException("next must be called at least once before remove")
+        }
+      }
+    }
+  }
+  */
+  
+  /**
+   * See [java.awt.Font.getFont].
+   */
+  def get(nm: String) = java.awt.Font.getFont(nm)
+  /**
+   * See [java.awt.Font.getFont].
+   */
+  def get(nm: String, font: Font) = java.awt.Font.getFont(nm, font)
+  
+  def Insets(x: Int, y: Int, width: Int, height: Int) = new Insets(x, y, width, height)
+  def Rectangle(x: Int, y: Int, width: Int, height: Int) = new Insets(x, y, width, height)
+  def Point(x: Int, y: Int) = new Point(x, y)
+  def Dimension(x: Int, y: Int) = new Dimension(x, y) 
+}*/
\ No newline at end of file
diff --git a/src/swing/scala/swing/FormattedTextField.scala b/src/swing/scala/swing/FormattedTextField.scala
index 0760555..7996e4f 100644
--- a/src/swing/scala/swing/FormattedTextField.scala
+++ b/src/swing/scala/swing/FormattedTextField.scala
@@ -1,8 +1,18 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
 package scala.swing
 
+import event._
 import javax.swing._
 import java.awt.event._
-import event._
 
 object FormattedTextField {
   /**
@@ -22,7 +32,7 @@ object FormattedTextField {
  * @see javax.swing.JFormattedTextField
  */
 class FormattedTextField(format: java.text.Format) extends TextComponent {
-  override lazy val peer: JFormattedTextField = new JFormattedTextField(format)
+  override lazy val peer: JFormattedTextField = new JFormattedTextField(format) with SuperMixin
   
   import FormattedTextField._
  
@@ -31,4 +41,4 @@ class FormattedTextField(format: java.text.Format) extends TextComponent {
   
   def focusLostBehavior: FocusLostBehavior.Value = FocusLostBehavior(peer.getFocusLostBehavior)
   def focusLostBehavior_=(b: FocusLostBehavior.Value) { peer.setFocusLostBehavior(b.id) }
-}
\ No newline at end of file
+}
diff --git a/src/swing/scala/swing/Frame.scala b/src/swing/scala/swing/Frame.scala
deleted file mode 100644
index 3e37f28..0000000
--- a/src/swing/scala/swing/Frame.scala
+++ /dev/null
@@ -1,52 +0,0 @@
-package scala.swing
-
-import java.awt.{Image, Point}
-import javax.swing._
-import event._
-
-/**
- * A window with decoration such as a title, border, and action buttons.
- * 
- * @see javax.swing.JFrame
- */
-class Frame extends UIElement with RootPanel with Publisher {
-  override lazy val peer: JFrame = new JFrame
-  def title: String = peer.getTitle
-  def title_=(s: String) = peer.setTitle(s)
-
-  override def contents_=(c: Component) {
-    super.contents_=(c)
-    peer.pack() // pack also validates, which is generally required after an add
-  }
-  def defaultButton: Option[Button] = 
-    Swing.toOption(peer.getRootPane.getDefaultButton).map(Component.wrapperFor(_))
-  def defaultButton_=(b: Button) { 
-    peer.getRootPane.setDefaultButton(b.peer) 
-  }
-  def defaultButton_=(b: Option[Button]) { 
-    peer.getRootPane.setDefaultButton(Swing.toNull(b.map(_.peer))) 
-  }
-  
-  def dispose() { peer.dispose() }
-  
-  def pack(): this.type = { peer.pack(); this }
-  
-  def menuBar: MenuBar = Component.wrapperFor(peer.getJMenuBar)
-  def menuBar_=(m: MenuBar) = peer.setJMenuBar(m.peer)
-  
-  def setLocationRelativeTo(c: UIElement) { peer.setLocationRelativeTo(c.peer) }
-  def location_=(p: Point) { peer.setLocation(p) }
-  
-  def iconImage: Image = peer.getIconImage
-  def iconImage_=(i: Image) { peer.setIconImage(i) }
-  
-  peer.addWindowListener(new java.awt.event.WindowListener {
-    def windowActivated(e: java.awt.event.WindowEvent) { publish(WindowActivated(Frame.this)) }
-    def windowClosed(e: java.awt.event.WindowEvent) { publish(WindowClosed(Frame.this)) }
-    def windowClosing(e: java.awt.event.WindowEvent) { publish(WindowClosing(Frame.this)) }
-    def windowDeactivated(e: java.awt.event.WindowEvent) { publish(WindowDeactivated(Frame.this)) }
-    def windowDeiconified(e: java.awt.event.WindowEvent) { publish(WindowDeiconified(Frame.this)) }
-    def windowIconified(e: java.awt.event.WindowEvent) { publish(WindowIconified(Frame.this)) }
-    def windowOpened(e: java.awt.event.WindowEvent) { publish(WindowOpened(Frame.this)) }
-  })
-}
diff --git a/src/swing/scala/swing/GUIApplication.scala b/src/swing/scala/swing/GUIApplication.scala
index ab5f7c7..95cc8cb 100644
--- a/src/swing/scala/swing/GUIApplication.scala
+++ b/src/swing/scala/swing/GUIApplication.scala
@@ -1,23 +1,30 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
 package scala.swing
 
-import javax.swing._
 import event.Event
+import javax.swing._
 
-class GUIApplication {
-  //def defaultLookAndFeelDecorated: Boolean = true
+/**
+ * Convenience class with utility methods for GUI applications.
+ */
+ at deprecated("Use SwingApplication instead") class GUIApplication {
 
-  def init() = {
-    //UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName())
-    //JFrame.setDefaultLookAndFeelDecorated(defaultLookAndFeelDecorated)
-  }
+  /**
+   * Called before the GUI is created. Override to customize.
+   */
+  def init() {}
 
   /**
    * Initializes the framework and runs the given program.
    */
-  def run(prog: => Unit): Unit =
-    SwingUtilities.invokeLater {
-      new Runnable() { 
-        def run() = { init(); prog }
-      }
-    }
+  def run(prog: => Unit) = Swing.onEDT { init(); prog }
 }
diff --git a/src/swing/scala/swing/GridBagPanel.scala b/src/swing/scala/swing/GridBagPanel.scala
index f349585..e7d38e2 100644
--- a/src/swing/scala/swing/GridBagPanel.scala
+++ b/src/swing/scala/swing/GridBagPanel.scala
@@ -1,6 +1,16 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
 package scala.swing
 
-import java.awt.{Insets, GridBagConstraints}
+import java.awt.{GridBagConstraints, GridBagLayout}
 
 
 object GridBagPanel {
@@ -19,7 +29,7 @@ object GridBagPanel {
     val SouthWest = Value(GridBagConstraints.SOUTHWEST)
     val West = Value(GridBagConstraints.WEST)
     val NorthWest = Value(GridBagConstraints.NORTHWEST)
-    val CENTER = Value(GridBagConstraints.CENTER)
+    val Center = Value(GridBagConstraints.CENTER)
     
     val PageStart = Value(GridBagConstraints.PAGE_START)
     val PageEnd = Value(GridBagConstraints.PAGE_END)
@@ -39,10 +49,10 @@ object GridBagPanel {
  * @see java.awt.GridBagLayout
  */
 class GridBagPanel extends Panel with LayoutContainer {
-  override lazy val peer = new javax.swing.JPanel(new java.awt.GridBagLayout)
+  override lazy val peer = new javax.swing.JPanel(new GridBagLayout) with SuperMixin
   import GridBagPanel._
   
-  private def layoutManager = peer.getLayout.asInstanceOf[java.awt.GridBagLayout]
+  private def layoutManager = peer.getLayout.asInstanceOf[GridBagLayout]
 
   /**
    * Convenient conversion from xy-coords given as pairs to 
diff --git a/src/swing/scala/swing/GridPanel.scala b/src/swing/scala/swing/GridPanel.scala
index 893d28f..2fb8b5a 100644
--- a/src/swing/scala/swing/GridPanel.scala
+++ b/src/swing/scala/swing/GridPanel.scala
@@ -1,3 +1,13 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
 package scala.swing
 
 object GridPanel {
@@ -10,7 +20,8 @@ object GridPanel {
  * @see java.awt.GridLayout
  */
 class GridPanel(rows0: Int, cols0: Int) extends Panel with SequentialContainer.Wrapper {
-  override lazy val peer = new javax.swing.JPanel(new java.awt.GridLayout(rows0, cols0))
+  override lazy val peer = 
+    new javax.swing.JPanel(new java.awt.GridLayout(rows0, cols0)) with SuperMixin
   
   /*type Constraints = (Int, Int)
     
diff --git a/src/swing/scala/swing/Key.scala b/src/swing/scala/swing/Key.scala
deleted file mode 100644
index 7a127c1..0000000
--- a/src/swing/scala/swing/Key.scala
+++ /dev/null
@@ -1,195 +0,0 @@
-package scala.swing
-
-object Key extends Enumeration {
-  import java.awt.event.KeyEvent._
-
-  val Enter = Value(VK_ENTER)
-  val BackSpace = Value(VK_BACK_SPACE)
-  val Tab = Value(VK_TAB)
-  val Cancel = Value(VK_CANCEL)
-  val Clear = Value(VK_CLEAR)
-  val Shift = Value(VK_SHIFT)
-  val Control = Value(VK_CONTROL)
-  val Alt = Value(VK_ALT)
-  val Pause = Value(VK_PAUSE)
-  val CapsLock = Value(VK_CAPS_LOCK)
-  val Escape = Value(VK_ESCAPE)
-  val Space = Value(VK_SPACE)
-  val PageUp = Value(VK_PAGE_UP)
-  val PageDown = Value(VK_PAGE_DOWN)
-  val End = Value(VK_END)
-  val Home = Value(VK_HOME)
-  val Left = Value(VK_LEFT)
-  val Up = Value(VK_UP)
-  val Right = Value(VK_RIGHT)
-  val Down = Value(VK_DOWN)
-  val Comma = Value(VK_COMMA)
-  val Minus = Value(VK_MINUS)
-  val Period = Value(VK_PERIOD)
-  val Slash = Value(VK_SLASH)
-  val Key0 = Value(VK_0)
-  val Key1 = Value(VK_1)
-  val Key2 = Value(VK_2)
-  val Key3 = Value(VK_3)
-  val Key4 = Value(VK_4)
-  val Key5 = Value(VK_5)
-  val Key6 = Value(VK_6)
-  val Key7 = Value(VK_7)
-  val Key8 = Value(VK_8)
-  val Key9 = Value(VK_9)
-  val Semicolon = Value(VK_SEMICOLON)
-  val Equals = Value(VK_EQUALS)
-  val A = Value(VK_A)
-  val B = Value(VK_B)
-  val C = Value(VK_C)
-  val D = Value(VK_D)
-  val E = Value(VK_E)
-  val F = Value(VK_F)
-  val G = Value(VK_G)
-  val H = Value(VK_H)
-  val I = Value(VK_I)
-  val J = Value(VK_J)
-  val K = Value(VK_K)
-  val L = Value(VK_L)
-  val M = Value(VK_M)
-  val N = Value(VK_N)
-  val O = Value(VK_O)
-  val P = Value(VK_P)
-  val Q = Value(VK_Q)
-  val R = Value(VK_R)
-  val S = Value(VK_S)
-  val T = Value(VK_T)
-  val U = Value(VK_U)
-  val V = Value(VK_V)
-  val W = Value(VK_W)
-  val X = Value(VK_X)
-  val Y = Value(VK_Y)
-  val Z = Value(VK_Z)
-  val OpenBracket = Value(VK_OPEN_BRACKET)
-  val BackSlash = Value(VK_BACK_SLASH)
-  val CloseBracket = Value(VK_CLOSE_BRACKET)
-  val Numpad0 = Value(VK_NUMPAD0)
-  val Numpad1 = Value(VK_NUMPAD1)
-  val Numpad2 = Value(VK_NUMPAD2)
-  val Numpad3 = Value(VK_NUMPAD3)
-  val Numpad4 = Value(VK_NUMPAD4)
-  val Numpad5 = Value(VK_NUMPAD5)
-  val Numpad6 = Value(VK_NUMPAD6)
-  val Numpad7 = Value(VK_NUMPAD7)
-  val Numpad8 = Value(VK_NUMPAD8)
-  val Numpad9 = Value(VK_NUMPAD9)
-  val Multiply = Value(VK_MULTIPLY)
-  val Add = Value(VK_ADD)
-  val Separater = Value(VK_SEPARATER)
-  val Separator = Value(VK_SEPARATOR)
-  val Subtract = Value(VK_SUBTRACT)
-  val Decimal = Value(VK_DECIMAL)
-  val Divide = Value(VK_DIVIDE)
-  val Delete = Value(VK_DELETE)
-  val NumLock = Value(VK_NUM_LOCK)
-  val ScrollLock = Value(VK_SCROLL_LOCK)
-  val F1 = Value(VK_F1)
-  val F2 = Value(VK_F2)
-  val F3 = Value(VK_F3)
-  val F4 = Value(VK_F4)
-  val F5 = Value(VK_F5)
-  val F6 = Value(VK_F6)
-  val F7 = Value(VK_F7)
-  val F8 = Value(VK_F8)
-  val F9 = Value(VK_F9)
-  val F10 = Value(VK_F10)
-  val F11 = Value(VK_F11)
-  val F12 = Value(VK_F12)
-  val F13 = Value(VK_F13)
-  val F14 = Value(VK_F14)
-  val F15 = Value(VK_F15)
-  val F16 = Value(VK_F16)
-  val F17 = Value(VK_F17)
-  val F18 = Value(VK_F18)
-  val F19 = Value(VK_F19)
-  val F20 = Value(VK_F20)
-  val F21 = Value(VK_F21)
-  val F22 = Value(VK_F22)
-  val F23 = Value(VK_F23)
-  val F24 = Value(VK_F24)
-  val Printscreen = Value(VK_PRINTSCREEN)
-  val Insert = Value(VK_INSERT)
-  val Help = Value(VK_HELP)
-  val Meta = Value(VK_META)
-  val BackQuote = Value(VK_BACK_QUOTE)
-  val Quote = Value(VK_QUOTE)
-  val KpUp = Value(VK_KP_UP)
-  val KpDown = Value(VK_KP_DOWN)
-  val KpLeft = Value(VK_KP_LEFT)
-  val KpRight = Value(VK_KP_RIGHT)
-  val DeadGrave = Value(VK_DEAD_GRAVE)
-  val DeadAcute = Value(VK_DEAD_ACUTE)
-  val DeadCircumflex = Value(VK_DEAD_CIRCUMFLEX)
-  val DeadTilde = Value(VK_DEAD_TILDE)
-  val DeadMacron = Value(VK_DEAD_MACRON)
-  val DeadBreve = Value(VK_DEAD_BREVE)
-  val DeadAbovedot = Value(VK_DEAD_ABOVEDOT)
-  val DeadDiaeresis = Value(VK_DEAD_DIAERESIS)
-  val DeadAbovering = Value(VK_DEAD_ABOVERING)
-  val DeadDoubleacute = Value(VK_DEAD_DOUBLEACUTE)
-  val DeadCaron = Value(VK_DEAD_CARON)
-  val DeadCedilla = Value(VK_DEAD_CEDILLA)
-  val DeadOgonek = Value(VK_DEAD_OGONEK)
-  val DeadIota = Value(VK_DEAD_IOTA)
-  val DeadVoicedSound = Value(VK_DEAD_VOICED_SOUND)
-  val DeadSemivoicedSound = Value(VK_DEAD_SEMIVOICED_SOUND)
-  val Ampersand = Value(VK_AMPERSAND)
-  val Asterisk = Value(VK_ASTERISK)
-  val Quotedbl = Value(VK_QUOTEDBL)
-  val Less = Value(VK_LESS)
-  val Greater = Value(VK_GREATER)
-  val Braceleft = Value(VK_BRACELEFT)
-  val Braceright = Value(VK_BRACERIGHT)
-  val At = Value(VK_AT)
-  val Colon = Value(VK_COLON)
-  val Circumflex = Value(VK_CIRCUMFLEX)
-  val Dollar = Value(VK_DOLLAR)
-  val EuroSign = Value(VK_EURO_SIGN)
-  val ExclamationMark = Value(VK_EXCLAMATION_MARK)
-  val InvertedExclamationMark = Value(VK_INVERTED_EXCLAMATION_MARK)
-  val LeftParenthesis = Value(VK_LEFT_PARENTHESIS)
-  val NumberSign = Value(VK_NUMBER_SIGN)
-  val Plus = Value(VK_PLUS)
-  val RightParenthesis = Value(VK_RIGHT_PARENTHESIS)
-  val Underscore = Value(VK_UNDERSCORE)
-  val Windows = Value(VK_WINDOWS)
-  val ContextMenu = Value(VK_CONTEXT_MENU)
-  val Final = Value(VK_FINAL)
-  val Convert = Value(VK_CONVERT)
-  val Nonconvert = Value(VK_NONCONVERT)
-  val Accept = Value(VK_ACCEPT)
-  val Modechange = Value(VK_MODECHANGE)
-  val Kana = Value(VK_KANA)
-  val Kanji = Value(VK_KANJI)
-  val Alphanumeric = Value(VK_ALPHANUMERIC)
-  val Katakana = Value(VK_KATAKANA)
-  val Hiragana = Value(VK_HIRAGANA)
-  val FullWidth = Value(VK_FULL_WIDTH)
-  val HalfWidth = Value(VK_HALF_WIDTH)
-  val RomanCharacters = Value(VK_ROMAN_CHARACTERS)
-  val AllCandidates = Value(VK_ALL_CANDIDATES)
-  val PreviousCandidate = Value(VK_PREVIOUS_CANDIDATE)
-  val CodeInput = Value(VK_CODE_INPUT)
-  val JapaneseKatakana = Value(VK_JAPANESE_KATAKANA)
-  val JapaneseHiragana = Value(VK_JAPANESE_HIRAGANA)
-  val JapaneseRoman = Value(VK_JAPANESE_ROMAN)
-  val KanaLock = Value(VK_KANA_LOCK)
-  val InputMethodOnOff = Value(VK_INPUT_METHOD_ON_OFF)
-  val Cut = Value(VK_CUT)
-  val Copy = Value(VK_COPY)
-  val Paste = Value(VK_PASTE)
-  val Undo = Value(VK_UNDO)
-  val Again = Value(VK_AGAIN)
-  val Find = Value(VK_FIND)
-  val Props = Value(VK_PROPS)
-  val Stop = Value(VK_STOP)
-  val Compose = Value(VK_COMPOSE)
-  val AltGraph = Value(VK_ALT_GRAPH)
-  val Begin = Value(VK_BEGIN)
-  val Undefined = Value(VK_UNDEFINED)
-}
diff --git a/src/swing/scala/swing/Label.scala b/src/swing/scala/swing/Label.scala
index 9d6f495..177f71e 100644
--- a/src/swing/scala/swing/Label.scala
+++ b/src/swing/scala/swing/Label.scala
@@ -1,3 +1,13 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
 package scala.swing
 
 import javax.swing._
@@ -9,7 +19,8 @@ import scala.swing.Swing._
  * @see javax.swing.JLabel
  */
 class Label(text0: String, icon0: Icon, align: Alignment.Value) extends Component {
-  override lazy val peer: JLabel = new JLabel(text0, toNullIcon(icon0), align.id) with SuperMixin
+  override lazy val peer: JLabel = 
+    new JLabel(text0, toNullIcon(icon0), align.id) with SuperMixin
   
   def this() = this("", EmptyIcon, Alignment.Center)
   def this(s: String) = this(s, EmptyIcon, Alignment.Center)
diff --git a/src/swing/scala/swing/LayoutContainer.scala b/src/swing/scala/swing/LayoutContainer.scala
index f749b85..b4519be 100644
--- a/src/swing/scala/swing/LayoutContainer.scala
+++ b/src/swing/scala/swing/LayoutContainer.scala
@@ -1,20 +1,37 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
 package scala.swing
 
 import javax.swing.JComponent
 import scala.collection.mutable.Map
 
-/**
- * A container that associates layout constraints with its children.
- * See GridBagPanel for an example.
+/** <p>
+ *    A container that associates layout constraints of member type
+ *    <code>Constraints</code> with its children. See <code>GridBagPanel</code>
+ *    for an example container with custom constraints. 
+ *  </p>
+ *
+ *  @note [Java Swing] In scala.swing, panels and layout managers are 
+ *  combined into subclasses of this base class. This approach allows for typed
+ *  component constraints.
  */
 trait LayoutContainer extends Container.Wrapper {
   /**
-   * The specific type of constraints.
+   * The type of component constraints for this container.
    */
   type Constraints <: AnyRef
   
   /**
-   * Used to obtain the constraints from a Swing layout manager.
+   * Obtains the constraints for the given component from the underlying
+   * Swing layout manager.
    */
   protected def constraintsFor(c: Component): Constraints
   /**
@@ -23,26 +40,37 @@ trait LayoutContainer extends Container.Wrapper {
    */
   protected def areValid(c: Constraints): (Boolean, String)
   /**
-   * Adds the component to the layout manager and the peer.
+   * Adds a component with the given constraints to the underlying layout 
+   * manager and the component peer. This method needs to interact properly 
+   * with method `constraintsFor`, i.e., it might need to remove previously
+   * held components in order to maintain layout consistency. See `BorderPanel`
+   * for an example.
    */
   protected def add(comp: Component, c: Constraints)
   
   /**
    * A map of components to the associated layout constraints.
-   * Any element in this map is automatically added to this panel.
+   * Any element in this map is automatically added to the contents of this 
+   * panel. Therefore, specifying the layout of a component via 
+   * 
+   * layout(myComponent) = myConstraints
+   * 
+   * also ensures that myComponent is properly added to this container.
    */
   def layout: Map[Component, Constraints] = new Map[Component, Constraints] {
-    def -=(c: Component) { _contents -= c }
-    def update(c: Component, l: Constraints) {
+    def -= (c: Component): this.type = { _contents -= c; this }
+    def += (cl: (Component, Constraints)): this.type = { update(cl._1, cl._2); this }
+    override def update (c: Component, l: Constraints) {
       val (v, msg) = areValid(l)
-      if (!v) throw new IllegalArgumentException(msg) 
+      if (!v) throw new IllegalArgumentException(msg)
       add(c, l)
+      this
     }
-    def get(c: Component) = Swing.toOption(constraintsFor(c))
-    def size = peer.getComponentCount
-    def elements: Iterator[(Component, Constraints)] = 
-      Iterator.range(0,size).map { c => 
-        val comp = Component.wrapperFor[Component](peer.getComponent(c).asInstanceOf[JComponent])
+    def get(c: Component) = Option(constraintsFor(c))
+    override def size = peer.getComponentCount
+    def iterator: Iterator[(Component, Constraints)] = 
+      peer.getComponents.iterator.map { c => 
+        val comp = UIElement.cachedWrapper[Component](c.asInstanceOf[JComponent])
         (comp, constraintsFor(comp))
       }
   }
diff --git a/src/swing/scala/swing/ListView.scala b/src/swing/scala/swing/ListView.scala
index 354c572..a06772a 100644
--- a/src/swing/scala/swing/ListView.scala
+++ b/src/swing/scala/swing/ListView.scala
@@ -1,9 +1,18 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
 package scala.swing
 
+import event._
 import javax.swing._
 import javax.swing.event._
-import event._
-import java.awt.Color
 
 object ListView {
   /**
@@ -26,8 +35,8 @@ object ListView {
      * Wrapper for <code>javax.swing.ListCellRenderer<code>s
      */
   	class Wrapped[A](override val peer: ListCellRenderer) extends Renderer[A] {
-  	  def componentFor(list: ListView[_], isSelected: Boolean, hasFocus: Boolean, a: A, index: Int) = {
-        Component.wrap(peer.getListCellRendererComponent(list.peer, a, index, isSelected, hasFocus).asInstanceOf[JComponent])
+  	  def componentFor(list: ListView[_], isSelected: Boolean, focused: Boolean, a: A, index: Int) = {
+        Component.wrap(peer.getListCellRendererComponent(list.peer, a, index, isSelected, focused).asInstanceOf[JComponent])
       }
   	}
    
@@ -46,8 +55,8 @@ object ListView {
      * </code>
      */
     def apply[A,B](f: A => B)(implicit renderer: Renderer[B]): Renderer[A] = new Renderer[A] {
-      def componentFor(list: ListView[_], isSelected: Boolean, hasFocus: Boolean, a: A, index: Int): Component = 
-        renderer.componentFor(list, isSelected, hasFocus, f(a), index)                                  
+      def componentFor(list: ListView[_], isSelected: Boolean, focused: Boolean, a: A, index: Int): Component = 
+        renderer.componentFor(list, isSelected, focused, f(a), index)                                  
     }
   }
   
@@ -61,10 +70,10 @@ object ListView {
    */
   abstract class Renderer[-A] {
     def peer: ListCellRenderer = new ListCellRenderer {
-      def getListCellRendererComponent(list: JList, a: Any, index: Int, isSelected: Boolean, hasFocus: Boolean) = 
-        componentFor(ListView.wrap[A](list), isSelected, hasFocus, a.asInstanceOf[A], index).peer
+      def getListCellRendererComponent(list: JList, a: Any, index: Int, isSelected: Boolean, focused: Boolean) = 
+        componentFor(ListView.wrap[A](list), isSelected, focused, a.asInstanceOf[A], index).peer
     }
-    def componentFor(list: ListView[_], isSelected: Boolean, hasFocus: Boolean, a: A, index: Int): Component
+    def componentFor(list: ListView[_], isSelected: Boolean, focused: Boolean, a: A, index: Int): Component
   }
   
   /**
@@ -84,7 +93,7 @@ object ListView {
      * This includes foreground and background colors, as well as colors 
      * of item selections.
      */
-    def preConfigure(list: ListView[_], isSelected: Boolean, hasFocus: Boolean, a: A, index: Int) {
+    def preConfigure(list: ListView[_], isSelected: Boolean, focused: Boolean, a: A, index: Int) {
       if (isSelected) {
         component.background = list.selectionBackground
         component.foreground = list.selectionForeground
@@ -96,14 +105,14 @@ object ListView {
     /**
      * Configuration that is specific to the component and this renderer.
      */
-    def configure(list: ListView[_], isSelected: Boolean, hasFocus: Boolean, a: A, index: Int)
+    def configure(list: ListView[_], isSelected: Boolean, focused: Boolean, a: A, index: Int)
 
     /**
      * Configures the component before returning it.
      */
-    def componentFor(list: ListView[_], isSelected: Boolean, hasFocus: Boolean, a: A, index: Int): Component = {
-      preConfigure(list, isSelected, hasFocus, a, index)
-      configure(list, isSelected, hasFocus, a, index)
+    def componentFor(list: ListView[_], isSelected: Boolean, focused: Boolean, a: A, index: Int): Component = {
+      preConfigure(list, isSelected, focused, a, index)
+      configure(list, isSelected, focused, a, index)
       component
     }
   }
@@ -115,10 +124,9 @@ object ListView {
    */
   implicit object GenericRenderer extends Renderer[Any] {
     override lazy val peer: ListCellRenderer = new DefaultListCellRenderer
-    def componentFor(list: ListView[_], isSelected: Boolean, hasFocus: Boolean, a: Any, index: Int): Component = {
-      val c = peer.getListCellRendererComponent(list.peer, a, index, isSelected, hasFocus).asInstanceOf[JComponent]
-      val w = Component.wrapperFor[Component](c)
-      if (w eq null) Component.wrap(c) else w
+    def componentFor(list: ListView[_], isSelected: Boolean, focused: Boolean, a: Any, index: Int): Component = {
+      val c = peer.getListCellRendererComponent(list.peer, a, index, isSelected, focused).asInstanceOf[JComponent]
+      Component.wrap(c)
     }
   }
 }
@@ -134,7 +142,7 @@ object ListView {
  */
 class ListView[A] extends Component {
   import ListView._
-  override lazy val peer: JList = new JList
+  override lazy val peer: JList = new JList with SuperMixin
   
   def this(items: Seq[A]) = {
     this()
@@ -148,12 +156,12 @@ class ListView[A] extends Component {
   
   def listData: Seq[A] = peer.getModel match {
     case model: ModelWrapper => model.items
-    case model @ _ => new Seq[A] {
+    case model @ _ => new Seq[A] { selfSeq =>
      def length = model.getSize
-     def elements = new Iterator[A] {
+     def iterator = new Iterator[A] {
        var idx = 0
        def next = { idx += 1; apply(idx-1) }
-       def hasNext = idx < length
+       def hasNext = idx < selfSeq.length
      }
      def apply(n: Int) = model.getElementAt(n).asInstanceOf[A]
     }
@@ -171,31 +179,39 @@ class ListView[A] extends Component {
    */
   object selection extends Publisher {
     protected abstract class Indices[A](a: =>Seq[A]) extends scala.collection.mutable.Set[A] { 
-      def -=(n: A) 
-      def +=(n: A) 
+      def -=(n: A): this.type 
+      def +=(n: A): this.type
       def contains(n: A) = a.contains(n)
-      def size = a.length
-      def elements = a.elements
+      override def size = a.length
+      def iterator = a.iterator
     }
+    
+    def leadIndex: Int = peer.getSelectionModel.getLeadSelectionIndex
+    def anchorIndex: Int = peer.getSelectionModel.getAnchorSelectionIndex
   
     /**
      * The indices of the currently selected items.
      */
     object indices extends Indices(peer.getSelectedIndices) {
-      def -=(n: Int) { peer.removeSelectionInterval(n,n) }
-      def +=(n: Int) { peer.addSelectionInterval(n,n) }
-      
+      def -=(n: Int): this.type = { peer.removeSelectionInterval(n,n); this }
+      def +=(n: Int): this.type = { peer.addSelectionInterval(n,n); this }
+      @deprecated("Use ListView.selection.leadIndex")
       def leadIndex: Int = peer.getSelectionModel.getLeadSelectionIndex
+      @deprecated("Use ListView.selection.anchorIndex")
       def anchorIndex: Int = peer.getSelectionModel.getAnchorSelectionIndex
     }
+    
+    @deprecated("Use ListView.selectIndices") 
     def selectIndices(ind: Int*) = peer.setSelectedIndices(ind.toArray)
     
     /**
      * The currently selected items.
      */
-    object items extends SeqProxy[A] {
+    object items extends scala.collection.SeqProxy[A] {
       def self = peer.getSelectedValues.map(_.asInstanceOf[A])
+      @deprecated("Use ListView.selection.leadIndex")
       def leadIndex: Int = peer.getSelectionModel.getLeadSelectionIndex
+      @deprecated("Use ListView.selection.anchorIndex")
       def anchorIndex: Int = peer.getSelectionModel.getAnchorSelectionIndex
     }
     
@@ -204,7 +220,7 @@ class ListView[A] extends Component {
 
     peer.getSelectionModel.addListSelectionListener(new ListSelectionListener {
       def valueChanged(e: javax.swing.event.ListSelectionEvent) {
-        publish(ListSelectionChanged(ListView.this, e.getFirstIndex to e.getLastIndex, e.getValueIsAdjusting))
+        publish(new ListSelectionChanged(ListView.this, e.getFirstIndex to e.getLastIndex, e.getValueIsAdjusting))
       }
     })
 
@@ -228,9 +244,11 @@ class ListView[A] extends Component {
   def selectionBackground: Color = peer.getSelectionBackground
   def selectionBackground_=(c: Color) = peer.setSelectionBackground(c)
   
+  def selectIndices(ind: Int*) = peer.setSelectedIndices(ind.toArray)
+  
   peer.getModel.addListDataListener(new ListDataListener {
     def contentsChanged(e: ListDataEvent) { publish(ListChanged(ListView.this)) }
     def intervalRemoved(e: ListDataEvent) { publish(ListElementsRemoved(ListView.this, e.getIndex0 to e.getIndex1)) }
     def intervalAdded(e: ListDataEvent) { publish(ListElementsAdded(ListView.this, e.getIndex0 to e.getIndex1)) }
   })
-}
\ No newline at end of file
+}
diff --git a/src/swing/scala/swing/MainFrame.scala b/src/swing/scala/swing/MainFrame.scala
index 0d47967..415301f 100644
--- a/src/swing/scala/swing/MainFrame.scala
+++ b/src/swing/scala/swing/MainFrame.scala
@@ -1,3 +1,13 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
 package scala.swing
 
 import event._
@@ -7,7 +17,5 @@ import event._
  * framework and quits the application when closed.
  */
 class MainFrame extends Frame {
-  reactions += {
-    case WindowClosing(_) => System.exit(1)
-  }
+  override def closeOperation { System.exit(0) }
 }
diff --git a/src/swing/scala/swing/Menu.scala b/src/swing/scala/swing/Menu.scala
index e603f2a..1cb5ab4 100644
--- a/src/swing/scala/swing/Menu.scala
+++ b/src/swing/scala/swing/Menu.scala
@@ -1,20 +1,34 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
 package scala.swing
 
 import scala.collection.mutable._
 import javax.swing._
 
+object MenuBar {
+  case object NoMenuBar extends MenuBar
+}
+
 /**
  * A menu bar. Each window can contain at most one. Contains a number of menus.
  * 
  * @see javax.swing.JMenuBar
  */
 class MenuBar extends Component with SequentialContainer.Wrapper {
-  override lazy val peer: JMenuBar = new JMenuBar
+  override lazy val peer: JMenuBar = new JMenuBar with SuperMixin
   
   def menus: Seq[Menu] = contents.filter(_.isInstanceOf[Menu]).map(_.asInstanceOf[Menu])
   
   // Not implemented by Swing
-  //def helpMenu: Menu = Component.wrapperFor(peer.getHelpMenu)
+  //def helpMenu: Menu = UIElement.cachedWrapper(peer.getHelpMenu)
   //def helpMenu_=(m: Menu) { peer.setHelpMenu(m.peer) }
 }
 
diff --git a/src/swing/scala/swing/Orientable.scala b/src/swing/scala/swing/Orientable.scala
index c350b7a..8aac30f 100644
--- a/src/swing/scala/swing/Orientable.scala
+++ b/src/swing/scala/swing/Orientable.scala
@@ -1,8 +1,24 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
 package scala.swing
 
+object Orientable {
+  trait Wrapper extends Oriented.Wrapper with Orientable {
+    def orientation_=(o: Orientation.Value) { peer.setOrientation(o.id) }
+  }
+}
+
 /**
  * An <code>Oriented</code> whose orientation can be changed.
  */
 trait Orientable extends Oriented {
-  def orientation_=(o: Orientation.Value) { peer.setOrientation(o.id) }
+  def orientation_=(o: Orientation.Value)
 }
diff --git a/src/swing/scala/swing/Orientation.scala b/src/swing/scala/swing/Orientation.scala
index 6657155..e017b23 100644
--- a/src/swing/scala/swing/Orientation.scala
+++ b/src/swing/scala/swing/Orientation.scala
@@ -1,8 +1,19 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
 package scala.swing
 
-import javax.swing.SwingConstants._
+import java.awt.Adjustable._
 
 object Orientation extends Enumeration {
   val Horizontal = Value(HORIZONTAL)
   val Vertical = Value(VERTICAL)
+  val NoOrientation = Value(NO_ORIENTATION)
 }
diff --git a/src/swing/scala/swing/Oriented.scala b/src/swing/scala/swing/Oriented.scala
index 86108e2..cb1bdd5 100644
--- a/src/swing/scala/swing/Oriented.scala
+++ b/src/swing/scala/swing/Oriented.scala
@@ -1,12 +1,34 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
 package scala.swing
 
+object Oriented {
+  trait Wrapper extends Oriented {
+    def peer: OrientedMixin
+    
+    /*
+     * Need to revert to structural type, since scroll bars are oriented 
+     * and these are created by scroll panes. Shouldn't be a bootleneck.
+     */
+    protected type OrientedMixin = {
+      def getOrientation(): Int
+      def setOrientation(n: Int) 
+    }
+    def orientation: Orientation.Value = Orientation(peer.getOrientation)
+  }
+}
+
 /**
  * Something that can have an orientation.
  */
 trait Oriented {
-  def peer: javax.swing.JComponent { 
-    def getOrientation(): Int
-    def setOrientation(n: Int) 
-  }
-  def orientation: Orientation.Value = Orientation(peer.getOrientation)
+  def orientation: Orientation.Value
 }
diff --git a/src/swing/scala/swing/Panel.scala b/src/swing/scala/swing/Panel.scala
index 579d232..1671915 100644
--- a/src/swing/scala/swing/Panel.scala
+++ b/src/swing/scala/swing/Panel.scala
@@ -1,7 +1,17 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
 package scala.swing
 
 /**
- * A component that can contain other components, such as layout panels.
+ * A component that can contain other components.
  *
  * @see javax.swing.JPanel
  */
diff --git a/src/swing/scala/swing/PasswordField.scala b/src/swing/scala/swing/PasswordField.scala
index 6eec232..7c18b92 100644
--- a/src/swing/scala/swing/PasswordField.scala
+++ b/src/swing/scala/swing/PasswordField.scala
@@ -1,8 +1,18 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
 package scala.swing
 
+import event._
 import javax.swing._
 import java.awt.event._
-import event._
 
 /**
  * A password field, that displays a replacement character for each character in the password. 
@@ -10,7 +20,7 @@ import event._
  * @see javax.swing.JPasswordField
  */
 class PasswordField(text0: String, columns0: Int) extends TextField(text0, columns0) {
-  override lazy val peer: JPasswordField = new JPasswordField(text0, columns0)
+  override lazy val peer: JPasswordField = new JPasswordField(text0, columns0) with SuperMixin
   def this(text: String) = this(text, 0)
   def this(columns: Int) = this("", columns)
   def this() = this("")
diff --git a/src/swing/scala/swing/ProgressBar.scala b/src/swing/scala/swing/ProgressBar.scala
index 62697b0..94347e7 100644
--- a/src/swing/scala/swing/ProgressBar.scala
+++ b/src/swing/scala/swing/ProgressBar.scala
@@ -1,3 +1,13 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
 package scala.swing
 
 import event._
@@ -9,8 +19,9 @@ import event._
  * 
  * @see javax.swing.JProgressBar
  */
-class ProgressBar extends Component with Orientable {
-  override lazy val peer: javax.swing.JProgressBar = new javax.swing.JProgressBar
+class ProgressBar extends Component with Orientable.Wrapper {
+  override lazy val peer: javax.swing.JProgressBar = 
+    new javax.swing.JProgressBar with SuperMixin
   
   def min: Int = peer.getMinimum
   def min_=(v: Int) { peer.setMinimum(v) }
@@ -30,4 +41,4 @@ class ProgressBar extends Component with Orientable {
   
   def paintBorder: Boolean = peer.isBorderPainted
   def paintBorder(v: Boolean) { peer.setBorderPainted(v) }
-}
\ No newline at end of file
+}
diff --git a/src/swing/scala/swing/Publisher.scala b/src/swing/scala/swing/Publisher.scala
index df24494..44de7eb 100644
--- a/src/swing/scala/swing/Publisher.scala
+++ b/src/swing/scala/swing/Publisher.scala
@@ -1,19 +1,32 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
 package scala.swing
 
-import scala.collection.mutable._
+import scala.collection._
+import scala.collection.mutable.{Buffer, HashSet, Set}
 import event.Event
 
-/**
- * Notifies registered reactions when an event is published. Publishers are also 
- * reactors and listen to themselves per default as a convenience.
- * 
- * In order to reduce memory leaks, reactions are weakly referenced by default, 
- * unless they implement <code>Reactions.StronglyReferenced</code>. That way, 
- * the lifetime of reactions are more easily bound to the registering object, 
- * which are reactors in common client code and hold strong references to their 
- * reactions. As a result, reactors can be garbage collected even though they 
- * still have reactions registered at some publisher, but not vice versa
- * since reactors (strongly) reference publishers they are interested in.
+/** <p>
+ *    Notifies registered reactions when an event is published. Publishers are 
+ *    also reactors and listen to themselves per default as a convenience.
+ *  </p>
+ *  <p>
+ *    In order to reduce memory leaks, reactions are weakly referenced by default, 
+ *    unless they implement <code>Reactions.StronglyReferenced</code>. That way, 
+ *    the lifetime of reactions are more easily bound to the registering object, 
+ *    which are reactors in common client code and hold strong references to their 
+ *    reactions. As a result, reactors can be garbage collected even though they 
+ *    still have reactions registered at some publisher, but not vice versa
+ *    since reactors (strongly) reference publishers they are interested in.
+ *  </p>
  */
 trait Publisher extends Reactor {
   import Reactions._
@@ -27,25 +40,47 @@ trait Publisher extends Reactor {
     }
   }
 
-  def subscribe(listener: Reaction) { listeners += listener }
-  def unsubscribe(listener: Reaction) { listeners -= listener }
+  private[swing] def subscribe(listener: Reaction) { listeners += listener }
+  private[swing] def unsubscribe(listener: Reaction) { listeners -= listener }
   
   /**
    * Notify all registered reactions.
    */
-  def publish(e: Event) { for (val l <- listeners) l(e) }
+  def publish(e: Event) { for (l <- listeners) l(e) }
   
   listenTo(this)
 }
 
+/**
+ * A publisher that subscribes itself to an underlying event source not before the first 
+ * reaction is installed. Can unsubscribe itself when the last reaction is uninstalled.
+ */
+private[swing] trait LazyPublisher extends Publisher {
+  import Reactions._
+  
+  protected def onFirstSubscribe()
+  protected def onLastUnsubscribe()
+  
+  override def subscribe(listener: Reaction) { 
+    if(listeners.size == 1) onFirstSubscribe() 
+    super.subscribe(listener) 
+  }
+  override def unsubscribe(listener: Reaction) { 
+    super.unsubscribe(listener) 
+    if(listeners.size == 1) onLastUnsubscribe()
+  }
+}
+
+
+
 import scala.ref._
 
-private[swing] trait SingleRefCollection[+A <: AnyRef] extends Collection[A] { self =>
+private[swing] trait SingleRefCollection[+A <: AnyRef] extends Iterable[A] { self =>
 
-  trait Ref[+A<:AnyRef] extends Reference[A] {
+  trait Ref[+A <: AnyRef] extends Reference[A] {
     override def hashCode() = {
       val v = get
-      if (v == None) 0 else v.get.hashCode
+      if (v == None) 0 else v.get.##
     }
     override def equals(that: Any) = that match {
       case that: ReferenceWrapper[_] => 
@@ -60,11 +95,11 @@ private[swing] trait SingleRefCollection[+A <: AnyRef] extends Collection[A] { s
   protected[this] def Ref(a: A): Ref[A]
   protected[this] val referenceQueue = new ReferenceQueue[A]
   
-  protected val underlying: Collection[Reference[A]]
+  protected val underlying: Iterable[Reference[A]]
       
   def purgeReferences() { 
     var ref = referenceQueue.poll
-    while(ref != None) { 
+    while (ref != None) { 
       removeReference(ref.get.asInstanceOf[Reference[A]])
       ref = referenceQueue.poll
     }
@@ -72,8 +107,8 @@ private[swing] trait SingleRefCollection[+A <: AnyRef] extends Collection[A] { s
   
   protected[this] def removeReference(ref: Reference[A])
   
-  def elements = new Iterator[A] {
-    private val elems = self.underlying.elements
+  def iterator = new Iterator[A] {
+    private val elems = self.underlying.iterator
     private var hd: A = _
     private var ahead: Boolean = false
     private def skip: Unit =
@@ -93,7 +128,7 @@ private[swing] trait SingleRefCollection[+A <: AnyRef] extends Collection[A] { s
 
 private[swing] class StrongReference[+T <: AnyRef](value: T) extends Reference[T] {
     private[this] var ref: Option[T] = Some(value)
-    @deprecated def isValid: Boolean = ref != None
+    def isValid: Boolean = ref != None
     def apply(): T = ref.get
     def get : Option[T] = ref
     override def toString = get.map(_.toString).getOrElse("<deleted>")
@@ -102,23 +137,18 @@ private[swing] class StrongReference[+T <: AnyRef](value: T) extends Reference[T
     def isEnqueued(): Boolean = false
   }
   
-  abstract class RefBuffer[A <: AnyRef] extends Buffer[A] with SingleRefCollection[A] { self =>
+abstract class RefBuffer[A <: AnyRef] extends Buffer[A] with SingleRefCollection[A] { self =>
   protected val underlying: Buffer[Reference[A]]
 
-  def +=(el: A) { purgeReferences(); underlying += Ref(el) }
-  def +:(el: A) = { purgeReferences(); Ref(el) +: underlying; this }
+  def +=(el: A): this.type = { purgeReferences(); underlying += Ref(el); this }
+  def +=:(el: A) = { purgeReferences(); Ref(el) +=: underlying; this }
   def remove(el: A) { underlying -= Ref(el); purgeReferences(); }
   def remove(n: Int) = { val el = apply(n); remove(el); el }
   def insertAll(n: Int, iter: Iterable[A]) {
     purgeReferences()
-    underlying.insertAll(n, iter.projection.map(Ref(_)))
+    underlying.insertAll(n, iter.view.map(Ref(_)))
   }
   def update(n: Int, el: A) { purgeReferences(); underlying(n) = Ref(el) }
-  def readOnly : Seq[A] = new Seq[A] {
-    def length = self.length
-    def elements = self.elements
-    def apply(n: Int) = self(n)
-  }
   def apply(n: Int) = { 
     purgeReferences()
     var el = underlying(n).get
@@ -133,14 +163,14 @@ private[swing] class StrongReference[+T <: AnyRef](value: T) extends Reference[T
 
   protected[this] def removeReference(ref: Reference[A]) { underlying -= ref }
 }
-  
+ 
 private[swing] abstract class RefSet[A <: AnyRef] extends Set[A] with SingleRefCollection[A] { self =>
   protected val underlying: Set[Reference[A]]
   
-  def -=(el: A) { underlying -= Ref(el); purgeReferences() }
-  def +=(el: A) { purgeReferences(); underlying += Ref(el) }
-  def contains(el: A) = { purgeReferences(); underlying.contains(Ref(el)) }
-  def size = { purgeReferences(); underlying.size }
+  def -=(el: A): this.type = { underlying -= Ref(el); purgeReferences(); this }
+  def +=(el: A): this.type = { purgeReferences(); underlying += Ref(el); this }
+  def contains(el: A): Boolean = { purgeReferences(); underlying.contains(Ref(el)) }
+  override def size = { purgeReferences(); underlying.size }
   
   protected[this] def removeReference(ref: Reference[A]) { underlying -= ref }
 }
diff --git a/src/swing/scala/swing/RadioButton.scala b/src/swing/scala/swing/RadioButton.scala
index ebfb728..9cd5650 100644
--- a/src/swing/scala/swing/RadioButton.scala
+++ b/src/swing/scala/swing/RadioButton.scala
@@ -1,3 +1,13 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
 package scala.swing
 
 import javax.swing._
@@ -10,6 +20,6 @@ import javax.swing._
  * @see javax.swing.JRadioButton
  */
 class RadioButton(text0: String) extends ToggleButton {
-  override lazy val peer: JRadioButton = new JRadioButton(text0)
+  override lazy val peer: JRadioButton = new JRadioButton(text0) with SuperMixin
   def this() = this("")
-}
\ No newline at end of file
+}
diff --git a/src/swing/scala/swing/Reactions.scala b/src/swing/scala/swing/Reactions.scala
index c261079..7c1662b 100644
--- a/src/swing/scala/swing/Reactions.scala
+++ b/src/swing/scala/swing/Reactions.scala
@@ -1,3 +1,13 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
 package scala.swing
 
 import event.Event
@@ -9,8 +19,8 @@ object Reactions {
   class Impl extends Reactions {
     private val parts: Buffer[Reaction] = new ListBuffer[Reaction]
     def isDefinedAt(e: Event) = parts.exists(_ isDefinedAt e)
-    def += (r: Reaction) = { parts += r }
-    def -= (r: Reaction) { parts -= r }
+    def += (r: Reaction): this.type = { parts += r; this }
+    def -= (r: Reaction): this.type = { parts -= r; this }
     def apply(e: Event) {
       for (p <- parts) if (p isDefinedAt e) p(e)
     }
@@ -37,10 +47,10 @@ abstract class Reactions extends Reactions.Reaction {
   /**
    * Add a reaction.
    */
-  def += (r: Reactions.Reaction) 
+  def += (r: Reactions.Reaction): this.type
 
   /**
    * Remove the given reaction.
    */
-  def -= (r: Reactions.Reaction)
+  def -= (r: Reactions.Reaction): this.type
 }
diff --git a/src/swing/scala/swing/Reactor.scala b/src/swing/scala/swing/Reactor.scala
index 596acb1..48ea23d 100644
--- a/src/swing/scala/swing/Reactor.scala
+++ b/src/swing/scala/swing/Reactor.scala
@@ -1,3 +1,13 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
 package scala.swing
 
 /**
@@ -12,9 +22,9 @@ trait Reactor {
    * Listen to the given publisher as long as <code>deafTo</code> isn't called for 
    * them.
    */
-  def listenTo(ps: Publisher*) = for (val p <- ps) p.subscribe(reactions)
+  def listenTo(ps: Publisher*) = for (p <- ps) p.subscribe(reactions)
   /**
    * Installed reaction won't receive events from the given publisher anylonger.
    */
-  def deafTo(ps: Publisher*) = for (val p <- ps) p.unsubscribe(reactions)
+  def deafTo(ps: Publisher*) = for (p <- ps) p.unsubscribe(reactions)
 }
diff --git a/src/swing/scala/swing/RichWindow.scala b/src/swing/scala/swing/RichWindow.scala
new file mode 100644
index 0000000..10c6321
--- /dev/null
+++ b/src/swing/scala/swing/RichWindow.scala
@@ -0,0 +1,205 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.swing
+
+import java.awt.{Window => AWTWindow, Frame => AWTFrame}
+import javax.swing._
+import Swing._
+
+object RichWindow {
+  /**
+   * Mixin this trait if you want an undecorated window.
+   */
+  trait Undecorated extends RichWindow {
+    // we do a mixin here, since setUndecorated is only allowed to be called
+    // when the component is not displayable.
+    peer.setUndecorated(true) 
+  }
+}
+
+/**
+ * A window that adds some functionality to the plain Window class and serves as 
+ * the common base class for frames and dialogs.
+ * 
+ * Implementation note: this class is sealed since we need to know that a rich
+ * window is either a dialog or a frame at some point.
+ */
+sealed trait RichWindow extends Window {
+  def peer: AWTWindow with InterfaceMixin
+  
+  trait InterfaceMixin extends super.InterfaceMixin {
+    def getJMenuBar: JMenuBar
+    def setJMenuBar(b: JMenuBar)
+    def setUndecorated(b: Boolean)
+    def setTitle(s: String)
+    def getTitle: String
+    def setResizable(b: Boolean)
+    def isResizable: Boolean
+  }
+  
+  def title: String = peer.getTitle
+  def title_=(s: String) = peer.setTitle(s)
+  
+  /**
+   * The menu bar of this frame or `NoMenuBar` if no menu bar is set.
+   */
+  def menuBar: MenuBar = {
+      val m = UIElement.cachedWrapper[MenuBar](peer.getJMenuBar)
+      if (m != null) m else MenuBar.NoMenuBar 
+  }
+  /**
+   * Set the current menu bar of this frame. Pass `NoMenuBar` if this frame 
+   * should not show a menu bar.
+   */
+  def menuBar_=(m: MenuBar) = 
+    peer.setJMenuBar(if(m == MenuBar.NoMenuBar) null else m.peer)
+  
+  def resizable_=(b: Boolean) { peer.setResizable(b) }
+  def resizable = peer.isResizable
+}
+
+/**
+ * A window with decoration such as a title, border, and action buttons.
+ * 
+ * An AWT window cannot be wrapped dynamically with this class, i.e., you cannot 
+ * write something like new Window { def peer = myAWTWindow }
+ * 
+ * @see javax.swing.JFrame
+ */
+class Frame extends RichWindow {
+  override lazy val peer: JFrame with InterfaceMixin = new JFrame with InterfaceMixin with SuperMixin
+  
+  protected trait SuperMixin extends JFrame {
+    override protected def processWindowEvent(e: java.awt.event.WindowEvent) {
+      super.processWindowEvent(e)
+      if (e.getID() == java.awt.event.WindowEvent.WINDOW_CLOSING)
+        closeOperation()
+    }
+  }
+
+  def iconify() { peer.setExtendedState(peer.getExtendedState | AWTFrame.ICONIFIED) }
+  def uniconify() { peer.setExtendedState(peer.getExtendedState & ~AWTFrame.ICONIFIED) }
+  def iconified() { (peer.getExtendedState & AWTFrame.ICONIFIED) != 0 }
+  def maximize() { peer.setExtendedState(peer.getExtendedState | AWTFrame.MAXIMIZED_BOTH) }
+  def unmaximize() { peer.setExtendedState(peer.getExtendedState & ~AWTFrame.MAXIMIZED_BOTH) }
+  def maximized() { (peer.getExtendedState & AWTFrame.MAXIMIZED_BOTH) != 0 }
+  
+  def iconImage: Image = peer.getIconImage
+  def iconImage_=(i: Image) { peer.setIconImage(i) }
+}
+
+/**
+ * Simple predefined dialogs.
+ * 
+ * @see javax.swing.JOptionPane
+ */
+object Dialog {
+  /**
+   * The message type of a dialog.
+   */
+  object Message extends Enumeration {
+    val Error = Value(JOptionPane.ERROR_MESSAGE)
+    val Info = Value(JOptionPane.INFORMATION_MESSAGE)
+    val Warning = Value(JOptionPane.WARNING_MESSAGE)
+    val Question = Value(JOptionPane.QUESTION_MESSAGE)
+    val Plain = Value(JOptionPane.PLAIN_MESSAGE)
+  }
+  
+  /**
+   * The possible answers a user can select.
+   */
+  object Options extends Enumeration {
+    val Default = Value(JOptionPane.DEFAULT_OPTION)
+    val YesNo = Value(JOptionPane.YES_NO_OPTION)
+    val YesNoCancel = Value(JOptionPane.YES_NO_CANCEL_OPTION)
+    val OkCancel = Value(JOptionPane.OK_CANCEL_OPTION)
+  }
+  
+  /**
+   * The selected result of dialog.
+   */
+  object Result extends Enumeration {
+    val Yes = Value(JOptionPane.YES_OPTION)
+    val Ok = Yes
+    val No = Value(JOptionPane.NO_OPTION)
+    val Cancel = Value(JOptionPane.CANCEL_OPTION)
+    val Closed = Value(JOptionPane.CLOSED_OPTION)
+  }
+  
+  private def uiString(txt: String) = UIManager.getString(txt)
+  
+  def showConfirmation(parent: Component = null,
+                       message: Any, 
+                       title: String = uiString("OptionPane.titleText"), 
+                       optionType: Options.Value = Options.YesNo, 
+                       messageType: Message.Value = Message.Question, 
+                       icon: Icon = EmptyIcon): Result.Value =
+     Result(JOptionPane.showConfirmDialog(nullPeer(parent), message, title, 
+                                   optionType.id, messageType.id, Swing.wrapIcon(icon)))
+  
+  def showOptions(parent: Component = null, 
+                  message: Any, 
+                  title: String = uiString("OptionPane.titleText"),  
+                  optionType: Options.Value = Options.YesNo, 
+                  messageType: Message.Value = Message.Question, 
+                  icon: Icon = EmptyIcon, 
+                  entries: Seq[Any], 
+                  initial: Int): Result.Value = {
+    val r = JOptionPane.showOptionDialog(nullPeer(parent), message, title, 
+                                   optionType.id, messageType.id, Swing.wrapIcon(icon), 
+                                   entries map toAnyRef toArray, entries(initial))
+    Result(r)
+  }
+
+  def showInput[A](parent: Component = null, 
+                   message: Any, 
+                   title: String = uiString("OptionPane.inputDialogTitle"),
+                   messageType: Message.Value = Message.Question, 
+                   icon: Icon = EmptyIcon, 
+                   entries: Seq[A] = Nil, 
+                   initial: A): Option[A] = {
+    val e = if (entries.isEmpty) null
+            else entries map toAnyRef toArray
+    val r = JOptionPane.showInputDialog(nullPeer(parent), message, title,
+        messageType.id, Swing.wrapIcon(icon), 
+        e, initial)
+        
+    toOption[A](r)
+  }
+  def showMessage(parent: Component = null, 
+                  message: Any, 
+                  title: String = uiString("OptionPane.messageDialogTitle"), 
+                  messageType: Message.Value = Message.Info, 
+                  icon: Icon = EmptyIcon) {
+     JOptionPane.showMessageDialog(nullPeer(parent), message, title, 
+                                   messageType.id, Swing.wrapIcon(icon))
+  }
+}
+
+/**
+ * A dialog window.
+ * 
+ * @see javax.swing.JDialog
+ */
+class Dialog(owner: Window) extends RichWindow {
+  override lazy val peer: JDialog with InterfaceMixin = 
+    if (owner == null) new JDialog with InterfaceMixin
+    else owner match {
+      case f: Frame => new JDialog(f.peer) with InterfaceMixin
+      case d: Dialog => new JDialog(d.peer) with InterfaceMixin
+    }
+  
+  def this() = this(null)
+  
+  def modal_=(b: Boolean) { peer.setModal(b) }
+  def modal = peer.isModal
+}
+
diff --git a/src/swing/scala/swing/RootPanel.scala b/src/swing/scala/swing/RootPanel.scala
index c4d2bf9..931b82a 100644
--- a/src/swing/scala/swing/RootPanel.scala
+++ b/src/swing/scala/swing/RootPanel.scala
@@ -1,3 +1,13 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
 package scala.swing
 
 /**
@@ -11,11 +21,13 @@ trait RootPanel extends Container {
   /**
    * At most one component.
    */
-  def contents: Seq[Component] = {
-    Swing.toOption(peer.getContentPane.getComponent(0)).map { c => 
-      Component.wrapperFor(c.asInstanceOf[javax.swing.JComponent])
-    }.toList
-  }
+  def contents: Seq[Component] = 
+    if (peer.getContentPane.getComponentCount == 0) Nil
+    else {
+      val c = peer.getContentPane.getComponent(0).asInstanceOf[javax.swing.JComponent]
+      List(UIElement.cachedWrapper[Component](c))
+    }
+  
   def contents_=(c: Component) {
     if (peer.getContentPane.getComponentCount > 0) {
       val old = peer.getContentPane.getComponent(0)
diff --git a/src/swing/scala/swing/ScrollBar.scala b/src/swing/scala/swing/ScrollBar.scala
new file mode 100644
index 0000000..148228a
--- /dev/null
+++ b/src/swing/scala/swing/ScrollBar.scala
@@ -0,0 +1,39 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.swing
+
+import javax.swing.{JScrollBar, BoundedRangeModel}
+import java.awt.event.{AdjustmentListener}
+
+object ScrollBar {
+  def wrap(c: JScrollBar): ScrollBar = { 
+    val w = UIElement.cachedWrapper[ScrollBar](c)
+    if (w != null) w 
+    else new ScrollBar { override lazy val peer = c }
+  }
+}
+
+class ScrollBar extends Component with Orientable.Wrapper with Adjustable.Wrapper {
+	override lazy val peer: JScrollBar = new JScrollBar with SuperMixin
+
+	def valueIsAjusting = peer.getValueIsAdjusting
+	def valueIsAjusting_=(b : Boolean) = peer.setValueIsAdjusting(b)
+
+	// TODO: can we find a better interface?
+	//def setValues(value: Int = this.value, visible: Int = visibleAmount, 
+	//             min: Int = minimum, max: Int = maximum) =    
+	//  peer.setValues(value, visible, min, max)
+
+// Not currently needed, requires wrapper for BoundedRangeModel 
+//
+//    	    def model = peer.getModel
+//    	    def model_=(m : BoundedRangeModel) = peer.setModel(m)
+}
diff --git a/src/swing/scala/swing/ScrollPane.scala b/src/swing/scala/swing/ScrollPane.scala
index ed323da..c4796ec 100644
--- a/src/swing/scala/swing/ScrollPane.scala
+++ b/src/swing/scala/swing/ScrollPane.scala
@@ -1,6 +1,37 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
 package scala.swing
 
-import javax.swing.JScrollPane
+import javax.swing.{JScrollPane, ScrollPaneConstants}
+
+object ScrollPane {
+  object BarPolicy extends Enumeration {
+    import ScrollPaneConstants._
+    val AsNeeded = new Value(HORIZONTAL_SCROLLBAR_AS_NEEDED,
+                             VERTICAL_SCROLLBAR_AS_NEEDED)
+    val Never = new Value(HORIZONTAL_SCROLLBAR_NEVER,
+                          VERTICAL_SCROLLBAR_NEVER)
+    val Always = new Value(HORIZONTAL_SCROLLBAR_ALWAYS,
+                           VERTICAL_SCROLLBAR_ALWAYS)
+
+    def wrap(id: Int) = id match {
+      case HORIZONTAL_SCROLLBAR_AS_NEEDED | VERTICAL_SCROLLBAR_AS_NEEDED => AsNeeded
+      case HORIZONTAL_SCROLLBAR_NEVER | VERTICAL_SCROLLBAR_NEVER => Never
+      case HORIZONTAL_SCROLLBAR_ALWAYS | VERTICAL_SCROLLBAR_ALWAYS => Always
+    }
+    class Value(val horizontalPeer: Int, val verticalPeer: Int) extends super.Val {
+      override def id = horizontalPeer
+    }
+  }
+}
 
 /**
  * Can have at most a single child component, which will be put inside a canvas (the viewport)
@@ -9,13 +40,15 @@ import javax.swing.JScrollPane
  * @see javax.swing.JScrollPane
  */
 class ScrollPane extends Component with Container {
-  override lazy val peer: JScrollPane = new JScrollPane
+  import ScrollPane._
+  
+  override lazy val peer: JScrollPane = new JScrollPane with SuperMixin
   def this(c: Component) = {
     this()
-    viewportView = c
+    contents = c
   } 
   def contents: Seq[Component] = 
-    List(Component.wrapperFor(peer.getViewport.getView.asInstanceOf[javax.swing.JComponent]))
+    List(UIElement.cachedWrapper[Component](peer.getViewport.getView.asInstanceOf[javax.swing.JComponent]))
   
   /**
    * Sets the single child.
@@ -29,11 +62,27 @@ class ScrollPane extends Component with Container {
    * want to let the row header be a list view with the same row height as 
    * the viewport component.
    */
-  def rowHeaderView: Option[Component] = Swing.toOption(peer.getRowHeader.getView).map(Component.wrapperFor(_))
+  def rowHeaderView: Option[Component] = 
+    Option(peer.getRowHeader.getView) map UIElement.cachedWrapper[Component]
   def rowHeaderView_=(c: Component) = peer.setRowHeaderView(c.peer)
-  def rowHeaderView_=(c: Option[Component]) = peer.setRowHeaderView(Swing.toNull(c.map(_.peer)))
+  def rowHeaderView_=(c: Option[Component]) = peer.setRowHeaderView(c map (_.peer) orNull)
+  
+  def columnHeaderView: Option[Component] = 
+    Option(peer.getColumnHeader.getView) map UIElement.cachedWrapper[Component]
+  def columnHeaderView_=(c: Component) = peer.setColumnHeaderView(c.peer)
+  def columnHeaderView_=(c: Option[Component]) = peer.setColumnHeaderView(c map (_.peer) orNull)
   
-  def viewportView: Option[Component] = Swing.toOption(peer.getViewport.getView).map(Component.wrapperFor(_))
+  def viewportView: Option[Component] = 
+    Option(peer.getViewport.getView) map UIElement.cachedWrapper[Component]
   def viewportView_=(c: Component) = peer.setViewportView(c.peer)
-  def viewportView_=(c: Option[Component]) = peer.setViewportView(Swing.toNull(c.map(_.peer)))
+  def viewportView_=(c: Option[Component]) = peer.setViewportView(c map (_.peer) orNull)
+
+  def verticalScrollBarPolicy = BarPolicy.wrap(peer.getVerticalScrollBarPolicy)
+  def verticalScrollBarPolicy_=(p: BarPolicy.Value) = peer.setVerticalScrollBarPolicy(p.verticalPeer)
+  
+  def horizontalScrollBarPolicy = BarPolicy.wrap(peer.getHorizontalScrollBarPolicy)
+  def horizontalScrollBarPolicy_=(p: BarPolicy.Value) = peer.setHorizontalScrollBarPolicy(p.horizontalPeer)
+  
+  def horizontalScrollBar = ScrollBar.wrap(peer.getHorizontalScrollBar)
+  def verticalScrollBar = ScrollBar.wrap(peer.getVerticalScrollBar)
 }
diff --git a/src/swing/scala/swing/Scrollable.scala b/src/swing/scala/swing/Scrollable.scala
index a44c96f..24512ad 100644
--- a/src/swing/scala/swing/Scrollable.scala
+++ b/src/swing/scala/swing/Scrollable.scala
@@ -1,6 +1,30 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
 package scala.swing
 
-import java.awt.Rectangle
+object Scrollable {
+  trait Wrapper extends Scrollable {
+    protected def scrollablePeer: javax.swing.Scrollable
+    def preferredViewportSize = scrollablePeer.getPreferredScrollableViewportSize
+    
+    def tracksViewportHeight: Boolean = scrollablePeer.getScrollableTracksViewportHeight
+    def tracksViewportWidth: Boolean = scrollablePeer.getScrollableTracksViewportWidth
+    
+    def blockIncrement(visibleRect: Rectangle, orientation: Orientation.Value, direction: Int): Int =
+      scrollablePeer.getScrollableBlockIncrement(visibleRect, orientation.id, direction)
+    
+    def unitIncrement(visibleRect: Rectangle, orientation: Orientation.Value, direction: Int): Int =
+      scrollablePeer.getScrollableUnitIncrement(visibleRect, orientation.id, direction)
+  }
+}
 
 /**
  * A component that is specially suitable for being placed inside a
@@ -9,15 +33,11 @@ import java.awt.Rectangle
  * @see javax.swing.Scrollable
  */
 trait Scrollable extends Component {
-  protected def scrollablePeer: javax.swing.Scrollable
-  def preferredViewportSize = scrollablePeer.getPreferredScrollableViewportSize
-  
-  def tracksViewportHeight: Boolean = scrollablePeer.getScrollableTracksViewportHeight
-  def tracksViewportWidth: Boolean = scrollablePeer.getScrollableTracksViewportWidth
+  def preferredViewportSize: Dimension
   
-  def blockIncrement(visibleRect: Rectangle, orientation: Orientation.Value, direction: Int): Int =
-    scrollablePeer.getScrollableBlockIncrement(visibleRect, orientation.id, direction)
+  def tracksViewportHeight: Boolean
+  def tracksViewportWidth: Boolean
   
-  def unitIncrement(visibleRect: Rectangle, orientation: Orientation.Value, direction: Int): Int =
-    scrollablePeer.getScrollableUnitIncrement(visibleRect, orientation.id, direction)
+  def blockIncrement(visibleRect: Rectangle, orientation: Orientation.Value, direction: Int): Int  
+  def unitIncrement(visibleRect: Rectangle, orientation: Orientation.Value, direction: Int): Int
 }
diff --git a/src/swing/scala/swing/Separator.scala b/src/swing/scala/swing/Separator.scala
index 561c1bc..ff81133 100644
--- a/src/swing/scala/swing/Separator.scala
+++ b/src/swing/scala/swing/Separator.scala
@@ -1,3 +1,13 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
 package scala.swing
 
 import javax.swing._
@@ -7,7 +17,7 @@ import javax.swing._
  * 
  * @see javax.swing.JSeparator
  */
-class Separator(o: Orientation.Value) extends Component with Oriented {
-  override lazy val peer: JSeparator = new JSeparator(o.id)
+class Separator(o: Orientation.Value) extends Component with Oriented.Wrapper {
+  override lazy val peer: JSeparator = new JSeparator(o.id) with SuperMixin
   def this() = this(Orientation.Horizontal)
 }
diff --git a/src/swing/scala/swing/SequentialContainer.scala b/src/swing/scala/swing/SequentialContainer.scala
index b5cfb65..0d72652 100644
--- a/src/swing/scala/swing/SequentialContainer.scala
+++ b/src/swing/scala/swing/SequentialContainer.scala
@@ -1,3 +1,13 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
 package scala.swing
 
 import scala.collection.mutable.Buffer
@@ -6,16 +16,21 @@ object SequentialContainer {
   /**
    * Utility trait for wrapping sequential containers.
    */
-  trait Wrapper extends Component with SequentialContainer with Container.Wrapper {
+  trait Wrapper extends SequentialContainer with Container.Wrapper {
     override val contents: Buffer[Component] = new Content
     //def contents_=(c: Component*)  { contents.clear(); contents ++= c }
   }
 }
 
 /**
- * A container that contains children in a specific sequential order.
+ * A container for which a sequential order of children makes sense, such as 
+ * flow panels, or menus. Its contents are mutable.
  */
 trait SequentialContainer extends Container {
+  /**
+   * The mutable child components of this container. The order matters and 
+   * usually indicates the layout of the children.
+   */
   override def contents: Buffer[Component]
   //def contents_=(c: Component*)
 }
diff --git a/src/swing/scala/swing/SimpleGUIApplication.scala b/src/swing/scala/swing/SimpleGUIApplication.scala
index b16d373..df6b6a2 100644
--- a/src/swing/scala/swing/SimpleGUIApplication.scala
+++ b/src/swing/scala/swing/SimpleGUIApplication.scala
@@ -1,23 +1,47 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
 package scala.swing
 
 import javax.swing._
 
 /**
  * Extend this class for most simple UI applications. Clients need to implement the 
- * <code>top</code> method. Framework intialization is done by this class.
+ * <code>top</code> method. Framework initialization is done by this class.
+ * 
+ * In order to conform to Swing's threading policy, never implement top or any additional 
+ * member that created Swing components as a value unless component creation happens on 
+ * the EDT (see Swing.onEDT and Swing.onEDTWait). Lazy values are okay for the same reason
+ * if they are initialized on the EDT always.
  */
-abstract class SimpleGUIApplication extends GUIApplication {
+ at deprecated("Use SimpleSwingApplication instead") abstract class SimpleGUIApplication extends GUIApplication {
+  
+  /**
+   * A GUI application's version of the main method. Called by the default 
+   * main method implementation provided by this class.
+   * Implement to return the top-level frame of this application. 
+   */
   def top: Frame
 
-  def main(args: Array[String]) = {
-    SwingUtilities.invokeLater {
-      new Runnable { def run() { init(); top.pack(); top.visible = true } }
-    }
+  /**
+   * Calls top, packs the frame, and displays it.
+   */
+  def main(args: Array[String]) = run {
+    val t = top
+    t.pack()
+    t.visible = true
   }
   
   def resourceFromClassloader(path: String): java.net.URL =
     this.getClass.getResource(path)
   
   def resourceFromUserDirectory(path: String): java.io.File =
-    new java.io.File(System.getProperty("user.dir"), path)
+    new java.io.File(util.Properties.userDir, path)
 }
diff --git a/src/swing/scala/swing/SimpleSwingApplication.scala b/src/swing/scala/swing/SimpleSwingApplication.scala
new file mode 100644
index 0000000..3416eed
--- /dev/null
+++ b/src/swing/scala/swing/SimpleSwingApplication.scala
@@ -0,0 +1,17 @@
+package scala.swing
+
+abstract class SimpleSwingApplication extends SwingApplication {
+  def top: Frame
+  
+  override def startup(args: Array[String]) {
+    val t = top
+    if (t.size == new Dimension(0,0)) t.pack()
+    t.visible = true
+  }
+  
+  def resourceFromClassloader(path: String): java.net.URL =
+    this.getClass.getResource(path)
+  
+  def resourceFromUserDirectory(path: String): java.io.File =
+    new java.io.File(util.Properties.userDir, path)
+}
diff --git a/src/swing/scala/swing/Slider.scala b/src/swing/scala/swing/Slider.scala
index eaf23a5..f3dafa1 100644
--- a/src/swing/scala/swing/Slider.scala
+++ b/src/swing/scala/swing/Slider.scala
@@ -1,5 +1,16 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
 package scala.swing
 
+import javax.swing.{JSlider, JLabel}
 import event._
 
 /**
@@ -11,8 +22,8 @@ import event._
  * 
  * @see javax.swing.JSlider
  */
-class Slider extends Component with Orientable with Publisher {
-  override lazy val peer: javax.swing.JSlider = new javax.swing.JSlider
+class Slider extends Component with Orientable.Wrapper with Publisher {
+  override lazy val peer: JSlider = new JSlider with SuperMixin
   
   def min: Int = peer.getMinimum
   def min_=(v: Int) { peer.setMinimum(v) }
@@ -40,19 +51,21 @@ class Slider extends Component with Orientable with Publisher {
   
   def adjusting = peer.getValueIsAdjusting
   
-  def labels: scala.collection.Map[Int, Label] = 
-    new scala.collection.jcl.MapWrapper[Int, Label] { 
-      def underlying = peer.getLabelTable.asInstanceOf[java.util.Hashtable[Int, Label]] 
-    }
+  def labels: scala.collection.Map[Int, Label] = {
+    val labelTable = peer.getLabelTable.asInstanceOf[java.util.Hashtable[Int, JLabel]]
+    new scala.collection.JavaConversions.JMapWrapper(labelTable)
+      .mapValues(v => UIElement.cachedWrapper[Label](v))
+  }
   def labels_=(l: scala.collection.Map[Int, Label]) {
+    // TODO: do some lazy wrapping
     val table = new java.util.Hashtable[Any, Any]
-    for ((k,v) <- l) table.put(k, v)
+    for ((k,v) <- l) table.put(k, v.peer)
     peer.setLabelTable(table)
   }
   
   peer.addChangeListener(new javax.swing.event.ChangeListener {
     def stateChanged(e: javax.swing.event.ChangeEvent) { 
-      publish(ValueChanged(Slider.this)) 
+      publish(new ValueChanged(Slider.this)) 
     }
   })
-}
\ No newline at end of file
+}
diff --git a/src/swing/scala/swing/SplitPane.scala b/src/swing/scala/swing/SplitPane.scala
index ce0cfee..901e4d5 100644
--- a/src/swing/scala/swing/SplitPane.scala
+++ b/src/swing/scala/swing/SplitPane.scala
@@ -1,3 +1,13 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
 package scala.swing
 
 import event._
@@ -10,8 +20,9 @@ import Swing._
  * 
  * @see javax.swing.JSplitPane
  */
-class SplitPane(o: Orientation.Value, left: Component, right: Component) extends Component with Container with Orientable {
-  override lazy val peer: javax.swing.JSplitPane = new javax.swing.JSplitPane(o.id, left.peer, right.peer)
+class SplitPane(o: Orientation.Value, left: Component, right: Component) extends Component with Container with Orientable.Wrapper {
+  override lazy val peer: javax.swing.JSplitPane = 
+    new javax.swing.JSplitPane(o.id, left.peer, right.peer) with SuperMixin
   def this(o: Orientation.Value) = this(o, new Component {}, new Component {})
   def this() = this(Orientation.Horizontal)
   
@@ -21,9 +32,11 @@ class SplitPane(o: Orientation.Value, left: Component, right: Component) extends
     peer.setRightComponent(right.peer)
   }
   
-  def topComponent: Component = Component.wrapperFor(peer.getTopComponent.asInstanceOf[javax.swing.JComponent])
+  def topComponent: Component = 
+    UIElement.cachedWrapper[Component](peer.getTopComponent.asInstanceOf[javax.swing.JComponent])
   def topComponent_=(c: Component) { peer.setTopComponent(c.peer) }
-  def bottomComponent: Component = Component.wrapperFor(peer.getBottomComponent.asInstanceOf[javax.swing.JComponent])
+  def bottomComponent: Component = 
+    UIElement.cachedWrapper[Component](peer.getBottomComponent.asInstanceOf[javax.swing.JComponent])
   def bottomComponent_=(c: Component) { peer.setBottomComponent(c.peer) }
   
   def leftComponent: Component = topComponent
@@ -50,4 +63,4 @@ class SplitPane(o: Orientation.Value, left: Component, right: Component) extends
   def oneTouchExpandable_=(b: Boolean) { peer.setOneTouchExpandable(b) }
   def continuousLayout: Boolean = peer.isContinuousLayout
   def continuousLayout_=(b: Boolean) { peer.setContinuousLayout(b) }
-}
\ No newline at end of file
+}
diff --git a/src/swing/scala/swing/Swing.scala b/src/swing/scala/swing/Swing.scala
index baeae09..05533b5 100644
--- a/src/swing/scala/swing/Swing.scala
+++ b/src/swing/scala/swing/Swing.scala
@@ -1,34 +1,39 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
 package scala.swing
 
 import java.awt.event._
 import javax.swing.event._
-import java.awt.{Color, Dimension, Point}
 import javax.swing.border._
-import javax.swing.{JComponent, Icon, BorderFactory}
+import javax.swing.{JComponent, Icon, BorderFactory, SwingUtilities}
 
 /**
  * Helpers for this package.
  */
 object Swing {
-  protected[swing] def ifNull[A](o: Object, a: A): A = if(o eq null) a else o.asInstanceOf[A]
-  protected[swing] def toOption[A](o: Object): Option[A] = if(o eq null) None else Some(o.asInstanceOf[A])
-  protected[swing] def toNull[A>:Null<:AnyRef](a: Option[A]): A = if(a == None) null else a.get
   protected[swing] def toNoIcon(i: Icon): Icon = if(i == null) EmptyIcon else i
   protected[swing] def toNullIcon(i: Icon): Icon = if(i == EmptyIcon) null else i
-  
+  protected[swing] def nullPeer(c: Component) = if (c != null) c.peer else null
+
   implicit def pair2Dimension(p: (Int, Int)): Dimension = new Dimension(p._1, p._2)
   implicit def pair2Point(p: (Int, Int)): Point = new Point(p._1, p._2)
+  implicit def pair2Point(p: (Int, Int, Int, Int)): Rectangle = new Rectangle(p._1, p._2, p._3, p._4)
   
-  /**
-   * Allows one to use blocks as runnables.
-   */
-  implicit def block2Runnable(block: =>Unit): Runnable = new Runnable {
-    override def run = block
+  @inline final def Runnable(@inline block: =>Unit) = new Runnable {
+    def run = block
   }
-  def ChangeListener(f: ChangeEvent => Unit) = new ChangeListener {
+  final def ChangeListener(f: ChangeEvent => Unit) = new ChangeListener {
     def stateChanged(e: ChangeEvent) { f(e) }
   }
-  def ActionListener(f: ActionEvent => Unit) = new ActionListener {
+  final def ActionListener(f: ActionEvent => Unit) = new ActionListener {
     def actionPerformed(e: ActionEvent) { f(e) }
   }
   
@@ -119,4 +124,16 @@ object Swing {
       
   def TitledBorder(border: Border, title: String) = 
     BorderFactory.createTitledBorder(border, title) 
+  
+  /**
+   * Schedule the given code to be executed on the Swing event dispatching 
+   * thread (EDT). Returns immediately.
+   */
+  @inline final def onEDT(op: =>Unit) = SwingUtilities invokeLater Runnable(op)
+
+  /**
+   * Schedule the given code to be executed on the Swing event dispatching 
+   * thread (EDT). Blocks until after the code has been run.
+   */
+  @inline final def onEDTWait(op: =>Unit) = SwingUtilities invokeAndWait Runnable(op)
 }
diff --git a/src/swing/scala/swing/SwingActor.scala b/src/swing/scala/swing/SwingActor.scala
new file mode 100644
index 0000000..01df831
--- /dev/null
+++ b/src/swing/scala/swing/SwingActor.scala
@@ -0,0 +1,35 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.swing
+
+import scala.actors._
+
+// Dummy to keep ant from recompiling on every run.
+trait SwingActor { }
+
+/*object SwingActor {
+  /**
+   * Similar to Actor.actor, but creates an instance of a SwingActor.
+   */
+  def apply(body: => Unit): Actor =
+    new SwingActor { def act() = body }.start()
+}
+
+/**
+ * An actor that runs on the Swing event dispatching thread (EDT).
+ */
+abstract class SwingActor extends Actor {
+  override val scheduler = new SchedulerAdapter {
+    def execute(op: =>Unit) = Swing onEDT op
+    def onTerminate(a: Actor)(op: => Unit) {}
+    def terminated(a: Actor) {}
+  }
+}*/
diff --git a/src/swing/scala/swing/SwingApplication.scala b/src/swing/scala/swing/SwingApplication.scala
new file mode 100644
index 0000000..a7285a5
--- /dev/null
+++ b/src/swing/scala/swing/SwingApplication.scala
@@ -0,0 +1,9 @@
+package scala.swing
+
+abstract class SwingApplication extends Reactor {
+  def main(args: Array[String]) = Swing.onEDT { startup(args) }
+  
+  def startup(args: Array[String])
+  def quit() { shutdown(); System.exit(0) }
+  def shutdown() {}
+}
diff --git a/src/swing/scala/swing/SwingWorker.scala b/src/swing/scala/swing/SwingWorker.scala
new file mode 100644
index 0000000..1755990
--- /dev/null
+++ b/src/swing/scala/swing/SwingWorker.scala
@@ -0,0 +1,21 @@
+package scala.swing
+
+import scala.actors._
+
+object SwingWorker {
+  
+}
+
+abstract class SwingWorker extends Actor {  
+  def queue() {
+    
+  }
+  
+  def done() {
+    
+  }
+  
+  private var _cancelled = false
+  def cancelled: Boolean = _cancelled
+  def cancelled_=(b: Boolean) { _cancelled = b }
+}
\ No newline at end of file
diff --git a/src/swing/scala/swing/TabbedPane.scala b/src/swing/scala/swing/TabbedPane.scala
index 12a8548..92dd148 100644
--- a/src/swing/scala/swing/TabbedPane.scala
+++ b/src/swing/scala/swing/TabbedPane.scala
@@ -1,9 +1,18 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
 package scala.swing
 
 import event._
 import scala.collection.mutable.Buffer
 import javax.swing.{JTabbedPane, JComponent}
-import java.awt.{Color, Rectangle}
 
 
 object TabbedPane {
@@ -26,10 +35,14 @@ object TabbedPane {
     protected[TabbedPane] var parent: TabbedPane = parent0
     
     protected var _title = title0
-    def title: String = _title//parent.peer.getTitleAt(index)
-    def title_=(t: String) { _title = title0; if (parent != null) parent.peer.setTitleAt(index, t) }
+    def title: String = _title
+    def title_=(t: String) { 
+      // beware to keep this order since, index depends on the _old_ title
+      if (parent != null) parent.peer.setTitleAt(index, t)
+      _title = t 
+    }
     protected var _content = content0
-    def content: Component = _content//Component.wrapperFor(peer.getComponentAt(index).asInstanceOf[JComponent])
+    def content: Component = _content//UIElement.cachedWrapper(peer.getComponentAt(index).asInstanceOf[JComponent])
     def content_=(c: Component) { _content = c; if (parent != null) parent.peer.setComponentAt(index, c.peer) }
     protected var _tip = tip0
     def tip: String = _tip//peer.getToolTipTextAt(index)
@@ -63,7 +76,7 @@ object TabbedPane {
  * @see javax.swing.JTabbedPane
  */
 class TabbedPane extends Component with Publisher {
-  override lazy val peer: JTabbedPane = new JTabbedPane
+  override lazy val peer: JTabbedPane = new JTabbedPane with SuperMixin
   import TabbedPane._
   
   object pages extends BufferWrapper[Page] {
@@ -82,11 +95,11 @@ class TabbedPane extends Component with Publisher {
       peer.insertTab(t.title, null, t.content.peer, t.tip, n) 
     }
 
-    def +=(t: Page) { t.parent = TabbedPane.this; peer.addTab(t.title, null, t.content.peer, t.tip) }
+    def +=(t: Page): this.type = { t.parent = TabbedPane.this; peer.addTab(t.title, null, t.content.peer, t.tip); this }
     def length = peer.getTabCount
     def apply(n: Int) = new Page(TabbedPane.this, peer.getTitleAt(n),
-                                Component.wrapperFor(peer.getComponentAt(n).asInstanceOf[javax.swing.JComponent]), 
-                                peer.getToolTipTextAt(n))
+      UIElement.cachedWrapper[Component](peer.getComponentAt(n).asInstanceOf[javax.swing.JComponent]), 
+      peer.getToolTipTextAt(n))
   }
   
   def tabLayoutPolicy: Layout.Value = Layout(peer.getTabLayoutPolicy)
diff --git a/src/swing/scala/swing/Table.scala b/src/swing/scala/swing/Table.scala
index 4a0e0bc..5673198 100644
--- a/src/swing/scala/swing/Table.scala
+++ b/src/swing/scala/swing/Table.scala
@@ -1,11 +1,20 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
 package scala.swing
 
+import event._
 import javax.swing._
 import javax.swing.table._
 import javax.swing.event._
-import java.awt.{Dimension, Color}
-import event._
-import scala.collection.mutable.Set
+import scala.collection.mutable
 
 object Table {
   object AutoResizeMode extends Enumeration {
@@ -77,6 +86,10 @@ object Table {
   }
   
   class LabelRenderer[A](convert: A => (Icon, String)) extends AbstractRenderer[A, Label](new Label) {
+    def this() {
+      this{ a => (null, a.toString) }
+    }
+    
     def configure(table: Table, isSelected: Boolean, hasFocus: Boolean, a: A, row: Int, column: Int) {
       val (icon, text) = convert(a)
       component.icon = icon
@@ -90,10 +103,13 @@ object Table {
 /**
  * Displays a matrix of items.
  * 
+ * To obtain a scrollable table or row and columns headers, 
+ * wrap the table in a scroll pane.
+ * 
  * @see javax.swing.JTable
  */
-class Table extends Component with Scrollable with Publisher {
-  override lazy val peer: JTable = new JTable with Table.JTableMixin {
+class Table extends Component with Scrollable.Wrapper {
+  override lazy val peer: JTable = new JTable with Table.JTableMixin with SuperMixin {
     def tableWrapper = Table.this
     override def getCellRenderer(r: Int, c: Int) = new TableCellRenderer {
       def getTableCellRendererComponent(table: JTable, value: AnyRef, isSelected: Boolean, hasFocus: Boolean, row: Int, column: Int) = 
@@ -104,9 +120,10 @@ class Table extends Component with Scrollable with Publisher {
   }
   import Table._
     
-  def this(rowData: Array[Array[Any]], columnNames: Seq[Any]) = {
+  // TODO: use IndexedSeq[_ <: IndexedSeq[Any]], see ticket #2005
+  def this(rowData: Array[Array[Any]], columnNames: Seq[_]) = {
     this()
-    peer.setModel(new AbstractTableModel {
+    model = new AbstractTableModel {
       override def getColumnName(column: Int) = columnNames(column).toString
       def getRowCount() = rowData.length
       def getColumnCount() = columnNames.length
@@ -116,7 +133,7 @@ class Table extends Component with Scrollable with Publisher {
         rowData(row)(col) = value
         fireTableCellUpdated(row, col)
       }
-    })
+    }
   }
   def this(rows: Int, columns: Int) = {
     this()
@@ -137,6 +154,7 @@ class Table extends Component with Scrollable with Publisher {
   def model = peer.getModel()
   def model_=(x: TableModel) = {
     peer.setModel(x)
+    model.removeTableModelListener(modelListener)
     model.addTableModelListener(modelListener)
   }
   
@@ -155,39 +173,41 @@ class Table extends Component with Scrollable with Publisher {
     
   object selection extends Publisher {
     // TODO: could be a sorted set
-    protected abstract class SelectionSet[A](a: =>Seq[A]) extends scala.collection.mutable.Set[A] { 
-      def -=(n: A) 
-      def +=(n: A) 
+    protected abstract class SelectionSet[A](a: =>Seq[A]) extends mutable.Set[A] { 
+      def -=(n: A): this.type 
+      def +=(n: A): this.type
       def contains(n: A) = a.contains(n)
-      def size = a.length
-      def elements = a.elements
+      override def size = a.length
+      def iterator = a.iterator
     }
     
     object rows extends SelectionSet(peer.getSelectedRows) {
-      def -=(n: Int) { peer.removeRowSelectionInterval(n,n) }
-      def +=(n: Int) { peer.addRowSelectionInterval(n,n) }
+      def -=(n: Int) = { peer.removeRowSelectionInterval(n,n); this }
+      def +=(n: Int) = { peer.addRowSelectionInterval(n,n); this }
       
       def leadIndex: Int = peer.getSelectionModel.getLeadSelectionIndex
       def anchorIndex: Int = peer.getSelectionModel.getAnchorSelectionIndex
     }
     
     object columns extends SelectionSet(peer.getSelectedColumns) { 
-      def -=(n: Int) { peer.removeColumnSelectionInterval(n,n) }
-      def +=(n: Int) { peer.addColumnSelectionInterval(n,n) }
+      def -=(n: Int) = { peer.removeColumnSelectionInterval(n,n); this }
+      def +=(n: Int) = { peer.addColumnSelectionInterval(n,n); this }
       
       def leadIndex: Int = peer.getColumnModel.getSelectionModel.getLeadSelectionIndex
       def anchorIndex: Int = peer.getColumnModel.getSelectionModel.getAnchorSelectionIndex
     }
 
-    def cells: Set[(Int, Int)] = 
+    def cells: mutable.Set[(Int, Int)] = 
       new SelectionSet[(Int, Int)]((for(r <- selection.rows; c <- selection.columns) yield (r,c)).toSeq) { outer =>
-        def -=(n: (Int, Int)) { 
+        def -=(n: (Int, Int)) = { 
           peer.removeRowSelectionInterval(n._1,n._1)
-          peer.removeColumnSelectionInterval(n._2,n._2) 
+          peer.removeColumnSelectionInterval(n._2,n._2)
+          this
         }
-        def +=(n: (Int, Int)) { 
+        def +=(n: (Int, Int)) = { 
           peer.addRowSelectionInterval(n._1,n._1)
-          peer.addColumnSelectionInterval(n._2,n._2) 
+          peer.addColumnSelectionInterval(n._2,n._2)
+          this
         }
         override def size = peer.getSelectedRowCount * peer.getSelectedColumnCount
       }
@@ -198,7 +218,7 @@ class Table extends Component with Scrollable with Publisher {
      * but the result is a table that does not produce useful selections.
      */
     def intervalMode: IntervalMode.Value = IntervalMode(peer.getSelectionModel.getSelectionMode)
-    def intervalMode_=(m: IntervalMode.Value) { peer.getSelectionModel.setSelectionMode(m.id) }
+    def intervalMode_=(m: IntervalMode.Value) { peer.setSelectionMode(m.id) }
     def elementMode: ElementMode.Value = 
       if(peer.getColumnSelectionAllowed && peer.getRowSelectionAllowed) ElementMode.Cell
       else if(peer.getColumnSelectionAllowed) ElementMode.Column
@@ -225,26 +245,24 @@ class Table extends Component with Scrollable with Publisher {
     })
   }
   
-  private val initialRenderer = peer.getDefaultRenderer(classOf[AnyRef])
-  
   /**
    * Supplies a renderer component for a given cell.
    */
-  protected def rendererComponent(isSelected: Boolean, hasFocus: Boolean, row: Int, column: Int): Component = 
+  protected def rendererComponent(isSelected: Boolean, focused: Boolean, row: Int, column: Int): Component = 
     new Component { 
       override lazy val peer = {
-        val v = Table.this.peer.getValueAt(row, column)
+        val v = apply(row, column).asInstanceOf[AnyRef]
         if (v != null)
           Table.this.peer.getDefaultRenderer(v.getClass).getTableCellRendererComponent(Table.this.peer, 
-                 v, isSelected, hasFocus, row, column).asInstanceOf[JComponent]
+                 v, isSelected, focused, row, column).asInstanceOf[JComponent]
         else Table.this.peer.getDefaultRenderer(classOf[Object]).getTableCellRendererComponent(Table.this.peer, 
-                 v, isSelected, hasFocus, row, column).asInstanceOf[JComponent]
+                 v, isSelected, focused, row, column).asInstanceOf[JComponent]
       }
     }
   
   // TODO: a public API for setting editors
   protected def editor(row: Int, column: Int) = {
-    val v = Table.this.peer.getValueAt(row, column)
+    val v = apply(row, column).asInstanceOf[AnyRef]
     if (v != null)
       Table.this.peer.getDefaultEditor(v.getClass)
     else
@@ -252,14 +270,20 @@ class Table extends Component with Scrollable with Publisher {
   }
   
   /**
-   * Get the current value of the given cell.
+   * Get the current value of the given cell. 
+   * The given cell coordinates are in view coordinates and thus not 
+   * necessarily the same as for the model.
    */
-  def apply(row: Int, column: Int): Any = model.getValueAt(row, column)
+  def apply(row: Int, column: Int): Any = model.getValueAt(row, viewToModelColumn(column))
+  
+  def viewToModelColumn(idx: Int) = peer.convertColumnIndexToModel(idx)
+  def modelToViewColumn(idx: Int) = peer.convertColumnIndexToView(idx)
+
   
   /**
    * Change the value of the given cell.
    */
-  def update(row: Int, column: Int, value: Any) { model.setValueAt(value, row, column) }
+  def update(row: Int, column: Int, value: Any) { model.setValueAt(value, row, viewToModelColumn(column)) }
 
   /**
    * Visually update the given cell.
@@ -275,7 +299,7 @@ class Table extends Component with Scrollable with Publisher {
     def tableChanged(e: TableModelEvent) = publish(
       e.getType match {
         case TableModelEvent.UPDATE =>
-          if (e.getFirstRow == 0 && e.getLastRow == Math.MAX_INT && e.getColumn == TableModelEvent.ALL_COLUMNS)
+          if (e.getFirstRow == 0 && e.getLastRow == Int.MaxValue && e.getColumn == TableModelEvent.ALL_COLUMNS)
             TableChanged(Table.this)
           else if (e.getFirstRow == TableModelEvent.HEADER_ROW)
             TableStructureChanged(Table.this)
@@ -288,5 +312,4 @@ class Table extends Component with Scrollable with Publisher {
       }
     )
   }
-  model.addTableModelListener(modelListener)
 }
diff --git a/src/swing/scala/swing/TextArea.scala b/src/swing/scala/swing/TextArea.scala
index 8f8ebc2..0292a88 100644
--- a/src/swing/scala/swing/TextArea.scala
+++ b/src/swing/scala/swing/TextArea.scala
@@ -1,16 +1,27 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
 package scala.swing
 
+import event._
 import javax.swing._
 import java.awt.event._
-import event._
 
 /**
  * A text component that allows multiline text input and display.
  *
  * @see javax.swing.JTextArea
  */
-class TextArea(text0: String, rows0: Int, columns0: Int) extends TextComponent with TextComponent.HasColumns with TextComponent.HasRows {
-  override lazy val peer: JTextArea = new JTextArea(text0, rows0, columns0)
+class TextArea(text0: String, rows0: Int, columns0: Int) extends TextComponent 
+    with TextComponent.HasColumns with TextComponent.HasRows {
+  override lazy val peer: JTextArea = new JTextArea(text0, rows0, columns0) with SuperMixin
   def this(text: String) = this(text, 0, 0)
   def this(rows: Int, columns: Int) = this("", rows, columns)
   def this() = this("", 0, 0)
@@ -33,4 +44,4 @@ class TextArea(text0: String, rows0: Int, columns0: Int) extends TextComponent w
   def wordWrap_=(w: Boolean) = peer.setWrapStyleWord(w)
   def charWrap: Boolean = !peer.getWrapStyleWord
   def charWrap_=(w: Boolean) = peer.setWrapStyleWord(!w)
-}
\ No newline at end of file
+}
diff --git a/src/swing/scala/swing/TextComponent.scala b/src/swing/scala/swing/TextComponent.scala
index d47fba0..5abc5cc 100644
--- a/src/swing/scala/swing/TextComponent.scala
+++ b/src/swing/scala/swing/TextComponent.scala
@@ -1,9 +1,19 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
 package scala.swing
 
+import event._
 import javax.swing._
 import javax.swing.text._
 import javax.swing.event._
-import event._
 
 object TextComponent {
   trait HasColumns extends TextComponent { 
@@ -37,6 +47,10 @@ class TextComponent extends Component with Publisher {
     def selectionVisible_=(b: Boolean) { peer.getCaret.setSelectionVisible(b) }
     def blinkRate: Int = peer.getCaret.getBlinkRate
     def blinkRate_=(n: Int) { peer.getCaret.setBlinkRate(n) }
+    def color: Color = peer.getCaretColor
+    def color_=(c: Color) = peer.setCaretColor(c)
+    def position: Int = peer.getCaretPosition
+    def position_=(p: Int) = peer.setCaretPosition(p)
     
     peer.addCaretListener {
       new CaretListener {
@@ -51,13 +65,14 @@ class TextComponent extends Component with Publisher {
   def editable_=(x: Boolean) = peer.setEditable(x)
   def cut() { peer.cut() }
   def copy() { peer.copy() }
+  def paste() { peer.paste() }
   def selected: String = peer.getSelectedText
   
   def selectAll() { peer.selectAll() }
   
   peer.getDocument.addDocumentListener(new DocumentListener {
-    def changedUpdate(e:DocumentEvent) { publish(ValueChanged(TextComponent.this)) }
-    def insertUpdate(e:DocumentEvent) { publish(ValueChanged(TextComponent.this)) }
-    def removeUpdate(e:DocumentEvent) { publish(ValueChanged(TextComponent.this)) }
+    def changedUpdate(e:DocumentEvent) { publish(new ValueChanged(TextComponent.this)) }
+    def insertUpdate(e:DocumentEvent) { publish(new ValueChanged(TextComponent.this)) }
+    def removeUpdate(e:DocumentEvent) { publish(new ValueChanged(TextComponent.this)) }
   })
-}
\ No newline at end of file
+}
diff --git a/src/swing/scala/swing/TextField.scala b/src/swing/scala/swing/TextField.scala
index 07edead..d7dd83c 100644
--- a/src/swing/scala/swing/TextField.scala
+++ b/src/swing/scala/swing/TextField.scala
@@ -1,8 +1,18 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
 package scala.swing
 
+import event._
 import javax.swing._
 import java.awt.event._
-import event._
 
 
 /*object TextField {
@@ -19,7 +29,7 @@ import event._
  * 
  * @see javax.swing.JTextField
  */
-class TextField(text0: String, columns0: Int) extends TextComponent with TextComponent.HasColumns {
+class TextField(text0: String, columns0: Int) extends TextComponent with TextComponent.HasColumns with Action.Trigger.Wrapper {
   override lazy val peer: JTextField = new JTextField(text0, columns0) with SuperMixin 
   def this(text: String) = this(text, 0)
   def this(columns: Int) = this("", columns)
@@ -28,26 +38,41 @@ class TextField(text0: String, columns0: Int) extends TextComponent with TextCom
   def columns: Int = peer.getColumns
   def columns_=(n: Int) = peer.setColumns(n)
 
-  peer.addActionListener(Swing.ActionListener { e =>
+  /** @see javax.swing.JTextField#getHorizontalAlignment() */
+  def horizontalAlignment: Alignment.Value = Alignment(peer.getHorizontalAlignment)
+  /** @see javax.swing.JTextField#setHorizontalAlignment() */
+  def horizontalAlignment_=(x: Alignment.Value) { peer.setHorizontalAlignment(x.id) }
+  
+  private lazy val actionListener = Swing.ActionListener { e =>
     publish(EditDone(TextField.this))
-  })
+  }
   
-  peer.addFocusListener(new FocusAdapter {
-    override def focusLost(e: java.awt.event.FocusEvent) { EditDone(TextField.this) }
-  })
+  protected override def onFirstSubscribe {
+    super.onFirstSubscribe
+    peer.addActionListener(actionListener)
+    peer.addFocusListener(new FocusAdapter {
+      override def focusLost(e: java.awt.event.FocusEvent) { publish(EditDone(TextField.this)) }
+    })
+  }
+  
+  protected override def onLastUnsubscribe {
+    super.onLastUnsubscribe
+    peer.removeActionListener(actionListener)
+  }
   
   def verifier: String => Boolean = s => peer.getInputVerifier.verify(peer) 
   def verifier_=(v: String => Boolean) { 
     peer.setInputVerifier(new InputVerifier {
+      private val old = peer.getInputVerifier
       def verify(c: JComponent) = v(text)
-      override def shouldYieldFocus(c: JComponent) = 
-        peer.getInputVerifier.shouldYieldFocus(c)
+      override def shouldYieldFocus(c: JComponent) = old.shouldYieldFocus(c)
     }) 
   }
   def shouldYieldFocus: String=>Boolean = s => peer.getInputVerifier.shouldYieldFocus(peer)
   def shouldYieldFocus_=(y: String=>Boolean) { 
     peer.setInputVerifier(new InputVerifier {
-      def verify(c: JComponent) = peer.getInputVerifier.verify(c)
+      private val old = peer.getInputVerifier
+      def verify(c: JComponent) = old.verify(c)
       override def shouldYieldFocus(c: JComponent) = y(text)
     })
   }
diff --git a/src/swing/scala/swing/ToggleButton.scala b/src/swing/scala/swing/ToggleButton.scala
index 2eb2c0d..0e7b7f0 100644
--- a/src/swing/scala/swing/ToggleButton.scala
+++ b/src/swing/scala/swing/ToggleButton.scala
@@ -1,7 +1,17 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
 package scala.swing
 
-import javax.swing._
 import event._
+import javax.swing._
 
 /**
  * A two state button with a push button like user interface. 
@@ -10,6 +20,6 @@ import event._
  * @see javax.swing.JToggleButton
  */
 class ToggleButton(text0: String) extends AbstractButton {
-  override lazy val peer: JToggleButton = new JToggleButton(text0)
+  override lazy val peer: JToggleButton = new JToggleButton(text0) with SuperMixin
   def this() = this("")
 }
diff --git a/src/swing/scala/swing/UIElement.scala b/src/swing/scala/swing/UIElement.scala
index 19bee4d..d58d12f 100644
--- a/src/swing/scala/swing/UIElement.scala
+++ b/src/swing/scala/swing/UIElement.scala
@@ -1,18 +1,85 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
 package scala.swing
 
-import java.awt.{Color, Cursor, Font, Dimension}
+import java.awt.Cursor
+import event._
+import scala.collection.mutable.HashMap
+import scala.ref._
+import java.util.WeakHashMap
+
+object UIElement {
+  private val ClientKey = "scala.swingWrapper"
+  private[this] val wrapperCache = new WeakHashMap[java.awt.Component, WeakReference[UIElement]]
+
+  private def cache(e: UIElement) = e.peer match {
+    case p: javax.swing.JComponent => p.putClientProperty(ClientKey, e)
+    case _ => wrapperCache.put(e.peer, new WeakReference(e))
+  }
+  
+  /**
+   * Looks up the internal component cache for a wrapper of the given 
+   * Java Swing peer. If this method finds one of the given type `C`, 
+   * it will return that wrapper. Otherwise it returns `null`. This 
+   * method never throws an exception.
+   * 
+   * Clients should be extremely careful with type parameter `C` and 
+   * its interaction with type inference. Better err on the side of caution 
+   * and explicitly specify `C`.  
+   */
+  private[swing] def cachedWrapper[C>:Null<:UIElement](c: java.awt.Component): C = {
+    val w = c match {
+      case c: javax.swing.JComponent => c.getClientProperty(ClientKey)
+      case _ => wrapperCache.get(c)
+    }
+    try { w.asInstanceOf[C] } catch { case _ => null }
+  }
+  
+  /**
+   * Returns a wrapper for a given Java Swing peer. If there is a 
+   * compatible wrapper in use, this method will return it.
+   * 
+   * `wrap` methods in companion objects of subclasses of UIElement have the 
+   * same behavior, except that they return more specific wrappers.
+   */
+  def wrap(c: java.awt.Component): UIElement = {
+    val w = cachedWrapper[UIElement](c)
+    if (w != null) w 
+    else new UIElement { def peer = c }
+  }
+}
 
 /**
  * The base trait of all user interface elements. Subclasses belong to one 
  * of two groups: top-level elements such as windows and dialogs, or 
  * <code>Component</code>s.
  * 
+ * @note [Java Swing] This trait does not have an exact counterpart in 
+ * Java Swing. The peer is of type java.awt.Component since this is the 
+ * least common upper bound of possible underlying peers.
+ * 
+ * @note [Implementation] A UIElement automatically adds itself to the 
+ * component cache on creation.
+ * 
  * @see java.awt.Component
  */
-trait UIElement extends Proxy {
+trait UIElement extends Proxy with LazyPublisher {
+  /**
+   * The underlying Swing peer.
+   */
   def peer: java.awt.Component
   def self = peer
   
+  UIElement.cache(this)
+  
   def foreground: Color = peer.getForeground
   def foreground_=(c: Color) = peer.setForeground(c)
   def background: Color = peer.getBackground
@@ -24,7 +91,6 @@ trait UIElement extends Proxy {
   def maximumSize_=(x: Dimension) = peer.setMaximumSize(x)
   def preferredSize = peer.getPreferredSize
   def preferredSize_=(x: Dimension) = peer.setPreferredSize(x)
-  def preferredSize_=(xy: (Int, Int)) { peer.setPreferredSize(new Dimension(xy._1, xy._2)) }
   
   def font: Font = peer.getFont
   def font_=(f: Font) = peer.setFont(f)
@@ -33,8 +99,10 @@ trait UIElement extends Proxy {
   def location = peer.getLocation
   def bounds = peer.getBounds
   def size = peer.getSize
+  @deprecated("Explicit size assignement for UIElements is not supported anymore. " +
+  		"Use a layout manager or subclass Window.") 
   def size_=(dim: Dimension) = peer.setSize(dim)
-  def size_=(xy: (Int, Int)) { peer.setSize(new Dimension(xy._1, xy._2)) }
+
   def locale = peer.getLocale
   def toolkit = peer.getToolkit
   
@@ -44,6 +112,28 @@ trait UIElement extends Proxy {
   def visible: Boolean = peer.isVisible
   def visible_=(b: Boolean) { peer.setVisible(b) }
   def showing: Boolean = peer.isShowing
+  def displayable: Boolean = peer.isDisplayable
   
   def repaint() { peer.repaint }
+  def repaint(rect: Rectangle) { peer.repaint(rect.x, rect.y, rect.width, rect.height) }
+  def ignoreRepaint: Boolean = peer.getIgnoreRepaint
+  def ignoreRepaint_=(b: Boolean) { peer.setIgnoreRepaint(b) }
+  
+  protected def onFirstSubscribe {
+    peer.addComponentListener(new java.awt.event.ComponentListener {
+      def componentHidden(e: java.awt.event.ComponentEvent) { 
+        publish(UIElementHidden(UIElement.this)) 
+      }
+      def componentShown(e: java.awt.event.ComponentEvent) { 
+        publish(UIElementShown(UIElement.this)) 
+      }
+      def componentMoved(e: java.awt.event.ComponentEvent) { 
+        publish(UIElementMoved(UIElement.this)) 
+      }
+      def componentResized(e: java.awt.event.ComponentEvent) { 
+        publish(UIElementResized(UIElement.this)) 
+      }
+    })
+  }
+  protected def onLastUnsubscribe {}
 }
diff --git a/src/swing/scala/swing/Views.scala b/src/swing/scala/swing/Views.scala
deleted file mode 100644
index 0b7305e..0000000
--- a/src/swing/scala/swing/Views.scala
+++ /dev/null
@@ -1,7 +0,0 @@
-package scala.swing
-
-//object Views {
-  //implicit def action2MenuItem(a: Action): MenuItem = new MenuItem(a)
-  //implicit def action2Button(a: Action): Button = new Button(a)
-  //implicit def string2Label(s: String): Label = new Label(s)
-//}
diff --git a/src/swing/scala/swing/Window.scala b/src/swing/scala/swing/Window.scala
new file mode 100644
index 0000000..101cd2d
--- /dev/null
+++ b/src/swing/scala/swing/Window.scala
@@ -0,0 +1,73 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.swing
+
+import java.awt.{Window => AWTWindow}
+import event._
+import javax.swing._
+
+/**
+ * A window with decoration such as a title, border, and action buttons.
+ * 
+ * An AWT window cannot be wrapped dynamically with this class, i.e., you cannot 
+ * write something like new Window { def peer = myAWTWindow }
+ * 
+ * @see javax.swing.JFrame
+ */
+abstract class Window extends UIElement with RootPanel with Publisher { outer =>
+  def peer: AWTWindow with InterfaceMixin
+  
+  protected trait InterfaceMixin extends javax.swing.RootPaneContainer
+  
+  /**
+   * This method is called when the window is closing, after all other window 
+   * event listeners have been processed.
+   */
+  def closeOperation() {}
+
+  override def contents_=(c: Component) {
+    super.contents_=(c)
+    peer.pack() // pack also validates, which is generally required after an add
+  }
+  def defaultButton: Option[Button] = 
+    toOption(peer.getRootPane.getDefaultButton) map UIElement.cachedWrapper[Button]
+  def defaultButton_=(b: Button) { 
+    peer.getRootPane.setDefaultButton(b.peer) 
+  }
+  def defaultButton_=(b: Option[Button]) { 
+    peer.getRootPane.setDefaultButton(b map (_.peer) orNull)
+  }
+  
+  def dispose() { peer.dispose() }
+  
+  def pack(): this.type = { peer.pack(); this }
+  
+  def setLocationRelativeTo(c: UIElement) { peer.setLocationRelativeTo(c.peer) }
+  def centerOnScreen() { peer.setLocationRelativeTo(null) }
+  def location_=(p: Point) { peer.setLocation(p) }
+  override def size_=(size: Dimension) { peer.setSize(size) }
+  def bounds_=(rect: Rectangle) { peer.setBounds(rect) }
+  
+  def owner: Window = UIElement.cachedWrapper[Window](peer.getOwner)
+  
+  def open() { peer setVisible true }
+  def close() { peer setVisible false }
+  
+  peer.addWindowListener(new java.awt.event.WindowListener {
+    def windowActivated(e: java.awt.event.WindowEvent) { publish(WindowActivated(outer)) }
+    def windowClosed(e: java.awt.event.WindowEvent) { publish(WindowClosed(outer)) }
+    def windowClosing(e: java.awt.event.WindowEvent) { publish(WindowClosing(outer)) }
+    def windowDeactivated(e: java.awt.event.WindowEvent) { publish(WindowDeactivated(outer)) }
+    def windowDeiconified(e: java.awt.event.WindowEvent) { publish(WindowDeiconified(outer)) }
+    def windowIconified(e: java.awt.event.WindowEvent) { publish(WindowIconified(outer)) }
+    def windowOpened(e: java.awt.event.WindowEvent) { publish(WindowOpened(outer)) }
+  })
+}
diff --git a/src/swing/scala/swing/event/ActionEvent.scala b/src/swing/scala/swing/event/ActionEvent.scala
index c800f20..83df36a 100644
--- a/src/swing/scala/swing/event/ActionEvent.scala
+++ b/src/swing/scala/swing/event/ActionEvent.scala
@@ -1,3 +1,18 @@
-package scala.swing.event
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
 
-case class ActionEvent(override val source: Component) extends ComponentEvent
+
+
+package scala.swing
+package event
+
+object ActionEvent {
+  def unapply(a: ActionEvent): Option[Component] = Some(a.source)
+}
+
+class ActionEvent(override val source: Component) extends ComponentEvent
diff --git a/src/swing/scala/swing/event/AdjustingEvent.scala b/src/swing/scala/swing/event/AdjustingEvent.scala
index ad3aa5f..823ee1f 100644
--- a/src/swing/scala/swing/event/AdjustingEvent.scala
+++ b/src/swing/scala/swing/event/AdjustingEvent.scala
@@ -1,11 +1,25 @@
-package scala.swing.event
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
 
-/**
- * An event that indicates some editing operation that can be still in progress. 
- * Example: dragging a slider creates a number of AdjustmentEvents with 
- * adjusting == true until the user finally releases the mouse button.
+
+
+package scala.swing
+package event
+
+/** <p>
+ *    An event that indicates some editing operation that can be still in
+ *    progress.<br/> 
+ *    Example: dragging a slider creates a number of <code>AdjustmentEvents</code>
+ *    with <code>adjusting == true</code> until the user finally releases the
+ *    mouse button.
+ *  </p>
  */
 trait AdjustingEvent extends ComponentEvent {
   def adjusting: Boolean
   def committed: Boolean = !adjusting
-}
\ No newline at end of file
+}
diff --git a/src/swing/scala/swing/event/BackgroundChanged.scala b/src/swing/scala/swing/event/BackgroundChanged.scala
index 6673ec4..3b6a71b 100644
--- a/src/swing/scala/swing/event/BackgroundChanged.scala
+++ b/src/swing/scala/swing/event/BackgroundChanged.scala
@@ -1,3 +1,14 @@
-package scala.swing.event
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.swing
+package event
 
 case class BackgroundChanged(override val source: Component) extends ComponentEvent
diff --git a/src/swing/scala/swing/event/ButtonClicked.scala b/src/swing/scala/swing/event/ButtonClicked.scala
index 1f9049a..b5bd5eb 100644
--- a/src/swing/scala/swing/event/ButtonClicked.scala
+++ b/src/swing/scala/swing/event/ButtonClicked.scala
@@ -1,4 +1,15 @@
-package scala.swing.event
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.swing
+package event
 
 case class ButtonClicked(override val source: AbstractButton) extends ActionEvent(source)
 
diff --git a/src/swing/scala/swing/event/CaretUpdate.scala b/src/swing/scala/swing/event/CaretUpdate.scala
index f5cd170..0560159 100644
--- a/src/swing/scala/swing/event/CaretUpdate.scala
+++ b/src/swing/scala/swing/event/CaretUpdate.scala
@@ -1,3 +1,14 @@
-package scala.swing.event
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.swing
+package event
 
 case class CaretUpdate(override val source: TextComponent) extends ComponentEvent
diff --git a/src/swing/scala/swing/event/ComponentEvent.scala b/src/swing/scala/swing/event/ComponentEvent.scala
index a76207d..ae015ef 100644
--- a/src/swing/scala/swing/event/ComponentEvent.scala
+++ b/src/swing/scala/swing/event/ComponentEvent.scala
@@ -1,10 +1,25 @@
-package scala.swing.event
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.swing
+package event
 
 trait ComponentEvent extends UIEvent {
-  override val source: Component
+  val source: Component
 }
 
-case class ComponentMoved(override val source: Component) extends ComponentEvent
-case class ComponentResized(override val source: Component) extends ComponentEvent
-case class ComponentShown(override val source: Component) extends ComponentEvent
-case class ComponentHidden(override val source: Component) extends ComponentEvent
+ at deprecated("Use UIElementMoved instead.") 
+case class ComponentMoved(source: Component) extends ComponentEvent
+ at deprecated("Use UIElementResized instead.") 
+case class ComponentResized(source: Component) extends ComponentEvent
+ at deprecated("Use UIElementShown instead.") 
+case class ComponentShown(source: Component) extends ComponentEvent
+ at deprecated("Use UIElementHidden instead.") 
+case class ComponentHidden(source: Component) extends ComponentEvent
diff --git a/src/swing/scala/swing/event/ContainerEvent.scala b/src/swing/scala/swing/event/ContainerEvent.scala
index d15b070..5eecf6a 100644
--- a/src/swing/scala/swing/event/ContainerEvent.scala
+++ b/src/swing/scala/swing/event/ContainerEvent.scala
@@ -1,4 +1,15 @@
-package scala.swing.event
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.swing
+package event
 
 abstract class ContainerEvent(override val source: Container) extends UIEvent
 
diff --git a/src/swing/scala/swing/event/EditDone.scala b/src/swing/scala/swing/event/EditDone.scala
index b802a1a..250cf6f 100644
--- a/src/swing/scala/swing/event/EditDone.scala
+++ b/src/swing/scala/swing/event/EditDone.scala
@@ -1,3 +1,14 @@
-package scala.swing.event
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.swing
+package event
 
 case class EditDone(override val source: TextField) extends ValueChanged(source)
diff --git a/src/swing/scala/swing/event/Event.scala b/src/swing/scala/swing/event/Event.scala
index 4de5930..3e04ae6 100644
--- a/src/swing/scala/swing/event/Event.scala
+++ b/src/swing/scala/swing/event/Event.scala
@@ -1,3 +1,14 @@
-package scala.swing.event
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.swing
+package event
 
 trait Event
diff --git a/src/swing/scala/swing/event/FocusEvent.scala b/src/swing/scala/swing/event/FocusEvent.scala
index c914b41..d20bdd5 100644
--- a/src/swing/scala/swing/event/FocusEvent.scala
+++ b/src/swing/scala/swing/event/FocusEvent.scala
@@ -1,4 +1,15 @@
-package scala.swing.event
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.swing
+package event
 
 /**
  * The other component is None if it is a non Swing, i.e., AWT or native, component.
@@ -9,4 +20,4 @@ case class FocusGained(override val source: Component, override val other: Optio
            extends FocusEvent(source, other, temporary) 
 
 case class FocusLost(override val source: Component, override val other: Option[Component], override val temporary: Boolean) 
-           extends FocusEvent(source, other, temporary) 
\ No newline at end of file
+           extends FocusEvent(source, other, temporary) 
diff --git a/src/swing/scala/swing/event/FontChanged.scala b/src/swing/scala/swing/event/FontChanged.scala
index b2e0902..701d279 100644
--- a/src/swing/scala/swing/event/FontChanged.scala
+++ b/src/swing/scala/swing/event/FontChanged.scala
@@ -1,3 +1,14 @@
-package scala.swing.event
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.swing
+package event
 
 case class FontChanged(override val source: Component) extends ComponentEvent
diff --git a/src/swing/scala/swing/event/ForegroundChanged.scala b/src/swing/scala/swing/event/ForegroundChanged.scala
index 94a1a8a..4a11de8 100644
--- a/src/swing/scala/swing/event/ForegroundChanged.scala
+++ b/src/swing/scala/swing/event/ForegroundChanged.scala
@@ -1,3 +1,14 @@
-package scala.swing.event
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.swing
+package event
 
 case class ForegroundChanged(override val source: Component) extends ComponentEvent
diff --git a/src/swing/scala/swing/event/InputEvent.scala b/src/swing/scala/swing/event/InputEvent.scala
index ae24d53..69cbdba 100644
--- a/src/swing/scala/swing/event/InputEvent.scala
+++ b/src/swing/scala/swing/event/InputEvent.scala
@@ -1,6 +1,20 @@
-package scala.swing.event
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.swing
+package event
 
 trait InputEvent extends ComponentEvent {
-  val when: Long
-  val modifiers: Int
+  def peer: java.awt.event.InputEvent
+  def when: Long = peer.getWhen
+  def modifiers: Key.Modifiers
+  def consume() { peer.consume() }
+  def consumed: Boolean = peer.isConsumed
 }
diff --git a/src/swing/scala/swing/event/Key.scala b/src/swing/scala/swing/event/Key.scala
new file mode 100644
index 0000000..ec72767
--- /dev/null
+++ b/src/swing/scala/swing/event/Key.scala
@@ -0,0 +1,232 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.swing
+package event
+
+/**
+ * Enumeration of key codes used by key events.
+ */
+object Key extends Enumeration {
+  import java.awt.event.KeyEvent._
+
+  object Location extends Enumeration {
+    val Left = Value(java.awt.event.KeyEvent.KEY_LOCATION_LEFT)
+    val Right = Value(java.awt.event.KeyEvent.KEY_LOCATION_RIGHT)
+    val Numpad = Value(java.awt.event.KeyEvent.KEY_LOCATION_NUMPAD)
+    val Standard = Value(java.awt.event.KeyEvent.KEY_LOCATION_STANDARD)
+    val Unknown = Value(java.awt.event.KeyEvent.KEY_LOCATION_UNKNOWN)
+  }
+  
+  type Modifiers = Int
+  
+  object Modifier {
+    import java.awt.event.InputEvent._
+    val Shift = SHIFT_DOWN_MASK
+    val Control = CTRL_DOWN_MASK
+    val Alt = ALT_DOWN_MASK
+    val AltGraph = ALT_GRAPH_DOWN_MASK
+    val Meta = META_DOWN_MASK
+    def text(mods: Int) = java.awt.event.KeyEvent.getKeyModifiersText(mods)
+  }
+  
+  //def text(k: Value) = java.awt.event.KeyEvent.getKeyText(k.id)
+  
+  val Shift = Value(VK_SHIFT, getKeyText(VK_SHIFT))
+  val Control = Value(VK_CONTROL, getKeyText(VK_CONTROL))
+  val Alt = Value(VK_ALT, getKeyText(VK_ALT))
+  val AltGraph = Value(VK_ALT_GRAPH, getKeyText(VK_ALT_GRAPH))
+  val Meta = Value(VK_META, getKeyText(VK_META))
+  
+  val Enter = Value(VK_ENTER, getKeyText(VK_ENTER))
+  val BackSpace = Value(VK_BACK_SPACE, getKeyText(VK_BACK_SPACE))
+  val Tab = Value(VK_TAB, getKeyText(VK_TAB))
+  val Cancel = Value(VK_CANCEL, getKeyText(VK_CANCEL))
+  val Clear = Value(VK_CLEAR, getKeyText(VK_CLEAR))
+  
+  val Pause = Value(VK_PAUSE, getKeyText(VK_PAUSE))
+  val CapsLock = Value(VK_CAPS_LOCK, getKeyText(VK_CAPS_LOCK))
+  val Escape = Value(VK_ESCAPE, getKeyText(VK_ESCAPE))
+  val Space = Value(VK_SPACE, getKeyText(VK_SPACE))
+  val PageUp = Value(VK_PAGE_UP, getKeyText(VK_PAGE_UP))
+  val PageDown = Value(VK_PAGE_DOWN, getKeyText(VK_PAGE_DOWN))
+  val End = Value(VK_END, getKeyText(VK_END))
+  val Home = Value(VK_HOME, getKeyText(VK_HOME))
+  val Left = Value(VK_LEFT, getKeyText(VK_LEFT))
+  val Up = Value(VK_UP, getKeyText(VK_UP))
+  val Right = Value(VK_RIGHT, getKeyText(VK_RIGHT))
+  val Down = Value(VK_DOWN, getKeyText(VK_DOWN))
+  val Comma = Value(VK_COMMA, getKeyText(VK_COMMA))
+  val Minus = Value(VK_MINUS, getKeyText(VK_MINUS))
+  val Period = Value(VK_PERIOD, getKeyText(VK_PERIOD))
+  val Slash = Value(VK_SLASH, getKeyText(VK_SLASH))
+  val Key0 = Value(VK_0, getKeyText(VK_0))
+  val Key1 = Value(VK_1, getKeyText(VK_1))
+  val Key2 = Value(VK_2, getKeyText(VK_2))
+  val Key3 = Value(VK_3, getKeyText(VK_3))
+  val Key4 = Value(VK_4, getKeyText(VK_4))
+  val Key5 = Value(VK_5, getKeyText(VK_5))
+  val Key6 = Value(VK_6, getKeyText(VK_6))
+  val Key7 = Value(VK_7, getKeyText(VK_7))
+  val Key8 = Value(VK_8, getKeyText(VK_8))
+  val Key9 = Value(VK_9, getKeyText(VK_9))
+  val Semicolon = Value(VK_SEMICOLON, getKeyText(VK_SEMICOLON))
+  val Equals = Value(VK_EQUALS, getKeyText(VK_EQUALS))
+  val A = Value(VK_A, getKeyText(VK_A))
+  val B = Value(VK_B, getKeyText(VK_B))
+  val C = Value(VK_C, getKeyText(VK_C))
+  val D = Value(VK_D, getKeyText(VK_D))
+  val E = Value(VK_E, getKeyText(VK_E))
+  val F = Value(VK_F, getKeyText(VK_F))
+  val G = Value(VK_G, getKeyText(VK_G))
+  val H = Value(VK_H, getKeyText(VK_H))
+  val I = Value(VK_I, getKeyText(VK_I))
+  val J = Value(VK_J, getKeyText(VK_J))
+  val K = Value(VK_K, getKeyText(VK_K))
+  val L = Value(VK_L, getKeyText(VK_L))
+  val M = Value(VK_M, getKeyText(VK_M))
+  val N = Value(VK_N, getKeyText(VK_N))
+  val O = Value(VK_O, getKeyText(VK_O))
+  val P = Value(VK_P, getKeyText(VK_P))
+  val Q = Value(VK_Q, getKeyText(VK_Q))
+  val R = Value(VK_R, getKeyText(VK_R))
+  val S = Value(VK_S, getKeyText(VK_S))
+  val T = Value(VK_T, getKeyText(VK_T))
+  val U = Value(VK_U, getKeyText(VK_U))
+  val V = Value(VK_V, getKeyText(VK_V))
+  val W = Value(VK_W, getKeyText(VK_W))
+  val X = Value(VK_X, getKeyText(VK_X))
+  val Y = Value(VK_Y, getKeyText(VK_Y))
+  val Z = Value(VK_Z, getKeyText(VK_Z))
+  val OpenBracket = Value(VK_OPEN_BRACKET, getKeyText(VK_OPEN_BRACKET))
+  val BackSlash = Value(VK_BACK_SLASH, getKeyText(VK_BACK_SLASH))
+  val CloseBracket = Value(VK_CLOSE_BRACKET, getKeyText(VK_CLOSE_BRACKET))
+  val Numpad0 = Value(VK_NUMPAD0, getKeyText(VK_NUMPAD0))
+  val Numpad1 = Value(VK_NUMPAD1, getKeyText(VK_NUMPAD1))
+  val Numpad2 = Value(VK_NUMPAD2, getKeyText(VK_NUMPAD2))
+  val Numpad3 = Value(VK_NUMPAD3, getKeyText(VK_NUMPAD3))
+  val Numpad4 = Value(VK_NUMPAD4, getKeyText(VK_NUMPAD4))
+  val Numpad5 = Value(VK_NUMPAD5, getKeyText(VK_NUMPAD5))
+  val Numpad6 = Value(VK_NUMPAD6, getKeyText(VK_NUMPAD6))
+  val Numpad7 = Value(VK_NUMPAD7, getKeyText(VK_NUMPAD7))
+  val Numpad8 = Value(VK_NUMPAD8, getKeyText(VK_NUMPAD8))
+  val Numpad9 = Value(VK_NUMPAD9, getKeyText(VK_NUMPAD9))
+  val Multiply = Value(VK_MULTIPLY, getKeyText(VK_MULTIPLY))
+  val Add = Value(VK_ADD, getKeyText(VK_ADD))
+  val Separator = Value(VK_SEPARATOR, getKeyText(VK_SEPARATOR))
+  val Subtract = Value(VK_SUBTRACT, getKeyText(VK_SUBTRACT))
+  val Decimal = Value(VK_DECIMAL, getKeyText(VK_DECIMAL))
+  val Divide = Value(VK_DIVIDE, getKeyText(VK_DIVIDE))
+  val Delete = Value(VK_DELETE, getKeyText(VK_DELETE))
+  val NumLock = Value(VK_NUM_LOCK, getKeyText(VK_NUM_LOCK))
+  val ScrollLock = Value(VK_SCROLL_LOCK, getKeyText(VK_SCROLL_LOCK))
+  val F1 = Value(VK_F1, getKeyText(VK_F1))
+  val F2 = Value(VK_F2, getKeyText(VK_F2))
+  val F3 = Value(VK_F3, getKeyText(VK_F3))
+  val F4 = Value(VK_F4, getKeyText(VK_F4))
+  val F5 = Value(VK_F5, getKeyText(VK_F5))
+  val F6 = Value(VK_F6, getKeyText(VK_F6))
+  val F7 = Value(VK_F7, getKeyText(VK_F7))
+  val F8 = Value(VK_F8, getKeyText(VK_F8))
+  val F9 = Value(VK_F9, getKeyText(VK_F9))
+  val F10 = Value(VK_F10, getKeyText(VK_F10))
+  val F11 = Value(VK_F11, getKeyText(VK_F11))
+  val F12 = Value(VK_F12, getKeyText(VK_F12))
+  val F13 = Value(VK_F13, getKeyText(VK_F13))
+  val F14 = Value(VK_F14, getKeyText(VK_F14))
+  val F15 = Value(VK_F15, getKeyText(VK_F15))
+  val F16 = Value(VK_F16, getKeyText(VK_F16))
+  val F17 = Value(VK_F17, getKeyText(VK_F17))
+  val F18 = Value(VK_F18, getKeyText(VK_F18))
+  val F19 = Value(VK_F19, getKeyText(VK_F19))
+  val F20 = Value(VK_F20, getKeyText(VK_F20))
+  val F21 = Value(VK_F21, getKeyText(VK_F21))
+  val F22 = Value(VK_F22, getKeyText(VK_F22))
+  val F23 = Value(VK_F23, getKeyText(VK_F23))
+  val F24 = Value(VK_F24, getKeyText(VK_F24))
+  val Printscreen = Value(VK_PRINTSCREEN, getKeyText(VK_PRINTSCREEN))
+  val Insert = Value(VK_INSERT, getKeyText(VK_INSERT))
+  val Help = Value(VK_HELP, getKeyText(VK_HELP))
+  val BackQuote = Value(VK_BACK_QUOTE, getKeyText(VK_BACK_QUOTE))
+  val Quote = Value(VK_QUOTE, getKeyText(VK_QUOTE))
+  val KpUp = Value(VK_KP_UP, getKeyText(VK_KP_UP))
+  val KpDown = Value(VK_KP_DOWN, getKeyText(VK_KP_DOWN))
+  val KpLeft = Value(VK_KP_LEFT, getKeyText(VK_KP_LEFT))
+  val KpRight = Value(VK_KP_RIGHT, getKeyText(VK_KP_RIGHT))
+  val DeadGrave = Value(VK_DEAD_GRAVE, getKeyText(VK_DEAD_GRAVE))
+  val DeadAcute = Value(VK_DEAD_ACUTE, getKeyText(VK_DEAD_ACUTE))
+  val DeadCircumflex = Value(VK_DEAD_CIRCUMFLEX, getKeyText(VK_DEAD_CIRCUMFLEX))
+  val DeadTilde = Value(VK_DEAD_TILDE, getKeyText(VK_DEAD_TILDE))
+  val DeadMacron = Value(VK_DEAD_MACRON, getKeyText(VK_DEAD_MACRON))
+  val DeadBreve = Value(VK_DEAD_BREVE, getKeyText(VK_DEAD_BREVE))
+  val DeadAbovedot = Value(VK_DEAD_ABOVEDOT, getKeyText(VK_DEAD_ABOVEDOT))
+  val DeadDiaeresis = Value(VK_DEAD_DIAERESIS, getKeyText(VK_DEAD_DIAERESIS))
+  val DeadAbovering = Value(VK_DEAD_ABOVERING, getKeyText(VK_DEAD_ABOVERING))
+  val DeadDoubleacute = Value(VK_DEAD_DOUBLEACUTE, getKeyText(VK_DEAD_DOUBLEACUTE))
+  val DeadCaron = Value(VK_DEAD_CARON, getKeyText(VK_DEAD_CARON))
+  val DeadCedilla = Value(VK_DEAD_CEDILLA, getKeyText(VK_DEAD_CEDILLA))
+  val DeadOgonek = Value(VK_DEAD_OGONEK, getKeyText(VK_DEAD_OGONEK))
+  val DeadIota = Value(VK_DEAD_IOTA, getKeyText(VK_DEAD_IOTA))
+  val DeadVoicedSound = Value(VK_DEAD_VOICED_SOUND, getKeyText(VK_DEAD_VOICED_SOUND))
+  val DeadSemivoicedSound = Value(VK_DEAD_SEMIVOICED_SOUND, getKeyText(VK_DEAD_SEMIVOICED_SOUND))
+  val Ampersand = Value(VK_AMPERSAND, getKeyText(VK_AMPERSAND))
+  val Asterisk = Value(VK_ASTERISK, getKeyText(VK_ASTERISK))
+  val Quotedbl = Value(VK_QUOTEDBL, getKeyText(VK_QUOTEDBL))
+  val Less = Value(VK_LESS, getKeyText(VK_LESS))
+  val Greater = Value(VK_GREATER, getKeyText(VK_GREATER))
+  val Braceleft = Value(VK_BRACELEFT, getKeyText(VK_BRACELEFT))
+  val Braceright = Value(VK_BRACERIGHT, getKeyText(VK_BRACERIGHT))
+  val At = Value(VK_AT, getKeyText(VK_AT))
+  val Colon = Value(VK_COLON, getKeyText(VK_COLON))
+  val Circumflex = Value(VK_CIRCUMFLEX, getKeyText(VK_CIRCUMFLEX))
+  val Dollar = Value(VK_DOLLAR, getKeyText(VK_DOLLAR))
+  val EuroSign = Value(VK_EURO_SIGN, getKeyText(VK_EURO_SIGN))
+  val ExclamationMark = Value(VK_EXCLAMATION_MARK, getKeyText(VK_EXCLAMATION_MARK))
+  val InvertedExclamationMark = Value(VK_INVERTED_EXCLAMATION_MARK, getKeyText(VK_INVERTED_EXCLAMATION_MARK))
+  val LeftParenthesis = Value(VK_LEFT_PARENTHESIS, getKeyText(VK_LEFT_PARENTHESIS))
+  val NumberSign = Value(VK_NUMBER_SIGN, getKeyText(VK_NUMBER_SIGN))
+  val Plus = Value(VK_PLUS, getKeyText(VK_PLUS))
+  val RightParenthesis = Value(VK_RIGHT_PARENTHESIS, getKeyText(VK_RIGHT_PARENTHESIS))
+  val Underscore = Value(VK_UNDERSCORE, getKeyText(VK_UNDERSCORE))
+  val Windows = Value(VK_WINDOWS, getKeyText(VK_WINDOWS))
+  val ContextMenu = Value(VK_CONTEXT_MENU, getKeyText(VK_CONTEXT_MENU))
+  val Final = Value(VK_FINAL, getKeyText(VK_FINAL))
+  val Convert = Value(VK_CONVERT, getKeyText(VK_CONVERT))
+  val Nonconvert = Value(VK_NONCONVERT, getKeyText(VK_NONCONVERT))
+  val Accept = Value(VK_ACCEPT, getKeyText(VK_ACCEPT))
+  val Modechange = Value(VK_MODECHANGE, getKeyText(VK_MODECHANGE))
+  val Kana = Value(VK_KANA, getKeyText(VK_KANA))
+  val Kanji = Value(VK_KANJI, getKeyText(VK_KANJI))
+  val Alphanumeric = Value(VK_ALPHANUMERIC, getKeyText(VK_ALPHANUMERIC))
+  val Katakana = Value(VK_KATAKANA, getKeyText(VK_KATAKANA))
+  val Hiragana = Value(VK_HIRAGANA, getKeyText(VK_HIRAGANA))
+  val FullWidth = Value(VK_FULL_WIDTH, getKeyText(VK_FULL_WIDTH))
+  val HalfWidth = Value(VK_HALF_WIDTH, getKeyText(VK_HALF_WIDTH))
+  val RomanCharacters = Value(VK_ROMAN_CHARACTERS, getKeyText(VK_ROMAN_CHARACTERS))
+  val AllCandidates = Value(VK_ALL_CANDIDATES, getKeyText(VK_ALL_CANDIDATES))
+  val PreviousCandidate = Value(VK_PREVIOUS_CANDIDATE, getKeyText(VK_PREVIOUS_CANDIDATE))
+  val CodeInput = Value(VK_CODE_INPUT, getKeyText(VK_CODE_INPUT))
+  val JapaneseKatakana = Value(VK_JAPANESE_KATAKANA, getKeyText(VK_JAPANESE_KATAKANA))
+  val JapaneseHiragana = Value(VK_JAPANESE_HIRAGANA, getKeyText(VK_JAPANESE_HIRAGANA))
+  val JapaneseRoman = Value(VK_JAPANESE_ROMAN, getKeyText(VK_JAPANESE_ROMAN))
+  val KanaLock = Value(VK_KANA_LOCK, getKeyText(VK_KANA_LOCK))
+  val InputMethodOnOff = Value(VK_INPUT_METHOD_ON_OFF, getKeyText(VK_INPUT_METHOD_ON_OFF))
+  val Cut = Value(VK_CUT, getKeyText(VK_CUT))
+  val Copy = Value(VK_COPY, getKeyText(VK_COPY))
+  val Paste = Value(VK_PASTE, getKeyText(VK_PASTE))
+  val Undo = Value(VK_UNDO, getKeyText(VK_UNDO))
+  val Again = Value(VK_AGAIN, getKeyText(VK_AGAIN))
+  val Find = Value(VK_FIND, getKeyText(VK_FIND))
+  val Props = Value(VK_PROPS, getKeyText(VK_PROPS))
+  val Stop = Value(VK_STOP, getKeyText(VK_STOP))
+  val Compose = Value(VK_COMPOSE, getKeyText(VK_COMPOSE))
+  val Begin = Value(VK_BEGIN, getKeyText(VK_BEGIN))
+  val Undefined = Value(VK_UNDEFINED, getKeyText(VK_UNDEFINED))
+}
diff --git a/src/swing/scala/swing/event/KeyEvent.scala b/src/swing/scala/swing/event/KeyEvent.scala
new file mode 100644
index 0000000..d014f0b
--- /dev/null
+++ b/src/swing/scala/swing/event/KeyEvent.scala
@@ -0,0 +1,43 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.swing
+package event
+
+import javax.swing.JComponent
+
+sealed abstract class KeyEvent extends InputEvent {
+  def peer: java.awt.event.KeyEvent
+}
+
+case class KeyTyped(val source: Component, char: Char, val modifiers: Key.Modifiers, 
+                    location: Key.Location.Value)
+                   (val peer: java.awt.event.KeyEvent) extends KeyEvent {
+  def this(e: java.awt.event.KeyEvent) = 
+    this(UIElement.cachedWrapper[Component](e.getSource.asInstanceOf[JComponent]), 
+        e.getKeyChar, e.getModifiersEx, 
+        Key.Location(e.getKeyLocation))(e)
+} 
+
+case class KeyPressed(val source: Component, key: Key.Value, val modifiers: Key.Modifiers, 
+                    location: Key.Location.Value)
+                   (val peer: java.awt.event.KeyEvent) extends KeyEvent {
+  def this(e: java.awt.event.KeyEvent) = 
+    this(UIElement.cachedWrapper[Component](e.getSource.asInstanceOf[JComponent]), 
+        Key(e.getKeyCode), e.getModifiersEx, Key.Location(e.getKeyLocation))(e) 
+}
+
+case class KeyReleased(val source: Component, key: Key.Value, val modifiers: Key.Modifiers, 
+                    location: Key.Location.Value)
+                   (val peer: java.awt.event.KeyEvent) extends KeyEvent {
+  def this(e: java.awt.event.KeyEvent) = 
+    this(UIElement.cachedWrapper[Component](e.getSource.asInstanceOf[JComponent]), 
+        Key(e.getKeyCode), e.getModifiersEx, Key.Location(e.getKeyLocation))(e) 
+}
diff --git a/src/swing/scala/swing/event/ListEvent.scala b/src/swing/scala/swing/event/ListEvent.scala
index 5dcb0a9..0c3c06e 100644
--- a/src/swing/scala/swing/event/ListEvent.scala
+++ b/src/swing/scala/swing/event/ListEvent.scala
@@ -1,4 +1,15 @@
-package scala.swing.event
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.swing
+package event
 
 trait ListEvent[A] extends ComponentEvent {
   override val source: ListView[A]
@@ -29,4 +40,4 @@ object ListElementsRemoved {
   def apply[A](source: ListView[A], range: Range) = new ListElementsRemoved(source, range)
 }
 class ListElementsRemoved[A](override val source: ListView[A], val range: Range) 
-           extends ListChange(source) 
\ No newline at end of file
+           extends ListChange(source) 
diff --git a/src/swing/scala/swing/event/MouseEvent.scala b/src/swing/scala/swing/event/MouseEvent.scala
index 63266cc..1e22887 100644
--- a/src/swing/scala/swing/event/MouseEvent.scala
+++ b/src/swing/scala/swing/event/MouseEvent.scala
@@ -1,32 +1,79 @@
-package scala.swing.event
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.swing
+package event
 
 import java.awt.Point
+import javax.swing.JComponent
+
+sealed abstract class MouseEvent extends InputEvent {
+  def peer: java.awt.event.MouseEvent
+  def point: Point
+}
+
+sealed abstract class MouseButtonEvent extends MouseEvent {
+  def clicks: Int
+  def triggersPopup: Boolean
+}
+case class MouseClicked(val source: Component, point: Point, val modifiers: Key.Modifiers, 
+                     clicks: Int, triggersPopup: Boolean)(val peer: java.awt.event.MouseEvent)
+           extends MouseButtonEvent {
+  def this(e: java.awt.event.MouseEvent) = 
+    this(UIElement.cachedWrapper[Component](e.getSource.asInstanceOf[JComponent]), 
+        e.getPoint, e.getModifiersEx, e.getClickCount, e.isPopupTrigger)(e)             
+}
+case class MousePressed(val source: Component, point: Point, val modifiers: Key.Modifiers, 
+                        clicks: Int, triggersPopup: Boolean)(val peer: java.awt.event.MouseEvent)
+           extends MouseButtonEvent {
+  def this(e: java.awt.event.MouseEvent) = 
+    this(UIElement.cachedWrapper[Component](e.getSource.asInstanceOf[JComponent]), 
+        e.getPoint, e.getModifiersEx, e.getClickCount, e.isPopupTrigger)(e)             
+}
+case class MouseReleased(val source: Component, point: Point, val modifiers: Key.Modifiers, 
+                        clicks: Int, triggersPopup: Boolean)(val peer: java.awt.event.MouseEvent)
+           extends MouseButtonEvent {
+  def this(e: java.awt.event.MouseEvent) = 
+    this(UIElement.cachedWrapper[Component](e.getSource.asInstanceOf[JComponent]), 
+        e.getPoint, e.getModifiersEx, e.getClickCount, e.isPopupTrigger)(e)             
+}
+
+sealed abstract class MouseMotionEvent extends MouseEvent
+case class MouseMoved(val source: Component, point: Point, val modifiers: Key.Modifiers)(val peer: java.awt.event.MouseEvent)
+           extends MouseMotionEvent {
+  def this(e: java.awt.event.MouseEvent) = 
+    this(UIElement.cachedWrapper[Component](e.getSource.asInstanceOf[JComponent]), 
+        e.getPoint, e.getModifiersEx)(e)             
+}
+case class MouseDragged(val source: Component, point: Point, val modifiers: Key.Modifiers)(val peer: java.awt.event.MouseEvent)
+           extends MouseMotionEvent {
+  def this(e: java.awt.event.MouseEvent) = 
+    this(UIElement.cachedWrapper[Component](e.getSource.asInstanceOf[JComponent]), 
+        e.getPoint, e.getModifiersEx)(e)             
+}
+case class MouseEntered(val source: Component, point: Point, val modifiers: Key.Modifiers)(val peer: java.awt.event.MouseEvent)
+           extends MouseMotionEvent {
+  def this(e: java.awt.event.MouseEvent) = 
+    this(UIElement.cachedWrapper[Component](e.getSource.asInstanceOf[JComponent]), 
+        e.getPoint, e.getModifiersEx)(e)             
+}
+case class MouseExited(val source: Component, point: Point, val modifiers: Key.Modifiers)(val peer: java.awt.event.MouseEvent)
+           extends MouseMotionEvent {
+  def this(e: java.awt.event.MouseEvent) = 
+      this(UIElement.cachedWrapper[Component](e.getSource.asInstanceOf[JComponent]), 
+          e.getPoint, e.getModifiersEx)(e)             
+}
 
-class MouseEvent(val source: Component, point: Point, val modifiers: Int)(val when: Long) extends InputEvent
-
-class MouseButtonEvent(source: Component, point: Point, override val modifiers: Int, 
-                     clicks: Int, triggersPopup: Boolean)(when: Long)
-      extends MouseEvent(source, point, modifiers)(when)
-case class MouseClicked(override val source: Component, point: Point, override val modifiers: Int, 
-                     clicks: Int, triggersPopup: Boolean)(when: Long)
-           extends MouseButtonEvent(source, point, modifiers, clicks, triggersPopup)(when)
-case class MousePressed(override val source: Component, point: Point, override val modifiers: Int, 
-                        clicks: Int, triggersPopup: Boolean)(when: Long)
-           extends MouseButtonEvent(source, point, modifiers, clicks, triggersPopup)(when)
-case class MouseReleased(override val source: Component, point: Point, override val modifiers: Int, 
-                        clicks: Int, triggersPopup: Boolean)(when: Long)
-           extends MouseButtonEvent(source, point, modifiers, clicks, triggersPopup)(when)
-
-class MouseMotionEvent(source: Component, point: Point, modifiers: Int)(when: Long)
-      extends MouseEvent(source, point, modifiers)(when)
-case class MouseMoved(override val source: Component, point: Point, override val modifiers: Int)(when: Long)
-           extends MouseMotionEvent(source, point, modifiers)(when)
-case class MouseDragged(override val source: Component, point: Point, override val modifiers: Int)(when: Long)
-           extends MouseMotionEvent(source, point, modifiers)(when)
-case class MouseEntered(override val source: Component, point: Point, override val modifiers: Int)(when: Long)
-           extends MouseMotionEvent(source, point, modifiers)(when)
-case class MouseExited(override val source: Component, point: Point, override val modifiers: Int)(when: Long)
-           extends MouseMotionEvent(source, point, modifiers)(when)
-
-case class MouseWheelMoved(override val source: Component, point: Point, override val modifiers: Int, rotation: Int)(when: Long)
-           extends MouseEvent(source, point, modifiers)(when)
\ No newline at end of file
+case class MouseWheelMoved(val source: Component, point: Point, val modifiers: Key.Modifiers, rotation: Int)(val peer: java.awt.event.MouseEvent)
+           extends MouseEvent {
+  def this(e: java.awt.event.MouseWheelEvent) = 
+    this(UIElement.cachedWrapper[Component](e.getSource.asInstanceOf[JComponent]), 
+        e.getPoint, e.getModifiersEx, e.getWheelRotation)(e)             
+}
diff --git a/src/swing/scala/swing/event/SelectionEvent.scala b/src/swing/scala/swing/event/SelectionEvent.scala
index 0f1091e..7035978 100644
--- a/src/swing/scala/swing/event/SelectionEvent.scala
+++ b/src/swing/scala/swing/event/SelectionEvent.scala
@@ -1,11 +1,34 @@
-package scala.swing.event
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
 
-trait SelectionEvent extends ComponentEvent
 
+
+package scala.swing
+package event
+
+/**
+ * An event that indicates a change in a selection such as in a list view or a table.
+ */
+trait SelectionEvent
+
+/**
+ * An event that indicates a selection of a range of indices.
+ */
 trait ListSelectionEvent extends SelectionEvent {
   def range: Range
 }
 
 case class SelectionChanged(override val source: Component) extends ComponentEvent with SelectionEvent
-case class ListSelectionChanged[A](override val source: ListView[A], range: Range, live: Boolean) 
-  extends SelectionChanged(source) with ListEvent[A]
\ No newline at end of file
+
+object ListSelectionChanged {
+  def unapply[A](e: ListSelectionChanged[A]): Option[(ListView[A], Range, Boolean)] = 
+    Some((e.source, e.range, e.live))
+}
+
+class ListSelectionChanged[A](override val source: ListView[A], val range: Range, val live: Boolean) 
+  extends SelectionChanged(source) with ListEvent[A]
diff --git a/src/swing/scala/swing/event/TableEvent.scala b/src/swing/scala/swing/event/TableEvent.scala
index d5f5ecc..2864290 100644
--- a/src/swing/scala/swing/event/TableEvent.scala
+++ b/src/swing/scala/swing/event/TableEvent.scala
@@ -1,4 +1,15 @@
-package scala.swing.event
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.swing
+package event
 
 abstract class TableEvent(override val source: Table) extends ComponentEvent
 
@@ -6,7 +17,7 @@ abstract class TableChange(override val source: Table) extends TableEvent(source
 
 /**
  * The most general table change. The table might have changed completely, 
- * i.e., comlumns might have been reordered, rows added or removed, etc. 
+ * i.e., columns might have been reordered, rows added or removed, etc. 
  * No other event indicates that the structure might have changed.
  */
 case class TableStructureChanged(override val source: Table) extends TableChange(source)
@@ -25,11 +36,11 @@ case class TableUpdated(override val source: Table, range: Range, column: Int)
 /**
  * Any change that caused the table to change it's size
  */ 
-case class TableResized(override val source: Table) extends TableChange(source)
+class TableResized(override val source: Table) extends TableChange(source)
 case class TableRowsAdded(override val source: Table, range: Range) extends TableResized(source)
 case class TableRowsRemoved(override val source: Table, range: Range) extends TableResized(source)
 
 case class TableColumnsSelected(override val source: Table, range: Range, adjusting: Boolean) 
            extends TableEvent(source) with AdjustingEvent with ListSelectionEvent
 case class TableRowsSelected(override val source: Table, range: Range, adjusting: Boolean) 
-           extends TableEvent(source) with AdjustingEvent with ListSelectionEvent
\ No newline at end of file
+           extends TableEvent(source) with AdjustingEvent with ListSelectionEvent
diff --git a/src/swing/scala/swing/event/UIEvent.scala b/src/swing/scala/swing/event/UIEvent.scala
index f2941e7..0373268 100644
--- a/src/swing/scala/swing/event/UIEvent.scala
+++ b/src/swing/scala/swing/event/UIEvent.scala
@@ -1,5 +1,21 @@
-package scala.swing.event
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+
+package scala.swing
+package event
 
 trait UIEvent extends Event {
   val source: UIElement
 }
+
+case class UIElementMoved(source: UIElement) extends UIEvent
+case class UIElementResized(source: UIElement) extends UIEvent
+case class UIElementShown(source: UIElement) extends UIEvent
+case class UIElementHidden(source: UIElement) extends UIEvent
diff --git a/src/swing/scala/swing/event/ValueChanged.scala b/src/swing/scala/swing/event/ValueChanged.scala
index 1097a52..5f32c03 100644
--- a/src/swing/scala/swing/event/ValueChanged.scala
+++ b/src/swing/scala/swing/event/ValueChanged.scala
@@ -1,3 +1,18 @@
-package scala.swing.event
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
 
-case class ValueChanged(override val source: Component) extends ComponentEvent
+
+
+package scala.swing
+package event
+
+object ValueChanged {
+  def unapply(a: ValueChanged): Option[Component] = Some(a.source)
+}
+
+class ValueChanged(override val source: Component) extends ComponentEvent
diff --git a/src/swing/scala/swing/event/WindowActivated.scala b/src/swing/scala/swing/event/WindowActivated.scala
index c2ed2f6..3c0fae4 100644
--- a/src/swing/scala/swing/event/WindowActivated.scala
+++ b/src/swing/scala/swing/event/WindowActivated.scala
@@ -1,3 +1,14 @@
-package scala.swing.event
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
 
-case class WindowActivated(override val source: Frame) extends WindowEvent(source)
+
+
+package scala.swing
+package event
+
+case class WindowActivated(override val source: Window) extends WindowEvent(source)
diff --git a/src/swing/scala/swing/event/WindowClosed.scala b/src/swing/scala/swing/event/WindowClosed.scala
index d719e47..80afe1a 100644
--- a/src/swing/scala/swing/event/WindowClosed.scala
+++ b/src/swing/scala/swing/event/WindowClosed.scala
@@ -1,3 +1,4 @@
-package scala.swing.event
+package scala.swing
+package event
 
-case class WindowClosed(override val source: Frame) extends WindowEvent(source)
+case class WindowClosed(override val source: Window) extends WindowEvent(source)
diff --git a/src/swing/scala/swing/event/WindowClosing.scala b/src/swing/scala/swing/event/WindowClosing.scala
index 5f75365..7d878f0 100644
--- a/src/swing/scala/swing/event/WindowClosing.scala
+++ b/src/swing/scala/swing/event/WindowClosing.scala
@@ -1,3 +1,14 @@
-package scala.swing.event
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
 
-case class WindowClosing(override val source: Frame) extends WindowEvent(source)
+
+
+package scala.swing
+package event
+
+case class WindowClosing(override val source: Window) extends WindowEvent(source)
diff --git a/src/swing/scala/swing/event/WindowDeactivated.scala b/src/swing/scala/swing/event/WindowDeactivated.scala
index ca5f330..08f0f63 100644
--- a/src/swing/scala/swing/event/WindowDeactivated.scala
+++ b/src/swing/scala/swing/event/WindowDeactivated.scala
@@ -1,3 +1,14 @@
-package scala.swing.event
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
 
-case class WindowDeactivated(override val source: Frame) extends WindowEvent(source)
+
+
+package scala.swing
+package event
+
+case class WindowDeactivated(override val source: Window) extends WindowEvent(source)
diff --git a/src/swing/scala/swing/event/WindowDeiconified.scala b/src/swing/scala/swing/event/WindowDeiconified.scala
index 828a65a..2abeb73 100644
--- a/src/swing/scala/swing/event/WindowDeiconified.scala
+++ b/src/swing/scala/swing/event/WindowDeiconified.scala
@@ -1,3 +1,14 @@
-package scala.swing.event
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
 
-case class WindowDeiconified(override val source: Frame) extends WindowEvent(source)
+
+
+package scala.swing
+package event
+
+case class WindowDeiconified(override val source: Window) extends WindowEvent(source)
diff --git a/src/swing/scala/swing/event/WindowEvent.scala b/src/swing/scala/swing/event/WindowEvent.scala
index c0caf2b..d1be47d 100644
--- a/src/swing/scala/swing/event/WindowEvent.scala
+++ b/src/swing/scala/swing/event/WindowEvent.scala
@@ -1,3 +1,14 @@
-package scala.swing.event
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
 
-abstract class WindowEvent(override val source: Frame) extends UIEvent
+
+
+package scala.swing
+package event
+
+abstract class WindowEvent(override val source: Window) extends UIEvent
diff --git a/src/swing/scala/swing/event/WindowIconified.scala b/src/swing/scala/swing/event/WindowIconified.scala
index 1a18d71..82ec8ab 100644
--- a/src/swing/scala/swing/event/WindowIconified.scala
+++ b/src/swing/scala/swing/event/WindowIconified.scala
@@ -1,3 +1,14 @@
-package scala.swing.event
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
 
-case class WindowIconified(override val source: Frame) extends WindowEvent(source)
+
+
+package scala.swing
+package event
+
+case class WindowIconified(override val source: Window) extends WindowEvent(source)
diff --git a/src/swing/scala/swing/event/WindowOpened.scala b/src/swing/scala/swing/event/WindowOpened.scala
index e6f45dc..54684c3 100644
--- a/src/swing/scala/swing/event/WindowOpened.scala
+++ b/src/swing/scala/swing/event/WindowOpened.scala
@@ -1,3 +1,14 @@
-package scala.swing.event
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
 
-case class WindowOpened(override val source: Frame) extends WindowEvent(source)
+
+
+package scala.swing
+package event
+
+case class WindowOpened(override val source: Window) extends WindowEvent(source)
diff --git a/src/swing/scala/swing/model/Matrix.scala b/src/swing/scala/swing/model/Matrix.scala
index ddd9481..7ff056a 100644
--- a/src/swing/scala/swing/model/Matrix.scala
+++ b/src/swing/scala/swing/model/Matrix.scala
@@ -1,4 +1,17 @@
-package scala.swing.model
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2007-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+package scala.swing
+package model
+
+// Dummy to keep ant from recompiling on every run.
+trait Matrix { }
 
 /*trait Matrix[A] extends Function2[Int, Int, A] {
   
@@ -100,7 +113,7 @@ object Matrix {
   
   implicit def MatrixToSeqs[A](matrix: Matrix[A]): Seq[Seq[A]] = {
     val result = new Array[SubArray[A]](matrix.width)
-    for (val col <- 0 until matrix.width)
+    for (col <- 0 until matrix.width)
       result(col) = new SubArray[A](matrix.delegate, col * matrix.height, matrix.height)
     result
   }
diff --git a/src/swing/scala/swing/package.scala b/src/swing/scala/swing/package.scala
new file mode 100644
index 0000000..763ee85
--- /dev/null
+++ b/src/swing/scala/swing/package.scala
@@ -0,0 +1,20 @@
+package scala
+
+/**
+ * Useful imports that don't have wrappers.
+ */
+package object swing {
+  type Point = java.awt.Point
+  type Dimension = java.awt.Dimension
+  type Rectangle = java.awt.Rectangle
+  type Insets = java.awt.Insets
+  
+  type Graphics2D = java.awt.Graphics2D
+  type Color = java.awt.Color
+  type Image = java.awt.Image
+  type Font = java.awt.Font
+  
+  protected[swing] def ifNull[A](o: Object, a: A): A = if(o eq null) a else o.asInstanceOf[A]
+  protected[swing] def toOption[A](o: Object): Option[A] = if(o eq null) None else Some(o.asInstanceOf[A])
+  protected[swing] def toAnyRef(x: Any): AnyRef = x.asInstanceOf[AnyRef]
+}
diff --git a/src/swing/scala/swing/test/ButtonApp.scala b/src/swing/scala/swing/test/ButtonApp.scala
index 9d8fcb0..dcf567d 100644
--- a/src/swing/scala/swing/test/ButtonApp.scala
+++ b/src/swing/scala/swing/test/ButtonApp.scala
@@ -1,9 +1,12 @@
-package scala.swing.test
+package scala.swing
+package test
+
+import java.awt.Dimension
 
 import swing._
 import swing.event._
 
-object ButtonApp extends SimpleGUIApplication {
+object ButtonApp extends SimpleSwingApplication {
   def top = new MainFrame {
     title = "My Frame"
     contents = new GridPanel(2, 2) {
@@ -16,6 +19,7 @@ object ButtonApp extends SimpleGUIApplication {
         }
       }
     }
-    size = (300, 80)
+    size = new Dimension(300, 80)
   }
 }
+
diff --git a/src/swing/scala/swing/test/CelsiusConverter.scala b/src/swing/scala/swing/test/CelsiusConverter.scala
index f5bc7a0..36bd047 100644
--- a/src/swing/scala/swing/test/CelsiusConverter.scala
+++ b/src/swing/scala/swing/test/CelsiusConverter.scala
@@ -1,11 +1,12 @@
-package scala.swing.test
+package scala.swing
+package test
 
 import swing._
 import event._
 
 /** A GUI app to convert celsius to centigrade
  */    
-object CelsiusConverter extends SimpleGUIApplication {
+object CelsiusConverter extends SimpleSwingApplication {
   def top = new MainFrame {
     title = "Convert Celsius to Fahrenheit"
     val tempCelsius = new TextField
diff --git a/src/swing/scala/swing/test/CelsiusConverter2.scala b/src/swing/scala/swing/test/CelsiusConverter2.scala
index bc2d441..b3f2cf4 100644
--- a/src/swing/scala/swing/test/CelsiusConverter2.scala
+++ b/src/swing/scala/swing/test/CelsiusConverter2.scala
@@ -1,27 +1,33 @@
-package scala.swing.test
+package scala.swing
+package test
 
 import swing._
 import event._
 
-object CelsiusConverter2 extends SimpleGUIApplication {
-  val ui = new FlowPanel {
-   	val Celsius = new TextField { columns = 5 }
-    val Fahrenheit = new TextField { columns = 5 }
-    contents.append(Celsius, new Label(" Celsius  =  "), 
-                    Fahrenheit, new Label(" Fahrenheit"))
+object CelsiusConverter2 extends SimpleSwingApplication {
+  def newField = new TextField { 
+    text = "0"
+    columns = 5
+    horizontalAlignment = Alignment.Right
+  }
+  val celsius = newField
+  val fahrenheit = newField
+  
+  listenTo(fahrenheit, celsius)
+  reactions += {
+    case EditDone(`fahrenheit`) =>
+      val f = Integer.parseInt(fahrenheit.text)
+      val c = (f - 32) * 5 / 9
+      celsius.text = c.toString
+    case EditDone(`celsius`) =>
+      val c = Integer.parseInt(celsius.text)
+      val f = c * 9 / 5 + 32
+      fahrenheit.text = f.toString
+  }
+  
+  lazy val ui = new FlowPanel(celsius, new Label(" Celsius  =  "), 
+                              fahrenheit, new Label(" Fahrenheit")) {
     border = Swing.EmptyBorder(15, 10, 10, 10)
-    
-    listenTo(Fahrenheit, Celsius)
-    reactions += {
-      case EditDone(Fahrenheit) =>
-        val f = Integer.parseInt(Fahrenheit.text)
-        val c = (f - 32) * 5 / 9
-        Celsius.text = c.toString
-      case EditDone(Celsius) =>
-        val c = Integer.parseInt(Celsius.text)
-        val f = c * 9 / 5 + 32
-        Fahrenheit.text = f.toString
-    }
   }
   def top = new MainFrame {
     title = "Convert Celsius / Fahrenheit"
diff --git a/src/swing/scala/swing/test/ComboBoxes.scala b/src/swing/scala/swing/test/ComboBoxes.scala
index 8d51514..d202c9d 100644
--- a/src/swing/scala/swing/test/ComboBoxes.scala
+++ b/src/swing/scala/swing/test/ComboBoxes.scala
@@ -1,4 +1,5 @@
-package scala.swing.test
+package scala.swing
+package test
 
 import swing._
 import event._
@@ -12,9 +13,9 @@ import javax.swing.{Icon, ImageIcon}
  * 
  * TODO: clean up layout
  */
-object ComboBoxes extends SimpleGUIApplication {
+object ComboBoxes extends SimpleSwingApplication {
   import ComboBox._
-  val ui = new FlowPanel {
+  lazy val ui = new FlowPanel {
    	contents += new ComboBox(List(1,2,3,4))
         
     val patterns = List("dd MMMMM yyyy",
@@ -64,7 +65,7 @@ object ComboBoxes extends SimpleGUIApplication {
 
     val iconBox = new ComboBox(icons) {
       renderer = new ListView.AbstractRenderer[Icon, Label](new Label) {
-        def configure(list: ListView[_], isSelected: Boolean, hasFocus: Boolean, icon: Icon, index: Int) {
+        def configure(list: ListView[_], isSelected: Boolean, focused: Boolean, icon: Icon, index: Int) {
   	      component.icon = icon
           component.xAlignment = Alignment.Center
           if(isSelected) {
diff --git a/src/swing/scala/swing/test/CountButton.scala b/src/swing/scala/swing/test/CountButton.scala
index b2908e4..36828c2 100644
--- a/src/swing/scala/swing/test/CountButton.scala
+++ b/src/swing/scala/swing/test/CountButton.scala
@@ -1,9 +1,10 @@
-package scala.swing.test
+package scala.swing
+package test
 
 import scala.swing._ 
 import scala.swing.event._ 
 
-object CountButton extends SimpleGUIApplication {
+object CountButton extends SimpleSwingApplication {
   def top = new MainFrame {
     title = "My Frame"
     contents = new GridPanel(2, 2) {
diff --git a/src/swing/scala/swing/test/Dialogs.scala b/src/swing/scala/swing/test/Dialogs.scala
index b6c65da..0e3ea03 100644
--- a/src/swing/scala/swing/test/Dialogs.scala
+++ b/src/swing/scala/swing/test/Dialogs.scala
@@ -1,13 +1,14 @@
-package scala.swing.test
+package scala.swing
+package test
 
 import swing._
 import swing.event._
 
-object Dialogs extends SimpleGUIApplication {
+object Dialogs extends SimpleSwingApplication {
   import TabbedPane._
   
-  val label = new Label("No Result yet")
-  val tabs = new TabbedPane {
+  lazy val label = new Label("No Result yet")
+  lazy val tabs = new TabbedPane {
     pages += new Page("File", new GridBagPanel { grid =>
       import GridBagPanel._
       val buttonText = new TextField("Click Me")
@@ -60,38 +61,39 @@ object Dialogs extends SimpleGUIApplication {
           case `ok` => 
             showMessage(buttons, "Eggs aren't supposed to be green.")
           case `ynlf` => 
-            showConfirmation(buttons, "Would you like green eggs and ham?",
-                            "An Inane Question", Options.YesNo) match {
-              case Result.Yes => label.text = "Ewww!"
-              case Result.No => label.text = "Me neither!"
-              case _ => label.text = "Come on -- tell me!"
+            label.text = showConfirmation(buttons, 
+                             "Would you like green eggs and ham?",
+                             "An Inane Question") match {
+              case Result.Yes => "Ewww!"
+              case Result.No => "Me neither!"
+              case _ => "Come on -- tell me!"
           }
           case `ynp` => 
             val options = List("Yes, please",
                                "No, thanks",
                                "No eggs, no ham!")
-            showOptions(buttons,
+            label.text = showOptions(buttons,
                         "Would you like some green eggs to go with that ham?",
                         "A Silly Question",
-                        Options.YesNo, Message.Question,
-                        Swing.EmptyIcon, options, 2) match {
-              case Result.Yes => label.text = "You're kidding!"
-              case Result.No => label.text = "I don't like them, either."
-              case _ => label.text = "Come on -- 'fess up!"
+                        entries = options, 
+                        initial = 2) match {
+              case Result.Yes => "You're kidding!"
+              case Result.No => "I don't like them, either."
+              case _ => "Come on -- 'fess up!"
             }
           case `yncp` => 
             val options = List("Yes, please",
                                "No, thanks",
                                "No eggs, no ham!")
-            showOptions(buttons,
-                        "Would you like some green eggs to go with that ham?",
-                        "A Silly Question",
-                        Options.YesNoCancel, Message.Question,
-                        Swing.EmptyIcon, options, 2) match {
-              case Result.Yes => label.text = "Here you go: green eggs and ham!"
-              case Result.No => label.text = "OK, just the ham, then."
-              case Result.Cancel => label.text = "Well, I'm certainly not going to eat them!"
-              case _ => label.text = "Please tell me what you want!"
+            label.text = showOptions(buttons,
+                        message = "Would you like some green eggs to go with that ham?",
+                        title = "A Silly Question",
+                        entries = options, 
+                        initial = 2) match {
+              case Result.Yes => "Here you go: green eggs and ham!"
+              case Result.No => "OK, just the ham, then."
+              case Result.Cancel => "Well, I'm certainly not going to eat them!"
+              case _ => "Please tell me what you want!"
             }
         }            
       })) = Position.South
@@ -101,10 +103,10 @@ object Dialogs extends SimpleGUIApplication {
       val mutex = new ButtonGroup
       val pick = new RadioButton("Pick one of several choices")
       val enter = new RadioButton("Enter some text")
-      //val nonClosing = new RadioButton("Non-auto-closing dialog")
-      //val validate = new RadioButton("Input-validating dialog (with custom message area)")
-      //val nonModal = new RadioButton("Non-modal dialog")
-      val radios = List(pick, enter)//, nonClosing, validate, nonModal)
+      val custom = new RadioButton("Custom")
+      val customUndec = new RadioButton("Custom undecorated")
+      val custom2 = new RadioButton("2 custom dialogs")
+      val radios = List(pick, enter, custom, customUndec, custom2)
       mutex.buttons ++= radios
       mutex.select(pick)      
       val buttons = new BoxPanel(Orientation.Vertical) {
@@ -117,42 +119,57 @@ object Dialogs extends SimpleGUIApplication {
           case `pick` => 
             val possibilities = List("ham", "spam", "yam")
             val s = showInput(buttons,
-                      "Complete the sentence:\n"
-                      + "\"Green eggs and...\"",
+                      "Complete the sentence:\n\"Green eggs and...\"",
                       "Customized Dialog",
-                      Message.Plain, Swing.EmptyIcon,
+                      Message.Plain, 
+                      Swing.EmptyIcon,
                       possibilities, "ham")
 
-                    //If a string was returned, say so.
-            if ((s != None) && (s.get.length > 0))
-              label.text =  "Green eggs and... " + s.get + "!"
+            //If a string was returned, say so.
+            label.text = if ((s != None) && (s.get.length > 0))
+              "Green eggs and... " + s.get + "!"
             else
-              label.text = "Come on, finish the sentence!"
+              "Come on, finish the sentence!"
           case `enter` => 
             val s = showInput(buttons,
-                      "Complete the sentence:\n"
-                      + "\"Green eggs and...\"",
+                      "Complete the sentence:\n\"Green eggs and...\"",
                       "Customized Dialog",
-                      Message.Plain, Swing.EmptyIcon,
+                      Message.Plain, 
+                      Swing.EmptyIcon,
                       Nil, "ham")
 
-                    //If a string was returned, say so.
-            if ((s != None) && (s.get.length > 0))
-              label.text =  "Green eggs and... " + s.get + "!"
+            //If a string was returned, say so.
+            label.text = if ((s != None) && (s.get.length > 0))
+              "Green eggs and... " + s.get + "!"
             else
-              label.text = "Come on, finish the sentence!"
+              "Come on, finish the sentence!"
+          case `custom` =>
+            val dialog = new Dialog(top)
+            dialog.open()
+            dialog.contents = Button("Close Me!") { dialog.close() }
+          case `customUndec` =>
+            val dialog = new Dialog with RichWindow.Undecorated
+            dialog.open()
+            dialog.contents = Button("Close Me!") { dialog.close() }
+          case `custom2` =>
+            val d1 = new Dialog
+            val d2 = new Dialog(d1)
+            d1.open()
+            d2.open()
+            d1.contents = Button("Close Me! I am the owner and will automatically close the other one") { d1.close() }
+            d2.contents = Button("Close Me!") { d2.close() }
         }            
       })) = Position.South
     })
   }
   
-  val ui = new BorderPanel {
+  lazy val ui: Panel = new BorderPanel {
     layout(tabs) = BorderPanel.Position.Center
     layout(label) = BorderPanel.Position.South
   }
    
   
-  def top = new MainFrame { 
+  lazy val top = new MainFrame { 
     title = "Dialog Demo"
     contents = ui
   }
diff --git a/src/swing/scala/swing/test/GridBagDemo.scala b/src/swing/scala/swing/test/GridBagDemo.scala
index 8503bb6..26b1f82 100644
--- a/src/swing/scala/swing/test/GridBagDemo.scala
+++ b/src/swing/scala/swing/test/GridBagDemo.scala
@@ -1,12 +1,13 @@
-package scala.swing.test
+package scala.swing
+package test
 
 import swing._
 import swing.event._
 import GridBagPanel._
 import java.awt.Insets
 
-object GridBagDemo extends SimpleGUIApplication {
-  val ui = new GridBagPanel {
+object GridBagDemo extends SimpleSwingApplication {
+  lazy val ui = new GridBagPanel {
     val c = new Constraints
     val shouldFill = true
     if (shouldFill) {
diff --git a/src/swing/scala/swing/test/HelloWorld.scala b/src/swing/scala/swing/test/HelloWorld.scala
index e4d70cd..6014a14 100644
--- a/src/swing/scala/swing/test/HelloWorld.scala
+++ b/src/swing/scala/swing/test/HelloWorld.scala
@@ -1,14 +1,14 @@
-package scala.swing.test
+package scala.swing
+package test
 
 import swing._
 
-object HelloWorld extends GUIApplication {
-  def main(args: Array[String]) = run {
-    val frame = new Frame {
-      title = "HelloWorldSwing"
-      contents = new Label("Hello World")
-    }
-    frame.pack()
-    frame.visible = true
+/**
+ * A simple swing demo.
+ */
+object HelloWorld extends SimpleSwingApplication {
+  def top = new MainFrame {
+    title = "Hello, World!"
+    contents = new Button("Click Me!")
   }
-}
+}
\ No newline at end of file
diff --git a/src/swing/scala/swing/test/LabelTest.scala b/src/swing/scala/swing/test/LabelTest.scala
new file mode 100644
index 0000000..f1d7005
--- /dev/null
+++ b/src/swing/scala/swing/test/LabelTest.scala
@@ -0,0 +1,20 @@
+package scala.swing
+package test
+
+import scala.swing._
+import scala.swing.event._
+
+object LabelTest extends SimpleSwingApplication {
+  def top = new MainFrame{
+    contents = new Label { 
+      text = "Hello"
+      import java.awt.event._
+      listenTo(mouse.clicks)
+      reactions += {
+        case MousePressed(_,_,_,_,_) => 
+          println("Mouse pressed2") 
+      }
+    }
+  }
+}
+
diff --git a/src/swing/scala/swing/test/LinePainting.scala b/src/swing/scala/swing/test/LinePainting.scala
new file mode 100644
index 0000000..0824934
--- /dev/null
+++ b/src/swing/scala/swing/test/LinePainting.scala
@@ -0,0 +1,53 @@
+package scala.swing
+package test
+import scala.swing.Swing._
+import scala.swing.{MainFrame, Panel, SimpleGUIApplication}
+import scala.swing.event._
+import java.awt.{Color, Dimension, Graphics, Graphics2D, Point, geom}
+
+/**
+ * Dragging the mouse draws a simple graph
+ * 
+ * @author Frank Teubler, Ingo Maier
+ */
+object LinePainting extends SimpleSwingApplication {
+  lazy val ui = new Panel {
+    background = Color.white
+    preferredSize = (200,200)
+
+    focusable = true
+    listenTo(mouse.clicks, mouse.moves, keys)
+    
+    reactions += {
+      case e: MousePressed  => 
+        moveTo(e.point)
+        requestFocusInWindow()
+      case e: MouseDragged  => lineTo(e.point)
+      case e: MouseReleased => lineTo(e.point)
+      case KeyTyped(_,'c',_,_) => 
+        path = new geom.GeneralPath
+        repaint()
+      case _: FocusLost => repaint()
+    }
+
+    /* records the dragging */
+    var path = new geom.GeneralPath
+
+    def lineTo(p: Point) { path.lineTo(p.x, p.y); repaint() }
+    def moveTo(p: Point) { path.moveTo(p.x, p.y); repaint() }
+
+    override def paintComponent(g: Graphics2D) = {
+      super.paintComponent(g)
+      g.setColor(new Color(100,100,100))
+      g.drawString("Press left mouse button and drag to paint." + 
+                   (if(hasFocus) " Press 'c' to clear." else ""), 10, size.height-10)
+      g.setColor(Color.black)
+      g.draw(path)
+    }
+  }
+  
+  def top = new MainFrame {
+    title = "Simple Line Painting Demo"
+    contents = ui
+  }
+}
diff --git a/src/swing/scala/swing/test/ListViewDemo.scala b/src/swing/scala/swing/test/ListViewDemo.scala
new file mode 100644
index 0000000..c36e6cf
--- /dev/null
+++ b/src/swing/scala/swing/test/ListViewDemo.scala
@@ -0,0 +1,18 @@
+package scala.swing
+package test
+
+object ListViewDemo extends SimpleSwingApplication {
+  def top = new MainFrame {
+    case class City(name: String, country: String, population: Int, capital: Boolean)
+    val items = List(City("Lausanne", "Switzerland", 129273, false),
+                              City("Paris", "France", 2203817, true), 
+                              City("New York", "USA", 8363710 , false),
+                              City("Berlin", "Germany", 3416300, true),
+                              City("Tokio", "Japan", 12787981, true))
+    import ListView._
+    contents = new FlowPanel(new ScrollPane(new ListView(items) {
+      renderer = Renderer(_.name)
+    }))
+                             //new ScrollPane(new Table(items)))
+  }
+}
diff --git a/src/swing/scala/swing/test/SimpleApplet.scala b/src/swing/scala/swing/test/SimpleApplet.scala
index 4af7956..4531952 100644
--- a/src/swing/scala/swing/test/SimpleApplet.scala
+++ b/src/swing/scala/swing/test/SimpleApplet.scala
@@ -1,4 +1,5 @@
-package scala.swing.test
+package scala.swing
+package test
 
 import event._
 
@@ -6,8 +7,7 @@ class SimpleApplet extends Applet {
   object ui extends UI with Reactor {
     def init() = {
       val button = new Button("Press here!")
-      val text = new TextArea("Java Version: " +
-                System.getProperty("java.version")+"\n")
+      val text = new TextArea("Java Version: " + util.Properties.javaVersion + "\n")
       listenTo(button)
       reactions += {
         case ButtonClicked(_) => text.text += "Button Pressed!\n"
diff --git a/src/swing/scala/swing/test/SwingApp.scala b/src/swing/scala/swing/test/SwingApp.scala
index e6c22c4..0ec664e 100644
--- a/src/swing/scala/swing/test/SwingApp.scala
+++ b/src/swing/scala/swing/test/SwingApp.scala
@@ -1,9 +1,10 @@
-package scala.swing.test
+package scala.swing
+package test
 
 import swing._
 import swing.event._
 
-object SwingApp extends SimpleGUIApplication {
+object SwingApp extends SimpleSwingApplication {
   def top = new MainFrame {
     title = "SwingApp"
     var numclicks = 0
diff --git a/src/swing/scala/swing/test/TableSelection.scala b/src/swing/scala/swing/test/TableSelection.scala
index 36b1894..1631214 100644
--- a/src/swing/scala/swing/test/TableSelection.scala
+++ b/src/swing/scala/swing/test/TableSelection.scala
@@ -1,110 +1,97 @@
-package scala.swing.test
+package scala.swing
+package test
 
 import java.awt.Dimension
-import swing._
 import swing.event._
 
-object TableSelection extends SimpleGUIApplication {
+object TableSelection extends SimpleSwingApplication {
   val model = Array(List("Mary", "Campione", "Snowboarding", 5, false).toArray,
-            List("Alison", "Huml", "Rowing", 5, false).toArray,
-            List("Kathy", "Walrath", "Knitting", 5, false).toArray,
-            List("Sharon", "Zakhour", "Speed reading", 5, false).toArray,
-            List("Philip", "Milne", "Pool", 5, false).toArray)
+                    List("Alison", "Huml", "Rowing", 5, false).toArray,
+                    List("Kathy", "Walrath", "Knitting", 5, false).toArray,
+                    List("Sharon", "Zakhour", "Speed reading", 5, false).toArray,
+                    List("Philip", "Milne", "Pool", 5, false).toArray)
+  /*val model = Array.tabulate(10000) { i => 
+    List("Mary", "Campione", "Snowboarding", i, false).toArray                
+  }*/
   
-  val ui = new BoxPanel(Orientation.Vertical) {
-      val table = new Table(model, Array("First Name", "Last Name", "Sport", "# of Years", "Vegetarian")) {
-        preferredViewportSize = new Dimension(500, 70)
-        val l = new Table.LabelRenderer[String](a => (null,a))
-        override def rendererComponent(isSelected: Boolean, hasFocus: Boolean, row: Int, column: Int): Component =
-         TableSelection.model(row)(column) match {
-           case s: String => l.componentFor(this, isSelected, hasFocus, s, row, column)
-           case _ => super.rendererComponent(isSelected, hasFocus, row, column)
-         }
-      }
-      //1.6:table.fillsViewportHeight = true
-      listenTo(table.selection)
-      
-      contents += new ScrollPane(table)
-      
-      contents += new Label("Selection Mode")
+  lazy val ui = new BoxPanel(Orientation.Vertical) {
+    val table = new Table(model, Array("First Name", "Last Name", "Sport", "# of Years", "Vegetarian")) {
+      preferredViewportSize = new Dimension(500, 70)
+    }
+    //1.6:table.fillsViewportHeight = true
+    listenTo(table.selection)
       
-      def radio(mutex: ButtonGroup, text: String): RadioButton = {
-        val b = new RadioButton(text)
-        listenTo(b)
-        mutex.buttons += b
-        contents += b
-        b
-      }
+    contents += new ScrollPane(table)
+    contents += new Label("Selection Mode")
       
-      val intervalMutex = new ButtonGroup
-      val multiInterval = radio(intervalMutex, "Multiple Interval Selection")
-      val elementInterval = radio(intervalMutex, "Single Selection")
-      val singleInterval = radio(intervalMutex, "Single Interval Selection")
-      intervalMutex.select(multiInterval)
+    def radio(mutex: ButtonGroup, text: String): RadioButton = {
+      val b = new RadioButton(text)
+      listenTo(b)
+      mutex.buttons += b
+      contents += b
+      b
+    }
       
-      contents += new Label("Selection Options")
-      val elemMutex = new ButtonGroup
-      val rowSelection = radio(elemMutex, "Row Selection")
-      val columnSelection = radio(elemMutex, "Column Selection")
-      val cellSelection = radio(elemMutex, "Cell Selection")
-      elemMutex.select(rowSelection)
+    val intervalMutex = new ButtonGroup
+    val multiInterval = radio(intervalMutex, "Multiple Interval Selection")
+    val elementInterval = radio(intervalMutex, "Single Selection")
+    val singleInterval = radio(intervalMutex, "Single Interval Selection")
+    intervalMutex.select(multiInterval)
+    
+    contents += new Label("Selection Options")
+    val elemMutex = new ButtonGroup
+    val rowSelection = radio(elemMutex, "Row Selection")
+    val columnSelection = radio(elemMutex, "Column Selection")
+    val cellSelection = radio(elemMutex, "Cell Selection")
+    elemMutex.select(rowSelection)
             
-      val output = new TextArea(5, 40) { editable = false }
-      contents += new ScrollPane(output)
+    val output = new TextArea(5, 40) { editable = false }
+    contents += new ScrollPane(output)
       
-      def outputSelection() {
-        output.append("Lead: " + table.selection.rows.leadIndex + "," + 
-                        table.selection.columns.leadIndex + ". ")
-        output.append("Rows:")
-        for (c <- table.selection.rows) output.append(" " + c)
-        output.append(". Columns:")
-        for (c <- table.selection.columns) output.append(" " + c)
-        output.append(".\n")
-      }
-      reactions += {
-        case ButtonClicked(_) => 
-          rowSelection.selected = table.selection.elementMode == Table.ElementMode.Row
-          columnSelection.selected = table.selection.elementMode == Table.ElementMode.Column
-          if (cellSelection.enabled) {
-            cellSelection.selected = table.selection.elementMode == Table.ElementMode.Cell
-          }
-      }
+    def outputSelection() {
+      output.append("Lead: " + table.selection.rows.leadIndex + "," + 
+          table.selection.columns.leadIndex + ". ")
+      output.append("Rows:")
+      for (c <- table.selection.rows) output.append(" " + c)
+      output.append(". Columns:")
+      for (c <- table.selection.columns) output.append(" " + c)
+      output.append(".\n")
+    }
       
-      reactions += {
-        case ButtonClicked(`multiInterval`) => 
-          table.selection.intervalMode = Table.IntervalMode.MultiInterval
-          if (cellSelection.selected) {
-            elemMutex.select(rowSelection)
-            table.selection.elementMode = Table.ElementMode.None
-          }
-          cellSelection.enabled = false
-        case ButtonClicked(`elementInterval`) =>
-          table.selection.intervalMode = Table.IntervalMode.Single
-          cellSelection.enabled = true
-        case ButtonClicked(`singleInterval`) =>
-          table.selection.intervalMode = Table.IntervalMode.SingleInterval
-          cellSelection.enabled = true
-        case ButtonClicked(`rowSelection`) => 
-          if (rowSelection.selected) 
-            table.selection.elementMode = Table.ElementMode.Row
-        case ButtonClicked(`columnSelection`) =>
-          if (columnSelection.selected) 
-            table.selection.elementMode = Table.ElementMode.Column
-        case ButtonClicked(`cellSelection`) =>
-          if (cellSelection.selected) 
-            table.selection.elementMode = Table.ElementMode.Cell
-        case TableRowsSelected(_, range, false) => 
-          output.append("Rows selected, changes: " + range + "\n")
-          outputSelection()
-        case TableColumnsSelected(_, range, false) => 
-          output.append("Columns selected, changes " + range + "\n")
-          outputSelection()
-      }
+    reactions += {
+      case ButtonClicked(`multiInterval`) => 
+        table.selection.intervalMode = Table.IntervalMode.MultiInterval
+        if (cellSelection.selected) {
+          elemMutex.select(rowSelection)
+          table.selection.elementMode = Table.ElementMode.None
+        }
+        cellSelection.enabled = false
+      case ButtonClicked(`elementInterval`) =>
+        table.selection.intervalMode = Table.IntervalMode.Single
+        cellSelection.enabled = true
+      case ButtonClicked(`singleInterval`) =>
+        table.selection.intervalMode = Table.IntervalMode.SingleInterval
+        cellSelection.enabled = true
+      case ButtonClicked(`rowSelection`) => 
+        if (rowSelection.selected) 
+          table.selection.elementMode = Table.ElementMode.Row
+      case ButtonClicked(`columnSelection`) =>
+        if (columnSelection.selected) 
+          table.selection.elementMode = Table.ElementMode.Column
+      case ButtonClicked(`cellSelection`) =>
+        if (cellSelection.selected) 
+          table.selection.elementMode = Table.ElementMode.Cell
+      case TableRowsSelected(_, range, false) => 
+        output.append("Rows selected, changes: " + range + "\n")
+        outputSelection()
+      case TableColumnsSelected(_, range, false) => 
+        output.append("Columns selected, changes " + range + "\n")
+        outputSelection()
     }
+  }
   
   def top = new MainFrame {
     title = "Table Selection"
     contents = ui
   }
 }
-
diff --git a/src/swing/scala/swing/test/UIDemo.scala b/src/swing/scala/swing/test/UIDemo.scala
index 8343b48..8e4ac40 100644
--- a/src/swing/scala/swing/test/UIDemo.scala
+++ b/src/swing/scala/swing/test/UIDemo.scala
@@ -1,85 +1,94 @@
-package scala.swing.test
+package scala.swing
+package test
 
 import swing._
 import event._
 import Swing._
+import ListView._
 
-object UIDemo extends SimpleGUIApplication {
+object UIDemo extends SimpleSwingApplication {
   def top = new MainFrame {
-    title = "UIElement Test"
+    title = "Scala Swing Demo"
     
-    menuBar = new MenuBar
-    
-    val menu = new Menu("A Menu")
-    menu.contents += new MenuItem("An item")
-    menu.contents += new MenuItem(Action("An action item") {
-      println("Action '"+ title +"' invoked")
-    })
-    menu.contents += new Separator
-    menu.contents += new CheckMenuItem("Check me")
-    menu.contents += new CheckMenuItem("Me too!")
-    menu.contents += new Separator
-    val a = new RadioMenuItem("a")
-    val b = new RadioMenuItem("b")
-    val c = new RadioMenuItem("c")
-    val mutex = new ButtonGroup(a,b,c)
-    menu.contents ++= mutex.buttons
-    
-    menuBar.contents += menu
-    menuBar.contents += new Menu("Empty Menu")
-    
-    var reactLive = false
-    
-    import Swing._
+    /*
+     * Create a menu bar with a couple of menus and menu items and 
+     * set the result as this frame's menu bar.
+     */
+    menuBar = new MenuBar {
+      contents += new Menu("A Menu") {
+        contents += new MenuItem("An item")
+        contents += new MenuItem(Action("An action item") {
+          println("Action '"+ title +"' invoked")
+        })
+        contents += new Separator
+        contents += new CheckMenuItem("Check me")
+        contents += new CheckMenuItem("Me too!")
+        contents += new Separator
+        val a = new RadioMenuItem("a")
+        val b = new RadioMenuItem("b")
+        val c = new RadioMenuItem("c")
+        val mutex = new ButtonGroup(a,b,c)
+        contents ++= mutex.buttons
+      }
+      contents += new Menu("Empty Menu")
+    }
     
+    /*
+     * The root component in this frame is a panel with a border layout. 
+     */
     contents = new BorderPanel {
       import BorderPanel.Position._
+      
+      var reactLive = false
+      
       val tabs = new TabbedPane {
         import TabbedPane._
         val buttons = new FlowPanel {
           border = Swing.EmptyBorder(5,5,5,5)
+          
           contents += new BoxPanel(Orientation.Vertical) {
             border = CompoundBorder(TitledBorder(EtchedBorder, "Radio Buttons"), EmptyBorder(5,5,5,10))
             val a = new RadioButton("Green Vegetables")
-    		val b = new RadioButton("Red Meat")
-    		val c = new RadioButton("White Tofu")
-    		val mutex = new ButtonGroup(a,b,c)
-    		contents ++= mutex.buttons
+            val b = new RadioButton("Red Meat")
+            val c = new RadioButton("White Tofu")
+            val mutex = new ButtonGroup(a,b,c)
+            contents ++= mutex.buttons
           }
           contents += new BoxPanel(Orientation.Vertical) {
             border = CompoundBorder(TitledBorder(EtchedBorder, "Check Boxes"), EmptyBorder(5,5,5,10))
             val paintLabels = new CheckBox("Paint Labels")
-    		val paintTicks = new CheckBox("Paint Ticks")
-    		val snapTicks = new CheckBox("Snap To Ticks")
-    		val live = new CheckBox("Live")
-    		contents.append(paintLabels, paintTicks, snapTicks, live)
-    		listenTo(paintLabels, paintTicks, snapTicks, live)
-    		reactions += {
-    		  case ButtonClicked(`paintLabels`) => 
-    		    slider.paintLabels = paintLabels.selected
-    		  case ButtonClicked(`paintTicks`) => 
-    		    slider.paintTicks = paintTicks.selected
-    		  case ButtonClicked(`snapTicks`) => 
-    		    slider.snapToTicks = snapTicks.selected
-    		  case ButtonClicked(`live`) => 
-    		    reactLive = live.selected
-    		}
+            val paintTicks = new CheckBox("Paint Ticks")
+            val snapTicks = new CheckBox("Snap To Ticks")
+            val live = new CheckBox("Live")
+            contents.append(paintLabels, paintTicks, snapTicks, live)
+            listenTo(paintLabels, paintTicks, snapTicks, live)
+            reactions += {
+              case ButtonClicked(`paintLabels`) => 
+                slider.paintLabels = paintLabels.selected
+              case ButtonClicked(`paintTicks`) => 
+                slider.paintTicks = paintTicks.selected
+              case ButtonClicked(`snapTicks`) => 
+                slider.snapToTicks = snapTicks.selected
+              case ButtonClicked(`live`) => 
+                reactLive = live.selected
+            }
           }
+          contents += new Button(Action("Center Frame") { centerOnScreen() })
         }
-        pages += new Page("Buttons", buttons)
+        pages += new Page("Buttons", buttons) 
         pages += new Page("GridBag", GridBagDemo.ui)
         pages += new Page("Converter", CelsiusConverter2.ui)
         pages += new Page("Tables", TableSelection.ui)
         pages += new Page("Dialogs", Dialogs.ui)
         pages += new Page("Combo Boxes", ComboBoxes.ui)
-        pages += new Page("Split Panes", new SplitPane(Orientation.Vertical, new Button("Hello"), new Button("World")) {
-                            continuousLayout = true
-                          })
+        pages += new Page("Split Panes", 
+          new SplitPane(Orientation.Vertical, new Button("Hello"), new Button("World")) {
+            continuousLayout = true
+          })
         
         val password = new FlowPanel {
           contents += new Label("Enter your secret password here ")
           val field = new PasswordField(10)
-          
           contents += field
           val label = new Label(field.text)
           contents += label
@@ -90,12 +99,13 @@ object UIDemo extends SimpleGUIApplication {
         }
         
         pages += new Page("Password", password)
+        pages += new Page("Painting", LinePainting.ui)
+        //pages += new Page("Text Editor", TextEditor.ui)
       }
             
       val list = new ListView(tabs.pages) {
-        selection.selectIndices(0)
+        selectIndices(0)
         selection.intervalMode = ListView.IntervalMode.Single
-        import ListView._
         renderer = ListView.Renderer(_.title)
       }
       val center = new SplitPane(Orientation.Vertical, new ScrollPane(list), tabs) {
@@ -103,7 +113,12 @@ object UIDemo extends SimpleGUIApplication {
         continuousLayout = true
       }      
       layout(center) = Center 
-            
+      
+      /*
+       * This slider is used above, so we need lazy initialization semantics.
+       * Objects or lazy vals are the way to go, but objects give us better 
+       * type inference at times.
+       */
       object slider extends Slider {
         min = 0
         value = tabs.selection.index
@@ -111,7 +126,10 @@ object UIDemo extends SimpleGUIApplication {
         majorTickSpacing = 1
       }
       layout(slider) = South
-      
+
+      /*
+       * Establish connection between the tab pane, slider, and list view.
+       */
       listenTo(slider)
       listenTo(tabs.selection)
       listenTo(list.selection)
@@ -120,12 +138,11 @@ object UIDemo extends SimpleGUIApplication {
           if(!slider.adjusting || reactLive) tabs.selection.index = slider.value
         case SelectionChanged(`tabs`) => 
           slider.value = tabs.selection.index
-          list.selection.selectIndices(tabs.selection.index)
+          list.selectIndices(tabs.selection.index)
         case SelectionChanged(`list`) =>
-          if (list.selection.items.size == 1)
+          if (list.selection.items.length == 1)
             tabs.selection.page = list.selection.items(0)
       }
     }
   }
-}
-
+}
\ No newline at end of file
diff --git a/src/swing/scala/swing/test/images/banana.jpg b/src/swing/scala/swing/test/images/banana.jpg
index 81fc4ab..62267a4 100644
Binary files a/src/swing/scala/swing/test/images/banana.jpg and b/src/swing/scala/swing/test/images/banana.jpg differ
diff --git a/src/swing/scala/swing/test/images/margarita1.jpg b/src/swing/scala/swing/test/images/margarita1.jpg
index 4857233..d315f7c 100644
Binary files a/src/swing/scala/swing/test/images/margarita1.jpg and b/src/swing/scala/swing/test/images/margarita1.jpg differ
diff --git a/src/swing/scala/swing/test/images/margarita2.jpg b/src/swing/scala/swing/test/images/margarita2.jpg
index c5fefb0..c8b076e 100644
Binary files a/src/swing/scala/swing/test/images/margarita2.jpg and b/src/swing/scala/swing/test/images/margarita2.jpg differ
diff --git a/src/swing/scala/swing/test/images/rose.jpg b/src/swing/scala/swing/test/images/rose.jpg
index 5c2e756..d4a2b58 100644
Binary files a/src/swing/scala/swing/test/images/rose.jpg and b/src/swing/scala/swing/test/images/rose.jpg differ
diff --git a/src/swing/swing.version.properties b/src/swing/swing.version.properties
index 30ac6bb..ba3675f 100644
--- a/src/swing/swing.version.properties
+++ b/src/swing/swing.version.properties
@@ -1,2 +1,2 @@
 version.major=0
-version.minor=4
\ No newline at end of file
+version.minor=4
diff --git a/test/files/cli/test1/Main.check.j9vm5 b/test/attic/files/cli/test1/Main.check.j9vm5
similarity index 100%
rename from test/files/cli/test1/Main.check.j9vm5
rename to test/attic/files/cli/test1/Main.check.j9vm5
diff --git a/test/files/cli/test1/Main.check.java b/test/attic/files/cli/test1/Main.check.java
similarity index 100%
rename from test/files/cli/test1/Main.check.java
rename to test/attic/files/cli/test1/Main.check.java
diff --git a/test/files/cli/test1/Main.check.java5 b/test/attic/files/cli/test1/Main.check.java5
similarity index 100%
rename from test/files/cli/test1/Main.check.java5
rename to test/attic/files/cli/test1/Main.check.java5
diff --git a/test/files/cli/test1/Main.check.java5_api b/test/attic/files/cli/test1/Main.check.java5_api
similarity index 100%
rename from test/files/cli/test1/Main.check.java5_api
rename to test/attic/files/cli/test1/Main.check.java5_api
diff --git a/test/files/cli/test1/Main.check.java5_j9 b/test/attic/files/cli/test1/Main.check.java5_j9
similarity index 100%
rename from test/files/cli/test1/Main.check.java5_j9
rename to test/attic/files/cli/test1/Main.check.java5_j9
diff --git a/test/files/cli/test1/Main.check.javac b/test/attic/files/cli/test1/Main.check.javac
similarity index 100%
rename from test/files/cli/test1/Main.check.javac
rename to test/attic/files/cli/test1/Main.check.javac
diff --git a/test/files/cli/test1/Main.check.javac5 b/test/attic/files/cli/test1/Main.check.javac5
similarity index 100%
rename from test/files/cli/test1/Main.check.javac5
rename to test/attic/files/cli/test1/Main.check.javac5
diff --git a/test/files/cli/test1/Main.check.javac6 b/test/attic/files/cli/test1/Main.check.javac6
similarity index 100%
rename from test/files/cli/test1/Main.check.javac6
rename to test/attic/files/cli/test1/Main.check.javac6
diff --git a/test/files/cli/test1/Main.check.jikes b/test/attic/files/cli/test1/Main.check.jikes
similarity index 100%
rename from test/files/cli/test1/Main.check.jikes
rename to test/attic/files/cli/test1/Main.check.jikes
diff --git a/test/files/cli/test1/Main.check.jikes5 b/test/attic/files/cli/test1/Main.check.jikes5
similarity index 100%
rename from test/files/cli/test1/Main.check.jikes5
rename to test/attic/files/cli/test1/Main.check.jikes5
diff --git a/test/files/cli/test1/Main.check.scala b/test/attic/files/cli/test1/Main.check.scala
similarity index 100%
rename from test/files/cli/test1/Main.check.scala
rename to test/attic/files/cli/test1/Main.check.scala
diff --git a/test/files/cli/test1/Main.check.scala_api b/test/attic/files/cli/test1/Main.check.scala_api
similarity index 100%
rename from test/files/cli/test1/Main.check.scala_api
rename to test/attic/files/cli/test1/Main.check.scala_api
diff --git a/test/files/cli/test1/Main.check.scala_j9 b/test/attic/files/cli/test1/Main.check.scala_j9
similarity index 100%
rename from test/files/cli/test1/Main.check.scala_j9
rename to test/attic/files/cli/test1/Main.check.scala_j9
diff --git a/test/attic/files/cli/test1/Main.check.scalac b/test/attic/files/cli/test1/Main.check.scalac
new file mode 100644
index 0000000..8465810
--- /dev/null
+++ b/test/attic/files/cli/test1/Main.check.scalac
@@ -0,0 +1,63 @@
+scalac error: bad option: '-dd'
+  scalac -help  gives more information
+Usage: scalac <options | source files>
+where possible options include: 
+  -doc                            Generate documentation
+  -g:<g>                          Generate debugging info (none,source,line,vars,notc)
+  -nowarn                         Generate no warnings
+  -noassert                       Generate no assertions and assumptions
+  -verbose                        Output messages about what the compiler is doing
+  -classpath <path>               Specify where to find user class files
+  -sourcepath <path>              Specify where to find input source files
+  -bootclasspath <path>           Override location of bootstrap class files
+  -extdirs <dirs>                 Override location of installed extensions
+  -d <directory>                  Specify where to place generated class files
+  -encoding <encoding>            Specify character encoding used by source files
+  -windowtitle <windowtitle>      Specify window title of generated HTML documentation
+  -documenttitle <documenttitle>  Specify document title of generated HTML documentation
+  -target:<target>                Specify which backend to use (jvm-1.5,msil)
+  -migrate                        Assist in migrating from Scala version 1.0
+  -o <file>                       Name of the output assembly (only relevant with -target:msil)
+  -r <path>                       List of assemblies referenced by the program (only relevant with -target:msil)
+  -debug                          Output debugging messages
+  -deprecation                    enable detailed deprecation warnings
+  -unchecked                      enable detailed unchecked warnings
+  -statistics                     Print compiler statistics
+  -explaintypes                   Explain type errors in more detail
+  -resident                       Compiler stays resident, files to compile are read from standard input
+  -uniqid                         Print identifiers with unique names (debugging option)
+  -printtypes                     Print tree types (debugging option)
+  -prompt                         Display a prompt after each error (debugging option)
+  -noimports                      Compile without any implicit imports
+  -nopredefs                      Compile without any implicit predefined values
+  -skip:<phase>                   Skip <phase>
+  -check:<phase>                  Check the tree at start of <phase>
+  -print:<phase>                  Print out program after <phase>
+  -printer:<printer>              Printer to use (text,html)
+  -printfile <file>               Specify file in which to print trees
+  -graph:<phase>                  Graph the program after <phase>
+  -browse:<phase>                 Browse the abstract syntax tree after <phase>
+  -stop:<phase>                   Stop after phase <phase>
+  -log:<phase>                    Log operations in <phase>
+  -logall                         Log all operations
+  -version                        Print product version and exit
+  -help                           Print a synopsis of standard options
+  -nouescape                      disables handling of \u unicode escapes
+  -Xinline                        Perform inlining when possible
+  -XO                             Optimize. implies -Xinline, -Xcloselim and -Xdce
+  -Xcloselim                      Perform closure elimination
+  -Xdce                           Perform dead code elimination
+  -Xwarndeadcode                  Emit warnings for dead code
+  -XbytecodeRead                  Enable bytecode reader.
+  -Xdetach                        Perform detaching of remote closures
+  -Xshowcls <class>               Show class info
+  -Xshowobj <object>              Show object info
+  -Xlinearizer:<Xlinearizer>      Linearizer to use (normal,dfs,rpo,dump)
+  -Xgenerics                      Use generic Java types
+  -Xprintpos                      Print tree positions (as offsets)
+  -Xscript                        compile script file
+  -Xexperimental                  enable experimental extensions
+  -Xplugtypes                     parse but ignore annotations in more locations
+  -Xkilloption                    optimizes option types
+
+one error found
diff --git a/test/files/cli/test1/Main.check.scalaint b/test/attic/files/cli/test1/Main.check.scalaint
similarity index 100%
rename from test/files/cli/test1/Main.check.scalaint
rename to test/attic/files/cli/test1/Main.check.scalaint
diff --git a/test/files/cli/test1/Main.java b/test/attic/files/cli/test1/Main.java
similarity index 100%
rename from test/files/cli/test1/Main.java
rename to test/attic/files/cli/test1/Main.java
diff --git a/test/files/cli/test1/Main.scala b/test/attic/files/cli/test1/Main.scala
similarity index 100%
rename from test/files/cli/test1/Main.scala
rename to test/attic/files/cli/test1/Main.scala
diff --git a/test/files/cli/test2/Main.check.j9vm5 b/test/attic/files/cli/test2/Main.check.j9vm5
similarity index 100%
rename from test/files/cli/test2/Main.check.j9vm5
rename to test/attic/files/cli/test2/Main.check.j9vm5
diff --git a/test/files/cli/test2/Main.check.java b/test/attic/files/cli/test2/Main.check.java
similarity index 100%
rename from test/files/cli/test2/Main.check.java
rename to test/attic/files/cli/test2/Main.check.java
diff --git a/test/files/cli/test2/Main.check.java5 b/test/attic/files/cli/test2/Main.check.java5
similarity index 100%
rename from test/files/cli/test2/Main.check.java5
rename to test/attic/files/cli/test2/Main.check.java5
diff --git a/test/files/cli/test2/Main.check.java5_api b/test/attic/files/cli/test2/Main.check.java5_api
similarity index 100%
rename from test/files/cli/test2/Main.check.java5_api
rename to test/attic/files/cli/test2/Main.check.java5_api
diff --git a/test/files/cli/test2/Main.check.java5_j9 b/test/attic/files/cli/test2/Main.check.java5_j9
similarity index 100%
rename from test/files/cli/test2/Main.check.java5_j9
rename to test/attic/files/cli/test2/Main.check.java5_j9
diff --git a/test/files/cli/test2/Main.check.javac b/test/attic/files/cli/test2/Main.check.javac
similarity index 100%
rename from test/files/cli/test2/Main.check.javac
rename to test/attic/files/cli/test2/Main.check.javac
diff --git a/test/files/cli/test2/Main.check.javac5 b/test/attic/files/cli/test2/Main.check.javac5
similarity index 100%
rename from test/files/cli/test2/Main.check.javac5
rename to test/attic/files/cli/test2/Main.check.javac5
diff --git a/test/files/cli/test2/Main.check.javac6 b/test/attic/files/cli/test2/Main.check.javac6
similarity index 100%
rename from test/files/cli/test2/Main.check.javac6
rename to test/attic/files/cli/test2/Main.check.javac6
diff --git a/test/files/cli/test2/Main.check.jikes b/test/attic/files/cli/test2/Main.check.jikes
similarity index 100%
rename from test/files/cli/test2/Main.check.jikes
rename to test/attic/files/cli/test2/Main.check.jikes
diff --git a/test/files/cli/test2/Main.check.jikes5 b/test/attic/files/cli/test2/Main.check.jikes5
similarity index 100%
rename from test/files/cli/test2/Main.check.jikes5
rename to test/attic/files/cli/test2/Main.check.jikes5
diff --git a/test/files/cli/test2/Main.check.scala b/test/attic/files/cli/test2/Main.check.scala
similarity index 100%
rename from test/files/cli/test2/Main.check.scala
rename to test/attic/files/cli/test2/Main.check.scala
diff --git a/test/files/cli/test2/Main.check.scala_api b/test/attic/files/cli/test2/Main.check.scala_api
similarity index 100%
rename from test/files/cli/test2/Main.check.scala_api
rename to test/attic/files/cli/test2/Main.check.scala_api
diff --git a/test/files/cli/test2/Main.check.scala_j9 b/test/attic/files/cli/test2/Main.check.scala_j9
similarity index 100%
rename from test/files/cli/test2/Main.check.scala_j9
rename to test/attic/files/cli/test2/Main.check.scala_j9
diff --git a/test/attic/files/cli/test2/Main.check.scalac b/test/attic/files/cli/test2/Main.check.scalac
new file mode 100644
index 0000000..8465810
--- /dev/null
+++ b/test/attic/files/cli/test2/Main.check.scalac
@@ -0,0 +1,63 @@
+scalac error: bad option: '-dd'
+  scalac -help  gives more information
+Usage: scalac <options | source files>
+where possible options include: 
+  -doc                            Generate documentation
+  -g:<g>                          Generate debugging info (none,source,line,vars,notc)
+  -nowarn                         Generate no warnings
+  -noassert                       Generate no assertions and assumptions
+  -verbose                        Output messages about what the compiler is doing
+  -classpath <path>               Specify where to find user class files
+  -sourcepath <path>              Specify where to find input source files
+  -bootclasspath <path>           Override location of bootstrap class files
+  -extdirs <dirs>                 Override location of installed extensions
+  -d <directory>                  Specify where to place generated class files
+  -encoding <encoding>            Specify character encoding used by source files
+  -windowtitle <windowtitle>      Specify window title of generated HTML documentation
+  -documenttitle <documenttitle>  Specify document title of generated HTML documentation
+  -target:<target>                Specify which backend to use (jvm-1.5,msil)
+  -migrate                        Assist in migrating from Scala version 1.0
+  -o <file>                       Name of the output assembly (only relevant with -target:msil)
+  -r <path>                       List of assemblies referenced by the program (only relevant with -target:msil)
+  -debug                          Output debugging messages
+  -deprecation                    enable detailed deprecation warnings
+  -unchecked                      enable detailed unchecked warnings
+  -statistics                     Print compiler statistics
+  -explaintypes                   Explain type errors in more detail
+  -resident                       Compiler stays resident, files to compile are read from standard input
+  -uniqid                         Print identifiers with unique names (debugging option)
+  -printtypes                     Print tree types (debugging option)
+  -prompt                         Display a prompt after each error (debugging option)
+  -noimports                      Compile without any implicit imports
+  -nopredefs                      Compile without any implicit predefined values
+  -skip:<phase>                   Skip <phase>
+  -check:<phase>                  Check the tree at start of <phase>
+  -print:<phase>                  Print out program after <phase>
+  -printer:<printer>              Printer to use (text,html)
+  -printfile <file>               Specify file in which to print trees
+  -graph:<phase>                  Graph the program after <phase>
+  -browse:<phase>                 Browse the abstract syntax tree after <phase>
+  -stop:<phase>                   Stop after phase <phase>
+  -log:<phase>                    Log operations in <phase>
+  -logall                         Log all operations
+  -version                        Print product version and exit
+  -help                           Print a synopsis of standard options
+  -nouescape                      disables handling of \u unicode escapes
+  -Xinline                        Perform inlining when possible
+  -XO                             Optimize. implies -Xinline, -Xcloselim and -Xdce
+  -Xcloselim                      Perform closure elimination
+  -Xdce                           Perform dead code elimination
+  -Xwarndeadcode                  Emit warnings for dead code
+  -XbytecodeRead                  Enable bytecode reader.
+  -Xdetach                        Perform detaching of remote closures
+  -Xshowcls <class>               Show class info
+  -Xshowobj <object>              Show object info
+  -Xlinearizer:<Xlinearizer>      Linearizer to use (normal,dfs,rpo,dump)
+  -Xgenerics                      Use generic Java types
+  -Xprintpos                      Print tree positions (as offsets)
+  -Xscript                        compile script file
+  -Xexperimental                  enable experimental extensions
+  -Xplugtypes                     parse but ignore annotations in more locations
+  -Xkilloption                    optimizes option types
+
+one error found
diff --git a/test/files/cli/test2/Main.check.scalaint b/test/attic/files/cli/test2/Main.check.scalaint
similarity index 100%
rename from test/files/cli/test2/Main.check.scalaint
rename to test/attic/files/cli/test2/Main.check.scalaint
diff --git a/test/files/cli/test2/Main.java b/test/attic/files/cli/test2/Main.java
similarity index 100%
rename from test/files/cli/test2/Main.java
rename to test/attic/files/cli/test2/Main.java
diff --git a/test/files/cli/test2/Main.scala b/test/attic/files/cli/test2/Main.scala
similarity index 100%
rename from test/files/cli/test2/Main.scala
rename to test/attic/files/cli/test2/Main.scala
diff --git a/test/files/cli/test3/Main.check.j9vm5 b/test/attic/files/cli/test3/Main.check.j9vm5
similarity index 100%
rename from test/files/cli/test3/Main.check.j9vm5
rename to test/attic/files/cli/test3/Main.check.j9vm5
diff --git a/test/files/cli/test3/Main.check.java b/test/attic/files/cli/test3/Main.check.java
similarity index 100%
rename from test/files/cli/test3/Main.check.java
rename to test/attic/files/cli/test3/Main.check.java
diff --git a/test/files/cli/test3/Main.check.java5 b/test/attic/files/cli/test3/Main.check.java5
similarity index 100%
rename from test/files/cli/test3/Main.check.java5
rename to test/attic/files/cli/test3/Main.check.java5
diff --git a/test/files/cli/test3/Main.check.java5_api b/test/attic/files/cli/test3/Main.check.java5_api
similarity index 100%
rename from test/files/cli/test3/Main.check.java5_api
rename to test/attic/files/cli/test3/Main.check.java5_api
diff --git a/test/files/cli/test3/Main.check.java5_j9 b/test/attic/files/cli/test3/Main.check.java5_j9
similarity index 100%
rename from test/files/cli/test3/Main.check.java5_j9
rename to test/attic/files/cli/test3/Main.check.java5_j9
diff --git a/test/files/cli/test3/Main.check.javac b/test/attic/files/cli/test3/Main.check.javac
similarity index 100%
rename from test/files/cli/test3/Main.check.javac
rename to test/attic/files/cli/test3/Main.check.javac
diff --git a/test/files/cli/test3/Main.check.javac5 b/test/attic/files/cli/test3/Main.check.javac5
similarity index 100%
rename from test/files/cli/test3/Main.check.javac5
rename to test/attic/files/cli/test3/Main.check.javac5
diff --git a/test/files/cli/test3/Main.check.javac6 b/test/attic/files/cli/test3/Main.check.javac6
similarity index 100%
rename from test/files/cli/test3/Main.check.javac6
rename to test/attic/files/cli/test3/Main.check.javac6
diff --git a/test/files/cli/test3/Main.check.jikes b/test/attic/files/cli/test3/Main.check.jikes
similarity index 100%
rename from test/files/cli/test3/Main.check.jikes
rename to test/attic/files/cli/test3/Main.check.jikes
diff --git a/test/files/cli/test3/Main.check.jikes5 b/test/attic/files/cli/test3/Main.check.jikes5
similarity index 100%
rename from test/files/cli/test3/Main.check.jikes5
rename to test/attic/files/cli/test3/Main.check.jikes5
diff --git a/test/files/cli/test3/Main.check.scala b/test/attic/files/cli/test3/Main.check.scala
similarity index 100%
rename from test/files/cli/test3/Main.check.scala
rename to test/attic/files/cli/test3/Main.check.scala
diff --git a/test/files/cli/test3/Main.check.scala_api b/test/attic/files/cli/test3/Main.check.scala_api
similarity index 100%
rename from test/files/cli/test3/Main.check.scala_api
rename to test/attic/files/cli/test3/Main.check.scala_api
diff --git a/test/files/cli/test3/Main.check.scala_j9 b/test/attic/files/cli/test3/Main.check.scala_j9
similarity index 100%
rename from test/files/cli/test3/Main.check.scala_j9
rename to test/attic/files/cli/test3/Main.check.scala_j9
diff --git a/test/attic/files/cli/test3/Main.check.scalac b/test/attic/files/cli/test3/Main.check.scalac
new file mode 100644
index 0000000..8465810
--- /dev/null
+++ b/test/attic/files/cli/test3/Main.check.scalac
@@ -0,0 +1,63 @@
+scalac error: bad option: '-dd'
+  scalac -help  gives more information
+Usage: scalac <options | source files>
+where possible options include: 
+  -doc                            Generate documentation
+  -g:<g>                          Generate debugging info (none,source,line,vars,notc)
+  -nowarn                         Generate no warnings
+  -noassert                       Generate no assertions and assumptions
+  -verbose                        Output messages about what the compiler is doing
+  -classpath <path>               Specify where to find user class files
+  -sourcepath <path>              Specify where to find input source files
+  -bootclasspath <path>           Override location of bootstrap class files
+  -extdirs <dirs>                 Override location of installed extensions
+  -d <directory>                  Specify where to place generated class files
+  -encoding <encoding>            Specify character encoding used by source files
+  -windowtitle <windowtitle>      Specify window title of generated HTML documentation
+  -documenttitle <documenttitle>  Specify document title of generated HTML documentation
+  -target:<target>                Specify which backend to use (jvm-1.5,msil)
+  -migrate                        Assist in migrating from Scala version 1.0
+  -o <file>                       Name of the output assembly (only relevant with -target:msil)
+  -r <path>                       List of assemblies referenced by the program (only relevant with -target:msil)
+  -debug                          Output debugging messages
+  -deprecation                    enable detailed deprecation warnings
+  -unchecked                      enable detailed unchecked warnings
+  -statistics                     Print compiler statistics
+  -explaintypes                   Explain type errors in more detail
+  -resident                       Compiler stays resident, files to compile are read from standard input
+  -uniqid                         Print identifiers with unique names (debugging option)
+  -printtypes                     Print tree types (debugging option)
+  -prompt                         Display a prompt after each error (debugging option)
+  -noimports                      Compile without any implicit imports
+  -nopredefs                      Compile without any implicit predefined values
+  -skip:<phase>                   Skip <phase>
+  -check:<phase>                  Check the tree at start of <phase>
+  -print:<phase>                  Print out program after <phase>
+  -printer:<printer>              Printer to use (text,html)
+  -printfile <file>               Specify file in which to print trees
+  -graph:<phase>                  Graph the program after <phase>
+  -browse:<phase>                 Browse the abstract syntax tree after <phase>
+  -stop:<phase>                   Stop after phase <phase>
+  -log:<phase>                    Log operations in <phase>
+  -logall                         Log all operations
+  -version                        Print product version and exit
+  -help                           Print a synopsis of standard options
+  -nouescape                      disables handling of \u unicode escapes
+  -Xinline                        Perform inlining when possible
+  -XO                             Optimize. implies -Xinline, -Xcloselim and -Xdce
+  -Xcloselim                      Perform closure elimination
+  -Xdce                           Perform dead code elimination
+  -Xwarndeadcode                  Emit warnings for dead code
+  -XbytecodeRead                  Enable bytecode reader.
+  -Xdetach                        Perform detaching of remote closures
+  -Xshowcls <class>               Show class info
+  -Xshowobj <object>              Show object info
+  -Xlinearizer:<Xlinearizer>      Linearizer to use (normal,dfs,rpo,dump)
+  -Xgenerics                      Use generic Java types
+  -Xprintpos                      Print tree positions (as offsets)
+  -Xscript                        compile script file
+  -Xexperimental                  enable experimental extensions
+  -Xplugtypes                     parse but ignore annotations in more locations
+  -Xkilloption                    optimizes option types
+
+one error found
diff --git a/test/files/cli/test3/Main.check.scalaint b/test/attic/files/cli/test3/Main.check.scalaint
similarity index 100%
rename from test/files/cli/test3/Main.check.scalaint
rename to test/attic/files/cli/test3/Main.check.scalaint
diff --git a/test/attic/files/cli/test3/Main.java b/test/attic/files/cli/test3/Main.java
new file mode 100644
index 0000000..208863d
--- /dev/null
+++ b/test/attic/files/cli/test3/Main.java
@@ -0,0 +1,10 @@
+// @info 2 dependency
+package test3;
+public class Main {
+  public static void main(String args[]) {
+    System.out.print("3: ");
+    test1.Main.main(args);
+    System.out.print("3: ");
+    test2.Main.main(args);
+  }
+}
diff --git a/test/attic/files/cli/test3/Main.scala b/test/attic/files/cli/test3/Main.scala
new file mode 100644
index 0000000..63fc11b
--- /dev/null
+++ b/test/attic/files/cli/test3/Main.scala
@@ -0,0 +1,10 @@
+// @info 2 dependencies
+package test3
+object Main {
+  def main(args: Array[String]) = {
+    Console.print("3: ")
+    test1.Main.main(args)
+    Console.print("3: ")
+    test2.Main.main(args)
+  }
+}
diff --git a/test/clitest b/test/clitest
deleted file mode 100644
index 19348a0..0000000
--- a/test/clitest
+++ /dev/null
@@ -1,497 +0,0 @@
-#!/bin/sh
-##############################################################################
-#                      __                                                    #
-#      ________ ___   / /  ___     Scala Tools Launch Script                 #
-#     / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL                  #
-#   __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/                    #
-#  /____/\___/_/ |_/____/_/ | |                                              #
-#                           |/                                               #
-##############################################################################
-
-# $Id: clitest 16894 2009-01-13 13:09:41Z cunei $
-
-##############################################################################
-# Error functions
-
-# Prints a warning message on stderr.
-warning() {
-    echo "$0: warning:" "$@" 1>&2;
-}
-
-# Prints an error message on stderr.
-error() {
-    echo "$0:" "$@" 1>&2;
-}
-
-# Prints an error message on stderr and exits with a non-zero status.
-abort() {
-    error "$@";
-    exit 1;
-}
-
-##############################################################################
-# Printing functions
-
-# Initializes the printf functions
-printf_initialization() {
-    case "$1" in
-        many )
-            printf_font_outline="printf \\033[1;39m";
-            printf_font_success="printf \\033[1;32m";
-            printf_font_failure="printf \\033[1;31m";
-            printf_font_warning="printf \\033[1;33m";
-            printf_font_default="printf \\033[0;39m";
-            ;;
-        some )
-            printf_font_outline="printf \\033[1m";
-            printf_font_success="printf \\033[0m";
-            printf_font_failure="printf \\033[1m";
-            printf_font_warning="printf \\033[1m";
-            printf_font_default="printf \\033[0m";
-            ;;
-        none )
-            printf_font_outline="";
-            printf_font_success="";
-            printf_font_failure="";
-            printf_font_warning="";
-            printf_font_default="";
-            ;;
-        * )
-            abort "unknown color mode \`$1'";
-            ;;
-    esac;
-}
-
-# Prints formated text in outline font.
-printf_outline() {
-    $printf_font_outline;
-    printf "$@";
-    $printf_font_default;
-}
-
-##############################################################################
-# File name and path list conversion functions
-
-# Prints the OS-specific form of the specified Unix form file name.
-get_os_filename() {
-    [ $# = 1 ] || abort "internal error";
-    case "$UNAME" in
-        CYGWIN* ) cygpath --windows "$1";;
-        *       ) echo "$@";;
-    esac;
-}
-
-# Prints the Unix form of the specified OS-specific form file name.
-get_unix_filename() {
-    [ $# = 1 ] || abort "internal error";
-    case "$UNAME" in
-        CYGWIN* ) cygpath --unix "$1";;
-        *       ) echo "$@";;
-    esac;
-}
-
-# Prints the OS-specific form of the specified Unix form path list.
-get_os_pathlist() {
-    [ $# = 1 ] || abort "internal error";
-    case "$UNAME" in
-        CYGWIN* ) cygpath --window --path "$1";;
-        *       ) echo "$@";;
-    esac;
-}
-
-# Prints the Unix form of the specified OS-specific form path list.
-get_unix_pathlist() {
-    [ $# = 1 ] || abort "internal error";
-    case "$UNAME" in
-        CYGWIN* ) cygpath --unix --path "$1";;
-        *       ) echo "$@";;
-    esac;
-}
-
-##############################################################################
-# Implementation of clitest
-
-# Prints the clitest usage.
-test_print_usage() {
-    [ $# = 0 ] || abort "internal error";
-    echo "Usage: $0 [OPTION]..."
-}
-
-# Prints the clitest help.
-test_print_help() {
-    [ $# = 0 ] || abort "internal error";
-    test_print_usage;
-    echo "";
-    echo "--quick         use the 'quick' build instead of distribution";
-    echo '--installed     use the installed programs on $PATH'
-    echo "--debug         redirect all outputs to standard output";
-    echo "--info          display information messages";
-    echo "--javac         run same tests with the Sun Java compiler";
-    echo "--jikes         run same tests with the IBM Java compiler";
-    echo "--jredir=<dir>  specify the Sun JRE installation directory (jikes)";
-    echo "--objdir=<dir>  specify where to place generated files";
-    echo "--verbose       display verbose messages";
-    echo "--help, -?      display this help and exit";
-    echo "--version       output version information and exit";
-}
-
-# Prints the clitest version.
-test_print_version() {
-    [ $# = 0 ] || abort "internal error";
-    echo "$SCRIPT 1.3";
-}
-
-# Adds a new file to the appropriate file list(s).
-test_add_file() {
-    [ $# = 1 ] || abort "internal error";
-    case "$1" in
-        *.scala )
-            if [ ! \( -d "$1" -o -f "$1" \) ]; then
-                abort "don't know what to do with '$1'";
-            fi;
-            dir=`dirname "$1"`;
-            file=`cd $dir && pwd`/`basename $1`;
-            FILES="$FILES $file";;
-        * )
-            if [ ! -d "$1" ]; then
-                abort "don't know what to do with '$1'";
-            fi;
-            dir=`cd "$1" && pwd`;
-            file=`find "$dir" -name "Main$SUFFIX" -a -type f -print`;
-            FILES="$FILES $file";;
-    esac;
-}
-
-test_run() {
-    [ $# = 1 ] || abort "internal error";
-    cmd="$1"; shift 1;
-    [ "$DEBUG" = "debug" ] && ( printf_outline "[DEBUG]"; echo "$cmd");
-    eval "$cmd";
-}
-
-test_diff() {
-    [ $# = 2 ] || abort "internal error";
-    check="$1"; shift 1;
-    log="$1"; shift 1;
-    [ "$DEBUG" = "debug" ] && return;
-    sed -e "s#$TEST_DIR/##g" $log > $TMP_FILE;
-    $DIFF $check $TMP_FILE > $DIFF_FILE
-    if [ -n "`cat $DIFF_FILE`" ] ; then
-        printf_outline "\\nDifferences between check and log files:\\n";
-        file=`echo $check | sed -e "s#$PREFIX/##g"`;
-        printf "$file\\n";
-        cat $DIFF_FILE;
-    fi
-}
-
-test_compile() {
-    [ $# = 3 ] || abort "internal error";
-    source="$1"; shift 1;
-    check="$1"; shift 1;
-    info="$1"; shift 1;
-    [ -d "$OUTPUT_DIR" ] || mkdir -p $OUTPUT_DIR;
-    [ -f "$LOG_FILE" ] && $RM $LOG_FILE;
-    if [ "$COMPILER" = "javac" ] || [ "$COMPILER" = "jikes" ]; then
-        suffix=".${COMPILER}";
-        [ "$LANG" = "java5" ] && suffix=".${COMPILER}5";
-        [ "$LANG" = "java6" ] && suffix=".${COMPILER}6";
-    else
-        suffix=".$COMPILER";
-    fi;
-    file=`echo $source | sed -e "s#$PREFIX/##g"`;
-    if [ "$LEVEL" = "info" ] || [ "$LEVEL" = "verbose" ] ; then
-        printf_outline "\\nSource file: $file\\n"
-        cat $source;
-    fi
-    printf "\\n";
-
-    #=`get_unix_filename "$source"`;
-    printf "Compile $file ($info) with unknown option '-dd'\\n"
-    test_run "env CLASSPATH= $COMPILER_COMMAND \
-        -dd $OUTPUT_DIR $source 2>> $LOG_FILE 1>> $LOG_FILE";
-
-    printf "Compile $file ($info) with no classpath information\\n"
-    test_run "env CLASSPATH= $COMPILER_COMMAND \
-        -d $OUTPUT_DIR $source 2>> $LOG_FILE 1>> $LOG_FILE";
-
-    printf "Compile $file ($info) with variable CLASSPATH\\n"
-    test_run "env CLASSPATH=$OUTPUT_DIR $COMPILER_COMMAND \
-        -d $OUTPUT_DIR $source 2>> $LOG_FILE 1>> $LOG_FILE";
-
-    printf "Compile $file ($info) with option -classpath\\n"
-    test_run "env CLASSPATH= $COMPILER_COMMAND -classpath $OUTPUT_DIR \
-        -d $OUTPUT_DIR $source 2>> $LOG_FILE 1>> $LOG_FILE";
-
-    printf "Compile $file ($info) with current directory as default classpath\\n"
-    test_run "(cd $OUTPUT_DIR &&
-        env CLASSPATH= $COMPILER_COMMAND $source 2>> $LOG_FILE 1>> $LOG_FILE)";
-
-    test_diff "$check$suffix" "$LOG_FILE";
-
-    if [ "$LEVEL" = "verbose" ] ; then
-        printf_outline "\\nTest directory:\\n";
-        $TREE $TMP_DIR;
-    fi
-}
-
-test_execute() {
-    [ $# = 2 ] || abort "internal error";
-    main="$1"; shift 1;
-    check="$1"; shift 1;
-    suffix=".$LANG";
-    [ "$LANG" = "java6" ] && suffix=".java5";
-
-    [ -f "$LOG_FILE" ] && $RM $LOG_FILE;
-    printf "\\n";
-
-    printf "Execute $main with unknown option '-cpp'\\n"
-    test_run "env CLASSPATH= \
-        $RUNTIME_COMMAND -cpp $OUTPUT_DIR $main 2 \
-        2>> $LOG_FILE 1>> $LOG_FILE";
-
-    printf "Execute $main with variable CLASSPATH\\n"
-    test_run "env CLASSPATH=$OUTPUT_DIR \
-        $RUNTIME_COMMAND $main 1 \
-        2>> $LOG_FILE 1>> $LOG_FILE";
-
-    printf "Execute $main with option -classpath\\n"
-    test_run "env CLASSPATH= \
-        $RUNTIME_COMMAND -classpath $OUTPUT_DIR $main 2 \
-        2>> $LOG_FILE 1>> $LOG_FILE";
-
-    printf "Execute $main with current directory as default classpath\\n"
-    test_run "(cd $OUTPUT_DIR &&
-        env CLASSPATH= $RUNTIME_COMMAND $main 3 2>> $LOG_FILE 1>> $LOG_FILE)";
-
-    printf "Execute $main with quoted argument\\n"
-    test_run "env CLASSPATH= \
-        $RUNTIME_COMMAND -classpath $OUTPUT_DIR $main 4 \"a b c\" \
-        2>> $LOG_FILE 1>> $LOG_FILE";
-
-    test_diff "$check$suffix" "$LOG_FILE";
-}
-
-test_interpret() {
-    [ $# = 2 ] || abort "internal error";
-    main="$1"; shift 1;
-    check="$1"; shift 1;
-    [ "$LANG" = "scala" ] || return;
-    [ -f "$LOG_FILE" ] && $RM $LOG_FILE;
-    printf "\\n"
-
-    printf "Interpret $main with unknown option '-cpp'\\n"
-    test_run "(env CLASSPATH= \
-        printf $main'.main(Array(\"0\"))\n:q' | $INTERPRETER_COMMAND \
-        -cpp $OUTPUT_DIR 2>> $LOG_FILE 1>> $LOG_FILE)";
-    printf "\\n" >> $LOG_FILE  # newline
-
-    printf "Interpret $main with variable CLASSPATH\\n"
-    test_run "(printf $main'.main(Array(\"1\"))\n:q' \
-        | env CLASSPATH=$OUTPUT_DIR $INTERPRETER_COMMAND \
-        2>> $LOG_FILE 1>> $LOG_FILE)";
-    printf "\\n" >> $LOG_FILE  # newline
-
-    printf "Interpret $main with option -classpath\\n"
-    test_run "(env CLASSPATH= \
-        printf $main'.main(Array(\"2\"))\n:q' | $INTERPRETER_COMMAND \
-        -classpath $OUTPUT_DIR 2>> $LOG_FILE 1>> $LOG_FILE)";
-    printf "\\n" >> $LOG_FILE  # newline
-
-    printf "Interpret $main with current directory as default classpath\\n"
-    test_run "(cd $OUTPUT_DIR &&
-        printf $main'.main(Array(\"3\"))\n:q' | $INTERPRETER_COMMAND \
-        2>> $LOG_FILE 1>> $LOG_FILE)";
-    printf "\\n" >> $LOG_FILE # newline
-
-    test_diff "$check.scalaint" "$LOG_FILE";
-}
-
-test_docgen() {
-    [ $# = 2 ] || abort "internal error";
-    source="$1"; shift 1;
-    check="$1"; shift 1;
-    [ -d "$OUTPUT_DIR" ] || mkdir -p $OUTPUT_DIR;
-    [ -f "$LOG_FILE" ] && $RM $LOG_FILE;
-    [ -d "$API_DIR" ] && $RM -r "$API_DIR/*" || mkdir -p $API_DIR; 
-    suffix=".${LANG}_api";
-    file=`echo $source | sed -e "s#$PREFIX/##g"`;
-    if [ "$LEVEL" = "info" ] || [ "$LEVEL" = "verbose" ] ; then
-        printf_outline "\\nSource file: $file\\n"
-        cat $source;
-    fi
-    printf "\\n";
-
-    printf "Generate documentation for $file\\n"
-    test_run "env CLASSPATH= $DOCGEN_COMMAND \
-        -d $API_DIR $source 2>> $LOG_FILE 1>> $LOG_FILE";
-
-    n=`$TREE $API_DIR | wc -l`;
-    $TREE $API_DIR | tail -n `echo "$n-1" | bc` > "$LOG_FILE";
-    test_diff "$check$suffix" "$LOG_FILE";
-
-    if [ "$LEVEL" = "verbose" ] ; then
-        printf_outline "\\nAPI directory:\\n";
-        $TREE $API_DIR;
-    fi
-}
-
-##############################################################################
-# Initialization
-
-unset SCRIPT;
-UNAME=`uname`;
-SOURCE=$0;
-SCRIPT=`basename "$SOURCE"`;
-while [ -h "$SOURCE" ]; do
-    SCRIPT=`basename "$SOURCE"`;
-    LOOKUP=`ls -ld "$SOURCE"`;
-    TARGET=`expr "$LOOKUP" : '.*-> \(.*\)$'`;
-    if expr "${TARGET:-.}/" : '/.*/$' > /dev/null; then
-        SOURCE=${TARGET:-.};
-    else
-        SOURCE=`dirname "$SOURCE"`/${TARGET:-.};
-    fi;
-done;
-PREFIX=`dirname "$SOURCE"`/..;
-prefix=$PREFIX;
-PREFIX=`cd "$PREFIX"; pwd`;
-
-QUICK="$PREFIX/build/quick/bin/"
-if [ -d "$PREFIX/dists" ]; then
-    LATEST="$PREFIX/dists/latest/bin/";
-else
-    if [ -d "$PREFIX/build" ]; then
-        LATEST="$QUICK";
-    else
-        LATEST="$PREFIX/bin/";
-    fi;
-fi;
-BIN_DIR="$LATEST"
-
-if [ -n "`which mktemp`" ] ; then
-    TMP_DIR=`mktemp -d`
-else
-    TMP_DIR=${TMPDIR-/tmp}/tmp-$USER.`basename $0`
-fi
-
-if [ -d "$PREFIX/test" ]; then
-    TEST_DIR="$PREFIX/test";
-elif [ -d "$PREFIX/misc/scala-test" ]; then
-    TEST_DIR="$PREFIX/misc/scala-test";
-else
-    abort "Test directory not found";
-fi;
-SOURCE_DIR=$TEST_DIR/files/cli
-OUTPUT_DIR=$TMP_DIR/classes
-API_DIR=$TMP_DIR/api
-
-DIFF="diff";
-RM="rm -f";
-TREE="tree";
-
-case `uname` in
-    CYGWIN* )
-        DIFF="diff --text --strip-trailing-cr";
-        ;;
-esac;
-
-DEBUG="";
-LANG="scala";
-SUFFIX=".scala";
-COMPILER="scalac";
-LEVEL="";
-while [ $# -gt 0 ]; do
-    case "$1" in
-        --debug    ) DEBUG="debug"; LEVEL="verbose"; shift 1;;
-        --quick    ) BIN_DIR="$QUICK"; shift 1;;
-        --installed) BIN_DIR=""; shift 1;;
-        --info     ) LEVEL="info"; shift 1;;
-        --javac    ) LANG="java"; SUFFIX=".java"; COMPILER="javac"; shift 1;;
-        --jikes    ) LANG="java"; SUFFIX=".java"; COMPILER="jikes"; shift 1;;
-        --jredir=* ) JRE_DIR=`expr "$1" : "--jredir=\(.*\)"`; shift 1;;
-        --objdir=* ) OUTPUT_DIR=`expr "$1" : "--objdir=\(.*\)"`; shift 1;;
-        --verbose  ) LEVEL="verbose"; shift 1;;
-        --help     ) test_print_help; exit 0;;
-        --version  ) test_print_version; exit 0;;
-        -*         ) abort "unknown option $1";;
-        *          ) test_add_file "$1"; shift 1;; #test_print_usage; exit 0;;
-    esac;
-done;
-
-if [ "$LANG" = "scala" ]; then
-    RUNTIME_COMMAND="${BIN_DIR}scala";
-    COMPILER_COMMAND="${BIN_DIR}$COMPILER";
-    INTERPRETER_COMMAND="${BIN_DIR}scala";
-    DOCGEN_COMMAND="${BIN_DIR}scaladoc";
-elif [ "$LANG" = "java" ]; then
-    RUNTIME_COMMAND=`which ${JAVACMD:=java}`
-    BIN_DIR=`dirname $RUNTIME_COMMAND`;
-    [ "$COMPILER" = "javac" ] && COMPILER_COMMAND=$BIN_DIR/$COMPILER;
-    [ "$COMPILER" = "jikes" ] && COMPILER_COMMAND=`which $COMPILER`;
-    DOCGEN_COMMAND=`dirname "$COMPILER_COMMAND"`/javadoc;
-else
-    abort "unknown language '$LANG'"
-fi
-[ -x "$COMPILER_COMMAND" ] || abort "Command $COMPILER_COMMAND not found";
-[ -x "$RUNTIME_COMMAND"  ] || abort "Command $RUNTIME_COMMAND not found";
-
-printf_initialization "${COLOR:-many}";
-
-printf_outline "Output directory is : $OUTPUT_DIR\\n";
-printf_outline "Compiler command is : $COMPILER_COMMAND\\n";
-printf_outline "Runtime command is  : $RUNTIME_COMMAND\\n";
-
-jvm_version=`${JAVACMD:=java} -version 2>&1 | head -3 | tail -1`
-printf_outline "Java runtime is     : $jvm_version\\n";
-if [ "$LANG" = "scala" ]; then
-    [ `echo "$jvm_version" | grep -c "J9"` = "1" ] && LANG="${LANG}_j9";
-elif [ "$LANG" = "java" ]; then
-    if [ "$COMPILER" = "jikes" ]; then
-         if [ "$LANG" = "java" ]; then
-             jre_home=`dirname $RUNTIME_COMMAND`/..;
-         elif [ -n "$JRE_DIR" ]; then
-             jre_home=$JRE_DIR;
-         else
-             abort "Jikes requires Sun JVM (use option '--jredir')";
-         fi;
-         cpath=`find $jre_home -name "rt.jar"`;
-         COMPILER_COMMAND="${COMPILER_COMMAND} -bootclasspath $cpath";
-    fi;
-    [ `echo "$jvm_version" | grep -c "1\.5"` = "1" ] && LANG="${LANG}5";
-    [ `echo "$jvm_version" | grep -c "1\.6"` = "1" ] && LANG="${LANG}6";
-    [ `echo "$jvm_version" | grep -c "J9"` = "1" ] && LANG="${LANG}_j9";
-fi
-
-if [ "$DEBUG" = "debug" ] ; then
-    LOG_FILE=/dev/tty
-else
-    LOG_FILE=${TMP_DIR}/${SCRIPT}.log
-fi
-DIFF_FILE=${TMP_DIR}/${SCRIPT}.diff
-TMP_FILE=${TMP_DIR}/${SCRIPT}.tmp
-
-##############################################################################
-
-if [ -z "$FILES" ]; then
-    FILES=`find "$SOURCE_DIR" -name "Main$SUFFIX" -a -type f -print`;
-fi;
-for testfile in "" $FILES; do
-    [ -z "$testfile" ] && continue;
-    checkfile=`dirname "$testfile"`/`basename "$testfile" "$SUFFIX"`.check
-    info=`awk '$1 ~ /^\/\//{i=index($0,"@info ");if(i>0){print substr($0,i+6)}}' "$testfile"`;
-    test_compile "$testfile" "$checkfile" "$info";
-    if [ "$?" = "0" ] ; then
-        scala_main=`echo "$testfile" | \
-            sed -e "s#${SOURCE_DIR}/\(.*\)\${SUFFIX}#\1#g" -e "s#\/#\.#g"`;
-        test_execute "$scala_main" "$checkfile";
-        test_interpret "$scala_main" "$checkfile";
-        test_docgen "$testfile" "$checkfile";
-    fi
-done;
-
-##############################################################################
-# Epilog
-
-$RM -r $TMP_DIR
-
-##############################################################################
diff --git a/test/files/jvm5/bug680.check b/test/debug/buildmanager/.gitignore
similarity index 100%
copy from test/files/jvm5/bug680.check
copy to test/debug/buildmanager/.gitignore
diff --git a/test/files/jvm5/bug680.check b/test/debug/jvm/.gitignore
similarity index 100%
copy from test/files/jvm5/bug680.check
copy to test/debug/jvm/.gitignore
diff --git a/test/files/jvm5/bug680.check b/test/debug/neg/.gitignore
similarity index 100%
copy from test/files/jvm5/bug680.check
copy to test/debug/neg/.gitignore
diff --git a/test/files/jvm5/bug680.check b/test/debug/pos/.gitignore
similarity index 100%
copy from test/files/jvm5/bug680.check
copy to test/debug/pos/.gitignore
diff --git a/test/files/jvm5/bug680.check b/test/debug/res/.gitignore
similarity index 100%
copy from test/files/jvm5/bug680.check
copy to test/debug/res/.gitignore
diff --git a/test/files/jvm5/bug680.check b/test/debug/run/.gitignore
similarity index 100%
copy from test/files/jvm5/bug680.check
copy to test/debug/run/.gitignore
diff --git a/test/files/jvm5/bug680.check b/test/debug/scalacheck/.gitignore
similarity index 100%
copy from test/files/jvm5/bug680.check
copy to test/debug/scalacheck/.gitignore
diff --git a/test/files/jvm5/bug680.check b/test/debug/scalap/.gitignore
similarity index 100%
copy from test/files/jvm5/bug680.check
copy to test/debug/scalap/.gitignore
diff --git a/test/files/jvm5/bug680.check b/test/debug/shootout/.gitignore
similarity index 100%
copy from test/files/jvm5/bug680.check
copy to test/debug/shootout/.gitignore
diff --git a/test/diff/diff.README b/test/diff/diff.README
deleted file mode 100644
index 839a1c2..0000000
--- a/test/diff/diff.README
+++ /dev/null
@@ -1,16 +0,0 @@
-DiffUtils for Windows 2.8.7
----------------------------
-
-DiffUtils shows differences between files.
-
-Source: http://gnuwin32.sourceforge.net/packages/diffutils.htm
-
-
-The minimal set of files required to run diff is the following:
-
-  bin\diff.exe (150528 bytes)
-  bin\libiconv2.dll (898048 bytes)
-  bin\libintl3.dll (92672 bytes)
-
-
-$Id: diff.README 7771 2006-06-12 13:22:39Z dubochet $
diff --git a/test/diff/diff.exe b/test/diff/diff.exe
deleted file mode 100644
index 85f370d..0000000
Binary files a/test/diff/diff.exe and /dev/null differ
diff --git a/test/diff/libiconv2.dll b/test/diff/libiconv2.dll
deleted file mode 100644
index 747073f..0000000
Binary files a/test/diff/libiconv2.dll and /dev/null differ
diff --git a/test/diff/libintl3.dll b/test/diff/libintl3.dll
deleted file mode 100644
index 2efd211..0000000
Binary files a/test/diff/libintl3.dll and /dev/null differ
diff --git a/test/disabled-windows/script/loadAndExecute.check b/test/disabled-windows/script/loadAndExecute.check
new file mode 100644
index 0000000..ccd8cd6
--- /dev/null
+++ b/test/disabled-windows/script/loadAndExecute.check
@@ -0,0 +1 @@
+List(hello, world)
diff --git a/test/disabled-windows/script/loadAndExecute/lAndE1.scala b/test/disabled-windows/script/loadAndExecute/lAndE1.scala
new file mode 100644
index 0000000..b20d1a9
--- /dev/null
+++ b/test/disabled-windows/script/loadAndExecute/lAndE1.scala
@@ -0,0 +1,3 @@
+object Bop {
+  implicit def int2list(x: Int): List[String] = List("hello", "world")
+}
\ No newline at end of file
diff --git a/test/disabled-windows/script/loadAndExecute/lAndE2.scala b/test/disabled-windows/script/loadAndExecute/lAndE2.scala
new file mode 100644
index 0000000..ea15a04
--- /dev/null
+++ b/test/disabled-windows/script/loadAndExecute/lAndE2.scala
@@ -0,0 +1 @@
+import Bop._
diff --git a/test/disabled-windows/script/loadAndExecute/loadAndExecute.scala b/test/disabled-windows/script/loadAndExecute/loadAndExecute.scala
new file mode 100644
index 0000000..2a97183
--- /dev/null
+++ b/test/disabled-windows/script/loadAndExecute/loadAndExecute.scala
@@ -0,0 +1,3 @@
+#!/bin/sh
+
+scala -nocompdaemon -i lAndE1.scala lAndE2.scala -e 'println(5: List[String])'
diff --git a/test/files/script/utf8.bat b/test/disabled-windows/script/utf8.bat
similarity index 100%
rename from test/files/script/utf8.bat
rename to test/disabled-windows/script/utf8.bat
diff --git a/test/files/script/utf8.check b/test/disabled-windows/script/utf8.check
similarity index 100%
rename from test/files/script/utf8.check
rename to test/disabled-windows/script/utf8.check
diff --git a/test/disabled-windows/script/utf8.scala b/test/disabled-windows/script/utf8.scala
new file mode 100644
index 0000000..5dfade0
--- /dev/null
+++ b/test/disabled-windows/script/utf8.scala
@@ -0,0 +1,26 @@
+#!/bin/sh
+# 
+# Checks if UTF-8 output makes it through unmangled.
+
+cygwin=false;
+case "`uname`" in
+    CYGWIN*) cygwin=true ;;
+esac
+
+SOURCE="$0";
+if $cygwin; then
+    if [ "$OS" = "Windows_NT" ] && cygpath -m .>/dev/null 2>/dev/null ; 
+then
+        format=mixed
+    else
+        format=windows
+    fi
+    SOURCE=`cygpath --$format "$SOURCE"`;
+fi
+
+exec scala -Dfile.encoding="UTF-8" -nocompdaemon "$SOURCE" "$@"
+!#
+
+/*Comment Комментарий*/
+Console.println("QWERTY");
+Console.println("ЙЦУКЕН");
diff --git a/test/disabled/buildmanager/t2651_1/A.scala b/test/disabled/buildmanager/t2651_1/A.scala
new file mode 100644
index 0000000..d712f6f
--- /dev/null
+++ b/test/disabled/buildmanager/t2651_1/A.scala
@@ -0,0 +1 @@
+trait A[T]
diff --git a/test/disabled/buildmanager/t2651_1/B.scala b/test/disabled/buildmanager/t2651_1/B.scala
new file mode 100644
index 0000000..a8aca3d
--- /dev/null
+++ b/test/disabled/buildmanager/t2651_1/B.scala
@@ -0,0 +1,2 @@
+trait B[T] extends A[T]
+
diff --git a/test/disabled/buildmanager/t2651_1/C.scala b/test/disabled/buildmanager/t2651_1/C.scala
new file mode 100644
index 0000000..690dcf5
--- /dev/null
+++ b/test/disabled/buildmanager/t2651_1/C.scala
@@ -0,0 +1,3 @@
+object C {
+	new A[Int] {}
+}
diff --git a/test/disabled/buildmanager/t2651_1/D.scala b/test/disabled/buildmanager/t2651_1/D.scala
new file mode 100644
index 0000000..51273ad
--- /dev/null
+++ b/test/disabled/buildmanager/t2651_1/D.scala
@@ -0,0 +1,3 @@
+object D {
+	def x[T](a: A[T]) = a
+}
diff --git a/test/disabled/buildmanager/t2651_1/t2651_1.changes/A2.scala b/test/disabled/buildmanager/t2651_1/t2651_1.changes/A2.scala
new file mode 100644
index 0000000..574b522
--- /dev/null
+++ b/test/disabled/buildmanager/t2651_1/t2651_1.changes/A2.scala
@@ -0,0 +1,2 @@
+trait A
+
diff --git a/test/disabled/buildmanager/t2651_1/t2651_1.check b/test/disabled/buildmanager/t2651_1/t2651_1.check
new file mode 100644
index 0000000..8d2cbc8
--- /dev/null
+++ b/test/disabled/buildmanager/t2651_1/t2651_1.check
@@ -0,0 +1,19 @@
+builder > A.scala B.scala C.scala D.scala
+compiling Set(A.scala, B.scala, C.scala, D.scala)
+Changes: Map()
+builder > A.scala
+compiling Set(A.scala)
+Changes: Map(trait A -> List(Changed(Class(A))[ tparams: List()]))
+invalidate B.scala because parents have changed [Changed(Class(A))[ tparams: List()]]
+invalidate C.scala because parents have changed [Changed(Class(A))[ tparams: List()]]
+invalidate D.scala because it references changed class [Changed(Class(A))[ tparams: List()]]
+compiling Set(B.scala, C.scala, D.scala)
+B.scala:1: error: A does not take type parameters
+trait B[T] extends A[T]
+                   ^
+C.scala:2: error: A does not take type parameters
+	new A[Int] {}
+            ^
+D.scala:2: error: A does not take type parameters
+	def x[T](a: A[T]) = a
+                    ^
diff --git a/test/disabled/buildmanager/t2651_1/t2651_1.test b/test/disabled/buildmanager/t2651_1/t2651_1.test
new file mode 100644
index 0000000..4f67d5e
--- /dev/null
+++ b/test/disabled/buildmanager/t2651_1/t2651_1.test
@@ -0,0 +1,3 @@
+>>compile A.scala B.scala C.scala D.scala
+>>update A.scala=>A2.scala
+>>compile A.scala
diff --git a/test/disabled/lib/annotations.jar b/test/disabled/lib/annotations.jar
new file mode 100644
index 0000000..59fa4b7
Binary files /dev/null and b/test/disabled/lib/annotations.jar differ
diff --git a/test/disabled/lib/enums.jar b/test/disabled/lib/enums.jar
new file mode 100644
index 0000000..f661d13
Binary files /dev/null and b/test/disabled/lib/enums.jar differ
diff --git a/test/disabled/lib/genericNest.jar b/test/disabled/lib/genericNest.jar
new file mode 100644
index 0000000..bc08c1e
Binary files /dev/null and b/test/disabled/lib/genericNest.jar differ
diff --git a/test/disabled/lib/methvsfield.jar b/test/disabled/lib/methvsfield.jar
new file mode 100644
index 0000000..f266071
Binary files /dev/null and b/test/disabled/lib/methvsfield.jar differ
diff --git a/test/disabled/lib/nest.jar b/test/disabled/lib/nest.jar
new file mode 100644
index 0000000..4eda4be
Binary files /dev/null and b/test/disabled/lib/nest.jar differ
diff --git a/test/disabled/lib/scalacheck.jar b/test/disabled/lib/scalacheck.jar
new file mode 100644
index 0000000..be3243a
Binary files /dev/null and b/test/disabled/lib/scalacheck.jar differ
diff --git a/test/disabled/pos/bug2919.scala b/test/disabled/pos/bug2919.scala
new file mode 100644
index 0000000..5e51cf9
--- /dev/null
+++ b/test/disabled/pos/bug2919.scala
@@ -0,0 +1,12 @@
+import javax.xml.bind.annotation.adapters.XmlAdapter
+import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter
+
+case class Link(
+  @XmlJavaTypeAdapter(classOf[StringOptionAdapter]) val title: Option[String]
+)
+
+class StringOptionAdapter extends XmlAdapter[String, Option[String]] {
+  def unmarshal(str: String) = error("stub")
+  def marshal(op: Option[String]) = error("Stub")
+}
+
diff --git a/test/disabled/pos/spec-traits.scala b/test/disabled/pos/spec-traits.scala
new file mode 100644
index 0000000..49a59d5
--- /dev/null
+++ b/test/disabled/pos/spec-traits.scala
@@ -0,0 +1,83 @@
+trait A[@specialized(Int) T] { def foo: T }
+class B extends A[Int] { val foo = 10 }
+class C extends B
+
+// issue 3309
+class Lazy {
+  def test[U](block: => U): Unit = { block }
+
+  test { lazy val x = 1 }
+}
+
+// issue 3307
+class Bug3307 {
+  def f[Z](block: String => Z) { 
+    block("abc") 
+  }
+  
+  ({ () => 
+    f { implicit x => println(x) } })() 
+}
+
+// issue 3301
+  trait T[X]
+
+class Bug3301 {
+  def t[A]: T[A] = error("stub")
+
+  () => {
+    type X = Int
+
+    def foo[X] = t[X]
+    ()
+  }
+}
+// issue 3299
+object Failure {
+  def thunk() {
+    for (i <- 1 to 2) {
+      val Array(a, b) = Array(1,2)
+      ()
+    }
+  }
+}
+
+// issue 3296
+
+object AA
+{
+    def f(block: => Unit) {}
+
+    object BB
+    {
+        f {
+            object CC
+
+            ()
+        }
+    }
+
+  def foo[T](x: T) = { object A; false }
+}
+
+// issue 3292
+import scala.swing._
+import scala.swing.GridBagPanel._
+
+object Grid {
+
+  def later(code : => Unit) =
+    javax.swing.SwingUtilities.invokeLater(new Runnable { def run { code }})
+
+  def test = later {
+    val frame = new Dialog {
+      contents = new GridBagPanel {
+        val c = new Constraints
+      }
+    }
+  }
+
+}
+
+// issue 3325
+object O { def f[@specialized T] { for(k <- Nil: List[T]) { } } }
diff --git a/test/files/run/docgenerator.check b/test/disabled/run/docgenerator.check
similarity index 100%
rename from test/files/run/docgenerator.check
rename to test/disabled/run/docgenerator.check
diff --git a/test/disabled/run/docgenerator.scala b/test/disabled/run/docgenerator.scala
new file mode 100644
index 0000000..8e0c758
--- /dev/null
+++ b/test/disabled/run/docgenerator.scala
@@ -0,0 +1,295 @@
+object Test {
+  import java.io.{File, FileReader, FileWriter}
+
+  /** Tests the generation of the HTML documentation for some Scala
+   *  code samples (see value 'code' below) with different scaladoc
+   *  options (currently -access:<value>).
+   *
+   *  @author Stephane Micheloud
+   */
+  def main(args: Array[String]) {
+    // overwrites value of UrlContext.generator in file DocUtil.scala
+    System.setProperty("doc.generator", "scaladoc")
+    var dirname = System.getProperty("partest.output")
+    if (dirname eq null) dirname = System.getProperty("java.io.tmpdir")
+    val tmpDir = new File(dirname)
+    tmpDir.mkdirs()
+    test1(tmpDir)
+    test2(tmpDir)
+  }
+
+  private def test1(tmpDir: File) {
+    def testOptions(inFile: File, outDirName: String, opts: String*) {
+      val outDir = createDir(tmpDir, outDirName)
+      val args = Array.concat(Array("-d", outDir.getPath, inFile.getPath), opts.toArray:Array[String])
+      if (MainDoc.main0(args)) {
+        for (name <- List("all-classes.html", "index.html")) {
+          val outFile = new File(outDir, name)
+          val n = outFile.length.toInt
+          val in = new FileReader(outFile)
+          val cbuf = new Array[Char](n)
+          in.read(cbuf, 0, n)
+          println(new String(cbuf))
+        }
+        println
+      }
+    }
+    val inFile = {
+      val f = new File(tmpDir.getPath, "docgenerator1.scala")
+      val writer = new FileWriter(f)
+      writer.write(code1, 0, code1.length)
+      writer.close
+      f
+    }
+    testOptions(inFile, "test1", "") // none (default is -access:protected)
+    testOptions(inFile, "test2", "-access:public")
+    testOptions(inFile, "test3", "-access:protected")
+    testOptions(inFile, "test4", "-access:private")
+  }
+
+  private def test2(tmpDir: File) {
+    val code ="""
+package annots
+
+ at deprecated("msg")
+object Foo { val x = 0 }
+
+ at deprecated("msg")
+class Bar { val x = 1 }
+
+object Foo1 {
+  @deprecated("msg")
+  object Foo11 { val x = 3 }
+}
+
+class Bar1 {
+  @deprecated("msg")
+  object Foo11 { val x = 2 }
+}
+
+class Bar2 {
+  def bar {
+    @deprecated("msg")
+    object Foo21 { val x = 4 }
+    ()
+  }
+}
+
+object Foo2 {
+  def foo {
+    @deprecated("msg")
+    object Foo21 { val x = 5 }
+    ()
+  }
+}
+"""
+    val inFile = {
+      val f = new File(tmpDir.getPath, "docgenerator2.scala")
+      val writer = new FileWriter(f)
+      writer.write(code, 0, code.length)
+      writer.close
+      f
+    }
+    val outDir = createDir(tmpDir, "annots1")
+    val args = Array.concat(Array("-d", outDir.getPath, inFile.getPath))
+    if (MainDoc.main0(args)) {
+      for (name <- List("all-classes.html", "index.html")) {
+        val outFile = new File(outDir, name)
+        val n = outFile.length.toInt
+        val in = new FileReader(outFile)
+        val cbuf = new Array[Char](n)
+        in.read(cbuf, 0, n)
+        println(new String(cbuf))
+      }
+      println
+    }
+  }
+
+  object MainDoc {
+    import scala.tools.nsc._
+    import scala.tools.nsc.doc.DefaultDocDriver
+    import scala.tools.nsc.reporters.ConsoleReporter
+    def error(msg: String) { Console.err.println(msg) }
+    var reporter: ConsoleReporter = _
+    def process(args: Array[String]) {
+      val docSettings = new scala.tools.nsc.doc.Settings(error)
+      // when running that compiler, give it a scala-library to the classpath
+      docSettings.classpath.value = System.getProperty("java.class.path")
+      reporter = new ConsoleReporter(docSettings)
+      val command = new CompilerCommand(args.toList, docSettings)
+      try {
+        object compiler extends Global(command.settings, reporter) {
+	  override protected def computeInternalPhases() : Unit = {
+	    phasesSet += syntaxAnalyzer
+	    phasesSet += analyzer.namerFactory
+	    phasesSet += analyzer.typerFactory
+	  }
+	  override def onlyPresentation = true
+	}
+        if (reporter.hasErrors) {
+          reporter.flush()
+          return
+        }
+        val run = new compiler.Run
+        run compile command.files
+        object generator extends DefaultDocDriver {
+          lazy val global: compiler.type = compiler
+          lazy val settings = docSettings
+        }
+        generator process run.units
+        reporter.printSummary()
+      } catch {
+        case ex @ FatalError(msg) =>
+          if (command.settings.debug.value)
+            ex.printStackTrace();
+        reporter.error(null, "fatal error: " + msg)
+      }
+    }
+    def main(args: Array[String]) {
+      process(args)
+      exit(if (reporter.hasErrors) 1 else 0)
+    }
+    // main returning a status (no exit code)
+    def main0(args: Array[String]): Boolean = {
+      process(args)
+      !reporter.hasErrors
+    }
+  }
+
+  private def createDir(parent: File, dirname: String): File = {
+    val outDir = new File(parent, dirname)
+    outDir.mkdir
+    outDir
+  }
+
+  private val code1 = """
+package examples
+
+abstract class C0 {
+  def foo_public
+  protected def foo_protected
+  private def foo_private {}
+  class C1_Public {
+    val x_public = ()
+    protected val x_protected = ()
+    private val x_private = ()
+  }
+  protected class C1_Protected {
+    val x_public = ()
+    protected val x_protected = ()
+    private val x_private = ()
+  }
+  private class C1_Private {
+    val x_public = ()
+    protected val x_protected = ()
+    private val x_private = ()
+  }
+}
+
+protected abstract class C0_Protected {
+  def foo_public
+  protected def foo_protected
+  private def foo_private {}
+  class C1_Public {
+    val x_public = ()
+    protected val x_protected = ()
+    private val x_private = ()
+  }
+  protected class C1_Protected {
+    val x_public = ()
+    protected val x_protected = ()
+    private val x_private = ()
+  }
+  private class C1_Private {
+    val x_public = ()
+    protected val x_protected = ()
+    private val x_private = ()
+  }
+}
+
+private abstract class C0_Private {
+  def foo_public
+  protected def foo_protected
+  private def foo_private {}
+  class C1_Public {
+    val x_public = ()
+    protected val x_protected = ()
+    private val x_private = ()
+  }
+  protected class C1_Protected {
+    val x_public = ()
+    protected val x_protected = ()
+    private val x_private = ()
+  }
+  private class C1_Private {
+    val x_public = ()
+    protected val x_protected = ()
+    private val x_private = ()
+  }
+}
+
+
+object obj0 {
+  def bar_public {}
+  protected def bar_protected {}
+  private def bar_private {}
+  object obj1_Public {
+    val x_public = ()
+    protected val x_protected = ()
+    private val x_private = ()
+  }
+  protected object obj1_Protected {
+    val x_public = ()
+    protected val x_protected = ()
+    private val x_private = ()
+  }
+  private object obj1_Private {
+    val x_public = ()
+    protected val x_protected = ()
+    private val x_private = ()
+  }
+}
+
+protected object obj0_Protected {
+  def bar_public {}
+  protected def bar_protected {}
+  private def bar_private {}
+  object obj1_Public {
+    val x_public = ()
+    protected val x_protected = ()
+    private val x_private = ()
+  }
+  protected object obj1_Protected {
+    val x_public = ()
+    protected val x_protected = ()
+    private val x_private = ()
+  }
+  private object obj1_Private {
+    val x_public = ()
+    protected val x_protected = ()
+    private val x_private = ()
+  }
+}
+
+private object obj0_Private {
+  def bar_public {}
+  protected def bar_protected {}
+  private def bar_private {}
+  object obj1_Public {
+    val x_public = ()
+    protected val x_protected = ()
+    private val x_private = ()
+  }
+  protected object obj1_Protected {
+    val x_public = ()
+    protected val x_protected = ()
+    private val x_private = ()
+  }
+  private object obj1_Private {
+    val x_public = ()
+    protected val x_protected = ()
+    private val x_private = ()
+  }
+}
+"""
+}
diff --git a/test/disabled/run/script-positions.scala b/test/disabled/run/script-positions.scala
new file mode 100644
index 0000000..2c80d55
--- /dev/null
+++ b/test/disabled/run/script-positions.scala
@@ -0,0 +1,86 @@
+import scala.tools.nsc._
+import util.stringFromStream
+
+// Testing "scripts" without the platform delights which accompany actual scripts.
+object Scripts {
+
+  val test1 = 
+"""#!/bin/sh 
+  exec scala $0 $@ 
+!#
+
+println("statement 1")
+println("statement 2".thisisborked)
+println("statement 3")
+"""
+
+  val output1 =
+"""thisisborked.scala:6: error: value thisisborked is not a member of java.lang.String
+println("statement 2".thisisborked)
+                      ^
+one error found"""
+  val test2 =
+"""#!scala
+// foo
+// bar
+!#
+
+val x = "line 6"
+val y = "line 7"
+val z "line 8""""
+
+  val output2 = 
+"""bob.scala:8: error: '=' expected but string literal found.
+val z "line 8"
+      ^
+bob.scala:8: error: illegal start of simple expression
+val z "line 8"
+             ^
+two errors found"""
+}
+
+object Test {
+  import Scripts._
+  
+  def settings = new GenericRunnerSettings(println _)
+  settings.nocompdaemon.value = true
+  
+  def runScript(code: String): String =
+    stringFromStream(stream =>
+      Console.withOut(stream) {
+        Console.withErr(stream) {
+          ScriptRunner.runCommand(settings, code, Nil)
+        }
+      }
+    )
+  
+  val tests: List[(String, String)] = List(
+    test1 -> output1,
+    test2 -> output2
+  )
+  // def lines(s: String) = s split """\r\n|\r|\n""" toList
+  def lines(s: String) = s split "\\n" toList
+
+  // strip the random temp filename from error msgs
+  def stripFilename(s: String) = (s indexOf ".scala:") match {
+    case -1   => s
+    case idx  => s drop (idx + 7)
+  }
+  def toLines(text: String) = lines(text) map stripFilename
+  
+  def main(args: Array[String]): Unit = {
+    for ((code, expected) <- tests) {      
+      val out = toLines(runScript(code))
+      val exp = toLines(expected)
+      val nomatch = out zip exp filter { case (x, y) => x != y }
+      val success = out.size == exp.size && nomatch.isEmpty
+      
+      assert(
+        success,
+        "Output doesn't match expected:\n" +
+        "Expected:\n" + expected +
+        "Actual:\n" + out.mkString("\n")
+      )
+    }
+  }
+}
diff --git a/test/disabled/run/t2946/Parsers.scala b/test/disabled/run/t2946/Parsers.scala
new file mode 100644
index 0000000..c096103
--- /dev/null
+++ b/test/disabled/run/t2946/Parsers.scala
@@ -0,0 +1,4 @@
+class Parser {
+  def parse(t: Any): Unit = {
+  }
+}
diff --git a/test/disabled/run/t2946/ResponseCommon.scala b/test/disabled/run/t2946/ResponseCommon.scala
new file mode 100644
index 0000000..fa9d8ac
--- /dev/null
+++ b/test/disabled/run/t2946/ResponseCommon.scala
@@ -0,0 +1,14 @@
+trait ResponseCommon extends Parser {
+  private[this] var paramsParser: Parser = null
+  def withParamsParser(parser: Parser) = {paramsParser = parser; this}
+
+  class Foo {
+    println(paramsParser)
+  }
+
+  override abstract def parse(t: Any): Unit = t match {
+    case ("params", value: List[_]) => value.foreach {paramsParser.parse(_)}
+    case _ => super.parse(t)
+  }
+}
+
diff --git a/test/disabled/run/t2946/Test.scala b/test/disabled/run/t2946/Test.scala
new file mode 100644
index 0000000..e9d9896
--- /dev/null
+++ b/test/disabled/run/t2946/Test.scala
@@ -0,0 +1,7 @@
+class Test extends Parser with ResponseCommon
+
+object Test {
+  def main(args: Array[String]) {
+    new Test
+  }
+}
diff --git a/test/disabled/scalacheck/redblack.scala b/test/disabled/scalacheck/redblack.scala
new file mode 100644
index 0000000..301d332
--- /dev/null
+++ b/test/disabled/scalacheck/redblack.scala
@@ -0,0 +1,157 @@
+import org.scalacheck._
+import Prop._
+import Gen._
+
+/*
+Properties of a Red & Black Tree:
+
+A node is either red or black.
+The root is black. (This rule is used in some definitions and not others. Since the
+root can always be changed from red to black but not necessarily vice-versa this 
+rule has little effect on analysis.)
+All leaves are black.
+Both children of every red node are black.
+Every simple path from a given node to any of its descendant leaves contains the same number of black nodes.
+*/
+
+abstract class RedBlackTest extends Properties("RedBlack") {
+  object RedBlackTest extends scala.collection.immutable.RedBlack[Int] {
+    def isSmaller(x: Int, y: Int) = x < y
+  }
+  
+  import RedBlackTest._
+  
+  def rootIsBlack[A](t: Tree[A]) = t.isBlack
+  
+  def areAllLeavesBlack[A](t: Tree[A]): Boolean = t match {
+    case Empty => t.isBlack
+    case ne: NonEmpty[_] => List(ne.left, ne.right) forall areAllLeavesBlack
+  }
+  
+  def areRedNodeChildrenBlack[A](t: Tree[A]): Boolean = t match {
+    case RedTree(_, _, left, right) => List(left, right) forall (t => t.isBlack && areRedNodeChildrenBlack(t)) 
+    case BlackTree(_, _, left, right) => List(left, right) forall areRedNodeChildrenBlack
+    case Empty => true
+  }
+  
+  def blackNodesToLeaves[A](t: Tree[A]): List[Int] = t match {
+    case Empty => List(1)
+    case BlackTree(_, _, left, right) => List(left, right) flatMap blackNodesToLeaves map (_ + 1)
+    case RedTree(_, _, left, right) => List(left, right) flatMap blackNodesToLeaves
+  }
+  
+  def areBlackNodesToLeavesEqual[A](t: Tree[A]): Boolean = t match {
+    case Empty => true
+    case ne: NonEmpty[_] => 
+      (
+        blackNodesToLeaves(ne).removeDuplicates.size == 1 
+        && areBlackNodesToLeavesEqual(ne.left) 
+        && areBlackNodesToLeavesEqual(ne.right)
+      )
+  }
+  
+  def orderIsPreserved[A](t: Tree[A]): Boolean = t match {
+    case Empty => true
+    case ne: NonEmpty[_] =>
+      (
+        (ne.left.iterator map (_._1) forall (isSmaller(_, ne.key)))
+        && (ne.right.iterator map (_._1) forall (isSmaller(ne.key, _)))
+        && (List(ne.left, ne.right) forall orderIsPreserved)
+      )
+  }
+  
+  def setup(l: List[Int], invariant: Tree[Unit] => Boolean): (Boolean, Tree[Unit])
+
+  def listNoRepetitions(size: Int) = for {
+    s <- Gen.choose(1, size)
+    l <- Gen.listOfN(size, Gen.choose(0, Int.MaxValue)) suchThat (l => l.size == l.removeDuplicates.size)
+  } yield l 
+  def listFewRepetitions(size: Int) = for {
+    s <- Gen.choose(1, size)
+    l <- Gen.listOfN(s, Gen.choose(0, size * 4)) suchThat (l => l.size != l.removeDuplicates.size)
+  } yield l
+  def listManyRepetitions(size: Int) =  for {
+    s <- Gen.choose(1, size)
+    l <- Gen.listOfN(s, Gen.choose(0, size)) suchThat (l => l.size != l.removeDuplicates.size)
+  } yield l
+  def listEvenRepetitions(size: Int) = listFewRepetitions(size) map (x => 
+    scala.util.Random.shuffle(x zip x flatMap { case (a, b) => List(a, b) })
+  )
+  
+  // Arbitrarily weighted list distribution types
+  val seqType: Gen[Int => Gen[List[Int]]]
+  
+  def myGen(sized: Int) = for {
+    size <- Gen.choose(0, sized)
+    seq <- seqType
+    list <- seq(size)
+  } yield list
+  
+  property("root is black") = forAll(myGen(10)) { l => 
+    setup(l, rootIsBlack)._1 :| setup(l, rootIsBlack)._2.toString
+  }
+  property("all leaves are black") = forAll(myGen(50)) { l => 
+    setup(l, areAllLeavesBlack)._1 :| setup(l, areAllLeavesBlack)._2.toString
+  }
+  property("children of red nodes are black") = forAll(myGen(50)) { l => 
+    setup(l, areRedNodeChildrenBlack)._1 :| setup(l, areRedNodeChildrenBlack)._2.toString
+  }
+  property("Every path from a node to its descendant leaves contains the same number of black nodes") = forAll(myGen(50)) { l => 
+    setup(l, areBlackNodesToLeavesEqual)._1 :| setup(l, areBlackNodesToLeavesEqual)._2.toString
+  }
+  property("Ordering of keys is preserved") = forAll(myGen(50)) { l =>
+    setup(l, orderIsPreserved)._1 :| setup(l, orderIsPreserved)._2.toString
+  }
+}
+
+object TestInsertion extends RedBlackTest {
+  import RedBlackTest._
+  override val seqType = Gen.frequency(
+    (1, listNoRepetitions _),
+    (1, listManyRepetitions _)
+  )
+
+  property("update adds elements") = forAll(myGen(50)) { l =>
+    val tree = l.foldLeft(Empty: Tree[Unit])((acc, n) => acc update (n, ()))
+    forAll(Gen.pick(1, l)) ( n => !(tree lookup n.head isEmpty) :| "Tree: "+tree+" N: "+n.head )
+  }
+
+  override def setup(l: List[Int], invariant: Tree[Unit] => Boolean) = l.foldLeft((true, Empty: Tree[Unit])) { 
+    case ((true, acc), n) => 
+      val newRoot = acc update (n, ())
+      (invariant(newRoot), newRoot)
+    case (failed, _) => failed
+  }
+}
+
+object TestDeletion extends RedBlackTest {
+  import RedBlackTest._
+  override val seqType = Gen.frequency(
+    (2, listFewRepetitions _),
+    (3, listManyRepetitions _),
+    (1, listEvenRepetitions _)
+  )
+  
+  property("delete removes elements") = forAll(myGen(50)) { l =>
+    val tree = l.foldLeft(Empty: Tree[Unit])((acc, n) => acc update (n, ()))
+    forAll(Gen.choose(1, l.size)) { numberOfElementsToRemove =>
+      forAll(Gen.pick(numberOfElementsToRemove, l)) { elementsToRemove =>
+        val newTree = elementsToRemove.foldLeft(tree)((acc, n) => acc delete n)
+        (elementsToRemove forall (n => newTree lookup n isEmpty)) :| "Tree: "+tree+"New Tree: "+newTree+" Elements to Remove: "+elementsToRemove 
+      }
+    }
+  }
+  
+  override def setup(l: List[Int], invariant: Tree[Unit] => Boolean) = l.foldLeft((true, Empty: Tree[Unit])) { 
+    case ((true, acc), n) => 
+      val newRoot = if (acc lookup n isEmpty) acc update (n, ()) else acc delete n
+      (invariant(newRoot), newRoot)
+    case (failed, _) => failed
+  }
+}
+
+object Test extends Properties("RedBlack") {
+  include(TestInsertion)
+  include(TestDeletion)
+}
+
diff --git a/test/files/ant/fsc-build.xml b/test/files/ant/fsc-build.xml
index 07d9a9e..9323be1 100644
--- a/test/files/ant/fsc-build.xml
+++ b/test/files/ant/fsc-build.xml
@@ -1,5 +1,4 @@
 <?xml version="1.0" encoding="UTF-8"?>
-<!-- $Id: fsc-build.xml 10669 2007-04-12 13:41:27Z michelou $ -->
 
 <project name="fsc" default="run" basedir=".">
 
diff --git a/test/files/ant/imported.xml b/test/files/ant/imported.xml
index d57967a..9e2a3ff 100644
--- a/test/files/ant/imported.xml
+++ b/test/files/ant/imported.xml
@@ -1,5 +1,4 @@
 <?xml version="1.0" encoding="UTF-8"?>
-<!-- $Id: imported.xml 10669 2007-04-12 13:41:27Z michelou $ -->
 
 <project name="imported" default="run" basedir=".">
 
diff --git a/test/files/ant/scalac-build.xml b/test/files/ant/scalac-build.xml
index acff214..0276124 100644
--- a/test/files/ant/scalac-build.xml
+++ b/test/files/ant/scalac-build.xml
@@ -1,5 +1,4 @@
 <?xml version="1.0" encoding="UTF-8"?>
-<!-- $Id: scalac-build.xml 10669 2007-04-12 13:41:27Z michelou $ -->
 
 <project name="scalac" default="run" basedir=".">
 
diff --git a/test/files/ant/scaladoc-build.xml b/test/files/ant/scaladoc-build.xml
index e854af7..839c7bd 100644
--- a/test/files/ant/scaladoc-build.xml
+++ b/test/files/ant/scaladoc-build.xml
@@ -1,5 +1,4 @@
 <?xml version="1.0" encoding="UTF-8"?>
-<!-- $Id: $ -->
 
 <project name="scaladoc" default="run" basedir=".">
 
diff --git a/test/files/bench/equality/eq.scala b/test/files/bench/equality/eq.scala
new file mode 100644
index 0000000..4e57a81
--- /dev/null
+++ b/test/files/bench/equality/eq.scala
@@ -0,0 +1,34 @@
+object eq extends testing.Benchmark {
+
+  def eqtest[T](creator: Int => T, n: Int): Int = {
+    val elems = Array.tabulate[AnyRef](n)(i => creator(i % 2).asInstanceOf[AnyRef])
+
+    var sum = 0
+    var i = 0
+    while (i < n) {
+      var j = 0
+      while (j < n) {
+        if (elems(i) eq elems(j)) sum += 1
+        j += 1
+      }
+      i += 1
+    }
+    sum
+  }
+
+  val obj1 = new Object
+  val obj2 = new Object
+
+  def run() {
+    var sum = 0
+    sum += eqtest(x => if (x == 0) obj1 else obj2, 2000)
+    sum += eqtest(x => x, 1000)
+    sum += eqtest(x => x.toChar, 550)
+    sum += eqtest(x => x.toByte, 550)
+    sum += eqtest(x => x.toLong, 550)
+    sum += eqtest(x => x.toShort, 100)
+    sum += eqtest(x => x.toFloat, 100)
+    sum += eqtest(x => x.toDouble, 100)
+    assert(sum == 2958950)
+  }
+}
diff --git a/test/files/bench/equality/eqeq.eqlog b/test/files/bench/equality/eqeq.eqlog
new file mode 100644
index 0000000..d1e27ac
--- /dev/null
+++ b/test/files/bench/equality/eqeq.eqlog
@@ -0,0 +1,42 @@
+Banchmark results for testing equality operations:
+eq.scala: Base case, use eq equality only
+eqeq.scala: Test case, use == instead of eq.
+All tests run on Thinkpad T400, 1.6.0_12 client VM.
+Test command: java eq 5 5
+              java eqeq 5 5
+eq.scala, no -optimise
+eq$		109		78		79		63		63
+eq$		94		63		63		78		78
+eq$		94		62		62		62		78
+eq$		94		78		78		78		78
+eq$		94		78		78		78		78
+eq.scala, with -optimise
+eq$		421		63		62		47		63
+eq$		406		62		62		63		62
+eq$		407		62		62		78		63
+eq$		406		63		63		62		62
+eq$		407		62		62		63		47
+eqeq.scala with version of BoxesRuntime as of Nov 13th, no -optimise
+eqeq$		562		516		516		516		515
+eqeq$		547		515		515		531		532
+eqeq$		532		516		516		515		516
+eqeq$		547		531		531		516		531
+eqeq$		547		515		515		516		516
+eqeq.scala with version of BoxesRuntime as of Nov 13th, with -optimise
+eqeq$		1031		390		391		391		391
+eqeq$		1031		391		391		391		390
+eqeq$		1031		390		390		391		391
+eqeq$		1031		406		407		391		390
+eqeq$		1031		390		390		391		391
+eqeq.scala with 1st optimized of Nov 14th, no -optimise
+eqeq$		484		421		438		438		437
+eqeq$		484		438		437		437		438
+eqeq$		469		437		453		454		438
+eqeq$		468		437		438		468		438
+eqeq$		485		437		437		422		438
+eqeq.scala with 1st optimized of Nov 14th, with -optimise
+eqeq$		1016		375		391		375		375
+eqeq$		1016		375		391		390		375
+eqeq$		1016		390		391		375		375
+eqeq$		1015		375		391		390		375
+eqeq$		1016		390		375		375		375
diff --git a/test/files/bench/equality/eqeq.scala b/test/files/bench/equality/eqeq.scala
new file mode 100644
index 0000000..e1fda69
--- /dev/null
+++ b/test/files/bench/equality/eqeq.scala
@@ -0,0 +1,46 @@
+/** benchmark for testing equality.
+ *  Mix: == between non-numbers ith Object.equals as equality: 66%
+ *          50% of these are tests where eq is true.
+ *       == between boxed integers: 17%
+ *       == between boxed characters: 5%
+ *       == between boxed bytes: 5%
+ *       == between boxed longs: 5%
+ *       == between boxed shorts: < 1%
+ *       == between boxed floats: < 1%
+ *       == between boxed doubles: < 1%
+ * In all cases 50% of the tests return true.
+ */
+object eqeq extends testing.Benchmark {
+
+  def eqeqtest[T](creator: Int => T, n: Int): Int = {
+    val elems = Array.tabulate[AnyRef](n)(i => creator(i % 2).asInstanceOf[AnyRef])
+
+    var sum = 0
+    var i = 0
+    while (i < n) {
+      var j = 0
+      while (j < n) {
+        if (elems(i) == elems(j)) sum += 1
+        j += 1
+      }
+      i += 1
+    }
+    sum
+  }
+
+  val obj1 = new Object
+  val obj2 = new Object
+
+  def run() {
+    var sum = 0
+    sum += eqeqtest(x => if (x == 0) obj1 else obj2, 2000)
+    sum += eqeqtest(x => x, 1000)
+    sum += eqeqtest(x => x.toChar, 550)
+    sum += eqeqtest(x => x.toByte, 550)
+    sum += eqeqtest(x => x.toLong, 550)
+    sum += eqeqtest(x => x.toShort, 100)
+    sum += eqeqtest(x => x.toFloat, 100)
+    sum += eqeqtest(x => x.toDouble, 100)
+    assert(sum == 2968750)
+  }
+}
diff --git a/test/files/buildmanager/annotated/A.scala b/test/files/buildmanager/annotated/A.scala
new file mode 100644
index 0000000..4130cf2
--- /dev/null
+++ b/test/files/buildmanager/annotated/A.scala
@@ -0,0 +1 @@
+case class A[T](x: String, y: T)
diff --git a/test/files/buildmanager/annotated/annotated.check b/test/files/buildmanager/annotated/annotated.check
new file mode 100644
index 0000000..ce92c9a
--- /dev/null
+++ b/test/files/buildmanager/annotated/annotated.check
@@ -0,0 +1,6 @@
+builder > A.scala
+compiling Set(A.scala)
+Changes: Map()
+builder > A.scala
+compiling Set(A.scala)
+Changes: Map(class A -> List(), object A -> List())
diff --git a/test/files/buildmanager/annotated/annotated.test b/test/files/buildmanager/annotated/annotated.test
new file mode 100644
index 0000000..392e0d3
--- /dev/null
+++ b/test/files/buildmanager/annotated/annotated.test
@@ -0,0 +1,2 @@
+>>compile A.scala
+>>compile A.scala
diff --git a/test/files/buildmanager/freshnames/A.scala b/test/files/buildmanager/freshnames/A.scala
new file mode 100644
index 0000000..e8ab26c
--- /dev/null
+++ b/test/files/buildmanager/freshnames/A.scala
@@ -0,0 +1,16 @@
+abstract class A {
+
+    var t: List[B]
+    
+    def foo(n: String): Option[B] = {
+        t.reverse find (_.names contains n)
+    }
+    
+    def bar(n: Int): Option[B] = {
+        t.reverse find (_.names contains n)
+    }
+}
+
+//class A
+case class B(names: List[String])
+
diff --git a/test/files/buildmanager/freshnames/B.scala b/test/files/buildmanager/freshnames/B.scala
new file mode 100644
index 0000000..d700225
--- /dev/null
+++ b/test/files/buildmanager/freshnames/B.scala
@@ -0,0 +1,4 @@
+abstract class C extends A {
+    def test(n: Int) = bar(n)
+}
+
diff --git a/test/files/buildmanager/freshnames/freshnames.check b/test/files/buildmanager/freshnames/freshnames.check
new file mode 100644
index 0000000..9f05fb8
--- /dev/null
+++ b/test/files/buildmanager/freshnames/freshnames.check
@@ -0,0 +1,6 @@
+builder > B.scala A.scala
+compiling Set(A.scala, B.scala)
+Changes: Map()
+builder > A.scala
+compiling Set(A.scala)
+Changes: Map(class A -> List(), class B -> List(), object B -> List())
diff --git a/test/files/buildmanager/freshnames/freshnames.test b/test/files/buildmanager/freshnames/freshnames.test
new file mode 100644
index 0000000..20b2029
--- /dev/null
+++ b/test/files/buildmanager/freshnames/freshnames.test
@@ -0,0 +1,2 @@
+>>compile B.scala A.scala
+>>compile A.scala
diff --git a/test/files/buildmanager/infer/A.scala b/test/files/buildmanager/infer/A.scala
new file mode 100644
index 0000000..46b5391
--- /dev/null
+++ b/test/files/buildmanager/infer/A.scala
@@ -0,0 +1,16 @@
+class Foo(flag: Boolean) {
+    val classpath = 
+        if (flag)
+            new AClasspath
+        else
+            new BClasspath
+}
+
+class AClasspath extends MergedClasspath[A]
+
+class BClasspath extends MergedClasspath[B]
+
+abstract class MergedClasspath[T]
+
+class A
+class B
diff --git a/test/files/buildmanager/infer/infer.check b/test/files/buildmanager/infer/infer.check
new file mode 100644
index 0000000..1f73697
--- /dev/null
+++ b/test/files/buildmanager/infer/infer.check
@@ -0,0 +1,6 @@
+builder > A.scala
+compiling Set(A.scala)
+Changes: Map()
+builder > A.scala
+compiling Set(A.scala)
+Changes: Map(class A -> List(), class AClasspath -> List(), class B -> List(), class BClasspath -> List(), class Foo -> List(), class MergedClasspath -> List())
diff --git a/test/files/buildmanager/infer/infer.test b/test/files/buildmanager/infer/infer.test
new file mode 100644
index 0000000..392e0d3
--- /dev/null
+++ b/test/files/buildmanager/infer/infer.test
@@ -0,0 +1,2 @@
+>>compile A.scala
+>>compile A.scala
diff --git a/test/files/buildmanager/overloaded_1/A.scala b/test/files/buildmanager/overloaded_1/A.scala
new file mode 100644
index 0000000..33b63b8
--- /dev/null
+++ b/test/files/buildmanager/overloaded_1/A.scala
@@ -0,0 +1,11 @@
+trait As {
+  trait C extends D {
+    override def foo = this  /// Shouldn't cause the change
+    override def foo(act: List[D]) = this
+  }
+    
+  abstract class D{
+    def foo: D = this
+    def foo(act: List[D]) = this
+  }
+}
diff --git a/test/files/buildmanager/overloaded_1/overloaded_1.check b/test/files/buildmanager/overloaded_1/overloaded_1.check
new file mode 100644
index 0000000..4d643ce
--- /dev/null
+++ b/test/files/buildmanager/overloaded_1/overloaded_1.check
@@ -0,0 +1,6 @@
+builder > A.scala
+compiling Set(A.scala)
+Changes: Map()
+builder > A.scala
+compiling Set(A.scala)
+Changes: Map(class As$D -> List(), object As$C$class -> List(), object As$class -> List(), trait As -> List(), trait As$C -> List())
diff --git a/test/files/buildmanager/overloaded_1/overloaded_1.test b/test/files/buildmanager/overloaded_1/overloaded_1.test
new file mode 100644
index 0000000..392e0d3
--- /dev/null
+++ b/test/files/buildmanager/overloaded_1/overloaded_1.test
@@ -0,0 +1,2 @@
+>>compile A.scala
+>>compile A.scala
diff --git a/test/files/buildmanager/simpletest/A.scala b/test/files/buildmanager/simpletest/A.scala
new file mode 100644
index 0000000..ef70470
--- /dev/null
+++ b/test/files/buildmanager/simpletest/A.scala
@@ -0,0 +1,3 @@
+class A {
+  def foo = 2
+}
diff --git a/test/files/buildmanager/simpletest/B.scala b/test/files/buildmanager/simpletest/B.scala
new file mode 100644
index 0000000..364dc6e
--- /dev/null
+++ b/test/files/buildmanager/simpletest/B.scala
@@ -0,0 +1,3 @@
+class B extends A {
+  override def foo = 2
+}
diff --git a/test/files/buildmanager/simpletest/simpletest.changes/A1.scala b/test/files/buildmanager/simpletest/simpletest.changes/A1.scala
new file mode 100644
index 0000000..83d15dc
--- /dev/null
+++ b/test/files/buildmanager/simpletest/simpletest.changes/A1.scala
@@ -0,0 +1 @@
+class A
diff --git a/test/files/buildmanager/simpletest/simpletest.check b/test/files/buildmanager/simpletest/simpletest.check
new file mode 100644
index 0000000..95ea2c4
--- /dev/null
+++ b/test/files/buildmanager/simpletest/simpletest.check
@@ -0,0 +1,11 @@
+builder > A.scala B.scala
+compiling Set(A.scala, B.scala)
+Changes: Map()
+builder > A.scala
+compiling Set(A.scala)
+Changes: Map(class A -> List(Removed(Definition(A.foo))))
+invalidate B.scala because inherited method removed [Removed(Definition(A.foo))]
+compiling Set(B.scala)
+B.scala:2: error: method foo overrides nothing
+  override def foo = 2
+               ^
diff --git a/test/files/buildmanager/simpletest/simpletest.test b/test/files/buildmanager/simpletest/simpletest.test
new file mode 100644
index 0000000..2c0be15
--- /dev/null
+++ b/test/files/buildmanager/simpletest/simpletest.test
@@ -0,0 +1,3 @@
+>>compile A.scala B.scala
+>>update A.scala=>A1.scala
+>>compile A.scala
diff --git a/test/files/buildmanager/t2280/A.scala b/test/files/buildmanager/t2280/A.scala
new file mode 100644
index 0000000..5febade
--- /dev/null
+++ b/test/files/buildmanager/t2280/A.scala
@@ -0,0 +1 @@
+class A extends B
diff --git a/test/files/buildmanager/t2280/B.java b/test/files/buildmanager/t2280/B.java
new file mode 100644
index 0000000..aef8e10
--- /dev/null
+++ b/test/files/buildmanager/t2280/B.java
@@ -0,0 +1,2 @@
+public class B {}
+
diff --git a/test/files/buildmanager/t2280/t2280.check b/test/files/buildmanager/t2280/t2280.check
new file mode 100644
index 0000000..7ea7511
--- /dev/null
+++ b/test/files/buildmanager/t2280/t2280.check
@@ -0,0 +1,6 @@
+builder > A.scala B.java
+compiling Set(A.scala, B.java)
+Changes: Map()
+builder > B.java
+compiling Set(B.java)
+Changes: Map(class B -> List())
diff --git a/test/files/buildmanager/t2280/t2280.test b/test/files/buildmanager/t2280/t2280.test
new file mode 100644
index 0000000..2eda777
--- /dev/null
+++ b/test/files/buildmanager/t2280/t2280.test
@@ -0,0 +1,2 @@
+>>compile A.scala B.java
+>>compile B.java
diff --git a/test/files/buildmanager/t2556_1/A.scala b/test/files/buildmanager/t2556_1/A.scala
new file mode 100644
index 0000000..c6e200b
--- /dev/null
+++ b/test/files/buildmanager/t2556_1/A.scala
@@ -0,0 +1,3 @@
+class A {
+  def x(i: Int) = i+"3"
+}
diff --git a/test/files/buildmanager/t2556_1/B.scala b/test/files/buildmanager/t2556_1/B.scala
new file mode 100644
index 0000000..8529587
--- /dev/null
+++ b/test/files/buildmanager/t2556_1/B.scala
@@ -0,0 +1,3 @@
+class B extends A {
+  def x(s: String) = s+"5"
+}
diff --git a/test/files/buildmanager/t2556_1/t2556_1.changes/A2.scala b/test/files/buildmanager/t2556_1/t2556_1.changes/A2.scala
new file mode 100644
index 0000000..4ac1045
--- /dev/null
+++ b/test/files/buildmanager/t2556_1/t2556_1.changes/A2.scala
@@ -0,0 +1,4 @@
+class A {
+  def x(i: String) = i+"3"
+}
+
diff --git a/test/files/buildmanager/t2556_1/t2556_1.check b/test/files/buildmanager/t2556_1/t2556_1.check
new file mode 100644
index 0000000..dc9437f
--- /dev/null
+++ b/test/files/buildmanager/t2556_1/t2556_1.check
@@ -0,0 +1,12 @@
+builder > A.scala B.scala
+compiling Set(A.scala, B.scala)
+Changes: Map()
+builder > A.scala
+compiling Set(A.scala)
+Changes: Map(class A -> List(Changed(Definition(A.x))[method x changed from (i: Int)java.lang.String to (i: java.lang.String)java.lang.String flags: <method>]))
+invalidate B.scala because inherited method changed [Changed(Definition(A.x))[method x changed from (i: Int)java.lang.String to (i: java.lang.String)java.lang.String flags: <method>]]
+compiling Set(B.scala)
+B.scala:2: error: overriding method x in class A of type (i: String)java.lang.String;
+ method x needs `override' modifier
+  def x(s: String) = s+"5"
+      ^
diff --git a/test/files/buildmanager/t2556_1/t2556_1.test b/test/files/buildmanager/t2556_1/t2556_1.test
new file mode 100644
index 0000000..6f3bd03
--- /dev/null
+++ b/test/files/buildmanager/t2556_1/t2556_1.test
@@ -0,0 +1,3 @@
+>>compile A.scala B.scala
+>>update A.scala=>A2.scala
+>>compile A.scala
diff --git a/test/files/buildmanager/t2556_2/A.scala b/test/files/buildmanager/t2556_2/A.scala
new file mode 100644
index 0000000..b8da5c8
--- /dev/null
+++ b/test/files/buildmanager/t2556_2/A.scala
@@ -0,0 +1,4 @@
+class A {
+  def x(i: Int) = i+"3"
+}
+
diff --git a/test/files/buildmanager/t2556_2/B.scala b/test/files/buildmanager/t2556_2/B.scala
new file mode 100644
index 0000000..80ff25d
--- /dev/null
+++ b/test/files/buildmanager/t2556_2/B.scala
@@ -0,0 +1,2 @@
+class B extends A
+
diff --git a/test/files/buildmanager/t2556_2/C.scala b/test/files/buildmanager/t2556_2/C.scala
new file mode 100644
index 0000000..0ab13e3
--- /dev/null
+++ b/test/files/buildmanager/t2556_2/C.scala
@@ -0,0 +1,4 @@
+class C extends B {
+  def x(s: String) = s+"5"
+}
+
diff --git a/test/files/buildmanager/t2556_2/t2556_2.changes/A2.scala b/test/files/buildmanager/t2556_2/t2556_2.changes/A2.scala
new file mode 100644
index 0000000..4ac1045
--- /dev/null
+++ b/test/files/buildmanager/t2556_2/t2556_2.changes/A2.scala
@@ -0,0 +1,4 @@
+class A {
+  def x(i: String) = i+"3"
+}
+
diff --git a/test/files/buildmanager/t2556_2/t2556_2.check b/test/files/buildmanager/t2556_2/t2556_2.check
new file mode 100644
index 0000000..a4d6724
--- /dev/null
+++ b/test/files/buildmanager/t2556_2/t2556_2.check
@@ -0,0 +1,13 @@
+builder > A.scala B.scala C.scala
+compiling Set(A.scala, B.scala, C.scala)
+Changes: Map()
+builder > A.scala
+compiling Set(A.scala)
+Changes: Map(class A -> List(Changed(Definition(A.x))[method x changed from (i: Int)java.lang.String to (i: java.lang.String)java.lang.String flags: <method>]))
+invalidate B.scala because inherited method changed [Changed(Definition(A.x))[method x changed from (i: Int)java.lang.String to (i: java.lang.String)java.lang.String flags: <method>]]
+invalidate C.scala because inherited method changed [Changed(Definition(A.x))[method x changed from (i: Int)java.lang.String to (i: java.lang.String)java.lang.String flags: <method>]]
+compiling Set(B.scala, C.scala)
+C.scala:2: error: overriding method x in class A of type (i: String)java.lang.String;
+ method x needs `override' modifier
+  def x(s: String) = s+"5"
+      ^
diff --git a/test/files/buildmanager/t2556_2/t2556_2.test b/test/files/buildmanager/t2556_2/t2556_2.test
new file mode 100644
index 0000000..9f31bb6
--- /dev/null
+++ b/test/files/buildmanager/t2556_2/t2556_2.test
@@ -0,0 +1,3 @@
+>>compile A.scala B.scala C.scala
+>>update A.scala=>A2.scala
+>>compile A.scala
diff --git a/test/files/buildmanager/t2556_3/A.scala b/test/files/buildmanager/t2556_3/A.scala
new file mode 100644
index 0000000..089a05f
--- /dev/null
+++ b/test/files/buildmanager/t2556_3/A.scala
@@ -0,0 +1,5 @@
+class A {
+  def x = 3
+}
+class B extends A
+
diff --git a/test/files/buildmanager/t2556_3/B.scala b/test/files/buildmanager/t2556_3/B.scala
new file mode 100644
index 0000000..0ec5ae4
--- /dev/null
+++ b/test/files/buildmanager/t2556_3/B.scala
@@ -0,0 +1,5 @@
+object E {
+  def main(args: Array[String]) =
+    println( (new C).x )
+}
+
diff --git a/test/files/buildmanager/t2556_3/C.scala b/test/files/buildmanager/t2556_3/C.scala
new file mode 100644
index 0000000..403df84
--- /dev/null
+++ b/test/files/buildmanager/t2556_3/C.scala
@@ -0,0 +1,2 @@
+class C extends B
+
diff --git a/test/files/buildmanager/t2556_3/t2556_3.changes/A2.scala b/test/files/buildmanager/t2556_3/t2556_3.changes/A2.scala
new file mode 100644
index 0000000..21cb277
--- /dev/null
+++ b/test/files/buildmanager/t2556_3/t2556_3.changes/A2.scala
@@ -0,0 +1,5 @@
+class A {
+  def x = 3
+}
+class B
+
diff --git a/test/files/buildmanager/t2556_3/t2556_3.check b/test/files/buildmanager/t2556_3/t2556_3.check
new file mode 100644
index 0000000..af0c63e
--- /dev/null
+++ b/test/files/buildmanager/t2556_3/t2556_3.check
@@ -0,0 +1,18 @@
+builder > A.scala B.scala C.scala
+compiling Set(A.scala, B.scala, C.scala)
+Changes: Map()
+builder > A.scala
+compiling Set(A.scala)
+Changes: Map(class A -> List(), class B -> List(Changed(Class(B))[List((A,java.lang.Object), (ScalaObject,ScalaObject))]))
+invalidate C.scala because parents have changed [Changed(Class(B))[List((A,java.lang.Object), (ScalaObject,ScalaObject))]]
+invalidate B.scala because it references invalid (no longer inherited) definition [ParentChanged(Class(C))]
+compiling Set(B.scala, C.scala)
+B.scala:3: error: type mismatch;
+ found   : C
+ required: ?{val x: ?}
+Note that implicit conversions are not applicable because they are ambiguous:
+ both method any2ArrowAssoc in object Predef of type [A](x: A)ArrowAssoc[A]
+ and method any2Ensuring in object Predef of type [A](x: A)Ensuring[A]
+ are possible conversion functions from C to ?{val x: ?}
+    println( (new C).x )
+              ^
diff --git a/test/files/buildmanager/t2556_3/t2556_3.test b/test/files/buildmanager/t2556_3/t2556_3.test
new file mode 100644
index 0000000..9f31bb6
--- /dev/null
+++ b/test/files/buildmanager/t2556_3/t2556_3.test
@@ -0,0 +1,3 @@
+>>compile A.scala B.scala C.scala
+>>update A.scala=>A2.scala
+>>compile A.scala
diff --git a/test/files/buildmanager/t2557/A.scala b/test/files/buildmanager/t2557/A.scala
new file mode 100644
index 0000000..3be55f1
--- /dev/null
+++ b/test/files/buildmanager/t2557/A.scala
@@ -0,0 +1,4 @@
+trait A {
+    def x = 3
+}
+
diff --git a/test/files/buildmanager/t2557/B.scala b/test/files/buildmanager/t2557/B.scala
new file mode 100644
index 0000000..ea86a90
--- /dev/null
+++ b/test/files/buildmanager/t2557/B.scala
@@ -0,0 +1,4 @@
+trait B extends A {
+    override def x = super.x * 2
+}
+
diff --git a/test/files/buildmanager/t2557/C.scala b/test/files/buildmanager/t2557/C.scala
new file mode 100644
index 0000000..dd575ac
--- /dev/null
+++ b/test/files/buildmanager/t2557/C.scala
@@ -0,0 +1,3 @@
+trait C extends A {
+    override def x = super.x + 5
+}
diff --git a/test/files/buildmanager/t2557/D.scala b/test/files/buildmanager/t2557/D.scala
new file mode 100644
index 0000000..4e662a8
--- /dev/null
+++ b/test/files/buildmanager/t2557/D.scala
@@ -0,0 +1 @@
+trait D extends C with B
diff --git a/test/files/buildmanager/t2557/E.scala b/test/files/buildmanager/t2557/E.scala
new file mode 100644
index 0000000..2aee552
--- /dev/null
+++ b/test/files/buildmanager/t2557/E.scala
@@ -0,0 +1 @@
+trait E extends D
diff --git a/test/files/buildmanager/t2557/F.scala b/test/files/buildmanager/t2557/F.scala
new file mode 100644
index 0000000..e199670
--- /dev/null
+++ b/test/files/buildmanager/t2557/F.scala
@@ -0,0 +1,4 @@
+object F extends E {
+    def main(args: Array[String]) =
+        println(x)
+}
diff --git a/test/files/buildmanager/t2557/t2557.changes/D2.scala b/test/files/buildmanager/t2557/t2557.changes/D2.scala
new file mode 100644
index 0000000..67295f8
--- /dev/null
+++ b/test/files/buildmanager/t2557/t2557.changes/D2.scala
@@ -0,0 +1,2 @@
+trait D extends B with C
+
diff --git a/test/files/buildmanager/t2557/t2557.check b/test/files/buildmanager/t2557/t2557.check
new file mode 100644
index 0000000..f51e801
--- /dev/null
+++ b/test/files/buildmanager/t2557/t2557.check
@@ -0,0 +1,10 @@
+builder > A.scala B.scala C.scala D.scala E.scala F.scala
+compiling Set(A.scala, B.scala, C.scala, D.scala, E.scala, F.scala)
+Changes: Map()
+builder > D.scala
+compiling Set(D.scala)
+Changes: Map(trait D -> List(Changed(Class(D))[List((java.lang.Object,java.lang.Object), (C,B), (B,C))]))
+invalidate E.scala because parents have changed [Changed(Class(D))[List((java.lang.Object,java.lang.Object), (C,B), (B,C))]]
+invalidate F.scala because parents have changed [Changed(Class(D))[List((java.lang.Object,java.lang.Object), (C,B), (B,C))]]
+compiling Set(E.scala, F.scala)
+Changes: Map(object F -> List(), trait E -> List())
diff --git a/test/files/buildmanager/t2557/t2557.test b/test/files/buildmanager/t2557/t2557.test
new file mode 100644
index 0000000..6b01030
--- /dev/null
+++ b/test/files/buildmanager/t2557/t2557.test
@@ -0,0 +1,3 @@
+>>compile A.scala B.scala C.scala D.scala E.scala F.scala
+>>update D.scala=>D2.scala
+>>compile D.scala
diff --git a/test/files/buildmanager/t2559/A.scala b/test/files/buildmanager/t2559/A.scala
new file mode 100644
index 0000000..fb4f6e3
--- /dev/null
+++ b/test/files/buildmanager/t2559/A.scala
@@ -0,0 +1,5 @@
+sealed trait A
+class B extends A
+class C extends A
+//class E extends A
+
diff --git a/test/files/buildmanager/t2559/D.scala b/test/files/buildmanager/t2559/D.scala
new file mode 100644
index 0000000..906b69a
--- /dev/null
+++ b/test/files/buildmanager/t2559/D.scala
@@ -0,0 +1,8 @@
+object D {
+  def x(a: A) = 
+    a match {
+      case _: B => ()
+      case _: C => ()
+    }
+}
+
diff --git a/test/files/buildmanager/t2559/t2559.changes/A2.scala b/test/files/buildmanager/t2559/t2559.changes/A2.scala
new file mode 100644
index 0000000..8e90594
--- /dev/null
+++ b/test/files/buildmanager/t2559/t2559.changes/A2.scala
@@ -0,0 +1,5 @@
+sealed trait A
+class B extends A
+class C extends A
+class E extends A
+
diff --git a/test/files/buildmanager/t2559/t2559.check b/test/files/buildmanager/t2559/t2559.check
new file mode 100644
index 0000000..752278f
--- /dev/null
+++ b/test/files/buildmanager/t2559/t2559.check
@@ -0,0 +1,14 @@
+builder > A.scala D.scala
+compiling Set(A.scala, D.scala)
+Changes: Map()
+builder > A.scala
+compiling Set(A.scala)
+Changes: Map(class B -> List(), class C -> List(), class E -> List(Changed(Class(A))[class E extends a sealed trait A]), trait A -> List())
+invalidate D.scala because it references changed class [Changed(Class(A))[class E extends a sealed trait A]]
+compiling Set(D.scala)
+D.scala:3: warning: match is not exhaustive!
+missing combination              E
+
+    a match {
+    ^
+Changes: Map(object D -> List())
diff --git a/test/files/buildmanager/t2559/t2559.test b/test/files/buildmanager/t2559/t2559.test
new file mode 100644
index 0000000..b787c5b
--- /dev/null
+++ b/test/files/buildmanager/t2559/t2559.test
@@ -0,0 +1,3 @@
+>>compile A.scala D.scala
+>>update A.scala=>A2.scala
+>>compile A.scala
diff --git a/test/files/buildmanager/t2562/A.scala b/test/files/buildmanager/t2562/A.scala
new file mode 100644
index 0000000..740cd1e
--- /dev/null
+++ b/test/files/buildmanager/t2562/A.scala
@@ -0,0 +1,7 @@
+object A
+{
+  def x0 = B.x0                                                                   
+  def x1 = B.x1
+  def x2 = B.x2
+  def x3 = 3
+}
diff --git a/test/files/buildmanager/t2562/B.scala b/test/files/buildmanager/t2562/B.scala
new file mode 100644
index 0000000..a524e5c
--- /dev/null
+++ b/test/files/buildmanager/t2562/B.scala
@@ -0,0 +1,8 @@
+object B
+{
+  def x0 = A.x1                                                                   
+  def x1 = A.x2
+  def x2 = A.x3
+}
+
+
diff --git a/test/files/buildmanager/t2562/t2562.changes/A2.scala b/test/files/buildmanager/t2562/t2562.changes/A2.scala
new file mode 100644
index 0000000..c560e1e
--- /dev/null
+++ b/test/files/buildmanager/t2562/t2562.changes/A2.scala
@@ -0,0 +1,8 @@
+object A
+{
+  def x0 = B.x0                                                                   
+  def x1 = B.x1
+  def x2 = B.x2
+  def x3 = "3"
+}
+
diff --git a/test/files/buildmanager/t2562/t2562.check b/test/files/buildmanager/t2562/t2562.check
new file mode 100644
index 0000000..813d273
--- /dev/null
+++ b/test/files/buildmanager/t2562/t2562.check
@@ -0,0 +1,12 @@
+builder > A.scala B.scala
+compiling Set(A.scala, B.scala)
+Changes: Map()
+builder > A.scala
+compiling Set(A.scala)
+Changes: Map(object A -> List(Changed(Definition(A.x3))[method x3 changed from ()Int to ()java.lang.String flags: <method>]))
+invalidate B.scala because it references changed definition [Changed(Definition(A.x3))[method x3 changed from ()Int to ()java.lang.String flags: <method>]]
+compiling Set(B.scala)
+Changes: Map(object B -> List(Changed(Definition(B.x2))[method x2 changed from ()Int to ()java.lang.String flags: <method>]))
+invalidate A.scala because it references changed definition [Changed(Definition(B.x2))[method x2 changed from ()Int to ()java.lang.String flags: <method>]]
+compiling Set(A.scala, B.scala)
+Changes: Map(object A -> List(Changed(Definition(A.x0))[method x0 changed from ()Int to ()java.lang.String flags: <method>], Changed(Definition(A.x1))[method x1 changed from ()Int to ()java.lang.String flags: <method>], Changed(Definition(A.x2))[method x2 changed from ()Int to ()java.lang.String flags: <method>]), object B -> List(Changed(Definition(B.x0))[method x0 changed from ()Int to ()java.lang.String flags: <method>], Changed(Definition(B.x1))[method x1 changed from ()Int to ()java [...]
diff --git a/test/files/buildmanager/t2562/t2562.test b/test/files/buildmanager/t2562/t2562.test
new file mode 100644
index 0000000..6f3bd03
--- /dev/null
+++ b/test/files/buildmanager/t2562/t2562.test
@@ -0,0 +1,3 @@
+>>compile A.scala B.scala
+>>update A.scala=>A2.scala
+>>compile A.scala
diff --git a/test/files/buildmanager/t2649/A.scala b/test/files/buildmanager/t2649/A.scala
new file mode 100644
index 0000000..86cc3f2
--- /dev/null
+++ b/test/files/buildmanager/t2649/A.scala
@@ -0,0 +1,3 @@
+object A {
+  def x(zz: Int, yy: Int) = yy - zz
+}
diff --git a/test/files/buildmanager/t2649/B.scala b/test/files/buildmanager/t2649/B.scala
new file mode 100644
index 0000000..26c8951
--- /dev/null
+++ b/test/files/buildmanager/t2649/B.scala
@@ -0,0 +1,4 @@
+object B {
+  def main(args: Array[String]): Unit =
+    println( A.x(zz = 3, yy = 4) )
+}
diff --git a/test/files/buildmanager/t2649/t2649.changes/A2.scala b/test/files/buildmanager/t2649/t2649.changes/A2.scala
new file mode 100644
index 0000000..9a6309f
--- /dev/null
+++ b/test/files/buildmanager/t2649/t2649.changes/A2.scala
@@ -0,0 +1,4 @@
+object A {
+  def x(yy: Int, zz: Int) = yy - zz
+}
+
diff --git a/test/files/buildmanager/t2649/t2649.check b/test/files/buildmanager/t2649/t2649.check
new file mode 100644
index 0000000..5b698ec
--- /dev/null
+++ b/test/files/buildmanager/t2649/t2649.check
@@ -0,0 +1,9 @@
+builder > A.scala B.scala
+compiling Set(A.scala, B.scala)
+Changes: Map()
+builder > A.scala
+compiling Set(A.scala)
+Changes: Map(object A -> List(Changed(Definition(A.x))[method x changed from (zz: Int,yy: Int)Int to (yy: Int,zz: Int)Int flags: <method>]))
+invalidate B.scala because it references changed definition [Changed(Definition(A.x))[method x changed from (zz: Int,yy: Int)Int to (yy: Int,zz: Int)Int flags: <method>]]
+compiling Set(B.scala)
+Changes: Map(object B -> List())
diff --git a/test/files/buildmanager/t2649/t2649.test b/test/files/buildmanager/t2649/t2649.test
new file mode 100644
index 0000000..6f3bd03
--- /dev/null
+++ b/test/files/buildmanager/t2649/t2649.test
@@ -0,0 +1,3 @@
+>>compile A.scala B.scala
+>>update A.scala=>A2.scala
+>>compile A.scala
diff --git a/test/files/buildmanager/t2650_1/A.scala b/test/files/buildmanager/t2650_1/A.scala
new file mode 100644
index 0000000..74714a3
--- /dev/null
+++ b/test/files/buildmanager/t2650_1/A.scala
@@ -0,0 +1,4 @@
+trait A {
+    type S[_]
+}
+
diff --git a/test/files/buildmanager/t2650_1/B.scala b/test/files/buildmanager/t2650_1/B.scala
new file mode 100644
index 0000000..80f0e30
--- /dev/null
+++ b/test/files/buildmanager/t2650_1/B.scala
@@ -0,0 +1,3 @@
+trait B extends A {
+    type F = S[Int]
+}
diff --git a/test/files/buildmanager/t2650_1/t2650_1.changes/A2.scala b/test/files/buildmanager/t2650_1/t2650_1.changes/A2.scala
new file mode 100644
index 0000000..2b8ead4
--- /dev/null
+++ b/test/files/buildmanager/t2650_1/t2650_1.changes/A2.scala
@@ -0,0 +1,3 @@
+trait A {
+    type S
+}
diff --git a/test/files/buildmanager/t2650_1/t2650_1.check b/test/files/buildmanager/t2650_1/t2650_1.check
new file mode 100644
index 0000000..ecddb33
--- /dev/null
+++ b/test/files/buildmanager/t2650_1/t2650_1.check
@@ -0,0 +1,11 @@
+builder > A.scala B.scala
+compiling Set(A.scala, B.scala)
+Changes: Map()
+builder > A.scala
+compiling Set(A.scala)
+Changes: Map(trait A -> List(Changed(Definition(A.S))[type S changed from A.this.S[_] to A.this.S flags: <deferred>]))
+invalidate B.scala because inherited method changed [Changed(Definition(A.S))[type S changed from A.this.S[_] to A.this.S flags: <deferred>]]
+compiling Set(B.scala)
+B.scala:2: error: B.this.S does not take type parameters
+    type F = S[Int]
+             ^
diff --git a/test/files/buildmanager/t2650_1/t2650_1.test b/test/files/buildmanager/t2650_1/t2650_1.test
new file mode 100644
index 0000000..6f3bd03
--- /dev/null
+++ b/test/files/buildmanager/t2650_1/t2650_1.test
@@ -0,0 +1,3 @@
+>>compile A.scala B.scala
+>>update A.scala=>A2.scala
+>>compile A.scala
diff --git a/test/files/buildmanager/t2650_2/A.scala b/test/files/buildmanager/t2650_2/A.scala
new file mode 100644
index 0000000..bcea634
--- /dev/null
+++ b/test/files/buildmanager/t2650_2/A.scala
@@ -0,0 +1,3 @@
+trait A {
+  type S = Int
+}
diff --git a/test/files/buildmanager/t2650_2/B.scala b/test/files/buildmanager/t2650_2/B.scala
new file mode 100644
index 0000000..22a3a9a
--- /dev/null
+++ b/test/files/buildmanager/t2650_2/B.scala
@@ -0,0 +1,4 @@
+trait B extends A {
+  def x: S
+  def y: Int = x
+}
diff --git a/test/files/buildmanager/t2650_2/t2650_2.changes/A2.scala b/test/files/buildmanager/t2650_2/t2650_2.changes/A2.scala
new file mode 100644
index 0000000..8274c1b
--- /dev/null
+++ b/test/files/buildmanager/t2650_2/t2650_2.changes/A2.scala
@@ -0,0 +1,4 @@
+trait A {
+  type S = Long
+}
+
diff --git a/test/files/buildmanager/t2650_2/t2650_2.check b/test/files/buildmanager/t2650_2/t2650_2.check
new file mode 100644
index 0000000..7ab72fb
--- /dev/null
+++ b/test/files/buildmanager/t2650_2/t2650_2.check
@@ -0,0 +1,13 @@
+builder > A.scala B.scala
+compiling Set(A.scala, B.scala)
+Changes: Map()
+builder > A.scala
+compiling Set(A.scala)
+Changes: Map(trait A -> List(Changed(Definition(A.S))[type S changed from A.this.S to A.this.S flags: ]))
+invalidate B.scala because inherited method changed [Changed(Definition(A.S))[type S changed from A.this.S to A.this.S flags: ]]
+compiling Set(B.scala)
+B.scala:3: error: type mismatch;
+ found   : B.this.S
+ required: Int
+  def y: Int = x
+               ^
diff --git a/test/files/buildmanager/t2650_2/t2650_2.test b/test/files/buildmanager/t2650_2/t2650_2.test
new file mode 100644
index 0000000..6f3bd03
--- /dev/null
+++ b/test/files/buildmanager/t2650_2/t2650_2.test
@@ -0,0 +1,3 @@
+>>compile A.scala B.scala
+>>update A.scala=>A2.scala
+>>compile A.scala
diff --git a/test/files/buildmanager/t2650_3/A.scala b/test/files/buildmanager/t2650_3/A.scala
new file mode 100644
index 0000000..cd13843
--- /dev/null
+++ b/test/files/buildmanager/t2650_3/A.scala
@@ -0,0 +1,4 @@
+trait A {
+  type T = Int
+  def x: T
+}
diff --git a/test/files/buildmanager/t2650_3/B.scala b/test/files/buildmanager/t2650_3/B.scala
new file mode 100644
index 0000000..46a8cf2
--- /dev/null
+++ b/test/files/buildmanager/t2650_3/B.scala
@@ -0,0 +1,3 @@
+object B {
+  def x(a: A): Int = a.x
+}
diff --git a/test/files/buildmanager/t2650_3/t2650_3.changes/A2.scala b/test/files/buildmanager/t2650_3/t2650_3.changes/A2.scala
new file mode 100644
index 0000000..e5667b2
--- /dev/null
+++ b/test/files/buildmanager/t2650_3/t2650_3.changes/A2.scala
@@ -0,0 +1,4 @@
+trait A {
+  type T = Long
+  def x: T
+}
diff --git a/test/files/buildmanager/t2650_3/t2650_3.check b/test/files/buildmanager/t2650_3/t2650_3.check
new file mode 100644
index 0000000..27be2f5
--- /dev/null
+++ b/test/files/buildmanager/t2650_3/t2650_3.check
@@ -0,0 +1,13 @@
+builder > A.scala B.scala
+compiling Set(A.scala, B.scala)
+Changes: Map()
+builder > A.scala
+compiling Set(A.scala)
+Changes: Map(trait A -> List(Changed(Definition(A.T))[type T changed from A.this.T to A.this.T flags: ]))
+invalidate B.scala because it references changed definition [Changed(Definition(A.T))[type T changed from A.this.T to A.this.T flags: ]]
+compiling Set(B.scala)
+B.scala:2: error: type mismatch;
+ found   : a.T
+ required: Int
+  def x(a: A): Int = a.x
+                       ^
diff --git a/test/files/buildmanager/t2650_3/t2650_3.test b/test/files/buildmanager/t2650_3/t2650_3.test
new file mode 100644
index 0000000..6f3bd03
--- /dev/null
+++ b/test/files/buildmanager/t2650_3/t2650_3.test
@@ -0,0 +1,3 @@
+>>compile A.scala B.scala
+>>update A.scala=>A2.scala
+>>compile A.scala
diff --git a/test/files/buildmanager/t2650_4/A.scala b/test/files/buildmanager/t2650_4/A.scala
new file mode 100644
index 0000000..b9a519e
--- /dev/null
+++ b/test/files/buildmanager/t2650_4/A.scala
@@ -0,0 +1,5 @@
+trait A {
+  type T = Int
+  type T2 = T
+  def x: T2
+}
diff --git a/test/files/buildmanager/t2650_4/B.scala b/test/files/buildmanager/t2650_4/B.scala
new file mode 100644
index 0000000..46a8cf2
--- /dev/null
+++ b/test/files/buildmanager/t2650_4/B.scala
@@ -0,0 +1,3 @@
+object B {
+  def x(a: A): Int = a.x
+}
diff --git a/test/files/buildmanager/t2650_4/t2650_4.changes/A2.scala b/test/files/buildmanager/t2650_4/t2650_4.changes/A2.scala
new file mode 100644
index 0000000..0220e7b
--- /dev/null
+++ b/test/files/buildmanager/t2650_4/t2650_4.changes/A2.scala
@@ -0,0 +1,5 @@
+trait A {
+  type T = Long
+  type T2 = T
+  def x: T2
+}
diff --git a/test/files/buildmanager/t2650_4/t2650_4.check b/test/files/buildmanager/t2650_4/t2650_4.check
new file mode 100644
index 0000000..ba092d0
--- /dev/null
+++ b/test/files/buildmanager/t2650_4/t2650_4.check
@@ -0,0 +1,13 @@
+builder > A.scala B.scala
+compiling Set(A.scala, B.scala)
+Changes: Map()
+builder > A.scala
+compiling Set(A.scala)
+Changes: Map(trait A -> List(Changed(Definition(A.T))[type T changed from A.this.T to A.this.T flags: ]))
+invalidate B.scala because it references changed definition [Changed(Definition(A.T))[type T changed from A.this.T to A.this.T flags: ]]
+compiling Set(B.scala)
+B.scala:2: error: type mismatch;
+ found   : a.T2
+ required: Int
+  def x(a: A): Int = a.x
+                       ^
diff --git a/test/files/buildmanager/t2650_4/t2650_4.test b/test/files/buildmanager/t2650_4/t2650_4.test
new file mode 100644
index 0000000..6f3bd03
--- /dev/null
+++ b/test/files/buildmanager/t2650_4/t2650_4.test
@@ -0,0 +1,3 @@
+>>compile A.scala B.scala
+>>update A.scala=>A2.scala
+>>compile A.scala
diff --git a/test/files/buildmanager/t2651_2/A.scala b/test/files/buildmanager/t2651_2/A.scala
new file mode 100644
index 0000000..d712f6f
--- /dev/null
+++ b/test/files/buildmanager/t2651_2/A.scala
@@ -0,0 +1 @@
+trait A[T]
diff --git a/test/files/buildmanager/t2651_2/t2651_2.changes/A2.scala b/test/files/buildmanager/t2651_2/t2651_2.changes/A2.scala
new file mode 100644
index 0000000..7fb573e
--- /dev/null
+++ b/test/files/buildmanager/t2651_2/t2651_2.changes/A2.scala
@@ -0,0 +1 @@
+trait A[S]
diff --git a/test/files/buildmanager/t2651_2/t2651_2.check b/test/files/buildmanager/t2651_2/t2651_2.check
new file mode 100644
index 0000000..dd789b7
--- /dev/null
+++ b/test/files/buildmanager/t2651_2/t2651_2.check
@@ -0,0 +1,6 @@
+builder > A.scala
+compiling Set(A.scala)
+Changes: Map()
+builder > A.scala
+compiling Set(A.scala)
+Changes: Map(trait A -> List())
diff --git a/test/files/buildmanager/t2651_2/t2651_2.test b/test/files/buildmanager/t2651_2/t2651_2.test
new file mode 100644
index 0000000..d061447
--- /dev/null
+++ b/test/files/buildmanager/t2651_2/t2651_2.test
@@ -0,0 +1,3 @@
+>>compile A.scala
+>>update A.scala=>A2.scala
+>>compile A.scala
diff --git a/test/files/buildmanager/t2651_3/A.scala b/test/files/buildmanager/t2651_3/A.scala
new file mode 100644
index 0000000..14f9e46
--- /dev/null
+++ b/test/files/buildmanager/t2651_3/A.scala
@@ -0,0 +1,3 @@
+trait A[T, S] {
+    def x: T
+}
diff --git a/test/files/buildmanager/t2651_3/t2651_3.changes/A2.scala b/test/files/buildmanager/t2651_3/t2651_3.changes/A2.scala
new file mode 100644
index 0000000..51bf27d
--- /dev/null
+++ b/test/files/buildmanager/t2651_3/t2651_3.changes/A2.scala
@@ -0,0 +1,3 @@
+trait A[T, S] {
+    def x: S
+}
diff --git a/test/files/buildmanager/t2651_3/t2651_3.check b/test/files/buildmanager/t2651_3/t2651_3.check
new file mode 100644
index 0000000..d4bac19
--- /dev/null
+++ b/test/files/buildmanager/t2651_3/t2651_3.check
@@ -0,0 +1,6 @@
+builder > A.scala
+compiling Set(A.scala)
+Changes: Map()
+builder > A.scala
+compiling Set(A.scala)
+Changes: Map(trait A -> List(Changed(Definition(A.x))[method x changed from ()T to ()S flags: <deferred> <method>]))
diff --git a/test/files/buildmanager/t2651_3/t2651_3.test b/test/files/buildmanager/t2651_3/t2651_3.test
new file mode 100644
index 0000000..d061447
--- /dev/null
+++ b/test/files/buildmanager/t2651_3/t2651_3.test
@@ -0,0 +1,3 @@
+>>compile A.scala
+>>update A.scala=>A2.scala
+>>compile A.scala
diff --git a/test/files/buildmanager/t2651_4/A.scala b/test/files/buildmanager/t2651_4/A.scala
new file mode 100644
index 0000000..63f2a16
--- /dev/null
+++ b/test/files/buildmanager/t2651_4/A.scala
@@ -0,0 +1,5 @@
+trait A[T, S] {
+  def x: T
+  def y(a: T)
+  def z[B <: T]
+}
diff --git a/test/files/buildmanager/t2651_4/B.scala b/test/files/buildmanager/t2651_4/B.scala
new file mode 100644
index 0000000..b33dbde
--- /dev/null
+++ b/test/files/buildmanager/t2651_4/B.scala
@@ -0,0 +1,3 @@
+trait B extends A[Int, String] {
+  def x = 3
+}
diff --git a/test/files/buildmanager/t2651_4/t2651_4.changes/A2.scala b/test/files/buildmanager/t2651_4/t2651_4.changes/A2.scala
new file mode 100644
index 0000000..f155129
--- /dev/null
+++ b/test/files/buildmanager/t2651_4/t2651_4.changes/A2.scala
@@ -0,0 +1,5 @@
+trait A[S, T] {
+  def x: T
+  def y(a: T)
+  def z[B <: T]
+}
diff --git a/test/files/buildmanager/t2651_4/t2651_4.check b/test/files/buildmanager/t2651_4/t2651_4.check
new file mode 100644
index 0000000..c4ce382
--- /dev/null
+++ b/test/files/buildmanager/t2651_4/t2651_4.check
@@ -0,0 +1,13 @@
+builder > A.scala B.scala
+compiling Set(A.scala, B.scala)
+Changes: Map()
+builder > A.scala
+compiling Set(A.scala)
+Changes: Map(trait A -> List(Changed(Definition(A.x))[method x changed from ()T to ()T flags: <deferred> <method>], Changed(Definition(A.y))[method y changed from (a: T)Unit to (a: T)Unit flags: <deferred> <method>], Changed(Definition(A.z))[method z changed from [B <: T]()Unit to [B <: T]()Unit flags: <deferred> <method>]))
+invalidate B.scala because inherited method changed [Changed(Definition(A.x))[method x changed from ()T to ()T flags: <deferred> <method>]]
+compiling Set(B.scala)
+B.scala:2: error: type mismatch;
+ found   : Int(3)
+ required: String
+  def x = 3
+          ^
diff --git a/test/files/buildmanager/t2651_4/t2651_4.test b/test/files/buildmanager/t2651_4/t2651_4.test
new file mode 100644
index 0000000..6f3bd03
--- /dev/null
+++ b/test/files/buildmanager/t2651_4/t2651_4.test
@@ -0,0 +1,3 @@
+>>compile A.scala B.scala
+>>update A.scala=>A2.scala
+>>compile A.scala
diff --git a/test/files/buildmanager/t2652/A.scala b/test/files/buildmanager/t2652/A.scala
new file mode 100644
index 0000000..a62506e
--- /dev/null
+++ b/test/files/buildmanager/t2652/A.scala
@@ -0,0 +1,3 @@
+class A {
+  def x[T](t: T) = t
+}
diff --git a/test/files/buildmanager/t2652/B.scala b/test/files/buildmanager/t2652/B.scala
new file mode 100644
index 0000000..86d08f0
--- /dev/null
+++ b/test/files/buildmanager/t2652/B.scala
@@ -0,0 +1,4 @@
+object B {
+  val y = (new A).x(3)
+}
+
diff --git a/test/files/buildmanager/t2652/t2652.changes/A2.scala b/test/files/buildmanager/t2652/t2652.changes/A2.scala
new file mode 100644
index 0000000..29135c0
--- /dev/null
+++ b/test/files/buildmanager/t2652/t2652.changes/A2.scala
@@ -0,0 +1,4 @@
+class A {
+  def x[@specialized T](t: T) = t
+}
+
diff --git a/test/files/buildmanager/t2652/t2652.check b/test/files/buildmanager/t2652/t2652.check
new file mode 100644
index 0000000..0e685c1
--- /dev/null
+++ b/test/files/buildmanager/t2652/t2652.check
@@ -0,0 +1,9 @@
+builder > A.scala B.scala
+compiling Set(A.scala, B.scala)
+Changes: Map()
+builder > A.scala
+compiling Set(A.scala)
+Changes: Map(class A -> List(Added(Definition(A.x$mBc$sp)), Added(Definition(A.x$mCc$sp)), Added(Definition(A.x$mDc$sp)), Added(Definition(A.x$mFc$sp)), Added(Definition(A.x$mIc$sp)), Added(Definition(A.x$mLc$sp)), Added(Definition(A.x$mSc$sp)), Added(Definition(A.x$mVc$sp)), Added(Definition(A.x$mZc$sp)), Changed(Definition(A.x))[method x changed from [T](t: T)T to [T](t: T)T flags: <method>]))
+invalidate B.scala because it references changed definition [Changed(Definition(A.x))[method x changed from [T](t: T)T to [T](t: T)T flags: <method>]]
+compiling Set(B.scala)
+Changes: Map(object B -> List())
diff --git a/test/files/buildmanager/t2652/t2652.test b/test/files/buildmanager/t2652/t2652.test
new file mode 100644
index 0000000..6f3bd03
--- /dev/null
+++ b/test/files/buildmanager/t2652/t2652.test
@@ -0,0 +1,3 @@
+>>compile A.scala B.scala
+>>update A.scala=>A2.scala
+>>compile A.scala
diff --git a/test/files/buildmanager/t2653/A.scala b/test/files/buildmanager/t2653/A.scala
new file mode 100644
index 0000000..fb17a15
--- /dev/null
+++ b/test/files/buildmanager/t2653/A.scala
@@ -0,0 +1,2 @@
+class A[+T]
+
diff --git a/test/files/buildmanager/t2653/B.scala b/test/files/buildmanager/t2653/B.scala
new file mode 100644
index 0000000..8f55a88
--- /dev/null
+++ b/test/files/buildmanager/t2653/B.scala
@@ -0,0 +1,3 @@
+object B {
+  val a: A[Any] = new A[Int]
+}
diff --git a/test/files/buildmanager/t2653/t2653.changes/A2.scala b/test/files/buildmanager/t2653/t2653.changes/A2.scala
new file mode 100644
index 0000000..51d13cc
--- /dev/null
+++ b/test/files/buildmanager/t2653/t2653.changes/A2.scala
@@ -0,0 +1,2 @@
+class A[T]
+
diff --git a/test/files/buildmanager/t2653/t2653.check b/test/files/buildmanager/t2653/t2653.check
new file mode 100644
index 0000000..0d40601
--- /dev/null
+++ b/test/files/buildmanager/t2653/t2653.check
@@ -0,0 +1,13 @@
+builder > A.scala B.scala
+compiling Set(A.scala, B.scala)
+Changes: Map()
+builder > A.scala
+compiling Set(A.scala)
+Changes: Map(class A -> List(Changed(Class(A))[ tparams: List((type T,type T))], Changed(Definition(A.<init>))[constructor A changed from ()A[T] to ()A[T] flags: <method>]))
+invalidate B.scala because it references changed class [Changed(Class(A))[ tparams: List((type T,type T))]]
+compiling Set(B.scala)
+B.scala:2: error: type mismatch;
+ found   : A[Int]
+ required: A[Any]
+  val a: A[Any] = new A[Int]
+                  ^
diff --git a/test/files/buildmanager/t2653/t2653.test b/test/files/buildmanager/t2653/t2653.test
new file mode 100644
index 0000000..6f3bd03
--- /dev/null
+++ b/test/files/buildmanager/t2653/t2653.test
@@ -0,0 +1,3 @@
+>>compile A.scala B.scala
+>>update A.scala=>A2.scala
+>>compile A.scala
diff --git a/test/files/buildmanager/t2654/A.scala b/test/files/buildmanager/t2654/A.scala
new file mode 100644
index 0000000..75f396d
--- /dev/null
+++ b/test/files/buildmanager/t2654/A.scala
@@ -0,0 +1,2 @@
+class A
+
diff --git a/test/files/buildmanager/t2654/B.scala b/test/files/buildmanager/t2654/B.scala
new file mode 100644
index 0000000..a18aec3
--- /dev/null
+++ b/test/files/buildmanager/t2654/B.scala
@@ -0,0 +1 @@
+class B extends A
diff --git a/test/files/buildmanager/t2654/t2654.changes/A2.scala b/test/files/buildmanager/t2654/t2654.changes/A2.scala
new file mode 100644
index 0000000..c302edb
--- /dev/null
+++ b/test/files/buildmanager/t2654/t2654.changes/A2.scala
@@ -0,0 +1,4 @@
+class A {
+  private def x = 5
+}
+
diff --git a/test/files/buildmanager/t2654/t2654.check b/test/files/buildmanager/t2654/t2654.check
new file mode 100644
index 0000000..68f6e8e
--- /dev/null
+++ b/test/files/buildmanager/t2654/t2654.check
@@ -0,0 +1,6 @@
+builder > A.scala B.scala
+compiling Set(A.scala, B.scala)
+Changes: Map()
+builder > A.scala
+compiling Set(A.scala)
+Changes: Map(class A -> List())
diff --git a/test/files/buildmanager/t2654/t2654.test b/test/files/buildmanager/t2654/t2654.test
new file mode 100644
index 0000000..6f3bd03
--- /dev/null
+++ b/test/files/buildmanager/t2654/t2654.test
@@ -0,0 +1,3 @@
+>>compile A.scala B.scala
+>>update A.scala=>A2.scala
+>>compile A.scala
diff --git a/test/files/buildmanager/t2655/A.scala b/test/files/buildmanager/t2655/A.scala
new file mode 100644
index 0000000..b2c54ac
--- /dev/null
+++ b/test/files/buildmanager/t2655/A.scala
@@ -0,0 +1,4 @@
+object A {
+  def x(i: => String) = ()
+}
+
diff --git a/test/files/buildmanager/t2655/B.scala b/test/files/buildmanager/t2655/B.scala
new file mode 100644
index 0000000..6c1918c
--- /dev/null
+++ b/test/files/buildmanager/t2655/B.scala
@@ -0,0 +1,3 @@
+object B {
+  val x = A.x("3")
+}
diff --git a/test/files/buildmanager/t2655/t2655.changes/A2.scala b/test/files/buildmanager/t2655/t2655.changes/A2.scala
new file mode 100644
index 0000000..0d6a7c6
--- /dev/null
+++ b/test/files/buildmanager/t2655/t2655.changes/A2.scala
@@ -0,0 +1,4 @@
+object A {
+  def x(i: Function0[String]) = ()
+}
+
diff --git a/test/files/buildmanager/t2655/t2655.check b/test/files/buildmanager/t2655/t2655.check
new file mode 100644
index 0000000..a4a071e
--- /dev/null
+++ b/test/files/buildmanager/t2655/t2655.check
@@ -0,0 +1,13 @@
+builder > A.scala B.scala
+compiling Set(A.scala, B.scala)
+Changes: Map()
+builder > A.scala
+compiling Set(A.scala)
+Changes: Map(object A -> List(Changed(Definition(A.x))[method x changed from (i: Function0)Unit to (i: Function0)Unit flags: <method>]))
+invalidate B.scala because it references changed definition [Changed(Definition(A.x))[method x changed from (i: Function0)Unit to (i: Function0)Unit flags: <method>]]
+compiling Set(B.scala)
+B.scala:2: error: type mismatch;
+ found   : java.lang.String("3")
+ required: () => String
+  val x = A.x("3")
+              ^
diff --git a/test/files/buildmanager/t2655/t2655.test b/test/files/buildmanager/t2655/t2655.test
new file mode 100644
index 0000000..6f3bd03
--- /dev/null
+++ b/test/files/buildmanager/t2655/t2655.test
@@ -0,0 +1,3 @@
+>>compile A.scala B.scala
+>>update A.scala=>A2.scala
+>>compile A.scala
diff --git a/test/files/buildmanager/t2657/A.scala b/test/files/buildmanager/t2657/A.scala
new file mode 100644
index 0000000..2a6c62d
--- /dev/null
+++ b/test/files/buildmanager/t2657/A.scala
@@ -0,0 +1,3 @@
+class A {
+  implicit def y(i: Int): String = i.toString
+}
diff --git a/test/files/buildmanager/t2657/B.scala b/test/files/buildmanager/t2657/B.scala
new file mode 100644
index 0000000..7786989
--- /dev/null
+++ b/test/files/buildmanager/t2657/B.scala
@@ -0,0 +1,4 @@
+object B extends A {
+  val x: String = 3
+}
+
diff --git a/test/files/buildmanager/t2657/t2657.changes/A2.scala b/test/files/buildmanager/t2657/t2657.changes/A2.scala
new file mode 100644
index 0000000..7dc99d4
--- /dev/null
+++ b/test/files/buildmanager/t2657/t2657.changes/A2.scala
@@ -0,0 +1,3 @@
+class A {
+  def y(i: Int): String = i.toString
+}
diff --git a/test/files/buildmanager/t2657/t2657.check b/test/files/buildmanager/t2657/t2657.check
new file mode 100644
index 0000000..9713f66
--- /dev/null
+++ b/test/files/buildmanager/t2657/t2657.check
@@ -0,0 +1,13 @@
+builder > A.scala B.scala
+compiling Set(A.scala, B.scala)
+Changes: Map()
+builder > A.scala
+compiling Set(A.scala)
+Changes: Map(class A -> List(Changed(Definition(A.y))[method y changed from (i: Int)java.lang.String to (i: Int)java.lang.String flags: implicit <method>]))
+invalidate B.scala because inherited method changed [Changed(Definition(A.y))[method y changed from (i: Int)java.lang.String to (i: Int)java.lang.String flags: implicit <method>]]
+compiling Set(B.scala)
+B.scala:2: error: type mismatch;
+ found   : Int(3)
+ required: String
+  val x: String = 3
+                  ^
diff --git a/test/files/buildmanager/t2657/t2657.test b/test/files/buildmanager/t2657/t2657.test
new file mode 100644
index 0000000..6f3bd03
--- /dev/null
+++ b/test/files/buildmanager/t2657/t2657.test
@@ -0,0 +1,3 @@
+>>compile A.scala B.scala
+>>update A.scala=>A2.scala
+>>compile A.scala
diff --git a/test/files/buildmanager/t2789/A.scala b/test/files/buildmanager/t2789/A.scala
new file mode 100644
index 0000000..08d5bc8
--- /dev/null
+++ b/test/files/buildmanager/t2789/A.scala
@@ -0,0 +1,5 @@
+class A {
+  implicit def e: E = new E
+  def x(i: Int)(implicit y: E): String = ""
+}
+class E
diff --git a/test/files/buildmanager/t2789/B.scala b/test/files/buildmanager/t2789/B.scala
new file mode 100644
index 0000000..dcefbee
--- /dev/null
+++ b/test/files/buildmanager/t2789/B.scala
@@ -0,0 +1,3 @@
+object B extends A {
+  val y = x(3)
+}
diff --git a/test/files/buildmanager/t2789/t2789.changes/A2.scala b/test/files/buildmanager/t2789/t2789.changes/A2.scala
new file mode 100644
index 0000000..4ba3814
--- /dev/null
+++ b/test/files/buildmanager/t2789/t2789.changes/A2.scala
@@ -0,0 +1,5 @@
+class A {
+  def e: E = new E
+  def x(i: Int)(implicit y: E): String = ""
+}
+class E
diff --git a/test/files/buildmanager/t2789/t2789.check b/test/files/buildmanager/t2789/t2789.check
new file mode 100644
index 0000000..78c5119
--- /dev/null
+++ b/test/files/buildmanager/t2789/t2789.check
@@ -0,0 +1,11 @@
+builder > A.scala B.scala
+compiling Set(A.scala, B.scala)
+Changes: Map()
+builder > A.scala
+compiling Set(A.scala)
+Changes: Map(class A -> List(Changed(Definition(A.e))[method e changed from ()E to ()E flags: implicit <method>]), class E -> List())
+invalidate B.scala because inherited method changed [Changed(Definition(A.e))[method e changed from ()E to ()E flags: implicit <method>]]
+compiling Set(B.scala)
+B.scala:2: error: could not find implicit value for parameter y: E
+  val y = x(3)
+           ^
diff --git a/test/files/buildmanager/t2789/t2789.test b/test/files/buildmanager/t2789/t2789.test
new file mode 100644
index 0000000..6f3bd03
--- /dev/null
+++ b/test/files/buildmanager/t2789/t2789.test
@@ -0,0 +1,3 @@
+>>compile A.scala B.scala
+>>update A.scala=>A2.scala
+>>compile A.scala
diff --git a/test/files/buildmanager/t2790/A.scala b/test/files/buildmanager/t2790/A.scala
new file mode 100644
index 0000000..6e9c1a9
--- /dev/null
+++ b/test/files/buildmanager/t2790/A.scala
@@ -0,0 +1,5 @@
+object A {
+  def x(f: String, g: Int): Int = g
+  def x(f: Int, g: Int = 3): Int = g
+}
+
diff --git a/test/files/buildmanager/t2790/B.scala b/test/files/buildmanager/t2790/B.scala
new file mode 100644
index 0000000..441055c
--- /dev/null
+++ b/test/files/buildmanager/t2790/B.scala
@@ -0,0 +1,4 @@
+object B {
+  val y = A.x(5)
+}
+
diff --git a/test/files/buildmanager/t2790/t2790.changes/A2.scala b/test/files/buildmanager/t2790/t2790.changes/A2.scala
new file mode 100644
index 0000000..704ef4e
--- /dev/null
+++ b/test/files/buildmanager/t2790/t2790.changes/A2.scala
@@ -0,0 +1,4 @@
+object A {
+  def x(f: String, g: Int = 3): Int = g
+  def x(f: Int, g: Int): Int = g
+}
diff --git a/test/files/buildmanager/t2790/t2790.check b/test/files/buildmanager/t2790/t2790.check
new file mode 100644
index 0000000..3a57d28
--- /dev/null
+++ b/test/files/buildmanager/t2790/t2790.check
@@ -0,0 +1,14 @@
+builder > A.scala B.scala
+compiling Set(A.scala, B.scala)
+Changes: Map()
+builder > A.scala
+compiling Set(A.scala)
+Changes: Map(object A -> List(Added(Definition(A.x)), Changed(Definition(A.x))[value x changed from (f: java.lang.String,g: Int)Int to (f: java.lang.String,g: Int)Int <and> (f: Int,g: Int)Int flags: <method>]))
+invalidate B.scala because it references changed definition [Changed(Definition(A.x))[value x changed from (f: java.lang.String,g: Int)Int to (f: java.lang.String,g: Int)Int <and> (f: Int,g: Int)Int flags: <method>]]
+compiling Set(B.scala)
+B.scala:2: error: type mismatch;
+ found   : Int(5)
+ required: String
+Error occurred in an application involving default arguments.
+  val y = A.x(5)
+              ^
diff --git a/test/files/buildmanager/t2790/t2790.test b/test/files/buildmanager/t2790/t2790.test
new file mode 100644
index 0000000..6f3bd03
--- /dev/null
+++ b/test/files/buildmanager/t2790/t2790.test
@@ -0,0 +1,3 @@
+>>compile A.scala B.scala
+>>update A.scala=>A2.scala
+>>compile A.scala
diff --git a/test/files/buildmanager/t3045/A.java b/test/files/buildmanager/t3045/A.java
new file mode 100644
index 0000000..d1acb00
--- /dev/null
+++ b/test/files/buildmanager/t3045/A.java
@@ -0,0 +1,7 @@
+public interface A {
+  public class C implements A {}
+}
+
+class B {
+  static class C {}
+}
diff --git a/test/files/buildmanager/t3045/t3045.check b/test/files/buildmanager/t3045/t3045.check
new file mode 100644
index 0000000..5e4e71e
--- /dev/null
+++ b/test/files/buildmanager/t3045/t3045.check
@@ -0,0 +1,3 @@
+builder > A.java
+compiling Set(A.java)
+Changes: Map()
diff --git a/test/files/buildmanager/t3045/t3045.test b/test/files/buildmanager/t3045/t3045.test
new file mode 100644
index 0000000..6cf7e35
--- /dev/null
+++ b/test/files/buildmanager/t3045/t3045.test
@@ -0,0 +1 @@
+>>compile A.java
diff --git a/test/files/buildmanager/t3054/bar/Bar.java b/test/files/buildmanager/t3054/bar/Bar.java
new file mode 100644
index 0000000..e1b056d
--- /dev/null
+++ b/test/files/buildmanager/t3054/bar/Bar.java
@@ -0,0 +1,7 @@
+package bar;
+import foo.Foo$;
+
+
+public class Bar {
+  void bar() { Foo$.MODULE$.foo(); }
+}
diff --git a/test/files/buildmanager/t3054/foo/Foo.scala b/test/files/buildmanager/t3054/foo/Foo.scala
new file mode 100644
index 0000000..c4838b9
--- /dev/null
+++ b/test/files/buildmanager/t3054/foo/Foo.scala
@@ -0,0 +1,5 @@
+package foo
+
+class Foo {
+  def foo = println("foo")
+}
diff --git a/test/files/buildmanager/t3054/t3054.check b/test/files/buildmanager/t3054/t3054.check
new file mode 100644
index 0000000..97cca88
--- /dev/null
+++ b/test/files/buildmanager/t3054/t3054.check
@@ -0,0 +1,3 @@
+builder > bar/Bar.java foo/Foo.scala
+compiling Set(bar/Bar.java, foo/Foo.scala)
+Changes: Map()
diff --git a/test/files/buildmanager/t3054/t3054.test b/test/files/buildmanager/t3054/t3054.test
new file mode 100644
index 0000000..903df24
--- /dev/null
+++ b/test/files/buildmanager/t3054/t3054.test
@@ -0,0 +1 @@
+>>compile bar/Bar.java foo/Foo.scala
diff --git a/test/files/buildmanager/t3133/A.java b/test/files/buildmanager/t3133/A.java
new file mode 100644
index 0000000..c4e7f3a
--- /dev/null
+++ b/test/files/buildmanager/t3133/A.java
@@ -0,0 +1,7 @@
+public class A {
+  class Foo {} 
+    
+  public A(Foo a) {}
+    
+  private void bar(Foo z) {}
+}
diff --git a/test/files/buildmanager/t3133/t3133.check b/test/files/buildmanager/t3133/t3133.check
new file mode 100644
index 0000000..5e4e71e
--- /dev/null
+++ b/test/files/buildmanager/t3133/t3133.check
@@ -0,0 +1,3 @@
+builder > A.java
+compiling Set(A.java)
+Changes: Map()
diff --git a/test/files/buildmanager/t3133/t3133.test b/test/files/buildmanager/t3133/t3133.test
new file mode 100644
index 0000000..6cf7e35
--- /dev/null
+++ b/test/files/buildmanager/t3133/t3133.test
@@ -0,0 +1 @@
+>>compile A.java
diff --git a/test/files/cldc/randoms.check b/test/files/cldc/randoms.check
deleted file mode 100644
index e73fdf3..0000000
--- a/test/files/cldc/randoms.check
+++ /dev/null
@@ -1 +0,0 @@
-Execution completed.
diff --git a/test/files/cldc/randoms.scala b/test/files/cldc/randoms.scala
deleted file mode 100644
index d8de997..0000000
--- a/test/files/cldc/randoms.scala
+++ /dev/null
@@ -1,29 +0,0 @@
-import javax.microedition.lcdui._
-import javax.microedition.midlet.MIDlet
-
-class Test extends MIDlet with CommandListener {
-
-  def startApp {
-    val display = Display.getDisplay(this)
-    
-    val mainForm = new Form("randoms")
-    mainForm append "Welcome to the world of MIDlets!"
-    mainForm append "(build with Scala)"
-    val rnd = new Random
-    for (i <- 0 until 10) mainForm append rnd.nextInt.toString
-
-    val exitCommand = new Command("Exit", Command.EXIT, 0)
-    mainForm addCommand exitCommand
-    mainForm setCommandListener this
-
-    display setCurrent mainForm
-  }
-  def pauseApp {}
-
-  def destroyApp(unconditional: Boolean) {}
-
-  def commandAction(c: Command, s: Displayable) {
-    if (c.getCommandType == Command.EXIT)
-      notifyDestroyed
-  }
-}
diff --git a/test/files/cli/test1/Main.check.scalac b/test/files/cli/test1/Main.check.scalac
deleted file mode 100644
index 22020d9..0000000
--- a/test/files/cli/test1/Main.check.scalac
+++ /dev/null
@@ -1,63 +0,0 @@
-scalac error: bad option: '-dd'
-  scalac -help  gives more information
-Usage: scalac <options | source files>
-where possible options include: 
-  -doc                            Generate documentation
-  -g:<g>                          Generate debugging info (none,source,line,vars,notc)
-  -nowarn                         Generate no warnings
-  -noassert                       Generate no assertions and assumptions
-  -verbose                        Output messages about what the compiler is doing
-  -classpath <path>               Specify where to find user class files
-  -sourcepath <path>              Specify where to find input source files
-  -bootclasspath <path>           Override location of bootstrap class files
-  -extdirs <dirs>                 Override location of installed extensions
-  -d <directory>                  Specify where to place generated class files
-  -encoding <encoding>            Specify character encoding used by source files
-  -windowtitle <windowtitle>      Specify window title of generated HTML documentation
-  -documenttitle <documenttitle>  Specify document title of generated HTML documentation
-  -target:<target>                Specify which backend to use (jvm-1.5,jvm-1.4,msil,cldc)
-  -migrate                        Assist in migrating from Scala version 1.0
-  -o <file>                       Name of the output assembly (only relevant with -target:msil)
-  -r <path>                       List of assemblies referenced by the program (only relevant with -target:msil)
-  -debug                          Output debugging messages
-  -deprecation                    enable detailed deprecation warnings
-  -unchecked                      enable detailed unchecked warnings
-  -statistics                     Print compiler statistics
-  -explaintypes                   Explain type errors in more detail
-  -resident                       Compiler stays resident, files to compile are read from standard input
-  -uniqid                         Print identifiers with unique names (debugging option)
-  -printtypes                     Print tree types (debugging option)
-  -prompt                         Display a prompt after each error (debugging option)
-  -noimports                      Compile without any implicit imports
-  -nopredefs                      Compile without any implicit predefined values
-  -skip:<phase>                   Skip <phase>
-  -check:<phase>                  Check the tree at start of <phase>
-  -print:<phase>                  Print out program after <phase>
-  -printer:<printer>              Printer to use (text,html)
-  -printfile <file>               Specify file in which to print trees
-  -graph:<phase>                  Graph the program after <phase>
-  -browse:<phase>                 Browse the abstract syntax tree after <phase>
-  -stop:<phase>                   Stop after phase <phase>
-  -log:<phase>                    Log operations in <phase>
-  -logall                         Log all operations
-  -version                        Print product version and exit
-  -help                           Print a synopsis of standard options
-  -nouescape                      disables handling of \u unicode escapes
-  -Xinline                        Perform inlining when possible
-  -XO                             Optimize. implies -Xinline, -Xcloselim and -Xdce
-  -Xcloselim                      Perform closure elimination
-  -Xdce                           Perform dead code elimination
-  -Xwarndeadcode                  Emit warnings for dead code
-  -XbytecodeRead                  Enable bytecode reader.
-  -Xdetach                        Perform detaching of remote closures
-  -Xshowcls <class>               Show class info
-  -Xshowobj <object>              Show object info
-  -Xlinearizer:<Xlinearizer>      Linearizer to use (normal,dfs,rpo,dump)
-  -Xgenerics                      Use generic Java types
-  -Xprintpos                      Print tree positions (as offsets)
-  -Xscript                        compile script file
-  -Xexperimental                  enable experimental extensions
-  -Xplugtypes                     parse but ignore annotations in more locations
-  -Xkilloption                    optimizes option types
-
-one error found
diff --git a/test/files/cli/test2/Main.check.scalac b/test/files/cli/test2/Main.check.scalac
deleted file mode 100644
index 22020d9..0000000
--- a/test/files/cli/test2/Main.check.scalac
+++ /dev/null
@@ -1,63 +0,0 @@
-scalac error: bad option: '-dd'
-  scalac -help  gives more information
-Usage: scalac <options | source files>
-where possible options include: 
-  -doc                            Generate documentation
-  -g:<g>                          Generate debugging info (none,source,line,vars,notc)
-  -nowarn                         Generate no warnings
-  -noassert                       Generate no assertions and assumptions
-  -verbose                        Output messages about what the compiler is doing
-  -classpath <path>               Specify where to find user class files
-  -sourcepath <path>              Specify where to find input source files
-  -bootclasspath <path>           Override location of bootstrap class files
-  -extdirs <dirs>                 Override location of installed extensions
-  -d <directory>                  Specify where to place generated class files
-  -encoding <encoding>            Specify character encoding used by source files
-  -windowtitle <windowtitle>      Specify window title of generated HTML documentation
-  -documenttitle <documenttitle>  Specify document title of generated HTML documentation
-  -target:<target>                Specify which backend to use (jvm-1.5,jvm-1.4,msil,cldc)
-  -migrate                        Assist in migrating from Scala version 1.0
-  -o <file>                       Name of the output assembly (only relevant with -target:msil)
-  -r <path>                       List of assemblies referenced by the program (only relevant with -target:msil)
-  -debug                          Output debugging messages
-  -deprecation                    enable detailed deprecation warnings
-  -unchecked                      enable detailed unchecked warnings
-  -statistics                     Print compiler statistics
-  -explaintypes                   Explain type errors in more detail
-  -resident                       Compiler stays resident, files to compile are read from standard input
-  -uniqid                         Print identifiers with unique names (debugging option)
-  -printtypes                     Print tree types (debugging option)
-  -prompt                         Display a prompt after each error (debugging option)
-  -noimports                      Compile without any implicit imports
-  -nopredefs                      Compile without any implicit predefined values
-  -skip:<phase>                   Skip <phase>
-  -check:<phase>                  Check the tree at start of <phase>
-  -print:<phase>                  Print out program after <phase>
-  -printer:<printer>              Printer to use (text,html)
-  -printfile <file>               Specify file in which to print trees
-  -graph:<phase>                  Graph the program after <phase>
-  -browse:<phase>                 Browse the abstract syntax tree after <phase>
-  -stop:<phase>                   Stop after phase <phase>
-  -log:<phase>                    Log operations in <phase>
-  -logall                         Log all operations
-  -version                        Print product version and exit
-  -help                           Print a synopsis of standard options
-  -nouescape                      disables handling of \u unicode escapes
-  -Xinline                        Perform inlining when possible
-  -XO                             Optimize. implies -Xinline, -Xcloselim and -Xdce
-  -Xcloselim                      Perform closure elimination
-  -Xdce                           Perform dead code elimination
-  -Xwarndeadcode                  Emit warnings for dead code
-  -XbytecodeRead                  Enable bytecode reader.
-  -Xdetach                        Perform detaching of remote closures
-  -Xshowcls <class>               Show class info
-  -Xshowobj <object>              Show object info
-  -Xlinearizer:<Xlinearizer>      Linearizer to use (normal,dfs,rpo,dump)
-  -Xgenerics                      Use generic Java types
-  -Xprintpos                      Print tree positions (as offsets)
-  -Xscript                        compile script file
-  -Xexperimental                  enable experimental extensions
-  -Xplugtypes                     parse but ignore annotations in more locations
-  -Xkilloption                    optimizes option types
-
-one error found
diff --git a/test/files/cli/test3/Main.check.scalac b/test/files/cli/test3/Main.check.scalac
deleted file mode 100644
index 22020d9..0000000
--- a/test/files/cli/test3/Main.check.scalac
+++ /dev/null
@@ -1,63 +0,0 @@
-scalac error: bad option: '-dd'
-  scalac -help  gives more information
-Usage: scalac <options | source files>
-where possible options include: 
-  -doc                            Generate documentation
-  -g:<g>                          Generate debugging info (none,source,line,vars,notc)
-  -nowarn                         Generate no warnings
-  -noassert                       Generate no assertions and assumptions
-  -verbose                        Output messages about what the compiler is doing
-  -classpath <path>               Specify where to find user class files
-  -sourcepath <path>              Specify where to find input source files
-  -bootclasspath <path>           Override location of bootstrap class files
-  -extdirs <dirs>                 Override location of installed extensions
-  -d <directory>                  Specify where to place generated class files
-  -encoding <encoding>            Specify character encoding used by source files
-  -windowtitle <windowtitle>      Specify window title of generated HTML documentation
-  -documenttitle <documenttitle>  Specify document title of generated HTML documentation
-  -target:<target>                Specify which backend to use (jvm-1.5,jvm-1.4,msil,cldc)
-  -migrate                        Assist in migrating from Scala version 1.0
-  -o <file>                       Name of the output assembly (only relevant with -target:msil)
-  -r <path>                       List of assemblies referenced by the program (only relevant with -target:msil)
-  -debug                          Output debugging messages
-  -deprecation                    enable detailed deprecation warnings
-  -unchecked                      enable detailed unchecked warnings
-  -statistics                     Print compiler statistics
-  -explaintypes                   Explain type errors in more detail
-  -resident                       Compiler stays resident, files to compile are read from standard input
-  -uniqid                         Print identifiers with unique names (debugging option)
-  -printtypes                     Print tree types (debugging option)
-  -prompt                         Display a prompt after each error (debugging option)
-  -noimports                      Compile without any implicit imports
-  -nopredefs                      Compile without any implicit predefined values
-  -skip:<phase>                   Skip <phase>
-  -check:<phase>                  Check the tree at start of <phase>
-  -print:<phase>                  Print out program after <phase>
-  -printer:<printer>              Printer to use (text,html)
-  -printfile <file>               Specify file in which to print trees
-  -graph:<phase>                  Graph the program after <phase>
-  -browse:<phase>                 Browse the abstract syntax tree after <phase>
-  -stop:<phase>                   Stop after phase <phase>
-  -log:<phase>                    Log operations in <phase>
-  -logall                         Log all operations
-  -version                        Print product version and exit
-  -help                           Print a synopsis of standard options
-  -nouescape                      disables handling of \u unicode escapes
-  -Xinline                        Perform inlining when possible
-  -XO                             Optimize. implies -Xinline, -Xcloselim and -Xdce
-  -Xcloselim                      Perform closure elimination
-  -Xdce                           Perform dead code elimination
-  -Xwarndeadcode                  Emit warnings for dead code
-  -XbytecodeRead                  Enable bytecode reader.
-  -Xdetach                        Perform detaching of remote closures
-  -Xshowcls <class>               Show class info
-  -Xshowobj <object>              Show object info
-  -Xlinearizer:<Xlinearizer>      Linearizer to use (normal,dfs,rpo,dump)
-  -Xgenerics                      Use generic Java types
-  -Xprintpos                      Print tree positions (as offsets)
-  -Xscript                        compile script file
-  -Xexperimental                  enable experimental extensions
-  -Xplugtypes                     parse but ignore annotations in more locations
-  -Xkilloption                    optimizes option types
-
-one error found
diff --git a/test/files/cli/test3/Main.java b/test/files/cli/test3/Main.java
deleted file mode 100644
index 89800b4..0000000
--- a/test/files/cli/test3/Main.java
+++ /dev/null
@@ -1,10 +0,0 @@
-// @info 2 dependency
-package test3;
-public class Main {
-  public static void main(String args[]) {
-    System.out.print("3: ");
-    test1.Main.main(args);
-    System.out.print("3: ");
-    test2.Main.main(args);
-  }
-}
\ No newline at end of file
diff --git a/test/files/cli/test3/Main.scala b/test/files/cli/test3/Main.scala
deleted file mode 100644
index c97e18c..0000000
--- a/test/files/cli/test3/Main.scala
+++ /dev/null
@@ -1,10 +0,0 @@
-// @info 2 dependencies
-package test3
-object Main {
-  def main(args: Array[String]) = {
-    Console.print("3: ")
-    test1.Main.main(args)
-    Console.print("3: ")
-    test2.Main.main(args)
-  }
-}
\ No newline at end of file
diff --git a/test/files/continuations-neg/function0.check b/test/files/continuations-neg/function0.check
new file mode 100644
index 0000000..0a66763
--- /dev/null
+++ b/test/files/continuations-neg/function0.check
@@ -0,0 +1,6 @@
+function0.scala:11: error: type mismatch;
+ found   : () => Int @scala.util.continuations.cpsParam[Int,Int]
+ required: () => Int
+    val g: () => Int = f
+                       ^
+one error found
diff --git a/test/files/continuations-neg/function0.scala b/test/files/continuations-neg/function0.scala
new file mode 100644
index 0000000..6ef0d98
--- /dev/null
+++ b/test/files/continuations-neg/function0.scala
@@ -0,0 +1,16 @@
+// $Id$
+
+import scala.util.continuations._
+
+
+object Test {
+ 
+  def main(args: Array[String]): Any = {
+    
+    val f = () => shift { k: (Int=>Int) => k(7) }
+    val g: () => Int = f
+    
+    println(reset(g()))
+  }
+  
+}
\ No newline at end of file
diff --git a/test/files/continuations-neg/function2.check b/test/files/continuations-neg/function2.check
new file mode 100644
index 0000000..4833057
--- /dev/null
+++ b/test/files/continuations-neg/function2.check
@@ -0,0 +1,6 @@
+function2.scala:11: error: type mismatch;
+ found   : () => Int
+ required: () => Int @util.continuations.package.cps[Int]
+    val g: () => Int @cps[Int] = f
+                                 ^
+one error found
diff --git a/test/files/continuations-neg/function2.scala b/test/files/continuations-neg/function2.scala
new file mode 100644
index 0000000..402c6dc
--- /dev/null
+++ b/test/files/continuations-neg/function2.scala
@@ -0,0 +1,16 @@
+// $Id$
+
+import scala.util.continuations._
+
+
+object Test {
+ 
+  def main(args: Array[String]): Any = {
+    
+    val f = () => 7
+    val g: () => Int @cps[Int] = f
+    
+    println(reset(g()))
+  }
+  
+}
\ No newline at end of file
diff --git a/test/files/continuations-neg/function3.check b/test/files/continuations-neg/function3.check
new file mode 100644
index 0000000..4705ad9
--- /dev/null
+++ b/test/files/continuations-neg/function3.check
@@ -0,0 +1,6 @@
+function3.scala:10: error: type mismatch;
+ found   : Int @scala.util.continuations.cpsParam[Int,Int]
+ required: Int
+    val g: () => Int = () => shift { k: (Int=>Int) => k(7) }
+                                   ^
+one error found
diff --git a/test/files/continuations-neg/function3.scala b/test/files/continuations-neg/function3.scala
new file mode 100644
index 0000000..c4acc4c
--- /dev/null
+++ b/test/files/continuations-neg/function3.scala
@@ -0,0 +1,15 @@
+// $Id$
+
+import scala.util.continuations._
+
+
+object Test {
+ 
+  def main(args: Array[String]): Any = {
+    
+    val g: () => Int = () => shift { k: (Int=>Int) => k(7) }
+    
+    println(reset(g()))
+  }
+  
+}
\ No newline at end of file
diff --git a/test/files/continuations-neg/infer0.check b/test/files/continuations-neg/infer0.check
new file mode 100644
index 0000000..1dd072e
--- /dev/null
+++ b/test/files/continuations-neg/infer0.check
@@ -0,0 +1,4 @@
+infer0.scala:11: error: cannot cps-transform expression 8: type arguments [Int(8),String,Int] do not conform to method shiftUnit's type parameter bounds [A,B,C >: B]
+    test(8)
+         ^
+one error found
diff --git a/test/files/continuations-neg/infer0.scala b/test/files/continuations-neg/infer0.scala
new file mode 100644
index 0000000..9cf69c5
--- /dev/null
+++ b/test/files/continuations-neg/infer0.scala
@@ -0,0 +1,14 @@
+// $Id$
+
+import scala.util.continuations._
+
+
+object Test {
+ 
+  def test(x: => Int @cpsParam[String,Int]) = 7
+  
+  def main(args: Array[String]): Any = {
+    test(8)
+  }
+  
+}
\ No newline at end of file
diff --git a/test/files/continuations-neg/infer2.check b/test/files/continuations-neg/infer2.check
new file mode 100644
index 0000000..59eb670
--- /dev/null
+++ b/test/files/continuations-neg/infer2.check
@@ -0,0 +1,4 @@
+infer2.scala:14: error: illegal answer type modification: scala.util.continuations.cpsParam[String,Int] andThen scala.util.continuations.cpsParam[String,Int]
+    test { sym(); sym() }    
+         ^
+one error found
diff --git a/test/files/continuations-neg/infer2.scala b/test/files/continuations-neg/infer2.scala
new file mode 100644
index 0000000..eaffbc1
--- /dev/null
+++ b/test/files/continuations-neg/infer2.scala
@@ -0,0 +1,19 @@
+// $Id$
+
+import scala.util.continuations._
+
+
+object Test {
+ 
+  def test(x: => Int @cpsParam[String,Int]) = 7
+  
+  def sym() = shift { k: (Int => String) => 9 }
+  
+  
+  def main(args: Array[String]): Any = {
+    test { sym(); sym() }    
+  }
+  
+}
+
+
diff --git a/test/files/continuations-neg/lazy.check b/test/files/continuations-neg/lazy.check
new file mode 100644
index 0000000..bfa44c5
--- /dev/null
+++ b/test/files/continuations-neg/lazy.check
@@ -0,0 +1,6 @@
+lazy.scala:5: error: type mismatch;
+ found   : Unit @scala.util.continuations.cpsParam[Unit,Unit]
+ required: Unit
+  def foo = {
+            ^
+one error found
diff --git a/test/files/continuations-neg/lazy.scala b/test/files/continuations-neg/lazy.scala
new file mode 100644
index 0000000..d150d5f
--- /dev/null
+++ b/test/files/continuations-neg/lazy.scala
@@ -0,0 +1,16 @@
+import scala.util.continuations._ 
+ 
+object Test { 
+
+  def foo = {
+    lazy val x = shift((k:Unit=>Unit)=>k())
+    println(x)
+  }
+ 
+  def main(args: Array[String]) { 
+    reset {
+      foo
+    }
+  } 
+	
+}
\ No newline at end of file
diff --git a/test/files/continuations-neg/t1929.check b/test/files/continuations-neg/t1929.check
new file mode 100644
index 0000000..f42c3a1
--- /dev/null
+++ b/test/files/continuations-neg/t1929.check
@@ -0,0 +1,6 @@
+t1929.scala:8: error: type mismatch;
+ found   : Int @scala.util.continuations.cpsParam[String,java.lang.String] @scala.util.continuations.cpsSynth
+ required: Int @scala.util.continuations.cpsParam[Int,java.lang.String]
+    reset {
+          ^
+one error found
diff --git a/test/files/continuations-neg/t1929.scala b/test/files/continuations-neg/t1929.scala
new file mode 100644
index 0000000..02eda91
--- /dev/null
+++ b/test/files/continuations-neg/t1929.scala
@@ -0,0 +1,17 @@
+// $Id$
+
+import scala.util.continuations._
+
+
+object Test {
+  def main(args : Array[String]) {
+    reset {
+      println("up")
+      val x = shift((k:Int=>String) => k(8) + k(2))
+      println("down " + x)
+      val y = shift((k:Int=>String) => k(3))
+      println("down2 " + y)
+      y + x
+  	}
+  }
+}
\ No newline at end of file
diff --git a/test/files/continuations-neg/t2285.check b/test/files/continuations-neg/t2285.check
new file mode 100644
index 0000000..d5dff6a
--- /dev/null
+++ b/test/files/continuations-neg/t2285.check
@@ -0,0 +1,6 @@
+t2285.scala:9: error: type mismatch;
+ found   : Int @scala.util.continuations.cpsParam[String,String] @scala.util.continuations.cpsSynth
+ required: Int @scala.util.continuations.cpsParam[Int,String]
+  def foo() = reset { bar(); 7 }
+                    ^
+one error found
diff --git a/test/files/continuations-neg/t2285.scala b/test/files/continuations-neg/t2285.scala
new file mode 100644
index 0000000..b906dc4
--- /dev/null
+++ b/test/files/continuations-neg/t2285.scala
@@ -0,0 +1,11 @@
+// $Id$
+
+import scala.util.continuations._
+
+object Test {
+
+  def bar() = shift { k: (String => String) => k("1") }
+ 
+  def foo() = reset { bar(); 7 }
+        
+}
diff --git a/test/files/continuations-neg/t2949.check b/test/files/continuations-neg/t2949.check
new file mode 100644
index 0000000..dd97688
--- /dev/null
+++ b/test/files/continuations-neg/t2949.check
@@ -0,0 +1,6 @@
+t2949.scala:13: error: type mismatch;
+ found   : Int
+ required: ? @scala.util.continuations.cpsParam[List[?],Any]
+    x * y
+      ^
+one error found
diff --git a/test/files/continuations-neg/t2949.scala b/test/files/continuations-neg/t2949.scala
new file mode 100644
index 0000000..2d426a4
--- /dev/null
+++ b/test/files/continuations-neg/t2949.scala
@@ -0,0 +1,15 @@
+// $Id$
+
+import scala.util.continuations._
+
+object Test {
+
+  def reflect[A,B](xs : List[A]) = shift{ xs.flatMap[B, List[B]] }
+  def reify[A, B](x : A @cpsParam[List[A], B]) = reset{ List(x) }
+
+  def main(args: Array[String]): Unit = println(reify {
+    val x = reflect[Int, Int](List(1,2,3)) 
+    val y = reflect[Int, Int](List(2,4,8))
+    x * y
+  })
+}
diff --git a/test/files/continuations-neg/trycatch2.check b/test/files/continuations-neg/trycatch2.check
new file mode 100644
index 0000000..5ff2838
--- /dev/null
+++ b/test/files/continuations-neg/trycatch2.check
@@ -0,0 +1,7 @@
+trycatch2.scala:11: error: only simple cps types allowed in try/catch blocks (found: Int @scala.util.continuations.cpsParam[String,Int])
+  def foo1 = try {
+             ^
+trycatch2.scala:19: error: only simple cps types allowed in try/catch blocks (found: Int @scala.util.continuations.cpsParam[String,Int])
+  def foo2 = try {
+             ^
+two errors found
diff --git a/test/files/continuations-neg/trycatch2.scala b/test/files/continuations-neg/trycatch2.scala
new file mode 100644
index 0000000..d614191
--- /dev/null
+++ b/test/files/continuations-neg/trycatch2.scala
@@ -0,0 +1,33 @@
+// $Id$
+
+import scala.util.continuations._
+
+object Test {
+
+  def fatal[T]: T = throw new Exception
+  def cpsIntStringInt = shift { k:(Int=>String) => k(3); 7 }
+  def cpsIntIntString = shift { k:(Int=>Int) => k(3); "7" }
+  
+  def foo1 = try {
+    fatal[Int]
+    cpsIntStringInt
+  } catch {
+    case ex =>
+      cpsIntStringInt
+  }
+
+  def foo2 = try {
+    fatal[Int]
+    cpsIntStringInt
+  } catch {
+    case ex =>
+      cpsIntStringInt
+  }
+
+
+  def main(args: Array[String]): Unit = {
+    println(reset { foo1; "3" })
+    println(reset { foo2; "3" })
+  }
+
+}
\ No newline at end of file
diff --git a/test/files/continuations-run/basics.check b/test/files/continuations-run/basics.check
new file mode 100644
index 0000000..54c059f
--- /dev/null
+++ b/test/files/continuations-run/basics.check
@@ -0,0 +1,2 @@
+28
+28
\ No newline at end of file
diff --git a/test/files/continuations-run/basics.scala b/test/files/continuations-run/basics.scala
new file mode 100644
index 0000000..b63710b
--- /dev/null
+++ b/test/files/continuations-run/basics.scala
@@ -0,0 +1,23 @@
+// $Id$
+
+import scala.util.continuations._
+
+
+object Test {
+
+  def m0() = {
+    shift((k:Int => Int) => k(k(7))) * 2
+  }
+
+  def m1() = {
+    2 * shift((k:Int => Int) => k(k(7)))
+  }
+
+  def main(args: Array[String]) = {
+    
+    println(reset(m0()))
+    println(reset(m1()))
+    
+  }
+  
+}
diff --git a/test/files/continuations-run/function1.check b/test/files/continuations-run/function1.check
new file mode 100644
index 0000000..7f8f011
--- /dev/null
+++ b/test/files/continuations-run/function1.check
@@ -0,0 +1 @@
+7
diff --git a/test/files/continuations-run/function1.scala b/test/files/continuations-run/function1.scala
new file mode 100644
index 0000000..fbd413e
--- /dev/null
+++ b/test/files/continuations-run/function1.scala
@@ -0,0 +1,16 @@
+// $Id$
+
+import scala.util.continuations._
+
+
+object Test {
+ 
+  def main(args: Array[String]): Any = {
+    
+    val f = () => shift { k: (Int=>Int) => k(7) }
+    val g: () => Int @cps[Int] = f
+    
+    println(reset(g()))
+  }
+  
+}
\ No newline at end of file
diff --git a/test/files/continuations-run/function4.check b/test/files/continuations-run/function4.check
new file mode 100644
index 0000000..c793025
--- /dev/null
+++ b/test/files/continuations-run/function4.check
@@ -0,0 +1 @@
+7
\ No newline at end of file
diff --git a/test/files/continuations-run/function4.scala b/test/files/continuations-run/function4.scala
new file mode 100644
index 0000000..2ccd0b4
--- /dev/null
+++ b/test/files/continuations-run/function4.scala
@@ -0,0 +1,15 @@
+// $Id$
+
+import scala.util.continuations._
+
+
+object Test {
+ 
+  def main(args: Array[String]): Any = {
+    
+    val g: () => Int @cps[Int] = () => shift { k: (Int=>Int) => k(7) }
+    
+    println(reset(g()))
+  }
+  
+}
\ No newline at end of file
diff --git a/test/files/continuations-run/function5.check b/test/files/continuations-run/function5.check
new file mode 100644
index 0000000..c793025
--- /dev/null
+++ b/test/files/continuations-run/function5.check
@@ -0,0 +1 @@
+7
\ No newline at end of file
diff --git a/test/files/continuations-run/function5.scala b/test/files/continuations-run/function5.scala
new file mode 100644
index 0000000..fe528e1
--- /dev/null
+++ b/test/files/continuations-run/function5.scala
@@ -0,0 +1,15 @@
+// $Id$
+
+import scala.util.continuations._
+
+
+object Test {
+ 
+  def main(args: Array[String]): Any = {
+    
+    val g: () => Int @cps[Int] = () => 7
+    
+    println(reset(g()))
+  }
+  
+}
\ No newline at end of file
diff --git a/test/files/continuations-run/function6.check b/test/files/continuations-run/function6.check
new file mode 100644
index 0000000..c793025
--- /dev/null
+++ b/test/files/continuations-run/function6.check
@@ -0,0 +1 @@
+7
\ No newline at end of file
diff --git a/test/files/continuations-run/function6.scala b/test/files/continuations-run/function6.scala
new file mode 100644
index 0000000..54a6ffc
--- /dev/null
+++ b/test/files/continuations-run/function6.scala
@@ -0,0 +1,16 @@
+// $Id$
+
+import scala.util.continuations._
+
+
+object Test {
+ 
+  def main(args: Array[String]): Any = {
+    
+    val g: PartialFunction[Int, Int @cps[Int]] = { case x => 7 }
+    
+    println(reset(g(2)))
+    
+  }
+  
+}
\ No newline at end of file
diff --git a/test/files/continuations-run/ifelse0.check b/test/files/continuations-run/ifelse0.check
new file mode 100644
index 0000000..f8bc798
--- /dev/null
+++ b/test/files/continuations-run/ifelse0.check
@@ -0,0 +1,2 @@
+10
+9
\ No newline at end of file
diff --git a/test/files/continuations-run/ifelse0.scala b/test/files/continuations-run/ifelse0.scala
new file mode 100644
index 0000000..2facab4
--- /dev/null
+++ b/test/files/continuations-run/ifelse0.scala
@@ -0,0 +1,18 @@
+// $Id$
+
+import scala.util.continuations._
+
+
+object Test {
+ 
+  def test(x:Int) = if (x <= 7)
+    shift { k: (Int=>Int) => k(k(k(x))) }
+  else
+    shift { k: (Int=>Int) => k(x) }
+  
+  def main(args: Array[String]): Any = {
+    println(reset(1 + test(7)))
+    println(reset(1 + test(8)))
+  }
+  
+}
\ No newline at end of file
diff --git a/test/files/continuations-run/ifelse1.check b/test/files/continuations-run/ifelse1.check
new file mode 100644
index 0000000..86a3fbc
--- /dev/null
+++ b/test/files/continuations-run/ifelse1.check
@@ -0,0 +1,4 @@
+10
+9
+8
+11
\ No newline at end of file
diff --git a/test/files/continuations-run/ifelse1.scala b/test/files/continuations-run/ifelse1.scala
new file mode 100644
index 0000000..c624b84
--- /dev/null
+++ b/test/files/continuations-run/ifelse1.scala
@@ -0,0 +1,25 @@
+// $Id$
+
+import scala.util.continuations._
+
+
+object Test {
+ 
+  def test1(x:Int) = if (x <= 7)
+    shift { k: (Int=>Int) => k(k(k(x))) }
+  else
+    x
+  
+  def test2(x:Int) = if (x <= 7)
+    x
+  else
+    shift { k: (Int=>Int) => k(k(k(x))) }
+
+  def main(args: Array[String]): Any = {
+    println(reset(1 + test1(7)))
+    println(reset(1 + test1(8)))
+    println(reset(1 + test2(7)))
+    println(reset(1 + test2(8)))
+  }
+  
+}
\ No newline at end of file
diff --git a/test/files/continuations-run/ifelse2.check b/test/files/continuations-run/ifelse2.check
new file mode 100644
index 0000000..f97a95b
--- /dev/null
+++ b/test/files/continuations-run/ifelse2.check
@@ -0,0 +1,4 @@
+abort
+()
+alive
+()
diff --git a/test/files/continuations-run/ifelse2.scala b/test/files/continuations-run/ifelse2.scala
new file mode 100644
index 0000000..506acc4
--- /dev/null
+++ b/test/files/continuations-run/ifelse2.scala
@@ -0,0 +1,16 @@
+// $Id$
+
+import scala.util.continuations._
+
+
+object Test {
+ 
+  def test(x:Int) = if (x <= 7)
+    shift { k: (Unit=>Unit) => println("abort") }
+  
+  def main(args: Array[String]): Any = {
+    println(reset{ test(7); println("alive") })
+    println(reset{ test(8); println("alive") })
+  }
+  
+}
\ No newline at end of file
diff --git a/test/files/continuations-run/ifelse3.check b/test/files/continuations-run/ifelse3.check
new file mode 100644
index 0000000..95b562c
--- /dev/null
+++ b/test/files/continuations-run/ifelse3.check
@@ -0,0 +1,2 @@
+6
+9
diff --git a/test/files/continuations-run/ifelse3.scala b/test/files/continuations-run/ifelse3.scala
new file mode 100644
index 0000000..54566a4
--- /dev/null
+++ b/test/files/continuations-run/ifelse3.scala
@@ -0,0 +1,21 @@
+// $Id$
+
+import scala.util.continuations._
+
+
+object Test {
+ 
+  def util(x: Boolean) = shift { k: (Boolean=>Int) => k(x) }
+ 
+  def test(x:Int) = if (util(x <= 7))
+    x - 1
+  else
+    x + 1
+    
+  
+  def main(args: Array[String]): Any = {
+    println(reset(test(7)))
+    println(reset(test(8)))
+  }
+  
+}
\ No newline at end of file
diff --git a/test/files/continuations-run/infer1.scala b/test/files/continuations-run/infer1.scala
new file mode 100644
index 0000000..1082250
--- /dev/null
+++ b/test/files/continuations-run/infer1.scala
@@ -0,0 +1,33 @@
+// $Id$
+
+import scala.util.continuations._
+
+
+object Test {
+ 
+  def test(x: => Int @cpsParam[String,Int]) = 7
+  
+  def test2() = {
+    val x = shift { k: (Int => String) => 9 }
+    x
+  }
+
+  def test3(x: => Int @cpsParam[Int,Int]) = 7
+
+  
+  def util() = shift { k: (String => String) => "7" }
+  
+  def main(args: Array[String]): Any = {
+    test { shift { k: (Int => String) => 9 } }
+    test { shift { k: (Int => String) => 9 }; 2 }
+//    test { shift { k: (Int => String) => 9 }; util() }  <-- doesn't work
+    test { shift { k: (Int => String) => 9 }; util(); 2 }
+
+
+    test { shift { k: (Int => String) => 9 }; { test3(0); 2 } }
+
+    test3 { { test3(0); 2 } }
+
+  }
+  
+}
\ No newline at end of file
diff --git a/test/files/continuations-run/match0.check b/test/files/continuations-run/match0.check
new file mode 100644
index 0000000..f8bc798
--- /dev/null
+++ b/test/files/continuations-run/match0.check
@@ -0,0 +1,2 @@
+10
+9
\ No newline at end of file
diff --git a/test/files/continuations-run/match0.scala b/test/files/continuations-run/match0.scala
new file mode 100644
index 0000000..b65d343
--- /dev/null
+++ b/test/files/continuations-run/match0.scala
@@ -0,0 +1,18 @@
+// $Id$
+
+import scala.util.continuations._
+
+
+object Test {
+ 
+  def test(x:Int) = x match {
+    case 7 => shift { k: (Int=>Int) => k(k(k(x))) }
+    case 8 => shift { k: (Int=>Int) => k(x) }
+  }
+  
+  def main(args: Array[String]): Any = {
+    println(reset(1 + test(7)))
+    println(reset(1 + test(8)))
+  }
+  
+}
\ No newline at end of file
diff --git a/test/files/continuations-run/match1.check b/test/files/continuations-run/match1.check
new file mode 100644
index 0000000..73053d3
--- /dev/null
+++ b/test/files/continuations-run/match1.check
@@ -0,0 +1,2 @@
+10
+9
diff --git a/test/files/continuations-run/match1.scala b/test/files/continuations-run/match1.scala
new file mode 100644
index 0000000..20671f2
--- /dev/null
+++ b/test/files/continuations-run/match1.scala
@@ -0,0 +1,18 @@
+// $Id$
+
+import scala.util.continuations._
+
+
+object Test {
+ 
+  def test(x:Int) = x match {
+    case 7 => shift { k: (Int=>Int) => k(k(k(x))) }
+    case _ => x
+  }
+  
+  def main(args: Array[String]): Any = {
+    println(reset(1 + test(7)))
+    println(reset(1 + test(8)))
+  }
+  
+}
\ No newline at end of file
diff --git a/test/files/continuations-run/match2.check b/test/files/continuations-run/match2.check
new file mode 100644
index 0000000..cbf9134
--- /dev/null
+++ b/test/files/continuations-run/match2.check
@@ -0,0 +1,2 @@
+B
+B
diff --git a/test/files/continuations-run/match2.scala b/test/files/continuations-run/match2.scala
new file mode 100644
index 0000000..8b0fb94
--- /dev/null
+++ b/test/files/continuations-run/match2.scala
@@ -0,0 +1,26 @@
+// $Id$
+
+import scala.util.continuations._
+
+
+object Test {
+ 
+  def test1() = {
+    val (a, b) = shift { k: (((String,String)) => String) => k("A","B") }
+    b
+  }
+
+  case class Elem[T,U](a: T, b: U)
+  
+  def test2() = {
+    val Elem(a,b) = shift { k: (Elem[String,String] => String) => k(Elem("A","B")) }
+    b
+  }
+
+  
+  def main(args: Array[String]): Any = {
+    println(reset(test1()))
+    println(reset(test2()))
+  }
+  
+}
\ No newline at end of file
diff --git a/test/files/continuations-run/t1807.check b/test/files/continuations-run/t1807.check
new file mode 100644
index 0000000..56a6051
--- /dev/null
+++ b/test/files/continuations-run/t1807.check
@@ -0,0 +1 @@
+1
\ No newline at end of file
diff --git a/test/files/continuations-run/t1807.scala b/test/files/continuations-run/t1807.scala
new file mode 100644
index 0000000..278b3a9
--- /dev/null
+++ b/test/files/continuations-run/t1807.scala
@@ -0,0 +1,14 @@
+// $Id$
+
+import scala.util.continuations._
+
+
+object Test {
+  def main(args: Array[String]): Unit = {
+    val z = reset {
+      val f: (() => Int @cps[Int]) = () => 1
+      f()
+    }
+    println(z)
+  }
+}
\ No newline at end of file
diff --git a/test/files/continuations-run/t1808.scala b/test/files/continuations-run/t1808.scala
new file mode 100644
index 0000000..125c7c1
--- /dev/null
+++ b/test/files/continuations-run/t1808.scala
@@ -0,0 +1,10 @@
+// $Id$
+
+import scala.util.continuations._
+
+
+object Test {
+  def main(args: Array[String]): Unit = {
+    reset0 { 0 }
+  }
+}
\ No newline at end of file
diff --git a/test/files/continuations-run/t1820.scala b/test/files/continuations-run/t1820.scala
new file mode 100644
index 0000000..893ddab
--- /dev/null
+++ b/test/files/continuations-run/t1820.scala
@@ -0,0 +1,14 @@
+// $Id$
+
+import scala.util.continuations._
+
+
+object Test {
+  def shifted: Unit @suspendable = shift { (k: Unit => Unit) => () }
+  def test1(b: => Boolean) = {
+    reset {
+      if (b) shifted
+    }
+  }
+  def main(args: Array[String]) = test1(true)
+}
\ No newline at end of file
diff --git a/test/files/continuations-run/t1821.check b/test/files/continuations-run/t1821.check
new file mode 100644
index 0000000..f7b7611
--- /dev/null
+++ b/test/files/continuations-run/t1821.check
@@ -0,0 +1,4 @@
+()
+()
+()
+()
\ No newline at end of file
diff --git a/test/files/continuations-run/t1821.scala b/test/files/continuations-run/t1821.scala
new file mode 100644
index 0000000..0d5fb55
--- /dev/null
+++ b/test/files/continuations-run/t1821.scala
@@ -0,0 +1,20 @@
+// $Id$
+
+import scala.util.continuations._
+
+
+object Test {
+  def suspended[A](x: A): A @suspendable = x
+  def test1[A](x: A): A @suspendable = suspended(x) match { case x => x }
+  def test2[A](x: List[A]): A @suspendable = suspended(x) match { case List(x) => x }
+
+  def test3[A](x: A): A @suspendable = x match { case x => x }
+  def test4[A](x: List[A]): A @suspendable = x match { case List(x) => x }
+
+  def main(args: Array[String]) = {
+    println(reset(test1()))
+    println(reset(test2(List(()))))
+    println(reset(test3()))
+    println(reset(test4(List(()))))
+  }
+}
\ No newline at end of file
diff --git a/test/files/continuations-run/t2864.check b/test/files/continuations-run/t2864.check
new file mode 100644
index 0000000..d411bb7
--- /dev/null
+++ b/test/files/continuations-run/t2864.check
@@ -0,0 +1 @@
+400
diff --git a/test/files/continuations-run/t2864.scala b/test/files/continuations-run/t2864.scala
new file mode 100644
index 0000000..7a2579e
--- /dev/null
+++ b/test/files/continuations-run/t2864.scala
@@ -0,0 +1,30 @@
+import scala.util.continuations._
+object Test {
+
+  def double[B](n : Int)(k : Int => B) : B = k(n * 2)
+
+  def main(args : Array[String]) {
+     reset {
+       val result1 = shift(double[Unit](100))
+       val result2 = shift(double[Unit](result1))
+       println(result2)
+     }
+  }
+
+  def foo: Int @cps[Int] = {
+    val a0 = shift((k:Int=>Int) => k(0))
+    val x0 = 2
+    val a1 = shift((k:Int=>Int) => x0)
+    0
+  }
+
+/*
+  def bar: ControlContext[Int,Int,Int] = {
+    shiftR((k:Int=>Int) => k(0)).flatMap { a0 =>
+    val x0 = 2
+    shiftR((k:Int=>Int) => x0).map { a1 =>
+    0
+    }}
+  }
+*/
+}
\ No newline at end of file
diff --git a/test/files/continuations-run/t2934.check b/test/files/continuations-run/t2934.check
new file mode 100644
index 0000000..a925865
--- /dev/null
+++ b/test/files/continuations-run/t2934.check
@@ -0,0 +1 @@
+List(3, 4, 5)
diff --git a/test/files/continuations-run/t2934.scala b/test/files/continuations-run/t2934.scala
new file mode 100644
index 0000000..a1b8ca9
--- /dev/null
+++ b/test/files/continuations-run/t2934.scala
@@ -0,0 +1,10 @@
+import scala.util.continuations._
+
+object Test {
+  def main(args : Array[String]) {
+   println(reset {
+     val x = shift(List(1,2,3).flatMap[Int, List[Int]])
+     List(x + 2)
+   })
+  }
+}
diff --git a/test/files/continuations-run/t3199.check b/test/files/continuations-run/t3199.check
new file mode 100644
index 0000000..a065247
--- /dev/null
+++ b/test/files/continuations-run/t3199.check
@@ -0,0 +1 @@
+Right(7)
diff --git a/test/files/continuations-run/t3199.scala b/test/files/continuations-run/t3199.scala
new file mode 100644
index 0000000..7b54793
--- /dev/null
+++ b/test/files/continuations-run/t3199.scala
@@ -0,0 +1,20 @@
+import _root_.scala.collection.Seq 
+import _root_.scala.util.control.Exception 
+import _root_.scala.util.continuations._ 
+ 
+object Test { 
+ 
+  trait AbstractResource[+R <: AnyRef]  { 
+    def reflect[B] : R @cpsParam[B,Either[Throwable, B]] = shift(acquireFor) 
+    def acquireFor[B](f :  R => B) : Either[Throwable, B] = { 
+	      import Exception._ 
+	      catching(List(classOf[Throwable]) : _*) either (f(null.asInstanceOf[R])) 
+	    } 
+	  }   
+	 
+	  def main(args: Array[String]) : Unit = { 
+	     val x = new AbstractResource[String] { } 
+	     val result = x.acquireFor( x =>  7 ) 
+	     println(result) 
+	  } 
+	} 
diff --git a/test/files/continuations-run/t3199b.check b/test/files/continuations-run/t3199b.check
new file mode 100644
index 0000000..b5d8bb5
--- /dev/null
+++ b/test/files/continuations-run/t3199b.check
@@ -0,0 +1 @@
+[1, 2, 3]
diff --git a/test/files/continuations-run/t3199b.scala b/test/files/continuations-run/t3199b.scala
new file mode 100644
index 0000000..2122c96
--- /dev/null
+++ b/test/files/continuations-run/t3199b.scala
@@ -0,0 +1,11 @@
+object Test {
+  
+  def test() = {
+    java.util.Arrays.asList(Array(1,2,3):_*)
+  }
+  
+  def main(args: Array[String]) = {
+    println(test())
+  }
+  
+}
\ No newline at end of file
diff --git a/test/files/continuations-run/t3223.check b/test/files/continuations-run/t3223.check
new file mode 100644
index 0000000..ec63514
--- /dev/null
+++ b/test/files/continuations-run/t3223.check
@@ -0,0 +1 @@
+9
diff --git a/test/files/continuations-run/t3223.scala b/test/files/continuations-run/t3223.scala
new file mode 100644
index 0000000..efed1ff
--- /dev/null
+++ b/test/files/continuations-run/t3223.scala
@@ -0,0 +1,19 @@
+import scala.util.continuations._
+object Test {
+
+  def foo(x:Int) = {
+    try { 
+      throw new Exception
+      shiftUnit0[Int,Int](7)
+    } catch {
+      case ex =>  
+        val g = (a:Int)=>a
+        9
+    }
+  }
+  
+  def main(args: Array[String]) {
+    println(reset(foo(0)))
+  }
+
+}
\ No newline at end of file
diff --git a/test/files/continuations-run/t3225.check b/test/files/continuations-run/t3225.check
new file mode 100644
index 0000000..df1a8a9
--- /dev/null
+++ b/test/files/continuations-run/t3225.check
@@ -0,0 +1,12 @@
+8
+8
+9
+9
+8
+9
+8
+8
+9
+9
+8
+9
diff --git a/test/files/continuations-run/t3225.scala b/test/files/continuations-run/t3225.scala
new file mode 100644
index 0000000..5b6259c
--- /dev/null
+++ b/test/files/continuations-run/t3225.scala
@@ -0,0 +1,56 @@
+// $Id$
+
+import scala.util.continuations._
+
+
+object Test {
+
+  class Bla {
+    val x = 8
+    def y[T] = 9
+  }
+
+/*
+  def bla[A] = shift { k:(Bla=>A) => k(new Bla) }
+*/
+
+  def bla1 = shift { k:(Bla=>Bla) => k(new Bla) }
+  def bla2 = shift { k:(Bla=>Int) => k(new Bla) }
+
+  def fooA = bla2.x
+  def fooB[T] = bla2.y[T]
+
+  def testMono() = {
+    println(reset(bla1).x)
+    println(reset(bla2.x))
+    println(reset(bla2.y[Int]))
+    println(reset(bla2.y))
+    println(reset(fooA))
+    println(reset(fooB))
+    0
+  }
+
+  def blaX[A] = shift { k:(Bla=>A) => k(new Bla) }
+  
+  def fooX[A] = blaX[A].x
+  def fooY[A] = blaX[A].y[A]
+  
+  def testPoly() = {
+    println(reset(blaX[Bla]).x)
+    println(reset(blaX[Int].x))
+    println(reset(blaX[Int].y[Int]))
+    println(reset(blaX[Int].y))
+    println(reset(fooX[Int]))
+    println(reset(fooY[Int]))
+    0
+  }
+
+
+  // TODO: check whether this also applies to a::shift { k => ... }
+
+  def main(args: Array[String]) = {
+    testMono()
+    testPoly()
+  }
+  
+}
diff --git a/test/files/continuations-run/trycatch0.check b/test/files/continuations-run/trycatch0.check
new file mode 100644
index 0000000..3680690
--- /dev/null
+++ b/test/files/continuations-run/trycatch0.check
@@ -0,0 +1,2 @@
+10
+10
\ No newline at end of file
diff --git a/test/files/continuations-run/trycatch0.scala b/test/files/continuations-run/trycatch0.scala
new file mode 100644
index 0000000..ec39863
--- /dev/null
+++ b/test/files/continuations-run/trycatch0.scala
@@ -0,0 +1,25 @@
+// $Id$
+
+import scala.util.continuations._
+
+object Test {
+  
+  def foo = try {
+    shift((k: Int=>Int) => k(7))
+  } catch {
+    case ex =>
+      9
+  }
+
+  def bar = try {
+    7
+  } catch {
+    case ex =>
+    shiftUnit0[Int,Int](9)
+  }
+  
+  def main(args: Array[String]): Unit = {
+    println(reset { foo + 3 })
+    println(reset { bar + 3 })
+  }
+}
\ No newline at end of file
diff --git a/test/files/continuations-run/trycatch1.check b/test/files/continuations-run/trycatch1.check
new file mode 100644
index 0000000..a028d2b
--- /dev/null
+++ b/test/files/continuations-run/trycatch1.check
@@ -0,0 +1,4 @@
+12
+12
+12
+12
\ No newline at end of file
diff --git a/test/files/continuations-run/trycatch1.scala b/test/files/continuations-run/trycatch1.scala
new file mode 100644
index 0000000..10dfd30
--- /dev/null
+++ b/test/files/continuations-run/trycatch1.scala
@@ -0,0 +1,48 @@
+// $Id$
+
+import scala.util.continuations._
+
+object Test {
+
+  def fatal: Int = throw new Exception()
+  
+  def foo1 = try {
+    fatal
+    shift((k: Int=>Int) => k(7))
+  } catch {
+    case ex =>
+      9
+  }
+
+  def foo2 = try {
+    shift((k: Int=>Int) => k(7))
+    fatal
+  } catch {
+    case ex =>
+      9
+  }
+
+  def bar1 = try {
+    fatal
+    7
+  } catch {
+    case ex =>
+      shiftUnit0[Int,Int](9) // regular shift causes no-symbol doesn't have owner
+  }
+
+  def bar2 = try {
+    7
+    fatal
+  } catch {
+    case ex =>
+      shiftUnit0[Int,Int](9) // regular shift causes no-symbol doesn't have owner
+  }
+
+  def main(args: Array[String]): Unit = {
+    println(reset { foo1 + 3 })
+    println(reset { foo2 + 3 })
+    println(reset { bar1 + 3 })
+    println(reset { bar2 + 3 })
+  }
+
+}
\ No newline at end of file
diff --git a/test/files/continuations-run/while0.check b/test/files/continuations-run/while0.check
new file mode 100644
index 0000000..d58c55a
--- /dev/null
+++ b/test/files/continuations-run/while0.check
@@ -0,0 +1 @@
+9000
diff --git a/test/files/continuations-run/while0.scala b/test/files/continuations-run/while0.scala
new file mode 100644
index 0000000..46005a4
--- /dev/null
+++ b/test/files/continuations-run/while0.scala
@@ -0,0 +1,22 @@
+// $Id$
+
+import scala.util.continuations._
+
+
+object Test {
+ 
+  def foo(): Int @cps[Unit] = 2
+  
+  def test(): Unit @cps[Unit] = {
+    var x = 0
+    while (x < 9000) { // pick number large enough to require tail-call opt
+      x += foo()
+    }
+    println(x)
+  }
+
+  def main(args: Array[String]): Any = {
+    reset(test())
+  }
+  
+}
\ No newline at end of file
diff --git a/test/files/continuations-run/while1.check b/test/files/continuations-run/while1.check
new file mode 100644
index 0000000..3d5f0b9
--- /dev/null
+++ b/test/files/continuations-run/while1.check
@@ -0,0 +1,11 @@
+up
+up
+up
+up
+up
+10
+down
+down
+down
+down
+down
diff --git a/test/files/continuations-run/while1.scala b/test/files/continuations-run/while1.scala
new file mode 100644
index 0000000..fd41ab3
--- /dev/null
+++ b/test/files/continuations-run/while1.scala
@@ -0,0 +1,22 @@
+// $Id$
+
+import scala.util.continuations._
+
+
+object Test {
+ 
+  def foo(): Int @cps[Unit] = shift { k => println("up"); k(2); println("down") }
+  
+  def test(): Unit @cps[Unit] = {
+    var x = 0
+    while (x < 9) {
+      x += foo()
+    }
+    println(x)
+  }
+
+  def main(args: Array[String]): Any = {
+    reset(test())
+  }
+  
+}
\ No newline at end of file
diff --git a/test/files/continuations-run/while2.check b/test/files/continuations-run/while2.check
new file mode 100644
index 0000000..9fe5151
--- /dev/null
+++ b/test/files/continuations-run/while2.check
@@ -0,0 +1,19 @@
+up
+up
+up
+up
+up
+up
+up
+up
+up
+9000
+down
+down
+down
+down
+down
+down
+down
+down
+down
diff --git a/test/files/continuations-run/while2.scala b/test/files/continuations-run/while2.scala
new file mode 100644
index 0000000..63f9cb9
--- /dev/null
+++ b/test/files/continuations-run/while2.scala
@@ -0,0 +1,23 @@
+// $Id$
+
+import scala.util.continuations._
+
+
+object Test {
+ 
+  def foo1(): Int @cps[Unit] = 2
+  def foo2(): Int @cps[Unit] = shift { k => println("up"); k(2); println("down") }
+  
+  def test(): Unit @cps[Unit] = {
+    var x = 0
+    while (x < 9000) { // pick number large enough to require tail-call opt
+      x += (if (x % 1000 != 0) foo1() else foo2())
+    }
+    println(x)
+  }
+
+  def main(args: Array[String]): Any = {
+    reset(test())
+  }
+  
+}
\ No newline at end of file
diff --git a/test/files/jvm/JavaInteraction.scala b/test/files/jvm/JavaInteraction.scala
index 26162f7..1316fad 100644
--- a/test/files/jvm/JavaInteraction.scala
+++ b/test/files/jvm/JavaInteraction.scala
@@ -1,7 +1,6 @@
 //############################################################################
 // Test Java interaction
 //############################################################################
-// $Id: JavaInteraction.scala 9110 2006-11-01 16:03:28Z mihaylov $
 
 import java.awt.Color;
 import java.awt.Point;
diff --git a/test/files/jvm/actor-bangbang.scala b/test/files/jvm/actor-bangbang.scala
deleted file mode 100644
index 92a5bcf..0000000
--- a/test/files/jvm/actor-bangbang.scala
+++ /dev/null
@@ -1,47 +0,0 @@
-import scala.actors._
-import scala.actors.Actor._
-
-class MyActor extends Actor {
-  def act() {
-    loop {
-      react {
-        case 'hello =>
-          sender ! 'hello
-        case 'stop =>
-          exit()
-      }
-    }
-  }
-}
-
-object Test {
-  def main(args: Array[String]) {
-    val a = new MyActor
-    a.start()
-
-    val b = new Actor {
-      def act() {
-        react {
-          case r: MyActor =>
-            var i = 0
-            loop {
-              i += 1
-              val ft = r !! 'hello
-              react {
-                case ft.ch ! msg =>
-                  if (i % 10000 == 0)
-                    println(msg)
-                  if (i >= 50000) {
-                    r ! 'stop
-                    exit()
-                  }
-              }
-            }
-        }
-      }
-    }
-    b.start()
-
-    b ! a
-  }
-}
diff --git a/test/files/jvm/actor-bangbang2.scala b/test/files/jvm/actor-bangbang2.scala
deleted file mode 100644
index a071ac3..0000000
--- a/test/files/jvm/actor-bangbang2.scala
+++ /dev/null
@@ -1,45 +0,0 @@
-import scala.actors._
-import scala.actors.Actor._
-
-class MyActor extends Actor {
-  def act() {
-    loop {
-      react {
-        case 'hello =>
-          sender ! 'hello
-        case 'stop =>
-          exit()
-      }
-    }
-  }
-}
-
-object Test {
-  def main(args: Array[String]) {
-    val a = new MyActor
-    a.start()
-
-    val b = new Actor {
-      def act() {
-        react {
-          case r: MyActor =>
-            var i = 0
-            loop {
-              i += 1
-              val ft = r !! 'hello
-              val msg = ft()
-              if (i % 10000 == 0)
-                println(msg)
-              if (i >= 50000) {
-                r ! 'stop
-                exit()
-              }
-            }
-        }
-      }
-    }
-    b.start()
-
-    b ! a
-  }
-}
diff --git a/test/files/jvm/actor-exceptions.check b/test/files/jvm/actor-exceptions.check
new file mode 100644
index 0000000..d86bac9
--- /dev/null
+++ b/test/files/jvm/actor-exceptions.check
@@ -0,0 +1 @@
+OK
diff --git a/test/files/jvm/actor-exceptions.scala b/test/files/jvm/actor-exceptions.scala
new file mode 100644
index 0000000..3ee4db9
--- /dev/null
+++ b/test/files/jvm/actor-exceptions.scala
@@ -0,0 +1,65 @@
+
+import scala.actors.{Actor, Exit}
+import Actor._
+
+case class MyException(text: String) extends Exception {
+  override def fillInStackTrace() = this
+}
+
+case class MyOtherException(text: String) extends Exception {
+  override def fillInStackTrace() = this
+}
+
+object Master extends Actor {
+  trapExit = true
+  def act() {
+    try {
+    link(Slave)
+    Slave.start()
+    for (i <- 0 until 10) Slave ! A
+    react {
+      case Exit(from, reason) =>
+        println("OK")
+    }
+    } catch {
+      case e: Throwable if !e.isInstanceOf[scala.util.control.ControlThrowable] =>
+        e.printStackTrace()
+    }
+  }
+}
+
+object Slave extends Actor {
+  override def toString = "Slave"
+  override def exceptionHandler: PartialFunction[Exception, Unit] = {
+    case MyException(text) =>
+    case other if !other.isInstanceOf[scala.util.control.ControlThrowable] => super.exceptionHandler(other)
+  }
+  def act() {
+    try {
+    var cnt = 0
+    loop {
+      react {
+        case A =>
+          cnt += 1
+          if (cnt % 2 != 0) throw MyException("problem")
+          if (cnt == 10) {
+            throw MyOtherException("unhandled")
+          }
+      }
+    }
+    } catch {
+      case e: Throwable if !e.isInstanceOf[scala.util.control.ControlThrowable] &&
+                           !e.isInstanceOf[MyException] &&
+                           !e.isInstanceOf[MyOtherException] =>
+        e.printStackTrace()
+    }
+  }
+}
+
+case object A
+
+object Test {
+  def main(args: Array[String]) {
+    Master.start()
+  }
+}
diff --git a/test/files/jvm/actor-executor.check b/test/files/jvm/actor-executor.check
new file mode 100644
index 0000000..bdbdb5c
--- /dev/null
+++ b/test/files/jvm/actor-executor.check
@@ -0,0 +1,20 @@
+Two: OK
+One: OK
+Two: OK
+One: OK
+Two: OK
+One: OK
+Two: OK
+One: OK
+Two: OK
+One: OK
+Two: OK
+One: OK
+Two: OK
+One: OK
+Two: OK
+One: OK
+Two: OK
+One: OK
+Two: OK
+One: OK
diff --git a/test/files/jvm/actor-executor.scala b/test/files/jvm/actor-executor.scala
new file mode 100644
index 0000000..b1f9cae
--- /dev/null
+++ b/test/files/jvm/actor-executor.scala
@@ -0,0 +1,75 @@
+import java.util.concurrent.Executors
+import scala.actors.{Actor, SchedulerAdapter}
+import Actor._
+
+trait AdaptedActor extends Actor {
+  override def scheduler =
+    Test.scheduler
+}
+
+object One extends AdaptedActor {
+  def act() {
+    try {
+    Two.start()
+    var i = 0
+    loopWhile (i < 10000) {
+      i += 1
+      Two ! 'MsgForTwo
+      react {
+        case 'MsgForOne =>
+          if (i % 1000 == 0)
+            println("One: OK")
+          if (i == 10000)
+            Test.executor.shutdown()
+      }
+    }
+    } catch {
+      case e: Throwable if !e.isInstanceOf[scala.util.control.ControlThrowable] =>
+        e.printStackTrace()
+    }
+  }
+}
+
+object Two extends AdaptedActor {
+  def act() {
+    try {
+    var i = 0
+    loopWhile (i < 10000) {
+      i += 1
+      react {
+        case 'MsgForTwo =>
+          if (i % 1000 == 0)
+            println("Two: OK")
+          One ! 'MsgForOne
+      }
+    }
+    } catch {
+      case e: Throwable if !e.isInstanceOf[scala.util.control.ControlThrowable] =>
+        e.printStackTrace()
+    }
+  }
+}
+
+object Test {
+  val executor =
+    Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors())
+
+  val scheduler =
+    new SchedulerAdapter {
+      def execute(block: => Unit) {
+        val task = new Runnable {
+          def run() { block }
+        }
+        try {
+          executor.execute(task)
+        } catch {
+          case ree: java.util.concurrent.RejectedExecutionException =>
+            task.run()
+        }
+      }
+    }
+
+  def main(args: Array[String]) {
+    One.start()
+  }
+}
diff --git a/test/files/jvm/actor-executor2.check b/test/files/jvm/actor-executor2.check
new file mode 100644
index 0000000..da78f45
--- /dev/null
+++ b/test/files/jvm/actor-executor2.check
@@ -0,0 +1,21 @@
+Two: OK
+One: OK
+Two: OK
+One: OK
+Two: OK
+One: OK
+Two: OK
+One: OK
+Two: OK
+One: OK
+Two: OK
+One: OK
+Two: OK
+One: OK
+Two: OK
+One: OK
+Two: OK
+One: OK
+Two: OK
+One: OK
+One exited
diff --git a/test/files/jvm/actor-executor2.scala b/test/files/jvm/actor-executor2.scala
new file mode 100644
index 0000000..f8fcaef
--- /dev/null
+++ b/test/files/jvm/actor-executor2.scala
@@ -0,0 +1,88 @@
+import scala.actors.{Actor, SchedulerAdapter, Exit}
+import Actor._
+import java.util.concurrent.{Executors, RejectedExecutionException}
+
+object One extends AdaptedActor {
+  def act() {
+    try {
+    Two.start()
+    var i = 0
+    loopWhile (i < Test.NUM_MSG) {
+      i += 1
+      Two ! 'MsgForTwo
+      react {
+        case 'MsgForOne =>
+          if (i % (Test.NUM_MSG/10) == 0)
+            println("One: OK")
+      }
+    }
+    } catch {
+      case e: Throwable if !e.isInstanceOf[scala.util.control.ControlThrowable] =>
+        e.printStackTrace()
+    }
+  }
+}
+
+object Two extends AdaptedActor {
+  def act() {
+    try {
+    var i = 0
+    loopWhile (i < Test.NUM_MSG) {
+      i += 1
+      react {
+        case 'MsgForTwo =>
+          if (i % (Test.NUM_MSG/10) == 0)
+            println("Two: OK")
+          One ! 'MsgForOne
+      }
+    }
+    } catch {
+      case e: Throwable if !e.isInstanceOf[scala.util.control.ControlThrowable] =>
+        e.printStackTrace()
+    }
+  }
+}
+
+trait AdaptedActor extends Actor {
+  override def scheduler =
+    Test.scheduler
+}
+
+object Test {
+  val NUM_MSG = 100000
+
+  val executor =
+    Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors())
+
+  val scheduler =
+    new SchedulerAdapter {
+      def execute(block: => Unit) {
+        val task = new Runnable {
+          def run() { block }
+        }
+        try {
+          executor.execute(task)
+        } catch {
+          case ree: RejectedExecutionException =>
+            task.run() // run task on current thread
+        }
+      }
+    }
+
+  def main(args: Array[String]) {
+    try {
+    self.trapExit = true
+    link(One)
+    One.start()
+
+    receive {
+      case Exit(from, reason) =>
+        println("One exited")
+        Test.executor.shutdown()
+    }
+    } catch {
+      case e: Throwable if !e.isInstanceOf[scala.util.control.ControlThrowable] =>
+        e.printStackTrace()
+    }
+  }
+}
diff --git a/test/files/jvm/actor-executor3.check b/test/files/jvm/actor-executor3.check
new file mode 100644
index 0000000..bdbdb5c
--- /dev/null
+++ b/test/files/jvm/actor-executor3.check
@@ -0,0 +1,20 @@
+Two: OK
+One: OK
+Two: OK
+One: OK
+Two: OK
+One: OK
+Two: OK
+One: OK
+Two: OK
+One: OK
+Two: OK
+One: OK
+Two: OK
+One: OK
+Two: OK
+One: OK
+Two: OK
+One: OK
+Two: OK
+One: OK
diff --git a/test/files/jvm/actor-executor3.scala b/test/files/jvm/actor-executor3.scala
new file mode 100644
index 0000000..4fde2c6
--- /dev/null
+++ b/test/files/jvm/actor-executor3.scala
@@ -0,0 +1,62 @@
+import scala.actors.Actor
+import scala.actors.scheduler.ExecutorScheduler
+import java.util.concurrent.Executors
+
+object One extends AdaptedActor {
+  def act() {
+    try {
+    Two.start()
+    var i = 0
+    loopWhile (i < Test.NUM_MSG) {
+      i += 1
+      Two ! 'MsgForTwo
+      react {
+        case 'MsgForOne =>
+          if (i % (Test.NUM_MSG/10) == 0)
+            println("One: OK")
+      }
+    }
+    } catch {
+      case e: Throwable if !e.isInstanceOf[scala.util.control.ControlThrowable] =>
+        e.printStackTrace()
+    }
+  }
+}
+
+object Two extends AdaptedActor {
+  def act() {
+    try {
+    var i = 0
+    loopWhile (i < Test.NUM_MSG) {
+      i += 1
+      react {
+        case 'MsgForTwo =>
+          if (i % (Test.NUM_MSG/10) == 0)
+            println("Two: OK")
+          One ! 'MsgForOne
+      }
+    }
+    } catch {
+      case e: Throwable if !e.isInstanceOf[scala.util.control.ControlThrowable] =>
+        e.printStackTrace()
+    }
+  }
+}
+
+trait AdaptedActor extends Actor {
+  override def scheduler =
+    Test.scheduler
+}
+
+object Test {
+  val NUM_MSG = 100000
+
+  val executor =
+    Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors())
+
+  val scheduler = ExecutorScheduler(executor)
+
+  def main(args: Array[String]) {
+    One.start()
+  }
+}
diff --git a/test/files/jvm/actor-getstate.check b/test/files/jvm/actor-getstate.check
new file mode 100644
index 0000000..2c94e48
--- /dev/null
+++ b/test/files/jvm/actor-getstate.check
@@ -0,0 +1,2 @@
+OK
+OK
diff --git a/test/files/jvm/actor-getstate.scala b/test/files/jvm/actor-getstate.scala
new file mode 100644
index 0000000..a6e15a8
--- /dev/null
+++ b/test/files/jvm/actor-getstate.scala
@@ -0,0 +1,85 @@
+import scala.actors.{Reactor, Actor, TIMEOUT}
+import Actor._
+
+object Test {
+
+  def assert(cond: => Boolean, hint: String) {
+    if (!cond)
+      println("FAIL ["+hint+"]")
+  }
+
+  def expectActorState(a: Reactor[T] forSome { type T }, s: Actor.State.Value) {
+    var done = false
+    var i = 0
+    while (!done) {
+      i = i + 1
+      if (i == 10) { // only wait for 2 seconds total
+        println("FAIL ["+a+": expected "+s+"]")
+        done = true
+      }
+
+      Thread.sleep(200)
+      if (a.getState == s) // success
+        done = true
+    }
+  }
+
+  def main(args: Array[String]) {
+    actor {
+      val a = new Reactor[Any] {
+        def act() {
+          assert(getState == Actor.State.Runnable, "runnable1")
+          react {
+            case 'go =>
+              println("OK")
+          }
+        }
+      }
+      expectActorState(a, Actor.State.New)
+
+      a.start()
+      expectActorState(a, Actor.State.Suspended)
+
+      a ! 'go
+      expectActorState(a, Actor.State.Terminated)
+
+      val b = new Actor {
+        def act() {
+          assert(getState == Actor.State.Runnable, "runnable2: "+getState)
+          react {
+            case 'go =>
+              reactWithin(100000) {
+                case TIMEOUT =>
+                case 'go =>
+                  receive {
+                    case 'go =>
+                  }
+                  receiveWithin(100000) {
+                    case TIMEOUT =>
+                    case 'go =>
+                      println("OK")
+                  }
+              }
+          }
+        }
+      }
+      expectActorState(b, Actor.State.New)
+
+      b.start()
+      expectActorState(b, Actor.State.Suspended)
+
+      b ! 'go
+      expectActorState(b, Actor.State.TimedSuspended)
+
+      b ! 'go
+      expectActorState(b, Actor.State.Blocked)
+
+      b ! 'go
+      expectActorState(b, Actor.State.TimedBlocked)
+
+      b ! 'go
+      expectActorState(b, Actor.State.Terminated)
+    }
+  }
+
+}
diff --git a/test/files/jvm/actor-link-getstate.check b/test/files/jvm/actor-link-getstate.check
new file mode 100644
index 0000000..9755447
--- /dev/null
+++ b/test/files/jvm/actor-link-getstate.check
@@ -0,0 +1,2 @@
+Done
+Terminated
diff --git a/test/files/jvm/actor-link-getstate.scala b/test/files/jvm/actor-link-getstate.scala
new file mode 100644
index 0000000..c4c33ef
--- /dev/null
+++ b/test/files/jvm/actor-link-getstate.scala
@@ -0,0 +1,62 @@
+import scala.actors.{Actor, Exit}
+import scala.actors.Actor._
+
+case class MyException(text: String) extends Exception(text) {
+  override def fillInStackTrace() = this
+}
+
+object Slave extends Actor {
+  def act() {
+    try {
+    loop {
+      react {
+        case 'doWork =>
+          Console.err.println("Done")
+          reply('done)
+      }
+    }
+    } catch {
+      case e: Throwable if !e.isInstanceOf[scala.util.control.ControlThrowable] =>
+        e.printStackTrace()
+    }
+  }
+}
+
+object Master extends Actor {
+  override def toString = "Master"
+  def act() {
+    try {
+    link(Slave)
+    Slave ! 'doWork
+    react {
+      case 'done =>
+        throw new MyException("Master crashed")
+    }
+    } catch {
+      case e: Throwable if !e.isInstanceOf[scala.util.control.ControlThrowable] =>
+        e.printStackTrace()
+    }
+  }
+}
+
+object Test {
+
+  def main(args: Array[String]) {
+    actor {
+      try {
+      self.trapExit = true
+      link(Slave)
+      Slave.start()
+      Master.start()
+      react {
+        case Exit(from, reason) if (from == Slave) =>
+          Console.err.println(Slave.getState)
+      }
+      } catch {
+        case e: Throwable if !e.isInstanceOf[scala.util.control.ControlThrowable] =>
+          e.printStackTrace()
+      }
+    }
+  }
+
+}
diff --git a/test/files/jvm/actor-looping.scala b/test/files/jvm/actor-looping.scala
index 9599adb..475d475 100644
--- a/test/files/jvm/actor-looping.scala
+++ b/test/files/jvm/actor-looping.scala
@@ -6,6 +6,7 @@ object Test {
 
   def main(args: Array[String]) {
     val a = actor {
+      try {
       var cnt = 0
       loop {
         react {
@@ -20,6 +21,10 @@ object Test {
             }
         }
       }
+      } catch {
+        case e: Throwable if !e.isInstanceOf[scala.util.control.ControlThrowable] =>
+          e.printStackTrace()
+      }
     }
 
     for (i <- 0 until 10) a ! A
diff --git a/test/files/jvm/actor-normal-exit.scala b/test/files/jvm/actor-normal-exit.scala
index 40dc7b7..20863d5 100644
--- a/test/files/jvm/actor-normal-exit.scala
+++ b/test/files/jvm/actor-normal-exit.scala
@@ -5,18 +5,28 @@ object Test {
   object Master extends Actor {
     trapExit = true
     def act() {
+      try {
       Slave.start()
       react {
         case Exit(from, reason) =>
           println("slave exited for reason " + reason)
       }
+      } catch {
+        case e: Throwable if !e.isInstanceOf[scala.util.control.ControlThrowable] =>
+          e.printStackTrace()
+      }
     }
   }
 
   object Slave extends Actor {
     def act() {
+      try {
       link(Master)
       println("Done")
+      } catch {
+        case e: Throwable if !e.isInstanceOf[scala.util.control.ControlThrowable] =>
+          e.printStackTrace()
+      }
     }
   }
 
diff --git a/test/files/jvm/actor-receivewithin.scala b/test/files/jvm/actor-receivewithin.scala
index a9582c8..a5c87c2 100644
--- a/test/files/jvm/actor-receivewithin.scala
+++ b/test/files/jvm/actor-receivewithin.scala
@@ -29,19 +29,17 @@ object A extends Actor {
           }
         }
         B ! 'next
-        receive {
-          case 'done =>
-            cnt = 0
-            while (cnt < 501) {
-              cnt += 1
-              receiveWithin (500) {
-                case 'msg2 =>
-                  if (cnt % 100 == 0)
-                    println("'msg2")
-                case TIMEOUT =>
-                  println("TIMEOUT")
-              }
-            }
+        receive { case 'done => }
+        cnt = 0
+        while (cnt < 501) {
+          cnt += 1
+          receiveWithin (500) {
+            case 'msg2 =>
+              if (cnt % 100 == 0)
+                println("'msg2")
+            case TIMEOUT =>
+              println("TIMEOUT")
+          }
         }
     }
   }
diff --git a/test/files/jvm/actor-reply.scala b/test/files/jvm/actor-reply.scala
deleted file mode 100644
index 42c8ca1..0000000
--- a/test/files/jvm/actor-reply.scala
+++ /dev/null
@@ -1,31 +0,0 @@
-import scala.actors.Actor
-
-object Test {
-  def main(args: Array[String]) {
-    val a = new Actor {
-      def act() {
-        react {
-          case 'hello =>
-            sender ! 'hello
-        }
-      }
-    }
-    a.start()
-
-    val b = new Actor {
-      def act() {
-        react {
-          case r: Actor =>
-            r ! 'hello
-            react {
-              case any =>
-                println(any)
-            }
-        }
-      }
-    }
-    b.start()
-
-    b ! a
-  }
-}
diff --git a/test/files/jvm/actor-syncsend.scala b/test/files/jvm/actor-syncsend.scala
deleted file mode 100644
index fb6b16d..0000000
--- a/test/files/jvm/actor-syncsend.scala
+++ /dev/null
@@ -1,44 +0,0 @@
-import scala.actors._
-import scala.actors.Actor._
-
-class MyActor extends Actor {
-  def act() {
-    loop {
-      react {
-        case 'hello =>
-          sender ! 'hello
-        case 'stop =>
-          exit()
-      }
-    }
-  }
-}
-
-object Test {
-  def main(args: Array[String]) {
-    val a = new MyActor
-    a.start()
-
-    val b = new Actor {
-      def act() {
-        react {
-          case r: MyActor =>
-            var i = 0
-            loop {
-              i += 1
-              val msg = r !? 'hello
-              if (i % 10000 == 0)
-                println(msg)
-              if (i >= 50000) {
-                r ! 'stop
-                exit()
-              }
-            }
-        }
-      }
-    }
-    b.start()
-
-    b ! a
-  }
-}
diff --git a/test/files/jvm/actor-syncsend2.scala b/test/files/jvm/actor-syncsend2.scala
deleted file mode 100644
index 3cca97c..0000000
--- a/test/files/jvm/actor-syncsend2.scala
+++ /dev/null
@@ -1,44 +0,0 @@
-import scala.actors._
-import scala.actors.Actor._
-
-class MyActor extends Actor {
-  def act() {
-    loop {
-      react {
-        case 'hello =>
-          sender ! 'hello
-        case 'stop =>
-          exit()
-      }
-    }
-  }
-}
-
-object Test {
-  def main(args: Array[String]) {
-    val a = new MyActor
-    a.start()
-
-    val b = new Actor {
-      def act() {
-        react {
-          case r: MyActor =>
-            var i = 0
-            loop {
-              i += 1
-              val msg = r !? (500, 'hello)
-              if (i % 10000 == 0)
-                println(msg)
-              if (i >= 50000) {
-                r ! 'stop
-                exit()
-              }
-            }
-        }
-      }
-    }
-    b.start()
-
-    b ! a
-  }
-}
diff --git a/test/files/jvm/actor-termination.scala b/test/files/jvm/actor-termination.scala
index 19dfaf8..d8e44a2 100644
--- a/test/files/jvm/actor-termination.scala
+++ b/test/files/jvm/actor-termination.scala
@@ -5,9 +5,14 @@ import scala.actors.Actor
 object Test {
   def main(args: Array[String]) {
     Actor.actor {
+      try {
       println("I'm going to make you wait.")
       Thread.sleep(5000)
       println("Ok, I'm done.")
+      } catch {
+        case e: Throwable if !e.isInstanceOf[scala.util.control.ControlThrowable] =>
+          e.printStackTrace()
+      }
     }
   }
 }
diff --git a/test/files/jvm/actor-uncaught-exception.check b/test/files/jvm/actor-uncaught-exception.check
new file mode 100644
index 0000000..2c94e48
--- /dev/null
+++ b/test/files/jvm/actor-uncaught-exception.check
@@ -0,0 +1,2 @@
+OK
+OK
diff --git a/test/files/jvm/actor-uncaught-exception.scala b/test/files/jvm/actor-uncaught-exception.scala
new file mode 100644
index 0000000..5ae66de
--- /dev/null
+++ b/test/files/jvm/actor-uncaught-exception.scala
@@ -0,0 +1,63 @@
+import scala.actors.{Actor, Exit}
+
+class MyException(msg: String) extends Exception(msg) {
+  override def fillInStackTrace() = this
+}
+
+object Test { 
+
+  case object StartError extends Actor { 
+    def act() { 
+      try {
+      throw new MyException("I don't want to run!") 
+      } catch {
+        case e: Throwable if (!e.isInstanceOf[scala.util.control.ControlThrowable] &&
+                              !e.isInstanceOf[MyException]) =>
+          e.printStackTrace()
+      }
+    } 
+  } 
+
+  case object MessageError extends Actor { 
+    def act() { 
+      try {
+      react { 
+        case _ => throw new MyException("No message for me!") 
+      } 
+      } catch {
+        case e: Throwable if !e.isInstanceOf[scala.util.control.ControlThrowable] =>
+          e.printStackTrace()
+      }
+    } 
+  } 
+
+  case object Supervisor extends Actor { 
+    def act() { 
+      try {
+      trapExit = true 
+      link(StartError)
+      link(MessageError)
+      StartError.start() 
+      MessageError.start()
+
+      Actor.loop { 
+        react { 
+          case Exit(actor, reason) =>
+            println("OK")
+            if (actor == StartError)
+              MessageError ! 'ping
+            else
+              exit()
+        } 
+      } 
+      } catch {
+        case e: Throwable if !e.isInstanceOf[scala.util.control.ControlThrowable] =>
+          e.printStackTrace()
+      }
+    } 
+  } 
+
+  def main(args: Array[String]) { 
+    Supervisor.start() 
+  } 
+} 
diff --git a/test/files/jvm/actor-uncaught-exception2.check b/test/files/jvm/actor-uncaught-exception2.check
new file mode 100644
index 0000000..870a5d3
--- /dev/null
+++ b/test/files/jvm/actor-uncaught-exception2.check
@@ -0,0 +1,2 @@
+UncaughtException(StartError,None,None,MyException: I don't want to run!)
+UncaughtException(MessageError,Some('ping),Some(Supervisor),MyException: No message for me!)
diff --git a/test/files/jvm/actor-uncaught-exception2.scala b/test/files/jvm/actor-uncaught-exception2.scala
new file mode 100644
index 0000000..0364cbe
--- /dev/null
+++ b/test/files/jvm/actor-uncaught-exception2.scala
@@ -0,0 +1,63 @@
+import scala.actors.{Actor, Exit, Debug}
+
+class MyException(msg: String) extends Exception(msg) {
+  override def fillInStackTrace() = this
+}
+
+object Test { 
+
+  case object StartError extends Actor { 
+    def act() { 
+      try {
+      throw new MyException("I don't want to run!") 
+      } catch {
+        case e: Throwable if (!e.isInstanceOf[scala.util.control.ControlThrowable] &&
+                              !e.isInstanceOf[MyException]) =>
+          e.printStackTrace()
+      }
+    } 
+  } 
+
+  case object MessageError extends Actor { 
+    def act() { 
+      try {
+      react { 
+        case _ => throw new MyException("No message for me!") 
+      } 
+      } catch {
+        case e: Throwable if !e.isInstanceOf[scala.util.control.ControlThrowable] =>
+          e.printStackTrace()
+      }
+    } 
+  } 
+
+  case object Supervisor extends Actor { 
+    def act() { 
+      try {
+      trapExit = true 
+      link(StartError)
+      link(MessageError)
+      StartError.start() 
+      MessageError.start()
+
+      Actor.loop { 
+        react { 
+          case Exit(actor, reason) =>
+            println(reason)
+            if (actor == StartError)
+              MessageError ! 'ping
+            else
+              exit()
+        } 
+      } 
+      } catch {
+        case e: Throwable if !e.isInstanceOf[scala.util.control.ControlThrowable] =>
+          e.printStackTrace()
+      }
+    } 
+  } 
+
+  def main(args: Array[String]) { 
+    Supervisor.start() 
+  } 
+} 
diff --git a/test/files/jvm/annotations.check b/test/files/jvm/annotations.check
new file mode 100644
index 0000000..e307f89
--- /dev/null
+++ b/test/files/jvm/annotations.check
@@ -0,0 +1,52 @@
+class java.rmi.RemoteException
+class java.io.IOException
+ at java.lang.Deprecated()
+ at test.SourceAnnotation(mails={scala at lists.epfl.ch,scala-lounge at lists.epfl.ch}, value=http://scala-lang.org)
+class Test4$Foo1
+
+ at test.SourceAnnotation(mails={you at bloodsuckers.com}, value=http://bloodsuckers.com)
+class Test4$Foo2
+
+ at test.SourceAnnotation(mails={bill.gates at bloodsuckers.com}, value=http://bloodsuckers.com)
+class Test4$Foo3
+
+ at test.SourceAnnotation(mails={bill.gates at bloodsuckers.com}, value=file:///dev/null)
+private final int Test4$Foo4.x
+
+ at test.SourceAnnotation(mails={bill.gates at bloodsuckers.com}, value=file:///dev/zero)
+public int Test4$Foo5.bar()
+
+ at test.SourceAnnotation(mails={bill.gates at bloodsuckers.com}, value=primary constructor)
+public Test4$Foo6(java.lang.String)
+
+ at test.SourceAnnotation(mails={bill.gates at bloodsuckers.com}, value=secondary constructor)
+public Test4$Foo7()
+
+ at test.SourceAnnotation(mails={bill.gates at bloodsuckers.com}, value=constructor val)
+public Test4$Foo8(int)
+
+ at test.SourceAnnotation(mails={bill.gates at bloodsuckers.com}, value=http://eppli.com)
+private int Test4$Foo9.z
+
+ at test.SourceAnnotation(mails={bill.gates at bloodsuckers.com}, value=http://eppli.com)
+public int Test4$Foo9.getZ()
+
+ at test.SourceAnnotation(mails={bill.gates at bloodsuckers.com}, value=http://apple.com)
+public int Test4$Foo9.x()
+
+ at test.SourceAnnotation(mails={bill.gates at bloodsuckers.com}, value=http://uppla.com)
+public void Test4$Foo9.setY(int)
+
+ at test.SourceAnnotation(mails={bill.gates at bloodsuckers.com}, value=on param 1)
+public Test4$Foo10(java.lang.String)
+
+ at test.SourceAnnotation(mails={bill.gates at bloodsuckers.com}, value=on param 2)
+private final java.lang.String Test4$Foo11.name
+
+ at test.SourceAnnotation(mails={bill.gates at bloodsuckers.com}, value=on param 3)
+public void Test4$Foo12.name_$eq(java.lang.String)
+
+0
+99
+dylan
+2
diff --git a/test/files/jvm/annotations.scala b/test/files/jvm/annotations.scala
new file mode 100644
index 0000000..f32eb62
--- /dev/null
+++ b/test/files/jvm/annotations.scala
@@ -0,0 +1,214 @@
+object Test1 {
+  class Foo {
+    @remote
+    def foo: Unit = ()
+  }
+  def run {
+    val method = classOf[Foo].getMethod("foo")
+    method.getExceptionTypes foreach println
+  }
+}
+
+object Test2 {
+  import java.io.{BufferedReader,FileReader, IOException}
+  class Reader(fname: String) {
+    private val in = new BufferedReader(new FileReader(fname))
+
+    @throws(classOf[IOException])
+    def read() = in.read()
+  }
+  def run {
+    val method = classOf[Reader].getMethod("read")
+    method.getExceptionTypes foreach println
+  }
+}
+
+/* Java:
+public class Main {
+    @Deprecated
+    public void foo() {}
+    public static void main(String[] args) throws Exception {
+        Method method = Class.forName("test.Main").getMethod("foo", new Class[]{});
+        Annotation annotation = method.getAnnotation(Deprecated.class);
+        System.out.println(annotation); // @java.lang.Deprecated()
+    }
+}
+*/
+object Test3 {
+  import java.lang.Deprecated
+  class Foo {
+    @Deprecated
+    def foo: Unit = ()
+  }
+  def run {
+    val method = classOf[Foo].getMethod("foo")
+    val annotation = method.getAnnotation(classOf[Deprecated])
+    println(annotation)
+  }
+}
+
+/* Java:
+ at Retention(value=RetentionPolicy.RUNTIME)
+ at interface Source {
+   public String url();
+   public String mail();
+}
+ at Source(url="http://scala.epfl.ch", mail="scala at lists.epfl.ch")
+class Foo {}
+public class Main {
+    public static void main(String[] args) throws Exception {
+        Class clazz = Class.forName("test.Foo");
+        Annotation[] annotations = clazz.getAnnotations();
+        for (int i = 0; i < annotations.length; i++)
+            System.out.println(annotations[i]);
+        // @test.Main$Source(url=http://scala-lang.org, mail=scala at lists.epfl.ch)
+    }
+}
+*/
+object Test4 {
+  import test.SourceAnnotation // defined in SourceAnnotation.java
+  @SourceAnnotation(value = "http://scala-lang.org",
+                    mails = Array("scala at lists.epfl.ch", "scala-lounge at lists.epfl.ch"))
+  class Foo1
+  @SourceAnnotation(value = "http://bloodsuckers.com",
+                    mails = Array("you at bloodsuckers.com"))
+  class Foo2
+  @SourceAnnotation("http://bloodsuckers.com")
+  class Foo3
+  class Foo4 {
+    @SourceAnnotation("file:///dev/null")
+    val x = 1
+  }
+  class Foo5 {
+    @SourceAnnotation("file:///dev/zero")
+    def bar: Int = 0
+  }
+  class Foo6 @SourceAnnotation("primary constructor") (s: String) {
+    // to guarantee that primary constructor annotations
+    // are not applied to secondary constructors
+    def this() = this("")
+  }
+  class Foo7(s: String) {
+    @SourceAnnotation("secondary constructor")
+    def this() = this("")
+  }
+  class Foo8(@SourceAnnotation("constructor val") val n: Int) {}
+  class Foo9 {
+    import scala.annotation.target._
+    import scala.reflect.BeanProperty
+    @(SourceAnnotation @getter)("http://apple.com") val x = 0
+    @BeanProperty @(SourceAnnotation @beanSetter)("http://uppla.com") var y = 0
+
+    type myAnn = SourceAnnotation @beanGetter @field
+    @BeanProperty @myAnn("http://eppli.com") var z = 0
+  }
+  class Foo10(@SourceAnnotation("on param 1") val name: String)
+  class Foo11(@(SourceAnnotation @scala.annotation.target.field)("on param 2") val name: String)
+  class Foo12(@(SourceAnnotation @scala.annotation.target.setter)("on param 3") var name: String)
+  def run {
+    import java.lang.annotation.Annotation
+    import java.lang.reflect.AnnotatedElement
+    def printSourceAnnotation(a: Annotation) {
+      val ann = a.asInstanceOf[SourceAnnotation]
+      println("@test.SourceAnnotation(mails=" + ann.mails.deepMkString("{", ",", "}") +
+              ", value=" + ann.value + ")")
+    }
+    def printSourceAnnotations(target: AnnotatedElement) {
+      //print SourceAnnotation in a predefined way to insure
+      // against difference in the JVMs (e.g. Sun's vs IBM's)
+      val anns = target.getAnnotations()
+      anns foreach printSourceAnnotation
+      if (anns.length > 0) {
+        println(target)
+        println
+      }
+    }
+    def printParamSourceAnnotations(target: { def getParameterAnnotations(): Array[Array[Annotation]] }) {
+      val anns = target.getParameterAnnotations().flatten
+      anns foreach printSourceAnnotation
+      if (anns.length > 0) {
+        println(target)
+        println
+      }
+    }
+    printSourceAnnotations(classOf[Foo1])
+    printSourceAnnotations(classOf[Foo2])
+    printSourceAnnotations(classOf[Foo3])
+    classOf[Foo4].getDeclaredFields  foreach printSourceAnnotations
+    classOf[Foo4].getDeclaredMethods foreach printSourceAnnotations
+    classOf[Foo5].getDeclaredMethods foreach printSourceAnnotations
+    classOf[Foo6].getDeclaredConstructors foreach printSourceAnnotations
+    classOf[Foo7].getDeclaredConstructors foreach printSourceAnnotations
+    classOf[Foo8].getDeclaredFields  foreach printSourceAnnotations
+    classOf[Foo8].getDeclaredMethods foreach printSourceAnnotations
+    classOf[Foo8].getDeclaredConstructors foreach printParamSourceAnnotations
+    classOf[Foo9].getDeclaredFields.sortWith((x, y) => x.toString < y.toString)  foreach printSourceAnnotations
+    classOf[Foo9].getDeclaredMethods.sortWith((x, y) => x.toString < y.toString) foreach printSourceAnnotations
+    classOf[Foo10].getDeclaredFields.sortWith((x, y) => x.toString < y.toString)  foreach printSourceAnnotations
+    classOf[Foo10].getDeclaredMethods.sortWith((x, y) => x.toString < y.toString) foreach printSourceAnnotations
+    classOf[Foo10].getDeclaredConstructors foreach printParamSourceAnnotations
+    classOf[Foo11].getDeclaredFields.sortWith((x, y) => x.toString < y.toString)  foreach printSourceAnnotations
+    classOf[Foo11].getDeclaredMethods.sortWith((x, y) => x.toString < y.toString) foreach printSourceAnnotations
+    classOf[Foo11].getDeclaredConstructors foreach printParamSourceAnnotations
+    classOf[Foo12].getDeclaredFields.sortWith((x, y) => x.toString < y.toString)  foreach printSourceAnnotations
+    classOf[Foo12].getDeclaredMethods.sortWith((x, y) => x.toString < y.toString) foreach printSourceAnnotations
+    classOf[Foo12].getDeclaredConstructors foreach printParamSourceAnnotations
+  }
+}
+
+object Test5 {
+  import scala.reflect.BeanProperty
+  import java.lang.Integer
+
+  class Count {
+    // we use "Integer" instead of "Int" because of Java reflection
+    @BeanProperty
+    var count: Integer = 0
+
+    private val getter =
+      getClass().getMethod("getCount")
+    private val setter =
+      getClass().getMethod("setCount", classOf[Integer])
+
+    def get = getter.invoke(this).asInstanceOf[Integer].intValue
+    def set(n: Int) = setter.invoke(this, new Integer(n))
+  }
+  def run {
+    val count = new Count
+    println(count.get)
+    count.set(99)
+    println(count.get)
+  }
+}
+
+object Test6 {
+  import scala.reflect.BeanProperty
+  import scala.reflect.BooleanBeanProperty
+  class C(@BeanProperty var text: String)
+  class D(@BooleanBeanProperty var prop: Boolean) {
+    @BeanProperty val m: Int = if (prop) 1 else 2
+  }
+
+  def run {
+    val c = new C("bob")
+    c.setText("dylan")
+    println(c.getText())
+    if (new D(true).isProp()) {
+      println(new D(false).getM())
+    }
+  }
+}
+
+// #3345
+class A3345(@volatile private var i:Int)
+
+object Test {
+  def main(args: Array[String]) {
+    Test1.run
+    Test2.run
+    Test3.run     // requires the use of -target:jvm-1.5
+    Test4.run
+    Test5.run
+    Test6.run
+  }
+}
diff --git a/test/files/jvm/bigints.check b/test/files/jvm/bigints.check
deleted file mode 100644
index 3e67ff1..0000000
--- a/test/files/jvm/bigints.check
+++ /dev/null
@@ -1,14 +0,0 @@
-3
-true
-false
-true
-true
-
-3
-true
-false
-true
-true
-9223372036854775806
-false
-true
diff --git a/test/files/jvm/bigints.scala b/test/files/jvm/bigints.scala
index 1d30a52..7a79787 100644
--- a/test/files/jvm/bigints.scala
+++ b/test/files/jvm/bigints.scala
@@ -1,38 +1,60 @@
-object Test extends Application {
-  Test1
-  Test2
+//############################################################################
+// BigInt, BigDecimal 
+//############################################################################
+
+//############################################################################
+
+import testing.SUnit._
+
+/** Test the Scala implementation of class <code>scala.BigDecimal</code>.
+*
+*  @author Stephane Micheloud
+*/
+object Test extends TestConsoleMain {
+  def suite = new TestSuite(
+    Test_BigInt,
+    Test_BigDecimal
+  )
 }
 
-object Test1 {
-  import BigInt._
-
-  val x: BigInt = 1
-  val y = x + 1
-  val z = 1 + y
-  println(z)
-  println(z <= 3)
-  println(3 < z)
-  println(z == 3)
-  println(3 == z)
-  println()
+object Test_BigInt extends TestCase("BigInt") with Assert {
+  override def enableStackTrace = false
+  override def runTest {
+    import BigInt._
+
+    val x: BigInt = 1
+    val y = x + 1
+    val z = 1 + y
+    assertEquals("int_add_bigint", 1+y, y+1)
+    assertEquals("int_sub_bigint", 1-y, -(y-1))
+    assertEquals("int_mul_bigint", 2*x*y, y*x*2)
+    assertTrue("z_<=_3", z <= 3)
+    assertFalse("3_<_z", 3 < z)
+  }
 }
 
-object Test2 {
-  import BigDecimal._
-
-  val x: BigDecimal = 1
-  val y = x + 1
-  val z = 1 + y
-  println(z)
-  println(z <= 3)
-  println(3 < z)
-  println(z == 3)
-  println(3 == z)
-  
-  val a = BigDecimal(Math.MAX_LONG)
-  val b = BigDecimal(Test1.x)
-  val c = a - b
-  println(c)
-  println(c > Math.MAX_LONG)
-  println(c <= Math.MAX_LONG)
+object Test_BigDecimal extends TestCase("BigDecimal") with Assert {
+  override def enableStackTrace = false
+  override def runTest {
+    import scala.BigDecimal, BigDecimal._
+
+    val xi: BigDecimal = 1
+    val xd: BigDecimal = 1.0
+    val xf: BigDecimal = BigDecimal(1.0f)
+    val xs: BigDecimal = BigDecimal("1.0")
+    val xbi: BigDecimal = BigDecimal(scala.BigInt(1))
+
+    val x: BigDecimal = 1
+    val y = x + 1
+    val z = 1 + y
+    assertTrue("z_<=_3", z <= 3)
+    assertFalse("3_<_z", 3 < z)
+
+    val a: BigDecimal= Math.MAX_LONG
+    val b: BigDecimal = 1
+    val c = a - b
+    assertFalse("c_>_MAX_LONG", c > Math.MAX_LONG)
+    assertTrue("c_<=_MAX_LONG", c <= Math.MAX_LONG)
+  }
 }
+
diff --git a/test/files/jvm5/bug676.check b/test/files/jvm/bug676.check
similarity index 100%
rename from test/files/jvm5/bug676.check
rename to test/files/jvm/bug676.check
diff --git a/test/files/jvm5/bug676.scala b/test/files/jvm/bug676.scala
similarity index 100%
rename from test/files/jvm5/bug676.scala
rename to test/files/jvm/bug676.scala
diff --git a/test/files/jvm5/bug680.check b/test/files/jvm/bug680.check
similarity index 100%
copy from test/files/jvm5/bug680.check
copy to test/files/jvm/bug680.check
diff --git a/test/files/jvm5/bug680.scala b/test/files/jvm/bug680.scala
similarity index 100%
rename from test/files/jvm5/bug680.scala
rename to test/files/jvm/bug680.scala
diff --git a/test/files/jvm5/console.check b/test/files/jvm/console.check
similarity index 100%
rename from test/files/jvm5/console.check
rename to test/files/jvm/console.check
diff --git a/test/files/jvm5/console.scala b/test/files/jvm/console.scala
similarity index 100%
rename from test/files/jvm5/console.scala
rename to test/files/jvm/console.scala
diff --git a/test/files/jvm/daemon-actor-termination.check b/test/files/jvm/daemon-actor-termination.check
new file mode 100644
index 0000000..b2ff72f
--- /dev/null
+++ b/test/files/jvm/daemon-actor-termination.check
@@ -0,0 +1,2 @@
+MSG1
+MSG2
diff --git a/test/files/jvm/daemon-actor-termination.scala b/test/files/jvm/daemon-actor-termination.scala
new file mode 100644
index 0000000..6ddfc31
--- /dev/null
+++ b/test/files/jvm/daemon-actor-termination.scala
@@ -0,0 +1,38 @@
+import scala.actors.{Actor, DaemonActor}
+
+/* Test that a daemon Actor that hasn't finished does not prevent termination */
+object Test {
+
+  class MyDaemon extends DaemonActor {
+    def act() {
+      try {
+      react {
+        case 'hello =>
+          println("MSG1")
+          reply()
+          react {
+            case 'bye =>
+              println("done")
+          }
+      }
+      } catch {
+        case e: Throwable if !e.isInstanceOf[scala.util.control.ControlThrowable] =>
+          e.printStackTrace()
+      }
+    }
+  }
+
+  def main(args: Array[String]) {
+    val daemon = new MyDaemon
+    daemon.start()
+    Actor.actor {
+      try {
+      daemon !? 'hello
+      println("MSG2")
+      } catch {
+        case e: Throwable if !e.isInstanceOf[scala.util.control.ControlThrowable] =>
+          e.printStackTrace()
+      }
+    }
+  }
+}
diff --git a/test/files/jvm/deprecation.cmds b/test/files/jvm/deprecation.cmds
new file mode 100644
index 0000000..4c0f73c
--- /dev/null
+++ b/test/files/jvm/deprecation.cmds
@@ -0,0 +1,3 @@
+javac Defs.java
+scalac Test_1.scala
+javac Use_2.java
diff --git a/test/files/jvm/deprecation/Defs.java b/test/files/jvm/deprecation/Defs.java
new file mode 100644
index 0000000..52101c3
--- /dev/null
+++ b/test/files/jvm/deprecation/Defs.java
@@ -0,0 +1,12 @@
+public class Defs {
+    /** @deprecated */
+    public int i = 1;
+
+    /** @deprecated */
+    public int bar() { return 0; }
+
+    /** @deprecated */
+    public class Inner {
+        public int buz() { return 0; }
+    }
+}
diff --git a/test/files/jvm/deprecation/Test_1.scala b/test/files/jvm/deprecation/Test_1.scala
new file mode 100644
index 0000000..5bd87b8
--- /dev/null
+++ b/test/files/jvm/deprecation/Test_1.scala
@@ -0,0 +1,17 @@
+class Test {
+  def test {
+    val d = new Defs
+    val u = d.i + 1
+    d.i = 2
+    val v = d.bar()
+    val i = new d.Inner
+    val w = i.buz()
+  }
+  
+  @deprecated("no longer!") class Inner {
+    @deprecated("uncool") def f: Int = 1
+    @deprecated("this one as well!") var g = -1
+  }
+}
+
+object Test { def main(args: Array[String]) { } }
diff --git a/test/files/jvm/deprecation/Use_2.java b/test/files/jvm/deprecation/Use_2.java
new file mode 100644
index 0000000..65da8a8
--- /dev/null
+++ b/test/files/jvm/deprecation/Use_2.java
@@ -0,0 +1,10 @@
+class Use_2 {
+    public int test() {
+        Test u = new Test();
+        Test.Inner a = u.new Inner();
+        int i = a.f();
+        int j = a.g();
+        a.g_$eq(5);
+        return i + j;
+    }
+}
\ No newline at end of file
diff --git a/test/files/jvm/future-alarm.check b/test/files/jvm/future-alarm.check
new file mode 100644
index 0000000..01a87d1
--- /dev/null
+++ b/test/files/jvm/future-alarm.check
@@ -0,0 +1,20 @@
+OK
+OK
+OK
+OK
+OK
+OK
+OK
+OK
+OK
+OK
+OK
+OK
+OK
+OK
+OK
+OK
+OK
+OK
+OK
+OK
diff --git a/test/files/jvm/future-alarm.scala b/test/files/jvm/future-alarm.scala
new file mode 100644
index 0000000..8ee902b
--- /dev/null
+++ b/test/files/jvm/future-alarm.scala
@@ -0,0 +1,21 @@
+import scala.actors.Futures
+
+object Test {
+  def main(args: Array[String]) {
+    try {
+    for (i <- 1 to 100000) {
+      Futures.alarm(0)
+      if (i % 10000 == 0)
+        println("OK")
+    }
+    for (_ <- 1 to 10) {
+      val ft = Futures.alarm(100)
+      ft()
+      println("OK")
+    }
+    } catch {
+      case e: Throwable if !e.isInstanceOf[scala.util.control.ControlThrowable] =>
+        e.printStackTrace()
+    }
+  }
+}
diff --git a/test/files/jvm/future-awaitall-zero.check b/test/files/jvm/future-awaitall-zero.check
new file mode 100644
index 0000000..d86bac9
--- /dev/null
+++ b/test/files/jvm/future-awaitall-zero.check
@@ -0,0 +1 @@
+OK
diff --git a/test/files/jvm/future-awaitall-zero.scala b/test/files/jvm/future-awaitall-zero.scala
new file mode 100644
index 0000000..cd6ba17
--- /dev/null
+++ b/test/files/jvm/future-awaitall-zero.scala
@@ -0,0 +1,22 @@
+import scala.actors.Futures._
+import scala.actors.Actor._
+
+object Test {
+  def main(args: Array[String]) {
+    try {
+    val ft1 = future { reactWithin(10000) {
+      case _ => println("FAIL")
+    } }
+
+    val ft2 = future { reactWithin(20000) {
+      case _ => println("FAIL")
+    } }
+
+    val res = awaitAll(0, ft1, ft2)
+    println("OK")
+    } catch {
+      case e: Throwable if !e.isInstanceOf[scala.util.control.ControlThrowable] =>
+        e.printStackTrace()
+    }
+  }
+}
diff --git a/test/files/jvm/future-termination.check b/test/files/jvm/future-termination.check
new file mode 100644
index 0000000..dc33546
--- /dev/null
+++ b/test/files/jvm/future-termination.check
@@ -0,0 +1 @@
+I can't wait that long, bye.
diff --git a/test/files/jvm/future-termination.scala b/test/files/jvm/future-termination.scala
new file mode 100644
index 0000000..f51642c
--- /dev/null
+++ b/test/files/jvm/future-termination.scala
@@ -0,0 +1,19 @@
+import scala.actors.Futures 
+ 
+/* Test that unevaluated futures do not prevent program termination */ 
+ 
+object Test { 
+  def main(args: Array[String]) { 
+    try {
+    val meaningOfLife = Futures.future { 
+      Thread.sleep(5000) // pretend this is a harder problem than it is 
+      println("I have the answer!") 
+      42 
+    } 
+    println("I can't wait that long, bye.") 
+    } catch {
+      case e: Throwable if !e.isInstanceOf[scala.util.control.ControlThrowable] =>
+        e.printStackTrace()
+    }
+  } 
+}
diff --git a/test/files/jvm5/genericNest.scala b/test/files/jvm/genericNest.scala
similarity index 100%
rename from test/files/jvm5/genericNest.scala
rename to test/files/jvm/genericNest.scala
diff --git a/test/files/jvm/getGenericSuperclass.check b/test/files/jvm/getGenericSuperclass.check
new file mode 100644
index 0000000..d8f1c73
--- /dev/null
+++ b/test/files/jvm/getGenericSuperclass.check
@@ -0,0 +1,2 @@
+scala.collection.immutable.List<scala.runtime.Nothing$>
+scala.Option<scala.runtime.Nothing$>
diff --git a/test/files/jvm/getGenericSuperclass.scala b/test/files/jvm/getGenericSuperclass.scala
new file mode 100644
index 0000000..d8c5461
--- /dev/null
+++ b/test/files/jvm/getGenericSuperclass.scala
@@ -0,0 +1,6 @@
+object Test {
+  def main(args: Array[String]) {
+    println(Nil.getClass.getGenericSuperclass)
+    println(None.getClass.getGenericSuperclass)
+  }
+}
diff --git a/test/files/jvm/inner.scala b/test/files/jvm/inner.scala
new file mode 100644
index 0000000..156d9e6
--- /dev/null
+++ b/test/files/jvm/inner.scala
@@ -0,0 +1,127 @@
+//############################################################################
+// Test Java interaction with scala inner classes
+//############################################################################
+
+import java.io.{BufferedReader, File, FileWriter, InputStreamReader}
+
+class A {
+  val abc = "A.abc"
+
+  protected class B(x: Int, y: String) {
+    println(abc); println(x)
+    println(y)
+  }
+
+  trait Itf {
+    def method1(x: Int): Int
+    
+    trait Itf2 extends Itf {
+      def method2: Unit
+    }
+  }
+
+  trait PlainTrait {
+    def method1(x: Int): Int
+  }
+
+  class Impl(a: Int) extends Itf {
+    def method1(x: Int) = {
+      println(x)
+      println(a)
+      x + a
+    }
+  }
+
+  val impl = new Impl(0)
+
+  class Impl2 extends Impl(1) with impl.Itf2 {
+    def method2 = {
+      println(abc)
+    }
+  }
+
+  def newImpl: Itf = new Impl(1)
+  def newImpl2: Itf#Itf2 = new Impl2
+
+  class Outer1(arg1: Int) {
+    class Outer2(arg2: Int) {
+      class Outer3(arg3: Int) {
+        println("Outer3: " + arg1 + " " + arg2 + " " + arg3);
+      }
+    }
+  }
+}
+
+object Scalatest {
+  private val outputdir = System.getProperty("partest.output", "inner.obj")
+  private val scalalib  = System.getProperty("partest.lib", "")
+  private val classpath = outputdir + File.pathSeparator + scalalib
+  private val javabin  = {
+    val jhome = new File(System.getProperty("java.home"))
+    if (jhome.getName == "jre")
+      new File(jhome.getParent, "bin").getAbsolutePath
+    else
+      new File(jhome, "bin").getAbsolutePath
+  }
+  private val javacmd   = javabin + File.separator + "java"
+  private val javac     = javabin + File.separator + "javac"
+
+  def javac(src: String, fname: String) {
+    val tmpfilename = outputdir + File.separator + fname
+    val tmpfile = new FileWriter(tmpfilename)
+    tmpfile.write(src)
+    tmpfile.close
+    exec(javac + " -d " + outputdir + " -classpath " + classpath + " " + tmpfilename)
+  }
+
+  def java(cname: String) =
+    exec(javacmd + " -cp " + classpath + " " + cname)
+
+  /** Execute cmd, wait for the process to end and pipe it's output to stdout */
+  private def exec(cmd: String) {
+    val proc = Runtime.getRuntime().exec(cmd)
+    val inp = new BufferedReader(new InputStreamReader(proc.getInputStream))
+    val errp = new BufferedReader(new InputStreamReader(proc.getErrorStream))
+    proc.waitFor()
+    while (inp.ready) println(inp.readLine())
+    while (errp.ready) println(errp.readLine())
+  }
+}
+
+object Test {
+  def main(args: Array[String]) {
+    val javaInteraction = """
+public class JavaInteraction {
+    public static void main(String[] args) {
+        A a = new A();
+        A.B b = a.new B(1, "Hello");
+
+        A.Itf itf = a.newImpl();
+        itf.method1(1);
+
+        A.Itf.Itf2 itf2 = a.newImpl2();
+        itf2.method2();
+
+        A.Outer1 o1 = a.new Outer1(1);
+        A.Outer1.Outer2 o2 = o1.new Outer2(2);
+        A.Outer1.Outer2.Outer3 or = o2.new Outer3(3);
+    }
+}
+"""
+    Scalatest.javac(javaInteraction, "JavaInteraction.java")
+    Scalatest.java("JavaInteraction")
+
+    val accessingScala = """
+public class AccessingScala {
+    public static void main(String[] args) {
+        A a = new A();
+        System.out.println(a.abc());
+    }
+}
+"""
+    Scalatest.javac(accessingScala, "AccessingScala.java")
+    Scalatest.java("AccessingScala")
+  }
+}
+
+//############################################################################
diff --git a/test/files/jvm/interpreter.check b/test/files/jvm/interpreter.check
new file mode 100644
index 0000000..b74ba1b
--- /dev/null
+++ b/test/files/jvm/interpreter.check
@@ -0,0 +1,235 @@
+Type in expressions to have them evaluated.
+Type :help for more information.
+
+scala> 
+scala> 
+scala> res0: Int = 7
+
+scala>      |      |      |      | gcd: (x: Int,y: Int)Int
+
+scala> five: Int = 5
+
+scala> x: Int = 1
+
+scala> x: Int = 2
+
+scala> three: Int = 3
+
+scala> defined type alias anotherint
+
+scala> four: anotherint = 4
+
+scala> <console>:6: error: type mismatch;
+ found   : java.lang.String("hello")
+ required: anotherint
+       val bogus: anotherint = "hello"
+                               ^
+
+scala> defined trait PointlessTrait
+
+scala> x: Int = 2
+y: Int = 3
+
+scala> hello
+
+scala> 
+scala> 
+scala> t1513: Array[Null] = Array(null)
+
+scala> 
+scala> atom: scala.xml.Atom[Unit] = ()
+
+scala> 
+scala> defined class S
+
+scala> fish: S = fish
+
+scala> 
+scala> arr: Array[java.lang.String] = Array(What's, up, doc?)
+
+scala> 
+scala> arrInt: Any = Array(1, 2, 3)
+
+scala> 
+scala> arrArrInt: Any = Array(Array(1, 2), Array(3, 4))
+
+scala> 
+scala> 
+scala> defined class Foo
+
+scala> defined class Bar
+
+scala> foo2bar: (foo: Foo)Bar
+
+scala> bar: Bar = Bar(3)
+
+scala> 
+scala> 
+scala> import bar._
+
+scala> m: Int = 3
+
+scala> 
+scala> 
+scala> one: Int = 1
+
+scala> one: Int = 1
+
+scala> one: Int = 1
+
+scala> one: Int = 1
+
+scala> one: Int = 1
+
+scala> one: Int = 1
+
+scala> one: Int = 1
+
+scala> one: Int = 1
+
+scala> one: Int = 1
+
+scala> one: Int = 1
+
+scala> one: Int = 1
+
+scala> one: Int = 1
+
+scala> one: Int = 1
+
+scala> one: Int = 1
+
+scala> one: Int = 1
+
+scala> one: Int = 1
+
+scala> one: Int = 1
+
+scala> one: Int = 1
+
+scala> one: Int = 1
+
+scala> one: Int = 1
+
+scala> 
+scala> 
+scala> x1: Int = 1
+
+scala> x2: Int = 1
+
+scala> x3: Int = 1
+
+scala> x4: Int = 1
+
+scala> x5: Int = 1
+
+scala> x6: Int = 1
+
+scala> x7: Int = 1
+
+scala> x8: Int = 1
+
+scala> x9: Int = 1
+
+scala> x10: Int = 1
+
+scala> x11: Int = 1
+
+scala> x12: Int = 1
+
+scala> x13: Int = 1
+
+scala> x14: Int = 1
+
+scala> x15: Int = 1
+
+scala> x16: Int = 1
+
+scala> x17: Int = 1
+
+scala> x18: Int = 1
+
+scala> x19: Int = 1
+
+scala> x20: Int = 1
+
+scala> 
+scala> two: Int = 2
+
+scala> 
+scala> 
+scala> 
+scala> xs: Array[_] = Array(1, 2)
+
+scala> res2: Int = 2
+
+scala> res3: Any = 1
+
+scala> res4: Array[_] = Array(2)
+
+scala> res5: Array[java.lang.String] = Array(abc, abc)
+
+scala> res6: scala.collection.mutable.ArraySeq[_] = ArraySeq(1, 2)
+
+scala> res7: Array[(_$1, _$1)] forSome { type _$1 } = Array((1,1), (2,2))
+
+scala> 
+scala> 
+scala> 
+scala> <console>:1: error: '=' expected but '=>' found.
+       def x => y => z
+             ^
+
+scala> <console>:1: error: expected start of definition
+       [1,2,3]
+       ^
+
+scala> 
+scala> 
+scala> 
+scala>      |      |      |      | res8: scala.xml.Elem = 
+<a>
+<b d="dd" c="c"></b></a>
+
+scala> 
+scala> 
+scala>      |      |      |      | 
+scala> 
+scala> 
+scala> 
+scala>      |      |      | res9: java.lang.String = 
+
+hello
+there
+
+
+scala> 
+scala>      |      | You typed two blank lines.  Starting a new command.
+
+scala> 
+scala> match: Int
+
+scala> x: Int = 1
+
+scala> 
+scala> 
+scala> defined class Exp
+defined class Fact
+defined class Term
+
+scala>      |      | <console>:16: warning: match is not exhaustive!
+missing combination            Exp
+missing combination           Term
+
+       def f(e: Exp) = e match {  // non-exhaustive warning here
+                       ^
+f: (e: Exp)Int
+
+scala> 
+scala> 
+plusOne: (x: Int)Int
+res0: Int = 6
+res1: java.lang.String = after reset
+<console>:6: error: not found: value plusOne
+       plusOne(5) // should be undefined now
+       ^
diff --git a/test/files/jvm/interpreter.scala b/test/files/jvm/interpreter.scala
new file mode 100644
index 0000000..1437b97
--- /dev/null
+++ b/test/files/jvm/interpreter.scala
@@ -0,0 +1,191 @@
+import scala.tools.nsc._
+import java.io.{BufferedReader, StringReader, PrintWriter,
+                Writer, OutputStreamWriter}
+
+object Test {
+  val testCodeString = <code>
+// basics
+3+4
+def gcd(x: Int, y: Int): Int = {{
+          if (x == 0) y
+          else if (y == 0) x
+          else gcd(y%x, x)
+}}
+val five = gcd(15,35)
+var x = 1
+x = 2
+val three = x+1
+type anotherint = Int
+val four: anotherint = 4
+val bogus: anotherint = "hello"
+trait PointlessTrait
+val (x,y) = (2,3)
+println("hello")
+
+// ticket #1513
+val t1513 = Array(null)
+// ambiguous toString problem from #547
+val atom = new scala.xml.Atom()
+// overriding toString problem from #1404
+class S(override val toString : String)
+val fish = new S("fish")
+// Test that arrays pretty print nicely.
+val arr = Array("What's", "up", "doc?") 
+// Test that arrays pretty print nicely, even when we give them type Any
+val arrInt : Any = Array(1,2,3)
+// Test that nested arrays are pretty-printed correctly
+val arrArrInt : Any = Array(Array(1, 2), Array(3, 4))
+
+// implicit conversions
+case class Foo(n: Int)
+case class Bar(n: Int)
+implicit def foo2bar(foo: Foo) = Bar(foo.n)
+val bar: Bar = Foo(3)
+
+// importing from a previous result
+import bar._
+val m = n
+
+// stressing the imports mechanism
+val one = 1
+val one = 1
+val one = 1
+val one = 1
+val one = 1
+val one = 1
+val one = 1
+val one = 1
+val one = 1
+val one = 1
+val one = 1
+val one = 1
+val one = 1
+val one = 1
+val one = 1
+val one = 1
+val one = 1
+val one = 1
+val one = 1
+val one = 1
+
+
+val x1 = 1
+val x2 = 1
+val x3 = 1
+val x4 = 1
+val x5 = 1
+val x6 = 1
+val x7 = 1
+val x8 = 1
+val x9 = 1
+val x10 = 1
+val x11 = 1
+val x12 = 1
+val x13 = 1
+val x14 = 1
+val x15 = 1
+val x16 = 1
+val x17 = 1
+val x18 = 1
+val x19 = 1
+val x20 = 1
+
+val two = one + x5
+
+// handling generic wildcard arrays (#2386)
+// It's put here because type feedback is an important part of it.
+val xs: Array[_] = Array(1, 2)
+xs.size
+xs.head
+xs filter (_ == 2)
+xs map (_ => "abc")
+xs map (x => x)
+xs map (x => (x, x))
+
+// interior syntax errors should *not* go into multi-line input mode.
+// both of the following should abort immediately:
+def x => y => z
+[1,2,3]
+
+
+// multi-line XML
+<a>
+<b
+  c="c"
+  d="dd"
+/></a>
+
+
+/*
+  /*
+    multi-line comment
+  */
+*/
+
+
+// multi-line string
+"""
+hello
+there
+"""
+
+(1 +   // give up early by typing two blank lines
+
+
+// defining and using quoted names should work (ticket #323)
+def `match` = 1 
+val x = `match` 
+
+// multiple classes defined on one line
+sealed class Exp; class Fact extends Exp; class Term extends Exp
+def f(e: Exp) = e match {{  // non-exhaustive warning here
+  case _:Fact => 3
+}}
+
+</code>.text
+
+  /** A writer that skips the first line of text.  The first
+   *  line of interpreter output is skipped because it includes
+   *  a version number. */
+  class Skip1Writer(writer: Writer) extends Writer {
+    var seenNL = false
+
+    def write(cbuf: Array[Char], off: Int, len: Int) {
+      if (seenNL) 
+	writer.write(cbuf, off, len) 
+      else {
+	val slice : Array[Char] = cbuf.slice(off, off+len)
+	val i = slice.indexOf('\n')
+	if (i >= 0) {
+	  seenNL = true
+	  writer.write(slice, i+1, slice.length-(i+1))
+	} else {
+	  // skip it
+	}
+      }
+    }
+
+    def close() { writer.close() }
+    def flush() { writer.flush() }
+  }
+
+
+  def main(args: Array[String]) {
+    val input = new BufferedReader(new StringReader(testCodeString))
+    val output = new PrintWriter(
+      new Skip1Writer(new OutputStreamWriter(Console.out)))
+    val repl = new InterpreterLoop(input, output)
+    val settings = new Settings
+    // when running that compiler, give it a scala-library to the classpath
+    settings.classpath.value = System.getProperty("java.class.path")
+    repl.main(settings)
+    println()
+
+    val interp = new Interpreter(settings)
+    interp.interpret("def plusOne(x: Int) = x + 1")
+    interp.interpret("plusOne(5)")
+    interp.reset()
+    interp.interpret("\"after reset\"")
+    interp.interpret("plusOne(5) // should be undefined now")
+  }
+}
diff --git a/test/files/jvm/libnatives.jnilib b/test/files/jvm/libnatives.jnilib
index 370a726..daac50e 100644
Binary files a/test/files/jvm/libnatives.jnilib and b/test/files/jvm/libnatives.jnilib differ
diff --git a/test/files/jvm/manifests.check b/test/files/jvm/manifests.check
index bfcd6a2..69ab066 100644
--- a/test/files/jvm/manifests.check
+++ b/test/files/jvm/manifests.check
@@ -1,35 +1,35 @@
-x=(), m=void
-x=true, m=boolean
-x=a, m=char
-x=1, m=int
+x=(), m=Unit
+x=true, m=Boolean
+x=a, m=Char
+x=1, m=Int
 x=abc, m=java.lang.String
 x='abc, m=scala.Symbol
 
-x=List(()), m=scala.List[void]
-x=List(true), m=scala.List[boolean]
-x=List(1), m=scala.List[int]
-x=List(abc), m=scala.List[java.lang.String]
-x=List('abc), m=scala.List[scala.Symbol]
-
-x=[Z, m=Array[boolean]
-x=[C, m=Array[char]
-x=[I, m=Array[int]
-x=Array(abc), m=Array[java.lang.String]
-x=Array('abc), m=Array[scala.Symbol]
-
-x=((),()), m=scala.Tuple2[void, void]
-x=(true,false), m=scala.Tuple2[boolean, boolean]
-x=(1,2), m=scala.Tuple2[int, int]
+x=List(()), m=scala.collection.immutable.List[Unit]
+x=List(true), m=scala.collection.immutable.List[Boolean]
+x=List(1), m=scala.collection.immutable.List[Int]
+x=List(abc), m=scala.collection.immutable.List[java.lang.String]
+x=List('abc), m=scala.collection.immutable.List[scala.Symbol]
+
+x=[Z, m=Array[Boolean]
+x=[C, m=Array[Char]
+x=[I, m=Array[Int]
+x=[Ljava.lang.String;, m=Array[java.lang.String]
+x=[Lscala.Symbol;, m=Array[scala.Symbol]
+
+x=((),()), m=scala.Tuple2[Unit, Unit]
+x=(true,false), m=scala.Tuple2[Boolean, Boolean]
+x=(1,2), m=scala.Tuple2[Int, Int]
 x=(abc,xyz), m=scala.Tuple2[java.lang.String, java.lang.String]
 x=('abc,'xyz), m=scala.Tuple2[scala.Symbol, scala.Symbol]
 
 x=Test$, m=Test$
-x=scala.List$, m=scala.List$
+x=scala.collection.immutable.List$, m=scala.collection.immutable.List$
 
-x=Foo, m=Foo[int]
-x=Foo, m=Foo[scala.List[int]]
-x=Foo, m=Foo[Foo[int]]
-x=Foo, m=Foo[scala.List[Foo[int]]]
+x=Foo, m=Foo[Int]
+x=Foo, m=Foo[scala.collection.immutable.List[Int]]
+x=Foo, m=Foo[Foo[Int]]
+x=Foo, m=Foo[scala.collection.immutable.List[Foo[Int]]]
 
 x=Test1$$anon$1, m=Test1$$anon$1
 
diff --git a/test/files/jvm/mkLibNatives.bat b/test/files/jvm/mkLibNatives.bat
index d58d021..100246a 100644
--- a/test/files/jvm/mkLibNatives.bat
+++ b/test/files/jvm/mkLibNatives.bat
@@ -2,7 +2,6 @@
 
 rem ##########################################################################
 rem # Author  : Stephane Micheloud
-rem # Revision: $Id: mkLibNatives.bat 16473 2008-11-01 20:01:29Z michelou $
 rem ##########################################################################
 
 rem ##########################################################################
diff --git a/test/files/jvm/mkLibNatives.sh b/test/files/jvm/mkLibNatives.sh
index 55eefbe..ed80c24 100644
--- a/test/files/jvm/mkLibNatives.sh
+++ b/test/files/jvm/mkLibNatives.sh
@@ -2,7 +2,6 @@
 
 ##############################################################################
 # Author  : Stephane Micheloud
-# Revision: $Id: mkLibNatives.sh 13914 2008-02-07 13:25:36Z dubochet $
 ##############################################################################
 
 ##############################################################################
diff --git a/test/files/jvm/nest.scala b/test/files/jvm/nest.scala
index 60f3a31..3ab6248 100644
--- a/test/files/jvm/nest.scala
+++ b/test/files/jvm/nest.scala
@@ -1,7 +1,6 @@
 //############################################################################
 // Test Scala interaction with Java nested classes and static members.
 //############################################################################
-// $Id: inner.scala 8902 2006-10-10 10:58:10 +0200 (Tue, 10 Oct 2006) mihaylov $
 
 /** found in nest.jar, compiled from nest.java */
 import nestpkg._;
diff --git a/test/files/jvm/nest/nest.java b/test/files/jvm/nest/nest.java
new file mode 100644
index 0000000..3f6f0be
--- /dev/null
+++ b/test/files/jvm/nest/nest.java
@@ -0,0 +1,38 @@
+package nestpkg;
+
+
+/** This file is needed for test 'nest.scala'. It should
+ *  be compiled with javac and packaged into lib/nest.jar
+ */
+public class nest {
+    public static class best {
+        public static class rest {
+            public static rest test = new rest();
+            public static int  x = 10;
+            public int inc(int i) {
+                return i + 1;
+            }
+        }
+    }
+
+
+    String name = "Outer name";
+
+    public class Inn {
+        int x;
+
+        public Inn(int x) {
+            this.x = x;
+        }
+
+        public void doSomething() {
+            System.out.println("Inn " + name + " x: " + x);
+        }
+    }
+
+    protected class ProtInn {
+        public void doSomething() {
+            System.out.println("ProtInn " + name);
+        }
+    }
+}
diff --git a/test/files/jvm/nest/nest.scala b/test/files/jvm/nest/nest.scala
new file mode 100644
index 0000000..3ab6248
--- /dev/null
+++ b/test/files/jvm/nest/nest.scala
@@ -0,0 +1,21 @@
+//############################################################################
+// Test Scala interaction with Java nested classes and static members.
+//############################################################################
+
+/** found in nest.jar, compiled from nest.java */
+import nestpkg._;
+
+object Test extends Application {
+  val x = nest.best.rest.test
+  Console.println(x.inc(1))
+
+  val o = new nest.best;
+  val r = new nest.best.rest;
+  Console.println(nest.best.rest.test.inc(2))
+  Console.println(nest.best.rest.x)
+
+  print("Instantiating public inner class: ")
+  val outer = new nest
+  val inn   = new outer.Inn(42)
+  inn.doSomething
+}
diff --git a/test/files/jvm5/outerEnum.check b/test/files/jvm/outerEnum.check
similarity index 100%
rename from test/files/jvm5/outerEnum.check
rename to test/files/jvm/outerEnum.check
diff --git a/test/files/jvm5/outerEnum.scala b/test/files/jvm/outerEnum.scala
similarity index 100%
rename from test/files/jvm5/outerEnum.scala
rename to test/files/jvm/outerEnum.scala
diff --git a/test/files/jvm/protectedacc.scala b/test/files/jvm/protectedacc.scala
index d3bd5c9..525725f 100644
--- a/test/files/jvm/protectedacc.scala
+++ b/test/files/jvm/protectedacc.scala
@@ -1,7 +1,6 @@
 //############################################################################
 // Test Java interaction with scala inner classes
 //############################################################################
-// $Id:  $
 
 import java.io.{BufferedReader, File, FileWriter, InputStreamReader}
 
diff --git a/test/files/jvm/reactor-exceptionOnSend.check b/test/files/jvm/reactor-exceptionOnSend.check
new file mode 100644
index 0000000..45d62e2
--- /dev/null
+++ b/test/files/jvm/reactor-exceptionOnSend.check
@@ -0,0 +1,2 @@
+receiver handles exception
+process
diff --git a/test/files/jvm/reactor-exceptionOnSend.scala b/test/files/jvm/reactor-exceptionOnSend.scala
new file mode 100644
index 0000000..3d9a042
--- /dev/null
+++ b/test/files/jvm/reactor-exceptionOnSend.scala
@@ -0,0 +1,55 @@
+import scala.actors.Reactor
+import scala.actors.Actor._
+
+case class MyException(text: String) extends Exception(text)
+
+object A extends Reactor[Any] {
+  override def exceptionHandler = {
+    case MyException(text) =>
+      println("receiver handles exception")
+  }
+
+  def guard(): Boolean =
+    if (state == 0) {
+      state = 1
+      throw MyException("illegal state")
+    } else
+      true
+
+  var state = 0
+
+  def act() {
+    try {
+    loop {
+      react {
+        case 'hello if guard() =>
+          println("process")
+          exit()
+      }
+    }
+    } catch {
+      case e: Throwable if (!e.isInstanceOf[scala.util.control.ControlThrowable] &&
+                            !e.isInstanceOf[MyException]) =>
+        e.printStackTrace()
+    }
+  }
+}
+
+object B extends Reactor[Any] {
+  def act() {
+    try {
+    A.start()
+    A ! 'hello
+    A ! 'hello
+    } catch {
+      case e: Throwable if !e.isInstanceOf[scala.util.control.ControlThrowable] =>
+        e.printStackTrace()
+    }
+  }
+}
+
+object Test {
+  def main(args: Array[String]) {
+    B.start()
+  }
+}
diff --git a/test/files/jvm/reactor-producer-consumer.check b/test/files/jvm/reactor-producer-consumer.check
new file mode 100644
index 0000000..d971cea
--- /dev/null
+++ b/test/files/jvm/reactor-producer-consumer.check
@@ -0,0 +1,10 @@
+42
+42
+42
+42
+42
+42
+42
+42
+42
+42
diff --git a/test/files/jvm/reactor-producer-consumer.scala b/test/files/jvm/reactor-producer-consumer.scala
new file mode 100644
index 0000000..8a6b17c
--- /dev/null
+++ b/test/files/jvm/reactor-producer-consumer.scala
@@ -0,0 +1,95 @@
+import scala.actors.Reactor
+
+object Test {
+  case class Stop()
+  case class Get(from: Reactor[Any])
+  case class Put(x: Int)
+
+  class UnboundedBuffer extends Reactor[Any] {
+    def act() {
+      try {
+      react {
+        case Stop() =>
+        case Get(from) =>
+          val consumer = from
+          react {
+            case msg @ Put(x) =>
+              consumer ! x
+              act()
+          }
+      }
+      } catch {
+        case e: Throwable if !e.isInstanceOf[scala.util.control.ControlThrowable] =>
+          e.printStackTrace()
+      }
+    }
+  }
+
+  class Producer(buf: UnboundedBuffer, n: Int, delay: Long, parent: Reactor[Any]) extends Reactor[Any] {
+    def act() {
+      try {
+      var i = 0
+      while (i < n) {
+        i += 1
+        if (delay > 0) Thread.sleep(delay)
+        buf ! Put(42)
+      }
+      parent ! Stop()
+      } catch {
+        case e: Throwable if !e.isInstanceOf[scala.util.control.ControlThrowable] =>
+          e.printStackTrace()
+      }
+    }
+  }
+
+  class Consumer(buf: UnboundedBuffer, n: Int, delay: Long, parent: Reactor[Any]) extends Reactor[Any] {
+    val step = n / 10
+    var i = 0
+    def act() {
+      try {
+      if (i < n) {
+        i += 1
+        if (delay > 0) Thread.sleep(delay)
+        buf ! Get(this)
+        react {
+          case res =>
+            if (i % step == 0)
+              println(res)
+            act()
+        }
+      } else {
+        parent ! Stop()
+      }
+      } catch {
+        case e: Throwable if !e.isInstanceOf[scala.util.control.ControlThrowable] =>
+          e.printStackTrace()
+      }
+    }
+  }
+
+  def main(args: Array[String]) {
+    val parent = new Reactor[Any] {
+      def act() {
+        try {
+        val buffer = new UnboundedBuffer
+        buffer.start()
+        val producer = new Producer(buffer, 10000, 0, this)
+        producer.start()
+        val consumer = new Consumer(buffer, 10000, 0, this)
+        consumer.start()
+        react {
+          case Stop() =>
+            react {
+              case Stop() =>
+                buffer ! Stop()
+            }
+        }
+        } catch {
+          case e: Throwable if !e.isInstanceOf[scala.util.control.ControlThrowable] =>
+            e.printStackTrace()
+        }
+      }
+    }
+    parent.start()
+  }
+}
diff --git a/test/files/jvm/reactor.check b/test/files/jvm/reactor.check
new file mode 100644
index 0000000..7b16085
--- /dev/null
+++ b/test/files/jvm/reactor.check
@@ -0,0 +1,22 @@
+Pong: ping 0
+Ping: pong
+Pong: ping 10000
+Ping: pong
+Pong: ping 20000
+Ping: pong
+Pong: ping 30000
+Ping: pong
+Pong: ping 40000
+Ping: pong
+Pong: ping 50000
+Ping: pong
+Pong: ping 60000
+Ping: pong
+Pong: ping 70000
+Ping: pong
+Pong: ping 80000
+Ping: pong
+Pong: ping 90000
+Ping: pong
+Ping: stop
+Pong: stop
diff --git a/test/files/jvm/reactor.scala b/test/files/jvm/reactor.scala
new file mode 100644
index 0000000..dbc9a6b
--- /dev/null
+++ b/test/files/jvm/reactor.scala
@@ -0,0 +1,70 @@
+
+import scala.actors.Reactor
+
+case class Ping(from: Reactor[Any])
+case object Pong
+case object Stop
+
+/**
+ * Ping pong example for Reactor.
+ *
+ * @author  Philipp Haller
+ */
+object Test {
+  def main(args: Array[String]) {
+    val pong = new PongActor
+    val ping = new PingActor(100000, pong)
+    ping.start
+    pong.start
+  }
+}
+
+class PingActor(count: Int, pong: Reactor[Any]) extends Reactor[Any] {
+  def act() {
+    try {
+    var pingsLeft = count - 1
+    pong ! Ping(this)
+    loop {
+      react {
+        case Pong =>
+          if (pingsLeft % 10000 == 0)
+            println("Ping: pong")
+          if (pingsLeft > 0) {
+            pong ! Ping(this)
+            pingsLeft -= 1
+          } else {
+            println("Ping: stop")
+            pong ! Stop
+            exit()
+          }
+      }
+    }
+    } catch {
+      case e: Throwable if !e.isInstanceOf[scala.util.control.ControlThrowable] =>
+        e.printStackTrace()
+    }
+  }
+}
+
+class PongActor extends Reactor[Any] {
+  def act() {
+    try {
+    var pongCount = 0
+    loop {
+      react {
+        case Ping(from) =>
+          if (pongCount % 10000 == 0)
+            println("Pong: ping "+pongCount)
+          from ! Pong
+          pongCount += 1
+        case Stop =>
+          println("Pong: stop")
+          exit()
+      }
+    }
+    } catch {
+      case e: Throwable if !e.isInstanceOf[scala.util.control.ControlThrowable] =>
+        e.printStackTrace()
+    }
+  }
+}
diff --git a/test/files/jvm/actor-bangbang.check b/test/files/jvm/replyablereactor.check
similarity index 100%
copy from test/files/jvm/actor-bangbang.check
copy to test/files/jvm/replyablereactor.check
diff --git a/test/files/jvm/replyablereactor.scala b/test/files/jvm/replyablereactor.scala
new file mode 100644
index 0000000..e1fabc9
--- /dev/null
+++ b/test/files/jvm/replyablereactor.scala
@@ -0,0 +1,56 @@
+import scala.actors.ReplyReactor
+
+class MyActor extends ReplyReactor {
+  def act() {
+    try {
+    loop {
+      react {
+        case 'hello =>
+          sender ! 'hello
+        case 'stop =>
+          exit()
+      }
+    }
+    } catch {
+      case e: Throwable if !e.isInstanceOf[scala.util.control.ControlThrowable] =>
+        e.printStackTrace()
+    }
+  }
+}
+
+object Test {
+  def main(args: Array[String]) {
+    val a = new MyActor
+    a.start()
+
+    val b = new ReplyReactor {
+      def act() {
+        try {
+        react {
+          case r: MyActor =>
+            var i = 0
+            loop {
+              i += 1
+              val ft = r !! 'hello
+              ft.inputChannel.react {
+                case msg =>
+                  if (i % 10000 == 0)
+                    println(msg)
+                  if (i >= 50000) {
+                    r ! 'stop
+                    exit()
+                  }
+              }
+            }
+        }
+        } catch {
+          case e: Throwable if !e.isInstanceOf[scala.util.control.ControlThrowable] =>
+            e.printStackTrace()
+        }
+      }
+    }
+    b.start()
+
+    b ! a
+  }
+}
diff --git a/test/files/jvm/actor-bangbang2.check b/test/files/jvm/replyablereactor2.check
similarity index 100%
rename from test/files/jvm/actor-bangbang2.check
rename to test/files/jvm/replyablereactor2.check
diff --git a/test/files/jvm/replyablereactor2.scala b/test/files/jvm/replyablereactor2.scala
new file mode 100644
index 0000000..da9e0e2
--- /dev/null
+++ b/test/files/jvm/replyablereactor2.scala
@@ -0,0 +1,55 @@
+import scala.actors._
+import scala.actors.Actor._
+
+class MyActor extends ReplyReactor {
+  def act() {
+    try {
+    loop {
+      react {
+        case 'hello =>
+          sender ! 'hello
+        case 'stop =>
+          exit()
+      }
+    }
+    } catch {
+      case e: Throwable if !e.isInstanceOf[scala.util.control.ControlThrowable] =>
+        e.printStackTrace()
+    }
+  }
+}
+
+object Test {
+  def main(args: Array[String]) {
+    val a = new MyActor
+    a.start()
+
+    val b = new Reactor[Any] {
+      def act() {
+        try {
+        react {
+          case r: MyActor =>
+            var i = 0
+            loop {
+              i += 1
+              val ft = r !! 'hello
+              val msg = ft()
+              if (i % 10000 == 0)
+                println(msg)
+              if (i >= 50000) {
+                r ! 'stop
+                exit()
+              }
+            }
+        }
+        } catch {
+          case e: Throwable if !e.isInstanceOf[scala.util.control.ControlThrowable] =>
+            e.printStackTrace()
+        }
+      }
+    }
+    b.start()
+
+    b ! a
+  }
+}
diff --git a/test/files/jvm/actor-syncsend.check b/test/files/jvm/replyablereactor3.check
similarity index 100%
rename from test/files/jvm/actor-syncsend.check
rename to test/files/jvm/replyablereactor3.check
diff --git a/test/files/jvm/replyablereactor3.scala b/test/files/jvm/replyablereactor3.scala
new file mode 100644
index 0000000..2c26b8a
--- /dev/null
+++ b/test/files/jvm/replyablereactor3.scala
@@ -0,0 +1,54 @@
+import scala.actors._
+import scala.actors.Actor._
+
+class MyActor extends ReplyReactor {
+  def act() {
+    try {
+    loop {
+      react {
+        case 'hello =>
+          sender ! 'hello
+        case 'stop =>
+          exit()
+      }
+    }
+    } catch {
+      case e: Throwable if !e.isInstanceOf[scala.util.control.ControlThrowable] =>
+        e.printStackTrace()
+    }
+  }
+}
+
+object Test {
+  def main(args: Array[String]) {
+    val a = new MyActor
+    a.start()
+
+    val b = new Reactor[Any] {
+      def act() {
+        try {
+        react {
+          case r: MyActor =>
+            var i = 0
+            loop {
+              i += 1
+              val msg = r !? 'hello
+              if (i % 10000 == 0)
+                println(msg)
+              if (i >= 50000) {
+                r ! 'stop
+                exit()
+              }
+            }
+        }
+        } catch {
+          case e: Throwable if !e.isInstanceOf[scala.util.control.ControlThrowable] =>
+            e.printStackTrace()
+        }
+      }
+    }
+    b.start()
+
+    b ! a
+  }
+}
diff --git a/test/files/jvm/actor-syncsend2.check b/test/files/jvm/replyablereactor4.check
similarity index 100%
rename from test/files/jvm/actor-syncsend2.check
rename to test/files/jvm/replyablereactor4.check
diff --git a/test/files/jvm/replyablereactor4.scala b/test/files/jvm/replyablereactor4.scala
new file mode 100644
index 0000000..7679a5a
--- /dev/null
+++ b/test/files/jvm/replyablereactor4.scala
@@ -0,0 +1,54 @@
+import scala.actors._
+import scala.actors.Actor._
+
+class MyActor extends ReplyReactor {
+  def act() {
+    try {
+    loop {
+      react {
+        case 'hello =>
+          sender ! 'hello
+        case 'stop =>
+          exit()
+      }
+    }
+    } catch {
+      case e: Throwable if !e.isInstanceOf[scala.util.control.ControlThrowable] =>
+        e.printStackTrace()
+    }
+  }
+}
+
+object Test {
+  def main(args: Array[String]) {
+    val a = new MyActor
+    a.start()
+
+    val b = new Reactor[Any] {
+      def act() {
+        try {
+        react {
+          case r: MyActor =>
+            var i = 0
+            loop {
+              i += 1
+              val msg = r !? (500, 'hello)
+              if (i % 10000 == 0)
+                println(msg)
+              if (i >= 50000) {
+                r ! 'stop
+                exit()
+              }
+            }
+        }
+        } catch {
+          case e: Throwable if !e.isInstanceOf[scala.util.control.ControlThrowable] =>
+            e.printStackTrace()
+        }
+      }
+    }
+    b.start()
+
+    b ! a
+  }
+}
diff --git a/test/files/jvm/replyreactor-react-sender.check b/test/files/jvm/replyreactor-react-sender.check
new file mode 100644
index 0000000..d86bac9
--- /dev/null
+++ b/test/files/jvm/replyreactor-react-sender.check
@@ -0,0 +1 @@
+OK
diff --git a/test/files/jvm/replyreactor-react-sender.scala b/test/files/jvm/replyreactor-react-sender.scala
new file mode 100644
index 0000000..c988429
--- /dev/null
+++ b/test/files/jvm/replyreactor-react-sender.scala
@@ -0,0 +1,51 @@
+import scala.actors.ReplyReactor
+import scala.actors.Actor._
+
+object Test {
+
+  val NUM = 2000
+
+  def main(args: Array[String]) {
+    var b: ReplyReactor = null
+
+    val a = new ReplyReactor {
+      def act() {
+        try {
+        var i = 0
+        loopWhile (i < NUM) {
+          i += 1
+          react {
+            case 'hello if sender == this => b ! 'fail
+            case 'hello if sender == b => // do nothing
+          }
+        } andThen {
+          b ! 'ok
+        }
+        } catch {
+          case e: Throwable if !e.isInstanceOf[scala.util.control.ControlThrowable] =>
+            e.printStackTrace()
+        }
+      }
+    }
+    a.start()
+
+    b = new ReplyReactor {
+      def act() {
+        try {
+        for (_ <- 0 until NUM)
+          a ! 'hello
+        react {
+          case 'fail => println("FAIL")
+          case 'ok   => println("OK")
+          case other => println(other)
+        }
+        } catch {
+          case e: Throwable if !e.isInstanceOf[scala.util.control.ControlThrowable] =>
+            e.printStackTrace()
+        }
+      }
+    }
+    b.start()
+  }
+
+}
diff --git a/test/files/jvm/actor-reply.check b/test/files/jvm/replyreactor.check
similarity index 100%
rename from test/files/jvm/actor-reply.check
rename to test/files/jvm/replyreactor.check
diff --git a/test/files/jvm/replyreactor.scala b/test/files/jvm/replyreactor.scala
new file mode 100644
index 0000000..0cecf29
--- /dev/null
+++ b/test/files/jvm/replyreactor.scala
@@ -0,0 +1,41 @@
+import scala.actors.ReplyReactor
+
+object Test {
+  def main(args: Array[String]) {
+    val a = new ReplyReactor {
+      def act() {
+        try {
+        react {
+          case 'hello =>
+            sender ! 'hello
+        }
+        } catch {
+          case e: Throwable if !e.isInstanceOf[scala.util.control.ControlThrowable] =>
+            e.printStackTrace()
+        }
+      }
+    }
+    a.start()
+
+    val b = new ReplyReactor {
+      def act() {
+        try {
+        react {
+          case r: ReplyReactor =>
+            r ! 'hello
+            react {
+              case any =>
+                println(any)
+            }
+        }
+        } catch {
+          case e: Throwable if !e.isInstanceOf[scala.util.control.ControlThrowable] =>
+            e.printStackTrace()
+        }
+      }
+    }
+    b.start()
+
+    b ! a
+  }
+}
diff --git a/test/files/jvm/scheduler-adapter.check b/test/files/jvm/scheduler-adapter.check
new file mode 100644
index 0000000..b278674
--- /dev/null
+++ b/test/files/jvm/scheduler-adapter.check
@@ -0,0 +1,6 @@
+before
+before
+before
+Two: received msg
+before
+One: received msg
diff --git a/test/files/jvm/scheduler-adapter.scala b/test/files/jvm/scheduler-adapter.scala
new file mode 100644
index 0000000..d6a8a44
--- /dev/null
+++ b/test/files/jvm/scheduler-adapter.scala
@@ -0,0 +1,51 @@
+import scala.actors.{Actor, SchedulerAdapter}
+
+trait AdaptedActor extends Actor {
+  override def scheduler =
+    Test.adapted
+}
+
+object One extends AdaptedActor {
+  def act() {
+    try {
+    Two.start()
+    Two ! 'MsgForTwo
+    react {
+      case 'MsgForOne =>
+        println("One: received msg")
+    }
+    } catch {
+      case e: Throwable if !e.isInstanceOf[scala.util.control.ControlThrowable] =>
+        e.printStackTrace()
+    }
+  }
+}
+
+object Two extends AdaptedActor {
+  def act() {
+    try {
+    react {
+      case 'MsgForTwo =>
+        println("Two: received msg")
+        One ! 'MsgForOne
+    }
+    } catch {
+      case e: Throwable if !e.isInstanceOf[scala.util.control.ControlThrowable] =>
+        e.printStackTrace()
+    }
+  }
+}
+
+object Test {
+  val adapted =
+    new SchedulerAdapter {
+      def execute(block: => Unit) {
+        println("before")
+        block
+      }
+    }
+
+  def main(args: Array[String]) {
+    One.start()
+  }
+}
diff --git a/test/files/jvm/serialization.check b/test/files/jvm/serialization.check
index 7125d4b..3f095cb 100644
--- a/test/files/jvm/serialization.check
+++ b/test/files/jvm/serialization.check
@@ -1,130 +1,209 @@
-x0 = List(1, 2, 3)
-y0 = List(1, 2, 3)
-x0 eq y0: false - y0 eq x0: false
-x0 equals y0: true - y0 equals x0: true
-
-x1 = List()
-y1 = List()
-x1 eq y1: true - y1 eq x1: true
-
-x2 = None
-y2 = None
-x2 eq y2: true - y2 eq x2: true
-
-x3 = Array[1,2,3]
-y3 = Array[1,2,3]
-arrayEquals(x3, y3): true
-
-x4 = <na>
-y4 = <na>
-x4(2): 4 - y4(2): 4
-
-x5 = 'hello
-y5 = 'hello
-x5 eq y5: true - y5 eq x5: true
-x5 equals y5: true - y5 equals x5: true
-
-x6 = (BannerLimit,12345)
-y6 = (BannerLimit,12345)
-x6 eq y6: false - y6 eq x6: false
-x6 equals y6: true - y6 equals x6: true
-
-x7 = {scala.BigDecimal$RoundingMode(0), scala.BigDecimal$RoundingMode(1), scala.BigDecimal$RoundingMode(2), scala.BigDecimal$RoundingMode(3), scala.BigDecimal$RoundingMode(4), scala.BigDecimal$RoundingMode(5), scala.BigDecimal$RoundingMode(6), scala.BigDecimal$RoundingMode(7)}
-y7 = {scala.BigDecimal$RoundingMode(0), scala.BigDecimal$RoundingMode(1), scala.BigDecimal$RoundingMode(2), scala.BigDecimal$RoundingMode(3), scala.BigDecimal$RoundingMode(4), scala.BigDecimal$RoundingMode(5), scala.BigDecimal$RoundingMode(6), scala.BigDecimal$RoundingMode(7)}
-x7 eq y7: true - y7 eq x7: true
-x7 equals y7: true - y7 equals x7: true
-
-x8 = {Test1_scala$WeekDay(0), Test1_scala$WeekDay(1), Test1_scala$WeekDay(2), Test1_scala$WeekDay(3), Test1_scala$WeekDay(4), Test1_scala$WeekDay(5), Test1_scala$WeekDay(6)}
-y8 = {Test1_scala$WeekDay(0), Test1_scala$WeekDay(1), Test1_scala$WeekDay(2), Test1_scala$WeekDay(3), Test1_scala$WeekDay(4), Test1_scala$WeekDay(5), Test1_scala$WeekDay(6)}
-x8 eq y8: true - y8 eq x8: true
-x8 equals y8: true - y8 equals x8: true
-
-x9 = scala.BigDecimal$RoundingMode(0)
-y9 = scala.BigDecimal$RoundingMode(0)
-x9 eq y9: true - y9 eq x9: true
-x9 equals y9: true - y9 equals x9: true
-
-x10 = Test1_scala$WeekDay(0)
-y10 = Test1_scala$WeekDay(0)
-x10 eq y10: true - y10 eq x10: true
-x10 equals y10: true - y10 equals x10: true
-
-x9 eq x10: false - x10 eq x9: false
-x9 equals x10: false - x10 equals x9: false
-x9 eq y10: false - y10 eq x9: false
-x9 equals y10: false - y10 equals x9: false
+a1 = Array[1,2,3]
+_a1 = Array[1,2,3]
+arrayEquals(a1, _a1): true
+
+c1 = Cell(a)
+_c1 = Cell(a)
+c1 eq _c1: false, _c1 eq c1: false
+c1 equals _c1: true, _c1 equals c1: true
+
+e1 = Left(1)
+_e1 = Left(1)
+e1 eq _e1: false, _e1 eq e1: false
+e1 equals _e1: true, _e1 equals e1: true
+
+x7 = RoundingMode
+y7 = RoundingMode
+x7 eq y7: true, y7 eq x7: true
+x7 equals y7: true, y7 equals x7: true
+
+x8 = WeekDay
+y8 = WeekDay
+x8 eq y8: true, y8 eq x8: true
+x8 equals y8: true, y8 equals x8: true
+
+x9 = UP
+y9 = UP
+x9 eq y9: true, y9 eq x9: true
+x9 equals y9: true, y9 equals x9: true
+
+x10 = Monday
+y10 = Monday
+x10 eq y10: true, y10 eq x10: true
+x10 equals y10: true, y10 equals x10: true
+
+x9 eq x10: false, x10 eq x9: false
+x9 equals x10: false, x10 equals x9: false
+x9 eq y10: false, y10 eq x9: false
+x9 equals y10: false, y10 equals x9: false
+
+f1 = <na>
+_f1 = <na>
+f1(2): 4, _f1(2): 4
+
+xs0 = List(1, 2, 3)
+_xs0 = List(1, 2, 3)
+xs0 eq _xs0: false, _xs0 eq xs0: false
+xs0 equals _xs0: true, _xs0 equals xs0: true
+
+xs1 = List()
+_xs1 = List()
+xs1 eq _xs1: true, _xs1 eq xs1: true
+
+o1 = None
+_o1 = None
+o1 eq _o1: true, _o1 eq o1: true
+
+o2 = Some(1)
+_o2 = Some(1)
+o2 eq _o2: false, _o2 eq o2: false
+o2 equals _o2: true, _o2 equals o2: true
+
+s1 = 'hello
+_s1 = 'hello
+s1 eq _s1: true, _s1 eq s1: true
+s1 equals _s1: true, _s1 equals s1: true
+
+t1 = (BannerLimit,12345)
+_t1 = (BannerLimit,12345)
+t1 eq _t1: false, _t1 eq t1: false
+t1 equals _t1: true, _t1 equals t1: true
+
+x = BitSet(1, 2)
+y = BitSet(1, 2)
+x equals y: true, y equals x: true
+
+x = BitSet(2, 3)
+y = BitSet(2, 3)
+x equals y: true, y equals x: true
+
+x = Map(1 -> A, 2 -> B, 3 -> C)
+y = Map(1 -> A, 2 -> B, 3 -> C)
+x equals y: true, y equals x: true
+
+x = Set(1, 2)
+y = Set(1, 2)
+x equals y: true, y equals x: true
 
 x = List((buffers,20), (layers,2), (title,3))
 y = List((buffers,20), (layers,2), (title,3))
-x equals y: true - y equals x: true
+x equals y: true, y equals x: true
 
 x = Map(buffers -> 20, layers -> 2, title -> 3)
 y = Map(buffers -> 20, layers -> 2, title -> 3)
-x equals y: true - y equals x: true
-
-x = Set(2, 3)
-y = Set(2, 3)
-x equals y: true - y equals x: true
+x equals y: true, y equals x: true
 
 x = Set(5, 3)
 y = Set(5, 3)
-x equals y: true - y equals x: true
+x equals y: true, y equals x: true
 
 x = Queue(a, b, c)
 y = Queue(a, b, c)
-x equals y: true - y equals x: true
+x equals y: true, y equals x: true
+
+x = Range(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
+y = Range(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
+x equals y: true, y equals x: true
+
+x = NumericRange(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
+y = NumericRange(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
+x equals y: true, y equals x: true
+
+x = Map(1 -> A, 2 -> B, 3 -> C)
+y = Map(1 -> A, 2 -> B, 3 -> C)
+x equals y: true, y equals x: true
+
+x = TreeSet(1, 2, 3)
+y = TreeSet(1, 2, 3)
+x equals y: true, y equals x: true
 
-x = Stack(a, b, c)
-y = Stack(a, b, c)
-x equals y: true - y equals x: true
+x = Stack(c, b, a)
+y = Stack(c, b, a)
+x equals y: true, y equals x: true
+
+x = Stream(0, ?)
+y = Stream(0, ?)
+x equals y: true, y equals x: true
 
 x = Map(42 -> FortyTwo)
 y = Map(42 -> FortyTwo)
-x equals y: true - y equals x: true
+x equals y: true, y equals x: true
+
+x = TreeSet(0, 2)
+y = TreeSet(0, 2)
+x equals y: true, y equals x: true
 
-x = Set(0, 2)
-y = Set(0, 2)
-x equals y: true - y equals x: true
+x = Vector('a, 'b, 'c)
+y = Vector('a, 'b, 'c)
+x equals y: true, y equals x: true
 
 x = ArrayBuffer(one, two)
 y = ArrayBuffer(one, two)
-x equals y: true - y equals x: true
+x equals y: true, y equals x: true
+
+x = ArrayBuilder.ofLong
+y = ArrayBuilder.ofLong
+x equals y: true, y equals x: true
+
+x = ArrayBuilder.ofFloat
+y = ArrayBuilder.ofFloat
+x equals y: true, y equals x: true
 
-x = Map(title -> 3, buffers -> 20, layers -> 2)
-y = Map(title -> 3, buffers -> 20, layers -> 2)
-x equals y: true - y equals x: true
+x = ArrayStack(3, 2, 20)
+y = ArrayStack(3, 2, 20)
+x equals y: true, y equals x: true
 
-x = Set(0, 8, 9)
-y = Set(0, 8, 9)
-x equals y: true - y equals x: true
+x = BitSet(0, 8, 9)
+y = BitSet(0, 8, 9)
+x equals y: true, y equals x: true
+
+x = Map(A -> 1, C -> 3, B -> 2)
+y = Map(B -> 2, C -> 3, A -> 1)
+x equals y: true, y equals x: true
 
 x = Set(layers, buffers, title)
 y = Set(layers, buffers, title)
-x equals y: true - y equals x: true
+x equals y: true, y equals x: true
 
-x = LinkedList(2, 3)
-y = LinkedList(2, 3)
-x equals y: true - y equals x: true
+x = History()
+y = History()
+x equals y: true, y equals x: true
+
+x = ListBuffer(white, black)
+y = ListBuffer(white, black)
+x equals y: true, y equals x: true
 
 x = Queue(20, 2, 3)
 y = Queue(20, 2, 3)
-x equals y: true - y equals x: true
+x equals y: true, y equals x: true
 
-x = Stack(20, 2, 3)
-y = Stack(20, 2, 3)
-x equals y: true - y equals x: true
+x = Stack(3, 2, 20)
+y = Stack(3, 2, 20)
+x equals y: true, y equals x: true
 
-x = ListBuffer(white, black)
-y = ListBuffer(white, black)
-x equals y: true - y equals x: true
+x = abc
+y = abc
+x equals y: true, y equals x: true
+
+x = WrappedArray(1, 2, 3)
+y = WrappedArray(1, 2, 3)
+x equals y: true, y equals x: true
+
+x =  xml:src="hello"
+y =  xml:src="hello"
+x equals y: true, y equals x: true
+
+x = <title></title>
+y = <title></title>
+x equals y: true, y equals x: true
 
 x = <html><title>title</title><body></body></html>
 y = <html><title>title</title><body></body></html>
-x equals y: true - y equals x: true
+x equals y: true, y equals x: true
 
 x = <html>
       <body>
-       <table cellpadding="2" cellspacing="0">
+        <table cellpadding="2" cellspacing="0">
         <tr>
           <th>Last Name</th>
           <th>First Name</th>
@@ -141,10 +220,10 @@ x = <html>
         </tr>
       </table>
       </body>
-    </html>
+      </html>
 y = <html>
       <body>
-       <table cellpadding="2" cellspacing="0">
+        <table cellpadding="2" cellspacing="0">
         <tr>
           <th>Last Name</th>
           <th>First Name</th>
@@ -161,26 +240,26 @@ y = <html>
         </tr>
       </table>
       </body>
-    </html>
-x equals y: true - y equals x: true
+      </html>
+x equals y: true, y equals x: true
 
 x = Tim
 y = Tim
-x equals y: true - y equals x: true
+x equals y: true, y equals x: true
 
 x = Bob
 y = Bob
-x equals y: true - y equals x: true
+x equals y: true, y equals x: true
 
 x = John
 y = John
-x equals y: true - y equals x: true
+x equals y: true, y equals x: true
 
 x = Bill
 y = Bill
-x equals y: true - y equals x: true
+x equals y: true, y equals x: true
 
 x = Paul
 y = Paul
-x equals y: true - y equals x: true
+x equals y: true, y equals x: true
 
diff --git a/test/files/jvm/serialization.scala b/test/files/jvm/serialization.scala
index 609210e..06086f4 100644
--- a/test/files/jvm/serialization.scala
+++ b/test/files/jvm/serialization.scala
@@ -1,18 +1,6 @@
 //############################################################################
 // Serialization
 //############################################################################
-// $Id: serialization.scala 15934 2008-08-26 12:10:05Z michelou $
-
-import java.lang.System
-
-object EqualityTest {
-  def check[A, B](x: A, y: B) {
-    println("x = " + x)
-    println("y = " + y)
-    println("x equals y: " + (x equals y) + " - y equals x: " + (y equals x))
-    println()
-  }
-}
 
 object Serialize {
   @throws(classOf[java.io.IOException])
@@ -30,7 +18,14 @@ object Serialize {
       new java.io.ObjectInputStream(new java.io.ByteArrayInputStream(buffer))
     in.readObject().asInstanceOf[A]
   }
+  def check[A, B](x: A, y: B) {
+    println("x = " + x)
+    println("y = " + y)
+    println("x equals y: " + (x equals y) + ", y equals x: " + (y equals x))
+    println()
+  }
 }
+import Serialize._
 
 //############################################################################
 // Test classes in package "scala"
@@ -38,7 +33,7 @@ object Serialize {
 object Test1_scala {
 
   private def arrayToString[A](arr: Array[A]): String =
-    List.fromArray(arr).mkString("Array[",",","]")
+    arr.mkString("Array[",",","]")
 
   private def arrayEquals[A, B](a1: Array[A], a2: Array[B]): Boolean =
     (a1.length == a2.length) &&
@@ -51,92 +46,140 @@ object Test1_scala {
   }
   import WeekDay._, BigDecimal._, RoundingMode._
 
-  val x0 = List(1, 2, 3)
-  val x1 = Nil
-  val x2 = None
-  val x3 = Array(1, 2, 3)
-  val x4 = { x: Int => 2 * x }
-  val x5 = 'hello
-  val x6 = ("BannerLimit", 12345)
-  val x7 = BigDecimal.RoundingMode
-  val x8 = WeekDay
-  val x9 = ROUND_UP
-  val x10 = Monday
-
+  // in alphabetic order
   try {
-    val y0: List[Int]          = Serialize.read(Serialize.write(x0))
-    val y1: List[Nothing]      = Serialize.read(Serialize.write(x1))
-    val y2: Option[Nothing]    = Serialize.read(Serialize.write(x2))
-    val y3: Array[Int]         = Serialize.read(Serialize.write(x3))
-    val y4: Function[Int, Int] = Serialize.read(Serialize.write(x4))
-    val y5: Symbol             = Serialize.read(Serialize.write(x5))
-    val y6: (String, Int)      = Serialize.read(Serialize.write(x6))
-    val y7: RoundingMode.type  = Serialize.read(Serialize.write(x7))
-    val y8: WeekDay.type       = Serialize.read(Serialize.write(x8))
-    val y9: RoundingMode       = Serialize.read(Serialize.write(x9))
-    val y10: WeekDay           = Serialize.read(Serialize.write(x10))
-
-    println("x0 = " + x0)
-    println("y0 = " + y0)
-    println("x0 eq y0: " + (x0 eq y0) + " - y0 eq x0: " + (y0 eq x0))
-    println("x0 equals y0: " + (x0 equals y0) + " - y0 equals x0: " + (y0 equals x0))
-    println()
-    println("x1 = " + x1)
-    println("y1 = " + y1)
-    println("x1 eq y1: " + (x1 eq y1) + " - y1 eq x1: " + (y1 eq x1))
-    println()
-    println("x2 = " + x2)
-    println("y2 = " + y2)
-    println("x2 eq y2: " + (x2 eq y2) + " - y2 eq x2: " + (y2 eq x2))
-    println()
-    println("x3 = " + arrayToString(x3))
-    println("y3 = " + arrayToString(y3))
-    println("arrayEquals(x3, y3): " + arrayEquals(x3, y3))
+    // Array
+    val a1 = Array(1, 2, 3)
+    val _a1: Array[Int] = read(write(a1))
+    println("a1 = " + arrayToString(a1))
+    println("_a1 = " + arrayToString(_a1))
+    println("arrayEquals(a1, _a1): " + arrayEquals(a1, _a1))
     println()
-    println("x4 = <na>")
-    println("y4 = <na>")
-    println("x4(2): " + x4(2) + " - y4(2): " + y4(2))
-    println()
-    println("x5 = " + x5)
-    println("y5 = " + y5)
-    println("x5 eq y5: " + (x5 eq y5) + " - y5 eq x5: " + (y5 eq x5))
-    println("x5 equals y5: " + (x5 equals y5) + " - y5 equals x5: " + (y5 equals x5))
+
+    // Cell
+    val c1 = new Cell('a')
+    val _c1: Cell[Char] = read(write(c1))
+    println("c1 = " + c1)
+    println("_c1 = " + _c1)
+    println("c1 eq _c1: " + (c1 eq _c1) + ", _c1 eq c1: " + (_c1 eq c1))
+    println("c1 equals _c1: " + (c1 equals _c1) + ", _c1 equals c1: " + (_c1 equals c1))
     println()
-    println("x6 = " + x6)
-    println("y6 = " + y6)
-    println("x6 eq y6: " + (x6 eq y6) + " - y6 eq x6: " + (y6 eq x6))
-    println("x6 equals y6: " + (x6 equals y6) + " - y6 equals x6: " + (y6 equals x6))
+
+    // Either
+    val e1 = Left(1)
+    val _e1: Either[Int, String] = read(write(e1))
+    println("e1 = " + e1)
+    println("_e1 = " + _e1)
+    println("e1 eq _e1: " + (e1 eq _e1) + ", _e1 eq e1: " + (_e1 eq e1))
+    println("e1 equals _e1: " + (e1 equals _e1) + ", _e1 equals e1: " + (_e1 equals e1))
     println()
+
+    // Enumeration
+    val x7 = BigDecimal.RoundingMode
+    val y7: RoundingMode.type = read(write(x7))
     println("x7 = " + x7)
     println("y7 = " + y7)
-    println("x7 eq y7: " + (x7 eq y7) + " - y7 eq x7: " + (y7 eq x7))
-    println("x7 equals y7: " + (x7 equals y7) + " - y7 equals x7: " + (y7 equals x7))
+    println("x7 eq y7: " + (x7 eq y7) + ", y7 eq x7: " + (y7 eq x7))
+    println("x7 equals y7: " + (x7 equals y7) + ", y7 equals x7: " + (y7 equals x7))
     println()
+
+    val x8 = WeekDay
+    val y8: WeekDay.type = read(write(x8))
     println("x8 = " + x8)
     println("y8 = " + y8)
-    println("x8 eq y8: " + (x8 eq y8) + " - y8 eq x8: " + (y8 eq x8))
-    println("x8 equals y8: " + (x8 equals y8) + " - y8 equals x8: " + (y8 equals x8))
+    println("x8 eq y8: " + (x8 eq y8) + ", y8 eq x8: " + (y8 eq x8))
+    println("x8 equals y8: " + (x8 equals y8) + ", y8 equals x8: " + (y8 equals x8))
     println()
+
+    val x9 = UP
+    val y9: RoundingMode = read(write(x9))
     println("x9 = " + x9)
     println("y9 = " + y9)
-    println("x9 eq y9: " + (x9 eq y9) + " - y9 eq x9: " + (y9 eq x9))
-    println("x9 equals y9: " + (x9 equals y9) + " - y9 equals x9: " + (y9 equals x9))
+    println("x9 eq y9: " + (x9 eq y9) + ", y9 eq x9: " + (y9 eq x9))
+    println("x9 equals y9: " + (x9 equals y9) + ", y9 equals x9: " + (y9 equals x9))
     println()
+
+    val x10 = Monday
+    val y10: WeekDay = read(write(x10))
     println("x10 = " + x10)
     println("y10 = " + y10)
-    println("x10 eq y10: " + (x10 eq y10) + " - y10 eq x10: " + (y10 eq x10))
-    println("x10 equals y10: " + (x10 equals y10) + " - y10 equals x10: " + (y10 equals x10))
+    println("x10 eq y10: " + (x10 eq y10) + ", y10 eq x10: " + (y10 eq x10))
+    println("x10 equals y10: " + (x10 equals y10) + ", y10 equals x10: " + (y10 equals x10))
     println()
-    println("x9 eq x10: " + (x9 eq x10) + " - x10 eq x9: " + (x10 eq x9))
-    println("x9 equals x10: " + (x9 equals x10) + " - x10 equals x9: " + (x10 equals x9))
-    println("x9 eq y10: " + (x9 eq y10) + " - y10 eq x9: " + (y10 eq x9))
-    println("x9 equals y10: " + (x9 equals y10) + " - y10 equals x9: " + (y10 equals x9))
+
+    println("x9 eq x10: " + (x9 eq x10) + ", x10 eq x9: " + (x10 eq x9))
+    println("x9 equals x10: " + (x9 equals x10) + ", x10 equals x9: " + (x10 equals x9))
+    println("x9 eq y10: " + (x9 eq y10) + ", y10 eq x9: " + (y10 eq x9))
+    println("x9 equals y10: " + (x9 equals y10) + ", y10 equals x9: " + (y10 equals x9))
+    println()
+
+    // Function
+    val f1 = { x: Int => 2 * x }
+    val _f1: Function[Int, Int] = read(write(f1))
+    println("f1 = <na>")
+    println("_f1 = <na>")
+    println("f1(2): " + f1(2) + ", _f1(2): " + _f1(2))
+    println()
+
+    // List
+    val xs0 = List(1, 2, 3)
+    val _xs0: List[Int] = read(write(xs0))
+    println("xs0 = " + xs0)
+    println("_xs0 = " + _xs0)
+    println("xs0 eq _xs0: " + (xs0 eq _xs0) + ", _xs0 eq xs0: " + (_xs0 eq xs0))
+    println("xs0 equals _xs0: " + (xs0 equals _xs0) + ", _xs0 equals xs0: " + (_xs0 equals xs0))
+    println()
+
+    val xs1 = Nil
+    val _xs1: List[Nothing] = read(write(xs1))
+    println("xs1 = " + xs1)
+    println("_xs1 = " + _xs1)
+    println("xs1 eq _xs1: " + (xs1 eq _xs1) + ", _xs1 eq xs1: " + (_xs1 eq xs1))
+    println()
+
+    // Option
+    val o1 = None
+    val _o1: Option[Nothing] = read(write(o1))
+    println("o1 = " + o1)
+    println("_o1 = " + _o1)
+    println("o1 eq _o1: " + (o1 eq _o1) + ", _o1 eq o1: " + (_o1 eq o1))
+    println()
+
+    val o2 = Some(1)
+    val _o2: Option[Int] = read(write(o2))
+    println("o2 = " + o2)
+    println("_o2 = " + _o2)
+    println("o2 eq _o2: " + (o2 eq _o2) + ", _o2 eq o2: " + (_o2 eq o2))
+    println("o2 equals _o2: " + (o2 equals _o2) + ", _o2 equals o2: " + (_o2 equals o2))
+    println()
+/*
+    // Responder
+    val r1 = Responder.constant("xyz")
+    val _r1: Responder[String] = read(write(r1))
+    check(r1, _r1)
+*/
+    // Symbol
+    val s1 = 'hello
+    val _s1: Symbol = read(write(s1))
+    println("s1 = " + s1)
+    println("_s1 = " + _s1)
+    println("s1 eq _s1: " + (s1 eq _s1) + ", _s1 eq s1: " + (_s1 eq s1))
+    println("s1 equals _s1: " + (s1 equals _s1) + ", _s1 equals s1: " + (_s1 equals s1))
+    println()
+
+    // Tuple
+    val t1 = ("BannerLimit", 12345)
+    val _t1: (String, Int) = read(write(t1))
+    println("t1 = " + t1)
+    println("_t1 = " + _t1)
+    println("t1 eq _t1: " + (t1 eq _t1) + ", _t1 eq t1: " + (_t1 eq t1))
+    println("t1 equals _t1: " + (t1 equals _t1) + ", _t1 equals t1: " + (_t1 equals t1))
     println()
   }
   catch {
     case e: Exception =>
-      e.printStackTrace()
       println("Error in Test1_scala: " + e)
+      throw e
   }
 }
 
@@ -146,50 +189,97 @@ object Test1_scala {
 @serializable
 object Test2_immutable {
   import scala.collection.immutable.{
-    BitSet, ListMap, ListSet, Queue, Stack, TreeSet, TreeMap}
-
-  val x1 = List(
-    Pair("buffers", 20),
-    Pair("layers", 2),
-    Pair("title", 3)
-  )
-
-  val x2 = new ListMap[String, Int] + ("buffers" -> 20, "layers" -> 2, "title" -> 3)
-
-  val x3 = {
-    val bs = new collection.mutable.BitSet()
-    bs += 2; bs += 3
-    bs.toImmutable
-  }
-
-  val x4 = new ListSet[Int]() + 3 + 5
-
-  val x5 = new Queue("a", "b", "c")
-
-  val x6 = new Stack().push("a", "b", "c")
-
-  val x7 = new TreeMap[Int, String] + (42 -> "FortyTwo")
-
-  val x8 = new TreeSet[Int]() + 2 + 0
+    BitSet, HashMap, HashSet, ListMap, ListSet, Queue, Range, SortedMap,
+    SortedSet, Stack, Stream, TreeMap, TreeSet, Vector}
 
+  // in alphabetic order
   try {
-    val y1: List[Pair[String, Int]] = Serialize.read(Serialize.write(x1))
-    val y2: ListMap[String, Int]    = Serialize.read(Serialize.write(x2))
-    val y3: BitSet                  = Serialize.read(Serialize.write(x3))
-    val y4: ListSet[Int]            = Serialize.read(Serialize.write(x4))
-    val y5: Queue[String]           = Serialize.read(Serialize.write(x5))
-    val y6: Stack[String]           = Serialize.read(Serialize.write(x6))
-    val y7: TreeMap[Int, String]    = Serialize.read(Serialize.write(x7))
-    val y8: TreeSet[Int]            = Serialize.read(Serialize.write(x8))
-
-    EqualityTest.check(x1, y1)
-    EqualityTest.check(x2, y2)
-    EqualityTest.check(x3, y3)
-    EqualityTest.check(x4, y4)
-    EqualityTest.check(x5, y5)
-    EqualityTest.check(x6, y6)
-    EqualityTest.check(x7, y7)
-    EqualityTest.check(x8, y8)
+    // BitSet
+    val bs1 = BitSet.empty + 1 + 2
+    val _bs1: BitSet = read(write(bs1))
+    check(bs1, _bs1)
+
+    val bs2 = {
+      val bs = new collection.mutable.BitSet()
+      bs += 2; bs += 3
+      bs.toImmutable
+    }
+    val _bs2: BitSet = read(write(bs2))
+    check(bs2, _bs2)
+
+    // HashMap
+    val hm1 = new HashMap[Int, String] + (1 -> "A", 2 -> "B", 3 -> "C")
+    val _hm1: HashMap[Int, String] = read(write(hm1))
+    check(hm1, _hm1)
+
+    // HashSet
+    val hs1 = new HashSet[Int] + 1 + 2
+    val _hs1: HashSet[Int] = read(write(hs1))
+    check(hs1, _hs1)
+
+    // List
+    val xs1 = List(("buffers", 20), ("layers", 2), ("title", 3))
+    val _xs1: List[(String, Int)] = read(write(xs1))
+    check(xs1, _xs1)
+
+    // ListMap
+    val lm1 = new ListMap[String, Int] + ("buffers" -> 20, "layers" -> 2, "title" -> 3)
+    val _lm1: ListMap[String, Int] = read(write(lm1))
+    check(lm1, _lm1)
+
+    // ListSet
+    val ls1 = new ListSet[Int] + 3 + 5
+    val _ls1: ListSet[Int] = read(write(ls1))
+    check(ls1, _ls1)
+
+    // Queue
+    val q1 = Queue("a", "b", "c")
+    val _q1: Queue[String] = read(write(q1))
+    check(q1, _q1)
+
+    // Range
+    val r1 = 0 until 10
+    val _r1: Range = read(write(r1))
+    check(r1, _r1)
+
+    val r2 = Range.Long(0L, 10L, 1)
+    val _r2: r2.type = read(write(r2))
+    check(r2, _r2)
+
+    // SortedMap
+    val sm1 = SortedMap.empty[Int, String] + (2 -> "B", 3 -> "C", 1 -> "A")
+    val _sm1: SortedMap[Int, String] = read(write(sm1))
+    check(sm1, _sm1)
+
+    // SortedSet
+    val ss1 = SortedSet.empty[Int] + 2 + 3 + 1
+    val _ss1: SortedSet[Int] = read(write(ss1))
+    check(ss1, _ss1)
+
+    // Stack
+    val s1 = new Stack().push("a", "b", "c")
+    val _s1: Stack[String] = read(write(s1))
+    check(s1, _s1)
+
+    // Stream
+    val st1 = Stream.range(0, 10)
+    val _st1: Stream[Int] = read(write(st1))
+    check(st1, _st1)
+
+    // TreeMap
+    val tm1 = new TreeMap[Int, String] + (42 -> "FortyTwo")
+    val _tm1: TreeMap[Int, String] = read(write(tm1))
+    check(tm1, _tm1)
+
+    // TreeSet
+    val ts1 = new TreeSet[Int]() + 2 + 0
+    val _ts1: TreeSet[Int] = read(write(ts1))
+    check(ts1, _ts1)
+
+    // Vector
+    val v1 = Vector('a, 'b, 'c)
+    val _v1: Vector[Symbol] = read(write(v1))
+    check(v1, _v1)
   }
   catch {
     case e: Exception =>
@@ -202,65 +292,110 @@ object Test2_immutable {
 // Test classes in package "scala.collection.mutable"
 
 object Test3_mutable {
+  import scala.reflect.ClassManifest
   import scala.collection.mutable.{
-    ArrayBuffer, BitSet, HashMap, HashSet, History, LinkedList, ListBuffer,
-    Publisher, Queue, RevertableHistory, Stack}
-
-  val x0 = new ArrayBuffer[String]
-  x0 ++= List("one", "two")
-
-  val x2 = new BitSet()
-  x2 += 0
-  x2 += 8
-  x2 += 9
-
-  val x1 = new HashMap[String, Int]
-  x1 ++= Test2_immutable.x1
-
-  val x3 = new HashSet[String]
-  x3 ++= Test2_immutable.x1.map(p => p._1)
-
-  @serializable
-  class Feed extends Publisher[String, Feed]
-
-  val x8 = new History[String, Feed]
-
-  val x4 = new LinkedList[Int](2, null)
-  x4.append(new LinkedList(3, null))
-
-  val x7 = new ListBuffer[String]
-  x7 ++= List("white", "black")
-
-  val x5 = new Queue[Int]
-  x5 ++= Test2_immutable.x1.map(p => p._2)
-
-  val x6 = new Stack[Int]
-  x6 ++= x5
+    ArrayBuffer, ArrayBuilder, ArrayStack, BitSet, DoubleLinkedList,
+    HashMap, HashSet, History, LinkedList, ListBuffer, Publisher, Queue,
+    Stack, StringBuilder, WrappedArray}
 
+  // in alphabetic order
   try {
-    val y0: ArrayBuffer[String]   = Serialize.read(Serialize.write(x0))
-    val y1: HashMap[String, Int]  = Serialize.read(Serialize.write(x1))
-    val y2: BitSet                = Serialize.read(Serialize.write(x2))
-    val y3: HashSet[String]       = Serialize.read(Serialize.write(x3))
-    val y4: LinkedList[Int]       = Serialize.read(Serialize.write(x4))
-    val y5: Queue[Int]            = Serialize.read(Serialize.write(x5))
-    val y6: Stack[Int]            = Serialize.read(Serialize.write(x6))
-    val y7: ListBuffer[String]    = Serialize.read(Serialize.write(x7))
-    val y8: History[String, Feed] = Serialize.read(Serialize.write(x8))
-
-    EqualityTest.check(x0, y0)
-    EqualityTest.check(x1, y1)
-    EqualityTest.check(x2, y2)
-    EqualityTest.check(x3, y3)
-    EqualityTest.check(x4, y4)
-    EqualityTest.check(x5, y5)
-    EqualityTest.check(x6, y6)
-    EqualityTest.check(x7, y7)
-    //EqualityTest.check(x8, y8) //todo
+    // ArrayBuffer
+    val ab1 = new ArrayBuffer[String]
+    ab1 ++= List("one", "two")
+    val _ab1: ArrayBuffer[String] = read(write(ab1))
+    check(ab1, _ab1)
+
+    // ArrayBuilder
+    val abu1 = ArrayBuilder.make[Long]
+    val _abu1: ArrayBuilder[ClassManifest[Long]] = read(write(abu1))
+    check(abu1, _abu1)
+
+    val abu2 = ArrayBuilder.make[Float]
+    val _abu2: ArrayBuilder[ClassManifest[Float]] = read(write(abu2))
+    check(abu2, _abu2)
+
+    // ArrayStack
+    val as1 = new ArrayStack[Int]
+    as1 ++= List(20, 2, 3).iterator
+    val _as1: ArrayStack[Int] = read(write(as1))
+    check(as1, _as1)
+
+    // BitSet
+    val bs1 = new BitSet()
+    bs1 += 0
+    bs1 += 8
+    bs1 += 9
+    val _bs1: BitSet = read(write(bs1))
+    check(bs1, _bs1)
+/*
+    // DoubleLinkedList
+    val dl1 = new DoubleLinkedList[Int](2, null)
+    dl1.append(new DoubleLinkedList(3, null))
+    val _dl1: DoubleLinkedList[Int] = read(write(dl1))
+    check(dl1, _dl1)
+*/
+    // HashMap
+    val hm1 = new HashMap[String, Int]
+    hm1 ++= List(("A", 1), ("B", 2), ("C", 3)).iterator
+    val _hm1: HashMap[String, Int] = read(write(hm1))
+    check(hm1, _hm1)
+
+    // HashSet
+    val hs1 = new HashSet[String]
+    hs1 ++= List("layers", "buffers", "title").iterator
+    val _hs1: HashSet[String] = read(write(hs1))
+    check(hs1, _hs1)
+
+    // History
+    @serializable
+    class Feed extends Publisher[String]
+
+    val h1 = new History[String, Int]
+    val _h1: History[String, Int] = read(write(h1))
+    check(h1, _h1)
+/*
+    // LinkedList
+    val ll1 = new LinkedList[Int](2, null)
+    ll1.append(new LinkedList(3, null))
+    val _ll1: LinkedList[Int] = read(write(ll1))
+    check(ll1, _ll1)
+*/
+    // ListBuffer
+    val lb1 = new ListBuffer[String]
+    lb1 ++= List("white", "black")
+    val _lb1: ListBuffer[String] = read(write(lb1))
+    check(lb1, _lb1)
+
+    // Publisher
+
+    // Queue
+    val q1 = new Queue[Int]
+    q1 ++= List(20, 2, 3).iterator
+    val _q1: Queue[Int] = read(write(q1))
+    check(q1, _q1)
+
+    // Stack
+    val s1 = new Stack[Int]
+    s1 pushAll q1
+    val _s1: Stack[Int] = read(write(s1))
+    check(s1, _s1)
+
+    // StringBuilder
+    val sb1 = new StringBuilder
+    sb1 append "abc"
+    val _sb1: StringBuilder = read(write(sb1))
+    check(sb1, _sb1)
+
+    // WrappedArray
+    val wa1 = WrappedArray.make(Array(1, 2, 3))
+    val _wa1: WrappedArray[Int] = read(write(wa1))
+    check(wa1, _wa1)
   }
   catch {
     case e: Exception =>
       println("Error in Test3_mutable: " + e)
+      throw e
   }
 }
 
@@ -268,50 +403,62 @@ object Test3_mutable {
 // Test classes in package "scala.xml"
 
 object Test4_xml {
-  import scala.xml.Elem
-
-  val x1 = <html><title>title</title><body></body></html>;
+  import scala.xml.{Attribute, Document, Elem, Null, PrefixedAttribute, Text}
 
   case class Person(name: String, age: Int)
 
-  class AddressBook(a: Person*) {
-    private val people: List[Person] = a.toList
-    def toXHTML =
+  try {
+    // Attribute
+    val a1 = new PrefixedAttribute("xml", "src", Text("hello"), Null)
+    val _a1: Attribute = read(write(a1))
+    check(a1, _a1)
+
+    // Document
+    val d1 = new Document
+    d1.docElem = <title></title>
+    d1.encoding = Some("UTF-8")
+    val _d1: Document = read(write(d1))
+    check(d1, _d1)
+
+    // Elem
+    val e1 = <html><title>title</title><body></body></html>;
+    val _e1: Elem = read(write(e1))
+    check(e1, _e1)
+
+    class AddressBook(a: Person*) {
+      private val people: List[Person] = a.toList
+      def toXHTML =
       <table cellpadding="2" cellspacing="0">
         <tr>
           <th>Last Name</th>
           <th>First Name</th>
         </tr>
-        { for (val p <- people) yield
+        { for (p <- people) yield
         <tr>
           <td> { p.name } </td>
           <td> { p.age.toString() } </td>
         </tr> }
       </table>;
-  }
+    }
 
-  val people = new AddressBook(
-    Person("Tom", 20),
-    Person("Bob", 22),
-    Person("James", 19))
+    val people = new AddressBook(
+      Person("Tom", 20),
+      Person("Bob", 22),
+      Person("James", 19))
 
-  val x2 =
-    <html>
+    val e2 =
+      <html>
       <body>
-       { people.toXHTML }
+        { people.toXHTML }
       </body>
-    </html>;
-
-  try {
-    val y1: scala.xml.Elem = Serialize.read(Serialize.write(x1))
-    val y2: scala.xml.Elem = Serialize.read(Serialize.write(x2))
-
-    EqualityTest.check(x1, y1)
-    EqualityTest.check(x2, y2)
+      </html>;
+    val _e2: Elem = read(write(e2))
+    check(e2, _e2)
   }
   catch {
     case e: Exception =>
       println("Error in Test4_xml: " + e)
+      throw e
   }
 }
 
@@ -340,11 +487,11 @@ object Test5 {
   val x2 = bob
 
   try {
-    val y1: Person   = Serialize.read(Serialize.write(x1))
-    val y2: Employee = Serialize.read(Serialize.write(x2))
+    val y1: Person   = read(write(x1))
+    val y2: Employee = read(write(x2))
 
-    EqualityTest.check(x1, y1)
-    EqualityTest.check(x2, y2)
+    check(x1, y1)
+    check(x2, y2)
   }
   catch {
     case e: Exception =>
@@ -370,13 +517,13 @@ object Test6 {
   val x3 = paul
 
   try {
-    val y1: Person   = Serialize.read(Serialize.write(x1))
-    val y2: Employee = Serialize.read(Serialize.write(x2))
-    val y3: Person   = Serialize.read(Serialize.write(x3))
+    val y1: Person   = read(write(x1))
+    val y2: Employee = read(write(x2))
+    val y3: Person   = read(write(x3))
 
-    EqualityTest.check(x1, y1)
-    EqualityTest.check(x2, y2)
-    EqualityTest.check(x3, y3)
+    check(x1, y1)
+    check(x2, y2)
+    check(x3, y3)
   }
   catch {
     case e: Exception =>
diff --git a/test/files/jvm/stringbuilder.scala b/test/files/jvm/stringbuilder.scala
new file mode 100644
index 0000000..8f73cfa
--- /dev/null
+++ b/test/files/jvm/stringbuilder.scala
@@ -0,0 +1,98 @@
+import testing.SUnit._
+
+/** Test the Scala implementation of class <code>scala.StringBuilder</code>.
+ *
+ *  @author Stephane Micheloud
+ */
+object Test extends TestConsoleMain {
+  def suite = new TestSuite(
+    Test1, //ctor, reverse
+    Test2, //append
+    Test3, //insert
+    Test4  //indexOf, lastIndexOf
+  )
+}
+
+object Test1 extends TestCase("ctor") with Assert {
+  override def enableStackTrace = false
+  override def runTest {
+    val j0 = new java.lang.StringBuilder("abc") // Java 1.5+
+    val s0 = new StringBuilder("abc")
+    assertEquals("s0 equals j0", false, s0 equals j0)
+    assertEquals("s0.toString equals j0.toString", true, s0.toString equals j0.toString)
+
+    val str = """
+Scala is a general purpose programming language designed to express common programming patterns in a concise, elegant, and type-safe way. It smoothly integrates features of object-oriented and functional languages. It is also fully interoperable with Java."""
+    val j1 = new java.lang.StringBuilder(100) append str
+    val s1 = new java.lang.StringBuilder(100) append str
+    assertEquals("s1.toString equals j1.toString", true, s1.toString equals j1.toString)
+
+    val j2 = j0 reverse
+    val s2 = s0 reverse;
+    //println("j2="+j2+", s2="+s2)//debug
+    assertEquals("s2.toString equals j2.toString", true, s2.toString equals j2.toString)
+
+    val j3 = j2; j3 setCharAt (0, j3 charAt 2)
+    val s3 = s2; s3(0) = s3(2)
+    //println("j3="+j3+", s3="+s3)//debug
+    assertEquals("s3.toString equals j3.toString", true, s3.toString equals j3.toString)    
+ }
+}
+
+object Test2 extends TestCase("append") with Assert {
+  override def enableStackTrace = false
+  override def runTest {
+    val j0 = new java.lang.StringBuilder("abc") // Java 1.5+
+    val s0 = new StringBuilder("abc")
+
+    j0 append true append (1.toByte) append 'a' append 9 append -1L append 1.2e-10f append -2.1e+100d
+    s0 append true append (1.toByte) append 'a' append 9 append -1L append 1.2e-10f append -2.1e+100d
+
+    assertEquals("s0.toString equals j0.toString", true, s0.toString equals j0.toString)
+
+    val j1 = new java.lang.StringBuilder // Java 1.5+
+    val s1 = new StringBuilder
+    j1 append "###" append Array('0', '1', '2') append "xyz".subSequence(0, 3)
+    s1 append "###" appendAll Array('0', '1', '2') appendAll List('x', 'y', 'z')
+    assertEquals("s1.toString equals j1.toString", true, s1.toString equals j1.toString)
+ }
+}
+
+object Test3 extends TestCase("insert") with Assert {
+  override def enableStackTrace = false
+  override def runTest {
+    val j0 = new java.lang.StringBuilder("abc") // Java 1.5+
+    val s0 = new StringBuilder("abc")
+
+    j0 insert (0, true) insert (0, 1.toByte) insert (0, 'a') insert (0, 88.toShort) insert (0, 9) insert (0, -1L)
+    s0 insert (0, true) insert (0, 1.toByte) insert (0, 'a') insert (0, 88.toShort) insert (0, 9) insert (0, -1L)
+    //println("j0="+j0+", s0="+s0)//debug
+    assertEquals("s0.toString equals j0.toString", true, s0.toString equals j0.toString)
+
+    val j1 = new java.lang.StringBuilder // Java 1.5+
+    val s1 = new StringBuilder
+    j1 insert (0, "###") insert (0, Array('0', '1', '2')) insert (0, "xyz".subSequence(0, 3))
+    s1 insert (0, "###") insertAll (0, Array('0', '1', '2')) insertAll (0, List('x', 'y', 'z'))
+    //println("j1="+j1+", s1="+s1)//debug
+    assertEquals("s1.toString equals j1.toString", true, s1.toString equals j1.toString)
+
+  }
+}
+
+object Test4 extends TestCase("indefOf") with Assert {
+  override def enableStackTrace = false
+  override def runTest {
+    val j0 = new java.lang.StringBuilder("abc") // Java 1.5+
+    val s0 = new StringBuilder("abc")
+
+    val j1 = j0 indexOf("c")
+    val s1 = s0 indexOf("c")
+    //println("j1="+j1+", s1="+s1)//debug
+    assertEquals("s1 == j1", true, s1 == j1)
+
+    val j2 = j0 append "123abc" lastIndexOf("c")
+    val s2 = s0 append "123abc" lastIndexOf("c")
+    //println("j2="+j2+", s2="+s2)//debug
+    assertEquals("s2 == j2", true, s2 == j2)
+ }
+}
diff --git a/test/files/jvm5/sync-var.check b/test/files/jvm/sync-var.check
similarity index 100%
rename from test/files/jvm5/sync-var.check
rename to test/files/jvm/sync-var.check
diff --git a/test/files/jvm/sync-var.scala b/test/files/jvm/sync-var.scala
new file mode 100644
index 0000000..8a6c2ba
--- /dev/null
+++ b/test/files/jvm/sync-var.scala
@@ -0,0 +1,53 @@
+import java.util.concurrent._
+import java.util.concurrent.atomic._
+
+object Test { def main(args: Array[String]) {
+
+val n = 10000
+val i = new AtomicInteger(n)
+val j = new AtomicInteger(n)
+val sum = new AtomicInteger
+
+val q = new scala.concurrent.SyncVar[Int]
+
+val producers = (1 to 3) map { z => new Thread {
+  override def run() {
+    var again = true
+    while (again) {
+      val x = i.getAndDecrement()
+      if (x > 0)
+        q put x
+      else
+        again = false
+    }
+  }
+} }
+
+val summers = (1 to 7) map { z => new Thread {
+  override def run() {
+    val x = j.decrementAndGet()
+    if (x >= 0) {
+      sum addAndGet q.take()
+    }
+    if (x > 0) {
+      run()
+    } else {
+      // done
+    }
+  }
+} }
+
+summers foreach { _.start() }
+producers foreach { _.start() }
+
+summers foreach { _.join() }
+
+val got = sum.get
+val expected = (n + 1) * n / 2
+println(got + " " + expected + " " + (got == expected))
+
+producers foreach { _.join() }
+
+} }
+
+// vim: set ts=2 sw=2 et:
diff --git a/test/files/jvm5/t0014.check b/test/files/jvm/t0014.check
similarity index 100%
rename from test/files/jvm5/t0014.check
rename to test/files/jvm/t0014.check
diff --git a/test/files/jvm5/t0014.scala b/test/files/jvm/t0014.scala
similarity index 100%
rename from test/files/jvm5/t0014.scala
rename to test/files/jvm/t0014.scala
diff --git a/test/files/jvm/t1143-2/t1143-2.scala b/test/files/jvm/t1143-2/t1143-2.scala
index 58bc1d7..44b1feb 100644
--- a/test/files/jvm/t1143-2/t1143-2.scala
+++ b/test/files/jvm/t1143-2/t1143-2.scala
@@ -52,7 +52,7 @@ class Main {
   var pass = "pass"
   def main(args : Array[String]) : Unit = {
     val f = new Form {
-      val p = new Printer( new VarModel( pass, pass=_ ) );
+      val p = new Printer( new VarModel( pass, s => pass = s ) );
       p.print
     }
     ()
diff --git a/test/files/jvm/t1143.scala b/test/files/jvm/t1143.scala
index 4f4557a..7dd374f 100644
--- a/test/files/jvm/t1143.scala
+++ b/test/files/jvm/t1143.scala
@@ -55,7 +55,7 @@ class Main {
   var pass = "pass"
   def main(args: Array[String]) {
     val f = new Form {
-      val p = new Printer(new VarModel(pass, pass=_))
+      val p = new Printer(new VarModel(pass, s => pass = s))
     }
     ()
   }
diff --git a/test/files/jvm/t1342.check b/test/files/jvm/t1342.check
new file mode 100644
index 0000000..814f4a4
--- /dev/null
+++ b/test/files/jvm/t1342.check
@@ -0,0 +1,2 @@
+one
+two
diff --git a/test/files/jvm/t1342/JI.java b/test/files/jvm/t1342/JI.java
new file mode 100644
index 0000000..2de46d9
--- /dev/null
+++ b/test/files/jvm/t1342/JI.java
@@ -0,0 +1,3 @@
+interface JI {
+   void varArgsMethod( String ... args );
+}
diff --git a/test/files/jvm/t1342/SI.scala b/test/files/jvm/t1342/SI.scala
new file mode 100644
index 0000000..8e3b753
--- /dev/null
+++ b/test/files/jvm/t1342/SI.scala
@@ -0,0 +1,10 @@
+class SI extends JI {
+   def varArgsMethod( args : String*) {
+        for( arg <- args ) println( arg )
+   }
+}
+
+object Test extends Application {
+  val x: JI = new SI
+  x.varArgsMethod("one", "two")
+}
diff --git a/test/files/jvm/t1449.check b/test/files/jvm/t1449.check
new file mode 100644
index 0000000..d81cc07
--- /dev/null
+++ b/test/files/jvm/t1449.check
@@ -0,0 +1 @@
+42
diff --git a/test/files/jvm/t1449.scala b/test/files/jvm/t1449.scala
new file mode 100644
index 0000000..3822cf7
--- /dev/null
+++ b/test/files/jvm/t1449.scala
@@ -0,0 +1,25 @@
+import scala.actors.Actor._
+import scala.actors.Future
+import scala.actors.Futures._
+object Test {
+  def main(args: Array[String]) {
+    val a = actor {
+      try {
+      react {
+        case ft: Future[a] =>
+          println(ft())
+      }
+      } catch {
+        case e: Throwable if !e.isInstanceOf[scala.util.control.ControlThrowable] =>
+          e.printStackTrace()
+      }
+    }
+    try {
+    val ft = future { 42 }
+    a ! ft
+    } catch {
+      case e: Throwable if !e.isInstanceOf[scala.util.control.ControlThrowable] =>
+        e.printStackTrace()
+    }
+  }
+}
diff --git a/test/files/jvm5/t1461.scala b/test/files/jvm/t1461.scala
similarity index 100%
rename from test/files/jvm5/t1461.scala
rename to test/files/jvm/t1461.scala
diff --git a/test/files/jvm5/t1464.check b/test/files/jvm/t1464.check
similarity index 100%
copy from test/files/jvm5/t1464.check
copy to test/files/jvm/t1464.check
diff --git a/test/files/jvm5/t1464/MyTrait.scala b/test/files/jvm/t1464/MyTrait.scala
similarity index 100%
rename from test/files/jvm5/t1464/MyTrait.scala
rename to test/files/jvm/t1464/MyTrait.scala
diff --git a/test/files/jvm5/t1464/Test.java b/test/files/jvm/t1464/Test.java
similarity index 100%
rename from test/files/jvm5/t1464/Test.java
rename to test/files/jvm/t1464/Test.java
diff --git a/test/files/jvm/t1600.scala b/test/files/jvm/t1600.scala
new file mode 100644
index 0000000..7e23687
--- /dev/null
+++ b/test/files/jvm/t1600.scala
@@ -0,0 +1,76 @@
+
+/**
+ * Checks that serialization of hash-based collections works correctly if the hashCode
+ * changes on deserialization.
+ */
+object Test {
+  
+  import collection._
+  def main(args: Array[String]) {
+    for (i <- Seq(0, 1, 2, 10, 100)) {
+      def entries = (0 until i).map(i => (new Foo, i)).toList
+      def elements = entries.map(_._1)
+      
+      val maps = Seq[Map[Foo, Int]](new mutable.HashMap, new mutable.LinkedHashMap,
+          immutable.HashMap.empty).map(_ ++ entries)
+      test[Map[Foo, Int]](maps, entries.size, assertMap _)
+      
+      val sets = Seq[Set[Foo]](new mutable.HashSet, new mutable.LinkedHashSet,
+          immutable.HashSet.empty).map(_ ++ elements)
+      test[Set[Foo]](sets, entries.size, assertSet _)
+    }
+  }
+  
+  private def test[A <: AnyRef](collections: Seq[A], expectedSize: Int, assertFunction: (A, Int) => Unit) {
+    for (collection <- collections) {
+      assertFunction(collection, expectedSize)
+
+      val bytes = toBytes(collection)
+      Foo.hashCodeModifier = 1
+      val deserializedCollection = toObject[A](bytes)
+      
+      assertFunction(deserializedCollection, expectedSize)
+      assert(deserializedCollection.getClass == collection.getClass,
+          "collection class should remain the same after deserialization ("+deserializedCollection.getClass+" != "+collection.getClass+")")
+      Foo.hashCodeModifier = 0
+    }
+  }
+  
+  private def toObject[A](bytes: Array[Byte]): A = {
+    val in = new java.io.ObjectInputStream(new java.io.ByteArrayInputStream(bytes))
+    in.readObject.asInstanceOf[A]
+  }
+  
+  private def toBytes(o: AnyRef): Array[Byte] = {
+    val bos = new java.io.ByteArrayOutputStream
+    val out = new java.io.ObjectOutputStream(bos)
+    out.writeObject(o)
+    out.close
+    bos.toByteArray
+  }
+  
+  private def assertMap[A, B](map: Map[A, B], expectedSize: Int) {
+    assert(expectedSize == map.size, "expected map size: " + expectedSize + ", actual size: " + map.size)
+    map.foreach { case (k, v) =>
+      assert(map.contains(k), "contains should return true for key in the map, key: " + k)
+      assert(map(k) == v)
+    }
+  }
+  
+  private def assertSet[A](set: Set[A], expectedSize: Int) {
+    assert(expectedSize == set.size, "expected set size: " + expectedSize + ", actual size: " + set.size)
+    set.foreach { e => assert(set.contains(e), "contains should return true for element in the set, element: " + e) }
+  }
+  
+  object Foo {
+    /* Used to simulate a hashCode change caused by deserializing an instance with an 
+     * identity-based hashCode in another JVM.
+     */
+    var hashCodeModifier = 0
+  }
+  
+  @serializable
+  class Foo {
+    override def hashCode = System.identityHashCode(this) + Foo.hashCodeModifier
+  }
+}
diff --git a/test/files/jvm/t1652.check b/test/files/jvm/t1652.check
new file mode 100644
index 0000000..dfa480c
--- /dev/null
+++ b/test/files/jvm/t1652.check
@@ -0,0 +1,2 @@
+OK1
+OK2
diff --git a/test/files/jvm5/bug680.check b/test/files/jvm/t1948.check
similarity index 100%
copy from test/files/jvm5/bug680.check
copy to test/files/jvm/t1948.check
diff --git a/test/files/jvm/t1948.scala b/test/files/jvm/t1948.scala
new file mode 100644
index 0000000..084c956
--- /dev/null
+++ b/test/files/jvm/t1948.scala
@@ -0,0 +1,24 @@
+import scala.actors._
+import scala.actors.Actor._
+
+object Test {
+
+  def main (args: Array[String]) {
+    val actors = (1 to 1000).toList map { x => actor {
+      try {
+      loop { react {
+      case x: Array[Int] => reply ("OK"); exit }}
+      } catch {
+        case e: Throwable if !e.isInstanceOf[scala.util.control.ControlThrowable] =>
+          e.printStackTrace()
+      }
+    } }
+    try {
+    actors foreach { x => x !? new Array[Int] (1000000) }
+    } catch {
+      case e: Throwable if !e.isInstanceOf[scala.util.control.ControlThrowable] =>
+        e.printStackTrace()
+    }
+  }
+
+}
diff --git a/test/files/jvm5/bug680.check b/test/files/jvm/t2104.check
similarity index 100%
copy from test/files/jvm5/bug680.check
copy to test/files/jvm/t2104.check
diff --git a/test/files/jvm/t2104.scala b/test/files/jvm/t2104.scala
new file mode 100644
index 0000000..e672f02
--- /dev/null
+++ b/test/files/jvm/t2104.scala
@@ -0,0 +1,51 @@
+/* https://lampsvn.epfl.ch/trac/scala/ticket/2104
+   symptom: Source via Buffered Source always loses the last char of the input file.
+   cause: BufferedSource? doesn't check return for -1 (EOF), and uses reader.ready() improperly as a substitute.
+
+  test: check over all possible strings of length up to N over alphabet chars:
+  write file, then read back its chars, and get back the original.
+
+*/
+object Test
+{
+  val N=4
+
+  import java.io.{ File => JFile }
+  import java.io.FileWriter
+  import io.Source
+  def overwrite(file: JFile,w: FileWriter=>Unit) {
+    val fw=new FileWriter(file)
+    w(fw)
+    fw.close
+  }
+  def delete_after(f: JFile,g: Source=>Unit) = {
+    g(Source.fromFile(f))
+    f.delete
+  }
+  def store_tempfile(f: FileWriter=>Unit)(implicit name:String) : JFile = {
+    val tp=JFile.createTempFile(name,null)
+    overwrite(tp,f)
+    tp
+  }
+
+  implicit val name="bug2104"
+  val chars=List('\n','\r','a')
+
+  type Cs = List[Char]
+  def all_strings(n: Int) : List[Cs] = {
+    if (n==0) List(Nil)
+    else {
+      val sufs=all_strings(n-1)
+      chars.flatMap((c)=>sufs.map(c :: _))
+    }
+  }
+  def test(n: Int) {
+    for(l <- all_strings(n)) {
+      val tmp=store_tempfile((f)=>l.foreach(f.write(_)))
+      delete_after(tmp,(s)=>assert(s.toList == l))
+    }
+  }
+  def main(args: Array[String]) {
+    (0 until N).foreach(test(_))
+  }
+}
diff --git a/test/files/jvm/t2214.check b/test/files/jvm/t2214.check
new file mode 100644
index 0000000..72601ba
--- /dev/null
+++ b/test/files/jvm/t2214.check
@@ -0,0 +1,3 @@
+got DEBT
+got FUTURE
+got EQUITY
diff --git a/test/files/jvm/t2214.scala b/test/files/jvm/t2214.scala
new file mode 100644
index 0000000..db3e400
--- /dev/null
+++ b/test/files/jvm/t2214.scala
@@ -0,0 +1,39 @@
+
+object InvestmentType extends Enumeration {
+  val Debt = Value("DEBT")
+  val Future = Value("FUTURE")
+  val Equity = Value("EQUITY")
+}
+
+object Test {
+  def main(args: Array[String]) = {
+    val buf = new java.io.ByteArrayOutputStream
+    val oos = new java.io.ObjectOutputStream(buf)
+    InvestmentType.values.foreach {i => oos.writeObject(i)}
+    oos.flush
+    oos.close
+    val ois = new java.io.ObjectInputStream(
+                new java.io.ByteArrayInputStream(buf.toByteArray))
+    var obj: Object = null
+    foreach(ois) { obj =>
+      obj match {
+        case InvestmentType.Debt => println("got " + obj)
+        case InvestmentType.Equity => println("got " + obj)
+        case InvestmentType.Future => println("got " + obj)
+        case _ => println("unknown: " + obj + " of: " + obj.getClass)
+      }
+    }
+  }
+
+  def foreach(os: java.io.ObjectInputStream)(f: Object => Unit) {
+    try {
+      val obj = os.readObject
+      if (obj != null) {
+        f(obj)
+        foreach(os)(f)
+      }
+    } catch {
+      case e: java.io.EOFException => //IGNORE
+    }
+  }
+}
diff --git a/test/files/jvm/t2359.check b/test/files/jvm/t2359.check
new file mode 100644
index 0000000..8a1218a
--- /dev/null
+++ b/test/files/jvm/t2359.check
@@ -0,0 +1,5 @@
+1
+2
+3
+4
+5
diff --git a/test/files/jvm/t2359.scala b/test/files/jvm/t2359.scala
new file mode 100644
index 0000000..69c69d7
--- /dev/null
+++ b/test/files/jvm/t2359.scala
@@ -0,0 +1,46 @@
+import scala.actors.Futures._
+
+object Test {
+  def main(args: Array[String]) {
+    val x = future {
+      try {
+      System.out.println(1)
+      future {
+        try {
+        System.out.println(2)
+        future {
+          try {
+          System.out.println(3)
+          future {
+            try {
+            System.out.println(4)
+            future {
+              try {
+              System.out.println(5)
+              } catch {
+                case e: Throwable if !e.isInstanceOf[scala.util.control.ControlThrowable] =>
+                  e.printStackTrace()
+              }
+            }()
+            } catch {
+              case e: Throwable if !e.isInstanceOf[scala.util.control.ControlThrowable] =>
+                e.printStackTrace()
+            }
+          }()
+          } catch {
+            case e: Throwable if !e.isInstanceOf[scala.util.control.ControlThrowable] =>
+              e.printStackTrace()
+          }
+        }()
+        } catch {
+          case e: Throwable if !e.isInstanceOf[scala.util.control.ControlThrowable] =>
+            e.printStackTrace()
+        }
+      }()
+      } catch {
+        case e: Throwable if !e.isInstanceOf[scala.util.control.ControlThrowable] =>
+          e.printStackTrace()
+      }
+    }()
+  }
+}
diff --git a/test/files/jvm/t2470.check b/test/files/jvm/t2470.check
new file mode 100644
index 0000000..11539b2
--- /dev/null
+++ b/test/files/jvm/t2470.check
@@ -0,0 +1 @@
+List(@Action(block=ACTION))
diff --git a/test/files/jvm/t2470.cmds b/test/files/jvm/t2470.cmds
new file mode 100644
index 0000000..b4ef0f4
--- /dev/null
+++ b/test/files/jvm/t2470.cmds
@@ -0,0 +1,3 @@
+javac Action.java Task.java
+scalac Test_1.scala
+scalac Read_Classfile_2.scala
diff --git a/test/files/jvm/t2470/Action.java b/test/files/jvm/t2470/Action.java
new file mode 100644
index 0000000..62c71c4
--- /dev/null
+++ b/test/files/jvm/t2470/Action.java
@@ -0,0 +1,6 @@
+import java.lang.annotation.*;
+
+ at Retention(value=RetentionPolicy.RUNTIME)
+public @interface Action {
+    Task.Scope block() default Task.Scope.ACTION;
+}
diff --git a/test/files/jvm/t2470/Read_Classfile_2.scala b/test/files/jvm/t2470/Read_Classfile_2.scala
new file mode 100644
index 0000000..0796177
--- /dev/null
+++ b/test/files/jvm/t2470/Read_Classfile_2.scala
@@ -0,0 +1,3 @@
+class Read {
+  val t = Test
+}
diff --git a/test/files/jvm/t2470/Task.java b/test/files/jvm/t2470/Task.java
new file mode 100644
index 0000000..64004b5
--- /dev/null
+++ b/test/files/jvm/t2470/Task.java
@@ -0,0 +1,3 @@
+class Task {
+    public enum Scope { ACTION, HIKA }
+}
diff --git a/test/files/jvm/t2470/Test_1.scala b/test/files/jvm/t2470/Test_1.scala
new file mode 100644
index 0000000..00cf287
--- /dev/null
+++ b/test/files/jvm/t2470/Test_1.scala
@@ -0,0 +1,11 @@
+object Test {
+  class Foo {
+    @Action(block = Task.Scope.ACTION)
+    def foo = 0
+  }
+
+  def main(args: Array[String]) {
+    val m = classOf[Foo].getDeclaredMethods().find(_.toString.contains("foo")).get
+    println(m.getAnnotations().toList)
+  }
+}
diff --git a/test/files/jvm/t2511.check b/test/files/jvm/t2511.check
new file mode 100644
index 0000000..ec747fa
--- /dev/null
+++ b/test/files/jvm/t2511.check
@@ -0,0 +1 @@
+null
\ No newline at end of file
diff --git a/test/files/jvm/t2511.scala b/test/files/jvm/t2511.scala
new file mode 100644
index 0000000..d4b5e83
--- /dev/null
+++ b/test/files/jvm/t2511.scala
@@ -0,0 +1,30 @@
+object Test {
+
+  import java.io._
+
+  trait IMyMessage extends Serializable {
+    @transient var message: String = null
+  }
+
+  class MyMessage extends IMyMessage
+
+  def serialize = {
+    val buf = new ByteArrayOutputStream(10000)
+    val out = new ObjectOutputStream(buf)
+    val m = new MyMessage
+    m.message = "foo"
+    out.writeObject(m)
+    out.flush
+    buf.toByteArray
+  }
+
+  def unserialize(buf:Array[Byte]) = {
+    val in = new ObjectInputStream(new ByteArrayInputStream(buf))
+    in.readObject.asInstanceOf[MyMessage]
+  }
+
+  def main(args: Array[String]) {
+    val m = unserialize(serialize)
+    println(m.message)
+  }
+}
diff --git a/test/files/jvm/t2530.check b/test/files/jvm/t2530.check
new file mode 100644
index 0000000..0f1c021
--- /dev/null
+++ b/test/files/jvm/t2530.check
@@ -0,0 +1,21 @@
+     Iteration  1 succeeded 
+     Iteration  2 succeeded 
+     Iteration  3 succeeded 
+     Iteration  4 succeeded 
+     Iteration  5 succeeded 
+     Iteration  6 succeeded 
+     Iteration  7 succeeded 
+     Iteration  8 succeeded 
+     Iteration  9 succeeded 
+     Iteration 10 succeeded 
+     Iteration 11 succeeded 
+     Iteration 12 succeeded 
+     Iteration 13 succeeded 
+     Iteration 14 succeeded 
+     Iteration 15 succeeded 
+     Iteration 16 succeeded 
+     Iteration 17 succeeded 
+     Iteration 18 succeeded 
+     Iteration 19 succeeded 
+     Iteration 20 succeeded 
+Test done with no deadlock. Try again, it will not occur...
diff --git a/test/files/jvm/t2530.scala b/test/files/jvm/t2530.scala
new file mode 100644
index 0000000..c2925a9
--- /dev/null
+++ b/test/files/jvm/t2530.scala
@@ -0,0 +1,96 @@
+import scala.actors.{Future, Futures}
+
+object Test {
+
+  def main(args:Array[String]) : Unit = {
+    //scala.actors.Debug.level = 3
+    val size = /*if (args.length > 0) Integer.parseInt(args(0)) else*/ 8
+    val (m,n) = (size, size)
+    def random = (for (i <- 0 until m*n) yield java.lang.Math.random).toArray
+    val A = Matrix(m, n, random)
+    val B = Matrix(m, n, random)
+    val format = new java.text.DecimalFormat("000.00'ms'");
+    var iter = 1
+    val done = 21
+    while (iter < done) {
+      val start = System.nanoTime()
+      val result = A * B
+      val time = System.nanoTime() - start
+      result match {
+        case Some(result) => {
+          printf("     Iteration %2d succeeded %n", iter/*, format.format(time / 1e6)*/)
+          iter += 1
+        }
+        case None => {
+          printf(">>>> Iteration %2d failed after %s <<<<< %n", iter, format.format(time / 1e6))
+          iter = done
+        }
+      }
+    }
+    println("Test done with no deadlock. Try again, it will not occur...")
+  }
+}
+
+case class Matrix(numRows: Int, numCols: Int, values: Array[Double])  {
+
+  def this(m:Int, n:Int) = this(m, n, new Array[Double](m*n))
+
+  def offset(i:Int, j:Int) = i * numCols + j
+  def apply(i:Int, j:Int) = values( offset(i,j) )
+  def update(i:Int, j:Int, value:Double) = values(offset(i, j)) = value;
+
+  def *(by:Matrix) = {
+    val aM = numRows
+    val aN = numCols
+    assert(aM == by.numCols)
+    assert(aN == by.numRows)
+    val resultMatrix = new Matrix(aM, aM)
+    val m = aM.asInstanceOf[Int]
+    val n = aN.asInstanceOf[Int]
+
+    val rows = for (j <- 0 until m) yield {
+      Futures.future {
+        try {
+        val b_j = new Array[Double](n)
+        var k = 0
+        while (k < n) { // sadly, while loops are still faster than for loops
+          b_j(k) = by(k,j)
+          k += 1
+        }
+        var i = 0
+        while (i < m) {
+          var s = 0.0d;
+          k = 0
+          while (k < n) {
+            s += Matrix.this(i,k) * b_j(k)
+            k += 1
+          }
+          resultMatrix(i,j) = s
+          i += 1
+        }
+        //printf("future %d of %d completed.%n", j, m)
+        j
+        } catch {
+          case e: Throwable if !e.isInstanceOf[scala.util.control.ControlThrowable] =>
+            e.printStackTrace()
+        }
+      }
+    }
+
+    // rows.foreach { x=> x() } // This appears to force sequential execution, so use:
+    // timeout is 10 years; see http://lampsvn.epfl.ch/trac/scala/ticket/2515
+    val done: List[Option[Any]] = try {
+      Futures.awaitAll(10*365*24*60*60*1000, rows.toArray : _*) // list to array, as varargs.
+    } catch {
+      case e: Throwable if !e.isInstanceOf[scala.util.control.ControlThrowable] =>
+        e.printStackTrace()
+        List()
+    }
+
+    if (done.contains(None))
+      None
+    else
+      Some(resultMatrix)
+  }
+
+}
diff --git a/test/files/jvm5/bug680.check b/test/files/jvm/t2570.check
similarity index 100%
copy from test/files/jvm5/bug680.check
copy to test/files/jvm/t2570.check
diff --git a/test/files/jvm/t2570/Test.scala b/test/files/jvm/t2570/Test.scala
new file mode 100644
index 0000000..7944aed
--- /dev/null
+++ b/test/files/jvm/t2570/Test.scala
@@ -0,0 +1,3 @@
+class Test2 extends Test1[Test3[Test4]]
+class Test4
+object Test extends Application {} 
\ No newline at end of file
diff --git a/test/files/jvm/t2570/Test1.java b/test/files/jvm/t2570/Test1.java
new file mode 100644
index 0000000..f305736
--- /dev/null
+++ b/test/files/jvm/t2570/Test1.java
@@ -0,0 +1,2 @@
+public class Test1<T extends Test3> {
+}
\ No newline at end of file
diff --git a/test/files/jvm/t2570/Test3.java b/test/files/jvm/t2570/Test3.java
new file mode 100644
index 0000000..97603b5
--- /dev/null
+++ b/test/files/jvm/t2570/Test3.java
@@ -0,0 +1,2 @@
+public class Test3<T> {
+}
\ No newline at end of file
diff --git a/test/files/jvm5/bug680.check b/test/files/jvm/t2585.check
similarity index 100%
copy from test/files/jvm5/bug680.check
copy to test/files/jvm/t2585.check
diff --git a/test/files/jvm/t2585/Test.java b/test/files/jvm/t2585/Test.java
new file mode 100644
index 0000000..51fe20d
--- /dev/null
+++ b/test/files/jvm/t2585/Test.java
@@ -0,0 +1,16 @@
+class J { S s ; }
+
+public class Test {
+  public static void main(String[] args) {
+    final X x = new X();
+    final OuterImpl o = new OuterImpl(x);
+
+    final OuterImpl.Inner i1 = o.newInner();
+    i1.getT().getI().getT().getI();  // <--- Error: "The method getI() is undefined for the type Object"
+
+    final Outer<X>.Inner i2 = o.newInner();
+    i2.getT().getI().getT().getI(); // <--- Error: "The method getI() is undefined for the type Object"
+
+    HashMap<String, String> map = new HashMap<String, String>();
+  }
+}
\ No newline at end of file
diff --git a/test/files/jvm/t2585/genericouter.scala b/test/files/jvm/t2585/genericouter.scala
new file mode 100644
index 0000000..e06aa81
--- /dev/null
+++ b/test/files/jvm/t2585/genericouter.scala
@@ -0,0 +1,25 @@
+case class S(n:Int)
+
+trait TraversableLike[+A, +Repr] {
+  class WithFilter(p: A => Boolean)
+  def withFilter(p: A => Boolean): WithFilter = new WithFilter(p)
+}
+
+class HashMap[K, +V] extends TraversableLike[(K, V), HashMap[K, V]]
+
+class Outer[T](val t: T) {
+  class Inner {
+    def getT : T = t
+  }
+}
+
+class OuterImpl(x: X) extends Outer[X](x) {
+  def newInner = new Inner
+}
+
+class X {
+  def getI : Outer[X]#Inner = {
+    val oImpl = new OuterImpl(this)
+    new oImpl.Inner
+  }
+}
\ No newline at end of file
diff --git a/test/files/jvm/t2827.check b/test/files/jvm/t2827.check
new file mode 100644
index 0000000..c318e01
--- /dev/null
+++ b/test/files/jvm/t2827.check
@@ -0,0 +1,3 @@
+Larry
+Curly
+Moe
diff --git a/test/files/jvm/t2827.scala b/test/files/jvm/t2827.scala
new file mode 100644
index 0000000..d89e685
--- /dev/null
+++ b/test/files/jvm/t2827.scala
@@ -0,0 +1,14 @@
+object Stooges extends Enumeration {
+  type Stooge = Value
+  val Larry, Curly, Moe = Value
+  def nextStooge(v:Stooges.Stooge):Stooges.Stooge =
+    Stooges((v.id+1) % Stooges.maxId)
+}
+
+object Test {
+  def main(args: Array[String]) {
+    println(Stooges.Larry)
+    println(Stooges.Curly)
+    println(Stooges.Moe)
+  }
+}
diff --git a/test/files/jvm/t3003.check b/test/files/jvm/t3003.check
new file mode 100644
index 0000000..c69e389
--- /dev/null
+++ b/test/files/jvm/t3003.check
@@ -0,0 +1 @@
+List(List(@Annot(optionType=class java.lang.String)))
diff --git a/test/files/jvm/t3003.cmds b/test/files/jvm/t3003.cmds
new file mode 100644
index 0000000..c003966
--- /dev/null
+++ b/test/files/jvm/t3003.cmds
@@ -0,0 +1,2 @@
+javac Annot.java
+scalac Test_1.scala
diff --git a/test/files/jvm/t3003/Annot.java b/test/files/jvm/t3003/Annot.java
new file mode 100644
index 0000000..1d5f206
--- /dev/null
+++ b/test/files/jvm/t3003/Annot.java
@@ -0,0 +1,4 @@
+ at java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
+public @interface Annot {
+    Class<?> optionType();
+}
diff --git a/test/files/jvm/t3003/Test_1.scala b/test/files/jvm/t3003/Test_1.scala
new file mode 100644
index 0000000..ec7f220
--- /dev/null
+++ b/test/files/jvm/t3003/Test_1.scala
@@ -0,0 +1,8 @@
+class C {
+  @Annot(optionType=classOf[String]) val k = 0
+}
+object Test {
+  def main(args: Array[String]) {
+    println(classOf[C].getDeclaredFields.toList.sortBy(f => f.getName).map(f => f.getAnnotations.toList))
+  }
+}
diff --git a/test/files/jvm/t3102.check b/test/files/jvm/t3102.check
new file mode 100644
index 0000000..d705e0b
--- /dev/null
+++ b/test/files/jvm/t3102.check
@@ -0,0 +1,2 @@
+42
+OK
diff --git a/test/files/jvm/t3102.scala b/test/files/jvm/t3102.scala
new file mode 100644
index 0000000..fbcf2e6
--- /dev/null
+++ b/test/files/jvm/t3102.scala
@@ -0,0 +1,36 @@
+import scala.actors.{Actor, TIMEOUT}
+import Actor._
+
+object Test {
+  def main(args: Array[String]) {
+    val a = actor {
+      try {
+      react {
+        case 'hello =>
+          reply(42)
+      }
+      } catch {
+        case e: Throwable if !e.isInstanceOf[scala.util.control.ControlThrowable] =>
+          e.printStackTrace()
+      }
+    }
+
+    val b = actor {
+      try {
+      self.trapExit = true
+      val ft = a !! 'hello
+      println(ft())
+      // no message should be left over in mailbox
+      reactWithin(0) {
+        case TIMEOUT =>
+          println("OK")
+        case any =>
+          println(any)
+      }
+      } catch {
+        case e: Throwable if !e.isInstanceOf[scala.util.control.ControlThrowable] =>
+          e.printStackTrace()
+      }
+    }
+  }
+}
diff --git a/test/files/jvm/t3356.check b/test/files/jvm/t3356.check
new file mode 100644
index 0000000..6a9284d
--- /dev/null
+++ b/test/files/jvm/t3356.check
@@ -0,0 +1 @@
+sending download requests
diff --git a/test/files/jvm/t3356.scala b/test/files/jvm/t3356.scala
new file mode 100644
index 0000000..5626281
--- /dev/null
+++ b/test/files/jvm/t3356.scala
@@ -0,0 +1,54 @@
+import scala.actors.{Actor, Exit, !, UncaughtException}
+import Actor._
+
+case class ImageInfo(text: String) {
+  def downloadImage(): ImageData = {
+    ImageData(text)
+  }
+}
+
+case class ImageData(text: String)
+case class Download(info: ImageInfo)
+
+object Test {
+
+  def scanForImageInfo(url: String): List[ImageInfo] =
+    List(ImageInfo("A"), ImageInfo("B"))
+
+  def renderImage(data: ImageData) {
+    println("rendering image "+data.text)
+  }
+
+  def renderImages(url: String) {
+    val imageInfos = scanForImageInfo(url)
+    println("sending download requests")
+    val dataFutures = for (info <- imageInfos) yield {
+      val loader = link {
+        react { case Download(info) =>
+          throw new Exception("no connection")
+          reply(info.downloadImage())
+        }; {}
+      }
+      loader !! Download(info)
+    }
+    var i = 0
+    loopWhile (i < imageInfos.size) {
+      i += 1
+      val FutureInput = dataFutures(i-1).inputChannel
+      react {
+        case FutureInput ! (data @ ImageData(_)) =>
+          renderImage(data)
+        case Exit(from, UncaughtException(_, Some(Download(info)), _, _, cause)) =>
+          println("Couldn't download image "+info+" because of "+cause)
+      }
+    }
+    println("OK, all images rendered.")
+  }
+
+  def main(args: Array[String]) {
+    actor {
+      renderImages("panorama.epfl.ch")
+    }
+  }
+
+}
diff --git a/test/files/jvm/actor-bangbang.check b/test/files/jvm/t3365.check
similarity index 100%
rename from test/files/jvm/actor-bangbang.check
rename to test/files/jvm/t3365.check
diff --git a/test/files/jvm/t3365.scala b/test/files/jvm/t3365.scala
new file mode 100644
index 0000000..b94e804
--- /dev/null
+++ b/test/files/jvm/t3365.scala
@@ -0,0 +1,65 @@
+import scala.actors.{ReplyReactor, Channel, Actor, Future}
+
+case class ChannelMsg(chan: Channel[Any])
+
+class MyActor extends Actor {
+  def act() {
+    try {
+    val chan = new Channel[Any](this)
+    loop {
+      react {
+        case other: ReplyReactor =>
+          other ! ChannelMsg(chan)
+          loop {
+            chan.react {
+              case 'hello =>
+                reply('hello)
+              case 'stop =>
+                exit()
+            }
+          }
+      }
+    }
+    } catch {
+      case e: Throwable if !e.isInstanceOf[scala.util.control.ControlThrowable] =>
+        e.printStackTrace()
+    }
+  }
+}
+
+object Test {
+  def main(args: Array[String]) {
+    val a = new MyActor
+    a.start()
+
+    val b = new Actor {
+      def act() {
+        try {
+        react {
+          case ChannelMsg(c) =>
+            var i = 0
+            loop {
+              i += 1
+              val ft: Future[Any] = c !! 'hello
+              ft.inputChannel.react {
+                case msg =>
+                  if (i % 10000 == 0)
+                    println(msg)
+                  if (i >= 50000) {
+                    c ! 'stop
+                    exit()
+                  }
+              }
+            }
+        }
+        } catch {
+          case e: Throwable if !e.isInstanceOf[scala.util.control.ControlThrowable] =>
+            e.printStackTrace()
+        }
+      }
+    }
+    b.start()
+
+    a ! b
+  }
+}
diff --git a/test/files/jvm/t3407.check b/test/files/jvm/t3407.check
new file mode 100644
index 0000000..a133c88
--- /dev/null
+++ b/test/files/jvm/t3407.check
@@ -0,0 +1,10 @@
+result: 42
+result: 42
+result: 42
+result: 42
+result: 42
+result: 42
+result: 42
+result: 42
+result: 42
+result: 42
diff --git a/test/files/jvm/t3407.scala b/test/files/jvm/t3407.scala
new file mode 100644
index 0000000..6c2ce85
--- /dev/null
+++ b/test/files/jvm/t3407.scala
@@ -0,0 +1,19 @@
+import scala.actors._, scala.actors.Actor._
+
+object Test {
+
+  def main(args: Array[String]) {
+    for (i <- 1 to 10) {
+      val ft = Futures.future { 42 }
+      println("result: " + ft())
+    }
+
+    for (i <- 1 to 10) {
+      receiveWithin(0) {
+        case TIMEOUT =>
+        case msg => println("unexpected: " + msg)
+      }
+    }
+  }
+
+}
diff --git a/test/files/jvm/t3412-channel.check b/test/files/jvm/t3412-channel.check
new file mode 100644
index 0000000..954c6e8
--- /dev/null
+++ b/test/files/jvm/t3412-channel.check
@@ -0,0 +1,10 @@
+6
+6
+6
+6
+6
+6
+6
+6
+6
+6
diff --git a/test/files/jvm/t3412-channel.scala b/test/files/jvm/t3412-channel.scala
new file mode 100644
index 0000000..fcc439b
--- /dev/null
+++ b/test/files/jvm/t3412-channel.scala
@@ -0,0 +1,38 @@
+import scala.actors._, scala.actors.Actor._, scala.actors.Futures._
+
+object Test {
+
+  def main(args: Array[String]) {
+
+    actor {
+      val C: Channel[Int] = new Channel[Int](self)
+
+      def respondAll(fts: List[Future[Int]], cnt: Int): Unit =
+        fts match {
+          case List() => C ! 0
+          case ft :: rest =>
+            if (cnt % 100 == 0)
+              println(ft())
+            respondAll(rest, cnt + 1)
+        }
+
+      actor {
+        val fts = for (_ <- 1 to 1000)
+                  yield C !! (3, {case x: Int => x})
+
+        actor {
+          respondAll(fts.toList, 0)
+        }
+      }
+
+      loop {
+        C.react {
+          case 0 => exit()
+          case i => reply(i * 2)
+        }
+      }
+    }
+
+  }
+
+}
diff --git a/test/files/jvm/t3412.check b/test/files/jvm/t3412.check
new file mode 100644
index 0000000..954c6e8
--- /dev/null
+++ b/test/files/jvm/t3412.check
@@ -0,0 +1,10 @@
+6
+6
+6
+6
+6
+6
+6
+6
+6
+6
diff --git a/test/files/jvm/t3412.scala b/test/files/jvm/t3412.scala
new file mode 100644
index 0000000..ced15ab
--- /dev/null
+++ b/test/files/jvm/t3412.scala
@@ -0,0 +1,32 @@
+import scala.actors._, scala.actors.Actor._, scala.actors.Futures._
+
+object Test {
+
+  def main(args: Array[String]) {
+
+    val a = actor {
+      loop { react {
+        case i: Int => reply(i * 2)
+        case 'stop => exit()
+      } }
+    }
+
+    val fts = for (_ <- 1 to 1000)
+      yield a !! (3, {case x: Int => x})
+
+    def respondAll(fts: List[Future[Int]], cnt: Int): Unit =
+      fts match {
+        case List() => a ! 'stop
+        case ft :: rest =>
+          if (cnt % 100 == 0)
+            println(ft())
+          respondAll(rest, cnt + 1)
+      }
+
+    actor {
+      respondAll(fts.toList, 0)
+    }
+
+  }
+
+}
diff --git a/test/files/jvm/t3415/Hello.java b/test/files/jvm/t3415/Hello.java
new file mode 100644
index 0000000..ae72064
--- /dev/null
+++ b/test/files/jvm/t3415/Hello.java
@@ -0,0 +1,3 @@
+public @interface Hello {
+    String msg() default "hoi";
+}
diff --git a/test/files/jvm/t3415/HelloWorld.scala b/test/files/jvm/t3415/HelloWorld.scala
new file mode 100644
index 0000000..53bf55e
--- /dev/null
+++ b/test/files/jvm/t3415/HelloWorld.scala
@@ -0,0 +1,4 @@
+object Test extends Application {
+  @Hello
+  def foo() { }
+}
diff --git a/test/files/jvm/t3470.check b/test/files/jvm/t3470.check
new file mode 100644
index 0000000..94cb526
--- /dev/null
+++ b/test/files/jvm/t3470.check
@@ -0,0 +1,3 @@
+A: started: 1
+A: started: 2
+A: started: 3
diff --git a/test/files/jvm/t3470.scala b/test/files/jvm/t3470.scala
new file mode 100644
index 0000000..5e4242c
--- /dev/null
+++ b/test/files/jvm/t3470.scala
@@ -0,0 +1,30 @@
+import scala.actors._
+
+object Test {
+
+  def expectActorState(a: Reactor[T] forSome { type T }, s: Actor.State.Value) {
+    var done = false
+    var i = 0
+    while (!done) {
+      i = i + 1
+      if (i == 10) { // only wait for 2 seconds total
+        println("FAIL ["+a+": expected "+s+"]")
+        done = true
+      }
+
+      Thread.sleep(200)
+      if (a.getState == s) // success
+        done = true
+    }
+  }
+
+  def main(args: Array[String]) {
+    val a = new Actor { var c = 0; def act() = { c += 1; println("A: started: " + c) } }
+    a.start()
+    expectActorState(a, Actor.State.Terminated)
+    a.restart()
+    expectActorState(a, Actor.State.Terminated)
+    a.restart()
+  }
+
+}
diff --git a/test/files/jvm5/throws-annot.check b/test/files/jvm/throws-annot.check
similarity index 100%
rename from test/files/jvm5/throws-annot.check
rename to test/files/jvm/throws-annot.check
diff --git a/test/files/jvm5/throws-annot.scala b/test/files/jvm/throws-annot.scala
similarity index 100%
rename from test/files/jvm5/throws-annot.scala
rename to test/files/jvm/throws-annot.scala
diff --git a/test/files/jvm/ticket2163/ticket2163.java b/test/files/jvm/ticket2163/ticket2163.java
new file mode 100644
index 0000000..b6511d2
--- /dev/null
+++ b/test/files/jvm/ticket2163/ticket2163.java
@@ -0,0 +1,9 @@
+import java.util.*;
+
+public class ticket2163 {
+    public void test() {
+      List<Integer> array = new ArrayList<Integer>();
+      Ticket2163Scala<List> foo = new Ticket2163Scala<List>(array);
+      foo.bar(array);
+    }
+}
diff --git a/test/files/jvm/ticket2163/ticket2163.scala b/test/files/jvm/ticket2163/ticket2163.scala
new file mode 100644
index 0000000..d30bfe2
--- /dev/null
+++ b/test/files/jvm/ticket2163/ticket2163.scala
@@ -0,0 +1,5 @@
+class Ticket2163Scala[CC[X]](x: CC[Int]) {
+  def bar[DD[X]](meh: DD[Int]): CC[Int] = x
+}
+
+object Test extends Application {}
diff --git a/test/files/jvm/typerep.check b/test/files/jvm/typerep.check
index ff98348..ca93180 100644
--- a/test/files/jvm/typerep.check
+++ b/test/files/jvm/typerep.check
@@ -9,10 +9,12 @@ Float
 Double
 String
 Unit
+Class[Int]
 
 Some[Int]
 Some[Int]
 Some[Some[Int]]
+Some[List[Int]]
 None
 None
 
diff --git a/test/files/jvm/typerep.scala b/test/files/jvm/typerep.scala
index ee039b7..cb00da4 100644
--- a/test/files/jvm/typerep.scala
+++ b/test/files/jvm/typerep.scala
@@ -1,7 +1,6 @@
 //############################################################################
 // Type Representation at runtime
 //############################################################################
-// $Id:  $
 
 import TypeRep._
 
@@ -49,7 +48,7 @@ object testPrimitives {
   println(getType(0.0d))
   println(getType("abc"))
   println(getType(())) // Unit
-//  println(getType(classOf[Int])) // Class
+  println(getType(classOf[Int])) // Class
   println
 }
 
@@ -58,7 +57,9 @@ object testOptions {
   val x: Option[Int] = Some(2)
   println(getType(x))
   println(getType(Some(Some(3))))
-  println(getType(None))
+  println(getType(Some(List(3))))
+  //println(getType(Some(None: List[Int])))  // error: no implicit argument matching parameter type TypeRep[object None] was foun
+  println(getType(None: Option[Int]))
   val y: Option[Int] = None
   println(getType(y))
   println
@@ -68,7 +69,7 @@ object testLists {
   println(getType(List(3)))
   println(getType(3 :: Nil))
   println(getType(List(List(3))))
-  println(getType(Nil))
+  println(getType(Nil: List[Int]))
   println(getType(List(1, "abc")))
   println
 }
@@ -156,7 +157,7 @@ object TypeRep {
 
   def getType[A](x: Option[A])(implicit rep: TypeRep[A]): TypeRep[Option[A]] = (x match {
     case Some(v) => SomeRep(rep)
-    case None    => NoneRep // or NoneRep(rep)
+    case None    => NoneRep
   }).asInstanceOf[TypeRep[Option[A]]]
 
   def getType[A](x: List[A])(implicit rep: TypeRep[A]): TypeRep[List[A]] = (x match {
@@ -174,12 +175,14 @@ object TypeRep {
   implicit def doubleRep: TypeRep[Double] = DoubleRep
 
   implicit def unitRep: TypeRep[Unit] = UnitRep
-//  implicit def classRep: TypeRep[Class] = ClassRep
   implicit def stringRep: TypeRep[String] = StringRep
-  implicit def noneRep: TypeRep[Option[Nothing]] = NoneRep[Nothing](NothingRep.asInstanceOf[TypeRep[Nothing]])
+  //implicit def noneRep: TypeRep[None.type] = NoneRep//[Nothing](NothingRep.asInstanceOf[TypeRep[Nothing]])
   implicit def anyRep: TypeRep[Any] = AnyRep
   implicit def nothingRep: TypeRep[Nothing] = NothingRep
 
+  implicit def classRep[A](implicit elemrep: TypeRep[A]): TypeRep[Class[A]] =
+    ClassRep(elemrep)
+
   implicit def someRep[A](implicit elemrep: TypeRep[A]): TypeRep[Some[A]] =
     SomeRep(elemrep)
 
@@ -189,9 +192,10 @@ object TypeRep {
   implicit def arrayRep[A](implicit elemrep: TypeRep[A]): TypeRep[Array[A]] =
     ArrayRep(elemrep)
 
-  implicit def tuple2Rep[A1, A2](implicit _1: TypeRep[A1], _2: TypeRep[A2]): TypeRep[Tuple2[A1, A2]] =
+  implicit def tuple2Rep[A1, A2](implicit _1: TypeRep[A1], _2: TypeRep[A2]): TypeRep[(A1, A2)] =
     Tuple2Rep(_1, _2)
-  implicit def tuple3Rep[A1, A2, A3](implicit _1: TypeRep[A1], _2: TypeRep[A2], _3: TypeRep[A3]): TypeRep[Tuple3[A1, A2, A3]] =
+
+  implicit def tuple3Rep[A1, A2, A3](implicit _1: TypeRep[A1], _2: TypeRep[A2], _3: TypeRep[A3]): TypeRep[(A1, A2, A3)] =
     Tuple3Rep(_1, _2, _3)
   implicit def tuple4Rep[A1, A2, A3, A4](implicit _1: TypeRep[A1], _2: TypeRep[A2], _3: TypeRep[A3], _4: TypeRep[A4]): TypeRep[Tuple4[A1, A2, A3, A4]] =
     Tuple4Rep(_1, _2, _3, _4)
@@ -263,7 +267,7 @@ object TypeRep {
   case object StringRep extends TypeRep[String] {
     override def toString = "String"
   }
-  case object NoneRep extends TypeRep[Option[Nothing]] {
+  case object NoneRep extends TypeRep[None.type] {
     override def toString = "None"
   }
   case object NilRep extends TypeRep[Nil.type] {
@@ -277,6 +281,10 @@ object TypeRep {
   }
 
   @serializable
+  case class ClassRep[A](elemRep: TypeRep[A]) extends TypeRep[Class[A]] {
+    override def toString = "Class[" + elemRep + "]"
+  }
+  @serializable
   case class SomeRep[A](elemRep: TypeRep[A]) extends TypeRep[Some[A]] {
     override def toString = "Some[" + elemRep + "]"
   }
@@ -296,7 +304,7 @@ object TypeRep {
   }
 
   @serializable
-  case class Tuple2Rep[A1, A2](_1: TypeRep[A1], _2: TypeRep[A2]) extends TypeRep[Tuple2[A1, A2]] {
+  case class Tuple2Rep[A1, A2](_1: TypeRep[A1], _2: TypeRep[A2]) extends TypeRep[(A1, A2)] {
     override def toString = "Tuple2[" + _1 + ", " + _2 + "]"
   }
   @serializable
diff --git a/test/files/jvm/unittest_io.scala b/test/files/jvm/unittest_io.scala
index 97a7f98..42c793f 100644
--- a/test/files/jvm/unittest_io.scala
+++ b/test/files/jvm/unittest_io.scala
@@ -7,7 +7,7 @@ object Test extends TestConsoleMain {
       new ReadlinesTest
   )
 
-  class ReadlinesTest extends TestCase("scala.io.Source method getLines") {
+  class ReadlinesTest extends TestCase("scala.io.Source method getLines()") {
     
     val src = Source.fromString(""" 
 This is a file
@@ -16,7 +16,7 @@ it is split on several lines.
 isn't it?
 """)
     def runTest() = assertEquals("wrong number of lines",src.getLines.toList.length,5) // five new lines in there
-    //for(val line <- src.getLines) {
+    //for (line <- src.getLines) {
     //  Console.print(line)
     //}
   }
diff --git a/test/files/jvm/unittest_xml.scala b/test/files/jvm/unittest_xml.scala
index 592c904..1c36e74 100644
--- a/test/files/jvm/unittest_xml.scala
+++ b/test/files/jvm/unittest_xml.scala
@@ -2,14 +2,8 @@
 object Test {
 
   import scala.testing.SUnit._
-  import scala.xml.{MetaData, Null, Parsing, PrefixedAttribute, UnprefixedAttribute }
+  import scala.xml.{MetaData, Null, Utility, PrefixedAttribute, UnprefixedAttribute }
 
-  class ParsingTest extends TestCase("scala.xml.Parsing") with Assert {
-    override def runTest = {
-      assertTrue(Parsing.isNameStart('b'))
-      assertFalse(Parsing.isNameStart(':'))
-    }
-  }
   class MetaDataTest extends TestCase("scala.xml.MetaData") with Assert {
 
     import scala.xml.{HasKeyValue, TopScope, NamespaceBinding, Node, Atom, Text }
@@ -65,6 +59,10 @@ object Test {
 
   class UtilityTest extends TestCase("scala.xml.Utility") with Assert {
     def runTest() = {
+      assertTrue(Utility.isNameStart('b'))
+      assertFalse(Utility.isNameStart(':'))
+      
+      
     val x = <foo>
                <toomuchws/>
             </foo>
@@ -92,19 +90,20 @@ object Test {
 	 val pp = new xml.PrettyPrinter(80,5)
 	assertEquals("pretty print sorted attrib:"+pp.format(q), "<a a=\"2\" g=\"3\" j=\"2\" oo=\"2\"></a>", pp.format(q))
 
+    <hi>
+      <there/>
+      <guys/>
+    </hi>.hashCode // Bug #777
   }
   }
 
   def main(args:Array[String]) = {
     val ts = new TestSuite(
-      new ParsingTest, 
       new MetaDataTest,
       new UtilityTest 
     )
     val tr = new TestResult()
     ts.run(tr)
-    for(val failure <- tr.failures) {
-      Console.println(failure)
-    }
+    tr.failures foreach Console.println
   }
 }
diff --git a/test/files/jvm/xml01.scala b/test/files/jvm/xml01.scala
index 4766de1..574d207 100644
--- a/test/files/jvm/xml01.scala
+++ b/test/files/jvm/xml01.scala
@@ -25,20 +25,18 @@ object Test extends Application with Assert {
     override def text = ""
   }
 
-  assertSameElements(List(3), List(3))
-
   println("equality")
-  assertEquals(c, parsedxml11)
-  assertEquals(parsedxml1, parsedxml11)
-  assertSameElements(List(parsedxml1), List(parsedxml11))
-  assertSameElements(Array(parsedxml1).toList, List(parsedxml11))
+  assertEqualsXML(c, parsedxml11)
+  assertEqualsXML(parsedxml1, parsedxml11)
+  assertSameElementsXML(List(parsedxml1), List(parsedxml11))
+  assertSameElementsXML(Array(parsedxml1).toList, List(parsedxml11))
 
   val x2 = "<book><author>Peter Buneman</author><author>Dan Suciu</author><title>Data on ze web</title></book>";
 
   val i = new InputSource(new StringReader(x2))
   val x2p = XML.load(i)
 
-  assertEquals(x2p, Elem(null, "book"  , e, sc,
+  assertEqualsXML(x2p, Elem(null, "book"  , e, sc,
                         Elem(null, "author", e, sc,Text("Peter Buneman")), 
                         Elem(null, "author", e, sc,Text("Dan Suciu")), 
                         Elem(null, "title" , e, sc,Text("Data on ze web"))));
@@ -51,19 +49,19 @@ object Test extends Application with Assert {
   println("xpath \\")
 
 
-  assertSameElements(parsedxml1 \ "_" ,    List(Elem(null,"world", e, sc)))
+  assertSameElementsXML(parsedxml1 \ "_" ,    List(Elem(null,"world", e, sc)))
 
-  assertSameElements(parsedxml1 \ "world", List(Elem(null,"world", e, sc)))
+  assertSameElementsXML(parsedxml1 \ "world", List(Elem(null,"world", e, sc)))
 
 /*
   Console.println( parsedxml2 \ "_" );
-  Console.println( (parsedxml2 \ "_" ).elements);
-  for( val i <- (parsedxml2 \ "_" ).elements) {
+  Console.println( (parsedxml2 \ "_" ).iterator);
+  for( val i <- (parsedxml2 \ "_" ).iterator) {
     Console.println( i );
   };
   */
 
-  assertSameElements( 
+  assertSameElementsXML( 
       parsedxml2 \ "_" , 
       
       List(
@@ -77,7 +75,7 @@ object Test extends Application with Assert {
   );
   assertEquals( (parsedxml2 \ "author").length, 0 );
 
-  assertSameElements( 
+  assertSameElementsXML( 
       parsedxml2 \ "book", 
       
       List(
@@ -91,7 +89,7 @@ object Test extends Application with Assert {
       )
   );
 
-  assertSameElements( 
+  assertSameElementsXML( 
 
       parsedxml2 \ "_" \ "_",
 
@@ -104,7 +102,7 @@ object Test extends Application with Assert {
     )
   );
 
-  assertSameElements( 
+  assertSameElementsXML( 
 
       parsedxml2 \ "_" \ "author",
 
@@ -116,11 +114,11 @@ object Test extends Application with Assert {
     
   );
 
-  assertSameElements( (parsedxml2 \ "_" \ "_" \ "author"), List() );
+  assertSameElementsXML( (parsedxml2 \ "_" \ "_" \ "author"), List() );
 
   Console.println("xpath \\\\ DESCENDANTS");
 
-  assertSameElements( 
+  assertSameElementsXML( 
 
       parsedxml2 \\ "author",
 
@@ -133,7 +131,7 @@ object Test extends Application with Assert {
  );
 
 
-  assertSameElements( 
+  assertSameElementsXML( 
 
       parsedxml2 \\ "title",
 
@@ -144,10 +142,10 @@ object Test extends Application with Assert {
 
 
   println(
-    (parsedxml2 \\ "book" ){ n:Node => n \ "title" == "Data on ze web" }
+    (parsedxml2 \\ "book" ){ n:Node => (n \ "title") xml_== "Data on ze web" }
   );
 
-  assertEquals( 
+  assertEqualsXML( 
 
       (new NodeSeq { val theSeq = List( parsedxml2 ) }) \\ "_",
 
@@ -191,13 +189,13 @@ object Test extends Application with Assert {
 
     val zz1 = <xml:group><a/><b/><c/></xml:group>
 
-    assertTrue(zx1 == zz1)
+    assertTrue(zx1 xml_== zz1)
     assertTrue(zz1.length == 3)
 
     // unparsed
 
-    val uup = <xml:unparsed>&<<>""^%@$!#</xml:unparsed>
-    assertTrue(uup == "&<<>\"\"^%@$!#")
+    // val uup = <xml:unparsed>&<<>""^%@$!#</xml:unparsed>
+    // assertTrue(uup == "&<<>\"\"^%@$!#")
     // test unicode escapes backslash u 
 
   println("attribute value normalization")
diff --git a/test/files/jvm/xml02.scala b/test/files/jvm/xml02.scala
index 49616ee..02aabf3 100644
--- a/test/files/jvm/xml02.scala
+++ b/test/files/jvm/xml02.scala
@@ -3,7 +3,7 @@ import testing.SUnit._
 object Test extends TestConsoleMain {
 
   import scala.xml.{NodeSeq, Utility}
-  import NodeSeq.view
+  import NodeSeq.seqToNodeSeq
 
   val ax = <hello foo="bar" x:foo="baz" xmlns:x="the namespace from outer space">
              <world/>
@@ -18,10 +18,10 @@ object Test extends TestConsoleMain {
   object XmlEx extends TestCase("attributes") with Assert {
 
     override def runTest = {
-      assertTrue("@one",       ax \ "@foo" == "bar")              // uses NodeSeq.view!
-      assertTrue("@two",       ax \ "@foo" == xml.Text("bar"))    // dto.
-      assertTrue("@three",     bx \ "@foo" == "bar&x")            // dto.
-      assertTrue  ("@four", (bx \ "@foo") sameElements List(xml.Text("bar&x")))
+      assertTrue("@one",       (ax \ "@foo") xml_== "bar")              // uses NodeSeq.view!
+      assertTrue("@two",       (ax \ "@foo") xml_== xml.Text("bar"))    // dto.
+      assertTrue("@three",     (bx \ "@foo") xml_== "bar&x")            // dto.
+      assertTrue  ("@four", (bx \ "@foo") xml_sameElements List(xml.Text("bar&x")))
       assertEquals("@five",  "<hello foo=\"bar&x\"></hello>", bx.toString)
     }
   }
@@ -29,8 +29,8 @@ object Test extends TestConsoleMain {
   object XmlEy extends TestCase("attributes with namespace") with Assert {
     override def runTest = {
       val z = ax \ "@{the namespace from outer space}foo"
-      assertTrue("@six",   ax \ "@{the namespace from outer space}foo" == "baz")
-      assertTrue("@eight", cx \ "@{the namespace from outer space}foo" == "baz")
+      assertTrue("@six",   (ax \ "@{the namespace from outer space}foo") xml_== "baz")
+      assertTrue("@eight", (cx \ "@{the namespace from outer space}foo") xml_== "baz")
  
       try {
         ax \ "@"
@@ -58,8 +58,8 @@ object Test extends TestConsoleMain {
     override def runTest = {
       assertTrue(<hello/> match { case <hello/> => true; case _ => false; })
       assertTrue(<x:ga xmlns:x="z"/> match { case <x:ga/> => true; case _ => false; });
-      assertTrue(Utility.trim(cx) match { case n @ <hello>crazy text world</hello> if n \ "@foo" == "bar" => true; })
-      assertTrue(Utility.trim(cx) match { case n @ <z:hello>crazy text world</z:hello> if n \ "@foo" == "bar" => true; })
+      assertTrue(Utility.trim(cx) match { case n @ <hello>crazy text world</hello> if (n \ "@foo") xml_== "bar" => true; })
+      assertTrue(Utility.trim(cx) match { case n @ <z:hello>crazy text world</z:hello> if (n \ "@foo") xml_== "bar" => true; })
     }
   }
 
diff --git a/test/files/jvm/xmlpull.scala b/test/files/jvm/xmlpull.scala
index fb802c2..9ba7d4c 100644
--- a/test/files/jvm/xmlpull.scala
+++ b/test/files/jvm/xmlpull.scala
@@ -7,25 +7,25 @@ object Test {
   val src = Source.fromString("<hello><world/>!</hello>")
  
   def main(args: Array[String]) {
-    var er = new XMLEventReader().initialize(src)
+    var er = new XMLEventReader(src)
     er.next match {
       case EvElemStart(_, "hello", _, _) => //println("1")
-	}
-	er.next match {
+    }
+    er.next match {
       case EvElemStart(_, "world", _, _) => //println("2")
     }
-	er.next match {
+    er.next match {
       case EvElemEnd(_, "world") => //println("3")
     }
-	er.next match {
+    er.next match {
       case EvText("!") => //println("4")
-	}
+    }
     er.next match {
       case EvElemEnd(_, "hello") => //println("5")
-	}
-	// you get the picture...
-	er.stop  // allow thread to be garbage-collected
-	//println("6")
+    }
+    // you get the picture...
+    er.stop  // allow thread to be garbage-collected
+    //println("6")
   }
 }
  
diff --git a/test/files/jvm/xmlstuff.scala b/test/files/jvm/xmlstuff.scala
index cc9d974..3508070 100644
--- a/test/files/jvm/xmlstuff.scala
+++ b/test/files/jvm/xmlstuff.scala
@@ -64,9 +64,9 @@ passed ok
       Text(x.attributes("value").toString + y.attributes("bazValue").toString+ "!")
     };
     val pelems_2 = new NodeSeq { val theSeq = List(Text("38!"),Text("58!")) };
-    assertSameElements(pelems_1, pelems_2)
+    assertSameElementsXML(pelems_1, pelems_2)
 
-    assertEquals(p \\ "@bazValue", Text("8"))
+    assertEqualsXML(p \\ "@bazValue", Text("8"))
 
     val books = 
     <bks>
@@ -97,7 +97,7 @@ passed ok
   println( new scala.xml.PrettyPrinter(80, 5).formatNodes (
     for (t <- books \\ "title";
          r <- reviews \\ "entry"
-         if r \ "title" == t) yield
+         if (r \ "title") xml_== t) yield
           <result>
     { t }
     { r \ "remarks" }
@@ -139,7 +139,7 @@ val addrBook =
   println( new scala.xml.PrettyPrinter(80, 5).formatNodes (
     for (t <- addrBook \\ "entry";
          r <- phoneBook \\ "entry"
-         if t \ "name" == r \ "name") yield
+         if (t \ "name") xml_== (r \ "name")) yield
           <result>
     { t.child }
     { r \ "phone" }
diff --git a/test/files/jvm5/annotations.check b/test/files/jvm5/annotations.check
deleted file mode 100644
index 4183013..0000000
--- a/test/files/jvm5/annotations.check
+++ /dev/null
@@ -1,35 +0,0 @@
-class java.rmi.RemoteException
-class java.io.IOException
- at java.lang.Deprecated()
- at test.SourceAnnotation(mails={scala at lists.epfl.ch,scala-lounge at lists.epfl.ch}, value=http://scala-lang.org)
-class Test4$Foo1
-
- at test.SourceAnnotation(mails={you at bloodsuckers.com}, value=http://bloodsuckers.com)
-class Test4$Foo2
-
- at test.SourceAnnotation(mails={bill.gates at bloodsuckers.com}, value=http://bloodsuckers.com)
-class Test4$Foo3
-
- at test.SourceAnnotation(mails={bill.gates at bloodsuckers.com}, value=file:///dev/null)
-private final int Test4$Foo4.x
-
- at test.SourceAnnotation(mails={bill.gates at bloodsuckers.com}, value=file:///dev/null)
-public int Test4$Foo4.x()
-
- at test.SourceAnnotation(mails={bill.gates at bloodsuckers.com}, value=file:///dev/zero)
-public int Test4$Foo5.bar()
-
- at test.SourceAnnotation(mails={bill.gates at bloodsuckers.com}, value=primary constructor)
-public Test4$Foo6(java.lang.String)
-
- at test.SourceAnnotation(mails={bill.gates at bloodsuckers.com}, value=secondary constructor)
-public Test4$Foo7()
-
- at test.SourceAnnotation(mails={bill.gates at bloodsuckers.com}, value=constructor val)
-private final int Test4$Foo8.n
-
- at test.SourceAnnotation(mails={bill.gates at bloodsuckers.com}, value=constructor val)
-public int Test4$Foo8.n()
-
-0
-99
diff --git a/test/files/jvm5/annotations.scala b/test/files/jvm5/annotations.scala
deleted file mode 100644
index 9af2d33..0000000
--- a/test/files/jvm5/annotations.scala
+++ /dev/null
@@ -1,159 +0,0 @@
-object Test1 {
-  class Foo {
-    @remote
-    def foo: Unit = ()
-  }
-  def run {
-    val method = classOf[Foo].getMethod("foo")
-    method.getExceptionTypes foreach println
-  }
-}
-
-object Test2 {
-  import java.io.{BufferedReader,FileReader, IOException}
-  class Reader(fname: String) {
-    private val in = new BufferedReader(new FileReader(fname))
-
-    @throws(classOf[IOException])
-    def read() = in.read()
-  }
-  def run {
-    val method = classOf[Reader].getMethod("read")
-    method.getExceptionTypes foreach println
-  }
-}
-
-/* Java:
-public class Main {
-    @Deprecated
-    public void foo() {}
-    public static void main(String[] args) throws Exception {
-        Method method = Class.forName("test.Main").getMethod("foo", new Class[]{});
-        Annotation annotation = method.getAnnotation(Deprecated.class);
-        System.out.println(annotation); // @java.lang.Deprecated()
-    }
-}
-*/
-object Test3 {
-  import java.lang.Deprecated
-  class Foo {
-    @Deprecated
-    def foo: Unit = ()
-  }
-  def run {
-    val method = classOf[Foo].getMethod("foo")
-    val annotation = method.getAnnotation(classOf[Deprecated])
-    println(annotation)
-  }
-}
-
-/* Java:
- at Retention(value=RetentionPolicy.RUNTIME)
- at interface Source {
-   public String url();
-   public String mail();
-}
- at Source(url="http://scala.epfl.ch", mail="scala at lists.epfl.ch")
-class Foo {}
-public class Main {
-    public static void main(String[] args) throws Exception {
-        Class clazz = Class.forName("test.Foo");
-        Annotation[] annotations = clazz.getAnnotations();
-        for (int i = 0; i < annotations.length; i++)
-            System.out.println(annotations[i]);
-        // @test.Main$Source(url=http://scala-lang.org, mail=scala at lists.epfl.ch)
-    }
-}
-*/
-object Test4 {
-  import test.SourceAnnotation // defined in SourceAnnotation.java
-  @SourceAnnotation{val value = "http://scala-lang.org",
-                    val mails = Array("scala at lists.epfl.ch", "scala-lounge at lists.epfl.ch")}
-  class Foo1
-  @SourceAnnotation("http://bloodsuckers.com") { val mails = Array("you at bloodsuckers.com") }
-  class Foo2
-  @SourceAnnotation("http://bloodsuckers.com")
-  class Foo3
-  class Foo4 {
-    @SourceAnnotation("file:///dev/null")
-    val x = 1
-  }
-  class Foo5 {
-    @SourceAnnotation("file:///dev/zero")
-    def bar: Int = 0
-  }
-  class Foo6 @SourceAnnotation("primary constructor")(s: String) {
-    // to guarantee that primary constructor annotations
-    // are not applied to secondary constructors
-    def this() = this("")
-  }
-  class Foo7(s: String) {
-    @SourceAnnotation("secondary constructor")
-    def this() = this("")
-  }
-  class Foo8(@SourceAnnotation("constructor val") val n: Int) {}
-  def run {
-    import java.lang.annotation.Annotation
-    import java.lang.reflect.AnnotatedElement
-    def printSourceAnnotations(target: AnnotatedElement) {
-      //print SourceAnnotation in a predefined way to insure
-      // against difference in the JVMs (e.g. Sun's vs IBM's)
-      def printSourceAnnotation(a: Annotation) {
-        val ann = a.asInstanceOf[SourceAnnotation]
-        println("@test.SourceAnnotation(mails=" + ann.mails.deepMkString("{", ",", "}") +
-                ", value=" + ann.value + ")")
-      }
-      val anns = target.getAnnotations()
-      anns foreach printSourceAnnotation
-      if (anns.length > 0) {
-        println(target)
-        println
-      }
-    }
-    printSourceAnnotations(classOf[Foo1])
-    printSourceAnnotations(classOf[Foo2])
-    printSourceAnnotations(classOf[Foo3])
-    classOf[Foo4].getDeclaredFields  foreach printSourceAnnotations
-    classOf[Foo4].getDeclaredMethods foreach printSourceAnnotations
-    classOf[Foo5].getDeclaredMethods foreach printSourceAnnotations
-    classOf[Foo6].getDeclaredConstructors foreach printSourceAnnotations
-    classOf[Foo7].getDeclaredConstructors foreach printSourceAnnotations
-    classOf[Foo8].getDeclaredFields  foreach printSourceAnnotations
-    classOf[Foo8].getDeclaredMethods foreach printSourceAnnotations
-  }
-}
-
-object Test5 {
-  import scala.reflect.BeanProperty
-  import java.lang.Integer
-
-  class Count {
-    // we use "Integer" instead of "Int" because of Java reflection
-    @BeanProperty
-    private var count: Integer = 0
-
-    private val getter =
-      getClass().getMethod("getCount")
-    private val setter =
-      getClass().getMethod("setCount", classOf[Integer])
-
-    def get = getter.invoke(this).asInstanceOf[Integer].intValue
-    def set(n: Int) = setter.invoke(this, new Integer(n))
-  }
-  def run {
-    val count = new Count
-    println(count.get)
-    count.set(99)
-    println(count.get)
-  }
-}
-
-object Test {
-  def main(args: Array[String]) {
-    Test1.run
-    Test2.run
-    Test3.run     // requires the use of -target:jvm-1.5
-    Test4.run
-    Test5.run
-  }
-}
diff --git a/test/files/jvm5/interpreter.check b/test/files/jvm5/interpreter.check
deleted file mode 100644
index aa2776f..0000000
--- a/test/files/jvm5/interpreter.check
+++ /dev/null
@@ -1,212 +0,0 @@
-Type in expressions to have them evaluated.
-Type :help for more information.
-
-scala> 
-scala> 
-scala> res0: Int = 7
-
-scala>      |      |      |      | gcd: (Int,Int)Int
-
-scala> five: Int = 5
-
-scala> x: Int = 1
-
-scala> x: Int = 2
-
-scala> three: Int = 3
-
-scala> defined type alias anotherint
-
-scala> four: anotherint = 4
-
-scala> <console>:5: error: type mismatch;
- found   : java.lang.String("hello")
- required: anotherint
-       val bogus: anotherint = "hello"
-                               ^
-
-scala> defined trait PointlessTrait
-
-scala> x: Int = 2
-y: Int = 3
-
-scala> hello
-
-scala> 
-scala> 
-scala> t1513: Array[Null] = Array(null)
-
-scala> 
-scala> atom: scala.xml.Atom[Unit] = ()
-
-scala> 
-scala> defined class S
-
-scala> fish: S = fish
-
-scala> 
-scala> arr: Array[java.lang.String] = Array(What's, up, doc?)
-
-scala> 
-scala> arrInt: Any = Array(1, 2, 3)
-
-scala> 
-scala> arrArrInt: Any = Array(Array(1, 2), Array(3, 4))
-
-scala> 
-scala> 
-scala> defined class Foo
-
-scala> defined class Bar
-
-scala> foo2bar: (Foo)Bar
-
-scala> bar: Bar = Bar(3)
-
-scala> 
-scala> 
-scala> import bar._
-
-scala> m: Int = 3
-
-scala> 
-scala> 
-scala> one: Int = 1
-
-scala> one: Int = 1
-
-scala> one: Int = 1
-
-scala> one: Int = 1
-
-scala> one: Int = 1
-
-scala> one: Int = 1
-
-scala> one: Int = 1
-
-scala> one: Int = 1
-
-scala> one: Int = 1
-
-scala> one: Int = 1
-
-scala> one: Int = 1
-
-scala> one: Int = 1
-
-scala> one: Int = 1
-
-scala> one: Int = 1
-
-scala> one: Int = 1
-
-scala> one: Int = 1
-
-scala> one: Int = 1
-
-scala> one: Int = 1
-
-scala> one: Int = 1
-
-scala> one: Int = 1
-
-scala> 
-scala> 
-scala> x1: Int = 1
-
-scala> x2: Int = 1
-
-scala> x3: Int = 1
-
-scala> x4: Int = 1
-
-scala> x5: Int = 1
-
-scala> x6: Int = 1
-
-scala> x7: Int = 1
-
-scala> x8: Int = 1
-
-scala> x9: Int = 1
-
-scala> x10: Int = 1
-
-scala> x11: Int = 1
-
-scala> x12: Int = 1
-
-scala> x13: Int = 1
-
-scala> x14: Int = 1
-
-scala> x15: Int = 1
-
-scala> x16: Int = 1
-
-scala> x17: Int = 1
-
-scala> x18: Int = 1
-
-scala> x19: Int = 1
-
-scala> x20: Int = 1
-
-scala> 
-scala> two: Int = 2
-
-scala> 
-scala> 
-scala> 
-scala> 
-scala> <console>:1: error: '=' expected but '=>' found.
-       def x => y => z
-             ^
-
-scala> <console>:1: error: expected start of definition
-       [1,2,3]
-       ^
-
-scala> 
-scala> 
-scala> 
-scala>      |      |      |      | res3: scala.xml.Elem = 
-<a>
-       <b d="dd" c="c"></b></a>
-
-scala> 
-scala> 
-scala>      |      |      |      | 
-scala> 
-scala> 
-scala> 
-scala>      |      |      | res4: java.lang.String = 
-
-       hello
-       there
-       
-
-scala> 
-scala>      |      | You typed two blank lines.  Starting a new command.
-
-scala> 
-scala> match: Int
-
-scala> x: Int = 1
-
-scala> 
-scala> 
-scala> defined class Exp
-defined class Fact
-defined class Term
-
-scala>      |      | <console>:15: warning: match is not exhaustive!
-missing combination           Term
-
-       def f(e: Exp) = e match {  // non-exhaustive warning here
-                       ^
-f: (Exp)Int
-
-scala> 
-scala> 
diff --git a/test/files/jvm5/interpreter.scala b/test/files/jvm5/interpreter.scala
deleted file mode 100644
index 1c3a98a..0000000
--- a/test/files/jvm5/interpreter.scala
+++ /dev/null
@@ -1,172 +0,0 @@
-import scala.tools.nsc._
-import java.io.{BufferedReader, StringReader, PrintWriter,
-                Writer, OutputStreamWriter}
-
-object Test {
-  val testCodeString = <code>
-// basics
-3+4
-def gcd(x: Int, y: Int): Int = {{
-          if (x == 0) y
-          else if (y == 0) x
-          else gcd(y%x, x)
-}}
-val five = gcd(15,35)
-var x = 1
-x = 2
-val three = x+1
-type anotherint = Int
-val four: anotherint = 4
-val bogus: anotherint = "hello"
-trait PointlessTrait
-val (x,y) = (2,3)
-println("hello")
-
-// ticket #1513
-val t1513 = Array(null)
-// ambiguous toString problem from #547
-val atom = new scala.xml.Atom()
-// overriding toString problem from #1404
-class S(override val toString : String)
-val fish = new S("fish")
-// Test that arrays pretty print nicely.
-val arr = Array("What's", "up", "doc?") 
-// Test that arrays pretty print nicely, even when we give them type Any
-val arrInt : Any = Array(1,2,3)
-// Test that nested arrays are pretty-printed correctly
-val arrArrInt : Any = Array(Array(1, 2), Array(3, 4))
-
-// implicit conversions
-case class Foo(n: Int)
-case class Bar(n: Int)
-implicit def foo2bar(foo: Foo) = Bar(foo.n)
-val bar: Bar = Foo(3)
-
-// importing from a previous result
-import bar._
-val m = n
-
-// stressing the imports mechanism
-val one = 1
-val one = 1
-val one = 1
-val one = 1
-val one = 1
-val one = 1
-val one = 1
-val one = 1
-val one = 1
-val one = 1
-val one = 1
-val one = 1
-val one = 1
-val one = 1
-val one = 1
-val one = 1
-val one = 1
-val one = 1
-val one = 1
-val one = 1
-
-
-val x1 = 1
-val x2 = 1
-val x3 = 1
-val x4 = 1
-val x5 = 1
-val x6 = 1
-val x7 = 1
-val x8 = 1
-val x9 = 1
-val x10 = 1
-val x11 = 1
-val x12 = 1
-val x13 = 1
-val x14 = 1
-val x15 = 1
-val x16 = 1
-val x17 = 1
-val x18 = 1
-val x19 = 1
-val x20 = 1
-
-val two = one + x5
-
-
-// interior syntax errors should *not* go into multi-line input mode.
-// both of the following should abort immediately:
-def x => y => z
-[1,2,3]
-
-
-// multi-line XML
-<a>
-<b
-  c="c"
-  d="dd"
-/></a>
-
-
-/*
-  /*
-    multi-line comment
-  */
-*/
-
-
-// multi-line string
-"""
-hello
-there
-"""
-
-(1 +   // give up early by typing two blank lines
-
-
-// defining and using quoted names should work (ticket #323)
-def `match` = 1 
-val x = `match` 
-
-// multiple classes defined on one line
-sealed class Exp; class Fact extends Exp; class Term extends Exp
-def f(e: Exp) = e match {{  // non-exhaustive warning here
-  case _:Fact => 3
-}}
-
-</code>.text
-
-  /** A writer that skips the first line of text.  The first
-   *  line of interpreter output is skipped because it includes
-   *  a version number. */
-  class Skip1Writer(writer: Writer) extends Writer {
-    var seenNL = false
-
-    def write(cbuf: Array[Char], off: Int, len: Int) {
-      if (seenNL) 
-	writer.write(cbuf, off, len) 
-      else {
-	val slice : Array[Char] = cbuf.slice(off, off+len)
-	val i = slice.indexOf('\n')
-	if (i >= 0) {
-	  seenNL = true
-	  writer.write(slice, i+1, slice.length-(i+1))
-	} else {
-	  // skip it
-	}
-      }
-    }
-
-    def close() { writer.close() }
-    def flush() { writer.flush() }
-  }
-
-
-  def main(args: Array[String]) {
-    val input = new BufferedReader(new StringReader(testCodeString))
-    val output = new PrintWriter(
-      new Skip1Writer(new OutputStreamWriter(Console.out)))
-    val repl = new InterpreterLoop(input, output)
-    repl.main(new Settings)
-    println()
-  }
-}
diff --git a/test/files/jvm5/mkAnnotationsJar.sh b/test/files/jvm5/mkAnnotationsJar.sh
deleted file mode 100644
index 8b2c49d..0000000
--- a/test/files/jvm5/mkAnnotationsJar.sh
+++ /dev/null
@@ -1,29 +0,0 @@
-#!/bin/sh
-
-##############################################################################
-# Author  : Nikolay Mihaylov
-# Revision: $Id: mkAnnotationsJar.sh 13048 2007-10-10 14:55:16Z dragos $
-##############################################################################
-
-##############################################################################
-# variables
-
-OBJDIR=./classes
-
-if [ -z "${JAVA_HOME}" ]; then
-  echo "environment variable JAVA_HOME is undefined."
-  exit
-fi
-
-JAVAC=${JAVA_HOME}/bin/javac
-JAVAC_OPTIONS="-source 1.5 -target 1.5"
-
-JAR=${JAVA_HOME}/bin/jar
-
-##############################################################################
-# commands
-
-mkdir -p ${OBJDIR}
-${JAVAC} ${JAVAC_OPTIONS} -d ${OBJDIR} SourceAnnotation.java NestedAnnotations.java
-${JAR} cf ../lib/annotations.jar -C ${OBJDIR} .
-rm -rf ${OBJDIR}
diff --git a/test/files/jvm5/stringbuilder.scala b/test/files/jvm5/stringbuilder.scala
deleted file mode 100644
index 463bd09..0000000
--- a/test/files/jvm5/stringbuilder.scala
+++ /dev/null
@@ -1,99 +0,0 @@
-/* $Id: stringbuilder.scala 14446 2008-03-25 15:50:30Z michelou $ */
-
-import testing.SUnit._
-
-/** Test the Scala implementation of class <code>scala.StringBuilder</code>.
- *
- *  @author Stephane Micheloud
- */
-object Test extends TestConsoleMain {
-  def suite = new TestSuite(
-    Test1, //ctor, reverse
-    Test2, //append
-    Test3, //insert
-    Test4  //indexOf, lastIndexOf
-  )
-}
-
-object Test1 extends TestCase("ctor") with Assert {
-  override def enableStackTrace = false
-  override def runTest {
-    val j0 = new java.lang.StringBuilder("abc") // Java 1.5+
-    val s0 = new StringBuilder("abc")
-    assertEquals("s0 equals j0", false, s0 equals j0)
-    assertEquals("s0.toString equals j0.toString", true, s0.toString equals j0.toString)
-
-    val str = """
-Scala is a general purpose programming language designed to express common programming patterns in a concise, elegant, and type-safe way. It smoothly integrates features of object-oriented and functional languages. It is also fully interoperable with Java."""
-    val j1 = new java.lang.StringBuilder(100) append str
-    val s1 = new java.lang.StringBuilder(100) append str
-    assertEquals("s1.toString equals j1.toString", true, s1.toString equals j1.toString)
-
-    val j2 = j0 reverse
-    val s2 = s0 reverse;
-    //println("j2="+j2+", s2="+s2)//debug
-    assertEquals("s2.toString equals j2.toString", true, s2.toString equals j2.toString)
-
-    val j3 = j2; j3 setCharAt (0, j3 charAt 2)
-    val s3 = s2; s3(0) = s3(2)
-    //println("j3="+j3+", s3="+s3)//debug
-    assertEquals("s3.toString equals j3.toString", true, s3.toString equals j3.toString)    
- }
-}
-
-object Test2 extends TestCase("append") with Assert {
-  override def enableStackTrace = false
-  override def runTest {
-    val j0 = new java.lang.StringBuilder("abc") // Java 1.5+
-    val s0 = new StringBuilder("abc")
-
-    j0 append true append (1.toByte) append 'a' append 9 append -1L append 1.2e-10f append -2.1e+100d
-    s0 append true append (1.toByte) append 'a' append 9 append -1L append 1.2e-10f append -2.1e+100d
-    assertEquals("s0.toString equals j0.toString", true, s0.toString equals j0.toString)
-
-    val j1 = new java.lang.StringBuilder // Java 1.5+
-    val s1 = new StringBuilder
-    j1 append "###" append Array('0', '1', '2') append "xyz".subSequence(0, 3)
-    s1 append "###" append Array('0', '1', '2') append List('x', 'y', 'z')
-    assertEquals("s1.toString equals j1.toString", true, s1.toString equals j1.toString)
- }
-}
-
-object Test3 extends TestCase("insert") with Assert {
-  override def enableStackTrace = false
-  override def runTest {
-    val j0 = new java.lang.StringBuilder("abc") // Java 1.5+
-    val s0 = new StringBuilder("abc")
-
-    j0 insert (0, true) insert (0, 1.toByte) insert (0, 'a') insert (0, 88.toShort) insert (0, 9) insert (0, -1L)
-    s0 insert (0, true) insert (0, 1.toByte) insert (0, 'a') insert (0, 88.toShort) insert (0, 9) insert (0, -1L)
-    //println("j0="+j0+", s0="+s0)//debug
-    assertEquals("s0.toString equals j0.toString", true, s0.toString equals j0.toString)
-
-    val j1 = new java.lang.StringBuilder // Java 1.5+
-    val s1 = new StringBuilder
-    j1 insert (0, "###") insert (0, Array('0', '1', '2')) insert (0, "xyz".subSequence(0, 3))
-    s1 insert (0, "###") insert (0, Array('0', '1', '2')) insert (0, List('x', 'y', 'z'))
-    //println("j1="+j1+", s1="+s1)//debug
-    assertEquals("s1.toString equals j1.toString", true, s1.toString equals j1.toString)
-
-  }
-}
-
-object Test4 extends TestCase("indefOf") with Assert {
-  override def enableStackTrace = false
-  override def runTest {
-    val j0 = new java.lang.StringBuilder("abc") // Java 1.5+
-    val s0 = new StringBuilder("abc")
-
-    val j1 = j0 indexOf("c")
-    val s1 = s0 indexOf("c")
-    //println("j1="+j1+", s1="+s1)//debug
-    assertEquals("s1 == j1", true, s1 == j1)
-
-    val j2 = j0 append "123abc" lastIndexOf("c")
-    val s2 = s0 append "123abc" lastIndexOf("c")
-    //println("j2="+j2+", s2="+s2)//debug
-    assertEquals("s2 == j2", true, s2 == j2)
- }
-}
diff --git a/test/files/jvm5/sync-var.scala b/test/files/jvm5/sync-var.scala
deleted file mode 100644
index aa6ae9f..0000000
--- a/test/files/jvm5/sync-var.scala
+++ /dev/null
@@ -1,53 +0,0 @@
-import java.util.concurrent._
-import java.util.concurrent.atomic._
-
-object Test { def main(args: Array[String]) {
-
-val n = 10000
-val i = new AtomicInteger(n)
-val j = new AtomicInteger(n)
-val sum = new AtomicInteger
-
-val q = new scala.concurrent.SyncVar[Int]
-
-val producers = (1 to 3).force map { z => new Thread {
-  override def run() {
-    var again = true
-    while (again) {
-      val x = i.getAndDecrement()
-      if (x > 0)
-        q put x
-      else
-        again = false
-    }
-  }
-} }
-
-val summers = (1 to 7).force map { z => new Thread {
-  override def run() {
-    val x = j.decrementAndGet()
-    if (x >= 0) {
-      sum addAndGet q.take()
-    }
-    if (x > 0) {
-      run()
-    } else {
-      // done
-    }
-  }
-} }
-
-summers foreach { _.start() }
-producers foreach { _.start() }
-
-summers foreach { _.join() }
-
-val got = sum.get
-val expected = (n + 1) * n / 2
-println(got + " " + expected + " " + (got == expected))
-
-producers foreach { _.join() }
-
-} }
-
-// vim: set ts=2 sw=2 et:
diff --git a/test/files/jvm5/typerep.check b/test/files/jvm5/typerep.check
deleted file mode 100644
index ca93180..0000000
--- a/test/files/jvm5/typerep.check
+++ /dev/null
@@ -1,49 +0,0 @@
-Boolean
-Boolean
-true
-Byte
-Char
-Int
-Long
-Float
-Double
-String
-Unit
-Class[Int]
-
-Some[Int]
-Some[Int]
-Some[Some[Int]]
-Some[List[Int]]
-None
-None
-
-List[Int]
-List[Int]
-List[List[Int]]
-Nil
-List[Any]
-
-Array[Int]
-Array[Array[Int]]
-Array[Int]
-Array[Int]
-Array[Int]
-Array[Int]
-
-Tuple2[Int, String]
-Tuple3[Char, Char, String]
-Tuple2[Tuple2[Int, String], Tuple2[Int, String]]
-Tuple2[Tuple2[Some[Char], Int], Tuple2[Some[Char], Int]]
-
-Function1[Int, Int]
-Int
-Function1[Int, Int]
-Int
-Function1[Int, Function1[Int, Int]]
-Function1[Int, Int]
-Int
-Function3[Boolean, List[Char], Int, Int]
-Function2[Function1[Int, Int], Int, Int]
-Int
-
diff --git a/test/files/jvm5/typerep.scala b/test/files/jvm5/typerep.scala
deleted file mode 100644
index 98782b3..0000000
--- a/test/files/jvm5/typerep.scala
+++ /dev/null
@@ -1,383 +0,0 @@
-//############################################################################
-// Type Representation at runtime
-//############################################################################
-// $Id:  $
-
-import TypeRep._
-
-object Test extends Application {
-  testPrimitives
-  testOptions
-  testLists
-  testArrays
-  testTuples
-  testFuncs
-  testClasses
-}
-
-object serialize {
-  import java.io._
-
-  @throws(classOf[IOException])
-  def write[A](o: A): Array[Byte] = {
-    val ba = new ByteArrayOutputStream(512)
-    val out = new ObjectOutputStream(ba)
-    out.writeObject(o)
-    out.close()
-    ba.toByteArray()
-  }
-  @throws(classOf[IOException])
-  @throws(classOf[ClassNotFoundException])
-  def read[A](buffer: Array[Byte]): A = {
-    val in =
-      new ObjectInputStream(new ByteArrayInputStream(buffer))
-    in.readObject().asInstanceOf[A]
-  }
-}
-
-object testPrimitives {
-  println(getType(true))
-  val b = false; val bt = getType(b)
-  println(bt)
-  val bt1: TypeRep[Boolean] = serialize.read(serialize.write(bt))
-  println(bt1 == bt)
-  println(getType(16.toByte))
-  println(getType('a'))
-  println(getType(3))
-  println(getType(3l))
-  println(getType(0.0f))
-  println(getType(0.0d))
-  println(getType("abc"))
-  println(getType(())) // Unit
-  println(getType(classOf[Int])) // Class
-  println
-}
-
-object testOptions {
-  println(getType(Some(2)))
-  val x: Option[Int] = Some(2)
-  println(getType(x))
-  println(getType(Some(Some(3))))
-  println(getType(Some(List(3))))
-  //println(getType(Some(None)))  // error: no implicit argument matching parameter type TypeRep[object None] was foun
-  println(getType(None))
-  val y: Option[Int] = None
-  println(getType(y))
-  println
-}
-
-object testLists {
-  println(getType(List(3)))
-  println(getType(3 :: Nil))
-  println(getType(List(List(3))))
-  println(getType(Nil))
-  println(getType(List(1, "abc")))
-  println
-}
-
-object testArrays {
-  println(getType(Array(3)))
-  println(getType(Array(Array(3), Array(4))))
-  println(getType(new Array[Int](0)))
-  println(getType(List(1).toArray))
-  println(getType(List[Int]().toArray))
-  println(getType(Array(3).drop(1).toArray)) // empty
-  println
-}
-
-object testTuples {
-  println(getType((3, "abc")))
-  println(getType(Triple('a', 'b', "c")))
-  println(getType(((3, "abc"), (4, "xyz"))))
-  println(getType(((Some('b'), 3), (Some('a'), 4))))
-  //println(getType(((Some('b'), 3), (None, 4))))
-  println
-}
-
-object testFuncs {
-  def f1(x: Int): Int = 2 * x
-  println(getType(f1 _))
-  println(getType(f1(2)))
-  val f2 = (x: Int) => 2 * x
-  println(getType(f2))
-  println(getType(f2(2)))
-  val f3 = (x: Int) => (y: Int) => x + y
-  println(getType(f3))
-  println(getType(f3(2)))
-  println(getType(f3(2)(2)))
-  def f4(b: Boolean, c: List[Char], i: Int): Int = i
-  println(getType(f4 _))
-  def f5(f: Int => Int, x: Int) = f(x)
-  println(getType(f5 _))
-  println(getType(f5(f1, 1)))
-  println  
-}
-
-class Foo {
-  class Bar(x: Int)
-}
-
-
-object foo extends Foo
-
-package pkg1 {
-  class C1
-  object c1 extends C1
-}
-
-object testClasses {
-  /*
-  case object FooRep extends TypeRep[Foo] {
-    override def toString = "Foo"
-  }
-  implicit def fooRep[A](x: A)(implicit rep: TypeRep[foo.type]): TypeRep[foo.type] = rep
-  println(getType(foo))
-  println(getType(new foo.Bar(0)))
-  val foo2 = new Foo
-  println(getType(foo2))
-  println(getType(new foo2.Bar(1)))
-  println
-
-  println(getType(pkg1.c1))
-  val c1 = new pkg1.C1
-  println(getType(c1))
-  println
-  */
-}
-
-
-/**
- *  @author Stephane Micheloud
- *  @version 1.0
- */
-abstract class TypeRep[A]
-
-object TypeRep {
-
-  def getType[A](x: A)(implicit rep: TypeRep[A]): TypeRep[A] = rep
-
-  def getType[A](x: Option[A])(implicit rep: TypeRep[A]): TypeRep[Option[A]] = (x match {
-    case Some(v) => SomeRep(rep)
-    case None    => NoneRep
-  }).asInstanceOf[TypeRep[Option[A]]]
-
-  def getType[A](x: List[A])(implicit rep: TypeRep[A]): TypeRep[List[A]] = (x match {
-    case h :: t => ListRep(getType(h))
-    case Nil    => NilRep
-  }).asInstanceOf[TypeRep[List[A]]]
-
-  implicit def boolRep: TypeRep[Boolean] = BooleanRep
-  implicit def byteRep: TypeRep[Byte] = ByteRep
-  implicit def charRep: TypeRep[Char] = CharRep
-  implicit def shortRep: TypeRep[Short] = ShortRep
-  implicit def intRep: TypeRep[Int] = IntRep
-  implicit def longRep: TypeRep[Long] = LongRep
-  implicit def floatRep: TypeRep[Float] = FloatRep
-  implicit def doubleRep: TypeRep[Double] = DoubleRep
-
-  implicit def unitRep: TypeRep[Unit] = UnitRep
-  implicit def stringRep: TypeRep[String] = StringRep
-  //implicit def noneRep: TypeRep[None.type] = NoneRep//[Nothing](NothingRep.asInstanceOf[TypeRep[Nothing]])
-  implicit def anyRep: TypeRep[Any] = AnyRep
-  implicit def nothingRep: TypeRep[Nothing] = NothingRep
-
-  implicit def classRep[A](implicit elemrep: TypeRep[A]): TypeRep[Class[A]] =
-    ClassRep(elemrep)
-
-  implicit def someRep[A](implicit elemrep: TypeRep[A]): TypeRep[Some[A]] =
-    SomeRep(elemrep)
-
-  implicit def listRep[A](implicit elemrep: TypeRep[A]): TypeRep[List[A]] =
-    ListRep(elemrep)
-
-  implicit def arrayRep[A](implicit elemrep: TypeRep[A]): TypeRep[Array[A]] =
-    ArrayRep(elemrep)
-
-  implicit def tuple2Rep[A1, A2](implicit _1: TypeRep[A1], _2: TypeRep[A2]): TypeRep[(A1, A2)] =
-    Tuple2Rep(_1, _2)
-
-  implicit def tuple3Rep[A1, A2, A3](implicit _1: TypeRep[A1], _2: TypeRep[A2], _3: TypeRep[A3]): TypeRep[(A1, A2, A3)] =
-    Tuple3Rep(_1, _2, _3)
-  implicit def tuple4Rep[A1, A2, A3, A4](implicit _1: TypeRep[A1], _2: TypeRep[A2], _3: TypeRep[A3], _4: TypeRep[A4]): TypeRep[Tuple4[A1, A2, A3, A4]] =
-    Tuple4Rep(_1, _2, _3, _4)
-  implicit def tuple5Rep[A1, A2, A3, A4, A5](implicit _1: TypeRep[A1], _2: TypeRep[A2], _3: TypeRep[A3], _4: TypeRep[A4], _5: TypeRep[A5]): TypeRep[Tuple5[A1, A2, A3, A4, A5]] =
-    Tuple5Rep(_1, _2, _3, _4, _5)
-  implicit def tuple6Rep[A1, A2, A3, A4, A5, A6](implicit _1: TypeRep[A1], _2: TypeRep[A2], _3: TypeRep[A3], _4: TypeRep[A4], _5: TypeRep[A5], _6: TypeRep[A6]): TypeRep[Tuple6[A1, A2, A3, A4, A5, A6]] =
-    Tuple6Rep(_1, _2, _3, _4, _5, _6)
-  implicit def tuple7Rep[A1, A2, A3, A4, A5, A6, A7](implicit _1: TypeRep[A1], _2: TypeRep[A2], _3: TypeRep[A3], _4: TypeRep[A4], _5: TypeRep[A5], _6: TypeRep[A6], _7: TypeRep[A7]): TypeRep[Tuple7[A1, A2, A3, A4, A5, A6, A7]] =
-    Tuple7Rep(_1, _2, _3, _4, _5, _6, _7)
-  implicit def tuple8Rep[A1, A2, A3, A4, A5, A6, A7, A8](implicit _1: TypeRep[A1], _2: TypeRep[A2], _3: TypeRep[A3], _4: TypeRep[A4], _5: TypeRep[A5], _6: TypeRep[A6], _7: TypeRep[A7], _8: TypeRep[A8]): TypeRep[Tuple8[A1, A2, A3, A4, A5, A6, A7, A8]] =
-    Tuple8Rep(_1, _2, _3, _4, _5, _6, _7, _8)
-  implicit def tuple9Rep[A1, A2, A3, A4, A5, A6, A7, A8, A9](implicit _1: TypeRep[A1], _2: TypeRep[A2], _3: TypeRep[A3], _4: TypeRep[A4], _5: TypeRep[A5], _6: TypeRep[A6], _7: TypeRep[A7], _8: TypeRep[A8], _9: TypeRep[A9]): TypeRep[Tuple9[A1, A2, A3, A4, A5, A6, A7, A8, A9]] =
-    Tuple9Rep(_1, _2, _3, _4, _5, _6, _7, _8, _9)
-
-  implicit def func1Rep[A1, B](implicit a1: TypeRep[A1], b: TypeRep[B]): TypeRep[Function1[A1, B]] =
-    Function1Rep(a1, b)
-  implicit def func2Rep[A1, A2, B](implicit a1: TypeRep[A1], a2: TypeRep[A2], b: TypeRep[B]): TypeRep[Function2[A1, A2, B]] =
-    Function2Rep(a1, a2, b)
-  implicit def func3Rep[A1, A2, A3, B](implicit a1: TypeRep[A1], a2: TypeRep[A2], a3: TypeRep[A3], b: TypeRep[B]): TypeRep[Function3[A1, A2, A3, B]] =
-    Function3Rep(a1, a2, a3, b)
-  implicit def func4Rep[A1, A2, A3, A4, B](implicit a1: TypeRep[A1], a2: TypeRep[A2], a3: TypeRep[A3], a4: TypeRep[A4], b: TypeRep[B]): TypeRep[Function4[A1, A2, A3, A4, B]] =
-    Function4Rep(a1, a2, a3, a4, b)
-  implicit def func5Rep[A1, A2, A3, A4, A5, B](implicit a1: TypeRep[A1], a2: TypeRep[A2], a3: TypeRep[A3], a4: TypeRep[A4], a5: TypeRep[A5], b: TypeRep[B]): TypeRep[Function5[A1, A2, A3, A4, A5, B]] =
-    Function5Rep(a1, a2, a3, a4, a5, b)
-  implicit def func6Rep[A1, A2, A3, A4, A5, A6, B](implicit a1: TypeRep[A1], a2: TypeRep[A2], a3: TypeRep[A3], a4: TypeRep[A4], a5: TypeRep[A5], a6: TypeRep[A6], b: TypeRep[B]): TypeRep[Function6[A1, A2, A3, A4, A5, A6, B]] =
-    Function6Rep(a1, a2, a3, a4, a5, a6, b)
-  implicit def func7Rep[A1, A2, A3, A4, A5, A6, A7, B](implicit a1: TypeRep[A1], a2: TypeRep[A2], a3: TypeRep[A3], a4: TypeRep[A4], a5: TypeRep[A5], a6: TypeRep[A6], a7: TypeRep[A7], b: TypeRep[B]): TypeRep[Function7[A1, A2, A3, A4, A5, A6, A7, B]] =
-    Function7Rep(a1, a2, a3, a4, a5, a6, a7, b)
-  implicit def func8Rep[A1, A2, A3, A4, A5, A6, A7, A8, B](implicit a1: TypeRep[A1], a2: TypeRep[A2], a3: TypeRep[A3], a4: TypeRep[A4], a5: TypeRep[A5], a6: TypeRep[A6], a7: TypeRep[A7], a8: TypeRep[A8], b: TypeRep[B]): TypeRep[Function8[A1, A2, A3, A4, A5, A6, A7, A8, B]] =
-    Function8Rep(a1, a2, a3, a4, a5, a6, a7, a8, b)
-  implicit def func9Rep[A1, A2, A3, A4, A5, A6, A7, A8, A9, B](implicit a1: TypeRep[A1], a2: TypeRep[A2], a3: TypeRep[A3], a4: TypeRep[A4], a5: TypeRep[A5], a6: TypeRep[A6], a7: TypeRep[A7], a8: TypeRep[A8], a9: TypeRep[A9], b: TypeRep[B]): TypeRep[Function9[A1, A2, A3, A4, A5, A6, A7, A8, A9, B]] =
-    Function9Rep(a1, a2, a3, a4, a5, a6, a7, a8, a9, b)
-/*
-  implicit def objectRep[A <: AnyRef](obj: A)(implicit rep: TypeRep[A]): TypeRep[AnyClass] =
-    ObjectRep(obj.getClass)
-*/
-
-  case object BooleanRep extends TypeRep[Boolean] {
-    override def toString = "Boolean"
-  }
-  case object ByteRep extends TypeRep[Byte] {
-    override def toString = "Byte"
-  }
-  case object CharRep extends TypeRep[Char] {
-    override def toString = "Char"
-  }
-  case object ShortRep extends TypeRep[Short] {
-    override def toString = "Short"
-  }
-  case object IntRep extends TypeRep[Int] {
-    override def toString = "Int"
-  }
-  case object LongRep extends TypeRep[Long] {
-    override def toString = "Long"
-  }
-  case object FloatRep extends TypeRep[Float] {
-    override def toString = "Float"
-  }
-  case object DoubleRep extends TypeRep[Double] {
-    override def toString = "Double"
-  }
-
-  case object UnitRep extends TypeRep[Unit] {
-    override def toString = "Unit"
-  }
-//  case object ClassRep extends TypeRep[AnyClass] {
-//    override def toString = "Class"
-//  }
-  case object StringRep extends TypeRep[String] {
-    override def toString = "String"
-  }
-  case object NoneRep extends TypeRep[None.type] {
-    override def toString = "None"
-  }
-  case object NilRep extends TypeRep[Nil.type] {
-    override def toString = "Nil"
-  }
-  case object AnyRep extends TypeRep[Any] {
-    override def toString = "Any"
-  }
-  case object NothingRep extends TypeRep[Nothing] {
-    override def toString = "Nothing"
-  }
-
-  @serializable
-  case class ClassRep[A](elemRep: TypeRep[A]) extends TypeRep[Class[A]] {
-    override def toString = "Class[" + elemRep + "]"
-  }
-  @serializable
-  case class SomeRep[A](elemRep: TypeRep[A]) extends TypeRep[Some[A]] {
-    override def toString = "Some[" + elemRep + "]"
-  }
-  @serializable
-  case class NoneRep[A](elemRep: TypeRep[A]) extends TypeRep[Option[A]] {
-    override def toString = "None[" + elemRep + "]"
-  }
-
-  @serializable
-  case class ListRep[A](elemRep: TypeRep[A]) extends TypeRep[List[A]] {
-    override def toString = "List[" + elemRep + "]"
-  }
-
-  @serializable
-  case class ArrayRep[A](elemRep: TypeRep[A]) extends TypeRep[Array[A]] {
-    override def toString = "Array[" + elemRep + "]"
-  }
-
-  @serializable
-  case class Tuple2Rep[A1, A2](_1: TypeRep[A1], _2: TypeRep[A2]) extends TypeRep[(A1, A2)] {
-    override def toString = "Tuple2[" + _1 + ", " + _2 + "]"
-  }
-  @serializable
-  case class Tuple3Rep[A1, A2, A3](_1: TypeRep[A1], _2: TypeRep[A2], _3: TypeRep[A3]) extends TypeRep[Tuple3[A1, A2, A3]] {
-    override def toString = "Tuple3[" + _1 + ", " + _2 + ", " + _3 + "]"
-  }
-  @serializable
-  case class Tuple4Rep[A1, A2, A3, A4](_1: TypeRep[A1], _2: TypeRep[A2], _3: TypeRep[A3], _4: TypeRep[A4]) extends TypeRep[Tuple4[A1, A2, A3, A4]] {
-    override def toString = "Tuple4[" + _1 + ", " + _2 + ", " + _3 + ", " + _4 + "]"
-  }
-  @serializable
-  case class Tuple5Rep[A1, A2, A3, A4, A5](_1: TypeRep[A1], _2: TypeRep[A2], _3: TypeRep[A3], _4: TypeRep[A4], _5: TypeRep[A5]) extends TypeRep[Tuple5[A1, A2, A3, A4, A5]] {
-    override def toString = "Tuple5[" + _1 + ", " + _2 + ", " + _3 + ", " + _4 + ", " + _5 + "]"
-  }
-  @serializable
-  case class Tuple6Rep[A1, A2, A3, A4, A5, A6](val _1: TypeRep[A1], val _2: TypeRep[A2], val _3: TypeRep[A3], val _4: TypeRep[A4], val _5: TypeRep[A5], val _6: TypeRep[A6]) extends TypeRep[Tuple6[A1, A2, A3, A4, A5, A6]] {
-    override def toString = "Tuple6[" + _1 + ", " + _2 + ", " + _3 + ", " + _4 + ", " + _5 + ", " + _6 + "]"
-  }
-  @serializable
-  case class Tuple7Rep[A1, A2, A3, A4, A5, A6, A7](val _1: TypeRep[A1], val _2: TypeRep[A2], val _3: TypeRep[A3], val _4: TypeRep[A4], val _5: TypeRep[A5], val _6: TypeRep[A6], val _7: TypeRep[A7]) extends TypeRep[Tuple7[A1, A2, A3, A4, A5, A6, A7]] {
-    override def toString = "Tuple7[" + _1 + ", " + _2 + ", " + _3 + ", " + _4 + ", " + _5 + ", " + _6 + ", " + _7 + "]"
-  }
-  @serializable
-  case class Tuple8Rep[A1, A2, A3, A4, A5, A6, A7, A8](val _1: TypeRep[A1], val _2: TypeRep[A2], val _3: TypeRep[A3], val _4: TypeRep[A4], val _5: TypeRep[A5], val _6: TypeRep[A6], val _7: TypeRep[A7], val _8: TypeRep[A8]) extends TypeRep[Tuple8[A1, A2, A3, A4, A5, A6, A7, A8]] {
-    override def toString = "Tuple8[" + _1 + ", " + _2 + ", " + _3 + ", " + _4 + ", " + _5 + ", " + _6 + ", " + _7 + ", " + _8 + "]"
-  }
-  @serializable
-  case class Tuple9Rep[A1, A2, A3, A4, A5, A6, A7, A8, A9](val _1: TypeRep[A1], val _2: TypeRep[A2], val _3: TypeRep[A3], val _4: TypeRep[A4], val _5: TypeRep[A5], val _6: TypeRep[A6], val _7: TypeRep[A7], val _8: TypeRep[A8], val _9: TypeRep[A9]) extends TypeRep[Tuple9[A1, A2, A3, A4, A5, A6, A7, A8, A9]] {
-    override def toString = "Tuple9[" + _1 + ", " + _2 + ", " + _3 + ", " + _4 + ", " + _5 + ", " + _6 + ", " + _7 + ", " + _8 + ", " + _9 + "]"
-  }
-
-  @serializable
-  case class Function1Rep[A1, B](a1: TypeRep[A1], b: TypeRep[B]) extends TypeRep[Function1[A1, B]] {
-    override def toString = "Function1[" + a1 + ", " + b + "]"
-  }
-  @serializable
-  case class Function2Rep[A1, A2, B](a1: TypeRep[A1], a2: TypeRep[A2], b: TypeRep[B]) extends TypeRep[Function2[A1, A2, B]] {
-    override def toString = "Function2[" + a1 + ", " + a2 + ", " + b + "]"
-  }
-  @serializable
-  case class Function3Rep[A1, A2, A3, B](a1: TypeRep[A1], a2: TypeRep[A2], a3: TypeRep[A3], b: TypeRep[B]) extends TypeRep[Function3[A1, A2, A3, B]] {
-    override def toString = "Function3[" + a1 + ", " + a2 + ", " + a3 + ", " + b + "]"
-  }
-  @serializable
-  case class Function4Rep[A1, A2, A3, A4, B](a1: TypeRep[A1], a2: TypeRep[A2], a3: TypeRep[A3], a4: TypeRep[A4], b: TypeRep[B]) extends TypeRep[Function4[A1, A2, A3, A4, B]] {
-    override def toString = "Function4[" + a1 + ", " + a2 + ", " + a3 + ", " + a4 + ", " + b + "]"
-  }
-  @serializable
-  case class Function5Rep[A1, A2, A3, A4, A5, B](a1: TypeRep[A1], a2: TypeRep[A2], a3: TypeRep[A3], a4: TypeRep[A4], a5: TypeRep[A5], b: TypeRep[B]) extends TypeRep[Function5[A1, A2, A3, A4, A5, B]] {
-    override def toString = "Function5[" + a1 + ", " + a2 + ", " + a3 + ", " + a4 + ", " + a5 + ", " + b + "]"
-  }
-  @serializable
-  case class Function6Rep[A1, A2, A3, A4, A5, A6, B](a1: TypeRep[A1], a2: TypeRep[A2], a3: TypeRep[A3], a4: TypeRep[A4], a5: TypeRep[A5], a6: TypeRep[A6], b: TypeRep[B]) extends TypeRep[Function6[A1, A2, A3, A4, A5, A6, B]] {
-    override def toString = "Function6[" + a1 + ", " + a2 + ", " + a3 + ", " + a4 + ", " + a5 + ", " + a6 + ", " + b + "]"
-  }
-  @serializable
-  case class Function7Rep[A1, A2, A3, A4, A5, A6, A7, B](a1: TypeRep[A1], a2: TypeRep[A2], a3: TypeRep[A3], a4: TypeRep[A4], a5: TypeRep[A5], a6: TypeRep[A6], a7: TypeRep[A7], b: TypeRep[B]) extends TypeRep[Function7[A1, A2, A3, A4, A5, A6, A7, B]] {
-    override def toString = "Function7[" + a1 + ", " + a2 + ", " + a3 + ", " + a4 + ", " + a5 + ", " + a6 + ", " + a7 + ", " + b + "]"
-  }
-  @serializable
-  case class Function8Rep[A1, A2, A3, A4, A5, A6, A7, A8, B](a1: TypeRep[A1], a2: TypeRep[A2], a3: TypeRep[A3], a4: TypeRep[A4], a5: TypeRep[A5], a6: TypeRep[A6], a7: TypeRep[A7], a8: TypeRep[A8], b: TypeRep[B]) extends TypeRep[Function8[A1, A2, A3, A4, A5, A6, A7, A8, B]] {
-    override def toString = "Function8[" + a1 + ", " + a2 + ", " + a3 + ", " + a4 + ", " + a5 + ", " + a6 + ", " + a7 + ", " + a8 + b + "]"
-  }
-  @serializable
-  case class Function9Rep[A1, A2, A3, A4, A5, A6, A7, A8, A9, B](a1: TypeRep[A1], a2: TypeRep[A2], a3: TypeRep[A3], a4: TypeRep[A4], a5: TypeRep[A5], a6: TypeRep[A6], a7: TypeRep[A7], a8: TypeRep[A8], a9: TypeRep[A9], b: TypeRep[B]) extends TypeRep[Function9[A1, A2, A3, A4, A5, A6, A7, A8, A9, B]] {
-    override def toString = "Function9[" + a1 + ", " + a2 + ", " + a3 + ", " + a4 + ", " + a5 + ", " + a6 + ", " + a7 + ", " + a8 + ", " + b + "]"
-  }
-/*
-  @serializable
-  case class ObjectRep[A](c: Class) extends TypeRep[A] {
-    override def toString = c.getName
-  }
-*/
-}
-
diff --git a/test/files/lib/ScalaCheck.jar b/test/files/lib/ScalaCheck.jar
deleted file mode 100644
index 4789417..0000000
Binary files a/test/files/lib/ScalaCheck.jar and /dev/null differ
diff --git a/test/files/lib/scalacheck.jar b/test/files/lib/scalacheck.jar
new file mode 100644
index 0000000..be3243a
Binary files /dev/null and b/test/files/lib/scalacheck.jar differ
diff --git a/test/files/neg/abstract-vars.check b/test/files/neg/abstract-vars.check
new file mode 100644
index 0000000..8aa4774
--- /dev/null
+++ b/test/files/neg/abstract-vars.check
@@ -0,0 +1,21 @@
+abstract-vars.scala:5: error: class Fail1 needs to be abstract, since variable x is not defined
+(Note that variables need to be initialized to be defined)
+class Fail1 extends A {
+      ^
+abstract-vars.scala:9: error: class Fail2 needs to be abstract, since variable x in class A of type Int is not defined
+(Note that variables need to be initialized to be defined)
+class Fail2 extends A { }
+      ^
+abstract-vars.scala:11: error: class Fail3 needs to be abstract, since variable x in class A of type Int is not defined
+(Note that an abstract var requires a setter in addition to the getter)
+class Fail3 extends A {
+      ^
+abstract-vars.scala:14: error: class Fail4 needs to be abstract, since variable x in class A of type Int is not defined
+(Note that an abstract var requires a setter in addition to the getter)
+class Fail4 extends A {
+      ^
+abstract-vars.scala:18: error: class Fail5 needs to be abstract, since variable x in class A of type Int is not defined
+(Note that an abstract var requires a getter in addition to the setter)
+class Fail5 extends A {
+      ^
+5 errors found
diff --git a/test/files/neg/abstract-vars.scala b/test/files/neg/abstract-vars.scala
new file mode 100644
index 0000000..df6109d
--- /dev/null
+++ b/test/files/neg/abstract-vars.scala
@@ -0,0 +1,29 @@
+abstract class A {
+  var x: Int
+}
+
+class Fail1 extends A {
+  var x: Int
+}
+
+class Fail2 extends A { }
+
+class Fail3 extends A {
+  val x: Int = 5
+}
+class Fail4 extends A {
+  def x: Int = 5
+}
+
+class Fail5 extends A {
+  def x_=(y: Int) = ()
+}
+
+class Success1 extends A {
+  val x: Int = 5
+  def x_=(y: Int) = ()
+}
+
+class Success2 extends A {
+  var x: Int = 5
+}
diff --git a/test/files/neg/abstract.check b/test/files/neg/abstract.check
index b735391..811708c 100644
--- a/test/files/neg/abstract.check
+++ b/test/files/neg/abstract.check
@@ -2,10 +2,10 @@ abstract.scala:6: error: type mismatch;
  found   : A
  required: A.this.T
   def foo2: T = bar().baz();
-                      ^
+                         ^
 abstract.scala:9: error: type mismatch;
  found   : A
  required: A.this.T
   def foo5: T = baz().baz();
-                      ^
+                         ^
 two errors found
diff --git a/test/files/neg/accesses.check b/test/files/neg/accesses.check
index 627c17d..94fcd61 100644
--- a/test/files/neg/accesses.check
+++ b/test/files/neg/accesses.check
@@ -1,16 +1,16 @@
-accesses.scala:23: error: error overriding method f2 in class A of type => Unit;
+accesses.scala:23: error: overriding method f2 in class A of type => Unit;
  method f2 has weaker access privileges; it should not be private
   private def f2: Unit = ()
               ^
-accesses.scala:24: error: error overriding method f3 in class A of type => Unit;
+accesses.scala:24: error: overriding method f3 in class A of type => Unit;
  method f3 has weaker access privileges; it should be at least protected
   private[p2] def f3: Unit = ()
                   ^
-accesses.scala:25: error: error overriding method f4 in class A of type => Unit;
+accesses.scala:25: error: overriding method f4 in class A of type => Unit;
  method f4 has weaker access privileges; it should be at least private[p1]
   private[p2] def f4: Unit
                   ^
-accesses.scala:26: error: error overriding method f5 in class A of type => Unit;
+accesses.scala:26: error: overriding method f5 in class A of type => Unit;
  method f5 has weaker access privileges; it should be at least protected[p1]
   protected[p2] def f5: Unit
                     ^
diff --git a/test/files/neg/annot-nonconst.check b/test/files/neg/annot-nonconst.check
index ef1a72a..23429bb 100644
--- a/test/files/neg/annot-nonconst.check
+++ b/test/files/neg/annot-nonconst.check
@@ -1,10 +1,18 @@
 annot-nonconst.scala:1: warning: implementation restriction: subclassing Classfile does not
 make your annotation visible at runtime.  If that is what
 you want, you must write the annotation class in Java.
-class Length(n: Int) extends ClassfileAnnotation
+class Length(value: Int) extends ClassfileAnnotation
       ^
-annot-nonconst.scala:5: error: attribute argument needs to be a constant; found: Test.this.n
+annot-nonconst.scala:2: warning: implementation restriction: subclassing Classfile does not
+make your annotation visible at runtime.  If that is what
+you want, you must write the annotation class in Java.
+class Ann2(value: String) extends ClassfileAnnotation
+      ^
+annot-nonconst.scala:6: error: annotation argument needs to be a constant; found: n
   @Length(n) def foo = "foo"
           ^
-one warning found
-one error found
+annot-nonconst.scala:7: error: annotation argument needs to be a constant; found: null
+  @Ann2(null) def bar = "bar"
+        ^
+two warnings found
+two errors found
diff --git a/test/files/neg/annot-nonconst.scala b/test/files/neg/annot-nonconst.scala
index 5a0b72a..69bb60d 100644
--- a/test/files/neg/annot-nonconst.scala
+++ b/test/files/neg/annot-nonconst.scala
@@ -1,6 +1,8 @@
-class Length(n: Int) extends ClassfileAnnotation
+class Length(value: Int) extends ClassfileAnnotation
+class Ann2(value: String) extends ClassfileAnnotation
 
 object Test {
   def n = 15
   @Length(n) def foo = "foo"
+  @Ann2(null) def bar = "bar"
 }
diff --git a/test/files/neg/array-not-seq.check b/test/files/neg/array-not-seq.check
new file mode 100644
index 0000000..c16ecda
--- /dev/null
+++ b/test/files/neg/array-not-seq.check
@@ -0,0 +1,7 @@
+array-not-seq.scala:2: error: An Array will no longer match as Seq[_].
+  def f1(x: Any) = x.isInstanceOf[Seq[_]]
+                                 ^
+error: An Array will no longer match as Seq[_].
+error: An Array will no longer match as Seq[_].
+error: An Array will no longer match as Seq[_].
+four errors found
diff --git a/test/files/neg/array-not-seq.flags b/test/files/neg/array-not-seq.flags
new file mode 100644
index 0000000..4e9f7e4
--- /dev/null
+++ b/test/files/neg/array-not-seq.flags
@@ -0,0 +1 @@
+-Xmigration -Xfatal-warnings
\ No newline at end of file
diff --git a/test/files/neg/array-not-seq.scala b/test/files/neg/array-not-seq.scala
new file mode 100644
index 0000000..5f367bd
--- /dev/null
+++ b/test/files/neg/array-not-seq.scala
@@ -0,0 +1,26 @@
+object Test {
+  def f1(x: Any) = x.isInstanceOf[Seq[_]]
+  def f2(x: Any) = x match {
+    case _: Seq[_]  => true
+    case _          => false
+  }
+
+  def f3(x: Any) = x match {
+    case _: Array[_]  => true
+    case _            => false
+  }
+  
+  def f4(x: Any) = x.isInstanceOf[Traversable[_]]
+  
+  def f5(x1: Any, x2: Any, x3: AnyRef) = (x1, x2, x3) match {
+    case (Some(_: Seq[_]), Nil, _)        => 1
+    case (None, List(_: List[_], _), _)   => 2
+    case _                                => 3
+  }
+
+  def main(args: Array[String]): Unit = {
+    // println(f1(Array(1)))
+    // println(f2(Array(1)))
+    // println(f3(Array(1))
+  }
+}
diff --git a/test/files/neg/badtok-1.check b/test/files/neg/badtok-1.check
index 94116d3..b05bc60 100644
--- a/test/files/neg/badtok-1.check
+++ b/test/files/neg/badtok-1.check
@@ -1,7 +1,7 @@
-badtok-1.scala:2: error: missing terminating quote
+badtok-1.scala:2: error: unclosed character literal
 '42'
 ^
-badtok-1.scala:2: error: unterminated character literal
+badtok-1.scala:2: error: unclosed character literal
 '42'
    ^
 two errors found
diff --git a/test/files/neg/badtok-1.scala b/test/files/neg/badtok-1.scala
index 739ea20..706e794 100644
--- a/test/files/neg/badtok-1.scala
+++ b/test/files/neg/badtok-1.scala
@@ -1,2 +1,2 @@
 // bug 989
-'42'
\ No newline at end of file
+'42'
diff --git a/test/files/neg/badtok-2.check b/test/files/neg/badtok-2.check
index 6364b85..e6861c2 100644
--- a/test/files/neg/badtok-2.check
+++ b/test/files/neg/badtok-2.check
@@ -1,7 +1,4 @@
-badtok-2.scala:3: error: unterminated quoted identifier
+badtok-2.scala:3: error: unclosed quoted identifier
 `x
 ^
-badtok-2.scala:3: error: '}' expected but eof found.
-`x
- ^
-two errors found
+one error found
diff --git a/test/files/neg/badtok-2.scala b/test/files/neg/badtok-2.scala
index 2074abe..4d1ba1b 100644
--- a/test/files/neg/badtok-2.scala
+++ b/test/files/neg/badtok-2.scala
@@ -1,3 +1,3 @@
 //bug 990
 object Test {
-`x
\ No newline at end of file
+`x
diff --git a/test/files/neg/badtok-3.check b/test/files/neg/badtok-3.check
new file mode 100644
index 0000000..aee4f6f
--- /dev/null
+++ b/test/files/neg/badtok-3.check
@@ -0,0 +1,4 @@
+badtok-3.scala:2: error: input ended while parsing XML
+  <x
+    ^
+one error found
diff --git a/test/files/neg/badtok-3.scala b/test/files/neg/badtok-3.scala
new file mode 100644
index 0000000..49ad3bf
--- /dev/null
+++ b/test/files/neg/badtok-3.scala
@@ -0,0 +1,2 @@
+object Test {
+  <x
diff --git a/test/files/neg/bug1038.check b/test/files/neg/bug1038.check
new file mode 100644
index 0000000..e09cbbc
--- /dev/null
+++ b/test/files/neg/bug1038.check
@@ -0,0 +1,5 @@
+bug1038.scala:4: error: not enough arguments for constructor X: (x: Int)X.
+Unspecified value parameter x.
+  val a = new X
+          ^
+one error found
diff --git a/test/files/neg/bug1038.scala b/test/files/neg/bug1038.scala
new file mode 100644
index 0000000..9fdcae2
--- /dev/null
+++ b/test/files/neg/bug1038.scala
@@ -0,0 +1,8 @@
+class X(x : Int)
+
+object Y {
+  val a = new X
+  import a._
+  implicit val b : Int = 1
+  implicit val c = 2
+}
\ No newline at end of file
diff --git a/test/files/neg/bug1106.scala b/test/files/neg/bug1106.scala
index 36b5a0e..a218eee 100644
--- a/test/files/neg/bug1106.scala
+++ b/test/files/neg/bug1106.scala
@@ -2,4 +2,4 @@ class Par[S]
 val p = new Par[String]
 class Foo[T[x]<:Par[x]](t: T[String])
 
-new Foo[p.type](p) // crashes compiler
\ No newline at end of file
+new Foo[p.type](p) // crashes compiler
diff --git a/test/files/neg/bug1112.check b/test/files/neg/bug1112.check
index 779aa90..d94dba9 100644
--- a/test/files/neg/bug1112.check
+++ b/test/files/neg/bug1112.check
@@ -1,4 +1,4 @@
-bug1112.scala:12: error: wrong number of arguments for method call: (Int)(=> () => Unit)Unit
+bug1112.scala:12: error: too many arguments for method call: (p: Int)(f: => () => Unit)Unit
     call(0,() => System.out.println("here we are"))
-    ^
+        ^
 one error found
diff --git a/test/files/neg/bug112706A.check b/test/files/neg/bug112706A.check
new file mode 100644
index 0000000..8fb5bfc
--- /dev/null
+++ b/test/files/neg/bug112706A.check
@@ -0,0 +1,6 @@
+bug112706A.scala:5: error: constructor cannot be instantiated to expected type;
+ found   : (T1, T2)
+ required: java.lang.String
+    case Tuple2(node,_) =>   
+         ^
+one error found
diff --git a/test/files/neg/bug112706A.scala b/test/files/neg/bug112706A.scala
new file mode 100644
index 0000000..b7799af
--- /dev/null
+++ b/test/files/neg/bug112706A.scala
@@ -0,0 +1,8 @@
+package test;
+trait Test {
+  def foo(p : List[Tuple2[String,String]]) = {
+    for (t <- p) t._1 match {
+    case Tuple2(node,_) =>   
+    }
+  }
+}
diff --git a/test/files/neg/bug1181.check b/test/files/neg/bug1181.check
index 0baf975..38045ed 100644
--- a/test/files/neg/bug1181.check
+++ b/test/files/neg/bug1181.check
@@ -1,4 +1,4 @@
-bug1181.scala:9: error: not a legal formal parameter
+bug1181.scala:9: error: missing parameter type
      _ => buildMap(map.update(keyList.head, valueList.head), keyList.tail, valueList.tail)
      ^
 one error found
diff --git a/test/files/neg/bug1275.check b/test/files/neg/bug1275.check
index 9f806c0..6ee8365 100644
--- a/test/files/neg/bug1275.check
+++ b/test/files/neg/bug1275.check
@@ -1,4 +1,6 @@
-bug1275.scala:13: error: The kind of type MyType does not conform to the expected kind of type MyType[+t] <: TestCovariance.Seq[t] in trait Seq.
-    def span[a, s <: Seq[a] { type MyType <: s } ](xs: s): s = xs f
-                                   ^
+bug1275.scala:11: error: type mismatch;
+ found   : xs.MyType[a]
+ required: s
+     = xs f
+          ^
 one error found
diff --git a/test/files/neg/bug1275.scala b/test/files/neg/bug1275.scala
index 7b9b044..1175b30 100644
--- a/test/files/neg/bug1275.scala
+++ b/test/files/neg/bug1275.scala
@@ -1,14 +1,15 @@
-// tested using Scala compiler version 2.6.0-RC1 -- (c) 2002-2009 LAMP/EPFL
-
-// prompted by "Covariant return types" mailing list question
-object TestCovariance {
-
-    // see  Type constructor polymorphism  in  http://www.scala-lang.org/docu/changelog.html
-    trait Seq[+t] {
-        type MyType[+t] <: Seq[t]
-
-        def f: MyType[t]
-    }
-
-    def span[a, s <: Seq[a] { type MyType <: s } ](xs: s): s = xs f
-}
+object Test {
+  trait Seq[+t] {
+    type MyType[+t] <: Seq[t]
+
+    def f: MyType[t]
+  }
+
+  // illegal abstract type member refinement: changes the arity of MyType
+  // the error is pretty strange, since the compiler forms the illegal type xs.MyType[a] anyway
+  def span[a, s <: Seq[a] { type MyType/*look ma, no type parameters!*/ <: s } ](xs: s): s
+     = xs f
+//        ^
+// found   : xs.MyType[a]
+// required: s
+}
\ No newline at end of file
diff --git a/test/files/neg/bug1279a.check b/test/files/neg/bug1279a.check
deleted file mode 100644
index edfd1fe..0000000
--- a/test/files/neg/bug1279a.check
+++ /dev/null
@@ -1,6 +0,0 @@
-bug1279a.scala:34: error: type mismatch;
- found   : first.selfType
- required: M{type T <: this.T}
-   def all4Impl[U](first: M {type T <: U}): Stream[M {type T <: U}] = Stream.cons(first, all4Impl(first.next))
-                                                                                                        ^
-one error found
diff --git a/test/files/neg/bug1279a.scala b/test/files/neg/bug1279a.scala
deleted file mode 100644
index 7568d3a..0000000
--- a/test/files/neg/bug1279a.scala
+++ /dev/null
@@ -1,38 +0,0 @@
-// providing the type parameter in the recursive call to all4Impl
-// avoids the problem
-
-
-// covariant linked list
-abstract class M
-{ self =>
-
-    type T
-    final type selfType = M {type T <: self.T}
-    type actualSelfType >: self.type <: selfType
-
-    def next: selfType
-
-
-    // I don't understand why this doesn't compile, but that's a separate matter
-    // error: method all2 cannot be accessed in M.this.selfType
-    // because its instance type => Stream[M{type T <: M.this.selfType#T}]
-    // contains a malformed type: M.this.selfType#T
-    // def all2: Stream[M {type T <: self.T}] = Stream.cons(self: actualSelfType, next.all2)
-
-
-    // compiles successfully
-    // def all3: Stream[M {type T <: self.T}] = all3Impl(self: actualSelfType)
-    // private def all3Impl(first: M {type T <: self.T}): Stream[M {type T <: self.T}] = Stream.cons(first, all3Impl(first.next))
-
-
-
-    def all4: Stream[M {type T <: self.T}] = Unrelated.all4Impl[T](self: actualSelfType)
-}
-
-object Unrelated
-{
-   def all4Impl[U](first: M {type T <: U}): Stream[M {type T <: U}] = Stream.cons(first, all4Impl(first.next))
-
-// compiles successfully
-//      def all4Impl[U](first: M {type T <: U}): Stream[M {type T <: U}] = Stream.cons(first, all4Impl[U](first.next))
-}
diff --git a/test/files/neg/bug1286.check b/test/files/neg/bug1286.check
new file mode 100644
index 0000000..9bf6325
--- /dev/null
+++ b/test/files/neg/bug1286.check
@@ -0,0 +1,2 @@
+error: fatal error: Companions 'object Foo' and 'trait Foo' must be defined in same file.
+one error found
diff --git a/test/files/neg/bug1286/a.scala b/test/files/neg/bug1286/a.scala
new file mode 100644
index 0000000..85ffe3b
--- /dev/null
+++ b/test/files/neg/bug1286/a.scala
@@ -0,0 +1,3 @@
+trait Foo {
+  def jump = Foo.x
+}
diff --git a/test/files/neg/bug1286/b.scala b/test/files/neg/bug1286/b.scala
new file mode 100644
index 0000000..48f3b44
--- /dev/null
+++ b/test/files/neg/bug1286/b.scala
@@ -0,0 +1,3 @@
+object Foo extends Foo {
+  val x = "x"
+}
diff --git a/test/files/neg/bug1333.check b/test/files/neg/bug1333.check
new file mode 100644
index 0000000..11ba633
--- /dev/null
+++ b/test/files/neg/bug1333.check
@@ -0,0 +1,4 @@
+bug1333.scala:1: error: case classes limited by implementation: maximum of 2 constructor parameter lists.
+case class A(a: Int)(b: Int)(c: Int)
+           ^
+one error found
diff --git a/test/files/neg/bug1333.scala b/test/files/neg/bug1333.scala
new file mode 100644
index 0000000..e16b38c
--- /dev/null
+++ b/test/files/neg/bug1333.scala
@@ -0,0 +1 @@
+case class A(a: Int)(b: Int)(c: Int)
diff --git a/test/files/neg/bug1523.check b/test/files/neg/bug1523.check
new file mode 100644
index 0000000..96d052f
--- /dev/null
+++ b/test/files/neg/bug1523.check
@@ -0,0 +1,4 @@
+bug1523.scala:4: error: too many arguments for method bug: (x: Any)Any
+  def go() = bug("a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a")
+                ^
+one error found
diff --git a/test/files/neg/bug1523.scala b/test/files/neg/bug1523.scala
new file mode 100644
index 0000000..b8754f4
--- /dev/null
+++ b/test/files/neg/bug1523.scala
@@ -0,0 +1,5 @@
+object test {  
+  def bug(x: Any) = x
+  
+  def go() = bug("a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a")
+}
diff --git a/test/files/neg/bug1623.check b/test/files/neg/bug1623.check
new file mode 100644
index 0000000..cfc2b53
--- /dev/null
+++ b/test/files/neg/bug1623.check
@@ -0,0 +1,4 @@
+bug1623.scala:11: error: class BImpl cannot be instantiated because it does not conform to its self-type test.BImpl with test.A
+  val b = new BImpl
+          ^
+one error found
diff --git a/test/files/neg/bug1623.scala b/test/files/neg/bug1623.scala
new file mode 100644
index 0000000..d4bd6f4
--- /dev/null
+++ b/test/files/neg/bug1623.scala
@@ -0,0 +1,12 @@
+package test
+
+trait A 
+trait B 
+
+class BImpl extends B {
+  this: A =>
+}
+
+object Test2 extends Application {
+  val b = new BImpl
+}
diff --git a/test/files/neg/bug1838.check b/test/files/neg/bug1838.check
new file mode 100644
index 0000000..0c08bfe
--- /dev/null
+++ b/test/files/neg/bug1838.check
@@ -0,0 +1,7 @@
+bug1838.scala:6: error: `sealed' modifier can be used only for classes
+  sealed val v = 0
+             ^
+bug1838.scala:5: error: `sealed' modifier can be used only for classes
+  sealed def f = 0
+             ^
+two errors found
diff --git a/test/files/neg/bug1838.scala b/test/files/neg/bug1838.scala
new file mode 100644
index 0000000..36eeb40
--- /dev/null
+++ b/test/files/neg/bug1838.scala
@@ -0,0 +1,7 @@
+package test
+
+class A {
+  sealed class B
+  sealed def f = 0
+  sealed val v = 0
+}
diff --git a/test/files/neg/bug1878.check b/test/files/neg/bug1878.check
new file mode 100644
index 0000000..f760781
--- /dev/null
+++ b/test/files/neg/bug1878.check
@@ -0,0 +1,15 @@
+bug1878.scala:3: error: _* may only come last
+  val err1 = "" match { case Seq(f @ _*, ',') => f }
+                                 ^
+bug1878.scala:3: error: scrutinee is incompatible with pattern type;
+ found   : Seq[A]
+ required: java.lang.String
+  val err1 = "" match { case Seq(f @ _*, ',') => f }
+                                ^
+bug1878.scala:9: error: _* may only come last
+  val List(List(_*, arg2), _) = List(List(1,2,3), List(4,5,6))
+                 ^
+bug1878.scala:13: error: _* may only come last
+    case <p> { _* } </p> =>
+                ^
+four errors found
diff --git a/test/files/neg/bug1878.scala b/test/files/neg/bug1878.scala
new file mode 100644
index 0000000..32d5ce5
--- /dev/null
+++ b/test/files/neg/bug1878.scala
@@ -0,0 +1,15 @@
+object Test extends Application {
+  // illegal 
+  val err1 = "" match { case Seq(f @ _*, ',') => f }
+  
+  // no error
+  val List(List(arg1, _*), _) = List(List(1,2,3), List(4,5,6))
+  
+  // illegal
+  val List(List(_*, arg2), _) = List(List(1,2,3), List(4,5,6))
+  
+  // illegal - bug #1764
+  null match {
+    case <p> { _* } </p> =>
+  }
+}
diff --git a/test/files/neg/bug1909b.check b/test/files/neg/bug1909b.check
new file mode 100644
index 0000000..e5de5fe
--- /dev/null
+++ b/test/files/neg/bug1909b.check
@@ -0,0 +1,4 @@
+bug1909b.scala:4: error: this can be used only in a class, object, or template
+    def bar() = this.z + 5
+                ^
+one error found
diff --git a/test/files/neg/bug1909b.scala b/test/files/neg/bug1909b.scala
new file mode 100644
index 0000000..6aa7870
--- /dev/null
+++ b/test/files/neg/bug1909b.scala
@@ -0,0 +1,7 @@
+class Ticket1909 (x: Int) {
+  var z = 12
+  def this() = this({
+    def bar() = this.z + 5
+    bar
+  })
+}
\ No newline at end of file
diff --git a/test/files/neg/bug1960.check b/test/files/neg/bug1960.check
new file mode 100644
index 0000000..6615d90
--- /dev/null
+++ b/test/files/neg/bug1960.check
@@ -0,0 +1,4 @@
+bug1960.scala:5: error: parameter 'p' requires field but conflicts with p in 'TBase'
+class Aclass (p: Int) extends TBase { def g{ f(p) } }
+              ^
+one error found
diff --git a/test/files/neg/bug1960.scala b/test/files/neg/bug1960.scala
new file mode 100644
index 0000000..b381e9d
--- /dev/null
+++ b/test/files/neg/bug1960.scala
@@ -0,0 +1,5 @@
+object ClassFormatErrorExample extends Application { new Aclass(1) }
+
+trait TBase { var p:Int = 0; def f(p1: Int) {} }
+
+class Aclass (p: Int) extends TBase { def g{ f(p) } }
diff --git a/test/files/neg/bug2102.check b/test/files/neg/bug2102.check
new file mode 100644
index 0000000..075aa85
--- /dev/null
+++ b/test/files/neg/bug2102.check
@@ -0,0 +1,6 @@
+bug2102.scala:2: error: type mismatch;
+ found   : java.util.Iterator[Int]
+ required: scala.Iterator[_]
+  val x: Iterator[_] = new java.util.ArrayList[Int]().iterator
+                                                      ^
+one error found
diff --git a/test/files/neg/bug2102.scala b/test/files/neg/bug2102.scala
new file mode 100644
index 0000000..9c37039
--- /dev/null
+++ b/test/files/neg/bug2102.scala
@@ -0,0 +1,3 @@
+object Test {
+  val x: Iterator[_] = new java.util.ArrayList[Int]().iterator
+}
diff --git a/test/files/neg/bug2144.check b/test/files/neg/bug2144.check
new file mode 100644
index 0000000..989bddc
--- /dev/null
+++ b/test/files/neg/bug2144.check
@@ -0,0 +1,4 @@
+bug2144.scala:2: error: Parameter type in structural refinement may not refer to an abstract type defined outside that refinement
+  def foo[A](a: A) = new { def bar(x: A): A = x }
+                               ^
+one error found
diff --git a/test/files/neg/bug2144.scala b/test/files/neg/bug2144.scala
new file mode 100644
index 0000000..af9a5e1
--- /dev/null
+++ b/test/files/neg/bug2144.scala
@@ -0,0 +1,3 @@
+object Test {
+  def foo[A](a: A) = new { def bar(x: A): A = x }
+}
diff --git a/test/files/neg/bug2148.check b/test/files/neg/bug2148.check
new file mode 100644
index 0000000..22be424
--- /dev/null
+++ b/test/files/neg/bug2148.check
@@ -0,0 +1,4 @@
+bug2148.scala:9: error: type A is not a stable prefix
+  val b = new A with A#A1
+                       ^
+one error found
diff --git a/test/files/neg/bug2148.scala b/test/files/neg/bug2148.scala
new file mode 100644
index 0000000..c0521d9
--- /dev/null
+++ b/test/files/neg/bug2148.scala
@@ -0,0 +1,10 @@
+class A { 
+  var i = 0
+  trait A1 extends A { 
+    i += 1
+  }
+}
+
+object Bob {
+  val b = new A with A#A1
+}
\ No newline at end of file
diff --git a/test/files/neg/bug2206.check b/test/files/neg/bug2206.check
new file mode 100644
index 0000000..3deb4d9
--- /dev/null
+++ b/test/files/neg/bug2206.check
@@ -0,0 +1,5 @@
+bug2206.scala:10: error: value f is not a member of o.A
+ Note: implicit method ax is not applicable here because it comes after the application point and it lacks an explicit result type
+  a.f()
+    ^
+one error found
diff --git a/test/files/neg/bug2206.scala b/test/files/neg/bug2206.scala
new file mode 100644
index 0000000..cd2ec22
--- /dev/null
+++ b/test/files/neg/bug2206.scala
@@ -0,0 +1,15 @@
+object o {
+  class A
+
+  class AX {
+      def f() { }
+  }
+
+  import Implicits._
+  val a = new A
+  a.f()
+
+  object Implicits {
+      implicit def ax(a: A) = new AX
+  }
+}
\ No newline at end of file
diff --git a/test/files/neg/bug2213.check b/test/files/neg/bug2213.check
new file mode 100644
index 0000000..b24f7dc
--- /dev/null
+++ b/test/files/neg/bug2213.check
@@ -0,0 +1,15 @@
+bug2213.scala:9: error: class C needs to be abstract, since:
+value y in class A of type Int is not defined
+value x in class A of type Int is not defined
+method g in class A of type => Int is not defined
+method f in class A of type => Int is not defined
+class C extends A {}
+      ^
+bug2213.scala:11: error: object creation impossible, since:
+value y in class A of type Int is not defined
+value x in class A of type Int is not defined
+method g in class A of type => Int is not defined
+method f in class A of type => Int is not defined
+object Q extends A { }
+       ^
+two errors found
diff --git a/test/files/neg/bug2213.scala b/test/files/neg/bug2213.scala
new file mode 100644
index 0000000..af1df3c
--- /dev/null
+++ b/test/files/neg/bug2213.scala
@@ -0,0 +1,11 @@
+abstract class A {
+  def f: Int
+  def g: Int
+
+  val x: Int
+  val y: Int
+}
+
+class C extends A {}
+
+object Q extends A { }
\ No newline at end of file
diff --git a/test/files/neg/bug2275a.check b/test/files/neg/bug2275a.check
new file mode 100644
index 0000000..892a903
--- /dev/null
+++ b/test/files/neg/bug2275a.check
@@ -0,0 +1,13 @@
+bug2275a.scala:4: error: in XML literal: in XML content, please use '}}' to express '}'
+  }else{
+  ^
+bug2275a.scala:3: error:  I encountered a '}' where I didn't expect one, maybe this tag isn't closed <br>
+    <br>
+     ^
+bug2275a.scala:4: error: ';' expected but 'else' found.
+  }else{
+   ^
+bug2275a.scala:7: error: '}' expected but eof found.
+}
+ ^
+four errors found
diff --git a/test/files/neg/bug2275a.scala b/test/files/neg/bug2275a.scala
new file mode 100644
index 0000000..7f2b803
--- /dev/null
+++ b/test/files/neg/bug2275a.scala
@@ -0,0 +1,7 @@
+object Test {
+  if(true) {
+    <br>
+  }else{
+    <span>{"louenesee"}</span>
+  }
+}
diff --git a/test/files/neg/bug2275b.check b/test/files/neg/bug2275b.check
new file mode 100644
index 0000000..4b61f24
--- /dev/null
+++ b/test/files/neg/bug2275b.check
@@ -0,0 +1,13 @@
+bug2275b.scala:2: error: in XML literal: in XML content, please use '}}' to express '}'
+  {<br>}xx
+       ^
+bug2275b.scala:2: error:  I encountered a '}' where I didn't expect one, maybe this tag isn't closed <br>
+  {<br>}xx
+    ^
+bug2275b.scala:2: error: ';' expected but identifier found.
+  {<br>}xx
+        ^
+bug2275b.scala:3: error: '}' expected but eof found.
+}
+ ^
+four errors found
diff --git a/test/files/neg/bug2275b.scala b/test/files/neg/bug2275b.scala
new file mode 100644
index 0000000..312cba8
--- /dev/null
+++ b/test/files/neg/bug2275b.scala
@@ -0,0 +1,3 @@
+object Test {
+  {<br>}xx
+}
diff --git a/test/files/neg/bug276.check b/test/files/neg/bug276.check
new file mode 100644
index 0000000..edc4ec5
--- /dev/null
+++ b/test/files/neg/bug276.check
@@ -0,0 +1,5 @@
+bug276.scala:6: error: overriding type Bar in class Foo, which equals (Int, Int);
+ class Bar cannot be used here - classes and objects can only override abstract types
+  class Bar
+        ^
+one error found
diff --git a/test/files/neg/bug276.scala b/test/files/neg/bug276.scala
new file mode 100644
index 0000000..dfc8b46
--- /dev/null
+++ b/test/files/neg/bug276.scala
@@ -0,0 +1,7 @@
+class Foo {
+  type Bar = (Int, Int)
+}
+
+class FooFoo extends Foo {
+  class Bar
+}
diff --git a/test/files/neg/bug278.check b/test/files/neg/bug278.check
new file mode 100644
index 0000000..ad0a973
--- /dev/null
+++ b/test/files/neg/bug278.check
@@ -0,0 +1,10 @@
+bug278.scala:5: error: overloaded method value a with alternatives:
+  => (C.this.A) => Unit <and>
+  => () => Unit
+ does not take type parameters
+  a[A]
+  ^
+bug278.scala:4: error: method a is defined twice
+  def a = (p:A) => ()
+      ^
+two errors found
diff --git a/test/files/neg/bug278.scala b/test/files/neg/bug278.scala
new file mode 100644
index 0000000..16ffe10
--- /dev/null
+++ b/test/files/neg/bug278.scala
@@ -0,0 +1,6 @@
+class C {
+  class A
+  def a = () => ()
+  def a = (p:A) => ()
+  a[A]
+}
diff --git a/test/files/neg/bug284.check b/test/files/neg/bug284.check
new file mode 100644
index 0000000..821727b
--- /dev/null
+++ b/test/files/neg/bug284.check
@@ -0,0 +1,8 @@
+bug284.scala:2: warning: Detected apparent refinement of Unit; are you missing an '=' sign?
+    def f1(a: T): Unit { }
+                       ^
+bug284.scala:5: error: Unmatched closing brace '}' ignored here
+  }
+  ^
+one warning found
+one error found
diff --git a/test/files/neg/bug284.scala b/test/files/neg/bug284.scala
new file mode 100644
index 0000000..a210130
--- /dev/null
+++ b/test/files/neg/bug284.scala
@@ -0,0 +1,6 @@
+trait B[T] {
+    def f1(a: T): Unit { }
+    def f2(a: T): Unit
+    def f3(a: T) { }
+  }
+}
diff --git a/test/files/neg/bug3209.check b/test/files/neg/bug3209.check
new file mode 100644
index 0000000..fa50f4c
--- /dev/null
+++ b/test/files/neg/bug3209.check
@@ -0,0 +1,4 @@
+bug3209.scala:2: error: expected start of definition
+package test
+^
+one error found
diff --git a/test/files/neg/bug3209.scala b/test/files/neg/bug3209.scala
new file mode 100644
index 0000000..d893726
--- /dev/null
+++ b/test/files/neg/bug3209.scala
@@ -0,0 +1,2 @@
+ at javax.annotation.Generated(Array("test"))
+package test
\ No newline at end of file
diff --git a/test/files/neg/bug3631.check b/test/files/neg/bug3631.check
new file mode 100644
index 0000000..12d94aa
--- /dev/null
+++ b/test/files/neg/bug3631.check
@@ -0,0 +1,4 @@
+bug3631.scala:3: error: Implementation restriction: case classes cannot have more than 22 parameters.
+case class X23(x1: Int, x2: Int, x3: Int, x4: Int, x5: Int, x6: Int, x7: Int, x8: Int, x9: Int, x10: Int, x11: Int, x12: Int, x13: Int, x14: Int, x15: Int, x16: Int, x17: Int, x18: Int, x19: Int, x20: Int, x21: Int, x22: Int, x23: Int) { }
+           ^
+one error found
diff --git a/test/files/neg/bug3631.scala b/test/files/neg/bug3631.scala
new file mode 100644
index 0000000..bcf9161
--- /dev/null
+++ b/test/files/neg/bug3631.scala
@@ -0,0 +1,3 @@
+case class X22(x1: Int, x2: Int, x3: Int, x4: Int, x5: Int, x6: Int, x7: Int, x8: Int, x9: Int, x10: Int, x11: Int, x12: Int, x13: Int, x14: Int, x15: Int, x16: Int, x17: Int, x18: Int, x19: Int, x20: Int, x21: Int, x22: Int) { }
+
+case class X23(x1: Int, x2: Int, x3: Int, x4: Int, x5: Int, x6: Int, x7: Int, x8: Int, x9: Int, x10: Int, x11: Int, x12: Int, x13: Int, x14: Int, x15: Int, x16: Int, x17: Int, x18: Int, x19: Int, x20: Int, x21: Int, x22: Int, x23: Int) { }
\ No newline at end of file
diff --git a/test/files/neg/bug414.check b/test/files/neg/bug414.check
index c0f039a..ec23e26 100644
--- a/test/files/neg/bug414.check
+++ b/test/files/neg/bug414.check
@@ -1,7 +1,3 @@
-bug414.scala:1: warning: case classes without a parameter list have been deprecated;
-use either case objects or case classes with `()' as parameter list.
-case class Empty[a] extends IntMap[a];
-                    ^
 bug414.scala:5: error: pattern type is incompatible with expected type;
  found   : object Empty
  required: IntMap[a]
@@ -12,5 +8,4 @@ bug414.scala:7: error: type mismatch;
  required: a
                 case _ =>
                        ^
-one warning found
 two errors found
diff --git a/test/files/neg/bug414.scala b/test/files/neg/bug414.scala
index 7983fe8..2bc83ee 100644
--- a/test/files/neg/bug414.scala
+++ b/test/files/neg/bug414.scala
@@ -1,4 +1,4 @@
-case class Empty[a] extends IntMap[a];
+case class Empty[a]() extends IntMap[a];
 case class Node[a](left: IntMap[a], keyVal: Pair[Int, a], right: IntMap[a]) extends IntMap[a];
 abstract class IntMap[a] {
         def lookup(key: Int): a = this match {
diff --git a/test/files/neg/bug421.check b/test/files/neg/bug421.check
index 8cf29fa..71daba2 100644
--- a/test/files/neg/bug421.check
+++ b/test/files/neg/bug421.check
@@ -1,5 +1,4 @@
-bug421.scala:5: error: no regular expression pattern allowed here
-(regular expression patterns are only allowed in arguments to *-parameters)
+bug421.scala:5: error: star patterns must correspond with varargs parameters
     case Bar("foo",_*) => error("huh?");
                     ^
 one error found
diff --git a/test/files/neg/bug473.check b/test/files/neg/bug473.check
new file mode 100644
index 0000000..7d21dfb
--- /dev/null
+++ b/test/files/neg/bug473.check
@@ -0,0 +1,4 @@
+bug473.scala:3: error: super constructor cannot be passed a self reference unless parameter is declared by-name
+case object Voop extends Foo(Voop)
+                 ^
+one error found
diff --git a/test/files/neg/bug473.scala b/test/files/neg/bug473.scala
new file mode 100644
index 0000000..c763170
--- /dev/null
+++ b/test/files/neg/bug473.scala
@@ -0,0 +1,3 @@
+class Foo(x: Foo)
+case object Bar extends Foo(null)
+case object Voop extends Foo(Voop)
diff --git a/test/files/neg/bug520.check b/test/files/neg/bug520.check
index 6768ebb..258f811 100644
--- a/test/files/neg/bug520.check
+++ b/test/files/neg/bug520.check
@@ -1,4 +1,4 @@
 bug520.scala:8: error: overloaded method verifyKeyword needs result type
       verifyKeyword("", source, pos);
-      ^
+                   ^
 one error found
diff --git a/test/files/neg/bug521.check b/test/files/neg/bug521.check
index b85e266..d8e9268 100644
--- a/test/files/neg/bug521.check
+++ b/test/files/neg/bug521.check
@@ -1,15 +1,15 @@
 bug521.scala:10: error: class PlainFile needs to be abstract, since method path in class AbstractFile of type => String is not defined
 class PlainFile(val file : File) extends AbstractFile {}
       ^
-bug521.scala:13: error: error overriding value file in class PlainFile of type java.io.File;
+bug521.scala:13: error: overriding value file in class PlainFile of type java.io.File;
  value file needs `override' modifier
 final class ZipArchive(val file : File, archive : ZipFile) extends PlainFile(file) {
                            ^
 bug521.scala:13: error: class ZipArchive needs to be abstract, since method path in class AbstractFile of type => String is not defined
 final class ZipArchive(val file : File, archive : ZipFile) extends PlainFile(file) {
             ^
-bug521.scala:15: error: error overriding value path in class VirtualFile of type String;
- method path is not stable
+bug521.scala:15: error: overriding value path in class VirtualFile of type String;
+ method path needs to be a stable, immutable value
     override def path = "";
                  ^
 four errors found
diff --git a/test/files/neg/bug545.scala b/test/files/neg/bug545.scala
index 4063b71..f1f9909 100644
--- a/test/files/neg/bug545.scala
+++ b/test/files/neg/bug545.scala
@@ -6,4 +6,4 @@ object Test {
     case Nil => null
     case _ => throw new Error("too many!")
   }
-}
\ No newline at end of file
+}
diff --git a/test/files/neg/bug550.check b/test/files/neg/bug550.check
index 8f1a5c0..e1650b7 100644
--- a/test/files/neg/bug550.check
+++ b/test/files/neg/bug550.check
@@ -1,7 +1,7 @@
-bug550.scala:6: error: class List takes type parameters
+bug550.scala:6: error: type List takes type parameters
   def sum[a](xs: List)(implicit m: Monoid[a]): a =
                  ^
-bug550.scala:8: error: no implicit argument matching parameter type Monoid[Nothing] was found.
+bug550.scala:8: error: could not find implicit value for parameter m: Monoid[a]
   sum(List(1,2,3))
-  ^
+     ^
 two errors found
diff --git a/test/files/neg/bug555.check b/test/files/neg/bug555.check
deleted file mode 100644
index e72714d..0000000
--- a/test/files/neg/bug555.check
+++ /dev/null
@@ -1,4 +0,0 @@
-bug555.scala:4: error: block must end in result expression, not in definition
-  }
-  ^
-one error found
diff --git a/test/files/neg/bug555.scala b/test/files/neg/bug555.scala
deleted file mode 100644
index 26dbe6c..0000000
--- a/test/files/neg/bug555.scala
+++ /dev/null
@@ -1,5 +0,0 @@
-object Main extends Application {
-  def tata = {
-    def titi = {}
-  }
-}
diff --git a/test/files/neg/bug563.scala b/test/files/neg/bug563.scala
index 927773d..3261491 100644
--- a/test/files/neg/bug563.scala
+++ b/test/files/neg/bug563.scala
@@ -1,7 +1,7 @@
 object Test {
     def map[A,R](a : List[A], f : A => R) : List[R] = a.map(f);
     
-    def split(sn : Iterable[List[Cell[int]]]) : unit =
-        for (val n <- sn)
+    def split(sn : Iterable[List[Cell[Int]]]) : Unit =
+        for (n <- sn)
             map(n,ptr => new Cell(ptr.elem));
 }
diff --git a/test/files/neg/bug576.check b/test/files/neg/bug576.check
index 72d5d25..b496cca 100644
--- a/test/files/neg/bug576.check
+++ b/test/files/neg/bug576.check
@@ -1,4 +1,4 @@
 bug576.scala:14: error: overloaded method insert needs result type
       if (true) sibling.insert(node);
-                        ^
+                              ^
 one error found
diff --git a/test/files/neg/bug585.check b/test/files/neg/bug585.check
index af66898..4f4c5bf 100644
--- a/test/files/neg/bug585.check
+++ b/test/files/neg/bug585.check
@@ -1,4 +1,4 @@
-bug585.scala:1: error: unterminated comment
+bug585.scala:1: error: unclosed comment
 /*
 ^
 one error found
diff --git a/test/files/neg/bug588.check b/test/files/neg/bug588.check
index f4129d6..5f55c95 100644
--- a/test/files/neg/bug588.check
+++ b/test/files/neg/bug588.check
@@ -1,13 +1,13 @@
 bug588.scala:3: error: double definition:
-method visit:((Int) => String)Boolean and
-method visit:((Int) => unit)Boolean at line 2
-have same type after erasure: (Function1)Boolean
+method visit:(f: (Int) => String)Boolean and
+method visit:(f: (Int) => Unit)Boolean at line 2
+have same type after erasure: (f: Function1)Boolean
   def visit(f: Int => String): Boolean
       ^
 bug588.scala:10: error: double definition:
-method f:(Test.this.TypeB)Unit and
-method f:(Test.this.TypeA)Unit at line 9
-have same type after erasure: (Test#TraitA)Unit
+method f:(brac: Test.this.TypeB)Unit and
+method f:(node: Test.this.TypeA)Unit at line 9
+have same type after erasure: (brac: Test#TraitA)Unit
   def f(brac : TypeB) : Unit;
       ^
 two errors found
diff --git a/test/files/neg/bug588.scala b/test/files/neg/bug588.scala
index 9b9e9c5..1bc6d26 100644
--- a/test/files/neg/bug588.scala
+++ b/test/files/neg/bug588.scala
@@ -1,5 +1,5 @@
 abstract class Test0 {
-  def visit(f: Int => unit): Boolean  
+  def visit(f: Int => Unit): Boolean  
   def visit(f: Int => String): Boolean
 }
 trait Test {
diff --git a/test/files/neg/bug608.check b/test/files/neg/bug608.check
index 8337c51..a8e32e4 100644
--- a/test/files/neg/bug608.check
+++ b/test/files/neg/bug608.check
@@ -1,6 +1,6 @@
 bug608.scala:16: error: type mismatch;
- found   : (a) => a
- required: (_1.a) => ? where val _1: hs{type s = hs; type a = ha}
-	     = g(f(x).bimap(id))
-                            ^
+ found   : hs{type a = ha}
+ required: hs{type s = hs; type a = ha}
+       = g(f(x).bimap(id))
+                     ^
 one error found
diff --git a/test/files/neg/bug608.scala b/test/files/neg/bug608.scala
index f683039..1f12764 100644
--- a/test/files/neg/bug608.scala
+++ b/test/files/neg/bug608.scala
@@ -1,17 +1,17 @@
 trait CrashDueToTypeError {
-	def id[a](x :a) :a = x
+  def id[a](x :a) :a = x
 
-	trait Bifunctor {
-		type a; //	 content 
-		type s <: Bifunctor
+  trait Bifunctor {
+    type a; //   content 
+    type s <: Bifunctor
 
-		// uncomment        this-vvvvvvvvvvvvvvvvvvvvvvvvvvvv, and it compiles 
-		def bimap[c](f :a=>c) :s{/*type s=Bifunctor.this.s;*/type a=c; }
-	}
+    // uncomment        this-vvvvvvvvvvvvvvvvvvvvvvvvvvvv, and it compiles
+    def bimap[c](f :a=>c) :s{/*type s=Bifunctor.this.s;*/type a=c; }
+  }
 
-	def hylo[hs <: Bifunctor,ha,hb,hc]
-	    (f :hb=>hs{type s=hs; type a=ha}, 
-	     g :hs{type s=hs; type a=ha}=>hc)(x :hb) 
-	     :hc 
-	     = g(f(x).bimap(id))
+  def hylo[hs <: Bifunctor,ha,hb,hc]
+      (f :hb=>hs{type s=hs; type a=ha},
+       g :hs{type s=hs; type a=ha}=>hc)(x :hb)
+       :hc
+       = g(f(x).bimap(id))
 }
diff --git a/test/files/neg/bug630.check b/test/files/neg/bug630.check
index 03113be..739d214 100644
--- a/test/files/neg/bug630.check
+++ b/test/files/neg/bug630.check
@@ -1,5 +1,5 @@
-bug630.scala:20: error: error overriding value foo in trait Bar of type Req2;
- object foo has incompatible type object Test.foo
+bug630.scala:20: error: overriding value foo in trait Bar of type Req2;
+ object foo has incompatible type
         object foo extends Req1
                ^
 one error found
diff --git a/test/files/neg/bug649.check b/test/files/neg/bug649.check
index dd5b6a1..2a1533d 100644
--- a/test/files/neg/bug649.check
+++ b/test/files/neg/bug649.check
@@ -1,4 +1,4 @@
 bug649.scala:3: error: overloaded method foo needs result type
   def foo[A] = foo[A]
-               ^
+                  ^
 one error found
diff --git a/test/files/neg/bug663.check b/test/files/neg/bug663.check
index d1ef2ae..6ae7198 100644
--- a/test/files/neg/bug663.check
+++ b/test/files/neg/bug663.check
@@ -1,7 +1,7 @@
 bug663.scala:11: error: name clash between defined and inherited member:
-method asMatch:(Test.this.Node)Any and
-method asMatch:(Test.this.Matchable)Any in trait MatchableImpl
-have same type after erasure: (test.Test#NodeImpl)java.lang.Object
+method asMatch:(m: Test.this.Node)Any and
+method asMatch:(node: Test.this.Matchable)Any in trait MatchableImpl
+have same type after erasure: (m: test.Test#NodeImpl)java.lang.Object
     def asMatch(m : Node) : Any = {
         ^
 one error found
diff --git a/test/files/neg/bug668.check b/test/files/neg/bug668.check
index 698cef6..10be0c8 100644
--- a/test/files/neg/bug668.check
+++ b/test/files/neg/bug668.check
@@ -1,4 +1,4 @@
-bug668.scala:1: error: trait Iterable takes type parameters
+bug668.scala:1: error: type Iterable takes type parameters
 class Test extends Iterable
                    ^
 one error found
diff --git a/test/files/neg/bug691.check b/test/files/neg/bug691.check
index f811fc3..47ac8c3 100644
--- a/test/files/neg/bug691.check
+++ b/test/files/neg/bug691.check
@@ -1,4 +1,4 @@
 bug691.scala:27: error: ambiguous parent class qualifier
     trait TiC extends super[Arrow].Ti2 with super[AssignArrow].Ti1;
-                            ^
+                      ^
 one error found
diff --git a/test/files/neg/bug692.check b/test/files/neg/bug692.check
index 099a261..9e96027 100644
--- a/test/files/neg/bug692.check
+++ b/test/files/neg/bug692.check
@@ -1,19 +1,24 @@
 bug692.scala:3: error: not found: type T
-  trait Type[T0] extends Type0[T];
+  trait Type[T0] extends Type0[T];
                                ^
 bug692.scala:10: error: class Foo takes type parameters
-  case class FooType() extends ClassType[Foo,AnyRef](ObjectType());
+  case class FooType() extends ClassType[Foo,AnyRef](ObjectType());
                                          ^
 bug692.scala:13: error: class Foo takes type parameters
-  case class BarType[T3 <: Foo](tpeT : RefType[T3]) extends ClassType[Bar[T3],Foo](FooType);
+  case class BarType[T3 <: Foo](tpeT : RefType[T3]) extends ClassType[Bar[T3],Foo](FooType);
                                                                               ^
 bug692.scala:13: error: class Foo takes type parameters
-  case class BarType[T3 <: Foo](tpeT : RefType[T3]) extends ClassType[Bar[T3],Foo](FooType);
+  case class BarType[T3 <: Foo](tpeT : RefType[T3]) extends ClassType[Bar[T3],Foo](FooType);
                            ^
-bug692.scala:19: error: class Foo takes type parameters
-  class Bar[A <: Foo](implicit tpeA : Type[A]) extends Foo;
-                 ^
 bug692.scala:14: error: class Foo takes type parameters
-  implicit def typeOfBar[T4 <: Foo](implicit elem : RefType[T4]) : RefType[Bar[T4]] = 
+  implicit def typeOfBar[T4 <: Foo](implicit elem : RefType[T4]) : RefType[Bar[T4]] = 
                                ^
-6 errors found
+bug692.scala:15: error: type mismatch;
+ found   : test3.this.BarType[T4]
+ required: test3.this.RefType[test3.this.Bar[T4]]
+    BarType(elem);
+           ^
+bug692.scala:19: error: class Foo takes type parameters
+  class Bar[A <: Foo](implicit tpeA : Type[A]) extends Foo;
+                 ^
+7 errors found
diff --git a/test/files/neg/bug693.scala b/test/files/neg/bug693.scala
index 36be83b..d2074be 100644
--- a/test/files/neg/bug693.scala
+++ b/test/files/neg/bug693.scala
@@ -2,4 +2,4 @@ abstract class test4 {
   trait Type;
   val x : Type = null;
   val x : Int = 10; 
-}
\ No newline at end of file
+}
diff --git a/test/files/neg/bug696.check b/test/files/neg/bug696.check
index 623c95f..1ca740c 100644
--- a/test/files/neg/bug696.check
+++ b/test/files/neg/bug696.check
@@ -1,5 +1,5 @@
 bug696.scala:4: error: diverging implicit expansion for type TypeUtil0.Type[Any]
 starting with method WithType in object TypeUtil0
   as[Any](null);
-  ^
+         ^
 one error found
diff --git a/test/files/neg/bug700.check b/test/files/neg/bug700.check
index 33a67e5..5c28540 100644
--- a/test/files/neg/bug700.check
+++ b/test/files/neg/bug700.check
@@ -1,4 +1,4 @@
 bug700.scala:6: error: method foobar in trait Foo is accessed from super. It may not be abstract unless it is overridden by a member declared `abstract' and `override'
-  def foobar: unit = super.foobar
+  def foobar: Unit = super.foobar
                            ^
 one error found
diff --git a/test/files/neg/bug700.scala b/test/files/neg/bug700.scala
index 7477bb5..b08c8b5 100644
--- a/test/files/neg/bug700.scala
+++ b/test/files/neg/bug700.scala
@@ -3,7 +3,7 @@ trait Foo {
 }
 
 trait Bar extends Foo {
-  def foobar: unit = super.foobar
+  def foobar: Unit = super.foobar
 }
 
 // the following definition breaks the compiler
diff --git a/test/files/neg/bug708.check b/test/files/neg/bug708.check
index 513709f..cfeb01c 100644
--- a/test/files/neg/bug708.check
+++ b/test/files/neg/bug708.check
@@ -1,5 +1,5 @@
-bug708.scala:8: error: error overriding type S in trait X with bounds >: Nothing <: A.this.T;
- type S has incompatible type Any
+bug708.scala:8: error: overriding type S in trait X with bounds >: Nothing <: A.this.T;
+ type S has incompatible type
     override private[A] type S = Any;
                              ^
 one error found
diff --git a/test/files/neg/bug765.scala b/test/files/neg/bug765.scala
index f1100df..3e5371b 100644
--- a/test/files/neg/bug765.scala
+++ b/test/files/neg/bug765.scala
@@ -1,5 +1,5 @@
 object test {
-  for (val e <- List()) { //required
+  for (e <- List()) { //required
     val bar = new Bar123
     val res = bar.f       //required
     ()
diff --git a/test/files/neg/bug766.scala b/test/files/neg/bug766.scala
index 9829b23..b4b04d9 100644
--- a/test/files/neg/bug766.scala
+++ b/test/files/neg/bug766.scala
@@ -1,7 +1,7 @@
 object B
 {
   def a = {
-    for (val n <- Nil; val m <- Nil) {
+    for (n <- Nil; m <- Nil) {
       val p = badIdentifier
       false
     }
diff --git a/test/files/neg/bug783.check b/test/files/neg/bug783.check
index 19e3ead..bf82edc 100644
--- a/test/files/neg/bug783.check
+++ b/test/files/neg/bug783.check
@@ -2,5 +2,5 @@ bug783.scala:12: error: type mismatch;
  found   : Contexts.this.Global#Template
  required: Contexts.this.global.Template
       globalInit0.Template(10, 20);
-                  ^
+                          ^
 one error found
diff --git a/test/files/neg/bug856.check b/test/files/neg/bug856.check
index e1d0801..168855d 100644
--- a/test/files/neg/bug856.check
+++ b/test/files/neg/bug856.check
@@ -1,4 +1,6 @@
-bug856.scala:3: error: class ComplexRect needs to be abstract, since method _2 in trait Product2 of type => Double is not defined
+bug856.scala:3: error: class ComplexRect needs to be abstract, since:
+method _2 in trait Product2 of type => Double is not defined
+method canEqual in trait Equals of type (that: Any)Boolean is not defined
 class ComplexRect(val _1:Double, _2:Double) extends Complex {
       ^
 one error found
diff --git a/test/files/neg/bug875.check b/test/files/neg/bug875.check
index d547c8d..16a9822 100644
--- a/test/files/neg/bug875.check
+++ b/test/files/neg/bug875.check
@@ -4,8 +4,8 @@ bug875.scala:3: error: no `: _*' annotation allowed here
                            ^
 bug875.scala:6: error: no `: _*' annotation allowed here
 (such annotations are only allowed in arguments to *-parameters)
-  mkList(xs: _*)
-           ^
+  mkList1(xs: _*)
+            ^
 bug875.scala:15: error: no `: _*' annotation allowed here
 (such annotations are only allowed in arguments to *-parameters)
   f(true, 1, xs: _*)
diff --git a/test/files/neg/bug875.scala b/test/files/neg/bug875.scala
index 9c579b0..38affd5 100644
--- a/test/files/neg/bug875.scala
+++ b/test/files/neg/bug875.scala
@@ -1,9 +1,9 @@
 object Test extends Application {
   val xs = List(4, 5, 6)
   val ys = List(1, 2, 3, xs: _*)
-  def mkList(x: Int) = List(x)
-  def mkList(x: Boolean) = List(x)
-  mkList(xs: _*)
+  def mkList1(x: Int) = List(x)
+  def mkList2(x: Boolean) = List(x)
+  mkList1(xs: _*)
 
 
   def f(x: Int*) = List(x: _*)
diff --git a/test/files/neg/bug876.check b/test/files/neg/bug876.check
index 8ef2c03..8552242 100644
--- a/test/files/neg/bug876.check
+++ b/test/files/neg/bug876.check
@@ -1,4 +1,4 @@
-bug876.scala:25: error: wrong number of arguments for method apply: (AssertionError.A)manager.B in trait Map
+bug876.scala:25: error: too many arguments for method apply: (key: AssertionError.A)manager.B in trait MapLike
         assert(manager.map(A2) == List(manager.map(A2, A1)))
-                                               ^
+                                                  ^
 one error found
diff --git a/test/files/neg/bug877.check b/test/files/neg/bug877.check
index e710413..ddd1154 100644
--- a/test/files/neg/bug877.check
+++ b/test/files/neg/bug877.check
@@ -1,7 +1,7 @@
-bug877.scala:3: error: parents of traits may not have parameters
-trait Foo extends A(22A, Bug!) {}
-                   ^
 bug877.scala:3: error: Invalid literal number
 trait Foo extends A(22A, Bug!) {}
                     ^
+bug877.scala:3: error: parents of traits may not have parameters
+trait Foo extends A(22A, Bug!) {}
+                   ^
 two errors found
diff --git a/test/files/neg/bug882.check b/test/files/neg/bug882.check
index 52245eb..4e3e6d0 100644
--- a/test/files/neg/bug882.check
+++ b/test/files/neg/bug882.check
@@ -1,4 +1,4 @@
-bug882.scala:2: error: traits cannot have type parameters with <% bounds
+bug882.scala:2: error: traits cannot have type parameters with context bounds `: ...' nor view bounds `<% ...'
 trait SortedSet[A <% Ordered[A]] {
                                  ^
 one error found
diff --git a/test/files/neg/bug900.check b/test/files/neg/bug900.check
index 3ba577b..6085ffe 100644
--- a/test/files/neg/bug900.check
+++ b/test/files/neg/bug900.check
@@ -2,8 +2,8 @@ bug900.scala:4: error: type mismatch;
  found   : Foo.this.x.type (with underlying type Foo.this.bar)
  required: AnyRef
 Note that implicit conversions are not applicable because they are ambiguous:
- both method any2stringadd in object Predef of type (Any)scala.runtime.StringAdd
- and method any2ArrowAssoc in object Predef of type [A](A)ArrowAssoc[A]
+ both method any2stringadd in object Predef of type (x: Any)scala.runtime.StringAdd
+ and method any2ArrowAssoc in object Predef of type [A](x: A)ArrowAssoc[A]
  are possible conversion functions from Foo.this.x.type to AnyRef
         def break(): x.type
                      ^
diff --git a/test/files/neg/bug910.check b/test/files/neg/bug910.check
index ffb07fa..2bc2d98 100644
--- a/test/files/neg/bug910.check
+++ b/test/files/neg/bug910.check
@@ -1,6 +1,6 @@
 bug910.scala:4: error: type mismatch;
  found   : Seq[Char]
- required: Seq[int]
-    val y: Seq[int] = rest
+ required: scala.Seq[Int]
+    val y: Seq[Int] = rest
                       ^
 one error found
diff --git a/test/files/neg/bug910.scala b/test/files/neg/bug910.scala
index 2f28ea4..540ee70 100644
--- a/test/files/neg/bug910.scala
+++ b/test/files/neg/bug910.scala
@@ -1,7 +1,7 @@
 object RegExpTest1 extends Application {
   def co(x: Seq[Char]) = x match {
     case Seq('s','c','a','l','a', rest @ _*) =>
-    val y: Seq[int] = rest
+    val y: Seq[Int] = rest
         y
   }
 }
diff --git a/test/files/neg/bug935.check b/test/files/neg/bug935.check
new file mode 100644
index 0000000..63b2679
--- /dev/null
+++ b/test/files/neg/bug935.check
@@ -0,0 +1,7 @@
+bug935.scala:5: error: type arguments [Test3.B] do not conform to class E's type parameter bounds [T <: String]
+  @E[B](new B) val b = "hi"
+                   ^
+bug935.scala:11: error: type arguments [Test4.B] do not conform to class E's type parameter bounds [T <: String]
+  val b: String @E[B](new B) = "hi"
+                 ^
+two errors found
diff --git a/test/files/neg/bug935.scala b/test/files/neg/bug935.scala
new file mode 100644
index 0000000..8677efa
--- /dev/null
+++ b/test/files/neg/bug935.scala
@@ -0,0 +1,12 @@
+object Test3 {
+  class E[T >: Nothing <: String](s: T) extends Annotation
+  class B
+  // val a = new E[B](new B)
+  @E[B](new B) val b = "hi"
+}
+
+object Test4 {
+  class E[T <: String](s: T) extends Annotation
+  class B
+  val b: String @E[B](new B) = "hi"
+}
diff --git a/test/files/neg/bug944.check b/test/files/neg/bug944.check
new file mode 100644
index 0000000..d45b968
--- /dev/null
+++ b/test/files/neg/bug944.check
@@ -0,0 +1,4 @@
+bug944.scala:5: error: implementation restricts functions to 22 parameters
+           a23:Int) => 1
+                    ^
+one error found
diff --git a/test/files/neg/bug944.scala b/test/files/neg/bug944.scala
new file mode 100644
index 0000000..352269a
--- /dev/null
+++ b/test/files/neg/bug944.scala
@@ -0,0 +1,6 @@
+object TooManyArgsFunction {
+  val f = (a1:Int, a2:Int, a3:Int, a4:Int, a5:Int, a6:Int, a7:Int, a8:Int, 
+           a9:Int, a10:Int, a11:Int, a12:Int, a13:Int, a14:Int, a15:Int, 
+           a16:Int, a17:Int, a18:Int, a19:Int, a20:Int, a21:Int, a22:Int, 
+           a23:Int) => 1
+}
diff --git a/test/files/neg/bug960.check b/test/files/neg/bug960.check
index e61394f..ebfc3c6 100644
--- a/test/files/neg/bug960.check
+++ b/test/files/neg/bug960.check
@@ -1,6 +1,6 @@
 bug960.scala:18: error: ambiguous reference to overloaded definition,
-both method unapply in object List of type [a](List[a])Option[Null]
-and  method unapply in object List of type [a](List[a])Option[(a, List[a])]
+both method unapply in object List of type [a](xs: List[a])Option[Null]
+and  method unapply in object List of type [a](xs: List[a])Option[(a, List[a])]
 match argument types (List[a])
     case List(x, xs) => 7
          ^
diff --git a/test/files/neg/bug961.check b/test/files/neg/bug961.check
index 33bb055..439ed98 100644
--- a/test/files/neg/bug961.check
+++ b/test/files/neg/bug961.check
@@ -1,9 +1,4 @@
-bug961.scala:4: warning: case classes without a parameter list have been deprecated;
-use either case objects or case classes with `()' as parameter list.
-    private case class B_inner extends A
-                               ^
 bug961.scala:11: error: Temp.this.B of type object Temp.B does not take parameters
-  B() match {
-  ^
-one warning found
+  B() match {
+   ^
 one error found
diff --git a/test/files/neg/bug961.scala b/test/files/neg/bug961.scala
index 15309b9..088bddd 100644
--- a/test/files/neg/bug961.scala
+++ b/test/files/neg/bug961.scala
@@ -1,7 +1,7 @@
-object Temp{
+object Temp {
   abstract class A
-  object B{
-    private case class B_inner extends A
+  object B {
+    private case class B_inner() extends A
     def apply: A = B_inner()
     def unapply(a: A) = a match {
       case B_inner() => true
diff --git a/test/files/neg/bug987.scala b/test/files/neg/bug987.scala
index 0c65b98..5b2addf 100644
--- a/test/files/neg/bug987.scala
+++ b/test/files/neg/bug987.scala
@@ -1,4 +1,4 @@
-// tested using Scala compiler version 2.4.0-RC1 -- (c) 2002-2009 LAMP/EPFL
+// tested using Scala compiler version 2.4.0-RC1 -- (c) 2002-2010 LAMP/EPFL
 
 // Many thanks to all at LAMP for the work that goes into Scala.
 
diff --git a/test/files/neg/bug997.check b/test/files/neg/bug997.check
index e3c86c9..44e3832 100644
--- a/test/files/neg/bug997.check
+++ b/test/files/neg/bug997.check
@@ -1,12 +1,12 @@
 bug997.scala:7: error: wrong number of arguments for object Foo
 "x" match { case Foo(a) => Console.println(a) }
-                 ^
+                    ^
 bug997.scala:7: error: not found: value a
 "x" match { case Foo(a) => Console.println(a) }
                                            ^
 bug997.scala:13: error: wrong number of arguments for object Foo
 "x" match { case Foo(a, b, c) => Console.println((a,b,c)) }
-                 ^
+                    ^
 bug997.scala:13: error: not found: value a
 "x" match { case Foo(a, b, c) => Console.println((a,b,c)) }
                                                   ^
diff --git a/test/files/neg/checksensible.check b/test/files/neg/checksensible.check
index 21d0d81..9d0487f 100644
--- a/test/files/neg/checksensible.check
+++ b/test/files/neg/checksensible.check
@@ -1,50 +1,44 @@
 checksensible.scala:1: error: class Test needs to be abstract, since method isabstract is not defined
 class Test {
       ^
-checksensible.scala:3: warning: comparing values of types Ordered[Unit] and Unit using `>' will always yield false
-  println((c = 1) > 0)
-                  ^
-checksensible.scala:4: warning: comparing values of types Ordered[Unit] and Unit using `<=' will always yield true
-  println((c = 1) <= 0)
-                  ^
-checksensible.scala:5: warning: comparing values of types Unit and Int using `==' will always yield false
+checksensible.scala:3: warning: comparing values of types Unit and Int using `==' will always yield false
   println((c = 1) == 0)
                   ^
-checksensible.scala:7: warning: comparing values of types Int and java.lang.String using `==' will always yield false
+checksensible.scala:5: warning: comparing values of types Int and java.lang.String using `==' will always yield false
   println(1 == "abc")
             ^
-checksensible.scala:8: warning: comparing values of types Int and Boolean using `!=' will always yield true
+checksensible.scala:6: warning: comparing values of types Int and Boolean using `!=' will always yield true
   println(1 != true)
             ^
-checksensible.scala:10: warning: comparing a fresh object using `==' will always yield false
+checksensible.scala:8: warning: comparing a fresh object using `==' will always yield false
   println(((x: Int) => x + 1) == null)
                               ^
-checksensible.scala:11: warning: comparing a fresh object using `==' will always yield false
+checksensible.scala:9: warning: comparing a fresh object using `==' will always yield false
   println(new Object == new Object)
                      ^
-checksensible.scala:12: warning: comparing a fresh object using `!=' will always yield true
-  println(new Array(1) != new Array(1))
-                       ^
-checksensible.scala:15: warning: comparing values of types Int and Null using `==' will always yield false
+checksensible.scala:10: warning: comparing a fresh object using `!=' will always yield true
+  println(new Exception() != new Exception())
+                          ^
+checksensible.scala:13: warning: comparing values of types Int and Null using `==' will always yield false
   if (foo.length == null) //  == 0 makes more sense, but still
                  ^
-checksensible.scala:24: warning: comparing values of types Unit and Int using `!=' will always yield true
+checksensible.scala:22: warning: comparing values of types Unit and Int using `!=' will always yield true
     while ((c = in.read) != -1)
                          ^
-checksensible.scala:30: warning: comparing values of types Unit and Boolean using `==' will always yield false
+checksensible.scala:28: warning: comparing values of types Unit and Boolean using `==' will always yield false
   println({} == true)
              ^
-checksensible.scala:32: warning: comparing a fresh object using `==' will always yield false
+checksensible.scala:30: warning: comparing a fresh object using `==' will always yield false
   println(new Object == 1)
                      ^
-checksensible.scala:33: warning: comparing values of types Int and java.lang.Object using `==' will always yield false
+checksensible.scala:31: warning: comparing values of types Int and java.lang.Object using `==' will always yield false
   println(1 == (new Object))
             ^
-checksensible.scala:37: warning: comparing values of types Int and Unit using `!=' will always yield true
+checksensible.scala:35: warning: comparing values of types Int and Unit using `!=' will always yield true
   println(1 != println)
             ^
-checksensible.scala:38: warning: comparing values of types Int and Symbol using `!=' will always yield true
+checksensible.scala:36: warning: comparing values of types Int and Symbol using `!=' will always yield true
   println(1 != 'sym)
             ^
-15 warnings found
+13 warnings found
 one error found
diff --git a/test/files/neg/checksensible.scala b/test/files/neg/checksensible.scala
index 59d5ccd..06452e5 100644
--- a/test/files/neg/checksensible.scala
+++ b/test/files/neg/checksensible.scala
@@ -1,7 +1,5 @@
 class Test {
   var c = 0
-  println((c = 1) > 0)
-  println((c = 1) <= 0)
   println((c = 1) == 0)
 
   println(1 == "abc")
@@ -9,7 +7,7 @@ class Test {
 
   println(((x: Int) => x + 1) == null)
   println(new Object == new Object)
-  println(new Array(1) != new Array(1))
+  println(new Exception() != new Exception())
 
   val foo: Array[String] = Array("1","2","3")
   if (foo.length == null) //  == 0 makes more sense, but still
diff --git a/test/files/neg/checksensibleUnit.check b/test/files/neg/checksensibleUnit.check
new file mode 100644
index 0000000..1de1aa8
--- /dev/null
+++ b/test/files/neg/checksensibleUnit.check
@@ -0,0 +1,7 @@
+checksensibleUnit.scala:3: error: value > is not a member of Unit
+  println((c = 1) > 0)
+          ^
+checksensibleUnit.scala:4: error: value <= is not a member of Unit
+  println((c = 1) <= 0)
+          ^
+two errors found
diff --git a/test/files/neg/checksensibleUnit.scala b/test/files/neg/checksensibleUnit.scala
new file mode 100644
index 0000000..11c3b67
--- /dev/null
+++ b/test/files/neg/checksensibleUnit.scala
@@ -0,0 +1,5 @@
+class Test {
+  var c = 0
+  println((c = 1) > 0)
+  println((c = 1) <= 0)
+}
diff --git a/test/files/neg/constrs.check b/test/files/neg/constrs.check
index 3524709..4f4a12b 100644
--- a/test/files/neg/constrs.check
+++ b/test/files/neg/constrs.check
@@ -8,7 +8,7 @@ constrs.scala:10: error: called constructor's definition must precede calling co
     def this() = this("abc")
                  ^
 constrs.scala:12: error: called constructor's definition must precede calling constructor's definition
-    def this(x: boolean) = this(x)
+    def this(x: Boolean) = this(x)
                            ^
 constrs.scala:16: error: type mismatch;
  found   : Int(1)
diff --git a/test/files/neg/constrs.scala b/test/files/neg/constrs.scala
index 969f593..016df09 100644
--- a/test/files/neg/constrs.scala
+++ b/test/files/neg/constrs.scala
@@ -9,7 +9,7 @@ object test {
   class Foo(x: Int) {
     def this() = this("abc")
     def this(x: String) = this(1)
-    def this(x: boolean) = this(x)
+    def this(x: Boolean) = this(x)
   }
 
   class Bar[a](x: a) {
diff --git a/test/files/neg/cyclics.check b/test/files/neg/cyclics.check
new file mode 100644
index 0000000..c240387
--- /dev/null
+++ b/test/files/neg/cyclics.check
@@ -0,0 +1,10 @@
+cyclics.scala:2: error: illegal cyclic reference involving type A
+  type A = List[A]
+                ^
+cyclics.scala:3: error: illegal cyclic reference involving type B
+  type B[T] = List[B[B[T]]]
+                   ^
+cyclics.scala:5: error: illegal cyclic reference involving type E
+  type C = I { type E = C }
+                        ^
+three errors found
diff --git a/test/files/neg/cyclics.scala b/test/files/neg/cyclics.scala
new file mode 100644
index 0000000..adfc94e
--- /dev/null
+++ b/test/files/neg/cyclics.scala
@@ -0,0 +1,6 @@
+object test {
+  type A = List[A]
+  type B[T] = List[B[B[T]]]
+  trait I { type E }
+  type C = I { type E = C }
+}
diff --git a/test/files/neg/depmet_1.check b/test/files/neg/depmet_1.check
new file mode 100644
index 0000000..7a4f845
--- /dev/null
+++ b/test/files/neg/depmet_1.check
@@ -0,0 +1,10 @@
+depmet_1.scala:2: error: illegal dependent method type: parameter appears in the type of another parameter in the same section or an earlier one
+  def precise0(y: x.type)(x: String): Unit = {}
+                          ^
+depmet_1.scala:3: error: illegal dependent method type: parameter appears in the type of another parameter in the same section or an earlier one
+  def precise1(x: String, y: x.type): Unit = {}
+               ^
+depmet_1.scala:4: error: not found: value y
+  def precise2[T <: y.type](y: String): Unit = {}
+                    ^
+three errors found
diff --git a/test/files/neg/depmet_1.flags b/test/files/neg/depmet_1.flags
new file mode 100644
index 0000000..1c26b24
--- /dev/null
+++ b/test/files/neg/depmet_1.flags
@@ -0,0 +1 @@
+-Ydependent-method-types
\ No newline at end of file
diff --git a/test/files/neg/depmet_1.scala b/test/files/neg/depmet_1.scala
new file mode 100644
index 0000000..fc672e1
--- /dev/null
+++ b/test/files/neg/depmet_1.scala
@@ -0,0 +1,5 @@
+object Test {
+  def precise0(y: x.type)(x: String): Unit = {}
+  def precise1(x: String, y: x.type): Unit = {}
+  def precise2[T <: y.type](y: String): Unit = {}
+}
\ No newline at end of file
diff --git a/test/files/neg/divergent-implicit.check b/test/files/neg/divergent-implicit.check
index 8d57f92..07af851 100644
--- a/test/files/neg/divergent-implicit.check
+++ b/test/files/neg/divergent-implicit.check
@@ -1,11 +1,12 @@
-divergent-implicit.scala:4: error: diverging implicit expansion for type (Int) => B
-starting with method cast in object Test1
+divergent-implicit.scala:4: error: type mismatch;
+ found   : Int(1)
+ required: String
   val x1: String = 1
                    ^
 divergent-implicit.scala:5: error: diverging implicit expansion for type (Int) => String
 starting with method cast in object Test1
   val x2: String = cast[Int, String](1)
-                   ^
+                                    ^
 divergent-implicit.scala:14: error: diverging implicit expansion for type (Test2.Baz) => Test2.Bar
 starting with method baz2bar in object Test2
   val x: Bar = new Foo
diff --git a/test/files/neg/gadts1.check b/test/files/neg/gadts1.check
index 01d1412..4c91a3b 100644
--- a/test/files/neg/gadts1.check
+++ b/test/files/neg/gadts1.check
@@ -2,5 +2,5 @@ gadts1.scala:15: error: type mismatch;
  found   : Test.Double
  required: a
     case NumTerm(n) => c.x = Double(1.0) 
-                             ^
+                                   ^
 one error found
diff --git a/test/files/neg/gadts1.scala b/test/files/neg/gadts1.scala
index 53389e2..1b455f4 100644
--- a/test/files/neg/gadts1.scala
+++ b/test/files/neg/gadts1.scala
@@ -1,8 +1,8 @@
 object Test{
 
 abstract class Number
-case class Int(n: int) extends Number
-case class Double(d: double) extends Number
+case class Int(n: scala.Int) extends Number
+case class Double(d: scala.Double) extends Number
 
 trait Term[+a]
 case class Cell[a](var x: a) extends Term[a]
@@ -10,7 +10,7 @@ case class NumTerm(val n: Number) extends Term[Number]
 class IntTerm(n: Int) extends NumTerm(n) with Term[Int]
 
 
-def f[a](t:Term[a], c:Cell[a]): unit = 
+def f[a](t:Term[a], c:Cell[a]): Unit = 
   t match {  
     case NumTerm(n) => c.x = Double(1.0) 
   }
@@ -18,7 +18,7 @@ def f[a](t:Term[a], c:Cell[a]): unit =
 
 val x:Term[Number] = NumTerm(Int(5))
 
-def main(args: Array[String]): unit = {
+def main(args: Array[String]): Unit = {
   val cell = Cell[Int](Int(6))
   Console.println(cell)
   f[Int](new IntTerm(Int(5)), cell)
diff --git a/test/files/neg/higherkind_novalue.scala b/test/files/neg/higherkind_novalue.scala
index c2e117b..9c1480c 100644
--- a/test/files/neg/higherkind_novalue.scala
+++ b/test/files/neg/higherkind_novalue.scala
@@ -1,4 +1,4 @@
 abstract class HigherKind[m[s]] {
   val x: m // type of kind *->* doesn't classify a value, but a val/def/... can only contain/return a value
   def y: m
-}
\ No newline at end of file
+}
diff --git a/test/files/neg/illegal-stmt-start.check b/test/files/neg/illegal-stmt-start.check
new file mode 100644
index 0000000..0174752
--- /dev/null
+++ b/test/files/neg/illegal-stmt-start.check
@@ -0,0 +1,4 @@
+illegal-stmt-start.scala:3: error: illegal start of statement (no modifiers allowed here)
+    private def bar {}
+    ^
+one error found
diff --git a/test/files/neg/illegal-stmt-start.scala b/test/files/neg/illegal-stmt-start.scala
new file mode 100644
index 0000000..48ae0a8
--- /dev/null
+++ b/test/files/neg/illegal-stmt-start.scala
@@ -0,0 +1,5 @@
+class Test {
+  def foo {
+    private def bar {}
+  }
+}
\ No newline at end of file
diff --git a/test/files/neg/implicits.check b/test/files/neg/implicits.check
index 409d6ce..d975ccf 100644
--- a/test/files/neg/implicits.check
+++ b/test/files/neg/implicits.check
@@ -1,11 +1,11 @@
-implicits.scala:21: error: type mismatch;
- found   : Pos
- required: ?{val +: ?}
-Note that implicit conversions are not applicable because they are ambiguous:
- most specific definition is: method pos2int in object Super of type (Pos)int
- yet alternative definition   method any2plus in object Sub of type (Any)Sub.Plus
- is defined in a subclass.
- Both definitions are possible conversion functions from Pos to ?{val +: ?}
-  f(p+1)
-    ^
-one error found
+implicits.scala:38: error: type mismatch;
+ found   : test2.HSome[java.lang.String,test2.HMap]
+ required: Int
+  foo(set)
+      ^
+implicits.scala:46: error: type mismatch;
+ found   : List[Any]
+ required: scala.List[Mxml]
+        children.toList.flatMap ( e => {
+                                ^
+two errors found
diff --git a/test/files/neg/implicits.scala b/test/files/neg/implicits.scala
index 836724c..e908fb0 100644
--- a/test/files/neg/implicits.scala
+++ b/test/files/neg/implicits.scala
@@ -3,7 +3,7 @@ class Pos
 class Super
 
 object Super {
-  implicit def pos2int(p: Pos): int = 0
+  implicit def pos2int(p: Pos): Int = 0
 }  
 
 object Sub extends Super {
@@ -17,6 +17,42 @@ object Test {
   import Super._
   import Sub._
   val p = new Pos
-  def f(x: int): int = x
+  def f(x: Int): Int = x
   f(p+1)
 }
+
+object test2 {
+  sealed trait HMap {
+    def +[T](v: T) = HSome(v,this)
+  }
+
+  final case class HSome[T, L <: HMap](head: T, tail: L) extends HMap
+
+  final object HEmpty extends HMap
+
+  val set = HEmpty + 3 + "3"
+  implicit def select[T](t: HSome[T,_]) = t.head
+  implicit def selectTail[L](t: HSome[_,L]) = t.tail
+  
+  def foo(x: Int) = 3
+  foo(set)
+}
+
+// #2180
+class Mxml {
+
+    private def processChildren( children:Seq[Any] ):List[Mxml] = {
+
+        children.toList.flatMap ( e => {
+
+            e match {
+
+                case s:scala.collection.Traversable[_] => s case a => List(a)
+
+            }
+
+        })
+
+    }
+
+} 
diff --git a/test/files/neg/java-access-neg.check b/test/files/neg/java-access-neg.check
new file mode 100644
index 0000000..af2812b
--- /dev/null
+++ b/test/files/neg/java-access-neg.check
@@ -0,0 +1,16 @@
+S2.scala:12: error: method packageAbstract overrides nothing
+  override private[b] def packageAbstract() = ()      // fail
+                          ^
+S2.scala:16: error: method packageConcrete overrides nothing
+  override private[b] def packageConcrete() = ()      // fail
+                          ^
+S2.scala:36: error: method packageConcrete overrides nothing
+  override protected[b] def packageConcrete() = ()    // fail
+                            ^
+S2.scala:47: error: method packageConcrete overrides nothing
+  override private[a] def packageConcrete() = ()        // fail
+                          ^
+S2.scala:58: error: method packageConcrete overrides nothing
+  override def packageConcrete() = ()   // fail
+               ^
+5 errors found
diff --git a/test/files/neg/java-access-neg/J.java b/test/files/neg/java-access-neg/J.java
new file mode 100644
index 0000000..4f20246
--- /dev/null
+++ b/test/files/neg/java-access-neg/J.java
@@ -0,0 +1,15 @@
+package a.b;
+
+public abstract class J {
+  public J() { }
+  J(int x1) { }
+  protected J(int x1, int x2) { }
+  
+  abstract void packageAbstract();
+  protected abstract void protectedAbstract();
+  public abstract void publicAbstract();
+  
+  void packageConcrete() { return; }
+  protected void protectedConcrete() { return; }
+  public void publicConcrete() { return; }
+}
diff --git a/test/files/neg/java-access-neg/S2.scala b/test/files/neg/java-access-neg/S2.scala
new file mode 100644
index 0000000..dd0af8d
--- /dev/null
+++ b/test/files/neg/java-access-neg/S2.scala
@@ -0,0 +1,61 @@
+package a.b
+package c
+
+import a.b.J
+
+/** Variations of java-access-pos with us in a nested package.
+ */
+
+/** Declaring "override" all the time.
+ */
+class S1 extends J {
+  override private[b] def packageAbstract() = ()      // fail
+  override protected[b] def protectedAbstract() = ()
+  override def publicAbstract() = ()
+  
+  override private[b] def packageConcrete() = ()      // fail
+  override protected[b] def protectedConcrete() = ()
+  override def publicConcrete() = ()
+}
+
+/** Implementing abstracts.
+ */
+class S2 extends J {
+  private[b] def packageAbstract() = ()     // fail
+  protected[b] def protectedAbstract() = ()
+  def publicAbstract() = ()
+}
+
+/** Widening access.
+ */
+class S3 extends J {
+  protected[b] def packageAbstract() = ()   // fail
+  protected[b] def protectedAbstract() = ()
+  def publicAbstract() = ()
+  
+  override protected[b] def packageConcrete() = ()    // fail
+  override protected[b] def protectedConcrete() = ()
+  override def publicConcrete() = ()
+}
+/** More widening.
+ */
+class S4 extends J {
+  private[a] def packageAbstract() = ()         // fail
+  protected[a] def protectedAbstract() = ()
+  def publicAbstract() = ()
+  
+  override private[a] def packageConcrete() = ()        // fail
+  override protected[a] def protectedConcrete() = ()
+  override def publicConcrete() = ()
+}
+/** Yet more widening.
+ */
+class S5 extends J {
+  def packageAbstract() = ()      // fail
+  def protectedAbstract() = ()
+  def publicAbstract() = ()
+  
+  override def packageConcrete() = ()   // fail
+  override def protectedConcrete() = ()
+  override def publicConcrete() = ()
+}
diff --git a/test/files/neg/lazy-override.check b/test/files/neg/lazy-override.check
index d1c9d30..793e6b2 100644
--- a/test/files/neg/lazy-override.check
+++ b/test/files/neg/lazy-override.check
@@ -1,8 +1,8 @@
-lazy-override.scala:11: error: error overriding value x in class A of type Int;
+lazy-override.scala:11: error: overriding value x in class A of type Int;
  lazy value x cannot override a concrete non-lazy value
     override lazy val x: Int = { print("/*B.x*/"); 3 }
                       ^
-lazy-override.scala:13: error: error overriding lazy value y in class A of type Int;
+lazy-override.scala:13: error: overriding lazy value y in class A of type Int;
  value y must be declared lazy to override a concrete lazy value
     override val y: Int = { print("/*B.y*/"); 3 }
                  ^
diff --git a/test/files/neg/migration28.check b/test/files/neg/migration28.check
new file mode 100644
index 0000000..4c8c58e
--- /dev/null
+++ b/test/files/neg/migration28.check
@@ -0,0 +1,8 @@
+migration28.scala:5: error: method ++= in class Stack is deprecated: use pushAll
+  s ++= List(1,2,3)
+  ^
+migration28.scala:7: error: method foreach in class Stack has changed semantics:
+Stack iterator and foreach now traverse in FIFO order.
+  s foreach (_ => ())
+  ^
+two errors found
diff --git a/test/files/neg/migration28.flags b/test/files/neg/migration28.flags
new file mode 100644
index 0000000..197b319
--- /dev/null
+++ b/test/files/neg/migration28.flags
@@ -0,0 +1 @@
+-Xfatal-warnings -Xmigration
diff --git a/test/files/neg/migration28.scala b/test/files/neg/migration28.scala
new file mode 100644
index 0000000..346c1a6
--- /dev/null
+++ b/test/files/neg/migration28.scala
@@ -0,0 +1,12 @@
+object Test {
+  import scala.collection.mutable._
+  
+  val s = new Stack[Int]
+  s ++= List(1,2,3)
+  s map (_ + 1)
+  s foreach (_ => ())
+  
+  def main(args: Array[String]): Unit = {
+    
+  }
+}
diff --git a/test/files/neg/multi-array.check b/test/files/neg/multi-array.check
index 94d0613..f8432a7 100644
--- a/test/files/neg/multi-array.check
+++ b/test/files/neg/multi-array.check
@@ -1,4 +1,8 @@
-multi-array.scala:6: error: too many arguments for array constructor: found 2 but array has only 1 dimension(s)
+multi-array.scala:6: warning: new Array(...) with multiple dimensions has been deprecated; use Array.ofDim(...) instead
   val a: Array[Int] = new Array(10, 10)
                       ^
+multi-array.scala:6: error: too many dimensions for array creation
+  val a: Array[Int] = new Array(10, 10)
+                      ^
+one warning found
 one error found
diff --git a/test/files/neg/multi-array.flags b/test/files/neg/multi-array.flags
new file mode 100644
index 0000000..c36e713
--- /dev/null
+++ b/test/files/neg/multi-array.flags
@@ -0,0 +1 @@
+-deprecation
\ No newline at end of file
diff --git a/test/files/neg/names-defaults-neg-ref.check b/test/files/neg/names-defaults-neg-ref.check
new file mode 100644
index 0000000..00052c7
--- /dev/null
+++ b/test/files/neg/names-defaults-neg-ref.check
@@ -0,0 +1,16 @@
+names-defaults-neg-ref.scala:3: error: in anonymous class $anon, multiple overloaded alternatives of method f define default arguments.
+The members with defaults are defined in trait B2235 and trait A2235.
+  new A2235 with B2235
+      ^
+names-defaults-neg-ref.scala:7: error: in class A, multiple overloaded alternatives of method foo define default arguments.
+class A {
+      ^
+names-defaults-neg-ref.scala:17: error: in class C, multiple overloaded alternatives of method bar define default arguments.
+The members with defaults are defined in class C and class B.
+class C extends B {
+      ^
+names-defaults-neg-ref.scala:21: error: overriding method bar$default$1 in class B of type => String;
+ method bar$default$1 has incompatible type
+  def bar(i: Int = 129083) = i
+          ^
+four errors found
diff --git a/test/files/neg/names-defaults-neg-ref.scala b/test/files/neg/names-defaults-neg-ref.scala
new file mode 100644
index 0000000..4611aad
--- /dev/null
+++ b/test/files/neg/names-defaults-neg-ref.scala
@@ -0,0 +1,26 @@
+object Test extends Application {
+  // #2235
+  new A2235 with B2235
+}
+
+// only one overloaded alternative is allowed to have defaults
+class A {
+  def foo(a: Int = 0) = a
+  def foo(b: String = "another") = b
+}
+
+class B {
+  def foo(a: Int) = a
+  def bar(u: String = "ldksj") = u
+}
+
+class C extends B {
+  override def foo(a: Int = 1092) = a
+  def foo(b: String = "lskdfj")
+
+  def bar(i: Int = 129083) = i
+}
+
+// #2235
+trait A2235 { def f(x: Int = 1) = x }
+trait B2235 { def f(x: String = "1") = x }
diff --git a/test/files/neg/names-defaults-neg.check b/test/files/neg/names-defaults-neg.check
new file mode 100644
index 0000000..5d8f2e2
--- /dev/null
+++ b/test/files/neg/names-defaults-neg.check
@@ -0,0 +1,149 @@
+names-defaults-neg.scala:65: error: not enough arguments for method apply: (a: Int,b: String)(c: Int*)Fact in object Fact.
+Unspecified value parameter b.
+  val fac = Fact(1)(2, 3)
+                ^
+names-defaults-neg.scala:5: error: type mismatch;
+ found   : java.lang.String("#")
+ required: Int
+  test1(b = 2, a = "#")
+                   ^
+names-defaults-neg.scala:8: error: positional after named argument.
+  test1(b = "(*", 23)
+                  ^
+names-defaults-neg.scala:13: error: reference to x is ambiguous; it is both, a parameter
+name of the method and the name of a variable currently in scope.
+  test2(x = 1)
+          ^
+names-defaults-neg.scala:15: error: not found: value c
+  test1(c = 0, b = "joke")
+        ^
+names-defaults-neg.scala:16: error: not found: value m
+  test7((m = 1))  // named arguments must be top-level assignments
+         ^
+names-defaults-neg.scala:17: error: not found: value m
+  test7({m = 1})
+         ^
+names-defaults-neg.scala:18: error: not found: value m
+  test7 { m = 1 } // no named arguments in argument block
+          ^
+names-defaults-neg.scala:19: error: reference to x is ambiguous; it is both, a parameter
+name of the method and the name of a variable currently in scope.
+  test8(x = 1)
+          ^
+names-defaults-neg.scala:22: error: parameter specified twice: a
+  test1(1, a = 2)
+             ^
+names-defaults-neg.scala:23: error: parameter specified twice: b
+  test1(b = 1, b = "2")
+                 ^
+names-defaults-neg.scala:26: error: {
+  val x$5: Int(3) = 3;
+  val x$6: Int(1) = 1;
+  Test.this.test3(1, 3)
+} of type Int does not take parameters
+  test3(b = 3, a = 1)(3)
+                     ^
+names-defaults-neg.scala:35: error: ambiguous reference to overloaded definition,
+both method f in object t1 of type (b: String,a: Int)java.lang.String
+and  method f in object t1 of type (a: Int,b: String)java.lang.String
+match argument types (b: java.lang.String,a: Int)
+  t1.f(b = "dkljf", a = 1)
+     ^
+names-defaults-neg.scala:42: error: ambiguous reference to overloaded definition,
+both method f in object t3 of type (a2: Int)(b: Int)java.lang.String
+and  method f in object t3 of type (a1: Int)java.lang.String
+match argument types (Int)
+  t3.f(1)
+     ^
+names-defaults-neg.scala:43: error: ambiguous reference to overloaded definition,
+both method f in object t3 of type (a2: Int)(b: Int)java.lang.String
+and  method f in object t3 of type (a1: Int)java.lang.String
+match argument types (Int)
+  t3.f(1)(2)
+     ^
+names-defaults-neg.scala:49: error: ambiguous reference to overloaded definition,
+both method g in object t7 of type (a: B)java.lang.String
+and  method g in object t7 of type (a: C,b: Int*)java.lang.String
+match argument types (C)
+  t7.g(new C()) // ambigous reference
+     ^
+names-defaults-neg.scala:53: error: parameter specified twice: b
+  test5(a = 1, b = "dkjl", b = "dkj")
+                             ^
+names-defaults-neg.scala:54: error: parameter specified twice: b
+  test5(1, "2", b = 3)
+                  ^
+names-defaults-neg.scala:55: error: when using named arguments, the vararg parameter has to be specified exactly once
+  test5(b = "dlkj")
+       ^
+names-defaults-neg.scala:61: error: ambiguous reference to overloaded definition,
+both method f in object t8 of type (b: String,a: Int)java.lang.String
+and  method f in object t8 of type (a: Int,b: java.lang.Object)java.lang.String
+match argument types (a: Int,b: java.lang.String) and expected result type Any
+  println(t8.f(a = 0, b = "1")) // ambigous reference
+             ^
+names-defaults-neg.scala:69: error: wrong number of arguments for <none>: (x: Int,y: String)A1
+  A1() match { case A1(_) => () }
+                      ^
+names-defaults-neg.scala:76: error: no type parameters for method test4: (x: T[T[List[T[X forSome { type X }]]]])T[T[List[T[X forSome { type X }]]]] exist so that it can be applied to arguments (List[Int])
+ --- because ---
+argument expression's type is not compatible with formal parameter type;
+ found   : List[Int]
+ required: ?T[ ?T[ scala.List[?T[ X forSome { type X } ]] ] ]
+Error occurred in an application involving default arguments.
+  test4()
+  ^
+names-defaults-neg.scala:79: error: type mismatch;
+ found   : List[Int]
+ required: scala.List[scala.List[?]]
+  def test6[T](x: List[List[T]] = List(1,2)) = x
+                                      ^
+names-defaults-neg.scala:82: error: type mismatch;
+ found   : Int
+ required: String
+Error occurred in an application involving default arguments.
+  new A2[String]()
+  ^
+names-defaults-neg.scala:86: error: module extending its companion class cannot use default constructor arguments
+    object C extends C()
+             ^
+names-defaults-neg.scala:120: error: reference to var2 is ambiguous; it is both, a parameter
+name of the method and the name of a variable currently in scope.
+  delay(var2 = 40)
+             ^
+names-defaults-neg.scala:123: error: missing parameter type for expanded function ((x$1) => a = x$1)
+  val taf2: Int => Unit = testAnnFun(a = _, b = get("+"))
+                                         ^
+names-defaults-neg.scala:124: error: parameter specified twice: a
+  val taf3 = testAnnFun(b = _: String, a = get(8))
+                                         ^
+names-defaults-neg.scala:125: error: wrong number of parameters; expected = 2
+  val taf4: (Int, String) => Unit = testAnnFun(_, b = _)
+                                              ^
+names-defaults-neg.scala:133: error: variable definition needs type because the name is used as named argument the definition.
+  def t3 { var x = t.f(x = 1) }
+               ^
+names-defaults-neg.scala:136: error: variable definition needs type because the name is used as named argument the definition.
+  object t6 { var x = t.f(x = 1) }
+                  ^
+names-defaults-neg.scala:139: error: variable definition needs type because the name is used as named argument the definition.
+  class t9 { var x = t.f(x = 1) }
+                 ^
+names-defaults-neg.scala:153: error: variable definition needs type because the name is used as named argument the definition.
+  def u3 { var x = u.f(x = 1) }
+               ^
+names-defaults-neg.scala:156: error: variable definition needs type because the name is used as named argument the definition.
+  def u6 { var x = u.f(x = "32") }
+               ^
+names-defaults-neg.scala:159: error: reference to x is ambiguous; it is both, a parameter
+name of the method and the name of a variable currently in scope.
+  def u9 { var x: Int = u.f(x = 1) }
+                              ^
+names-defaults-neg.scala:166: error: variable definition needs type because the name is used as named argument the definition.
+  class u15 { var x = u.f(x = 1) }
+                  ^
+names-defaults-neg.scala:169: error: reference to x is ambiguous; it is both, a parameter
+name of the method and the name of a variable currently in scope.
+  class u18 { var x: Int = u.f(x = 1) }
+                                 ^
+37 errors found
diff --git a/test/files/neg/names-defaults-neg.scala b/test/files/neg/names-defaults-neg.scala
new file mode 100644
index 0000000..daa97a8
--- /dev/null
+++ b/test/files/neg/names-defaults-neg.scala
@@ -0,0 +1,173 @@
+object Test extends Application {
+  // TESTS
+
+  // re-ordering
+  test1(b = 2, a = "#")
+
+  // mixing named and positional
+  test1(b = "(*", 23)
+
+  // assignment / names
+  var x = 0
+  var y = 0
+  test2(x = 1)
+  test2(y = 1)
+  test1(c = 0, b = "joke")
+  test7((m = 1))  // named arguments must be top-level assignments
+  test7({m = 1})
+  test7 { m = 1 } // no named arguments in argument block
+  test8(x = 1)
+
+  // argument specified twice
+  test1(1, a = 2)
+  test1(b = 1, b = "2")
+
+  // error message when there are too many argument lists (not very nice..)
+  test3(b = 3, a = 1)(3)
+
+
+
+  // overloading resolution
+  object t1 {
+    def f(a: Int, b: String) = "first"
+    def f(b: String, a: Int) = "second"
+  }
+  t1.f(b = "dkljf", a = 1)
+
+
+  object t3 {
+    def f(a1: Int) = "first"
+    def f(a2: Int)(b: Int) = "second"
+  }
+  t3.f(1)
+  t3.f(1)(2)
+
+  object t7 {
+    def g(a: C, b: Int*) = "third"
+    def g(a: B) = "fourth"
+  }
+  t7.g(new C()) // ambigous reference
+
+  // vararg
+  def test5(a: Int, b: String*) = a
+  test5(a = 1, b = "dkjl", b = "dkj")
+  test5(1, "2", b = 3)
+  test5(b = "dlkj")
+
+  object t8 {
+    def f(a: Int, b: Object) = "first"
+    def f(b: String, a: Int) = "second"
+  }
+  println(t8.f(a = 0, b = "1")) // ambigous reference
+
+
+  // case class copy does not exist if there's a vararg
+  val fac = Fact(1)(2, 3)
+  val facc = fac.copy(b = "dlkfj")()
+
+  // no defaults in patterns
+  A1() match { case A1(_) => () }
+
+
+  // return types of default getters
+
+  // definition compiles, but default cannot  be used, it doesn't conform
+  def test4[T[P]](x: T[T[List[T[X forSome { type X }]]]] = List(1,2)) = x
+  test4()
+
+  // doesn't compile
+  def test6[T](x: List[List[T]] = List(1,2)) = x
+
+  // correct error message
+  new A2[String]()
+
+  object t3648 {
+    class C(val s: String = "")
+    object C extends C()
+  }
+
+  // DEFINITIONS
+  def test1(a: Int, b: String) = a +": "+ b
+  def test2(x: Unit) = println("test2")
+  def test3(a: Int, b: Int) = a + b
+  def test7(m: Int) = m
+  def test8[T](x: => T) = println("test8")
+}
+
+class B {
+  def foo(a: Int) = a
+  def bar(u: String = "ldksj") = u
+}
+
+class C extends B {
+  override def foo(a: Int = 1092) = a
+  def foo(b: String = "lskdfj")
+
+  def bar(i: Int = 129083) = i
+}
+
+case class Fact(a: Int, b: String)(c: Int*)
+
+case class A1(x: Int = 1, y: String = "2")
+
+class A2[T](a: T = 1)
+
+
+// anonymous functions
+object anfun {
+  var var2 = 0
+  def delay(var2: => Unit) { var2 }
+  delay(var2 = 40)
+
+  def testAnnFun(a: Int, b: String) = println(a +": "+ b)
+  val taf2: Int => Unit = testAnnFun(a = _, b = get("+"))
+  val taf3 = testAnnFun(b = _: String, a = get(8))
+  val taf4: (Int, String) => Unit = testAnnFun(_, b = _)
+}
+
+object t3685 {
+  object t { def f(x: Int) = x }
+
+  def t1 { def x = t.f(x = 1) }
+  def t2 { val x = t.f(x = 1) }
+  def t3 { var x = t.f(x = 1) }
+  object t4 { def x = t.f(x = 1) }
+  object t5 { val x = t.f(x = 1) }
+  object t6 { var x = t.f(x = 1) }
+  class t7 { def x = t.f(x = 1) }
+  class t8 { val x = t.f(x = 1) }
+  class t9 { var x = t.f(x = 1) }
+
+  def t10 { def x: Int = t.f(x = 1) }
+  def t11 { val x: Int = t.f(x = 1) }
+  def t12 { var x: Int = t.f(x = 1) }
+  class t13 { def x: Int = t.f(x = 1) }
+  class t14 { val x: Int = t.f(x = 1) }
+  class t15 { var x: Int = t.f(x = 1) }
+
+
+  object u { def f[T](x: T) = 100 }
+
+  def u1 { def x = u.f(x = 1) }
+  def u2 { val x = u.f(x = 1) }
+  def u3 { var x = u.f(x = 1) }
+  def u4 { def x = u.f(x = "23") }
+  def u5 { val x = u.f(x = "32") }
+  def u6 { var x = u.f(x = "32") }
+  def u7 { def x: Int = u.f(x = 1) }
+  def u8 { val x: Int = u.f(x = 1) }
+  def u9 { var x: Int = u.f(x = 1) }
+  def u10 { def x: Int = u.f(x = "32") }
+  def u11 { val x: Int = u.f(x = "32") }
+  def u12 { var x: Int = u.f(x = "32") }
+
+  class u13 { def x = u.f(x = 1) }
+  class u14 { val x = u.f(x = 1) }
+  class u15 { var x = u.f(x = 1) }
+  class u16 { def x: Int = u.f(x = 1) }
+  class u17 { val x: Int = u.f(x = 1) }
+  class u18 { var x: Int = u.f(x = 1) }
+  class u19 { def x: Int = u.f(x = "32") }
+  class u20 { val x: Int = u.f(x = "32") }
+  class u21 { var x: Int = u.f(x = "32") }
+}
diff --git a/test/files/neg/overload-msg.check b/test/files/neg/overload-msg.check
new file mode 100644
index 0000000..780830b
--- /dev/null
+++ b/test/files/neg/overload-msg.check
@@ -0,0 +1,13 @@
+overload-msg.scala:3: error: overloaded method value + with alternatives:
+  (Double)Double <and>
+  (Float)Float <and>
+  (Long)Long <and>
+  (scala.Int)scala.Int <and>
+  (Char)scala.Int <and>
+  (Short)scala.Int <and>
+  (Byte)scala.Int <and>
+  (java.lang.String)java.lang.String
+ cannot be applied to (Int(in method f))
+  def f[Int](y: Int) = x + y
+                       ^
+one error found
diff --git a/test/files/neg/overload-msg.scala b/test/files/neg/overload-msg.scala
new file mode 100644
index 0000000..8967222
--- /dev/null
+++ b/test/files/neg/overload-msg.scala
@@ -0,0 +1,4 @@
+// type parameter shadows actual type, massive overload error confuses.
+class A(x: Int) { 
+  def f[Int](y: Int) = x + y
+}
diff --git a/test/files/neg/overload.check b/test/files/neg/overload.check
index 5f7644e..abfabaf 100644
--- a/test/files/neg/overload.check
+++ b/test/files/neg/overload.check
@@ -1,7 +1,7 @@
-overload.scala:10: error: erroneous reference to overloaded definition,
-most specific definition is: method f in class C of type (int)Unit,
-yet alternative definition   method f in class D of type (Any)Unit
-is defined in a subclass
+overload.scala:10: error: ambiguous reference to overloaded definition,
+both method f in class D of type (x: Any)Unit
+and  method f in class C of type (x: Int)Unit
+match argument types (Int)
   (new D).f(1)
           ^
 one error found
diff --git a/test/files/neg/overload.scala b/test/files/neg/overload.scala
index 311ea38..6ad911e 100644
--- a/test/files/neg/overload.scala
+++ b/test/files/neg/overload.scala
@@ -1,5 +1,5 @@
 class C {
-  def f(x: int) {}
+  def f(x: Int) {}
 }
 
 class D extends C {
diff --git a/test/files/neg/override.check b/test/files/neg/override.check
new file mode 100644
index 0000000..0336fb2
--- /dev/null
+++ b/test/files/neg/override.check
@@ -0,0 +1,5 @@
+override.scala:9: error: overriding type T in trait A with bounds >: Int <: Int;
+ type T in trait B with bounds >: String <: String has incompatible type
+  lazy val x : A with B = x
+           ^
+one error found
diff --git a/test/files/neg/override.scala b/test/files/neg/override.scala
new file mode 100644
index 0000000..764b066
--- /dev/null
+++ b/test/files/neg/override.scala
@@ -0,0 +1,15 @@
+trait X {
+  trait A { type T >: Int <: Int }
+  val x : A
+  var n : x.T = 3
+}
+
+trait Y extends X {
+  trait B { type T >: String <: String }
+  lazy val x : A with B = x
+  n = "foo"
+}
+
+object Test extends Application {
+  new Y {}
+}
diff --git a/test/files/neg/parstar.check b/test/files/neg/parstar.check
new file mode 100644
index 0000000..108f0f4
--- /dev/null
+++ b/test/files/neg/parstar.check
@@ -0,0 +1,7 @@
+parstar.scala:8: error: *-parameter must come last
+    def m(a: A*, b: B ) = a.toArray
+          ^
+parstar.scala:9: error: *-parameter must come last
+    def m(a: A*, b: B*) = a.toArray
+          ^
+two errors found
diff --git a/test/pending/neg/parstar.scala b/test/files/neg/parstar.scala
similarity index 100%
rename from test/pending/neg/parstar.scala
rename to test/files/neg/parstar.scala
diff --git a/test/files/neg/pat_unreachable.check b/test/files/neg/pat_unreachable.check
new file mode 100644
index 0000000..4e1463d
--- /dev/null
+++ b/test/files/neg/pat_unreachable.check
@@ -0,0 +1,7 @@
+pat_unreachable.scala:5: error: unreachable code
+    case Seq(x, y, z, w) => List(z,w) // redundant!
+                                ^
+pat_unreachable.scala:9: error: unreachable code
+    case Seq(x, y) => List(x, y)
+                          ^
+two errors found
diff --git a/test/files/neg/pat_unreachable.scala b/test/files/neg/pat_unreachable.scala
new file mode 100644
index 0000000..527731e
--- /dev/null
+++ b/test/files/neg/pat_unreachable.scala
@@ -0,0 +1,20 @@
+
+object Test extends Application {
+  def unreachable1(xs:Seq[Char]) = xs match {
+    case Seq(x, y, _*) => x::y::Nil
+    case Seq(x, y, z, w) => List(z,w) // redundant!
+  }
+  def unreachable2(xs:Seq[Char]) = xs match {
+    case Seq(x, y, _*) => x::y::Nil
+    case Seq(x, y) => List(x, y)
+  }
+  
+  def not_unreachable(xs:Seq[Char]) = xs match {
+    case Seq(x, y, _*) => x::y::Nil
+    case Seq(x) => List(x)
+  }
+  def not_unreachable2(xs:Seq[Char]) = xs match {
+    case Seq(x, y) => x::y::Nil
+    case Seq(x, y, z, _*) => List(x,y)
+  }
+}
diff --git a/test/files/neg/patmat-type-check.check b/test/files/neg/patmat-type-check.check
new file mode 100644
index 0000000..ab638b6
--- /dev/null
+++ b/test/files/neg/patmat-type-check.check
@@ -0,0 +1,21 @@
+patmat-type-check.scala:18: error: scrutinee is incompatible with pattern type;
+ found   : Seq[A]
+ required: java.lang.String
+  def f1 = "bob".reverse match { case Seq('b', 'o', 'b') => true } // fail
+                                         ^
+patmat-type-check.scala:19: error: scrutinee is incompatible with pattern type;
+ found   : Seq[A]
+ required: Array[Char]
+  def f2 = "bob".toArray match { case Seq('b', 'o', 'b') => true } // fail
+                                         ^
+patmat-type-check.scala:23: error: scrutinee is incompatible with pattern type;
+ found   : Seq[A]
+ required: Test.Bop2
+  def f3(x: Bop2) = x match { case Seq('b', 'o', 'b') => true } // fail
+                                      ^
+patmat-type-check.scala:27: error: scrutinee is incompatible with pattern type;
+ found   : Seq[A]
+ required: Test.Bop3[T]
+  def f4[T](x: Bop3[T]) = x match { case Seq('b', 'o', 'b') => true } // fail
+                                            ^
+four errors found
diff --git a/test/files/neg/patmat-type-check.scala b/test/files/neg/patmat-type-check.scala
new file mode 100644
index 0000000..f6658b0
--- /dev/null
+++ b/test/files/neg/patmat-type-check.scala
@@ -0,0 +1,28 @@
+object Test
+{
+  def s1 = "bob".toList  match { case Seq('b', 'o', 'b') => true }  // list ok
+  
+  // not final, allowed
+  class Bop 
+  def s2(x: Bop) = x match { case Seq('b', 'o', 'b') => true }
+  
+  // covariance, allowed
+  final class Bop4[+T]
+  def s3[T](x: Bop4[T]) = x match { case Seq('b', 'o', 'b') => true }
+  
+  // contravariance, allowed
+  final class Bop5[T, U, -V]
+  def s4[T1, T2](x: Bop5[_, T1, T2]) = x match { case Seq('b', 'o', 'b') => true }
+
+  // String and Array are final/invariant, disallowed
+  def f1 = "bob".reverse match { case Seq('b', 'o', 'b') => true } // fail
+  def f2 = "bob".toArray match { case Seq('b', 'o', 'b') => true } // fail
+
+  // final, no type parameters, should be disallowed
+  final class Bop2
+  def f3(x: Bop2) = x match { case Seq('b', 'o', 'b') => true } // fail
+  
+  // final, invariant type parameter, should be disallowed
+  final class Bop3[T]
+  def f4[T](x: Bop3[T]) = x match { case Seq('b', 'o', 'b') => true } // fail
+}
diff --git a/test/files/neg/patmatexhaust.check b/test/files/neg/patmatexhaust.check
index 66b0f3c..ca76930 100644
--- a/test/files/neg/patmatexhaust.check
+++ b/test/files/neg/patmatexhaust.check
@@ -15,8 +15,8 @@ missing combination           Qult          Qult
     def ma3(x:Mult) = (x,x) match { // not exhaustive
                        ^
 patmatexhaust.scala:49: warning: match is not exhaustive!
-missing combination             Gu
 missing combination             Gp
+missing combination             Gu
 
     def ma4(x:Deep) = x match { // missing cases: Gu, Gp
                       ^
@@ -25,8 +25,13 @@ missing combination             Gp
 
     def ma5(x:Deep) = x match { // Gp
                       ^
-patmatexhaust.scala:70: error: unreachable code
+patmatexhaust.scala:75: warning: match is not exhaustive!
+missing combination              B
+
+  def ma9(x: B) = x match {
+                  ^
+patmatexhaust.scala:92: error: unreachable code
       case 1 => 
              ^
-5 warnings found
+6 warnings found
 one error found
diff --git a/test/files/neg/patmatexhaust.scala b/test/files/neg/patmatexhaust.scala
index 1b0ad29..81812d6 100644
--- a/test/files/neg/patmatexhaust.scala
+++ b/test/files/neg/patmatexhaust.scala
@@ -1,5 +1,5 @@
 class TestSealedExhaustive { // compile only
-    sealed class Foo
+    sealed abstract class Foo
 
     case class Bar(x:Int) extends Foo
     case object Baz extends Foo
@@ -12,7 +12,7 @@ class TestSealedExhaustive { // compile only
       case Baz    => // not exhaustive
     }
 
-    sealed class Mult
+    sealed abstract class Mult
     case class Kult(s:Mult) extends Mult
     case class Qult() extends Mult
 
@@ -32,7 +32,7 @@ class TestSealedExhaustive { // compile only
       case (Qult(), Kult(_))    => 
     }
 
-    sealed class Deep
+    sealed abstract class Deep
 
     case object Ga extends Deep
     sealed class Gp extends Deep
@@ -65,6 +65,28 @@ class TestSealedExhaustive { // compile only
     case 1::2::Nil =>
       case _ =>
   }
+  
+  sealed class B
+  case class B1() extends B
+  case object B2 extends B
+  def ma8(x: B) = x match {
+    case _: B => true
+  }
+  def ma9(x: B) = x match {
+    case B1() => true       // missing B, which is not abstract so must be included
+    case B2   => true
+  }
+  sealed abstract class C
+  abstract class C1 extends C
+  object C2 extends C
+  case object C6 extends C
+  class C3 extends C1
+  case class C4() extends C3
+  def ma10(x: C) = x match { // exhaustive
+    case C4()     => true
+    case C2 | C6  => true
+  } 
+  
   def redundant = 1 match { // include this otherwise script won't test this in files/neg
     case 1 =>
       case 1 => 
diff --git a/test/files/neg/patternalts.scala b/test/files/neg/patternalts.scala
index 62d0325..56b682b 100644
--- a/test/files/neg/patternalts.scala
+++ b/test/files/neg/patternalts.scala
@@ -1,8 +1,5 @@
 object Test {
   List(1) match {
     case List(x) | List() => Console.println(x)
-  }
-  List(2) match {
-    case List(_: Int) | List() => Console.println()
-  }
+  }  
 }
diff --git a/test/files/neg/sabin2.check b/test/files/neg/sabin2.check
index 92578bc..8a09361 100644
--- a/test/files/neg/sabin2.check
+++ b/test/files/neg/sabin2.check
@@ -2,5 +2,5 @@ sabin2.scala:22: error: type mismatch;
  found   : Test.Base#T
  required: _7.T where val _7: Test.Base
    a.set(b.get()) // Error
-           ^
+              ^
 one error found
diff --git a/test/files/neg/spec-overrides.check b/test/files/neg/spec-overrides.check
new file mode 100644
index 0000000..639186a
--- /dev/null
+++ b/test/files/neg/spec-overrides.check
@@ -0,0 +1,7 @@
+spec-overrides.scala:8: error: Type parameter has to be specialized at least for the same types as in the overridden method. Missing types: Int
+  override def a[@specialized(Double) T](t: T): List[T] = Nil
+                                      ^
+spec-overrides.scala:12: error: Type parameter has to be specialized at least for the same types as in the overridden method. Missing types: Int
+  override def a[T](t: T): List[T] = Nil
+                 ^
+two errors found
diff --git a/test/files/neg/spec-overrides.scala b/test/files/neg/spec-overrides.scala
new file mode 100644
index 0000000..27d39ad
--- /dev/null
+++ b/test/files/neg/spec-overrides.scala
@@ -0,0 +1,26 @@
+class P {
+  def a[@specialized(Int) T](t: T): List[T] = List(t)
+}
+class FX extends P {
+  override def a[@specialized(Int) T](t: T): List[T] = Nil
+}
+class FX1 extends P {
+  override def a[@specialized(Double) T](t: T): List[T] = Nil
+}
+
+class FX2 extends P {
+  override def a[T](t: T): List[T] = Nil
+}
+
+object Test extends Application {
+  val fx = new FX
+  val p = new P
+ 
+  println(fx.a(3))
+  println((fx: P).a(3))
+  println((fx: P).a(3.0))
+
+
+  // val d = new Derived[Int]
+  // println((d: Base[Int]).m(10))
+}
diff --git a/test/files/neg/structural.check b/test/files/neg/structural.check
index a0342c4..100b989 100644
--- a/test/files/neg/structural.check
+++ b/test/files/neg/structural.check
@@ -1,19 +1,31 @@
-structural.scala:3: error: illegal dependent method type
-  def f(x: { type D; def m: D }) = x.m
-        ^
-structural.scala:10: error: Parameter type in structural refinement may not refer to abstract type defined outside that same refinement
-    def f1[C <: AnyRef](x: AnyRef{ type D <: AnyRef; def m[E >: Null <: AnyRef](x: A): AnyRef; val x: A }) = x.m[Tata](x.x) //fail
-                                                                                   ^
-structural.scala:11: error: Parameter type in structural refinement may not refer to abstract type defined outside that same refinement
-    def f2[C <: AnyRef](x: AnyRef{ type D <: AnyRef; def m[E >: Null <: AnyRef](x: B): AnyRef; val x: B }) = x.m[Tata](x.x) //fail
-                                                                                   ^
-structural.scala:12: error: Parameter type in structural refinement may not refer to abstract type defined outside that same refinement
-    def f3[C <: AnyRef](x: AnyRef{ type D <: AnyRef; def m[E >: Null <: AnyRef](x: C): AnyRef; val x: C }) = x.m[Tata](x.x) //fail
-                                                                                   ^
+structural.scala:47: error: Parameter type in structural refinement may not refer to the type of that refinement (self type)
+  val s1 = new { def f(p: this.type): Unit = () }
+                     ^
 structural.scala:19: error: illegal dependent method type
-    def f9[C <: AnyRef](x: AnyRef{ type D <: AnyRef; def m[E >: Null <: AnyRef](x: AnyRef): D }) = x.m[Tata](()) //suceed
+    def f9[C <: Object](x: Object{ type D <: Object; def m[E >: Null <: Object](x: Object): D }) = x.m[Tata](null) //fail
                         ^
-structural.scala:42: error: Parameter type in structural refinement may not refer to abstract type defined outside that same refinement
+structural.scala:10: error: Parameter type in structural refinement may not refer to an abstract type defined outside that refinement
+    def f1[C <: Object](x: Object{ type D <: Object; def m[E >: Null <: Object](x: A): Object; val x: A }) = x.m[Tata](x.x) //fail
+                                                         ^
+structural.scala:11: error: Parameter type in structural refinement may not refer to an abstract type defined outside that refinement
+    def f2[C <: Object](x: Object{ type D <: Object; def m[E >: Null <: Object](x: B): Object; val x: B }) = x.m[Tata](x.x) //fail
+                                                         ^
+structural.scala:12: error: Parameter type in structural refinement may not refer to an abstract type defined outside that refinement
+    def f3[C <: Object](x: Object{ type D <: Object; def m[E >: Null <: Object](x: C): Object; val x: C }) = x.m[Tata](x.x) //fail
+                                                         ^
+structural.scala:13: error: Parameter type in structural refinement may not refer to a type member of that refinement
+    def f4[C <: Object](x: Object{ type D <: Object; def m[E >: Null <: Object](x: D): Object; val x: D }) = x.m[Tata](x.x) //fail
+                                                         ^
+structural.scala:42: error: Parameter type in structural refinement may not refer to an abstract type defined outside that refinement
   type Summable[T] = { def +(v : T) : T }
-                                 ^
-6 errors found
+                           ^
+structural.scala:46: error: Parameter type in structural refinement may not refer to the type of that refinement (self type)
+  type S1 = { def f(p: this.type): Unit }
+                  ^
+structural.scala:49: error: Parameter type in structural refinement may not refer to a type member of that refinement
+  type S2 = { type T; def f(p: T): Unit }
+                          ^
+structural.scala:52: error: Parameter type in structural refinement may not refer to an abstract type defined outside that refinement
+  def s3[U >: Null <: Object](p: { def f(p: U): Unit; def u: U }) = ()
+                                       ^
+10 errors found
diff --git a/test/files/neg/structural.scala b/test/files/neg/structural.scala
index ac60a0e..de7b6ef 100644
--- a/test/files/neg/structural.scala
+++ b/test/files/neg/structural.scala
@@ -1,23 +1,23 @@
 object Test extends Application {
   
-  def f(x: { type D; def m: D }) = x.m
+  def f(x: { type D; def m: D }): Null = null
     
   class Tata
   
-  abstract class Toto[A <: AnyRef] {
-    type B <: AnyRef
+  abstract class Toto[A <: Object] {
+    type B <: Object
     
-    def f1[C <: AnyRef](x: AnyRef{ type D <: AnyRef; def m[E >: Null <: AnyRef](x: A): AnyRef; val x: A }) = x.m[Tata](x.x) //fail
-    def f2[C <: AnyRef](x: AnyRef{ type D <: AnyRef; def m[E >: Null <: AnyRef](x: B): AnyRef; val x: B }) = x.m[Tata](x.x) //fail
-    def f3[C <: AnyRef](x: AnyRef{ type D <: AnyRef; def m[E >: Null <: AnyRef](x: C): AnyRef; val x: C }) = x.m[Tata](x.x) //fail
-    def f4[C <: AnyRef](x: AnyRef{ type D <: AnyRef; def m[E >: Null <: AnyRef](x: D): AnyRef; val x: D }) = x.m[Tata](x.x) //suceed
-    def f5[C <: AnyRef](x: AnyRef{ type D <: AnyRef; def m[E >: Null <: AnyRef](x: E): AnyRef; val x: Tata }) = x.m[Tata](x.x) //suceed
+    def f1[C <: Object](x: Object{ type D <: Object; def m[E >: Null <: Object](x: A): Object; val x: A }) = x.m[Tata](x.x) //fail
+    def f2[C <: Object](x: Object{ type D <: Object; def m[E >: Null <: Object](x: B): Object; val x: B }) = x.m[Tata](x.x) //fail
+    def f3[C <: Object](x: Object{ type D <: Object; def m[E >: Null <: Object](x: C): Object; val x: C }) = x.m[Tata](x.x) //fail
+    def f4[C <: Object](x: Object{ type D <: Object; def m[E >: Null <: Object](x: D): Object; val x: D }) = x.m[Tata](x.x) //fail
+    def f5[C <: Object](x: Object{ type D <: Object; def m[E >: Null <: Object](x: E): Object; val x: Tata }) = x.m[Tata](x.x) //suceed
     
-    def f6[C <: AnyRef](x: AnyRef{ type D <: AnyRef; def m[E >: Null <: AnyRef](x: AnyRef): A }) = x.m[Tata](()) //suceed
-    def f7[C <: AnyRef](x: AnyRef{ type D <: AnyRef; def m[E >: Null <: AnyRef](x: AnyRef): B }) = x.m[Tata](()) //suceed
-    def f8[C <: AnyRef](x: AnyRef{ type D <: AnyRef; def m[E >: Null <: AnyRef](x: AnyRef): C }) = x.m[Tata](()) //suceed
-    def f9[C <: AnyRef](x: AnyRef{ type D <: AnyRef; def m[E >: Null <: AnyRef](x: AnyRef): D }) = x.m[Tata](()) //suceed
-    def f0[C <: AnyRef](x: AnyRef{ type D <: AnyRef; def m[E >: Null <: AnyRef](x: AnyRef): E }) = x.m[Tata](()) //suceed
+    def f6[C <: Object](x: Object{ type D <: Object; def m[E >: Null <: Object](x: Object): A }) = x.m[Tata](null) //suceed
+    def f7[C <: Object](x: Object{ type D <: Object; def m[E >: Null <: Object](x: Object): B }) = x.m[Tata](null) //suceed
+    def f8[C <: Object](x: Object{ type D <: Object; def m[E >: Null <: Object](x: Object): C }) = x.m[Tata](null) //suceed
+    def f9[C <: Object](x: Object{ type D <: Object; def m[E >: Null <: Object](x: Object): D }) = x.m[Tata](null) //fail
+    def f0[C <: Object](x: Object{ type D <: Object; def m[E >: Null <: Object](x: Object): E }) = x.m[Tata](null) //suceed
     
   }
   
@@ -26,20 +26,29 @@ object Test extends Application {
     type B = Tata
   }
   
-  toto.f1[Tata](new AnyRef{ type D = Tata; def m[E >: Null <: AnyRef](x: Tata): AnyRef = null; val x = tata })
-  toto.f2[Tata](new AnyRef{ type D = Tata; def m[E >: Null <: AnyRef](x: Tata): AnyRef = null; val x = tata })
-  toto.f3[Tata](new AnyRef{ type D = Tata; def m[E >: Null <: AnyRef](x: Tata): AnyRef = null; val x = tata })
-  toto.f4[Tata](new AnyRef{ type D = Tata; def m[E >: Null <: AnyRef](x: D): AnyRef = null; val x = tata })
-  toto.f5[Tata](new AnyRef{ type D = Tata; def m[E >: Null <: AnyRef](x: E): AnyRef = null; val x = tata })
+  //toto.f1[Tata](new Object{ type D = Tata; def m[E >: Null <: Object](x: Tata): Object = null; val x = tata })
+  //toto.f2[Tata](new Object{ type D = Tata; def m[E >: Null <: Object](x: Tata): Object = null; val x = tata })
+  //toto.f3[Tata](new Object{ type D = Tata; def m[E >: Null <: Object](x: Tata): Object = null; val x = tata })
+  //toto.f4[Tata](new Object{ type D = Tata; def m[E >: Null <: Object](x: D): Object = null; val x = tata })
+  toto.f5[Tata](new Object{ type D = Tata; def m[E >: Null <: Object](x: E): Object = null; val x: Test.Tata = tata })
   
-  toto.f6[Tata](new AnyRef{ type D = Tata; def m[E >: Null <: AnyRef](x: AnyRef): Tata = null })
-  toto.f7[Tata](new AnyRef{ type D = Tata; def m[E >: Null <: AnyRef](x: AnyRef): Tata = null })
-  toto.f8[Tata](new AnyRef{ type D = Tata; def m[E >: Null <: AnyRef](x: AnyRef): Tata = null })
-  toto.f9[Tata](new AnyRef{ type D = Tata; def m[E >: Null <: AnyRef](x: AnyRef): D = null })
-  toto.f0[Tata](new AnyRef{ type D = Tata; def m[E >: Null <: AnyRef](x: AnyRef): E = null })
+  toto.f6[Tata](new Object{ type D = Tata; def m[E >: Null <: Object](x: Object): Tata = null })
+  toto.f7[Tata](new Object{ type D = Tata; def m[E >: Null <: Object](x: Object): Tata = null })
+  toto.f8[Tata](new Object{ type D = Tata; def m[E >: Null <: Object](x: Object): Tata = null })
+  //toto.f9[Tata](new Object{ type D = Tata; def m[E >: Null <: Object](x: Object): D = null })
+  toto.f0[Tata](new Object{ type D = Tata; def m[E >: Null <: Object](x: Object): E = null })
   
   /* Bug #1246 */
   type Summable[T] = { def +(v : T) : T }
   def sum[T <: Summable[T]](xs : List[T]) = xs.reduceLeft[T](_ + _)
   
-}
\ No newline at end of file
+  /* Bug #1004 & #967 */
+  type S1 = { def f(p: this.type): Unit }
+  val s1 = new { def f(p: this.type): Unit = () }
+  
+  type S2 = { type T; def f(p: T): Unit }
+  //val s2: S2 = new { type T = A; def f(p: T): Unit = () }
+  
+  def s3[U >: Null <: Object](p: { def f(p: U): Unit; def u: U }) = ()
+  
+}
diff --git a/test/files/neg/switch.check b/test/files/neg/switch.check
new file mode 100644
index 0000000..7212c1a
--- /dev/null
+++ b/test/files/neg/switch.check
@@ -0,0 +1,10 @@
+switch.scala:28: error: could not emit switch for @switch annotated match
+  def fail1(c: Char) = (c: @switch) match {
+                                    ^
+switch.scala:38: error: could not emit switch for @switch annotated match
+  def fail2(c: Char) = (c: @switch @unchecked) match {
+                                               ^
+switch.scala:45: error: could not emit switch for @switch annotated match
+  def fail3(c: Char) = (c: @unchecked @switch) match {
+                                               ^
+three errors found
diff --git a/test/files/neg/switch.scala b/test/files/neg/switch.scala
new file mode 100644
index 0000000..a3dfd86
--- /dev/null
+++ b/test/files/neg/switch.scala
@@ -0,0 +1,66 @@
+import scala.annotation.switch
+
+// this is testing not so much how things ought to be but how they are;
+// the test is supposed to start failing if the behavior changes at all.
+object Other {
+  val C1 = 'P'                // fails: not final
+  final val C2 = 'Q'          // succeeds: singleton type Char('Q') inferred
+  final val C3: Char = 'R'    // fails: type Char specified
+  final val C4 = '\u000A'     // succeeds like C2 but more unicodey
+}
+
+object Main {
+  def succ1(c: Char) = (c: @switch) match {
+    case 'A' | 'B' | 'C'  => true
+    case 'd'              => true
+    case 'f' | 'g'        => true
+    case _                => false
+  }
+  
+  def succ2(c: Char) = (c: @switch) match {
+    case 'A' | 'B' | 'C'  => true
+    case Other.C2         => true
+    case Other.C4         => true
+    case _                => false
+  }
+  
+  // has a guard
+  def fail1(c: Char) = (c: @switch) match {
+    case 'A' | 'B' | 'C'  => true
+    case x if x == 'A'    => true
+    case _                => false
+  }
+  
+  // throwing in @unchecked on the next two to make sure
+  // multiple annotations are processed correctly
+  
+  // thinks a val in an object is constant... so naive
+  def fail2(c: Char) = (c: @switch @unchecked) match {
+    case 'A'        => true
+    case Other.C1   => true
+    case _          => false
+  }
+  
+  // more naivete
+  def fail3(c: Char) = (c: @unchecked @switch) match {
+    case 'A'        => true
+    case Other.C3   => true
+    case _          => false
+  }
+  
+  // guard case done correctly
+  def succ3(c: Char) = (c: @switch) match {
+    case 'A' | 'B' | 'C'  => true
+    case x                => x == 'A'
+  }
+  
+  // some ints just to mix it up a bit
+  def succ4(x: Int, y: Int) = ((x+y): @switch) match {
+    case  1 => 5
+    case  2 => 10
+    case  3 => 20
+    case  4 => 50
+    case 5|6|7|8 => 100
+    case _  => -1
+  }    
+}
diff --git a/test/files/neg/t0003.check b/test/files/neg/t0003.check
index 5e29b18..fb5bb56 100644
--- a/test/files/neg/t0003.check
+++ b/test/files/neg/t0003.check
@@ -1,6 +1,6 @@
 t0003.scala:2: error: type mismatch;
  found   : (A) => (B) => B
- required: (?) => B
+ required: (A) => B
   def foo[A, B, C](l: List[A], f: A => B=>B, g: B=>B=>C): List[C] = l map (g compose f)
                                                                                      ^
 one error found
diff --git a/test/files/neg/t0015.check b/test/files/neg/t0015.check
index 2979237..eb25fc4 100644
--- a/test/files/neg/t0015.check
+++ b/test/files/neg/t0015.check
@@ -3,9 +3,4 @@ t0015.scala:5: error: type mismatch;
  required: (Nothing) => ?
    Nil.map(f _)
            ^
-t0015.scala:21: error: type mismatch;
- found   : M
- required: M.this.selfType
-    f[Int](self: selfType)
-           ^
-two errors found
+one error found
diff --git a/test/files/neg/t0015.scala b/test/files/neg/t0015.scala
index 35a6cd1..225197f 100644
--- a/test/files/neg/t0015.scala
+++ b/test/files/neg/t0015.scala
@@ -18,7 +18,7 @@ abstract class M
     // compiles successfully
     //f[Int](self: actualSelfType)
 
-    f[Int](self: selfType)
+    f[Int](self: selfType) // compiles Ok now was well, because we narrow to singletonType in this situation
 
     //def g(x: Any) = {}
     //g(self: selfType)
diff --git a/test/files/neg/t0117.check b/test/files/neg/t0117.check
index 53b5bd9..fd6af54 100644
--- a/test/files/neg/t0117.check
+++ b/test/files/neg/t0117.check
@@ -1,4 +1,4 @@
 t0117.scala:2: error: implementation restriction: traits may not select fields or methods from to super[C] where C is a class
 trait B extends A { println(super[A].a) }
-                                  ^
+                            ^
 one error found
diff --git a/test/files/neg/t0152.check b/test/files/neg/t0152.check
index 562e6f1..84f78dc 100644
--- a/test/files/neg/t0152.check
+++ b/test/files/neg/t0152.check
@@ -1,6 +1,6 @@
 t0152.scala:10: error: illegal inheritance;
  object boom inherits different type instances of class Value:
 Value[Int] and Value[java.lang.String]
- object boom extends Value[java.lang.String]("foo") with PlusOne
+ object boom extends Value[java.lang.String]("foo") with PlusOne
         ^
 one error found
diff --git a/test/files/neg/t0204.check b/test/files/neg/t0204.check
index 27b88d2..0f7acfd 100644
--- a/test/files/neg/t0204.check
+++ b/test/files/neg/t0204.check
@@ -1,4 +1,4 @@
 t0204.scala:4: error: class type required but Program.A{type T = String} found
- trait C extends B
+ trait C extends B
                  ^
 one error found
diff --git a/test/files/neg/t0218.check b/test/files/neg/t0218.check
index c7a6d95..6bb7591 100644
--- a/test/files/neg/t0218.check
+++ b/test/files/neg/t0218.check
@@ -1,4 +1,4 @@
 t0218.scala:10: error: class type required but APQ.this.P found
-    List(new PP) 
+    List(new PP) 
              ^
 one error found
diff --git a/test/files/neg/t0218.scala b/test/files/neg/t0218.scala
index 4d4cc52..3d1f52e 100644
--- a/test/files/neg/t0218.scala
+++ b/test/files/neg/t0218.scala
@@ -6,7 +6,7 @@ trait APQ {
 
   type PP = P
 
-  def pq(numQueens: int, numRows: int) : List[Placement] = {
+  def pq(numQueens: Int, numRows: Int) : List[Placement] = {
     List(new PP) 
   }
 }
diff --git a/test/files/neg/t0226.check b/test/files/neg/t0226.check
index 1d9f707..af81e41 100644
--- a/test/files/neg/t0226.check
+++ b/test/files/neg/t0226.check
@@ -4,7 +4,7 @@ t0226.scala:5: error: not found: type A1
 t0226.scala:5: error: not found: type A1
       (implicit _1: Foo[List[A1]], _2: Foo[A2]): Foo[Tuple2[List[A1], A2]] =
                              ^
-t0226.scala:8: error: no implicit argument matching parameter type Test.this.Foo[((List[Char], Int), (object Nil, Int))] was found.
+t0226.scala:8: error: could not find implicit value for parameter rep: Test.this.Foo[((List[Char], Int), (object Nil, Int))]
   foo(((List('b'), 3), (Nil, 4)))
-  ^
+     ^
 three errors found
diff --git a/test/files/neg/t0259.check b/test/files/neg/t0259.check
index 8c6ce1d..24e35e6 100644
--- a/test/files/neg/t0259.check
+++ b/test/files/neg/t0259.check
@@ -1,7 +1,7 @@
 t0259.scala:4: error: double definition:
-constructor TestCase3:(String*)test.TestCase3 and
-constructor TestCase3:((String, Int)*)test.TestCase3 at line 3
-have same type after erasure: (Seq)test.TestCase3
+constructor TestCase3:(groups: String*)test.TestCase3 and
+constructor TestCase3:(groups: (String, Int)*)test.TestCase3 at line 3
+have same type after erasure: (groups: Seq)test.TestCase3
   def this( groups: String*) = this()
       ^
 one error found
diff --git a/test/files/neg/t0345.check b/test/files/neg/t0345.check
index f4a5275..1e55d01 100644
--- a/test/files/neg/t0345.check
+++ b/test/files/neg/t0345.check
@@ -1,4 +1,4 @@
-t0345.scala:2: error: object creation impossible, since method cons in trait Lizt of type (Nothing)Unit is not defined
-    val empty = new Lizt[Nothing] {
-                ^
+t0345.scala:2: error: object creation impossible, since method cons in trait Lizt of type (a: Nothing)Unit is not defined
+    val empty = new Lizt[Nothing] {
+                    ^
 one error found
diff --git a/test/files/neg/t0351.check b/test/files/neg/t0351.check
index d374c90..ce10605 100644
--- a/test/files/neg/t0351.check
+++ b/test/files/neg/t0351.check
@@ -1,4 +1,4 @@
 t0351.scala:2: error: no by-name parameter type allowed here
-  def identity[T](x : => T) : (=> T)
+  def identity[T](x : => T) : (=> T)
                                ^
 one error found
diff --git a/test/files/neg/t0528neg.scala b/test/files/neg/t0528neg.scala
index 911745b..30d20c9 100644
--- a/test/files/neg/t0528neg.scala
+++ b/test/files/neg/t0528neg.scala
@@ -3,7 +3,7 @@ trait Sequ[+A] {
 }
 
 class RichStr extends Sequ[Char] {
-  // override to a primitve array
+  // override to a primitive array
   def toArray: Array[Char] = new Array[Char](10)
 }
 
diff --git a/test/files/neg/t0590.check b/test/files/neg/t0590.check
index b928c1c..a3ef70c 100644
--- a/test/files/neg/t0590.check
+++ b/test/files/neg/t0590.check
@@ -1,5 +1,6 @@
-t0590.scala:2: error: diverging implicit expansion for type (Null(null)) => T
-starting with method foo in object Test
+t0590.scala:2: error: type mismatch;
+ found   : Null(null)
+ required: T
   implicit def foo[T] : T = null
                             ^
 one error found
diff --git a/test/files/neg/t0673.check b/test/files/neg/t0673.check
new file mode 100644
index 0000000..cc67e99
--- /dev/null
+++ b/test/files/neg/t0673.check
@@ -0,0 +1,4 @@
+Test.scala:2: error: object InnerClass is not a value
+  val x = JavaClass.InnerClass
+                    ^
+one error found
diff --git a/test/pending/neg/t0673/JavaClass.java b/test/files/neg/t0673/JavaClass.java
similarity index 100%
rename from test/pending/neg/t0673/JavaClass.java
rename to test/files/neg/t0673/JavaClass.java
diff --git a/test/pending/neg/t0673/Test.scala b/test/files/neg/t0673/Test.scala
similarity index 100%
rename from test/pending/neg/t0673/Test.scala
rename to test/files/neg/t0673/Test.scala
diff --git a/test/pending/neg/t0699.check b/test/files/neg/t0699.check
similarity index 100%
rename from test/pending/neg/t0699.check
rename to test/files/neg/t0699.check
diff --git a/test/files/neg/t0699/A.scala b/test/files/neg/t0699/A.scala
new file mode 100644
index 0000000..a75ebbd
--- /dev/null
+++ b/test/files/neg/t0699/A.scala
@@ -0,0 +1,4 @@
+object A {
+  sealed trait T
+  sealed class C
+}
diff --git a/test/files/neg/t0699/B.scala b/test/files/neg/t0699/B.scala
new file mode 100644
index 0000000..d27ad16
--- /dev/null
+++ b/test/files/neg/t0699/B.scala
@@ -0,0 +1,5 @@
+object B {
+  trait T1 extends A.T
+  trait T2 extends A.C
+  class C1 extends A.C
+}
diff --git a/test/files/neg/t0842.check b/test/files/neg/t0842.check
index 5f88f08..3351aa1 100644
--- a/test/files/neg/t0842.check
+++ b/test/files/neg/t0842.check
@@ -1,4 +1,4 @@
 t0842.scala:1: error: A.this.type does not take type parameters
-trait A[T] { def m: this.type[T] = this }
+trait A[T] { def m: this.type[T] = this }
                         ^
 one error found
diff --git a/test/files/neg/t1163.check b/test/files/neg/t1163.check
index c96ec73..69e6b7a 100644
--- a/test/files/neg/t1163.check
+++ b/test/files/neg/t1163.check
@@ -1,5 +1,5 @@
-t1163.scala:2: error: error overriding method foo in trait Sub of type => Sub;
- method foo in trait Super of type => Super has incompatible type => Super;
+t1163.scala:2: error: overriding method foo in trait Sub of type => Sub;
+ method foo in trait Super of type => Super has incompatible type;
  (Note that method foo in trait Sub of type => Sub is abstract,
   and is therefore overridden by concrete method foo in trait Super of type => Super)
 trait Sub extends Super { override def foo: Sub }
diff --git a/test/files/neg/t1215.check b/test/files/neg/t1215.check
index 1f9dd6b..77a9304 100644
--- a/test/files/neg/t1215.check
+++ b/test/files/neg/t1215.check
@@ -1,4 +1,4 @@
 t1215.scala:2: error: value += is not a member of Int
   val x = 1 += 1
-            ^
+          ^
 one error found
diff --git a/test/files/neg/t1355.check b/test/files/neg/t1355.check
new file mode 100644
index 0000000..f9786e9
--- /dev/null
+++ b/test/files/neg/t1355.check
@@ -0,0 +1,4 @@
+t1355.scala:1: error: type arguments [A[T]] do not conform to trait A's type parameter bounds [T <: A[A[T]]]
+trait A[T <: A[A[T]]]
+             ^
+one error found
diff --git a/test/files/neg/t1355.scala b/test/files/neg/t1355.scala
new file mode 100644
index 0000000..3e5e375
--- /dev/null
+++ b/test/files/neg/t1355.scala
@@ -0,0 +1 @@
+trait A[T <: A[A[T]]]
\ No newline at end of file
diff --git a/test/files/neg/t1422.check b/test/files/neg/t1422.check
new file mode 100644
index 0000000..5931fcb
--- /dev/null
+++ b/test/files/neg/t1422.check
@@ -0,0 +1,4 @@
+t1422.scala:1: error: private[this] not allowed for case class parameters
+case class A(private[this] val foo:String)
+                               ^
+one error found
diff --git a/test/files/neg/t1422.scala b/test/files/neg/t1422.scala
new file mode 100644
index 0000000..751f05a
--- /dev/null
+++ b/test/files/neg/t1422.scala
@@ -0,0 +1 @@
+case class A(private[this] val foo:String)
diff --git a/test/files/neg/t1477.check b/test/files/neg/t1477.check
new file mode 100644
index 0000000..e497637
--- /dev/null
+++ b/test/files/neg/t1477.check
@@ -0,0 +1,5 @@
+t1477.scala:13: error: overriding type V in trait C with bounds >: Nothing <: Middle.this.D;
+ type V is a volatile type; cannot override a type with non-volatile upper bound
+    type V <: (D with U)
+         ^
+one error found
diff --git a/test/files/neg/t1477.scala b/test/files/neg/t1477.scala
new file mode 100644
index 0000000..3ecd275
--- /dev/null
+++ b/test/files/neg/t1477.scala
@@ -0,0 +1,25 @@
+object Test extends Application {
+ trait A
+ trait B extends A
+
+  trait C {
+    type U
+    trait D { type T >: B <: A }
+    type V <: D
+    val y: V#T = new B { }
+  }
+ 
+  trait Middle extends C {
+    type V <: (D with U)
+  }
+
+  class D extends Middle {
+    trait E
+    trait F { type T = E }
+    type U = F
+    def frob(arg : E) : E = arg
+    frob(y)
+  }
+
+  new D
+}
diff --git a/test/files/neg/t1659.check b/test/files/neg/t1659.check
deleted file mode 100644
index b566cfc..0000000
--- a/test/files/neg/t1659.check
+++ /dev/null
@@ -1,5 +0,0 @@
-t1659.scala:3: error: error overriding method u in trait W of type [A](Y{type X = A})Unit;
- method u has incompatible type [A](Y{type X = A})Null
-class Z extends W { def u[A](v : Y { type X = A }) = null }
-                        ^
-one error found
diff --git a/test/files/neg/t1701.check b/test/files/neg/t1701.check
new file mode 100644
index 0000000..782b690
--- /dev/null
+++ b/test/files/neg/t1701.check
@@ -0,0 +1,4 @@
+t1701.scala:1: error: java.lang.Cloneable does not take type parameters
+class A extends java.lang.Cloneable[String, Option, Int]
+                          ^
+one error found
diff --git a/test/files/neg/t1701.scala b/test/files/neg/t1701.scala
new file mode 100644
index 0000000..7cd6ff9
--- /dev/null
+++ b/test/files/neg/t1701.scala
@@ -0,0 +1 @@
+class A extends java.lang.Cloneable[String, Option, Int]
diff --git a/test/files/neg/t1705.check b/test/files/neg/t1705.check
new file mode 100644
index 0000000..7f75bd0
--- /dev/null
+++ b/test/files/neg/t1705.check
@@ -0,0 +1,7 @@
+t1705.scala:9: error: can't existentially abstract over parameterized type this.T[Z]
+    val c = new C{
+            ^
+t1705.scala:14: error: can't existentially abstract over parameterized type C[String]
+    val x1 = {
+             ^
+two errors found
diff --git a/test/files/neg/t1705.scala b/test/files/neg/t1705.scala
new file mode 100644
index 0000000..bf1fcea
--- /dev/null
+++ b/test/files/neg/t1705.scala
@@ -0,0 +1,35 @@
+package trials
+object crashing {
+  trait C {
+    abstract class T[A] {
+      def f[Z] (a:T[Z]) : T[A]
+    }
+  }
+  abstract class Thing {
+    val c = new C{
+      class T[A](a:A) {
+        def f[Z](t:T[Z]) = new T(a)
+      }
+    }
+    val x1 = {
+      class C[T] { val x: T }
+      new C[String]
+    }
+  }
+}
+/* 
+
+Infinite loop in Typer.addLocals. Printing all calls to it:
+
+addLocals: Unit
+addLocals: this.T[A]
+addLocals: java.lang.Object with crashing.C{ ... }
+addLocals: >: Nothing <: java.lang.Object with crashing.C{type T[A] <: java.lang.Object with ScalaObject{def f[Z](this.T[Z]): this.T[A]}}
+addLocals: >: Nothing <: java.lang.Object with ScalaObject{def f[Z](this.T[Z]): this.T[Z]}
+addLocals: >: Nothing <: java.lang.Object with ScalaObject{def f[Z](this.T[Z]): this.T[Z]}
+addLocals: >: Nothing <: java.lang.Object with ScalaObject{def f[Z](this.T[Z]): this.T[Z]}
+[...]
+*
+  C { type T[A] <: { def f[Z]: T[Z] => T[A] } }
+
+*/
diff --git a/test/files/neg/t2031.check b/test/files/neg/t2031.check
new file mode 100644
index 0000000..74aa6c9
--- /dev/null
+++ b/test/files/neg/t2031.check
@@ -0,0 +1,6 @@
+t2031.scala:8: error: polymorphic expression cannot be instantiated to expected type;
+ found   : [A]scala.collection.mutable.Builder[A,scala.collection.immutable.TreeSet[A]]
+ required: scala.collection.generic.CanBuildFrom[scala.collection.immutable.TreeSet[Int],Int,?]
+ res0.map(x => x)(TreeSet.newBuilder)
+                          ^
+one error found
diff --git a/test/files/neg/t2031.scala b/test/files/neg/t2031.scala
new file mode 100644
index 0000000..e4708c4
--- /dev/null
+++ b/test/files/neg/t2031.scala
@@ -0,0 +1,9 @@
+import scala.collection.immutable._
+
+object Test extends Application {
+ val res0 = TreeSet(1, 2, 3)
+
+ //res0.map(x => x)(TreeSet.newBuilder[Int])
+
+ res0.map(x => x)(TreeSet.newBuilder)
+}
diff --git a/test/files/neg/t2130.check b/test/files/neg/t2130.check
new file mode 100644
index 0000000..6d6902b
--- /dev/null
+++ b/test/files/neg/t2130.check
@@ -0,0 +1,4 @@
+t2130.scala:4: error: implementation restriction: package object foo cannot contain case class X
+    case class X()
+               ^
+one error found
diff --git a/test/files/neg/t2130.scala b/test/files/neg/t2130.scala
new file mode 100644
index 0000000..012698f
--- /dev/null
+++ b/test/files/neg/t2130.scala
@@ -0,0 +1,6 @@
+// for now we disallow case class in package objects
+package object foo {
+
+    case class X()
+
+}
diff --git a/test/files/neg/t2139.check b/test/files/neg/t2139.check
new file mode 100644
index 0000000..e26f290
--- /dev/null
+++ b/test/files/neg/t2139.check
@@ -0,0 +1,6 @@
+t2139.scala:13: error: type mismatch;
+ found   : Int(4)
+ required: Nothing
+  val z:Int=(u.f _)(4)
+                    ^
+one error found
diff --git a/test/files/neg/t2139.scala b/test/files/neg/t2139.scala
new file mode 100644
index 0000000..4f09b5a
--- /dev/null
+++ b/test/files/neg/t2139.scala
@@ -0,0 +1,15 @@
+/*
+  NOTE: if inference is changed so that
+        T is inferred to be Int, rather than Nothing,
+        the piece of code below will start to compile OK.
+        In that case, see ticket #2139, and make sure that
+        the generated code will no longer crash!
+*/
+class U {
+  def f[T](x:T):T=x
+}
+object H extends Application {
+  val u=new U
+  val z:Int=(u.f _)(4)
+  println("done")
+}
diff --git a/test/files/neg/t2179.check b/test/files/neg/t2179.check
new file mode 100644
index 0000000..aa94fab
--- /dev/null
+++ b/test/files/neg/t2179.check
@@ -0,0 +1,9 @@
+t2179.scala:2: error: inferred type arguments [scala.collection.immutable.Seq[Double]{def companion: scala.collection.generic.GenericCompanion[scala.collection.immutable.Seq[Any]]; protected def thisCollection: Seq[Double]{def companion: scala.collection.generic.GenericCompanion[Seq[Any]]}}] do not conform to method reduceLeft's type parameter bounds [B >: List[Double]]
+  (Nil:List[List[Double]]).reduceLeft((_: Any, _: Any) => Nil.indices.map(_ => 0d))
+                           ^
+t2179.scala:2: error: type mismatch;
+ found   : (Any, Any) => scala.collection.immutable.IndexedSeq[Double]
+ required: (scala.collection.immutable.Seq[Double]{def companion: scala.collection.generic.GenericCompanion[scala.collection.immutable.Seq[Any]]; protected def thisCollection: Seq[Double]{def companion: scala.collection.generic.GenericCompanion[Seq[Any]]}}, List[Double]) => scala.collection.immutable.Seq[Double]{def companion: scala.collection.generic.GenericCompanion[scala.collection.immutable.Seq[Any]]; protected def thisCollection: Seq[Double]{def companion: scala.collection.generic.G [...]
+  (Nil:List[List[Double]]).reduceLeft((_: Any, _: Any) => Nil.indices.map(_ => 0d))
+                                                       ^
+two errors found
diff --git a/test/files/neg/t2179.scala b/test/files/neg/t2179.scala
new file mode 100644
index 0000000..89e22b6
--- /dev/null
+++ b/test/files/neg/t2179.scala
@@ -0,0 +1,3 @@
+object Test {
+  (Nil:List[List[Double]]).reduceLeft((_: Any, _: Any) => Nil.indices.map(_ => 0d))
+}
diff --git a/test/files/neg/t2208.check b/test/files/neg/t2208.check
new file mode 100644
index 0000000..a97b20c
--- /dev/null
+++ b/test/files/neg/t2208.check
@@ -0,0 +1,4 @@
+t2208.scala:7: error: type arguments [Any] do not conform to type Alias's type parameter bounds [X <: Test.A]
+	class C extends Alias[Any]   // not ok, normalisation should check bounds before expanding Alias
+                        ^
+one error found
\ No newline at end of file
diff --git a/test/files/neg/t2208.scala b/test/files/neg/t2208.scala
new file mode 100644
index 0000000..43bb0ad
--- /dev/null
+++ b/test/files/neg/t2208.scala
@@ -0,0 +1,8 @@
+object Test  {
+	class A
+
+	class B[X]
+	type Alias[X <: A] = B[X]
+
+	class C extends Alias[Any]   // not ok, normalisation should check bounds before expanding Alias
+}
\ No newline at end of file
diff --git a/test/files/neg/t2316.check b/test/files/neg/t2316.check
new file mode 100644
index 0000000..fea1745
--- /dev/null
+++ b/test/files/neg/t2316.check
@@ -0,0 +1,7 @@
+t2316.scala:28: error: ambiguous implicit values:
+ both method T1FromT3 in object T1 of type (implicit t3: test.T3)test.T1
+ and method T1FromT2 in object T1 of type (implicit t2: test.T2)test.T1
+ match expected type test.T1
+      val t1 = requireT1
+               ^
+one error found
diff --git a/test/files/neg/t2316.scala b/test/files/neg/t2316.scala
new file mode 100644
index 0000000..ccda9d5
--- /dev/null
+++ b/test/files/neg/t2316.scala
@@ -0,0 +1,43 @@
+object test {
+  case class T1(val source: String)
+
+
+  object T1 {
+    implicit def T1FromT2(implicit t2: T2): T1 = T1("implicit def T1FromT2")
+    implicit def T1FromT3(implicit t3: T3): T1 = T1("implicit def T1FromT3")
+  }
+
+  trait T2 {
+  }
+
+  object T2 {
+    implicit val t2: T2 = new T2 {}
+  }
+
+  trait T3
+
+  def requireT1(implicit t1: T1) = t1
+
+  {
+      val t1 = requireT1
+      assert(t1.source == "implicit def T1FromT2")
+  }
+
+  {
+      implicit def t3: T3 = new T3 {}
+      val t1 = requireT1
+      assert(t1.source == "implicit def T1FromT2")
+
+      // Expected a compile error here, but because T1.T1FromT2(T2.t2) was cached as a non-local implicit
+      // expression for type T1, this is not checked!
+      //
+      // (fragment of implicit-cache-error2.scala):26: error: ambiguous implicit values:
+      // both method T1FromT3 in object T1 of type (implicit t3: this.T3)this.T1
+      // and method T1FromT2 in object T1 of type (implicit t2: this.T2)this.T1
+      // match expected type this.T1
+      //    val t1 = requireT1
+      //              ^
+      // one error found
+
+  }
+}
\ No newline at end of file
diff --git a/test/files/neg/t2336.check b/test/files/neg/t2336.check
new file mode 100644
index 0000000..9837174
--- /dev/null
+++ b/test/files/neg/t2336.check
@@ -0,0 +1,4 @@
+t2336.scala:6: error: type Foo[Int] is not a stable prefix
+  new Foo[Int]#Bar(0)
+               ^
+one error found
diff --git a/test/files/neg/t2336.scala b/test/files/neg/t2336.scala
new file mode 100644
index 0000000..4cea02b
--- /dev/null
+++ b/test/files/neg/t2336.scala
@@ -0,0 +1,7 @@
+// we get now: t2336.scala:5: error: type Foo[Int] is not a stable prefix
+class Foo[A] {
+  class Bar[B >: A](x: B) extends Foo[B]
+}
+object bug {
+  new Foo[Int]#Bar(0)
+}
diff --git a/test/files/neg/t2386.check b/test/files/neg/t2386.check
new file mode 100644
index 0000000..2caa46c
--- /dev/null
+++ b/test/files/neg/t2386.check
@@ -0,0 +1,4 @@
+t2386.scala:2: error: could not find implicit value for evidence parameter of type scala.reflect.ClassManifest[Array[_ >: java.lang.String with Int]]
+  val a = Array(Array(1, 2), Array("a","b"))
+               ^
+one error found
diff --git a/test/files/neg/t2386.scala b/test/files/neg/t2386.scala
new file mode 100644
index 0000000..56146cc
--- /dev/null
+++ b/test/files/neg/t2386.scala
@@ -0,0 +1,3 @@
+object Test {
+  val a = Array(Array(1, 2), Array("a","b"))
+}
diff --git a/test/files/neg/t2416.check b/test/files/neg/t2416.check
new file mode 100644
index 0000000..0899ad0
--- /dev/null
+++ b/test/files/neg/t2416.check
@@ -0,0 +1,10 @@
+t2416.scala:3: error: type arguments [Int] do not conform to trait A's type parameter bounds [X <: Double]
+  def x : A[Int]#B = 10 // no you won't
+          ^
+t2416.scala:8: error: type arguments [Boolean] do not conform to type B's type parameter bounds [Y <: Double]
+  def x : A#B[Boolean] = 10 // seriously?
+            ^
+t2416.scala:13: error: type arguments [String] do not conform to type B's type parameter bounds [Z <: Double]
+  type C[Z <: A] = Z#B[String] // nuh-uh!
+                     ^
+three errors found
diff --git a/test/files/neg/t2416.scala b/test/files/neg/t2416.scala
new file mode 100644
index 0000000..6bb57a9
--- /dev/null
+++ b/test/files/neg/t2416.scala
@@ -0,0 +1,14 @@
+object t2416a {
+  trait A[X <: Double] { type B = X }
+  def x : A[Int]#B = 10 // no you won't
+}
+
+object t2416b {
+  trait A{type B[Y <: Double] = Int}
+  def x : A#B[Boolean] = 10 // seriously?
+}
+
+object t2416c {
+  trait A{type B[Z <: Double] = Int}
+  type C[Z <: A] = Z#B[String] // nuh-uh!
+}
\ No newline at end of file
diff --git a/test/files/neg/t2421b.check b/test/files/neg/t2421b.check
new file mode 100644
index 0000000..f666a7d
--- /dev/null
+++ b/test/files/neg/t2421b.check
@@ -0,0 +1,4 @@
+t2421b.scala:12: error: could not find implicit value for parameter aa: Test.F[Test.A]
+  f
+  ^
+one error found
\ No newline at end of file
diff --git a/test/files/neg/t2421b.scala b/test/files/neg/t2421b.scala
new file mode 100644
index 0000000..a8d22f2
--- /dev/null
+++ b/test/files/neg/t2421b.scala
@@ -0,0 +1,17 @@
+object Test {
+  class A
+  class B
+  class C
+  class F[X]
+
+  def f(implicit aa: F[A]) = println(aa)
+
+  // implicit def a : F[A] = new F[A]()
+  implicit def b[X <: B] = new F[X]()
+
+  f
+}
+
+/* bug: 
+error: type arguments [Test2.A] do not conform to method b's type parameter bounds [X <: Test2.B]
+*/
\ No newline at end of file
diff --git a/test/files/neg/t2462a.check b/test/files/neg/t2462a.check
new file mode 100644
index 0000000..040a01f
--- /dev/null
+++ b/test/files/neg/t2462a.check
@@ -0,0 +1,4 @@
+t2462a.scala:2: error: Cannot construct a collection of type List[String] with elements of type Int based on a collection of type List[String].
+  List(1,2,3).map[Int, List[String]](x => 1)
+                                    ^
+one error found
diff --git a/test/files/neg/t2462a.scala b/test/files/neg/t2462a.scala
new file mode 100644
index 0000000..2d523b4
--- /dev/null
+++ b/test/files/neg/t2462a.scala
@@ -0,0 +1,3 @@
+object Test {
+  List(1,2,3).map[Int, List[String]](x => 1)
+}
\ No newline at end of file
diff --git a/test/files/neg/t2462b.check b/test/files/neg/t2462b.check
new file mode 100644
index 0000000..bc0d9aa
--- /dev/null
+++ b/test/files/neg/t2462b.check
@@ -0,0 +1,14 @@
+t2462b.scala:6: warning: Invalid implicitNotFound message for trait Meh in package test:
+The type parameters Too, Elem referenced in the message of the @implicitNotFound annotation are not defined by trait Meh.
+trait Meh[-From, +To]
+      ^
+t2462b.scala:9: warning: Invalid implicitNotFound message for trait Meh2 in package test:
+The type parameter Elem referenced in the message of the @implicitNotFound annotation is not defined by trait Meh2.
+trait Meh2[-From, +To]
+      ^
+t2462b.scala:12: error: overriding method x in class thankyoupartest of type => Int;
+ method x needs `override' modifier
+class testmustfail extends thankyoupartest { def x = 43 }
+                                                 ^
+two warnings found
+one error found
diff --git a/test/files/neg/t2462b.scala b/test/files/neg/t2462b.scala
new file mode 100644
index 0000000..7a1389c
--- /dev/null
+++ b/test/files/neg/t2462b.scala
@@ -0,0 +1,12 @@
+package test
+
+import scala.annotation.implicitNotFound
+
+ at implicitNotFound(msg = "Cannot construct a collection of type ${Too} with elements of type ${Elem} based on a collection of type ${From}.")
+trait Meh[-From, +To]
+
+ at implicitNotFound(msg = "Cannot construct a collection of type ${To} ${Elem}.")
+trait Meh2[-From, +To]
+
+class thankyoupartest { def x = 42 }
+class testmustfail extends thankyoupartest { def x = 43 }
diff --git a/test/files/neg/t2494.check b/test/files/neg/t2494.check
new file mode 100644
index 0000000..6d43011
--- /dev/null
+++ b/test/files/neg/t2494.check
@@ -0,0 +1,4 @@
+t2494.scala:1: error: recursive value a needs type
+object A { val a = { println("a = " + a); a = 1} }
+                                      ^
+one error found
diff --git a/test/files/neg/t2494.scala b/test/files/neg/t2494.scala
new file mode 100644
index 0000000..71e6bc4
--- /dev/null
+++ b/test/files/neg/t2494.scala
@@ -0,0 +1 @@
+object A { val a = { println("a = " + a); a = 1} }
diff --git a/test/files/neg/t2641.check b/test/files/neg/t2641.check
new file mode 100644
index 0000000..771624e
--- /dev/null
+++ b/test/files/neg/t2641.check
@@ -0,0 +1,35 @@
+t2641.scala:19: error: illegal cyclic reference involving trait ManagedSeq
+        with TraversableViewLike[A, ManagedSeqStrict[A], ManagedSeq[A]]
+                                                         ^
+t2641.scala:17: error: illegal inheritance;
+ self-type ManagedSeq does not conform to ManagedSeqStrict[A]'s selftype ManagedSeqStrict[A]
+        extends ManagedSeqStrict[A]
+                ^
+t2641.scala:18: error: illegal inheritance;
+ self-type ManagedSeq does not conform to scala.collection.TraversableView[A,ManagedSeqStrict[A]]'s selftype scala.collection.TraversableView[A,ManagedSeqStrict[A]]
+        with TraversableView[A, ManagedSeqStrict[A]]
+             ^
+t2641.scala:17: error: illegal inheritance;
+ self-type ManagedSeq does not conform to ScalaObject's selftype ScalaObject
+        extends ManagedSeqStrict[A]
+        ^
+t2641.scala:25: error: something is wrong (wrong class file?): trait ManagedSeq with type parameters [A,Coll] gets applied to arguments [], phase = typer
+  trait Transformed[+B] extends ManagedSeq[B, Coll] with super.Transformed[B]
+        ^
+t2641.scala:27: error: something is wrong (wrong class file?): trait ManagedSeq with type parameters [A,Coll] gets applied to arguments [], phase = namer
+  trait Sliced extends Transformed[A] with super.Sliced {
+               ^
+t2641.scala:27: error: illegal inheritance; superclass Any
+ is not a subclass of the superclass ManagedSeqStrict
+ of the mixin trait Transformed
+  trait Sliced extends Transformed[A] with super.Sliced {
+                       ^
+t2641.scala:27: error: illegal inheritance; superclass Any
+ is not a subclass of the superclass Object
+ of the mixin trait Sliced
+  trait Sliced extends Transformed[A] with super.Sliced {
+                                                 ^
+t2641.scala:28: error: value managedIterator is not a member of ManagedSeq
+    override def managedIterator = self.managedIterator slice (from, until)
+                                        ^
+9 errors found
diff --git a/test/files/neg/t2641.scala b/test/files/neg/t2641.scala
new file mode 100644
index 0000000..68a4ca3
--- /dev/null
+++ b/test/files/neg/t2641.scala
@@ -0,0 +1,31 @@
+import scala.collection._
+import scala.collection.generic._
+import scala.collection.mutable.Builder
+
+
+abstract class ManagedSeqStrict[+A]
+        extends Traversable[A]
+        with GenericTraversableTemplate[A, ManagedSeqStrict]
+{
+    override def companion: GenericCompanion[ManagedSeqStrict] = null
+   
+    override def foreach[U](f: A => U): Unit =
+        null
+}
+
+trait ManagedSeq[+A, +Coll]
+        extends ManagedSeqStrict[A]
+        with TraversableView[A, ManagedSeqStrict[A]]
+        with TraversableViewLike[A, ManagedSeqStrict[A], ManagedSeq[A]]
+{ self =>
+   
+    override def underlying = throw new Exception("no underlying")
+   
+  //trait Transformed[+B] extends ManagedSeq[B] with super.Transformed[B]
+  trait Transformed[+B] extends ManagedSeq[B, Coll] with super.Transformed[B]
+
+  trait Sliced extends Transformed[A] with super.Sliced {
+    override def managedIterator = self.managedIterator slice (from, until)
+  }
+
+}
diff --git a/test/files/neg/t2773.check b/test/files/neg/t2773.check
new file mode 100644
index 0000000..6e88762
--- /dev/null
+++ b/test/files/neg/t2773.check
@@ -0,0 +1,7 @@
+t2773.scala:5: error: x is not a member of c
+  import c.x
+         ^
+t2773.scala:6: error: not found: value x
+  println(x)
+          ^
+two errors found
diff --git a/test/files/neg/t2773.scala b/test/files/neg/t2773.scala
new file mode 100644
index 0000000..aaa6351
--- /dev/null
+++ b/test/files/neg/t2773.scala
@@ -0,0 +1,8 @@
+class C(x: Int) { def foo = x }
+
+object Test {
+  val c = new C(0)
+  import c.x
+  println(x)
+}
+
diff --git a/test/files/neg/t2775.check b/test/files/neg/t2775.check
new file mode 100644
index 0000000..a30d35f
--- /dev/null
+++ b/test/files/neg/t2775.check
@@ -0,0 +1,4 @@
+t2775.scala:1: error: cannot find class manifest for element type B.this.T
+trait B[S] { type T = S; val c = new Array[T](1) }
+                                 ^
+one error found
diff --git a/test/files/neg/t2775.scala b/test/files/neg/t2775.scala
new file mode 100644
index 0000000..9e4f2f6
--- /dev/null
+++ b/test/files/neg/t2775.scala
@@ -0,0 +1 @@
+trait B[S] { type T = S; val c = new Array[T](1) }
diff --git a/test/files/neg/t2779.check b/test/files/neg/t2779.check
new file mode 100644
index 0000000..4f94a78
--- /dev/null
+++ b/test/files/neg/t2779.check
@@ -0,0 +1,4 @@
+t2779.scala:16: error: method f is defined twice
+    override def f = List(M1)
+                 ^
+one error found
diff --git a/test/files/neg/t2779.scala b/test/files/neg/t2779.scala
new file mode 100644
index 0000000..d025055
--- /dev/null
+++ b/test/files/neg/t2779.scala
@@ -0,0 +1,25 @@
+abstract class M
+{
+    def f: List[M] = Nil
+}
+
+object M1 extends M
+
+object M2 extends M
+{
+    override def f = List(M1)
+}
+
+object M3 extends M
+{
+    override def f = List(M1)
+    override def f = List(M1)
+}
+
+object M4 extends M
+{
+    override def f = List(
+        M3,
+        M2
+    )
+}
diff --git a/test/files/neg/t2801.check b/test/files/neg/t2801.check
new file mode 100644
index 0000000..25320de
--- /dev/null
+++ b/test/files/neg/t2801.check
@@ -0,0 +1,6 @@
+t2801.scala:2: error: type mismatch;
+ found   : Null(null)
+ required: A
+  def f[A <: AnyRef] = { val a: A = null ; a }
+                                    ^
+one error found
diff --git a/test/files/neg/t2801.scala b/test/files/neg/t2801.scala
new file mode 100644
index 0000000..d425f58
--- /dev/null
+++ b/test/files/neg/t2801.scala
@@ -0,0 +1,3 @@
+object Test {
+  def f[A <: AnyRef] = { val a: A = null ; a }
+}
diff --git a/test/files/neg/t2870.check b/test/files/neg/t2870.check
new file mode 100644
index 0000000..6577577
--- /dev/null
+++ b/test/files/neg/t2870.check
@@ -0,0 +1,7 @@
+t2870.scala:1: error: not found: type Jar
+class Jars(jar: Jar)
+                ^
+t2870.scala:6: error: illegal cyclic reference involving value <import>
+  val scala = fromClasspathString(javaClassPath) 
+                                  ^
+two errors found
diff --git a/test/files/neg/t2870.scala b/test/files/neg/t2870.scala
new file mode 100644
index 0000000..59fba3e
--- /dev/null
+++ b/test/files/neg/t2870.scala
@@ -0,0 +1,9 @@
+class Jars(jar: Jar)
+
+object Jars {  
+  import scala.util.Properties.javaClassPath
+
+  val scala = fromClasspathString(javaClassPath) 
+    
+  def fromClasspathString(s: String): Jars = null
+}
diff --git a/test/files/neg/t2918.check b/test/files/neg/t2918.check
new file mode 100644
index 0000000..e67f24e
--- /dev/null
+++ b/test/files/neg/t2918.check
@@ -0,0 +1,7 @@
+t2918.scala:2: error: cyclic aliasing or subtyping involving type A
+  def g[X, A[X] <: A[X]](x: A[X]) = x 
+           ^
+t2918.scala:2: error: A does not take type parameters
+  def g[X, A[X] <: A[X]](x: A[X]) = x 
+                            ^
+two errors found
diff --git a/test/files/neg/t2918.scala b/test/files/neg/t2918.scala
new file mode 100644
index 0000000..03477cc
--- /dev/null
+++ b/test/files/neg/t2918.scala
@@ -0,0 +1,3 @@
+object Test {
+  def g[X, A[X] <: A[X]](x: A[X]) = x 
+}
diff --git a/test/files/neg/t3006.check b/test/files/neg/t3006.check
new file mode 100644
index 0000000..9a90d32
--- /dev/null
+++ b/test/files/neg/t3006.check
@@ -0,0 +1,6 @@
+t3006.scala:8: error: type mismatch;
+ found   : java.lang.String("H")
+ required: Int
+  println(A(3) + "H")
+                 ^
+one error found
diff --git a/test/files/neg/t3006.scala b/test/files/neg/t3006.scala
new file mode 100644
index 0000000..f476c17
--- /dev/null
+++ b/test/files/neg/t3006.scala
@@ -0,0 +1,10 @@
+object Test extends Application {
+  case class A(x: Int);
+
+  class Foo(a: A) { println("Foo created!"); def +(x: Int) = new A(this.a.x + x); }
+
+  implicit def aToFoo(x: A) = new Foo(x);
+
+  println(A(3) + "H")
+
+}
diff --git a/test/files/neg/t3015.check b/test/files/neg/t3015.check
new file mode 100644
index 0000000..32809b0
--- /dev/null
+++ b/test/files/neg/t3015.check
@@ -0,0 +1,11 @@
+t3015.scala:7: error: scrutinee is incompatible with pattern type;
+ found   : _$1 where type _$1
+ required: java.lang.String
+  val b(foo) = "foo" 
+       ^
+t3015.scala:7: error: type mismatch;
+ found   : _$1(in value foo) where type _$1(in value foo) <: java.lang.String
+ required: (some other)_$1(in value foo) where type (some other)_$1(in value foo)
+  val b(foo) = "foo" 
+      ^
+two errors found
diff --git a/test/files/neg/t3015.scala b/test/files/neg/t3015.scala
new file mode 100644
index 0000000..a23e967
--- /dev/null
+++ b/test/files/neg/t3015.scala
@@ -0,0 +1,8 @@
+class UnApp[P] {
+  def unapply(a: P): Option[P] = Some(a)
+}
+
+object Test extends Application {
+  val b: UnApp[_] = new UnApp[String]
+  val b(foo) = "foo" 
+}
diff --git a/test/files/neg/t3115.check b/test/files/neg/t3115.check
new file mode 100644
index 0000000..04f64ee
--- /dev/null
+++ b/test/files/neg/t3115.check
@@ -0,0 +1,10 @@
+t3115.scala:6: error: object Math in object sc is deprecated: 
+  println(sc.Math)
+             ^
+t3115.scala:7: error: object Math in package scala is deprecated: use scala.math package instead
+  println(scala.Math)
+                ^
+t3115.scala:8: error: object Math in package scala is deprecated: use scala.math package instead
+  scala.Math.Pi
+        ^
+three errors found
diff --git a/test/files/neg/t3115.flags b/test/files/neg/t3115.flags
new file mode 100644
index 0000000..d1b831e
--- /dev/null
+++ b/test/files/neg/t3115.flags
@@ -0,0 +1 @@
+-deprecation -Xfatal-warnings
\ No newline at end of file
diff --git a/test/files/neg/t3115.scala b/test/files/neg/t3115.scala
new file mode 100644
index 0000000..4aeeb40
--- /dev/null
+++ b/test/files/neg/t3115.scala
@@ -0,0 +1,9 @@
+object sc {
+  @deprecated("") object Math
+}
+
+object Test {
+  println(sc.Math)
+  println(scala.Math)
+  scala.Math.Pi
+}
diff --git a/test/files/neg/t3118.check b/test/files/neg/t3118.check
new file mode 100644
index 0000000..da00f1c
--- /dev/null
+++ b/test/files/neg/t3118.check
@@ -0,0 +1,7 @@
+t3118.scala:6: error: value C is not a member of O1
+  println(x.C())   // should not be accessible
+            ^
+t3118.scala:7: error: type C is not a member of O1
+  println(new x.C) // is correctly not accessible
+                ^
+two errors found
diff --git a/test/files/neg/t3118.scala b/test/files/neg/t3118.scala
new file mode 100644
index 0000000..75f3b8f
--- /dev/null
+++ b/test/files/neg/t3118.scala
@@ -0,0 +1,8 @@
+class O1 {
+  private[this] case class C()
+  
+  val x = new O1
+  
+  println(x.C())   // should not be accessible
+  println(new x.C) // is correctly not accessible
+}
diff --git a/test/files/neg/t3222.check b/test/files/neg/t3222.check
new file mode 100644
index 0000000..6170827
--- /dev/null
+++ b/test/files/neg/t3222.check
@@ -0,0 +1,13 @@
+t3222.scala:1: error: not found: type B
+ at throws(classOf[B])
+                ^
+t3222.scala:4: error: not found: type D
+  def foo(@throws(classOf[D]) x: Int) {}
+                          ^
+t3222.scala:3: error: not found: type C
+  @throws(classOf[C])
+                  ^
+t3222.scala:6: error: not found: type E
+  @throws(classOf[E])
+                  ^
+four errors found
diff --git a/test/files/neg/t3222.scala b/test/files/neg/t3222.scala
new file mode 100644
index 0000000..448292e
--- /dev/null
+++ b/test/files/neg/t3222.scala
@@ -0,0 +1,9 @@
+ at throws(classOf[B])
+class ExceptionTest {
+  @throws(classOf[C])
+  def foo(@throws(classOf[D]) x: Int) {}
+
+  @throws(classOf[E])
+  type t = String
+}
+
diff --git a/test/files/neg/t3224.check b/test/files/neg/t3224.check
new file mode 100644
index 0000000..29304c5
--- /dev/null
+++ b/test/files/neg/t3224.check
@@ -0,0 +1,6 @@
+t3224.scala:29: error: polymorphic expression cannot be instantiated to expected type;
+ found   : [T]Array[T]
+ required: List[?]
+  println(Texts textL Array()); println(Texts textL Array(1)); println(Texts textL Array(1, 1))
+                           ^
+one error found
diff --git a/test/files/neg/t3224.scala b/test/files/neg/t3224.scala
new file mode 100644
index 0000000..6b6ed95
--- /dev/null
+++ b/test/files/neg/t3224.scala
@@ -0,0 +1,30 @@
+object Texts{
+  def textL[T](list: List[T]) = {     
+    list match{                        
+      case List() => "Empty"              
+      case List(_) => "One"      
+      case List(_*) => "Many"
+    }
+  }
+
+  def textA[T](array: Array[T]) = {     
+    array match{                        
+      case Array() => "Empty"              
+      case Array(_) => "One"      
+      case Array(_*) => "Many"
+    }
+  }
+}
+
+object Test extends Application {
+
+  implicit def array2list[T](array: Array[T]) = {
+    println(array.toList.size)
+    array.toList
+  }
+
+  
+  println(Texts textL List()); println(Texts textL List(1)); println(Texts textL List(1, 1));
+
+  println(Texts textL Array()); println(Texts textL Array(1)); println(Texts textL Array(1, 1))
+}
diff --git a/test/files/neg/t3399.check b/test/files/neg/t3399.check
new file mode 100644
index 0000000..eb6c679
--- /dev/null
+++ b/test/files/neg/t3399.check
@@ -0,0 +1,4 @@
+t3399.scala:23: error: could not find implicit value for parameter e: =:=[Nats.Add[Nats._1,Nats._1],Nats._1]
+    implicitly[ Add[_1, _1] =:= _1]
+              ^
+one error found
diff --git a/test/files/neg/t3399.scala b/test/files/neg/t3399.scala
new file mode 100644
index 0000000..b1fe4e5
--- /dev/null
+++ b/test/files/neg/t3399.scala
@@ -0,0 +1,24 @@
+object Nats {
+    sealed trait Nat {
+        // fold right on N, N-1, ..., 1
+        type FoldR[Init <: Type, Type, F <: Fold[Nat, Type]] <: Type
+    }
+    sealed trait _0 extends Nat {
+        type FoldR[Init <: Type, Type, F <: Fold[Nat, Type]] = Init
+    }
+    sealed trait Succ[N <: Nat] extends Nat {
+        type FoldR[Init <: Type, Type, F <: Fold[Nat, Type]] =
+          F#Apply[Succ[N], N#FoldR[Init, Type, F]]
+    }
+    
+    type Add[A <: Nat, B <: Nat] = A#FoldR[B, Nat, Inc]
+    trait Fold[-Elem, Value] {
+        type Apply[N <: Elem, Acc <: Value] <: Value
+    }
+    type Inc = Fold[Any, Nat] {
+        type Apply[N <: Any, Acc <: Nat] = Succ[Acc]
+    }
+    
+    type _1 = Succ[_0]
+    implicitly[ Add[_1, _1] =:= _1]
+}
\ No newline at end of file
diff --git a/test/files/neg/t3403.check b/test/files/neg/t3403.check
new file mode 100644
index 0000000..e52d140
--- /dev/null
+++ b/test/files/neg/t3403.check
@@ -0,0 +1,4 @@
+t3403.scala:2: error: implementation limitation: the BeanProperty annotation cannot be used in a type alias or renamed import
+class Foo { @bp var bar: Int = 1 }
+                    ^
+one error found
diff --git a/test/files/neg/t3403.scala b/test/files/neg/t3403.scala
new file mode 100644
index 0000000..8be6ab2
--- /dev/null
+++ b/test/files/neg/t3403.scala
@@ -0,0 +1,2 @@
+import scala.reflect.{BeanProperty => bp}
+class Foo { @bp var bar: Int = 1 }
diff --git a/test/files/neg/t3453.check b/test/files/neg/t3453.check
new file mode 100644
index 0000000..52c9481
--- /dev/null
+++ b/test/files/neg/t3453.check
@@ -0,0 +1,21 @@
+t3453.scala:18: error: type mismatch;
+ found   : A
+ required: B
+        new A
+        ^
+t3453.scala:36: error: type mismatch;
+ found   : A
+ required: B
+        new A
+        ^
+t3453.scala:50: error: type mismatch;
+ found   : A
+ required: B
+        new A
+        ^
+t3453.scala:64: error: type mismatch;
+ found   : A
+ required: B
+        new A
+        ^
+four errors found
diff --git a/test/files/neg/t3453.scala b/test/files/neg/t3453.scala
new file mode 100644
index 0000000..0f1c6e0
--- /dev/null
+++ b/test/files/neg/t3453.scala
@@ -0,0 +1,66 @@
+// test shadowing of implicits by synonymous non-implicit symbols
+// whether they be inherited, imported (explicitly or using a wildcard) or defined directly
+class A
+class B
+
+trait S {
+    implicit def aToB(a: A): B = new B
+}
+
+class T1 extends S {
+    def x: B = {
+        val aToB = 3
+        // ok: doesn't compile, because aToB method requires 'T.this.' prefix
+        //aToB(new A)
+
+        // bug: compiles, using T.this.aToB,
+        //   despite it not being accessible without a prefix
+        new A
+    }
+}
+
+object O {
+    implicit def aToB(a: A): B = new B
+}
+
+class T2a {
+    import O._
+    
+    def x: B = {
+        val aToB = 3
+        // ok: doesn't compile, because aToB method requires 'T.this.' prefix
+        //aToB(new A)
+
+        // bug: compiles, using T.this.aToB,
+        //   despite it not being accessible without a prefix
+        new A
+    }
+}
+
+class T2b {
+    import O.aToB
+    
+    def x: B = {
+        val aToB = 3
+        // ok: doesn't compile, because aToB method requires 'T.this.' prefix
+        //aToB(new A)
+
+        // bug: compiles, using T.this.aToB,
+        //   despite it not being accessible without a prefix
+        new A
+    }
+}
+
+class T3 {
+    implicit def aToB(a: A): B = new B
+    
+    def x: B = {
+        val aToB = 3
+        // ok: doesn't compile, because aToB method requires 'T.this.' prefix
+        //aToB(new A)
+
+        // bug: compiles, using T.this.aToB,
+        //   despite it not being accessible without a prefix
+        new A
+    }
+}
\ No newline at end of file
diff --git a/test/files/neg/t3507.check b/test/files/neg/t3507.check
new file mode 100644
index 0000000..1246a20
--- /dev/null
+++ b/test/files/neg/t3507.check
@@ -0,0 +1,4 @@
+t3507.scala:13: error: could not find implicit value for evidence parameter of type Manifest[object _1.b.c]
+  mani/*[object _1.b.c]*/(c) // kaboom in manifestOfType / TreeGen.mkAttributedQualifier
+                         ^
+one error found
diff --git a/test/files/neg/t3507.scala b/test/files/neg/t3507.scala
new file mode 100644
index 0000000..32688d3
--- /dev/null
+++ b/test/files/neg/t3507.scala
@@ -0,0 +1,15 @@
+class A {
+  object b {
+    object c
+  }
+  def m = b.c
+}
+
+object Test {
+  var a: A = new A // mutable
+  val c /*: object _1.b.c forSome { val _1: A } */ = a.m // widening using existential
+  
+  def mani[T: Manifest](x: T) = ()
+  mani/*[object _1.b.c]*/(c) // kaboom in manifestOfType / TreeGen.mkAttributedQualifier
+  // --> _1 is not in scope here
+}
\ No newline at end of file
diff --git a/test/files/neg/t3604.check b/test/files/neg/t3604.check
new file mode 100644
index 0000000..b07c5c9
--- /dev/null
+++ b/test/files/neg/t3604.check
@@ -0,0 +1,7 @@
+t3604.scala:3: error: in XML literal: expected closing tag of abbr
+    <abbr></div>
+               ^
+t3604.scala:3: error: start tag was here: abbr>
+    <abbr></div>
+     ^
+two errors found
diff --git a/test/files/neg/t3604.scala b/test/files/neg/t3604.scala
new file mode 100644
index 0000000..f890a58
--- /dev/null
+++ b/test/files/neg/t3604.scala
@@ -0,0 +1,6 @@
+object Main {
+  <div>
+    <abbr></div>
+    { "..." }
+  </div>
+}
diff --git a/test/files/neg/t3653.check b/test/files/neg/t3653.check
new file mode 100644
index 0000000..ac6e2ca
--- /dev/null
+++ b/test/files/neg/t3653.check
@@ -0,0 +1,7 @@
+t3653.scala:3: error: double definition:
+method x:(implicit x: Int)Int and
+method x:(i: Int)Int at line 2
+have same type after erasure: (x: Int)Int
+   def x(implicit x: Int) = 5
+       ^
+one error found
diff --git a/test/files/neg/t3653.scala b/test/files/neg/t3653.scala
new file mode 100644
index 0000000..96cf960
--- /dev/null
+++ b/test/files/neg/t3653.scala
@@ -0,0 +1,4 @@
+class B {
+   def x(i: Int) = 3
+   def x(implicit x: Int) = 5
+}
\ No newline at end of file
diff --git a/test/files/neg/t3663.check b/test/files/neg/t3663.check
new file mode 100644
index 0000000..09ea25a
--- /dev/null
+++ b/test/files/neg/t3663.check
@@ -0,0 +1,4 @@
+main.scala:11: error: variable foo cannot be accessed in test.Test
+      println(t.foo)
+                ^
+one error found
diff --git a/test/files/neg/t3663/PackageProtected.java b/test/files/neg/t3663/PackageProtected.java
new file mode 100644
index 0000000..f4535a5
--- /dev/null
+++ b/test/files/neg/t3663/PackageProtected.java
@@ -0,0 +1,5 @@
+package test;
+
+class PackageProtected {
+    int foo;
+}
diff --git a/test/files/neg/t3663/main.scala b/test/files/neg/t3663/main.scala
new file mode 100644
index 0000000..2961955
--- /dev/null
+++ b/test/files/neg/t3663/main.scala
@@ -0,0 +1,14 @@
+package test
+
+final class Test extends PackageProtected {
+  def bar = foo
+}
+
+package another {
+  object Main {
+    def bug(t: Test) {
+      // Can always be replicated.
+      println(t.foo)
+    }
+  }
+}
\ No newline at end of file
diff --git a/test/files/neg/t3691.check b/test/files/neg/t3691.check
new file mode 100644
index 0000000..1b548cc
--- /dev/null
+++ b/test/files/neg/t3691.check
@@ -0,0 +1,16 @@
+t3691.scala:4: error: type mismatch;
+ found   : java.lang.Object with Test.A[String]
+ required: AnyRef{type A[x]}
+ val b = (new A[String]{}): { type A[x] } // not ok
+          ^
+t3691.scala:5: error: type mismatch;
+ found   : java.lang.Object with Test.A[String]
+ required: AnyRef{type A}
+ val c = (new A[String]{}): { type A } // not ok
+          ^
+t3691.scala:7: error: type mismatch;
+ found   : java.lang.Object{type A = String}
+ required: AnyRef{type A[X]}
+ val x = (new { type A = String }): { type A[X] } // not ok
+          ^
+three errors found
diff --git a/test/files/neg/t3691.scala b/test/files/neg/t3691.scala
new file mode 100644
index 0000000..69e8bef
--- /dev/null
+++ b/test/files/neg/t3691.scala
@@ -0,0 +1,11 @@
+object Test {
+ trait A[X] { type A[x <: X] = x }
+ val a = (new A[String]{}): { type A[x <: String] } // ok
+ val b = (new A[String]{}): { type A[x] } // not ok
+ val c = (new A[String]{}): { type A } // not ok
+
+ val x = (new { type A = String }): { type A[X] } // not ok
+//a: AnyRef{type A[X]}
+
+  identity[x.A[Any]] _
+}
\ No newline at end of file
diff --git a/test/files/neg/t3692.check b/test/files/neg/t3692.check
new file mode 100644
index 0000000..ce89a65
--- /dev/null
+++ b/test/files/neg/t3692.check
@@ -0,0 +1,14 @@
+t3692.scala:11: warning: type Integer in package scala is deprecated: use <code>java.lang.Integer</code> instead
+      case m0: Map[Int, Int] => new java.util.HashMap[Integer, Integer]
+                                              ^
+t3692.scala:12: warning: type Integer in package scala is deprecated: use <code>java.lang.Integer</code> instead
+      case m1: Map[Int, V] => new java.util.HashMap[Integer, V]
+                                            ^
+t3692.scala:13: warning: type Integer in package scala is deprecated: use <code>java.lang.Integer</code> instead
+      case m2: Map[T, Int] => new java.util.HashMap[T, Integer]
+                                            ^
+t3692.scala:13: error: unreachable code
+      case m2: Map[T, Int] => new java.util.HashMap[T, Integer]
+                              ^
+three warnings found
+one error found
diff --git a/test/files/neg/t3692.scala b/test/files/neg/t3692.scala
new file mode 100644
index 0000000..78b0e4b
--- /dev/null
+++ b/test/files/neg/t3692.scala
@@ -0,0 +1,17 @@
+object ManifestTester {
+  def main(args: Array[String]) = {
+    val map = Map("John" -> 1, "Josh" -> 2)
+    new ManifestTester().toJavaMap(map)
+  }
+}
+
+class ManifestTester {
+  private final def toJavaMap[T, V](map: Map[T, V])(implicit m1: Manifest[T], m2: Manifest[V]): java.util.Map[_, _] = {
+    map match {
+      case m0: Map[Int, Int] => new java.util.HashMap[Integer, Integer]
+      case m1: Map[Int, V] => new java.util.HashMap[Integer, V]
+      case m2: Map[T, Int] => new java.util.HashMap[T, Integer]
+      case _ => new java.util.HashMap[T, V]
+    }
+  }
+}
\ No newline at end of file
diff --git a/test/files/neg/t3757.check b/test/files/neg/t3757.check
new file mode 100644
index 0000000..1507df8
--- /dev/null
+++ b/test/files/neg/t3757.check
@@ -0,0 +1,4 @@
+B.scala:4: error: method foo overrides nothing
+  override def foo = "B"
+               ^
+one error found
diff --git a/test/files/neg/t3757/A.java b/test/files/neg/t3757/A.java
new file mode 100644
index 0000000..37da86f
--- /dev/null
+++ b/test/files/neg/t3757/A.java
@@ -0,0 +1,5 @@
+package a;
+
+public abstract class A {
+  abstract String foo(); // package protected!
+}
\ No newline at end of file
diff --git a/test/files/neg/t3757/B.scala b/test/files/neg/t3757/B.scala
new file mode 100644
index 0000000..68766a9
--- /dev/null
+++ b/test/files/neg/t3757/B.scala
@@ -0,0 +1,5 @@
+package b
+
+class B extends a.A { 
+  override def foo = "B"
+}
\ No newline at end of file
diff --git a/test/files/neg/t3769.check b/test/files/neg/t3769.check
new file mode 100644
index 0000000..7537ed2
--- /dev/null
+++ b/test/files/neg/t3769.check
@@ -0,0 +1,10 @@
+t3769.scala:2: error: in XML literal: expected closing tag of a
+  val x = <b> <c><a></c> {"text"} </b>
+                       ^
+t3769.scala:2: error: start tag was here: a>
+  val x = <b> <c><a></c> {"text"} </b>
+                  ^
+t3769.scala:2: error: ';' expected but '{' found.
+  val x = <b> <c><a></c> {"text"} </b>
+                         ^
+three errors found
diff --git a/test/files/neg/t3769.scala b/test/files/neg/t3769.scala
new file mode 100644
index 0000000..0132b59
--- /dev/null
+++ b/test/files/neg/t3769.scala
@@ -0,0 +1,3 @@
+object Test {
+  val x = <b> <c><a></c> {"text"} </b>
+}
diff --git a/test/files/neg/t3773.check b/test/files/neg/t3773.check
new file mode 100644
index 0000000..29a3e14
--- /dev/null
+++ b/test/files/neg/t3773.check
@@ -0,0 +1,4 @@
+t3773.scala:3: error: method elements in trait IterableLike is deprecated: use `iterator' instead
+  for ((v, t) <- m.elements) ()
+                   ^
+one error found
diff --git a/test/files/neg/t3773.flags b/test/files/neg/t3773.flags
new file mode 100644
index 0000000..d1b831e
--- /dev/null
+++ b/test/files/neg/t3773.flags
@@ -0,0 +1 @@
+-deprecation -Xfatal-warnings
\ No newline at end of file
diff --git a/test/files/neg/t3773.scala b/test/files/neg/t3773.scala
new file mode 100644
index 0000000..3b92ed2
--- /dev/null
+++ b/test/files/neg/t3773.scala
@@ -0,0 +1,5 @@
+object t {
+  val m = Map(1 -> "one")
+  for ((v, t) <- m.elements) ()
+}
+
diff --git a/test/files/neg/t3774.check b/test/files/neg/t3774.check
new file mode 100644
index 0000000..f1a787a
--- /dev/null
+++ b/test/files/neg/t3774.check
@@ -0,0 +1,7 @@
+t3774.scala:4: error: overloaded method value ++ with alternatives:
+  [B1 >: List[Int]](xs: scala.collection.TraversableOnce[((Int, Int), B1)])scala.collection.immutable.Map[(Int, Int),B1] <and>
+  [B >: ((Int, Int), List[Int]),That](that: scala.collection.TraversableOnce[B])(implicit bf: scala.collection.generic.CanBuildFrom[scala.collection.immutable.Map[(Int, Int),List[Int]],B,That])That
+ cannot be applied to (scala.collection.immutable.IndexedSeq[((Int, Int), scala.collection.immutable.Range.Inclusive with scala.collection.immutable.Range.ByOne)])
+  Map[(Int,Int),List[Int]]() ++ (for(x <- 0 to 1 ; y <- 0 to 1) yield {(x,y)-> (0 to 1)})
+                          ^
+one error found
diff --git a/test/files/neg/t3774.scala b/test/files/neg/t3774.scala
new file mode 100644
index 0000000..2869925
--- /dev/null
+++ b/test/files/neg/t3774.scala
@@ -0,0 +1,5 @@
+// This used to hang the lub process. Now it rejects the file. This is still not correct,
+// but we can solve this only after a redesign of lub a la dot.
+object Hang {
+  Map[(Int,Int),List[Int]]() ++ (for(x <- 0 to 1 ; y <- 0 to 1) yield {(x,y)-> (0 to 1)})
+}
diff --git a/test/files/neg/t3776.check b/test/files/neg/t3776.check
new file mode 100644
index 0000000..e8798df
--- /dev/null
+++ b/test/files/neg/t3776.check
@@ -0,0 +1,4 @@
+t3776.scala:8: error: value someOperation is not a member of _$1
+    def parsedAs[T](v: T) = MyParser.parse(pattern, a).get someOperation v 
+                                                       ^
+one error found
diff --git a/test/files/neg/t3776.scala b/test/files/neg/t3776.scala
new file mode 100644
index 0000000..454f914
--- /dev/null
+++ b/test/files/neg/t3776.scala
@@ -0,0 +1,10 @@
+import util.parsing.combinator.{PackratParsers, RegexParsers}
+
+object MyParser extends RegexParsers with PackratParsers {
+}
+
+object Test {
+  class ParsedAs(a: String) (implicit pattern: MyParser.Parser[_]) {
+    def parsedAs[T](v: T) = MyParser.parse(pattern, a).get someOperation v 
+  }
+}
diff --git a/test/files/neg/t3873.check b/test/files/neg/t3873.check
new file mode 100644
index 0000000..54d6abd
--- /dev/null
+++ b/test/files/neg/t3873.check
@@ -0,0 +1,6 @@
+t3873.scala:11: error: type mismatch;
+ found   : Test.a.B
+ required: a.B
+  wrongf(new A)(a.b) // should not compile -- TODO: improve error message? the "a" is ambiguous
+                  ^
+one error found
diff --git a/test/files/neg/t3873.flags b/test/files/neg/t3873.flags
new file mode 100644
index 0000000..1c26b24
--- /dev/null
+++ b/test/files/neg/t3873.flags
@@ -0,0 +1 @@
+-Ydependent-method-types
\ No newline at end of file
diff --git a/test/files/neg/t3873.scala b/test/files/neg/t3873.scala
new file mode 100644
index 0000000..e7815f0
--- /dev/null
+++ b/test/files/neg/t3873.scala
@@ -0,0 +1,12 @@
+class A {
+  class B
+  def b: B = new B
+}
+
+object Test {
+  def wrongf(a: A)(b: a.B): a.B = b
+
+  val a = new A
+  wrongf(a)(a.b)
+  wrongf(new A)(a.b) // should not compile -- TODO: improve error message? the "a" is ambiguous
+}
\ No newline at end of file
diff --git a/test/files/neg/t742.check b/test/files/neg/t742.check
new file mode 100644
index 0000000..f587948
--- /dev/null
+++ b/test/files/neg/t742.check
@@ -0,0 +1,5 @@
+t742.scala:5: error: kinds of the type arguments (Crash._1,Crash._2,Any) do not conform to the expected kinds of the type parameters (type m,type n,type z).
+Crash._1's type parameters do not match type m's expected parameters: type s1 has one type parameter, but type n has two
+    type p = mul[_1, _2, Any]  // mul[_1, _1, Any] needs -Yrecursion
+             ^
+one error found
diff --git a/test/files/neg/t742.scala b/test/files/neg/t742.scala
new file mode 100644
index 0000000..bb1c2f8
--- /dev/null
+++ b/test/files/neg/t742.scala
@@ -0,0 +1,8 @@
+object Crash {
+    type mul[m[n[s[_], z], z], n[s[_], z], z] = m[n, z]
+    type _1[s1[_], z1] = s1[z1]
+    type _2[s1[_], z1] = s1[z1]
+    type p = mul[_1, _2, Any]  // mul[_1, _1, Any] needs -Yrecursion
+    // _1[_2, Zero]
+    // _2[Zero]
+}
\ No newline at end of file
diff --git a/test/files/neg/t771.check b/test/files/neg/t771.check
new file mode 100644
index 0000000..c0d1e00
--- /dev/null
+++ b/test/files/neg/t771.check
@@ -0,0 +1,4 @@
+t771.scala:4: error: trait Iterator is abstract; cannot be instantiated
+  def c[A](it:java.util.Iterator[A]) = new scala.Iterator[A]
+                                       ^
+one error found
diff --git a/test/files/neg/t771.scala b/test/files/neg/t771.scala
new file mode 100644
index 0000000..26bf441
--- /dev/null
+++ b/test/files/neg/t771.scala
@@ -0,0 +1,5 @@
+class Foo {
+  def a = c(b)
+  def b[List[AnyRef]] = new java.util.Iterator[List[Object]] { }
+  def c[A](it:java.util.Iterator[A]) = new scala.Iterator[A]
+}
diff --git a/test/files/neg/tailrec.check b/test/files/neg/tailrec.check
new file mode 100644
index 0000000..27d99f6
--- /dev/null
+++ b/test/files/neg/tailrec.check
@@ -0,0 +1,16 @@
+tailrec.scala:43: error: could not optimize @tailrec annotated method: it contains a recursive call not in tail position
+  def facfail(n: Int): Int =
+      ^
+tailrec.scala:50: error: could not optimize @tailrec annotated method: it is neither private nor final so can be overridden
+  @tailrec def fail1(x: Int): Int = fail1(x)
+               ^
+tailrec.scala:53: error: could not optimize @tailrec annotated method: it contains a recursive call not in tail position
+  @tailrec final def fail2[T](xs: List[T]): List[T] = xs match {
+                     ^
+tailrec.scala:59: error: could not optimize @tailrec annotated method: it is called recursively with different type arguments
+  @tailrec final def fail3[T](x: Int): Int = fail3(x - 1)
+                     ^
+tailrec.scala:63: error: could not optimize @tailrec annotated method: it changes type of 'this' on a polymorphic recursive call
+    @tailrec final def fail4[U](other: Tom[U], x: Int): Int = other.fail4[U](other, x - 1)
+                       ^
+5 errors found
diff --git a/test/files/neg/tailrec.scala b/test/files/neg/tailrec.scala
new file mode 100644
index 0000000..6d836df
--- /dev/null
+++ b/test/files/neg/tailrec.scala
@@ -0,0 +1,65 @@
+import scala.annotation.tailrec
+
+// putting @tailrec through the paces
+object Winners {
+  @tailrec
+  def facsucc(n: Int, acc: Int): Int =
+    if (n == 0) acc
+    else facsucc(n - 1, n * acc)
+
+  @tailrec def loopsucc1(x: Int): Int = loopsucc1(x - 1)
+  @tailrec def loopsucc2[T](x: Int): Int = loopsucc2[T](x - 1)
+  
+  def ding {
+    object dong {
+      @tailrec def loopsucc3(x: Int): Int = loopsucc3(x)
+    }
+    ()
+  }
+  
+  def inner(q: Int) = {
+    @tailrec
+    def loopsucc4(x: Int): Int = loopsucc4(x + 1)
+    
+    loopsucc4(q)
+  }
+  
+  object innerBob {
+    @tailrec def loopsucc5(x: Int): Int = loopsucc5(x)
+  }
+}
+
+class Winners {
+  @tailrec private def succ1(x: Int): Int = succ1(x)
+  @tailrec final def succ2(x: Int): Int = succ2(x)
+  @tailrec final def succ3[T](in: List[T], acc: List[T]): List[T] = in match {
+    case Nil      => Nil
+    case x :: xs  => succ3(xs, x :: acc)
+  }
+}
+
+object Failures {
+  @tailrec
+  def facfail(n: Int): Int =
+    if (n == 0) 1
+    else n * facfail(n - 1)
+}
+
+class Failures {  
+  // not private, not final
+  @tailrec def fail1(x: Int): Int = fail1(x)
+  
+  // a typical between-chair-and-keyboard error
+  @tailrec final def fail2[T](xs: List[T]): List[T] = xs match {
+    case Nil      => Nil
+    case x :: xs  => x :: fail2[T](xs)
+  }
+  
+  // unsafe
+  @tailrec final def fail3[T](x: Int): Int = fail3(x - 1)
+  
+  // unsafe
+  class Tom[T](x: Int) {
+    @tailrec final def fail4[U](other: Tom[U], x: Int): Int = other.fail4[U](other, x - 1)
+  }
+}
diff --git a/test/files/neg/tcpoly_bounds.scala b/test/files/neg/tcpoly_bounds.scala
index ae1f410..b444c59 100644
--- a/test/files/neg/tcpoly_bounds.scala
+++ b/test/files/neg/tcpoly_bounds.scala
@@ -1,3 +1,3 @@
 class A[m[x] <: Option[x]]
 object a extends A[Some]
-object b extends A[List]
\ No newline at end of file
+object b extends A[List]
diff --git a/test/files/neg/tcpoly_infer_ticket1162.check b/test/files/neg/tcpoly_infer_ticket1162.check
new file mode 100644
index 0000000..0333422
--- /dev/null
+++ b/test/files/neg/tcpoly_infer_ticket1162.check
@@ -0,0 +1,4 @@
+tcpoly_infer_ticket1162.scala:6: error: wrong number of type parameters for method apply: [A,B,F[_]]()Test.Lift[A,B,F] in object Lift
+  def simplify[A,B]: Expression[A,B] = Lift[A,B]()
+                                           ^
+one error found
diff --git a/test/files/neg/tcpoly_infer_ticket1162.scala b/test/files/neg/tcpoly_infer_ticket1162.scala
new file mode 100644
index 0000000..b88bd35
--- /dev/null
+++ b/test/files/neg/tcpoly_infer_ticket1162.scala
@@ -0,0 +1,8 @@
+object Test {
+  trait Expression[A,B] 
+
+  case class Lift[A,B,F[_]]() extends Expression[F[A],F[B]]
+  
+  def simplify[A,B]: Expression[A,B] = Lift[A,B]()
+}
+
diff --git a/test/files/neg/tcpoly_override.scala b/test/files/neg/tcpoly_override.scala
index f2c3b04..7f64ad0 100644
--- a/test/files/neg/tcpoly_override.scala
+++ b/test/files/neg/tcpoly_override.scala
@@ -7,4 +7,4 @@ trait B // First-order type
 
 class C extends A {
  type T = B // This compiles well (@M: ... but it shouldn't)
-}
\ No newline at end of file
+}
diff --git a/test/files/neg/tcpoly_ticket2101.check b/test/files/neg/tcpoly_ticket2101.check
new file mode 100644
index 0000000..eac582e
--- /dev/null
+++ b/test/files/neg/tcpoly_ticket2101.check
@@ -0,0 +1,4 @@
+tcpoly_ticket2101.scala:2: error: type arguments [T2,X] do not conform to class T's type parameter bounds [A[Y] <: T[A,B],B]
+class T2[X] extends T[T2, X] // ill-typed
+                    ^
+one error found
\ No newline at end of file
diff --git a/test/files/neg/tcpoly_ticket2101.scala b/test/files/neg/tcpoly_ticket2101.scala
new file mode 100644
index 0000000..3af07ac
--- /dev/null
+++ b/test/files/neg/tcpoly_ticket2101.scala
@@ -0,0 +1,28 @@
+class T[A[Y] <: T[A, B], B]
+class T2[X] extends T[T2, X] // ill-typed
+// because this bound is not met:
+// Forall Y. T2[Y] <: T[T2, X]
+
+// debugging before fix:
+// def isSubType0 -->       
+// case (PolyType(tparams1, res1), PolyType(tparams2, res2)) => println("<:<PT: "+((tparams1, res1), (tparams2, res2))) //@MDEBUG
+//   (tparams1.length == tparams2.length &&
+//    List.forall2(tparams1, tparams2) 
+//      ((p1, p2) => p2.info.substSym(tparams2, tparams1) <:< p1.info) &&
+//    res1 <:< res2.substSym(tparams2, tparams1))
+
+// generates output:
+// <:<PT: ((List(type Y),A[Y]),(List(type Y),T[A,B]))
+// <:<PT: ((List(type X),T2[X]),(List(type Y),T[T2,X]))
+
+// however, last check should have been:
+// <:<PT: ((List(type X1),T2[X1]),(List(type Y1),T[T2,X]))
+
+// case (PolyType(tparams1, res1), PolyType(tparams2, res2)) => println("<:<PT: "+((tparams1, res1), (tparams2, res2))) //@MDEBUG
+//   (tparams1.length == tparams2.length &&
+//    {
+//      val tpsFresh = cloneSymbols(tparams1) // @M cloneSymbols(tparams2) should be equivalent -- TODO: check
+//      List.forall2(tparams1, tparams2) 
+//         ((p1, p2) => p2.info.substSym(tparams2, tpsFresh) <:< p1.info.substSym(tparams1, tpsFresh)) &&
+//       res1.substSym(tparams1, tpsFresh) <:< res2.substSym(tparams2, tpsFresh)   
+//    })
diff --git a/test/files/neg/tcpoly_variance.check b/test/files/neg/tcpoly_variance.check
index 146240a..2df4b4d 100644
--- a/test/files/neg/tcpoly_variance.check
+++ b/test/files/neg/tcpoly_variance.check
@@ -1,5 +1,5 @@
-tcpoly_variance.scala:6: error: error overriding method str in class A of type => m[java.lang.Object];
- method str has incompatible type => m[String]
+tcpoly_variance.scala:6: error: overriding method str in class A of type => m[java.lang.Object];
+ method str has incompatible type
  override def str: m[String]  = error("foo") // since x in m[x] is invariant, ! m[String] <: m[Object]
               ^
 one error found
diff --git a/test/files/neg/tcpoly_variance.scala b/test/files/neg/tcpoly_variance.scala
index 8122938..52c1452 100644
--- a/test/files/neg/tcpoly_variance.scala
+++ b/test/files/neg/tcpoly_variance.scala
@@ -4,4 +4,4 @@ class A[m[x]] {
 
 class B[m[x]] extends A[m] {
  override def str: m[String]  = error("foo") // since x in m[x] is invariant, ! m[String] <: m[Object]
-}
\ No newline at end of file
+}
diff --git a/test/files/neg/tcpoly_variance_enforce.check b/test/files/neg/tcpoly_variance_enforce.check
index c13a092..508ed90 100644
--- a/test/files/neg/tcpoly_variance_enforce.check
+++ b/test/files/neg/tcpoly_variance_enforce.check
@@ -1,44 +1,44 @@
-tcpoly_variance_enforce.scala:15: error: the kinds of the type arguments (FooInvar) do not conform to the expected kinds of the type parameters (type m) in trait coll.
+tcpoly_variance_enforce.scala:15: error: kinds of the type arguments (FooInvar) do not conform to the expected kinds of the type parameters (type m) in trait coll.
 FooInvar's type parameters do not match type m's expected parameters: type x (in class FooInvar) is invariant, but type x is declared covariant
 object fcollinv extends coll[FooInvar]      // error
                         ^
-tcpoly_variance_enforce.scala:16: error: the kinds of the type arguments (FooContra) do not conform to the expected kinds of the type parameters (type m) in trait coll.
+tcpoly_variance_enforce.scala:16: error: kinds of the type arguments (FooContra) do not conform to the expected kinds of the type parameters (type m) in trait coll.
 FooContra's type parameters do not match type m's expected parameters: type x (in class FooContra) is contravariant, but type x is declared covariant
 object fcollcon extends coll[FooContra]     // error
                         ^
-tcpoly_variance_enforce.scala:17: error: the kinds of the type arguments (FooString) do not conform to the expected kinds of the type parameters (type m) in trait coll.
+tcpoly_variance_enforce.scala:17: error: kinds of the type arguments (FooString) do not conform to the expected kinds of the type parameters (type m) in trait coll.
 FooString's type parameters do not match type m's expected parameters: type x (in class FooString)'s bounds >: Nothing <: String are stricter than type x's declared bounds >: Nothing <: Any
 object fcollwb extends coll[FooString]      // error
                        ^
-tcpoly_variance_enforce.scala:19: error: the kinds of the type arguments (FooCov) do not conform to the expected kinds of the type parameters (type m) in trait coll2.
+tcpoly_variance_enforce.scala:19: error: kinds of the type arguments (FooCov) do not conform to the expected kinds of the type parameters (type m) in trait coll2.
 FooCov's type parameters do not match type m's expected parameters: type x (in class FooCov) is covariant, but type x is declared contravariant
 object fcoll2ok extends coll2[FooCov]       // error
                         ^
-tcpoly_variance_enforce.scala:20: error: the kinds of the type arguments (FooInvar) do not conform to the expected kinds of the type parameters (type m) in trait coll2.
+tcpoly_variance_enforce.scala:20: error: kinds of the type arguments (FooInvar) do not conform to the expected kinds of the type parameters (type m) in trait coll2.
 FooInvar's type parameters do not match type m's expected parameters: type x (in class FooInvar) is invariant, but type x is declared contravariant
 object fcoll2inv extends coll2[FooInvar]    // error
                          ^
-tcpoly_variance_enforce.scala:22: error: the kinds of the type arguments (FooString) do not conform to the expected kinds of the type parameters (type m) in trait coll2.
+tcpoly_variance_enforce.scala:22: error: kinds of the type arguments (FooString) do not conform to the expected kinds of the type parameters (type m) in trait coll2.
 FooString's type parameters do not match type m's expected parameters: type x (in class FooString) is covariant, but type x is declared contravarianttype x (in class FooString)'s bounds >: Nothing <: String are stricter than type x's declared bounds >: Nothing <: Any
 object fcoll2wb extends coll2[FooString]      // error
                         ^
-tcpoly_variance_enforce.scala:27: error: the kinds of the type arguments (FooString) do not conform to the expected kinds of the type parameters (type m) in trait coll3.
+tcpoly_variance_enforce.scala:27: error: kinds of the type arguments (FooString) do not conform to the expected kinds of the type parameters (type m) in trait coll3.
 FooString's type parameters do not match type m's expected parameters: type x (in class FooString)'s bounds >: Nothing <: String are stricter than type x's declared bounds >: Nothing <: Any
 object fcoll3wb extends  coll3[FooString]   // error
                          ^
-tcpoly_variance_enforce.scala:30: error: the kinds of the type arguments (FooString,Int) do not conform to the expected kinds of the type parameters (type m,type y) in trait coll4.
+tcpoly_variance_enforce.scala:30: error: kinds of the type arguments (FooString,Int) do not conform to the expected kinds of the type parameters (type m,type y) in trait coll4.
 FooString's type parameters do not match type m's expected parameters: type x (in class FooString)'s bounds >: Nothing <: String are stricter than type x's declared bounds >: Nothing <: y
 object fcoll4_1 extends  coll4[FooString, Int] // error
                          ^
-tcpoly_variance_enforce.scala:31: error: the kinds of the type arguments (FooString,Any) do not conform to the expected kinds of the type parameters (type m,type y) in trait coll4.
+tcpoly_variance_enforce.scala:31: error: kinds of the type arguments (FooString,Any) do not conform to the expected kinds of the type parameters (type m,type y) in trait coll4.
 FooString's type parameters do not match type m's expected parameters: type x (in class FooString)'s bounds >: Nothing <: String are stricter than type x's declared bounds >: Nothing <: y
 object fcoll4_2 extends  coll4[FooString, Any] // error
                          ^
-tcpoly_variance_enforce.scala:37: error: the kinds of the type arguments (FooInvar) do not conform to the expected kinds of the type parameters (type m) in trait coll.
+tcpoly_variance_enforce.scala:37: error: kinds of the type arguments (FooInvar) do not conform to the expected kinds of the type parameters (type m) in trait coll.
 FooInvar's type parameters do not match type m's expected parameters: type x (in class FooInvar) is invariant, but type x is declared covariant
   def x: coll[FooInvar] = error("foo") // error
          ^
-tcpoly_variance_enforce.scala:38: error: the kinds of the type arguments (FooContra) do not conform to the expected kinds of the type parameters (type m) in trait coll.
+tcpoly_variance_enforce.scala:38: error: kinds of the type arguments (FooContra) do not conform to the expected kinds of the type parameters (type m) in trait coll.
 FooContra's type parameters do not match type m's expected parameters: type x (in class FooContra) is contravariant, but type x is declared covariant
   def y: coll[FooContra] = error("foo") // error
          ^
diff --git a/test/files/neg/tcpoly_variance_enforce.scala b/test/files/neg/tcpoly_variance_enforce.scala
index ff5f8de..417fc54 100644
--- a/test/files/neg/tcpoly_variance_enforce.scala
+++ b/test/files/neg/tcpoly_variance_enforce.scala
@@ -39,4 +39,4 @@ object test {
 }
 
 
-// TODO: need test for rank N with N >: 2
\ No newline at end of file
+// TODO: need test for rank N with N >: 2
diff --git a/test/files/neg/ticket513.check b/test/files/neg/ticket513.check
new file mode 100644
index 0000000..8994269
--- /dev/null
+++ b/test/files/neg/ticket513.check
@@ -0,0 +1,4 @@
+ticket513.scala:6: error: type arguments [NotThatBound] do not conform to trait T's type parameter bounds [A <: Bound]
+object Wrong extends Wrap[T[NotThatBound]]
+                     ^
+one error found
diff --git a/test/files/neg/ticket513.scala b/test/files/neg/ticket513.scala
new file mode 100644
index 0000000..5aecc7a
--- /dev/null
+++ b/test/files/neg/ticket513.scala
@@ -0,0 +1,6 @@
+class Bound
+class NotThatBound
+trait T[A <: Bound]
+trait Wrap[X]
+
+object Wrong extends Wrap[T[NotThatBound]]
diff --git a/test/files/neg/typeerror.check b/test/files/neg/typeerror.check
index 3e21a79..3ce11da 100644
--- a/test/files/neg/typeerror.check
+++ b/test/files/neg/typeerror.check
@@ -1,6 +1,6 @@
 typeerror.scala:6: error: type mismatch;
  found   : Long(in method add)
- required: Long(in package scala)
+ required: scala.Long
     else add2(x.head, y.head) :: add(x.tail, y.tail)
                 ^
 one error found
diff --git a/test/files/neg/unit2anyref.check b/test/files/neg/unit2anyref.check
new file mode 100644
index 0000000..2616fd3
--- /dev/null
+++ b/test/files/neg/unit2anyref.check
@@ -0,0 +1,8 @@
+unit2anyref.scala:2: error: type mismatch;
+ found   : Unit
+ required: AnyRef
+Note: primitive types are not implicitly converted to AnyRef.
+You can safely force boxing by casting x.asInstanceOf[AnyRef].
+  val x: AnyRef = ()  // this should not succeed.
+                  ^
+one error found
diff --git a/test/files/neg/unit2anyref.scala b/test/files/neg/unit2anyref.scala
new file mode 100644
index 0000000..1e9cdbf
--- /dev/null
+++ b/test/files/neg/unit2anyref.scala
@@ -0,0 +1,3 @@
+object Test {
+  val x: AnyRef = ()  // this should not succeed.
+}
diff --git a/test/files/neg/unreachablechar.check b/test/files/neg/unreachablechar.check
index 7442e11..58ce1a7 100644
--- a/test/files/neg/unreachablechar.check
+++ b/test/files/neg/unreachablechar.check
@@ -1,4 +1,4 @@
 unreachablechar.scala:5: error: unreachable code
     case 'f' => println("not stuff?");
-                ^
+                       ^
 one error found
diff --git a/test/files/neg/variances.check b/test/files/neg/variances.check
index d809d0f..d395e45 100644
--- a/test/files/neg/variances.check
+++ b/test/files/neg/variances.check
@@ -4,7 +4,13 @@ variances.scala:4: error: covariant type A occurs in contravariant position in t
 variances.scala:14: error: covariant type A occurs in contravariant position in type A of value a
     private[this] def setA(a : A) = this.a = a 
                            ^
-variances.scala:16: error: covariant type A occurs in invariant position in type test.C[A] with ScalaObject{def this(): object Foo.this.Baz} of object Baz
+variances.scala:16: error: covariant type A occurs in invariant position in supertype test.C[A] with ScalaObject of object Baz
     object Baz extends C[A]
            ^
-three errors found
+variances.scala:63: error: covariant type A occurs in contravariant position in type => test.Covariant.T[A]{val m: (A) => A} of value x
+    val x: T[A] {
+        ^
+variances.scala:79: error: covariant type T occurs in contravariant position in type => test.TestAlias.B[C.this.A] of method foo
+    def foo: B[A]
+        ^
+5 errors found
diff --git a/test/files/neg/variances.scala b/test/files/neg/variances.scala
index 10a2621..57abba1 100644
--- a/test/files/neg/variances.scala
+++ b/test/files/neg/variances.scala
@@ -58,4 +58,24 @@ object Covariant {
     val x : java.lang.Character = test.a.getA
     Console.println("XXX " + x)
   }
+
+  abstract class T[+A] {
+    val x: T[A] {
+      val m: A => A
+    }
+  }
+  object ST extends T[String] {
+    val x: T[String] { val m: String => String } = ST
+    val m: String => String = (_.substring(1))
+  }
+  val t: T[Any] = ST
+  t.x.m(new Object)
+}
+
+object TestAlias {
+  class B[-T]
+  trait C[+T] {
+    type A = T
+    def foo: B[A]
+  }
 }
diff --git a/test/files/neg/viewtest.check b/test/files/neg/viewtest.check
index 5415ba4..21ed93a 100644
--- a/test/files/neg/viewtest.check
+++ b/test/files/neg/viewtest.check
@@ -3,10 +3,4 @@ viewtest.scala:43: error: type mismatch;
  required: List[a(in method view3)]
         case y1: List[a] => compareLists(x, y1)
                                             ^
-viewtest.scala:104: error: ambiguous implicit values:
- both method view4 in object O of type [a](a)a
- and method identity in object Predef of type [A](A)A
- match expected type (test.Str) => test.Ordered[test.Str]
-        t = t insert Str(s)
-              ^
-two errors found
+one error found
diff --git a/test/files/neg/viewtest.scala b/test/files/neg/viewtest.scala
index 7547da3..ddb7fa4 100644
--- a/test/files/neg/viewtest.scala
+++ b/test/files/neg/viewtest.scala
@@ -12,13 +12,13 @@ trait Ordered[+a] {
    */
   def compareTo [b >: a <% Ordered[b]](that: b): Int
 
-  def <  [b >: a <% Ordered[b]](that: b): boolean = (this compareTo that) <  0
+  def <  [b >: a <% Ordered[b]](that: b): Boolean = (this compareTo that) <  0
 
-  def >  [b >: a <% Ordered[b]](that: b): boolean = (this compareTo that) >  0
+  def >  [b >: a <% Ordered[b]](that: b): Boolean = (this compareTo that) >  0
 
-  def <= [b >: a <% Ordered[b]](that: b): boolean = (this compareTo that) <= 0
+  def <= [b >: a <% Ordered[b]](that: b): Boolean = (this compareTo that) <= 0
 
-  def >= [b >: a <% Ordered[b]](that: b): boolean = (this compareTo that) >= 0
+  def >= [b >: a <% Ordered[b]](that: b): Boolean = (this compareTo that) >= 0
 }
 
 
@@ -30,9 +30,9 @@ object O {
       case _ => -(y compareTo x)
     }
   }
-  implicit def view2(x: char): Ordered[char] = new Ordered[char] {
-    def compareTo [b >: char <% Ordered[b]](y: b): Int = y match {
-      case y1: char => x - y1
+  implicit def view2(x: Char): Ordered[Char] = new Ordered[Char] {
+    def compareTo [b >: Char <% Ordered[b]](y: b): Int = y match {
+      case y1: Char => x - y1
       case _ => -(y compareTo x)
     }
   }
@@ -93,21 +93,21 @@ object Test {
   def main(args: Array[String]) = {
     {
       var t: Tree[String] = Empty
-      for (val s <- args) {
+      for (s <- args) {
         t = t insert s
       }
       Console.println(t.elements)
     }
     {
       var t: Tree[Str] = Empty
-      for (val s <- args) {
+      for (s <- args) {
         t = t insert Str(s)
       }
       Console.println(t.elements)
     }
     {
-      var t: Tree[List[char]] = Empty
-      for (val s <- args) {
+      var t: Tree[List[Char]] = Empty
+      for (s <- args) {
         t = t insert toCharList(s)
       }
       Console.println(t.elements)
diff --git a/test/files/neg/wellkinded_app2.scala b/test/files/neg/wellkinded_app2.scala
index 5b73611..7bb4c87 100644
--- a/test/files/neg/wellkinded_app2.scala
+++ b/test/files/neg/wellkinded_app2.scala
@@ -1,4 +1,4 @@
 // test well-kindedness checks
 class WellKinded[s <: Throwable] {
       val foo: s[Int]
-}
\ No newline at end of file
+}
diff --git a/test/files/neg/wellkinded_bounds.check b/test/files/neg/wellkinded_bounds.check
index 9099934..806eb09 100644
--- a/test/files/neg/wellkinded_bounds.check
+++ b/test/files/neg/wellkinded_bounds.check
@@ -1,4 +1,4 @@
-wellkinded_bounds.scala:2: error: class List takes type parameters
+wellkinded_bounds.scala:2: error: type List takes type parameters
 class WellKindedWrongSyntax[s <: List] { // must be s[x] <: List[x]
                                  ^
 one error found
diff --git a/test/files/neg/wellkinded_bounds.scala b/test/files/neg/wellkinded_bounds.scala
index 7b80ce1..cfa5e74 100644
--- a/test/files/neg/wellkinded_bounds.scala
+++ b/test/files/neg/wellkinded_bounds.scala
@@ -1,3 +1,3 @@
 // test well-kindedness checks -- syntax error
 class WellKindedWrongSyntax[s <: List] { // must be s[x] <: List[x]
-}
\ No newline at end of file
+}
diff --git a/test/files/neg/wellkinded_wrongarity.scala b/test/files/neg/wellkinded_wrongarity.scala
index 39f8b7a..2bb0e2c 100644
--- a/test/files/neg/wellkinded_wrongarity.scala
+++ b/test/files/neg/wellkinded_wrongarity.scala
@@ -2,4 +2,4 @@
 
 class Monad[m[x]]
 
-object mp extends Monad[Pair]
\ No newline at end of file
+object mp extends Monad[Pair]
diff --git a/test/files/neg/wellkinded_wrongarity2.scala b/test/files/neg/wellkinded_wrongarity2.scala
index 3154732..aac617b 100644
--- a/test/files/neg/wellkinded_wrongarity2.scala
+++ b/test/files/neg/wellkinded_wrongarity2.scala
@@ -9,4 +9,4 @@ trait ms3[m[_], t] extends Monad[m[t]] // wrong -- added to check regression on
 // expecting types of kind *
 trait Foo[x]
 trait Bar1[m[_]] extends Foo[m[Int]] // check that m[Int] is properly recognized as kind-*
-trait Bar2[m[_]] extends Foo[m] // check that m is properly recognized as kind *->*, while * is expected
\ No newline at end of file
+trait Bar2[m[_]] extends Foo[m] // check that m is properly recognized as kind *->*, while * is expected
diff --git a/test/files/neg/xmlcorner.check b/test/files/neg/xmlcorner.check
index 5d3e928..8791829 100644
--- a/test/files/neg/xmlcorner.check
+++ b/test/files/neg/xmlcorner.check
@@ -3,5 +3,5 @@ xmlcorner.scala:2: error: illegal start of simple expression
                   ^
 xmlcorner.scala:5: error: in XML literal: name cannot end in ':'
       val wrong = <bla:  />
-                      ^
+                       ^
 two errors found
diff --git a/test/files/pos/NoCyclicReference.scala b/test/files/pos/NoCyclicReference.scala
new file mode 100644
index 0000000..e428966
--- /dev/null
+++ b/test/files/pos/NoCyclicReference.scala
@@ -0,0 +1,7 @@
+package test
+
+trait Iterable[+A] { self =>
+
+  type CC[B] <: Iterable[B] { type CC[C] = self.CC[C] }
+
+}
diff --git a/test/files/pos/annotations.scala b/test/files/pos/annotations.scala
index 4e2bc6a..0819379 100644
--- a/test/files/pos/annotations.scala
+++ b/test/files/pos/annotations.scala
@@ -1,14 +1,26 @@
 class ann(i: Int) extends Annotation
+class cfann(x: String) extends ClassfileAnnotation
+
+// annotations on abstract types
+abstract class C1[@serializable @cloneable +T, U, V[_]]
+abstract class C2[@deprecated
+                  @ann(1) T <: Number,
+                  V]
+abstract class C3 {
+  @ann(2) type X <: Number
+}
 
 object Test {
 
   // bug #1028
   val x = 1
   @ann(x) val a = ()
-  @ann({val y = 2; y}) val b = ()
+  @ann({val yy = 2; yy}) val b = ()
+  val bb: Int @ann({val yy = 2; yy}) = 10
 
   def c: Int @ann(x) = 1
   def d: String @ann({val z = 0; z - 1}) = "2"
+  def e[@deprecated T, U](x: T) = x
 
   //bug #1214
   val y = new (Integer @ann(0))(2)
@@ -21,5 +33,78 @@ object Test {
 
   // bug #1070
   trait T { @BeanProperty var field = 1 }
+
+  // annotation on annotation constructor
+  @(ann @ann(100))(200) def foo() = 300
+
+  // #2984
+  private final val NAMESPACE = "/info"
+  @cfann(x = NAMESPACE + "/index") def index = "success"
+}
+
+// test forward references to getters / setters
+class BeanPropertyTests {
+  @scala.reflect.BeanProperty lazy val lv1 = 0
+
+  def foo() {
+    val bp1 = new BeanPropertyTests1
+
+    println(lv1)
+    println(getLv1())
+    println(bp1.getLv2())
+
+    println(getV1())
+    setV1(10)
+    bp1.setV2(100)
+  }
+
+  @scala.reflect.BeanProperty var v1 = 0
+
+}
+
+class BeanPropertyTests1 {
+  @scala.reflect.BeanProperty lazy val lv2 = "0"
+  @scala.reflect.BeanProperty var v2 = 0
 }
 
+// test mixin of getters / setters, and implementing abstract
+// methods using @BeanProperty
+class C extends T with BeanF {
+  def foo() {
+    setF("doch!")
+    setG(true)
+    this.getF()
+  }
+}
+
+trait T {
+  @scala.reflect.BeanProperty var f = "nei"
+  @scala.reflect.BooleanBeanProperty var g = false
+}
+
+trait BeanF {
+  def getF(): String
+  def setF(n: String): Unit
+
+  def isG(): Boolean
+  def setG(nb: Boolean): Unit
+}
+
+
+class Ann3(arr: Array[String]) extends ClassfileAnnotation
+class Ann4(i: Int) extends ClassfileAnnotation
+class Ann5(value: Class[_]) extends ClassfileAnnotation
+
+object Test3 {
+  final val i = 1083
+  final val cls = classOf[String]
+}
+
+class Test4 {
+  @Ann3(arr = Array("dlkfj", "DSF"))
+  @Ann4(i = 2908)
+  @Ann4(i = Test3.i)
+  @Ann5(value = classOf[Int])
+  @Ann5(Test3.cls)
+  def foo {}
+}
diff --git a/test/files/pos/arrays2.scala b/test/files/pos/arrays2.scala
index 6f4a09a..2d5409c 100644
--- a/test/files/pos/arrays2.scala
+++ b/test/files/pos/arrays2.scala
@@ -9,3 +9,15 @@ object arrays2 {
   }
 }
 
+// #2422
+object arrays4 {
+  val args = Array[String]("World") 
+  "Hello %1$s".format(args: _*) 
+}
+
+// #2461
+object arrays3 {
+  import scala.collection.JavaConversions._
+  def apply[X](xs : X*) : java.util.List[X] = java.util.Arrays.asList(xs: _*)
+}
+
diff --git a/test/files/pos/attributes.scala b/test/files/pos/attributes.scala
index c57ba91..f3bbb4c 100644
--- a/test/files/pos/attributes.scala
+++ b/test/files/pos/attributes.scala
@@ -1,5 +1,3 @@
-/* $Id: attributes.scala 13860 2008-02-01 15:27:55Z phaller $ */
-
 @serializable  class C1;
 @serializable @volatile  class C2;
 @serializable @volatile  class C3;
@@ -37,9 +35,10 @@ abstract class A1 {
 
 object O6 {
   @serializable  val x1 = new C1;
-  @serializable @volatile  val x2 = new C2;
-  @serializable @volatile  val x3 = new C3;
-  @serializable @volatile @serializable  val x4 = new C4;
+  // volatile val sensibly disallowed as of r18645
+  @serializable val x2 = new C2;
+  @serializable val x3 = new C3;
+  @serializable val x4 = new C4;
 
   @serializable  var y1: C1 = _;
   @serializable @volatile  var y2: C2 = _;
diff --git a/test/files/pos/bounds.scala b/test/files/pos/bounds.scala
index 5bc5cf8..cfea462 100644
--- a/test/files/pos/bounds.scala
+++ b/test/files/pos/bounds.scala
@@ -7,5 +7,5 @@ class ListMap[A, +B] extends Map[A, B] {}
 
 object ListMap {
   def empty[X, Y] = new ListMap[X, Y]
-  def apply[A1, B2](elems: Pair[A1, B2]*): Map[A1, B2] = empty[A1,B2].++(elems.elements)
+  def apply[A1, B2](elems: Pair[A1, B2]*): Map[A1, B2] = empty[A1,B2].++(elems.iterator)
 }
diff --git a/test/files/pos/bug0029.scala b/test/files/pos/bug0029.scala
index 1b33c6c..0af45ab 100644
--- a/test/files/pos/bug0029.scala
+++ b/test/files/pos/bug0029.scala
@@ -1,3 +1,3 @@
 object Main {
-  def f[a]: List[List[a]] = for (val l1 <- Nil; val l2 <- Nil) yield l1;
+  def f[a]: List[List[a]] = for (val l1 <- Nil; val l2 <- Nil) yield l1
 }
diff --git a/test/files/pos/bug0091.scala b/test/files/pos/bug0091.scala
index 54c821b..d491b7c 100644
--- a/test/files/pos/bug0091.scala
+++ b/test/files/pos/bug0091.scala
@@ -1,6 +1,6 @@
 class Bug {
   def main(args: Array[String]) = {
     var msg: String = null; // no bug if "null" instead of "_"
-    val f:  PartialFunction[Any, unit] = { case 42 => msg = "coucou" };
+    val f:  PartialFunction[Any, Unit] = { case 42 => msg = "coucou" };
   }
 }
diff --git a/test/files/pos/bug0646.scala b/test/files/pos/bug0646.scala
index f9af2f8..6146e60 100644
--- a/test/files/pos/bug0646.scala
+++ b/test/files/pos/bug0646.scala
@@ -10,7 +10,7 @@ object xfor {
     </bks>;
 
   new NodeSeq { val theSeq = books.child }  match {
-    case t @ <title>Blabla</title> => t
+    case t @ Seq(<title>Blabla</title>) => t
   }
 
   //val n: NodeSeq = new NodeSeq { val theSeq = books.child } 
diff --git a/test/files/pos/bug1001.scala b/test/files/pos/bug1001.scala
index 1b909fb..776a334 100644
--- a/test/files/pos/bug1001.scala
+++ b/test/files/pos/bug1001.scala
@@ -101,5 +101,5 @@ object N26 extends Ee
 object N31 extends Ee
 {
     // If we use List[C](N26,N25), we achieve successful compilation
-    val data = List(N26,N25)
+    val data = List[C](N26,N25)
 }
diff --git a/test/files/pos/bug1049.scala b/test/files/pos/bug1049.scala
index 452259b..3cc9d0c 100644
--- a/test/files/pos/bug1049.scala
+++ b/test/files/pos/bug1049.scala
@@ -2,6 +2,6 @@ package bug1049
 
 abstract class Test {
   type T <: A
-  class A requires T
-  class B requires T extends A
+  class A { self: T => }
+  class B extends A { self: T => }
 }
diff --git a/test/files/pos/bug1050.scala b/test/files/pos/bug1050.scala
index 8ca7971..1dfa20c 100644
--- a/test/files/pos/bug1050.scala
+++ b/test/files/pos/bug1050.scala
@@ -2,7 +2,7 @@ package bug1050
 
 abstract class A {
   type T <: scala.ScalaObject
-  class A requires T {
+  class A { this: T =>
     def b = 3
     def c = b
     b
diff --git a/test/pending/pos/bug1070.scala b/test/files/pos/bug1070.scala
similarity index 100%
rename from test/pending/pos/bug1070.scala
rename to test/files/pos/bug1070.scala
diff --git a/test/files/pos/bug1075.scala b/test/files/pos/bug1075.scala
index 936ef72..0f518b2 100644
--- a/test/files/pos/bug1075.scala
+++ b/test/files/pos/bug1075.scala
@@ -5,7 +5,7 @@ class Directory(var dir_ : String)
   }
   dir_ = dir_.replaceAll("/{2,}", "/")
 
-  def this(serialized : Array[byte]) = {
+  def this(serialized : Array[Byte]) = {
     this(new String(serialized, "UTF-8"))
   }
 
diff --git a/test/files/pos/bug1085.scala b/test/files/pos/bug1085.scala
index 8330b7e..c59e657 100644
--- a/test/files/pos/bug1085.scala
+++ b/test/files/pos/bug1085.scala
@@ -6,4 +6,4 @@ object Test {
   def listFunctor[a]: Functor[a]{type MyType[x]=List[x]} = new Functor[a] {
     type MyType[t]=List[t]
   }
-}
\ No newline at end of file
+}
diff --git a/test/files/pos/bug1090.scala b/test/files/pos/bug1090.scala
index c34ec0a..dca762a 100644
--- a/test/files/pos/bug1090.scala
+++ b/test/files/pos/bug1090.scala
@@ -1,7 +1,7 @@
 object Test {
   trait Manager {
     type Node;
-    def elements : Iterator[Node]
+    def iterator : Iterator[Node]
   }
   trait Core {
     type Node;
@@ -9,8 +9,8 @@ object Test {
     trait Manager extends Test.Manager {
       type Node = Core.this.Node
     }
-    def f(manager : Manager) = manager.elements.foreach{
+    def f(manager : Manager) = manager.iterator.foreach{
       case node : NodeImpl => 
     }
   }
-}
\ No newline at end of file
+}
diff --git a/test/files/pos/bug1136.check b/test/files/pos/bug1136.check
deleted file mode 100644
index 0747cdd..0000000
--- a/test/files/pos/bug1136.check
+++ /dev/null
@@ -1,2 +0,0 @@
-warning: there were unchecked warnings; re-run with -unchecked for details
-one warning found
diff --git a/test/files/pos/bug116.scala b/test/files/pos/bug116.scala
index 2b1b4e9..1e31b71 100644
--- a/test/files/pos/bug116.scala
+++ b/test/files/pos/bug116.scala
@@ -1,5 +1,3 @@
-// $Id: bug116.scala 5359 2005-12-16 15:33:49Z dubochet $
-
 class C {
   def this(x: Int) = {
     this();
diff --git a/test/files/pos/bug1185.scala b/test/files/pos/bug1185.scala
new file mode 100644
index 0000000..de453ec
--- /dev/null
+++ b/test/files/pos/bug1185.scala
@@ -0,0 +1,15 @@
+class Test {
+  private[this] var member = 0;
+  def foo() = {
+    (() => member=1)()
+  }
+  def look=member
+}
+
+object Main{
+  def main(args : Array[String]){
+    val fff=new Test()
+    fff.foo()
+    assert(1==fff.look)
+  }
+}
diff --git a/test/files/pos/bug1210a.scala b/test/files/pos/bug1210a.scala
index 5a867d5..fbb0a61 100644
--- a/test/files/pos/bug1210a.scala
+++ b/test/files/pos/bug1210a.scala
@@ -12,4 +12,4 @@ trait FP {
   abstract class Test[T] {
     val v: Test[T] = v.v
   }
-}
\ No newline at end of file
+}
diff --git a/test/files/pos/bug1272.scala b/test/files/pos/bug1272.scala
new file mode 100644
index 0000000..aab1a88
--- /dev/null
+++ b/test/files/pos/bug1272.scala
@@ -0,0 +1,9 @@
+object ImplicitTest {
+  implicit val i : Int = 10
+  implicit def a(implicit i : Int) : Array[Byte] = null
+  implicit def b[T](implicit i : Int) : Array[T] = null
+  
+  def fn[T](implicit x : T) = 0
+  
+  val x = fn[Array[Byte]]
+}
\ No newline at end of file
diff --git a/test/files/pos/bug1279a.scala b/test/files/pos/bug1279a.scala
new file mode 100644
index 0000000..9212b58
--- /dev/null
+++ b/test/files/pos/bug1279a.scala
@@ -0,0 +1,40 @@
+// see #13
+// providing the type parameter in the recursive call to all4Impl
+// avoids the problem
+
+
+// covariant linked list
+abstract class M
+{ self =>
+
+    type T
+    final type selfType = M {type T <: self.T}
+    type actualSelfType >: self.type <: selfType
+
+    def next: selfType
+
+
+    // I don't understand why this doesn't compile, but that's a separate matter
+    // error: method all2 cannot be accessed in M.this.selfType
+    // because its instance type => Stream[M{type T <: M.this.selfType#T}]
+    // contains a malformed type: M.this.selfType#T
+    // def all2: Stream[M {type T <: self.T}] = Stream.cons(self: actualSelfType, next.all2)
+
+
+    // compiles successfully
+    // def all3: Stream[M {type T <: self.T}] = all3Impl(self: actualSelfType)
+    // private def all3Impl(first: M {type T <: self.T}): Stream[M {type T <: self.T}] = Stream.cons(first, all3Impl(first.next))
+
+
+
+    def all4: Stream[M {type T <: self.T}] = Unrelated.all4Impl[T](self: actualSelfType)
+}
+
+object Unrelated
+{
+  // TODO!!! fix this bug for real, it compiles successfully, but weird types are inferred
+   // def all4Impl[U](first: M {type T <: U}): Stream[M {type T <: U}] = Stream.cons(first, all4Impl(first.next))
+
+// compiles successfully
+     def all4Impl[U](first: M {type T <: U}): Stream[M {type T <: U}] = Stream.cons(first, all4Impl[U](first.next))
+}
diff --git a/test/files/pos/bug1381.scala b/test/files/pos/bug1381.scala
new file mode 100644
index 0000000..0762891
--- /dev/null
+++ b/test/files/pos/bug1381.scala
@@ -0,0 +1,31 @@
+import scala.reflect.Manifest
+
+class D[V <: Variable]
+
+class ID[V<:IV] extends D[V] {
+  type E = V#ValueType
+  def index(value:E) : Int = 0
+  // Comment this out to eliminate crash.  Or see below
+  def index(values:E*) : Iterable[Int] = null
+}
+
+abstract class Variable {
+  type VT <: Variable
+  def d : D[VT] = null
+}
+
+abstract class PV[T](initval:T) extends Variable  {
+  type VT <: PV[T]
+  type ValueType = T
+}
+
+trait IV extends Variable  {
+  type ValueType
+}
+
+abstract class EV[T](initval:T) extends PV[T](initval) with IV {
+  type VT <: EV[T]
+  override def d : ID[VT] = null
+  // Comment this out to eliminate crash
+  protected var indx = d.index(initval)
+}
diff --git a/test/files/pos/bug1385.scala b/test/files/pos/bug1385.scala
new file mode 100644
index 0000000..59953bc
--- /dev/null
+++ b/test/files/pos/bug1385.scala
@@ -0,0 +1,3 @@
+ at serializable object Test {                    
+  private def readResolve:AnyRef = this
+}
diff --git a/test/files/pos/bug1560.scala b/test/files/pos/bug1560.scala
new file mode 100644
index 0000000..b1d0415
--- /dev/null
+++ b/test/files/pos/bug1560.scala
@@ -0,0 +1,11 @@
+object Test extends Application {
+  trait C[T] {
+    def t: T
+  }
+  
+  def b: Option[C[_]] = null
+  
+  def c = b match {
+    case Some(b) => b.t
+  } 
+}
diff --git a/test/files/pos/bug1565.scala b/test/files/pos/bug1565.scala
new file mode 100644
index 0000000..030086c
--- /dev/null
+++ b/test/files/pos/bug1565.scala
@@ -0,0 +1,18 @@
+object Bug1565 {
+  object X0 { 0;  (a : Int, b : Int, c : Int) => println(List(a, b))   }
+  def x() = { 0; (a : Int, b : Int) => println(List(a, b)) ; 0  }
+
+  (a : Int, b : Int) => println(List(a, b))
+  
+  // various function syntaxes to exercise the parser
+  val xs = List(1,2,3)
+  xs.filter(x => x < 2)
+  xs.filter((x) => x < 2)
+  xs.filter { x => x < 2 }
+  xs.filter { _ < 2 }
+  xs.filter (_ < 2)
+  xs.foreach { e =>
+    val buf0 = e + 1
+    buf0
+  }
+}
diff --git a/test/files/pos/bug160.scala b/test/files/pos/bug160.scala
index 0f765d9..91ac2ba 100644
--- a/test/files/pos/bug160.scala
+++ b/test/files/pos/bug160.scala
@@ -1,5 +1,3 @@
-// $Id: bug160.scala 5359 2005-12-16 15:33:49Z dubochet $
-
 class Foo(s:String) {
   def this() = { this("DEFAULT") }
 }
diff --git a/test/files/pos/bug1626.scala b/test/files/pos/bug1626.scala
new file mode 100644
index 0000000..200be47
--- /dev/null
+++ b/test/files/pos/bug1626.scala
@@ -0,0 +1,4 @@
+object o {
+  val n = <a xmlns=""/>
+  n.namespace == null
+}
diff --git a/test/files/pos/bug1737/A.java b/test/files/pos/bug1737/A.java
new file mode 100644
index 0000000..ee87e29
--- /dev/null
+++ b/test/files/pos/bug1737/A.java
@@ -0,0 +1,3 @@
+public interface A<T extends String> {
+    T get();
+}
\ No newline at end of file
diff --git a/test/files/pos/bug1737/B.java b/test/files/pos/bug1737/B.java
new file mode 100644
index 0000000..28a1907
--- /dev/null
+++ b/test/files/pos/bug1737/B.java
@@ -0,0 +1 @@
+public abstract class B implements A {}
\ No newline at end of file
diff --git a/test/files/pos/bug1737/c.scala b/test/files/pos/bug1737/c.scala
new file mode 100644
index 0000000..782ec18
--- /dev/null
+++ b/test/files/pos/bug1737/c.scala
@@ -0,0 +1,4 @@
+class C extends B {
+    this: A[_] =>
+    def get = "foo"
+}
\ No newline at end of file
diff --git a/test/files/pos/bug175.scala b/test/files/pos/bug175.scala
index 9ad1934..4c0eb28 100644
--- a/test/files/pos/bug175.scala
+++ b/test/files/pos/bug175.scala
@@ -1,5 +1,3 @@
-// $Id: bug175.scala 5359 2005-12-16 15:33:49Z dubochet $
-
 abstract class C {
   def this(x: Unit) = { this() }
 }
diff --git a/test/files/pos/bug177.scala b/test/files/pos/bug177.scala
index b3e13dc..33b4de9 100644
--- a/test/files/pos/bug177.scala
+++ b/test/files/pos/bug177.scala
@@ -1,5 +1,3 @@
-// $Id: bug177.scala 5359 2005-12-16 15:33:49Z dubochet $
-
 class A {
   def foo = {
     object Y {
diff --git a/test/files/pos/bug183.scala b/test/files/pos/bug183.scala
index 463f5a9..d7ed27f 100644
--- a/test/files/pos/bug183.scala
+++ b/test/files/pos/bug183.scala
@@ -1,5 +1,3 @@
-// $Id: bug183.scala 5359 2005-12-16 15:33:49Z dubochet $
-
 object Test {
   new Foo(0);
   class Foo(x: Int);
diff --git a/test/files/pos/bug1843.scala b/test/files/pos/bug1843.scala
new file mode 100644
index 0000000..cc73353
--- /dev/null
+++ b/test/files/pos/bug1843.scala
@@ -0,0 +1,25 @@
+/**
+* Scala Compiler Will Crash On this File
+* ... Or Will It?
+*
+*/
+
+object Crash {
+  trait UpdateType[A]
+  case class StateUpdate[A](updateType : UpdateType[A], value : A)
+  case object IntegerUpdateType extends UpdateType[Integer]
+
+  //However this method will cause a crash
+  def crash(updates: List[StateUpdate[_]]) {
+    updates match {
+      case Nil =>
+      case u::us =>
+        u match {
+          //Line below seems to be the crashing line
+          case StateUpdate(key, newValue) if (key == IntegerUpdateType) =>
+            println("Requires a statement to induce the crash")
+          case _ =>
+        }
+    }
+  }
+}
diff --git a/test/files/pos/bug1858.scala b/test/files/pos/bug1858.scala
new file mode 100644
index 0000000..c06e73e
--- /dev/null
+++ b/test/files/pos/bug1858.scala
@@ -0,0 +1,13 @@
+import scala.collection.immutable.Stack
+
+object Test {
+
+  def test = {
+    val s = new Stack[Int]
+    s.push(1)
+    s.push(1, 2)
+    s.push(1, 2, 3)
+    s.push(1, 2, 3, 4)
+  }
+
+}
diff --git a/test/files/pos/bug1909.scala b/test/files/pos/bug1909.scala
new file mode 100644
index 0000000..01213f6
--- /dev/null
+++ b/test/files/pos/bug1909.scala
@@ -0,0 +1,8 @@
+// Until #1909 is fixed, if this compiles the bytecode
+// will trigger a VerifyError.  This liftings and the one
+// in 1909b.scala actually happen in two different places
+// (uncurry and lambdalifter.)
+class Ticket1909 {
+  def this(value: Int) = this()
+  def this(p: String) = this(try 0)
+}
diff --git a/test/files/pos/bug1909b.scala b/test/files/pos/bug1909b.scala
new file mode 100644
index 0000000..b914bee
--- /dev/null
+++ b/test/files/pos/bug1909b.scala
@@ -0,0 +1,6 @@
+class Ticket1909 (x: Int) {
+  def this() = this({
+    def bar() = 5
+    bar
+  })
+}
\ No newline at end of file
diff --git a/test/files/pos/bug2018.scala b/test/files/pos/bug2018.scala
new file mode 100644
index 0000000..1736c39
--- /dev/null
+++ b/test/files/pos/bug2018.scala
@@ -0,0 +1,15 @@
+class A {
+  val b = new B
+
+  def getChildren = List(new A).iterator
+
+  class B {
+    private def check = true
+
+    private def getAncestor(p: A): A = {
+      val c = (p.getChildren.find(_.b.check)) match {case Some(d) => d case None => p}
+
+      if (c == p) p else c.b.getAncestor(c)
+    }
+  }
+}
\ No newline at end of file
diff --git a/test/files/pos/bug2023.scala b/test/files/pos/bug2023.scala
new file mode 100644
index 0000000..de3e848
--- /dev/null
+++ b/test/files/pos/bug2023.scala
@@ -0,0 +1,16 @@
+trait C[A]
+
+object C {
+  implicit def ipl[A](implicit from: A => Ordered[A]): C[A] = null
+}
+	
+object P {
+  def foo[A](i: A, j: A)(implicit c: C[A]): Unit = ()
+}
+	
+class ImplicitChainTest {
+  def testTrivial: Unit = {
+    P.foo('0', '9')
+    P.foo('0', '9')
+  }
+}
diff --git a/test/files/pos/bug2081.scala b/test/files/pos/bug2081.scala
new file mode 100644
index 0000000..d772c02
--- /dev/null
+++ b/test/files/pos/bug2081.scala
@@ -0,0 +1,11 @@
+object ScalaForRubyists {
+  class RichInt(n: Int) {
+    def days = 1000*60*60*24*n
+  }
+
+  implicit def RichInt(n: Int): RichInt = new RichInt(n)
+
+  val x = 10.days
+  // a couple parser corner cases I wanted not to break
+  val y = 5.e0 + 5e7  
+}
diff --git a/test/files/pos/bug2127.scala b/test/files/pos/bug2127.scala
new file mode 100644
index 0000000..d6244c1
--- /dev/null
+++ b/test/files/pos/bug2127.scala
@@ -0,0 +1,5 @@
+class Foo private (val value : Int)
+
+abstract class Bar(val ctor : (Int) => Foo)
+
+object Foo extends Bar(new Foo(_)) //<--- ILLEGAL ACCESS
\ No newline at end of file
diff --git a/test/files/pos/bug2168.scala b/test/files/pos/bug2168.scala
new file mode 100644
index 0000000..d7bfa96
--- /dev/null
+++ b/test/files/pos/bug2168.scala
@@ -0,0 +1,6 @@
+object Test extends Application {
+  def foo1(x: AnyRef) = x match { case x: Function0[_] => x() }
+  def foo2(x: AnyRef) = x match { case x: Function0[Any] => x() }
+}
+  
+  
diff --git a/test/files/pos/bug2187-2.scala b/test/files/pos/bug2187-2.scala
new file mode 100644
index 0000000..3f2742d
--- /dev/null
+++ b/test/files/pos/bug2187-2.scala
@@ -0,0 +1,7 @@
+class Test {
+  def test[A](list: List[A]) = list match {
+    case Seq(x, y) => "xy"
+    case Seq(x) => "x"
+    case _ => "something else"
+  }
+}
\ No newline at end of file
diff --git a/test/files/pos/bug2187.scala b/test/files/pos/bug2187.scala
new file mode 100644
index 0000000..003b8c1
--- /dev/null
+++ b/test/files/pos/bug2187.scala
@@ -0,0 +1,7 @@
+// bug #2187
+object Test extends Application {
+  def foo(xs:List[String]) = xs match {
+    case Seq(x) => x
+    case Seq(x,y) => ""
+  }
+}
diff --git a/test/files/pos/bug2260.scala b/test/files/pos/bug2260.scala
new file mode 100644
index 0000000..4e4cc5a
--- /dev/null
+++ b/test/files/pos/bug2260.scala
@@ -0,0 +1,10 @@
+package top
+
+class Text(val value: String) extends Ordered[Text] {
+  def compare(that: Text) = value.compare(that.value)
+}
+
+object Index {
+  import scala.collection.immutable.TreeMap
+  val tree = TreeMap.empty[Text, String]
+}
diff --git a/test/files/pos/bug2261.scala b/test/files/pos/bug2261.scala
new file mode 100644
index 0000000..a499af8
--- /dev/null
+++ b/test/files/pos/bug2261.scala
@@ -0,0 +1,6 @@
+object Test extends Application {
+  class Bob[T]
+  implicit def foo2bar[T](xs: List[T]): Bob[T] = new Bob[T]
+  var x: Bob[Int] = null
+  x = List(1,2,3)
+}
diff --git a/test/files/pos/bug2310.scala b/test/files/pos/bug2310.scala
new file mode 100644
index 0000000..e08411a
--- /dev/null
+++ b/test/files/pos/bug2310.scala
@@ -0,0 +1,38 @@
+import scala.Stream._
+
+object consistencyError {
+  /* this gives an error: 
+  Consistency problem compiling (virtual file)!
+  Trying to call method body%1(List(scala.collection.immutable.Stream[A])) with arguments (List(tp2, temp6, temp5))
+      case (l #:: ls, rs) => None
+                              ^
+  scala.tools.nsc.symtab.Types$TypeError: too many arguments for method body%1: (val rs: scala.collection.immutable.Stream[A])None.type
+  
+  two errors found
+  vss(0) = 
+  args = List(tp2, temp6, temp5)
+  vss(1) = value rs, value ls, value l
+  args = List(tp2, temp6, temp5)
+  targets(0) = FinalState(,scala.None)
+  targets(1) = FinalState(,scala.None)
+  labels(1) = method body%1
+  labels(0) = method body%0
+  bx = 1
+  label.tpe = (val rs: scala.collection.immutable.Stream[A])None.type    
+  */
+  def crash[A](lefts: Stream[A], rights: Stream[A]) = (lefts, rights) match {
+    case (Stream.Empty, Stream.Empty) => None
+    case (l #:: ls, rs) => None
+  }
+  
+  // These work
+  // def works1[A](lefts: Stream[A]) = lefts match {
+  //   case Stream.Empty => None
+  //   case l #:: ls => None
+  // }
+  // 
+  // def works2[A](lefts: Stream[A], rights: Stream[A]) = (lefts, rights) match {
+  //   case (Stream.Empty, Stream.Empty) => None
+  //   case (ls, rs) => None
+  // }
+}
diff --git a/test/files/pos/bug2409/J.java b/test/files/pos/bug2409/J.java
new file mode 100644
index 0000000..6b7c45f
--- /dev/null
+++ b/test/files/pos/bug2409/J.java
@@ -0,0 +1,4 @@
+class J {
+	static class J2 { }
+	J(J2 j2) { }
+}
diff --git a/test/files/pos/bug2409/bug2409.scala b/test/files/pos/bug2409/bug2409.scala
new file mode 100644
index 0000000..5775008
--- /dev/null
+++ b/test/files/pos/bug2409/bug2409.scala
@@ -0,0 +1 @@
+object S { new J(null) }
\ No newline at end of file
diff --git a/test/files/pos/bug247.scala b/test/files/pos/bug247.scala
index edc623c..983b799 100644
--- a/test/files/pos/bug247.scala
+++ b/test/files/pos/bug247.scala
@@ -16,10 +16,11 @@ class Tree[KEY,Entry](order:Order[KEY]) {
   def size =0;
 }
 
-class TreeMap[KEY,VALUE](_factory:TreeMapFactory[KEY]) extends Tree[KEY,Pair[KEY,VALUE]](_factory.order) with Map[KEY, VALUE] {
+class TreeMap[KEY,VALUE](_factory:TreeMapFactory[KEY]) extends Tree[KEY,Pair[KEY,VALUE]](_factory.order) with scala.collection.DefaultMap[KEY, VALUE] with Map[KEY, VALUE] {
   val factory = _factory
   val order = _factory.order;
   def this(newOrder:Order[KEY]) = this(new TreeMapFactory[KEY](newOrder));
   def get(key:KEY) = null;
-  def elements:Iterator[Pair[KEY,VALUE]] = null;
+  def iterator:Iterator[Pair[KEY,VALUE]] = null;
+  override def size = super[Tree].size
 }
diff --git a/test/files/pos/bug2486.scala b/test/files/pos/bug2486.scala
new file mode 100644
index 0000000..69fe4c1
--- /dev/null
+++ b/test/files/pos/bug2486.scala
@@ -0,0 +1,3 @@
+class A[T]
+class B extends A[Int]
+class C[T] extends A[T] { def f(t: A[T]) = t match { case x: B => () } }
diff --git a/test/files/pos/bug252.scala b/test/files/pos/bug252.scala
new file mode 100644
index 0000000..b10811f
--- /dev/null
+++ b/test/files/pos/bug252.scala
@@ -0,0 +1,17 @@
+abstract class Module {}
+
+abstract class T {
+  type moduleType <: Module
+  val module: moduleType
+}
+
+abstract class Base {
+  type mType = Module
+  type tType = T { type moduleType <: mType }
+}
+
+abstract class Derived extends Base {
+  def f(inputs: List[tType]): Unit = {
+    for (t <- inputs; val m = t.module) { }
+  }
+}
diff --git a/test/files/pos/bug2691.scala b/test/files/pos/bug2691.scala
new file mode 100644
index 0000000..d289605
--- /dev/null
+++ b/test/files/pos/bug2691.scala
@@ -0,0 +1,10 @@
+object Breakdown {
+  def unapplySeq(x: Int): Some[List[String]] = Some(List("", "there")) 
+}
+object Test {
+  42 match {
+    case Breakdown("") =>  // needed to trigger bug
+    case Breakdown("foo") =>  // needed to trigger bug
+    case Breakdown("", who) => println ("hello " + who)
+  }
+}
diff --git a/test/files/pos/bug284.scala b/test/files/pos/bug284.scala
new file mode 100644
index 0000000..19673b7
--- /dev/null
+++ b/test/files/pos/bug284.scala
@@ -0,0 +1,5 @@
+trait B[T] {
+    def f1(a: T): Unit { }
+    def f2(a: T): Unit
+    def f3(a: T) { }
+}
diff --git a/test/files/pos/bug287.scala b/test/files/pos/bug287.scala
index 81a0195..8e5e883 100644
--- a/test/files/pos/bug287.scala
+++ b/test/files/pos/bug287.scala
@@ -1,7 +1,7 @@
 object testBuf {
   class mystream extends java.io.BufferedOutputStream(new java.io.FileOutputStream("/dev/null")) {
     def w( x:String ):Unit = {
-      val foo = new Array[byte](2);
+      val foo = new Array[Byte](2);
 
       // write( byte[] ) is defined in FilterOutputStream, the superclass of BufferedOutputStream
       super.write( foo ); // error
diff --git a/test/files/pos/bug289.scala b/test/files/pos/bug289.scala
index ea591be..96c0244 100644
--- a/test/files/pos/bug289.scala
+++ b/test/files/pos/bug289.scala
@@ -1,5 +1,3 @@
-// $Id: bug289.scala 5359 2005-12-16 15:33:49Z dubochet $
-
 class A {
   object B;
 }
diff --git a/test/files/pos/bug2939.scala b/test/files/pos/bug2939.scala
new file mode 100644
index 0000000..67677f2
--- /dev/null
+++ b/test/files/pos/bug2939.scala
@@ -0,0 +1,13 @@
+import collection._
+
+object Proxies {
+  class C1 extends MapProxy[Int,Int] { def self = Map[Int,Int]() }
+  class C2 extends mutable.MapProxy[Int,Int] { def self = mutable.Map[Int,Int]() }
+  class C3 extends immutable.MapProxy[Int,Int] { def self = immutable.Map[Int,Int]() }
+  
+  class C4 extends SetProxy[Int] { def self = Set[Int]() }
+  class C5 extends mutable.SetProxy[Int] { def self = mutable.Set[Int]() }
+  class C6 extends immutable.SetProxy[Int] { def self = immutable.Set[Int]() }
+  
+  class C7 extends SeqProxy[Int] { def self = Seq[Int]() }
+}
\ No newline at end of file
diff --git a/test/files/pos/bug2945.scala b/test/files/pos/bug2945.scala
new file mode 100644
index 0000000..762bdb6
--- /dev/null
+++ b/test/files/pos/bug2945.scala
@@ -0,0 +1,12 @@
+object Foo {
+  def test(s: String) = {
+    (s: Seq[Char]) match {
+        case Seq('f', 'o', 'o', ' ', rest1 @ _*) =>
+          rest1
+        case Seq('b', 'a', 'r', ' ', ' ', rest2 @ _*) =>
+          rest2
+        case _ =>
+          s
+    }
+  }
+}
\ No newline at end of file
diff --git a/test/files/pos/bug3020.scala b/test/files/pos/bug3020.scala
new file mode 100644
index 0000000..cb429cd
--- /dev/null
+++ b/test/files/pos/bug3020.scala
@@ -0,0 +1,9 @@
+object Test {
+  def main(args: Array[String]): Unit = {
+    var x = true
+    
+    ( { if (x) new scala.util.Random() } .asInstanceOf[Runnable] )
+  }
+}
+
+
diff --git a/test/files/pos/bug3097.flags b/test/files/pos/bug3097.flags
new file mode 100644
index 0000000..144ddac
--- /dev/null
+++ b/test/files/pos/bug3097.flags
@@ -0,0 +1 @@
+-unchecked -Xfatal-warnings
diff --git a/test/files/pos/bug3097.scala b/test/files/pos/bug3097.scala
new file mode 100644
index 0000000..a034b96
--- /dev/null
+++ b/test/files/pos/bug3097.scala
@@ -0,0 +1,31 @@
+package seal
+
+sealed trait ISimpleValue
+
+sealed trait IListValue extends ISimpleValue {
+  def items: List[IAtomicValue[_]]
+}
+sealed trait IAtomicValue[O] extends ISimpleValue {
+  def data: O
+}
+
+sealed trait IAbstractDoubleValue[O] extends IAtomicValue[O] { }
+sealed trait IDoubleValue extends IAbstractDoubleValue[Double]
+
+case class ListValue(val items: List[IAtomicValue[_]]) extends IListValue
+class DoubleValue(val data: Double) extends IDoubleValue {
+  def asDouble = data
+}
+
+object Test {
+  /**
+   * @param args the command line arguments
+   */
+  def main(args: Array[String]): Unit = {
+    val v: ISimpleValue = new DoubleValue(1)
+    v match {
+      case m: IListValue => println("list")
+      case a: IAtomicValue[_] => println("atomic")
+    }
+  }
+}
diff --git a/test/files/pos/bug3136.scala b/test/files/pos/bug3136.scala
new file mode 100644
index 0000000..6a5850a
--- /dev/null
+++ b/test/files/pos/bug3136.scala
@@ -0,0 +1,19 @@
+class Type
+class Symbol
+case class PolyType(tps: List[Symbol], res: Type) extends Type
+class OtherType extends Type
+
+// case class NullaryMethodType(tp: Type) extends Type
+
+object NullaryMethodType {
+  def apply(resTpe: Type): Type = PolyType(List(), resTpe)
+  def unapply(tp: Type): Option[(Type)] = None
+}
+
+object Test {
+  def TEST(tp: Type): String = 
+    tp match {
+      case PolyType(ps1, PolyType(ps2, res @ PolyType(a, b))) => "1"+tp // couldn't find a simpler version that still crashes
+      case NullaryMethodType(meh) => "2"+meh
+    }
+}
diff --git a/test/files/pos/bug3175.scala b/test/files/pos/bug3175.scala
new file mode 100644
index 0000000..497ff82
--- /dev/null
+++ b/test/files/pos/bug3175.scala
@@ -0,0 +1,7 @@
+object Test {
+  def f(g:{val update:Unit}) = g.update 
+  
+  def main(args: Array[String]): Unit = {
+    
+  }
+}
diff --git a/test/files/pos/bug318.scala b/test/files/pos/bug318.scala
index 590961c..dbe0e05 100644
--- a/test/files/pos/bug318.scala
+++ b/test/files/pos/bug318.scala
@@ -1,5 +1,3 @@
-// $Id: bug318.scala 5359 2005-12-16 15:33:49Z dubochet $
-
 object Test {
   def fun: Int = {
     object o {
diff --git a/test/files/pos/bug3252.flags b/test/files/pos/bug3252.flags
new file mode 100644
index 0000000..eb4d19b
--- /dev/null
+++ b/test/files/pos/bug3252.flags
@@ -0,0 +1 @@
+-optimise
\ No newline at end of file
diff --git a/test/files/pos/bug3252.scala b/test/files/pos/bug3252.scala
new file mode 100644
index 0000000..4b8e862
--- /dev/null
+++ b/test/files/pos/bug3252.scala
@@ -0,0 +1,15 @@
+class A {
+    def f(x : Boolean) : Thread = {
+        g {
+            x match {
+                case false =>
+                    B.h { }
+            }
+        }
+    }
+
+    private def g[T](block : => T) = error("")
+}
+object B {
+    def h(block : => Unit) : Nothing = error("")
+}
\ No newline at end of file
diff --git a/test/files/pos/bug3278.scala b/test/files/pos/bug3278.scala
new file mode 100644
index 0000000..788ec75
--- /dev/null
+++ b/test/files/pos/bug3278.scala
@@ -0,0 +1,15 @@
+class Foo
+class Test {
+	def update[B](x : B, b : Int) {}
+	def apply[B](x : B) = 1
+}
+
+object Test {
+	def main(a : Array[String]) {
+		val a = new Test
+		val f = new Foo
+		a(f) = 1 //works
+		a(f) = a(f) + 1 //works
+		a(f) += 1 //error: reassignment to val
+	}
+}
\ No newline at end of file
diff --git a/test/files/pos/bug3411.scala b/test/files/pos/bug3411.scala
new file mode 100644
index 0000000..b76fec6
--- /dev/null
+++ b/test/files/pos/bug3411.scala
@@ -0,0 +1,8 @@
+object A  {
+  def g(c: PartialFunction[Any,Unit]) {}
+  
+  def f {
+    lazy val x = 0
+    g { case `x` => }
+  }
+}
diff --git a/test/files/pos/bug3420.flags b/test/files/pos/bug3420.flags
new file mode 100644
index 0000000..ea03113
--- /dev/null
+++ b/test/files/pos/bug3420.flags
@@ -0,0 +1 @@
+-optimise -Xfatal-warnings
\ No newline at end of file
diff --git a/test/files/pos/bug3420.scala b/test/files/pos/bug3420.scala
new file mode 100644
index 0000000..0fc56ed
--- /dev/null
+++ b/test/files/pos/bug3420.scala
@@ -0,0 +1,5 @@
+class C {
+    val cv = Map[Int, Int](1 -> 2)
+    lazy val cl = Map[Int, Int](1 -> 2)
+    def cd = Map[Int, Int](1 -> 2)
+}
diff --git a/test/files/pos/bug3430.flags b/test/files/pos/bug3430.flags
new file mode 100644
index 0000000..eb4d19b
--- /dev/null
+++ b/test/files/pos/bug3430.flags
@@ -0,0 +1 @@
+-optimise
\ No newline at end of file
diff --git a/test/files/pos/bug3430.scala b/test/files/pos/bug3430.scala
new file mode 100644
index 0000000..4990abb
--- /dev/null
+++ b/test/files/pos/bug3430.scala
@@ -0,0 +1,13 @@
+// package com.example
+
+object A {    
+  def f1(f: String => Boolean) = f("a")
+
+  def f2(): Boolean =
+    f1 { s1 =>
+      f1 { s2 =>
+        while (true) { }
+        true
+      }
+    }
+}
\ No newline at end of file
diff --git a/test/files/pos/bug3480.scala b/test/files/pos/bug3480.scala
new file mode 100644
index 0000000..8303651
--- /dev/null
+++ b/test/files/pos/bug3480.scala
@@ -0,0 +1,4 @@
+object Test {
+  val List(_*) = List(1)
+	val Array( who, what @ _* ) = "Eclipse plugin cannot not handle this" split (" ")
+}
diff --git a/test/files/pos/bug3495.flags b/test/files/pos/bug3495.flags
new file mode 100644
index 0000000..08de722
--- /dev/null
+++ b/test/files/pos/bug3495.flags
@@ -0,0 +1 @@
+-Dsoot.class.path=bin:.
diff --git a/test/files/pos/bug3495.scala b/test/files/pos/bug3495.scala
new file mode 100644
index 0000000..8d5dff4
--- /dev/null
+++ b/test/files/pos/bug3495.scala
@@ -0,0 +1,2 @@
+class Foo { }
+
diff --git a/test/files/pos/bug3521/DoubleValue.java b/test/files/pos/bug3521/DoubleValue.java
new file mode 100644
index 0000000..28f05cd
--- /dev/null
+++ b/test/files/pos/bug3521/DoubleValue.java
@@ -0,0 +1,7 @@
+import java.lang.annotation.*;
+
+ at Retention(RetentionPolicy.RUNTIME)
+ at Target(ElementType.FIELD)
+public @interface DoubleValue {
+  double value();
+} 
\ No newline at end of file
diff --git a/test/files/pos/bug3521/a.scala b/test/files/pos/bug3521/a.scala
new file mode 100644
index 0000000..94bb451
--- /dev/null
+++ b/test/files/pos/bug3521/a.scala
@@ -0,0 +1,4 @@
+class Test {
+  @DoubleValue(-0.05)
+  var a = 0
+}
\ No newline at end of file
diff --git a/test/files/pos/bug3568.scala b/test/files/pos/bug3568.scala
new file mode 100644
index 0000000..950c165
--- /dev/null
+++ b/test/files/pos/bug3568.scala
@@ -0,0 +1,46 @@
+import scala.annotation._
+import scala.annotation.unchecked._
+import scala.collection._
+
+
+package object buffer {
+  val broken = new ArrayVec2() // commenting out this line causes the file to compile.
+
+  val works = Class.forName("buffer.ArrayVec2").newInstance().asInstanceOf[ArrayVec2]
+}
+
+package buffer {
+  object Main {
+    // ArrayVec2 can be compiled, instantiated and used.
+    def main(args: Array[String]) { println(works) }
+  }
+  
+  trait ElemType { type Element; type Component <: ElemType }
+  trait Float1 extends ElemType { type Element = Float; type Component = Float1}
+  class Vec2 extends ElemType { type Element = Vec2;  type Component = Float1 }
+
+  abstract class BaseSeq[T <: ElemType, E]
+  extends IndexedSeq[E] with IndexedSeqOptimized[E, IndexedSeq[E]] {
+    def length = 1
+    def apply(i: Int) :E
+  }
+
+  abstract class GenericSeq[T <: ElemType] extends BaseSeq[T, T#Element]
+  trait DataArray[T <: ElemType] extends BaseSeq[T, T#Element]
+  trait DataView[T <: ElemType] extends BaseSeq[T, T#Element]
+  abstract class BaseFloat1 extends BaseSeq[Float1, Float]
+
+  class ArrayFloat1 extends BaseFloat1 with DataArray[Float1] {
+    def apply(i: Int) :Float = 0f
+  }
+
+  class ViewFloat1 extends BaseFloat1 with DataView[Float1] {
+    def apply(i: Int) :Float = 0f
+  }
+
+  class ArrayVec2(val backingSeq: ArrayFloat1)
+  extends GenericSeq[Vec2] with DataArray[Vec2] {
+    def this() = this(new ArrayFloat1)
+    def apply(i: Int) :Vec2 = null
+  }
+}
\ No newline at end of file
diff --git a/test/files/pos/bug3570.scala b/test/files/pos/bug3570.scala
new file mode 100644
index 0000000..8921f83
--- /dev/null
+++ b/test/files/pos/bug3570.scala
@@ -0,0 +1,7 @@
+class test {
+	object Break extends Throwable
+	def break = throw Break
+	def block(x: => Unit) {
+		try { x } catch { case e: Break.type => }
+	}
+}
diff --git a/test/files/pos/bug3578.scala b/test/files/pos/bug3578.scala
new file mode 100644
index 0000000..306cde8
--- /dev/null
+++ b/test/files/pos/bug3578.scala
@@ -0,0 +1,30 @@
+object Test {
+  sealed abstract class JValue {
+    def ++(other: JValue) = {
+      def append(value1: JValue, value2: JValue): JValue = (value1, value2) match {
+	case (JNothing, x) => x
+	case (x, JNothing) => x
+	case (JObject(xs), x: JField) => JObject(xs ::: List(x))
+	case (x: JField, JObject(xs)) => JObject(x :: xs)
+	case (JArray(xs), JArray(ys)) => JArray(xs ::: ys)
+	case (JArray(xs), v: JValue) => JArray(xs ::: List(v))
+	case (v: JValue, JArray(xs)) => JArray(v :: xs)
+	case (f1: JField, f2: JField) => JObject(f1 :: f2 :: Nil)
+	case (JField(n, v1), v2: JValue) => JField(n, append(v1, v2))
+	case (x, y) => JArray(x :: y :: Nil)
+      }
+      append(this, other)
+    }
+  }
+
+  case object JNothing extends JValue
+  case object JNull extends JValue
+  case class JString(s: String) extends JValue
+  case class JDouble(num: Double) extends JValue
+  case class JInt(num: BigInt) extends JValue
+  case class JBool(value: Boolean) extends JValue
+  case class JField(name: String, value: JValue) extends JValue
+  case class JObject(obj: List[JField]) extends JValue 
+  case class JArray(arr: List[JValue]) extends JValue
+}
+
diff --git a/test/files/pos/bug359.scala b/test/files/pos/bug359.scala
index ccd1fa2..11233c3 100644
--- a/test/files/pos/bug359.scala
+++ b/test/files/pos/bug359.scala
@@ -1,5 +1,3 @@
-// $Id: bug359.scala 5359 2005-12-16 15:33:49Z dubochet $
-
 object Bug359 {
   class C;
   def f1(xs: List[C]): C = {
diff --git a/test/files/pos/bug360.scala b/test/files/pos/bug360.scala
index 9450ef5..f3716d4 100644
--- a/test/files/pos/bug360.scala
+++ b/test/files/pos/bug360.scala
@@ -1,5 +1,3 @@
-// $Id: bug360.scala 11911 2007-06-05 15:57:59Z odersky $
-
 abstract class Bug360A { self: Bug360C =>
   def f: String = "hello";
 }
diff --git a/test/files/pos/bug361.scala b/test/files/pos/bug361.scala
index ddc5cf5..1d19ecb 100644
--- a/test/files/pos/bug361.scala
+++ b/test/files/pos/bug361.scala
@@ -1,5 +1,3 @@
-// $Id: bug361.scala 15311 2008-06-10 08:46:06Z michelou $
-
 class Bug361Global extends Bug361Trees
 
 abstract class Bug361Trees { self: Bug361Global =>
diff --git a/test/files/pos/bug372.scala b/test/files/pos/bug372.scala
index 88f375f..9ce5b9a 100644
--- a/test/files/pos/bug372.scala
+++ b/test/files/pos/bug372.scala
@@ -1,4 +1,2 @@
-// $Id: bug372.scala 11911 2007-06-05 15:57:59Z odersky $
-
 class Bug372Names;
 class Bug372Symbols { self: Bug372Symbols with Bug372Names => }
diff --git a/test/files/pos/bug430-feb09.scala b/test/files/pos/bug430-feb09.scala
new file mode 100644
index 0000000..bba8996
--- /dev/null
+++ b/test/files/pos/bug430-feb09.scala
@@ -0,0 +1,34 @@
+// Compiles
+package a {
+  case class A[T]()
+}
+
+// Compiles
+package b.scala {
+  class B[T]
+}
+
+// Doesn't compile: type Nothing is not a member of c.scala
+package c.scala {
+  case class C[T]()
+}
+
+// Doesn't compile: type Nothing is not a member of d.scala 
+package d.scala.d {
+  case class D[T]()
+}
+
+// Doesn't compile: type Any is not a member of e.scala 
+package e.scala {
+  case class E[T >: Nothing]()
+}
+
+// Compiles
+package f.scala {
+  case class F[T >: Nothing <: Any]()
+}
+
+// Doesn't compile: type <byname> is not a member of package h.scala
+package h.scala {
+  case class H(s: String)(t: =>String)
+}
diff --git a/test/files/pos/bug432.scala b/test/files/pos/bug432.scala
index 8e3097a..087fd70 100644
--- a/test/files/pos/bug432.scala
+++ b/test/files/pos/bug432.scala
@@ -1,2 +1,2 @@
-case class Tata
+case class Tata()
 object Tata
diff --git a/test/files/pos/bug460.scala b/test/files/pos/bug460.scala
new file mode 100644
index 0000000..466d06c
--- /dev/null
+++ b/test/files/pos/bug460.scala
@@ -0,0 +1,9 @@
+object Bug460 {
+  def testFun(x : Int, y : Int) = x + y
+  val fn = testFun _ 
+  
+  fn(1, 2) // Ok 
+  (testFun(_, _))(1, 2) // Ok
+  (testFun _).apply(1, 2)
+  (testFun _)(1, 2) // Error! (but no longer)
+}
diff --git a/test/files/pos/bug516.scala b/test/files/pos/bug516.scala
index 623684e..735b259 100644
--- a/test/files/pos/bug516.scala
+++ b/test/files/pos/bug516.scala
@@ -1,12 +1,13 @@
 import scala.collection.mutable._;
+import scala.collection.script._;
 
 class Members;
 
 object subscriber extends Subscriber[Message[String] with Undoable, Members] {
  def notify(pub: Members, event: Message[String] with Undoable): Unit = 
   (event: Message[String]) match {
-   case Include(elem) => Console.println("ADD: " + elem);
-   case  Remove(elem) => Console.println("REM: " + elem);
+   case Include(l, elem) => Console.println("ADD: " + elem);
+   case  Remove(l, elem) => Console.println("REM: " + elem);
    //case i : Include[HasTree] with Undoable  =>
    //case r : Remove [HasTree] with Undoable  =>
   }
diff --git a/test/files/pos/bug703.scala b/test/files/pos/bug703.scala
index 06686c6..b24d70c 100644
--- a/test/files/pos/bug703.scala
+++ b/test/files/pos/bug703.scala
@@ -19,7 +19,7 @@ object Go {
       super.f;
     }
   }
-  class Super {
+  class Super extends A {
     def f: Unit = Console.println("A")
   }
   def main(args : Array[String]) : Unit = {
diff --git a/test/files/pos/bug715.cmds b/test/files/pos/bug715.cmds
new file mode 100644
index 0000000..2836967
--- /dev/null
+++ b/test/files/pos/bug715.cmds
@@ -0,0 +1,2 @@
+scalac meredith_1.scala
+scalac runner_2.scala
diff --git a/test/files/pos/bug715/meredith_1.scala b/test/files/pos/bug715/meredith_1.scala
new file mode 100644
index 0000000..3ed2e57
--- /dev/null
+++ b/test/files/pos/bug715/meredith_1.scala
@@ -0,0 +1,98 @@
+package com.sap.dspace.model.othello;
+
+import scala.xml._
+
+trait XMLRenderer {
+  type T <: {def getClass() : java.lang.Class[_]}
+  val valueTypes =
+    List(
+      classOf[java.lang.Boolean],
+      classOf[java.lang.Integer],
+      classOf[java.lang.Float],
+      classOf[java.lang.String] 
+      // more to come
+      )
+
+  def value2XML(
+    value : Object,
+    field : java.lang.reflect.Field,
+    pojo : T
+    ) : Node = {
+      value match {
+	case null => Text( "null" )
+	case vUnmatched =>
+	  if (value.isInstanceOf[java.lang.Boolean]) 
+	    Text( value.asInstanceOf[java.lang.Boolean].toString )
+	  else if (value.isInstanceOf[java.lang.Integer]) 
+	    Text( value.asInstanceOf[java.lang.Integer].toString )
+	  else if (value.isInstanceOf[java.lang.Float]) 
+	    Text( value.asInstanceOf[java.lang.Float].toString )
+    // else if (value.isInstanceOf[T]) 
+    //   pojo2XML( value.asInstanceOf[T] ) 
+	  else
+	  <unmatchedType>
+	    <theType>
+	      {vUnmatched.getClass.toString}
+	    </theType>
+	    <theValue>
+	      {vUnmatched.toString}
+	    </theValue>
+	  </unmatchedType>
+      }
+    }
+
+  def field2XML(
+    field : java.lang.reflect.Field,
+    pojo : T
+  ) : Elem = {
+
+    val accessible = field.isAccessible;
+    field.setAccessible( true );
+    // BUGBUG lgm need to disambiguate on type and possibly make
+    // recursive call to pojo2XML
+    val fldValXML = value2XML( field.get( pojo ), field, pojo );
+    field.setAccessible( accessible );
+
+    Elem(
+      null,
+      field.getName,
+      null,
+      TopScope, 
+      fldValXML
+      )
+  }
+
+  def pojo2XML( pojo : T ) : Elem = {
+    val progeny =
+      for (field <- pojo.getClass.getDeclaredFields)
+      yield field2XML( field, pojo );
+
+    Elem(
+      null,
+      pojo.getClass.getName,
+      null,
+      TopScope,
+      progeny.asInstanceOf[Array[scala.xml.Node]] : _*
+      )    
+  }
+}
+
+case class POJO2XMLRenderer( recurse : Boolean )
+     extends XMLRenderer {
+       type T = java.io.Serializable
+  override def value2XML(
+    value : Object,
+    field : java.lang.reflect.Field,
+    pojo : java.io.Serializable
+    ) : Node = {
+      if (recurse) super.value2XML( value, field, pojo )
+      else Text( value + "" )
+    }
+}
+
+object thePOJO2XMLRenderer extends POJO2XMLRenderer( true ) {
+}
+
+object Test extends Application {
+  println(com.sap.dspace.model.othello.thePOJO2XMLRenderer)
+}
diff --git a/test/files/pos/bug715/runner_2.scala b/test/files/pos/bug715/runner_2.scala
new file mode 100644
index 0000000..1e4f40d
--- /dev/null
+++ b/test/files/pos/bug715/runner_2.scala
@@ -0,0 +1,3 @@
+object Test extends Application {
+  println(com.sap.dspace.model.othello.thePOJO2XMLRenderer)
+}
diff --git a/test/files/pos/bug756.scala b/test/files/pos/bug756.scala
new file mode 100644
index 0000000..a3c790c
--- /dev/null
+++ b/test/files/pos/bug756.scala
@@ -0,0 +1,6 @@
+object test {
+  for {
+    n <- Some(42)
+    _ <- Some(24)
+  } yield n
+}
diff --git a/test/files/pos/bug927.scala b/test/files/pos/bug927.scala
index 8b2fe72..8f3cdac 100644
--- a/test/files/pos/bug927.scala
+++ b/test/files/pos/bug927.scala
@@ -2,10 +2,10 @@ object Test {
 
   def sum(stream: Stream[Int]): Int =
     stream match {
-      case Stream.empty => 0
+      case Stream.Empty => 0
       case Stream.cons(hd, tl) => hd + sum(tl)
     }
-  val str: Stream[Int] = Stream.fromIterator(List(1,2,3).elements)
+  val str: Stream[Int] = Stream.fromIterator(List(1,2,3).iterator)
   assert(sum(str) == 6)
   
 }
diff --git a/test/files/pos/builders.scala b/test/files/pos/builders.scala
new file mode 100644
index 0000000..51d8af8
--- /dev/null
+++ b/test/files/pos/builders.scala
@@ -0,0 +1,66 @@
+object builders {
+
+  trait Builder[-From, +To, -Elem] {
+    def += (elem: Elem)
+    def result: To
+  }
+
+  implicit def iterableBuilder[A, B] = new Builder[Iterable[A], Iterable[B], B] {
+    println("new iterable builder")
+    private val buf = new scala.collection.mutable.ListBuffer[B]
+    def += (elem: B) { buf += elem }
+    def result: Iterable[B] = buf.toList
+  }
+
+  implicit def listBuilder[A, B] = new Builder[List[A], List[B], B] {
+    println("new list builder")
+    private val buf = new scala.collection.mutable.ListBuffer[B]
+    def += (elem: B) { buf += elem }
+    def result: List[B] = buf.toList
+  }
+/*  
+  def fill[A, Dim1, Dim2, Coll](n1: Int, n2: Int, elem: A)(implicit b1: Builder[Coll, Dim1, A], b2: Builder[Coll, Dim2, Dim1]) = {
+    for (i <- 0 until n1) {
+      for (j <- 0 until n2) {
+        b1 += elem
+      }	
+      b2 += b1.result
+    }
+    b2.result
+  }	
+*/
+/*
+  implicit def arrayBuilder[A, B] = new Builder[Array[A], Array[B], B] {
+    println("new arr ay builder")
+    private val buf = new scala.collection.mutable.ListBuffer[B]
+    def += (elem: B) { buf += elem }
+    def result: Array[B] = buf.toArray
+  }	
+*/
+  class Iter[A, C](elems: List[A]) {
+    def ++ [B  >: A, D](xs: Iterable[B])(implicit b: Builder[C, D, B]): D = {
+      for (x <- elems) b += x
+      for (x <- xs) b += x
+      b.result
+    }
+    def map[B, D](f: A => B)(implicit b: Builder[C, D, B]): D = {
+      for (x <- elems) b += f(x)
+      b.result
+    }
+  }
+  
+  def main(args : Array[String]) : Unit = {
+    val x1 = new Iter[Int, List[Int]](List(1, 2, 3))
+//    val x2 = new Iter[Int, Array[Int]](List(1, 2, 3))
+    val x3 = new Iter[Int, Iterable[Int]](List(1, 2, 3))
+    val y1: List[Int] = x1.map (_ + 1)
+//    val y2: Array[Int] = x2.map (_ + 1)
+    val y3: Iterable[Int] = x3.map (_ + 1)
+    val z1: List[Int] = y1
+//    val z2: Array[Int] = y2
+    val z3: Iterable[Int] = y3
+    println(z1)
+//    println(z2)
+    println(z3)
+  }
+}
diff --git a/test/files/pos/caseClassInMethod.scala b/test/files/pos/caseClassInMethod.scala
new file mode 100644
index 0000000..958e5dd
--- /dev/null
+++ b/test/files/pos/caseClassInMethod.scala
@@ -0,0 +1,5 @@
+object t {
+  def f = { object C; case class C(); 1 }
+  // pending: def g = { case class D(x: Int); object D; 2 }
+  def h = { case class E(y: Int = 10); 3 }
+}
diff --git a/test/files/pos5/chang/Outer.java b/test/files/pos/chang/Outer.java
similarity index 100%
rename from test/files/pos5/chang/Outer.java
rename to test/files/pos/chang/Outer.java
diff --git a/test/files/pos5/chang/Test.scala b/test/files/pos/chang/Test.scala
similarity index 100%
rename from test/files/pos5/chang/Test.scala
rename to test/files/pos/chang/Test.scala
diff --git a/test/files/pos/cls.scala b/test/files/pos/cls.scala
index 54104ae..1366199 100644
--- a/test/files/pos/cls.scala
+++ b/test/files/pos/cls.scala
@@ -14,4 +14,4 @@ object test {
   val a1 = new A(1, "hello");
   val b1 = new B(1, "hello");
 }
-}
\ No newline at end of file
+}
diff --git a/test/files/pos/clsrefine.scala b/test/files/pos/clsrefine.scala
index d54a0c3..b29c01d 100644
--- a/test/files/pos/clsrefine.scala
+++ b/test/files/pos/clsrefine.scala
@@ -37,4 +37,4 @@ object test {
     val y2 = "hello";
   }
 }
-}
\ No newline at end of file
+}
diff --git a/test/files/pos/collectGenericCC.scala b/test/files/pos/collectGenericCC.scala
new file mode 100644
index 0000000..7504752
--- /dev/null
+++ b/test/files/pos/collectGenericCC.scala
@@ -0,0 +1,14 @@
+import scala.collection.generic._
+import scala.collection._
+
+object Test {
+  def collect[A, Res](r: Traversable[A])(implicit bf: CanBuild[A, Res]) = {
+    val b = bf()
+    for (a <- r) b += a
+    b.result
+  }
+  
+  collect[Int, Vector[Int]](List(1,2,3,4)) 
+  collect[Char, String](List('1','2','3','4'))
+  collect[Char, Array[Char]](List('1','2','3','4'))  
+}
\ No newline at end of file
diff --git a/test/files/pos/collections.scala b/test/files/pos/collections.scala
index 4f45a42..23b23d0 100644
--- a/test/files/pos/collections.scala
+++ b/test/files/pos/collections.scala
@@ -2,9 +2,9 @@ package mixins;
 
 import scala.collection.mutable._;
 
-class Collections extends HashSet[Int] with ObservableSet[Int,Collections] {
-  override def +=(elem: Int): Unit = super.+=(elem);
-  override def -=(elem: Int): Unit = super.-=(elem);
+class Collections extends HashSet[Int] with ObservableSet[Int] {
+  override def +=(elem: Int): this.type = super.+=(elem);
+  override def -=(elem: Int): this.type = super.-=(elem);
   override def clear: Unit = super.clear;
 
 }
diff --git a/test/files/pos/compile.scala b/test/files/pos/compile.scala
index 0bedb89..bb2526e 100644
--- a/test/files/pos/compile.scala
+++ b/test/files/pos/compile.scala
@@ -1,7 +1,6 @@
 //############################################################################
 // Compile Time Bugs & Test Cases
 //############################################################################
-// $Id: compile.scala 5359 2005-12-16 15:33:49Z dubochet $
 
 import java.lang.System; // to avoid name clash with .NET's library
 
diff --git a/test/files/pos/compile1.scala b/test/files/pos/compile1.scala
index 74b6bda..6886d39 100644
--- a/test/files/pos/compile1.scala
+++ b/test/files/pos/compile1.scala
@@ -1,7 +1,6 @@
 //############################################################################
 // Compile Time Bugs & Test Cases
 //############################################################################
-// $Id: compile1.scala 5359 2005-12-16 15:33:49Z dubochet $
 
 import java.lang.System; // to avoid name clash with .NET's library
 
diff --git a/test/files/pos/context.scala b/test/files/pos/context.scala
new file mode 100644
index 0000000..13f6bb4
--- /dev/null
+++ b/test/files/pos/context.scala
@@ -0,0 +1,38 @@
+class Context {
+  object symwrap extends SymbolWrapper {
+    val context: Context.this.type = Context.this
+  }
+  object typewrap extends TypeWrapper {
+    val context: Context.this.type = Context.this
+  }
+  object symbols extends symwrap.Symbols;
+  object types extends typewrap.Types;
+}
+
+abstract class SymbolWrapper {
+  val context: Context;
+  import context._;
+  
+  class Symbols {
+    self: context.symbols.type =>
+    
+    abstract class Symbol {
+      def typ: types.Type;
+      def sym: Symbol = typ.sym;
+    }
+  }
+}
+
+abstract class TypeWrapper {
+  val context: Context;
+  import context._;
+
+  class Types {
+    self: context.types.type =>
+    
+    abstract class Type {
+      def sym: symbols.Symbol;
+      def typ: Type = sym.typ;
+    }
+  }
+}
diff --git a/test/files/pos/context.scala.disabled b/test/files/pos/context.scala.disabled
deleted file mode 100644
index 575df9a..0000000
--- a/test/files/pos/context.scala.disabled
+++ /dev/null
@@ -1,34 +0,0 @@
-class Context {
-  object symwrap extends SymbolWrapper {
-    val context: Context.this.type = Context.this
-  }
-  object typewrap extends TypeWrapper {
-    val context: Context.this.type = Context.this
-  }
-  object symbols extends symwrap.Symbols;
-  object types extends typewrap.Types;
-}
-
-abstract class SymbolWrapper {
-  val context: Context;
-  import context._;
-  
-  class Symbols requires context.symbols.type {
-    abstract class Symbol {
-      def typ: types.Type;
-      def sym: Symbol = typ.sym;
-    }
-  }
-}
-
-abstract class TypeWrapper {
-  val context: Context;
-  import context._;
-
-  class Types requires context.types.type {
-    abstract class Type {
-      def sym: symbols.Symbol;
-      def typ: Type = sym.typ;
-    }
-  }
-}
diff --git a/test/files/pos/cyclics.scala b/test/files/pos/cyclics.scala
new file mode 100644
index 0000000..051bdd6
--- /dev/null
+++ b/test/files/pos/cyclics.scala
@@ -0,0 +1,26 @@
+trait Param[T]
+trait Abs { type T }
+trait Cyclic1[A <: Param[A]]    // works
+trait Cyclic2[A <: Abs { type T <: A }]   
+trait Cyclic3 { type A <: Abs { type T = A } }    
+trait Cyclic4 { type A <: Param[A] }   // works
+trait Cyclic5 { type AA <: Abs; type A <: AA { type T = A } }    
+
+
+trait IterableTemplate {
+  type Elem
+  type Constr <: IterableTemplate
+  type ConstrOf[A] = Constr { type Elem = A }
+  
+  def iterator: Iterator[Elem]
+  
+  def map [B] (f: Elem => B): ConstrOf[B]
+  
+  def foreach(f: Elem => Unit) = iterator.foreach(f)
+}
+
+
+trait Iterable[A] extends IterableTemplate { self =>
+  type Elem 
+  type Constr <: Iterable[A] { type Constr <: Iterable.this.Constr }
+}
diff --git a/test/files/pos/depexists.scala b/test/files/pos/depexists.scala
new file mode 100644
index 0000000..d539c84
--- /dev/null
+++ b/test/files/pos/depexists.scala
@@ -0,0 +1,5 @@
+object depexists {
+
+  val c: Cell[(a, b)] forSome { type a <: Number; type b <: (a, a) } = null
+  val d = c
+}
diff --git a/test/files/pos/depmet_1.flags b/test/files/pos/depmet_1.flags
new file mode 100644
index 0000000..1c26b24
--- /dev/null
+++ b/test/files/pos/depmet_1.flags
@@ -0,0 +1 @@
+-Ydependent-method-types
\ No newline at end of file
diff --git a/test/files/pos/depmet_1.scala b/test/files/pos/depmet_1.scala
new file mode 100644
index 0000000..166e991
--- /dev/null
+++ b/test/files/pos/depmet_1.scala
@@ -0,0 +1,6 @@
+object Test {
+  def precise(x: String)(y: x.type): x.type = y
+  val foo = "foo"
+  val fun : foo.type => foo.type = precise(foo)
+  val bar : foo.type = precise(foo)(foo)
+}
\ No newline at end of file
diff --git a/test/files/pos/depmet_implicit_chaining_zw.flags b/test/files/pos/depmet_implicit_chaining_zw.flags
new file mode 100644
index 0000000..1c26b24
--- /dev/null
+++ b/test/files/pos/depmet_implicit_chaining_zw.flags
@@ -0,0 +1 @@
+-Ydependent-method-types
\ No newline at end of file
diff --git a/test/files/pos/depmet_implicit_chaining_zw.scala b/test/files/pos/depmet_implicit_chaining_zw.scala
new file mode 100644
index 0000000..93da3b0
--- /dev/null
+++ b/test/files/pos/depmet_implicit_chaining_zw.scala
@@ -0,0 +1,28 @@
+trait Zero
+trait Succ[N]
+
+trait ZipWith[N, S] {
+  type T
+  val x: T = error("")
+}
+
+object ZipWith {
+  implicit def ZeroZipWith[S] = new ZipWith[Zero, S] {
+    type T = Stream[S]
+  }
+
+  implicit def SuccZipWith[N, S, R](implicit zWith : ZipWith[N, R]) = new ZipWith[Succ[N], S => R] {
+    type T = Stream[S] => zWith.T // dependent types replace the associated types functionality
+  }
+
+  // can't use implicitly[ZipWith[Succ[Succ[Zero]], Int => String => Boolean]], 
+  // since that will chop of the {type T = ... } refinement in adapt (pt = ZipWith[Succ[Succ[Zero]], Int => String => Boolean])
+  // this works
+  // def zipWith(implicit zw: ZipWith[Succ[Succ[Zero]], Int => String => Boolean]): zw.T = zw.x
+  // thus, I present ?: implicitly on steroids!
+  def ?[T <: AnyRef](implicit w: T): w.type = w
+
+  type _2 = Succ[Succ[Zero]]
+  val zw = ?[ZipWith[_2, Int => String => Boolean]].x // : Stream[Int] => Stream[String] => Stream[Boolean]
+  // val zw = implicitly[ZipWith[Succ[Succ[Zero]], Int => String => Boolean]{type T = Stream[Int] => Stream[String] => Stream[Boolean]}].x
+}
\ No newline at end of file
diff --git a/test/files/pos/depmet_implicit_norm_ret.flags b/test/files/pos/depmet_implicit_norm_ret.flags
new file mode 100644
index 0000000..1c26b24
--- /dev/null
+++ b/test/files/pos/depmet_implicit_norm_ret.flags
@@ -0,0 +1 @@
+-Ydependent-method-types
\ No newline at end of file
diff --git a/test/files/pos/depmet_implicit_norm_ret.scala b/test/files/pos/depmet_implicit_norm_ret.scala
new file mode 100644
index 0000000..bafd2f7
--- /dev/null
+++ b/test/files/pos/depmet_implicit_norm_ret.scala
@@ -0,0 +1,29 @@
+object Test{
+  def ?[S <: AnyRef](implicit w : S) : w.type = w
+  
+  // fallback, lower priority (overloading rules apply: pick alternative in subclass lowest in subtyping lattice)
+  class ZipWithDefault {
+    implicit def ZeroZipWith[S] = new ZipWith[S] {
+      type T = Stream[S]
+    }    
+  }
+  
+  object ZipWith extends ZipWithDefault {
+    // def apply[S: ZipWith](s : S) = ?[ZipWith[S]].zipWith(s) // TODO: bug return type should be inferred
+    def apply[S](s : S)(implicit zw: ZipWith[S]): zw.T = zw.zipWith(s)
+
+    implicit def SuccZipWith[S,R](implicit zWith : ZipWith[R]) = new ZipWith[S => R] {
+      type T = Stream[S] => zWith.T // dependent types replace the associated types functionality
+    }    
+  }
+  
+  trait ZipWith[S] {
+    type T
+    def zipWith : S => T = error("")
+  }
+  
+  // bug: inferred return type = (Stream[A]) => java.lang.Object with Test.ZipWith[B]{type T = Stream[B]}#T
+  // this seems incompatible with vvvvvvvvvvvvvvvvvvvvvv   -- #3731
+  def map[A,B](f : A => B)   /* : Stream[A] => Stream[B]*/ = ZipWith(f) 
+  val tst: Stream[Int] = map{x: String => x.length}(Stream("a"))  
+}  
\ No newline at end of file
diff --git a/test/files/pos/depmet_implicit_oopsla_session.flags b/test/files/pos/depmet_implicit_oopsla_session.flags
new file mode 100644
index 0000000..1c26b24
--- /dev/null
+++ b/test/files/pos/depmet_implicit_oopsla_session.flags
@@ -0,0 +1 @@
+-Ydependent-method-types
\ No newline at end of file
diff --git a/test/files/pos/depmet_implicit_oopsla_session.scala b/test/files/pos/depmet_implicit_oopsla_session.scala
new file mode 100644
index 0000000..e2c67d7
--- /dev/null
+++ b/test/files/pos/depmet_implicit_oopsla_session.scala
@@ -0,0 +1,63 @@
+object Sessions {
+  trait Session[This] {
+    type Dual
+    type HasDual[D] = Session[This]{type Dual=D}
+    def run(p: This, dp: Dual): Unit
+  }
+
+  implicit object StopSession extends Session[Stop] {
+    type Dual = Stop
+
+    def run(p: Stop, dp: Stop): Unit = {}
+  }
+
+  implicit def InDual[A, B](implicit sessionDIn: Session[B]) = 
+    new Session[In[A, B]] {
+      type Dual = Out[A, sessionDIn.Dual]
+
+      def run(p: In[A, B], dp: Dual): Unit = 
+        sessionDIn.run(p.func(dp.x), dp.y)
+  }
+
+  implicit def OutDual[A, B](implicit sessionDOut: Session[B]) = 
+    new Session[Out[A, B]] {
+     type Dual = In[A, sessionDOut.Dual]
+
+     def run(p: Out[A, B], dp: Dual): Unit = 
+       sessionDOut.run(p.y, dp.func(p.x))
+  }
+
+  sealed case class Stop()
+  sealed case class In[-A, +B](func: A => B)
+  sealed case class Out[+A, +B](x: A, y: B)
+
+  def addServer =
+    In{x: Int => 
+    In{y: Int => System.out.println("Thinking")
+    Out(x+y,
+    Stop())}}
+
+  def addClient =
+    Out(3,
+    Out(4, { System.out.println("Waiting")
+    In{z: Int => System.out.println(z)
+    Stop()}}))
+
+  def runSession[S, D: Session[S]#HasDual](p: S, dp: D) =
+    implicitly[Session[S]#HasDual[D]].run(p, dp)
+
+  // def runSession[S, D](p: S, dp: D)(implicit s: Session[S]#HasDual[D]) =
+  //   s.run(p, dp)
+  // 
+  // def runSession[S, D](p: S, dp: D)(implicit s: Session[S]{type Dual=D}) =
+  //   s.run(p, dp)
+
+  // TODO: can we relax the ordering restrictions on dependencies so that we can use
+  // def runSession[S](p: S, dp: s.Dual)(implicit s: Session[S]) =
+  //   s.run(p, dp)
+  // to emphasise similarity of type parameters and implicit arguments:
+  // def runSession[S][val s: Session[S]](p: S, dp: s.Dual) =
+  //   s.run(p, dp)
+
+  def myRun = runSession(addServer, addClient)
+}
\ No newline at end of file
diff --git a/test/files/pos/depmet_implicit_oopsla_session_2.flags b/test/files/pos/depmet_implicit_oopsla_session_2.flags
new file mode 100644
index 0000000..1c26b24
--- /dev/null
+++ b/test/files/pos/depmet_implicit_oopsla_session_2.flags
@@ -0,0 +1 @@
+-Ydependent-method-types
\ No newline at end of file
diff --git a/test/files/pos/depmet_implicit_oopsla_session_2.scala b/test/files/pos/depmet_implicit_oopsla_session_2.scala
new file mode 100644
index 0000000..8d7daa6
--- /dev/null
+++ b/test/files/pos/depmet_implicit_oopsla_session_2.scala
@@ -0,0 +1,87 @@
+object Sessions {
+  def ?[T <: AnyRef](implicit w: T): w.type = w
+
+  // session states
+  sealed case class Stop()
+  sealed case class In[-Data, +Cont](recv: Data => Cont)
+  sealed case class Out[+Data, +Cont](data: Data, cont: Cont)
+
+  // the type theory of communicating sessions:
+
+  // an instance of type Session[S]{type Dual=D} is evidence that S and D are duals
+  // such a value witnesses this fact by describing how to compose an instance of S with an instance of D (through the run method)
+  trait Session[S] { type Self = S
+    type Dual
+    type HasDual[D] = Session[Self]{type Dual=D}
+    def run(self: Self, dual: Dual): Unit
+  }
+
+  // friendly interface to the theory
+  def runSession[S, D: Session[S]#HasDual](session: S, dual: D) =
+    ?[Session[S]#HasDual[D]].run(session, dual)
+
+  // facts in the theory:
+
+  // ------------------------[StopDual]
+  // Stop is the dual of Stop
+  implicit object StopDual extends Session[Stop] {
+    type Dual = Stop
+
+    def run(self: Self, dual: Dual): Unit = {}
+  }
+
+  //            CD is the dual of Cont
+  // -------------------------------------------[InDual]
+  // Out[Data, CD] is the dual of In[Data, Cont]
+  implicit def InDual[Data, Cont](implicit cont: Session[Cont]) = new Session[In[Data, Cont]] {
+    type Dual = Out[Data, cont.Dual]
+
+    def run(self: Self, dual: Dual): Unit = 
+      cont.run(self.recv(dual.data), dual.cont)
+  }
+
+  //            CD is the dual of Cont
+  // -------------------------------------------[OutDual]
+  // In[Data, CD] is the dual of Out[Data, Cont]
+  implicit def OutDual[Data, Cont](implicit cont: Session[Cont]) = new Session[Out[Data, Cont]] {
+    type Dual = In[Data, cont.Dual]
+
+    def run(self: Self, dual: Dual): Unit = 
+      cont.run(self.cont, dual.recv(self.data))
+  }
+
+  // a concrete session
+  def addServer =
+    In{x: Int => 
+    In{y: Int => System.out.println("Thinking")
+    Out(x+y,
+    Stop())}}
+
+  def addClient =
+    Out(3,
+    Out(4, { System.out.println("Waiting")
+    In{z: Int => System.out.println(z)
+    Stop()}}))
+
+  def myRun = runSession(addServer, addClient)
+}
+
+/* future improvements:
+
+
+  // def runSession[S, D](p: S, dp: D)(implicit s: Session[S]#HasDual[D]) =
+  //   s.run(p, dp)
+  // 
+  // def runSession[S, D](p: S, dp: D)(implicit s: Session[S]{type Dual=D}) =
+  //   s.run(p, dp)
+
+  // TODO: can we relax the ordering restrictions on dependencies so that we can write
+  //  one possibility: graph of dependencies between arguments must be acyclic
+  // def runSession[S](p: S, dp: s.Dual)(implicit s: Session[S]) =
+  //   s.run(p, dp)
+  // to emphasise similarity of type parameters and implicit arguments:
+  // def runSession[S][val s: Session[S]](p: S, dp: s.Dual) =
+  //   s.run(p, dp)
+
+
+*/
\ No newline at end of file
diff --git a/test/files/pos/depmet_implicit_oopsla_session_simpler.flags b/test/files/pos/depmet_implicit_oopsla_session_simpler.flags
new file mode 100644
index 0000000..1c26b24
--- /dev/null
+++ b/test/files/pos/depmet_implicit_oopsla_session_simpler.flags
@@ -0,0 +1 @@
+-Ydependent-method-types
\ No newline at end of file
diff --git a/test/files/pos/depmet_implicit_oopsla_session_simpler.scala b/test/files/pos/depmet_implicit_oopsla_session_simpler.scala
new file mode 100644
index 0000000..d2986ef
--- /dev/null
+++ b/test/files/pos/depmet_implicit_oopsla_session_simpler.scala
@@ -0,0 +1,44 @@
+object Sessions {
+  trait Session {
+    type Dual <: Session
+
+    def run(dp: Dual): Unit
+  }
+
+  sealed case class Stop extends Session {
+    type Dual = Stop
+
+    def run(dp: Dual): Unit = {}
+  }
+
+  // can't write B <: Session{type Dual = BDual} due to limitations in type inference algorithm
+  // (type variables cannot occur on both sides of <:)
+  // using B#Dual instead of BDual is too imprecise, since it is disconnected from the actual argument that is passed for B
+  // would be nice if we could introduce a universal quantification over BDual that is not part of the 
+  // type parameter list
+  sealed case class In[A, B <: Session, BDual <: Session](recv: A => B)(implicit dual: B <:< Session{type Dual=BDual}) extends Session {
+    type Dual = Out[A, BDual]
+
+    def run(dp: Dual): Unit = recv(dp.data) run dp.cont
+  }
+
+  sealed case class Out[A, B <: Session](data: A, cont: B) extends Session {
+     type Dual = In[A, cont.Dual, cont.Dual#Dual]
+
+     def run(dp: Dual): Unit = cont run dp.recv(data)
+  }
+
+  def addServer =
+    In{x: Int => 
+    In{y: Int => System.out.println("Thinking")
+    Out(x+y,
+    Stop())}}
+
+  def addClient =
+    Out(3,
+    Out(4, { System.out.println("Waiting")
+    In{z: Int => System.out.println(z)
+    Stop()}}))
+
+  def myRun = addServer run addClient
+}
diff --git a/test/files/pos/depmet_implicit_oopsla_zipwith.flags b/test/files/pos/depmet_implicit_oopsla_zipwith.flags
new file mode 100644
index 0000000..1c26b24
--- /dev/null
+++ b/test/files/pos/depmet_implicit_oopsla_zipwith.flags
@@ -0,0 +1 @@
+-Ydependent-method-types
\ No newline at end of file
diff --git a/test/files/pos/depmet_implicit_oopsla_zipwith.scala b/test/files/pos/depmet_implicit_oopsla_zipwith.scala
new file mode 100644
index 0000000..fe69802
--- /dev/null
+++ b/test/files/pos/depmet_implicit_oopsla_zipwith.scala
@@ -0,0 +1,44 @@
+case class Zero()
+case class Succ[N](x: N)
+import Stream.{cons, continually}
+
+trait ZipWith[N, S] {
+  type T
+
+  def manyApp: N => Stream[S] => T
+  def zipWith: N => S => T = n => f => manyApp(n)(continually(f))
+}
+object ZipWith {
+  implicit def ZeroZipWith[S] = new ZipWith[Zero, S] {
+    type T = Stream[S]
+
+    def manyApp = n => xs => xs
+  }
+
+  implicit def SuccZipWith[N, S, R](implicit zw: ZipWith[N, R]) = 
+    new ZipWith[Succ[N],S => R] {
+      type T = Stream[S] => zw.T
+
+      def zapp[A, B](xs: Stream[A => B], ys: Stream[A]): Stream[B] = (xs, ys) match {
+        case (cons(f, fs), cons(s, ss)) => cons(f(s),zapp(fs, ss))
+        case (_, _) => Stream.empty
+      }
+
+      def manyApp = n => xs => ss => n match {
+        case Succ(i) => zw.manyApp(i)(zapp(xs, ss))
+      }
+    }
+}
+
+object Test {
+  def zWith[N, S](n: N, s: S)(implicit zw: ZipWith[N, S]): zw.T = zw.zipWith(n)(s)
+
+  def zipWith0: Stream[Int] = zWith(Zero(),0) 
+
+// (Stream[A]) => java.lang.Object with ZipWith[Zero,B]{type T = Stream[B]}#T
+// should normalise to: Stream[A] => Stream[B]
+  def map[A, B](f: A => B) = zWith(Succ(Zero()),f)
+                               
+  def zipWith3[A, B, C, D](f: A => B => C => D) = //: Stream[A] => Stream[B] => Stream[C] => Stream[D] = // BUG why do we need a return type?
+    zWith(Succ(Succ(Succ(Zero()))),f)
+}
\ No newline at end of file
diff --git a/test/files/pos/depmet_implicit_tpbetareduce.flags b/test/files/pos/depmet_implicit_tpbetareduce.flags
new file mode 100644
index 0000000..1c26b24
--- /dev/null
+++ b/test/files/pos/depmet_implicit_tpbetareduce.flags
@@ -0,0 +1 @@
+-Ydependent-method-types
\ No newline at end of file
diff --git a/test/files/pos/depmet_implicit_tpbetareduce.scala b/test/files/pos/depmet_implicit_tpbetareduce.scala
new file mode 100644
index 0000000..c0b9b4e
--- /dev/null
+++ b/test/files/pos/depmet_implicit_tpbetareduce.scala
@@ -0,0 +1,12 @@
+trait HOSeq {
+  trait Accumulator[+coll[x], elT]
+  trait Iterable[+t] {
+    type m[+x] 
+    def accumulator[t]: Accumulator[m, t]
+  }
+  implicit def listAccumulator[elT]: Accumulator[List, elT] = new Accumulator[List, elT] {}  
+  trait List[+t] extends Iterable[t] {
+    type m[+x] = List[x]
+    def accumulator[t]: Accumulator[List, t] = listAccumulator[t]
+  }
+}
\ No newline at end of file
diff --git a/test/files/pos/eta.scala b/test/files/pos/eta.scala
index 68e927c..2dd2970 100644
--- a/test/files/pos/eta.scala
+++ b/test/files/pos/eta.scala
@@ -1,5 +1,3 @@
-// $Id: eta.scala 5552 2006-01-17 15:29:35Z michelou $
-
 object test {
 
 def sum(f: Int => Int)(x: Int, y: Int): Int = 0;
diff --git a/test/files/pos/exbound.scala b/test/files/pos/exbound.scala
new file mode 100644
index 0000000..243d583
--- /dev/null
+++ b/test/files/pos/exbound.scala
@@ -0,0 +1,7 @@
+class A[T <: A[T]] {
+
+}
+
+object Test {
+  val x: A[X] forSome { type X } = null
+}
diff --git a/test/files/pos/ilya/J.java b/test/files/pos/ilya/J.java
new file mode 100644
index 0000000..b469623
--- /dev/null
+++ b/test/files/pos/ilya/J.java
@@ -0,0 +1,14 @@
+package test;
+
+class Foo {
+}
+
+class Boo<T extends Foo>{}
+
+class Bar<BooT extends Boo<FooT>, FooT extends Foo>{
+ private final int myInt;
+
+ public Bar(int i) {
+   myInt = i;
+ }
+}
diff --git a/test/files/pos/ilya/S.scala b/test/files/pos/ilya/S.scala
new file mode 100644
index 0000000..952c004
--- /dev/null
+++ b/test/files/pos/ilya/S.scala
@@ -0,0 +1,5 @@
+package test
+
+class ScBar[BooT <: Boo[FooT], FooT <: Foo](i: Int) extends Bar[BooT, FooT](i) {
+
+}
diff --git a/test/files/pos5/ilya2/A.scala b/test/files/pos/ilya2/A.scala
similarity index 100%
rename from test/files/pos5/ilya2/A.scala
rename to test/files/pos/ilya2/A.scala
diff --git a/test/files/pos5/ilya2/B.java b/test/files/pos/ilya2/B.java
similarity index 100%
rename from test/files/pos5/ilya2/B.java
rename to test/files/pos/ilya2/B.java
diff --git a/test/files/pos5/ilya2/Nullable.java b/test/files/pos/ilya2/Nullable.java
similarity index 100%
rename from test/files/pos5/ilya2/Nullable.java
rename to test/files/pos/ilya2/Nullable.java
diff --git a/test/files/pos/implicits.scala b/test/files/pos/implicits.scala
new file mode 100644
index 0000000..2c01dd0
--- /dev/null
+++ b/test/files/pos/implicits.scala
@@ -0,0 +1,89 @@
+// #1435
+object t1435 {
+  implicit def a(s:String):String = error("")
+  implicit def a(i:Int):String = error("")
+  implicit def b(i:Int):String = error("")
+}
+
+class C1435 {
+  val v:String = {
+    import t1435.a
+    2
+  }
+}
+
+// #1492
+class C1492 {
+
+  class X
+
+  def foo(x: X => X) {}
+
+  foo ( implicit x => implicitly[X] )
+  foo { implicit x => implicitly[X] }
+}
+
+// #1579
+object Test1579 {
+  class Column
+  class Query[E](val value: E)
+  class Invoker(q: Any) { val foo = null }
+
+  implicit def unwrap[C](q: Query[C]) = q.value
+  implicit def invoker(q: Query[Column]) = new Invoker(q)
+
+  val q = new Query(new Column)
+  q.foo
+}
+// #1625
+object Test1625 {
+
+  class Wrapped(x:Any) {
+    def unwrap() = x
+  }
+
+  implicit def byName[A](x: =>A) = new Wrapped(x)
+
+  implicit def byVal[A](x: A) = x
+  
+  def main(args: Array[String]) = {
+
+//    val res:Wrapped = 7 // works
+
+    val res = 7.unwrap() // doesn't work
+
+    println("=> result: " + res)
+  }
+}
+
+object Test2188 {
+  implicit def toJavaList[A: ClassManifest](t:collection.Seq[A]):java.util.List[A] = java.util.Arrays.asList(t.toArray:_*)   
+
+  val x: java.util.List[String] = List("foo")
+}
+
+object TestNumericWidening {
+  val y = 1
+  val x: java.lang.Long = y
+}
+
+// #2709 
+package foo2709 { 
+  class A 
+  class B 
+ 
+  package object bar { 
+    implicit def a2b(a: A): B = new B 
+  } 
+ 
+  package bar { 
+    object test { 
+      new A: B 
+    } 
+  } 
+} 
+
+// Problem with specs
+object specsProblem {
+  println(implicitly[Manifest[Class[_]]])
+}
diff --git a/test/files/pos/imports.scala b/test/files/pos/imports.scala
index 5eae86c..5f70a5d 100644
--- a/test/files/pos/imports.scala
+++ b/test/files/pos/imports.scala
@@ -13,4 +13,4 @@ object test {
 object test1 {
   import test._;
   foo
-} 
\ No newline at end of file
+} 
diff --git a/test/files/pos/java-access-pos/J.java b/test/files/pos/java-access-pos/J.java
new file mode 100644
index 0000000..4f20246
--- /dev/null
+++ b/test/files/pos/java-access-pos/J.java
@@ -0,0 +1,15 @@
+package a.b;
+
+public abstract class J {
+  public J() { }
+  J(int x1) { }
+  protected J(int x1, int x2) { }
+  
+  abstract void packageAbstract();
+  protected abstract void protectedAbstract();
+  public abstract void publicAbstract();
+  
+  void packageConcrete() { return; }
+  protected void protectedConcrete() { return; }
+  public void publicConcrete() { return; }
+}
diff --git a/test/files/pos/java-access-pos/S1.scala b/test/files/pos/java-access-pos/S1.scala
new file mode 100644
index 0000000..cc739d9
--- /dev/null
+++ b/test/files/pos/java-access-pos/S1.scala
@@ -0,0 +1,67 @@
+package a.b
+
+/** Declaring "override" all the time.
+ */
+class S1 extends J {
+  override private[b] def packageAbstract() = ()
+  override protected[b] def protectedAbstract() = ()
+  override def publicAbstract() = ()
+  
+  override private[b] def packageConcrete() = ()
+  override protected[b] def protectedConcrete() = ()
+  override def publicConcrete() = ()
+}
+
+/** Implementing abstracts.
+ */
+class S2 extends J {
+  private[b] def packageAbstract() = ()
+  protected[b] def protectedAbstract() = ()
+  def publicAbstract() = ()
+}
+
+/** Widening access.
+ */
+class S3 extends J {
+  protected[b] def packageAbstract() = ()
+  protected[b] def protectedAbstract() = ()
+  def publicAbstract() = ()
+  
+  override protected[b] def packageConcrete() = ()
+  override protected[b] def protectedConcrete() = ()
+  override def publicConcrete() = ()
+}
+/** More widening.
+ */
+class S4 extends J {
+  private[a] def packageAbstract() = ()
+  protected[a] def protectedAbstract() = ()
+  def publicAbstract() = ()
+  
+  override private[a] def packageConcrete() = ()
+  override protected[a] def protectedConcrete() = ()
+  override def publicConcrete() = ()
+}
+/** Yet more widening.
+ */
+class S5 extends J {
+  def packageAbstract() = ()
+  def protectedAbstract() = ()
+  def publicAbstract() = ()
+  
+  override def packageConcrete() = ()
+  override def protectedConcrete() = ()
+  override def publicConcrete() = ()
+}
+/** Constructors.
+ */
+class S6 extends J(1) {  
+  def packageAbstract() = ()
+  def protectedAbstract() = ()
+  def publicAbstract() = ()
+}
+class S7 extends J(1, 2) {
+  def packageAbstract() = ()
+  def protectedAbstract() = ()
+  def publicAbstract() = ()
+}
\ No newline at end of file
diff --git a/test/files/pos/jesper.scala b/test/files/pos/jesper.scala
deleted file mode 100644
index b2a027b..0000000
--- a/test/files/pos/jesper.scala
+++ /dev/null
@@ -1,30 +0,0 @@
-object Pair {
- sealed trait Pair {
-   type First
-   type Second <: Pair
- }
-
- case class End extends Pair {
-   type First = Nothing
-   type Second = End
-
-   def ::[T](v : T) : Cons[T, End] = Cons(v, this)
- }
-
- case object End extends End
-
- final case class Cons[T1, T2 <: Pair](_1 : T1, _2 : T2) extends Pair {
-   type First = T1
-   type Second = T2
-
-   def ::[T](v : T) : Cons[T, Cons[T1, T2]] = Cons(v, this)
-   def find[T](implicit finder : Cons[T1, T2] => T) = finder(this)
- }
-
- implicit def findFirst[T1, T2 <: Pair] : Cons[T1, T2] => T1 = (p : Cons[T1, T2]) => p._1
- implicit def findSecond[T, T1, T2 <: Pair](implicit finder : T2 => T) : Cons[T1, T2] => T = (p : Cons[T1, T2]) => finder(p._2)
-
- val p : Cons[Int, Cons[Boolean, End]] = 10 :: false :: End
-// val x : Boolean = p.find[Boolean](findSecond(findFirst))
- val x2 : Boolean = p.find[Boolean]  // Doesn't compile
-}
diff --git a/test/files/pos/lambdalift.scala b/test/files/pos/lambdalift.scala
index 5348b28..10bbf3a 100644
--- a/test/files/pos/lambdalift.scala
+++ b/test/files/pos/lambdalift.scala
@@ -12,4 +12,4 @@ object test {
     }
     g() + new inner().g();
   }		
-}
\ No newline at end of file
+}
diff --git a/test/files/pos/lambdalift1.scala b/test/files/pos/lambdalift1.scala
index d9172f5..01b224c 100644
--- a/test/files/pos/lambdalift1.scala
+++ b/test/files/pos/lambdalift1.scala
@@ -14,4 +14,4 @@ object test {
     }
     new A().g()
   }
-}
\ No newline at end of file
+}
diff --git a/test/files/pos/lexical.scala b/test/files/pos/lexical.scala
new file mode 100644
index 0000000..034b84b
--- /dev/null
+++ b/test/files/pos/lexical.scala
@@ -0,0 +1,9 @@
+// #2081
+class RichInt(n: Int) {
+  def days = 1000*60*60*24*n
+}
+
+object Test extends Application {
+  implicit def RichInt(n: Int): RichInt = new RichInt(n)
+  println(10.days)
+}
diff --git a/test/files/pos/looping-jsig.scala b/test/files/pos/looping-jsig.scala
index 4bf0ba8..e2d9e76 100644
--- a/test/files/pos/looping-jsig.scala
+++ b/test/files/pos/looping-jsig.scala
@@ -14,5 +14,5 @@ trait BugTrack {
     def amethod[T](p: =>A[T]): A[T] = A(in => cache.get(p) match {
            case Some(res) => res
            case None => p(in)
-     }).giveMeSame
+     }).giveMeSame.asInstanceOf[A[T]]
 }
diff --git a/test/files/pos/manifest1.scala b/test/files/pos/manifest1.scala
index 1dd5946..8901aa7 100644
--- a/test/files/pos/manifest1.scala
+++ b/test/files/pos/manifest1.scala
@@ -13,8 +13,9 @@ object Test {
   abstract class C { type T = String; val x: T }
   val c = new C { val x = "abc" }
   foo(c.x)
-  abstract class D { type T; val x: T }
-  val d: D = new D { type T = String; val x = "x" }
+  abstract class D { type T; implicit val m: Manifest[T]; val x: T }
+  val stringm = implicitly[Manifest[String]]
+  val d: D = new D { type T = String; val m = stringm; val x = "x" }
+  import d.m
   foo(d.x)
-  
 }
diff --git a/test/files/pos/michel3.scala b/test/files/pos/michel3.scala
index 0e85295..348a66a 100644
--- a/test/files/pos/michel3.scala
+++ b/test/files/pos/michel3.scala
@@ -1,3 +1,3 @@
 abstract class A() {
   val v : Int
-}
\ No newline at end of file
+}
diff --git a/test/files/pos/nested2.scala b/test/files/pos/nested2.scala
index 302688a..421ea6f 100644
--- a/test/files/pos/nested2.scala
+++ b/test/files/pos/nested2.scala
@@ -5,5 +5,5 @@ class C[A] {
 
 object Test {
   val x = new C[String]
-  val y: C[String]#D[int] = new x.D[int]
+  val y: C[String]#D[Int] = new x.D[Int]
 }
diff --git a/test/files/pos/nothing_manifest_disambig.scala b/test/files/pos/nothing_manifest_disambig.scala
new file mode 100644
index 0000000..0767420
--- /dev/null
+++ b/test/files/pos/nothing_manifest_disambig.scala
@@ -0,0 +1,10 @@
+object Test {
+  def mani[T: Manifest](xs: T) = xs
+  mani(List())
+ 
+  def listElMani[T: Manifest](xs: List[T]) = xs
+  listElMani(List())
+ 
+  def foo[A, C](m : C)(implicit ev: C <:< Traversable[A], mani: Manifest[A]): (C, A, Manifest[A]) = (m, m.head, mani)
+  foo(List(1,2,3)) 
+}
\ No newline at end of file
diff --git a/test/files/pos/null.scala b/test/files/pos/null.scala
index 59f88ee..1c68e29 100644
--- a/test/files/pos/null.scala
+++ b/test/files/pos/null.scala
@@ -1,3 +1,3 @@
 object M {
   val x: Boolean = null == null;
-}
\ No newline at end of file
+}
diff --git a/test/files/pos/nullary.scala b/test/files/pos/nullary.scala
index ab38a3a..8e5a834 100644
--- a/test/files/pos/nullary.scala
+++ b/test/files/pos/nullary.scala
@@ -17,4 +17,4 @@ class Concrete extends NullaryTest[Int, List] {
 object test {
         (new Concrete).nullary2
         (new Concrete).nullary3        
-}
\ No newline at end of file
+}
diff --git a/test/files/pos/nullary_poly.scala b/test/files/pos/nullary_poly.scala
index f4cef4d..4de7235 100644
--- a/test/files/pos/nullary_poly.scala
+++ b/test/files/pos/nullary_poly.scala
@@ -7,4 +7,4 @@ class A {
   
   // user-defined:
   def polyNullary[T]: List[T] = Nil
-}
\ No newline at end of file
+}
diff --git a/test/files/pos/packageobjs.scala b/test/files/pos/packageobjs.scala
new file mode 100644
index 0000000..ccab133
--- /dev/null
+++ b/test/files/pos/packageobjs.scala
@@ -0,0 +1,8 @@
+package object overloading {
+    def bar(f: (Int) => Unit): Unit = ()
+    def bar(f: (Int, Int) => Unit): Unit = ()
+}
+
+class PackageObjectOverloadingTest {
+    overloading.bar( (i: Int) => () ) // doesn't compile.
+}
diff --git a/test/files/pos/patterns2.scala b/test/files/pos/patterns2.scala
index 93dcedb..821fc43 100644
--- a/test/files/pos/patterns2.scala
+++ b/test/files/pos/patterns2.scala
@@ -13,4 +13,4 @@ object test {
     case Some(b) => 4;
     case None => 5;
   }
-}
\ No newline at end of file
+}
diff --git a/test/files/pos/philippe1.scala b/test/files/pos/philippe1.scala
index 3cace0e..4b4b22e 100644
--- a/test/files/pos/philippe1.scala
+++ b/test/files/pos/philippe1.scala
@@ -5,4 +5,4 @@ object test {
       val res: Array[String] = id(args);
       ()
   }
-}
\ No newline at end of file
+}
diff --git a/test/files/pos/philippe2.scala b/test/files/pos/philippe2.scala
index ec5e558..55a283d 100644
--- a/test/files/pos/philippe2.scala
+++ b/test/files/pos/philippe2.scala
@@ -1,5 +1,3 @@
-// $Id: philippe2.scala 5552 2006-01-17 15:29:35Z michelou $
-
 import scala._;
 class m1() {
   def n() = 0;
diff --git a/test/files/pos/relax_implicit_divergence.scala b/test/files/pos/relax_implicit_divergence.scala
new file mode 100644
index 0000000..8525c84
--- /dev/null
+++ b/test/files/pos/relax_implicit_divergence.scala
@@ -0,0 +1,7 @@
+class A(val options: Seq[String])
+
+object Test {
+  implicit def ss: Equiv[Seq[String]] = error("dummy")
+  implicit def equivA(implicit seqEq: Equiv[Seq[String]]): Equiv[A] = error("dummy")
+  implicitly[Equiv[A]]
+}
\ No newline at end of file
diff --git a/test/files/pos/scala-singleton.scala b/test/files/pos/scala-singleton.scala
new file mode 100644
index 0000000..5e0baa0
--- /dev/null
+++ b/test/files/pos/scala-singleton.scala
@@ -0,0 +1,55 @@
+// A bunch of ridiculous seeming tests until you realize much
+// of this didn't work until the commit which accompanies this.
+object Test {
+  def f1(x: AnyRef with Singleton): AnyRef with Singleton = x
+  def f2[T <: AnyRef with Singleton](x: T): T = x
+    
+  val x1: AnyRef with Singleton = "abc"
+  val x2 = "def"
+  final val x3 = "ghi"
+  val x4: String = "jkl"
+  
+  // compiles...
+  def narrow1(x: AnyRef): AnyRef with Singleton = x
+
+  // compiles, still doesn't help.
+  def narrow2(x: AnyRef): AnyRef with Singleton = x.asInstanceOf[x.type]
+
+  // fails, wait, what? This fails and narrow1 compiles?
+  def narrow3(x: AnyRef): AnyRef with Singleton = x.asInstanceOf[AnyRef with Singleton]
+  
+  // ok
+  def narrow4[T <: AnyRef](x: T): AnyRef with Singleton = x
+  
+  object imp {
+    implicit def narrow4[T <: AnyRef](x: T): AnyRef with Singleton = x
+    val x5: String = "mno"
+    def imp1 = f1(x5)
+    
+    // f2(x5)   // doesn't work but I think it should
+    def imp2 = f2(narrow4(x5))
+  }
+  
+  def main(args: Array[String]): Unit = {
+    // compiles
+    f1(x1)
+    f1(x2)
+    f1(x3)
+    f1(x4)
+    
+    f2(x1)
+    // f2(x2)
+    // f2(x3)   // maybe this one should work
+    // f2(x4)
+
+    f1(narrow1(x4))
+    f1(narrow2(x4))
+    f1(narrow3(x4))
+    f1(narrow4(x4))
+    f2(narrow1(x4))
+    f2(narrow2(x4))
+    f2(narrow3(x4))
+    f2(narrow4(x4))
+  }
+}
+
diff --git a/test/files/pos/scan.scala b/test/files/pos/scan.scala
new file mode 100644
index 0000000..f056c77
--- /dev/null
+++ b/test/files/pos/scan.scala
@@ -0,0 +1,23 @@
+
+
+
+
+object Test {
+
+  def main(args: Array[String]) {
+    val lst = List(1, 2, 3, 4, 5)
+    
+    assert(lst.scanLeft(0)(_ + _) == List(0, 1, 3, 6, 10, 15))
+    assert(lst.scanRight(0)(_ + _) == List(15, 14, 12, 9, 5, 0))
+    
+    val emp = List[Int]()
+    assert(emp.scanLeft(0)(_ + _) == List(0))
+    assert(emp.scanRight(0)(_ + _) == List(0))
+    
+    val stream = Stream(1, 2, 3, 4, 5)
+    assert(stream.scanLeft(0)(_ + _) == Stream(0, 1, 3, 6, 10, 15))
+    
+    assert(Stream.from(1).scanLeft(0)(_ + _).take(5) == Stream(0, 1, 3, 6, 10))
+  }
+
+}
\ No newline at end of file
diff --git a/test/files/pos/scoping3.scala b/test/files/pos/scoping3.scala
index e35ffb3..f6d531d 100644
--- a/test/files/pos/scoping3.scala
+++ b/test/files/pos/scoping3.scala
@@ -1,5 +1,3 @@
-// $Id: scoping3.scala 15104 2008-05-20 10:32:59Z michelou $
-
 object CI {
   trait TreeDisplay {
     type TreeNode <: ITreeNode
diff --git a/test/files/pos/selftails.scala b/test/files/pos/selftails.scala
new file mode 100644
index 0000000..7c58543
--- /dev/null
+++ b/test/files/pos/selftails.scala
@@ -0,0 +1,23 @@
+package net.liftweb.util
+ 
+/**
+* This trait adds functionality to Scala standard types
+*/
+trait BasicTypesHelpers { self: StringHelpers with ControlHelpers =>
+ 
+  /**
+   * Compare two arrays of Byte for byte equality.
+   * @return true if two Byte arrays contain the same bytes
+   */
+  def isEq(a: Array[Byte], b: Array[Byte]) = {
+    def eq(a: Array[Byte], b: Array[Byte], pos: Int, len: Int): Boolean = {
+      if (pos == len) true
+      else if (a(pos) != b(pos)) false
+      else eq(a , b, pos + 1, len)
+    }
+    a.length == b.length && eq(a, b, 0, a.length)
+  }
+}
+
+trait StringHelpers 
+trait ControlHelpers
diff --git a/test/files/pos/signatures/Test.java b/test/files/pos/signatures/Test.java
new file mode 100644
index 0000000..78c1965
--- /dev/null
+++ b/test/files/pos/signatures/Test.java
@@ -0,0 +1,11 @@
+import scala.collection.mutable.IndexedSeq;
+import test.Outer;
+
+/* Test correct generation of java signatures. The Outer class should not
+ * have a Java signature attribute for the inner method definition. Trait
+ * Mutable should have one, even though it is also a nested definition. 
+ * (but for classes there is a way to tell about nesting to the JVM).
+ */
+class Test {
+    Outer o = new Outer();
+}
diff --git a/test/files/pos/signatures/sig.scala b/test/files/pos/signatures/sig.scala
new file mode 100644
index 0000000..3feb9c4
--- /dev/null
+++ b/test/files/pos/signatures/sig.scala
@@ -0,0 +1,12 @@
+package test
+
+/* Tests correct generation of Java signatures. The local method 'bar' should
+ * not get a generic signature, as it may refer to type parameters of the enclosing 
+ * method, and the JVM does not know about nested methods.
+ */
+class Outer {
+  def foo[A, B](x: A, y: B) = {
+    def bar[X](x1: A, y1: B, z1: X) = z1
+    bar(x, y, 10)
+  }
+}
diff --git a/test/files/pos/spec-Function1.scala b/test/files/pos/spec-Function1.scala
new file mode 100644
index 0000000..24ee6c0
--- /dev/null
+++ b/test/files/pos/spec-Function1.scala
@@ -0,0 +1,48 @@
+
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2002-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+// generated by genprod on Wed Apr 23 10:06:16 CEST 2008 (with fancy comment) (with extra methods)
+
+package scala
+
+
+/** <p>
+ *    Function with 1 parameters.
+ *  </p>
+ *  <p>
+      In the following example the definition of
+ *    <code>succ</code> is a shorthand for the anonymous class definition
+ *    <code>anonfun1</code>:
+ *  </p>
+ *  <pre>
+ *  <b>object</b> Main <b>extends</b> Application {
+ *
+ *    <b>val</b> succ = (x: Int) => x + 1
+ *
+ *    <b>val</b> anonfun1 = <b>new</b> Function1[Int, Int] {
+ *      <b>def</b> apply(x: Int): Int = x + 1
+ *    }
+ *
+ *    println(succ(0))
+ *    println(anonfun1(0))
+ *  }</pre>
+ */
+trait Function1[@specialized -T1, @specialized +R] extends AnyRef { self =>
+  def apply(v1:T1): R
+  override def toString() = "<function>"
+  
+  /** (f compose g)(x) ==  f(g(x))
+   */
+  def compose[A](g: A => T1): A => R = { x => apply(g(x)) }
+  
+  /** (f andThen g)(x) ==  g(f(x))
+   */
+  def andThen[A](g: R => A): T1 => A = { x => g(apply(x)) }
+
+}
diff --git a/test/files/pos/spec-List.scala b/test/files/pos/spec-List.scala
new file mode 100644
index 0000000..17acb40
--- /dev/null
+++ b/test/files/pos/spec-List.scala
@@ -0,0 +1,869 @@
+/*                     __                                               *\
+**     ________ ___   / /  ___     Scala API                            **
+**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
+**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
+** /____/\___/_/ |_/____/_/ | |                                         **
+**                          |/                                          **
+\*                                                                      */
+
+
+package scala.collection
+package immutable
+
+import generic._
+import mutable.{Builder, ListBuffer}
+import annotation.tailrec
+
+/** A class representing an ordered collection of elements of type
+ *  <code>a</code>. This class comes with two implementing case
+ *  classes <code>scala.Nil</code> and <code>scala.::</code> that
+ *  implement the abstract members <code>isEmpty</code>,
+ *  <code>head</code> and <code>tail</code>.
+ *
+ *  @author  Martin Odersky and others
+ *  @version 2.8
+ */
+sealed trait List[@specialized +A] extends LinearSeq[A] 
+                                  with Product 
+                                  with GenericTraversableTemplate[A, List]
+                                  with LinearSeqOptimized[A, List[A]] {
+  override def companion: GenericCompanion[List] = List
+
+  import scala.collection.{Iterable, Traversable, Seq}
+
+  /** Returns true if the list does not contain any elements.
+   *  @return <code>true</code>, iff the list is empty.
+   */
+  def isEmpty: Boolean
+
+  /** Returns this first element of the list.
+   *
+   *  @return the first element of this list.
+   *  @throws Predef.NoSuchElementException if the list is empty.
+   */
+  def head: A
+
+  /** Returns this list without its first element.
+   *
+   *  @return this list without its first element.
+   *  @throws Predef.NoSuchElementException if the list is empty.
+   */
+  def tail: List[A]
+
+  // New methods in List
+
+  /** <p>
+   *    Add an element <code>x</code> at the beginning of this list.
+   *  </p>
+   *
+   *  @param x the element to prepend.
+   *  @return  the list with <code>x</code> added at the beginning.
+   *  @ex <code>1 :: List(2, 3) = List(2, 3).::(1) = List(1, 2, 3)</code>
+   */
+  def ::[@specialized B >: A] (x: B): List[B] =
+    new scala.collection.immutable.::(x, this)
+
+  /** <p>
+   *    Returns a list resulting from the concatenation of the given
+   *    list <code>prefix</code> and this list. 
+   *  </p>
+   *
+   *  @param prefix the list to concatenate at the beginning of this list.
+   *  @return the concatenation of the two lists.
+   *  @ex <code>List(1, 2) ::: List(3, 4) = List(3, 4).:::(List(1, 2)) = List(1, 2, 3, 4)</code>
+   */
+  def :::[B >: A](prefix: List[B]): List[B] =
+    if (isEmpty) prefix
+    else (new ListBuffer[B] ++= prefix).prependToList(this)
+
+  /** Reverse the given prefix and append the current list to that.
+   *  This function is equivalent to an application of <code>reverse</code>
+   *  on the prefix followed by a call to <code>:::</code>, but is more
+   *  efficient.
+   *
+   *  @param prefix the prefix to reverse and then prepend
+   *  @return       the concatenation of the reversed prefix and the current list.
+   */
+  def reverse_:::[B >: A](prefix: List[B]): List[B] = {
+    var these: List[B] = this
+    var pres = prefix
+    while (!pres.isEmpty) {
+      these = pres.head :: these
+      pres = pres.tail
+    }
+    these
+  }
+
+  /** Apply a function to all the elements of the list, and return the
+   *  reversed list of results. This is equivalent to a call to <code>map</code>
+   *  followed by a call to <code>reverse</code>, but more efficient.
+   *  !!! should we deprecate this? Why have reverseMap, but not filterMap or reverseFilter, say?
+   *  @param f the function to apply to each elements.
+   *  @return  the reversed list of results.
+   */
+  def reverseMap[B](f: A => B): List[B] = {
+    @tailrec
+    def loop(l: List[A], res: List[B]): List[B] = l match {
+      case Nil => res
+      case head :: tail => loop(tail, f(head) :: res)
+    }
+    loop(this, Nil)
+  }
+
+  /** Like xs map f, but returns <code>xs</code> unchanged if function
+   *  <code>f</code> maps all elements to themselves (wrt ==).
+   *  @note Unlike `map`, `mapConserve` is not tail-recursive.
+   */
+  def mapConserve[B >: A] (f: A => B): List[B] = {
+    def loop(ys: List[A]): List[B] =
+      if (ys.isEmpty) this
+      else {
+        val head0 = ys.head
+        val head1 = f(head0)
+        if (head1 == head0) {
+          loop(ys.tail)
+        } else {
+          val ys1 = head1 :: ys.tail.mapConserve(f)
+          if (this eq ys) ys1
+          else {
+            val b = new ListBuffer[B]
+            var xc = this
+            while (xc ne ys) {
+              b += xc.head
+              xc = xc.tail
+            }
+            b.prependToList(ys1)
+          }
+        }
+      }
+    loop(this)
+  }
+
+  // Overridden methods from IterableLike or overloaded variants of such methods
+  
+  /** Create a new list which contains all elements of this list
+   *  followed by all elements of Traversable `that'
+   */
+  override def ++[B >: A, That](xs: TraversableOnce[B])(implicit bf: CanBuildFrom[List[A], B, That]): That = {
+    val b = bf(this)
+    if (b.isInstanceOf[ListBuffer[_]]) (this ::: xs.toList).asInstanceOf[That]
+    else super.++(xs)
+  }
+
+  /** Overrides the method in Iterable for efficiency.
+   *
+   *  @return  the list itself
+   */
+  override def toList: List[A] = this
+
+  /** Returns the <code>n</code> first elements of this list, or else the whole 
+   *  list, if it has less than <code>n</code> elements.
+
+   *  @param n the number of elements to take.
+   *  @return the <code>n</code> first elements of this list.
+   */
+  override def take(n: Int): List[A] = {
+    val b = new ListBuffer[A]
+    var i = 0
+    var these = this
+    while (!these.isEmpty && i < n) {
+      i += 1
+      b += these.head
+      these = these.tail
+    }
+    if (these.isEmpty) this
+    else b.toList
+  }
+
+  /** Returns the list without its <code>n</code> first elements.
+   *  If this list has less than <code>n</code> elements, the empty list is returned.
+   *
+   *  @param n the number of elements to drop.
+   *  @return the list without its <code>n</code> first elements.
+   */
+  override def drop(n: Int): List[A] = {
+    var these = this
+    var count = n
+    while (!these.isEmpty && count > 0) {
+      these = these.tail
+      count -= 1
+    }
+    these
+  }
+
+  /** Returns the list with elements belonging to the given index range.
+   *
+   *  @param start the start position of the list slice.
+   *  @param end   the end position (exclusive) of the list slice.
+   *  @return the list with elements belonging to the given index range.
+   */
+  override def slice(start: Int, end: Int): List[A] = {
+    var len = end
+    if (start > 0) len -= start
+    drop(start) take len
+  }
+
+  /** Returns the rightmost <code>n</code> elements from this list.
+   *
+   *  @param n the number of elements to take
+   *  @return the suffix of length <code>n</code> of the list
+   */
+  override def takeRight(n: Int): List[A] = {
+    @tailrec
+    def loop(lead: List[A], lag: List[A]): List[A] = lead match {
+      case Nil => lag
+      case _ :: tail => loop(tail, lag.tail)
+    }
+    loop(drop(n), this)
+  }
+  
+  // dropRight is inherited from Stream
+
+  /** Split the list at a given point and return the two parts thus
+   *  created.
+   *
+   *  @param n the position at which to split
+   *  @return  a pair of lists composed of the first <code>n</code>
+   *           elements, and the other elements.
+   */
+  override def splitAt(n: Int): (List[A], List[A]) = {
+    val b = new ListBuffer[A]
+    var i = 0
+    var these = this
+    while (!these.isEmpty && i < n) {
+      i += 1
+      b += these.head
+      these = these.tail
+    }
+    (b.toList, these)
+  }
+
+  /** Returns the longest prefix of this list whose elements satisfy
+   *  the predicate <code>p</code>.
+   *
+   *  @param p the test predicate.
+   *  @return  the longest prefix of this list whose elements satisfy
+   *           the predicate <code>p</code>.
+   */
+  override def takeWhile(p: A => Boolean): List[A] = {
+    val b = new ListBuffer[A]
+    var these = this
+    while (!these.isEmpty && p(these.head)) {
+      b += these.head
+      these = these.tail
+    }
+    b.toList
+  }
+
+  /** Returns the longest suffix of this list whose first element
+   *  does not satisfy the predicate <code>p</code>.
+   *
+   *  @param p the test predicate.
+   *  @return  the longest suffix of the list whose first element
+   *           does not satisfy the predicate <code>p</code>.
+   */
+  override def dropWhile(p: A => Boolean): List[A] = {
+    @tailrec
+    def loop(xs: List[A]): List[A] =
+      if (xs.isEmpty || !p(xs.head)) xs
+      else loop(xs.tail)
+
+    loop(this)
+  }
+
+  /** Returns the longest prefix of the list whose elements all satisfy
+   *  the given predicate, and the rest of the list.
+   *
+   *  @param p the test predicate
+   *  @return  a pair consisting of the longest prefix of the list whose
+   *           elements all satisfy <code>p</code>, and the rest of the list.
+   */
+  override def span(p: A => Boolean): (List[A], List[A]) = {
+    val b = new ListBuffer[A]
+    var these = this
+    while (!these.isEmpty && p(these.head)) {
+      b += these.head
+      these = these.tail
+    }
+    (b.toList, these)
+  }
+
+  /** A list consisting of all elements of this list in reverse order.
+   */
+  override def reverse: List[A] = {
+    var result: List[A] = Nil
+    var these = this
+    while (!these.isEmpty) {
+      result = these.head :: result
+      these = these.tail
+    }
+    result
+  }
+
+  override def stringPrefix = "List"
+
+  override def toStream : Stream[A] = 
+    if (isEmpty) Stream.Empty
+    else new Stream.Cons(head, tail.toStream)
+
+  // !!! todo: work in patch
+
+  /** Computes the difference between this list and the given list
+   *  <code>that</code>.
+   *
+   *  @param that the list of elements to remove from this list.
+   *  @return     this list without the elements of the given list
+   *              <code>that</code>.
+   */
+  @deprecated("use `diff' instead")
+  def -- [B >: A](that: List[B]): List[B] = {
+    val b = new ListBuffer[B]
+    var these = this
+    while (!these.isEmpty) {
+      if (!that.contains(these.head)) b += these.head
+      these = these.tail
+    }
+    b.toList
+  }
+
+  /** Computes the difference between this list and the given object
+   *  <code>x</code>.
+   *
+   *  @param x    the object to remove from this list.
+   *  @return     this list without occurrences of the given object
+   *              <code>x</code>.
+   */
+  @deprecated("use `diff' instead")
+  def - [B >: A](x: B): List[B] = {
+    val b = new ListBuffer[B]
+    var these = this
+    while (!these.isEmpty) {
+      if (these.head != x) b += these.head
+      these = these.tail
+    }
+    b.toList
+  }
+
+  /** <p>
+   *    Sort the list according to the comparison function
+   *    <code><(e1: a, e2: a) => Boolean</code>,
+   *    which should be true iff <code>e1</code> is smaller than
+   *    <code>e2</code>.
+   *  !!! todo: move sorting to IterableLike
+   *  </p>
+   *
+   *  @param lt the comparison function
+   *  @return   a list sorted according to the comparison function
+   *            <code><(e1: a, e2: a) => Boolean</code>.
+   *  @ex <pre>
+   *    List("Steve", "Tom", "John", "Bob")
+   *      .sort((e1, e2) => (e1 compareTo e2) < 0) =
+   *    List("Bob", "John", "Steve", "Tom")</pre>
+   */
+  @deprecated("use `sortWith' instead")
+  def sort(lt : (A,A) => Boolean): List[A] = {
+    /** Merge two already-sorted lists */
+    def merge(l1: List[A], l2: List[A]): List[A] = {
+      val res = new ListBuffer[A]
+      var left1 = l1
+      var left2 = l2
+
+      while (!left1.isEmpty && !left2.isEmpty) {
+	if(lt(left1.head, left2.head)) {
+	  res += left1.head
+	  left1 = left1.tail
+	} else {
+	  res += left2.head
+	  left2 = left2.tail
+	}
+      }
+
+      res ++= left1
+      res ++= left2
+
+      res.toList
+    }
+
+    /** Split a list into two lists of about the same size */
+    def split(lst: List[A]) = {
+      val res1 = new ListBuffer[A]
+      val res2 = new ListBuffer[A]
+      var left = lst
+
+      while (!left.isEmpty) {
+	res1 += left.head
+	left = left.tail
+	if (!left.isEmpty) {
+	  res2 += left.head
+	  left = left.tail
+	}
+      }
+
+      (res1.toList, res2.toList)
+    }
+
+
+    /** Merge-sort the specified list */
+    def ms(lst: List[A]): List[A] =
+      lst match {
+	case Nil => lst
+	case x :: Nil => lst
+	case x :: y :: Nil =>
+	  if (lt(x,y))
+	    lst
+	  else
+	    y :: x :: Nil
+
+	case lst =>
+          val (l1, l2) = split(lst)
+          val l1s = ms(l1)
+          val l2s = ms(l2)
+          merge(l1s, l2s)
+      }
+
+    ms(this)
+  }
+
+}
+
+/** The empty list.
+ *
+ *  @author  Martin Odersky
+ *  @version 1.0, 15/07/2003
+ */
+ at SerialVersionUID(0 - 8256821097970055419L)
+case object Nil extends List[Nothing] {
+  override def isEmpty = true
+  override def head: Nothing =
+    throw new NoSuchElementException("head of empty list")
+  override def tail: List[Nothing] =
+    throw new NoSuchElementException("tail of empty list")
+  // Removal of equals method here might lead to an infinite recusion similar to IntMap.equals.
+  override def equals(that: Any) = that match {
+    case that1: Seq[_] => that1.isEmpty
+    case _ => false
+  }
+}
+
+/** A non empty list characterized by a head and a tail.
+ *
+ *  @author  Martin Odersky
+ *  @version 1.0, 15/07/2003
+ */
+ at SerialVersionUID(0L - 8476791151983527571L)
+final case class ::[@specialized B](private var hd: B, private[scala] var tl: List[B]) extends List[B] {
+  override def head : B = hd
+  override def tail : List[B] = tl
+  override def isEmpty: Boolean = false
+
+  import java.io._
+
+  private def writeObject(out: ObjectOutputStream) {
+    var xs: List[B] = this
+    while (!xs.isEmpty) { out.writeObject(xs.head); xs = xs.tail }
+    out.writeObject(ListSerializeEnd)
+  }
+
+  private def readObject(in: ObjectInputStream) {
+    hd = in.readObject.asInstanceOf[B]
+    assert(hd != ListSerializeEnd)
+    var current: ::[B] = this
+    while (true) in.readObject match {
+      case ListSerializeEnd =>
+        current.tl = Nil
+        return
+      case a : Any =>
+        val list : ::[B] = new ::(a.asInstanceOf[B], Nil)
+        current.tl = list
+        current = list
+    }
+  }
+}
+
+/** This object provides methods for creating specialized lists, and for
+ *  transforming special kinds of lists (e.g. lists of lists).
+ *
+ *  @author  Martin Odersky
+ *  @version 2.8
+ */
+object List extends SeqFactory[List] {
+  
+  import collection.{Iterable, Seq}
+
+  implicit def builderFactory[A]: CanBuildFrom[Coll, A, List[A]] = 
+    new GenericCanBuildFrom[A] {
+      override def apply() = newBuilder[A]
+    }
+  def newBuilder[A]: Builder[A, List[A]] = new ListBuffer[A]
+
+  override def empty[A]: List[A] = Nil
+
+  override def apply[A](xs: A*): List[A] = xs.toList
+
+  /** Create a sorted list with element values
+   * <code>v<sub>n+1</sub> = step(v<sub>n</sub>)</code>
+   * where <code>v<sub>0</sub> = start</code>
+   * and elements are in the range between <code>start</code> (inclusive)
+   * and <code>end</code> (exclusive)
+   *
+   *  @param start the start value of the list
+   *  @param end  the end value of the list
+   *  @param step the increment function of the list, which given <code>v<sub>n</sub></code>,
+   *              computes <code>v<sub>n+1</sub></code>. Must be monotonically increasing
+   *              or decreasing.
+   *  @return     the sorted list of all integers in range [start;end).
+   */
+  @deprecated("use `iterate' instead")
+  def range(start: Int, end: Int, step: Int => Int): List[Int] = {
+    val up = step(start) > start
+    val down = step(start) < start
+    val b = new ListBuffer[Int]
+    var i = start
+    while ((!up || i < end) && (!down || i > end)) {
+      b += i
+      val next = step(i)
+      if (i == next)
+        throw new IllegalArgumentException("the step function did not make any progress on "+ i)
+      i = next
+    }
+    b.toList
+  }
+
+  /** Create a list containing several copies of an element.
+   *
+   *  @param n    the length of the resulting list
+   *  @param elem the element composing the resulting list
+   *  @return     a list composed of n elements all equal to elem
+   */
+  @deprecated("use `fill' instead")
+  def make[A](n: Int, elem: A): List[A] = {
+    val b = new ListBuffer[A]
+    var i = 0
+    while (i < n) {
+      b += elem
+      i += 1
+    }
+    b.toList
+  }
+
+  /** Concatenate all the elements of a given list of lists.
+   *
+   *  @param xss the list of lists that are to be concatenated
+   *  @return    the concatenation of all the lists
+   */
+  @deprecated("use `xss.flatten' instead")
+  def flatten[A](xss: List[List[A]]): List[A] = { 
+    val b = new ListBuffer[A] 
+    for (xs <- xss) {
+      var xc = xs
+      while (!xc.isEmpty) {
+        b += xc.head
+        xc = xc.tail
+      }
+    }
+    b.toList
+  }
+
+  /** Transforms a list of pairs into a pair of lists.
+   *
+   *  @param xs the list of pairs to unzip
+   *  @return a pair of lists.
+   */
+  @deprecated("use `xs.unzip' instead")
+  def unzip[A,B](xs: List[(A,B)]): (List[A], List[B]) = {
+    val b1 = new ListBuffer[A]
+    val b2 = new ListBuffer[B]
+    var xc = xs
+    while (!xc.isEmpty) {
+      b1 += xc.head._1
+      b2 += xc.head._2
+      xc = xc.tail
+    }
+    (b1.toList, b2.toList)
+  }
+
+  /** Transforms an iterable of pairs into a pair of lists.
+   *
+   *  @param xs the iterable of pairs to unzip
+   *  @return a pair of lists.
+   */
+  @deprecated("use `xs.unzip' instead")
+  def unzip[A,B](xs: Iterable[(A,B)]): (List[A], List[B]) = 
+      xs.foldRight[(List[A], List[B])]((Nil, Nil)) {
+        case ((x, y), (xs, ys)) => (x :: xs, y :: ys)
+      }
+
+  /**
+   * Returns the <code>Left</code> values in the given <code>Iterable</code>
+   * of <code>Either</code>s.
+   */
+  @deprecated("use `Either.lefts' instead")
+  def lefts[A, B](es: Iterable[Either[A, B]]) = 
+    es.foldRight[List[A]](Nil)((e, as) => e match {
+      case Left(a) => a :: as
+      case Right(_) => as
+    })     
+ 
+  /**
+   * Returns the <code>Right</code> values in the given<code>Iterable</code> of  <code>Either</code>s.
+   */
+  @deprecated("use `Either.rights' instead")
+  def rights[A, B](es: Iterable[Either[A, B]]) = 
+    es.foldRight[List[B]](Nil)((e, bs) => e match {
+      case Left(_) => bs
+      case Right(b) => b :: bs
+    })
+
+  /** Transforms an Iterable of Eithers into a pair of lists.
+   *
+   *  @param xs the iterable of Eithers to separate
+   *  @return a pair of lists.
+   */
+  @deprecated("use `Either.separate' instead")
+  def separate[A,B](es: Iterable[Either[A,B]]): (List[A], List[B]) =
+      es.foldRight[(List[A], List[B])]((Nil, Nil)) {
+      case (Left(a), (lefts, rights)) => (a :: lefts, rights)
+      case (Right(b), (lefts, rights)) => (lefts, b :: rights)
+    }
+
+  /** Converts an iterator to a list.
+   *
+   *  @param it the iterator to convert
+   *  @return   a list that contains the elements returned by successive
+   *            calls to <code>it.next</code>
+   */
+  @deprecated("use `it.toList' instead")
+  def fromIterator[A](it: Iterator[A]): List[A] = it.toList
+
+  /** Converts an array into a list.
+   *
+   *  @param arr the array to convert
+   *  @return    a list that contains the same elements than <code>arr</code>
+   *             in the same order
+   */
+  @deprecated("use `array.toList' instead")
+  def fromArray[A](arr: Array[A]): List[A] = fromArray(arr, 0, arr.length)
+
+  /** Converts a range of an array into a list.
+   *
+   *  @param arr   the array to convert
+   *  @param start the first index to consider
+   *  @param len   the length of the range to convert
+   *  @return      a list that contains the same elements than <code>arr</code>
+   *               in the same order
+   */
+  @deprecated("use `array.view(start, end).toList' instead")
+  def fromArray[A](arr: Array[A], start: Int, len: Int): List[A] = {
+    var res: List[A] = Nil
+    var i = start + len
+    while (i > start) {
+      i -= 1
+      res = arr(i) :: res
+    }
+    res
+  }
+
+  /** Parses a string which contains substrings separated by a
+   *  separator character and returns a list of all substrings.
+   *
+   *  @param str       the string to parse
+   *  @param separator the separator character
+   *  @return          the list of substrings
+   */
+  @deprecated("use `str.split(separator).toList' instead")
+  def fromString(str: String, separator: Char): List[String] = {
+    var words: List[String] = Nil
+    var pos = str.length()
+    while (pos > 0) {
+      val pos1 = str.lastIndexOf(separator, pos - 1)
+      if (pos1 + 1 < pos)
+        words = str.substring(pos1 + 1, pos) :: words
+      pos = pos1
+    }
+    words
+  }
+
+  /** Returns the given string as a list of characters.
+   *
+   *  @param str the string to convert.
+   *  @return    the string as a list of characters.
+   */
+  @deprecated("use `str.toList' instead")
+  def fromString(str: String): List[Char] = str.toList
+
+  /** Returns the given list of characters as a string.
+   *
+   *  @param xs the list to convert.
+   *  @return   the list in form of a string.
+   */
+  @deprecated("use `xs.mkString' instead")
+  def toString(xs: List[Char]): String = {
+    val sb = new StringBuilder()
+    var xc = xs
+    while (!xc.isEmpty) {
+      sb.append(xc.head)
+      xc = xc.tail
+    }
+    sb.toString()
+  }
+
+  /** Like xs map f, but returns <code>xs</code> unchanged if function
+   *  <code>f</code> maps all elements to themselves.
+   */
+  @deprecated("use `xs.mapConserve(f)' instead")
+  def mapConserve[A <: AnyRef](xs: List[A])(f: A => A): List[A] = {
+    def loop(ys: List[A]): List[A] =
+      if (ys.isEmpty) xs
+      else {
+        val head0 = ys.head
+        val head1 = f(head0)
+        if (head1 eq head0) {
+          loop(ys.tail)
+        } else {
+          val ys1 = head1 :: mapConserve(ys.tail)(f)
+          if (xs eq ys) ys1
+          else {
+            val b = new ListBuffer[A]
+            var xc = xs
+            while (xc ne ys) {
+              b += xc.head
+              xc = xc.tail
+            }
+            b.prependToList(ys1)
+          }
+        }
+      }
+    loop(xs)
+  }
+
+  /** Returns the list resulting from applying the given function <code>f</code>
+   *  to corresponding elements of the argument lists.
+   *  @param f function to apply to each pair of elements.
+   *  @return <code>[f(a0,b0), ..., f(an,bn)]</code> if the lists are 
+   *          <code>[a0, ..., ak]</code>, <code>[b0, ..., bl]</code> and
+   *          <code>n = min(k,l)</code>
+   */
+  @deprecated("use `(xs, ys).map(f)' instead")
+  def map2[A,B,C](xs: List[A], ys: List[B])(f: (A, B) => C): List[C] = {
+    val b = new ListBuffer[C]
+    var xc = xs
+    var yc = ys
+    while (!xc.isEmpty && !yc.isEmpty) {
+      b += f(xc.head, yc.head)
+      xc = xc.tail
+      yc = yc.tail
+    }
+    b.toList
+  }
+
+  /** Returns the list resulting from applying the given function
+   *  <code>f</code> to corresponding elements of the argument lists.
+   *
+   *  @param f function to apply to each pair of elements.
+   *  @return  <code>[f(a<sub>0</sub>,b<sub>0</sub>,c<sub>0</sub>),
+   *           ..., f(a<sub>n</sub>,b<sub>n</sub>,c<sub>n</sub>)]</code>
+   *           if the lists are <code>[a<sub>0</sub>, ..., a<sub>k</sub>]</code>,
+   *           <code>[b<sub>0</sub>, ..., b<sub>l</sub>]</code>,
+   *           <code>[c<sub>0</sub>, ..., c<sub>m</sub>]</code> and
+   *           <code>n = min(k,l,m)</code>
+   */
+  @deprecated("use `(xs, ys, zs).map(f)' instead")
+  def map3[A,B,C,D](xs: List[A], ys: List[B], zs: List[C])(f: (A, B, C) => D): List[D] = {
+    val b = new ListBuffer[D]
+    var xc = xs
+    var yc = ys
+    var zc = zs
+    while (!xc.isEmpty && !yc.isEmpty && !zc.isEmpty) {
+      b += f(xc.head, yc.head, zc.head)
+      xc = xc.tail
+      yc = yc.tail
+      zc = zc.tail
+    }
+    b.toList
+  }
+
+  /** Tests whether the given predicate <code>p</code> holds 
+   *  for all corresponding elements of the argument lists.
+   *
+   *  @param p function to apply to each pair of elements.
+   *  @return  <code>(p(a<sub>0</sub>,b<sub>0</sub>) &&
+   *           ... && p(a<sub>n</sub>,b<sub>n</sub>))]</code>
+   *           if the lists are <code>[a<sub>0</sub>, ..., a<sub>k</sub>]</code>;
+   *           <code>[b<sub>0</sub>, ..., b<sub>l</sub>]</code>
+   *           and <code>n = min(k,l)</code>
+   */
+  @deprecated("use `(xs, ys).forall(f)' instead")
+  def forall2[A,B](xs: List[A], ys: List[B])(f: (A, B) => Boolean): Boolean = {
+    var xc = xs
+    var yc = ys
+    while (!xc.isEmpty && !yc.isEmpty) {
+      if (!f(xc.head, yc.head)) return false
+      xc = xc.tail
+      yc = yc.tail
+    }
+    true
+  }
+
+  /** Tests whether the given predicate <code>p</code> holds
+   *  for some corresponding elements of the argument lists.
+   *
+   *  @param p function to apply to each pair of elements.
+   *  @return  <code>n != 0 && (p(a<sub>0</sub>,b<sub>0</sub>) ||
+   *           ... || p(a<sub>n</sub>,b<sub>n</sub>))]</code> if the lists are
+   *           <code>[a<sub>0</sub>, ..., a<sub>k</sub>]</code>,
+   *           <code>[b<sub>0</sub>, ..., b<sub>l</sub>]</code> and
+   *           <code>n = min(k,l)</code>
+   */
+  @deprecated("use `(xs, ys).exists(f)' instead")
+  def exists2[A,B](xs: List[A], ys: List[B])(f: (A, B) => Boolean): Boolean = {
+    var xc = xs
+    var yc = ys
+    while (!xc.isEmpty && !yc.isEmpty) {
+      if (f(xc.head, yc.head)) return true
+      xc = xc.tail
+      yc = yc.tail
+    }
+    false
+  }
+
+  /** Transposes a list of lists.
+   *  pre: All element lists have the same length.
+   *
+   *  @param xss the list of lists
+   *  @return    the transposed list of lists
+   */
+  @deprecated("use p`xss.transpose' instead")
+  def transpose[A](xss: List[List[A]]): List[List[A]] = {
+    val buf = new ListBuffer[List[A]]
+    var yss = xss
+    while (!yss.head.isEmpty) {
+      buf += (yss map (_.head))
+      yss = (yss map (_.tail))
+    }
+    buf.toList
+  }
+
+  /** Lists with ordered elements are ordered
+  implicit def list2ordered[a <% Ordered[a]](x: List[a]): Ordered[List[a]] = new Ordered[List[a]] {
+    def compare [b >: List[a] <% Ordered[b]](y: b): Int = y match {
+      case y1: List[a] => compareLists(x, y1);
+      case _ => -(y compare x)
+    }
+    private def compareLists(xs: List[a], ys: List[a]): Int = {
+      if (xs.isEmpty && ys.isEmpty) 0
+      else if (xs.isEmpty) -1
+      else if (ys.isEmpty) 1
+      else {
+        val s = xs.head compare ys.head;
+        if (s != 0) s
+        else compareLists(xs.tail, ys.tail)
+      }
+    }
+  }
+   */
+}
+
+/** Only used for list serialization */
+ at SerialVersionUID(0L - 8476791151975527571L)
+private[scala] case object ListSerializeEnd
+
diff --git a/test/files/pos/spec-annotations.scala b/test/files/pos/spec-annotations.scala
new file mode 100644
index 0000000..215f00d
--- /dev/null
+++ b/test/files/pos/spec-annotations.scala
@@ -0,0 +1,35 @@
+class ann(i: Int) extends Annotation
+
+// annotations on abstract types
+abstract class C1[@serializable @cloneable +T, U, V[_]]
+abstract class C2[@deprecated
+                  @ann(1) T <: Number,
+                  V]
+abstract class C3 {
+  @ann(2) type X <: Number
+}
+
+object Test {
+
+  // bug #1028
+  val x = 1
+  @ann(x) val a = ()
+  @ann({val y = 2; y}) val b = ()
+
+  def c: Int @ann(x) = 1
+  def d: String @ann({val z = 0; z - 1}) = "2"
+  def e[@deprecated T, U](x: T) = x
+
+  //bug #1214
+  val y = new (Integer @ann(0))(2)
+
+  import scala.reflect.BeanProperty
+
+  // bug #637
+  trait S { def getField(): Int }
+  class O extends S { @BeanProperty val field = 0 }
+
+  // bug #1070
+  trait T { @BeanProperty var field = 1 }
+}
+
diff --git a/test/files/pos/spec-arrays.scala b/test/files/pos/spec-arrays.scala
new file mode 100644
index 0000000..84f6eef
--- /dev/null
+++ b/test/files/pos/spec-arrays.scala
@@ -0,0 +1,214 @@
+abstract class AbsArray[T] {
+  def apply(idx: Int): T
+  def update(idx: Int, elem: T)
+  def length: Int
+  def applyByte(idx: Int): Byte = apply(idx).asInstanceOf[Byte]
+  def updateByte(idx: Int, elem: Byte) = update(idx, elem.asInstanceOf[T])
+  def applyChar(idx: Int): Char = apply(idx).asInstanceOf[Char]
+  def updateChar(idx: Int, elem: Char) = update(idx, elem.asInstanceOf[T])
+  def applyShort(idx: Int): Short = apply(idx).asInstanceOf[Short]
+  def updateShort(idx: Int, elem: Short) = update(idx, elem.asInstanceOf[T])
+  def applyInt(idx: Int): Int = apply(idx).asInstanceOf[Int]
+  def updateInt(idx: Int, elem: Int) = update(idx, elem.asInstanceOf[T])
+  def applyLong(idx: Int): Long = apply(idx).asInstanceOf[Long]
+  def updateLong(idx: Int, elem: Long) = update(idx, elem.asInstanceOf[T])
+  def applyFloat(idx: Int): Float = apply(idx).asInstanceOf[Float]
+  def updateFloat(idx: Int, elem: Float) = update(idx, elem.asInstanceOf[T])
+  def applyDouble(idx: Int): Double = apply(idx).asInstanceOf[Double]
+  def updateDouble(idx: Int, elem: Double) = update(idx, elem.asInstanceOf[T])
+  def applyBoolean(idx: Int): Boolean = apply(idx).asInstanceOf[Boolean]
+  def updateBoolean(idx: Int, elem: Boolean) = update(idx, elem.asInstanceOf[T])
+  def applyObject(idx: Int): Object = apply(idx).asInstanceOf[Object]
+  def updateObject(idx: Int, elem: Object) = update(idx, elem.asInstanceOf[T])
+}  
+
+final class IntArray(arr: Array[Int]) extends AbsArray[Int] {
+  def apply(idx: Int): Int = applyInt(idx)
+  def update(idx: Int, elem: Int) = updateInt(idx, elem)
+  override def applyInt(idx: Int): Int = arr(idx)
+  override def updateInt(idx: Int, elem: Int) = arr(idx) = elem
+  def length: Int = arr.length
+}
+
+final class ArraySeq[T](arr: Array[T]) extends AbsArray[T] {
+  def apply(idx: Int): T = arr(idx)
+  def update(idx: Int, elem: T) = arr(idx) = elem
+  def length: Int = arr.length
+}
+
+class SpecArray[@specialized T](arr: Array[T]) extends AbsArray[T] {
+  def apply(idx: Int): T = arr(idx)
+  def update(idx: Int, elem: T) = arr(idx) = elem
+  def length: Int = arr.length
+}
+
+abstract class Test {
+  def sum(): Int
+  def modify(i: Int)
+  def run() {
+    var s = 0
+    for (i <- 1 to 1000000) {
+      s += sum()
+      modify(i)
+    }
+    println(s)
+  }
+}
+
+class ScalaSpecTest extends Test {
+  val arr = new IntArray(new Array[Int](1000))
+
+  def sum(): Int = {
+    var acc = 0
+    var i = 0
+    while (i < arr.length) { acc = acc + arr.applyInt(i); i += 1 }
+    acc
+  }
+  
+  def modify(j: Int) = {
+    val base = j * 100 % 1000
+    var i = 0
+    while (i < 100) {
+      arr.updateInt(i + base, arr.applyInt(i + base) + 1)
+      i += 1
+    }
+  }
+}
+    
+class ScalaSpec2Test extends Test {
+  val arr: AbsArray[Int] = new IntArray(new Array[Int](1000))
+
+  def sum(): Int = {
+    var acc = 0
+    var i = 0
+    while (i < arr.length) { acc = acc + arr.applyInt(i); i += 1 }
+    acc
+  }
+  
+  def modify(j: Int) = {
+    val base = j * 100 % 1000
+    var i = 0
+    while (i < 100) {
+      arr.updateInt(i + base, arr.applyInt(i + base) + 1)
+      i += 1
+    }
+  }
+}
+    
+class ScalaWrapTest extends Test {
+  val arr: AbsArray[Int] = new ArraySeq(new Array[Int](1000))
+
+  def sum(): Int = {
+    var acc = 0
+    var i = 0
+    while (i < arr.length) { acc = acc + arr.applyInt(i); i += 1 }
+    acc
+  }
+  
+  def modify(j: Int) = {
+    val base = j * 100 % 1000
+    var i = 0
+    while (i < 100) {
+      arr.updateInt(i + base, arr.applyInt(i + base) + 1)
+      i += 1
+    }
+  }
+}
+    
+class ScalaGenTest extends Test {
+  val arr: AbsArray[Integer] = new ArraySeq(new Array[Integer](1000))
+  for (i <- 0 until arr.length) arr(i) = new Integer(0)
+
+  def sum(): Int = {
+    var acc = 0
+    var i = 0
+    while (i < arr.length) { acc = acc + arr.apply(i).intValue; i += 1 }
+    acc
+  }
+  
+  def modify(j: Int) = {
+    val base = j * 100 % 1000
+    var i = 0
+    while (i < 100) {
+      arr.update(i + base, new Integer(arr.apply(i + base).intValue + 1))
+      i += 1
+    }
+  }
+}
+    
+class JavaTest extends Test {
+  val arr = new Array[Int](1000)
+
+  def sum(): Int = {
+    var acc = 0
+    var i = 0
+    while (i < arr.length) { acc = acc + arr(i); i += 1 }
+    acc
+  }
+  
+  def modify(j: Int) = {
+    val base = j * 100 % 1000
+    var i = 0
+    while (i < 100) {
+      arr(i + base) += 1
+      i += 1
+    }
+  }
+}
+
+/** Specialized array test. */
+class ScalaSpec3Test extends Test {
+  val arr: SpecArray[Int] = new SpecArray(new Array[Int](1000))
+
+  def sum(): Int = {
+    var acc = 0
+    var i = 0
+    while (i < arr.length) { acc = acc + arr(i); i += 1 }
+    acc
+  }
+  
+  def modify(j: Int) = {
+    val base = j * 100 % 1000
+    var i = 0
+    while (i < 100) {
+      arr(i + base) = arr(i + base) + 1
+      i += 1
+    }
+  }
+}
+
+object TestJava extends scala.testing.Benchmark {
+  def run() {
+    (new JavaTest).run()
+  }
+}
+
+object TestSpec extends scala.testing.Benchmark {
+  def run() {
+    (new ScalaSpecTest).run()
+  }
+}
+     
+object TestSpec2 extends scala.testing.Benchmark {
+  def run() {
+    (new ScalaSpec2Test).run()
+  }
+}
+     
+object TestGen extends scala.testing.Benchmark {
+  def run() {
+    (new ScalaGenTest).run()
+  }
+}
+     
+object TestWrap extends scala.testing.Benchmark {
+  def run() {
+    (new ScalaWrapTest).run()
+  }
+}
+     
+object TestSpec3 extends scala.testing.Benchmark {
+  def run() {
+    (new ScalaSpec3Test).run()
+  }
+}
diff --git a/test/files/pos/spec-asseenfrom.scala b/test/files/pos/spec-asseenfrom.scala
new file mode 100644
index 0000000..cf20fc5
--- /dev/null
+++ b/test/files/pos/spec-asseenfrom.scala
@@ -0,0 +1,29 @@
+class Automaton[@specialized(Double) W,State] { 
+
+  def finalWeight(s: State): W = error("todo");
+
+  def allStates: Set[State] = error("toodo");
+
+  /**
+   * Returns a map from states to its final weight. may expand all nodes.
+   */
+  def finalStateWeights = Map.empty ++ allStates.map { s => (s,finalWeight(s)) }
+
+  // This works fine:
+  /*
+  def finalStateWeights() = {
+    val it = allStates.iterator;
+    while(it.hasNext) {
+      finalWeight(it.next);
+    }
+  }
+  */
+
+}
+
+abstract class Automaton2[@specialized T1, T2] {
+  def finalWeight(s: T2): T1
+  def allStates: Set[T2]
+
+  def f = allStates map finalWeight
+}
diff --git a/test/files/pos/spec-constr.scala b/test/files/pos/spec-constr.scala
new file mode 100644
index 0000000..e908b65
--- /dev/null
+++ b/test/files/pos/spec-constr.scala
@@ -0,0 +1,7 @@
+class SparseArray2[@specialized(Int) T:ClassManifest](val maxSize: Int, initialLength:Int = 3) {
+  private var data = new Array[T](initialLength);
+  private var index = new Array[Int](initialLength);
+
+  // comment out to compile correctly
+  data.length + 3;
+}
diff --git a/test/files/pos/spec-cyclic.scala b/test/files/pos/spec-cyclic.scala
new file mode 100644
index 0000000..b983caa
--- /dev/null
+++ b/test/files/pos/spec-cyclic.scala
@@ -0,0 +1,33 @@
+trait AbsFun[@specialized -A, @specialized +B] {
+  def apply(x: A): B
+}
+
+trait MyPartialFunction[-A, +B] extends AnyRef with AbsFun[A, B]
+
+trait ColMap[A, +B] extends MyPartialFunction[A, B] /*with Collection[(A, B)] */
+
+trait ColSorted[K,+A] extends ColRanged[K,A] 
+
+trait ColSortedMap[K,+E] extends ColMap[K,E] with ColSorted[K,Tuple2[K,E]] 
+
+trait MutMap[A, B] extends AnyRef
+      with ColMap[A, B]
+
+trait ColRanged[K, +A] //extends Iterable[A] 
+
+trait JclRanged[K,A] extends ColRanged[K,A] //with MutableIterable[A] {
+
+trait JclMap[K,E] extends /*collection.jcl.MutableIterable[Tuple2[K,E]] with*/ MutMap[K,E] 
+
+trait JclSorted[K,A] extends ColSorted[K,A] with JclRanged[K,A]
+
+trait JclSortedMap[K,E] extends ColSortedMap[K,E] with JclMap[K,E] with JclSorted[K,Tuple2[K,E]]
+
+class Foo[A, B] extends JclSortedMap[A, B] {
+  def apply(x: A): B = error("NYI")
+}
+
+class Bar {
+  val x: Foo[Int, Int] = new Foo[Int, Int]
+  x.apply(0)
+}
diff --git a/test/files/pos/spec-doubledef.scala b/test/files/pos/spec-doubledef.scala
new file mode 100644
index 0000000..86b0d85
--- /dev/null
+++ b/test/files/pos/spec-doubledef.scala
@@ -0,0 +1,28 @@
+object Test {
+  def fn[@specialized T, @specialized U](t : T => Int, u : U => Int) : T =
+    null.asInstanceOf[T]
+}
+
+trait A[@specialized(Int) T] {
+  var value: T
+  def getWith[@specialized(Int) Z](f: T => Z) = f(value)
+}
+
+class C extends A[Int] {
+  var value = 10
+  override def getWith[@specialized(Int) Z](f: Int => Z) = f(value)
+}
+
+abstract class B[T, @specialized(scala.Int) U : Manifest, @specialized(scala.Int) V <% Ordered[V]] {
+    val u: U
+    val v: V
+
+    def f(t: T, v2: V): Pair[U, V] = {
+        val m: Array[U] = null
+        if (m.isEmpty) {
+            Pair(u, v)
+        } else {
+            Pair(u, v2)
+        }
+    }
+}
diff --git a/test/files/pos/spec-example1.scala b/test/files/pos/spec-example1.scala
new file mode 100644
index 0000000..870c0ed
--- /dev/null
+++ b/test/files/pos/spec-example1.scala
@@ -0,0 +1,17 @@
+abstract class C[@specialized T](_f: T) {
+  def m(x: T): T
+  def n(x: T): T = x
+
+  val f: T = _f
+/*
+  class Inner[@specialized B] {
+    def foo(x: T): T = x
+  }
+
+  new Inner
+*/
+}
+
+class D extends C[Int](0) {
+  def m(x: Int): Int = x * x
+}
diff --git a/test/files/pos/spec-fields.scala b/test/files/pos/spec-fields.scala
new file mode 100644
index 0000000..26a8c4f
--- /dev/null
+++ b/test/files/pos/spec-fields.scala
@@ -0,0 +1,10 @@
+abstract class Foo[@specialized T: ClassManifest, U <: Ordered[U]](x: T, size: Int) {
+  var y: T
+  var z: T = x
+
+  def initialSize = 16
+  val array = new Array[T](initialSize + size)
+
+  def getZ = z
+  def setZ(zz: T) = z = zz
+}
diff --git a/test/files/pos/spec-foo.scala b/test/files/pos/spec-foo.scala
new file mode 100644
index 0000000..aabe0d5
--- /dev/null
+++ b/test/files/pos/spec-foo.scala
@@ -0,0 +1,4 @@
+class Foo {
+  val xs = List(1, 2)
+  1 :: xs
+}
diff --git a/test/files/pos/spec-funs.scala b/test/files/pos/spec-funs.scala
new file mode 100644
index 0000000..9acc505
--- /dev/null
+++ b/test/files/pos/spec-funs.scala
@@ -0,0 +1,63 @@
+trait AbsFunction1[@specialized -T, @specialized +U] {
+  def apply(x: T): U
+}
+
+final class IntTest {
+
+  val niters = 10000
+
+  def transF(xs: Array[Int], f: AbsFunction1[Int, Int]) = {
+    var i = 0
+    var s = 0
+    while (i < xs.length) {
+      xs(i) = f(xs(i)) + 1
+      i += 1
+    }
+  }
+
+  def run() {
+    val xs = new Array[Int](10000)
+    val f = new AbsFunction1[Int, Int] {
+      def apply(x: Int): Int = x * x
+    }    
+    for (j <- 0 until niters) {
+      transF(xs, f)
+    }
+    var acc = 0
+    for (i <- 0 until xs.length) acc += xs(i)
+    println(acc)
+  }
+}
+
+final class ClosureTest {
+
+  val niters = 10000
+
+  def transF(xs: Array[Int], f: Int => Int) = {
+    var i = 0
+    var s = 0
+    while (i < xs.length) {
+      xs(i) = f.apply(xs(i)) + 1
+      i += 1
+    }
+  }
+
+  def run() {
+    val xs = new Array[Int](10000)
+//    val f = (x: Int) => x * x
+    for (j <- 0 until niters) {
+      transF(xs, x => x * x)
+    }
+    var acc = 0
+    for (i <- 0 until xs.length) acc += xs(i)
+    println(acc)
+  }
+}
+
+object TestInt extends testing.Benchmark {
+  def run() = (new IntTest).run()
+}
+
+object TestClosure extends testing.Benchmark {
+  def run() = (new ClosureTest).run()
+}
diff --git a/test/files/pos/spec-lists.scala b/test/files/pos/spec-lists.scala
new file mode 100644
index 0000000..01416da
--- /dev/null
+++ b/test/files/pos/spec-lists.scala
@@ -0,0 +1,6 @@
+object Main extends Application {
+
+  val xs = 1 :: 2 :: 3 :: 4 :: 5 :: Nil
+
+  println(xs)
+}
diff --git a/test/files/pos/spec-localdefs.scala b/test/files/pos/spec-localdefs.scala
new file mode 100644
index 0000000..2df500e
--- /dev/null
+++ b/test/files/pos/spec-localdefs.scala
@@ -0,0 +1,7 @@
+class Foo[@specialized T] {
+  def foo(x: T) = {
+    class Bar
+    x.asInstanceOf[List[Bar]]
+    x.asInstanceOf[Bar]
+  }
+}
diff --git a/test/files/pos/spec-maps.scala b/test/files/pos/spec-maps.scala
new file mode 100644
index 0000000..fe214c9
--- /dev/null
+++ b/test/files/pos/spec-maps.scala
@@ -0,0 +1,10 @@
+trait Fun1[@specialized +R, @specialized -T] {
+  def apply(x: T): R
+}
+
+object Main {
+  def mapA[@specialized B](xs: Array[B], f: Fun1[B, B]) {
+    for (i <- 0 until xs.length)
+      xs(i) = f(xs(i))
+  }
+}
diff --git a/test/files/pos/spec-multiplectors.scala b/test/files/pos/spec-multiplectors.scala
new file mode 100644
index 0000000..8434a13
--- /dev/null
+++ b/test/files/pos/spec-multiplectors.scala
@@ -0,0 +1,3 @@
+class Spec[@specialized(Int) A]() {
+  def this(n: Int) = this()
+}
diff --git a/test/files/pos/spec-params.scala b/test/files/pos/spec-params.scala
new file mode 100644
index 0000000..f522512
--- /dev/null
+++ b/test/files/pos/spec-params.scala
@@ -0,0 +1,32 @@
+class Foo[@specialized A: ClassManifest] {
+
+  // conflicting in bounds, expect a normalized member calling m
+  // and bridge + implementation in specialized subclasses
+  // and overloads here according to specialization on A
+  def m1[@specialized B <: A](x: B, y: A) =
+    goal(x)
+
+  // conflicting, unsolvable, expect a warning
+  def m2[@specialized B <: String](x: B) = x.concat("a")
+
+  // conflicting in bounds, no mention of other spec members
+  // expect an overload here plus implementation in 
+  // compatible specialized subclasses
+  def m3[@specialized B >: A](x: B) = ()
+
+  // non-conflicting, expect a normalized overload implementation here
+  def m4[@specialized T, U <: Ordered[T]](x: T, y: U) = ()
+
+  // non-conflicting, expect a normalized overload implementation here
+  def m5[@specialized B](x: B) = x
+  
+  // non-conflicting, expect a normalized implementation here
+  // and specialized implementations for all expansions in specialized subclasses
+  def m6[@specialized B](x: B, y: A) = 
+    goal(y)
+
+  def goal(x: A) = {
+    val xs = new Array[A](1)
+    xs(0) = x
+  }
+}
diff --git a/test/files/pos/spec-partially.scala b/test/files/pos/spec-partially.scala
new file mode 100644
index 0000000..90778e4
--- /dev/null
+++ b/test/files/pos/spec-partially.scala
@@ -0,0 +1,5 @@
+/** Test case for partially specialized classes. see #2880. */
+
+class Arc[State, @specialized T](label: T, to: State)
+
+
diff --git a/test/files/pos/spec-partialmap.scala b/test/files/pos/spec-partialmap.scala
new file mode 100644
index 0000000..09684e0
--- /dev/null
+++ b/test/files/pos/spec-partialmap.scala
@@ -0,0 +1,17 @@
+
+// ticket #3378, overloaded specialized variants
+import scala.collection.{Traversable,TraversableLike};
+import scala.collection.generic.CanBuildFrom;
+
+trait PartialMap[@specialized A, at specialized B]
+extends PartialFunction[A,B] with Iterable[(A,B)] {
+
+   // commenting out this declaration gives a different exception.
+  /** Getter for all values for which the given key function returns true. */
+   def apply(f : (A => Boolean)) : Iterator[B] =
+     for ((k,v) <- iterator; if f(k)) yield v;
+
+  // if this is commented, it compiles fine:
+  def apply[This <: Traversable[A], That](keys : TraversableLike[A,This])
+  (implicit bf: CanBuildFrom[This, B, That]) : That = keys.map(apply);
+}
diff --git a/test/files/pos/spec-polymeth.scala b/test/files/pos/spec-polymeth.scala
new file mode 100644
index 0000000..df2f460
--- /dev/null
+++ b/test/files/pos/spec-polymeth.scala
@@ -0,0 +1,8 @@
+abstract class AbsFun[@specialized R] {
+//  def andThen[B](x: B): B
+
+  def compose[A](x: A, y: R): A = {
+    val y: A = x
+    x
+  }
+}
diff --git a/test/files/pos/spec-private.scala b/test/files/pos/spec-private.scala
new file mode 100644
index 0000000..7d53bad
--- /dev/null
+++ b/test/files/pos/spec-private.scala
@@ -0,0 +1,10 @@
+class Foo {
+
+  def foo[@specialized(Int) T](x: T) = new Object {
+    private final val myEdges = List(1, 2 , 3)
+
+    def boo {
+      myEdges
+    }
+  }
+}
diff --git a/test/files/pos/spec-sealed.scala b/test/files/pos/spec-sealed.scala
new file mode 100644
index 0000000..73256ac
--- /dev/null
+++ b/test/files/pos/spec-sealed.scala
@@ -0,0 +1,32 @@
+sealed abstract class MyList[@specialized +A] {
+  def head: A
+  def tail: MyList[A]
+
+  def ::[@specialized B >: A](x: B): MyList[B] = 
+    new Cons[B](x, this)
+}
+
+case object MyNil extends MyList[Nothing] {
+  def head = error("nil")
+  def tail = error("nil")
+}
+
+case class Cons[@specialized a](private val hd: a, tl: MyList[a]) extends MyList[a] {
+  def head = hd
+  def tail = tl
+}
+
+abstract class IntList extends MyList[Int]
+
+object Main extends Application {
+  val xs = 1 :: 2 :: 3 :: MyNil 
+  println(xs)
+}
+
+/*
+final class ConsI(hd1: Int, tl1: MyList[Int]) extends Cons[Int](hd1, tl1) {
+  override val hd = hd1
+  override val tl = tl1
+}
+*/
+//class IntCons(_hd: Int, _tl: MyList[Int]) extends Cons[Int](_hd, _tl)
diff --git a/test/files/pos/spec-short.scala b/test/files/pos/spec-short.scala
new file mode 100644
index 0000000..94a8007
--- /dev/null
+++ b/test/files/pos/spec-short.scala
@@ -0,0 +1,26 @@
+abstract class AbsFun[@specialized T, @specialized U] {
+  // abstract function, fully specialized
+  def apply(x: T): U
+
+  // abstract function, specialized
+  def sum(xs: List[T]): Int
+
+  def prod(xs: List[T], mul: (Int, T) => Int): Int = 
+    (1 /: xs)(mul)
+
+  // concrete function, not specialized
+  def bar(m: String): String = m
+
+  // abstract function, not specialized
+  def abs(m: Int): Int
+}
+
+class Square extends AbsFun[Int, Int] {
+  def apply(x: Int): Int = x * x
+
+  def sum(xs: List[Int]): Int = 
+    (0 /: xs) (_ + _)
+
+  def abs(m: Int): Int = 
+    sum(List(1, 2, 3))
+}
diff --git a/test/files/pos/spec-simple.scala b/test/files/pos/spec-simple.scala
new file mode 100644
index 0000000..66a48d1
--- /dev/null
+++ b/test/files/pos/spec-simple.scala
@@ -0,0 +1,51 @@
+class Foo[@specialized T] {
+  var v: T = _
+
+  def foo(x: T): T = x
+
+  println("abc")
+
+  class Bar[@specialized U] {
+    def bar(x: U): T = v
+//    def barInt(x: Int): T = bar(x.asInstanceOf[U])
+  }
+}
+
+class Test {
+  def test {
+    val a = new Foo[Int]
+    val b = new a.Bar[Int]
+    a.foo(10)
+    b.bar(11)
+  }
+}
+
+/*
+abstract class Foo[@specialized T] {
+  def foo(x: T): T
+  def foo$Int(x: Int): Int
+
+  abstract class Bar[@specialized U] {
+    def bar(x: U): T
+    def bar$Int(x: Int): T
+  }
+  abstract class Bar$Int extends Bar[Int] {
+    def bar(x: Int): T = bar$Int(x)
+    def bar$Int(x: Int): T
+  }
+}
+
+abstract class Foo$Int extends Foo[Int] {
+  def foo(x: Int): Int = foo$Int(x)
+  def foo$Int(x: Int): Int
+
+  abstract class Bar[@specialized U] {
+    def bar(x: U): Int
+    def bar$Int(x: Int): Int
+  }
+  abstract class Bar$Int extends Bar[Int] {
+    def bar(x: Int): Int = bar$Int(x)
+    def bar$Int(x: Int): Int
+  }
+}
+*/
diff --git a/test/files/pos/spec-sparsearray.scala b/test/files/pos/spec-sparsearray.scala
new file mode 100644
index 0000000..ea7710a
--- /dev/null
+++ b/test/files/pos/spec-sparsearray.scala
@@ -0,0 +1,24 @@
+import scala.collection.mutable.MapLike
+
+class SparseArray[@specialized(Int) T:ClassManifest] extends collection.mutable.Map[Int,T] with collection.mutable.MapLike[Int,T,SparseArray[T]] {
+  override def get(x: Int) = {
+    val ind = findOffset(x)
+    if(ind < 0) None else Some(error("ignore"))
+  }
+
+  /**
+   * Returns the offset into index and data for the requested vector
+   * index.  If the requested index is not found, the return value is
+   * negative and can be converted into an insertion point with -(rv+1).
+   */
+  private def findOffset(i : Int) : Int = {
+    error("impl doesn't matter")
+  }
+
+  override def apply(i : Int) : T = { error("ignore") }
+  override def update(i : Int, value : T) = error("ignore")
+  override def empty = new SparseArray[T]
+  def -=(ind: Int) = error("ignore")
+  def +=(kv: (Int,T)) = error("ignore")
+  override final def iterator = error("ignore")
+}
diff --git a/test/files/pos/spec-super.scala b/test/files/pos/spec-super.scala
new file mode 100644
index 0000000..67179e0
--- /dev/null
+++ b/test/files/pos/spec-super.scala
@@ -0,0 +1,20 @@
+import scala.collection.immutable._
+import scala.collection.mutable.ListBuffer
+import scala.collection.generic._
+
+trait Base[+A] extends Traversable[A] {
+  def add[B >: A, That](that: Traversable[B])(implicit bf: CanBuildFrom[Base[A], B, That]): That = {
+    val b = bf(this)
+    b ++= this
+    b ++= that
+    b.result
+  }
+
+}
+
+abstract class Derived[@specialized +A] extends Base[A] {
+  override def add[B >: A, That](that: Traversable[B])(implicit bf: CanBuildFrom[Base[A], B, That]): That = {
+    val b = bf(this)
+    super.add[B, That](that)
+  }
+}
diff --git a/test/files/pos/spec-t3497.scala b/test/files/pos/spec-t3497.scala
new file mode 100644
index 0000000..6cc0e24
--- /dev/null
+++ b/test/files/pos/spec-t3497.scala
@@ -0,0 +1,16 @@
+abstract class A[T, @specialized U] {
+    def score(state: T): U
+}
+
+object B extends A[ Array[Byte], Int ] {
+  def score(state: Array[Byte]): Int = {
+    var index = 0
+    while (index < state.length) { // (index < 2) leads to the #2755 NullPointerException
+      if (state(index) == 0) {
+        return -1
+      }
+    }
+    
+    return 0
+  }
+}
diff --git a/test/files/pos/spec-tailcall.scala b/test/files/pos/spec-tailcall.scala
new file mode 100644
index 0000000..d91e2f5
--- /dev/null
+++ b/test/files/pos/spec-tailcall.scala
@@ -0,0 +1,17 @@
+class TailCall[@specialized T] {
+  final def dropLeft(n: Int, xs: List[T]): List[T] = 
+    if (n == 0) xs
+    else dropLeft(n - 1, xs.tail)
+/*
+  def filter(pf: PartialFunction[Option[String], Boolean]) = null
+
+  def crash(o: Option[String]) = filter {
+    case None if {
+      def dropLeft[T](n: Int, xs: List[T]): List[T] = 
+        if (n == 0) xs
+        else dropLeft(n - 1, xs.tail)
+      dropLeft(2, List(1, 2, 3)).isEmpty
+    } => true
+  }
+*/
+}
diff --git a/test/files/pos/spec-thistype.scala b/test/files/pos/spec-thistype.scala
new file mode 100644
index 0000000..52b2bf3
--- /dev/null
+++ b/test/files/pos/spec-thistype.scala
@@ -0,0 +1,3 @@
+class Foo[@specialized A] {
+  def bar(xs: List[A]): this.type = this
+}
diff --git a/test/files/pos/spec-vector.scala b/test/files/pos/spec-vector.scala
new file mode 100644
index 0000000..06e49b5
--- /dev/null
+++ b/test/files/pos/spec-vector.scala
@@ -0,0 +1,4 @@
+// ticket #3379, abstract overrides
+trait Vector extends (Int=>Double) {
+  override def apply(i: Int): Double  
+}
diff --git a/test/files/pos/strings.scala b/test/files/pos/strings.scala
index 3bf40e3..83b8179 100644
--- a/test/files/pos/strings.scala
+++ b/test/files/pos/strings.scala
@@ -4,3 +4,7 @@ object test {
   def f() = "hello".concat("world");
 
 }
+// #1000
+object A {
+  println("""This a "raw" string ending with a "double quote"""") 
+}
diff --git a/test/files/pos/sudoku.scala b/test/files/pos/sudoku.scala
index bee4097..be05665 100644
--- a/test/files/pos/sudoku.scala
+++ b/test/files/pos/sudoku.scala
@@ -2,7 +2,7 @@ object SudokuSolver extends Application {
   // The board is represented by an array of strings (arrays of chars),
   // held in a global variable m. The program begins by reading 9 lines
   // of input to fill the board
-  var m: Array[Array[Char]] = List.tabulate(9, (x: Int) => readLine.toArray).toArray
+  var m: Array[Array[Char]] = Array.tabulate(9)((x: Int) => readLine.toArray)
  
   // For printing m, a method print is defined
   def print = { println(""); m map (carr => println(new String(carr))) }
diff --git a/test/files/pos/super.cmds b/test/files/pos/super.cmds
new file mode 100644
index 0000000..8f3f8a4
--- /dev/null
+++ b/test/files/pos/super.cmds
@@ -0,0 +1,2 @@
+javac Super_1.java
+scalac Super_2.scala
diff --git a/test/files/pos/super/Super_1.java b/test/files/pos/super/Super_1.java
new file mode 100644
index 0000000..418ae96
--- /dev/null
+++ b/test/files/pos/super/Super_1.java
@@ -0,0 +1,6 @@
+// A.java
+interface Inter<T> { }
+
+class Super implements Inter<Super.Inner> {  
+  public class Inner { };
+}
diff --git a/test/files/pos/super/Super_2.scala b/test/files/pos/super/Super_2.scala
new file mode 100644
index 0000000..862e55a
--- /dev/null
+++ b/test/files/pos/super/Super_2.scala
@@ -0,0 +1,6 @@
+object Test {
+  val x: Super = null
+
+  def main(args: Array[String]) {
+  }
+}
diff --git a/test/files/pos/switchUnbox.flags b/test/files/pos/switchUnbox.flags
new file mode 100644
index 0000000..cdf5f84
--- /dev/null
+++ b/test/files/pos/switchUnbox.flags
@@ -0,0 +1 @@
+-Ysqueeze:on
diff --git a/test/files/pos/switchUnbox.scala b/test/files/pos/switchUnbox.scala
new file mode 100644
index 0000000..b8942e2
--- /dev/null
+++ b/test/files/pos/switchUnbox.scala
@@ -0,0 +1,11 @@
+// this test has accompanying .flags file 
+//  that contains -Xsqueeze:on
+// 
+object Foo {
+  var xyz: (Int, String) = (1, "abc")
+  xyz._1 match {
+    case 1 => Console.println("OK")
+    case 2 => Console.println("OK")
+    case _ => Console.println("KO")
+  }
+}
diff --git a/test/files/pos/t0165.scala b/test/files/pos/t0165.scala
index 05c4a1c..76aef85 100644
--- a/test/files/pos/t0165.scala
+++ b/test/files/pos/t0165.scala
@@ -1,5 +1,5 @@
 package test3
-import scala.collection.jcl.LinkedHashMap
+import scala.collection.mutable.LinkedHashMap
 
 trait Main {
   def asMany : ArrayResult = {
diff --git a/test/files/pos/t0586.scala b/test/files/pos/t0586.scala
index 86115a7..540e225 100644
--- a/test/files/pos/t0586.scala
+++ b/test/files/pos/t0586.scala
@@ -6,4 +6,4 @@ object RClose {
     } finally {
       s.close()
     }
-}
\ No newline at end of file
+}
diff --git a/test/files/pos/t0591.scala b/test/files/pos/t0591.scala
index de02d6b..15f2dba 100644
--- a/test/files/pos/t0591.scala
+++ b/test/files/pos/t0591.scala
@@ -4,4 +4,4 @@ object Test {
   implicit val hello = "Hello"
   implicitly[String]
   implicitly[Option[String]]
-}
\ No newline at end of file
+}
diff --git a/test/files/pos/t0612/C.scala b/test/files/pos/t0612/C.scala
new file mode 100644
index 0000000..1f260a5
--- /dev/null
+++ b/test/files/pos/t0612/C.scala
@@ -0,0 +1,6 @@
+package test
+package app
+
+class C {
+  Ob.f
+}
diff --git a/test/pending/pos/t0612/Ob.scala b/test/files/pos/t0612/Ob.scala
similarity index 100%
rename from test/pending/pos/t0612/Ob.scala
rename to test/files/pos/t0612/Ob.scala
diff --git a/test/files/pos/t0674.scala b/test/files/pos/t0674.scala
index 2bd9d9a..6884d84 100644
--- a/test/files/pos/t0674.scala
+++ b/test/files/pos/t0674.scala
@@ -39,9 +39,10 @@ for(a <- Some(1);
     l <- Some(12);
     m <- Some(13);
     n <- Some(14);
-    o <- Some(15);
-    p <- Some(16);
-    q <- Some(17);
-    r <- Some(18);
-    s <- Some(19)) yield a)
+    o <- Some(15)
+//    p <- Some(16);
+//    q <- Some(17)
+//    r <- Some(18);
+//    s <- Some(19)
+   ) yield a)
 }
diff --git a/test/files/pos5/t0695/JavaClass.java b/test/files/pos/t0695/JavaClass.java
similarity index 100%
rename from test/files/pos5/t0695/JavaClass.java
rename to test/files/pos/t0695/JavaClass.java
diff --git a/test/files/pos5/t0695/Test.scala b/test/files/pos/t0695/Test.scala
similarity index 100%
rename from test/files/pos5/t0695/Test.scala
rename to test/files/pos/t0695/Test.scala
diff --git a/test/files/pos/t0710.scala b/test/files/pos/t0710.scala
index 4512a10..fb440bc 100644
--- a/test/files/pos/t0710.scala
+++ b/test/files/pos/t0710.scala
@@ -1,6 +1,6 @@
 object t0710 {
   def method {
-    sealed case class Parent
+    sealed class Parent
     case object Child extends Parent
     val x: Parent = Child
     x match {
diff --git a/test/files/pos/t0816.scala b/test/files/pos/t0816.scala
new file mode 100644
index 0000000..738a634
--- /dev/null
+++ b/test/files/pos/t0816.scala
@@ -0,0 +1,12 @@
+abstract class Atest(val data: String)
+
+case class Btest(override val data: String, val b: Boolean) extends Atest(data)
+
+case class Ctest(override val data: String) extends Btest(data, true)
+
+class testCaseClass {
+  def test(x: Atest) = x match {
+    case Ctest(data) => Console.println("C")  
+    case Btest(data, b) => Console.println("B")
+  }
+}
diff --git a/test/files/pos/t0851.scala b/test/files/pos/t0851.scala
deleted file mode 100644
index fc7109d..0000000
--- a/test/files/pos/t0851.scala
+++ /dev/null
@@ -1,14 +0,0 @@
-package test
-
-object test1 {
-  case class Foo[T,T2](f : (T,T2) => String) extends (((T,T2)) => String){
-    def apply(t : T) = (s:T2) => f(t,s)
-    def apply(p : (T,T2)) = f(p._1,p._2)
-  }
-  implicit def g[T](f : (T,String) => String) = Foo(f)
-  def main(args : Array[String]) : Unit = {
-    val f = (x:Int,s:String) => s + x
-    println(f(1))
-    ()
-  }
-}
diff --git a/test/files/pos/t0872.scala b/test/files/pos/t0872.scala
deleted file mode 100644
index 6dc0249..0000000
--- a/test/files/pos/t0872.scala
+++ /dev/null
@@ -1,8 +0,0 @@
-object Main {
-  def main(args : Array[String]) {
-    val fn = (a : Int, str : String) => "a: " + a + ", str: " + str
-    implicit def fx[T](f : (T,String) => String) = (x:T) => f(x,null)
-    println(fn(1))
-    ()  
-  }
-}
diff --git a/test/files/pos/t0971.java b/test/files/pos/t0971.java
deleted file mode 100644
index 5db2200..0000000
--- a/test/files/pos/t0971.java
+++ /dev/null
@@ -1,4 +0,0 @@
-class A { 
-    int y = 1, z;
-    static Object x = new java.util.HashMap<Object , Object > () ;
-}
\ No newline at end of file
diff --git a/test/files/pos/t0999.scala b/test/files/pos/t0999.scala
deleted file mode 100644
index c384820..0000000
--- a/test/files/pos/t0999.scala
+++ /dev/null
@@ -1,5 +0,0 @@
-object A {
-  val d: Double = Math.sqrt(5 match {
-    case x: Double => x
-  })
-}
diff --git a/test/pending/pos/t1000.scala b/test/files/pos/t1000.scala
similarity index 100%
rename from test/pending/pos/t1000.scala
rename to test/files/pos/t1000.scala
diff --git a/test/files/pos/t1029.cmds b/test/files/pos/t1029.cmds
new file mode 100644
index 0000000..06b863d
--- /dev/null
+++ b/test/files/pos/t1029.cmds
@@ -0,0 +1,2 @@
+scalac Test_1.scala
+scalac Test_2.scala
diff --git a/test/files/pos/t1029/Test_1.scala b/test/files/pos/t1029/Test_1.scala
new file mode 100644
index 0000000..e828087
--- /dev/null
+++ b/test/files/pos/t1029/Test_1.scala
@@ -0,0 +1,7 @@
+class ann(a: Array[Int]) extends StaticAnnotation
+
+object Test1 {
+  // bug #1029
+  @ann(Array(10, 2)) def u = ()
+  val v: String @ann(Array(13, 2)) = "-1"
+}
diff --git a/test/files/pos/t1029/Test_2.scala b/test/files/pos/t1029/Test_2.scala
new file mode 100644
index 0000000..0058905
--- /dev/null
+++ b/test/files/pos/t1029/Test_2.scala
@@ -0,0 +1,3 @@
+object Test {
+  val t = Test1
+}
diff --git a/test/files/pos/t1035.scala b/test/files/pos/t1035.scala
new file mode 100644
index 0000000..5c8670a
--- /dev/null
+++ b/test/files/pos/t1035.scala
@@ -0,0 +1,32 @@
+//A fatal error or Scala compiler
+// Scala compiler version 2.7.1-final -- (c) 2002-2010 LAMP/EPFL
+// Carlos Loria cloria at artinsoft.com
+// 7/10/2008
+
+class A  {
+  var name:String = _
+  def getName() = name
+  def this(name:String, age:Int){this();this.name=name}
+  
+}
+
+class B(name:String) extends A(name,0){
+}
+
+class D {
+
+   object A {
+     def unapply(p:A) = Some(p.getName)
+   }
+   
+   object B {
+     def unapply(p:B) = Some(p.getName)
+   }
+   def foo(p:Any) = p match {
+      case B(n)    => println("B") 
+      case A(n)    => println("A")  
+      
+        
+   }
+
+}
diff --git a/test/files/pos/t1049.scala b/test/files/pos/t1049.scala
deleted file mode 100644
index dad8357..0000000
--- a/test/files/pos/t1049.scala
+++ /dev/null
@@ -1,9 +0,0 @@
-class J {
-    type tttt[a, b] <: _root_.scala.collection.mutable.Map[a, b]
-
-    def r(a : tttt[String, String]) = {
-        0 match {
-            case a : a.MapTo =>
-        }
-    }
-}
diff --git a/test/pending/pos/t1053.scala b/test/files/pos/t1053.scala
similarity index 100%
rename from test/pending/pos/t1053.scala
rename to test/files/pos/t1053.scala
diff --git a/test/files/pos/t1087.scala b/test/files/pos/t1087.scala
deleted file mode 100644
index bb0d701..0000000
--- a/test/files/pos/t1087.scala
+++ /dev/null
@@ -1,3 +0,0 @@
-case class Foo
-case class Prd (pred : Char => Boolean) extends Foo
-
diff --git a/test/files/pos5/t1101/J.java b/test/files/pos/t1101/J.java
similarity index 100%
rename from test/files/pos5/t1101/J.java
rename to test/files/pos/t1101/J.java
diff --git a/test/files/pos5/t1101/S.scala b/test/files/pos/t1101/S.scala
similarity index 100%
rename from test/files/pos5/t1101/S.scala
rename to test/files/pos/t1101/S.scala
diff --git a/test/files/pos5/t1102/J.java b/test/files/pos/t1102/J.java
similarity index 100%
rename from test/files/pos5/t1102/J.java
rename to test/files/pos/t1102/J.java
diff --git a/test/files/pos5/t1102/S.scala b/test/files/pos/t1102/S.scala
similarity index 100%
rename from test/files/pos5/t1102/S.scala
rename to test/files/pos/t1102/S.scala
diff --git a/test/files/pos/t1107/O.scala b/test/files/pos/t1107/O.scala
new file mode 100644
index 0000000..aa605a6
--- /dev/null
+++ b/test/files/pos/t1107/O.scala
@@ -0,0 +1,13 @@
+object O
+{
+  def d(t: Top) = t match {
+    case s: Sub => true
+    case _ => false
+  }
+  
+  def main(args: Array[String]): Unit = {
+    val c = new AnyRef with C
+
+    c.bob.toString + c.bob2.toString
+  }  
+}
diff --git a/test/files/pos/t1107/T.scala b/test/files/pos/t1107/T.scala
new file mode 100644
index 0000000..1f3712d
--- /dev/null
+++ b/test/files/pos/t1107/T.scala
@@ -0,0 +1,7 @@
+sealed trait Top
+sealed trait Sub extends Top
+trait C { 
+  private object P extends Sub
+  def bob() = P.getClass
+  def bob2() = O.d(P)
+}
diff --git a/test/files/pos/t1147.scala b/test/files/pos/t1147.scala
index e320571..d4b3967 100644
--- a/test/files/pos/t1147.scala
+++ b/test/files/pos/t1147.scala
@@ -1,5 +1,5 @@
 class App(arg: String) {
-  @deprecated def this() {
+  @deprecated("..") def this() {
     this("foo")
   }
 }
diff --git a/test/files/pos5/t1150/J.java b/test/files/pos/t1150/J.java
similarity index 100%
rename from test/files/pos5/t1150/J.java
rename to test/files/pos/t1150/J.java
diff --git a/test/files/pos5/t1150/S.scala b/test/files/pos/t1150/S.scala
similarity index 100%
rename from test/files/pos5/t1150/S.scala
rename to test/files/pos/t1150/S.scala
diff --git a/test/files/pos5/t1152/J.java b/test/files/pos/t1152/J.java
similarity index 100%
rename from test/files/pos5/t1152/J.java
rename to test/files/pos/t1152/J.java
diff --git a/test/files/pos5/t1152/S.scala b/test/files/pos/t1152/S.scala
similarity index 100%
rename from test/files/pos5/t1152/S.scala
rename to test/files/pos/t1152/S.scala
diff --git a/test/files/pos/t1164.scala b/test/files/pos/t1164.scala
new file mode 100644
index 0000000..307ca92
--- /dev/null
+++ b/test/files/pos/t1164.scala
@@ -0,0 +1,29 @@
+
+
+object test {  		
+
+	class Foo[a](val arg : a) 
+
+	object Foo  { 
+	def apply [a](arg : a, right :a) = new Foo[a](arg) 
+	def unapply [a](m : Foo[a]) = Some (m.arg) 
+	} 
+	
+	def matchAndGetArgFromFoo[a]( e:Foo[a]):a = {e match { case Foo(x) => x }}
+	
+	
+	//  Try the same thing as above but use function as argument to Bar
+	// constructor
+	
+	type FunIntToA [a] = (Int) => a
+	class Bar[a] (var f: FunIntToA[a]) 
+	
+	object Bar {
+		def apply[a](f: FunIntToA[a]) = new Bar[a](f)
+		def unapply[a](m: Bar[a]) = Some (m.f)
+	}
+	
+	def matchAndGetFunFromBar[a](b:Bar[a]) : FunIntToA[a] = { b match { case Bar(x) => x}}
+	 
+
+}
diff --git a/test/files/pos5/t1176/J.java b/test/files/pos/t1176/J.java
similarity index 100%
rename from test/files/pos5/t1176/J.java
rename to test/files/pos/t1176/J.java
diff --git a/test/files/pos5/t1176/S.scala b/test/files/pos/t1176/S.scala
similarity index 100%
rename from test/files/pos5/t1176/S.scala
rename to test/files/pos/t1176/S.scala
diff --git a/test/files/pos/t1186/t1186.java b/test/files/pos/t1186/t1186.java
new file mode 100644
index 0000000..5f26076
--- /dev/null
+++ b/test/files/pos/t1186/t1186.java
@@ -0,0 +1,8 @@
+import scala.collection.immutable.Map;
+
+class Test {
+
+  void foo() {
+      Map<String, String> map = null;
+  }
+}
diff --git a/test/files/pos5/t1196/J.java b/test/files/pos/t1196/J.java
similarity index 100%
rename from test/files/pos5/t1196/J.java
rename to test/files/pos/t1196/J.java
diff --git a/test/files/pos5/t1196/S.scala b/test/files/pos/t1196/S.scala
similarity index 100%
rename from test/files/pos5/t1196/S.scala
rename to test/files/pos/t1196/S.scala
diff --git a/test/files/pos5/t1197/J.java b/test/files/pos/t1197/J.java
similarity index 100%
rename from test/files/pos5/t1197/J.java
rename to test/files/pos/t1197/J.java
diff --git a/test/files/pos5/t1197/S.scala b/test/files/pos/t1197/S.scala
similarity index 100%
rename from test/files/pos5/t1197/S.scala
rename to test/files/pos/t1197/S.scala
diff --git a/test/files/pos5/t1203/J.java b/test/files/pos/t1203/J.java
similarity index 100%
rename from test/files/pos5/t1203/J.java
rename to test/files/pos/t1203/J.java
diff --git a/test/files/pos5/t1203/S.scala b/test/files/pos/t1203/S.scala
similarity index 100%
rename from test/files/pos5/t1203/S.scala
rename to test/files/pos/t1203/S.scala
diff --git a/test/files/pos/t1226.scala b/test/files/pos/t1226.scala
new file mode 100644
index 0000000..0af21cb
--- /dev/null
+++ b/test/files/pos/t1226.scala
@@ -0,0 +1,8 @@
+package graphs;
+
+abstract class Graph (private[graphs] val mappings : Any){
+}
+
+class Nodes (mappings : Any)  extends Graph(mappings) {
+  mappings.toString;
+}
diff --git a/test/files/pos/t1230/J.java b/test/files/pos/t1230/J.java
new file mode 100644
index 0000000..35aefd2
--- /dev/null
+++ b/test/files/pos/t1230/J.java
@@ -0,0 +1 @@
+class J { public int foo ; }
diff --git a/test/files/pos/t1230/S.scala b/test/files/pos/t1230/S.scala
new file mode 100644
index 0000000..f8a691b
--- /dev/null
+++ b/test/files/pos/t1230/S.scala
@@ -0,0 +1 @@
+object S extends Application { (new J).foo = 5 }
diff --git a/test/files/pos/t1231/J.java b/test/files/pos/t1231/J.java
new file mode 100644
index 0000000..6b24205
--- /dev/null
+++ b/test/files/pos/t1231/J.java
@@ -0,0 +1 @@
+enum J { j1 }
diff --git a/test/files/pos/t1231/S.scala b/test/files/pos/t1231/S.scala
new file mode 100644
index 0000000..ee08866
--- /dev/null
+++ b/test/files/pos/t1231/S.scala
@@ -0,0 +1 @@
+object S extends Application { println(J.j1) }
diff --git a/test/files/pos/t1232/J.java b/test/files/pos/t1232/J.java
new file mode 100644
index 0000000..2d9e3bb
--- /dev/null
+++ b/test/files/pos/t1232/J.java
@@ -0,0 +1,2 @@
+package j;
+public class J { public enum E { e1 } }
diff --git a/test/files/pos/t1232/J2.java b/test/files/pos/t1232/J2.java
new file mode 100644
index 0000000..2923778
--- /dev/null
+++ b/test/files/pos/t1232/J2.java
@@ -0,0 +1,2 @@
+import s.S;
+class J2 { }
diff --git a/test/files/pos/t1232/S.scala b/test/files/pos/t1232/S.scala
new file mode 100644
index 0000000..1b6bca7
--- /dev/null
+++ b/test/files/pos/t1232/S.scala
@@ -0,0 +1,2 @@
+package s
+class S { j.J.E.e1 }
diff --git a/test/files/pos5/t1235/Test.java b/test/files/pos/t1235/Test.java
similarity index 100%
rename from test/files/pos5/t1235/Test.java
rename to test/files/pos/t1235/Test.java
diff --git a/test/files/pos/t1236.scala b/test/files/pos/t1236.scala
new file mode 100644
index 0000000..7028162
--- /dev/null
+++ b/test/files/pos/t1236.scala
@@ -0,0 +1,14 @@
+trait Empty[E[_]] {
+  def e[A]: E[A] 
+}
+
+object T {
+  val ListEmpty = new Empty[List] {
+    def e[A] = Nil
+  }
+
+  def foo[F[_]](q:(String,String)) = "hello"
+  def foo[F[_]](e: Empty[F]) = "world"
+
+  val x = foo[List](ListEmpty)
+}
\ No newline at end of file
diff --git a/test/files/pos/t1254/t1254.java b/test/files/pos/t1254/t1254.java
new file mode 100644
index 0000000..17dc391
--- /dev/null
+++ b/test/files/pos/t1254/t1254.java
@@ -0,0 +1,28 @@
+/* Taken from ticket #1254. Tests Java signatures in mirror classes and that
+   Nothing is translated to Nothing$.
+*/
+
+import scala.None;
+
+// This compiles with javac but fails with Eclipse java compiler:
+// 'The type scala.Nothing cannot be resolved. It is indirectly referenced from required .class files'
+class NothingBug3 {
+    public NothingBug3() {
+	scala.Option<?> o = scala.None$.MODULE$;
+
+        test(o);
+        None.toLeft(new scala.runtime.AbstractFunction0<Integer>() { 
+                public Integer apply() { return 0; }
+            });
+    }
+
+    public <T>void test(scala.Option<T> f) {}
+}
+
+// This compiles with javac but fails with Eclipse java compiler:
+// 'The type scala.Nothing cannot be resolved. It is indirectly referenced from required .class files'
+class NothingBug4 {
+    public NothingBug4() {
+	scala.Option o = scala.None$.MODULE$;
+    }
+}
diff --git a/test/files/pos/t1260.scala b/test/files/pos/t1260.scala
new file mode 100644
index 0000000..9cd860a
--- /dev/null
+++ b/test/files/pos/t1260.scala
@@ -0,0 +1,18 @@
+case class Foo(a: String, b: String)
+
+object Bar {
+  def unapply(s: String): Option[Long] =
+    try { Some(s.toLong) } catch { case _ => None }
+}
+
+object Test {
+  def main(args: Array[String]) {
+    val f = Foo("1", "2")
+    f match {
+      case Foo(Bar(1), Bar(2)) => 1
+      case Foo(Bar(i), Bar(j)) if i >= 0 => 2
+      case _ => 3
+    }
+  }
+}
+
diff --git a/test/files/pos5/t1263/Test.java b/test/files/pos/t1263/Test.java
similarity index 100%
rename from test/files/pos5/t1263/Test.java
rename to test/files/pos/t1263/Test.java
diff --git a/test/files/pos5/t1263/test.scala b/test/files/pos/t1263/test.scala
similarity index 100%
rename from test/files/pos5/t1263/test.scala
rename to test/files/pos/t1263/test.scala
diff --git a/test/files/pos/t1380.flags b/test/files/pos/t1380.flags
deleted file mode 100644
index f0b0ef7..0000000
--- a/test/files/pos/t1380.flags
+++ /dev/null
@@ -1 +0,0 @@
--cp pending/pos/t1380/gnujaxp.jar
diff --git a/test/pending/pos/t1409/AbstractImpl.java b/test/files/pos/t1409/AbstractImpl.java
similarity index 100%
rename from test/pending/pos/t1409/AbstractImpl.java
rename to test/files/pos/t1409/AbstractImpl.java
diff --git a/test/pending/pos/t1409/ConcreteImpl.scala b/test/files/pos/t1409/ConcreteImpl.scala
similarity index 100%
rename from test/pending/pos/t1409/ConcreteImpl.scala
rename to test/files/pos/t1409/ConcreteImpl.scala
diff --git a/test/pending/pos/t1409/OuterInterface.java b/test/files/pos/t1409/OuterInterface.java
similarity index 100%
rename from test/pending/pos/t1409/OuterInterface.java
rename to test/files/pos/t1409/OuterInterface.java
diff --git a/test/files/pos/t1422.scala b/test/files/pos/t1422.scala
new file mode 100644
index 0000000..658f5c7
--- /dev/null
+++ b/test/files/pos/t1422.scala
@@ -0,0 +1,2 @@
+case class A(private val foo:String)
+case class B(protected[this] val foo:String)
diff --git a/test/pending/pos/t1438.scala b/test/files/pos/t1438.scala
similarity index 100%
rename from test/pending/pos/t1438.scala
rename to test/files/pos/t1438.scala
diff --git a/test/pending/pos/t1439.scala b/test/files/pos/t1439.scala
similarity index 100%
rename from test/pending/pos/t1439.scala
rename to test/files/pos/t1439.scala
diff --git a/test/files/pos/t1459/AbstractBase.java b/test/files/pos/t1459/AbstractBase.java
new file mode 100644
index 0000000..4924194
--- /dev/null
+++ b/test/files/pos/t1459/AbstractBase.java
@@ -0,0 +1,5 @@
+package base;
+
+public abstract class AbstractBase {
+    public abstract void doStuff(String... params); // !!! was Object..
+}
\ No newline at end of file
diff --git a/test/files/pos/t1459/App.scala b/test/files/pos/t1459/App.scala
new file mode 100644
index 0000000..1152fcb
--- /dev/null
+++ b/test/files/pos/t1459/App.scala
@@ -0,0 +1,18 @@
+package foo
+import base._
+
+object App extends Application {
+  class Concrete extends AbstractBase {
+     override def doStuff(params:java.lang.String*): Unit = println("doStuff invoked")
+  }
+
+  val impl = new Concrete
+
+  //succeeds
+  impl.doStuff(null)
+
+  val caller = new Caller
+  
+  // fails with AbstractMethodError
+  caller.callDoStuff(impl)
+}
diff --git a/test/files/pos/t1459/Caller.java b/test/files/pos/t1459/Caller.java
new file mode 100644
index 0000000..4ae51d8
--- /dev/null
+++ b/test/files/pos/t1459/Caller.java
@@ -0,0 +1,7 @@
+package base;
+
+public class Caller {
+   public void callDoStuff(AbstractBase impl) {
+       impl.doStuff("abc"); // was new Object());
+   }
+}
\ No newline at end of file
diff --git a/test/files/pos/t1545.scala b/test/files/pos/t1545.scala
new file mode 100644
index 0000000..d52cfa1
--- /dev/null
+++ b/test/files/pos/t1545.scala
@@ -0,0 +1,16 @@
+object Main extends Application {
+
+    case class Foo (field : Option[String])
+
+    val x : PartialFunction[Foo,Int] =
+        {
+            c => c.field match {
+                case Some (s) => 42
+                case None     => 99
+            }
+        }
+        
+    println (x (Foo (None))) // prints 99
+    println (x (Foo (Some ("foo")))) // prints 42
+        
+}
diff --git a/test/files/pos/t1560.scala b/test/files/pos/t1560.scala
new file mode 100644
index 0000000..c1d8a81
--- /dev/null
+++ b/test/files/pos/t1560.scala
@@ -0,0 +1,13 @@
+object Test extends Application {
+  
+  trait C[T] {
+    def t: T
+  }
+  
+  def b: Option[C[x] forSome { type x }] = null
+  
+  def c = b match {
+    case Some(b) => b.t
+  }
+  
+}
diff --git a/test/files/pos/t1569.flags b/test/files/pos/t1569.flags
new file mode 100644
index 0000000..1c26b24
--- /dev/null
+++ b/test/files/pos/t1569.flags
@@ -0,0 +1 @@
+-Ydependent-method-types
\ No newline at end of file
diff --git a/test/files/pos/t1569.scala b/test/files/pos/t1569.scala
new file mode 100644
index 0000000..e5f9553
--- /dev/null
+++ b/test/files/pos/t1569.scala
@@ -0,0 +1,5 @@
+object Bug {
+  class C { type T }
+  def foo(x: Int)(y: C)(z: y.T) {}
+  foo(3)(new C { type T = String })("hello")
+}
\ No newline at end of file
diff --git a/test/files/pos/t1614/bar.scala b/test/files/pos/t1614/bar.scala
new file mode 100644
index 0000000..be994c3
--- /dev/null
+++ b/test/files/pos/t1614/bar.scala
@@ -0,0 +1,4 @@
+// bar.scala
+object Bar {
+    val a = new FooImpl with AbstractOverrideFoo
+}
diff --git a/test/files/pos/t1614/foo.scala b/test/files/pos/t1614/foo.scala
new file mode 100644
index 0000000..e6cc41b
--- /dev/null
+++ b/test/files/pos/t1614/foo.scala
@@ -0,0 +1,12 @@
+// foo.scala
+trait Foo {
+    def foo(arg: List[_])
+}
+trait FooImpl extends Foo {
+    def foo(arg: List[_]) {}
+}
+trait AbstractOverrideFoo extends Foo {
+    abstract override def foo(arg: List[_]) {
+        super.foo(arg)
+    }
+}
diff --git a/test/files/pos/t1642/JavaCallingScalaHashMap.java b/test/files/pos/t1642/JavaCallingScalaHashMap.java
new file mode 100644
index 0000000..976e465
--- /dev/null
+++ b/test/files/pos/t1642/JavaCallingScalaHashMap.java
@@ -0,0 +1,8 @@
+import scala.collection.immutable.HashMap;
+import scala.collection.immutable.Map;
+
+public class JavaCallingScalaHashMap {
+    public static void main( String[] args ) {
+        Map<String, Integer> hashMap = new HashMap<String, Integer>();
+    }
+}
diff --git a/test/files/pos/t1642/test.scala b/test/files/pos/t1642/test.scala
new file mode 100644
index 0000000..72e53b0
--- /dev/null
+++ b/test/files/pos/t1642/test.scala
@@ -0,0 +1,6 @@
+package x
+abstract class H[A] {
+  type P <: R[P]
+  def a: P
+}
+class R[F]
diff --git a/test/files/neg/t1659.scala b/test/files/pos/t1659.scala
similarity index 100%
rename from test/files/neg/t1659.scala
rename to test/files/pos/t1659.scala
diff --git a/test/files/pos/t1675.scala b/test/files/pos/t1675.scala
new file mode 100644
index 0000000..dcf1bf5
--- /dev/null
+++ b/test/files/pos/t1675.scala
@@ -0,0 +1,11 @@
+package a
+object Foo extends pack.Bar {
+ for(i <- 0 to 10) {
+   test("")
+ }
+}
+package pack {
+  class Bar {
+    protected def test(s: String*) {}
+  }
+}
diff --git a/test/files/pos/t1693.scala b/test/files/pos/t1693.scala
new file mode 100644
index 0000000..f3615f4
--- /dev/null
+++ b/test/files/pos/t1693.scala
@@ -0,0 +1,9 @@
+object Test {
+  class Foo
+  class SomeOps(x : Foo) { def foo(x: String) = 1 }
+  class OtherOps(x : Foo) { def foo(x: Int) = 1 }
+  implicit def mkSomeOps(x: Foo) : SomeOps = new SomeOps(x)
+  implicit def mkOtherOps(x: Foo) : OtherOps = new OtherOps(x)
+
+  (new Foo).foo(1)
+}
\ No newline at end of file
diff --git a/test/files/pos5/t1711/Seq.scala b/test/files/pos/t1711/Seq.scala
similarity index 100%
rename from test/files/pos5/t1711/Seq.scala
rename to test/files/pos/t1711/Seq.scala
diff --git a/test/files/pos5/t1711/Test.java b/test/files/pos/t1711/Test.java
similarity index 100%
rename from test/files/pos5/t1711/Test.java
rename to test/files/pos/t1711/Test.java
diff --git a/test/files/pos/t1722-A.scala b/test/files/pos/t1722-A.scala
new file mode 100644
index 0000000..9e522a5
--- /dev/null
+++ b/test/files/pos/t1722-A.scala
@@ -0,0 +1,10 @@
+sealed trait Top
+trait C {
+  private object P extends Top
+}                                                                                                                     
+/*  
+$ scala -e 'new AnyRef with C'
+error: error while loading Top, class file '/private/tmp/bobobo/./Top.class' is broken
+(error reading Scala signature of /private/tmp/bobobo/./Top.class: malformed Scala signature of Top at 185; reference value P of trait C refers to nonexisting symbol.)
+one error found
+*/
diff --git a/test/files/pos/t1722/Test.scala b/test/files/pos/t1722/Test.scala
new file mode 100644
index 0000000..5685d8f
--- /dev/null
+++ b/test/files/pos/t1722/Test.scala
@@ -0,0 +1,5 @@
+package t1722
+
+object Test {
+  val x = new AnyRef with C 
+}
diff --git a/test/files/pos/t1722/Top.scala b/test/files/pos/t1722/Top.scala
new file mode 100644
index 0000000..cec4c53
--- /dev/null
+++ b/test/files/pos/t1722/Top.scala
@@ -0,0 +1,13 @@
+package t1722
+
+sealed trait Top
+trait C {
+  private object P extends Top
+}                                                                                                                     
+/*  
+$ scala -e 'new AnyRef with C'
+error: error while loading Top, class file '/private/tmp/bobobo/./Top.class' is broken
+(error reading Scala signature of /private/tmp/bobobo/./Top.class: malformed Scala signature of Top at 185; reference value P of trait C refers to nonexisting symbol.)
+one error found
+Martin: I think this has to do with children property.
+*/
diff --git a/test/files/pos/t1745/J.java b/test/files/pos/t1745/J.java
new file mode 100644
index 0000000..d95efe8
--- /dev/null
+++ b/test/files/pos/t1745/J.java
@@ -0,0 +1,10 @@
+class J { 
+  S1 s1;
+  S2 s2;
+  
+  String s = bar(S3.foo(), S3.bar("def"));
+  
+  private String bar(String s1, String s2) {
+    return s1 + s2;
+  }
+}
diff --git a/test/files/pos/t1745/S.scala b/test/files/pos/t1745/S.scala
new file mode 100644
index 0000000..84c4371
--- /dev/null
+++ b/test/files/pos/t1745/S.scala
@@ -0,0 +1,7 @@
+case class S1(n: Int) { }
+case class S2(n: Int, p: Int) { }
+class S3 { }
+object S3 {
+  def foo() = "abc"
+  def bar[T](x: T): T = x
+}
diff --git a/test/files/pos/t1751.cmds b/test/files/pos/t1751.cmds
new file mode 100644
index 0000000..d4a4898
--- /dev/null
+++ b/test/files/pos/t1751.cmds
@@ -0,0 +1,3 @@
+javac SuiteClasses.java
+scalac A2_1.scala
+scalac A1_2.scala
diff --git a/test/files/pos/t1751/A1_2.scala b/test/files/pos/t1751/A1_2.scala
new file mode 100644
index 0000000..354d5ee
--- /dev/null
+++ b/test/files/pos/t1751/A1_2.scala
@@ -0,0 +1,2 @@
+ at SuiteClasses(Array(classOf[A2]))
+class A1
diff --git a/test/files/pos/t1751/A2_1.scala b/test/files/pos/t1751/A2_1.scala
new file mode 100644
index 0000000..c768062
--- /dev/null
+++ b/test/files/pos/t1751/A2_1.scala
@@ -0,0 +1,2 @@
+ at SuiteClasses(Array())
+class A2
diff --git a/test/files/pos/t1751/SuiteClasses.java b/test/files/pos/t1751/SuiteClasses.java
new file mode 100644
index 0000000..a415e4f
--- /dev/null
+++ b/test/files/pos/t1751/SuiteClasses.java
@@ -0,0 +1,3 @@
+public @interface SuiteClasses {
+    public Class<?>[] value();
+}
diff --git a/test/files/pos/t1756.scala b/test/files/pos/t1756.scala
new file mode 100644
index 0000000..7aea525
--- /dev/null
+++ b/test/files/pos/t1756.scala
@@ -0,0 +1,54 @@
+
+/** 
+This is a tricky issue which has to do with the fact that too much conflicting
+type information is propagated into a single implicit search, where the intended
+solution applies two implicit searches.
+
+Roughly, in x + x * y, the first x is first typed as Poly[A]. That
+means the x * y is then typed as Poly[A]. Then the second x is typed
+as Poly[A], then y is typed as Poly[Poly[A]]. The application x * y
+fails, so the coef2poly implicit conversion is applied to x. That
+means we look for an implicit conversion from type Poly[A] to type
+?{val *(x$1: ?>: Poly[Poly[A]] <: Any): Poly[A]}. Note that the result
+type Poly[A] is propagated into the implicit search. Poly[A] comes as
+expected type from x+, because the lhs x is still typed as a Poly[A].
+This means that the argument of the implicit conversion is typechecked
+with expected type A with Poly[A]. And no solution is found.
+
+To solve this, I added a fallback scheme similar to implicit arguments:
+When an implicit view that adds a method matching given arguments and result
+type fails, try again without the result type.
+*/
+trait Ring[T <: Ring[T]] {
+  def +(that: T): T
+  def *(that: T): T
+}
+
+class A extends Ring[A] {
+  def +(that: A) = new A
+  def *(that: A) = new A
+}
+
+class Poly[C <: Ring[C]](val c: C) extends Ring[Poly[C]] {
+  def +(that: Poly[C]) = new Poly(this.c+that.c)
+  def *(that: Poly[C]) = new Poly(this.c*that.c)
+}
+
+object Test extends Application {
+  
+  implicit def coef2poly[C <: Ring[C]](c: C): Poly[C] = new Poly(c)
+
+  val a = new A
+  val x = new Poly(new A)
+  
+  println(x+a) // works
+  println(a+x) // works
+  
+  val y = new Poly(new Poly(new A))
+  
+  println(x+y*x) // works
+  println(x*y+x) // works
+  println(y*x+x) // works
+  
+  println(x+x*y) // failed before
+}
diff --git a/test/files/pos/t1761.scala b/test/files/pos/t1761.scala
new file mode 100644
index 0000000..2af7280
--- /dev/null
+++ b/test/files/pos/t1761.scala
@@ -0,0 +1,10 @@
+import scala.xml._
+
+class Foo {
+  val elements: Seq[Node] = Nil
+  val innerTransform: PartialFunction[Elem, String] = {
+    case Elem(_, l: String, _, _, _ @ _*) if elements.exists(_.label == l) => 
+      l
+  }
+}
+
diff --git a/test/files/pos/t1782.cmds b/test/files/pos/t1782.cmds
new file mode 100644
index 0000000..61f3d37
--- /dev/null
+++ b/test/files/pos/t1782.cmds
@@ -0,0 +1,2 @@
+javac Ann.java Days.java ImplementedBy.java
+scalac Test_1.scala
diff --git a/test/files/pos/t1782/Ann.java b/test/files/pos/t1782/Ann.java
new file mode 100644
index 0000000..0dcfbd2
--- /dev/null
+++ b/test/files/pos/t1782/Ann.java
@@ -0,0 +1,3 @@
+public @interface Ann {
+    public Days value();
+}
diff --git a/test/files/pos/t1782/Days.java b/test/files/pos/t1782/Days.java
new file mode 100644
index 0000000..203a87b
--- /dev/null
+++ b/test/files/pos/t1782/Days.java
@@ -0,0 +1,3 @@
+public enum Days {
+    Friday, Sunday
+}
diff --git a/test/files/pos/t1782/ImplementedBy.java b/test/files/pos/t1782/ImplementedBy.java
new file mode 100644
index 0000000..6aa8b4f
--- /dev/null
+++ b/test/files/pos/t1782/ImplementedBy.java
@@ -0,0 +1,3 @@
+public @interface ImplementedBy {
+    public Class<?> value();
+}
diff --git a/test/files/pos/t1782/Test_1.scala b/test/files/pos/t1782/Test_1.scala
new file mode 100644
index 0000000..e61ef8e
--- /dev/null
+++ b/test/files/pos/t1782/Test_1.scala
@@ -0,0 +1,16 @@
+ at ImplementedBy(classOf[Provider])
+trait Service {
+  def someMethod()
+}
+
+class Provider
+    extends Service
+{
+  // test enumeration java annotations
+  @Ann(Days.Friday) def someMethod() = ()
+
+  // #2103
+  @scala.reflect.BeanProperty
+  @Ann(value = Days.Sunday)
+  val t2103 = "test"
+}
diff --git a/test/files/pos/t1789.scala b/test/files/pos/t1789.scala
new file mode 100644
index 0000000..1a37d48
--- /dev/null
+++ b/test/files/pos/t1789.scala
@@ -0,0 +1,5 @@
+object S {
+  try { }
+  catch { case _ => }
+  finally { while(true) { } }
+}
diff --git a/test/files/pos/t1798.scala b/test/files/pos/t1798.scala
new file mode 100644
index 0000000..93df61e
--- /dev/null
+++ b/test/files/pos/t1798.scala
@@ -0,0 +1,10 @@
+object Foo { private def bar(): Int = 55 }
+class Foo(x: Int) { def this() = this(Foo.bar()) }
+
+/*
+ * scalac28 a.scala 
+a.scala:2: error: method bar cannot be accessed in object Foo
+class Foo(x: Int) { def this() = this(Foo.bar()) }
+                                          ^
+one error found
+*/
diff --git a/test/files/pos/t1836/J.java b/test/files/pos/t1836/J.java
new file mode 100644
index 0000000..a009a59
--- /dev/null
+++ b/test/files/pos/t1836/J.java
@@ -0,0 +1 @@
+public abstract class J<T> { protected J(T id) { } }
diff --git a/test/files/pos/t1836/S.scala b/test/files/pos/t1836/S.scala
new file mode 100644
index 0000000..88ce106
--- /dev/null
+++ b/test/files/pos/t1836/S.scala
@@ -0,0 +1 @@
+class S extends J("")
diff --git a/test/files/pos/t1840/J.java b/test/files/pos/t1840/J.java
new file mode 100644
index 0000000..a697596
--- /dev/null
+++ b/test/files/pos/t1840/J.java
@@ -0,0 +1,4 @@
+package p;
+class J { 
+  J() {} 
+}
diff --git a/test/files/pos/t1840/S.scala b/test/files/pos/t1840/S.scala
new file mode 100644
index 0000000..ff513d2
--- /dev/null
+++ b/test/files/pos/t1840/S.scala
@@ -0,0 +1,2 @@
+package p
+class S { new J }
diff --git a/test/files/pos/t1896/D0.scala b/test/files/pos/t1896/D0.scala
new file mode 100644
index 0000000..05febb2
--- /dev/null
+++ b/test/files/pos/t1896/D0.scala
@@ -0,0 +1,11 @@
+package p
+
+class X[T]
+
+trait A {
+  def m(s:X[_]) {}
+}
+
+trait B extends A {
+  def f { super.m(null) }
+}
diff --git a/test/files/pos/t1896/D1.scala b/test/files/pos/t1896/D1.scala
new file mode 100644
index 0000000..e1ab506
--- /dev/null
+++ b/test/files/pos/t1896/D1.scala
@@ -0,0 +1,2 @@
+package p
+class C extends B
diff --git a/test/files/pos/t1937/NumberGenerator.java b/test/files/pos/t1937/NumberGenerator.java
new file mode 100644
index 0000000..59d6047
--- /dev/null
+++ b/test/files/pos/t1937/NumberGenerator.java
@@ -0,0 +1,7 @@
+package br.com.caelum.caelumweb2.money;
+
+public class NumberGenerator {
+	public String generate() {
+		return null;
+	}
+}
diff --git a/test/files/pos/t1942.cmds b/test/files/pos/t1942.cmds
new file mode 100644
index 0000000..c143110
--- /dev/null
+++ b/test/files/pos/t1942.cmds
@@ -0,0 +1,2 @@
+scalac A_1.scala
+scalac Test_2.scala
diff --git a/test/files/pos/t1942/A_1.scala b/test/files/pos/t1942/A_1.scala
new file mode 100644
index 0000000..19a7575
--- /dev/null
+++ b/test/files/pos/t1942/A_1.scala
@@ -0,0 +1,11 @@
+class A {
+  def foo(x: Int) = 0
+  def foo(x: String) = 1
+}
+
+class ann(x: Int) extends StaticAnnotation
+
+class t {
+  val a = new A
+  @ann(a.foo(1)) def bar = 1
+}
diff --git a/test/files/pos/t1942/Test_2.scala b/test/files/pos/t1942/Test_2.scala
new file mode 100644
index 0000000..6c045bb
--- /dev/null
+++ b/test/files/pos/t1942/Test_2.scala
@@ -0,0 +1,3 @@
+class Test {
+  println(new t)
+}
diff --git a/test/files/pos/t1987.scala b/test/files/pos/t1987.scala
new file mode 100644
index 0000000..ccab133
--- /dev/null
+++ b/test/files/pos/t1987.scala
@@ -0,0 +1,8 @@
+package object overloading {
+    def bar(f: (Int) => Unit): Unit = ()
+    def bar(f: (Int, Int) => Unit): Unit = ()
+}
+
+class PackageObjectOverloadingTest {
+    overloading.bar( (i: Int) => () ) // doesn't compile.
+}
diff --git a/test/files/pos/t1996.scala b/test/files/pos/t1996.scala
new file mode 100644
index 0000000..2730128
--- /dev/null
+++ b/test/files/pos/t1996.scala
@@ -0,0 +1,19 @@
+object forbug {
+  val l1 = List(List(ValDef(new A)), List(ValDef(new A)))
+  for ((e1s, e2s) <- l1.zip(l1);
+       (e1, e2) <- e1s.zip(e2s)) {
+    e1.a.doSome(20)
+//    ()
+  }
+}
+
+
+class A {
+  def doSome(a: Int): this.type = {
+    println(a)
+    this
+  }
+}
+
+case class ValDef(a: A)
+
diff --git a/test/files/pos/t2023.scala b/test/files/pos/t2023.scala
new file mode 100644
index 0000000..de3e848
--- /dev/null
+++ b/test/files/pos/t2023.scala
@@ -0,0 +1,16 @@
+trait C[A]
+
+object C {
+  implicit def ipl[A](implicit from: A => Ordered[A]): C[A] = null
+}
+	
+object P {
+  def foo[A](i: A, j: A)(implicit c: C[A]): Unit = ()
+}
+	
+class ImplicitChainTest {
+  def testTrivial: Unit = {
+    P.foo('0', '9')
+    P.foo('0', '9')
+  }
+}
diff --git a/test/files/pos/t2060.scala b/test/files/pos/t2060.scala
new file mode 100644
index 0000000..cf7250f
--- /dev/null
+++ b/test/files/pos/t2060.scala
@@ -0,0 +1,44 @@
+/* The problem here is that we cannot insert an implicit to
+ * add a polymorphic method which is then instantiated to the
+ * right type. When searching for the implicit in the `fails to compile
+ * line':
+ *
+ *   val failure = 1.0 + new Op[Int]
+ * 
+ * we reduce the problem to finding a function from Double to
+ * {+: _ >: Op[Int] <: Any}, that is, a method which takes
+ * an argument which is an Op[Int] or a supertype thereof.
+ * Class Rich is not a subtype of this structural record, because
+ * polymorphic method instantiation is not contained in subtyping.
+ * That is: The method type [I](op : Op[I]): Op[I] is not a subtype
+ * of (Op[Int]): Op[Int].
+ * At present it is unclear whether this problem can be solved.
+ */
+object Test {
+  class Op[I];
+  class IntOp extends Op[Int];
+
+  class Rich(x : Double) {
+    def +       (op : IntOp): IntOp = op;
+    def +    [I](op : Op[I]): Op[I] = op;
+    def plus [I](op : Op[I]): Op[I] = op;
+  }
+
+  implicit def iToRich(x : Double) =
+    new Rich(x);
+
+  // fails to compile
+  val x = 1.0 + new Op[Int]
+
+  // works as expected --
+  //   problem isn't in adding new "+"
+  val a = 1.0 + new IntOp;
+
+  // works as expected --
+  //   problem isn't in binding type variable I
+  val b = 1.0 plus new Op[Int];
+
+  // works as expected --
+  //   problem isn't in using Rich.+[I](op : Op[I])
+  val c = iToRich(1.0) + new Op[Int];
+}
diff --git a/test/files/pos/t2082.scala b/test/files/pos/t2082.scala
new file mode 100644
index 0000000..38937d7
--- /dev/null
+++ b/test/files/pos/t2082.scala
@@ -0,0 +1,39 @@
+
+trait Mapper[T <: Mapper[T]]
+
+trait KeyedMapper[KeyType, T <: KeyedMapper[KeyType, T]] extends Mapper[T] 
+
+
+trait KeyedMetaMapper[KeyType, T <: KeyedMapper[KeyType, T]] 
+
+trait MappedForeignKey[KeyType, Owner <: Mapper[Owner], Other <: KeyedMapper[KeyType, Other]]
+
+trait IdPK
+
+class TestSubject extends KeyedMapper[Long, TestSubject] with IdPK
+
+class TestRun extends KeyedMapper[Long, TestRun] with IdPK {
+	object testSubject extends MappedForeignKey[Long, TestRun, TestSubject]
+}
+
+object TestRun extends TestRun with KeyedMetaMapper[Long, TestRun]
+
+class MetaTestSubject extends TestSubject with KeyedMetaMapper[Long, TestSubject]
+object TestSubject extends MetaTestSubject 
+
+object Main {
+  
+  def oneToOneJoin[PType <: KeyedMapper[Long, PType] with IdPK,
+                   CType <: KeyedMapper[Long, CType] with IdPK,
+                   CMetaType <: CType with KeyedMetaMapper[Long, CType], 
+                   FKType <: MappedForeignKey[Long, PType, CType]]
+  (parents: List[PType], metaMapper: CMetaType, keyGetter: (PType) => FKType ): 
+  Map[Long, CType] = Map.empty
+  
+  def callIt {
+    oneToOneJoin[TestRun, TestSubject, MetaTestSubject, 
+                 MappedForeignKey[Long, TestRun, TestSubject]](
+    List(), TestSubject, (tr: TestRun) => tr.testSubject)
+  }
+
+}
diff --git a/test/files/pos/t2133.scala b/test/files/pos/t2133.scala
new file mode 100644
index 0000000..99bac5c
--- /dev/null
+++ b/test/files/pos/t2133.scala
@@ -0,0 +1,18 @@
+trait Foo {
+  object bar {
+    private[this] def fn() = 5
+  }
+}
+
+trait Foo2 {
+  object bip {
+    def fn() = 10
+  }
+}
+
+class Bob extends AnyRef with Foo with Foo2 {
+  import bip._
+  import bar._
+  
+  def go() = fn()
+}
diff --git a/test/files/pos/t2183.scala b/test/files/pos/t2183.scala
new file mode 100644
index 0000000..1243568
--- /dev/null
+++ b/test/files/pos/t2183.scala
@@ -0,0 +1,5 @@
+import scala.collection.mutable._
+
+object Test {
+  val m = new HashSet[String] with SynchronizedSet[String]
+}
diff --git a/test/files/pos/t2208.scala b/test/files/pos/t2208.scala
new file mode 100644
index 0000000..f1a521b
--- /dev/null
+++ b/test/files/pos/t2208.scala
@@ -0,0 +1,8 @@
+object Test  {
+	class A
+
+	class B[X]
+	type Alias[X <: A] = B[X]
+
+	val foo: B[A] = new Alias[A] // check that type aliases can be instantiated
+}
\ No newline at end of file
diff --git a/test/files/pos/t2234.scala b/test/files/pos/t2234.scala
new file mode 100644
index 0000000..cea657b
--- /dev/null
+++ b/test/files/pos/t2234.scala
@@ -0,0 +1,4 @@
+object Test extends Application {
+  val res0 = 1 #:: Stream.empty
+  res0 match { case 1 #:: xs => xs }
+}
diff --git a/test/files/pos/t2261.scala b/test/files/pos/t2261.scala
new file mode 100644
index 0000000..af24234
--- /dev/null
+++ b/test/files/pos/t2261.scala
@@ -0,0 +1,9 @@
+class Bob[T]
+object Test {
+  implicit def foo2bar[T](xs: List[T]): Bob[T] = new Bob[T]
+  var x: Bob[Int] = null
+  x = List(1,2,3)
+  // the problem here was that somehow the type variable that was used to infer the type argument for List.apply
+  // would accumulate several conflicting constraints
+  // can't reproduce with 
+}
\ No newline at end of file
diff --git a/test/files/pos/t2293.scala b/test/files/pos/t2293.scala
new file mode 100644
index 0000000..65f717f
--- /dev/null
+++ b/test/files/pos/t2293.scala
@@ -0,0 +1,5 @@
+import scala.collection.JavaConversions._
+
+object Test {
+  val m: java.util.Map[String,String] = collection.mutable.Map("1"->"2")
+}
\ No newline at end of file
diff --git a/test/files/pos/t2305.scala b/test/files/pos/t2305.scala
new file mode 100644
index 0000000..d0b103f
--- /dev/null
+++ b/test/files/pos/t2305.scala
@@ -0,0 +1,26 @@
+import java.util.ArrayList
+
+trait Bind[Z[_]] 
+
+class MySerializable[X] extends java.io.Serializable
+
+object Bind {
+	implicit val JavaArrayListBind: Bind[ArrayList] = new Bind[ArrayList] {}
+	implicit val MySerializableBind: Bind[MySerializable] = new Bind[MySerializable] {}
+}
+
+object works {
+	// this works fine:
+	def runbind(implicit bind: Bind[MySerializable]) {}
+	runbind
+}
+
+object breaks {
+	def runbind(implicit bind: Bind[ArrayList]) {}
+	runbind  
+	/*java.lang.AssertionError: assertion failed: java.io.Serializable
+		at scala.Predef$.assert(Predef.scala:107)
+		at scala.tools.nsc.symtab.Types$TypeRef.transform(Types.scala:1417)
+		at scala.tools.nsc.symtab.Types$TypeRef.baseType(Types.scala:1559)
+	*/
+}
diff --git a/test/files/pos/t2331.scala b/test/files/pos/t2331.scala
new file mode 100644
index 0000000..9a15b5c
--- /dev/null
+++ b/test/files/pos/t2331.scala
@@ -0,0 +1,11 @@
+trait C {
+  def m[T]: T
+}
+
+object Test {
+  val o /*: C --> no crash*/ = new C {
+    def m[T]: Nothing /*: T --> no crash*/ = error("omitted")
+  }
+
+  o.m[Nothing]
+}
\ No newline at end of file
diff --git a/test/files/pos/t2377/Q.java b/test/files/pos/t2377/Q.java
new file mode 100644
index 0000000..e3d11c7
--- /dev/null
+++ b/test/files/pos/t2377/Q.java
@@ -0,0 +1,12 @@
+public final class Q {
+  public static final class Stage {
+    public static Builder newBuilder() { return new Builder(); }
+    public static final class Builder { }
+    public Builder toBuilder() { return newBuilder(); }
+  }
+  public static final class WorkUnit {
+    public static Builder newBuilder() { return new Builder(); }
+    public static final class Builder { }
+    public Builder toBuilder() { return newBuilder(); }
+  }
+}
diff --git a/test/files/pos/t2377/a.scala b/test/files/pos/t2377/a.scala
new file mode 100644
index 0000000..bda59ce
--- /dev/null
+++ b/test/files/pos/t2377/a.scala
@@ -0,0 +1,8 @@
+import Q._
+
+class Bop(var workUnit: WorkUnit) {
+  def addStages(stageBuilder: Stage.Builder): Unit = {
+    val builder = workUnit.toBuilder
+    ()
+  }
+}
diff --git a/test/files/pos/t2413/TestJava.java b/test/files/pos/t2413/TestJava.java
new file mode 100644
index 0000000..252c01f
--- /dev/null
+++ b/test/files/pos/t2413/TestJava.java
@@ -0,0 +1,7 @@
+package pack;
+
+public class TestJava {
+    protected String repeatParam(String ... items) {
+        return "nothing";
+    }
+}
diff --git a/test/files/pos/t2413/TestScalac.scala b/test/files/pos/t2413/TestScalac.scala
new file mode 100644
index 0000000..6992a30
--- /dev/null
+++ b/test/files/pos/t2413/TestScalac.scala
@@ -0,0 +1,23 @@
+import pack.TestJava
+
+class Foo extends TestJava {
+
+   // THIS METHOD YIELDS TO CRASH
+/*   def foomethod : Option[String] => Unit = {
+      case None =>  
+        val path = repeatParam("s","a","b","c")
+        ()
+      case Some(error) =>
+        ()
+   }
+
+  // THIS IS OK
+  def foomethod2 : String = repeatParam("s","a");
+
+  // THIS IS OK
+  val aVal = repeatParam("1","2","3") */
+
+  // THIS YIELDS TO CRASH
+  for (a <- 1 to 4 ; anotherVal = repeatParam("1","2","3"))
+    yield anotherVal
+}
diff --git a/test/files/pos/t2421.scala b/test/files/pos/t2421.scala
new file mode 100644
index 0000000..26e485c
--- /dev/null
+++ b/test/files/pos/t2421.scala
@@ -0,0 +1,14 @@
+object Test {
+  abstract class <~<[-From, +To] extends (From => To)
+  implicit def trivial[A]: A <~< A = error("")
+
+
+  trait Forcible[T]
+  implicit val forcibleInt: (Int <~< Forcible[Int]) = error("")
+
+  def headProxy[P <: Forcible[Int]](implicit w: Int <~< P): P = error("")
+  
+  headProxy 
+  // trivial[Int] should not be considered a valid implicit, since w would have type Int <~< Int, 
+  // and headProxy's type parameter P cannot be instantiated to Int
+}
\ No newline at end of file
diff --git a/test/files/pos/t2421_delitedsl.scala b/test/files/pos/t2421_delitedsl.scala
new file mode 100644
index 0000000..ad6afa7
--- /dev/null
+++ b/test/files/pos/t2421_delitedsl.scala
@@ -0,0 +1,37 @@
+trait DeliteDSL {
+  abstract class <~<[-From, +To] extends (From => To)
+  implicit def trivial[A]: A <~< A = new (A <~< A) {def apply(x: A) = x}  
+
+  trait Forcible[T]
+  object Forcible {
+    def factory[T](f: T => Forcible[T]) = new (T <~< Forcible[T]){def apply(x: T) = f(x)}  
+  }
+
+  case class DeliteInt(x: Int) extends Forcible[Int]
+  implicit val forcibleInt = Forcible.factory(DeliteInt(_: Int))
+
+  import scala.collection.Traversable
+  class DeliteCollection[T](val xs: Traversable[T]) {
+    // must use existential in bound of P, instead of T itself, because we cannot both have:
+        // Test.x below: DeliteCollection[T=Int] -> P=DeliteInt <: Forcible[T=Int], as T=Int <~< P=DeliteInt
+        // Test.xAlready below: DeliteCollection[T=DeliteInt] -> P=DeliteInt <: Forcible[T=DeliteInt], as T=DeliteInt <~< P=DeliteInt
+        // this would required DeliteInt <: Forcible[Int] with Forcible[DeliteInt]
+
+    def headProxy[P <: Forcible[_]](implicit w: T <~< P): P = xs.head
+  }
+  // If T is already a proxy (it is forcible), the compiler should use
+  // forcibleIdentity to deduce that P=T.  If T is Int, the compiler
+  // should use intToForcible to deduce that P=DeliteInt.
+  // 
+  // Without this feature, the user must write 'xs.proxyOfFirst[DeliteInt]',
+  // with the feature they can write 'xs.proxyOfFirst', which is shorter and
+  // avoids exposing internal DELITE types to the world.
+
+  object Test {
+    val x = new DeliteCollection(List(1,2,3)).headProxy 
+    // inferred: val x: Forcible[Int] = new DeliteCollection[Int](List.apply[Int](1, 2, 3)).headProxy[Forcible[Int]](forcibleInt);
+
+    val xAlready = new DeliteCollection(List(DeliteInt(1),DeliteInt(2),DeliteInt(3))).headProxy 
+    // inferred: val xAlready: DeliteInt = new DeliteCollection[DeliteInt](List.apply[DeliteInt](DeliteInt(1), DeliteInt(2), DeliteInt(3))).headProxy[DeliteInt](trivial[DeliteInt]);
+  }
+}
\ No newline at end of file
diff --git a/test/files/pos/t2421b.scala b/test/files/pos/t2421b.scala
new file mode 100644
index 0000000..8b848ab
--- /dev/null
+++ b/test/files/pos/t2421b.scala
@@ -0,0 +1,19 @@
+object Test {
+  class A
+  class B
+  class C
+  class F[X]
+
+  def f(implicit aa: F[A]) = println(aa)
+
+  implicit def a : F[A] = new F[A]()
+  implicit def b[X <: B] = new F[X]()
+
+  f
+}
+/* bug: 
+error: ambiguous implicit values:
+ both method b in object Test1 of type [X <: Test1.B]Test1.F[X]
+ and method a in object Test1 of type => Test1.F[Test1.A]
+ match expected type Test1.F[Test1.A]
+*/
diff --git a/test/files/pos/t2421c.scala b/test/files/pos/t2421c.scala
new file mode 100644
index 0000000..755e6a3
--- /dev/null
+++ b/test/files/pos/t2421c.scala
@@ -0,0 +1,17 @@
+object Test {
+  class A
+  class B
+  class C
+  class F[X]
+
+  def f(implicit aa: F[A]) = println(aa)
+
+  implicit def a : F[A] = new F[A]()
+
+  // generalised from t2421b to verify we check enough
+  class G[X]
+  implicit def g[X] = new G[X]()
+  implicit def b[X <: B](implicit mx: G[X]) = new F[X]()
+
+  f
+}
\ No newline at end of file
diff --git a/test/files/pos/t2425.scala b/test/files/pos/t2425.scala
new file mode 100644
index 0000000..403f1a1
--- /dev/null
+++ b/test/files/pos/t2425.scala
@@ -0,0 +1,15 @@
+trait B
+class D extends B
+object Test extends Application {
+  def foo[T](bar: T) = {
+    bar match {
+      case _: Array[Array[_]] => println("array 2d")
+      case _: Array[_] => println("array 1d")
+      case _ => println("something else")
+    }
+  }
+  foo(Array.fill(10)(2))
+  foo(Array.fill(10, 10)(2))
+  foo(Array.fill(10, 10, 10)(2))
+  foo(List(1, 2, 3))
+}
diff --git a/test/files/pos/t2429.scala b/test/files/pos/t2429.scala
new file mode 100644
index 0000000..3ea3f9e
--- /dev/null
+++ b/test/files/pos/t2429.scala
@@ -0,0 +1,25 @@
+object Msg {
+  trait T
+  
+  trait TSeq
+  
+  object TSeq {
+    implicit def fromSeq(s: Seq[T]): TSeq = error("stub")
+  }
+
+  def render {
+    val msgs: TSeq = (List[(Any, Any)]().flatMap {
+      case (a, b) => {
+        a match {
+          case _ => b match {
+            case _ => error("stub")
+          }
+        }
+      }
+    } /*: Seq[T] Adding this type annotation avoids the compile error.*/)
+  }
+}
+object Oops {
+ implicit def someImplicit(s: Seq[_]): String = error("stub")
+ def item: String = Nil map { case e: Any => e }
+}
diff --git a/test/files/pos/t2433/A.java b/test/files/pos/t2433/A.java
new file mode 100644
index 0000000..8ae23ff
--- /dev/null
+++ b/test/files/pos/t2433/A.java
@@ -0,0 +1,4 @@
+class A223 extends B223.Inner {
+    static class Inner {}
+    void foo() {}
+}
\ No newline at end of file
diff --git a/test/files/pos/t2433/B.java b/test/files/pos/t2433/B.java
new file mode 100644
index 0000000..d0d5580
--- /dev/null
+++ b/test/files/pos/t2433/B.java
@@ -0,0 +1,4 @@
+class B223 {
+    static class Inner {}
+    void m(A223.Inner x) {}
+}
\ No newline at end of file
diff --git a/test/files/pos/t2433/Test.scala b/test/files/pos/t2433/Test.scala
new file mode 100644
index 0000000..0e07231
--- /dev/null
+++ b/test/files/pos/t2433/Test.scala
@@ -0,0 +1,3 @@
+object Test {
+  (new A223).foo()
+}
diff --git a/test/files/pos/t2444.scala b/test/files/pos/t2444.scala
new file mode 100644
index 0000000..a052270
--- /dev/null
+++ b/test/files/pos/t2444.scala
@@ -0,0 +1,15 @@
+object Test {
+
+  trait Foo
+
+  class Bar { 
+    object baz extends Foo
+  }
+
+  def frob[P1, P2<:Foo](f:P1 => P2) = () 
+
+  def main(args:Array[String]) : Unit = {
+  	frob((p:Bar) => p.baz) 
+  }
+
+}
diff --git a/test/files/pos/t2454.scala b/test/files/pos/t2454.scala
new file mode 100644
index 0000000..00f2e6f
--- /dev/null
+++ b/test/files/pos/t2454.scala
@@ -0,0 +1,25 @@
+package am;
+
+trait One[M[_]] {
+  val x : Int
+}
+
+trait Two[M[_,_]] {
+  val x : Int
+}
+
+object Test {
+  // Works.
+  val x = new Two[Map] {
+    val x = 5
+  }
+
+  val o = new One[java.util.List] {
+    val x = 1
+  }
+
+  // Does not work
+  val y = new Two[java.util.concurrent.ConcurrentHashMap] {
+    val x = 3
+  }
+}
diff --git a/test/files/pos/t2464.cmds b/test/files/pos/t2464.cmds
new file mode 100644
index 0000000..ca733ef
--- /dev/null
+++ b/test/files/pos/t2464.cmds
@@ -0,0 +1,3 @@
+javac JavaOne.java
+scalac ScalaOne_1.scala
+scalac t2464_2.scala
diff --git a/test/files/pos/t2464/JavaOne.java b/test/files/pos/t2464/JavaOne.java
new file mode 100644
index 0000000..ff36868
--- /dev/null
+++ b/test/files/pos/t2464/JavaOne.java
@@ -0,0 +1,5 @@
+class ClassTwo {
+	public static class Child  {
+		public void func2() {return ;}
+	}
+}
diff --git a/test/files/pos/t2464/ScalaOne_1.scala b/test/files/pos/t2464/ScalaOne_1.scala
new file mode 100644
index 0000000..0271b9c
--- /dev/null
+++ b/test/files/pos/t2464/ScalaOne_1.scala
@@ -0,0 +1,6 @@
+class ScalaClassOne extends ClassTwo.Child {
+  def func4() = {
+    func2
+  }	
+}
+
diff --git a/test/files/pos/t2464/t2464_2.scala b/test/files/pos/t2464/t2464_2.scala
new file mode 100644
index 0000000..13a52c9
--- /dev/null
+++ b/test/files/pos/t2464/t2464_2.scala
@@ -0,0 +1,3 @@
+object Test {
+  val c1 = new ScalaClassOne
+}
diff --git a/test/files/pos/t2484.scala b/test/files/pos/t2484.scala
new file mode 100644
index 0000000..20c51b0
--- /dev/null
+++ b/test/files/pos/t2484.scala
@@ -0,0 +1,17 @@
+class Admin extends javax.swing.JApplet {
+  val jScrollPane = new javax.swing.JScrollPane (null, 0, 0)
+  def bug2484: Unit = {
+    scala.concurrent.ops.spawn {jScrollPane.synchronized {
+      def someFunction () = {}
+      //scala.concurrent.ops.spawn {someFunction ()}
+      jScrollPane.addComponentListener (new java.awt.event.ComponentAdapter {override def componentShown (e: java.awt.event.ComponentEvent) = {
+        someFunction (); jScrollPane.removeComponentListener (this)}})
+    }}
+  }
+}
+// t2630.scala
+object Test {
+  def meh(xs: List[Any]) {
+    xs map { x =>  (new AnyRef {}) }
+  }
+}
diff --git a/test/files/pos/t2500.scala b/test/files/pos/t2500.scala
new file mode 100644
index 0000000..76dea4c
--- /dev/null
+++ b/test/files/pos/t2500.scala
@@ -0,0 +1,6 @@
+object Test {
+	import scala.collection._
+	((Map(1 -> "a", 2 -> "b"): collection.Map[Int, String]) map identity[(Int, String)]) : scala.collection.Map[Int,String]
+	((SortedMap(1 -> "a", 2 -> "b"): collection.SortedMap[Int, String]) map identity[(Int, String)]): scala.collection.SortedMap[Int,String]
+	((SortedSet(1, 2): collection.SortedSet[Int]) map identity[Int]): scala.collection.SortedSet[Int]
+}
\ No newline at end of file
diff --git a/test/files/pos/t2504.scala b/test/files/pos/t2504.scala
new file mode 100644
index 0000000..0abe7dd
--- /dev/null
+++ b/test/files/pos/t2504.scala
@@ -0,0 +1,5 @@
+object Test {
+  val ys: Iterable[_] = Array("abc")
+  val xs = Array("abc")        
+  xs sameElements Array("abc")
+}
diff --git a/test/files/pos/t2545.scala b/test/files/pos/t2545.scala
new file mode 100644
index 0000000..b4238fb
--- /dev/null
+++ b/test/files/pos/t2545.scala
@@ -0,0 +1,10 @@
+trait Frog[T] {
+      def hello: T 
+      def size: Int                                                                                                                                                          
+    }
+
+    trait OnlyWithFrogs {
+      self: Frog[_] =>
+
+        def sizeStr = size.toString
+    }
diff --git a/test/files/pos/t2569/Child.scala b/test/files/pos/t2569/Child.scala
new file mode 100644
index 0000000..3d7f424
--- /dev/null
+++ b/test/files/pos/t2569/Child.scala
@@ -0,0 +1,9 @@
+package varargs
+  
+  class Child extends Parent {
+  
+    override def concatenate(strings: String*): String =
+      strings map("\"" + _ + "\"") mkString("(", ", ", ")")
+  
+  }
+
diff --git a/test/files/pos/t2569/Parent.java b/test/files/pos/t2569/Parent.java
new file mode 100644
index 0000000..133f2ee
--- /dev/null
+++ b/test/files/pos/t2569/Parent.java
@@ -0,0 +1,13 @@
+package varargs;
+  
+  public class Parent {
+  
+      public String concatenate(String... strings) {
+          StringBuilder builder = new StringBuilder();
+          for (String s : strings) {
+              builder.append(s);
+          }
+          return builder.toString();
+      }
+  
+  }
diff --git a/test/files/pos/t2591.scala b/test/files/pos/t2591.scala
new file mode 100644
index 0000000..d3c32ba
--- /dev/null
+++ b/test/files/pos/t2591.scala
@@ -0,0 +1,15 @@
+class A
+class B
+
+object Implicits {
+  implicit def imp(x: A): Int = 41
+  implicit def imp(x: B): Int = 41
+}
+
+object Test {
+	// should cause imp to be in scope so that the next expression type checks
+	// `import Implicits._` works
+	import Implicits.imp
+
+  (new A) : Int
+}
\ No newline at end of file
diff --git a/test/files/pos/t2610.scala b/test/files/pos/t2610.scala
new file mode 100644
index 0000000..8dd4cde
--- /dev/null
+++ b/test/files/pos/t2610.scala
@@ -0,0 +1,17 @@
+package mada; package defects; package tests
+
+package object bbb {
+    def bar = ()
+    aaa.foo // value foo is not a member of package mada.defects.tests.aaa
+}
+
+package object aaa {
+    def foo = ()
+}
+
+/* compiles successfully if placed here..
+package object bbb {
+    def bar = ()
+    aaa.foo // value foo is not a member of package mada.defects.tests.aaa
+}
+*/
\ No newline at end of file
diff --git a/test/files/pos/t2619.scala b/test/files/pos/t2619.scala
new file mode 100644
index 0000000..565bc95
--- /dev/null
+++ b/test/files/pos/t2619.scala
@@ -0,0 +1,80 @@
+abstract class F {
+    final def apply(x: Int): AnyRef = null
+}
+abstract class AbstractModule {
+    def as: List[AnyRef]
+    def ms: List[AbstractModule]
+    def fs: List[F] = Nil
+    def rs(x: Int): List[AnyRef] = fs.map(_(x))
+}
+abstract class ModuleType1 extends AbstractModule {}
+abstract class ModuleType2 extends AbstractModule {}
+
+object ModuleAE extends ModuleType1 {
+    def as = Nil
+    def ms = Nil
+}
+object ModuleAF extends ModuleType2 {
+    def as = Nil
+    def ms = List(ModuleAE)
+}
+object ModuleAG extends ModuleType1 {
+    def as = List("")
+    def ms = Nil
+}
+object ModuleAI extends ModuleType1 {
+    def as = Nil
+    def ms = List(ModuleAE)
+}
+object ModuleAK extends ModuleType2 {
+    def as = Nil
+    def ms = List(ModuleAF)
+}
+object ModuleAL extends ModuleType1 {
+    def as = Nil
+    def ms = List(
+        ModuleAG,
+        ModuleAI
+    )
+}
+object ModuleAM extends ModuleType1 {
+    def as = Nil
+    def ms = List(
+        ModuleAL,
+        ModuleAE
+    ) ::: List(ModuleAK)
+}
+object ModuleBE extends ModuleType1 {
+    def as = Nil
+    def ms = Nil
+}
+object ModuleBF extends ModuleType2 {
+    def as = Nil
+    def ms = List(ModuleBE)
+}
+object ModuleBG extends ModuleType1 {
+    def as = List("")
+    def ms = Nil
+}
+object ModuleBI extends ModuleType1 {
+    def as = Nil
+    def ms = List(ModuleBE)
+}
+object ModuleBK extends ModuleType2 {
+    def as = Nil
+    def ms = List(ModuleBF)
+}
+object ModuleBL extends ModuleType1 {
+    def as = Nil
+    def ms = List(
+        ModuleBG,
+        ModuleBI
+    )
+}
+object ModuleBM extends ModuleType1 {
+    def as = Nil
+    def ms = List(
+        ModuleBL,
+        ModuleBE
+    ) ::: List(ModuleBK)
+}
\ No newline at end of file
diff --git a/test/files/pos/t2624.scala b/test/files/pos/t2624.scala
new file mode 100644
index 0000000..76f0e30
--- /dev/null
+++ b/test/files/pos/t2624.scala
@@ -0,0 +1,4 @@
+object Test {
+  List(1).map(identity(_))
+  List(1).map(identity) // this didn't typecheck before the fix
+}
diff --git a/test/files/pos/t2635.scala b/test/files/pos/t2635.scala
new file mode 100644
index 0000000..7cd5531
--- /dev/null
+++ b/test/files/pos/t2635.scala
@@ -0,0 +1,16 @@
+abstract class Base
+
+object Test
+{
+  def run(c: Class[_ <: Base]): Unit = {
+  }
+
+  def main(args: Array[String]): Unit =
+  {
+    val sc: Option[Class[_ <: Base]] = Some(classOf[Base])
+    sc match {
+      case Some(c) => run(c)
+      case None =>
+    }
+  }
+}
diff --git a/test/files/pos/t2660.scala b/test/files/pos/t2660.scala
new file mode 100644
index 0000000..b1908b2
--- /dev/null
+++ b/test/files/pos/t2660.scala
@@ -0,0 +1,25 @@
+package hoho
+
+class G
+
+class H extends G
+
+class A[T](x: T) {
+
+  def this(y: G, z: T) = {
+    this(z)
+    print(1)
+  }
+
+  def this(z: H, h: T) = {
+    this(h)
+    print(2)
+  }
+}
+
+object T {
+  def main(args: Array[String]) {
+    implicit def g2h(g: G): H = new H
+    new A(new H, 23)
+  }
+}
\ No newline at end of file
diff --git a/test/files/pos/t2664.scala b/test/files/pos/t2664.scala
new file mode 100644
index 0000000..7b667d0
--- /dev/null
+++ b/test/files/pos/t2664.scala
@@ -0,0 +1,9 @@
+package pkg1 {
+    class C {
+        private[pkg1] def foo: Int = 1
+    }
+
+    trait T extends C {
+        private[pkg1] abstract override def foo = super.foo + 1
+    }
+}
diff --git a/test/files/pos/t2665.scala b/test/files/pos/t2665.scala
new file mode 100644
index 0000000..108daf5
--- /dev/null
+++ b/test/files/pos/t2665.scala
@@ -0,0 +1,3 @@
+object Test {
+  val x: Unit = Array("") 
+}
\ No newline at end of file
diff --git a/test/files/pos/t2667.scala b/test/files/pos/t2667.scala
new file mode 100644
index 0000000..b214cc7
--- /dev/null
+++ b/test/files/pos/t2667.scala
@@ -0,0 +1,6 @@
+object A {
+  def foo(x: Int, y: Int*): Int = 45
+  def foo[T](x: T*): Int = 55
+
+  val x: Unit = foo(23, 23f)
+}
\ No newline at end of file
diff --git a/test/files/pos/t2669.scala b/test/files/pos/t2669.scala
new file mode 100644
index 0000000..e34f08f
--- /dev/null
+++ b/test/files/pos/t2669.scala
@@ -0,0 +1,28 @@
+// #2629, #2639, #2669
+object Test2669 {
+
+  def test[T](l: java.util.ArrayList[_ <: T]) = 1
+  test(new java.util.ArrayList[String]())
+
+}
+
+import java.util.ArrayList
+
+object Test2629 {
+  def main(args: Array[String]): Unit = {
+    val l = new ArrayList[String](1)
+    val m = new ArrayList(l)
+
+    println(l.size)
+    println(m.size)
+  }
+}
+
+
+import java.util.Vector
+
+// scalac cannot detect lack of type params, but then throws AssertionError later:
+class TVector2639 {
+  val b = new Vector  // this line passed without error detected 
+  val a = new Vector(1) // this line caused throwing AssertionError when scalac
+}
diff --git a/test/files/pos/t2673.scala b/test/files/pos/t2673.scala
new file mode 100644
index 0000000..7f232df
--- /dev/null
+++ b/test/files/pos/t2673.scala
@@ -0,0 +1,4 @@
+object Test {
+  val xs = Array(1, 2, 3)
+  (xs, xs).zipped map (_ + _)
+}
\ No newline at end of file
diff --git a/test/files/pos/t2683.scala b/test/files/pos/t2683.scala
new file mode 100644
index 0000000..4ba34b5
--- /dev/null
+++ b/test/files/pos/t2683.scala
@@ -0,0 +1,7 @@
+class A
+class B extends A
+
+object Test {
+  val c: Class[_ <: A] = Class.forName("B").asSubclass(classOf[A])
+  val x: Option[Class[_ <: A]] = Some(3).map { case _ => c }
+}
diff --git a/test/files/pos/t2691.scala b/test/files/pos/t2691.scala
new file mode 100644
index 0000000..3c0d193
--- /dev/null
+++ b/test/files/pos/t2691.scala
@@ -0,0 +1,9 @@
+object Breakdown {
+  def unapplySeq(x: Int): Some[List[String]] = Some(List("", "there")) 
+}
+object Test {
+  42 match {
+    case Breakdown("") =>  // needed to trigger bug
+    case Breakdown("", who) => println ("hello " + who)
+  }
+}
\ No newline at end of file
diff --git a/test/files/pos/t2698.scala b/test/files/pos/t2698.scala
new file mode 100644
index 0000000..0e2662d
--- /dev/null
+++ b/test/files/pos/t2698.scala
@@ -0,0 +1,10 @@
+import scala.collection._
+import scala.util.regexp._
+
+abstract class S2 {
+  val lang: WordExp
+  type __labelT = lang._labelT
+
+  var deltaq: Array[__labelT] = _
+  def delta1  = immutable.Map(deltaq.zipWithIndex: _*)
+}
diff --git a/test/files/pos/t2708.scala b/test/files/pos/t2708.scala
new file mode 100644
index 0000000..19485bf
--- /dev/null
+++ b/test/files/pos/t2708.scala
@@ -0,0 +1 @@
+class Foo(@volatile var v: Int)
diff --git a/test/files/pos/t2726.cmds b/test/files/pos/t2726.cmds
new file mode 100644
index 0000000..5fcb18b
--- /dev/null
+++ b/test/files/pos/t2726.cmds
@@ -0,0 +1,2 @@
+scalac SQLBuilder_1.scala
+scalac test_2.scala
diff --git a/test/files/pos/t2726/SQLBuilder_1.scala b/test/files/pos/t2726/SQLBuilder_1.scala
new file mode 100644
index 0000000..7b3e3d8
--- /dev/null
+++ b/test/files/pos/t2726/SQLBuilder_1.scala
@@ -0,0 +1,7 @@
+class SQLBuilder extends SQLBuilder.Segment
+
+object SQLBuilder { 
+  trait Segment 
+}
+
+
diff --git a/test/files/pos/t2726/test_2.scala b/test/files/pos/t2726/test_2.scala
new file mode 100644
index 0000000..e738143
--- /dev/null
+++ b/test/files/pos/t2726/test_2.scala
@@ -0,0 +1,3 @@
+object SQuery2Test {
+  new SQLBuilder
+}
diff --git a/test/files/pos/t2741/2741-1.scala b/test/files/pos/t2741/2741-1.scala
new file mode 100644
index 0000000..7a7ef41
--- /dev/null
+++ b/test/files/pos/t2741/2741-1.scala
@@ -0,0 +1,13 @@
+sealed trait Kleisli[M[_], A, B]
+
+trait PartialApplyKA[T[_[_], _, _], M[_], A] {
+  type Apply[B] = T[M, A, B]
+}
+
+trait MA[M[_], A]
+
+trait MAs {
+  val a: MA[PartialApplyKA[Kleisli, List, String]#Apply, Int] = null
+}
+
+object Scalaz extends MAs
diff --git a/test/files/pos/t2741/2741-2.scala b/test/files/pos/t2741/2741-2.scala
new file mode 100644
index 0000000..d17c76e
--- /dev/null
+++ b/test/files/pos/t2741/2741-2.scala
@@ -0,0 +1,5 @@
+// object Test compiles jointly, but not separately.
+object Test {
+  import Scalaz._
+  Scalaz.a
+}
\ No newline at end of file
diff --git a/test/files/pos/t2794.scala b/test/files/pos/t2794.scala
new file mode 100644
index 0000000..a17edf8
--- /dev/null
+++ b/test/files/pos/t2794.scala
@@ -0,0 +1,9 @@
+class Key[T]
+
+class Entry[T](val k: Key[T], val v: T)
+
+object Entry {
+
+    def makeDefault[T >: Null <: AnyRef] = new Entry[T](new Key[T], null: T)
+
+}
diff --git a/test/files/pos/t2795.scala b/test/files/pos/t2795.scala
new file mode 100644
index 0000000..a4e1b7d
--- /dev/null
+++ b/test/files/pos/t2795.scala
@@ -0,0 +1,17 @@
+package bug1
+
+trait Element[T] {
+}
+
+trait Config {
+  type T <: Element[T]
+  implicit val m: ClassManifest[T]
+  // XXX Following works fine:
+  // type T <: Element[_]
+}
+
+trait Transform { self: Config =>
+  def processBlock(block: Array[T]): Unit = {
+    var X = new Array[T](1)
+  }
+}
diff --git a/test/files/pos/t2797.scala b/test/files/pos/t2797.scala
new file mode 100644
index 0000000..4323664
--- /dev/null
+++ b/test/files/pos/t2797.scala
@@ -0,0 +1,9 @@
+class MyVector[A] {
+  def map[B](f: A => B): MyVector[B] = error("")
+}
+
+object Test {
+  def unzip[B, C](_this: MyVector[(B, C)]): (MyVector[B], MyVector[C]) = {
+    (_this.map{ bc => bc._1 }, _this.map{ bc => bc._2 })
+  }
+}
\ No newline at end of file
diff --git a/test/files/pos/t2799.flags b/test/files/pos/t2799.flags
new file mode 100644
index 0000000..d1b831e
--- /dev/null
+++ b/test/files/pos/t2799.flags
@@ -0,0 +1 @@
+-deprecation -Xfatal-warnings
\ No newline at end of file
diff --git a/test/files/pos/t2799.scala b/test/files/pos/t2799.scala
new file mode 100644
index 0000000..fe93c0e
--- /dev/null
+++ b/test/files/pos/t2799.scala
@@ -0,0 +1 @@
+ at deprecated("hi mom") case class Bob ()
diff --git a/test/files/pos/t2809.scala b/test/files/pos/t2809.scala
new file mode 100644
index 0000000..1f68b0b
--- /dev/null
+++ b/test/files/pos/t2809.scala
@@ -0,0 +1,20 @@
+package p1 {
+  abstract class T1 {
+    protected def bug(p: Int = 1): Int // without 'protected' compiles fine
+  }
+}
+package p2 { // all being in the same package compiles fine
+  import p1._
+  abstract class T2 extends T1 {
+    class A {
+      bug()
+    }
+  }
+
+  abstract class T3 extends T2 {
+    class A {
+      bug()
+    }
+  }
+}
+
diff --git a/test/files/pos/t2810.scala b/test/files/pos/t2810.scala
new file mode 100644
index 0000000..c85eca1
--- /dev/null
+++ b/test/files/pos/t2810.scala
@@ -0,0 +1,8 @@
+
+
+
+
+object Test {
+  val closeable1: { def close(): Unit } = new scala.io.Source { val iter: Iterator[Char] = "".iterator }
+  val closeable2: { def close(): Unit } = new java.io.Closeable { def close() = {} }
+}
diff --git a/test/files/pos/t2868.cmds b/test/files/pos/t2868.cmds
new file mode 100644
index 0000000..ed8124a
--- /dev/null
+++ b/test/files/pos/t2868.cmds
@@ -0,0 +1,3 @@
+javac Jann.java Nest.java
+scalac pick_1.scala
+scalac test_2.scala
diff --git a/test/files/pos/t2868/Jann.java b/test/files/pos/t2868/Jann.java
new file mode 100644
index 0000000..f5b68de
--- /dev/null
+++ b/test/files/pos/t2868/Jann.java
@@ -0,0 +1,5 @@
+public @interface Jann {
+    public String str();
+    public Nest inn();
+    public int[] arr();
+}
diff --git a/test/files/pos/t2868/Nest.java b/test/files/pos/t2868/Nest.java
new file mode 100644
index 0000000..5365229
--- /dev/null
+++ b/test/files/pos/t2868/Nest.java
@@ -0,0 +1,3 @@
+public @interface Nest {
+    public int value();
+}
diff --git a/test/files/pos/t2868/pick_1.scala b/test/files/pos/t2868/pick_1.scala
new file mode 100644
index 0000000..e91728e
--- /dev/null
+++ b/test/files/pos/t2868/pick_1.scala
@@ -0,0 +1,7 @@
+class ann(s: String) extends StaticAnnotation
+class pick {
+  final val s = "bang!"
+  @ann("bang!") def foo = 1
+  @Jann(str = "bang!", inn = new Nest(1), arr = Array(1, 2)) def bar = 2
+  @Jann(str = "bang!", inn = new Nest(1), arr = Array(1, 2)) def baz = 3
+}
diff --git a/test/files/pos/t2868/test_2.scala b/test/files/pos/t2868/test_2.scala
new file mode 100644
index 0000000..f11ef0f
--- /dev/null
+++ b/test/files/pos/t2868/test_2.scala
@@ -0,0 +1,6 @@
+class test {
+  val l = (new pick).s
+  val u = (new pick).foo
+  val c = (new pick).bar
+  val k = (new pick).baz
+}
diff --git a/test/files/pos/t2913.scala b/test/files/pos/t2913.scala
new file mode 100644
index 0000000..ee86b9e
--- /dev/null
+++ b/test/files/pos/t2913.scala
@@ -0,0 +1,53 @@
+class A {
+  def foo(a: Int) = 0
+}
+
+class RichA {
+  def foo(a: String) = 0
+  def foo(a: String, b: String) = 0
+  def foo() = 0
+}
+
+object Test {
+
+  implicit def AToRichA(a: A) = new RichA
+  
+  val a = new A
+  a.foo()
+  a.foo(1)
+
+  a.foo("")       // Without implicits, a type error regarding invalid argument types is generated at `""`. This is
+                  // the same position as an argument, so the 'second try' typing with an Implicit View is tried, 
+                  // and AToRichA(a).foo("") is found.
+                  //
+                  // My reading of the spec "7.3 Views" is that `a.foo` denotes a member of `a`, so the view should
+                  // not be triggered.
+                  //
+                  // But perhaps the implementation was changed to solve See https://lampsvn.epfl.ch/trac/scala/ticket/1756
+
+  a.foo("a", "b") // Without implicits, a type error regarding invalid arity is generated at `foo(<error>"", "")`.
+                  // Typers#tryTypedApply:3274 only checks if the error is as the same position as `foo`, `"a"`, or `"b"`.
+                  // None of these po
+}
+
+// t0851 is essentially the same:
+object test1 {
+  case class Foo[T,T2](f : (T,T2) => String) extends (((T,T2)) => String){
+    def apply(t : T) = (s:T2) => f(t,s)
+    def apply(p : (T,T2)) = f(p._1,p._2)
+  }
+  implicit def g[T](f : (T,String) => String) = Foo(f)
+  def main(args : Array[String]) : Unit = {
+    val f = (x:Int,s:String) => s + x
+    println(f(1))
+    ()
+  }
+}
+object Main {
+  def main(args : Array[String]) {
+    val fn = (a : Int, str : String) => "a: " + a + ", str: " + str
+    implicit def fx[T](f : (T,String) => String) = (x:T) => f(x,null)
+    println(fn(1))
+    ()  
+  }
+}
diff --git a/test/files/pos/t294.cmds b/test/files/pos/t294.cmds
new file mode 100644
index 0000000..62c9a5a
--- /dev/null
+++ b/test/files/pos/t294.cmds
@@ -0,0 +1,3 @@
+javac Ann.java Ann2.java
+scalac Test_1.scala
+scalac Test_2.scala
diff --git a/test/files/pos/t294/Ann.java b/test/files/pos/t294/Ann.java
new file mode 100644
index 0000000..934ca46
--- /dev/null
+++ b/test/files/pos/t294/Ann.java
@@ -0,0 +1,3 @@
+public @interface Ann {
+    public Ann2[] nested();
+}
diff --git a/test/files/pos/t294/Ann2.java b/test/files/pos/t294/Ann2.java
new file mode 100644
index 0000000..025b79e
--- /dev/null
+++ b/test/files/pos/t294/Ann2.java
@@ -0,0 +1,3 @@
+public @interface Ann2 {
+    public int value();
+}
diff --git a/test/files/pos/t294/Test_1.scala b/test/files/pos/t294/Test_1.scala
new file mode 100644
index 0000000..ff1f34b
--- /dev/null
+++ b/test/files/pos/t294/Test_1.scala
@@ -0,0 +1,7 @@
+// also test pickling of java annotations; Test_2.scala will
+// read this class file
+ at Ann(nested = Array(new Ann2(10))) class Test {
+  @Ann2(100) var ctx: Object = _
+  @Ann(nested = Array()) def foo = 10
+  @Ann(nested = Array(new Ann2(10), new Ann2(23))) val bam = -3
+}
diff --git a/test/files/pos/t294/Test_2.scala b/test/files/pos/t294/Test_2.scala
new file mode 100644
index 0000000..9fb1c6e
--- /dev/null
+++ b/test/files/pos/t294/Test_2.scala
@@ -0,0 +1 @@
+class Test2 extends Test
diff --git a/test/files/pos/t2940/Cycle.java b/test/files/pos/t2940/Cycle.java
new file mode 100644
index 0000000..eef6c23
--- /dev/null
+++ b/test/files/pos/t2940/Cycle.java
@@ -0,0 +1,3 @@
+public interface Cycle<T extends Cycle<?>> {
+    void doStuff();
+}
\ No newline at end of file
diff --git a/test/files/pos/t2940/Error.scala b/test/files/pos/t2940/Error.scala
new file mode 100644
index 0000000..7c60066
--- /dev/null
+++ b/test/files/pos/t2940/Error.scala
@@ -0,0 +1,12 @@
+abstract class Error {
+	val c: Cycle[_]
+}
+
+object Test {
+  trait Quux[T] extends Cycle[Quux[T]]
+  val x = new Quux[Int] { def doStuff() { } }
+  
+  def main(args: Array[String]): Unit = {
+        
+  }
+}
diff --git a/test/files/pos/t2956/BeanDefinitionVisitor.java b/test/files/pos/t2956/BeanDefinitionVisitor.java
new file mode 100644
index 0000000..2ff5daa
--- /dev/null
+++ b/test/files/pos/t2956/BeanDefinitionVisitor.java
@@ -0,0 +1,6 @@
+import java.util.Map;
+public class BeanDefinitionVisitor {
+	@SuppressWarnings("unchecked")
+	protected void visitMap(Map<?, ?> mapVal) {
+	}
+}
diff --git a/test/files/pos/t2956/t2956.scala b/test/files/pos/t2956/t2956.scala
new file mode 100644
index 0000000..eb6e817
--- /dev/null
+++ b/test/files/pos/t2956/t2956.scala
@@ -0,0 +1,7 @@
+import scala.collection.JavaConversions._
+
+class Outer {
+  protected class Inner extends BeanDefinitionVisitor {
+    protected def visitMap(mapVal: Map[_, _]): Unit = ()
+  }
+}
\ No newline at end of file
diff --git a/test/files/pos/t2994a.scala b/test/files/pos/t2994a.scala
new file mode 100644
index 0000000..f2d57c3
--- /dev/null
+++ b/test/files/pos/t2994a.scala
@@ -0,0 +1,27 @@
+object Naturals {
+  trait NAT {
+    type a[s[_ <: NAT] <: NAT, z <: NAT] <: NAT
+    type v = a[SUCC, ZERO]
+  }
+  final class ZERO extends NAT {
+    type a[s[_ <: NAT] <: NAT, z <: NAT] = z
+  }
+  final class SUCC[n <: NAT] extends NAT {
+    type a[s[_ <: NAT] <: NAT, z <: NAT] = s[n#a[s, z]]
+  }
+  type _0 = ZERO
+  type _1 = SUCC[_0]
+  type _2 = SUCC[_1]
+  type _3 = SUCC[_2]
+  type _4 = SUCC[_3]
+  type _5 = SUCC[_4]
+  type _6 = SUCC[_5]
+
+  
+  // crashes scala-2.8.0 beta1  
+  trait MUL[n <: NAT, m <: NAT] extends NAT {
+    trait curry[n[_[_], _], s[_]] { type f[z <: NAT] = n[s, z] }
+    type a[s[_ <: NAT] <: NAT, z <: NAT] = n#a[curry[m#a, s]#f, z]
+  }
+
+}
\ No newline at end of file
diff --git a/test/files/pos/t2994b.scala b/test/files/pos/t2994b.scala
new file mode 100644
index 0000000..c9d9cc8
--- /dev/null
+++ b/test/files/pos/t2994b.scala
@@ -0,0 +1,7 @@
+object Test {
+  trait Bar[X[_]]
+  trait Baz[S[_] <: Bar[S]] {
+    type Apply[T]
+  }
+  trait Foo[V[_] <: Bar[V]] extends Bar[Baz[V]#Apply]
+}
\ No newline at end of file
diff --git a/test/files/pos/t3037.scala b/test/files/pos/t3037.scala
new file mode 100644
index 0000000..b71ffe0
--- /dev/null
+++ b/test/files/pos/t3037.scala
@@ -0,0 +1,13 @@
+package test
+
+object A {
+  println(("a" match {
+    case "a" => 1
+    case _ => "a"
+  }).asInstanceOf[Object])
+  def foo[T](x: T) = x
+  var x: Int = 1
+  var y: Long = 1L
+  x = foo(x)
+  y = foo(y)
+}
diff --git a/test/files/pos/t3071.scala b/test/files/pos/t3071.scala
new file mode 100644
index 0000000..7e14432
--- /dev/null
+++ b/test/files/pos/t3071.scala
@@ -0,0 +1,7 @@
+class A (val i: Int) {
+  def copy (i: Int = this.i): A = new A(i)
+}
+
+class B (val j: Int) extends A(1) {
+  override def copy (j: Int = this.j): B = new B(j)
+}
diff --git a/test/files/pos/t3076/C2.scala b/test/files/pos/t3076/C2.scala
new file mode 100644
index 0000000..d08f9ee
--- /dev/null
+++ b/test/files/pos/t3076/C2.scala
@@ -0,0 +1,4 @@
+class C2 {
+  def m1() { new T { } }
+  def m2() { new T { } }
+}
diff --git a/test/files/pos/t3076/T.scala b/test/files/pos/t3076/T.scala
new file mode 100644
index 0000000..b710a29
--- /dev/null
+++ b/test/files/pos/t3076/T.scala
@@ -0,0 +1,2 @@
+trait T { private val z = new C1 }
+private class C1
diff --git a/test/files/pos/t3079.scala b/test/files/pos/t3079.scala
new file mode 100644
index 0000000..4bead34
--- /dev/null
+++ b/test/files/pos/t3079.scala
@@ -0,0 +1,17 @@
+sealed trait Identity[A] {
+  val value: A
+}
+
+trait Coerce[A, B] {
+  def unwrap: (A => B)
+}
+
+object Coerce {
+  def IdentityCoerce[B] = new Coerce[Identity[B], B] {
+     // java.lang.Error: A in trait Identity cannot be instantiated from ?x$1.type
+     def unwrap = _.value
+     
+     // Providing the type of _ works around the problem.
+     //def unwrap = (_: Identity[B]).value 
+  }
+}
\ No newline at end of file
diff --git a/test/files/pos/t3108.scala b/test/files/pos/t3108.scala
new file mode 100644
index 0000000..6a1da73
--- /dev/null
+++ b/test/files/pos/t3108.scala
@@ -0,0 +1,5 @@
+object A {
+  val a: NotNull = ""
+  val b: NotNull = 41
+}
+
diff --git a/test/files/pos/t3152.scala b/test/files/pos/t3152.scala
new file mode 100644
index 0000000..a20428d
--- /dev/null
+++ b/test/files/pos/t3152.scala
@@ -0,0 +1,20 @@
+trait Applicative[M[_]]
+
+sealed trait MA[M[_], A] {
+  def sequence[N[_], B](implicit a: A <:< N[B], n: Applicative[N]): N[M[B]] = error("stub")
+  // def sequence3[N[_], B]()(implicit a: A <:< N[B], n: Applicative[N]): N[M[B]] = error("stub")
+}
+
+object test {
+  implicit def ListMA[A](l: List[A]): MA[List, A] = error("stub")
+  implicit val ao: Applicative[Option] = error("stub")
+
+  /* This compiles OK:
+  (Nil: List[Option[Int]]).sequence3(): Option[List[Int]]
+  */
+
+  // BUG: error: immutable is not an enclosing class
+  // !!! No line number is reported with the error
+  (Nil: List[Option[Int]]).sequence: Option[List[Int]]
+  (List[Option[Int]]()).sequence: Option[List[Int]]
+}
\ No newline at end of file
diff --git a/test/files/pos/t3174.scala b/test/files/pos/t3174.scala
new file mode 100644
index 0000000..c3d90a4
--- /dev/null
+++ b/test/files/pos/t3174.scala
@@ -0,0 +1,14 @@
+object test {
+  def method() {
+    class Foo extends AnyRef {
+      object Color {
+        object Blue
+      }
+
+      class Board {
+        val grid = Color.Blue
+      }
+    }
+    new Foo
+  }
+ }
diff --git a/test/files/pos/t3174b.scala b/test/files/pos/t3174b.scala
new file mode 100644
index 0000000..002c4f0
--- /dev/null
+++ b/test/files/pos/t3174b.scala
@@ -0,0 +1,12 @@
+trait Foo[X] { def foo : Map[String,Foo[X]] }
+
+object Test {
+  def f[T]() : Foo[T] = {
+    class Anon extends Foo[T] { 
+      var foo: Map[String, Foo[T]] = Map[String,Foo[T]]() 
+      //def foo = Map[String,Foo[T]]() 
+      //def foo_=(x: Map[String,Foo[T]]) {}
+    }
+    new Anon
+  }
+}
diff --git a/test/files/pos/t3177.scala b/test/files/pos/t3177.scala
new file mode 100644
index 0000000..21893c9
--- /dev/null
+++ b/test/files/pos/t3177.scala
@@ -0,0 +1,39 @@
+trait InvariantFunctor[F[_]] {
+  def xmap[A, B](ma: F[A], f: A => B, g: B => A): F[B]
+}
+ 
+object InvariantFunctor {
+  import Endo._
+  
+  implicit val EndoInvariantFunctor = new InvariantFunctor[Endo] {
+    def xmap[A, B](ma: Endo[A], f: A => B, g: B => A): Endo[B] = (b: B) => f(ma(g(b)))    
+  }
+  
+  // The definition about fails with:
+  // anon-type.scala:9: error: not found: value b
+  //       def xmap[A, B](ma: Endo[A], f: A => B, g: B => A): Endo[B] = (b: B) => f(ma(g(b)))    
+  //                                                                                     ^
+  //   anon-type.scala:8: error: not found: type $anon
+  //     implicit val EndoInvariantFunctor = new InvariantFunctor[Endo] {
+  //                                         ^
+
+
+  // These both work:
+  // implicit val EndoInvariantFunctorAscribed: InvariantFunctor[Endo] = new InvariantFunctor[Endo] {
+  //   def xmap[A, B](ma: Endo[A], f: A => B, g: B => A): Endo[B] = (b: B) => f(ma(g(b)))    
+  // }
+  // 
+  // implicit val EndoInvariantFunctorStubbed = new InvariantFunctor[Endo] {
+  //   def xmap[A, B](ma: Endo[A], f: A => B, g: B => A): Endo[B] = error("stub")
+  // }
+}
+
+trait Endo[X]
+
+object Endo {
+  implicit def EndoTo[A](f: A => A): Endo[A] = new Endo[A] {
+    def apply(a: A) = f(a)
+  }
+
+  implicit def EndoFrom[A](e: Endo[A]): A => A = e.apply(_)
+}
\ No newline at end of file
diff --git a/test/files/pos/t3249/Test.java b/test/files/pos/t3249/Test.java
new file mode 100644
index 0000000..4cc7cb2
--- /dev/null
+++ b/test/files/pos/t3249/Test.java
@@ -0,0 +1,5 @@
+public class Test {
+  public static void meh() {
+    new A<Integer>().f();
+  }
+}
\ No newline at end of file
diff --git a/test/files/pos/t3249/a.scala b/test/files/pos/t3249/a.scala
new file mode 100644
index 0000000..0394464
--- /dev/null
+++ b/test/files/pos/t3249/a.scala
@@ -0,0 +1,11 @@
+class A[U] { def f[T] = { class X extends A[T] } }
+
+
+/*
+$ scalac a.scala
+$ javac -cp .:$SCALA_HOME/lib/scala-library.jar  -Xprint 'A$X$1'
+
+  public class X$1 extends A<java.lang.Object> implements scala.ScalaObject {
+    public X$1(A<U> null);
+  }
+*/
\ No newline at end of file
diff --git a/test/files/pos/t3274.scala b/test/files/pos/t3274.scala
new file mode 100644
index 0000000..dfa6a4e
--- /dev/null
+++ b/test/files/pos/t3274.scala
@@ -0,0 +1,9 @@
+trait A { this: B => 
+  trait X { 
+    class Y1 extends Y
+  } 
+}
+
+trait B extends A {
+  trait Y { def f {} }
+}
\ No newline at end of file
diff --git a/test/files/pos/t3349/AbstractTupleSet.java b/test/files/pos/t3349/AbstractTupleSet.java
new file mode 100644
index 0000000..47b440a
--- /dev/null
+++ b/test/files/pos/t3349/AbstractTupleSet.java
@@ -0,0 +1,9 @@
+public abstract class AbstractTupleSet implements TupleSet {
+  public void addColumn(String name, Class type) {
+    throw new UnsupportedOperationException();
+  }
+
+  public void addColumn(String name, String expr) {
+    throw new UnsupportedOperationException();
+  }    
+}
diff --git a/test/files/pos/t3349/Table.java b/test/files/pos/t3349/Table.java
new file mode 100644
index 0000000..1609367
--- /dev/null
+++ b/test/files/pos/t3349/Table.java
@@ -0,0 +1,9 @@
+public class Table extends AbstractTupleSet {
+  public void addColumn(String name, Class type) {
+    throw new UnsupportedOperationException();
+  }
+
+  public void addColumn(String name, String expr) {
+    throw new UnsupportedOperationException();
+  }
+}
\ No newline at end of file
diff --git a/test/files/pos/t3349/Test.scala b/test/files/pos/t3349/Test.scala
new file mode 100644
index 0000000..8174e4c
--- /dev/null
+++ b/test/files/pos/t3349/Test.scala
@@ -0,0 +1,5 @@
+object Test {
+  val label = "name"
+  val table: Table = error("")
+  table.addColumn( label, label.getClass )
+}
\ No newline at end of file
diff --git a/test/files/pos/t3349/TupleSet.java b/test/files/pos/t3349/TupleSet.java
new file mode 100644
index 0000000..14a073a
--- /dev/null
+++ b/test/files/pos/t3349/TupleSet.java
@@ -0,0 +1,4 @@
+public interface TupleSet {
+    public void addColumn(String name, Class type);
+    public void addColumn(String name, String expr);
+}
\ No newline at end of file
diff --git a/test/files/pos/t3363.scala b/test/files/pos/t3363.scala
new file mode 100644
index 0000000..302f8c4
--- /dev/null
+++ b/test/files/pos/t3363.scala
@@ -0,0 +1,18 @@
+object TestCase { 
+       
+        //now matter if you put (abstract) class or trait it will fail in all cases 
+        trait MapOps[T] 
+         
+        //if fs was reduced to List (generic type with one parameter) then the code compiles 
+        //if you inherit from MapOps[T] instead of MapOps[F] then code compiles fine 
+        implicit def map2ops[T,F](fs: Map[T,F]) = new MapOps[F] { 
+          //if you remove this line, then code compiles 
+	    lazy val m: Manifest[T] = error("just something to make it compile") 
+	    def is(xs: List[T]) = List(xs) 
+	  } 
+	 
+	  def main(args: Array[String]) { 
+	    println(Map(1 -> "2") is List(2)) 
+	  } 
+	 
+	} 
diff --git a/test/files/pos/t3373.scala b/test/files/pos/t3373.scala
new file mode 100644
index 0000000..b4af361
--- /dev/null
+++ b/test/files/pos/t3373.scala
@@ -0,0 +1,11 @@
+class Entry(time: Long) {
+ def getTime: Long = time
+}
+
+object Test {
+  def extractTime(e: Entry) = e.getTime
+
+  implicit val orderEntries = new Ordering[Entry] {
+   def compare(first: Entry, second: Entry) = extractTime(first) compare extractTime(second)
+  }
+}
\ No newline at end of file
diff --git a/test/files/pos/t3374.scala b/test/files/pos/t3374.scala
new file mode 100644
index 0000000..4c02931
--- /dev/null
+++ b/test/files/pos/t3374.scala
@@ -0,0 +1,6 @@
+trait Parent {
+ type Test[A, H[B <: A]]
+}
+trait Sub extends Parent {
+ type Test[AS, HS[B <: AS]] = AS
+}
\ No newline at end of file
diff --git a/test/files/pos/t3384.scala b/test/files/pos/t3384.scala
new file mode 100644
index 0000000..4d4a81d
--- /dev/null
+++ b/test/files/pos/t3384.scala
@@ -0,0 +1,14 @@
+package test
+
+package p {
+  class A(a: String = "")
+}
+
+package object po {
+  type A = p.A
+}
+
+import po._
+class C {
+  val a = new A() //p.A.init$default$1)
+}
diff --git a/test/files/pos/t3404/Base.java b/test/files/pos/t3404/Base.java
new file mode 100644
index 0000000..c5df18c
--- /dev/null
+++ b/test/files/pos/t3404/Base.java
@@ -0,0 +1,3 @@
+abstract class Base {
+  abstract Class foo(Object o);
+}
\ No newline at end of file
diff --git a/test/files/pos/t3404/Derived.scala b/test/files/pos/t3404/Derived.scala
new file mode 100644
index 0000000..16976fe
--- /dev/null
+++ b/test/files/pos/t3404/Derived.scala
@@ -0,0 +1,3 @@
+class Derived extends Base {
+  def foo(a: AnyRef) = classOf[String]
+}
\ No newline at end of file
diff --git a/test/files/pos/t3417.scala b/test/files/pos/t3417.scala
new file mode 100644
index 0000000..d2de160
--- /dev/null
+++ b/test/files/pos/t3417.scala
@@ -0,0 +1,11 @@
+trait X extends NotNull {
+    def foo = 1
+}
+
+trait Y extends Object with NotNull {
+    def bar = 1
+}
+
+class Z extends NotNull
+
+class W extends Object with NotNull
diff --git a/test/files/pos/t3419/B_1.scala b/test/files/pos/t3419/B_1.scala
new file mode 100644
index 0000000..a8ec7ed
--- /dev/null
+++ b/test/files/pos/t3419/B_1.scala
@@ -0,0 +1,3 @@
+trait T[A,B] {
+  type X[a <: A, b <: B] <: B
+}
\ No newline at end of file
diff --git a/test/files/pos/t3419/C_2.scala b/test/files/pos/t3419/C_2.scala
new file mode 100644
index 0000000..da721d2
--- /dev/null
+++ b/test/files/pos/t3419/C_2.scala
@@ -0,0 +1,3 @@
+object F {
+  type S = T[Any,Int] {type X[N <: Int, Acc <: Int] = Acc}
+}
\ No newline at end of file
diff --git a/test/files/pos/t3429/A.scala b/test/files/pos/t3429/A.scala
new file mode 100644
index 0000000..4b70580
--- /dev/null
+++ b/test/files/pos/t3429/A.scala
@@ -0,0 +1,12 @@
+class A {
+  @Test(exc = classOf[Exception])
+  def myTestMethod = 0
+}
+// rytz at chara:~/scala/trunk/sandbox$ javac Test.java 
+// rytz at chara:~/scala/trunk/sandbox$ ../build/pack/bin/scalac A.scala 
+// A.scala:2: error: type mismatch;
+//  found   : java.lang.Class[Exception](classOf[java.lang.Exception])
+//  required: java.lang.Class
+//   @Test(exc = classOf[Exception])
+//                      ^
+// one error found
\ No newline at end of file
diff --git a/test/files/pos/t3429/Test.java b/test/files/pos/t3429/Test.java
new file mode 100644
index 0000000..e7c57c9
--- /dev/null
+++ b/test/files/pos/t3429/Test.java
@@ -0,0 +1,3 @@
+public @interface Test {
+  public Class exc() default Exception.class;
+}
\ No newline at end of file
diff --git a/test/files/pos/t3477.scala b/test/files/pos/t3477.scala
new file mode 100644
index 0000000..660aa55
--- /dev/null
+++ b/test/files/pos/t3477.scala
@@ -0,0 +1,7 @@
+class J3 {
+  def f[K, K1 >: K, V](x: Map[K1, V]): Map[K, V] = error("")
+}
+
+object Test {
+  (new J3).f(Map[Int, Int]())
+}
\ No newline at end of file
diff --git a/test/files/pos/t3486/JTest.java b/test/files/pos/t3486/JTest.java
new file mode 100644
index 0000000..0bf388b
--- /dev/null
+++ b/test/files/pos/t3486/JTest.java
@@ -0,0 +1,3 @@
+public class JTest<A> extends T2<A> {
+  public A m( A a ) { return a; }
+}
\ No newline at end of file
diff --git a/test/files/pos/t3486/test.scala b/test/files/pos/t3486/test.scala
new file mode 100644
index 0000000..544232b
--- /dev/null
+++ b/test/files/pos/t3486/test.scala
@@ -0,0 +1,6 @@
+trait Test[A] {
+  def m( a: A ): A
+  def specified(a:A):A = a
+}
+
+abstract class T2[A] extends Test[A]
\ No newline at end of file
diff --git a/test/files/pos/t3494.scala b/test/files/pos/t3494.scala
new file mode 100644
index 0000000..35a4bcd
--- /dev/null
+++ b/test/files/pos/t3494.scala
@@ -0,0 +1,7 @@
+object Test {
+  def f[T](xs: T*) = ()
+
+  val x = "abc"
+
+  f[x.type](x)
+}
\ No newline at end of file
diff --git a/test/files/pos/t3560.scala b/test/files/pos/t3560.scala
new file mode 100644
index 0000000..3cde971
--- /dev/null
+++ b/test/files/pos/t3560.scala
@@ -0,0 +1,2 @@
+trait Foo[X] { def foo : Map[String,Foo[X]] }
+object T3560 { def f[T]() : Foo[T] = new Foo[T] { var foo = Map[String,Foo[T]]() } }
diff --git a/test/files/pos/t3568.scala b/test/files/pos/t3568.scala
new file mode 100644
index 0000000..0f26e2f
--- /dev/null
+++ b/test/files/pos/t3568.scala
@@ -0,0 +1,46 @@
+import scala.annotation._
+import scala.annotation.unchecked._
+import scala.collection._
+
+
+package object buffer {
+  val broken = new ArrayVec2() // commenting out this line causes the file to compile.
+
+  val works = Class.forName("buffer.ArrayVec2").newInstance().asInstanceOf[ArrayVec2]
+}
+
+package buffer {
+  object Main {
+    // ArrayVec2 can be compiled, instantiated and used.
+    def main(args: Array[String]) { println(works) }
+  }
+  
+  trait ElemType { type Element; type Component <: ElemType }
+  trait Float1 extends ElemType { type Element = Float; type Component = Float1}
+  class Vec2 extends ElemType { type Element = Vec2;  type Component = Float1 }
+
+  abstract class BaseSeq[T <: ElemType, E]
+  extends IndexedSeq[E] with IndexedSeqOptimized[E, IndexedSeq[E]] {
+    def length = 1
+    def apply(i: Int) :E
+  }
+
+  abstract class GenericSeq[T <: ElemType] extends BaseSeq[T, T#Element]
+  trait DataArray[T <: ElemType] extends BaseSeq[T, T#Element]
+  trait DataView[T <: ElemType] extends BaseSeq[T, T#Element]
+  abstract class BaseFloat1 extends BaseSeq[Float1, Float]
+
+  class ArrayFloat1 extends BaseFloat1 with DataArray[Float1] {
+    def apply(i: Int) :Float = 0f
+  }
+
+  class ViewFloat1 extends BaseFloat1 with DataView[Float1] {
+    def apply(i: Int) :Float = 0f
+  }
+
+  class ArrayVec2(val backingSeq: ArrayFloat1)
+  extends GenericSeq[Vec2] with DataArray[Vec2] {
+    def this() = this(new ArrayFloat1)
+    def apply(i: Int) :Vec2 = null
+  }
+}
diff --git a/test/files/pos/t3582.scala b/test/files/pos/t3582.scala
new file mode 100644
index 0000000..e20af5e
--- /dev/null
+++ b/test/files/pos/t3582.scala
@@ -0,0 +1,12 @@
+trait C[A]
+object Test {
+  def ImplicitParamCA[CC[A], A](implicit ev: C[A]) {implicitly[C[A]]} // must use this exact syntax...
+  // error: could not find implicit value for parameter e: C[A]
+}
+// [[syntax trees at end of typer]]
+// abstract trait C#5[A#9116 >: Nothing#5832 <: Any#52] extends scala#33.AnyRef#2780;
+// final object Test#15 extends java.lang.Object#2485 with ScalaObject#1913 {
+//   def ImplicitParamCA#9123[CC#9124[A#10858 >: Nothing#5832 <: Any#52] >: [A#10858]Nothing#5832 <: [A#10858]Any#52, 
+//                            A#9125 >: Nothing#5832 <: Any#52](implicit ev#10856: C#5[A#9127]): Unit#3818
+//         = scala#34.this.Predef#1683.implicitly#8816[C#5[A#10858]]()
+// }
diff --git a/test/files/pos/t3582b.scala b/test/files/pos/t3582b.scala
new file mode 100644
index 0000000..8f0bfb9
--- /dev/null
+++ b/test/files/pos/t3582b.scala
@@ -0,0 +1,5 @@
+object ParamScoping {
+  // scoping worked fine in the result type, but was wrong in body
+  // reason: typedTypeDef needs new context, which was set up by typed1 but not by typedDefDef and typedClassDef
+  def noOverlapFOwithHO[T, G[T]]: G[T] =  null.asInstanceOf[G[T]]
+}
\ No newline at end of file
diff --git a/test/files/pos/t3612.scala b/test/files/pos/t3612.scala
new file mode 100644
index 0000000..d3bcc37
--- /dev/null
+++ b/test/files/pos/t3612.scala
@@ -0,0 +1,6 @@
+trait C
+
+class Outer {
+  object O0 extends C {}
+  object O extends C { self => }
+}
\ No newline at end of file
diff --git a/test/files/pos/t3622/test/AsyncTask.java b/test/files/pos/t3622/test/AsyncTask.java
new file mode 100644
index 0000000..cfcea3f
--- /dev/null
+++ b/test/files/pos/t3622/test/AsyncTask.java
@@ -0,0 +1,5 @@
+package test;
+
+public abstract class AsyncTask<Params, Progress, Result> {
+    protected abstract Result doInBackground(Params... args);
+}
\ No newline at end of file
diff --git a/test/files/pos/t3622/test/MyAsyncTask.java b/test/files/pos/t3622/test/MyAsyncTask.java
new file mode 100644
index 0000000..9ef4947
--- /dev/null
+++ b/test/files/pos/t3622/test/MyAsyncTask.java
@@ -0,0 +1,9 @@
+package test;
+
+public abstract class MyAsyncTask extends AsyncTask<String, String, String> {
+    protected abstract String doInBackground1(String[] args);
+    @Override
+    protected String doInBackground(String... args) {
+        return doInBackground1(new String[]{"dummy"});
+    }
+}
\ No newline at end of file
diff --git a/test/files/pos/t3622/test/Test.scala b/test/files/pos/t3622/test/Test.scala
new file mode 100644
index 0000000..fb82c58
--- /dev/null
+++ b/test/files/pos/t3622/test/Test.scala
@@ -0,0 +1,5 @@
+package test
+
+class Test extends MyAsyncTask {
+  protected[test] def doInBackground1(args: Array[String]): String = ""
+}
\ No newline at end of file
diff --git a/test/files/pos/t3676.scala b/test/files/pos/t3676.scala
new file mode 100644
index 0000000..60c0cea
--- /dev/null
+++ b/test/files/pos/t3676.scala
@@ -0,0 +1,5 @@
+trait SeqLike[+Repr]
+trait Seq extends SeqLike[Seq]
+
+trait MySeq extends Seq with SeqLike[MySub]
+trait MySub extends MySeq
diff --git a/test/files/pos/t3688.scala b/test/files/pos/t3688.scala
new file mode 100644
index 0000000..0ac1cfe
--- /dev/null
+++ b/test/files/pos/t3688.scala
@@ -0,0 +1,9 @@
+import collection.mutable
+import collection.JavaConversions._
+import java.{util => ju}
+
+object Test {
+
+ implicitly[mutable.Map[Int, String] => ju.Dictionary[Int, String]]
+
+}
diff --git a/test/files/pos/t3731.scala b/test/files/pos/t3731.scala
new file mode 100644
index 0000000..7593854
--- /dev/null
+++ b/test/files/pos/t3731.scala
@@ -0,0 +1,13 @@
+object Test{
+  trait ZW[S]{type T}
+  def ZipWith[S, M <: ZW[S]]: M#T = error("ZW")
+
+  // meh must be parameterised to force an asSeenFrom that 
+  // duplicates the refinement in the TR's pre without updating its sym
+  def meh[A] = ZipWith[A, ZW[A]{type T=Stream[A]}]
+
+  meh[Int]: Stream[Int]
+}
+// debugging output in coevolveSym should say:
+// coevolved type T#11029 : Stream#3234[A#9228] to type T#11277 : Stream#3234[A#9227]
+// with Test.ZW#9219[A#9228]{type T#11029 = Stream#3234[A#9228]} -> Test.ZW#9219[A#9227]{type T#11277 = Stream#3234[A#9227]}
diff --git a/test/files/pos/t3777.scala b/test/files/pos/t3777.scala
new file mode 100644
index 0000000..165eeeb
--- /dev/null
+++ b/test/files/pos/t3777.scala
@@ -0,0 +1,7 @@
+object Test {
+  type Point = Map[Symbol, String]
+  type Points = IndexedSeq[Point]
+
+  def makePoints2: Points = IndexedSeq[Point]()
+  val spoints2 = util.Random.shuffle(makePoints2)
+}
diff --git a/test/files/pos/t3859.scala b/test/files/pos/t3859.scala
new file mode 100644
index 0000000..83d4c37
--- /dev/null
+++ b/test/files/pos/t3859.scala
@@ -0,0 +1,4 @@
+class Test {
+  def foo: Unit = bar(Array(): _*)
+  def bar(values: AnyRef*): Unit = ()
+}
\ No newline at end of file
diff --git a/test/files/pos/t3864/scalaz_2.scala b/test/files/pos/t3864/scalaz_2.scala
new file mode 100644
index 0000000..a3f5b69
--- /dev/null
+++ b/test/files/pos/t3864/scalaz_2.scala
@@ -0,0 +1 @@
+object Scalaz extends Tuples
\ No newline at end of file
diff --git a/test/files/pos/t3864/tuples_1.scala b/test/files/pos/t3864/tuples_1.scala
new file mode 100644
index 0000000..1d19af6
--- /dev/null
+++ b/test/files/pos/t3864/tuples_1.scala
@@ -0,0 +1,78 @@
+trait PimpedType[X] {
+  val value: X
+}
+
+trait Tuples {
+
+  
+trait Tuple15W[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O] extends PimpedType[Tuple15[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O]] {
+  def fold[Z](f: => (A, B, C, D, E, F, G, H, I, J, K, L, M, N, O) => Z): Z = {import value._; f(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15)}
+  def toIndexedSeq[Z](implicit ev: value.type <:< Tuple15[Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z]): IndexedSeq[Z] = {val zs = ev(value); import zs._; IndexedSeq(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15)}
+  def mapElements[AA, BB, CC, DD, EE, FF, GG, HH, II, JJ, KK, LL, MM, NN, OO](_1: (A => AA) = identity[A] _, _2: (B => BB) = identity[B] _, _3: (C => CC) = identity[C] _, _4: (D => DD) = identity[D] _, _5: (E => EE) = identity[E] _, _6: (F => FF) = identity[F] _, _7: (G => GG) = identity[G] _, _8: (H => HH) = identity[H] _, _9: (I => II) = identity[I] _, _10: (J => JJ) = identity[J] _, _11: (K => KK) = identity[K] _, _12: (L => LL) = identity[L] _, _13: (M => MM) = identity[M] _, _14: (N [...]
+}
+
+implicit def ToTuple15W[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O](t: (A, B, C, D, E, F, G, H, I, J, K, L, M, N, O)): Tuple15W[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O] = new { val value = t } with Tuple15W[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O]
+
+  
+trait Tuple16W[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P] extends PimpedType[Tuple16[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P]] {
+  def fold[Z](f: => (A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P) => Z): Z = {import value._; f(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16)}
+  def toIndexedSeq[Z](implicit ev: value.type <:< Tuple16[Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z]): IndexedSeq[Z] = {val zs = ev(value); import zs._; IndexedSeq(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16)}
+  def mapElements[AA, BB, CC, DD, EE, FF, GG, HH, II, JJ, KK, LL, MM, NN, OO, PP](_1: (A => AA) = identity[A] _, _2: (B => BB) = identity[B] _, _3: (C => CC) = identity[C] _, _4: (D => DD) = identity[D] _, _5: (E => EE) = identity[E] _, _6: (F => FF) = identity[F] _, _7: (G => GG) = identity[G] _, _8: (H => HH) = identity[H] _, _9: (I => II) = identity[I] _, _10: (J => JJ) = identity[J] _, _11: (K => KK) = identity[K] _, _12: (L => LL) = identity[L] _, _13: (M => MM) = identity[M] _, _14 [...]
+}
+
+implicit def ToTuple16W[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P](t: (A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P)): Tuple16W[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P] = new { val value = t } with Tuple16W[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P]
+
+  
+trait Tuple17W[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q] extends PimpedType[Tuple17[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q]] {
+  def fold[Z](f: => (A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q) => Z): Z = {import value._; f(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17)}
+  def toIndexedSeq[Z](implicit ev: value.type <:< Tuple17[Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z]): IndexedSeq[Z] = {val zs = ev(value); import zs._; IndexedSeq(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17)}
+  def mapElements[AA, BB, CC, DD, EE, FF, GG, HH, II, JJ, KK, LL, MM, NN, OO, PP, QQ](_1: (A => AA) = identity[A] _, _2: (B => BB) = identity[B] _, _3: (C => CC) = identity[C] _, _4: (D => DD) = identity[D] _, _5: (E => EE) = identity[E] _, _6: (F => FF) = identity[F] _, _7: (G => GG) = identity[G] _, _8: (H => HH) = identity[H] _, _9: (I => II) = identity[I] _, _10: (J => JJ) = identity[J] _, _11: (K => KK) = identity[K] _, _12: (L => LL) = identity[L] _, _13: (M => MM) = identity[M] _, [...]
+}
+
+implicit def ToTuple17W[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q](t: (A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q)): Tuple17W[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q] = new { val value = t } with Tuple17W[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q]
+
+  
+trait Tuple18W[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R] extends PimpedType[Tuple18[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R]] {
+  def fold[Z](f: => (A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R) => Z): Z = {import value._; f(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18)}
+  def toIndexedSeq[Z](implicit ev: value.type <:< Tuple18[Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z]): IndexedSeq[Z] = {val zs = ev(value); import zs._; IndexedSeq(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18)}
+  def mapElements[AA, BB, CC, DD, EE, FF, GG, HH, II, JJ, KK, LL, MM, NN, OO, PP, QQ, RR](_1: (A => AA) = identity[A] _, _2: (B => BB) = identity[B] _, _3: (C => CC) = identity[C] _, _4: (D => DD) = identity[D] _, _5: (E => EE) = identity[E] _, _6: (F => FF) = identity[F] _, _7: (G => GG) = identity[G] _, _8: (H => HH) = identity[H] _, _9: (I => II) = identity[I] _, _10: (J => JJ) = identity[J] _, _11: (K => KK) = identity[K] _, _12: (L => LL) = identity[L] _, _13: (M => MM) = identity[M [...]
+}
+
+implicit def ToTuple18W[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R](t: (A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R)): Tuple18W[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R] = new { val value = t } with Tuple18W[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R]
+
+  
+trait Tuple19W[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S] extends PimpedType[Tuple19[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S]] {
+  def fold[Z](f: => (A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S) => Z): Z = {import value._; f(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19)}
+  def toIndexedSeq[Z](implicit ev: value.type <:< Tuple19[Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z]): IndexedSeq[Z] = {val zs = ev(value); import zs._; IndexedSeq(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19)}
+  def mapElements[AA, BB, CC, DD, EE, FF, GG, HH, II, JJ, KK, LL, MM, NN, OO, PP, QQ, RR, SS](_1: (A => AA) = identity[A] _, _2: (B => BB) = identity[B] _, _3: (C => CC) = identity[C] _, _4: (D => DD) = identity[D] _, _5: (E => EE) = identity[E] _, _6: (F => FF) = identity[F] _, _7: (G => GG) = identity[G] _, _8: (H => HH) = identity[H] _, _9: (I => II) = identity[I] _, _10: (J => JJ) = identity[J] _, _11: (K => KK) = identity[K] _, _12: (L => LL) = identity[L] _, _13: (M => MM) = identi [...]
+}
+
+implicit def ToTuple19W[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S](t: (A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S)): Tuple19W[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S] = new { val value = t } with Tuple19W[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S]
+
+  
+trait Tuple20W[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T] extends PimpedType[Tuple20[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T]] {
+  def fold[Z](f: => (A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T) => Z): Z = {import value._; f(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20)}
+  def toIndexedSeq[Z](implicit ev: value.type <:< Tuple20[Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z]): IndexedSeq[Z] = {val zs = ev(value); import zs._; IndexedSeq(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20)}
+  def mapElements[AA, BB, CC, DD, EE, FF, GG, HH, II, JJ, KK, LL, MM, NN, OO, PP, QQ, RR, SS, TT](_1: (A => AA) = identity[A] _, _2: (B => BB) = identity[B] _, _3: (C => CC) = identity[C] _, _4: (D => DD) = identity[D] _, _5: (E => EE) = identity[E] _, _6: (F => FF) = identity[F] _, _7: (G => GG) = identity[G] _, _8: (H => HH) = identity[H] _, _9: (I => II) = identity[I] _, _10: (J => JJ) = identity[J] _, _11: (K => KK) = identity[K] _, _12: (L => LL) = identity[L] _, _13: (M => MM) = id [...]
+}
+
+implicit def ToTuple20W[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T](t: (A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T)): Tuple20W[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T] = new { val value = t } with Tuple20W[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T]
+
+  
+trait Tuple21W[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U] extends PimpedType[Tuple21[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U]] {
+  def fold[Z](f: => (A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U) => Z): Z = {import value._; f(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21)}
+  def toIndexedSeq[Z](implicit ev: value.type <:< Tuple21[Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z]): IndexedSeq[Z] = {val zs = ev(value); import zs._; IndexedSeq(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21)}
+  def mapElements[AA, BB, CC, DD, EE, FF, GG, HH, II, JJ, KK, LL, MM, NN, OO, PP, QQ, RR, SS, TT, UU](_1: (A => AA) = identity[A] _, _2: (B => BB) = identity[B] _, _3: (C => CC) = identity[C] _, _4: (D => DD) = identity[D] _, _5: (E => EE) = identity[E] _, _6: (F => FF) = identity[F] _, _7: (G => GG) = identity[G] _, _8: (H => HH) = identity[H] _, _9: (I => II) = identity[I] _, _10: (J => JJ) = identity[J] _, _11: (K => KK) = identity[K] _, _12: (L => LL) = identity[L] _, _13: (M => MM)  [...]
+}
+
+implicit def ToTuple21W[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U](t: (A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U)): Tuple21W[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U] = new { val value = t } with Tuple21W[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U]
+
+  
+trait Tuple22W[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V] extends PimpedType[Tuple22[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V]] {
+  def fold[Z](f: => (A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V) => Z): Z = {import value._; f(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22)}
+  def toIndexedSeq[Z](implicit ev: value.type <:< Tuple22[Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z, Z]): IndexedSeq[Z] = {val zs = ev(value); import zs._; IndexedSeq(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22)}
+  def mapElements[AA, BB, CC, DD, EE, FF, GG, HH, II, JJ, KK, LL, MM, NN, OO, PP, QQ, RR, SS, TT, UU, VV](_1: (A => AA) = identity[A] _, _2: (B => BB) = identity[B] _, _3: (C => CC) = identity[C] _, _4: (D => DD) = identity[D] _, _5: (E => EE) = identity[E] _, _6: (F => FF) = identity[F] _, _7: (G => GG) = identity[G] _, _8: (H => HH) = identity[H] _, _9: (I => II) = identity[I] _, _10: (J => JJ) = identity[J] _, _11: (K => KK) = identity[K] _, _12: (L => LL) = identity[L] _, _13: (M =>  [...]
+}
+
+implicit def ToTuple22W[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V](t: (A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V)): Tuple22W[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V] = new { val value = t } with Tuple22W[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V]
+}
\ No newline at end of file
diff --git a/test/pending/pos/t425.scala b/test/files/pos/t425.scala
similarity index 100%
rename from test/pending/pos/t425.scala
rename to test/files/pos/t425.scala
diff --git a/test/files/pos/tcpoly_boundedmonad.scala b/test/files/pos/tcpoly_boundedmonad.scala
index 74c9fa7..24a9117 100644
--- a/test/files/pos/tcpoly_boundedmonad.scala
+++ b/test/files/pos/tcpoly_boundedmonad.scala
@@ -16,4 +16,4 @@ class Set[T <: Ordered[T]] extends Monad[T, Set, Ordered] {
               (f: T => Result[S]): Result[S]  = error("TODO") 
               
   def filter(p: T => Boolean): Set[T] = error("TODO")               
-}
\ No newline at end of file
+}
diff --git a/test/files/pos/tcpoly_bounds1.scala b/test/files/pos/tcpoly_bounds1.scala
index 89d16af..142c0b7 100644
--- a/test/files/pos/tcpoly_bounds1.scala
+++ b/test/files/pos/tcpoly_bounds1.scala
@@ -11,4 +11,4 @@ trait ListMonad[a] extends Monad[List, Any, a]
 
 trait MyOrdered[a]
 trait MySet[x <: MyOrdered[x]]
-trait SetMonad[a <: MyOrdered[a]] extends Monad[MySet, MyOrdered, a]
\ No newline at end of file
+trait SetMonad[a <: MyOrdered[a]] extends Monad[MySet, MyOrdered, a]
diff --git a/test/files/pos/tcpoly_checkkinds_mix.scala b/test/files/pos/tcpoly_checkkinds_mix.scala
index 5a962ad..2d265da 100644
--- a/test/files/pos/tcpoly_checkkinds_mix.scala
+++ b/test/files/pos/tcpoly_checkkinds_mix.scala
@@ -7,4 +7,4 @@ trait Iterable[A <: Bound[A], Bound[_]] {
 
 trait OrderedSet[T <: Ordered[T]] extends Iterable[T, Ordered] { 
   type MyType[x <: Ordered[x]] = OrderedSet[x]
-} 
\ No newline at end of file
+} 
diff --git a/test/files/pos/tcpoly_gm.scala b/test/files/pos/tcpoly_gm.scala
index b872ef6..ecaeef9 100644
--- a/test/files/pos/tcpoly_gm.scala
+++ b/test/files/pos/tcpoly_gm.scala
@@ -12,4 +12,4 @@ object foo {
     r.app(y) 
   }
 }
- 
\ No newline at end of file
+ 
diff --git a/test/files/pos/tcpoly_infer_easy.scala b/test/files/pos/tcpoly_infer_easy.scala
new file mode 100644
index 0000000..0f19295
--- /dev/null
+++ b/test/files/pos/tcpoly_infer_easy.scala
@@ -0,0 +1,5 @@
+object Test {
+	def test[CC[+X] <: Iterable[X], A](xs: CC[A]): CC[A] = xs
+	val xs = test(List(1,2))
+	val xs2: List[Int] = test(List(1,2))
+}
diff --git a/test/files/pos/tcpoly_infer_explicit_tuple_wrapper.scala b/test/files/pos/tcpoly_infer_explicit_tuple_wrapper.scala
new file mode 100644
index 0000000..97594d5
--- /dev/null
+++ b/test/files/pos/tcpoly_infer_explicit_tuple_wrapper.scala
@@ -0,0 +1,16 @@
+import scala.collection.generic.GenericTraversableTemplate
+import scala.collection.Iterable
+
+class IterableOps[CC[+B] <: Iterable[B] with GenericTraversableTemplate[B, CC], A1, A2](tuple: (CC[A1], Iterable[A2])) {
+  def unzip: (CC[A1], CC[A2]) = error("foo")
+}
+
+object Test {
+
+  implicit def tupleOfIterableWrapper[CC[+B] <: Iterable[B] with GenericTraversableTemplate[B, CC], A1, A2](tuple: (CC[A1], Iterable[A2])) 
+      = new IterableOps[CC, A1, A2](tuple)
+    
+  val t = (List(1, 2, 3), List(6, 5, 4))
+
+  tupleOfIterableWrapper(t) unzip
+}
\ No newline at end of file
diff --git a/test/files/pos/tcpoly_infer_implicit_tuple_wrapper.scala b/test/files/pos/tcpoly_infer_implicit_tuple_wrapper.scala
new file mode 100644
index 0000000..3073b29
--- /dev/null
+++ b/test/files/pos/tcpoly_infer_implicit_tuple_wrapper.scala
@@ -0,0 +1,18 @@
+import scala.collection.generic.GenericTraversableTemplate
+import scala.collection.Iterable
+
+class IterableOps[CC[+B] <: Iterable[B] with GenericTraversableTemplate[B, CC], A1, A2](tuple: (CC[A1], Iterable[A2])) {
+  def unzip: (CC[A1], CC[A2]) = error("foo")
+}
+
+object Test {
+
+  implicit def tupleOfIterableWrapper[CC[+B] <: Iterable[B] with GenericTraversableTemplate[B, CC], A1, A2](tuple: (CC[A1], Iterable[A2]))
+      = new IterableOps[CC, A1, A2](tuple)
+
+  val t = (List(1, 2, 3), List(6, 5, 4))
+
+  tupleOfIterableWrapper(t) unzip
+
+  t unzip
+}
\ No newline at end of file
diff --git a/test/files/pos/tcpoly_infer_ticket1864.scala b/test/files/pos/tcpoly_infer_ticket1864.scala
new file mode 100644
index 0000000..5874832
--- /dev/null
+++ b/test/files/pos/tcpoly_infer_ticket1864.scala
@@ -0,0 +1,51 @@
+import scala.collection.mutable.{Buffer, ArrayBuffer}
+
+class RichBuffer[T, B[U] <: Buffer[U]](buffer: Buffer[T]) {
+  def mymap[S](f: T => S)(implicit rv: B[S]): B[S] = {
+    buffer.foreach{ e =>
+      rv += f(e)
+    }
+    rv
+  }
+}
+
+object Application {
+  def mymap2[T, B[U] <: Buffer[U], S](buffer: B[T], f: T => S)(implicit rv: B[S]): B[S] = {
+    buffer.foreach{ e =>
+      rv += f(e)
+    }
+    rv
+  }
+
+  def mymap3[T, B <: Buffer[T], S](buffer: B, f: T => T)(implicit rv: B): B = {
+    buffer.foreach{ e =>
+      rv += f(e)
+    }
+    rv
+  }
+
+  def mymap4[T, B[U] <: Buffer[U], S](buffer: B[T])(f: T => S) (implicit rv: B[S]): B[S] = {
+    buffer.foreach{ e =>
+      rv += f(e)
+    }
+    rv
+  }
+
+
+  def main(args: Array[String]) {
+    implicit def richBuffer[T, B[U] <: Buffer[U]](buffer: B[T]): RichBuffer[T, B] =
+      new RichBuffer[T, B](buffer)
+
+    implicit val rv = new ArrayBuffer[Int]
+    val buf = new ArrayBuffer[Int]
+    (1 to 5).foreach(buf += _)
+    buf.mymap(x => x*x)
+    richBuffer(buf).mymap[Int](x => x*x)
+    richBuffer[Int, ArrayBuffer](buf).mymap[Int](x => x*x)
+    mymap2(buf, (x: Int) => x*x)
+    mymap2[Int, ArrayBuffer, Int](buf, (x: Int) => x*x)
+    // mymap3(buf, x => x*x)                                     // compiler error
+    mymap3(buf, (x: Int) => x*x)
+    mymap4(buf)(x => x*x)
+  }
+}
diff --git a/test/files/pos/tcpoly_infer_ticket474.scala b/test/files/pos/tcpoly_infer_ticket474.scala
new file mode 100644
index 0000000..8c9be4d
--- /dev/null
+++ b/test/files/pos/tcpoly_infer_ticket474.scala
@@ -0,0 +1,27 @@
+trait Builder[C[_], T] {
+  def +=(x: T)
+  def finalise: C[T]
+}
+
+trait Buildable[C[_]] {
+  def builder[T]: Builder[C,T]
+}
+
+object Test {
+
+  implicit object buildableList extends Buildable[List] {
+    def builder[T] = new Builder[List,T] {
+      val buf = new scala.collection.mutable.ListBuffer[T]
+      def +=(x: T) = buf += x
+      def finalise = buf.toList
+    }
+  }
+
+  def foo[C[_],T](x: T)(implicit b: Buildable[C]): C[T] = {
+    val builder = b.builder[T]
+    builder += x
+    builder.finalise
+  }
+
+  val l: List[Int] = foo(8)
+}
\ No newline at end of file
diff --git a/test/files/pos/tcpoly_infer_ticket716.scala b/test/files/pos/tcpoly_infer_ticket716.scala
new file mode 100644
index 0000000..cfba07f
--- /dev/null
+++ b/test/files/pos/tcpoly_infer_ticket716.scala
@@ -0,0 +1,26 @@
+
+trait Functor[F[_]] {
+  def fmap[A,B](fun: A=>B, arg:F[A]): F[B]
+}
+object Functor{
+  implicit val ListFunctor: Functor[List] = new Functor[List] {
+    def fmap[A, B](f: A => B, arg: List[A]):List[B] = arg map f
+  }
+
+  final class OOFunctor[F[_],A](arg:F[A])(implicit ftr: Functor[F]) {
+    def fmap[B](fun: A=>B):F[B] = ftr.fmap(fun,arg)
+  }
+
+  //breaks if uncommented
+  implicit def lifttoOO[F[_],A](arg:F[A])(implicit ftr: Functor[F]) = new OOFunctor[F,A](arg)(ftr)
+
+  //works if uncommented
+  //implicit def liftListtoOO[A](arg:List[A]):OOFunctor[List,A] = new OOFunctor[List,A](arg)
+}
+
+object GeneralLiftingDemo extends Application {
+  import Functor._
+  val l = List(1,2,3)
+  val res = l fmap( 1+) // TODO: should not need explicit call to lifttoOO
+  println("OO : " + res )
+}
\ No newline at end of file
diff --git a/test/files/pos/tcpoly_late_method_params.scala b/test/files/pos/tcpoly_late_method_params.scala
index b64a410..c929891 100644
--- a/test/files/pos/tcpoly_late_method_params.scala
+++ b/test/files/pos/tcpoly_late_method_params.scala
@@ -2,4 +2,4 @@ trait Foo {
   def flatMap[RT <: RBound[RT], RBound[_], Result[x <: RBound[x]]]: Result[RT] 
 // bounds for RT& = >: scala.this.Nothing <: RBound&[RT&]
                                    // bounds for x = >: scala.this.Nothing <: RBound&[x]
-}
\ No newline at end of file
+}
diff --git a/test/files/pos/tcpoly_method.scala b/test/files/pos/tcpoly_method.scala
index 7f61c2e..80dc048 100644
--- a/test/files/pos/tcpoly_method.scala
+++ b/test/files/pos/tcpoly_method.scala
@@ -3,4 +3,4 @@ trait Iterable[m[+x], +t] {
   
   def foo[a[x]] = "a"
   val x = foo[List]
-}
\ No newline at end of file
+}
diff --git a/test/files/pos/tcpoly_overloaded.scala b/test/files/pos/tcpoly_overloaded.scala
index 8f3bdcc..4240074 100644
--- a/test/files/pos/tcpoly_overloaded.scala
+++ b/test/files/pos/tcpoly_overloaded.scala
@@ -22,4 +22,4 @@ trait Test {
             (f: T => List[S], foo: Int): List[S]  = error("foo")              
   }
   val l: MList[String] = moo.flatMap[String, List, Any, MList]((x: Int) => new MList("String"))
-}
\ No newline at end of file
+}
diff --git a/test/files/pos/tcpoly_param_scoping.scala b/test/files/pos/tcpoly_param_scoping.scala
index 1019fdf..f8a03f6 100644
--- a/test/files/pos/tcpoly_param_scoping.scala
+++ b/test/files/pos/tcpoly_param_scoping.scala
@@ -5,4 +5,4 @@ trait FOO3[m[A <: B], B]
 class Test {
   def foo[a[x]] = "a"
 }
-//trait Idiom[idi[x]] { def foo: idi[Int]}
\ No newline at end of file
+//trait Idiom[idi[x]] { def foo: idi[Int]}
diff --git a/test/files/pos/tcpoly_return_overriding.scala b/test/files/pos/tcpoly_return_overriding.scala
index 95dcc1e..0814e73 100644
--- a/test/files/pos/tcpoly_return_overriding.scala
+++ b/test/files/pos/tcpoly_return_overriding.scala
@@ -10,4 +10,4 @@ trait Rep[t] {
 // + that substitution (of types&symbols) preserves isHigherKinded when replacing a higher-kinded type with another one
 object foo extends Rep[Unit] {
   def rep[g[x]](implicit gen: Generic[g]): g[Unit]= gen.unit
-}
\ No newline at end of file
+}
diff --git a/test/files/pos/tcpoly_seq.scala b/test/files/pos/tcpoly_seq.scala
index 4c3c866..b5f46f6 100644
--- a/test/files/pos/tcpoly_seq.scala
+++ b/test/files/pos/tcpoly_seq.scala
@@ -16,21 +16,21 @@ trait HOSeq {
   //           is an invariant position -- should probably rule that out?
   trait Iterable[+m[+x], +t] {
     //def unit[a](orig: a): m[a]
-    def elements: Iterator[t]
+    def iterator: Iterator[t]
     
     // construct an empty accumulator that will produce the same structure as this iterable, with elements of type t
     def accumulator[t]: Accumulator[m, t]
                                     
     def filter(p: t => Boolean): m[t] = {
       val buf = accumulator[t]
-      val elems = elements
+      val elems = iterator
       while (elems.hasNext) { val x = elems.next; if (p(x)) buf += x }
       buf.result
     }
     
     def map[s](f: t => s): m[s] = {
       val buf = accumulator[s]
-      val elems = elements
+      val elems = iterator
       while (elems.hasNext) buf += f(elems.next)
       buf.result
     }
@@ -42,9 +42,9 @@ trait HOSeq {
     def flatMap[resColl[+x] <: Iterable[resColl, x], s](f: t => resColl[s])(implicit buf: Accumulator[resColl, s]): resColl[s] = { 
         // TODO:  would a viewbound for resColl[x] be better?
         // -- 2nd-order type params are not yet in scope in view bound
-      val elems = elements
+      val elems = iterator
       while (elems.hasNext) {
-        val elemss: Iterator[s] = f(elems.next).elements
+        val elemss: Iterator[s] = f(elems.next).iterator
         while (elemss.hasNext) buf += elemss.next
       }
       buf.result
@@ -108,7 +108,7 @@ trait HOSeq {
     def head: t
     def tail: List[t]
     def isEmpty: Boolean
-    def elements: Iterator[t] = new Iterator[t] {
+    def iterator: Iterator[t] = new Iterator[t] {
     var these = List.this
     def hasNext: Boolean = !these.isEmpty
     def next: t =
diff --git a/test/files/pos/tcpoly_seq_typealias.scala b/test/files/pos/tcpoly_seq_typealias.scala
index 00e736d..0651ad9 100644
--- a/test/files/pos/tcpoly_seq_typealias.scala
+++ b/test/files/pos/tcpoly_seq_typealias.scala
@@ -18,21 +18,21 @@ trait HOSeq {
     type m[+x] 
     
     //def unit[a](orig: a): m[a]
-    def elements: Iterator[t]
+    def iterator: Iterator[t]
     
     // construct an empty accumulator that will produce the same structure as this iterable, with elements of type t
     def accumulator[t]: Accumulator[m, t]
                                     
     def filter(p: t => Boolean): m[t] = {
       val buf = accumulator[t]
-      val elems = elements
+      val elems = iterator
       while (elems.hasNext) { val x = elems.next; if (p(x)) buf += x }
       buf.result
     }
     
     def map[s](f: t => s): m[s] = {
       val buf = accumulator[s]
-      val elems = elements
+      val elems = iterator
       while (elems.hasNext) buf += f(elems.next)
       buf.result
     }
@@ -44,9 +44,9 @@ trait HOSeq {
     def flatMap[resColl[+x] <: Iterable[x], s](f: t => resColl[s])(implicit buf: Accumulator[resColl, s]): resColl[s] = { 
         // TODO:  would a viewbound for resColl[x] be better?
         // -- 2nd-order type params are not yet in scope in view bound
-      val elems = elements
+      val elems = iterator
       while (elems.hasNext) {
-        val elemss: Iterator[s] = f(elems.next).elements
+        val elemss: Iterator[s] = f(elems.next).iterator
         while (elemss.hasNext) buf += elemss.next
       }
       buf.result
@@ -112,7 +112,7 @@ trait HOSeq {
     def head: t
     def tail: List[t]
     def isEmpty: Boolean
-    def elements: Iterator[t] = new Iterator[t] {
+    def iterator: Iterator[t] = new Iterator[t] {
       var these = List.this
       def hasNext: Boolean = !these.isEmpty
       def next: t =
diff --git a/test/files/pos/tcpoly_subst.scala b/test/files/pos/tcpoly_subst.scala
index af47458..f8ddb9a 100644
--- a/test/files/pos/tcpoly_subst.scala
+++ b/test/files/pos/tcpoly_subst.scala
@@ -1,4 +1,4 @@
 object test {
   def make[m[x], b]: m[b] = error("foo")
   val lst: List[Int] = make[List, Int]
-}
\ No newline at end of file
+}
diff --git a/test/files/pos/tcpoly_ticket2096.scala b/test/files/pos/tcpoly_ticket2096.scala
new file mode 100644
index 0000000..d92589c
--- /dev/null
+++ b/test/files/pos/tcpoly_ticket2096.scala
@@ -0,0 +1,30 @@
+// smallest expression of monad i can find
+trait MBrace[C[X] <: MBrace[C,X],A] {
+ def nest( a : A ) : C[A]
+ def flatten[T <: C[C[A]]]( bsq : T ) : C[A]
+}
+
+// a monad that is a Seq
+trait MBraceSeq[C[X] <: MBrace[C,X] with Seq[X],A] extends MBrace[C,A]
+
+// one of the simplest witnesses of monad i can find
+case class MSequitor[A]( a_ : A* ) extends Seq[A] with MBrace[MSequitor,A]
+{
+ override def nest( a : A ) = new MSequitor[A]( a )
+ override def flatten[T <: MSequitor[MSequitor[A]]]( bsq : T ) : MSequitor[A] = {
+   (new MSequitor[A]( ) /: bsq)( {
+     ( acc : MSequitor[A], e : MSequitor[A] ) => ( acc ++ e ).asInstanceOf[MSequitor[A]]
+   } )
+ }
+ override def length = a_.length
+ override def iterator = a_.iterator
+ override def apply( n : Int ) = a_.apply( n )
+}
+
+//  type arguments [MSequitor,A] do not conform to trait MBraceSeq's type parameter bounds [C[_] <: MBrace[C,A] with Seq[A],A]
+// a statement of the instance relation
+class MBraceSequitor[A] extends MBraceSeq[MSequitor,A] {
+ val empty : MSequitor[A] = new MSequitor[A]( )
+ override def nest( a : A ) = empty.nest( a )
+ override def flatten[T <: MSequitor[MSequitor[A]]]( bsq : T ): MSequitor[A] = empty.flatten( bsq )
+}
\ No newline at end of file
diff --git a/test/files/pos/tcpoly_typeapp.scala b/test/files/pos/tcpoly_typeapp.scala
index 7fb4dca..4cb1da4 100644
--- a/test/files/pos/tcpoly_typeapp.scala
+++ b/test/files/pos/tcpoly_typeapp.scala
@@ -1,4 +1,4 @@
 abstract class x {
  type t[m[x] <: Bound[x], Bound[x]]
  val x: t[scala.collection.mutable.MutableList, Iterable]
-}
\ No newline at end of file
+}
diff --git a/test/files/pos/tcpoly_typesub.scala b/test/files/pos/tcpoly_typesub.scala
index bb29d88..a56d0a2 100644
--- a/test/files/pos/tcpoly_typesub.scala
+++ b/test/files/pos/tcpoly_typesub.scala
@@ -11,4 +11,4 @@ trait TypeSub {
     type c[+y] = y with t
     castSub[c](lt)
   }
-}
\ No newline at end of file
+}
diff --git a/test/files/pos/tcpoly_variance.scala b/test/files/pos/tcpoly_variance.scala
index 9e034ef..b641716 100644
--- a/test/files/pos/tcpoly_variance.scala
+++ b/test/files/pos/tcpoly_variance.scala
@@ -4,4 +4,4 @@ class A[m[+x]] {
 
 class B[m[+x]] extends A[m] {
  override def str: m[String]  = error("foo")
-}
\ No newline at end of file
+}
diff --git a/test/files/pos/tcpoly_wildcards.scala b/test/files/pos/tcpoly_wildcards.scala
index eed0e6f..d3bb86b 100644
--- a/test/files/pos/tcpoly_wildcards.scala
+++ b/test/files/pos/tcpoly_wildcards.scala
@@ -1,3 +1,3 @@
 trait test[b[_,_]] {
   def moo[a[_, _]] = error("a")
-}
\ No newline at end of file
+}
diff --git a/test/files/pos/test2.scala b/test/files/pos/test2.scala
index fe36d07..0dcc16f 100644
--- a/test/files/pos/test2.scala
+++ b/test/files/pos/test2.scala
@@ -2,4 +2,4 @@ import scala._;
 object test2 {
   def f(x: Int): Int = 'a';
   def g(x: Int) = f(f(x));
-}
\ No newline at end of file
+}
diff --git a/test/files/pos/test5refine.scala b/test/files/pos/test5refine.scala
index 771588b..290449c 100644
--- a/test/files/pos/test5refine.scala
+++ b/test/files/pos/test5refine.scala
@@ -72,4 +72,4 @@ object test {
       j.chk_ix(j.val_jx);
       j.chk_ix(val_njx); 
   }
-}
\ No newline at end of file
+}
diff --git a/test/files/pos/thistypes.scala b/test/files/pos/thistypes.scala
index b9e1b46..26339e0 100644
--- a/test/files/pos/thistypes.scala
+++ b/test/files/pos/thistypes.scala
@@ -5,4 +5,4 @@ trait B {
 
 trait C extends B {
   def foo: C.this.I;
-} 
\ No newline at end of file
+} 
diff --git a/test/files/pos/ticket0137.scala b/test/files/pos/ticket0137.scala
index d79be71..72f955f 100644
--- a/test/files/pos/ticket0137.scala
+++ b/test/files/pos/ticket0137.scala
@@ -5,4 +5,4 @@ trait AbsM {
   }
 
   type AM[_] // to trigger the bug, this must be an abstract type member that comes after the reference to it
-}
\ No newline at end of file
+}
diff --git a/test/files/pos/ticket2197.scala b/test/files/pos/ticket2197.scala
new file mode 100644
index 0000000..3c9a04f
--- /dev/null
+++ b/test/files/pos/ticket2197.scala
@@ -0,0 +1,7 @@
+trait PartialType[T[_, _], A] {
+  type Apply[B] = T[A, B]
+}
+
+sealed trait State[S, +A]
+trait Pure[P[_]]
+trait StatePure[X] extends Pure[PartialType[State, X]#Apply]
diff --git a/test/files/pos/ticket2201.scala b/test/files/pos/ticket2201.scala
new file mode 100644
index 0000000..21af170
--- /dev/null
+++ b/test/files/pos/ticket2201.scala
@@ -0,0 +1,8 @@
+class Test
+object Test { implicit def view(x : Test) = 0 }
+
+object Call {
+  def call(implicit view : Test => Int) = view(null)
+  call
+  call
+}
diff --git a/test/files/pos/ticket2251.scala b/test/files/pos/ticket2251.scala
new file mode 100644
index 0000000..7b6efb0
--- /dev/null
+++ b/test/files/pos/ticket2251.scala
@@ -0,0 +1,25 @@
+
+// Martin: I am not sure this is a solvable problem right now. I'll leave it in pending.
+// derived from pos/bug1001
+class A
+trait B[T <: B[T]] extends A
+class C extends B[C]
+class D extends B[D]
+
+class Data {
+  // force computing lub of C and D (printLubs enabled:)
+
+/*
+lub of List(D, C) at depth 2
+  lub of List(D, C) at depth 1
+    lub of List(D, C) at depth 0
+    lub of List(D, C) is A
+  lub of List(D, C) is B[_1] forSome { type _1 >: D with C <: A }
+lub of List(D, C) is B[_2] forSome { type _2 >: D with C{} <: B[_1] forSome { type _1 >: D with C{} <: A } }
+*/
+// --> result = WRONG
+
+  // should be: B[X] forSome {type X <: B[X]} -- can this be done automatically? for now, just detect f-bounded polymorphism and fall back to more coarse approximation
+
+  val data: List[A] = List(new C, new D)
+}
diff --git a/test/files/pos/tryexpr.scala b/test/files/pos/tryexpr.scala
new file mode 100644
index 0000000..c6c2feb
--- /dev/null
+++ b/test/files/pos/tryexpr.scala
@@ -0,0 +1,10 @@
+// stretching more flexible try/catch's legs a bit
+object o {
+  try Integer.parseInt("xxxx") catch { case e => 5 }
+  try 5
+  try try try 10
+  try try try 10 catch { case e => 20 } finally 30
+  try try try 10 catch { case e => 20 } finally 30 finally 40
+  try try try 10 catch { case e => 20 } finally 30 finally 40 finally 50
+  try try try 10 finally 50
+}
diff --git a/test/files/pos/typealias_dubious.scala b/test/files/pos/typealias_dubious.scala
index 4796977..587453a 100644
--- a/test/files/pos/typealias_dubious.scala
+++ b/test/files/pos/typealias_dubious.scala
@@ -12,4 +12,4 @@ abstract class Actor {
 
   def dubiousSend(msg: MailBox#Message) = 
     unstable.send(msg) // in.Message becomes unstable.Message, but that's ok since Message is a concrete type member
-}      
\ No newline at end of file
+}      
diff --git a/test/files/pos/typesafecons.scala b/test/files/pos/typesafecons.scala
index b2a027b..5243280 100644
--- a/test/files/pos/typesafecons.scala
+++ b/test/files/pos/typesafecons.scala
@@ -4,7 +4,7 @@ object Pair {
    type Second <: Pair
  }
 
- case class End extends Pair {
+ class End extends Pair {
    type First = Nothing
    type Second = End
 
diff --git a/test/files/pos/unapplyComplex.scala b/test/files/pos/unapplyComplex.scala
index 886e265..7015834 100644
--- a/test/files/pos/unapplyComplex.scala
+++ b/test/files/pos/unapplyComplex.scala
@@ -1,4 +1,6 @@
-trait Complex extends Product2[Double, Double]
+trait Complex extends Product2[Double, Double] {
+  def canEqual(other: Any) = other.isInstanceOf[Complex]
+}
 
 class ComplexRect(val _1: Double, val _2: Double) extends Complex {
   override def toString = "ComplexRect("+_1+","+_2+")"
diff --git a/test/files/pos/unapplyGeneric.scala b/test/files/pos/unapplyGeneric.scala
index bf88816..987efdd 100644
--- a/test/files/pos/unapplyGeneric.scala
+++ b/test/files/pos/unapplyGeneric.scala
@@ -2,7 +2,9 @@ object Bar {
   def unapply[A,B](bar:Bar[A,B]) = Some(bar)
 }
 
-class Bar[A,B](val _1:A, val _2:B) extends Product2[A,B]
+class Bar[A,B](val _1:A, val _2:B) extends Product2[A,B] {
+  def canEqual(other: Any) = other.isInstanceOf[Bar[_,_]]
+}
 
 object Test {
   new Bar(2, 'a') match {
diff --git a/test/files/pos5/ilya/J.java b/test/files/pos5/ilya/J.java
deleted file mode 100644
index 0794664..0000000
--- a/test/files/pos5/ilya/J.java
+++ /dev/null
@@ -1,14 +0,0 @@
-package test;
-
-class Foo {
-}
-
-class Boo<T extends Foo>{}
-
-class Bar<BooT extends Boo<FooT>, FooT extends Foo>{
- private final int myInt;
-
- public Bar(int i) {
-   myInt = i;
- }
-}
\ No newline at end of file
diff --git a/test/files/pos5/ilya/S.scala b/test/files/pos5/ilya/S.scala
deleted file mode 100644
index 9cf0990..0000000
--- a/test/files/pos5/ilya/S.scala
+++ /dev/null
@@ -1,5 +0,0 @@
-package test
-
-class ScBar[BooT <: Boo[FooT], FooT <: Foo](i: Int) extends Bar[BooT, FooT](i) {
-
-}
diff --git a/test/files/pos5/misc-pos.log b/test/files/pos5/misc-pos.log
deleted file mode 100644
index b921dd4..0000000
--- a/test/files/pos5/misc-pos.log
+++ /dev/null
@@ -1,4 +0,0 @@
-A.java:3: error: illegal cyclic reference involving object A
-import static test.A.STATE.UNDEF;
-       ^
-one error found
diff --git a/test/files/pos5/t1186.java b/test/files/pos5/t1186.java
deleted file mode 100644
index ed137b4..0000000
--- a/test/files/pos5/t1186.java
+++ /dev/null
@@ -1,8 +0,0 @@
-import scala.collection.immutable.Map;
-
-class Test {
-
-  void foo() {
-      Map<String, String> map = null;
-  }
-}
\ No newline at end of file
diff --git a/test/files/pos5/t1230/J.java b/test/files/pos5/t1230/J.java
deleted file mode 100644
index 809344f..0000000
--- a/test/files/pos5/t1230/J.java
+++ /dev/null
@@ -1 +0,0 @@
-class J { public int foo ; }
diff --git a/test/files/pos5/t1230/S.scala b/test/files/pos5/t1230/S.scala
deleted file mode 100644
index 2524f4c..0000000
--- a/test/files/pos5/t1230/S.scala
+++ /dev/null
@@ -1 +0,0 @@
-object S extends Application { (new J).foo = 5 }
diff --git a/test/files/pos5/t1231/J.java b/test/files/pos5/t1231/J.java
deleted file mode 100644
index 1dfc949..0000000
--- a/test/files/pos5/t1231/J.java
+++ /dev/null
@@ -1 +0,0 @@
-enum J { j1 }
\ No newline at end of file
diff --git a/test/files/pos5/t1231/S.scala b/test/files/pos5/t1231/S.scala
deleted file mode 100644
index 6ed1742..0000000
--- a/test/files/pos5/t1231/S.scala
+++ /dev/null
@@ -1 +0,0 @@
-object S extends Application { println(J.j1) }
diff --git a/test/files/pos5/t1232/J.java b/test/files/pos5/t1232/J.java
deleted file mode 100644
index 72e509c..0000000
--- a/test/files/pos5/t1232/J.java
+++ /dev/null
@@ -1,2 +0,0 @@
-package j;
-public class J { public enum E { e1 } }
\ No newline at end of file
diff --git a/test/files/pos5/t1232/J2.java b/test/files/pos5/t1232/J2.java
deleted file mode 100644
index d0ce351..0000000
--- a/test/files/pos5/t1232/J2.java
+++ /dev/null
@@ -1,2 +0,0 @@
-import s.S;
-class J2 { }
\ No newline at end of file
diff --git a/test/files/pos5/t1232/S.scala b/test/files/pos5/t1232/S.scala
deleted file mode 100644
index 3c33bd4..0000000
--- a/test/files/pos5/t1232/S.scala
+++ /dev/null
@@ -1,2 +0,0 @@
-package s
-class S { j.J.E.e1 }
diff --git a/test/files/positions/Anon.scala b/test/files/positions/Anon.scala
new file mode 100644
index 0000000..65eb7ae
--- /dev/null
+++ b/test/files/positions/Anon.scala
@@ -0,0 +1,9 @@
+object Anon {
+  trait Foo {
+	val bar : Int
+  }
+  
+  def foo = new Foo {
+	override val bar = 23
+  }
+}
diff --git a/test/files/jvm5/bug680.check b/test/files/positions/Empty.scala
similarity index 100%
copy from test/files/jvm5/bug680.check
copy to test/files/positions/Empty.scala
diff --git a/test/files/positions/Enclosing1.scala b/test/files/positions/Enclosing1.scala
new file mode 100644
index 0000000..7c8fbaf
--- /dev/null
+++ b/test/files/positions/Enclosing1.scala
@@ -0,0 +1,5 @@
+object Enclosing1 {
+  do {
+	  
+  } while (true)
+}
diff --git a/test/files/positions/Enclosing2.scala b/test/files/positions/Enclosing2.scala
new file mode 100644
index 0000000..502df5d
--- /dev/null
+++ b/test/files/positions/Enclosing2.scala
@@ -0,0 +1,5 @@
+object Enclosing2 {
+
+  class C
+  trait T { this : C => }
+}
diff --git a/test/files/positions/Enclosing3.scala b/test/files/positions/Enclosing3.scala
new file mode 100644
index 0000000..a6fbd4b
--- /dev/null
+++ b/test/files/positions/Enclosing3.scala
@@ -0,0 +1 @@
+class Enclosing3[T <% String] {}
diff --git a/test/files/positions/Enclosing4.scala b/test/files/positions/Enclosing4.scala
new file mode 100644
index 0000000..8337712
--- /dev/null
+++ b/test/files/positions/Enclosing4.scala
@@ -0,0 +1 @@
+//
diff --git a/test/files/positions/ExcludedPrefix1.scala b/test/files/positions/ExcludedPrefix1.scala
new file mode 100644
index 0000000..72d9756
--- /dev/null
+++ b/test/files/positions/ExcludedPrefix1.scala
@@ -0,0 +1,41 @@
+object ExcludedPrefix1 {
+  case
+  class Foo
+
+  case
+  object
+  BLAH
+  
+  val
+  a = 1
+  
+  var
+  b = 2
+  
+  def
+  c = 23
+  
+  private
+  def
+  d = 23
+
+  lazy
+  val
+  e = 23
+  
+  private
+  type
+  f = Int
+  
+  val
+  g,
+  h = 23
+  
+  val
+  (i,
+   j) = (0, 0)
+   
+  val Pair(
+   k,
+   l) = (0, 0)
+}
diff --git a/test/files/positions/MultipleDefs1.scala b/test/files/positions/MultipleDefs1.scala
new file mode 100644
index 0000000..10c0a77
--- /dev/null
+++ b/test/files/positions/MultipleDefs1.scala
@@ -0,0 +1,3 @@
+object MultipleDefs1 {
+  val a, b = 23
+}
diff --git a/test/files/positions/New1.scala b/test/files/positions/New1.scala
new file mode 100644
index 0000000..bd17c0d
--- /dev/null
+++ b/test/files/positions/New1.scala
@@ -0,0 +1,3 @@
+class New1 {
+  val a = new
+}
diff --git a/test/files/positions/Overlap1.scala b/test/files/positions/Overlap1.scala
new file mode 100644
index 0000000..6fda17d
--- /dev/null
+++ b/test/files/positions/Overlap1.scala
@@ -0,0 +1,5 @@
+object Overlap1 {
+	val l = List("foo")
+	val p = true
+	for(e <- l if p) yield e.length
+}
diff --git a/test/files/positions/Overlap2.scala b/test/files/positions/Overlap2.scala
new file mode 100644
index 0000000..4b77d04
--- /dev/null
+++ b/test/files/positions/Overlap2.scala
@@ -0,0 +1,3 @@
+object Overlap2 {
+  for(a <- Some("foo") ; (b, c) = (1, 2)) {}
+}
diff --git a/test/files/positions/Overlap3.scala b/test/files/positions/Overlap3.scala
new file mode 100644
index 0000000..657c12d
--- /dev/null
+++ b/test/files/positions/Overlap3.scala
@@ -0,0 +1,3 @@
+object Overlap3 {
+  val (a, b) = (0, 0) 
+}
diff --git a/test/files/positions/Overlap4.scala b/test/files/positions/Overlap4.scala
new file mode 100644
index 0000000..0049293
--- /dev/null
+++ b/test/files/positions/Overlap4.scala
@@ -0,0 +1,3 @@
+object Overlap4 {
+  val Pair(a, b) = (0, 0)
+}
diff --git a/test/files/positions/Overlap5.scala b/test/files/positions/Overlap5.scala
new file mode 100644
index 0000000..e6f7064
--- /dev/null
+++ b/test/files/positions/Overlap5.scala
@@ -0,0 +1,3 @@
+object Overlap5 {
+  class A[T : List, U]
+}
diff --git a/test/files/positions/Overlap6.scala b/test/files/positions/Overlap6.scala
new file mode 100644
index 0000000..1d63043
--- /dev/null
+++ b/test/files/positions/Overlap6.scala
@@ -0,0 +1,3 @@
+object Overlap6 {
+  class A[T <% String, U]
+}
diff --git a/test/files/positions/Overlap7.scala b/test/files/positions/Overlap7.scala
new file mode 100644
index 0000000..b3dc0d1
--- /dev/null
+++ b/test/files/positions/Overlap7.scala
@@ -0,0 +1,3 @@
+import java.lang.String, java.lang.Object
+
+class Overlap7
diff --git a/test/files/positions/Scaladoc1.scala b/test/files/positions/Scaladoc1.scala
new file mode 100644
index 0000000..9306e2c
--- /dev/null
+++ b/test/files/positions/Scaladoc1.scala
@@ -0,0 +1,8 @@
+object Scaladoc1 {
+  /**
+   * Foo
+   */
+  val (a, b) = (1, 2)
+  a
+  b
+}
diff --git a/test/files/positions/Scaladoc2.scala b/test/files/positions/Scaladoc2.scala
new file mode 100644
index 0000000..78bc4ac
--- /dev/null
+++ b/test/files/positions/Scaladoc2.scala
@@ -0,0 +1,16 @@
+object Scaladoc2 {
+  def f {
+    /**
+     * Foo
+     */
+    def g {}
+    
+    /*
+     * Blah blah
+     */
+    def h{}
+    h
+  }
+  
+  def h {}
+}
diff --git a/test/files/positions/Scaladoc3.scala b/test/files/positions/Scaladoc3.scala
new file mode 100644
index 0000000..bb9d66f
--- /dev/null
+++ b/test/files/positions/Scaladoc3.scala
@@ -0,0 +1,8 @@
+object Scaladoc3 {
+  /**
+   * Foo
+   */
+  import scala.collection.mutable.ArrayBuffer
+  
+  def f {}
+}
diff --git a/test/files/positions/Scaladoc4.scala b/test/files/positions/Scaladoc4.scala
new file mode 100644
index 0000000..f613dda
--- /dev/null
+++ b/test/files/positions/Scaladoc4.scala
@@ -0,0 +1,8 @@
+object Scaladoc4 {
+  /**
+   * Foo
+   */
+  2+2
+  
+  def f {}
+}
diff --git a/test/files/positions/Scaladoc5.scala b/test/files/positions/Scaladoc5.scala
new file mode 100644
index 0000000..c33828c
--- /dev/null
+++ b/test/files/positions/Scaladoc5.scala
@@ -0,0 +1,8 @@
+/**
+ * Foo
+ */
+package positions
+
+object Scaladoc5 {
+
+}
diff --git a/test/files/positions/Scaladoc6.scala b/test/files/positions/Scaladoc6.scala
new file mode 100644
index 0000000..5c230ed
--- /dev/null
+++ b/test/files/positions/Scaladoc6.scala
@@ -0,0 +1,10 @@
+object Scaladoc6 {
+  {
+    /**
+     * Foo
+     */
+    val i = 23
+  }
+  
+  def f {}
+}
diff --git a/test/files/positions/Scaladoc7.scala b/test/files/positions/Scaladoc7.scala
new file mode 100644
index 0000000..6175222
--- /dev/null
+++ b/test/files/positions/Scaladoc7.scala
@@ -0,0 +1,6 @@
+object Scaladoc7 {
+  /**
+   * Foo
+   */
+  val Pair(i, j) = (1, 2)
+}
diff --git a/test/files/positions/Scaladoc8.scala b/test/files/positions/Scaladoc8.scala
new file mode 100644
index 0000000..519d6ca
--- /dev/null
+++ b/test/files/positions/Scaladoc8.scala
@@ -0,0 +1,6 @@
+/**
+ * Foo
+ */
+object Scaladoc8 {
+
+}
diff --git a/test/files/positions/SyntheticNonSynthetic1.scala b/test/files/positions/SyntheticNonSynthetic1.scala
new file mode 100644
index 0000000..0d87c8a
--- /dev/null
+++ b/test/files/positions/SyntheticNonSynthetic1.scala
@@ -0,0 +1,3 @@
+object SyntheticNonSynthetic1 {
+  val foo : List[Class[_ <: Throwable]] = Nil
+}
diff --git a/test/files/positions/SyntheticNonSynthetic2.scala b/test/files/positions/SyntheticNonSynthetic2.scala
new file mode 100644
index 0000000..ba53186
--- /dev/null
+++ b/test/files/positions/SyntheticNonSynthetic2.scala
@@ -0,0 +1,3 @@
+object SyntheticNonSynthetic2 {
+  def foo[A >: Exception] (a : A) {}
+}
diff --git a/test/files/positions/Unpositioned1.scala b/test/files/positions/Unpositioned1.scala
new file mode 100644
index 0000000..7fc520e
--- /dev/null
+++ b/test/files/positions/Unpositioned1.scala
@@ -0,0 +1,3 @@
+object Unpositioned1 {
+  for (a <- Some("foo") ; val b = true) {}
+}
diff --git a/test/files/positions/Unsupported1.scala b/test/files/positions/Unsupported1.scala
new file mode 100644
index 0000000..1dca4ad
--- /dev/null
+++ b/test/files/positions/Unsupported1.scala
@@ -0,0 +1,3 @@
+object Unsupported1 {
+  1 match { case <object>rest }</object> => rest }
+}
diff --git a/test/files/positions/Unsupported2.scala b/test/files/positions/Unsupported2.scala
new file mode 100644
index 0000000..e21df5e
--- /dev/null
+++ b/test/files/positions/Unsupported2.scala
@@ -0,0 +1,5 @@
+object Unsupported2 {
+  for (k <- 0 until xs.xize)
+    for(i = 0 until (xs.size)) {
+    }
+}
diff --git a/test/files/res/bug597.check b/test/files/res/bug597.check
index ed46e87..6cf64f7 100644
--- a/test/files/res/bug597.check
+++ b/test/files/res/bug597.check
@@ -1,4 +1,4 @@
 
 nsc> 
 nsc> 
-nsc> 
\ No newline at end of file
+nsc> 
diff --git a/test/files/res/bug687.check b/test/files/res/bug687.check
index 92e5e4e..ee9520d 100644
--- a/test/files/res/bug687.check
+++ b/test/files/res/bug687.check
@@ -1,11 +1,11 @@
 
 nsc> 
 nsc> bug687/QueryB.scala:3: error: name clash between defined and inherited member:
-method equals:(java.lang.Object)Boolean and
-method equals:(Any)Boolean in class Any
-have same type after erasure: (java.lang.Object)Boolean
+method equals:(o: java.lang.Object)Boolean and
+method equals:(x$1: Any)Boolean in class Any
+have same type after erasure: (o: java.lang.Object)Boolean
   override def equals(o : Object) = false;
                ^
 
 nsc> 
-nsc> 
\ No newline at end of file
+nsc> 
diff --git a/test/files/res/bug687/QueryB.scala b/test/files/res/bug687/QueryB.scala
index ce93005..3e1e0b7 100644
--- a/test/files/res/bug687/QueryB.scala
+++ b/test/files/res/bug687/QueryB.scala
@@ -1,4 +1,4 @@
 package bug687;
 trait Query {
   override def equals(o : Object) = false;
-}
\ No newline at end of file
+}
diff --git a/test/files/res/bug722.check b/test/files/res/bug722.check
index ed46e87..6cf64f7 100644
--- a/test/files/res/bug722.check
+++ b/test/files/res/bug722.check
@@ -1,4 +1,4 @@
 
 nsc> 
 nsc> 
-nsc> 
\ No newline at end of file
+nsc> 
diff --git a/test/files/res/bug722/IfElse.scala b/test/files/res/bug722/IfElse.scala
index a10607a..1515ecf 100644
--- a/test/files/res/bug722/IfElse.scala
+++ b/test/files/res/bug722/IfElse.scala
@@ -1,4 +1,4 @@
 package bug722;
 trait IfEse extends ScanBased {
   object condition extends WhitespaceLink;
-}
\ No newline at end of file
+}
diff --git a/test/files/res/bug735.check b/test/files/res/bug735.check
index ed46e87..6cf64f7 100644
--- a/test/files/res/bug735.check
+++ b/test/files/res/bug735.check
@@ -1,4 +1,4 @@
 
 nsc> 
 nsc> 
-nsc> 
\ No newline at end of file
+nsc> 
diff --git a/test/files/res/bug735/ScalaTyper.scala b/test/files/res/bug735/ScalaTyper.scala
index 29c4bb3..75e7a18 100644
--- a/test/files/res/bug735/ScalaTyper.scala
+++ b/test/files/res/bug735/ScalaTyper.scala
@@ -2,4 +2,4 @@
 package bug735;
 trait ScalaTyper extends ScalaExpressions {
   val values = new ValueFactory {}
-}
\ No newline at end of file
+}
diff --git a/test/files/res/bug743.check b/test/files/res/bug743.check
index ed46e87..6cf64f7 100644
--- a/test/files/res/bug743.check
+++ b/test/files/res/bug743.check
@@ -1,4 +1,4 @@
 
 nsc> 
 nsc> 
-nsc> 
\ No newline at end of file
+nsc> 
diff --git a/test/files/res/bug785.check b/test/files/res/bug785.check
index ed46e87..6cf64f7 100644
--- a/test/files/res/bug785.check
+++ b/test/files/res/bug785.check
@@ -1,4 +1,4 @@
 
 nsc> 
 nsc> 
-nsc> 
\ No newline at end of file
+nsc> 
diff --git a/test/files/res/bug831.check b/test/files/res/bug831.check
index ed46e87..6cf64f7 100644
--- a/test/files/res/bug831.check
+++ b/test/files/res/bug831.check
@@ -1,4 +1,4 @@
 
 nsc> 
 nsc> 
-nsc> 
\ No newline at end of file
+nsc> 
diff --git a/test/files/res/bug831/NewScalaTestXXX.scala b/test/files/res/bug831/NewScalaTestXXX.scala
index e5cc799..a1dafa8 100644
--- a/test/files/res/bug831/NewScalaTestXXX.scala
+++ b/test/files/res/bug831/NewScalaTestXXX.scala
@@ -1,2 +1,2 @@
 package bug831;
-abstract class NewScalaTestXXX extends NewScalaParserXXX;
\ No newline at end of file
+abstract class NewScalaTestXXX extends NewScalaParserXXX;
diff --git a/test/files/run/Course-2002-01.scala b/test/files/run/Course-2002-01.scala
index ac32e45..3426f26 100644
--- a/test/files/run/Course-2002-01.scala
+++ b/test/files/run/Course-2002-01.scala
@@ -1,7 +1,6 @@
 //############################################################################
 // Programmation IV - 2002 - Week 01
 //############################################################################
-// $Id: Course-2002-01.scala 5359 2005-12-16 15:33:49Z dubochet $
 
 object M0 {
 
diff --git a/test/files/run/Course-2002-02.scala b/test/files/run/Course-2002-02.scala
index 046fce3..56d7298 100644
--- a/test/files/run/Course-2002-02.scala
+++ b/test/files/run/Course-2002-02.scala
@@ -1,7 +1,6 @@
 //############################################################################
 // Programmation IV - 2002 - Week 02
 //############################################################################
-// $Id: Course-2002-02.scala 11911 2007-06-05 15:57:59Z odersky $
 
 object M0 {
   def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)
diff --git a/test/files/run/Course-2002-03.scala b/test/files/run/Course-2002-03.scala
index ea5db37..c3b357e 100644
--- a/test/files/run/Course-2002-03.scala
+++ b/test/files/run/Course-2002-03.scala
@@ -1,7 +1,6 @@
 //############################################################################
 // Programmation IV - 2002 - Week 03
 //############################################################################
-// $Id: Course-2002-03.scala 12557 2007-08-17 14:22:22Z michelou $
 
 
 object M0 {
diff --git a/test/files/run/Course-2002-04.scala b/test/files/run/Course-2002-04.scala
index 037a5bb..368e29d 100644
--- a/test/files/run/Course-2002-04.scala
+++ b/test/files/run/Course-2002-04.scala
@@ -1,7 +1,6 @@
 //############################################################################
 // Programmation IV - 2002 - Week 04
 //############################################################################
-// $Id: Course-2002-04.scala 5359 2005-12-16 15:33:49Z dubochet $
 
 object M0 {
 
diff --git a/test/files/run/Course-2002-05.scala b/test/files/run/Course-2002-05.scala
index 0e116de..8ed8e04 100644
--- a/test/files/run/Course-2002-05.scala
+++ b/test/files/run/Course-2002-05.scala
@@ -1,7 +1,6 @@
 //############################################################################
 // Programmation IV - 2002 - Week 05
 //############################################################################
-// $Id: Course-2002-05.scala 15311 2008-06-10 08:46:06Z michelou $
 
 object M0 {
   def partition[a](xs: List[a], pred: a => Boolean): Pair[List[a], List[a]] = {
diff --git a/test/files/run/Course-2002-06.scala b/test/files/run/Course-2002-06.scala
index 60b9f4d..e4fb86a 100644
--- a/test/files/run/Course-2002-06.scala
+++ b/test/files/run/Course-2002-06.scala
@@ -1,7 +1,6 @@
 //############################################################################
 // Programmation IV - 2002 - Week 06
 //############################################################################
-// $Id: Course-2002-06.scala 12557 2007-08-17 14:22:22Z michelou $
 
 /** Two-dimensional vector. */
 class Vector (_x: Double, _y: Double) {
diff --git a/test/files/run/Course-2002-07.scala b/test/files/run/Course-2002-07.scala
index ed5cdef..7848ae3 100644
--- a/test/files/run/Course-2002-07.scala
+++ b/test/files/run/Course-2002-07.scala
@@ -1,7 +1,6 @@
 //############################################################################
 // Programmation IV - 2002 - Week 07
 //############################################################################
-// $Id: Course-2002-07.scala 15311 2008-06-10 08:46:06Z michelou $
 
 object M0 {
 
diff --git a/test/files/run/Course-2002-08.scala b/test/files/run/Course-2002-08.scala
index a1bb6f4..85b0bad 100644
--- a/test/files/run/Course-2002-08.scala
+++ b/test/files/run/Course-2002-08.scala
@@ -1,7 +1,6 @@
 //############################################################################
 // Programmation IV - 2002 - Week 08
 //############################################################################
-// $Id: Course-2002-08.scala 5359 2005-12-16 15:33:49Z dubochet $
 
 import List._;
 
diff --git a/test/files/run/Course-2002-09.scala b/test/files/run/Course-2002-09.scala
index a3670d3..384a91e 100644
--- a/test/files/run/Course-2002-09.scala
+++ b/test/files/run/Course-2002-09.scala
@@ -1,7 +1,6 @@
 //############################################################################
 // Programmation IV - 2002 - Week 09
 //############################################################################
-// $Id: Course-2002-09.scala 15114 2008-05-20 14:25:02Z michelou $
 
 trait Constraint {
   def newValue: Unit;
@@ -82,7 +81,7 @@ class Constant(q: Quantity, v: Double) extends Constraint {
 class Probe(name: String, q: Quantity) extends Constraint {
   def newValue: Unit = printProbe(q.getValue);
   def dropValue: Unit = printProbe(None);
-  private def printProbe(v: Option[double]) {
+  private def printProbe(v: Option[Double]) {
     val vstr = v match {
       case Some(x) => x.toString()
       case None => "?"
@@ -104,7 +103,7 @@ class Quantity() {
       if (v != v1) error("Error! contradiction: " + v + " and " + v1);
     case None =>
       informant = setter; value = Some(v);
-      for (val c <- constraints; !(c == informant)) {
+      for (c <- constraints; if !(c == informant)) {
         c.newValue;
       }
   }
@@ -113,7 +112,7 @@ class Quantity() {
   def forgetValue(retractor: Constraint): Unit = {
     if (retractor == informant) {
       value = None;
-      for (val c <- constraints; !(c == informant)) c.dropValue;
+      for (c <- constraints; if !(c == informant)) c.dropValue;
     }
   }
   def forgetValue: Unit = forgetValue(NoConstraint);
@@ -259,7 +258,7 @@ object M2 {
     };
   }
 
-  def show(x: Option[int], y: Option[Int], z: Option[int]) = {
+  def show(x: Option[Int], y: Option[Int], z: Option[Int]) = {
     Console.print("a = " +set(a,x)+ ", b = " +set(b,y)+ ", c = " +set(c,z));
     Console.println(" => " + a.str + " * " + b.str + " = " + c.str);
     a.forgetValue; b.forgetValue; c.forgetValue;
diff --git a/test/files/run/Course-2002-10.scala b/test/files/run/Course-2002-10.scala
index 1ae4742..e978bc8 100644
--- a/test/files/run/Course-2002-10.scala
+++ b/test/files/run/Course-2002-10.scala
@@ -1,7 +1,6 @@
 //############################################################################
 // Programmation IV - 2002 - Week 10
 //############################################################################
-// $Id: Course-2002-10.scala 15116 2008-05-20 15:43:03Z michelou $
 
 import Math.{Pi, log}
 
diff --git a/test/files/run/Course-2002-13.scala b/test/files/run/Course-2002-13.scala
index bf2bc3a..c016d41 100644
--- a/test/files/run/Course-2002-13.scala
+++ b/test/files/run/Course-2002-13.scala
@@ -1,7 +1,6 @@
 //############################################################################
 // Programmation IV - 2002 - Week 13
 //############################################################################
-// $Id: Course-2002-13.scala 15318 2008-06-10 10:27:45Z michelou $
 
 class Tokenizer(s: String, delimiters: String) extends Iterator[String] {
 
@@ -67,7 +66,7 @@ object Terms {
     override def toString() =
       a + (if (ts.isEmpty) "" else ts.mkString("(", ",", ")"));
     def map(s: Subst): Term = Con(a, ts map (t => t map s));
-    def tyvars = (ts flatMap (t => t.tyvars)).removeDuplicates;
+    def tyvars = (ts flatMap (t => t.tyvars)).distinct;
   }
 
   private var count = 0;
@@ -114,7 +113,7 @@ object Programs {
 
   case class Clause(lhs: Term, rhs: List[Term]) {
     def tyvars =
-      (lhs.tyvars ::: (rhs flatMap (t => t.tyvars))).removeDuplicates;
+      (lhs.tyvars ::: (rhs flatMap (t => t.tyvars))).distinct;
     def newInstance = {
       var s: Subst = List();
       for (val a <- tyvars) { s = Binding(a, newVar(a)) :: s }
diff --git a/test/files/run/MutableListTest.scala b/test/files/run/MutableListTest.scala
new file mode 100644
index 0000000..7043157
--- /dev/null
+++ b/test/files/run/MutableListTest.scala
@@ -0,0 +1,126 @@
+
+
+
+import scala.collection.mutable.MutableList
+
+
+
+class ExtList[T] extends MutableList[T] {
+  def printState {
+    println("Length: " + len)
+    println("Last elem: " + last0.elem)
+    println("First elem: " + first0.elem)
+    println("After first elem: " + first0.next.elem)
+    println("After first: " + first0.next)
+    println("Last: " + last0)
+  }
+}
+
+object Test {
+
+  def main(args: Array[String]) {
+    testEmpty
+    testAddElement
+    testAddFewElements
+    testAddMoreElements
+    testTraversables
+  }
+
+  def testEmpty {
+    val mlist = new MutableList[Int]
+    assert(mlist.isEmpty)
+    assert(mlist.get(0) == None)
+  }
+
+  def testAddElement {
+    val mlist = new MutableList[Int]
+    mlist += 17
+    assert(mlist.nonEmpty)
+    assert(mlist.length == 1)
+    assert(mlist.head == 17)
+    assert(mlist.last == 17)
+    assert(mlist(0) == 17)
+    assert(mlist.tail.isEmpty)
+    assert(mlist.tail.length == 0)
+    mlist(0) = 101
+    assert(mlist(0) == 101)
+    assert(mlist.toList == List(101))
+    assert(mlist.tail.get(0) == None)
+    assert((mlist.tail += 19).head == 19)
+    assert(mlist.tail.length == 0)
+  }
+
+  def testAddFewElements {
+    val mlist = new MutableList[Int]
+    for (i <- 0 until 2) mlist += i
+//    mlist.printState
+    for (i <- 0 until 2) assert(mlist(i) == i)
+    assert(mlist.length == 2)
+    assert(mlist.nonEmpty)
+    assert(mlist.tail.length == 1)
+    assert(mlist.tail.tail.length == 0)
+    assert(mlist.tail.tail.isEmpty)
+  }
+
+  def testAddMoreElements {
+    val mlist = new MutableList[Int]
+    for (i <- 0 until 10) mlist += i * i
+    assert(mlist.nonEmpty)
+    assert(mlist.length == 10)
+    for (i <- 0 until 10) assert(mlist(i) == i * i)
+    assert(mlist(5) == 5 * 5)
+    assert(mlist(9) == 9 * 9)
+    var sometail = mlist
+    for (i <- 0 until 10) {
+      assert(sometail.head == i * i)
+      sometail = sometail.tail
+    }
+    mlist(5) = -25
+    assert(mlist(5) == -25)
+    mlist(0) = -1
+    assert(mlist(0) == -1)
+    mlist(9) = -81
+    assert(mlist(9) == -81)
+    assert(mlist(5) == -25)
+    assert(mlist(0) == -1)
+    assert(mlist.last == -81)
+    mlist.clear
+    assert(mlist.isEmpty)
+    mlist += 1001
+    assert(mlist.head == 1001)
+    mlist += 9999
+    assert(mlist.tail.head == 9999)
+    assert(mlist.last == 9999)
+  }
+
+  def testTraversables {
+    val mlist = new MutableList[Int]
+    for (i <- 0 until 10) mlist += i * i
+    var lst = mlist.drop(5)
+    for (i <- 0 until 5) assert(lst(i) == (i + 5) * (i + 5))
+    lst = lst.take(3)
+    for (i <- 0 until 3) assert(lst(i) == (i + 5) * (i + 5))
+    lst += 129
+    assert(lst(3) == 129)
+    assert(lst.last == 129)
+    assert(lst.length == 4)
+    lst += 7
+    assert(lst.init.last == 129)
+    assert(lst.length == 5)
+    lst.clear
+    assert(lst.length == 0)
+    for (i <- 0 until 5) lst += i
+    assert(lst.reduceLeft(_ + _) == 10)
+  }
+
+}
+
+
+
+
+
+
+
+
+
+
diff --git a/test/files/run/NestedClasses.scala b/test/files/run/NestedClasses.scala
index e485b9c..6db713e 100644
--- a/test/files/run/NestedClasses.scala
+++ b/test/files/run/NestedClasses.scala
@@ -1,7 +1,6 @@
 //############################################################################
 // Test nested classes
 //############################################################################
-// $Id: NestedClasses.scala 5359 2005-12-16 15:33:49Z dubochet $
 
 // The following set of classes tests nasty references to "outer"
 // values.
diff --git a/test/files/run/OrderingTest.scala b/test/files/run/OrderingTest.scala
new file mode 100644
index 0000000..a3eca5f
--- /dev/null
+++ b/test/files/run/OrderingTest.scala
@@ -0,0 +1,36 @@
+object Test extends Application {
+  def test[T](t1 : T, t2 : T)(implicit ord : Ordering[T]) = {
+    val cmp = ord.compare(t1, t2);
+    val cmp2 = ord.compare(t2, t1);
+
+    assert((cmp == 0) == (cmp2 == 0))
+    assert((cmp > 0) == (cmp2 < 0))
+    assert((cmp < 0) == (cmp2 > 0))
+  } 
+
+  def testAll[T](t1 : T, t2 : T)(implicit ord : Ordering[T]) = {
+    assert(ord.compare(t1, t2) < 0)
+    test(t1, t2);
+    test(t1, t1);
+    test(t2, t2);
+  }
+
+  assert(Ordering[String].compare("australopithecus", "brontausaurus") < 0)
+  // assert(Ordering[Unit].compare((), ()) == 0) 
+ 
+  testAll("bar", "foo");
+  testAll[Byte](0, 1);
+  testAll(false, true)
+  testAll(1, 2);
+  testAll(1.0, 2.0);
+  testAll(None, Some(1));
+  testAll[Iterable[Int]](List(1), List(1, 2));
+  testAll[Iterable[Int]](List(1, 2), List(2));
+  testAll((1, "bar"), (1, "foo"))
+  testAll((1, "foo"), (2, "bar"))
+  
+  // sortBy
+  val words = "The quick brown fox jumped over the lazy dog".split(' ')
+  val result = words.sortBy(x => (x.length, x.head))
+  assert(result sameElements Array[String]("The", "dog", "fox", "the", "lazy", "over", "brown", "quick", "jumped"))
+}
diff --git a/test/files/run/QueueTest.scala b/test/files/run/QueueTest.scala
new file mode 100644
index 0000000..2f8ecae
--- /dev/null
+++ b/test/files/run/QueueTest.scala
@@ -0,0 +1,297 @@
+
+
+import scala.collection.mutable.Queue
+
+
+
+
+class ExtQueue[T] extends Queue[T] {
+  def printState {
+    println("-------------------")
+    println("Length: " + len)
+    println("First: " + first0)
+    println("First elem: " + first0.elem)
+    println("After first: " + first0.next)
+  }
+}
+
+object Test {
+  
+  def main(args: Array[String]) {
+    testEmpty
+    testEnqueue
+    testTwoEnqueues
+    testFewEnqueues
+    testMoreEnqueues
+  }
+
+  def testEmpty {
+    val queue = new Queue[Int]
+
+    assert(queue.isEmpty)
+    assert(queue.size == 0)
+    assert(queue.length == 0)
+    assert(queue.dequeueFirst(_ > 500) == None)
+    assert(queue.dequeueAll(_ > 500).isEmpty)
+
+    queue.clear
+    assert(queue.isEmpty)
+    assert(queue.size == 0)
+    assert(queue.length == 0)
+    assert(queue.dequeueFirst(_ > 500) == None)
+    assert(queue.dequeueAll(_ > 500).isEmpty)    
+  }
+
+  def testEnqueue {
+    val queue = new Queue[Int]
+    
+    queue.enqueue(10)
+    assert(queue.nonEmpty)
+    assert(queue.size == 1)
+    assert(queue.length == 1)
+    assert(queue.head == 10)
+    assert(queue(0) == 10)
+    assert(queue.init.isEmpty)
+    assert(queue.tail.isEmpty)
+
+    queue.clear
+    assert(queue.isEmpty)
+    assert(queue.length == 0)
+
+    queue.enqueue(11)
+    assert(queue.nonEmpty)
+    assert(queue.length == 1)
+    assert(queue.head == 11)
+    assert(queue.front == 11)
+    
+    val deq = queue.dequeue
+    assert(deq == 11)
+    assert(queue.isEmpty)
+    assert(queue.length == 0)
+
+    queue.enqueue(12)
+    val pdopt = queue.dequeueFirst(_ > 999)
+    assert(pdopt == None)
+    assert(queue.nonEmpty && queue.length == 1)
+
+    val somepd = queue.dequeueFirst(_ >= 1)
+    assert(somepd == Some(12))
+    assert(queue.isEmpty && queue.length == 0)
+  }
+
+  def testTwoEnqueues {
+    val queue = new ExtQueue[Int]
+    queue.enqueue(30)
+    queue.enqueue(40)
+    
+    assert(queue.length == 2)
+    assert(queue.size == 2)
+    assert(queue.nonEmpty)
+    assert(queue.front == 30)
+//    queue.printState
+    
+    val all = queue.dequeueAll(_ > 20)
+    assert(all.size == 2)
+    assert(all.contains(30))
+    assert(all.contains(40))
+    assert(queue.size == 0)
+    assert(queue.isEmpty)
+  }
+
+  def testFewEnqueues {
+    val queue = new ExtQueue[Int]
+    queue.enqueue(10)
+    queue.enqueue(20)
+    
+    assert(queue.length == 2)
+    assert(queue.nonEmpty)
+    assert(queue.head == 10)
+    assert(queue.last == 20)
+    assert(queue.front == 10)
+//    queue.printState
+    
+    val ten = queue.dequeue
+    assert(ten == 10)
+    assert(queue.length == 1)
+//    queue.printState
+    
+    queue.enqueue(30)
+//    queue.printState
+    val gt25 = queue.dequeueFirst(_ > 25)
+    assert(gt25 == Some(30))
+    assert(queue.nonEmpty)
+    assert(queue.length == 1)
+    assert(queue.head == 20)
+    assert(queue.front == 20)
+//    queue.printState
+
+    queue.enqueue(30)
+//    queue.printState
+    val lt25 = queue.dequeueFirst(_ < 25)
+    assert(lt25 == Some(20))
+    assert(queue.nonEmpty)
+    assert(queue.length == 1)
+//    queue.printState
+
+    queue.enqueue(40)
+//    queue.printState
+    val all = queue.dequeueAll(_ > 20)
+//    queue.printState
+    assert(all.size == 2)
+    assert(all.contains(30))
+    assert(all.contains(40))
+    assert(queue.isEmpty)
+    assert(queue.length == 0)
+    
+    queue.enqueue(50)
+    queue.enqueue(60)
+//    queue.printState
+    val allgt55 = queue.dequeueAll(_ > 55)
+//    println(allgt55)
+//    queue.printState
+    assert(allgt55.size == 1)
+    assert(allgt55.contains(60))
+    assert(queue.length == 1)
+
+    queue.enqueue(70)
+    queue.enqueue(80)
+//    queue.printState
+    val alllt75 = queue.dequeueAll(_ < 75)
+//    queue.printState
+    assert(alllt75.size == 2)
+    assert(alllt75.contains(70))
+    assert(alllt75.contains(50))
+    assert(queue.length == 1)
+    assert(queue.head == 80)
+    assert(queue.last == 80)
+    assert(queue.front == 80)
+  }
+
+  def testMoreEnqueues {
+    val queue = new ExtQueue[Int]
+    for (i <- 0 until 10) queue.enqueue(i * 2)
+
+    for (i <- 0 until 10) {
+      val top = queue.dequeue
+      assert(top == i * 2)
+      assert(queue.length == 10 - i - 1)
+    }
+    assert(queue.isEmpty)
+    assert(queue.length == 0)
+    
+    for (i <- 0 until 10) queue.enqueue(i * i)
+    assert(queue.length == 10)
+    assert(queue.nonEmpty)
+
+    //queue.printState
+    val gt5 = queue.dequeueAll(_ > 4)
+    //queue.printState
+    //println(gt5)
+    assert(gt5.size == 7)
+    assert(queue.length == 3)
+    assert(queue.nonEmpty)
+
+    queue.clear
+    assert(queue.length == 0)
+    assert(queue.isEmpty)
+    
+    for (i <- 0 until 10) queue.enqueue(i)
+    assert(queue.length == 10)
+    
+    val even = queue.dequeueAll(_ % 2 == 0)
+    assert(even.size == 5)
+    assert(even.sameElements(List(0, 2, 4, 6, 8)))
+    assert(queue.length == 5)
+    assert(queue.head == 1)
+    assert(queue.last == 9)
+
+    val odd = queue.dequeueAll(_ %2 == 1)
+    assert(odd.size == 5)
+    assert(queue.length == 0)
+    assert(queue.isEmpty)
+    assert(odd.sameElements(List(1, 3, 5, 7, 9)))
+    
+    for (i <- 0 until 10) queue.enqueue(i * i)
+    assert(queue.last == 81)
+    assert(queue.head == 0)
+    assert(queue.length == 10)
+    
+    val foddgt25 = queue.dequeueFirst(num => num > 25 && num % 2 == 1)
+    assert(foddgt25 == Some(49))
+    assert(queue.length == 9)
+    assert(queue.nonEmpty)
+
+    //queue.printState
+    val lt30 = queue.dequeueAll(_ < 30)
+    //println(lt30)
+    //queue.printState
+    assert(lt30.size == 6)
+    assert(queue.length == 3)
+    
+    val fgt60 = queue.dequeueFirst(_ > 60)
+    assert(fgt60 == Some(64))
+    assert(queue.length == 2)
+    assert(queue.head == 36)
+    assert(queue.last == 81)
+
+    val sgt60 = queue.dequeueFirst(_ > 60)
+    assert(sgt60 == Some(81))
+    assert(queue.length == 1)
+    assert(queue.head == 36)
+    assert(queue.last == 36)
+
+    val nogt60 = queue.dequeueFirst(_ > 60)
+    assert(nogt60 == None)
+    assert(queue.length == 1)
+    assert(queue.nonEmpty)
+    assert(queue.head == 36)
+
+    val gt0 = queue.dequeueFirst(_ > 0)
+    assert(gt0 == Some(36))
+    assert(queue.length == 0)
+    assert(queue.isEmpty)
+
+    for (i <- 0 until 4) queue.enqueue(i)
+    val interv = queue.dequeueAll(n => n > 0 && n < 3)
+    assert(interv.sameElements(List(1, 2)))
+    assert(queue.length == 2)
+    assert(queue.head == 0)
+    assert(queue.last == 3)
+
+    queue.dequeue
+    assert(queue.head == 3)
+    
+    queue.enqueue(9)
+    val three = queue.dequeueFirst(_ < 5)
+    assert(three == Some(3))
+    assert(queue.length == 1)
+    assert(queue.head == 9)
+
+    queue.clear
+    for (i <- -100 until 100) queue.enqueue(i * i + i % 7 + 5)
+    assert(queue.length == 200)
+
+    val manyodds = queue.dequeueAll(_ % 2 == 1)
+    assert((manyodds.size + queue.length) == 200)
+
+    queue.dequeueAll(_ > -10000)
+    assert(queue.isEmpty)
+
+    for (i <- 0 until 100) queue.enqueue(i)
+    val multof3 = queue.dequeueAll(_ % 3 == 0)
+    assert(multof3.size == 34)
+    assert(queue.size == 66)
+    
+    val n98 = queue.dequeueFirst(_ == 98)
+    assert(n98 == Some(98))
+    assert(queue.size == 65)
+    assert(queue.last == 97)
+    assert(queue.head == 1)
+    // well... seems to work
+  }
+
+}
+
+
+
+
diff --git a/test/files/run/ReplacementMatching.scala b/test/files/run/ReplacementMatching.scala
new file mode 100644
index 0000000..faa4641
--- /dev/null
+++ b/test/files/run/ReplacementMatching.scala
@@ -0,0 +1,47 @@
+
+
+
+import util.matching._
+
+
+
+
+object Test {
+  
+  def main(args: Array[String]) {
+    replacementMatching
+    groupsMatching
+  }
+  
+  def replacementMatching {
+    val regex = """\$\{(.+?)\}""".r
+    val replaced = regex.replaceAllIn("Replacing: ${main}. And another method: ${foo}.",
+        (m: util.matching.Regex.Match) => {
+      val identifier = m.group(1)
+      identifier
+    })
+    assert(replaced == "Replacing: main. And another method: foo.")
+    
+    val regex3 = """\$\{(.+?)\}""".r
+    val replaced3 = regex3.replaceSomeIn("Replacing: ${main}. And another: ${foo}.", (m: util.matching.Regex.Match) => {
+      val id = m.group(1)
+      if (id.startsWith("m")) Some(id) else None
+    })
+    assert(replaced3 == "Replacing: main. And another: ${foo}.")
+  }
+  
+  def groupsMatching {
+    val Date = """(\d+)/(\d+)/(\d+)""".r
+    for (Regex.Groups(a, b, c) <- Date findFirstMatchIn "1/1/2001 marks the start of the millenium. 31/12/2000 doesn't.") {
+      assert(a == "1")
+      assert(b == "1")
+      assert(c == "2001")
+    }
+    for (Regex.Groups(a, b, c) <- (Date findAllIn "1/1/2001 marks the start of the millenium. 31/12/2000 doesn't.").matchData) {
+      assert(a == "1" || a == "31")
+      assert(b == "1" || b == "12")
+      assert(c == "2001" || c == "2000")
+    }
+  }
+  
+}
diff --git a/test/files/run/ReverseSeqView.scala b/test/files/run/ReverseSeqView.scala
new file mode 100644
index 0000000..8839406
--- /dev/null
+++ b/test/files/run/ReverseSeqView.scala
@@ -0,0 +1,25 @@
+
+
+
+
+
+
+object Test extends Application {
+  
+  val lstv = List(1, 2, 3).view
+  val lstvr = lstv.reverse
+  assert(lstvr.iterator.toList == List(3, 2, 1))
+  assert(lstvr.reverse == List(1, 2, 3))
+  assert(lstvr.reverseIterator.toList == List(1, 2, 3))
+  assert(lstvr.reverseMap(_ + 1) == List(2, 3, 4))
+  
+}
+
+
+
+
+
+
+
+
+
diff --git a/test/files/run/SymbolsTest.scala b/test/files/run/SymbolsTest.scala
new file mode 100644
index 0000000..cdd68ab
--- /dev/null
+++ b/test/files/run/SymbolsTest.scala
@@ -0,0 +1,283 @@
+
+
+
+
+class Slazz {
+  val s1 = 'myFirstSymbol
+  val s2 = 'mySecondSymbol
+  def s3 = 'myThirdSymbol
+  var s4: Symbol = null
+
+  s4 = 'myFourthSymbol
+}
+
+class Base {
+  val basesymbol = 'symbase
+}
+
+class Sub extends Base {
+  val subsymbol = 'symsub
+}
+
+trait Signs {
+  val ind = 'indication
+  val trace = 'trace
+}
+
+trait Lazy1 {
+  lazy val v1 = "lazy v1"
+  lazy val s1 = 'lazySymbol1
+}
+
+trait Lazy2 {
+  lazy val v2 = "lazy v2"
+  lazy val s2 = 'lazySymbol2
+}
+
+trait Lazy3 {
+  lazy val v3 = "lazy v3"
+  lazy val s3 = 'lazySymbol3
+}
+
+object SingletonOfLazyness {
+  lazy val lazysym = 'lazySymbol
+  lazy val another = 'another
+  lazy val lastone = 'lastone
+}
+
+/*
+ * Tests symbols to see if they work correct.
+ */
+object Test {
+  class Inner {
+    val simba = 'smba
+    var mfs: Symbol = null
+    mfs = Symbol("mfsa")
+  }
+  
+  object InnerObject {
+    val o1 = 'aaa
+    val o2 = 'ddd
+  }
+
+  def aSymbol = 'myFirstSymbol
+  val anotherSymbol = 'mySecondSymbol
+
+  def main(args: Array[String]) {
+    testLiterals
+    testForLoop
+    testInnerClasses
+    testInnerObjects
+    testWithHashMaps
+    testLists
+    testAnonymous
+    testNestedObject
+    testInheritance
+    testTraits
+    testLazyTraits
+    testLazyObjects
+  }
+
+  def testLiterals {
+    val scl = new Slazz
+    assert(scl.s1 == aSymbol)
+    assert(scl.s2 == anotherSymbol)
+    assert(scl.s3 == 'myThirdSymbol)
+    assert(scl.s4 == Symbol.apply("myFourthSymbol"))
+    assert(scl.s1 == Symbol("myFirstSymbol"))
+  }
+
+  def testForLoop {
+    for (i <- 0 until 100) List("Val" + i)
+  }
+
+  def testInnerClasses {
+    val innerPower = new Inner
+    assert(innerPower.simba == 'smba)
+    assert(innerPower.mfs == 'mfsa)
+  }
+
+  def testInnerObjects {
+    assert(InnerObject.o1 == 'aaa)
+    assert(InnerObject.o2 == 'ddd)
+  }
+  
+  def testWithHashMaps {
+    val map = new collection.mutable.HashMap[Symbol, Symbol]
+    map.put(InnerObject.o1, 'smba)
+    map.put(InnerObject.o2, 'mfsa)
+    map.put(Symbol("WeirdKey" + 1), Symbol("Weird" + "Val" + 1))
+    assert(map('aaa) == 'smba)
+    assert(map('ddd) == 'mfsa)
+    assert(map('WeirdKey1) == Symbol("WeirdVal1"))
+    
+    map.clear
+    for (i <- 0 until 100) map.put(Symbol("symKey" + i), Symbol("symVal" + i))
+    assert(map(Symbol("symKey15")) == Symbol("symVal15"))
+    assert(map('symKey22) == 'symVal22)
+    assert(map('symKey73) == 'symVal73)
+    assert(map('symKey56) == 'symVal56)
+    assert(map('symKey91) == 'symVal91)
+  }
+
+  def testLists {
+    var lst: List[Symbol] = Nil
+    for (i <- 0 until 100) lst ::= Symbol("lsym" + (99 - i))
+    assert(lst(0) == 'lsym0)
+    assert(lst(10) == 'lsym10)
+    assert(lst(30) == 'lsym30)
+    assert(lst(40) == 'lsym40)
+    assert(lst(65) == 'lsym65)
+    assert(lst(90) == 'lsym90)
+  }
+
+  def testAnonymous { // TODO complaints classdef can't be found for some reason, runs fine in my case
+    // val anon = () => {
+    //   val simba = 'smba
+    //   simba
+    // }
+    // val an2 = () => {
+    //   object nested {
+    // 	val m = 'mfsa
+    //   }
+    //   nested.m
+    // }
+    // val an3 = () => {
+    //   object nested {
+    // 	val f = () => {
+    // 	  'layered
+    // 	}
+    // 	def gets = f()
+    //   }
+    //   nested.gets
+    // }
+    // val inner = new Inner
+    // assert(anon() == inner.simba)
+    // assert(anon().toString == "'smba")
+    // assert(an2() == 'mfsa)
+    // assert(an3() == Symbol("layered" + ""))
+  }
+
+  def testNestedObject {
+    object nested {
+      def sign = 'sign
+      def insignia = 'insignia
+    }
+    assert(nested.sign == 'sign)
+    assert(nested.insignia == 'insignia)
+    assert(('insignia).toString == "'insignia")
+  }
+
+  def testInheritance {
+    val base = new Base
+    val sub = new Sub
+    assert(base.basesymbol == 'symbase)
+    assert(sub.subsymbol == 'symsub)
+    assert(sub.basesymbol == 'symbase)
+
+    val anon = new Sub {
+      def subsubsymbol = 'symsubsub
+    }
+    assert(anon.subsubsymbol == 'symsubsub)
+    assert(anon.subsymbol == 'symsub)
+    assert(anon.basesymbol == 'symbase)
+    
+    object nested extends Sub {
+      def objsymbol = 'symobj
+    }
+    assert(nested.objsymbol == 'symobj)
+    assert(nested.subsymbol == 'symsub)
+    assert(nested.basesymbol == 'symbase)
+    assert(('symbase).toString == "'symbase")
+  }
+
+  def testTraits {
+    val fromTrait = new AnyRef with Signs {
+      def traitsymbol = 'traitSymbol
+    }
+
+    assert(fromTrait.traitsymbol == 'traitSymbol)
+    assert(fromTrait.ind == 'indication)
+    assert(fromTrait.trace == 'trace)
+    assert(('trace).toString == "'trace")
+
+    trait Compl {
+      val s1 = 's1
+      def s2 = 's2
+      object inner {
+	val s3 = 's3
+	val s4 = 's4
+      }
+    }
+
+    val compl = new Sub with Signs with Compl
+    assert(compl.s1 == 's1)
+    assert(compl.s2 == 's2)
+    assert(compl.inner.s3 == 's3)
+    assert(compl.inner.s4 == 's4)
+    assert(compl.ind == 'indication)
+    assert(compl.trace == 'trace)
+    assert(compl.subsymbol == 'symsub)
+    assert(compl.basesymbol == 'symbase)
+
+    object Local extends Signs with Compl {
+      val s5 = 's5
+      def s6 = 's6
+      object inner2 {
+	val s7 = 's7
+	def s8 = 's8
+      }
+    }
+    assert(Local.s5 == 's5)
+    assert(Local.s6 == 's6)
+    assert(Local.inner2.s7 == 's7)
+    assert(Local.inner2.s8 == 's8)
+    assert(Local.inner.s3 == 's3)
+    assert(Local.inner.s4 == 's4)
+    assert(Local.s1 == 's1)
+    assert(Local.s2 == 's2)
+    assert(Local.trace == 'trace)
+    assert(Local.ind == 'indication)
+    assert(('s8).toString == "'s8")
+  }
+
+  def testLazyTraits {
+    val l1 = new AnyRef with Lazy1
+    val l2 = new AnyRef with Lazy2
+    val l3 = new AnyRef with Lazy3
+
+    l1.v1
+    l2.v2
+    l3.v3
+    assert((l1.s1).toString == "'lazySymbol1")
+    assert(l2.s2 == Symbol("lazySymbol" + 2))
+    assert(l3.s3 == 'lazySymbol3)
+  }
+
+  def testLazyObjects {
+    assert(SingletonOfLazyness.lazysym == 'lazySymbol)
+    assert(SingletonOfLazyness.another == Symbol("ano" + "ther"))
+    assert((SingletonOfLazyness.lastone).toString == "'lastone")
+
+    object nested {
+      lazy val sym1 = 'snested1
+      lazy val sym2 = 'snested2
+    }
+
+    assert(nested.sym1 == 'snested1)
+    assert(nested.sym2 == Symbol("snested" + "2"))
+  }
+
+}
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/test/files/run/adding-growing-set.scala b/test/files/run/adding-growing-set.scala
new file mode 100644
index 0000000..5903813
--- /dev/null
+++ b/test/files/run/adding-growing-set.scala
@@ -0,0 +1,11 @@
+/** This will run a a loooong time if Set's builder copies a
+ *  complete new Set for every element.
+ */
+object Test {
+  def main(args: Array[String]): Unit = {
+    val a = new Array[Long](1000000)
+    (1 to 10000) foreach (i => a(i) = i)
+    val s = collection.mutable.Set(a: _*)
+    assert(s.sum > 0)
+  }
+}
diff --git a/test/files/run/arrayclone.scala b/test/files/run/arrayclone.scala
new file mode 100644
index 0000000..55d8fc3
--- /dev/null
+++ b/test/files/run/arrayclone.scala
@@ -0,0 +1,106 @@
+object Test extends Application{
+  BooleanArrayClone;
+  ByteArrayClone;
+  ShortArrayClone;
+  CharArrayClone;
+  IntArrayClone;
+  LongArrayClone;
+  FloatArrayClone;
+  DoubleArrayClone;
+  ObjectArrayClone;
+  PolymorphicArrayClone;
+}
+
+object BooleanArrayClone{
+  val it : Array[Boolean] = Array(true, false);
+  val cloned = it.clone();
+  assert(cloned.sameElements(it));
+  cloned(0) = false;
+  assert(it(0) == true) 
+}
+
+object ByteArrayClone{
+  val it : Array[Byte] = Array(1, 0);
+  val cloned = it.clone();
+  assert(cloned.sameElements(it));
+  cloned(0) = 0;
+  assert(it(0) == 1) 
+}
+
+object ShortArrayClone{
+  val it : Array[Short] = Array(1, 0);
+  val cloned = it.clone();
+  assert(cloned.sameElements(it));
+  cloned(0) = 0;
+  assert(it(0) == 1) 
+}
+
+object CharArrayClone{
+  val it : Array[Char] = Array(1, 0);
+  val cloned = it.clone();
+  assert(cloned.sameElements(it));
+  cloned(0) = 0;
+  assert(it(0) == 1) 
+}
+
+object IntArrayClone{
+  val it : Array[Int] = Array(1, 0);
+  val cloned = it.clone();
+  assert(cloned.sameElements(it));
+  cloned(0) = 0;
+  assert(it(0) == 1) 
+}
+
+object LongArrayClone{
+  val it : Array[Long] = Array(1, 0);
+  val cloned = it.clone();
+  assert(cloned.sameElements(it));
+  cloned(0) = 0;
+  assert(it(0) == 1) 
+}
+
+object FloatArrayClone{
+  val it : Array[Float] = Array(1, 0);
+  val cloned = it.clone();
+  assert(cloned.sameElements(it));
+  cloned(0) = 0;
+  assert(it(0) == 1) 
+}
+
+object DoubleArrayClone{
+  val it : Array[Double] = Array(1, 0);
+  val cloned = it.clone();
+  assert(cloned.sameElements(it));
+  cloned(0) = 0;
+  assert(it(0) == 1) 
+}
+
+object ObjectArrayClone{
+  val it : Array[String] = Array("1", "0");
+  val cloned = it.clone();
+  assert(cloned.sameElements(it));
+  cloned(0) = "0";
+  assert(it(0) == "1") 
+}
+
+object PolymorphicArrayClone{
+  def testIt[T](it : Array[T], one : T, zero : T) = {
+    val cloned = it.clone();
+    assert(cloned.sameElements(it));
+    cloned(0) = zero;
+    assert(it(0) == one) 
+  }  
+
+  testIt(Array("one", "two"), "one", "two");
+
+  class Mangler[T: Manifest](ts : T*){
+    // this will always be a BoxedAnyArray even after we've unboxed its contents.
+    val it = ts.toArray[T]; 
+  }
+
+  val mangled = new Mangler[Int](0, 1);
+
+  val y : Array[Int] = mangled.it; // make sure it's unboxed
+
+  testIt(mangled.it, 0, 1);
+}
diff --git a/test/files/run/arraycopy.scala b/test/files/run/arraycopy.scala
new file mode 100644
index 0000000..82c34c2
--- /dev/null
+++ b/test/files/run/arraycopy.scala
@@ -0,0 +1,31 @@
+
+
+object Test {
+  def main(args: Array[String]) {
+    val a = new Array[Int](10)
+    val b = new Array[Any](10)
+    for (i <- 0 until 10) b(i) = i
+    
+    Array.copy(b, 3, a, 3, 7)
+    assert(a.toSeq == List(0, 0, 0, 3, 4, 5, 6, 7, 8, 9))
+  }
+}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/test/files/run/arrays.check b/test/files/run/arrays.check
index 658b849..b1f7fae 100644
--- a/test/files/run/arrays.check
+++ b/test/files/run/arrays.check
@@ -1 +1 @@
-checks: 2304
+checks: 2302
diff --git a/test/files/run/arrays.scala b/test/files/run/arrays.scala
index 11b7a7a..cd1cf13 100644
--- a/test/files/run/arrays.scala
+++ b/test/files/run/arrays.scala
@@ -1,7 +1,6 @@
 //############################################################################
 // Arrays
 //############################################################################
-// $Id: arrays.scala 14478 2008-04-02 11:02:48Z michelou $
 
 //############################################################################
 
@@ -159,6 +158,12 @@ object Test {
     c(xs)
   }
 
+  def checkT2368() {
+    val arr = Array(1, 2, 3)
+    arr(0) += 1
+    assert(arr(0) == 2)
+  }
+
   //##########################################################################
   // Values
 
@@ -348,13 +353,6 @@ object Test {
     val x1 = Array.concat(Array(1, 2), Array(3, 4))
     val y1 = Array(1, 2, 3, 4)
     check(x1 sameElements y1, x1.toList, y1.toList)
-
-    val x2 = Array.concat(List(1, 2), List(3, 4))
-    check(x2 sameElements y1, x2.toList, y1.toList)
-
-    val x3 = Array.concat(<a>aaa</a>, <x>xxx</x>)
-    val y3 = <a>aaa</a><x>xxx</x>;
-    check(x3 sameElements y3, x3.toList, y3.toList)
   }
 
   //##########################################################################
@@ -927,6 +925,7 @@ object Test {
 
     checkZip
     checkConcat
+    checkT2368()
 
     //######################################################################
 
@@ -937,3 +936,4 @@ object Test {
 
   //##########################################################################
 }
+
diff --git a/test/files/run/arybufgrow.scala b/test/files/run/arybufgrow.scala
index 4dccd96..9e18435 100644
--- a/test/files/run/arybufgrow.scala
+++ b/test/files/run/arybufgrow.scala
@@ -2,8 +2,8 @@ import scala.collection.mutable._;
 
 object Test extends Application {
   val buf = new ArrayBuffer[String];
-  for(val i <- List.range(0,1000)) {
-    buf + "hello";
+  for (i <- List.range(0,1000)) {
+    buf += "hello";
   }
 
   Console.println("1000 = " + buf.length);
diff --git a/test/files/run/bigDecimalCache.scala b/test/files/run/bigDecimalCache.scala
new file mode 100644
index 0000000..e8ebefe
--- /dev/null
+++ b/test/files/run/bigDecimalCache.scala
@@ -0,0 +1,9 @@
+object Test {  
+  def main(args: Array[String]): Unit = {
+    val bd5a = BigDecimal(5)
+    val mc = java.math.MathContext.DECIMAL32
+    val bd5b = BigDecimal(5,mc)
+    
+    assert(bd5b.mc == mc)
+  }
+}
diff --git a/test/files/run/bitsets-msil.check b/test/files/run/bitsets-msil.check
index 9fefa31..b187571 100644
--- a/test/files/run/bitsets-msil.check
+++ b/test/files/run/bitsets-msil.check
@@ -1,23 +1,23 @@
-ms0 = Set(2)
-ms1 = Set(2)
-ms2 = Set(2)
+ms0 = BitSet(2)
+ms1 = BitSet(2)
+ms2 = BitSet(2)
 mb0 = False
 mb1 = True
 mb2 = False
 xs0 = List(2)
 xs1 = List(2)
 xs2 = List(2)
-ma0 = List(4)
-ma1 = List(4)
-ma2 = List(4)
-mi0 = Set(2)
-mi1 = Set(2)
-mi2 = Set(2)
+ma0 = List(2)
+ma1 = List(2)
+ma2 = List(2)
+mi0 = BitSet(2)
+mi1 = BitSet(2)
+mi2 = BitSet(2)
 
-is0 = Set()
-is1 = Set()
-is2 = Set(2)
-is3 = Set()
+is0 = BitSet()
+is1 = BitSet()
+is2 = BitSet(2)
+is3 = BitSet()
 ib0 = False
 ib1 = False
 ib2 = True
@@ -26,8 +26,8 @@ ys0 = List()
 ys1 = List()
 ys2 = List(2)
 ys3 = List()
-ia0 = List(0)
-ia1 = List(0)
-ia2 = List(4)
+ia0 = List()
+ia1 = List()
+ia2 = List(2)
 ia3 = List()
 
diff --git a/test/files/run/bitsets.check b/test/files/run/bitsets.check
index 01bd685..478de26 100644
--- a/test/files/run/bitsets.check
+++ b/test/files/run/bitsets.check
@@ -1,23 +1,23 @@
-ms0 = Set(2)
-ms1 = Set(2)
-ms2 = Set(2)
+ms0 = BitSet(2)
+ms1 = BitSet(2)
+ms2 = BitSet(2)
 mb0 = false
 mb1 = true
 mb2 = false
 xs0 = List(2)
 xs1 = List(2)
 xs2 = List(2)
-ma0 = List(4)
-ma1 = List(4)
-ma2 = List(4)
-mi0 = Set(2)
-mi1 = Set(2)
-mi2 = Set(2)
+ma0 = List(2)
+ma1 = List(2)
+ma2 = List(2)
+mi0 = BitSet(2)
+mi1 = BitSet(2)
+mi2 = BitSet(2)
 
-is0 = Set()
-is1 = Set()
-is2 = Set(2)
-is3 = Set()
+is0 = BitSet()
+is1 = BitSet()
+is2 = BitSet(2)
+is3 = BitSet()
 ib0 = false
 ib1 = false
 ib2 = true
@@ -26,8 +26,8 @@ ys0 = List()
 ys1 = List()
 ys2 = List(2)
 ys3 = List()
-ia0 = List(0)
-ia1 = List(0)
-ia2 = List(4)
+ia0 = List()
+ia1 = List()
+ia2 = List(2)
 ia3 = List()
 
diff --git a/test/files/run/bitsets.scala b/test/files/run/bitsets.scala
index 9098f44..ac2b8eb 100644
--- a/test/files/run/bitsets.scala
+++ b/test/files/run/bitsets.scala
@@ -1,7 +1,6 @@
 //############################################################################
 // Bitsets
 //############################################################################
-// $Id: bitsets.scala 10576 2007-03-30 13:16:25Z mcdirmid $
 
 //############################################################################
 
@@ -26,13 +25,13 @@ object TestMutable {
   Console.println("mb1 = " + ms1.contains(2))
   Console.println("mb2 = " + ms2.contains(3))
 
-  Console.println("xs0 = " + ms0.elements.toList)
-  Console.println("xs1 = " + ms1.elements.toList)
-  Console.println("xs2 = " + ms2.elements.toList)
+  Console.println("xs0 = " + ms0.iterator.toList)
+  Console.println("xs1 = " + ms1.iterator.toList)
+  Console.println("xs2 = " + ms2.iterator.toList)
 
-  Console.println("ma0 = " + ms0.underlying.toList)
-  Console.println("ma1 = " + ms1.underlying.toList)
-  Console.println("ma2 = " + ms2.underlying.toList)
+  Console.println("ma0 = " + ms0.toList)
+  Console.println("ma1 = " + ms1.toList)
+  Console.println("ma2 = " + ms2.toList)
 
   Console.println("mi0 = " + ms0.toImmutable)
   Console.println("mi1 = " + ms1.toImmutable)
@@ -43,10 +42,10 @@ object TestMutable {
 object TestImmutable {
   import scala.collection.immutable.BitSet
 
-  val is0 = new BitSet(8, 1, null, false)
-  val is1 = new BitSet(8, 1, Array(), false)
-  val is2 = new BitSet(8, 8, Array(4), false)
-  val is3 = new BitSet(0, 0, null, false)
+  val is0 = BitSet()
+  val is1 = BitSet.fromArray(Array())
+  val is2 = BitSet.fromArray(Array(4))
+  val is3 = BitSet.empty
 
   Console.println("is0 = " + is0)
   Console.println("is1 = " + is1)
@@ -58,15 +57,15 @@ object TestImmutable {
   Console.println("ib2 = " + is2.contains(2))
   Console.println("ib3 = " + is3.contains(2))
 
-  Console.println("ys0 = " + is0.elements.toList)
-  Console.println("ys1 = " + is1.elements.toList)
-  Console.println("ys2 = " + is2.elements.toList)
-  Console.println("ys3 = " + is3.elements.toList)
+  Console.println("ys0 = " + is0.iterator.toList)
+  Console.println("ys1 = " + is1.iterator.toList)
+  Console.println("ys2 = " + is2.iterator.toList)
+  Console.println("ys3 = " + is3.iterator.toList)
 
-  Console.println("ia0 = " + is0.underlying.toList)
-  Console.println("ia1 = " + is1.underlying.toList)
-  Console.println("ia2 = " + is2.underlying.toList)
-  Console.println("ia3 = " + is3.underlying.toList)
+  Console.println("ia0 = " + is0.toList)
+  Console.println("ia1 = " + is1.toList)
+  Console.println("ia2 = " + is2.toList)
+  Console.println("ia3 = " + is3.toList)
   Console.println
 }
 
diff --git a/test/files/run/boolexprs.scala b/test/files/run/boolexprs.scala
index b2f4807..4f1c4b1 100644
--- a/test/files/run/boolexprs.scala
+++ b/test/files/run/boolexprs.scala
@@ -1,7 +1,6 @@
 //############################################################################
 // Boolean Expressions
 //############################################################################
-// $Id: boolexprs.scala 15114 2008-05-20 14:25:02Z michelou $
 
 class Counter {
   private var n: Int = 0;
diff --git a/test/files/run/breakout.check b/test/files/run/breakout.check
new file mode 100644
index 0000000..7971496
--- /dev/null
+++ b/test/files/run/breakout.check
@@ -0,0 +1 @@
+2, 3, 4
diff --git a/test/files/run/breakout.scala b/test/files/run/breakout.scala
new file mode 100644
index 0000000..01ea088
--- /dev/null
+++ b/test/files/run/breakout.scala
@@ -0,0 +1,9 @@
+import scala.collection.generic._
+import scala.collection._
+import scala.collection.mutable._
+
+object Test extends Application {
+	val l = List(1, 2, 3)
+	val a: Array[Int] =  l.map(_ + 1)(breakOut)
+	println(a.mkString(", "))
+}
\ No newline at end of file
diff --git a/test/files/run/bridges.scala b/test/files/run/bridges.scala
index 66d7f48..fda86ea 100644
--- a/test/files/run/bridges.scala
+++ b/test/files/run/bridges.scala
@@ -1,7 +1,6 @@
 //############################################################################
 // Test bridge methods
 //############################################################################
-// $Id: bridges.scala 8881 2006-10-06 17:34:40Z odersky $
 
 class A;
 class B;
diff --git a/test/files/run/bug1005.check b/test/files/run/bug1005.check
new file mode 100644
index 0000000..6ec0929
--- /dev/null
+++ b/test/files/run/bug1005.check
@@ -0,0 +1,2 @@
+Halp!
+Halp!
diff --git a/test/files/run/bug1005.scala b/test/files/run/bug1005.scala
new file mode 100644
index 0000000..60129bc
--- /dev/null
+++ b/test/files/run/bug1005.scala
@@ -0,0 +1,19 @@
+object Test
+{
+  class Foo[T](x : Array[AnyRef]) { def bar = x.asInstanceOf[Array[T]] }
+  class Bar[T](x : Array[T]) { def bar = x.asInstanceOf[Array[AnyRef]] }
+
+  object FromMono{
+     def main(args : Array[String]) = (new Foo[AnyRef](Array[AnyRef]("Halp!"))).bar
+  }
+
+  object FromPoly{
+    def main(args : Array[String]) = (new Bar[AnyRef](Array[AnyRef]("Halp!"))).bar
+  }
+  
+  def main(args: Array[String]): Unit = {
+    println(FromMono main null mkString)
+    println(FromPoly main null mkString)
+  }
+}
+
diff --git a/test/files/run/bug1044.scala b/test/files/run/bug1044.scala
new file mode 100644
index 0000000..da20439
--- /dev/null
+++ b/test/files/run/bug1044.scala
@@ -0,0 +1,4 @@
+object Test extends Application {
+  val ducks = Array[AnyRef]("Huey", "Dewey", "Louie");
+  ducks.elements.asInstanceOf[Iterator[String]]
+}
diff --git a/test/files/run/bug1074.check b/test/files/run/bug1074.check
index 7dc0742..ccf1cb1 100644
--- a/test/files/run/bug1074.check
+++ b/test/files/run/bug1074.check
@@ -1,3 +1,3 @@
-q0 = Set(kl, jk, fg, ef, gh, a, cd, de, hj, b, lm, mn)
+q0 = Set(kl, jk, cd, fg, ef, gh, a, de, hj, b, lm, mn)
 q1 = Set() 0
 q2 = Set() 0
diff --git a/test/pending/run/bug1079.check b/test/files/run/bug1079.check
similarity index 100%
rename from test/pending/run/bug1079.check
rename to test/files/run/bug1079.check
diff --git a/test/files/run/bug1079.scala b/test/files/run/bug1079.scala
new file mode 100644
index 0000000..ae8234b
--- /dev/null
+++ b/test/files/run/bug1079.scala
@@ -0,0 +1,3 @@
+object Test extends Application {
+  println(<t user:tag=""/> == <t user:tag="X"/>)
+}
diff --git a/test/files/run/bug1110.scala b/test/files/run/bug1110.scala
new file mode 100644
index 0000000..092bc85
--- /dev/null
+++ b/test/files/run/bug1110.scala
@@ -0,0 +1,11 @@
+class Stuff {
+  def zoop(p: Any{def &(q: Int): Int}) = p & 7
+  def floop = new { def & = "Hello" }
+
+  assert((floop &) == "Hello")
+  assert(zoop(10) == 2)
+}
+
+object Test extends Application {
+  new Stuff
+}
diff --git a/test/files/run/bug1141.check b/test/files/run/bug1141.check
new file mode 100644
index 0000000..7262160
--- /dev/null
+++ b/test/files/run/bug1141.check
@@ -0,0 +1,2 @@
+var
+args
diff --git a/test/files/run/bug1141.scala b/test/files/run/bug1141.scala
new file mode 100644
index 0000000..7de0313
--- /dev/null
+++ b/test/files/run/bug1141.scala
@@ -0,0 +1,7 @@
+object Test extends Application {
+  val foo = new {
+    def apply(args : String*) = args foreach println
+  }
+  
+  foo("var", "args")
+}
diff --git a/test/files/run/bug1192.scala b/test/files/run/bug1192.scala
index 9e9173b..c199198 100644
--- a/test/files/run/bug1192.scala
+++ b/test/files/run/bug1192.scala
@@ -1,7 +1,7 @@
 object Test extends Application {
   val v1: Array[Array[Int]] = Array(Array(1, 2), Array(3, 4))
   def f[T](w: Array[Array[T]]) {
-    for (val r <- w) println(r.toString)
+    for (val r <- w) println(r.deep.toString)
   }
   f(v1)
 }
diff --git a/test/files/run/bug1300.check b/test/files/run/bug1300.check
new file mode 100644
index 0000000..0f29a1f
--- /dev/null
+++ b/test/files/run/bug1300.check
@@ -0,0 +1 @@
+abcdabcdabcd
diff --git a/test/files/run/bug1300.scala b/test/files/run/bug1300.scala
new file mode 100644
index 0000000..7b2fd79
--- /dev/null
+++ b/test/files/run/bug1300.scala
@@ -0,0 +1,13 @@
+object Test extends Application
+{
+  val a1 = Array(0,1,2,3).toArray[Any]
+//  val a1 = x1.toArray[Any]
+  val a2 = Array('a','b','c','d').toArray[Any]
+  val a3 = Array("e","f","g","h").toArray[Any]
+  
+  Array.copy(a3, 0, a1, 0, 4)
+  Array.copy(a2, 0, a3, 0, 4)
+  Array.copy(a2, 0, a1, 0, 4)
+  
+  println(a1.mkString + a2.mkString + a3.mkString)
+}
diff --git a/test/files/run/bug1309.scala b/test/files/run/bug1309.scala
new file mode 100644
index 0000000..6b5167e
--- /dev/null
+++ b/test/files/run/bug1309.scala
@@ -0,0 +1,7 @@
+object Test {
+  def f(ras: => RandomAccessSeq[Byte]): RandomAccessSeq[Byte] = ras
+  
+  def main(args: Array[String]): Unit = {
+    f(new Array[Byte](0))
+  }
+}
diff --git a/test/files/run/bug1360.check b/test/files/run/bug1360.check
new file mode 100644
index 0000000..8417e20
--- /dev/null
+++ b/test/files/run/bug1360.check
@@ -0,0 +1,2 @@
+[one, two]
+[1, 2, 3]
diff --git a/test/files/run/bug1360.scala b/test/files/run/bug1360.scala
new file mode 100644
index 0000000..4703127
--- /dev/null
+++ b/test/files/run/bug1360.scala
@@ -0,0 +1,7 @@
+object Test {
+  def main(args: Array[String]) {
+    val seq: Seq[String] = List("one", "two")
+    println(java.util.Arrays.asList(seq: _*))
+    println(java.util.Arrays.asList(Seq(1,2,3): _*))
+  }
+}
diff --git a/test/files/run/bug1373.scala b/test/files/run/bug1373.scala
new file mode 100644
index 0000000..537421c
--- /dev/null
+++ b/test/files/run/bug1373.scala
@@ -0,0 +1,6 @@
+// Testing whether case class params come back in the right order.
+object Test extends Application {
+  case class Foo(private val a: String, b: String, private val c: String, d: String, private val e: String)
+  val x = Foo("a", "b", "c", "d", "e")
+  assert(x.toString == """Foo(a,b,c,d,e)""")
+}
\ No newline at end of file
diff --git a/test/files/run/bug1434.scala b/test/files/run/bug1434.scala
new file mode 100644
index 0000000..63bd88e
--- /dev/null
+++ b/test/files/run/bug1434.scala
@@ -0,0 +1,15 @@
+object Test {
+  class A[T] { val op = null }
+  class B extends A[Any]
+  class C extends B
+
+  def f(o: AnyRef) = o match {
+    case a: A[_] if(a.op != null) => "with op"
+    case c: C => "C"
+    case b: B => "B"
+  }
+
+  def main(args: Array[String]) = {
+    assert("C" == f(new C))
+  }
+}
diff --git a/test/files/run/bug1466.scala b/test/files/run/bug1466.scala
new file mode 100644
index 0000000..fdbb5cb
--- /dev/null
+++ b/test/files/run/bug1466.scala
@@ -0,0 +1,11 @@
+object IOvervalueMyPrivacy {
+  private[this] var i = 0
+  def go = {
+    List(1,2,3).foreach(i += _)
+    i
+  }
+}
+
+object Test extends Application {
+  assert(IOvervalueMyPrivacy.go == 6)
+}
diff --git a/test/files/run/bug1766.scala b/test/files/run/bug1766.scala
new file mode 100644
index 0000000..94f6935
--- /dev/null
+++ b/test/files/run/bug1766.scala
@@ -0,0 +1,16 @@
+object Test extends Application {
+  
+  class C(s: String) {
+  
+    def this(i: Int) = this("bar")
+    
+    def f = {
+      val v: { def n: Int } = new { val n = 3 }
+      v.n
+    }
+    
+  }
+  
+  new C("foo").f
+  
+}
diff --git a/test/files/run/bug2005.scala b/test/files/run/bug2005.scala
new file mode 100644
index 0000000..4176709
--- /dev/null
+++ b/test/files/run/bug2005.scala
@@ -0,0 +1,10 @@
+object Test {
+  def main(args: Array[String]) {
+    val a = new Array[Array[Int]](2,2)
+    test(a)
+  }
+  def test[A](t: Array[Array[A]]) {
+    val tmp = t(0)
+    t(1) = tmp
+  }
+}
diff --git a/test/files/run/bug2029.check b/test/files/run/bug2029.check
new file mode 100644
index 0000000..57b610c
--- /dev/null
+++ b/test/files/run/bug2029.check
@@ -0,0 +1,3 @@
+1,2,3,4,5
+4,3,2
+true
diff --git a/test/files/run/bug2029.scala b/test/files/run/bug2029.scala
new file mode 100644
index 0000000..1cbe97a
--- /dev/null
+++ b/test/files/run/bug2029.scala
@@ -0,0 +1,16 @@
+object Test{
+  def main(args : Array[String]){
+    import scala.collection.immutable.TreeSet;
+
+    val mainSet = TreeSet(1 to 5 :_*)
+  
+    var compareCalled = false;
+    val smallerSet = TreeSet(2 to 4 :_*)(Ordering[Int].reverse)
+ 
+    println(mainSet.mkString(","))
+    println(smallerSet.mkString(","))
+    println(smallerSet.subsetOf(mainSet));
+  }
+
+
+}
diff --git a/test/files/run/bug2075.scala b/test/files/run/bug2075.scala
new file mode 100644
index 0000000..f328fad
--- /dev/null
+++ b/test/files/run/bug2075.scala
@@ -0,0 +1,7 @@
+object Test extends Application {
+  var tm = new scala.collection.immutable.TreeMap[Int,Int]
+  for (i <- 0 to 100)
+    tm = tm.insert(i, i)
+
+  tm.keySet.filter(_ < 40)
+}
\ No newline at end of file
diff --git a/test/files/run/bug2124.check b/test/files/run/bug2124.check
new file mode 100644
index 0000000..2b88402
--- /dev/null
+++ b/test/files/run/bug2124.check
@@ -0,0 +1 @@
+<p><lost></lost><q></q></p>
diff --git a/test/files/run/bug2124.scala b/test/files/run/bug2124.scala
new file mode 100644
index 0000000..a4fd654
--- /dev/null
+++ b/test/files/run/bug2124.scala
@@ -0,0 +1,25 @@
+import scala.xml._
+
+import scala.xml.transform._
+
+object Test {
+  val sampleXml = <p><lost/><t><s><r></r></s></t></p>
+
+  def main(args: scala.Array[String]) {
+
+    println(new RuleTransformer(new RewriteRule {
+
+        override def transform(n: Node): NodeSeq = { 
+          val result = n match {
+          case <t>{_*}</t> => <q/>
+
+          case n => n
+
+          }
+//          println ("Rewriting '" +n+ "' to: '" + result+ "'")
+
+          result
+        }
+      }).transform(sampleXml))
+  }
+}
diff --git a/test/files/run/bug2125.check b/test/files/run/bug2125.check
new file mode 100644
index 0000000..2b88402
--- /dev/null
+++ b/test/files/run/bug2125.check
@@ -0,0 +1 @@
+<p><lost></lost><q></q></p>
diff --git a/test/files/run/bug2125.scala b/test/files/run/bug2125.scala
new file mode 100644
index 0000000..a10ed98
--- /dev/null
+++ b/test/files/run/bug2125.scala
@@ -0,0 +1,25 @@
+import scala.xml._
+
+import scala.xml.transform._
+
+object Test {
+
+  val sampleXml = <xml:group><p><lost/><t><s><r></r></s></t></p></xml:group>
+  
+  def main(args: scala.Array[String]) {
+    println(new RuleTransformer(new RewriteRule {
+
+        override def transform(n: Node): NodeSeq = { 
+
+          val result = n match {
+
+          case <t>{_*}</t> => <q/>
+
+          case n => n
+          }
+//          println ("Rewriting '" +n+ "' to: '" + result+ "'")
+          result
+        }
+      }).transform(sampleXml))
+  }
+}
diff --git a/test/files/run/bug2175.scala b/test/files/run/bug2175.scala
new file mode 100644
index 0000000..7885882
--- /dev/null
+++ b/test/files/run/bug2175.scala
@@ -0,0 +1,20 @@
+case class Property[T](private var t: T) {
+ var beforeChanges: List[(T, T) => Unit] = Nil
+ var afterChanges: List[T => Unit] = Nil
+ def apply = t
+ def update(t2: T) = {
+  beforeChanges foreach (_(t, t2))
+  t = t2
+  afterChanges foreach (_(t2))
+ }
+}
+
+object Test
+{
+  def main(args: Array[String]): Unit = {
+    val x = Property(10)
+    x update 25
+    assert(x.apply == 25)
+  }
+}
+
diff --git a/test/files/run/bug2241.scala b/test/files/run/bug2241.scala
new file mode 100644
index 0000000..53a0d70
--- /dev/null
+++ b/test/files/run/bug2241.scala
@@ -0,0 +1,7 @@
+object Test extends Application {
+  def f(a:Array[Int]) = a match {
+    case Array(1, _*) => "yes"
+    case _ => "no"
+  }
+  assert(f(null) == "no")
+}
diff --git a/test/files/run/bug2250.scala b/test/files/run/bug2250.scala
new file mode 100644
index 0000000..1ed3337
--- /dev/null
+++ b/test/files/run/bug2250.scala
@@ -0,0 +1,12 @@
+object Test {
+  def main(args: Array[String]): Unit = {
+    val a: Array[String] = "goobledy bing, goobledy bling, wikka wokka wup.".split("")
+    val b = java.util.Arrays.asList(a: _*)
+    java.util.Collections.shuffle(b)
+
+    // we'll say rather unlikely a.sameElements(b) unless
+    // they are pointing to the same array
+    import scala.collection.JavaConversions._
+    assert(a sameElements b)
+  }
+}
diff --git a/test/files/run/bug2276.check b/test/files/run/bug2276.check
new file mode 100644
index 0000000..95f51c8
--- /dev/null
+++ b/test/files/run/bug2276.check
@@ -0,0 +1,8 @@
+<root>
+      <subnode>
+        <version>2</version>
+      </subnode>
+      <contents>
+        <version>2</version>
+      </contents>
+    </root>
diff --git a/test/files/run/bug2276.scala b/test/files/run/bug2276.scala
new file mode 100644
index 0000000..68b9976
--- /dev/null
+++ b/test/files/run/bug2276.scala
@@ -0,0 +1,24 @@
+import scala.xml._
+import scala.xml.transform._
+
+object Test extends Application {
+  val inputXml : Node = 
+    <root>
+      <subnode>
+        <version>1</version>
+      </subnode>
+      <contents>
+        <version>1</version>
+      </contents>
+    </root>
+
+  object t1 extends RewriteRule {
+    override def transform(n: Node): Seq[Node] = n match {
+      case <version>{x}</version> if x.toString.toInt < 4 => <version>{x.toString.toInt+1}</version>
+      case other => other
+    }
+  }
+
+  val ruleTransformer = new RuleTransformer(t1)
+  println(ruleTransformer(inputXml))
+}
diff --git a/test/files/run/bug2354.scala b/test/files/run/bug2354.scala
new file mode 100644
index 0000000..5419911
--- /dev/null
+++ b/test/files/run/bug2354.scala
@@ -0,0 +1,17 @@
+import scala.xml.parsing._
+import scala.io.Source
+
+object Test
+{
+  val xml_good = "<title><![CDATA[Hello [tag]]]></title>"
+  val xml_bad = "<title><![CDATA[Hello [tag] ]]></title>"
+
+  val parser1 = ConstructingParser.fromSource(Source.fromString(xml_good),false)
+  val parser2 = ConstructingParser.fromSource(Source.fromString(xml_bad),false)
+  
+  def main(args: Array[String]): Unit = {
+    parser1.document
+    parser2.document
+  }
+}
+
diff --git a/test/files/run/bug2378.scala b/test/files/run/bug2378.scala
new file mode 100644
index 0000000..f696a78
--- /dev/null
+++ b/test/files/run/bug2378.scala
@@ -0,0 +1,9 @@
+object Test
+{
+  val f1 = -0.0
+  val f2 = -(0.0)
+  def main(args: Array[String]): Unit = {
+    assert(f1.toString startsWith "-")
+    assert(f2.toString startsWith "-")
+  }
+}
diff --git a/test/files/run/bug2512.scala b/test/files/run/bug2512.scala
new file mode 100644
index 0000000..c2dfda6
--- /dev/null
+++ b/test/files/run/bug2512.scala
@@ -0,0 +1,14 @@
+import scala.tools.nsc.util.HashSet
+
+object Test
+{
+  val runs = 10000
+  class Bop
+  
+  def main(args: Array[String]): Unit = {
+    val set: HashSet[Bop] = new HashSet("Bop", 16)
+    (1 to runs).toList foreach (_ => set addEntry new Bop)
+    
+    assert(runs == set.size && set.size == set.iterator.length)
+  }
+}
diff --git a/test/files/run/bug2514.scala b/test/files/run/bug2514.scala
new file mode 100644
index 0000000..21c4afb
--- /dev/null
+++ b/test/files/run/bug2514.scala
@@ -0,0 +1,15 @@
+object Test
+{
+  implicit def x[A](a: A) = new { def xx = a }
+  
+  def main(args: Array[String]): Unit = {
+    val r1 = 12 xx;
+    val r2 = 12.xx
+    val r3 = 12.`xx`
+    val r4 = 12.xx + 12.xx
+    val r5 = 12.`xx` + 12.xx
+    val r6 = 12.3.`xx` + 12.xx
+    
+    assert(r5 == 24)
+  }
+}
\ No newline at end of file
diff --git a/test/files/run/bug2552.check b/test/files/run/bug2552.check
new file mode 100644
index 0000000..1deeae7
--- /dev/null
+++ b/test/files/run/bug2552.check
@@ -0,0 +1,48 @@
+p(0)
+0
+p(1)
+1
+p(2)
+2
+p(3)
+3
+p(4)
+4
+p(5)
+5
+p(6)
+6
+p(7)
+7
+p(8)
+8
+p(9)
+9
+p(10)
+p(0)
+true
+true
+0
+p(1)
+true
+1
+p(2)
+false
+false
+p(0)
+true
+true
+0
+p(1)
+p(2)
+2
+p(3)
+p(4)
+4
+p(5)
+p(6)
+6
+p(7)
+p(8)
+8
+p(9)
diff --git a/test/files/run/bug2552.scala b/test/files/run/bug2552.scala
new file mode 100644
index 0000000..34fe250
--- /dev/null
+++ b/test/files/run/bug2552.scala
@@ -0,0 +1,34 @@
+object Test extends Application {
+	def testTakeWhile = {
+		val numbers = Iterator.range(0, 50)
+		val zeroTo9 = numbers.takeWhile(x => { println("p(" + x + ")"); x < 10 } )
+		
+		zeroTo9.foreach(println _)
+		
+		val zeroTo1 = Iterator.range(0, 20).takeWhile(x => { println("p(" + x + ")"); x < 2 } )
+	
+		println(zeroTo1.hasNext)
+		println(zeroTo1.hasNext)
+		println(zeroTo1.next)
+		println(zeroTo1.hasNext)
+		println(zeroTo1.next)
+		println(zeroTo1.hasNext)
+		println(zeroTo1.hasNext)
+	}
+	
+	def testFilter = {
+		val predicate = (x: Int) => { println("p(" + x + ")"); x % 2 == 0 }
+		
+		val evens = Iterator.range(0, 10).filter(predicate)
+		
+		println(evens.hasNext)
+		println(evens.hasNext)
+		println(evens.next)
+		
+		evens.foreach(println _)
+	}
+
+	testTakeWhile
+	testFilter
+}
+
diff --git a/test/files/run/bug2636.scala b/test/files/run/bug2636.scala
new file mode 100644
index 0000000..3271f79
--- /dev/null
+++ b/test/files/run/bug2636.scala
@@ -0,0 +1,35 @@
+object Test
+{
+  type Foo = { def update(x: Int, value: String): Unit }
+  type Foo2 = { def update(x: Int, value: String): Int }
+  type Foo3 = { def update(x: Int, value: String): Array[Int] }
+  
+  def alen() = {
+    type L1 = { def length: Int }
+    def len(p: L1) = p.length
+    val x: L1 = Array(1,2,3)
+    len(x)
+  }
+  
+  type A1 = { def apply(x: Int): String }
+  def arrApply(a: A1, x: Int) = a(x)
+  
+  def main(args: Array[String]): Unit = {
+    val arr = new Array[String](3)
+    val p1: Foo = arr
+    def a1 = p1(0) = "b"
+
+    val p2: Foo2 = new { def update(x: Int, value: String) = { p1(1) = "o" ; 1 } }
+    def a2 = p2(0) = "c"    
+    
+    val p3: Foo3 = new { def update(x: Int, value: String) = { p1(2) = "b" ; Array(1) } }
+    def a3 = p3(10) = "hi mom"
+    
+    a1 ; a2 ; a3 ;
+
+    assert(arr.mkString == "bob")
+    assert(alen() == 3)
+    assert(arrApply(arr, 1) == "o")
+    assert(arrApply(new { def apply(x: Int) = "tom" }, -100) == "tom")
+  }
+}
\ No newline at end of file
diff --git a/test/files/run/bug2721.check b/test/files/run/bug2721.check
new file mode 100644
index 0000000..2bd7656
--- /dev/null
+++ b/test/files/run/bug2721.check
@@ -0,0 +1,2 @@
+root:-rootVal-sub:-subVal-
+root:-rootVal-sub:-subVal-
diff --git a/test/files/run/bug2721.scala b/test/files/run/bug2721.scala
new file mode 100644
index 0000000..93af884
--- /dev/null
+++ b/test/files/run/bug2721.scala
@@ -0,0 +1,12 @@
+object Test
+{
+  val xml1 = <root xmlns:ns="nsUri" ns:at="rootVal"><sub ns:at="subVal"/></root>
+  val xml2= scala.xml.XML.loadString("""<root xmlns:ns="nsUri" ns:at="rootVal"><sub ns:at="subVal"/></root>""")
+  
+  def backslashSearch(x: xml.Elem) = "root:-"+(x \ "@{nsUri}at") +"-sub:-"+(x \ "sub" \ "@{nsUri}at") +"-"
+  
+  def main(args: Array[String]): Unit = {
+    println(backslashSearch(xml1))
+    println(backslashSearch(xml2))
+  }
+}
diff --git a/test/files/run/bug2876.scala b/test/files/run/bug2876.scala
new file mode 100644
index 0000000..f71879e
--- /dev/null
+++ b/test/files/run/bug2876.scala
@@ -0,0 +1,7 @@
+object Test
+{
+  def main(args: Array[String]): Unit = {
+    "x".view.filter(_ => true).take(1)
+  }
+}
+
diff --git a/test/files/run/bug2958.scala b/test/files/run/bug2958.scala
new file mode 100644
index 0000000..b9563a1
--- /dev/null
+++ b/test/files/run/bug2958.scala
@@ -0,0 +1,16 @@
+object Test {
+  def f(args: Array[String]) = args match {
+    case Array("-p", prefix, from, to) =>
+      prefix + from + to
+    
+    case Array(from, to) =>
+      from + to
+
+    case _ =>
+      "default"
+  }
+  
+  def main(args: Array[String]) {
+    assert(f(Array("1", "2")) == "12")
+  }
+}
\ No newline at end of file
diff --git a/test/files/run/bug298.check b/test/files/run/bug298.check
new file mode 100644
index 0000000..1cd1d22
--- /dev/null
+++ b/test/files/run/bug298.check
@@ -0,0 +1,2 @@
+List(42, 24)
+List((42,42), (24,24))
diff --git a/test/files/run/bug298.scala b/test/files/run/bug298.scala
new file mode 100644
index 0000000..c6179f1
--- /dev/null
+++ b/test/files/run/bug298.scala
@@ -0,0 +1,17 @@
+object Test extends Application {
+  implicit def anyList[T]: List[T] = Nil
+
+  implicit def intList: List[Int] = 42::24::Nil
+
+  def foo[T](implicit x: T) = x
+
+  val s = foo[List[Int]]
+
+  println(s)  // correct - prints "List(42, 24)"
+
+  implicit def tupleList[T](implicit t: List[T]): List[(T,T)] = t.map(x => (x,x))
+
+  val t = foo[List[Tuple2[Int,Int]]]
+
+  println(t)  // incorrect - prints "List()"
+}
\ No newline at end of file
diff --git a/test/files/run/bug3004.scala b/test/files/run/bug3004.scala
new file mode 100644
index 0000000..a1e9c6c
--- /dev/null
+++ b/test/files/run/bug3004.scala
@@ -0,0 +1,14 @@
+object MyClass {
+  val duplicate: Int = 10
+}
+
+class MyClass {
+  private val duplicate = MyClass.duplicate
+}
+
+object Test {
+  def main(args: Array[String]): Unit = {
+    val x = new MyClass
+    ()
+  }
+}
diff --git a/test/files/run/bug3126.scala b/test/files/run/bug3126.scala
new file mode 100644
index 0000000..36322bf
--- /dev/null
+++ b/test/files/run/bug3126.scala
@@ -0,0 +1,9 @@
+object Test {
+  case class C(x: Int)
+  val v: Some[Int] = null
+
+  def main(args: Array[String]): Unit = {
+    try C.unapply(null) catch { case _: MatchError => }
+    try v match { case Some(1) => } catch { case _: MatchError => }
+  }
+}
diff --git a/test/files/run/bug3175.check b/test/files/run/bug3175.check
new file mode 100644
index 0000000..1224614
--- /dev/null
+++ b/test/files/run/bug3175.check
@@ -0,0 +1,11 @@
+10
+15
+3
+3
+3
+5
+5
+5
+100
+jabooboo
+hi mom
diff --git a/test/files/run/bug3175.scala b/test/files/run/bug3175.scala
new file mode 100644
index 0000000..aff2e67
--- /dev/null
+++ b/test/files/run/bug3175.scala
@@ -0,0 +1,55 @@
+/** A bit down the road this test will examine
+ *  the bytecode.
+ */
+object Test {
+  def len(x:{ def length: Int }) = x.length
+  def f1(x:{ def apply(x: Int): Long }) = x(0)
+  def f2(x:{ def apply(x: Int): Byte }) = x(0)
+  def f3(x:{ def apply(x: Int): String }) = x(0).length
+  
+  def f4(x:{ def update(x: Int, y: Long): Unit }, y: Long) = x(0) = y
+  def f5(x:{ def update(x: Int, y: Byte): Unit }, y: Byte) = x(0) = y
+  def f6(x:{ def update(x: Int, y: String): Unit }, y: String) = x(0) = y
+  
+  def f7(x: { def length: Any }) = x.length
+  
+  def f8(x: { def apply(x: Int): Any }) = x(0)
+  def f9(x: { def apply(x: Int): Int }) = x(0)
+  def f10(x: { def apply(x: Int): Long }) = x(0)
+  
+  // update has some interesting special cases
+  def f11(x:{ def update(x: Int, y: Long): Any }, y: Long) = x(0) = y
+  def f12(x:{ def update(x: Int, y: String): AnyVal }, y: String) = x(0) = y  
+  def f13(x:{ def update(x: Int, y: String): AnyRef }, y: String) = x(0) = y
+    
+  // doesn't work yet, see #3197
+  // def fclone(x:{ def clone(): AnyRef }) = x.clone()
+  
+  def main(args: Array[String]): Unit = {
+    val longs = Array(5L)
+    val bytes = Array(5: Byte)
+    val strs = Array("abcde", "fghjij")
+    
+    println(len(Array(1,2,3)) + len(Array(4.0,5.0f)) + len(Array("abc", 5)) + len("bop"))
+    println(f1(longs) + f2(bytes) + f3(strs))
+    
+    f4(longs, 1)
+    f5(bytes, 1)
+    f6(strs, "a")
+    
+    println(f1(longs) + f2(bytes) + f3(strs))
+    
+    println(f7(Array(1,2,3)))
+    println(f7("def"))
+    
+    println(f8(Array(5)))
+    println(f9(Array(5)))
+    println(f10(Array(5)))
+    
+    f11(longs, 100L)
+    f12(strs, "jabooboo")
+    println(longs(0))
+    println(strs(0))
+    f13(new { def update(x: Int, y: String): List[Int] = { println("hi mom") ; Nil } }, "irrelevant")
+  }
+}
diff --git a/test/files/run/bug3269.check b/test/files/run/bug3269.check
new file mode 100644
index 0000000..c25611c
--- /dev/null
+++ b/test/files/run/bug3269.check
@@ -0,0 +1,2 @@
+1
+Hello
diff --git a/test/files/run/bug3269.scala b/test/files/run/bug3269.scala
new file mode 100644
index 0000000..6fe7271
--- /dev/null
+++ b/test/files/run/bug3269.scala
@@ -0,0 +1,9 @@
+object Test {
+  def main(args: Array[String]): Unit = {
+    val it = List(1).iterator ++ { println("Hello"); Iterator.empty }
+    println(it.next)
+    it.hasNext
+    it.hasNext
+    it.hasNext 
+  }
+}
diff --git a/test/files/run/bug3327.check b/test/files/run/bug3327.check
new file mode 100644
index 0000000..980a0d5
--- /dev/null
+++ b/test/files/run/bug3327.check
@@ -0,0 +1 @@
+Hello World!
diff --git a/test/files/run/bug3327.scala b/test/files/run/bug3327.scala
new file mode 100644
index 0000000..7e6d3fc
--- /dev/null
+++ b/test/files/run/bug3327.scala
@@ -0,0 +1,8 @@
+object Test {
+  def main (args : Array[String]) {
+    val b = new StringBuilder
+    b.append ("Hello World!")
+    b.lastIndexOf ('e')
+    println (b.toString)
+  }
+}
\ No newline at end of file
diff --git a/test/files/run/bug3395.check b/test/files/run/bug3395.check
new file mode 100644
index 0000000..5f5521f
--- /dev/null
+++ b/test/files/run/bug3395.check
@@ -0,0 +1,2 @@
+abc
+def
diff --git a/test/files/run/bug3395.scala b/test/files/run/bug3395.scala
new file mode 100644
index 0000000..01cc431
--- /dev/null
+++ b/test/files/run/bug3395.scala
@@ -0,0 +1,13 @@
+object Test {
+  def main(args: Array[String]): Unit = {
+    Seq("") match { 
+      case Seq("")      => println("abc")
+      case Seq(_, _, x) => println(x)
+    }
+    
+    Seq(1, 2, "def") match { 
+      case Seq("")      => println("abc")
+      case Seq(_, _, x) => println(x)
+    }
+  }
+}
\ No newline at end of file
diff --git a/test/files/run/bug3397.scala b/test/files/run/bug3397.scala
new file mode 100644
index 0000000..243fe76
--- /dev/null
+++ b/test/files/run/bug3397.scala
@@ -0,0 +1,7 @@
+object Test {
+  def main(args: Array[String]): Unit = {
+    val x = Seq(Set(1,2,3),Set(4,5,6),Set(7,8,9)).transpose
+    
+    ()
+  }
+}
diff --git a/test/files/run/bug3516.check b/test/files/run/bug3516.check
new file mode 100644
index 0000000..d0d10d8
--- /dev/null
+++ b/test/files/run/bug3516.check
@@ -0,0 +1,3 @@
+1
+1
+21
diff --git a/test/files/run/bug3516.scala b/test/files/run/bug3516.scala
new file mode 100644
index 0000000..82a97f2
--- /dev/null
+++ b/test/files/run/bug3516.scala
@@ -0,0 +1,13 @@
+object Test {
+  def mkIterator = (1 to 5).iterator map (x => { println(x) ; x })
+  def mkInfinite = Iterator continually { println(1) ; 1 }
+  
+  def main(args: Array[String]): Unit = {
+    // Stream is strict in its head so we should see 1 from each of them.
+    val s1 = mkIterator.toStream
+    val s2 = mkInfinite.toStream
+    // back and forth without slipping into nontermination.
+    println((Stream from 1).toIterator.drop(10).toStream.drop(10).toIterator.next)
+    ()
+  }
+}
diff --git a/test/files/run/bug3529.scala b/test/files/run/bug3529.scala
new file mode 100644
index 0000000..bb82424
--- /dev/null
+++ b/test/files/run/bug3529.scala
@@ -0,0 +1,14 @@
+object Test {
+  def main(args: Array[String]): Unit = {
+    assert(1 to 10 drop 10 isEmpty)
+    assert(1 until 10 drop 9 isEmpty)
+    assert(1 to 10 by 2 drop 5 isEmpty)
+    assert(10 to 1 by -1 drop 10 isEmpty)
+    assert((10 to 1 by -1 drop 9) == Seq(1))
+
+    assert((1 to 10 drop 9) == Seq(10))
+    assert((1 until 10 drop 9) == Nil)
+
+    assert(Stream(1 to 10).flatten.toList == Stream(1 until 11).flatten.toList)
+  }
+}
diff --git a/test/files/run/bug3540.scala b/test/files/run/bug3540.scala
new file mode 100644
index 0000000..4eb3de7
--- /dev/null
+++ b/test/files/run/bug3540.scala
@@ -0,0 +1,7 @@
+object Test {
+  def main(args: Array[String]): Unit = {
+    assert(List.iterate(List(1,2,3), 4)(_.tail).last.isEmpty)
+    assert(Stream.iterate(Stream(1,2,3), 4)(_.tail).last.isEmpty)
+    assert(Array.iterate(Array(1,2,3), 4)(_.tail).last.isEmpty)    
+  }
+}
diff --git a/test/files/run/bug3563.scala b/test/files/run/bug3563.scala
new file mode 100644
index 0000000..2a80ef4
--- /dev/null
+++ b/test/files/run/bug3563.scala
@@ -0,0 +1,21 @@
+
+
+
+
+
+// ticket #3563
+object Test {
+  
+  def main(args: Array[String]) {
+    var sum = 0
+    val setseq = Set(1, 2, 3, 4).toSeq
+    setseq.map( n => { sum += n; n * n }).head
+    assert(sum == 10)
+    
+    sum = 0
+    val mapseq = Map(1 -> 1, 2 -> 2, 3 -> 3, 4 -> 4).toSeq
+    mapseq.map( n => { sum += n._1; (n._1 + n._1, n._2 * n._2) }).head
+    assert(sum == 10)
+  }
+  
+}
diff --git a/test/files/run/bug3616.check b/test/files/run/bug3616.check
new file mode 100644
index 0000000..f31e21b
--- /dev/null
+++ b/test/files/run/bug3616.check
@@ -0,0 +1 @@
+Fruit.ValueSet(A, B, C)
diff --git a/test/files/run/bug3616.scala b/test/files/run/bug3616.scala
new file mode 100644
index 0000000..777b97f
--- /dev/null
+++ b/test/files/run/bug3616.scala
@@ -0,0 +1,12 @@
+object X extends Enumeration {
+    val Y = Value
+}
+object Fruit extends Enumeration {
+    val x = X.Y
+    val A,B,C = Value
+}
+object Test {
+  def main(args: Array[String]): Unit = {
+    println(Fruit.values)
+  }
+}
diff --git a/test/files/run/bug363.check b/test/files/run/bug363.check
new file mode 100644
index 0000000..040b97c
--- /dev/null
+++ b/test/files/run/bug363.check
@@ -0,0 +1 @@
+I love the smell of (Array[String])Unit in the morning.
diff --git a/test/files/run/bug363.scala b/test/files/run/bug363.scala
new file mode 100644
index 0000000..5f3f30a
--- /dev/null
+++ b/test/files/run/bug363.scala
@@ -0,0 +1,9 @@
+object Test {
+  def main(args: Array[String]) {
+    println("I love the smell of (Array[String])Unit in the morning.")
+  }
+}
+  
+class Test {
+  def kurtz() = "We must kill them. We must incinerate them."
+}
diff --git a/test/files/run/bug408.scala b/test/files/run/bug408.scala
new file mode 100644
index 0000000..4d3dcbc
--- /dev/null
+++ b/test/files/run/bug408.scala
@@ -0,0 +1,12 @@
+object Test
+{
+  val a = scala.collection.immutable.Set.empty ++ (0 to 100000)
+  val b = scala.collection.immutable.Set.empty ++ (0 to 100000)
+  
+  def main(args: Array[String]): Unit = {
+    a -- b
+    a -- b
+    a -- b
+    a -- b
+  }
+}
diff --git a/test/files/run/bug429.check b/test/files/run/bug429.check
index 29d0834..9e871b7 100644
--- a/test/files/run/bug429.check
+++ b/test/files/run/bug429.check
@@ -1 +1 @@
-AyB1
\ No newline at end of file
+AyB1
diff --git a/test/files/run/bug594.scala b/test/files/run/bug594.scala
index b120f47..f923a3c 100644
--- a/test/files/run/bug594.scala
+++ b/test/files/run/bug594.scala
@@ -1,8 +1,8 @@
 object Test {
   def main(args: Array[String]): Unit = {
     val array = Array("one", "two", "three")
-    val firstTwo: Array[String] = array.subArray(0,2)
-    for(val x <- firstTwo)
+    val firstTwo: Array[String] = array.slice(0,2)
+    for (x <- firstTwo)
       Console.println(x)
   }
 }
diff --git a/test/files/run/bug627.check b/test/files/run/bug627.check
index f3304eb..39e641d 100644
--- a/test/files/run/bug627.check
+++ b/test/files/run/bug627.check
@@ -1 +1 @@
-Array(1, 2, 3, 4)
+WrappedArray(1, 2, 3, 4)
diff --git a/test/files/run/bug627.scala b/test/files/run/bug627.scala
index 6415694..ecaf150 100644
--- a/test/files/run/bug627.scala
+++ b/test/files/run/bug627.scala
@@ -1,6 +1,6 @@
 object Test {
   def main(args: Array[String]) {
-    val s: Seq[int] = Array(1, 2, 3, 4)
+    val s: Seq[Int] = Array(1, 2, 3, 4)
     println(s)
   }
 }
diff --git a/test/files/run/bug751.scala b/test/files/run/bug751.scala
new file mode 100644
index 0000000..294d3af
--- /dev/null
+++ b/test/files/run/bug751.scala
@@ -0,0 +1,6 @@
+object Test {
+  def main(args: Array[String]): Unit = {
+    val map =  Map(1 -> "a", 2 -> "b", 3 -> "c")
+    assert(map.filterKeys(_ % 2 == 0).isInstanceOf[scala.collection.immutable.Map[_,_]])
+  }
+}
diff --git a/test/files/run/bugs.scala b/test/files/run/bugs.scala
index 58a8e99..d5905af 100644
--- a/test/files/run/bugs.scala
+++ b/test/files/run/bugs.scala
@@ -1,7 +1,6 @@
 //############################################################################
 // Bugs
 //############################################################################
-// $Id: bugs.scala 15313 2008-06-10 09:25:57Z michelou $
 
 //############################################################################
 // Bug 98
diff --git a/test/files/run/bugs2087-and-2400.scala b/test/files/run/bugs2087-and-2400.scala
new file mode 100644
index 0000000..93cd633
--- /dev/null
+++ b/test/files/run/bugs2087-and-2400.scala
@@ -0,0 +1,20 @@
+object Test
+{
+  def negativeCharMaker = new (Short => Char) { def apply(x: Short) = x.toChar }
+  def main(args: Array[String]): Unit = {
+    // throws exception if -100 gets to Character.valueOf
+    val x = negativeCharMaker(-100) 
+    
+    // chars are unsigned, they should never be equal to negative values
+    assert((-100).toShort != (-100).toChar)
+    assert((-100).toChar != (-100).toShort)
+    assert((-100).toChar != (-100).toByte)
+    assert((-100).toByte != (-100).toChar)
+    
+    // BoxesRunTime must agree as well
+    assert(((-100).toShort: Any) != (-100).toChar)
+    assert(((-100).toChar: Any) != (-100).toShort)
+    assert(((-100).toChar: Any) != (-100).toByte)
+    assert(((-100).toByte: Any) != (-100).toChar)
+  }
+}
diff --git a/test/files/run/bytecodecs.scala b/test/files/run/bytecodecs.scala
new file mode 100644
index 0000000..bf8a0f8
--- /dev/null
+++ b/test/files/run/bytecodecs.scala
@@ -0,0 +1,39 @@
+import scala.reflect.generic.ByteCodecs._
+
+object Test {
+
+  def test8to7(xs: Array[Byte]) {
+    val ys = encode8to7(xs)
+    decode7to8(ys, ys.length)
+    assert(ys.take(xs.length).deep == xs.deep,
+           "test8to7("+xs.deep+") failed, result = "+ys.take(xs.length).deep)
+  }
+
+  def testAll(xs: Array[Byte]) {
+    val ys = encode(xs)
+    decode(ys)
+    assert(ys.take(xs.length).deep == xs.deep,
+           "testAll("+xs.deep+") failed, result = "+ys.take(xs.length).deep)
+  }
+
+  def test(inputs: Array[Byte]*) {
+    for (input <- inputs) {
+      test8to7(input)
+      testAll(input)
+    }
+  }
+
+  def main(args: Array[String]) {
+    test(
+      Array(1, 2, 3),
+      Array(1, 2, 3, 4, 5, 6, 7),
+      Array(1, -2, 0, -3, -5, -6, -7),
+      Array(1, 3, -1, -128, 0, 0, -128, 1, 2, 3))
+    val rand = new scala.util.Random()
+    for (i <- 1 until 5000) {
+      var xs = new Array[Byte](i)
+      rand.nextBytes(xs)
+      test(xs)
+    }
+  }
+}
diff --git a/test/files/run/caseClassEquality.scala b/test/files/run/caseClassEquality.scala
new file mode 100644
index 0000000..4940d80
--- /dev/null
+++ b/test/files/run/caseClassEquality.scala
@@ -0,0 +1,36 @@
+object Test {
+  abstract class A1
+  case class C1(x: Int) extends A1
+  class C2(x: Int) extends C1(x) {
+    override def productPrefix = "Shazbot!"
+  }
+  class C3(x: Int) extends C1(x) {
+    override def canEqual(other: Any) = other.isInstanceOf[C3]
+    override def equals(other: Any) = other match {
+      case ob: C3 => x == ob.x
+      case _      => false
+    }
+  }
+  
+  case class CS1(xs: Any*)
+  class CS2(xs: Seq[_]*) extends CS1(xs: _*)
+  class CS3(xs: IndexedSeq[Int]*) extends CS2(xs: _*)
+  
+  case class H1(x: Int, y: Double)
+  class H2(x: Double, y: Int) extends H1(y, x)
+  
+  def main(args: Array[String]): Unit = {
+    assert(C1(5) == new C2(5))
+    assert(new C2(5) == C1(5))
+    assert(C1(5).hashCode == new C2(5).hashCode)
+    assert(new C2(5).hashCode == C1(5).hashCode)
+  
+    assert(C1(5) != new C3(5))
+    assert(new C3(5) != C1(5))
+    
+    assert(CS1(List(1d,2d), Seq[Float](3f, 4f)) == new CS3(IndexedSeq(1,2), IndexedSeq(3, 4)))
+    
+    assert(H1(5, 10d) == new H2(10d, 5))
+    assert(H1(5, 10d).hashCode == new H2(10d, 5).hashCode)
+  }
+}
diff --git a/test/files/run/caseclasses.scala b/test/files/run/caseclasses.scala
index 56fe6da..ed5643a 100644
--- a/test/files/run/caseclasses.scala
+++ b/test/files/run/caseclasses.scala
@@ -2,8 +2,6 @@ case class Foo(x: Int)(y: Int)
 
 case class Bar
 
-case class Baz(override val x: Int, y: Int) extends Foo(x)(y)
-
 abstract class Base
 abstract case class Abs(x: Int) extends Base
 
@@ -30,10 +28,6 @@ object Test extends Application {
     case Foo(1) => Console.println("OK")
     case Bar() => Console.println("NO")
   }
-  (Baz(1, 2): AnyRef) match {
-    case Baz(1, 2) => ;
-    case Bar() => Console.println("NO")
-  }
   try {
     Bar() productElement 3
     throw new NullPointerException("duh")
diff --git a/test/files/run/castsingleton.check b/test/files/run/castsingleton.check
new file mode 100644
index 0000000..4974228
--- /dev/null
+++ b/test/files/run/castsingleton.check
@@ -0,0 +1,2 @@
+L()
+L()
diff --git a/test/files/run/castsingleton.scala b/test/files/run/castsingleton.scala
new file mode 100644
index 0000000..3921696
--- /dev/null
+++ b/test/files/run/castsingleton.scala
@@ -0,0 +1,11 @@
+object Test extends Application {
+  case class L();
+  object N extends L();
+
+  def empty(xs : L) : Unit = xs match {
+    case x at N  => println(x); println(x);
+    case x    => println(x); println(x);
+  }
+
+  empty(L())
+} 
diff --git a/test/files/run/classof.check b/test/files/run/classof.check
index af7082f..0d650b8 100644
--- a/test/files/run/classof.check
+++ b/test/files/run/classof.check
@@ -10,13 +10,13 @@ float
 double
 Class types
 class SomeClass
-class scala.List
+class scala.collection.immutable.List
 class scala.Tuple2
 Arrays:
 class [Lscala.runtime.BoxedUnit;
 class [I
 class [D
-class [Lscala.List;
+class [Lscala.collection.immutable.List;
 Functions: 
 interface scala.Function2
 interface scala.Function1
diff --git a/test/files/run/collection-stacks.check b/test/files/run/collection-stacks.check
deleted file mode 100644
index fcb39c4..0000000
--- a/test/files/run/collection-stacks.check
+++ /dev/null
@@ -1,14 +0,0 @@
-1-2-3: true
-1-2-3: true
-apply
-1: true
-1: true
-3: true
-3: true
-top
-3: true
-3: true
-pop
-1-2: true
-3: true
-1-2: true
diff --git a/test/files/run/collection-stacks.scala b/test/files/run/collection-stacks.scala
deleted file mode 100644
index 8305282..0000000
--- a/test/files/run/collection-stacks.scala
+++ /dev/null
@@ -1,38 +0,0 @@
-import scala.collection._
-
-object Test extends Application {
-  def mutableStack[T](xs: T*): mutable.Stack[T] = {
-    val s = new mutable.Stack[T]
-    s.push(xs: _*)
-    s
-  }
-  
-  def immutableStack[T](xs: T*): immutable.Stack[T] = {
-    immutable.Stack.Empty push xs
-  }
-  
-  def check[T](expected: T, got: T) {
-    println(got + ": " + (expected == got))
-  }
-  
-  // check #957
-  check("1-2-3", immutableStack(1, 2, 3).elements.mkString("-"))
-  check("1-2-3", mutableStack(1, 2, 3).elements.mkString("-"))
-  
-  println("apply")
-  check(1, immutableStack(1, 2, 3).apply(0))
-  check(1, mutableStack(1, 2, 3).apply(0))
-  check(3, immutableStack(1, 2, 3).apply(2))
-  check(3, mutableStack(1, 2, 3).apply(2))
-  
-  println("top")
-  check(3, immutableStack(1, 2, 3).top)
-  check(3, mutableStack(1, 2, 3).top)
-  
-  println("pop")
-  check("1-2", immutableStack(1, 2, 3).pop.mkString("-"))
-  check(3, mutableStack(1, 2, 3).pop())
-  check("1-2", { val s = mutableStack(1, 2, 3); s.pop(); s.toList.mkString("-") })
-}
-
-// vim: set ts=2 sw=2 et:
diff --git a/test/files/run/collections.check b/test/files/run/collections.check
index 0442e48..b87a599 100644
--- a/test/files/run/collections.check
+++ b/test/files/run/collections.check
@@ -32,7 +32,3 @@ test4: 25005003
 test1: 14005
 test2: 9007003, iters = 3000
 test3: 9007003
-***** immutable.UnBalancedTreeMap:
-test1: 14005
-test2: 1013003, iters = 1000
-test3: 1013003
diff --git a/test/files/run/collections.scala b/test/files/run/collections.scala
index 721414c..2bbeed0 100644
--- a/test/files/run/collections.scala
+++ b/test/files/run/collections.scala
@@ -113,5 +113,4 @@ object Test extends Application {
   test("immutable.Map", immutable.Map[Int, Int](), 5000)
   test("immutable.TreeMap", new immutable.TreeMap[Int, Int], 5000)
   test("immutable.ListMap", new immutable.ListMap[Int, Int], 3000)
-  test("immutable.UnBalancedTreeMap", new immutable.UnbalancedTreeMap[Int, Int], 1000)
 }
diff --git a/test/files/run/colltest.scala b/test/files/run/colltest.scala
index 65c3676..b657700 100644
--- a/test/files/run/colltest.scala
+++ b/test/files/run/colltest.scala
@@ -25,7 +25,7 @@ class TestSet(s0: Set[Int], s1: Set[Int]) {
     case 7         => "size"
   }
   def checkSubSet(pre: String, s0: Set[Int], s1: Set[Int]) {
-    for (e <- s0.elements)
+    for (e <- s0.iterator)
       if (!(s1 contains e)) {
         assert(false, pre+" element: "+e+"\n S0 = "+s0+"\n S1 = "+s1)
       }
@@ -46,5 +46,5 @@ class TestSet(s0: Set[Int], s1: Set[Int]) {
   Console.println("succeeded for "+Iterations+" iterations.")
 }
 object Test extends Application {
-  new TestSet(HashSet.empty, new scala.collection.jcl.LinkedHashSet)
+  new TestSet(HashSet.empty, new scala.collection.mutable.LinkedHashSet)
 }
diff --git a/test/files/run/colltest1.check b/test/files/run/colltest1.check
new file mode 100644
index 0000000..7377174
--- /dev/null
+++ b/test/files/run/colltest1.check
@@ -0,0 +1,109 @@
+new test starting with List()
+10: List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
+9: List(2, 3, 4, 5, 6, 7, 8, 9, 10)
+1
+List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
+new test starting with List()
+10: List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
+9: List(2, 3, 4, 5, 6, 7, 8, 9, 10)
+1
+List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
+new test starting with Stream()
+10: Stream(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
+9: Stream(2, 3, 4, 5, 6, 7, 8, 9, 10)
+1
+Stream(1, ?)
+new test starting with WrappedArray()
+10: ArrayBuffer(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
+9: ArrayBuffer(2, 3, 4, 5, 6, 7, 8, 9, 10)
+1
+ArrayBuffer(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
+new test starting with ArrayBuffer()
+10: ArrayBuffer(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
+9: ArrayBuffer(2, 3, 4, 5, 6, 7, 8, 9, 10)
+1
+ArrayBuffer(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
+new test starting with ListBuffer()
+10: ListBuffer(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
+9: ListBuffer(2, 3, 4, 5, 6, 7, 8, 9, 10)
+1
+ListBuffer(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
+new test starting with List()
+10: List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
+9: List(2, 3, 4, 5, 6, 7, 8, 9, 10)
+1
+new test starting with ArrayBuffer()
+10: ArrayBuffer(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
+9: ArrayBuffer(2, 3, 4, 5, 6, 7, 8, 9, 10)
+1
+new test starting with List()
+10: List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
+9: List(2, 3, 4, 5, 6, 7, 8, 9, 10)
+1
+new test starting with List()
+10: List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
+9: List(2, 3, 4, 5, 6, 7, 8, 9, 10)
+1
+new test starting with ArrayBuffer()
+10: ArrayBuffer(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
+9: ArrayBuffer(2, 3, 4, 5, 6, 7, 8, 9, 10)
+1
+new test starting with List()
+10: List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
+9: List(2, 3, 4, 5, 6, 7, 8, 9, 10)
+1
+new test starting with List()
+10: List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
+9: List(2, 3, 4, 5, 6, 7, 8, 9, 10)
+1
+List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
+new test starting with ArrayBuffer()
+10: ArrayBuffer(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
+9: ArrayBuffer(2, 3, 4, 5, 6, 7, 8, 9, 10)
+1
+ArrayBuffer(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
+new test starting with List()
+10: List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
+9: List(2, 3, 4, 5, 6, 7, 8, 9, 10)
+1
+List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
+new test starting with List()
+10: List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
+9: List(2, 3, 4, 5, 6, 7, 8, 9, 10)
+1
+List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
+new test starting with Vector()
+10: Vector(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
+9: Vector(2, 3, 4, 5, 6, 7, 8, 9, 10)
+1
+Vector(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
+new test starting with Vector()
+10: Vector(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
+9: Vector(2, 3, 4, 5, 6, 7, 8, 9, 10)
+1
+Vector(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
+new test starting with List()
+10: List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
+9: List(2, 3, 4, 5, 6, 7, 8, 9, 10)
+1
+List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
+new test starting with ArrayBuffer()
+10: ArrayBuffer(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
+9: ArrayBuffer(2, 3, 4, 5, 6, 7, 8, 9, 10)
+1
+ArrayBuffer(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
+true
+false
+true
+List((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))
+List((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))
+List((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))
+List((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))
+List((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))
+List((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))
+List((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))
+List((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))
+List((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))
+List((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))
+List((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))
+List((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))
diff --git a/test/files/run/colltest1.scala b/test/files/run/colltest1.scala
new file mode 100644
index 0000000..a505847
--- /dev/null
+++ b/test/files/run/colltest1.scala
@@ -0,0 +1,237 @@
+import collection._
+
+object Test extends Application {
+
+  def orderedTraversableTest(empty: Traversable[Int]) {
+    println("new test starting with "+empty)
+    assert(empty.isEmpty)
+    val ten = empty ++ List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
+    println(ten.size+": "+ten)
+    println(ten.tail.size+": "+ten.tail)
+    assert(ten == empty ++ (1 to 10))
+    assert(ten.size == 10)
+    assert(ten forall (_ <= 10))
+    assert(ten exists (_ == 5))
+    assert((ten count (_ % 2 == 0)) == 5)
+    assert((ten find (_ % 2 == 0)) == Some(2))
+    assert((0 /: ten)(_ + _) == 55)
+    assert((ten :\ 0)(_ + _) == 55)
+    println(ten.head)
+    val x = ten reduceLeft (_ + _)
+    assert(x == 55, x)
+    assert((ten reduceRight (_ + _)) == 55)
+    val firstFive = empty ++ (1 to 5)
+    val secondFive = empty ++ (6 to 10)
+    assert(firstFive ++ secondFive == ten, firstFive ++ secondFive)
+    val odds = ten filter (_ % 2 != 0)
+    val evens = ten filterNot (_ % 2 != 0)
+    assert(odds.size == evens.size)
+    val (o, e) = ten.partition(_ % 2 == 0)
+    assert(o.size == e.size)
+    val gs = ten groupBy (x => x / 4)
+    val vs1 = (for (k <- gs.keysIterator; v <- gs(k).toIterable.iterator) yield v).toList.sorted
+    val vs2 = gs.values.toList.flatten.sorted
+//    val vs2 = gs.values.toList flatMap (xs => xs)
+    assert(ten.head == 1)
+    assert(ten.tail.head == 2)
+    assert(ten.tail.size == 9)
+    assert(ten.tail.foldLeft(10)(_ + _) == 64)
+    assert(ten.last == 10)
+    assert(List(ten.head) ++ ten.tail == ten)
+    assert(ten.init ++ List(ten.last) == ten, ten.init)
+    assert(vs1 == vs2, vs1+"!="+vs2)
+    assert(vs1 == ten)
+    assert((ten take 5) == firstFive)
+    assert((ten drop 5) == secondFive)
+    assert(ten slice (3, 3) isEmpty)
+    assert((ten slice (3, 6)) == List(4, 5, 6), ten slice (3, 6))
+    assert((ten takeWhile (_ <= 5)) == firstFive)
+    assert((ten dropWhile (_ <= 5)) == secondFive)
+    assert((ten span (_ <= 5)) == (firstFive, secondFive))
+    assert((ten splitAt 5) == (firstFive, secondFive), ten splitAt 5)
+    val buf = new mutable.ArrayBuffer[Int]
+    firstFive copyToBuffer buf
+    secondFive copyToBuffer buf
+    assert(buf.result == ten, buf.result)
+    assert(ten.toArray.size == 10)
+    assert(ten.toArray.toSeq == ten, ten.toArray.toSeq)
+    assert(ten.toIterable == ten)
+    assert(ten.toList == ten)
+    assert(ten.toSeq == ten)
+    assert(ten.toStream == ten)
+    assert(ten.toString endsWith "(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)")
+    assert(ten.mkString("[", "; ", "]") endsWith "[1; 2; 3; 4; 5; 6; 7; 8; 9; 10]")
+  }                               
+
+  def orderedIterableTest(empty: Iterable[Int]) {
+    orderedTraversableTest(empty)
+    val six = empty ++ List(1, 2, 3, 4, 5, 6)
+    assert(six.iterator.toStream == six)
+    assert(six.takeRight(4) == List(3, 4, 5, 6), six.takeRight(4))
+    assert(six.dropRight(3) == List(1, 2, 3))
+    assert(six sameElements (1 to 6))
+  }
+
+  def sequenceTest(empty: Seq[Int]) {
+    orderedIterableTest(empty)
+    val ten = empty ++ (1 to 10)
+    println(ten)
+    val tenPlus = ten map (_ + 1)
+    assert((ten zip tenPlus) forall { case (x, y) => x + 1 == y })
+    val dble = ten flatMap (x => List(x, x))
+    assert(dble.distinct == ten)
+    assert(ten.length == 10)
+    assert(ten(0) == 1 && ten(9) == 10)
+    assert((ten lengthCompare 10) == 0 && (ten lengthCompare 1) > 0 && (ten lengthCompare 11) < 0)
+    assert((ten isDefinedAt 0) && (ten isDefinedAt 9))
+    assert(!(ten isDefinedAt -1)); 
+    assert(!(ten isDefinedAt 10))
+    val tenten = ten zip ten
+    assert((tenten map (_._1)) == ten)
+    assert((tenten map (_._2)) == ten)
+    assert(ten.zipWithIndex forall { case (x, y) => x == y + 1 })
+    assert(ten.segmentLength(_ <= 8, 4) == 4, ten.segmentLength(_ <= 8, 4))
+    assert(ten.prefixLength(_ <= 8) == 8)
+    assert(ten.indexWhere(_ >= 8, 4) == 7, ten.indexWhere(_ >= 8, 4))
+    assert(ten.indexWhere(_ >= 8) == 7)
+    assert(ten.indexOf(5) == 4)
+    assert(ten.indexOf(5, 4) == 4)
+    assert(ten.indexOf(5, 5) == -1)
+    assert(ten.lastIndexOf(5) == 4, ten.lastIndexOf(5))
+    assert(ten.lastIndexOf(5, 4) == 4)
+    assert(ten.lastIndexOf(5, 3) == -1)
+    assert(ten.lastIndexWhere(_ <= 8) == 7)
+    assert(ten.lastIndexWhere(_ <= 8, 6) == 6)
+    assert(ten.lastIndexWhere(_ <= 8, 8) == 7)
+    assert(ten.reverse startsWith List(10, 9, 8), ten.reverse.take(10).toList)
+    assert(ten.reverse.length == 10)
+    assert(ten.reverse.reverse == ten)
+    assert(ten.reverseIterator.toList.reverse == ten, ten.reverseIterator.toList)
+    assert(ten.startsWith(List(1)))
+    assert(ten.startsWith(List(3, 4), 2))
+    assert(ten.endsWith(List(9, 10)))
+    assert(ten.endsWith(List()))
+    assert(ten.indexOfSlice(List(3, 4, 5)) == 2, ten.indexOfSlice(List(3, 4, 5)))
+    assert(ten.lastIndexOfSlice(List(8, 9, 10)) == 7)
+    assert(ten.lastIndexOfSlice(List(1, 2, 3)) == 0)
+    assert(ten.lastIndexOfSlice(List(9, 10, 11)) == -1)
+    assert(ten contains 1)
+    assert(ten contains 10)
+    assert(!(ten contains 0))
+    assert((empty ++ (1 to 7) union empty ++ (3 to 10)) == List(1, 2, 3, 4, 5, 6, 7, 3, 4, 5, 6, 7, 8, 9, 10))
+    assert((ten diff ten).isEmpty)
+    assert((ten diff List()) == ten)
+    assert((ten diff (ten filter (_ % 2 == 0))) == (ten filterNot  (_ % 2 == 0)))
+    assert((ten intersect ten) == ten)
+    assert((ten intersect List(5)) == List(5))
+    assert((ten ++ ten).distinct == ten)
+    assert(ten.patch(3, List(4, 5, 6, 7), 4) == ten)
+    assert(ten.patch(0, List(1, 2, 3), 9) == List(1, 2, 3, 10))
+    assert(empty.padTo(10, 7) == Array.fill(10)(7).toSeq)
+    assert((ten zip ten.indices) == ten.zipWithIndex)
+    assert(ten.sortWith(_ < _) == ten)
+    assert(ten.sortWith(_ > _) == ten.reverse)
+  }
+
+  def setTest(empty: => Set[String]) {
+    var s = empty + "A" + "B" + "C"
+    s += ("D", "E", "F")
+    s ++= List("G", "H", "I")
+    s ++= ('J' to 'Z') map (_.toString)
+    assert(s forall (s contains))
+    assert(s contains "X")
+    assert(!(s contains "0"))
+    s = s + "0"
+    assert(s contains "0")
+    s = s - "X"
+    assert(!(s contains "X"))
+    assert(empty.isEmpty)
+    assert(!s.isEmpty)
+    assert((s intersect s) == s)
+    assert((empty intersect s) == empty)
+    assert(!s.isEmpty)
+    val s1 = s intersect empty
+    assert(s1 == empty, s1)
+    def abc = empty + ("a", "b", "c")
+    def bc = empty + ("b", "c")
+    assert(bc subsetOf abc)
+  }
+
+  def rangeTest(r: Range) {
+    val ten = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
+    assert(r == ten)
+    assert(r.toList == ten)
+    assert((r filter (_ % 2 == 0)) == (ten filter (_ % 2 == 0)))
+    println((r map (_ + 1)) == (ten map (_ + 1)))
+    println((r map (_ * 2)) == (ten map (_ + 1)))
+    println((r flatMap (i => 0 until i)) == (ten flatMap (i => 0 until i)))
+  }
+
+  def mapTest(empty: => Map[String, String]) = {
+    var m = empty + ("A" -> "A") + ("B" -> "B") + ("C" -> "C")
+    m += (("D" -> "D"), ("E" -> "E"), ("F" -> "F"))
+    m ++= List(("G" -> "G"), ("H" -> "H"), ("I" -> "I"))
+    m ++= ('J' to 'Z') map (x => (x.toString -> x.toString))
+    println(m.toList.sorted)
+    assert(!m.isEmpty)
+    assert(m.keySet forall (k => (m get k) == Some(k))) 
+    assert(m.keySet forall (k => (m apply k) == k)) 
+    assert(m.keySet forall (m contains))
+    assert(m.getOrElse("7", "@") == "@")
+    assert(m.keySet.size == 26)
+    assert(m.size == 26)
+    assert(m.keySet == Set() ++ m.keysIterator)
+    assert(m.keySet == m.keysIterator.toList.toSet, m.keySet.toList+"!="+m.keysIterator.toList.toSet)
+    val m1 = empty ++ m
+    val mm = m -- m.keySet.toList
+    assert(mm.isEmpty, mm)
+    def m3 = empty ++ m1
+    assert(m1 == m3)
+    println(m3.toList.sorted)
+    val m4 = m3 filterNot { case (k, v) => k != "A" }
+    assert(m4.size == 1, m4)
+  }
+
+  def mutableMapTest(empty: => mutable.Map[String, String]) = {
+    mapTest(empty)
+    val m1 = empty ++ (('A' to 'Z') map (_.toString) map (x => (x, x)))
+    val m2 = m1 retain ((k, v) => k == "N")
+    assert(m2.size == 1, m2)
+  }
+
+  sequenceTest(Nil)
+  sequenceTest(List())
+  sequenceTest(Stream.empty)
+  sequenceTest(Array[Int]())
+  sequenceTest(mutable.ArrayBuffer())
+  sequenceTest(mutable.ListBuffer())
+  orderedTraversableTest(Traversable())
+  orderedTraversableTest(mutable.Traversable())
+  orderedTraversableTest(immutable.Traversable())
+  orderedIterableTest(Iterable())
+  orderedIterableTest(mutable.Iterable())
+  orderedIterableTest(immutable.Iterable())
+  sequenceTest(Seq())
+  sequenceTest(mutable.Seq())
+  sequenceTest(immutable.Seq())
+  sequenceTest(LinearSeq())
+  sequenceTest(IndexedSeq())
+  sequenceTest(Vector())
+//  sequenceTest(mutable.LinearSeq())
+  sequenceTest(immutable.LinearSeq())
+  sequenceTest(mutable.IndexedSeq())
+  rangeTest(1 to 10)
+
+  setTest(Set())
+  setTest(mutable.Set())
+  setTest(immutable.Set())
+  setTest(mutable.HashSet())
+  setTest(immutable.HashSet())
+
+  mapTest(Map())
+  mutableMapTest(mutable.Map())
+  mapTest(immutable.Map())
+  mapTest(immutable.TreeMap())
+  mutableMapTest(mutable.HashMap())
+  mapTest(immutable.HashMap())
+}
diff --git a/test/pending/run/complicatedmatch.check b/test/files/run/complicatedmatch.check
similarity index 100%
rename from test/pending/run/complicatedmatch.check
rename to test/files/run/complicatedmatch.check
diff --git a/test/pending/run/complicatedmatch.scala b/test/files/run/complicatedmatch.scala
similarity index 100%
rename from test/pending/run/complicatedmatch.scala
rename to test/files/run/complicatedmatch.scala
diff --git a/test/files/run/concurrent-stream.check b/test/files/run/concurrent-stream.check
new file mode 100644
index 0000000..d4adf84
--- /dev/null
+++ b/test/files/run/concurrent-stream.check
@@ -0,0 +1,3 @@
+Testing standard cons.
+Evaluation 0: List(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
+Evaluation 1: List(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
diff --git a/test/files/run/concurrent-stream.scala b/test/files/run/concurrent-stream.scala
new file mode 100644
index 0000000..42c6959
--- /dev/null
+++ b/test/files/run/concurrent-stream.scala
@@ -0,0 +1,36 @@
+// test concurrent calls to Stream.tail
+object Test  {
+
+def slowRange(from: Int, until: Int, cons: (Int, => Stream[Int]) => Stream[Int]): Stream[Int] = {
+  var current = from
+  def next: Stream[Int] = {
+    Thread.sleep(100)
+    if (current >= until) Stream.empty
+    else {
+      val stream = cons(current, next)
+      current += 1
+      stream
+    }
+  }
+  next
+}
+
+def testCons(cons: (Int, => Stream[Int]) => Stream[Int]): Unit = {
+  import scala.actors.Actor._
+
+  val stream = slowRange(0, 10, cons)
+  val main = self
+  actor { main ! stream.toList }
+  actor { main ! stream.toList }
+  val eval0 = receive { case list: List[Int] => list }
+  val eval1 = receive { case list: List[Int] => list }
+  println("Evaluation 0: " + eval0)
+  println("Evaluation 1: " + eval1)
+}
+
+  def main(args: Array[String]) {
+    println("Testing standard cons.")
+    testCons(Stream.cons.apply(_, _))
+  }
+}
+
diff --git a/test/files/run/constrained-types.check b/test/files/run/constrained-types.check
index c8f0a83..8050017 100644
--- a/test/files/run/constrained-types.check
+++ b/test/files/run/constrained-types.check
@@ -52,8 +52,8 @@ val y = b.y  // should keep the annotation
 y: Int @Annot(Stuff.x) = 10
 
 -----
-def m(x: String): String @Annot(x) = x     // m should be annotated with a debruijn
-m: (x$0:String)String @Annot(x)
+def m(x: String): String @Annot(x) = x
+m: (x: String)String @Annot(x)
 
 -----
 val three = "three"
@@ -69,11 +69,11 @@ four: java.lang.String = four
 
 -----
 val four2 = m(four) // should have an existential bound
-four2: String @Annot(x) forSome { val x: java.lang.String } = four
+four2: java.lang.String @Annot(x) forSome { val x: java.lang.String } = four
 
 -----
 val four3 = four2   // should have the same type as four2
-four3: String @Annot(x) forSome { val x: java.lang.String } = four
+four3: java.lang.String @Annot(x) forSome { val x: java.lang.String } = four
 
 -----
 val stuff = m("stuff") // should not crash
@@ -85,7 +85,7 @@ defined class peer
 
 -----
 class NPE[T <: NPE[T] @peer] // should not crash
-error: illegal cyclic reference involving class NPE
+defined class NPE
 
 -----
 def m = {
@@ -93,7 +93,7 @@ def m = {
   val y : String @Annot(x) = x
   y
 } // x should be existentially bound
-m: String @Annot(x) forSome { val x: java.lang.String }
+m: java.lang.String @Annot(x) forSome { val x: java.lang.String }
 
 -----
 def n(y: String) = {
@@ -105,7 +105,7 @@ def n(y: String) = {
   }
   m("stuff".stripMargin)
 } // x should be existentially bound
-n: (String)String @Annot(x) forSome { val x: String }
+n: (y: String)java.lang.String @Annot(x) forSome { val x: String }
 
 -----
 class rep extends Annotation
@@ -121,7 +121,7 @@ y: java.lang.String = hello
 
 -----
 val x = 3 : Int @Annot(e+f+g+h) //should have a graceful error message
-<console>:5: error: not found: value e
+<console>:6: error: not found: value e
        val x = 3 : Int @Annot(e+f+g+h) //should have a graceful error message
                               ^
 
diff --git a/test/files/run/constrained-types.scala b/test/files/run/constrained-types.scala
index d301991..b3d5254 100644
--- a/test/files/run/constrained-types.scala
+++ b/test/files/run/constrained-types.scala
@@ -45,7 +45,7 @@ object Test {
     "val y = b.y  // should keep the annotation",
 
 
-    "def m(x: String): String @Annot(x) = x     // m should be annotated with a debruijn",
+    "def m(x: String): String @Annot(x) = x",
     "val three = \"three\"",
     "val three2 = m(three:three.type)  // should change x to three",
     "var four = \"four\"",
@@ -89,6 +89,9 @@ object Test {
     val settings = new Settings
     settings.Xexperimental.value = true
     settings.selfInAnnots.value = true
+    settings.deprecation.value = true
+    // when running that compiler, give it a scala-library to the classpath
+    settings.classpath.value = System.getProperty("java.class.path")
 
     val interp = new Interpreter(settings)
 
diff --git a/test/files/run/constructors.scala b/test/files/run/constructors.scala
index 9c5a83e..9092643 100644
--- a/test/files/run/constructors.scala
+++ b/test/files/run/constructors.scala
@@ -1,5 +1,3 @@
-// $Id: constructors.scala 5359 2005-12-16 15:33:49Z dubochet $
-
 // Test constructors, including multiple ones.
 
 class A(x: Int, y: Int) {
diff --git a/test/files/run/deeps.check b/test/files/run/deeps.check
deleted file mode 100644
index f1925fc..0000000
--- a/test/files/run/deeps.check
+++ /dev/null
@@ -1,83 +0,0 @@
-false
-false
-true
-
-false
-false
-true
-
-x=Array(1)
-y=Array(1)
-false
-false
-true
-
-x=Array(Array(1), Array(1))
-y=Array(Array(1), Array(1))
-false
-false
-true
-
-x=Array(Array(Array(1), Array(1)), Array(Array(1), Array(1)))
-y=Array(Array(Array(1), Array(1)), Array(Array(1), Array(1)))
-false
-false
-true
-
-false
-false
-true
-false
-false
-true
-Array(true, false)
-Array(true, false)
-[true;false]
-true;false
-
-Array([Z at 0000000, [Z at 0000000)
-Array(Array(true, false), Array(true, false))
-[[true;false];[true;false]]
-true;false;true;false
-
-Array([[Z at 0000000, [[Z at 0000000)
-Array(Array(Array(true, false), Array(true, false)), Array(Array(true, false), Array(true, false)))
-[[[true;false];[true;false]];[[true;false];[true;false]]]
-true;false;true;false;true;false;true;false
-
-Array(1.0, 0.0)
-Array(1.0, 0.0)
-[1.0;0.0]
-1.0;0.0
-
-Array([D at 0000000, [D at 0000000)
-Array(Array(1.0, 0.0), Array(1.0, 0.0))
-[[1.0;0.0];[1.0;0.0]]
-1.0;0.0;1.0;0.0
-
-Array([[D at 0000000, [[D at 0000000)
-Array(Array(Array(1.0, 0.0), Array(1.0, 0.0)), Array(Array(1.0, 0.0), Array(1.0, 0.0)))
-[[[1.0;0.0];[1.0;0.0]];[[1.0;0.0];[1.0;0.0]]]
-1.0;0.0;1.0;0.0;1.0;0.0;1.0;0.0
-
-Array(a, b)
-Array(a, b)
-[a;b]
-a;b
-
-Array([Ljava.lang.String;@0000000, [Ljava.lang.String;@0000000)
-Array(Array(a, b), Array(a, b))
-[[a;b];[a;b]]
-a;b;a;b
-
-Array([[Ljava.lang.String;@0000000, [[Ljava.lang.String;@0000000)
-Array(Array(Array(a, b), Array(a, b)), Array(Array(a, b), Array(a, b)))
-[[[a;b];[a;b]];[[a;b];[a;b]]]
-a;b;a;b;a;b;a;b
-
-[[true; false]; [false]]
-[[1; 2]; [3]]
-[[1; 2]; [3]]
-
-Array(boo, and, foo)
-Array(a)
diff --git a/test/files/run/deeps.scala b/test/files/run/deeps.scala
deleted file mode 100644
index f80812b..0000000
--- a/test/files/run/deeps.scala
+++ /dev/null
@@ -1,112 +0,0 @@
-//############################################################################
-// deepEquals / deepToString
-//############################################################################
-// $Id: $
-
-//############################################################################
-
-object Test extends Application {
-
-  def testEquals1 {
-    println(Array(1) == Array(1))
-    println(Array(1) equals Array(1))
-    println(Array(1) deepEquals Array(1))
-    println  
-  }
-
-  def testEquals2 {
-    println(Array(Array(1), Array(2)) == Array(Array(1), Array(2)))
-    println(Array(Array(1), Array(2)) equals Array(Array(1), Array(2)))
-    println(Array(Array(1), Array(2)) deepEquals Array(Array(1), Array(2)))
-    println  
-  }
-
-  def testEquals3 {
-    val a1 = Array(1)
-    val b1 = Array(1)
-    val a2 = Array(a1, b1)
-    val b2 = Array(a1, b1)
-    val a3 = Array(a2, b2)
-    val b3 = Array(a2, b2)
-    def test[T](x: Array[T], y: Array[T]) {
-      println("x=" + x.deepToString)
-      println("y=" + y.deepToString)
-      println(x == y)
-      println(x equals y)
-      println(x deepEquals y)
-      println
-    }
-    test(a1, b1)
-    test(a2, b2)
-    test(a3, b3)
-  }
-
-  def testEquals4 {
-    println("boo:and:foo".split(':') == "boo:and:foo".split(':'))
-    println("boo:and:foo".split(':') equals "boo:and:foo".split(':'))
-    println("boo:and:foo".split(':') deepEquals "boo:and:foo".split(':'))
-
-    val xs = new java.util.ArrayList[String](); xs.add("a")
-    val ys = new java.util.ArrayList[String](); ys.add("a")
-    println(xs.toArray == ys.toArray)
-    println(xs.toArray equals ys.toArray)
-    println(xs.toArray deepEquals ys.toArray)
-  }
-
-  def testToString1 {
-    def sweep(s: String) =
-      s.replaceAll("D@[0-9a-fA-F]+", "D at 0000000")
-       .replaceAll("Z@[0-9a-fA-F]+", "Z at 0000000")
-       .replaceAll(";@[0-9a-fA-F]+", ";@0000000")
-    def test[T](a: Array[T]) {
-      println(sweep(a.toString))
-      println(a.deepToString)  
-      println(a.deepMkString("[", ";", "]"))
-      println(a.deepMkString(";"))
-      println
-    }
-
-    val ba1 = Array(true, false)
-    val ba2 = Array(ba1, ba1)
-    val ba3 = Array(ba2, ba2)
-    test(ba1)
-    test(ba2)
-    test(ba3)
-
-    val da1 = Array(1.0d, 0.0d)
-    val da2 = Array(da1, da1)
-    val da3 = Array(da2, da2)
-    test(da1)
-    test(da2)
-    test(da3)
-
-    val sa1 = Array("a", "b")
-    val sa2 = Array(sa1, sa1)
-    val sa3 = Array(sa2, sa2)
-    test(sa1)
-    test(sa2)
-    test(sa3)
-  }
-
-  def testToString2 {
-    println(Array(Array(true, false), Array(false)).deepMkString("[", "; ", "]"))
-    println(Array(Array('1', '2'), Array('3')).deepMkString("[", "; ", "]"))
-    println(Array(Array(1, 2), Array(3)).deepMkString("[", "; ", "]"))
-    println
-  }
-
-  def testToString3 {
-    println("boo:and:foo".split(':').deepToString)
-
-    val xs = new java.util.ArrayList[String](); xs.add("a")
-    println(xs.toArray.deepToString)
-  }
-
-  testEquals1
-  testEquals2
-  testEquals3
-  testEquals4
-  testToString1
-  testToString2
-  testToString3
-}
diff --git a/test/files/run/distinct.check b/test/files/run/distinct.check
new file mode 100644
index 0000000..b0883f3
--- /dev/null
+++ b/test/files/run/distinct.check
@@ -0,0 +1 @@
+abcdefghijklmnopqrstuvwxyz
diff --git a/test/files/run/distinct.scala b/test/files/run/distinct.scala
new file mode 100644
index 0000000..09e5a07
--- /dev/null
+++ b/test/files/run/distinct.scala
@@ -0,0 +1,15 @@
+/** This is a test to make sure distinct always
+ *  returns the first of any duplicated element.
+ */
+object Test {
+  val alphabet = 'a' to 'z' mkString ""
+  val alphaList = 'a' to 'z' toList
+  def shuffled = util.Random.shuffle(alphaList)
+  
+  def main(args: Array[String]): Unit = {
+    val longList = alphaList ++ (1 to 9 flatMap (_ => shuffled))
+    val result = longList.distinct mkString ""
+
+    println(result)
+  }
+}
diff --git a/test/files/run/docgenerator.scala b/test/files/run/docgenerator.scala
deleted file mode 100644
index b738231..0000000
--- a/test/files/run/docgenerator.scala
+++ /dev/null
@@ -1,288 +0,0 @@
-object Test {
-  import java.io.{File, FileReader, FileWriter}
-
-  /** Tests the generation of the HTML documentation for some Scala
-   *  code samples (see value 'code' below) with different scaladoc
-   *  options (currently -access:<value>).
-   *
-   *  @author Stephane Micheloud
-   */
-  def main(args: Array[String]) {
-    // overwrites value of UrlContext.generator in file DocUtil.scala
-    System.setProperty("doc.generator", "scaladoc")
-    var dirname = System.getProperty("scalatest.output")
-    if (dirname eq null) dirname = System.getProperty("java.io.tmpdir")
-    val tmpDir = new File(dirname)
-    tmpDir.mkdirs()
-    test1(tmpDir)
-    test2(tmpDir)
-  }
-
-  private def test1(tmpDir: File) {
-    def testOptions(inFile: File, outDirName: String, opts: String*) {
-      val outDir = createDir(tmpDir, outDirName)
-      val args = Array.concat(Array("-d", outDir.getPath, inFile.getPath), opts.toArray:Array[String])
-      if (MainDoc.main0(args)) {
-        for (name <- List("all-classes.html", "index.html")) {
-          val outFile = new File(outDir, name)
-          val n = outFile.length.toInt
-          val in = new FileReader(outFile)
-          val cbuf = new Array[Char](n)
-          in.read(cbuf, 0, n)
-          println(new String(cbuf))
-        }
-        println
-      }
-    }
-    val inFile = {
-      val f = new File(tmpDir.getPath, "docgenerator1.scala")
-      val writer = new FileWriter(f)
-      writer.write(code1, 0, code1.length)
-      writer.close
-      f
-    }
-    testOptions(inFile, "test1", "") // none (default is -access:protected)
-    testOptions(inFile, "test2", "-access:public")
-    testOptions(inFile, "test3", "-access:protected")
-    testOptions(inFile, "test4", "-access:private")
-  }
-
-  private def test2(tmpDir: File) {
-    val code ="""
-package annots
-
- at deprecated
-object Foo { val x = 0 }
-
- at deprecated
-class Bar { val x = 1 }
-
-object Foo1 {
-  @deprecated
-  object Foo11 { val x = 3 }
-}
-
-class Bar1 {
-  @deprecated
-  object Foo11 { val x = 2 }
-}
-
-class Bar2 {
-  def bar {
-    @deprecated
-    object Foo21 { val x = 4 }
-    ()
-  }
-}
-
-object Foo2 {
-  def foo {
-    @deprecated
-    object Foo21 { val x = 5 }
-    ()
-  }
-}
-"""
-    val inFile = {
-      val f = new File(tmpDir.getPath, "docgenerator2.scala")
-      val writer = new FileWriter(f)
-      writer.write(code, 0, code.length)
-      writer.close
-      f
-    }
-    val outDir = createDir(tmpDir, "annots1")
-    val args = Array.concat(Array("-d", outDir.getPath, inFile.getPath))
-    if (MainDoc.main0(args)) {
-      for (name <- List("all-classes.html", "index.html")) {
-        val outFile = new File(outDir, name)
-        val n = outFile.length.toInt
-        val in = new FileReader(outFile)
-        val cbuf = new Array[Char](n)
-        in.read(cbuf, 0, n)
-        println(new String(cbuf))
-      }
-      println
-    }
-  }
-
-  object MainDoc {
-    import scala.tools.nsc._
-    import scala.tools.nsc.doc.DefaultDocDriver
-    import scala.tools.nsc.reporters.ConsoleReporter
-    def error(msg: String) { Console.err.println(msg) }
-    var reporter: ConsoleReporter = _
-    def process(args: Array[String]) {
-      val docSettings = new scala.tools.nsc.doc.Settings(error)
-      reporter = new ConsoleReporter(docSettings)
-      val command = new CompilerCommand(List.fromArray(args), docSettings, error, false)
-      try {
-        object compiler extends Global(command.settings, reporter) {
-	  override def onlyPresentation = true
-	}
-        if (reporter.hasErrors) {
-          reporter.flush()
-          return
-        }
-        val run = new compiler.Run
-        run compile command.files
-        object generator extends DefaultDocDriver {
-          lazy val global: compiler.type = compiler
-          lazy val settings = docSettings
-        }
-        generator process run.units
-        reporter.printSummary()
-      } catch {
-        case ex @ FatalError(msg) =>
-          if (command.settings.debug.value)
-            ex.printStackTrace();
-        reporter.error(null, "fatal error: " + msg)
-      }
-    }
-    def main(args: Array[String]) {
-      process(args)
-      exit(if (reporter.hasErrors) 1 else 0)
-    }
-    // main returning a status (no exit code)
-    def main0(args: Array[String]): Boolean = {
-      process(args)
-      !reporter.hasErrors
-    }
-  }
-
-  private def createDir(parent: File, dirname: String): File = {
-    val outDir = new File(parent, dirname)
-    outDir.mkdir
-    outDir
-  }
-
-  private val code1 = """
-package examples
-
-abstract class C0 {
-  def foo_public
-  protected def foo_protected
-  private def foo_private {}
-  class C1_Public {
-    val x_public = ()
-    protected val x_protected = ()
-    private val x_private = ()
-  }
-  protected class C1_Protected {
-    val x_public = ()
-    protected val x_protected = ()
-    private val x_private = ()
-  }
-  private class C1_Private {
-    val x_public = ()
-    protected val x_protected = ()
-    private val x_private = ()
-  }
-}
-
-protected abstract class C0_Protected {
-  def foo_public
-  protected def foo_protected
-  private def foo_private {}
-  class C1_Public {
-    val x_public = ()
-    protected val x_protected = ()
-    private val x_private = ()
-  }
-  protected class C1_Protected {
-    val x_public = ()
-    protected val x_protected = ()
-    private val x_private = ()
-  }
-  private class C1_Private {
-    val x_public = ()
-    protected val x_protected = ()
-    private val x_private = ()
-  }
-}
-
-private abstract class C0_Private {
-  def foo_public
-  protected def foo_protected
-  private def foo_private {}
-  class C1_Public {
-    val x_public = ()
-    protected val x_protected = ()
-    private val x_private = ()
-  }
-  protected class C1_Protected {
-    val x_public = ()
-    protected val x_protected = ()
-    private val x_private = ()
-  }
-  private class C1_Private {
-    val x_public = ()
-    protected val x_protected = ()
-    private val x_private = ()
-  }
-}
-
-
-object obj0 {
-  def bar_public {}
-  protected def bar_protected {}
-  private def bar_private {}
-  object obj1_Public {
-    val x_public = ()
-    protected val x_protected = ()
-    private val x_private = ()
-  }
-  protected object obj1_Protected {
-    val x_public = ()
-    protected val x_protected = ()
-    private val x_private = ()
-  }
-  private object obj1_Private {
-    val x_public = ()
-    protected val x_protected = ()
-    private val x_private = ()
-  }
-}
-
-protected object obj0_Protected {
-  def bar_public {}
-  protected def bar_protected {}
-  private def bar_private {}
-  object obj1_Public {
-    val x_public = ()
-    protected val x_protected = ()
-    private val x_private = ()
-  }
-  protected object obj1_Protected {
-    val x_public = ()
-    protected val x_protected = ()
-    private val x_private = ()
-  }
-  private object obj1_Private {
-    val x_public = ()
-    protected val x_protected = ()
-    private val x_private = ()
-  }
-}
-
-private object obj0_Private {
-  def bar_public {}
-  protected def bar_protected {}
-  private def bar_private {}
-  object obj1_Public {
-    val x_public = ()
-    protected val x_protected = ()
-    private val x_private = ()
-  }
-  protected object obj1_Protected {
-    val x_public = ()
-    protected val x_protected = ()
-    private val x_private = ()
-  }
-  private object obj1_Private {
-    val x_public = ()
-    protected val x_protected = ()
-    private val x_private = ()
-  }
-}
-"""
-}
diff --git a/test/files/run/elidable.check b/test/files/run/elidable.check
new file mode 100644
index 0000000..4ce04f0
--- /dev/null
+++ b/test/files/run/elidable.check
@@ -0,0 +1 @@
+Good for me, I was not elided.
diff --git a/test/files/run/elidable.flags b/test/files/run/elidable.flags
new file mode 100644
index 0000000..93fd3d5
--- /dev/null
+++ b/test/files/run/elidable.flags
@@ -0,0 +1 @@
+-Xelide-below 900
diff --git a/test/files/run/elidable.scala b/test/files/run/elidable.scala
new file mode 100644
index 0000000..264efba
--- /dev/null
+++ b/test/files/run/elidable.scala
@@ -0,0 +1,16 @@
+import annotation._
+import elidable._
+
+object Test {
+  @elidable(FINEST) def f1() = assert(false, "Should have been elided.")
+  @elidable(INFO) def f2() = assert(false, "Should have been elided.")
+  @elidable(SEVERE) def f3() = println("Good for me, I was not elided.")
+  @elidable(INFO) def f4 = assert(false, "Should have been elided (no parens).")
+  
+  def main(args: Array[String]): Unit = {
+    f1()
+    f2()
+    f3()
+    f4
+  }
+}
diff --git a/test/files/run/enums.check b/test/files/run/enums.check
index b76705b..f53aba8 100644
--- a/test/files/run/enums.check
+++ b/test/files/run/enums.check
@@ -1,4 +1,5 @@
 test Test1 was successful
 test Test2 was successful
 test Test3 was successful
+test Test4 was successful
 
diff --git a/test/files/run/enums.scala b/test/files/run/enums.scala
index f34ea17..fcca8d3 100644
--- a/test/files/run/enums.scala
+++ b/test/files/run/enums.scala
@@ -1,7 +1,6 @@
 //############################################################################
 // Enumerations
 //############################################################################
-// $Id: enums.scala 9116 2006-11-02 08:46:39Z mihaylov $
 
 object Test1 {
 
@@ -13,7 +12,7 @@ object Test1 {
     ! (d == WeekDays.Sat || d == WeekDays.Sun);
 
   def run: Int = {
-    val it = WeekDays filter (isWorkingDay);
+    val it = WeekDays.values filter (isWorkingDay);
     it.toList.length
   }
 }
@@ -30,7 +29,7 @@ object Test2 {
   }
 
   def run: Int = {
-    val it = for (val s <- ThreadState; s.id != 0) yield s;
+    val it = for (val s <- ThreadState.values; s.id != 0) yield s;
     it.toList.length
   }
 }
@@ -42,11 +41,30 @@ object Test3 {
   }
 
   def run: Int = {
-    val it = for (val d <- Direction; d.toString() startsWith "N") yield d;
+    val it = for (val d <- Direction.values; d.toString() startsWith "N") yield d;
     it.toList.length
   }
 }
 
+object Test4 {
+
+  object Direction extends Enumeration("North", "South", "East", "West") {
+    val North, South, East, West = Value;
+  }
+
+  def run: Int = {
+    val dir = Direction.withName("North")
+    assert(dir.toString == "North")
+    try {
+      Direction.withName("Nord")
+      assert(false)
+    } catch {
+      case e: Exception => /* do nothing */
+    }
+    0
+  }
+}
+
 //############################################################################
 // Test code
 
@@ -74,6 +92,7 @@ object Test {
     check_success("Test1", Test1.run, 5);
     check_success("Test2", Test2.run, 5);
     check_success("Test3", Test3.run, 1);
+    check_success("Test4", Test4.run, 0);
     Console.println;
   }
 }
diff --git a/test/files/run/equality.scala b/test/files/run/equality.scala
new file mode 100644
index 0000000..68055fd
--- /dev/null
+++ b/test/files/run/equality.scala
@@ -0,0 +1,40 @@
+// a quickly assembled test of equality.  Needs work.
+object Test
+{
+  import scala.runtime.ScalaRunTime.hash
+  
+  def makeFromInt(x: Int) = List(
+    x.toByte, x.toShort, x.toInt, x.toLong, x.toFloat, x.toDouble, BigInt(x), BigDecimal(x)
+  ) ::: (
+    if (x < 0) Nil else List(x.toChar)
+  )
+  def makeFromDouble(x: Double) = List(
+    x.toShort, x.toInt, x.toLong, x.toFloat, x.toDouble, BigInt(x.toInt), BigDecimal(x)
+  )
+  
+  def main(args: Array[String]): Unit = {
+    var xs = makeFromInt(5)
+    for (x <- xs ; y <- xs) {
+      assert(x == y, x + " == " + y)
+      assert(hash(x) == hash(y), "hash(%s) == hash(%s)".format(x, y))
+    }
+    
+    xs = makeFromInt(-5)
+    for (x <- xs ; y <- xs) {
+      assert(x == y, x + " == " + y)
+      assert(hash(x) == hash(y), "hash(%s) == hash(%s)".format(x, y))
+    }
+    
+    xs = makeFromDouble(500.0)
+    for (x <- xs ; y <- xs) {
+      assert(x == y, x + " == " + y)
+      assert(hash(x) == hash(y), "hash(%s) == hash(%s)".format(x, y))
+    }
+    
+    // negatives
+    val bigLong = new java.util.concurrent.atomic.AtomicLong(Long.MaxValue)
+    assert(-1 != bigLong && bigLong != -1)  // bigLong.intValue() == -1
+    assert(BigDecimal(1.1) != 1L)
+    assert(1L != BigDecimal(1.1))
+  }
+}
diff --git a/test/files/run/exceptions-2.scala b/test/files/run/exceptions-2.scala
index 52120a6..d0312a4 100644
--- a/test/files/run/exceptions-2.scala
+++ b/test/files/run/exceptions-2.scala
@@ -1,7 +1,5 @@
 /*
  * Try exception handling and finally blocks.
- *
- * $Id: exceptions-2.scala 15975 2008-08-31 11:40:19Z cunei $
  */
 
 trait Tree extends Exception;
@@ -269,6 +267,23 @@ object Test {
     try { 1 } catch { case e: java.io.IOException => () }
   }
 
+  /** Test that empty finally clauses containing while are correctly emitted.
+   */
+  class Issue {
+    var b = 0
+    try {
+      //    println("abc")
+    } finally {
+      while (b == -1) {b = 0}
+    }
+  }
+
+  /* Tests that class Issue passes verification. */
+  def whileInFinally = {
+    new Issue
+  }
+
+
 
   def main(args: Array[String]): Unit = {
     Console.println("nested1: ");
@@ -328,5 +343,7 @@ object Test {
 
     Console.println("Return with finally clause that cleans the stack")
     returnWithFinallyClean
+
+    whileInFinally
   }
 }
diff --git a/test/files/run/exceptions-nest.check b/test/files/run/exceptions-nest.check
new file mode 100644
index 0000000..48725e4
--- /dev/null
+++ b/test/files/run/exceptions-nest.check
@@ -0,0 +1,13 @@
+2
+23
+2
+5
+2
+4
+OK
+4
+OK
+10
+1
+()
+10
diff --git a/test/files/run/exceptions-nest.scala b/test/files/run/exceptions-nest.scala
new file mode 100644
index 0000000..d3f3745
--- /dev/null
+++ b/test/files/run/exceptions-nest.scala
@@ -0,0 +1,157 @@
+object Test extends Application {
+
+  println(test1)
+  println(test2)
+  println(test3)
+  println(test4)
+  println(test5)
+  try { println(test6) } catch { case _ => println("OK") }
+  println(test7)
+  try { println(test8) } catch { case _ => println("OK") }
+  println(test9)
+  println(test10)
+  println(test11)
+  println(test12)
+
+  def test1 = {
+    var x = 1
+    try {
+      x = 2
+    } catch {
+      case _: NullPointerException => x = 3
+      case _ => x = 4
+    }
+    x
+  }
+
+  def test2 = {
+    var x = 1
+    try {
+      x = 2
+      try {
+        x = 21
+      } catch {
+        case _ => x = 22
+      }
+      x = 23
+    } catch {
+      case _: NullPointerException => x = 3
+      case _ => x = 4
+    }
+    x
+  }
+
+  def test3 = {
+    var x = 1
+    try {
+      try{x = 2} catch { case _ => x = 4 }
+    } catch {
+      case _: NullPointerException => x = 3
+      case _ => x = 4
+    }
+    x
+  }
+
+  def test4 = {
+    var x = 1
+    try {
+      x = 2
+    } catch {
+      case _: NullPointerException => x = 3
+      case _ => x = 4
+    }
+    try {
+      x = 5
+    } catch {
+      case _: NullPointerException => x = 6
+    }
+    x
+  }
+
+  def test5 = {
+    var x = 1
+    try {
+      x = 2
+    } catch {
+      case _: NullPointerException => try { x = 3 } catch { case f => throw f }
+      case _ => x = 4; try { x = 41 } catch { case _: Exception => x = 42 }; x = 43
+    }
+    x
+  }
+
+  def test6: Int = {
+    var x = 1
+    try {
+      x = 2
+      (null: String).toString
+    } catch {
+      case e: NullPointerException =>
+        throw e
+      case _ =>
+        x = 3
+        return 1000
+    } finally {
+      x = 4
+      println(x)
+    }
+    x
+  }
+
+  def test7 = {
+    var x = 1
+    try {
+      x = 2
+    } finally {
+      try {
+        x = 4
+      } catch {
+        case _ => x = 5
+      }
+    }
+    x
+  }
+
+  def test8 = {
+    var x = 1
+    try {
+      throw new NullPointerException
+    } catch {
+      case e => throw e
+    }
+    x
+  }
+
+  def test9 = {
+    try { "" match {
+      case s: String => 10
+    }} catch { case _ => 20 }
+  }
+
+  var x10 = 1
+  def test10: Int = {
+    try { 1 }
+    catch { case e if (x10 == 1) => 1 }
+  }
+
+   def test11 {
+    try { () }
+    catch { case e => () }
+  }
+
+  class E1 extends Exception
+  class E2 extends Exception
+  class E3 extends Exception
+
+  def test12_impl(op: => Int) = try {
+    op
+  } catch {
+    case e: E1 => 2
+    case e: E2 => 3
+    case e: E3 => 4
+  }
+  def test12 =
+    test12_impl(1) +
+    test12_impl(throw new E1) +
+    test12_impl(throw new E2) +
+    test12_impl(throw new E3)
+}
diff --git a/test/files/run/exceptions.scala b/test/files/run/exceptions.scala
index 17d1e46..fc3566f 100644
--- a/test/files/run/exceptions.scala
+++ b/test/files/run/exceptions.scala
@@ -1,7 +1,6 @@
 //############################################################################
 // Exceptions
 //############################################################################
-// $Id: exceptions.scala 9116 2006-11-02 08:46:39Z mihaylov $
 
 //############################################################################
 
diff --git a/test/files/run/existentials.scala b/test/files/run/existentials.scala
index d95d32b..78980df 100644
--- a/test/files/run/existentials.scala
+++ b/test/files/run/existentials.scala
@@ -52,7 +52,7 @@ object Bug1189 {
 
 object Test extends Application {
 
-  val x = { class I[T]; (new C(new I[String]), new C(new I[Int])) }
+  val x = { class I; class J; (new C(new I), new C(new J)) }
   val y: (C[X], C[Y]) forSome { type X; type Y } = x
 
    def foo(x : Counter[T] { def name : String } forSome { type T }) = x match {
diff --git a/test/files/run/exoticnames.scala b/test/files/run/exoticnames.scala
index 7c8dcea..9250d62 100644
--- a/test/files/run/exoticnames.scala
+++ b/test/files/run/exoticnames.scala
@@ -4,4 +4,4 @@ object Test extends Application {
   def `.` = error("bla")
   def `)` = error("bla")
   def `,` = error("bla")
-}
\ No newline at end of file
+}
diff --git a/test/files/run/fors.scala b/test/files/run/fors.scala
index 7465b01..868a053 100644
--- a/test/files/run/fors.scala
+++ b/test/files/run/fors.scala
@@ -1,7 +1,6 @@
 //############################################################################
 // for-comprehensions (old and new syntax)
 //############################################################################
-// $Id: $
 
 //############################################################################
 
diff --git a/test/files/run/forvaleq.scala b/test/files/run/forvaleq.scala
index f1e0cd1..2a95880 100644
--- a/test/files/run/forvaleq.scala
+++ b/test/files/run/forvaleq.scala
@@ -1,5 +1,4 @@
 // test "foo = expr" clauses in for comprehensions
-// $Id: forvaleq.scala 15311 2008-06-10 08:46:06Z michelou $
 
 import scala.collection.immutable.Queue
 import scala.{List=>L}
@@ -49,7 +48,7 @@ object Test {
     // make sure it works on non-Ls
     
  //   val input: Queue = Queue.Empty[int].incl(L.range(0,20))
-    val input = L.range(0, 20).elements
+    val input = L.range(0, 20).iterator
     val oddFirstTimesTwo =
       for {x <- input
           xf = firstDigit(x)
diff --git a/test/files/run/groupby.scala b/test/files/run/groupby.scala
new file mode 100644
index 0000000..fe08f52
--- /dev/null
+++ b/test/files/run/groupby.scala
@@ -0,0 +1,18 @@
+
+
+
+// Fixes #3422
+object Test {
+  
+  def main(args: Array[String]) { 
+    val arr = Array.range(0,10)
+    val map = arr groupBy (_%2)
+    val v1 = map(0)
+    val v2 = map(0)
+    // this should hold, of course, assuming also that group by returns a regular
+    // map implementation, and does nothing fancy - and it should return just a
+    // hash map by default.
+    assert(v1 eq v2)
+  }
+  
+}
diff --git a/test/files/run/hashCodeBoxesRunTime.scala b/test/files/run/hashCodeBoxesRunTime.scala
new file mode 100644
index 0000000..081a733
--- /dev/null
+++ b/test/files/run/hashCodeBoxesRunTime.scala
@@ -0,0 +1,28 @@
+// This only tests direct access to the methods in BoxesRunTime,
+// not the whole scheme.
+object Test
+{
+  import java.{ lang => jl }
+  import scala.runtime.BoxesRunTime.{ hashFromNumber, hashFromObject }
+  
+  def allSame[T](xs: List[T]) = assert(xs.distinct.size == 1, "failed: " + xs)
+  
+  def mkNumbers(x: Int): List[Number] =
+    List(x.toByte, x.toShort, x, x.toLong, x.toFloat, x.toDouble)
+  
+  def testLDF(x: Long) = allSame(List[Number](x, x.toDouble, x.toFloat) map hashFromNumber)
+   
+  def main(args: Array[String]): Unit = {
+    List(Byte.MinValue, -1, 0, 1, Byte.MaxValue) foreach { n => 
+      val hashes = mkNumbers(n) map hashFromNumber
+      allSame(hashes)
+      if (n >= 0) {
+        val charCode = hashFromObject(n.toChar: Character)
+        assert(charCode == hashes.head)
+      }
+    }
+    
+    testLDF(Short.MaxValue.toLong)
+    testLDF(Short.MinValue.toLong)
+  }
+}
diff --git a/test/files/run/hashhash.scala b/test/files/run/hashhash.scala
new file mode 100644
index 0000000..5a78593
--- /dev/null
+++ b/test/files/run/hashhash.scala
@@ -0,0 +1,15 @@
+object Test
+{
+  class A { val x1 = this.## ; val x2 = super.## }
+  val myA = new A
+  assert(myA.x1 == myA.x2)
+  
+  def confirmSame(x: Any)       = assert(x.## == x.hashCode, "%s.## != %s.hashCode".format(x, x))
+  def confirmDifferent(x: Any)  = assert(x.## != x.hashCode, "%s.## == %s.hashCode (but should not)".format(x, x))
+    
+  def main(args: Array[String]): Unit = {
+    /** Just a little sanity check, not to be confused with a unit test. */
+    List(5, 5.5f, "abc", new AnyRef, new A, ()) foreach confirmSame
+    List(5.0f, 1.0d, -(5.0f), (-1.0d)) foreach confirmDifferent
+  }
+}
diff --git a/test/files/run/implicits.scala b/test/files/run/implicits.scala
index 3fd3561..e554575 100644
--- a/test/files/run/implicits.scala
+++ b/test/files/run/implicits.scala
@@ -23,3 +23,26 @@ object Test extends Application {
   Console.println(s)
   Console.println(2: String)
 }
+
+object TestPriority {
+
+  class C(x: Int) { def foo: Int = x + 1 }
+
+  class D(x: Int) { def foo: Int = x + 2 }
+
+  class IMPL {
+    implicit def Int2C(x: Int): C = new C(x)
+  }
+
+  object impl extends IMPL {
+    implicit def Int2D(x: Int): D = new D(x)
+  }
+
+  import impl._
+
+  val x: C = 2
+  val y: D = 2
+  assert(x.foo == 3, x.foo)
+  assert(y.foo == 4, y.foo)
+  assert((2).foo == 4, (2).foo)
+}
diff --git a/test/files/run/imports.scala b/test/files/run/imports.scala
index 4ce3b0a..4bdbef9 100644
--- a/test/files/run/imports.scala
+++ b/test/files/run/imports.scala
@@ -1,7 +1,6 @@
 //############################################################################
 // Import statements
 //############################################################################
-// $Id: imports.scala 11911 2007-06-05 15:57:59Z odersky $
 
 //############################################################################
 
diff --git a/test/files/run/infiniteloop.check b/test/files/run/infiniteloop.check
index be0b143..6f8cf6e 100644
--- a/test/files/run/infiniteloop.check
+++ b/test/files/run/infiniteloop.check
@@ -1 +1 @@
-Stream(512, ?)
+Stream(512, 256, 128, 64, 32, 16, 8, 4, 2, 1)
diff --git a/test/files/run/inliner-infer.check b/test/files/run/inliner-infer.check
new file mode 100644
index 0000000..d702bd6
--- /dev/null
+++ b/test/files/run/inliner-infer.check
@@ -0,0 +1,2 @@
+non-empty
+empty
diff --git a/test/files/run/inliner-infer.scala b/test/files/run/inliner-infer.scala
new file mode 100644
index 0000000..2c818c4
--- /dev/null
+++ b/test/files/run/inliner-infer.scala
@@ -0,0 +1,29 @@
+
+
+/** Test that the inliner is not inferring that `xs' is
+ *  always Nil, removing the call to isEmpty.
+ */
+object Test extends Application {
+
+  @annotation.tailrec
+  def walk(xs: MyList): Unit = {
+    if (xs.isEmpty) 
+      println("empty") 
+    else {
+      println("non-empty")
+      walk(MyNil)
+    }
+  }
+
+  walk(new MyList)
+}
+
+class MyList {
+  def isEmpty = false
+}
+
+object MyNil extends MyList {
+  override def isEmpty = true
+}
+
+  
diff --git a/test/files/run/iq.scala b/test/files/run/iq.scala
index d2e7d43..59baee1 100644
--- a/test/files/run/iq.scala
+++ b/test/files/run/iq.scala
@@ -1,4 +1,4 @@
-/* $Id: iq.scala 16113 2008-09-16 19:38:07Z spoon $ 
+/*
  * Test file for immutable queues.
  */
 
@@ -62,7 +62,7 @@ object iq {
      * Expected: q8: Queue(2,3,4,5,6,7,8,9,10,11)    
      */
     Console.println("q8: " + q8)
-    val q9 = new Queue(2,3,4,5,6,7,8,9,10,11)
+    val q9 = Queue(2,3,4,5,6,7,8,9,10,11)
 
     /* Testing ==
      *  Expected: q8 == q9: true
@@ -73,7 +73,7 @@ object iq {
      *  Expected: Elements:  1  2  3  4  5  6  7  8  9 
      */
     Console.print("Elements: "); 
-    q6.elements.foreach(e => Console.print(" "+ e + " "))
+    q6.iterator.foreach(e => Console.print(" "+ e + " "))
     Console.println; 
 
    /* Testing mkString
diff --git a/test/files/run/issue192.scala b/test/files/run/issue192.scala
index ec5ca5c..32e203a 100644
--- a/test/files/run/issue192.scala
+++ b/test/files/run/issue192.scala
@@ -63,8 +63,8 @@ object Test extends Application {
   print("f17 = "); println(f17(false) == (false && true))
   
   print("f18 = "); println(f18(4) == (4 << 7))
-  print("f19 = "); println(f19(4) == (4 >> 7))
-  print("f20 = "); println(f20(4) == (4 >>> 7))
+  print("f19 = "); println(f19(-4) == (-4 >> 7))
+  print("f20 = "); println(f20(-4) == (-4 >>> 7))
              
   print("f21 = "); println(f21(4.2) == (4.2.toByte))
   print("f22 = "); println(f22(4.2) == (4.2.toShort))
@@ -86,4 +86,4 @@ object Test extends Application {
   
   println("ok")
   
-}
\ No newline at end of file
+}
diff --git a/test/files/run/iterables.scala b/test/files/run/iterables.scala
index 5fb587a..5334b45 100644
--- a/test/files/run/iterables.scala
+++ b/test/files/run/iterables.scala
@@ -1,7 +1,7 @@
 object Test extends Application {
   class Test(n: Int) extends Iterable[Int] {
     private var i = 0
-    def elements = new Iterator[Int] {
+    def iterator = new Iterator[Int] {
       def hasNext = i < n
       def next =
         if (hasNext) { val v = i; i += 1; v }
diff --git a/test/files/run/iterator-iterate-lazy.scala b/test/files/run/iterator-iterate-lazy.scala
new file mode 100644
index 0000000..73886f1
--- /dev/null
+++ b/test/files/run/iterator-iterate-lazy.scala
@@ -0,0 +1,5 @@
+object Test {
+  def main(args: Array[String]): Unit = {
+    Iterator.iterate(1 to 5 toList)(_.tail).takeWhile(_.nonEmpty).map(_.head).toList
+  }
+}
diff --git a/test/files/run/iterator3444.scala b/test/files/run/iterator3444.scala
new file mode 100644
index 0000000..2d0643b
--- /dev/null
+++ b/test/files/run/iterator3444.scala
@@ -0,0 +1,23 @@
+
+
+// ticked #3444
+object Test {
+  
+  def main(args: Array[String]) {
+    val it = (1 to 12).toSeq.iterator
+    
+    assert(it.next == 1)
+    assert(it.take(2).toList == List(2, 3))
+    
+    val jt = (4 to 12).toSeq.iterator
+    assert(jt.next == 4)
+    assert(jt.drop(5).toList == List(10, 11, 12))
+    
+    val kt = (1 until 10).toSeq.iterator
+    assert(kt.drop(50).toList == Nil)
+    
+    val mt = (1 until 5).toSeq.iterator
+    assert(mt.take(50).toList == List(1, 2, 3, 4))
+  }
+  
+}
diff --git a/test/files/run/iterators.check b/test/files/run/iterators.check
index cd1b791..bb139c1 100644
--- a/test/files/run/iterators.check
+++ b/test/files/run/iterators.check
@@ -7,7 +7,7 @@ test check_drop was successful
 test check_foreach was successful
 test check_forall was successful
 test check_fromArray was successful
-test check_collect was successful
+test check_toSeq was successful
 test check_indexOf was successful
 test check_findIndexOf was successful
 
diff --git a/test/files/run/iterators.scala b/test/files/run/iterators.scala
index 497aaf5..f0f93f0 100644
--- a/test/files/run/iterators.scala
+++ b/test/files/run/iterators.scala
@@ -1,7 +1,6 @@
 //############################################################################
 // Iterators
 //############################################################################
-// $Id: iterators.scala 15216 2008-05-27 13:27:03Z stepancheg $
 
 //############################################################################
 
@@ -84,8 +83,8 @@ object Test {
     xs0.length + xs1.length + xs2.length + xs3.length + xs4.length
   }
   
-  def check_collect: String =
-    List(1, 2, 3, 4, 5).elements.collect.mkString("x")
+  def check_toSeq: String =
+    List(1, 2, 3, 4, 5).iterator.toSeq.mkString("x")
   
   def check_indexOf: String = {
     val i = List(1, 2, 3, 4, 5).indexOf(4)
@@ -94,8 +93,8 @@ object Test {
   }
   
   def check_findIndexOf: String = {
-    val i = List(1, 2, 3, 4, 5).findIndexOf { x: Int => x >= 4 }
-    val j = List(1, 2, 3, 4, 5).findIndexOf { x: Int => x >= 16 }
+    val i = List(1, 2, 3, 4, 5).indexWhere { x: Int => x >= 4 }
+    val j = List(1, 2, 3, 4, 5).indexWhere { x: Int => x >= 16 }
     "" + i + "x" + j
   }
 
@@ -125,7 +124,7 @@ object Test {
     check_success("check_foreach",  check_foreach,  190)
     check_success("check_forall",   check_forall,     0)
     check_success("check_fromArray",check_fromArray, 14)
-    check_success("check_collect",  check_collect, "1x2x3x4x5")
+    check_success("check_toSeq",  check_toSeq, "1x2x3x4x5")
     check_success("check_indexOf",     check_indexOf,     "3x-1")
     check_success("check_findIndexOf", check_findIndexOf, "3x-1")
     println()
diff --git a/test/files/run/json.check b/test/files/run/json.check
index a735624..021214b 100644
--- a/test/files/run/json.check
+++ b/test/files/run/json.check
@@ -1,12 +1,17 @@
-Some(List((name,value)))
-Some(List((name,va1ue)))
-Some(List((name,List((name1,va1ue1), (name2,va1ue2)))))
-Some(List((name,")))
-Some(List((age,0.0)))
+Passed: Map(name -> value)
+Passed: Map(name -> va1ue)
+Passed: Map(name -> Map(name1 -> va1ue1, name2 -> va1ue2))
+Passed: Map(name -> ")
+Passed: Map(function -> add_symbol)
+Passed: List(Map(a -> team), Map(b -> 52.0))
+Passed: Map()
+Passed: List()
+Passed: List(4.0, 1.0, 3.0, 2.0, 6.0, 5.0, 8.0, 7.0)
+Passed: Map(age -> 0.0)
 
-Some(List((firstName,John), (lastName,Smith), (address,List((streetAddress,21 2nd Street), (city,New York), (state,NY), (postalCode,10021.0))), (phoneNumbers,List(212 732-1234, 646 123-4567))))
+Passed: Map(firstName -> John, lastName -> Smith, address -> Map(streetAddress -> 21 2nd Street, city -> New York, state -> NY, postalCode -> 10021.0), phoneNumbers -> List(212 732-1234, 646 123-4567))
 
-Some(List((fullname,Sean Kelly), (org,SK Consulting), (emailaddrs,List(List((type,work), (value,kelly at seankelly.biz)), List((type,home), (pref,1.0), (value,kelly at seankelly.tv)))), (telephones,List(List((type,work), (pref,1.0), (value,+1 214 555 1212)), List((type,fax), (value,+1 214 555 1213)), List((type,mobile), (value,+1 214 555 1214)))), (addresses,List(List((type,work), (format,us), (value,1234 Main StnSpringfield, TX 78080-1216)), List((type,home), (format,us), (value,5678 Main Stn [...]
+Passed: Map(addresses -> List(Map(format -> us, type -> work, value -> 1234 Main StnSpringfield, TX 78080-1216), Map(format -> us, type -> home, value -> 5678 Main StnSpringfield, TX 78080-1316)), emailaddrs -> List(Map(type -> work, value -> kelly at seankelly.biz), Map(pref -> 1.0, type -> home, value -> kelly at seankelly.tv)), fullname -> Sean Kelly, org -> SK Consulting, telephones -> List(Map(pref -> 1.0, type -> work, value -> +1 214 555 1212), Map(type -> fax, value -> +1 214 555 1213) [...]
 
-Some(List((web-app,List((servlet,List(List((servlet-name,cofaxCDS), (servlet-class,org.cofax.cds.CDSServlet), (init-param,List((configGlossary:installationAt,Philadelphia, PA), (configGlossary:adminEmail,ksm at pobox.com), (configGlossary:poweredBy,Cofax), (configGlossary:poweredByIcon,/images/cofax.gif), (configGlossary:staticPath,/content/static), (templateProcessorClass,org.cofax.WysiwygTemplate), (templateLoaderClass,org.cofax.FilesTemplateLoader), (templatePath,templates), (templateOve [...]
+Passed: Map(web-app -> Map(servlet -> List(Map(init-param -> Map(cachePackageTagsRefresh -> 60.0, cachePackageTagsStore -> 200.0, cachePackageTagsTrack -> 200.0, cachePagesDirtyRead -> 10.0, cachePagesRefresh -> 10.0, cachePagesStore -> 100.0, cachePagesTrack -> 200.0, cacheTemplatesRefresh -> 15.0, cacheTemplatesStore -> 50.0, cacheTemplatesTrack -> 100.0, configGlossary:adminEmail -> ksm at pobox.com, configGlossary:installationAt -> Philadelphia, PA, configGlossary:poweredBy -> Cofax, co [...]
 
diff --git a/test/files/run/json.scala b/test/files/run/json.scala
index 2e7ee4a..6d25999 100644
--- a/test/files/run/json.scala
+++ b/test/files/run/json.scala
@@ -1,14 +1,80 @@
 import scala.util.parsing.json._
+import scala.collection.immutable.TreeMap
 
 object Test extends Application {
-  def printJSON(s: String) {
-    println(JSON parse s)
+  /* This method converts parsed JSON back into real JSON notation with objects in
+   * sorted-key order. Not required by the spec, but it allows us to to a stable
+   * toString comparison. */
+  def jsonToString(in : Any) : String = in match {
+    case l : List[_] => "[" + l.map(jsonToString).mkString(", ") + "]"
+    case m : Map[String,_] => "{" + m.elements.toList
+         .sort({ (x,y) => x._1 < y._1 })
+         .map({ case (k,v) => "\"" + k + "\": " + jsonToString(v) })
+         .mkString(", ") + "}"
+    case s : String => "\"" + s + "\""
+    case x => x.toString
   }
-  printJSON("{\"name\": \"value\"}")
-  printJSON("{\"name\": \"va1ue\"}")  // ticket #136
-  printJSON("{\"name\": { \"name1\": \"va1ue1\", \"name2\": \"va1ue2\" } }")
+
+  def sortJSON(in : Any) : Any = in match {
+    case l : List[_] => l.map(sortJSON)
+    case m : Map[String,_] => TreeMap(m.mapElements(sortJSON).elements.toSeq : _*)
+    case x => x
+  }
+
+  // For this one, just parsing should be considered a pass
+  def printJSON(given : String) {
+    JSON parseFull given match {
+      case None => println("Parse failed for \"%s\"".format(given))
+      case Some(parsed) => println("Passed: " + sortJSON(parsed))
+    }
+  }
+    
+  def printJSON(given : String, expected : Any) {
+    JSON parseFull given match {
+      case None => println("Parse failed for \"%s\"".format(given))
+      case Some(parsed) => if (parsed == expected) {
+        println("Passed: " + parsed)
+      } else {
+        val eStr = sortJSON(expected).toString
+        val pStr = sortJSON(parsed).toString
+
+        // Figure out where the Strings differ and generate a marker
+        val mismatchPosition = eStr.toList.zip(pStr.toList).findIndexOf({case (a,b) => a != b}) match {
+          case -1 => Math.min(eStr.length, pStr.length)
+          case x => x
+        }
+        val reason = (" " * mismatchPosition) + "^"
+        println("Expected, got:\n  %s\n  %s (from \"%s\")\n  %s".format(eStr, pStr, given, reason))
+      }
+    }
+  }
+
+  // The library should differentiate between lower case "l" and number "1" (ticket #136)
+  printJSON("{\"name\": \"value\"}", Map("name" -> "value"))
+  printJSON("{\"name\": \"va1ue\"}", Map("name" -> "va1ue"))
+  printJSON("{\"name\": { \"name1\": \"va1ue1\", \"name2\": \"va1ue2\" } }",
+            Map("name" -> Map("name1" -> "va1ue1", "name2" -> "va1ue2")))
+
+  // Unicode escapes should be handled properly
   printJSON("{\"name\": \"\\u0022\"}")
-  printJSON("{\"age\": 0}") 
+
+  // The library should return a map for JSON objects (ticket #873)
+  printJSON("""{"function":"add_symbol"}""", Map("function" -> "add_symbol"))
+
+  // The library should recurse into arrays to find objects (ticket #2207)
+  printJSON("""[{"a": "team"},{"b": 52}]""", List(Map("a" -> "team"), Map("b" -> 52.0)))
+  
+  // The library should differentiate between empty maps and lists (ticket #3284)
+  printJSON("{}", Map()) 
+  printJSON("[]", List())
+  
+  // Lists should be returned in the same order as specified
+  printJSON("[4,1,3,2,6,5,8,7]", List[Double](4,1,3,2,6,5,8,7))
+
+  // Additional tests
+  printJSON("{\"age\": 0}")
+
+
   println
 
   // from http://en.wikipedia.org/wiki/JSON
@@ -27,8 +93,25 @@ object Test extends Application {
         "646 123-4567"
     ]
 }"""
-  //println(sample1)
-  printJSON(sample1)
+
+  // Should be equivalent to:
+  val sample1Obj = Map(
+    "firstName" -> "John",
+    "lastName" -> "Smith",
+    "address" -> Map(
+      "streetAddress" -> "21 2nd Street",
+      "city" -> "New York",
+      "state" -> "NY",
+      "postalCode" -> 10021
+    ),
+    "phoneNumbers"-> List(
+        "212 732-1234",
+        "646 123-4567"
+    )
+  )
+
+  
+  printJSON(sample1, sample1Obj)
   println
 
   // from http://www.developer.com/lang/jscript/article.php/3596836
diff --git a/test/files/run/lazy-concurrent.check b/test/files/run/lazy-concurrent.check
new file mode 100644
index 0000000..33cff9d
--- /dev/null
+++ b/test/files/run/lazy-concurrent.check
@@ -0,0 +1 @@
+Initializing singleton.
diff --git a/test/files/run/lazy-concurrent.scala b/test/files/run/lazy-concurrent.scala
new file mode 100644
index 0000000..4699ed6
--- /dev/null
+++ b/test/files/run/lazy-concurrent.scala
@@ -0,0 +1,17 @@
+object Test {
+  def main(args: Array[String]) {
+    class Singleton {
+      val field = ()
+      println("Initializing singleton.")
+    }
+    lazy val Singleton = new Singleton
+
+    var i = 0
+    while (i < 4) {
+      new Thread(new Runnable {
+        def run = Singleton.field
+      }).start
+      i += 1
+    }
+  }
+}
diff --git a/test/files/run/lazy-leaks.scala b/test/files/run/lazy-leaks.scala
new file mode 100644
index 0000000..e7073b5
--- /dev/null
+++ b/test/files/run/lazy-leaks.scala
@@ -0,0 +1,18 @@
+class Lazy(f: => Int) {
+     lazy val get: Int = f
+}
+
+object Test extends Application
+{
+     val buffer = new scala.collection.mutable.ListBuffer[Lazy]
+
+     // This test requires 4 Mb of RAM if Lazy is discarding thunks
+     // It consumes 4 Gb of RAM if Lazy is not discarding thunks
+
+     for (val idx <- Iterator.range(0, 1024)) {
+         val data = new Array[Int](1024*1024)
+         val lz: Lazy = new Lazy(data.length)
+         buffer += lz
+         lz.get
+     }
+}
diff --git a/test/files/run/lazy-locals.check b/test/files/run/lazy-locals.check
index 63beca0..7d14da2 100644
--- a/test/files/run/lazy-locals.check
+++ b/test/files/run/lazy-locals.check
@@ -82,3 +82,8 @@ forced lazy val t at n = 5
 First 5 elements of ones: List(1, 1, 1, 1, 1)
 I am initialized when the constructor is run
 false
+forcing x
+forcing y
+42
+15
+42
diff --git a/test/files/run/lazy-locals.scala b/test/files/run/lazy-locals.scala
index 5279901..5755007 100644
--- a/test/files/run/lazy-locals.scala
+++ b/test/files/run/lazy-locals.scala
@@ -161,6 +161,28 @@ object Test extends Application {
     }
   }
 
+  // see #1589
+  object NestedLazyVals extends Application {
+    lazy val x = { 
+      lazy val y = { println("forcing y"); 42; }
+      println("forcing x")
+      y 
+    }
+    
+    val x1 = 5 + { lazy val y = 10 ; y }
+    
+    println(x)
+    println(x1)
+  }
+  
+  trait TNestedLazyVals {
+    lazy val x = { lazy val y = 42; y }
+  }
+
+  object ONestedLazyVals extends Application with TNestedLazyVals {
+    println(x)
+  }
+
   println(testLazy)
   testLazy32
   testLazy33
@@ -169,4 +191,6 @@ object Test extends Application {
   testRecVal
   new CtorBlock
   println(testReturnInLazyVal)
+  NestedLazyVals
+  ONestedLazyVals
 }
diff --git a/test/files/run/lisp.scala b/test/files/run/lisp.scala
index 69afb5d..63b6158 100644
--- a/test/files/run/lisp.scala
+++ b/test/files/run/lisp.scala
@@ -1,7 +1,6 @@
 //############################################################################
 // Lisp interpreter
 //############################################################################
-// $Id: lisp.scala 15114 2008-05-20 14:25:02Z michelou $
 
 //############################################################################
 // Lisp Scanner
@@ -333,7 +332,7 @@ object LispAny extends Lisp {
     val result = eval1(x, env);
     if (trace) {
       indent -= 1;
-      for (val x <- range(1, indent)) Console.print(" ");
+      for (x <- range(1, indent)) Console.print(" ");
       Console.println("<=== " + result);
     }
     curexp = prevexp;
diff --git a/test/files/run/lists.scala b/test/files/run/lists.scala
index 1b1a553..8a319c2 100644
--- a/test/files/run/lists.scala
+++ b/test/files/run/lists.scala
@@ -1,7 +1,6 @@
 //############################################################################
 // Lists
 //############################################################################
-// $Id: lists.scala 17137 2009-02-17 20:09:49Z rytz $
 
 //############################################################################
 
@@ -13,13 +12,85 @@ import testing.SUnit._
  */
 object Test extends TestConsoleMain {
   def suite = new TestSuite(
+    Test_multiset, // multiset operations: union, intersect, diff 
     Test1, //count, exists, filter, ..
     Test2, //#468
     Test3, //#1691
-    Test4  //#1721
+    Test4,  //#1721
+    Test5
   )
 }
 
+object Test_multiset extends TestCase("multiset") with Assert {
+  override def enableStackTrace = false
+  override def runTest {
+    def isSubListOf[A](thiz: List[A], that: List[A]): Boolean =
+      thiz forall (that contains _)
+    val xs = List(1, 1, 2)
+    val ys = List(1, 2, 2, 3)
+    assertEquals("xs_union_ys", List(1, 1, 2, 1, 2, 2, 3), xs union ys)
+    assertEquals("ys_union_xs", List(1, 2, 2, 3, 1, 1, 2), ys union xs)
+    assertEquals("xs_intersect_ys", List(1, 2), xs intersect ys)
+    assertEquals("ys_intersect_xs", List(1, 2), ys intersect xs)
+    assertEquals("xs_diff_ys", List(1), xs diff ys)
+    assertEquals("ys_diff_xs", List(2, 3), ys diff xs)
+    assertTrue("xs_subset_ys", isSubListOf(xs -- ys, xs diff ys))
+
+    val zs = List(0, 1, 1, 2, 2, 2)
+    assertEquals("zs_union_ys", List(0, 1, 1, 2, 2, 2, 1, 2, 2, 3), zs union ys)
+    assertEquals("ys_union_zs", List(1, 2, 2, 3, 0, 1, 1, 2, 2, 2), ys union zs)
+    assertEquals("zs_intersect_ys", List(1, 2, 2), zs intersect ys)
+    assertEquals("ys_intersect_zs", List(1, 2, 2), ys intersect zs)
+    assertEquals("zs_diff_ys", List(0, 1, 2), zs diff ys)
+    assertEquals("ys_diff_zs", List(3), ys diff zs)
+    assertTrue("xs_subset_ys", isSubListOf(zs -- ys, zs diff ys))
+
+    val ws = List(2)
+    assertEquals("ws_union_ys", List(2, 1, 2, 2, 3), ws union ys)
+    assertEquals("ys_union_ws", List(1, 2, 2, 3, 2), ys union ws)
+    assertEquals("ws_intersect_ys", List(2), ws intersect ys)
+    assertEquals("ys_intersect_ws", List(2), ys intersect ws)
+    assertEquals("ws_diff_ys", List(), ws diff ys)
+    assertEquals("ys_diff_ws", List(1, 2, 3), ys diff ws)
+    assertTrue("ws_subset_ys", isSubListOf(ws -- ys, ws diff ys))
+
+    val vs = List(3, 2, 2, 1)
+    assertEquals("xs_union_vs", List(1, 1, 2, 3, 2, 2, 1), xs union vs)
+    assertEquals("vs_union_xs", List(3, 2, 2, 1, 1, 1, 2), vs union xs)
+    assertEquals("xs_intersect_vs", List(1, 2), xs intersect vs)
+    assertEquals("vs_intersect_xs", List(2, 1), vs intersect xs)
+    assertEquals("xs_diff_vs", List(1), xs diff vs)
+    assertEquals("vs_diff_xs", List(3, 2), vs diff xs)
+    assertTrue("xs_subset_vs", isSubListOf(xs -- vs, xs diff vs))
+
+    // tests adapted from Thomas Jung 
+    assertTrue(
+      "be symmetric after sorting", {
+        def sort(zs: List[Int]) = zs sort ( _ > _ )
+        sort(xs intersect ys) == sort(ys intersect xs)
+      })
+    assertTrue(
+      "obey min cardinality", {
+        def cardinality[A](zs: List[A], e: A): Int = zs count (e == _)
+        val intersection = xs intersect ys
+        xs forall (e => cardinality(intersection, e) == (cardinality(xs, e) 
+min cardinality(ys, e)))
+      })
+    assertTrue(
+      "maintain order", {
+        val intersection = xs intersect ys
+		val unconsumed = xs.foldLeft(intersection){(rest, e) =>
+		  if (! rest.isEmpty && e == rest.head) rest.tail else rest
+		}
+		unconsumed.isEmpty
+      })
+    assertTrue(
+      "has the list as again intersection",
+      xs == (xs intersect xs)
+    )
+  }
+}
+
 object Test1 extends TestCase("ctor") with Assert {
   override def enableStackTrace = false
   override def runTest {
@@ -34,12 +105,6 @@ object Test1 extends TestCase("ctor") with Assert {
     val n2 = xs4 count { e => e < 5 }
     assertEquals("check_count", 4, n1 + n2)
   }
-  /* deprecated
-  {
-    val ys1 = xs1 diff xs4
-    val ys2 = xs3 diff xs5
-    assertEquals("check_diff", 3, ys1.length + ys2.length)
-  }*/
   {
     val b1 = xs1 exists { e => e % 2 == 0 }
     val b2 = xs4 exists { e => e == 5 }
@@ -61,21 +126,11 @@ object Test1 extends TestCase("ctor") with Assert {
     assertEquals("check_forall", true, b1 & b2)
   }
   {
-    val ys1 = xs1 intersect xs4
-    val ys2 = xs3 intersect xs5
-    assertEquals("check_intersect", 2, ys1.length + ys2.length)
-  }
-  {
-    val ys1 = xs1 remove { e => e % 2 != 0 }
-    val ys2 = xs4 remove { e => e < 5 }
+    val ys1 = xs1 filterNot { e => e % 2 != 0 }
+    val ys2 = xs4 filterNot { e => e < 5 }
     assertEquals("check_remove", 3, ys1.length + ys2.length)
   }
   {
-    val ys1 = xs1 union xs4
-    val ys2 = xs3 union xs5
-    assertEquals("check_union", 10, ys1.length + ys2.length)
-  }
-  {
     val ys1 = xs1 zip xs2
     val ys2 = xs1 zip xs3
     assertEquals("check_zip", 4, ys1.length + ys2.length)
@@ -96,7 +151,7 @@ object Test2 extends TestCase("t0468") with Assert {
     val xs2 = List(0)
  
     val ys1 = xs1 ::: List(4)
-    assertEquals("check_+", List(1, 2, 3, 4), ys1)
+    assertEquals("check_:::", List(1, 2, 3, 4), ys1)
 
     val ys2 = ys1 - 4
     assertEquals("check_-", xs1, ys2)
@@ -140,3 +195,16 @@ object Test4 extends TestCase("t1721") with Assert {
     assertTrue(List().endsWith(List()))
   }
 }
+
+object Test5 extends TestCase("list pattern matching") {
+  def show(xs: List[String]) = xs match {
+    case "foo" :: args => args.toString
+    case List(x) => x.toString
+    case Nil => "Nil"
+  }
+  override def runTest {
+    assert(show(List()) == "Nil")
+    assert(show(List("a")) == "a")
+    assert(show(List("foo", "b")) == "List(b)")
+  }
+}
diff --git a/test/files/run/literals.scala b/test/files/run/literals.scala
index 39f7efd..32bc29f 100644
--- a/test/files/run/literals.scala
+++ b/test/files/run/literals.scala
@@ -1,7 +1,6 @@
 //############################################################################
 // Literals
 //############################################################################
-// $Id: literals.scala 15311 2008-06-10 08:46:06Z michelou $
 
 //############################################################################
 
diff --git a/test/files/run/manifests.scala b/test/files/run/manifests.scala
new file mode 100644
index 0000000..1da06b8
--- /dev/null
+++ b/test/files/run/manifests.scala
@@ -0,0 +1,147 @@
+object Test
+{
+  object Variances extends Enumeration {
+    val CO, IN, CONTRA = Value
+  }
+  import Variances.{ CO, IN, CONTRA }
+  
+  object SubtypeRelationship extends Enumeration {
+    val NONE, SAME, SUB, SUPER = Value
+  }
+  import SubtypeRelationship.{ NONE, SAME, SUB, SUPER }
+  
+  class VarianceTester[T, U, CC[_]](expected: Variances.Value)(
+            implicit ev1: Manifest[T], ev2: Manifest[U], ev3: Manifest[CC[T]], ev4: Manifest[CC[U]]) {
+              
+    def elements = List(ev1 <:< ev2, ev2 <:< ev1)
+    def containers = List(ev3 <:< ev4, ev4 <:< ev3)
+
+    def isUnrelated = typeCompare[T, U] == NONE
+    def isSame = typeCompare[T, U] == SAME
+    def isSub = typeCompare[T, U] == SUB
+    def isSuper = typeCompare[T, U] == SUPER
+        
+    def showsCovariance = (elements == containers)
+    def showsContravariance = (elements == containers.reverse)
+    def showsInvariance = containers forall (_ == isSame)
+
+    def allContainerVariances = List(showsCovariance, showsInvariance, showsContravariance)
+    
+    def showsExpectedVariance =
+      if (isUnrelated) allContainerVariances forall (_ == false)
+      else if (isSame) allContainerVariances forall (_ == true)
+      else expected match {
+        case CO     => showsCovariance && !showsContravariance && !showsInvariance
+        case IN     => showsInvariance && !showsCovariance && !showsContravariance
+        case CONTRA => showsContravariance && !showsCovariance && !showsInvariance
+      }
+  }
+  
+  def showsCovariance[T, U, CC[_]](implicit ev1: Manifest[T], ev2: Manifest[U], ev3: Manifest[CC[T]], ev4: Manifest[CC[U]]) =
+    new VarianceTester[T, U, CC](CO) showsExpectedVariance
+
+  def showsInvariance[T, U, CC[_]](implicit ev1: Manifest[T], ev2: Manifest[U], ev3: Manifest[CC[T]], ev4: Manifest[CC[U]]) =
+    new VarianceTester[T, U, CC](IN) showsExpectedVariance
+    
+  def showsContravariance[T, U, CC[_]](implicit ev1: Manifest[T], ev2: Manifest[U], ev3: Manifest[CC[T]], ev4: Manifest[CC[U]]) =
+    new VarianceTester[T, U, CC](CONTRA) showsExpectedVariance
+  
+  def typeCompare[T, U](implicit ev1: Manifest[T], ev2: Manifest[U]) = (ev1 <:< ev2, ev2 <:< ev1) match {
+    case (true, true)   => SAME
+    case (true, false)  => SUB
+    case (false, true)  => SUPER
+    case (false, false) => NONE
+  }
+  
+  def assertAnyRef[T: Manifest] = List(
+    manifest[T] <:< manifest[Any],
+    manifest[T] <:< manifest[AnyRef],
+    !(manifest[T] <:< manifest[AnyVal])
+  ) foreach (assert(_, "assertAnyRef"))
+  
+  def assertAnyVal[T: Manifest] = List(
+    manifest[T] <:< manifest[Any],
+    !(manifest[T] <:< manifest[AnyRef]),
+    manifest[T] <:< manifest[AnyVal]
+  ) foreach (assert(_, "assertAnyVal"))
+  
+  def assertSameType[T: Manifest, U: Manifest] = assert(typeCompare[T, U] == SAME, "assertSameType")
+  def assertSuperType[T: Manifest, U: Manifest] = assert(typeCompare[T, U] == SUPER, "assertSuperType")
+  def assertSubType[T: Manifest, U: Manifest] = assert(typeCompare[T, U] == SUB, "assertSubType")
+  def assertNoRelationship[T: Manifest, U: Manifest] = assert(typeCompare[T, U] == NONE, "assertNoRelationship")
+  
+  def testVariancesVia[T: Manifest, U: Manifest] = assert(
+    typeCompare[T, U] == SUB && 
+    showsCovariance[T, U, List] &&
+    showsInvariance[T, U, Set],
+    "testVariancesVia"
+  )
+  
+  def runAllTests = {
+    assertAnyVal[AnyVal]
+    assertAnyVal[Unit]
+    assertAnyVal[Int] 
+    assertAnyVal[Double] 
+    assertAnyVal[Boolean]
+    assertAnyVal[Char]
+  
+    assertAnyRef[AnyRef]
+    assertAnyRef[java.lang.Object]
+    assertAnyRef[java.lang.Integer]
+    assertAnyRef[java.lang.Double]
+    assertAnyRef[java.lang.Boolean]
+    assertAnyRef[java.lang.Character]
+    assertAnyRef[String]
+    assertAnyRef[scala.List[String]]
+    assertAnyRef[scala.List[_]]
+        
+    // variance doesn't work yet
+    // testVariancesVia[String, Any]
+    // testVariancesVia[String, AnyRef]
+
+    assertSubType[List[String], List[Any]]
+    assertSubType[List[String], List[AnyRef]]
+    assertNoRelationship[List[String], List[AnyVal]]
+  
+    assertSubType[List[Int], List[Any]]
+    assertSubType[List[Int], List[AnyVal]]
+    assertNoRelationship[List[Int], List[AnyRef]]
+    
+    // Nothing
+    assertSubType[Nothing, Any]
+    assertSubType[Nothing, AnyVal]
+    assertSubType[Nothing, AnyRef]
+    assertSubType[Nothing, String]
+    assertSubType[Nothing, List[String]]
+    assertSubType[Nothing, Null]
+    assertSameType[Nothing, Nothing]
+    
+    // Null
+    assertSubType[Null, Any]
+    assertNoRelationship[Null, AnyVal]
+    assertSubType[Null, AnyRef]
+    assertSubType[Null, String]
+    assertSubType[Null, List[String]]
+    assertSameType[Null, Null]
+    assertSuperType[Null, Nothing]
+    
+    // Any
+    assertSameType[Any, Any]
+    assertSuperType[Any, AnyVal]
+    assertSuperType[Any, AnyRef]
+    assertSuperType[Any, String]
+    assertSuperType[Any, List[String]]
+    assertSuperType[Any, Null]
+    assertSuperType[Any, Nothing]
+    
+    // Misc unrelated types
+    assertNoRelationship[Unit, AnyRef]
+    assertNoRelationship[Unit, Int]
+    assertNoRelationship[Int, Long]
+    assertNoRelationship[Boolean, String]
+    assertNoRelationship[List[Boolean], List[String]]
+    assertNoRelationship[Set[Boolean], Set[String]]
+  }
+
+  def main(args: Array[String]): Unit = runAllTests
+}
diff --git a/test/files/run/mapValues.scala b/test/files/run/mapValues.scala
new file mode 100644
index 0000000..bd1794b
--- /dev/null
+++ b/test/files/run/mapValues.scala
@@ -0,0 +1,8 @@
+object Test {
+  val m = Map(1 -> 1, 2 -> 2)
+  val mv = (m mapValues identity) - 1
+  
+  def main(args: Array[String]): Unit = {
+    assert(mv.size == 1)
+  }
+}
diff --git a/test/files/run/map_java_conversions.scala b/test/files/run/map_java_conversions.scala
new file mode 100644
index 0000000..58ff471
--- /dev/null
+++ b/test/files/run/map_java_conversions.scala
@@ -0,0 +1,60 @@
+
+
+
+
+
+object Test {
+  
+  def main(args: Array[String]) {
+    import collection.JavaConversions._
+    
+    test(new java.util.HashMap[String, String])
+    test(new java.util.Properties)
+    testConcMap
+  }
+  
+  def testConcMap {
+    import collection.JavaConversions._
+    
+    val concMap = new java.util.concurrent.ConcurrentHashMap[String, String]
+    
+    test(concMap)
+    val cmap = asConcurrentMap(concMap)
+    cmap.putIfAbsent("absentKey", "absentValue")
+    cmap.put("somekey", "somevalue")
+    assert(cmap.remove("somekey", "somevalue") == true)
+    assert(cmap.replace("absentKey", "newAbsentValue") == Some("absentValue"))
+    assert(cmap.replace("absentKey", "newAbsentValue", ".......") == true)
+  }
+  
+  def test(m: collection.mutable.Map[String, String]) {
+    m.clear
+    assert(m.size == 0)
+    
+    m.put("key", "value")
+    assert(m.size == 1)
+    
+    assert(m.put("key", "anotherValue") == Some("value"))
+    assert(m.put("key2", "value2") == None)
+    assert(m.size == 2)
+    
+    m += (("key3", "value3"))
+    assert(m.size == 3)
+    
+    m -= "key2"
+    assert(m.size == 2)
+    assert(m.nonEmpty)
+    assert(m.remove("key") == Some("anotherValue"))
+    
+    m.clear
+    for (i <- 0 until 10) m += (("key" + i, "value" + i))
+    for ((k, v) <- m) assert(k.startsWith("key"))
+  }
+  
+}
+
+
+
+
+
+
diff --git a/test/files/run/matcharraytail.check b/test/files/run/matcharraytail.check
index 049db39..f2844d4 100644
--- a/test/files/run/matcharraytail.check
+++ b/test/files/run/matcharraytail.check
@@ -1,2 +1,2 @@
 Array(foo, bar, baz)
-Array(bar, baz)
+Vector(bar, baz)
diff --git a/test/files/run/matcharraytail.scala b/test/files/run/matcharraytail.scala
index cdd79ac..0ee95bc 100644
--- a/test/files/run/matcharraytail.scala
+++ b/test/files/run/matcharraytail.scala
@@ -1,6 +1,6 @@
 object Test extends Application{
   Array("foo", "bar", "baz") match {
-    case x at Array("foo", bar @_*) => println(x.toString); println(bar.toString);
+    case x at Array("foo", bar @_*) => println(x.deep.toString); println(bar.toString);
     case Array(x, y, z) => println("shouldn't have fallen through");
     case _ => println("default case?!");
   }
diff --git a/test/files/run/matchemptyarray.scala b/test/files/run/matchemptyarray.scala
index 63abf74..a7147f2 100644
--- a/test/files/run/matchemptyarray.scala
+++ b/test/files/run/matchemptyarray.scala
@@ -1,5 +1,5 @@
 object Test extends Application{
   Array[String]() match {
-    case x at Array() => println(x.toString());
+    case x at Array() => println(x.deep.toString());
   }
 }
diff --git a/test/files/run/matchnull.check b/test/files/run/matchnull.check
new file mode 100644
index 0000000..64861d8
--- /dev/null
+++ b/test/files/run/matchnull.check
@@ -0,0 +1,3 @@
+-1
+-1
+-1
diff --git a/test/files/run/matchnull.scala b/test/files/run/matchnull.scala
new file mode 100644
index 0000000..cfb3049
--- /dev/null
+++ b/test/files/run/matchnull.scala
@@ -0,0 +1,12 @@
+object Test
+{
+  def f1 = null match { case x: AnyRef => 1 case _ => -1 }
+  def f2(x: Any) = x match { case 52 => 1 ; case null => -1 ; case _ => 0 }
+  def f3(x: AnyRef) = x match { case x: String => 1 ; case List(_) => 0 ; case null => -1 ; case _ => -2 }
+  
+  def main(args: Array[String]): Unit = {
+    println(f1)
+    println(f2(null))
+    println(f3(null))
+  }
+}
diff --git a/test/files/run/misc.scala b/test/files/run/misc.scala
index 31fdc8f..139d2d7 100644
--- a/test/files/run/misc.scala
+++ b/test/files/run/misc.scala
@@ -1,5 +1,3 @@
-// $Id: misc.scala 15114 2008-05-20 14:25:02Z michelou $
-
 object Test {
 
   def fac(n: Int): Int = if (n < 2) 1 else fac(n - 1) * n;
diff --git a/test/files/run/mixins.scala b/test/files/run/mixins.scala
index 1479953..23aec6b 100644
--- a/test/files/run/mixins.scala
+++ b/test/files/run/mixins.scala
@@ -1,5 +1,3 @@
-// $Id: mixins.scala 5359 2005-12-16 15:33:49Z dubochet $
-
 // Test 1: "super" coming from mixins
 
 import Console._;
diff --git a/test/files/run/multi-array.check b/test/files/run/multi-array.check
index 2f236b9..f163dae 100644
--- a/test/files/run/multi-array.check
+++ b/test/files/run/multi-array.check
@@ -1,3 +1,4 @@
 Array(1, 2, 3)
 null
+Array(Array(0, 0, 0), Array(0, 0, 0), Array(0, 0, 0))
 Array(Array(0, 1, 2), Array(1, 2, 3), Array(2, 3, 4))
diff --git a/test/files/run/multi-array.scala b/test/files/run/multi-array.scala
index 1dbbad3..42f6475 100644
--- a/test/files/run/multi-array.scala
+++ b/test/files/run/multi-array.scala
@@ -5,8 +5,10 @@ object Test extends Application {
   val aaiIncomplete = new Array[Array[Array[Int]]](3)
   println(aaiIncomplete(0))
 
-  val aaiComplete: Array[Array[Int]] = new Array[Array[Int]](3, 3)
+  val aaiComplete: Array[Array[Int]] = Array.ofDim[Int](3, 3) // new Array[Array[Int]](3, 3)
+  println(aaiComplete.deep)
   for (i <- 0 until 3; j <- 0 until 3)
     aaiComplete(i)(j) = i + j
   println(aaiComplete.deepToString)
+  assert(aaiComplete.last.last == 4)
 }
diff --git a/test/files/run/names-defaults.check b/test/files/run/names-defaults.check
new file mode 100644
index 0000000..d31e98b
--- /dev/null
+++ b/test/files/run/names-defaults.check
@@ -0,0 +1,118 @@
+1: @
+get: $
+get: 2
+2: $
+get: 3
+get: **
+3: **
+get: 110
+get: 11
+get: \
+get: 2.399
+11: \, 110, 2.399
+get: 14
+get: 3920
+get: }
+get: [
+14: [, 3920, }
+get: 4
+get: @
+4: @
+get: 10
+get: flu
+10: flu
+get: 8
+get: 9
+get: %
+get: 5
+5: %, 17
+12: ', 13, 16
+1: bird, swine, 10
+20
+30
+40
+6: ~
+14: /
+100: 100: nix, nix, 982, 982, 0
+100: overridden, bla, 0, 0, 555
+100: overridden, , 93.3, 93.3, -1
+first
+first
+second
+first
+second
+second
+second
+first
+second
+f
+second
+second
+first
+third
+fourth
+fifth
+sixth
+first
+2, List(4, 4, 4)
+2, List()
+5
+get: 11
+11
+get: 1
+get: 2
+get: 2
+3
+0
+get: 20
+get: 20
+20
+0
+1
+dlkfj0dlkfj102
+lskf2dkflj2
+dlkd5nixda10nixdadklfj1dklfj
+C(dlkf,234,struct)struct???
+C(dflkj,234,Some(209))None!!
+dflk10
+1-1jupee
+12.39
+2
+Factory(1,blabla)
+Factory(-1,blabla)
+Fact2(ju,1)
+Fact2(1,1)
+Fact2(10,blabla)
+test5
+2
+test5
+3
+test5
+4
+test5
+5
+10: 2
+slkdfj1
+1
+lskfdjlk
+11
+2
+20
+10
+jaa
+kldfj110101
+klfj1
+blublu1
+my text
+List(1, 2)
+3
+3
+3
+3
+3
+3
+3
+3
+3
+3
+3
diff --git a/test/files/run/names-defaults.scala b/test/files/run/names-defaults.scala
new file mode 100644
index 0000000..ee08625
--- /dev/null
+++ b/test/files/run/names-defaults.scala
@@ -0,0 +1,470 @@
+object Test extends Application {
+  def get[T](x: T) = { println("get: "+ x); x }
+
+  // TESTS
+
+  // re-order using names, call-site evaluation order
+  test1(1, "@")
+  test1(b = get("$"), a = get(2))
+  test1(a = get(3), b = get("**")) // should not transform into a block. how to test?
+  test3(b = get(110), a = get(11))(c = get("\\"), d = get(2.399))
+  test3(get(14), get(3920))(d = get("}"), c = get("["))
+
+
+  // mixing named and positional
+  test1(get(4), b = get("@"))
+  test1(a = get(10), get("flu"))
+  test2(get(8), v = get(9))(get("%"), l = get(5))
+  test3(12, 13)("'", d = 16)
+  test3(a = 1, "swine")(c = "bird", d = 10L)
+
+
+  // anonymous functions
+  {
+    def doMod(f: Int => Unit) { f(20) }
+    var var1 = 0
+    doMod(var1 = _)
+    println(var1)
+
+    synchronized(var1 = 30)
+    println(var1)
+
+    var var2 = 0
+    def delay(var2: => Int) = { var2 }
+    println(delay(var2 = 40))
+  }
+  val f1: (Int, String) => Unit = test1(_, _); f1(6, "~")
+
+
+  test4(14)
+
+
+  // defaults: subclass overrides, adds and inherits default
+  val b = new Base
+  b.test1(b = "nix")(982)(f = 0)
+  val s = new Sub1
+  s.test1(a = new { override def toString = "bla" })(m = 0)()
+
+  // defaults are chosen dynamically
+  val b2: Base = new Sub1
+  b2.test1(b = "")(c = 93.3)(f = -1)
+
+
+
+  // overloading resolution
+  object t1 {
+    def f(a: Int, b: String) = "first"
+    def f(b: String, a: Int) = "second"
+  }
+  println(t1.f(1, "2")) // first
+
+  object t2 {
+    def f(a: Int, b: Double, c: Object) = "first"
+    def f(a: Int, b: Double, c: String) = "second"
+  }
+  println(t2.f(1, c = new Base(), b = 2.2)) // first
+  println(t2.f(28, b = 3.89, c = "ldksfj")) // second
+
+  object t3 {
+    def f(a1: Int) = "first"
+    def f(a2: Int)(b: Int) = "second"
+  }
+  println(t3.f(a1 = 10))    // first
+  println(t3.f(a2 = 20)(1)) // second
+
+  object t4 {
+    def f(a: Int, b: String = "foo") = "first"
+    def f(a: Int) = "second"
+  }
+  println(t4.f(109)) // second
+  println(t4.f(a = 20)) // second
+
+  object t5 {
+    def f(a: Object) = "first"
+    val f: String => String = a => "second"
+  }
+  println(t5.f(new Sub1())) // firsst
+  println(t5.f("dfklj"))    // second
+
+  object t6 {
+    def f(a: String = "sdf", b: Int) = "f"
+    def f(a: Int, b: Int) = "s"
+  }
+  println(t6.f(b = 289)) // f
+
+  object t7 {
+    def f(a: Int, b: String*) = "first"
+    def f(a: Int) = "second"
+    def g(a: Sub1, b: Int*) = "third"
+    def g(a: Base) = "fourth"
+    def h(a: Base, b: Int*) = "fifth"
+    def h(a: Sub1) = "sixth"
+  }
+  println(t7.f(1)) // second
+  println(t7.f(a = 19)) // second
+  println(t7.f(b = "sl19", a = 28)) // first
+  println(t7.g(new Sub1(), 1, 2)) // third
+  println(t7.g(new Base())) // fourth
+  println(t7.h(new Base())) // fifth
+  println(t7.h(new Sub1())) // sixth
+
+  object t9 {
+    def f(a: String, b: Int = 11) = "first"
+    def f(a: Double) = "second"
+  }
+  println(t9.f("bla")) // first
+
+
+  // vararg
+  def test5(a: Int, b: Int)(c: Int, d: String*) = a +", "+ d.toList
+  println(test5(b = 1, a = 2)(3, "4", "4", "4"))
+  println(test5(b = 1, a = 2)(c = 29))
+
+
+  // tuple conversion
+  def foo(a: Int, b: Int)(c: (Int, String)) = a + c._1
+  println(foo(b = 1, a = 2)(3, "4"))
+
+
+  // by-name parameters
+  def bn1(a: Int, b: => Int) = a
+  println(bn1(b = get(10), a = get(11))) // should not see get(10)
+
+  def bn2(a: Int, b: => Int)(c: Int = b) = a + b
+  println(bn2(b = get(2), a = get(1))()) // should get: 1, 2, 2
+
+  def bn3(a: => Int = get(10)) = 0
+  def bn4(a: => Int = get(20)) = {a; a}
+  println(bn3())
+  println(bn4())
+  println(bn4(a = 0))
+
+  class t2929(x: => Int = 1) {
+    def foo = x
+  }
+  println((new t2929()).foo)
+
+  // constructors
+  val a1 = new A(b = "dlkfj")(d = 102)
+  println(a1.print)
+  val a2 = new A[String, Nothing](2, "dkflj")(d = 2, c = "lskf")
+  println(a2.print)
+  val b1 = new B("dklfj")(e = "nixda")
+  println(b1.printB)
+  val c1 = new C(a = "dlkf", c = new { override def toString() = "struct" })(e = "???")
+  println(c1.print)
+  val c2 = C("dflkj", c = Some(209): Option[Int])(None, "!!")
+  println(c2.print)
+
+
+  // "super" qualifier
+  val b10 = new B1
+  println(b10.bar())
+
+
+  // defaults in traits / abstract classes
+  val mn = new MN
+  println(mn.foo()())
+  println(mn.bar(10))
+  // anonymous class
+  println((new M { def foo[T >: String](x: Int, y: T)(z: String = "2") = z ; def bar(x: Int, y: Double) = x }).foo()())
+
+  // copy method for case classes
+  val fact = Factory(y = "blabla")()
+  println(fact)
+  println(fact.copy(x = -1)("dldl"))
+
+  println(Fact2()("jyp"))
+  println(Fact2(x = 1)())
+  println(Fact2(10)().copy(y = "blabla")())
+
+
+  // assignment to var <-> named argument
+  var argName = 1
+  test5(argName = (argName = 2))
+  println(argName) // should be 2
+  test5({argName = 3})
+  println(argName) // should be 3
+  test5((argName = 4))
+  println(argName) // should be 4
+  test5 { argName = 5 }
+  println(argName) // should be 5
+  val a: Unit = test1(a = 10, b = "2") // local values a and b exist, but not ambiuous since they're val's
+
+
+  // dependent types and copy method
+  val a11 = new A2
+  val b11 = a11.B2(new a11.C2)(1)
+  println(b11.copy()())
+
+
+
+  // bug #2057
+  class O { class I(val x: Int = 1) }
+  class U extends O { val f = new I() }
+  val u1 = new U
+  println(u1.f.x)
+
+
+  // names / defaults in self constructor call
+  new A3("lskfdjlk")
+  new A4(1.23, ",")
+
+
+  // names / defaults in super constructor call
+  new B4()
+  new B5()
+
+  // no re-naming of parameters which are free in a closure of the body (lambdalift)
+  println(test6(10)())
+  test7("jaa")
+
+  // implicits + defaults
+  {
+    implicit val implInt = 10101
+    println(test8())
+  }
+
+  println(test9)
+
+  {
+    implicit val implString = "blublu"
+    println(test9)
+  }
+
+
+  // result type of default getters: parameter type, except if this one mentions any type
+  // parameter, in which case the result type is inferred. examples:
+
+  // result type of default getter is "String => String". if it were infered, the compiler
+  // would put "Nothing => Nothing", which is useless
+  def transform(s: String, f: String => String = identity _) = f(s)
+  println(transform("my text"))
+
+
+  // a bug reported on a mailing list: see comment in Typer.typedModuleDef
+  object TT
+  class TT(x: Int = 1)
+  val v = new TT()
+
+
+  // result type of the default getter is inferred (parameter type mentions type parameter T)
+  def test10[T](x: List[T] = List(1,2)) = x
+  println(test10())
+
+  // some complicated type which mentions T
+  def test11[T[P]](x: T[T[List[T[X forSome { type X }]]]] = List(1,2)) = x
+  // (cannot call f using the default, List(1,2) doesn't match the param type)
+
+  def multinest = { def bar(x: Int = 1) = { def bar(x: Int = 2) = x; bar() + x }; bar() }
+  println(multinest)
+
+
+  // #2290
+  def spawn(a: Int, b: => Unit) = { () }
+  def t {
+    spawn(b = { val ttt = 1; ttt }, a = 0)
+  }
+
+  // #2382
+  class A2382[+T](x: T => Int) { def foo(a: T => Int = x) = 0 }
+
+  // #2390
+  case class A2390[T](x: Int) { def copy(a: Int)(b: Int = 0) = 0 }
+
+  // #2489
+  class A2489 { def foo { def bar(a: Int = 1) = a; bar(); val u = 0 } }
+
+  // a bug reported on the mailing lists, related to #2489
+  class Test2489 {
+    def foo(): Int = {
+      val i = 10
+      case class Foo(j: Int)
+      i
+    }
+  }
+
+  // #2784
+  class Test2784 {
+    object t { def f(x: Int) = x }
+    val one = t f (x = 1)
+  }
+
+  // #2820
+  class Test2820 {
+    class A[T](f: String = "ski!")
+    class C extends A
+  }
+
+  object t3178 {
+    def foo(x: String) = x
+    def foo(x: Int) = x
+    def bar(foo: Int) = foo
+    bar(foo = 1)
+  }
+
+
+  // #3207
+  trait P3207[T] {
+    class Inner(val f: T => Unit = (x: T) => println(x))
+  }
+
+  object Test3207_1 {
+    val p = new P3207[Int] {}
+    val q = new p.Inner() {
+      def g = 0
+    }
+  }
+
+  object Test3207_2 {
+    val p = new P3207[Int] {
+      val inner = new Inner() {
+        def g = 0
+      }
+    }
+  }
+
+  // #3344
+  def m3344_1 = { case class C(x: Int); C(1).copy(2).x }
+  m3344_1
+  def m3344_2 = { class C(val x: Int = 1); new C().x }
+  m3344_2
+
+  // #3338
+  object t3338 {
+    class Container {
+      class GenericClass[T](arg: String = "")
+    }
+
+    object Container extends Container
+
+    class Test {
+      val a = new Container.GenericClass()
+    }
+  }
+  (new t3338.Test).a
+
+
+  // subclassing and defaults in both class constructors
+  class CBLAH(val x: Int = 1)
+  class DBLAH(val y: String = "2") extends CBLAH()
+  (new DBLAH())
+
+
+  // #3697
+  object t3697 {
+    def a(x: Int*)(s: Int = 3) = s
+    def b(a: Int, b: Int, c: Int*) = a + b
+  }
+  println(t3697.a(Seq(3): _*)())
+  println(t3697.a(3)())
+  println(t3697.a()())
+  println(t3697.a(2,3,1)())
+  println(t3697.b(a = 1, b = 2))
+  println(t3697.b(a = 1, b = 2, 3))
+  println(t3697.b(b = 1, a = 2, c = 3))
+  println(t3697.b(a = 1, b = 2, 3, 4))
+  println(t3697.b(a = 1, b = 2, Seq(3, 4): _*))
+  println(t3697.b(b = 1, a = 2, c = Seq(3, 4): _*))
+
+
+  // DEFINITIONS
+  def test1(a: Int, b: String) = println(a +": "+ b)
+  def test2(u: Int, v: Int)(k: String, l: Int) = println(l +": "+ k +", "+ (u + v))
+
+  def test3[T1, T2](a: Int, b: T1)(c: String, d: T2) = println(a +": "+ c +", "+ b +", "+ d)
+
+  def test4(a: Int) = {
+    def inner(b: Int = a, c: String) = println(b +": "+ c)
+    inner(c = "/")
+  }
+  def test5(argName: Unit) = println("test5")
+  def test6(x: Int) = { () => x }
+  def test7(s: String) = List(1).foreach(_ => println(s))
+
+  def test8(x: Int = 1)(implicit y: Int, z: String = "kldfj") = z + x + y
+  def test9(implicit x: Int = 1, z: String = "klfj") = z + x
+}
+
+
+class Base {
+  def test1[T1, T2](a: Int = 100, b: T1)(c: T2, d: String = a +": "+ b)(e: T2 = c, f: Int) =
+    println(a +": "+ d +", "+ b +", "+ c +", "+ e +", "+ f)
+}
+
+class Sub1 extends Base {
+  override def test1[U1, U2](b: Int, a: U1)(m: U2, r: String = "overridden")(o: U2, f: Int = 555) =
+    println(b +": "+ r +", "+ a +", "+ m +", "+ o +", "+ f)
+}
+
+
+class A[T <: String, U](a: Int = 0, b: T)(c: String = b, d: Int) { def print = c + a + b + d }
+class B[T](a: T, b: Int = 1)(c: T = a, e: String = "dklsf") extends A(5, e)("dlkd", 10) { def printB = super.print + e + a + b + c }
+
+case class C[U](a: String, b: Int = 234, c: U)(d: U = c, e: String = "dlkfj") { def print = toString + d + e }
+
+
+class A1 {
+  def foo(a: Int = 10, b: String) = b + a
+}
+class B1 extends A1 {
+  def bar(a: String = "dflk") = super.foo(b = a)
+}
+
+trait N {
+  def foo[T >: String](x: Int = -1, y: T = "jupee")(z: String): Object
+}
+
+abstract class M extends N {
+  // also tests #2116, specialize return type when overriding.
+  def foo[T >: String](x: Int, y: T)(z: String = "1"): String
+  def bar(n: Int, m: Double = 1.239): Double
+}
+
+class MN extends M {
+  def foo[T >: String](x: Int, y: T)(z: String) = z + x + y
+  def bar(n: Int, m: Double) = n*m
+}
+
+case class Factory(x: Int = 1, y: String)(z: String = y)
+case class Fact2[T, +U](x: T = "ju", y: U = 1)(z: T = 2)
+
+
+// dependent types and copy method
+class A2 {
+  case class B2(x: C2)(y: Int) extends A2 {
+    override def toString = "slkdfj" + y
+  }
+  class C2
+}
+
+
+
+// using names / defaults in self constructor call.
+// overloading resolution: calling A3("string") picks the second, method with default is always less specific.
+class A3(x: String, y: Int = 10) {
+  def this(a: Object) {
+    this(y = 10, x = a.toString())
+    println(x)
+  }
+}
+class A4(x: String, y: Int = 11) {
+  def this(b: Double, sep: String) {
+    this(sep + b + sep)
+    println(y)
+  }
+}
+
+
+// using names / defaults in super constructor call
+class A5(x: Int, val y: Int = 2)(z: Int = x + y)
+class B4 extends A5(10)() {
+  println(y)
+}
+class B5 extends A5(y = 20, x = 2)() {
+  println(y)
+}
+
+// overriding default can be less specific (but has to conform to argument type!)
+class A6 { def foo(a: Object = "dlkf") = 0 }
+class B6 extends A6 { override def foo(a: Object = new Object) = 1 }
diff --git a/test/files/run/nodebuffer-array.check b/test/files/run/nodebuffer-array.check
new file mode 100644
index 0000000..49f8bfa
--- /dev/null
+++ b/test/files/run/nodebuffer-array.check
@@ -0,0 +1,3 @@
+<entry>
+    <elem>a</elem><elem>b</elem><elem>c</elem>
+    </entry>
diff --git a/test/files/run/nodebuffer-array.scala b/test/files/run/nodebuffer-array.scala
new file mode 100644
index 0000000..4e1ffe1
--- /dev/null
+++ b/test/files/run/nodebuffer-array.scala
@@ -0,0 +1,15 @@
+object Test {
+  
+  def f(s: String) = {
+    <entry>
+    {
+      for (item <- s split ',') yield
+        <elem>{ item }</elem>
+    }
+    </entry>
+  }
+  
+  def main(args: Array[String]): Unit = {
+    println(f("a,b,c"))
+  }
+}
diff --git a/test/files/run/numbereq.scala b/test/files/run/numbereq.scala
new file mode 100644
index 0000000..77a217d
--- /dev/null
+++ b/test/files/run/numbereq.scala
@@ -0,0 +1,41 @@
+object Test {
+  def mkNumbers(x: Int): List[AnyRef] = {
+    val base = List(
+      BigDecimal(x),
+      BigInt(x),
+      new java.lang.Double(x.toDouble),
+      new java.lang.Float(x.toFloat),
+      new java.lang.Long(x.toLong),
+      new java.lang.Integer(x)
+    )
+    val extras = List(
+      if (x >= Short.MinValue && x <= Short.MaxValue) List(new java.lang.Short(x.toShort)) else Nil,
+      if (x >= Byte.MinValue && x <= Byte.MaxValue) List(new java.lang.Byte(x.toByte)) else Nil,
+      if (x >= Char.MinValue && x <= Char.MaxValue) List(new java.lang.Character(x.toChar)) else Nil
+    ).flatten
+    
+    base ::: extras
+  }
+      
+  
+  def main(args: Array[String]): Unit = {
+    val ints    = (0 to 15).toList map (Short.MinValue >> _)
+    val ints2   = ints map (x => -x)
+    val ints3   = ints map (_ + 1)
+    val ints4   = ints2 map (_ - 1)
+    
+    val setneg1 = ints map mkNumbers
+    val setneg2 = ints3 map mkNumbers
+    val setpos1 = ints2 map mkNumbers
+    val setpos2 = ints4 map mkNumbers
+    val zero = mkNumbers(0)
+    
+    val sets = setneg1 ++ setneg2 ++ List(zero) ++ setpos1 ++ setpos2    
+    
+    for (set <- sets ; x <- set ; y <- set) {
+      // println("'%s' == '%s' (%s == %s) (%s == %s)".format(x, y, x.hashCode, y.hashCode, x.##, y.##))
+      assert(x == y, "%s/%s != %s/%s".format(x, x.getClass, y, y.getClass))
+      assert(x.## == y.##, "%s != %s".format(x.getClass, y.getClass))
+    }
+  }
+}
\ No newline at end of file
diff --git a/test/files/run/overloads.scala b/test/files/run/overloads.scala
index d0519ac..e84fef0 100644
--- a/test/files/run/overloads.scala
+++ b/test/files/run/overloads.scala
@@ -1,7 +1,6 @@
 //############################################################################
 // Overloads
 //############################################################################
-// $Id: overloads.scala 6644 2006-03-09 12:12:37Z odersky $
 
 //############################################################################
 
diff --git a/test/files/run/packrat1.check b/test/files/run/packrat1.check
new file mode 100644
index 0000000..e9f797e
--- /dev/null
+++ b/test/files/run/packrat1.check
@@ -0,0 +1,7 @@
+1
+3
+5
+81
+4
+37
+9
diff --git a/test/files/run/packrat1.scala b/test/files/run/packrat1.scala
new file mode 100644
index 0000000..71b593d
--- /dev/null
+++ b/test/files/run/packrat1.scala
@@ -0,0 +1,47 @@
+import scala.util.parsing.combinator._
+
+import scala.util.parsing.combinator.syntactical.StandardTokenParsers
+import scala.util.parsing.input._
+import scala.util.parsing.syntax._
+
+import scala.collection.mutable.HashMap
+
+object Test extends Application{
+  import grammars._
+
+  val head = phrase(term)
+
+  println(extractResult(head(new lexical.Scanner("1"))))
+  println(extractResult(head(new lexical.Scanner("1+2"))))
+  println(extractResult(head(new lexical.Scanner("9-4"))))
+  println(extractResult(head(new lexical.Scanner("9*9"))))
+  println(extractResult(head(new lexical.Scanner("8/2"))))
+  println(extractResult(head(new lexical.Scanner("4*9-0/7+9-8*1"))))
+  println(extractResult(head(new lexical.Scanner("(1+2)*3"))))
+}
+
+object grammars extends StandardTokenParsers with PackratParsers{
+  
+  def extractResult(r : ParseResult[_]) = r match {
+    case Success(a,_) => a
+    case NoSuccess(a,_) => a
+  }
+  
+  lexical.delimiters ++= List("+","-","*","/","(",")")
+  lexical.reserved ++= List("Hello","World")
+  
+  /****
+   * term = term + fact | term - fact | fact
+   * fact = fact * num  | fact / num  | num
+   */
+
+
+ val term: PackratParser[Int] = (term~("+"~>fact) ^^ {case x~y => x+y}
+           |term~("-"~>fact) ^^ {case x~y => x-y}
+           |fact)
+  
+ val fact: PackratParser[Int] = (fact~("*"~>numericLit) ^^ {case x~y => x*y.toInt}
+           |fact~("/"~>numericLit) ^^ {case x~y => x/y.toInt}
+           |"("~>term<~")"
+           |numericLit ^^ {_.toInt})
+ }
diff --git a/test/files/run/packrat2.check b/test/files/run/packrat2.check
new file mode 100644
index 0000000..55a32ac
--- /dev/null
+++ b/test/files/run/packrat2.check
@@ -0,0 +1,7 @@
+1
+3
+81
+43
+59
+188
+960
diff --git a/test/files/run/packrat2.scala b/test/files/run/packrat2.scala
new file mode 100644
index 0000000..45558e8
--- /dev/null
+++ b/test/files/run/packrat2.scala
@@ -0,0 +1,57 @@
+import scala.util.parsing.combinator._
+
+import scala.util.parsing.combinator.syntactical.StandardTokenParsers
+import scala.util.parsing.input._
+import scala.util.parsing.syntax._
+
+import scala.collection.mutable.HashMap
+
+object Test extends Application{
+  import grammars2._
+
+  val head = phrase(exp)
+
+  println(extractResult(head(new lexical.Scanner("1"))))
+  println(extractResult(head(new lexical.Scanner("1+2"))))
+  println(extractResult(head(new lexical.Scanner("9*9"))))
+  println(extractResult(head(new lexical.Scanner("4*9+7"))))
+  println(extractResult(head(new lexical.Scanner("4*9+7*2+3*3"))))
+  println(extractResult(head(new lexical.Scanner("4*9+7*2+3*3+9*5+7*6*2"))))
+  println(extractResult(head(new lexical.Scanner("4*(9+7)*(2+3)*3"))))
+
+}
+
+object grammars2 extends StandardTokenParsers with PackratParsers{
+  
+  def extractResult(r : ParseResult[_]) = r match{
+    case Success(a,_) => a
+    case NoSuccess(a,_) => a
+  }
+  
+  lexical.delimiters ++= List("+","-","*","/","(",")")
+  lexical.reserved ++= List("Hello","World")
+  
+  /*
+   * exp = sum | prod | num
+   * sum = exp ~ "+" ~ num
+   * prod = exp ~ "*" ~ num
+   */
+
+  val exp : PackratParser[Int] = sum | prod | numericLit ^^{_.toInt} | "("~>exp<~")"
+  val sum : PackratParser[Int] = exp~("+"~>exp) ^^ {case x~y => x+y}
+  val prod: PackratParser[Int] = exp~("*"~>(numericLit ^^{_.toInt} | exp)) ^^ {case x~y => x*y}
+  
+   
+ /* lexical.reserved ++= List("a","b", "c")
+  val a : PackratParser[Any] = numericLit^^{x => primeFactors(x.toInt)}
+  val b : PackratParser[Any] = memo("b")
+  val c : PackratParser[Any] = memo("c")
+  val AnBnCn : PackratParser[Any] = 
+    parseButDontEat(repMany1(a,b))~not(b)~>rep1(a)~repMany1(b,c)// ^^{case x~y => x:::y}
+  //val c : PackratParser[Any] = parseButDontEat(a)~a~a
+  //println(c((new PackratReader(new lexical.Scanner("45 24")))))
+  val r = new PackratReader(new lexical.Scanner("45 b c"))
+  println(AnBnCn(r))
+  println(r.getCache.size)
+*/ 
+}
diff --git a/test/files/run/packrat3.check b/test/files/run/packrat3.check
new file mode 100644
index 0000000..4d84623
--- /dev/null
+++ b/test/files/run/packrat3.check
@@ -0,0 +1,7 @@
+(((List(a, b)~())~List(a))~List(b, c))
+(((List(a, a, b, b)~())~List(a, a))~List(b, b, c, c))
+(((List(a, a, a, b, b, b)~())~List(a, a, a))~List(b, b, b, c, c, c))
+(((List(a, a, a, a, b, b, b, b)~())~List(a, a, a, a))~List(b, b, b, b, c, c, c, c))
+Expected failure
+``b'' expected but `c' found
+``c'' expected but EOF found
diff --git a/test/files/run/packrat3.scala b/test/files/run/packrat3.scala
new file mode 100644
index 0000000..e58d16a
--- /dev/null
+++ b/test/files/run/packrat3.scala
@@ -0,0 +1,51 @@
+import scala.util.parsing.combinator._
+
+import scala.util.parsing.combinator.syntactical.StandardTokenParsers
+import scala.util.parsing.input._
+import scala.util.parsing.syntax._
+
+import scala.collection.mutable.HashMap
+
+object Test {
+  def main(args: Array[String]): Unit = {
+    import grammars3._
+
+    val head = phrase(AnBnCn)
+
+    println(extractResult(head(new lexical.Scanner("a b c"))))
+    println(extractResult(head(new lexical.Scanner("a a b b c c"))))
+    println(extractResult(head(new lexical.Scanner("a a a b b b c c c"))))
+    println(extractResult(head(new lexical.Scanner("a a a a b b b b c c c c"))))
+
+    println(extractResult(AnBnCn(new PackratReader(new lexical.Scanner("a a a b b b b c c c c")))))
+    println(extractResult(AnBnCn(new PackratReader(new lexical.Scanner("a a a a b b b c c c c")))))
+    println(extractResult(AnBnCn(new PackratReader(new lexical.Scanner("a a a a b b b b c c c")))))
+  }
+}
+
+object grammars3 extends StandardTokenParsers with PackratParsers {
+  
+  def extractResult(r: ParseResult[_]) = r match {
+    case Success(a,_) => a
+    case NoSuccess(a,_) => a
+  }
+  
+
+  lexical.reserved ++= List("a","b", "c")
+  val a: PackratParser[Any] = memo("a")
+  val b: PackratParser[Any] = memo("b")
+  val c: PackratParser[Any] = memo("c")
+
+  val AnBnCn: PackratParser[Any] = 
+    guard(repMany1(a,b) ~ not(b)) ~ rep1(a) ~ repMany1(b,c)// ^^{case x~y => x:::y}
+
+
+  private def repMany[T](p: => Parser[T], q: => Parser[T]): Parser[List[T]] = 
+  ( p~repMany(p,q)~q ^^ {case x~xs~y => x::xs:::(y::Nil)}
+   | success(Nil)
+  )
+
+  def repMany1[T](p: => Parser[T], q: => Parser[T]): Parser[List[T]] = 
+   p~opt(repMany(p,q))~q ^^ {case x~Some(xs)~y => x::xs:::(y::Nil)}
+
+} 
diff --git a/test/files/run/patmat-seqs.check b/test/files/run/patmat-seqs.check
new file mode 100644
index 0000000..bb2a5ee
--- /dev/null
+++ b/test/files/run/patmat-seqs.check
@@ -0,0 +1,13 @@
+s3
+s2
+s1
+s0
+ss6
+d
+s3
+s3
+d
+s1
+s3
+d
+d
diff --git a/test/files/run/patmat-seqs.scala b/test/files/run/patmat-seqs.scala
new file mode 100644
index 0000000..e237116
--- /dev/null
+++ b/test/files/run/patmat-seqs.scala
@@ -0,0 +1,42 @@
+object Test {
+  def f1(x: Any) = x match {
+    case Seq(1, 2, 3) => "s3"
+    case Seq(4, 5) => "s2"
+    case Seq(7) => "s1"
+    case Nil => "s0"
+    case Seq(_, _, _, _, _, x: String) => "ss6"
+    case _ => "d"
+  }
+  
+  def f2(x: Any) = x match {
+    case Seq("a", "b", _*)  => "s2"
+    case Seq(1, _*)         => "s1"
+    case Seq(5, 6, 7, _*)   => "s3"
+    case _                  => "d"
+  }
+  
+  def main(args: Array[String]): Unit = {
+    val xs1 = List(
+      List(1,2,3),
+      List(4,5),
+      Vector(7),
+      Seq(),
+      Seq(1, 2, 3, 4, 5, "abcd"),
+      "abc"
+    ) map f1
+    
+    xs1 foreach println
+    
+    val xs2 = List(
+      Seq(5, 6, 7),
+      Seq(5, 6, 7, 8, 9),
+      Seq("a"),
+      Seq(1, 6, 7),
+      List(5, 6, 7),
+      Nil,
+      5
+    ) map f2
+    
+    xs2 foreach println
+  }
+}
diff --git a/test/files/run/patmatnew.scala b/test/files/run/patmatnew.scala
index d57310a..e2c95e3 100644
--- a/test/files/run/patmatnew.scala
+++ b/test/files/run/patmatnew.scala
@@ -273,10 +273,14 @@ object Test extends TestConsoleMain {
     //def doMatch3(xs:List[char]) = xs match {
     //  case List(_*, z, w) => w::Nil
     //}
-    def doMatch4(xs:Seq[Char]) = xs match {
-      case Seq(x, y, _*) => x::y::Nil
-      case Seq(x, y, z, w) => List(z,w) // redundant!
-    }
+    // 
+    // Since the second case should have been unreachable all along,
+    // let's just comment this one out.
+    //
+    // def doMatch4(xs:Seq[Char]) = xs match {
+    //   case Seq(x, y, _*) => x::y::Nil
+    //   case Seq(x, y, z, w) => List(z,w) // redundant!
+    // }
     def doMatch5(xs:Seq[Char]) = xs match {
       case Seq(x, y, 'c', w @ _*) => x::y::Nil
       case Seq(x, y, z @ _*)    => z
@@ -289,8 +293,8 @@ object Test extends TestConsoleMain {
     override def runTest() {
       assertEquals(List('a','b'), doMatch1(List('a','b','c','d')))
       assertEquals(List('c','d'), doMatch2(List('a','b','c','d')))
-      //assertEquals(doMatch3(List('a','b','c','d')), List('d'))
-      assertEquals(List('a','b'), doMatch4(List('a','b','c','d')))
+      // assertEquals(doMatch3(List('a','b','c','d')), List('d'))
+      // assertEquals(List('a','b'), doMatch4(List('a','b','c','d')))
       assertEquals(List('a','b'), doMatch5(List('a','b','c','d')))
       assertEquals(List('c','d'), doMatch6(List('a','b','c','d')))
     }
@@ -311,11 +315,11 @@ object Test extends TestConsoleMain {
   object TestStream extends TestCase("unapply for Streams") {
     def sum(stream: Stream[Int]): Int =
       stream match {
-        case Stream.empty => 0
+        case Stream.Empty => 0
         case Stream.cons(hd, tl) => hd + sum(tl)
       }
     
-    val str: Stream[int] = Stream.fromIterator(List(1,2,3).elements)
+    val str: Stream[Int] = List(1,2,3).iterator.toStream
 
     def runTest() = assertEquals(sum(str), 6)
   }
@@ -500,8 +504,8 @@ object Test extends TestConsoleMain {
 
   object Bug1261 {
     sealed trait Elem
-    case class Foo extends Elem
-    case class Bar extends Elem
+    case class Foo() extends Elem
+    case class Bar() extends Elem
     trait Row extends Elem
     object Row {
       def unapply(r: Row) = true
@@ -698,10 +702,10 @@ object Test extends TestConsoleMain {
   object Bug995 extends TestCase("aladdin #995") {
     def foo(v: Any): String = v match {
       case s: Seq[_] => "Seq" // see hack in object Seq.unapplySeq
-      //case a: AnyRef if runtime.ScalaRunTime.isArray(a) => "Array"
+      case a: AnyRef if runtime.ScalaRunTime.isArray(a) => "Array"
       case _ => v.toString
     }
-    override def runTest { assertEquals("Seq", foo(Array(0))) } 
+    override def runTest { assertEquals("Array", foo(Array(0))) } 
   }
 
   // bug#1093 (contribution #460)
@@ -921,8 +925,8 @@ override def runTest() {
 
   object Ticket710 {  // compile-only
     def method {
-      sealed case class Parent
-      case object Child extends Parent
+      sealed class Parent()
+      case object Child extends Parent()
       val x: Parent = Child
       x match {
         case Child => ()
diff --git a/test/files/run/priorityQueue.scala b/test/files/run/priorityQueue.scala
new file mode 100644
index 0000000..a3460cd
--- /dev/null
+++ b/test/files/run/priorityQueue.scala
@@ -0,0 +1,346 @@
+
+
+
+import scala.collection.mutable.PriorityQueue
+
+
+
+
+
+
+// populate a priority queue a few different ways and make sure they all seem equal
+object Test {
+
+  def main(args: Array[String]) {
+    testInsertionsAndEqualities
+    testIntensiveEnqueueDequeue
+    testIndexing
+    testTails
+    testInits
+    testFilters
+    testDrops
+    testUpdates
+    testEquality
+    testMisc
+    testReverse
+  }
+
+  def testInsertionsAndEqualities {
+    import scala.util.Random.nextInt
+    val pq1 = new PriorityQueue[String]
+    val pq2 = new PriorityQueue[String]
+    val pq3 = new PriorityQueue[String]
+    val pq4 = new PriorityQueue[String]
+    
+    val strings = (1 to 20).toList map (i => List.fill((Math.abs(nextInt % 20)) + 1)("x").mkString)
+    
+    pq1 ++= strings
+    pq2 ++= strings.reverse
+    for (s <- strings) pq3 += s
+    for (s <- strings.reverse) pq4 += s
+    
+    val pqs = List(pq1, pq2, pq3, pq4, pq1.clone, pq2.clone)
+  
+    for (queue1 <- pqs ; queue2 <- pqs) {
+      assert(queue1 == queue2)
+      assert(queue1.max == queue2.max)
+    }
+    
+    assertPriority(pq1)
+  }
+
+  def testIndexing {
+    val pq = new PriorityQueue[Char]
+    "The quick brown fox jumps over the lazy dog".foreach(pq += _)
+
+    // val iter = pq.iterator
+    // while (iter.hasNext) println("`" + iter.next + "`")
+    assert(pq(0) == 'z')
+    assert(pq(1) == 'y')
+    assert(pq(2) == 'x')
+    assert(pq(3) == 'w')
+    assert(pq(4) == 'v')
+    assert(pq(5) == 'u')
+    assert(pq(7) == 't')
+    assert(pq(8) == 's')
+    assert(pq(9) == 'r')
+    assert(pq(10) == 'r')
+
+    pq.clear
+    "abcdefghijklmnopqrstuvwxyz".foreach(pq += _)
+    for (i <- 0 until 26) assert(pq(i) == ('z' - i))
+
+    val intpq = new PriorityQueue[Int]
+    val intlst = new collection.mutable.ArrayBuffer ++ (0 until 100)
+    val random = new util.Random(101)
+    while (intlst.nonEmpty) {
+      val idx = random.nextInt(intlst.size)
+      intpq += intlst(idx)
+      intlst.remove(idx)
+    }
+    for (i <- 0 until 100) assert(intpq(i) == (99 - i))
+  }
+  
+  def testTails {
+    val pq = new PriorityQueue[Int]
+    for (i <- 0 until 10) pq += i * 4321 % 200
+
+    assert(pq.size == 10)
+    assert(pq.nonEmpty)
+
+    val tailpq = pq.tail
+    // pq.printstate
+    // tailpq.printstate
+    assert(tailpq.size == 9)
+    assert(tailpq.nonEmpty)
+    assertPriorityDestructive(tailpq)
+  }
+
+  def assertPriorityDestructive[A](pq: PriorityQueue[A])(implicit ord: Ordering[A]) {
+    import ord._
+    var prev: A = null.asInstanceOf[A]
+    while (pq.nonEmpty) {
+      val curr = pq.dequeue
+      if (prev != null) assert(curr <= prev)
+      prev = curr
+    }
+  }
+
+  def assertPriority[A](pq: PriorityQueue[A])(implicit ord: Ordering[A]) {
+    import ord._
+    var prev: A = null.asInstanceOf[A]
+    val iter = pq.iterator
+    while (iter.hasNext) {
+      val curr = iter.next
+      if (prev != null) assert(curr <= prev)
+      prev = curr
+    }
+  }
+
+  def testInits {
+    val pq = new PriorityQueue[Long]
+    for (i <- 0 until 20) pq += (i + 313) * 111 % 300
+    
+    assert(pq.size == 20)
+    
+    val initpq = pq.init
+    assert(initpq.size == 19)
+    assertPriorityDestructive(initpq)
+  }
+
+  def testFilters {
+    val pq = new PriorityQueue[String]
+    for (i <- 0 until 100) pq += "Some " + (i * 312 % 200)
+    
+    val filpq = pq.filter(_.indexOf('0') != -1)
+    assertPriorityDestructive(filpq)
+  }
+
+  def testIntensiveEnqueueDequeue {
+    val pq = new PriorityQueue[Int]
+    
+    testIntensive(1000, pq)
+    pq.clear
+    testIntensive(200, pq)
+  }
+  
+  def testIntensive(sz: Int, pq: PriorityQueue[Int]) {
+    val lst = new collection.mutable.ArrayBuffer[Int] ++ (0 until sz)
+    val rand = new util.Random(7)
+    while (lst.nonEmpty) {
+      val idx = rand.nextInt(lst.size)
+      pq.enqueue(lst(idx))
+      lst.remove(idx)
+      if (rand.nextDouble < 0.25 && pq.nonEmpty) pq.dequeue
+      assertPriority(pq)
+    }
+  }
+
+  def testDrops {
+    val pq = new PriorityQueue[Int]
+    pq ++= (0 until 100)
+    val droppq = pq.drop(50)
+    assertPriority(droppq)
+    
+    pq.clear
+    pq ++= droppq
+    assertPriorityDestructive(droppq)
+    assertPriority(pq)
+    assertPriorityDestructive(pq)
+  }
+
+  def testUpdates {
+    val pq = new PriorityQueue[Int]
+    pq ++= (0 until 36)
+    assertPriority(pq)
+
+    pq(0) = 100
+    assert(pq(0) == 100)
+    assert(pq.dequeue == 100)
+    assertPriority(pq)
+
+    pq.clear
+    
+    pq ++= (1 to 100)
+    pq(5) = 200
+    assert(pq(0) == 200)
+    assert(pq(1) == 100)
+    assert(pq(2) == 99)
+    assert(pq(3) == 98)
+    assert(pq(4) == 97)
+    assert(pq(5) == 96)
+    assert(pq(6) == 94)
+    assert(pq(7) == 93)
+    assert(pq(98) == 2)
+    assert(pq(99) == 1)
+    assertPriority(pq)
+
+    pq(99) = 450
+    assert(pq(0) == 450)
+    assert(pq(1) == 200)
+    assert(pq(99) == 2)
+    assertPriority(pq)
+
+    pq(1) = 0
+    assert(pq(1) == 100)
+    assert(pq(99) == 0)
+    assertPriority(pq)
+    assertPriorityDestructive(pq)
+  }
+
+  def testEquality {
+    val pq1 = new PriorityQueue[Int]
+    val pq2 = new PriorityQueue[Int]
+    
+    pq1 ++= (0 until 50)
+    var i = 49
+    while (i >= 0) {
+      pq2 += i
+      i -= 1
+    }
+    assert(pq1 == pq2)
+    assertPriority(pq2)
+    
+    pq1 += 100
+    assert(pq1 != pq2)
+    pq2 += 100
+    assert(pq1 == pq2)
+    pq2 += 200
+    assert(pq1 != pq2)
+    pq1 += 200
+    assert(pq1 == pq2)
+    assertPriorityDestructive(pq1)
+    assertPriorityDestructive(pq2)
+  }
+
+  def testMisc {
+    val pq = new PriorityQueue[Int]
+    pq ++= (0 until 100)
+    assert(pq.size == 100)
+    
+    val (p1, p2) = pq.partition(_ < 50)
+    assertPriorityDestructive(p1)
+    assertPriorityDestructive(p2)
+
+    val spq = pq.slice(25, 75)
+    assertPriorityDestructive(spq)
+
+    pq.clear
+    pq ++= (0 until 10)
+    pq += 5
+    assert(pq.size == 11)
+
+    val ind = pq.lastIndexWhere(_ == 5)
+    assert(ind == 5)
+    assertPriorityDestructive(pq)
+
+    pq.clear
+    pq ++= (0 until 10)
+    assert(pq.lastIndexWhere(_ == 9) == 0)
+    assert(pq.lastIndexOf(8) == 1)
+    assert(pq.lastIndexOf(7) == 2)
+    
+    pq += 5
+    pq += 9
+    assert(pq.lastIndexOf(9) == 1)
+    assert(pq.lastIndexWhere(_ % 2 == 1) == 10)
+    assert(pq.lastIndexOf(5) == 6)
+    
+    val lst = pq.reverseIterator.toList
+    for (i <- 0 until 5) assert(lst(i) == i)
+    assert(lst(5) == 5)
+    assert(lst(6) == 5)
+    assert(lst(7) == 6)
+    assert(lst(8) == 7)
+    assert(lst(9) == 8)
+    assert(lst(10) == 9)
+    assert(lst(11) == 9)
+    
+    pq.clear
+    assert(pq.reverseIterator.toList.isEmpty)
+    
+    pq ++= (50 to 75)
+    assert(pq.lastIndexOf(70) == 5)
+    
+    pq += 55
+    pq += 70
+    assert(pq.lastIndexOf(70) == 6)
+    assert(pq.lastIndexOf(55) == 22)
+    assert(pq.lastIndexOf(55, 21) == 21)
+    assert(pq.lastIndexWhere(_ > 54) == 22)
+    assert(pq.lastIndexWhere(_ > 54, 21) == 21)
+    assert(pq.lastIndexWhere(_ > 69, 5) == 5)
+  }
+  
+  def testReverse {
+    val pq = new PriorityQueue[(Int, Int)]
+    pq ++= (for (i <- 0 until 10) yield (i, i * i % 10))
+    
+    assert(pq.reverse.size == pq.reverseIterator.toList.size)
+    assert((pq.reverse zip pq.reverseIterator.toList).forall(p => p._1 == p._2))
+    assert(pq.reverse.sameElements(pq.reverseIterator.toSeq))
+    assert(pq.reverse(0)._1 == pq(9)._1)
+    assert(pq.reverse(1)._1 == pq(8)._1)
+    assert(pq.reverse(4)._1 == pq(5)._1)
+    assert(pq.reverse(9)._1 == pq(0)._1)
+    
+    pq += ((7, 7))
+    pq += ((7, 9))
+    pq += ((7, 8))
+    assert(pq.reverse.reverse == pq)
+    assert(pq.reverse.lastIndexWhere(_._2 == 6) == 6)
+    assertPriorityDestructive(pq.reverse.reverse)
+    
+    val iq = new PriorityQueue[Int]
+    iq ++= (0 until 50)
+    assert(iq.reverse == iq.reverseIterator.toSeq)
+    assert(iq.reverse.reverse == iq)
+    
+    iq += 25
+    iq += 40
+    iq += 10
+    assert(iq.reverse == iq.reverseIterator.toList)
+    assert(iq.reverse.reverse == iq)
+    assert(iq.reverse.lastIndexWhere(_ == 10) == 11)
+    assertPriorityDestructive(iq.reverse.reverse)
+  }
+  
+}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/test/files/run/programmatic-main.check b/test/files/run/programmatic-main.check
new file mode 100644
index 0000000..e6c83a6
--- /dev/null
+++ b/test/files/run/programmatic-main.check
@@ -0,0 +1,25 @@
+parser
+namer
+packageobjects
+typer
+superaccessors
+pickler
+refchecks
+liftcode
+uncurry
+tailcalls
+specialize
+explicitouter
+erasure
+lazyvals
+lambdalift
+constructors
+flatten
+mixin
+cleanup
+icode
+inliner
+closelim
+dce
+jvm
+terminal
diff --git a/test/files/run/programmatic-main.scala b/test/files/run/programmatic-main.scala
new file mode 100644
index 0000000..b44b1a9
--- /dev/null
+++ b/test/files/run/programmatic-main.scala
@@ -0,0 +1,12 @@
+import scala.tools.nsc._
+import io.Path
+
+object Test {
+  val cwd = Option(System.getProperty("partest.cwd")) getOrElse "."
+  val basedir = Path(cwd).parent / "lib" path
+  val baseargs = Array("-usejavacp", "-bootclasspath", basedir + "/scala-library.jar", "-cp", basedir + "/scala-compiler.jar")
+    
+  def main(args: Array[String]): Unit = {
+    Main process (baseargs ++ Array("-Xshow-phases"))
+  }
+}
diff --git a/test/files/run/proxy.check b/test/files/run/proxy.check
new file mode 100644
index 0000000..9eb68b1
--- /dev/null
+++ b/test/files/run/proxy.check
@@ -0,0 +1,4 @@
+false
+true
+false
+false
diff --git a/test/files/run/proxy.scala b/test/files/run/proxy.scala
new file mode 100644
index 0000000..869cbf8
--- /dev/null
+++ b/test/files/run/proxy.scala
@@ -0,0 +1,9 @@
+object Test extends Application {
+  val p = new Proxy {
+    def self = 2 
+  }
+  println(p equals 1)
+  println(p equals 2)
+  println(p equals 3)
+  println(p equals null)
+}
diff --git a/test/files/run/randomAccessSeq-apply.scala b/test/files/run/randomAccessSeq-apply.scala
index 416416e..f398ea1 100644
--- a/test/files/run/randomAccessSeq-apply.scala
+++ b/test/files/run/randomAccessSeq-apply.scala
@@ -6,7 +6,7 @@ object Test extends Application {
   assert(List(1) == single.toList)
   
   val two = RandomAccessSeq("a", "b")
-  assert("a" == two.first)
+  assert("a" == two.head)
   assert("b" == two.apply(1))
   
   println("OK")
diff --git a/test/files/run/range.scala b/test/files/run/range.scala
index 5d0ca84..387b2d0 100644
--- a/test/files/run/range.scala
+++ b/test/files/run/range.scala
@@ -1,14 +1,57 @@
-object Test extends Application{
+import scala.collection.immutable.{ Range, NumericRange }
+
+object Test {
   def rangeForeach(range : Range) = {
     val buffer = new scala.collection.mutable.ListBuffer[Int];
     range.foreach(buffer += _);
-    assert(buffer.toList == range.elements.toList);
+    assert(buffer.toList == range.iterator.toList, buffer.toList+"/"+range.iterator.toList)
+  }
+  
+  case class GR[T](val x: T)(implicit val num: Integral[T]) {
+    import num._
+    
+    def negated = GR[T](-x)
+    
+    def gr1 = NumericRange(x, x, x)
+    def gr2 = NumericRange.inclusive(x, x, x)
+    def gr3 = NumericRange(x, x * fromInt(10), x)
+    def gr4 = NumericRange.inclusive(x, x * fromInt(10), x)
+    
+    def check = assert(
+      gr1.isEmpty && !gr2.isEmpty &&
+      gr3.size == 9 && gr4.size == 10 && 
+      (gr3.toList ::: negated.gr3.toList).sum == num.zero && 
+      !(gr3 contains (x * fromInt(10))) &&
+      (gr4 contains (x * fromInt(10)))
+    )
+  }  
+  
+  def main(args: Array[String]): Unit = {
+    implicit val imp1 = Numeric.BigDecimalAsIfIntegral
+    implicit val imp2 = Numeric.DoubleAsIfIntegral
+    
+    val _grs = List[GR[_]](
+      GR(BigDecimal(5.0)),
+      GR(BigInt(5)),
+      GR(5L),
+      GR(5.0d),
+      GR(2.toByte)
+    )
+    val grs = _grs ::: (_grs map (_.negated))
+    grs foreach (_.check)
+    
+    assert(NumericRange(1, 10, 1) sameElements (1 until 10))
+    assert(NumericRange.inclusive(1, 10, 1) sameElements (1 to 10))
+    assert(NumericRange.inclusive(1, 100, 3) sameElements (1 to 100 by 3))
+    
+    // #2518
+    assert((3L to 7 by 2) sameElements List(3L, 5L, 7L))
+    
+    rangeForeach(1 to 10);
+    rangeForeach(1 until 10);
+    rangeForeach(10 to 1 by -1);
+    rangeForeach(10 until 1 by -1);
+    rangeForeach(10 to 1 by -3);
+    rangeForeach(10 until 1 by -3);    
   }
-
-  rangeForeach(1 to 10);
-  rangeForeach(1 until 10);
-  rangeForeach(10 to 1 by -1);
-  rangeForeach(10 until 1 by -1);
-  rangeForeach(10 to 1 by -3);
-  rangeForeach(10 until 1 by -3);
 }
diff --git a/test/files/run/regularpatmat.check b/test/files/run/regularpatmat.check
deleted file mode 100644
index 3417d9a..0000000
--- a/test/files/run/regularpatmat.check
+++ /dev/null
@@ -1,126 +0,0 @@
-pretest
-passed ok
-testWR_1
-passed ok
-passed ok
-passed ok
-passed ok
-passed ok
-passed ok
-passed ok
-testWR_2
-passed ok
-passed ok
-passed ok
-passed ok
-passed ok
-passed ok
-passed ok
-testWR_3
-passed ok
-passed ok
-passed ok
-passed ok
-passed ok
-passed ok
-passed ok
-testWR_4
-passed ok
-passed ok
-passed ok
-passed ok
-passed ok
-passed ok
-passed ok
-testWR_5
-passed ok
-passed ok
-passed ok
-testWR_6
-passed ok
-passed ok
-testWR_7
-passed ok
-testWR_8
-passed ok
-testWS
-passed ok
-passed ok
-passed ok
-passed ok
-passed ok
-passed ok
-passed ok
-testWT
-passed ok
-passed ok
-passed ok
-passed ok
-passed ok
-passed ok
-passed ok
-testWV
-passed ok
-passed ok
-passed ok
-passed ok
-passed ok
-passed ok
-passed ok
-testBK
-passed ok
-passed ok
-passed ok
-passed ok
-passed ok
-passed ok
-passed ok
-passed ok
-passed ok
-testBM
-passed ok
-passed ok
-passed ok
-passed ok
-passed ok
-passed ok
-passed ok
-passed ok
-BN preTest: true
-testBN
-passed ok
-passed ok
-passed ok
-passed ok
-passed ok
-passed ok
-passed ok
-testBO
-passed ok
-passed ok
-passed ok
-passed ok
-passed ok
-passed ok
-testMZ - bugs #132 #133b #180 #195 #196 #398 #406 #441
-passed ok
-passed ok
-passed ok
-passed ok
-passed ok
-passed ok
-passed ok
-passed ok
-passed ok
-passed ok
-passed ok
-passed ok
-passed ok
-passed ok
-passed ok
-passed ok
-passed ok
-passed ok
-passed ok
-passed ok
-passed ok
diff --git a/test/files/run/regularpatmat.scala.disabled b/test/files/run/regularpatmat.scala.disabled
deleted file mode 100644
index d8e244d..0000000
--- a/test/files/run/regularpatmat.scala.disabled
+++ /dev/null
@@ -1,729 +0,0 @@
-// Burak's test suite for regular pattern matching
-
-//import java.lang.System; // to avoid name clash with .NET's library
-
-object Test {
-  def main(args: Array[String]): Unit = {
-    Console.println("pretest");
-    val L = List(1,2,3);
-    scala.testing.UnitTest.assertEquals( L, L match { case List(xs at _*) => xs; } ) ;
-
-    testWR.main(args);
-    testWS.main(args);
-    testWT.main(args);
-    testWV.main(args);
-    //testWW.main(args);
-    testBK.main(args);
-    testBL.main(args);
-    testBM.main(args);
-    testBN.main(args);
-    testBO.main(args);
-    testMZ.main;
-    //testNN.main;
-    //testBugSequenceApply.main;
-  }
-}
-
-// contains 17 visitors plus X
-
-// analyzer related (no execution)
-object bug179 {
-  case class One();
-  object Foo {
-    def test(xs: List[Any]) = xs match {
-      case List(((((One(), One())*) | (One(), One())), One())) =>
-	Console.println("case")
-      case _ =>
-	Console.println("default");
-    }
-  }
-}
-// testW? are for recognition only ( no variables )
-// testB? are for variables binding
-
-object values { // test values reused in nearly all test cases
-
-    val s0: List[Char] = Nil ;
-    val s1: List[Char] = 'a'::'b'::'c'::Nil ;
-    val s2: List[Char] = 'a'::'b'::'c'::s1 ;
-    val s3: List[Char] = 'a'::'a'::'a'::Nil ;
-    val s4: List[Char] = 'b'::'c'::Nil ;
-    val s5: List[Char] = 'b'::Nil ;
-    val s6: List[Char] = 'b'::'a'::'a'::'a'::Nil ;
-
-    val s7: List[Int]  = 1::2::7::Nil ;
-    val s8: List[Int]  = 1::0::1::0::Nil;
-    val s9: List[Int]  = Nil ;
-
-    val s10: List[Char] = '7'::'0'::'1'::'.'::'2'::'4'::Nil ;
-
-}
-
-// matching without binding
-
-// 2do            case [ 'a'; x; y ]   => 100
-//                case [ z @ ('a'; x; y) ]   => 100
-// 2do             case [ 'a'*; x @ ( _;('a'; 'b')* ); y @ 'b'* ]   => 100
-//                case _               => 321 // 20022 // this never happens
-
-object testBK {
-
-  import values._ ;
-  import scala.testing.UnitTest._ ;
-
-  def doit1(e: List[Char]): Int = e match {
-    case List( 'a'*, x @ ( 'a',('a', 'b')* ), y @ ('b'*) ) => 100
-    case List( _ * )         => 321
-  }
-
-  def test1: Unit = {
-    Console.println("testBK");
-    //test[List[Char],Int]( doit1, s0, 321);
-    assertEquals( doit1( s0 ), 321);
-    assertEquals( doit1( s1 ),321);
-    assertEquals( doit1( s2 ),321);
-    assertEquals( doit1( s3 ),100);
-    assertEquals( doit1( s4 ),321);
-    assertEquals( doit1( s5 ),321);
-    assertEquals( doit1( s6 ),321)
-  }
-
-  def main(args: Array[String]): Unit = {
-    test1;
-  }
-
-}
-
-// tests with binding
-
-object testBL {
-
-  import scala.testing.UnitTest._ ;
-
-  def preTest(a:String,b:String):boolean = (a==b);
-  
-  def doit(x: List[String]): String = x match {
-    case List( z @ "John" ) => z
-  }
-  
-  // BEWARE: main type should be specified... 
-  // often, last thing is not () then you have a problem
-
-  def main(args: Array[String]): Unit = {
-    val a = "John"; 
-    val b = "John";
-    
-    assertEquals(a == b, true);
-    assertEquals(doit(List(b)), "John")
-  }
-}
-
-object testBM {
-
-  import scala.testing.UnitTest._ ;
-  import values._ ;
-
-  def doit1(e: List[Char]): List[Char] = e match {
-    case List( 'a'*, x @ ( 'a',('a', 'b')* ), y @ ('b'*) )
-      => { x.toList }
-
-    case List( 'a'*, x @ (('a', 'b')*) , y @ (('a','b','c') *) )
-      => { y.toList }
-
-    case List( _ * )
-      => Nil
-  }
-
-  def test1: Unit = {
-    Console.println("testBM");
-    assertEquals( doit1( s0 ), Nil);
-    assertEquals( doit1( s1 ), s1);
-    assertEquals( doit1( s2 ), s2); 
-
-    assertEquals( doit1( s3 ), List('a'));
-    assertEquals( doit1( s4 ), Nil);
-    assertEquals( doit1( s5 ), Nil);
-    assertEquals( doit1( s6 ), Nil);
-
-    val t7:List[Char] = 'a'::'a'::'a'::'b'::'b'::'b'::Nil;
-    //val t7ex:List[Char] = 'a'::'a'::'b'::Nil; // with longest match policy
-
-    assertEquals( doit1( t7 ), List('a') );
-  }
-
-  def main(args: Array[String]) = {
-    test1
-  }
-
-}
-
-object testBN {
-
-  import scala.testing.UnitTest._ ;
-  import values._ ;
-        
-  class testClass;
-
-  case class testA(arg: List[Char]) extends testClass;
-
-  def doit1(e: testClass): List[Char] = e match {
-    case testA(List( 'a', x, y )) => x::y::Nil
-    case _                        => Nil
-  }
-
-  def test1:Unit = {
-    Console.print("BN preTest: ");
-    Console.println(Nil == Nil);
-    Console.println("testBN");
-
-    assertEquals(doit1(testA(s0)), Nil);
-    assertEquals(doit1(testA(s1)), 'b'::'c'::Nil);
-    assertEquals(doit1(testA(s2)), Nil);
-    assertEquals(doit1(testA(s3)), 'a'::'a'::Nil);
-    assertEquals(doit1(testA(s4)), Nil);
-    assertEquals(doit1(testA(s5)), Nil);
-    assertEquals(doit1(testA(s6)), Nil);
-  }
-
-  def main(args: Array[String]) = {
-    test1
-  }
-
-}
-
-object testBO  {
-
-  // example suggested by Matthias
-  import scala.testing.UnitTest._ ;
-
-  case class Person(firstname: String, lastname: String);
-
-  def onlyJohn(db: List[Person]): List[String] = db match {  
-    case List(Person("John", lastname)) => lastname::Nil
-    case _ => Nil
-  }
-
-  /** first longest match policy -> the star is greedy/hungry/...
-   */
-  def searchFirstJohn(db: List[Person]): String = db match {
-    case List( _ *, Person("John", lastname), _ * ) => lastname
-    case _ => "<not found>"
-  }
-
-  /** first longest match policy -> star is a greedy/hungry
-   */
-  def searchJohns(db: List[Person]): List[String] = db match {
-    case List( _ *, Person("John", lastname), rest@(_ *)) => {
-      //Console.print("before is : " + before);
-      lastname::searchJohns(rest.toList)
-    }
-    case _ => Nil
-  }
-
-  def main(args: Array[String]): Unit = {
-    val p1 = Person("Albert",  "Camus");
-    val p2 = Person("Henry",   "Miller");
-    val p3 = Person("John",    "Le Carre");
-    val p4 = Person("Herbert", "Franke");
-    val p5 = Person("John",    "Smith");
-    val p6 = Person("William", "Gibson");
-
-    val db: List[Person] = p1::p2::p3::p4::p5::p6::Nil;
-
-    val db2: List[Person] = p3::Nil;
-
-    Console.println("testBO");
-
-    assertEquals(onlyJohn(db),         Nil);
-    assertEquals(onlyJohn(db2),        "Le Carre"::Nil);
-    assertEquals(searchFirstJohn(db),  "Le Carre");
-    assertEquals(searchFirstJohn(db2), "Le Carre");
-    assertEquals(searchJohns(db),      "Le Carre"::"Smith"::Nil);
-    assertEquals(searchJohns(db2),     "Le Carre"::Nil);
-  }
-
-}
-
-object testWR  {
-
-  import values._ ;
-  import scala.testing.UnitTest._ ;
-
-  def doit1(e: List[Char]): Int = e match {
-    case List( 'a', 'b', 'c' ) => 100
-    case _                     => 321
-  }
-
-  def test1: Unit = {
-    Console.println("testWR_1");
-    assertEquals( doit1( s0 ), 321);
-    assertEquals( doit1( s1 ), 100);
-    assertEquals( doit1( s2 ), 321);
-    assertEquals( doit1( s3 ), 321);
-    assertEquals( doit1( s4 ), 321);
-    assertEquals( doit1( s5 ), 321);
-    assertEquals( doit1( s6 ), 321)
-  }
-
-  def doit2(e: List[Char]):Int = e match {
-    case List( ('a', 'b','c')? ) => 1000
-    case _                       => 321
-  }
-
-  def test2: Unit = {
-    Console.println("testWR_2");
-    assertEquals( doit2( s0 ), 1000);
-    assertEquals( doit2( s1 ), 1000);
-    assertEquals( doit2( s2 ),  321);
-    assertEquals( doit2( s3 ),  321);
-    assertEquals( doit2( s4 ),  321);
-    assertEquals( doit2( s5 ),  321);
-    assertEquals( doit2( s6 ),  321);
-  }
-
-  def doit3(e: List[Char]): String = e match {
-    case List( ('a', 'a','a')? ) => "ok"
-    case _                   => "fail"
-  }
-
-  def test3: Unit = {
-    Console.println("testWR_3");
-    assertEquals(doit3(s0), "ok");
-    assertEquals(doit3(s1), "fail");
-    assertEquals(doit3(s2), "fail");
-    assertEquals(doit3(s3), "ok");  
-    assertEquals(doit3(s4), "fail");
-    assertEquals(doit3(s5), "fail");
-    assertEquals(doit3(s6), "fail");
-  }
-
-  def doit4(e: List[Char]): String = e match {
-    case List( ('a'|'b')*,('a'|'b'|'c')+ ) => "ga!!!!"
-    case _                                 => "gu"
-  }
-
-  def test4: Unit = {
-    Console.println("testWR_4");
-    assertEquals( doit4( s0 ), "gu");
-    assertEquals( doit4( s1 ), "ga!!!!");
-    assertEquals( doit4( s2 ), "ga!!!!");
-    assertEquals( doit4( s3 ), "ga!!!!");
-    assertEquals( doit4( s4 ), "ga!!!!");
-    assertEquals( doit4( s5 ), "ga!!!!");
-    assertEquals( doit4( s6 ), "ga!!!!");
-  }
-
-  def doit5(e: List[Int]): String = e match {
-    case List( (0|1)+ ) => "binary"
-    case _              => "not binary"
-  }
-
-  def test5: Unit = {
-    Console.println("testWR_5");
-    assertEquals( doit5( s7 ), "not binary");
-    assertEquals( doit5( s8 ), "binary");
-    assertEquals( doit5( s9 ), "not binary");
-  }               
-
-  //  { ('0'..'9')*;'.';('0'..'9');('0'..'9')* ]
-  def doit6(e: List[Char]): String = e match {
-    case List( ('0'|'1'|'2'|'3'|'4'|'5'|'6'|'7'|'8'|'9')*,
-                '.',
-               ('0'|'1'|'2'|'3'|'4'|'5'|'6'|'7'|'8'|'9'),
-               ('0'|'1'|'2'|'3'|'4'|'5'|'6'|'7'|'8'|'9')* )
-
-                                              => "decimal number"
-                case _                        => "not decimal"
-  }
-
-  def test6: Unit = {
-    Console.println("testWR_6");
-    assertEquals(doit6(s3),  "not decimal");
-    assertEquals(doit6(s10), "decimal number");
-  }               
-
-  def test8: Unit = {
-    Console.println("testWR_8");
-      
-    assertTrue( List('d','c') match {
-      case List('a'*, 'd'|'e', 'c'*) => true
-      case _                         => false
-    });
-  }
-
-  def test7:Unit = {
-    Console.println("testWR_7");
-    assertEquals( List(1,2) match {
-      case List(1,(3*,2))=> true; // test normalization (pattern normalizer)
-      case _ => false;
-    }, true);
-  }
-
-  def main(args: Array[String]): Unit = {
-    test1;
-    test2;
-    test3;
-    test4;
-    test5;
-    test6;
-    test7;
-    test8;
-  }
-}
-
-object testWS {
-
-  import values._ ;
-  import scala.testing.UnitTest._ ;
-
-        /* strings:
-
-            "blabla" == [ "bla";"bla" ] == [ 'b';'l';'a';'b';'l';'a' ]
-
-            [ "blabla";'x';'y'? ] == [ ('b';'l';'a';'b';'l';'a'); 'x'; 'y'? ]
-
-        */
-
-        /*
-            def isIdentifierStart(c:char) ;
-
-            case [ ... ; _isIdentifierStart_ ; ... ]
-
-            calls method is..., needs to have type (elementType)Boolean
-            
-            translated to pattern
-            
-                 [ ... ; Apply(is..., Tree.Empty) ; ... ]
-
-         */
-
-         /* for tree automata: 
-
-        [ t0; t1; ...; tn ]  with ti = labeli ( argsi )
-
-        gets translated to
-
-        [ _isTree$0_ ; _isTree$1_ ; ... ; _isTree$n_ ]
-
-        where isTree$i( t ) = t.is[ labeli ] ... (algebraic matcher)
-
-        special case: sequences
-
-        [ ...; seq ; ... ] where seq = [ ... ]
-
-        gets translated to
-
-        [ ...; _seq$0_ ; ...] with seq$0( s ) = t.is[ Sequence ] and 
-                                                seq$0match( s.newIterator )
-
-        subroutines return 
-          1) d'abord true or false,
-          2) later ( true|false, environment )
-                       assume order on variables, enviroment is a tuple/sequence
-        */
-
-    def doit1(e: List[Char]):Int = e match {
-                case List( 'a', 'b', 'c' )        => 100
-                case List( ('a', 'b','c')? )      => 1004
-                case List( ('a', 'a','a')? )      => 50
-                case List( ('a'|'b')*,('a'|'b') ) => 700
-                case _                        => 321
-        };      
-
-  def test1: Unit = {
-    Console.println("testWS");
-    assertEquals( doit1( s0 ), 1004);
-    assertEquals( doit1( s1 ),  100);
-    assertEquals( doit1( s2 ),  321);
-    assertEquals( doit1( s3 ),  50);
-    assertEquals( doit1( s4 ), 321);
-    assertEquals( doit1( s5 ), 700);
-    assertEquals( doit1( s6 ), 700);
-  }
-
-  def main(args: Array[String]): Unit = {
-    test1;
-  }
-
-}
-
-object testWT  {
-
-  import values._ ;
-  import scala.testing.UnitTest._ ;
-
-  def doit1(e: List[Char]): Int = e match {
-    case List('a', _, _) => 100
-    case List(_ *)       => 321
-    case _               => 20022 // this never happens
-  }
-
-  def test1: Unit = {
-    Console.println("testWT");
-    assertEquals( doit1( s0 ),321);
-    assertEquals( doit1( s1 ),100);
-    assertEquals( doit1( s2 ),321);
-    assertEquals( doit1( s3 ),100);
-    assertEquals( doit1( s4 ),321);
-    assertEquals( doit1( s5 ),321);
-    assertEquals( doit1( s6 ),321)
-  }
-
-  def main(args: Array[String]): Unit = {
-    test1;
-  }
-
-}
-object testWV {
-
-  import values._ ;
-  import scala.testing.UnitTest._ ;
-        
-  class testClass;
-
-  case class testA( arg:List[Char] ) extends testClass;
-
-  def doit1(e: testClass):Int = e match {
-    case testA(List( 'a', 'b', 'c' ))        => 100
-    case testA(List( ('a', 'b','c')? ))      => 1004
-    case testA(List( ('a', 'a','a')? ))      => 50
-    case testA(List( ('a'|'b')*,('a'|'b') )) => 700
-    case testA( _ )                          => 321
-  }
-
-  def test1: Unit = {
-    Console.println("testWV");
-    assertEquals(doit1(testA(s0)), 1004);
-    assertEquals(doit1(testA(s1)),  100);
-    assertEquals(doit1(testA(s2)),  321);
-    assertEquals(doit1(testA(s3)),   50);
-    assertEquals(doit1(testA(s4)),  321);
-    assertEquals(doit1(testA(s5)),  700);
-    assertEquals(doit1(testA(s6)),  700);
-  }
-
-  def main(args: Array[String]) = {
-    test1
-  }
-
-}
-/*
-object testWW {
-
-        import values._ ;
-
-        import scala.testing.UnitTest._ ;
-        
-        class testClass;
-        case class testA( arg:List[Char] ) extends testClass;
-
-        def doit1(e: List[testClass]):Int = e match {
-        
-                case List( testA(List()), testA( List( 'a', 'b' )) )        => 100
-                case _                                                      => 321
-
-        };      
-
-        def test1:Unit = {
-                val x1 = List( testA(s0) );
-
-                Console.println("testWW");
-
-                assertEquals( doit1( x1 ), 321 );
-
-                val x2 = List( testA(Nil), testA('a'::'b'::Nil) );
-                                                  
-                assertEquals( doit1( x2 ), 100 );
-
-        }
-
-        def main( args:Array[String] ) = {
-                test1;
-        }
-
-}
-*/
-object testMZ {
-        import scala.testing.UnitTest.assertEquals ;
-  class Expr;
-  case class One(xs: List[Expr]) extends Expr;
-  case class Two() extends Expr;
-  def testFoo(xs: List[Expr]) = xs match { //bug#132
-    case List(Two()?,a,Two()?) => "a = " + a;
-    case List(Two()*,b,Two()*) => "b = " + b;
-    case List(_*) => "no match";
-  }
-  case class OneN();
-  def bind(xs: List[Any]):String = xs match { // bug#133b
-    case List(x@(OneN()*), y@(OneN())) => "case";
-    case _ => "default";
-  }
-  case class On();
-  case class Tw();
-  def testBar(xs: List[Any]) = xs match { // bug#180
-    case List(((On(), Tw())* | (On(), On())), On()) => "caseBar"
-    case _ => "default";
-  }
-
-
-  def mat195(x:Expr) = x match { // bug#195	
-    case One(x at List(_*)) =>
-    	"x = " + x;
-
-	case _ =>"default";
-
-  }
-
-  def mat196(xs: List[Any]) = xs match { // bug#196	
-    case List(b@(()|())) =>
-    	"case, b = " + b;
-
-	case _ =>"default";
-
-  }
-
-  def mat398(xs:List[Any]) = xs match { // bug#398
-    case List(1) => "one"
-    case x::xs   => "two"
-  }
-
-  def mat406() = {
-    class Type;
-    case class A() extends Type;
-    case class B() extends Type;
-    case class C() extends Type;
-    
-    def foo(x: Type, y: Type): String = Pair(x, y) match {
-      case Pair(A(), A()) 
-      | Pair(A(), B()) 
-      | Pair(B(), A()) 
-      | Pair(B(), B()) => "3"
-      case Pair(C(), C()) => "4"
-      case Pair(A(), _)
-      | Pair(B(), _) => "7"
-      case _ => "8"
-    }
-    
-    foo(A(), C())
-  }
-
-  def mat441() = {
-    val tata = 1;
-    val titi = 0.8 + Math.random();
-    try {
-      tata match {
-        case 1 if (titi < 0.5) => "a"
-        case 0 | 1             => "b"
-      }
-    } catch {
-      case _ => "c"
-    }
-  }
-
-  /* this will crash
-  def matSymbolCloning = {
-    2 match {
-      case 3 | 4 =>
-        class Foo extends scala.xml.Atom[Int](3) {
-          def bar = 7;
-        }
-        null
-    }
-  }
-  */
-
-  def main:Unit = {  
-                Console.println("testMZ - bugs #132 #133b #180 #195 #196 #398 #406 #441");
-    assertEquals(testFoo( List(Two(),Two(),Two(),Two()) ),"b = Two");
-    assertEquals(testFoo( List(Two(),Two(),Two()) ),"a = Two");
-    assertEquals(testFoo( List(Two(),Two()) ),"a = Two");
-    assertEquals(testFoo( List(Two()) ),"a = Two");
-    assertEquals(testFoo( List() ),"no match");
-    assertEquals(bind( List(OneN(),OneN()) ),"case");
-    assertEquals(testBar( List() ),"default");
-    assertEquals(testBar( List(On()) ),"caseBar");
-    assertEquals(testBar( List(On(), On())), "default");
-    assertEquals(testBar( List(On(), On(), On()) ),"caseBar");
-    assertEquals(testBar( List(On(), On(), On(), On()) ),"default");
-    assertEquals(testBar( List(On(), On(), On(), On(), On()) ),"default");
-    assertEquals(mat195( One(List(Two(),Two())) ),"x = List(Two,Two)");
-    assertEquals(mat195( One(List()) ),"x = List()");
-    assertEquals(mat195( Two() ),"default");
-    assertEquals(mat196( List(1) ),"default");
-    assertEquals(mat196( List() ),"case, b = List()");
-    assertEquals(mat398( List(2) ),"two");
-    assertEquals(mat398( List(2) ),"two");
-    assertEquals(mat406(), "7");
-    assertEquals(mat441(), "b");
-    ()
-  }
-  
-}
-/*
-object testNN {
- import scala.testing.UnitTest._ ;
-  abstract class K;
-  case class F(x:K*) extends K;
-  case class G() extends K;
-
-  def mtch(k:K):boolean = k match {
-      case F(F(G()*),G(),F(G()*)) => true;
-      case _ => false;
-  }
-
-  def main:Unit = {
-    Console.println("testNN");
-    assertEquals(mtch( F(F(G()),G(),F(G()))), true);
-    assertEquals(mtch( F(F(),G(),F(G(),G(),G(),G())) ), true);    
-    assertEquals(mtch( G() ), false);    
-    assertEquals(mtch( F(G()) ), false);    
-  }
-}
-*/
-object testNO {   // this does not need to be run, only compiled
-
-  trait Operator;
-  case class Increment() extends Operator;
-  case class Decrement() extends Operator;
-  
-  trait Expression {
-    def eval = this match {
-      case Operation (v: Value, o: Increment) => v
-      case Operation (v: Value, d: Decrement) => v
-    }
-  }
-  
-  case class Value() extends Expression;
-  case class Operation (e: Expression, o: Operator) extends Expression;
-
-
-}
-
-/** see comments in scala.tools.scalac.transformer.matching.PatternMatcher::isSeqApply 2005-02-17
- */
-
-/*
-object testBugSequenceApply {
-
-  val x = List(1,2,3);
-
-  case class ThreeBars extends Seq[Int] {
-    override def length = 3;
-    def elements = x.elements;
-    def apply(i:Int) = x.apply(i);
-  }
-
-  // this works
-  def main:Unit = {  
-    Console.print("testBugSequenceApply ");
-    val z: Seq[Int] = new ThreeBars();
-    Console.print(z match {
-      case Seq(1,2,3) => "hello" // but ThreeBars is a case class...
-    });
-    
-    Console.print(ThreeBars() match {
-      case Seq(1,2,3) => " hello" // but ThreeBars is a case class...
-    });
-  }
-}
-*/
diff --git a/test/files/run/richs.scala b/test/files/run/richs.scala
index 674ca8f..5ee5736 100644
--- a/test/files/run/richs.scala
+++ b/test/files/run/richs.scala
@@ -26,7 +26,7 @@ object RichCharTest1 extends RichTest {
 }
 // object RichCharTest2 extends RichTest {
 //   case class C(s: String) {
-//     private val it = s.elements
+//     private val it = s.iterator
 //     private var c: Char = _
 //     def ch(): Char = c
 //     def nextch(): Unit = { c = if (it.hasNext) it.next else ';' }
diff --git a/test/files/run/runtime.scala b/test/files/run/runtime.scala
index 8e3e438..2dcb41f 100644
--- a/test/files/run/runtime.scala
+++ b/test/files/run/runtime.scala
@@ -1,7 +1,6 @@
 //############################################################################
 // Run Time Bugs & Test Cases
 //############################################################################
-// $Id: runtime.scala 9982 2007-02-14 13:37:19Z odersky $
 
 //############################################################################
 // Test 0 - Array creation
diff --git a/test/files/run/sequenceComparisons.scala b/test/files/run/sequenceComparisons.scala
new file mode 100644
index 0000000..c8e14e4
--- /dev/null
+++ b/test/files/run/sequenceComparisons.scala
@@ -0,0 +1,121 @@
+import scala.collection.{ mutable, immutable }
+import collection.{ Seq, Traversable }
+
+object Test {
+  // TODO: 
+  //
+  // SeqProxy
+  // SeqForwarder
+  // the commented out ones in seqMakers
+  
+  val seqMakers = List[List[Int] => Seq[Int]](
+    // scala.Array(_: _*),
+    mutable.ArrayBuffer(_: _*),
+    // mutable.ArrayStack(_: _*),
+    mutable.Buffer(_: _*),
+    mutable.LinearSeq(_: _*),
+    // null on Nil
+    // mutable.LinkedList(_: _*),
+    mutable.ListBuffer(_: _*),
+    // mutable.PriorityQueue(_: _*),
+    // immutable.Queue(_: _*),
+    // mutable.Queue(_: _*),
+    immutable.Seq(_: _*),
+    mutable.Seq(_: _*),
+    immutable.Stack(_: _*),
+    // mutable.Stack(_: _*),    
+    immutable.IndexedSeq(_: _*), // was Vector
+    //mutable.Vector(_: _*),
+    immutable.List(_: _*),
+    immutable.Stream(_: _*)
+  )
+  
+  abstract class Data[T] {
+    val seq: Seq[T]
+    private def seqList = seq.toList
+    // _1 is inputs which must be true, _2 which must be false
+    type Inputs = (List[List[T]], List[List[T]])
+    case class Method(
+      f: (Seq[T], Seq[T]) => Boolean,
+      inputs: Inputs,
+      descr: String
+    ) {
+      def trueList  = inputs._1
+      def falseList = inputs._2
+    }
+
+    lazy val eqeq = Method(_ == _, (List(seqList), List(Nil, seqList drop 1, seqList ::: seqList)), "%s == %s")
+    
+    val startsWithInputs: Inputs
+    lazy val startsWith = Method(_ startsWith _, startsWithInputs, "%s startsWith %s")
+    
+    val endsWithInputs: Inputs
+    lazy val endsWith = Method(_ endsWith _, endsWithInputs, "%s endsWith %s")
+
+    val indexOfSliceInputs: Inputs
+    private def subseqTest(s1: Seq[T], s2: Seq[T]) = (s1 indexOfSlice s2) != -1
+    lazy val indexOfSlice = Method(subseqTest _, indexOfSliceInputs, "(%s indexOfSlice %s) != -1")
+    
+    val sameElementsInputs: Inputs
+    lazy val sameElements = Method(_ sameElements _, sameElementsInputs, "%s sameElements %s")
+    
+    def methodList = List(eqeq, startsWith, endsWith, indexOfSlice, sameElements)
+  }
+  
+  object test1 extends Data[Int] {
+    val seq = List(1,2,3,4,5)
+    
+    val startsWithInputs = (
+      List(Nil, List(1), List(1,2), seq),
+      List(List(1,2,3,4,6), seq ::: List(5), List(0))
+    )
+    
+    val endsWithInputs = (
+      List(Nil, List(5), List(4,5), seq),
+      List(0 :: seq, List(5,2,3,4,5), List(3,4), List(5,6))
+    )
+    
+    val indexOfSliceInputs = (
+      List(Nil, List(1), List(3), List(5), List(1,2), List(2,3,4), List(4,5), seq),
+      List(List(1,2,3,5), List(6), List(5,4,3,2,1), List(2,1))
+    )
+    
+    val sameElementsInputs = (
+      List(List(1,2,3,4,5)),
+      List(Nil, List(1), List(1,2), List(2,3,4), List(2,3,4,5), List(2,3,4,5,1), List(1,2,3,5,4), seq reverse)
+    )
+  }
+  
+  val failures = new mutable.ListBuffer[String]
+  var testCount = 0
+  
+  def assertOne(op1: Any, op2: Any, res: Boolean, str: String) {
+    testCount += 1
+    val resStr = str.format(op1, op2)
+    // println(resStr)
+    if (!res)
+      failures += ("FAIL: " + resStr)
+    // assert(res, resStr)
+  }
+  
+  def runSeqs() = {
+    for (s1f <- seqMakers ; s2f <- seqMakers ; testData <- List(test1)) {
+      import testData._
+      val scrut = s1f(seq)
+      
+      for (Method(f, (trueList, falseList), descr) <- methodList) {
+        for (s <- trueList; val rhs = s2f(s))
+          assertOne(scrut, rhs, f(scrut, rhs), descr)
+        
+        for (s <- falseList; val rhs = s2f(s))
+          assertOne(scrut, rhs, !f(scrut, rhs), "!(" + descr + ")")
+      }
+    }
+  }
+  
+  def main(args: Array[String]) {
+    runSeqs()
+    
+    assert(failures.isEmpty, failures mkString "\n")
+  }
+}
diff --git a/test/files/run/slice-strings.scala b/test/files/run/slice-strings.scala
new file mode 100644
index 0000000..2308586
--- /dev/null
+++ b/test/files/run/slice-strings.scala
@@ -0,0 +1,19 @@
+object Test {  
+  def cmp(x1: String) = {
+    val x2 = x1.toList
+    
+    -10 to 10 foreach { i =>
+      assert(x1.take(i) == x2.take(i).mkString)
+      assert(x1.drop(i) == x2.drop(i).mkString)
+      assert(x1.takeRight(i) == x2.takeRight(i).mkString)
+      assert(x1.dropRight(i) == x2.dropRight(i).mkString)
+    }
+    for (idx1 <- -3 to 3 ; idx2 <- -3 to 3) {
+      assert(x1.slice(idx1, idx2) == x2.slice(idx1, idx2).mkString)
+    }
+  }
+  
+  def main(args: Array[String]): Unit = {
+     cmp("abcde")
+  }
+}
diff --git a/test/files/run/slices.check b/test/files/run/slices.check
index 6840a02..c7af9db 100644
--- a/test/files/run/slices.check
+++ b/test/files/run/slices.check
@@ -26,11 +26,9 @@ Array(1, 2, 3)
 Array(1, 2, 3)
 Array(1, 2)
 Array()
-Array()
 
 Array(4)
 Array()
 Array()
 Array()
-Array()
 
diff --git a/test/files/run/slices.scala b/test/files/run/slices.scala
index 14789d3..9c76572 100644
--- a/test/files/run/slices.scala
+++ b/test/files/run/slices.scala
@@ -23,24 +23,24 @@ object Test extends Application {
   println
 
   // arrays
-  println(Array(1, 2, 3, 4).slice(1, 2))
-  println(Array(1, 2, 3, 4).slice(2, 1))
-  println(Array(1, 2, 3, 4).slice(-1, 1))
-  println(Array(1, 2, 3, 4).slice(1, -1))
-  println(Array(1, 2, 3, 4).slice(-2, 2))
+  println(Array(1, 2, 3, 4).slice(1, 2).deep)
+  println(Array(1, 2, 3, 4).slice(2, 1).deep)
+  println(Array(1, 2, 3, 4).slice(-1, 1).deep)
+  println(Array(1, 2, 3, 4).slice(1, -1).deep)
+  println(Array(1, 2, 3, 4).slice(-2, 2).deep)
   println
 
-  println(Array(1, 2, 3, 4) take 3)
-  println(Array(1, 2, 3) take 3)
-  println(Array(1, 2) take 3)
-  println((Array(): Array[Int]) take 3)
-  println(Array[Nothing]() take 3)  // contrib #757
+  println(Array(1, 2, 3, 4) take 3 deep)
+  println(Array(1, 2, 3) take 3 deep)
+  println(Array(1, 2) take 3 deep)
+  println((Array(): Array[Int]) take 3 deep)
+//  println(Array[Nothing]() take 3)  // contrib #757
   println
 
-  println(Array(1, 2, 3, 4) drop 3)
-  println(Array(1, 2, 3) drop 3)
-  println(Array(1, 2) drop 3)
-  println((Array(): Array[Int]) drop 3)
-  println(Array[Nothing]() drop 3)
+  println(Array(1, 2, 3, 4) drop 3 deep)
+  println(Array(1, 2, 3) drop 3 deep)
+  println(Array(1, 2) drop 3 deep)
+  println((Array(): Array[Int]) drop 3 deep)
+//  println(Array[Nothing]() drop 3)
   println
 }
diff --git a/test/files/run/spec-absfun.scala b/test/files/run/spec-absfun.scala
new file mode 100644
index 0000000..2b78054
--- /dev/null
+++ b/test/files/run/spec-absfun.scala
@@ -0,0 +1,43 @@
+
+/** Test inheritance. See #3085.
+ *  Anonymous functions extend AbstractFunction1[SpecializedPair[Int], Unit]. The
+ *  specialized type SpecializedPair$mcI$sp should not leak into the superclass because
+ *  the definition of apply would vary covariantly, and erasure won't consider it an
+ *  override of the abstract apply, leading to an AbstractMethodError at runtime.
+ */
+
+object Test {
+
+  private val Max = 1000
+
+  def main(args: Array[String]) {
+    notSpecialized()
+    specialized()
+  }
+
+  def notSpecialized() {
+    val pairs = for { i <- 1 to Max; j <- 1 to i } yield new Pair(i, j)
+    val time0 = System.nanoTime
+    pairs foreach { p => p.first * p.second }
+    val time1 = System.nanoTime
+//    println(time1 - time0)
+  }
+
+  def specialized() {
+    val pairs = for { i <- 1 to Max; j <- 1 to i } yield new SpecializedPair(i, j)
+    val time0 = System.nanoTime
+    pairs foreach { p => p.first * p.second }
+    val time1 = System.nanoTime
+//    println(time1 - time0)
+  }
+}
+
+class Pair[A](_first: A, _second: A) {
+  def first = _first
+  def second = _second
+}
+
+class SpecializedPair[@specialized(Int) A](_first: A, _second: A) {
+  def first = _first
+  def second = _second
+}
diff --git a/test/files/run/spec-ame.check b/test/files/run/spec-ame.check
new file mode 100644
index 0000000..afa12db
--- /dev/null
+++ b/test/files/run/spec-ame.check
@@ -0,0 +1,2 @@
+abc
+10
diff --git a/test/files/run/spec-ame.scala b/test/files/run/spec-ame.scala
new file mode 100644
index 0000000..5898170
--- /dev/null
+++ b/test/files/run/spec-ame.scala
@@ -0,0 +1,17 @@
+// ticket #3432
+object Test {
+  trait B[@specialized(Int) T] {
+    def value: T 
+  }
+
+  class A[@specialized(Int) T](x: T) { 
+    def foo: B[T] = new B[T] { 
+      def value = x 
+    } 
+  }
+
+  def main(args: Array[String]) {
+    println((new A("abc")).foo.value)
+    println((new A(10)).foo.value)
+  }
+}
diff --git a/test/files/run/spec-constr.check b/test/files/run/spec-constr.check
new file mode 100644
index 0000000..29d70d9
--- /dev/null
+++ b/test/files/run/spec-constr.check
@@ -0,0 +1,2 @@
+hello?
+goodbye
diff --git a/test/files/run/spec-constr.scala b/test/files/run/spec-constr.scala
new file mode 100644
index 0000000..4c80d09
--- /dev/null
+++ b/test/files/run/spec-constr.scala
@@ -0,0 +1,14 @@
+object Test {
+  class E[@specialized(Int) A](var f: A => Boolean) {
+    def this() = this(null)
+
+    println("hello?")
+    if (f == null) f = { _ => false }
+  }
+
+  def main(args: Array[String]) {
+    new E[Int]
+    println("goodbye")
+  }
+}
+
diff --git a/test/files/run/spec-early.check b/test/files/run/spec-early.check
new file mode 100644
index 0000000..414aacc
--- /dev/null
+++ b/test/files/run/spec-early.check
@@ -0,0 +1,4 @@
+a
+abc
+42
+abc
diff --git a/test/files/run/spec-early.scala b/test/files/run/spec-early.scala
new file mode 100644
index 0000000..84a8983
--- /dev/null
+++ b/test/files/run/spec-early.scala
@@ -0,0 +1,15 @@
+trait Tr
+
+class Foo[@specialized(Int) T](_x: T) extends {
+  val bar = "abc"
+  val baz = "bbc"
+} with Tr {
+  val x = _x
+  println(x)
+  println(bar)
+}
+
+object Test extends Application {
+  new Foo("a")
+  new Foo(42)
+}
diff --git a/test/files/run/spec-init.check b/test/files/run/spec-init.check
new file mode 100644
index 0000000..8a659f8
--- /dev/null
+++ b/test/files/run/spec-init.check
@@ -0,0 +1,9 @@
+abc
+abc
+null
+shouldn't see two initialized values and one uninitialized
+42
+42
+0
+ok
+ok
diff --git a/test/files/run/spec-init.scala b/test/files/run/spec-init.scala
new file mode 100644
index 0000000..bd3428f
--- /dev/null
+++ b/test/files/run/spec-init.scala
@@ -0,0 +1,41 @@
+class Foo[@specialized(Int) T](_x: T) {
+  val x = _x
+  def bar {}
+
+  val y = x
+  println(x)
+  println(y)
+  println(z)
+
+  def baz {}
+  val z = y
+
+}
+
+class Bar[@specialized(Int) T] {
+  def foo(x: T) = print(x)
+}
+
+object Global {
+  var msg = "ok"
+}
+
+class TouchGlobal[@specialized(Int) T](_x: T) {
+  println(Global.msg)
+  val x = {
+    Global.msg = "not ok"
+    _x
+  }
+}
+
+object Test {
+  def main(args: Array[String]) {
+    (new Foo("abc"))
+    println("shouldn't see two initialized values and one uninitialized")
+    (new Foo(42))
+
+    (new TouchGlobal(new Object))
+    Global.msg = "ok" // reset the value
+    (new TouchGlobal(42))
+  }
+}
diff --git a/test/files/run/spec-matrix.check b/test/files/run/spec-matrix.check
new file mode 100644
index 0000000..72e8ffc
--- /dev/null
+++ b/test/files/run/spec-matrix.check
@@ -0,0 +1 @@
+*
diff --git a/test/files/run/spec-matrix.scala b/test/files/run/spec-matrix.scala
new file mode 100644
index 0000000..2acf620
--- /dev/null
+++ b/test/files/run/spec-matrix.scala
@@ -0,0 +1,70 @@
+/** Test matrix multiplication with specialization.
+ */
+
+class Matrix[@specialized A: ClassManifest](val rows: Int, val cols: Int) {
+  private val arr: Array[Array[A]] = new Array[Array[A]](rows, cols)
+  
+  def apply(i: Int, j: Int): A = {
+    if (i < 0 || i >= rows || j < 0 || j >= cols)
+      throw new NoSuchElementException("Indexes out of bounds: " + (i, j))
+
+    arr(i)(j)
+  }
+
+  def update(i: Int, j: Int, e: A) {
+    arr(i)(j) = e
+  }
+
+  def rowsIterator: Iterator[Array[A]] = new Iterator[Array[A]] {
+    var idx = 0;
+    def hasNext = idx < rows
+    def next = {
+      idx += 1
+      arr(idx - 1)
+    }
+  }
+}
+
+object Test {
+  def main(args: Array[String]) {
+    val m = randomMatrix(200, 100)
+    val n = randomMatrix(100, 200)
+
+    mult(m, n)
+    println("*")
+  }
+
+  def randomMatrix(n: Int, m: Int) = {
+    val r = new util.Random(10)
+    val x = new Matrix[Int](n, m) 
+    for (i <- 0 until n; j <- 0 until m)
+      x(i, j) = r.nextInt
+    x
+  }
+
+
+  def multManifest[@specialized(Int) T](m: Matrix[T], n: Matrix[T])(implicit cm: ClassManifest[T], num: Numeric[T]) {
+    val p = new Matrix[T](m.rows, n.cols)
+    import num._
+
+    for (i <- 0 until m.rows) 
+      for (j <- 0 until n.cols) {
+        var sum = num.zero
+        for (k <- 0 until n.rows)
+          sum += m(i, k) * n(k, j)
+        p(i, j) = sum
+      }
+  }
+
+  def mult(m: Matrix[Int], n: Matrix[Int]) {
+    val p = new Matrix[Int](m.rows, n.cols)
+
+    for (i <- 0 until m.rows) 
+      for (j <- 0 until n.cols) {
+        var sum = 0
+        for (k <- 0 until n.rows)
+          sum += m(i, k) * n(k, j)
+        p(i, j) = sum
+      }
+  }
+}
diff --git a/test/files/jvm5/bug680.check b/test/files/run/spec-overrides.check
similarity index 100%
copy from test/files/jvm5/bug680.check
copy to test/files/run/spec-overrides.check
diff --git a/test/files/run/spec-overrides.scala b/test/files/run/spec-overrides.scala
new file mode 100644
index 0000000..f5d2e2f
--- /dev/null
+++ b/test/files/run/spec-overrides.scala
@@ -0,0 +1,20 @@
+ trait Base[@specialized(Double) B] {
+  def default: B;
+ }
+
+ trait D1 extends Base[Double] {
+  override def default = 0.0;
+ }
+
+ class D2 extends D1  {
+  override def default: Double = 1.0;
+ }
+
+
+object Test extends Application {
+  val d2 = new D2
+
+  assert(d2.default == 1.0, d2.default)
+  assert((d2: Base[_]).default == 1.0, (d2: Base[_]).default)
+  assert((d2: D1).default == 1.0, (d2: D1).default)
+}
diff --git a/test/files/run/spec-patmatch.check b/test/files/run/spec-patmatch.check
new file mode 100644
index 0000000..a6679fa
--- /dev/null
+++ b/test/files/run/spec-patmatch.check
@@ -0,0 +1,19 @@
+bool
+byte
+short
+char
+int
+long
+double
+float
+default
+object instantiations:
+bool
+byte
+short
+char
+int
+long
+double
+float
+default
diff --git a/test/files/run/spec-patmatch.scala b/test/files/run/spec-patmatch.scala
new file mode 100644
index 0000000..9293883
--- /dev/null
+++ b/test/files/run/spec-patmatch.scala
@@ -0,0 +1,52 @@
+class Foo[@specialized A] {
+  def test(x: A) = println(x match {
+   case _: Boolean => "bool"
+   case _: Byte => "byte"
+   case _: Short => "short"
+   case _: Char => "char"
+   case i: Int => "int"
+   case l: Long => "long"
+   case d: Double => "double"
+   case e: Float => "float"
+   case _ => "default"
+ })
+}
+
+object Test {
+ def test[@specialized A] (x: A) = println(x match {
+   case _: Boolean => "bool"
+   case _: Byte => "byte"
+   case _: Short => "short"
+   case _: Char => "char"
+   case i: Int => "int"
+   case l: Long => "long"
+   case d: Double => "double"
+   case e: Float => "float"
+   case _ => "default"
+ })
+
+  def main(args: Array[String]) {
+    test(true)
+    test(42.toByte)
+    test(42.toShort)
+    test('b')
+    test(42)
+    test(42l)
+    test(42.0)
+    test(42.0f)
+    test(new Object)
+
+    println("object instantiations:")
+    (new Foo).test(true)
+    (new Foo).test(42.toByte)
+    (new Foo).test(42.toShort)
+    (new Foo).test('b')
+    (new Foo).test(42)
+    (new Foo).test(42l)
+    (new Foo).test(42.0)
+    (new Foo).test(42.0f)
+    (new Foo).test(new Object)
+
+  }
+
+}
diff --git a/test/files/run/streamWithFilter.check b/test/files/run/streamWithFilter.check
new file mode 100644
index 0000000..6b0e91a
--- /dev/null
+++ b/test/files/run/streamWithFilter.check
@@ -0,0 +1,5 @@
+15
+30
+45
+60
+75
diff --git a/test/files/run/streamWithFilter.scala b/test/files/run/streamWithFilter.scala
new file mode 100644
index 0000000..7f8f9a0
--- /dev/null
+++ b/test/files/run/streamWithFilter.scala
@@ -0,0 +1,11 @@
+object Test {
+  val nums = Stream.from(1)
+  def isFizz(x: Int) = x % 3 == 0
+  def isBuzz(x: Int) = x % 5 == 0
+  // next line will run forever if withFilter isn't doing its thing.
+  val fizzbuzzes = for (n <- nums ; if isFizz(n) ; if isBuzz(n)) yield n
+  
+  def main(args: Array[String]): Unit = {
+    fizzbuzzes take 5 foreach println
+  }
+}
diff --git a/test/files/run/stream_flatmap_odds.check b/test/files/run/stream_flatmap_odds.check
new file mode 100644
index 0000000..2b945e7
--- /dev/null
+++ b/test/files/run/stream_flatmap_odds.check
@@ -0,0 +1 @@
+Stream(1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83)
diff --git a/test/files/run/stream_flatmap_odds.scala b/test/files/run/stream_flatmap_odds.scala
new file mode 100644
index 0000000..ed1a537
--- /dev/null
+++ b/test/files/run/stream_flatmap_odds.scala
@@ -0,0 +1,4 @@
+object Test extends Application {
+	lazy val odds: Stream[Int] = Stream(1) append ( odds flatMap {x => Stream(x + 2)} )
+	println(odds take 42 force)
+}
\ No newline at end of file
diff --git a/test/files/run/stream_length.check b/test/files/run/stream_length.check
new file mode 100644
index 0000000..9906de7
--- /dev/null
+++ b/test/files/run/stream_length.check
@@ -0,0 +1 @@
+Length: 970299
diff --git a/test/files/run/stream_length.scala b/test/files/run/stream_length.scala
new file mode 100644
index 0000000..68e9cad
--- /dev/null
+++ b/test/files/run/stream_length.scala
@@ -0,0 +1,15 @@
+
+
+object Test {
+  def walk(depth: Int, bias: String): Stream[String] = {
+    if (depth == 0)
+      Stream(bias)
+    else {
+      Stream.concat(Stream.range(1, 100).map((x: Int) => walk(depth-1, bias + x)))
+    }
+  }
+
+  def main(args: Array[String]) {
+    println("Length: " + walk(3, "---").length)
+  }
+}
diff --git a/test/files/run/streams.scala b/test/files/run/streams.scala
index 9959b4a..e3c871c 100644
--- a/test/files/run/streams.scala
+++ b/test/files/run/streams.scala
@@ -5,7 +5,7 @@ object Test extends Application {
   println
 
   val s1 = Stream.cons(1, Stream.empty)
-  println(s1.toArray)
+  println(s1.toArray.deep)
   println(s1.take(1))
   println(s1.take(2))
   println(s1.drop(1))
@@ -15,7 +15,7 @@ object Test extends Application {
   println
 
   val s2 = s1.append(Stream.cons(2, Stream.empty))
-  println(s2.toArray)
+  println(s2.toArray.deep)
   println(s2.drop(1))
   println(s2.drop(2))
   println(s2.drop(-1))
diff --git a/test/files/run/stringbuilder.scala b/test/files/run/stringbuilder.scala
new file mode 100644
index 0000000..8ee8435
--- /dev/null
+++ b/test/files/run/stringbuilder.scala
@@ -0,0 +1,40 @@
+object Test extends Application {
+  val str = "ABCDEFGHIJKLMABCDEFGHIJKLM"
+  val surrogateStr = "an old Turkic letter: \uD803\uDC22"
+  
+  type SB = { 
+    def indexOf(str: String): Int
+    def indexOf(str: String, fromIndex: Int): Int
+    def lastIndexOf(str: String): Int
+    def lastIndexOf(str: String, fromIndex: Int): Int
+  }
+  
+  import scala.collection.mutable.{ StringBuilder => ScalaStringBuilder }
+  import java.lang.{ StringBuilder => JavaStringBuilder }
+  
+  val sbScala = new ScalaStringBuilder() append str
+  val sbJava = new JavaStringBuilder() append str
+  val sbs: List[SB] = List[SB](sbScala, sbJava)
+  
+  def sameAnswers(f: (SB) => Int) = assert(f(sbScala) == f(sbJava))
+
+  sameAnswers(_.indexOf(""))
+  sameAnswers(_.indexOf("G"))
+  sameAnswers(_.indexOf("ABC"))
+  sameAnswers(_.indexOf("KLM"))
+  sameAnswers(_.indexOf("QZV"))
+  sameAnswers(_.indexOf("LMABC"))
+  sameAnswers(_.lastIndexOf(""))
+  sameAnswers(_.lastIndexOf("M"))
+  sameAnswers(_.lastIndexOf("ABCDEFG"))
+  sameAnswers(_.lastIndexOf("KLM"))
+  sameAnswers(_.lastIndexOf("QZV"))
+  sameAnswers(_.lastIndexOf("GHI", 22))
+  sameAnswers(_.lastIndexOf("KLM", 22))
+  
+  // testing that the "reverse" implementation avoids reversing surrogate pairs
+  val jsb = new JavaStringBuilder(surrogateStr) reverse
+  val ssb = new ScalaStringBuilder(surrogateStr) reverseContents ;
+  
+  assert(jsb.toString == ssb.toString)
+}
diff --git a/test/files/run/t0017.check b/test/files/run/t0017.check
index ab580f8..3a72142 100644
--- a/test/files/run/t0017.check
+++ b/test/files/run/t0017.check
@@ -1 +1 @@
-Array(Array(1, 3), Array(2, 4))
+Array(ArraySeq(1, 3), ArraySeq(2, 4))
diff --git a/test/files/run/t0017.scala b/test/files/run/t0017.scala
index 4b35a57..5f02606 100644
--- a/test/files/run/t0017.scala
+++ b/test/files/run/t0017.scala
@@ -14,4 +14,4 @@ val transposed = transpose(my_arr)
 
 println(transposed.deepToString)
 
-}
\ No newline at end of file
+}
diff --git a/test/files/run/t0421.check b/test/files/run/t0421.check
index eac7886..cdcf042 100644
--- a/test/files/run/t0421.check
+++ b/test/files/run/t0421.check
@@ -1,3 +1,3 @@
-[[0,1],[2,3],[4,5]]
-[[31.0]]
-[[24.0,32.0]]
+[Array(0, 1),Array(2, 3),Array(4, 5)]
+[Array(31.0)]
+[Array(24.0, 32.0)]
diff --git a/test/files/run/t0421.scala b/test/files/run/t0421.scala
index 7c4d7fc..121fc4f 100644
--- a/test/files/run/t0421.scala
+++ b/test/files/run/t0421.scala
@@ -1,7 +1,7 @@
 // ticket #421
 object Test extends Application {
 
-  def transpose[A](xss: Array[Array[A]]) = {
+  def transpose[A: ClassManifest](xss: Array[Array[A]]) = {
     for (i <- Array.range(0, xss(0).length)) yield
       for (xs <- xss) yield xs(i)
   }
@@ -14,6 +14,8 @@ object Test extends Application {
 
   def matmul(xss: Array[Array[Double]], yss: Array[Array[Double]]) = {
     val ysst = transpose(yss) 
+    val ysst1: Array[Array[Double]] = yss.transpose
+    assert(ysst.deep == ysst1.deep)
     for (xs <- xss) yield
       for (yst <- ysst) yield 
         scalprod(xs, yst)
diff --git a/test/files/run/t0432.scala b/test/files/run/t0432.scala
new file mode 100644
index 0000000..8ba9015
--- /dev/null
+++ b/test/files/run/t0432.scala
@@ -0,0 +1,15 @@
+object Test {
+  type valueType = { def value: this.type }
+
+  class StringValue(x: String) {
+    def value: this.type = this
+  }
+
+  def m(x: valueType) = x.value
+
+  val s = new StringValue("hei")
+
+  def main(args: Array[String]) {
+    m(s)
+  }
+}
diff --git a/test/files/run/t0485.check b/test/files/run/t0485.check
deleted file mode 100644
index 3a462cf..0000000
--- a/test/files/run/t0485.check
+++ /dev/null
@@ -1,32 +0,0 @@
-m1={(10,20), (20,30)}
-m2={(10,20)}
-m1.size > m2.size is true
-m1 equals m2 is true
-
-m1={(10,20), (20,30)}
-m2={(10,20)}
-m1.size > m2.size is true
-m1 equals m2 is true
-
-m1={(10,20), (20,30)}
-m2={(10,20)}
-m1.size > m2.size is true
-m1 equals m2 is true
-
-java.lang.CloneNotSupportedException: The underlying map doesn't implement the Cloneable interface
-
-s1=[10, 20]
-s2=[10]
-s1.size > s2 is true
-s1 equals s2 is true
-
-s1=[10, 20]
-s2=[10]
-s1.size > s2 is true
-s1 equals s2 is true
-
-s1=[10, 20]
-s2=[10]
-s1.size > s2 is true
-s1 equals s2 is true
-
diff --git a/test/files/run/t0485.scala b/test/files/run/t0485.scala
deleted file mode 100644
index 9e2017a..0000000
--- a/test/files/run/t0485.scala
+++ /dev/null
@@ -1,54 +0,0 @@
-import scala.collection.jcl
-
-object Test extends Application {
-  testMap
-  testSet
-}
-
-object testMap {
-  def toString(m1: collection.Map[Int, Int]): String =
-    m1.toList.sort((x, y) => x < y).mkString("{", ", ", "}")
-  def test(m1: jcl.Map[Int, Int]) {
-    try {
-      m1.put(10, 20)
-      val m2 = m1.clone()
-      m1.put(20, 30)
-      println("m1="+toString(m1))
-      println("m2="+toString(m2))
-      println("m1.size > m2.size is "+ (m1.size > m2.size))
-      m1.remove((20, 30))
-      println("m1 equals m2 is "+ (m1 equals m2))
-      println()
-    }
-    catch {
-      case e: Exception =>
-        println(e); println()
-    }
-  }
-  test(new jcl.HashMap[Int, Int])
-  // Clone on IdentityHashMap of java-ibm-1.6 behaves differently than all others
-  // Therefore, for now we will not perform this test on it.
-  // test(new jcl.IdentityHashMap[Int, Int])
-  test(new jcl.LinkedHashMap[Int, Int])
-  test(new jcl.TreeMap[Int, Int])
-  test(new jcl.WeakHashMap[Int, Int])
-}
-
-object testSet {
-  def toString(s1: collection.Set[Int]): String =
-    s1.toList.sort((x, y) => x < y).mkString("[", ", ", "]")
-  def test(s1: jcl.Set[Int]) {
-    s1.add(10)
-    val s2 = s1.clone()
-    s1.add(20)
-    println("s1="+toString(s1))
-    println("s2="+toString(s2))
-    println("s1.size > s2 is "+ (s1.size > s2.size))
-    s1.remove(20)
-    println("s1 equals s2 is "+ (s1 equals s2))
-    println()
-  }
-  test(new jcl.HashSet[Int])
-  test(new jcl.LinkedHashSet[Int])
-  test(new jcl.TreeSet[Int])
-}
diff --git a/test/files/run/t0528.scala b/test/files/run/t0528.scala
index b00ef4f..df6d13a 100644
--- a/test/files/run/t0528.scala
+++ b/test/files/run/t0528.scala
@@ -3,12 +3,12 @@ trait Sequ[A] {
 }
 
 class RichStr extends Sequ[Char] {
-  // override to a primitve array
+  // override to a primitive array
   def toArray: Array[Char] = Array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9')
 }
 
 object Test extends Application {
   val x: RichStr = new RichStr
 
-  println((x: Sequ[Char]).toArray) // calling through the bridge misses unboxing
+  println((x: Sequ[Char]).toArray.deep) // calling through the bridge misses unboxing
 }
diff --git a/test/files/run/t0607.scala b/test/files/run/t0607.scala
index afc7ff9..5601494 100644
--- a/test/files/run/t0607.scala
+++ b/test/files/run/t0607.scala
@@ -1,7 +1,7 @@
 object Test extends Application {
-  case class A
-  case class B extends A
+  case class A()
+  class B extends A() { override def toString() = "B()" }
   println(A())
-  println(B())
+  println(new B())
 }
 
diff --git a/test/files/run/t0677.scala b/test/files/run/t0677.scala
index 7978e3d..94f3081 100644
--- a/test/files/run/t0677.scala
+++ b/test/files/run/t0677.scala
@@ -1,5 +1,8 @@
 object Test extends Application {
-  class X[T] { val a = new Array[Array[T]](3,4) }
+  class X[T: ClassManifest] { 
+    val a = new Array[Array[T]](3,4)
+    val b = Array.ofDim[T](3, 4) 
+  }
   val x = new X[String]
   x.a(1)(2) = "hello"
   assert(x.a(1)(2) == "hello")
diff --git a/test/files/run/t0883.scala b/test/files/run/t0883.scala
index 0bdee62..c559926 100644
--- a/test/files/run/t0883.scala
+++ b/test/files/run/t0883.scala
@@ -1,4 +1,5 @@
-case class Foo(name: String)
+object Foo { def apply(x: String) = new Foo(x) }
+class Foo(name: String)
 case object Bar extends Foo("Bar")
 case class Baz extends Foo("Baz") 
 object Test extends Application {
diff --git a/test/files/run/t1167.check b/test/files/run/t1167.check
new file mode 100644
index 0000000..885d4c9
--- /dev/null
+++ b/test/files/run/t1167.check
@@ -0,0 +1,3 @@
+$anon$1
+$anon$2
+$anonfun$testFunc$1
diff --git a/test/files/run/t1167.scala b/test/files/run/t1167.scala
new file mode 100644
index 0000000..ac96262
--- /dev/null
+++ b/test/files/run/t1167.scala
@@ -0,0 +1,25 @@
+/** Tests for compatible InnerClasses attribute between trait and
+ *  impl classes, as well as anonymous classes.
+ */
+
+trait Test1 {
+  def testFunc(i:Int): Unit = {
+    (i:Int) => i + 5
+  }
+}
+	
+abstract class Foo {
+  override def toString = getClass.getSimpleName
+  
+  abstract class Bar {
+    override def toString = getClass.getSimpleName
+  } 
+}
+
+object Test extends Application {
+  val foo = new Foo {}
+  val bar = new foo.Bar {}
+  println(foo)
+  println(bar)
+  println(Class.forName("Test1$$anonfun$testFunc$1").getSimpleName)
+}
diff --git a/test/files/run/t1323.scala b/test/files/run/t1323.scala
index 6c2a445..831f8c7 100644
--- a/test/files/run/t1323.scala
+++ b/test/files/run/t1323.scala
@@ -1,25 +1,25 @@
 object Test extends Application {
-  println(" 1:" + List(1,2,3,4).indexOf(List(0,1)))        // -1
-  println(" 2:" + List(1,2,3,4).indexOf(List(1,2)))        //  0
-  println(" 3:" + List(1,2,3,4).indexOf(List(2,3)))        //  1
-  println(" 4:" + List(1,2,3,4).indexOf(List(3,4)))        //  2
-  println(" 5:" + List(1,2,3,4).indexOf(List(4,5)))        // -1 
-  println(" 6:" + List(1,2,3,4).indexOf(List(2,4)))        // -1
-  println(" 7:" + List(1,2,3,4).indexOf(List(4,3)))        // -1 
-  println(" 8:" + List(1,2,3,4).indexOf(List(1,3)))        // -1
-  println(" 9:" + List(1,2,3,4).indexOf(List(1,3)))        // -1
-  println("10:" + List(1,2,3,4).indexOf(List(1,2,3,4)))    //  0
-  println("11:" + List(1,2,3,4).indexOf(List(4,3,2,1)))    // -1
-  println("12:" + List(1,2,3,4).indexOf(List(1,2,3,4,5)))  // -1
-  println("13:" + List(1,2,3,4).indexOf(List(5,4,3,2,1)))  // -1
-  println("14:" + List(1,2,3,4).indexOf(List()))           //  0
-  println("15:" + List().indexOf(List()))                  //  0
-  println("16:" + List().indexOf(List(1,2,3,4)))           // -1
+  println(" 1:" + List(1,2,3,4).indexOfSlice(List(0,1)))        // -1
+  println(" 2:" + List(1,2,3,4).indexOfSlice(List(1,2)))        //  0
+  println(" 3:" + List(1,2,3,4).indexOfSlice(List(2,3)))        //  1
+  println(" 4:" + List(1,2,3,4).indexOfSlice(List(3,4)))        //  2
+  println(" 5:" + List(1,2,3,4).indexOfSlice(List(4,5)))        // -1 
+  println(" 6:" + List(1,2,3,4).indexOfSlice(List(2,4)))        // -1
+  println(" 7:" + List(1,2,3,4).indexOfSlice(List(4,3)))        // -1 
+  println(" 8:" + List(1,2,3,4).indexOfSlice(List(1,3)))        // -1
+  println(" 9:" + List(1,2,3,4).indexOfSlice(List(1,3)))        // -1
+  println("10:" + List(1,2,3,4).indexOfSlice(List(1,2,3,4)))    //  0
+  println("11:" + List(1,2,3,4).indexOfSlice(List(4,3,2,1)))    // -1
+  println("12:" + List(1,2,3,4).indexOfSlice(List(1,2,3,4,5)))  // -1
+  println("13:" + List(1,2,3,4).indexOfSlice(List(5,4,3,2,1)))  // -1
+  println("14:" + List(1,2,3,4).indexOfSlice(List()))           //  0
+  println("15:" + List().indexOfSlice(List()))                  //  0
+  println("16:" + List().indexOfSlice(List(1,2,3,4)))           // -1
 
   // Do some testing with infinite sequences
   def from(n: Int): Stream[Int] = Stream.cons(n, from(n + 1))
 
-  println("17:" + List(1,2,3,4).indexOf(from(1)))          // -1
-  println("18:" + from(1).indexOf(List(4,5,6)))            // 3
+  println("17:" + List(1,2,3,4).indexOfSlice(from(1)))          // -1
+  println("18:" + from(1).indexOfSlice(List(4,5,6)))            // 3
 }
 
diff --git a/test/files/run/t1368.scala b/test/files/run/t1368.scala
new file mode 100644
index 0000000..c9b2297
--- /dev/null
+++ b/test/files/run/t1368.scala
@@ -0,0 +1,9 @@
+object Test extends Application {
+  trait Happy { val status = "happy" }
+  trait Sad { val status = "sad" }
+
+  def go1 = (new AnyRef with Happy with Sad { override val status = "happysad" }).status
+  def go2 = (new AnyRef with Happy with Sad { val blurp = "happysad" ; override val status = blurp }).status
+  def go3 = (new AnyRef with Happy with Sad { override val status = blurp ; val blurp = "happysad" }).status
+}
+
diff --git a/test/files/run/t1500.check b/test/files/run/t1500.check
index b4e94e9..1032649 100644
--- a/test/files/run/t1500.check
+++ b/test/files/run/t1500.check
@@ -1,3 +1,3 @@
 defined class posingAs
-resolve: [A,B](A @posingAs[B])B
+resolve: [A,B](x: A @posingAs[B])B
 x: Any = 7
diff --git a/test/files/run/t1500.scala b/test/files/run/t1500.scala
index dd39c64..c312a9a 100644
--- a/test/files/run/t1500.scala
+++ b/test/files/run/t1500.scala
@@ -18,7 +18,9 @@ object Test {
   
   def main(args: Array[String]) = {
     
-    val tool = new Interpreter(new Settings())
+    val settings = new Settings()
+    settings.classpath.value = System.getProperty("java.class.path")
+    val tool = new Interpreter(settings)
     val global = tool.compiler
 
     import global._
@@ -29,7 +31,7 @@ object Test {
       /** Check annotations to decide whether tpe1 <:< tpe2 */
       def annotationsConform(tpe1: Type, tpe2: Type): Boolean = {
 
-        tpe1.attributes.forall(a1 => tpe2.attributes.forall(a2 => a1.atp <:< a2.atp))
+        tpe1.annotations.forall(a1 => tpe2.annotations.forall(a2 => a1.atp <:< a2.atp))
 
       }
     }
diff --git a/test/files/run/t1501.check b/test/files/run/t1501.check
index 7ec1495..f0fa911 100644
--- a/test/files/run/t1501.check
+++ b/test/files/run/t1501.check
@@ -1,3 +1,3 @@
 defined class xyz
-loopWhile: [T](=> Boolean)(=> Unit @xyz[T])Unit @xyz[T]
+loopWhile: [T](cond: => Boolean)(body: => Unit @xyz[T])Unit @xyz[T]
 test: ()Unit @xyz[Int]
diff --git a/test/files/run/t1501.scala b/test/files/run/t1501.scala
index 887f47f..05e4da8 100644
--- a/test/files/run/t1501.scala
+++ b/test/files/run/t1501.scala
@@ -28,8 +28,9 @@ object Test {
   </code>.text
   
   def main(args: Array[String]) = {
-    
-    val tool = new Interpreter(new Settings())
+    val settings = new Settings()
+    settings.classpath.value = System.getProperty("java.class.path")
+    val tool = new Interpreter(settings)
     val global = tool.compiler
 
     import global._
@@ -40,7 +41,7 @@ object Test {
       /** Check annotations to decide whether tpe1 <:< tpe2 */
       def annotationsConform(tpe1: Type, tpe2: Type): Boolean = {
 
-        tpe1.attributes.forall(a1 => tpe2.attributes.forall(a2 => a1.atp <:< a2.atp))
+        tpe1.annotations.forall(a1 => tpe2.annotations.forall(a2 => a1.atp <:< a2.atp))
 
       }
     }
diff --git a/test/files/run/t1505.scala b/test/files/run/t1505.scala
index 25c1a91..fdcd4f3 100644
--- a/test/files/run/t1505.scala
+++ b/test/files/run/t1505.scala
@@ -11,15 +11,9 @@ object R extends Enumeration {
 }
 
 object Test extends Application {
-  assert(Some(P(0)) == P.valueOf("A"))
-  assert(Some(P.C) == P.valueOf("C"))
-  assert(None == P.valueOf("Q"))
+  assert(P(0) == P.withName("A"))
+  assert(P.C == P.withName("C"))
 
-  assert(Some(Q(0)) == Q.valueOf("A"))
-  assert(Some(Q.C) == Q.valueOf("C"))
-  assert(None == Q.valueOf("Q"))
-
-  assert(None == R.valueOf("A"))
-  assert(None == R.valueOf("C"))
-  assert(None == R.valueOf("Q"))
+  assert(Q(0) == Q.withName("A"))
+  assert(Q.C == Q.withName("C"))
 }
diff --git a/test/files/run/t1524.check b/test/files/run/t1524.check
new file mode 100644
index 0000000..e79c5e8
--- /dev/null
+++ b/test/files/run/t1524.check
@@ -0,0 +1 @@
+initial
diff --git a/test/files/run/t1524.scala b/test/files/run/t1524.scala
new file mode 100644
index 0000000..4f6c65d
--- /dev/null
+++ b/test/files/run/t1524.scala
@@ -0,0 +1,7 @@
+object Test extends Application {
+
+  val buf = new scala.collection.mutable.ArrayBuffer[String] { override val initialSize = 0 }
+  buf += "initial"
+  buf += "second"
+  println(buf.head)
+}
diff --git a/test/files/run/t153.check b/test/files/run/t153.check
new file mode 100644
index 0000000..648a6de
--- /dev/null
+++ b/test/files/run/t153.check
@@ -0,0 +1 @@
+Stream(262144, 131072, 65536, 32768, 16384, 8192, 4096, 2048, 1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1)
diff --git a/test/files/run/t153.scala b/test/files/run/t153.scala
new file mode 100644
index 0000000..359e404
--- /dev/null
+++ b/test/files/run/t153.scala
@@ -0,0 +1,5 @@
+object Test extends Application {
+	def powers(x: Int) = if ((x&(x-1))==0) Some(x) else None
+	val res = (Stream.range(1, 500000) flatMap powers).reverse
+	println(res take 42 force)
+}
\ No newline at end of file
diff --git a/test/files/run/t1535.check b/test/files/run/t1535.check
index 93359aa..458a9ef 100644
--- a/test/files/run/t1535.check
+++ b/test/files/run/t1535.check
@@ -1,2 +1,2 @@
 42
-true
\ No newline at end of file
+true
diff --git a/test/files/run/t1535.scala b/test/files/run/t1535.scala
index 3633352..d0ae481 100644
--- a/test/files/run/t1535.scala
+++ b/test/files/run/t1535.scala
@@ -12,4 +12,4 @@ object Test extends Application {
     val n = new ClassDecl ()
     println (n.x)
     println (n.y)
-}
\ No newline at end of file
+}
diff --git a/test/files/run/t1618.scala b/test/files/run/t1618.scala
new file mode 100644
index 0000000..9f3ade6
--- /dev/null
+++ b/test/files/run/t1618.scala
@@ -0,0 +1,11 @@
+
+object Test extends Application {
+  import scala.tools.nsc.io._
+
+  val dir: VirtualDirectory = new VirtualDirectory("foo", None)
+  dir.subdirectoryNamed("foo")
+  assert(dir.lookupName("foo", true) != null)
+
+}
+
+
diff --git a/test/files/run/t1718.check b/test/files/run/t1718.check
new file mode 100644
index 0000000..27ba77d
--- /dev/null
+++ b/test/files/run/t1718.check
@@ -0,0 +1 @@
+true
diff --git a/test/files/run/t1718.scala b/test/files/run/t1718.scala
new file mode 100644
index 0000000..431e237
--- /dev/null
+++ b/test/files/run/t1718.scala
@@ -0,0 +1,10 @@
+object Test extends Application{
+  def matchesNull[T](mightBeNull: Array[T]): Boolean = mightBeNull match { 
+    case null => true
+    case x => false
+  }
+
+  val nullArray: Array[String] = null
+  println(matchesNull(nullArray)) 
+}
+
diff --git a/test/files/run/t1747.scala b/test/files/run/t1747.scala
new file mode 100644
index 0000000..f7f54ee
--- /dev/null
+++ b/test/files/run/t1747.scala
@@ -0,0 +1,6 @@
+object Foo extends Foo {
+  def f {}
+}
+class Foo
+
+object Test extends Application { Foo }
diff --git a/test/files/run/t1773.scala b/test/files/run/t1773.scala
new file mode 100644
index 0000000..04729df
--- /dev/null
+++ b/test/files/run/t1773.scala
@@ -0,0 +1,12 @@
+object Test extends Application
+{
+  val xs = List(
+    <a></a>,
+    <a/>,
+    <a>{ xml.NodeSeq.Empty }</a>,
+    <a>{""}</a>,
+    <a>{ if (true) "" else "I like turtles" }</a>
+  )
+  
+  for (x1 <- xs; x2 <- xs) assert (x1 xml_== x2)
+}
diff --git a/test/files/jvm5/bug680.check b/test/files/run/t1829.check
similarity index 100%
copy from test/files/jvm5/bug680.check
copy to test/files/run/t1829.check
diff --git a/test/files/run/t1829.scala b/test/files/run/t1829.scala
new file mode 100644
index 0000000..7c39d33
--- /dev/null
+++ b/test/files/run/t1829.scala
@@ -0,0 +1,12 @@
+object Test{
+  def main(args : Array[String]){
+    import scala.collection.immutable._  
+    assert(IntMap.empty == HashMap.empty);
+    assert(HashMap.empty == IntMap.empty);
+    assert(LongMap.empty == HashMap.empty);
+    assert(HashMap.empty == LongMap.empty);
+    assert(IntMap.empty == LongMap.empty);
+    assert(IntMap(1 -> 2) == HashMap(1 -> 2));
+    assert(LongMap(1L -> 2) == HashMap(1L -> 2));
+  }
+}
diff --git a/test/files/run/t1939.scala b/test/files/run/t1939.scala
new file mode 100644
index 0000000..7d62619
--- /dev/null
+++ b/test/files/run/t1939.scala
@@ -0,0 +1,34 @@
+class Module {}
+
+abstract class T {
+  type moduleType <: Module
+  def module: moduleType
+}
+
+final class T1(val module: Module) extends T {
+  type moduleType = Module
+}
+
+final class T2(_module: Module) extends T {
+  type moduleType = Module
+
+  def module = _module
+}
+
+object Test extends Application {
+
+  type mType = Module
+
+  type tType = T { type moduleType <: mType }
+  // type tType = T { type moduleType <: Module } // runs successfully
+  // type tType = T // runs successfully
+
+  def f(ts: List[tType]): Unit = {
+
+    for (t <- ts; m = t.module) {}
+    ts.map(t => t.module).foreach { _ => () }
+    // ts.map(t => (t : T).module).foreach { _ => () } // runs successfully
+  }
+
+  f(new T1(new Module) :: new T2(new Module) :: Nil)
+}
diff --git a/test/files/run/t2027.check b/test/files/run/t2027.check
new file mode 100644
index 0000000..d00491f
--- /dev/null
+++ b/test/files/run/t2027.check
@@ -0,0 +1 @@
+1
diff --git a/test/files/run/t2027.scala b/test/files/run/t2027.scala
new file mode 100644
index 0000000..ee9bd38
--- /dev/null
+++ b/test/files/run/t2027.scala
@@ -0,0 +1,6 @@
+object Test {
+  def main(args: Array[String]) {
+    def fibs: Stream[Int] = Stream.cons(0, Stream.cons(1, fibs.zip(fibs.tail).map(p => p._1 + p._2)))
+    println(fibs(2)) // stack overflow
+  }
+}
diff --git a/test/files/run/t2030.check b/test/files/run/t2030.check
new file mode 100644
index 0000000..5923569
--- /dev/null
+++ b/test/files/run/t2030.check
@@ -0,0 +1,2 @@
+true
+class scala.collection.immutable.TreeSet
\ No newline at end of file
diff --git a/test/files/run/t2030.scala b/test/files/run/t2030.scala
new file mode 100644
index 0000000..251ae2c
--- /dev/null
+++ b/test/files/run/t2030.scala
@@ -0,0 +1,8 @@
+import scala.collection.immutable._
+
+object Test extends Application {
+  val res0 = TreeSet(1, 2, 3, 4, 5, 6)
+  val res1 = res0.map(x => x)
+  println(res0.toList == res1.toList)
+  println(res1.getClass)
+}
diff --git a/test/files/run/t2074_2.check b/test/files/run/t2074_2.check
new file mode 100644
index 0000000..e4fc89b
--- /dev/null
+++ b/test/files/run/t2074_2.check
@@ -0,0 +1,3 @@
+SeqView(1, 2, 3)
+SeqView(1, 2, 3)
+SeqViewZ(...)
diff --git a/test/files/run/t2074_2.scala b/test/files/run/t2074_2.scala
new file mode 100644
index 0000000..1f59e0b
--- /dev/null
+++ b/test/files/run/t2074_2.scala
@@ -0,0 +1,22 @@
+// replaced all occurrences of 'Vector' with 'IndexedSeq'
+import scala.collection.immutable.IndexedSeq
+import scala.collection.SeqView
+
+object Test {
+  val funWithCCE = List.range(1,11).view.patch(5, List(100,101), 2)
+
+  val v = new SeqView[Int, IndexedSeq[Int]] {
+    def underlying = IndexedSeq(1,2,3)
+    def apply(idx: Int) = underlying(idx)
+    def length = underlying.length
+    def iterator = underlying.iterator
+  }
+  val w = IndexedSeq(1, 2, 3).view
+  
+  def main(args: Array[String]): Unit = {
+    println(v)
+    println(w)
+    println(go)
+  }
+  def go = v zip v
+}
diff --git a/test/files/run/t2111.check b/test/files/run/t2111.check
new file mode 100644
index 0000000..0fc64f3
--- /dev/null
+++ b/test/files/run/t2111.check
@@ -0,0 +1,6 @@
+Red
+Green
+Blue
+Blue
+Green
+Red
diff --git a/test/files/run/t2111.scala b/test/files/run/t2111.scala
new file mode 100644
index 0000000..3c6c5b8
--- /dev/null
+++ b/test/files/run/t2111.scala
@@ -0,0 +1,20 @@
+
+object Test extends Application {
+
+  object Color extends Enumeration {
+    val Red, Green, Blue = Value
+  }
+
+  class MyColor extends Enumeration {
+    val Red, Green, Blue = Value
+  }
+
+  println(Color.Red)
+  println(Color.Green)
+  println(Color.Blue)
+  val col = new MyColor
+  println(col.Blue)
+  println(col.Green)
+  println(col.Red)
+
+}
diff --git a/test/files/run/t2127.scala b/test/files/run/t2127.scala
new file mode 100644
index 0000000..869d8a3
--- /dev/null
+++ b/test/files/run/t2127.scala
@@ -0,0 +1,32 @@
+// Seems to be fixed in trunk
+
+// As discussed here: http://www.nabble.com/Companion-object-constructor-visibility-td24342096.html
+
+//Simplified example:
+
+    class Test private (val value : Int)
+
+    abstract class Bar(val ctor : (Int) => Test)
+
+    object Test extends Bar(new Test(_)) { //<--- ILLEGAL ACCESS
+      def main(args: Array[String]){}
+    }
+
+//however the following is legal:
+/*
+    class Foo private (val value : Int)
+
+    abstract class Bar{
+
+        var ctor : (Int) => Foo
+
+    }
+
+    object Foo extends Bar{
+
+        ctor = new Foo(_) //<--- Legal access
+
+    }
+
+The constructor invocation of Bar is done within the scope of object Foo's constructor, and therefor the private constructor of Foo should be visible and accessible.
+*/
diff --git a/test/files/run/t2147.check b/test/files/run/t2147.check
new file mode 100644
index 0000000..47e3206
--- /dev/null
+++ b/test/files/run/t2147.check
@@ -0,0 +1,2 @@
+11
+11
diff --git a/test/files/run/t2147.scala b/test/files/run/t2147.scala
new file mode 100644
index 0000000..185e617
--- /dev/null
+++ b/test/files/run/t2147.scala
@@ -0,0 +1,8 @@
+object Test extends Application {
+  val s: Seq[Int] = Stream.from(1)
+  val res0 = s.map(a => 2).head
+  val res1 = Stream.from(1).flatMap(a => List(1)).head
+
+  println((for{a <- Stream.from(1); b <- 1 to 5; if a > 10} yield a).head)
+  println((for{a <- Stream.from(1); b <- 1 to a; if a > 10} yield a).head)
+}
diff --git a/test/files/run/t2176.check b/test/files/run/t2176.check
new file mode 100644
index 0000000..2298e8b
--- /dev/null
+++ b/test/files/run/t2176.check
@@ -0,0 +1 @@
+Stream(1)
diff --git a/test/files/run/t2176.scala b/test/files/run/t2176.scala
new file mode 100644
index 0000000..f8b0727
--- /dev/null
+++ b/test/files/run/t2176.scala
@@ -0,0 +1,4 @@
+object Test extends Application {
+  val res0 = Stream.cons(1, Stream.cons( { println("ouch"); 2 }, Stream.empty))
+  println(res0.take(1).force)
+}
diff --git a/test/files/run/t2177.check b/test/files/run/t2177.check
new file mode 100644
index 0000000..e56e15b
--- /dev/null
+++ b/test/files/run/t2177.check
@@ -0,0 +1 @@
+12345
diff --git a/test/files/run/t2177.scala b/test/files/run/t2177.scala
new file mode 100644
index 0000000..fd1a29d
--- /dev/null
+++ b/test/files/run/t2177.scala
@@ -0,0 +1,3 @@
+object Test extends Application {
+  println(Stream.from(1).take(5).mkString)
+}
diff --git a/test/files/run/t2212.check b/test/files/run/t2212.check
new file mode 100644
index 0000000..302bd0b
--- /dev/null
+++ b/test/files/run/t2212.check
@@ -0,0 +1,3 @@
+LinkedList(1)
+LinkedList(1)
+true
diff --git a/test/files/run/t2212.scala b/test/files/run/t2212.scala
new file mode 100644
index 0000000..b9c0cd7
--- /dev/null
+++ b/test/files/run/t2212.scala
@@ -0,0 +1,10 @@
+object Test {
+  def main(args: Array[String]) {
+    import collection.mutable._
+    val x4 = LinkedList[Int](1)
+    println(x4)
+    val y4 = LinkedList[Int](1)
+    println(y4)
+    println(x4 equals y4) // or (y4 equals x4)
+  }
+}
diff --git a/test/files/run/t2236.scala b/test/files/run/t2236.scala
new file mode 100644
index 0000000..8e2b390
--- /dev/null
+++ b/test/files/run/t2236.scala
@@ -0,0 +1,17 @@
+class T[A](implicit val m:Manifest[A])
+class Foo
+class Bar extends T[Foo]
+object Test extends Application {
+  new Bar
+}
+
+object EvidenceTest {
+  trait E[T]
+  trait A[T] { implicit val e: E[T] = null }
+  class B[T : E] extends A[T] { override val e = null }
+
+  def f[T] {
+    implicit val e: E[T] = null
+    new B[T]{}
+  }
+}
diff --git a/test/files/run/t2255.check b/test/files/run/t2255.check
new file mode 100644
index 0000000..dda391b
--- /dev/null
+++ b/test/files/run/t2255.check
@@ -0,0 +1 @@
+List(1, 2, 3, 1, 2, 3)
diff --git a/test/files/run/t2255.scala b/test/files/run/t2255.scala
new file mode 100644
index 0000000..be800ad
--- /dev/null
+++ b/test/files/run/t2255.scala
@@ -0,0 +1,3 @@
+object Test extends Application {
+  println(Stream.continually(Stream(1, 2, 3)).flatten.take(6).toList)
+}
diff --git a/test/files/run/t2316.scala b/test/files/run/t2316.scala
new file mode 100644
index 0000000..a3d5bf8
--- /dev/null
+++ b/test/files/run/t2316.scala
@@ -0,0 +1,32 @@
+case class T1(source: String)
+
+object T1 {
+  implicit def T1FromT2(implicit t2: T2) = new T1(t2.source)
+}
+
+case class T2(source: String)
+
+object A {
+  def requireT1(implicit t1: T1) = t1
+
+  object B1 {
+    implicit val t2_b1 = new T2("from B1")
+    requireT1
+  }
+
+  object B2 {
+    def t1 = {
+      implicit val t2_b2 = new T2("from B2")
+      // Implicits.cacheResult returns T1.T1FromT2(t2_b1) here, which is bogus. Even though T1.T1FromT2 was found
+      // outside of the scope of A.B1, this implicit expression should _not_ be cached, as it includes the bound
+      // variable t2_b1 from this scope.
+      requireT1
+    }
+  }
+}
+
+object Test {
+  def main(args: Array[String]) {
+    assert(A.B2.t1.source == "from B2")
+  }
+}
\ No newline at end of file
diff --git a/test/files/run/t2417.check b/test/files/run/t2417.check
new file mode 100644
index 0000000..36c954b
--- /dev/null
+++ b/test/files/run/t2417.check
@@ -0,0 +1,12 @@
+testing small Map that doesn't promote to HashMap...
+
+testing single-threaded HashMap use...
+
+testing HashMap.size from multiple threads...
+
+testing small Set that doesn't promote to HashSet...
+
+testing single-threaded HashSet use...
+
+testing HashSet.size from multiple threads...
+
diff --git a/test/files/run/t2417.scala b/test/files/run/t2417.scala
new file mode 100644
index 0000000..aeb61a7
--- /dev/null
+++ b/test/files/run/t2417.scala
@@ -0,0 +1,77 @@
+// #2417
+object Test {
+  
+  def parallel(numThreads: Int)(block: => Unit) {
+    var failure: Throwable = null
+    val threads = Array.fromFunction(i => new Thread {
+      override def run {
+        try {
+          block
+          } catch {
+            case x => failure = x
+          }
+        }
+      })(numThreads)
+      for (t <- threads) t.start
+      for (t <- threads) t.join
+      if (failure != null) println("FAILURE: " + failure)
+    }
+  
+    def testSet(initialSize: Int, numThreads: Int, passes: Int) {
+      val orig = Set.empty ++ (1 to initialSize)
+      parallel(numThreads) {
+        for (pass <- 0 until passes) {
+          var s = orig
+          for (e <- (initialSize to 1 by -1)) {
+            s -= e
+            val obs = s.size
+            if (obs != e - 1) {
+              throw new Exception("removed e=" + e + ", size was " + obs + ", s=" + s)
+            }
+          }
+        }
+      }
+    }
+  
+    def testMap(initialSize: Int, numThreads: Int, passes: Int) {
+      val orig = Map.empty ++ ((1 to initialSize) map ((_,"v")))
+      parallel(numThreads) {
+        for (pass <- 0 until passes) {
+          var m = orig
+          for (e <- (initialSize to 1 by -1)) {
+            m -= e
+            val obs = m.size
+            if (obs != e - 1) {
+              throw new Exception("removed e=" + e + ", size was " + obs + ", m=" + m)
+            }
+          }
+        }
+      }
+    }
+  
+    def main(args: Array[String]) {
+      println("testing small Map that doesn't promote to HashMap...")
+      testMap(4, 2, 1000000)
+      println()
+  
+      println("testing single-threaded HashMap use...")
+      testMap(5, 1, 1000000)
+      println()
+  
+      println("testing HashMap.size from multiple threads...")
+      testMap(5, 2, 1000000)
+      println()
+  
+      println("testing small Set that doesn't promote to HashSet...")
+      testSet(4, 2, 1000000)
+      println()
+  
+      println("testing single-threaded HashSet use...")
+      testSet(5, 1, 1000000)
+      println()
+  
+      println("testing HashSet.size from multiple threads...")
+      testSet(5, 2, 1000000)
+      println()
+    }
+}
\ No newline at end of file
diff --git a/test/files/run/t2446.check b/test/files/run/t2446.check
new file mode 100644
index 0000000..00750ed
--- /dev/null
+++ b/test/files/run/t2446.check
@@ -0,0 +1 @@
+3
diff --git a/test/files/run/t2446.scala b/test/files/run/t2446.scala
new file mode 100644
index 0000000..29494ab
--- /dev/null
+++ b/test/files/run/t2446.scala
@@ -0,0 +1,9 @@
+object Test {
+  def main(args : Array[String]) : Unit = {
+    val arr = new Array[Int](10000)
+    arr(5000) = 1
+    arr (9000) = 2
+    val sum = arr.reduceRight(_ + _)
+    println(sum)
+  }
+}
diff --git a/test/files/run/t2503.scala b/test/files/run/t2503.scala
new file mode 100644
index 0000000..353a1dc
--- /dev/null
+++ b/test/files/run/t2503.scala
@@ -0,0 +1,19 @@
+import scala.collection.mutable._
+
+trait SB[A] extends Buffer[A] {
+
+  import collection.Traversable
+
+  abstract override def insertAll(n: Int, iter: Traversable[A]): Unit = synchronized {
+     super.insertAll(n, iter)
+  }
+
+  abstract override def update(n: Int, newelem: A): Unit = synchronized {
+    super.update(n, newelem)
+  }
+}
+
+object Test extends Application {
+  new ArrayBuffer[Int] with SB[Int]
+}
+
diff --git a/test/files/run/t2524.scala b/test/files/run/t2524.scala
new file mode 100644
index 0000000..552663e
--- /dev/null
+++ b/test/files/run/t2524.scala
@@ -0,0 +1,10 @@
+object Test {
+  def main(args: Array[String]) {
+    val m = new collection.mutable.HashMap[String, String] {
+      override def initialSize = 0
+    }
+    m.toString
+    m("key") = "value"
+    assert(m("key") == "value")
+  }
+}
diff --git a/test/files/run/t2526.scala b/test/files/run/t2526.scala
new file mode 100644
index 0000000..d371855
--- /dev/null
+++ b/test/files/run/t2526.scala
@@ -0,0 +1,53 @@
+/**
+ * Checks that various foreach methods overridden in mutable.HashMap as part of ticket #2526
+ * still work correctly.
+ */
+object Test {
+  import collection._
+  
+  def main(args: Array[String]) {
+    val m = new mutable.HashMap[String, String]
+    
+    /* Use non hash-based structure for verification */
+    val keys = List("a", "b", "c", "d", "e")
+    val valueSuffix = "value"
+    val values = keys.map(_ + valueSuffix)
+    val entries = keys.zip(values)
+    
+    for (k <- keys) m(k) = k + valueSuffix
+    
+    assertForeach(keys, m.keySet.iterator)
+    assertForeach(keys, m.keysIterator)
+    assertForeach(keys, m.keySet)
+
+    assertForeach(values, m.values.iterator)
+    assertForeach(values, m.valuesIterator)
+
+    assertForeach(entries, m)
+  }
+  
+  /* Checks foreach of `actual` goes over all the elements in `expected` */
+  private def assertForeach[E](expected: Traversable[E], actual: Iterator[E]): Unit = {
+    val notYetFound = new mutable.ArrayBuffer[E]() ++= expected
+    actual.foreach { e =>
+      assert(notYetFound.contains(e))
+      notYetFound -= e
+    }
+    assert(notYetFound.size == 0, "mutable.HashMap.foreach should have iterated over: " + notYetFound)
+  }
+  
+  /* 
+   * Checks foreach of `actual` goes over all the elements in `expected`
+   * We duplicate the method above because there is no common inteface between Traversable and
+   * Iterator and we want to avoid converting between collections to ensure that we test what
+   * we mean to test. 
+   */
+  private def assertForeach[E](expected: Traversable[E], actual: Traversable[E]): Unit = {
+    val notYetFound = new mutable.ArrayBuffer[E]() ++= expected
+    actual.foreach { e =>
+      assert(notYetFound.contains(e))
+      notYetFound -= e
+    }
+    assert(notYetFound.size == 0, "mutable.HashMap.foreach should have iterated over: " + notYetFound)
+  }
+}
diff --git a/test/files/run/t2544.check b/test/files/run/t2544.check
new file mode 100644
index 0000000..716b146
--- /dev/null
+++ b/test/files/run/t2544.check
@@ -0,0 +1,10 @@
+2
+2
+3
+3
+-2
+-2
+1
+1
+0
+0
diff --git a/test/files/run/t2544.scala b/test/files/run/t2544.scala
new file mode 100644
index 0000000..7e7cfeb
--- /dev/null
+++ b/test/files/run/t2544.scala
@@ -0,0 +1,19 @@
+object Test {
+  object Foo extends Seq[Int] {
+    def apply(i: Int) = i
+    def length = 4
+    def iterator = Iterator(0,1,2,3,4)
+  }
+  def main(args: Array[String]) = {
+    println(Foo indexWhere(_ >= 2,1))
+    println(Foo.toList indexWhere(_ >= 2,1))
+    println(Foo segmentLength(_ <= 3,1))
+    println(Foo.toList segmentLength(_ <= 3,1))
+    println(Foo lengthCompare 7)
+    println(Foo.toList lengthCompare 7)
+    println(Foo lengthCompare 2)
+    println(Foo.toList lengthCompare 2)
+    println(Foo lengthCompare 5)
+    println(Foo.toList lengthCompare 5)
+  }
+}
\ No newline at end of file
diff --git a/test/files/jvm5/bug680.check b/test/files/run/t2594_tcpoly.check
similarity index 100%
copy from test/files/jvm5/bug680.check
copy to test/files/run/t2594_tcpoly.check
diff --git a/test/files/run/t2594_tcpoly.scala b/test/files/run/t2594_tcpoly.scala
new file mode 100644
index 0000000..e759ca8
--- /dev/null
+++ b/test/files/run/t2594_tcpoly.scala
@@ -0,0 +1,18 @@
+trait Monad[M[_]] {
+  def foo[A](a: M[A]): M[A]
+}
+
+class Bar[A, B]
+class Bar1[A] { type And[B] = Bar[A, B] }
+
+object Test {
+  // the combination of partial applications and anonymous class is essential to reproduce the bug
+  // problem: missing bridge method
+  //  --> abstractmethoderror `Main$$anon$1.foo(Ljava/lang/Object;)Ljava/lang/Object;`
+  // the anonymous class only gets `public Bar foo(Bar a)`
+  def BarMonad[X] = new Monad[Bar1[X]#And] {
+    def foo[A](a: Bar[X, A]) = a
+  }
+
+  def main(as: Array[String]) { BarMonad[Int] foo (new Bar[Int, Int]) }
+}
\ No newline at end of file
diff --git a/test/files/run/t2754.scala b/test/files/run/t2754.scala
new file mode 100644
index 0000000..aeb5259
--- /dev/null
+++ b/test/files/run/t2754.scala
@@ -0,0 +1,39 @@
+object Test {
+    def main(args: Array[String]) {
+        val v: FooBarPlus[Int] = new FooBarPlusImpl()
+        v.foo += 10
+    }
+}
+
+trait Foo[P] {
+    def foo: P
+}
+
+trait FooBar[P] extends Foo[P] {
+    def bar: P
+}
+
+trait FooBarPlus[P] extends FooBar[P] {
+    override def foo: P
+    override def bar: P
+
+    def foo_=(x: P)
+    def bar_=(x: P)
+}
+
+class FooImpl extends Foo[Int] {
+    def foo = 1
+}
+
+class FooBarImpl extends FooImpl with FooBar[Int] {
+    protected var f = 0
+    protected var b = 0
+
+    override def foo = f
+    def bar = b
+}
+
+class FooBarPlusImpl extends FooBarImpl with FooBarPlus[Int] {
+    def foo_=(x: Int) { f = x }
+    def bar_=(x: Int) { b = x }
+}
diff --git a/test/files/run/t2849.scala b/test/files/run/t2849.scala
new file mode 100644
index 0000000..0588e5e
--- /dev/null
+++ b/test/files/run/t2849.scala
@@ -0,0 +1,46 @@
+
+
+
+import scala.collection.immutable.SortedSet
+import scala.collection.immutable.TreeSet
+
+
+
+object Test {
+  
+  def main(args: Array[String]) {
+    ticketExample
+    similarExample
+  }
+  
+  def ticketExample {
+    var big = 100000
+    
+    var aSortedSet: SortedSet[Int] = TreeSet(big)
+    
+    for (i <- 1 until 10000) {
+      aSortedSet = (aSortedSet - big) ++ (TreeSet(i, big - 1))
+      big = big - 1
+      if (i % 1000 == 0) {
+        aSortedSet.until(i)
+      }
+    }
+  }
+  
+  def similarExample {
+    var big = 100
+
+    var aSortedSet: SortedSet[Int] = TreeSet(big)
+
+    for (i <- 1 until 10000) {
+      aSortedSet = (aSortedSet - big) ++ (TreeSet(i, big - 1)) + big
+      big = big - 1
+      if (i % 1000 == 0) {
+        aSortedSet.until(i)
+      }
+    }
+  }
+  
+}
+
+
diff --git a/test/pending/jvm5/t1464.check b/test/files/run/t2857.check
similarity index 100%
rename from test/pending/jvm5/t1464.check
rename to test/files/run/t2857.check
diff --git a/test/files/run/t2857.scala b/test/files/run/t2857.scala
new file mode 100644
index 0000000..bd0d6fd
--- /dev/null
+++ b/test/files/run/t2857.scala
@@ -0,0 +1,9 @@
+object Test extends Application {
+  import collection.mutable._
+  val m = new HashMap[Int, Set[String]] with MultiMap[Int, String]
+  m.addBinding(6, "Foo")
+  m.removeBinding(6, "Foo")
+  println(m.contains(6))
+}
+
+
diff --git a/test/files/run/t2867.scala b/test/files/run/t2867.scala
new file mode 100644
index 0000000..0d30f95
--- /dev/null
+++ b/test/files/run/t2867.scala
@@ -0,0 +1,15 @@
+object Test {
+  case class A(l: List[_]*) 
+  
+  def main(args: Array[String]): Unit = {
+    /** Kind of sneaking a slightly different test in here as well as
+     *  testing 2867.  How subversive.
+     */
+    val xs1 = List(1, 2, 3)
+    val xs2 = List(1.0, 2.0, 3.0)
+    val xs3 = List[Any](1.0f, 2.0f, 3.0f)
+    val xs4 = List[Byte](1, 2, 3)
+    
+    assert(A(List(xs1, xs2)) == A(List(xs3, xs4)))
+  }
+}
diff --git a/test/files/run/t2886.check b/test/files/run/t2886.check
new file mode 100644
index 0000000..39ee46a
--- /dev/null
+++ b/test/files/run/t2886.check
@@ -0,0 +1 @@
+Function(List(LocalValue(NoSymbol,x,PrefixedType(SingleType(ThisType(Class(scala)),Field(scala.Predef,PrefixedType(ThisType(Class(scala)),Class(scala.Predef)))),TypeField(scala.Predef.String,PrefixedType(ThisType(Class(java.lang)),Class(java.lang.String)))))),Block(List(ValDef(LocalValue(NoSymbol,x$1,NoType),Ident(LocalValue(NoSymbol,x,PrefixedType(SingleType(ThisType(Class(scala)),Field(scala.Predef,PrefixedType(ThisType(Class(scala)),Class(scala.Predef)))),TypeField(scala.Predef.String [...]
\ No newline at end of file
diff --git a/test/files/run/t2886.scala b/test/files/run/t2886.scala
new file mode 100644
index 0000000..eb392f0
--- /dev/null
+++ b/test/files/run/t2886.scala
@@ -0,0 +1,7 @@
+object Test {
+  def test(name: String, address: String) = null
+  def main(args: Array[String]) = {
+    val tree = scala.reflect.Code.lift((x:String) => test(address=x,name=x)).tree
+    println(tree)
+  }
+}
diff --git a/test/files/run/t3026.check b/test/files/run/t3026.check
new file mode 100644
index 0000000..8c29b61
--- /dev/null
+++ b/test/files/run/t3026.check
@@ -0,0 +1,2 @@
+RED
+YELLOW
diff --git a/test/files/run/t3026.scala b/test/files/run/t3026.scala
new file mode 100644
index 0000000..0231c7b
--- /dev/null
+++ b/test/files/run/t3026.scala
@@ -0,0 +1,8 @@
+object Test {
+  abstract class Colour
+  case object RED extends Colour
+  case object YELLOW extends Colour
+  val items = Array(RED, YELLOW)
+  
+  def main(args: Array[String]): Unit = items foreach println
+}
diff --git a/test/files/run/t3112.check b/test/files/run/t3112.check
new file mode 100644
index 0000000..a95644c
--- /dev/null
+++ b/test/files/run/t3112.check
@@ -0,0 +1,4 @@
+Vector()
+Vector()
+Vector()
+Vector()
\ No newline at end of file
diff --git a/test/files/run/t3112.scala b/test/files/run/t3112.scala
new file mode 100644
index 0000000..88677fa
--- /dev/null
+++ b/test/files/run/t3112.scala
@@ -0,0 +1,11 @@
+// #3112
+object Test {
+
+  def main(args: Array[String]): Unit = {
+    println((Vector() ++ (0 until 32)) take 0) // works
+    println((Vector() ++ (0 until 33)) take 0) // error
+    println((Vector() ++ (0 until 32)) takeRight 0) // works
+    println((Vector() ++ (0 until 33)) takeRight 0) // error
+  }
+  
+}
\ No newline at end of file
diff --git a/test/files/run/t3158.check b/test/files/run/t3158.check
new file mode 100644
index 0000000..ab1cb28
--- /dev/null
+++ b/test/files/run/t3158.check
@@ -0,0 +1 @@
+Array(<function1>)
diff --git a/test/files/run/t3158.scala b/test/files/run/t3158.scala
new file mode 100644
index 0000000..2261b5c
--- /dev/null
+++ b/test/files/run/t3158.scala
@@ -0,0 +1,9 @@
+object Test {
+  def main(args: Array[String]) {
+    println(args.map(_ => foo _).deep) 
+  }
+
+  def foo(xs: String*) {
+    println(xs)
+  }
+}
diff --git a/test/files/jvm5/t1464.check b/test/files/run/t3186.check
similarity index 100%
copy from test/files/jvm5/t1464.check
copy to test/files/run/t3186.check
diff --git a/test/files/run/t3186.scala b/test/files/run/t3186.scala
new file mode 100644
index 0000000..2534d4a
--- /dev/null
+++ b/test/files/run/t3186.scala
@@ -0,0 +1,7 @@
+object Dist1 extends Enumeration { val Mile, Foot, Inch = Value }
+
+object Dist2 extends Enumeration { val Kilometer, Millimeter, Parsec = Value }
+
+object Test extends Application {
+  println(Dist1.Mile == Dist2.Kilometer)
+}
diff --git a/test/files/run/t3241.check b/test/files/run/t3241.check
new file mode 100644
index 0000000..348ebd9
--- /dev/null
+++ b/test/files/run/t3241.check
@@ -0,0 +1 @@
+done
\ No newline at end of file
diff --git a/test/files/run/t3241.scala b/test/files/run/t3241.scala
new file mode 100644
index 0000000..40097a0
--- /dev/null
+++ b/test/files/run/t3241.scala
@@ -0,0 +1,23 @@
+object Test {
+
+  def main(args : Array[String]) : Unit = {
+    recurse(Map(1->1, 2->2, 3->3, 4->4, 5->5, 6->6, 7->7))
+    recurse(Set(1,2,3,4,5,6,7))
+    println("done")
+  }
+
+  def recurse(map: collection.immutable.Map[Int, Int]): Unit = {
+    if (!map.isEmpty) {
+      val x = map.keys.head
+      recurse(map - x)
+    }
+  }
+
+  def recurse(set: collection.immutable.Set[Int]): Unit = {
+    if (!set.isEmpty) {
+      val x = set.toStream.head
+      recurse(set - x)
+    }
+  }
+
+}
diff --git a/test/files/run/t3242.check b/test/files/run/t3242.check
new file mode 100644
index 0000000..a145f6d
--- /dev/null
+++ b/test/files/run/t3242.check
@@ -0,0 +1,18 @@
+ append [num: 200] vec
+ remove [num: 200] vec
+ append [num: 400] vec
+ remove [num: 400] vec
+ append [num: 600] vec
+ remove [num: 600] vec
+ append [num: 800] vec
+ remove [num: 800] vec
+>> comparison done, num: 200
+ append [num: 2000] vec
+ remove [num: 2000] vec
+ append [num: 4000] vec
+ remove [num: 4000] vec
+ append [num: 6000] vec
+ remove [num: 6000] vec
+ append [num: 8000] vec
+ remove [num: 8000] vec
+>> comparison done, num: 2000
diff --git a/test/files/run/t3242.scala b/test/files/run/t3242.scala
new file mode 100644
index 0000000..f8defaa
--- /dev/null
+++ b/test/files/run/t3242.scala
@@ -0,0 +1,49 @@
+object Test {
+
+ def benchmarkA(num: Int) {
+
+   type A = Int
+
+   def updateM[M[_]](ms: M[A], update: (M[A], A)=>M[A]): M[A] = {
+     var is = ms
+     for (i <- 0 until num) is = update(is, i)
+     is
+   }
+
+   //
+   def vectorAppend: Vector[A] = updateM[Vector](Vector(), (as, a)=>{
+     val v = (as :+ a)
+     //println("==>append:    i: "+i1+", v: "+v)
+     v
+   })
+   // this will crash, Vector bug!
+   def vectorRemove(vec: Vector[A]): Vector[A] = updateM[Vector](vec, (as, a)=>{
+     val v = (as filterNot{ _ == a})
+     //val v = (is filter{ _ != i})
+     //println("==>remove:    i: "+a)
+     v
+   })
+
+   val ct = vectorAppend
+   println(" append [num: "+num+"] vec")
+   vectorRemove(ct)
+   println(" remove [num: "+num+"] vec")
+ } // BenchmarkA
+
+ def comparison(num: Int): Unit = {
+   for (i <- 1 until 5) benchmarkA(num*i)
+   println(">> comparison done, num: "+num);
+ }
+
+ def main(args: Array[String]): Unit = {
+   try {
+     //createBenchmarkA(23).testRun
+
+     comparison(200) // OK
+     comparison(2000) // this will crach
+
+   } catch {
+     case e: Exception => e.printStackTrace()
+   }
+ }
+}
diff --git a/test/files/run/t3242b.scala b/test/files/run/t3242b.scala
new file mode 100644
index 0000000..7a296aa
--- /dev/null
+++ b/test/files/run/t3242b.scala
@@ -0,0 +1,17 @@
+import scala.collection.immutable._
+
+object Test {
+
+  def test(n: Int) = {
+    var vb = new VectorBuilder[Int]
+    for (i <- 0 until n)
+      vb += i
+    val v = vb.result
+    assert(v == (0 until n), "not same as (0 until " + n + "): " + v)
+  }
+
+  def main(args: Array[String]): Unit = {
+    for (i <- 0 until 2000)
+      test(i)
+  }
+}
diff --git a/test/files/run/t3361.scala b/test/files/run/t3361.scala
new file mode 100644
index 0000000..3e6fc30
--- /dev/null
+++ b/test/files/run/t3361.scala
@@ -0,0 +1,100 @@
+object Test extends Application {
+  import scala.collection.mutable.DoubleLinkedList
+
+  empty
+  builder_1
+  builder_2
+  chaining_1
+  chaining_2
+  insert_1
+  insert_2
+  append_1
+  append_2
+
+  def empty {
+    val none = DoubleLinkedList()
+    require(none.size == 0)
+    none.foreach( _ => require(false))
+  }
+
+  def builder_1 {
+    val ten = DoubleLinkedList(1 to 10: _*)
+    require(10 == ten.size)
+  }
+
+  def builder_2 {
+    val ten = DoubleLinkedList(1 to 10: _*)
+    require((ten.size*(ten.size+1))/2 == ten.reduceLeft(_ + _))
+  }
+
+  def chaining_1 {
+    val ten = DoubleLinkedList(1 to 10: _*)
+    require(ten.reverse == DoubleLinkedList((1 to 10).reverse: _*))
+  }
+
+  def chaining_2 {
+    val ten = DoubleLinkedList(1 to 10: _*)
+    require(ten == ten.reverse.reverse)
+  }
+
+  def insert_1 {
+    val ten = DoubleLinkedList(1 to 10: _*)
+    ten.insert(DoubleLinkedList(11)) match {
+      case _: Unit => require(true)
+      case _ => require(false)
+    }
+    // Post-insert size test
+    require(11 == ten.size)
+    // Post-insert data test
+    require((ten.size*(ten.size+1))/2 == ten.reduceLeft(_ + _))
+    // Post-insert chaining test
+    require(ten == ten.reverse.reverse)
+    // Post-insert position test
+    require(ten.last == 11)
+  }
+
+  def insert_2 {
+    val ten = DoubleLinkedList(1 to 10: _*)
+    try {
+      DoubleLinkedList().insert(ten)
+    } catch {
+      case _: IllegalArgumentException => require(true)
+      case _ => require(false)
+    }
+    val zero = DoubleLinkedList(0)
+    zero.insert(ten)
+    require(zero.size == 11)
+    require(zero.head == 0)
+    require(zero.last == 10)
+  }
+
+  def append_1 {
+    val ten = DoubleLinkedList(1 to 10: _*)
+    val eleven = ten.append(DoubleLinkedList(11))
+    // Post-append equality test
+    require(ten == eleven)
+    // Post-append size test
+    require(11 == ten.size)
+    // Post-append data test
+    require((ten.size*(ten.size+1))/2 == ten.reduceLeft(_ + _))
+    // Post-append chaining test
+    require(ten == ten.reverse.reverse)
+    // Post-append position test
+    require(ten.last == 11)
+  }
+
+  def append_2 {
+    val ten = DoubleLinkedList(1 to 10: _*)
+    try {
+      DoubleLinkedList().append(ten)
+    } catch {
+      case _: IllegalArgumentException => require(true)
+      case _ => require(false)
+    }
+    val zero = DoubleLinkedList(0)
+    zero.append(ten)
+    require(zero.size == 11)
+    require(zero.head == 0)
+    require(zero.last == 10)
+  }
+}
diff --git a/test/files/run/t3493.scala b/test/files/run/t3493.scala
new file mode 100644
index 0000000..b0b7589
--- /dev/null
+++ b/test/files/run/t3493.scala
@@ -0,0 +1,15 @@
+
+
+
+
+object Test {
+  
+  def main(args: Array[String]) {
+    import scala.collection.immutable._
+    val x = TreeSet("a", "b", "c", "d")
+    val x2 = x + "e"
+    assert(x2.toString == "TreeSet(a, b, c, d, e)")
+    assert(x2.toString == runtime.ScalaRunTime.stringOf(x2).trim)
+  }
+  
+}
diff --git a/test/files/run/t3496.scala b/test/files/run/t3496.scala
new file mode 100644
index 0000000..80a4e6b
--- /dev/null
+++ b/test/files/run/t3496.scala
@@ -0,0 +1,15 @@
+
+
+
+
+// ticket #3496
+object Test {
+  
+  def main(args: Array[String]) {
+    val s = Stream.from(1)
+    s.take(5)
+    s.drop(5)
+    s.splitAt(5)
+  }
+  
+}
diff --git a/test/files/run/t3502.scala b/test/files/run/t3502.scala
new file mode 100644
index 0000000..9492b2d
--- /dev/null
+++ b/test/files/run/t3502.scala
@@ -0,0 +1,24 @@
+
+
+
+
+
+// ticket #3502
+object Test {
+  
+  object GeneratePrimeFactorsLazy extends (Int => List[Int]) {
+    override def apply(n:Int) = {
+      val s = Stream.range(2, n / 2).filter(n % _ == 0)
+      //val s = for (i <- Stream.range(2, n / 2); if n % i == 0) yield i
+      s.headOption.map(x => x :: apply(n / x)).getOrElse(List(n))
+    }
+  }
+  
+  def main(args:Array[String]) {
+    // a prime number
+    //val num = 623456789
+    val num = 2796203
+    assert(GeneratePrimeFactorsLazy(num) == List(num))
+  }
+  
+}
diff --git a/test/files/run/t3508.scala b/test/files/run/t3508.scala
new file mode 100644
index 0000000..01d976b
--- /dev/null
+++ b/test/files/run/t3508.scala
@@ -0,0 +1,11 @@
+
+
+import collection.immutable._
+
+
+// ticket #3508
+object Test {
+  def main(args: Array[String]) {
+    assert(Stream.tabulate(123)(_ + 1).toList == List.tabulate(123)(_ + 1))
+  }
+}
diff --git a/test/files/run/t3580.scala b/test/files/run/t3580.scala
new file mode 100644
index 0000000..ac9f81a
--- /dev/null
+++ b/test/files/run/t3580.scala
@@ -0,0 +1,17 @@
+
+
+
+
+
+object Test {
+  
+  class Empty extends Traversable[Nothing] {
+    def foreach[U](f: Nothing => U) {}
+  }
+  
+  def main(args: Array[String]) {
+    val t = new Empty
+    t.toStream
+  }
+  
+}
diff --git a/test/files/run/t3603.scala b/test/files/run/t3603.scala
new file mode 100644
index 0000000..a0821a2
--- /dev/null
+++ b/test/files/run/t3603.scala
@@ -0,0 +1,18 @@
+
+
+
+object Test {
+  
+  def main(args: Array[String]) {
+    import collection.immutable._
+    
+    val intmap = IntMap(1 -> 1, 2 -> 2)
+    val intres = intmap.map { case (a, b) => (a, b.toString) }
+    assert(intres.isInstanceOf[IntMap[_]])
+    
+    val longmap = LongMap(1L -> 1, 2L -> 2)
+    val longres = longmap.map { case (a, b) => (a, b.toString) }
+    assert(longres.isInstanceOf[LongMap[_]])
+  }
+  
+}
diff --git a/test/files/run/t3645.scala b/test/files/run/t3645.scala
new file mode 100644
index 0000000..af25433
--- /dev/null
+++ b/test/files/run/t3645.scala
@@ -0,0 +1,6 @@
+object Test {
+  def main(args: Array[String]) {
+    val s = Stream.tabulate(5)(x => x+2)
+    assert( s.toList == List(2,3,4,5,6) )
+  }
+}
diff --git a/test/files/run/t3667.check b/test/files/run/t3667.check
new file mode 100644
index 0000000..01e79c3
--- /dev/null
+++ b/test/files/run/t3667.check
@@ -0,0 +1,3 @@
+1
+2
+3
diff --git a/test/files/run/t3667.scala b/test/files/run/t3667.scala
new file mode 100644
index 0000000..7bd0b4e
--- /dev/null
+++ b/test/files/run/t3667.scala
@@ -0,0 +1,53 @@
+object Test {
+  def main(args: Array[String]) {
+    val o1 = new Outer1
+    val o2 = new Outer2
+    val o3 = new Outer3
+
+    println(1)
+    ser(new o1.Inner(1))
+    o1.Inner // make sure the Inner$module field of the Outer1 instance is initialized!
+    ser(new o1.Inner(1))
+
+    println(2)
+    ser(new o2.Inner(1))
+    o2.Inner
+    ser(new o2.Inner(1))
+
+    println(3)
+    ser(new o3.Inner(1))
+    o3.Inner
+    ser(new o3.Inner(1))
+
+    foo
+  }
+
+  def foo {
+    case class C(x: Int)
+    ser(new C(1))
+    ser(C)
+  }
+
+  def ser(o: AnyRef) {
+    val oos = new java.io.ObjectOutputStream(new java.io.ByteArrayOutputStream())
+    oos.writeObject(o)
+    oos.close()
+  }
+
+}
+
+ at serializable
+class Outer1 {
+  @serializable
+  class Inner(x: Int = 1)
+}
+
+ at serializable
+class Outer2 {
+  case class Inner(x: Int = 1)
+}
+
+ at serializable
+class Outer3 {
+  case class Inner(x: Int)
+}
diff --git a/test/files/run/t3726.check b/test/files/run/t3726.check
new file mode 100644
index 0000000..7a5775b
--- /dev/null
+++ b/test/files/run/t3726.check
@@ -0,0 +1,2 @@
+hi there
+5
\ No newline at end of file
diff --git a/test/files/run/t3726.scala b/test/files/run/t3726.scala
new file mode 100644
index 0000000..5ceed54
--- /dev/null
+++ b/test/files/run/t3726.scala
@@ -0,0 +1,8 @@
+object Test extends Application {
+  def test(f: () => Int) = {
+    val x = f()
+    5
+  }
+
+  println(test(() => { println("hi there"); 0 }))
+}
diff --git a/test/files/run/t3763.scala b/test/files/run/t3763.scala
new file mode 100644
index 0000000..c8462b7
--- /dev/null
+++ b/test/files/run/t3763.scala
@@ -0,0 +1,3 @@
+object Test extends Application {
+  val x = Array(Array(1), List(1))
+}
diff --git a/test/files/run/t493.scala b/test/files/run/t493.scala
new file mode 100644
index 0000000..7aaad1f
--- /dev/null
+++ b/test/files/run/t493.scala
@@ -0,0 +1,22 @@
+object Test {
+
+ val y = new collection.mutable.HashMap[String,Any]
+ val z = new collection.mutable.HashMap[String,Any]
+
+ y("msg") = Array[String]("1","2")
+
+ val array: Array[String] = Array[String]("1","2")
+ z("msg") = array
+
+ def main(args:Array[String]) = {
+
+   assert(y("msg").isInstanceOf[Array[_]])
+   assert(z("msg").isInstanceOf[Array[_]])
+
+   // these work, without producing a match error
+
+   (z.get("msg"): @unchecked) match {
+     case Some(_:Array[String]) =>
+   }
+  }
+}
diff --git a/test/files/run/t498.check b/test/files/run/t498.check
new file mode 100644
index 0000000..b1ce75e
--- /dev/null
+++ b/test/files/run/t498.check
@@ -0,0 +1 @@
+Stream(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
diff --git a/test/files/run/t498.scala b/test/files/run/t498.scala
new file mode 100644
index 0000000..50be317
--- /dev/null
+++ b/test/files/run/t498.scala
@@ -0,0 +1,5 @@
+object Test extends Application {
+// the function passed to flatMap produces lots of empty streams, but this should not overflow the stack
+	val res = Stream.from(1).flatMap(i => if (i < 3000) Stream.empty else List(1))
+	println(res take 42 force)
+}
\ No newline at end of file
diff --git a/test/files/run/tailcalls.scala b/test/files/run/tailcalls.scala
index 1605c4b..3338240 100644
--- a/test/files/run/tailcalls.scala
+++ b/test/files/run/tailcalls.scala
@@ -1,7 +1,6 @@
 //############################################################################
 // Tail Calls
 //############################################################################
-// $Id: tailcalls.scala 16655 2008-11-26 19:05:23Z dragos $
 
 //############################################################################
 // Calibration
@@ -381,6 +380,18 @@ object Test {
     check_success("FancyTailCalls.differentInstance",   FancyTailCalls.differentInstance(max, 42), 42)
     check_success("PolyObject.tramp", PolyObject.tramp[Int](max), 0)
   }
+
+  // testing explicit tailcalls.
+  
+  import scala.util.control.TailCalls._
+
+  def isEven(xs: List[Int]): TailRec[Boolean] =
+    if (xs.isEmpty) done(true) else tailcall(isOdd(xs.tail))
+
+  def isOdd(xs: List[Int]): TailRec[Boolean] =
+    if (xs.isEmpty) done(false) else tailcall(isEven(xs.tail)) 
+
+  assert(isEven((1 to 100000).toList).result)
   
 }
 
diff --git a/test/files/run/takeAndDrop.scala b/test/files/run/takeAndDrop.scala
new file mode 100644
index 0000000..6e87838
--- /dev/null
+++ b/test/files/run/takeAndDrop.scala
@@ -0,0 +1,14 @@
+object Test {  
+  def main(args: Array[String]): Unit = {
+    val range = 1 to 10
+    val target = (3 to 8).toList
+    val confirm = (xs: Seq[Int]) => assert(xs.toList == target, xs)
+    
+    confirm(range drop 2 dropRight 2)
+    confirm(range drop 1 dropRight 1 drop 1 dropRight 1)
+    confirm(range take 8 drop 2)
+    confirm(range takeRight 8 dropRight 2)
+    confirm(range drop 2 take 6)
+    confirm(range dropRight 1 take 8 takeRight 7 drop 1)
+  }
+}
diff --git a/test/files/run/tcpoly_monads.scala b/test/files/run/tcpoly_monads.scala
index b70776f..a549caa 100644
--- a/test/files/run/tcpoly_monads.scala
+++ b/test/files/run/tcpoly_monads.scala
@@ -39,4 +39,4 @@ trait OptionMonad extends Monads {
 
 object Test extends OptionMonad with Application {
   Console.println((Some("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") >>= (x => Some(x.length))).get)
-}
\ No newline at end of file
+}
diff --git a/test/files/run/tcpoly_overriding.scala b/test/files/run/tcpoly_overriding.scala
index 970e16c..00ab580 100644
--- a/test/files/run/tcpoly_overriding.scala
+++ b/test/files/run/tcpoly_overriding.scala
@@ -13,4 +13,4 @@ class B extends A[List] {
 
 object Test extends Application {
   Console.println((new B).b(0))
-}
\ No newline at end of file
+}
diff --git a/test/files/run/tcpoly_parseridioms.scala b/test/files/run/tcpoly_parseridioms.scala
index db88f90..2747e1b 100644
--- a/test/files/run/tcpoly_parseridioms.scala
+++ b/test/files/run/tcpoly_parseridioms.scala
@@ -63,7 +63,7 @@ trait Idioms {
 
   class IdiomaticTarget[idi[x], idiom <: Idiom[idi], s](i: idiom, tgt: s) { 
     def dot [t](fun: s => t, name: String) = new IdiomaticApp2[idi, idiom, t](i, i.liftedApply(i.pureMethod(name, fun))(i.pure(tgt)))
-  } // TODO: `.` -->  java.lang.ClassFormatError: Illegal method name "." in class Idioms$IdiomaticTarget
+  } // TODO: `.` -->  java.lang.ClassFormatError: Illegal method name "." in class Idioms$Id$
 
   class IdiomaticFunction[idi[x], idiom <: Idiom[idi], s, t](i: idiom, fun: s => t) { 
     def <| (a: idi[s]) = new IdiomaticApp[idi, idiom, t](i, i.liftedApply(i.pure(fun))(a))
diff --git a/test/files/run/treePrint.check b/test/files/run/treePrint.check
new file mode 100644
index 0000000..3360815
--- /dev/null
+++ b/test/files/run/treePrint.check
@@ -0,0 +1,5 @@
+def foo = {
+  var q: Boolean = false;
+  val x = 5;
+  ((x == 5) || (!q)) || (true)
+}
diff --git a/test/files/run/treePrint.scala b/test/files/run/treePrint.scala
new file mode 100644
index 0000000..075ceb5
--- /dev/null
+++ b/test/files/run/treePrint.scala
@@ -0,0 +1,40 @@
+/** Testing compact tree printers.
+ */
+object Test {
+  import scala.tools.nsc._
+  import java.io.{ OutputStream, BufferedReader, StringReader, PrintWriter, Writer, OutputStreamWriter}
+  
+  val code = """
+    def foo = {
+      var q: Boolean = false
+      val x = if (true) {
+        if (true) {
+          if (true) {
+            5
+          }
+          else if (true) {
+            5
+          } else {
+            10
+          }
+        }
+        else 20
+      }
+      else 30
+    
+      (x == 5) || !q || true
+    }
+  """  
+  
+  class NullOutputStream extends OutputStream { def write(b: Int) { } }
+
+  def main(args: Array[String]) {
+    val settings = new Settings
+    settings.classpath.value = System.getProperty("java.class.path")
+    settings.Ycompacttrees.value = true
+
+    val repl = new Interpreter(settings, new PrintWriter(new NullOutputStream))
+    repl.interpret("""def initialize = "Have to interpret something or we get errors." """)
+    println(repl.power mkTree code)
+  }
+}
diff --git a/test/files/run/try-2.scala b/test/files/run/try-2.scala
index 81887b2..677f0b4 100644
--- a/test/files/run/try-2.scala
+++ b/test/files/run/try-2.scala
@@ -1,7 +1,6 @@
 /*
  * Test different variants of the try-catch block.
  *
- * $Id: try-2.scala 14389 2008-03-16 03:01:18Z mcdirmid $
  */
 
 
diff --git a/test/files/run/typealias_overriding.scala b/test/files/run/typealias_overriding.scala
index 2858a6c..a102b66 100644
--- a/test/files/run/typealias_overriding.scala
+++ b/test/files/run/typealias_overriding.scala
@@ -20,4 +20,4 @@ object Test extends Application {
   }
 
   new Linked
-}
\ No newline at end of file
+}
diff --git a/test/files/run/unapply.scala b/test/files/run/unapply.scala
index 3b7e9a5..7b746af 100644
--- a/test/files/run/unapply.scala
+++ b/test/files/run/unapply.scala
@@ -90,7 +90,7 @@ object LisSeqArr extends TestCase("LisSeqArr") with Assert {
   def runTest {
     assertEquals((List(1,2,3): Any) match { case   List(x,y,_*) => (x,y)}, (1,2))
     assertEquals((List(1,2,3): Any) match { case    Seq(x,y,_*) => (x,y)}, (1,2))
-    assertEquals((Array(1,2,3): Any) match { case   Seq(x,y,_*) => (x,y)}, (1,2))
+    //assertEquals((Array(1,2,3): Any) match { case   Seq(x,y,_*) => (x,y)}, (1,2))
     //assertEquals((Array(1,2,3): Any) match { case Array(x,y,_*) => {x,y}}, {1,2})
 
     // just compile, feature request #1196
@@ -107,11 +107,11 @@ object StreamFoo extends TestCase("unapply for Streams") with Assert {
 
   def sum(stream: Stream[Int]): Int =
     stream match {
-      case Stream.empty => 0
+      case Stream.Empty => 0
       case Stream.cons(hd, tl) => hd + sum(tl)
     }
   override def runTest {
-    val str: Stream[int] = Stream.fromIterator(List(1,2,3).elements)
+    val str: Stream[Int] = Stream.fromIterator(List(1,2,3).iterator)
     assertEquals(sum(str), 6)
   }
 }
diff --git a/test/files/run/unapplyArray.scala b/test/files/run/unapplyArray.scala
index bf6582d..bf7c9e2 100644
--- a/test/files/run/unapplyArray.scala
+++ b/test/files/run/unapplyArray.scala
@@ -1,7 +1,7 @@
 object Test {
   def main(args:Array[String]): Unit = {
     val z = Array(1,2,3,4)
-    val zs: Seq[int] = z
+    val zs: Seq[Int] = z
     val za: Any = z
 
 /*
diff --git a/test/files/run/unittest_collection.scala b/test/files/run/unittest_collection.scala
index dfe9f97..dd95540 100644
--- a/test/files/run/unittest_collection.scala
+++ b/test/files/run/unittest_collection.scala
@@ -96,7 +96,7 @@ object Test {
     )
     val tr = new TestResult()
     ts.run(tr)
-    for(val failure <- tr.failures) {
+    for (failure <- tr.failures) {
       Console.println(failure)
     }
   }
diff --git a/test/files/run/unittest_iterator.scala b/test/files/run/unittest_iterator.scala
new file mode 100644
index 0000000..89ccdb9
--- /dev/null
+++ b/test/files/run/unittest_iterator.scala
@@ -0,0 +1,53 @@
+// Some iterator grouped/sliding unit tests
+object Test {  
+  def it = (1 to 10).iterator
+  def assertThat[T](expectedLength: Int, expectedLast: Seq[T])(it: Iterator[Seq[T]]) {
+    val xs = it.toList
+    def fail(msg: String) = "assertion failed on %s: %s".format(xs, msg)
+    assert(xs.size == expectedLength, fail("expected length " + expectedLength))
+    assert(xs.last == expectedLast, fail("expected last " + expectedLast))
+  }
+  
+  def main(args: Array[String]): Unit = {
+    val itSum = it.toStream.sum
+    for (i <- it) {
+      // sum of the groups == sum of the original
+      val thisSum = ((it grouped i) map (_.sum)).toStream.sum
+      assert(thisSum == itSum, thisSum + " != " + itSum) 
+    }
+    
+    // grouped
+    assertThat(4, List(10)) { it grouped 3 }
+    assertThat(3, List(7, 8, 9)) { it grouped 3 withPartial false }
+    assertThat(4, List(10, -1, -1)) { it grouped 3 withPadding -1 }
+
+    // testing by-name padding
+    val padIt = it
+    assertThat(4, List(10, 1, 2)) { it grouped 3 withPadding padIt.next }
+
+    // sliding
+    assertThat(8, List(8, 9, 10)) { it sliding 3 }
+    assertThat(3, (3 to 10).toList) { it sliding 8 }
+    assertThat(2, List(9, 10)) { it.sliding(8, 8) }
+    assertThat(1, (1 to 8).toList) { it.sliding(8, 8) withPartial false }
+    assertThat(2, List(9, 10, -1, -1, -1)) { it.sliding(5, 8) withPadding -1 }
+    assertThat(1, (1 to 5).toList) { it.sliding(5, 8) withPartial false }
+    
+    // larger step than window
+    assertThat(5, List(9)) { it.sliding(1, 2) }
+    assertThat(3, List(9, 10)) { it.sliding(2, 4) }
+    
+    // make sure it throws past the end
+    val thrown = try {
+      val it = List(1,2,3).sliding(2)
+      it.next
+      it.next
+      it.next
+      false
+    }
+    catch {
+      case _: NoSuchElementException => true
+    }
+    assert(thrown)
+  }
+}
diff --git a/test/files/run/vector1.check b/test/files/run/vector1.check
new file mode 100644
index 0000000..10447a0
--- /dev/null
+++ b/test/files/run/vector1.check
@@ -0,0 +1,6 @@
+===== test1 =====
+===== test2 =====
+===== test3 =====
+===== test4 =====
+===== test5 =====
+done
diff --git a/test/files/run/vector1.scala b/test/files/run/vector1.scala
new file mode 100644
index 0000000..b37cfe8
--- /dev/null
+++ b/test/files/run/vector1.scala
@@ -0,0 +1,199 @@
+// testing the impl from the scala library
+//package test5
+
+import scala.collection._
+import scala.collection.immutable._
+
+import scala.collection.generic._
+import scala.collection.mutable.Builder
+
+
+object Test {
+  
+    def vector(label: String, n: Int): Vector[String] = {
+      val a = new VectorBuilder[String]
+      for (i <- 0 until n)
+        a += (label + i)
+
+      val res = a.result
+      assertVector(res, label, 0, n)
+    }
+
+    def vectorForward(label: String, n: Int): Vector[String] = {
+      var a: Vector[String] = Vector.empty
+      for (i <- 0 until n)
+        a = a :+ (label + i)
+
+      assertVector(a, label, 0, n)
+    }
+
+    def vectorBackward(label: String, n: Int): Vector[String] = {
+      var a: Vector[String] = Vector.empty
+      for (i <- 0 until n)
+        a = (label + (n-1-i)) +: a
+
+      assertVector(a, label, 0, n)
+    }
+
+    def assertVector[V](a: Vector[V], label: String, start: Int, end: Int) = {
+      assertVectorIndexed(a, label, start, end)
+      assertVectorIterated(a, label, start, end)
+    }
+
+    def assertVectorIndexed[V](a: Vector[V], label: String, start: Int, end: Int) = {
+      val res = a
+      assert(res.length == (end-start), res.length+"!="+(end-start)+" ("+res+")")
+      for (i <- start until end) {
+        assert(res(i) == (label + i), ""+res(i)+"!="+(label + i))
+      }
+      res
+    }
+
+    def assertVectorIterated[V](a: Vector[V], label: String, start: Int, end: Int) = {
+      val res = a
+      assert(res.length == (end-start), res.length+"!="+(end-start)+" ("+res+")")
+      var i = start
+      var it = res.iterator
+      while(it.hasNext) {
+        val x = it.next()
+        assert(x == (label + i), x.toString+"!="+(label + i))
+        i += 1
+      }
+      assert(i == end)
+      res
+    }
+
+
+
+  def test1() = {
+    println("===== test1 =====")
+    
+    val N = 150000
+    val a = vector("a", N)
+    val b = vectorForward("b", N)
+    val c = vectorBackward("b", N)
+
+    ()
+//    //println(a)
+  }
+
+  def test2() = {
+    println("===== test2 =====")
+
+    var a: Vector[String] = Vector.empty
+    
+    val rand = new java.util.Random
+    
+    val N = 150000
+    var min = N/2//rand.nextInt(N)
+    var max = min
+    
+    val chunkLimit = 11
+    
+    def nextChunkSize = 3 //rand.nextInt(chunkLimit)
+    
+    def seqBack() = for (i <- 0 until Math.min(nextChunkSize, N-max)) { a = a :+ ("a"+max); max += 1 }
+    def seqFront() = for (i <- 0 until Math.min(nextChunkSize, min)) { min -= 1; a = ("a"+min) +: a }
+    
+    try {
+      
+    while (min > 0 || max < N) {
+      seqFront()
+      seqBack()
+    }
+  } catch {
+    case ex =>
+      //println("----------------")
+      //a.debug
+      throw ex
+  }
+    
+    assertVector(a, "a", 0, N)
+  }
+
+
+
+  def test3() = {
+    println("===== test3 =====")
+
+    val N = 150000
+    val a = vector("a", N)
+
+    val pos = scala.util.Random.shuffle(scala.collection.mutable.WrappedArray.make[Int](Array.tabulate[Int](N)(i => i)))
+
+    var b = a
+    
+    {
+      var i = 0
+      while (i < N) {
+        b = b.updated(pos(i), "b"+(pos(i)))
+        i += 1
+      }
+      
+      assertVector(b, "b", 0, N)
+    }
+
+//    //println(a)
+  }
+
+  def test4() = {
+    println("===== test4 =====")
+
+    val N = 150000
+    val a = vectorForward("a", N)
+
+    {
+      var i = 0
+      var it = a
+      while (i < N) {
+        assert(it.length == (N-i), it.length+" items at iteration "+i)
+        val x = it(0)
+        val y = it(N-i-1)
+        assert(x == "a"+i, x+"!=a"+i)
+        assert(y == "a"+(N-1), y+"!=a"+(N-1))
+        it = it.drop(1)
+        i += 1
+      }
+      assert(it.length == 0)
+    }
+
+//    //println(a)
+  }
+
+  def test5() = {
+    println("===== test5 =====")
+
+    val N = 150000
+    val a = vectorBackward("a", N)
+
+    {
+      var i = 0
+      var it = a
+      while (i < N) {
+        assert(it.length == (N-i), it.length+" items at iteration "+i)
+        val x = it(0)
+        val y = it(N-i-1)
+//        println("x " + x + "/" + i)
+//        println("y " + y)
+        assert(x == "a0", x+"!=a0")
+        assert(y == "a"+(N-i-1), y+"!=a"+(N-i-1))
+        it = it.dropRight(1)
+        i += 1
+      }
+      assert(it.length == 0)
+    }
+  }
+
+  def main(args: Array[String]) = {
+
+    test1()
+    test2()
+    test3()
+    test4()
+    test5()
+
+    println("done")
+  }
+
+}
+
diff --git a/test/files/run/viewtest.check b/test/files/run/viewtest.check
new file mode 100644
index 0000000..6e0fe81
--- /dev/null
+++ b/test/files/run/viewtest.check
@@ -0,0 +1,12 @@
+SeqViewZ(...)
+ys defined
+mapping 1
+2
+SeqViewMS(...)
+mapping 3
+4
+SeqViewM(...)
+mapping 1
+mapping 2
+mapping 3
+List(2, 3, 4)
diff --git a/test/files/run/viewtest.scala b/test/files/run/viewtest.scala
new file mode 100644
index 0000000..c5dffa5
--- /dev/null
+++ b/test/files/run/viewtest.scala
@@ -0,0 +1,46 @@
+import collection._
+object Test extends Application {
+
+  val xs: SeqView[(String, Int), Seq[_]] = List("x").view.zip(Stream.from(0))
+  println(xs)
+
+  val ys = List(1, 2, 3).view map { x => println("mapping "+x); x + 1 }
+  println("ys defined")
+  println(ys.head)
+  println(ys.tail)
+  println(ys(2))
+  println(ys)
+  println(ys.force)
+
+  val zs = Array(1, 2, 3).view
+  val as: SeqView[Int, Array[Int]] = zs map (_ + 1)
+  val bs: Array[Int] = as.force
+  val cs = zs.reverse
+  cs(0) += 1
+  assert(cs.force.deep == Array(4, 2, 1).deep)
+  assert(zs(2) == 4)
+  assert(bs.deep == Array(2, 3, 4).deep)
+}
+
+/* crash confirmed.
+2.8 regression: CCE when zipping list projection with stream
+Reported by: 	szeiger 	Owned by: 	odersky
+Priority: 	normal 	Component: 	Standard Library
+Keywords: 	collections, zip 	Cc: 	
+Fixed in version: 	
+Description
+
+Welcome to Scala version 2.8.0.r18784-b20090925021043 (Java HotSpot(TM) Client VM, Java 1.6.0_11).
+Type in expressions to have them evaluated.
+Type :help for more information.
+
+scala> List("x").view.zip(Stream.from(0))List("x").view.zip(Stream.from(0))
+java.lang.ClassCastException: scala.collection.generic.IterableViewTemplate$$anon$8 cannot be cast to scala.collection.generic.SequenceView
+        at .<init>(<console>:5)
+        at .<clinit>(<console>)
+        at RequestResult$.<init>(<console>:4)
+        at RequestResult$.<clinit>(<console>)
+        at RequestResult$result(<console>)
+        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
+        at sun.reflect.Nat...
+*/
diff --git a/test/files/run/weakconform.scala b/test/files/run/weakconform.scala
new file mode 100644
index 0000000..1ea81c9
--- /dev/null
+++ b/test/files/run/weakconform.scala
@@ -0,0 +1,4 @@
+object Test extends Application {
+  val x: Float = 10/3
+  assert(x == 3.0)
+}
diff --git a/test/files/run/withIndex.scala b/test/files/run/withIndex.scala
index 6d47087..910b1f1 100644
--- a/test/files/run/withIndex.scala
+++ b/test/files/run/withIndex.scala
@@ -2,8 +2,8 @@ object Test {
   def main(args: Array[String]) = {
     val ary: Array[String] = Array("a", "b", "c")
     val lst: List[String] = List("a", "b", "c")
-    val itr: Iterator[String] = lst.elements
-    val str: Stream[String] = Stream.fromIterator(lst.elements)
+    val itr: Iterator[String] = lst.iterator
+    val str: Stream[String] = lst.iterator.toStream
 
     Console.println(ary.zipWithIndex.toList)
     Console.println(lst.zipWithIndex.toList)
@@ -18,8 +18,8 @@ object Test {
 
     val emptyArray = new Array[String](0)
     val emptyList: List[String] = Nil
-    val emptyIterator = emptyList.elements
-    val emptyStream = Stream.empty
+    val emptyIterator = emptyList.iterator
+    val emptyStream: Stream[String] = Stream.empty
 
     Console.println(emptyArray.zipWithIndex.toList)
     Console.println(emptyList.zipWithIndex.toList)
diff --git a/test/files/run/xml-loop-bug.scala b/test/files/run/xml-loop-bug.scala
new file mode 100644
index 0000000..378ae9b
--- /dev/null
+++ b/test/files/run/xml-loop-bug.scala
@@ -0,0 +1,6 @@
+object Test {
+  def main(args: Array[String]): Unit = {
+    scala.tools.nsc.io.NullPrintStream.setOutAndErr()
+    scala.xml.parsing.ConstructingParser.fromSource(scala.io.Source.fromString("<!DOCTYPE xmeml SYSTEM> <xmeml> <sequence> </sequence> </xmeml> "), true).document.docElem 
+  }
+}
diff --git a/test/files/jvm5/bug680.check b/test/files/scalacheck/.gitignore
similarity index 100%
rename from test/files/jvm5/bug680.check
rename to test/files/scalacheck/.gitignore
diff --git a/test/files/scalacheck/list.scala b/test/files/scalacheck/list.scala
deleted file mode 100644
index b3396bc..0000000
--- a/test/files/scalacheck/list.scala
+++ /dev/null
@@ -1,10 +0,0 @@
-import org.scalacheck._
-import Prop._
-
-object Test {
-  val prop_ConcatLists = 
-    property((l1: List[Int], l2: List[Int]) => (l1.size + l2.size) == (l1 ::: l2).size)
-
-  val tests = List(("ConcatLists", prop_ConcatLists))
-}
-
diff --git a/test/files/scalap/abstractClass/A.scala b/test/files/scalap/abstractClass/A.scala
new file mode 100644
index 0000000..19a528d
--- /dev/null
+++ b/test/files/scalap/abstractClass/A.scala
@@ -0,0 +1,5 @@
+abstract class AbstractClass {
+
+    def foo: String
+
+}
diff --git a/test/files/scalap/abstractClass/result.test b/test/files/scalap/abstractClass/result.test
new file mode 100644
index 0000000..9b8fc4d
--- /dev/null
+++ b/test/files/scalap/abstractClass/result.test
@@ -0,0 +1,4 @@
+abstract class AbstractClass extends java.lang.Object with scala.ScalaObject {
+  def this() = { /* compiled code */ }
+  def foo : scala.Predef.String
+}
diff --git a/test/files/scalap/abstractMethod/A.scala b/test/files/scalap/abstractMethod/A.scala
new file mode 100644
index 0000000..4bedb37
--- /dev/null
+++ b/test/files/scalap/abstractMethod/A.scala
@@ -0,0 +1,4 @@
+trait AbstractMethod {
+  def arity: Int
+  def isCool = true
+}
diff --git a/test/files/scalap/abstractMethod/result.test b/test/files/scalap/abstractMethod/result.test
new file mode 100644
index 0000000..a1bd378
--- /dev/null
+++ b/test/files/scalap/abstractMethod/result.test
@@ -0,0 +1,5 @@
+trait AbstractMethod extends java.lang.Object with scala.ScalaObject {
+  def $init$() : scala.Unit = { /* compiled code */ }
+  def arity : scala.Int
+  def isCool : scala.Boolean = { /* compiled code */ }
+}
diff --git a/test/files/scalap/caseClass/A.scala b/test/files/scalap/caseClass/A.scala
new file mode 100644
index 0000000..95f9984
--- /dev/null
+++ b/test/files/scalap/caseClass/A.scala
@@ -0,0 +1,3 @@
+case class CaseClass[A <: Seq[Int]](i: A, s: String) {
+    def foo = 239 
+}
diff --git a/test/files/scalap/caseClass/result.test b/test/files/scalap/caseClass/result.test
new file mode 100644
index 0000000..eb1ad74
--- /dev/null
+++ b/test/files/scalap/caseClass/result.test
@@ -0,0 +1,14 @@
+ at scala.serializable
+case class CaseClass[A <: scala.Seq[scala.Int]](i : A, s : scala.Predef.String) extends java.lang.Object with scala.ScalaObject with scala.Product {
+  val i : A = { /* compiled code */ }
+  val s : scala.Predef.String = { /* compiled code */ }
+  def foo : scala.Int = { /* compiled code */ }
+  def copy[A <: scala.Seq[scala.Int]](i : A, s : scala.Predef.String) : CaseClass[A] = { /* compiled code */ }
+  override def hashCode() : scala.Int = { /* compiled code */ }
+  override def toString() : scala.Predef.String = { /* compiled code */ }
+  override def equals(x$1 : scala.Any) : scala.Boolean = { /* compiled code */ }
+  override def productPrefix : java.lang.String = { /* compiled code */ }
+  override def productArity : scala.Int = { /* compiled code */ }
+  override def productElement(x$1 : scala.Int) : scala.Any = { /* compiled code */ }
+  override def canEqual(x$1 : scala.Any) : scala.Boolean = { /* compiled code */ }
+}
\ No newline at end of file
diff --git a/test/files/scalap/caseObject/A.scala b/test/files/scalap/caseObject/A.scala
new file mode 100644
index 0000000..6a3ff10
--- /dev/null
+++ b/test/files/scalap/caseObject/A.scala
@@ -0,0 +1,3 @@
+case object CaseObject {
+    def bar = 239 
+}
diff --git a/test/files/scalap/caseObject/result.test b/test/files/scalap/caseObject/result.test
new file mode 100644
index 0000000..d888191
--- /dev/null
+++ b/test/files/scalap/caseObject/result.test
@@ -0,0 +1,9 @@
+case object CaseObject extends java.lang.Object with scala.ScalaObject with scala.Product {
+  def bar : scala.Int = { /* compiled code */ }
+  final override def toString() : java.lang.String = { /* compiled code */ }
+  override def productPrefix : java.lang.String = { /* compiled code */ }
+  override def productArity : scala.Int = { /* compiled code */ }
+  override def productElement(x$1 : scala.Int) : scala.Any = { /* compiled code */ }
+  override def canEqual(x$1 : scala.Any) : scala.Boolean = { /* compiled code */ }
+  protected def readResolve() : java.lang.Object = { /* compiled code */ }
+}
diff --git a/test/files/scalap/cbnParam/A.scala b/test/files/scalap/cbnParam/A.scala
new file mode 100644
index 0000000..2f366df
--- /dev/null
+++ b/test/files/scalap/cbnParam/A.scala
@@ -0,0 +1 @@
+class CbnParam(s: => String) 
diff --git a/test/files/scalap/cbnParam/result.test b/test/files/scalap/cbnParam/result.test
new file mode 100644
index 0000000..c6b2f4c
--- /dev/null
+++ b/test/files/scalap/cbnParam/result.test
@@ -0,0 +1,3 @@
+class CbnParam extends java.lang.Object with scala.ScalaObject {
+  def this(s : => scala.Predef.String) = { /* compiled code */ }
+}
diff --git a/test/files/scalap/classPrivate/A.scala b/test/files/scalap/classPrivate/A.scala
new file mode 100644
index 0000000..9f1bd34
--- /dev/null
+++ b/test/files/scalap/classPrivate/A.scala
@@ -0,0 +1,9 @@
+class ClassPrivate {
+  private def foo = 1
+  private[ClassPrivate] def bar = 2
+  def baz = 3
+  class Outer {
+    private[ClassPrivate] def qux = 4
+  }
+  protected def quux = 5
+}
\ No newline at end of file
diff --git a/test/files/scalap/classPrivate/result.test b/test/files/scalap/classPrivate/result.test
new file mode 100644
index 0000000..0d12b77
--- /dev/null
+++ b/test/files/scalap/classPrivate/result.test
@@ -0,0 +1,10 @@
+class ClassPrivate extends java.lang.Object with scala.ScalaObject {
+  def this() = { /* compiled code */ }
+  def baz : scala.Int = { /* compiled code */ }
+  class Outer extends java.lang.Object with scala.ScalaObject {
+    def this() = { /* compiled code */ }
+    private[ClassPrivate] def qux : scala.Int = { /* compiled code */ }
+  }
+  protected def quux : scala.Int = { /* compiled code */ }
+  private[ClassPrivate] def bar : scala.Int = { /* compiled code */ }
+}
\ No newline at end of file
diff --git a/test/files/scalap/classWithExistential/A.scala b/test/files/scalap/classWithExistential/A.scala
new file mode 100644
index 0000000..4a5213f
--- /dev/null
+++ b/test/files/scalap/classWithExistential/A.scala
@@ -0,0 +1,3 @@
+class ClassWithExistential {
+  def foo[A, B] : A=> B forSome {type A <: Seq[Int]; type B >: String} = null
+}
diff --git a/test/files/scalap/classWithExistential/result.test b/test/files/scalap/classWithExistential/result.test
new file mode 100644
index 0000000..91afdda
--- /dev/null
+++ b/test/files/scalap/classWithExistential/result.test
@@ -0,0 +1,4 @@
+class ClassWithExistential extends java.lang.Object with scala.ScalaObject {
+  def this() = { /* compiled code */ }
+  def foo[A, B] : scala.Function1[A, B forSome {type A <: scala.Seq[scala.Int]; type B >: scala.Predef.String}] = { /* compiled code */ }
+}
\ No newline at end of file
diff --git a/test/files/scalap/classWithSelfAnnotation/A.scala b/test/files/scalap/classWithSelfAnnotation/A.scala
new file mode 100644
index 0000000..9e03986
--- /dev/null
+++ b/test/files/scalap/classWithSelfAnnotation/A.scala
@@ -0,0 +1,4 @@
+class ClassWithSelfAnnotation {
+  this: CharSequence =>
+  def foo = 239
+}
diff --git a/test/files/scalap/classWithSelfAnnotation/result.test b/test/files/scalap/classWithSelfAnnotation/result.test
new file mode 100644
index 0000000..326437c
--- /dev/null
+++ b/test/files/scalap/classWithSelfAnnotation/result.test
@@ -0,0 +1,5 @@
+class ClassWithSelfAnnotation extends java.lang.Object with scala.ScalaObject {
+ this : ClassWithSelfAnnotation with java.lang.CharSequence =>
+  def this() = { /* compiled code */ }
+  def foo : scala.Int = { /* compiled code */ }
+}
diff --git a/test/files/scalap/covariantParam/A.scala b/test/files/scalap/covariantParam/A.scala
new file mode 100644
index 0000000..5b2c24d
--- /dev/null
+++ b/test/files/scalap/covariantParam/A.scala
@@ -0,0 +1,3 @@
+class CovariantParam[+A] {
+    def foo[A](a: A) = 42
+}
diff --git a/test/files/scalap/covariantParam/result.test b/test/files/scalap/covariantParam/result.test
new file mode 100644
index 0000000..8acd9b4
--- /dev/null
+++ b/test/files/scalap/covariantParam/result.test
@@ -0,0 +1,4 @@
+class CovariantParam[+A] extends java.lang.Object with scala.ScalaObject {
+  def this() = { /* compiled code */ }
+  def foo[A](a : A) : scala.Int = { /* compiled code */ }
+}
diff --git a/test/files/scalap/defaultParameter/A.scala b/test/files/scalap/defaultParameter/A.scala
new file mode 100644
index 0000000..d351495
--- /dev/null
+++ b/test/files/scalap/defaultParameter/A.scala
@@ -0,0 +1,3 @@
+trait DefaultParameter {
+  def foo(s: String = "hello"): Unit
+}
\ No newline at end of file
diff --git a/test/files/scalap/defaultParameter/result.test b/test/files/scalap/defaultParameter/result.test
new file mode 100644
index 0000000..38bf6ac
--- /dev/null
+++ b/test/files/scalap/defaultParameter/result.test
@@ -0,0 +1,3 @@
+trait DefaultParameter extends java.lang.Object {
+  def foo(s : scala.Predef.String) : scala.Unit
+}
\ No newline at end of file
diff --git a/test/files/scalap/implicitParam/A.scala b/test/files/scalap/implicitParam/A.scala
new file mode 100644
index 0000000..8065721
--- /dev/null
+++ b/test/files/scalap/implicitParam/A.scala
@@ -0,0 +1,3 @@
+class ImplicitParam {
+    def foo(i: Int)(implicit f: Float, d: Double) = 42
+}
diff --git a/test/files/scalap/implicitParam/result.test b/test/files/scalap/implicitParam/result.test
new file mode 100644
index 0000000..11d678d
--- /dev/null
+++ b/test/files/scalap/implicitParam/result.test
@@ -0,0 +1,4 @@
+class ImplicitParam extends java.lang.Object with scala.ScalaObject {
+  def this() = { /* compiled code */ }
+  def foo(i : scala.Int)(implicit f : scala.Float, d : scala.Double) : scala.Int = { /* compiled code */ }
+}
diff --git a/test/files/scalap/packageObject/A.scala b/test/files/scalap/packageObject/A.scala
new file mode 100644
index 0000000..7e429c9
--- /dev/null
+++ b/test/files/scalap/packageObject/A.scala
@@ -0,0 +1,4 @@
+package object PackageObject {
+  type A = String
+  def foo(i: Int) = 239
+}
diff --git a/test/files/scalap/packageObject/result.test b/test/files/scalap/packageObject/result.test
new file mode 100644
index 0000000..6a8d6ae
--- /dev/null
+++ b/test/files/scalap/packageObject/result.test
@@ -0,0 +1,5 @@
+package object PackageObject extends java.lang.Object with scala.ScalaObject {
+  def this() = { /* compiled code */ }
+  type A = scala.Predef.String
+  def foo(i : scala.Int) : scala.Int = { /* compiled code */ }
+}
diff --git a/test/files/scalap/paramClauses/A.scala b/test/files/scalap/paramClauses/A.scala
new file mode 100644
index 0000000..f9d1917
--- /dev/null
+++ b/test/files/scalap/paramClauses/A.scala
@@ -0,0 +1,3 @@
+class ParamClauses {
+    def foo(i: Int)(s: String)(t: Double) = 239
+}
diff --git a/test/files/scalap/paramClauses/result.test b/test/files/scalap/paramClauses/result.test
new file mode 100644
index 0000000..9ef93d2
--- /dev/null
+++ b/test/files/scalap/paramClauses/result.test
@@ -0,0 +1,4 @@
+class ParamClauses extends java.lang.Object with scala.ScalaObject {
+  def this() = { /* compiled code */ }
+  def foo(i : scala.Int)(s : scala.Predef.String)(t : scala.Double) : scala.Int = { /* compiled code */ }
+}
diff --git a/test/files/scalap/paramNames/A.scala b/test/files/scalap/paramNames/A.scala
new file mode 100644
index 0000000..7ba9ff0
--- /dev/null
+++ b/test/files/scalap/paramNames/A.scala
@@ -0,0 +1,3 @@
+class ParamNames {
+  def foo (s: => Seq[Int], s2: => Seq[Any]) {}
+}
diff --git a/test/files/scalap/paramNames/result.test b/test/files/scalap/paramNames/result.test
new file mode 100644
index 0000000..f9d98d9
--- /dev/null
+++ b/test/files/scalap/paramNames/result.test
@@ -0,0 +1,4 @@
+class ParamNames extends java.lang.Object with scala.ScalaObject {
+  def this() = { /* compiled code */ }
+  def foo(s : => scala.Seq[scala.Int], s2 : => scala.Seq[scala.Any]) : scala.Unit = { /* compiled code */ }
+}
diff --git a/test/files/scalap/sequenceParam/A.scala b/test/files/scalap/sequenceParam/A.scala
new file mode 100644
index 0000000..86e1334
--- /dev/null
+++ b/test/files/scalap/sequenceParam/A.scala
@@ -0,0 +1 @@
+class SequenceParam(s: String, i: Int*)
diff --git a/test/files/scalap/sequenceParam/result.test b/test/files/scalap/sequenceParam/result.test
new file mode 100644
index 0000000..4b9d784
--- /dev/null
+++ b/test/files/scalap/sequenceParam/result.test
@@ -0,0 +1,3 @@
+class SequenceParam extends java.lang.Object with scala.ScalaObject {
+  def this(s : scala.Predef.String, i : scala.Int*) = { /* compiled code */ }
+}
diff --git a/test/files/scalap/simpleClass/A.scala b/test/files/scalap/simpleClass/A.scala
new file mode 100644
index 0000000..fa82e62
--- /dev/null
+++ b/test/files/scalap/simpleClass/A.scala
@@ -0,0 +1,3 @@
+class SimpleClass {
+  def foo = 239
+}
diff --git a/test/files/scalap/simpleClass/result.test b/test/files/scalap/simpleClass/result.test
new file mode 100644
index 0000000..d10b633
--- /dev/null
+++ b/test/files/scalap/simpleClass/result.test
@@ -0,0 +1,4 @@
+class SimpleClass extends java.lang.Object with scala.ScalaObject {
+  def this() = { /* compiled code */ }
+  def foo : scala.Int = { /* compiled code */ }
+}
diff --git a/test/files/scalap/traitObject/A.scala b/test/files/scalap/traitObject/A.scala
new file mode 100644
index 0000000..d5f4318
--- /dev/null
+++ b/test/files/scalap/traitObject/A.scala
@@ -0,0 +1,7 @@
+trait TraitObject {
+    def foo = 239
+}
+
+object TraitObject {
+    def bar = 42
+}
diff --git a/test/files/scalap/traitObject/result.test b/test/files/scalap/traitObject/result.test
new file mode 100644
index 0000000..0d7de15
--- /dev/null
+++ b/test/files/scalap/traitObject/result.test
@@ -0,0 +1,8 @@
+trait TraitObject extends java.lang.Object with scala.ScalaObject {
+  def $init$() : scala.Unit = { /* compiled code */ }
+  def foo : scala.Int = { /* compiled code */ }
+}
+object TraitObject extends java.lang.Object with scala.ScalaObject {
+  def this() = { /* compiled code */ }
+  def bar : scala.Int = { /* compiled code */ }
+}
diff --git a/test/files/scalap/typeAnnotations/A.scala b/test/files/scalap/typeAnnotations/A.scala
new file mode 100644
index 0000000..ff2445e
--- /dev/null
+++ b/test/files/scalap/typeAnnotations/A.scala
@@ -0,0 +1,9 @@
+abstract class TypeAnnotations[@specialized R] {
+  @specialized val x = 10
+  @specialized type T
+
+  def compose[@specialized A](x: A, y: R): A = {
+    val y: A = x
+    x
+  }
+}
\ No newline at end of file
diff --git a/test/files/scalap/typeAnnotations/result.test b/test/files/scalap/typeAnnotations/result.test
new file mode 100644
index 0000000..b565d61
--- /dev/null
+++ b/test/files/scalap/typeAnnotations/result.test
@@ -0,0 +1,8 @@
+abstract class TypeAnnotations[@scala.specialized R] extends java.lang.Object with scala.ScalaObject {
+  def this() = { /* compiled code */ }
+  @scala.specialized
+  val x : scala.Int = { /* compiled code */ }
+  @scala.specialized
+  type T
+  def compose[@scala.specialized A](x : A, y : R) : A = { /* compiled code */ }
+}
\ No newline at end of file
diff --git a/test/files/scalap/valAndVar/A.scala b/test/files/scalap/valAndVar/A.scala
new file mode 100644
index 0000000..2d89348
--- /dev/null
+++ b/test/files/scalap/valAndVar/A.scala
@@ -0,0 +1,4 @@
+class ValAndVar {
+  val foo = ""
+  var bar = 42
+}
diff --git a/test/files/scalap/valAndVar/result.test b/test/files/scalap/valAndVar/result.test
new file mode 100644
index 0000000..934ad0a
--- /dev/null
+++ b/test/files/scalap/valAndVar/result.test
@@ -0,0 +1,5 @@
+class ValAndVar extends java.lang.Object with scala.ScalaObject {
+  def this() = { /* compiled code */ }
+  val foo : java.lang.String = { /* compiled code */ }
+  var bar : scala.Int = { /* compiled code */ }
+}
diff --git a/test/files/scalap/wildcardType/A.scala b/test/files/scalap/wildcardType/A.scala
new file mode 100644
index 0000000..4bb0d14
--- /dev/null
+++ b/test/files/scalap/wildcardType/A.scala
@@ -0,0 +1 @@
+class WildcardType(f: Int => _)
diff --git a/test/files/scalap/wildcardType/result.test b/test/files/scalap/wildcardType/result.test
new file mode 100644
index 0000000..aa3d5d5
--- /dev/null
+++ b/test/files/scalap/wildcardType/result.test
@@ -0,0 +1,3 @@
+class WildcardType extends java.lang.Object with scala.ScalaObject {
+  def this(f : scala.Function1[scala.Int, _]) = { /* compiled code */ }
+}
diff --git a/test/files/script/fact.args b/test/files/script/fact.args
index 7813681..7ed6ff8 100644
--- a/test/files/script/fact.args
+++ b/test/files/script/fact.args
@@ -1 +1 @@
-5
\ No newline at end of file
+5
diff --git a/test/files/script/second.bat b/test/files/script/second.bat
index 222372d..0d70859 100644
--- a/test/files/script/second.bat
+++ b/test/files/script/second.bat
@@ -1,3 +1,3 @@
- at echo off
-
-scala -nocompdaemon -e "println(\"My second argument is \" + args(1))"  arg1 arg2
+ at echo off
+
+scala -nocompdaemon -e "println(\"My second argument is \" + args(1))"  arg1 arg2
diff --git a/test/files/script/utf8.scala b/test/files/script/utf8.scala
deleted file mode 100644
index e0df666..0000000
--- a/test/files/script/utf8.scala
+++ /dev/null
@@ -1,27 +0,0 @@
-#!/bin/sh
-# fact - A simple Scala script that prints out the factorial of
-#        the argument specified on the command line.
-
-cygwin=false;
-case "`uname`" in
-    CYGWIN*) cygwin=true ;;
-esac
-
-SOURCE="$0";
-if $cygwin; then
-    if [ "$OS" = "Windows_NT" ] && cygpath -m .>/dev/null 2>/dev/null ; 
-then
-        format=mixed
-    else
-        format=windows
-    fi
-    SOURCE=`cygpath --$format "$SOURCE"`;
-fi
-
-export LC_CTYPE=en_US.UTF-8
-exec scala -nocompdaemon "$SOURCE" "$@"
-!#
-
-/*Comment Комментарий*/
-Console.println("QWERTY");
-Console.println("ЙЦУКЕН");
diff --git a/test/files/shootout/README b/test/files/shootout/README
index 4b37bc0..6acce16 100644
--- a/test/files/shootout/README
+++ b/test/files/shootout/README
@@ -11,4 +11,4 @@ find shootout/bench/ -iname *.scala -exec cp \{} $SCALA_SRC/test/files/shootout
  --> they supply the right arguments / input
 see also howtorun
 
-3) scalatest combines the original *.scala files with the appropriate scala.runner file
\ No newline at end of file
+3) scalatest combines the original *.scala files with the appropriate scala.runner file
diff --git a/test/files/shootout/ackermann.scala.runner b/test/files/shootout/ackermann.scala.runner
index 404ad27..8b774a6 100644
--- a/test/files/shootout/ackermann.scala.runner
+++ b/test/files/shootout/ackermann.scala.runner
@@ -1,3 +1,3 @@
 object Test extends Application {
  for(val n <- List(9,10,11)) ackermann.main(Array(n.toString)) 
-}  
\ No newline at end of file
+}  
diff --git a/test/files/shootout/ary.scala.runner b/test/files/shootout/ary.scala.runner
index 8443cf3..a2cbe7b 100644
--- a/test/files/shootout/ary.scala.runner
+++ b/test/files/shootout/ary.scala.runner
@@ -1,3 +1,3 @@
 object Test extends Application {
   for(val n <- List(3000,5000,7000,9000)) ary3.main(Array(n.toString)) 
-} 
\ No newline at end of file
+} 
diff --git a/test/files/shootout/binarytrees.scala-2.scala.runner b/test/files/shootout/binarytrees.scala-2.scala.runner
index 6e6b63b..dab4612 100644
--- a/test/files/shootout/binarytrees.scala-2.scala.runner
+++ b/test/files/shootout/binarytrees.scala-2.scala.runner
@@ -1,3 +1,3 @@
 object Test extends Application {
   for(val n <- List(12,14,16)) binarytrees.main(Array(n.toString)) 
-}
\ No newline at end of file
+}
diff --git a/test/files/shootout/binarytrees.scala-3.scala.runner b/test/files/shootout/binarytrees.scala-3.scala.runner
index 6e6b63b..dab4612 100644
--- a/test/files/shootout/binarytrees.scala-3.scala.runner
+++ b/test/files/shootout/binarytrees.scala-3.scala.runner
@@ -1,3 +1,3 @@
 object Test extends Application {
   for(val n <- List(12,14,16)) binarytrees.main(Array(n.toString)) 
-}
\ No newline at end of file
+}
diff --git a/test/files/shootout/binarytrees.scala.runner b/test/files/shootout/binarytrees.scala.runner
index 6e6b63b..dab4612 100644
--- a/test/files/shootout/binarytrees.scala.runner
+++ b/test/files/shootout/binarytrees.scala.runner
@@ -1,3 +1,3 @@
 object Test extends Application {
   for(val n <- List(12,14,16)) binarytrees.main(Array(n.toString)) 
-}
\ No newline at end of file
+}
diff --git a/test/files/shootout/chameneos.scala.runner b/test/files/shootout/chameneos.scala.runner
index f3563e5..d585a20 100644
--- a/test/files/shootout/chameneos.scala.runner
+++ b/test/files/shootout/chameneos.scala.runner
@@ -1,3 +1,3 @@
 object Test extends Application {
   for(val n <- List(10000,100000,1000000)) chameneos.main(Array(n.toString)) 
-}
\ No newline at end of file
+}
diff --git a/test/files/shootout/except.scala b/test/files/shootout/except.scala
index 624d04f..1024b7f 100644
--- a/test/files/shootout/except.scala
+++ b/test/files/shootout/except.scala
@@ -56,4 +56,4 @@ object except {
 }
 
 private class LoException extends Exception {}
-private class HiException extends Exception {}
\ No newline at end of file
+private class HiException extends Exception {}
diff --git a/test/files/shootout/except.scala.runner b/test/files/shootout/except.scala.runner
index 2d6b4cf..18f30cf 100644
--- a/test/files/shootout/except.scala.runner
+++ b/test/files/shootout/except.scala.runner
@@ -1,3 +1,3 @@
 object Test extends Application {
   for(val n <- List(100000,150000,200000,250000)) except.main(Array(n.toString)) 
-}
\ No newline at end of file
+}
diff --git a/test/files/shootout/fannkuch.scala-2.scala.runner b/test/files/shootout/fannkuch.scala-2.scala.runner
index af664fa..a0f682a 100644
--- a/test/files/shootout/fannkuch.scala-2.scala.runner
+++ b/test/files/shootout/fannkuch.scala-2.scala.runner
@@ -1,3 +1,3 @@
 object Test extends Application {
   for(val n <- List(8,9,10)) fannkuch.main(Array(n.toString)) 
-}
\ No newline at end of file
+}
diff --git a/test/files/shootout/fannkuch.scala.runner b/test/files/shootout/fannkuch.scala.runner
index af664fa..a0f682a 100644
--- a/test/files/shootout/fannkuch.scala.runner
+++ b/test/files/shootout/fannkuch.scala.runner
@@ -1,3 +1,3 @@
 object Test extends Application {
   for(val n <- List(8,9,10)) fannkuch.main(Array(n.toString)) 
-}
\ No newline at end of file
+}
diff --git a/test/files/shootout/fibo.scala.runner b/test/files/shootout/fibo.scala.runner
index e0973c3..eb30b39 100644
--- a/test/files/shootout/fibo.scala.runner
+++ b/test/files/shootout/fibo.scala.runner
@@ -1,3 +1,3 @@
 object Test extends Application {
   for(val n <- List(12,24,32)) fibo.main(Array(n.toString)) 
-}
\ No newline at end of file
+}
diff --git a/test/files/shootout/harmonic.scala.runner b/test/files/shootout/harmonic.scala.runner
index b47101a..5cf77d0 100644
--- a/test/files/shootout/harmonic.scala.runner
+++ b/test/files/shootout/harmonic.scala.runner
@@ -1,3 +1,3 @@
 object Test extends Application {
   for(val n <- List(6000000,8000000,10000000)) harmonic.main(Array(n.toString)) 
-}
\ No newline at end of file
+}
diff --git a/test/files/shootout/hash.scala.runner b/test/files/shootout/hash.scala.runner
index d4b3e2d..926a327 100644
--- a/test/files/shootout/hash.scala.runner
+++ b/test/files/shootout/hash.scala.runner
@@ -1,3 +1,3 @@
 object Test extends Application {
   for(val n <- List(40000,60000,80000,100000)) hash.main(Array(n.toString)) 
-}
\ No newline at end of file
+}
diff --git a/test/files/shootout/hash2.scala b/test/files/shootout/hash2.scala
index 4080399..39a6e09 100644
--- a/test/files/shootout/hash2.scala
+++ b/test/files/shootout/hash2.scala
@@ -25,7 +25,7 @@ object hash2 {
 
 
       while (n>0) {
-         for (val each <- table1.elements){
+         for (val each <- table1.iterator){
             val key = each._1;
             val c1 = each._2;
 
diff --git a/test/files/shootout/hash2.scala.runner b/test/files/shootout/hash2.scala.runner
index aeaf0d0..3a0783b 100644
--- a/test/files/shootout/hash2.scala.runner
+++ b/test/files/shootout/hash2.scala.runner
@@ -1,3 +1,3 @@
 object Test extends Application {
   for(val n <- List(50,100,150,200)) hash2.main(Array(n.toString)) 
-}
\ No newline at end of file
+}
diff --git a/test/files/shootout/hello.scala.runner b/test/files/shootout/hello.scala.runner
index 8a668e1..00b077e 100644
--- a/test/files/shootout/hello.scala.runner
+++ b/test/files/shootout/hello.scala.runner
@@ -1,3 +1,3 @@
 object Test extends Application {
   for(val n <- List(1,50,100,150,200)) hello.main(Array(n.toString)) 
-}
\ No newline at end of file
+}
diff --git a/test/files/shootout/howtorun b/test/files/shootout/howtorun
index e9e0a1a..8d3d572 100644
--- a/test/files/shootout/howtorun
+++ b/test/files/shootout/howtorun
@@ -76,7 +76,7 @@ methcall object Test extends Application {
 }  
 moments object Test extends Application {
   for(val n <- List(25,75,125,200)) {
-    System.setIn(new java.io.FileInputStream(System.getProperty("scalatest.cwd")+"/moments-input"+n+".txt"))
+    System.setIn(new java.io.FileInputStream(System.getProperty("partest.cwd")+"/moments-input"+n+".txt"))
     moments.main(Array(n.toString)) 
   }
 } 
@@ -119,20 +119,20 @@ recursive object Test extends Application {
 } 
 regexdna object Test extends Application {
   for(val n <- List(100000,300000,500000)) {
-    System.setIn(new java.io.FileInputStream(System.getProperty("scalatest.cwd")+"/regexdna-input"+n+".txt"))
+    System.setIn(new java.io.FileInputStream(System.getProperty("partest.cwd")+"/regexdna-input"+n+".txt"))
     regexdna.main(Array(n.toString)) 
   }
 } 
 regexmatch object Test extends Application {
   for(val n <- List(100,6000,9000,12000)) {
-    System.setIn(new java.io.FileInputStream(System.getProperty("scalatest.cwd")+"/regexmatch-input"+n+".txt"))
+    System.setIn(new java.io.FileInputStream(System.getProperty("partest.cwd")+"/regexmatch-input"+n+".txt"))
     regexmatch.main(Array(n.toString)) 
   }
 } 
 
 revcomp object Test extends Application {
   for(val n <- List(25000,250000,2500000)) {
-    System.setIn(new java.io.FileInputStream(System.getProperty("scalatest.cwd")+"/revcomp-input"+n+".txt"))
+    System.setIn(new java.io.FileInputStream(System.getProperty("partest.cwd")+"/revcomp-input"+n+".txt"))
     revcomp.main(Array(n.toString)) 
   }
 } 
@@ -155,7 +155,7 @@ spellcheck inputfile=../../website/desc/spellcheck-input.txt
 
 object Test extends Application {
   for(val n <- List(2500,25000,250000)) {
-    System.setIn(new java.io.FileInputStream(System.getProperty("scalatest.cwd")+"/knucleotide-input"+n+".txt"))
+    System.setIn(new java.io.FileInputStream(System.getProperty("partest.cwd")+"/knucleotide-input"+n+".txt"))
     knucleotide.main(Array(n.toString)) 
   }
 } 
@@ -165,7 +165,7 @@ strcat object Test extends Application {
 } 
 sumcol object Test extends Application {
   for(val n <- List(400,700,1000,8000)) {
-    System.setIn(new java.io.FileInputStream(System.getProperty("scalatest.cwd")+"/sumcol-input"+n+".txt"))
+    System.setIn(new java.io.FileInputStream(System.getProperty("partest.cwd")+"/sumcol-input"+n+".txt"))
     sumcol.main(Array(n.toString)) 
   }
 } 
@@ -196,7 +196,7 @@ wordfreq inputfile=../../website/desc/wordfreq-input.txt
 
 object Test extends Application {
   for(val n <- List(2500,25000,250000)) {
-    System.setIn(new java.io.FileInputStream(System.getProperty("scalatest.cwd")+"/knucleotide-input"+n+".txt"))
+    System.setIn(new java.io.FileInputStream(System.getProperty("partest.cwd")+"/knucleotide-input"+n+".txt"))
     knucleotide.main(Array(n.toString)) 
   }
 } 
diff --git a/test/files/shootout/knucleotide.scala-2.scala.runner b/test/files/shootout/knucleotide.scala-2.scala.runner
index 99701e8..dcc070b 100644
--- a/test/files/shootout/knucleotide.scala-2.scala.runner
+++ b/test/files/shootout/knucleotide.scala-2.scala.runner
@@ -1,6 +1,6 @@
 object Test extends Application {
   for(val n <- List(2500,25000,250000)) {
-    System.setIn(new java.io.FileInputStream(System.getProperty("scalatest.cwd")+"/knucleotide-input"+n+".txt"))
+    System.setIn(new java.io.FileInputStream(System.getProperty("partest.cwd")+"/knucleotide-input"+n+".txt"))
     knucleotide.main(Array(n.toString)) 
   }
-} 
\ No newline at end of file
+} 
diff --git a/test/files/shootout/knucleotide.scala-3.scala b/test/files/shootout/knucleotide.scala-3.scala
index 723f04b..88eb826 100644
--- a/test/files/shootout/knucleotide.scala-3.scala
+++ b/test/files/shootout/knucleotide.scala-3.scala
@@ -70,7 +70,7 @@ object knucleotide {
    def writeFrequencies(j: Int) = {
       val bag = generateFrequencies(j)
       val n = sequence.length - j + 1.0
-      val sortedValues = bag.elements.toList.sort(
+      val sortedValues = bag.iterator.toList.sort(
          (a,b) => if (a.value == b.value) a.key > b.key
                   else a.value > b.value )
 
@@ -90,7 +90,7 @@ object knucleotide {
 class HashBag[A] extends HashTable[A] {
    protected type Entry = Counter[A]
    protected def entryKey(e: Entry) = e.key
-   def elements = entries
+   def iterator = entries
 
    def +=(elem: A): Unit = {
       var bucket = table(index(elemHashCode(elem))).asInstanceOf[Entry]
diff --git a/test/files/shootout/knucleotide.scala-3.scala.runner b/test/files/shootout/knucleotide.scala-3.scala.runner
index 3aee96d..c35b0eb 100644
--- a/test/files/shootout/knucleotide.scala-3.scala.runner
+++ b/test/files/shootout/knucleotide.scala-3.scala.runner
@@ -1,6 +1,6 @@
 object Test extends Application {
   for(val n <- List(2500,25000,250000)) {
-    System.setIn(new java.io.FileInputStream(System.getProperty("scalatest.cwd")+"/knucleotide-input"+n+".txt"))
+    System.setIn(new java.io.FileInputStream(System.getProperty("partest.cwd")+"/knucleotide-input"+n+".txt"))
     knucleotide.main(Array(n.toString)) 
   }
-}
\ No newline at end of file
+}
diff --git a/test/files/shootout/lists.scala b/test/files/shootout/lists.scala
index cccbee9..506e50f 100644
--- a/test/files/shootout/lists.scala
+++ b/test/files/shootout/lists.scala
@@ -14,12 +14,12 @@ object lists {
 
       while (n > 0) {
          var L1 = new ListBuffer[Int]();
-         i=0; while (i < nSize){ L1 + i; i=i+1; } 
+         i=0; while (i < nSize){ L1 += i; i=i+1; } 
          var L2 = L1.clone().asInstanceOf[ListBuffer[Int]];
          var L3 = new ListBuffer[Int]();
-         while (L2.length > 0) L3 + L2.remove(0); 
+         while (L2.length > 0) L3 += L2.remove(0); 
          i = L3.length;
-         while (i > 0){ i=i-1; L2 + L3.remove(i); }
+         while (i > 0){ i=i-1; L2 += L3.remove(i); }
 
          Console println(L2 length);
          n = n - 1;
diff --git a/test/files/shootout/lists.scala.runner b/test/files/shootout/lists.scala.runner
index 93286d1..4a072cf 100644
--- a/test/files/shootout/lists.scala.runner
+++ b/test/files/shootout/lists.scala.runner
@@ -1,3 +1,3 @@
 object Test extends Application {
   for(val n <- List(4,8,12,16,18)) lists.main(Array(n.toString)) 
-}
\ No newline at end of file
+}
diff --git a/test/files/shootout/message.scala-2.javaopts b/test/files/shootout/message.scala-2.javaopts
deleted file mode 100644
index 1879c77..0000000
--- a/test/files/shootout/message.scala-2.javaopts
+++ /dev/null
@@ -1 +0,0 @@
--Xss128k
diff --git a/test/files/shootout/message.scala-2.scala b/test/files/shootout/message.scala-2.scala
index 574cad4..0ec230f 100644
--- a/test/files/shootout/message.scala-2.scala
+++ b/test/files/shootout/message.scala-2.scala
@@ -5,6 +5,7 @@
 
 import scala.actors._
 import scala.actors.Actor._
+import scala.actors.scheduler.SingleThreadedScheduler
 
 object message {
   def main(args: Array[String]) = {
@@ -31,5 +32,7 @@ object message {
 
     val firstActor = actorChain(nActors, null)
     var i = n; while (i > 0) { firstActor ! 0; i = i-1 }
+
+    Scheduler.shutdown()
   }
 }
diff --git a/test/files/shootout/message.scala-2.scala.runner b/test/files/shootout/message.scala-2.scala.runner
index d5e964c..afa5446 100644
--- a/test/files/shootout/message.scala-2.scala.runner
+++ b/test/files/shootout/message.scala-2.scala.runner
@@ -1,4 +1,4 @@
 object Test extends Application {
   //for(val n <- List(1000,2000,3000)) message.main(Array(n.toString)) 
   val n = 1000; message.main(Array(n.toString)) 
-}
\ No newline at end of file
+}
diff --git a/test/files/shootout/nbody.scala-2.scala.runner b/test/files/shootout/nbody.scala-2.scala.runner
index fc3dee8..6e3d54b 100644
--- a/test/files/shootout/nbody.scala-2.scala.runner
+++ b/test/files/shootout/nbody.scala-2.scala.runner
@@ -1,3 +1,3 @@
 object Test extends Application {
   for(val n <- List(200000,2000000,20000000)) nbody.main(Array(n.toString)) 
-}
\ No newline at end of file
+}
diff --git a/test/files/shootout/nestedloop.scala b/test/files/shootout/nestedloop.scala
index d3def9e..6969955 100644
--- a/test/files/shootout/nestedloop.scala
+++ b/test/files/shootout/nestedloop.scala
@@ -27,4 +27,4 @@ object nestedloop {
          catch { case _ => 1 }
       if (i>0) i; else 1;
    }
-}
\ No newline at end of file
+}
diff --git a/test/files/shootout/nestedloop.scala.runner b/test/files/shootout/nestedloop.scala.runner
index 75d60fd..1e84f7f 100644
--- a/test/files/shootout/nestedloop.scala.runner
+++ b/test/files/shootout/nestedloop.scala.runner
@@ -1,3 +1,3 @@
 object Test extends Application {
   for(val n <- List(8,12,16,18)) nestedloop.main(Array(n.toString)) 
-}
\ No newline at end of file
+}
diff --git a/test/files/shootout/nsieve.scala-2.scala.runner b/test/files/shootout/nsieve.scala-2.scala.runner
index 7f15911..8c9e80b 100644
--- a/test/files/shootout/nsieve.scala-2.scala.runner
+++ b/test/files/shootout/nsieve.scala-2.scala.runner
@@ -1,3 +1,3 @@
 object Test extends Application {
   for(val n <- List(7,8,9)) nsieve.main(Array(n.toString)) 
-}
\ No newline at end of file
+}
diff --git a/test/files/shootout/nsieve.scala-3.scala.runner b/test/files/shootout/nsieve.scala-3.scala.runner
index 7f15911..8c9e80b 100644
--- a/test/files/shootout/nsieve.scala-3.scala.runner
+++ b/test/files/shootout/nsieve.scala-3.scala.runner
@@ -1,3 +1,3 @@
 object Test extends Application {
   for(val n <- List(7,8,9)) nsieve.main(Array(n.toString)) 
-}
\ No newline at end of file
+}
diff --git a/test/files/shootout/nsievebits.scala-2.scala.runner b/test/files/shootout/nsievebits.scala-2.scala.runner
index 6f17928..dd3e909 100644
--- a/test/files/shootout/nsievebits.scala-2.scala.runner
+++ b/test/files/shootout/nsievebits.scala-2.scala.runner
@@ -1,3 +1,3 @@
 object Test extends Application {
   for(val n <- List(7,8,9)) nsievebits.main(Array(n.toString)) 
-}
\ No newline at end of file
+}
diff --git a/test/files/shootout/nsievebits.scala-3.scala.runner b/test/files/shootout/nsievebits.scala-3.scala.runner
index 6f17928..dd3e909 100644
--- a/test/files/shootout/nsievebits.scala-3.scala.runner
+++ b/test/files/shootout/nsievebits.scala-3.scala.runner
@@ -1,3 +1,3 @@
 object Test extends Application {
   for(val n <- List(7,8,9)) nsievebits.main(Array(n.toString)) 
-}
\ No newline at end of file
+}
diff --git a/test/files/shootout/nsievebits.scala.runner b/test/files/shootout/nsievebits.scala.runner
index 6f17928..dd3e909 100644
--- a/test/files/shootout/nsievebits.scala.runner
+++ b/test/files/shootout/nsievebits.scala.runner
@@ -1,3 +1,3 @@
 object Test extends Application {
   for(val n <- List(7,8,9)) nsievebits.main(Array(n.toString)) 
-}
\ No newline at end of file
+}
diff --git a/test/files/shootout/objinst.scala b/test/files/shootout/objinst.scala
index 92beac6..a1dac27 100644
--- a/test/files/shootout/objinst.scala
+++ b/test/files/shootout/objinst.scala
@@ -58,4 +58,4 @@ extends Toggle(b) {
       }
       this
    }
-}
\ No newline at end of file
+}
diff --git a/test/files/shootout/objinst.scala.runner b/test/files/shootout/objinst.scala.runner
index 4222cfb..2e96aae 100644
--- a/test/files/shootout/objinst.scala.runner
+++ b/test/files/shootout/objinst.scala.runner
@@ -1,3 +1,3 @@
 object Test extends Application {
   for(val n <- List(400000,700000,1000000,1500000)) objinst.main(Array(n.toString)) 
-}
\ No newline at end of file
+}
diff --git a/test/files/shootout/partialsums.scala-2.scala.runner b/test/files/shootout/partialsums.scala-2.scala.runner
index d65cb4b..fa351ef 100644
--- a/test/files/shootout/partialsums.scala-2.scala.runner
+++ b/test/files/shootout/partialsums.scala-2.scala.runner
@@ -1,3 +1,3 @@
 object Test extends Application {
   for(val n <- List(25000,250000,2500000)) partialsums.main(Array(n.toString)) 
-}
\ No newline at end of file
+}
diff --git a/test/files/shootout/partialsums.scala.runner b/test/files/shootout/partialsums.scala.runner
index d65cb4b..fa351ef 100644
--- a/test/files/shootout/partialsums.scala.runner
+++ b/test/files/shootout/partialsums.scala.runner
@@ -1,3 +1,3 @@
 object Test extends Application {
   for(val n <- List(25000,250000,2500000)) partialsums.main(Array(n.toString)) 
-}
\ No newline at end of file
+}
diff --git a/test/files/shootout/recursive.scala.runner b/test/files/shootout/recursive.scala.runner
index afb6d9f..bb6be54 100644
--- a/test/files/shootout/recursive.scala.runner
+++ b/test/files/shootout/recursive.scala.runner
@@ -1,3 +1,3 @@
 object Test extends Application {
   for(val n <- List(3,7,11)) recursive.main(Array(n.toString)) 
-}
\ No newline at end of file
+}
diff --git a/test/files/shootout/regexdna.scala b/test/files/shootout/regexdna.scala
index 71f2f9c..93a5c42 100644
--- a/test/files/shootout/regexdna.scala
+++ b/test/files/shootout/regexdna.scala
@@ -29,7 +29,7 @@ object regexdna {
          ,"agggtaa[cgt]|[acg]ttaccct"
          )
 
-      for (val v <- variants){
+      for (v <- variants){
          var count = 0
          m = Pattern.compile(v).matcher(sequence)
          while (m.find()) count = count + 1
@@ -51,7 +51,7 @@ object regexdna {
             ,Pair("Y", "(c|t)")
          )
 
-      for (val iub <- codes){
+      for (iub <- codes){
          iub match { 
             case Pair(code,alternative) => 
                sequence = Pattern.compile(code).matcher(sequence).replaceAll(alternative)
@@ -64,7 +64,7 @@ object regexdna {
 
    def readFully() = {
       val blockSize = 10240
-      val block = new Array[char](blockSize)
+      val block = new Array[Char](blockSize)
       val buffer = new StringBuffer(blockSize)
       val r = new InputStreamReader(System.in)
 
diff --git a/test/files/shootout/regexdna.scala.runner b/test/files/shootout/regexdna.scala.runner
index 08bcf43..adcf2c1 100644
--- a/test/files/shootout/regexdna.scala.runner
+++ b/test/files/shootout/regexdna.scala.runner
@@ -1,7 +1,7 @@
 object Test extends Application {
-  val base = System.getProperty("scalatest.cwd")+java.io.File.separator+"regexdna-input"
+  val base = System.getProperty("partest.cwd")+java.io.File.separator+"regexdna-input"
   for (n <- List(100000,300000,500000)) {
     System.setIn(new java.io.FileInputStream(base+n+".txt"))
     regexdna.main(Array(n.toString)) 
   }
-}
\ No newline at end of file
+}
diff --git a/test/files/shootout/strcat.scala.runner b/test/files/shootout/strcat.scala.runner
index 20bae3c..0f496b8 100644
--- a/test/files/shootout/strcat.scala.runner
+++ b/test/files/shootout/strcat.scala.runner
@@ -1,3 +1,3 @@
 object Test extends Application {
   for(val n <- List(10000,20000,30000,40000)) strcat.main(Array(n.toString)) 
-}
\ No newline at end of file
+}
diff --git a/test/files/shootout/sumcol.scala-2.scala.runner b/test/files/shootout/sumcol.scala-2.scala.runner
index 676c4ef..d47d366 100644
--- a/test/files/shootout/sumcol.scala-2.scala.runner
+++ b/test/files/shootout/sumcol.scala-2.scala.runner
@@ -1,6 +1,6 @@
 object Test extends Application {
   for(val n <- List(400,700,1000,8000)) {
-    System.setIn(new java.io.FileInputStream(System.getProperty("scalatest.cwd")+"/sumcol-input.txt"))
+    System.setIn(new java.io.FileInputStream(System.getProperty("partest.cwd")+"/sumcol-input.txt"))
     sumcol.main(Array(n.toString)) 
   }
-}
\ No newline at end of file
+}
diff --git a/test/files/shootout/sumcol.scala.runner b/test/files/shootout/sumcol.scala.runner
index 676c4ef..d47d366 100644
--- a/test/files/shootout/sumcol.scala.runner
+++ b/test/files/shootout/sumcol.scala.runner
@@ -1,6 +1,6 @@
 object Test extends Application {
   for(val n <- List(400,700,1000,8000)) {
-    System.setIn(new java.io.FileInputStream(System.getProperty("scalatest.cwd")+"/sumcol-input.txt"))
+    System.setIn(new java.io.FileInputStream(System.getProperty("partest.cwd")+"/sumcol-input.txt"))
     sumcol.main(Array(n.toString)) 
   }
-}
\ No newline at end of file
+}
diff --git a/test/files/shootout/takfp.scala.runner b/test/files/shootout/takfp.scala.runner
index ee592a0..105e8d7 100644
--- a/test/files/shootout/takfp.scala.runner
+++ b/test/files/shootout/takfp.scala.runner
@@ -1,3 +1,3 @@
 object Test extends Application {
   for(val n <- List(8,9,10)) takfp.main(Array(n.toString)) 
-}
\ No newline at end of file
+}
diff --git a/test/long-running/jvm/memleak2_actor.scala b/test/long-running/jvm/memleak2_actor.scala
new file mode 100644
index 0000000..1673b12
--- /dev/null
+++ b/test/long-running/jvm/memleak2_actor.scala
@@ -0,0 +1,39 @@
+import scala.actors._
+import Actor._
+
+case object Start
+case object EndMe
+
+class A extends Actor {
+  def act = loop {
+    react {
+      case Start =>
+      case EndMe =>
+        exit()
+    }
+  }
+}
+
+object Test {
+
+  def z(in: Long) = if (in / 1024L == 0L) in
+                    else if (in / (1024L * 1024L) == 0L) (in / 1024L).toString + "K"
+                    else (in / (1024L * 1024L)).toString + "M"
+
+  def main(args: Array[String]) {
+    val rt = Runtime.getRuntime()
+    for (o <- 1 to 300000) {
+      println("Outer [2AN] "+o)
+      var a: List[A] = Nil
+      for (i <- 1 to 10000) {
+        var t = new A
+        a = t :: a
+        t.start
+        t ! Start
+      }
+      for (act <- a) act ! EndMe
+      //rt.gc()
+      println("Free "+z(rt.freeMemory())+" total "+z(rt.totalMemory()))
+    }
+  }
+}
diff --git a/test/partest b/test/partest
old mode 100644
new mode 100755
index 2d89d3e..1e7da8b
--- a/test/partest
+++ b/test/partest
@@ -1,9 +1,9 @@
 #!/bin/sh
 
 ##############################################################################
-# Scala test runner 2.7.0-final
+# Scala test runner 2.8.0
 ##############################################################################
-# (c) 2002-2009 LAMP/EPFL
+# (c) 2002-2010 LAMP/EPFL
 #
 # This is free software; see the distribution for copying conditions.
 # There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A
@@ -30,8 +30,12 @@ while [ -h "$SOURCE" ]; do
         SOURCE=`dirname "$SOURCE"`/${TARGET:-.};
     fi;
 done;
-SCALA_HOME=`dirname "$SOURCE"`/..;
-SCALA_HOME=`cd "$SCALA_HOME"; pwd`;
+
+# see #2092
+SCALA_HOME=`dirname "$SOURCE"`
+SCALA_HOME=`cd "$SCALA_HOME"; pwd -P`
+SCALA_HOME=`cd "$SCALA_HOME"/..; pwd`
+
 if $cygwin; then
     SCALA_HOME=`cygpath --windows --short-name "$SCALA_HOME"`
     SCALA_HOME=`cygpath --unix "$SCALA_HOME"`
@@ -41,7 +45,7 @@ fi
 EXT_CLASSPATH=""
 if [ -z "$EXT_CLASSPATH" ] ; then
     if [ -f "$SCALA_HOME/lib/scala-partest.jar" ] ; then
-        for ext in `ls -d "$SCALA_HOME"/lib/*` ; do
+        for ext in "$SCALA_HOME"/lib/* ; do
             if [ -z "$EXT_CLASSPATH" ] ; then
                 EXT_CLASSPATH="$ext"
             else
@@ -71,7 +75,12 @@ if $cygwin; then
 fi
 
 # Reminder: substitution ${JAVA_OPTS:=-Xmx256M -Xms16M} DO NOT work on Solaris
-[ -n "$JAVA_OPTS" ] || JAVA_OPTS="-Xmx256M -Xms16M"
+[ -n "$JAVA_OPTS" ] || JAVA_OPTS="-Xmx512M -Xms16M"
 [ -n "$SCALAC_OPTS" ] || SCALAC_OPTS="-deprecation"
 
-${JAVACMD:=java} $JAVA_OPTS -cp "$EXT_CLASSPATH" -Dpartest.debug="${PARTEST_DEBUG}" -Dscala.home="${SCALA_HOME}" -Dscalatest.javacmd="${JAVACMD}" -Dscalatest.java_opts="${JAVA_OPTS}" -Dscalatest.scalac_opts="${SCALAC_OPTS}" -Dscalatest.javac_cmd="${JAVA_HOME}/bin/javac" scala.tools.partest.nest.NestRunner  "$@"
+partestDebugStr=""
+if [ ! -z "${PARTEST_DEBUG}" ] ; then
+  partestDebugStr="-Dpartest.debug=${PARTEST_DEBUG}"
+fi
+
+${JAVACMD:=java} $JAVA_OPTS -cp "$EXT_CLASSPATH" ${partestDebugStr} -Dscala.home="${SCALA_HOME}" -Dpartest.javacmd="${JAVACMD}" -Dpartest.java_opts="${JAVA_OPTS}" -Dpartest.scalac_opts="${SCALAC_OPTS}" -Dpartest.javac_cmd="${JAVA_HOME}/bin/javac" scala.tools.partest.nest.NestRunner  "$@"
diff --git a/test/partest-tests/jvm/actor-receivewithin.check b/test/partest-tests/jvm/actor-receivewithin.check
new file mode 100644
index 0000000..a6a3e88
--- /dev/null
+++ b/test/partest-tests/jvm/actor-receivewithin.check
@@ -0,0 +1,16 @@
+'msg
+'msg
+'msg
+'msg
+'msg
+TIMEOUT
+TIMEOUT
+TIMEOUT
+TIMEOUT
+TIMEOUT
+'msg2
+'msg2
+'msg2
+'msg2
+'msg2
+TIMEOUT
diff --git a/test/partest-tests/jvm/actor-receivewithin.scala b/test/partest-tests/jvm/actor-receivewithin.scala
new file mode 100644
index 0000000..a5c87c2
--- /dev/null
+++ b/test/partest-tests/jvm/actor-receivewithin.scala
@@ -0,0 +1,69 @@
+import scala.actors.{Actor, TIMEOUT}
+
+object A extends Actor {
+  def act() {
+    receive {
+      case 'done =>
+        var cnt = 0
+        while (cnt < 500) {
+          cnt += 1
+          receiveWithin (0) {
+            case 'msg =>
+              if (cnt % 100 == 0)
+                println("'msg")
+            case TIMEOUT =>
+              // should not happen
+              println("FAIL1")
+          }
+        }
+        cnt = 0
+        while (cnt < 500) {
+          cnt += 1
+          receiveWithin (0) {
+            case 'msg =>
+              // should not happen
+              println("FAIL2")
+            case TIMEOUT =>
+              if (cnt % 100 == 0)
+                println("TIMEOUT")
+          }
+        }
+        B ! 'next
+        receive { case 'done => }
+        cnt = 0
+        while (cnt < 501) {
+          cnt += 1
+          receiveWithin (500) {
+            case 'msg2 =>
+              if (cnt % 100 == 0)
+                println("'msg2")
+            case TIMEOUT =>
+              println("TIMEOUT")
+          }
+        }
+    }
+  }
+}
+
+object B extends Actor {
+  def act() {
+    A.start()
+    for (_ <- 1 to 500) {
+      A ! 'msg
+    }
+    A ! 'done
+    receive {
+      case 'next =>
+        for (_ <- 1 to 500) {
+          A ! 'msg2
+        }
+        A ! 'done
+    }
+  }
+}
+
+object Test {
+  def main(args:Array[String]) {
+    B.start()
+  }
+}
diff --git a/test/partest-tests/run/crash.scala b/test/partest-tests/run/crash.scala
new file mode 100644
index 0000000..1735cc4
--- /dev/null
+++ b/test/partest-tests/run/crash.scala
@@ -0,0 +1,6 @@
+object Test {
+  def main(args: Array[String]): Unit = {
+    val t = new Throwable("DOOM")
+    throw t
+  }
+}
diff --git a/test/partest-tests/run/streamWithFilter.check b/test/partest-tests/run/streamWithFilter.check
new file mode 100644
index 0000000..6b0e91a
--- /dev/null
+++ b/test/partest-tests/run/streamWithFilter.check
@@ -0,0 +1,5 @@
+15
+30
+45
+60
+75
diff --git a/test/partest-tests/run/streamWithFilter.scala b/test/partest-tests/run/streamWithFilter.scala
new file mode 100644
index 0000000..7f8f9a0
--- /dev/null
+++ b/test/partest-tests/run/streamWithFilter.scala
@@ -0,0 +1,11 @@
+object Test {
+  val nums = Stream.from(1)
+  def isFizz(x: Int) = x % 3 == 0
+  def isBuzz(x: Int) = x % 5 == 0
+  // next line will run forever if withFilter isn't doing its thing.
+  val fizzbuzzes = for (n <- nums ; if isFizz(n) ; if isBuzz(n)) yield n
+  
+  def main(args: Array[String]): Unit = {
+    fizzbuzzes take 5 foreach println
+  }
+}
diff --git a/test/partest-tests/run/timeout.scala b/test/partest-tests/run/timeout.scala
new file mode 100644
index 0000000..91417b3
--- /dev/null
+++ b/test/partest-tests/run/timeout.scala
@@ -0,0 +1,5 @@
+object Test {
+  def main(args: Array[String]): Unit = {
+    Thread.sleep(10000000)
+  }
+}
diff --git a/test/partest.bat b/test/partest.bat
index aea95fc..39fe830 100644
--- a/test/partest.bat
+++ b/test/partest.bat
@@ -3,7 +3,7 @@
 rem ##########################################################################
 rem # Scala code runner 2.7.0-final
 rem ##########################################################################
-rem # (c) 2002-2009 LAMP/EPFL
+rem # (c) 2002-2010 LAMP/EPFL
 rem #
 rem # This is free software; see the distribution for copying conditions.
 rem # There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A
@@ -53,7 +53,7 @@ if "%_EXTENSION_CLASSPATH%"=="" (
   )
 )
 
-set _PROPS=-Dscala.home="%_SCALA_HOME%" -Dscalatest.javacmd="%_JAVACMD%" -Dscalatest.java_options="%_JAVA_OPTS%" -Dscalatest.scalac_options="%_SCALAC_OPTS%" -Dscalatest.javac_cmd="%JAVA_HOME%\bin\javac"
+set _PROPS=-Dscala.home="%_SCALA_HOME%" -Dpartest.javacmd="%_JAVACMD%" -Dpartest.java_options="%_JAVA_OPTS%" -Dpartest.scalac_options="%_SCALAC_OPTS%" -Dpartest.javac_cmd="%JAVA_HOME%\bin\javac"
 
 rem echo %_JAVACMD% %_JAVA_OPTS% %_PROPS% -cp "%_EXTENSION_CLASSPATH%" scala.tools.partest.nest.NestRunner %_ARGS%
 %_JAVACMD% %_JAVA_OPTS% %_PROPS% -cp "%_EXTENSION_CLASSPATH%" scala.tools.partest.nest.NestRunner %_ARGS%
diff --git a/test/partestall b/test/partestall
deleted file mode 100644
index a1f585e..0000000
--- a/test/partestall
+++ /dev/null
@@ -1,8 +0,0 @@
-scala -cp ~/scala/build/quick/lib/partest:$HOME/scala/build/quick/lib/actors scala.tools.partest.nest.NestRunner --run
-scala -cp ~/scala/build/quick/lib/partest:$HOME/scala/build/quick/lib/actors scala.tools.partest.nest.NestRunner --jvm
-scala -cp ~/scala/build/quick/lib/partest:$HOME/scala/build/quick/lib/actors scala.tools.partest.nest.NestRunner --jvm5
-scala -cp ~/scala/build/quick/lib/partest:$HOME/scala/build/quick/lib/actors scala.tools.partest.nest.NestRunner --pos
-scala -cp ~/scala/build/quick/lib/partest:$HOME/scala/build/quick/lib/actors scala.tools.partest.nest.NestRunner --neg
-scala -cp ~/scala/build/quick/lib/partest:$HOME/scala/build/quick/lib/actors scala.tools.partest.nest.NestRunner --shootout
-sh scalatest --res
-sh scalatest --script
diff --git a/test/partestall.bat b/test/partestall.bat
deleted file mode 100644
index b8b8155..0000000
--- a/test/partestall.bat
+++ /dev/null
@@ -1,7 +0,0 @@
-scala -cp C:\scala\build\quick\lib\partest;C:\scala\build\quick\lib\actors scala.tools.partest.nest.NestRunner --run
-scala -cp C:\scala\build\quick\lib\partest;C:\scala\build\quick\lib\actors scala.tools.partest.nest.NestRunner --jvm
-scala -cp C:\scala\build\quick\lib\partest;C:\scala\build\quick\lib\actors scala.tools.partest.nest.NestRunner --jvm5
-scala -cp C:\scala\build\quick\lib\partest;C:\scala\build\quick\lib\actors scala.tools.partest.nest.NestRunner --pos
-scala -cp C:\scala\build\quick\lib\partest;C:\scala\build\quick\lib\actors scala.tools.partest.nest.NestRunner --neg
-scala -cp C:\scala\build\quick\lib\partest;C:\scala\build\quick\lib\actors scala.tools.partest.nest.NestRunner --shootout
-
diff --git a/test/pending/buildmanager/t2443/BitSet.scala b/test/pending/buildmanager/t2443/BitSet.scala
new file mode 100644
index 0000000..8d7c8dc
--- /dev/null
+++ b/test/pending/buildmanager/t2443/BitSet.scala
@@ -0,0 +1,2 @@
+import scala.collection.BitSet
+//class BitSet
diff --git a/test/pending/buildmanager/t2443/t2443.changes/BitSet2.scala b/test/pending/buildmanager/t2443/t2443.changes/BitSet2.scala
new file mode 100644
index 0000000..27a5d4d
--- /dev/null
+++ b/test/pending/buildmanager/t2443/t2443.changes/BitSet2.scala
@@ -0,0 +1 @@
+import scala.collection.BitSet
diff --git a/test/pending/buildmanager/t2443/t2443.check b/test/pending/buildmanager/t2443/t2443.check
new file mode 100644
index 0000000..dd88e1c
--- /dev/null
+++ b/test/pending/buildmanager/t2443/t2443.check
@@ -0,0 +1,6 @@
+builder > BitSet.scala
+compiling Set(BitSet.scala)
+builder > BitSet.scala
+Changes: Map(class BitSet -> List(Removed(Class(BitSet))))
+
+
diff --git a/test/pending/buildmanager/t2443/t2443.test b/test/pending/buildmanager/t2443/t2443.test
new file mode 100644
index 0000000..a1d61ff
--- /dev/null
+++ b/test/pending/buildmanager/t2443/t2443.test
@@ -0,0 +1,3 @@
+>>compile BitSet.scala
+>>update BitSet.scala=>BitSet2.scala
+>>compile BitSet.scala
diff --git a/test/pending/continuations-run/example0.scala b/test/pending/continuations-run/example0.scala
new file mode 100644
index 0000000..de5ea54
--- /dev/null
+++ b/test/pending/continuations-run/example0.scala
@@ -0,0 +1,9 @@
+// $Id$
+
+object Test {
+  
+  def main(args: Array[String]): Any = {
+    examples.continuations.Test0.main(args)
+  }
+  
+}
\ No newline at end of file
diff --git a/test/pending/continuations-run/example1.scala b/test/pending/continuations-run/example1.scala
new file mode 100644
index 0000000..e31d6af
--- /dev/null
+++ b/test/pending/continuations-run/example1.scala
@@ -0,0 +1,9 @@
+// $Id$
+
+object Test {
+  
+  def main(args: Array[String]): Any = {
+    examples.continuations.Test1.main(args)
+  }
+  
+}
\ No newline at end of file
diff --git a/test/pending/continuations-run/example16.scala b/test/pending/continuations-run/example16.scala
new file mode 100644
index 0000000..561f0ab
--- /dev/null
+++ b/test/pending/continuations-run/example16.scala
@@ -0,0 +1,9 @@
+// $Id$
+
+object Test {
+  
+  def main(args: Array[String]): Any = {
+    examples.continuations.Test16Printf.main(args)
+  }
+  
+}
\ No newline at end of file
diff --git a/test/pending/continuations-run/example2.scala b/test/pending/continuations-run/example2.scala
new file mode 100644
index 0000000..730f7cc
--- /dev/null
+++ b/test/pending/continuations-run/example2.scala
@@ -0,0 +1,9 @@
+// $Id$
+
+object Test {
+  
+  def main(args: Array[String]): Any = {
+    examples.continuations.Test2.main(args)
+  }
+  
+}
\ No newline at end of file
diff --git a/test/pending/continuations-run/example3.scala b/test/pending/continuations-run/example3.scala
new file mode 100644
index 0000000..41cf1cc
--- /dev/null
+++ b/test/pending/continuations-run/example3.scala
@@ -0,0 +1,9 @@
+// $Id$
+
+object Test {
+  
+  def main(args: Array[String]): Any = {
+    examples.continuations.Test3.main(args)
+  }
+  
+}
\ No newline at end of file
diff --git a/test/pending/continuations-run/example4.scala b/test/pending/continuations-run/example4.scala
new file mode 100644
index 0000000..adcc7aa
--- /dev/null
+++ b/test/pending/continuations-run/example4.scala
@@ -0,0 +1,9 @@
+// $Id$
+
+object Test {
+  
+  def main(args: Array[String]): Any = {
+    examples.continuations.Test4.main(args)
+  }
+  
+}
\ No newline at end of file
diff --git a/test/pending/continuations-run/example5.scala b/test/pending/continuations-run/example5.scala
new file mode 100644
index 0000000..241e8cd
--- /dev/null
+++ b/test/pending/continuations-run/example5.scala
@@ -0,0 +1,9 @@
+// $Id$
+
+object Test {
+  
+  def main(args: Array[String]): Any = {
+    examples.continuations.Test5.main(args)
+  }
+  
+}
\ No newline at end of file
diff --git a/test/pending/continuations-run/example6.scala b/test/pending/continuations-run/example6.scala
new file mode 100644
index 0000000..00f84fc
--- /dev/null
+++ b/test/pending/continuations-run/example6.scala
@@ -0,0 +1,9 @@
+// $Id$
+
+object Test {
+  
+  def main(args: Array[String]): Any = {
+    examples.continuations.Test6.main(args)
+  }
+  
+}
\ No newline at end of file
diff --git a/test/pending/continuations-run/example7.scala b/test/pending/continuations-run/example7.scala
new file mode 100644
index 0000000..64abc6d
--- /dev/null
+++ b/test/pending/continuations-run/example7.scala
@@ -0,0 +1,9 @@
+// $Id$
+
+object Test {
+  
+  def main(args: Array[String]): Any = {
+    examples.continuations.Test7.main(args)
+  }
+  
+}
\ No newline at end of file
diff --git a/test/pending/continuations-run/example8.scala b/test/pending/continuations-run/example8.scala
new file mode 100644
index 0000000..a5f953d
--- /dev/null
+++ b/test/pending/continuations-run/example8.scala
@@ -0,0 +1,9 @@
+// $Id$
+
+object Test {
+  
+  def main(args: Array[String]): Any = {
+    examples.continuations.Test8.main(args)
+  }
+  
+}
\ No newline at end of file
diff --git a/test/pending/continuations-run/example9.scala b/test/pending/continuations-run/example9.scala
new file mode 100644
index 0000000..09d792c
--- /dev/null
+++ b/test/pending/continuations-run/example9.scala
@@ -0,0 +1,9 @@
+// $Id$
+
+object Test {
+  
+  def main(args: Array[String]): Any = {
+    examples.continuations.Test9Monads.main(args)
+  }
+  
+}
\ No newline at end of file
diff --git a/test/pending/continuations-run/foreach.check b/test/pending/continuations-run/foreach.check
new file mode 100644
index 0000000..9bab7a2
--- /dev/null
+++ b/test/pending/continuations-run/foreach.check
@@ -0,0 +1,4 @@
+1
+2
+3
+enough is enough
\ No newline at end of file
diff --git a/test/pending/continuations-run/foreach.scala b/test/pending/continuations-run/foreach.scala
new file mode 100644
index 0000000..76823e7
--- /dev/null
+++ b/test/pending/continuations-run/foreach.scala
@@ -0,0 +1,33 @@
+// $Id$
+
+import scala.util.continuations._
+
+import scala.util.continuations.Loops._
+
+object Test {
+  
+  def main(args: Array[String]): Any = {
+    
+    
+    reset {
+      
+      val list = List(1,2,3,4,5)
+      
+      for (x <- list.suspendable) {
+        
+        shift { k: (Unit => Unit) =>
+          println(x)
+          if (x < 3)
+            k()
+          else
+            println("enough is enough")
+        }
+        
+      }
+      
+    }
+    
+    
+  }
+  
+}
\ No newline at end of file
diff --git a/test/pending/jvm/actor-executor4.check b/test/pending/jvm/actor-executor4.check
new file mode 100644
index 0000000..da78f45
--- /dev/null
+++ b/test/pending/jvm/actor-executor4.check
@@ -0,0 +1,21 @@
+Two: OK
+One: OK
+Two: OK
+One: OK
+Two: OK
+One: OK
+Two: OK
+One: OK
+Two: OK
+One: OK
+Two: OK
+One: OK
+Two: OK
+One: OK
+Two: OK
+One: OK
+Two: OK
+One: OK
+Two: OK
+One: OK
+One exited
diff --git a/test/pending/jvm/actor-executor4.scala b/test/pending/jvm/actor-executor4.scala
new file mode 100644
index 0000000..a912d76
--- /dev/null
+++ b/test/pending/jvm/actor-executor4.scala
@@ -0,0 +1,64 @@
+import scala.actors.{Actor, Exit}
+import scala.actors.scheduler.ExecutorScheduler
+import java.util.concurrent.Executors
+
+object One extends AdaptedActor {
+  def act() {
+    Two.start()
+    var i = 0
+    loopWhile (i < Test.NUM_MSG) {
+      i += 1
+      Two ! 'MsgForTwo
+      react {
+        case 'MsgForOne =>
+          if (i % (Test.NUM_MSG/10) == 0)
+            println("One: OK")
+      }
+    }
+  }
+}
+
+object Two extends AdaptedActor {
+  def act() {
+    var i = 0
+    loopWhile (i < Test.NUM_MSG) {
+      i += 1
+      react {
+        case 'MsgForTwo =>
+          if (i % (Test.NUM_MSG/10) == 0)
+            println("Two: OK")
+          One ! 'MsgForOne
+      }
+    }
+  }
+}
+
+trait AdaptedActor extends Actor {
+  override def scheduler =
+    Test.scheduler
+}
+
+object Test {
+  val NUM_MSG = 100000
+
+  val scheduler =
+    ExecutorScheduler(
+      Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()),
+      false)
+
+  def main(args: Array[String]) {
+    (new AdaptedActor {
+      def act() {
+        trapExit = true
+        link(One)
+        One.start()
+
+        receive {
+          case Exit(from, reason) =>
+            println("One exited")
+            Test.scheduler.shutdown()
+        }
+      }
+    }).start()
+  }
+}
diff --git a/test/pending/jvm/actor-receive-sender.check b/test/pending/jvm/actor-receive-sender.check
new file mode 100644
index 0000000..2c94e48
--- /dev/null
+++ b/test/pending/jvm/actor-receive-sender.check
@@ -0,0 +1,2 @@
+OK
+OK
diff --git a/test/pending/jvm/actor-receive-sender.scala b/test/pending/jvm/actor-receive-sender.scala
new file mode 100644
index 0000000..ea7c40c
--- /dev/null
+++ b/test/pending/jvm/actor-receive-sender.scala
@@ -0,0 +1,51 @@
+import scala.actors.{Actor, TIMEOUT, Exit}
+import scala.actors.Actor._
+
+object Test {
+
+  val NUM = 2000
+
+  def main(args: Array[String]) {
+    var b: Actor = null
+    var c: Actor = null
+
+    val a = actor {
+      for (_ <- 0 until NUM)
+        receive {
+          case 'hello if sender == b => // do nothing
+        }
+      b ! 'ok
+      for (_ <- 0 until NUM)
+        receiveWithin (1000) {
+          case 'bye if sender == b => // do nothing
+          case TIMEOUT => b ! 'fail
+        }
+      b ! 'ok
+    }
+
+    b = actor {
+      self.trapExit = true
+      link(a)
+
+      for (_ <- 0 until NUM)
+        a ! 'hello
+
+      val proceed = receive {
+        case Exit(from, reason) => println("FAIL"); false
+        case 'ok                => println("OK"); true
+        case other              => println(other); false
+      }
+
+      if (proceed) {
+        for (_ <- 0 until NUM)
+          a ! 'bye
+        receive {
+          case Exit(from, reason) => println("FAIL")
+          case 'ok                => println("OK")
+          case other              => println(other)
+        }
+      }
+    }
+  }
+
+}
diff --git a/test/files/jvm/terminateLinked.check b/test/pending/jvm/actorgc_leak.check
similarity index 100%
copy from test/files/jvm/terminateLinked.check
copy to test/pending/jvm/actorgc_leak.check
diff --git a/test/pending/jvm/actorgc_leak.scala b/test/pending/jvm/actorgc_leak.scala
new file mode 100644
index 0000000..de3e04f
--- /dev/null
+++ b/test/pending/jvm/actorgc_leak.scala
@@ -0,0 +1,63 @@
+
+import scala.actors.Actor
+
+object Test {
+  class FatActorFactory extends Actor {
+    def act() {
+      var cnt = 0
+      Actor.loopWhile(cnt < fatActors) {
+	//if ((cnt % 5) == 0) println(cnt)
+	val fa = new FatActor()
+	fa.start()
+	cnt += 1
+	if (cnt == fatActors) Monitor ! 'done
+      }
+    }
+  }
+  
+  class FatActor extends Actor {
+    def act() {
+      fat = new Array[Int](fatness)
+      react {
+	case 'hi => exit()
+      }
+    }
+    private var fat: Array[Int] = _
+  }
+
+  object Monitor extends Actor {
+    private var cnt = 0
+    def act() {
+      Actor.loop {
+	react {
+	  case 'done => {
+	    cnt += 1
+	    if (cnt == factories) System.exit(0) // once GC pressure stops FatActors stop being collected, and as
+	  }                                     // a result ActorGC never finds out that they are defunct
+	}
+      }
+    }
+  }
+
+  val factories = 4   // the number of factories to start
+  val fatActors = 50  // the number of FatActors for each factory to produce
+  val fatness = 1024*1024*10
+
+  def main(args: Array[String]) {
+    scala.actors.Scheduler.impl.shutdown()
+    val sched = {
+      val s = new scala.actors.FJTaskScheduler2
+      s.start()
+      s
+    }
+    scala.actors.Scheduler.impl = sched
+
+    Monitor.start()
+    for(i <- 1 to factories) {
+      //if ((i % 50) == 0) println(i)
+      val fa = new FatActorFactory()
+      fa.start()
+    }
+    println("Done")
+  }
+}
diff --git a/test/pending/jvm5/annotations.scala b/test/pending/jvm/annotations.scala
similarity index 100%
rename from test/pending/jvm5/annotations.scala
rename to test/pending/jvm/annotations.scala
diff --git a/test/pending/jvm/inner.scala b/test/pending/jvm/inner.scala
deleted file mode 100644
index d33cc47..0000000
--- a/test/pending/jvm/inner.scala
+++ /dev/null
@@ -1,126 +0,0 @@
-//############################################################################
-// Test Java interaction with scala inner classes
-//############################################################################
-// $Id: inner.scala 15964 2008-08-29 13:50:04Z cunei $
-
-import java.io.{BufferedReader, File, FileWriter, InputStreamReader}
-
-class A {
-  val abc = "A.abc"
-
-  protected class B(x: Int, y: String) {
-    println(abc); println(x)
-    println(y)
-  }
-
-  trait Itf {
-    def method1(x: Int): Int
-    
-    trait Itf2 extends Itf {
-      def method2: Unit
-    }
-  }
-
-  trait PlainTrait {
-    def method1(x: Int): Int
-  }
-
-  class Impl(a: Int) extends Itf {
-    def method1(x: Int) = {
-      println(x)
-      println(a)
-      x + a
-    }
-  }
-
-  class Impl2 extends Impl(1) with Itf#Itf2 {
-    def method2 = {
-      println(abc)
-    }
-  }
-
-  def newImpl: Itf = new Impl(1)
-  def newImpl2: Itf#Itf2 = new Impl2
-
-  class Outer1(arg1: Int) {
-    class Outer2(arg2: Int) {
-      class Outer3(arg3: Int) {
-        println("Outer3: " + arg1 + " " + arg2 + " " + arg3);
-      }
-    }
-  }
-}
-
-object Scalatest {
-  private val outputdir = System.getProperty("scalatest.output", "inner-jvm.obj")
-  private val scalalib  = System.getProperty("scalatest.lib", "")
-  private val classpath = outputdir + File.pathSeparator + scalalib
-  private val javabin  = {
-    val jhome = new File(System.getProperty("java.home"))
-    if (jhome.getName == "jre")
-      new File(jhome.getParent, "bin").getAbsolutePath
-    else
-      new File(jhome, "bin").getAbsolutePath
-  }
-  private val javacmd   = javabin + File.separator + "java"
-  private val javac     = javabin + File.separator + "javac"
-
-  def javac(src: String, fname: String) {
-    val tmpfilename = outputdir + File.separator + fname
-    val tmpfile = new FileWriter(tmpfilename)
-    tmpfile.write(src)
-    tmpfile.close
-    exec(javac + " -d " + outputdir + " -classpath " + classpath + " " + tmpfilename)
-  }
-
-  def java(cname: String) =
-    exec(javacmd + " -cp " + classpath + " " + cname)
-
-  /** Execute cmd, wait for the process to end and pipe it's output to stdout */
-  private def exec(cmd: String) {
-    val proc = Runtime.getRuntime().exec(cmd)
-    val inp = new BufferedReader(new InputStreamReader(proc.getInputStream))
-    val errp = new BufferedReader(new InputStreamReader(proc.getErrorStream))
-    proc.waitFor()
-    while (inp.ready) println(inp.readLine())
-    while (errp.ready) println(errp.readLine())
-  }
-}
-
-object Test {
-  def main(args: Array[String]) {
-    val javaInteraction = """
-public class JavaInteraction {
-    public static void main(String[] args) {
-        A a = new A();
-        A.B b = a.new B(1, "Hello");
-
-        A.Itf itf = a.newImpl();
-        itf.method1(1);
-
-        A.Itf.Itf2 itf2 = a.newImpl2();
-        itf2.method2();
-
-        A.Outer1 o1 = a.new Outer1(1);
-        A.Outer1.Outer2 o2 = o1.new Outer2(2);
-        A.Outer1.Outer2.Outer3 or = o2.new Outer3(3);
-    }
-}
-"""
-    Scalatest.javac(javaInteraction, "JavaInteraction.java")
-    Scalatest.java("JavaInteraction")
-
-    val accessingScala = """
-public class AccessingScala {
-    public static void main(String[] args) {
-        A a = new A();
-        System.out.println(a.abc());
-    }
-}
-"""
-    Scalatest.javac(accessingScala, "AccessingScala.java")
-    Scalatest.java("AccessingScala")
-  }
-}
-
-//############################################################################
diff --git a/test/pending/jvm/reactWithinZero.check b/test/pending/jvm/reactWithinZero.check
new file mode 100644
index 0000000..cf2a2fa
--- /dev/null
+++ b/test/pending/jvm/reactWithinZero.check
@@ -0,0 +1,2 @@
+TIMEOUT
+'ack
diff --git a/test/pending/jvm/reactWithinZero.scala b/test/pending/jvm/reactWithinZero.scala
new file mode 100644
index 0000000..0786ce2
--- /dev/null
+++ b/test/pending/jvm/reactWithinZero.scala
@@ -0,0 +1,18 @@
+import scala.actors.{Actor, TIMEOUT}
+
+class A extends Actor {
+  def act() = reactWithin(0) {
+    case TIMEOUT =>
+      println("TIMEOUT")
+      reply('ack)
+      act()
+    case x => println(x)
+  }
+}
+
+object Test {
+  def main(args: Array[String]): Unit = {
+    val a = new A
+    a.start()
+  }
+}
diff --git a/test/pending/jvm/receiveWithinZero.check b/test/pending/jvm/receiveWithinZero.check
new file mode 100644
index 0000000..cf2a2fa
--- /dev/null
+++ b/test/pending/jvm/receiveWithinZero.check
@@ -0,0 +1,2 @@
+TIMEOUT
+'ack
diff --git a/test/pending/jvm/receiveWithinZero.scala b/test/pending/jvm/receiveWithinZero.scala
new file mode 100644
index 0000000..315dd9c
--- /dev/null
+++ b/test/pending/jvm/receiveWithinZero.scala
@@ -0,0 +1,18 @@
+import scala.actors.{Actor, TIMEOUT}
+
+class A extends Actor {
+  def act() = receiveWithin(0) {
+    case TIMEOUT =>
+      println("TIMEOUT")
+      reply('ack)
+      act()
+    case x => println(x)
+  }
+}
+
+object Test {
+  def main(args: Array[String]): Unit = {
+    val a = new A
+    a.start()
+  }
+}
diff --git a/test/pending/jvm/serialization.check b/test/pending/jvm/serialization.check
index 144e316..397578b 100644
--- a/test/pending/jvm/serialization.check
+++ b/test/pending/jvm/serialization.check
@@ -1,10 +1,15 @@
+x0 = List(1, 2, 3)
+y0 = List(1, 2, 3)
+x0 eq y0: false, y0 eq x0: false
+x0 equals y0: true, y0 equals x0: true
+
 x1 = List()
 y1 = List()
-x1 eq y1: true - y1 eq x1: true
+x1 eq y1: true, y1 eq x1: true
 
 x2 = None
 y2 = None
-x2 eq y2: true - y2 eq x2: true
+x2 eq y2: true, y2 eq x2: true
 
 x3 = Array[1,2,3]
 y3 = Array[1,2,3]
@@ -14,73 +19,120 @@ x4 = <na>
 y4 = <na>
 x4(2): 4 - y4(2): 4
 
+x5 = 'hello
+y5 = 'hello
+x5 eq y5: true, y5 eq x5: true
+x5 equals y5: true, y5 equals x5: true
+
+x6 = (BannerLimit,12345)
+y6 = (BannerLimit,12345)
+x6 eq y6: false, y6 eq x6: false
+x6 equals y6: true, y6 equals x6: true
+
+x7 = RoundingMode
+y7 = RoundingMode
+x7 eq y7: true, y7 eq x7: true
+x7 equals y7: true, y7 equals x7: true
+
+x8 = WeekDay
+y8 = WeekDay
+x8 eq y8: true, y8 eq x8: true
+x8 equals y8: true, y8 equals x8: true
+
+x9 = UP
+y9 = UP
+x9 eq y9: true, y9 eq x9: true
+x9 equals y9: true, y9 equals x9: true
+
+x10 = WeekDay(0)
+y10 = WeekDay(0)
+x10 eq y10: true, y10 eq x10: true
+x10 equals y10: true, y10 equals x10: true
+
+x9 eq x10: false, x10 eq x9: false
+x9 equals x10: false, x10 equals x9: false
+x9 eq y10: false, y10 eq x9: false
+x9 equals y10: false, y10 equals x9: false
+
 x = List((buffers,20), (layers,2), (title,3))
 y = List((buffers,20), (layers,2), (title,3))
-x equals y: true - y equals x: true
+x equals y: true, y equals x: true
+
+x = Map(2 -> C, 1 -> B, 0 -> A)
+y = Map(2 -> C, 1 -> B, 0 -> A)
+x equals y: true, y equals x: true
 
 x = Map(buffers -> 20, layers -> 2, title -> 3)
 y = Map(buffers -> 20, layers -> 2, title -> 3)
-x equals y: true - y equals x: true
+x equals y: true, y equals x: true
 
 x = Set(2, 3)
 y = Set(2, 3)
-x equals y: true - y equals x: true
+x equals y: true, y equals x: true
 
 x = Set(5, 3)
 y = Set(5, 3)
-x equals y: true - y equals x: true
+x equals y: true, y equals x: true
 
-x = Queue(a,b,c)
-y = Queue(a,b,c)
-x equals y: true - y equals x: true
+x = Queue(a, b, c)
+y = Queue(a, b, c)
+x equals y: true, y equals x: true
 
-x = Stack(c, b, a)
-y = Stack(c, b, a)
-x equals y: true - y equals x: true
+x = Stack(a, b, c)
+y = Stack(a, b, c)
+x equals y: true, y equals x: true
 
 x = Map(42 -> FortyTwo)
 y = Map(42 -> FortyTwo)
-x equals y: true - y equals x: true
+x equals y: true, y equals x: true
 
-x = Set(0, 2)
-y = Set(0, 2)
-x equals y: true - y equals x: true
+x = TreeSet(0, 2)
+y = TreeSet(0, 2)
+x equals y: true, y equals x: true
+
+x = Vector(1, 2, 3)
+y = Vector(1, 2, 3)
+x equals y: true, y equals x: true
 
 x = ArrayBuffer(one, two)
 y = ArrayBuffer(one, two)
-x equals y: true - y equals x: true
+x equals y: true, y equals x: true
 
 x = Map(title -> 3, buffers -> 20, layers -> 2)
 y = Map(title -> 3, buffers -> 20, layers -> 2)
-x equals y: true - y equals x: true
+x equals y: true, y equals x: true
 
 x = Set(0, 8, 9)
 y = Set(0, 8, 9)
-x equals y: true - y equals x: true
+x equals y: true, y equals x: true
 
 x = Set(layers, buffers, title)
 y = Set(layers, buffers, title)
-x equals y: true - y equals x: true
+x equals y: true, y equals x: true
 
 x = LinkedList(2, 3)
 y = LinkedList(2, 3)
-x equals y: true - y equals x: true
+x equals y: true, y equals x: true
 
 x = Queue(20, 2, 3)
 y = Queue(20, 2, 3)
-x equals y: true - y equals x: true
+x equals y: true, y equals x: true
 
-x = Stack(20, 2, 3)
-y = Stack(20, 2, 3)
-x equals y: true - y equals x: true
+x = Stack(3, 2, 20)
+y = Stack(3, 2, 20)
+x equals y: true, y equals x: true
 
 x = ListBuffer(white, black)
 y = ListBuffer(white, black)
-x equals y: true - y equals x: true
+x equals y: true, y equals x: true
+
+x = History((Feed,hello))
+y = History((Feed,hello))
+x equals y: true, y equals x: true
 
 x = <html><title>title</title><body></body></html>
 y = <html><title>title</title><body></body></html>
-x equals y: true - y equals x: true
+x equals y: true, y equals x: true
 
 x = <html>
       <body>
@@ -122,25 +174,25 @@ y = <html>
       </table>
       </body>
     </html>
-x equals y: true - y equals x: true
+x equals y: true, y equals x: true
 
 x = Tim
 y = Tim
-x equals y: true - y equals x: true
+x equals y: true, y equals x: true
 
 x = Bob
 y = Bob
-x equals y: true - y equals x: true
+x equals y: true, y equals x: true
 
 x = John
 y = John
-x equals y: true - y equals x: true
+x equals y: true, y equals x: true
 
 x = Bill
 y = Bill
-x equals y: true - y equals x: true
+x equals y: true, y equals x: true
 
 x = Paul
 y = Paul
-x equals y: true - y equals x: true
+x equals y: true, y equals x: true
 
diff --git a/test/pending/jvm/serialization.scala b/test/pending/jvm/serialization.scala
index 9e9d88a..ff9413a 100644
--- a/test/pending/jvm/serialization.scala
+++ b/test/pending/jvm/serialization.scala
@@ -1,19 +1,9 @@
 //############################################################################
 // Serialization
 //############################################################################
-// $Id: serialization.scala 13688 2008-01-11 08:45:47Z washburn $
 
 import java.lang.System
 
-object EqualityTest {
-  def check[A, B](x: A, y: B) {
-    println("x = " + x)
-    println("y = " + y)
-    println("x equals y: " + (x equals y) + " - y equals x: " + (y equals x))
-    println()
-  }
-}
-
 object Serialize {
   @throws(classOf[java.io.IOException])
   def write[A](o: A): Array[Byte] = {
@@ -30,48 +20,115 @@ object Serialize {
       new java.io.ObjectInputStream(new java.io.ByteArrayInputStream(buffer))
     in.readObject().asInstanceOf[A]
   }
+  def check[A, B](x: A, y: B) {
+    println("x = " + x)
+    println("y = " + y)
+    println("x equals y: " + (x equals y) + ", y equals x: " + (y equals x))
+    println()
+  }
 }
+import Serialize._
 
 //############################################################################
 // Test classes in package "scala"
 
- at serializable
 object Test1_scala {
 
   private def arrayToString[A](arr: Array[A]): String =
-    List.fromArray(arr).mkString("Array[",",","]")
+    arr.mkString("Array[",",","]")
+
+  private def arrayEquals[A, B](a1: Array[A], a2: Array[B]): Boolean =
+    (a1.length == a2.length) &&
+    (Iterator.range(0, a1.length) forall { i => a1(i) == a2(i) })
 
-  private def arrayEquals[A, B](a1: Array[A], a2: Array[B]) =
-     (a1.length == a2.length) &&
-     (Iterator.range(0, a1.length) forall { i => a1(i) == a2(i) })
+  @serializable
+  object WeekDay extends Enumeration {
+    type WeekDay = Value
+    val Monday, Tuesday, Wednesday, Thusday, Friday, Saturday, Sunday = Value
+  }
+  import WeekDay._, BigDecimal._, RoundingMode._
 
+  val x0 = List(1, 2, 3)
   val x1 = Nil
   val x2 = None
   val x3 = Array(1, 2, 3)
   val x4 = { x: Int => 2 * x }
+  val x5 = 'hello
+  val x6 = ("BannerLimit", 12345)
+  val x7 = BigDecimal.RoundingMode
+  val x8 = WeekDay
+  val x9 = UP      // named element
+  val x10 = Monday // unamed element
 
   try {
-    val y1: List[Nothing]      = Serialize.read(Serialize.write(x1))
-    val y2: Option[Nothing]    = Serialize.read(Serialize.write(x2))
-    val y3: Array[Int]         = Serialize.read(Serialize.write(x3))
-    val y4: Function[Int, Int] = Serialize.read(Serialize.write(x4))
-
+    val y0: List[Int]          = read(write(x0))
+    val y1: List[Nothing]      = read(write(x1))
+    val y2: Option[Nothing]    = read(write(x2))
+    val y3: Array[Int]         = read(write(x3))
+    val y4: Function[Int, Int] = read(write(x4))
+    val y5: Symbol             = read(write(x5))
+    val y6: (String, Int)      = read(write(x6))
+    val y7: RoundingMode.type  = read(write(x7))
+    val y8: WeekDay.type       = read(write(x8))
+    val y9: RoundingMode       = read(write(x9))
+    val y10: WeekDay           = read(write(x10))
+
+    println("x0 = " + x0)
+    println("y0 = " + y0)
+    println("x0 eq y0: " + (x0 eq y0) + ", y0 eq x0: " + (y0 eq x0))
+    println("x0 equals y0: " + (x0 equals y0) + ", y0 equals x0: " + (y0 equals x0))
+    println()
     println("x1 = " + x1)
     println("y1 = " + y1)
-    println("x1 eq y1: " + (x1 eq y1) + " - y1 eq x1: " + (y1 eq x1))
-    println
+    println("x1 eq y1: " + (x1 eq y1) + ", y1 eq x1: " + (y1 eq x1))
+    println()
     println("x2 = " + x2)
     println("y2 = " + y2)
-    println("x2 eq y2: " + (x2 eq y2) + " - y2 eq x2: " + (y2 eq x2))
-    println
+    println("x2 eq y2: " + (x2 eq y2) + ", y2 eq x2: " + (y2 eq x2))
+    println()
     println("x3 = " + arrayToString(x3))
     println("y3 = " + arrayToString(y3))
     println("arrayEquals(x3, y3): " + arrayEquals(x3, y3))
-    println
+    println()
     println("x4 = <na>")
     println("y4 = <na>")
     println("x4(2): " + x4(2) + " - y4(2): " + y4(2))
-    println
+    println()
+    println("x5 = " + x5)
+    println("y5 = " + y5)
+    println("x5 eq y5: " + (x5 eq y5) + ", y5 eq x5: " + (y5 eq x5))
+    println("x5 equals y5: " + (x5 equals y5) + ", y5 equals x5: " + (y5 equals x5))
+    println()
+    println("x6 = " + x6)
+    println("y6 = " + y6)
+    println("x6 eq y6: " + (x6 eq y6) + ", y6 eq x6: " + (y6 eq x6))
+    println("x6 equals y6: " + (x6 equals y6) + ", y6 equals x6: " + (y6 equals x6))
+    println()
+    println("x7 = " + x7)
+    println("y7 = " + y7)
+    println("x7 eq y7: " + (x7 eq y7) + ", y7 eq x7: " + (y7 eq x7))
+    println("x7 equals y7: " + (x7 equals y7) + ", y7 equals x7: " + (y7 equals x7))
+    println()
+    println("x8 = " + x8)
+    println("y8 = " + y8)
+    println("x8 eq y8: " + (x8 eq y8) + ", y8 eq x8: " + (y8 eq x8))
+    println("x8 equals y8: " + (x8 equals y8) + ", y8 equals x8: " + (y8 equals x8))
+    println()
+    println("x9 = " + x9)
+    println("y9 = " + y9)
+    println("x9 eq y9: " + (x9 eq y9) + ", y9 eq x9: " + (y9 eq x9))
+    println("x9 equals y9: " + (x9 equals y9) + ", y9 equals x9: " + (y9 equals x9))
+    println()
+    println("x10 = " + x10)
+    println("y10 = " + y10)
+    println("x10 eq y10: " + (x10 eq y10) + ", y10 eq x10: " + (y10 eq x10))
+    println("x10 equals y10: " + (x10 equals y10) + ", y10 equals x10: " + (y10 equals x10))
+    println()
+    println("x9 eq x10: " + (x9 eq x10) + ", x10 eq x9: " + (x10 eq x9))
+    println("x9 equals x10: " + (x9 equals x10) + ", x10 equals x9: " + (x10 equals x9))
+    println("x9 eq y10: " + (x9 eq y10) + ", y10 eq x9: " + (y10 eq x9))
+    println("x9 equals y10: " + (x9 equals y10) + ", y10 equals x9: " + (y10 equals x9))
+    println()
   }
   catch {
     case e: Exception =>
@@ -86,18 +143,17 @@ object Test1_scala {
 @serializable
 object Test2_immutable {
   import scala.collection.immutable.{
-    BitSet, ListMap, ListSet, Queue, Stack, TreeSet, TreeMap}
+    BitSet, HashMap, ListMap, ListSet, Queue, Stack, TreeSet, TreeMap, Vector}
 
   val x1 = List(
-    Pair("buffers", 20),
-    Pair("layers", 2),
-    Pair("title", 3)
+    ("buffers", 20),
+    ("layers", 2),
+    ("title", 3)
   )
 
-  val x2 = new ListMap[String, Int]
-    .incl(Pair("buffers", 20))
-    .incl(Pair("layers", 2))
-    .incl(Pair("title", 3))
+  val m1 = new HashMap[Int, String] + (0 -> "A", 1 -> "B", 2 -> "C")
+
+  val x2 = new ListMap[String, Int] + ("buffers" -> 20, "layers" -> 2, "title" -> 3)
 
   val x3 = {
     val bs = new collection.mutable.BitSet()
@@ -105,34 +161,40 @@ object Test2_immutable {
     bs.toImmutable
   }
 
-  val x4 = new ListSet[Int]().incl(3).incl(5)
+  val x4 = new ListSet[Int]() + 3 + 5
+
+  val x5 = Queue("a", "b", "c")
 
-  val x5 = new Queue("a", "b", "c")
+  val x6 = Stack("a", "b", "c")
 
-  val x6 = new Stack().push("a", "b", "c")
+  val x7 = new TreeMap[Int, String] + (42 -> "FortyTwo")
 
-  val x7 = new TreeMap[Int, String] + 42 -> "FortyTwo"
+  val x8 = new TreeSet[Int]() + 2 + 0
 
-  val x8 = new TreeSet[Int]().incl(2).incl(0)
+  val x9 = Vector(1, 2, 3)
 
   try {
-    val y1: List[Pair[String, Int]] = Serialize.read(Serialize.write(x1))
-    val y2: ListMap[String, Int]    = Serialize.read(Serialize.write(x2))
-    val y3: BitSet                  = Serialize.read(Serialize.write(x3))
-    val y4: ListSet[Int]            = Serialize.read(Serialize.write(x4))
-    val y5: Queue[String]           = Serialize.read(Serialize.write(x5))
-    val y6: Stack[String]           = Serialize.read(Serialize.write(x6))
-    val y7: TreeMap[Int, String]    = Serialize.read(Serialize.write(x7))
-    val y8: TreeSet[Int]            = Serialize.read(Serialize.write(x8))
-
-    EqualityTest.check(x1, y1)
-    EqualityTest.check(x2, y2)
-    EqualityTest.check(x3, y3)
-    EqualityTest.check(x4, y4)
-    EqualityTest.check(x5, y5)
-    EqualityTest.check(x6, y6)
-    EqualityTest.check(x7, y7)
-    EqualityTest.check(x8, y8)
+    val y1: List[Pair[String, Int]] = read(write(x1))
+    val n1: HashMap[Int, String]    = read(write(m1))
+    val y2: ListMap[String, Int]    = read(write(x2))
+    val y3: BitSet                  = read(write(x3))
+    val y4: ListSet[Int]            = read(write(x4))
+    val y5: Queue[String]           = read(write(x5))
+    val y6: Stack[String]           = read(write(x6))
+    val y7: TreeMap[Int, String]    = read(write(x7))
+    val y8: TreeSet[Int]            = read(write(x8))
+    val y9: Vector[Int]             = read(write(x9))
+
+    check(x1, y1)
+    check(m1, n1)
+    check(x2, y2)
+    check(x3, y3)
+    check(x4, y4)
+    check(x5, y5)
+    check(x6, y6)
+    check(x7, y7)
+    check(x8, y8)
+    check(x9, y9)
   }
   catch {
     case e: Exception =>
@@ -163,43 +225,47 @@ object Test3_mutable {
   val x3 = new HashSet[String]
   x3 ++= Test2_immutable.x1.map(p => p._1)
 
-  @serializable
-  class Feed extends Publisher[String, Feed]
-
-  val x8 = new History[String, Feed]
-
   val x4 = new LinkedList[Int](2, null)
   x4.append(new LinkedList(3, null))
 
-  val x7 = new ListBuffer[String]
-  x7 ++= List("white", "black")
-
   val x5 = new Queue[Int]
   x5 ++= Test2_immutable.x1.map(p => p._2)
 
   val x6 = new Stack[Int]
-  x6 ++= x5
+  x6 pushAll x5
+
+  val x7 = new ListBuffer[String]
+  x7 ++= List("white", "black")
+
+  @serializable
+  class Feed extends Publisher[String, Feed] {
+    override def toString() = "Feed"
+  }
+  val feed = new Feed
+
+  val x8 = new History[String, Feed]
+  x8.notify(feed, "hello")
 
   try {
-    val y0: ArrayBuffer[String]   = Serialize.read(Serialize.write(x0))
-    val y1: HashMap[String, Int]  = Serialize.read(Serialize.write(x1))
-    val y2: BitSet                = Serialize.read(Serialize.write(x2))
-    val y3: HashSet[String]       = Serialize.read(Serialize.write(x3))
-    val y4: LinkedList[Int]       = Serialize.read(Serialize.write(x4))
-    val y5: Queue[Int]            = Serialize.read(Serialize.write(x5))
-    val y6: Stack[Int]            = Serialize.read(Serialize.write(x6))
-    val y7: ListBuffer[String]    = Serialize.read(Serialize.write(x7))
-    val y8: History[String, Feed] = Serialize.read(Serialize.write(x8))
-
-    EqualityTest.check(x0, y0)
-    EqualityTest.check(x1, y1)
-    EqualityTest.check(x2, y2)
-    EqualityTest.check(x3, y3)
-    EqualityTest.check(x4, y4)
-    EqualityTest.check(x5, y5)
-    EqualityTest.check(x6, y6)
-    EqualityTest.check(x7, y7)
-    //EqualityTest.check(x8, y8) //todo
+    val y0: ArrayBuffer[String]   = read(write(x0))
+    val y1: HashMap[String, Int]  = read(write(x1))
+    val y2: BitSet                = read(write(x2))
+    val y3: HashSet[String]       = read(write(x3))
+    val y4: LinkedList[Int]       = read(write(x4))
+    val y5: Queue[Int]            = read(write(x5))
+    val y6: Stack[Int]            = read(write(x6))
+    val y7: ListBuffer[String]    = read(write(x7))
+    val y8: History[String, Feed] = read(write(x8))
+
+    check(x0, y0)
+    check(x1, y1)
+    check(x2, y2)
+    check(x3, y3)
+    check(x4, y4)
+    check(x5, y5)
+    check(x6, y6)
+    check(x7, y7)
+    check(x8, y8)
   }
   catch {
     case e: Exception =>
@@ -225,7 +291,7 @@ object Test4_xml {
           <th>Last Name</th>
           <th>First Name</th>
         </tr>
-        { for (val p <- people) yield
+        { for (p <- people) yield
         <tr>
           <td> { p.name } </td>
           <td> { p.age.toString() } </td>
@@ -246,11 +312,11 @@ object Test4_xml {
     </html>;
 
   try {
-    val y1: scala.xml.Elem = Serialize.read(Serialize.write(x1))
-    val y2: scala.xml.Elem = Serialize.read(Serialize.write(x2))
+    val y1: scala.xml.Elem = read(write(x1))
+    val y2: scala.xml.Elem = read(write(x2))
 
-    EqualityTest.check(x1, y1)
-    EqualityTest.check(x2, y2)
+    check(x1, y1)
+    check(x2, y2)
   }
   catch {
     case e: Exception =>
@@ -283,11 +349,11 @@ object Test5 {
   val x2 = bob
 
   try {
-    val y1: Person   = Serialize.read(Serialize.write(x1))
-    val y2: Employee = Serialize.read(Serialize.write(x2))
+    val y1: Person   = read(write(x1))
+    val y2: Employee = read(write(x2))
 
-    EqualityTest.check(x1, y1)
-    EqualityTest.check(x2, y2)
+    check(x1, y1)
+    check(x2, y2)
   }
   catch {
     case e: Exception =>
@@ -313,13 +379,13 @@ object Test6 {
   val x3 = paul
 
   try {
-    val y1: Person   = Serialize.read(Serialize.write(x1))
-    val y2: Employee = Serialize.read(Serialize.write(x2))
-    val y3: Person   = Serialize.read(Serialize.write(x3))
+    val y1: Person   = read(write(x1))
+    val y2: Employee = read(write(x2))
+    val y3: Person   = read(write(x3))
 
-    EqualityTest.check(x1, y1)
-    EqualityTest.check(x2, y2)
-    EqualityTest.check(x3, y3)
+    check(x1, y1)
+    check(x2, y2)
+    check(x3, y3)
   }
   catch {
     case e: Exception =>
diff --git a/test/files/jvm5/t1464.check b/test/pending/jvm/t1464.check
similarity index 100%
rename from test/files/jvm5/t1464.check
rename to test/pending/jvm/t1464.check
diff --git a/test/pending/jvm/t1801.check b/test/pending/jvm/t1801.check
new file mode 100644
index 0000000..bf78a99
--- /dev/null
+++ b/test/pending/jvm/t1801.check
@@ -0,0 +1,6 @@
+0
+100
+200
+300
+400
+done!
diff --git a/test/pending/jvm/t1801.scala b/test/pending/jvm/t1801.scala
new file mode 100644
index 0000000..6ed7c56
--- /dev/null
+++ b/test/pending/jvm/t1801.scala
@@ -0,0 +1,31 @@
+import scala.actors.Actor._
+
+object Test {
+  val rt = Runtime.getRuntime()
+  val sender = actor {
+    var cnt = 0
+    while(cnt < 500) {
+      if ((cnt % 100) == 0) println(cnt)
+      receiver ! new Array[Int] (148576)
+      cnt += 1
+      //println ("Used Mem: " + (((rt.totalMemory() - rt.freeMemory()) / 1048576.) formatted "%.2f") + " Mb")
+    }
+    receiver ! 'exit
+  }
+
+  val receiver = actor {
+    loop {
+      react {
+        case x: Array[Int] => ()//println ("received " + x.length)
+	case 'exit => {
+          println("done!")
+	  exit()
+	}
+      }
+    }
+  }
+
+  def main (args: Array[String]) {
+    sender
+  }
+}
diff --git a/test/pending/jvm/t2515.check b/test/pending/jvm/t2515.check
new file mode 100644
index 0000000..8cb8bde
--- /dev/null
+++ b/test/pending/jvm/t2515.check
@@ -0,0 +1,10 @@
+Iteration  1 succeeded
+Iteration  2 succeeded
+Iteration  3 succeeded
+Iteration  4 succeeded
+Iteration  5 succeeded
+Iteration  6 succeeded
+Iteration  7 succeeded
+Iteration  8 succeeded
+Iteration  9 succeeded
+Iteration 10 succeeded
diff --git a/test/pending/jvm/t2515.scala b/test/pending/jvm/t2515.scala
new file mode 100644
index 0000000..ee65596
--- /dev/null
+++ b/test/pending/jvm/t2515.scala
@@ -0,0 +1,43 @@
+import scala.actors.{Futures, TIMEOUT}
+import scala.actors.Actor._
+
+object Test {
+
+  def compute(): Option[Boolean] = {
+    val fts = for (j <- 0 until 5) yield Futures.future {
+      receiveWithin (100) {
+        case TIMEOUT => true
+        case other   => false
+      }
+    }
+    val done = Futures.awaitAll(2000, fts.toArray: _*) // list to array, as varargs
+    if (done.contains(None))
+      None
+    else
+      Some(true)
+  }
+
+  def main(args:Array[String]) : Unit = {
+    val ft = Futures.future {
+      val format = new java.text.DecimalFormat("000.00'ms'")
+      var iter = 1
+      val done = 11
+      while (iter < done) {
+        val start = System.nanoTime()
+        val result = compute()
+        val time = System.nanoTime() - start
+        result match {
+          case Some(result) =>
+            //printf("Iteration %2d succeeded after %s %n", iter, format.format(time / 1e6))
+            printf("Iteration %2d succeeded%n", iter)
+            iter += 1
+          case None =>
+            printf(">>>> Iteration %2d failed after %s <<<<< %n", iter, format.format(time / 1e6))
+            iter = done
+        }
+      }
+    }
+    ft()
+  }
+
+}
diff --git a/test/pending/jvm/t2705/GenericInterface.java b/test/pending/jvm/t2705/GenericInterface.java
new file mode 100644
index 0000000..ff4ecd4
--- /dev/null
+++ b/test/pending/jvm/t2705/GenericInterface.java
@@ -0,0 +1 @@
+public interface GenericInterface<T> { }
diff --git a/test/pending/jvm/t2705/Methods.java b/test/pending/jvm/t2705/Methods.java
new file mode 100644
index 0000000..00eed6c
--- /dev/null
+++ b/test/pending/jvm/t2705/Methods.java
@@ -0,0 +1,4 @@
+public class Methods {
+  public static <T> GenericInterface<T> getGenericInterface() { return null; }
+  public static <T> void acceptGenericInterface(GenericInterface<? super T> gi) { }
+}
\ No newline at end of file
diff --git a/test/pending/jvm/t2705/t2705.scala b/test/pending/jvm/t2705/t2705.scala
new file mode 100644
index 0000000..cc3cfd9
--- /dev/null
+++ b/test/pending/jvm/t2705/t2705.scala
@@ -0,0 +1,5 @@
+class GenericsCompilerCrashTest {
+  def test() {
+    Methods.acceptGenericInterface(Methods.getGenericInterface())
+  }
+}
\ No newline at end of file
diff --git a/test/files/jvm/terminateLinked.check b/test/pending/jvm/terminateLinked.check
similarity index 100%
rename from test/files/jvm/terminateLinked.check
rename to test/pending/jvm/terminateLinked.check
diff --git a/test/files/jvm/terminateLinked.scala b/test/pending/jvm/terminateLinked.scala
similarity index 100%
rename from test/files/jvm/terminateLinked.scala
rename to test/pending/jvm/terminateLinked.scala
diff --git a/test/pending/jvm/timeout.scala b/test/pending/jvm/timeout.scala
index 8161faa..22b3647 100644
--- a/test/pending/jvm/timeout.scala
+++ b/test/pending/jvm/timeout.scala
@@ -1,3 +1,8 @@
+// Test is in pending because although it suceeds locally,
+// it takes too long on the machine which runs nightly tests.
+//
+// [partest] EXPECTED: 100 < x < 900
+// [partest] ACTUAL:   1519
 
 import scala.actors.Actor._
 import scala.actors.TIMEOUT
diff --git a/test/pending/neg/badtok-3.check b/test/pending/neg/badtok-3.check
deleted file mode 100644
index 25486b9..0000000
--- a/test/pending/neg/badtok-3.check
+++ /dev/null
@@ -1 +0,0 @@
-(something about, input ended while scanning XML literal)
diff --git a/test/pending/neg/badtok-3.scala b/test/pending/neg/badtok-3.scala
deleted file mode 100644
index 66bfb30..0000000
--- a/test/pending/neg/badtok-3.scala
+++ /dev/null
@@ -1,2 +0,0 @@
-object Test {
-  <x
\ No newline at end of file
diff --git a/test/pending/neg/bug112506A.scala b/test/pending/neg/bug112506A.scala
index 1a3ca2a..e1ecab2 100644
--- a/test/pending/neg/bug112506A.scala
+++ b/test/pending/neg/bug112506A.scala
@@ -1,5 +1,5 @@
 package test;
-import scala.collection.immutable._;
+import scala.collection.immutable.ListSet
 import scala.collection.mutable._;
 trait TypeManagerXXX {
   trait TypedNode;
diff --git a/test/pending/neg/bug112706A.scala b/test/pending/neg/bug112706A.scala
deleted file mode 100644
index eecce20..0000000
--- a/test/pending/neg/bug112706A.scala
+++ /dev/null
@@ -1,8 +0,0 @@
-package test;
-trait Test {
-  def foo(p : List[Tuple2[String,String]]) = {
-    for (val t <- p) t._1 match {
-    case Tuple2(node,_) =>   
-    }
-  }
-}
\ No newline at end of file
diff --git a/test/files/neg/bug1210.check b/test/pending/neg/bug1210.check
similarity index 100%
rename from test/files/neg/bug1210.check
rename to test/pending/neg/bug1210.check
diff --git a/test/pending/neg/bug1210.scala b/test/pending/neg/bug1210.scala
index 1c89b59..58ef50b 100644
--- a/test/pending/neg/bug1210.scala
+++ b/test/pending/neg/bug1210.scala
@@ -7,4 +7,4 @@ object Test {
 
     val v: selfType = id[M.this.selfType](_.v)
   }
-}
\ No newline at end of file
+}
diff --git a/test/pending/neg/bug1987.scala b/test/pending/neg/bug1987.scala
new file mode 100644
index 0000000..d45f1b0
--- /dev/null
+++ b/test/pending/neg/bug1987.scala
@@ -0,0 +1,14 @@
+
+
+// Copyright Shunsuke Sogame 2008-2009.
+// Distributed under the terms of an MIT-style license.
+
+
+package object overloading {
+    def bar(f: (Int) => Unit): Unit = ()
+    def bar(f: (Int, Int) => Unit): Unit = ()
+}
+
+class PackageObjectOverloadingTest {
+    overloading.bar( (i: Int) => () ) // doesn't compile.
+}
diff --git a/test/pending/neg/bug3189.check b/test/pending/neg/bug3189.check
new file mode 100644
index 0000000..520644f
--- /dev/null
+++ b/test/pending/neg/bug3189.check
@@ -0,0 +1,7 @@
+bug3189.scala:2: error: illegal start of simple pattern
+  val Array(a,b*) = ("": Any)
+                ^
+bug3189.scala:3: error: ')' expected but '}' found.
+}
+^
+two errors found
diff --git a/test/pending/neg/bug3189.scala b/test/pending/neg/bug3189.scala
new file mode 100644
index 0000000..4ea4bb7
--- /dev/null
+++ b/test/pending/neg/bug3189.scala
@@ -0,0 +1,3 @@
+object A {
+  val Array(a,b*) = ("": Any)
+}
\ No newline at end of file
diff --git a/test/pending/neg/bug421.scala b/test/pending/neg/bug421.scala
deleted file mode 100644
index bf7346f..0000000
--- a/test/pending/neg/bug421.scala
+++ /dev/null
@@ -1,9 +0,0 @@
-object foo  {
-  case class Bar(a:String, b:Object, c:String*);
-
-
-  Bar("foo","meets","bar") match {
-    case Bar("foo",_*) => error("huh?");
-  }
-
-}
diff --git a/test/pending/neg/bug452.check b/test/pending/neg/bug452.check
deleted file mode 100644
index 308ec18..0000000
--- a/test/pending/neg/bug452.check
+++ /dev/null
@@ -1,6 +0,0 @@
-bug452.scala:3: error: type mismatch;
- found   : Test
- required: Test.this.Foo
-    def this() = this(this);
-                      ^
-one error found
diff --git a/test/pending/neg/bug452.scala b/test/pending/neg/bug452.scala
deleted file mode 100644
index 855406d..0000000
--- a/test/pending/neg/bug452.scala
+++ /dev/null
@@ -1,8 +0,0 @@
-object Test {
-  class Foo(x: Foo) {
-    def this() = this(this);
-  }
-  def main(args: Array[String]): Unit = {
-    new Foo();
-  }
-}
diff --git a/test/pending/neg/bug558.check b/test/pending/neg/bug558.check
deleted file mode 100644
index a51856f..0000000
--- a/test/pending/neg/bug558.check
+++ /dev/null
@@ -1,4 +0,0 @@
-bug558.scala:13: error: value file is not a member of NewModel.this.RootURL
-    final val source = top.file;
-                          ^
-one error found
diff --git a/test/pending/neg/bug558.scala b/test/pending/neg/bug558.scala
deleted file mode 100644
index 3daae72..0000000
--- a/test/pending/neg/bug558.scala
+++ /dev/null
@@ -1,19 +0,0 @@
-package scala.tools.nsc.models;
-import scala.tools.util._;
-
-abstract class NewModel {
-  abstract class SymbolURL {
-    val top   : RootURL;
-    val name  : String;
-    val source  : AbstractFile;
-  }
-  abstract class NodeURL extends SymbolURL {
-    val parent : SymbolURL;
-    final val top = parent.top;
-    final val source = top.file;
-    
-  }
-  abstract class RootURL extends SymbolURL {
-    final val top   : RootURL = this;
-  }
-}
diff --git a/test/pending/neg/plugin-after-terminal.check b/test/pending/neg/plugin-after-terminal.check
new file mode 100644
index 0000000..096efe0
--- /dev/null
+++ b/test/pending/neg/plugin-after-terminal.check
@@ -0,0 +1,2 @@
+error: [phase assembly, after dependency on terminal phase not allowed: afterterminal => terminal]
+one error found
diff --git a/test/pending/neg/plugin-after-terminal.flags b/test/pending/neg/plugin-after-terminal.flags
new file mode 100644
index 0000000..6a44376
--- /dev/null
+++ b/test/pending/neg/plugin-after-terminal.flags
@@ -0,0 +1,2 @@
+-Xplugin:files/neg/plugin-after-terminal/lib/plugins.jar
+
diff --git a/test/pending/neg/plugin-after-terminal/lib/plugins.jar b/test/pending/neg/plugin-after-terminal/lib/plugins.jar
new file mode 100644
index 0000000..70963c6
Binary files /dev/null and b/test/pending/neg/plugin-after-terminal/lib/plugins.jar differ
diff --git a/test/pending/neg/plugin-after-terminal/misc/build.sh b/test/pending/neg/plugin-after-terminal/misc/build.sh
new file mode 100644
index 0000000..8899009
--- /dev/null
+++ b/test/pending/neg/plugin-after-terminal/misc/build.sh
@@ -0,0 +1,14 @@
+#!/bin/bash
+
+SCALAC="../../../../build/pack/bin/scalac -deprecation -cp ../../../../build/quick/classes/compiler/"
+
+BASE=`pwd`
+
+if [[ -d "${BASE}/src" ]] ; then
+
+    mkdir -p build
+    ${SCALAC} -d build src/*.scala
+    jar cf lib/plugins.jar -C misc/ scalac-plugin.xml -C build .
+    rm -rf build
+fi
+
diff --git a/test/pending/neg/plugin-after-terminal/misc/scalac-plugin.xml b/test/pending/neg/plugin-after-terminal/misc/scalac-plugin.xml
new file mode 100644
index 0000000..90ff27d
--- /dev/null
+++ b/test/pending/neg/plugin-after-terminal/misc/scalac-plugin.xml
@@ -0,0 +1,5 @@
+<plugin>
+  <name>beforeparser</name>
+  <classname>scala.test.plugins.ThePlugin</classname>
+</plugin>
+
diff --git a/test/pending/neg/plugin-after-terminal/src/ThePlugin.scala b/test/pending/neg/plugin-after-terminal/src/ThePlugin.scala
new file mode 100644
index 0000000..2a46073
--- /dev/null
+++ b/test/pending/neg/plugin-after-terminal/src/ThePlugin.scala
@@ -0,0 +1,31 @@
+package scala.test.plugins
+
+import scala.tools.nsc
+import nsc.Global
+import nsc.Phase
+import nsc.plugins.Plugin
+import nsc.plugins.PluginComponent
+
+class ThePlugin(val global: Global) extends Plugin {
+  import global._
+
+  val name = "afterterminal"
+  val description = "Declares one plugin that wants to be after the terminal phase"
+  val components = List[PluginComponent](thePhase)
+  
+  private object thePhase extends PluginComponent {
+    val global = ThePlugin.this.global
+
+    val runsAfter = List[String]("terminal")
+
+    val phaseName = ThePlugin.this.name
+
+    def newPhase(prev: Phase) = new ThePhase(prev)    
+  }
+  
+  private class ThePhase(prev: Phase) extends Phase(prev) {
+    def name = ThePlugin.this.name
+    def run {}
+  }
+}
+
diff --git a/test/pending/neg/plugin-after-terminal/testsource.scala b/test/pending/neg/plugin-after-terminal/testsource.scala
new file mode 100644
index 0000000..519d162
--- /dev/null
+++ b/test/pending/neg/plugin-after-terminal/testsource.scala
@@ -0,0 +1,4 @@
+object Test extends Application {
+  println("afterterminal")
+}
+
diff --git a/test/pending/neg/plugin-before-parser.check b/test/pending/neg/plugin-before-parser.check
new file mode 100644
index 0000000..9a40792
--- /dev/null
+++ b/test/pending/neg/plugin-before-parser.check
@@ -0,0 +1,2 @@
+error: [phase assembly, before dependency on parser phase not allowed: parser => beforeparser]
+one error found
diff --git a/test/pending/neg/plugin-before-parser.flags b/test/pending/neg/plugin-before-parser.flags
new file mode 100644
index 0000000..6325309
--- /dev/null
+++ b/test/pending/neg/plugin-before-parser.flags
@@ -0,0 +1,2 @@
+-Xplugin:files/neg/plugin-before-parser/lib/plugins.jar
+
diff --git a/test/pending/neg/plugin-before-parser/lib/plugins.jar b/test/pending/neg/plugin-before-parser/lib/plugins.jar
new file mode 100644
index 0000000..0800746
Binary files /dev/null and b/test/pending/neg/plugin-before-parser/lib/plugins.jar differ
diff --git a/test/pending/neg/plugin-before-parser/misc/build.sh b/test/pending/neg/plugin-before-parser/misc/build.sh
new file mode 100644
index 0000000..8899009
--- /dev/null
+++ b/test/pending/neg/plugin-before-parser/misc/build.sh
@@ -0,0 +1,14 @@
+#!/bin/bash
+
+SCALAC="../../../../build/pack/bin/scalac -deprecation -cp ../../../../build/quick/classes/compiler/"
+
+BASE=`pwd`
+
+if [[ -d "${BASE}/src" ]] ; then
+
+    mkdir -p build
+    ${SCALAC} -d build src/*.scala
+    jar cf lib/plugins.jar -C misc/ scalac-plugin.xml -C build .
+    rm -rf build
+fi
+
diff --git a/test/pending/neg/plugin-before-parser/misc/scalac-plugin.xml b/test/pending/neg/plugin-before-parser/misc/scalac-plugin.xml
new file mode 100644
index 0000000..90ff27d
--- /dev/null
+++ b/test/pending/neg/plugin-before-parser/misc/scalac-plugin.xml
@@ -0,0 +1,5 @@
+<plugin>
+  <name>beforeparser</name>
+  <classname>scala.test.plugins.ThePlugin</classname>
+</plugin>
+
diff --git a/test/pending/neg/plugin-before-parser/src/ThePlugin.scala b/test/pending/neg/plugin-before-parser/src/ThePlugin.scala
new file mode 100644
index 0000000..7ca8966
--- /dev/null
+++ b/test/pending/neg/plugin-before-parser/src/ThePlugin.scala
@@ -0,0 +1,32 @@
+package scala.test.plugins
+
+import scala.tools.nsc
+import nsc.Global
+import nsc.Phase
+import nsc.plugins.Plugin
+import nsc.plugins.PluginComponent
+
+class ThePlugin(val global: Global) extends Plugin {
+  import global._
+
+  val name = "beforeparser"
+  val description = "Declares one plugin that wants to be before the parser phase"
+  val components = List[PluginComponent](thePhase)
+  
+  private object thePhase extends PluginComponent {
+    val global = ThePlugin.this.global
+
+    val runsAfter = List[String]()
+    override val runsBefore = List[String]("parser")
+
+    val phaseName = ThePlugin.this.name
+
+    def newPhase(prev: Phase) = new ThePhase(prev)    
+  }
+  
+  private class ThePhase(prev: Phase) extends Phase(prev) {
+    def name = ThePlugin.this.name
+    def run {}
+  }
+}
+
diff --git a/test/pending/neg/plugin-before-parser/testsource.scala b/test/pending/neg/plugin-before-parser/testsource.scala
new file mode 100644
index 0000000..9928aaa
--- /dev/null
+++ b/test/pending/neg/plugin-before-parser/testsource.scala
@@ -0,0 +1,4 @@
+object Test extends Application {
+  println("beforeparser")
+}
+
diff --git a/test/pending/neg/plugin-cyclic-dependency.check b/test/pending/neg/plugin-cyclic-dependency.check
new file mode 100644
index 0000000..a29bc3f
--- /dev/null
+++ b/test/pending/neg/plugin-cyclic-dependency.check
@@ -0,0 +1,2 @@
+error: fatal error: Cycle in compiler phase dependencies detected, phase cyclicdependency1 reacted twice!
+one error found
diff --git a/test/pending/neg/plugin-cyclic-dependency.flags b/test/pending/neg/plugin-cyclic-dependency.flags
new file mode 100644
index 0000000..8716aaa
--- /dev/null
+++ b/test/pending/neg/plugin-cyclic-dependency.flags
@@ -0,0 +1,2 @@
+-Xplugin:files/neg/plugin-cyclic-dependency/lib/plugins.jar
+
diff --git a/test/pending/neg/plugin-cyclic-dependency/lib/plugins.jar b/test/pending/neg/plugin-cyclic-dependency/lib/plugins.jar
new file mode 100644
index 0000000..69565ba
Binary files /dev/null and b/test/pending/neg/plugin-cyclic-dependency/lib/plugins.jar differ
diff --git a/test/pending/neg/plugin-cyclic-dependency/misc/build.sh b/test/pending/neg/plugin-cyclic-dependency/misc/build.sh
new file mode 100644
index 0000000..8899009
--- /dev/null
+++ b/test/pending/neg/plugin-cyclic-dependency/misc/build.sh
@@ -0,0 +1,14 @@
+#!/bin/bash
+
+SCALAC="../../../../build/pack/bin/scalac -deprecation -cp ../../../../build/quick/classes/compiler/"
+
+BASE=`pwd`
+
+if [[ -d "${BASE}/src" ]] ; then
+
+    mkdir -p build
+    ${SCALAC} -d build src/*.scala
+    jar cf lib/plugins.jar -C misc/ scalac-plugin.xml -C build .
+    rm -rf build
+fi
+
diff --git a/test/pending/neg/plugin-cyclic-dependency/misc/scalac-plugin.xml b/test/pending/neg/plugin-cyclic-dependency/misc/scalac-plugin.xml
new file mode 100644
index 0000000..90ff27d
--- /dev/null
+++ b/test/pending/neg/plugin-cyclic-dependency/misc/scalac-plugin.xml
@@ -0,0 +1,5 @@
+<plugin>
+  <name>beforeparser</name>
+  <classname>scala.test.plugins.ThePlugin</classname>
+</plugin>
+
diff --git a/test/pending/neg/plugin-cyclic-dependency/src/ThePlugin.scala b/test/pending/neg/plugin-cyclic-dependency/src/ThePlugin.scala
new file mode 100644
index 0000000..bd94ce6
--- /dev/null
+++ b/test/pending/neg/plugin-cyclic-dependency/src/ThePlugin.scala
@@ -0,0 +1,41 @@
+package scala.test.plugins
+
+import scala.tools.nsc
+import nsc.Global
+import nsc.Phase
+import nsc.plugins.Plugin
+import nsc.plugins.PluginComponent
+
+class ThePlugin(val global: Global) extends Plugin {
+  import global._
+
+  val name = "cyclicdependency"
+  val description = "Declares two phases that have a cyclic dependency"
+  val components = List[PluginComponent](thePhase1,thePhase2)
+  
+  private object thePhase1 extends PluginComponent {
+    val global = ThePlugin.this.global
+
+    val runsAfter = List[String]("tailcalls","cyclicdependency2")
+
+    val phaseName = ThePlugin.this.name + "1"
+
+    def newPhase(prev: Phase) = new ThePhase(prev)    
+  }
+  
+  private object thePhase2 extends PluginComponent {
+    val global = ThePlugin.this.global
+
+    val runsAfter = List[String]("dce","cyclicdependency1")
+
+    val phaseName = ThePlugin.this.name + "2"
+
+    def newPhase(prev: Phase) = new ThePhase(prev)    
+  }
+  
+  private class ThePhase(prev: Phase) extends Phase(prev) {
+    def name = ThePlugin.this.name
+    def run {}
+  }
+}
+
diff --git a/test/pending/neg/plugin-cyclic-dependency/testsource.scala b/test/pending/neg/plugin-cyclic-dependency/testsource.scala
new file mode 100644
index 0000000..f1513ec
--- /dev/null
+++ b/test/pending/neg/plugin-cyclic-dependency/testsource.scala
@@ -0,0 +1,4 @@
+object Test extends Application {
+  println("cyclicdependency")
+}
+
diff --git a/test/pending/neg/plugin-multiple-rafter.check b/test/pending/neg/plugin-multiple-rafter.check
new file mode 100644
index 0000000..c54f884
--- /dev/null
+++ b/test/pending/neg/plugin-multiple-rafter.check
@@ -0,0 +1,4 @@
+error: fatal error: Multiple phases want to run right after the phase explicitouter
+Phases: erasure, multi-rafter, 
+Re-run with -Xgenerate-phase-graph <filename> to better see the problem.
+one error found
diff --git a/test/pending/neg/plugin-multiple-rafter.flags b/test/pending/neg/plugin-multiple-rafter.flags
new file mode 100644
index 0000000..dcae7f2
--- /dev/null
+++ b/test/pending/neg/plugin-multiple-rafter.flags
@@ -0,0 +1,2 @@
+-Xplugin:files/neg/plugin-multiple-rafter/lib/plugins.jar
+
diff --git a/test/pending/neg/plugin-multiple-rafter/lib/plugins.jar b/test/pending/neg/plugin-multiple-rafter/lib/plugins.jar
new file mode 100644
index 0000000..f951708
Binary files /dev/null and b/test/pending/neg/plugin-multiple-rafter/lib/plugins.jar differ
diff --git a/test/pending/neg/plugin-multiple-rafter/misc/build.sh b/test/pending/neg/plugin-multiple-rafter/misc/build.sh
new file mode 100644
index 0000000..8899009
--- /dev/null
+++ b/test/pending/neg/plugin-multiple-rafter/misc/build.sh
@@ -0,0 +1,14 @@
+#!/bin/bash
+
+SCALAC="../../../../build/pack/bin/scalac -deprecation -cp ../../../../build/quick/classes/compiler/"
+
+BASE=`pwd`
+
+if [[ -d "${BASE}/src" ]] ; then
+
+    mkdir -p build
+    ${SCALAC} -d build src/*.scala
+    jar cf lib/plugins.jar -C misc/ scalac-plugin.xml -C build .
+    rm -rf build
+fi
+
diff --git a/test/pending/neg/plugin-multiple-rafter/misc/scalac-plugin.xml b/test/pending/neg/plugin-multiple-rafter/misc/scalac-plugin.xml
new file mode 100644
index 0000000..90ff27d
--- /dev/null
+++ b/test/pending/neg/plugin-multiple-rafter/misc/scalac-plugin.xml
@@ -0,0 +1,5 @@
+<plugin>
+  <name>beforeparser</name>
+  <classname>scala.test.plugins.ThePlugin</classname>
+</plugin>
+
diff --git a/test/pending/neg/plugin-multiple-rafter/src/ThePlugin.scala b/test/pending/neg/plugin-multiple-rafter/src/ThePlugin.scala
new file mode 100644
index 0000000..819176f
--- /dev/null
+++ b/test/pending/neg/plugin-multiple-rafter/src/ThePlugin.scala
@@ -0,0 +1,31 @@
+package scala.test.plugins
+
+import scala.tools.nsc
+import nsc.Global
+import nsc.Phase
+import nsc.plugins.Plugin
+import nsc.plugins.PluginComponent
+
+class ThePlugin(val global: Global) extends Plugin {
+  import global._
+
+  val name = "multi-rafter"
+  val description = ""
+  val components = List[PluginComponent](thePhase)
+  
+  private object thePhase extends PluginComponent {
+    val global = ThePlugin.this.global
+
+    val runsAfter = List[String]()
+    override val runsRightAfter = Some("explicitouter")
+    val phaseName = ThePlugin.this.name
+
+    def newPhase(prev: Phase) = new ThePhase(prev)    
+  }
+  
+  private class ThePhase(prev: Phase) extends Phase(prev) {
+    def name = ThePlugin.this.name
+    def run {}
+  }
+}
+
diff --git a/test/pending/neg/plugin-multiple-rafter/testsource.scala b/test/pending/neg/plugin-multiple-rafter/testsource.scala
new file mode 100644
index 0000000..f73db1e
--- /dev/null
+++ b/test/pending/neg/plugin-multiple-rafter/testsource.scala
@@ -0,0 +1,4 @@
+object Test extends Application {
+  println("multi-rafter")
+}
+
diff --git a/test/pending/neg/plugin-rafter-before-1.check b/test/pending/neg/plugin-rafter-before-1.check
new file mode 100644
index 0000000..19ed4d2
--- /dev/null
+++ b/test/pending/neg/plugin-rafter-before-1.check
@@ -0,0 +1,2 @@
+error: fatal error: phase erasure want to run right after explicitouter, but some phase has declared to run before erasure. Re-run with -Xgenerate-phase-graph <filename> to better see the problem.
+one error found
diff --git a/test/pending/neg/plugin-rafter-before-1.flags b/test/pending/neg/plugin-rafter-before-1.flags
new file mode 100644
index 0000000..8bf0314
--- /dev/null
+++ b/test/pending/neg/plugin-rafter-before-1.flags
@@ -0,0 +1,2 @@
+-Xplugin:files/neg/plugin-rafter-before-1/lib/plugins.jar
+
diff --git a/test/pending/neg/plugin-rafter-before-1/lib/plugins.jar b/test/pending/neg/plugin-rafter-before-1/lib/plugins.jar
new file mode 100644
index 0000000..50c8e2c
Binary files /dev/null and b/test/pending/neg/plugin-rafter-before-1/lib/plugins.jar differ
diff --git a/test/pending/neg/plugin-rafter-before-1/misc/build.sh b/test/pending/neg/plugin-rafter-before-1/misc/build.sh
new file mode 100644
index 0000000..8899009
--- /dev/null
+++ b/test/pending/neg/plugin-rafter-before-1/misc/build.sh
@@ -0,0 +1,14 @@
+#!/bin/bash
+
+SCALAC="../../../../build/pack/bin/scalac -deprecation -cp ../../../../build/quick/classes/compiler/"
+
+BASE=`pwd`
+
+if [[ -d "${BASE}/src" ]] ; then
+
+    mkdir -p build
+    ${SCALAC} -d build src/*.scala
+    jar cf lib/plugins.jar -C misc/ scalac-plugin.xml -C build .
+    rm -rf build
+fi
+
diff --git a/test/pending/neg/plugin-rafter-before-1/misc/scalac-plugin.xml b/test/pending/neg/plugin-rafter-before-1/misc/scalac-plugin.xml
new file mode 100644
index 0000000..90ff27d
--- /dev/null
+++ b/test/pending/neg/plugin-rafter-before-1/misc/scalac-plugin.xml
@@ -0,0 +1,5 @@
+<plugin>
+  <name>beforeparser</name>
+  <classname>scala.test.plugins.ThePlugin</classname>
+</plugin>
+
diff --git a/test/pending/neg/plugin-rafter-before-1/src/ThePlugin.scala b/test/pending/neg/plugin-rafter-before-1/src/ThePlugin.scala
new file mode 100644
index 0000000..81ba85a
--- /dev/null
+++ b/test/pending/neg/plugin-rafter-before-1/src/ThePlugin.scala
@@ -0,0 +1,31 @@
+package scala.test.plugins
+
+import scala.tools.nsc
+import nsc.Global
+import nsc.Phase
+import nsc.plugins.Plugin
+import nsc.plugins.PluginComponent
+
+class ThePlugin(val global: Global) extends Plugin {
+  import global._
+
+  val name = "rafter-before-1"
+  val description = ""
+  val components = List[PluginComponent](thePhase1)
+  
+  private object thePhase1 extends PluginComponent {
+    val global = ThePlugin.this.global
+
+    val runsAfter = List[String]("refchecks")
+    override val runsBefore = List[String]("erasure")
+    val phaseName = ThePlugin.this.name
+
+    def newPhase(prev: Phase) = new ThePhase(prev)    
+  }
+  
+  private class ThePhase(prev: Phase) extends Phase(prev) {
+    def name = ThePlugin.this.name
+    def run {}
+  }
+}
+
diff --git a/test/pending/neg/plugin-rafter-before-1/testsource.scala b/test/pending/neg/plugin-rafter-before-1/testsource.scala
new file mode 100644
index 0000000..836459d
--- /dev/null
+++ b/test/pending/neg/plugin-rafter-before-1/testsource.scala
@@ -0,0 +1,4 @@
+object Test extends Application {
+  println("rafter-before-1")
+}
+
diff --git a/test/pending/neg/plugin-rightafter-terminal.check b/test/pending/neg/plugin-rightafter-terminal.check
new file mode 100644
index 0000000..6fe4f63
--- /dev/null
+++ b/test/pending/neg/plugin-rightafter-terminal.check
@@ -0,0 +1,2 @@
+error: [phase assembly, right after dependency on terminal phase not allowed: rightafterterminal => terminal]
+one error found
diff --git a/test/pending/neg/plugin-rightafter-terminal.flags b/test/pending/neg/plugin-rightafter-terminal.flags
new file mode 100644
index 0000000..948a318
--- /dev/null
+++ b/test/pending/neg/plugin-rightafter-terminal.flags
@@ -0,0 +1,2 @@
+-Xplugin:files/neg/plugin-rightafter-terminal/lib/plugins.jar
+
diff --git a/test/pending/neg/plugin-rightafter-terminal/lib/plugins.jar b/test/pending/neg/plugin-rightafter-terminal/lib/plugins.jar
new file mode 100644
index 0000000..dd476e1
Binary files /dev/null and b/test/pending/neg/plugin-rightafter-terminal/lib/plugins.jar differ
diff --git a/test/pending/neg/plugin-rightafter-terminal/misc/build.sh b/test/pending/neg/plugin-rightafter-terminal/misc/build.sh
new file mode 100644
index 0000000..8899009
--- /dev/null
+++ b/test/pending/neg/plugin-rightafter-terminal/misc/build.sh
@@ -0,0 +1,14 @@
+#!/bin/bash
+
+SCALAC="../../../../build/pack/bin/scalac -deprecation -cp ../../../../build/quick/classes/compiler/"
+
+BASE=`pwd`
+
+if [[ -d "${BASE}/src" ]] ; then
+
+    mkdir -p build
+    ${SCALAC} -d build src/*.scala
+    jar cf lib/plugins.jar -C misc/ scalac-plugin.xml -C build .
+    rm -rf build
+fi
+
diff --git a/test/pending/neg/plugin-rightafter-terminal/misc/scalac-plugin.xml b/test/pending/neg/plugin-rightafter-terminal/misc/scalac-plugin.xml
new file mode 100644
index 0000000..90ff27d
--- /dev/null
+++ b/test/pending/neg/plugin-rightafter-terminal/misc/scalac-plugin.xml
@@ -0,0 +1,5 @@
+<plugin>
+  <name>beforeparser</name>
+  <classname>scala.test.plugins.ThePlugin</classname>
+</plugin>
+
diff --git a/test/pending/neg/plugin-rightafter-terminal/src/ThePlugin.scala b/test/pending/neg/plugin-rightafter-terminal/src/ThePlugin.scala
new file mode 100644
index 0000000..9d6d30b
--- /dev/null
+++ b/test/pending/neg/plugin-rightafter-terminal/src/ThePlugin.scala
@@ -0,0 +1,32 @@
+package scala.test.plugins
+
+import scala.tools.nsc
+import nsc.Global
+import nsc.Phase
+import nsc.plugins.Plugin
+import nsc.plugins.PluginComponent
+
+class ThePlugin(val global: Global) extends Plugin {
+  import global._
+
+  val name = "rightafterterminal"
+  val description = "Declares one plugin that wants to be right after the terminal phase"
+  val components = List[PluginComponent](thePhase)
+  
+  private object thePhase extends PluginComponent {
+    val global = ThePlugin.this.global
+
+    val runsAfter = List[String]()
+    override val runsRightAfter = Some("terminal")
+    
+    val phaseName = ThePlugin.this.name
+
+    def newPhase(prev: Phase) = new ThePhase(prev)    
+  }
+  
+  private class ThePhase(prev: Phase) extends Phase(prev) {
+    def name = ThePlugin.this.name
+    def run {}
+  }
+}
+
diff --git a/test/pending/neg/plugin-rightafter-terminal/testsource.scala b/test/pending/neg/plugin-rightafter-terminal/testsource.scala
new file mode 100644
index 0000000..7af767b
--- /dev/null
+++ b/test/pending/neg/plugin-rightafter-terminal/testsource.scala
@@ -0,0 +1,4 @@
+object Test extends Application {
+  println("rightafterterminal")
+}
+
diff --git a/test/pending/neg/t0605.scala b/test/pending/neg/t0605.scala
deleted file mode 100644
index af24ced..0000000
--- a/test/pending/neg/t0605.scala
+++ /dev/null
@@ -1,3 +0,0 @@
-object Test {
-  println "Hello"
-}
diff --git a/test/pending/neg/t0673.check b/test/pending/neg/t0673.check
deleted file mode 100644
index e52f65a..0000000
--- a/test/pending/neg/t0673.check
+++ /dev/null
@@ -1,4 +0,0 @@
-Test.scala:2: error: not found: value JavaClass
-  val x = JavaClass.InnerClass
-          ^
-one error found
diff --git a/test/pending/neg/t1049.scala b/test/pending/neg/t1049.scala
deleted file mode 100644
index 8fb0f7f..0000000
--- a/test/pending/neg/t1049.scala
+++ /dev/null
@@ -1,5 +0,0 @@
-object T1049 {
-  "abc" match {
-    case x: x.Whatever =>
-  }
-}
diff --git a/test/pending/neg/t1477.scala b/test/pending/neg/t1477.scala
new file mode 100644
index 0000000..3ecd275
--- /dev/null
+++ b/test/pending/neg/t1477.scala
@@ -0,0 +1,25 @@
+object Test extends Application {
+ trait A
+ trait B extends A
+
+  trait C {
+    type U
+    trait D { type T >: B <: A }
+    type V <: D
+    val y: V#T = new B { }
+  }
+ 
+  trait Middle extends C {
+    type V <: (D with U)
+  }
+
+  class D extends Middle {
+    trait E
+    trait F { type T = E }
+    type U = F
+    def frob(arg : E) : E = arg
+    frob(y)
+  }
+
+  new D
+}
diff --git a/test/pending/neg/t1800.scala b/test/pending/neg/t1800.scala
new file mode 100644
index 0000000..eebbbad
--- /dev/null
+++ b/test/pending/neg/t1800.scala
@@ -0,0 +1,28 @@
+object ObjectHolder {
+    private[ObjectHolder] class PrivateObject
+    def getPrivateObject = new PrivateObject
+}
+
+object Test {
+    def main(args: Array[String]) {
+        // compiler error: class PrivateObject cannot be accessed
+        // in object test.ObjectHolder
+        val a: ObjectHolder.PrivateObject = ObjectHolder.getPrivateObject
+
+        // works fine
+        val b = ObjectHolder.getPrivateObject
+        println(b.getClass)
+    }
+}
+/*
+When declaring objects as private[package/object] or protected[package/object] it is possible to leak out references to these objects into the public api (can be desirable, this in itself is not a problem).
+
+When users of the api receive such private object via a function call, they can create a variable to reference the private object using inferred typing:
+
+val b = getPrivateObject()
+
+However they cannot create such variable using declared typing:
+
+val a: PrivateObject? = getPrivateObject()
+
+The line above will generate a compiler error: "class PrivateObject? cannot be accessed". Which makes sense, because PrivateObject? was declared private. But in this case inferred typing should not work either, otherwise the behaviors of inferred typing and declared typing become inconsistent. */
diff --git a/test/pending/neg/t1845.scala b/test/pending/neg/t1845.scala
new file mode 100644
index 0000000..cfb28aa
--- /dev/null
+++ b/test/pending/neg/t1845.scala
@@ -0,0 +1,12 @@
+// Compiling the attached code makes scalac give a NPE.
+
+import scala.util.parsing.combinator.syntactical.TokenParsers
+import scala.util.parsing.combinator.lexical.StdLexical
+import scala.util.parsing.syntax.StdTokens
+
+class MyTokenParsers extends TokenParsers {
+  import lexical._
+  type Tokens = StdTokens
+  type Elem = lexical.Token
+  val lexical = new StdLexical
+}
diff --git a/test/pending/neg/t2078.scala b/test/pending/neg/t2078.scala
new file mode 100644
index 0000000..a697afc
--- /dev/null
+++ b/test/pending/neg/t2078.scala
@@ -0,0 +1,9 @@
+class A[-S](y : S) {
+  val f  = new { val x = y }
+}
+
+object Test extends Application {
+  val a = new A(1)
+  val b = a : A[Nothing]
+  b.f.x
+}
diff --git a/test/pending/neg/t2079.scala b/test/pending/neg/t2079.scala
new file mode 100644
index 0000000..d609103
--- /dev/null
+++ b/test/pending/neg/t2079.scala
@@ -0,0 +1,25 @@
+trait A {
+  type T
+  var v : T
+}
+
+object B {
+  def f(x : { val y : A }) { x.y.v = x.y.v } 
+  
+  var a : A = _
+  var b : Boolean = false
+  def y : A = {
+    if(b) {
+      a = new A { type T = Int; var v = 1 }
+      a
+    } else {
+      a = new A { type T = String; var v = "" }
+      b = true
+      a
+    }
+  }
+}
+
+object Test extends Application {
+  B.f(B)
+}
diff --git a/test/pending/neg/t2080.scala b/test/pending/neg/t2080.scala
new file mode 100644
index 0000000..3f4306c
--- /dev/null
+++ b/test/pending/neg/t2080.scala
@@ -0,0 +1,17 @@
+trait A {
+ type T
+ def f(x : T) : T
+}
+
+trait B extends A {
+ trait T { }
+ override def f(x : T) : T = x
+}
+
+object C extends B {
+ override trait T {
+   def g {  }
+ }
+ override def f(x : T) : T = { x.g; x }
+}
+//It compiles without errors, but T in B and T in C are completely unrelated types. 
diff --git a/test/pending/neg/t2180.scala b/test/pending/neg/t2180.scala
new file mode 100644
index 0000000..a8055bf
--- /dev/null
+++ b/test/pending/neg/t2180.scala
@@ -0,0 +1,31 @@
+
+
+Given the following code (which is broken):
+
+class Mxml {
+
+    private def processChildren( children:Seq[Any] ):List[Mxml] = {
+
+        children.toList.flatMap ( e => {
+
+            e match {
+
+                case s:scala.collection.Traversable[_] => s case a => List(a)
+
+            }
+
+        })
+
+    }
+
+}
+
+I get the following error:
+
+Mxml.scala:5: error: could not find implicit value for parameter bf:scala.collection.generic.BuilderFactory[Any,List[Mxml],Sequence[Any]].
+
+    children.flatMap ( e => {
+
+I spent 4 hours failing before I figured out the problem. The return type was wrong. It should have been List[Any].
+
+I have seen similar errors with map. My solution in the past has been to change it to a foldLeft because I have never been able to determine how to fix the problem until now.
diff --git a/test/pending/neg/tcpoly_typealias_eta.scala b/test/pending/neg/tcpoly_typealias_eta.scala
index 8804d08..033c911 100644
--- a/test/pending/neg/tcpoly_typealias_eta.scala
+++ b/test/pending/neg/tcpoly_typealias_eta.scala
@@ -43,4 +43,4 @@ trait BCon extends A{
 
 trait BBound extends A{
   type m/*[+x <: String]*/ = FooBound/*[x]*/ // error: x with stricter bound
-}
\ No newline at end of file
+}
diff --git a/test/pending/neg/tcpoly_variance_enforce_getter_setter.scala b/test/pending/neg/tcpoly_variance_enforce_getter_setter.scala
index 40b025c..deafba8 100644
--- a/test/pending/neg/tcpoly_variance_enforce_getter_setter.scala
+++ b/test/pending/neg/tcpoly_variance_enforce_getter_setter.scala
@@ -9,4 +9,4 @@ object test {
    
   var x: coll[FooInvar] = _    // TODO: error should be reported only once instead of separately for getter and setter
   var y: coll[FooContra] = _
-}
\ No newline at end of file
+}
diff --git a/test/pending/pos/bug0305.scala b/test/pending/pos/bug0305.scala
index a7168be..1fc6678 100644
--- a/test/pending/pos/bug0305.scala
+++ b/test/pending/pos/bug0305.scala
@@ -5,4 +5,4 @@ object Test extends Application {
 
   Console.println( foo( List(3):_* ) )
 
-}
\ No newline at end of file
+}
diff --git a/test/pending/pos/bug1087.scala b/test/pending/pos/bug1087.scala
deleted file mode 100644
index 19d6211..0000000
--- a/test/pending/pos/bug1087.scala
+++ /dev/null
@@ -1,2 +0,0 @@
-case class Foo
-case class Prd (pred : Char => Boolean) extends Foo
diff --git a/test/pending/pos/bug1357.scala b/test/pending/pos/bug1357.scala
new file mode 100644
index 0000000..7bc6d45
--- /dev/null
+++ b/test/pending/pos/bug1357.scala
@@ -0,0 +1,21 @@
+object NonEmptyCons {
+  def unapply[H, T](c: (H, T)): Option[(H, T)] = Some(c)
+}
+
+
+object Main {
+
+  type BT[+H, +T <: Tuple2[Tuple2[H, T], Tuple2[H, T]]] = Tuple2[H, T]
+  
+  // type T = Tuple2[String,String]
+  type BinaryTree[+E] = BT[E, T forSome { type T <: Tuple2[BT[E, T], BT[E, T]] }]
+
+  def foo[E](tree: BinaryTree[E]): Unit = tree match {
+    case NonEmptyCons(_, tail) => {
+      tail match {
+        case NonEmptyCons(_, _) => {
+        }
+      }
+    }
+  }
+}
\ No newline at end of file
diff --git a/test/pending/pos/bug1957.scala b/test/pending/pos/bug1957.scala
new file mode 100644
index 0000000..f80cf73
--- /dev/null
+++ b/test/pending/pos/bug1957.scala
@@ -0,0 +1,38 @@
+object Test {
+    abstract class Settings {}
+
+    abstract class Grist
+    { self =>
+        type settingsType <: Settings
+        type moduleType <: Module {type settingsType = self.settingsType}
+        val module: moduleType
+    }
+
+    abstract class Tool
+    { self =>
+        type settingsType <: Settings
+        type moduleType = Module { type settingsType = self.settingsType }
+        type gristType = Grist { type moduleType <: self.moduleType; type settingsType <: self.settingsType }
+
+        def inputGrist: List[gristType]
+    }
+
+    abstract class Module
+    { self =>
+        type settingsType <: Settings
+        final type commonModuleType = Module {type settingsType = self.settingsType}
+        type selfType >: self.type <: commonModuleType
+
+        // BTW: if we use the commented out type declarations, the code compiles successfully
+        // type gristType = Grist {type settingsType <: self.settingsType; type moduleType <: commonModuleType }
+
+        val tools: List[Tool {type settingsType = self.settingsType}]
+
+        protected def f: List[commonModuleType] =
+        {
+            val inputGrists = tools.flatMap(_.inputGrist) // val inputGrists: List[gristType] =
+            inputGrists.map(_.module)
+        }
+
+    }
+}
diff --git a/test/pending/pos/bug2018.scala b/test/pending/pos/bug2018.scala
new file mode 100644
index 0000000..f1753f4
--- /dev/null
+++ b/test/pending/pos/bug2018.scala
@@ -0,0 +1,15 @@
+class A {
+  val b = new B
+
+  def getChildren = List(new A).elements
+
+  class B {
+    private def check = true
+
+    private def getAncestor(p: A): A = {
+      val c = (p.getChildren.find(_.b.check)) match {case Some(d) => d case None => p}
+
+      if (c == p) p else c.b.getAncestor(c)
+    }
+  }
+}
diff --git a/test/pending/pos/bug3420.flags b/test/pending/pos/bug3420.flags
new file mode 100644
index 0000000..ea03113
--- /dev/null
+++ b/test/pending/pos/bug3420.flags
@@ -0,0 +1 @@
+-optimise -Xfatal-warnings
\ No newline at end of file
diff --git a/test/pending/pos/bug3420.scala b/test/pending/pos/bug3420.scala
new file mode 100644
index 0000000..0fc56ed
--- /dev/null
+++ b/test/pending/pos/bug3420.scala
@@ -0,0 +1,5 @@
+class C {
+    val cv = Map[Int, Int](1 -> 2)
+    lazy val cl = Map[Int, Int](1 -> 2)
+    def cd = Map[Int, Int](1 -> 2)
+}
diff --git a/test/pending/pos/bug586.scala b/test/pending/pos/bug586.scala
index 9b9bd70..f07d0cd 100644
--- a/test/pending/pos/bug586.scala
+++ b/test/pending/pos/bug586.scala
@@ -11,7 +11,7 @@ with imm.Set[A]
   def +(elem: A) = new HashTreeSet(map + elem -> ())
   def -(elem: A) = new HashTreeSet(map - elem)
   def contains(elem: A) = map.isDefinedAt(elem)
-  def elements = map.elements.map(._1)
+  def iterator = map.iterator.map(._1)
   def empty:imm.Set[A] = new HashTreeSet[A]()
 }
 
diff --git a/test/pending/pos/local-objects.scala b/test/pending/pos/local-objects.scala
new file mode 100644
index 0000000..ed7c50e
--- /dev/null
+++ b/test/pending/pos/local-objects.scala
@@ -0,0 +1,9 @@
+
+
+object Main {
+ val x = {
+   object Boo
+   Boo
+ }
+}
+
diff --git a/test/pending/pos/misc/A.java b/test/pending/pos/misc/A.java
new file mode 100644
index 0000000..8eaa341
--- /dev/null
+++ b/test/pending/pos/misc/A.java
@@ -0,0 +1,13 @@
+package test;
+
+import static test.A.STATE.UNDEF;
+
+class A {
+
+    public STATE state = UNDEF;
+
+	protected static enum STATE {
+		UNDEF
+	}
+
+}
diff --git a/test/pending/pos/misc/B.scala b/test/pending/pos/misc/B.scala
new file mode 100644
index 0000000..afc3094
--- /dev/null
+++ b/test/pending/pos/misc/B.scala
@@ -0,0 +1,7 @@
+package test
+
+class B {
+	
+	def myA = new A()
+
+}
diff --git a/test/pending/pos/misc/J.java b/test/pending/pos/misc/J.java
new file mode 100644
index 0000000..4805791
--- /dev/null
+++ b/test/pending/pos/misc/J.java
@@ -0,0 +1,4 @@
+class J {
+    void f (@Override{ name = value } int x) {}
+    void g (String ... x) {}
+}
diff --git a/test/pending/pos/misc/S.scala b/test/pending/pos/misc/S.scala
new file mode 100644
index 0000000..c5bfb26
--- /dev/null
+++ b/test/pending/pos/misc/S.scala
@@ -0,0 +1,4 @@
+object Test extends J {
+  def h(xs: String*) {}
+  g("a", "b", "c")
+}
diff --git a/test/pending/pos/switchUnbox.flags b/test/pending/pos/switchUnbox.flags
deleted file mode 100644
index ec1ad20..0000000
--- a/test/pending/pos/switchUnbox.flags
+++ /dev/null
@@ -1 +0,0 @@
--Xsqueeze:on
diff --git a/test/pending/pos/switchUnbox.scala b/test/pending/pos/switchUnbox.scala
deleted file mode 100644
index 2e51fa6..0000000
--- a/test/pending/pos/switchUnbox.scala
+++ /dev/null
@@ -1,11 +0,0 @@
-// this test has accompanying .flags file 
-//  that contains -Xsqueeze:on
-// 
-object Foo {
-  var xyz: (int, String) = (1, "abc")
-  xyz._1 match {
-    case 1 => Console.println("OK")
-    case 2 => Console.println("OK")
-    case _ => Console.println("KO")
-  }
-}
diff --git a/test/pending/pos/t0612/C.scala b/test/pending/pos/t0612/C.scala
deleted file mode 100644
index 95a9aef..0000000
--- a/test/pending/pos/t0612/C.scala
+++ /dev/null
@@ -1,5 +0,0 @@
-package test.app
-
-class C {
-  Ob.f
-}
diff --git a/test/pending/pos/t0699/A.scala b/test/pending/pos/t0699/A.scala
deleted file mode 100644
index 740d8ec..0000000
--- a/test/pending/pos/t0699/A.scala
+++ /dev/null
@@ -1,4 +0,0 @@
-object A {
-  sealed trait T
-  sealed class C
-}
\ No newline at end of file
diff --git a/test/pending/pos/t0699/B.scala b/test/pending/pos/t0699/B.scala
deleted file mode 100644
index f1f17ef..0000000
--- a/test/pending/pos/t0699/B.scala
+++ /dev/null
@@ -1,5 +0,0 @@
-object B {
-  trait T1 extends A.T
-  trait T2 extends A.C
-  class C1 extends A.C
-}
\ No newline at end of file
diff --git a/test/pending/pos/t0816.scala b/test/pending/pos/t0816.scala
deleted file mode 100644
index 38d531d..0000000
--- a/test/pending/pos/t0816.scala
+++ /dev/null
@@ -1,12 +0,0 @@
-abstract class Atest(val data: String)
-
-case class Btest(override val data: String, val b: boolean) extends Atest(data)
-
-case class Ctest(override val data: String) extends Btest(data, true)
-
-class testCaseClass {
-  def test(x: Atest) = x match {
-    case Ctest(data) => Console.println("C")  
-    case Btest(data, b) => Console.println("B")
-  }
-}
diff --git a/test/pending/pos/t1003.scala b/test/pending/pos/t1003.scala
index 70a4c54..27becdb 100644
--- a/test/pending/pos/t1003.scala
+++ b/test/pending/pos/t1003.scala
@@ -1,3 +1,3 @@
 object A {
-  classOf[String].getMethod("equals", Array(""))
+  classOf[String].getMethod("equals", "")
 }
diff --git a/test/pending/pos/t1035.scala b/test/pending/pos/t1035.scala
deleted file mode 100644
index 957b8ff..0000000
--- a/test/pending/pos/t1035.scala
+++ /dev/null
@@ -1,32 +0,0 @@
-//A fatal error or Scala compiler
-// Scala compiler version 2.7.1-final -- (c) 2002-2009 LAMP/EPFL
-// Carlos Loria cloria at artinsoft.com
-// 7/10/2008
-
-class A  {
-  var name:String = _
-  def getName() = name
-  def this(name:String, age:Int){this();this.name=name}
-  
-}
-
-class B(name:String) extends A(name,0){
-}
-
-class D {
-
-   object A {
-     def unapply(p:A) = Some(p.getName)
-   }
-   
-   object B {
-     def unapply(p:B) = Some(p.getName)
-   }
-   def foo(p:Any) = p match {
-      case B(n)    => println("B") 
-      case A(n)    => println("A")  
-      
-        
-   }
-
-}
\ No newline at end of file
diff --git a/test/pending/pos/t1107/Object.scala b/test/pending/pos/t1107/Object.scala
deleted file mode 100644
index 0fd0469..0000000
--- a/test/pending/pos/t1107/Object.scala
+++ /dev/null
@@ -1,10 +0,0 @@
-object O
-{
-   def d(t: Top) =
-      t match
-      {
-         case s: Sub => true
-         case _ => false
-      }
-}
-
diff --git a/test/pending/pos/t1107/Trait.scala b/test/pending/pos/t1107/Trait.scala
deleted file mode 100644
index cd213f9..0000000
--- a/test/pending/pos/t1107/Trait.scala
+++ /dev/null
@@ -1,9 +0,0 @@
-sealed trait Top
-sealed trait Sub extends Top
-
-trait C
-{
-   private object P extends Sub
-}
-
-
diff --git a/test/pending/pos/t1164.scala b/test/pending/pos/t1164.scala
deleted file mode 100644
index 6b1e313..0000000
--- a/test/pending/pos/t1164.scala
+++ /dev/null
@@ -1,29 +0,0 @@
-
-
-object test {  		
-
-	class Foo[a](val arg : a) 
-
-	object Foo  { 
-	def apply [a](arg : a, right :a) = new Foo[a](arg) 
-	def unapply [a](m : Foo[a]) = Some (m.arg) 
-	} 
-	
-	def matchAndGetArgFromFoo[a]( e:Foo[a]):a = {e match { case Foo(x) => x }}
-	
-	
-	//  Try the same thing as above but use function as arguemnt to Bar
-	// constructor
-	
-	type FunIntToA [a] = (int) => a
-	class Bar[a] (var f: FunIntToA[a]) 
-	
-	object Bar {
-		def apply[a](f: FunIntToA[a]) = new Bar[a](f)
-		def unapply[a](m: Bar[a]) = Some (m.f)
-	}
-	
-	def matchAndGetFunFromBar[a](b:Bar[a]) : FunIntToA[a] = { b match { case Bar(x) => x}}
-	 
-
-}
diff --git a/test/pending/pos/t1260.scala b/test/pending/pos/t1260.scala
deleted file mode 100644
index 775571d..0000000
--- a/test/pending/pos/t1260.scala
+++ /dev/null
@@ -1,17 +0,0 @@
-case class Foo(a: String, b: String)
-
-object Bar {
-  def unapply(s: String): Option[Long] =
-    try { Some(s.toLong) } catch { case _ => None }
-}
-
-object Test {
-  def main(args: Array[String]) {
-    val f = Foo("1", "2")
-    f match {
-      case Foo(Bar(1), Bar(2)) => ()
-      case Foo(Bar(i), Bar(j)) if i >= 0 => () 
-    }
-  }
-}
-
diff --git a/test/files/pos/t1380/gnujaxp.jar b/test/pending/pos/t1380/gnujaxp.jar
similarity index 100%
rename from test/files/pos/t1380/gnujaxp.jar
rename to test/pending/pos/t1380/gnujaxp.jar
diff --git a/test/files/pos/t1380/hallo.scala b/test/pending/pos/t1380/hallo.scala
similarity index 100%
rename from test/files/pos/t1380/hallo.scala
rename to test/pending/pos/t1380/hallo.scala
diff --git a/test/pending/pos/t1786.scala b/test/pending/pos/t1786.scala
new file mode 100644
index 0000000..dca2eda
--- /dev/null
+++ b/test/pending/pos/t1786.scala
@@ -0,0 +1,20 @@
+/** This a consequence of the current type checking algorithm, where bounds
+ *  are checked only after variables are instantiated. I believe this will change once we go to contraint-based type inference. Assigning low priority until then.
+ * 
+ *
+ */
+class SomeClass(val intValue:Int)
+class MyClass[T <: SomeClass](val myValue:T) 
+
+object Test extends Application {
+  def myMethod(i:MyClass[_]) {
+    i.myValue.intValue/2      // << error i is of type Any
+  }
+
+  def myMethod(i:MyClass[_ <: SomeClass]) {
+    i.myValue.intValue/2      // << works
+  }
+}
+/*
+The below code shows a compiler flaw in that the wildcard "_" as value for a bounded type parameter either breaks the boundry - as it result in Any - or doesnt (as id hoped it to be) evaluates to the boundy.
+*/
diff --git a/test/pending/pos/t2071.scala b/test/pending/pos/t2071.scala
new file mode 100644
index 0000000..a384cdf
--- /dev/null
+++ b/test/pending/pos/t2071.scala
@@ -0,0 +1,21 @@
+/**
+ * We still have to evaluate whether we will permit existentials
+ * with cross type dependencies. My current reaction would be no.
+ * Ticket stays open until a decision is made.
+ */
+trait Iterable[+S]
+trait Box[U]
+
+trait A {
+ type T <: Iterable[S] forSome { type S <: Box[U]; type U }
+}
+
+trait B extends A {
+ type T <: Iterable[S] forSome { type S <: Box[U]; type U }
+}
+/*
+But according to SLS, 3.5.1 Type Equivalence: Two existential types (§3.2.10) are equivalent if they have the same number of quantifiers, and, after renaming one list of type quantifiers by another, the quantified types as well as lower and upper bounds of corresponding quantifiers are equivalent.
+
+So, every existential type must be equivalent to (and conform to) itself.
+Attachments
+*/
diff --git a/test/pending/pos/t2099.scala b/test/pending/pos/t2099.scala
new file mode 100644
index 0000000..934b669
--- /dev/null
+++ b/test/pending/pos/t2099.scala
@@ -0,0 +1,27 @@
+// nice to have, not terribly urgent, maybe?
+
+I have a trait:
+
+trait Vis[+T]
+
+and an object/class pair:
+
+object VisImpl? { def apply() = new VisImpl? } class VisImpl? extends Vis[Missing]
+
+Where Missing is some class of mine. In a separate project (where Vis and VisImpl? are on the classpath but Missing is not), if I do:
+
+object Test extends Application {
+
+    val v = VisImpl?() println(v)
+
+}
+
+This causes a Scala compiler error (using 2.7.5 compiler). The error is:
+
+"Caused by java.lang.RuntimeException?: malformed Scala signature of VisImpl? at 3634; reference value data of package mypack refers to nonexisting symbol"
+
+Where mypack is the root package of the Missing class. This is not a helpful error as all my classes share the same root package and the problem is not in the VisImpl? declaration in any case.
+
+I would expect to see an error of the form:
+
+" Type parameter not found 'Missing': VisImpl? extends Vis[Missing] at Test: #4: val v = VisImpl?() "
diff --git a/test/pending/pos/t2162.scala b/test/pending/pos/t2162.scala
new file mode 100644
index 0000000..b214047
--- /dev/null
+++ b/test/pending/pos/t2162.scala
@@ -0,0 +1,20 @@
+// crash verified; no solution yet
+class Foo(x: Int)
+class Bar extends Foo(1)
+
+trait A {
+  def foo[T <: Foo]
+}
+class B extends A {
+  def foo[Bar] { println("B.foo[Bar]") }
+}
+object test {
+  val x = new B
+  val y = new A {
+    def foo[Bar] { println("A.foo[Bar]") }
+  }
+  def main(args: Array[String]) {
+    x.foo // ok
+    y.foo // java.lang.AssertionError: assertion failed (Erasure.scala:441 in r18338))
+  }
+}
diff --git a/test/pending/pos/t2173.scala b/test/pending/pos/t2173.scala
new file mode 100644
index 0000000..9a9a2ed
--- /dev/null
+++ b/test/pending/pos/t2173.scala
@@ -0,0 +1,17 @@
+
+
+This (somewhat convoluted) code fails to compile
+
+class A[+U>:Null] {
+
+    type R[+X>:Null] = X type O[+X] = A[R[X]]
+
+}
+
+with the following error:
+
+type arguments [A.this.R[X]] do not conform to class A's type parameter bounds [+U >: Null]
+
+However, because type R[+X>:Null] is identical to X, it should carry X bounds and R[X] lower bound should be known to be X's lower bound, i.e. Null.
+
+The same problem occurs with upper bounds.
diff --git a/test/pending/pos/t2179.scala b/test/pending/pos/t2179.scala
new file mode 100644
index 0000000..fd37d8f
--- /dev/null
+++ b/test/pending/pos/t2179.scala
@@ -0,0 +1,6 @@
+on trunk r18368, this delightful little poison pill:
+
+(Nil:List[List[Double]]).reduceLeft((_: Any, _: Any) => Nil.indices.map(_ => 0d))
+
+sends the compiler into an apparently infinite loop. a sample thread dump shows:
+
diff --git a/test/pending/pos/t2194.scala b/test/pending/pos/t2194.scala
new file mode 100644
index 0000000..e87be50
--- /dev/null
+++ b/test/pending/pos/t2194.scala
@@ -0,0 +1,8 @@
+// tricky to do differently?
+class C
+
+object Test {
+  def f = { object o extends C; o}
+  val y: C = f
+  val x = f
+}
diff --git a/test/pending/pos/t2625.scala b/test/pending/pos/t2625.scala
new file mode 100644
index 0000000..94240cb
--- /dev/null
+++ b/test/pending/pos/t2625.scala
@@ -0,0 +1,9 @@
+package t
+
+object T {
+  case class A(x: Int)(x: Int)
+
+  def A(x: Boolean): Int = 34
+
+  A(23)
+}
\ No newline at end of file
diff --git a/test/pending/pos/t2635.scala b/test/pending/pos/t2635.scala
new file mode 100644
index 0000000..378631b
--- /dev/null
+++ b/test/pending/pos/t2635.scala
@@ -0,0 +1,16 @@
+abstract class Base
+
+object Test
+{
+  def run(c: Class[_ <: Base]): Unit = {
+  }
+
+  def main(args: Array[String]): Unit =
+  {
+    val sc: Option[Class[_ <: Base]] = Some(classOf[Base])
+    sc match {
+      case Some((c: Class[_ <: Base])) => run(c)
+      case None =>
+    }
+  }
+}
\ No newline at end of file
diff --git a/test/pending/pos/t2641.scala b/test/pending/pos/t2641.scala
new file mode 100644
index 0000000..fec825c
--- /dev/null
+++ b/test/pending/pos/t2641.scala
@@ -0,0 +1,16 @@
+import scala.collection._
+import scala.collection.generic._
+
+abstract class ManagedSeqStrict[+A]
+        extends Traversable[A]
+        with GenericTraversableTemplate[A, ManagedSeqStrict]
+
+trait ManagedSeq[+A, +Coll]
+        extends ManagedSeqStrict[A]
+        with TraversableView[A, ManagedSeqStrict[A]]
+        with TraversableViewLike[A, ManagedSeqStrict[A], ManagedSeq[A/*ERROR: too few type args*/]]
+{ self =>
+  trait Transformed[+B] extends ManagedSeq[B, Coll] with super.Transformed[B]
+
+  trait Sliced extends Transformed[A] with super.Sliced
+}
\ No newline at end of file
diff --git a/test/pending/pos5/misc/A.java b/test/pending/pos5/misc/A.java
deleted file mode 100644
index bc8ea48..0000000
--- a/test/pending/pos5/misc/A.java
+++ /dev/null
@@ -1,13 +0,0 @@
-package test;
-
-import static test.A.STATE.UNDEF;
-
-class A {
-
-    public STATE state = UNDEF;
-
-	protected static enum STATE {
-		UNDEF
-	}
-
-}
\ No newline at end of file
diff --git a/test/pending/pos5/misc/B.scala b/test/pending/pos5/misc/B.scala
deleted file mode 100644
index 7524f35..0000000
--- a/test/pending/pos5/misc/B.scala
+++ /dev/null
@@ -1,7 +0,0 @@
-package test
-
-class B {
-	
-	def myA = new A()
-
-}
\ No newline at end of file
diff --git a/test/pending/pos5/misc/J.java b/test/pending/pos5/misc/J.java
deleted file mode 100644
index abaad86..0000000
--- a/test/pending/pos5/misc/J.java
+++ /dev/null
@@ -1,4 +0,0 @@
-class J {
-    void f (@Override{ name = value } int x) {}
-    void g (String ... x) {}
-}
diff --git a/test/pending/pos5/misc/S.scala b/test/pending/pos5/misc/S.scala
deleted file mode 100644
index af99333..0000000
--- a/test/pending/pos5/misc/S.scala
+++ /dev/null
@@ -1,4 +0,0 @@
-object Test extends J {
-  def h(xs: String*) {}
-  g("a", "b", "c")
-}
diff --git a/test/pending/res/bug837/DataFlowAnalysis.scala b/test/pending/res/bug837/DataFlowAnalysis.scala
index 0197f5f..25c2fbc 100644
--- a/test/pending/res/bug837/DataFlowAnalysis.scala
+++ b/test/pending/res/bug837/DataFlowAnalysis.scala
@@ -14,4 +14,4 @@ abstract class Liveness {
     type P = String;
     val lattice = livenessLattice;
   }
-}
\ No newline at end of file
+}
diff --git a/test/pending/run/arrays-2.scala b/test/pending/run/arrays-2.scala
index dac6c57..5f8096d 100644
--- a/test/pending/run/arrays-2.scala
+++ b/test/pending/run/arrays-2.scala
@@ -1,7 +1,6 @@
 //############################################################################
 // Arrays 2
 //############################################################################
-// $Id: $
 
 //############################################################################
 
diff --git a/test/pending/run/bug1042.scala b/test/pending/run/bug1042.scala
index 47c0c37..26b06a6 100644
--- a/test/pending/run/bug1042.scala
+++ b/test/pending/run/bug1042.scala
@@ -11,4 +11,4 @@ case class B extends A {
 
 object Test extends Application {
   Console.println(B)
-}
\ No newline at end of file
+}
diff --git a/test/pending/run/bug1079.scala b/test/pending/run/bug1079.scala
deleted file mode 100644
index 5e7f2fc..0000000
--- a/test/pending/run/bug1079.scala
+++ /dev/null
@@ -1,3 +0,0 @@
-object Test extends Application {
-  println(<t user:tag=""/> == <t user:tag="X"/>)
-}
\ No newline at end of file
diff --git a/test/pending/run/bug1697.scala b/test/pending/run/bug1697.scala
new file mode 100644
index 0000000..01590dd
--- /dev/null
+++ b/test/pending/run/bug1697.scala
@@ -0,0 +1,19 @@
+class Term
+case class Num(n: Int) extends Term
+case class Add(x: Term, y: Term) extends Term
+
+object Value {
+  def unapply(term: Any): Boolean = true
+}
+
+object Test {
+  def main(args: Array[String]) {
+    val term = Add(Num(1), Add(Num(2), Num(3)))
+    val res = term match {
+      case Add(Num(x), Num(y))    => "Add(Num, Num)"
+      case Add(Value(), y)        => "Add(Value, ?)"
+      case _                      => "?"
+    }
+    assert(res == "Add(Value, ?)")
+  }
+}
diff --git a/test/pending/run/bug2087.scala b/test/pending/run/bug2087.scala
new file mode 100644
index 0000000..787e411
--- /dev/null
+++ b/test/pending/run/bug2087.scala
@@ -0,0 +1,8 @@
+object Test {
+  def main(args: Array[String]): Unit = {
+    val s: Short = 0xFA99.toShort
+    val c: Char = 0xFA99.toChar
+    
+    assert((s == c) == (c == s))
+  }
+}
\ No newline at end of file
diff --git a/test/pending/run/bug2364.check b/test/pending/run/bug2364.check
new file mode 100644
index 0000000..219305e
--- /dev/null
+++ b/test/pending/run/bug2364.check
@@ -0,0 +1 @@
+<test></test>
diff --git a/test/pending/run/bug2364.scala b/test/pending/run/bug2364.scala
new file mode 100644
index 0000000..d5805a1
--- /dev/null
+++ b/test/pending/run/bug2364.scala
@@ -0,0 +1,60 @@
+import java.io.ByteArrayInputStream
+import java.io.ByteArrayOutputStream
+import com.sun.xml.internal.fastinfoset._
+import com.sun.xml.internal.fastinfoset.sax._
+import scala.xml.parsing.NoBindingFactoryAdapter
+import scala.xml._
+
+// Note - this is in pending because com.sun.xml.etc is not standard,
+// and I don't have time to extract a smaller test.
+
+object Test {
+	def main(args: Array[String]) {
+		val node = <test/>
+		val bytes = new ByteArrayOutputStream
+		val serializer = new SAXDocumentSerializer()
+
+		serializer.setOutputStream(bytes)
+		serializer.startDocument()
+		serialize(node, serializer)
+		serializer.endDocument()
+		println(parse(new ByteArrayInputStream(bytes.toByteArray)))
+	}
+	def serialize(node: Node, serializer: SAXDocumentSerializer) {
+		node match {
+		case _ : ProcInstr | _ : Comment | _ : EntityRef =>
+		case x : Atom[_] =>
+			val chars = x.text.toCharArray
+			serializer.characters(chars, 0, chars.length)
+		case _ : Elem =>
+			serializer.startElement("", node.label.toLowerCase, node.label.toLowerCase, attributes(node.attributes))
+			for (m <- node.child) serialize(m, serializer)
+			serializer.endElement("", node.label.toLowerCase, node.label.toLowerCase)
+		}
+	}
+	def parse(str: ByteArrayInputStream) = {
+		val parser = new SAXDocumentParser
+		val fac = new NoBindingFactoryAdapter
+
+		parser.setContentHandler(fac)
+		try {
+			parser.parse(str)
+		} catch {
+		case x: Exception =>
+			x.printStackTrace
+		}
+		fac.rootElem
+	}
+	def attributes(d: MetaData) = {
+		val attrs = new AttributesHolder
+
+		if (d != null) {
+			for (attr <- d) {
+				val sb = new StringBuilder()
+				Utility.sequenceToXML(attr.value, TopScope, sb, true)
+				attrs.addAttribute(new QualifiedName("", "", attr.key.toLowerCase), sb.toString)
+			}
+		}
+		attrs
+	}
+}
diff --git a/test/pending/run/bug2365/Test.scala b/test/pending/run/bug2365/Test.scala
new file mode 100644
index 0000000..75f0c39
--- /dev/null
+++ b/test/pending/run/bug2365/Test.scala
@@ -0,0 +1,35 @@
+import scala.tools.nsc.io._
+import java.net.URL
+
+object A { def apply(d: { def apply(): Int}) = d.apply() }
+object A2 { def apply(d: { def apply(): Int}) = d.apply() }
+object A3 { def apply(d: { def apply(): Int}) = d.apply() }
+object A4 { def apply(d: { def apply(): Int}) = d.apply() }
+
+class B extends Function0[Int] {
+	def apply() = 3
+}
+
+object Test
+{
+  type StructF0 = { def apply(): Int }
+	def main(args: Array[String]) {
+		for(i <- 0 until 150)
+			println(i + " " + test(A.apply) + " " + test(A2.apply) + " " + test(A3.apply) + " " + test(A3.apply))
+	}
+	
+	def test(withF0: StructF0 => Int): Int = {
+	  // Some large jar
+	  val ivyJar = File("/local/lib/java/ivy.jar").toURL
+	  // load a class in a separate loader that will be passed to A
+	  val loader = new java.net.URLClassLoader(Array(File(".").toURL, ivyJar))
+	  // load a real class to fill perm gen space
+    Class.forName("org.apache.ivy.Ivy", true, loader).newInstance 
+    // create a class from another class loader with an apply: Int method
+  	val b = Class.forName("B", true, loader).newInstance
+	
+		// pass instance to a, which will call apply using structural type reflection.
+		// This should hold on to the class for B, which means bLoader will not get collected
+	  withF0(b.asInstanceOf[StructF0])
+	}
+}
diff --git a/test/pending/run/bug2365/bug2365.javaopts b/test/pending/run/bug2365/bug2365.javaopts
new file mode 100644
index 0000000..357e033
--- /dev/null
+++ b/test/pending/run/bug2365/bug2365.javaopts
@@ -0,0 +1 @@
+-XX:MaxPermSize=25M
diff --git a/test/pending/run/bug2365/run b/test/pending/run/bug2365/run
new file mode 100644
index 0000000..f3c44ad
--- /dev/null
+++ b/test/pending/run/bug2365/run
@@ -0,0 +1,13 @@
+#!/bin/sh
+#
+# This script should fail with any build of scala where #2365
+# is not fixed, and otherwise succeed.  Failure means running out
+# of PermGen space.
+
+CP=.:/local/lib/java/ivy.jar
+# SCALAC=/scala/inst/28/bin/scalac
+SCALAC=scalac
+RUN_OPTS="-XX:MaxPermSize=25M -verbose:gc"
+
+$SCALAC -cp $CP *.scala
+JAVA_OPTS="${RUN_OPTS}" scala -cp $CP Test
diff --git a/test/pending/run/bug3050.scala b/test/pending/run/bug3050.scala
new file mode 100644
index 0000000..2b85149
--- /dev/null
+++ b/test/pending/run/bug3050.scala
@@ -0,0 +1,10 @@
+object Test {
+  def main(args: Array[String]): Unit = {
+    val x = 
+      try { ("": Any) match { case List(_*) => true } }
+      catch { case _ => false }
+    
+    assert(x == false)
+  }
+}
+  
\ No newline at end of file
diff --git a/test/pending/run/bug3150.scala b/test/pending/run/bug3150.scala
new file mode 100644
index 0000000..8acdb50
--- /dev/null
+++ b/test/pending/run/bug3150.scala
@@ -0,0 +1,10 @@
+object Test {
+  case object Bob { override def equals(other: Any) = true }
+  def f(x: Any) = x match { case Bob => Bob }
+  
+  def main(args: Array[String]): Unit = {
+    assert(f(Bob) eq Bob)
+    assert(f(0) eq Bob)
+    assert(f(Nil) eq Bob)
+  }
+}
diff --git a/test/pending/run/hashCodeDistribution.flags b/test/pending/run/hashCodeDistribution.flags
new file mode 100644
index 0000000..7806652
--- /dev/null
+++ b/test/pending/run/hashCodeDistribution.flags
@@ -0,0 +1 @@
+-Yjenkins-hashCodes
\ No newline at end of file
diff --git a/test/pending/run/hashCodeDistribution.scala b/test/pending/run/hashCodeDistribution.scala
new file mode 100644
index 0000000..5be9d1d
--- /dev/null
+++ b/test/pending/run/hashCodeDistribution.scala
@@ -0,0 +1,17 @@
+// See ticket #2537.
+object Test {
+  case class C(x: Int, y: Int) { }
+  val COUNT = 300
+  val totalCodes = COUNT * COUNT
+
+  def main (args: Array[String]) = {
+    val hashCodes =
+      for (x <- 0 until COUNT; y <- 0 until COUNT) yield C(x,y).hashCode
+
+    val uniques = hashCodes.distinct
+    val collisionRate = (totalCodes - uniques.size) * 1000 / totalCodes
+
+    assert(collisionRate < 5, "Collision rate too high: %d / 1000".format(collisionRate))
+    // println("collisionRate = %d / 1000".format(collisionRate))
+  }
+}
\ No newline at end of file
diff --git a/test/pending/run/instanceOfAndTypeMatching.scala b/test/pending/run/instanceOfAndTypeMatching.scala
new file mode 100644
index 0000000..5273060
--- /dev/null
+++ b/test/pending/run/instanceOfAndTypeMatching.scala
@@ -0,0 +1,193 @@
+// Summary of incorrect or questionable behavior.
+// Full code and successful parts follow.
+
+object Summary {
+  class Outer {
+    class Inner { }
+    def f() = { class MethodInner ; new MethodInner }
+  }
+  
+  // 1 static issue:
+  // 
+  //   Given method in MethodInner: def g(other: MethodInner) = ()
+  //   method1.g(method1) fails to compile with type error.
+  //
+  //   Note that this cannot be worked around by widening the return type
+  //   of f() because MethodInner is declared inside of f.  So there is no way
+  //   I see for a class declared inside a method to receive members of its
+  //   own declared type -- not only the narrow type of those from this
+  //   instance, but ANY members, because there is no Foo#Bar syntax which will
+  //   traverse a method.
+  //
+  // 4 runtime issues:
+  // 
+  //   From the outside:     inner1.isInstanceOf[outer2.Inner] is true, should (maybe) be false
+  //   From inside inner1:   inner2.isInstanceOf[Outer.this.Inner] is true, should (maybe) be false
+  //   From the outside:     inner1 match { case _: outer2.Inner => true ... } is true, should definitely be false
+  //   From inside method1:  method2 match { case _: MethodInner => true ... } is true, should definitely be false
+  //
+  //   Note that the fact that every test returns true on instances of MethodInner means
+  //   that it is impossible to draw any type distinction between instances.  As far as one
+  //   can tell, they are all of the same type regardless not only of whether they were
+  //   created on the same method invocation but whether they are contained in the same
+  //   instance of Outer.
+  //
+  //   WRT "same method invocation", see Iterator.duplicate for an example of this.
+}
+
+// Tests
+
+class Outer {
+  class Inner {
+    def passOuter(other: Outer) = ()                  // pass any Outer
+    def passThisType(other: Outer.this.type) = ()     // pass only this Outer instance
+    def passInner(other: Inner) = ()                  // pass only Inners from this Outer instance
+    def passInner2(other: Outer.this.Inner) = ()      // same as above
+    def passInnerSharp(other: Outer#Inner) = ()       // pass any Inner
+    
+    def compareSimpleWithTypeMatch(other: Any) = other match {
+      case _: Inner => true
+      case _        => false
+    }
+    def compareSimpleWithInstanceOf(other: Any) = other.isInstanceOf[Inner]
+    
+    def compareSharpWithTypeMatch(other: Any) = {
+      other match {
+        case _: Outer#Inner => true
+        case _              => false
+      }
+    }
+    def compareSharpWithInstanceOf(other: Any) = other.isInstanceOf[Outer#Inner]
+    
+    def comparePathWithTypeMatch(other: Any) = other match {
+      case _: Outer.this.Inner  => true
+      case _                    => false
+    }
+    def comparePathWithInstanceOf(other: Any) = other.isInstanceOf[Outer.this.Inner]    
+  }
+  
+  def f() = {
+    class MethodInner { 
+      def passOuter(other: Outer) = ()                  // pass any Outer
+      def passThisType(other: Outer.this.type) = ()     // pass only this Outer instance
+      def passInner(other: Inner) = ()                  // pass only Inners from this Outer instance
+      def passInner2(other: Outer.this.Inner) = ()      // same as above
+      def passInnerSharp(other: Outer#Inner) = ()       // pass any Inner
+      def passMethodInner(other: MethodInner) = ()      // pass only MethodInners from this Outer instance
+      // is there any way to refer to Outer#MethodInner? Not that there should be.
+      
+      def compareWithInstanceOf(other: Any) = other.isInstanceOf[MethodInner]
+      def compareWithTypeMatch(other: Any) = other match {
+        case _: MethodInner => true
+        case _              => false
+      }
+    }
+    
+    new MethodInner
+  }
+}
+
+object Test 
+{
+  val outer1 = new Outer
+  val outer2 = new Outer
+  val inner1 = new outer1.Inner
+  val inner2 = new outer2.Inner
+  val method1 = outer1.f()
+  val method2 = outer2.f()
+  
+  def testInnerStatic = {
+    // these should all work
+    inner1.passOuter(outer1)
+    inner1.passOuter(outer2)
+    inner1.passThisType(outer1)
+    inner1.passInner(inner1)
+    inner1.passInner2(inner1)
+    inner1.passInnerSharp(inner1)
+    inner1.passInnerSharp(inner2)
+    
+    // these should all fail to compile, and do
+    //
+    // inner1.passThisType(outer2)
+    // inner1.passInner(inner2)
+    // inner1.passInner2(inner2)
+  }
+  def testInnerRuntime = {
+    println("testInnerRuntime\n")
+    
+    List("These should be true under any scenario: ",
+      inner1.isInstanceOf[outer1.Inner] , 
+      inner1.isInstanceOf[Outer#Inner] ,
+      inner1 match { case _: Outer#Inner => true ; case _ => false } ,
+      inner1 match { case _: outer1.Inner => true ; case _ => false } ,
+      inner1.compareSharpWithTypeMatch(inner2) ,
+      inner1.compareSharpWithInstanceOf(inner2)
+    ) foreach println
+    
+    List("These should be true under current proposal: ",
+      inner1.compareSimpleWithInstanceOf(inner2) 
+    ) foreach println
+    
+    List("These should be false under current proposal: ",
+      inner1.compareSimpleWithTypeMatch(inner2) ,
+      inner1.comparePathWithTypeMatch(inner2) 
+    ) foreach println
+    
+    List("These return true but I think should return false: ", 
+      inner1.isInstanceOf[outer2.Inner] ,               // true
+      inner1.comparePathWithInstanceOf(inner2)          // true
+    ) foreach println
+    
+    List("These are doing the wrong thing under current proposal",
+      inner1 match { case _: outer2.Inner => true ; case _ => false }    // should be false
+    ) foreach println
+  }
+
+  def testMethodInnerStatic = {
+    // these should all work
+    method1.passOuter(outer1)
+    method1.passOuter(outer2)
+    method1.passThisType(outer1)
+    method1.passInner(inner1)
+    method1.passInner2(inner1)
+    method1.passInnerSharp(inner1)
+    method1.passInnerSharp(inner2)
+    // This fails with:
+    //
+    // a.scala:114: error: type mismatch;
+    //  found   : Test.method1.type (with underlying type MethodInner forSome { type MethodInner <: java.lang.Object with ScalaObject{def passOuter(other: Outer): Unit; def passThisType(other: Test.outer1.type): Unit; def passInner(other: Test.outer1.Inner): Unit; def passInner2(other: Test.outer1.Inner): Unit; def passInnerSharp(other: Outer#Inner): Unit; def passMethodInner(other: MethodInner): Unit} })
+    //  required: MethodInner where type MethodInner <: java.lang.Object with ScalaObject{def passOuter(other: Outer): Unit; def passThisType(other: Test.outer1.type): Unit; def passInner(other: Test.outer1.Inner): Unit; def passInner2(other: Test.outer1.Inner): Unit; def passInnerSharp(other: Outer#Inner): Unit; def passMethodInner(other: MethodInner): Unit}
+    //     method1.passMethodInner(method1)
+    //                             ^
+    // method1.passMethodInner(method1)
+    
+    // these should all fail to compile, and do
+    //
+    // method1.passThisType(outer2)
+    // method1.passInner(inner2)
+    // method1.passInner2(inner2)
+    // method1.passMethodInner(method2)
+  }
+  
+  def testMethodInnerRuntime = {
+    println("\ntestMethodInnerRuntime\n")
+    
+    List("These should be true under any scenario: ",
+      method1.compareWithInstanceOf(method1) ,
+      method1.compareWithTypeMatch(method1) 
+    ) foreach println
+    
+    List("These should be true under current proposal: ",
+      method1.compareWithInstanceOf(method2)
+    ) foreach println
+    
+    List("These are doing the wrong thing under current proposal",
+      method1.compareWithTypeMatch(method2)    // should be false
+    ) foreach println
+  }
+  
+  def main(args: Array[String]): Unit = {
+    testInnerRuntime
+    testMethodInnerRuntime
+  }
+}
diff --git a/test/pending/run/string-reverse.scala b/test/pending/run/string-reverse.scala
new file mode 100644
index 0000000..976a970
--- /dev/null
+++ b/test/pending/run/string-reverse.scala
@@ -0,0 +1,22 @@
+/** In case we ever feel like taking on unicode string reversal.
+ *  See ticket #2565.
+ */
+object Test {
+  val xs = "Les Mise\u0301rables"   // this is the tricky one to reverse
+  val ys = "Les Misérables"
+  val xs2 = new StringBuilder(xs)
+  val ys2 = new StringBuilder(ys)
+  
+  def main(args: Array[String]): Unit = {
+    val out = new java.io.PrintStream(System.out, true, "UTF-8")
+    
+    out.println("Strings")
+    List(xs, xs.reverse, ys, ys.reverse) foreach (out println _)
+    
+    out.println("StringBuilder")
+    out.println(xs2.toString)
+    out.println(xs2.reverseContents().toString)
+    out.println(ys2.toString)
+    out.println(ys2.reverseContents().toString)
+  }
+}
\ No newline at end of file
diff --git a/test/pending/run/t0446.scala b/test/pending/run/t0446.scala
index e768896..0f74b32 100644
--- a/test/pending/run/t0446.scala
+++ b/test/pending/run/t0446.scala
@@ -3,4 +3,4 @@ object Test extends Application {
   val b = Array(1,3).dropWhile(_ < 2)
   println(a.toString)
   println(b.toString)
-}
\ No newline at end of file
+}
diff --git a/test/pending/run/t1044.scala b/test/pending/run/t1044.scala
index 136cc51..c521e58 100644
--- a/test/pending/run/t1044.scala
+++ b/test/pending/run/t1044.scala
@@ -1,4 +1,5 @@
+// looks OK
 object Main extends Application{
  val ducks = Array[AnyRef]("Huey", "Dewey", "Louie")
- ducks.elements/*.asInstanceOf[Iterator[String]]*/
+ ducks.iterator/*.asInstanceOf[Iterator[String]]*/
 }
diff --git a/test/pending/run/t1939.scala b/test/pending/run/t1939.scala
new file mode 100644
index 0000000..44ab176
--- /dev/null
+++ b/test/pending/run/t1939.scala
@@ -0,0 +1,41 @@
+// works in trunk
+class Module {}
+
+abstract class T {
+  type moduleType <: Module
+  def module: moduleType
+}
+
+final class T1(val module: Module) extends T {
+  type moduleType = Module
+}
+
+final class T2(_module: Module) extends T {
+  type moduleType = Module
+
+  def module = _module
+}
+
+object Main extends Application {
+
+  type mType = Module
+
+  type tType = T { type moduleType <: mType }
+  // type tType = T { type moduleType <: Module } // runs successfully
+  // type tType = T // runs successfully
+
+  def f(ts: List[tType]): Unit = {
+
+    for (t <- ts; m = t.module) {}
+    ts.map(_.module).foreach { _ => () }
+    // ts.map(t => (t : T).module).foreach { _ => () } // runs successfully
+  }
+
+  f(new T1(new Module) :: new T2(new Module) :: Nil)
+}
+
+/*
+ * java.lang.AbstractMethodError
+        at scala.List.foreach(List.scala:849)
+        at Main$.f
+*/
diff --git a/test/pending/run/t1980.scala b/test/pending/run/t1980.scala
new file mode 100644
index 0000000..9ecf5a4
--- /dev/null
+++ b/test/pending/run/t1980.scala
@@ -0,0 +1,27 @@
+by-name argument incorrectly evaluated on :-ending operator
+Reported by: 	extempore 	Owned by: 	odersky
+Priority: 	normal 	Component: 	Compiler
+Keywords: 		Cc: 	paulp@…
+Fixed in version: 	
+Description
+
+scala> def foo() = { println("foo") ; 5 }
+foo: ()Int
+
+scala> class C { def m1(f: => Int) = () ; def m2_:(f: => Int) = () }
+defined class C
+
+scala> val c = new C
+c: C = C at 96d484
+
+scala> c m1 foo()
+
+scala> foo() m2_: c
+foo
+
+But it is not evaluated if invoked directly:
+
+scala> c.m2_:(foo())
+
+scala>
+
diff --git a/test/pending/run/t2034.scala b/test/pending/run/t2034.scala
new file mode 100644
index 0000000..a599dc2
--- /dev/null
+++ b/test/pending/run/t2034.scala
@@ -0,0 +1,15 @@
+// no idea, reassigned to Iulian
+object Test {
+
+  def main(args: Array[String]) {
+    val fooz = new foo.foo2
+    println(fooz)
+  }
+
+  object foo {
+    class foo2 {
+      override def toString = getClass.toString//.getSimpleName
+    }
+  }
+
+}
diff --git a/test/pending/run/t3609.scala b/test/pending/run/t3609.scala
new file mode 100644
index 0000000..2629481
--- /dev/null
+++ b/test/pending/run/t3609.scala
@@ -0,0 +1,11 @@
+object Test extends Application {
+  class A
+  class B extends A
+  def foo(x: A, y: B) = print(1)
+  val foo = new {
+    //def apply(x: B, y: A) = print(3)
+    def apply = (x: B, z: B) => print(4)
+  }
+
+  foo(new B, new B)
+}
diff --git a/test/pending/run/treesetmap.check b/test/pending/run/treesetmap.check
new file mode 100644
index 0000000..c55dc06
--- /dev/null
+++ b/test/pending/run/treesetmap.check
@@ -0,0 +1 @@
+class scala.collection.immutable.TreeMap
diff --git a/test/pending/run/treesetmap.scala b/test/pending/run/treesetmap.scala
new file mode 100644
index 0000000..60902d2
--- /dev/null
+++ b/test/pending/run/treesetmap.scala
@@ -0,0 +1,5 @@
+object Test{
+  def main(args : Array[String]){
+    println(scala.collection.immutable.TreeSet(1, 2, 3).map(x => x).getClass);
+  }
+}
diff --git a/test/pending/scalacheck/array.scala b/test/pending/scalacheck/array.scala
new file mode 100644
index 0000000..f262bc6
--- /dev/null
+++ b/test/pending/scalacheck/array.scala
@@ -0,0 +1,37 @@
+import org.scalacheck._
+import Prop._
+import Gen._
+import Arbitrary._
+import util._
+import Buildable._
+import scala.collection.mutable.ArraySeq
+
+object Test extends Properties("Array") {
+  /** At this moment the authentic scalacheck Array Builder/Arb bits are commented out.
+   */
+  implicit def arbArray[T](implicit a: Arbitrary[T], m: Manifest[T]): Arbitrary[Array[T]] =
+    Arbitrary(containerOf[List,T](arbitrary[T]) map (_.toArray))
+  
+  val arrGen: Gen[Array[_]] = oneOf(
+    arbitrary[Array[Int]],
+    arbitrary[Array[Array[Int]]],
+    arbitrary[Array[List[String]]],
+    arbitrary[Array[String]],
+    arbitrary[Array[Boolean]],
+    arbitrary[Array[AnyVal]]
+  )
+  
+  // inspired by #1857 and #2352
+  property("eq/ne") = forAll(arrGen, arrGen) { (c1, c2) =>
+    (c1 eq c2) || (c1 ne c2)
+  }
+
+  // inspired by #2299
+  def smallInt = choose(1, 10)
+  property("ofDim") = forAll(smallInt, smallInt, smallInt) { (i1, i2, i3) =>
+    val arr = Array.ofDim[String](i1, i2, i3)
+    val flattened = arr flatMap (x => x) flatMap (x => x)
+    flattened.length == i1 * i2 * i3
+  }                                                                             
+}
+
diff --git a/test/pending/scalacheck/eqeq.scala b/test/pending/scalacheck/eqeq.scala
new file mode 100644
index 0000000..a783805
--- /dev/null
+++ b/test/pending/scalacheck/eqeq.scala
@@ -0,0 +1,37 @@
+import org.scalacheck._
+import Prop._
+import Gen._
+
+object Test extends Properties("==") {
+  def equalObjectsEqualHashcodes(x: Any, y: Any) = (x != y) || (x == y && x.## == y.##)
+  
+  // ticket #2087
+  property("short/char") = forAll { (x: Short) => {
+      val ch: Char = x.toChar
+      (x == ch) == (ch == x)
+    }
+  }
+
+  property("symmetry") = forAll { (x: AnyVal, y: AnyVal) => (x == y) == (y == x) }
+  property("transitivity") = forAll { (x: AnyVal, y: AnyVal, z: AnyVal) => x != y || y != z || x == z }
+  
+  property("##") = forAll { 
+    (x: Short) => {
+      val anyvals = List(x.toByte, x.toChar, x, x.toInt, x.toLong, x.toFloat, x.toDouble, BigInt(x), BigDecimal(x))
+      val shortAndLarger = anyvals drop 2
+
+      val result = (
+        ((anyvals, anyvals).zipped forall equalObjectsEqualHashcodes) && 
+        ((shortAndLarger, shortAndLarger).zipped forall (_ == _)) && 
+        ((shortAndLarger, shortAndLarger).zipped forall ((x, y) => (x: Any) == (y: Any)))
+      )
+      result
+    }
+  }
+  property("## 2") = forAll {
+    (dv: Double) => {
+      val fv = dv.toFloat
+      (fv != dv) || (fv.## == dv.##)
+    }
+  }
+}
diff --git a/test/pending/scalacheck/list.scala b/test/pending/scalacheck/list.scala
new file mode 100644
index 0000000..dfa8446
--- /dev/null
+++ b/test/pending/scalacheck/list.scala
@@ -0,0 +1,21 @@
+import org.scalacheck._
+import Prop._
+import Gen._
+
+object Test extends Properties("List") {
+  def sorted(xs: List[Int]) = xs sortWith (_ < _)
+
+  property("concat size") = forAll { (l1: List[Int], l2: List[Int]) => (l1.size + l2.size) == (l1 ::: l2).size }
+  property("reverse") = forAll { (l1: List[Int]) => l1.reverse.reverse == l1 }
+  property("toSet") = forAll { (l1: List[Int]) => sorted(l1.toSet.toList) sameElements sorted(l1).distinct }
+  property("flatten") = forAll { (xxs: List[List[Int]]) => xxs.flatten.length == (xxs map (_.length) sum) }
+  property("startsWith/take") = forAll { (xs: List[Int], count: Int) => xs startsWith (xs take count) }
+  property("endsWith/takeRight") = forAll { (xs: List[Int], count: Int) => xs endsWith (xs takeRight count) }
+  property("fill") = forAll(choose(1, 100)) { count =>
+    forAll { (x: Int) => 
+      val xs = List.fill(count)(x)
+      (xs.length == count) && (xs.distinct == List(x))
+    }
+  }
+}
+
diff --git a/test/pending/scalacheck/range.scala b/test/pending/scalacheck/range.scala
new file mode 100644
index 0000000..364c694
--- /dev/null
+++ b/test/pending/scalacheck/range.scala
@@ -0,0 +1,205 @@
+import org.scalacheck._
+import Prop._
+import Gen._
+import Arbitrary._
+
+class Counter(r: Range) {
+  var cnt = 0L
+  var last: Option[Int] = None
+  val str = "Range["+r.start+", "+r.end+", "+r.step+(if (r.isInclusive) "]" else ")")
+  def apply(x: Int) = {
+    cnt += 1L
+    if (cnt % 500000000L == 0L) {
+      println("Working: %s %d %d" format (str, cnt, x))
+    }
+    if (cnt > (Int.MaxValue.toLong + 1) * 2)
+      error("Count exceeds maximum possible for an Int Range")
+    if ((r.step > 0 && last.exists(_ > x)) || (r.step < 0 && last.exists(_ < x)))
+      error("Range wrapped: %d %s" format (x, last.toString))
+    last = Some(x)
+  }
+}
+  
+abstract class RangeTest(kind: String) extends Properties("Range "+kind) {
+  def myGen: Gen[Range]
+
+  val genRange = for {
+    start <- arbitrary[Int]
+    end <- arbitrary[Int]
+    step <- Gen.choose(1, (start - end).abs + 1)
+  } yield if (start < end) Range(start, end, step) else Range(start, end, -step)
+  
+  val genReasonableSizeRange = for {
+    start <- choose(-Int.MinValue, Int.MaxValue)
+    end <- choose(-Int.MinValue, Int.MaxValue)
+    step <- choose(-Int.MaxValue, Int.MaxValue)
+  } yield Range(start, end, if (step == 0) 100 else step)
+  
+  val genSmallRange = for {
+    start <- choose(-100, 100)
+    end <- choose(-100, 100)
+    step <- choose(1, 1)
+  } yield if (start < end) Range(start, end, step) else Range(start, end, -step)
+  
+  val genRangeByOne = for {
+    start <- arbitrary[Int]
+    end <- arbitrary[Int]
+    if (end.toLong - start.toLong).abs <= 10000000L 
+  } yield if (start < end) Range(start, end) else Range(end, start)
+  
+  def str(r: Range) = "Range["+r.start+", "+r.end+", "+r.step+(if (r.isInclusive) "]" else ")")
+  
+  def expectedSize(r: Range): Long = if (r.isInclusive) {
+    (r.end.toLong - r.start.toLong < 0, r.step < 0) match {
+      case (true, true) | (false, false) => (r.end.toLong - r.start.toLong).abs / r.step.abs.toLong + 1L
+      case _ => if (r.start == r.end) 1L else 0L
+    }
+  } else {
+    (r.end.toLong - r.start.toLong < 0, r.step < 0) match {
+      case (true, true) | (false, false) => (
+        (r.end.toLong - r.start.toLong).abs / r.step.abs.toLong 
+        + (if ((r.end.toLong - r.start.toLong).abs % r.step.abs.toLong > 0L) 1L else 0L)
+      )
+      case _ => 0L
+    }
+  }
+  
+  def within(r: Range, x: Int) = if (r.step > 0)
+    r.start <= x && (if (r.isInclusive) x <= r.end else x < r.end)
+  else
+    r.start >= x && (if (r.isInclusive) x >= r.end else x > r.end)
+    
+  def multiple(r: Range, x: Int) = (x.toLong - r.start) % r.step == 0 
+  
+  property("foreach.step") = forAll(myGen) { r => 
+    var allValid = true
+    val cnt = new Counter(r)
+//    println("--------------------")
+//    println(r)
+    r foreach { x => cnt(x)
+//      println(x + ", " + (x - r.start) + ", " + (x.toLong - r.start) + ", " + ((x.toLong - r.start) % r.step))
+      allValid &&= multiple(r, x)
+    }
+    allValid :| str(r)
+  }
+
+  property("foreach.inside.range") = forAll(myGen) { r => 
+    var allValid = true
+    var last: Option[Int] = None
+    val cnt = new Counter(r)
+    r foreach { x => cnt(x)
+      allValid &&= within(r, x)
+    }
+    allValid :| str(r)
+  }
+
+  property("foreach.visited.size") = forAll(myGen) { r => 
+    var visited = 0L
+    val cnt = new Counter(r)
+    r foreach { x => cnt(x)
+      visited += 1L
+    }
+//    println("----------")
+//    println(str(r))
+//    println("size: " + r.size)
+//    println("expected: " + expectedSize(r))
+//    println("visited: " + visited)
+    (visited == expectedSize(r)) :| str(r)
+  }
+  
+  property("length") = forAll(myGen suchThat (r => expectedSize(r).toInt == expectedSize(r))) { r =>
+    (r.length == expectedSize(r)) :| str(r)
+  }
+
+  property("isEmpty") = forAll(myGen suchThat (r => expectedSize(r).toInt == expectedSize(r))) { r =>
+    (r.isEmpty == (expectedSize(r) == 0L)) :| str(r)
+  }
+  
+  property("contains") = forAll(myGen, arbInt.arbitrary) { (r, x) =>
+//    println("----------------")
+//    println(str(r))
+//    println(x)
+//    println("within: " + within(r, x))
+//    println("multiple: " + multiple(r, x))
+//    println("contains: " + r.contains(x))
+    ((within(r, x) && multiple(r, x)) == r.contains(x)) :| str(r)+": "+x
+  }
+  
+  property("take") = forAll(myGen suchThat (r => expectedSize(r).toInt == expectedSize(r)), arbInt.arbitrary) { (r, x) =>
+    val t = r take x
+    (t.size == (0 max x min r.size) && t.start == r.start && t.step == r.step) :| str(r)+" / "+str(t)+": "+x
+  }
+  
+  property("takeWhile") = forAll(myGen suchThat (r => expectedSize(r).toInt == expectedSize(r)), arbInt.arbitrary) { (r, x) =>
+    val t = (if (r.step > 0) r takeWhile (_ <= x) else r takeWhile(_ >= x))
+    if (r.size == 0) {
+      (t.size == 0) :| str(r)+" / "+str(t)+": "+x
+    } else {
+      val t2 = (if (r.step > 0) Range(r.start, x min r.last, r.step).inclusive else Range(r.start, x max r.last, r.step).inclusive)
+      (t.start == r.start && t.size == t2.size && t.step == r.step) :| str(r)+" / "+str(t)+" / "+str(t2)+": "+x
+    }
+  }
+  
+  property("reverse.toSet.equal") = forAll(myGen) { r =>
+    val reversed = r.reverse
+    val aresame = r.toSet == reversed.toSet
+    if (!aresame) {
+      println(str(r))
+      println(r)
+      println(reversed)
+      println(r.toSet)
+      println(reversed.toSet)
+    }
+    aresame
+  }
+}
+
+object NormalRangeTest extends RangeTest("normal") {
+  override def myGen = genReasonableSizeRange
+  def genOne = for {
+    start <- arbitrary[Int]
+    end <- arbitrary[Int]
+    if (start.toLong - end.toLong).abs < Int.MaxValue.toLong
+  } yield Range(start, end, if (start < end) 1 else - 1)
+  property("by 1.size + 1 == inclusive.size") = forAll(genOne) { r =>
+    (r.size + 1 == r.inclusive.size) :| str(r)  
+  }
+}
+
+object InclusiveRangeTest extends RangeTest("inclusive") {
+  override def myGen = for (r <- genReasonableSizeRange) yield r.inclusive
+}
+
+object ByOneRangeTest extends RangeTest("byOne") {
+  override def myGen = genSmallRange
+}
+
+object InclusiveByOneRangeTest extends RangeTest("inclusiveByOne") {
+  override def myGen = for (r <- genSmallRange) yield r.inclusive
+}
+
+object SmallValuesRange extends RangeTest("smallValues") {
+  override def myGen = genSmallRange
+}
+
+object Test extends Properties("Range") {
+  include(NormalRangeTest)
+  include(InclusiveRangeTest)
+  include(ByOneRangeTest)
+  include(InclusiveByOneRangeTest)
+}
+
+/* Mini-benchmark
+def testRange(i: Int, j: Int, k: Int) = {
+  var count = 0
+  for {
+    vi <- 0 to i
+    vj <- 0 to j
+    vk <- 0 to k
+  } { count += 1 }
+}
+
+testRange(10, 1000, 10000)
+testRange(10000, 1000, 10)
+*/
+
diff --git a/test/pending/scalacheck/scan.scala b/test/pending/scalacheck/scan.scala
new file mode 100644
index 0000000..e9b25ce
--- /dev/null
+++ b/test/pending/scalacheck/scan.scala
@@ -0,0 +1,17 @@
+import org.scalacheck._
+import Prop._
+import Gen._
+
+
+object Test extends Properties("TraversableLike.scanLeft") {
+  property("scanLeft") = forAll { (xs: List[Int], z: Int) => {
+    val sums = xs.scanLeft(z)(_ + _)
+    (xs.size == 0) || sums.zip(sums.tail).map(x => x._2 - x._1) == xs
+  }}
+}
+
+
+
+
+
+
diff --git a/test/pending/script/bug2365.javaopts b/test/pending/script/bug2365.javaopts
new file mode 100644
index 0000000..357e033
--- /dev/null
+++ b/test/pending/script/bug2365.javaopts
@@ -0,0 +1 @@
+-XX:MaxPermSize=25M
diff --git a/test/pending/script/bug2365/Test.scala b/test/pending/script/bug2365/Test.scala
new file mode 100644
index 0000000..110dea2
--- /dev/null
+++ b/test/pending/script/bug2365/Test.scala
@@ -0,0 +1,35 @@
+import scala.tools.nsc.io._
+import java.net.URL
+
+object A { def apply(d: { def apply(): Int}) = d.apply() }
+object A2 { def apply(d: { def apply(): Int}) = d.apply() }
+object A3 { def apply(d: { def apply(): Int}) = d.apply() }
+object A4 { def apply(d: { def apply(): Int}) = d.apply() }
+
+class B extends Function0[Int] {
+	def apply() = 3
+}
+
+object Test
+{
+  type StructF0 = { def apply(): Int }
+	def main(args: Array[String]) {
+		for(i <- 0 until 150)
+			println(i + " " + test(A.apply) + " " + test(A2.apply) + " " + test(A3.apply) + " " + test(A3.apply))
+	}
+	
+	def test(withF0: StructF0 => Int): Int = {
+	  // Some large jar
+	  val jar = File("../../../../lib/scalacheck.jar").toURL
+	  // load a class in a separate loader that will be passed to A
+	  val loader = new java.net.URLClassLoader(Array(File(".").toURL, jar))
+	  // load a real class to fill perm gen space
+    Class.forName("org.scalacheck.Properties", true, loader).newInstance 
+    // create a class from another class loader with an apply: Int method
+  	val b = Class.forName("B", true, loader).newInstance
+	
+		// pass instance to a, which will call apply using structural type reflection.
+		// This should hold on to the class for B, which means bLoader will not get collected
+	  withF0(b.asInstanceOf[StructF0])
+	}
+}
diff --git a/test/pending/script/bug2365/bug2365.scala b/test/pending/script/bug2365/bug2365.scala
new file mode 100644
index 0000000..b5e0532
--- /dev/null
+++ b/test/pending/script/bug2365/bug2365.scala
@@ -0,0 +1,9 @@
+#!/bin/sh
+#
+# This script should fail with any build of scala where #2365
+# is not fixed, and otherwise succeed.  Failure means running out
+# of PermGen space.
+#
+
+scalac -cp .:/local/lib/java/ivy.jar Test.scala
+JAVA_OPTS="-XX:MaxPermSize=25M -verbose:gc" scalac -cp $CP Test
diff --git a/test/pending/shootout/fasta.scala.runner b/test/pending/shootout/fasta.scala.runner
index 7254038..89b43d7 100644
--- a/test/pending/shootout/fasta.scala.runner
+++ b/test/pending/shootout/fasta.scala.runner
@@ -1,3 +1,3 @@
 object Test extends Application {
   for(val n <- List(25000,250000,2500000)) fasta.main(Array(n.toString)) 
-}
\ No newline at end of file
+}
diff --git a/test/pending/shootout/harmonic.scala-3.scala.runner b/test/pending/shootout/harmonic.scala-3.scala.runner
index b47101a..5cf77d0 100644
--- a/test/pending/shootout/harmonic.scala-3.scala.runner
+++ b/test/pending/shootout/harmonic.scala-3.scala.runner
@@ -1,3 +1,3 @@
 object Test extends Application {
   for(val n <- List(6000000,8000000,10000000)) harmonic.main(Array(n.toString)) 
-}
\ No newline at end of file
+}
diff --git a/test/pending/shootout/heapsort.scala b/test/pending/shootout/heapsort.scala
index a3e7eb4..0097d92 100644
--- a/test/pending/shootout/heapsort.scala
+++ b/test/pending/shootout/heapsort.scala
@@ -69,4 +69,4 @@ object heapsort {
       if (i>0) i; else 1;
    }
 
-}
\ No newline at end of file
+}
diff --git a/test/pending/shootout/heapsort.scala.runner b/test/pending/shootout/heapsort.scala.runner
index 53fdd3c..7030aa3 100644
--- a/test/pending/shootout/heapsort.scala.runner
+++ b/test/pending/shootout/heapsort.scala.runner
@@ -1,3 +1,3 @@
 object Test extends Application {
   for(val n <- List(20000,40000,60000,80000,100000)) heapsort.main(Array(n.toString)) 
-}
\ No newline at end of file
+}
diff --git a/test/pending/shootout/mandelbrot.scala-2.scala b/test/pending/shootout/mandelbrot.scala-2.scala
index 3932010..dffdc35 100644
--- a/test/pending/shootout/mandelbrot.scala-2.scala
+++ b/test/pending/shootout/mandelbrot.scala-2.scala
@@ -3,6 +3,22 @@
    contributed by Isaac Gouy
 */
 
+// This test is in pending because it fails on windows only,
+// but partest's output and the fact that this test outputs in
+// binary makes it a challenge to debug remotely.  However,
+// it's easy to guess that it has to do with the BufferedOutputStream
+// and some kind of windows-specific damage that requires an extra
+// flush, or different line-ending characters, or any of the various
+// write-once-know-quirks-everywhere aspects of java i/o.
+//
+//   [partest] testing: [...]\files\shootout\mandelbrot.scala-2.scala                [FAILED]
+//   [partest] P4
+//   [partest] 200 200
+//   [partest] 
+// ^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^B^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@
+// ^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@
+// [etc]
+
 import java.io.BufferedOutputStream
 
 object mandelbrot { 
diff --git a/test/pending/shootout/mandelbrot.scala-2.scala.runner b/test/pending/shootout/mandelbrot.scala-2.scala.runner
index 78b31e5..9d2d314 100644
--- a/test/pending/shootout/mandelbrot.scala-2.scala.runner
+++ b/test/pending/shootout/mandelbrot.scala-2.scala.runner
@@ -1,3 +1,3 @@
 object Test extends Application {
   for(val n <- List(200,400,600)) mandelbrot.main(Array(n.toString)) 
-}
\ No newline at end of file
+}
diff --git a/test/pending/shootout/message.scala.runner b/test/pending/shootout/message.scala.runner
index c7dead9..32738b0 100644
--- a/test/pending/shootout/message.scala.runner
+++ b/test/pending/shootout/message.scala.runner
@@ -1,3 +1,3 @@
 object Test extends Application {
   for(val n <- List(1000,2000,3000)) message.main(Array(n.toString)) 
-}
\ No newline at end of file
+}
diff --git a/test/pending/shootout/meteor.scala-2.scala.runner b/test/pending/shootout/meteor.scala-2.scala.runner
index 1e6a02e..9f1b95e 100644
--- a/test/pending/shootout/meteor.scala-2.scala.runner
+++ b/test/pending/shootout/meteor.scala-2.scala.runner
@@ -1,3 +1,3 @@
 object Test extends Application {
   for(val n <- List(0)) meteor.main(Array(n.toString)) 
-}
\ No newline at end of file
+}
diff --git a/test/pending/shootout/meteor.scala-3.scala.runner b/test/pending/shootout/meteor.scala-3.scala.runner
index 1e6a02e..9f1b95e 100644
--- a/test/pending/shootout/meteor.scala-3.scala.runner
+++ b/test/pending/shootout/meteor.scala-3.scala.runner
@@ -1,3 +1,3 @@
 object Test extends Application {
   for(val n <- List(0)) meteor.main(Array(n.toString)) 
-}
\ No newline at end of file
+}
diff --git a/test/pending/shootout/meteor.scala-4.scala b/test/pending/shootout/meteor.scala-4.scala
index 4cbe32e..eb7d04e 100644
--- a/test/pending/shootout/meteor.scala-4.scala
+++ b/test/pending/shootout/meteor.scala-4.scala
@@ -123,7 +123,7 @@ final class Solver (n: Int) {
 
 /*
    def printPieces() = 
-      for (val i <- Iterator.range(0,Board.pieces)) pieces(i).print 
+      for (i <- Iterator.range(0,Board.pieces)) pieces(i).print 
 */
 
 }
@@ -164,13 +164,13 @@ final class Board {
 
 
    private val cache: Array[Array[Array[Array[ Array[BoardCell] ]]]] = 
-      for (val i <- Array.range(0,Board.pieces)) 
+      for (i <- Array.range(0,Board.pieces)) 
          yield 
-            for (val j <- Array.range(0,Piece.orientations)) 
+            for (j <- Array.range(0,Piece.orientations)) 
                yield 
-                  for (val k <- Array.range(0,Piece.size)) // piece cell index
+                  for (k <- Array.range(0,Piece.size)) // piece cell index
                      yield 
-                        for (val m <- Array.range(0,Board.size)) // board cell index
+                        for (m <- Array.range(0,Board.size)) // board cell index
                            yield null
 
 
@@ -236,10 +236,10 @@ final class Board {
 
 
    private def boardCells() = {
-      val a = for (val i <- Array.range(0,Board.size)) yield new BoardCell(i)
+      val a = for (i <- Array.range(0,Board.size)) yield new BoardCell(i)
       val m = (Board.size / Board.cols) - 1
 
-      for (val i <- Iterator.range(0,a.length)){
+      for (i <- Iterator.range(0,a.length)){
          val row = i / Board.cols
          val isFirst = i % Board.cols == 0
          val isLast = (i+1) % Board.cols == 0
@@ -275,9 +275,9 @@ final class Board {
 
    def printBoardCellsAndNeighbours() = {
       Console.println("cell\tNW NE W  E  SW SE")
-      for (val i <- Iterator.range(0,Board.size)){
+      for (i <- Iterator.range(0,Board.size)){
          Console.print(i + "\t")
-         for (val j <- Iterator.range(0,Cell.sides)){
+         for (j <- Iterator.range(0,Cell.sides)){
             val c = cells(i).next(j)
             if (c == null) 
                Console.print("-- ") 
@@ -319,7 +319,7 @@ final class Piece(_number: Int) {
    def cells = cache(orientation)
 
    private val cache = 
-      for (val i <- Array.range(0,Piece.orientations)) 
+      for (i <- Array.range(0,Piece.orientations)) 
          yield pieceOrientation(i)
 
    var orientation = 0
@@ -331,15 +331,15 @@ final class Piece(_number: Int) {
 
 
    private def pieceOrientation(k: Int) = {
-      val cells = for (val i <- Array.range(0,Piece.size)) yield new PieceCell()
+      val cells = for (i <- Array.range(0,Piece.size)) yield new PieceCell()
       makePiece(number,cells)
 
       var i = 0
       while (i < k){  
          if (i % Piece.rotations == 0) 
-            for (val c <- cells) c.flip
+            for (c <- cells) c.flip
          else
-            for (val c <- cells) c.rotate
+            for (c <- cells) c.rotate
 
          i = i + 1
       }
@@ -481,14 +481,14 @@ final class Piece(_number: Int) {
    def print() = {
       Console.println("Piece # " + number)
       Console.println("cell\tNW NE W  E  SW SE")
-      for (val i <- Iterator.range(0,Piece.size)){
+      for (i <- Iterator.range(0,Piece.size)){
          Console.print(i + "\t")
-         for (val j <- Iterator.range(0,Cell.sides)){
+         for (j <- Iterator.range(0,Cell.sides)){
             val c = cells(i).next(j)
             if (c == null) 
                Console.print("-- ") 
             else 
-               for (val k <- Iterator.range(0,Piece.size)){
+               for (k <- Iterator.range(0,Piece.size)){
                   if (cells(k) == c) Console.printf(" {0,number,0} ")(k)
                }       
          }
diff --git a/test/pending/shootout/meteor.scala-4.scala.runner b/test/pending/shootout/meteor.scala-4.scala.runner
index 1e6a02e..9f1b95e 100644
--- a/test/pending/shootout/meteor.scala-4.scala.runner
+++ b/test/pending/shootout/meteor.scala-4.scala.runner
@@ -1,3 +1,3 @@
 object Test extends Application {
   for(val n <- List(0)) meteor.main(Array(n.toString)) 
-}
\ No newline at end of file
+}
diff --git a/test/pending/shootout/meteor.scala.runner b/test/pending/shootout/meteor.scala.runner
index 1e6a02e..9f1b95e 100644
--- a/test/pending/shootout/meteor.scala.runner
+++ b/test/pending/shootout/meteor.scala.runner
@@ -1,3 +1,3 @@
 object Test extends Application {
   for(val n <- List(0)) meteor.main(Array(n.toString)) 
-}
\ No newline at end of file
+}
diff --git a/test/pending/shootout/methcall.scala b/test/pending/shootout/methcall.scala
index 7d8164f..2781da0 100644
--- a/test/pending/shootout/methcall.scala
+++ b/test/pending/shootout/methcall.scala
@@ -55,4 +55,4 @@ extends Toggle(b) {
       }
       this
    }
-}
\ No newline at end of file
+}
diff --git a/test/pending/shootout/methcall.scala.runner b/test/pending/shootout/methcall.scala.runner
index 3ddaa2d..1e50ac5 100644
--- a/test/pending/shootout/methcall.scala.runner
+++ b/test/pending/shootout/methcall.scala.runner
@@ -1,3 +1,3 @@
 object Test extends Application {
   for(val n <- List(100000,400000,700000,1000000)) methcall.main(Array(n.toString)) 
-}
\ No newline at end of file
+}
diff --git a/test/pending/shootout/nsieve.scala-4.scala.runner b/test/pending/shootout/nsieve.scala-4.scala.runner
index 7f15911..8c9e80b 100644
--- a/test/pending/shootout/nsieve.scala-4.scala.runner
+++ b/test/pending/shootout/nsieve.scala-4.scala.runner
@@ -1,3 +1,3 @@
 object Test extends Application {
   for(val n <- List(7,8,9)) nsieve.main(Array(n.toString)) 
-}
\ No newline at end of file
+}
diff --git a/test/pending/shootout/pidigits.scala.runner b/test/pending/shootout/pidigits.scala.runner
index fa20bcf..ad83b17 100644
--- a/test/pending/shootout/pidigits.scala.runner
+++ b/test/pending/shootout/pidigits.scala.runner
@@ -1,3 +1,3 @@
 object Test extends Application {
   for(val n <- List(600,800,1000)) pidigits.main(Array(n.toString)) 
-}
\ No newline at end of file
+}
diff --git a/test/pending/shootout/prodcons.scala.runner b/test/pending/shootout/prodcons.scala.runner
index 27754e2..d76c373 100644
--- a/test/pending/shootout/prodcons.scala.runner
+++ b/test/pending/shootout/prodcons.scala.runner
@@ -1,3 +1,3 @@
 object Test extends Application {
   for(val n <- List(30000,70000,100000,150000)) prodcons.main(Array(n.toString)) 
-}
\ No newline at end of file
+}
diff --git a/test/pending/shootout/random.scala.runner b/test/pending/shootout/random.scala.runner
index 924205b..ffe62e5 100644
--- a/test/pending/shootout/random.scala.runner
+++ b/test/pending/shootout/random.scala.runner
@@ -1,3 +1,3 @@
 object Test extends Application {
   for(val n <- List(9000,300000,600000,900000)) random.main(Array(n.toString)) 
-}
\ No newline at end of file
+}
diff --git a/test/pending/shootout/revcomp.scala-2.scala.runner b/test/pending/shootout/revcomp.scala-2.scala.runner
index 16f5b66..0f68f0d 100644
--- a/test/pending/shootout/revcomp.scala-2.scala.runner
+++ b/test/pending/shootout/revcomp.scala-2.scala.runner
@@ -1,6 +1,6 @@
 object Test extends Application {
   for(val n <- List(25000,250000,2500000)) {
-    System.setIn(new java.io.FileInputStream(System.getProperty("scalatest.cwd")+"/revcomp-input"+n+".txt"))
+    System.setIn(new java.io.FileInputStream(System.getProperty("partest.cwd")+"/revcomp-input"+n+".txt"))
     revcomp.main(Array(n.toString)) 
   }
-}
\ No newline at end of file
+}
diff --git a/test/pending/shootout/revcomp.scala-3.scala.runner b/test/pending/shootout/revcomp.scala-3.scala.runner
index 16f5b66..0f68f0d 100644
--- a/test/pending/shootout/revcomp.scala-3.scala.runner
+++ b/test/pending/shootout/revcomp.scala-3.scala.runner
@@ -1,6 +1,6 @@
 object Test extends Application {
   for(val n <- List(25000,250000,2500000)) {
-    System.setIn(new java.io.FileInputStream(System.getProperty("scalatest.cwd")+"/revcomp-input"+n+".txt"))
+    System.setIn(new java.io.FileInputStream(System.getProperty("partest.cwd")+"/revcomp-input"+n+".txt"))
     revcomp.main(Array(n.toString)) 
   }
-}
\ No newline at end of file
+}
diff --git a/test/pending/shootout/sieve.scala.runner b/test/pending/shootout/sieve.scala.runner
index 597a717..1c53d1d 100644
--- a/test/pending/shootout/sieve.scala.runner
+++ b/test/pending/shootout/sieve.scala.runner
@@ -1,3 +1,3 @@
 object Test extends Application {
   for(val n <- List(300,600,900,1200)) sieve.main(Array(n.toString)) 
-}
\ No newline at end of file
+}
diff --git a/test/postreview.py b/test/postreview.py
new file mode 100644
index 0000000..2e2518f
--- /dev/null
+++ b/test/postreview.py
@@ -0,0 +1,2540 @@
+#!/usr/bin/env python
+import cookielib
+import difflib
+import getpass
+import marshal
+import mimetools
+import ntpath
+import os
+import re
+import socket
+import stat
+import subprocess
+import sys
+import tempfile
+import urllib
+import urllib2
+from optparse import OptionParser
+from tempfile import mkstemp
+from urlparse import urljoin, urlparse
+
+try:
+    from hashlib import md5
+except ImportError:
+    # Support Python versions before 2.5.
+    from md5 import md5
+
+try:
+    import json
+except ImportError:
+    import simplejson as json
+
+# This specific import is necessary to handle the paths for
+# cygwin enabled machines.
+if (sys.platform.startswith('win')
+    or sys.platform.startswith('cygwin')):
+    import ntpath as cpath
+else:
+    import posixpath as cpath
+
+###
+# Default configuration -- user-settable variables follow.
+###
+
+# The following settings usually aren't needed, but if your Review
+# Board crew has specific preferences and doesn't want to express
+# them with command line switches, set them here and you're done.
+# In particular, setting the REVIEWBOARD_URL variable will allow
+# you to make it easy for people to submit reviews regardless of
+# their SCM setup.
+#
+# Note that in order for this script to work with a reviewboard site
+# that uses local paths to access a repository, the 'Mirror path'
+# in the repository setup page must be set to the remote URL of the
+# repository.
+
+#
+# Reviewboard URL.
+#
+# Set this if you wish to hard-code a default server to always use.
+# It's generally recommended to set this using your SCM repository
+# (for those that support it -- currently only SVN, Git, and Perforce).
+#
+# For example, on SVN:
+#   $ svn propset reviewboard:url http://reviewboard.example.com .
+#
+# Or with Git:
+#   $ git config reviewboard.url http://reviewboard.example.com
+#
+# On Perforce servers version 2008.1 and above:
+#   $ p4 counter reviewboard.url http://reviewboard.example.com
+#
+# Older Perforce servers only allow numerical counters, so embedding
+# the url in the counter name is also supported:
+#   $ p4 counter reviewboard.url.http:\|\|reviewboard.example.com 1
+#
+# Note that slashes are not allowed in Perforce counter names, so replace them
+# with pipe characters (they are a safe substitute as they are not used
+# unencoded in URLs). You may need to escape them when issuing the p4 counter
+# command as above.
+#
+# If this is not possible or desired, setting the value here will let
+# you get started quickly.
+#
+# For all other repositories, a .reviewboardrc file present at the top of
+# the checkout will also work. For example:
+#
+#   $ cat .reviewboardrc
+#   REVIEWBOARD_URL = "http://reviewboard.example.com"
+#
+REVIEWBOARD_URL = None
+
+# Default submission arguments.  These are all optional; run this
+# script with --help for descriptions of each argument.
+TARGET_GROUPS   = None
+TARGET_PEOPLE   = None
+SUBMIT_AS       = None
+PUBLISH         = False
+OPEN_BROWSER    = False
+
+# Debugging.  For development...
+DEBUG           = False
+
+###
+# End user-settable variables.
+###
+
+
+VERSION = "0.8"
+
+user_config = None
+tempfiles = []
+options = None
+
+
+class APIError(Exception):
+    pass
+
+
+class RepositoryInfo:
+    """
+    A representation of a source code repository.
+    """
+    def __init__(self, path=None, base_path=None, supports_changesets=False,
+                 supports_parent_diffs=False):
+        self.path = path
+        self.base_path = base_path
+        self.supports_changesets = supports_changesets
+        self.supports_parent_diffs = supports_parent_diffs
+        debug("repository info: %s" % self)
+
+    def __str__(self):
+        return "Path: %s, Base path: %s, Supports changesets: %s" % \
+            (self.path, self.base_path, self.supports_changesets)
+
+    def set_base_path(self, base_path):
+        if not base_path.startswith('/'):
+            base_path = '/' + base_path
+        debug("changing repository info base_path from %s to %s" % \
+              (self.base_path, base_path))
+        self.base_path = base_path
+
+    def find_server_repository_info(self, server):
+        """
+        Try to find the repository from the list of repositories on the server.
+        For Subversion, this could be a repository with a different URL. For
+        all other clients, this is a noop.
+        """
+        return self
+
+
+class SvnRepositoryInfo(RepositoryInfo):
+    """
+    A representation of a SVN source code repository. This version knows how to
+    find a matching repository on the server even if the URLs differ.
+    """
+    def __init__(self, path, base_path, uuid, supports_parent_diffs=False):
+        RepositoryInfo.__init__(self, path, base_path,
+                                supports_parent_diffs=supports_parent_diffs)
+        self.uuid = uuid
+
+    def find_server_repository_info(self, server):
+        """
+        The point of this function is to find a repository on the server that
+        matches self, even if the paths aren't the same. (For example, if self
+        uses an 'http' path, but the server uses a 'file' path for the same
+        repository.) It does this by comparing repository UUIDs. If the
+        repositories use the same path, you'll get back self, otherwise you'll
+        get a different SvnRepositoryInfo object (with a different path).
+        """
+        repositories = server.get_repositories()
+
+        for repository in repositories:
+            if repository['tool'] != 'Subversion':
+                continue
+
+            info = self._get_repository_info(server, repository)
+
+            if not info or self.uuid != info['uuid']:
+                continue
+
+            repos_base_path = info['url'][len(info['root_url']):]
+            relpath = self._get_relative_path(self.base_path, repos_base_path)
+            if relpath:
+                return SvnRepositoryInfo(info['url'], relpath, self.uuid)
+
+        # We didn't find a matching repository on the server. We'll just return
+        # self and hope for the best.
+        return self
+
+    def _get_repository_info(self, server, repository):
+        try:
+            return server.get_repository_info(repository['id'])
+        except APIError, e:
+            # If the server couldn't fetch the repository info, it will return
+            # code 210. Ignore those.
+            # Other more serious errors should still be raised, though.
+            rsp = e.args[0]
+            if rsp['err']['code'] == 210:
+                return None
+
+            raise e
+
+    def _get_relative_path(self, path, root):
+        pathdirs = self._split_on_slash(path)
+        rootdirs = self._split_on_slash(root)
+
+        # root is empty, so anything relative to that is itself
+        if len(rootdirs) == 0:
+            return path
+
+        # If one of the directories doesn't match, then path is not relative
+        # to root.
+        if rootdirs != pathdirs:
+            return None
+
+        # All the directories matched, so the relative path is whatever
+        # directories are left over. The base_path can't be empty, though, so
+        # if the paths are the same, return '/'
+        if len(pathdirs) == len(rootdirs):
+            return '/'
+        else:
+            return '/'.join(pathdirs[len(rootdirs):])
+
+    def _split_on_slash(self, path):
+        # Split on slashes, but ignore multiple slashes and throw away any
+        # trailing slashes.
+        split = re.split('/*', path)
+        if split[-1] == '':
+            split = split[0:-1]
+        return split
+
+
+class ReviewBoardHTTPPasswordMgr(urllib2.HTTPPasswordMgr):
+    """
+    Adds HTTP authentication support for URLs.
+
+    Python 2.4's password manager has a bug in http authentication when the
+    target server uses a non-standard port.  This works around that bug on
+    Python 2.4 installs. This also allows post-review to prompt for passwords
+    in a consistent way.
+
+    See: http://bugs.python.org/issue974757
+    """
+    def __init__(self, reviewboard_url):
+        self.passwd  = {}
+        self.rb_url  = reviewboard_url
+        self.rb_user = None
+        self.rb_pass = None
+
+    def find_user_password(self, realm, uri):
+        if uri.startswith(self.rb_url):
+            if self.rb_user is None or self.rb_pass is None:
+                print "==> HTTP Authentication Required"
+                print 'Enter username and password for "%s" at %s' % \
+                    (realm, urlparse(uri)[1])
+                self.rb_user = raw_input('Username: ')
+                self.rb_pass = getpass.getpass('Password: ')
+
+            return self.rb_user, self.rb_pass
+        else:
+            # If this is an auth request for some other domain (since HTTP
+            # handlers are global), fall back to standard password management.
+            return urllib2.HTTPPasswordMgr.find_user_password(self, realm, uri)
+
+
+class ReviewBoardServer(object):
+    """
+    An instance of a Review Board server.
+    """
+    def __init__(self, url, info, cookie_file):
+        self.url = url
+        if self.url[-1] != '/':
+            self.url += '/'
+        self._info = info
+        self._server_info = None
+        self.cookie_file = cookie_file
+        self.cookie_jar  = cookielib.MozillaCookieJar(self.cookie_file)
+
+        # Set up the HTTP libraries to support all of the features we need.
+        cookie_handler = urllib2.HTTPCookieProcessor(self.cookie_jar)
+        password_mgr   = ReviewBoardHTTPPasswordMgr(self.url)
+        auth_handler   = urllib2.HTTPBasicAuthHandler(password_mgr)
+
+        opener = urllib2.build_opener(cookie_handler, auth_handler)
+        opener.addheaders = [('User-agent', 'post-review/' + VERSION)]
+        urllib2.install_opener(opener)
+
+    def login(self, force=False):
+        """
+        Logs in to a Review Board server, prompting the user for login
+        information if needed.
+        """
+        if not force and self.has_valid_cookie():
+            return
+
+        print "==> Review Board Login Required"
+        print "Enter username and password for Review Board at %s" % self.url
+        if options.username:
+            username = options.username
+        elif options.submit_as:
+            username = options.submit_as
+        else:
+            username = raw_input('Username: ')
+
+        if not options.password:
+            password = getpass.getpass('Password: ')
+        else:
+            password = options.password
+
+        debug('Logging in with username "%s"' % username)
+        try:
+            self.api_post('api/json/accounts/login/', {
+                'username': username,
+                'password': password,
+            })
+        except APIError, e:
+            rsp, = e.args
+
+            die("Unable to log in: %s (%s)" % (rsp["err"]["msg"],
+                                               rsp["err"]["code"]))
+
+        debug("Logged in.")
+
+    def has_valid_cookie(self):
+        """
+        Load the user's cookie file and see if they have a valid
+        'rbsessionid' cookie for the current Review Board server.  Returns
+        true if so and false otherwise.
+        """
+        try:
+            parsed_url = urlparse(self.url)
+            host = parsed_url[1]
+            path = parsed_url[2] or '/'
+
+            # Cookie files don't store port numbers, unfortunately, so
+            # get rid of the port number if it's present.
+            host = host.split(":")[0]
+
+            debug("Looking for '%s %s' cookie in %s" % \
+                  (host, path, self.cookie_file))
+            self.cookie_jar.load(self.cookie_file, ignore_expires=True)
+
+            try:
+                cookie = self.cookie_jar._cookies[host][path]['rbsessionid']
+
+                if not cookie.is_expired():
+                    debug("Loaded valid cookie -- no login required")
+                    return True
+
+                debug("Cookie file loaded, but cookie has expired")
+            except KeyError:
+                debug("Cookie file loaded, but no cookie for this server")
+        except IOError, error:
+            debug("Couldn't load cookie file: %s" % error)
+
+        return False
+
+    def new_review_request(self, changenum, submit_as=None):
+        """
+        Creates a review request on a Review Board server, updating an
+        existing one if the changeset number already exists.
+
+        If submit_as is provided, the specified user name will be recorded as
+        the submitter of the review request (given that the logged in user has
+        the appropriate permissions).
+        """
+        try:
+            debug("Attempting to create review request for %s" % changenum)
+            data = { 'repository_path': self.info.path }
+
+            if changenum:
+                data['changenum'] = changenum
+
+            if submit_as:
+                debug("Submitting the review request as %s" % submit_as)
+                data['submit_as'] = submit_as
+
+            rsp = self.api_post('api/json/reviewrequests/new/', data)
+        except APIError, e:
+            rsp, = e.args
+
+            if not options.diff_only:
+                if rsp['err']['code'] == 204: # Change number in use
+                    debug("Review request already exists. Updating it...")
+                    rsp = self.api_post(
+                        'api/json/reviewrequests/%s/update_from_changenum/' %
+                        rsp['review_request']['id'])
+                else:
+                    raise e
+
+        debug("Review request created")
+        return rsp['review_request']
+
+    def set_review_request_field(self, review_request, field, value):
+        """
+        Sets a field in a review request to the specified value.
+        """
+        rid = review_request['id']
+
+        debug("Attempting to set field '%s' to '%s' for review request '%s'" %
+              (field, value, rid))
+
+        self.api_post('api/json/reviewrequests/%s/draft/set/' % rid, {
+            field: value,
+        })
+
+    def get_review_request(self, rid):
+        """
+        Returns the review request with the specified ID.
+        """
+        rsp = self.api_get('api/json/reviewrequests/%s/' % rid)
+        return rsp['review_request']
+
+    def get_repositories(self):
+        """
+        Returns the list of repositories on this server.
+        """
+        rsp = self.api_get('/api/json/repositories/')
+        return rsp['repositories']
+
+    def get_repository_info(self, rid):
+        """
+        Returns detailed information about a specific repository.
+        """
+        rsp = self.api_get('/api/json/repositories/%s/info/' % rid)
+        return rsp['info']
+
+    def save_draft(self, review_request):
+        """
+        Saves a draft of a review request.
+        """
+        self.api_post("api/json/reviewrequests/%s/draft/save/" %
+                      review_request['id'])
+        debug("Review request draft saved")
+
+    def upload_diff(self, review_request, diff_content, parent_diff_content):
+        """
+        Uploads a diff to a Review Board server.
+        """
+        debug("Uploading diff, size: %d" % len(diff_content))
+
+        if parent_diff_content:
+            debug("Uploading parent diff, size: %d" % len(parent_diff_content))
+
+        fields = {}
+        files = {}
+
+        if self.info.base_path:
+            fields['basedir'] = self.info.base_path
+
+        files['path'] = {
+            'filename': 'diff',
+            'content': diff_content
+        }
+
+        if parent_diff_content:
+            files['parent_diff_path'] = {
+                'filename': 'parent_diff',
+                'content': parent_diff_content
+            }
+
+        self.api_post('api/json/reviewrequests/%s/diff/new/' %
+                      review_request['id'], fields, files)
+
+    def publish(self, review_request):
+        """
+        Publishes a review request.
+        """
+        debug("Publishing")
+        self.api_post('api/json/reviewrequests/%s/publish/' %
+                      review_request['id'])
+
+    def _get_server_info(self):
+        if not self._server_info:
+            self._server_info = self._info.find_server_repository_info(self)
+
+        return self._server_info
+
+    info = property(_get_server_info)
+
+    def process_json(self, data):
+        """
+        Loads in a JSON file and returns the data if successful. On failure,
+        APIError is raised.
+        """
+        rsp = json.loads(data)
+
+        if rsp['stat'] == 'fail':
+            raise APIError, rsp
+
+        return rsp
+
+    def http_get(self, path):
+        """
+        Performs an HTTP GET on the specified path, storing any cookies that
+        were set.
+        """
+        debug('HTTP GETting %s' % path)
+
+        url = self._make_url(path)
+
+        try:
+            rsp = urllib2.urlopen(url).read()
+            self.cookie_jar.save(self.cookie_file)
+            return rsp
+        except urllib2.HTTPError, e:
+            print "Unable to access %s (%s). The host path may be invalid" % \
+                (url, e.code)
+            try:
+                debug(e.read())
+            except AttributeError:
+                pass
+            die()
+
+    def _make_url(self, path):
+        """Given a path on the server returns a full http:// style url"""
+        app = urlparse(self.url)[2]
+        if path[0] == '/':
+            url = urljoin(self.url, app[:-1] + path)
+        else:
+            url = urljoin(self.url, app + path)
+
+        if not url.startswith('http'):
+            url = 'http://%s' % url
+        return url
+
+    def api_get(self, path):
+        """
+        Performs an API call using HTTP GET at the specified path.
+        """
+        return self.process_json(self.http_get(path))
+
+    def http_post(self, path, fields, files=None):
+        """
+        Performs an HTTP POST on the specified path, storing any cookies that
+        were set.
+        """
+        if fields:
+            debug_fields = fields.copy()
+        else:
+            debug_fields = {}
+
+        if 'password' in debug_fields:
+            debug_fields["password"] = "**************"
+        url = self._make_url(path)
+        debug('HTTP POSTing to %s: %s' % (url, debug_fields))
+
+        content_type, body = self._encode_multipart_formdata(fields, files)
+        headers = {
+            'Content-Type': content_type,
+            'Content-Length': str(len(body))
+        }
+
+        try:
+            r = urllib2.Request(url, body, headers)
+            data = urllib2.urlopen(r).read()
+            self.cookie_jar.save(self.cookie_file)
+            return data
+        except urllib2.URLError, e:
+            try:
+                debug(e.read())
+            except AttributeError:
+                pass
+
+            die("Unable to access %s. The host path may be invalid\n%s" % \
+                (url, e))
+        except urllib2.HTTPError, e:
+            die("Unable to access %s (%s). The host path may be invalid\n%s" % \
+                (url, e.code, e.read()))
+
+    def api_post(self, path, fields=None, files=None):
+        """
+        Performs an API call using HTTP POST at the specified path.
+        """
+        return self.process_json(self.http_post(path, fields, files))
+
+    def _encode_multipart_formdata(self, fields, files):
+        """
+        Encodes data for use in an HTTP POST.
+        """
+        BOUNDARY = mimetools.choose_boundary()
+        content = ""
+
+        fields = fields or {}
+        files = files or {}
+
+        for key in fields:
+            content += "--" + BOUNDARY + "\r\n"
+            content += "Content-Disposition: form-data; name=\"%s\"\r\n" % key
+            content += "\r\n"
+            content += fields[key] + "\r\n"
+
+        for key in files:
+            filename = files[key]['filename']
+            value = files[key]['content']
+            content += "--" + BOUNDARY + "\r\n"
+            content += "Content-Disposition: form-data; name=\"%s\"; " % key
+            content += "filename=\"%s\"\r\n" % filename
+            content += "\r\n"
+            content += value + "\r\n"
+
+        content += "--" + BOUNDARY + "--\r\n"
+        content += "\r\n"
+
+        content_type = "multipart/form-data; boundary=%s" % BOUNDARY
+
+        return content_type, content
+
+
+class SCMClient(object):
+    """
+    A base representation of an SCM tool for fetching repository information
+    and generating diffs.
+    """
+    def get_repository_info(self):
+        return None
+
+    def scan_for_server(self, repository_info):
+        """
+        Scans the current directory on up to find a .reviewboard file
+        containing the server path.
+        """
+        server_url = self._get_server_from_config(user_config, repository_info)
+        if server_url:
+            return server_url
+
+        for path in walk_parents(os.getcwd()):
+            filename = os.path.join(path, ".reviewboardrc")
+            if os.path.exists(filename):
+                config = load_config_file(filename)
+                server_url = self._get_server_from_config(config,
+                                                          repository_info)
+                if server_url:
+                    return server_url
+
+        return None
+
+    def diff(self, args):
+        """
+        Returns the generated diff and optional parent diff for this
+        repository.
+
+        The returned tuple is (diff_string, parent_diff_string)
+        """
+        return (None, None)
+
+    def diff_between_revisions(self, revision_range, args, repository_info):
+        """
+        Returns the generated diff between revisions in the repository.
+        """
+        return None
+
+    def _get_server_from_config(self, config, repository_info):
+        if 'REVIEWBOARD_URL' in config:
+            return config['REVIEWBOARD_URL']
+        elif 'TREES' in config:
+            trees = config['TREES']
+            if not isinstance(trees, dict):
+                die("Warning: 'TREES' in config file is not a dict!")
+
+            if repository_info.path in trees and \
+               'REVIEWBOARD_URL' in trees[repository_info.path]:
+                return trees[repository_info.path]['REVIEWBOARD_URL']
+
+        return None
+
+
+class CVSClient(SCMClient):
+    """
+    A wrapper around the cvs tool that fetches repository
+    information and generates compatible diffs.
+    """
+    def get_repository_info(self):
+        if not check_install("cvs"):
+            return None
+
+        cvsroot_path = os.path.join("CVS", "Root")
+
+        if not os.path.exists(cvsroot_path):
+            return None
+
+        fp = open(cvsroot_path, "r")
+        repository_path = fp.read().strip()
+        fp.close()
+
+        i = repository_path.find("@")
+        if i != -1:
+            repository_path = repository_path[i + 1:]
+
+        i = repository_path.find(":")
+        if i != -1:
+            host = repository_path[:i]
+            try:
+                canon = socket.getfqdn(host)
+                repository_path = repository_path.replace('%s:' % host,
+                                                          '%s:' % canon)
+            except socket.error, msg:
+                debug("failed to get fqdn for %s, msg=%s" % (host, msg))
+
+        return RepositoryInfo(path=repository_path)
+
+    def diff(self, files):
+        """
+        Performs a diff across all modified files in a CVS repository.
+
+        CVS repositories do not support branches of branches in a way that
+        makes parent diffs possible, so we never return a parent diff
+        (the second value in the tuple).
+        """
+        return (self.do_diff(files), None)
+
+    def diff_between_revisions(self, revision_range, args, repository_info):
+        """
+        Performs a diff between 2 revisions of a CVS repository.
+        """
+        revs = []
+
+        for rev in revision_range.split(":"):
+            revs += ["-r", rev]
+
+        return self.do_diff(revs)
+
+    def do_diff(self, params):
+        """
+        Performs the actual diff operation through cvs diff, handling
+        fake errors generated by CVS.
+        """
+        # Diff returns "1" if differences were found.
+        return execute(["cvs", "diff", "-uN"] + params,
+                        extra_ignore_errors=(1,))
+
+
+class ClearCaseClient(SCMClient):
+    """
+    A wrapper around the clearcase tool that fetches repository
+    information and generates compatible diffs.
+    This client assumes that cygwin is installed on windows.
+    """
+    ccroot_path = "/view/reviewboard.diffview/vobs/"
+    viewinfo = ""
+    viewtype = "snapshot"
+
+    def get_filename_hash(self, fname):
+        # Hash the filename string so its easy to find the file later on.
+        return md5(fname).hexdigest()
+
+    def get_repository_info(self):
+        if not check_install('cleartool help'):
+            return None
+
+        # We must be running this from inside a view.
+        # Otherwise it doesn't make sense.
+        self.viewinfo = execute(["cleartool", "pwv", "-short"])
+        if self.viewinfo.startswith('\*\* NONE'):
+            return None
+
+        # Returning the hardcoded clearcase root path to match the server
+        #   respository path.
+        # There is no reason to have a dynamic path unless you have
+        #   multiple clearcase repositories. This should be implemented.
+        return RepositoryInfo(path=self.ccroot_path,
+                              base_path=self.ccroot_path,
+                              supports_parent_diffs=False)
+
+    def get_previous_version(self, files):
+        file = []
+        curdir = os.getcwd()
+
+        # Cygwin case must transform a linux-like path to windows like path
+        #   including drive letter.
+        if 'cygdrive' in curdir:
+            where = curdir.index('cygdrive') + 9
+            drive_letter = curdir[where:where+1]
+            curdir = drive_letter + ":\\" + curdir[where+2:len(curdir)]
+
+        for key in files:
+            # Sometimes there is a quote in the filename. It must be removed.
+            key = key.replace('\'', '')
+            elem_path = cpath.normpath(os.path.join(curdir, key))
+
+            # Removing anything before the last /vobs
+            #   because it may be repeated.
+            elem_path_idx = elem_path.rfind("/vobs")
+            if elem_path_idx != -1:
+                elem_path = elem_path[elem_path_idx:len(elem_path)].strip("\"")
+
+            # Call cleartool to get this version and the previous version
+            #   of the element.
+            curr_version, pre_version = execute(
+                ["cleartool", "desc", "-pre", elem_path])
+            curr_version = cpath.normpath(curr_version)
+            pre_version = pre_version.split(':')[1].strip()
+
+            # If a specific version was given, remove it from the path
+            #   to avoid version duplication
+            if "@@" in elem_path:
+                elem_path = elem_path[:elem_path.rfind("@@")]
+            file.append(elem_path + "@@" + pre_version)
+            file.append(curr_version)
+
+        # Determnine if the view type is snapshot or dynamic.
+        if os.path.exists(file[0]):
+            self.viewtype = "dynamic"
+
+        return file
+
+    def get_extended_namespace(self, files):
+        """
+        Parses the file path to get the extended namespace
+        """
+        versions = self.get_previous_version(files)
+
+        evfiles = []
+        hlist = []
+
+        for vkey in versions:
+            # Verify if it is a checkedout file.
+            if "CHECKEDOUT" in vkey:
+                # For checkedout files just add it to the file list
+                #   since it cannot be accessed outside the view.
+                splversions = vkey[:vkey.rfind("@@")]
+                evfiles.append(splversions)
+            else:
+                # For checkedin files.
+                ext_path = []
+                ver = []
+                fname = ""      # fname holds the file name without the version.
+                (bpath, fpath) = cpath.splitdrive(vkey)
+                if bpath :
+                    # Windows.
+                    # The version (if specified like file.c@@/main/1)
+                    #   should be kept as a single string
+                    #   so split the path and concat the file name
+                    #   and version in the last position of the list.
+                    ver = fpath.split("@@")
+                    splversions = fpath[:vkey.rfind("@@")].split("\\")
+                    fname = splversions.pop()
+                    splversions.append(fname + ver[1])
+                else :
+                    # Linux.
+                    bpath = vkey[:vkey.rfind("vobs")+4]
+                    fpath = vkey[vkey.rfind("vobs")+5:]
+                    ver = fpath.split("@@")
+                    splversions =  ver[0][:vkey.rfind("@@")].split("/")
+                    fname = splversions.pop()
+                    splversions.append(fname + ver[1])
+
+                filename = splversions.pop()
+                bpath = cpath.normpath(bpath + "/")
+                elem_path = bpath
+
+                for key in splversions:
+                    # For each element (directory) in the path,
+                    #   get its version from clearcase.
+                    elem_path = cpath.join(elem_path, key)
+
+                    # This is the version to be appended to the extended
+                    #   path list.
+                    this_version = execute(
+                        ["cleartool", "desc", "-fmt", "%Vn",
+                        cpath.normpath(elem_path)])
+                    if this_version:
+                        ext_path.append(key + "/@@" + this_version + "/")
+                    else:
+                        ext_path.append(key + "/")
+
+                # This must be done in case we haven't specified
+                #   the version on the command line.
+                ext_path.append(cpath.normpath(fname + "/@@" +
+                    vkey[vkey.rfind("@@")+2:len(vkey)]))
+                epstr = cpath.join(bpath, cpath.normpath(''.join(ext_path)))
+                evfiles.append(epstr)
+
+                """
+                In windows, there is a problem with long names(> 254).
+                In this case, we hash the string and copy the unextended
+                  filename to a temp file whose name is the hash.
+                This way we can get the file later on for diff.
+                The same problem applies to snapshot views where the
+                  extended name isn't available.
+                The previous file must be copied from the CC server
+                  to a local dir.
+                """
+                if cpath.exists(epstr) :
+                    pass
+                else:
+                    if len(epstr) > 254 or self.viewtype == "snapshot":
+                        name = self.get_filename_hash(epstr)
+                        # Check if this hash is already in the list
+                        try:
+                            i = hlist.index(name)
+                            die("ERROR: duplicate value %s : %s" %
+                                (name, epstr))
+                        except ValueError:
+                            hlist.append(name)
+
+                        normkey = cpath.normpath(vkey)
+                        td = tempfile.gettempdir()
+                        # Cygwin case must transform a linux-like path to
+                        # windows like path including drive letter
+                        if 'cygdrive' in td:
+                            where = td.index('cygdrive') + 9
+                            drive_letter = td[where:where+1] + ":"
+                            td = cpath.join(drive_letter, td[where+1:])
+                        tf = cpath.normpath(cpath.join(td, name))
+                        if cpath.exists(tf):
+                            debug("WARNING: FILE EXISTS")
+                            os.unlink(tf)
+                        execute(["cleartool", "get", "-to", tf, normkey])
+                    else:
+                        die("ERROR: FILE NOT FOUND : %s" % epstr)
+
+        return evfiles
+
+    def get_files_from_label(self, label):
+        voblist=[]
+        # Get the list of vobs for the current view
+        allvoblist = execute(["cleartool", "lsvob", "-short"]).split()
+        # For each vob, find if the label is present
+        for vob in allvoblist:
+            try:
+                execute(["cleartool", "describe", "-local",
+                    "lbtype:%s@%s" % (label, vob)]).split()
+                voblist.append(vob)
+            except:
+                pass
+
+        filelist=[]
+        # For each vob containing the label, get the file list
+        for vob in voblist:
+            try:
+                res = execute(["cleartool", "find", vob, "-all", "-version",
+                    "lbtype(%s)" % label, "-print"])
+                filelist.extend(res.split())
+            except :
+                pass
+
+        # Return only the unique itens
+        return set(filelist)
+
+    def diff(self, files):
+        """
+        Performs a diff of the specified file and its previous version.
+        """
+        # We must be running this from inside a view.
+        # Otherwise it doesn't make sense.
+        return self.do_diff(self.get_extended_namespace(files))
+
+    def diff_label(self, label):
+        """
+        Get the files that are attached to a label and diff them
+        TODO
+        """
+        return self.diff(self.get_files_from_label(label))
+
+    def diff_between_revisions(self, revision_range, args, repository_info):
+        """
+        Performs a diff between 2 revisions of a CC repository.
+        """
+        rev_str = ''
+
+        for rev in revision_range.split(":"):
+            rev_str += "-r %s " % rev
+
+        return self.do_diff(rev_str)
+
+    def do_diff(self, params):
+        # Diff returns "1" if differences were found.
+        # Add the view name and view type to the description
+        if options.description:
+            options.description = ("VIEW: " + self.viewinfo +
+                "VIEWTYPE: " + self.viewtype + "\n" + options.description)
+        else:
+            options.description = (self.viewinfo +
+                "VIEWTYPE: " + self.viewtype + "\n")
+
+        o = []
+        Feol = False
+        while len(params) > 0:
+            # Read both original and modified files.
+            onam = params.pop(0)
+            mnam = params.pop(0)
+            file_data = []
+            do_rem = False
+            # If the filename length is greater than 254 char for windows,
+            #   we copied the file to a temp file
+            #   because the open will not work for path greater than 254.
+            # This is valid for the original and
+            #   modified files if the name size is > 254.
+            for filenam in (onam, mnam) :
+                if cpath.exists(filenam) and self.viewtype == "dynamic":
+                    do_rem = False
+                    fn = filenam
+                elif len(filenam) > 254 or self.viewtype == "snapshot":
+                    fn = self.get_filename_hash(filenam)
+                    fn = cpath.join(tempfile.gettempdir(), fn)
+                    do_rem = True
+                fd = open(cpath.normpath(fn))
+                fdata = fd.readlines()
+                fd.close()
+                file_data.append(fdata)
+                # If the file was temp, it should be removed.
+                if do_rem:
+                    os.remove(filenam)
+
+            modi = file_data.pop()
+            orig = file_data.pop()
+
+            # For snapshot views, the local directories must be removed because
+            #   they will break the diff on the server. Just replacing
+            #   everything before the view name (including the view name) for
+            #   vobs do the work.
+            if (self.viewtype == "snapshot"
+                and (sys.platform.startswith('win')
+                  or sys.platform.startswith('cygwin'))):
+                    vinfo = self.viewinfo.rstrip("\r\n")
+                    mnam = "c:\\\\vobs" + mnam[mnam.rfind(vinfo) + len(vinfo):]
+                    onam = "c:\\\\vobs" + onam[onam.rfind(vinfo) + len(vinfo):]
+            # Call the diff lib to generate a diff.
+            # The dates are bogus, since they don't natter anyway.
+            # The only thing is that two spaces are needed to the server
+            #   so it can identify the heades correctly.
+            diff = difflib.unified_diff(orig, modi, onam, mnam,
+               '  2002-02-21 23:30:39.942229878 -0800',
+               '  2002-02-21 23:30:50.442260588 -0800', lineterm=' \n')
+            # Transform the generator output into a string output
+            #   Use a comprehension instead of a generator,
+            #   so 2.3.x doesn't fail to interpret.
+            diffstr = ''.join([str(l) for l in diff])
+            # Workaround for the difflib no new line at end of file
+            #   problem.
+            if not diffstr.endswith('\n'):
+                diffstr = diffstr + ("\n\\ No newline at end of file\n")
+            o.append(diffstr)
+
+        ostr = ''.join(o)
+        return (ostr, None) # diff, parent_diff (not supported)
+
+
+class SVNClient(SCMClient):
+    """
+    A wrapper around the svn Subversion tool that fetches repository
+    information and generates compatible diffs.
+    """
+    def get_repository_info(self):
+        if not check_install('svn help'):
+            return None
+
+        # Get the SVN repository path (either via a working copy or
+        # a supplied URI)
+        svn_info_params = ["svn", "info"]
+        if options.repository_url:
+            svn_info_params.append(options.repository_url)
+        data = execute(svn_info_params,
+                       ignore_errors=True)
+        m = re.search(r'^Repository Root: (.+)$', data, re.M)
+        if not m:
+            return None
+
+        path = m.group(1)
+
+        m = re.search(r'^URL: (.+)$', data, re.M)
+        if not m:
+            return None
+
+        base_path = m.group(1)[len(path):] or "/"
+
+        m = re.search(r'^Repository UUID: (.+)$', data, re.M)
+        if not m:
+            return None
+
+        return SvnRepositoryInfo(path, base_path, m.group(1))
+
+    def scan_for_server(self, repository_info):
+        # Scan first for dot files, since it's faster and will cover the
+        # user's $HOME/.reviewboardrc
+        server_url = super(SVNClient, self).scan_for_server(repository_info)
+        if server_url:
+            return server_url
+
+        return self.scan_for_server_property(repository_info)
+
+    def scan_for_server_property(self, repository_info):
+        def get_url_prop(path):
+            url = execute(["svn", "propget", "reviewboard:url", path]).strip()
+            return url or None
+
+        for path in walk_parents(os.getcwd()):
+            if not os.path.exists(os.path.join(path, ".svn")):
+                break
+
+            prop = get_url_prop(path)
+            if prop:
+                return prop
+
+        return get_url_prop(repository_info.path)
+
+    def diff(self, files):
+        """
+        Performs a diff across all modified files in a Subversion repository.
+
+        SVN repositories do not support branches of branches in a way that
+        makes parent diffs possible, so we never return a parent diff
+        (the second value in the tuple).
+        """
+        return (self.do_diff(["svn", "diff", "--diff-cmd=diff"] + files),
+                None)
+
+    def diff_between_revisions(self, revision_range, args, repository_info):
+        """
+        Performs a diff between 2 revisions of a Subversion repository.
+        """
+        if options.repository_url:
+            revisions = revision_range.split(':')
+            if len(revisions) < 1:
+                return None
+            elif len(revisions) == 1:
+                revisions.append('HEAD')
+
+            # if a new path was supplied at the command line, set it
+            if len(args):
+                repository_info.set_base_path(args[0])
+
+            url = repository_info.path + repository_info.base_path
+
+            old_url = url + '@' + revisions[0]
+            new_url = url + '@' + revisions[1]
+
+            return self.do_diff(["svn", "diff", "--diff-cmd=diff", old_url,
+                                 new_url],
+                                repository_info)
+        # Otherwise, perform the revision range diff using a working copy
+        else:
+            return self.do_diff(["svn", "diff", "--diff-cmd=diff", "-r",
+                                 revision_range],
+                                repository_info)
+
+    def do_diff(self, cmd, repository_info=None):
+        """
+        Performs the actual diff operation, handling renames and converting
+        paths to absolute.
+        """
+        diff = execute(cmd, split_lines=True)
+        diff = self.handle_renames(diff)
+        diff = self.convert_to_absolute_paths(diff, repository_info)
+
+        return ''.join(diff)
+
+    def handle_renames(self, diff_content):
+        """
+        The output of svn diff is incorrect when the file in question came
+        into being via svn mv/cp. Although the patch for these files are
+        relative to its parent, the diff header doesn't reflect this.
+        This function fixes the relevant section headers of the patch to
+        portray this relationship.
+        """
+
+        # svn diff against a repository URL on two revisions appears to
+        # handle moved files properly, so only adjust the diff file names
+        # if they were created using a working copy.
+        if options.repository_url:
+            return diff_content
+
+        result = []
+
+        from_line = ""
+        for line in diff_content:
+            if line.startswith('--- '):
+                from_line = line
+                continue
+
+            # This is where we decide how mangle the previous '--- '
+            if line.startswith('+++ '):
+                to_file, _ = self.parse_filename_header(line[4:])
+                info       = self.svn_info(to_file)
+                if info.has_key("Copied From URL"):
+                    url       = info["Copied From URL"]
+                    root      = info["Repository Root"]
+                    from_file = urllib.unquote(url[len(root):])
+                    result.append(from_line.replace(to_file, from_file))
+                else:
+                    result.append(from_line) #as is, no copy performed
+
+            # We only mangle '---' lines. All others get added straight to
+            # the output.
+            result.append(line)
+
+        return result
+
+
+    def convert_to_absolute_paths(self, diff_content, repository_info):
+        """
+        Converts relative paths in a diff output to absolute paths.
+        This handles paths that have been svn switched to other parts of the
+        repository.
+        """
+
+        result = []
+
+        for line in diff_content:
+            front = None
+            if line.startswith('+++ ') or line.startswith('--- ') or line.startswith('Index: '):
+                front, line = line.split(" ", 1)
+
+            if front:
+                if line.startswith('/'): #already absolute
+                    line = front + " " + line
+                else:
+                    # filename and rest of line (usually the revision
+                    # component)
+                    file, rest = self.parse_filename_header(line)
+
+                    # If working with a diff generated outside of a working
+                    # copy, then file paths are already absolute, so just
+                    # add initial slash.
+                    if options.repository_url:
+                        path = urllib.unquote(
+                            "%s/%s" % (repository_info.base_path, file))
+                    else:
+                        info = self.svn_info(file)
+                        url  = info["URL"]
+                        root = info["Repository Root"]
+                        path = urllib.unquote(url[len(root):])
+
+                    line = front + " " + path + rest
+
+            result.append(line)
+
+        return result
+
+    def svn_info(self, path):
+        """Return a dict which is the result of 'svn info' at a given path."""
+        svninfo = {}
+        for info in execute(["svn", "info", path],
+                            split_lines=True):
+            parts = info.strip().split(": ", 1)
+            if len(parts) == 2:
+                key, value = parts
+                svninfo[key] = value
+
+        return svninfo
+
+    # Adapted from server code parser.py
+    def parse_filename_header(self, s):
+        parts = None
+        if "\t" in s:
+            # There's a \t separating the filename and info. This is the
+            # best case scenario, since it allows for filenames with spaces
+            # without much work.
+            parts = s.split("\t")
+
+        # There's spaces being used to separate the filename and info.
+        # This is technically wrong, so all we can do is assume that
+        # 1) the filename won't have multiple consecutive spaces, and
+        # 2) there's at least 2 spaces separating the filename and info.
+        if "  " in s:
+            parts = re.split(r"  +", s)
+
+        if parts:
+            parts[1] = '\t' + parts[1]
+            return parts
+
+        # strip off ending newline, and return it as the second component
+        return [s.split('\n')[0], '\n']
+
+
+class PerforceClient(SCMClient):
+    """
+    A wrapper around the p4 Perforce tool that fetches repository information
+    and generates compatible diffs.
+    """
+    def get_repository_info(self):
+        if not check_install('p4 help'):
+            return None
+
+        data = execute(["p4", "info"], ignore_errors=True)
+
+        m = re.search(r'^Server address: (.+)$', data, re.M)
+        if not m:
+            return None
+
+        repository_path = m.group(1).strip()
+
+        try:
+            hostname, port = repository_path.split(":")
+            info = socket.gethostbyaddr(hostname)
+            repository_path = "%s:%s" % (info[0], port)
+        except (socket.gaierror, socket.herror):
+            pass
+
+        return RepositoryInfo(path=repository_path, supports_changesets=True)
+
+    def scan_for_server(self, repository_info):
+        # Scan first for dot files, since it's faster and will cover the
+        # user's $HOME/.reviewboardrc
+        server_url = \
+            super(PerforceClient, self).scan_for_server(repository_info)
+
+        if server_url:
+            return server_url
+
+        return self.scan_for_server_counter(repository_info)
+
+    def scan_for_server_counter(self, repository_info):
+        """
+        Checks the Perforce counters to see if the Review Board server's url
+        is specified. Since Perforce only started supporting non-numeric
+        counter values in server version 2008.1, we support both a normal
+        counter 'reviewboard.url' with a string value and embedding the url in
+        a counter name like 'reviewboard.url.http:||reviewboard.example.com'.
+        Note that forward slashes aren't allowed in counter names, so
+        pipe ('|') characters should be used. These should be safe because they
+        should not be used unencoded in urls.
+        """
+
+        counters_text = execute(["p4", "counters"])
+
+        # Try for a "reviewboard.url" counter first.
+        m = re.search(r'^reviewboard.url = (\S+)', counters_text, re.M)
+
+        if m:
+            return m.group(1)
+
+        # Next try for a counter of the form:
+        # reviewboard_url.http:||reviewboard.example.com
+        m2 = re.search(r'^reviewboard.url\.(\S+)', counters_text, re.M)
+
+        if m2:
+            return m2.group(1).replace('|', '/')
+
+        return None
+
+    def get_changenum(self, args):
+        if len(args) == 1:
+            try:
+                return str(int(args[0]))
+            except ValueError:
+                pass
+        return None
+
+    def diff(self, args):
+        """
+        Goes through the hard work of generating a diff on Perforce in order
+        to take into account adds/deletes and to provide the necessary
+        revision information.
+        """
+        # set the P4 enviroment:
+        if options.p4_client:
+           os.environ['P4CLIENT'] = options.p4_client
+
+        if options.p4_port:
+           os.environ['P4PORT'] = options.p4_port
+
+        changenum = self.get_changenum(args)
+        if changenum is None:
+            return self._path_diff(args)
+        else:
+            return self._changenum_diff(changenum)
+
+
+    def _path_diff(self, args):
+        """
+        Process a path-style diff.  See _changenum_diff for the alternate
+        version that handles specific change numbers.
+
+        Multiple paths may be specified in `args`.  The path styles supported
+        are:
+
+        //path/to/file
+        Upload file as a "new" file.
+
+        //path/to/dir/...
+        Upload all files as "new" files.
+
+        //path/to/file[@#]rev
+        Upload file from that rev as a "new" file.
+
+        //path/to/file[@#]rev,[@#]rev
+        Upload a diff between revs.
+
+        //path/to/dir/...[@#]rev,[@#]rev
+        Upload a diff of all files between revs in that directory.
+        """
+        r_revision_range = re.compile(r'^(?P<path>//[^@#]+)' +
+                                      r'(?P<revision1>[#@][^,]+)?' +
+                                      r'(?P<revision2>,[#@][^,]+)?$')
+
+        empty_filename = make_tempfile()
+        tmp_diff_from_filename = make_tempfile()
+        tmp_diff_to_filename = make_tempfile()
+
+        diff_lines = []
+
+        for path in args:
+            m = r_revision_range.match(path)
+
+            if not m:
+                die('Path %r does not match a valid Perforce path.' % (path,))
+            revision1 = m.group('revision1')
+            revision2 = m.group('revision2')
+            first_rev_path = m.group('path')
+
+            if revision1:
+                first_rev_path += revision1
+            records = self._run_p4(['files', first_rev_path])
+
+            # Make a map for convenience.
+            files = {}
+
+            # Records are:
+            # 'rev': '1'
+            # 'func': '...'
+            # 'time': '1214418871'
+            # 'action': 'edit'
+            # 'type': 'ktext'
+            # 'depotFile': '...'
+            # 'change': '123456'
+            for record in records:
+                if record['action'] != 'delete':
+                    if revision2:
+                        files[record['depotFile']] = [record, None]
+                    else:
+                        files[record['depotFile']] = [None, record]
+
+            if revision2:
+                # [1:] to skip the comma.
+                second_rev_path = m.group('path') + revision2[1:]
+                records = self._run_p4(['files', second_rev_path])
+                for record in records:
+                    if record['action'] != 'delete':
+                        try:
+                            m = files[record['depotFile']]
+                            m[1] = record
+                        except KeyError:
+                            files[record['depotFile']] = [None, record]
+
+            old_file = new_file = empty_filename
+            changetype_short = None
+
+            for depot_path, (first_record, second_record) in files.items():
+                old_file = new_file = empty_filename
+                if first_record is None:
+                    self._write_file(depot_path + '#' + second_record['rev'],
+                                     tmp_diff_to_filename)
+                    new_file = tmp_diff_to_filename
+                    changetype_short = 'A'
+                    base_revision = 0
+                elif second_record is None:
+                    self._write_file(depot_path + '#' + first_record['rev'],
+                                     tmp_diff_from_filename)
+                    old_file = tmp_diff_from_filename
+                    changetype_short = 'D'
+                    base_revision = int(first_record['rev'])
+                else:
+                    self._write_file(depot_path + '#' + first_record['rev'],
+                                     tmp_diff_from_filename)
+                    self._write_file(depot_path + '#' + second_record['rev'],
+                                     tmp_diff_to_filename)
+                    new_file = tmp_diff_to_filename
+                    old_file = tmp_diff_from_filename
+                    changetype_short = 'M'
+                    base_revision = int(first_record['rev'])
+
+                dl = self._do_diff(old_file, new_file, depot_path,
+                                   base_revision, changetype_short,
+                                   ignore_unmodified=True)
+                diff_lines += dl
+
+        os.unlink(empty_filename)
+        os.unlink(tmp_diff_from_filename)
+        os.unlink(tmp_diff_to_filename)
+        return (''.join(diff_lines), None)
+
+    def _run_p4(self, command):
+        """Execute a perforce command using the python marshal API.
+
+        - command: A list of strings of the command to execute.
+
+        The return type depends on the command being run.
+        """
+        command = ['p4', '-G'] + command
+        p = subprocess.Popen(command, stdout=subprocess.PIPE)
+        result = []
+        has_error = False
+
+        while 1:
+            try:
+                data = marshal.load(p.stdout)
+            except EOFError:
+                break
+            else:
+                result.append(data)
+                if data.get('code', None) == 'error':
+                    has_error = True
+
+        rc = p.wait()
+
+        if rc or has_error:
+            for record in result:
+                if 'data' in record:
+                    print record['data']
+            die('Failed to execute command: %s\n' % (command,))
+
+        return result
+
+    def _changenum_diff(self, changenum):
+        """
+        Process a diff for a particular change number.  This handles both
+        pending and submitted changelists.
+
+        See _path_diff for the alternate version that does diffs of depot
+        paths.
+        """
+        # TODO: It might be a good idea to enhance PerforceDiffParser to
+        # understand that newFile could include a revision tag for post-submit
+        # reviewing.
+        cl_is_pending = False
+
+        debug("Generating diff for changenum %s" % changenum)
+
+        description = execute(["p4", "describe", "-s", changenum],
+                              split_lines=True)
+
+        if '*pending*' in description[0]:
+            cl_is_pending = True
+
+        # Get the file list
+        for line_num, line in enumerate(description):
+            if 'Affected files ...' in line:
+                break
+        else:
+            # Got to the end of all the description lines and didn't find
+            # what we were looking for.
+            die("Couldn't find any affected files for this change.")
+
+        description = description[line_num+2:]
+
+        diff_lines = []
+
+        empty_filename = make_tempfile()
+        tmp_diff_from_filename = make_tempfile()
+        tmp_diff_to_filename = make_tempfile()
+
+        for line in description:
+            line = line.strip()
+            if not line:
+                continue
+
+            m = re.search(r'\.\.\. ([^#]+)#(\d+) (add|edit|delete|integrate|branch)', line)
+            if not m:
+                die("Unsupported line from p4 opened: %s" % line)
+
+            depot_path = m.group(1)
+            base_revision = int(m.group(2))
+            if not cl_is_pending:
+                # If the changelist is pending our base revision is the one that's
+                # currently in the depot. If we're not pending the base revision is
+                # actually the revision prior to this one
+                base_revision -= 1
+
+            changetype = m.group(3)
+
+            debug('Processing %s of %s' % (changetype, depot_path))
+
+            old_file = new_file = empty_filename
+            old_depot_path = new_depot_path = None
+            changetype_short = None
+
+            if changetype == 'edit' or changetype == 'integrate':
+                # A big assumption
+                new_revision = base_revision + 1
+
+                # We have an old file, get p4 to take this old version from the
+                # depot and put it into a plain old temp file for us
+                old_depot_path = "%s#%s" % (depot_path, base_revision)
+                self._write_file(old_depot_path, tmp_diff_from_filename)
+                old_file = tmp_diff_from_filename
+
+                # Also print out the new file into a tmpfile
+                if cl_is_pending:
+                    new_file = self._depot_to_local(depot_path)
+                else:
+                    new_depot_path = "%s#%s" %(depot_path, new_revision)
+                    self._write_file(new_depot_path, tmp_diff_to_filename)
+                    new_file = tmp_diff_to_filename
+
+                changetype_short = "M"
+
+            elif changetype == 'add' or changetype == 'branch':
+                # We have a new file, get p4 to put this new file into a pretty
+                # temp file for us. No old file to worry about here.
+                if cl_is_pending:
+                    new_file = self._depot_to_local(depot_path)
+                else:
+                    self._write_file(depot_path, tmp_diff_to_filename)
+                    new_file = tmp_diff_to_filename
+                changetype_short = "A"
+
+            elif changetype == 'delete':
+                # We've deleted a file, get p4 to put the deleted file into  a temp
+                # file for us. The new file remains the empty file.
+                old_depot_path = "%s#%s" % (depot_path, base_revision)
+                self._write_file(old_depot_path, tmp_diff_from_filename)
+                old_file = tmp_diff_from_filename
+                changetype_short = "D"
+            else:
+                die("Unknown change type '%s' for %s" % (changetype, depot_path))
+
+            dl = self._do_diff(old_file, new_file, depot_path, base_revision, changetype_short)
+            diff_lines += dl
+
+        os.unlink(empty_filename)
+        os.unlink(tmp_diff_from_filename)
+        os.unlink(tmp_diff_to_filename)
+        return (''.join(diff_lines), None)
+
+    def _do_diff(self, old_file, new_file, depot_path, base_revision,
+                 changetype_short, ignore_unmodified=False):
+        """
+        Do the work of producing a diff for Perforce.
+
+        old_file - The absolute path to the "old" file.
+        new_file - The absolute path to the "new" file.
+        depot_path - The depot path in Perforce for this file.
+        base_revision - The base perforce revision number of the old file as
+            an integer.
+        changetype_short - The change type as a single character string.
+        ignore_unmodified - If True, will return an empty list if the file
+            is not changed.
+
+        Returns a list of strings of diff lines.
+        """
+        if hasattr(os, 'uname') and os.uname()[0] == 'SunOS':
+            diff_cmd = ["gdiff", "-urNp", old_file, new_file]
+        else:
+            diff_cmd = ["diff", "-urNp", old_file, new_file]
+        # Diff returns "1" if differences were found.
+        dl = execute(diff_cmd, extra_ignore_errors=(1,2),
+                     translate_newlines=False)
+
+        # If the input file has ^M characters at end of line, lets ignore them.
+        dl = dl.replace('\r\r\n', '\r\n')
+        dl = dl.splitlines(True)
+
+        cwd = os.getcwd()
+        if depot_path.startswith(cwd):
+            local_path = depot_path[len(cwd) + 1:]
+        else:
+            local_path = depot_path
+
+        # Special handling for the output of the diff tool on binary files:
+        #     diff outputs "Files a and b differ"
+        # and the code below expects the output to start with
+        #     "Binary files "
+        if len(dl) == 1 and \
+           dl[0] == ('Files %s and %s differ'% (old_file, new_file)):
+            dl = ['Binary files %s and %s differ'% (old_file, new_file)]
+
+        if dl == [] or dl[0].startswith("Binary files "):
+            if dl == []:
+                if ignore_unmodified:
+                    return []
+                else:
+                    print "Warning: %s in your changeset is unmodified" % \
+                        local_path
+
+            dl.insert(0, "==== %s#%s ==%s== %s ====\n" % \
+                (depot_path, base_revision, changetype_short, local_path))
+            dl.append('\n')
+        else:
+            m = re.search(r'(\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d)', dl[1])
+            if m:
+                timestamp = m.group(1)
+            else:
+                # Thu Sep  3 11:24:48 2007
+                m = re.search(r'(\w+)\s+(\w+)\s+(\d+)\s+(\d\d:\d\d:\d\d)\s+(\d\d\d\d)', dl[1])
+                if not m:
+                    die("Unable to parse diff header: %s" % dl[1])
+
+                month_map = {
+                    "Jan": "01",
+                    "Feb": "02",
+                    "Mar": "03",
+                    "Apr": "04",
+                    "May": "05",
+                    "Jun": "06",
+                    "Jul": "07",
+                    "Aug": "08",
+                    "Sep": "09",
+                    "Oct": "10",
+                    "Nov": "11",
+                    "Dec": "12",
+                }
+                month = month_map[m.group(2)]
+                day = m.group(3)
+                timestamp = m.group(4)
+                year = m.group(5)
+
+                timestamp = "%s-%s-%s %s" % (year, month, day, timestamp)
+
+            dl[0] = "--- %s\t%s#%s\n" % (local_path, depot_path, base_revision)
+            dl[1] = "+++ %s\t%s\n" % (local_path, timestamp)
+
+        return dl
+
+    def _write_file(self, depot_path, tmpfile):
+        """
+        Grabs a file from Perforce and writes it to a temp file. p4 print sets
+        the file readonly and that causes a later call to unlink fail. So we
+        make the file read/write.
+        """
+        debug('Writing "%s" to "%s"' % (depot_path, tmpfile))
+        execute(["p4", "print", "-o", tmpfile, "-q", depot_path])
+        os.chmod(tmpfile, stat.S_IREAD | stat.S_IWRITE)
+
+    def _depot_to_local(self, depot_path):
+        """
+        Given a path in the depot return the path on the local filesystem to
+        the same file.  If there are multiple results, take only the last
+        result from the where command.
+        """
+        where_output = self._run_p4(['where', depot_path])
+        return where_output[-1]['path']
+
+
+class MercurialClient(SCMClient):
+    """
+    A wrapper around the hg Mercurial tool that fetches repository
+    information and generates compatible diffs.
+    """
+    def get_repository_info(self):
+        if not check_install('hg --help'):
+            return None
+
+        data = execute(["hg", "root"], ignore_errors=True)
+        if data.startswith('abort:'):
+            # hg aborted => no mercurial repository here.
+            return None
+
+        # Elsewhere, hg root output give us the repository path.
+
+        # We save data here to use it as a fallback. See below
+        local_data = data.strip()
+
+        svn = execute(["hg", "svn", "info", ], ignore_errors=True)
+
+        if (not svn.startswith('abort:') and
+            not svn.startswith("hg: unknown command")):
+            self.type = 'svn'
+            m = re.search(r'^Repository Root: (.+)$', svn, re.M)
+
+            if not m:
+                return None
+
+            path = m.group(1)
+            m2 = re.match(r'^(svn\+ssh|http|https)://([-a-zA-Z0-9.]*@)(.*)$',
+                          path)
+            if m2:
+                path = '%s://%s' % (m2.group(1), m2.group(3))
+
+            m = re.search(r'^URL: (.+)$', svn, re.M)
+
+            if not m:
+                return None
+
+            base_path = m.group(1)[len(path):] or "/"
+            return RepositoryInfo(path=path,
+                                  base_path=base_path,
+                                  supports_parent_diffs=True)
+
+        self.type = 'hg'
+
+        # We are going to search .hg/hgrc for the default path.
+        file_name = os.path.join(local_data,'.hg', 'hgrc')
+
+        if not os.path.exists(file_name):
+            return RepositoryInfo(path=local_data, base_path='/',
+                                  supports_parent_diffs=True)
+
+        f = open(file_name)
+        data = f.read()
+        f.close()
+
+        m = re.search(r'^default\s+=\s+(.+)$', data, re.M)
+
+        if not m:
+            # Return the local path, if no default value is found.
+            return RepositoryInfo(path=local_data, base_path='/',
+                                  supports_parent_diffs=True)
+
+        path = m.group(1).strip()
+
+        return RepositoryInfo(path=path, base_path='',
+                              supports_parent_diffs=True)
+
+    def diff(self, files):
+        """
+        Performs a diff across all modified files in a Mercurial repository.
+        """
+        # We don't support parent diffs with Mercurial yet, so we always
+        # return None for the parent diff.
+        if self.type == 'svn':
+            parent = execute(['hg', 'parent', '--svn', '--template',
+                              '{node}\n']).strip()
+
+            if options.parent_branch:
+                parent = options.parent_branch
+
+            if options.guess_summary and not options.summary:
+                options.summary = execute(['hg', 'log', '-r.', '--template',
+                                            r'{desc|firstline}\n'])
+
+            if options.guess_description and not options.description:
+                numrevs = len(execute(['hg', 'log', '-r.:%s' % parent,
+                                       '--follow', '--template',
+                                       r'{rev}\n']).strip().split('\n'))
+                options.description = execute(['hg', 'log', '-r.:%s' % parent,
+                                               '--follow', '--template',
+                                               r'{desc}\n\n', '--limit',
+                                               str(numrevs-1)]).strip()
+
+            return (execute(["hg", "diff", "--svn", '-r%s:.' % parent]), None)
+
+        return (execute(["hg", "diff"] + files), None)
+
+    def diff_between_revisions(self, revision_range, args, repository_info):
+        """
+        Performs a diff between 2 revisions of a Mercurial repository.
+        """
+        if self.type != 'hg':
+            raise NotImplementedError
+
+        r1, r2 = revision_range.split(':')
+        return execute(["hg", "diff", "-r", r1, "-r", r2])
+
+
+class GitClient(SCMClient):
+    """
+    A wrapper around git that fetches repository information and generates
+    compatible diffs. This will attempt to generate a diff suitable for the
+    remote repository, whether git, SVN or Perforce.
+    """
+    def get_repository_info(self):
+        if not check_install('git --help'):
+            return None
+
+        git_dir = execute(["git", "rev-parse", "--git-dir"],
+                          ignore_errors=True).strip()
+
+        if git_dir.startswith("fatal:") or not os.path.isdir(git_dir):
+            return None
+
+        # post-review in directories other than the top level of
+        # of a work-tree would result in broken diffs on the server
+        os.chdir(os.path.dirname(os.path.abspath(git_dir)))
+
+        # We know we have something we can work with. Let's find out
+        # what it is. We'll try SVN first.
+        data = execute(["git", "svn", "info"], ignore_errors=True)
+
+        m = re.search(r'^Repository Root: (.+)$', data, re.M)
+        if m:
+            path = m.group(1)
+            m = re.search(r'^URL: (.+)$', data, re.M)
+
+            if m:
+                base_path = m.group(1)[len(path):] or "/"
+                m = re.search(r'^Repository UUID: (.+)$', data, re.M)
+
+                if m:
+                    uuid = m.group(1)
+                    self.type = "svn"
+
+                    return SvnRepositoryInfo(path=path, base_path=base_path,
+                                             uuid=uuid,
+                                             supports_parent_diffs=True)
+        else:
+            # Versions of git-svn before 1.5.4 don't (appear to) support
+            # 'git svn info'.  If we fail because of an older git install,
+            # here, figure out what version of git is installed and give
+            # the user a hint about what to do next.
+            version = execute(["git", "svn", "--version"], ignore_errors=True)
+            version_parts = re.search('version (\d+)\.(\d+)\.(\d+)',
+                                      version)
+            svn_remote = execute(["git", "config", "--get",
+                                  "svn-remote.svn.url"], ignore_errors=True)
+
+            if (version_parts and
+                not self.is_valid_version((int(version_parts.group(1)),
+                                           int(version_parts.group(2)),
+                                           int(version_parts.group(3))),
+                                          (1, 5, 4)) and
+                svn_remote):
+                die("Your installation of git-svn must be upgraded to " + \
+                    "version 1.5.4 or later")
+
+        # Okay, maybe Perforce.
+        # TODO
+
+        # Nope, it's git then.
+        origin = execute(["git", "remote", "show", "origin"])
+        m = re.search(r'URL: (.+)', origin)
+        if m:
+            url = m.group(1).rstrip('/')
+            if url:
+                self.type = "git"
+                return RepositoryInfo(path=url, base_path='',
+                                      supports_parent_diffs=True)
+
+        return None
+
+    def is_valid_version(self, actual, expected):
+        """
+        Takes two tuples, both in the form:
+            (major_version, minor_version, micro_version)
+        Returns true if the actual version is greater than or equal to
+        the expected version, and false otherwise.
+        """
+        return (actual[0] > expected[0]) or \
+               (actual[0] == expected[0] and actual[1] > expected[1]) or \
+               (actual[0] == expected[0] and actual[1] == expected[1] and \
+                actual[2] >= expected[2])
+
+    def scan_for_server(self, repository_info):
+        # Scan first for dot files, since it's faster and will cover the
+        # user's $HOME/.reviewboardrc
+        server_url = super(GitClient, self).scan_for_server(repository_info)
+
+        if server_url:
+            return server_url
+
+        # TODO: Maybe support a server per remote later? Is that useful?
+        url = execute(["git", "config", "--get", "reviewboard.url"],
+                      ignore_errors=True).strip()
+        if url:
+            return url
+
+        if self.type == "svn":
+            # Try using the reviewboard:url property on the SVN repo, if it
+            # exists.
+            prop = SVNClient().scan_for_server_property(repository_info)
+
+            if prop:
+                return prop
+
+        return None
+
+    def diff(self, args):
+        """
+        Performs a diff across all modified files in the branch, taking into
+        account a parent branch.
+        """
+        parent_branch = options.parent_branch or "master"
+
+        diff_lines = self.make_diff(parent_branch)
+
+        if parent_branch != "master":
+            parent_diff_lines = self.make_diff("master", parent_branch)
+        else:
+            parent_diff_lines = None
+
+        if options.guess_summary and not options.summary:
+            options.summary = execute(["git", "log", "--pretty=format:%s",
+                                       "HEAD^.."], ignore_errors=True).strip()
+
+        if options.guess_description and not options.description:
+            options.description = execute(
+                ["git", "log", "--pretty=format:%s%n%n%b", parent_branch + ".."],
+                ignore_errors=True).strip()
+
+        return (diff_lines, parent_diff_lines)
+
+    def make_diff(self, parent_branch, source_branch=""):
+        """
+        Performs a diff on a particular branch range.
+        """
+        if self.type == "svn":
+            diff_lines = execute(["git", "diff", "--no-color", "--no-prefix",
+                                  "-r", "-u", "%s..%s" % (parent_branch,
+                                                          source_branch)],
+                                 split_lines=True)
+            return self.make_svn_diff(parent_branch, diff_lines)
+        elif self.type == "git":
+            return execute(["git", "diff", "--no-color", "--full-index",
+                            parent_branch])
+
+        return None
+
+    def make_svn_diff(self, parent_branch, diff_lines):
+        """
+        Formats the output of git diff such that it's in a form that
+        svn diff would generate. This is needed so the SVNTool in Review
+        Board can properly parse this diff.
+        """
+        rev = execute(["git", "svn", "find-rev", "master"]).strip()
+
+        if not rev:
+            return None
+
+        diff_data = ""
+        filename = ""
+        revision = ""
+        newfile = False
+
+        for line in diff_lines:
+            if line.startswith("diff "):
+                # Grab the filename and then filter this out.
+                # This will be in the format of:
+                #
+                # diff --git a/path/to/file b/path/to/file
+                info = line.split(" ")
+                diff_data += "Index: %s\n" % info[2]
+                diff_data += "=" * 67
+                diff_data += "\n"
+            elif line.startswith("index "):
+                # Filter this out.
+                pass
+            elif line.strip() == "--- /dev/null":
+                # New file
+                newfile = True
+            elif line.startswith("--- "):
+                newfile = False
+                diff_data += "--- %s\t(revision %s)\n" % \
+                             (line[4:].strip(), rev)
+            elif line.startswith("+++ "):
+                filename = line[4:].strip()
+                if newfile:
+                    diff_data += "--- %s\t(revision 0)\n" % filename
+                    diff_data += "+++ %s\t(revision 0)\n" % filename
+                else:
+                    # We already printed the "--- " line.
+                    diff_data += "+++ %s\t(working copy)\n" % filename
+            else:
+                diff_data += line
+
+        return diff_data
+
+    def diff_between_revisions(self, revision_range, args, repository_info):
+        pass
+
+
+SCMCLIENTS = (
+    SVNClient(),
+    CVSClient(),
+    GitClient(),
+    MercurialClient(),
+    PerforceClient(),
+    ClearCaseClient(),
+)
+
+def debug(s):
+    """
+    Prints debugging information if post-review was run with --debug
+    """
+    if DEBUG or options and options.debug:
+        print ">>> %s" % s
+
+
+def make_tempfile():
+    """
+    Creates a temporary file and returns the path. The path is stored
+    in an array for later cleanup.
+    """
+    fd, tmpfile = mkstemp()
+    os.close(fd)
+    tempfiles.append(tmpfile)
+    return tmpfile
+
+
+def check_install(command):
+    """
+    Try executing an external command and return a boolean indicating whether
+    that command is installed or not.  The 'command' argument should be
+    something that executes quickly, without hitting the network (for
+    instance, 'svn help' or 'git --version').
+    """
+    try:
+        p = subprocess.Popen(command.split(' '),
+                             stdin=subprocess.PIPE,
+                             stdout=subprocess.PIPE,
+                             stderr=subprocess.PIPE)
+        return True
+    except OSError:
+        return False
+
+
+def execute(command, env=None, split_lines=False, ignore_errors=False,
+            extra_ignore_errors=(), translate_newlines=True):
+    """
+    Utility function to execute a command and return the output.
+    """
+    if isinstance(command, list):
+        debug(subprocess.list2cmdline(command))
+    else:
+        debug(command)
+
+    if env:
+        env.update(os.environ)
+    else:
+        env = os.environ.copy()
+
+    env['LC_ALL'] = 'en_US.UTF-8'
+    env['LANGUAGE'] = 'en_US.UTF-8'
+
+    if sys.platform.startswith('win'):
+        p = subprocess.Popen(command,
+                             stdin=subprocess.PIPE,
+                             stdout=subprocess.PIPE,
+                             stderr=subprocess.STDOUT,
+                             shell=False,
+                             universal_newlines=translate_newlines,
+                             env=env)
+    else:
+        p = subprocess.Popen(command,
+                             stdin=subprocess.PIPE,
+                             stdout=subprocess.PIPE,
+                             stderr=subprocess.STDOUT,
+                             shell=False,
+                             close_fds=True,
+                             universal_newlines=translate_newlines,
+                             env=env)
+    if split_lines:
+        data = p.stdout.readlines()
+    else:
+        data = p.stdout.read()
+    rc = p.wait()
+    if rc and not ignore_errors and rc not in extra_ignore_errors:
+        die('Failed to execute command: %s\n%s' % (command, data))
+
+    return data
+
+
+def die(msg=None):
+    """
+    Cleanly exits the program with an error message. Erases all remaining
+    temporary files.
+    """
+    for tmpfile in tempfiles:
+        try:
+            os.unlink(tmpfile)
+        except:
+            pass
+
+    if msg:
+        print msg
+
+    sys.exit(1)
+
+
+def walk_parents(path):
+    """
+    Walks up the tree to the root directory.
+    """
+    while os.path.splitdrive(path)[1] != os.sep:
+        yield path
+        path = os.path.dirname(path)
+
+
+def load_config_file(filename):
+    """
+    Loads data from a config file.
+    """
+    config = {
+        'TREES': {},
+    }
+
+    if os.path.exists(filename):
+        try:
+            execfile(filename, config)
+        except:
+            pass
+
+    return config
+
+
+def tempt_fate(server, tool, changenum, diff_content=None,
+               parent_diff_content=None, submit_as=None, retries=3):
+    """
+    Attempts to create a review request on a Review Board server and upload
+    a diff. On success, the review request path is displayed.
+    """
+    try:
+        save_draft = False
+
+        if options.rid:
+            review_request = server.get_review_request(options.rid)
+        else:
+            review_request = server.new_review_request(changenum, submit_as)
+
+        if options.target_groups:
+            server.set_review_request_field(review_request, 'target_groups',
+                                            options.target_groups)
+            save_draft = True
+
+        if options.target_people:
+            server.set_review_request_field(review_request, 'target_people',
+                                            options.target_people)
+            save_draft = True
+
+        if options.summary:
+            server.set_review_request_field(review_request, 'summary',
+                                            options.summary)
+            save_draft = True
+
+        if options.branch:
+            server.set_review_request_field(review_request, 'branch',
+                                            options.branch)
+            save_draft = True
+
+        if options.bugs_closed:
+            server.set_review_request_field(review_request, 'bugs_closed',
+                                            options.bugs_closed)
+            save_draft = True
+
+        if options.description:
+            server.set_review_request_field(review_request, 'description',
+                                            options.description)
+            save_draft = True
+
+        if options.testing_done:
+            server.set_review_request_field(review_request, 'testing_done',
+                                            options.testing_done)
+            save_draft = True
+
+        if save_draft:
+            server.save_draft(review_request)
+    except APIError, e:
+        rsp, = e.args
+        if rsp['err']['code'] == 103: # Not logged in
+            retries = retries - 1
+
+            # We had an odd issue where the server ended up a couple of
+            # years in the future. Login succeeds but the cookie date was
+            # "odd" so use of the cookie appeared to fail and eventually
+            # ended up at max recursion depth :-(. Check for a maximum
+            # number of retries.
+            if retries >= 0:
+                server.login(force=True)
+                tempt_fate(server, tool, changenum, diff_content,
+                           parent_diff_content, submit_as, retries=retries)
+                return
+
+        if options.rid:
+            die("Error getting review request %s: %s (code %s)" % \
+                (options.rid, rsp['err']['msg'], rsp['err']['code']))
+        else:
+            die("Error creating review request: %s (code %s)" % \
+                (rsp['err']['msg'], rsp['err']['code']))
+
+
+    if not server.info.supports_changesets or not options.change_only:
+        try:
+            server.upload_diff(review_request, diff_content,
+                               parent_diff_content)
+        except APIError, e:
+            rsp, = e.args
+            print "Error uploading diff: %s (%s)" % (rsp['err']['msg'],
+                                                     rsp['err']['code'])
+            debug(rsp)
+            die("Your review request still exists, but the diff is not " +
+                "attached.")
+
+    if options.publish:
+        server.publish(review_request)
+
+    request_url = 'r/' + str(review_request['id'])
+    review_url = urljoin(server.url, request_url)
+
+    if not review_url.startswith('http'):
+        review_url = 'http://%s' % review_url
+
+    print "Review request #%s posted." % (review_request['id'],)
+    print
+    print review_url
+
+    return review_url
+
+
+def parse_options(args):
+    parser = OptionParser(usage="%prog [-pond] [-r review_id] [changenum]",
+                          version="%prog " + VERSION)
+
+    parser.add_option("-p", "--publish",
+                      dest="publish", action="store_true", default=PUBLISH,
+                      help="publish the review request immediately after "
+                           "submitting")
+    parser.add_option("-r", "--review-request-id",
+                      dest="rid", metavar="ID", default=None,
+                      help="existing review request ID to update")
+    parser.add_option("-o", "--open",
+                      dest="open_browser", action="store_true",
+                      default=OPEN_BROWSER,
+                      help="open a web browser to the review request page")
+    parser.add_option("-n", "--output-diff",
+                      dest="output_diff_only", action="store_true",
+                      default=False,
+                      help="outputs a diff to the console and exits. "
+                           "Does not post")
+    parser.add_option("--server",
+                      dest="server", default=REVIEWBOARD_URL,
+                      metavar="SERVER",
+                      help="specify a different Review Board server "
+                           "to use")
+    parser.add_option("--diff-only",
+                      dest="diff_only", action="store_true", default=False,
+                      help="uploads a new diff, but does not update "
+                           "info from changelist")
+    parser.add_option("--target-groups",
+                      dest="target_groups", default=TARGET_GROUPS,
+                      help="names of the groups who will perform "
+                           "the review")
+    parser.add_option("--target-people",
+                      dest="target_people", default=TARGET_PEOPLE,
+                      help="names of the people who will perform "
+                           "the review")
+    parser.add_option("--summary",
+                      dest="summary", default=None,
+                      help="summary of the review ")
+    parser.add_option("--description",
+                      dest="description", default=None,
+                      help="description of the review ")
+    parser.add_option("--description-file",
+                      dest="description_file", default=None,
+                      help="text file containing a description of the review")
+    parser.add_option("--guess-summary",
+                      dest="guess_summary", action="store_true",
+                      default=False,
+                      help="guess summary from the latest commit (git/"
+                           "hgsubversion only)")
+    parser.add_option("--guess-description",
+                      dest="guess_description", action="store_true",
+                      default=False,
+                      help="guess description based on commits on this branch "
+                           "(git/hgsubversion only)")
+    parser.add_option("--testing-done",
+                      dest="testing_done", default=None,
+                      help="details of testing done ")
+    parser.add_option("--testing-done-file",
+                      dest="testing_file", default=None,
+                      help="text file containing details of testing done ")
+    parser.add_option("--branch",
+                      dest="branch", default=None,
+                      help="affected branch ")
+    parser.add_option("--bugs-closed",
+                      dest="bugs_closed", default=None,
+                      help="list of bugs closed ")
+    parser.add_option("--revision-range",
+                      dest="revision_range", default=None,
+                      help="generate the diff for review based on given "
+                           "revision range")
+    parser.add_option("--label",
+                      dest="label", default=None,
+                      help="label (ClearCase Only) ")
+    parser.add_option("--submit-as",
+                      dest="submit_as", default=SUBMIT_AS, metavar="USERNAME",
+                      help="user name to be recorded as the author of the "
+                           "review request, instead of the logged in user")
+    parser.add_option("--username",
+                      dest="username", default=None, metavar="USERNAME",
+                      help="user name to be supplied to the reviewboard server")
+    parser.add_option("--password",
+                      dest="password", default=None, metavar="PASSWORD",
+                      help="password to be supplied to the reviewboard server")
+    parser.add_option("--change-only",
+                      dest="change_only", action="store_true",
+                      default=False,
+                      help="updates info from changelist, but does "
+                           "not upload a new diff (only available if your "
+                           "repository supports changesets)")
+    parser.add_option("--parent",
+                      dest="parent_branch", default=None,
+                      metavar="PARENT_BRANCH",
+                      help="the parent branch this diff should be against "
+                           "(only available if your repository supports "
+                           "parent diffs)")
+    parser.add_option("--p4-client",
+                      dest="p4_client", default=None,
+                      help="the Perforce client name that the review is in")
+    parser.add_option("--p4-port",
+                      dest="p4_port", default=None,
+                      help="the Perforce servers IP address that the review is on")
+    parser.add_option("--repository-url",
+                      dest="repository_url", default=None,
+                      help="the url for a repository for creating a diff "
+                           "outside of a working copy (currently only supported "
+                           "by Subversion).  Requires --revision-range")
+    parser.add_option("-d", "--debug",
+                      action="store_true", dest="debug", default=DEBUG,
+                      help="display debug output")
+
+    (globals()["options"], args) = parser.parse_args(args)
+
+    if options.description and options.description_file:
+        sys.stderr.write("The --description and --description-file options "
+                         "are mutually exclusive.\n")
+        sys.exit(1)
+
+    if options.description_file:
+        if os.path.exists(options.description_file):
+            fp = open(options.description_file, "r")
+            options.description = fp.read()
+            fp.close()
+        else:
+            sys.stderr.write("The description file %s does not exist.\n" %
+                             options.description_file)
+            sys.exit(1)
+
+    if options.testing_done and options.testing_file:
+        sys.stderr.write("The --testing-done and --testing-done-file options "
+                         "are mutually exclusive.\n")
+        sys.exit(1)
+
+    if options.testing_file:
+        if os.path.exists(options.testing_file):
+            fp = open(options.testing_file, "r")
+            options.testing_done = fp.read()
+            fp.close()
+        else:
+            sys.stderr.write("The testing file %s does not exist.\n" %
+                             options.testing_file)
+            sys.exit(1)
+
+    if options.repository_url and not options.revision_range:
+        sys.stderr.write("The --repository-url option requires the "
+                         "--revision-range option.\n")
+        sys.exit(1)
+
+    return args
+
+def determine_client():
+
+    repository_info = None
+    tool = None
+
+    # Try to find the SCM Client we're going to be working with.
+    for tool in SCMCLIENTS:
+        repository_info = tool.get_repository_info()
+
+        if repository_info:
+            break
+
+    if not repository_info:
+        if options.repository_url:
+            print "No supported repository could be access at the supplied url."
+        else:
+            print "The current directory does not contain a checkout from a"
+            print "supported source code repository."
+        sys.exit(1)
+
+    # Verify that options specific to an SCM Client have not been mis-used.
+    if options.change_only and not repository_info.supports_changesets:
+        sys.stderr.write("The --change-only option is not valid for the "
+                         "current SCM client.\n")
+        sys.exit(1)
+
+    if options.parent_branch and not repository_info.supports_parent_diffs:
+        sys.stderr.write("The --parent option is not valid for the "
+                         "current SCM client.\n")
+        sys.exit(1)
+
+    if ((options.p4_client or options.p4_port) and \
+        not isinstance(tool, PerforceClient)):
+        sys.stderr.write("The --p4-client and --p4-port options are not valid "
+                         "for the current SCM client.\n")
+        sys.exit(1)
+
+    return (repository_info, tool)
+
+def main():
+    if 'USERPROFILE' in os.environ:
+        homepath = os.path.join(os.environ["USERPROFILE"], "Local Settings",
+                                "Application Data")
+    elif 'HOME' in os.environ:
+        homepath = os.environ["HOME"]
+    else:
+        homepath = ''
+
+    # Load the config and cookie files
+    globals()['user_config'] = \
+        load_config_file(os.path.join(homepath, ".reviewboardrc"))
+    cookie_file = os.path.join(homepath, ".post-review-cookies.txt")
+
+    args = parse_options(sys.argv[1:])
+
+    repository_info, tool = determine_client()
+
+    # Try to find a valid Review Board server to use.
+    if options.server:
+        server_url = options.server
+    else:
+        server_url = tool.scan_for_server(repository_info)
+
+    if not server_url:
+        print "Unable to find a Review Board server for this source code tree."
+        sys.exit(1)
+
+    server = ReviewBoardServer(server_url, repository_info, cookie_file)
+
+    if repository_info.supports_changesets:
+        changenum = tool.get_changenum(args)
+    else:
+        changenum = None
+
+    if options.revision_range:
+        diff = tool.diff_between_revisions(options.revision_range, args,
+                                           repository_info)
+        parent_diff = None
+    elif options.label and isinstance(tool, ClearCaseClient):
+        diff, parent_diff = tool.diff_label(options.label)
+    else:
+        diff, parent_diff = tool.diff(args)
+
+    if options.output_diff_only:
+        print diff
+        sys.exit(0)
+
+    # Let's begin.
+    server.login()
+
+    review_url = tempt_fate(server, tool, changenum, diff_content=diff,
+                            parent_diff_content=parent_diff,
+                            submit_as=options.submit_as)
+
+    # Load the review up in the browser if requested to:
+    if options.open_browser:
+        try:
+            import webbrowser
+            if 'open_new_tab' in dir(webbrowser):
+                # open_new_tab is only in python 2.5+
+                webbrowser.open_new_tab(review_url)
+            elif 'open_new' in dir(webbrowser):
+                webbrowser.open_new(review_url)
+            else:
+                os.system( 'start %s' % review_url )
+        except:
+            print 'Error opening review URL: %s' % review_url
+
+
+if __name__ == "__main__":
+    main()
diff --git a/test/review b/test/review
new file mode 100644
index 0000000..e1ccb9c
--- /dev/null
+++ b/test/review
@@ -0,0 +1,44 @@
+#!/bin/sh
+
+if [ -z $1 ] || [ "$1" = "-h" ] || [ "$1" = "--help" ] || [ "$1" = "-help" ] || [ "$1" = "-?" ]; then
+  echo "Usage: `basename $0` [rev] [args]\n"
+  echo "  [rev]  : either the revision number without leading 'r' (post-commit),"
+  echo "           or '-loc' to create a review from current local changes (pre-commit)\n"
+  echo "  [args] : optional arguments:"
+  echo "     -r ID     existing review request ID to update\n"
+  exit 1
+fi
+
+POSTREVIEW=`dirname $0`/postreview.py
+
+if [ "$1" = "-loc" ]; then
+  echo "creating review request from local changes..."
+  REVARG=""
+  LOG=""
+  SUMMARY="local changes"
+  REPO=""
+else
+  REV=$1
+  PREV=`expr $REV - 1`
+  if [ $? -ne 0 ]; then
+    echo "argument revision not a number: $REV"
+    exit 1
+  fi
+
+  echo "creating review request for changeset $REV..."
+
+  LOG="`svn log http://lampsvn.epfl.ch/svn-repos/scala -c $REV`"
+  if [ $? -ne 0 ]; then
+    echo "could not get svn log for revision $REV"
+    exit 1
+  fi
+
+  REVARG="--revision-range=$PREV:$REV"
+  SUMMARY="r$REV"
+  REPO="--repository-url=http://lampsvn.epfl.ch/svn-repos/scala"
+fi
+
+
+shift # remove parameter $1 (revision)
+
+python $POSTREVIEW --server="https://chara2.epfl.ch" $REVARG --summary="$SUMMARY" --description="$LOG" $REPO -o $@
diff --git a/test/scala2-nightly-test.scm b/test/scala2-nightly-test.scm
deleted file mode 100644
index ba45736..0000000
--- a/test/scala2-nightly-test.scm
+++ /dev/null
@@ -1,137 +0,0 @@
-#!/bin/sh
-exec scsh -e main -s "$0" "$@"
-!#
-
-;; Script to perform the nightly test/build of Scala.
-;;
-;; Always make sure that the latest version of this file is copied to
-;; ~scalatest/bin/scala2-nightly-test.scm
-;;
-;; $Id: scala2-nightly-test.scm 14380 2008-03-13 12:24:34Z washburn $
-
-;; SVN repository containing the Scala compiler.
-(define scala-svn-repository-dir
-  "http://lampsvn.epfl.ch/svn-repos/scala/scala/trunk")
-(define plugin-svn-repository-dir
-  "http://lampsvn.epfl.ch/svn-repos/scala/plugin")
-
-;; SVN module containing the compiler.
-(define scala-svn-module-name "scala")
-(define plugin-svn-module-name "plugin")
-
-;; E-mail address to which the failure notification should be sent.
-(define notify-email "scala-reports at epfl.ch")
-;;(define notify-email "stephane.micheloud at epfl.ch") ; DEBUG
-;;(define notify-email "lex.spoon at epfl.ch") ; DEBUG
-;;(define notify-email "gilles.dubochet at epfl.ch") ; DEBUG
-
-;; Directory in which the distribution should be built.
-(define nightly-build-dir
-;;  (expand-file-name "~lex/scala/nightly"))  ; DEBUG
-    (expand-file-name "/home/linuxsoft/archives/scala/nightly"))
-
-;; End of configuration section.
-
-(define (main cmd-line)
-  (let ((prog (car cmd-line))
-        (args (cdr cmd-line)))
-    (if (= 1 (length args))
-        (scala-test (first args))
-        (display-usage-and-exit prog))))
-
-(define (display-usage-and-exit prog)
-  (format #t "Usage: ~a <result-dir>\n" prog)
-  (exit 1))
-
-(define (get-public-link file)
-  (temp-file-iterate (lambda (link) (create-symlink file link) link)
-                     (expand-file-name "~/public_html/log-scala2-~a.txt")))
-
-(define (get-checkout-dir base-dir date)
-  (expand-file-name (string-append (format-date "~Y-~m-~d" date) "-scala2") base-dir))
-
-(define (start-section title)
-  (format #t "\n* ~a\n\n" title))
-
-(define (scala-test base-dir)
-  (let* ((checkout-dir (get-checkout-dir base-dir (date)))
-         (log-file (expand-file-name "log-scala2" checkout-dir)))
-    (create-directory checkout-dir)
-    (call-with-output-file log-file
-      (lambda (log-port)
-        (with-current-output-port log-port
-          (with-current-error-port log-port
-            (stdports->stdio)
-            (with-cwd checkout-dir
-              (if (not (call-with-current-continuation scala-do-test))
-                  (let ((link (get-public-link log-file)))
-                    (send-warning-mail log-file
-                                       (file-name-nondirectory link)))))))))))
-
-(define (scala-do-test return)
-  (dynamic-wind
-      (lambda ()
-        (display "In Emacs, read this file in -*- Outline -*- mode\n")
-        (start-section "Starting time")
-        (display (format-date "~Y-~m-~d ~H:~M ~Z\n" (date))))
-      (lambda ()
-        (let ((fail-if-error (lambda (code) (if (not (zero? code))
-                                                (return #f)))))
-          (start-section "Checking out Scala module")
-          (fail-if-error (run (svn co ,scala-svn-repository-dir
-                                   ,scala-svn-module-name)))
-          (with-cwd scala-svn-module-name
-                    (start-section "Creating small Scala distribution")
-                    (fail-if-error (run (ant pack)))
-                    (run (ant msil)))
-
-          (start-section "Checking out Plugin module")
-          (fail-if-error (run (svn co ,plugin-svn-repository-dir
-                                   ,plugin-svn-module-name)))
-
-          (with-cwd plugin-svn-module-name
-                    (start-section "Creating Scala Eclipse plugin")
-                    (fail-if-error (run (ant dist))))
-
-          (with-cwd scala-svn-module-name
-                    (start-section "Testing Scala compiler")
-                    (fail-if-error
-                      (run (./test/scalatest --color=none
-                                             --show-log))))
-          #t
-        )
-      )
-      (lambda ()
-        (start-section "Ending time")
-        (display (format-date "~Y-~m-~d ~H:~M ~Z\n" (date))))))
-
-(define (send-warning-mail log-file-name link-name)
-  (send-mail
-   notify-email
-   `(("Subject"  . "Failure of nightly Scala 2 test")
-     ("To"       . ,notify-email)
-     ("Reply-To" . ,notify-email))
-   (string-append
-    "Tonight's automatic Scala test failed. More details can be found\n"
-    "in file "log-file-name"\n"
-    "which is available through the following URL:\n\n"
-    "  http://lamp.epfl.ch/~scalatest/"link-name"\n"
-    "\n"
-    (run/string (fgrep "[FAILED]" ,log-file-name)))))
-
-(define (send-mail to headers body)
-  (let ((mail-port (make-string-output-port)))
-    (for-each (lambda (name/contents)
-                (format mail-port "~a: ~a\n"
-                        (car name/contents)
-                        (cdr name/contents)))
-              headers)
-    (newline mail-port)
-    (write-string body mail-port)
-    (newline mail-port)
-    (run (/usr/sbin/sendmail "-i" ,to)
-         (<< ,(string-output-port-output mail-port)))))
-
-;;; Local Variables:
-;;; mode:scheme
-;;; End:
diff --git a/test/scala2-nightly-test.sh b/test/scala2-nightly-test.sh
deleted file mode 100644
index eca99c8..0000000
--- a/test/scala2-nightly-test.sh
+++ /dev/null
@@ -1,69 +0,0 @@
-#!/bin/sh
-
-[ -z "$JAVA_SDK" ] && ( echo "Variable JAVA_SDK not specified"; exit 1 )
-
-ANDROID_HOME=/home/linuxsoft/apps/android
-ANT_HOME=/home/linuxsoft/apps/ant
-JAVA_HOME=/home/linuxsoft/apps/$JAVA_SDK
-# uses scsh wrapper in ~/bin instead (mics)
-#SCSH_HOME=/home/linuxsoft/apps/scsh-rh9
-# Mono on linuxsoft is a 32-bit distro
-#MONO_HOME=/home/linuxsoft/apps/mono
-MONO_HOME=/opt/mono
-KVEM_HOME=/home/linuxsoft/apps/java-wtk
-RETROWEAVER_HOME=/home/linuxsoft/apps/retroweaver
-
-[ -d "$JAVA_HOME" ] || (echo "Invalid directory $JAVA_HOME"; exit 1 )
-
-PATH=/usr/local/bin:/bin:/usr/bin:/usr/sbin
-PATH=$ANT_HOME/bin:$JAVA_HOME/bin:$MONO_HOME/bin:$ANDROID_HOME/tools:$KVEM_HOME/bin:~/bin:$PATH
-
-LD_LIBRARY_PATH=/lib:/usr/lib
-
-ANT_OPTS="-Xms1024M -Xmx1024M -XX:MaxPermSize=128M"
-BUILD_DATE=`date +"%Y-%m-%d"`
-
-OUTPUT_DIR=~/scala-nightly-test/$JAVA_SDK
-TARGET_DIR=$OUTPUT_DIR/$BUILD_DATE-scala2
-#BUILD_DIR=$TARGET_DIR/scala/build
-LATEST_DIR=$TARGET_DIR/scala/dists
-LATEST_PLUGIN_DIR=$TARGET_DIR/plugin/dist
-NIGHTLY_DIR=/home/linuxsoft/archives/scala/nightly
-
-[ -d "$OUTPUT_DIR" ] || mkdir -p "$OUTPUT_DIR"
-
-JAVACMD=$JAVA_HOME/bin/java
-
-killall -9 scshvm 2>1
-killall -9 java 2>1
-
-env PATH="$PATH" ANT_OPTS="$ANT_OPTS" JAVACMD="$JAVACMD" \
-    ANDROID_HOME="$ANDROID_HOME" RETROWEAVER_HOME="$RETROWEAVER_HOME" \
-    ~/bin/scala2-nightly-test.scm $OUTPUT_DIR 
-
-# only build for Java 1.5 is made available on the page
-# http://www.scala-lang.org/downloads/distrib/files/nightly/
-test "$JAVA_SDK" != "java-1.5" && exit 0
-
-if [ -d "$LATEST_DIR" ] && [ `ls "$LATEST_DIR"/*.zip 2>1 | wc -l` -gt 0 ]; then
-    sbp_script="s/\(scala[a-z\-]*[0-9]\+\.[0-9]\+\.[0-9]\+\).*\(\.sbp\)/\1-latest\2/g"
-    tgz_script="s/\(scala[a-z\-]*[0-9]\+\.[0-9]\+\.[0-9]\+\).*\(\.tgz\)/\1-latest\2/g"
-    zip_script="s/\(scala[a-z\-]*[0-9]\+\.[0-9]\+\.[0-9]\+\).*\(\.zip\)/\1-latest\2/g"
-    (rm -rf $NIGHTLY_DIR && mkdir $NIGHTLY_DIR)
-    (cd $LATEST_DIR && cp *.tgz *.zip *.md5 *.sbp *.advert $NIGHTLY_DIR)
-    (cd $TARGET_DIR && cp log-scala2 $NIGHTLY_DIR)
-    (cd $NIGHTLY_DIR && tar xzf scala-*[^sources].tgz)
-    (cd $NIGHTLY_DIR && for f in *.sbp; do [ -h "$f" ] && continue; ln -sf $f `echo $f | sed -e "$sbp_script"`; done)
-    (cd $NIGHTLY_DIR && for f in *.tgz; do [ -h "$f" ] && continue; ln -sf $f `echo $f | sed -e "$tgz_script"`; done)
-    (cd $NIGHTLY_DIR && for f in *.zip; do [ -h "$f" ] && continue; ln -sf $f `echo $f | sed -e "$zip_script"`; done)
-fi
-if [ -d "$LATEST_PLUGIN_DIR" ]; then
-    latest_script="s/\(scala[a-z._]*[0-9]\+\.[0-9]\+\.[0-9]\+\).*\(\.zip\)/\1-latest\2/g"
-    (cd $LATEST_PLUGIN_DIR && cp -r *.zip scala.update $NIGHTLY_DIR)
-    (cd $NIGHTLY_DIR && for f in *.zip; do [ -h "$f" ] && continue; ln -sf $f `echo $f | sed -e "$latest_script"`; done)
-fi
-#disabled
-#if [ -d "$BUILD_DIR/api-compiler" ] && [ -d "$NIGHTLY_DIR/scala/doc/scala" ]; then
-#    cp -r $BUILD_DIR/api-compiler $NIGHTLY_DIR/scala/doc/scala
-#fi
-
diff --git a/test/scalatest b/test/scalatest
deleted file mode 100644
index e16eb44..0000000
--- a/test/scalatest
+++ /dev/null
@@ -1,973 +0,0 @@
-#!/bin/sh
-##############################################################################
-#                      __                                                    #
-#      ________ ___   / /  ___     Scala Tools Launch Script                 #
-#     / __/ __// _ | / /  / _ |    (c) 2002-2009, LAMP/EPFL                  #
-#   __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/                    #
-#  /____/\___/_/ |_/____/_/ | |                                              #
-#                           |/                                               #
-##############################################################################
-
-# $Id: scalatest 16881 2009-01-09 16:28:11Z cunei $
-
-##############################################################################
-# Error functions
-
-# Prints a warning message on stderr.
-warning() {
-    echo "$0: warning:" "$@" 1>&2;
-}
-
-# Prints an error message on stderr.
-error() {
-    echo "$0:" "$@" 1>&2;
-}
-
-# Prints an error message on stderr and exits with a non-zero status.
-abort() {
-    error "$@";
-    exit 1;
-}
-
-##############################################################################
-# Printing functions
-
-# Initializes the printf functions
-printf_initialization() {
-    case "$1" in
-        many )
-            printf_font_outline="printf \\033[1;39m";
-            printf_font_success="printf \\033[1;32m";
-            printf_font_failure="printf \\033[1;31m";
-            printf_font_warning="printf \\033[1;33m";
-            printf_font_default="printf \\033[0;39m";
-            ;;
-        some )
-            printf_font_outline="printf \\033[1m";
-            printf_font_success="printf \\033[0m";
-            printf_font_failure="printf \\033[1m";
-            printf_font_warning="printf \\033[1m";
-            printf_font_default="printf \\033[0m";
-            ;;
-        none )
-            printf_font_outline="";
-            printf_font_success="";
-            printf_font_failure="";
-            printf_font_warning="";
-            printf_font_default="";
-            ;;
-        * )
-            abort "unknown color mode \`$1'";
-            ;;
-    esac;
-}
-
-# Prints formated text in outline font.
-printf_outline() {
-    $printf_font_outline;
-    printf "$@";
-    $printf_font_default;
-}
-
-# Prints formated text in success font.
-printf_success() {
-    $printf_font_success;
-    printf "$@";
-    $printf_font_default;
-}
-
-# Prints formated text in failure font.
-printf_failure() {
-    $printf_font_failure;
-    printf "$@";
-    $printf_font_default;
-}
-
-# Prints formated text in warning font.
-printf_warning() {
-    $printf_font_warning;
-    printf "$@";
-    $printf_font_default;
-}
-
-##############################################################################
-# File name and path list conversion functions
-
-# Prints the OS-specific form of the specified Unix form file name.
-get_os_filename() {
-    [ $# = 1 ] || abort "internal error";
-    case "$UNAME" in
-        CYGWIN* ) cygpath --windows "$1";;
-        *       ) echo "$@";;
-    esac;
-}
-
-# Prints the Unix form of the specified OS-specific form file name.
-get_unix_filename() {
-    [ $# = 1 ] || abort "internal error";
-    case "$UNAME" in
-        CYGWIN* ) cygpath --unix "$1";;
-        *       ) echo "$@";;
-    esac;
-}
-
-# Prints the OS-specific form of the specified Unix form path list.
-get_os_pathlist() {
-    [ $# = 1 ] || abort "internal error";
-    case "$UNAME" in
-        CYGWIN* ) cygpath --window --path "$1";;
-        *       ) echo "$@";;
-    esac;
-}
-
-# Prints the Unix form of the specified OS-specific form path list.
-get_unix_pathlist() {
-    [ $# = 1 ] || abort "internal error";
-    case "$UNAME" in
-        CYGWIN* ) cygpath --unix --path "$1";;
-        *       ) echo "$@";;
-    esac;
-}
-
-# Collects all jar files in the given path
-get_ext_classpath() {
-    [ $# = 1 ] || abort "internal error";
-    # Constructing the extension classpath
-    cp=""
-    for ext in `ls $1/*.jar` ; do
-        if [ -z "$cp" ] ; then
-            cp="$ext"
-        else
-            cp="$cp:$ext"
-        fi
-    done
-
-    echo $cp
-}
-
-##############################################################################
-# Implementation of scalatest
-
-# Prints the scalatest usage.
-test_print_usage() {
-    [ $# = 0 ] || abort "internal error";
-    echo "Usage: `basename $0` [OPTION]... [FILE]..."
-}
-
-# Prints the scalatest help.
-test_print_help() {
-    [ $# = 0 ] || abort "internal error";
-    test_print_usage;
-    echo "";
-    echo "--auto          use filenames to select the test to run";
-    echo "--dis           next files test the class file disassembler";
-    echo "--run           next files test the interpreter and all backends";
-    echo "--jvm           next files test the JVM backend";
-    echo "--pos           next files test a compilation success";
-    echo "--neg           next files test a compilation failure";
-    echo "--res           next files test the resident compiler";
-    echo "--msil          next files test the .NET backend";
-    echo "--script        next files test Scala embedded in scripts";
-    echo "--ant           next files test the Ant tasks";
-    echo "--pending       perform the tests in the 'pending' directory";
-    echo "--shootout      next files test Debian's language shootout benchmarks";
-    echo "--quick         use the 'quick' build instead of distribution";
-    echo '--installed     use the installed programs on $PATH'
-    echo "--no-run        run no test, use results of last run";
-    echo "--show-log      show output of failed tests";
-    echo "--show-diff     show differences between actual and expected output";
-    echo "--use-fsc       use the Fast Scala compiler";
-    echo "--failed        test only files that failed last time";
-    echo "--errors=<int>  specify the number of expected errors";
-    echo "--flags=<flags> specify flags to pass on to the executable";
-    echo "--color=USAGE   control the color usage (USAGE=none|some|many)";
-    echo "--objdir=<dir>  specify where to place generated files";
-    echo "--help, -?      display this help and exit";
-    echo "--version       output version information and exit";
-    echo "";
-    echo "Report bugs to <scala at listes.epfl.ch>";
-}
-
-# Prints the scalatest version.
-test_print_version() {
-    [ $# = 0 ] || abort "internal error";
-    echo "$SCRIPT "'$Revision: 16881 $';
-}
-
-# Prints the name of the specified test file.
-test_print_testing() {
-    [ $# = 1 ] || abort "internal error";
-    printf_outline "testing: ";
-    case "$1" in
-        "$TESTROOT"* )
-            printf "%-60s " "[...]`expr "$1" : "$TESTROOT\(.*\)"`";
-            return 0;
-            ;;
-    esac;
-    printf "%-60s " "$1";
-}
-
-# Prints a test success notification.
-test_print_success() {
-    [ $# = 0 ] || abort "internal error";
-    printf "[";
-    printf_success "  OK  ";
-    printf "]\\n";
-}
-
-# Prints a test failure notification.
-test_print_failure() {
-    [ $# = 0 ] || abort "internal error";
-    printf "[";
-    printf_failure "FAILED";
-    printf "]\\n";
-}
-
-
-# Tests a compilation success.
-test_run_pos() {
-    rm -rf "$dstbase".obj &&
-    mkdir -p "$dstbase".obj &&
-    $SCALAC -d "$os_dstbase".obj "$@" "$os_srcbase".scala &&
-    rm -rf "$dstbase".obj;
-}
-
-
-# Tests a compilation failure.
-test_run_neg() {
-    rm -rf "$dstbase".obj &&
-    mkdir -p "$dstbase".obj &&
-    ( cd "$srcdir" && $SCALAC -d "$os_dstbase".obj "$@" "$testname".scala; );
-    if [ "$?" = 0 ]; then status=1; else status=0; fi;
-    rm -rf "$dstbase".obj;
-    return $status;
-}
-
-
-# Tests resident compiler.
-test_run_res() {
-    rm -rf "$dstbase".obj &&
-    mkdir -p "$dstbase".obj &&
-    (cd "$srcdir" && cat "$testname".res | $SCALAC -d "$os_dstbase".obj -Xresident -sourcepath . "$@"; );
-    #(cd "$TESTROOT" && cat "$srcdir/$testname".res | $SCALAC -d "$os_dstbase".obj -Xresident -sourcepath "$srcdir" "$@"; );
-    rm -rf "$dstbase".obj;
-}
-
-
-# Tests the JVM backend.
-# NB. property '-Djavacmd=$JAVACMD' is e.g used by jvm/inner.scala
-test_run_jvm() {
-    javaopts=$JAVA_OPTS;
-    if [ -f "$os_srcbase".javaopts ]; then
-        javaopts="$javaopts `cat "$os_srcbase".javaopts`"
-        if [ "$JAVA5" = "false" ]; then
-             # -Xss option available in Java versions 1.5 or newer
-             javaopts=`echo "$javaopts" | sed -e "s/-Xss[0-9]*[MmKk]//g"`
-        fi
-    fi
-    rm -rf "$dstbase".obj &&
-    mkdir -p "$dstbase".obj &&
-    ext_classpath=`get_os_pathlist "$JVM_EXT_CLASSPATH"` &&
-    (cd "$srcdir" && env JAVACMD="$JAVACMD" JAVA_OPTS="$javaopts" $SCALAC -d "$os_dstbase".obj \
-        -cp "$ext_classpath" "$@" "$testname".scala ) &&
-    libpath=`get_os_pathlist "$dstdir"` &&
-    scala_javaopts=`echo -Djava.library.path=$libpath` &&
-    scala_lib=`get_os_filename "$SCALA_LIB"` &&
-    classpath=`get_os_pathlist "$os_dstbase".obj:$CLASSPATH:$ext_classpath` &&
-    env JAVA_OPTS="$scala_javaopts" $SCALA -Djavacmd="$JAVACMD" \
-        -Dscalatest.output=$os_dstbase.obj -Dscalatest.lib=$scala_lib \
-        -classpath "$classpath" Test "jvm" &&
-    rm -rf "$dstbase".obj;
-}
-
-# Test the disassemblers.
-test_run_dis() {
-    argsfile="$srcbase".args;
-    [ ! -f "$argsfile" ] && argsfile=/dev/null;
-    rm -rf "$dstbase".obj &&
-    mkdir -p "$dstbase".obj &&
-    $SCALAC -d "$os_dstbase".obj "$@" "$os_srcbase".scala &&
-    $SCALAP -classpath "$os_dstbase".obj `cat "$argsfile"` &&
-    rm -rf "$dstbase".obj;
-}
-
-MSIL="msil"
-EXE="exe"
-# Tests the .NET backend.
-test_run_msil() {
-    assemblies=`get_os_pathlist $SCALA_ASSEM`;
-    rm -f "$dstbase".$MSIL &&
-    rm -f "$dstbase".$EXE &&
-
-    $SCALAC -nowarn -Xassem "$os_dstbase" -Xassem-path $assemblies "$@" \
-        -sourcepath "$PREFIX/build/msil/src" "$os_srcbase".scala &&
-    case "$UNAME" in
-        CYGWIN* )
-            $ILASM /qui /nol /out="$os_dstbase".$EXE "$os_dstbase".$MSIL \
-                > /dev/null &&
-#             peverify /il "$os_dstbase".EXE > /dev/null &&
-            "$dstbase".$EXE_SUFFIX "msil";;
-        * )
-            $ILASM /output:"$os_dstbase".$EXE "$os_dstbase".$MSIL \
-                > /dev/null &&
-            monopath=`get_os_pathlist $PREFIX/build/msil:$PREFIX/lib` &&
-            env MONO_PATH="$monopath" $MONO "$dstbase.$EXE" "msil";;
-    esac &&
-    rm -f "$dstbase".$EXE &&
-    rm -f "$dstbase".$MSIL;
-}
-
-# Tests the CLDC target platform.
-test_run_cldc() {
-    rm -rf "$dstbase".unverified "$dstbase".preverified &&
-    mkdir -p "$dstbase".unverified "$dstbase".preverified &&
-    cpath=`get_os_pathlist $KVEM_CLDC:$KVEM_MIDP:$SCALA_CLDC:"$dstbase".unverified` &&
-    $SCALAC -bootclasspath $cpath -target:cldc -d "$os_dstbase".unverified "$os_srcbase".scala &&
-    $KVEM_PREVERIFY -classpath $cpath -target cldc1.0 -d "$os_dstbase".preverified "$os_dstbase".unverified &&
-    ( echo MIDlet-Name: Test;
-      echo MIDlet-Version: 1.0.0;
-      echo MIDlet-Vendor: LAMP ) > "$dstbase".mf &&
-    $JARCMD cfm "$dstbase".jar "$dstbase".mf -C "$os_dstbase".preverified . &&
-    jarsize=`wc -c "$dstbase".jar  | cut -d ' ' -f 1` &&
-    ( echo MIDlet-1: Test, , Test;
-      echo MIDlet-Name: Test;
-      echo MIDlet-Version: 1.0.0;
-      echo MIDlet-Vendor: LAMP;
-      echo MIDlet-Jar-URL: "$dstbase".jar;
-      echo MIDlet-Jar-Size: $jarsize;
-      echo MicroEdition-Profile: MIDP-1.0;
-      echo MicroEdition-Configuration: CLDC-1.0 ) > "$dstbase".jad &&
-    cpath=`get_os_pathlist $SCALA_CLDCAPI:"$dstbase".jar` &&
-    $KVEM_EMULATOR -cp $cpath -Xdescriptor:"$dstbase".jad 2> /dev/null &&
-    head $logfile -n 4 | tail -n 1 > $logfile.0 &&
-    mv $logfile.0 $logfile
-}
-
-# Tests the Android target platform.
-test_run_android() {
-    rm -rf "$dstbase" &&
-    os_classes=`get_os_filename "$dstbase"/classes` &&
-    mkdir -p "$os_classes" &&
-    xml_file=`get_os_filename "$dstbase"/AndroidManifest.xml` &&
-    cp "$srcbase".xml $xml_file &&
-    cpath=`get_os_pathlist $ANDROID_LIB:"$dstbase"` &&
-    $SCALAC -bootclasspath $cpath -cp "$os_classes" -d "$os_classes" -encoding ascii "$os_srcbase".scala &&
-#    echo $JAVACCMD -bootclasspath $cpath -cp "$os_classes" -d "$os_classes" -encoding ascii "$os_srcbase"/**/*.java &&
-    extdirs=`get_os_pathlist "$ANDROID_HOME/tools/lib"` &&
-    dex_file=`get_os_filename "$os_dstbase"/classes.dex` &&
-    scala_lib=`get_os_filename "$SCALA_LIB"` &&
-    $JAVACMD -Djava.ext.dirs=$extdirs -Xmx384M -jar $DX_LIB \
-        --dex --output=$dex_file --locals=full --positions=lines \
-        "$scala_lib" "$os_classes" &&
-    ( cd "$dstbase" && zip -9q Test.apk *.xml *.dex &&
-      $ANDROID_ADB shell '"cd data/app; rm Test.apk"' 2>&1 1> /dev/null &&
-      $ANDROID_ADB install Test.apk 2> /dev/null)
-}
-
-# Tests a script with Scala code embedded in it
-test_run_script() {
-    argsfile="$srcbase.args"
-    if [ ! -r "$argsfile" ]; then
-        argsfile=/dev/null
-    fi
-    chmod +x "$srcbase.scala" 2> /dev/null
-    PATH="$BIN_DIR:$PATH" "$srcbase.scala" `cat $argsfile`
-}
-
-# Tests the Scala Ant task
-test_run_ant() {
-    if [ "$BIN_DIR" = "" ]; then BINARY=installed
-    elif [ "$BIN_DIR" = "$QUICK" ]; then BINARY=quick
-    else BINARY=latest
-    fi;
-    testname=`basename "$srcbase"`;
-    buildfile=`get_os_filename "$srcdir/$testname-build.xml"`;
-    rm -rf "$dstbase".obj &&
-    $ANT -f "$buildfile" -Dbinary="$BINARY" -Dbuild.dir="$os_dstbase".obj &&
-    rm -rf "$dstbase".obj;
-}
-
-# Tests the shootout benchmarks
-test_run_shootout() {
-    javaopts=$JAVA_OPTS;
-    if [ -f "$os_srcbase".javaopts ]; then
-        javaopts="$javaopts `cat "$os_srcbase".javaopts`"
-        if [ "$JAVA5" = "false" ]; then
-             # -Xss option available in Java versions 1.5 or newer
-             javaopts=`echo "$javaopts" | sed -e "s/-Xss[0-9]*[MmKk]//g"`
-        fi
-    fi
-    rm -rf "$dstbase".obj &&
-    mkdir -p "$dstbase".obj &&
-    testfile=`get_os_filename "$dstbase".obj/test.scala` &&
-    cat "$os_srcbase".scala.runner "$os_srcbase".scala > "$testfile" &&
-    ext_classpath=`get_os_pathlist "$JVM_EXT_CLASSPATH"` &&
-    $SCALAC -d "$os_dstbase".obj -cp "$ext_classpath" "$@" "$testfile" &&
-    scala_lib=`get_os_filename "$SCALA_LIB"` &&
-    classpath=`get_os_pathlist "$os_dstbase".obj:$CLASSPATH:$ext_classpath` &&
-    src_dir=`get_os_filename "$srcdir"` &&
-    env JAVACMD="$JAVACMD" JAVA_OPTS="$javaopts" \
-        $SCALA -Dscalatest.cwd="$src_dir" -Dscalatest.output=$os_dstbase.obj \
-               -Dscalatest.lib=$scala_lib -classpath "$classpath" Test &&
-    rm -rf "$dstbase".obj;
-}
-
-# Checks the specified test.
-test_check_test() {
-    [ $# = 1 ] || abort "internal error";
-    testfile="$1"; shift 1;
-    # compute test name
-    testname=`basename "$testfile" ."$TEST_EXT"`;
-
-    # compute source and destination directories (absolute paths)
-    srcdir=`dirname "$testfile"`;
-    srcdir=`cd "$srcdir"; pwd`;
-
-    dstdir="$OBJDIR""$srcdir";
-
-    # compute source and destination base names
-    srcbase="$srcdir"/"$testname";
-
-    dstbase="$dstdir"/"$testname"-$kind;
-    os_srcbase=`get_os_filename "$srcbase"`;
-    os_dstbase=`get_os_filename "$dstbase"`;
-
-    # compute flags file
-    flagsfile="$srcbase".flags;
-    [ ! -f "$flagsfile" ] && flagsfile=/dev/null;
-
-    # compute check file
-    checkfile="$srcbase"-$kind.check;
-    [ ! -f "$checkfile" ] && checkfile="$srcbase".check;
-    [ ! -f "$checkfile" ] && checkfile=/dev/null;
-
-    # compute log file
-    logfile="$dstbase".log;
-
-    # if we are testing only failed tests, skip successful tests
-    if [ "$FAILED" = "true" -a ! -f "$logfile" ]; then
-        return 0;
-    fi;
-
-    # if that's the first file of the section print section header
-    if [ -n "$header" ]; then
-        printf_outline "$header\\n";
-        unset header;
-    fi;
-
-    # print tested file
-    test_print_testing "$testfile";
-
-    # run test
-    if [ "$NORUN" = "true" ]; then
-        [ ! -f "$logfile" ];
-    else
-        rm -f "$logfile";
-        { [ -d "$dstdir" ] || mkdir -p "$dstdir"; } &&
-        ( test_run_$kind `cat "$flagsfile"` $FLAGS 1> "$logfile" 2>&1; ) &&
-        $DIFF "$logfile" "$checkfile" 1> /dev/null 2>&1 &&
-        rm -f "$logfile";
-    fi;
-
-    # print result
-    if [ "$?" = 0 ]; then
-        SUCCESS_COUNT=`echo "$SUCCESS_COUNT+1" | bc`;
-        test_print_success;
-    else
-        FAILURE_COUNT=`echo "$FAILURE_COUNT+1" | bc`;
-        test_print_failure;
-        [ ! -f "$logfile" ] && logfile=/dev/null;
-        [ "$SHOWLOG" = "true" ] && cat "$logfile";
-        [ "$SHOWDIFF" = "true" ] && $DIFF "$logfile" "$checkfile";
-    fi;
-}
-
-# Checks the specified file
-test_check_file() {
-    [ $# = 1 ] || abort "internal error";
-    file="$1"; shift 1;
-    for testfile in "" `find "$file" -name "*.obj" -prune -o -name "*.$TEST_EXT" -a -type f -print`; do
-        [ -z "$testfile" ] && continue;
-        test_check_test "$testfile";
-    done;
-}
-
-# Checks all files of the specified kind.
-test_check_kind() {
-    [ $# -ge 2 ] || abort "internal error";
-    header="$1"; shift 1;
-    kind="$1"; shift 1;
-    if [ "$kind" = "res" ]; then TEST_EXT="res"; else TEST_EXT="scala"; fi;
-
-    for file in "" "$@"; do
-        [ -z "$file" ] && continue;
-        test_check_file "$file";
-    done
-    [ -z "$header" ] && echo "";
-}
-
-# Checks everything.
-test_check_all() {
-    [ $# = 0 ] || abort "internal error";
-    test_check_kind "Testing disassembler" \
-        "dis" $FILES_DIS;
-    test_check_kind "Testing JVM backend" \
-        "jvm" $FILES_RUN $FILES_JVM;
-    test_check_kind "Testing compiler (on files whose compilation should succeed)" \
-        "pos" $FILES_POS;
-    test_check_kind "Testing compiler (on files whose compilation should fail)" \
-        "neg" $FILES_NEG;
-    test_check_kind "Testing .NET backend" \
-        "msil" $FILES_MSIL;
-    test_check_kind "Testing Scala embedded in script files"  \
-        "script" $FILES_SCRIPT;
-    test_check_kind "Testing Scala Ant tasks"  \
-        "ant" $FILES_ANT;
-    test_check_kind "Testing resident compiler" \
-        "res" $FILES_RES;
-    test_check_kind "Testing shootout benchmarks" \
-        "shootout" $FILES_SHOOTOUT;
-    test_check_kind "Testing CLDC benchmarks" \
-        "cldc" $FILES_CLDC;        
-    test_check_kind "Testing Android benchmarks" \
-        "android" $FILES_ANDROID;        
-}
-
-
-# Adds a new file to the appropriate file list(s).
-test_add_file() {
-    [ $# = 1 ] || abort "internal error";
-    case "$1" in
-        *.scala | *.res )
-            if [ ! \( -d "$1" -o -f "$1" \) ]; then
-                abort "don't know what to do with '$1'";
-            fi;;
-        * )
-            if [ ! -d "$1" ]; then
-                abort "don't know what to do with '$1'";
-            fi;;
-    esac;
-    TEST_ALL="false";
-    case "$TEST_TYPE" in
-        auto   ) ;;
-        android) FILES_ANDROID="$FILES_ANDROID $1"; return;;
-        cldc   ) FILES_CLDC="$FILES_CLDC $1"; return;;
-        dis    ) FILES_DIS="$FILES_DIS $1"; return;;
-        run    ) FILES_RUN="$FILES_RUN $1"; return;;
-        jvm    ) FILES_JVM="$FILES_JVM $1"; return;;
-        pos    ) FILES_POS="$FILES_POS $1"; return;;
-        neg    ) FILES_NEG="$FILES_NEG $1"; return;;
-        res    ) FILES_RES="$FILES_RES $1"; return;;
-        msil   ) FILES_MSIL="$FILES_MSIL $1"; return;;
-        script ) FILES_SCRIPT="$FILES_SCRIPT $1"; return;;
-        ant    ) FILES_ANT="$FILES_ANT $1"; return;;
-        shootout ) FILES_SHOOTOUT="$FILES_SHOOTOUT $1"; return;;
-        *      ) abort "unknown test type \`$TEST_TYPE'";;
-    esac;
-    case "$1" in
-        android | */android | */android/* | android/* ) FILES_ANDROID="$FILES_ANDROID $1";;
-        cldc | */cldc | */cldc/* | cldc/* ) FILES_CLDC="$FILES_CLDC $1";;
-        dis  | */dis  | */dis/*  | dis/*  ) FILES_DIS="$FILES_DIS $1";;
-        run  | */run  | */run/*  | run/*  ) FILES_RUN="$FILES_RUN $1";;
-        jvm5 | */jvm5 | */jvm5*  | jvm5/* )
-            if [ "$JAVA5" = "true" ]; then
-                FILES_JVM="$FILES_JVM $1"
-            fi;;
-        jvm  | */jvm  | */jvm/*  | jvm/*  ) FILES_JVM="$FILES_JVM $1";;
-        pos  | */pos  | */pos/*  | pos/*  ) FILES_POS="$FILES_POS $1";;
-        neg  | */neg  | */neg/*  | neg/*  ) FILES_NEG="$FILES_NEG $1";;
-        res  | */res  | */res/*  | res/*  ) FILES_RES="$FILES_RES $1";;
-        msil | */msil | */msil/* | msil/* ) FILES_MSIL="$FILES_MSIL $1";;
-        script | */script | */script/* | script/* ) FILES_SCRIPT="$FILES_SCRIPT $1";;
-        shootout | */shootout | */shootout/* | shootout/* ) FILES_SHOOTOUT="$FILES_SHOOTOUT $1";;
-        * ) abort "don't known what to do with \`$1'";;
-    esac;
-}
-
-test_get_location() {
-    [ $# = 1 ] || abort "internal error";
-    source="$1"; shift 1;
-    script=`basename "$source"`;
-    while [ -h "$source" ]; do
-        script=`basename "$source"`;
-        lookup=`ls -ld "$source"`;
-        target=`expr "$lookup" : '.*-> \(.*\)$'`;
-        if expr "${target:-.}/" : '/.*/$' > /dev/null; then
-            source=${target:-.};
-        else
-            source=`dirname "$source"`/${target:-.};
-       fi;
-    done;
-    location=`dirname "$source"`;
-    location=`cd "$location"; pwd`;
-    echo $location;
-}
-
-##############################################################################
-# Definition of UNAME, SOURCE, SCRIPT and PREFIX
-
-unset SCRIPT;
-UNAME=`uname`;
-SOURCE=$0;
-SCRIPT=`basename "$SOURCE"`;
-while [ -h "$SOURCE" ]; do
-    SCRIPT=`basename "$SOURCE"`;
-    LOOKUP=`ls -ld "$SOURCE"`;
-    TARGET=`expr "$LOOKUP" : '.*-> \(.*\)$'`;
-    if expr "${TARGET:-.}/" : '/.*/$' > /dev/null; then
-        SOURCE=${TARGET:-.};
-    else
-        SOURCE=`dirname "$SOURCE"`/${TARGET:-.};
-    fi;
-done;
-PREFIX=`dirname "$SOURCE"`/..;
-PREFIX=`cd "$PREFIX"; pwd`;
-
-##############################################################################
-# Invocation of $SCRIPT
-
-# Print deprecation warning
-echo "######################################################################"
-echo "## DEPRECATION WARNING                                              ##"
-echo "######################################################################"
-echo "## The 'scalatest' runner script has been deprecated. Please use    ##"
-echo "## 'partest' instead.                                               ##"
-echo "######################################################################"
-echo ""
-
-NORUN="false";
-SHOWLOG="false";
-SHOWDIFF="false";
-USEFSC="false";
-FAILED="false";
-ERRORS=0;
-SUCCESS_COUNT=0;
-FAILURE_COUNT=0;
-if [ -d "$PREFIX/test" ]; then
-    TESTROOT="$PREFIX/test";
-elif [ -d "$PREFIX/misc/scala-test" ]; then
-    TESTROOT="$PREFIX/misc/scala-test";
-else
-    abort "Test directory not found";
-fi;
-SRCDIR="$TESTROOT/files";
-OBJDIR="""";
-
-TEST_ALL="true";
-TEST_TYPE="auto";
-FILES_RUN="";
-FILES_JVM="";
-FILES_POS="";
-FILES_RES="";
-FILES_NEG="";
-FILES_MSIL="";
-FILES_SCRIPT="";
-FILES_DIS="";
-FILES_ANT="";
-FILES_SHOOTOUT="";
-FILES_CLDC="";
-FILES_ANDROID="";
-
-QUICK="$PREFIX/build/quick/bin"
-QUICK_LIB="$PREFIX/build/quick/lib/library"
-QUICK_COMP="$PREFIX/build/quick/lib/compiler"
-QUICK_ACT="$PREFIX/build/quick/lib/actors"
-QUICK_PREDEF="$PREFIX/build/quick/lib/predef.dll"
-QUICK_CLDC="$PREFIX/build/cldc/lib/scalaapi10-unverified.jar"  # unverified
-QUICK_CLDCAPI="$PREFIX/build/cldc/lib/scalaapi10.jar"  # preverified
-
-JVM_EXT_CLASSPATH=`get_ext_classpath $TESTROOT/files/lib`
-
-if [ -d "$PREFIX/dists" ]; then
-    LATEST="$PREFIX/dists/latest/bin";
-    LATEST_LIB="$PREFIX/dists/latest/lib/scala-library.jar";
-    LATEST_COMP="$PREFIX/dists/latest/lib/scala-compiler.jar";
-    LATEST_PREDEF="$PREFIX/dists/latest/lib/predef.dll";
-    LATEST_CLDC=$QUICK_CLDC;
-    LATEST_CLDCAPI=$QUICK_CLDCAPI;
-elif [ -d "$PREFIX/build" ]; then
-    LATEST="$QUICK";
-    LATEST_LIB=$QUICK_LIB;
-    LATEST_COMP=$QUICK_COMP;
-    LATEST_ACT=$QUICK_ACT;
-    LATEST_PREDEF=$QUICK_PREDEF;
-    LATEST_CLDC=$QUICK_CLDC;
-    LATEST_CLDCAPI=$QUICK_CLDCAPI;
-elif [ -d "$PREFIX/bin" ]; then
-    LATEST="$PREFIX/bin";
-    LATEST_LIB="$PREFIX/lib/scala-library.jar";
-    LATEST_COMP="$PREFIX/lib/scala-compiler.jar";
-    LATEST_PREDEF="$PREFIX/lib/predef.dll";
-    LATEST_CLDC="$PREFIX/lib/scalaapi10-unverified.jar";
-    LATEST_CLDCAPI="$PREFIX/lib/scalaapi10.jar";
-else
-    abort "Scala binaries could not be found";
-fi;
-BIN_DIR="$LATEST/"  # BIN_DIR should have a trailing / when needed, so that
-                    # it can also be set to the empty string
-
-SCALA_LIB="$LATEST_LIB";
-SCALA_COMP="$LATEST_COMP";
-SCALA_ACT="$LATEST_ACT";
-SCALA_CLDC="$LATEST_CLDC";
-SCALA_CLDCAPI="$LATEST_CLDCAPI";
-
-[ -x "$JAVACMD" ] || JAVACMD=java;
-[ -n "$JAVA_OPTS" ] || JAVA_OPTS="-Xmx256M -Xms16M";
-case `$JAVACMD \-version 2>&1 | xargs` in
-    *1.5.*IBM* ) JAVA5="true"; IBM_J9="true"; JAVA_OPTS="$JAVA_OPTS -Xss2M";;
-    *1.6.*IBM* ) JAVA5="true"; IBM_J9="true";;
-    *1.[5-7].* ) JAVA5="true";;
-    *1.4.*GNU* ) JAVA5="false"; GIJ="true"; JAVA_OPTS="--mx256m --ms16m";;
-             * ) JAVA5="false";;
-esac;
-
-case "$UNAME" in
-    CYGWIN* ) DIFF="diff --text --strip-trailing-cr";;
-    *       ) DIFF="diff --strip-trailing-cr";;
-esac;
-
-while [ $# -gt 0 ]; do
-    case "$1" in
-        --android    ) TEST_TYPE="android"; shift 1;;
-        --auto       ) TEST_TYPE="auto"; shift 1;;
-        --cldc       ) TEST_TYPE="cldc"; shift 1;;
-        --dis        ) TEST_TYPE="dis"; shift 1;;
-        --run        ) TEST_TYPE="run"; shift 1;;
-        --jvm        ) TEST_TYPE="jvm"; shift 1;;
-        --pos        ) TEST_TYPE="pos"; shift 1;;
-        --neg        ) TEST_TYPE="neg"; shift 1;;
-        --res        ) TEST_TYPE="res"; shift 1;;
-        --msil       ) TEST_TYPE="msil"; shift 1;;
-        --script     ) TEST_TYPE="script"; shift 1;;
-        --ant        ) TEST_TYPE="ant"; shift 1;;
-        --shootout   ) TEST_TYPE="shootout"; shift 1;;
-        --quick      ) BIN_DIR="$QUICK/"; SCALA_LIB=$QUICK_LIB;
-                       SCALA_COMP=$QUICK_COMP; SCALA_ACT=$QUICK_ACT;
-                       SCALA_PREDEF=$QUICK_PREDEF; shift 1;;
-        --installed  ) BIN_DIR=""; shift 1;;
-        --no-run     ) NORUN="true"; shift 1;;
-        --show-log   ) SHOWLOG="true"; shift 1;;
-        --show-diff  ) SHOWDIFF="true"; shift 1;;
-        --use-fsc    ) USEFSC="true"; shift 1;;
-        --failed     ) FAILED="true"; shift 1;;
-        --pending    ) SRCDIR="$TESTROOT/pending"; shift 1;;
-        --errors=    ) abort "illegal empty argument for option --errors";;
-        --errors=*   ) ERRORS=`expr "$1" : "--errors=\([0-9]*\)$"`;shift 1;;
-        --flags=     ) abort "illegal empty argument for option --flags";;
-        --flags=*    ) FLAGS=`expr "$1" : "--flags=\(.*\)"`; shift 1;;
-        --color=     ) abort "illegal empty argument for option --color";;
-        --color=*    ) COLOR=`expr "$1" : "--color=\(.*\)"`; shift 1;;
-        --objdir=*   ) OBJDIR=`expr "$1" : "--objdir=\(.*\)"`; shift 1;;
-        --help| -?   ) test_print_help; exit 0;;
-        --version    ) test_print_version; exit 0;;
-        -*           ) abort "unknown option $1";;
-        *            ) test_add_file "$1"; shift 1;;
-    esac;
-done;
-
-if [ "$TEST_TYPE" = "msil" ]; then
-    FLAGS="$FLAGS -target:msil";
-elif [ "$JAVA5" = "false" ]; then
-    FLAGS="$FLAGS -target:jvm-1.4";
-fi;
-
-if [ -z "$ERRORS" ]; then
-    abort "illegal non-numerical argument for option --errors";
-fi;
-
-if [ -z "$COLOR" -a -n "$EMACS" ]; then
-    COLOR="none";
-fi;
-printf_initialization "${COLOR:-many}";
-
-if [ "$TEST_ALL" = "true" ]; then
-    case "$TEST_TYPE" in
-        android ) FILES_ANDROID="$FILES_ANDROID $SRCDIR/android";;
-    esac;
-    case "$TEST_TYPE" in
-        cldc ) FILES_CLDC="$FILES_CLDC $SRCDIR/cldc";;
-    esac;
-    case "$TEST_TYPE" in
-        dis ) FILES_DIS="$FILES_DIS $SRCDIR/dis";;
-    esac;
-    case "$TEST_TYPE" in
-        run ) FILES_RUN="$FILES_RUN $SRCDIR/run";;
-    esac;
-    case "$TEST_TYPE" in
-        auto | shootout ) FILES_SHOOTOUT="$FILES_SHOOTOUT $SRCDIR/shootout";;
-    esac;    
-    case "$TEST_TYPE" in
-        auto | jvm )
-            FILES_JVM="$FILES_JVM $SRCDIR/run $SRCDIR/jvm"
-            if [ "$JAVA5" = "true" ]; then
-                FILES_JVM="$FILES_JVM $SRCDIR/jvm5";
-            fi;;
-    esac;
-    case "$TEST_TYPE" in
-        auto | pos ) FILES_POS="$FILES_POS $SRCDIR/pos";;
-    esac;
-    case "$TEST_TYPE" in
-        auto | neg ) FILES_NEG="$FILES_NEG $SRCDIR/neg";;
-    esac;
-    case "$TEST_TYPE" in
-        auto | res ) FILES_RES="$FILES_RES $SRCDIR/res";;
-    esac;
-    case "$TEST_TYPE" in
-        msil ) FILES_MSIL="$FILES_MSIL $SRCDIR/run";;
-    esac;
-    case "$TEST_TYPE" in
-        auto | script ) FILES_SCRIPT="$FILES_SCRIPT $SRCDIR/script";;
-    esac;
-    case "$TEST_TYPE" in
-        ant ) FILES_ANT="$FILES_ANT $SRCDIR/ant";;
-    esac;
-fi;
-
-SCALA="${BIN_DIR}scala";
-[ -z "$SCALAC_OPTS" ] && SCALAC_OPTS="-deprecation";
-if [ "$USEFSC" = "true" ]; then
-    SCALAC_CMD="${BIN_DIR}fsc";
-else
-    SCALAC_CMD="${BIN_DIR}scalac";
-fi;
-
-scalac=`which "$SCALAC_CMD" 2> /dev/null`
-if [ -z "$scalac" ] || [ ! -x "$scalac" ]; then
-    printf_failure "Missing command \"$SCALAC_CMD\"; run 'ant <target>'.\\n";
-    exit 1;
-fi;
-SCALAC="$SCALAC_CMD $SCALAC_OPTS";
-SCALAP="scalap";
-
-CLASSPATH=$SCALA_COMP:$SCALA_ACT
-SCALA_ASSEM=$SCALA_PREDEF:$PREFIX/lib/scalaruntime.dll:$PREFIX/lib/mscorlib.dll
-
-if [ -z "$ANT" ]; then
-    if [ -d "$ANT_HOME" ]; then
-        ANT="$ANT_HOME/bin/ant";
-    else
-        ANT="ant";
-    fi
-fi;
-if [ -z "$ILASM" ]; then
-    if [ -d "$MONO_HOME" ]; then
-        ILASM="$MONO_HOME/bin/ilasm";
-    else
-        ILASM="ilasm";
-    fi
-fi;
-if [ -z "$MONO" ]; then
-    if [ -d "$MONO_HOME" ]; then
-        MONO="$MONO_HOME/bin/mono";
-    else
-        MONO="mono";
-    fi
-fi;
-
-if [ -n "$OBJDIR" ]; then
-    if [ -d "$OBJDIR" ] || mkdir -p "$OBJDIR"; then
-        OBJDIR=`cd "$OBJDIR"; pwd`;
-    else
-        abort "could not create directory '$OBJDIR'";
-    fi
-fi;
-
-printf_outline "Source directory is : $SRCDIR\\n";
-bin_dir=$BIN_DIR
-if [ -z "$bin_dir" ]; then
-    scalac=`which $SCALAC_CMD`;
-    bin_dir=`test_get_location $scalac`;
-fi;
-printf_outline "Scala binaries in   : $bin_dir\\n";
-scala_version=`${SCALAC_CMD} -version 2>&1`
-printf_outline "Scala version is    : $scala_version\\n";
-[ -n "$SCALAC_OPTS" ] && printf_outline "Scalac options are  : $SCALAC_OPTS\\n";
-
-if [ $TEST_TYPE = "msil" ]; then
-    ilasm_version=`$ILASM --version 2>&1`;
-    printf_outline "ILasm version is    : $ilasm_version\\n";
-    mono_version=`$MONO --version | head -1`;
-    printf_outline "Mono version is     : $mono_version\\n";
-    if [ -f "$SCALA_PREDEF" ]; then
-        printf_outline "DLL library is      : $SCALA_PREDEF\\n";
-    else
-        printf_failure "Missing library \"predef.dll\"; run 'ant msil'.\\n";
-        exit 1;
-    fi
-else
-    javacmd=`which $JAVACMD 2>/dev/null`;
-    bin_dir=`test_get_location $javacmd`;
-    printf_outline "Java binaries in    : $bin_dir\\n";
-    if [ "$GIJ" = "true" ]; then
-        jvm_version=`$JAVACMD -version 2>&1 | head -2 | tail -1`
-    else
-        jvm_version=`$JAVACMD -version 2>&1 | head -3 | tail -1`
-    fi;
-    printf_outline "Java runtime is     : $jvm_version\\n";
-    [ -n "$JAVA_OPTS" ] && printf_outline "Java options are    : $JAVA_OPTS\\n";
-    if [ "$TEST_TYPE" = "ant" ]; then
-        ant_version=`$ANT -version`;
-        printf_outline "Ant version is      : $ant_version\\n";
-    elif [ "$TEST_TYPE" = "cldc" ]; then
-        if [ -d "$KVEM_HOME" ]; then
-            KVEM_PREVERIFY="$KVEM_HOME/bin/preverify";
-            KVEM_EMULATOR="$KVEM_HOME/bin/emulator";
-            KVEM_CLDC="$KVEM_HOME/lib/cldcapi10.jar";
-            KVEM_MIDP="$KVEM_HOME/lib/midpapi10.jar";
-            JARCMD="$bin_dir/jar";
-        elif [ -d "/home/linuxsoft/apps/" ]; then
-            error "option '--cldc' requires variable KVEM_HOME to be set"
-            abort "(eg. export KVEM_HOME=/home/linuxsoft/apps/java-wtk)";
-        else
-            abort "option '--cldc' requires variable KVEM_HOME to be set";
-        fi;
-        kvem_version=`$KVEM_EMULATOR -version | head -1`;
-        printf_outline "Emulator version is : $kvem_version\\n";
-    elif [ "$TEST_TYPE" = "android" ]; then
-      if [ -s "$ANDROID_HOME" ]; then
-            ANDROID_ADB="$ANDROID_HOME/tools/adb";
-            ANDROID_EMULATOR="$ANDROID_HOME/tools/emulator";
-            ANDROID_LIB="$ANDROID_HOME/android.jar";
-            DX_LIB="$ANDROID_HOME/tools/lib/dx.jar";
-            JAVACCMD="$bin_dir/javac";
-            JARCMD="$bin_dir/jar";
-        elif [ -d "/home/linuxsoft/apps/" ]; then
-            error "option '--android' requires variable ANDROID_HOME to be set"
-            abort "(eg. export ANDROID_HOME=/home/linuxsoft/apps/android)";
-        else
-            abort "option '--android' requires variable ANDROID_HOME to be set";
-        fi;
-        android_version="m3-rc22a"; #not yet available through command
-        printf_outline "Emulator version is : $android_version\\n";
-        status=`$ANDROID_ADB shell '"exit"' 2>&1 | wc -l` &&
-        [ "$status" = "0" ] || abort "Start the Android emulator before running the tests!!!";
-    fi
-fi;
-printf_outline "\\n";
-
-START_SECONDS=`date +%s`;
-test_check_all;
-END_SECONDS=`date +%s`;
-
-TOTAL_COUNT=`echo "$FAILURE_COUNT+$SUCCESS_COUNT" | bc`;
-
-ELAPSED_SECONDS=`expr $END_SECONDS - $START_SECONDS`;
-case "$UNAME" in
-    Darwin* ) ELAPSED_TIME=`date -r $ELAPSED_SECONDS +%T`;;
-    *       ) ELAPSED_TIME=`date --date="1970-01-01 $ELAPSED_SECONDS sec" +%T`;;
-esac;
-
-if [ $FAILURE_COUNT -eq 0 ]; then
-    printf_success "All of $TOTAL_COUNT tests were successful (elapsed time: $ELAPSED_TIME)\\n";
-else
-    printf_failure "$FAILURE_COUNT of $TOTAL_COUNT tests failed (elapsed time: $ELAPSED_TIME)\\n";
-fi;
-
-if [ $FAILURE_COUNT -eq "$ERRORS" ]; then
-    exit 0;
-else
-    exit 1;
-fi;
-
-##############################################################################
diff --git a/test/scalatest.bat b/test/scalatest.bat
deleted file mode 100644
index b0dc3bf..0000000
--- a/test/scalatest.bat
+++ /dev/null
@@ -1,321 +0,0 @@
- at echo off
-
-rem ##########################################################################
-rem # Copyright 2002-2009 LAMP/EPFL
-rem #
-rem # This is free software; see the distribution for copying conditions.
-rem # There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A
-rem # PARTICULAR PURPOSE.
-rem ##########################################################################
-
-rem We adopt the following conventions:
-rem - System/user environment variables start with a letter
-rem - Local batch variables start with an underscore ('_')
-
-echo ######################################################################
-echo ## DEPRECATION WARNING                                              ##
-echo ######################################################################
-echo ## The 'scalatest' runner script has been deprecated. Please use    ##
-echo ## 'partest' instead.                                               ##
-echo ######################################################################
-echo.
-
-if "%OS%"=="Windows_NT" (
-  @setlocal
-  call :set_home
-) else (
-  set _SCALA_HOME=%SCALA_HOME%
-  if "%_SCALA_HOME%"=="" goto err_home
-)
-
-rem We use the value of the JAVACMD environment variable if defined
-set _JAVACMD=%JAVACMD%
-if "%_JAVACMD%"=="" set _JAVACMD=java
-
-set _BIN=dists\latest\bin
-set _NORUN=
-set _TYPE=auto
-set _SHOWLOG=
-set _SHOWDIFF=
-set _FAILED=
-
-set _ARGS=
-:loop
-rem Argument %1 may contain quotes so we use parentheses here
-if (%1)==() goto exec
-if (%1)==(--auto)      set _TYPE=auto& goto next
-if (%1)==(--run)       set _TYPE=run& goto next
-if (%1)==(--jvm)       set _TYPE=jvm& goto next
-if (%1)==(--pos)       set _TYPE=pos& goto next
-if (%1)==(--neg)       set _TYPE=neg& goto next
-if (%1)==(--msil)      set _TYPE=msil& goto next
-if (%1)==(--quick)     set _BIN=build\quick\bin& goto next
-if (%1)==(--no-run)    set _NORUN=1& goto next
-if (%1)==(--show-log)  set _SHOWLOG=1& goto next
-if (%1)==(--show-diff) set _SHOWDIFF=1& goto next
-if (%1)==(--failed)    set _FAILED=1& goto next
-if (%1)==(--help)      call :prt_help & goto :eof
-if (%1)==(-h)          call :prt_help & goto :eof
-if (%1)==(-?)          call :prt_help & goto :eof
-if (%1)==(--version)   call :prt_version & goto :eof
-if (%1)==(-v)          call :prt_version & goto :eof
-call :chk_option %1
-if errorlevel 0 goto err_opt
-set _ARGS=%_ARGS% %1
-:next
-shift
-goto loop
-
-:exec
-if exist "%_SCALA_HOME%\meta\universe" (
-  set _BINDIR=%_SCALA_HOME%\bin
-  set _SRCDIR=%_SCALA_HOME%\misc\scala-test\files
-  set _DIFFDIR=%_SCALA_HOME%\bin\diff
-) else (
-  set _BINDIR=%_SCALA_HOME%\%_BIN%
-  set _SRCDIR=%_SCALA_HOME%\test\files
-  set _DIFFDIR=%_SCALA_HOME%\test\diff
-)
-
-set _SCALA=%_BINDIR%\scala
-set _SCALAC=%_BINDIR%\scalac
-set _SCALAP=%_BINDIR%\scalap
-set _DIFF=%_DIFFDIR%\diff.exe --text --strip-trailing-cr
-
-if not exist "%_BINDIR%" goto err_bin
-
-set _OBJDIR=
-set _TMPDIR=%TEMP%
-
-if not "%_OBJDIR%"=="" (
-  if not exist "%_OBJDIR%" mkdir "%_OBJDIR%"
-)
-if not "%_TMPDIR%"=="" (
-  if not exist "%_TMPDIR%" mkdir "%_TMPDIR%"
-)
-
-call :prt_dir "Source directory is  :" "%_SRCDIR%"
-call :prt_dir "Scala binaries are in:" "%_BINDIR%"
-call :set_version
-call :prt_dir "Scala version is     :" "%_NSC_VERSION%"
-call :prt_dir "Java runtime is      :" "%_JVM_VERSION%"
-
-set _FILES_POS=
-set _FILES_RUN=
-set _FILES_JVM=
-set _FILES_NEG=
-set _FILES_MSIL=
-
-if %_TYPE%==pos (
-  set _FILES_POS=%_SRCDIR%\pos
-) else if %_TYPE%==run (
-  set _FILES_RUN=%_SRCDIR%\run
-) else if %_TYPE%==jvm (
-  set _FILES_JVM=%_SRCDIR%\jvm
-  set _FILES_RUN=%_SRCDIR%\run
-) else if %_TYPE%==neg (
-  set _FILES_NEG=%_SRCDIR%\neg
-) else if %_TYPE%==msil (
-  set _FILES_MSIL=%_SRCDIR%\msil
-) else if %_TYPE%==auto (
-  set _FILES_POS=%_SRCDIR%\pos
-  set _FILES_NEG=%_SRCDIR%\neg
-  set _FILES_JVM=%_SRCDIR%\jvm
-  set _FILES_RUN=%_SRCDIR%\run
-) else (
-  goto err_test
-)
-:start
-call :chk_all
-goto end
-
-rem ##########################################################################
-rem # subroutines
-rem # NB. goto/call commands use only the first 8 characters of a label
-
-:prt_dir
-  echo %~1 %~2
-  goto :eof
-
-:prt_header
-  echo.
-  echo %~1
-  goto :eof
-
-:prt_help
-  echo Usage: scalatest [OPTION]...
-  echo.
-  echo --auto          use filenames to select the test to run
-  echo --run           next files test the interpreter and all backends
-  echo --jvm           next files test the JVM backend
-  echo --pos           next files test a compilation success
-  echo --neg           next files test a compilation failure
-  echo --msil          next files test the .NET 
-  echo --quick         use the 'quick' build instead of the distribution
-  echo --no-run        run no test, use results of last run
-  echo --show-log      show output of failed tests
-  echo --show-diff     show differences between actual and expected output
-  echo --failed        test only files that failed last time
-  echo --help, -h, -?  display this help and exit
-  echo --version, -v   output version information and exit
-  goto :eof
-
-:prt_version
-  echo Scala test suite 0.9.3 -- (c) 2002-2009 LAMP/EPFL
-  goto :eof
-
-:prt_status
-  set _MSG=testing: [...]\%~1\%2
-  if not "%_STATUS%"=="0" goto failed
-  set /a _CNT_SUCCESS=_CNT_SUCCESS+1
-  echo %_MSG%  [OK]
-  goto :eof
-  :failed
-  set /a _CNT_FAILURE=_CNT_FAILURE+1
-  echo %_MSG%  [FAILED]
-  if not "%_SHOWLOG%"=="" type %_LOGFILE%
-  goto :eof
-
-rem Variable "%~dps0" works on WinXP SP2 or newer
-rem (see http://support.microsoft.com/?kbid=833431)
-rem set _SCALA_HOME=%~dps0..
-:set_home
-  set _BINDIR=
-  for %%i in (%~sf0) do set _BINDIR=%_BINDIR%%%~dpsi
-  set _SCALA_HOME=%_BINDIR%..
-  goto :eof
-
-:set_version
-  set _TMPFILE=%_TMPDIR%\.version
-  call %_SCALAC% -version 2> %_TMPFILE%
-  for /f "tokens=*" %%f in (%_TMPFILE%) do @set _VERSION=%%f
-  set _NSC_VERSION=%_VERSION%
-  %_JAVACMD% -version 2> %_TMPFILE%
-  for /f "skip=2 tokens=*" %%f in (%_TMPFILE%) do @set _VERSION=%%f
-  set _JVM_VERSION=%_VERSION%
-  goto :eof
-
-:chk_option
-  echo %~1 | findstr /r /c:"-.*" 1>NUL
-  goto :eof
-
-rem Tests a compilation success.
-:test_pos
-  rmdir /s/q %_DSTBASE%.obj 2>NUL
-  mkdir %_DSTBASE%.obj
-  call %_SCALAC% -d %_DSTBASE%.obj %1 1>NUL 2>NUL
-  if errorlevel 1 goto status_pos
-  set _STATUS=0
-  goto next_pos
-  :status_pos
-  set _STATUS=1
-  :next_pos
-  rmdir /s/q %_DSTBASE%.obj
-  goto :eof
-
-rem Tests a compilation failure.
-:test_neg
-  rmdir /s/q %_DSTBASE%.obj 2>NUL
-  mkdir %_DSTBASE%.obj
-  call %_SCALAC% -d %_DSTBASE%.obj %1 1>NUL 2>NUL
-  if errorlevel 1 goto status_neg
-  set _STATUS=1
-  goto next_neg
-  :status_neg
-  set _STATUS=0
-  :next_neg
-  rmdir /s/q %_DSTBASE%.obj
-  goto :eof
-
-rem Tests the JVM backend.
-:test_jvm
-  rmdir /s/q %_DSTBASE%.obj 2>NUL
-  mkdir %_DSTBASE%.obj
-  call %_SCALAC% -d %_DSTBASE%.obj %1 2>NUL
-  if errorlevel 1 goto status_jvm
-  call %_SCALA% -cp %_DSTBASE%.obj Test "jvm" 1>%_LOGFILE% 2>NUL
-  if errorlevel 1 goto status_jvm
-  set _STATUS=0
-  goto next_jvm
-  :status_jvm
-  set _STATUS=1
-  :next_jvm
-  rmdir /s/q %_DSTBASE%.obj
-  goto :eof
-
-:chk_test
-  if "%_OBJDIR%"=="" (
-    set _DSTDIR=%_SRCDIR%
-  ) else (
-    set _DSTDIR=%_OBJDIR%
-  )
-  set _DSTBASE=%_DSTDIR%\%~n1-%_KIND%
-  set _LOGFILE=%_DSTBASE%.log
-  set _CHKFILE=%~dpn1.check
-
-  if not '%_HEADER%'=='' call :prt_header %_HEADER% & set _HEADER=
-
-  if "%_KIND%"=="jvm" call :test_jvm %1 & goto status
-  if "%_KIND%"=="pos" call :test_pos %1 & goto status
-  if "%_KIND%"=="neg" call :test_neg %1 & goto status
-  goto :eof
-  :status
-  if exist %_LOGFILE% %_DIFF% %_LOGFILE% %_CHKFILE% 2>NUL
-  call :prt_status %_KIND% %~nx1
-  del /s/q %_LOGFILE% 2>NUL 1>NUL
-  goto :eof
-
-:chk_file
-  set _CNT_SUCCESS=0
-  set _CNT_FAILURE=0
-  for %%f in (%1\*.scala) do call :chk_test %%f
-  set /a _CNT_TOTAL=_CNT_SUCCESS+_CNT_FAILURE
-  if "%_CNT_FAILURE%"=="0" goto success
-  echo %_CNT_FAILURE% of %_CNT_TOTAL% tests failed
-  goto :eof
-  :success
-  echo All of %_CNT_TOTAL% tests were successful
-  goto :eof
-
-:chk_kind
-  set _HEADER=%1
-  shift
-  set _KIND=%1
-  shift
-  :loop_kind
-  if "%1"=="" goto done
-  call :chk_file %1
-  shift
-  goto loop_kind
-  :done
-  goto :eof
-
-rem Checks everything.
-:chk_all
-  call :chk_kind "Testing JVM backend" jvm %_FILES_RUN% %_FILES_JVM%
-  call :chk_kind "Testing compiler (on files whose compilation should succeed)" pos %_FILES_POS%
-  call :chk_kind "Testing compiler (on files whose compilation should fail)" neg %_FILES_NEG%
-  call :chk_kind "Testing .NET backend" msil %_FILES_MSIL%
-  goto :eof
-
-rem ##########################################################################
-rem # errors
-
-:err_bin
-echo ERROR: missing command "%_SCALAC%; run "ant build".
-goto end
-
-:err_home
-echo ERROR: Windows NT or newer is required to run this batch command.
-goto end
-
-:err_test
-echo ERROR: Illegal test type %_TYPE%.
-goto end
-
-:err_opt
-echo ERROR: Unknown option %1
-goto end
-
-:end
-if "%OS%"=="Windows_NT" @endlocal
diff --git a/test/simplejson/__init__.py b/test/simplejson/__init__.py
new file mode 100644
index 0000000..d5b4d39
--- /dev/null
+++ b/test/simplejson/__init__.py
@@ -0,0 +1,318 @@
+r"""JSON (JavaScript Object Notation) <http://json.org> is a subset of
+JavaScript syntax (ECMA-262 3rd edition) used as a lightweight data
+interchange format.
+
+:mod:`simplejson` exposes an API familiar to users of the standard library
+:mod:`marshal` and :mod:`pickle` modules. It is the externally maintained
+version of the :mod:`json` library contained in Python 2.6, but maintains
+compatibility with Python 2.4 and Python 2.5 and (currently) has
+significant performance advantages, even without using the optional C
+extension for speedups.
+
+Encoding basic Python object hierarchies::
+
+    >>> import simplejson as json
+    >>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
+    '["foo", {"bar": ["baz", null, 1.0, 2]}]'
+    >>> print json.dumps("\"foo\bar")
+    "\"foo\bar"
+    >>> print json.dumps(u'\u1234')
+    "\u1234"
+    >>> print json.dumps('\\')
+    "\\"
+    >>> print json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True)
+    {"a": 0, "b": 0, "c": 0}
+    >>> from StringIO import StringIO
+    >>> io = StringIO()
+    >>> json.dump(['streaming API'], io)
+    >>> io.getvalue()
+    '["streaming API"]'
+
+Compact encoding::
+
+    >>> import simplejson as json
+    >>> json.dumps([1,2,3,{'4': 5, '6': 7}], separators=(',',':'))
+    '[1,2,3,{"4":5,"6":7}]'
+
+Pretty printing::
+
+    >>> import simplejson as json
+    >>> s = json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4)
+    >>> print '\n'.join([l.rstrip() for l in  s.splitlines()])
+    {
+        "4": 5,
+        "6": 7
+    }
+
+Decoding JSON::
+
+    >>> import simplejson as json
+    >>> obj = [u'foo', {u'bar': [u'baz', None, 1.0, 2]}]
+    >>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]') == obj
+    True
+    >>> json.loads('"\\"foo\\bar"') == u'"foo\x08ar'
+    True
+    >>> from StringIO import StringIO
+    >>> io = StringIO('["streaming API"]')
+    >>> json.load(io)[0] == 'streaming API'
+    True
+
+Specializing JSON object decoding::
+
+    >>> import simplejson as json
+    >>> def as_complex(dct):
+    ...     if '__complex__' in dct:
+    ...         return complex(dct['real'], dct['imag'])
+    ...     return dct
+    ...
+    >>> json.loads('{"__complex__": true, "real": 1, "imag": 2}',
+    ...     object_hook=as_complex)
+    (1+2j)
+    >>> import decimal
+    >>> json.loads('1.1', parse_float=decimal.Decimal) == decimal.Decimal('1.1')
+    True
+
+Specializing JSON object encoding::
+
+    >>> import simplejson as json
+    >>> def encode_complex(obj):
+    ...     if isinstance(obj, complex):
+    ...         return [obj.real, obj.imag]
+    ...     raise TypeError(repr(o) + " is not JSON serializable")
+    ...
+    >>> json.dumps(2 + 1j, default=encode_complex)
+    '[2.0, 1.0]'
+    >>> json.JSONEncoder(default=encode_complex).encode(2 + 1j)
+    '[2.0, 1.0]'
+    >>> ''.join(json.JSONEncoder(default=encode_complex).iterencode(2 + 1j))
+    '[2.0, 1.0]'
+
+
+Using simplejson.tool from the shell to validate and pretty-print::
+
+    $ echo '{"json":"obj"}' | python -m simplejson.tool
+    {
+        "json": "obj"
+    }
+    $ echo '{ 1.2:3.4}' | python -m simplejson.tool
+    Expecting property name: line 1 column 2 (char 2)
+"""
+__version__ = '2.0.9'
+__all__ = [
+    'dump', 'dumps', 'load', 'loads',
+    'JSONDecoder', 'JSONEncoder',
+]
+
+__author__ = 'Bob Ippolito <bob at redivi.com>'
+
+from decoder import JSONDecoder
+from encoder import JSONEncoder
+
+_default_encoder = JSONEncoder(
+    skipkeys=False,
+    ensure_ascii=True,
+    check_circular=True,
+    allow_nan=True,
+    indent=None,
+    separators=None,
+    encoding='utf-8',
+    default=None,
+)
+
+def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True,
+        allow_nan=True, cls=None, indent=None, separators=None,
+        encoding='utf-8', default=None, **kw):
+    """Serialize ``obj`` as a JSON formatted stream to ``fp`` (a
+    ``.write()``-supporting file-like object).
+
+    If ``skipkeys`` is true then ``dict`` keys that are not basic types
+    (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``)
+    will be skipped instead of raising a ``TypeError``.
+
+    If ``ensure_ascii`` is false, then the some chunks written to ``fp``
+    may be ``unicode`` instances, subject to normal Python ``str`` to
+    ``unicode`` coercion rules. Unless ``fp.write()`` explicitly
+    understands ``unicode`` (as in ``codecs.getwriter()``) this is likely
+    to cause an error.
+
+    If ``check_circular`` is false, then the circular reference check
+    for container types will be skipped and a circular reference will
+    result in an ``OverflowError`` (or worse).
+
+    If ``allow_nan`` is false, then it will be a ``ValueError`` to
+    serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``)
+    in strict compliance of the JSON specification, instead of using the
+    JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).
+
+    If ``indent`` is a non-negative integer, then JSON array elements and object
+    members will be pretty-printed with that indent level. An indent level
+    of 0 will only insert newlines. ``None`` is the most compact representation.
+
+    If ``separators`` is an ``(item_separator, dict_separator)`` tuple
+    then it will be used instead of the default ``(', ', ': ')`` separators.
+    ``(',', ':')`` is the most compact JSON representation.
+
+    ``encoding`` is the character encoding for str instances, default is UTF-8.
+
+    ``default(obj)`` is a function that should return a serializable version
+    of obj or raise TypeError. The default simply raises TypeError.
+
+    To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
+    ``.default()`` method to serialize additional types), specify it with
+    the ``cls`` kwarg.
+
+    """
+    # cached encoder
+    if (not skipkeys and ensure_ascii and
+        check_circular and allow_nan and
+        cls is None and indent is None and separators is None and
+        encoding == 'utf-8' and default is None and not kw):
+        iterable = _default_encoder.iterencode(obj)
+    else:
+        if cls is None:
+            cls = JSONEncoder
+        iterable = cls(skipkeys=skipkeys, ensure_ascii=ensure_ascii,
+            check_circular=check_circular, allow_nan=allow_nan, indent=indent,
+            separators=separators, encoding=encoding,
+            default=default, **kw).iterencode(obj)
+    # could accelerate with writelines in some versions of Python, at
+    # a debuggability cost
+    for chunk in iterable:
+        fp.write(chunk)
+
+
+def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True,
+        allow_nan=True, cls=None, indent=None, separators=None,
+        encoding='utf-8', default=None, **kw):
+    """Serialize ``obj`` to a JSON formatted ``str``.
+
+    If ``skipkeys`` is false then ``dict`` keys that are not basic types
+    (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``)
+    will be skipped instead of raising a ``TypeError``.
+
+    If ``ensure_ascii`` is false, then the return value will be a
+    ``unicode`` instance subject to normal Python ``str`` to ``unicode``
+    coercion rules instead of being escaped to an ASCII ``str``.
+
+    If ``check_circular`` is false, then the circular reference check
+    for container types will be skipped and a circular reference will
+    result in an ``OverflowError`` (or worse).
+
+    If ``allow_nan`` is false, then it will be a ``ValueError`` to
+    serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in
+    strict compliance of the JSON specification, instead of using the
+    JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).
+
+    If ``indent`` is a non-negative integer, then JSON array elements and
+    object members will be pretty-printed with that indent level. An indent
+    level of 0 will only insert newlines. ``None`` is the most compact
+    representation.
+
+    If ``separators`` is an ``(item_separator, dict_separator)`` tuple
+    then it will be used instead of the default ``(', ', ': ')`` separators.
+    ``(',', ':')`` is the most compact JSON representation.
+
+    ``encoding`` is the character encoding for str instances, default is UTF-8.
+
+    ``default(obj)`` is a function that should return a serializable version
+    of obj or raise TypeError. The default simply raises TypeError.
+
+    To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
+    ``.default()`` method to serialize additional types), specify it with
+    the ``cls`` kwarg.
+
+    """
+    # cached encoder
+    if (not skipkeys and ensure_ascii and
+        check_circular and allow_nan and
+        cls is None and indent is None and separators is None and
+        encoding == 'utf-8' and default is None and not kw):
+        return _default_encoder.encode(obj)
+    if cls is None:
+        cls = JSONEncoder
+    return cls(
+        skipkeys=skipkeys, ensure_ascii=ensure_ascii,
+        check_circular=check_circular, allow_nan=allow_nan, indent=indent,
+        separators=separators, encoding=encoding, default=default,
+        **kw).encode(obj)
+
+
+_default_decoder = JSONDecoder(encoding=None, object_hook=None)
+
+
+def load(fp, encoding=None, cls=None, object_hook=None, parse_float=None,
+        parse_int=None, parse_constant=None, **kw):
+    """Deserialize ``fp`` (a ``.read()``-supporting file-like object containing
+    a JSON document) to a Python object.
+
+    If the contents of ``fp`` is encoded with an ASCII based encoding other
+    than utf-8 (e.g. latin-1), then an appropriate ``encoding`` name must
+    be specified. Encodings that are not ASCII based (such as UCS-2) are
+    not allowed, and should be wrapped with
+    ``codecs.getreader(fp)(encoding)``, or simply decoded to a ``unicode``
+    object and passed to ``loads()``
+
+    ``object_hook`` is an optional function that will be called with the
+    result of any object literal decode (a ``dict``). The return value of
+    ``object_hook`` will be used instead of the ``dict``. This feature
+    can be used to implement custom decoders (e.g. JSON-RPC class hinting).
+
+    To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
+    kwarg.
+
+    """
+    return loads(fp.read(),
+        encoding=encoding, cls=cls, object_hook=object_hook,
+        parse_float=parse_float, parse_int=parse_int,
+        parse_constant=parse_constant, **kw)
+
+
+def loads(s, encoding=None, cls=None, object_hook=None, parse_float=None,
+        parse_int=None, parse_constant=None, **kw):
+    """Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON
+    document) to a Python object.
+
+    If ``s`` is a ``str`` instance and is encoded with an ASCII based encoding
+    other than utf-8 (e.g. latin-1) then an appropriate ``encoding`` name
+    must be specified. Encodings that are not ASCII based (such as UCS-2)
+    are not allowed and should be decoded to ``unicode`` first.
+
+    ``object_hook`` is an optional function that will be called with the
+    result of any object literal decode (a ``dict``). The return value of
+    ``object_hook`` will be used instead of the ``dict``. This feature
+    can be used to implement custom decoders (e.g. JSON-RPC class hinting).
+
+    ``parse_float``, if specified, will be called with the string
+    of every JSON float to be decoded. By default this is equivalent to
+    float(num_str). This can be used to use another datatype or parser
+    for JSON floats (e.g. decimal.Decimal).
+
+    ``parse_int``, if specified, will be called with the string
+    of every JSON int to be decoded. By default this is equivalent to
+    int(num_str). This can be used to use another datatype or parser
+    for JSON integers (e.g. float).
+
+    ``parse_constant``, if specified, will be called with one of the
+    following strings: -Infinity, Infinity, NaN, null, true, false.
+    This can be used to raise an exception if invalid JSON numbers
+    are encountered.
+
+    To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
+    kwarg.
+
+    """
+    if (cls is None and encoding is None and object_hook is None and
+            parse_int is None and parse_float is None and
+            parse_constant is None and not kw):
+        return _default_decoder.decode(s)
+    if cls is None:
+        cls = JSONDecoder
+    if object_hook is not None:
+        kw['object_hook'] = object_hook
+    if parse_float is not None:
+        kw['parse_float'] = parse_float
+    if parse_int is not None:
+        kw['parse_int'] = parse_int
+    if parse_constant is not None:
+        kw['parse_constant'] = parse_constant
+    return cls(encoding=encoding, **kw).decode(s)
diff --git a/test/simplejson/decoder.py b/test/simplejson/decoder.py
new file mode 100644
index 0000000..b769ea4
--- /dev/null
+++ b/test/simplejson/decoder.py
@@ -0,0 +1,354 @@
+"""Implementation of JSONDecoder
+"""
+import re
+import sys
+import struct
+
+from simplejson.scanner import make_scanner
+try:
+    from simplejson._speedups import scanstring as c_scanstring
+except ImportError:
+    c_scanstring = None
+
+__all__ = ['JSONDecoder']
+
+FLAGS = re.VERBOSE | re.MULTILINE | re.DOTALL
+
+def _floatconstants():
+    _BYTES = '7FF80000000000007FF0000000000000'.decode('hex')
+    if sys.byteorder != 'big':
+        _BYTES = _BYTES[:8][::-1] + _BYTES[8:][::-1]
+    nan, inf = struct.unpack('dd', _BYTES)
+    return nan, inf, -inf
+
+NaN, PosInf, NegInf = _floatconstants()
+
+
+def linecol(doc, pos):
+    lineno = doc.count('\n', 0, pos) + 1
+    if lineno == 1:
+        colno = pos
+    else:
+        colno = pos - doc.rindex('\n', 0, pos)
+    return lineno, colno
+
+
+def errmsg(msg, doc, pos, end=None):
+    # Note that this function is called from _speedups
+    lineno, colno = linecol(doc, pos)
+    if end is None:
+        #fmt = '{0}: line {1} column {2} (char {3})'
+        #return fmt.format(msg, lineno, colno, pos)
+        fmt = '%s: line %d column %d (char %d)'
+        return fmt % (msg, lineno, colno, pos)
+    endlineno, endcolno = linecol(doc, end)
+    #fmt = '{0}: line {1} column {2} - line {3} column {4} (char {5} - {6})'
+    #return fmt.format(msg, lineno, colno, endlineno, endcolno, pos, end)
+    fmt = '%s: line %d column %d - line %d column %d (char %d - %d)'
+    return fmt % (msg, lineno, colno, endlineno, endcolno, pos, end)
+
+
+_CONSTANTS = {
+    '-Infinity': NegInf,
+    'Infinity': PosInf,
+    'NaN': NaN,
+}
+
+STRINGCHUNK = re.compile(r'(.*?)(["\\\x00-\x1f])', FLAGS)
+BACKSLASH = {
+    '"': u'"', '\\': u'\\', '/': u'/',
+    'b': u'\b', 'f': u'\f', 'n': u'\n', 'r': u'\r', 't': u'\t',
+}
+
+DEFAULT_ENCODING = "utf-8"
+
+def py_scanstring(s, end, encoding=None, strict=True, _b=BACKSLASH, _m=STRINGCHUNK.match):
+    """Scan the string s for a JSON string. End is the index of the
+    character in s after the quote that started the JSON string.
+    Unescapes all valid JSON string escape sequences and raises ValueError
+    on attempt to decode an invalid string. If strict is False then literal
+    control characters are allowed in the string.
+    
+    Returns a tuple of the decoded string and the index of the character in s
+    after the end quote."""
+    if encoding is None:
+        encoding = DEFAULT_ENCODING
+    chunks = []
+    _append = chunks.append
+    begin = end - 1
+    while 1:
+        chunk = _m(s, end)
+        if chunk is None:
+            raise ValueError(
+                errmsg("Unterminated string starting at", s, begin))
+        end = chunk.end()
+        content, terminator = chunk.groups()
+        # Content is contains zero or more unescaped string characters
+        if content:
+            if not isinstance(content, unicode):
+                content = unicode(content, encoding)
+            _append(content)
+        # Terminator is the end of string, a literal control character,
+        # or a backslash denoting that an escape sequence follows
+        if terminator == '"':
+            break
+        elif terminator != '\\':
+            if strict:
+                msg = "Invalid control character %r at" % (terminator,)
+                #msg = "Invalid control character {0!r} at".format(terminator)
+                raise ValueError(errmsg(msg, s, end))
+            else:
+                _append(terminator)
+                continue
+        try:
+            esc = s[end]
+        except IndexError:
+            raise ValueError(
+                errmsg("Unterminated string starting at", s, begin))
+        # If not a unicode escape sequence, must be in the lookup table
+        if esc != 'u':
+            try:
+                char = _b[esc]
+            except KeyError:
+                msg = "Invalid \\escape: " + repr(esc)
+                raise ValueError(errmsg(msg, s, end))
+            end += 1
+        else:
+            # Unicode escape sequence
+            esc = s[end + 1:end + 5]
+            next_end = end + 5
+            if len(esc) != 4:
+                msg = "Invalid \\uXXXX escape"
+                raise ValueError(errmsg(msg, s, end))
+            uni = int(esc, 16)
+            # Check for surrogate pair on UCS-4 systems
+            if 0xd800 <= uni <= 0xdbff and sys.maxunicode > 65535:
+                msg = "Invalid \\uXXXX\\uXXXX surrogate pair"
+                if not s[end + 5:end + 7] == '\\u':
+                    raise ValueError(errmsg(msg, s, end))
+                esc2 = s[end + 7:end + 11]
+                if len(esc2) != 4:
+                    raise ValueError(errmsg(msg, s, end))
+                uni2 = int(esc2, 16)
+                uni = 0x10000 + (((uni - 0xd800) << 10) | (uni2 - 0xdc00))
+                next_end += 6
+            char = unichr(uni)
+            end = next_end
+        # Append the unescaped character
+        _append(char)
+    return u''.join(chunks), end
+
+
+# Use speedup if available
+scanstring = c_scanstring or py_scanstring
+
+WHITESPACE = re.compile(r'[ \t\n\r]*', FLAGS)
+WHITESPACE_STR = ' \t\n\r'
+
+def JSONObject((s, end), encoding, strict, scan_once, object_hook, _w=WHITESPACE.match, _ws=WHITESPACE_STR):
+    pairs = {}
+    # Use a slice to prevent IndexError from being raised, the following
+    # check will raise a more specific ValueError if the string is empty
+    nextchar = s[end:end + 1]
+    # Normally we expect nextchar == '"'
+    if nextchar != '"':
+        if nextchar in _ws:
+            end = _w(s, end).end()
+            nextchar = s[end:end + 1]
+        # Trivial empty object
+        if nextchar == '}':
+            return pairs, end + 1
+        elif nextchar != '"':
+            raise ValueError(errmsg("Expecting property name", s, end))
+    end += 1
+    while True:
+        key, end = scanstring(s, end, encoding, strict)
+
+        # To skip some function call overhead we optimize the fast paths where
+        # the JSON key separator is ": " or just ":".
+        if s[end:end + 1] != ':':
+            end = _w(s, end).end()
+            if s[end:end + 1] != ':':
+                raise ValueError(errmsg("Expecting : delimiter", s, end))
+
+        end += 1
+
+        try:
+            if s[end] in _ws:
+                end += 1
+                if s[end] in _ws:
+                    end = _w(s, end + 1).end()
+        except IndexError:
+            pass
+
+        try:
+            value, end = scan_once(s, end)
+        except StopIteration:
+            raise ValueError(errmsg("Expecting object", s, end))
+        pairs[key] = value
+
+        try:
+            nextchar = s[end]
+            if nextchar in _ws:
+                end = _w(s, end + 1).end()
+                nextchar = s[end]
+        except IndexError:
+            nextchar = ''
+        end += 1
+
+        if nextchar == '}':
+            break
+        elif nextchar != ',':
+            raise ValueError(errmsg("Expecting , delimiter", s, end - 1))
+
+        try:
+            nextchar = s[end]
+            if nextchar in _ws:
+                end += 1
+                nextchar = s[end]
+                if nextchar in _ws:
+                    end = _w(s, end + 1).end()
+                    nextchar = s[end]
+        except IndexError:
+            nextchar = ''
+
+        end += 1
+        if nextchar != '"':
+            raise ValueError(errmsg("Expecting property name", s, end - 1))
+
+    if object_hook is not None:
+        pairs = object_hook(pairs)
+    return pairs, end
+
+def JSONArray((s, end), scan_once, _w=WHITESPACE.match, _ws=WHITESPACE_STR):
+    values = []
+    nextchar = s[end:end + 1]
+    if nextchar in _ws:
+        end = _w(s, end + 1).end()
+        nextchar = s[end:end + 1]
+    # Look-ahead for trivial empty array
+    if nextchar == ']':
+        return values, end + 1
+    _append = values.append
+    while True:
+        try:
+            value, end = scan_once(s, end)
+        except StopIteration:
+            raise ValueError(errmsg("Expecting object", s, end))
+        _append(value)
+        nextchar = s[end:end + 1]
+        if nextchar in _ws:
+            end = _w(s, end + 1).end()
+            nextchar = s[end:end + 1]
+        end += 1
+        if nextchar == ']':
+            break
+        elif nextchar != ',':
+            raise ValueError(errmsg("Expecting , delimiter", s, end))
+
+        try:
+            if s[end] in _ws:
+                end += 1
+                if s[end] in _ws:
+                    end = _w(s, end + 1).end()
+        except IndexError:
+            pass
+
+    return values, end
+
+class JSONDecoder(object):
+    """Simple JSON <http://json.org> decoder
+
+    Performs the following translations in decoding by default:
+
+    +---------------+-------------------+
+    | JSON          | Python            |
+    +===============+===================+
+    | object        | dict              |
+    +---------------+-------------------+
+    | array         | list              |
+    +---------------+-------------------+
+    | string        | unicode           |
+    +---------------+-------------------+
+    | number (int)  | int, long         |
+    +---------------+-------------------+
+    | number (real) | float             |
+    +---------------+-------------------+
+    | true          | True              |
+    +---------------+-------------------+
+    | false         | False             |
+    +---------------+-------------------+
+    | null          | None              |
+    +---------------+-------------------+
+
+    It also understands ``NaN``, ``Infinity``, and ``-Infinity`` as
+    their corresponding ``float`` values, which is outside the JSON spec.
+
+    """
+
+    def __init__(self, encoding=None, object_hook=None, parse_float=None,
+            parse_int=None, parse_constant=None, strict=True):
+        """``encoding`` determines the encoding used to interpret any ``str``
+        objects decoded by this instance (utf-8 by default).  It has no
+        effect when decoding ``unicode`` objects.
+
+        Note that currently only encodings that are a superset of ASCII work,
+        strings of other encodings should be passed in as ``unicode``.
+
+        ``object_hook``, if specified, will be called with the result
+        of every JSON object decoded and its return value will be used in
+        place of the given ``dict``.  This can be used to provide custom
+        deserializations (e.g. to support JSON-RPC class hinting).
+
+        ``parse_float``, if specified, will be called with the string
+        of every JSON float to be decoded. By default this is equivalent to
+        float(num_str). This can be used to use another datatype or parser
+        for JSON floats (e.g. decimal.Decimal).
+
+        ``parse_int``, if specified, will be called with the string
+        of every JSON int to be decoded. By default this is equivalent to
+        int(num_str). This can be used to use another datatype or parser
+        for JSON integers (e.g. float).
+
+        ``parse_constant``, if specified, will be called with one of the
+        following strings: -Infinity, Infinity, NaN.
+        This can be used to raise an exception if invalid JSON numbers
+        are encountered.
+
+        """
+        self.encoding = encoding
+        self.object_hook = object_hook
+        self.parse_float = parse_float or float
+        self.parse_int = parse_int or int
+        self.parse_constant = parse_constant or _CONSTANTS.__getitem__
+        self.strict = strict
+        self.parse_object = JSONObject
+        self.parse_array = JSONArray
+        self.parse_string = scanstring
+        self.scan_once = make_scanner(self)
+
+    def decode(self, s, _w=WHITESPACE.match):
+        """Return the Python representation of ``s`` (a ``str`` or ``unicode``
+        instance containing a JSON document)
+
+        """
+        obj, end = self.raw_decode(s, idx=_w(s, 0).end())
+        end = _w(s, end).end()
+        if end != len(s):
+            raise ValueError(errmsg("Extra data", s, end, len(s)))
+        return obj
+
+    def raw_decode(self, s, idx=0):
+        """Decode a JSON document from ``s`` (a ``str`` or ``unicode`` beginning
+        with a JSON document) and return a 2-tuple of the Python
+        representation and the index in ``s`` where the document ended.
+
+        This can be used to decode a JSON document from a string that may
+        have extraneous data at the end.
+
+        """
+        try:
+            obj, end = self.scan_once(s, idx)
+        except StopIteration:
+            raise ValueError("No JSON object could be decoded")
+        return obj, end
diff --git a/test/simplejson/encoder.py b/test/simplejson/encoder.py
new file mode 100644
index 0000000..cf58290
--- /dev/null
+++ b/test/simplejson/encoder.py
@@ -0,0 +1,440 @@
+"""Implementation of JSONEncoder
+"""
+import re
+
+try:
+    from simplejson._speedups import encode_basestring_ascii as c_encode_basestring_ascii
+except ImportError:
+    c_encode_basestring_ascii = None
+try:
+    from simplejson._speedups import make_encoder as c_make_encoder
+except ImportError:
+    c_make_encoder = None
+
+ESCAPE = re.compile(r'[\x00-\x1f\\"\b\f\n\r\t]')
+ESCAPE_ASCII = re.compile(r'([\\"]|[^\ -~])')
+HAS_UTF8 = re.compile(r'[\x80-\xff]')
+ESCAPE_DCT = {
+    '\\': '\\\\',
+    '"': '\\"',
+    '\b': '\\b',
+    '\f': '\\f',
+    '\n': '\\n',
+    '\r': '\\r',
+    '\t': '\\t',
+}
+for i in range(0x20):
+    #ESCAPE_DCT.setdefault(chr(i), '\\u{0:04x}'.format(i))
+    ESCAPE_DCT.setdefault(chr(i), '\\u%04x' % (i,))
+
+# Assume this produces an infinity on all machines (probably not guaranteed)
+INFINITY = float('1e66666')
+FLOAT_REPR = repr
+
+def encode_basestring(s):
+    """Return a JSON representation of a Python string
+
+    """
+    def replace(match):
+        return ESCAPE_DCT[match.group(0)]
+    return '"' + ESCAPE.sub(replace, s) + '"'
+
+
+def py_encode_basestring_ascii(s):
+    """Return an ASCII-only JSON representation of a Python string
+
+    """
+    if isinstance(s, str) and HAS_UTF8.search(s) is not None:
+        s = s.decode('utf-8')
+    def replace(match):
+        s = match.group(0)
+        try:
+            return ESCAPE_DCT[s]
+        except KeyError:
+            n = ord(s)
+            if n < 0x10000:
+                #return '\\u{0:04x}'.format(n)
+                return '\\u%04x' % (n,)
+            else:
+                # surrogate pair
+                n -= 0x10000
+                s1 = 0xd800 | ((n >> 10) & 0x3ff)
+                s2 = 0xdc00 | (n & 0x3ff)
+                #return '\\u{0:04x}\\u{1:04x}'.format(s1, s2)
+                return '\\u%04x\\u%04x' % (s1, s2)
+    return '"' + str(ESCAPE_ASCII.sub(replace, s)) + '"'
+
+
+encode_basestring_ascii = c_encode_basestring_ascii or py_encode_basestring_ascii
+
+class JSONEncoder(object):
+    """Extensible JSON <http://json.org> encoder for Python data structures.
+
+    Supports the following objects and types by default:
+
+    +-------------------+---------------+
+    | Python            | JSON          |
+    +===================+===============+
+    | dict              | object        |
+    +-------------------+---------------+
+    | list, tuple       | array         |
+    +-------------------+---------------+
+    | str, unicode      | string        |
+    +-------------------+---------------+
+    | int, long, float  | number        |
+    +-------------------+---------------+
+    | True              | true          |
+    +-------------------+---------------+
+    | False             | false         |
+    +-------------------+---------------+
+    | None              | null          |
+    +-------------------+---------------+
+
+    To extend this to recognize other objects, subclass and implement a
+    ``.default()`` method with another method that returns a serializable
+    object for ``o`` if possible, otherwise it should call the superclass
+    implementation (to raise ``TypeError``).
+
+    """
+    item_separator = ', '
+    key_separator = ': '
+    def __init__(self, skipkeys=False, ensure_ascii=True,
+            check_circular=True, allow_nan=True, sort_keys=False,
+            indent=None, separators=None, encoding='utf-8', default=None):
+        """Constructor for JSONEncoder, with sensible defaults.
+
+        If skipkeys is false, then it is a TypeError to attempt
+        encoding of keys that are not str, int, long, float or None.  If
+        skipkeys is True, such items are simply skipped.
+
+        If ensure_ascii is true, the output is guaranteed to be str
+        objects with all incoming unicode characters escaped.  If
+        ensure_ascii is false, the output will be unicode object.
+
+        If check_circular is true, then lists, dicts, and custom encoded
+        objects will be checked for circular references during encoding to
+        prevent an infinite recursion (which would cause an OverflowError).
+        Otherwise, no such check takes place.
+
+        If allow_nan is true, then NaN, Infinity, and -Infinity will be
+        encoded as such.  This behavior is not JSON specification compliant,
+        but is consistent with most JavaScript based encoders and decoders.
+        Otherwise, it will be a ValueError to encode such floats.
+
+        If sort_keys is true, then the output of dictionaries will be
+        sorted by key; this is useful for regression tests to ensure
+        that JSON serializations can be compared on a day-to-day basis.
+
+        If indent is a non-negative integer, then JSON array
+        elements and object members will be pretty-printed with that
+        indent level.  An indent level of 0 will only insert newlines.
+        None is the most compact representation.
+
+        If specified, separators should be a (item_separator, key_separator)
+        tuple.  The default is (', ', ': ').  To get the most compact JSON
+        representation you should specify (',', ':') to eliminate whitespace.
+
+        If specified, default is a function that gets called for objects
+        that can't otherwise be serialized.  It should return a JSON encodable
+        version of the object or raise a ``TypeError``.
+
+        If encoding is not None, then all input strings will be
+        transformed into unicode using that encoding prior to JSON-encoding.
+        The default is UTF-8.
+
+        """
+
+        self.skipkeys = skipkeys
+        self.ensure_ascii = ensure_ascii
+        self.check_circular = check_circular
+        self.allow_nan = allow_nan
+        self.sort_keys = sort_keys
+        self.indent = indent
+        if separators is not None:
+            self.item_separator, self.key_separator = separators
+        if default is not None:
+            self.default = default
+        self.encoding = encoding
+
+    def default(self, o):
+        """Implement this method in a subclass such that it returns
+        a serializable object for ``o``, or calls the base implementation
+        (to raise a ``TypeError``).
+
+        For example, to support arbitrary iterators, you could
+        implement default like this::
+
+            def default(self, o):
+                try:
+                    iterable = iter(o)
+                except TypeError:
+                    pass
+                else:
+                    return list(iterable)
+                return JSONEncoder.default(self, o)
+
+        """
+        raise TypeError(repr(o) + " is not JSON serializable")
+
+    def encode(self, o):
+        """Return a JSON string representation of a Python data structure.
+
+        >>> JSONEncoder().encode({"foo": ["bar", "baz"]})
+        '{"foo": ["bar", "baz"]}'
+
+        """
+        # This is for extremely simple cases and benchmarks.
+        if isinstance(o, basestring):
+            if isinstance(o, str):
+                _encoding = self.encoding
+                if (_encoding is not None
+                        and not (_encoding == 'utf-8')):
+                    o = o.decode(_encoding)
+            if self.ensure_ascii:
+                return encode_basestring_ascii(o)
+            else:
+                return encode_basestring(o)
+        # This doesn't pass the iterator directly to ''.join() because the
+        # exceptions aren't as detailed.  The list call should be roughly
+        # equivalent to the PySequence_Fast that ''.join() would do.
+        chunks = self.iterencode(o, _one_shot=True)
+        if not isinstance(chunks, (list, tuple)):
+            chunks = list(chunks)
+        return ''.join(chunks)
+
+    def iterencode(self, o, _one_shot=False):
+        """Encode the given object and yield each string
+        representation as available.
+
+        For example::
+
+            for chunk in JSONEncoder().iterencode(bigobject):
+                mysocket.write(chunk)
+
+        """
+        if self.check_circular:
+            markers = {}
+        else:
+            markers = None
+        if self.ensure_ascii:
+            _encoder = encode_basestring_ascii
+        else:
+            _encoder = encode_basestring
+        if self.encoding != 'utf-8':
+            def _encoder(o, _orig_encoder=_encoder, _encoding=self.encoding):
+                if isinstance(o, str):
+                    o = o.decode(_encoding)
+                return _orig_encoder(o)
+
+        def floatstr(o, allow_nan=self.allow_nan, _repr=FLOAT_REPR, _inf=INFINITY, _neginf=-INFINITY):
+            # Check for specials.  Note that this type of test is processor- and/or
+            # platform-specific, so do tests which don't depend on the internals.
+
+            if o != o:
+                text = 'NaN'
+            elif o == _inf:
+                text = 'Infinity'
+            elif o == _neginf:
+                text = '-Infinity'
+            else:
+                return _repr(o)
+
+            if not allow_nan:
+                raise ValueError(
+                    "Out of range float values are not JSON compliant: " +
+                    repr(o))
+
+            return text
+
+
+        if _one_shot and c_make_encoder is not None and not self.indent and not self.sort_keys:
+            _iterencode = c_make_encoder(
+                markers, self.default, _encoder, self.indent,
+                self.key_separator, self.item_separator, self.sort_keys,
+                self.skipkeys, self.allow_nan)
+        else:
+            _iterencode = _make_iterencode(
+                markers, self.default, _encoder, self.indent, floatstr,
+                self.key_separator, self.item_separator, self.sort_keys,
+                self.skipkeys, _one_shot)
+        return _iterencode(o, 0)
+
+def _make_iterencode(markers, _default, _encoder, _indent, _floatstr, _key_separator, _item_separator, _sort_keys, _skipkeys, _one_shot,
+        ## HACK: hand-optimized bytecode; turn globals into locals
+        False=False,
+        True=True,
+        ValueError=ValueError,
+        basestring=basestring,
+        dict=dict,
+        float=float,
+        id=id,
+        int=int,
+        isinstance=isinstance,
+        list=list,
+        long=long,
+        str=str,
+        tuple=tuple,
+    ):
+
+    def _iterencode_list(lst, _current_indent_level):
+        if not lst:
+            yield '[]'
+            return
+        if markers is not None:
+            markerid = id(lst)
+            if markerid in markers:
+                raise ValueError("Circular reference detected")
+            markers[markerid] = lst
+        buf = '['
+        if _indent is not None:
+            _current_indent_level += 1
+            newline_indent = '\n' + (' ' * (_indent * _current_indent_level))
+            separator = _item_separator + newline_indent
+            buf += newline_indent
+        else:
+            newline_indent = None
+            separator = _item_separator
+        first = True
+        for value in lst:
+            if first:
+                first = False
+            else:
+                buf = separator
+            if isinstance(value, basestring):
+                yield buf + _encoder(value)
+            elif value is None:
+                yield buf + 'null'
+            elif value is True:
+                yield buf + 'true'
+            elif value is False:
+                yield buf + 'false'
+            elif isinstance(value, (int, long)):
+                yield buf + str(value)
+            elif isinstance(value, float):
+                yield buf + _floatstr(value)
+            else:
+                yield buf
+                if isinstance(value, (list, tuple)):
+                    chunks = _iterencode_list(value, _current_indent_level)
+                elif isinstance(value, dict):
+                    chunks = _iterencode_dict(value, _current_indent_level)
+                else:
+                    chunks = _iterencode(value, _current_indent_level)
+                for chunk in chunks:
+                    yield chunk
+        if newline_indent is not None:
+            _current_indent_level -= 1
+            yield '\n' + (' ' * (_indent * _current_indent_level))
+        yield ']'
+        if markers is not None:
+            del markers[markerid]
+
+    def _iterencode_dict(dct, _current_indent_level):
+        if not dct:
+            yield '{}'
+            return
+        if markers is not None:
+            markerid = id(dct)
+            if markerid in markers:
+                raise ValueError("Circular reference detected")
+            markers[markerid] = dct
+        yield '{'
+        if _indent is not None:
+            _current_indent_level += 1
+            newline_indent = '\n' + (' ' * (_indent * _current_indent_level))
+            item_separator = _item_separator + newline_indent
+            yield newline_indent
+        else:
+            newline_indent = None
+            item_separator = _item_separator
+        first = True
+        if _sort_keys:
+            items = dct.items()
+            items.sort(key=lambda kv: kv[0])
+        else:
+            items = dct.iteritems()
+        for key, value in items:
+            if isinstance(key, basestring):
+                pass
+            # JavaScript is weakly typed for these, so it makes sense to
+            # also allow them.  Many encoders seem to do something like this.
+            elif isinstance(key, float):
+                key = _floatstr(key)
+            elif key is True:
+                key = 'true'
+            elif key is False:
+                key = 'false'
+            elif key is None:
+                key = 'null'
+            elif isinstance(key, (int, long)):
+                key = str(key)
+            elif _skipkeys:
+                continue
+            else:
+                raise TypeError("key " + repr(key) + " is not a string")
+            if first:
+                first = False
+            else:
+                yield item_separator
+            yield _encoder(key)
+            yield _key_separator
+            if isinstance(value, basestring):
+                yield _encoder(value)
+            elif value is None:
+                yield 'null'
+            elif value is True:
+                yield 'true'
+            elif value is False:
+                yield 'false'
+            elif isinstance(value, (int, long)):
+                yield str(value)
+            elif isinstance(value, float):
+                yield _floatstr(value)
+            else:
+                if isinstance(value, (list, tuple)):
+                    chunks = _iterencode_list(value, _current_indent_level)
+                elif isinstance(value, dict):
+                    chunks = _iterencode_dict(value, _current_indent_level)
+                else:
+                    chunks = _iterencode(value, _current_indent_level)
+                for chunk in chunks:
+                    yield chunk
+        if newline_indent is not None:
+            _current_indent_level -= 1
+            yield '\n' + (' ' * (_indent * _current_indent_level))
+        yield '}'
+        if markers is not None:
+            del markers[markerid]
+
+    def _iterencode(o, _current_indent_level):
+        if isinstance(o, basestring):
+            yield _encoder(o)
+        elif o is None:
+            yield 'null'
+        elif o is True:
+            yield 'true'
+        elif o is False:
+            yield 'false'
+        elif isinstance(o, (int, long)):
+            yield str(o)
+        elif isinstance(o, float):
+            yield _floatstr(o)
+        elif isinstance(o, (list, tuple)):
+            for chunk in _iterencode_list(o, _current_indent_level):
+                yield chunk
+        elif isinstance(o, dict):
+            for chunk in _iterencode_dict(o, _current_indent_level):
+                yield chunk
+        else:
+            if markers is not None:
+                markerid = id(o)
+                if markerid in markers:
+                    raise ValueError("Circular reference detected")
+                markers[markerid] = o
+            o = _default(o)
+            for chunk in _iterencode(o, _current_indent_level):
+                yield chunk
+            if markers is not None:
+                del markers[markerid]
+
+    return _iterencode
diff --git a/test/simplejson/scanner.py b/test/simplejson/scanner.py
new file mode 100644
index 0000000..adbc6ec
--- /dev/null
+++ b/test/simplejson/scanner.py
@@ -0,0 +1,65 @@
+"""JSON token scanner
+"""
+import re
+try:
+    from simplejson._speedups import make_scanner as c_make_scanner
+except ImportError:
+    c_make_scanner = None
+
+__all__ = ['make_scanner']
+
+NUMBER_RE = re.compile(
+    r'(-?(?:0|[1-9]\d*))(\.\d+)?([eE][-+]?\d+)?',
+    (re.VERBOSE | re.MULTILINE | re.DOTALL))
+
+def py_make_scanner(context):
+    parse_object = context.parse_object
+    parse_array = context.parse_array
+    parse_string = context.parse_string
+    match_number = NUMBER_RE.match
+    encoding = context.encoding
+    strict = context.strict
+    parse_float = context.parse_float
+    parse_int = context.parse_int
+    parse_constant = context.parse_constant
+    object_hook = context.object_hook
+
+    def _scan_once(string, idx):
+        try:
+            nextchar = string[idx]
+        except IndexError:
+            raise StopIteration
+
+        if nextchar == '"':
+            return parse_string(string, idx + 1, encoding, strict)
+        elif nextchar == '{':
+            return parse_object((string, idx + 1), encoding, strict, _scan_once, object_hook)
+        elif nextchar == '[':
+            return parse_array((string, idx + 1), _scan_once)
+        elif nextchar == 'n' and string[idx:idx + 4] == 'null':
+            return None, idx + 4
+        elif nextchar == 't' and string[idx:idx + 4] == 'true':
+            return True, idx + 4
+        elif nextchar == 'f' and string[idx:idx + 5] == 'false':
+            return False, idx + 5
+
+        m = match_number(string, idx)
+        if m is not None:
+            integer, frac, exp = m.groups()
+            if frac or exp:
+                res = parse_float(integer + (frac or '') + (exp or ''))
+            else:
+                res = parse_int(integer)
+            return res, m.end()
+        elif nextchar == 'N' and string[idx:idx + 3] == 'NaN':
+            return parse_constant('NaN'), idx + 3
+        elif nextchar == 'I' and string[idx:idx + 8] == 'Infinity':
+            return parse_constant('Infinity'), idx + 8
+        elif nextchar == '-' and string[idx:idx + 9] == '-Infinity':
+            return parse_constant('-Infinity'), idx + 9
+        else:
+            raise StopIteration
+
+    return _scan_once
+
+make_scanner = c_make_scanner or py_make_scanner
diff --git a/test/simplejson/tool.py b/test/simplejson/tool.py
new file mode 100644
index 0000000..9044331
--- /dev/null
+++ b/test/simplejson/tool.py
@@ -0,0 +1,37 @@
+r"""Command-line tool to validate and pretty-print JSON
+
+Usage::
+
+    $ echo '{"json":"obj"}' | python -m simplejson.tool
+    {
+        "json": "obj"
+    }
+    $ echo '{ 1.2:3.4}' | python -m simplejson.tool
+    Expecting property name: line 1 column 2 (char 2)
+
+"""
+import sys
+import simplejson
+
+def main():
+    if len(sys.argv) == 1:
+        infile = sys.stdin
+        outfile = sys.stdout
+    elif len(sys.argv) == 2:
+        infile = open(sys.argv[1], 'rb')
+        outfile = sys.stdout
+    elif len(sys.argv) == 3:
+        infile = open(sys.argv[1], 'rb')
+        outfile = open(sys.argv[2], 'wb')
+    else:
+        raise SystemExit(sys.argv[0] + " [infile [outfile]]")
+    try:
+        obj = simplejson.load(infile)
+    except ValueError, e:
+        raise SystemExit(e)
+    simplejson.dump(obj, outfile, sort_keys=True, indent=4)
+    outfile.write('\n')
+
+
+if __name__ == '__main__':
+    main()
diff --git a/test/files/jvm5/NestedAnnotations.java b/test/support/annotations/NestedAnnotations.java
similarity index 100%
rename from test/files/jvm5/NestedAnnotations.java
rename to test/support/annotations/NestedAnnotations.java
diff --git a/test/files/jvm5/OuterEnum.java b/test/support/annotations/OuterEnum.java
similarity index 100%
rename from test/files/jvm5/OuterEnum.java
rename to test/support/annotations/OuterEnum.java
diff --git a/test/files/jvm5/OuterTParams.java b/test/support/annotations/OuterTParams.java
similarity index 100%
rename from test/files/jvm5/OuterTParams.java
rename to test/support/annotations/OuterTParams.java
diff --git a/test/files/jvm5/SourceAnnotation.java b/test/support/annotations/SourceAnnotation.java
similarity index 100%
rename from test/files/jvm5/SourceAnnotation.java
rename to test/support/annotations/SourceAnnotation.java
diff --git a/test/support/annotations/mkAnnotationsJar.sh b/test/support/annotations/mkAnnotationsJar.sh
new file mode 100644
index 0000000..3d69351
--- /dev/null
+++ b/test/support/annotations/mkAnnotationsJar.sh
@@ -0,0 +1,28 @@
+#!/bin/sh
+
+##############################################################################
+# Author  : Nikolay Mihaylov
+##############################################################################
+
+##############################################################################
+# variables
+
+OBJDIR=./classes
+
+if [ -z "${JAVA_HOME}" ]; then
+  echo "environment variable JAVA_HOME is undefined."
+  exit
+fi
+
+JAVAC=${JAVA_HOME}/bin/javac
+JAVAC_OPTIONS="-source 1.5 -target 1.5"
+
+JAR=${JAVA_HOME}/bin/jar
+
+##############################################################################
+# commands
+
+mkdir -p ${OBJDIR}
+${JAVAC} ${JAVAC_OPTIONS} -d ${OBJDIR} SourceAnnotation.java NestedAnnotations.java
+${JAR} cf ../lib/annotations.jar -C ${OBJDIR} .
+rm -rf ${OBJDIR}
diff --git a/tools/abspath b/tools/abspath
new file mode 100644
index 0000000..a2d1410
--- /dev/null
+++ b/tools/abspath
@@ -0,0 +1,9 @@
+#!/bin/sh
+#
+# print the absolute path of each argument
+
+for relpath in $* ; do
+  D=`dirname "$relpath"`
+  B=`basename "$relpath"`  
+  echo "`cd \"$D\" 2>/dev/null && pwd || echo \"$D\"`/$B"
+done
\ No newline at end of file
diff --git a/tools/cpof b/tools/cpof
new file mode 100644
index 0000000..ab5a42b
--- /dev/null
+++ b/tools/cpof
@@ -0,0 +1,30 @@
+#!/bin/sh
+#
+# Creates a classpath out of the contents of each directory
+# given as an argument.
+
+if [ $# == 0 ] ; then
+  echo "Usage: $0 [dir1 dir2 ...]"
+  exit 1
+fi
+
+THISDIR=`dirname $0`
+ABSCMD="${THISDIR}/abspath"
+CPRES=""
+
+for dir in $* ; do
+  absdir=`${ABSCMD} $dir`
+  LS=`ls -1 ${absdir}`
+
+  for x in $LS ; do
+    ABS=`${ABSCMD} "${absdir}/${x}"`
+    CPRES="${CPRES}:${ABS}"
+  done
+done
+
+# shaving the : off the beginning.  Applause to /bin/sh for
+# keeping us humble about how far we've come.
+LEN=$(( ${#CPRES} - 1 ))
+result=${CPRES:1:${LEN}}
+
+echo $result
diff --git a/tools/diffPickled b/tools/diffPickled
new file mode 100644
index 0000000..b4a345d
--- /dev/null
+++ b/tools/diffPickled
@@ -0,0 +1,51 @@
+#!/bin/sh
+#
+# Shows the difference in pickler output between two variations on a class.
+#
+# If quick and strap are built normally you can run
+#
+#   diffPickled foo.bar.Baz
+#
+# to see any differences between them in that class.
+
+USAGE="Usage: $0 classpath1 classpath2 class"
+TOOLSDIR=`dirname $0`
+BUILDDIR="${TOOLSDIR}/../build"
+QUICKDIR="${BUILDDIR}/quick"
+STRAPDIR="${BUILDDIR}/strap"
+
+CP1=""
+CP2=""
+CLASS=""
+
+if [ $# == 1 ] ; then
+  if [ -e ${QUICKDIR} ] && [ -e ${STRAPDIR} ] ; then
+    CP1=`${TOOLSDIR}/quickcp`
+    CP2=`${TOOLSDIR}/strapcp`
+    CLASS=$1
+  else
+    echo $USAGE
+    echo "(If only one argument is given, $QUICKDIR and $STRAPDIR must exist.)"
+    exit 1
+  fi
+elif [ $# == 3 ] ; then
+  CP1=$1
+  CP2=$2
+  CLASS=$3
+else
+  echo $USAGE
+  exit 1
+fi
+
+TMPDIR="/tmp/scala_pickle_diff${RANDOM}"
+
+if mkdir -m 0700 "$TMPDIR" 2>/dev/null ; then
+  ${TOOLSDIR}/showPickled -cp $CP1 $CLASS > "${TMPDIR}/out1.txt"
+  ${TOOLSDIR}/showPickled -cp $CP2 $CLASS > "${TMPDIR}/out2.txt"
+  diff "${TMPDIR}/out1.txt" "${TMPDIR}/out2.txt"
+  rm -rf ${TMPDIR}
+else
+  echo "Failed to create temporary directory ${TMPDIR}."
+  exit 1
+fi
+
diff --git a/tools/git-get-rev b/tools/git-get-rev
new file mode 100644
index 0000000..9adda35
--- /dev/null
+++ b/tools/git-get-rev
@@ -0,0 +1,5 @@
+#!/bin/sh
+#
+
+GIT_PAGER=cat
+git log -10 | grep git-svn-id | head -1
\ No newline at end of file
diff --git a/tools/packcp b/tools/packcp
new file mode 100644
index 0000000..42bce9e
--- /dev/null
+++ b/tools/packcp
@@ -0,0 +1,5 @@
+#!/bin/sh
+#
+
+THISDIR=`dirname $0`
+${THISDIR}/cpof ${THISDIR}/../build/pack/lib
diff --git a/tools/pathResolver b/tools/pathResolver
new file mode 100644
index 0000000..efff45e
--- /dev/null
+++ b/tools/pathResolver
@@ -0,0 +1,11 @@
+#!/bin/sh
+#
+
+WHICH=`which scala`
+BASE=`dirname $WHICH`
+LIBDIR=$BASE/../lib
+
+echo Using ${WHICH}.
+echo
+
+java -cp "${LIBDIR}/*" scala.tools.util.PathResolver $*
diff --git a/tools/quickcp b/tools/quickcp
new file mode 100644
index 0000000..0bfcad1
--- /dev/null
+++ b/tools/quickcp
@@ -0,0 +1,8 @@
+#!/bin/sh
+#
+
+THISDIR=`dirname $0`
+cp=`${THISDIR}/cpof ${THISDIR}/../build/quick/classes`
+fjbg=`${THISDIR}/abspath ${THISDIR}/../lib/fjbg.jar`
+
+echo ${cp}:${fjbg}
diff --git a/tools/scalawhich b/tools/scalawhich
new file mode 100644
index 0000000..6a4b178
--- /dev/null
+++ b/tools/scalawhich
@@ -0,0 +1,4 @@
+#!/bin/sh
+#
+
+scala scala.tools.util.Which $*
diff --git a/tools/scmp b/tools/scmp
new file mode 100644
index 0000000..f6acea5
--- /dev/null
+++ b/tools/scmp
@@ -0,0 +1,4 @@
+#!/bin/sh
+#
+
+scala scala.tools.cmd.program.Scmp "$@"
diff --git a/tools/showPickled b/tools/showPickled
new file mode 100644
index 0000000..27421c3
--- /dev/null
+++ b/tools/showPickled
@@ -0,0 +1,32 @@
+#!/bin/sh
+#
+# Shows the pickled scala data in a classfile.
+
+if [ $# == 0 ] ; then
+  echo "Usage: $0 [--bare] [-cp classpath] <class*>"
+  exit 1
+fi
+
+TOOLSDIR=`dirname $0`
+CPOF="$TOOLSDIR/cpof"
+
+PACK="$TOOLSDIR/../build/pack/lib"
+QUICK="$TOOLSDIR/../build/quick/classes"
+STARR="$TOOLSDIR/../lib"
+CP=""
+
+if [ -f "${PACK}/scala-library.jar" ] ; then
+  CP=`${TOOLSDIR}/packcp`
+elif [ -d "${QUICK}/library" ] ; then
+  CP=`${TOOLSDIR}/quickcp`
+else
+  CP=`${TOOLSDIR}/starrcp`
+fi
+
+if [ "$1" == "-cp" ] ; then
+  shift
+  CP="${1}:${CP}"
+  shift
+fi
+
+java -cp "$CP" scala.tools.nsc.util.ShowPickled $*
diff --git a/tools/starrcp b/tools/starrcp
new file mode 100644
index 0000000..6add566
--- /dev/null
+++ b/tools/starrcp
@@ -0,0 +1,5 @@
+#!/bin/sh
+#
+
+THISDIR=`dirname $0`
+${THISDIR}/cpof ${THISDIR}/../lib
\ No newline at end of file
diff --git a/tools/strapcp b/tools/strapcp
new file mode 100644
index 0000000..61e4a61
--- /dev/null
+++ b/tools/strapcp
@@ -0,0 +1,8 @@
+#!/bin/sh
+#
+
+THISDIR=`dirname $0`
+cp=`${THISDIR}/cpof ${THISDIR}/../build/strap/classes`
+fjbg=`${THISDIR}/abspath ${THISDIR}/../lib/fjbg.jar`
+
+echo ${cp}:${fjbg}
diff --git a/tools/tokens b/tools/tokens
new file mode 100644
index 0000000..b910fb2
--- /dev/null
+++ b/tools/tokens
@@ -0,0 +1,4 @@
+#!/bin/sh
+#
+
+scala scala.tools.cmd.program.Tokens "$@"
diff --git a/tools/truncate b/tools/truncate
new file mode 100644
index 0000000..b7f410e
--- /dev/null
+++ b/tools/truncate
@@ -0,0 +1,7 @@
+#!/bin/bash
+
+find . -type f -not -path "*.svn*" -name "*.scala" -exec sed -i "" -e 's/$ *Id.*$/$Id$/g' {} \;
+find . -type f -not -path "*.svn*" -name "*.java" -exec sed -i "" -e 's/$ *Id.*$/$Id$/g' {} \;
+find . -type f -not -path "*.svn*" -name "*.cs" -exec sed -i "" -e 's/$ *Id.*$/$Id$/g' {} \;
+find . -type f -not -path "*.svn*" -name "*.js" -exec sed -i "" -e 's/$ *Id.*$/$Id$/g' {} \;
+find . -type f -not -path "*.svn*" -name "*.scala.disabled" -exec sed -i "" -e 's/$ *Id.*$/$Id$/g' {} \;

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/pkg-java/scala-2.10.git



More information about the pkg-java-commits mailing list